mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 20:50:44 +00:00
Compare commits
27
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4b96aebedc | ||
|
|
53e5e38a4e | ||
|
|
3b47c21bb0 | ||
|
|
9a62d86a89 | ||
|
|
4b32c532fe | ||
|
|
bbc84c0da0 | ||
|
|
d2f77cdea3 | ||
|
|
3a36379db4 | ||
|
|
147e2a9f1a | ||
|
|
a7fa8b0d65 | ||
|
|
e6b657a2e9 | ||
|
|
c05e631c6d | ||
|
|
34a583b101 | ||
|
|
061c28b405 | ||
|
|
0214a7bab5 | ||
|
|
47b526fba9 | ||
|
|
c68e3ccb4c | ||
|
|
fb6282ceb2 | ||
|
|
2f28a5adbb | ||
|
|
788de1e83b | ||
|
|
1013746e17 | ||
|
|
9ddb708cdf | ||
|
|
6f1ac2a906 | ||
|
|
782c49167c | ||
|
|
c95e175210 | ||
|
|
509811aad0 | ||
|
|
b9372408c8 |
No files matched your search
@@ -10,6 +10,8 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Changed
|
||||
- The native ARM64 DBT now runs the 32- and 64-bit register and immediate forms of ADC and SBB itself instead of falling back to the shared interpreter (#195). The guest CF is moved into the host carry before ADCS or SBCS, inverted for SBB because SBCS subtracts NOT C while SBB subtracts CF. Memory forms and 8- and 16-bit forms still use the shared semantics. `tests/x86_carry_chain.rs` runs 256-bit add and subtract chains of 64- and 32-bit limbs, in one block and split one block per limb, against widening `u128`/`i128` reference arithmetic in both engines, plus immediate 128-bit increments and decrements and the `sbb reg, reg` carry mask. Locally verified on Apple M5 only.
|
||||
- Removed the temporary region-list allocation from each instruction-byte fetch while preserving lookup order, execute-permission checks and error behavior (part of #104).
|
||||
- Release and bench builds now use fat link-time optimization with one codegen unit (#116). On a local Apple M5, `dbt_bench` medians over five alternating runs dropped by about 6 % for the interpreter (903 to 845 µs) and about 9 % for cold DBT (1.155 to 1.046 ms), while warm DBT (cache hits) became about 2 % slower (21.83-22.08 to 22.29-22.54 µs over four further runs). The `xenora` binary shrank from 2.73 to 2.11 MB. A clean release build of the workspace takes about 14 s instead of 6 s. Debug and test builds are unchanged.
|
||||
- The ARM64 assembler loads 64-bit constants with the fewest MOVZ or MOVN plus MOVK instructions (#92). It no longer emits MOVK for zero halfwords and starts from MOVN when more halfwords are 0xFFFF than zero, so small negative values take one instruction instead of four. On Apple M5 the DBT benchmark emits 245,168 instead of 290,184 native bytes for its 626 blocks (-15.5%) and the 1,048 integer fixture instructions 128,724 instead of 145,732 (-11.7%); benchmark run times did not change measurably. New tests check the sequences against LLVM encodings and execute 1,056 of them on the host through the JIT.
|
||||
- Resolve the tiled BC1 mip and array layer once per linearization and copy contiguous block runs within each tile row. Partial edge blocks are retained and padding slots are skipped. Closes #349.
|
||||
@@ -19,15 +21,25 @@ remains unsupported.
|
||||
- Moved gfx1030 `s_mov_b32` (SOP1) into the semantic registry, preserving its existing decode domain and shader output. The move operand rule retains explicit VCC and EXEC half destinations. Part of #215.
|
||||
- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215.
|
||||
- Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches.
|
||||
- Reuse up to 16 native Metal compute pipelines per context for repeated shader source and entry points. Pending dispatches retain their pipelines through completion, including after eviction. Dispatch profiles report zero library and pipeline setup time when a cached pipeline is reused. Closes #132.
|
||||
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
|
||||
|
||||
### Fixed
|
||||
- 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
|
||||
- `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.
|
||||
- `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).
|
||||
- Added the VOP3A (`_e64`) encodings of eleven gfx1030 VOP2 integer forms (`v_mul_{i32_i24,hi_i32_i24,u32_u24,hi_u32_u24}`, `v_{min,max}_{i32,u32}`, `v_xnor_b32`, `v_sub_nc_u32`, `v_subrev_nc_u32`) and of the sixteen Wave32 integer compares (explicit SGPR mask destination, `s_cbranch_vccz` through `vcc_lo`, a translation error for reads of runtime-only SGPR results) as semantic-registry encoding variants, with VGPR sources only. New fixtures `vop3-integer` and `vop3-compare` with IR and MSL goldens, and an independent guide-derived oracle (`tests/validation/tests/vop3_{integer,compare}.rs`) that agrees on both reference interpreters and on native Metal. Part of #215.
|
||||
- Added `scripts/cpu-tests.sh`, which lists the default-feature workspace test targets and runs
|
||||
deterministic shards of them (`--shard K/N`), with `--check N` showing every target lands in
|
||||
exactly one shard. It does not replace `cargo test --locked --workspace` or
|
||||
`scripts/test-gpu.sh`. `docs/testing/cpu-coverage.md` records local CPU gate timings on one
|
||||
Apple M4 host (about 40 s wall time; one loader target takes about 19 s) and shows that the 2- and
|
||||
3-shard unions match the full gate's 681 passed and 34 ignored tests (#159).
|
||||
- Added guest texture binding through D3D12-style descriptor tables (#303): shader-visible CBV_SRV_UAV and sampler heaps, `CreateShaderResourceView` for one-level RGBA8 and BC1 2D textures, a point/clamp `CreateSampler`, a root signature with one pixel-stage SRV table and one sampler table, and `SetDescriptorHeaps`/`SetGraphicsRootDescriptorTable` in `crates/loader/src/graphics.rs`, plus `NativeCompute::render_rgba8_sampled_bc1`. Verified locally on an Apple M5 Pro under Metal validation: a guest draw with the translated `image_sample_lz` pixel stage matches the software reference and hand-derived images on 16 of 16 pixels for two RGBA8 textures and 64 of 64 for an 8×8 BC1 texture. A wrong descriptor slot changes the image, off-centre and out-of-range coordinates point-sample with clamping, and a rejected binding, draw shape or resource state never reaches the backend. The software reference samples BC1 with the spec-exact decoder, while Apple's hardware rounds BC1's interpolated palette entries differently (171/84 against 170/85), so the BC1 fixtures use only endpoint colours. Not yet reachable from guest imports. Not yet independently accepted.
|
||||
- Added MOVNTI, the SSE2 non-temporal store of a 32- or 64-bit general register to memory (part of #125). Both engines used to stop on it with an illegal-instruction exit. It is an ordinary store, as the other non-temporal stores already are; the register form and the 66 prefix stay rejected, and a destination that cannot be written faults without changing state. The SDM-derived case `movdqa_movaps_aligned_store_and_load` in `cpu_known_answers.rs`, which ends in a MOVNTI, moved from refused to verified, and `tests/x86/integer.txt` gains four assembled instructions checked by the text-only reference in `x86_integer.rs`. MASKMOVDQU stays rejected and SSE2 stays unreported by CPUID. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added MFENCE, LFENCE and SFENCE and documented the ordering of guest memory accesses (part of #199). Both engines used to stop on a fence with an illegal-instruction exit. Each engine runs one guest instruction at a time on one host thread and completes its loads and stores before the next, so accesses are already totally ordered and the fences change nothing; `docs/cpu/instruction-registry.md` states this and that it holds only while guest threads do not run on several host threads. Five single-thread cases in `cpu_known_answers.rs` and three assembled fixtures cover them, and the memory forms that share the opcode stay rejected. SSE2 is still not reported by CPUID because other SSE2 instructions are rejected; the refused SSE2 instruction that `cpu_features.rs` holds is now MASKMOVDQU. No multi-thread behaviour is established, and nothing was compared with x86 hardware; awaiting independent review.
|
||||
@@ -204,6 +216,8 @@ 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).
|
||||
- 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.
|
||||
- Fixed the MXCSR flags of an unmasked floating-point overflow whose result is exact before the exponent is bounded, such as the largest binary32 value times two (#128). Only the overflow flag is set; the precision flag used to be set as well although nothing was rounded. A masked overflow still sets both flags and delivers infinity or the largest finite value, and an unmasked overflow that is also inexact still sets both. Five Intel SDM cases in `cpu_known_answers.rs` moved from open defect to verified on both engines, with three more for the other rounding modes, and the scalar and conversion sweeps now compare the precision flag in this case as well. Not compared with x86 hardware; awaiting independent review.
|
||||
- Fixed the decoder refusing an instruction whose REX prefix is followed by a legacy prefix (#69). Such a REX is ignored, as the Intel SDM (Vol. 2A, 2.2.1) specifies, so `48 66 01 D8` now runs as `add ax, bx`; it used to stop the guest with an illegal-instruction exit. The ignored byte still counts toward the instruction's length, and a REX that directly precedes the opcode behaves as before. The interpreter, the DBT and the static probe share the decoder. One SDM-derived case in `cpu_known_answers.rs` moved from refused to verified and three were added, for an ignored REX.B, an ignored REX.W before a segment prefix, and a later REX that does apply. Two REX bytes in a row and the address-size prefix stay rejected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Fixed import binding writing some slots before finding an unresolved import, and service calls taking effect before an unreadable return address was noticed. A service that changes a nonvolatile register, including XMM6 to XMM15, now stops the guest (part of #201).
|
||||
|
||||
@@ -309,7 +309,7 @@ These require a Metal-capable Apple Silicon Mac.
|
||||
scripts/test-gpu.sh
|
||||
```
|
||||
|
||||
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths. The full semantic-review batch defaults to a 300-second timeout; set `XENORA_SEMANTIC_TIMEOUT` to raise or lower it for a slower or faster host.
|
||||
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths. The full semantic-review batch defaults to a 300-second timeout; set `XENORA_SEMANTIC_TIMEOUT` to raise or lower it for a slower or faster host. On macOS, the script uses a Python 3 fallback when GNU `timeout` is unavailable.
|
||||
|
||||
### Verify guest execution
|
||||
|
||||
|
||||
+1137
-15
File diff suppressed because it is too large.
Load diff
@@ -430,6 +430,46 @@ impl Arm64Assembler {
|
||||
);
|
||||
}
|
||||
|
||||
/// ADCS (64-bit, flags updating): ADCS Xd, Xn, Xm computes Xn + Xm + C.
|
||||
pub fn adcs_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xba000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// ADCS (32-bit, flags updating): ADCS Wd, Wn, Wm computes Wn + Wm + C.
|
||||
pub fn adcs_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
|
||||
self.emit(
|
||||
0x3a000000
|
||||
| ((wm as u32 & 0x1f) << 16)
|
||||
| ((wn as u32 & 0x1f) << 5)
|
||||
| (wd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// SBCS (64-bit, flags updating): SBCS Xd, Xn, Xm computes Xn - Xm - !C.
|
||||
pub fn sbcs_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xfa000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// SBCS (32-bit, flags updating): SBCS Wd, Wn, Wm computes Wn - Wm - !C.
|
||||
pub fn sbcs_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
|
||||
self.emit(
|
||||
0x7a000000
|
||||
| ((wm as u32 & 0x1f) << 16)
|
||||
| ((wn as u32 & 0x1f) << 5)
|
||||
| (wd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// ADD (immediate, 64-bit): ADD Xd, Xn, #imm12
|
||||
pub fn add_imm_64(&mut self, xd: u8, xn: u8, imm12: u16) {
|
||||
self.emit(
|
||||
|
||||
@@ -335,6 +335,9 @@ pub fn is_native(insn: &Insn) -> bool {
|
||||
let scanned = matches!(insn.size, 2 | 4 | 8);
|
||||
match insn.op {
|
||||
Op::Add | Op::Sub | Op::Cmp | Op::And | Op::Or | Op::Xor | Op::Test => wide,
|
||||
// Register and immediate forms only; a memory destination would have
|
||||
// to restore the guest carry again after the store helper call.
|
||||
Op::Adc | Op::Sbb => wide && insn.memory().is_none(),
|
||||
Op::Inc | Op::Dec | Op::Neg | Op::Not => wide,
|
||||
Op::Cmov => wide,
|
||||
Op::Bsf | Op::Bsr => scanned,
|
||||
@@ -587,9 +590,26 @@ impl Emitter<'_> {
|
||||
}
|
||||
|
||||
/// X11 = X9 op X10, setting host NZCV only for the arithmetic operations.
|
||||
/// ADC and SBB also read the guest CF and clobber X12 and X13.
|
||||
fn compute(&mut self, op: Op, wide: bool) {
|
||||
let asm = &mut *self.asm;
|
||||
if matches!(op, Op::Adc | Op::Sbb) {
|
||||
// ADCS adds the host C, so C must equal the guest CF. SBCS
|
||||
// subtracts NOT C, while x86 SBB subtracts the borrow CF, so there
|
||||
// C must be its inverse. A compare sets C when it does not borrow.
|
||||
asm.ldrb_uoff(X12, X19, CF);
|
||||
if op == Op::Adc {
|
||||
asm.load_imm_64(X13, 1);
|
||||
asm.cmp_reg_32(X12, X13); // C = CF >= 1
|
||||
} else {
|
||||
asm.cmp_reg_32(XZR, X12); // C = 0 >= CF
|
||||
}
|
||||
}
|
||||
match (op, wide) {
|
||||
(Op::Adc, true) => asm.adcs_reg_64(X11, X9, X10),
|
||||
(Op::Adc, false) => asm.adcs_reg_32(X11, X9, X10),
|
||||
(Op::Sbb, true) => asm.sbcs_reg_64(X11, X9, X10),
|
||||
(Op::Sbb, false) => asm.sbcs_reg_32(X11, X9, X10),
|
||||
(Op::Add | Op::Inc, true) => asm.adds_reg_64(X11, X9, X10),
|
||||
(Op::Add | Op::Inc, false) => asm.adds_reg_32(X11, X9, X10),
|
||||
(Op::And | Op::Test, true) => asm.ands_reg_64(X11, X9, X10),
|
||||
@@ -623,7 +643,7 @@ impl Emitter<'_> {
|
||||
match op {
|
||||
// INC and DEC leave CF unchanged.
|
||||
Op::Inc | Op::Dec => {}
|
||||
Op::Add => {
|
||||
Op::Add | Op::Adc => {
|
||||
asm.cset_32(X12, Condition::Cs);
|
||||
asm.strb_uoff(X12, X19, CF);
|
||||
}
|
||||
|
||||
+221
-3
@@ -515,9 +515,20 @@ impl GuestMemory {
|
||||
|
||||
/// Read an instruction byte from guest memory, verifying execute permission.
|
||||
pub fn fetch_instruction_byte(&self, address: u64) -> Result<u8, MemoryError> {
|
||||
let mut buf = [0u8; 1];
|
||||
self.read_checked(address, &mut buf, Some("execute"))?;
|
||||
Ok(buf[0])
|
||||
address.checked_add(1).ok_or(MemoryError::Overflow)?;
|
||||
let region = self
|
||||
.regions
|
||||
.iter()
|
||||
.find(|region| region.base + region.data.len() as u64 > address)
|
||||
.filter(|region| region.base <= address)
|
||||
.ok_or(MemoryError::UnmappedAddress(address))?;
|
||||
if !region.permissions.execute {
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "execute",
|
||||
});
|
||||
}
|
||||
Ok(region.data[(address - region.base) as usize])
|
||||
}
|
||||
|
||||
/// Read a 64-bit integer (little endian) from guest memory.
|
||||
@@ -636,3 +647,210 @@ mod tests {
|
||||
assert_eq!(memory.heap_allocation_size(PROCESS_HEAP, moved), Some(1));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod instruction_fetch_tests {
|
||||
use super::{MemoryPermissions as P, *};
|
||||
|
||||
fn denied(address: u64) -> Result<u8, MemoryError> {
|
||||
Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "execute",
|
||||
})
|
||||
}
|
||||
fn missing(address: u64) -> Result<u8, MemoryError> {
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_reports_overflow_before_lookup() {
|
||||
let m = GuestMemory::new();
|
||||
for at in [0, 1, 0x1000, u64::MAX - 1] {
|
||||
assert_eq!(m.fetch_instruction_byte(at), missing(at));
|
||||
}
|
||||
assert_eq!(
|
||||
m.fetch_instruction_byte(u64::MAX),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(u64::MAX, 0, P::NO_ACCESS).unwrap();
|
||||
assert_eq!(
|
||||
m.fetch_instruction_byte(u64::MAX),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_checks_execute_permission_for_every_byte_value() {
|
||||
let bytes: Vec<u8> = (0..=255).collect();
|
||||
for flags in 0..8 {
|
||||
let permission = P {
|
||||
read: flags & 1 != 0,
|
||||
write: flags & 2 != 0,
|
||||
execute: flags & 4 != 0,
|
||||
};
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(0x1000, bytes.len(), permission, &bytes)
|
||||
.unwrap();
|
||||
for (offset, byte) in bytes.iter().enumerate() {
|
||||
let at = 0x1000 + offset as u64;
|
||||
assert_eq!(
|
||||
m.fetch_instruction_byte(at),
|
||||
if flags & 4 != 0 {
|
||||
Ok(*byte)
|
||||
} else {
|
||||
denied(at)
|
||||
},
|
||||
"flags={flags}, at={at:x}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_handles_sparse_and_out_of_order_mappings() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(0x3000, 2, P::READ_EXECUTE, &[0xc1, 0xc2])
|
||||
.unwrap();
|
||||
m.map_region_with_data(0, 2, P::READ_EXECUTE, &[0x01, 0x02])
|
||||
.unwrap();
|
||||
m.map_region_with_data(0x2000, 1, P::READ_ONLY, &[0xb1])
|
||||
.unwrap();
|
||||
m.map_region_with_data(0x1000, 2, P::READ_EXECUTE, &[0xa1, 0xa2])
|
||||
.unwrap();
|
||||
for (at, byte) in [
|
||||
(0, 1),
|
||||
(1, 2),
|
||||
(0x1000, 0xa1),
|
||||
(0x1001, 0xa2),
|
||||
(0x3000, 0xc1),
|
||||
(0x3001, 0xc2),
|
||||
] {
|
||||
assert_eq!(m.fetch_instruction_byte(at), Ok(byte));
|
||||
}
|
||||
assert_eq!(m.fetch_instruction_byte(0x2000), denied(0x2000));
|
||||
for at in [2, 0xfff, 0x1002, 0x2001, 0x2fff, 0x3002] {
|
||||
assert_eq!(m.fetch_instruction_byte(at), missing(at));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_ignores_empty_mappings_at_shared_boundaries() {
|
||||
for zero_first in [false, true] {
|
||||
for execute in [false, true] {
|
||||
let mut m = GuestMemory::new();
|
||||
let permission = P {
|
||||
read: false,
|
||||
write: false,
|
||||
execute,
|
||||
};
|
||||
if zero_first {
|
||||
for _ in 0..7 {
|
||||
m.map_region(0x1000, 0, P::READ_WRITE_EXECUTE).unwrap();
|
||||
}
|
||||
}
|
||||
m.map_region_with_data(0x1000, 2, permission, &[0x34, 0x56])
|
||||
.unwrap();
|
||||
for _ in 0..7 {
|
||||
m.map_region(0x1000, 0, P::NO_ACCESS).unwrap();
|
||||
}
|
||||
for _ in 0..7 {
|
||||
m.map_region(0x1002, 0, P::READ_WRITE_EXECUTE).unwrap();
|
||||
}
|
||||
for (at, byte) in [(0x1000, 0x34), (0x1001, 0x56)] {
|
||||
assert_eq!(
|
||||
m.fetch_instruction_byte(at),
|
||||
if execute { Ok(byte) } else { denied(at) }
|
||||
);
|
||||
}
|
||||
assert_eq!(m.fetch_instruction_byte(0x1002), missing(0x1002));
|
||||
}
|
||||
}
|
||||
let mut m = GuestMemory::new();
|
||||
for at in [1, 1, 2, 0x1000] {
|
||||
m.map_region(at, 0, P::READ_WRITE_EXECUTE).unwrap();
|
||||
}
|
||||
for at in [0, 1, 2, 3, 0x1000] {
|
||||
assert_eq!(m.fetch_instruction_byte(at), missing(at));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_checks_adjacent_mapping_permissions() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(0x1000, 1, P::READ_EXECUTE, &[0xa5])
|
||||
.unwrap();
|
||||
m.map_region_with_data(0x1001, 1, P::READ_WRITE, &[0x5a])
|
||||
.unwrap();
|
||||
m.map_region(0x1001, 0, P::READ_EXECUTE).unwrap();
|
||||
m.map_region_with_data(0x1002, 1, P::READ_EXECUTE, &[0xc3])
|
||||
.unwrap();
|
||||
assert_eq!(m.fetch_instruction_byte(0x1000), Ok(0xa5));
|
||||
assert_eq!(m.fetch_instruction_byte(0x1001), denied(0x1001));
|
||||
assert_eq!(m.fetch_instruction_byte(0x1002), Ok(0xc3));
|
||||
assert_eq!(m.fetch_instruction_byte(0x1003), missing(0x1003));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_handles_the_highest_region_end() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(u64::MAX - 2, 2, P::READ_EXECUTE, &[0x12, 0x34])
|
||||
.unwrap();
|
||||
m.map_region(u64::MAX, 0, P::READ_EXECUTE).unwrap();
|
||||
assert_eq!(
|
||||
m.fetch_instruction_byte(u64::MAX - 3),
|
||||
missing(u64::MAX - 3)
|
||||
);
|
||||
assert_eq!(m.fetch_instruction_byte(u64::MAX - 2), Ok(0x12));
|
||||
assert_eq!(m.fetch_instruction_byte(u64::MAX - 1), Ok(0x34));
|
||||
assert_eq!(
|
||||
m.fetch_instruction_byte(u64::MAX),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_observes_writes_clones_and_mapping_changes() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(0x1000, 1, P::READ_WRITE_EXECUTE, &[0x11])
|
||||
.unwrap();
|
||||
let mut clone = m.clone();
|
||||
m.write_u8(0x1000, 0x22).unwrap();
|
||||
clone.write_u8(0x1000, 0x33).unwrap();
|
||||
assert_eq!(m.fetch_instruction_byte(0x1000), Ok(0x22));
|
||||
assert_eq!(clone.fetch_instruction_byte(0x1000), Ok(0x33));
|
||||
let base = m
|
||||
.map_virtual_allocation(0x4000, 1, P::READ_WRITE_EXECUTE)
|
||||
.unwrap();
|
||||
m.write_u8(base, 0x44).unwrap();
|
||||
assert_eq!(m.fetch_instruction_byte(base), Ok(0x44));
|
||||
assert!(m.release_virtual_allocation(base));
|
||||
assert_eq!(m.fetch_instruction_byte(base), missing(base));
|
||||
m.map_region_with_data(base, 1, P::READ_ONLY, &[0x55])
|
||||
.unwrap();
|
||||
assert_eq!(m.fetch_instruction_byte(base), denied(base));
|
||||
assert_eq!(clone.fetch_instruction_byte(base), missing(base));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_keeps_first_mapping_priority_after_empty_heap_growth() {
|
||||
// Existing private allocation methods can grow a zero allocation onto an
|
||||
// earlier mapping at its base. The fetch-only patch must preserve the
|
||||
// original mapping's priority even for this already-representable state.
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(0x1000, 1, P::READ_EXECUTE, &[0x90])
|
||||
.unwrap();
|
||||
const BASE: u64 = 0x0000_0003_0000_0000;
|
||||
m.map_region_with_data(BASE, 4, P::READ_EXECUTE, &[0x11, 0x22, 0x33, 0x44])
|
||||
.unwrap();
|
||||
let empty = m.map_heap_allocation(PROCESS_HEAP, 0).unwrap();
|
||||
assert_eq!(empty, BASE);
|
||||
assert_eq!(
|
||||
m.resize_heap_allocation(PROCESS_HEAP, empty, 2, true),
|
||||
Ok(BASE)
|
||||
);
|
||||
assert_eq!(m.fetch_instruction_byte(BASE), Ok(0x11));
|
||||
assert_eq!(m.fetch_instruction_byte(BASE + 1), Ok(0x22));
|
||||
assert_eq!(m.fetch_instruction_byte(BASE + 3), Ok(0x44));
|
||||
}
|
||||
}
|
||||
+446
-26
@@ -11,11 +11,39 @@ use crate::memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
use crate::pe::ParsedPe;
|
||||
use std::fmt;
|
||||
|
||||
/// Most callbacks one TLS directory may list.
|
||||
pub const MAX_TLS_CALLBACKS: usize = 64;
|
||||
|
||||
/// Bytes below the stack top that a callback is entered with: the return
|
||||
/// address and the 32-byte home space the Win64 convention gives every callee.
|
||||
const CALLBACK_FRAME: u64 = 40;
|
||||
|
||||
/// Errors arising during TLS setup or callback invocation.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum TlsError {
|
||||
DirectoryOutOfBounds { rva: u32 },
|
||||
InvalidTemplateRange { start: u64, end: u64 },
|
||||
DirectoryOutOfBounds {
|
||||
rva: u32,
|
||||
},
|
||||
InvalidTemplateRange {
|
||||
start: u64,
|
||||
end: u64,
|
||||
},
|
||||
/// `AddressOfCallbacks` is not zero and not inside a section of the image.
|
||||
CallbackArrayOutOfBounds {
|
||||
address: u64,
|
||||
},
|
||||
/// The callback array leaves its section before a null entry.
|
||||
CallbackArrayUnterminated {
|
||||
address: u64,
|
||||
},
|
||||
/// The callback array lists more than [`MAX_TLS_CALLBACKS`] entries.
|
||||
TooManyCallbacks {
|
||||
limit: usize,
|
||||
},
|
||||
/// The stack cannot hold a callback's entry frame or is not 16-byte aligned.
|
||||
InvalidCallbackStack {
|
||||
stack_top: u64,
|
||||
},
|
||||
CallbackExecutionFault(ExitReason),
|
||||
Memory(MemoryError),
|
||||
}
|
||||
@@ -32,6 +60,27 @@ impl fmt::Display for TlsError {
|
||||
"invalid TLS template range: 0x{start:016x}..0x{end:016x}"
|
||||
)
|
||||
}
|
||||
Self::CallbackArrayOutOfBounds { address } => {
|
||||
write!(
|
||||
f,
|
||||
"TLS callback array at 0x{address:016x} is outside the image"
|
||||
)
|
||||
}
|
||||
Self::CallbackArrayUnterminated { address } => {
|
||||
write!(
|
||||
f,
|
||||
"TLS callback array at 0x{address:016x} has no null entry in its section"
|
||||
)
|
||||
}
|
||||
Self::TooManyCallbacks { limit } => {
|
||||
write!(f, "TLS callback array lists more than {limit} callbacks")
|
||||
}
|
||||
Self::InvalidCallbackStack { stack_top } => {
|
||||
write!(
|
||||
f,
|
||||
"stack top 0x{stack_top:016x} cannot hold an aligned TLS callback frame"
|
||||
)
|
||||
}
|
||||
Self::CallbackExecutionFault(e) => {
|
||||
write!(f, "fault during TLS callback execution: {e}")
|
||||
}
|
||||
@@ -78,7 +127,7 @@ pub fn parse_tls_directory(bytes: &[u8], pe: &ParsedPe) -> Result<Option<TlsDire
|
||||
) as usize;
|
||||
|
||||
// TLS directory is directory index 9 (offset 112 + 9 * 8 = 184 in Optional Header)
|
||||
if size_of_opt < 192 || bytes.len() < opt_offset + 188 {
|
||||
if size_of_opt < 192 || bytes.len() < opt_offset + 192 {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
@@ -114,24 +163,7 @@ pub fn parse_tls_directory(bytes: &[u8], pe: &ParsedPe) -> Result<Option<TlsDire
|
||||
u32::from_le_bytes(bytes[tls_off + 32..tls_off + 36].try_into().unwrap());
|
||||
let characteristics = u32::from_le_bytes(bytes[tls_off + 36..tls_off + 40].try_into().unwrap());
|
||||
|
||||
let mut callbacks = Vec::new();
|
||||
if callbacks_address >= pe.image_base {
|
||||
let cb_rva = (callbacks_address - pe.image_base) as u32;
|
||||
if let Some(cb_off) = pe.rva_to_file_offset(cb_rva) {
|
||||
let mut curr = cb_off;
|
||||
while curr + 8 <= bytes.len() {
|
||||
let target = u64::from_le_bytes(bytes[curr..curr + 8].try_into().unwrap());
|
||||
if target == 0 {
|
||||
break;
|
||||
}
|
||||
callbacks.push(target);
|
||||
curr += 8;
|
||||
if callbacks.len() >= 64 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let callbacks = read_callbacks(bytes, pe, callbacks_address)?;
|
||||
|
||||
Ok(Some(TlsDirectory {
|
||||
raw_data_start_va,
|
||||
@@ -144,9 +176,74 @@ pub fn parse_tls_directory(bytes: &[u8], pe: &ParsedPe) -> Result<Option<TlsDire
|
||||
}))
|
||||
}
|
||||
|
||||
/// Read the null-terminated callback array that `address` names.
|
||||
///
|
||||
/// A null `address` means the image has no callbacks. Any other value must be a
|
||||
/// virtual address inside one section, and the array must reach its null entry
|
||||
/// inside that section. Bytes past the section's file data, up to its virtual
|
||||
/// size, are zero in the loaded image and are read as zero here.
|
||||
fn read_callbacks(bytes: &[u8], pe: &ParsedPe, address: u64) -> Result<Vec<u64>, TlsError> {
|
||||
if address == 0 {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let (section, start) = address
|
||||
.checked_sub(pe.image_base)
|
||||
.and_then(|rva| u32::try_from(rva).ok())
|
||||
.and_then(|rva| {
|
||||
pe.sections.iter().find_map(|section| {
|
||||
let offset = rva.checked_sub(section.virtual_address)?;
|
||||
let extent = section.virtual_size.max(section.raw_data_size);
|
||||
(offset < extent).then_some((section, u64::from(offset)))
|
||||
})
|
||||
})
|
||||
.ok_or(TlsError::CallbackArrayOutOfBounds { address })?;
|
||||
let extent = u64::from(section.virtual_size.max(section.raw_data_size));
|
||||
let byte_at = |offset: u64| -> Option<u8> {
|
||||
if offset >= extent {
|
||||
None
|
||||
} else if offset >= u64::from(section.raw_data_size) {
|
||||
Some(0)
|
||||
} else {
|
||||
let file = u64::from(section.raw_data_ptr) + offset;
|
||||
bytes.get(usize::try_from(file).ok()?).copied()
|
||||
}
|
||||
};
|
||||
|
||||
let mut callbacks = Vec::new();
|
||||
let mut offset = start;
|
||||
loop {
|
||||
let mut entry = [0u8; 8];
|
||||
for byte in &mut entry {
|
||||
*byte = byte_at(offset).ok_or(TlsError::CallbackArrayUnterminated { address })?;
|
||||
offset += 1;
|
||||
}
|
||||
let target = u64::from_le_bytes(entry);
|
||||
if target == 0 {
|
||||
return Ok(callbacks);
|
||||
}
|
||||
if callbacks.len() == MAX_TLS_CALLBACKS {
|
||||
return Err(TlsError::TooManyCallbacks {
|
||||
limit: MAX_TLS_CALLBACKS,
|
||||
});
|
||||
}
|
||||
callbacks.push(target);
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes reserved at `thread_tls_base` for the thread's TLS pointer array.
|
||||
const TLS_ARRAY_SIZE: usize = 0x1000;
|
||||
|
||||
/// Set up TLS runtime state in guest memory:
|
||||
/// 1. Assign TLS index (e.g. 0) at `index_address`.
|
||||
/// 2. Allocate and initialize per-thread TLS storage from the template.
|
||||
/// 1. Assign TLS index 0 at `index_address`.
|
||||
/// 2. Map the thread's TLS pointer array at `thread_tls_base`.
|
||||
/// 3. Map the thread's data block one page above it, initialized from the
|
||||
/// template and zero fill, and store its address in the array slot of the
|
||||
/// index.
|
||||
///
|
||||
/// `thread_tls_base` is the value the thread environment block holds as its
|
||||
/// TLS pointer. Compiled code loads that pointer, indexes it by the module's
|
||||
/// TLS index to find the data block, and then adds a variable's offset, so the
|
||||
/// array and the data are separate regions.
|
||||
pub fn setup_tls(
|
||||
tls: &TlsDirectory,
|
||||
loaded_base: u64,
|
||||
@@ -187,15 +284,25 @@ pub fn setup_tls(
|
||||
memory.read_bytes(actual_start, &mut template_data)?;
|
||||
}
|
||||
|
||||
// Allocate per-thread TLS block
|
||||
// Allocate the pointer array and the per-thread TLS block.
|
||||
let block_base = thread_tls_base
|
||||
.checked_add(TLS_ARRAY_SIZE as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
let page_size = 4096;
|
||||
let map_size = (total_size + page_size - 1) & !(page_size - 1);
|
||||
memory.map_region_with_data(
|
||||
memory.map_region(
|
||||
thread_tls_base,
|
||||
TLS_ARRAY_SIZE,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
)?;
|
||||
memory.map_region_with_data(
|
||||
block_base,
|
||||
map_size,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
&template_data,
|
||||
)?;
|
||||
// Slot 0 belongs to the index assigned above.
|
||||
memory.write_u64(thread_tls_base, block_base)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -206,6 +313,11 @@ pub fn setup_tls(
|
||||
/// - RCX = DllHandle (loaded_base)
|
||||
/// - RDX = Reason (DLL_PROCESS_ATTACH = 1)
|
||||
/// - R8 = Reserved (0)
|
||||
///
|
||||
/// Each callback is entered as after a CALL from a 16-byte aligned stack: RSP
|
||||
/// is `stack_top - 40`, holding the return address below 32 bytes of home
|
||||
/// space. A `stack_top` that is not 16-byte aligned or cannot hold that frame
|
||||
/// is rejected before any callback runs.
|
||||
pub fn execute_tls_callbacks(
|
||||
callbacks: &[u64],
|
||||
loaded_base: u64,
|
||||
@@ -215,6 +327,12 @@ pub fn execute_tls_callbacks(
|
||||
memory: &mut GuestMemory,
|
||||
dbt: &mut DbtEngine,
|
||||
) -> Result<usize, TlsError> {
|
||||
if callbacks.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
if stack_top < CALLBACK_FRAME || !stack_top.is_multiple_of(16) {
|
||||
return Err(TlsError::InvalidCallbackStack { stack_top });
|
||||
}
|
||||
let delta = (loaded_base as i128) - (preferred_base as i128);
|
||||
let mut executed_count = 0;
|
||||
|
||||
@@ -224,7 +342,7 @@ pub fn execute_tls_callbacks(
|
||||
// Reset CPU state for callback execution adhering to Win64 ABI
|
||||
cpu.rip = actual_cb_va;
|
||||
// Stack pointer aligned with 32-byte shadow space + return address
|
||||
let rsp = stack_top - 40;
|
||||
let rsp = stack_top - CALLBACK_FRAME;
|
||||
cpu.set(Register::Rsp, rsp);
|
||||
// Write synthetic magic return address (0xFFFF_FFFF_FFFF_0000) into [RSP]
|
||||
let magic_ret = 0xFFFF_FFFF_FFFF_0000u64;
|
||||
@@ -261,3 +379,305 @@ pub fn execute_tls_callbacks(
|
||||
|
||||
Ok(executed_count)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
//! Expectations come from Microsoft's public PE Format page (the TLS
|
||||
//! directory: `AddressOfCallbacks` is a virtual address of a null-terminated
|
||||
//! array, and a callback is `void cb(PVOID DllHandle, DWORD Reason, PVOID
|
||||
//! Reserved)`) and its x64 calling convention page (the stack is 16-byte
|
||||
//! aligned before a call, the caller provides 32 bytes of home space, and
|
||||
//! the first three integer arguments are in RCX, RDX and R8). The headers
|
||||
//! and code bytes below are original. Nothing here ran on Windows.
|
||||
|
||||
use super::*;
|
||||
use crate::pe::PeSection;
|
||||
|
||||
const IMAGE_BASE: u64 = 0x1_4000_0000;
|
||||
const SECTION_RVA: u32 = 0x1000;
|
||||
const SECTION_FILE: usize = 0x400;
|
||||
const SECTION_SIZE: u32 = 0x400;
|
||||
/// Offset of the optional header: `e_lfanew` (0x80), signature, COFF header.
|
||||
const OPTIONAL_HEADER: usize = 0x80 + 24;
|
||||
|
||||
fn parsed(virtual_size: u32) -> ParsedPe {
|
||||
ParsedPe {
|
||||
machine: 0x8664,
|
||||
number_of_sections: 1,
|
||||
time_date_stamp: 0,
|
||||
image_base: IMAGE_BASE,
|
||||
section_alignment: 0x1000,
|
||||
file_alignment: 0x200,
|
||||
size_of_image: 0x3000,
|
||||
size_of_headers: 0x400,
|
||||
entry_point_rva: 0,
|
||||
sections: vec![PeSection {
|
||||
name: ".rdata".into(),
|
||||
virtual_address: SECTION_RVA,
|
||||
virtual_size,
|
||||
raw_data_ptr: SECTION_FILE as u32,
|
||||
raw_data_size: SECTION_SIZE,
|
||||
characteristics: crate::pe::IMAGE_SCN_MEM_READ,
|
||||
permissions: MemoryPermissions::READ_ONLY,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
/// A file with one section holding a TLS directory at its start and the
|
||||
/// callback `entries` at `array_rva`. The directory names `callbacks_address`.
|
||||
/// Every byte after the section's file data is 0xCC.
|
||||
fn file(callbacks_address: u64, array_rva: u32, entries: &[u64]) -> Vec<u8> {
|
||||
let section_end = SECTION_FILE + SECTION_SIZE as usize;
|
||||
let mut bytes = vec![0u8; section_end];
|
||||
bytes.resize(section_end + 0x200, 0xCC);
|
||||
bytes[0x3C..0x40].copy_from_slice(&0x80u32.to_le_bytes());
|
||||
// SizeOfOptionalHeader: a PE32+ optional header with 16 data directories.
|
||||
bytes[0x94..0x96].copy_from_slice(&240u16.to_le_bytes());
|
||||
// Data directory 9 (TLS): RVA and size.
|
||||
let entry = OPTIONAL_HEADER + 112 + 9 * 8;
|
||||
bytes[entry..entry + 4].copy_from_slice(&SECTION_RVA.to_le_bytes());
|
||||
bytes[entry + 4..entry + 8].copy_from_slice(&40u32.to_le_bytes());
|
||||
// IMAGE_TLS_DIRECTORY64.AddressOfCallBacks is its fourth 8-byte field.
|
||||
bytes[SECTION_FILE + 24..SECTION_FILE + 32]
|
||||
.copy_from_slice(&callbacks_address.to_le_bytes());
|
||||
let mut at = SECTION_FILE + (array_rva - SECTION_RVA) as usize;
|
||||
for entry in entries {
|
||||
bytes[at..at + 8].copy_from_slice(&entry.to_le_bytes());
|
||||
at += 8;
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
fn callbacks_of(bytes: &[u8], pe: &ParsedPe) -> Result<Vec<u64>, TlsError> {
|
||||
parse_tls_directory(bytes, pe).map(|tls| tls.expect("a TLS directory").callbacks)
|
||||
}
|
||||
|
||||
const ARRAY_RVA: u32 = 0x1100;
|
||||
const ARRAY: u64 = IMAGE_BASE + ARRAY_RVA as u64;
|
||||
const FIRST: u64 = IMAGE_BASE + 0x2000;
|
||||
const SECOND: u64 = IMAGE_BASE + 0x2010;
|
||||
|
||||
#[test]
|
||||
fn callbacks_are_read_in_order_up_to_the_null_entry() {
|
||||
let bytes = file(ARRAY, ARRAY_RVA, &[FIRST, SECOND, 0, IMAGE_BASE + 0x2020]);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Ok(vec![FIRST, SECOND])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_null_callbacks_address_means_no_callbacks() {
|
||||
let bytes = file(0, ARRAY_RVA, &[FIRST, 0]);
|
||||
assert_eq!(callbacks_of(&bytes, &parsed(SECTION_SIZE)), Ok(vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_callback_array_outside_the_image_is_rejected() {
|
||||
for address in [8, IMAGE_BASE - 8, IMAGE_BASE + 0x800, IMAGE_BASE + 0x5000] {
|
||||
let bytes = file(address, ARRAY_RVA, &[FIRST, 0]);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Err(TlsError::CallbackArrayOutOfBounds { address }),
|
||||
"{address:#x}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_callback_array_address_is_not_truncated_to_32_bits() {
|
||||
// The low 32 bits of the offset name the real array.
|
||||
let address = ARRAY + (1 << 32);
|
||||
let bytes = file(address, ARRAY_RVA, &[FIRST, 0]);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Err(TlsError::CallbackArrayOutOfBounds { address })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_callback_array_must_end_inside_its_section() {
|
||||
// Two entries fill the last 16 bytes of the section; the file goes on.
|
||||
let rva = SECTION_RVA + SECTION_SIZE - 16;
|
||||
let address = IMAGE_BASE + u64::from(rva);
|
||||
let bytes = file(address, rva, &[FIRST, SECOND]);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Err(TlsError::CallbackArrayUnterminated { address })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_fill_after_the_section_file_data_ends_the_array() {
|
||||
// The section is larger in memory than in the file, so the bytes after
|
||||
// its file data are zero when loaded, whatever follows in the file.
|
||||
let rva = SECTION_RVA + SECTION_SIZE - 16;
|
||||
let address = IMAGE_BASE + u64::from(rva);
|
||||
let bytes = file(address, rva, &[FIRST, SECOND]);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE + 0x100)),
|
||||
Ok(vec![FIRST, SECOND])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_callback_array_over_the_limit_is_rejected() {
|
||||
let entries: Vec<u64> = (0..65).map(|index| FIRST + index * 16).collect();
|
||||
let mut at_limit = entries[..MAX_TLS_CALLBACKS].to_vec();
|
||||
at_limit.push(0);
|
||||
let bytes = file(ARRAY, ARRAY_RVA, &at_limit);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Ok(entries[..64].to_vec())
|
||||
);
|
||||
|
||||
let mut over = entries.clone();
|
||||
over.push(0);
|
||||
let bytes = file(ARRAY, ARRAY_RVA, &over);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Err(TlsError::TooManyCallbacks { limit: 64 })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_cut_inside_the_tls_data_directory_has_no_tls_directory() {
|
||||
let bytes = file(ARRAY, ARRAY_RVA, &[FIRST, 0]);
|
||||
let entry = OPTIONAL_HEADER + 112 + 9 * 8;
|
||||
for length in entry..entry + 8 {
|
||||
let directory = parse_tls_directory(&bytes[..length], &parsed(SECTION_SIZE));
|
||||
assert!(matches!(directory, Ok(None)), "length {length:#x}");
|
||||
}
|
||||
}
|
||||
|
||||
const CODE: u64 = 0x40_0000;
|
||||
const STACK_TOP: u64 = 0x80_0000;
|
||||
const SENTINEL: u64 = 0xFFFF_FFFF_FFFF_0000;
|
||||
|
||||
/// Code at `CODE`, a 4 KiB stack below `STACK_TOP` and a fresh translator.
|
||||
fn guest(code: &[u8]) -> (CpuState, GuestMemory, DbtEngine) {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(CODE, 0x1000, MemoryPermissions::READ_EXECUTE, code)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(STACK_TOP - 0x1000, 0x1000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
(
|
||||
CpuState::new(0, 0),
|
||||
memory,
|
||||
DbtEngine::new(64 * 1024).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Two callbacks 16 bytes apart. Each shifts RAX left by four bits and sets
|
||||
/// its own number in the low bits, so RAX records the order they ran in.
|
||||
const TAGGING: [u8; 25] = [
|
||||
0x48, 0xC1, 0xE0, 0x04, // shl rax, 4
|
||||
0x48, 0x83, 0xC8, 0x01, // or rax, 1
|
||||
0xC3, // ret
|
||||
0, 0, 0, 0, 0, 0, 0, // padding
|
||||
0x48, 0xC1, 0xE0, 0x04, // shl rax, 4
|
||||
0x48, 0x83, 0xC8, 0x02, // or rax, 2
|
||||
0xC3, // ret
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn a_callback_is_entered_with_the_win64_arguments_and_frame() {
|
||||
let code = [0x48, 0x89, 0xE0, 0xC3]; // mov rax, rsp; ret
|
||||
let (mut cpu, mut memory, mut dbt) = guest(&code);
|
||||
// Loaded 64 KiB above the preferred base: the listed address is rebased.
|
||||
let loaded = IMAGE_BASE + 0x1_0000;
|
||||
let listed = [CODE - 0x1_0000];
|
||||
let ran = execute_tls_callbacks(
|
||||
&listed,
|
||||
loaded,
|
||||
IMAGE_BASE,
|
||||
STACK_TOP,
|
||||
&mut cpu,
|
||||
&mut memory,
|
||||
&mut dbt,
|
||||
);
|
||||
assert_eq!(ran, Ok(1));
|
||||
let entry_rsp = cpu.get(Register::Rax);
|
||||
assert_eq!(entry_rsp, STACK_TOP - 40);
|
||||
// A callee is entered 8 bytes off 16-byte alignment, as after a CALL.
|
||||
assert_eq!(entry_rsp % 16, 8);
|
||||
assert_eq!(memory.read_u64(entry_rsp), Ok(SENTINEL));
|
||||
assert_eq!(cpu.get(Register::Rcx), loaded);
|
||||
assert_eq!(cpu.get(Register::Rdx), 1); // DLL_PROCESS_ATTACH
|
||||
assert_eq!(cpu.get(Register::R8), 0);
|
||||
// RET popped the return address and nothing else.
|
||||
assert_eq!(cpu.get(Register::Rsp), entry_rsp + 8);
|
||||
assert_eq!(cpu.rip, SENTINEL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callbacks_run_in_array_order() {
|
||||
for (order, recorded) in [([CODE, CODE + 16], 0x12), ([CODE + 16, CODE], 0x21)] {
|
||||
let (mut cpu, mut memory, mut dbt) = guest(&TAGGING);
|
||||
let ran = execute_tls_callbacks(
|
||||
&order,
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
STACK_TOP,
|
||||
&mut cpu,
|
||||
&mut memory,
|
||||
&mut dbt,
|
||||
);
|
||||
assert_eq!(ran, Ok(2));
|
||||
assert_eq!(cpu.get(Register::Rax), recorded);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_callback_over_the_instruction_budget_stops_the_sequence() {
|
||||
let mut code = TAGGING.to_vec();
|
||||
code.resize(32, 0);
|
||||
code.extend([0xEB, 0xFE]); // jmp to itself
|
||||
let (mut cpu, mut memory, mut dbt) = guest(&code);
|
||||
let ran = execute_tls_callbacks(
|
||||
&[CODE, CODE + 32, CODE + 16],
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
STACK_TOP,
|
||||
&mut cpu,
|
||||
&mut memory,
|
||||
&mut dbt,
|
||||
);
|
||||
assert_eq!(
|
||||
ran,
|
||||
Err(TlsError::CallbackExecutionFault(
|
||||
ExitReason::StepLimitExceeded
|
||||
))
|
||||
);
|
||||
// The first callback ran; the one after the endless one did not.
|
||||
assert_eq!(cpu.get(Register::Rax), 0x1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unusable_callback_stack_is_rejected_before_anything_runs() {
|
||||
for stack_top in [0, 32, STACK_TOP - 8, STACK_TOP - 1] {
|
||||
let (mut cpu, mut memory, mut dbt) = guest(&TAGGING);
|
||||
let ran = execute_tls_callbacks(
|
||||
&[CODE],
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
stack_top,
|
||||
&mut cpu,
|
||||
&mut memory,
|
||||
&mut dbt,
|
||||
);
|
||||
assert_eq!(
|
||||
ran,
|
||||
Err(TlsError::InvalidCallbackStack { stack_top }),
|
||||
"{stack_top:#x}"
|
||||
);
|
||||
assert_eq!(cpu, CpuState::new(0, 0));
|
||||
assert_eq!(memory.read_u64(STACK_TOP - 48), Ok(0));
|
||||
// No callback, no frame: the stack is not looked at.
|
||||
let none = execute_tls_callbacks(&[], 0, 0, stack_top, &mut cpu, &mut memory, &mut dbt);
|
||||
assert_eq!(none, Ok(0));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -164,3 +164,45 @@ fn vector_operations_match_llvm() {
|
||||
assert_eq!(assembler.instructions(), [*word], "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn carry_arithmetic_matches_llvm() {
|
||||
// `llvm-mc -triple=aarch64-apple-macos -show-encoding`.
|
||||
let cases: &[(&str, Emit, u32)] = &[
|
||||
(
|
||||
"adcs x11, x9, x10",
|
||||
|a| a.adcs_reg_64(11, 9, 10),
|
||||
0xba0a012b,
|
||||
),
|
||||
(
|
||||
"adcs w11, w9, w10",
|
||||
|a| a.adcs_reg_32(11, 9, 10),
|
||||
0x3a0a012b,
|
||||
),
|
||||
(
|
||||
"adcs x0, x30, x17",
|
||||
|a| a.adcs_reg_64(0, 30, 17),
|
||||
0xba1103c0,
|
||||
),
|
||||
(
|
||||
"sbcs x11, x9, x10",
|
||||
|a| a.sbcs_reg_64(11, 9, 10),
|
||||
0xfa0a012b,
|
||||
),
|
||||
(
|
||||
"sbcs w11, w9, w10",
|
||||
|a| a.sbcs_reg_32(11, 9, 10),
|
||||
0x7a0a012b,
|
||||
),
|
||||
(
|
||||
"sbcs w0, w30, w17",
|
||||
|a| a.sbcs_reg_32(0, 30, 17),
|
||||
0x7a1103c0,
|
||||
),
|
||||
];
|
||||
for (text, emit, word) in cases {
|
||||
let mut assembler = Arm64Assembler::new();
|
||||
emit(&mut assembler);
|
||||
assert_eq!(assembler.instructions(), [*word], "{text}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Thread-local storage layout as compiled code reads it (#76).
|
||||
//!
|
||||
//! Microsoft's public PE Format page ("The .tls Section") describes the
|
||||
//! access: load the address of the thread's TLS array from the thread
|
||||
//! environment block, load the module's TLS index from the address the TLS
|
||||
//! directory names, use the index times the pointer size as an offset into
|
||||
//! the array to get the address of the module's data block, then add the
|
||||
//! variable's offset in the template. The block starts as a copy of the
|
||||
//! template followed by `SizeOfZeroFill` zero bytes.
|
||||
//!
|
||||
//! The startup harness stores the `thread_tls_base` it passes to `setup_tls`
|
||||
//! in the TEB's TLS pointer field, so these tests start from that value and
|
||||
//! follow the same steps through guest memory. The directory and template are
|
||||
//! original. Nothing here ran on Windows.
|
||||
|
||||
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P, TlsDirectory, setup_tls};
|
||||
|
||||
const IMAGE: u64 = 0x1_4000_0000;
|
||||
const TEMPLATE: u64 = IMAGE + 0x3000;
|
||||
const INDEX: u64 = IMAGE + 0x4000;
|
||||
const THREAD_TLS: u64 = 0x3_0000_0000;
|
||||
/// Read as a pointer, the first eight bytes are the template's own address, so
|
||||
/// a layout that takes the data for the array still finds readable memory.
|
||||
const TEMPLATE_BYTES: [u8; 20] = [
|
||||
0x00, 0x30, 0x00, 0x40, 0x01, 0x00, 0x00, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,
|
||||
0xA1, 0xB2, 0xC3, 0xD4,
|
||||
];
|
||||
|
||||
fn directory(template_len: u64, zero_fill: u32) -> TlsDirectory {
|
||||
TlsDirectory {
|
||||
raw_data_start_va: TEMPLATE,
|
||||
raw_data_end_va: TEMPLATE + template_len,
|
||||
index_address: INDEX,
|
||||
size_of_zero_fill: zero_fill,
|
||||
..TlsDirectory::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// An image with the template in read-only data and a writable index that
|
||||
/// does not start at zero.
|
||||
fn image(base: u64) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
TEMPLATE - IMAGE + base,
|
||||
0x1000,
|
||||
P::READ_ONLY,
|
||||
&TEMPLATE_BYTES,
|
||||
)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(INDEX - IMAGE + base, 0x1000, P::READ_WRITE, &[0xFF; 8])
|
||||
.unwrap();
|
||||
memory
|
||||
}
|
||||
|
||||
/// The address of the module's data block, found the way compiled code does.
|
||||
fn block_address(memory: &GuestMemory, teb_tls_pointer: u64, index_address: u64) -> u64 {
|
||||
let index = u64::from(memory.read_u32(index_address).unwrap());
|
||||
memory.read_u64(teb_tls_pointer + index * 8).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tls_array_slot_leads_to_a_copy_of_the_template() {
|
||||
let mut memory = image(IMAGE);
|
||||
setup_tls(&directory(20, 12), IMAGE, IMAGE, &mut memory, THREAD_TLS).unwrap();
|
||||
|
||||
assert_eq!(memory.read_u32(INDEX), Ok(0));
|
||||
let block = block_address(&memory, THREAD_TLS, INDEX);
|
||||
assert_ne!(block, THREAD_TLS, "the array is not the data block");
|
||||
assert_ne!(block, TEMPLATE, "the block is the thread's own copy");
|
||||
let mut data = [0xEEu8; 32];
|
||||
memory.read_bytes(block, &mut data).unwrap();
|
||||
assert_eq!(data[..20], TEMPLATE_BYTES);
|
||||
assert_eq!(data[20..], [0u8; 12]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_thread_block_is_writable_and_separate_from_the_template() {
|
||||
let mut memory = image(IMAGE);
|
||||
setup_tls(&directory(20, 12), IMAGE, IMAGE, &mut memory, THREAD_TLS).unwrap();
|
||||
let block = block_address(&memory, THREAD_TLS, INDEX);
|
||||
|
||||
memory.write_u64(block + 8, 0x0102_0304_0506_0708).unwrap();
|
||||
assert_eq!(memory.read_u64(block + 8), Ok(0x0102_0304_0506_0708));
|
||||
// The image's template is the initial value for later threads.
|
||||
let mut template = [0u8; 20];
|
||||
memory.read_bytes(TEMPLATE, &mut template).unwrap();
|
||||
assert_eq!(template, TEMPLATE_BYTES);
|
||||
// The array slot still names the block after the block is written.
|
||||
assert_eq!(block_address(&memory, THREAD_TLS, INDEX), block);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rebased_image_uses_its_loaded_addresses() {
|
||||
let loaded = IMAGE + 0x20_0000;
|
||||
let mut memory = image(loaded);
|
||||
setup_tls(&directory(20, 0), loaded, IMAGE, &mut memory, THREAD_TLS).unwrap();
|
||||
|
||||
let index_address = INDEX - IMAGE + loaded;
|
||||
assert_eq!(memory.read_u32(index_address), Ok(0));
|
||||
let block = block_address(&memory, THREAD_TLS, index_address);
|
||||
let mut data = [0u8; 20];
|
||||
memory.read_bytes(block, &mut data).unwrap();
|
||||
assert_eq!(data, TEMPLATE_BYTES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zero_fill_only_directory_gets_a_zeroed_block() {
|
||||
let mut memory = image(IMAGE);
|
||||
setup_tls(&directory(0, 24), IMAGE, IMAGE, &mut memory, THREAD_TLS).unwrap();
|
||||
let block = block_address(&memory, THREAD_TLS, INDEX);
|
||||
let mut data = [0xEEu8; 24];
|
||||
memory.read_bytes(block, &mut data).unwrap();
|
||||
assert_eq!(data, [0u8; 24]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inverted_template_range_is_rejected_before_anything_is_mapped() {
|
||||
let mut memory = image(IMAGE);
|
||||
let mut inverted = directory(20, 0);
|
||||
inverted.raw_data_end_va = TEMPLATE - 1;
|
||||
assert!(setup_tls(&inverted, IMAGE, IMAGE, &mut memory, THREAD_TLS).is_err());
|
||||
assert_eq!(
|
||||
memory.read_u64(THREAD_TLS),
|
||||
Err(MemoryError::UnmappedAddress(THREAD_TLS))
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Multiword ADC and SBB carry chains through the interpreter and the native
|
||||
//! DBT.
|
||||
//!
|
||||
//! Encodings were assembled with LLVM (`llvm-mc -triple=x86_64`, Intel syntax).
|
||||
//! Expected values come from widening `u128` and `i128` arithmetic over the
|
||||
//! limbs, following the ADC and SBB operation sections of the Intel SDM Vol. 2:
|
||||
//! DEST = DEST + SRC + CF and DEST = DEST - (SRC + CF). They never read the
|
||||
//! production semantics. Both engines must also agree on the complete state,
|
||||
//! including PF and AF, which the reference does not model.
|
||||
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter};
|
||||
use xenora_loader::dbt::{DbtEngine, is_native};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::x86_decode::decode;
|
||||
use xenora_loader::x86_table::Op;
|
||||
|
||||
const ENTRY: u64 = 0x1000;
|
||||
/// `jmp +0`: ends the translated block, so the next instruction reads CF from
|
||||
/// the guest state stored by the previous block.
|
||||
const JMP: [u8; 2] = [0xEB, 0x00];
|
||||
const HLT: u8 = 0xF4;
|
||||
|
||||
/// Limb registers: A in RAX, RBX, RCX, RDX and B in R8 to R11.
|
||||
const A: [usize; 4] = [0, 3, 1, 2];
|
||||
const B: [usize; 4] = [8, 9, 10, 11];
|
||||
|
||||
// add rax, r8; adc rbx, r9; adc rcx, r10; adc rdx, r11 (and the SUB/SBB and
|
||||
// 32-bit equivalents).
|
||||
const ADD64: [&[u8]; 4] = [
|
||||
&[0x4C, 0x01, 0xC0],
|
||||
&[0x4C, 0x11, 0xCB],
|
||||
&[0x4C, 0x11, 0xD1],
|
||||
&[0x4C, 0x11, 0xDA],
|
||||
];
|
||||
const SUB64: [&[u8]; 4] = [
|
||||
&[0x4C, 0x29, 0xC0],
|
||||
&[0x4C, 0x19, 0xCB],
|
||||
&[0x4C, 0x19, 0xD1],
|
||||
&[0x4C, 0x19, 0xDA],
|
||||
];
|
||||
const ADD32: [&[u8]; 4] = [
|
||||
&[0x44, 0x01, 0xC0],
|
||||
&[0x44, 0x11, 0xCB],
|
||||
&[0x44, 0x11, 0xD1],
|
||||
&[0x44, 0x11, 0xDA],
|
||||
];
|
||||
const SUB32: [&[u8]; 4] = [
|
||||
&[0x44, 0x29, 0xC0],
|
||||
&[0x44, 0x19, 0xCB],
|
||||
&[0x44, 0x19, 0xD1],
|
||||
&[0x44, 0x19, 0xDA],
|
||||
];
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum Chain {
|
||||
Add,
|
||||
Sub,
|
||||
}
|
||||
|
||||
/// Expected limbs and CF, ZF, SF, OF of the last limb.
|
||||
#[derive(PartialEq, Eq, Debug)]
|
||||
struct Expected {
|
||||
limbs: [u64; 4],
|
||||
cf: bool,
|
||||
zf: bool,
|
||||
sf: bool,
|
||||
of: bool,
|
||||
}
|
||||
|
||||
fn reference(chain: Chain, bits: u32, a: [u64; 4], b: [u64; 4]) -> Expected {
|
||||
let mask = if bits == 64 {
|
||||
u64::MAX
|
||||
} else {
|
||||
(1u64 << bits) - 1
|
||||
};
|
||||
let modulus = 1u128 << bits;
|
||||
let signed = |value: u64| -> i128 {
|
||||
let value = i128::from(value & mask);
|
||||
if value >= (1i128 << (bits - 1)) {
|
||||
value - (1i128 << bits)
|
||||
} else {
|
||||
value
|
||||
}
|
||||
};
|
||||
let mut limbs = [0; 4];
|
||||
let mut carry = 0u128;
|
||||
let mut of = false;
|
||||
for i in 0..4 {
|
||||
let (x, y) = (u128::from(a[i] & mask), u128::from(b[i] & mask));
|
||||
let wide = match chain {
|
||||
Chain::Add => x + y + carry,
|
||||
Chain::Sub => x + modulus - y - carry,
|
||||
};
|
||||
limbs[i] = (wide % modulus) as u64;
|
||||
let exact = match chain {
|
||||
Chain::Add => signed(a[i]) + signed(b[i]) + carry as i128,
|
||||
Chain::Sub => signed(a[i]) - signed(b[i]) - carry as i128,
|
||||
};
|
||||
of = exact != signed(limbs[i]);
|
||||
carry = match chain {
|
||||
Chain::Add => u128::from(wide >= modulus),
|
||||
Chain::Sub => u128::from(y + carry > x),
|
||||
};
|
||||
}
|
||||
Expected {
|
||||
limbs,
|
||||
cf: carry != 0,
|
||||
zf: limbs[3] == 0,
|
||||
sf: limbs[3] >> (bits - 1) & 1 != 0,
|
||||
of,
|
||||
}
|
||||
}
|
||||
|
||||
fn program(parts: &[&[u8]], split: bool) -> Vec<u8> {
|
||||
let mut code = Vec::new();
|
||||
for (i, part) in parts.iter().enumerate() {
|
||||
if split && i > 0 {
|
||||
code.extend_from_slice(&JMP);
|
||||
}
|
||||
code.extend_from_slice(part);
|
||||
}
|
||||
code.push(HLT);
|
||||
code
|
||||
}
|
||||
|
||||
fn load(code: &[u8], gpr: [u64; 16], cf: bool) -> (CpuState, GuestMemory) {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
|
||||
.unwrap();
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr = gpr;
|
||||
cpu.flags.cf = cf;
|
||||
(cpu, memory)
|
||||
}
|
||||
|
||||
/// Run `code` to its HLT in both engines, check they agree on the whole state
|
||||
/// and that the DBT never left native code, and return the final state.
|
||||
fn run_both(code: &[u8], gpr: [u64; 16], cf: bool, context: &str) -> CpuState {
|
||||
let (cpu, mut memory) = load(code, gpr, cf);
|
||||
let interpreted = Interpreter::new(cpu, &mut memory, 64).run();
|
||||
let (mut cpu, mut memory) = load(code, gpr, cf);
|
||||
let mut engine = DbtEngine::new(16 * 1024).unwrap();
|
||||
let translated = engine.run(&mut cpu, &mut memory, 64);
|
||||
assert_eq!(interpreted.exit_reason, ExitReason::Halt, "{context}");
|
||||
assert_eq!(translated.exit_reason, ExitReason::Halt, "{context}");
|
||||
assert_eq!(translated.final_state, interpreted.final_state, "{context}");
|
||||
assert_eq!(engine.metrics.interpreter_fallbacks, 0, "{context}");
|
||||
interpreted.final_state
|
||||
}
|
||||
|
||||
struct Random(u64);
|
||||
|
||||
impl Random {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 >> 12;
|
||||
self.0 ^= self.0 << 25;
|
||||
self.0 ^= self.0 >> 27;
|
||||
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
|
||||
}
|
||||
}
|
||||
|
||||
/// Limb values at the carry and overflow boundaries of a `bits`-wide limb.
|
||||
fn edges(bits: u32) -> [u64; 6] {
|
||||
let max = if bits == 64 {
|
||||
u64::MAX
|
||||
} else {
|
||||
(1u64 << bits) - 1
|
||||
};
|
||||
let sign = 1u64 << (bits - 1);
|
||||
[0, 1, max - 1, max, sign, sign - 1]
|
||||
}
|
||||
|
||||
fn operand_sets(bits: u32) -> Vec<([u64; 4], [u64; 4])> {
|
||||
let edges = edges(bits);
|
||||
let mut sets = Vec::new();
|
||||
for &x in &edges {
|
||||
for &y in &edges {
|
||||
sets.push(([x; 4], [y; 4]));
|
||||
sets.push(([x, y, x, y], [y, x, y, x]));
|
||||
}
|
||||
}
|
||||
let mut random = Random(0x0195_ADC5_BB00_0001);
|
||||
for _ in 0..256 {
|
||||
let mut pick = || {
|
||||
let raw = random.next();
|
||||
if raw & 3 == 0 {
|
||||
edges[(raw >> 8) as usize % edges.len()] | raw & !edges[3]
|
||||
} else {
|
||||
raw
|
||||
}
|
||||
};
|
||||
let a = [pick(), pick(), pick(), pick()];
|
||||
let b = [pick(), pick(), pick(), pick()];
|
||||
sets.push((a, b));
|
||||
}
|
||||
sets
|
||||
}
|
||||
|
||||
fn check_chain(chain: Chain, bits: u32, parts: [&[u8]; 4]) {
|
||||
for part in &parts[1..] {
|
||||
let insn = decode(ENTRY, |address| {
|
||||
part.get((address - ENTRY) as usize).copied().ok_or(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(matches!(insn.op, Op::Adc | Op::Sbb));
|
||||
assert!(is_native(&insn), "{:?}", insn.op);
|
||||
}
|
||||
let mut random = Random(u64::from(bits) << 8 | chain as u64);
|
||||
for (a, b) in operand_sets(bits) {
|
||||
let expected = reference(chain, bits, a, b);
|
||||
for split in [false, true] {
|
||||
let code = program(&parts, split);
|
||||
let mut gpr: [u64; 16] = std::array::from_fn(|_| random.next());
|
||||
for i in 0..4 {
|
||||
gpr[A[i]] = a[i];
|
||||
gpr[B[i]] = b[i];
|
||||
}
|
||||
// The leading ADD or SUB must ignore the incoming carry.
|
||||
for cf in [false, true] {
|
||||
let context = format!("{chain:?}{bits} split={split} cf={cf} a={a:x?} b={b:x?}");
|
||||
let state = run_both(&code, gpr, cf, &context);
|
||||
let limbs = A.map(|index| state.gpr[index]);
|
||||
// A 32-bit destination clears bits 63:32.
|
||||
assert_eq!(limbs, expected.limbs, "{context}");
|
||||
assert_eq!(B.map(|index| state.gpr[index]), b, "{context}");
|
||||
let flags = (
|
||||
state.flags.cf,
|
||||
state.flags.zf,
|
||||
state.flags.sf,
|
||||
state.flags.of,
|
||||
);
|
||||
let wanted = (expected.cf, expected.zf, expected.sf, expected.of);
|
||||
assert_eq!(flags, wanted, "{context}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_matches_native_wide_arithmetic() {
|
||||
// 128-bit sanity checks of the reference itself on the low two limbs.
|
||||
let cases = [
|
||||
(u128::MAX, 1u128),
|
||||
(0, 1),
|
||||
(1u128 << 64, 1),
|
||||
(0x8000_0000_0000_0000_0000_0000_0000_0000, 1),
|
||||
];
|
||||
for (x, y) in cases {
|
||||
let a = [x as u64, (x >> 64) as u64, 0, 0];
|
||||
let b = [y as u64, (y >> 64) as u64, 0, 0];
|
||||
let sum = reference(Chain::Add, 64, a, b);
|
||||
let expected = x.wrapping_add(y);
|
||||
assert_eq!(sum.limbs[0], expected as u64);
|
||||
assert_eq!(sum.limbs[1], (expected >> 64) as u64);
|
||||
let difference = reference(Chain::Sub, 64, a, b);
|
||||
let expected = x.wrapping_sub(y);
|
||||
assert_eq!(difference.limbs[0], expected as u64);
|
||||
assert_eq!(difference.limbs[1], (expected >> 64) as u64);
|
||||
// The upper limbs are zero, so the 256-bit borrow is the 128-bit one.
|
||||
assert_eq!(difference.cf, y > x);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_adc_chains_of_64_bit_limbs_carry_across_blocks() {
|
||||
check_chain(Chain::Add, 64, ADD64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sub_sbb_chains_of_64_bit_limbs_borrow_across_blocks() {
|
||||
check_chain(Chain::Sub, 64, SUB64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_adc_chains_of_32_bit_limbs_carry_across_blocks() {
|
||||
check_chain(Chain::Add, 32, ADD32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sub_sbb_chains_of_32_bit_limbs_borrow_across_blocks() {
|
||||
check_chain(Chain::Sub, 32, SUB32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_chains_run_one_block_per_limb() {
|
||||
let code = program(&ADD64, true);
|
||||
let (mut cpu, mut memory) = load(&code, [0; 16], false);
|
||||
let mut engine = DbtEngine::new(16 * 1024).unwrap();
|
||||
let result = engine.run(&mut cpu, &mut memory, 64);
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(engine.metrics.blocks_compiled, 4);
|
||||
assert_eq!(engine.metrics.interpreter_fallbacks, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn immediate_forms_increment_and_decrement_a_128_bit_value() {
|
||||
// add rax, 1; adc rbx, 0 and sub rax, 1; sbb rbx, 0.
|
||||
let increment: [&[u8]; 2] = [&[0x48, 0x83, 0xC0, 0x01], &[0x48, 0x83, 0xD3, 0x00]];
|
||||
let decrement: [&[u8]; 2] = [&[0x48, 0x83, 0xE8, 0x01], &[0x48, 0x83, 0xDB, 0x00]];
|
||||
let values = [
|
||||
0u128,
|
||||
1,
|
||||
u64::MAX as u128,
|
||||
1u128 << 64,
|
||||
u128::MAX,
|
||||
u128::MAX - 1,
|
||||
1u128 << 127,
|
||||
(1u128 << 127) - 1,
|
||||
];
|
||||
for value in values {
|
||||
for split in [false, true] {
|
||||
for (parts, expected, carry, overflow) in [
|
||||
(
|
||||
&increment,
|
||||
value.wrapping_add(1),
|
||||
value == u128::MAX,
|
||||
value == (1u128 << 127) - 1,
|
||||
),
|
||||
(
|
||||
&decrement,
|
||||
value.wrapping_sub(1),
|
||||
value == 0,
|
||||
value == 1u128 << 127,
|
||||
),
|
||||
] {
|
||||
let code = program(parts, split);
|
||||
let mut gpr = [0x5A5A_5A5A_5A5A_5A5A; 16];
|
||||
gpr[0] = value as u64;
|
||||
gpr[3] = (value >> 64) as u64;
|
||||
let context = format!("{value:#x} split={split} {:x?}", parts[0]);
|
||||
let state = run_both(&code, gpr, true, &context);
|
||||
assert_eq!(state.gpr[0], expected as u64, "{context}");
|
||||
assert_eq!(state.gpr[3], (expected >> 64) as u64, "{context}");
|
||||
assert_eq!(state.flags.cf, carry, "{context}");
|
||||
assert_eq!(state.flags.of, overflow, "{context}");
|
||||
assert_eq!(state.flags.zf, (expected >> 64) == 0, "{context}");
|
||||
assert_eq!(state.flags.sf, expected >> 127 != 0, "{context}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sbb_of_a_register_with_itself_materializes_the_carry_mask() {
|
||||
// sbb esi, esi and sbb rsi, rsi give -CF and borrow exactly when CF was
|
||||
// set; adc edi, 0 adds CF to 0x89ABCDEF without a carry out. The 32-bit
|
||||
// forms clear bits 63:32.
|
||||
// (code, destination register, value from CF, CF out from CF in)
|
||||
type Case = (&'static [u8], usize, fn(bool) -> u64, fn(bool) -> bool);
|
||||
let cases: [Case; 3] = [
|
||||
(
|
||||
&[0x19, 0xF6],
|
||||
6,
|
||||
|cf| if cf { 0xFFFF_FFFF } else { 0 },
|
||||
|cf| cf,
|
||||
),
|
||||
(
|
||||
&[0x48, 0x19, 0xF6],
|
||||
6,
|
||||
|cf| if cf { u64::MAX } else { 0 },
|
||||
|cf| cf,
|
||||
),
|
||||
(
|
||||
&[0x83, 0xD7, 0x00],
|
||||
7,
|
||||
|cf| u64::from(cf) + 0x89AB_CDEF,
|
||||
|_| false,
|
||||
),
|
||||
];
|
||||
for (code, register, value, carry) in cases {
|
||||
for cf in [false, true] {
|
||||
let mut gpr = [0x0123_4567_89AB_CDEF; 16];
|
||||
gpr[6] = 0xDEAD_BEEF_0000_0001;
|
||||
let program = [code, &[HLT]].concat();
|
||||
let context = format!("{code:x?} cf={cf}");
|
||||
let state = run_both(&program, gpr, cf, &context);
|
||||
assert_eq!(state.gpr[register], value(cf), "{context}");
|
||||
assert_eq!(state.flags.cf, carry(cf), "{context}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+76
-27
@@ -1,4 +1,4 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
use std::ffi::c_void;
|
||||
use std::fmt;
|
||||
use std::mem::size_of_val;
|
||||
@@ -37,6 +37,16 @@ const MAX_GROUPS: usize = 64;
|
||||
const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP;
|
||||
const MAX_SOURCE_BYTES: usize = 64 * 1024;
|
||||
const MAX_IN_FLIGHT: usize = 16;
|
||||
const MAX_CACHED_PIPELINES: usize = 16;
|
||||
|
||||
type ComputePipeline = Retained<ProtocolObject<dyn MTLComputePipelineState>>;
|
||||
|
||||
struct CachedPipeline {
|
||||
source: Box<str>,
|
||||
entry: Box<str>,
|
||||
shader_validation: bool,
|
||||
pipeline: ComputePipeline,
|
||||
}
|
||||
|
||||
const BC_READBACK: &str = r"
|
||||
#include <metal_stdlib>
|
||||
@@ -148,7 +158,9 @@ impl std::error::Error for MetalError {}
|
||||
/// measure a single submission and are not a benchmark distribution.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RunProfile {
|
||||
/// Host library compilation time, or zero when reusing a compute pipeline.
|
||||
pub library_seconds: f64,
|
||||
/// Host pipeline creation time, or zero when reusing a compute pipeline.
|
||||
pub pipeline_seconds: f64,
|
||||
pub gpu_seconds: f64,
|
||||
/// Host wall time from the start of setup until wait observes completion.
|
||||
@@ -171,6 +183,8 @@ pub struct NativeCompute {
|
||||
device: Retained<ProtocolObject<dyn MTLDevice>>,
|
||||
queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,
|
||||
submissions: Mutex<SubmissionTable>,
|
||||
// Least recently used first. In-flight submissions retain their own reference.
|
||||
compute_pipelines: Mutex<VecDeque<CachedPipeline>>,
|
||||
}
|
||||
|
||||
/// A submitted dispatch whose result can be collected by its issuing context.
|
||||
@@ -247,7 +261,7 @@ struct SubmissionEntry {
|
||||
/// Metal reports Completed or Error.
|
||||
struct InFlightResources {
|
||||
command: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
|
||||
_pipeline: Retained<ProtocolObject<dyn MTLComputePipelineState>>,
|
||||
_pipeline: ComputePipeline,
|
||||
_input: Option<Retained<ProtocolObject<dyn MTLBuffer>>>,
|
||||
output: Retained<ProtocolObject<dyn MTLBuffer>>,
|
||||
_texture: Option<Retained<ProtocolObject<dyn MTLTexture>>>,
|
||||
@@ -348,6 +362,7 @@ impl NativeCompute {
|
||||
device,
|
||||
queue,
|
||||
submissions: Mutex::default(),
|
||||
compute_pipelines: Mutex::default(),
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -901,7 +916,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
self.run_profiled_words(source, entry, input, Some(width))
|
||||
}
|
||||
|
||||
/// Compile the kernel and report the smaller of the device and pipeline width limits.
|
||||
/// Find or compile the kernel and report the smaller of the device and pipeline width limits.
|
||||
///
|
||||
/// Input size and threadgroup count are checked separately at dispatch.
|
||||
///
|
||||
@@ -911,11 +926,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
pub fn max_group_width(&self, source: &str, entry: &str) -> Result<usize, MetalError> {
|
||||
validate_source(source, &[entry])?;
|
||||
autoreleasepool(|_| {
|
||||
let options = compile_options()?;
|
||||
let library = self.compile_library(source, &options)?;
|
||||
let function = find_function(&library, entry)?;
|
||||
let pipeline = self.compute_pipeline(&function)?;
|
||||
verify_shader_validation(&pipeline)?;
|
||||
let (pipeline, _, _) = self.prepare_compute_pipeline(source, entry)?;
|
||||
Ok(self.pipeline_group_width_limit(&pipeline))
|
||||
})
|
||||
}
|
||||
@@ -963,15 +974,8 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
host_start: Instant,
|
||||
) -> Result<Submission<'_>, MetalError> {
|
||||
self.submissions().check_capacity()?;
|
||||
let options = compile_options()?;
|
||||
let library_start = Instant::now();
|
||||
let library = self.compile_library(source, &options)?;
|
||||
let library_seconds = library_start.elapsed().as_secs_f64();
|
||||
let function = find_function(&library, entry)?;
|
||||
let pipeline_start = Instant::now();
|
||||
let pipeline = self.compute_pipeline(&function)?;
|
||||
let pipeline_seconds = pipeline_start.elapsed().as_secs_f64();
|
||||
verify_shader_validation(&pipeline)?;
|
||||
let (pipeline, library_seconds, pipeline_seconds) =
|
||||
self.prepare_compute_pipeline(source, entry)?;
|
||||
|
||||
let limit = self.pipeline_group_width_limit(&pipeline);
|
||||
let width = match group_width {
|
||||
@@ -1108,18 +1112,67 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
})
|
||||
}
|
||||
|
||||
fn compute_pipeline(
|
||||
fn prepare_compute_pipeline(
|
||||
&self,
|
||||
function: &ProtocolObject<dyn MTLFunction>,
|
||||
) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, MetalError> {
|
||||
self.device
|
||||
.newComputePipelineStateWithFunction_error(function)
|
||||
source: &str,
|
||||
entry: &str,
|
||||
) -> Result<(ComputePipeline, f64, f64), MetalError> {
|
||||
let shader_validation = std::env::var("MTL_SHADER_VALIDATION").as_deref() == Ok("1");
|
||||
// Device identity is fixed by this context. All misses use the same
|
||||
// compile options (safe math, precise functions, default language,
|
||||
// no macros) and unspecialized functions. Any configurable options
|
||||
// must become part of the key before they are used here.
|
||||
let mut cache = self
|
||||
.compute_pipelines
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(index) = cache.iter().position(|cached| {
|
||||
cached.source.as_ref() == source
|
||||
&& cached.entry.as_ref() == entry
|
||||
&& cached.shader_validation == shader_validation
|
||||
}) {
|
||||
let cached = cache.remove(index).expect("position in the locked cache");
|
||||
let pipeline = cached.pipeline.clone();
|
||||
cache.push_back(cached);
|
||||
return Ok((pipeline, 0.0, 0.0));
|
||||
}
|
||||
|
||||
// Serialize cache misses in this context so concurrent requests for
|
||||
// one key share the same build. The submission table is unlocked here.
|
||||
let options = compile_options()?;
|
||||
let library_start = Instant::now();
|
||||
let library = self.compile_library(source, &options)?;
|
||||
let library_seconds = library_start.elapsed().as_secs_f64();
|
||||
let function = find_function(&library, entry)?;
|
||||
let pipeline_start = Instant::now();
|
||||
let pipeline = self
|
||||
.device
|
||||
.newComputePipelineStateWithFunction_error(&function)
|
||||
.map_err(|error| {
|
||||
MetalError::new(
|
||||
"newComputePipelineStateWithFunction",
|
||||
error.localizedDescription().to_string(),
|
||||
)
|
||||
})
|
||||
})?;
|
||||
let pipeline_seconds = pipeline_start.elapsed().as_secs_f64();
|
||||
if shader_validation {
|
||||
verify_shader_validation(&pipeline)?;
|
||||
}
|
||||
|
||||
// Bound owned key text to 1 MiB. A valid oversized key can run
|
||||
// uncached, so this budget does not alter source or entry validation.
|
||||
if entry.len() <= MAX_SOURCE_BYTES.saturating_sub(source.len()) {
|
||||
if cache.len() == MAX_CACHED_PIPELINES {
|
||||
cache.pop_front();
|
||||
}
|
||||
cache.push_back(CachedPipeline {
|
||||
source: source.into(),
|
||||
entry: entry.into(),
|
||||
shader_validation,
|
||||
pipeline: pipeline.clone(),
|
||||
});
|
||||
}
|
||||
Ok((pipeline, library_seconds, pipeline_seconds))
|
||||
}
|
||||
|
||||
fn pipeline_group_width_limit(
|
||||
@@ -1232,10 +1285,6 @@ fn check_command_status(
|
||||
fn verify_shader_validation(
|
||||
pipeline: &ProtocolObject<dyn MTLComputePipelineState>,
|
||||
) -> Result<(), MetalError> {
|
||||
if std::env::var("MTL_SHADER_VALIDATION").as_deref() != Ok("1") {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if !pipeline.respondsToSelector(sel!(shaderValidation)) {
|
||||
return Err(MetalError::new(
|
||||
"shaderValidation",
|
||||
|
||||
@@ -356,6 +356,131 @@ fn multiple_submissions() {
|
||||
assert_eq!(second, [5, 5, 1, 5]);
|
||||
}
|
||||
|
||||
fn pipeline_was_reused(profile: &xenora_metal::RunProfile) -> bool {
|
||||
profile.library_seconds == 0.0 && profile.pipeline_seconds == 0.0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_pipeline_cache_distinguishes_source_entry_and_context() {
|
||||
let context = context();
|
||||
let source = fixture("output[id] = input[id] + 1u;");
|
||||
let second_entry =
|
||||
fixture("output[id] = input[id] * 2u;").replace("void fixture(", "void other(");
|
||||
let source = format!("{source}\n{second_entry}");
|
||||
let changed = source.replace("input[id] + 1u", "input[id] - 1u");
|
||||
let input = [0, 11, u32::MAX];
|
||||
|
||||
for (msl, entry, expected) in [
|
||||
(source.as_str(), "fixture", [1, 12, 0]),
|
||||
(source.as_str(), "other", [0, 22, u32::MAX - 1]),
|
||||
(changed.as_str(), "fixture", [u32::MAX, 10, u32::MAX - 1]),
|
||||
] {
|
||||
let cold = native(context.run_words_profiled(msl, entry, &input));
|
||||
let warm = native(context.run_words_profiled(msl, entry, &input));
|
||||
assert!(!pipeline_was_reused(&cold), "{entry}");
|
||||
assert!(pipeline_was_reused(&warm), "{entry}");
|
||||
assert_eq!(cold.output, expected, "{entry}");
|
||||
assert_eq!(warm.output, expected, "{entry}");
|
||||
}
|
||||
let separate = native(NativeCompute::new());
|
||||
let fresh = native(separate.run_words_profiled(&source, "fixture", &input));
|
||||
assert!(!pipeline_was_reused(&fresh));
|
||||
assert_eq!(fresh.output, [1, 12, 0]);
|
||||
|
||||
for _ in 0..2 {
|
||||
for (msl, entry, operation) in [
|
||||
(source.as_str(), "missing", "newFunctionWithName"),
|
||||
("not valid MSL", "fixture", "newLibraryWithSource"),
|
||||
] {
|
||||
let error = context
|
||||
.run_words_profiled(msl, entry, &input)
|
||||
.expect_err("invalid pipeline must still fail after warming the cache");
|
||||
assert_eq!(error.operation, operation);
|
||||
}
|
||||
}
|
||||
let error = context
|
||||
.run_words_with_group_width(&source, "fixture", &input, 0)
|
||||
.expect_err("cached pipeline must still check dispatch width");
|
||||
assert_eq!(error.operation, "threadgroup width");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_pipeline_cache_bounds_key_bytes_without_rejecting_maximum_source() {
|
||||
const SOURCE_LIMIT: usize = 64 * 1024;
|
||||
let context = context();
|
||||
let mut source = fixture("output[id] = input[id] ^ 1u;");
|
||||
source.push_str("\n// ");
|
||||
source.push_str(&" ".repeat(SOURCE_LIMIT - source.len()));
|
||||
|
||||
for _ in 0..2 {
|
||||
let profile = native(context.run_words_profiled(&source, "fixture", &[8]));
|
||||
assert_eq!(profile.output, [9]);
|
||||
assert!(!pipeline_was_reused(&profile));
|
||||
}
|
||||
source.push(' ');
|
||||
let error = context
|
||||
.run_words_profiled(&source, "fixture", &[8])
|
||||
.expect_err("source above 64 KiB must fail before pipeline lookup");
|
||||
assert_eq!(error.operation, "source bounds");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_pipeline_cache_evicts_oldest_unused_key_and_keeps_pending_work_alive() {
|
||||
let context = context();
|
||||
// Seventeen entries in one source fit in Metal's input limit and exceed
|
||||
// Xenora's 16-pipeline cache. Each kernel writes a distinct result.
|
||||
let source: String = (0..=16)
|
||||
.map(|id| {
|
||||
fixture(&format!("output[id] = input[id] + {id}u;"))
|
||||
.replace("void fixture(", &format!("void entry{id}("))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
native(context.max_group_width(&source, "entry0"));
|
||||
let (pending, gate) = native(context.submit_words_gated(&source, "entry1", &[7]));
|
||||
for id in 2..16 {
|
||||
native(context.max_group_width(&source, &format!("entry{id}")));
|
||||
}
|
||||
native(context.max_group_width(&source, "entry0"));
|
||||
native(context.max_group_width(&source, "entry16"));
|
||||
gate.open();
|
||||
let finished = native(context.wait(pending));
|
||||
assert_eq!(finished.output, [8]);
|
||||
|
||||
let recent = native(context.run_words_profiled(&source, "entry0", &[29]));
|
||||
assert!(pipeline_was_reused(&recent));
|
||||
assert_eq!(recent.output, [29]);
|
||||
let rebuilt = native(context.run_words_profiled(&source, "entry1", &[17]));
|
||||
assert!(!pipeline_was_reused(&rebuilt));
|
||||
assert_eq!(rebuilt.output, [18]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simultaneous_compute_submissions_share_one_pipeline_build() {
|
||||
let context = context();
|
||||
let source = fixture("output[id] = input[id] ^ 5u;");
|
||||
let start = std::sync::Barrier::new(4);
|
||||
std::thread::scope(|scope| {
|
||||
let workers: Vec<_> = (0..4)
|
||||
.map(|input| {
|
||||
let (context, source, start) = (&context, &source, &start);
|
||||
scope.spawn(move || {
|
||||
start.wait();
|
||||
let token = native(context.submit_words(source, "fixture", &[input]));
|
||||
let result = native(context.wait(token));
|
||||
assert_eq!(result.output, [input ^ 5]);
|
||||
usize::from(!pipeline_was_reused(&result))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let builds: usize = workers
|
||||
.into_iter()
|
||||
.map(|worker| worker.join().unwrap())
|
||||
.sum();
|
||||
assert_eq!(builds, 1);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_propagate() {
|
||||
let context = context();
|
||||
@@ -413,3 +538,52 @@ kernel void fixture(device const uint *input [[buffer(0)]],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual GPU timing run"]
|
||||
fn compute_pipeline_reuse_benchmark() {
|
||||
const WARMUPS: usize = 10;
|
||||
const SAMPLES: usize = 101;
|
||||
let warm_context = context();
|
||||
let device = warm_context.device_name();
|
||||
let source = fixture("output[id] = input[id] * 7u + 3u;");
|
||||
let input = mixing_input(131);
|
||||
let expected: Vec<_> = input
|
||||
.iter()
|
||||
.map(|word| word.wrapping_mul(7).wrapping_add(3))
|
||||
.collect();
|
||||
let mut timings = [[[0.0; SAMPLES]; 4]; 2];
|
||||
|
||||
for round in 0..WARMUPS + SAMPLES {
|
||||
let cold_context = context();
|
||||
// Alternate order so neither measurement always follows the other.
|
||||
let contexts = [&cold_context, &warm_context];
|
||||
for index in [round % 2, (round + 1) % 2] {
|
||||
let profile = native(contexts[index].run_words_profiled(&source, "fixture", &input));
|
||||
assert_eq!(profile.output, expected, "context={index} round={round}");
|
||||
if round >= WARMUPS {
|
||||
for (samples, seconds) in timings[index].iter_mut().zip([
|
||||
profile.library_seconds,
|
||||
profile.pipeline_seconds,
|
||||
profile.host_seconds,
|
||||
profile.gpu_seconds,
|
||||
]) {
|
||||
samples[round - WARMUPS] = seconds;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (label, [mut library, mut pipeline, mut host, mut gpu]) in
|
||||
["fresh context", "repeated context"]
|
||||
.into_iter()
|
||||
.zip(timings)
|
||||
{
|
||||
println!(
|
||||
"device={device} {label} samples={SAMPLES} library_us[{}] pipeline_us[{}] host_us[{}] gpu_us[{}]",
|
||||
timing_summary(&mut library),
|
||||
timing_summary(&mut pipeline),
|
||||
timing_summary(&mut host),
|
||||
timing_summary(&mut gpu),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,7 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
|
||||
- [Testing and acceptance index](testing/README.md) — Entry point for test procedures, evidence and review records.
|
||||
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](testing/shader-form-acceptance.md) — Independence, command, log and promotion rules for fixture-verified instruction forms.
|
||||
- [Engineering progress](progress.md) — Verification commands, metric definitions, and open release gates.
|
||||
- [CPU test runtime and shard selection](testing/cpu-coverage.md) — Measured CPU gate cost and deterministic test-target shards.
|
||||
- [Test inventory comparison](testing/test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
|
||||
- [Persistent resource and translated rendering acceptance](testing/x9-acceptance.md) — Pinned upstream tests, native ARM64 results and unsupported cases.
|
||||
- [Baseline acceptance](testing/phase-02-baseline.md), [Phase 01 assurance](testing/phase01-assurance.md), and [independent reviews](testing/review-log.md) — Candidate-specific results and release findings.
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
# CPU test runtime and shard selection
|
||||
|
||||
This page records what the CPU test gate costs and describes
|
||||
`scripts/cpu-tests.sh`, which splits that gate into deterministic shards. The
|
||||
shards are a convenience for local iteration and parallel runners. They do not
|
||||
replace any gate: `cargo test --locked --workspace` stays the full CPU gate, and
|
||||
`scripts/test-gpu.sh` stays the GPU gate.
|
||||
|
||||
## What counts as a CPU test
|
||||
|
||||
A CPU test is any test target that `cargo test --locked --workspace` builds with
|
||||
default features. Targets that need a Metal device are either behind the
|
||||
`gpu-tests` feature (`xenora-metal`, `xenora-loader`, `xenora-ffi`) or marked
|
||||
`#[ignore = "requires a native Metal device ..."]` (for example
|
||||
`tests/validation/known_answers.rs`), so the default run does not execute them.
|
||||
`scripts/test-gpu.sh` runs them. The selection uses Cargo's own target list, so
|
||||
it never decides by file name which tests are CPU tests.
|
||||
|
||||
One exception: two `xenora-ffi` library tests
|
||||
(`test_resource_management_lifecycle_and_validation` and
|
||||
`test_deferred_resource_retirement_waits_for_in_flight`) call
|
||||
`xenora_session_create_texture`. When a Metal device is available, that
|
||||
function creates one and uploads a texture; when none is available, it
|
||||
continues without one. So on a Mac these default tests do touch Metal, and they
|
||||
are not GPU verification. The selection keeps them because the full gate runs
|
||||
them.
|
||||
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
scripts/cpu-tests.sh --list # every default-feature test target, sorted
|
||||
scripts/cpu-tests.sh --shard 2/3 # run shard 2 of 3
|
||||
scripts/cpu-tests.sh --check 3 # show that 3 shards cover every target once
|
||||
```
|
||||
|
||||
Targets are sorted by package, kind and name. Shard K of N takes each target
|
||||
whose zero-based index i satisfies i mod N = K - 1. Shard 1 also runs the
|
||||
workspace doctests. A new target joins a shard without any edit to the script.
|
||||
The script exits 1 when any selected target fails or when Cargo cannot build the
|
||||
workspace. Partial target lists never run. It exits 2 on bad arguments.
|
||||
It uses at most four Cargo build jobs unless `CARGO_BUILD_JOBS` says otherwise.
|
||||
|
||||
## Measurements
|
||||
|
||||
Host: Apple M4 (10 cores), macOS on ARM64, `cargo 1.100.0`, target
|
||||
`aarch64-apple-darwin`, debug test profile, main at `d7f7d58`. All runs used a
|
||||
warm build unless noted. These are single-host samples, not benchmarks.
|
||||
|
||||
Full gate, `cargo test --locked --workspace`, three runs: 40.47 s, 39.99 s and
|
||||
40.12 s wall time. It ran 82 test targets plus doctests (92 `test result` lines):
|
||||
681 passed, 0 failed, 34 ignored.
|
||||
|
||||
Running each target alone through `cargo test -p <package> <selector>` adds up
|
||||
to 79.5 s, because every invocation pays Cargo start-up. The five most expensive
|
||||
targets, one sample each:
|
||||
|
||||
| Target | Wall time | Passed / ignored |
|
||||
| --- | --- | --- |
|
||||
| `xenora-loader --test runtime_services` | 19.13 s | 23 / 0 |
|
||||
| `xenora-loader --test cpu_known_answers` | 8.18 s | 42 / 5 |
|
||||
| `xenora-loader --test probe_delay_imports` | 3.53 s | 8 / 0 |
|
||||
| `xenora-loader --test probe_truncation` | 3.32 s | 1 / 0 |
|
||||
| `xenora-ffi --lib` | 2.16 s | 18 / 0 |
|
||||
|
||||
`runtime_services` alone is about a quarter of the summed cost. Any shard that
|
||||
contains it takes at least about 19 s. The next step for a faster gate is
|
||||
profiling that target, not finer sharding.
|
||||
|
||||
Shard runs, one sample each, sequential on the same host:
|
||||
|
||||
| Selection | Wall time per shard | Passed | Failed | Ignored | Result lines |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 2 shards | 37.98 s, 4.55 s | 360 + 321 = 681 | 0 | 21 + 13 = 34 | 51 + 41 = 92 |
|
||||
| 3 shards | 6.54 s, 29.55 s, 6.27 s | 160 + 282 + 239 = 681 | 0 | 9 + 12 + 13 = 34 | 38 + 27 + 27 = 92 |
|
||||
|
||||
For both shard counts, the union of the shards matches the full gate exactly
|
||||
in passed, failed, ignored and result-line counts. Round-robin by name does
|
||||
not balance cost: with one dominant target, parallel shards finish no sooner
|
||||
than the shard that holds it. Running the shards one after another costs more
|
||||
than the full gate, because each target pays Cargo start-up.
|
||||
|
||||
## Verification of the script
|
||||
|
||||
- `--check N` for N = 1 to 4 reports that all 82 targets are covered once.
|
||||
- `--check 3` fails when the selection expression is changed to skip a
|
||||
residue or to repeat a target.
|
||||
- `--list` exits 1 with an error when a crate fails to compile, instead of
|
||||
printing a shortened list.
|
||||
- Bad arguments (`--shard 0/2`, `--shard 3/2`, `--check x`) exit 2.
|
||||
|
||||
## Limitations
|
||||
|
||||
- Timings come from one machine and few samples. Re-measure before using them
|
||||
for decisions.
|
||||
- Shard membership changes when targets are added or renamed. Shards from two
|
||||
different commits are not comparable.
|
||||
- The experiment workspace `experiments/x1` is outside the selection. CI runs
|
||||
it separately.
|
||||
Executable
+113
@@ -0,0 +1,113 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#
|
||||
# Deterministic CPU-only selection of the workspace test targets (#159).
|
||||
#
|
||||
# scripts/cpu-tests.sh --list print every default-feature test target
|
||||
# scripts/cpu-tests.sh --shard K/N run shard K of N (1 <= K <= N)
|
||||
# scripts/cpu-tests.sh --check N prove N shards cover every target once
|
||||
#
|
||||
# Targets are the ones `cargo test --locked --workspace` builds with default
|
||||
# features, sorted by package, kind and name. Shard K takes every target whose
|
||||
# index i in that order has i mod N == K - 1; shard 1 also runs the doctests.
|
||||
# New targets join a shard automatically. The selection never replaces the full
|
||||
# gate, `cargo test --locked --workspace`; `gpu-tests` targets stay in
|
||||
# scripts/test-gpu.sh.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
export CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-4}
|
||||
|
||||
usage() {
|
||||
echo "usage: $0 --list | --shard K/N | --check N" >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
# Prints "package selector..." for each test target, one per line, sorted.
|
||||
# Fails when Cargo cannot build every target, so a partial list never runs.
|
||||
targets() {
|
||||
json=$(cargo test --locked --workspace --no-run --message-format=json) || {
|
||||
echo "cpu-tests: cargo could not build the workspace test targets" >&2
|
||||
exit 1
|
||||
}
|
||||
printf '%s\n' "$json" | python3 -c '
|
||||
import json, sys
|
||||
rows = set()
|
||||
for line in sys.stdin:
|
||||
m = json.loads(line)
|
||||
if m.get("reason") != "compiler-artifact" or not m.get("executable"):
|
||||
continue
|
||||
if not m["profile"]["test"]:
|
||||
continue
|
||||
pkg = m["package_id"].split("#")[-1].split("@")[0]
|
||||
kind, name = m["target"]["kind"][0], m["target"]["name"]
|
||||
sel = {"test": "--test " + name, "bin": "--bin " + name}.get(kind, "--lib")
|
||||
rows.add(f"{pkg} {sel}")
|
||||
if not rows:
|
||||
sys.exit("cpu-tests: no test targets found; does the workspace build?")
|
||||
print("\n".join(sorted(rows)))
|
||||
'
|
||||
}
|
||||
|
||||
# Keeps the lines of stdin that belong to shard $1 of $2.
|
||||
select_shard() {
|
||||
awk -v k="$1" -v n="$2" '(NR - 1) % n == k - 1'
|
||||
}
|
||||
|
||||
parse_count() {
|
||||
case $1 in '' | *[!0-9]*) usage ;; esac
|
||||
[ "$1" -ge 1 ] || usage
|
||||
}
|
||||
|
||||
[ $# -ge 1 ] || usage
|
||||
case $1 in
|
||||
--list)
|
||||
[ $# -eq 1 ] || usage
|
||||
targets
|
||||
;;
|
||||
--check)
|
||||
[ $# -eq 2 ] || usage
|
||||
parse_count "$2"
|
||||
all=$(targets)
|
||||
total=$(printf '%s\n' "$all" | wc -l | tr -d ' ')
|
||||
union=$(k=1; while [ "$k" -le "$2" ]; do
|
||||
printf '%s\n' "$all" | select_shard "$k" "$2"
|
||||
k=$((k + 1))
|
||||
done)
|
||||
if [ "$(printf '%s\n' "$union" | sort)" != "$(printf '%s\n' "$all" | sort)" ]; then
|
||||
echo "cpu-tests: $2 shards do not cover the $total targets exactly once" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "cpu-tests: $2 shards cover all $total targets exactly once"
|
||||
;;
|
||||
--shard)
|
||||
[ $# -eq 2 ] || usage
|
||||
k=${2%/*}
|
||||
n=${2#*/}
|
||||
[ "$k/$n" = "$2" ] || usage
|
||||
parse_count "$k"
|
||||
parse_count "$n"
|
||||
[ "$k" -le "$n" ] || usage
|
||||
all=$(targets)
|
||||
selected=$(printf '%s\n' "$all" | select_shard "$k" "$n")
|
||||
failed=0
|
||||
# Word splitting of $line is intended: it holds "package --test name".
|
||||
while IFS= read -r line; do
|
||||
[ -n "$line" ] || continue
|
||||
echo "cpu-tests[$k/$n]: cargo test --locked -p $line"
|
||||
# shellcheck disable=SC2086
|
||||
cargo test --locked -p $line || failed=$((failed + 1))
|
||||
done <<EOF
|
||||
$selected
|
||||
EOF
|
||||
if [ "$k" -eq 1 ]; then
|
||||
echo "cpu-tests[$k/$n]: cargo test --locked --workspace --doc"
|
||||
cargo test --locked --workspace --doc || failed=$((failed + 1))
|
||||
fi
|
||||
if [ "$failed" -ne 0 ]; then
|
||||
echo "cpu-tests[$k/$n]: $failed target(s) failed" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "cpu-tests[$k/$n]: all selected targets passed"
|
||||
;;
|
||||
*) usage ;;
|
||||
esac
|
||||
@@ -13,6 +13,43 @@ export CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-4}
|
||||
# allow slower hosts to raise it without editing the script.
|
||||
export XENORA_SEMANTIC_TIMEOUT=${XENORA_SEMANTIC_TIMEOUT:-300s}
|
||||
|
||||
# macOS does not ship GNU timeout. Python 3 is already a project requirement,
|
||||
# so use a small POSIX-compatible fallback rather than making coreutils a
|
||||
# prerequisite for the native suite.
|
||||
if ! command -v timeout >/dev/null 2>&1; then
|
||||
timeout() {
|
||||
duration=$1
|
||||
shift
|
||||
python3 - "$duration" "$@" <<'PY'
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
text = sys.argv[1]
|
||||
match = re.fullmatch(r"(\d+(?:\.\d+)?)([smh]?)", text)
|
||||
if match is None:
|
||||
print(f"timeout: invalid duration {text!r}", file=sys.stderr)
|
||||
raise SystemExit(2)
|
||||
seconds = float(match.group(1)) * {"": 1, "s": 1, "m": 60, "h": 3600}[match.group(2)]
|
||||
try:
|
||||
process = subprocess.Popen(sys.argv[2:], start_new_session=True)
|
||||
except FileNotFoundError as error:
|
||||
print(f"timeout: {error}", file=sys.stderr)
|
||||
raise SystemExit(127)
|
||||
try:
|
||||
code = process.wait(timeout=seconds)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.wait()
|
||||
print(f"timeout: command exceeded {seconds:g} seconds", file=sys.stderr)
|
||||
raise SystemExit(124)
|
||||
raise SystemExit(code)
|
||||
PY
|
||||
}
|
||||
fi
|
||||
|
||||
cargo test --locked -p xenora-metal --features gpu-tests --test native_compute --no-run
|
||||
timeout 30s cargo test --locked -p xenora-metal --features gpu-tests --test native_compute -- \
|
||||
--nocapture --test-threads=1
|
||||
|
||||
Reference in new issue
Block a user