Compare commits

...
Author SHA1 Message Date
Adeeb Rahman 482ec7b432 Merge origin/main into feat/system-runtime-expansion
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 21:21:30 -05:00
Adeeb Rahman a188ac5646 Add CRT floating-point string conversion
strtod, strtof, wcstod, wcstof, atof and _wtof parse the C-locale
grammar (decimal, inf, nan) and return in XMM0, rounding once straight
to the result type. Overflow and underflow to zero set ERANGE.
Hexadecimal floating constants stop the guest rather than parse as 0.
The metadata mapped strtod, strtof and wcstod to the host libc.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 21:15:53 -05:00
Adeeb Rahman dc86483001 Add CRT ungetc and fgets
ungetc keeps one pushed-back byte beside the stream data, so reads see
it but it never reaches the file; seeks, rewind and writes discard it.
fgets reads up to count - 1 bytes and stops after a newline. The import
metadata classified ungetc as a native libc call although it takes a
guest FILE cookie.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 21:06:27 -05:00
Adeeb Rahman b4a4ca8a56 Add LLP64 CRT integer abs and div
abs, labs, llabs, div, ldiv and lldiv run as runtime services with
Windows' 32-bit long and the Win64 struct returns (lldiv_t through a
hidden pointer). Division by zero raises a divide error. The metadata
mapped labs and ldiv to the LP64 host libc; they are now runtime
services. The generated abs adapter wraps instead of panicking on the
minimum integer, and SymbolDb::insert lets the pipeline test keep
covering the adapter path.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 21:01:59 -05:00
Adeeb Rahman d15315e79e End the guest on abort, terminate, _purecall and _exit
abort, terminate and _purecall (ucrtbase and the CRT runtime API set)
and __std_terminate and _purecall (vcruntime140) end the guest process
with exit code 3 through the process exit from #331; _exit uses its
status. No handlers can be installed yet. The import metadata described
abort and _exit as identical-ABI native libc calls and ExitProcess as a
stub; all are now runtime services.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 20:52:20 -05:00
Adeeb Rahman 30580fea19 Merge origin/main into feat/system-runtime-expansion
Keeps both QueueHandles methods (has_handle from this branch, open_count
and close_all from #331). SyntheticFile now carries timestamps on this
branch, so the process-exit file_contents helper reads it through a new
data() accessor.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 20:34:19 -05:00
Adeeb Rahman b111c8f5de Merge origin/main into feat/system-runtime-expansion
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 20:21:37 -05:00
Adeeb Rahman 152ed1c2eb Record the review checkpoint after fixing #312 merge conflicts
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 20:16:23 -05:00
Adeeb Rahman 5c6fcb28af Merge origin/main into feat/system-runtime-expansion
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 20:13:55 -05:00
Adeeb Rahman 093ef7ba66 Fault the guest instead of the host on oversized strncpy and XInput pointers
strncpy and wcsncpy allocated the whole guest-supplied count for the
zero padding, so an all-ones count aborted the host. The padding is now
written in bounded chunks and faults at the first unwritable byte.
XInputSetState computed the second motor's address before checking the
first read, which overflowed for a pointer at the top of the address
space; the vibration struct is now read as one DWORD. Both were found
by the runtime_services fuzz replay after merging main.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 20:13:40 -05:00
Adeeb Rahman c4428d13a0 Merge origin/main into feat/system-runtime-expansion
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 20:05:53 -05:00
Adeeb Rahman 6eb35222d8 Add CRT character and line stdio and fflush
fputc, putc, fputs, puts, fgetc, getc and fflush now run as runtime
services on the shared fopen stream state. fflush writes host-backed
streams to their mount before fclose. The import metadata classified
these as native libc calls although they take guest FILE cookies.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 20:05:34 -05:00
Adeeb Rahman 0aa93d7039 Catalog the guest thread services in the import metadata
CreateThread, ExitThread, SuspendThread and ResumeThread were still
classified as stubs after the scheduler landed, and three more thread
services were uncatalogued. The pipeline test's stub sample now uses the
l1-1-2 API set, which is still a stub, so its counts are unchanged.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 19:56:57 -05:00
Adeeb Rahman d75ce94da6 Merge remote-tracking branch 'origin/main' into feat/system-runtime-expansion 2026-11-24 19:52:50 -05:00
Adeeb Rahman 5ea41817aa Add bounds-checked CRT string copy and append
strcpy_s, strcat_s, strncpy_s, strncat_s and their wcs forms follow the
documented EINVAL, ERANGE and _TRUNCATE rules. The import metadata had
mapped six of them to unchecked libc functions that ignore the buffer
size; they are now runtime services, and the pipeline test asserts so.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 19:52:42 -05:00
Adeeb Rahman 4befaaa4b5 Record parked timer work and claimed files in the runtime handoff
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 19:46:58 -05:00
Adeeb Rahman 4fd1432599 Add GetTimeZoneInformation and GetLogicalProcessorInformation
The guest time zone is UTC with no daylight transition. Processor
topology reports one core per profile processor and one package; no
simulated cache entries are reported.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 19:41:53 -05:00
Adeeb Rahman 7cb2da51f0 Add IsProcessorFeaturePresent from the guest CPUID table
Each PF_* feature is present only when guest CPUID reports every bit it
depends on, so startup code cannot pick instruction sets the translator
does not advertise. Features without a CPUID test report FALSE.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 19:38:21 -05:00
Adeeb Rahman 2e8d7faa32 Add UCRT _msize, _recalloc and aligned allocation
_msize, _recalloc, _aligned_malloc, _aligned_realloc, _aligned_msize
and _aligned_free on the CRT heap. Aligned blocks are tracked so double
and mismatched frees stop the guest.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 19:32:23 -05:00
Adeeb Rahman 112853ff88 Add std::exception message copy and destroy helpers
__std_exception_copy duplicates an owned message on the CRT heap and
shares a borrowed one; __std_exception_destroy frees an owned message
and clears the record.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 19:27:26 -05:00
Adeeb Rahman 6cf0325564 Catalog registered runtime services in the import metadata
Classify the 84 kernel32, UCRT, Winsock, XGameRuntime and XInput
services the registry provided without a metadata entry. Only the
synthetic fixture modules remain uncatalogued.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 19:23:54 -05:00
Adeeb Rahman cdb43d03b0 Add an API coverage report and fix stale stub metadata
xenora imports coverage lists every standard runtime service by module
and status and where the import metadata disagrees with the registry.
It found six kernel32 services the metadata still classified as stubs.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 19:21:43 -05:00
Adeeb Rahman 9f472c9115 Add C++ type_info helpers to vcruntime140
__std_type_info_compare, __std_type_info_hash, __std_type_info_name and
__std_type_info_destroy_list compare and hash by decorated name and
undecorate plain class, struct, union and enum names. Decorations they
do not model stop the guest instead of returning a wrong name.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 19:19:23 -05:00
Adeeb Rahman 626de36f39 Add XInput controller services with a simulated source
XInputGetState, XInputSetState, XInputGetCapabilities and XInputEnable
on xinput1_4.dll, reachable from xinput1_3.dll and xinput9_1_0.dll.
Readings come from a host-connected ControllerSource; without one,
every slot reports ERROR_DEVICE_NOT_CONNECTED.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 19:16:39 -05:00
Adeeb Rahman 1fdefc7250 Add ioctlsocket FIONREAD and FIONBIO for loopback sockets
FIONREAD reports unread stream bytes or the size of the next datagram.
FIONBIO accepts non-blocking mode; blocking mode returns WSAEOPNOTSUPP
because loopback sockets never block.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 18:57:02 -05:00
Adeeb Rahman 16e0ff446a Add process-local Winsock TCP loopback
Stream sockets listen, accept and connect between guest sockets on
127.0.0.1 inside the runtime; no host socket is opened. Each socket
buffers up to 64 KiB, send takes what fits, recv returns 0 at end of
file after shutdown(SD_SEND) or closesocket, and sending to a closed
peer reports WSAECONNRESET. WSAPoll reports listen-queue readiness,
write space and POLLHUP. TCP and UDP ports are separate namespaces.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 18:54:04 -05:00
Adeeb Rahman 9a7ae95f61 Record PR push, CI and MoveFileExW in the runtime handoff
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 18:47:37 -05:00
Adeeb Rahman 6229447a6a Add MoveFileExW with replace and write-through on both drives
MoveFileExW accepts MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH
and MOVEFILE_COPY_ALLOWED. A closed file may atomically replace another
closed file on a host mount or the synthetic C: drive; directories are
never replaced, and open files can neither move nor be replaced. Write
through flushes both host directories. Moves between drives report
ERROR_NOT_SAME_DEVICE, or ERROR_NOT_SUPPORTED when a copy is allowed.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 18:47:18 -05:00
Adeeb Rahman 7bb47989e5 Rename files and directories within writable host mounts
MoveFileW now renames closed files and directories inside one writable
host mount using an exclusive host rename (renameatx_np RENAME_EXCL on
macOS, renameat2 RENAME_NOREPLACE on Linux), so an existing name is
never replaced. A change of case alone renames in place. Open files,
read-only mounts, the mount root and moves between drives fail with
explicit Win32 errors.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 18:38:16 -05:00
Adeeb Rahman b1b6629f8b Update system-runtime handoff after upstream sync and mount quota
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 18:33:49 -05:00
Adeeb Rahman 30cf55e753 Bound net growth of writable host mounts with an optional quota
HostMount::with_quota limits the net bytes and the number of files and
directories guest operations add to a writable mount. Win32 writes,
extending SetEndOfFile, CreateFileW, CreateDirectoryW, GetTempFileNameW
and CRT fopen/fclose are charged; deletion and shrinking give the
amount back, never below zero. Exceeding a limit fails with
ERROR_DISK_FULL (CRT ENOSPC) and leaves the host unchanged.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 18:33:49 -05:00
Adeeb Rahman 52ddb4f51f Merge remote-tracking branch 'origin/main' into feat/system-runtime-expansion
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 18:19:19 -05:00
Adeeb Rahman 4afbbc3a32 Format system runtime changes for workspace verification
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 16:02:20 -05:00
Adeeb Rahman b0b6733a27 Share file position and timestamp policy across duplicate handles
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 16:01:23 -05:00
Adeeb Rahman bbfe9027a9 Honor timestamp suppression on synthetic guest file handles
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 16:00:28 -05:00
Adeeb Rahman b031640fef Advance synthetic file timestamps using the guest clock
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:59:03 -05:00
Adeeb Rahman 6aa386a916 Merge remote-tracking branch 'origin/main' into feat/system-runtime-expansion
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 15:58:47 -05:00
Adeeb Rahman 6dc241323b Track explicit timestamps on synthetic guest files
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:57:53 -05:00
Adeeb Rahman cda25954fa Update mounted file timestamps through guest handles
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:56:26 -05:00
Adeeb Rahman c4a2b53ac4 Read Win32 file timestamps from open guest handles
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:55:12 -05:00
Adeeb Rahman 7b0255b4df Merge remote-tracking branch 'origin/main' into feat/system-runtime-expansion
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 15:54:37 -05:00
Adeeb Rahman da9f2c0035 Expose mounted file timestamps to Win32 guests
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:53:55 -05:00
Adeeb Rahman b15226efe9 Return extended Win32 path metadata
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:52:08 -05:00
Adeeb Rahman 74fdf04f78 Report Win32 file types for guest disk handles
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:50:55 -05:00
Adeeb Rahman 1127cac9d9 Implement legacy Win32 file size queries
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:49:58 -05:00
Adeeb Rahman 0fdd33a440 Flush writable guest file handles
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:48:41 -05:00
Adeeb Rahman ef5337557f Support ASCII Win32 file creation and open
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:47:18 -05:00
Adeeb Rahman d96dd70bc3 Support ASCII Win32 file deletion
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:45:59 -05:00
Adeeb Rahman 89dae334bf Support ASCII Win32 file attribute queries
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:44:44 -05:00
Adeeb Rahman 55c51b40d4 Merge remote-tracking branch 'origin/main' into feat/system-runtime-expansion 2026-11-24 15:43:41 -05:00
Adeeb Rahman f21d8ea1be Create guest temporary files on explicit host mounts
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:43:10 -05:00
Adeeb Rahman 941ac8cf2e Create temporary files on the synthetic guest drive
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:41:41 -05:00
Adeeb Rahman db20a1870f Expose guest-scoped Win32 temporary directory lookup
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:39:40 -05:00
Adeeb Rahman c45e11d5af Report host directory creation collisions consistently
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:37:28 -05:00
Adeeb Rahman b00321aa1e Implement caller-owned UCRT wide tokenization
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:35:46 -05:00
Adeeb Rahman d8d008668f Verify strtok_s through translated Win64 imports
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:34:04 -05:00
Adeeb Rahman 8b12bf4212 Merge remote-tracking branch 'origin/main' into feat/system-runtime-expansion 2026-11-24 15:32:56 -05:00
Adeeb Rahman d94173ba3d Implement caller-owned UCRT byte tokenization
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:32:38 -05:00
Adeeb Rahman 83e497a97b Document Win64 CRT tokenization and search signatures in the catalog
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:29:34 -05:00
Adeeb Rahman 3b926d5166 Verify wcstok guest ABI and cross-alias continuation
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:23:23 -05:00
Adeeb Rahman 290a6b620b Implement wide CRT tokenization with explicit guest context
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:22:00 -05:00
Adeeb Rahman ddd190ab18 Add checked linear byte and wide CRT substring search
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:20:26 -05:00
Adeeb Rahman e12421264f Implement Win64 CRT byte and wide character-set searches
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:19:01 -05:00
Adeeb Rahman d62644ab6a Merge remote-tracking branch 'origin/main' into feat/system-runtime-expansion
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:17:19 -05:00
Adeeb Rahman 83544bd811 Implement bounded guest CRT strtok with isolated cursors
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:17:00 -05:00
Adeeb Rahman 96bbfcb883 Merge remote-tracking branch 'origin/main' into feat/system-runtime-expansion
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 15:15:08 -05:00
Adeeb Rahman 3b6f9d99da Support ASCII Win32 current-directory calls
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:14:40 -05:00
Adeeb Rahman 742284152f Resolve synthetic Win32 file paths against the guest current directory
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:13:16 -05:00
Adeeb Rahman d0f199b0e8 Merge remote-tracking branch 'origin/main' into feat/system-runtime-expansion
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 15:10:54 -05:00
Adeeb RahmanandCursor c789dc6fd0 Merge upstream main 3c8b6ba into system runtime branch
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-24 15:04:03 -05:00
Adeeb RahmanandCursor 05135df227 Refresh handoff tip commit after publishing the brief.
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-24 15:03:09 -05:00
Adeeb RahmanandCursor 36f9b1c4ba Document system-runtime handoff for the next agent.
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-24 15:02:57 -05:00
Adeeb Rahman 8a677bc265 Drop dead AT_EMPTY_PATH unlink and document name-based remove limits.
Linux unlinkat rejects AT_EMPTY_PATH, and macOS never compiled that path,
so every remove was already name-based. State the in-mount TOCTOU plainly.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 15:00:57 -05:00
Adeeb Rahman 550b2cec5f Merge upstream main d7f7d58 into system runtime branch
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 12:29:00 -05:00
Adeeb Rahman 680f572af4 Expand CRT I/O, env, time, rand and Winsock UDP helpers.
Mount-backed fopen, atoi/_putenv/time/rand/_stricmp, synthetic
GetModuleFileName paths, and sendto/recvfrom for the loopback stack.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 12:26:04 -05:00
Adeeb Rahman 2aa0cb0a5a Schedule XAsync work and completion through manual queues
When an XAsyncBlock carries a non-null XTaskQueue handle, submit work to
the work port and completion to the completion port so guests can
XTaskQueueDispatch them. Null-queue immediate dispatch is unchanged.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 11:41:05 -05:00
Adeeb Rahman 450a5e4889 Merge upstream main 1d363c3 into system runtime branch
Integrate VOP2 VCC, VOPC16, SOPP control and REP/MOVS/STOS landings.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 11:34:56 -05:00
Adeeb Rahman 86c7d5e4cd Merge host-mount doc clarification into system runtime branch
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 11:30:19 -05:00
Adeeb Rahman e5622b7dd3 Clarify host-mount docs await a human security audit
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 11:30:09 -05:00
Adeeb Rahman 203ed40bd0 Merge empty CI retrigger tip into system runtime branch
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 11:29:57 -05:00
Adeeb Rahman 897d2c9e40 Retrigger native CI after cancelled ARM64 job
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 11:23:36 -05:00
Adeeb Rahman e80700550f Fix printf errno path after stream writability check
Keep guest memory borrows disjoint when reporting EINVAL for a
non-writable stdout cookie.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 11:10:11 -05:00
Adeeb Rahman 3c3d1f5cc0 Add printf and fprintf on the in-memory CRT stream subset
Route formatted output through the shared sprintf converter; stdout and
stderr discard payloads while file streams append the rendered bytes.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 11:09:47 -05:00
Adeeb Rahman 2a788e7684 Merge upstream main 3348d34 into system runtime branch
Integrate VOPC 64-bit integer compare registry forms (#215 / #324).

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 11:09:14 -05:00
Adeeb Rahman 8ae0d847c9 Add in-memory CRT FILE streams and process environment queries
Implement fopen/fread/fwrite and related stream helpers over a bounded
runtime file store, plus getenv and GetEnvironmentVariableA/W against a
guest-owned environment block that does not expose the host process.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 11:09:13 -05:00
Adeeb Rahman b5f26155cf Merge upstream main 6ad1602 into system runtime branch
Restore the XADD/CMPXCHG/LOCK changelog entry (#198 / #321).

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 11:04:48 -05:00
Adeeb Rahman fd0a19658e Document expanded CRT string and locale surface
Keep interfaces and changelog aligned with the newly registered C-locale
and string services.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 11:04:14 -05:00
Adeeb Rahman 1c89092fe4 Add wcscpy, wcsncpy, wcscat, wcschr and wcsrchr CRT services
Wide-string copies and searches over checked guest memory, matching the
byte-string budget and fail-closed unterminated input policy.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 11:04:02 -05:00
Adeeb Rahman 8a4cfb59c9 Merge upstream main bf2c279 into system runtime branch
Integrate CPUID guest feature contract (#130 / #322).

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 11:03:20 -05:00
Adeeb Rahman b56da7f587 Add strstr, strspn and strcspn CRT services
Span and substring scans over checked guest memory with the shared 1 MiB
budget, registered as standard services.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 11:03:20 -05:00
Adeeb Rahman d292e537f1 Add strcpy, strncpy, strcat, strncat and memchr CRT services
Checked guest-memory implementations for the remaining core byte-string
mutators, registered as standard services alongside the existing scans.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 11:02:51 -05:00
Adeeb Rahman 587711ab6e Add C-locale ctype classification and case mapping
Implement isalnum/isalpha/isdigit and related predicates plus
tolower/toupper with MSVC EOF rules, registered as standard services.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 11:01:39 -05:00
Adeeb Rahman 2d8cd4579e Merge upstream main a031883 into system runtime branch
Integrate XADD/CMPXCHG/LOCK memory forms (#198 / #320).

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 11:00:28 -05:00
Adeeb Rahman 991a02ea04 Add C-locale CRT, sprintf subset, and immediate XAsync helpers
Extend the system runtime with setlocale/localeconv (C only), a bounded
sprintf/snprintf converter, and XAsyncRun/GetStatus/Cancel/GetResultSize
on the calling thread. Register the new symbols as standard services.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 11:00:25 -05:00
Adeeb Rahman 6ec0f88f76 Merge upstream main 7499d6f into system runtime branch
Integrate VOP1 integer registry forms (#215 / #318). No runtime overlap.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 10:54:15 -05:00
Adeeb Rahman 1780d0bd3d Merge upstream main fb05446 into system runtime branch
Harden host-backed guest drives after agent security and implementation
review: O_NOFOLLOW mount roots, identity re-check before unlink with
Linux AT_EMPTY_PATH when available, CREATE_ALWAYS truncate coverage,
and honest docs about residual trusted-host limits.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 10:52:12 -05:00
Adeeb Rahman 5ee54f1eb6 Fail closed on unreadable host file identity and bound file sizes
Author-side review findings: sharing and delete checks now treat an
unreadable identity as the same file, writable mounts limit file size
(1 GiB by default), and errno handling is portable.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 10:44:45 -05:00
Adeeb Rahman 228f968df3 Merge upstream main b9f6985 into system runtime branch
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 10:35:58 -05:00
Adeeb Rahman d65240969e Harden host-backed guest drives after review
Accept only D: to Z:. Hide multiply linked files. Verify each opened
descriptor's type and identity against the listing. Compare live
device and inode for sharing and deletion, and check sharing before a
truncating open. Report directory listing errors and limits
explicitly. Add regression tests for hard links, host swaps between
listing and open, renames, read-only enforcement and limits, and
describe the policy and its remaining limits without unconditional
confinement claims.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 10:33:02 -05:00
Adeeb Rahman 176993c504 Merge upstream main 7504a5d into system runtime branch
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 10:25:02 -05:00
Adeeb Rahman 41c6942180 Decode MSVC decorated names for import diagnostics
Add a clean-room decoder for the common decoration grammar, show its
output in generator manifests, and test it against names clang mangles
for x86_64-pc-windows-msvc.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 10:24:44 -05:00
Adeeb Rahman 27ce4cddb1 Benchmark guest service dispatch and scan CRT strings in blocks
Add correctness-gated guest loops that time services through the
import table. Scan string lengths 256 units at a time, falling back to
single units at mapping boundaries to keep exact faults.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 10:19:44 -05:00
Adeeb Rahman f2f9992335 Merge upstream main f2e6db0 into system runtime branch
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 10:14:40 -05:00
Adeeb Rahman a4307f905a Fuzz the standard guest service registry
Drive random service call sequences with adversarial arguments and
check memory and register invariants after every call. The libFuzzer
target and a stable replay test share one driver.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 10:14:40 -05:00
Adeeb Rahman eabab264ea Merge upstream main 0a722d2 into system runtime branch
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 10:02:59 -05:00
Adeeb Rahman 21738c9d67 Back guest drives with explicitly mounted host directories
Resolve each path component from the mount's root descriptor with
openat and O_NOFOLLOW, matching names case-insensitively and hiding
symbolic links, so guest paths cannot leave the mounted root. Mounts
are read-only unless configured writable.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 10:02:59 -05:00
50 changed files with 13967 additions and 857 deletions

No files matched your search

+48
View File
@@ -27,11 +27,51 @@ remains unsupported.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Fixed
- The import metadata classified `strtod`, `strtof` and `wcstod` as native libc calls with an identical ABI and `atof`/`_wtof` as stubs; they are now runtime services.
- The import metadata classified `ungetc` as a native libc call with an identical ABI, although it takes a guest `FILE*`; it and `fgets` are now runtime services.
- The import metadata mapped `labs` and `ldiv` to the host libc as identical-ABI calls, but Windows `long` is 32 bits and macOS `long` is 64 bits; the integer functions are now runtime services. The generated `abs`/`labs` adapter no longer panics on the minimum integer. `crates/import-gen/tests/pipeline.rs` now exercises the adapter path through a test-only native entry, because no built-in symbol uses it any more.
- The import metadata still classified `ExitProcess` on `kernel32.dll` and `api-ms-win-core-processthreads-l1-1-0.dll` as a stub that "calls exit(0)" after guest process exit landed (#331). It is now a runtime service; the coverage report shows no disagreements.
- The import metadata classified `abort` and `_exit` as native libc calls with an identical ABI, which would describe ending the host process. They, `terminate` and `_purecall` are now runtime services that end only the guest.
- Guest `strncpy` and `wcsncpy` with a count far larger than the destination (for example all ones) aborted the host process while allocating the zero padding. The padding is now written in bounded chunks, and the guest faults at the first byte it cannot write. Found by the `runtime_services` fuzz replay after the stronger harness from main was merged; covered by `tests/runtime_crt_strncpy.rs`.
- The import metadata classified `fputc`, `putc`, `fputs`, `puts`, `fgetc`, `getc` and `fflush` as native libc calls with an identical ABI, although they take guest `FILE*` cookies; they are now runtime services.
- The import metadata still classified `CreateThread`, `ExitThread`, `SuspendThread` and `ResumeThread` as stubs after the guest thread scheduler landed, and did not list `TerminateThread`, `GetExitCodeThread` or `SwitchToThread`. They are now runtime services on `kernel32.dll` and `api-ms-win-core-processthreads-l1-1-0.dll`.
- The import metadata described `strcpy_s`, `strcat_s`, `strncpy_s`, `strncat_s`, `wcscpy_s` and `wcscat_s` as libc wrappers that ignore the buffer size. The generator emitted stopping stubs for that class, so no unchecked copy ever ran, but the entries bypassed the runtime services; they are now classified as runtime services.
- The import metadata classified `GetCurrentProcess`, `GetCurrentProcessId`, `GetCurrentThread`, `GetCurrentThreadId`, `GetThreadPriority` and `SetThreadPriority` on `kernel32.dll` and `api-ms-win-core-processthreads-l1-1-0.dll` as stubs although the runtime provides them, so the import generator would have emitted stubs for working services.
- Removed the unused Linux `AT_EMPTY_PATH` unlink path from host-backed drives and corrected docs/changelog claims: removal is name-based on every host, with the in-mount check-then-unlink race against trusted host writers stated plainly.
- Non-canonical 64-bit guest data addresses now raise `#GP` instead of a memory fault in both the interpreter and native DBT, including accesses that cross the canonical-address boundary. The synthetic architectural test is enabled again.
- Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing.
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
### Added
- Winsock `ioctlsocket` with `FIONREAD` (unread stream bytes or next datagram size) and `FIONBIO` for non-blocking mode; requesting blocking mode returns `WSAEOPNOTSUPP` because loopback sockets never block.
- XInput controller services (`XInputGetState`, `XInputSetState`, `XInputGetCapabilities`, `XInputEnable`) on `xinput1_4.dll`, `xinput1_3.dll` and `xinput9_1_0.dll`, fed by a host-connected controller source. Tests use a simulated controller; no physical controller or app input path is connected yet.
- C++ `type_info` helpers on `vcruntime140.dll`: equality, ordering and hashing by decorated name, and readable names for plain class, struct, union and enum types. Unsupported decorations such as templates stop the guest rather than return a wrong name.
- `__std_exception_copy` and `__std_exception_destroy` on `vcruntime140.dll`, so copied `std::exception` objects keep their own message after the original is destroyed. Throwing and catching exceptions remain unsupported.
- UCRT `_msize`, `_recalloc` and the `_aligned_malloc` family on the CRT heap, with overflow checks, zeroed growth and detection of double or mismatched aligned frees. Alignments above 64 KiB fail rather than return a misaligned block.
- Bounds-checked `strcpy_s`, `strcat_s`, `strncpy_s`, `strncat_s` and their `wcs` forms, with the documented `EINVAL`, `ERANGE` and `_TRUNCATE` behaviour.
- CRT `fputc`, `putc`, `fputs`, `puts`, `fgetc`, `getc` and `fflush`. `fflush` writes a host-backed stream to its mounted file (charging the mount quota) and publishes an in-memory file before `fclose`; standard output is still discarded.
- Abnormal CRT termination: `abort`, `terminate`, `_purecall`, `__std_terminate` and `_exit` end the guest process through the same exit as `ExitProcess` (exit code 3 for the abort family, the given status for `_exit`). Handlers cannot be installed yet, and `exit` is not provided.
- CRT `abs`, `labs`, `llabs`, `div`, `ldiv` and `lldiv` with Windows' 32-bit `long` and the Win64 struct-return rules (`lldiv_t` through a hidden pointer). Division by zero stops the guest with a divide error.
- CRT `ungetc` (one byte of push-back that is never written to the file) and `fgets` (line reads up to the count) on the shared `fopen` streams.
- CRT `strtod`, `strtof`, `wcstod`, `wcstof`, `atof` and `_wtof` in the "C" locale, returning in XMM0, correctly rounded straight to the result type, with `ERANGE` on overflow and on underflow to zero. Hexadecimal floating constants stop the guest. The guest test harness gains `Guest::run_state` to read XMM results.
- `SymbolDb::insert` lets a project classify a module the built-in import metadata does not describe.
- `IsProcessorFeaturePresent`, answered from the guest CPUID table so startup code never selects instruction sets the translator does not report. It currently reports no optional features.
- `GetTimeZoneInformation` (the guest zone is UTC) and `GetLogicalProcessorInformation` (cores and package from the guest profile; no simulated caches are reported).
- `xenora imports coverage` writes a deterministic report of every standard runtime service by module and status, and lists where the import metadata disagrees with the registry.
- The import metadata now classifies the 84 kernel32, UCRT, Winsock, XGameRuntime and XInput services the runtime registered without a catalog entry, so the import generator no longer treats them as unknown. Only the synthetic fixture modules remain uncatalogued.
- Process-local Winsock TCP loopback: `listen`, `accept`, stream `connect`, `send`, `recv` and `shutdown` between guest sockets on 127.0.0.1, with 64 KiB of buffering per socket, end of file on shutdown or close, `WSAECONNRESET` after the peer closes, `POLLHUP` from `WSAPoll`, and separate TCP and UDP port spaces. No host socket is opened. Translated guest tests cover streaming, flow control, shutdown, closing, refusal and external-address rejection.
- `MoveFileExW` on host mounts and the synthetic C: drive, with `MOVEFILE_REPLACE_EXISTING` (atomic replacement of a closed file, as in the write-then-replace save pattern), `MOVEFILE_WRITE_THROUGH` (flushes both host directories) and `MOVEFILE_COPY_ALLOWED`. Directories are never replaced, open files cannot be moved or replaced, and moves between drives report `ERROR_NOT_SAME_DEVICE` or, when a copy is allowed, `ERROR_NOT_SUPPORTED`.
- `MoveFileW` renames closed files and directories within one writable host mount, including changes of case only. It uses an exclusive host rename (`renameatx_np` with `RENAME_EXCL` on macOS), so an existing name is never replaced. Moves between drives and of open files fail explicitly. A translated guest test covers renames, collisions, confinement and errors.
- Writable host mounts accept an optional quota (`HostMount::with_quota`) on the net bytes and the number of files and directories guest operations add. Win32 writes, extending `SetEndOfFile`, file and directory creation, `GetTempFileNameW` and CRT `fopen`/`fclose` are charged; deletion and shrinking give the amount back. Exceeding the quota fails with `ERROR_DISK_FULL` (CRT `ENOSPC`) without changing the host. A translated guest test covers each path.
- Extended CRT FILE streams so mounted drive paths (`D:\…`) open through the host mount table: the file is buffered under the stream size cap and writable streams replace the host file on `fclose`. Single-component names stay in-memory. Covered by unit and import-table tests.
- Added CRT `atoi` / `atol` / `atoll` / `_atoi64` / `_wtoi` / `_wtol` / `_wtoi64` as base-10 wrappers over the existing integer conversion parser (Windows LLP64 `long` is 32-bit).
- Added `_putenv` and `SetEnvironmentVariableA` / `SetEnvironmentVariableW` to update the runtime-owned environment block used by `getenv` and `GetEnvironmentVariable*`.
- Added CRT calendar time (`time`, `_time64`, `gmtime_s`, `localtime_s`, `_gmtime64_s`, `_localtime64_s`) against the injectable guest clock. Local time matches UTC; there is no guest timezone database.
- Added CRT `srand` / `rand` / `rand_s` using the publicly documented MSVC LCG. `rand_s` is not a CSPRNG.
- Documented the process-local Winsock UDP loopback (`ws2_32.dll`) in `docs/interfaces.md`: bounds, non-blocking `recv`, and that nothing reaches the host network stack.
- Added process-local Winsock `sendto` / `recvfrom` for unconnected IPv4 UDP loopback (auto-bind on send, source address on receive).
- Added CRT `_stricmp` / `_strnicmp` / `_wcsicmp` / `_wcsnicmp` with C-locale ASCII case folding only.
- Added `GetModuleFileNameA` / `GetModuleFileNameW` returning synthetic guest paths (`C:\xenora\guest.exe` for a null handle; `C:\Windows\System32\<module>` for built-in DLLs).
- Added `tests/runtime_clock.rs`, which reads the performance counter, its frequency, both tick counts, the unbiased interrupt time and the system time from one injected clock and checks that they report the same elapsed time in their own units, after a host advance and after a guest `Sleep`, and that none of them decreases up to and past the end of the clock (#204). Expected values are worked out by hand from the documented units. Timed waits still return without consuming clock time.
- Added opt-in shader IR constant folding (`CompileOptions::fold_constants` / `compile_with`) for pure vector unary and binary ops whose operands are already constants (#141). Floating-point ops still use the exact positive-normal rules; loads, stores, lane masks, merges and branches are never folded. Default `compile` keeps the historical IR. Covered by hand-computed known-answer compiler tests (shifts by 32/33, ashr, min_i32 vs min_u32, mul_hi_i32_i24, ffbh_i32, exact float fold, load-derived float non-fold, and verify rejection of inexact constant float add) with a fold-on versus fold-off check, plus an MSL template drift check over every foldable op.
- Added opt-in shader IR common-subexpression elimination (`CompileOptions::eliminate_common_subexpressions` / `compile_with`) that reuses the first result of an equivalent pure vector unary or binary (#142). Equivalence is the same operation and the same operand values in the same order; constant operands match by bit pattern. Loads, stores, constant definitions, lane masks, merges, branches and other side-effecting or execution-mask-dependent ops are left in place. The pass runs after constant folding, so folded results stay constants and a later pure op on two equal folded constants can still be reused. Default `compile` keeps the historical IR. Covered by hand-derived known-answer compiler tests for reuse (and/xor, not, exact float add), for rejected loads, swapped subtracts, lane masks, lane merges and VCC selects, and for the four combinations with constant folding (1 + 2 = 3, and 1.0 + 2.0 = 3.0), and a check that the 13 golden fixtures, none of which repeats an expression, compile unchanged with the pass on. No speedup is claimed.
@@ -95,6 +135,14 @@ remains unsupported.
- Added a `runtime_services` fuzz target (`scripts/fuzz.sh runtime_services`) and a stable-toolchain replay test sharing the same driver. Both call random sequences of the standard guest services with zero, all-ones, writable, read-only, executable, unmapped, raw and earlier-result arguments, and check after every call that read-only and code memory are unchanged and nonvolatile registers are preserved. Writable guest memory is filled from a deterministic pattern so corpus bytes are reserved for dispatch. An earlier 300-second campaign's input and edge counts are withdrawn: that run exhausted each input while filling the 65,536-byte writable region and never reached the dispatch loop. After the harness fix, a local 300-second campaign on Apple Silicon (`scripts/fuzz.sh runtime_services 300`) ran 96,589 inputs (4,008 coverage edges, 9,940 features) without a crash; the first minutes also found a ~3.7 GiB `XMemAlloc` host OOM, which is now fixed by failing closed on overflowing sizes and routing mappings through the virtual allocation budget. Services that wait on real time or reach native Metal are excluded.
- Added guest drives backed by explicitly mounted host directories, read-only unless configured writable. Every operation resolves paths from the mount's root descriptor with `openat` and `O_NOFOLLOW`. Mount roots are opened with `O_NOFOLLOW`. Symbolic links, devices and multiply linked files are hidden. Each opened descriptor's type and identity are verified against the listing. Sharing and deletion checks compare live device and inode, and listings are bounded with explicit errors. Removal re-checks identity then uses name-based `unlinkat` (in-mount TOCTOU against trusted host writers remains; file unlinks fail closed if the held inode's link count did not drop). Regression tests cover traversal, links, host swaps between calls and between listing and open, renames, read-only enforcement and limits. The policy and its remaining limits are in `docs/interfaces.md`. Guest path confinement for this boundary was agent-reviewed (not a human security audit).
- Added C-locale CRT services (`setlocale`, `localeconv`), C-locale `ctype.h` predicates and case mapping, byte and wide string mutators (`strcpy`/`strncpy`/`strcat`/`strncat`/`memchr`/`strstr`/`strspn`/`strcspn`, `wcscpy`/`wcsncpy`/`wcscat`/`wcschr`/`wcsrchr`), and a bounded `sprintf`/`snprintf` subset (`%%`, `%c`, `%s`, `%d`/`%i`, `%u`, `%x`/`%X`, `%p`, optional widths and `l`/`ll`/`z`/`t`). Non-C locales and unsupported conversions fail closed. See `docs/interfaces.md`.
- Added an XAsync subset (`XAsyncRun`, `XAsyncGetStatus`, `XAsyncCancel`, `XAsyncGetResultSize`) on `xgameruntime.dll`. With a null queue, work and completion run on the calling thread before `XAsyncRun` returns. With a manual `XTaskQueue` handle in the `XAsyncBlock`, work is submitted to the work port and completion to the completion port for `XTaskQueueDispatch`. Waiting GetStatus is unsupported.
- Added CRT FILE streams (`fopen`/`fclose`/`fread`/`fwrite`/`fseek`/`ftell`/`feof`/`ferror`/`rewind`, `__acrt_iob_func`) and a runtime environment block for `getenv` / `GetEnvironmentVariableA` / `GetEnvironmentVariableW`. Single-component names stay in an in-memory store. Paths with a mounted drive letter (`D:\…`) open through the host mount table: contents are buffered up to the stream size cap and writable streams replace the host file on `fclose`. The host process environment is not exposed by default.
- Added guest system information, memory status, calendar time conversion, interrupt time and sleeping. The guest sees a configurable simulated machine (`GuestSystemProfile`, one processor by default), kept separate from the detected host hardware (`HostCapabilities`). Sleeping goes through the injectable clock, so tests advance time deterministically. An original PE32+ fixture verifies `SYSTEM_INFO`, `MEMORYSTATUSEX` and `SYSTEMTIME` layouts and leap-year handling against dates computed independently.
- Added services that call guest code and continue when it returns. The import dispatcher can run a sequence of guest callbacks on a checked stack frame, verifying the Win64 nonvolatile registers after each one. The CRT uses this for `qsort`, `qsort_s`, `bsearch`, `bsearch_s`, `_initterm`, `_initterm_e`, onexit tables, `atexit` and `_cexit`. Kernel32 uses it for `InitOnceExecuteOnce` and `FlsFree` cleanup callbacks. Original guest comparators and initializers in a PE32+ fixture verify ordering, stop-on-failure and register preservation.
+185
View File
@@ -0,0 +1,185 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! `xenora imports coverage`: what the standard service registry provides,
//! set against what the import metadata says about the same symbols.
//!
//! The report is built from the registry and the built-in symbol database
//! alone, so the same source tree always produces the same bytes. It does not
//! read executables, the network or the clock.
use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::process::ExitCode;
use std::sync::Arc;
use xenora_import_gen::{Classification, SymbolDb};
use xenora_loader::ImportRegistry;
use xenora_loader::import_table::ImportName;
use xenora_loader::imports::ServiceStatus;
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
const DEFAULT_OUT: &str = "artifacts/coverage/api-coverage.md";
#[derive(Default)]
struct Counts {
implemented: usize,
partial: usize,
stub: usize,
aliases: usize,
}
/// Render the report.
pub fn render() -> String {
let mut registry = ImportRegistry::new();
register_standard_services(
&mut registry,
Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))),
);
let db = SymbolDb::builtin();
let mut modules: BTreeMap<String, Counts> = BTreeMap::new();
let mut services: Vec<(String, String, ServiceStatus)> = registry
.iter_registered()
.map(|(module, symbol, status)| (module.to_ascii_lowercase(), symbol.to_owned(), status))
.collect();
services.sort_by(|a, b| (&a.0, &a.1).cmp(&(&b.0, &b.1)));
for (module, _, status) in &services {
let counts = modules.entry(module.clone()).or_default();
match status {
ServiceStatus::Implemented => counts.implemented += 1,
ServiceStatus::Partial => counts.partial += 1,
ServiceStatus::Stub => counts.stub += 1,
}
}
let mut aliases: Vec<(String, String, String)> = registry
.iter_aliases()
.map(|(module, symbol, target)| {
(
module.to_owned(),
symbol.to_owned(),
target.to_ascii_lowercase(),
)
})
.collect();
aliases.sort();
for (module, _, _) in &aliases {
modules.entry(module.clone()).or_default().aliases += 1;
}
// Metadata the registry contradicts, in either direction.
let mut unclassified = Vec::new();
let mut disagreeing = Vec::new();
for (module, symbol, status) in &services {
match db.get(module, symbol) {
None => unclassified.push(format!("`{module}!{symbol}` ({})", status.as_str())),
Some(Classification::StandardService) => {}
Some(class) => disagreeing.push(format!(
"`{module}!{symbol}`: registered {}, metadata says {}",
status.as_str(),
class.tier_name()
)),
}
}
let mut missing = Vec::new();
for (module, symbol, class) in db.entries() {
if matches!(class, Classification::StandardService)
&& registry
.resolve(module, &ImportName::Name(symbol.to_owned()))
.is_none()
{
missing.push(format!("`{module}!{symbol}`"));
}
}
let total = |pick: fn(&Counts) -> usize| modules.values().map(pick).sum::<usize>();
let mut md = String::new();
let _ = writeln!(md, "# Runtime API coverage");
let _ = writeln!(md);
let _ = writeln!(
md,
"Generated by `xenora imports coverage` from the standard service registry and the built-in import metadata. Do not edit."
);
let _ = writeln!(md);
let _ = writeln!(
md,
"A registered service is not a compatibility claim. `implemented` and `partial` describe behaviour against the documented contract for synthetic guests; no service has been independently accepted, and no Xbox or commercial game has run."
);
let _ = writeln!(md);
let _ = writeln!(md, "## Totals");
let _ = writeln!(md);
let _ = writeln!(md, "| Measure | Count |");
let _ = writeln!(md, "| --- | ---: |");
let _ = writeln!(md, "| Services | {} |", services.len());
let _ = writeln!(md, "| Implemented | {} |", total(|c| c.implemented));
let _ = writeln!(md, "| Partial | {} |", total(|c| c.partial));
let _ = writeln!(md, "| Stub | {} |", total(|c| c.stub));
let _ = writeln!(md, "| Aliases (not services) | {} |", aliases.len());
let _ = writeln!(
md,
"| Registered but not in metadata | {} |",
unclassified.len()
);
let _ = writeln!(
md,
"| Metadata disagrees with registry | {} |",
disagreeing.len()
);
let _ = writeln!(
md,
"| Metadata expects a service that is missing | {} |",
missing.len()
);
let _ = writeln!(md);
let _ = writeln!(md, "## By module");
let _ = writeln!(md);
let _ = writeln!(md, "| Module | Implemented | Partial | Stub | Aliases |");
let _ = writeln!(md, "| --- | ---: | ---: | ---: | ---: |");
for (module, c) in &modules {
let _ = writeln!(
md,
"| `{module}` | {} | {} | {} | {} |",
c.implemented, c.partial, c.stub, c.aliases
);
}
for (title, list) in [
("Metadata expects a service that is missing", &missing),
("Metadata disagrees with registry", &disagreeing),
("Registered but not in metadata", &unclassified),
] {
let _ = writeln!(md);
let _ = writeln!(md, "## {title}");
let _ = writeln!(md);
if list.is_empty() {
let _ = writeln!(md, "None.");
}
for line in list {
let _ = writeln!(md, "- {line}");
}
}
md
}
/// `xenora imports coverage [--out <file>]`
pub fn command(args: &[String]) -> ExitCode {
let out = match args {
[] => DEFAULT_OUT.to_owned(),
[flag, path] if flag == "--out" => path.clone(),
_ => {
eprintln!("usage: xenora imports coverage [--out <file>]");
return ExitCode::from(2);
}
};
let report = render();
let path = std::path::Path::new(&out);
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty())
&& let Err(error) = std::fs::create_dir_all(parent)
{
eprintln!("failed to create {}: {error}", parent.display());
return ExitCode::FAILURE;
}
if let Err(error) = std::fs::write(path, &report) {
eprintln!("failed to write {out}: {error}");
return ExitCode::FAILURE;
}
println!("Coverage report written to: {out}");
ExitCode::SUCCESS
}
+5 -2
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-or-later
mod coverage;
mod demo;
mod runner;
mod shaders;
@@ -147,9 +148,10 @@ fn main() -> ExitCode {
/// `xenora imports generate --pe <path> [--out <dir>]`
/// `xenora imports metadata sync [--out <dir>]`
/// `xenora imports verify`
/// `xenora imports coverage [--out <file>]`
fn imports_command(args: Vec<String>) -> ExitCode {
if args.is_empty() {
eprintln!("usage: xenora imports <sync|generate|metadata|verify> [options]");
eprintln!("usage: xenora imports <sync|generate|metadata|verify|coverage> [options]");
return ExitCode::from(2);
}
@@ -158,9 +160,10 @@ fn imports_command(args: Vec<String>) -> ExitCode {
"sync" => run_imports_sync_cli(&args[1..]),
"metadata" => run_imports_metadata_cli(&args[1..]),
"verify" => run_imports_verify_cli(&args[1..]),
"coverage" => coverage::command(&args[1..]),
other => {
eprintln!("unknown imports subcommand: {other}");
eprintln!("usage: xenora imports <sync|generate|metadata|verify> [options]");
eprintln!("usage: xenora imports <sync|generate|metadata|verify|coverage> [options]");
ExitCode::from(2)
}
}
+62
View File
@@ -0,0 +1,62 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! `xenora imports coverage` is deterministic and agrees with the registry.
use std::process::Command;
fn report(name: &str) -> String {
let path =
std::env::temp_dir().join(format!("xenora-coverage-{}-{name}.md", std::process::id()));
let status = Command::new(env!("CARGO_BIN_EXE_xenora"))
.args(["imports", "coverage", "--out"])
.arg(&path)
.status()
.unwrap();
assert!(status.success());
let text = std::fs::read_to_string(&path).unwrap();
std::fs::remove_file(path).unwrap();
text
}
fn count(report: &str, measure: &str) -> usize {
let prefix = format!("| {measure} | ");
let line = report
.lines()
.find(|line| line.starts_with(&prefix))
.unwrap_or_else(|| panic!("no {measure} row"));
line[prefix.len()..].trim_end_matches(" |").parse().unwrap()
}
#[test]
fn coverage_is_deterministic_and_consistent() {
let first = report("a");
assert_eq!(first, report("b"), "two runs differ");
let services = count(&first, "Services");
assert!(services > 100, "{services}");
assert_eq!(
services,
count(&first, "Implemented") + count(&first, "Partial") + count(&first, "Stub")
);
// The import generator skips adapters for these, so none may be missing.
assert_eq!(
count(&first, "Metadata expects a service that is missing"),
0
);
for row in [
"| `xinput1_4.dll` |",
"| `vcruntime140.dll` |",
"| `ws2_32.dll` |",
] {
assert!(first.contains(row), "{row}");
}
}
#[test]
fn coverage_rejects_unknown_arguments() {
let status = Command::new(env!("CARGO_BIN_EXE_xenora"))
.args(["imports", "coverage", "--bogus"])
.status()
.unwrap();
assert_eq!(status.code(), Some(2));
}
+323 -153
View File
@@ -88,6 +88,13 @@ impl SymbolDb {
entries
}
/// Add or replace one classification, for a project-specific module the
/// built-in database does not describe. `module` is matched
/// case-insensitively, like [`SymbolDb::get`].
pub fn insert(&mut self, module: &str, symbol: &str, classification: Classification) {
self.ins(module, symbol, classification);
}
/// Build the built-in database. Every entry here is derived exclusively from
/// public Microsoft documentation and ISO/POSIX standards.
pub fn builtin() -> Self {
@@ -111,6 +118,7 @@ impl SymbolDb {
db.populate_win32_profile();
db.populate_win32_sysinfo();
db.populate_win32_file();
db.populate_registered_services();
db.populate_unsupported();
db
}
@@ -215,60 +223,37 @@ impl SymbolDb {
for module in [m, "ucrtbase.dll"] {
for symbol in [
"strlen", "strnlen", "strcmp", "strncmp", "wcslen", "wcsnlen", "wcscmp", "wcsncmp",
"memset", "memcpy", "memmove", "memcmp",
"memset", "memcpy", "memmove", "memcmp", "memchr", "strcpy", "strncpy", "strcat",
"strncat", "strstr", "wcsstr", "strspn", "strcspn", "strtok", "strtok_s",
"strpbrk", "wcsspn", "wcscspn", "wcspbrk", "wcstok", "wcstok_s", "wcscpy",
"wcsncpy", "wcscat", "wcschr", "wcsrchr", "isalnum", "isalpha", "isdigit",
"islower", "isspace", "isxdigit", "isupper", "isprint", "iscntrl", "ispunct",
"tolower", "toupper",
] {
self.ins(module, symbol, Classification::StandardService);
}
}
for (sym, libc) in &[
("isalnum", "isalnum"),
("isalpha", "isalpha"),
("isdigit", "isdigit"),
("islower", "islower"),
("isspace", "isspace"),
("isxdigit", "isxdigit"),
("isupper", "isupper"),
("isprint", "isprint"),
("iscntrl", "iscntrl"),
("ispunct", "ispunct"),
("tolower", "tolower"),
("toupper", "toupper"),
("memchr", "memchr"),
("strcat", "strcat"),
("strcpy", "strcpy"),
("strcspn", "strcspn"),
("strncat", "strncat"),
("strncpy", "strncpy"),
("strpbrk", "strpbrk"),
("strspn", "strspn"),
("strstr", "strstr"),
("strtok", "strtok"),
("wcscat", "wcscat"),
("wcscpy", "wcscpy"),
("wcsncpy", "wcsncpy"),
("wcsstr", "wcsstr"),
("wcstok", "wcstok"),
("wcsspn", "wcsspn"),
("wcscspn", "wcscspn"),
("wcsrchr", "wcsrchr"),
("wcschr", "wcschr"),
("wcsicmp", "wcscasecmp"),
] {
self.crt_native(m, sym, libc, "ISO C / POSIX — identical ABI on macOS");
}
// Safe-CRT variants — wrappers that ignore the buffer size (safe on our sandbox)
for sym in &[
"strcat_s",
"strcpy_s",
"strncpy_s",
"strncat_s",
"wcscpy_s",
"wcscat_s",
] {
self.ins(m, sym, Classification::CrtWrapper {
libc_sym: &sym[..sym.len() - 2], // drop _s
wrapper_note: "Safe-CRT: delegates to libc equivalent, ignoring buffer-size arg",
});
self.crt_native(
m,
"wcsicmp",
"wcscasecmp",
"Legacy wide comparison candidate",
);
// Bounds-checked copies are runtime services: mapping them to the
// unchecked libc functions would drop the size check they exist for.
for module in [m, "ucrtbase.dll"] {
for symbol in [
"strcat_s",
"strcpy_s",
"strncpy_s",
"strncat_s",
"wcscpy_s",
"wcscat_s",
"wcsncpy_s",
"wcsncat_s",
] {
self.ins(module, symbol, Classification::StandardService);
}
}
self.win32_stub(
m,
@@ -296,34 +281,44 @@ impl SymbolDb {
fn populate_crt_stdio(&mut self) {
let m = "api-ms-win-crt-stdio-l1-1-0.dll";
for module in [m, "ucrtbase.dll"] {
for symbol in [
"sprintf",
"snprintf",
"fopen",
"fclose",
"fread",
"fwrite",
"fseek",
"ftell",
"feof",
"ferror",
"rewind",
"__acrt_iob_func",
"fprintf",
"printf",
"fputc",
"putc",
"fputs",
"puts",
"fgetc",
"getc",
"fflush",
"ungetc",
"fgets",
] {
self.ins(module, symbol, Classification::StandardService);
}
}
for (sym, libc) in &[
("fclose", "fclose"),
("fflush", "fflush"),
("fgetc", "fgetc"),
("fgetpos", "fgetpos"),
("fopen", "fopen"),
("fputc", "fputc"),
("fputs", "fputs"),
("fread", "fread"),
("fseek", "fseek"),
("fsetpos", "fsetpos"),
("ftell", "ftell"),
("fwrite", "fwrite"),
("getc", "getc"),
("putc", "putc"),
("puts", "puts"),
("rewind", "rewind"),
("remove", "remove"),
("rename", "rename"),
("setvbuf", "setvbuf"),
("ungetc", "ungetc"),
("vsprintf", "vsprintf"),
("vsnprintf", "vsnprintf"),
("vfprintf", "vfprintf"),
("sprintf", "sprintf"),
("snprintf", "snprintf"),
("fprintf", "fprintf"),
("printf", "printf"),
("sscanf", "sscanf"),
("fscanf", "fscanf"),
("scanf", "scanf"),
@@ -342,7 +337,6 @@ impl SymbolDb {
"__stdio_common_vswprintf_s",
"__stdio_common_vswscanf",
"__stdio_common_vsnwprintf_s",
"__acrt_iob_func",
] {
self.win32_stub(
m,
@@ -378,9 +372,7 @@ impl SymbolDb {
fn populate_crt_runtime(&mut self) {
let m = "api-ms-win-crt-runtime-l1-1-0.dll";
for (sym, libc) in &[
("abort", "abort"),
("exit", "exit"),
("_exit", "_exit"),
("rand", "rand"),
("srand", "srand"),
("atoi", "atoi"),
@@ -390,7 +382,11 @@ impl SymbolDb {
self.crt_native(m, sym, libc, "ISO C runtime — identical ABI on macOS");
}
for module in [m, "ucrtbase.dll"] {
for symbol in ["_errno", "_get_errno", "_set_errno"] {
for symbol in ["_errno", "_get_errno", "_set_errno", "getenv"] {
self.ins(module, symbol, Classification::StandardService);
}
// Abnormal termination ends the guest process, never the host.
for symbol in ["abort", "_exit", "terminate", "_purecall"] {
self.ins(module, symbol, Classification::StandardService);
}
}
@@ -421,7 +417,6 @@ impl SymbolDb {
false,
"CRT invalid param abort",
);
self.win32_stub(m, "_purecall", false, "pure virtual call trap");
// Initializer and exit functions are guest code.
for module in [m, "ucrtbase.dll"] {
for symbol in [
@@ -468,7 +463,6 @@ impl SymbolDb {
);
self.win32_stub(m, "__p___argv", false, "argv pointer — returns null");
self.win32_stub(m, "__p__commode", false, "_commode pointer — stub");
self.win32_stub(m, "terminate", false, "C++ terminate — calls abort");
self.win32_stub(
m,
"__std_terminate",
@@ -495,7 +489,18 @@ impl SymbolDb {
fn populate_crt_heap(&mut self) {
let m = "api-ms-win-crt-heap-l1-1-0.dll";
for module in [m, "ucrtbase.dll"] {
for symbol in ["malloc", "free", "calloc", "realloc"] {
for symbol in [
"malloc",
"free",
"calloc",
"realloc",
"_msize",
"_recalloc",
"_aligned_malloc",
"_aligned_realloc",
"_aligned_msize",
"_aligned_free",
] {
self.ins(module, symbol, Classification::StandardService);
}
}
@@ -540,11 +545,8 @@ impl SymbolDb {
}
}
for (sym, libc) in &[
("strtod", "strtod"),
("strtof", "strtof"),
("mbstowcs", "mbstowcs"),
("wcstombs", "wcstombs"),
("wcstod", "wcstod"),
("wctob", "wctob"),
("btowc", "btowc"),
] {
@@ -554,21 +556,25 @@ impl SymbolDb {
self.win32_stub(m, "_itoa_s", false, "Windows itoa_s — safe variant");
self.win32_stub(m, "_wtoi", false, "Wide char to int");
self.win32_stub(m, "_wtol", false, "Wide char to long");
self.win32_stub(m, "_wtof", false, "Wide char to float");
self.win32_stub(m, "atof", false, "atof ISO C — maps to libc");
// Note: atof already in runtime; just stub if it appears here too
// Floating conversions return in XMM0 and parse in the "C" locale.
for module in [m, "ucrtbase.dll"] {
for symbol in ["strtod", "strtof", "wcstod", "wcstof", "atof", "_wtof"] {
self.ins(module, symbol, Classification::StandardService);
}
}
}
// ---- api-ms-win-crt-utility --------------------------------------------
fn populate_crt_utility(&mut self) {
let m = "api-ms-win-crt-utility-l1-1-0.dll";
self.crt_native(m, "abs", "abs", "ISO C abs");
self.crt_native(m, "labs", "labs", "ISO C labs");
self.crt_native(m, "llabs", "llabs", "ISO C llabs");
self.crt_native(m, "div", "div", "ISO C div");
self.crt_native(m, "ldiv", "ldiv", "ISO C ldiv");
self.crt_native(m, "lldiv", "lldiv", "ISO C lldiv");
// Windows long is 32 bits and lldiv_t returns through a hidden
// pointer, so these cannot map to the LP64 host libc.
for module in [m, "ucrtbase.dll"] {
for symbol in ["abs", "labs", "llabs", "div", "ldiv", "lldiv"] {
self.ins(module, symbol, Classification::StandardService);
}
}
// The comparators are guest code, so these cannot use host libc.
for module in [m, "ucrtbase.dll"] {
for symbol in ["qsort", "qsort_s", "bsearch", "bsearch_s"] {
@@ -599,13 +605,11 @@ impl SymbolDb {
fn populate_crt_locale(&mut self) {
let m = "api-ms-win-crt-locale-l1-1-0.dll";
self.crt_native(m, "localeconv", "localeconv", "ISO C localeconv");
self.win32_stub(
m,
"setlocale",
false,
"Windows setlocale — stub returning 'C'",
);
for module in [m, "ucrtbase.dll"] {
for symbol in ["setlocale", "localeconv"] {
self.ins(module, symbol, Classification::StandardService);
}
}
self.win32_stub(
m,
"_create_locale",
@@ -621,6 +625,143 @@ impl SymbolDb {
);
}
// ---- Services the loader registry provides ------------------------------
/// Standard services registered by `crates/loader/src/services` that no
/// other table classifies. Synthetic fixture modules are left out.
fn populate_registered_services(&mut self) {
for (module, symbols) in [
(
"api-ms-win-core-processthreads-l1-1-0.dll",
&["IsProcessorFeaturePresent"][..],
),
(
"api-ms-win-core-timezone-l1-1-0.dll",
&["GetTimeZoneInformation"][..],
),
(
"api-ms-win-core-sysinfo-l1-1-0.dll",
&["GetLogicalProcessorInformation"][..],
),
(
"kernel32.dll",
&[
"IsProcessorFeaturePresent",
"GetTimeZoneInformation",
"GetLogicalProcessorInformation",
"CloseHandle",
"FreeLibrary",
"GetCurrentDirectoryA",
"GetCurrentDirectoryW",
"GetLastError",
"GetModuleFileNameA",
"GetModuleFileNameW",
"GetProcessId",
"GetProcessPriorityBoost",
"LoadLibraryA",
"LoadLibraryW",
"OpenThread",
"SetCurrentDirectoryA",
"SetCurrentDirectoryW",
"SetEnvironmentVariableA",
"SetEnvironmentVariableW",
"SetLastError",
"SetProcessPriorityBoost",
"VirtualAlloc",
"VirtualFree",
][..],
),
(
"ucrtbase.dll",
&[
"_atoi64",
"_gmtime64_s",
"_localtime64_s",
"_putenv",
"_stricmp",
"_strnicmp",
"_time64",
"_wcsicmp",
"_wcsnicmp",
"_wtoi",
"_wtoi64",
"_wtol",
"atoi",
"atol",
"atoll",
"gmtime_s",
"localtime_s",
"rand",
"rand_s",
"srand",
"time",
][..],
),
(
"ws2_32.dll",
&[
"WSACleanup",
"WSAGetLastError",
"WSAPoll",
"WSASetLastError",
"WSAStartup",
"accept",
"bind",
"closesocket",
"connect",
"getpeername",
"getsockname",
"getsockopt",
"htonl",
"htons",
"inet_ntop",
"inet_pton",
"ioctlsocket",
"listen",
"ntohl",
"ntohs",
"recv",
"recvfrom",
"send",
"sendto",
"shutdown",
"socket",
][..],
),
(
"xgameruntime.dll",
&[
"XAsyncCancel",
"XAsyncGetResultSize",
"XAsyncGetStatus",
"XAsyncRun",
"XTaskQueueCloseHandle",
"XTaskQueueCreate",
"XTaskQueueCreateComposite",
"XTaskQueueDispatch",
"XTaskQueueDuplicateHandle",
"XTaskQueueGetPort",
"XTaskQueueSubmitCallback",
"XTaskQueueSubmitDelayedCallback",
"XTaskQueueTerminate",
][..],
),
(
"xinput1_4.dll",
&[
"XInputEnable",
"XInputGetCapabilities",
"XInputGetState",
"XInputSetState",
][..],
),
] {
for symbol in symbols {
self.ins(module, symbol, Classification::StandardService);
}
}
}
// ---- VCRUNTIME140 / VCRUNTIME140_1 -------------------------------------
fn populate_vcruntime(&mut self) {
@@ -652,18 +793,33 @@ impl SymbolDb {
"__current_exception_context",
"current exception context — stub",
);
self.runtime_helper(m, "__std_exception_copy", "std::exception copy — stub");
self.runtime_helper(
m,
"__std_exception_destroy",
"std::exception destroy — stub",
);
self.runtime_helper(m, "__std_terminate", "std::terminate — calls abort");
self.runtime_helper(
m,
"__std_type_info_compare",
"type_info comparison — stub returning -1",
);
if *m == "vcruntime140.dll" {
for symbol in [
"__std_type_info_compare",
"__std_type_info_hash",
"__std_type_info_name",
"__std_type_info_destroy_list",
"__std_exception_copy",
"__std_exception_destroy",
"__std_terminate",
"_purecall",
] {
self.ins(m, symbol, Classification::StandardService);
}
} else {
self.runtime_helper(
m,
"__std_type_info_compare",
"type_info comparison — stub returning -1",
);
self.runtime_helper(m, "__std_exception_copy", "std::exception copy — stub");
self.runtime_helper(
m,
"__std_exception_destroy",
"std::exception destroy — stub",
);
}
self.runtime_helper(m, "memcpy", "CRT memcpy delegate — same as libc");
self.runtime_helper(m, "memset", "CRT memset delegate — same as libc");
self.runtime_helper(m, "memmove", "CRT memmove delegate — same as libc");
@@ -716,36 +872,48 @@ impl SymbolDb {
"TerminateProcess — calls exit(1)",
);
self.win32_stub(m, "GetStartupInfoW", false, "GetStartupInfoW — fills zeros");
self.win32_stub(
m,
"GetCurrentThreadId",
false,
"returns synthetic thread ID",
);
self.win32_stub(
m,
"GetCurrentProcessId",
false,
"returns synthetic process ID",
);
self.win32_stub(m, "GetCurrentThread", false, "returns pseudo-handle");
self.win32_stub(m, "GetCurrentProcess", false, "returns pseudo-handle -1");
self.win32_stub(
m,
"SetThreadPriority",
false,
"no-op in single-thread context",
);
self.win32_stub(
m,
"GetThreadPriority",
false,
"returns THREAD_PRIORITY_NORMAL",
);
// Typed services in crates/loader/runtime/services.txt, which
// does not list the l1-1-2 API set for them.
for (symbol, note) in [
("GetCurrentThreadId", "returns synthetic thread ID"),
("GetCurrentProcessId", "returns synthetic process ID"),
("GetCurrentThread", "returns pseudo-handle"),
("GetCurrentProcess", "returns pseudo-handle -1"),
("SetThreadPriority", "no-op in single-thread context"),
("GetThreadPriority", "returns THREAD_PRIORITY_NORMAL"),
] {
if *m == p2 {
self.win32_stub(m, symbol, false, note);
} else {
self.ins(m, symbol, Classification::StandardService);
}
}
self.win32_stub(m, "Sleep", false, "Sleep — no-op (single-threaded)");
self.win32_stub(m, "ExitProcess", false, "ExitProcess — calls exit(0)");
self.win32_stub(
m,
"ExitProcess",
false,
"ExitProcess — not registered on this API set",
);
self.win32_stub(m, "ExitThread", false, "ExitThread — calls exit(0)");
}
// The guest thread scheduler provides these on kernel32 and the
// l1-1-0 API set only; l1-1-2 keeps its stub classification.
for module in [p1, "kernel32.dll"] {
for symbol in [
"CreateThread",
"ExitThread",
"TerminateThread",
"GetExitCodeThread",
"SuspendThread",
"ResumeThread",
"SwitchToThread",
// Process exit (#331) ends the guest, never the host.
"ExitProcess",
] {
self.ins(module, symbol, Classification::StandardService);
}
}
let err = "api-ms-win-core-errorhandling-l1-1-0.dll";
self.win32_stub(err, "GetLastError", false, "returns last_error from TEB");
self.win32_stub(err, "SetLastError", false, "sets last_error in TEB");
@@ -924,6 +1092,14 @@ impl SymbolDb {
self.ins(module, symbol, Classification::StandardService);
}
}
for module in [
"kernel32.dll",
"api-ms-win-core-processenvironment-l1-1-0.dll",
] {
for symbol in ["GetEnvironmentVariableA", "GetEnvironmentVariableW"] {
self.ins(module, symbol, Classification::StandardService);
}
}
}
// ---- Win32 system info -------------------------------------------------
@@ -993,25 +1169,33 @@ impl SymbolDb {
fn populate_win32_file(&mut self) {
let m = "api-ms-win-core-file-l1-1-0.dll";
self.win32_stub(
m,
"CreateFileA",
false,
"CreateFile — stub returning INVALID_HANDLE_VALUE",
);
for module in [m, "kernel32.dll"] {
for symbol in [
"CreateFileA",
"CreateFileW",
"ReadFile",
"WriteFile",
"GetFileSize",
"GetFileSizeEx",
"GetFileType",
"GetFileTime",
"SetFileTime",
"FlushFileBuffers",
"SetFilePointerEx",
"SetEndOfFile",
"CreateDirectoryW",
"RemoveDirectoryW",
"DeleteFileA",
"DeleteFileW",
"GetFileAttributesA",
"GetFileAttributesW",
"GetFileAttributesExA",
"GetFileAttributesExW",
"GetTempPathA",
"GetTempPathW",
"GetTempFileNameW",
"MoveFileW",
"MoveFileExW",
"FindFirstFileW",
"FindNextFileW",
"FindClose",
@@ -1020,20 +1204,6 @@ impl SymbolDb {
}
}
self.win32_stub(m, "CloseHandle", false, "CloseHandle — no-op stub");
self.win32_stub(m, "GetFileSize", false, "GetFileSize — stub returning 0");
self.win32_stub(
m,
"GetFileAttributesA",
false,
"GetFileAttributes — stub returning INVALID",
);
self.win32_stub(m, "DeleteFileA", false, "DeleteFile — stub returning FALSE");
self.win32_stub(
m,
"FlushFileBuffers",
false,
"FlushFileBuffers — no-op stub",
);
}
// ---- Proprietary / unavailable -----------------------------------------
+2 -1
View File
@@ -342,8 +342,9 @@ fn symbol_to_ident_lower(sym: &str) -> String {
pub(crate) fn crt_dispatch_expr(symbol: &str) -> Option<String> {
Some(match symbol {
// abs(int) -> int
// Windows long is 32 bits. The minimum wraps, as x86 neg does.
"abs" | "labs" => r#"let x = args.rcx as i32;
Ok(x.abs() as u64)"#
Ok(u64::from(x.wrapping_abs() as u32))"#
.to_string(),
"llabs" => r#"let x = args.rcx as i64;
Ok(x.unsigned_abs())"#
+96
View File
@@ -257,6 +257,102 @@ impl MetadataCatalog {
"<wchar.h>",
"Compares up to count 16-bit Windows code units of two strings",
);
for (character, string, header, tokenize, search, find_any, span, complement) in [
(
"char",
AbiType::StringAnsi,
"<string.h>",
"strtok",
"strstr",
"strpbrk",
"strspn",
"strcspn",
),
(
"wchar_t",
AbiType::StringWide,
"<wchar.h>",
"wcstok",
"wcsstr",
"wcspbrk",
"wcsspn",
"wcscspn",
),
] {
let pointer = AbiType::Pointer {
is_const: false,
pointee: character.into(),
};
let mut params = vec![("str", pointer.clone()), ("delimiters", string.clone())];
if tokenize == "wcstok" {
params.push((
"context",
AbiType::Pointer {
is_const: false,
pointee: "wchar_t *".into(),
},
));
}
self.add(
"ucrtbase.dll",
tokenize,
pointer.clone(),
params,
header,
"Splits writable guest text into tokens",
);
self.add(
"ucrtbase.dll",
&format!("{tokenize}_s"),
pointer.clone(),
vec![
("str", pointer.clone()),
("delimiters", string.clone()),
(
"context",
AbiType::Pointer {
is_const: false,
pointee: format!("{character} *"),
},
),
],
header,
"Splits writable guest text using a caller-owned continuation pointer",
);
for (symbol, argument, description) in [
(search, "needle", "Finds the first matching substring"),
(
find_any,
"accept",
"Finds the first character in the supplied set",
),
] {
self.add(
"ucrtbase.dll",
symbol,
pointer.clone(),
vec![("str", string.clone()), (argument, string.clone())],
header,
description,
);
}
for (symbol, description) in [
(span, "Counts the leading units in the supplied set"),
(
complement,
"Counts the leading units outside the supplied set",
),
] {
self.add(
"ucrtbase.dll",
symbol,
AbiType::U64,
vec![("str", string.clone()), ("set", string.clone())],
header,
description,
);
}
}
self.add(
"ucrtbase.dll",
"memset",
+60 -10
View File
@@ -18,11 +18,22 @@ fn test_builtin_db_classifies_crt_string() {
let strlen_cls = db.get("api-ms-win-crt-string-l1-1-0.dll", "strlen");
assert!(matches!(strlen_cls, Some(Classification::StandardService)));
let strcat_s_cls = db.get("api-ms-win-crt-string-l1-1-0.dll", "strcat_s");
assert!(matches!(
strcat_s_cls,
Some(Classification::CrtWrapper { .. })
db.get("api-ms-win-crt-string-l1-1-0.dll", "strtok"),
Some(Classification::StandardService)
));
// Bounds-checked copies must reach the runtime service, never an
// unchecked libc wrapper that ignores the destination size.
for symbol in ["strcat_s", "strcpy_s", "strncpy_s", "wcscpy_s"] {
assert!(
matches!(
db.get("api-ms-win-crt-string-l1-1-0.dll", symbol),
Some(Classification::StandardService)
),
"{symbol}"
);
}
}
#[test]
@@ -71,9 +82,9 @@ fn typed_csv_preserves_ordinals_and_identically_spelled_names() {
fn test_manifest_and_codegen_pipeline() {
let csv_content = r#""module","symbol_or_ordinal","iat_rva"
"api-ms-win-crt-math-l1-1-0.dll","acos",0x1000
"api-ms-win-crt-string-l1-1-0.dll","tolower",0x1008
"API-MS-WIN-CRT-STRING-L1-1-0.DLL","tolower",0x1048
"api-ms-win-core-processthreads-l1-1-0.dll","CreateThread",0x1010
"custom-crt.dll","toupper",0x1008
"CUSTOM-CRT.DLL","toupper",0x1048
"api-ms-win-core-processthreads-l1-1-2.dll","CreateThread",0x1010
"custom.dll","UnknownCustomFunc",0x1018
"kernel32.dll","QueryPerformanceCounter",0x1020
"api-ms-win-core-profile-l1-1-0.dll","QueryPerformanceFrequency",0x1028
@@ -90,7 +101,18 @@ fn test_manifest_and_codegen_pipeline() {
let records = parse_csv(csv_file.to_str().unwrap()).unwrap();
assert_eq!(records.len(), 10);
let db = SymbolDb::builtin();
// Every built-in symbol with a generated adapter is now a runtime
// service, so the adapter path is exercised through a project-specific
// module classified as native.
let mut db = SymbolDb::builtin();
db.insert(
"custom-crt.dll",
"toupper",
Classification::CrtNative {
libc_sym: "toupper",
note: "test-only native mapping",
},
);
let manifest = Manifest::build(&records, &db);
let summary = manifest.summary();
@@ -113,7 +135,7 @@ fn test_manifest_and_codegen_pipeline() {
let files = generate(&manifest, &db);
assert!(files.crt_rs.contains("register_generated_crt_services"));
assert_eq!(files.crt_rs.matches("\"tolower\"").count(), 1);
assert_eq!(files.crt_rs.matches("\"toupper\"").count(), 1);
let acos = files.crt_rs.split_once("\"acos\"").unwrap().1;
let acos = acos.split("registry.register_with_status").next().unwrap();
assert!(acos.contains("ServiceStatus::Stub"));
@@ -131,7 +153,7 @@ fn test_manifest_and_codegen_pipeline() {
assert!(!files.stubs_rs.contains("GetThreadId"));
assert!(!files.stubs_rs.contains("DuplicateHandle"));
assert!(!files.stubs_rs.contains("GetTickCount64"));
assert!(files.tests_rs.contains("generated_test_tolower"));
assert!(files.tests_rs.contains("generated_test_toupper"));
let out_dir = tmp_dir.join("out");
files.write_all(out_dir.to_str().unwrap()).unwrap();
@@ -147,6 +169,10 @@ fn test_catalog_describes_windows_wide_string_signatures() {
let catalog = MetadataCatalog::builtin();
let wide = AbiType::StringWide;
let wide_pointer = AbiType::Pointer {
is_const: false,
pointee: "wchar_t".into(),
};
for (symbol, return_type, parameters) in [
("wcslen", AbiType::U64, vec![wide.clone()]),
("wcsnlen", AbiType::U64, vec![wide.clone(), AbiType::U64]),
@@ -154,7 +180,31 @@ fn test_catalog_describes_windows_wide_string_signatures() {
(
"wcsncmp",
AbiType::I32,
vec![wide.clone(), wide, AbiType::U64],
vec![wide.clone(), wide.clone(), AbiType::U64],
),
(
"wcsstr",
wide_pointer.clone(),
vec![wide.clone(), wide.clone()],
),
(
"wcspbrk",
wide_pointer.clone(),
vec![wide.clone(), wide.clone()],
),
("wcsspn", AbiType::U64, vec![wide.clone(), wide.clone()]),
("wcscspn", AbiType::U64, vec![wide.clone(), wide.clone()]),
(
"wcstok",
wide_pointer.clone(),
vec![
wide_pointer,
wide,
AbiType::Pointer {
is_const: false,
pointee: "wchar_t *".into(),
},
],
),
] {
let signature = catalog.lookup("ucrtbase.dll", symbol).unwrap();
+4 -1
View File
@@ -219,6 +219,9 @@ pub(crate) struct GuestCallback {
pub(crate) entry: u64,
pub(crate) context: u64,
pub(crate) cancelled: bool,
/// Optional host continuation after the guest callback returns. Used by
/// queued `XAsyncRun` so work can update status and schedule completion.
pub(crate) task: Option<Arc<Mutex<Box<dyn CallbackTask>>>>,
}
type CallbackDispatch = Box<
@@ -781,7 +784,7 @@ impl ImportRegistry {
CallbackFrame {
resume: ret_addr,
preserved,
task: None,
task: callback.task,
after,
},
);
+1
View File
@@ -126,6 +126,7 @@ pub struct GuestMemory {
private_heap_serial: u64,
// Stable errno pointers indexed by the guest thread's TEB address.
crt_errno: std::collections::BTreeMap<u64, u64>,
pub(crate) crt_token_cursors: std::collections::BTreeMap<u64, u64>,
pub(crate) callback_frames:
std::collections::BTreeMap<(u64, u64), crate::imports::CallbackFrame>,
}
+75 -3
View File
@@ -11,10 +11,23 @@
mod crt;
mod crt_callbacks;
mod crt_ctype;
mod crt_env;
mod crt_exit;
mod crt_float;
mod crt_heap;
mod crt_integer;
mod crt_locale;
mod crt_safe_string;
mod crt_stdio;
mod crt_time;
mod cxx;
mod events;
mod files;
mod gdk_async;
mod gdk_queue;
mod heap;
pub mod host_files;
mod modules;
mod platform_fixture;
mod process;
@@ -23,6 +36,7 @@ pub mod sysinfo;
mod task_fixture;
pub(crate) mod threads;
mod winsock;
pub mod xinput;
use crate::runtime::HResult;
@@ -30,7 +44,7 @@ use crate::cpu::ExitReason;
use crate::imports::{ImportRegistry, ServiceStatus};
use crate::memory::{ALLOCATION_GRANULARITY, GuestMemory, MemoryError, MemoryPermissions};
use std::collections::{BTreeMap, BTreeSet};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, OnceLock};
use std::time::Instant;
@@ -160,8 +174,9 @@ struct ObjectState {
priority: i32,
last_handle: u64,
handles: BTreeMap<u64, GuestObject>,
files: BTreeMap<String, Vec<u8>>,
files: BTreeMap<String, files::SyntheticFile>,
directories: BTreeSet<String>,
current_directory: String,
}
impl ObjectState {
@@ -198,6 +213,8 @@ pub struct ServicesState {
/// Characteristics the guest is told it runs on. These are simulated and
/// independent of the host; see [`sysinfo::HostCapabilities`] for the host.
pub guest_profile: sysinfo::GuestSystemProfile,
/// Host directories exposed as guest drives; see [`ServicesState::mount`].
mounts: Vec<host_files::HostMount>,
objects: Mutex<ObjectState>,
last_errors: Mutex<BTreeMap<u64, u32>>,
synch: Mutex<synch::Synch>,
@@ -208,10 +225,21 @@ pub struct ServicesState {
/// The status the guest process exited with. Set once.
exit_status: Mutex<Option<u32>>,
winsock: Mutex<winsock::Winsock>,
/// Where XInput readings come from; see [`ServicesState::set_controllers`].
controllers: Arc<dyn xinput::ControllerSource>,
xinput: Mutex<xinput::XInput>,
type_names: Arc<Mutex<cxx::TypeNames>>,
aligned: Mutex<crt_heap::AlignedBlocks>,
task_fixture: Mutex<task_fixture::TaskFixture>,
platform_fixture: Mutex<platform_fixture::PlatformFixture>,
gdk_queues: Mutex<gdk_queue::QueueHandles>,
gdk_queue_changed: Condvar,
gdk_async: Arc<Mutex<gdk_async::AsyncOps>>,
locale: Mutex<crt_locale::LocaleState>,
stdio: Mutex<crt_stdio::StdioState>,
env: Mutex<crt_env::EnvState>,
/// Seed for the CRT `rand` / `srand` LCG (process-wide, like UCRT).
crt_rand: AtomicU32,
winsock_changed: Condvar,
pub next_alloc_addr: AtomicU64,
pub graphics: Arc<Mutex<crate::graphics::GraphicsContext>>,
@@ -226,6 +254,7 @@ impl ServicesState {
process_id: 0x4100, // Synthetic process ID
thread_id: 0x4104, // Synthetic main thread ID
guest_profile: sysinfo::GuestSystemProfile::default(),
mounts: Vec::new(),
objects: Mutex::new(ObjectState::default()),
last_errors: Mutex::default(),
synch: Mutex::default(),
@@ -234,15 +263,44 @@ impl ServicesState {
atexit: Mutex::default(),
exit_status: Mutex::default(),
winsock: Mutex::default(),
controllers: Arc::new(xinput::NoControllers),
xinput: Mutex::default(),
type_names: Arc::default(),
aligned: Mutex::default(),
task_fixture: Mutex::default(),
platform_fixture: Mutex::default(),
gdk_queues: Mutex::default(),
gdk_queue_changed: Condvar::new(),
gdk_async: Arc::new(Mutex::default()),
locale: Mutex::default(),
stdio: Mutex::default(),
env: Mutex::default(),
crt_rand: AtomicU32::new(1),
winsock_changed: Condvar::new(),
next_alloc_addr: AtomicU64::new(0x0000_0002_0000_0000), // 8GB guest heap
graphics: Arc::new(Mutex::new(crate::graphics::GraphicsContext::new())),
}
}
/// Connect a controller source to XInput. Without one, every slot reports
/// that no controller is connected.
pub fn set_controllers(&mut self, source: Arc<dyn xinput::ControllerSource>) {
self.controllers = source;
}
/// Expose a host directory to the guest. Each drive letter can be mounted
/// once. Nothing on the host is reachable unless it is mounted here.
pub fn mount(&mut self, mount: host_files::HostMount) -> Result<(), host_files::HostMount> {
if self
.mounts
.iter()
.any(|existing| existing.drive() == mount.drive())
{
return Err(mount);
}
self.mounts.push(mount);
Ok(())
}
fn uptime_millis(&self) -> u64 {
let ticks = self
.clock
@@ -292,7 +350,7 @@ impl ServicesState {
.expect("guest object state")
.files
.get(name)
.cloned()
.map(|file| file.data().to_vec())
}
/// End the guest process. The first exit decides the status; a later one
@@ -481,8 +539,16 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
files::register(registry, &state);
crt::register(registry);
crt::register_heap(registry);
crt_heap::register(registry, &state);
crt_safe_string::register(registry, &state);
crt::register_errno(registry);
crt::register_conversions(registry);
crt::register_rand(registry, &state);
crt_locale::register(registry, &state);
crt_ctype::register(registry);
crt_stdio::register(registry, &state);
crt_env::register(registry, &state);
crt_time::register(registry, &state);
crt_callbacks::register(registry, &state);
heap::register(registry, &state);
@@ -706,11 +772,17 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
ServiceStatus::Implemented,
);
winsock::register(registry, &state);
xinput::register(registry, &state);
cxx::register(registry, &state);
task_fixture::register(registry, &state);
platform_fixture::register(registry, &state);
gdk_queue::register(registry, &state);
gdk_async::register(registry, &state);
modules::register(registry, &state);
process::register(registry, &state);
crt_exit::register(registry, &state);
crt_integer::register(registry);
crt_float::register(registry);
}
/// Implementations behind the generated adapters. A failure the guest can
+870 -4
View File
@@ -2,9 +2,12 @@
//! C runtime services that operate on checked guest memory.
use super::ServicesState;
use crate::cpu::ExitReason;
use crate::imports::{ImportRegistry, ServiceStatus, Win64Args};
use crate::memory::{GuestMemory, MemoryError, PROCESS_HEAP};
use std::sync::Arc;
use std::sync::atomic::Ordering;
const SCAN_BUDGET: u64 = 1_048_576;
const UCRT: &str = "ucrtbase.dll";
@@ -84,17 +87,30 @@ fn string_length(
Err(ExitReason::IllegalInstruction(0xFE))
}
fn fold_ascii(unit: u16) -> u16 {
if (b'A' as u16..=b'Z' as u16).contains(&unit) {
unit + 32
} else {
unit
}
}
fn compare_strings(
memory: &GuestMemory,
left: u64,
right: u64,
limit: u64,
unit: StringUnit,
case_insensitive: bool,
) -> Result<u64, ExitReason> {
let budget = SCAN_BUDGET / unit.width();
for offset in 0..limit.min(budget) {
let a = unit.read(memory, left, offset)?;
let b = unit.read(memory, right, offset)?;
let mut a = unit.read(memory, left, offset)?;
let mut b = unit.read(memory, right, offset)?;
if case_insensitive {
a = fold_ascii(a);
b = fold_ascii(b);
}
if a != b || a == 0 {
return Ok(u64::from((i32::from(a) - i32::from(b)) as u32));
}
@@ -130,10 +146,10 @@ pub(super) fn register(registry: &mut ImportRegistry) {
string_length(memory, args.rcx, args.rdx, unit)
});
registry.register(UCRT, compare, move |args, _, memory| {
compare_strings(memory, args.rcx, args.rdx, u64::MAX, unit)
compare_strings(memory, args.rcx, args.rdx, u64::MAX, unit, false)
});
registry.register(UCRT, bounded_compare, move |args, _, memory| {
compare_strings(memory, args.rcx, args.rdx, args.r8, unit)
compare_strings(memory, args.rcx, args.rdx, args.r8, unit, false)
});
for symbol in [length, bounded_length, compare, bounded_compare] {
registry.alias(CRT_STRING_API, UCRT, symbol);
@@ -141,6 +157,21 @@ pub(super) fn register(registry: &mut ImportRegistry) {
}
}
// C-locale ASCII case folding only (not Unicode case mapping).
for (symbol, bounded, unit) in [
("_stricmp", false, StringUnit::Byte),
("_strnicmp", true, StringUnit::Byte),
("_wcsicmp", false, StringUnit::Wide),
("_wcsnicmp", true, StringUnit::Wide),
] {
registry.register(UCRT, symbol, move |args, _, memory| {
let limit = if bounded { args.r8 } else { u64::MAX };
compare_strings(memory, args.rcx, args.rdx, limit, unit, true)
});
registry.alias(CRT_STRING_API, UCRT, symbol);
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
}
registry.register(UCRT, "memset", |args, _, memory| {
if args.r8 != 0 {
let buffer = transfer_buffer(args.r8, args.rdx as u8)?;
@@ -190,6 +221,559 @@ pub(super) fn register(registry: &mut ImportRegistry) {
registry.alias(CRT_STRING_API, UCRT, symbol);
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
}
registry.register(UCRT, "memchr", |args, _, memory| {
if args.r8 == 0 {
return Ok(0);
}
let mut buffer = transfer_buffer(args.r8, 0)?;
memory
.read_bytes(args.rcx, &mut buffer)
.map_err(ExitReason::MemoryFault)?;
Ok(buffer
.iter()
.position(|&byte| byte == args.rdx as u8)
.map_or(0, |index| args.rcx + index as u64))
});
registry.register(UCRT, "strcpy", |args, _, memory| {
copy_string(memory, args.rcx, args.rdx, u64::MAX, true)
});
registry.register(UCRT, "strncpy", |args, _, memory| {
copy_string(memory, args.rcx, args.rdx, args.r8, false)
});
registry.register(UCRT, "strcat", |args, _, memory| {
append_string(memory, args.rcx, args.rdx, u64::MAX)
});
registry.register(UCRT, "strncat", |args, _, memory| {
append_string(memory, args.rcx, args.rdx, args.r8)
});
for (symbol, unit) in [("strstr", StringUnit::Byte), ("wcsstr", StringUnit::Wide)] {
registry.register(UCRT, symbol, move |args, _, memory| {
find_substring(memory, args.rcx, args.rdx, unit)
});
}
registry.register(UCRT, "strspn", |args, _, memory| {
span_length(memory, args.rcx, args.rdx, true)
});
registry.register(UCRT, "strcspn", |args, _, memory| {
span_length(memory, args.rcx, args.rdx, false)
});
registry.register(UCRT, "strpbrk", |args, _, memory| {
let offset = span_length(memory, args.rcx, args.rdx, false)?;
match StringUnit::Byte.read(memory, args.rcx, offset)? {
0 => Ok(0),
_ => Ok(args.rcx + offset),
}
});
for (symbol, accept) in [("wcsspn", true), ("wcscspn", false)] {
registry.register(UCRT, symbol, move |args, _, memory| {
wide_span(memory, args.rcx, args.rdx, accept)
});
}
registry.register(UCRT, "wcspbrk", |args, _, memory| {
let offset = wide_span(memory, args.rcx, args.rdx, false)?;
match StringUnit::Wide.read(memory, args.rcx, offset)? {
0 => Ok(0),
_ => Ok(args.rcx + offset * 2),
}
});
registry.register(UCRT, "strtok", |args, cpu, memory| {
tokenize(memory, cpu.gs_base, args.rcx, args.rdx)
});
for (symbol, unit) in [
("strtok_s", StringUnit::Byte),
("wcstok_s", StringUnit::Wide),
] {
registry.register(UCRT, symbol, move |args, cpu, memory| {
tokenize_s(memory, cpu.gs_base, args.rcx, args.rdx, args.r8, unit)
});
}
registry.register(UCRT, "wcstok", |args, _, memory| {
tokenize_wide(memory, args.rcx, args.rdx, args.r8)
});
registry.register(UCRT, "wcscpy", |args, _, memory| {
copy_wide(memory, args.rcx, args.rdx, u64::MAX, true)
});
registry.register(UCRT, "wcsncpy", |args, _, memory| {
copy_wide(memory, args.rcx, args.rdx, args.r8, false)
});
registry.register(UCRT, "wcscat", |args, _, memory| {
append_wide(memory, args.rcx, args.rdx)
});
registry.register(UCRT, "wcschr", |args, _, memory| {
find_wide(memory, args.rcx, args.rdx as u16, true)
});
registry.register(UCRT, "wcsrchr", |args, _, memory| {
find_wide(memory, args.rcx, args.rdx as u16, false)
});
for symbol in [
"memchr", "strcpy", "strncpy", "strcat", "strncat", "strstr", "wcsstr", "strspn",
"strcspn", "wcscpy", "wcsncpy", "wcscat", "wcschr", "wcsrchr", "strtok", "strpbrk",
"wcsspn", "wcscspn", "wcspbrk", "wcstok", "strtok_s", "wcstok_s",
] {
registry.alias(CRT_STRING_API, UCRT, symbol);
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
}
}
fn find_substring(
memory: &GuestMemory,
haystack: u64,
needle: u64,
unit: StringUnit,
) -> Result<u64, ExitReason> {
if haystack == 0 || needle == 0 {
return Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(0)));
}
let length = string_length(memory, needle, u64::MAX, unit)?;
if length == 0 {
return Ok(haystack);
}
let pattern = (0..length)
.map(|offset| unit.read(memory, needle, offset))
.collect::<Result<Vec<_>, _>>()?;
// Prefix lengths avoid rescanning repeated substrings in guest memory.
let mut prefix = vec![0usize; pattern.len()];
for index in 1..pattern.len() {
let mut matched = prefix[index - 1];
while matched != 0 && pattern[index] != pattern[matched] {
matched = prefix[matched - 1];
}
prefix[index] = matched + usize::from(pattern[index] == pattern[matched]);
}
let mut matched = 0;
for offset in 0..(SCAN_BUDGET / unit.width()) {
let current = unit.read(memory, haystack, offset)?;
if current == 0 {
return Ok(0);
}
while matched != 0 && current != pattern[matched] {
matched = prefix[matched - 1];
}
if current == pattern[matched] {
matched += 1;
if matched == pattern.len() {
return Ok(haystack + (offset + 1 - length) * unit.width());
}
}
}
Err(ExitReason::IllegalInstruction(0xFE))
}
fn copy_wide(
memory: &mut GuestMemory,
dest: u64,
source: u64,
limit: u64,
always_terminate: bool,
) -> Result<u64, ExitReason> {
if dest == 0 || source == 0 {
return Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(0)));
}
if limit == 0 {
return Ok(dest);
}
let mut words = Vec::new();
let scan = limit.min(SCAN_BUDGET / 2);
for index in 0..scan {
let word = memory
.read_u16(source + index * 2)
.map_err(ExitReason::MemoryFault)?;
words.push(word);
if word == 0 {
break;
}
if !always_terminate && words.len() as u64 == limit {
break;
}
}
if always_terminate && words.last().copied() != Some(0) {
return Err(ExitReason::IllegalInstruction(0xFE));
}
let mut bytes = Vec::with_capacity(words.len() * 2);
for word in &words {
bytes.extend_from_slice(&word.to_le_bytes());
}
memory
.write_bytes(dest, &bytes)
.map_err(ExitReason::MemoryFault)?;
if !always_terminate {
let total = limit
.checked_mul(2)
.ok_or(ExitReason::MemoryFault(MemoryError::UnmappedAddress(dest)))?;
pad_zeros(memory, dest, bytes.len() as u64, total)?;
}
Ok(dest)
}
/// Zero `dest[from..to]` for the strncpy family, which pads to the count.
/// The count is guest controlled, so the padding is written in bounded
/// chunks and the first unmapped or read-only byte faults; the whole count
/// is never allocated on the host.
fn pad_zeros(memory: &mut GuestMemory, dest: u64, from: u64, to: u64) -> Result<(), ExitReason> {
const CHUNK: u64 = 4096;
let zeros = [0u8; CHUNK as usize];
let mut written = from;
while written < to {
let length = (to - written).min(CHUNK);
let at = dest
.checked_add(written)
.ok_or(ExitReason::MemoryFault(MemoryError::UnmappedAddress(dest)))?;
memory
.write_bytes(at, &zeros[..length as usize])
.map_err(ExitReason::MemoryFault)?;
written += length;
}
Ok(())
}
fn append_wide(memory: &mut GuestMemory, dest: u64, source: u64) -> Result<u64, ExitReason> {
let end = string_length(memory, dest, SCAN_BUDGET / 2, StringUnit::Wide)?;
let mut words = Vec::new();
for index in 0..(SCAN_BUDGET / 2) {
let word = memory
.read_u16(source + index * 2)
.map_err(ExitReason::MemoryFault)?;
words.push(word);
if word == 0 {
break;
}
}
if words.last().copied() != Some(0) {
return Err(ExitReason::IllegalInstruction(0xFE));
}
let mut bytes = Vec::with_capacity(words.len() * 2);
for word in words {
bytes.extend_from_slice(&word.to_le_bytes());
}
memory
.write_bytes(dest + end * 2, &bytes)
.map_err(ExitReason::MemoryFault)?;
Ok(dest)
}
fn find_wide(
memory: &GuestMemory,
address: u64,
needle: u16,
first: bool,
) -> Result<u64, ExitReason> {
if address == 0 {
return Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(0)));
}
let mut last = None;
for index in 0..(SCAN_BUDGET / 2) {
let word = memory
.read_u16(address + index * 2)
.map_err(ExitReason::MemoryFault)?;
if word == needle {
let found = address + index * 2;
if first {
return Ok(found);
}
last = Some(found);
}
if word == 0 {
return Ok(if needle == 0 {
address + index * 2
} else {
last.unwrap_or(0)
});
}
}
Err(ExitReason::IllegalInstruction(0xFE))
}
fn span_length(
memory: &GuestMemory,
address: u64,
set: u64,
accept: bool,
) -> Result<u64, ExitReason> {
if address == 0 || set == 0 {
return Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(0)));
}
let present = byte_set(memory, set)?;
for index in 0..SCAN_BUDGET {
let byte = memory
.read_u8(address + index)
.map_err(ExitReason::MemoryFault)?;
if byte == 0 || present[byte as usize] != accept {
return Ok(index);
}
}
Err(ExitReason::IllegalInstruction(0xFE))
}
fn byte_set(memory: &GuestMemory, address: u64) -> Result<[bool; 256], ExitReason> {
let mut present = [false; 256];
for offset in 0..SCAN_BUDGET {
let byte = StringUnit::Byte.read(memory, address, offset)? as usize;
if byte == 0 {
return Ok(present);
}
present[byte] = true;
}
Err(ExitReason::IllegalInstruction(0xFE))
}
fn wide_span(
memory: &GuestMemory,
address: u64,
set: u64,
accept: bool,
) -> Result<u64, ExitReason> {
if address == 0 || set == 0 {
return Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(0)));
}
let present = wide_set(memory, set)?;
let limit = SCAN_BUDGET / 2;
for offset in 0..limit {
let unit = StringUnit::Wide.read(memory, address, offset)? as usize;
let found = present[unit / 64] & (1 << (unit % 64)) != 0;
if unit == 0 || found != accept {
return Ok(offset);
}
}
Err(ExitReason::IllegalInstruction(0xFE))
}
fn wide_set(memory: &GuestMemory, address: u64) -> Result<[u64; 1024], ExitReason> {
let mut present = [0; 1024];
for offset in 0..(SCAN_BUDGET / 2) {
let unit = StringUnit::Wide.read(memory, address, offset)? as usize;
if unit == 0 {
return Ok(present);
}
present[unit / 64] |= 1 << (unit % 64);
}
Err(ExitReason::IllegalInstruction(0xFE))
}
fn locate_token(
memory: &GuestMemory,
cursor: u64,
unit: StringUnit,
delimiter: impl Fn(usize) -> bool,
) -> Result<(u64, u64, bool), ExitReason> {
let mut token = None;
for offset in 0..(SCAN_BUDGET / unit.width()) {
let value = unit.read(memory, cursor, offset)? as usize;
let position = cursor + offset * unit.width();
if value == 0 {
return Ok((token.unwrap_or(0), position, false));
}
if !delimiter(value) {
token.get_or_insert(position);
} else if let Some(token) = token {
return Ok((token, position, true));
}
}
Err(ExitReason::IllegalInstruction(0xFE))
}
fn tokenize_wide(
memory: &mut GuestMemory,
input: u64,
delimiters: u64,
context: u64,
) -> Result<u64, ExitReason> {
if delimiters == 0 || context == 0 {
return Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(0)));
}
let cursor = if input != 0 {
input
} else {
memory.read_u64(context).map_err(ExitReason::MemoryFault)?
};
if cursor == 0 {
return Ok(0);
}
let present = wide_set(memory, delimiters)?;
let (token, position, split) = locate_token(memory, cursor, StringUnit::Wide, |unit| {
present[unit / 64] & (1 << (unit % 64)) != 0
})?;
memory
.check_write(context, 8)
.map_err(ExitReason::MemoryFault)?;
let next = if split {
let next = position
.checked_add(2)
.ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?;
memory
.write_u16(position, 0)
.map_err(ExitReason::MemoryFault)?;
next
} else {
0
};
memory
.write_u64(context, next)
.map_err(ExitReason::MemoryFault)?;
Ok(token)
}
fn tokenize_s(
memory: &mut GuestMemory,
teb: u64,
input: u64,
delimiters: u64,
context: u64,
unit: StringUnit,
) -> Result<u64, ExitReason> {
if delimiters == 0 || context == 0 {
set_errno(memory, teb, EINVAL)?;
return Ok(0);
}
let cursor = if input == 0 {
memory.read_u64(context).map_err(ExitReason::MemoryFault)?
} else {
input
};
if cursor == 0 {
set_errno(memory, teb, EINVAL)?;
return Ok(0);
}
let (token, position, split) = match unit {
StringUnit::Byte => {
let present = byte_set(memory, delimiters)?;
locate_token(memory, cursor, unit, |byte| present[byte])?
}
StringUnit::Wide => {
let present = wide_set(memory, delimiters)?;
locate_token(memory, cursor, unit, |value| {
present[value / 64] & (1 << (value % 64)) != 0
})?
}
};
memory
.check_write(context, 8)
.map_err(ExitReason::MemoryFault)?;
let next = if split {
let next = position
.checked_add(unit.width())
.ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?;
match unit {
StringUnit::Byte => memory.write_u8(position, 0),
StringUnit::Wide => memory.write_u16(position, 0),
}
.map_err(ExitReason::MemoryFault)?;
next
} else {
position
};
memory
.write_u64(context, next)
.map_err(ExitReason::MemoryFault)?;
Ok(token)
}
fn tokenize(
memory: &mut GuestMemory,
teb: u64,
input: u64,
delimiters: u64,
) -> Result<u64, ExitReason> {
let cursor = if input == 0 {
let Some(&saved) = memory.crt_token_cursors.get(&teb) else {
return Ok(0);
};
saved
} else {
input
};
if delimiters == 0 {
return Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(0)));
}
let present = byte_set(memory, delimiters)?;
let (token, position, split) =
locate_token(memory, cursor, StringUnit::Byte, |byte| present[byte])?;
if split {
if memory.crt_token_cursors.len() >= 1024 && !memory.crt_token_cursors.contains_key(&teb) {
return Err(ExitReason::MemoryFault(MemoryError::AllocationFailed));
}
let next = position
.checked_add(1)
.ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?;
memory
.write_u8(position, 0)
.map_err(ExitReason::MemoryFault)?;
memory.crt_token_cursors.insert(teb, next);
} else {
memory.crt_token_cursors.remove(&teb);
}
Ok(token)
}
fn copy_string(
memory: &mut GuestMemory,
dest: u64,
source: u64,
limit: u64,
always_terminate: bool,
) -> Result<u64, ExitReason> {
if dest == 0 || source == 0 {
return Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(0)));
}
if limit == 0 {
return Ok(dest);
}
let mut copied = Vec::new();
let scan = limit.min(SCAN_BUDGET);
for index in 0..scan {
let byte = memory
.read_u8(source + index)
.map_err(ExitReason::MemoryFault)?;
copied.push(byte);
if byte == 0 {
break;
}
if !always_terminate && copied.len() as u64 == limit {
break;
}
}
if always_terminate && copied.last().copied() != Some(0) {
return Err(ExitReason::IllegalInstruction(0xFE));
}
memory
.write_bytes(dest, &copied)
.map_err(ExitReason::MemoryFault)?;
if !always_terminate {
pad_zeros(memory, dest, copied.len() as u64, limit)?;
}
Ok(dest)
}
fn append_string(
memory: &mut GuestMemory,
dest: u64,
source: u64,
limit: u64,
) -> Result<u64, ExitReason> {
let end = string_length(memory, dest, SCAN_BUDGET, StringUnit::Byte)?;
if limit == 0 {
memory
.write_u8(dest + end, 0)
.map_err(ExitReason::MemoryFault)?;
return Ok(dest);
}
let mut extra = Vec::new();
let scan = limit.min(SCAN_BUDGET);
for index in 0..scan {
let byte = memory
.read_u8(source + index)
.map_err(ExitReason::MemoryFault)?;
if byte == 0 {
break;
}
extra.push(byte);
}
extra.push(0);
memory
.write_bytes(dest + end, &extra)
.map_err(ExitReason::MemoryFault)?;
Ok(dest)
}
const ENOMEM: u32 = 12;
@@ -334,6 +918,30 @@ pub(super) fn register_conversions(registry: &mut ImportRegistry) {
registry.alias("api-ms-win-crt-convert-l1-1-0.dll", UCRT, symbol);
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
}
// `atoi` / `atol` and wide / 64-bit siblings: base 10, no end pointer.
// On Windows LLP64, `long` is 32-bit, so `atol` matches `atoi`.
for (symbol, wide_result, unit) in [
("atoi", false, StringUnit::Byte),
("atol", false, StringUnit::Byte),
("atoll", true, StringUnit::Byte),
("_atoi64", true, StringUnit::Byte),
("_wtoi", false, StringUnit::Wide),
("_wtol", false, StringUnit::Wide),
("_wtoi64", true, StringUnit::Wide),
] {
registry.register(UCRT, symbol, move |args, cpu, memory| {
let fixed = Win64Args {
rcx: args.rcx,
rdx: 0,
r8: 10,
r9: 0,
rsp: args.rsp,
};
parse_integer(memory, &fixed, cpu.gs_base, true, wide_result, unit)
});
registry.alias("api-ms-win-crt-convert-l1-1-0.dll", UCRT, symbol);
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
}
}
pub(super) fn register_errno(registry: &mut ImportRegistry) {
@@ -414,6 +1022,111 @@ fn free(memory: &mut GuestMemory, address: u64) -> Result<(), ExitReason> {
}
}
/// MSVC-compatible linear congruential generator used by historical UCRT
/// `rand` / `srand` (publicly documented recurrence). Not cryptographic.
fn next_rand(seed: &std::sync::atomic::AtomicU32) -> u32 {
let mut produced = 0u32;
seed.try_update(Ordering::SeqCst, Ordering::SeqCst, |state| {
let next = state.wrapping_mul(214013).wrapping_add(2531011);
produced = (next >> 16) & 0x7fff;
Some(next)
})
.expect("rand update always returns a value");
produced
}
pub(super) fn register_rand(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
let srand = Arc::clone(state);
registry.register(UCRT, "srand", move |args, _, _| {
srand.crt_rand.store(args.rcx as u32, Ordering::SeqCst);
Ok(0)
});
let rand = Arc::clone(state);
registry.register(UCRT, "rand", move |_, _, _| {
Ok(u64::from(next_rand(&rand.crt_rand)))
});
let rand_s = Arc::clone(state);
registry.register(UCRT, "rand_s", move |args, cpu, memory| {
if args.rcx == 0 {
set_errno(memory, cpu.gs_base, EINVAL)?;
return Ok(u64::from(EINVAL));
}
// Fill a guest `unsigned int` with 15 bits of LCG output in the low
// half, matching `rand`, rather than claiming CSPRNG strength.
let value = next_rand(&rand_s.crt_rand);
memory
.write_u32(args.rcx, value)
.map_err(ExitReason::MemoryFault)?;
Ok(0)
});
for symbol in ["srand", "rand", "rand_s"] {
registry.alias("api-ms-win-crt-utility-l1-1-0.dll", UCRT, symbol);
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
}
}
#[cfg(test)]
#[test]
fn stricmp_folds_ascii_case_only() {
use crate::cpu::{CpuState, Register};
use crate::import_table::ImportName;
let mut registry = ImportRegistry::new();
register(&mut registry);
let mut memory = GuestMemory::new();
let mut cpu = CpuState::default();
let left = memory.map_heap_allocation(PROCESS_HEAP, 8).unwrap();
let right = memory.map_heap_allocation(PROCESS_HEAP, 8).unwrap();
memory.write_bytes(left, b"AbC\0").unwrap();
memory.write_bytes(right, b"aBc\0").unwrap();
cpu.set(Register::Rcx, left);
cpu.set(Register::Rdx, right);
let service = registry
.resolve(UCRT, &ImportName::Name("_stricmp".into()))
.unwrap();
assert_eq!(
(service.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory).unwrap(),
0
);
memory.write_bytes(right, b"aBd\0").unwrap();
let ordered = (service.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory).unwrap() as i32;
assert!(ordered < 0);
cpu.set(Register::R8, 2);
let nicmp = registry
.resolve(UCRT, &ImportName::Name("_strnicmp".into()))
.unwrap();
assert_eq!(
(nicmp.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory).unwrap(),
0
);
}
#[cfg(test)]
#[test]
fn srand_rand_match_msvc_lcg_sequence() {
use crate::cpu::{CpuState, Register};
use crate::import_table::ImportName;
use crate::services::MockClock;
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
let mut registry = ImportRegistry::new();
register_rand(&mut registry, &state);
let mut memory = GuestMemory::new();
let mut cpu = CpuState::default();
let call = |symbol: &str, arg: u64, cpu: &mut CpuState, memory: &mut GuestMemory| {
cpu.set(Register::Rcx, arg);
let service = registry
.resolve(UCRT, &ImportName::Name(symbol.to_owned()))
.unwrap();
(service.handler)(&Win64Args::new(cpu), cpu, memory).unwrap()
};
assert_eq!(call("srand", 1, &mut cpu, &mut memory), 0);
// First three outputs after srand(1) for the documented MSVC LCG.
assert_eq!(call("rand", 0, &mut cpu, &mut memory), 41);
assert_eq!(call("rand", 0, &mut cpu, &mut memory), 18_467);
assert_eq!(call("rand", 0, &mut cpu, &mut memory), 6_334);
}
#[cfg(test)]
#[test]
fn errno_isolated_by_guest_teb_on_one_host_thread() {
@@ -451,3 +1164,156 @@ fn errno_isolated_by_guest_teb_on_one_host_thread() {
assert_eq!(call("_errno", &mut first, &mut memory), first_slot);
assert_eq!(memory.read_u32(first_slot).unwrap(), 23);
}
#[cfg(test)]
#[test]
fn strcpy_strncpy_strcat_and_memchr_operate_on_guest_memory() {
use crate::cpu::{CpuState, Register};
use crate::import_table::ImportName;
let mut registry = ImportRegistry::new();
register(&mut registry);
let mut memory = GuestMemory::new();
let mut cpu = CpuState::default();
let call = |symbol: &str, args: [u64; 3], cpu: &mut CpuState, memory: &mut GuestMemory| {
cpu.set(Register::Rcx, args[0]);
cpu.set(Register::Rdx, args[1]);
cpu.set(Register::R8, args[2]);
let service = registry
.resolve(UCRT, &ImportName::Name(symbol.to_owned()))
.unwrap();
(service.handler)(&Win64Args::new(cpu), cpu, memory).unwrap()
};
let dest = memory.map_heap_allocation(PROCESS_HEAP, 16).unwrap();
let source = memory.map_heap_allocation(PROCESS_HEAP, 8).unwrap();
memory.write_bytes(source, b"ab\0").unwrap();
assert_eq!(
call("strcpy", [dest, source, 0], &mut cpu, &mut memory),
dest
);
let mut out = [0u8; 3];
memory.read_bytes(dest, &mut out).unwrap();
assert_eq!(&out, b"ab\0");
assert_eq!(
call("memchr", [dest, u64::from(b'b'), 3], &mut cpu, &mut memory),
dest + 1
);
assert_eq!(
call("strncpy", [dest, source, 4], &mut cpu, &mut memory),
dest
);
let mut padded = [0u8; 4];
memory.read_bytes(dest, &mut padded).unwrap();
assert_eq!(&padded, b"ab\0\0");
memory.write_bytes(dest, b"x\0").unwrap();
assert_eq!(
call("strcat", [dest, source, 0], &mut cpu, &mut memory),
dest
);
let mut joined = [0u8; 4];
memory.read_bytes(dest, &mut joined).unwrap();
assert_eq!(&joined, b"xab\0");
}
#[cfg(test)]
#[test]
fn strtok_keeps_independent_cursors_and_accepts_new_delimiters() {
use crate::memory::MemoryPermissions;
let mut memory = GuestMemory::new();
memory
.map_region(0x1000, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
memory.write_bytes(0x1000, b",a,b;c\0").unwrap();
memory.write_bytes(0x1020, b"x,y\0").unwrap();
memory.write_bytes(0x1040, b",\0").unwrap();
memory.write_bytes(0x1048, b";\0").unwrap();
assert_eq!(tokenize(&mut memory, 1, 0x1000, 0x1040).unwrap(), 0x1001);
assert_eq!(tokenize(&mut memory, 2, 0x1020, 0x1040).unwrap(), 0x1020);
assert_eq!(memory.read_u8(0x1002).unwrap(), 0);
assert!(tokenize(&mut memory, 1, 0, 0x2000).is_err());
assert_eq!(tokenize(&mut memory, 1, 0, 0x1048).unwrap(), 0x1003);
assert_eq!(tokenize(&mut memory, 2, 0, 0x1040).unwrap(), 0x1022);
assert_eq!(tokenize(&mut memory, 1, 0, 0x1048).unwrap(), 0x1005);
assert_eq!(tokenize(&mut memory, 1, 0, 0x1048).unwrap(), 0);
assert_eq!(tokenize(&mut memory, 2, 0, 0x1040).unwrap(), 0);
}
#[cfg(test)]
#[test]
fn substring_search_handles_overlapping_prefixes_and_stops_at_first_match() {
use crate::memory::MemoryPermissions;
let mut memory = GuestMemory::new();
memory
.map_region_with_data(0x1000, 7, MemoryPermissions::READ_ONLY, b"aaaaaab")
.unwrap();
memory
.map_region_with_data(0x2000, 5, MemoryPermissions::READ_ONLY, b"aaab\0")
.unwrap();
assert_eq!(
find_substring(&memory, 0x1000, 0x2000, StringUnit::Byte).unwrap(),
0x1003
);
}
#[cfg(test)]
#[test]
fn wcstok_uses_explicit_context_and_preserves_input_on_invalid_context() {
use crate::memory::MemoryPermissions;
let mut memory = GuestMemory::new();
memory
.map_region(0x1000, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region(0x2000, 8, MemoryPermissions::READ_ONLY)
.unwrap();
for (index, value) in [0x03bb, 0x2603, 0x03bc, 0].into_iter().enumerate() {
memory.write_u16(0x1000 + index as u64 * 2, value).unwrap();
}
memory.write_u16(0x1020, 0x2603).unwrap();
assert!(tokenize_wide(&mut memory, 0x1000, 0x1020, 0x2000).is_err());
assert_eq!(memory.read_u16(0x1002).unwrap(), 0x2603);
assert_eq!(
tokenize_wide(&mut memory, 0x1000, 0x1020, 0x1040).unwrap(),
0x1000
);
assert_eq!(memory.read_u16(0x1002).unwrap(), 0);
assert_eq!(memory.read_u64(0x1040).unwrap(), 0x1004);
assert_eq!(tokenize_wide(&mut memory, 0, 0x1020, 0x1048).unwrap(), 0);
assert_eq!(
tokenize_wide(&mut memory, 0, 0x1020, 0x1040).unwrap(),
0x1004
);
assert_eq!(memory.read_u64(0x1040).unwrap(), 0);
}
#[cfg(test)]
#[test]
fn strtok_s_keeps_context_and_errno_separate() {
use crate::memory::MemoryPermissions;
let mut memory = GuestMemory::new();
memory
.map_region(0x1000, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
memory.write_bytes(0x1000, b",a,b;c\0").unwrap();
memory.write_bytes(0x1010, b"x,y\0").unwrap();
memory.write_bytes(0x1020, b",\0;\0").unwrap();
let call = |memory: &mut GuestMemory, input, delimiters, context| {
tokenize_s(memory, 0, input, delimiters, context, StringUnit::Byte).unwrap()
};
let errno = memory.crt_errno_address(0).unwrap();
assert_eq!(call(&mut memory, 0, 0x1020, 0x1040), 0);
assert_eq!(memory.read_u32(errno).unwrap(), EINVAL);
memory.write_u32(errno, 0).unwrap();
assert_eq!(call(&mut memory, 0x1000, 0x1020, 0x1040), 0x1001);
assert_eq!(call(&mut memory, 0x1010, 0x1020, 0x1048), 0x1010);
assert_eq!(call(&mut memory, 0, 0x1022, 0x1040), 0x1003);
assert_eq!(call(&mut memory, 0, 0x1022, 0x1040), 0x1005);
assert_eq!(memory.read_u64(0x1040).unwrap(), 0x1006);
assert_eq!(call(&mut memory, 0, 0x1022, 0x1040), 0);
assert_eq!(call(&mut memory, 0, 0x1020, 0x1048), 0x1012);
assert_eq!(memory.read_u32(errno).unwrap(), 0);
}
+127
View File
@@ -0,0 +1,127 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! C-locale character classification and case mapping (`ctype.h`).
//!
//! Predicates follow the MSVC contract: the argument is an `int` that is either
//! `EOF` (-1) or representable as `unsigned char`. Out-of-range values stop the
//! guest rather than invoking undefined behaviour.
use crate::cpu::ExitReason;
use crate::imports::{ImportRegistry, ServiceStatus};
const UCRT: &str = "ucrtbase.dll";
const STRING_API: &str = "api-ms-win-crt-string-l1-1-0.dll";
const EOF: i32 = -1;
fn as_char(value: u64) -> Result<Option<u8>, ExitReason> {
let value = value as i32;
if value == EOF {
return Ok(None);
}
if !(0..=255).contains(&value) {
return Err(ExitReason::IllegalInstruction(0xFE));
}
Ok(Some(value as u8))
}
fn classify(value: u64, pred: fn(u8) -> bool) -> Result<u64, ExitReason> {
Ok(u64::from(as_char(value)?.is_some_and(pred)))
}
fn map_case(value: u64, map: fn(u8) -> u8) -> Result<u64, ExitReason> {
Ok(match as_char(value)? {
None => value as i32 as u64,
Some(byte) => u64::from(map(byte)),
})
}
fn is_alnum(byte: u8) -> bool {
byte.is_ascii_alphanumeric()
}
fn is_alpha(byte: u8) -> bool {
byte.is_ascii_alphabetic()
}
fn is_digit(byte: u8) -> bool {
byte.is_ascii_digit()
}
fn is_lower(byte: u8) -> bool {
byte.is_ascii_lowercase()
}
fn is_upper(byte: u8) -> bool {
byte.is_ascii_uppercase()
}
fn is_space(byte: u8) -> bool {
matches!(byte, b' ' | b'\t' | b'\n' | b'\r' | b'\x0b' | b'\x0c')
}
fn is_xdigit(byte: u8) -> bool {
byte.is_ascii_hexdigit()
}
fn is_print(byte: u8) -> bool {
(0x20..=0x7e).contains(&byte)
}
fn is_cntrl(byte: u8) -> bool {
byte < 0x20 || byte == 0x7f
}
fn is_punct(byte: u8) -> bool {
is_print(byte) && !is_alnum(byte) && !is_space(byte)
}
pub(super) fn register(registry: &mut ImportRegistry) {
for (symbol, pred) in [
("isalnum", is_alnum as fn(u8) -> bool),
("isalpha", is_alpha),
("isdigit", is_digit),
("islower", is_lower),
("isupper", is_upper),
("isspace", is_space),
("isxdigit", is_xdigit),
("isprint", is_print),
("iscntrl", is_cntrl),
("ispunct", is_punct),
] {
registry.register(UCRT, symbol, move |args, _, _| classify(args.rcx, pred));
registry.alias(STRING_API, UCRT, symbol);
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
}
registry.register(UCRT, "tolower", |args, _, _| {
map_case(args.rcx, |byte| byte.to_ascii_lowercase())
});
registry.register(UCRT, "toupper", |args, _, _| {
map_case(args.rcx, |byte| byte.to_ascii_uppercase())
});
for symbol in ["tolower", "toupper"] {
registry.alias(STRING_API, UCRT, symbol);
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cpu::CpuState;
use crate::import_table::ImportName;
use crate::imports::Win64Args;
use crate::memory::GuestMemory;
#[test]
fn ctype_follows_c_locale_ascii_rules() {
let mut registry = ImportRegistry::new();
register(&mut registry);
let mut memory = GuestMemory::new();
let mut cpu = CpuState::default();
let mut call = |symbol: &str, value: i32| {
cpu.set(crate::cpu::Register::Rcx, value as u64);
let service = registry
.resolve(UCRT, &ImportName::Name(symbol.into()))
.unwrap();
(service.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory).unwrap()
};
assert_ne!(call("isalpha", b'A' as i32), 0);
assert_eq!(call("isalpha", b'1' as i32), 0);
assert_ne!(call("isdigit", b'9' as i32), 0);
assert_eq!(call("isdigit", EOF), 0);
assert_eq!(call("tolower", b'Z' as i32), u64::from(b'z'));
assert_eq!(call("toupper", b'a' as i32), u64::from(b'A'));
assert_eq!(call("tolower", EOF), EOF as u64);
}
}
+451
View File
@@ -0,0 +1,451 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Process environment block for CRT `getenv` and Win32 environment queries.
//!
//! Values are stored in the runtime and copied into durable guest buffers on
//! read. The guest cannot see the host process environment unless an entry is
//! explicitly installed here.
use super::ServicesState;
use crate::cpu::ExitReason;
use crate::imports::{ImportRegistry, ServiceStatus};
use crate::memory::{GuestMemory, MemoryError, PROCESS_HEAP};
use std::collections::BTreeMap;
use std::sync::Arc;
const UCRT: &str = "ucrtbase.dll";
const CRT_RUNTIME_API: &str = "api-ms-win-crt-runtime-l1-1-0.dll";
const KERNEL32: &str = "kernel32.dll";
const PROCESS_ENV_API: &str = "api-ms-win-core-processenvironment-l1-1-0.dll";
const EINVAL: u32 = 22;
const MAX_NAME: usize = 256;
const MAX_VALUE: usize = 32 * 1024;
#[derive(Default)]
pub(super) struct EnvState {
values: BTreeMap<String, String>,
/// Guest VA of the last getenv result for each key (ASCII).
buffers: BTreeMap<String, u64>,
}
impl EnvState {
pub(super) fn get(&self, key: &str) -> Option<&str> {
self.values.get(key).map(String::as_str)
}
fn with_defaults() -> Self {
let mut values = BTreeMap::new();
values.insert("OS".into(), "Windows_NT".into());
values.insert("NUMBER_OF_PROCESSORS".into(), "1".into());
Self {
values,
buffers: BTreeMap::new(),
}
}
}
fn fault(error: MemoryError) -> ExitReason {
ExitReason::MemoryFault(error)
}
fn set_errno(memory: &mut GuestMemory, teb: u64, error: u32) -> Result<(), ExitReason> {
let address = memory.crt_errno_address(teb).map_err(fault)?;
memory.write_u32(address, error).map_err(fault)
}
fn read_c_string(memory: &GuestMemory, address: u64, limit: usize) -> Result<String, ExitReason> {
if address == 0 {
return Err(ExitReason::IllegalInstruction(0xFE));
}
let mut bytes = Vec::new();
for index in 0..limit {
let byte = memory.read_u8(address + index as u64).map_err(fault)?;
if byte == 0 {
return String::from_utf8(bytes).map_err(|_| ExitReason::IllegalInstruction(0xFE));
}
bytes.push(byte);
}
Err(ExitReason::IllegalInstruction(0xFE))
}
fn read_wide_string(
memory: &GuestMemory,
address: u64,
limit: usize,
) -> Result<String, ExitReason> {
if address == 0 {
return Err(ExitReason::IllegalInstruction(0xFE));
}
let mut units = Vec::new();
for index in 0..limit {
let unit = memory.read_u16(address + index as u64 * 2).map_err(fault)?;
if unit == 0 {
return String::from_utf16(&units).map_err(|_| ExitReason::IllegalInstruction(0xFE));
}
units.push(unit);
}
Err(ExitReason::IllegalInstruction(0xFE))
}
fn store_ascii(
memory: &mut GuestMemory,
env: &mut EnvState,
key: &str,
value: &str,
) -> Result<u64, ExitReason> {
if value.len() > MAX_VALUE {
return Err(ExitReason::IllegalInstruction(0xFE));
}
let needed = value.len() + 1;
let buffer = if let Some(&existing) = env.buffers.get(key) {
existing
} else {
let address = memory
.map_heap_allocation(PROCESS_HEAP, needed.max(1))
.map_err(fault)?;
env.buffers.insert(key.to_owned(), address);
address
};
// Grow by allocating a replacement if the old buffer is too small.
let mut bytes = value.as_bytes().to_vec();
bytes.push(0);
if memory.write_bytes(buffer, &bytes).is_err() {
let address = memory
.map_heap_allocation(PROCESS_HEAP, bytes.len())
.map_err(fault)?;
memory.write_bytes(address, &bytes).map_err(fault)?;
env.buffers.insert(key.to_owned(), address);
return Ok(address);
}
Ok(buffer)
}
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
{
let mut env = state.env.lock().expect("env state");
if env.values.is_empty() {
*env = EnvState::with_defaults();
}
}
let getenv = Arc::clone(state);
registry.register(UCRT, "getenv", move |args, cpu, memory| {
if args.rcx == 0 {
set_errno(memory, cpu.gs_base, EINVAL)?;
return Ok(0);
}
let name = read_c_string(memory, args.rcx, MAX_NAME)?;
let key = name.to_ascii_uppercase();
let mut env = getenv.env.lock().expect("env state");
let Some(value) = env.values.get(&key).cloned() else {
return Ok(0);
};
store_ascii(memory, &mut env, &key, &value)
});
let get_a = Arc::clone(state);
registry.register(
KERNEL32,
"GetEnvironmentVariableA",
move |args, cpu, memory| {
let (name, buffer, size) = (args.rcx, args.rdx, args.r8 as u32);
if name == 0 {
return get_a.fail(cpu.gs_base, 87, 0);
}
let key = read_c_string(memory, name, MAX_NAME)?.to_ascii_uppercase();
let env = get_a.env.lock().expect("env state");
let Some(value) = env.values.get(&key) else {
return get_a.fail(cpu.gs_base, 203, 0); // ERROR_ENVVAR_NOT_FOUND
};
let needed = value.len() + 1;
if buffer == 0 || size == 0 {
return Ok(needed as u64);
}
if (size as usize) < needed {
let copy = (size as usize).saturating_sub(1).min(value.len());
memory
.write_bytes(buffer, &value.as_bytes()[..copy])
.map_err(fault)?;
if size > 0 {
memory.write_u8(buffer + copy as u64, 0).map_err(fault)?;
}
return get_a.fail(cpu.gs_base, 122, needed as u64); // ERROR_INSUFFICIENT_BUFFER
}
let mut bytes = value.as_bytes().to_vec();
bytes.push(0);
memory.write_bytes(buffer, &bytes).map_err(fault)?;
Ok((needed - 1) as u64)
},
);
let get_w = Arc::clone(state);
registry.register(
KERNEL32,
"GetEnvironmentVariableW",
move |args, cpu, memory| {
let (name, buffer, size) = (args.rcx, args.rdx, args.r8 as u32);
if name == 0 {
return get_w.fail(cpu.gs_base, 87, 0);
}
let key = read_wide_string(memory, name, MAX_NAME)?.to_ascii_uppercase();
let env = get_w.env.lock().expect("env state");
let Some(value) = env.values.get(&key) else {
return get_w.fail(cpu.gs_base, 203, 0);
};
let wide: Vec<u16> = value.encode_utf16().collect();
let needed = wide.len() + 1;
if buffer == 0 || size == 0 {
return Ok(needed as u64);
}
if (size as usize) < needed {
return get_w.fail(cpu.gs_base, 122, needed as u64);
}
for (index, unit) in wide.iter().enumerate() {
memory
.write_u16(buffer + index as u64 * 2, *unit)
.map_err(fault)?;
}
memory
.write_u16(buffer + wide.len() as u64 * 2, 0)
.map_err(fault)?;
Ok(wide.len() as u64)
},
);
let putenv = Arc::clone(state);
registry.register(UCRT, "_putenv", move |args, cpu, memory| {
if args.rcx == 0 {
set_errno(memory, cpu.gs_base, EINVAL)?;
return Ok(u64::from(u32::MAX));
}
let entry = read_c_string(memory, args.rcx, MAX_NAME + MAX_VALUE + 1)?;
let Some((name, value)) = entry.split_once('=') else {
set_errno(memory, cpu.gs_base, EINVAL)?;
return Ok(u64::from(u32::MAX));
};
if name.is_empty() || name.len() > MAX_NAME || value.len() > MAX_VALUE {
set_errno(memory, cpu.gs_base, EINVAL)?;
return Ok(u64::from(u32::MAX));
}
let key = name.to_ascii_uppercase();
let mut env = putenv.env.lock().expect("env state");
if value.is_empty() {
env.values.remove(&key);
env.buffers.remove(&key);
} else {
env.values.insert(key.clone(), value.to_owned());
env.buffers.remove(&key);
}
Ok(0)
});
let set_a = Arc::clone(state);
registry.register(
KERNEL32,
"SetEnvironmentVariableA",
move |args, cpu, memory| {
let (name, value) = (args.rcx, args.rdx);
if name == 0 {
return set_a.fail(cpu.gs_base, 87, 0);
}
let key = read_c_string(memory, name, MAX_NAME)?.to_ascii_uppercase();
if key.is_empty() {
return set_a.fail(cpu.gs_base, 87, 0);
}
let mut env = set_a.env.lock().expect("env state");
if value == 0 {
env.values.remove(&key);
env.buffers.remove(&key);
return Ok(1);
}
let text = read_c_string(memory, value, MAX_VALUE)?;
if text.len() > MAX_VALUE {
return set_a.fail(cpu.gs_base, 206, 0); // ERROR_FILENAME_EXCED_RANGE
}
env.values.insert(key.clone(), text);
env.buffers.remove(&key);
Ok(1)
},
);
let set_w = Arc::clone(state);
registry.register(
KERNEL32,
"SetEnvironmentVariableW",
move |args, cpu, memory| {
let (name, value) = (args.rcx, args.rdx);
if name == 0 {
return set_w.fail(cpu.gs_base, 87, 0);
}
let key = read_wide_string(memory, name, MAX_NAME)?.to_ascii_uppercase();
if key.is_empty() {
return set_w.fail(cpu.gs_base, 87, 0);
}
let mut env = set_w.env.lock().expect("env state");
if value == 0 {
env.values.remove(&key);
env.buffers.remove(&key);
return Ok(1);
}
let text = read_wide_string(memory, value, MAX_VALUE)?;
if text.len() > MAX_VALUE {
return set_w.fail(cpu.gs_base, 206, 0);
}
env.values.insert(key.clone(), text);
env.buffers.remove(&key);
Ok(1)
},
);
registry.alias(CRT_RUNTIME_API, UCRT, "getenv");
registry.alias(CRT_RUNTIME_API, UCRT, "_putenv");
registry.set_status(UCRT, "getenv", ServiceStatus::Partial);
registry.set_status(UCRT, "_putenv", ServiceStatus::Partial);
for symbol in [
"GetEnvironmentVariableA",
"GetEnvironmentVariableW",
"SetEnvironmentVariableA",
"SetEnvironmentVariableW",
] {
registry.alias(PROCESS_ENV_API, KERNEL32, symbol);
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cpu::{CpuState, Register};
use crate::import_table::ImportName;
use crate::imports::Win64Args;
use crate::services::MockClock;
fn call(
registry: &ImportRegistry,
module: &str,
symbol: &str,
args: [u64; 4],
cpu: &mut CpuState,
memory: &mut GuestMemory,
) -> u64 {
cpu.set(Register::Rcx, args[0]);
cpu.set(Register::Rdx, args[1]);
cpu.set(Register::R8, args[2]);
cpu.set(Register::R9, args[3]);
let service = registry
.resolve(module, &ImportName::Name(symbol.into()))
.unwrap();
(service.handler)(&Win64Args::new(cpu), cpu, memory).unwrap()
}
#[test]
fn getenv_returns_installed_values() {
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
let mut registry = ImportRegistry::new();
register(&mut registry, &state);
let mut memory = GuestMemory::new();
let mut cpu = CpuState {
gs_base: 0x10000,
..CpuState::default()
};
let name = memory.map_heap_allocation(PROCESS_HEAP, 8).unwrap();
memory.write_bytes(name, b"OS\0").unwrap();
let value = call(
&registry,
UCRT,
"getenv",
[name, 0, 0, 0],
&mut cpu,
&mut memory,
);
assert_ne!(value, 0);
let mut bytes = [0u8; 11];
memory.read_bytes(value, &mut bytes).unwrap();
assert_eq!(&bytes[..10], b"Windows_NT");
}
#[test]
fn putenv_and_set_environment_variable_update_the_block() {
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
let mut registry = ImportRegistry::new();
register(&mut registry, &state);
let mut memory = GuestMemory::new();
let mut cpu = CpuState {
gs_base: 0x10000,
..CpuState::default()
};
let entry = memory.map_heap_allocation(PROCESS_HEAP, 32).unwrap();
memory.write_bytes(entry, b"XENORA_TEST=one\0").unwrap();
assert_eq!(
call(
&registry,
UCRT,
"_putenv",
[entry, 0, 0, 0],
&mut cpu,
&mut memory
),
0
);
let name = memory.map_heap_allocation(PROCESS_HEAP, 16).unwrap();
memory.write_bytes(name, b"XENORA_TEST\0").unwrap();
let value = call(
&registry,
UCRT,
"getenv",
[name, 0, 0, 0],
&mut cpu,
&mut memory,
);
assert_ne!(value, 0);
let mut bytes = [0u8; 4];
memory.read_bytes(value, &mut bytes).unwrap();
assert_eq!(&bytes, b"one\0");
let next = memory.map_heap_allocation(PROCESS_HEAP, 8).unwrap();
memory.write_bytes(next, b"two\0").unwrap();
assert_eq!(
call(
&registry,
KERNEL32,
"SetEnvironmentVariableA",
[name, next, 0, 0],
&mut cpu,
&mut memory
),
1
);
let value = call(
&registry,
UCRT,
"getenv",
[name, 0, 0, 0],
&mut cpu,
&mut memory,
);
let mut bytes = [0u8; 4];
memory.read_bytes(value, &mut bytes).unwrap();
assert_eq!(&bytes, b"two\0");
assert_eq!(
call(
&registry,
KERNEL32,
"SetEnvironmentVariableA",
[name, 0, 0, 0],
&mut cpu,
&mut memory
),
1
);
assert_eq!(
call(
&registry,
UCRT,
"getenv",
[name, 0, 0, 0],
&mut cpu,
&mut memory
),
0
);
}
}
+55
View File
@@ -0,0 +1,55 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Abnormal CRT termination: `abort`, `_exit`, `terminate`,
//! `__std_terminate` and `_purecall`.
//!
//! Expected behaviour is from the public Microsoft C runtime pages. `abort`
//! ends the process with exit code 3 when no `SIGABRT` handler takes over.
//! `_exit` ends it with the given status and runs no `atexit` functions. The
//! default `terminate` handler calls `abort`, and so does the default
//! pure-virtual-call handler behind `_purecall`.
//!
//! No handler can be installed in Xenora yet: `signal`, `set_terminate` and
//! `_set_purecall_handler` are not runtime services, so a guest that tries
//! stops there. The default path is therefore the whole behaviour. Every exit
//! goes through the same process exit as `ExitProcess`; the host process is
//! never ended. Debug-CRT message boxes and Windows Error Reporting are not
//! modelled.
use super::ServicesState;
use crate::cpu::ExitReason;
use crate::imports::{ImportRegistry, ServiceStatus};
use std::sync::Arc;
const UCRT: &str = "ucrtbase.dll";
const CRT_RUNTIME_API: &str = "api-ms-win-crt-runtime-l1-1-0.dll";
const VCRUNTIME: &str = "vcruntime140.dll";
/// The exit code `abort` reports without a `SIGABRT` handler.
const ABORT_EXIT_CODE: u32 = 3;
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
// Each of these reaches abort's default path.
for (module, symbol) in [
(UCRT, "abort"),
(UCRT, "terminate"),
(UCRT, "_purecall"),
(VCRUNTIME, "__std_terminate"),
(VCRUNTIME, "_purecall"),
] {
let s = Arc::clone(state);
registry.register_with_status(module, symbol, ServiceStatus::Partial, move |_, _, _| {
Err(ExitReason::ProcessExit(s.exit_process(ABORT_EXIT_CODE)))
});
}
let s = Arc::clone(state);
registry.register_with_status(UCRT, "_exit", ServiceStatus::Partial, move |args, _, _| {
// The status is an int; the process exit code is its 32 bits.
Err(ExitReason::ProcessExit(s.exit_process(args.rcx as u32)))
});
for symbol in ["abort", "terminate", "_purecall", "_exit"] {
registry.alias(CRT_RUNTIME_API, UCRT, symbol);
}
}
+315
View File
@@ -0,0 +1,315 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Floating-point string conversion: `strtod`, `strtof`, `wcstod`, `wcstof`,
//! `atof` and `_wtof`.
//!
//! Parsing follows the ISO C grammar in the "C" locale: optional white space,
//! an optional sign, then a decimal number (digits with an optional `.` and an
//! optional exponent), `inf` or `infinity`, or `nan` with an optional
//! `(n-char-sequence)`, all case-insensitive. The decimal digits are converted
//! with Rust's correctly rounded parser straight to the result type, so
//! `strtof` never rounds through `double`. The result is returned in XMM0.
//!
//! A result that overflows becomes infinity and sets `ERANGE`. Nonzero digits
//! that round to zero also set `ERANGE`. Whether the UCRT sets `ERANGE` for a
//! subnormal but nonzero result has not been established from public
//! documentation, so Xenora leaves `errno` unchanged there. A `nan` payload is
//! accepted and ignored; the result is the default quiet NaN with the parsed
//! sign. Hexadecimal floating constants (`0x1.8p3`) are not converted: they
//! stop the guest instead of being parsed as `0`.
use crate::cpu::{CpuState, ExitReason};
use crate::imports::{ImportRegistry, ServiceStatus};
use crate::memory::{GuestMemory, MemoryError};
use crate::runtime::{Float32, Float64, Return};
const UCRT: &str = "ucrtbase.dll";
const CONVERT_API: &str = "api-ms-win-crt-convert-l1-1-0.dll";
const ERANGE: u32 = 34;
/// Longest number accepted, in characters.
const MAX_LENGTH: usize = 1 << 20;
#[derive(Clone, Copy, PartialEq)]
enum Width {
Byte,
Wide,
}
#[derive(Clone, Copy)]
enum Target {
Double,
Single,
}
fn unsupported() -> ExitReason {
ExitReason::IllegalInstruction(0xFE)
}
/// Reads one character at a time from a guest string.
struct Cursor<'a> {
memory: &'a GuestMemory,
base: u64,
width: Width,
index: usize,
}
impl Cursor<'_> {
fn peek_at(&self, ahead: usize) -> Result<char, ExitReason> {
let index = self.index + ahead;
if index > MAX_LENGTH {
return Err(unsupported());
}
let step = if self.width == Width::Wide { 2 } else { 1 };
let address = (index as u64)
.checked_mul(step)
.and_then(|offset| self.base.checked_add(offset))
.ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?;
let unit = match self.width {
Width::Byte => self.memory.read_u8(address).map(u16::from),
Width::Wide => self.memory.read_u16(address),
}
.map_err(ExitReason::MemoryFault)?;
// Only ASCII takes part in the grammar; anything else ends the number.
Ok(if unit < 0x80 {
unit as u8 as char
} else {
'\u{FFFD}'
})
}
fn peek(&self) -> Result<char, ExitReason> {
self.peek_at(0)
}
/// Consume `word` (lowercase ASCII) if the input matches it ignoring case.
fn eat_word(&mut self, word: &str) -> Result<bool, ExitReason> {
for (ahead, expected) in word.chars().enumerate() {
if self.peek_at(ahead)?.to_ascii_lowercase() != expected {
return Ok(false);
}
}
self.index += word.len();
Ok(true)
}
fn take_digits(&mut self, into: &mut String) -> Result<usize, ExitReason> {
let mut count = 0;
while self.peek()?.is_ascii_digit() {
into.push(self.peek()?);
self.index += 1;
count += 1;
}
Ok(count)
}
}
enum Parsed {
/// Nothing was converted; the end pointer is the start of the string.
None,
Value {
bits: u64,
range_error: bool,
end: usize,
},
}
fn parse(
memory: &GuestMemory,
base: u64,
width: Width,
target: Target,
) -> Result<Parsed, ExitReason> {
let mut cursor = Cursor {
memory,
base,
width,
index: 0,
};
while matches!(
cursor.peek()?,
' ' | '\t' | '\n' | '\u{0B}' | '\u{0C}' | '\r'
) {
cursor.index += 1;
}
let mut text = String::new();
let negative = cursor.peek()? == '-';
if matches!(cursor.peek()?, '-' | '+') {
cursor.index += 1;
}
if negative {
text.push('-');
}
if cursor.eat_word("infinity")? || cursor.eat_word("inf")? {
let bits = match target {
Target::Double => f64::INFINITY.to_bits(),
Target::Single => u64::from(f32::INFINITY.to_bits()),
};
return Ok(Parsed::Value {
bits: with_sign(bits, negative, target),
range_error: false,
end: cursor.index,
});
}
if cursor.eat_word("nan")? {
// An optional (n-char-sequence) is consumed only when it closes.
if cursor.peek()? == '(' {
let mut ahead = 1;
loop {
let c = cursor.peek_at(ahead)?;
if c == ')' {
cursor.index += ahead + 1;
break;
}
if !(c.is_ascii_alphanumeric() || c == '_') {
break;
}
ahead += 1;
}
}
let bits = match target {
Target::Double => 0x7FF8_0000_0000_0000,
Target::Single => 0x7FC0_0000,
};
return Ok(Parsed::Value {
bits: with_sign(bits, negative, target),
range_error: false,
end: cursor.index,
});
}
if cursor.peek()? == '0' && matches!(cursor.peek_at(1)?, 'x' | 'X') {
let next = cursor.peek_at(2)?;
if next.is_ascii_hexdigit() || (next == '.' && cursor.peek_at(3)?.is_ascii_hexdigit()) {
return Err(unsupported());
}
}
let mut digits = cursor.take_digits(&mut text)?;
let mut nonzero = text.bytes().any(|b| (b'1'..=b'9').contains(&b));
if cursor.peek()? == '.' {
let mark = text.len();
text.push('.');
cursor.index += 1;
let fraction = cursor.take_digits(&mut text)?;
nonzero |= text[mark..].bytes().any(|b| (b'1'..=b'9').contains(&b));
digits += fraction;
if digits == 0 {
return Ok(Parsed::None);
}
}
if digits == 0 {
return Ok(Parsed::None);
}
// An exponent counts only when at least one digit follows it.
if matches!(cursor.peek()?, 'e' | 'E') {
let sign = matches!(cursor.peek_at(1)?, '+' | '-');
let first = cursor.peek_at(if sign { 2 } else { 1 })?;
if first.is_ascii_digit() {
text.push('e');
if sign {
text.push(cursor.peek_at(1)?);
}
cursor.index += if sign { 2 } else { 1 };
cursor.take_digits(&mut text)?;
}
}
let (bits, overflow, zero) = match target {
Target::Double => {
let value: f64 = text.parse().map_err(|_| unsupported())?;
(value.to_bits(), value.is_infinite(), value == 0.0)
}
Target::Single => {
let value: f32 = text.parse().map_err(|_| unsupported())?;
(
u64::from(value.to_bits()),
value.is_infinite(),
value == 0.0,
)
}
};
Ok(Parsed::Value {
bits,
range_error: overflow || (zero && nonzero),
end: cursor.index,
})
}
fn with_sign(bits: u64, negative: bool, target: Target) -> u64 {
if !negative {
return bits;
}
match target {
Target::Double => bits | (1 << 63),
Target::Single => bits | (1 << 31),
}
}
fn convert(
memory: &mut GuestMemory,
cpu: &mut CpuState,
string: u64,
end_pointer: u64,
width: Width,
target: Target,
) -> Result<u64, ExitReason> {
if string == 0 {
return Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(0)));
}
let (bits, end) = match parse(memory, string, width, target)? {
Parsed::None => (0, 0),
Parsed::Value {
bits,
range_error,
end,
} => {
if range_error {
let errno = memory
.crt_errno_address(cpu.gs_base)
.map_err(ExitReason::MemoryFault)?;
memory
.write_u32(errno, ERANGE)
.map_err(ExitReason::MemoryFault)?;
}
(bits, end)
}
};
if end_pointer != 0 {
let step = if width == Width::Wide { 2 } else { 1 };
memory
.write_u64(end_pointer, string + end as u64 * step)
.map_err(ExitReason::MemoryFault)?;
}
Ok(match target {
Target::Double => Float64(bits).place(cpu),
Target::Single => Float32(bits as u32).place(cpu),
})
}
pub(super) fn register(registry: &mut ImportRegistry) {
for (symbol, width, target) in [
("strtod", Width::Byte, Target::Double),
("strtof", Width::Byte, Target::Single),
("wcstod", Width::Wide, Target::Double),
("wcstof", Width::Wide, Target::Single),
] {
registry.register_with_status(
UCRT,
symbol,
ServiceStatus::Partial,
move |args, cpu, memory| convert(memory, cpu, args.rcx, args.rdx, width, target),
);
}
for (symbol, width) in [("atof", Width::Byte), ("_wtof", Width::Wide)] {
registry.register_with_status(
UCRT,
symbol,
ServiceStatus::Partial,
move |args, cpu, memory| convert(memory, cpu, args.rcx, 0, width, Target::Double),
);
}
for symbol in ["strtod", "strtof", "wcstod", "wcstof", "atof", "_wtof"] {
registry.alias(CONVERT_API, UCRT, symbol);
}
}
+256
View File
@@ -0,0 +1,256 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! UCRT block-size, aligned and zeroing allocation services on the CRT heap.
//!
//! Behaviour follows the public UCRT reference pages for `_msize`,
//! `_recalloc`, `_aligned_malloc`, `_aligned_realloc`, `_aligned_msize` and
//! `_aligned_free`. Cases those pages send to the invalid-parameter handler
//! set `errno` to `EINVAL` and return the documented failure value instead;
//! the handler itself is not modelled.
//!
//! Heap blocks start on 64 KiB boundaries, so an aligned block is an ordinary
//! CRT heap block whose address is checked against the requested alignment.
//! Aligned blocks are recorded so that `_aligned_free` of any other pointer,
//! including a second free of the same block, stops the guest with a memory
//! fault instead of being ignored.
use super::ServicesState;
use crate::cpu::ExitReason;
use crate::imports::{ImportRegistry, ServiceStatus};
use crate::memory::{GuestMemory, MemoryError, PROCESS_HEAP};
use std::collections::BTreeSet;
use std::sync::Arc;
const UCRT: &str = "ucrtbase.dll";
const CRT_HEAP_API: &str = "api-ms-win-crt-heap-l1-1-0.dll";
const ENOMEM: u32 = 12;
const EINVAL: u32 = 22;
const SIZE_FAILURE: u64 = u64::MAX;
/// Blocks handed out by the aligned allocators.
#[derive(Default)]
pub(super) struct AlignedBlocks(BTreeSet<u64>);
fn fault(error: MemoryError) -> ExitReason {
ExitReason::MemoryFault(error)
}
fn set_errno(memory: &mut GuestMemory, teb: u64, error: u32) -> Result<(), ExitReason> {
let address = memory.crt_errno_address(teb).map_err(fault)?;
memory.write_u32(address, error).map_err(fault)
}
fn failed(memory: &mut GuestMemory, teb: u64, error: u32, value: u64) -> Result<u64, ExitReason> {
set_errno(memory, teb, error)?;
Ok(value)
}
/// A new aligned block, or `None` when the heap cannot provide one.
fn aligned_block(memory: &mut GuestMemory, size: u64, alignment: u64) -> Option<u64> {
let size = usize::try_from(size.max(1)).ok()?;
let block = memory.map_heap_allocation(PROCESS_HEAP, size).ok()?;
if block % alignment == 0 {
Some(block)
} else {
// Larger alignments than the heap provides are refused, not faked.
memory.release_heap_allocation(PROCESS_HEAP, block);
None
}
}
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
registry.register_with_status(
UCRT,
"_msize",
ServiceStatus::Partial,
|args, cpu, memory| {
if args.rcx == 0 {
return failed(memory, cpu.gs_base, EINVAL, SIZE_FAILURE);
}
match memory.heap_allocation_size(PROCESS_HEAP, args.rcx) {
Some(size) => Ok(size as u64),
None => Err(fault(MemoryError::UnmappedAddress(args.rcx))),
}
},
);
registry.register_with_status(
UCRT,
"_recalloc",
ServiceStatus::Partial,
|args, cpu, memory| {
let (block, count, size) = (args.rcx, args.rdx, args.r8);
let Some(total) = count.checked_mul(size) else {
return failed(memory, cpu.gs_base, ENOMEM, 0);
};
if block == 0 {
return match memory.map_heap_allocation(PROCESS_HEAP, total.max(1) as usize) {
Ok(address) => Ok(address),
Err(_) => failed(memory, cpu.gs_base, ENOMEM, 0),
};
}
let Some(previous) = memory.heap_allocation_size(PROCESS_HEAP, block) else {
return Err(fault(MemoryError::UnmappedAddress(block)));
};
if total == 0 {
memory.release_heap_allocation(PROCESS_HEAP, block);
return Ok(0);
}
let Ok(total) = usize::try_from(total) else {
return failed(memory, cpu.gs_base, ENOMEM, 0);
};
match memory.resize_heap_allocation(PROCESS_HEAP, block, total, false) {
Ok(address) => {
// Bytes past the old block start at zero, as documented.
if total > previous {
memory
.write_bytes(address + previous as u64, &vec![0; total - previous])
.map_err(fault)?;
}
Ok(address)
}
// The original block is left unchanged.
Err(_) => failed(memory, cpu.gs_base, ENOMEM, 0),
}
},
);
let malloc = Arc::clone(state);
registry.register_with_status(
UCRT,
"_aligned_malloc",
ServiceStatus::Partial,
move |args, cpu, memory| {
let (size, alignment) = (args.rcx, args.rdx);
if !alignment.is_power_of_two() {
return failed(memory, cpu.gs_base, EINVAL, 0);
}
match aligned_block(memory, size, alignment) {
Some(block) => {
malloc
.aligned
.lock()
.expect("aligned blocks")
.0
.insert(block);
Ok(block)
}
None => failed(memory, cpu.gs_base, ENOMEM, 0),
}
},
);
let realloc = Arc::clone(state);
registry.register_with_status(
UCRT,
"_aligned_realloc",
ServiceStatus::Partial,
move |args, cpu, memory| {
let (block, size, alignment) = (args.rcx, args.rdx, args.r8);
if !alignment.is_power_of_two() {
return failed(memory, cpu.gs_base, EINVAL, 0);
}
let mut blocks = realloc.aligned.lock().expect("aligned blocks");
if block == 0 {
return match aligned_block(memory, size, alignment) {
Some(new) => {
blocks.0.insert(new);
Ok(new)
}
None => failed(memory, cpu.gs_base, ENOMEM, 0),
};
}
if !blocks.0.contains(&block) {
return Err(fault(MemoryError::UnmappedAddress(block)));
}
if size == 0 {
blocks.0.remove(&block);
memory.release_heap_allocation(PROCESS_HEAP, block);
return Ok(0);
}
let Ok(size) = usize::try_from(size) else {
return failed(memory, cpu.gs_base, ENOMEM, 0);
};
let previous = memory
.heap_allocation_size(PROCESS_HEAP, block)
.ok_or(fault(MemoryError::UnmappedAddress(block)))?;
// Grow or shrink in place when that keeps the alignment.
if let Ok(same) = memory.resize_heap_allocation(PROCESS_HEAP, block, size, true) {
return Ok(same);
}
let Some(new) = aligned_block(memory, size as u64, alignment) else {
return failed(memory, cpu.gs_base, ENOMEM, 0);
};
let mut bytes = vec![0; previous.min(size)];
memory.read_bytes(block, &mut bytes).map_err(fault)?;
memory.write_bytes(new, &bytes).map_err(fault)?;
memory.release_heap_allocation(PROCESS_HEAP, block);
blocks.0.remove(&block);
blocks.0.insert(new);
Ok(new)
},
);
let msize = Arc::clone(state);
registry.register_with_status(
UCRT,
"_aligned_msize",
ServiceStatus::Partial,
move |args, cpu, memory| {
let (block, alignment, offset) = (args.rcx, args.rdx, args.r8);
if block == 0 || !alignment.is_power_of_two() || offset != 0 {
// A nonzero offset belongs to `_aligned_offset_malloc`, which
// is not provided, so no block here can have one.
return failed(memory, cpu.gs_base, EINVAL, SIZE_FAILURE);
}
if !msize
.aligned
.lock()
.expect("aligned blocks")
.0
.contains(&block)
{
return Err(fault(MemoryError::UnmappedAddress(block)));
}
memory
.heap_allocation_size(PROCESS_HEAP, block)
.map(|size| size as u64)
.ok_or(fault(MemoryError::UnmappedAddress(block)))
},
);
let free = Arc::clone(state);
registry.register_with_status(
UCRT,
"_aligned_free",
ServiceStatus::Implemented,
move |args, _, memory| {
if args.rcx == 0 {
return Ok(0);
}
// A pointer this allocator never returned, or one already freed.
if !free
.aligned
.lock()
.expect("aligned blocks")
.0
.remove(&args.rcx)
{
return Err(fault(MemoryError::UnmappedAddress(args.rcx)));
}
memory.release_heap_allocation(PROCESS_HEAP, args.rcx);
Ok(0)
},
);
for symbol in [
"_msize",
"_recalloc",
"_aligned_malloc",
"_aligned_realloc",
"_aligned_msize",
"_aligned_free",
] {
registry.alias(CRT_HEAP_API, UCRT, symbol);
}
}
+91
View File
@@ -0,0 +1,91 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Integer `abs`, `labs`, `llabs`, `div`, `ldiv` and `lldiv`.
//!
//! These follow the Windows LLP64 data model, where `long` is 32 bits. The
//! macOS `long` is 64 bits, so the host `labs` and `ldiv` would read a guest
//! argument's upper half and return the wrong width; they are implemented
//! here instead.
//!
//! Returns follow the Win64 calling convention: `div_t` and `ldiv_t` (two
//! 32-bit fields, 8 bytes) come back in RAX with the quotient in the low half.
//! `lldiv_t` (16 bytes) is returned through a hidden pointer the caller passes
//! in RCX, so the operands move to RDX and R8 and RAX returns that pointer.
//!
//! C leaves the absolute value of the minimum integer, division by zero and
//! the minimum divided by -1 undefined. `abs` wraps, as the x86 `neg`
//! instruction does. The divisions stop the guest with a divide error, as the
//! x86 `idiv` instruction does for the same operands; they never return an
//! invented quotient.
use crate::cpu::ExitReason;
use crate::imports::{ImportRegistry, ServiceStatus};
use crate::memory::GuestMemory;
const UCRT: &str = "ucrtbase.dll";
const UTILITY_API: &str = "api-ms-win-crt-utility-l1-1-0.dll";
/// Quotient and remainder truncated toward zero, as C requires. `checked_*`
/// fails for exactly the operands on which `idiv` raises a divide error.
fn divide32(numerator: i32, denominator: i32) -> Result<(i32, i32), ExitReason> {
numerator
.checked_div(denominator)
.zip(numerator.checked_rem(denominator))
.ok_or(ExitReason::DivideError)
}
fn divide64(numerator: i64, denominator: i64) -> Result<(i64, i64), ExitReason> {
numerator
.checked_div(denominator)
.zip(numerator.checked_rem(denominator))
.ok_or(ExitReason::DivideError)
}
/// Pack a 32-bit quotient and remainder as an 8-byte struct in RAX.
fn pack32((quotient, remainder): (i32, i32)) -> u64 {
u64::from(quotient as u32) | (u64::from(remainder as u32) << 32)
}
fn write_lldiv(
memory: &mut GuestMemory,
result: u64,
value: (i64, i64),
) -> Result<u64, ExitReason> {
let mut bytes = [0u8; 16];
bytes[..8].copy_from_slice(&value.0.to_le_bytes());
bytes[8..].copy_from_slice(&value.1.to_le_bytes());
memory
.write_bytes(result, &bytes)
.map_err(ExitReason::MemoryFault)?;
Ok(result)
}
pub(super) fn register(registry: &mut ImportRegistry) {
// int and long are both 32 bits under LLP64; the result zero-extends
// into RAX like any 32-bit return.
for symbol in ["abs", "labs"] {
registry.register_with_status(UCRT, symbol, ServiceStatus::Implemented, |args, _, _| {
Ok(u64::from((args.rcx as i32).wrapping_abs() as u32))
});
}
registry.register_with_status(UCRT, "llabs", ServiceStatus::Implemented, |args, _, _| {
Ok((args.rcx as i64).wrapping_abs() as u64)
});
for symbol in ["div", "ldiv"] {
registry.register_with_status(UCRT, symbol, ServiceStatus::Implemented, |args, _, _| {
divide32(args.rcx as i32, args.rdx as i32).map(pack32)
});
}
registry.register_with_status(
UCRT,
"lldiv",
ServiceStatus::Implemented,
|args, _, memory| {
let value = divide64(args.rdx as i64, args.r8 as i64)?;
write_lldiv(memory, args.rcx, value)
},
);
for symbol in ["abs", "labs", "llabs", "div", "ldiv", "lldiv"] {
registry.alias(UTILITY_API, UCRT, symbol);
}
}
+189
View File
@@ -0,0 +1,189 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! C-locale CRT services. Only the `"C"` locale is supported; other locale
//! names fail closed. `localeconv` returns a guest `lconv` that describes the
//! C locale and stays valid until the next successful `setlocale`.
use super::ServicesState;
use crate::cpu::ExitReason;
use crate::imports::{ImportRegistry, ServiceStatus};
use crate::memory::{GuestMemory, MemoryError, PROCESS_HEAP};
use std::sync::Arc;
const UCRT: &str = "ucrtbase.dll";
const LOCALE_API: &str = "api-ms-win-crt-locale-l1-1-0.dll";
const EINVAL: u32 = 22;
const LC_ALL: i32 = 0;
const LC_TIME: i32 = 5;
/// Windows `CHAR_MAX` used for "not available" monetary fields.
const CHAR_MAX: u8 = 127;
/// Pointers (10) + char fields (8) in the MSVC x64 `lconv` we expose.
const LCONV_BYTES: usize = 10 * 8 + 8;
const STRING_BYTES: usize = 16;
#[derive(Default)]
pub(super) struct LocaleState {
/// Guest VA of the packed C-locale blob (strings then `lconv`), or 0.
block: u64,
/// Guest VA of the durable `"C"` name string.
name: u64,
}
fn fault(error: MemoryError) -> ExitReason {
ExitReason::MemoryFault(error)
}
fn set_errno(memory: &mut GuestMemory, teb: u64, error: u32) -> Result<(), ExitReason> {
let address = memory.crt_errno_address(teb).map_err(fault)?;
memory.write_u32(address, error).map_err(fault)
}
fn read_c_string(memory: &GuestMemory, address: u64, limit: usize) -> Result<String, ExitReason> {
if address == 0 {
return Ok(String::new());
}
let mut bytes = Vec::new();
for index in 0..limit {
let byte = memory.read_u8(address + index as u64).map_err(fault)?;
if byte == 0 {
return String::from_utf8(bytes).map_err(|_| ExitReason::IllegalInstruction(0xFE));
}
bytes.push(byte);
}
Err(ExitReason::IllegalInstruction(0xFE))
}
fn is_c_locale(name: &str) -> bool {
name.is_empty()
|| name.eq_ignore_ascii_case("C")
|| name.eq_ignore_ascii_case("POSIX")
|| name.eq_ignore_ascii_case("C.UTF-8")
|| name.eq_ignore_ascii_case("C.utf8")
}
fn valid_category(category: i32) -> bool {
(LC_ALL..=LC_TIME).contains(&category)
}
fn ensure_c_locale(
state: &Arc<ServicesState>,
memory: &mut GuestMemory,
) -> Result<(u64, u64), ExitReason> {
let mut locale = state.locale.lock().expect("locale state");
if locale.block != 0 && locale.name != 0 {
return Ok((locale.block, locale.name));
}
let total = STRING_BYTES + LCONV_BYTES;
let block = memory
.map_heap_allocation(PROCESS_HEAP, total)
.map_err(fault)?;
// Layout: [0]=".\0", [2]="" (empty at the extra NUL), [3]="C\0"; lconv at 16.
memory.write_bytes(block, b".\0\0C\0").map_err(fault)?;
let decimal = block;
let empty = block + 2;
let name = block + 3;
let lconv = block + STRING_BYTES as u64;
let mut bytes = [0u8; LCONV_BYTES];
let write_ptr = |bytes: &mut [u8], index: usize, value: u64| {
bytes[index * 8..(index + 1) * 8].copy_from_slice(&value.to_le_bytes());
};
write_ptr(&mut bytes, 0, decimal); // decimal_point
write_ptr(&mut bytes, 1, empty); // thousands_sep
write_ptr(&mut bytes, 2, empty); // grouping
write_ptr(&mut bytes, 3, empty); // int_curr_symbol
write_ptr(&mut bytes, 4, empty); // currency_symbol
write_ptr(&mut bytes, 5, empty); // mon_decimal_point
write_ptr(&mut bytes, 6, empty); // mon_thousands_sep
write_ptr(&mut bytes, 7, empty); // mon_grouping
write_ptr(&mut bytes, 8, empty); // positive_sign
write_ptr(&mut bytes, 9, empty); // negative_sign
for field in 0..8 {
bytes[80 + field] = CHAR_MAX;
}
memory.write_bytes(lconv, &bytes).map_err(fault)?;
locale.block = block;
locale.name = name;
Ok((block, name))
}
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
let setlocale = Arc::clone(state);
registry.register(UCRT, "setlocale", move |args, cpu, memory| {
let category = args.rcx as i32;
if !valid_category(category) {
set_errno(memory, cpu.gs_base, EINVAL)?;
return Ok(0);
}
if args.rdx == 0 {
let (_, name) = ensure_c_locale(&setlocale, memory)?;
return Ok(name);
}
let requested = read_c_string(memory, args.rdx, 64)?;
if !is_c_locale(&requested) {
set_errno(memory, cpu.gs_base, EINVAL)?;
return Ok(0);
}
let (_, name) = ensure_c_locale(&setlocale, memory)?;
Ok(name)
});
let localeconv = Arc::clone(state);
registry.register(UCRT, "localeconv", move |_, _, memory| {
let (block, _) = ensure_c_locale(&localeconv, memory)?;
Ok(block + STRING_BYTES as u64)
});
for symbol in ["setlocale", "localeconv"] {
registry.alias(LOCALE_API, UCRT, symbol);
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cpu::CpuState;
use crate::imports::Win64Args;
use crate::services::MockClock;
use crate::services::ServicesState;
#[test]
fn setlocale_accepts_only_the_c_locale() {
use crate::cpu::Register;
use crate::import_table::ImportName;
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
let mut registry = ImportRegistry::new();
register(&mut registry, &state);
let mut memory = GuestMemory::new();
let mut cpu = CpuState {
gs_base: 0x10000,
..CpuState::default()
};
let call = |symbol: &str, cpu: &mut CpuState, memory: &mut GuestMemory| {
let service = registry
.resolve(UCRT, &ImportName::Name(symbol.to_owned()))
.unwrap();
(service.handler)(&Win64Args::new(cpu), cpu, memory).unwrap()
};
let name = memory.map_heap_allocation(PROCESS_HEAP, 8).unwrap();
memory.write_bytes(name, b"C\0").unwrap();
cpu.set(Register::Rcx, LC_ALL as u64);
cpu.set(Register::Rdx, name);
let returned = call("setlocale", &mut cpu, &mut memory);
assert_ne!(returned, 0);
let mut label = [0u8; 2];
memory.read_bytes(returned, &mut label).unwrap();
assert_eq!(&label, b"C\0");
let bad = memory.map_heap_allocation(PROCESS_HEAP, 16).unwrap();
memory.write_bytes(bad, b"en_US\0").unwrap();
cpu.set(Register::Rdx, bad);
assert_eq!(call("setlocale", &mut cpu, &mut memory), 0);
let lconv = call("localeconv", &mut cpu, &mut memory);
assert_ne!(lconv, 0);
let decimal = memory.read_u64(lconv).unwrap();
let mut point = [0u8; 2];
memory.read_bytes(decimal, &mut point).unwrap();
assert_eq!(&point, b".\0");
}
}
@@ -0,0 +1,207 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Bounds-checked UCRT string copy and append: `strcpy_s`, `strcat_s`,
//! `strncpy_s`, `strncat_s` and their `wcs` counterparts.
//!
//! Behaviour follows the public UCRT reference pages for those functions.
//! Each returns its `errno_t` and also stores it in `errno`, except
//! `STRUNCATE`, which is a successful truncation. Where those pages invoke the
//! invalid-parameter handler, the handler is not modelled: the function
//! returns the documented error instead. Sizes and counts are in characters.
//! When an error is reported after the destination was validated, its first
//! character is set to the terminator, as documented.
use super::ServicesState;
use crate::cpu::ExitReason;
use crate::imports::{ImportRegistry, ServiceStatus};
use crate::memory::{GuestMemory, MemoryError};
use std::sync::Arc;
const UCRT: &str = "ucrtbase.dll";
const CRT_STRING_API: &str = "api-ms-win-crt-string-l1-1-0.dll";
const EINVAL: u32 = 22;
const ERANGE: u32 = 34;
const STRUNCATE: u32 = 80;
/// `_TRUNCATE`: copy as much as fits.
const TRUNCATE: u64 = u64::MAX;
/// Longest string, in characters, these functions scan.
const SCAN_LIMIT: u64 = 1 << 20;
fn fault(error: MemoryError) -> ExitReason {
ExitReason::MemoryFault(error)
}
#[derive(Clone, Copy)]
struct Unit(u64);
impl Unit {
fn at(self, base: u64, index: u64) -> Result<u64, ExitReason> {
index
.checked_mul(self.0)
.and_then(|offset| base.checked_add(offset))
.ok_or(fault(MemoryError::Overflow))
}
fn read(self, memory: &GuestMemory, base: u64, index: u64) -> Result<u16, ExitReason> {
let address = self.at(base, index)?;
match self.0 {
1 => memory.read_u8(address).map(u16::from),
_ => memory.read_u16(address),
}
.map_err(fault)
}
fn write(
self,
memory: &mut GuestMemory,
base: u64,
index: u64,
value: u16,
) -> Result<(), ExitReason> {
let address = self.at(base, index)?;
match self.0 {
1 => memory.write_u8(address, value as u8),
_ => memory.write_u16(address, value),
}
.map_err(fault)
}
/// Characters before the terminator, if one occurs within `limit`.
fn length(
self,
memory: &GuestMemory,
base: u64,
limit: u64,
) -> Result<Option<u64>, ExitReason> {
for index in 0..limit.min(SCAN_LIMIT) {
if self.read(memory, base, index)? == 0 {
return Ok(Some(index));
}
}
Ok(None)
}
fn copy(
self,
memory: &mut GuestMemory,
to: u64,
from: u64,
count: u64,
) -> Result<(), ExitReason> {
for index in 0..count {
let value = self.read(memory, from, index)?;
self.write(memory, to, index, value)?;
}
Ok(())
}
}
struct Call<'a> {
memory: &'a mut GuestMemory,
teb: u64,
unit: Unit,
}
impl Call<'_> {
fn finish(&mut self, error: u32) -> Result<u64, ExitReason> {
if error != 0 && error != STRUNCATE {
let address = self.memory.crt_errno_address(self.teb).map_err(fault)?;
self.memory.write_u32(address, error).map_err(fault)?;
}
Ok(u64::from(error))
}
/// Clear the destination and report `error`.
fn reset(&mut self, dest: u64, error: u32) -> Result<u64, ExitReason> {
self.unit.write(self.memory, dest, 0, 0)?;
self.finish(error)
}
/// Write `count` characters of `src` at `dest + start`, then a terminator.
fn place(&mut self, dest: u64, start: u64, src: u64, count: u64) -> Result<(), ExitReason> {
let at = self.unit.at(dest, start)?;
self.unit.copy(self.memory, at, src, count)?;
self.unit.write(self.memory, dest, start + count, 0)
}
/// `strncpy_s` when `count` is `None` means `strcpy_s`; the append
/// variants first find the end of `dest`.
fn run(
&mut self,
dest: u64,
size: u64,
src: u64,
count: Option<u64>,
append: bool,
) -> Result<u64, ExitReason> {
if dest == 0 || size == 0 {
return self.finish(EINVAL);
}
let start = if append {
match self.unit.length(self.memory, dest, size)? {
Some(length) => length,
// An unterminated destination is invalid.
None => return self.reset(dest, EINVAL),
}
} else {
0
};
if count == Some(0) {
// Nothing to copy, even from a null source.
self.unit.write(self.memory, dest, start, 0)?;
return self.finish(0);
}
if src == 0 {
return self.reset(dest, EINVAL);
}
let room = size - start;
let truncate = count == Some(TRUNCATE);
let wanted_limit = match count {
Some(count) if !truncate => count,
_ => room.saturating_add(1),
};
// Characters of `src` that would be copied, bounded by what can matter.
let length = self
.unit
.length(self.memory, src, wanted_limit)?
.unwrap_or(wanted_limit);
if length < room {
self.place(dest, start, src, length)?;
return self.finish(0);
}
if truncate {
self.place(dest, start, src, room - 1)?;
return self.finish(STRUNCATE);
}
self.reset(dest, ERANGE)
}
}
pub(super) fn register(registry: &mut ImportRegistry, _: &Arc<ServicesState>) {
for (symbol, width, counted, append) in [
("strcpy_s", 1, false, false),
("strcat_s", 1, false, true),
("strncpy_s", 1, true, false),
("strncat_s", 1, true, true),
("wcscpy_s", 2, false, false),
("wcscat_s", 2, false, true),
("wcsncpy_s", 2, true, false),
("wcsncat_s", 2, true, true),
] {
registry.register_with_status(
UCRT,
symbol,
ServiceStatus::Partial,
move |args, cpu, memory| {
let count = counted.then_some(args.r9);
Call {
memory,
teb: cpu.gs_base,
unit: Unit(width),
}
.run(args.rcx, args.rdx, args.r8, count, append)
},
);
registry.alias(CRT_STRING_API, UCRT, symbol);
}
}
File diff suppressed because it is too large. Load diff
+214
View File
@@ -0,0 +1,214 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! CRT calendar time against the injectable guest clock.
//!
//! `time` / `_time64` report Unix seconds derived from the same FILETIME clock
//! as `GetSystemTimeAsFileTime`. `gmtime_s` / `localtime_s` and their 64-bit
//! forms fill a Windows `tm` in UTC; there is no guest timezone database, so
//! local time matches UTC and `tm_isdst` is always zero.
use super::ServicesState;
use crate::cpu::ExitReason;
use crate::imports::{ImportRegistry, ServiceStatus};
use crate::memory::{GuestMemory, MemoryError};
use std::sync::Arc;
const UCRT: &str = "ucrtbase.dll";
const CRT_TIME_API: &str = "api-ms-win-crt-time-l1-1-0.dll";
const EINVAL: u32 = 22;
const FILETIME_TICKS_PER_SEC: u64 = 10_000_000;
/// Seconds from 1601-01-01 to 1970-01-01.
const SECS_1601_TO_1970: u64 = 11_644_473_600;
fn fault(error: MemoryError) -> ExitReason {
ExitReason::MemoryFault(error)
}
fn set_errno(memory: &mut GuestMemory, teb: u64, error: u32) -> Result<(), ExitReason> {
let address = memory.crt_errno_address(teb).map_err(fault)?;
memory.write_u32(address, error).map_err(fault)
}
fn unix_from_filetime(filetime: u64) -> Option<i64> {
let secs = filetime / FILETIME_TICKS_PER_SEC;
if secs < SECS_1601_TO_1970 {
return Some(0);
}
i64::try_from(secs - SECS_1601_TO_1970).ok()
}
/// Proleptic Gregorian date for a day count relative to 1970-01-01.
fn civil_from_days(days: i64) -> (i64, u16, u16) {
let shifted = days + 719_468;
let era = shifted.div_euclid(146_097);
let day_of_era = shifted.rem_euclid(146_097);
let year_of_era =
(day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let month_index = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * month_index + 2) / 5 + 1;
let month = if month_index < 10 {
month_index + 3
} else {
month_index - 9
};
let year = year_of_era + era * 400 + i64::from(month <= 2);
(year, month as u16, day as u16)
}
fn day_of_year(year: i64, month: u16, day: u16) -> i32 {
const CUMULATIVE: [i32; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
let extra = i32::from(leap && month > 2);
CUMULATIVE[month as usize - 1] + i32::from(day) - 1 + extra
}
/// Windows `struct tm` field order (nine 32-bit ints).
fn write_tm(memory: &mut GuestMemory, dest: u64, unix: i64) -> Result<(), ExitReason> {
let days = unix.div_euclid(86_400);
let of_day = unix.rem_euclid(86_400) as i32;
let (year, month, day) = civil_from_days(days);
let fields = [
of_day % 60, // tm_sec
(of_day / 60) % 60, // tm_min
of_day / 3600, // tm_hour
i32::from(day), // tm_mday
i32::from(month) - 1, // tm_mon
(year - 1900) as i32, // tm_year
((days + 4).rem_euclid(7)) as i32, // tm_wday (1970-01-01 was Thursday)
day_of_year(year, month, day), // tm_yday
0, // tm_isdst
];
for (index, field) in fields.into_iter().enumerate() {
memory
.write_u32(dest + index as u64 * 4, field as u32)
.map_err(fault)?;
}
Ok(())
}
fn store_time(memory: &mut GuestMemory, dest: u64, value: i64) -> Result<(), ExitReason> {
if dest == 0 {
return Ok(());
}
memory.write_u64(dest, value as u64).map_err(fault)
}
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
let time64 = Arc::clone(state);
registry.register(UCRT, "_time64", move |args, _, memory| {
let now = unix_from_filetime(time64.clock.now_filetime()).unwrap_or(0);
store_time(memory, args.rcx, now)?;
Ok(now as u64)
});
let time32 = Arc::clone(state);
registry.register(UCRT, "time", move |args, _, memory| {
let now = unix_from_filetime(time32.clock.now_filetime()).unwrap_or(0);
// 32-bit `time_t` saturates rather than wrapping past 2038.
let clipped = now.clamp(i32::MIN as i64, i32::MAX as i64) as i32;
if args.rcx != 0 {
memory.write_u32(args.rcx, clipped as u32).map_err(fault)?;
}
Ok(u64::from(clipped as u32))
});
for (symbol, wide) in [
("gmtime_s", false),
("localtime_s", false),
("_gmtime64_s", true),
("_localtime64_s", true),
] {
let clock = Arc::clone(state);
registry.register(UCRT, symbol, move |args, cpu, memory| {
let (tm, time_ptr) = (args.rcx, args.rdx);
if tm == 0 || time_ptr == 0 {
set_errno(memory, cpu.gs_base, EINVAL)?;
return Ok(u64::from(EINVAL));
}
let unix = if wide {
memory.read_u64(time_ptr).map_err(fault)? as i64
} else {
memory.read_u32(time_ptr).map_err(fault)? as i32 as i64
};
let _ = clock; // timezone-free: local == UTC
write_tm(memory, tm, unix)?;
Ok(0)
});
}
for symbol in [
"time",
"_time64",
"gmtime_s",
"localtime_s",
"_gmtime64_s",
"_localtime64_s",
] {
registry.alias(CRT_TIME_API, UCRT, symbol);
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cpu::{CpuState, Register};
use crate::import_table::ImportName;
use crate::imports::Win64Args;
use crate::memory::PROCESS_HEAP;
use crate::services::MockClock;
fn call(
registry: &ImportRegistry,
symbol: &str,
args: [u64; 4],
cpu: &mut CpuState,
memory: &mut GuestMemory,
) -> u64 {
cpu.set(Register::Rcx, args[0]);
cpu.set(Register::Rdx, args[1]);
cpu.set(Register::R8, args[2]);
cpu.set(Register::R9, args[3]);
let service = registry
.resolve(UCRT, &ImportName::Name(symbol.into()))
.unwrap();
(service.handler)(&Win64Args::new(cpu), cpu, memory).unwrap()
}
#[test]
fn time64_and_gmtime_s_match_unix_epoch() {
// 1970-01-01 00:00:00 UTC as FILETIME.
let filetime = SECS_1601_TO_1970 * FILETIME_TICKS_PER_SEC;
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(filetime))));
let mut registry = ImportRegistry::new();
register(&mut registry, &state);
let mut memory = GuestMemory::new();
let mut cpu = CpuState {
gs_base: 0x10000,
..CpuState::default()
};
let slot = memory.map_heap_allocation(PROCESS_HEAP, 8).unwrap();
assert_eq!(
call(&registry, "_time64", [slot, 0, 0, 0], &mut cpu, &mut memory),
0
);
assert_eq!(memory.read_u64(slot).unwrap(), 0);
let tm = memory.map_heap_allocation(PROCESS_HEAP, 36).unwrap();
assert_eq!(
call(
&registry,
"_gmtime64_s",
[tm, slot, 0, 0],
&mut cpu,
&mut memory
),
0
);
assert_eq!(memory.read_u32(tm).unwrap(), 0); // sec
assert_eq!(memory.read_u32(tm + 12).unwrap(), 1); // mday
assert_eq!(memory.read_u32(tm + 16).unwrap(), 0); // mon
assert_eq!(memory.read_u32(tm + 20).unwrap(), 70); // year
assert_eq!(memory.read_u32(tm + 24).unwrap(), 4); // Thursday
}
}
+273
View File
@@ -0,0 +1,273 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! C++ `type_info` and `std::exception` helpers exported by `vcruntime140.dll`.
//!
//! Compiled `typeid`, `type_info::operator==`, `type_info::before`,
//! `type_info::hash_code` and `type_info::name` call these helpers with a
//! pointer to the type descriptor's data: an 8-byte slot that caches the
//! readable name, followed by the NUL-terminated decorated name such as
//! `.?AVWidget@ui@@`. That layout is the publicly described MSVC RTTI type
//! descriptor (virtual table pointer, spare word, name).
//!
//! * Equality and ordering compare decorated names byte by byte.
//! * `__std_type_info_hash` is FNV-1a over the decorated name. The C++
//! standard only requires equal types to hash equally within one run; the
//! value is not claimed to match the one Microsoft's runtime computes.
//! * `__std_type_info_name` undecorates plain class, struct, union and enum
//! names, including namespaces and nesting. Other decorations (templates,
//! back-references, anonymous namespaces, pointer and function types) stop
//! the guest rather than return a wrong name.
//!
//! `std::exception` keeps its message in an `__std_exception_data` record: the
//! message pointer, then a one-byte flag saying whether the exception owns
//! (and must free) that text. `__std_exception_copy` gives a copy its own
//! duplicate of an owned message so `what()` stays equal after the original is
//! destroyed, and shares a borrowed one. `__std_exception_destroy` frees an
//! owned message and clears the record. Owned text lives on the CRT heap, so
//! guest `malloc` and `free` interoperate with it.
use super::ServicesState;
use crate::cpu::ExitReason;
use crate::imports::{ImportRegistry, ServiceStatus};
use crate::memory::{GuestMemory, MemoryError, PROCESS_HEAP};
use std::sync::{Arc, Mutex};
const MODULE: &str = "vcruntime140.dll";
/// Longest decorated name read from the guest.
const MAX_NAME: usize = 4096;
/// Longest exception message duplicated, in bytes.
const MAX_MESSAGE: usize = 1 << 20;
fn fault(error: MemoryError) -> ExitReason {
ExitReason::MemoryFault(error)
}
fn unsupported<T>() -> Result<T, ExitReason> {
Err(ExitReason::IllegalInstruction(0xFE))
}
/// The decorated name stored after the cached-name slot at `data`.
fn decorated(memory: &GuestMemory, data: u64) -> Result<Vec<u8>, ExitReason> {
if data == 0 {
return Err(fault(MemoryError::UnmappedAddress(0)));
}
let start = data.checked_add(8).ok_or(fault(MemoryError::Overflow))?;
let mut name = Vec::new();
for offset in 0..MAX_NAME as u64 {
let byte = memory.read_u8(start + offset).map_err(fault)?;
if byte == 0 {
return Ok(name);
}
name.push(byte);
}
unsupported()
}
/// FNV-1a, 64-bit.
fn hash(name: &[u8]) -> u64 {
name.iter().fold(0xcbf2_9ce4_8422_2325, |state, &byte| {
(state ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3)
})
}
/// The readable name of a plain class, struct, union or enum type, or `None`
/// when the decoration uses anything else.
pub fn undecorate(name: &[u8]) -> Option<String> {
let name = std::str::from_utf8(name).ok()?;
let rest = name.strip_prefix(".?A")?;
let (keyword, rest) = match rest.as_bytes().first()? {
b'V' => ("class", &rest[1..]),
b'U' => ("struct", &rest[1..]),
b'T' => ("union", &rest[1..]),
// `W4` is an enum with an int underlying type.
b'W' => ("enum", rest.strip_prefix("W4")?),
_ => return None,
};
let parts = rest.strip_suffix("@@")?;
let fragments: Vec<&str> = parts.split('@').collect();
let plain = |part: &&str| {
!part.is_empty()
&& !part.as_bytes()[0].is_ascii_digit()
&& part
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
};
if !fragments.iter().all(plain) {
return None;
}
let qualified: Vec<&str> = fragments.into_iter().rev().collect();
Some(format!("{keyword} {}", qualified.join("::")))
}
/// Names allocated by `__std_type_info_name`, released by
/// `__std_type_info_destroy_list`.
#[derive(Default)]
pub(super) struct TypeNames {
allocations: Vec<u64>,
}
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
registry.register_with_status(
MODULE,
"__std_type_info_compare",
ServiceStatus::Implemented,
|args, _, memory| {
if args.rcx == args.rdx {
return Ok(0);
}
let left = decorated(memory, args.rcx)?;
let right = decorated(memory, args.rdx)?;
let result: i32 = match left.cmp(&right) {
std::cmp::Ordering::Less => -1,
std::cmp::Ordering::Equal => 0,
std::cmp::Ordering::Greater => 1,
};
Ok(u64::from(result as u32))
},
);
registry.register_with_status(
MODULE,
"__std_type_info_hash",
ServiceStatus::Partial,
|args, _, memory| Ok(hash(&decorated(memory, args.rcx)?)),
);
let names: Arc<Mutex<TypeNames>> = Arc::clone(&state.type_names);
registry.register_with_status(
MODULE,
"__std_type_info_name",
ServiceStatus::Partial,
move |args, _, memory| {
let cached = memory.read_u64(args.rcx).map_err(fault)?;
if cached != 0 {
return Ok(cached);
}
let Some(readable) = undecorate(&decorated(memory, args.rcx)?) else {
return unsupported();
};
let mut bytes = readable.into_bytes();
bytes.push(0);
let address = memory
.map_heap_allocation(PROCESS_HEAP, bytes.len())
.map_err(fault)?;
memory.write_bytes(address, &bytes).map_err(fault)?;
memory.write_u64(args.rcx, address).map_err(fault)?;
names.lock().expect("type names").allocations.push(address);
Ok(address)
},
);
let destroy = Arc::clone(&state.type_names);
registry.register_with_status(
MODULE,
"__std_type_info_destroy_list",
ServiceStatus::Partial,
move |_, _, memory| {
// Descriptors keep their cached pointers, as after the runtime
// unloads; nothing reads them once the list is destroyed.
for address in destroy.lock().expect("type names").allocations.drain(..) {
memory.release_heap_allocation(PROCESS_HEAP, address);
}
Ok(0)
},
);
registry.register_with_status(
MODULE,
"__std_exception_copy",
ServiceStatus::Partial,
|args, _, memory| {
let (from, to) = (args.rcx, args.rdx);
let text = memory.read_u64(from).map_err(fault)?;
let owned = memory.read_u8(from + 8).map_err(fault)? != 0;
if !owned || text == 0 {
memory.write_u64(to, text).map_err(fault)?;
memory.write_u8(to + 8, 0).map_err(fault)?;
return Ok(0);
}
let mut bytes = Vec::new();
loop {
let byte = memory.read_u8(text + bytes.len() as u64).map_err(fault)?;
bytes.push(byte);
if byte == 0 {
break;
}
if bytes.len() > MAX_MESSAGE {
return unsupported();
}
}
// An allocation failure leaves an empty record, so the copy
// reports the runtime's generic message rather than share text it
// does not own.
let Ok(copy) = memory.map_heap_allocation(PROCESS_HEAP, bytes.len()) else {
memory.write_u64(to, 0).map_err(fault)?;
memory.write_u8(to + 8, 0).map_err(fault)?;
return Ok(0);
};
memory.write_bytes(copy, &bytes).map_err(fault)?;
memory.write_u64(to, copy).map_err(fault)?;
memory.write_u8(to + 8, 1).map_err(fault)?;
Ok(0)
},
);
registry.register_with_status(
MODULE,
"__std_exception_destroy",
ServiceStatus::Partial,
|args, _, memory| {
let text = memory.read_u64(args.rcx).map_err(fault)?;
let owned = memory.read_u8(args.rcx + 8).map_err(fault)? != 0;
if owned && text != 0 && !memory.release_heap_allocation(PROCESS_HEAP, text) {
// Freeing memory the CRT heap never handed out is a guest bug.
return Err(fault(MemoryError::UnmappedAddress(text)));
}
memory.write_u64(args.rcx, 0).map_err(fault)?;
memory.write_u8(args.rcx + 8, 0).map_err(fault)?;
Ok(0)
},
);
}
#[cfg(test)]
mod tests {
use super::{hash, undecorate};
#[test]
fn undecorates_plain_and_nested_type_names() {
let cases = [
(".?AVWidget@@", "class Widget"),
(".?AUPoint@geometry@@", "struct geometry::Point"),
(".?ATValue@@", "union Value"),
(".?AW4Color@ui@app@@", "enum app::ui::Color"),
(".?AVInner@Outer@@", "class Outer::Inner"),
];
for (decorated, readable) in cases {
assert_eq!(undecorate(decorated.as_bytes()).as_deref(), Some(readable));
}
}
#[test]
fn refuses_decorations_it_does_not_model() {
for decorated in [
".?AV?$Box@H@@", // template
".?AVImpl@?A0x1234@@", // anonymous namespace
".?AVA@1@@", // back-reference
".?AVWidget@", // unterminated
".PEAX", // pointer type
".?AW1Small@@", // enum with a non-int underlying type
".?AV@@",
"?AVWidget@@",
] {
assert_eq!(undecorate(decorated.as_bytes()), None, "{decorated}");
}
}
#[test]
fn hash_is_fnv1a() {
assert_eq!(hash(b""), 0xcbf2_9ce4_8422_2325);
assert_eq!(hash(b"a"), 0xaf63_dc4c_8601_ec8c);
assert_ne!(hash(b".?AVA@@"), hash(b".?AVB@@"));
}
}
File diff suppressed because it is too large. Load diff
+285
View File
@@ -0,0 +1,285 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Documented XAsync helpers on top of the manual GDK task-queue subset.
//!
//! With a null queue in the `XAsyncBlock`, `XAsyncRun` runs work and optional
//! completion on the calling thread before it returns (immediate dispatch).
//! With a non-null manual `XTaskQueue` handle, work is submitted to the work
//! port and completion to the completion port; the caller must
//! `XTaskQueueDispatch` those ports. `XAsyncGetStatus` with `wait=true` is
//! unsupported either way.
use super::ServicesState;
use crate::cpu::ExitReason;
use crate::imports::{
CallbackStart, CallbackStep, CallbackTask, GuestCallback, ImportRegistry, ServiceStatus,
Win64Args,
};
use crate::memory::{GuestMemory, MemoryError};
use crate::runtime::HResult;
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use std::time::Instant;
const MODULE: &str = "xgameruntime.dll";
const ASYNC_BLOCK_SIZE: u64 = 56;
const E_PENDING: u64 = 0x8000_000A;
const E_ABORT: u64 = 0x8000_4004;
const E_INVALIDARG: u64 = 0x8007_0057;
const WORK_PORT: u32 = 0;
const COMPLETION_PORT: u32 = 1;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Status {
Pending,
Done(u32),
}
#[derive(Default)]
pub(super) struct AsyncOps {
ops: BTreeMap<u64, Status>,
}
fn fault(error: MemoryError) -> ExitReason {
ExitReason::MemoryFault(error)
}
fn guest_hresult(code: u32) -> u64 {
HResult::from_win32(code).guest_return()
}
struct AsyncRun {
block: u64,
completion: u64,
/// Non-zero when work was queued; completion is submitted to this handle.
queue: u64,
ops: Arc<Mutex<AsyncOps>>,
state: Arc<ServicesState>,
phase: Phase,
}
enum Phase {
Work,
Complete,
}
impl CallbackTask for AsyncRun {
fn resume(
&mut self,
result: u64,
_: u64,
_: &mut GuestMemory,
) -> Result<CallbackStep, ExitReason> {
match self.phase {
Phase::Work => {
let status = result as u32;
self.ops
.lock()
.expect("async ops")
.ops
.insert(self.block, Status::Done(status));
if self.completion == 0 {
// Immediate path returns S_OK to XAsyncRun; queued path
// returns TRUE to XTaskQueueDispatch.
let value = if self.queue == 0 {
HResult::OK.guest_return()
} else {
1
};
return Ok(CallbackStep::Return(value));
}
if self.queue == 0 {
self.phase = Phase::Complete;
return Ok(CallbackStep::Call {
entry: self.completion,
args: [self.block, 0, 0, 0],
});
}
// Queue completion onto the completion port; the guest must
// dispatch that port separately.
let mut queues = self
.state
.gdk_queues
.lock()
.expect("GDK queue handle table");
let callback = super::gdk_queue::scheduled(
Instant::now(),
GuestCallback {
entry: self.completion,
context: self.block,
cancelled: false,
task: None,
},
);
if queues
.submit(self.queue, COMPLETION_PORT, callback)
.is_err()
{
return Ok(CallbackStep::Return(0));
}
self.state.gdk_queue_changed.notify_all();
Ok(CallbackStep::Return(1))
}
Phase::Complete => Ok(CallbackStep::Return(HResult::OK.guest_return())),
}
}
}
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
let run = Arc::clone(state);
registry.register_callback_task(
MODULE,
"XAsyncRun",
ServiceStatus::Partial,
move |args, _, memory, _| start_run(&run, args, memory),
);
let status = Arc::clone(state);
registry.register_with_status(
MODULE,
"XAsyncGetStatus",
ServiceStatus::Partial,
move |args, _, memory| {
let block = args.rcx;
if block == 0
|| memory
.check_write(block, ASYNC_BLOCK_SIZE as usize)
.is_err()
{
return Ok(E_INVALIDARG);
}
if args.rdx != 0 {
return Ok(guest_hresult(50)); // ERROR_NOT_SUPPORTED as HRESULT
}
let ops = status.gdk_async.lock().expect("async ops");
Ok(match ops.ops.get(&block) {
Some(Status::Pending) => E_PENDING,
Some(Status::Done(code)) => u64::from(*code),
None => E_INVALIDARG,
})
},
);
let cancel = Arc::clone(state);
registry.register_with_status(
MODULE,
"XAsyncCancel",
ServiceStatus::Partial,
move |args, _, memory| {
let block = args.rcx;
if block == 0
|| memory
.check_write(block, ASYNC_BLOCK_SIZE as usize)
.is_err()
{
return Ok(0);
}
let mut ops = cancel.gdk_async.lock().expect("async ops");
if let Some(Status::Pending) = ops.ops.get(&block) {
ops.ops.insert(block, Status::Done(E_ABORT as u32));
}
Ok(0)
},
);
registry.register_with_status(
MODULE,
"XAsyncGetResultSize",
ServiceStatus::Partial,
move |args, _, memory| {
if args.rcx == 0
|| args.rdx == 0
|| memory
.check_write(args.rcx, ASYNC_BLOCK_SIZE as usize)
.is_err()
{
return Ok(E_INVALIDARG);
}
memory.write_u64(args.rdx, 0).map_err(fault)?;
Ok(HResult::OK.guest_return())
},
);
}
fn start_run(
state: &Arc<ServicesState>,
args: &Win64Args,
memory: &mut GuestMemory,
) -> Result<CallbackStart, ExitReason> {
let block = args.rcx;
let work = args.rdx;
if block == 0
|| work == 0
|| memory
.check_write(block, ASYNC_BLOCK_SIZE as usize)
.is_err()
{
return Ok(CallbackStart::Return(E_INVALIDARG));
}
memory
.fetch_instruction_byte(work)
.map_err(ExitReason::MemoryFault)?;
let queue = memory.read_u64(block).map_err(fault)?;
let completion = memory.read_u64(block + 16).map_err(fault)?;
if completion != 0 {
memory
.fetch_instruction_byte(completion)
.map_err(ExitReason::MemoryFault)?;
}
{
let mut ops = state.gdk_async.lock().expect("async ops");
if matches!(ops.ops.get(&block), Some(Status::Pending)) {
return Ok(CallbackStart::Return(E_INVALIDARG));
}
ops.ops.insert(block, Status::Pending);
}
let task = AsyncRun {
block,
completion,
queue,
ops: Arc::clone(&state.gdk_async),
state: Arc::clone(state),
phase: Phase::Work,
};
if queue == 0 {
return Ok(CallbackStart::Call {
task: Box::new(task),
entry: work,
args: [block, 0, 0, 0],
});
}
// Queue path: schedule work on the work port and return immediately.
let mut queues = state.gdk_queues.lock().expect("GDK queue handle table");
if !queues.has_handle(queue) {
state
.gdk_async
.lock()
.expect("async ops")
.ops
.remove(&block);
return Ok(CallbackStart::Return(E_INVALIDARG));
}
let callback = super::gdk_queue::scheduled(
Instant::now(),
GuestCallback {
entry: work,
context: block,
cancelled: false,
task: Some(Arc::new(Mutex::new(Box::new(task)))),
},
);
if let Err(error) = queues.submit(queue, WORK_PORT, callback) {
state
.gdk_async
.lock()
.expect("async ops")
.ops
.remove(&block);
return Ok(CallbackStart::Return(guest_hresult(error)));
}
state.gdk_queue_changed.notify_all();
Ok(CallbackStart::Return(HResult::OK.guest_return()))
}
+20 -7
View File
@@ -34,13 +34,26 @@ struct Queue {
ports: [u64; 2],
}
struct ScheduledCallback {
pub(super) struct ScheduledCallback {
owner: u64,
ready_at: Instant,
callback: GuestCallback,
}
/// Build a delayed/immediate scheduled callback for queue submission.
pub(super) fn scheduled(ready_at: Instant, callback: GuestCallback) -> ScheduledCallback {
ScheduledCallback {
owner: 0,
ready_at,
callback,
}
}
impl QueueHandles {
pub(super) fn has_handle(&self, handle: u64) -> bool {
self.queues.contains_key(&handle)
}
/// Task-queue handles the guest has open.
pub(super) fn open_count(&self) -> usize {
self.queues.len()
@@ -100,7 +113,7 @@ impl QueueHandles {
}
}
fn submit(
pub(super) fn submit(
&mut self,
handle: u64,
selector: u32,
@@ -255,15 +268,15 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
{
return Ok(E_ABORT);
}
let callback = ScheduledCallback {
owner: 0,
ready_at: Instant::now() + Duration::from_millis(u64::from(delay)),
callback: GuestCallback {
let callback = scheduled(
Instant::now() + Duration::from_millis(u64::from(delay)),
GuestCallback {
entry,
context,
cancelled: false,
task: None,
},
};
);
let result = queues.submit(args.rcx, args.rdx as u32, callback);
if result.is_ok() {
submit.gdk_queue_changed.notify_all();
+890
View File
@@ -0,0 +1,890 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Guest drive letters backed by explicitly configured host directories.
//!
//! Each mount holds a descriptor for its root. Guest paths are resolved one
//! component at a time with `openat` and `O_NOFOLLOW` from that descriptor,
//! matching names case-insensitively against the directory listing.
//!
//! Policy, enforced on every operation:
//! - `.` and `..` components, device names and absolute host paths cannot be
//! expressed in a guest path.
//! - Symbolic links, devices, sockets, FIFOs, non-UTF-8 names and regular
//! files with more than one hard link are hidden from the guest and cannot
//! be opened, so a link cannot alias a host file outside the root.
//! - After each `openat`, the descriptor is checked with `fstat`: it must be
//! the expected type (directory or regular file), have one link if it is a
//! file, and keep the device and inode the listing reported. A concurrent
//! host change that swaps an entry between the listing and the open fails
//! with `ERROR_ACCESS_DENIED` instead of reaching the replacement.
//! - Reads, writes and truncation use the verified descriptor, so they reach
//! the same file however the host renames it afterwards. Read-only mounts
//! open every file `O_RDONLY`, so the host kernel also refuses writes.
//! - Sharing and deletion checks compare device and inode, not guest paths.
//!
//! Not covered: another host process that moves a directory or file the guest
//! already holds open out of the mount. The guest keeps its handle to that
//! object. Host processes with write access to a mounted directory are
//! trusted. Removal and renaming are name-based after a final listing check, so
//! a concurrent host rename in that window can delete or move a different entry
//! inside the root (never outside it); directories have no post-unlink check.
//! This boundary was agent-reviewed for guest path confinement; it is not a
//! substitute for an independent human security audit.
use std::ffi::{CStr, CString};
use std::fs::File;
use std::io;
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, OwnedFd};
use std::path::Path;
use std::sync::{Arc, Mutex};
pub(super) const ERROR_FILE_NOT_FOUND: u32 = 2;
pub(super) const ERROR_PATH_NOT_FOUND: u32 = 3;
pub(super) const ERROR_ACCESS_DENIED: u32 = 5;
pub(super) const ERROR_FILE_EXISTS: u32 = 80;
const ERROR_NOT_ENOUGH_MEMORY: u32 = 8;
const ERROR_GEN_FAILURE: u32 = 31;
const ERROR_DISK_FULL: u32 = 112;
const ERROR_DIR_NOT_EMPTY: u32 = 145;
pub(super) const ERROR_FILENAME_EXCED_RANGE: u32 = 206;
const ERROR_IO_DEVICE: u32 = 1117;
/// Default largest file guest writes may produce on a writable mount.
pub const DEFAULT_MAX_FILE_SIZE: u64 = 1 << 30;
/// Largest number of entries read from one host directory.
pub const MAX_DIRECTORY_ENTRIES: usize = 4096;
/// How much a guest may add to one writable mount while it is mounted.
///
/// Usage is net growth relative to the mount's contents when it was created:
/// bytes added by writes and extending truncation, minus bytes freed by
/// shrinking or deleting files, and entries created minus entries deleted.
/// Freeing never takes usage below zero, so deleting files that were already
/// there does not raise the limit beyond the configured amount. Changes made
/// by host processes are not counted.
#[derive(Debug)]
pub(super) struct Budget {
max_bytes: Option<u64>,
max_entries: Option<u64>,
used: Mutex<Usage>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Usage {
pub bytes: u64,
pub entries: u64,
}
impl Budget {
/// Account for a file changing from `from` to `to` bytes. Growth beyond
/// the byte limit fails with `ERROR_DISK_FULL` and charges nothing.
pub(super) fn resize(&self, from: u64, to: u64) -> Result<(), u32> {
let mut used = self.used.lock().expect("mount usage");
if to > from {
let bytes = used.bytes.checked_add(to - from).ok_or(ERROR_DISK_FULL)?;
if self.max_bytes.is_some_and(|max| bytes > max) {
return Err(ERROR_DISK_FULL);
}
used.bytes = bytes;
} else {
used.bytes = used.bytes.saturating_sub(from - to);
}
Ok(())
}
/// Reserve one new file or directory entry.
pub(super) fn add_entry(&self) -> Result<(), u32> {
let mut used = self.used.lock().expect("mount usage");
if self.max_entries.is_some_and(|max| used.entries >= max) {
return Err(ERROR_DISK_FULL);
}
used.entries += 1;
Ok(())
}
/// Release an entry, and the bytes of a file, that no longer exist.
pub(super) fn remove_entry(&self, bytes: u64) {
let mut used = self.used.lock().expect("mount usage");
used.entries = used.entries.saturating_sub(1);
used.bytes = used.bytes.saturating_sub(bytes);
}
fn usage(&self) -> Usage {
*self.used.lock().expect("mount usage")
}
}
/// A guest drive letter backed by a host directory.
pub struct HostMount {
drive: u8,
root: Arc<OwnedFd>,
writable: bool,
max_file_size: u64,
budget: Arc<Budget>,
}
impl HostMount {
/// Mount `root` as guest drive `drive`, which must be D: to Z:. The
/// directory is opened once; later changes to the host path name do not
/// move the mount.
pub fn new(drive: char, root: &Path, writable: bool) -> io::Result<Self> {
let drive = drive.to_ascii_lowercase();
if !('d'..='z').contains(&drive) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"host mounts use drive letters D: to Z:",
));
}
let path = CString::new(root.as_os_str().as_encoded_bytes())
.map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?;
// SAFETY: `path` is NUL-terminated; the result is checked.
// `O_NOFOLLOW` rejects a symlink at the final path component so a
// mount root cannot silently expand to another tree.
let fd = unsafe {
libc::open(
path.as_ptr(),
libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC | libc::O_NOFOLLOW,
)
};
if fd < 0 {
return Err(io::Error::last_os_error());
}
// SAFETY: `fd` is a newly opened descriptor owned by nothing else.
let root = unsafe { OwnedFd::from_raw_fd(fd) };
let st = status(root.as_fd())?;
if st.st_mode & libc::S_IFMT != libc::S_IFDIR {
return Err(io::Error::from_raw_os_error(libc::ENOTDIR));
}
Ok(Self {
drive: drive as u8,
root: Arc::new(root),
writable,
max_file_size: DEFAULT_MAX_FILE_SIZE,
budget: Arc::new(Budget {
max_bytes: None,
max_entries: None,
used: Mutex::default(),
}),
})
}
/// Limit the net bytes and the net number of files and directories guest
/// operations may add to this mount. `None` leaves that amount
/// unlimited; the per-file size limit still applies. Operations that
/// would exceed a limit fail with `ERROR_DISK_FULL`.
pub fn with_quota(mut self, bytes: Option<u64>, entries: Option<u64>) -> Self {
self.budget = Arc::new(Budget {
max_bytes: bytes,
max_entries: entries,
used: Mutex::default(),
});
self
}
/// Net bytes and entries guest operations have added so far.
pub fn usage(&self) -> Usage {
self.budget.usage()
}
pub(super) fn budget(&self) -> &Arc<Budget> {
&self.budget
}
/// Limit how large guest writes and truncation may make any file on this
/// mount. Files that are already larger stay readable.
pub fn with_max_file_size(mut self, bytes: u64) -> Self {
self.max_file_size = bytes;
self
}
pub fn max_file_size(&self) -> u64 {
self.max_file_size
}
pub fn drive(&self) -> char {
self.drive as char
}
pub fn writable(&self) -> bool {
self.writable
}
}
/// Win32 error for a host failure. Unknown errors keep a distinct generic code.
pub(super) fn win32_error(error: &io::Error) -> u32 {
match error.raw_os_error() {
Some(libc::ENOENT) => ERROR_FILE_NOT_FOUND,
Some(libc::ENOTDIR) => ERROR_PATH_NOT_FOUND,
Some(libc::EACCES | libc::EPERM | libc::EROFS | libc::ELOOP | libc::EISDIR) => {
ERROR_ACCESS_DENIED
}
Some(libc::EEXIST) => ERROR_FILE_EXISTS,
Some(libc::ENOSPC | libc::EDQUOT | libc::EFBIG) => ERROR_DISK_FULL,
Some(libc::ENOTEMPTY) => ERROR_DIR_NOT_EMPTY,
Some(libc::ENAMETOOLONG) => ERROR_FILENAME_EXCED_RANGE,
Some(libc::EINVAL) => 87, // ERROR_INVALID_PARAMETER
Some(libc::ENOMEM) => ERROR_NOT_ENOUGH_MEMORY,
Some(libc::EIO) => ERROR_IO_DEVICE,
_ => ERROR_GEN_FAILURE,
}
}
fn refused() -> io::Error {
io::Error::from_raw_os_error(libc::EACCES)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum Kind {
File,
Directory,
}
/// The host object a name refers to: device and inode.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) struct FileId {
device: u64,
inode: u64,
}
impl FileId {
/// A label for the handle table. Sharing compares live identities.
pub(super) fn key(self) -> String {
format!("host:{:x}:{:x}", self.device, self.inode)
}
}
#[derive(Debug)]
pub(super) struct Entry {
/// The host name, with its original case.
pub(super) name: String,
pub(super) kind: Kind,
pub(super) size: u64,
pub(super) times: [u64; 3],
pub(super) id: FileId,
}
/// Type, link count, size and identity of `stat`, or `None` for objects the
/// guest may not see.
fn classify(status: &libc::stat) -> Option<(Kind, u64, FileId)> {
let kind = match status.st_mode & libc::S_IFMT {
libc::S_IFREG if status.st_nlink == 1 => Kind::File,
libc::S_IFDIR => Kind::Directory,
_ => return None,
};
let id = FileId {
device: status.st_dev as u64,
inode: status.st_ino,
};
Some((kind, status.st_size as u64, id))
}
fn file_times(status: &libc::stat) -> [u64; 3] {
fn filetime(seconds: i64, nanoseconds: i64) -> u64 {
let ticks =
(i128::from(seconds) + 11_644_473_600) * 10_000_000 + i128::from(nanoseconds) / 100;
u64::try_from(ticks).unwrap_or(0)
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
let created = if status.st_birthtime == 0 && status.st_birthtime_nsec == 0 {
0
} else {
filetime(status.st_birthtime, status.st_birthtime_nsec)
};
#[cfg(target_os = "linux")]
let created = 0;
[
created,
filetime(status.st_atime, status.st_atime_nsec),
filetime(status.st_mtime, status.st_mtime_nsec),
]
}
fn status(fd: BorrowedFd<'_>) -> io::Result<libc::stat> {
let mut status = std::mem::MaybeUninit::<libc::stat>::uninit();
// SAFETY: `fd` is open and `status` has room for a stat.
if unsafe { libc::fstat(fd.as_raw_fd(), status.as_mut_ptr()) } != 0 {
return Err(io::Error::last_os_error());
}
// SAFETY: fstat succeeded and initialized `status`.
Ok(unsafe { status.assume_init() })
}
pub(super) fn open_file_times(file: &File) -> io::Result<[u64; 3]> {
status(file.as_fd()).map(|status| file_times(&status))
}
pub(super) fn set_open_file_times(file: &File, accessed: u64, modified: u64) -> io::Result<()> {
use std::fs::FileTimes;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
fn system_time(ticks: u64) -> io::Result<SystemTime> {
const UNIX_EPOCH_TICKS: u64 = 116_444_736_000_000_000;
let delta = ticks.abs_diff(UNIX_EPOCH_TICKS);
let duration = Duration::new(delta / 10_000_000, (delta % 10_000_000) as u32 * 100);
let result = if ticks >= UNIX_EPOCH_TICKS {
UNIX_EPOCH.checked_add(duration)
} else {
UNIX_EPOCH.checked_sub(duration)
};
result.ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL))
}
let mut times = FileTimes::new();
if accessed != 0 {
times = times.set_accessed(system_time(accessed)?);
}
if modified != 0 {
times = times.set_modified(system_time(modified)?);
}
file.set_times(times)
}
/// Check that an opened descriptor is still the object the listing reported.
fn verify(fd: &OwnedFd, kind: Kind, expected: Option<FileId>) -> io::Result<FileId> {
match classify(&status(fd.as_fd())?) {
Some((found, _, id)) if found == kind && expected.is_none_or(|expected| expected == id) => {
Ok(id)
}
_ => Err(refused()),
}
}
/// The current identity of an open host file. Some file systems, such as
/// exFAT, change a file's inode number when its storage is first allocated,
/// so identities are compared as they are now rather than as they were when
/// the file was opened.
/// `None` means the identity could not be read; callers must then treat the
/// file as possibly the same one.
pub(super) fn current_id(file: &File) -> Option<FileId> {
let status = status(file.as_fd()).ok()?;
Some(FileId {
device: status.st_dev as u64,
inode: status.st_ino,
})
}
fn clear_errno() {
// SAFETY: errno is thread-local and always writable.
#[cfg(any(target_os = "macos", target_os = "ios"))]
unsafe {
*libc::__error() = 0
};
// SAFETY: as above.
#[cfg(target_os = "linux")]
unsafe {
*libc::__errno_location() = 0
};
}
fn c_name(name: &str) -> io::Result<CString> {
CString::new(name).map_err(|_| io::Error::from_raw_os_error(libc::EINVAL))
}
fn open_at(directory: &OwnedFd, name: &str, flags: i32, mode: u32) -> io::Result<OwnedFd> {
let name = c_name(name)?;
// SAFETY: `name` is NUL-terminated and `directory` is an open descriptor.
let fd = unsafe {
libc::openat(
directory.as_raw_fd(),
name.as_ptr(),
flags | libc::O_NOFOLLOW | libc::O_CLOEXEC,
mode,
)
};
if fd < 0 {
return Err(io::Error::last_os_error());
}
// SAFETY: `fd` is a newly opened descriptor owned by nothing else.
Ok(unsafe { OwnedFd::from_raw_fd(fd) })
}
fn open_directory(parent: &OwnedFd, name: &str, expected: Option<FileId>) -> io::Result<OwnedFd> {
let directory = open_at(parent, name, libc::O_RDONLY | libc::O_DIRECTORY, 0)?;
verify(&directory, Kind::Directory, expected)?;
Ok(directory)
}
/// Visible entries of `directory`. Errors from reading the directory or from
/// examining an entry are returned, except an entry removed while listing.
pub(super) fn list(directory: &OwnedFd) -> io::Result<Vec<Entry>> {
// fdopendir takes ownership of its descriptor, so give it a duplicate.
// SAFETY: `directory` is open; the duplicate is checked.
let duplicate = unsafe { libc::fcntl(directory.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 0) };
if duplicate < 0 {
return Err(io::Error::last_os_error());
}
// SAFETY: `duplicate` is a directory descriptor owned by nothing else.
let stream = unsafe { libc::fdopendir(duplicate) };
if stream.is_null() {
let error = io::Error::last_os_error();
// SAFETY: fdopendir failed, so the duplicate is still ours to close.
unsafe { libc::close(duplicate) };
return Err(error);
}
// SAFETY: fdopendir shares the descriptor's offset with every duplicate.
unsafe { libc::rewinddir(stream) };
let mut entries = Vec::new();
let result = loop {
// readdir signals errors only through errno, so clear it first.
clear_errno();
// SAFETY: `stream` is a valid directory stream until closedir below.
let entry = unsafe { libc::readdir(stream) };
if entry.is_null() {
let error = io::Error::last_os_error();
break match error.raw_os_error() {
Some(0) | None => Ok(()),
Some(_) => Err(error),
};
}
// SAFETY: readdir returned a valid entry with a NUL-terminated name.
let raw = unsafe { CStr::from_ptr((*entry).d_name.as_ptr()) };
let Ok(name) = raw.to_str() else { continue };
if name == "." || name == ".." {
continue;
}
let mut status = std::mem::MaybeUninit::<libc::stat>::uninit();
// SAFETY: `raw` is NUL-terminated and `status` has room for a stat.
let found = unsafe {
libc::fstatat(
directory.as_raw_fd(),
raw.as_ptr(),
status.as_mut_ptr(),
libc::AT_SYMLINK_NOFOLLOW,
)
};
if found != 0 {
let error = io::Error::last_os_error();
if error.raw_os_error() == Some(libc::ENOENT) {
continue;
}
break Err(error);
}
// SAFETY: fstatat succeeded and initialized `status`.
let status = unsafe { status.assume_init() };
let Some((kind, size, id)) = classify(&status) else {
continue;
};
if entries.len() >= MAX_DIRECTORY_ENTRIES {
break Err(io::Error::from_raw_os_error(libc::ENOMEM));
}
entries.push(Entry {
name: name.to_owned(),
kind,
size,
times: file_times(&status),
id,
});
};
// SAFETY: `stream` is valid and closed exactly once.
unsafe { libc::closedir(stream) };
result.map(|()| entries)
}
/// The entry in `directory` whose name matches `component` ignoring ASCII
/// case. Two entries that differ only by case are ambiguous and refused.
fn find(directory: &OwnedFd, component: &str) -> io::Result<Option<Entry>> {
let mut matches = list(directory)?
.into_iter()
.filter(|entry| entry.name.eq_ignore_ascii_case(component));
let first = matches.next();
if matches.next().is_some() {
return Err(refused());
}
Ok(first)
}
/// A guest path on a mounted drive: the mount and its validated components.
pub(super) struct Resolved<'a> {
pub(super) mount: &'a HostMount,
pub(super) components: Vec<String>,
}
impl Resolved<'_> {
/// Open the directory holding the final component.
pub(super) fn parent(&self) -> Result<OwnedFd, u32> {
let parents = self
.components
.split_last()
.map_or(&[][..], |(_, parents)| parents);
self.walk(parents)
}
/// Open the directory the whole path names.
pub(super) fn directory(&self) -> Result<OwnedFd, u32> {
self.walk(&self.components)
}
fn walk(&self, components: &[String]) -> Result<OwnedFd, u32> {
let mut directory =
open_directory(&self.mount.root, ".", None).map_err(|error| win32_error(&error))?;
for component in components {
match find(&directory, component).map_err(|error| win32_error(&error))? {
Some(entry) if entry.kind == Kind::Directory => {
directory = open_directory(&directory, &entry.name, Some(entry.id))
.map_err(|error| win32_error(&error))?;
}
_ => return Err(ERROR_PATH_NOT_FOUND),
}
}
Ok(directory)
}
/// The final component's directory and existing entry, if any. The root
/// itself resolves to a directory with no name.
pub(super) fn lookup(&self) -> Result<(OwnedFd, Option<Entry>), u32> {
let parent = self.parent()?;
let Some(name) = self.components.last() else {
let status = status(parent.as_fd()).map_err(|error| win32_error(&error))?;
let Some((Kind::Directory, _, id)) = classify(&status) else {
return Err(win32_error(&refused()));
};
let root = Entry {
name: String::new(),
kind: Kind::Directory,
size: 0,
times: file_times(&status),
id,
};
return Ok((parent, Some(root)));
};
let entry = find(&parent, name).map_err(|error| win32_error(&error))?;
Ok((parent, entry))
}
}
/// Resolve `path`, which keeps its case, when it names a mounted drive.
/// `valid` checks each component against Windows naming rules.
pub(super) fn resolve<'a>(
mounts: &'a [HostMount],
path: &str,
valid: impl Fn(&str) -> bool,
) -> Option<Result<Resolved<'a>, u32>> {
let bytes = path.as_bytes();
if bytes.len() < 2 || bytes[1] != b':' {
return None;
}
let drive = bytes[0].to_ascii_lowercase();
let mount = mounts.iter().find(|mount| mount.drive == drive)?;
let Some(rest) = path[2..].strip_prefix('\\') else {
// Drive-relative paths such as "D:file" depend on a current directory.
return Some(Err(ERROR_PATH_NOT_FOUND));
};
let components: Vec<String> = rest
.split('\\')
.filter(|component| !component.is_empty())
.map(str::to_owned)
.collect();
if !components
.iter()
.all(|component| valid(&component.to_ascii_lowercase()))
{
return Some(Err(123)); // ERROR_INVALID_NAME
}
Some(Ok(Resolved { mount, components }))
}
pub(super) struct OpenRequest {
pub(super) read: bool,
pub(super) write: bool,
pub(super) create: bool,
}
/// Open `name` in `directory`, creating it exclusively when it did not exist,
/// and check the result is the regular file `expected` names.
pub(super) fn open_file(
directory: &OwnedFd,
name: &str,
request: &OpenRequest,
expected: Option<FileId>,
) -> io::Result<(File, FileId)> {
let mut flags = match (request.read, request.write) {
(_, false) => libc::O_RDONLY,
(false, true) => libc::O_WRONLY,
(true, true) => libc::O_RDWR,
};
if request.create {
flags |= libc::O_CREAT | libc::O_EXCL;
}
let fd = open_at(directory, name, flags, 0o644)?;
let id = verify(&fd, Kind::File, expected)?;
Ok((File::from(fd), id))
}
pub(super) fn create_directory(directory: &OwnedFd, name: &str) -> io::Result<()> {
let name = c_name(name)?;
// SAFETY: `name` is NUL-terminated and `directory` is open.
if unsafe { libc::mkdirat(directory.as_raw_fd(), name.as_ptr(), 0o755) } != 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
/// Remove the entry `name` after checking it is still the object `expected`.
///
/// Removal is always name-based `unlinkat` after re-checking the directory
/// listing. A concurrent host rename between that check and the unlink can
/// still remove a different in-tree entry (never one outside the root). Host
/// writers under the mount are trusted for that residual race. After a file
/// unlink, the held descriptor must show `nlink == 0` or the call fails, so a
/// lost race on a file is not reported as success; directories have no such
/// post-check.
pub(super) fn remove(directory: &OwnedFd, name: &str, expected: &Entry) -> io::Result<()> {
let opened = match expected.kind {
Kind::Directory => open_directory(directory, name, Some(expected.id))?,
Kind::File => open_at(directory, name, libc::O_RDONLY, 0)?,
};
verify(&opened, expected.kind, Some(expected.id))?;
// Confirm the directory entry still names this object before unlinking.
match find(directory, name)? {
Some(entry) if entry.id == expected.id && entry.kind == expected.kind => {}
_ => return Err(refused()),
}
let cname = c_name(name)?;
let flags = match expected.kind {
Kind::Directory => libc::AT_REMOVEDIR,
Kind::File => 0,
};
// SAFETY: `cname` is NUL-terminated and `directory` is open.
if unsafe { libc::unlinkat(directory.as_raw_fd(), cname.as_ptr(), flags) } != 0 {
return Err(io::Error::last_os_error());
}
if expected.kind == Kind::File {
let st = status(opened.as_fd())?;
if st.st_nlink != 0 {
// Name-based unlink hit a different dentry; the intended file is
// still linked.
return Err(refused());
}
}
Ok(())
}
/// Rename `from` in `source` to `to` in `target`, after checking the source
/// entry is still the object `expected`. The target name must not exist,
/// except when it names the source itself (a change of case only) or the
/// regular file `replacing`, which the rename then replaces atomically.
///
/// The exclusive rename is atomic on the host, so a concurrent host change
/// cannot make the guest replace an existing entry. As with [`remove`], the
/// source is matched by name after the final listing check, so a concurrent
/// host rename in that window can move a different in-tree entry.
pub(super) fn rename(
source: &OwnedFd,
from: &str,
expected: &Entry,
target: &OwnedFd,
to: &str,
replacing: Option<&Entry>,
) -> io::Result<()> {
match find(source, from)? {
Some(entry) if entry.id == expected.id && entry.kind == expected.kind => {}
_ => return Err(refused()),
}
let overwrite = match find(target, to)? {
Some(entry) if entry.id == expected.id => true,
Some(entry)
if replacing.is_some_and(|old| old.id == entry.id)
&& entry.kind == Kind::File
&& expected.kind == Kind::File =>
{
true
}
Some(_) => return Err(io::Error::from_raw_os_error(libc::EEXIST)),
None => false,
};
let from = c_name(from)?;
let to = c_name(to)?;
// SAFETY: both names are NUL-terminated and both directories are open.
let result = unsafe {
if overwrite {
libc::renameat(
source.as_raw_fd(),
from.as_ptr(),
target.as_raw_fd(),
to.as_ptr(),
)
} else {
exclusive_rename(source.as_raw_fd(), &from, target.as_raw_fd(), &to)
}
};
if result != 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
/// Flush a directory's entries to stable storage.
pub(super) fn sync_directory(directory: &OwnedFd) -> io::Result<()> {
// SAFETY: `directory` is an open descriptor.
if unsafe { libc::fsync(directory.as_raw_fd()) } != 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
/// `renameat` that fails with `EEXIST` instead of replacing the target.
///
/// # Safety
/// Both descriptors must be open directories.
unsafe fn exclusive_rename(source: i32, from: &CStr, target: i32, to: &CStr) -> i32 {
#[cfg(any(target_os = "macos", target_os = "ios"))]
// SAFETY: guaranteed by the caller; the names are NUL-terminated.
unsafe {
libc::renameatx_np(
source,
from.as_ptr(),
target,
to.as_ptr(),
libc::RENAME_EXCL,
)
}
#[cfg(target_os = "linux")]
// SAFETY: as above.
unsafe {
libc::renameat2(
source,
from.as_ptr(),
target,
to.as_ptr(),
libc::RENAME_NOREPLACE,
)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn tree(name: &str) -> std::path::PathBuf {
let base = std::env::var_os("XENORA_TEST_TMP").map_or_else(
|| std::path::PathBuf::from("/tmp"),
std::path::PathBuf::from,
);
let path = base.join(format!("xenora-host-unit-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).unwrap();
path
}
fn root(path: &Path) -> OwnedFd {
open_directory(&HostMount::new('d', path, true).unwrap().root, ".", None).unwrap()
}
#[test]
fn an_entry_swapped_after_listing_is_refused() {
let path = tree("swap");
std::fs::create_dir(path.join("Data")).unwrap();
std::fs::write(path.join("file.bin"), b"a").unwrap();
std::fs::create_dir(path.join("outside")).unwrap();
let fd = root(&path);
let data = find(&fd, "data").unwrap().unwrap();
let file = find(&fd, "FILE.BIN").unwrap().unwrap();
// Swap both entries between the listing and the open.
std::fs::rename(path.join("Data"), path.join("Moved")).unwrap();
std::fs::rename(path.join("outside"), path.join("Data")).unwrap();
std::fs::rename(path.join("file.bin"), path.join("old.bin")).unwrap();
std::fs::write(path.join("file.bin"), b"replacement").unwrap();
let error = open_directory(&fd, &data.name, Some(data.id)).unwrap_err();
assert_eq!(error.raw_os_error(), Some(libc::EACCES));
let request = OpenRequest {
read: true,
write: false,
create: false,
};
let error = open_file(&fd, &file.name, &request, Some(file.id)).unwrap_err();
assert_eq!(error.raw_os_error(), Some(libc::EACCES));
let error = remove(&fd, &file.name, &file).unwrap_err();
assert_eq!(error.raw_os_error(), Some(libc::EACCES));
assert_eq!(
std::fs::read(path.join("file.bin")).unwrap(),
b"replacement"
);
std::fs::remove_dir_all(&path).unwrap();
}
#[test]
fn read_only_opens_cannot_write_at_the_host_level() {
use std::os::unix::fs::FileExt;
let path = tree("read-only");
std::fs::write(path.join("file.bin"), b"keep").unwrap();
let fd = root(&path);
let entry = find(&fd, "file.bin").unwrap().unwrap();
let request = OpenRequest {
read: true,
write: false,
create: false,
};
let (file, _) = open_file(&fd, &entry.name, &request, Some(entry.id)).unwrap();
assert!(file.write_at(b"x", 0).is_err());
assert!(file.set_len(0).is_err());
assert_eq!(std::fs::read(path.join("file.bin")).unwrap(), b"keep");
std::fs::remove_dir_all(&path).unwrap();
}
#[test]
fn ambiguous_case_variants_are_refused() {
let path = tree("case");
std::fs::write(path.join("a.txt"), b"1").unwrap();
if std::fs::write(path.join("A.TXT"), b"2").is_ok()
&& std::fs::read(path.join("a.txt")).unwrap() == b"1"
{
// Only a case-sensitive file system can hold both names.
assert_eq!(
find(&root(&path), "a.txt").unwrap_err().raw_os_error(),
Some(libc::EACCES)
);
}
std::fs::remove_dir_all(&path).unwrap();
}
#[test]
fn budgets_charge_net_growth_and_never_credit_below_zero() {
let budget = Budget {
max_bytes: Some(10),
max_entries: Some(1),
used: Mutex::default(),
};
assert_eq!(budget.resize(0, 10), Ok(()));
assert_eq!(budget.resize(10, 11), Err(ERROR_DISK_FULL));
assert_eq!(budget.usage().bytes, 10);
// Shrinking a larger file that predates the mount frees at most what
// was charged.
assert_eq!(budget.resize(100, 0), Ok(()));
assert_eq!(budget.usage().bytes, 0);
assert_eq!(budget.resize(u64::MAX - 1, u64::MAX), Ok(()));
assert_eq!(budget.resize(0, u64::MAX), Err(ERROR_DISK_FULL));
assert_eq!(budget.add_entry(), Ok(()));
assert_eq!(budget.add_entry(), Err(ERROR_DISK_FULL));
budget.remove_entry(5);
budget.remove_entry(5);
assert_eq!(
budget.usage(),
Usage {
bytes: 0,
entries: 0
}
);
let unlimited = HostMount::new('d', Path::new("/"), true).unwrap();
assert_eq!(unlimited.budget().resize(0, u64::MAX), Ok(()));
}
#[test]
fn symlink_mount_roots_are_rejected() {
let path = tree("symlink-root");
std::fs::create_dir(path.join("real")).unwrap();
std::os::unix::fs::symlink(path.join("real"), path.join("link")).unwrap();
match HostMount::new('d', &path.join("link"), false) {
Ok(_) => panic!("symlink mount root should be rejected"),
// Darwin may report ENOTDIR instead of ELOOP for
// O_DIRECTORY|O_NOFOLLOW on a symlink.
Err(error) => assert!(
matches!(error.raw_os_error(), Some(libc::ELOOP | libc::ENOTDIR)),
"{error}"
),
}
assert!(HostMount::new('d', &path.join("real"), false).is_ok());
std::fs::remove_dir_all(&path).unwrap();
}
}
+100 -5
View File
@@ -14,7 +14,10 @@ const LOADER_API: &str = "api-ms-win-core-libraryloader-l1-2-0.dll";
const UCRT: &str = "ucrtbase.dll";
const MODULE_NOT_FOUND: u32 = 126;
const PROCEDURE_NOT_FOUND: u32 = 127;
const ERROR_INSUFFICIENT_BUFFER: u32 = 122;
const MODULE_BASE: u64 = 0x0000_0007_e000_0000;
/// Synthetic path for the running guest image (`GetModuleFileName(NULL, …)`).
const GUEST_IMAGE_PATH: &str = r"C:\xenora\guest.exe";
#[derive(Default)]
struct Modules {
@@ -50,6 +53,23 @@ fn read_name(
Ok(None)
}
fn synthetic_module_path(modules: &Modules, handle: u64) -> Option<String> {
if handle == 0 {
return Some(GUEST_IMAGE_PATH.to_owned());
}
let mut canonical = None;
for (name, &mapped) in &modules.names {
if mapped != handle {
continue;
}
if name.ends_with(".dll") && !name.starts_with("api-ms-") {
canonical = Some(name.clone());
break;
}
}
canonical.map(|name| format!(r"C:\Windows\System32\{name}"))
}
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
let modules = Arc::new(OnceLock::<Modules>::new());
let named_operations = [
@@ -112,12 +132,12 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
let lookup = Arc::clone(&modules);
let trampolines = registry.dynamic_trampolines();
let state = Arc::clone(state);
let proc_state = Arc::clone(state);
registry.register(KERNEL32, "GetProcAddress", move |args, cpu, memory| {
let modules = lookup.get().expect("built-in module catalog");
let references = modules.references.lock().expect("module references");
if args.rcx != MODULE_BASE && !references.contains_key(&args.rcx) {
return state.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
return proc_state.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
}
let export = if let Ok(ordinal) = u16::try_from(args.rdx) {
ImportName::Ordinal(ordinal)
@@ -125,20 +145,67 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
let Some(symbol) =
read_name(memory, args.rdx, false).map_err(ExitReason::MemoryFault)?
else {
return state.fail(cpu.gs_base, PROCEDURE_NOT_FOUND, 0);
return proc_state.fail(cpu.gs_base, PROCEDURE_NOT_FOUND, 0);
};
ImportName::Name(symbol)
};
match modules.exports[&args.rcx].get(&export) {
Some(&index) => Ok(trampolines.expose(index)),
None => state.fail(cpu.gs_base, PROCEDURE_NOT_FOUND, 0),
None => proc_state.fail(cpu.gs_base, PROCEDURE_NOT_FOUND, 0),
}
});
for (symbol, wide) in [("GetModuleFileNameA", false), ("GetModuleFileNameW", true)] {
let file_state = Arc::clone(state);
let modules = Arc::clone(&modules);
registry.register(KERNEL32, symbol, move |args, cpu, memory| {
let (handle, buffer, size) = (args.rcx, args.rdx, args.r8 as u32);
let modules = modules.get().expect("built-in module catalog");
let Some(path) = synthetic_module_path(modules, handle) else {
return file_state.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
};
let units: Vec<u16> = if wide {
path.encode_utf16().collect()
} else {
path.bytes().map(u16::from).collect()
};
let needed = units.len() + 1;
if buffer == 0 || size == 0 {
return Ok(needed as u64);
}
let copy = (size as usize).saturating_sub(1).min(units.len());
if wide {
for (index, unit) in units[..copy].iter().enumerate() {
memory
.write_u16(buffer + index as u64 * 2, *unit)
.map_err(ExitReason::MemoryFault)?;
}
memory
.write_u16(buffer + copy as u64 * 2, 0)
.map_err(ExitReason::MemoryFault)?;
} else {
let mut bytes: Vec<u8> = units[..copy].iter().map(|u| *u as u8).collect();
bytes.push(0);
memory
.write_bytes(buffer, &bytes)
.map_err(ExitReason::MemoryFault)?;
}
if (size as usize) < needed {
return file_state.fail(cpu.gs_base, ERROR_INSUFFICIENT_BUFFER, size as u64);
}
Ok(units.len() as u64)
});
}
for symbol in named_operations
.map(|(symbol, _, _)| symbol)
.into_iter()
.chain(["GetProcAddress", "FreeLibrary"])
.chain([
"GetProcAddress",
"FreeLibrary",
"GetModuleFileNameA",
"GetModuleFileNameW",
])
{
registry.alias(LOADER_API, KERNEL32, symbol);
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
@@ -236,5 +303,33 @@ mod tests {
registry.dispatch(ordinal, &mut cpu, &mut memory).unwrap();
assert_eq!(cpu.get(Register::Rax), 42);
assert_eq!(cpu.rip, 0x1234);
let mut cpu = CpuState::default();
cpu.set(Register::Rcx, 0);
cpu.set(Register::Rdx, 0x10500);
cpu.set(Register::R8, 64);
let service = registry
.resolve(LOADER_API, &ImportName::Name("GetModuleFileNameA".into()))
.unwrap();
let written =
(service.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory).unwrap() as usize;
assert_eq!(written, GUEST_IMAGE_PATH.len());
let mut bytes = vec![0u8; written + 1];
memory.read_bytes(0x10500, &mut bytes).unwrap();
assert_eq!(
std::str::from_utf8(&bytes[..written]).unwrap(),
GUEST_IMAGE_PATH
);
cpu.set(Register::Rcx, MODULE_BASE);
cpu.set(Register::Rdx, 0x10600);
cpu.set(Register::R8, 64);
let written =
(service.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory).unwrap() as usize;
let mut bytes = vec![0u8; written + 1];
memory.read_bytes(0x10600, &mut bytes).unwrap();
assert_eq!(
std::str::from_utf8(&bytes[..written]).unwrap(),
r"C:\Windows\System32\kernel32.dll"
);
}
}
+531 -402
View File
@@ -1,402 +1,531 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! System information, calendar time and sleeping.
//!
//! The guest sees a simulated machine described by [`GuestSystemProfile`].
//! [`HostCapabilities`] reports what the Mac actually has. The two are kept
//! separate so detected host hardware is never presented to the guest as its
//! own, and guest-visible values do not change from one Mac to another.
use super::{ERROR_INVALID_PARAMETER, KERNEL32, ServicesState};
use crate::cpu::ExitReason;
use crate::imports::{ImportRegistry, ServiceStatus};
use crate::memory::{ALLOCATION_GRANULARITY, DYNAMIC_BUDGET, GuestMemory, MemoryError};
use std::sync::Arc;
const SYSINFO_API: &str = "api-ms-win-core-sysinfo-l1-1-0.dll";
const SYSINFO_API_2: &str = "api-ms-win-core-sysinfo-l1-2-0.dll";
const TIMEZONE_API: &str = "api-ms-win-core-timezone-l1-1-0.dll";
const SYNCH_API: &str = "api-ms-win-core-synch-l1-1-0.dll";
const SYNCH_API_2: &str = "api-ms-win-core-synch-l1-2-0.dll";
const REALTIME_API: &str = "api-ms-win-core-realtime-l1-1-0.dll";
const PROCESSOR_ARCHITECTURE_AMD64: u16 = 9;
const PROCESSOR_AMD_X8664: u32 = 8664;
const GUEST_PAGE_SIZE: u32 = 4096;
/// The x64 Windows user address range.
const MINIMUM_APPLICATION_ADDRESS: u64 = 0x1_0000;
const MAXIMUM_APPLICATION_ADDRESS: u64 = 0x7fff_fffe_ffff;
const MEMORYSTATUSEX_SIZE: u32 = 64;
const INFINITE: u32 = u32::MAX;
/// Longest sleep the runtime performs. A single guest thread sleeping longer
/// is reported rather than silently shortened.
const MAX_SLEEP_MILLIS: u32 = 10_000;
const TICKS_PER_MILLI: u64 = 10_000;
const MILLIS_PER_DAY: u64 = 86_400_000;
/// Days from 1601-01-01 to 1970-01-01.
const DAYS_1601_TO_1970: i64 = 134_774;
/// FILETIME values at or above this are rejected by FileTimeToSystemTime.
const MAX_FILETIME: u64 = 0x8000_0000_0000_0000;
/// What the guest is told about the machine it runs on.
#[derive(Clone, Debug)]
pub struct GuestSystemProfile {
/// Reported processors. One, because guest code runs on one thread at a time.
pub processors: u32,
}
impl Default for GuestSystemProfile {
fn default() -> Self {
Self { processors: 1 }
}
}
/// Hardware detected on the host Mac. Never reported to the guest.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HostCapabilities {
pub logical_processors: Option<u64>,
pub physical_memory: Option<u64>,
pub page_size: Option<u64>,
}
impl HostCapabilities {
pub fn detect() -> Self {
let logical_processors = std::thread::available_parallelism()
.ok()
.map(|count| count.get() as u64);
// SAFETY: sysconf takes no pointers.
let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
Self {
logical_processors,
physical_memory: physical_memory(),
page_size: u64::try_from(page_size).ok().filter(|&size| size > 0),
}
}
}
#[cfg(target_os = "macos")]
fn physical_memory() -> Option<u64> {
let mut bytes = 0u64;
let mut size = std::mem::size_of::<u64>();
// SAFETY: the name is NUL-terminated and the output buffer is a u64 whose
// size is passed in `size`; no new value is written.
let status = unsafe {
libc::sysctlbyname(
c"hw.memsize".as_ptr(),
(&raw mut bytes).cast(),
&raw mut size,
std::ptr::null_mut(),
0,
)
};
(status == 0 && size == std::mem::size_of::<u64>()).then_some(bytes)
}
#[cfg(not(target_os = "macos"))]
fn physical_memory() -> Option<u64> {
None
}
/// A Windows `SYSTEMTIME`, in field order.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct SystemTime {
year: u16,
month: u16,
day_of_week: u16,
day: u16,
hour: u16,
minute: u16,
second: u16,
milliseconds: u16,
}
impl SystemTime {
fn to_bytes(self) -> [u8; 16] {
let fields = [
self.year,
self.month,
self.day_of_week,
self.day,
self.hour,
self.minute,
self.second,
self.milliseconds,
];
let mut bytes = [0; 16];
for (chunk, field) in bytes.as_chunks_mut::<2>().0.iter_mut().zip(fields) {
*chunk = field.to_le_bytes();
}
bytes
}
fn from_bytes(bytes: [u8; 16]) -> Self {
let field = |index: usize| u16::from_le_bytes([bytes[2 * index], bytes[2 * index + 1]]);
Self {
year: field(0),
month: field(1),
day_of_week: field(2),
day: field(3),
hour: field(4),
minute: field(5),
second: field(6),
milliseconds: field(7),
}
}
}
/// Proleptic Gregorian date for a day count relative to 1970-01-01.
fn civil_from_days(days: i64) -> (i64, u16, u16) {
let shifted = days + 719_468;
let era = shifted.div_euclid(146_097);
let day_of_era = shifted.rem_euclid(146_097);
let year_of_era =
(day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let month_index = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * month_index + 2) / 5 + 1;
let month = if month_index < 10 {
month_index + 3
} else {
month_index - 9
};
let year = year_of_era + era * 400 + i64::from(month <= 2);
(year, month as u16, day as u16)
}
fn days_from_civil(year: i64, month: u16, day: u16) -> i64 {
let year = year - i64::from(month <= 2);
let era = year.div_euclid(400);
let year_of_era = year - era * 400;
let month_index = (i64::from(month) + 9) % 12;
let day_of_year = (153 * month_index + 2) / 5 + i64::from(day) - 1;
let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
era * 146_097 + day_of_era - 719_468
}
fn is_leap(year: u16) -> bool {
year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400))
}
fn days_in_month(year: u16, month: u16) -> u16 {
match month {
2 if is_leap(year) => 29,
2 => 28,
4 | 6 | 9 | 11 => 30,
_ => 31,
}
}
fn filetime_to_system_time(filetime: u64) -> Option<SystemTime> {
if filetime >= MAX_FILETIME {
return None;
}
let millis = filetime / TICKS_PER_MILLI;
let days = (millis / MILLIS_PER_DAY) as i64;
let of_day = millis % MILLIS_PER_DAY;
let (year, month, day) = civil_from_days(days - DAYS_1601_TO_1970);
Some(SystemTime {
year: year as u16,
month,
// 1601-01-01 was a Monday, and Sunday is zero.
day_of_week: ((days + 1) % 7) as u16,
day,
hour: (of_day / 3_600_000) as u16,
minute: (of_day / 60_000 % 60) as u16,
second: (of_day / 1000 % 60) as u16,
milliseconds: (of_day % 1000) as u16,
})
}
/// The day of week is ignored, as documented for SystemTimeToFileTime.
fn system_time_to_filetime(time: SystemTime) -> Option<u64> {
let valid = (1601..=30827).contains(&time.year)
&& (1..=12).contains(&time.month)
&& (1..=days_in_month(time.year, time.month)).contains(&time.day)
&& time.hour < 24
&& time.minute < 60
&& time.second < 60
&& time.milliseconds < 1000;
if !valid {
return None;
}
let days = days_from_civil(i64::from(time.year), time.month, time.day) + DAYS_1601_TO_1970;
let millis = days as u64 * MILLIS_PER_DAY
+ u64::from(time.hour) * 3_600_000
+ u64::from(time.minute) * 60_000
+ u64::from(time.second) * 1000
+ u64::from(time.milliseconds);
Some(millis * TICKS_PER_MILLI)
}
fn fault(error: MemoryError) -> ExitReason {
ExitReason::MemoryFault(error)
}
fn write_system_info(
state: &ServicesState,
memory: &mut GuestMemory,
address: u64,
) -> Result<(), ExitReason> {
let processors = state.guest_profile.processors.clamp(1, 64);
let mask = u64::MAX >> (64 - processors);
let mut info = [0u8; 48];
info[0..2].copy_from_slice(&PROCESSOR_ARCHITECTURE_AMD64.to_le_bytes());
info[4..8].copy_from_slice(&GUEST_PAGE_SIZE.to_le_bytes());
info[8..16].copy_from_slice(&MINIMUM_APPLICATION_ADDRESS.to_le_bytes());
info[16..24].copy_from_slice(&MAXIMUM_APPLICATION_ADDRESS.to_le_bytes());
info[24..32].copy_from_slice(&mask.to_le_bytes());
info[32..36].copy_from_slice(&processors.to_le_bytes());
info[36..40].copy_from_slice(&PROCESSOR_AMD_X8664.to_le_bytes());
info[40..44].copy_from_slice(&(ALLOCATION_GRANULARITY as u32).to_le_bytes());
// wProcessorLevel and wProcessorRevision stay zero: no CPU model is simulated.
memory.write_bytes(address, &info).map_err(fault)
}
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
for symbol in ["GetSystemInfo", "GetNativeSystemInfo"] {
let s = Arc::clone(state);
registry.register(KERNEL32, symbol, move |args, _, mem| {
write_system_info(&s, mem, args.rcx)?;
Ok(0)
});
}
let s = Arc::clone(state);
registry.register(KERNEL32, "GlobalMemoryStatusEx", move |args, cpu, mem| {
let address = args.rcx;
if mem.read_u32(address).map_err(fault)? != MEMORYSTATUSEX_SIZE {
return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
}
let (mapped, virtual_bytes, heap_bytes) = mem.usage();
// Guest physical memory is the virtual-allocation and heap budgets;
// there is no paging file.
let total = 2 * DYNAMIC_BUDGET;
let used = (virtual_bytes + heap_bytes).min(total);
let total_virtual = MAXIMUM_APPLICATION_ADDRESS - MINIMUM_APPLICATION_ADDRESS + 1;
let mut status = [0u8; 64];
status[0..4].copy_from_slice(&MEMORYSTATUSEX_SIZE.to_le_bytes());
status[4..8].copy_from_slice(&((used * 100 / total) as u32).to_le_bytes());
for (offset, value) in [
(8, total),
(16, total - used),
(24, total),
(32, total - used),
(40, total_virtual),
(48, total_virtual.saturating_sub(mapped)),
] {
status[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
}
mem.write_bytes(address, &status).map_err(fault)?;
Ok(1)
});
// The guest time zone is UTC, so local time equals system time.
for symbol in ["GetSystemTime", "GetLocalTime"] {
let s = Arc::clone(state);
registry.register(KERNEL32, symbol, move |args, _, mem| {
let time = filetime_to_system_time(s.clock.now_filetime())
.ok_or(ExitReason::IllegalInstruction(0xFE))?;
mem.write_bytes(args.rcx, &time.to_bytes()).map_err(fault)?;
Ok(0)
});
}
let s = Arc::clone(state);
registry.register(
KERNEL32,
"GetSystemTimePreciseAsFileTime",
move |args, _, mem| {
mem.write_u64(args.rcx, s.clock.now_filetime())
.map_err(fault)?;
Ok(0)
},
);
let s = Arc::clone(state);
registry.register(KERNEL32, "FileTimeToSystemTime", move |args, cpu, mem| {
let filetime = mem.read_u64(args.rcx).map_err(fault)?;
let Some(time) = filetime_to_system_time(filetime) else {
return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
};
mem.write_bytes(args.rdx, &time.to_bytes()).map_err(fault)?;
Ok(1)
});
let s = Arc::clone(state);
registry.register(KERNEL32, "SystemTimeToFileTime", move |args, cpu, mem| {
let mut bytes = [0; 16];
mem.read_bytes(args.rcx, &mut bytes).map_err(fault)?;
let Some(filetime) = system_time_to_filetime(SystemTime::from_bytes(bytes)) else {
return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
};
mem.write_u64(args.rdx, filetime).map_err(fault)?;
Ok(1)
});
let s = Arc::clone(state);
registry.register(
KERNEL32,
"QueryUnbiasedInterruptTime",
move |args, _, mem| {
let elapsed = s.clock.performance_count().saturating_sub(s.clock_origin);
mem.write_u64(args.rcx, elapsed).map_err(fault)?;
Ok(1)
},
);
// No APCs can be queued, so an alertable SleepEx always runs to completion
// and returns zero rather than WAIT_IO_COMPLETION.
for symbol in ["Sleep", "SleepEx"] {
let s = Arc::clone(state);
registry.register(KERNEL32, symbol, move |args, _, _| {
let millis = args.rcx as u32;
if millis == INFINITE || millis > MAX_SLEEP_MILLIS {
return Err(ExitReason::IllegalInstruction(0xFE));
}
s.clock.sleep(u64::from(millis) * TICKS_PER_MILLI);
Ok(0)
});
}
for (symbol, api_set) in [
("GetSystemInfo", SYSINFO_API),
("GetNativeSystemInfo", SYSINFO_API_2),
("GlobalMemoryStatusEx", SYSINFO_API),
("GetSystemTime", SYSINFO_API),
("GetLocalTime", SYSINFO_API),
("GetSystemTimePreciseAsFileTime", SYSINFO_API_2),
("FileTimeToSystemTime", TIMEZONE_API),
("SystemTimeToFileTime", TIMEZONE_API),
("QueryUnbiasedInterruptTime", REALTIME_API),
("Sleep", SYNCH_API_2),
("SleepEx", SYNCH_API),
] {
registry.alias(api_set, KERNEL32, symbol);
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn calendar_conversion_round_trips_across_leap_and_century_boundaries() {
for days in (-DAYS_1601_TO_1970..2_000_000).step_by(997) {
let (year, month, day) = civil_from_days(days);
assert_eq!(days_from_civil(year, month, day), days);
}
assert!(is_leap(2000) && is_leap(2024) && !is_leap(1900) && !is_leap(2100));
}
#[test]
fn host_capabilities_are_detected_on_this_mac() {
let host = HostCapabilities::detect();
assert!(host.logical_processors.unwrap() >= 1);
assert!(host.page_size.unwrap() >= 4096);
#[cfg(target_os = "macos")]
assert!(host.physical_memory.unwrap() >= 1 << 30);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
//! System information, calendar time and sleeping.
//!
//! The guest sees a simulated machine described by [`GuestSystemProfile`].
//! [`HostCapabilities`] reports what the Mac actually has. The two are kept
//! separate so detected host hardware is never presented to the guest as its
//! own, and guest-visible values do not change from one Mac to another.
use super::{ERROR_INVALID_PARAMETER, ERROR_NOACCESS, KERNEL32, ServicesState};
use crate::cpu::ExitReason;
use crate::imports::{ImportRegistry, ServiceStatus};
use crate::memory::{ALLOCATION_GRANULARITY, DYNAMIC_BUDGET, GuestMemory, MemoryError};
use std::sync::Arc;
const SYSINFO_API: &str = "api-ms-win-core-sysinfo-l1-1-0.dll";
const SYSINFO_API_2: &str = "api-ms-win-core-sysinfo-l1-2-0.dll";
const TIMEZONE_API: &str = "api-ms-win-core-timezone-l1-1-0.dll";
const SYNCH_API: &str = "api-ms-win-core-synch-l1-1-0.dll";
const SYNCH_API_2: &str = "api-ms-win-core-synch-l1-2-0.dll";
const REALTIME_API: &str = "api-ms-win-core-realtime-l1-1-0.dll";
const PROCESSOR_ARCHITECTURE_AMD64: u16 = 9;
const PROCESSOR_AMD_X8664: u32 = 8664;
const GUEST_PAGE_SIZE: u32 = 4096;
/// The x64 Windows user address range.
const MINIMUM_APPLICATION_ADDRESS: u64 = 0x1_0000;
const MAXIMUM_APPLICATION_ADDRESS: u64 = 0x7fff_fffe_ffff;
const MEMORYSTATUSEX_SIZE: u32 = 64;
const INFINITE: u32 = u32::MAX;
/// Longest sleep the runtime performs. A single guest thread sleeping longer
/// is reported rather than silently shortened.
const MAX_SLEEP_MILLIS: u32 = 10_000;
const TICKS_PER_MILLI: u64 = 10_000;
const MILLIS_PER_DAY: u64 = 86_400_000;
/// Days from 1601-01-01 to 1970-01-01.
const DAYS_1601_TO_1970: i64 = 134_774;
/// FILETIME values at or above this are rejected by FileTimeToSystemTime.
const MAX_FILETIME: u64 = 0x8000_0000_0000_0000;
const TIME_ZONE_INFORMATION_SIZE: usize = 172;
const TIME_ZONE_ID_UNKNOWN: u32 = 0;
const TIME_ZONE_ID_INVALID: u32 = u32::MAX;
const UTC_NAME: &str = "Coordinated Universal Time";
const ERROR_INSUFFICIENT_BUFFER: u32 = 122;
/// `SYSTEM_LOGICAL_PROCESSOR_INFORMATION` on x64.
const PROCESSOR_INFO_SIZE: usize = 32;
const RELATION_PROCESSOR_CORE: u32 = 0;
const RELATION_PROCESSOR_PACKAGE: u32 = 3;
/// One core per guest processor and one package holding them all. No cache
/// or NUMA entries are reported, because no cache hierarchy is simulated.
fn processor_topology(processors: u32) -> Vec<[u8; PROCESSOR_INFO_SIZE]> {
let entry = |mask: u64, relationship: u32| {
let mut bytes = [0u8; PROCESSOR_INFO_SIZE];
bytes[..8].copy_from_slice(&mask.to_le_bytes());
bytes[8..12].copy_from_slice(&relationship.to_le_bytes());
bytes
};
let mut entries: Vec<_> = (0..processors)
.map(|index| entry(1 << index, RELATION_PROCESSOR_CORE))
.collect();
let all = if processors == 64 {
u64::MAX
} else {
(1 << processors) - 1
};
entries.push(entry(all, RELATION_PROCESSOR_PACKAGE));
entries
}
/// What the guest is told about the machine it runs on.
#[derive(Clone, Debug)]
pub struct GuestSystemProfile {
/// Reported processors. One, because guest code runs on one thread at a time.
pub processors: u32,
}
impl Default for GuestSystemProfile {
fn default() -> Self {
Self { processors: 1 }
}
}
/// Hardware detected on the host Mac. Never reported to the guest.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HostCapabilities {
pub logical_processors: Option<u64>,
pub physical_memory: Option<u64>,
pub page_size: Option<u64>,
}
impl HostCapabilities {
pub fn detect() -> Self {
let logical_processors = std::thread::available_parallelism()
.ok()
.map(|count| count.get() as u64);
// SAFETY: sysconf takes no pointers.
let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
Self {
logical_processors,
physical_memory: physical_memory(),
page_size: u64::try_from(page_size).ok().filter(|&size| size > 0),
}
}
}
#[cfg(target_os = "macos")]
fn physical_memory() -> Option<u64> {
let mut bytes = 0u64;
let mut size = std::mem::size_of::<u64>();
// SAFETY: the name is NUL-terminated and the output buffer is a u64 whose
// size is passed in `size`; no new value is written.
let status = unsafe {
libc::sysctlbyname(
c"hw.memsize".as_ptr(),
(&raw mut bytes).cast(),
&raw mut size,
std::ptr::null_mut(),
0,
)
};
(status == 0 && size == std::mem::size_of::<u64>()).then_some(bytes)
}
#[cfg(not(target_os = "macos"))]
fn physical_memory() -> Option<u64> {
None
}
/// A Windows `SYSTEMTIME`, in field order.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct SystemTime {
year: u16,
month: u16,
day_of_week: u16,
day: u16,
hour: u16,
minute: u16,
second: u16,
milliseconds: u16,
}
impl SystemTime {
fn to_bytes(self) -> [u8; 16] {
let fields = [
self.year,
self.month,
self.day_of_week,
self.day,
self.hour,
self.minute,
self.second,
self.milliseconds,
];
let mut bytes = [0; 16];
for (chunk, field) in bytes.as_chunks_mut::<2>().0.iter_mut().zip(fields) {
*chunk = field.to_le_bytes();
}
bytes
}
fn from_bytes(bytes: [u8; 16]) -> Self {
let field = |index: usize| u16::from_le_bytes([bytes[2 * index], bytes[2 * index + 1]]);
Self {
year: field(0),
month: field(1),
day_of_week: field(2),
day: field(3),
hour: field(4),
minute: field(5),
second: field(6),
milliseconds: field(7),
}
}
}
/// Proleptic Gregorian date for a day count relative to 1970-01-01.
fn civil_from_days(days: i64) -> (i64, u16, u16) {
let shifted = days + 719_468;
let era = shifted.div_euclid(146_097);
let day_of_era = shifted.rem_euclid(146_097);
let year_of_era =
(day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let month_index = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * month_index + 2) / 5 + 1;
let month = if month_index < 10 {
month_index + 3
} else {
month_index - 9
};
let year = year_of_era + era * 400 + i64::from(month <= 2);
(year, month as u16, day as u16)
}
fn days_from_civil(year: i64, month: u16, day: u16) -> i64 {
let year = year - i64::from(month <= 2);
let era = year.div_euclid(400);
let year_of_era = year - era * 400;
let month_index = (i64::from(month) + 9) % 12;
let day_of_year = (153 * month_index + 2) / 5 + i64::from(day) - 1;
let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
era * 146_097 + day_of_era - 719_468
}
fn is_leap(year: u16) -> bool {
year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400))
}
fn days_in_month(year: u16, month: u16) -> u16 {
match month {
2 if is_leap(year) => 29,
2 => 28,
4 | 6 | 9 | 11 => 30,
_ => 31,
}
}
fn filetime_to_system_time(filetime: u64) -> Option<SystemTime> {
if filetime >= MAX_FILETIME {
return None;
}
let millis = filetime / TICKS_PER_MILLI;
let days = (millis / MILLIS_PER_DAY) as i64;
let of_day = millis % MILLIS_PER_DAY;
let (year, month, day) = civil_from_days(days - DAYS_1601_TO_1970);
Some(SystemTime {
year: year as u16,
month,
// 1601-01-01 was a Monday, and Sunday is zero.
day_of_week: ((days + 1) % 7) as u16,
day,
hour: (of_day / 3_600_000) as u16,
minute: (of_day / 60_000 % 60) as u16,
second: (of_day / 1000 % 60) as u16,
milliseconds: (of_day % 1000) as u16,
})
}
/// The day of week is ignored, as documented for SystemTimeToFileTime.
fn system_time_to_filetime(time: SystemTime) -> Option<u64> {
let valid = (1601..=30827).contains(&time.year)
&& (1..=12).contains(&time.month)
&& (1..=days_in_month(time.year, time.month)).contains(&time.day)
&& time.hour < 24
&& time.minute < 60
&& time.second < 60
&& time.milliseconds < 1000;
if !valid {
return None;
}
let days = days_from_civil(i64::from(time.year), time.month, time.day) + DAYS_1601_TO_1970;
let millis = days as u64 * MILLIS_PER_DAY
+ u64::from(time.hour) * 3_600_000
+ u64::from(time.minute) * 60_000
+ u64::from(time.second) * 1000
+ u64::from(time.milliseconds);
Some(millis * TICKS_PER_MILLI)
}
fn fault(error: MemoryError) -> ExitReason {
ExitReason::MemoryFault(error)
}
fn write_system_info(
state: &ServicesState,
memory: &mut GuestMemory,
address: u64,
) -> Result<(), ExitReason> {
let processors = state.guest_profile.processors.clamp(1, 64);
let mask = u64::MAX >> (64 - processors);
let mut info = [0u8; 48];
info[0..2].copy_from_slice(&PROCESSOR_ARCHITECTURE_AMD64.to_le_bytes());
info[4..8].copy_from_slice(&GUEST_PAGE_SIZE.to_le_bytes());
info[8..16].copy_from_slice(&MINIMUM_APPLICATION_ADDRESS.to_le_bytes());
info[16..24].copy_from_slice(&MAXIMUM_APPLICATION_ADDRESS.to_le_bytes());
info[24..32].copy_from_slice(&mask.to_le_bytes());
info[32..36].copy_from_slice(&processors.to_le_bytes());
info[36..40].copy_from_slice(&PROCESSOR_AMD_X8664.to_le_bytes());
info[40..44].copy_from_slice(&(ALLOCATION_GRANULARITY as u32).to_le_bytes());
// wProcessorLevel and wProcessorRevision stay zero: no CPU model is simulated.
memory.write_bytes(address, &info).map_err(fault)
}
/// `IsProcessorFeaturePresent` feature numbers from the public `winnt.h`
/// list, each with the guest CPUID bits that must all be set for it.
///
/// Answers come from [`crate::cpu::cpuid`], the table that also defines what
/// guest `CPUID` returns, so the two never disagree. A feature with no CPUID
/// test here (for example `PF_NX_ENABLED` or `PF_FASTFAIL_AVAILABLE`) and any
/// unknown number report `FALSE`.
/// A CPUID leaf, the result register index (EAX = 0 … EDX = 3) and a mask.
type CpuidBit = (u32, usize, u32);
const PROCESSOR_FEATURES: [(u32, &[CpuidBit]); 14] = [
(2, &[(1, 3, 1 << 8)]), // PF_COMPARE_EXCHANGE_DOUBLE: CMPXCHG8B
(3, &[(1, 3, 1 << 23)]), // PF_MMX_INSTRUCTIONS_AVAILABLE
(6, &[(1, 3, 1 << 25)]), // PF_XMMI_INSTRUCTIONS_AVAILABLE: SSE
(8, &[(1, 3, 1 << 4)]), // PF_RDTSC_INSTRUCTION_AVAILABLE
(10, &[(1, 3, 1 << 26)]), // PF_XMMI64_INSTRUCTIONS_AVAILABLE: SSE2
(13, &[(1, 2, 1)]), // PF_SSE3_INSTRUCTIONS_AVAILABLE
(14, &[(1, 2, 1 << 13)]), // PF_COMPARE_EXCHANGE128: CMPXCHG16B
(17, &[(1, 2, 1 << 26), (1, 2, 1 << 27)]), // PF_XSAVE_ENABLED: XSAVE, OSXSAVE
(28, &[(1, 2, 1 << 30)]), // PF_RDRAND_INSTRUCTION_AVAILABLE
(36, &[(1, 2, 1 << 9)]), // PF_SSSE3_INSTRUCTIONS_AVAILABLE
(37, &[(1, 2, 1 << 19)]), // PF_SSE4_1_INSTRUCTIONS_AVAILABLE
(38, &[(1, 2, 1 << 20)]), // PF_SSE4_2_INSTRUCTIONS_AVAILABLE
(39, &[(1, 2, 1 << 28)]), // PF_AVX_INSTRUCTIONS_AVAILABLE
(40, &[(7, 1, 1 << 5)]), // PF_AVX2_INSTRUCTIONS_AVAILABLE
];
/// Whether guest CPUID reports every bit `feature` needs.
pub fn processor_feature_present(feature: u32) -> bool {
PROCESSOR_FEATURES
.iter()
.find(|(number, _)| *number == feature)
.is_some_and(|(_, bits)| {
bits.iter()
.all(|&(leaf, register, mask)| crate::cpu::cpuid(leaf, 0)[register] & mask == mask)
})
}
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
registry.register_with_status(
KERNEL32,
"IsProcessorFeaturePresent",
ServiceStatus::Partial,
|args, _, _| Ok(u64::from(processor_feature_present(args.rcx as u32))),
);
registry.alias(
"api-ms-win-core-processthreads-l1-1-0.dll",
KERNEL32,
"IsProcessorFeaturePresent",
);
for symbol in ["GetSystemInfo", "GetNativeSystemInfo"] {
let s = Arc::clone(state);
registry.register(KERNEL32, symbol, move |args, _, mem| {
write_system_info(&s, mem, args.rcx)?;
Ok(0)
});
}
let s = Arc::clone(state);
registry.register(KERNEL32, "GlobalMemoryStatusEx", move |args, cpu, mem| {
let address = args.rcx;
if mem.read_u32(address).map_err(fault)? != MEMORYSTATUSEX_SIZE {
return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
}
let (mapped, virtual_bytes, heap_bytes) = mem.usage();
// Guest physical memory is the virtual-allocation and heap budgets;
// there is no paging file.
let total = 2 * DYNAMIC_BUDGET;
let used = (virtual_bytes + heap_bytes).min(total);
let total_virtual = MAXIMUM_APPLICATION_ADDRESS - MINIMUM_APPLICATION_ADDRESS + 1;
let mut status = [0u8; 64];
status[0..4].copy_from_slice(&MEMORYSTATUSEX_SIZE.to_le_bytes());
status[4..8].copy_from_slice(&((used * 100 / total) as u32).to_le_bytes());
for (offset, value) in [
(8, total),
(16, total - used),
(24, total),
(32, total - used),
(40, total_virtual),
(48, total_virtual.saturating_sub(mapped)),
] {
status[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
}
mem.write_bytes(address, &status).map_err(fault)?;
Ok(1)
});
// The guest time zone is UTC, so local time equals system time.
for symbol in ["GetSystemTime", "GetLocalTime"] {
let s = Arc::clone(state);
registry.register(KERNEL32, symbol, move |args, _, mem| {
let time = filetime_to_system_time(s.clock.now_filetime())
.ok_or(ExitReason::IllegalInstruction(0xFE))?;
mem.write_bytes(args.rcx, &time.to_bytes()).map_err(fault)?;
Ok(0)
});
}
let s = Arc::clone(state);
registry.register(
KERNEL32,
"GetSystemTimePreciseAsFileTime",
move |args, _, mem| {
mem.write_u64(args.rcx, s.clock.now_filetime())
.map_err(fault)?;
Ok(0)
},
);
let s = Arc::clone(state);
registry.register(KERNEL32, "FileTimeToSystemTime", move |args, cpu, mem| {
let filetime = mem.read_u64(args.rcx).map_err(fault)?;
let Some(time) = filetime_to_system_time(filetime) else {
return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
};
mem.write_bytes(args.rdx, &time.to_bytes()).map_err(fault)?;
Ok(1)
});
let s = Arc::clone(state);
registry.register(KERNEL32, "SystemTimeToFileTime", move |args, cpu, mem| {
let mut bytes = [0; 16];
mem.read_bytes(args.rcx, &mut bytes).map_err(fault)?;
let Some(filetime) = system_time_to_filetime(SystemTime::from_bytes(bytes)) else {
return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
};
mem.write_u64(args.rdx, filetime).map_err(fault)?;
Ok(1)
});
let s = Arc::clone(state);
registry.register(
KERNEL32,
"QueryUnbiasedInterruptTime",
move |args, _, mem| {
let elapsed = s.clock.performance_count().saturating_sub(s.clock_origin);
mem.write_u64(args.rcx, elapsed).map_err(fault)?;
Ok(1)
},
);
// No APCs can be queued, so an alertable SleepEx always runs to completion
// and returns zero rather than WAIT_IO_COMPLETION.
for symbol in ["Sleep", "SleepEx"] {
let s = Arc::clone(state);
registry.register(KERNEL32, symbol, move |args, _, _| {
let millis = args.rcx as u32;
if millis == INFINITE || millis > MAX_SLEEP_MILLIS {
return Err(ExitReason::IllegalInstruction(0xFE));
}
s.clock.sleep(u64::from(millis) * TICKS_PER_MILLI);
Ok(0)
});
}
let zone = Arc::clone(state);
registry.register(KERNEL32, "GetTimeZoneInformation", move |args, cpu, mem| {
// TIME_ZONE_INFORMATION is 172 bytes: Bias, StandardName[32],
// StandardDate, StandardBias, DaylightName[32], DaylightDate,
// DaylightBias. UTC has no bias and no daylight transition, so every
// field but the two names is zero.
let mut info = [0u8; TIME_ZONE_INFORMATION_SIZE];
for offset in [4, 88] {
for (index, unit) in UTC_NAME.encode_utf16().enumerate() {
info[offset + 2 * index..offset + 2 * index + 2]
.copy_from_slice(&unit.to_le_bytes());
}
}
if args.rcx == 0 || mem.write_bytes(args.rcx, &info).is_err() {
return zone.fail(cpu.gs_base, ERROR_NOACCESS, u64::from(TIME_ZONE_ID_INVALID));
}
Ok(u64::from(TIME_ZONE_ID_UNKNOWN))
});
let topology = Arc::clone(state);
registry.register(
KERNEL32,
"GetLogicalProcessorInformation",
move |args, cpu, mem| {
let (buffer, length) = (args.rcx, args.rdx);
if length == 0 {
return topology.fail(cpu.gs_base, ERROR_NOACCESS, 0);
}
let processors = topology.guest_profile.processors.clamp(1, 64);
let entries = processor_topology(processors);
let needed = (entries.len() * PROCESSOR_INFO_SIZE) as u32;
let available = mem.read_u32(length).map_err(ExitReason::MemoryFault)?;
if buffer == 0 || available < needed {
mem.write_u32(length, needed)
.map_err(ExitReason::MemoryFault)?;
return topology.fail(cpu.gs_base, ERROR_INSUFFICIENT_BUFFER, 0);
}
let bytes: Vec<u8> = entries.concat();
if mem.write_bytes(buffer, &bytes).is_err() {
return topology.fail(cpu.gs_base, ERROR_NOACCESS, 0);
}
mem.write_u32(length, needed)
.map_err(ExitReason::MemoryFault)?;
Ok(1)
},
);
for (symbol, api_set) in [
("GetTimeZoneInformation", TIMEZONE_API),
("GetLogicalProcessorInformation", SYSINFO_API),
("GetSystemInfo", SYSINFO_API),
("GetNativeSystemInfo", SYSINFO_API_2),
("GlobalMemoryStatusEx", SYSINFO_API),
("GetSystemTime", SYSINFO_API),
("GetLocalTime", SYSINFO_API),
("GetSystemTimePreciseAsFileTime", SYSINFO_API_2),
("FileTimeToSystemTime", TIMEZONE_API),
("SystemTimeToFileTime", TIMEZONE_API),
("QueryUnbiasedInterruptTime", REALTIME_API),
("Sleep", SYNCH_API_2),
("SleepEx", SYNCH_API),
] {
registry.alias(api_set, KERNEL32, symbol);
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn calendar_conversion_round_trips_across_leap_and_century_boundaries() {
for days in (-DAYS_1601_TO_1970..2_000_000).step_by(997) {
let (year, month, day) = civil_from_days(days);
assert_eq!(days_from_civil(year, month, day), days);
}
assert!(is_leap(2000) && is_leap(2024) && !is_leap(1900) && !is_leap(2100));
}
#[test]
fn host_capabilities_are_detected_on_this_mac() {
let host = HostCapabilities::detect();
assert!(host.logical_processors.unwrap() >= 1);
assert!(host.page_size.unwrap() >= 4096);
#[cfg(target_os = "macos")]
assert!(host.physical_memory.unwrap() >= 1 << 30);
}
}
+635 -46
View File
@@ -1,6 +1,8 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Process-local Winsock UDP loopback for the synthetic guest.
//! Process-local Winsock loopback for the synthetic guest: UDP datagrams and
//! TCP streams between sockets of the same guest on 127.0.0.1. No host socket
//! is ever opened, so guest code cannot reach the host network.
use super::{ERROR_INVALID_PARAMETER, ServicesState};
use crate::cpu::ExitReason;
@@ -16,6 +18,10 @@ const WSADATA_SIZE: usize = 408;
const MAX_DATAGRAM: usize = 65_507;
const MAX_PENDING_DATAGRAMS: usize = 16;
const MAX_SOCKETS: usize = 64;
/// Bytes a stream socket buffers before senders see `WSAEWOULDBLOCK`.
const STREAM_BUFFER: usize = 64 * 1024;
/// Largest number of connections waiting in one listen queue.
const MAX_BACKLOG: usize = 16;
const SOCKET_ERROR: u64 = u32::MAX as u64;
const INVALID_SOCKET: u64 = u64::MAX;
const WSAEACCES: u32 = 10013;
@@ -36,6 +42,10 @@ const WSAEAFNOSUPPORT: u32 = 10047;
const WSASYSNOTREADY: u32 = 10091;
const WSAVERNOTSUPPORTED: u32 = 10092;
const WSANOTINITIALISED: u32 = 10093;
const WSAECONNRESET: u32 = 10054;
const WSAEISCONN: u32 = 10056;
const WSAESHUTDOWN: u32 = 10058;
const WSAECONNREFUSED: u32 = 10061;
#[derive(Default)]
pub(super) struct Winsock {
@@ -46,11 +56,38 @@ pub(super) struct Winsock {
poll_waiters: usize,
}
#[derive(Clone, Copy, Default, PartialEq, Eq)]
enum Kind {
#[default]
Datagram,
Stream,
}
#[derive(Default)]
struct Socket {
kind: Kind,
port: Option<u16>,
peer: Option<u16>,
pending: VecDeque<(u16, Vec<u8>)>,
stream: Stream,
}
/// Connection state of a stream socket.
#[derive(Default)]
struct Stream {
/// Handles of connections waiting for `accept`, when listening.
listen: Option<(usize, VecDeque<u64>)>,
/// The other end of the connection while it is open.
link: Option<u64>,
/// Created by `connect` on a listener's port; shares that port.
accepted: bool,
inbound: VecDeque<u8>,
/// The other end will send nothing more.
peer_closed: bool,
/// The other end was closed, so sending fails.
peer_gone: bool,
send_closed: bool,
receive_closed: bool,
}
impl Winsock {
@@ -71,11 +108,13 @@ impl Winsock {
self.sockets.get(&handle).ok_or(WSAENOTSOCK)
}
fn port(&self, requested: u16) -> Result<u16, u32> {
/// A local port for a socket of `kind`. TCP and UDP ports are separate,
/// and accepted connections share their listener's port.
fn port(&self, requested: u16, kind: Kind) -> Result<u16, u32> {
let available = |port| {
self.sockets
.values()
.all(|socket| socket.port != Some(port))
self.sockets.values().all(|socket| {
socket.kind != kind || socket.stream.accepted || socket.port != Some(port)
})
};
if requested != 0 {
return available(requested)
@@ -86,6 +125,130 @@ impl Winsock {
.find(|&port| available(port))
.ok_or(WSAEADDRINUSE)
}
fn allocate(&mut self, socket: Socket) -> Result<u64, u32> {
if self.sockets.len() >= MAX_SOCKETS {
return Err(WSAEMFILE);
}
let next = self.serial.checked_add(1).ok_or(WSAEMFILE)?;
self.serial = next;
let handle = 0x5300_0000_0000_0000 | u64::from(next);
self.sockets.insert(handle, socket);
Ok(handle)
}
/// The datagram socket a datagram from `source` to `port` reaches.
fn datagram_target(&mut self, port: u16, source: u16) -> Option<&mut Socket> {
self.sockets.values_mut().find(|socket| {
socket.kind == Kind::Datagram
&& socket.port == Some(port)
&& socket.peer.is_none_or(|peer| peer == source)
})
}
/// Close `handle`. The other end of a stream sees end of file, and
/// connections still waiting in a listen queue are closed too.
fn close(&mut self, handle: u64) -> bool {
let Some(socket) = self.sockets.remove(&handle) else {
return false;
};
let mut links: Vec<u64> = socket.stream.link.into_iter().collect();
for waiting in socket
.stream
.listen
.into_iter()
.flat_map(|(_, queue)| queue)
{
if let Some(waiting) = self.sockets.remove(&waiting) {
links.extend(waiting.stream.link);
}
}
for link in links {
if let Some(other) = self.sockets.get_mut(&link) {
other.stream.link = None;
other.stream.peer_closed = true;
other.stream.peer_gone = true;
}
}
true
}
fn connect_stream(&mut self, handle: u64, port: u16) -> Result<(), u32> {
let socket = self.socket(handle)?;
if socket.stream.listen.is_some() {
return Err(WSAEINVAL);
}
if socket.peer.is_some() {
return Err(WSAEISCONN);
}
let existing = socket.port;
let listener = self
.sockets
.iter()
.find(|(_, socket)| {
socket.kind == Kind::Stream
&& socket.port == Some(port)
&& socket.stream.listen.is_some()
})
.map(|(&listener, socket)| (listener, socket.stream.listen.as_ref()))
.and_then(|(listener, listen)| {
listen.map(|(backlog, queue)| (listener, *backlog, queue.len()))
});
let Some((listener, backlog, waiting)) = listener else {
return Err(WSAECONNREFUSED);
};
if waiting >= backlog {
return Err(WSAECONNREFUSED);
}
let local = match existing {
Some(local) => local,
None => self.port(0, Kind::Stream)?,
};
let accepted = self.allocate(Socket {
kind: Kind::Stream,
port: Some(port),
peer: Some(local),
stream: Stream {
link: Some(handle),
accepted: true,
..Stream::default()
},
..Socket::default()
})?;
let socket = self.sockets.get_mut(&handle).expect("validated socket");
socket.port = Some(local);
socket.peer = Some(port);
socket.stream.link = Some(accepted);
let (_, queue) = self
.sockets
.get_mut(&listener)
.and_then(|listener| listener.stream.listen.as_mut())
.expect("listener found above");
queue.push_back(accepted);
Ok(())
}
/// How many of `length` bytes a stream send may take now, and where they
/// go. Checked before any guest memory is read.
fn stream_room(&self, handle: u64, length: usize) -> Result<(u64, usize), u32> {
let socket = self.socket(handle)?;
if socket.stream.send_closed {
return Err(WSAESHUTDOWN);
}
if socket.stream.peer_gone {
return Err(WSAECONNRESET);
}
let link = socket.stream.link.ok_or(WSAENOTCONN)?;
let target = &self.sockets[&link];
if target.stream.receive_closed {
return Err(WSAECONNRESET);
}
let room = STREAM_BUFFER - target.stream.inbound.len();
if room == 0 && length != 0 {
return Err(WSAEWOULDBLOCK);
}
Ok((link, length.min(room)))
}
}
fn loopback_port(memory: &GuestMemory, address: u64, size: u32) -> Result<u16, u32> {
@@ -161,22 +324,19 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
if args.rcx as u32 != 2 {
return fail(WSAEAFNOSUPPORT);
}
if args.rdx as u32 != 2 {
return fail(WSAESOCKTNOSUPPORT);
}
if !matches!(args.r8 as u32, 0 | 17) {
return fail(WSAEPROTONOSUPPORT);
}
if net.sockets.len() >= MAX_SOCKETS {
return fail(WSAEMFILE);
}
let Some(next) = net.serial.checked_add(1) else {
return fail(WSAEMFILE);
let kind = match (args.rdx as u32, args.r8 as u32) {
(2, 0 | 17) => Kind::Datagram,
(1, 0 | 6) => Kind::Stream,
(1 | 2, _) => return fail(WSAEPROTONOSUPPORT),
_ => return fail(WSAESOCKTNOSUPPORT),
};
net.serial = next;
let socket = 0x5300_0000_0000_0000 | u64::from(next);
net.sockets.insert(socket, Socket::default());
Ok(socket)
match net.allocate(Socket {
kind,
..Socket::default()
}) {
Ok(socket) => Ok(socket),
Err(error) => fail(error),
}
});
let close = Arc::clone(state);
@@ -185,7 +345,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
if net.refs == 0 {
return close.fail(cpu.gs_base, WSANOTINITIALISED, SOCKET_ERROR);
}
if net.sockets.remove(&args.rcx).is_none() {
if !net.close(args.rcx) {
return close.fail(cpu.gs_base, WSAENOTSOCK, SOCKET_ERROR);
}
close.winsock_changed.notify_all();
@@ -197,6 +357,8 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
register_socket_names(registry, state);
register_socket_options(registry, state);
register_poll(registry, state);
register_stream(registry, state);
register_ioctl(registry, state);
let get = Arc::clone(state);
registry.register(MODULE, "WSAGetLastError", move |_, cpu, _| {
@@ -307,15 +469,20 @@ fn register_loopback(registry: &mut ImportRegistry, state: &Arc<ServicesState>)
let mut net = state.winsock.lock().expect("guest Winsock state");
let result = (|| {
let socket = net.socket(args.rcx)?;
let existing = socket.port;
let (kind, existing) = (socket.kind, socket.port);
let requested = loopback_port(memory, args.rdx, args.r8 as u32)?;
if connect && requested == 0 || !connect && existing.is_some() {
return Err(WSAEINVAL);
}
if connect && kind == Kind::Stream {
net.connect_stream(args.rcx, requested)?;
state.winsock_changed.notify_all();
return Ok(0);
}
let local = match (connect, existing) {
(true, Some(port)) => port,
(true, None) => net.port(0)?,
(false, _) => net.port(requested)?,
(true, None) => net.port(0, kind)?,
(false, _) => net.port(requested, kind)?,
};
let socket = net.sockets.get_mut(&args.rcx).expect("validated socket");
socket.port = Some(local);
@@ -340,12 +507,27 @@ fn register_loopback(registry: &mut ImportRegistry, state: &Arc<ServicesState>)
let mut net = send.winsock.lock().expect("guest Winsock state");
let result = (|| {
let socket = net.socket(args.rcx)?;
let peer = socket.peer.ok_or(WSAENOTCONN)?;
let source = socket.port.expect("connected socket is bound");
let length = args.r8 as i32;
if length < 0 || args.r9 as u32 != 0 {
return Err(WSAEINVAL);
}
if socket.kind == Kind::Stream {
// Read only what the peer can take, so a short send
// never touches guest bytes it does not report.
let (link, length) = net.stream_room(args.rcx, length as usize)?;
let mut data = vec![0; length];
if length != 0 {
memory
.read_bytes(args.rdx, &mut data)
.map_err(|_| WSAEFAULT)?;
}
let target = net.sockets.get_mut(&link).expect("linked socket exists");
target.stream.inbound.extend(data);
send.winsock_changed.notify_all();
return Ok(length as u64);
}
let peer = socket.peer.ok_or(WSAENOTCONN)?;
let source = socket.port.expect("connected socket is bound");
let length = length as usize;
if length > MAX_DATAGRAM {
return Err(WSAEMSGSIZE);
@@ -356,9 +538,7 @@ fn register_loopback(registry: &mut ImportRegistry, state: &Arc<ServicesState>)
.read_bytes(args.rdx, &mut data)
.map_err(|_| WSAEFAULT)?;
}
if let Some(target) = net.sockets.values_mut().find(|socket| {
socket.port == Some(peer) && socket.peer.is_none_or(|port| port == source)
}) {
if let Some(target) = net.datagram_target(peer, source) {
if target.pending.len() == MAX_PENDING_DATAGRAMS {
return Err(WSAENOBUFS);
}
@@ -379,10 +559,39 @@ fn register_loopback(registry: &mut ImportRegistry, state: &Arc<ServicesState>)
move |args, cpu, memory| {
let mut net = recv.winsock.lock().expect("guest Winsock state");
let result = (|| {
if net.socket(args.rcx)?.port.is_none() {
let socket = net.socket(args.rcx)?;
let length = args.r8 as i32;
if socket.kind == Kind::Stream {
if length < 0 || args.r9 as u32 != 0 {
return Err(WSAEINVAL);
}
if socket.peer.is_none() {
return Err(WSAENOTCONN);
}
if socket.stream.receive_closed {
return Err(WSAESHUTDOWN);
}
let socket = net.sockets.get_mut(&args.rcx).expect("validated socket");
let stream = &mut socket.stream;
if stream.inbound.is_empty() {
return if stream.peer_closed {
Ok(0)
} else {
Err(WSAEWOULDBLOCK)
};
}
let copied = (length as usize).min(stream.inbound.len());
let data: Vec<u8> = stream.inbound.range(..copied).copied().collect();
if copied != 0 {
memory.write_bytes(args.rdx, &data).map_err(|_| WSAEFAULT)?;
}
stream.inbound.drain(..copied);
recv.winsock_changed.notify_all();
return Ok(copied as u64);
}
if socket.port.is_none() {
return Err(WSAEINVAL);
}
let length = args.r8 as i32;
if length < 0 || args.r9 as u32 != 0 {
return Err(WSAEINVAL);
}
@@ -405,6 +614,130 @@ fn register_loopback(registry: &mut ImportRegistry, state: &Arc<ServicesState>)
socket_result(&recv, cpu.gs_base, result)
},
);
let sendto = Arc::clone(state);
registry.register_with_status(
MODULE,
"sendto",
ServiceStatus::Partial,
move |args, cpu, memory| {
let mut net = sendto.winsock.lock().expect("guest Winsock state");
let result = (|| {
let length = args.r8 as i32;
let flags = args.r9 as u32;
let to = args.get(4, memory).map_err(|_| WSAEFAULT)?;
let tolen = args.get(5, memory).map_err(|_| WSAEFAULT)? as u32;
if length < 0 || flags != 0 {
return Err(WSAEINVAL);
}
if net.socket(args.rcx)?.kind == Kind::Stream {
return Err(WSAEOPNOTSUPP);
}
let peer = loopback_port(memory, to, tolen)?;
let (bound, connected) = {
let socket = net.socket(args.rcx)?;
(socket.port, socket.peer)
};
if connected.is_some_and(|port| port != peer) {
return Err(WSAEINVAL);
}
let source = match bound {
Some(port) => port,
None => {
let local = net.port(0, Kind::Datagram)?;
net.sockets
.get_mut(&args.rcx)
.expect("validated socket")
.port = Some(local);
local
}
};
let length = length as usize;
if length > MAX_DATAGRAM {
return Err(WSAEMSGSIZE);
}
let mut data = vec![0; length];
if length != 0 {
memory
.read_bytes(args.rdx, &mut data)
.map_err(|_| WSAEFAULT)?;
}
if let Some(target) = net.datagram_target(peer, source) {
if target.pending.len() == MAX_PENDING_DATAGRAMS {
return Err(WSAENOBUFS);
}
target.pending.push_back((source, data));
sendto.winsock_changed.notify_all();
}
Ok(length as u64)
})();
socket_result(&sendto, cpu.gs_base, result)
},
);
let recvfrom = Arc::clone(state);
registry.register_with_status(
MODULE,
"recvfrom",
ServiceStatus::Partial,
move |args, cpu, memory| {
let mut net = recvfrom.winsock.lock().expect("guest Winsock state");
let result = (|| {
let socket = net.socket(args.rcx)?;
if socket.kind == Kind::Stream {
return Err(WSAEOPNOTSUPP);
}
if socket.port.is_none() {
return Err(WSAEINVAL);
}
let length = args.r8 as i32;
let flags = args.r9 as u32;
let from = args.get(4, memory).map_err(|_| WSAEFAULT)?;
let fromlen = args.get(5, memory).map_err(|_| WSAEFAULT)?;
if length < 0 || flags != 0 {
return Err(WSAEINVAL);
}
let socket = net.sockets.get_mut(&args.rcx).expect("validated socket");
let (source, data) = socket.pending.front().ok_or(WSAEWOULDBLOCK)?;
let copied = (length as usize).min(data.len());
if copied != 0 {
memory
.write_bytes(args.rdx, &data[..copied])
.map_err(|_| WSAEFAULT)?;
}
let truncated = copied < data.len();
let source = *source;
socket.pending.pop_front();
if from != 0 {
if fromlen == 0 {
return Err(WSAEFAULT);
}
let capacity = memory.read_u32(fromlen).map_err(|_| WSAEFAULT)? as i32;
let mut address = [0; 16];
if capacity < address.len() as i32 {
return Err(WSAEFAULT);
}
memory
.check_write(from, address.len())
.map_err(|_| WSAEFAULT)?;
memory.check_write(fromlen, 4).map_err(|_| WSAEFAULT)?;
address[..2].copy_from_slice(&2_u16.to_le_bytes());
address[2..4].copy_from_slice(&source.to_be_bytes());
address[4..8].copy_from_slice(&[127, 0, 0, 1]);
memory.write_bytes(from, &address).map_err(|_| WSAEFAULT)?;
memory
.write_u32(fromlen, address.len() as u32)
.map_err(|_| WSAEFAULT)?;
}
recvfrom.winsock_changed.notify_all();
if truncated {
return Err(WSAEMSGSIZE);
}
Ok(copied as u64)
})();
socket_result(&recvfrom, cpu.gs_base, result)
},
);
}
fn register_socket_names(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
@@ -456,6 +789,7 @@ fn register_socket_options(registry: &mut ImportRegistry, state: &Arc<ServicesSt
const SOL_SOCKET: u32 = 0xffff;
const SO_TYPE: u32 = 0x1008;
const SO_MAX_MSG_SIZE: u32 = 0x2003;
const SOCK_STREAM: u32 = 1;
const SOCK_DGRAM: u32 = 2;
let state = Arc::clone(state);
@@ -466,10 +800,11 @@ fn register_socket_options(registry: &mut ImportRegistry, state: &Arc<ServicesSt
move |args, cpu, memory| {
let result = (|| {
let net = state.winsock.lock().expect("guest Winsock state");
net.socket(args.rcx)?;
let value = match (args.rdx as u32, args.r8 as u32) {
(SOL_SOCKET, SO_TYPE) => SOCK_DGRAM,
(SOL_SOCKET, SO_MAX_MSG_SIZE) => MAX_DATAGRAM as u32,
let kind = net.socket(args.rcx)?.kind;
let value = match (args.rdx as u32, args.r8 as u32, kind) {
(SOL_SOCKET, SO_TYPE, Kind::Datagram) => SOCK_DGRAM,
(SOL_SOCKET, SO_TYPE, Kind::Stream) => SOCK_STREAM,
(SOL_SOCKET, SO_MAX_MSG_SIZE, Kind::Datagram) => MAX_DATAGRAM as u32,
_ => return Err(WSAENOPROTOOPT),
};
let length = args.get(4, memory).map_err(|_| WSAEFAULT)?;
@@ -493,6 +828,7 @@ fn register_socket_options(registry: &mut ImportRegistry, state: &Arc<ServicesSt
fn register_poll(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
const MAX_POLL_MS: i32 = 1_000;
const POLLFD_SIZE: usize = 16;
const POLLHUP: u16 = 0x0002;
const POLLNVAL: u16 = 0x0004;
const POLLWRNORM: u16 = 0x0010;
const POLLRDNORM: u16 = 0x0100;
@@ -543,17 +879,44 @@ fn register_poll(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
let mut result = POLLNVAL;
if let Some(socket) = net.sockets.get(&handle) {
result = 0;
if !socket.pending.is_empty() {
result |= events & POLLRDNORM;
}
if let Some(peer) = socket.peer
&& !net.sockets.values().any(|target| {
target.port == Some(peer)
&& target.peer.is_none_or(|port| Some(port) == socket.port)
&& target.pending.len() == MAX_PENDING_DATAGRAMS
})
{
result |= events & POLLWRNORM;
if socket.kind == Kind::Stream {
let stream = &socket.stream;
let readable = match &stream.listen {
Some((_, queue)) => !queue.is_empty(),
None => !stream.inbound.is_empty() || stream.peer_closed,
};
if readable {
result |= events & POLLRDNORM;
}
if stream.peer_closed {
result |= POLLHUP;
}
if !stream.send_closed
&& stream
.link
.and_then(|link| net.sockets.get(&link))
.is_some_and(|target| {
target.stream.inbound.len() < STREAM_BUFFER
})
{
result |= events & POLLWRNORM;
}
} else {
if !socket.pending.is_empty() {
result |= events & POLLRDNORM;
}
if let Some(peer) = socket.peer
&& !net.sockets.values().any(|target| {
target.kind == Kind::Datagram
&& target.port == Some(peer)
&& target
.peer
.is_none_or(|port| Some(port) == socket.port)
&& target.pending.len() == MAX_PENDING_DATAGRAMS
})
{
result |= events & POLLWRNORM;
}
}
}
fd[10..12].copy_from_slice(&result.to_le_bytes());
@@ -586,6 +949,187 @@ fn register_poll(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
);
}
/// Write a 127.0.0.1 `sockaddr_in` for `port` through `address` and its
/// length through `length`, both checked before either is written.
fn write_loopback_address(
memory: &mut GuestMemory,
address: u64,
length: u64,
port: u16,
) -> Result<(), u32> {
if length == 0 {
return Err(WSAEFAULT);
}
let capacity = memory.read_u32(length).map_err(|_| WSAEFAULT)? as i32;
let mut data = [0; 16];
if capacity < data.len() as i32 {
return Err(WSAEFAULT);
}
memory
.check_write(address, data.len())
.map_err(|_| WSAEFAULT)?;
memory.check_write(length, 4).map_err(|_| WSAEFAULT)?;
data[..2].copy_from_slice(&2_u16.to_le_bytes());
data[2..4].copy_from_slice(&port.to_be_bytes());
data[4..8].copy_from_slice(&[127, 0, 0, 1]);
memory.write_bytes(address, &data).map_err(|_| WSAEFAULT)?;
memory
.write_u32(length, data.len() as u32)
.map_err(|_| WSAEFAULT)
}
fn register_stream(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
let listen = Arc::clone(state);
registry.register_with_status(
MODULE,
"listen",
ServiceStatus::Partial,
move |args, cpu, _| {
let mut net = listen.winsock.lock().expect("guest Winsock state");
let result = (|| {
let socket = net.socket(args.rcx)?;
if socket.kind != Kind::Stream {
return Err(WSAEOPNOTSUPP);
}
if socket.peer.is_some() {
return Err(WSAEISCONN);
}
if socket.port.is_none() {
return Err(WSAEINVAL);
}
// SOMAXCONN and larger requests are clamped to the queue limit.
let backlog = (args.rdx as i32).clamp(1, MAX_BACKLOG as i32) as usize;
let socket = net.sockets.get_mut(&args.rcx).expect("validated socket");
match &mut socket.stream.listen {
Some((limit, _)) => *limit = backlog,
listen => *listen = Some((backlog, VecDeque::new())),
}
Ok(0)
})();
socket_result(&listen, cpu.gs_base, result)
},
);
let accept = Arc::clone(state);
registry.register_with_status(
MODULE,
"accept",
ServiceStatus::Partial,
move |args, cpu, memory| {
let mut net = accept.winsock.lock().expect("guest Winsock state");
let result = (|| {
let socket = net.socket(args.rcx)?;
let Some((_, queue)) = &socket.stream.listen else {
return Err(WSAEINVAL);
};
let &waiting = queue.front().ok_or(WSAEWOULDBLOCK)?;
let peer = net.sockets[&waiting]
.peer
.expect("accepted socket has a peer");
if args.rdx != 0 {
write_loopback_address(memory, args.rdx, args.r8, peer)?;
}
let socket = net.sockets.get_mut(&args.rcx).expect("validated socket");
socket
.stream
.listen
.as_mut()
.expect("listening socket")
.1
.pop_front();
accept.winsock_changed.notify_all();
Ok(waiting)
})();
match result {
Ok(handle) => Ok(handle),
Err(error) => accept.fail(cpu.gs_base, error, INVALID_SOCKET),
}
},
);
let shutdown = Arc::clone(state);
registry.register_with_status(
MODULE,
"shutdown",
ServiceStatus::Partial,
move |args, cpu, _| {
let mut net = shutdown.winsock.lock().expect("guest Winsock state");
let result = (|| {
let socket = net.socket(args.rcx)?;
if socket.kind != Kind::Stream {
return Err(WSAEOPNOTSUPP);
}
if socket.peer.is_none() {
return Err(WSAENOTCONN);
}
let (receive, send) = match args.rdx as u32 {
0 => (true, false),
1 => (false, true),
2 => (true, true),
_ => return Err(WSAEINVAL),
};
let link = socket.stream.link;
let socket = net.sockets.get_mut(&args.rcx).expect("validated socket");
socket.stream.receive_closed |= receive;
socket.stream.send_closed |= send;
if send && let Some(other) = link.and_then(|link| net.sockets.get_mut(&link)) {
other.stream.peer_closed = true;
}
shutdown.winsock_changed.notify_all();
Ok(0)
})();
socket_result(&shutdown, cpu.gs_base, result)
},
);
}
fn register_ioctl(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
const FIONREAD: u32 = 0x4004_667f;
const FIONBIO: u32 = 0x8004_667e;
let state = Arc::clone(state);
registry.register_with_status(
MODULE,
"ioctlsocket",
ServiceStatus::Partial,
move |args, cpu, memory| {
let net = state.winsock.lock().expect("guest Winsock state");
let result = (|| {
let socket = net.socket(args.rcx)?;
let command = args.rdx as u32;
if !matches!(command, FIONREAD | FIONBIO) {
return Err(WSAEINVAL);
}
if args.r8 == 0 {
return Err(WSAEFAULT);
}
if command == FIONBIO {
// Every socket here is already non-blocking; blocking mode
// is not supported rather than silently ignored.
let enable = memory.read_u32(args.r8).map_err(|_| WSAEFAULT)?;
return if enable != 0 {
Ok(0)
} else {
Err(WSAEOPNOTSUPP)
};
}
// FIONREAD: unread stream bytes, or the size of the next
// datagram.
let available = match socket.kind {
Kind::Stream if socket.stream.listen.is_some() => return Err(WSAEINVAL),
Kind::Stream => socket.stream.inbound.len(),
Kind::Datagram => socket.pending.front().map_or(0, |(_, data)| data.len()),
};
memory
.write_u32(args.r8, available as u32)
.map_err(|_| WSAEFAULT)?;
Ok(0)
})();
socket_result(&state, cpu.gs_base, result)
},
);
}
#[cfg(test)]
#[test]
fn loopback_datagrams_preserve_boundaries_and_reject_external_addresses() {
@@ -640,6 +1184,51 @@ fn loopback_datagrams_preserve_boundaries_and_reject_external_addresses() {
u64::from(WSAEACCES)
);
memory.write_u8(0x1204, 127).unwrap();
// Unconnected sendto / recvfrom before the connected path.
let mut ephemeral = [0; 16];
ephemeral[..8].copy_from_slice(&[2, 0, 0x13, 0x88, 127, 0, 0, 1]);
memory.write_bytes(0x1600, &ephemeral).unwrap();
memory.write_bytes(0x1300, b"ping").unwrap();
memory.write_u64(0x1700, 0x1600).unwrap(); // to
memory.write_u64(0x1708, 16).unwrap(); // tolen
let mut cpu = CpuState::default();
cpu.set(Register::Rcx, client);
cpu.set(Register::Rdx, 0x1300);
cpu.set(Register::R8, 4);
cpu.set(Register::R9, 0);
cpu.set(Register::Rsp, 0x1800);
memory.write_u64(0x1800 + 40, 0x1600).unwrap();
memory.write_u64(0x1800 + 48, 16).unwrap();
let descriptor = registry
.resolve(MODULE, &ImportName::Name("sendto".into()))
.unwrap();
assert_eq!(
(descriptor.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory).unwrap(),
4
);
memory.write_u64(0x1900, 0x1a00).unwrap(); // from buffer ptr slot unused; pass from/fromlen
memory.write_u32(0x1b00, 16).unwrap();
cpu.set(Register::Rcx, server);
cpu.set(Register::Rdx, 0x1400);
cpu.set(Register::R8, 4);
cpu.set(Register::R9, 0);
memory.write_u64(0x1800 + 40, 0x1a00).unwrap();
memory.write_u64(0x1800 + 48, 0x1b00).unwrap();
let descriptor = registry
.resolve(MODULE, &ImportName::Name("recvfrom".into()))
.unwrap();
assert_eq!(
(descriptor.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory).unwrap(),
4
);
let mut got = [0; 4];
memory.read_bytes(0x1400, &mut got).unwrap();
assert_eq!(&got, b"ping");
assert_eq!(memory.read_u16(0x1a00).unwrap(), 2);
let mut ip = [0; 4];
memory.read_bytes(0x1a04, &mut ip).unwrap();
assert_eq!(ip, [127, 0, 0, 1]);
assert_eq!(call(&mut memory, "connect", &[client, 0x1200, 16]), 0);
memory.write_bytes(0x1300, b"hello").unwrap();
assert_eq!(call(&mut memory, "send", &[client, 0x1300, 5, 0]), 5);
+304
View File
@@ -0,0 +1,304 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! XInput controller services backed by a host-supplied [`ControllerSource`].
//!
//! Structure layouts, button masks and return codes follow the public XInput
//! reference (`XINPUT_STATE`, `XINPUT_GAMEPAD`, `XINPUT_VIBRATION`,
//! `XINPUT_CAPABILITIES`, `XInputGetState`, `XInputSetState`,
//! `XInputGetCapabilities` and `XInputEnable`). The functions return their
//! error code directly and leave the thread's last-error value alone.
//!
//! A source decides what is connected. [`SimulatedControllers`] is a
//! deterministic source for tests; it is not physical hardware. Without a
//! source every slot reports `ERROR_DEVICE_NOT_CONNECTED`.
use super::ServicesState;
use crate::cpu::ExitReason;
use crate::imports::{ImportRegistry, ServiceStatus};
use std::sync::{Arc, Mutex};
const MODULE: &str = "xinput1_4.dll";
const ALIASES: [&str; 2] = ["xinput1_3.dll", "xinput9_1_0.dll"];
/// Number of controller slots XInput exposes.
pub const XUSER_MAX_COUNT: u32 = 4;
const ERROR_SUCCESS: u64 = 0;
const ERROR_BAD_ARGUMENTS: u64 = 160;
const ERROR_NOACCESS: u64 = 998;
const ERROR_DEVICE_NOT_CONNECTED: u64 = 1167;
const XINPUT_FLAG_GAMEPAD: u32 = 1;
const XINPUT_DEVTYPE_GAMEPAD: u8 = 1;
const XINPUT_DEVSUBTYPE_GAMEPAD: u8 = 1;
const XINPUT_CAPS_FFB_SUPPORTED: u16 = 1;
/// Every button bit `XINPUT_GAMEPAD` defines.
pub const ALL_BUTTONS: u16 = 0xF3FF;
/// One `XINPUT_GAMEPAD` reading.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Gamepad {
pub buttons: u16,
pub left_trigger: u8,
pub right_trigger: u8,
pub thumb_lx: i16,
pub thumb_ly: i16,
pub thumb_rx: i16,
pub thumb_ry: i16,
}
impl Gamepad {
fn bytes(self) -> [u8; 12] {
let mut bytes = [0; 12];
bytes[..2].copy_from_slice(&self.buttons.to_le_bytes());
bytes[2] = self.left_trigger;
bytes[3] = self.right_trigger;
for (index, axis) in [self.thumb_lx, self.thumb_ly, self.thumb_rx, self.thumb_ry]
.into_iter()
.enumerate()
{
bytes[4 + 2 * index..6 + 2 * index].copy_from_slice(&axis.to_le_bytes());
}
bytes
}
}
/// Where controller readings come from.
pub trait ControllerSource: Send + Sync {
/// The current reading of slot `index` (below [`XUSER_MAX_COUNT`]), or
/// `None` when nothing is connected there.
fn read(&self, index: u32) -> Option<Gamepad>;
/// Whether the controller in slot `index` can vibrate.
fn supports_vibration(&self, index: u32) -> bool;
/// Set the motor speeds of slot `index`; `false` when not connected.
fn vibrate(&self, index: u32, left: u16, right: u16) -> bool;
}
/// A source with nothing connected.
pub struct NoControllers;
impl ControllerSource for NoControllers {
fn read(&self, _: u32) -> Option<Gamepad> {
None
}
fn supports_vibration(&self, _: u32) -> bool {
false
}
fn vibrate(&self, _: u32, _: u16, _: u16) -> bool {
false
}
}
#[derive(Clone, Copy, Default)]
struct SimulatedSlot {
pad: Gamepad,
rumble: bool,
motors: (u16, u16),
}
/// Deterministic controllers for tests, changed through its methods.
#[derive(Default)]
pub struct SimulatedControllers {
slots: Mutex<[Option<SimulatedSlot>; XUSER_MAX_COUNT as usize]>,
}
impl SimulatedControllers {
/// Connect a neutral controller to `index`, with or without motors.
pub fn connect(&self, index: u32, rumble: bool) {
self.slots.lock().expect("simulated controllers")[index as usize] = Some(SimulatedSlot {
rumble,
..SimulatedSlot::default()
});
}
pub fn disconnect(&self, index: u32) {
self.slots.lock().expect("simulated controllers")[index as usize] = None;
}
/// Replace the reading of a connected controller.
pub fn set(&self, index: u32, pad: Gamepad) {
if let Some(slot) = &mut self.slots.lock().expect("simulated controllers")[index as usize] {
slot.pad = pad;
}
}
/// The motor speeds last applied to slot `index`.
pub fn motors(&self, index: u32) -> Option<(u16, u16)> {
self.slots.lock().expect("simulated controllers")[index as usize].map(|slot| slot.motors)
}
}
impl ControllerSource for SimulatedControllers {
fn read(&self, index: u32) -> Option<Gamepad> {
self.slots.lock().expect("simulated controllers")[index as usize].map(|slot| slot.pad)
}
fn supports_vibration(&self, index: u32) -> bool {
self.slots.lock().expect("simulated controllers")[index as usize]
.is_some_and(|slot| slot.rumble)
}
fn vibrate(&self, index: u32, left: u16, right: u16) -> bool {
match &mut self.slots.lock().expect("simulated controllers")[index as usize] {
Some(slot) => {
if slot.rumble {
slot.motors = (left, right);
}
true
}
None => false,
}
}
}
/// Guest-visible XInput state: packet numbers, the enable switch and the
/// vibration each slot last asked for.
pub(super) struct XInput {
enabled: bool,
last: [Option<Gamepad>; XUSER_MAX_COUNT as usize],
packets: [u32; XUSER_MAX_COUNT as usize],
requested: [(u16, u16); XUSER_MAX_COUNT as usize],
}
impl Default for XInput {
fn default() -> Self {
Self {
enabled: true,
last: [None; XUSER_MAX_COUNT as usize],
packets: [0; XUSER_MAX_COUNT as usize],
requested: [(0, 0); XUSER_MAX_COUNT as usize],
}
}
}
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
let get = Arc::clone(state);
registry.register_with_status(
MODULE,
"XInputGetState",
ServiceStatus::Partial,
move |args, _, memory| {
let index = args.rcx as u32;
if index >= XUSER_MAX_COUNT || args.rdx == 0 {
return Ok(ERROR_BAD_ARGUMENTS);
}
let Some(pad) = get.controllers.read(index) else {
get.xinput.lock().expect("xinput state").last[index as usize] = None;
return Ok(ERROR_DEVICE_NOT_CONNECTED);
};
let mut xinput = get.xinput.lock().expect("xinput state");
// While disabled, applications see a neutral controller.
let pad = if xinput.enabled {
pad
} else {
Gamepad::default()
};
let slot = index as usize;
if xinput.last[slot] != Some(pad) {
xinput.last[slot] = Some(pad);
xinput.packets[slot] = xinput.packets[slot].wrapping_add(1);
}
let mut bytes = [0; 16];
bytes[..4].copy_from_slice(&xinput.packets[slot].to_le_bytes());
bytes[4..].copy_from_slice(&pad.bytes());
if memory.write_bytes(args.rdx, &bytes).is_err() {
return Ok(ERROR_NOACCESS);
}
Ok(ERROR_SUCCESS)
},
);
let set = Arc::clone(state);
registry.register_with_status(
MODULE,
"XInputSetState",
ServiceStatus::Partial,
move |args, _, memory| {
let index = args.rcx as u32;
if index >= XUSER_MAX_COUNT || args.rdx == 0 {
return Ok(ERROR_BAD_ARGUMENTS);
}
// XINPUT_VIBRATION is two consecutive WORDs, read as one DWORD so
// a guest pointer at the top of the address space cannot overflow.
let Ok(motors) = memory.read_u32(args.rdx) else {
return Ok(ERROR_NOACCESS);
};
let (left, right) = (motors as u16, (motors >> 16) as u16);
if set.controllers.read(index).is_none() {
return Ok(ERROR_DEVICE_NOT_CONNECTED);
}
let mut xinput = set.xinput.lock().expect("xinput state");
xinput.requested[index as usize] = (left, right);
// A disabled XInput keeps the request until it is enabled again.
if xinput.enabled && !set.controllers.vibrate(index, left, right) {
return Ok(ERROR_DEVICE_NOT_CONNECTED);
}
Ok(ERROR_SUCCESS)
},
);
let caps = Arc::clone(state);
registry.register_with_status(
MODULE,
"XInputGetCapabilities",
ServiceStatus::Partial,
move |args, _, memory| {
let index = args.rcx as u32;
let flags = args.rdx as u32;
if index >= XUSER_MAX_COUNT || flags & !XINPUT_FLAG_GAMEPAD != 0 || args.r8 == 0 {
return Ok(ERROR_BAD_ARGUMENTS);
}
if caps.controllers.read(index).is_none() {
return Ok(ERROR_DEVICE_NOT_CONNECTED);
}
let rumble = caps.controllers.supports_vibration(index);
// Each field reports the resolution the source provides: every
// button, 8-bit triggers and 16-bit sticks.
let resolution = Gamepad {
buttons: ALL_BUTTONS,
left_trigger: 0xFF,
right_trigger: 0xFF,
thumb_lx: -1,
thumb_ly: -1,
thumb_rx: -1,
thumb_ry: -1,
};
let motors: u16 = if rumble { 0xFFFF } else { 0 };
let mut bytes = [0; 20];
bytes[0] = XINPUT_DEVTYPE_GAMEPAD;
bytes[1] = XINPUT_DEVSUBTYPE_GAMEPAD;
let flags = if rumble { XINPUT_CAPS_FFB_SUPPORTED } else { 0 };
bytes[2..4].copy_from_slice(&flags.to_le_bytes());
bytes[4..16].copy_from_slice(&resolution.bytes());
bytes[16..18].copy_from_slice(&motors.to_le_bytes());
bytes[18..20].copy_from_slice(&motors.to_le_bytes());
if memory.write_bytes(args.r8, &bytes).is_err() {
return Ok(ERROR_NOACCESS);
}
Ok(ERROR_SUCCESS)
},
);
let enable = Arc::clone(state);
registry.register_with_status(
MODULE,
"XInputEnable",
ServiceStatus::Partial,
move |args, _, _| -> Result<u64, ExitReason> {
let enabled = args.rcx as u32 != 0;
let mut xinput = enable.xinput.lock().expect("xinput state");
xinput.enabled = enabled;
for index in 0..XUSER_MAX_COUNT {
let (left, right) = if enabled {
xinput.requested[index as usize]
} else {
(0, 0)
};
enable.controllers.vibrate(index, left, right);
}
Ok(0)
},
);
for module in ALIASES {
for symbol in ["XInputGetState", "XInputSetState", "XInputGetCapabilities"] {
registry.alias(module, MODULE, symbol);
}
}
registry.alias("xinput1_3.dll", MODULE, "XInputEnable");
}
+82
View File
@@ -0,0 +1,82 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Abnormal CRT termination through the guest import table. Expectations are
//! from the public Microsoft C runtime pages: `abort` ends the process with
//! exit code 3 when no SIGABRT handler takes over, `_exit` ends it with its
//! status, and the default `terminate` and pure-virtual-call handlers call
//! `abort`. Each stub is `call [slot]; hlt`, so a service that returned would
//! report Halt instead of a process exit.
mod support;
use support::*;
use xenora_loader::cpu::ExitReason;
const UCRT: &str = "ucrtbase.dll";
const RUNTIME: &str = "api-ms-win-crt-runtime-l1-1-0.dll";
const VCRUNTIME: &str = "vcruntime140.dll";
const IMPORTS: &[(&str, &str)] = &[
(UCRT, "abort"),
(UCRT, "terminate"),
(UCRT, "_purecall"),
(VCRUNTIME, "__std_terminate"),
(UCRT, "_exit"),
("kernel32.dll", "SetLastError"),
("kernel32.dll", "CreateEventW"),
];
const RUNTIME_IMPORTS: &[(&str, &str)] = &[
(RUNTIME, "abort"),
(RUNTIME, "terminate"),
(RUNTIME, "_purecall"),
(VCRUNTIME, "_purecall"),
(RUNTIME, "_exit"),
];
#[test]
fn abort_terminate_and_purecall_exit_with_code_three() {
for imports in [IMPORTS, RUNTIME_IMPORTS] {
for &(module, symbol) in imports.iter().filter(|(_, s)| *s != "_exit") {
if module == "kernel32.dll" {
continue;
}
let mut guest = Guest::new(imports, &[]);
// Arguments are ignored: these functions take none.
let (_, exit) = guest.run(symbol, &[0x55]);
assert_eq!(exit, ExitReason::ProcessExit(3), "{module}!{symbol}");
assert_eq!(guest.state.exit_status(), Some(3), "{module}!{symbol}");
}
}
}
#[test]
fn underscore_exit_uses_its_whole_32_bit_status() {
for imports in [IMPORTS, RUNTIME_IMPORTS] {
for (argument, status) in [
(0, 0),
(7, 7),
(0xFFFF_FFFF, 0xFFFF_FFFF),
(0x1_0000_0002, 2),
] {
let mut guest = Guest::new(imports, &[]);
let (_, exit) = guest.run("_exit", &[argument]);
assert_eq!(exit, ExitReason::ProcessExit(status), "{argument:#x}");
}
}
}
#[test]
fn abort_closes_handles_and_nothing_runs_afterwards() {
let mut guest = Guest::new(IMPORTS, &[]);
assert_ne!(guest.call("CreateEventW", &[0, 1, 0, 0]), 0);
assert_eq!(guest.state.open_handle_count(), 1);
assert_eq!(guest.run("abort", &[]).1, ExitReason::ProcessExit(3));
assert_eq!(guest.state.open_handle_count(), 0);
// A later exit does not change the status, and no service runs.
assert_eq!(guest.run("_exit", &[9]).1, ExitReason::ProcessExit(3));
assert_eq!(
guest.run("SetLastError", &[5]).1,
ExitReason::ProcessExit(3)
);
assert_eq!(guest.state.last_error(THREAD_A), 0);
}
+190
View File
@@ -0,0 +1,190 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Floating-point string conversion through the guest import table. Results
//! are read from XMM0. Expected values are the IEEE 754 nearest values of the
//! decimal inputs, written as bit patterns or exact Rust literals, and follow
//! the ISO C grammar for strtod in the "C" locale.
mod support;
use support::*;
use xenora_loader::cpu::{CpuState, ExitReason};
const UCRT: &str = "ucrtbase.dll";
const CONVERT: &str = "api-ms-win-crt-convert-l1-1-0.dll";
const IMPORTS: &[(&str, &str)] = &[
(UCRT, "strtod"),
(UCRT, "strtof"),
(UCRT, "wcstod"),
(UCRT, "wcstof"),
(UCRT, "atof"),
(UCRT, "_wtof"),
(UCRT, "_errno"),
];
const ALIASES: &[(&str, &str)] = &[(CONVERT, "strtod"), (CONVERT, "atof")];
const TEXT: u64 = SCRATCH;
const END: u64 = SCRATCH + 0x800;
fn xmm0(cpu: &CpuState) -> u64 {
cpu.xmm[0] as u64
}
/// Run `symbol` and return XMM0's low 64 bits and RAX.
fn float_call(guest: &mut Guest, symbol: &str, args: &[u64]) -> u64 {
let (cpu, exit) = guest.run_state(symbol, args);
assert_eq!(exit, ExitReason::Halt, "{symbol}");
xmm0(&cpu)
}
fn put(guest: &mut Guest, text: &str) {
guest.memory.write_bytes(TEXT, text.as_bytes()).unwrap();
guest.memory.write_u8(TEXT + text.len() as u64, 0).unwrap();
}
fn put_wide(guest: &mut Guest, text: &str) {
for (i, unit) in text.encode_utf16().chain([0]).enumerate() {
guest.memory.write_u16(TEXT + 2 * i as u64, unit).unwrap();
}
}
fn errno(guest: &mut Guest) -> u32 {
let at = guest.call("_errno", &[]);
guest.u32_at(at)
}
fn clear_errno(guest: &mut Guest) {
let at = guest.call("_errno", &[]);
guest.memory.write_u32(at, 0).unwrap();
}
/// strtod `text`, returning the bits and how many bytes were consumed.
fn strtod(guest: &mut Guest, text: &str) -> (u64, u64) {
put(guest, text);
let bits = float_call(guest, "strtod", &[TEXT, END]);
(bits, guest.u64_at(END) - TEXT)
}
#[test]
fn decimal_forms_parse_to_the_nearest_double() {
let mut guest = Guest::new(IMPORTS, &[]);
for (text, value, consumed) in [
("1.5", 1.5f64, 3),
(" \t-42", -42.0, 6),
("+.25x", 0.25, 4),
("7.", 7.0, 2),
("1e3", 1000.0, 3),
("2.5E-1", 0.25, 6),
// The exponent needs a digit; "e" and "e+" are left unconsumed.
("3e", 3.0, 1),
("3e+", 3.0, 1),
// 0.1 is not exact: the nearest double is 0x3FB999999999999A.
("0.1", 0.1, 3),
("-0", -0.0, 2),
] {
let (bits, used) = strtod(&mut guest, text);
assert_eq!(bits, value.to_bits(), "{text:?}");
assert_eq!(used, consumed, "{text:?}");
}
assert_eq!(0.1f64.to_bits(), 0x3FB9_9999_9999_999A);
}
#[test]
fn no_conversion_returns_zero_and_the_start() {
let mut guest = Guest::new(IMPORTS, &[]);
for text in ["", "abc", " .", "-", "+e5", " x1"] {
let (bits, used) = strtod(&mut guest, text);
assert_eq!((bits, used), (0, 0), "{text:?}");
}
}
#[test]
fn infinity_and_nan_are_case_insensitive() {
let mut guest = Guest::new(IMPORTS, &[]);
for (text, bits, consumed) in [
("inf", f64::INFINITY.to_bits(), 3),
("-INFINITY!", f64::NEG_INFINITY.to_bits(), 9),
("Infinit", f64::INFINITY.to_bits(), 3),
("nan", 0x7FF8_0000_0000_0000, 3),
("-NaN(abc_1)z", 0xFFF8_0000_0000_0000, 11),
// An unclosed payload is not part of the number.
("nan(ab", 0x7FF8_0000_0000_0000, 3),
] {
assert_eq!(strtod(&mut guest, text), (bits, consumed), "{text:?}");
}
}
#[test]
fn out_of_range_results_set_erange() {
let mut guest = Guest::new(IMPORTS, &[]);
clear_errno(&mut guest);
assert_eq!(strtod(&mut guest, "1e400").0, f64::INFINITY.to_bits());
assert_eq!(errno(&mut guest), 34);
clear_errno(&mut guest);
assert_eq!(strtod(&mut guest, "-1e-400").0, (-0.0f64).to_bits());
assert_eq!(errno(&mut guest), 34, "nonzero digits underflowed to zero");
clear_errno(&mut guest);
assert_eq!(strtod(&mut guest, "0.000e-400").0, 0);
assert_eq!(errno(&mut guest), 0, "an exact zero is not a range error");
// 3.4e38 fits a float; 3.5e38 overflows only in single precision.
clear_errno(&mut guest);
put(&mut guest, "3.5e38");
let single = float_call(&mut guest, "strtof", &[TEXT, 0]);
assert_eq!(single as u32, f32::INFINITY.to_bits());
assert_eq!(errno(&mut guest), 34);
}
#[test]
fn strtof_rounds_once_from_the_decimal() {
let mut guest = Guest::new(IMPORTS, &[]);
// 1.00000005960464477539062500001 lies just above the midpoint between
// 1.0f and the next float, so it rounds up. Rounding through double first
// lands exactly on the midpoint and then rounds to even, giving 1.0f.
let text = "1.00000005960464477539062500001";
put(&mut guest, text);
let single = float_call(&mut guest, "strtof", &[TEXT, END]) as u32;
assert_eq!(single, 0x3F80_0001);
let through_double = text.parse::<f64>().unwrap() as f32;
assert_eq!(through_double.to_bits(), 0x3F80_0000, "the hazard is real");
}
#[test]
fn wide_forms_and_atof_share_the_parser() {
let mut guest = Guest::new(IMPORTS, &[]);
put_wide(&mut guest, " -2.5e2z");
assert_eq!(
float_call(&mut guest, "wcstod", &[TEXT, END]),
(-250.0f64).to_bits()
);
assert_eq!(
guest.u64_at(END),
TEXT + 2 * 7,
"end counts wide characters"
);
assert_eq!(
float_call(&mut guest, "wcstof", &[TEXT, 0]) as u32,
(-250.0f32).to_bits()
);
assert_eq!(
float_call(&mut guest, "_wtof", &[TEXT]),
(-250.0f64).to_bits()
);
put(&mut guest, "6.25 apples");
assert_eq!(float_call(&mut guest, "atof", &[TEXT]), 6.25f64.to_bits());
let mut aliased = Guest::new(ALIASES, &[]);
put(&mut aliased, "0.5");
assert_eq!(float_call(&mut aliased, "atof", &[TEXT]), 0.5f64.to_bits());
assert_eq!(
float_call(&mut aliased, "strtod", &[TEXT, 0]),
0.5f64.to_bits()
);
}
#[test]
fn hexadecimal_constants_stop_the_guest() {
let mut guest = Guest::new(IMPORTS, &[]);
put(&mut guest, "0x1.8p3");
assert_eq!(guest.fails("strtod", &[TEXT, END]), RUNTIME_LIMIT);
// Without a hex digit after it, "0x" is just the number zero.
assert_eq!(strtod(&mut guest, "0xg"), (0, 1));
}
+152
View File
@@ -0,0 +1,152 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! UCRT block-size, zeroing and aligned allocation through the guest import
//! table. Expectations follow the public UCRT reference pages for `_msize`,
//! `_recalloc`, `_aligned_malloc`, `_aligned_realloc`, `_aligned_msize`,
//! `_aligned_free` and the `errno` constants.
mod support;
use support::*;
use xenora_loader::cpu::ExitReason;
const UCRT: &str = "ucrtbase.dll";
const IMPORTS: &[(&str, &str)] = &[
(UCRT, "malloc"),
(UCRT, "free"),
(UCRT, "_errno"),
(UCRT, "_msize"),
(UCRT, "_recalloc"),
(UCRT, "_aligned_malloc"),
(UCRT, "_aligned_realloc"),
(UCRT, "_aligned_msize"),
(UCRT, "_aligned_free"),
];
const ENOMEM: u32 = 12;
const EINVAL: u32 = 22;
const SIZE_FAILURE: u64 = u64::MAX;
fn errno(guest: &mut Guest) -> u32 {
let address = guest.call("_errno", &[]);
guest.u32_at(address)
}
fn clear_errno(guest: &mut Guest) {
let address = guest.call("_errno", &[]);
guest.memory.write_u32(address, 0).unwrap();
}
fn faults(guest: &mut Guest, symbol: &str, args: &[u64]) {
assert!(
matches!(guest.fails(symbol, args), ExitReason::MemoryFault(_)),
"{symbol}"
);
}
#[test]
fn msize_reports_the_requested_size_and_rejects_null() {
let mut guest = Guest::new(IMPORTS, &[]);
let block = guest.call("malloc", &[100]);
assert_eq!(guest.call("_msize", &[block]), 100);
clear_errno(&mut guest);
assert_eq!(guest.call("_msize", &[0]), SIZE_FAILURE);
assert_eq!(errno(&mut guest), EINVAL);
guest.call("free", &[block]);
faults(&mut guest, "_msize", &[block]);
}
#[test]
fn recalloc_zeroes_new_bytes_and_keeps_old_ones() {
let mut guest = Guest::new(IMPORTS, &[]);
let block = guest.call("_recalloc", &[0, 4, 4]);
assert_ne!(block, 0);
assert_eq!(guest.call("_msize", &[block]), 16);
guest.memory.write_bytes(block, &[0xAB; 16]).unwrap();
let grown = guest.call("_recalloc", &[block, 8, 4]);
assert_eq!(guest.call("_msize", &[grown]), 32);
let mut bytes = [0u8; 32];
guest.memory.read_bytes(grown, &mut bytes).unwrap();
assert_eq!(&bytes[..16], &[0xAB; 16]);
assert_eq!(&bytes[16..], &[0; 16], "new bytes are zero");
clear_errno(&mut guest);
assert_eq!(guest.call("_recalloc", &[grown, u64::MAX, 2]), 0);
assert_eq!(errno(&mut guest), ENOMEM);
assert_eq!(guest.call("_msize", &[grown]), 32, "unchanged on overflow");
assert_eq!(
guest.call("_recalloc", &[grown, 0, 4]),
0,
"size zero frees"
);
faults(&mut guest, "_msize", &[grown]);
}
#[test]
fn aligned_blocks_honour_alignment_size_and_reallocation() {
let mut guest = Guest::new(IMPORTS, &[]);
for alignment in [1, 16, 4096, 65536] {
let block = guest.call("_aligned_malloc", &[40, alignment]);
assert_ne!(block, 0, "{alignment}");
assert_eq!(block % alignment, 0, "{alignment}");
assert_eq!(guest.call("_aligned_msize", &[block, alignment, 0]), 40);
guest.call("_aligned_free", &[block]);
}
let block = guest.call("_aligned_malloc", &[64, 64]);
guest.memory.write_bytes(block, &[0x5A; 64]).unwrap();
let grown = guest.call("_aligned_realloc", &[block, 1 << 20, 64]);
assert_ne!(grown, 0);
assert_eq!(grown % 64, 0);
assert_eq!(guest.call("_aligned_msize", &[grown, 64, 0]), 1 << 20);
let mut bytes = [0u8; 64];
guest.memory.read_bytes(grown, &mut bytes).unwrap();
assert_eq!(bytes, [0x5A; 64], "contents move with the block");
let fresh = guest.call("_aligned_realloc", &[0, 8, 32]);
assert_eq!(fresh % 32, 0);
assert_eq!(guest.call("_aligned_realloc", &[fresh, 0, 32]), 0);
guest.call("_aligned_free", &[grown]);
}
#[test]
fn aligned_allocators_reject_bad_alignment_and_bad_frees() {
let mut guest = Guest::new(IMPORTS, &[]);
for alignment in [0, 3, 48] {
clear_errno(&mut guest);
assert_eq!(guest.call("_aligned_malloc", &[16, alignment]), 0);
assert_eq!(errno(&mut guest), EINVAL, "{alignment}");
}
// More alignment than the heap provides fails rather than misaligns.
clear_errno(&mut guest);
assert_eq!(guest.call("_aligned_malloc", &[16, 1 << 20]), 0);
assert_eq!(errno(&mut guest), ENOMEM);
let block = guest.call("_aligned_malloc", &[16, 16]);
clear_errno(&mut guest);
assert_eq!(guest.call("_aligned_msize", &[block, 16, 8]), SIZE_FAILURE);
assert_eq!(errno(&mut guest), EINVAL);
assert_eq!(guest.call("_aligned_free", &[0]), 0, "null is a no-op");
guest.call("_aligned_free", &[block]);
faults(&mut guest, "_aligned_free", &[block]); // double free
let plain = guest.call("malloc", &[16]);
faults(&mut guest, "_aligned_free", &[plain]); // not from _aligned_malloc
faults(&mut guest, "_aligned_realloc", &[plain, 32, 16]);
faults(&mut guest, "_aligned_msize", &[plain, 16, 0]);
guest.call("free", &[plain]);
}
#[test]
fn heap_api_set_reaches_the_same_allocator() {
const API: &[(&str, &str)] = &[
("api-ms-win-crt-heap-l1-1-0.dll", "_aligned_malloc"),
("api-ms-win-crt-heap-l1-1-0.dll", "_aligned_free"),
("api-ms-win-crt-heap-l1-1-0.dll", "_msize"),
];
let mut guest = Guest::new(API, &[]);
let block = guest.call("_aligned_malloc", &[24, 256]);
assert_eq!(block % 256, 0);
assert_eq!(guest.call("_msize", &[block]), 24);
guest.call("_aligned_free", &[block]);
faults(&mut guest, "_aligned_free", &[block]);
}
+115
View File
@@ -0,0 +1,115 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Integer abs and div through the guest import table, under the Windows
//! LLP64 model (`long` is 32 bits) and the Win64 return rules: an 8-byte
//! `div_t`/`ldiv_t` comes back in RAX with the quotient in the low half, and a
//! 16-byte `lldiv_t` through a hidden pointer in RCX that RAX returns.
//! Expected values follow ISO C (quotients truncate toward zero and
//! `quot * den + rem == num`) and were worked out by hand.
mod support;
use support::*;
use xenora_loader::cpu::ExitReason;
const UCRT: &str = "ucrtbase.dll";
const IMPORTS: &[(&str, &str)] = &[
(UCRT, "abs"),
(UCRT, "labs"),
(UCRT, "llabs"),
(UCRT, "div"),
(UCRT, "ldiv"),
(UCRT, "lldiv"),
];
const UTILITY: &[(&str, &str)] = &[
("api-ms-win-crt-utility-l1-1-0.dll", "labs"),
("api-ms-win-crt-utility-l1-1-0.dll", "lldiv"),
];
const RESULT: u64 = SCRATCH;
fn int(value: i32) -> u64 {
// A 32-bit argument; the upper half of the register is garbage the
// callee must ignore.
0xDEAD_BEEF_0000_0000 | u64::from(value as u32)
}
fn split(rax: u64) -> (i32, i32) {
(rax as u32 as i32, (rax >> 32) as u32 as i32)
}
#[test]
fn abs_and_labs_are_32_bit_and_llabs_is_64_bit() {
let mut guest = Guest::new(IMPORTS, &[]);
for symbol in ["abs", "labs"] {
assert_eq!(guest.call(symbol, &[int(-5)]), 5, "{symbol}");
assert_eq!(guest.call(symbol, &[int(7)]), 7, "{symbol}");
// The minimum wraps to itself, as x86 neg does.
assert_eq!(
guest.call(symbol, &[int(i32::MIN)]),
0x8000_0000,
"{symbol}"
);
}
assert_eq!(
guest.call("llabs", &[(-5_000_000_000i64) as u64]),
5_000_000_000
);
assert_eq!(guest.call("llabs", &[i64::MIN as u64]), i64::MIN as u64);
}
#[test]
fn div_and_ldiv_pack_quotient_and_remainder_into_rax() {
let mut guest = Guest::new(IMPORTS, &[]);
for symbol in ["div", "ldiv"] {
for (num, den, quot, rem) in [
(7, 2, 3, 1),
(-7, 2, -3, -1),
(7, -2, -3, 1),
(-7, -2, 3, -1),
(i32::MIN, 1, i32::MIN, 0),
] {
let rax = guest.call(symbol, &[int(num), int(den)]);
assert_eq!(split(rax), (quot, rem), "{symbol}({num}, {den})");
}
}
}
#[test]
fn lldiv_returns_through_the_hidden_pointer() {
for imports in [IMPORTS, UTILITY] {
let mut guest = Guest::new(imports, &[]);
let num = -10_000_000_007i64;
let rax = guest.call("lldiv", &[RESULT, num as u64, 1_000_000_000]);
assert_eq!(rax, RESULT);
assert_eq!(guest.u64_at(RESULT) as i64, -10);
assert_eq!(guest.u64_at(RESULT + 8) as i64, -7);
// The API set reaches the same LLP64 labs.
if imports == UTILITY {
assert_eq!(guest.call("labs", &[int(-3)]), 3);
}
}
}
#[test]
fn division_by_zero_and_overflow_raise_a_divide_error() {
let mut guest = Guest::new(IMPORTS, &[]);
for symbol in ["div", "ldiv"] {
assert_eq!(
guest.fails(symbol, &[int(1), int(0)]),
ExitReason::DivideError
);
assert_eq!(
guest.fails(symbol, &[int(i32::MIN), int(-1)]),
ExitReason::DivideError
);
}
assert_eq!(
guest.fails("lldiv", &[RESULT, 1, 0]),
ExitReason::DivideError
);
assert_eq!(
guest.fails("lldiv", &[RESULT, i64::MIN as u64, u64::MAX]),
ExitReason::DivideError
);
}
@@ -0,0 +1,187 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Bounds-checked UCRT string copy and append through the guest import table.
//! Expectations follow the public UCRT pages for strcpy_s, strcat_s,
//! strncpy_s and strncat_s (and their wcs forms): EINVAL for a null or empty
//! destination or a null source, ERANGE when the result does not fit, and
//! STRUNCATE when _TRUNCATE shortens the copy. A failure after the
//! destination is validated leaves it as an empty string.
mod support;
use support::*;
const UCRT: &str = "ucrtbase.dll";
const IMPORTS: &[(&str, &str)] = &[
(UCRT, "_errno"),
(UCRT, "strcpy_s"),
(UCRT, "strcat_s"),
(UCRT, "strncpy_s"),
(UCRT, "strncat_s"),
(UCRT, "wcscpy_s"),
(UCRT, "wcscat_s"),
(UCRT, "wcsncpy_s"),
("api-ms-win-crt-string-l1-1-0.dll", "wcsncat_s"),
];
const EINVAL: u64 = 22;
const ERANGE: u64 = 34;
const STRUNCATE: u64 = 80;
const TRUNCATE: u64 = u64::MAX;
const DEST: u64 = SCRATCH;
const SRC: u64 = SCRATCH + 0x100;
fn put(guest: &mut Guest, at: u64, text: &str) {
let mut bytes = text.as_bytes().to_vec();
bytes.push(0);
guest.memory.write_bytes(at, &bytes).unwrap();
}
fn put_wide(guest: &mut Guest, at: u64, text: &str) {
for (index, unit) in text.encode_utf16().chain([0]).enumerate() {
guest.memory.write_u16(at + 2 * index as u64, unit).unwrap();
}
}
fn text(guest: &Guest, at: u64) -> String {
let mut bytes = Vec::new();
while let Ok(byte) = guest.memory.read_u8(at + bytes.len() as u64) {
if byte == 0 {
break;
}
bytes.push(byte);
}
String::from_utf8(bytes).unwrap()
}
fn wide(guest: &Guest, at: u64) -> String {
let units: Vec<u16> = (0..)
.map(|i| guest.u16_at(at + 2 * i))
.take_while(|&u| u != 0)
.collect();
String::from_utf16(&units).unwrap()
}
fn errno(guest: &mut Guest) -> u64 {
let address = guest.call("_errno", &[]);
u64::from(guest.u32_at(address))
}
fn clear_errno(guest: &mut Guest) {
let address = guest.call("_errno", &[]);
guest.memory.write_u32(address, 0).unwrap();
}
fn fill(guest: &mut Guest) {
guest.memory.write_bytes(DEST, &[b'#'; 64]).unwrap();
}
#[test]
fn strcpy_s_copies_when_it_fits_and_reports_errors() {
let mut guest = Guest::new(IMPORTS, &[]);
put(&mut guest, SRC, "hello");
fill(&mut guest);
assert_eq!(guest.call("strcpy_s", &[DEST, 6, SRC]), 0);
assert_eq!(text(&guest, DEST), "hello");
// Needs six bytes with the terminator.
fill(&mut guest);
clear_errno(&mut guest);
assert_eq!(guest.call("strcpy_s", &[DEST, 5, SRC]), ERANGE);
assert_eq!(errno(&mut guest), ERANGE);
assert_eq!(guest.memory.read_u8(DEST).unwrap(), 0, "emptied");
fill(&mut guest);
assert_eq!(guest.call("strcpy_s", &[DEST, 8, 0]), EINVAL);
assert_eq!(guest.memory.read_u8(DEST).unwrap(), 0);
fill(&mut guest);
assert_eq!(guest.call("strcpy_s", &[DEST, 0, SRC]), EINVAL);
assert_eq!(guest.memory.read_u8(DEST).unwrap(), b'#', "untouched");
assert_eq!(guest.call("strcpy_s", &[0, 8, SRC]), EINVAL);
assert_eq!(errno(&mut guest), EINVAL);
}
#[test]
fn strcat_s_appends_and_rejects_unterminated_destinations() {
let mut guest = Guest::new(IMPORTS, &[]);
put(&mut guest, DEST, "ab");
put(&mut guest, SRC, "cde");
assert_eq!(guest.call("strcat_s", &[DEST, 6, SRC]), 0);
assert_eq!(text(&guest, DEST), "abcde");
assert_eq!(guest.call("strcat_s", &[DEST, 8, SRC]), ERANGE);
assert_eq!(text(&guest, DEST), "");
// No terminator within the stated size.
fill(&mut guest);
assert_eq!(guest.call("strcat_s", &[DEST, 10, SRC]), EINVAL);
assert_eq!(guest.memory.read_u8(DEST).unwrap(), 0);
}
#[test]
fn strncpy_s_counts_truncates_and_handles_zero() {
let mut guest = Guest::new(IMPORTS, &[]);
put(&mut guest, SRC, "abcdef");
fill(&mut guest);
assert_eq!(guest.call("strncpy_s", &[DEST, 8, SRC, 3]), 0);
assert_eq!(text(&guest, DEST), "abc");
// The count is larger than the string: the whole string is copied.
assert_eq!(guest.call("strncpy_s", &[DEST, 8, SRC, 100]), 0);
assert_eq!(text(&guest, DEST), "abcdef");
assert_eq!(guest.call("strncpy_s", &[DEST, 4, SRC, 5]), ERANGE);
assert_eq!(text(&guest, DEST), "");
clear_errno(&mut guest);
assert_eq!(
guest.call("strncpy_s", &[DEST, 4, SRC, TRUNCATE]),
STRUNCATE
);
assert_eq!(text(&guest, DEST), "abc");
assert_eq!(errno(&mut guest), 0, "truncation is not an error");
assert_eq!(guest.call("strncpy_s", &[DEST, 7, SRC, TRUNCATE]), 0);
assert_eq!(text(&guest, DEST), "abcdef");
// A count of zero empties the destination even with a null source.
assert_eq!(guest.call("strncpy_s", &[DEST, 4, 0, 0]), 0);
assert_eq!(text(&guest, DEST), "");
assert_eq!(guest.call("strncpy_s", &[DEST, 4, 0, 2]), EINVAL);
}
#[test]
fn strncat_s_appends_up_to_count_or_truncates() {
let mut guest = Guest::new(IMPORTS, &[]);
put(&mut guest, DEST, "12");
put(&mut guest, SRC, "34567");
assert_eq!(guest.call("strncat_s", &[DEST, 8, SRC, 2]), 0);
assert_eq!(text(&guest, DEST), "1234");
assert_eq!(
guest.call("strncat_s", &[DEST, 8, SRC, TRUNCATE]),
STRUNCATE
);
assert_eq!(text(&guest, DEST), "1234345");
put(&mut guest, DEST, "12");
assert_eq!(guest.call("strncat_s", &[DEST, 5, SRC, 3]), ERANGE);
assert_eq!(text(&guest, DEST), "");
}
#[test]
fn wide_forms_count_characters_not_bytes() {
let mut guest = Guest::new(IMPORTS, &[]);
put_wide(&mut guest, SRC, "héllo");
assert_eq!(guest.call("wcscpy_s", &[DEST, 6, SRC]), 0);
assert_eq!(wide(&guest, DEST), "héllo");
assert_eq!(guest.call("wcscpy_s", &[DEST, 5, SRC]), ERANGE);
assert_eq!(guest.u16_at(DEST), 0);
put_wide(&mut guest, DEST, "ab");
put_wide(&mut guest, SRC, "cd");
assert_eq!(guest.call("wcscat_s", &[DEST, 5, SRC]), 0);
assert_eq!(wide(&guest, DEST), "abcd");
put_wide(&mut guest, SRC, "wxyz");
assert_eq!(
guest.call("wcsncpy_s", &[DEST, 3, SRC, TRUNCATE]),
STRUNCATE
);
assert_eq!(wide(&guest, DEST), "wx");
// The string API set reaches the same service.
assert_eq!(guest.call("wcsncat_s", &[DEST, 4, SRC, 1]), 0);
assert_eq!(wide(&guest, DEST), "wxw");
}
@@ -0,0 +1,266 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Character and line stdio on in-memory CRT streams through the guest import
//! table. Expectations follow the public UCRT pages for fputc, putc, fputs,
//! puts, fgetc, getc, fflush, ungetc and fgets: the character functions return
//! the byte as an unsigned char or EOF, fputs and puts return a non-negative
//! value or EOF, fflush returns 0 or EOF, ungetc returns the pushed-back byte
//! or EOF, and fgets returns the buffer or a null pointer.
mod support;
use support::*;
const UCRT: &str = "ucrtbase.dll";
const IMPORTS: &[(&str, &str)] = &[
(UCRT, "fopen"),
(UCRT, "fclose"),
(UCRT, "feof"),
(UCRT, "ferror"),
(UCRT, "fputc"),
(UCRT, "putc"),
(UCRT, "fputs"),
(UCRT, "puts"),
(UCRT, "fgetc"),
("api-ms-win-crt-stdio-l1-1-0.dll", "getc"),
(UCRT, "fflush"),
(UCRT, "ungetc"),
(UCRT, "fgets"),
(UCRT, "fread"),
(UCRT, "fseek"),
(UCRT, "ftell"),
(UCRT, "_errno"),
];
const EOF: u64 = u32::MAX as u64;
const NAME: u64 = SCRATCH;
const WRITE: u64 = SCRATCH + 0x40;
const READ: u64 = SCRATCH + 0x48;
const TEXT: u64 = SCRATCH + 0x80;
const UPDATE: u64 = SCRATCH + 0x50;
const LINE: u64 = SCRATCH + 0x200;
fn guest() -> Guest {
let mut guest = Guest::new(IMPORTS, &[]);
guest.memory.write_bytes(NAME, b"chars.txt\0").unwrap();
guest.memory.write_bytes(WRITE, b"w\0").unwrap();
guest.memory.write_bytes(READ, b"r\0").unwrap();
guest.memory.write_bytes(UPDATE, b"r+\0").unwrap();
guest
}
/// Write `contents` to chars.txt and open it with `mode`.
fn file_with(guest: &mut Guest, contents: &[u8], mode: u64) -> u64 {
let out = guest.call("fopen", &[NAME, WRITE]);
for &byte in contents {
guest.call("fputc", &[u64::from(byte), out]);
}
assert_eq!(guest.call("fclose", &[out]), 0);
let stream = guest.call("fopen", &[NAME, mode]);
assert_ne!(stream, 0);
stream
}
fn c_string(guest: &Guest, at: u64) -> Vec<u8> {
let mut bytes = Vec::new();
while let Ok(byte) = guest.memory.read_u8(at + bytes.len() as u64) {
if byte == 0 {
break;
}
bytes.push(byte);
}
bytes
}
fn read_all(guest: &mut Guest, stream: u64) -> Vec<u8> {
let mut bytes = Vec::new();
loop {
let byte = guest.call("fgetc", &[stream]);
if byte == EOF {
return bytes;
}
assert!(byte <= 0xFF, "fgetc returns an unsigned char");
bytes.push(byte as u8);
}
}
#[test]
fn characters_and_lines_round_trip_through_a_file() {
let mut guest = guest();
let out = guest.call("fopen", &[NAME, WRITE]);
assert_ne!(out, 0);
// fputc writes (unsigned char)c and returns it.
assert_eq!(guest.call("fputc", &[0x141, out]), 0x41);
assert_eq!(guest.call("putc", &[0xFF, out]), 0xFF);
guest.memory.write_bytes(TEXT, b"line one\0").unwrap();
assert_eq!(guest.call("fputs", &[TEXT, out]), 0, "no newline appended");
assert_eq!(guest.call("fclose", &[out]), 0);
let input = guest.call("fopen", &[NAME, READ]);
assert_eq!(read_all(&mut guest, input), b"A\xFFline one");
assert_ne!(guest.call("feof", &[input]), 0);
assert_eq!(guest.call("ferror", &[input]), 0);
// Writing to a read-only stream fails and sets the error indicator.
assert_eq!(guest.call("fputc", &[b'x' as u64, input]), EOF);
assert_ne!(guest.call("ferror", &[input]), 0);
assert_eq!(guest.call("fclose", &[input]), 0);
}
#[test]
fn reading_a_write_only_stream_fails() {
let mut guest = guest();
let out = guest.call("fopen", &[NAME, WRITE]);
assert_eq!(guest.call("fgetc", &[out]), EOF);
assert_ne!(guest.call("ferror", &[out]), 0);
assert_eq!(
guest.call("getc", &[out]),
EOF,
"the stdio API set reaches the same service"
);
assert_eq!(guest.call("fclose", &[out]), 0);
}
#[test]
fn fflush_publishes_contents_before_close() {
let mut guest = guest();
let out = guest.call("fopen", &[NAME, WRITE]);
guest.memory.write_bytes(TEXT, b"early\0").unwrap();
guest.call("fputs", &[TEXT, out]);
assert_eq!(guest.call("fflush", &[out]), 0);
// A second stream sees the flushed contents while the first is open.
let input = guest.call("fopen", &[NAME, READ]);
assert_eq!(read_all(&mut guest, input), b"early");
assert_eq!(
guest.call("fflush", &[input]),
0,
"flushing input has no effect"
);
assert_eq!(guest.call("fflush", &[0]), 0, "null flushes every stream");
assert_eq!(guest.call("fclose", &[input]), 0);
assert_eq!(guest.call("fclose", &[out]), 0);
}
#[test]
fn puts_writes_a_line_to_standard_output() {
let mut guest = guest();
guest.memory.write_bytes(TEXT, b"hello\0").unwrap();
// Standard output accepts and discards output; puts reports success.
assert_eq!(guest.call("puts", &[TEXT]), 0);
}
#[test]
fn ungetc_pushes_back_one_byte_that_reads_next() {
let mut guest = guest();
let input = file_with(&mut guest, b"abc", READ);
assert_eq!(guest.call("fgetc", &[input]), u64::from(b'a'));
// The same byte: the position simply steps back.
assert_eq!(
guest.call("ungetc", &[u64::from(b'a'), input]),
u64::from(b'a')
);
assert_eq!(guest.call("ftell", &[input]), 0);
assert_eq!(guest.call("fgetc", &[input]), u64::from(b'a'));
// A different byte reads in its place; ftell counts it as unread.
assert_eq!(guest.call("fgetc", &[input]), u64::from(b'b'));
assert_eq!(
guest.call("ungetc", &[0x1_7A, input]),
0x7A,
"unsigned char"
);
assert_eq!(guest.call("ftell", &[input]), 1);
// Only one byte of push-back is guaranteed.
assert_eq!(guest.call("ungetc", &[u64::from(b'q'), input]), EOF);
assert_eq!(read_all(&mut guest, input), b"zc");
assert_eq!(guest.call("fclose", &[input]), 0);
}
#[test]
fn ungetc_rejects_eof_clears_the_eof_indicator_and_is_discarded_by_seeks() {
let mut guest = guest();
let input = file_with(&mut guest, b"xy", READ);
// Nothing read yet: there is no byte to push back over.
assert_eq!(guest.call("ungetc", &[u64::from(b'w'), input]), EOF);
assert_eq!(read_all(&mut guest, input), b"xy");
assert_ne!(guest.call("feof", &[input]), 0);
assert_eq!(guest.call("ungetc", &[EOF, input]), EOF);
assert_eq!(
guest.call("ungetc", &[u64::from(b'Y'), input]),
u64::from(b'Y')
);
assert_eq!(guest.call("feof", &[input]), 0);
// fread sees the pushed-back byte first.
assert_eq!(guest.call("fread", &[LINE, 1, 4, input]), 1);
assert_eq!(guest.memory.read_u8(LINE).unwrap(), b'Y');
// A seek discards a push-back.
assert_eq!(
guest.call("ungetc", &[u64::from(b'Q'), input]),
u64::from(b'Q')
);
assert_eq!(guest.call("fseek", &[input, 0, 0]), 0);
assert_eq!(read_all(&mut guest, input), b"xy");
assert_eq!(guest.call("fclose", &[input]), 0);
}
#[test]
fn a_pushed_back_byte_never_reaches_the_file() {
let mut guest = guest();
let update = file_with(&mut guest, b"kept", UPDATE);
assert_eq!(guest.call("fgetc", &[update]), u64::from(b'k'));
assert_eq!(
guest.call("ungetc", &[u64::from(b'X'), update]),
u64::from(b'X')
);
assert_eq!(guest.call("fclose", &[update]), 0);
let input = guest.call("fopen", &[NAME, READ]);
assert_eq!(read_all(&mut guest, input), b"kept");
assert_eq!(guest.call("fclose", &[input]), 0);
}
#[test]
fn fgets_reads_lines_up_to_the_count() {
let mut guest = guest();
let input = file_with(&mut guest, b"one\ntwo words\nend", READ);
assert_eq!(guest.call("fgets", &[LINE, 64, input]), LINE);
assert_eq!(c_string(&guest, LINE), b"one\n", "keeps the newline");
// A count of 5 reads at most four bytes.
assert_eq!(guest.call("fgets", &[LINE, 5, input]), LINE);
assert_eq!(c_string(&guest, LINE), b"two ");
assert_eq!(guest.call("fgets", &[LINE, 64, input]), LINE);
assert_eq!(c_string(&guest, LINE), b"words\n");
// The last line has no newline; end of file ends it.
assert_eq!(guest.call("fgets", &[LINE, 64, input]), LINE);
assert_eq!(c_string(&guest, LINE), b"end");
assert_ne!(guest.call("feof", &[input]), 0);
// At end of file with nothing read: null, buffer unchanged.
guest.memory.write_bytes(LINE, b"keep\0").unwrap();
assert_eq!(guest.call("fgets", &[LINE, 64, input]), 0);
assert_eq!(c_string(&guest, LINE), b"keep");
assert_eq!(guest.call("fclose", &[input]), 0);
}
#[test]
fn fgets_validates_its_arguments() {
let mut guest = guest();
let input = file_with(&mut guest, b"abc", READ);
let errno = guest.call("_errno", &[]);
for (buffer, count) in [(0, 8), (LINE, 0), (LINE, u64::from(u32::MAX))] {
guest.memory.write_u32(errno, 0).unwrap();
assert_eq!(guest.call("fgets", &[buffer, count, input]), 0);
assert_eq!(
guest.u32_at(errno),
22,
"EINVAL for {buffer:#x}, {count:#x}"
);
}
// A count of one stores just the terminator and reads nothing.
guest.memory.write_bytes(LINE, b"zz\0").unwrap();
assert_eq!(guest.call("fgets", &[LINE, 1, input]), LINE);
assert_eq!(guest.memory.read_u8(LINE).unwrap(), 0);
assert_eq!(guest.call("fgetc", &[input]), u64::from(b'a'));
// A write-only stream cannot be read.
let out = guest.call("fopen", &[NAME, WRITE]);
assert_eq!(guest.call("fgets", &[LINE, 8, out]), 0);
assert_ne!(guest.call("ferror", &[out]), 0);
assert_eq!(guest.call("fclose", &[out]), 0);
assert_eq!(guest.call("fclose", &[input]), 0);
}
@@ -0,0 +1,68 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! strncpy and wcsncpy through the guest import table. C requires both to pad
//! the destination with zeros up to the count. The count comes from the guest,
//! so a count far past the destination must fault the guest at the first byte
//! it cannot write, not exhaust host memory. The runtime_services fuzz replay
//! found the original host crash with an all-ones count.
mod support;
use support::*;
use xenora_loader::cpu::ExitReason;
const UCRT: &str = "ucrtbase.dll";
const IMPORTS: &[(&str, &str)] = &[(UCRT, "strncpy"), (UCRT, "wcsncpy")];
const SRC: u64 = SCRATCH;
const DEST: u64 = SCRATCH + 0x100;
#[test]
fn strncpy_pads_to_the_count() {
let mut guest = Guest::new(IMPORTS, &[]);
guest.memory.write_bytes(SRC, b"ab\0").unwrap();
guest.memory.write_bytes(DEST, &[b'#'; 16]).unwrap();
assert_eq!(guest.call("strncpy", &[DEST, SRC, 8]), DEST);
let mut out = [0u8; 9];
for (i, byte) in out.iter_mut().enumerate() {
*byte = guest.memory.read_u8(DEST + i as u64).unwrap();
}
assert_eq!(
&out, b"ab\0\0\0\0\0\0#",
"padded to eight bytes, no further"
);
}
#[test]
fn wcsncpy_pads_to_the_count_in_characters() {
let mut guest = Guest::new(IMPORTS, &[]);
guest.memory.write_u16(SRC, u16::from(b'x')).unwrap();
guest.memory.write_u16(SRC + 2, 0).unwrap();
guest.memory.write_bytes(DEST, &[0xFF; 16]).unwrap();
assert_eq!(guest.call("wcsncpy", &[DEST, SRC, 4]), DEST);
assert_eq!(guest.u16_at(DEST), u16::from(b'x'));
for i in 1..4 {
assert_eq!(guest.u16_at(DEST + 2 * i), 0);
}
assert_eq!(
guest.u16_at(DEST + 8),
0xFFFF,
"four characters, no further"
);
}
#[test]
fn a_count_past_the_destination_faults_the_guest() {
let mut guest = Guest::new(IMPORTS, &[]);
guest.memory.write_bytes(SRC, b"ab\0").unwrap();
guest.memory.write_u16(SRC + 0x10, 0).unwrap();
for (symbol, source) in [("strncpy", SRC), ("wcsncpy", SRC + 0x10)] {
for count in [u64::MAX, SCRATCH_LEN * 4] {
let reason = guest.fails(symbol, &[DEST, source, count]);
assert!(
matches!(reason, ExitReason::MemoryFault(_)),
"{symbol} count {count:#x}: {reason:?}"
);
}
}
}
+186
View File
@@ -0,0 +1,186 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! C++ `type_info` helpers through the guest import table. Each type
//! descriptor's data is an 8-byte cached-name slot followed by the decorated
//! name, per the publicly described MSVC RTTI type descriptor layout. The
//! decorated names here are written by hand for these tests.
mod support;
use support::*;
use xenora_loader::cpu::ExitReason;
const IMPORTS: &[(&str, &str)] = &[
("vcruntime140.dll", "__std_type_info_compare"),
("vcruntime140.dll", "__std_type_info_hash"),
("vcruntime140.dll", "__std_type_info_name"),
("vcruntime140.dll", "__std_type_info_destroy_list"),
("vcruntime140.dll", "__std_exception_copy"),
("vcruntime140.dll", "__std_exception_destroy"),
("ucrtbase.dll", "malloc"),
("ucrtbase.dll", "free"),
];
const WIDGET: u64 = SCRATCH;
const WIDGET_COPY: u64 = SCRATCH + 0x40;
const POINT: u64 = SCRATCH + 0x80;
const COLOR: u64 = SCRATCH + 0xC0;
const TEMPLATE: u64 = SCRATCH + 0x100;
const LIST: u64 = SCRATCH + 0x200;
const ORIGINAL: u64 = SCRATCH + 0x300;
const COPY: u64 = SCRATCH + 0x320;
const MESSAGE: u64 = SCRATCH + 0x340;
fn descriptor(guest: &mut Guest, at: u64, name: &str) {
guest.memory.write_u64(at, 0).unwrap();
let mut bytes = name.as_bytes().to_vec();
bytes.push(0);
guest.memory.write_bytes(at + 8, &bytes).unwrap();
}
fn text(guest: &Guest, mut at: u64) -> String {
let mut bytes = Vec::new();
loop {
let byte = guest.memory.read_u8(at).unwrap();
if byte == 0 {
return String::from_utf8(bytes).unwrap();
}
bytes.push(byte);
at += 1;
}
}
fn guest() -> Guest {
let mut guest = Guest::new(IMPORTS, &[]);
descriptor(&mut guest, WIDGET, ".?AVWidget@ui@@");
// A second descriptor for the same type, as another module would carry.
descriptor(&mut guest, WIDGET_COPY, ".?AVWidget@ui@@");
descriptor(&mut guest, POINT, ".?AUPoint@@");
descriptor(&mut guest, COLOR, ".?AW4Color@@");
descriptor(&mut guest, TEMPLATE, ".?AV?$Box@H@@");
guest
}
fn compare(guest: &mut Guest, left: u64, right: u64) -> i32 {
guest.call("__std_type_info_compare", &[left, right]) as u32 as i32
}
#[test]
fn equal_types_compare_equal_across_descriptors_and_order_consistently() {
let mut guest = guest();
assert_eq!(compare(&mut guest, WIDGET, WIDGET), 0);
assert_eq!(compare(&mut guest, WIDGET, WIDGET_COPY), 0);
let forward = compare(&mut guest, WIDGET, POINT);
let backward = compare(&mut guest, POINT, WIDGET);
assert_ne!(forward, 0);
assert_eq!(forward, -backward, "before() is antisymmetric");
// 'U' (0x55) sorts before 'V' (0x56) in the decorated names.
assert_eq!(backward, -1);
}
#[test]
fn equal_types_hash_equally() {
let mut guest = guest();
let widget = guest.call("__std_type_info_hash", &[WIDGET]);
assert_eq!(guest.call("__std_type_info_hash", &[WIDGET_COPY]), widget);
assert_ne!(guest.call("__std_type_info_hash", &[POINT]), widget);
}
#[test]
fn name_undecorates_caches_and_is_released_by_destroy_list() {
let mut guest = guest();
let name = guest.call("__std_type_info_name", &[WIDGET, LIST]);
assert_ne!(name, 0);
assert_eq!(text(&guest, name), "class ui::Widget");
assert_eq!(guest.u64_at(WIDGET), name, "cached in the descriptor");
assert_eq!(guest.call("__std_type_info_name", &[WIDGET, LIST]), name);
let point = guest.call("__std_type_info_name", &[POINT, LIST]);
assert_eq!(text(&guest, point), "struct Point");
let color = guest.call("__std_type_info_name", &[COLOR, LIST]);
assert_eq!(text(&guest, color), "enum Color");
guest.call("__std_type_info_destroy_list", &[LIST]);
assert!(
guest.memory.read_u8(name).is_err(),
"destroy_list frees the names it allocated"
);
}
#[test]
fn unmodelled_names_and_bad_pointers_stop_the_guest() {
let mut guest = guest();
assert_eq!(
guest.fails("__std_type_info_name", &[TEMPLATE, LIST]),
RUNTIME_LIMIT
);
assert_eq!(guest.u64_at(TEMPLATE), 0, "nothing cached");
assert!(matches!(
guest.fails("__std_type_info_compare", &[WIDGET, 0x10]),
ExitReason::MemoryFault(_)
));
assert!(matches!(
guest.fails("__std_type_info_hash", &[0]),
ExitReason::MemoryFault(_)
));
}
fn record(guest: &mut Guest, at: u64, text: u64, owned: bool) {
guest.memory.write_u64(at, text).unwrap();
guest.memory.write_u8(at + 8, u8::from(owned)).unwrap();
}
fn owned_flag(guest: &Guest, at: u64) -> u8 {
guest.memory.read_u8(at + 8).unwrap()
}
#[test]
fn exception_copies_duplicate_owned_messages_and_share_borrowed_ones() {
let mut guest = guest();
// A borrowed literal is shared, never freed.
guest.memory.write_bytes(MESSAGE, b"literal\0").unwrap();
record(&mut guest, ORIGINAL, MESSAGE, false);
record(&mut guest, COPY, 0xDEAD, true);
guest.call("__std_exception_copy", &[ORIGINAL, COPY]);
assert_eq!(guest.u64_at(COPY), MESSAGE);
assert_eq!(owned_flag(&guest, COPY), 0);
guest.call("__std_exception_destroy", &[COPY]);
assert_eq!(text(&guest, MESSAGE), "literal");
assert_eq!((guest.u64_at(COPY), owned_flag(&guest, COPY)), (0, 0));
// An owned message from guest malloc gets its own copy, so destroying
// the original leaves the copy's what() intact.
let owned = guest.call("malloc", &[16]);
guest.memory.write_bytes(owned, b"bad_alloc\0").unwrap();
record(&mut guest, ORIGINAL, owned, true);
guest.call("__std_exception_copy", &[ORIGINAL, COPY]);
let duplicate = guest.u64_at(COPY);
assert_ne!(duplicate, owned);
assert_eq!(owned_flag(&guest, COPY), 1);
guest.call("__std_exception_destroy", &[ORIGINAL]);
assert!(guest.memory.read_u8(owned).is_err(), "original text freed");
assert_eq!(text(&guest, duplicate), "bad_alloc");
// The duplicate came from the CRT heap, so guest free releases it.
guest.call("free", &[duplicate]);
assert!(guest.memory.read_u8(duplicate).is_err());
}
#[test]
fn exception_records_with_no_message_or_bad_pointers() {
let mut guest = guest();
record(&mut guest, ORIGINAL, 0, true);
record(&mut guest, COPY, 0xDEAD, true);
guest.call("__std_exception_copy", &[ORIGINAL, COPY]);
assert_eq!((guest.u64_at(COPY), owned_flag(&guest, COPY)), (0, 0));
guest.call("__std_exception_destroy", &[COPY]);
// An owned pointer the heap never allocated is a guest bug, not a no-op.
record(&mut guest, ORIGINAL, MESSAGE, true);
assert!(matches!(
guest.fails("__std_exception_destroy", &[ORIGINAL]),
ExitReason::MemoryFault(_)
));
assert!(matches!(
guest.fails("__std_exception_copy", &[0x10, COPY]),
ExitReason::MemoryFault(_)
));
}
File diff suppressed because it is too large. Load diff
+137
View File
@@ -334,6 +334,143 @@ fn system_time_comes_from_the_injected_clock() {
}
}
fn tokenization_guest(symbol: &'static str) -> (DbtEngine, GuestMemory) {
let image = build(&[
("ucrtbase.dll", Symbol::Name(symbol)),
("api-ms-win-crt-string-l1-1-0.dll", Symbol::Name(symbol)),
("ucrtbase.dll", Symbol::Name("_errno")),
]);
let pe = ParsedPe::parse(&image.bytes).unwrap();
let mut memory = pe.load_into_memory(&image.bytes).unwrap().memory;
memory
.map_region(SCRATCH, 4096, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region(STACK, 4096, MemoryPermissions::READ_WRITE)
.unwrap();
let (mut registry, _) = standard(0);
assert_eq!(
registry
.bind_imports(&pe, &image.bytes, BASE, &mut memory)
.unwrap(),
3
);
let mut engine = DbtEngine::new(256 * 1024).unwrap();
engine.set_import_registry(registry);
(engine, memory)
}
fn call_tokenization_import(
engine: &mut DbtEngine,
memory: &mut GuestMemory,
slot: u32,
[input, separators, context]: [u64; 3],
) -> u64 {
let entry = BASE + u64::from(CODE_RVA + 16 * slot);
let mut cpu = CpuState::new(entry, STACK_TOP);
cpu.set(Register::Rcx, input);
cpu.set(Register::Rdx, separators);
cpu.set(Register::R8, context);
let result = engine.run(&mut cpu, memory, 8);
assert_eq!(result.exit_reason, ExitReason::Halt);
cpu.get(Register::Rax)
}
#[test]
fn guest_wcstok_s_resumes_in_wide_units_and_sets_errno() {
let (mut engine, mut memory) = tokenization_guest("wcstok_s");
let input = SCRATCH;
let delimiters = SCRATCH + 32;
let context = SCRATCH + 64;
for (index, value) in [0x2603, 0x03bb, 0x2603, 0x03bc, 0].into_iter().enumerate() {
memory.write_u16(input + 2 * index as u64, value).unwrap();
}
memory.write_u16(delimiters, 0x2603).unwrap();
let mut call = |memory: &mut GuestMemory, slot, args| {
call_tokenization_import(&mut engine, memory, slot, args)
};
let errno = call(&mut memory, 2, [0; 3]);
assert_eq!(call(&mut memory, 1, [0, delimiters, context]), 0);
assert_eq!(memory.read_u32(errno).unwrap(), 22);
memory.write_u32(errno, 0).unwrap();
assert_eq!(
call(&mut memory, 0, [input, delimiters, context]),
input + 2
);
assert_eq!(memory.read_u16(input + 4).unwrap(), 0);
assert_eq!(memory.read_u64(context).unwrap(), input + 6);
assert_eq!(call(&mut memory, 1, [0, delimiters, context]), input + 6);
assert_eq!(call(&mut memory, 1, [0, delimiters, context]), 0);
assert_eq!(memory.read_u64(context).unwrap(), input + 8);
assert_eq!(memory.read_u32(errno).unwrap(), 0);
}
#[test]
fn guest_wcstok_resumes_from_its_win64_context_argument() {
let (mut engine, mut memory) = tokenization_guest("wcstok");
let input = SCRATCH;
let separators = SCRATCH + 32;
let context = SCRATCH + 64;
let write = |memory: &mut GuestMemory, at, text: &str| {
let data: Vec<_> = text
.encode_utf16()
.chain([0])
.flat_map(u16::to_le_bytes)
.collect();
memory.write_bytes(at, &data).unwrap();
};
write(&mut memory, input, "☃λ☃μ;ν");
write(&mut memory, separators, "☃");
let mut call = |memory: &mut GuestMemory, slot, text| {
call_tokenization_import(&mut engine, memory, slot, [text, separators, context])
};
assert_eq!(call(&mut memory, 0, input), input + 2);
assert_eq!(memory.read_u16(input + 4).unwrap(), 0);
assert_eq!(memory.read_u64(context).unwrap(), input + 6);
write(&mut memory, separators, ";");
assert_eq!(call(&mut memory, 1, 0), input + 6);
assert_eq!(memory.read_u16(input + 8).unwrap(), 0);
assert_eq!(call(&mut memory, 0, 0), input + 10);
assert_eq!(memory.read_u64(context).unwrap(), 0);
assert_eq!(call(&mut memory, 1, 0), 0);
}
#[test]
fn guest_strtok_s_shares_context_across_win64_import_aliases() {
let (mut engine, mut memory) = tokenization_guest("strtok_s");
let input = SCRATCH;
let delimiters = SCRATCH + 32;
let context = SCRATCH + 64;
memory.write_bytes(input, b",a,b;c\0").unwrap();
memory.write_bytes(delimiters, b",\0;\0").unwrap();
let mut call = |memory: &mut GuestMemory, slot, args| {
call_tokenization_import(&mut engine, memory, slot, args)
};
let errno = call(&mut memory, 2, [0; 3]);
assert_eq!(call(&mut memory, 1, [0, delimiters, context]), 0);
assert_eq!(memory.read_u32(errno).unwrap(), 22);
memory.write_u32(errno, 0).unwrap();
assert_eq!(
call(&mut memory, 0, [input, delimiters, context]),
input + 1
);
assert_eq!(memory.read_u8(input + 2).unwrap(), 0);
assert_eq!(memory.read_u64(context).unwrap(), input + 3);
assert_eq!(
call(&mut memory, 1, [0, delimiters + 2, context]),
input + 3
);
assert_eq!(memory.read_u8(input + 4).unwrap(), 0);
assert_eq!(call(&mut memory, 0, [0, delimiters, context]), input + 5);
assert_eq!(call(&mut memory, 1, [0, delimiters, context]), 0);
assert_eq!(memory.read_u64(context).unwrap(), input + 6);
assert_eq!(memory.read_u32(errno).unwrap(), 0);
}
#[test]
fn guest_udp_loopback_delivers_datagrams_through_bound_imports() {
let symbols = [
+134
View File
@@ -250,3 +250,137 @@ fn sleeping_advances_the_injected_clock() {
assert_eq!(guest.fails("SleepEx", &[60_000, 0]), RUNTIME_LIMIT);
assert_eq!(guest.call("GetTickCount64", &[]), 255);
}
/// `IsProcessorFeaturePresent` must agree with what translated guest code sees
/// when it executes `CPUID`, bit for bit, per the CPUID feature flags in the
/// public Intel and AMD manuals and the `PF_*` numbers in winnt.h.
#[test]
fn processor_features_agree_with_guest_cpuid() {
const FEATURES: &[(&str, &str)] = &[
("kernel32.dll", "IsProcessorFeaturePresent"),
(
"api-ms-win-core-processthreads-l1-1-0.dll",
"IsProcessorFeaturePresent",
),
];
// mov eax, leaf; xor ecx, ecx; cpuid; hlt
let leaf = |n: u8| vec![0xB8, n, 0, 0, 0, 0x31, 0xC9, 0x0F, 0xA2, 0xF4];
let mut guest = Guest::new(FEATURES, &[leaf(1), leaf(7)]);
let registers = |guest: &mut Guest, index| {
use xenora_loader::cpu::{ExitReason, Register};
let (cpu, exit) = guest.execute(routine(index), 16);
assert_eq!(exit, ExitReason::Halt);
(
cpu.get(Register::Rbx) as u32,
cpu.get(Register::Rcx) as u32,
cpu.get(Register::Rdx) as u32,
)
};
let (_, ecx1, edx1) = registers(&mut guest, 0);
let (ebx7, _, _) = registers(&mut guest, 1);
let cases = [
(2, edx1 & (1 << 8) != 0),
(3, edx1 & (1 << 23) != 0),
(6, edx1 & (1 << 25) != 0),
(8, edx1 & (1 << 4) != 0),
(10, edx1 & (1 << 26) != 0),
(13, ecx1 & 1 != 0),
(14, ecx1 & (1 << 13) != 0),
(17, ecx1 & (3 << 26) == 3 << 26),
(28, ecx1 & (1 << 30) != 0),
(36, ecx1 & (1 << 9) != 0),
(37, ecx1 & (1 << 19) != 0),
(38, ecx1 & (1 << 20) != 0),
(39, ecx1 & (1 << 28) != 0),
(40, ebx7 & (1 << 5) != 0),
];
for (feature, expected) in cases {
let answer = guest.call("IsProcessorFeaturePresent", &[feature]);
assert_eq!(answer, u64::from(expected), "PF {feature}");
}
// No CPUID test exists for these, so they are not claimed:
// PF_NX_ENABLED (12), PF_FASTFAIL_AVAILABLE (23), and unknown numbers.
for feature in [12, 23, 9999, u32::MAX as u64] {
assert_eq!(guest.call("IsProcessorFeaturePresent", &[feature]), 0);
}
}
/// `TIME_ZONE_INFORMATION` (172 bytes) and `TIME_ZONE_ID_UNKNOWN` per the
/// public GetTimeZoneInformation page: a zone without daylight saving.
#[test]
fn time_zone_is_utc_without_daylight_saving() {
const ZONE: &[(&str, &str)] = &[
(
"api-ms-win-core-timezone-l1-1-0.dll",
"GetTimeZoneInformation",
),
("kernel32.dll", "GetLastError"),
];
let mut guest = Guest::new(ZONE, &[]);
guest.memory.write_bytes(SCRATCH, &[0xCC; 176]).unwrap();
assert_eq!(guest.call("GetTimeZoneInformation", &[SCRATCH]), 0);
let name = |offset: u64| {
let units: Vec<u16> = (0..32)
.map(|i| guest.u16_at(SCRATCH + offset + 2 * i))
.collect();
String::from_utf16(&units[..units.iter().position(|&u| u == 0).unwrap()]).unwrap()
};
assert_eq!(name(4), "Coordinated Universal Time");
assert_eq!(name(88), "Coordinated Universal Time");
assert_eq!(guest.u32_at(SCRATCH), 0, "Bias");
for (offset, length) in [(68, 20), (152, 20)] {
for byte in 0..length {
assert_eq!(guest.memory.read_u8(SCRATCH + offset + byte).unwrap(), 0);
}
}
assert_eq!(
guest.u32_at(SCRATCH + 172),
0xCCCC_CCCC,
"nothing past the struct"
);
assert_eq!(guest.call("GetTimeZoneInformation", &[0]), u32::MAX as u64);
assert_eq!(guest.error(), 998);
}
/// SYSTEM_LOGICAL_PROCESSOR_INFORMATION entries are 32 bytes on x64; a short
/// buffer fails with ERROR_INSUFFICIENT_BUFFER and the required length.
#[test]
fn processor_topology_follows_the_guest_profile() {
const TOPOLOGY: &[(&str, &str)] = &[
(
"api-ms-win-core-sysinfo-l1-1-0.dll",
"GetLogicalProcessorInformation",
),
("kernel32.dll", "GetLastError"),
];
let length = SCRATCH + 0x800;
let mut state = ServicesState::new(Arc::new(MockClock::new(0)));
state.guest_profile = GuestSystemProfile { processors: 2 };
let mut guest = Guest::with_state(TOPOLOGY, &[], state);
guest.memory.write_u32(length, 0).unwrap();
assert_eq!(
guest.call("GetLogicalProcessorInformation", &[0, length]),
0
);
assert_eq!(guest.error(), 122);
// Two cores and one package.
assert_eq!(guest.u32_at(length), 3 * 32);
assert_eq!(
guest.call("GetLogicalProcessorInformation", &[SCRATCH, length]),
1
);
let entry = |index: u64| {
(
guest.u64_at(SCRATCH + 32 * index),
guest.u32_at(SCRATCH + 32 * index + 8),
)
};
assert_eq!(entry(0), (0b01, 0), "RelationProcessorCore");
assert_eq!(entry(1), (0b10, 0), "RelationProcessorCore");
assert_eq!(entry(2), (0b11, 3), "RelationProcessorPackage");
assert_eq!(
guest.call("GetLogicalProcessorInformation", &[SCRATCH, 0]),
0
);
assert_eq!(guest.error(), 998);
}
@@ -0,0 +1,338 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Process-local TCP loopback through the guest import table. Two guest
//! sockets connect on 127.0.0.1 and exchange a byte stream; no host socket is
//! opened. Expected results follow the public Winsock reference pages for
//! socket, bind, listen, accept, connect, send, recv, shutdown, closesocket,
//! WSAPoll and getsockopt, and the Windows Sockets error code list.
mod support;
use support::*;
const WS2: &str = "ws2_32.dll";
const IMPORTS: &[(&str, &str)] = &[
(WS2, "WSAStartup"),
(WS2, "WSAGetLastError"),
(WS2, "socket"),
(WS2, "closesocket"),
(WS2, "bind"),
(WS2, "listen"),
(WS2, "accept"),
(WS2, "connect"),
(WS2, "send"),
(WS2, "recv"),
(WS2, "sendto"),
(WS2, "shutdown"),
(WS2, "getsockname"),
(WS2, "getsockopt"),
(WS2, "WSAPoll"),
(WS2, "ioctlsocket"),
];
const ERROR: u64 = u32::MAX as u64;
const INVALID_SOCKET: u64 = u64::MAX;
const WSAEACCES: u64 = 10013;
const WSAEINVAL: u64 = 10022;
const WSAEWOULDBLOCK: u64 = 10035;
const WSAEOPNOTSUPP: u64 = 10045;
const WSAECONNRESET: u64 = 10054;
const WSAEISCONN: u64 = 10056;
const WSAENOTCONN: u64 = 10057;
const WSAESHUTDOWN: u64 = 10058;
const WSAECONNREFUSED: u64 = 10061;
const POLLHUP: u16 = 0x0002;
const POLLWRNORM: u16 = 0x0010;
const POLLRDNORM: u16 = 0x0100;
const ADDRESS: u64 = SCRATCH;
const PEER: u64 = SCRATCH + 0x20;
const LENGTH: u64 = SCRATCH + 0x40;
const POLL: u64 = SCRATCH + 0x60;
const VALUE: u64 = SCRATCH + 0x80;
const WSADATA: u64 = SCRATCH + 0x100;
const BUFFER: u64 = SCRATCH + 0x400;
const CHUNK: u64 = 1024;
struct Net(Guest);
impl Net {
fn new() -> Self {
let mut guest = Guest::new(IMPORTS, &[]);
assert_eq!(guest.call("WSAStartup", &[0x0202, WSADATA]), 0);
Self(guest)
}
/// The function's result, or its WSAGetLastError code when it returned
/// `failure`.
fn call(&mut self, symbol: &str, args: &[u64], failure: u64) -> Result<u64, u64> {
let result = self.0.call(symbol, args);
if result == failure {
Err(self.0.call("WSAGetLastError", &[]))
} else {
Ok(result)
}
}
fn put_address(&mut self, ip: [u8; 4], port: u16) {
let mut data = [0; 16];
data[..2].copy_from_slice(&2_u16.to_le_bytes());
data[2..4].copy_from_slice(&port.to_be_bytes());
data[4..8].copy_from_slice(&ip);
self.0.memory.write_bytes(ADDRESS, &data).unwrap();
}
fn stream(&mut self) -> u64 {
self.call("socket", &[2, 1, 6], INVALID_SOCKET).unwrap()
}
fn bind(&mut self, socket: u64, port: u16) -> Result<u64, u64> {
self.put_address([127, 0, 0, 1], port);
self.call("bind", &[socket, ADDRESS, 16], ERROR)
}
fn connect(&mut self, socket: u64, ip: [u8; 4], port: u16) -> Result<u64, u64> {
self.put_address(ip, port);
self.call("connect", &[socket, ADDRESS, 16], ERROR)
}
fn accept(&mut self, listener: u64) -> Result<(u64, u16), u64> {
self.0.memory.write_u32(LENGTH, 16).unwrap();
let socket = self.call("accept", &[listener, PEER, LENGTH], INVALID_SOCKET)?;
assert_eq!(self.0.u32_at(LENGTH), 16);
assert_eq!(self.0.u16_at(PEER), 2);
let mut ip = [0; 4];
self.0.memory.read_bytes(PEER + 4, &mut ip).unwrap();
assert_eq!(ip, [127, 0, 0, 1]);
Ok((socket, u16::from_be(self.0.u16_at(PEER + 2))))
}
fn local_port(&mut self, socket: u64) -> u16 {
self.0.memory.write_u32(LENGTH, 16).unwrap();
self.call("getsockname", &[socket, PEER, LENGTH], ERROR)
.unwrap();
u16::from_be(self.0.u16_at(PEER + 2))
}
fn send(&mut self, socket: u64, bytes: &[u8]) -> Result<u64, u64> {
self.0.memory.write_bytes(BUFFER, bytes).unwrap();
self.call("send", &[socket, BUFFER, bytes.len() as u64, 0], ERROR)
}
fn recv(&mut self, socket: u64, capacity: u64) -> Result<Vec<u8>, u64> {
let received = self.call("recv", &[socket, BUFFER, capacity, 0], ERROR)?;
let mut bytes = vec![0; received as usize];
self.0.memory.read_bytes(BUFFER, &mut bytes).unwrap();
Ok(bytes)
}
fn poll(&mut self, socket: u64, events: u16) -> u16 {
self.0.memory.write_u64(POLL, socket).unwrap();
self.0.memory.write_u16(POLL + 8, events).unwrap();
self.0.memory.write_u16(POLL + 10, 0xffff).unwrap();
self.call("WSAPoll", &[POLL, 1, 0], ERROR).unwrap();
self.0.u16_at(POLL + 10)
}
}
#[test]
fn loopback_tcp_connects_streams_and_closes_between_guest_sockets() {
let mut net = Net::new();
let listener = net.stream();
// listen needs a bound socket.
assert_eq!(net.call("listen", &[listener, 4], ERROR), Err(WSAEINVAL));
assert_eq!(net.bind(listener, 5000), Ok(0));
assert_eq!(net.call("listen", &[listener, 0x7fff_ffff], ERROR), Ok(0));
assert_eq!(net.accept(listener), Err(WSAEWOULDBLOCK));
assert_eq!(net.poll(listener, POLLRDNORM), 0);
let client = net.stream();
assert_eq!(net.connect(client, [127, 0, 0, 1], 5000), Ok(0));
assert_eq!(net.connect(client, [127, 0, 0, 1], 5000), Err(WSAEISCONN));
assert_eq!(net.poll(listener, POLLRDNORM), POLLRDNORM);
let client_port = net.local_port(client);
let (server, peer_port) = net.accept(listener).unwrap();
assert_eq!(peer_port, client_port);
assert_eq!(net.local_port(server), 5000);
assert_eq!(net.accept(listener), Err(WSAEWOULDBLOCK));
// A byte stream keeps no message boundaries.
assert_eq!(net.recv(server, 16), Err(WSAEWOULDBLOCK));
assert_eq!(net.send(client, b"hello"), Ok(5));
assert_eq!(net.send(client, b" world"), Ok(6));
assert_eq!(
net.poll(server, POLLRDNORM | POLLWRNORM),
POLLRDNORM | POLLWRNORM
);
assert_eq!(net.recv(server, 3).unwrap(), b"hel");
assert_eq!(net.recv(server, 64).unwrap(), b"lo world");
assert_eq!(net.recv(server, 64), Err(WSAEWOULDBLOCK));
// The receiver buffers 64 KiB; then sends would block until it reads.
let chunk = vec![0x5a; CHUNK as usize];
let mut queued = 0;
while net.send(client, &chunk) == Ok(CHUNK) {
queued += CHUNK;
assert!(queued <= 64 * 1024);
}
assert_eq!(queued, 64 * 1024);
assert_eq!(net.send(client, &chunk), Err(WSAEWOULDBLOCK));
assert_eq!(net.poll(client, POLLWRNORM), 0);
assert_eq!(net.recv(server, CHUNK).unwrap(), chunk);
assert_eq!(net.poll(client, POLLWRNORM), POLLWRNORM);
assert_eq!(net.send(client, &chunk), Ok(CHUNK));
while queued != 0 {
assert_eq!(net.recv(server, CHUNK).unwrap().len() as u64, CHUNK);
queued -= CHUNK;
}
// Shutting down the client's sending side is end of file for the server;
// the server can still answer.
assert_eq!(net.send(client, b"last"), Ok(4));
assert_eq!(net.call("shutdown", &[client, 1], ERROR), Ok(0));
assert_eq!(net.send(client, b"more"), Err(WSAESHUTDOWN));
assert_eq!(net.recv(server, 64).unwrap(), b"last");
assert_eq!(net.recv(server, 64).unwrap(), b"");
assert_eq!(net.send(server, b"bye"), Ok(3));
assert_eq!(net.recv(client, 64).unwrap(), b"bye");
assert_eq!(net.call("shutdown", &[client, 9], ERROR), Err(WSAEINVAL));
// Closing one end gives the other end of file, a hang-up and resets.
assert_eq!(net.call("closesocket", &[client], ERROR), Ok(0));
assert_eq!(net.recv(server, 64).unwrap(), b"");
assert_eq!(net.poll(server, POLLRDNORM), POLLRDNORM | POLLHUP);
assert_eq!(net.send(server, b"x"), Err(WSAECONNRESET));
assert_eq!(net.call("closesocket", &[server], ERROR), Ok(0));
assert_eq!(net.call("closesocket", &[listener], ERROR), Ok(0));
}
#[test]
fn loopback_tcp_refuses_what_it_cannot_reach() {
let mut net = Net::new();
let listener = net.stream();
assert_eq!(net.bind(listener, 5001), Ok(0));
assert_eq!(net.call("listen", &[listener, 1], ERROR), Ok(0));
// Nothing listens on 5002; external addresses never leave the process.
let client = net.stream();
assert_eq!(
net.connect(client, [127, 0, 0, 1], 5002),
Err(WSAECONNREFUSED)
);
assert_eq!(net.connect(client, [10, 0, 0, 1], 5001), Err(WSAEACCES));
assert_eq!(net.send(client, b"x"), Err(WSAENOTCONN));
assert_eq!(net.recv(client, 4), Err(WSAENOTCONN));
// A backlog of one holds one waiting connection.
assert_eq!(net.connect(client, [127, 0, 0, 1], 5001), Ok(0));
let second = net.stream();
assert_eq!(
net.connect(second, [127, 0, 0, 1], 5001),
Err(WSAECONNREFUSED)
);
// Data sent before accept waits for the accepted socket.
assert_eq!(net.send(client, b"early"), Ok(5));
let (server, _) = net.accept(listener).unwrap();
assert_eq!(net.recv(server, 64).unwrap(), b"early");
assert_eq!(net.connect(second, [127, 0, 0, 1], 5001), Ok(0));
// Closing a listener closes connections it has not accepted.
assert_eq!(net.call("closesocket", &[listener], ERROR), Ok(0));
assert_eq!(net.recv(second, 64).unwrap(), b"");
assert_eq!(net.send(second, b"x"), Err(WSAECONNRESET));
// The accepted connection is unaffected.
assert_eq!(net.send(server, b"ok"), Ok(2));
assert_eq!(net.recv(client, 64).unwrap(), b"ok");
// TCP and UDP ports are separate, and each keeps its own operations.
let datagram = net.call("socket", &[2, 2, 17], INVALID_SOCKET).unwrap();
assert_eq!(net.bind(datagram, 5001), Ok(0));
assert_eq!(
net.call("listen", &[datagram, 1], ERROR),
Err(WSAEOPNOTSUPP)
);
assert_eq!(
net.call("shutdown", &[datagram, 1], ERROR),
Err(WSAEOPNOTSUPP)
);
net.0.memory.write_u32(LENGTH, 4).unwrap();
assert_eq!(
net.call(
"getsockopt",
&[client, 0xffff, 0x1008, VALUE, LENGTH],
ERROR
),
Ok(0)
);
assert_eq!(net.0.u32_at(VALUE), 1); // SOCK_STREAM
net.put_address([127, 0, 0, 1], 5001);
assert_eq!(
net.call("sendto", &[client, BUFFER, 1, 0, ADDRESS, 16], ERROR),
Err(WSAEOPNOTSUPP)
);
// Mismatched protocols are refused.
assert_eq!(
net.call("socket", &[2, 1, 17], INVALID_SOCKET),
Err(10043) // WSAEPROTONOSUPPORT
);
}
/// ioctlsocket FIONREAD reports unread stream bytes and the size of the next
/// datagram; FIONBIO accepts non-blocking mode only, since sockets here never
/// block. Unknown commands and bad pointers fail.
#[test]
fn ioctlsocket_reports_readable_bytes_and_non_blocking_mode() {
const FIONREAD: u64 = 0x4004_667f;
const FIONBIO: u64 = 0x8004_667e;
let mut net = Net::new();
let listener = net.stream();
assert_eq!(net.bind(listener, 5003), Ok(0));
assert_eq!(net.call("listen", &[listener, 1], ERROR), Ok(0));
let client = net.stream();
assert_eq!(net.connect(client, [127, 0, 0, 1], 5003), Ok(0));
let (server, _) = net.accept(listener).unwrap();
let readable = |net: &mut Net, socket: u64| {
net.0.memory.write_u32(VALUE, 0xdead_beef).unwrap();
net.call("ioctlsocket", &[socket, FIONREAD, VALUE], ERROR)
.map(|_| net.0.u32_at(VALUE))
};
assert_eq!(readable(&mut net, server), Ok(0));
assert_eq!(net.send(client, b"abc"), Ok(3));
assert_eq!(net.send(client, b"de"), Ok(2));
assert_eq!(readable(&mut net, server), Ok(5));
assert_eq!(net.recv(server, 4).unwrap(), b"abcd");
assert_eq!(readable(&mut net, server), Ok(1));
assert_eq!(readable(&mut net, listener), Err(WSAEINVAL));
let receiver = net.call("socket", &[2, 2, 17], INVALID_SOCKET).unwrap();
let sender = net.call("socket", &[2, 2, 17], INVALID_SOCKET).unwrap();
assert_eq!(net.bind(receiver, 5004), Ok(0));
assert_eq!(net.connect(sender, [127, 0, 0, 1], 5004), Ok(0));
assert_eq!(readable(&mut net, receiver), Ok(0));
assert_eq!(net.send(sender, b"seven!!"), Ok(7));
assert_eq!(net.send(sender, b"two"), Ok(3));
assert_eq!(readable(&mut net, receiver), Ok(7));
net.0.memory.write_u32(VALUE, 1).unwrap();
assert_eq!(
net.call("ioctlsocket", &[server, FIONBIO, VALUE], ERROR),
Ok(0)
);
net.0.memory.write_u32(VALUE, 0).unwrap();
assert_eq!(
net.call("ioctlsocket", &[server, FIONBIO, VALUE], ERROR),
Err(WSAEOPNOTSUPP)
);
assert_eq!(
net.call("ioctlsocket", &[server, FIONREAD, 0], ERROR),
Err(10014)
);
assert_eq!(
net.call("ioctlsocket", &[server, 0x1234, VALUE], ERROR),
Err(WSAEINVAL)
);
assert_eq!(
net.call("ioctlsocket", &[0x77, FIONREAD, VALUE], ERROR),
Err(10038)
);
}
+322 -10
View File
@@ -1087,6 +1087,8 @@ fn test_guest_crt_wide_strings_use_16_bit_units() {
let slot = PROCESS_FIXTURE_OUTPUT;
for module in ["ucrtbase.dll", "api-ms-win-crt-string-l1-1-0.dll"] {
for (symbol, args, expected) in [
("wcsspn", [slot, slot + 6, 0], 4),
("wcscspn", [slot, slot + 8, 0], 4),
("wcslen", [slot, 0, 0], 4),
("wcsnlen", [slot, 3, 0], 3),
("wcsnlen", [slot, 7, 0], 4),
@@ -1100,6 +1102,18 @@ fn test_guest_crt_wide_strings_use_16_bit_units() {
expected
);
}
for (set, expected) in [(slot + 6, slot), (slot + 8, 0)] {
let result = call_service_fixture(&state, module, "wcspbrk", &[slot, set]);
assert_eq!(result.execution.final_state.get(Register::Rax), expected);
}
for (haystack, needle, expected) in [
(slot, slot + 2, slot),
(slot, slot + 8, slot),
(slot + 8, slot, 0),
] {
let result = call_service_fixture(&state, module, "wcsstr", &[haystack, needle]);
assert_eq!(result.execution.final_state.get(Register::Rax), expected);
}
}
}
@@ -1109,6 +1123,18 @@ fn test_guest_crt_string_length_through_iat() {
for module in ["ucrtbase.dll", "api-ms-win-crt-string-l1-1-0.dll"] {
// The fixture seeds the output slot with eight 0xff bytes followed by zeroed stack bytes.
for (symbol, address, bound, expected) in [
(
"strpbrk",
PROCESS_FIXTURE_OUTPUT,
PROCESS_FIXTURE_OUTPUT + 7,
PROCESS_FIXTURE_OUTPUT,
),
(
"strpbrk",
PROCESS_FIXTURE_OUTPUT,
PROCESS_FIXTURE_OUTPUT + 8,
0,
),
("strlen", PROCESS_FIXTURE_OUTPUT, 0, 8),
("strlen", PROCESS_FIXTURE_OUTPUT + 8, 0, 0),
("strnlen", PROCESS_FIXTURE_OUTPUT, 3, 3),
@@ -1619,8 +1645,22 @@ fn test_guest_synthetic_file_io_through_iat() {
access
},
),
([0x49, 0xb8], 0),
([0x49, 0xb9], 0),
(
[0x49, 0xb8],
if symbol == "GetTempFileNameW" {
disposition
} else {
0
},
),
(
[0x49, 0xb9],
match (symbol, access) {
("GetTempFileNameW", 0) => PROCESS_FIXTURE_OUTPUT,
("GetTempFileNameW", address) => address,
_ => 0,
},
),
] {
code.extend_from_slice(&register);
code.extend_from_slice(&value.to_le_bytes());
@@ -1633,13 +1673,31 @@ fn test_guest_synthetic_file_io_through_iat() {
append_import_call(&mut code, 0x2060);
code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x48, 0xf4]);
code.resize(0x80, 0);
code.extend(name.encode_utf16().chain([0]).flat_map(u16::to_le_bytes));
if matches!(
symbol,
"SetCurrentDirectoryA" | "GetFileAttributesA" | "CreateFileA"
) {
code.extend_from_slice(name.as_bytes());
code.push(0);
} else {
code.extend(name.encode_utf16().chain([0]).flat_map(u16::to_le_bytes));
}
if let Some(target) = target {
code.resize(0x180, 0);
code.extend(target.encode_utf16().chain([0]).flat_map(u16::to_le_bytes));
}
let bytes = TestPeBuilder::new(IMAGE, 0x1000)
.add_import(MODULE, symbol)
.add_import(
if matches!(
symbol,
"SetCurrentDirectoryA" | "SetCurrentDirectoryW" | "SetEnvironmentVariableW"
) {
"kernel32.dll"
} else {
MODULE
},
symbol,
)
.code(&code)
.build();
let mut imports = ImportRegistry::new();
@@ -1669,11 +1727,119 @@ fn test_guest_synthetic_file_io_through_iat() {
let namespace = |symbol, path| path_call(symbol, path, 0, 0, None);
let call = |symbol, args: &[u64]| call_service_fixture(&state, "kernel32.dll", symbol, args);
let output = PROCESS_FIXTURE_OUTPUT;
let temp = call("GetTempPathA", &[4, output]);
assert_eq!(temp.execution.final_state.get(Register::Rax), 3);
assert_eq!(
temp.image.memory.read_u32(output).unwrap().to_le_bytes(),
*b"C:\\\0"
);
let short = call("GetTempPathW", &[3, output]);
assert_eq!(short.execution.final_state.get(Register::Rax), 4);
assert_eq!(short.image.memory.read_u64(output).unwrap(), u64::MAX);
assert_eq!(
path_call("SetEnvironmentVariableW", "TEMP", 0, 0, Some("C:/work")),
1
);
assert_eq!(
path_call("SetEnvironmentVariableW", "TMP", 0, 0, Some("C:/scratch")),
1
);
let temp = call_service_fixture(&state, MODULE, "GetTempPathW", &[12, output]);
assert_eq!(temp.execution.final_state.get(Register::Rax), 11);
assert_eq!(
(0..12)
.map(|i| temp.image.memory.read_u16(output + i * 2).unwrap())
.collect::<Vec<_>>(),
"C:\\scratch\\"
.encode_utf16()
.chain([0])
.collect::<Vec<_>>()
);
assert_eq!(namespace("CreateDirectoryW", "C:/work"), 1);
assert_eq!(namespace("SetCurrentDirectoryW", "C:/work"), 1);
let temp_file =
|directory, unique| path_result("GetTempFileNameW", directory, 0, unique, Some("prefix"));
let explicit = temp_file("C:/work", 0x1_002a);
assert_eq!(explicit.execution.final_state.get(Register::Rax), 0x1_002a);
let read_name = |result: &xenora_loader::startup::StartupResult| {
let units: Vec<_> = (0..64)
.map(|i| result.image.memory.read_u16(output + i * 2).unwrap())
.take_while(|&unit| unit != 0)
.collect();
String::from_utf16(&units).unwrap()
};
let suggested = read_name(&explicit);
assert_eq!(suggested, r"C:\work\pre002A.TMP");
assert_eq!(open(&suggested, 0x8000_0000, 3), u64::MAX);
let rejected = path_result("GetTempFileNameW", ".", 1, 0, Some("prefix"));
assert_eq!(rejected.execution.final_state.get(Register::Rax), 0);
for (number, expected) in [(1, r"C:\work\pre0001.TMP"), (2, r"C:\work\pre0002.TMP")] {
let created = temp_file(".", 0);
assert_eq!(created.execution.final_state.get(Register::Rax), number);
assert_eq!(read_name(&created), expected);
let handle = open(expected, 0x8000_0000, 3);
assert_ne!(handle, u64::MAX);
let size = call("GetFileSizeEx", &[handle, output]);
assert_eq!(size.execution.final_state.get(Register::Rax), 1);
assert_eq!(size.image.memory.read_u64(output).unwrap(), 0);
call("CloseHandle", &[handle]);
}
for expected in [r"C:\work\pre0001.TMP", r"C:\work\pre0002.TMP"] {
assert_eq!(namespace("DeleteFileW", expected), 1);
}
let narrow = call("GetCurrentDirectoryA", &[8, output]);
assert_eq!(narrow.execution.final_state.get(Register::Rax), 7);
assert_eq!(
narrow.image.memory.read_u64(output).unwrap().to_le_bytes(),
*b"C:\\work\0"
);
assert_eq!(
call("GetCurrentDirectoryW", &[0, 0])
.execution
.final_state
.get(Register::Rax),
8
);
let cwd = call("GetCurrentDirectoryW", &[8, output]);
assert_eq!(cwd.execution.final_state.get(Register::Rax), 7);
assert_eq!(
(0..8)
.map(|i| cwd.image.memory.read_u16(output + i * 2).unwrap())
.collect::<Vec<_>>(),
"C:\\work".encode_utf16().chain([0]).collect::<Vec<_>>()
);
assert_eq!(namespace("GetFileAttributesA", "C:/WORK"), 0x10);
assert_eq!(namespace("RemoveDirectoryW", "C:/work"), 0);
let relative = path_call("CreateFileA", "relative.dat", 0x4000_0000, 2, None);
assert_ne!(relative, u64::MAX);
call("CloseHandle", &[relative]);
assert_eq!(
namespace("GetFileAttributesW", "C:/work/relative.dat"),
0x80
);
assert_eq!(namespace("SetCurrentDirectoryA", "C:/"), 1);
assert_eq!(namespace("DeleteFileW", "C:/work/relative.dat"), 1);
assert_eq!(namespace("RemoveDirectoryW", "C:/work"), 1);
assert_eq!(open("C:/../outside", 0x4000_0000, 2), u64::MAX);
let writer = open("C:/Sample.dat", 0x4000_0000, 2);
assert_ne!(writer, u64::MAX);
assert_eq!(open("sample.dat", 0x8000_0000, 3), u64::MAX);
assert_eq!(
call("GetFileType", &[writer])
.execution
.final_state
.get(Register::Rax),
1
);
let wrote = call("WriteFile", &[writer, output, 4, output + 8, 0]);
assert_eq!(
call("FlushFileBuffers", &[writer])
.execution
.final_state
.get(Register::Rax),
1
);
assert_eq!(wrote.execution.final_state.get(Register::Rax), 1);
assert_eq!(wrote.image.memory.read_u32(output + 8).unwrap(), 4);
assert_eq!(
@@ -2167,14 +2333,14 @@ fn test_guest_crt_long_conversions_through_iat() {
.unwrap();
assert_eq!(result.bound_imports, 2);
assert_eq!(result.execution.exit_reason, ExitReason::Halt);
let end = result
.image
.memory
.read_u64(PROCESS_FIXTURE_OUTPUT)
.unwrap();
(
result.execution.final_state.get(Register::Rbx),
result
.image
.memory
.read_u64(PROCESS_FIXTURE_OUTPUT)
.unwrap()
- INPUT,
end.saturating_sub(INPUT),
result
.image
.memory
@@ -2230,6 +2396,21 @@ fn test_guest_crt_long_conversions_through_iat() {
for symbol in ["wcstoll", "wcstoull", "_wcstoi64", "_wcstoui64"] {
assert_eq!(run(symbol, &wide, 10), (4_294_967_296, 20, 0));
}
// atoi family: fixed base 10 and no end pointer. Reuse the IAT fixture but
// only check the returned integer (the end slot is not written).
let atoi = |symbol, input: &[u8]| run(symbol, input, 10).0;
assert_eq!(atoi("atoi", b" -42x\0"), u64::from((-42i32) as u32));
assert_eq!(atoi("atol", b"2147483647\0"), i32::MAX as u64);
assert_eq!(atoi("atoll", b"9223372036854775807\0"), i64::MAX as u64);
assert_eq!(atoi("_atoi64", b"-9223372036854775808\0"), i64::MIN as u64);
let wide = " -7"
.encode_utf16()
.chain([0])
.flat_map(u16::to_le_bytes)
.collect::<Vec<_>>();
assert_eq!(atoi("_wtoi", &wide), u64::from((-7i32) as u32));
assert_eq!(atoi("_wtol", &wide), u64::from((-7i32) as u32));
assert_eq!(atoi("_wtoi64", &wide), (-7i64) as u64);
}
#[test]
@@ -2621,3 +2802,134 @@ fn test_virtual_allocation_release_through_iat() {
assert_eq!((value, error), (0, expected_error));
}
}
#[test]
fn guest_xasync_run_completes_on_the_calling_thread() {
const IMAGE: u64 = 0x140000000;
const MODULE: &str = "xgameruntime.dll";
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
let block = PROCESS_FIXTURE_STACK_TOP - 0x400;
let mut code = vec![0x48, 0x83, 0xec, 0x48];
// Zero the XAsyncBlock and point its completion callback at IMAGE+0x1110.
code.extend_from_slice(&[0x48, 0xb8]);
code.extend_from_slice(&block.to_le_bytes());
code.extend_from_slice(&[0x48, 0x31, 0xc9, 0x48, 0x89, 0x08, 0x48, 0x89, 0x48, 0x08]);
code.extend_from_slice(&[0x48, 0xb9]);
code.extend_from_slice(&(IMAGE + 0x1110).to_le_bytes());
code.extend_from_slice(&[0x48, 0x89, 0x48, 0x10]);
code.extend_from_slice(&[0x48, 0x89, 0x48, 0x18, 0x48, 0x89, 0x48, 0x20]);
code.extend_from_slice(&[0x48, 0x89, 0x48, 0x28, 0x48, 0x89, 0x48, 0x30]);
// XAsyncRun(block, work=IMAGE+0x1100)
code.extend_from_slice(&[0x48, 0x89, 0xc1]); // rcx = block
code.extend_from_slice(&[0x48, 0xba]);
code.extend_from_slice(&(IMAGE + 0x1100).to_le_bytes());
append_import_call(&mut code, 0x2060);
code.extend_from_slice(&[0x48, 0x89, 0xc3]); // rbx = XAsyncRun result
code.extend_from_slice(&[0x48, 0x89, 0xc8, 0x48, 0x31, 0xd2]); // rcx=block, rdx=0
append_import_call(&mut code, 0x21a0); // XAsyncGetStatus
code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x48, 0xf4]);
code.resize(0x100, 0);
// work: return 0x2222_0001
code.extend_from_slice(&[0xb8, 0x01, 0x00, 0x22, 0x22, 0xc3]);
code.resize(0x110, 0);
// completion: mark internal[0] = 0xA5
code.extend_from_slice(&[0xc6, 0x41, 0x18, 0xa5, 0xc3]);
let image = TestPeBuilder::new(IMAGE, 0x1000)
.add_import(MODULE, "XAsyncRun")
.add_import(MODULE, "XAsyncGetStatus")
.code(&code)
.build();
let mut registry = ImportRegistry::new();
register_standard_services(&mut registry, Arc::clone(&state));
let result = run_synthetic_startup(
&image,
StartupLayout {
image_base: IMAGE,
stack_top: PROCESS_FIXTURE_STACK_TOP,
tls_base: 0x300000000,
},
registry,
200,
)
.unwrap();
assert_eq!(result.execution.exit_reason, ExitReason::Halt);
assert_eq!(result.execution.final_state.get(Register::Rbx), 0); // XAsyncRun S_OK
assert_eq!(result.execution.final_state.get(Register::Rax), 0x2222_0001);
assert_eq!(result.image.memory.read_u8(block + 0x18).unwrap(), 0xa5);
}
#[test]
fn guest_xasync_run_schedules_work_and_completion_on_a_manual_queue() {
const IMAGE: u64 = 0x140000000;
const MODULE: &str = "xgameruntime.dll";
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
let call = |symbol, args: &[u64]| call_service_fixture(&state, MODULE, symbol, args);
let output = PROCESS_FIXTURE_STACK_TOP - 0x480;
let block = PROCESS_FIXTURE_STACK_TOP - 0x400;
let created = call("XTaskQueueCreate", &[0, 0, output]);
let queue = created.image.memory.read_u64(output).unwrap();
let mut code = vec![0x48, 0x83, 0xec, 0x48];
// XAsyncBlock: queue at +0, completion at +0x10, rest zeroed.
code.extend_from_slice(&[0x48, 0xb8]);
code.extend_from_slice(&block.to_le_bytes());
code.extend_from_slice(&[0x48, 0x31, 0xc9, 0x48, 0x89, 0x08, 0x48, 0x89, 0x48, 0x08]);
code.extend_from_slice(&[0x48, 0x89, 0x48, 0x10, 0x48, 0x89, 0x48, 0x18]);
code.extend_from_slice(&[
0x48, 0x89, 0x48, 0x20, 0x48, 0x89, 0x48, 0x28, 0x48, 0x89, 0x48, 0x30,
]);
code.extend_from_slice(&[0x48, 0xb9]);
code.extend_from_slice(&queue.to_le_bytes());
code.extend_from_slice(&[0x48, 0x89, 0x08]); // block.queue = queue
code.extend_from_slice(&[0x48, 0xb9]);
code.extend_from_slice(&(IMAGE + 0x1110).to_le_bytes());
code.extend_from_slice(&[0x48, 0x89, 0x48, 0x10]); // block.callback
// XAsyncRun(block, work) — returns before work runs.
code.extend_from_slice(&[0x48, 0x89, 0xc1]);
code.extend_from_slice(&[0x48, 0xba]);
code.extend_from_slice(&(IMAGE + 0x1100).to_le_bytes());
append_import_call(&mut code, 0x2060);
code.extend_from_slice(&[0x48, 0x89, 0xc3]); // rbx = XAsyncRun result
// Dispatch work port, then completion port.
code.extend_from_slice(&[0x48, 0xb9]);
code.extend_from_slice(&queue.to_le_bytes());
code.extend_from_slice(&[0x31, 0xd2, 0x45, 0x31, 0xc0]); // port 0, timeout 0
append_import_call(&mut code, 0x21a0); // XTaskQueueDispatch
code.extend_from_slice(&[0x48, 0xb9]);
code.extend_from_slice(&queue.to_le_bytes());
code.extend_from_slice(&[0xba, 0x01, 0x00, 0x00, 0x00, 0x45, 0x31, 0xc0]); // port 1
append_import_call(&mut code, 0x21a0);
code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x48, 0xf4]);
code.resize(0x100, 0);
code.extend_from_slice(&[0xb8, 0x01, 0x00, 0x22, 0x22, 0xc3]); // work
code.resize(0x110, 0);
code.extend_from_slice(&[0xc6, 0x41, 0x18, 0xa5, 0xc3]); // completion
let image = TestPeBuilder::new(IMAGE, 0x1000)
.add_import(MODULE, "XAsyncRun")
.add_import(MODULE, "XTaskQueueDispatch")
.code(&code)
.build();
let mut registry = ImportRegistry::new();
register_standard_services(&mut registry, Arc::clone(&state));
let result = run_synthetic_startup(
&image,
StartupLayout {
image_base: IMAGE,
stack_top: PROCESS_FIXTURE_STACK_TOP,
tls_base: 0x300000000,
},
registry,
400,
)
.unwrap();
assert_eq!(result.execution.exit_reason, ExitReason::Halt);
assert_eq!(result.execution.final_state.get(Register::Rbx), 0); // XAsyncRun S_OK
assert_eq!(result.image.memory.read_u8(block + 0x18).unwrap(), 0xa5);
assert_eq!(
call("XAsyncGetStatus", &[block, 0])
.execution
.final_state
.get(Register::Rax),
0x2222_0001
);
}
+227
View File
@@ -0,0 +1,227 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! XInput through the guest import table, fed by simulated controllers. The
//! expected layouts and codes come from the public XInput reference pages for
//! XInputGetState, XInputSetState, XInputGetCapabilities, XInputEnable and the
//! XINPUT_STATE, XINPUT_GAMEPAD, XINPUT_VIBRATION and XINPUT_CAPABILITIES
//! structures. A simulated controller is not physical hardware.
mod support;
use std::sync::Arc;
use support::*;
use xenora_loader::services::xinput::{Gamepad, SimulatedControllers};
use xenora_loader::services::{MockClock, ServicesState};
const IMPORTS: &[(&str, &str)] = &[
("xinput1_4.dll", "XInputGetState"),
("xinput1_4.dll", "XInputSetState"),
("xinput1_4.dll", "XInputGetCapabilities"),
("xinput1_4.dll", "XInputEnable"),
("kernel32.dll", "GetLastError"),
];
const ERROR_SUCCESS: u64 = 0;
const ERROR_BAD_ARGUMENTS: u64 = 160;
const ERROR_NOACCESS: u64 = 998;
const ERROR_DEVICE_NOT_CONNECTED: u64 = 1167;
const STATE: u64 = SCRATCH;
const VIBRATION: u64 = SCRATCH + 0x40;
const CAPS: u64 = SCRATCH + 0x80;
const UNMAPPED: u64 = 0x10;
fn guest() -> (Guest, Arc<SimulatedControllers>) {
let pads = Arc::new(SimulatedControllers::default());
let mut state = ServicesState::new(Arc::new(MockClock::new(0)));
state.set_controllers(pads.clone());
(Guest::with_state(IMPORTS, &[], state), pads)
}
fn read_state(guest: &Guest) -> (u32, Gamepad) {
let at = |offset| STATE + offset;
let pad = Gamepad {
buttons: guest.u16_at(at(4)),
left_trigger: guest.memory.read_u8(at(6)).unwrap(),
right_trigger: guest.memory.read_u8(at(7)).unwrap(),
thumb_lx: guest.u16_at(at(8)) as i16,
thumb_ly: guest.u16_at(at(10)) as i16,
thumb_rx: guest.u16_at(at(12)) as i16,
thumb_ry: guest.u16_at(at(14)) as i16,
};
(guest.u32_at(STATE), pad)
}
#[test]
fn get_state_reports_readings_and_advances_packets_only_on_change() {
let (mut guest, pads) = guest();
assert_eq!(
guest.call("XInputGetState", &[0, STATE]),
ERROR_DEVICE_NOT_CONNECTED
);
pads.connect(0, true);
let pad = Gamepad {
buttons: 0x1000 | 0x0001, // A and DPAD_UP
left_trigger: 0x40,
right_trigger: 0xFF,
thumb_lx: -32768,
thumb_ly: 32767,
thumb_rx: -1,
thumb_ry: 12345,
};
pads.set(0, pad);
assert_eq!(guest.call("XInputGetState", &[0, STATE]), ERROR_SUCCESS);
let (first, seen) = read_state(&guest);
assert_eq!(seen, pad);
assert_eq!(guest.call("XInputGetState", &[0, STATE]), ERROR_SUCCESS);
assert_eq!(read_state(&guest).0, first, "unchanged reading");
pads.set(0, Gamepad::default());
assert_eq!(guest.call("XInputGetState", &[0, STATE]), ERROR_SUCCESS);
let (second, seen) = read_state(&guest);
assert_ne!(second, first);
assert_eq!(seen, Gamepad::default());
// Other slots stay disconnected.
assert_eq!(
guest.call("XInputGetState", &[1, STATE]),
ERROR_DEVICE_NOT_CONNECTED
);
pads.disconnect(0);
assert_eq!(
guest.call("XInputGetState", &[0, STATE]),
ERROR_DEVICE_NOT_CONNECTED
);
}
#[test]
fn bad_arguments_and_unmapped_buffers_return_codes_without_last_error() {
let (mut guest, pads) = guest();
pads.connect(0, true);
assert_eq!(
guest.call("XInputGetState", &[4, STATE]),
ERROR_BAD_ARGUMENTS
);
assert_eq!(guest.call("XInputGetState", &[0, 0]), ERROR_BAD_ARGUMENTS);
assert_eq!(guest.call("XInputGetState", &[0, UNMAPPED]), ERROR_NOACCESS);
assert_eq!(guest.call("XInputSetState", &[0, 0]), ERROR_BAD_ARGUMENTS);
assert_eq!(guest.call("XInputSetState", &[0, UNMAPPED]), ERROR_NOACCESS);
// The last address must not overflow while reading the second motor.
assert_eq!(guest.call("XInputSetState", &[0, u64::MAX]), ERROR_NOACCESS);
assert_eq!(
guest.call("XInputGetCapabilities", &[0, 2, CAPS]),
ERROR_BAD_ARGUMENTS
);
assert_eq!(
guest.call("XInputGetCapabilities", &[0, 1, UNMAPPED]),
ERROR_NOACCESS
);
assert_eq!(guest.error(), 0, "XInput leaves last-error alone");
}
#[test]
fn set_state_drives_motors_and_enable_pauses_them() {
let (mut guest, pads) = guest();
guest.memory.write_u16(VIBRATION, 0x1234).unwrap();
guest.memory.write_u16(VIBRATION + 2, 0xABCD).unwrap();
assert_eq!(
guest.call("XInputSetState", &[2, VIBRATION]),
ERROR_DEVICE_NOT_CONNECTED
);
pads.connect(2, true);
assert_eq!(guest.call("XInputSetState", &[2, VIBRATION]), ERROR_SUCCESS);
assert_eq!(pads.motors(2), Some((0x1234, 0xABCD)));
pads.set(
2,
Gamepad {
buttons: 0x2000,
..Gamepad::default()
},
);
guest.call("XInputEnable", &[0]);
assert_eq!(pads.motors(2), Some((0, 0)), "disabling stops the motors");
assert_eq!(guest.call("XInputGetState", &[2, STATE]), ERROR_SUCCESS);
assert_eq!(
read_state(&guest).1,
Gamepad::default(),
"neutral while disabled"
);
guest.memory.write_u16(VIBRATION, 0x0101).unwrap();
assert_eq!(guest.call("XInputSetState", &[2, VIBRATION]), ERROR_SUCCESS);
assert_eq!(pads.motors(2), Some((0, 0)), "held while disabled");
guest.call("XInputEnable", &[1]);
assert_eq!(pads.motors(2), Some((0x0101, 0xABCD)), "resumed on enable");
assert_eq!(guest.call("XInputGetState", &[2, STATE]), ERROR_SUCCESS);
assert_eq!(read_state(&guest).1.buttons, 0x2000);
}
#[test]
fn capabilities_describe_a_gamepad_and_whether_it_vibrates() {
let (mut guest, pads) = guest();
assert_eq!(
guest.call("XInputGetCapabilities", &[3, 0, CAPS]),
ERROR_DEVICE_NOT_CONNECTED
);
pads.connect(3, true);
pads.connect(1, false);
for (slot, motors, flags) in [(3, 0xFFFF, 1), (1, 0, 0)] {
assert_eq!(
guest.call("XInputGetCapabilities", &[slot, 1, CAPS]),
ERROR_SUCCESS
);
assert_eq!(
guest.memory.read_u8(CAPS).unwrap(),
1,
"XINPUT_DEVTYPE_GAMEPAD"
);
assert_eq!(
guest.memory.read_u8(CAPS + 1).unwrap(),
1,
"GAMEPAD subtype"
);
assert_eq!(guest.u16_at(CAPS + 2), flags, "XINPUT_CAPS_FFB_SUPPORTED");
assert_eq!(guest.u16_at(CAPS + 4), 0xF3FF, "every defined button");
assert_eq!(guest.memory.read_u8(CAPS + 6).unwrap(), 0xFF);
assert_eq!(guest.memory.read_u8(CAPS + 7).unwrap(), 0xFF);
for axis in 0..4 {
assert_eq!(guest.u16_at(CAPS + 8 + 2 * axis), 0xFFFF);
}
assert_eq!(guest.u16_at(CAPS + 16), motors);
assert_eq!(guest.u16_at(CAPS + 18), motors);
}
}
#[test]
fn without_a_source_no_controller_is_connected() {
let mut guest = Guest::new(IMPORTS, &[]);
for slot in 0..4 {
assert_eq!(
guest.call("XInputGetState", &[slot, STATE]),
ERROR_DEVICE_NOT_CONNECTED
);
}
}
#[test]
fn older_xinput_dll_names_reach_the_same_service() {
for module in ["xinput1_3.dll", "xinput9_1_0.dll"] {
let imports: &'static [(&str, &str)] =
Box::leak(vec![(module, "XInputGetState")].into_boxed_slice());
let pads = Arc::new(SimulatedControllers::default());
pads.connect(0, false);
pads.set(
0,
Gamepad {
buttons: 0x8000,
..Gamepad::default()
},
);
let mut state = ServicesState::new(Arc::new(MockClock::new(0)));
state.set_controllers(pads.clone());
let mut guest = Guest::with_state(imports, &[], state);
assert_eq!(
guest.call("XInputGetState", &[0, STATE]),
ERROR_SUCCESS,
"{module}"
);
assert_eq!(guest.u16_at(STATE + 4), 0x8000, "{module}");
}
}
+8 -1
View File
@@ -175,6 +175,13 @@ impl Guest {
/// Call an import with Win64 arguments. Arguments after the fourth go on
/// the stack after the return address and the home area.
pub fn run(&mut self, symbol: &str, args: &[u64]) -> (u64, ExitReason) {
let (cpu, exit) = self.run_state(symbol, args);
(cpu.get(Register::Rax), exit)
}
/// Like `run`, but returns the whole register state, for services that
/// return in XMM0.
pub fn run_state(&mut self, symbol: &str, args: &[u64]) -> (CpuState, ExitReason) {
let index = self
.imports
.iter()
@@ -205,7 +212,7 @@ impl Guest {
assert_eq!(cpu.get(register), 0x5EED_0000 + index as u64, "{symbol}");
}
}
(cpu.get(Register::Rax), result.exit_reason)
(cpu, result.exit_reason)
}
/// Call an import as the main thread of a scheduled run: the engine runs
+1
View File
@@ -63,6 +63,7 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
- [Legal scope](legal.md), [dependency licensing](licenses.md), and [third-party notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution findings.
- [Contribution guidelines](../CONTRIBUTING.md) — Original authorship, Developer Certificate of Origin sign-off, and evidence requirements.
- [Agent task queue](coordination/agent-tasks.md) — Areas, claiming, leases, upstream sync, verification and the security model for parallel contributors and coding agents.
- [System-runtime agent handoff](coordination/system-runtime-handoff.md) — Pick-up brief for the Win32/CRT/runtime lane: branch tip, open PRs (#312/#316), review status, goals, and next actions.
- [CPU/runtime expansion campaign ledger](coordination/cpu-campaign-ledger.md) — Progress ledger for the Xenora native CPU and runtime compatibility campaign: starting/current commits, completed batches, new forms, verification evidence and the next implementation target.
- [Infrastructure QA ownership](coordination/infrastructure-qa-ownership.md) — Non-overlapping paths for infrastructure and QA tooling.
- [Agent queue smoke evidence](coordination/agent-queue-smoke.md) — Live Actions results from the disposable smoke repository.
+231
View File
@@ -0,0 +1,231 @@
# System-runtime agent handoff
**PR review checkpoint:** 2026-11-25T01:16Z (UTC) — ranveersoni98's "Please fix merge conflicts" on #312 (2026-11-25T01:02Z) addressed at `5c6fcb2` and answered on the PR; #316 is merged. No other new human feedback.
**Owner identity on commits:** Adeeb Rahman `<therealabeeb@icloud.com>` (GitHub: `soggyramennoodle`)
**Do not add** `Co-authored-by: Cursor` or any AI attribution trailers (`AGENTS.md`).
This file is the pick-up brief for the next agent continuing the system-runtime lane. Read it before editing.
## Resume here
1. Start at `docs/coordination/system-runtime-handoff.md` in `/Volumes/SSD/Xenora`.
2. Check [PR #312](https://github.com/ranveersoni98/Xenora/pull/312) and [PR #316](https://github.com/ranveersoni98/Xenora/pull/316) for conversation comments, review submissions, and inline review comments newer than the PR review checkpoint above. Address any new actionable feedback immediately.
3. If there is no new actionable feedback, continue the remaining work in `/Users/therealabeeb/Downloads/gta6 prompt 1 6.2 sol low.txt`. The SSD copy is `artifacts/system-runtime/implementation-brief.txt` and the work log is `artifacts/system-runtime/ledger.md`.
4. While actively working, recheck both PRs every 10 minutes and sync upstream `main` every 10–15 minutes. Resume prompt work after addressing feedback.
---
## One-line status
Active branch `feat/system-runtime-expansion` is at local tip **`c45e11d`**. The last fetched fork tip is **`c789dc6`**. Review-fix tip for elforeign is **`8a677bc`**. PR **#312** is open with **CHANGES_REQUESTED** (blocking items addressed; awaiting re-review). PR **#316** still **CHANGES_REQUESTED** (fuzz harness fix already replied; awaiting maintainer re-review). Keep expanding runtime **unless** new PR feedback appears — then switch to feedback first.
---
## Test environment note
The SSD is **exFAT** (no hard links, no POSIX permissions). Do **not** set `XENORA_TEST_TMP` to an SSD path: 9 host-file tests fail there for filesystem reasons. Leave it unset (defaults to `/tmp`, APFS).
## Workspace and remotes
| Item | Value |
| --- | --- |
| Workspace | `/Volumes/SSD/Xenora` |
| Fork remote | `fork` → `https://github.com/soggyramennoodle/Xenora.git` |
| Upstream remote | `origin` → `https://github.com/ranveersoni98/Xenora.git` |
| Active branch | `feat/system-runtime-expansion` (tracks `fork/feat/system-runtime-expansion`) |
| Local branch tip | `b0b6733` — Share file position and timestamp policy across duplicate handles |
| Last fetched fork tip | `c789dc6` |
| Last fetched upstream `main` | `3b47c21` (merged into both PR branches 2026-11-24) |
| Toolchain | `CARGO_HOME=/Volumes/SSD/xenora-toolchain/cargo` `RUSTUP_HOME=/Volumes/SSD/xenora-toolchain/rustup` put `…/cargo/bin` on `PATH` |
| Prompt / brief | `/Users/therealabeeb/Downloads/gta6 prompt 1 6.2 sol low.txt` (ownership of Win32/CRT/runtime lane — **not finished**) |
`origin` is upstream; push feature work to **`fork`**, not `origin`, unless the user says otherwise.
---
## Standing goals (from human)
1. Own system-runtime expansion from the prompt (CRT, Win32 services, FS, net, platform) on `feat/system-runtime-expansion`.
2. Sync with upstream `main` every ~10–15 minutes when actively implementing.
3. **PR feedback has priority:** if new human review comments land on open PRs (#312, #316, …), stop feature work and address them first.
4. If there is **no** new feedback on a tick, **continue expanding** the runtime.
5. Do not push/commit without user authorization (user **did** authorize push/PR for the CRT expansion and review fixes).
6. Never claim Xbox/game execution. Never invent passing tests. Follow `AGENTS.md` (ARM64 native, DCO `Signed-off-by`, no AI co-author trailers).
7. **Not our claim:** guest thread scheduler — [issue #323](https://github.com/ranveersoni98/Xenora/issues/323) claimed by `jelly013`. Do not take it.
Suggested reply if asked about #323: *Not us — we’re on system-runtime CRT/FS/Winsock/XAsync. Go ahead and open the PR for #323.*
---
## Open pull requests
### [#312](https://github.com/ranveersoni98/Xenora/pull/312) — primary vehicle
- **Title:** System runtime: host mounts, CRT, XAsync and Winsock loopback
- **Head:** `soggyramennoodle:feat/system-runtime-expansion` → `main`
- **State:** OPEN, **CHANGES_REQUESTED**
- **Reviews:**
- `ranveersoni98` — earlier FS security CHANGES_REQUESTED (hardenings done; human audit still pending).
- `elforeign` — 2026-11-24T17:28:55Z CHANGES_REQUESTED (see below). **Reply posted** at tip `8a677bc` addressing blockers.
#### elforeign blocking items — status
| # | Request | Status |
| --- | --- | --- |
| 1 | Remove `Co-authored-by: Cursor` trailers from history | **Done** — `filter-branch` msg-filter; **0** trailers on `origin/main..HEAD`; force-pushed with lease to `8a677bc` |
| 2 | Dead Linux `AT_EMPTY_PATH` unlink + false TOCTOU claims | **Done** — path removed; docs/module/changelog corrected to name-based remove only |
| 3 | Name-based remove race / nlink post-check | **Done** — documented plainly (in-root only; host writers trusted; file nlink fail-closed; dirs no post-check) |
#### elforeign non-blocking (not done yet)
- ASCII-only case folding follow-up verified locally in `c45e11d` on SSD-backed APFS. The commit is unpushed.
- Per-mount quota implemented locally: `HostMount::with_quota(bytes, entries)` (net growth, `ERROR_DISK_FULL`/`ENOSPC`), guest test `mount_quota_bounds_net_bytes_and_entries_added_by_the_guest`.
- Scope: branch still overlaps #316 history; once #316 merges, #312 diff should shrink toward FS+later CRT — or split if maintainer asks.
#### Local verification after unlink fix
```sh
export CARGO_HOME=/Volumes/SSD/xenora-toolchain/cargo RUSTUP_HOME=/Volumes/SSD/xenora-toolchain/rustup
export PATH="/Volumes/SSD/xenora-toolchain/cargo/bin:$PATH"
cargo test -p xenora-loader --test runtime_host_files # 10 passed
cargo clippy -p xenora-loader --lib -- -D warnings
```
### [#316](https://github.com/ranveersoni98/Xenora/pull/316) — fuzz / bench / demangle
- **Head:** `feat/runtime-fuzz-bench`
- **State:** OPEN, **CHANGES_REQUESTED** (`ranveersoni98`)
- Blocking harness issues were addressed in a prior reply (deterministic mem fill, coverage asserts, corrected fuzz evidence, `XMemAlloc` fail-closed). **Awaiting re-review.** No new human comments since that reply at handoff time.
- Worktree used earlier: `/Volumes/SSD/xenora-x19-baseline` (may still exist).
---
## What this branch already contains (high level)
Relative to upstream `main`, the branch includes (among merges):
- Host-backed guest drives (`host_files.rs`, `runtime_host_files.rs`) + security hardenings.
- Large CRT surface: strings, ctype, locale, sprintf/snprintf, FILE streams (in-memory + **mount-backed fopen**), env get/set/`_putenv`, calendar time, `rand`/`srand`, `_stricmp` family, `atoi` family.
- XAsync immediate + manual `XTaskQueue` work/completion ports.
- Process-local Winsock UDP loopback + `sendto`/`recvfrom`.
- Synthetic `GetModuleFileNameA`/`W`.
- Some fuzz/bench/demangle history that also lives conceptually under #316.
Recent tip commits (after trailer rewrite; hashes changed):
- `680f572` — Expand CRT I/O, env, time, rand and Winsock UDP helpers
- `550b2ce` — Merge upstream main `d7f7d58`
- `8a677bc` — Drop dead `AT_EMPTY_PATH` unlink and document name-based remove limits
---
## Prompt 1 — honesty about completion
The download prompt is a **multi-phase ownership track**, not a finished checklist. Substantial subsets exist; **not done:** full C++ runtime, guest threads (#323 elsewhere), broad metadata→conformance productization, full Win32 surface, independent human security acceptance, mutation/perf campaigns, etc.
---
## Background automation
A shell loop (terminal ~`217814`) echoes `AGENT_LOOP_TICK_pr_feedback` every 10 minutes while running. On each tick:
1. `git fetch origin main` and note `HEAD..origin/main`.
2. Check #312 and #316 issue comments + reviews for **new human** feedback.
3. If new feedback → address it first (code + PR reply).
4. If none → continue feature work; optionally merge/sync `main` when needed.
5. Briefly tell the user the tick result.
Restart the loop if the terminal died:
```sh
cd /Volumes/SSD/Xenora
while true; do
sleep 600
echo 'AGENT_LOOP_TICK_pr_feedback {"prompt":"Check GitHub PRs #312 and #316 for new human review comments. If new feedback is not addressed, stop feature work and address it first. Fetch origin/main and sync if needed."}'
done
```
GitHub PR subscribe MCP returned 403 earlier; the local loop is the reliable path.
---
## Latest session (2026-11-24/25)
- Pushed both branches after merging main `3b47c21`: #312 at `7bb4798`, #316 at `324eab0`. Both MERGEABLE, all CI checks green (the advisory `check` job once failed on a GitHub GraphQL outage; re-triggered by editing the PR body, since we lack rerun rights).
- #312 description rewritten to `.github/PULL_REQUEST_TEMPLATE.md` (the `description` check enforces it).
- Added after push, local only: `6229447` MoveFileExW (replace / write-through / copy-allowed) on host and synthetic drives.
- Auto-fix cannot be enabled by the agent (no push rights to upstream); the user can enable it from the PR bar.
- #392 is claimed by zachdoxsee; #206 still awaits maintainer scope confirmation. Do not take either.
## Session 2026-11-25 additions
- XInput controller services (`626de36`) with a host-connected `ControllerSource`; tests use `SimulatedControllers`. No physical controller or app input path is connected; `crates/ffi/src/frame_loop.rs` input belongs to the app lane.
- C++ `type_info` helpers on `vcruntime140.dll` (`9f472c9`). Exception handling, `dynamic_cast` and thread-safe statics remain open.
- `xenora imports coverage` report. It lists 107 registered services with no import metadata; classifying them is open work.
- Audio mixer is #306, claimed by elforeign on 2026-11-24. Do not take it.
- Platform settings, saves with quota, profiles, notifications and capability reporting already exist as the synthetic `xenora_fixture.dll` platform fixture.
- Waitable timers are written and tested but **parked**, not pushed: waiting on a timer needs `services/events.rs`, which #323 (jelly013, PR #339) claims along with blocking waits. The patch and its test are in the ignored `artifacts/system-runtime/parked/`. Offer them on #323 or wait for #339 to land before reusing them.
- `std::terminate`, `_purecall`, `abort` and `_exit` are built on #331's process exit (`crt_exit.rs`). `exit` (runs `atexit` first), `signal`, `set_terminate` and `_set_purecall_handler` are still missing.
- Files claimed by other open work, avoid: `events.rs`, `synch.rs`, `threads.rs`, `scheduler.rs`, `cpu.rs`, `dbt.rs`, `imports.rs`, `memory.rs` (#323/#339); `process.rs`, `startup.rs`, `gdk_queue.rs`, `winsock.rs` (#329/#331); mock clock in `services.rs` (#204/#338). `services.rs` registration lines are shared by everyone; keep edits there to one field and one registration line.
## Next actions (priority order)
1. **Check both PRs** using the timestamp under Resume here.
2. On new #312/#316 comments → implement / reply immediately.
3. If quiet → continue CRT/runtime gaps that **do not** collide with #323 (no `CreateThread` scheduler). Sensible candidates:
- `GetTempFileNameW` is verified on synthetic and mounted drives. Continue remaining filesystem compatibility and verification from the brief. The host-mount quota suggestion remains open.
- `strtok_s` and `wcstok_s` are implemented and exercised through translated guest imports. Both are partial because they return `EINVAL` without invoking the UCRT invalid-parameter handler.
- Keep docs/`CHANGELOG` honest; no Xbox claims.
4. Sync `main` when new upstream commits appear; resolve changelog conflicts by **keeping both** sides.
5. Prefer updating **#312** for work that depends on host mounts; a cherry-pick onto bare `main` fails (stdio/host_files not on `main` alone).
6. DCO on every commit: `Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>`.
7. Do **not** force-push again unless a review requires another history rewrite; prefer normal commits.
---
## Key files
| Area | Paths |
| --- | --- |
| Host mounts | `crates/loader/src/services/host_files.rs`, `files.rs`, `tests/runtime_host_files.rs` |
| CRT | `crt.rs`, `crt_stdio.rs`, `crt_env.rs`, `crt_time.rs`, `crt_ctype.rs`, `crt_locale.rs`, `crt_callbacks.rs` |
| Winsock | `winsock.rs` |
| Modules | `modules.rs` |
| XAsync / queues | `gdk_async.rs`, `gdk_queue.rs` |
| Registration | `crates/loader/src/services.rs` |
| Contracts | `docs/interfaces.md`, `CHANGELOG.md` |
| Rules | `AGENTS.md`, `CONTRIBUTING.md`, `docs/legal.md` |
---
## Commands cheat sheet
```sh
export CARGO_HOME=/Volumes/SSD/xenora-toolchain/cargo
export RUSTUP_HOME=/Volumes/SSD/xenora-toolchain/rustup
export PATH="/Volumes/SSD/xenora-toolchain/cargo/bin:$PATH"
cd /Volumes/SSD/Xenora
git fetch origin main
git log --oneline HEAD..origin/main
cargo test -p xenora-loader --lib crt_stdio::tests
cargo test -p xenora-loader --test runtime_host_files
cargo clippy -p xenora-loader --lib -- -D warnings
cargo fmt -p xenora-loader -- --check
git push -u fork HEAD # after user auth; feature branch only
gh pr view 312 --repo ranveersoni98/Xenora
gh pr view 316 --repo ranveersoni98/Xenora
```
---
## Agent store copy
A mirror of this handoff may also live in the Cursor agent store for this chat:
`…/AgentStores/cursor_agent_stores/d3fb0682-0141-4df7-9bf0-e84a271beeea/files/HANDOFF-system-runtime.md`
Prefer the in-repo path above once pulled; keep them in sync if you edit either.
+419 -3
View File
@@ -224,7 +224,9 @@ and [virtual release](https://learn.microsoft.com/windows/win32/api/memoryapi/nf
### CRT strings and byte memory
The standard registry provides `strlen` and `strnlen` under UCRT and the CRT
The standard registry provides `strlen`, `strnlen`, `strcpy`, `strncpy`,
`strcat`, `strncat`, `memchr`, `strstr`, `strspn`, `strcspn`, and the wide
forms `wcscpy`, `wcsncpy`, `wcscat`, `wcschr` and `wcsrchr` 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
@@ -234,7 +236,9 @@ 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.
Counts and bounds for the wide variants are in code units. `_stricmp`,
`_strnicmp`, `_wcsicmp` and `_wcsnicmp` use the same rules with C-locale ASCII
case folding only (`A`–`Z`); they are not Unicode case mapping.
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.
@@ -272,7 +276,263 @@ 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.
same rules with 64-bit results. `atoi`, `atol`, `atoll`, `_atoi64`,
`_wtoi`, `_wtol` and `_wtoi64` reuse that parser with base 10 and no end
pointer; on Windows LLP64, `atol` matches `atoi` (32-bit `long`).
### CRT locale and formatted output
`setlocale` accepts only the C locale (`"C"`, `"POSIX"`, empty string, and
ASCII-case variants of `C.UTF-8`). Querying with a null locale name returns
a durable `"C"` string. Other locale names fail with `EINVAL` and a null
result. `localeconv` returns a guest `lconv` for that C locale. Thread
locales and `_create_locale` remain unsupported.
C-locale `ctype.h` predicates (`isalnum`, `isalpha`, `isdigit`, `islower`,
`isupper`, `isspace`, `isxdigit`, `isprint`, `iscntrl`, `ispunct`) and
`tolower` / `toupper` accept `EOF` or an `unsigned char` value. Other
`int` arguments stop the guest.
`sprintf` and `snprintf` implement a bounded C-locale subset: `%%`, `%c`,
`%s`, `%d`/`%i`, `%u`, `%x`/`%X`, `%p`, optional zero-pad widths, and
`l`/`ll`/`z`/`t` length modifiers. Null string arguments render as
`(null)`. Other conversions stop the guest. Transfers stay within the 1 MiB
service budget.
FILE streams implement `fopen`, `fclose`, `fread`, `fwrite`, `fseek`, `ftell`,
`feof`, `ferror`, `rewind` and `__acrt_iob_func`. Single path components (no
separators) use an in-memory store. Paths with a mounted drive letter open
through the same host mount policy as `CreateFileW`: the file is loaded into a
bounded buffer (up to 16 MiB, and not past the mount's size cap), and a
writable stream replaces the host contents on `fclose`. Up to 32 streams.
Stdin is empty, stdout/stderr discard writes. `printf` and `fprintf` use the
same format subset as `sprintf` (stdout discards the payload and returns the
length). The `__stdio_common_*` helpers remain unimplemented. Concurrent host
edits while a stream is open are not visible; this is a research subset, not
full CRT or Win32 file semantics.
### Process environment
`getenv`, `GetEnvironmentVariableA` and `GetEnvironmentVariableW` read a
runtime-owned environment block (defaults include `OS=Windows_NT`).
`_putenv` (`NAME=value`) and `SetEnvironmentVariableA` /
`SetEnvironmentVariableW` update or delete entries in that block. The host
process environment is not visible unless an entry is installed here.
### CRT calendar time
`time`, `_time64`, `gmtime_s`, `localtime_s`, `_gmtime64_s` and
`_localtime64_s` use the injectable guest clock (the same FILETIME source as
`GetSystemTimeAsFileTime`). There is no guest timezone database: local time
matches UTC and `tm_isdst` is always zero. 32-bit `time` saturates at the
2038 bounds rather than wrapping.
### CRT `rand`
`srand`, `rand` and `rand_s` use the publicly documented MSVC LCG
(`seed = seed * 214013 + 2531011`, return `(seed >> 16) & 0x7fff`). The seed is
process-wide. `rand_s` writes that 15-bit value into a guest `unsigned int`;
it is not a CSPRNG.
### Process-local Winsock UDP and TCP loopback
`ws2_32.dll` exposes a process-local IPv4 UDP loopback: `WSAStartup` /
`WSACleanup`, `socket` (AF_INET / SOCK_DGRAM / IPPROTO_UDP only),
`closesocket`, `bind`, `connect`, `send`, `recv`, `sendto`, `recvfrom`,
`getsockname`, `getpeername`, `getsockopt` (`SO_TYPE`, `SO_MAX_MSG_SIZE`),
`WSAPoll`, byte-order helpers, and `inet_ntop` / `inet_pton` for IPv4.
Datagrams stay in the runtime; nothing reaches the host network stack. Bound
addresses report `127.0.0.1`. At most 64 sockets, 16 pending datagrams per
socket and 65,507 bytes per datagram. `recv` / `recvfrom` are non-blocking
(`WSAEWOULDBLOCK` when empty). `sendto` may auto-bind an ephemeral port.
`WSAPoll` timeouts are capped at 1 second.
TCP streams (`socket` with SOCK_STREAM and protocol 0 or IPPROTO_TCP) connect
only to a listening guest socket on `127.0.0.1`, also inside the process.
`listen` clamps the backlog to 1–16 (SOMAXCONN included); a full queue or a
port with no listener reports `WSAECONNREFUSED`. `connect` completes at once,
and `accept` is non-blocking (`WSAEWOULDBLOCK` with nothing waiting). Each
socket buffers up to 64 KiB of unread bytes; `send` then takes what fits and
reports `WSAEWOULDBLOCK` when nothing fits, without reading the guest bytes it
does not report. `recv` returns 0 at end of file, after the peer's
`shutdown(SD_SEND)` or `closesocket`; sending to a closed peer reports
`WSAECONNRESET`, and `WSAPoll` reports `POLLHUP`. Closing a listener closes
connections it has not accepted. TCP and UDP ports are separate. `sendto`,
`recvfrom` and socket options other than `SO_TYPE` are not supported on
streams, and `shutdown` is not supported on datagram sockets. Raw sockets,
IPv6, blocking waits on streams and host interfaces remain unsupported.
`ioctlsocket` supports `FIONREAD` (unread stream bytes, or the size of the
next datagram; `WSAEINVAL` on a listening socket) and `FIONBIO` with a nonzero
argument. Every socket is already non-blocking, so asking for blocking mode
returns `WSAEOPNOTSUPP` instead of being ignored.
### CRT character and line streams
`fputc`, `putc`, `fputs`, `puts`, `fgetc`, `getc` and `fflush` are registered
on `ucrtbase.dll` and `api-ms-win-crt-stdio-l1-1-0.dll` and share the stream
state of `fopen`. The character functions return the byte as an unsigned char
or `EOF`; writing a read-only stream or reading a write-only one returns `EOF`
and sets the error indicator. `fputs` adds no newline and `puts` adds one;
standard output accepts and discards output. `fflush` writes a dirty
host-backed stream to its mounted file now rather than at `fclose`, charging
the mount quota, and publishes an in-memory file so a second `fopen` sees it.
A null stream flushes every open stream, and flushing an input stream has no
effect.
`ungetc` pushes back one byte after at least one byte has been read: the
position steps back, and the next read returns the pushed-back byte. It
clears the end-of-file indicator and is never written to the file; a seek,
`rewind` or write discards it. Pushing back `EOF`, a second byte, or a byte at
the start of the stream returns `EOF`. C guarantees only one byte of
push-back, and Xenora does not provide more. `fgets` reads at most
`count - 1` bytes, stops after a newline (kept in the buffer) and adds a
terminator. At end of file with nothing read it returns null and leaves the
buffer unchanged. A null buffer or a count of zero or less sets `EINVAL` and
returns null.
### Bounds-checked string copies
`strcpy_s`, `strcat_s`, `strncpy_s`, `strncat_s`, `wcscpy_s`, `wcscat_s`,
`wcsncpy_s` and `wcsncat_s` are registered on `ucrtbase.dll` and
`api-ms-win-crt-string-l1-1-0.dll`. Sizes and counts are in characters. A null
or zero-sized destination returns `EINVAL` and leaves it untouched. A null
source (with a nonzero count), an unterminated append destination, or a result
that does not fit returns `EINVAL` or `ERANGE` and leaves the destination
empty. A count of `_TRUNCATE` copies what fits and returns `STRUNCATE`, which
is not stored in `errno`; a count of zero writes only the terminator. Every
other error is also stored in `errno`. The invalid-parameter handler is not
modelled.
### CRT block sizes and aligned allocation
`_msize`, `_recalloc`, `_aligned_malloc`, `_aligned_realloc`, `_aligned_msize`
and `_aligned_free` are registered on `ucrtbase.dll` and
`api-ms-win-crt-heap-l1-1-0.dll`, using the same CRT heap as `malloc`.
`_msize` reports the requested size. `_recalloc` checks `count * size` for
overflow (`ENOMEM`, block unchanged), zeroes bytes past the old size, and frees
the block for a size of zero.
Heap blocks start on 64 KiB boundaries, so an aligned block is an ordinary
heap block whose address is checked. Alignments that are not powers of two
return `NULL` with `EINVAL`; alignments above 64 KiB return `NULL` with
`ENOMEM` instead of a misaligned block. `_aligned_realloc` resizes in place
when it can and otherwise moves the contents to a new aligned block.
`_aligned_offset_malloc` is not provided, so `_aligned_msize` with a nonzero
offset returns `EINVAL`. Aligned blocks are recorded: passing `_aligned_free`,
`_aligned_realloc` or `_aligned_msize` a pointer that `_aligned_malloc` did not
return, or one already freed, stops the guest with a memory fault. Calls the
UCRT sends to the invalid-parameter handler set `errno` and return the
documented failure value; the handler is not modelled.
### C++ type identity
`__std_type_info_compare`, `__std_type_info_hash`, `__std_type_info_name` and
`__std_type_info_destroy_list` are registered on `vcruntime140.dll`. They back
`typeid` equality, `type_info::before`, `hash_code` and `name`. Each takes the
type descriptor's data: an 8-byte cached-name slot followed by the decorated
name, as in the publicly described MSVC RTTI type descriptor.
Two descriptors with the same decorated name compare equal and hash equally,
so a type seen from two modules is one type. The hash is FNV-1a over the
decorated name and is not claimed to match Microsoft's runtime. `name`
undecorates plain class, struct, union and int-based enum names with their
namespaces (`.?AVWidget@ui@@` becomes `class ui::Widget`), allocates the text
on the guest heap and caches it in the descriptor; `destroy_list` frees those
names. Templates, back-references, anonymous namespaces and non-class types
stop the guest instead of returning a wrong name.
`__std_exception_copy` and `__std_exception_destroy` manage the message record
inside `std::exception`: the message pointer, then a one-byte flag that says
whether the exception owns the text. A copy duplicates an owned message on the
CRT heap, so `what()` stays the same after the original is destroyed, and
shares a borrowed one. If the duplicate cannot be allocated, the copy gets an
empty record. Destroy frees an owned message (guest `free` and these helpers
use the same heap) and clears the record. Destroying an owned pointer the heap
never allocated stops the guest with a memory fault.
Throwing and catching exceptions, `dynamic_cast` and thread-safe static
initialization are not implemented. `terminate` and `_purecall` are described
under abnormal termination below.
### Abnormal CRT termination
`abort`, `terminate` and `_purecall` (on `ucrtbase.dll` and
`api-ms-win-crt-runtime-l1-1-0.dll`) and `__std_terminate` and `_purecall` (on
`vcruntime140.dll`) end the guest process with exit code 3, the code the
Microsoft C runtime documents for `abort` without a `SIGABRT` handler. The
default `terminate` and pure-virtual-call handlers call `abort`. `_exit` ends
the process with the low 32 bits of its status and runs no `atexit`
functions. All of them use the same process exit as `ExitProcess`: handles
close, the first exit decides the status, and the host process never ends.
No handler can be installed: `signal`, `set_terminate` and
`_set_purecall_handler` are not runtime services, so a guest that calls them
stops there instead of getting a handler that is silently ignored. `exit`,
which must run `atexit` functions first, is not provided. Debug-CRT message
boxes and error reporting are not modelled.
### CRT integer absolute value and division
`abs`, `labs`, `llabs`, `div`, `ldiv` and `lldiv` are registered on
`ucrtbase.dll` and `api-ms-win-crt-utility-l1-1-0.dll`. They follow the
Windows LLP64 model, where `long` is 32 bits, so `labs` and `ldiv` match `abs`
and `div` and ignore the upper half of each argument register. `div_t` and
`ldiv_t` return in RAX with the quotient in the low 32 bits and the remainder
in the high 32 bits. `lldiv_t` is 16 bytes, so the caller passes a result
pointer in RCX, the operands arrive in RDX and R8, and RAX returns the pointer.
Quotients truncate toward zero. The absolute value of the minimum integer
wraps to itself. Division by zero and the minimum divided by -1 stop the guest
with a divide error, as the x86 `idiv` instruction does.
### CRT floating-point string conversion
`strtod`, `strtof`, `wcstod`, `wcstof`, `atof` and `_wtof` are registered on
`ucrtbase.dll` and `api-ms-win-crt-convert-l1-1-0.dll` and return their
result in XMM0. They parse the ISO C grammar in the "C" locale: leading white
space, an optional sign, then decimal digits with an optional `.` and an
optional exponent (consumed only if a digit follows `e`), `inf`, `infinity`,
or `nan` with an optional closed `(n-char-sequence)`, all case-insensitive.
Decimal input is rounded once, directly to the result type, so `strtof` does
not round through `double`. With no conversion the result is 0 and the end
pointer is the string itself.
Overflow returns a signed infinity and sets `ERANGE`, and so do nonzero digits
that round to zero. Whether the UCRT also sets `ERANGE` for a subnormal
nonzero result is not established from public documentation, so Xenora
leaves `errno` unchanged there. A NaN payload is accepted and ignored; the
result is the default quiet NaN with the parsed sign. Hexadecimal floating
constants such as `0x1.8p3` stop the guest rather than being parsed as `0`.
### XInput controllers
`XInputGetState`, `XInputSetState`, `XInputGetCapabilities` and
`XInputEnable` are registered on `xinput1_4.dll`; `xinput1_3.dll` and
`xinput9_1_0.dll` reach the same services (`xinput9_1_0.dll` has no
`XInputEnable`). Readings come from a `ControllerSource` the host connects
with `ServicesState::set_controllers`. Without one, every slot reports
`ERROR_DEVICE_NOT_CONNECTED`. `SimulatedControllers` is a deterministic source
for tests; no physical controller or app input path is connected yet.
The functions return their error code and leave last-error alone: a slot of 4
or more, a null buffer or unknown capability flags return
`ERROR_BAD_ARGUMENTS`, and an unmapped buffer returns `ERROR_NOACCESS`.
`dwPacketNumber` advances only when the reading changes. While
`XInputEnable(FALSE)` is in effect, `XInputGetState` reports a neutral
controller and the motors stop; the last vibration request is applied again
when XInput is enabled. Capabilities report a gamepad with every defined
button, full trigger and stick resolution, and force feedback only when the
source says the controller can vibrate. Battery, keystroke and audio-device
functions are not implemented.
### XAsync helpers
`XAsyncRun`, `XAsyncGetStatus`, `XAsyncCancel` and `XAsyncGetResultSize` are
registered on `xgameruntime.dll`. With a null queue in the `XAsyncBlock`, the
work callback and optional completion callback run on the calling thread
before `XAsyncRun` returns (immediate dispatch). With a non-null manual
`XTaskQueue` handle, work is submitted to the work port and completion to the
completion port; the guest must `XTaskQueueDispatch` those ports.
`XAsyncGetStatus` with `wait=true` returns `ERROR_NOT_SUPPORTED`.
### Built-in guest modules
@@ -282,6 +542,10 @@ 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.
`GetModuleFileNameA` / `GetModuleFileNameW` return synthetic paths:
`C:\xenora\guest.exe` for a null handle, and
`C:\Windows\System32\<module>` for built-in DLL handles. They do not reveal
host filesystem paths.
### Synthetic guest files
@@ -307,6 +571,146 @@ 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.
### Host-backed guest drives
`ServicesState::mount` exposes a host directory to the guest as a drive
letter from D: to Z:, through `HostMount::new(drive, root, writable)`. Without
a mount, nothing on the host is reachable through these services. Mounts are
read-only unless created writable.
The partial `GetFileAttributesExA/W` services return attributes and 64-bit
sizes for `GetFileExInfoStandard`. Host-mounted entries carry access and
modification timestamps and creation time where the host supplies it.
Synthetic files use the guest clock and accept explicit timestamp changes. Directory enumeration uses the same
timestamp representation. `GetFileTime` reads these values from an open
file with read access and accepts null pointers for omitted values.
The partial `SetFileTime` service updates access and modification times on
writable mounted files. On synthetic files it also accepts creation-time
updates. Null inputs and zero FILETIMEs leave fields unchanged. Host
creation-time updates and host timestamp suppression are unsupported.
Synthetic handles accept all-ones access and write times to suppress
automatic updates for that open file.
Synthetic files update access time after a nonempty read and modification
time after a nonempty write or truncation.
The ANSI form accepts ASCII paths.
The partial `FlushFileBuffers` service requires a writable file handle.
It synchronizes the backing file on a host mount. Synthetic file writes
are already visible in the guest's in-memory filesystem.
The ANSI forms `CreateFileA`, `DeleteFileA`, and `GetFileAttributesA`
accept ASCII paths and use the same guest namespace and mount rules as the
wide forms.
The partial `GetTempPathA/W` services use the first nonempty guest value
among `TMP`, `TEMP`, and `USERPROFILE`, falling back to the synthetic
`C:\` root. They add a trailing separator without checking whether the
directory exists. The narrow entry point accepts ASCII. No host environment
is consulted.
The partial `GetTempFileNameW` service accepts ASCII prefixes on the synthetic
drive and explicitly mounted drives. Automatic creation requires a writable
mount and uses exclusive creation inside the resolved directory. A nonzero unique value formats a name without creating a file. A zero
value picks an available name using the guest clock and creates an empty file
without retaining a handle. Callers can remove it with `DeleteFileW`.
The confinement policy below is enforced in `services/host_files.rs` and
covered by `crates/loader/tests/runtime_host_files.rs` and unit tests in that
module. Guest path confinement for this boundary was reviewed by Cursor
security-review and implementation-review agents (not a human audit).
- **Path resolution.** The root directory is opened once with
`O_DIRECTORY | O_NOFOLLOW`, so a symlink mount root is rejected. Every
operation resolves the guest path from that descriptor one component at a
time with `openat` and `O_NOFOLLOW`. `.` and `..` components, device names,
Windows-invalid characters and drive-relative paths are rejected. Names
match the host listing ignoring ASCII case. Two host entries that match
the same name under this rule are refused as ambiguous. Non-ASCII letters
must match the spelling in the listing. If the host filesystem treats a
different spelling as a collision, exclusive file creation returns
`ERROR_FILE_EXISTS` and directory creation returns `ERROR_ALREADY_EXISTS`.
- **Hidden entries.** The guest cannot see or open symbolic links, devices,
sockets, FIFOs, non-UTF-8 names, or regular files with more than one hard
link. Hiding multiply linked files prevents a hard link from aliasing a
host file outside the root. The cost is that legitimately hard-linked files
are hidden too.
- **Descriptor verification.** After each `openat`, the descriptor is
checked with `fstat`: it must be the expected type, a file must have one
link, and the device and inode must match what the listing reported. A host
change that swaps an entry between the listing and the open fails with
`ERROR_ACCESS_DENIED`. Removal opens and re-verifies the entry, re-checks
the directory listing, then uses name-based `unlinkat`. A concurrent host
rename in that window can still remove a different entry inside the mount
(never outside it). Host writers under the mount are trusted for that
residual race. A file unlink that did not drop the held inode's link count
fails closed; directories have no post-unlink check.
- **File identity.** Reads, writes and truncation use the verified
descriptor, so they reach the same file after a host rename. Sharing checks
and the open-file check in DeleteFileW compare the live device and inode of
every open handle, not guest paths. A truncating open is checked for
sharing before it truncates. If an open handle's identity cannot be read,
the check treats it as the same file, so failures deny access rather than
grant it.
- **Read-only enforcement.** Read-only mounts reject creation, truncation,
writes, deletion and directory changes with `ERROR_ACCESS_DENIED`. They also
open every file `O_RDONLY`, so the host kernel refuses writes as well.
- **Resource limits.** A directory listing is bounded at 4,096 visible
entries. Larger directories report `ERROR_NOT_ENOUGH_MEMORY` rather than a
partial listing. Open handles share the 1,024-handle object table.
Transfers are limited to 1 MiB per call. On writable mounts, writes and
truncation cannot make a file larger than the mount's limit
(`HostMount::with_max_file_size`, 1 GiB by default); they report
`ERROR_DISK_FULL` instead.
- **Mount quota.** `HostMount::with_quota(bytes, entries)` optionally bounds
the net bytes and the net number of files and directories that guest
operations add to a writable mount, relative to its contents when mounted.
Writes, extending `SetEndOfFile`, `CreateFileW`, `CreateDirectoryW`,
`GetTempFileNameW` and CRT `fopen` are charged; shrinking, `DeleteFileW`
and `RemoveDirectoryW` give the amount back, never below zero. An operation
that would exceed a limit fails with `ERROR_DISK_FULL` (CRT: `ENOSPC`) and
leaves the host unchanged. CRT streams are charged when `fclose` writes them
back. Changes made by host processes are not counted, and
`HostMount::usage` reports the current amounts. No quota is set by default.
- **Errors.** Errors from reading a directory or examining an entry are
reported, except an entry removed while it is being listed. Host errors map
to specific Win32 codes (for example `ENOENT` to `ERROR_FILE_NOT_FOUND`,
`ENOTEMPTY` to `ERROR_DIR_NOT_EMPTY`, `ENOSPC` to `ERROR_DISK_FULL`);
unrecognized errors report `ERROR_GEN_FAILURE`.
Not covered: another host process that moves a directory or file the guest
already holds open out of the mount. The guest keeps its handle to that
object, because handles refer to opened files, not paths. Host processes with
write access to a mounted directory are therefore trusted if confinement
matters against concurrent host writers. Name-based removal still has a short
in-mount TOCTOU against such writers (check-then-unlink by name). Some file
systems do not keep inode numbers stable (exFAT renumbers a file when its
storage is first allocated), so identities are compared live rather than
cached; if an open handle's identity cannot be read, sharing checks fail
closed.
CreateFileW, ReadFile, WriteFile, GetFileSizeEx, SetFilePointerEx,
SetEndOfFile, GetFileAttributesW, FindFirstFileW and FindNextFileW work on
mounted drives with the same handle types, rights, sharing modes and file
positions as the synthetic drive. CreateDirectoryW, RemoveDirectoryW and
DeleteFileW also work on writable mounts. Files on read-only mounts report
`FILE_ATTRIBUTE_READONLY`. MoveFileW renames a closed file or a directory
within one writable mount with an exclusive host rename, so it never replaces
an existing name (`ERROR_ALREADY_EXISTS`); a change of case alone renames in
place. An open file reports `ERROR_SHARING_VIOLATION`, since
`FILE_SHARE_DELETE` is not supported. MoveFileExW accepts
`MOVEFILE_REPLACE_EXISTING`, which atomically replaces a closed file (never a
directory, `ERROR_ACCESS_DENIED`), `MOVEFILE_WRITE_THROUGH`, which flushes both
host directories before returning, and `MOVEFILE_COPY_ALLOWED`; other flags
return `ERROR_NOT_SUPPORTED`. The synthetic C: drive follows the same rules
for files. Moves between drives return `ERROR_NOT_SAME_DEVICE`, or
`ERROR_NOT_SUPPORTED` with `MOVEFILE_COPY_ALLOWED` (and from MoveFileW), since
the copy Windows would then make is not implemented. As with deletion, the source
is matched by name after a final listing check, so a concurrent host rename
can move a different entry inside the mount, never one outside it.
Times, alternate names and asynchronous I/O are not reported. The mount
tests need a temporary directory that supports hard links and POSIX
permissions: `/tmp`, or the directory named by `XENORA_TEST_TMP`.
### Event and semaphore signaling
The synthetic runtime supports unnamed manual-reset and auto-reset events
@@ -401,6 +805,18 @@ separately, for diagnostics.
`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.
- `IsProcessorFeaturePresent` answers from the same fixed table that guest
`CPUID` returns, so the two always agree. A feature is present only when
every CPUID bit it depends on is set; today that table sets none of the
features the function can report, so every answer is `FALSE`. Features
with no CPUID test, such as `PF_NX_ENABLED` and `PF_FASTFAIL_AVAILABLE`,
and unknown numbers report `FALSE`.
- `GetLogicalProcessorInformation` reports one core per profile processor
and one package holding them, 32 bytes each. No cache or NUMA entries are
reported, because no cache hierarchy is simulated. A short buffer fails with
`ERROR_INSUFFICIENT_BUFFER` and the required length.
- `GetTimeZoneInformation` reports UTC: zero bias, both names "Coordinated
Universal Time", no daylight transition, and `TIME_ZONE_ID_UNKNOWN`.
- `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
+11
View File
@@ -9,6 +9,7 @@ Guest imports resolve through one lookup, `ImportRegistry::resolve`. Binding, th
| Adapters | `crates/loader/src/runtime_table.rs` | Generated Win64 argument and result adapters and static metadata. |
| Handlers | `handlers` in `crates/loader/src/services.rs` | Rust implementations. They see guest memory and service state, never the CPU. |
| Report | [services.md](services.md) | Generated counts. Aliases are counted apart from services. |
| Coverage | `xenora imports coverage` | Every service the standard registry provides, by module and status, checked against the import metadata. Writes `artifacts/coverage/api-coverage.md` by default. |
## Rules
@@ -25,6 +26,16 @@ Guest imports resolve through one lookup, `ImportRegistry::resolve`. Binding, th
2. Add the entry to `services.txt` and the handler to `services.rs`.
3. Run `cargo run -p xenora-import-gen --bin xenora-runtime-gen generate`.
## Coverage report
`cargo run -p xenora -- imports coverage [--out <file>]` builds the standard registry and the built-in import metadata and writes one Markdown report. It reads no executable, network or clock, so the same tree gives the same bytes; a CLI test runs it twice and compares. The report lists three kinds of disagreement:
- the metadata expects a standard service that the registry does not resolve, which the CLI tests also reject;
- the registry provides a service the metadata classifies as something else, such as a stub, so the import generator would emit a stub for a working service;
- the registry provides a service the metadata does not list at all.
Counts are not compatibility claims, and the report is not committed: it changes whenever a service is added.
## Outside this registry
The fixture graphics services, `XMemAlloc` and the `XMemFree` stub are still registered by hand. The older import-list generator in `crates/import-gen` is separate: its output is not compiled into the loader, and several of its generated conformance tests check Rust library functions rather than a service.