mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-27 19:40:28 +00:00
Compare commits
48
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c18f9ffa7f | ||
|
|
acb3839351 | ||
|
|
f9d5838091 | ||
|
|
4173a781af | ||
|
|
2f68ee9d4a | ||
|
|
e7a2159c82 | ||
|
|
98e9420b7f | ||
|
|
238b5a001b | ||
|
|
99ed89787e | ||
|
|
522560d0a2 | ||
|
|
d28d539a90 | ||
|
|
8c4b2344df | ||
|
|
a75d018435 | ||
|
|
4652eb08cb | ||
|
|
ab73969135 | ||
|
|
8ee0304237 | ||
|
|
42cdb7d122 | ||
|
|
e57386950b | ||
|
|
0aeb2b69a9 | ||
|
|
1342878c49 | ||
|
|
34e99b3745 | ||
|
|
d5fa319f56 | ||
|
|
e5d83e87ac | ||
|
|
985d3b9e78 | ||
|
|
a91c7fa39d | ||
|
|
22425287e2 | ||
|
|
874c7c7a63 | ||
|
|
f30e4af4eb | ||
|
|
501117c4d8 | ||
|
|
3d796f51cf | ||
|
|
48d22f533b | ||
|
|
464393e02a | ||
|
|
aae04a2956 | ||
|
|
721073169c | ||
|
|
26148f49f6 | ||
|
|
e81382de37 | ||
|
|
afe8d16d9e | ||
|
|
d326e929a9 | ||
|
|
149869a053 | ||
|
|
32251af4c8 | ||
|
|
1c6bd25723 | ||
|
|
007ad360e9 | ||
|
|
0d6cef6c4e | ||
|
|
64a0cb1596 | ||
|
|
53e5e38a4e | ||
|
|
47a819e05b | ||
|
|
729e1b4cb1 | ||
|
|
1dcf722323 |
No files matched your search
@@ -34,10 +34,13 @@ remains unsupported.
|
||||
|
||||
### Fixed
|
||||
- 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.
|
||||
- An instruction longer than 15 bytes now stops both engines with a general-protection fault instead of an illegal-instruction exit (#384; Intel SDM Vol. 3A, 7.15). The decoder still stops before fetching a 16th byte, and the DBT translates the faulting instruction on its own so the instructions before it in a block complete first. The `defect_overlong_instruction` known answer from #155 is now verified, with three more cases.
|
||||
- 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
|
||||
- The gfx1030 identification benchmark fixture now runs as an ordinary integration test, so workspace tests check LLVM-derived names, families, lengths and byte boundaries without invoking a timing run.
|
||||
- Added a CPU benchmark for gfx1030 metadata identification (#173). It verifies instruction boundaries on a mixed-family stream assembled with LLVM and reports first-pass and repeated-pass throughput.
|
||||
- Added a Win64 ABI regression showing that a service may write the caller-allocated shadow space. Existing negative controls cover nonvolatile XMM-register corruption; the unchanged-home-slot test now describes its handler rather than implying an ABI preservation requirement.
|
||||
- Added a BetterXen development phase plan based on current source, pending PRs and existing acceptance records, linked from both contributor entry points. It separates baseline reconciliation, hosted C execution, guest threading, translated rendering, application integration and measured optimization; no new runtime or compatibility acceptance is claimed.
|
||||
- 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.
|
||||
@@ -46,6 +49,9 @@ remains unsupported.
|
||||
- The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review.
|
||||
- Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify 16-byte-aligned call entry (`RSP % 16 == 8`), caller-owned 32-byte shadow space accessibility/integrity, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
|
||||
- `dbt_bench` can compare two of its JSON documents when `XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json>` is set (#114). It prints each median with its change and whether the change exceeds the larger recorded IQR, and lists changed DBT counters. It refuses, with exit status 1 and the differing field named, to compare runs from different CPUs, operating systems or architectures, with unknown host fields, or with different workloads, sample counts, debug assertions or build labels. A new optional `XENORA_DBT_BENCH_BUILD_LABEL` records build settings the benchmark cannot see, such as LTO. No benchmark runs in this mode.
|
||||
- LAHF and SAHF run in both engines, and guest CPUID reports them in leaf `8000_0001h`, ECX bit 0 (#387; Intel SDM Vol. 2A LAHF, Vol. 2B SAHF). The DBT runs them through the shared semantics. The four known answers from #155 that both engines refused are now verified, with twelve more cases, and the independent reference in `tests/x86_integer.rs` covers both instructions.
|
||||
- LOOP, LOOPE, LOOPNE and JRCXZ run in both engines (#396; Intel SDM Vol. 2A, LOOP/LOOPcc and Jcc). The count is RCX; the address-size prefix stays rejected, so JECXZ and the ECX-counted forms are still refused. The DBT runs them through the shared semantics and ends its block at each. The three known answers from #155 that both engines refused are now verified, with eleven more cases, and `tests/cpu_loop.rs` checks a loop that spans translated blocks against a step-by-step model for every count, ZF match point and step budget.
|
||||
- `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=<path>` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged.
|
||||
- Added synthetic guest handle-lifetime regression tests (#205) for capacity reuse, stale handles, duplicate rights and lifetime, wrong object types, thread pseudo handles and failed-output nonmutation. Runtime behavior is unchanged; independent acceptance is pending.
|
||||
- Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302).
|
||||
@@ -88,6 +94,7 @@ remains unsupported.
|
||||
- Added 985 LLVM-assembled integer instructions with a bit-level reference that reads only their assembly text, compared with the interpreter and the DBT over 47,280 states, plus 4,000 random instruction sequences compared between the engines.
|
||||
- Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215.
|
||||
- Added MOVZX, MOVSX (0F B6/B7/BE/BF) and MOVSXD (63) for register and checked memory operands in the interpreter and the native DBT, with exact lengths in the static probe (parts of #65, #66, #67, #68 and #117; awaiting independent review). Covered: 16-, 32- and 64-bit destinations, AH/CH/DH/BH without REX, FS/GS bases and RIP-relative operands. Other 0x66 forms are rejected instead of running at the wrong width. Known-answer encodings come from the LLVM assembler; MOV immediates (B8-BF) have regressions proving they are never read as sign extensions.
|
||||
- Added FNINIT (`DB E3`), the one instruction a C program built with the mingw-w64 runtime needs that the decoder refused (#378, part of Gate A2). Guest state gains the x87 control, status and tag words in `CpuState::x87`, and FNINIT sets them to the Intel SDM values `037F`, `0` and `FFFF`. Both engines run the shared semantics; nothing is lowered to ARM64 and the host's floating-point state is never touched. The registry gains a form key, `rm`, that pins a register-only form to one ModRM byte, because the other bytes of `DB /4` are different instructions. No other x87 instruction exists: FNSTCW, FLDCW, FNCLEX, FWAIT and all x87 arithmetic stay rejected, there are no x87 data registers, nothing can read the three words back, and CPUID still reports no FPU. Nine SDM-derived cases in `cpu_known_answers.rs`, whose harness now starts every case with the three words away from their reset values and requires every other instruction to keep them, one assembled fixture checked by the text-only reference in `x86_integer.rs`, and a sweep of every ModRM byte under opcodes `D8` to `DF` in both engines cover it. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added Phase II infrastructure CLIs under `scripts/qa` and `scripts/release` (#277): read-only RDNA2 expansion planning over live inventories, unified verification profiles with stale-evidence detection, CPU/runtime coverage scans, benchmark regression comparisons that reject incompatible identities, git rename/delete scope collision reports, and release-readiness reports with SBOM/checksum/bundle checks. Covered by `tests/qa` and `tests/release`; advisory until reviewed.
|
||||
- Added advisory infrastructure QA helpers under `scripts/qa/` and `scripts/release/` (issue #277): exit-status-preserving orchestration with JSON reports, PR scope/DCO/artifact checks, benchmark percentile analysis over existing samples, environment and repository health diagnostics, ARM64 Mach-O/bundle/codesign helpers, and checksum manifests. Covered by `tests/qa/` and `tests/release/`; checks stay advisory until reviewed.
|
||||
- Recorded agent-queue live smoke evidence for issue #180 against the disposable private repository `ranveersoni98/xenora-agent-queue-smoke`, including claim grant, overlap refusal, release, not-ready denial, progress renew and a successful audit dispatch after fixing comment-only `apply_actions` and audit permissions/argparse issues.
|
||||
@@ -130,14 +137,22 @@ remains unsupported.
|
||||
|
||||
- Added non-alertable extended event waits through both Win64 wait APIs.
|
||||
|
||||
- Added the C runtime's `exit`, `_exit` and `abort` (#395, part of Gate A2), on top of the process exit from #329. A C program ends through `exit`, not `ExitProcess`, and a program built with the mingw-w64 runtime imports all three; the loader refused it before its entry point because they did not resolve. `exit` calls the functions registered with `atexit` and `_crt_atexit`, most recently registered first, and then ends the guest with `ExitReason::ProcessExit(status)`; `_exit` ends it with its status and `abort` with exit code 3, and neither calls a registered function. All three go through the same cleanup as `ExitProcess` and never end the host. A function registered while `exit` runs is called next, as ISO C requires; `exit` called again from a registered function, which ISO C leaves undefined, runs the remaining functions once and ends with the later status. All three are partial: no stream is flushed because there are none, `abort` prints no message and calls no `SIGABRT` handler, and thread-local destructors are not run. Nine tests in `crt_exit.rs` call them from guest code. `docs/testing/gate-a.md` now describes A2 as in progress and not passing. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added immediate wait-any and wait-all for guest event handles.
|
||||
|
||||
- Added guest CRT signed and unsigned 64-bit conversions for narrow and wide strings.
|
||||
|
||||
- Added command-line arguments for a hosted C program (#392, part of Gate A2): the C runtime services `__p___argc`, `__p___argv`, `__p__environ`, `_configure_narrow_argv` and `_initialize_narrow_environment`, and a host method, `ServicesState::set_program_arguments`, that supplies the program's `argv`. A program built with the mingw-w64 runtime gets `argc`, `argv` and `envp` for `main` through these five, and the loader refused it before its entry point because they did not resolve. After configuration the guest finds the host's arguments in `__argc` and `__argv`, each NUL-terminated, with a null pointer after the last; with no host input it gets one empty argument, as ISO C specifies. The host method refuses a NUL byte, more than 32,767 bytes in all, and a call after the guest has built its table. The three variables are documented and the two initialization functions are not, so their behaviour is Xenora's: no code page, no wildcard expansion, and an empty environment table. All five are `partial`. Four tests in `runtime_services.rs` call the services from guest code and compare what the guest sees with what the test supplied. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added bounded guest CRT long-integer parsing for byte and wide strings.
|
||||
|
||||
- Added standard output for a hosted C program (#400, part of Gate A2): a `printf` formatting engine, the standard streams, and capture of what the guest writes to `stdout` and `stderr`. The services are `__acrt_iob_func`, `__stdio_common_vfprintf` (what `printf` and `fprintf` call in a program built with the mingw-w64 runtime), `fwrite`, `fputs`, `fflush` and `setvbuf`; a host reads the output through `ServicesState::standard_output` and `standard_error`. The engine handles the flags, width, precision and size prefixes of `d`, `i`, `u`, `o`, `x`, `X`, `c`, `s`, `p` and `%%` as Microsoft's format specification page and ISO C describe, reading arguments from the guest's `va_list`. The standard streams are text-mode streams, so a line feed is captured as carriage return and line feed. Floating-point and wide conversions, a locale object, other streams and files are not modelled and stop the guest with the runtime-limit fault instead of printing something wrong; `%n` and unknown conversions return -1 with `EINVAL`. All six services are `partial`. The engine's output matches the host C library's `snprintf` on 2,600 generated cases whose result ISO C defines (`crates/loader/tests/printf/reference.py`), with hand-written cases for the Windows-specific rules, and seven tests in `runtime_services.rs` call the services from guest code. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added guest CRT errno accessors and allocation failure reporting for the synthetic main thread.
|
||||
|
||||
- Added nine C runtime services that a C program's startup code calls or imports before `main`, and one alias (#382, part of Gate A2): `_set_app_type`, `_set_new_mode`, `_configthreadlocale`, `__setusermatherr`, `_set_invalid_parameter_handler`, `__p__fmode`, `__p__commode`, `signal` and `SetUnhandledExceptionFilter`, plus `memcpy` through `api-ms-win-crt-private-l1-1-0.dll`. A program built with the mingw-w64 runtime imports all of them, and the loader refused it before its entry point because they did not resolve. Each records what it is given and returns what its public documentation says: the previous mode, setting or handler, the documented failure value, or the address of the guest variables `_fmode` and `_commode`. All nine are declared `partial` in the typed registry because nothing acts on a recorded value: no handler or filter is ever called, no signal is raised, there is no locale, and nothing reads `_fmode` yet. `ServicesState` gains two read-only accessors, `crt_app_type` and `crt_user_math_error`. Five tests in `runtime_services.rs` call the services from guest code through a bound import table. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added guest CRT allocation, zeroed array allocation, resizing, and release.
|
||||
|
||||
- Added private guest heap creation and destruction with per-heap allocation ownership.
|
||||
@@ -146,6 +161,8 @@ remains unsupported.
|
||||
|
||||
- Added the synthetic default process heap with allocation, size queries, and release.
|
||||
|
||||
- Added `VirtualProtect`, `VirtualQuery` and `__C_specific_handler` as `stub` services so that a C program built with the mingw-w64 runtime can bind its imports (#388, part of Gate A2). Such a program imports all three and does not call them on a normal run; without them the loader refused it before its entry point. A call to any of them stops the guest with the runtime-limit fault (`IllegalInstruction(0xFE)`) and writes nothing, so a program that needs one stops there and cannot run on with a made-up result. No page protection is changed, no region is described and no exception is dispatched. The service generator's API-set table gains `api-ms-win-crt-private-l1-1-0.dll` for `ucrtbase.dll`, which is inferred and not taken from a document that names it. Two tests in `runtime_services.rs` call the stubs from guest code and check how they resolve. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added Win64 signatures for wide-string length and comparison and overlapping byte moves to the import catalog.
|
||||
|
||||
- Added guest CRT wide-string length and comparison using Windows 16-bit code units.
|
||||
@@ -244,6 +261,7 @@ remains unsupported.
|
||||
- Fixed the address reported when a guest memory access faults part-way across a 4 KiB page boundary (#175). An access that starts in a mapped page and runs into an unmapped or forbidden one now reports the first byte it may not touch; it used to report the start of the access. An access whose first byte fails reports the same address as before, and a failed access still reads and writes nothing. Three Intel SDM page-fault cases in `cpu_known_answers.rs` moved from open defect to verified on both engines. `crates/loader/tests/memory_page_boundaries.rs` checks permissions, adjacent pages, address overflow and the fault address at every 4 KiB guest boundary across two host pages (16 KiB each on Apple Silicon). Guest memory is checked in software, so the host page size does not affect these results. Four #82 expectations and one CRT `memmove` expectation that pinned the start address were corrected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Fixed the native dependency audit reading Cargo JSON and inspection-tool output in the process locale encoding; it now reads and reports UTF-8 paths and diagnostics under an ASCII locale (#363).
|
||||
- Fixed a latent ARM64 `LSLV` encoding bug that forced bit 1 of the shift-count register field (part of #131). The dynamic binary translator uses `X10` in its only call, which already has that bit set. `RBIT`, `CLZ` and `LSLV` now panic on out-of-range register numbers before emitting an instruction. Encoding tests use words checked against LLVM's assembler.
|
||||
- Fixed flat (untextured) guest `DrawInstanced` draws in the synthetic D3D12-style graphics context (#148). A draw with zero instances or fewer than three vertices now draws nothing. A non-zero start vertex or start instance, more than one instance or more than three vertices now fails with `GraphicsError::Unsupported` instead of drawing the view's first triangle. Vertex reads stay inside the vertex buffer, so a view past its end, or one whose guest address would overflow, fails with `IndexOutOfRange` instead of reading neighbouring guest memory or panicking. `crates/loader/tests/repeated_frames.rs` runs these through repeated reset, record, close and execute frames on the software reference backend, with hand-derived pixels; no native Metal result is claimed.
|
||||
- Made the static probe and the binder share one bounded import parser, after the truncated-name fix for #270. Truncated, unterminated, empty or non-ASCII names, reserved bits and endless tables are reported by the probe and refused by the binder.
|
||||
- Fixed TLS callback metadata that was accepted or misread without an error (#78). A non-zero `AddressOfCallbacks` outside the image's sections, or 4 GiB or more above the image base, is now refused; it used to mean "no callbacks" or read the list from an unrelated place. The callback list must reach its null entry inside its section, where the section's zero-filled tail counts, and a list of more than 64 callbacks is refused where it used to be cut short. `execute_tls_callbacks` refuses a stack top that is not 16-byte aligned or cannot hold the entry frame, which used to overflow a subtraction, and a file cut inside the TLS data-directory entry no longer panics the parser. `TlsError` gains four variants for these cases. Twelve unit tests in `crates/loader/src/tls.rs` use original headers and code, and also check the argument registers, the stack pointer at entry and after return, callback order and the instruction budget. Expectations come from Microsoft's public PE Format and x64 calling convention pages; nothing ran on Windows, and independent review is pending.
|
||||
- Fixed the thread's TLS pointer naming the TLS data itself (#76). Compiled code loads the pointer from the thread environment block, indexes it by the module's TLS index to get the address of the data block, and then adds a variable's offset; the loader had mapped the data where the pointer array belongs, so the first eight bytes of the template were used as the block address. `setup_tls` now maps a pointer array at the thread's TLS base and the data block one page above it, and stores the block address in the slot of the index it assigns. `crates/loader/tests/tls_layout.rs` follows that access sequence through guest memory for a template with zero fill, a rebased image and a zero-fill-only directory. The data block of the fixture harness can now be at most 60 KiB, down from 64 KiB, before it would meet the thread environment block. Alignment requests above 4 KiB and more than one module's TLS are not handled. The access sequence follows Microsoft's public PE Format page; nothing ran on Windows, and independent review is pending.
|
||||
|
||||
Generated
+1
@@ -166,6 +166,7 @@ dependencies = [
|
||||
name = "xenora-benchmarks"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-isa",
|
||||
"xenora-metal",
|
||||
"xenora-ref",
|
||||
"xenora-shader",
|
||||
|
||||
@@ -17,3 +17,10 @@ path = "src/main.rs"
|
||||
xenora-shader = { path = "../crates/shader" }
|
||||
xenora-ref = { path = "../crates/ref" }
|
||||
xenora-metal = { path = "../crates/metal" }
|
||||
|
||||
[dev-dependencies]
|
||||
xenora-isa = { path = "../crates/isa" }
|
||||
|
||||
[[bench]]
|
||||
name = "gfx1030_identify"
|
||||
harness = false
|
||||
@@ -0,0 +1,16 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original gfx1030 Wave32 instruction stream for metadata identification.
|
||||
s_mov_b32 s12, 0x89abcdef
|
||||
v_add_f32_e32 v4, v5, v9
|
||||
s_cmp_lt_u32 s12, s13
|
||||
ds_read_b32 v8, v2 offset:12
|
||||
v_mov_b32_dpp v9, v6 quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf
|
||||
s_add_u32 s16, s17, s18
|
||||
buffer_store_dword v7, off, s[4:7], 0
|
||||
v_fma_f32 v5, v8, v10, 0x3f800003
|
||||
s_movk_i32 s19, 0x2345
|
||||
global_load_dword v3, v[10:11], off
|
||||
v_cmp_lt_u32_e32 vcc_lo, v3, v7
|
||||
s_load_dword s20, s[22:23], 0x20
|
||||
v_pk_add_f16 v3, v4, v6
|
||||
s_waitcnt vmcnt(0)
|
||||
@@ -0,0 +1,143 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! CPU-only gfx1030 metadata benchmark.
|
||||
//!
|
||||
//! Run `cargo bench --locked -p xenora-benchmarks --bench gfx1030_identify`
|
||||
//! from the repository root. Repeat the command to collect independent
|
||||
//! first-pass samples. The first pass is the first identification in a fresh
|
||||
//! process with the input already in memory. It does not measure process
|
||||
//! startup or guarantee cold hardware caches. Repeated passes use the same
|
||||
//! stream after the untimed correctness check.
|
||||
//!
|
||||
//! To verify the fixture bytes and instruction lengths independently, run:
|
||||
//! ```sh
|
||||
//! llvm-mc -triple=amdgcn-amd-amdhsa -mcpu=gfx1030 -mattr=+wavefrontsize32 \
|
||||
//! -show-encoding benchmarks/benches/fixtures/gfx1030_mixed.s
|
||||
//! ```
|
||||
|
||||
use std::hint::black_box;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use xenora_isa::meta::{EncodingFamily, Identified, identify};
|
||||
|
||||
const COPIES: usize = 4096;
|
||||
const WARM_PASSES: usize = 9;
|
||||
|
||||
// Encodings and lengths come from llvm-mc, one row per instruction in
|
||||
// fixtures/gfx1030_mixed.s. Each word is stored in little-endian order.
|
||||
const FIXTURE: &[(&str, EncodingFamily, &[u32])] = {
|
||||
use EncodingFamily::*;
|
||||
&[
|
||||
("S_MOV_B32", Sop1, &[0xbe8c03ff, 0x89abcdef]),
|
||||
("V_ADD_F32", Vop2, &[0x06081305]),
|
||||
("S_CMP_LT_U32", Sopc, &[0xbf0a0d0c]),
|
||||
("DS_READ_B32", Ds, &[0xd8d8000c, 0x08000002]),
|
||||
("V_MOV_B32", Vop1, &[0x7e1202fa, 0xff004e06]),
|
||||
("S_ADD_U32", Sop2, &[0x80101211]),
|
||||
("BUFFER_STORE_DWORD", Mubuf, &[0xe0700000, 0x80010700]),
|
||||
("V_FMA_F32", Vop3, &[0xd54b0005, 0x03fe1508, 0x3f800003]),
|
||||
("S_MOVK_I32", Sopk, &[0xb0132345]),
|
||||
("GLOBAL_LOAD_DWORD", Global, &[0xdc308000, 0x037d000a]),
|
||||
("V_CMP_LT_U32", Vopc, &[0x7d820f03]),
|
||||
("S_LOAD_DWORD", Smem, &[0xf400050b, 0xfa000020]),
|
||||
("V_PK_ADD_F16", Vop3p, &[0xcc0f4003, 0x1a020d04]),
|
||||
("S_WAITCNT", Sopp, &[0xbf8c3f70]),
|
||||
]
|
||||
};
|
||||
|
||||
fn walk(stream: &[u8], mut observe: impl FnMut(usize, Identified)) -> usize {
|
||||
let mut offset = 0;
|
||||
let mut count = 0;
|
||||
while offset < stream.len() {
|
||||
let identified = identify(&stream[offset..])
|
||||
.unwrap_or_else(|error| panic!("identification failed at byte {offset}: {error}"));
|
||||
observe(offset, identified);
|
||||
offset += identified.len;
|
||||
count += 1;
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
fn verify(stream: &[u8]) {
|
||||
let mut expected_offset = 0;
|
||||
let mut expected = FIXTURE.iter().cycle();
|
||||
let count = walk(stream, |offset, identified| {
|
||||
let &(name, family, words) = expected.next().expect("fixture is nonempty");
|
||||
let len = std::mem::size_of_val(words);
|
||||
assert_eq!(offset, expected_offset, "byte boundary for {name}");
|
||||
assert_eq!(identified.len, len, "length of {name} at byte {offset}");
|
||||
assert_eq!(identified.form.name, name, "mnemonic at byte {offset}");
|
||||
assert_eq!(identified.form.family, family, "family at byte {offset}");
|
||||
expected_offset += len;
|
||||
});
|
||||
assert_eq!(expected_offset, stream.len());
|
||||
assert_eq!(count, COPIES * FIXTURE.len());
|
||||
}
|
||||
|
||||
fn measure(stream: &[u8]) -> Duration {
|
||||
let start = Instant::now();
|
||||
let count = walk(black_box(stream), |_, identified| {
|
||||
black_box(identified);
|
||||
});
|
||||
let elapsed = start.elapsed();
|
||||
assert_eq!(count, COPIES * FIXTURE.len());
|
||||
elapsed
|
||||
}
|
||||
|
||||
fn report(label: &str, elapsed: Duration, byte_count: usize) {
|
||||
let seconds = elapsed.as_secs_f64();
|
||||
let count = (COPIES * FIXTURE.len()) as f64;
|
||||
println!(
|
||||
"{label}: {:.3} ms, {:.2} ns/instruction, {:.2} MiB/s",
|
||||
seconds * 1e3,
|
||||
seconds * 1e9 / count,
|
||||
byte_count as f64 / (1024.0 * 1024.0) / seconds
|
||||
);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let block: Vec<u8> = FIXTURE
|
||||
.iter()
|
||||
.flat_map(|(_, _, words)| words.iter().flat_map(|word| word.to_le_bytes()))
|
||||
.collect();
|
||||
let stream = block.repeat(COPIES);
|
||||
|
||||
// 'cargo test --all-targets' checks the fixture without timing it.
|
||||
if !std::env::args().any(|arg| arg == "--bench") {
|
||||
verify(&stream);
|
||||
return;
|
||||
}
|
||||
|
||||
// Keep the first pass ahead of any metadata lookups. Validate the entire
|
||||
// stream before reporting any timings. That validation also warms the path.
|
||||
let first = measure(&stream);
|
||||
verify(&stream);
|
||||
let mut warm = [Duration::ZERO; WARM_PASSES];
|
||||
for sample in &mut warm {
|
||||
*sample = measure(&stream);
|
||||
}
|
||||
warm.sort_unstable();
|
||||
|
||||
println!(
|
||||
"gfx1030 metadata identification: {} instructions, {} bytes, {} repeated passes",
|
||||
COPIES * FIXTURE.len(),
|
||||
stream.len(),
|
||||
WARM_PASSES
|
||||
);
|
||||
report("First pass in a fresh process", first, stream.len());
|
||||
report("Repeated minimum", warm[0], stream.len());
|
||||
report("Repeated median", warm[WARM_PASSES / 2], stream.len());
|
||||
report("Repeated maximum", warm[WARM_PASSES - 1], stream.len());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn mixed_llvm_fixture_preserves_names_families_lengths_and_boundaries() {
|
||||
let block: Vec<u8> = super::FIXTURE
|
||||
.iter()
|
||||
.flat_map(|(_, _, words)| words.iter().flat_map(|word| word.to_le_bytes()))
|
||||
.collect();
|
||||
super::verify(&block.repeat(super::COPIES));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Exercise the benchmark's LLVM-derived fixture during ordinary workspace tests.
|
||||
#[allow(dead_code)]
|
||||
#[path = "../benches/gfx1030_identify.rs"]
|
||||
mod benchmark;
|
||||
@@ -71,6 +71,13 @@ pub fn get_api_sets_for_canonical(canonical: &str) -> &'static [&'static str] {
|
||||
"api-ms-win-crt-filesystem-l1-1-0.dll",
|
||||
"api-ms-win-crt-locale-l1-1-0.dll",
|
||||
"api-ms-win-crt-environment-l1-1-0.dll",
|
||||
// The API set a program built with the mingw-w64 UCRT runtime
|
||||
// imports `memcpy` and `__C_specific_handler` from. That it
|
||||
// forwards to ucrtbase.dll is inferred from its name and from
|
||||
// Microsoft's "Universal CRT deployment" page, which says the
|
||||
// Universal CRT ships as ucrtbase.dll plus `api-ms-win-*.dll`
|
||||
// forwarders. No document naming this set was found.
|
||||
"api-ms-win-crt-private-l1-1-0.dll",
|
||||
],
|
||||
_ => &[],
|
||||
}
|
||||
|
||||
@@ -5,7 +5,14 @@
|
||||
//! Set `XENORA_DBT_BENCH_JSON=<path>` to also write the results as one JSON
|
||||
//! document (format version 1). The text output does not change. Values the
|
||||
//! benchmark cannot determine, such as the git revision outside a checkout,
|
||||
//! are written as `null`.
|
||||
//! are written as `null`. The benchmark cannot see build settings such as LTO,
|
||||
//! so `XENORA_DBT_BENCH_BUILD_LABEL=<text>` records a label of your choosing
|
||||
//! for them.
|
||||
//!
|
||||
//! Set `XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json>` to compare
|
||||
//! two such documents instead of running the benchmark. The comparison is
|
||||
//! refused, with exit status 1, unless both runs used the same host, workload,
|
||||
//! build settings and sample counts.
|
||||
//!
|
||||
//! The benchmark target disables Cargo's test harness. To run the percentile
|
||||
//! unit tests, build with
|
||||
@@ -154,6 +161,7 @@ struct RunInfo {
|
||||
revision: Option<String>,
|
||||
dirty: Option<bool>,
|
||||
debug_assertions: bool,
|
||||
build_label: Option<String>,
|
||||
guest_code_bytes: usize,
|
||||
warmup: usize,
|
||||
}
|
||||
@@ -187,6 +195,7 @@ fn run_info(guest_code_bytes: usize, warmup: usize) -> RunInfo {
|
||||
dirty: command_output("git", &["status", "--porcelain", "--untracked-files=no"])
|
||||
.map(|status| !status.is_empty()),
|
||||
debug_assertions: cfg!(debug_assertions),
|
||||
build_label: non_empty(std::env::var("XENORA_DBT_BENCH_BUILD_LABEL").ok()),
|
||||
guest_code_bytes,
|
||||
warmup,
|
||||
}
|
||||
@@ -274,7 +283,10 @@ fn json_document(
|
||||
),
|
||||
(
|
||||
"build",
|
||||
json_object(&[("debug_assertions", info.debug_assertions.to_string())]),
|
||||
json_object(&[
|
||||
("debug_assertions", info.debug_assertions.to_string()),
|
||||
("label", json_option(info.build_label.as_ref(), string)),
|
||||
]),
|
||||
),
|
||||
(
|
||||
"workload",
|
||||
@@ -319,7 +331,471 @@ fn json_document(
|
||||
])
|
||||
}
|
||||
|
||||
/// A parsed JSON value. Numbers keep their source text, so integers compare exactly.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Json {
|
||||
Null,
|
||||
Bool(bool),
|
||||
Number(String),
|
||||
String(String),
|
||||
Array(Vec<Json>),
|
||||
Object(Vec<(String, Json)>),
|
||||
}
|
||||
|
||||
impl Json {
|
||||
/// The value at a dotted path such as `host.cpu`, if every step is an object key.
|
||||
fn get(&self, path: &str) -> Option<&Json> {
|
||||
path.split('.').try_fold(self, |value, key| match value {
|
||||
Json::Object(fields) => fields.iter().find(|(k, _)| k == key).map(|(_, v)| v),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_JSON_DEPTH: usize = 32;
|
||||
|
||||
/// Reads one JSON document (RFC 8259) and rejects anything after it.
|
||||
fn parse_json(text: &str) -> Result<Json, String> {
|
||||
let mut reader = JsonReader {
|
||||
bytes: text.as_bytes(),
|
||||
pos: 0,
|
||||
};
|
||||
let value = reader.value(0)?;
|
||||
reader.skip_whitespace();
|
||||
if reader.pos != reader.bytes.len() {
|
||||
return reader.error("unexpected data after the document");
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
struct JsonReader<'a> {
|
||||
bytes: &'a [u8],
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl JsonReader<'_> {
|
||||
fn error<T>(&self, what: &str) -> Result<T, String> {
|
||||
Err(format!("{what} at byte {}", self.pos))
|
||||
}
|
||||
|
||||
fn peek(&self) -> Option<u8> {
|
||||
self.bytes.get(self.pos).copied()
|
||||
}
|
||||
|
||||
fn skip_whitespace(&mut self) {
|
||||
while matches!(self.peek(), Some(b' ' | b'\t' | b'\n' | b'\r')) {
|
||||
self.pos += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn expect(&mut self, byte: u8) -> Result<(), String> {
|
||||
if self.peek() == Some(byte) {
|
||||
self.pos += 1;
|
||||
Ok(())
|
||||
} else {
|
||||
self.error(&format!("expected '{}'", byte as char))
|
||||
}
|
||||
}
|
||||
|
||||
fn value(&mut self, depth: usize) -> Result<Json, String> {
|
||||
if depth > MAX_JSON_DEPTH {
|
||||
return self.error("nesting too deep");
|
||||
}
|
||||
self.skip_whitespace();
|
||||
match self.peek() {
|
||||
None => self.error("unexpected end of input"),
|
||||
Some(b'n') => self.literal("null", Json::Null),
|
||||
Some(b't') => self.literal("true", Json::Bool(true)),
|
||||
Some(b'f') => self.literal("false", Json::Bool(false)),
|
||||
Some(b'"') => Ok(Json::String(self.string()?)),
|
||||
Some(b'[') => self.array(depth),
|
||||
Some(b'{') => self.object(depth),
|
||||
Some(b'-' | b'0'..=b'9') => self.number(),
|
||||
Some(_) => self.error("unexpected character"),
|
||||
}
|
||||
}
|
||||
|
||||
fn literal(&mut self, word: &str, value: Json) -> Result<Json, String> {
|
||||
if self.bytes[self.pos..].starts_with(word.as_bytes()) {
|
||||
self.pos += word.len();
|
||||
Ok(value)
|
||||
} else {
|
||||
self.error("invalid literal")
|
||||
}
|
||||
}
|
||||
|
||||
fn array(&mut self, depth: usize) -> Result<Json, String> {
|
||||
self.expect(b'[')?;
|
||||
let mut items = Vec::new();
|
||||
self.skip_whitespace();
|
||||
if self.peek() == Some(b']') {
|
||||
self.pos += 1;
|
||||
return Ok(Json::Array(items));
|
||||
}
|
||||
loop {
|
||||
items.push(self.value(depth + 1)?);
|
||||
self.skip_whitespace();
|
||||
match self.peek() {
|
||||
Some(b',') => self.pos += 1,
|
||||
Some(b']') => {
|
||||
self.pos += 1;
|
||||
return Ok(Json::Array(items));
|
||||
}
|
||||
_ => return self.error("expected ',' or ']'"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn object(&mut self, depth: usize) -> Result<Json, String> {
|
||||
self.expect(b'{')?;
|
||||
let mut fields: Vec<(String, Json)> = Vec::new();
|
||||
self.skip_whitespace();
|
||||
if self.peek() == Some(b'}') {
|
||||
self.pos += 1;
|
||||
return Ok(Json::Object(fields));
|
||||
}
|
||||
loop {
|
||||
self.skip_whitespace();
|
||||
let key = self.string()?;
|
||||
if fields.iter().any(|(k, _)| *k == key) {
|
||||
return self.error(&format!("duplicate key `{key}`"));
|
||||
}
|
||||
self.skip_whitespace();
|
||||
self.expect(b':')?;
|
||||
let value = self.value(depth + 1)?;
|
||||
fields.push((key, value));
|
||||
self.skip_whitespace();
|
||||
match self.peek() {
|
||||
Some(b',') => self.pos += 1,
|
||||
Some(b'}') => {
|
||||
self.pos += 1;
|
||||
return Ok(Json::Object(fields));
|
||||
}
|
||||
_ => return self.error("expected ',' or '}'"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn digits(&mut self) -> usize {
|
||||
let start = self.pos;
|
||||
while matches!(self.peek(), Some(b'0'..=b'9')) {
|
||||
self.pos += 1;
|
||||
}
|
||||
self.pos - start
|
||||
}
|
||||
|
||||
fn number(&mut self) -> Result<Json, String> {
|
||||
let start = self.pos;
|
||||
if self.peek() == Some(b'-') {
|
||||
self.pos += 1;
|
||||
}
|
||||
match self.peek() {
|
||||
Some(b'0') => self.pos += 1,
|
||||
Some(b'1'..=b'9') => {
|
||||
self.digits();
|
||||
}
|
||||
_ => return self.error("invalid number"),
|
||||
}
|
||||
if self.peek() == Some(b'.') {
|
||||
self.pos += 1;
|
||||
if self.digits() == 0 {
|
||||
return self.error("invalid number");
|
||||
}
|
||||
}
|
||||
if matches!(self.peek(), Some(b'e' | b'E')) {
|
||||
self.pos += 1;
|
||||
if matches!(self.peek(), Some(b'+' | b'-')) {
|
||||
self.pos += 1;
|
||||
}
|
||||
if self.digits() == 0 {
|
||||
return self.error("invalid number");
|
||||
}
|
||||
}
|
||||
// Only ASCII digits and signs were consumed.
|
||||
Ok(Json::Number(
|
||||
String::from_utf8_lossy(&self.bytes[start..self.pos]).into_owned(),
|
||||
))
|
||||
}
|
||||
|
||||
fn hex4(&mut self) -> Result<u32, String> {
|
||||
let digits = self.bytes.get(self.pos..self.pos + 4);
|
||||
let value = digits
|
||||
.and_then(|d| std::str::from_utf8(d).ok())
|
||||
.and_then(|d| u32::from_str_radix(d, 16).ok());
|
||||
match value {
|
||||
Some(value) if digits.is_some_and(|d| d.iter().all(u8::is_ascii_hexdigit)) => {
|
||||
self.pos += 4;
|
||||
Ok(value)
|
||||
}
|
||||
_ => self.error("invalid \\u escape"),
|
||||
}
|
||||
}
|
||||
|
||||
fn unicode_escape(&mut self) -> Result<char, String> {
|
||||
let first = self.hex4()?;
|
||||
let code = match first {
|
||||
0xD800..=0xDBFF => {
|
||||
if !self.bytes[self.pos..].starts_with(b"\\u") {
|
||||
return self.error("unpaired surrogate");
|
||||
}
|
||||
self.pos += 2;
|
||||
let second = self.hex4()?;
|
||||
if !(0xDC00..=0xDFFF).contains(&second) {
|
||||
return self.error("unpaired surrogate");
|
||||
}
|
||||
0x10000 + ((first - 0xD800) << 10) + (second - 0xDC00)
|
||||
}
|
||||
0xDC00..=0xDFFF => return self.error("unpaired surrogate"),
|
||||
code => code,
|
||||
};
|
||||
char::from_u32(code).map_or_else(|| self.error("invalid code point"), Ok)
|
||||
}
|
||||
|
||||
fn string(&mut self) -> Result<String, String> {
|
||||
self.expect(b'"')?;
|
||||
let mut out = String::new();
|
||||
loop {
|
||||
// Copy the run up to the next quote, backslash or control byte. Those
|
||||
// are ASCII, so the run never ends inside a multi-byte character.
|
||||
let start = self.pos;
|
||||
while matches!(self.peek(), Some(b) if b != b'"' && b != b'\\' && b >= 0x20) {
|
||||
self.pos += 1;
|
||||
}
|
||||
match std::str::from_utf8(&self.bytes[start..self.pos]) {
|
||||
Ok(run) => out.push_str(run),
|
||||
Err(_) => return self.error("invalid UTF-8"),
|
||||
}
|
||||
match self.peek() {
|
||||
Some(b'"') => {
|
||||
self.pos += 1;
|
||||
return Ok(out);
|
||||
}
|
||||
Some(b'\\') => {
|
||||
self.pos += 1;
|
||||
let escaped = self.peek();
|
||||
self.pos += 1;
|
||||
out.push(match escaped {
|
||||
Some(b'"') => '"',
|
||||
Some(b'\\') => '\\',
|
||||
Some(b'/') => '/',
|
||||
Some(b'b') => '\u{8}',
|
||||
Some(b'f') => '\u{c}',
|
||||
Some(b'n') => '\n',
|
||||
Some(b'r') => '\r',
|
||||
Some(b't') => '\t',
|
||||
Some(b'u') => self.unicode_escape()?,
|
||||
_ => {
|
||||
self.pos -= 1;
|
||||
return self.error("invalid escape");
|
||||
}
|
||||
});
|
||||
}
|
||||
Some(_) => return self.error("control character in string"),
|
||||
None => return self.error("unterminated string"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fields that must be equal for two runs to be compared. A field listed in
|
||||
/// `OPTIONAL_FIELDS` counts as `null` when a document does not have it.
|
||||
const MATCHING_FIELDS: [&str; 15] = [
|
||||
"format_version",
|
||||
"benchmark",
|
||||
"host.cpu",
|
||||
"host.os",
|
||||
"host.arch",
|
||||
"build.debug_assertions",
|
||||
"build.label",
|
||||
"workload.name",
|
||||
"workload.guest_instructions",
|
||||
"workload.guest_code_bytes",
|
||||
"workload.instruction_budget",
|
||||
"workload.warmup_rounds",
|
||||
"timings.interpreter.samples",
|
||||
"timings.cold_dbt.samples",
|
||||
"timings.warm_dbt.samples",
|
||||
];
|
||||
|
||||
/// Older version 1 documents predate the build label.
|
||||
const OPTIONAL_FIELDS: [&str; 1] = ["build.label"];
|
||||
|
||||
/// Host fields that must be known: two unknown CPUs are not the same CPU.
|
||||
const KNOWN_FIELDS: [&str; 3] = ["host.cpu", "host.os", "host.arch"];
|
||||
|
||||
const SERIES: [(&str, &str); 3] = [
|
||||
("interpreter", "Interpreter"),
|
||||
("cold_dbt", "Cold DBT"),
|
||||
("warm_dbt", "Warm DBT"),
|
||||
];
|
||||
|
||||
const COUNTERS: [&str; 8] = [
|
||||
"blocks_compiled",
|
||||
"cache_hits",
|
||||
"cache_misses",
|
||||
"native_bytes_emitted",
|
||||
"dbt_dispatches",
|
||||
"instructions_executed",
|
||||
"interpreter_fallbacks",
|
||||
"service_calls",
|
||||
];
|
||||
|
||||
fn field<'a>(doc: &'a Json, path: &str) -> Result<&'a Json, String> {
|
||||
match doc.get(path) {
|
||||
Some(value) => Ok(value),
|
||||
None if OPTIONAL_FIELDS.contains(&path) => Ok(&Json::Null),
|
||||
None => Err(format!("missing field `{path}`")),
|
||||
}
|
||||
}
|
||||
|
||||
fn integer(doc: &Json, path: &str) -> Result<u128, String> {
|
||||
match field(doc, path)? {
|
||||
Json::Number(text) => text
|
||||
.parse()
|
||||
.map_err(|_| format!("`{path}` is not a non-negative integer")),
|
||||
_ => Err(format!("`{path}` is not a number")),
|
||||
}
|
||||
}
|
||||
|
||||
fn text(doc: &Json, path: &str) -> String {
|
||||
match doc.get(path) {
|
||||
Some(Json::String(value)) => value.clone(),
|
||||
Some(Json::Bool(value)) => value.to_string(),
|
||||
Some(Json::Number(value)) => value.clone(),
|
||||
// The build label is optional, so its absence is not an unknown value.
|
||||
_ if OPTIONAL_FIELDS.contains(&path) => "none".to_owned(),
|
||||
_ => "unknown".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn duration(ns: u128) -> Duration {
|
||||
Duration::from_nanos(u64::try_from(ns).unwrap_or(u64::MAX))
|
||||
}
|
||||
|
||||
fn change(before: u128, after: u128) -> String {
|
||||
if before == 0 {
|
||||
return "n/a".to_owned();
|
||||
}
|
||||
format!(
|
||||
"{:+.2}%",
|
||||
(after as f64 - before as f64) / before as f64 * 100.0
|
||||
)
|
||||
}
|
||||
|
||||
fn source(doc: &Json) -> String {
|
||||
let dirty = match doc.get("source.dirty") {
|
||||
Some(Json::Bool(true)) => " with local changes",
|
||||
Some(Json::Bool(false)) => "",
|
||||
_ => ", local changes unknown",
|
||||
};
|
||||
format!("{}{dirty}", text(doc, "source.revision"))
|
||||
}
|
||||
|
||||
/// Compares two exported documents. Returns the report lines, or why the runs
|
||||
/// cannot be compared.
|
||||
fn compare_documents(baseline: &Json, candidate: &Json) -> Result<Vec<String>, String> {
|
||||
for doc in [baseline, candidate] {
|
||||
if field(doc, "format_version")? != &Json::Number("1".to_owned()) {
|
||||
return Err("only format version 1 is supported".to_owned());
|
||||
}
|
||||
}
|
||||
for path in KNOWN_FIELDS {
|
||||
for (name, doc) in [("baseline", baseline), ("candidate", candidate)] {
|
||||
if field(doc, path)? == &Json::Null {
|
||||
return Err(format!(
|
||||
"`{path}` is unknown in the {name}, so the hosts cannot be shown to match"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
for path in MATCHING_FIELDS {
|
||||
if field(baseline, path)? != field(candidate, path)? {
|
||||
return Err(format!(
|
||||
"`{path}` differs: baseline {}, candidate {}",
|
||||
text(baseline, path),
|
||||
text(candidate, path)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let mut lines = vec![
|
||||
format!("Baseline: {}", source(baseline)),
|
||||
format!("Candidate: {}", source(candidate)),
|
||||
format!(
|
||||
"Host: {}, {} {}; debug assertions {}; build label {}",
|
||||
text(baseline, "host.cpu"),
|
||||
text(baseline, "host.os"),
|
||||
text(baseline, "host.arch"),
|
||||
text(baseline, "build.debug_assertions"),
|
||||
text(baseline, "build.label"),
|
||||
),
|
||||
];
|
||||
if field(baseline, "host.os_version")? != field(candidate, "host.os_version")? {
|
||||
lines.push(format!(
|
||||
"Note: OS version differs: baseline {}, candidate {}",
|
||||
text(baseline, "host.os_version"),
|
||||
text(candidate, "host.os_version")
|
||||
));
|
||||
}
|
||||
for (key, label) in SERIES {
|
||||
let path = |stat: &str| format!("timings.{key}.{stat}");
|
||||
let before = integer(baseline, &path("median_ns"))?;
|
||||
let after = integer(candidate, &path("median_ns"))?;
|
||||
let spread = integer(baseline, &path("iqr_ns"))?.max(integer(candidate, &path("iqr_ns"))?);
|
||||
let verdict = if before.abs_diff(after) > spread {
|
||||
"larger than"
|
||||
} else {
|
||||
"within"
|
||||
};
|
||||
lines.push(format!(
|
||||
"{label}: median {:?} -> {:?} ({}), {verdict} the larger IQR {:?}",
|
||||
duration(before),
|
||||
duration(after),
|
||||
change(before, after),
|
||||
duration(spread)
|
||||
));
|
||||
}
|
||||
let mut counters_changed = false;
|
||||
for counter in COUNTERS {
|
||||
let path = format!("cold_dbt_metrics.{counter}");
|
||||
let (before, after) = (integer(baseline, &path)?, integer(candidate, &path)?);
|
||||
if before != after {
|
||||
counters_changed = true;
|
||||
lines.push(format!(
|
||||
"Cold DBT {counter}: {before} -> {after} ({})",
|
||||
change(before, after)
|
||||
));
|
||||
}
|
||||
}
|
||||
if !counters_changed {
|
||||
lines.push("Cold DBT counters are identical".to_owned());
|
||||
}
|
||||
Ok(lines)
|
||||
}
|
||||
|
||||
fn compare_files(spec: &str) -> Result<Vec<String>, String> {
|
||||
let (baseline, candidate) = spec
|
||||
.split_once(',')
|
||||
.ok_or("expected <baseline.json>,<candidate.json>")?;
|
||||
let read = |path: &str| {
|
||||
let text = std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?;
|
||||
parse_json(&text).map_err(|e| format!("{path}: {e}"))
|
||||
};
|
||||
compare_documents(&read(baseline)?, &read(candidate)?)
|
||||
}
|
||||
|
||||
fn main() {
|
||||
if let Ok(spec) = std::env::var("XENORA_DBT_BENCH_COMPARE") {
|
||||
match compare_files(&spec) {
|
||||
Ok(lines) => lines.iter().for_each(|line| println!("{line}")),
|
||||
Err(reason) => {
|
||||
eprintln!("dbt_bench: cannot compare: {reason}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let sample_count = std::env::var("XENORA_DBT_BENCH_SAMPLES")
|
||||
.map_or(101, |value| value.parse::<usize>().expect("sample count"));
|
||||
assert!(sample_count > 0);
|
||||
@@ -494,6 +970,7 @@ mod tests {
|
||||
revision: Some("0123abcd".to_owned()),
|
||||
dirty: Some(false),
|
||||
debug_assertions: false,
|
||||
build_label: Some("fat-lto".to_owned()),
|
||||
guest_code_bytes: 40_011,
|
||||
warmup: 10,
|
||||
}
|
||||
@@ -528,7 +1005,7 @@ mod tests {
|
||||
r#"{{"format_version":1,"benchmark":"dbt_bench","unix_time":1700000000,"#,
|
||||
r#""host":{{"cpu":"Test \"CPU\"\\1","os":"macos","os_version":null,"arch":"aarch64"}},"#,
|
||||
r#""source":{{"revision":"0123abcd","dirty":false}},"#,
|
||||
r#""build":{{"debug_assertions":false}},"#,
|
||||
r#""build":{{"debug_assertions":false,"label":"fat-lto"}},"#,
|
||||
r#""workload":{{"name":"add_rax_chain","guest_instructions":{},"guest_code_bytes":40011,"instruction_budget":20000,"warmup_rounds":10}},"#,
|
||||
r#""timings":{{"interpreter":{},"cold_dbt":{},"warm_dbt":{}}},"#,
|
||||
r#""cold_dbt_metrics":{{"blocks_compiled":626,"cache_hits":0,"cache_misses":626,"native_bytes_emitted":245168,"dbt_dispatches":626,"instructions_executed":10002,"interpreter_fallbacks":1,"service_calls":0}}}}"#,
|
||||
@@ -580,4 +1057,302 @@ mod tests {
|
||||
assert_eq!(s.iqr, Duration::from_micros(30));
|
||||
assert_eq!(s.mips, INSTRUCTIONS as f64 / 25e-6 / 1e6);
|
||||
}
|
||||
|
||||
// `cargo bench` builds this target with `--cfg test` but without `--test`,
|
||||
// so this module is compiled with its #[test] functions removed and shared
|
||||
// helpers look unused there.
|
||||
#[allow(dead_code)]
|
||||
fn comparable_document() -> super::Json {
|
||||
super::parse_json(concat!(
|
||||
r#"{"format_version":1,"benchmark":"dbt_bench","unix_time":1,"#,
|
||||
r#""host":{"cpu":"Apple M5","os":"macos","os_version":"27.2.1","arch":"aarch64"},"#,
|
||||
r#""source":{"revision":"aaaa","dirty":false},"#,
|
||||
r#""build":{"debug_assertions":false,"label":null},"#,
|
||||
r#""workload":{"name":"add_rax_chain","guest_instructions":10002,"guest_code_bytes":40011,"instruction_budget":20000,"warmup_rounds":10},"#,
|
||||
r#""timings":{"#,
|
||||
r#""interpreter":{"samples":101,"median_ns":900000,"min_ns":1,"max_ns":2,"p95_ns":1,"p99_ns":1,"iqr_ns":20000,"median_mips":11.1},"#,
|
||||
r#""cold_dbt":{"samples":101,"median_ns":1100000,"min_ns":1,"max_ns":2,"p95_ns":1,"p99_ns":1,"iqr_ns":40000,"median_mips":9.1},"#,
|
||||
r#""warm_dbt":{"samples":101,"median_ns":22000,"min_ns":1,"max_ns":2,"p95_ns":1,"p99_ns":1,"iqr_ns":500,"median_mips":454.6}},"#,
|
||||
r#""cold_dbt_metrics":{"blocks_compiled":626,"cache_hits":0,"cache_misses":626,"native_bytes_emitted":245168,"dbt_dispatches":626,"instructions_executed":10002,"interpreter_fallbacks":0,"service_calls":0}}"#,
|
||||
))
|
||||
.expect("fixture parses")
|
||||
}
|
||||
|
||||
/// Replaces the value at a dotted path, which must exist except for its last key.
|
||||
#[allow(dead_code)]
|
||||
fn set(doc: &mut super::Json, path: &str, value: super::Json) {
|
||||
let (parent, key) = path.rsplit_once('.').map_or(("", path), |(p, k)| (p, k));
|
||||
let mut node = doc;
|
||||
for step in parent.split('.').filter(|s| !s.is_empty()) {
|
||||
let super::Json::Object(fields) = node else {
|
||||
panic!("{step} is not in an object")
|
||||
};
|
||||
node = &mut fields.iter_mut().find(|(k, _)| k == step).expect(step).1;
|
||||
}
|
||||
let super::Json::Object(fields) = node else {
|
||||
panic!("{path} has no parent object")
|
||||
};
|
||||
match fields.iter_mut().find(|(k, _)| k == key) {
|
||||
Some(entry) => entry.1 = value,
|
||||
None => fields.push((key.to_owned(), value)),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reader_accepts_json_values() {
|
||||
use super::{Json, parse_json};
|
||||
|
||||
let doc = parse_json(
|
||||
r#" { "a" : [1, -0.5, 2e3, 3E-2, true, false, null, {}, []], "s": "q\"b\\s\/n\n\té😀 Zażółć" } "#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
doc.get("a"),
|
||||
Some(&Json::Array(vec![
|
||||
Json::Number("1".to_owned()),
|
||||
Json::Number("-0.5".to_owned()),
|
||||
Json::Number("2e3".to_owned()),
|
||||
Json::Number("3E-2".to_owned()),
|
||||
Json::Bool(true),
|
||||
Json::Bool(false),
|
||||
Json::Null,
|
||||
Json::Object(vec![]),
|
||||
Json::Array(vec![]),
|
||||
]))
|
||||
);
|
||||
assert_eq!(
|
||||
doc.get("s"),
|
||||
Some(&Json::String("q\"b\\s/n\n\té😀 Zażółć".to_owned()))
|
||||
);
|
||||
assert_eq!(doc.get("a.b"), None);
|
||||
assert_eq!(doc.get("missing"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reader_rejects_malformed_json() {
|
||||
use super::parse_json;
|
||||
|
||||
let deep = "[".repeat(40) + &"]".repeat(40);
|
||||
for bad in [
|
||||
"",
|
||||
"{",
|
||||
r#"{"a":1,}"#,
|
||||
r#"{"a" 1}"#,
|
||||
r#"{"a":1,"a":2}"#,
|
||||
"[1 2]",
|
||||
"01",
|
||||
"1.",
|
||||
"-",
|
||||
"1e",
|
||||
"+1",
|
||||
"tru",
|
||||
r#""open"#,
|
||||
"\"tab\tinside\"",
|
||||
r#""\x""#,
|
||||
r#""\u12g4""#,
|
||||
r#""\u+123""#,
|
||||
r#""\ud83d""#,
|
||||
r#""\ude00""#,
|
||||
r#""\ud83dA""#,
|
||||
"{} {}",
|
||||
deep.as_str(),
|
||||
] {
|
||||
assert!(parse_json(bad).is_err(), "accepted {bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exported_document_reads_back() {
|
||||
use super::{DbtMetrics, Duration, Json, RunInfo, Summary, json_document, parse_json};
|
||||
|
||||
let summary = Summary {
|
||||
samples: 7,
|
||||
median: Duration::from_nanos(1_234_567),
|
||||
min: Duration::from_nanos(1),
|
||||
max: Duration::from_nanos(9),
|
||||
p95: Duration::from_nanos(8),
|
||||
p99: Duration::from_nanos(9),
|
||||
iqr: Duration::from_nanos(3),
|
||||
mips: 8.25,
|
||||
};
|
||||
let info = RunInfo {
|
||||
unix_time: None,
|
||||
cpu: Some("CPU \"x\" \\ \u{1}".to_owned()),
|
||||
os: "macos",
|
||||
os_version: None,
|
||||
arch: "aarch64",
|
||||
revision: None,
|
||||
dirty: Some(true),
|
||||
debug_assertions: true,
|
||||
build_label: Some("é label".to_owned()),
|
||||
guest_code_bytes: 5,
|
||||
warmup: 2,
|
||||
};
|
||||
let metrics = DbtMetrics {
|
||||
native_bytes_emitted: 42,
|
||||
..DbtMetrics::default()
|
||||
};
|
||||
let doc = parse_json(&json_document(
|
||||
&info, &summary, &summary, &summary, &metrics,
|
||||
))
|
||||
.unwrap();
|
||||
let string = |s: &str| Some(Json::String(s.to_owned()));
|
||||
assert_eq!(doc.get("host.cpu").cloned(), string("CPU \"x\" \\ \u{1}"));
|
||||
assert_eq!(doc.get("build.label").cloned(), string("é label"));
|
||||
assert_eq!(doc.get("host.os_version"), Some(&Json::Null));
|
||||
assert_eq!(doc.get("source.dirty"), Some(&Json::Bool(true)));
|
||||
assert_eq!(
|
||||
doc.get("timings.cold_dbt.median_ns"),
|
||||
Some(&Json::Number("1234567".to_owned()))
|
||||
);
|
||||
assert_eq!(
|
||||
doc.get("cold_dbt_metrics.native_bytes_emitted"),
|
||||
Some(&Json::Number("42".to_owned()))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comparison_reports_changes_against_the_spread() {
|
||||
use super::{Json, compare_documents};
|
||||
|
||||
let baseline = comparable_document();
|
||||
let mut candidate = comparable_document();
|
||||
set(
|
||||
&mut candidate,
|
||||
"source.revision",
|
||||
Json::String("bbbb".to_owned()),
|
||||
);
|
||||
set(&mut candidate, "source.dirty", Json::Bool(true));
|
||||
// 900 µs -> 846 µs is 54 µs, beyond the larger IQR of 20 µs.
|
||||
set(
|
||||
&mut candidate,
|
||||
"timings.interpreter.median_ns",
|
||||
Json::Number("846000".to_owned()),
|
||||
);
|
||||
// 1.1 ms -> 1.12 ms is 20 µs, within the larger IQR of 45 µs.
|
||||
set(
|
||||
&mut candidate,
|
||||
"timings.cold_dbt.median_ns",
|
||||
Json::Number("1120000".to_owned()),
|
||||
);
|
||||
set(
|
||||
&mut candidate,
|
||||
"timings.cold_dbt.iqr_ns",
|
||||
Json::Number("45000".to_owned()),
|
||||
);
|
||||
set(
|
||||
&mut candidate,
|
||||
"cold_dbt_metrics.native_bytes_emitted",
|
||||
Json::Number("290184".to_owned()),
|
||||
);
|
||||
set(
|
||||
&mut candidate,
|
||||
"host.os_version",
|
||||
Json::String("27.3".to_owned()),
|
||||
);
|
||||
|
||||
let lines = compare_documents(&baseline, &candidate).unwrap();
|
||||
assert_eq!(
|
||||
lines,
|
||||
[
|
||||
"Baseline: aaaa",
|
||||
"Candidate: bbbb with local changes",
|
||||
"Host: Apple M5, macos aarch64; debug assertions false; build label none",
|
||||
"Note: OS version differs: baseline 27.2.1, candidate 27.3",
|
||||
"Interpreter: median 900µs -> 846µs (-6.00%), larger than the larger IQR 20µs",
|
||||
"Cold DBT: median 1.1ms -> 1.12ms (+1.82%), within the larger IQR 45µs",
|
||||
"Warm DBT: median 22µs -> 22µs (+0.00%), within the larger IQR 500ns",
|
||||
"Cold DBT native_bytes_emitted: 245168 -> 290184 (+18.36%)",
|
||||
]
|
||||
);
|
||||
|
||||
let same = compare_documents(&baseline, &baseline).unwrap();
|
||||
assert_eq!(same.last().unwrap(), "Cold DBT counters are identical");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comparison_rejects_every_mismatching_field() {
|
||||
use super::{Json, compare_documents};
|
||||
|
||||
// Written out independently of MATCHING_FIELDS, so dropping a field
|
||||
// there fails this test.
|
||||
for path in [
|
||||
"format_version",
|
||||
"benchmark",
|
||||
"host.cpu",
|
||||
"host.os",
|
||||
"host.arch",
|
||||
"build.debug_assertions",
|
||||
"build.label",
|
||||
"workload.name",
|
||||
"workload.guest_instructions",
|
||||
"workload.guest_code_bytes",
|
||||
"workload.instruction_budget",
|
||||
"workload.warmup_rounds",
|
||||
"timings.interpreter.samples",
|
||||
"timings.cold_dbt.samples",
|
||||
"timings.warm_dbt.samples",
|
||||
] {
|
||||
let mut candidate = comparable_document();
|
||||
let other = match path {
|
||||
"build.debug_assertions" => Json::Bool(true),
|
||||
"build.label" => Json::String("fat-lto".to_owned()),
|
||||
// A valid but different version is refused as unsupported first.
|
||||
"format_version" => Json::Number("2".to_owned()),
|
||||
p if p.contains("samples")
|
||||
|| p.starts_with("workload.") && p != "workload.name" =>
|
||||
{
|
||||
Json::Number("7".to_owned())
|
||||
}
|
||||
_ => Json::String("other".to_owned()),
|
||||
};
|
||||
set(&mut candidate, path, other);
|
||||
let error = compare_documents(&comparable_document(), &candidate).expect_err(path);
|
||||
assert!(
|
||||
error.contains(path) || path == "format_version" && error.contains("version"),
|
||||
"{path}: {error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comparison_needs_known_hosts_and_matching_labels() {
|
||||
use super::{Json, compare_documents};
|
||||
|
||||
for path in ["host.cpu", "host.os", "host.arch"] {
|
||||
let mut unknown = comparable_document();
|
||||
set(&mut unknown, path, Json::Null);
|
||||
let error = compare_documents(&unknown, &unknown).expect_err(path);
|
||||
assert!(error.contains("unknown in the baseline"), "{error}");
|
||||
}
|
||||
|
||||
// A document written before the label existed counts as having no label.
|
||||
let mut old = comparable_document();
|
||||
let Json::Object(fields) = &mut old else {
|
||||
unreachable!()
|
||||
};
|
||||
let build = &mut fields.iter_mut().find(|(k, _)| k == "build").unwrap().1;
|
||||
let Json::Object(build) = build else {
|
||||
unreachable!()
|
||||
};
|
||||
build.retain(|(k, _)| k != "label");
|
||||
assert!(compare_documents(&old, &comparable_document()).is_ok());
|
||||
|
||||
let mut labelled = comparable_document();
|
||||
set(
|
||||
&mut labelled,
|
||||
"build.label",
|
||||
Json::String("fat-lto".to_owned()),
|
||||
);
|
||||
assert!(compare_documents(&old, &labelled).is_err());
|
||||
assert!(compare_documents(&labelled, &labelled).is_ok());
|
||||
|
||||
let mut missing = comparable_document();
|
||||
let Json::Object(fields) = &mut missing else {
|
||||
unreachable!()
|
||||
};
|
||||
fields.retain(|(k, _)| k != "workload");
|
||||
let error = compare_documents(&comparable_document(), &missing).unwrap_err();
|
||||
assert!(error.contains("missing field `workload.name`"), "{error}");
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,9 @@
|
||||
differs. Never writes.
|
||||
|
||||
Rejects unknown keys and vocabulary, overlapping encodings, digit and plain
|
||||
forms sharing an opcode, operand constraints that contradict each other, LOCK
|
||||
on a form that cannot write memory, and flags declared both written and
|
||||
undefined. Standard library only (Python 3.11+).
|
||||
forms sharing an opcode, operand constraints that contradict each other, a
|
||||
fixed r/m field on a form that could take memory, LOCK on a form that cannot
|
||||
write memory, and flags declared both written and undefined. Standard library only (Python 3.11+).
|
||||
"""
|
||||
|
||||
import sys
|
||||
@@ -27,7 +27,7 @@ RUST = HERE / "src/x86_table.rs"
|
||||
TOP_KEYS = {"schema", "architecture", "documents", "operation", "alu", "form", "group"}
|
||||
OPERATION_KEYS = {"reads", "writes", "undefined", "conditional", "terminator", "faults", "ref"}
|
||||
FORM_KEYS = {"op", "map", "prefix", "opcode", "count", "digit", "enc", "size", "imm", "src",
|
||||
"memory_only", "register_only", "no_rex_b", "unaligned", "lock"}
|
||||
"memory_only", "register_only", "rm", "no_rex_b", "unaligned", "lock"}
|
||||
GROUP_KEYS = {"map", "opcodes", "digits"}
|
||||
FLAGS = ["cf", "zf", "sf", "of", "pf", "af"]
|
||||
MAPS = {"1": "ONE_BYTE", "0f": "TWO_BYTE"}
|
||||
@@ -169,6 +169,13 @@ def load(text):
|
||||
fail(f"{where}: memory_only and register_only contradict")
|
||||
if (form.get("memory_only") or form.get("register_only")) and not modrm:
|
||||
fail(f"{where}: operand restriction without ModRM")
|
||||
form.setdefault("rm", None)
|
||||
if form["rm"] is not None:
|
||||
# bool is an int in Python; `rm = true` is not a field value.
|
||||
if type(form["rm"]) is not int or not 0 <= form["rm"] <= 7:
|
||||
fail(f"{where}: rm must be a ModRM r/m field value 0-7")
|
||||
if not form.get("register_only") or form["digit"] is None:
|
||||
fail(f"{where}: a fixed r/m field needs register_only and a digit")
|
||||
sourced = form["enc"] in XMM_RM or form["enc"] == "xmm_gpr_imm"
|
||||
if sourced != bool(form["src"]) and form["enc"] not in ("reg_rm", "rm"):
|
||||
fail(f"{where}: source size does not match the encoding")
|
||||
@@ -273,6 +280,7 @@ def generate(operations, forms):
|
||||
f"source: {SRCS[form['src']]}, has_modrm: {str(ENCS[form['enc']][1]).lower()}, "
|
||||
f"memory_only: {str(bool(form.get('memory_only'))).lower()}, "
|
||||
f"register_only: {str(bool(form.get('register_only'))).lower()}, "
|
||||
f"fixed_rm: {'None' if form['rm'] is None else 'Some(%d)' % form['rm']}, "
|
||||
f"no_rex_b: {str(bool(form.get('no_rex_b'))).lower()}, "
|
||||
f"unaligned: {str(bool(form.get('unaligned'))).lower()}, "
|
||||
f"lockable: {str(bool(form.get('lock'))).lower()} }},")
|
||||
|
||||
@@ -116,6 +116,58 @@ service kernel32.dll GetSystemTimeAsFileTime(time: out<8>) -> void
|
||||
ref sysinfoapi.h GetSystemTimeAsFileTime
|
||||
test system_time_comes_from_the_injected_clock
|
||||
|
||||
# Standard streams and formatted output for a hosted C program. Output to
|
||||
# stdout and stderr is captured; any other stream, input, floating-point and
|
||||
# wide conversions stop the guest with the runtime-limit fault.
|
||||
|
||||
service ucrtbase.dll __acrt_iob_func(index: u32) -> ptr
|
||||
handler standard_stream
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails stops the guest for an index above 2 or when the streams cannot be allocated
|
||||
ref corecrt_wstdio.h __acrt_iob_func
|
||||
test standard_streams_are_three_stable_file_objects
|
||||
|
||||
service ucrtbase.dll __stdio_common_vfprintf(options: u64, stream: ptr, format: ptr, locale: ptr, arguments: ptr) -> i32
|
||||
handler vfprintf
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails -1 with errno EINVAL for a null stream or format or an invalid format; stops the guest for what is not modelled
|
||||
ref corecrt_stdio_config.h __stdio_common_vfprintf; Microsoft Learn, vfprintf and format specification syntax
|
||||
test formatted_output_reaches_the_captured_standard_streams
|
||||
|
||||
service ucrtbase.dll fwrite(buffer: ptr, size: u64, count: u64, stream: ptr) -> u64
|
||||
handler fwrite
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails 0 with errno EINVAL for a null buffer or stream; stops the guest for a stream other than stdout or stderr
|
||||
ref stdio.h fwrite
|
||||
test fwrite_and_fputs_write_to_the_captured_standard_streams
|
||||
|
||||
service ucrtbase.dll fputs(text: ptr, stream: ptr) -> i32
|
||||
handler fputs
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails EOF with errno EINVAL for a null string or stream; stops the guest for a stream other than stdout or stderr
|
||||
ref stdio.h fputs
|
||||
test fwrite_and_fputs_write_to_the_captured_standard_streams
|
||||
|
||||
service ucrtbase.dll fflush(stream: ptr) -> i32
|
||||
handler fflush
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails stops the guest for a stream that is not a standard stream
|
||||
ref stdio.h fflush
|
||||
test fflush_and_setvbuf_return_their_documented_results
|
||||
|
||||
service ucrtbase.dll setvbuf(stream: ptr, buffer: ptr, mode: i32, size: u64) -> i32
|
||||
handler setvbuf
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails -1 with errno EINVAL for a null stream, an unknown mode or a size outside 2 to INT_MAX; stops the guest for a stream that is not a standard stream
|
||||
ref stdio.h setvbuf
|
||||
test fflush_and_setvbuf_return_their_documented_results
|
||||
|
||||
service kernel32.dll GetLastError() -> u32
|
||||
handler get_last_error
|
||||
status partial
|
||||
@@ -132,6 +184,51 @@ service kernel32.dll SetLastError(code: u32) -> void
|
||||
ref errhandlingapi.h SetLastError
|
||||
test last_error_is_set_by_failures_and_by_the_guest
|
||||
|
||||
# What a hosted C program's startup code hands to `main`. The three pointer
|
||||
# functions and the two initialization functions are listed by Microsoft only
|
||||
# by name; crates/loader/src/services/crt_arguments.rs says what is documented,
|
||||
# inferred and Xenora's choice.
|
||||
|
||||
service ucrtbase.dll __p___argc() -> ptr
|
||||
handler argc_pointer
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails stops the guest when the variable cannot be allocated
|
||||
ref Microsoft Learn, C runtime library reference, __argc, __argv, __wargv
|
||||
test program_arguments_reach_the_guest_as_argc_and_argv
|
||||
|
||||
service ucrtbase.dll __p___argv() -> ptr
|
||||
handler argv_pointer
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails stops the guest when the variable cannot be allocated
|
||||
ref Microsoft Learn, C runtime library reference, __argc, __argv, __wargv
|
||||
test program_arguments_reach_the_guest_as_argc_and_argv
|
||||
|
||||
service ucrtbase.dll __p__environ() -> ptr
|
||||
handler environ_pointer
|
||||
status partial
|
||||
alias api-ms-win-crt-environment-l1-1-0.dll
|
||||
fails stops the guest when the variable cannot be allocated
|
||||
ref Microsoft Learn, C runtime library reference, _environ, _wenviron
|
||||
test the_environment_table_is_empty_and_ends_with_a_null_pointer
|
||||
|
||||
service ucrtbase.dll _configure_narrow_argv(mode: i32) -> i32
|
||||
handler configure_narrow_argv
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails EINVAL for a mode other than 0, 1 or 2; stops the guest when the table cannot be allocated
|
||||
ref corecrt_startup.h _configure_narrow_argv
|
||||
test program_arguments_reach_the_guest_as_argc_and_argv
|
||||
|
||||
service ucrtbase.dll _initialize_narrow_environment() -> i32
|
||||
handler initialize_narrow_environment
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails stops the guest when the table cannot be allocated
|
||||
ref corecrt_startup.h _initialize_narrow_environment
|
||||
test the_environment_table_is_empty_and_ends_with_a_null_pointer
|
||||
|
||||
service kernel32.dll VirtualAlloc(address: ptr, size: u64, kind: u32, protect: u32) -> ptr
|
||||
handler virtual_alloc
|
||||
status partial
|
||||
@@ -148,6 +245,34 @@ service kernel32.dll VirtualFree(address: ptr, size: u64, kind: u32) -> bool32
|
||||
ref memoryapi.h VirtualFree
|
||||
test virtual_memory_is_mapped_released_and_bounded
|
||||
|
||||
# Stubs. A program built with the mingw-w64 runtime imports these three and
|
||||
# does not call them on a normal run. They exist so that its imports bind. A
|
||||
# call stops the guest with the runtime-limit fault and changes nothing.
|
||||
|
||||
service kernel32.dll VirtualProtect(address: ptr, size: u64, protect: u32, old: out<4>) -> bool32
|
||||
handler virtual_protect
|
||||
status stub
|
||||
alias api-ms-win-core-memory-l1-1-0.dll
|
||||
fails always: stops the guest with the runtime-limit fault; no protection changes
|
||||
ref memoryapi.h VirtualProtect
|
||||
test memory_and_exception_stubs_stop_the_guest_and_change_nothing
|
||||
|
||||
service kernel32.dll VirtualQuery(address: ptr, information: out<48>, length: u64) -> u64
|
||||
handler virtual_query
|
||||
status stub
|
||||
alias api-ms-win-core-memory-l1-1-0.dll
|
||||
fails always: stops the guest with the runtime-limit fault; nothing is written
|
||||
ref memoryapi.h VirtualQuery
|
||||
test memory_and_exception_stubs_stop_the_guest_and_change_nothing
|
||||
|
||||
service ucrtbase.dll __C_specific_handler(record: ptr, frame: ptr, context: ptr, dispatcher: ptr) -> i32
|
||||
handler c_specific_handler
|
||||
status stub
|
||||
alias api-ms-win-crt-private-l1-1-0.dll
|
||||
fails always: stops the guest with the runtime-limit fault; no exception is dispatched
|
||||
ref Microsoft Learn, x64 exception handling, language-specific handler
|
||||
test memory_and_exception_stubs_stop_the_guest_and_change_nothing
|
||||
|
||||
service ucrtbase.dll sqrt(x: f64) -> f64
|
||||
handler sqrt
|
||||
status partial
|
||||
@@ -179,3 +304,78 @@ service ucrtbase.dll fabsf(x: f32) -> f32
|
||||
fails never
|
||||
ref math.h fabsf (ISO C, IEC 60559 abs)
|
||||
test floating_arguments_and_results_use_xmm_registers
|
||||
|
||||
# What a C program's startup code configures before `main`. Each value is
|
||||
# recorded and returned as documented; nothing in the runtime acts on it.
|
||||
|
||||
service ucrtbase.dll _set_app_type(kind: i32) -> void
|
||||
handler set_app_type
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails never
|
||||
ref corecrt_startup.h _set_app_type
|
||||
test crt_app_type_and_math_error_handler_are_recorded
|
||||
|
||||
service ucrtbase.dll _set_new_mode(mode: i32) -> i32
|
||||
handler set_new_mode
|
||||
status partial
|
||||
alias api-ms-win-crt-heap-l1-1-0.dll
|
||||
fails -1 with errno EINVAL for a mode other than 0 or 1
|
||||
ref new.h _set_new_mode
|
||||
test crt_startup_modes_return_the_previous_setting
|
||||
|
||||
service ucrtbase.dll _configthreadlocale(request: i32) -> i32
|
||||
handler configure_thread_locale
|
||||
status partial
|
||||
alias api-ms-win-crt-locale-l1-1-0.dll
|
||||
fails -1 with errno EINVAL for a request other than 0, 1 or 2
|
||||
ref locale.h _configthreadlocale
|
||||
test crt_startup_modes_return_the_previous_setting
|
||||
|
||||
service ucrtbase.dll __setusermatherr(handler: ptr) -> void
|
||||
handler set_user_math_error
|
||||
status partial
|
||||
alias api-ms-win-crt-math-l1-1-0.dll
|
||||
fails never
|
||||
ref corecrt_startup.h __setusermatherr
|
||||
test crt_app_type_and_math_error_handler_are_recorded
|
||||
|
||||
service ucrtbase.dll _set_invalid_parameter_handler(handler: ptr) -> ptr
|
||||
handler set_invalid_parameter_handler
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails never
|
||||
ref stdlib.h _set_invalid_parameter_handler
|
||||
test crt_startup_handlers_return_the_previous_handler
|
||||
|
||||
service ucrtbase.dll __p__fmode() -> ptr
|
||||
handler file_mode_pointer
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails stops the guest when the variable cannot be allocated
|
||||
ref Microsoft Learn, C runtime library reference, __p__fmode
|
||||
test crt_file_mode_variables_are_guest_memory
|
||||
|
||||
service ucrtbase.dll __p__commode() -> ptr
|
||||
handler commit_mode_pointer
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails stops the guest when the variable cannot be allocated
|
||||
ref Microsoft Learn, C runtime library reference, __p__commode
|
||||
test crt_file_mode_variables_are_guest_memory
|
||||
|
||||
service ucrtbase.dll signal(signal: i32, handler: ptr) -> ptr
|
||||
handler signal
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails SIG_ERR with errno EINVAL for a signal the documentation does not list
|
||||
ref signal.h signal
|
||||
test crt_startup_handlers_return_the_previous_handler
|
||||
|
||||
service kernel32.dll SetUnhandledExceptionFilter(filter: ptr) -> ptr
|
||||
handler set_unhandled_exception_filter
|
||||
status partial
|
||||
alias api-ms-win-core-errorhandling-l1-1-0.dll
|
||||
fails never
|
||||
ref errhandlingapi.h SetUnhandledExceptionFilter
|
||||
test crt_startup_handlers_return_the_previous_handler
|
||||
@@ -85,6 +85,36 @@ impl Default for Mxcsr {
|
||||
}
|
||||
}
|
||||
|
||||
/// x87 FPU control, status and tag words.
|
||||
///
|
||||
/// FNINIT is the only instruction that writes them and nothing reads them yet.
|
||||
/// The x87 data registers and every other x87 instruction are not modelled.
|
||||
/// The host's floating-point state is never involved.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct X87State {
|
||||
pub control: u16,
|
||||
pub status: u16,
|
||||
pub tag: u16,
|
||||
}
|
||||
|
||||
impl X87State {
|
||||
/// What FINIT and FNINIT set (Intel SDM Vol. 2A, "FINIT/FNINIT"; Vol. 1,
|
||||
/// 8.1.3 to 8.1.7): every exception masked, 64-bit precision, round to
|
||||
/// nearest; no flag, top of stack 0; every register tagged empty.
|
||||
pub const INIT: Self = Self {
|
||||
control: 0x037F,
|
||||
status: 0,
|
||||
tag: 0xFFFF,
|
||||
};
|
||||
}
|
||||
|
||||
impl Default for X87State {
|
||||
fn default() -> Self {
|
||||
Self::INIT
|
||||
}
|
||||
}
|
||||
|
||||
/// x86-64 CPU state. Native DBT accesses the general registers and RIP by offset.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
@@ -99,6 +129,9 @@ pub struct CpuState {
|
||||
pub mxcsr: Mxcsr,
|
||||
/// Direction flag: string instructions step RSI and RDI down when set.
|
||||
pub df: bool,
|
||||
/// Starts as FNINIT leaves it. The value an operating system gives a new
|
||||
/// thread is not modelled.
|
||||
pub x87: X87State,
|
||||
}
|
||||
|
||||
impl CpuState {
|
||||
@@ -114,6 +147,7 @@ impl CpuState {
|
||||
xmm: [0; 16],
|
||||
mxcsr: Mxcsr::default(),
|
||||
df: false,
|
||||
x87: X87State::INIT,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,6 +164,8 @@ impl CpuState {
|
||||
pub const CPUID_CMOV: u32 = 1 << 15;
|
||||
/// CPUID leaf 1, ECX: POPCNT.
|
||||
pub const CPUID_POPCNT: u32 = 1 << 23;
|
||||
/// CPUID leaf 0x8000_0001, ECX: LAHF and SAHF in 64-bit mode.
|
||||
pub const CPUID_LAHF_SAHF: u32 = 1;
|
||||
/// CPUID leaf 0x8000_0001, ECX: LZCNT.
|
||||
pub const CPUID_LZCNT: u32 = 1 << 5;
|
||||
/// CPUID leaf 0x8000_0001, EDX: 64-bit mode.
|
||||
@@ -150,7 +186,7 @@ pub fn cpuid(leaf: u32, _subleaf: u32) -> [u32; 4] {
|
||||
1 => [0, 0, CPUID_POPCNT, CPUID_CMOV],
|
||||
// Highest extended leaf.
|
||||
0x8000_0000 => [0x8000_0001, 0, 0, 0],
|
||||
0x8000_0001 => [0, 0, CPUID_LZCNT, CPUID_LONG_MODE],
|
||||
0x8000_0001 => [0, 0, CPUID_LAHF_SAHF | CPUID_LZCNT, CPUID_LONG_MODE],
|
||||
_ => [0; 4],
|
||||
}
|
||||
}
|
||||
@@ -212,7 +248,21 @@ impl std::error::Error for ExitReason {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod layout_tests {
|
||||
use super::{CpuState, RFlags, Register};
|
||||
use super::{CpuState, RFlags, Register, X87State};
|
||||
|
||||
/// Intel SDM Vol. 2A, "FINIT/FNINIT", Operation.
|
||||
#[test]
|
||||
fn a_new_guest_starts_with_the_x87_words_fninit_sets() {
|
||||
let init = X87State {
|
||||
control: 0x037F,
|
||||
status: 0,
|
||||
tag: 0xFFFF,
|
||||
};
|
||||
assert_eq!(X87State::INIT, init);
|
||||
assert_eq!(X87State::default(), init);
|
||||
assert_eq!(CpuState::default().x87, init);
|
||||
assert_eq!(CpuState::new(0x1000, 0x2000).x87, init);
|
||||
}
|
||||
|
||||
/// The native translator addresses guest registers and RIP by raw byte
|
||||
/// offset. Keep these assertions next to the struct so a layout change
|
||||
@@ -483,6 +533,8 @@ impl From<DecodeError<MemoryError>> for ExitReason {
|
||||
match error {
|
||||
DecodeError::Fetch(fault) => Self::MemoryFault(fault),
|
||||
DecodeError::Unsupported(byte) => Self::IllegalInstruction(byte),
|
||||
// Intel SDM Vol. 3A, 7.15: exceeding the 15-byte limit is #GP(0).
|
||||
DecodeError::TooLong => Self::GeneralProtection,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -184,7 +184,9 @@ impl DbtEngine {
|
||||
if block_limit > 1
|
||||
&& matches!(
|
||||
block,
|
||||
Err(ExitReason::IllegalInstruction(_) | ExitReason::MemoryFault(_))
|
||||
Err(ExitReason::IllegalInstruction(_)
|
||||
| ExitReason::MemoryFault(_)
|
||||
| ExitReason::GeneralProtection)
|
||||
)
|
||||
{
|
||||
block = self.get_or_compile_block(cpu.rip, memory, 1);
|
||||
|
||||
@@ -120,10 +120,11 @@ pub enum GraphicsError {
|
||||
/// An index buffer format other than DXGI `R16_UINT` (57) or `R32_UINT` (42).
|
||||
InvalidIndexFormat(u32),
|
||||
/// An indexed draw reads past its index buffer or fetches a vertex,
|
||||
/// after applying the base vertex, outside its vertex buffer.
|
||||
/// after applying the base vertex, outside its vertex buffer, or a flat
|
||||
/// draw reads its vertices outside the vertex buffer.
|
||||
IndexOutOfRange,
|
||||
/// A descriptor heap, view, sampler, root signature or binding outside
|
||||
/// the supported texture-binding subset. Nothing is drawn.
|
||||
/// A descriptor heap, view, sampler, root signature, binding or draw
|
||||
/// outside the supported subset. Nothing is drawn.
|
||||
Unsupported(&'static str),
|
||||
}
|
||||
|
||||
@@ -151,8 +152,8 @@ impl std::fmt::Display for GraphicsError {
|
||||
Self::InvalidIndexFormat(format) => {
|
||||
write!(f, "unsupported index buffer format {format}")
|
||||
}
|
||||
Self::IndexOutOfRange => write!(f, "indexed draw outside its index or vertex buffer"),
|
||||
Self::Unsupported(what) => write!(f, "unsupported texture binding: {what}"),
|
||||
Self::IndexOutOfRange => write!(f, "draw outside its index or vertex buffer"),
|
||||
Self::Unsupported(what) => write!(f, "unsupported graphics operation: {what}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1673,9 +1674,22 @@ impl GraphicsContext {
|
||||
rendered_output = Some(pixels);
|
||||
continue;
|
||||
}
|
||||
if *vertex_count_per_instance < 3 {
|
||||
// Zero instances, or fewer vertices than one triangle,
|
||||
// draw nothing. The flat path draws only the first
|
||||
// triangle of the view, once; anything else is rejected
|
||||
// rather than drawn as a different triangle.
|
||||
if *vertex_count_per_instance < 3 || *instance_count == 0 {
|
||||
continue;
|
||||
}
|
||||
if *vertex_count_per_instance != 3
|
||||
|| *instance_count != 1
|
||||
|| *start_vertex_location != 0
|
||||
|| *start_instance_location != 0
|
||||
{
|
||||
return Err(GraphicsError::Unsupported(
|
||||
"flat draw other than one instance of the view's first three vertices",
|
||||
));
|
||||
}
|
||||
draw_count += 1;
|
||||
let v_res_handle =
|
||||
vertex_resource.ok_or(GraphicsError::InvalidResourceHandle)?;
|
||||
@@ -1684,15 +1698,10 @@ impl GraphicsContext {
|
||||
.get(&v_res_handle)
|
||||
.ok_or(GraphicsError::InvalidResourceHandle)?;
|
||||
|
||||
// Read vertices from guest memory backing or resource data
|
||||
let mut raw_vtx = [0u8; 48]; // 3 * 4 * float32
|
||||
if let Some(guest_addr) = v_res.guest_backing_addr {
|
||||
memory.read_bytes(guest_addr + vertex_offset as u64, &mut raw_vtx)?;
|
||||
} else if v_res.data.len() >= vertex_offset + 48 {
|
||||
raw_vtx.copy_from_slice(&v_res.data[vertex_offset..vertex_offset + 48]);
|
||||
} else {
|
||||
return Err(GraphicsError::InvalidDescriptor);
|
||||
}
|
||||
// Three float4 positions, inside the resource whether it
|
||||
// is backed by guest memory or by its own bytes.
|
||||
let mut raw_vtx = [0u8; 48];
|
||||
Self::read_resource(v_res, memory, vertex_offset, &mut raw_vtx)?;
|
||||
|
||||
let mut vertices = [[0.0f32; 4]; 3];
|
||||
for (i, row) in vertices.iter_mut().enumerate() {
|
||||
|
||||
@@ -8,7 +8,7 @@ use crate::runtime::{Call, Parameter, Return, ServiceContext, ServiceMetadata};
|
||||
use crate::services::{ServicesState, handlers};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub static SERVICES: [ServiceMetadata; 20] = [
|
||||
pub static SERVICES: [ServiceMetadata; 43] = [
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "SetProcessPriorityBoost",
|
||||
@@ -141,6 +141,72 @@ pub static SERVICES: [ServiceMetadata; 20] = [
|
||||
reference: "sysinfoapi.h GetSystemTimeAsFileTime",
|
||||
tests: &["system_time_comes_from_the_injected_clock"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "__acrt_iob_func",
|
||||
parameters: &[Parameter { name: "index", kind: "u32" }],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "stops the guest for an index above 2 or when the streams cannot be allocated",
|
||||
reference: "corecrt_wstdio.h __acrt_iob_func",
|
||||
tests: &["standard_streams_are_three_stable_file_objects"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "__stdio_common_vfprintf",
|
||||
parameters: &[Parameter { name: "options", kind: "u64" }, Parameter { name: "stream", kind: "ptr" }, Parameter { name: "format", kind: "ptr" }, Parameter { name: "locale", kind: "ptr" }, Parameter { name: "arguments", kind: "ptr" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "-1 with errno EINVAL for a null stream or format or an invalid format; stops the guest for what is not modelled",
|
||||
reference: "corecrt_stdio_config.h __stdio_common_vfprintf; Microsoft Learn, vfprintf and format specification syntax",
|
||||
tests: &["formatted_output_reaches_the_captured_standard_streams"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "fwrite",
|
||||
parameters: &[Parameter { name: "buffer", kind: "ptr" }, Parameter { name: "size", kind: "u64" }, Parameter { name: "count", kind: "u64" }, Parameter { name: "stream", kind: "ptr" }],
|
||||
result: "u64",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "0 with errno EINVAL for a null buffer or stream; stops the guest for a stream other than stdout or stderr",
|
||||
reference: "stdio.h fwrite",
|
||||
tests: &["fwrite_and_fputs_write_to_the_captured_standard_streams"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "fputs",
|
||||
parameters: &[Parameter { name: "text", kind: "ptr" }, Parameter { name: "stream", kind: "ptr" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "EOF with errno EINVAL for a null string or stream; stops the guest for a stream other than stdout or stderr",
|
||||
reference: "stdio.h fputs",
|
||||
tests: &["fwrite_and_fputs_write_to_the_captured_standard_streams"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "fflush",
|
||||
parameters: &[Parameter { name: "stream", kind: "ptr" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "stops the guest for a stream that is not a standard stream",
|
||||
reference: "stdio.h fflush",
|
||||
tests: &["fflush_and_setvbuf_return_their_documented_results"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "setvbuf",
|
||||
parameters: &[Parameter { name: "stream", kind: "ptr" }, Parameter { name: "buffer", kind: "ptr" }, Parameter { name: "mode", kind: "i32" }, Parameter { name: "size", kind: "u64" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "-1 with errno EINVAL for a null stream, an unknown mode or a size outside 2 to INT_MAX; stops the guest for a stream that is not a standard stream",
|
||||
reference: "stdio.h setvbuf",
|
||||
tests: &["fflush_and_setvbuf_return_their_documented_results"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "GetLastError",
|
||||
@@ -163,6 +229,61 @@ pub static SERVICES: [ServiceMetadata; 20] = [
|
||||
reference: "errhandlingapi.h SetLastError",
|
||||
tests: &["last_error_is_set_by_failures_and_by_the_guest"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "__p___argc",
|
||||
parameters: &[],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
|
||||
failure: "stops the guest when the variable cannot be allocated",
|
||||
reference: "Microsoft Learn, C runtime library reference, __argc, __argv, __wargv",
|
||||
tests: &["program_arguments_reach_the_guest_as_argc_and_argv"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "__p___argv",
|
||||
parameters: &[],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
|
||||
failure: "stops the guest when the variable cannot be allocated",
|
||||
reference: "Microsoft Learn, C runtime library reference, __argc, __argv, __wargv",
|
||||
tests: &["program_arguments_reach_the_guest_as_argc_and_argv"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "__p__environ",
|
||||
parameters: &[],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-environment-l1-1-0.dll"],
|
||||
failure: "stops the guest when the variable cannot be allocated",
|
||||
reference: "Microsoft Learn, C runtime library reference, _environ, _wenviron",
|
||||
tests: &["the_environment_table_is_empty_and_ends_with_a_null_pointer"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "_configure_narrow_argv",
|
||||
parameters: &[Parameter { name: "mode", kind: "i32" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
|
||||
failure: "EINVAL for a mode other than 0, 1 or 2; stops the guest when the table cannot be allocated",
|
||||
reference: "corecrt_startup.h _configure_narrow_argv",
|
||||
tests: &["program_arguments_reach_the_guest_as_argc_and_argv"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "_initialize_narrow_environment",
|
||||
parameters: &[],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
|
||||
failure: "stops the guest when the table cannot be allocated",
|
||||
reference: "corecrt_startup.h _initialize_narrow_environment",
|
||||
tests: &["the_environment_table_is_empty_and_ends_with_a_null_pointer"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "VirtualAlloc",
|
||||
@@ -185,6 +306,39 @@ pub static SERVICES: [ServiceMetadata; 20] = [
|
||||
reference: "memoryapi.h VirtualFree",
|
||||
tests: &["virtual_memory_is_mapped_released_and_bounded"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "VirtualProtect",
|
||||
parameters: &[Parameter { name: "address", kind: "ptr" }, Parameter { name: "size", kind: "u64" }, Parameter { name: "protect", kind: "u32" }, Parameter { name: "old", kind: "out<4>" }],
|
||||
result: "bool32",
|
||||
status: ServiceStatus::Stub,
|
||||
aliases: &["api-ms-win-core-memory-l1-1-0.dll"],
|
||||
failure: "always: stops the guest with the runtime-limit fault; no protection changes",
|
||||
reference: "memoryapi.h VirtualProtect",
|
||||
tests: &["memory_and_exception_stubs_stop_the_guest_and_change_nothing"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "VirtualQuery",
|
||||
parameters: &[Parameter { name: "address", kind: "ptr" }, Parameter { name: "information", kind: "out<48>" }, Parameter { name: "length", kind: "u64" }],
|
||||
result: "u64",
|
||||
status: ServiceStatus::Stub,
|
||||
aliases: &["api-ms-win-core-memory-l1-1-0.dll"],
|
||||
failure: "always: stops the guest with the runtime-limit fault; nothing is written",
|
||||
reference: "memoryapi.h VirtualQuery",
|
||||
tests: &["memory_and_exception_stubs_stop_the_guest_and_change_nothing"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "__C_specific_handler",
|
||||
parameters: &[Parameter { name: "record", kind: "ptr" }, Parameter { name: "frame", kind: "ptr" }, Parameter { name: "context", kind: "ptr" }, Parameter { name: "dispatcher", kind: "ptr" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Stub,
|
||||
aliases: &["api-ms-win-crt-private-l1-1-0.dll"],
|
||||
failure: "always: stops the guest with the runtime-limit fault; no exception is dispatched",
|
||||
reference: "Microsoft Learn, x64 exception handling, language-specific handler",
|
||||
tests: &["memory_and_exception_stubs_stop_the_guest_and_change_nothing"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "sqrt",
|
||||
@@ -229,6 +383,105 @@ pub static SERVICES: [ServiceMetadata; 20] = [
|
||||
reference: "math.h fabsf (ISO C, IEC 60559 abs)",
|
||||
tests: &["floating_arguments_and_results_use_xmm_registers"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "_set_app_type",
|
||||
parameters: &[Parameter { name: "kind", kind: "i32" }],
|
||||
result: "void",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
|
||||
failure: "never",
|
||||
reference: "corecrt_startup.h _set_app_type",
|
||||
tests: &["crt_app_type_and_math_error_handler_are_recorded"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "_set_new_mode",
|
||||
parameters: &[Parameter { name: "mode", kind: "i32" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-heap-l1-1-0.dll"],
|
||||
failure: "-1 with errno EINVAL for a mode other than 0 or 1",
|
||||
reference: "new.h _set_new_mode",
|
||||
tests: &["crt_startup_modes_return_the_previous_setting"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "_configthreadlocale",
|
||||
parameters: &[Parameter { name: "request", kind: "i32" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-locale-l1-1-0.dll"],
|
||||
failure: "-1 with errno EINVAL for a request other than 0, 1 or 2",
|
||||
reference: "locale.h _configthreadlocale",
|
||||
tests: &["crt_startup_modes_return_the_previous_setting"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "__setusermatherr",
|
||||
parameters: &[Parameter { name: "handler", kind: "ptr" }],
|
||||
result: "void",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-math-l1-1-0.dll"],
|
||||
failure: "never",
|
||||
reference: "corecrt_startup.h __setusermatherr",
|
||||
tests: &["crt_app_type_and_math_error_handler_are_recorded"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "_set_invalid_parameter_handler",
|
||||
parameters: &[Parameter { name: "handler", kind: "ptr" }],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
|
||||
failure: "never",
|
||||
reference: "stdlib.h _set_invalid_parameter_handler",
|
||||
tests: &["crt_startup_handlers_return_the_previous_handler"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "__p__fmode",
|
||||
parameters: &[],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "stops the guest when the variable cannot be allocated",
|
||||
reference: "Microsoft Learn, C runtime library reference, __p__fmode",
|
||||
tests: &["crt_file_mode_variables_are_guest_memory"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "__p__commode",
|
||||
parameters: &[],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "stops the guest when the variable cannot be allocated",
|
||||
reference: "Microsoft Learn, C runtime library reference, __p__commode",
|
||||
tests: &["crt_file_mode_variables_are_guest_memory"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "signal",
|
||||
parameters: &[Parameter { name: "signal", kind: "i32" }, Parameter { name: "handler", kind: "ptr" }],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
|
||||
failure: "SIG_ERR with errno EINVAL for a signal the documentation does not list",
|
||||
reference: "signal.h signal",
|
||||
tests: &["crt_startup_handlers_return_the_previous_handler"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "SetUnhandledExceptionFilter",
|
||||
parameters: &[Parameter { name: "filter", kind: "ptr" }],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-core-errorhandling-l1-1-0.dll"],
|
||||
failure: "never",
|
||||
reference: "errhandlingapi.h SetUnhandledExceptionFilter",
|
||||
tests: &["crt_startup_handlers_return_the_previous_handler"],
|
||||
},
|
||||
];
|
||||
|
||||
/// Register every generated service and its API-set aliases.
|
||||
@@ -331,6 +584,65 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
Ok(0)
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "__acrt_iob_func", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u32(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::standard_stream(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "__stdio_common_vfprintf", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let a2 = call.u64(2)?;
|
||||
let a3 = call.u64(3)?;
|
||||
let a4 = call.u64(4)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::vfprintf(&mut context, a0, a1, a2, a3, a4)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "fwrite", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let a2 = call.u64(2)?;
|
||||
let a3 = call.u64(3)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::fwrite(&mut context, a0, a1, a2, a3)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "fputs", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::fputs(&mut context, a0, a1)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "fflush", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::fflush(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "setvbuf", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let a2 = call.i32(2)?;
|
||||
let a3 = call.u64(3)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::setvbuf(&mut context, a0, a1, a2, a3)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "GetLastError", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let _ = args;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
@@ -346,6 +658,42 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
Ok(0)
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "__p___argc", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let _ = args;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::argc_pointer(&mut context)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "__p___argv", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let _ = args;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::argv_pointer(&mut context)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "__p__environ", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let _ = args;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::environ_pointer(&mut context)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "_configure_narrow_argv", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.i32(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::configure_narrow_argv(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "_initialize_narrow_environment", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let _ = args;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::initialize_narrow_environment(&mut context)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "VirtualAlloc", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
@@ -367,6 +715,38 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "VirtualProtect", ServiceStatus::Stub, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let a2 = call.u32(2)?;
|
||||
let a3 = call.out::<4>(3)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: bool = handlers::virtual_protect(&mut context, a0, a1, a2, a3)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "VirtualQuery", ServiceStatus::Stub, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.out::<48>(1)?;
|
||||
let a2 = call.u64(2)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::virtual_query(&mut context, a0, a1, a2)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "__C_specific_handler", ServiceStatus::Stub, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let a2 = call.u64(2)?;
|
||||
let a3 = call.u64(3)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::c_specific_handler(&mut context, a0, a1, a2, a3)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "sqrt", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.f64(0)?;
|
||||
@@ -398,6 +778,77 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let result: crate::runtime::Float32 = handlers::fabsf(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "_set_app_type", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.i32(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let () = handlers::set_app_type(&mut context, a0)?;
|
||||
Ok(0)
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "_set_new_mode", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.i32(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::set_new_mode(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "_configthreadlocale", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.i32(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::configure_thread_locale(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "__setusermatherr", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let () = handlers::set_user_math_error(&mut context, a0)?;
|
||||
Ok(0)
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "_set_invalid_parameter_handler", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::set_invalid_parameter_handler(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "__p__fmode", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let _ = args;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::file_mode_pointer(&mut context)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "__p__commode", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let _ = args;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::commit_mode_pointer(&mut context)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "signal", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.i32(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::signal(&mut context, a0, a1)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "SetUnhandledExceptionFilter", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::set_unhandled_exception_filter(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
for service in &SERVICES {
|
||||
for alias in service.aliases {
|
||||
if let Err(error) = registry.try_alias(alias, service.library, service.symbol) {
|
||||
|
||||
@@ -10,7 +10,11 @@
|
||||
//! - Xbox physical memory: `XMemAlloc`, `XMemFree`
|
||||
|
||||
mod crt;
|
||||
mod crt_arguments;
|
||||
mod crt_callbacks;
|
||||
mod crt_format;
|
||||
mod crt_startup;
|
||||
mod crt_streams;
|
||||
mod events;
|
||||
mod files;
|
||||
mod gdk_queue;
|
||||
@@ -25,6 +29,8 @@ pub(crate) mod threads;
|
||||
mod winsock;
|
||||
|
||||
use crate::runtime::HResult;
|
||||
pub use crt_arguments::{MAX_PROGRAM_ARGUMENT_BYTES, ProgramArgumentsError};
|
||||
pub use crt_streams::MAX_CAPTURED_OUTPUT;
|
||||
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
@@ -200,13 +206,16 @@ pub struct ServicesState {
|
||||
pub guest_profile: sysinfo::GuestSystemProfile,
|
||||
objects: Mutex<ObjectState>,
|
||||
last_errors: Mutex<BTreeMap<u64, u32>>,
|
||||
crt_arguments: Mutex<crt_arguments::CrtArguments>,
|
||||
synch: Mutex<synch::Synch>,
|
||||
crt_streams: Mutex<crt_streams::StandardStreams>,
|
||||
pub(crate) threads: Mutex<threads::ThreadTable>,
|
||||
pub(crate) hooks: Arc<threads::SchedulerHooks>,
|
||||
/// Functions registered with `atexit`, run in reverse order by `_cexit`.
|
||||
atexit: Mutex<Vec<u64>>,
|
||||
/// The status the guest process exited with. Set once.
|
||||
exit_status: Mutex<Option<u32>>,
|
||||
crt_startup: Mutex<crt_startup::CrtStartup>,
|
||||
winsock: Mutex<winsock::Winsock>,
|
||||
task_fixture: Mutex<task_fixture::TaskFixture>,
|
||||
platform_fixture: Mutex<platform_fixture::PlatformFixture>,
|
||||
@@ -228,11 +237,14 @@ impl ServicesState {
|
||||
guest_profile: sysinfo::GuestSystemProfile::default(),
|
||||
objects: Mutex::new(ObjectState::default()),
|
||||
last_errors: Mutex::default(),
|
||||
crt_arguments: Mutex::default(),
|
||||
synch: Mutex::default(),
|
||||
crt_streams: Mutex::default(),
|
||||
threads: Mutex::default(),
|
||||
hooks: Arc::default(),
|
||||
atexit: Mutex::default(),
|
||||
exit_status: Mutex::default(),
|
||||
crt_startup: Mutex::default(),
|
||||
winsock: Mutex::default(),
|
||||
task_fixture: Mutex::default(),
|
||||
platform_fixture: Mutex::default(),
|
||||
@@ -243,6 +255,21 @@ impl ServicesState {
|
||||
graphics: Arc::new(Mutex::new(crate::graphics::GraphicsContext::new())),
|
||||
}
|
||||
}
|
||||
/// Give a hosted C program the arguments its `main` receives in `argv`,
|
||||
/// program name first. Call it before running the guest: the C runtime's
|
||||
/// startup code builds `argv` once, and a call after that is refused.
|
||||
///
|
||||
/// The strings reach the guest as their bytes; no code page is applied.
|
||||
/// A host that never calls this gives the program one argument, the empty
|
||||
/// string. An empty slice gives it none.
|
||||
pub fn set_program_arguments(&self, arguments: &[&str]) -> Result<(), ProgramArgumentsError> {
|
||||
self.crt_arguments().supply(arguments)
|
||||
}
|
||||
|
||||
fn crt_arguments(&self) -> std::sync::MutexGuard<'_, crt_arguments::CrtArguments> {
|
||||
self.crt_arguments.lock().expect("program arguments")
|
||||
}
|
||||
|
||||
fn uptime_millis(&self) -> u64 {
|
||||
let ticks = self
|
||||
.clock
|
||||
@@ -326,6 +353,23 @@ impl ServicesState {
|
||||
status
|
||||
}
|
||||
|
||||
/// Everything the guest has written to `stdout`, as the bytes a text-mode
|
||||
/// stream hands the operating system: each line feed the program wrote is
|
||||
/// a carriage return and a line feed here.
|
||||
pub fn standard_output(&self) -> Vec<u8> {
|
||||
self.crt_streams().output().to_vec()
|
||||
}
|
||||
|
||||
/// Everything the guest has written to `stderr`, in the same form as
|
||||
/// [`Self::standard_output`].
|
||||
pub fn standard_error(&self) -> Vec<u8> {
|
||||
self.crt_streams().error().to_vec()
|
||||
}
|
||||
|
||||
fn crt_streams(&self) -> std::sync::MutexGuard<'_, crt_streams::StandardStreams> {
|
||||
self.crt_streams.lock().expect("standard streams")
|
||||
}
|
||||
|
||||
/// Read the last-error value for a guest thread's TEB.
|
||||
pub fn last_error(&self, teb: u64) -> u32 {
|
||||
self.last_errors
|
||||
@@ -360,6 +404,22 @@ impl ServicesState {
|
||||
}
|
||||
}
|
||||
|
||||
fn crt_startup(&self) -> std::sync::MutexGuard<'_, crt_startup::CrtStartup> {
|
||||
self.crt_startup.lock().expect("C runtime startup state")
|
||||
}
|
||||
|
||||
/// The application type the guest passed to `_set_app_type`, zero until it
|
||||
/// does. Nothing in the runtime depends on it.
|
||||
pub fn crt_app_type(&self) -> i32 {
|
||||
self.crt_startup().app_type()
|
||||
}
|
||||
|
||||
/// The guest function passed to `__setusermatherr`, zero until one is. It
|
||||
/// is never called.
|
||||
pub fn crt_user_math_error(&self) -> u64 {
|
||||
self.crt_startup().user_math_error()
|
||||
}
|
||||
|
||||
/// Record a guest error and return the documented failure value.
|
||||
fn fail<T>(&self, teb: u64, error: u32, value: T) -> Result<T, ExitReason> {
|
||||
self.set_last_error(teb, error);
|
||||
@@ -722,6 +782,9 @@ pub(crate) mod handlers {
|
||||
|
||||
type Outcome<T> = Result<T, ExitReason>;
|
||||
|
||||
/// The exit for a request the runtime does not model.
|
||||
const RUNTIME_LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE);
|
||||
|
||||
pub fn set_process_priority_boost(
|
||||
context: &mut ServiceContext<'_>,
|
||||
process: u64,
|
||||
@@ -874,6 +937,83 @@ pub(crate) mod handlers {
|
||||
.map_err(ExitReason::MemoryFault)
|
||||
}
|
||||
|
||||
// Standard streams and formatted output (#400). `crt_streams.rs` holds
|
||||
// the rules; a documented failure sets errno to EINVAL here.
|
||||
|
||||
fn or_einval<T>(
|
||||
context: &mut ServiceContext<'_>,
|
||||
outcome: crt_streams::Outcome<T>,
|
||||
) -> Outcome<T> {
|
||||
match outcome? {
|
||||
Ok(value) => Ok(value),
|
||||
Err(crt_streams::Invalid(value)) => {
|
||||
crt::set_errno(context.memory, context.teb, crt::EINVAL)?;
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn standard_stream(context: &mut ServiceContext<'_>, index: u32) -> Outcome<u64> {
|
||||
context.state.crt_streams().file(context.memory, index)
|
||||
}
|
||||
|
||||
pub fn vfprintf(
|
||||
context: &mut ServiceContext<'_>,
|
||||
options: u64,
|
||||
stream: u64,
|
||||
format: u64,
|
||||
locale: u64,
|
||||
arguments: u64,
|
||||
) -> Outcome<i32> {
|
||||
let outcome = context.state.crt_streams().print(
|
||||
context.memory,
|
||||
options,
|
||||
stream,
|
||||
format,
|
||||
locale,
|
||||
arguments,
|
||||
);
|
||||
or_einval(context, outcome)
|
||||
}
|
||||
|
||||
pub fn fwrite(
|
||||
context: &mut ServiceContext<'_>,
|
||||
buffer: u64,
|
||||
size: u64,
|
||||
count: u64,
|
||||
stream: u64,
|
||||
) -> Outcome<u64> {
|
||||
let outcome =
|
||||
context
|
||||
.state
|
||||
.crt_streams()
|
||||
.write_items(context.memory, buffer, size, count, stream);
|
||||
or_einval(context, outcome)
|
||||
}
|
||||
|
||||
pub fn fputs(context: &mut ServiceContext<'_>, text: u64, stream: u64) -> Outcome<i32> {
|
||||
let outcome = context
|
||||
.state
|
||||
.crt_streams()
|
||||
.put_string(context.memory, text, stream);
|
||||
or_einval(context, outcome)
|
||||
}
|
||||
|
||||
pub fn fflush(context: &mut ServiceContext<'_>, stream: u64) -> Outcome<i32> {
|
||||
context.state.crt_streams().flush(stream)
|
||||
}
|
||||
|
||||
pub fn setvbuf(
|
||||
context: &mut ServiceContext<'_>,
|
||||
stream: u64,
|
||||
_buffer: u64,
|
||||
mode: i32,
|
||||
size: u64,
|
||||
) -> Outcome<i32> {
|
||||
let outcome = context.state.crt_streams().set_buffer(stream, mode, size);
|
||||
or_einval(context, outcome)
|
||||
}
|
||||
|
||||
pub fn get_last_error(context: &mut ServiceContext<'_>) -> Outcome<u32> {
|
||||
Ok(context.state.last_error(context.teb))
|
||||
}
|
||||
@@ -883,6 +1023,38 @@ pub(crate) mod handlers {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// What a hosted C program's startup code hands to `main` (#392).
|
||||
// `crt_arguments.rs` says what is documented, inferred and Xenora's choice.
|
||||
|
||||
pub fn argc_pointer(context: &mut ServiceContext<'_>) -> Outcome<u64> {
|
||||
let mut arguments = context.state.crt_arguments();
|
||||
arguments.address(context.memory, crt_arguments::Variable::Argc)
|
||||
}
|
||||
|
||||
pub fn argv_pointer(context: &mut ServiceContext<'_>) -> Outcome<u64> {
|
||||
let mut arguments = context.state.crt_arguments();
|
||||
arguments.address(context.memory, crt_arguments::Variable::Argv)
|
||||
}
|
||||
|
||||
pub fn environ_pointer(context: &mut ServiceContext<'_>) -> Outcome<u64> {
|
||||
let mut arguments = context.state.crt_arguments();
|
||||
arguments.address(context.memory, crt_arguments::Variable::Environ)
|
||||
}
|
||||
|
||||
pub fn configure_narrow_argv(context: &mut ServiceContext<'_>, mode: i32) -> Outcome<i32> {
|
||||
context
|
||||
.state
|
||||
.crt_arguments()
|
||||
.configure(context.memory, mode)
|
||||
}
|
||||
|
||||
pub fn initialize_narrow_environment(context: &mut ServiceContext<'_>) -> Outcome<i32> {
|
||||
context
|
||||
.state
|
||||
.crt_arguments()
|
||||
.initialize_environment(context.memory)
|
||||
}
|
||||
|
||||
pub fn virtual_alloc(
|
||||
context: &mut ServiceContext<'_>,
|
||||
requested: u64,
|
||||
@@ -946,6 +1118,42 @@ pub(crate) mod handlers {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
// Stubs (#388). A program built with the mingw-w64 runtime imports these
|
||||
// three and does not call them on a normal run: the first two serve its
|
||||
// runtime pseudo-relocations and the third is the language handler Windows
|
||||
// calls while dispatching a structured exception. None is modelled, so a
|
||||
// call stops the guest with the runtime-limit fault. Returning a made-up
|
||||
// result would let the program run on with wrong state.
|
||||
|
||||
pub fn virtual_protect(
|
||||
_: &mut ServiceContext<'_>,
|
||||
_address: u64,
|
||||
_size: u64,
|
||||
_protect: u32,
|
||||
_old: OutPtr<4>,
|
||||
) -> Outcome<bool> {
|
||||
Err(RUNTIME_LIMIT)
|
||||
}
|
||||
|
||||
pub fn virtual_query(
|
||||
_: &mut ServiceContext<'_>,
|
||||
_address: u64,
|
||||
_information: OutPtr<48>,
|
||||
_length: u64,
|
||||
) -> Outcome<u64> {
|
||||
Err(RUNTIME_LIMIT)
|
||||
}
|
||||
|
||||
pub fn c_specific_handler(
|
||||
_: &mut ServiceContext<'_>,
|
||||
_record: u64,
|
||||
_frame: u64,
|
||||
_context: u64,
|
||||
_dispatcher: u64,
|
||||
) -> Outcome<i32> {
|
||||
Err(RUNTIME_LIMIT)
|
||||
}
|
||||
|
||||
/// The guest MXCSR is not visible to a service, so results use the default
|
||||
/// rounding and raise no guest flags; the registry marks them partial.
|
||||
const DEFAULT_MXCSR: u32 = crate::cpu::Mxcsr::RESET;
|
||||
@@ -968,4 +1176,85 @@ pub(crate) mod handlers {
|
||||
pub fn fabsf(_: &mut ServiceContext<'_>, x: Float32) -> Outcome<Float32> {
|
||||
Ok(Float32(x.0 & !(1 << 31)))
|
||||
}
|
||||
|
||||
// What a C program's startup code configures (#382). Each value is
|
||||
// recorded and returned; `crt_startup.rs` says what does not act on it.
|
||||
|
||||
pub fn set_app_type(context: &mut ServiceContext<'_>, kind: i32) -> Outcome<()> {
|
||||
context.state.crt_startup().set_app_type(kind);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_new_mode(context: &mut ServiceContext<'_>, mode: i32) -> Outcome<i32> {
|
||||
let previous = context.state.crt_startup().set_new_mode(mode);
|
||||
match previous {
|
||||
Some(previous) => Ok(previous),
|
||||
None => {
|
||||
crt::set_errno(context.memory, context.teb, crt::EINVAL)?;
|
||||
Ok(-1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn configure_thread_locale(context: &mut ServiceContext<'_>, request: i32) -> Outcome<i32> {
|
||||
let previous = context.state.crt_startup().configure_thread_locale(request);
|
||||
match previous {
|
||||
Some(previous) => Ok(previous),
|
||||
None => {
|
||||
crt::set_errno(context.memory, context.teb, crt::EINVAL)?;
|
||||
Ok(-1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_user_math_error(context: &mut ServiceContext<'_>, handler: u64) -> Outcome<()> {
|
||||
context.state.crt_startup().set_user_math_error(handler);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_invalid_parameter_handler(
|
||||
context: &mut ServiceContext<'_>,
|
||||
handler: u64,
|
||||
) -> Outcome<u64> {
|
||||
Ok(context
|
||||
.state
|
||||
.crt_startup()
|
||||
.set_invalid_parameter_handler(handler))
|
||||
}
|
||||
|
||||
pub fn file_mode_pointer(context: &mut ServiceContext<'_>) -> Outcome<u64> {
|
||||
context
|
||||
.state
|
||||
.crt_startup()
|
||||
.file_mode_address(context.memory, 0)
|
||||
}
|
||||
|
||||
pub fn commit_mode_pointer(context: &mut ServiceContext<'_>) -> Outcome<u64> {
|
||||
context
|
||||
.state
|
||||
.crt_startup()
|
||||
.file_mode_address(context.memory, 1)
|
||||
}
|
||||
|
||||
pub fn signal(context: &mut ServiceContext<'_>, signal: i32, handler: u64) -> Outcome<u64> {
|
||||
let previous = context.state.crt_startup().signal(signal, handler);
|
||||
match previous {
|
||||
Some(previous) => Ok(previous),
|
||||
None => {
|
||||
crt::set_errno(context.memory, context.teb, crt::EINVAL)?;
|
||||
// SIG_ERR is (void (*)(int))-1.
|
||||
Ok(u64::MAX)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_unhandled_exception_filter(
|
||||
context: &mut ServiceContext<'_>,
|
||||
filter: u64,
|
||||
) -> Outcome<u64> {
|
||||
Ok(context
|
||||
.state
|
||||
.crt_startup()
|
||||
.set_unhandled_exception_filter(filter))
|
||||
}
|
||||
}
|
||||
@@ -190,12 +190,14 @@ pub(super) fn register(registry: &mut ImportRegistry) {
|
||||
registry.alias(CRT_STRING_API, UCRT, symbol);
|
||||
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
// The mingw-w64 C runtime imports `memcpy` through this API set.
|
||||
registry.alias("api-ms-win-crt-private-l1-1-0.dll", UCRT, "memcpy");
|
||||
}
|
||||
|
||||
const ENOMEM: u32 = 12;
|
||||
const EINVAL: u32 = 22;
|
||||
pub(super) const EINVAL: u32 = 22;
|
||||
|
||||
fn set_errno(memory: &mut GuestMemory, teb: u64, error: u32) -> Result<(), ExitReason> {
|
||||
pub(super) fn set_errno(memory: &mut GuestMemory, teb: u64, error: u32) -> Result<(), ExitReason> {
|
||||
let address = memory
|
||||
.crt_errno_address(teb)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! The arguments and environment a hosted C program's startup code hands to
|
||||
//! `main`.
|
||||
//!
|
||||
//! Documented: the global variables `__argc` (the argument count), `__argv` (a
|
||||
//! pointer to the array of argument strings) and `_environ` (a pointer to the
|
||||
//! array of environment strings), and ISO C's rule that a null pointer follows
|
||||
//! the last argument.
|
||||
//!
|
||||
//! Inferred: that `__p___argc`, `__p___argv` and `__p__environ` return the
|
||||
//! address of those variables, as the documented `__p__fmode` does for
|
||||
//! `_fmode`. Microsoft lists all five functions here only by name.
|
||||
//!
|
||||
//! Xenora's choice, because nothing public describes it: what
|
||||
//! `_configure_narrow_argv` and `_initialize_narrow_environment` do. The
|
||||
//! arguments come from the host, as bytes with no code page; wildcards are not
|
||||
//! expanded; and the environment table is empty.
|
||||
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::memory::{GuestMemory, MemoryError, PROCESS_HEAP};
|
||||
use std::fmt;
|
||||
|
||||
const EINVAL: i32 = 22;
|
||||
/// `_crt_argv_no_arguments`, `_crt_argv_unexpanded_arguments` and
|
||||
/// `_crt_argv_expanded_arguments` (corecrt_startup.h).
|
||||
const NO_ARGUMENTS: i32 = 0;
|
||||
const UNEXPANDED_ARGUMENTS: i32 = 1;
|
||||
const EXPANDED_ARGUMENTS: i32 = 2;
|
||||
/// Windows limits a command line to 32,767 characters including its
|
||||
/// terminator (`CreateProcess`). The same bound is applied here to the
|
||||
/// arguments with their terminators.
|
||||
pub const MAX_PROGRAM_ARGUMENT_BYTES: usize = 32_767;
|
||||
|
||||
/// Why [`super::ServicesState::set_program_arguments`] refused its input.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ProgramArgumentsError {
|
||||
/// An argument holds a NUL byte, which would end it early in the guest.
|
||||
ContainsNul,
|
||||
/// The arguments and their terminators exceed
|
||||
/// [`MAX_PROGRAM_ARGUMENT_BYTES`].
|
||||
TooLong,
|
||||
/// The guest has already built `__argv`; it would not see a change.
|
||||
AlreadyConfigured,
|
||||
}
|
||||
|
||||
impl fmt::Display for ProgramArgumentsError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::ContainsNul => "a program argument contains a NUL byte",
|
||||
Self::TooLong => "the program arguments exceed 32,767 bytes",
|
||||
Self::AlreadyConfigured => "the guest has already configured its arguments",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ProgramArgumentsError {}
|
||||
|
||||
/// Which of the three guest variables a `__p_` function points at. The value
|
||||
/// is the variable's offset in their shared block.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum Variable {
|
||||
Argc = 0,
|
||||
Argv = 8,
|
||||
Environ = 16,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct CrtArguments {
|
||||
/// What the host supplied, program name first.
|
||||
supplied: Option<Vec<Vec<u8>>>,
|
||||
/// Guest address of the block holding `__argc`, `__argv` and `_environ`.
|
||||
variables: Option<u64>,
|
||||
configured: bool,
|
||||
environment_initialized: bool,
|
||||
}
|
||||
|
||||
fn fault(error: MemoryError) -> ExitReason {
|
||||
ExitReason::MemoryFault(error)
|
||||
}
|
||||
|
||||
impl CrtArguments {
|
||||
pub(super) fn supply(&mut self, arguments: &[&str]) -> Result<(), ProgramArgumentsError> {
|
||||
if self.configured {
|
||||
return Err(ProgramArgumentsError::AlreadyConfigured);
|
||||
}
|
||||
if arguments.iter().any(|argument| argument.contains('\0')) {
|
||||
return Err(ProgramArgumentsError::ContainsNul);
|
||||
}
|
||||
let bytes: usize = arguments.iter().map(|argument| argument.len() + 1).sum();
|
||||
if bytes > MAX_PROGRAM_ARGUMENT_BYTES {
|
||||
return Err(ProgramArgumentsError::TooLong);
|
||||
}
|
||||
self.supplied = Some(
|
||||
arguments
|
||||
.iter()
|
||||
.map(|argument| argument.as_bytes().to_vec())
|
||||
.collect(),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Guest address of one of the three variables. They are allocated
|
||||
/// together from the process heap on first use, as zeros: no arguments,
|
||||
/// and null `__argv` and `_environ`.
|
||||
pub(super) fn address(
|
||||
&mut self,
|
||||
memory: &mut GuestMemory,
|
||||
variable: Variable,
|
||||
) -> Result<u64, ExitReason> {
|
||||
let base = match self.variables {
|
||||
Some(base) => base,
|
||||
None => {
|
||||
let base = memory
|
||||
.map_heap_allocation(PROCESS_HEAP, 24)
|
||||
.map_err(fault)?;
|
||||
self.variables = Some(base);
|
||||
base
|
||||
}
|
||||
};
|
||||
Ok(base + variable as u64)
|
||||
}
|
||||
|
||||
/// `_configure_narrow_argv`. Modes 1 and 2 build `__argc` and `__argv`
|
||||
/// once; a later call changes nothing. Mode 0 builds nothing. Any other
|
||||
/// mode is refused with `EINVAL`.
|
||||
pub(super) fn configure(
|
||||
&mut self,
|
||||
memory: &mut GuestMemory,
|
||||
mode: i32,
|
||||
) -> Result<i32, ExitReason> {
|
||||
match mode {
|
||||
NO_ARGUMENTS => return Ok(0),
|
||||
UNEXPANDED_ARGUMENTS | EXPANDED_ARGUMENTS => {}
|
||||
_ => return Ok(EINVAL),
|
||||
}
|
||||
if self.configured {
|
||||
return Ok(0);
|
||||
}
|
||||
// With no host input the program name is not available, and ISO C
|
||||
// then makes argv[0] the empty string.
|
||||
let default = [Vec::new()];
|
||||
let arguments = self.supplied.as_deref().unwrap_or(&default);
|
||||
let table_bytes = 8 * (arguments.len() + 1);
|
||||
let string_bytes: usize = arguments.iter().map(|argument| argument.len() + 1).sum();
|
||||
let table = memory
|
||||
.map_heap_allocation(PROCESS_HEAP, table_bytes + string_bytes)
|
||||
.map_err(fault)?;
|
||||
// The pointers first, then the strings. The block starts as zeros, so
|
||||
// the pointer after the last argument and every terminator are in place.
|
||||
let mut string = table + table_bytes as u64;
|
||||
for (index, argument) in arguments.iter().enumerate() {
|
||||
memory
|
||||
.write_u64(table + 8 * index as u64, string)
|
||||
.map_err(fault)?;
|
||||
memory.write_bytes(string, argument).map_err(fault)?;
|
||||
string += argument.len() as u64 + 1;
|
||||
}
|
||||
let count = arguments.len() as u32;
|
||||
let argc = self.address(memory, Variable::Argc)?;
|
||||
let argv = self.address(memory, Variable::Argv)?;
|
||||
memory.write_u32(argc, count).map_err(fault)?;
|
||||
memory.write_u64(argv, table).map_err(fault)?;
|
||||
self.configured = true;
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
/// `_initialize_narrow_environment`. Points `_environ` at an empty table,
|
||||
/// one null pointer, once.
|
||||
pub(super) fn initialize_environment(
|
||||
&mut self,
|
||||
memory: &mut GuestMemory,
|
||||
) -> Result<i32, ExitReason> {
|
||||
if !self.environment_initialized {
|
||||
let table = memory.map_heap_allocation(PROCESS_HEAP, 8).map_err(fault)?;
|
||||
let environ = self.address(memory, Variable::Environ)?;
|
||||
memory.write_u64(environ, table).map_err(fault)?;
|
||||
self.environment_initialized = true;
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
@@ -400,6 +400,57 @@ impl CallbackTask for ExitFunctions {
|
||||
}
|
||||
}
|
||||
|
||||
/// `exit`: calls the functions registered with `atexit` and `_crt_atexit`,
|
||||
/// most recently registered first, and then ends the guest process.
|
||||
///
|
||||
/// It takes one function at a time from the shared list. A function that is
|
||||
/// registered while `exit` runs is therefore called next, before the older
|
||||
/// ones that have not run yet, as ISO C requires (7.22.4.2, 7.22.4.4). A
|
||||
/// registered function that calls `exit` again, which ISO C leaves undefined,
|
||||
/// starts a second task on the same list: the remaining functions run once
|
||||
/// each and the process ends with the later status.
|
||||
struct Exit {
|
||||
state: Arc<ServicesState>,
|
||||
status: u32,
|
||||
}
|
||||
|
||||
impl Exit {
|
||||
fn next(&mut self) -> Result<CallbackStep, ExitReason> {
|
||||
let function = self
|
||||
.state
|
||||
.atexit
|
||||
.lock()
|
||||
.expect("guest atexit functions")
|
||||
.pop();
|
||||
match function {
|
||||
Some(entry) => Ok(CallbackStep::Call {
|
||||
entry,
|
||||
args: [0; 4],
|
||||
}),
|
||||
None => Err(ExitReason::ProcessExit(
|
||||
self.state.exit_process(self.status),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn start(mut self) -> Result<CallbackStart, ExitReason> {
|
||||
match self.next()? {
|
||||
CallbackStep::Call { entry, args } => Ok(CallbackStart::Call {
|
||||
task: Box::new(self),
|
||||
entry,
|
||||
args,
|
||||
}),
|
||||
CallbackStep::Return(value) => Ok(CallbackStart::Return(value)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CallbackTask for Exit {
|
||||
fn resume(&mut self, _: u64, _: u64, _: &mut GuestMemory) -> Result<CallbackStep, ExitReason> {
|
||||
self.next()
|
||||
}
|
||||
}
|
||||
|
||||
fn register_exit_tables(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
registry.register(UCRT, "_initialize_onexit_table", |args, _, mem| {
|
||||
let table = args.rcx;
|
||||
@@ -473,6 +524,24 @@ fn register_exit_tables(registry: &mut ImportRegistry, state: &Arc<ServicesState
|
||||
Ok(ExitFunctions { pending }.start())
|
||||
});
|
||||
|
||||
// exit does not return. It is partial: no stream is flushed, because
|
||||
// there are none, and thread-local destructors are not run.
|
||||
let s = Arc::clone(state);
|
||||
registry.register_callback_task(
|
||||
UCRT,
|
||||
"exit",
|
||||
ServiceStatus::Partial,
|
||||
move |args, _, _, _| {
|
||||
// The status is an int, the low half of the first argument.
|
||||
Exit {
|
||||
state: Arc::clone(&s),
|
||||
status: args.rcx as u32,
|
||||
}
|
||||
.start()
|
||||
},
|
||||
);
|
||||
registry.alias(CRT_RUNTIME_API, UCRT, "exit");
|
||||
|
||||
for symbol in [
|
||||
"_initialize_onexit_table",
|
||||
"_register_onexit_function",
|
||||
|
||||
@@ -0,0 +1,743 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Formatting for the narrow `printf` family.
|
||||
//!
|
||||
//! The rules are from Microsoft's "Format specification syntax: printf and
|
||||
//! wprintf functions" and, where that page is silent, from ISO C 7.21.6.1. A
|
||||
//! conversion specification is `%[flags][width][.precision][size]type`.
|
||||
//!
|
||||
//! Supported: the flags `-`, `+`, space, `#` and `0`; a width and a precision
|
||||
//! given as digits or as `*`; the size prefixes `hh`, `h`, `l`, `ll`, `j`,
|
||||
//! `z`, `t`, `I`, `I32` and `I64`; and the types `d`, `i`, `u`, `o`, `x`, `X`,
|
||||
//! `c`, `s`, `p` and `%%`.
|
||||
//!
|
||||
//! Refused as invalid, as Windows does by default: `%n`, and a character that
|
||||
//! has no meaning as a type. Refused as not modelled, so that nothing is
|
||||
//! printed wrongly: the floating-point types, and wide characters and strings.
|
||||
//!
|
||||
//! Where the documentation leaves a choice, the choice made here is marked
|
||||
//! "Xenora's choice" at the code that makes it.
|
||||
|
||||
use crate::memory::MemoryError;
|
||||
|
||||
/// The most one call may produce, and the largest width or precision.
|
||||
pub(super) const MAX_OUTPUT: usize = 1 << 20;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum FormatError {
|
||||
/// The format is not valid: `%n`, an unknown type, a size prefix that
|
||||
/// does not apply to its type, or a string that ends inside a
|
||||
/// specification.
|
||||
Invalid,
|
||||
/// The format is valid and asks for something that is not modelled.
|
||||
Unsupported,
|
||||
/// The output, a width or a precision exceeds [`MAX_OUTPUT`].
|
||||
TooLong,
|
||||
/// Reading an argument or a string failed.
|
||||
Fault(MemoryError),
|
||||
}
|
||||
|
||||
/// Where the arguments and strings of one call come from.
|
||||
pub(super) trait Source {
|
||||
/// The next 8-byte argument slot.
|
||||
fn argument(&mut self) -> Result<u64, MemoryError>;
|
||||
/// The bytes of the string at `address` up to its terminator, or the first
|
||||
/// `limit` of them. Never called with a null address.
|
||||
fn string(&mut self, address: u64, limit: usize) -> Result<Vec<u8>, MemoryError>;
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Size {
|
||||
None,
|
||||
Char,
|
||||
Short,
|
||||
/// `l`: a `long`, which is 32 bits on Windows, or a wide character or
|
||||
/// string.
|
||||
Long,
|
||||
/// `ll`, `j`, `z`, `t`, `I` and `I64`: 64 bits on a 64-bit system.
|
||||
Quad,
|
||||
/// `I32`.
|
||||
Int32,
|
||||
/// `w`: a wide character or string.
|
||||
Wide,
|
||||
/// `L`: a `long double`.
|
||||
LongDouble,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Flags {
|
||||
left: bool,
|
||||
plus: bool,
|
||||
space: bool,
|
||||
alternate: bool,
|
||||
zero: bool,
|
||||
}
|
||||
|
||||
struct Spec {
|
||||
flags: Flags,
|
||||
width: usize,
|
||||
precision: Option<usize>,
|
||||
size: Size,
|
||||
}
|
||||
|
||||
struct Parser<'a> {
|
||||
format: &'a [u8],
|
||||
at: usize,
|
||||
}
|
||||
|
||||
impl Parser<'_> {
|
||||
fn peek(&self) -> Option<u8> {
|
||||
self.format.get(self.at).copied()
|
||||
}
|
||||
|
||||
fn take(&mut self, byte: u8) -> bool {
|
||||
let found = self.peek() == Some(byte);
|
||||
self.at += usize::from(found);
|
||||
found
|
||||
}
|
||||
|
||||
/// Decimal digits, possibly none.
|
||||
fn number(&mut self) -> Result<usize, FormatError> {
|
||||
let mut value = 0usize;
|
||||
while let Some(digit @ b'0'..=b'9') = self.peek() {
|
||||
value = value * 10 + usize::from(digit - b'0');
|
||||
if value > MAX_OUTPUT {
|
||||
return Err(FormatError::TooLong);
|
||||
}
|
||||
self.at += 1;
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn size(&mut self) -> Size {
|
||||
if self.take(b'h') {
|
||||
return if self.take(b'h') {
|
||||
Size::Char
|
||||
} else {
|
||||
Size::Short
|
||||
};
|
||||
}
|
||||
if self.take(b'l') {
|
||||
return if self.take(b'l') {
|
||||
Size::Quad
|
||||
} else {
|
||||
Size::Long
|
||||
};
|
||||
}
|
||||
if self.take(b'I') {
|
||||
let rest = &self.format[self.at..];
|
||||
if rest.starts_with(b"64") {
|
||||
self.at += 2;
|
||||
return Size::Quad;
|
||||
}
|
||||
if rest.starts_with(b"32") {
|
||||
self.at += 2;
|
||||
return Size::Int32;
|
||||
}
|
||||
// `I` alone is ptrdiff_t or size_t.
|
||||
return Size::Quad;
|
||||
}
|
||||
match self.peek() {
|
||||
Some(b'j' | b'z' | b't') => {
|
||||
self.at += 1;
|
||||
Size::Quad
|
||||
}
|
||||
Some(b'w') => {
|
||||
self.at += 1;
|
||||
Size::Wide
|
||||
}
|
||||
Some(b'L') => {
|
||||
self.at += 1;
|
||||
Size::LongDouble
|
||||
}
|
||||
_ => Size::None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An `int` argument is the low half of its slot.
|
||||
fn int(slot: u64) -> i32 {
|
||||
slot as u32 as i32
|
||||
}
|
||||
|
||||
fn bounded(value: usize) -> Result<usize, FormatError> {
|
||||
if value > MAX_OUTPUT {
|
||||
Err(FormatError::TooLong)
|
||||
} else {
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Pad `body` to the field width. `zeros` puts the padding after the first
|
||||
/// `lead` bytes (a sign or prefix) as zeros instead of before them as blanks.
|
||||
fn pad(out: &mut Vec<u8>, spec: &Spec, lead: usize, body: &[u8], zeros: bool) {
|
||||
let fill = spec.width.saturating_sub(body.len());
|
||||
if spec.flags.left {
|
||||
out.extend_from_slice(body);
|
||||
out.resize(out.len() + fill, b' ');
|
||||
} else if zeros {
|
||||
out.extend_from_slice(&body[..lead]);
|
||||
out.resize(out.len() + fill, b'0');
|
||||
out.extend_from_slice(&body[lead..]);
|
||||
} else {
|
||||
out.resize(out.len() + fill, b' ');
|
||||
out.extend_from_slice(body);
|
||||
}
|
||||
}
|
||||
|
||||
fn digits(mut value: u64, base: u64, upper: bool) -> Vec<u8> {
|
||||
let table: &[u8; 16] = if upper {
|
||||
b"0123456789ABCDEF"
|
||||
} else {
|
||||
b"0123456789abcdef"
|
||||
};
|
||||
let mut reversed = Vec::new();
|
||||
loop {
|
||||
reversed.push(table[(value % base) as usize]);
|
||||
value /= base;
|
||||
if value == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
reversed.reverse();
|
||||
reversed
|
||||
}
|
||||
|
||||
fn integer(out: &mut Vec<u8>, spec: &Spec, kind: u8, slot: u64) -> Result<(), FormatError> {
|
||||
let signed = matches!(kind, b'd' | b'i');
|
||||
// Without a size prefix an integer argument is a 32-bit int, and so is a
|
||||
// long. `hh` and `h` arguments arrive as an int and are converted back.
|
||||
let (negative, magnitude) = if signed {
|
||||
let value = match spec.size {
|
||||
Size::None | Size::Long | Size::Int32 => i64::from(int(slot)),
|
||||
Size::Char => i64::from(slot as u8 as i8),
|
||||
Size::Short => i64::from(slot as u16 as i16),
|
||||
Size::Quad => slot as i64,
|
||||
Size::Wide | Size::LongDouble => return Err(FormatError::Invalid),
|
||||
};
|
||||
(value < 0, value.unsigned_abs())
|
||||
} else {
|
||||
let value = match spec.size {
|
||||
Size::None | Size::Long | Size::Int32 => u64::from(slot as u32),
|
||||
Size::Char => u64::from(slot as u8),
|
||||
Size::Short => u64::from(slot as u16),
|
||||
Size::Quad => slot,
|
||||
Size::Wide | Size::LongDouble => return Err(FormatError::Invalid),
|
||||
};
|
||||
(false, value)
|
||||
};
|
||||
|
||||
let (base, upper) = match kind {
|
||||
b'o' => (8, false),
|
||||
b'x' => (16, false),
|
||||
b'X' => (16, true),
|
||||
_ => (10, false),
|
||||
};
|
||||
// The precision is the minimum number of digits, 1 by default. A zero
|
||||
// value with a precision of zero has no digits.
|
||||
let precision = spec.precision.unwrap_or(1);
|
||||
let mut number = if magnitude == 0 && precision == 0 {
|
||||
Vec::new()
|
||||
} else {
|
||||
digits(magnitude, base, upper)
|
||||
};
|
||||
if number.len() < precision {
|
||||
let mut padded = vec![b'0'; precision - number.len()];
|
||||
padded.append(&mut number);
|
||||
number = padded;
|
||||
}
|
||||
|
||||
let mut body = Vec::new();
|
||||
if signed {
|
||||
// The blank is ignored when both it and + appear.
|
||||
if negative {
|
||||
body.push(b'-');
|
||||
} else if spec.flags.plus {
|
||||
body.push(b'+');
|
||||
} else if spec.flags.space {
|
||||
body.push(b' ');
|
||||
}
|
||||
}
|
||||
if spec.flags.alternate {
|
||||
match kind {
|
||||
// ISO C: the precision grows, only if it must, so that the first
|
||||
// digit is a zero. A zero value with a precision of zero is "0".
|
||||
b'o' if number.first() != Some(&b'0') => body.push(b'0'),
|
||||
b'x' if magnitude != 0 => body.extend_from_slice(b"0x"),
|
||||
b'X' if magnitude != 0 => body.extend_from_slice(b"0X"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let lead = body.len();
|
||||
body.append(&mut number);
|
||||
bounded(body.len().max(spec.width))?;
|
||||
// 0 is ignored with - and when an integer has a precision.
|
||||
let zeros = spec.flags.zero && spec.precision.is_none();
|
||||
pad(out, spec, lead, &body, zeros);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Format `format` with the arguments and strings `source` supplies. Returns
|
||||
/// the bytes to write; their number is the function result of the `printf`
|
||||
/// family.
|
||||
pub(super) fn format(format: &[u8], source: &mut dyn Source) -> Result<Vec<u8>, FormatError> {
|
||||
let mut out = Vec::new();
|
||||
let mut parser = Parser { format, at: 0 };
|
||||
while let Some(byte) = parser.peek() {
|
||||
parser.at += 1;
|
||||
if byte != b'%' {
|
||||
out.push(byte);
|
||||
bounded(out.len())?;
|
||||
continue;
|
||||
}
|
||||
if parser.take(b'%') {
|
||||
out.push(b'%');
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut flags = Flags::default();
|
||||
loop {
|
||||
match parser.peek() {
|
||||
Some(b'-') => flags.left = true,
|
||||
Some(b'+') => flags.plus = true,
|
||||
Some(b' ') => flags.space = true,
|
||||
Some(b'#') => flags.alternate = true,
|
||||
Some(b'0') => flags.zero = true,
|
||||
_ => break,
|
||||
}
|
||||
parser.at += 1;
|
||||
}
|
||||
let width = if parser.take(b'*') {
|
||||
// ISO C: a negative width is the - flag and a positive width.
|
||||
let value = int(source.argument().map_err(FormatError::Fault)?);
|
||||
flags.left |= value < 0;
|
||||
bounded(value.unsigned_abs() as usize)?
|
||||
} else {
|
||||
parser.number()?
|
||||
};
|
||||
let precision = if !parser.take(b'.') {
|
||||
None
|
||||
} else if parser.take(b'*') {
|
||||
// ISO C: a negative precision is taken as if it were omitted.
|
||||
let value = int(source.argument().map_err(FormatError::Fault)?);
|
||||
match usize::try_from(value) {
|
||||
Ok(value) => Some(bounded(value)?),
|
||||
Err(_) => None,
|
||||
}
|
||||
} else {
|
||||
Some(parser.number()?)
|
||||
};
|
||||
let size = parser.size();
|
||||
let spec = Spec {
|
||||
flags,
|
||||
width,
|
||||
precision,
|
||||
size,
|
||||
};
|
||||
let kind = parser.peek().ok_or(FormatError::Invalid)?;
|
||||
parser.at += 1;
|
||||
|
||||
match kind {
|
||||
b'd' | b'i' | b'u' | b'o' | b'x' | b'X' => {
|
||||
let slot = source.argument().map_err(FormatError::Fault)?;
|
||||
integer(&mut out, &spec, kind, slot)?;
|
||||
}
|
||||
b'c' => {
|
||||
match spec.size {
|
||||
Size::None | Size::Short => {}
|
||||
Size::Long | Size::Wide => return Err(FormatError::Unsupported),
|
||||
_ => return Err(FormatError::Invalid),
|
||||
}
|
||||
// The precision has no effect on a character.
|
||||
let slot = source.argument().map_err(FormatError::Fault)?;
|
||||
// Xenora's choice: 0 pads any type, as the page's description
|
||||
// of the flag is not limited to numbers.
|
||||
pad(&mut out, &spec, 0, &[slot as u8], spec.flags.zero);
|
||||
}
|
||||
b's' => {
|
||||
match spec.size {
|
||||
Size::None | Size::Short => {}
|
||||
Size::Long | Size::Wide => return Err(FormatError::Unsupported),
|
||||
_ => return Err(FormatError::Invalid),
|
||||
}
|
||||
let address = source.argument().map_err(FormatError::Fault)?;
|
||||
let limit = spec.precision.unwrap_or(MAX_OUTPUT + 1);
|
||||
let text = if address == 0 {
|
||||
// Xenora's choice: the precision also limits "(null)".
|
||||
let null = b"(null)";
|
||||
null[..null.len().min(limit)].to_vec()
|
||||
} else {
|
||||
source.string(address, limit).map_err(FormatError::Fault)?
|
||||
};
|
||||
bounded(text.len().max(spec.width))?;
|
||||
pad(&mut out, &spec, 0, &text, spec.flags.zero);
|
||||
}
|
||||
b'p' => {
|
||||
if spec.size != Size::None {
|
||||
return Err(FormatError::Invalid);
|
||||
}
|
||||
let slot = source.argument().map_err(FormatError::Fault)?;
|
||||
// "An address in hexadecimal digits" is all the page says.
|
||||
// Xenora's choice: sixteen upper-case digits, and no other
|
||||
// flag or precision has an effect.
|
||||
let text = format!("{slot:016X}");
|
||||
pad(&mut out, &spec, 0, text.as_bytes(), false);
|
||||
}
|
||||
// Wide characters and strings, floating point and the counted
|
||||
// string structures are valid and not modelled.
|
||||
b'C' | b'S' | b'Z' | b'e' | b'E' | b'f' | b'F' | b'g' | b'G' | b'a' | b'A' => {
|
||||
return Err(FormatError::Unsupported);
|
||||
}
|
||||
// %n is disabled by default, and any other character has no
|
||||
// meaning as a type.
|
||||
_ => return Err(FormatError::Invalid),
|
||||
}
|
||||
bounded(out.len())?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{FormatError, MAX_OUTPUT, Source, format};
|
||||
use crate::memory::MemoryError;
|
||||
|
||||
/// A string argument is the address `STRINGS + 0x100 * index`.
|
||||
const STRINGS: u64 = 0x1000_0000;
|
||||
|
||||
struct Call {
|
||||
slots: Vec<u64>,
|
||||
strings: Vec<Vec<u8>>,
|
||||
next: usize,
|
||||
}
|
||||
|
||||
impl Source for Call {
|
||||
fn argument(&mut self) -> Result<u64, MemoryError> {
|
||||
let slot = self.slots.get(self.next).copied();
|
||||
self.next += 1;
|
||||
slot.ok_or(MemoryError::UnmappedAddress(self.next as u64))
|
||||
}
|
||||
|
||||
fn string(&mut self, address: u64, limit: usize) -> Result<Vec<u8>, MemoryError> {
|
||||
let index = ((address - STRINGS) / 0x100) as usize;
|
||||
let text = self
|
||||
.strings
|
||||
.get(index)
|
||||
.ok_or(MemoryError::UnmappedAddress(address))?;
|
||||
Ok(text[..text.len().min(limit)].to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
fn run(text: &str, slots: &[u64], strings: &[&str]) -> Result<String, FormatError> {
|
||||
let mut call = Call {
|
||||
slots: slots.to_vec(),
|
||||
strings: strings
|
||||
.iter()
|
||||
.map(|text| text.as_bytes().to_vec())
|
||||
.collect(),
|
||||
next: 0,
|
||||
};
|
||||
let bytes = format(text.as_bytes(), &mut call)?;
|
||||
assert_eq!(call.next, slots.len(), "{text}: arguments consumed");
|
||||
Ok(String::from_utf8(bytes).unwrap())
|
||||
}
|
||||
|
||||
fn ok(text: &str, slots: &[u64], strings: &[&str]) -> String {
|
||||
run(text, slots, strings).unwrap_or_else(|error| panic!("{text}: {error:?}"))
|
||||
}
|
||||
|
||||
/// The host C library's `snprintf`, on cases whose behaviour ISO C
|
||||
/// defines and Windows shares. `tests/printf/reference.py` wrote the file
|
||||
/// and says how each line is laid out.
|
||||
#[test]
|
||||
fn output_matches_the_host_c_library_on_defined_cases() {
|
||||
let vectors = include_str!("../../tests/printf/vectors.txt");
|
||||
let unhex = |text: &str| -> Vec<u8> {
|
||||
(0..text.len() / 2)
|
||||
.map(|at| u8::from_str_radix(&text[2 * at..2 * at + 2], 16).unwrap())
|
||||
.collect()
|
||||
};
|
||||
let mut cases = 0;
|
||||
for line in vectors.lines().filter(|line| !line.starts_with('#')) {
|
||||
let fields: Vec<&str> = line.split('\t').collect();
|
||||
let [template, arguments, expected] = fields[..] else {
|
||||
panic!("three fields: {line}");
|
||||
};
|
||||
let template = unhex(template);
|
||||
let (mut slots, mut strings) = (Vec::new(), Vec::new());
|
||||
for argument in arguments.split(',').filter(|text| !text.is_empty()) {
|
||||
let (kind, value) = argument.split_once(':').unwrap();
|
||||
match kind {
|
||||
"i" => slots.push(u64::from_str_radix(value, 16).unwrap()),
|
||||
"s" => {
|
||||
slots.push(STRINGS + 0x100 * strings.len() as u64);
|
||||
strings.push(unhex(value));
|
||||
}
|
||||
"n" => slots.push(0),
|
||||
_ => panic!("argument kind {kind}"),
|
||||
}
|
||||
}
|
||||
let mut call = Call {
|
||||
slots,
|
||||
strings,
|
||||
next: 0,
|
||||
};
|
||||
let shown = String::from_utf8_lossy(&template).into_owned();
|
||||
let got = format(&template, &mut call)
|
||||
.unwrap_or_else(|error| panic!("{shown} {arguments}: {error:?}"));
|
||||
assert_eq!(
|
||||
String::from_utf8_lossy(&got),
|
||||
String::from_utf8_lossy(&unhex(expected)),
|
||||
"{shown} with {arguments}"
|
||||
);
|
||||
assert_eq!(call.next, call.slots.len(), "{shown}: arguments consumed");
|
||||
cases += 1;
|
||||
}
|
||||
assert!(cases > 2000, "{cases} cases");
|
||||
}
|
||||
|
||||
/// Rules the host C library does not share or that the reference leaves
|
||||
/// out, each from the format specification page.
|
||||
#[test]
|
||||
fn windows_sizes_follow_the_format_specification_page() {
|
||||
// "The formatter consumes integer arguments ... as 32-bit int types";
|
||||
// a long is a 32-bit type on Windows. The upper half of the slot is
|
||||
// not part of either.
|
||||
let slot = 0xFFFF_FFFF_8000_0001;
|
||||
assert_eq!(ok("%d", &[slot], &[]), "-2147483647");
|
||||
assert_eq!(ok("%ld", &[slot], &[]), "-2147483647");
|
||||
assert_eq!(ok("%lu", &[slot], &[]), "2147483649");
|
||||
assert_eq!(ok("%lx", &[0x1_2345_6789], &[]), "23456789");
|
||||
assert_eq!(ok("%I32d", &[slot], &[]), "-2147483647");
|
||||
assert_eq!(ok("%I32u", &[slot], &[]), "2147483649");
|
||||
// ll, I64, j, t, z and I alone are 64-bit.
|
||||
for size in ["ll", "I64", "j", "t", "z", "I"] {
|
||||
assert_eq!(
|
||||
ok(&format!("%{size}d"), &[slot], &[]),
|
||||
"-2147483647",
|
||||
"{size}"
|
||||
);
|
||||
assert_eq!(
|
||||
ok(&format!("%{size}u"), &[u64::MAX], &[]),
|
||||
"18446744073709551615",
|
||||
"{size}"
|
||||
);
|
||||
assert_eq!(
|
||||
ok(&format!("%{size}x"), &[0x1_2345_6789], &[]),
|
||||
"123456789",
|
||||
"{size}"
|
||||
);
|
||||
}
|
||||
assert_eq!(ok("%I64d", &[1 << 63], &[]), "-9223372036854775808");
|
||||
// I followed by other digits is the size I and then literal text?
|
||||
// No: digits after the size are not a type, so the format is invalid.
|
||||
assert_eq!(run("%I16d", &[1], &[]), Err(FormatError::Invalid));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strings_characters_and_pointers() {
|
||||
// "If the argument that corresponds to %s ... is a null pointer,
|
||||
// "(null)" is displayed."
|
||||
assert_eq!(ok("[%s]", &[0], &[]), "[(null)]");
|
||||
assert_eq!(ok("[%10s]", &[0], &[]), "[ (null)]");
|
||||
assert_eq!(ok("[%-8s]", &[0], &[]), "[(null) ]");
|
||||
// Xenora's choice: the precision limits it too.
|
||||
assert_eq!(ok("[%.3s]", &[0], &[]), "[(nu]");
|
||||
// h is a single-byte character or string, as no prefix is.
|
||||
assert_eq!(
|
||||
ok("%hc%hs", &[u64::from(b'x'), super::tests::STRINGS], &["yz"]),
|
||||
"xyz"
|
||||
);
|
||||
// The precision has no effect on a character.
|
||||
assert_eq!(ok("[%.0c]", &[0x141], &[]), "[A]");
|
||||
// Xenora's choice for %p: sixteen upper-case hexadecimal digits.
|
||||
assert_eq!(ok("%p", &[0x1_4000_1abc], &[]), "0000000140001ABC");
|
||||
assert_eq!(ok("%p", &[0], &[]), "0000000000000000");
|
||||
assert_eq!(ok("[%20p]", &[0xABC], &[]), "[ 0000000000000ABC]");
|
||||
assert_eq!(ok("[%-20p]", &[0xABC], &[]), "[0000000000000ABC ]");
|
||||
// Xenora's choice: 0 pads a character and a string as it pads a number.
|
||||
assert_eq!(ok("[%03c]", &[u64::from(b'a')], &[]), "[00a]");
|
||||
assert_eq!(ok("[%05s]", &[STRINGS], &["ab"]), "[000ab]");
|
||||
assert_eq!(ok("[%-05s]", &[STRINGS], &["ab"]), "[ab ]");
|
||||
// "+: Use a sign (+ or -) to prefix the output value if it's of a
|
||||
// signed type", and the blank likewise: neither affects an unsigned
|
||||
// conversion.
|
||||
for (text, wanted) in [
|
||||
("%+u", "7"),
|
||||
("% u", "7"),
|
||||
("%+x", "7"),
|
||||
("% X", "7"),
|
||||
("%+o", "7"),
|
||||
("%+ 5u", " 7"),
|
||||
("%+d", "+7"),
|
||||
("% d", " 7"),
|
||||
] {
|
||||
assert_eq!(ok(text, &[7], &[]), wanted, "{text}");
|
||||
}
|
||||
// ISO C for %#.0o with a zero value, which the page does not cover.
|
||||
assert_eq!(ok("[%#.0o]", &[0], &[]), "[0]");
|
||||
assert_eq!(ok("[%.0o]", &[0], &[]), "[]");
|
||||
// Text between and around specifications is copied, and %% is a
|
||||
// percent sign.
|
||||
assert_eq!(
|
||||
ok("100%% of %s%c", &[STRINGS, u64::from(b'!')], &["it"]),
|
||||
"100% of it!"
|
||||
);
|
||||
assert_eq!(ok("", &[], &[]), "");
|
||||
assert_eq!(ok("plain", &[], &[]), "plain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_formats_are_refused() {
|
||||
// "The n specifier is disabled by default", and "if a percent sign is
|
||||
// followed by a character that has no meaning as a format field, the
|
||||
// invalid parameter handler is invoked."
|
||||
for text in [
|
||||
"%n",
|
||||
"%hn",
|
||||
"count %d%n",
|
||||
"%y",
|
||||
"%",
|
||||
"%5",
|
||||
"%-",
|
||||
"%.",
|
||||
"%.3",
|
||||
"%l",
|
||||
"%ll",
|
||||
"%h",
|
||||
"%I64",
|
||||
"%5%",
|
||||
"% %",
|
||||
"%!",
|
||||
"%\u{1}",
|
||||
] {
|
||||
let slots = [1, 2, 3];
|
||||
let mut call = Call {
|
||||
slots: slots.to_vec(),
|
||||
strings: Vec::new(),
|
||||
next: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
format(text.as_bytes(), &mut call),
|
||||
Err(FormatError::Invalid),
|
||||
"{text:?}"
|
||||
);
|
||||
}
|
||||
// A size prefix that does not apply to its type.
|
||||
for text in [
|
||||
"%wd", "%Ld", "%wu", "%Lx", "%llc", "%hhc", "%jc", "%lls", "%zs", "%I64s", "%lp",
|
||||
"%hp", "%llp", "%I32c",
|
||||
] {
|
||||
assert_eq!(run(text, &[1], &["s"]), Err(FormatError::Invalid), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_conversions_that_are_not_modelled_are_refused() {
|
||||
for kind in ["e", "E", "f", "F", "g", "G", "a", "A"] {
|
||||
for prefix in ["", ".3", "l", "L", "10.2", "#"] {
|
||||
let text = format!("%{prefix}{kind}");
|
||||
let mut call = Call {
|
||||
slots: vec![0x3FF0_0000_0000_0000],
|
||||
strings: Vec::new(),
|
||||
next: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
format(text.as_bytes(), &mut call),
|
||||
Err(FormatError::Unsupported),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
}
|
||||
// Wide characters and strings: C and S, and c and s with l or w.
|
||||
for text in ["%C", "%S", "%lc", "%ls", "%wc", "%ws", "%Z", "%hC", "%hS"] {
|
||||
let mut call = Call {
|
||||
slots: vec![STRINGS],
|
||||
strings: vec![b"w".to_vec()],
|
||||
next: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
format(text.as_bytes(), &mut call),
|
||||
Err(FormatError::Unsupported),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
// Nothing is produced before a later refusal either: the caller gets
|
||||
// an error, not a prefix.
|
||||
assert_eq!(
|
||||
run("ok %d then %f", &[1, 2], &[]),
|
||||
Err(FormatError::Unsupported)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_and_faults() {
|
||||
let most = MAX_OUTPUT;
|
||||
// A width or precision up to the bound is honoured; one more is not.
|
||||
assert_eq!(ok(&format!("%{most}d"), &[7], &[]).len(), most);
|
||||
assert_eq!(
|
||||
run(&format!("%{}d", most + 1), &[7], &[]),
|
||||
Err(FormatError::TooLong)
|
||||
);
|
||||
assert_eq!(ok(&format!("%.{most}d"), &[7], &[]).len(), most);
|
||||
assert_eq!(
|
||||
run(&format!("%.{}d", most + 1), &[7], &[]),
|
||||
Err(FormatError::TooLong)
|
||||
);
|
||||
assert_eq!(
|
||||
run("%99999999999999999999d", &[7], &[]),
|
||||
Err(FormatError::TooLong)
|
||||
);
|
||||
// The same through *, and the total over several conversions.
|
||||
assert_eq!(ok("%*d", &[most as u64, 7], &[]).len(), most);
|
||||
assert_eq!(
|
||||
run("%*d", &[most as u64 + 1, 7], &[]),
|
||||
Err(FormatError::TooLong)
|
||||
);
|
||||
assert_eq!(
|
||||
run("%.*d", &[most as u64 + 1, 7], &[]),
|
||||
Err(FormatError::TooLong)
|
||||
);
|
||||
let half = most / 2 + 1;
|
||||
assert_eq!(
|
||||
run(&format!("%{half}d%{half}d"), &[1, 2], &[]),
|
||||
Err(FormatError::TooLong)
|
||||
);
|
||||
// The most negative width is a left-justified width past the bound.
|
||||
assert_eq!(
|
||||
run("%*d", &[0x8000_0000, 7], &[]),
|
||||
Err(FormatError::TooLong)
|
||||
);
|
||||
// A string is read only up to its precision.
|
||||
assert_eq!(ok("%.2s", &[STRINGS], &["abcdef"]), "ab");
|
||||
|
||||
// A missing argument or an unreadable string is a fault, wherever in
|
||||
// the specification it is needed.
|
||||
for text in [
|
||||
"%d",
|
||||
"%*d",
|
||||
"%.*d",
|
||||
"%5.*d",
|
||||
"%s",
|
||||
"%c",
|
||||
"%p",
|
||||
"%d %d %d %d",
|
||||
] {
|
||||
assert!(
|
||||
matches!(run(text, &[], &[]), Err(FormatError::Fault(_))),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
let mut call = Call {
|
||||
slots: vec![STRINGS + 0x900],
|
||||
strings: Vec::new(),
|
||||
next: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
format(b"%s", &mut call),
|
||||
Err(FormatError::Fault(MemoryError::UnmappedAddress(
|
||||
STRINGS + 0x900
|
||||
)))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! What a C program's startup code configures in the C runtime before `main`.
|
||||
//!
|
||||
//! Each value is recorded and returned as its public documentation says, and
|
||||
//! nothing acts on any of them yet. No invalid-parameter handler, signal
|
||||
//! handler, exception filter, math-error handler or new handler is ever called,
|
||||
//! there is no locale, and nothing reads `_fmode` or `_commode` until stdio
|
||||
//! exists. The registry therefore declares every service here `partial`.
|
||||
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::memory::{GuestMemory, PROCESS_HEAP};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// `_O_TEXT` (fcntl.h), the documented initial value of `_fmode`.
|
||||
const O_TEXT: u32 = 0x4000;
|
||||
/// `_ENABLE_PER_THREAD_LOCALE` and `_DISABLE_PER_THREAD_LOCALE` (locale.h).
|
||||
const ENABLE_PER_THREAD_LOCALE: i32 = 1;
|
||||
const DISABLE_PER_THREAD_LOCALE: i32 = 2;
|
||||
/// The signals the documentation of `signal` lists, by their signal.h values:
|
||||
/// SIGINT, SIGILL, SIGFPE, SIGSEGV, SIGTERM and SIGABRT.
|
||||
const SIGNALS: [i32; 6] = [2, 4, 8, 11, 15, 22];
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct CrtStartup {
|
||||
app_type: i32,
|
||||
/// Whether `malloc` would call the new handler on failure. It never does.
|
||||
new_mode: i32,
|
||||
per_thread_locale: bool,
|
||||
user_math_error: u64,
|
||||
invalid_parameter_handler: u64,
|
||||
unhandled_exception_filter: u64,
|
||||
/// Handlers other than the default, `SIG_DFL`, which is zero.
|
||||
signals: BTreeMap<i32, u64>,
|
||||
/// Guest address of `_fmode`. `_commode` is the `int` after it.
|
||||
file_modes: Option<u64>,
|
||||
}
|
||||
|
||||
impl CrtStartup {
|
||||
pub(super) fn app_type(&self) -> i32 {
|
||||
self.app_type
|
||||
}
|
||||
|
||||
pub(super) fn set_app_type(&mut self, kind: i32) {
|
||||
self.app_type = kind;
|
||||
}
|
||||
|
||||
/// The previous mode, or `None` for a mode that is neither 0 nor 1.
|
||||
pub(super) fn set_new_mode(&mut self, mode: i32) -> Option<i32> {
|
||||
matches!(mode, 0 | 1).then(|| std::mem::replace(&mut self.new_mode, mode))
|
||||
}
|
||||
|
||||
/// The setting before the call, or `None` for a request that is not 0
|
||||
/// (query), enable or disable. A new process uses the global locale.
|
||||
pub(super) fn configure_thread_locale(&mut self, request: i32) -> Option<i32> {
|
||||
let before = if self.per_thread_locale {
|
||||
ENABLE_PER_THREAD_LOCALE
|
||||
} else {
|
||||
DISABLE_PER_THREAD_LOCALE
|
||||
};
|
||||
match request {
|
||||
0 => {}
|
||||
ENABLE_PER_THREAD_LOCALE => self.per_thread_locale = true,
|
||||
DISABLE_PER_THREAD_LOCALE => self.per_thread_locale = false,
|
||||
_ => return None,
|
||||
}
|
||||
Some(before)
|
||||
}
|
||||
|
||||
pub(super) fn user_math_error(&self) -> u64 {
|
||||
self.user_math_error
|
||||
}
|
||||
|
||||
pub(super) fn set_user_math_error(&mut self, handler: u64) {
|
||||
self.user_math_error = handler;
|
||||
}
|
||||
|
||||
pub(super) fn set_invalid_parameter_handler(&mut self, handler: u64) -> u64 {
|
||||
std::mem::replace(&mut self.invalid_parameter_handler, handler)
|
||||
}
|
||||
|
||||
pub(super) fn set_unhandled_exception_filter(&mut self, filter: u64) -> u64 {
|
||||
std::mem::replace(&mut self.unhandled_exception_filter, filter)
|
||||
}
|
||||
|
||||
/// The previous handler, or `None` for a signal the documentation does not
|
||||
/// list. One table serves the whole process.
|
||||
pub(super) fn signal(&mut self, signal: i32, handler: u64) -> Option<u64> {
|
||||
SIGNALS
|
||||
.contains(&signal)
|
||||
.then(|| self.signals.insert(signal, handler).unwrap_or(0))
|
||||
}
|
||||
|
||||
/// Guest address of `_fmode` (`index` 0) or `_commode` (`index` 1). Both
|
||||
/// are allocated together from the process heap on first use. `_fmode`
|
||||
/// starts as `_O_TEXT`, as documented. `_commode` starts as zero: its
|
||||
/// documentation gives no initial value, and zero is "no commit".
|
||||
pub(super) fn file_mode_address(
|
||||
&mut self,
|
||||
memory: &mut GuestMemory,
|
||||
index: u64,
|
||||
) -> Result<u64, ExitReason> {
|
||||
let base = match self.file_modes {
|
||||
Some(base) => base,
|
||||
None => {
|
||||
let base = memory
|
||||
.map_heap_allocation(PROCESS_HEAP, 8)
|
||||
.and_then(|base| memory.write_u32(base, O_TEXT).map(|()| base))
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
self.file_modes = Some(base);
|
||||
base
|
||||
}
|
||||
};
|
||||
Ok(base + 4 * index)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! The standard streams of a hosted C program, and where their output goes.
|
||||
//!
|
||||
//! `__acrt_iob_func` hands out the `FILE` objects for `stdin`, `stdout` and
|
||||
//! `stderr`. What the guest writes to `stdout` and to `stderr` is kept in two
|
||||
//! host-side buffers that a host or a test reads through `ServicesState`.
|
||||
//!
|
||||
//! The standard streams "always open in text mode by default", and in text
|
||||
//! mode "each line feed is replaced with a carriage return-line feed pair"
|
||||
//! that "has no effect on the return value" (Microsoft Learn, "Text and
|
||||
//! binary mode file I/O" and "fwrite"). The buffers hold the bytes after that
|
||||
//! replacement, which is what the operating system would be handed.
|
||||
//!
|
||||
//! Output is never held back: there is no buffering to flush or to configure.
|
||||
//! Any other stream, and input, are not modelled, and using one stops the
|
||||
//! guest with the runtime-limit fault.
|
||||
|
||||
use super::crt_format::{self, FormatError, Source};
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::memory::{GuestMemory, MemoryError, PROCESS_HEAP};
|
||||
|
||||
/// The exit for a request the runtime does not model.
|
||||
const RUNTIME_LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE);
|
||||
/// `typedef struct _iobuf { void* _Placeholder; } FILE;` (corecrt_wstdio.h).
|
||||
const FILE_BYTES: u64 = 8;
|
||||
/// The most a format string or one `fwrite` or `fputs` may hold.
|
||||
const MAX_TRANSFER: u64 = 1 << 20;
|
||||
/// The most each captured stream keeps. Writing past it stops the guest.
|
||||
pub const MAX_CAPTURED_OUTPUT: usize = 16 << 20;
|
||||
|
||||
/// Option bits of `__stdio_common_vfprintf` (corecrt_stdio_config.h) that do
|
||||
/// not change anything this engine formats: the wide-specifier bit concerns
|
||||
/// the wide functions, and the exponent and rounding bits concern floating
|
||||
/// point. Any other bit stops the guest.
|
||||
const IGNORED_OPTIONS: u64 = 0x04 | 0x10 | 0x20;
|
||||
|
||||
/// `_IOFBF`, `_IOLBF` and `_IONBF` (stdio.h).
|
||||
const IOFBF: i32 = 0x0000;
|
||||
const IOLBF: i32 = 0x0040;
|
||||
const IONBF: i32 = 0x0004;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Stream {
|
||||
Input,
|
||||
Output,
|
||||
Error,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct StandardStreams {
|
||||
/// Guest address of the three `FILE` objects, `stdin` first.
|
||||
files: Option<u64>,
|
||||
output: Vec<u8>,
|
||||
error: Vec<u8>,
|
||||
}
|
||||
|
||||
/// What a service returns when its documentation gives a failure result and
|
||||
/// an `errno` value: the handler sets `errno` to `EINVAL` and returns this.
|
||||
pub(super) struct Invalid<T>(pub T);
|
||||
|
||||
pub(super) type Outcome<T> = Result<Result<T, Invalid<T>>, ExitReason>;
|
||||
|
||||
fn fault(error: MemoryError) -> ExitReason {
|
||||
ExitReason::MemoryFault(error)
|
||||
}
|
||||
|
||||
/// The bytes of the C string at `address`, without its terminator.
|
||||
fn c_string(memory: &GuestMemory, address: u64, limit: u64) -> Result<Vec<u8>, MemoryError> {
|
||||
let mut bytes = Vec::new();
|
||||
for offset in 0..limit {
|
||||
let at = address.checked_add(offset).ok_or(MemoryError::Overflow)?;
|
||||
match memory.read_u8(at)? {
|
||||
0 => break,
|
||||
byte => bytes.push(byte),
|
||||
}
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Arguments from the guest's `va_list`: one 8-byte slot each, in order.
|
||||
struct VaList<'a> {
|
||||
memory: &'a GuestMemory,
|
||||
next: u64,
|
||||
}
|
||||
|
||||
impl Source for VaList<'_> {
|
||||
fn argument(&mut self) -> Result<u64, MemoryError> {
|
||||
let slot = self.memory.read_u64(self.next)?;
|
||||
self.next = self.next.checked_add(8).ok_or(MemoryError::Overflow)?;
|
||||
Ok(slot)
|
||||
}
|
||||
|
||||
fn string(&mut self, address: u64, limit: usize) -> Result<Vec<u8>, MemoryError> {
|
||||
c_string(self.memory, address, limit as u64)
|
||||
}
|
||||
}
|
||||
|
||||
impl StandardStreams {
|
||||
pub(super) fn output(&self) -> &[u8] {
|
||||
&self.output
|
||||
}
|
||||
|
||||
pub(super) fn error(&self) -> &[u8] {
|
||||
&self.error
|
||||
}
|
||||
|
||||
/// `__acrt_iob_func`: the `FILE` object of `stdin` (0), `stdout` (1) or
|
||||
/// `stderr` (2). The three are allocated together from the process heap
|
||||
/// on first use.
|
||||
pub(super) fn file(&mut self, memory: &mut GuestMemory, index: u32) -> Result<u64, ExitReason> {
|
||||
if index > 2 {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
}
|
||||
let base = match self.files {
|
||||
Some(base) => base,
|
||||
None => {
|
||||
let base = memory
|
||||
.map_heap_allocation(PROCESS_HEAP, (3 * FILE_BYTES) as usize)
|
||||
.map_err(fault)?;
|
||||
self.files = Some(base);
|
||||
base
|
||||
}
|
||||
};
|
||||
Ok(base + FILE_BYTES * u64::from(index))
|
||||
}
|
||||
|
||||
/// Which standard stream a non-null `FILE*` is. Any other pointer is a
|
||||
/// stream this runtime does not have.
|
||||
fn stream(&self, file: u64) -> Result<Stream, ExitReason> {
|
||||
let base = self.files.ok_or(RUNTIME_LIMIT)?;
|
||||
match file.wrapping_sub(base) {
|
||||
0 => Ok(Stream::Input),
|
||||
8 => Ok(Stream::Output),
|
||||
16 => Ok(Stream::Error),
|
||||
_ => Err(RUNTIME_LIMIT),
|
||||
}
|
||||
}
|
||||
|
||||
/// A stream that can be written: `stdout` or `stderr`.
|
||||
fn writable(&self, file: u64) -> Result<Stream, ExitReason> {
|
||||
match self.stream(file)? {
|
||||
Stream::Input => Err(RUNTIME_LIMIT),
|
||||
stream => Ok(stream),
|
||||
}
|
||||
}
|
||||
|
||||
/// Append to a captured stream, in text mode: each line feed becomes a
|
||||
/// carriage return and a line feed.
|
||||
fn write(&mut self, stream: Stream, bytes: &[u8]) -> Result<(), ExitReason> {
|
||||
let captured = match stream {
|
||||
Stream::Output => &mut self.output,
|
||||
Stream::Error => &mut self.error,
|
||||
Stream::Input => return Err(RUNTIME_LIMIT),
|
||||
};
|
||||
let feeds = bytes.iter().filter(|byte| **byte == b'\n').count();
|
||||
if bytes.len() + feeds > MAX_CAPTURED_OUTPUT - captured.len() {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
}
|
||||
for &byte in bytes {
|
||||
if byte == b'\n' {
|
||||
captured.push(b'\r');
|
||||
}
|
||||
captured.push(byte);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `__stdio_common_vfprintf`. Returns the number of characters written,
|
||||
/// before the text-mode replacement.
|
||||
pub(super) fn print(
|
||||
&mut self,
|
||||
memory: &GuestMemory,
|
||||
options: u64,
|
||||
file: u64,
|
||||
format: u64,
|
||||
locale: u64,
|
||||
arguments: u64,
|
||||
) -> Outcome<i32> {
|
||||
// A null stream or format: the function returns -1 and sets errno.
|
||||
if file == 0 || format == 0 {
|
||||
return Ok(Err(Invalid(-1)));
|
||||
}
|
||||
if options & !IGNORED_OPTIONS != 0 || locale != 0 {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
}
|
||||
let stream = self.writable(file)?;
|
||||
let template = c_string(memory, format, MAX_TRANSFER + 1).map_err(fault)?;
|
||||
if template.len() as u64 > MAX_TRANSFER {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
}
|
||||
let mut source = VaList {
|
||||
memory,
|
||||
next: arguments,
|
||||
};
|
||||
let text = match crt_format::format(&template, &mut source) {
|
||||
Ok(text) => text,
|
||||
// Windows calls the invalid parameter handler for an invalid
|
||||
// format. Xenora's choice for when execution continues: nothing
|
||||
// is written and the result is that of a null format.
|
||||
Err(FormatError::Invalid) => return Ok(Err(Invalid(-1))),
|
||||
Err(FormatError::Unsupported | FormatError::TooLong) => return Err(RUNTIME_LIMIT),
|
||||
Err(FormatError::Fault(error)) => return Err(fault(error)),
|
||||
};
|
||||
self.write(stream, &text)?;
|
||||
Ok(Ok(text.len() as i32))
|
||||
}
|
||||
|
||||
/// `fwrite`. Returns the number of whole items written.
|
||||
pub(super) fn write_items(
|
||||
&mut self,
|
||||
memory: &GuestMemory,
|
||||
buffer: u64,
|
||||
size: u64,
|
||||
count: u64,
|
||||
file: u64,
|
||||
) -> Outcome<u64> {
|
||||
if buffer == 0 || file == 0 {
|
||||
return Ok(Err(Invalid(0)));
|
||||
}
|
||||
let stream = self.writable(file)?;
|
||||
let Some(length) = size
|
||||
.checked_mul(count)
|
||||
.filter(|bytes| *bytes <= MAX_TRANSFER)
|
||||
else {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
};
|
||||
if length == 0 {
|
||||
return Ok(Ok(0));
|
||||
}
|
||||
let mut bytes = vec![0; length as usize];
|
||||
memory.read_bytes(buffer, &mut bytes).map_err(fault)?;
|
||||
self.write(stream, &bytes)?;
|
||||
Ok(Ok(count))
|
||||
}
|
||||
|
||||
/// `fputs`. Writes the string without its terminator and returns a
|
||||
/// nonnegative value, here 0; `EOF` is -1.
|
||||
pub(super) fn put_string(
|
||||
&mut self,
|
||||
memory: &GuestMemory,
|
||||
text: u64,
|
||||
file: u64,
|
||||
) -> Outcome<i32> {
|
||||
if text == 0 || file == 0 {
|
||||
return Ok(Err(Invalid(-1)));
|
||||
}
|
||||
let stream = self.writable(file)?;
|
||||
let bytes = c_string(memory, text, MAX_TRANSFER + 1).map_err(fault)?;
|
||||
if bytes.len() as u64 > MAX_TRANSFER {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
}
|
||||
self.write(stream, &bytes)?;
|
||||
Ok(Ok(0))
|
||||
}
|
||||
|
||||
/// `fflush`. A null stream means every open stream. Nothing is ever held
|
||||
/// back, so there is nothing to do.
|
||||
pub(super) fn flush(&self, file: u64) -> Result<i32, ExitReason> {
|
||||
if file != 0 {
|
||||
self.stream(file)?;
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
/// `setvbuf`. The mode and size are checked as documented and then have
|
||||
/// no effect.
|
||||
pub(super) fn set_buffer(&self, file: u64, mode: i32, size: u64) -> Outcome<i32> {
|
||||
if file == 0 {
|
||||
return Ok(Err(Invalid(-1)));
|
||||
}
|
||||
self.stream(file)?;
|
||||
let valid = match mode {
|
||||
// "No buffer is used, regardless of buffer or size."
|
||||
IONBF => true,
|
||||
// "Allowable range: 2 <= size <= INT_MAX".
|
||||
IOFBF | IOLBF => (2..=i32::MAX as u64).contains(&size),
|
||||
_ => false,
|
||||
};
|
||||
Ok(if valid { Ok(0) } else { Err(Invalid(-1)) })
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,10 @@ use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use std::sync::Arc;
|
||||
|
||||
const PROCESS_THREADS_API: &str = "api-ms-win-core-processthreads-l1-1-0.dll";
|
||||
const UCRT: &str = "ucrtbase.dll";
|
||||
const CRT_RUNTIME_API: &str = "api-ms-win-crt-runtime-l1-1-0.dll";
|
||||
/// The exit code `abort` ends the process with (Microsoft Learn, "abort").
|
||||
const ABORT_STATUS: u32 = 3;
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
// ExitProcess does not return (processthreadsapi.h). It stops the guest
|
||||
@@ -20,4 +24,26 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
});
|
||||
registry.alias(PROCESS_THREADS_API, KERNEL32, "ExitProcess");
|
||||
registry.set_status(KERNEL32, "ExitProcess", ServiceStatus::Partial);
|
||||
|
||||
// _exit ends the process without calling the functions registered with
|
||||
// atexit (Microsoft Learn, "exit, _Exit, _exit"). `exit`, which does call
|
||||
// them, is beside `_cexit` in crt_callbacks.rs.
|
||||
let s = Arc::clone(state);
|
||||
registry.register(UCRT, "_exit", move |args, _, _| {
|
||||
// The status is an int, the low half of the first argument.
|
||||
Err(ExitReason::ProcessExit(s.exit_process(args.rcx as u32)))
|
||||
});
|
||||
|
||||
// abort ends the process with exit code 3 and calls no registered
|
||||
// function. It is partial: it prints no message, and it does not call a
|
||||
// SIGABRT handler, which the documentation says it does when one is set.
|
||||
let s = Arc::clone(state);
|
||||
registry.register(UCRT, "abort", move |_, _, _| {
|
||||
Err(ExitReason::ProcessExit(s.exit_process(ABORT_STATUS)))
|
||||
});
|
||||
|
||||
for symbol in ["_exit", "abort"] {
|
||||
registry.alias(CRT_RUNTIME_API, UCRT, symbol);
|
||||
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
}
|
||||
@@ -14,8 +14,9 @@ use crate::x86_table::{
|
||||
/// Architectural x86-64 instruction length limit, in bytes.
|
||||
///
|
||||
/// An instruction may not exceed 15 bytes (Intel SDM Vol. 2A, "Instruction
|
||||
/// Length"). Sequences longer than this are not decodable and are rejected as
|
||||
/// illegal instructions.
|
||||
/// Length"). Decoding stops before a 16th byte would be fetched and reports
|
||||
/// [`DecodeError::TooLong`], a general-protection fault (Intel SDM Vol. 3A,
|
||||
/// 7.15).
|
||||
pub const MAX_INSTRUCTION_LEN: usize = 15;
|
||||
|
||||
/// Number of leading legacy segment prefix bytes (0x64 FS, 0x65 GS) at the
|
||||
@@ -47,6 +48,9 @@ pub struct Form {
|
||||
pub has_modrm: bool,
|
||||
pub memory_only: bool,
|
||||
pub register_only: bool,
|
||||
/// The only ModRM r/m field value the form accepts. Set only on
|
||||
/// register-only forms, so such a form matches exactly one ModRM byte.
|
||||
pub fixed_rm: Option<u8>,
|
||||
pub no_rex_b: bool,
|
||||
/// A 16-byte memory operand may have any alignment.
|
||||
pub unaligned: bool,
|
||||
@@ -204,24 +208,24 @@ pub enum DecodeError<E> {
|
||||
Fetch(E),
|
||||
/// No declared form matches; carries the byte that decided it.
|
||||
Unsupported(u8),
|
||||
/// The instruction would be longer than [`MAX_INSTRUCTION_LEN`] bytes.
|
||||
TooLong,
|
||||
}
|
||||
|
||||
struct Cursor<F> {
|
||||
fetch: F,
|
||||
rip: u64,
|
||||
len: usize,
|
||||
last: u8,
|
||||
}
|
||||
|
||||
impl<E, F: FnMut(u64) -> Result<u8, E>> Cursor<F> {
|
||||
fn u8(&mut self) -> Result<u8, DecodeError<E>> {
|
||||
if self.len == MAX_INSTRUCTION_LEN {
|
||||
return Err(DecodeError::Unsupported(self.last));
|
||||
return Err(DecodeError::TooLong);
|
||||
}
|
||||
let byte =
|
||||
(self.fetch)(self.rip.wrapping_add(self.len as u64)).map_err(DecodeError::Fetch)?;
|
||||
self.len += 1;
|
||||
self.last = byte;
|
||||
Ok(byte)
|
||||
}
|
||||
|
||||
@@ -260,12 +264,7 @@ pub fn decode<E>(
|
||||
rip: u64,
|
||||
fetch: impl FnMut(u64) -> Result<u8, E>,
|
||||
) -> Result<Insn, DecodeError<E>> {
|
||||
let mut cursor = Cursor {
|
||||
fetch,
|
||||
rip,
|
||||
len: 0,
|
||||
last: 0,
|
||||
};
|
||||
let mut cursor = Cursor { fetch, rip, len: 0 };
|
||||
let mut operand_size = false;
|
||||
let mut rep = false;
|
||||
let mut repne = false;
|
||||
@@ -430,7 +429,7 @@ pub fn decode<E>(
|
||||
reg = register((modrm >> 3) & 7, rex_r, size);
|
||||
let mode = modrm >> 6;
|
||||
if mode == 3 {
|
||||
if form.memory_only {
|
||||
if form.memory_only || form.fixed_rm.is_some_and(|field| field != modrm & 7) {
|
||||
return Err(DecodeError::Unsupported(opcode));
|
||||
}
|
||||
rm = Some(RmOperand::Reg(register(modrm & 7, rex_b, rm_size)));
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! the state unchanged. Flags that the architecture leaves undefined keep their
|
||||
//! previous value, which is permitted but not something guests may rely on.
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason, RFlags, Register, cpuid};
|
||||
use crate::cpu::{CpuState, ExitReason, RFlags, Register, X87State, cpuid};
|
||||
use crate::memory::GuestMemory;
|
||||
use crate::x86_decode::{Encoding, Insn, MemOperand, RegOperand, RmOperand, Segment};
|
||||
use crate::x86_simd;
|
||||
@@ -690,6 +690,26 @@ pub fn execute(
|
||||
next = insn.imm;
|
||||
}
|
||||
}
|
||||
// The count is RCX, decremented without changing any flag; LOOPE and
|
||||
// LOOPNE also test ZF (Intel SDM Vol. 2A, LOOP/LOOPcc).
|
||||
Op::Loop | Op::Loope | Op::Loopne => {
|
||||
let count = cpu.gpr[RCX].wrapping_sub(1);
|
||||
cpu.gpr[RCX] = count;
|
||||
let zf_holds = match insn.op {
|
||||
Op::Loope => cpu.flags.zf,
|
||||
Op::Loopne => !cpu.flags.zf,
|
||||
_ => true,
|
||||
};
|
||||
if count != 0 && zf_holds {
|
||||
next = insn.imm;
|
||||
}
|
||||
}
|
||||
// JRCXZ reads RCX and changes nothing (Intel SDM Vol. 2A, Jcc).
|
||||
Op::Jrcxz => {
|
||||
if cpu.gpr[RCX] == 0 {
|
||||
next = insn.imm;
|
||||
}
|
||||
}
|
||||
Op::Ret => {
|
||||
let sp = cpu.gpr[RSP];
|
||||
next = read_mem(memory, sp, 8)?;
|
||||
@@ -700,6 +720,12 @@ pub fn execute(
|
||||
// instruction starts, on one host thread, so guest accesses are already
|
||||
// totally ordered and a fence has nothing further to enforce.
|
||||
Op::Lfence | Op::Mfence | Op::Sfence => {}
|
||||
// The control, status and tag words take their initial values. The
|
||||
// no-wait form checks no pending exception, and the data registers,
|
||||
// which Xenora does not model, are left alone and only tagged empty
|
||||
// (Intel SDM Vol. 2A, "FINIT/FNINIT"). FNINIT also clears the x87
|
||||
// instruction and data pointers and last opcode, which are not modelled.
|
||||
Op::Fninit => cpu.x87 = X87State::INIT,
|
||||
Op::Cpuid => {
|
||||
// The leaf is EAX and the subleaf ECX. Each result is a 32-bit
|
||||
// register write, so the upper halves are cleared.
|
||||
@@ -742,6 +768,28 @@ pub fn execute(
|
||||
Op::Clc => cpu.flags.cf = false,
|
||||
Op::Stc => cpu.flags.cf = true,
|
||||
Op::Cmc => cpu.flags.cf = !cpu.flags.cf,
|
||||
// AH = SF:ZF:0:AF:0:PF:1:CF (Intel SDM Vol. 2A, LAHF).
|
||||
Op::Lahf => {
|
||||
let f = cpu.flags;
|
||||
let ah = u64::from(f.sf) << 7
|
||||
| u64::from(f.zf) << 6
|
||||
| u64::from(f.af) << 4
|
||||
| u64::from(f.pf) << 2
|
||||
| 1 << 1
|
||||
| u64::from(f.cf);
|
||||
cpu.gpr[RAX] = cpu.gpr[RAX] & !0xFF00 | ah << 8;
|
||||
}
|
||||
// SF, ZF, AF, PF and CF from AH bits 7, 6, 4, 2 and 0; OF is
|
||||
// unchanged (Intel SDM Vol. 2B, SAHF).
|
||||
Op::Sahf => {
|
||||
let ah = (cpu.gpr[RAX] >> 8) as u8;
|
||||
let flags = &mut cpu.flags;
|
||||
flags.sf = ah & 0x80 != 0;
|
||||
flags.zf = ah & 0x40 != 0;
|
||||
flags.af = ah & 0x10 != 0;
|
||||
flags.pf = ah & 0x04 != 0;
|
||||
flags.cf = ah & 0x01 != 0;
|
||||
}
|
||||
Op::Hlt => {
|
||||
cpu.rip = next;
|
||||
return Ok(Some(ExitReason::Halt));
|
||||
|
||||
+590
-519
File diff suppressed because it is too large.
Load diff
@@ -13,8 +13,8 @@
|
||||
//! assembled with `clang -target x86_64-apple-macos` and read with `objdump`.
|
||||
|
||||
use xenora_loader::cpu::{
|
||||
CPUID_CMOV, CPUID_LONG_MODE, CPUID_LZCNT, CPUID_POPCNT, CpuState, ExitReason, Interpreter,
|
||||
RFlags, cpuid,
|
||||
CPUID_CMOV, CPUID_LAHF_SAHF, CPUID_LONG_MODE, CPUID_LZCNT, CPUID_POPCNT, CpuState, ExitReason,
|
||||
Interpreter, RFlags, cpuid,
|
||||
};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
@@ -79,9 +79,9 @@ fn every_leaf_returns_its_documented_values() {
|
||||
(1, 0xFFFF_FFFF, [0, 0, 0x0080_0000, 0x0000_8000]),
|
||||
// Highest extended leaf.
|
||||
(0x8000_0000, 0, [0x8000_0001, 0, 0, 0]),
|
||||
// LZCNT is ECX bit 5 and long mode is EDX bit 29.
|
||||
(0x8000_0001, 0, [0, 0, 0x0000_0020, 0x2000_0000]),
|
||||
(0x8000_0001, 7, [0, 0, 0x0000_0020, 0x2000_0000]),
|
||||
// LAHF/SAHF is ECX bit 0, LZCNT ECX bit 5 and long mode EDX bit 29.
|
||||
(0x8000_0001, 0, [0, 0, 0x0000_0021, 0x2000_0000]),
|
||||
(0x8000_0001, 7, [0, 0, 0x0000_0021, 0x2000_0000]),
|
||||
// Everything else, above or between the highest leaves, is zeros.
|
||||
(2, 0, [0; 4]),
|
||||
(4, 0, [0; 4]),
|
||||
@@ -129,8 +129,14 @@ fn every_leaf_returns_its_documented_values() {
|
||||
.collect();
|
||||
assert_eq!(vendor, b"Xenora guest");
|
||||
assert_eq!(
|
||||
(CPUID_POPCNT, CPUID_CMOV, CPUID_LZCNT, CPUID_LONG_MODE),
|
||||
(1 << 23, 1 << 15, 1 << 5, 1 << 29)
|
||||
(
|
||||
CPUID_POPCNT,
|
||||
CPUID_CMOV,
|
||||
CPUID_LAHF_SAHF,
|
||||
CPUID_LZCNT,
|
||||
CPUID_LONG_MODE
|
||||
),
|
||||
(1 << 23, 1 << 15, 1, 1 << 5, 1 << 29)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -189,6 +195,10 @@ fn reported_features_have_all_their_instructions_in_the_fixtures() {
|
||||
decodable(&format!("{name} {high}, {}", memory(bits)));
|
||||
}
|
||||
}
|
||||
// LAHF and SAHF have one form each and no operands.
|
||||
assert_ne!(cpuid(0x8000_0001, 0)[ECX] & CPUID_LAHF_SAHF, 0);
|
||||
decodable("lahf");
|
||||
decodable("sahf");
|
||||
// Long mode: 64-bit operands and the registers only it has.
|
||||
assert_ne!(cpuid(0x8000_0001, 0)[EDX] & CPUID_LONG_MODE, 0);
|
||||
decodable("add r9, r12");
|
||||
@@ -232,7 +242,6 @@ fn unreported_features_each_have_an_instruction_that_is_refused() {
|
||||
("RDSEED", 7, EBX, 18, &[0x0F, 0xC7, 0xF8]), // rdseed eax
|
||||
("ADX", 7, EBX, 19, &[0x66, 0x0F, 0x38, 0xF6, 0xC1]), // adcx eax, ecx
|
||||
("SHA", 7, EBX, 29, &[0x0F, 0x38, 0xC9, 0xC1]), // sha1msg1 xmm0, xmm1
|
||||
("LAHF/SAHF", 0x8000_0001, ECX, 0, &[0x9F]), // lahf
|
||||
("PREFETCHW", 0x8000_0001, ECX, 8, &[0x0F, 0x0D, 0x0E]), // prefetchw [rsi]
|
||||
("SYSCALL/SYSRET", 0x8000_0001, EDX, 11, &[0x48, 0x0F, 0x07]), // sysretq
|
||||
("RDTSCP", 0x8000_0001, EDX, 27, &[0x0F, 0x01, 0xF9]), // rdtscp
|
||||
|
||||
@@ -41,6 +41,8 @@
|
||||
//! `f=*` and `keep=` require the initial value. A case without `f=` on the
|
||||
//! left runs with all flags clear and again with all flags set.
|
||||
//! * `mx=` is MXCSR; `mx=~20:1b88` ignores the bits in `20`. `=?` ignores a value.
|
||||
//! * `fcw=`, `fsw=` and `ftw=` are the x87 control, status and tag words. Every
|
||||
//! case starts with all three away from their FNINIT values.
|
||||
//! * Symbols: `D` writable data, `U` the unmapped page after it, `R` read-only
|
||||
//! data, `S` stack, `C` code, `FSB` and `GSB` segment bases.
|
||||
//! * Faults: `DE`, `GP`, `UD`, `XM`, and page faults `PFR`, `PFW`, `PFX` with
|
||||
@@ -50,7 +52,7 @@
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::fmt::Write as _;
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, Mxcsr, RFlags};
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, Mxcsr, RFlags, X87State};
|
||||
use xenora_loader::dbt::{DbtEngine, is_native};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
use xenora_loader::x86_decode::decode;
|
||||
@@ -598,6 +600,15 @@ const FLAG_MOVES: &str = r"
|
||||
SDM 2A LAHF
|
||||
lahf: rax=8877665544332211 f=CPASO => rax=8877665544339711 f=*
|
||||
lahf_zero: rax=8877665544332211 f=Z => rax=8877665544334211 f=*
|
||||
lahf_carry_only: rax=ffffffffffffffff f=C => rax=ffffffffffff03ff f=*
|
||||
lahf_parity_only: rax=ffffffffffffffff f=P => rax=ffffffffffff06ff f=*
|
||||
lahf_adjust_only: rax=ffffffffffffffff f=A => rax=ffffffffffff12ff f=*
|
||||
lahf_sign_only: rax=ffffffffffffffff f=S => rax=ffffffffffff82ff f=*
|
||||
lahf_does_not_store_of: rax=ffffffffffffffff f=O => rax=ffffffffffff02ff f=*
|
||||
@ rex.w lahf
|
||||
489f
|
||||
SDM 2A LAHF; 2A 2.2.1.2
|
||||
lahf_rex_w_changes_nothing: rax=ffffffffffffffff f=CO => rax=ffffffffffff03ff f=*
|
||||
@ sahf; lahf
|
||||
9e 9f
|
||||
SDM 2B SAHF
|
||||
@@ -606,6 +617,12 @@ sahf_ignores_bits_1_3_5: rax=ff00 f=O => rax=d700 f=CPAZSO
|
||||
9e
|
||||
SDM 2B SAHF
|
||||
sahf_clear_keeps_of: rax=2800 f=OC => f=cpazsO
|
||||
sahf_carry_only: rax=100 f=O => f=CpazsO
|
||||
sahf_parity_only: rax=400 f=O => f=cPazsO
|
||||
sahf_adjust_only: rax=1000 f=O => f=cpAzsO
|
||||
sahf_zero_only: rax=4000 f=O => f=cpaZsO
|
||||
sahf_sign_only: rax=8000 f=O => f=cpazSO
|
||||
sahf_reads_only_ah: rax=ffffffffffff00ff f=CPAZS => f=cpazso
|
||||
@ stc
|
||||
f9
|
||||
SDM 2B STC
|
||||
@@ -1082,6 +1099,8 @@ cmov_all_unsigned_below_signed_greater: rax=1 rbx=80000000 => rcx=1 r8=1 r9=0 r1
|
||||
b800000000 e305 b801000000 90
|
||||
SDM 2A Jcc
|
||||
jrcxz_tests_all_64_bits: rcx=100000000 => rax=1 f=*
|
||||
jrcxz_sees_bit_63: rcx=8000000000000000 => rax=1 f=*
|
||||
jrcxz_taken_at_zero_keeps_rcx: rcx=0 => rax=0 rcx=0 f=*
|
||||
@ mov eax, 0; jecxz 1f; mov eax, 1; 1: nop
|
||||
b800000000 67e305 b801000000 90
|
||||
SDM 2A Jcc
|
||||
@@ -1094,6 +1113,24 @@ loop_decrements_rcx_without_flags: rax=0 rcx=3 => rax=3 rcx=0 f=*
|
||||
488d4001 e0fa
|
||||
SDM 2A LOOP
|
||||
loopne_stops_on_zero_flag: rax=0 rcx=5 f=Z => rax=1 rcx=4 f=*
|
||||
@ mov eax, 0; loop 1f; mov eax, 1; 1: nop
|
||||
b800000000 e205 b801000000 90
|
||||
SDM 2A LOOP
|
||||
loop_from_zero_wraps_and_branches: rcx=0 => rax=0 rcx=ffffffffffffffff f=*
|
||||
loop_at_one_falls_through: rcx=1 => rax=1 rcx=0 f=*
|
||||
loop_counts_all_64_bits: rcx=100000000 => rax=0 rcx=ffffffff f=*
|
||||
@ mov eax, 0; loope 1f; mov eax, 1; 1: nop
|
||||
b800000000 e105 b801000000 90
|
||||
SDM 2A LOOP
|
||||
loope_taken_with_zf: rcx=2 f=Z => rax=0 rcx=1 f=*
|
||||
loope_not_taken_without_zf: rcx=2 f=CPASO => rax=1 rcx=1 f=*
|
||||
loope_count_expires_with_zf: rcx=1 f=Z => rax=1 rcx=0 f=*
|
||||
@ mov eax, 0; loopne 1f; mov eax, 1; 1: nop
|
||||
b800000000 e005 b801000000 90
|
||||
SDM 2A LOOP
|
||||
loopne_taken_without_zf: rcx=2 f=CPASO => rax=0 rcx=1 f=*
|
||||
loopne_not_taken_with_zf: rcx=2 f=Z => rax=1 rcx=1 f=*
|
||||
loopne_count_expires_without_zf: rcx=1 => rax=1 rcx=0 f=*
|
||||
";
|
||||
|
||||
const STACK_AND_CALLS: &str = r"
|
||||
@@ -1533,6 +1570,36 @@ fences_change_no_register_or_flag: rax=1122334455667788 rbx=99aabbccddeeff00 =>
|
||||
fences_ignore_the_rm_field: rax=1122334455667788 => f=*
|
||||
";
|
||||
|
||||
/// FNINIT, the only x87 instruction (#378). The three words it sets are all the
|
||||
/// x87 state there is: no data register, pointer or last opcode is modelled, and
|
||||
/// nothing can read the words back yet, so the cases look at guest state.
|
||||
const X87_INIT: &str = r"
|
||||
@ fninit
|
||||
dbe3
|
||||
SDM 2A FINIT/FNINIT (Operation); 1 8.1.5 (control word 037FH); 1 8.1.7 (tag FFFFH)
|
||||
fninit_sets_control_status_and_tag: fcw=0040 fsw=3a41 ftw=0000 => fcw=037f fsw=0 ftw=ffff f=*
|
||||
fninit_from_every_bit_set: fcw=ffff fsw=ffff ftw=0000 => fcw=037f fsw=0 ftw=ffff f=*
|
||||
fninit_from_every_bit_clear: fcw=0 fsw=0 ftw=0 => fcw=037f fsw=0 ftw=ffff f=*
|
||||
fninit_twice_is_the_same: fcw=037f fsw=0 ftw=ffff => fcw=037f fsw=0 ftw=ffff f=*
|
||||
fninit_from_the_harness_default: => fcw=037f fsw=0 ftw=ffff f=*
|
||||
@ fninit
|
||||
dbe3
|
||||
SDM 2A FINIT/FNINIT (the x87 words only; Flags Affected: C0 to C3 cleared, which are status-word bits)
|
||||
fninit_keeps_registers_flags_xmm_and_mxcsr: rax=1122334455667788 rbx=99aabbccddeeff00 x3=q:0123456789abcdef,fedcba9876543210 mx=5fbf => fcw=037f fsw=0 ftw=ffff f=*
|
||||
@ mov [rdi], rax; fninit; mov rbx, [rdi]
|
||||
488907 dbe3 488b1f
|
||||
SDM 2A FINIT/FNINIT
|
||||
fninit_touches_no_memory: rdi=D rax=1122334455667788 m0=0000000000000000 => rbx=1122334455667788 m0=8877665544332211 fcw=037f fsw=0 ftw=ffff f=*
|
||||
@ fninit; add al, bl
|
||||
dbe3 00d8
|
||||
SDM 2A FINIT/FNINIT; 2A ADD
|
||||
fninit_then_integer_code_runs_on: rax=7f rbx=1 => rax=80 fcw=037f fsw=0 ftw=ffff f=cpAzSO
|
||||
@ add al, bl
|
||||
00d8
|
||||
SDM 2A ADD (no x87 state is named)
|
||||
integer_code_keeps_the_x87_words: rax=7f rbx=1 fcw=1a2b fsw=3c4d ftw=5e6f => rax=80 f=cpAzSO
|
||||
";
|
||||
|
||||
const MEMORY_FAULTS: &str = r"
|
||||
@ mov r8d, 1; add al, bl; mov rcx, [rsi]; mov r9d, 2
|
||||
41b801000000 00d8 !488b0e 41b902000000
|
||||
@@ -2814,11 +2881,23 @@ dpps_mask: x1=d:3f800000,40000000,40400000,40800000 x2=d:3f800000,3f800000,3f800
|
||||
movddup_movsldup_movshdup: x2=d:7f800001,2,3,4 => x1=d:7f800001,2,7f800001,2 x3=d:7f800001,7f800001,3,3 x4=d:2,2,4,4 f=*
|
||||
";
|
||||
|
||||
const DEFECT_OVERLONG_INSTRUCTION: &str = r"
|
||||
const INSTRUCTION_LENGTH: &str = r"
|
||||
@ .byte 0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x01,0xd8
|
||||
!666666666666666666666666666601d8
|
||||
SDM 3A 7.15 Interrupt 13 (instruction length over 15 bytes)
|
||||
sixteen_byte_redundant_operand_size_prefixes: => ! GP
|
||||
@ .byte 0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x05,0x34,0x12
|
||||
666666666666666666666666053412
|
||||
SDM 2A 2.2.1 (15-byte limit); 2A ADD
|
||||
fifteen_bytes_ending_in_the_immediate_execute: rax=ffffffffffff0001 => rax=ffffffffffff1235 f=cPazso
|
||||
@ .byte 0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x05,0x34,0x12
|
||||
!66666666666666666666666666053412
|
||||
SDM 3A 7.15 Interrupt 13 (instruction length over 15 bytes)
|
||||
sixteenth_byte_in_the_immediate_is_gp: rax=1 => ! GP
|
||||
@ mov eax, 1; .byte 0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x05,0x34,0x12
|
||||
b801000000 !66666666666666666666666666053412
|
||||
SDM 3A 7.15 Interrupt 13 (instruction length over 15 bytes)
|
||||
overlong_after_an_instruction_retires_it_first: rax=ffffffffffffffff => rax=1 ! GP
|
||||
";
|
||||
|
||||
const PAGE_CROSSING: &str = r"
|
||||
@@ -2875,6 +2954,7 @@ const GROUPS: &[(&str, &str)] = &[
|
||||
("fs_gs", FS_GS),
|
||||
("decoding", DECODING),
|
||||
("fences", FENCES),
|
||||
("x87_init", X87_INIT),
|
||||
("memory_faults", MEMORY_FAULTS),
|
||||
("straddling_fault_address", STRADDLING_FAULT_ADDRESS),
|
||||
("noncanonical_address", NONCANONICAL_ADDRESS),
|
||||
@@ -2889,7 +2969,7 @@ const GROUPS: &[(&str, &str)] = &[
|
||||
("fp_packed_and_sticky", FP_PACKED_AND_STICKY),
|
||||
("fp_mxcsr_and_unmasked", FP_MXCSR_AND_UNMASKED),
|
||||
("fp_beyond_sse2", FP_BEYOND_SSE2),
|
||||
("defect_overlong_instruction", DEFECT_OVERLONG_INSTRUCTION),
|
||||
("instruction_length", INSTRUCTION_LENGTH),
|
||||
("exact_unmasked_overflow", EXACT_UNMASKED_OVERFLOW),
|
||||
("page_crossing", PAGE_CROSSING),
|
||||
];
|
||||
@@ -2922,16 +3002,11 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("haddps_hsubpd_addsubps", 0),
|
||||
("insertps_zero_mask", 0),
|
||||
("jecxz_tests_low_32_bits", 1),
|
||||
("jrcxz_tests_all_64_bits", 1),
|
||||
("lahf", 0),
|
||||
("lahf_zero", 0),
|
||||
("lea64_addr32_truncates_effective_address", 0),
|
||||
("lock_btc_memory", 0),
|
||||
("lodsd_zero_extends", 1),
|
||||
("lodsd_zero_extends_df_clear", 0),
|
||||
("lodsw_preserves_upper48", 1),
|
||||
("loop_decrements_rcx_without_flags", 1),
|
||||
("loopne_stops_on_zero_flag", 1),
|
||||
("maskmovdqu_selects_bytes", 0),
|
||||
("mov_moffs64_load", 0),
|
||||
("mov_moffs8_store", 0),
|
||||
@@ -2973,8 +3048,6 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("roundps_uses_mxcsr_rc", 0),
|
||||
("roundsd_suppress_precision", 0),
|
||||
("roundss_imm_modes", 0),
|
||||
("sahf_clear_keeps_of", 0),
|
||||
("sahf_ignores_bits_1_3_5", 0),
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -3219,6 +3292,13 @@ fn initial_cpu() -> CpuState {
|
||||
}
|
||||
cpu.fs_base = FS_BASE;
|
||||
cpu.gs_base = GS_BASE;
|
||||
// None of the three is what FNINIT sets, so a reset is always visible and
|
||||
// an instruction that wrongly resets one is caught by any case.
|
||||
cpu.x87 = X87State {
|
||||
control: 0x0c40,
|
||||
status: 0x2b05,
|
||||
tag: 0x5a5a,
|
||||
};
|
||||
cpu
|
||||
}
|
||||
|
||||
@@ -3279,6 +3359,13 @@ fn apply(text: &str, expected: &mut Expected) {
|
||||
expected.cpu.rip = value(data);
|
||||
} else if key == "gsbase" {
|
||||
expected.cpu.gs_base = value(data);
|
||||
} else if let Some(word) = match key {
|
||||
"fcw" => Some(&mut expected.cpu.x87.control),
|
||||
"fsw" => Some(&mut expected.cpu.x87.status),
|
||||
"ftw" => Some(&mut expected.cpu.x87.tag),
|
||||
_ => None,
|
||||
} {
|
||||
*word = u16::try_from(value(data)).expect("a 16-bit x87 word");
|
||||
} else if key == "mx" {
|
||||
if data == "?" {
|
||||
expected.mxcsr_mask = 0;
|
||||
@@ -3513,6 +3600,9 @@ fn check(case: &Case, engine: Engine, initial_flags: u8) -> Result<(), String> {
|
||||
if (cpu.fs_base, cpu.gs_base) != (want.cpu.fs_base, want.cpu.gs_base) {
|
||||
text.push_str(" segment base changed;");
|
||||
}
|
||||
if cpu.x87 != want.cpu.x87 {
|
||||
let _ = write!(text, " x87={:04x?} want {:04x?};", cpu.x87, want.cpu.x87);
|
||||
}
|
||||
let memory_text = Image::store(&memory).differences(&want.image);
|
||||
if !memory_text.is_empty() {
|
||||
let _ = write!(text, " memory{memory_text};");
|
||||
@@ -3655,6 +3745,11 @@ fn fences() {
|
||||
check_group(FENCES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn x87_init() {
|
||||
check_group(X87_INIT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_faults() {
|
||||
check_group(MEMORY_FAULTS);
|
||||
@@ -3726,9 +3821,8 @@ fn fp_beyond_sse2() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "known defect (#155): an instruction over 15 bytes is illegal, not #GP"]
|
||||
fn defect_overlong_instruction() {
|
||||
check_group(DEFECT_OVERLONG_INSTRUCTION);
|
||||
fn instruction_length() {
|
||||
check_group(INSTRUCTION_LENGTH);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! LOOP, LOOPE, LOOPNE and JRCXZ (issue #396).
|
||||
//!
|
||||
//! Expected results come from a step-by-step model written from the operation
|
||||
//! sections of the Intel SDM Vol. 2A for LOOP/LOOPcc and Jcc. The model never
|
||||
//! decodes or calls the production semantics. Encodings were assembled with
|
||||
//! `clang -target x86_64-apple-macos` and read with `objdump`. Nothing was
|
||||
//! compared with x86 hardware.
|
||||
//!
|
||||
//! In 64-bit mode with the default address size the count is RCX. LOOP
|
||||
//! decrements it without changing a flag and branches while the result is not
|
||||
//! zero; LOOPE also needs ZF set and LOOPNE ZF clear. JRCXZ branches when RCX is
|
||||
//! zero and changes nothing.
|
||||
|
||||
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, RFlags};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
|
||||
const ENTRY: u64 = 0x1000;
|
||||
|
||||
const RAX: usize = 0;
|
||||
const RCX: usize = 1;
|
||||
const RBX: usize = 3;
|
||||
const RDI: usize = 7;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum Kind {
|
||||
Loop,
|
||||
Loope,
|
||||
Loopne,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
fn opcode(self) -> u8 {
|
||||
match self {
|
||||
Kind::Loopne => 0xE0,
|
||||
Kind::Loope => 0xE1,
|
||||
Kind::Loop => 0xE2,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// ```text
|
||||
/// top: inc rbx 48 ff c3
|
||||
/// cmp rbx, rdi 48 39 fb
|
||||
/// jmp next eb 00 ; ends a translated block
|
||||
/// next: loop/loope/loopne top
|
||||
/// hlt f4
|
||||
/// ```
|
||||
fn loop_program(kind: Kind) -> Vec<u8> {
|
||||
vec![
|
||||
0x48,
|
||||
0xFF,
|
||||
0xC3,
|
||||
0x48,
|
||||
0x39,
|
||||
0xFB,
|
||||
0xEB,
|
||||
0x00,
|
||||
kind.opcode(),
|
||||
0xF6,
|
||||
0xF4,
|
||||
]
|
||||
}
|
||||
|
||||
/// Start of each instruction of [`loop_program`], and the end of HLT.
|
||||
const OFFSETS: [u64; 6] = [0, 3, 6, 8, 10, 11];
|
||||
|
||||
fn image(code: &[u8]) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
|
||||
.unwrap();
|
||||
memory
|
||||
}
|
||||
|
||||
/// The interpreter and the DBT, each from its own copy of the state. The DBT
|
||||
/// result carries the state it left in its own copy.
|
||||
fn both(cpu: &CpuState, code: &[u8], budget: usize) -> [(&'static str, ExecutionResult); 2] {
|
||||
let mut interpreted = image(code);
|
||||
let result = Interpreter::new(cpu.clone(), &mut interpreted, budget).run();
|
||||
let mut translated = image(code);
|
||||
let mut state = cpu.clone();
|
||||
let mut native = DbtEngine::new(64 * 1024)
|
||||
.unwrap()
|
||||
.run(&mut state, &mut translated, budget);
|
||||
native.final_state = state;
|
||||
[("interpreter", result), ("DBT", native)]
|
||||
}
|
||||
|
||||
/// What the model predicts after at most `budget` instructions.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct Outcome {
|
||||
exit: ExitReason,
|
||||
executed: usize,
|
||||
rip: u64,
|
||||
rcx: u64,
|
||||
rbx: u64,
|
||||
zf: bool,
|
||||
}
|
||||
|
||||
fn model(kind: Kind, rcx: u64, rbx: u64, rdi: u64, zf: bool, budget: usize) -> Outcome {
|
||||
let (mut rcx, mut rbx, mut zf) = (rcx, rbx, zf);
|
||||
let mut at = 0;
|
||||
let mut executed = 0;
|
||||
while executed < budget {
|
||||
executed += 1;
|
||||
at = match at {
|
||||
// INC writes ZF too (Intel SDM Vol. 2A, INC).
|
||||
0 => {
|
||||
rbx = rbx.wrapping_add(1);
|
||||
zf = rbx == 0;
|
||||
1
|
||||
}
|
||||
1 => {
|
||||
zf = rbx == rdi;
|
||||
2
|
||||
}
|
||||
2 => 3,
|
||||
3 => {
|
||||
rcx = rcx.wrapping_sub(1);
|
||||
let condition = match kind {
|
||||
Kind::Loop => true,
|
||||
Kind::Loope => zf,
|
||||
Kind::Loopne => !zf,
|
||||
};
|
||||
if rcx != 0 && condition { 0 } else { 4 }
|
||||
}
|
||||
_ => {
|
||||
return Outcome {
|
||||
exit: ExitReason::Halt,
|
||||
executed,
|
||||
rip: ENTRY + OFFSETS[5],
|
||||
rcx,
|
||||
rbx,
|
||||
zf,
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
Outcome {
|
||||
exit: ExitReason::StepLimitExceeded,
|
||||
executed,
|
||||
rip: ENTRY + OFFSETS[at],
|
||||
rcx,
|
||||
rbx,
|
||||
zf,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loops_match_the_model_for_every_count_match_point_and_budget() {
|
||||
let mut checked = 0;
|
||||
for kind in [Kind::Loop, Kind::Loope, Kind::Loopne] {
|
||||
let code = loop_program(kind);
|
||||
for rcx in [0, 1, 2, 3, 5, 0x1_0000_0000] {
|
||||
// RDI is the value of RBX after the iteration whose CMP sets ZF;
|
||||
// 0 never matches within these counts.
|
||||
for rdi in [0, 1, 2, 3, 4] {
|
||||
for zf in [false, true] {
|
||||
// Budgets that stop before, inside and after the loop.
|
||||
for budget in [1, 3, 4, 5, 8, 9, 11, 13, 22, 200] {
|
||||
let wanted = model(kind, rcx, 0, rdi, zf, budget);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RCX] = rcx;
|
||||
cpu.gpr[RDI] = rdi;
|
||||
cpu.flags.zf = zf;
|
||||
for (engine, result) in both(&cpu, &code, budget) {
|
||||
let state = &result.final_state;
|
||||
let found = Outcome {
|
||||
exit: result.exit_reason,
|
||||
executed: result.instructions_executed,
|
||||
rip: state.rip,
|
||||
rcx: state.gpr[RCX],
|
||||
rbx: state.gpr[RBX],
|
||||
zf: state.flags.zf,
|
||||
};
|
||||
assert_eq!(
|
||||
found, wanted,
|
||||
"{kind:?} rcx={rcx:#x} rdi={rdi} zf={zf} budget={budget} on the {engine}"
|
||||
);
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(checked, 3 * 6 * 5 * 2 * 10 * 2);
|
||||
}
|
||||
|
||||
/// ```text
|
||||
/// mov eax, 7 b8 07 00 00 00
|
||||
/// jrcxz done e3 05
|
||||
/// mov eax, 1 b8 01 00 00 00
|
||||
/// done: hlt f4
|
||||
/// ```
|
||||
#[test]
|
||||
fn jrcxz_branches_only_on_a_zero_rcx_and_changes_nothing() {
|
||||
let code = [
|
||||
0xB8, 0x07, 0x00, 0x00, 0x00, 0xE3, 0x05, 0xB8, 0x01, 0x00, 0x00, 0x00, 0xF4,
|
||||
];
|
||||
let mut values = vec![0, 1, u64::MAX];
|
||||
values.extend((0..64).map(|bit| 1u64 << bit));
|
||||
for rcx in values {
|
||||
for flags in [RFlags::default(), all_flags()] {
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RCX] = rcx;
|
||||
cpu.flags = flags;
|
||||
let mut wanted = cpu.clone();
|
||||
wanted.gpr[RAX] = if rcx == 0 { 7 } else { 1 };
|
||||
wanted.rip = ENTRY + code.len() as u64;
|
||||
for (engine, result) in both(&cpu, &code, 8) {
|
||||
assert_eq!(
|
||||
result.exit_reason,
|
||||
ExitReason::Halt,
|
||||
"rcx={rcx:#x} {engine}"
|
||||
);
|
||||
let executed = if rcx == 0 { 3 } else { 4 };
|
||||
assert_eq!(
|
||||
result.instructions_executed, executed,
|
||||
"rcx={rcx:#x} {engine}"
|
||||
);
|
||||
assert_eq!(result.final_state, wanted, "rcx={rcx:#x} {engine}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// LOOP from RCX = 0 wraps to 2^64 - 1 and branches. With a budget the loop
|
||||
/// stops early, and both engines agree on the whole state.
|
||||
#[test]
|
||||
fn loop_from_zero_wraps_and_keeps_every_flag() {
|
||||
let code = loop_program(Kind::Loop);
|
||||
for flags in [RFlags::default(), all_flags()] {
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RDI] = 1;
|
||||
cpu.flags = flags;
|
||||
let [(_, interpreted), (_, translated)] = both(&cpu, &code, 4);
|
||||
assert_eq!(interpreted.exit_reason, ExitReason::StepLimitExceeded);
|
||||
assert_eq!(interpreted.final_state.gpr[RCX], u64::MAX);
|
||||
assert_eq!(interpreted.final_state.rip, ENTRY);
|
||||
// INC and CMP set the flags; LOOP leaves them as CMP left them.
|
||||
let after_cmp = model(Kind::Loop, 0, 0, 1, flags.zf, 2).zf;
|
||||
assert_eq!(interpreted.final_state.flags.zf, after_cmp);
|
||||
assert_eq!(interpreted.final_state, translated.final_state);
|
||||
assert_eq!(interpreted.exit_reason, translated.exit_reason);
|
||||
}
|
||||
}
|
||||
|
||||
fn all_flags() -> RFlags {
|
||||
RFlags {
|
||||
cf: true,
|
||||
zf: true,
|
||||
sf: true,
|
||||
of: true,
|
||||
pf: true,
|
||||
af: true,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! The C runtime's `exit`, `_exit` and `abort` (issue #395), called from
|
||||
//! translated guest code through a bound import table.
|
||||
//!
|
||||
//! Expected behaviour is from the Microsoft Learn pages "exit, _Exit, _exit"
|
||||
//! (`exit` calls the functions registered by `atexit` "in last-in-first-out
|
||||
//! (LIFO) order"; `_exit` terminates "without ... processing atexit or _onexit
|
||||
//! functions") and "abort" ("calls _exit to terminate the process with exit
|
||||
//! code 3"), and from ISO C 7.22.4.2 and 7.22.4.4 for a function registered
|
||||
//! while `exit` runs. Calling `exit` again from a registered function is
|
||||
//! undefined in ISO C; the test for it states Xenora's rule. The order each
|
||||
//! test expects is the order in which it registered its functions. The guest
|
||||
//! code is original.
|
||||
|
||||
mod support;
|
||||
|
||||
use support::*;
|
||||
use xenora_loader::cpu::ExitReason;
|
||||
use xenora_loader::import_table::ImportName;
|
||||
use xenora_loader::imports::{ImportRegistry, ServiceStatus};
|
||||
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
|
||||
|
||||
const KERNEL32: &str = "kernel32.dll";
|
||||
const UCRT: &str = "ucrtbase.dll";
|
||||
const RUNTIME: &str = "api-ms-win-crt-runtime-l1-1-0.dll";
|
||||
|
||||
const EXIT: usize = 0;
|
||||
const ATEXIT: usize = 3;
|
||||
const IMPORTS: &[(&str, &str)] = &[
|
||||
(UCRT, "exit"),
|
||||
(UCRT, "_exit"),
|
||||
(UCRT, "abort"),
|
||||
(UCRT, "atexit"),
|
||||
(RUNTIME, "_crt_atexit"),
|
||||
(RUNTIME, "_cexit"),
|
||||
(KERNEL32, "CreateEventW"),
|
||||
(KERNEL32, "SetLastError"),
|
||||
];
|
||||
/// The same imports as a program built with mingw-w64 names the three: by the
|
||||
/// runtime API set.
|
||||
const BY_API_SET: &[(&str, &str)] = &[
|
||||
(RUNTIME, "exit"),
|
||||
(RUNTIME, "_exit"),
|
||||
(RUNTIME, "abort"),
|
||||
(UCRT, "atexit"),
|
||||
(RUNTIME, "_crt_atexit"),
|
||||
(RUNTIME, "_cexit"),
|
||||
(KERNEL32, "CreateEventW"),
|
||||
(KERNEL32, "SetLastError"),
|
||||
];
|
||||
|
||||
/// A decimal log of the registered functions that ran, oldest digit first.
|
||||
const LOG: u64 = SCRATCH;
|
||||
/// Set to one by code placed after a call that must not return.
|
||||
const RETURNED: u64 = SCRATCH + 0x100;
|
||||
|
||||
/// Guest address of the stub `call [slot]; hlt` for import `index`.
|
||||
fn stub(index: usize) -> u64 {
|
||||
BASE + u64::from(CODE_RVA) + 16 * index as u64
|
||||
}
|
||||
|
||||
/// Guest address of the import address table slot of import `index`, read
|
||||
/// from the displacement of its stub.
|
||||
fn slot(guest: &Guest, index: usize) -> u64 {
|
||||
let displacement = guest.u32_at(stub(index) + 2) as i32;
|
||||
(stub(index) + 6).wrapping_add_signed(i64::from(displacement))
|
||||
}
|
||||
|
||||
// Routine indices. Routines are 32 bytes apart.
|
||||
const APPEND_1: usize = 0;
|
||||
const APPEND_2: usize = 1;
|
||||
const APPEND_3: usize = 2;
|
||||
const APPEND_4: usize = 3;
|
||||
const APPEND_5: usize = 4;
|
||||
const REGISTER_4_THEN_APPEND_5: usize = 5;
|
||||
const EXIT_AGAIN: usize = 6;
|
||||
/// The status the `EXIT_AGAIN` routine exits with.
|
||||
const SECOND_STATUS: u32 = 77;
|
||||
|
||||
/// `log = log * 10 + digit; return 0`
|
||||
fn append(digit: u8) -> Vec<u8> {
|
||||
let mut code = vec![0x48, 0xB8]; // mov rax, LOG
|
||||
code.extend(LOG.to_le_bytes());
|
||||
code.extend([
|
||||
0x48, 0x8B, 0x08, // mov rcx, [rax]
|
||||
0x48, 0x6B, 0xC9, 0x0A, // imul rcx, rcx, 10
|
||||
0x48, 0x83, 0xC1, digit, // add rcx, digit
|
||||
0x48, 0x89, 0x08, // mov [rax], rcx
|
||||
0x31, 0xC0, // xor eax, eax
|
||||
0xC3, // ret
|
||||
]);
|
||||
code
|
||||
}
|
||||
|
||||
fn rel32(from_end: u64, to: u64) -> [u8; 4] {
|
||||
(to.wrapping_sub(from_end) as u32).to_le_bytes()
|
||||
}
|
||||
|
||||
/// A registered function that registers `APPEND_4` with `atexit`, through the
|
||||
/// import address table as compiled code would, and then appends 5.
|
||||
fn register_4_then_append_5(atexit_slot: u64) -> Vec<u8> {
|
||||
let at = routine(REGISTER_4_THEN_APPEND_5);
|
||||
let mut code = vec![0x48, 0x83, 0xEC, 0x28]; // sub rsp, 0x28
|
||||
code.extend([0x48, 0x8D, 0x0D]); // lea rcx, [rip + APPEND_4]
|
||||
code.extend(rel32(at + 11, routine(APPEND_4)));
|
||||
code.extend([0xFF, 0x15]); // call [rip + atexit slot]
|
||||
code.extend(rel32(at + 17, atexit_slot));
|
||||
code.extend([0x48, 0x83, 0xC4, 0x28]); // add rsp, 0x28
|
||||
code.push(0xE9); // jmp APPEND_5
|
||||
code.extend(rel32(at + 26, routine(APPEND_5)));
|
||||
code
|
||||
}
|
||||
|
||||
/// A registered function that calls `exit(SECOND_STATUS)`. The code after the
|
||||
/// call would record that `exit` returned.
|
||||
fn exit_again() -> Vec<u8> {
|
||||
let at = routine(EXIT_AGAIN);
|
||||
let mut code = vec![0x48, 0x83, 0xEC, 0x28]; // sub rsp, 0x28
|
||||
code.push(0xB9); // mov ecx, SECOND_STATUS
|
||||
code.extend(SECOND_STATUS.to_le_bytes());
|
||||
code.push(0xE8); // call <exit stub>
|
||||
code.extend(rel32(at + 14, stub(EXIT)));
|
||||
code.extend([0x48, 0xB8]); // mov rax, RETURNED
|
||||
code.extend(RETURNED.to_le_bytes());
|
||||
code.extend([
|
||||
0xC6, 0x00, 0x01, // mov byte ptr [rax], 1
|
||||
0x48, 0x83, 0xC4, 0x28, // add rsp, 0x28
|
||||
0xC3, // ret
|
||||
]);
|
||||
code
|
||||
}
|
||||
|
||||
fn guest_with(imports: &'static [(&'static str, &'static str)]) -> Guest {
|
||||
// The slot of `atexit` depends only on the import list, so a guest built
|
||||
// without routines tells where it is.
|
||||
let atexit_slot = slot(&Guest::new(imports, &[]), ATEXIT);
|
||||
let routines = [
|
||||
append(1),
|
||||
append(2),
|
||||
append(3),
|
||||
append(4),
|
||||
append(5),
|
||||
register_4_then_append_5(atexit_slot),
|
||||
exit_again(),
|
||||
];
|
||||
let guest = Guest::new(imports, &routines);
|
||||
assert_eq!(slot(&guest, ATEXIT), atexit_slot);
|
||||
guest
|
||||
}
|
||||
|
||||
fn guest() -> Guest {
|
||||
guest_with(IMPORTS)
|
||||
}
|
||||
|
||||
fn register(guest: &mut Guest, symbol: &str, index: usize) {
|
||||
assert_eq!(guest.call(symbol, &[routine(index)]) as u32, 0, "{symbol}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_runs_registered_functions_most_recent_first_then_ends_the_process() {
|
||||
for imports in [IMPORTS, BY_API_SET] {
|
||||
let mut guest = guest_with(imports);
|
||||
// atexit and _crt_atexit feed one list.
|
||||
register(&mut guest, "atexit", APPEND_1);
|
||||
register(&mut guest, "_crt_atexit", APPEND_2);
|
||||
register(&mut guest, "atexit", APPEND_3);
|
||||
assert_eq!(guest.u64_at(LOG), 0);
|
||||
assert_eq!(guest.state.exit_status(), None);
|
||||
// The status is an int: the upper half of RCX is not part of it.
|
||||
let (_, exit) = guest.run("exit", &[0xAAAA_BBBB_1234_5678]);
|
||||
assert_eq!(exit, ExitReason::ProcessExit(0x1234_5678));
|
||||
assert_eq!(guest.u64_at(LOG), 321, "last registered runs first");
|
||||
assert_eq!(guest.state.exit_status(), Some(0x1234_5678));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_with_nothing_registered_ends_the_process_with_its_status() {
|
||||
for (argument, status) in [
|
||||
(0, 0),
|
||||
(1, 1),
|
||||
(300, 300),
|
||||
(0xFFFF_FFFF, 0xFFFF_FFFF),
|
||||
(0x1_0000_0000, 0),
|
||||
] {
|
||||
let mut guest = guest();
|
||||
// The stub is `call [exit]; hlt`: a service that returned would reach
|
||||
// the HLT and report Halt.
|
||||
let (_, exit) = guest.run("exit", &[argument]);
|
||||
assert_eq!(exit, ExitReason::ProcessExit(status), "{argument:#x}");
|
||||
assert_eq!(guest.u64_at(LOG), 0);
|
||||
assert_eq!(guest.state.exit_status(), Some(status));
|
||||
}
|
||||
}
|
||||
|
||||
/// ISO C 7.22.4.4: registered functions are called in reverse order of
|
||||
/// registration, "except that a function is called after any previously
|
||||
/// registered functions that had already been called at the time it was
|
||||
/// registered". A function registered by the second function to run is
|
||||
/// therefore the third to run, ahead of the one registered first.
|
||||
#[test]
|
||||
fn a_function_registered_while_exit_runs_is_called_next() {
|
||||
let mut guest = guest();
|
||||
register(&mut guest, "atexit", APPEND_1);
|
||||
register(&mut guest, "atexit", REGISTER_4_THEN_APPEND_5);
|
||||
register(&mut guest, "atexit", APPEND_3);
|
||||
let (_, exit) = guest.run("exit", &[6]);
|
||||
assert_eq!(exit, ExitReason::ProcessExit(6));
|
||||
// 3 ran first; then the function that registered 4 and logged 5; then 4,
|
||||
// registered during exit; then 1, the oldest.
|
||||
assert_eq!(guest.u64_at(LOG), 3541);
|
||||
}
|
||||
|
||||
/// Calling `exit` from a registered function is undefined in ISO C. Xenora's
|
||||
/// rule: the functions that have not run yet run once each, and the process
|
||||
/// ends with the status of the later call. Nothing runs twice and the inner
|
||||
/// call does not return.
|
||||
#[test]
|
||||
fn exit_called_again_from_a_registered_function_finishes_with_the_later_status() {
|
||||
let mut guest = guest();
|
||||
register(&mut guest, "atexit", APPEND_1);
|
||||
register(&mut guest, "atexit", EXIT_AGAIN);
|
||||
register(&mut guest, "atexit", APPEND_3);
|
||||
let (_, exit) = guest.run("exit", &[5]);
|
||||
assert_eq!(exit, ExitReason::ProcessExit(SECOND_STATUS));
|
||||
// 3, then the function that called exit again, then 1 from inside that
|
||||
// second call. A status of 5 would mean the function never ran.
|
||||
assert_eq!(guest.u64_at(LOG), 31);
|
||||
assert_eq!(guest.memory.read_u8(RETURNED).unwrap(), 0);
|
||||
assert_eq!(guest.state.exit_status(), Some(SECOND_STATUS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn underscore_exit_and_abort_run_no_registered_function() {
|
||||
for imports in [IMPORTS, BY_API_SET] {
|
||||
// _exit ends the process with its status, an int.
|
||||
for (argument, status) in [(9, 9), (0xAAAA_BBBB_0000_0102, 0x102), (0, 0)] {
|
||||
let mut guest = guest_with(imports);
|
||||
register(&mut guest, "atexit", APPEND_1);
|
||||
register(&mut guest, "_crt_atexit", APPEND_2);
|
||||
let (_, exit) = guest.run("_exit", &[argument]);
|
||||
assert_eq!(exit, ExitReason::ProcessExit(status), "{argument:#x}");
|
||||
assert_eq!(guest.u64_at(LOG), 0);
|
||||
assert_eq!(guest.state.exit_status(), Some(status));
|
||||
}
|
||||
// abort takes no argument and ends the process with exit code 3,
|
||||
// whatever the argument registers hold.
|
||||
for junk in [0, 0x1234] {
|
||||
let mut guest = guest_with(imports);
|
||||
register(&mut guest, "atexit", APPEND_1);
|
||||
let (_, exit) = guest.run("abort", &[junk, junk, junk, junk]);
|
||||
assert_eq!(exit, ExitReason::ProcessExit(3));
|
||||
assert_eq!(guest.u64_at(LOG), 0);
|
||||
assert_eq!(guest.state.exit_status(), Some(3));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_way_out_closes_the_guest_handles() {
|
||||
for symbol in ["exit", "_exit", "abort"] {
|
||||
let mut guest = guest();
|
||||
assert_ne!(guest.call("CreateEventW", &[0, 1, 0, 0]), 0);
|
||||
assert_ne!(guest.call("CreateEventW", &[0, 0, 1, 0]), 0);
|
||||
assert_eq!(guest.state.open_handle_count(), 2);
|
||||
let (_, exit) = guest.run(symbol, &[4]);
|
||||
assert!(matches!(exit, ExitReason::ProcessExit(_)), "{symbol}");
|
||||
assert_eq!(guest.state.open_handle_count(), 0, "{symbol}");
|
||||
}
|
||||
// With registered functions: they run while the handles are still open,
|
||||
// and the handles are closed once the last one has returned.
|
||||
let mut guest = guest();
|
||||
assert_ne!(guest.call("CreateEventW", &[0, 1, 0, 0]), 0);
|
||||
register(&mut guest, "atexit", APPEND_1);
|
||||
assert_eq!(guest.run("exit", &[0]).1, ExitReason::ProcessExit(0));
|
||||
assert_eq!(guest.u64_at(LOG), 1);
|
||||
assert_eq!(guest.state.open_handle_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exited_guest_runs_nothing_further() {
|
||||
for symbol in ["exit", "_exit", "abort"] {
|
||||
let mut guest = guest();
|
||||
let first = guest.run(symbol, &[8]).1;
|
||||
assert!(matches!(first, ExitReason::ProcessExit(_)), "{symbol}");
|
||||
// Neither another service nor a second exit takes effect.
|
||||
for (later, argument) in [("SetLastError", 5), ("exit", 9), ("_exit", 9), ("abort", 0)] {
|
||||
assert_eq!(guest.run(later, &[argument]).1, first, "{symbol}, {later}");
|
||||
}
|
||||
assert_eq!(guest.state.last_error(THREAD_A), 0, "{symbol}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn functions_already_run_by_cexit_are_not_run_again_by_exit() {
|
||||
let mut guest = guest();
|
||||
register(&mut guest, "atexit", APPEND_1);
|
||||
register(&mut guest, "atexit", APPEND_2);
|
||||
// _cexit runs the registered functions and returns to the caller.
|
||||
assert_eq!(guest.call("_cexit", &[]), 0);
|
||||
assert_eq!(guest.u64_at(LOG), 21);
|
||||
// One registered afterwards is the only one exit has left to run.
|
||||
register(&mut guest, "atexit", APPEND_3);
|
||||
assert_eq!(guest.run("exit", &[2]).1, ExitReason::ProcessExit(2));
|
||||
assert_eq!(guest.u64_at(LOG), 213);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_three_resolve_under_the_library_and_the_runtime_api_set() {
|
||||
let state = std::sync::Arc::new(ServicesState::new(std::sync::Arc::new(MockClock::new(0))));
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, state);
|
||||
let named = |name: &str| ImportName::Name(name.to_owned());
|
||||
for symbol in ["exit", "_exit", "abort"] {
|
||||
let service = registry
|
||||
.resolve(UCRT, &named(symbol))
|
||||
.unwrap_or_else(|| panic!("{symbol}"));
|
||||
let aliased = registry.resolve(RUNTIME, &named(symbol)).unwrap();
|
||||
assert!(std::ptr::eq(service, aliased), "{symbol}");
|
||||
assert_eq!(service.status, ServiceStatus::Partial, "{symbol}");
|
||||
// Not exported by kernel32, and not through an unrelated API set.
|
||||
assert!(registry.resolve(KERNEL32, &named(symbol)).is_none());
|
||||
assert!(
|
||||
registry
|
||||
.resolve("api-ms-win-crt-heap-l1-1-0.dll", &named(symbol))
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
// The spelling is exact: _Exit is another function and is not provided.
|
||||
assert!(registry.resolve(UCRT, &named("_Exit")).is_none());
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Reference outputs for the printf formatting engine, from the host C library.
|
||||
|
||||
generate write vectors.txt beside this script
|
||||
--check regenerate in memory; exit 1 if the committed file differs
|
||||
|
||||
The cases are generated here, compiled into a small C program with the host
|
||||
`clang`, and formatted by the host C library's `snprintf`. That library is an
|
||||
implementation of ISO C 7.21.6.1 that shares no code with Xenora, so the file
|
||||
is an independent answer for every case whose result ISO C defines.
|
||||
|
||||
Left out on purpose, because the host and Windows differ or ISO C leaves the
|
||||
result undefined; `crt_format.rs` tests these by hand from Microsoft's page:
|
||||
|
||||
- the `l` size (a long is 64 bits on the host and 32 on Windows), `I`, `I32`
|
||||
and `I64`, which the host does not know
|
||||
- `%p`, and a null pointer for `%s`
|
||||
- `#` with `d`, `i`, `u`, `c` or `s`, `0` with `c` or `s`, and a precision
|
||||
with `c`, which ISO C leaves undefined
|
||||
- floating point, wide characters and `%n`, which the engine refuses
|
||||
|
||||
Each line of vectors.txt is three tab-separated fields:
|
||||
|
||||
format the format string, in hexadecimal
|
||||
arguments comma-separated, in order; `i:<16 hex digits>` is an 8-byte
|
||||
argument slot as the Win64 calling convention passes it (for an
|
||||
int the upper half is junk that must be ignored); `s:<hex>` is a
|
||||
string argument's bytes
|
||||
output what snprintf wrote, in hexadecimal
|
||||
|
||||
Standard library only (Python 3.9+). Needs `clang` on PATH.
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
VECTORS = HERE / "vectors.txt"
|
||||
MASK64 = (1 << 64) - 1
|
||||
|
||||
|
||||
class Random:
|
||||
"""xorshift64*, so the cases do not depend on the Python version."""
|
||||
|
||||
def __init__(self, seed):
|
||||
self.state = seed
|
||||
|
||||
def next(self):
|
||||
s = self.state
|
||||
s ^= s >> 12
|
||||
s ^= (s << 25) & MASK64
|
||||
s ^= s >> 27
|
||||
self.state = s
|
||||
return (s * 0x2545F4914F6CDD1D) & MASK64
|
||||
|
||||
def below(self, bound):
|
||||
return self.next() % bound
|
||||
|
||||
def pick(self, items):
|
||||
return items[self.below(len(items))]
|
||||
|
||||
|
||||
EDGES = [0, 1, 2, 7, 8, 9, 10, 15, 16, 99, 100, 127, 128, 255, 256, 4095, 32767, 32768, 65535,
|
||||
65536, 2**31 - 1, 2**31, 2**32 - 1, 2**32, 2**63 - 1, 2**63, 2**64 - 1]
|
||||
|
||||
# size prefix -> (bits, C type for a signed conversion, C type for an unsigned one)
|
||||
SIZES = {
|
||||
"": (32, "int", "unsigned"),
|
||||
"hh": (8, "int", "unsigned"),
|
||||
"h": (16, "int", "unsigned"),
|
||||
"ll": (64, "long long", "unsigned long long"),
|
||||
"j": (64, "intmax_t", "uintmax_t"),
|
||||
"z": (64, "ssize_t", "size_t"),
|
||||
"t": (64, "ptrdiff_t", "size_t"),
|
||||
}
|
||||
STRINGS = [b"", b"a", b"ab", b"hello", b"hello, world", b" padded ", b"100%", b"tab\there",
|
||||
bytes([0xC3, 0xA9, 0x7E, 0x80, 0xFF]), b"x" * 40]
|
||||
|
||||
|
||||
def value(random):
|
||||
kind = random.below(4)
|
||||
if kind == 0:
|
||||
return random.pick(EDGES)
|
||||
if kind == 1:
|
||||
return (-random.pick(EDGES)) & MASK64
|
||||
if kind == 2:
|
||||
return random.below(1000)
|
||||
return random.next()
|
||||
|
||||
|
||||
def junk(random):
|
||||
"""Upper half of a slot that holds a 32-bit argument."""
|
||||
return random.pick([0, 0xFFFFFFFF, 0xDEADBEEF, random.next() >> 32]) << 32
|
||||
|
||||
|
||||
def int_argument(random, number):
|
||||
"""An `int` argument: its C text and its slot."""
|
||||
low = number & 0xFFFFFFFF
|
||||
signed = low - (1 << 32) if low >> 31 else low
|
||||
return f"(int)({signed})", f"i:{junk(random) | low:016x}"
|
||||
|
||||
|
||||
def spec(random, kinds):
|
||||
"""One conversion specification: (text, [(C argument, slot text)])."""
|
||||
kind = random.pick(kinds)
|
||||
arguments = []
|
||||
# + and blank ask for a sign on a signed conversion. On an unsigned one they
|
||||
# are defined and have no effect, which is worth checking.
|
||||
allowed = {"d": "-+ 0", "i": "-+ 0", "u": "-+ 0", "o": "-+ #0", "x": "-+ #0", "X": "-+ #0",
|
||||
"c": "-", "s": "-"}[kind]
|
||||
flags = "".join(flag for flag in allowed if random.below(3) == 0)
|
||||
if flags and random.below(2):
|
||||
flags = flags[::-1]
|
||||
text = "%" + flags
|
||||
|
||||
choice = random.below(6)
|
||||
if choice in (1, 2):
|
||||
text += str(random.pick([1, 2, 3, 5, 8, 12, 20, 33]))
|
||||
elif choice == 3:
|
||||
text += "*"
|
||||
width = random.pick([0, 1, 4, 9, 17, -1, -6, -15])
|
||||
arguments.append(int_argument(random, width))
|
||||
|
||||
if kind != "c":
|
||||
choice = random.below(7)
|
||||
if choice == 1:
|
||||
text += "."
|
||||
elif choice in (2, 3):
|
||||
text += "." + str(random.pick([0, 1, 2, 4, 7, 11, 25]))
|
||||
elif choice == 4:
|
||||
text += ".*"
|
||||
precision = random.pick([0, 1, 3, 6, 14, -1, -5])
|
||||
arguments.append(int_argument(random, precision))
|
||||
|
||||
if kind == "c":
|
||||
byte = random.pick([0x41, 0x7A, 0x20, 0x25, 0x01, 0x7F, 0x80, 0xFF, 0x00, random.below(256)])
|
||||
# The argument is an int; only its low byte is the character.
|
||||
number = byte | (random.below(3) << 8)
|
||||
arguments.append(int_argument(random, number))
|
||||
elif kind == "s":
|
||||
string = random.pick(STRINGS)
|
||||
literal = "".join(f"\\{byte:03o}" for byte in string)
|
||||
arguments.append((f'"{literal}"', "s:" + string.hex()))
|
||||
else:
|
||||
size = random.pick(list(SIZES))
|
||||
text += size
|
||||
bits, signed_type, unsigned_type = SIZES[size]
|
||||
number = value(random)
|
||||
if bits == 64:
|
||||
if kind in "di":
|
||||
signed = number - (1 << 64) if number >> 63 else number
|
||||
# LLONG_MIN has no literal of its own.
|
||||
literal = "(-9223372036854775807LL - 1)" if signed == -(1 << 63) else f"{signed}LL"
|
||||
arguments.append((f"({signed_type})({literal})", f"i:{number:016x}"))
|
||||
else:
|
||||
arguments.append((f"({unsigned_type})({number}ULL)", f"i:{number:016x}"))
|
||||
else:
|
||||
# hh and h arguments are passed as an int that need not be in
|
||||
# range: the library converts it before printing.
|
||||
arguments.append(int_argument(random, number))
|
||||
return text + kind, arguments
|
||||
|
||||
|
||||
def cases():
|
||||
random = Random(0x9E3779B97F4A7C15)
|
||||
out = []
|
||||
literals = ["", "a", " ", "x=", "[", "]", "%%", "100%% ", "\n", "end"]
|
||||
for index in range(2600):
|
||||
if index < 1500:
|
||||
kinds = "diuoxX"
|
||||
elif index < 1800:
|
||||
kinds = "cs"
|
||||
else:
|
||||
kinds = "diuoxXcs"
|
||||
count = 1 if index < 1800 else 1 + random.below(3)
|
||||
text, arguments = random.pick(literals), []
|
||||
for _ in range(count):
|
||||
piece, more = spec(random, kinds)
|
||||
text += piece + random.pick(literals)
|
||||
arguments += more
|
||||
out.append((text.encode(), arguments))
|
||||
return out
|
||||
|
||||
|
||||
def reference(all_cases):
|
||||
lines = ["#include <stdio.h>", "#include <stdint.h>", "#include <stddef.h>",
|
||||
"#include <sys/types.h>",
|
||||
"static char b[8192];",
|
||||
"static void emit(int n) {",
|
||||
" if (n < 0 || n >= (int)sizeof b) { puts(\"!\"); return; }",
|
||||
" for (int i = 0; i < n; i++) printf(\"%02x\", (unsigned char)b[i]);",
|
||||
" putchar('\\n');",
|
||||
"}",
|
||||
"int main(void) {"]
|
||||
for text, arguments in all_cases:
|
||||
literal = "".join(f"\\{byte:03o}" for byte in text)
|
||||
call = ", ".join([f'"{literal}"'] + [argument for argument, _ in arguments])
|
||||
lines.append(f" emit(snprintf(b, sizeof b, {call}));")
|
||||
lines += [" return 0;", "}"]
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
source, binary = Path(directory, "reference.c"), Path(directory, "reference")
|
||||
source.write_text("\n".join(lines) + "\n")
|
||||
subprocess.run(["clang", "-w", "-O0", source, "-o", binary], check=True)
|
||||
output = subprocess.run([binary], check=True, capture_output=True, text=True).stdout
|
||||
results = output.splitlines()
|
||||
if len(results) != len(all_cases) or "!" in results:
|
||||
sys.exit("the reference program did not format every case")
|
||||
return results
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) != 2 or argv[1] not in ("generate", "--check"):
|
||||
sys.exit("usage: reference.py generate|--check")
|
||||
all_cases = cases()
|
||||
results = reference(all_cases)
|
||||
header = ["# Generated by crates/loader/tests/printf/reference.py from the host C library's",
|
||||
"# snprintf. Do not edit. Fields: format, arguments, output; see that script."]
|
||||
rows = [f"{text.hex()}\t{','.join(slot for _, slot in arguments)}\t{result}"
|
||||
for (text, arguments), result in zip(all_cases, results)]
|
||||
content = "\n".join(header + rows) + "\n"
|
||||
if argv[1] == "generate":
|
||||
VECTORS.write_text(content)
|
||||
elif not VECTORS.exists() or VECTORS.read_text() != content:
|
||||
sys.exit("vectors.txt differs from the host C library's output; run reference.py generate")
|
||||
print(f"vectors.txt: {len(rows)} cases")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,325 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Repeated-frame regression for the guest graphics context (issue #148).
|
||||
//!
|
||||
//! One device, queue, allocator and command list are driven through the
|
||||
//! per-frame loop a D3D12 guest uses: reset, record, close, execute. Each
|
||||
//! frame changes the guest-backed vertex data, the clear colour or the draw
|
||||
//! parameters. Expected pixels are written out by hand below for triangles
|
||||
//! chosen so their coverage of a 4×3 viewport is obvious; they are not
|
||||
//! computed by the rasterizer under test. These tests use the software
|
||||
//! reference backend only; no native Metal result is claimed here.
|
||||
|
||||
use xenora_loader::graphics::{
|
||||
CommandListType, GraphicsBackendId, GraphicsContext, GraphicsError, GraphicsHandle,
|
||||
ResourceDesc, ResourceDimension, ResourceStates,
|
||||
};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
|
||||
const WIDTH: usize = 4;
|
||||
const HEIGHT: usize = 3;
|
||||
const VERTICES: u64 = 0x0010_0000;
|
||||
/// Two triangles of three float4 positions each.
|
||||
const VERTEX_BYTES: usize = 96;
|
||||
const RED: [u8; 4] = [255, 0, 0, 255];
|
||||
|
||||
/// Covers every pixel centre of the viewport.
|
||||
const FULL: [[f32; 4]; 3] = [
|
||||
[-1.0, -1.0, 0.0, 1.0],
|
||||
[3.0, -1.0, 0.0, 1.0],
|
||||
[-1.0, 3.0, 0.0, 1.0],
|
||||
];
|
||||
/// Its right edge is x = 0 in clip space, so it covers the two left columns
|
||||
/// (centres at x = -0.75 and -0.25) and none of the two right ones.
|
||||
const LEFT_HALF: [[f32; 4]; 3] = [
|
||||
[0.0, 10.0, 0.0, 1.0],
|
||||
[0.0, -10.0, 0.0, 1.0],
|
||||
[-30.0, 0.0, 0.0, 1.0],
|
||||
];
|
||||
/// Lies wholly outside the viewport.
|
||||
const OFFSCREEN: [[f32; 4]; 3] = [
|
||||
[2.0, 2.0, 0.0, 1.0],
|
||||
[3.0, 2.0, 0.0, 1.0],
|
||||
[2.0, 3.0, 0.0, 1.0],
|
||||
];
|
||||
|
||||
struct Rig {
|
||||
ctx: GraphicsContext,
|
||||
memory: GuestMemory,
|
||||
queue: GraphicsHandle,
|
||||
alloc: GraphicsHandle,
|
||||
list: GraphicsHandle,
|
||||
vertices: GraphicsHandle,
|
||||
target: GraphicsHandle,
|
||||
}
|
||||
|
||||
fn rig() -> Rig {
|
||||
let mut ctx = GraphicsContext::new();
|
||||
let device = ctx.create_device().unwrap();
|
||||
let queue = ctx
|
||||
.create_command_queue(device, CommandListType::Direct)
|
||||
.unwrap();
|
||||
let alloc = ctx
|
||||
.create_command_allocator(device, CommandListType::Direct)
|
||||
.unwrap();
|
||||
let list = ctx
|
||||
.create_command_list(device, alloc, CommandListType::Direct)
|
||||
.unwrap();
|
||||
// A new list starts open; close it so every frame begins with a reset.
|
||||
ctx.close_command_list(list).unwrap();
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region(VERTICES, 0x1000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let buffer = ResourceDesc {
|
||||
dimension: ResourceDimension::Buffer,
|
||||
width: VERTEX_BYTES as u64,
|
||||
height: 1,
|
||||
depth_or_array_size: 1,
|
||||
mip_levels: 1,
|
||||
format_rgba8: false,
|
||||
};
|
||||
let vertices = ctx
|
||||
.create_committed_resource(
|
||||
device,
|
||||
buffer,
|
||||
ResourceStates::VERTEX_AND_CONSTANT_BUFFER,
|
||||
Some(VERTICES),
|
||||
)
|
||||
.unwrap();
|
||||
let texture = ResourceDesc {
|
||||
dimension: ResourceDimension::Texture2D,
|
||||
width: WIDTH as u64,
|
||||
height: HEIGHT as u32,
|
||||
depth_or_array_size: 1,
|
||||
mip_levels: 1,
|
||||
format_rgba8: true,
|
||||
};
|
||||
let target = ctx
|
||||
.create_committed_resource(device, texture, ResourceStates::PRESENT, None)
|
||||
.unwrap();
|
||||
Rig {
|
||||
ctx,
|
||||
memory,
|
||||
queue,
|
||||
alloc,
|
||||
list,
|
||||
vertices,
|
||||
target,
|
||||
}
|
||||
}
|
||||
|
||||
fn write_triangle(memory: &mut GuestMemory, slot: u64, triangle: [[f32; 4]; 3]) {
|
||||
let bytes: Vec<u8> = triangle
|
||||
.iter()
|
||||
.flatten()
|
||||
.flat_map(|value| value.to_le_bytes())
|
||||
.collect();
|
||||
memory.write_bytes(VERTICES + slot * 48, &bytes).unwrap();
|
||||
}
|
||||
|
||||
/// Pixels with `columns` red from the left and the rest in `clear`.
|
||||
fn expected(columns: usize, clear: [u8; 4]) -> Vec<u8> {
|
||||
(0..WIDTH * HEIGHT)
|
||||
.flat_map(|pixel| if pixel % WIDTH < columns { RED } else { clear })
|
||||
.collect()
|
||||
}
|
||||
|
||||
struct Draw {
|
||||
clear: [u8; 4],
|
||||
offset: usize,
|
||||
vertex_count: u32,
|
||||
instance_count: u32,
|
||||
start_vertex: u32,
|
||||
start_instance: u32,
|
||||
}
|
||||
|
||||
impl Draw {
|
||||
fn one(clear: [u8; 4]) -> Self {
|
||||
Self {
|
||||
clear,
|
||||
offset: 0,
|
||||
vertex_count: 3,
|
||||
instance_count: 1,
|
||||
start_vertex: 0,
|
||||
start_instance: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Record one frame: target to RENDER_TARGET, draw, back to PRESENT.
|
||||
fn record(rig: &mut Rig, draw: &Draw) -> Result<(), GraphicsError> {
|
||||
let ctx = &mut rig.ctx;
|
||||
ctx.reset_command_list(rig.list, rig.alloc)?;
|
||||
ctx.cmd_resource_barrier(
|
||||
rig.list,
|
||||
rig.target,
|
||||
ResourceStates::PRESENT,
|
||||
ResourceStates::RENDER_TARGET,
|
||||
)?;
|
||||
ctx.cmd_set_viewport(rig.list, WIDTH, HEIGHT)?;
|
||||
ctx.cmd_set_render_targets(rig.list, Some(rig.target), draw.clear)?;
|
||||
ctx.cmd_set_vertex_buffer(rig.list, rig.vertices, draw.offset, 48)?;
|
||||
ctx.cmd_draw_instanced(
|
||||
rig.list,
|
||||
draw.vertex_count,
|
||||
draw.instance_count,
|
||||
draw.start_vertex,
|
||||
draw.start_instance,
|
||||
)?;
|
||||
ctx.cmd_resource_barrier(
|
||||
rig.list,
|
||||
rig.target,
|
||||
ResourceStates::RENDER_TARGET,
|
||||
ResourceStates::PRESENT,
|
||||
)?;
|
||||
ctx.close_command_list(rig.list)
|
||||
}
|
||||
|
||||
fn frame(rig: &mut Rig, draw: &Draw) -> Result<(Vec<u8>, usize), GraphicsError> {
|
||||
record(rig, draw)?;
|
||||
let outcome = rig
|
||||
.ctx
|
||||
.execute_command_list(rig.queue, rig.list, &rig.memory)?;
|
||||
assert_eq!(outcome.backend, GraphicsBackendId::SoftwareReference);
|
||||
assert_eq!((outcome.width, outcome.height), (WIDTH, HEIGHT));
|
||||
Ok((outcome.pixels, outcome.draw_count))
|
||||
}
|
||||
|
||||
fn frame_index(rig: &Rig) -> u64 {
|
||||
rig.ctx.last_presentation.lock().unwrap().frame_index
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_frame_reflects_its_own_guest_vertices_and_clear_colour() {
|
||||
let mut rig = rig();
|
||||
let frames = [
|
||||
(LEFT_HALF, [0, 0, 64, 255], 2),
|
||||
(FULL, [10, 20, 30, 255], WIDTH),
|
||||
(OFFSCREEN, [1, 2, 3, 4], 0),
|
||||
(LEFT_HALF, [9, 9, 9, 255], 2),
|
||||
];
|
||||
for (index, (triangle, clear, columns)) in frames.into_iter().enumerate() {
|
||||
write_triangle(&mut rig.memory, 0, triangle);
|
||||
let (pixels, draws) = frame(&mut rig, &Draw::one(clear)).unwrap();
|
||||
let want = expected(columns, clear);
|
||||
assert_eq!(pixels, want, "frame {index}");
|
||||
assert_eq!(draws, 1, "frame {index}");
|
||||
assert_eq!(frame_index(&rig), index as u64 + 1);
|
||||
// The presentation holds this frame's pixels, not an earlier one's.
|
||||
let presented = rig.ctx.last_presentation.lock().unwrap().pixels.clone();
|
||||
assert_eq!(presented, want, "presented frame {index}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zero_instance_or_zero_vertex_frame_draws_nothing() {
|
||||
let mut rig = rig();
|
||||
write_triangle(&mut rig.memory, 0, FULL);
|
||||
let clear = [5, 6, 7, 255];
|
||||
for (vertices, instances) in [(3, 0), (0, 1), (2, 1)] {
|
||||
let draw = Draw {
|
||||
vertex_count: vertices,
|
||||
instance_count: instances,
|
||||
..Draw::one(clear)
|
||||
};
|
||||
let (pixels, draws) = frame(&mut rig, &draw).unwrap();
|
||||
assert_eq!(pixels, expected(0, clear), "{vertices} x {instances}");
|
||||
assert_eq!(draws, 0, "{vertices} x {instances}");
|
||||
}
|
||||
// The next ordinary frame still draws.
|
||||
let (pixels, draws) = frame(&mut rig, &Draw::one(clear)).unwrap();
|
||||
assert_eq!((pixels, draws), (expected(WIDTH, clear), 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_draw_parameters_fail_and_the_next_frame_recovers() {
|
||||
let mut rig = rig();
|
||||
write_triangle(&mut rig.memory, 0, LEFT_HALF);
|
||||
write_triangle(&mut rig.memory, 1, FULL);
|
||||
let clear = [0, 0, 0, 255];
|
||||
frame(&mut rig, &Draw::one(clear)).unwrap();
|
||||
let rejected = [
|
||||
Draw {
|
||||
start_vertex: 3,
|
||||
..Draw::one(clear)
|
||||
},
|
||||
Draw {
|
||||
instance_count: 2,
|
||||
..Draw::one(clear)
|
||||
},
|
||||
Draw {
|
||||
start_instance: 1,
|
||||
..Draw::one(clear)
|
||||
},
|
||||
Draw {
|
||||
vertex_count: 6,
|
||||
..Draw::one(clear)
|
||||
},
|
||||
];
|
||||
for draw in &rejected {
|
||||
// Only the draw is rejected. The barrier before it already ran, so
|
||||
// the target is left in RENDER_TARGET, as a guest would see it.
|
||||
let before = frame_index(&rig);
|
||||
let result = frame(&mut rig, draw);
|
||||
assert!(
|
||||
matches!(result, Err(GraphicsError::Unsupported(_))),
|
||||
"{result:?}"
|
||||
);
|
||||
assert_eq!(frame_index(&rig), before, "a failed frame is not presented");
|
||||
rig.ctx.reset_command_list(rig.list, rig.alloc).unwrap();
|
||||
rig.ctx
|
||||
.cmd_resource_barrier(
|
||||
rig.list,
|
||||
rig.target,
|
||||
ResourceStates::RENDER_TARGET,
|
||||
ResourceStates::PRESENT,
|
||||
)
|
||||
.unwrap();
|
||||
rig.ctx.close_command_list(rig.list).unwrap();
|
||||
rig.ctx
|
||||
.execute_command_list(rig.queue, rig.list, &rig.memory)
|
||||
.unwrap();
|
||||
}
|
||||
// The second triangle is still reachable through the view offset.
|
||||
let draw = Draw {
|
||||
offset: 48,
|
||||
..Draw::one(clear)
|
||||
};
|
||||
let (pixels, _) = frame(&mut rig, &draw).unwrap();
|
||||
assert_eq!(pixels, expected(WIDTH, clear));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vertex_view_outside_its_buffer_fails_without_reading_past_it() {
|
||||
let mut rig = rig();
|
||||
write_triangle(&mut rig.memory, 0, FULL);
|
||||
write_triangle(&mut rig.memory, 1, FULL);
|
||||
// Mapped guest memory continues past the buffer; the view must not.
|
||||
write_triangle(&mut rig.memory, 2, FULL);
|
||||
let clear = [0, 0, 0, 255];
|
||||
for offset in [VERTEX_BYTES - 47, VERTEX_BYTES, usize::MAX - 100] {
|
||||
let draw = Draw {
|
||||
offset,
|
||||
..Draw::one(clear)
|
||||
};
|
||||
assert_eq!(
|
||||
frame(&mut rig, &draw),
|
||||
Err(GraphicsError::IndexOutOfRange),
|
||||
"offset {offset}"
|
||||
);
|
||||
rig.ctx.reset_command_list(rig.list, rig.alloc).unwrap();
|
||||
rig.ctx
|
||||
.cmd_resource_barrier(
|
||||
rig.list,
|
||||
rig.target,
|
||||
ResourceStates::RENDER_TARGET,
|
||||
ResourceStates::PRESENT,
|
||||
)
|
||||
.unwrap();
|
||||
rig.ctx.close_command_list(rig.list).unwrap();
|
||||
rig.ctx
|
||||
.execute_command_list(rig.queue, rig.list, &rig.memory)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -102,8 +102,8 @@ def cases():
|
||||
out += [f"{op} ah, bl", f"{op} cl, dh", f"{op} {mem(8)}, ch"]
|
||||
out += ["mov ah, bl", "mov dl, ch", "mov bh, 0x21", "xchg ah, bl", "mov sil, dil",
|
||||
"movabs r15, 0x8877665544332211", "mov rcx, -2", "bswap ebx", "bswap r9",
|
||||
"cbw", "cwde", "cdqe", "cwd", "cdq", "cqo", "clc", "stc", "cmc", "nop", "cpuid",
|
||||
"nop dword ptr [rax + 8]", "pause", "lfence", "mfence", "sfence",
|
||||
"cbw", "cwde", "cdqe", "cwd", "cdq", "cqo", "clc", "stc", "cmc", "lahf", "sahf",
|
||||
"nop", "cpuid", "nop dword ptr [rax + 8]", "pause", "lfence", "mfence", "sfence", "fninit",
|
||||
f"movnti {mem(32)}, ebx", f"movnti {mem(64)}, rbx",
|
||||
f"movnti {mem(32)}, r9d", f"movnti {mem(64)}, r14", "push r9", "push rbx", "push -5", "push 0x12345678",
|
||||
f"push {mem(64)}", "pop rbx", "pop r12", f"pop {mem(64)}", "leave"]
|
||||
|
||||
@@ -1185,6 +1185,8 @@ b7 21 | mov bh, 0x21
|
||||
f8 | clc
|
||||
f9 | stc
|
||||
f5 | cmc
|
||||
9f | lahf
|
||||
9e | sahf
|
||||
90 | nop
|
||||
0f a2 | cpuid
|
||||
0f 1f 40 08 | nop dword ptr [rax + 8]
|
||||
@@ -1192,6 +1194,7 @@ f3 90 | pause
|
||||
0f ae e8 | lfence
|
||||
0f ae f0 | mfence
|
||||
0f ae f8 | sfence
|
||||
db e3 | fninit
|
||||
0f c3 5c be 10 | movnti dword ptr [rsi + 4*rdi + 16], ebx
|
||||
48 0f c3 5c be 10 | movnti qword ptr [rsi + 4*rdi + 16], rbx
|
||||
44 0f c3 4c be 10 | movnti dword ptr [rsi + 4*rdi + 16], r9d
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
//! but the interpreter and the DBT must still agree on the complete state.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags};
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags, X87State};
|
||||
use xenora_loader::dbt::{DbtEngine, is_native};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
use xenora_loader::x86_decode::decode;
|
||||
@@ -67,6 +67,8 @@ struct Machine {
|
||||
/// Stack qwords at STACK_TOP - 8 and STACK_TOP.
|
||||
pushed: u64,
|
||||
top: u64,
|
||||
/// x87 control, status and tag words.
|
||||
x87: [u16; 3],
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
@@ -329,6 +331,11 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
bits,
|
||||
high: false,
|
||||
};
|
||||
let ah = Place::Reg {
|
||||
index: RAX,
|
||||
bits: 8,
|
||||
high: true,
|
||||
};
|
||||
|
||||
if let Some(code) = name.strip_prefix("cmov") {
|
||||
let value = read(
|
||||
@@ -787,18 +794,46 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
m.flags.cf = !m.flags.cf;
|
||||
Outcome::Done(none)
|
||||
}
|
||||
// AH bits 7 to 0 are SF, ZF, 0, AF, 0, PF, 1 and CF; OF has no bit.
|
||||
"lahf" => {
|
||||
let f = m.flags;
|
||||
let bits = [f.cf, true, f.pf, false, f.af, false, f.zf, f.sf];
|
||||
let value = (0..8)
|
||||
.filter(|&index| bits[index])
|
||||
.map(|index| 1u128 << index)
|
||||
.sum();
|
||||
write(m, ah, value);
|
||||
Outcome::Done(none)
|
||||
}
|
||||
"sahf" => {
|
||||
let value = read(m, ah, 8);
|
||||
m.flags.cf = bit(value, 0);
|
||||
m.flags.pf = bit(value, 2);
|
||||
m.flags.af = bit(value, 4);
|
||||
m.flags.zf = bit(value, 6);
|
||||
m.flags.sf = bit(value, 7);
|
||||
Outcome::Done(none)
|
||||
}
|
||||
// The fences order memory accesses and compute nothing.
|
||||
"nop" | "pause" | "lfence" | "mfence" | "sfence" => Outcome::Done(none),
|
||||
"fninit" => {
|
||||
// Intel SDM Vol. 2A, "FINIT/FNINIT", Operation: FPUControlWord :=
|
||||
// 037FH, FPUStatusWord := 0, FPUTagWord := FFFFH. Nothing else here
|
||||
// is x87 state.
|
||||
m.x87 = [0x037F, 0, 0xFFFF];
|
||||
Outcome::Done(none)
|
||||
}
|
||||
"cpuid" => {
|
||||
// Xenora's guest CPUID contract, restated: the vendor "Xenora guest"
|
||||
// and the four features whose every instruction exists, CMOV and
|
||||
// POPCNT in leaf 1, LZCNT and long mode in leaf 0x8000_0001.
|
||||
// and the five features whose every instruction exists, CMOV and
|
||||
// POPCNT in leaf 1, LAHF/SAHF, LZCNT and long mode in leaf
|
||||
// 0x8000_0001.
|
||||
let word = |text: &[u8; 4]| u32::from_le_bytes(*text);
|
||||
let values = match m.gpr[RAX] as u32 {
|
||||
0 => [1, word(b"Xeno"), word(b"uest"), word(b"ra g")],
|
||||
1 => [0, 0, 1 << 23, 1 << 15],
|
||||
0x8000_0000 => [0x8000_0001, 0, 0, 0],
|
||||
0x8000_0001 => [0, 0, 1 << 5, 1 << 29],
|
||||
0x8000_0001 => [0, 0, 1 | 1 << 5, 1 << 29],
|
||||
_ => [0; 4],
|
||||
};
|
||||
// EAX, EBX, ECX and EDX, each zero-extended.
|
||||
@@ -898,6 +933,8 @@ impl Random {
|
||||
operand: self.value(),
|
||||
pushed: self.next(),
|
||||
top: self.value(),
|
||||
// Any bit pattern: nothing interprets these words.
|
||||
x87: [self.next() as u16, self.next() as u16, self.next() as u16],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -926,6 +963,12 @@ fn load(machine: &Machine, code: &[u8]) -> (CpuState, GuestMemory) {
|
||||
pf: f.pf,
|
||||
af: f.af,
|
||||
};
|
||||
let [control, status, tag] = machine.x87;
|
||||
cpu.x87 = X87State {
|
||||
control,
|
||||
status,
|
||||
tag,
|
||||
};
|
||||
(cpu, memory)
|
||||
}
|
||||
|
||||
@@ -984,6 +1027,13 @@ fn every_fixture_instruction_matches_the_reference_in_both_engines() {
|
||||
"{text}"
|
||||
);
|
||||
assert_eq!(state.rip, ENTRY + case.code.len() as u64, "{text}");
|
||||
let x87 = state.x87;
|
||||
assert_eq!(
|
||||
[x87.control, x87.status, x87.tag],
|
||||
expected.x87,
|
||||
"{text}: x87 words from {:04x?}",
|
||||
machine.x87
|
||||
);
|
||||
if !undefined.destination {
|
||||
assert_eq!(state.gpr, expected.gpr, "{text} from {cpu:x?}");
|
||||
assert_eq!(
|
||||
@@ -1043,6 +1093,10 @@ fn every_declared_form_is_executed_by_a_fixture() {
|
||||
let separate = [
|
||||
Op::Ldmxcsr,
|
||||
Op::Jcc,
|
||||
Op::Loop,
|
||||
Op::Loope,
|
||||
Op::Loopne,
|
||||
Op::Jrcxz,
|
||||
Op::Jmp,
|
||||
Op::Call,
|
||||
Op::Ret,
|
||||
@@ -1289,6 +1343,12 @@ fn undeclared_and_ambiguous_encodings_are_rejected() {
|
||||
&[0x0F, 0xC3, 0xC1], // movnti with a register destination
|
||||
&[0x66, 0x0F, 0xC3, 0x06], // 66 with movnti
|
||||
&[0x0F, 0xA3, 0x06], // bt [rsi], eax
|
||||
&[0x9B], // fwait
|
||||
&[0x9B, 0xDB, 0xE3], // finit: fwait, then fninit
|
||||
&[0x66, 0xDB, 0xE3], // 66 with fninit
|
||||
&[0xF3, 0xDB, 0xE3], // F3 with fninit
|
||||
&[0xF2, 0xDB, 0xE3], // F2 with fninit
|
||||
&[0xF0, 0xDB, 0xE3], // lock fninit
|
||||
&[0xC6, 0xC8, 0x01], // C6 /1
|
||||
&[0xFF, 0xF8], // FF /7
|
||||
&[0xFE, 0xD0], // FE /2
|
||||
@@ -1321,6 +1381,81 @@ fn undeclared_and_ambiguous_encodings_are_rejected() {
|
||||
}
|
||||
}
|
||||
|
||||
/// FNINIT (DB E3) is the only x87 instruction. Every other ModRM byte under the
|
||||
/// eight x87 escape opcodes, D8 to DF, stops both engines and changes nothing.
|
||||
/// That includes FNINIT's neighbours of the same digit, such as FNCLEX (DB E2),
|
||||
/// and the memory forms of that digit.
|
||||
#[test]
|
||||
fn fninit_is_the_only_x87_encoding_accepted() {
|
||||
let machine = Random(7).machine();
|
||||
assert_ne!(
|
||||
machine.x87,
|
||||
[0x037F, 0, 0xFFFF],
|
||||
"the reset must be visible"
|
||||
);
|
||||
let mut accepted = Vec::new();
|
||||
for opcode in 0xD8..=0xDF_u8 {
|
||||
for modrm in 0..=0xFF_u8 {
|
||||
// The padding is a SIB byte and displacement for the memory forms.
|
||||
let code = [opcode, modrm, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90];
|
||||
for native in [false, true] {
|
||||
let (mut cpu, mut memory) = load(&machine, &code);
|
||||
let before = cpu.clone();
|
||||
let data = bytes(&memory);
|
||||
let result = if native {
|
||||
DbtEngine::new(16 * 1024)
|
||||
.unwrap()
|
||||
.run(&mut cpu, &mut memory, 1)
|
||||
} else {
|
||||
Interpreter::new(cpu, &mut memory, 1).run()
|
||||
};
|
||||
let what = format!("{opcode:02X} {modrm:02X}, native {native}");
|
||||
assert_eq!(bytes(&memory), data, "{what}");
|
||||
if matches!(result.exit_reason, ExitReason::IllegalInstruction(_)) {
|
||||
assert_eq!(result.final_state, before, "{what}");
|
||||
continue;
|
||||
}
|
||||
accepted.push((opcode, modrm, native));
|
||||
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded, "{what}");
|
||||
// Only RIP and the three x87 words may differ.
|
||||
let mut wanted = before;
|
||||
wanted.rip = ENTRY + 2;
|
||||
wanted.x87 = X87State {
|
||||
control: 0x037F,
|
||||
status: 0,
|
||||
tag: 0xFFFF,
|
||||
};
|
||||
assert_eq!(result.final_state, wanted, "{what}");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(accepted, [(0xDB, 0xE3, false), (0xDB, 0xE3, true)]);
|
||||
}
|
||||
|
||||
/// A local rule, pinned so it cannot change unnoticed: a segment override or a
|
||||
/// REX prefix before FNINIT is accepted and has no effect, as the decoder
|
||||
/// treats them before any form without operands. It is not derived from a
|
||||
/// manual statement. The prefixes that are refused are in
|
||||
/// `undeclared_and_ambiguous_encodings_are_rejected`.
|
||||
#[test]
|
||||
fn prefixes_accepted_before_fninit_have_no_effect() {
|
||||
let machine = Random(11).machine();
|
||||
for prefix in [0x2E_u8, 0x64, 0x65, 0x40, 0x41, 0x48, 0x4F] {
|
||||
let code = [prefix, 0xDB, 0xE3, 0x90];
|
||||
let (cpu, _) = load(&machine, &code);
|
||||
let mut wanted = cpu;
|
||||
wanted.rip = ENTRY + 3;
|
||||
wanted.x87 = X87State {
|
||||
control: 0x037F,
|
||||
status: 0,
|
||||
tag: 0xFFFF,
|
||||
};
|
||||
let (state, exit, _) = run_both(&machine, &code, 1);
|
||||
assert_eq!(exit, ExitReason::StepLimitExceeded, "{prefix:02X}");
|
||||
assert_eq!(state, wanted, "{prefix:02X}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_syscalls_are_refused_by_the_dbt_only() {
|
||||
let machine = Random(9).machine();
|
||||
@@ -1447,6 +1582,7 @@ fn bit_scans_and_bit_tests_follow_the_architecture() {
|
||||
operand: 0,
|
||||
pushed: 0,
|
||||
top: STACK_TOP,
|
||||
x87: [0x037F, 0, 0xFFFF],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -178,7 +178,7 @@ fn interpreter_rejects_overlong_segment_prefix_run() {
|
||||
.unwrap();
|
||||
let cpu = CpuState::new(ENTRY, 0);
|
||||
let result = Interpreter::new(cpu, &mut memory, 8).run();
|
||||
assert_eq!(result.exit_reason, ExitReason::IllegalInstruction(0x65));
|
||||
assert_eq!(result.exit_reason, ExitReason::GeneralProtection);
|
||||
assert_eq!(result.instructions_executed, 0);
|
||||
assert_eq!(result.final_state.rip, ENTRY);
|
||||
}
|
||||
@@ -195,9 +195,61 @@ fn dbt_rejects_overlong_segment_prefix_run() {
|
||||
let result = DbtEngine::new(1024 * 1024)
|
||||
.expect("JIT memory allocation")
|
||||
.run(&mut cpu, &mut memory, 8);
|
||||
assert!(
|
||||
matches!(result.exit_reason, ExitReason::IllegalInstruction(_)),
|
||||
"expected IllegalInstruction, got {:?}",
|
||||
result.exit_reason
|
||||
);
|
||||
assert_eq!(result.exit_reason, ExitReason::GeneralProtection);
|
||||
assert_eq!(result.instructions_executed, 0);
|
||||
assert_eq!(cpu.rip, ENTRY);
|
||||
}
|
||||
|
||||
/// Runs `prefixes` bytes of 0x66 that end exactly at the end of a mapped page,
|
||||
/// with nothing mapped after it, on both engines.
|
||||
fn run_prefixes_at_page_end(prefixes: usize) -> [(ExitReason, u64, u64); 2] {
|
||||
const PAGE: u64 = 0x2000;
|
||||
const PAGE_LEN: usize = 0x1000;
|
||||
let mut data = vec![0x90; PAGE_LEN];
|
||||
data[PAGE_LEN - prefixes..].fill(0x66);
|
||||
let entry = PAGE + (PAGE_LEN - prefixes) as u64;
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(PAGE, PAGE_LEN, MemoryPermissions::READ_EXECUTE, &data)
|
||||
.unwrap();
|
||||
|
||||
let interpreted = Interpreter::new(CpuState::new(entry, 0), &mut memory, 8).run();
|
||||
let mut cpu = CpuState::new(entry, 0);
|
||||
let translated = DbtEngine::new(1024 * 1024)
|
||||
.expect("JIT memory allocation")
|
||||
.run(&mut cpu, &mut memory, 8);
|
||||
[
|
||||
(
|
||||
interpreted.exit_reason,
|
||||
interpreted.final_state.rip,
|
||||
interpreted.instructions_executed,
|
||||
),
|
||||
(
|
||||
translated.exit_reason,
|
||||
cpu.rip,
|
||||
translated.instructions_executed,
|
||||
),
|
||||
]
|
||||
.map(|(exit, rip, count)| (exit, rip.wrapping_sub(entry), count as u64))
|
||||
}
|
||||
|
||||
/// Fifteen prefixes are already too long whatever follows, so the 16th byte is
|
||||
/// never fetched: #GP, not a fetch fault on the unmapped page after them
|
||||
/// (Intel SDM Vol. 3A, 7.15).
|
||||
#[test]
|
||||
fn overlong_instruction_is_gp_without_fetching_the_sixteenth_byte() {
|
||||
for (exit, rip_offset, count) in run_prefixes_at_page_end(MAX_INSTRUCTION_LEN) {
|
||||
assert_eq!(exit, ExitReason::GeneralProtection);
|
||||
assert_eq!((rip_offset, count), (0, 0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Control for the test above: fourteen prefixes leave room for an opcode, so
|
||||
/// the fetch of the 15th byte is what fails.
|
||||
#[test]
|
||||
fn fourteen_prefixes_at_a_page_end_fault_on_the_fetch() {
|
||||
for (exit, rip_offset, count) in run_prefixes_at_page_end(MAX_INSTRUCTION_LEN - 1) {
|
||||
assert!(matches!(exit, ExitReason::MemoryFault(_)), "{exit:?}");
|
||||
assert_eq!((rip_offset, count), (0, 0));
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,9 @@
|
||||
# lock = true accepts the LOCK prefix (F0) when the ModRM operand is memory.
|
||||
# Every other use of LOCK is rejected, as the architecture's #UD.
|
||||
#
|
||||
# rm = N requires the ModRM r/m field to be N. It needs register_only, so the
|
||||
# form matches exactly one ModRM byte. At most one form per opcode and digit.
|
||||
#
|
||||
# prefix is a mandatory prefix: "66", "f3" or "f2". SSE forms use size x (XMM)
|
||||
# and give the ModRM operand width in src: x = 16 bytes, q = 8, d = 4, w = 2.
|
||||
# A 16-byte memory operand must be aligned unless unaligned = true.
|
||||
@@ -90,6 +93,11 @@ leave = { ref = "sdm LEAVE" }
|
||||
call = { terminator = true, ref = "sdm CALL" }
|
||||
jmp = { terminator = true, ref = "sdm JMP" }
|
||||
jcc = { reads = "cf zf sf of pf", terminator = true, ref = "sdm Jcc" }
|
||||
# The count is RCX: the address-size prefix that would select ECX is rejected.
|
||||
loopne = { reads = "zf", terminator = true, ref = "sdm LOOP/LOOPcc" }
|
||||
loope = { reads = "zf", terminator = true, ref = "sdm LOOP/LOOPcc" }
|
||||
loop = { terminator = true, ref = "sdm LOOP/LOOPcc" }
|
||||
jrcxz = { terminator = true, ref = "sdm Jcc" }
|
||||
ret = { terminator = true, ref = "sdm RET" }
|
||||
nop = { ref = "sdm NOP" }
|
||||
hlt = { terminator = true, ref = "sdm HLT" }
|
||||
@@ -97,9 +105,14 @@ syscall = { terminator = true, ref = "sdm SYSCALL" }
|
||||
clc = { writes = "cf", ref = "sdm CLC" }
|
||||
stc = { writes = "cf", ref = "sdm STC" }
|
||||
cmc = { reads = "cf", writes = "cf", ref = "sdm CMC" }
|
||||
# AH holds SF, ZF, AF, PF and CF; valid in 64-bit mode when CPUID
|
||||
# 8000_0001h ECX bit 0 is set.
|
||||
lahf = { reads = "cf zf sf pf af", ref = "sdm LAHF" }
|
||||
sahf = { writes = "cf zf sf pf af", ref = "sdm SAHF" }
|
||||
cpuid = { ref = "sdm CPUID" }
|
||||
cld = { ref = "sdm CLD" }
|
||||
std = { ref = "sdm STD" }
|
||||
fninit = { ref = "sdm FINIT/FNINIT" }
|
||||
# A REP form repeats by leaving RIP on itself, so these end a translated block.
|
||||
movs = { terminator = true, ref = "sdm MOVS/MOVSB/MOVSW/MOVSD/MOVSQ" }
|
||||
stos = { terminator = true, ref = "sdm STOS/STOSB/STOSW/STOSD/STOSQ" }
|
||||
@@ -512,6 +525,18 @@ opcode = 0x99
|
||||
enc = "none"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "sahf"
|
||||
opcode = 0x9E
|
||||
enc = "none"
|
||||
size = "n"
|
||||
|
||||
[[form]]
|
||||
op = "lahf"
|
||||
opcode = 0x9F
|
||||
enc = "none"
|
||||
size = "n"
|
||||
|
||||
[[form]]
|
||||
op = "mov"
|
||||
opcode = 0xB0
|
||||
@@ -563,6 +588,34 @@ opcode = 0xC9
|
||||
enc = "none"
|
||||
size = "q"
|
||||
|
||||
[[form]]
|
||||
op = "loopne"
|
||||
opcode = 0xE0
|
||||
enc = "rel"
|
||||
size = "n"
|
||||
imm = "rel8"
|
||||
|
||||
[[form]]
|
||||
op = "loope"
|
||||
opcode = 0xE1
|
||||
enc = "rel"
|
||||
size = "n"
|
||||
imm = "rel8"
|
||||
|
||||
[[form]]
|
||||
op = "loop"
|
||||
opcode = 0xE2
|
||||
enc = "rel"
|
||||
size = "n"
|
||||
imm = "rel8"
|
||||
|
||||
[[form]]
|
||||
op = "jrcxz"
|
||||
opcode = 0xE3
|
||||
enc = "rel"
|
||||
size = "n"
|
||||
imm = "rel8"
|
||||
|
||||
[[form]]
|
||||
op = "call"
|
||||
opcode = 0xE8
|
||||
@@ -672,6 +725,18 @@ opcode = 0xFD
|
||||
enc = "none"
|
||||
size = "n"
|
||||
|
||||
# FNINIT is DB E3 and nothing else: the other register bytes of digit 4 are
|
||||
# different instructions (DB E2 is FNCLEX) and the memory forms are not x87
|
||||
# initialisation at all. No other x87 form is declared.
|
||||
[[form]]
|
||||
op = "fninit"
|
||||
opcode = 0xDB
|
||||
digit = 4
|
||||
enc = "rm_unread"
|
||||
size = "n"
|
||||
register_only = true
|
||||
rm = 3
|
||||
|
||||
[[form]]
|
||||
op = "movzx"
|
||||
map = "0f"
|
||||
|
||||
@@ -5,14 +5,14 @@ The static PE probe, the interpreter and the native ARM64 dynamic binary transla
|
||||
| Part | File | Role |
|
||||
| --- | --- | --- |
|
||||
| Registry | `crates/loader/x86/instructions.toml` | Opcode map, opcode, ModRM digit, operand encoding, size, immediate, flag effects and public reference. Data only. |
|
||||
| Generator | `crates/loader/generate_x86.py` | `validate`, `generate` and `--check`. Rejects overlapping encodings, opcodes that are prefixes, contradictory operand rules, unknown vocabulary and flags both written and undefined. |
|
||||
| Generator | `crates/loader/generate_x86.py` | `validate`, `generate` and `--check`. Rejects overlapping encodings, opcodes that are prefixes, contradictory operand rules, a fixed r/m field on a form that could take memory, unknown vocabulary and flags both written and undefined. |
|
||||
| Tables | `crates/loader/src/x86_table.rs` | Generated static tables. No metadata is parsed at run time. |
|
||||
| Semantics | `crates/loader/src/x86_exec.rs`, `x86_simd.rs`, `x86_float.rs`, `softfloat.rs` | Rust primitives for integer, vector and floating-point forms. Every instruction is all-or-nothing. |
|
||||
| Lowering | `crates/loader/src/dbt.rs` | ARM64 for the forms `is_native` accepts. Every other form calls the shared semantics and is counted in `DbtMetrics::interpreter_fallbacks`. |
|
||||
|
||||
## Adding a form
|
||||
|
||||
1. Add the form, and its operation if new, to the registry with an Intel SDM or AMD APM reference.
|
||||
1. Add the form, and its operation if new, to the registry with an Intel SDM or AMD APM reference. A form that is one exact ModRM byte, not a whole digit, takes `register_only = true` and `rm = N`.
|
||||
2. Run `python3 crates/loader/generate_x86.py generate`.
|
||||
3. Implement the operation in `x86_exec.rs`. Leave flags the manuals call undefined unchanged.
|
||||
4. Add assembly text to `crates/loader/tests/x86/assemble.py`, run it with `generate`, and extend the reference in `tests/x86_integer.rs` or `tests/x86_vector.rs`. A declared form without a fixture fails `every_declared_form_is_executed_by_a_fixture`.
|
||||
@@ -68,6 +68,21 @@ MFENCE, LFENCE and SFENCE (`0F AE` with a register ModRM byte and digit 6, 5 or
|
||||
|
||||
This holds only while guest threads do not run on several host threads. ARM64 orders memory more weakly than x86, so an engine that ran guest threads in parallel would have to restore x86's ordering for ordinary accesses and give the fences a real effect. Nothing here provides or tests that. `tests/cpu_known_answers.rs` holds the single-thread cases: a store, a fence and a later load in program order, and no change to any other state. None of it has been compared with x86 hardware.
|
||||
|
||||
## x87 state and FNINIT
|
||||
|
||||
FNINIT (`DB E3`) is the only x87 instruction. It exists because the mingw-w64 C runtime runs it once before `main`, in `_fpreset`, and a program built with that runtime could not start without it.
|
||||
|
||||
`CpuState::x87` holds the control, status and tag words. FNINIT sets them to the values the Intel SDM gives (Vol. 2A, "FINIT/FNINIT"): control `037F` (every exception masked, 64-bit precision, round to nearest), status `0` and tag `FFFF` (every register empty). It changes nothing else, and both engines run the same shared code for it; nothing is lowered to ARM64. The host's floating-point state is never read or written.
|
||||
|
||||
What this does not include:
|
||||
|
||||
- **No other x87 instruction.** FNSTCW, FLDCW, FNCLEX, FWAIT (so FINIT, which is `9B DB E3`), every load, store and arithmetic form stay rejected. Nothing can read the three words back, so today they are only visible to a host that inspects `CpuState`.
|
||||
- **No data registers.** FNINIT leaves them unchanged on a real processor and tags them empty; Xenora has none. The x87 instruction and data pointers and the last opcode, which FNINIT also clears, are not modelled either.
|
||||
- **No operating-system start value.** A new `CpuState` holds the FNINIT values. An operating system may start a thread with a different control word, which is not modelled.
|
||||
- **CPUID still reports no FPU.** One instruction of the feature is not the feature.
|
||||
|
||||
The registry key `rm = 3` makes the form match that one ModRM byte. The other register bytes of `DB /4` are different instructions (`DB E2` is FNCLEX), so the form cannot ignore the r/m field the way the fences do. `fninit_is_the_only_x87_encoding_accepted` in `tests/x86_integer.rs` tries every ModRM byte under the eight x87 opcodes, `D8` to `DF`, in both engines. A segment override or REX prefix before FNINIT is accepted and has no effect, as for other forms without operands. `prefixes_accepted_before_fninit_have_no_effect` pins that as a local rule; it was not derived from a manual statement. The 0x66, F2, F3 and LOCK prefixes are refused. Nothing here has been compared with x86 hardware.
|
||||
|
||||
## String instructions
|
||||
|
||||
MOVS and STOS exist for 8-, 16-, 32- and 64-bit elements, alone and with REP (F3), together with the direction flag and CLD and STD. `CpuState::df` holds the flag. It is not one of the six status flags the registry tracks.
|
||||
@@ -89,12 +104,12 @@ CPUID (`0F A2`) returns a fixed table that never reads the host. It describes a
|
||||
| 0 | 1, the highest basic leaf | `Xeno` | `uest` | `ra g` |
|
||||
| 1 | 0 | 0 | POPCNT (bit 23) | CMOV (bit 15) |
|
||||
| 0x8000_0000 | 0x8000_0001, the highest extended leaf | 0 | 0 | 0 |
|
||||
| 0x8000_0001 | 0 | 0 | LZCNT (bit 5) | long mode (bit 29) |
|
||||
| 0x8000_0001 | 0 | 0 | LAHF/SAHF (bit 0), LZCNT (bit 5) | long mode (bit 29) |
|
||||
| any other | 0 | 0 | 0 | 0 |
|
||||
|
||||
A feature bit is set only when every instruction of that feature is implemented. That is stricter than "some of it works", and it has consequences:
|
||||
|
||||
- SSE and SSE2 are not reported, although most of their instructions exist, because parts are still rejected: RSQRTPS and MASKMOVDQU, for example. BMI1 is not reported although TZCNT exists, because ANDN does not. The x87 FPU, MMX, FXSAVE, CMPXCHG8B, the time-stamp counter, LAHF and SYSRET are absent too.
|
||||
- SSE and SSE2 are not reported, although most of their instructions exist, because parts are still rejected: RSQRTPS and MASKMOVDQU, for example. BMI1 is not reported although TZCNT exists, because ANDN does not. The x87 FPU is not reported although FNINIT exists. MMX, FXSAVE, CMPXCHG8B, the time-stamp counter and SYSRET are absent too.
|
||||
- The table is therefore truthful about BetterXen, not plausible as hardware: every real 64-bit processor reports the FPU and SSE2. A guest that tests a bit before using a feature avoids it; a guest that assumes SSE2 because it runs in 64-bit mode still gets every form that exists and an illegal-instruction exit for one that does not.
|
||||
- A leaf that is not listed returns zeros, whatever the subleaf. Intel processors answer a leaf above the highest basic one with that leaf's data instead; software is expected to read the highest leaf first.
|
||||
|
||||
@@ -104,4 +119,4 @@ A feature bit is set only when every instruction of that feature is implemented.
|
||||
|
||||
## Rejected on purpose
|
||||
|
||||
LOCK except as described above, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, LODS, CMPS, SCAS, REPE and REPNE, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B and CMPXCHG16B. The DBT also refuses raw SYSCALL.
|
||||
LOCK except as described above, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, LODS, CMPS, SCAS, REPE and REPNE, every x87 instruction except FNINIT, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B and CMPXCHG16B. The DBT also refuses raw SYSCALL.
|
||||
+165
-3
@@ -78,11 +78,35 @@ Windows while the process has one thread. The exit closes every guest handle:
|
||||
kernel objects, Winsock sockets and task-queue handles, which
|
||||
`ServicesState::open_handle_count` counts together. Files stay on the synthetic `C:` drive, guest memory stays mapped so the host
|
||||
can inspect it, and `atexit` functions are not run: that belongs to the C
|
||||
runtime's `exit`, which is not implemented. `ServicesState::exit_status`
|
||||
runtime's `exit`, described below. `ServicesState::exit_status`
|
||||
reports the status. After an exit the `DbtEngine` that ran the guest executes
|
||||
no further guest instruction and answers every later `run` with the same
|
||||
`ProcessExit`. A service callback that was in progress is never resumed.
|
||||
|
||||
A C program ends through the C runtime instead. `ucrtbase.dll` and
|
||||
`api-ms-win-crt-runtime-l1-1-0.dll` provide three ways out, each ending the
|
||||
guest with the same `ProcessExit` and the same cleanup as `ExitProcess`:
|
||||
|
||||
| Service | Behaviour |
|
||||
| --- | --- |
|
||||
| `exit(status)` | Calls the functions registered with `atexit` and `_crt_atexit`, most recently registered first, then ends the process with `status` |
|
||||
| `_exit(status)` | Ends the process with `status` and calls no registered function |
|
||||
| `abort()` | Ends the process with exit code 3 and calls no registered function |
|
||||
|
||||
`exit` takes one function at a time from the registered list. A function
|
||||
registered while `exit` runs is therefore called next, before the older ones
|
||||
that have not run yet, which is ISO C's rule. A registered function that calls
|
||||
`exit` again is undefined in ISO C; here the functions that have not run yet
|
||||
run once each and the process ends with the status of the later call.
|
||||
Functions that `_cexit` has already run are not run again.
|
||||
|
||||
All three are partial. `exit` flushes no stream, because there are none, and
|
||||
runs no thread-local destructor. It does not walk a module's own `_onexit`
|
||||
table; that module's startup code runs it through `_execute_onexit_table`.
|
||||
`abort` prints no message and does not call a `SIGABRT` handler, which the
|
||||
documentation says it does when one is set. `_Exit`, `quick_exit` and
|
||||
`_c_exit` are not provided. None of this has been compared with Windows.
|
||||
|
||||
A TLS callback may end the process too. Startup then reports the exit as its
|
||||
outcome, with the status, and runs neither the remaining callbacks nor the
|
||||
entry point; `StartupResult::tls_callbacks` counts the callbacks that finished.
|
||||
@@ -222,6 +246,24 @@ References include Microsoft's
|
||||
[virtual allocation](https://learn.microsoft.com/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc),
|
||||
and [virtual release](https://learn.microsoft.com/windows/win32/api/memoryapi/nf-memoryapi-virtualfree) contracts.
|
||||
|
||||
### Stubs a hosted C program binds
|
||||
|
||||
`VirtualProtect`, `VirtualQuery` and `__C_specific_handler` are declared
|
||||
`stub` in the typed registry (`docs/runtime/services.md`). A C program built
|
||||
with the mingw-w64 runtime imports all three and does not call them on a
|
||||
normal run: the first two serve its runtime pseudo-relocations, and the third
|
||||
is the language handler Windows calls while dispatching a structured
|
||||
exception. They exist so that such a program's imports bind.
|
||||
|
||||
A call to any of them stops the guest with the runtime-limit fault
|
||||
(`IllegalInstruction(0xFE)`). The service writes nothing: no output buffer, no
|
||||
result and no last-error value. It does not return a made-up success or a
|
||||
failure code Windows would not give, so a program that needs one of them
|
||||
stops at that call. Nothing here changes a page protection, describes a
|
||||
region or dispatches an exception; each needs work the runtime does not have
|
||||
yet (regions that can be split, translated-code invalidation for executable
|
||||
pages, recorded allocation bases, exception dispatch).
|
||||
|
||||
### CRT strings and byte memory
|
||||
|
||||
The standard registry provides `strlen` and `strnlen` under UCRT and the CRT
|
||||
@@ -241,6 +283,43 @@ up to 1 MiB. Each nonempty span must be fully mapped with the required permissio
|
||||
A span may cross adjacent guest regions. Writes validate the full destination before changing
|
||||
bytes, and moves preserve the original source bytes when ranges overlap.
|
||||
|
||||
### Program arguments and environment
|
||||
|
||||
A hosted C program's startup code gets `argc`, `argv` and `envp` for `main`
|
||||
from five C runtime services. A host supplies the arguments with
|
||||
`ServicesState::set_program_arguments(&["program", "first", ...])`, program
|
||||
name first, before it runs the guest.
|
||||
|
||||
| Service | Behaviour |
|
||||
| --- | --- |
|
||||
| `__p___argc()`, `__p___argv()`, `__p__environ()` | The address of the guest variable `__argc`, `__argv` or `_environ`. All three start as zero or null |
|
||||
| `_configure_narrow_argv(mode)` | For mode 1 or 2, sets `__argc` to the number of arguments and `__argv` to a table of pointers to their NUL-terminated strings, with a null pointer after the last, and returns 0. It builds the table once; later calls return 0 and change nothing. Mode 0 returns 0 and builds nothing. Any other mode returns `EINVAL` |
|
||||
| `_initialize_narrow_environment()` | Points `_environ` at a table holding one null pointer, once, and returns 0 |
|
||||
|
||||
`set_program_arguments` refuses an argument containing a NUL byte, arguments
|
||||
whose bytes and terminators exceed 32,767 (`MAX_PROGRAM_ARGUMENT_BYTES`, the
|
||||
documented Windows command-line limit), and a call after the guest has built
|
||||
its table. A host that never calls it gives the program one argument, the
|
||||
empty string, which is what ISO C specifies when no program name is
|
||||
available. An empty list gives it none.
|
||||
|
||||
What is documented, inferred and chosen:
|
||||
|
||||
- **Documented:** the three global variables and what they hold, and ISO C's
|
||||
rules for `argv` (a null pointer after the last argument, strings the
|
||||
program may modify).
|
||||
- **Inferred:** that each `__p_` function returns the address of its
|
||||
variable, as the documented `__p__fmode` does. Microsoft lists these five
|
||||
functions only by name.
|
||||
- **Xenora's choice:** what the two initialization functions do. Arguments
|
||||
reach the guest as the bytes of the host's strings, with no code page.
|
||||
Mode 2 asks for wildcard expansion and none is performed. The environment
|
||||
is empty. The variables and tables are blocks from the process heap.
|
||||
|
||||
The wide-character counterparts, `GetCommandLineA` and `GetCommandLineW`, and
|
||||
environment variables do not exist. All five services are `partial`. None of
|
||||
this has been compared with Windows.
|
||||
|
||||
### Guest heaps
|
||||
|
||||
`GetProcessHeap`, `HeapAlloc`, `HeapSize`, and `HeapFree` expose the
|
||||
@@ -264,6 +343,62 @@ Allocation failures also set the synthetic main thread's CRT `errno` to
|
||||
and CRT parameter or new-handler callbacks remain unsupported. See
|
||||
[Microsoft CRT allocation documentation](https://learn.microsoft.com/cpp/c-runtime-library/memory-allocation).
|
||||
|
||||
### Standard output and formatted printing
|
||||
|
||||
A hosted C program prints through the C runtime. Six services give it the
|
||||
standard streams, and what it writes to `stdout` and to `stderr` is captured
|
||||
where a host or a test can read it: `ServicesState::standard_output()` and
|
||||
`ServicesState::standard_error()`.
|
||||
|
||||
| Service | Behaviour |
|
||||
| --- | --- |
|
||||
| `__acrt_iob_func(index)` | The `FILE` object of `stdin` (0), `stdout` (1) or `stderr` (2) |
|
||||
| `__stdio_common_vfprintf(options, stream, format, locale, arguments)` | Formats with the arguments in the guest's `va_list`, writes to `stdout` or `stderr`, and returns the number of characters written. This is what `printf` and `fprintf` call |
|
||||
| `fwrite(buffer, size, count, stream)` | Writes `size * count` bytes and returns `count` |
|
||||
| `fputs(string, stream)` | Writes the string without its terminator and returns 0 |
|
||||
| `fflush(stream)` | Returns 0. A null stream means every stream |
|
||||
| `setvbuf(stream, buffer, mode, size)` | Checks the mode and size and returns 0 |
|
||||
|
||||
The standard streams are text-mode streams, so each line feed a program
|
||||
writes is captured as a carriage return and a line feed, as the Windows
|
||||
documentation of text mode describes. Function results count the characters
|
||||
before that replacement. Output is never held back: `fflush` has nothing to
|
||||
do and `setvbuf` only validates. Each captured stream keeps at most 16 MiB
|
||||
(`MAX_CAPTURED_OUTPUT`).
|
||||
|
||||
The formatting engine (`crates/loader/src/services/crt_format.rs`) follows
|
||||
Microsoft's "Format specification syntax: printf and wprintf functions" and
|
||||
ISO C:
|
||||
|
||||
- Flags `-`, `+`, blank, `#` and `0`; a width and a precision as digits or
|
||||
`*`; size prefixes `hh`, `h`, `l`, `ll`, `j`, `z`, `t`, `I`, `I32`, `I64`.
|
||||
- Types `d`, `i`, `u`, `o`, `x`, `X`, `c`, `s`, `p` and `%%`. An integer
|
||||
without a size prefix, and a `long`, is 32 bits. A null string prints
|
||||
`(null)`.
|
||||
- Its output is compared with the host C library's `snprintf` on 2,600
|
||||
generated cases whose result ISO C defines
|
||||
(`crates/loader/tests/printf/reference.py`).
|
||||
|
||||
Documented failures return their documented result and set `errno` to
|
||||
`EINVAL`: a null stream, format, buffer or string, and an invalid `setvbuf`
|
||||
mode or size. An invalid format, which includes `%n` because Windows
|
||||
disables it by default, also returns -1 with `EINVAL` and writes nothing;
|
||||
on Windows the invalid parameter handler runs first.
|
||||
|
||||
Everything else that is not modelled stops the guest with the runtime-limit
|
||||
fault and writes nothing, so that nothing is printed wrongly: the
|
||||
floating-point types (`e`, `f`, `g`, `a`), wide characters and strings (`C`,
|
||||
`S`, `lc`, `ls`), a locale object, option bits other than the three that do
|
||||
not affect these conversions, any stream other than `stdout` and `stderr`
|
||||
(files do not exist yet, and `stdin` cannot be written), an index above 2,
|
||||
more than 1 MiB in one call, and output past the 16 MiB bound.
|
||||
|
||||
Choices where the documentation leaves room, each marked in the source:
|
||||
`%p` prints sixteen upper-case hexadecimal digits; `0` pads a character and
|
||||
a string as it pads a number; a precision also limits `(null)`; `%#.0o` of
|
||||
zero prints `0`, which is ISO C's rule. All six services are `partial`. None
|
||||
of this has been compared with Windows.
|
||||
|
||||
### CRT integer conversion
|
||||
|
||||
UCRT and the CRT conversion API set expose strtol, strtoul, wcstol, and
|
||||
@@ -450,8 +585,8 @@ The CRT uses this for:
|
||||
on the default guest heap, and they hold at most 65,536 entries. Execution
|
||||
resets the table first, then calls the functions in reverse order of
|
||||
registration. `atexit` and `_crt_atexit` record process exit functions,
|
||||
which `_cexit` runs in reverse order. Process termination through `exit` is
|
||||
not modeled.
|
||||
which `_cexit` runs in reverse order and returns. `exit` runs them and
|
||||
then ends the process; see "PE32+ fixture startup" above.
|
||||
|
||||
Null comparators, null arrays with a nonzero count, and reversed or
|
||||
misaligned tables would reach the CRT invalid-parameter handler. That
|
||||
@@ -467,6 +602,33 @@ initialization use `api-ms-win-core-synch-l1-2-0`; SLists use
|
||||
`api-ms-win-core-processthreads-l1-1-0`; and FLS uses
|
||||
`api-ms-win-core-fibers-l1-1-0`.
|
||||
|
||||
### C runtime startup configuration
|
||||
|
||||
A C program's startup code configures the C runtime before `main`. Nine
|
||||
services record what it sets and return what their public documentation says.
|
||||
They are declared in the typed registry (`docs/runtime/services.md`), all
|
||||
`partial`, because nothing acts on a recorded value:
|
||||
|
||||
| Service | Returns | Not provided |
|
||||
| --- | --- | --- |
|
||||
| `_set_app_type(type)` | nothing | Nothing depends on the type |
|
||||
| `_set_new_mode(mode)` | the previous mode; -1 and `errno` `EINVAL` unless the mode is 0 or 1 | `malloc` never calls a new handler |
|
||||
| `_configthreadlocale(request)` | the setting before the call (1 enabled, 2 disabled; a program starts disabled); -1 and `errno` `EINVAL` unless the request is 0, 1 or 2 | There is no locale |
|
||||
| `__setusermatherr(handler)` | nothing | The handler is never called |
|
||||
| `_set_invalid_parameter_handler(handler)` | the previous handler, null at first | No service calls it for an invalid argument |
|
||||
| `__p__fmode()`, `__p__commode()` | the address of the guest `int` `_fmode` (initially `_O_TEXT`, `0x4000`, as documented) or `_commode` (initially 0; its documentation gives no initial value) | Nothing reads either until stdio exists |
|
||||
| `signal(sig, handler)` | the previous handler, `SIG_DFL` at first; `SIG_ERR` and `errno` `EINVAL` for a signal other than `SIGINT`, `SIGILL`, `SIGFPE`, `SIGSEGV`, `SIGTERM` and `SIGABRT` | No signal is ever raised. One table serves the process |
|
||||
| `SetUnhandledExceptionFilter(filter)` | the previous filter, null at first | No exception reaches it |
|
||||
|
||||
`_fmode` and `_commode` share one 8-byte block allocated from the process heap
|
||||
on the first call to either. `ServicesState::crt_app_type` and
|
||||
`ServicesState::crt_user_math_error` let a host read the two values no service
|
||||
returns. `signal.h` also defines `SIGBREAK` and `SIGABRT_COMPAT`, which the
|
||||
documentation of `signal` does not list; they are refused, and whether Windows
|
||||
accepts them was not checked. `memcpy` also resolves through
|
||||
`api-ms-win-crt-private-l1-1-0.dll`, the API set the mingw-w64 runtime imports
|
||||
it from. None of this has been compared with Windows.
|
||||
|
||||
## Synthetic tiled textures
|
||||
|
||||
The texture crate reads original fixtures in an array-layer-major layout. Each
|
||||
|
||||
@@ -6,14 +6,14 @@ A declared service is not a claim of compatibility. `implemented` and `partial`
|
||||
|
||||
| Measure | Count |
|
||||
| --- | ---: |
|
||||
| Services with a declared ABI | 20 |
|
||||
| Generated adapters | 20 |
|
||||
| Unique handler implementations | 20 |
|
||||
| Services with a declared ABI | 43 |
|
||||
| Generated adapters | 43 |
|
||||
| Unique handler implementations | 43 |
|
||||
| Implemented | 7 |
|
||||
| Partial | 13 |
|
||||
| Stub | 0 |
|
||||
| Conformance-tested through guest dispatch | 20 |
|
||||
| API-set aliases (not services) | 20 |
|
||||
| Partial | 33 |
|
||||
| Stub | 3 |
|
||||
| Conformance-tested through guest dispatch | 43 |
|
||||
| API-set aliases (not services) | 43 |
|
||||
| Independently accepted | 0 |
|
||||
|
||||
| Service | Signature | Status | Failure |
|
||||
@@ -30,11 +30,34 @@ A declared service is not a claim of compatibility. `implemented` and `partial`
|
||||
| `kernel32.dll!SetThreadPriority` | `(thread: handle, priority: i32) -> bool32` | partial | 0 with ERROR_INVALID_HANDLE, ERROR_ACCESS_DENIED, ERROR_NOT_SUPPORTED or ERROR_INVALID_PARAMETER |
|
||||
| `kernel32.dll!CloseHandle` | `(object: handle) -> bool32` | partial | 0 with ERROR_INVALID_HANDLE |
|
||||
| `kernel32.dll!GetSystemTimeAsFileTime` | `(time: out<8>) -> void` | implemented | guest fault on an invalid pointer |
|
||||
| `ucrtbase.dll!__acrt_iob_func` | `(index: u32) -> ptr` | partial | stops the guest for an index above 2 or when the streams cannot be allocated |
|
||||
| `ucrtbase.dll!__stdio_common_vfprintf` | `(options: u64, stream: ptr, format: ptr, locale: ptr, arguments: ptr) -> i32` | partial | -1 with errno EINVAL for a null stream or format or an invalid format; stops the guest for what is not modelled |
|
||||
| `ucrtbase.dll!fwrite` | `(buffer: ptr, size: u64, count: u64, stream: ptr) -> u64` | partial | 0 with errno EINVAL for a null buffer or stream; stops the guest for a stream other than stdout or stderr |
|
||||
| `ucrtbase.dll!fputs` | `(text: ptr, stream: ptr) -> i32` | partial | EOF with errno EINVAL for a null string or stream; stops the guest for a stream other than stdout or stderr |
|
||||
| `ucrtbase.dll!fflush` | `(stream: ptr) -> i32` | partial | stops the guest for a stream that is not a standard stream |
|
||||
| `ucrtbase.dll!setvbuf` | `(stream: ptr, buffer: ptr, mode: i32, size: u64) -> i32` | partial | -1 with errno EINVAL for a null stream, an unknown mode or a size outside 2 to INT_MAX; stops the guest for a stream that is not a standard stream |
|
||||
| `kernel32.dll!GetLastError` | `() -> u32` | partial | never |
|
||||
| `kernel32.dll!SetLastError` | `(code: u32) -> void` | partial | never |
|
||||
| `ucrtbase.dll!__p___argc` | `() -> ptr` | partial | stops the guest when the variable cannot be allocated |
|
||||
| `ucrtbase.dll!__p___argv` | `() -> ptr` | partial | stops the guest when the variable cannot be allocated |
|
||||
| `ucrtbase.dll!__p__environ` | `() -> ptr` | partial | stops the guest when the variable cannot be allocated |
|
||||
| `ucrtbase.dll!_configure_narrow_argv` | `(mode: i32) -> i32` | partial | EINVAL for a mode other than 0, 1 or 2; stops the guest when the table cannot be allocated |
|
||||
| `ucrtbase.dll!_initialize_narrow_environment` | `() -> i32` | partial | stops the guest when the table cannot be allocated |
|
||||
| `kernel32.dll!VirtualAlloc` | `(address: ptr, size: u64, kind: u32, protect: u32) -> ptr` | partial | 0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED, ERROR_INVALID_ADDRESS or ERROR_NOT_ENOUGH_MEMORY |
|
||||
| `kernel32.dll!VirtualFree` | `(address: ptr, size: u64, kind: u32) -> bool32` | partial | 0 with ERROR_NOT_SUPPORTED, ERROR_INVALID_PARAMETER or ERROR_INVALID_ADDRESS |
|
||||
| `kernel32.dll!VirtualProtect` | `(address: ptr, size: u64, protect: u32, old: out<4>) -> bool32` | stub | always: stops the guest with the runtime-limit fault; no protection changes |
|
||||
| `kernel32.dll!VirtualQuery` | `(address: ptr, information: out<48>, length: u64) -> u64` | stub | always: stops the guest with the runtime-limit fault; nothing is written |
|
||||
| `ucrtbase.dll!__C_specific_handler` | `(record: ptr, frame: ptr, context: ptr, dispatcher: ptr) -> i32` | stub | always: stops the guest with the runtime-limit fault; no exception is dispatched |
|
||||
| `ucrtbase.dll!sqrt` | `(x: f64) -> f64` | partial | NaN for a negative argument; errno is not set |
|
||||
| `ucrtbase.dll!sqrtf` | `(x: f32) -> f32` | partial | NaN for a negative argument; errno is not set |
|
||||
| `ucrtbase.dll!fabs` | `(x: f64) -> f64` | implemented | never |
|
||||
| `ucrtbase.dll!fabsf` | `(x: f32) -> f32` | implemented | never |
|
||||
| `ucrtbase.dll!_set_app_type` | `(kind: i32) -> void` | partial | never |
|
||||
| `ucrtbase.dll!_set_new_mode` | `(mode: i32) -> i32` | partial | -1 with errno EINVAL for a mode other than 0 or 1 |
|
||||
| `ucrtbase.dll!_configthreadlocale` | `(request: i32) -> i32` | partial | -1 with errno EINVAL for a request other than 0, 1 or 2 |
|
||||
| `ucrtbase.dll!__setusermatherr` | `(handler: ptr) -> void` | partial | never |
|
||||
| `ucrtbase.dll!_set_invalid_parameter_handler` | `(handler: ptr) -> ptr` | partial | never |
|
||||
| `ucrtbase.dll!__p__fmode` | `() -> ptr` | partial | stops the guest when the variable cannot be allocated |
|
||||
| `ucrtbase.dll!__p__commode` | `() -> ptr` | partial | stops the guest when the variable cannot be allocated |
|
||||
| `ucrtbase.dll!signal` | `(signal: i32, handler: ptr) -> ptr` | partial | SIG_ERR with errno EINVAL for a signal the documentation does not list |
|
||||
| `kernel32.dll!SetUnhandledExceptionFilter` | `(filter: ptr) -> ptr` | partial | never |
|
||||
+20
-5
@@ -8,7 +8,7 @@ when both pass.
|
||||
| Milestone | What it is | Status |
|
||||
| --- | --- | --- |
|
||||
| A1 | An original C program with no C library linked, importing documented `kernel32.dll` and `ucrtbase.dll` functions, run through the loader and the ARM64 DBT with proper process exit | Passes locally; awaiting independent review |
|
||||
| A2 | A hosted C program: a real C runtime startup, the standard C library, `argc` and `argv`, stdio and formatted output, normal exit and runtime cleanup | Not started |
|
||||
| A2 | A hosted C program: a real C runtime startup, the standard C library, `argc` and `argv`, stdio and formatted output, normal exit and runtime cleanup | In progress; does not pass |
|
||||
|
||||
## A1
|
||||
|
||||
@@ -47,7 +47,22 @@ whose entry point returns its status gives the same result as `ExitProcess`.
|
||||
|
||||
## A2
|
||||
|
||||
Not started. It needs at least the C standard I/O functions, `exit` with
|
||||
`atexit` handlers, command-line and environment access, and a decision on
|
||||
which C runtime startup code may be linked and under what licence. None of
|
||||
those are registered today.
|
||||
In progress. It does not pass, and there is no A2 test in the repository yet.
|
||||
|
||||
The target is an original C program built with the mingw-w64 runtime (UCRT),
|
||||
whose own startup code runs before `main`. Such a program needs pieces that
|
||||
are being added one issue at a time. This page records only what is in the
|
||||
tree it is part of:
|
||||
|
||||
| Piece | State here |
|
||||
| --- | --- |
|
||||
| Normal exit: `exit` with its `atexit` functions, `_exit` and `abort` | Present (#395), on top of the process exit A1 added |
|
||||
| The PE headers mapped at the image base, which the startup code reads | Separate change (#333) |
|
||||
| `FNINIT`, the one instruction the startup code needs that was refused | Separate change (#378) |
|
||||
| The C runtime startup calls, and the functions a program imports but does not call | Separate changes (#382, #388) |
|
||||
| `argc`, `argv` and the environment table | Separate change (#392) |
|
||||
| Standard streams, files and formatted output | Not started |
|
||||
| The A2 program itself, its build and its test | Not started |
|
||||
|
||||
Until the last two rows exist nothing here shows a hosted C program running,
|
||||
and A2 must not be reported as passing.
|
||||
@@ -75,6 +75,29 @@ class GenerateX86(unittest.TestCase):
|
||||
self.rejects(self.form('op = "mov"\nopcode = 0xD7\nenc = "reg_rm"\nsize = "v"\nlock = true'), message)
|
||||
self.rejects(self.form('op = "xadd"\nopcode = 0xD7\nenc = "rm_reg"\nsize = "v"\nregister_only = true\nlock = true'), message)
|
||||
|
||||
def test_a_fixed_rm_field_needs_a_register_only_digit_form(self):
|
||||
base = 'op = "nop"\nopcode = 0xD9\nenc = "rm_unread"\nsize = "n"\n'
|
||||
message = "needs register_only and a digit"
|
||||
self.rejects(self.form(base + "digit = 0\nrm = 3"), message)
|
||||
self.rejects(self.form(base + "digit = 0\nmemory_only = true\nrm = 3"), message)
|
||||
self.rejects(self.form(base + "register_only = true\nrm = 3"), message)
|
||||
for value in ("8", "-1", "true", '"3"'):
|
||||
self.rejects(self.form(base + f"digit = 0\nregister_only = true\nrm = {value}"), "r/m field value 0-7")
|
||||
# A second form on the same opcode and digit is an overlap, whatever its r/m field.
|
||||
self.rejects(self.form('op = "nop"\nopcode = 0xDB\ndigit = 4\nenc = "rm_unread"\nsize = "n"\n'
|
||||
"register_only = true\nrm = 2"), "overlapping")
|
||||
# The valid shape loads, and the key reaches the generated table.
|
||||
operations, forms = generate_x86.load(self.form(base + "digit = 0\nregister_only = true\nrm = 7"))
|
||||
self.assertEqual([f["rm"] for f in forms if f["map"] == "1" and f["opcode"] == 0xD9], [7])
|
||||
self.assertIn("register_only: true, fixed_rm: Some(7),", generate_x86.generate(operations, forms))
|
||||
|
||||
def test_fninit_is_the_only_form_with_a_fixed_rm_field_and_the_only_x87_form(self):
|
||||
_, forms = generate_x86.load(REGISTRY)
|
||||
fixed = [(f["op"], f["map"], f["opcode"], f["digit"], f["rm"]) for f in forms if f["rm"] is not None]
|
||||
self.assertEqual(fixed, [("fninit", "1", 0xDB, 4, 3)])
|
||||
x87 = [f["op"] for f in forms if f["map"] == "1" and 0xD8 <= f["opcode"] <= 0xDF]
|
||||
self.assertEqual(x87, ["fninit"])
|
||||
|
||||
def test_only_xadd_and_cmpxchg_are_lockable(self):
|
||||
_, forms = generate_x86.load(REGISTRY)
|
||||
self.assertEqual({form["op"] for form in forms if form.get("lock")}, {"cmpxchg", "xadd"})
|
||||
|
||||
Reference in new issue
Block a user