mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-28 22:21:11 +00:00
Compare commits
42
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
38359969cd | ||
|
|
3b47c21bb0 | ||
|
|
9a62d86a89 | ||
|
|
4b32c532fe | ||
|
|
bbc84c0da0 | ||
|
|
d2f77cdea3 | ||
|
|
3a36379db4 | ||
|
|
147e2a9f1a | ||
|
|
a7fa8b0d65 | ||
|
|
e6b657a2e9 | ||
|
|
c05e631c6d | ||
|
|
34a583b101 | ||
|
|
061c28b405 | ||
|
|
3b52215a30 | ||
|
|
0214a7bab5 | ||
|
|
47b526fba9 | ||
|
|
c68e3ccb4c | ||
|
|
fb6282ceb2 | ||
|
|
bb6a9f6912 | ||
|
|
a7e3e1e42c | ||
|
|
9c76bf16f0 | ||
|
|
788de1e83b | ||
|
|
b4f45573cf | ||
|
|
0766307acc | ||
|
|
ce8d16e367 | ||
|
|
938cbd3028 | ||
|
|
c9505e53e2 | ||
|
|
1013746e17 | ||
|
|
9ddb708cdf | ||
|
|
94783fa603 | ||
|
|
974d1fc62c | ||
|
|
6f1ac2a906 | ||
|
|
223a754eb7 | ||
|
|
d195978903 | ||
|
|
782c49167c | ||
|
|
6106c37912 | ||
|
|
c1ca4ea140 | ||
|
|
c95e175210 | ||
|
|
509811aad0 | ||
|
|
b9372408c8 | ||
|
|
8b67479526 | ||
|
|
84866956b9 |
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,6 +21,7 @@ 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
|
||||
@@ -26,14 +29,25 @@ remains unsupported.
|
||||
- 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 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.
|
||||
- Added the accumulator short form of XCHG, opcodes 91 to 97 and 90 with REX.B, at 16, 32 and 64 bits (part of #118). Assemblers choose this form whenever one operand is the accumulator, and both engines used to stop on it with an illegal-instruction exit. A 16-bit exchange keeps the upper 48 bits of both registers, a 32-bit one clears both upper halves, and `49 90` exchanges RAX with R8 while plain `90` stays NOP. Both engines run the shared semantics; nothing is lowered to ARM64. Three SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/x86/integer.txt` gains 20 assembled instructions checked by the text-only reference in `x86_integer.rs`. F3 before this form, 16-bit PUSH and POP and LODSW stay rejected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added RCL and RCR, the rotates through the carry flag, for 8-, 16-, 32- and 64-bit register and memory operands with a count of one, CL or an immediate (part of #121). The count is masked to five bits (six for 64-bit operands) and then reduced modulo 9 or 17 for 8- and 16-bit operands; a masked count of zero changes nothing, CF receives the last bit rotated out, and OF is set only for a count of one. Both engines run the shared semantics; nothing is lowered to ARM64. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and its shift sweep now runs both instructions at every width, count and carry against its bit-loop model. `tests/x86/integer.txt` gains 80 assembled RCL and RCR instructions, checked by the single-step reference in `x86_integer.rs`. SHLD and SHRD stay rejected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added four Wave32 gfx1030 VOP2 select and carry forms through the semantic registry. Conditional select, add with carry and both subtract orders with borrow use a per-lane VCC bit and have a guide-derived oracle that passes on both CPU interpreters and on native Metal (local Apple M5, API and shader validation); independent acceptance is pending. Part of #215.
|
||||
- Added decoding and Metal shader translation for twelve Wave32 VOPC 16-bit integer compares (#215). The signed and unsigned forms compare the low 16 bits of each source and write the Wave32 VCC mask. CPU verification covers 1,572 compiler acceptance cases and 408 rejections from the guide-derived oracle, which also passes on native Metal (1,572 cases in 1,420 programs on a local Apple M5 under API and shader validation); acceptance is pending.
|
||||
- Added MOVS and STOS for 8- to 64-bit elements, with and without REP, and the direction flag with CLD and STD (#129). A REP form runs one element per step and stays on the instruction until RCX is zero, so every element counts against the step budget, a repeat can stop part-way and resume, a zero count touches nothing, and a fault keeps the elements already done with RSI, RDI and RCX at the one that faulted. An FS or GS override applies to the MOVS source only. Both engines run these on the shared semantics with no bulk-copy path, so large copies are slow. LODS, CMPS, SCAS, REPE, REPNE and the address-size override stay rejected. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/cpu_rep.rs` adds a byte-array model over every form, direction and count; not compared with x86 hardware and awaiting independent review.
|
||||
- Added a deterministic guest thread scheduler (first part of #323): independent CPU contexts, guarded stacks and TEBs on one host thread, with bounded turns, `CreateThread`, `ExitThread`, `TerminateThread`, `GetExitCodeThread`, `SuspendThread`, `ResumeThread` and `SwitchToThread`. With a scheduler attached, `WaitForSingleObject` and `WaitForMultipleObjects` block only the calling guest thread, with timeouts, on threads, events, semaphores and mutexes; abandoned mutexes, deadlocks and per-thread faults are reported. Guest threads never run concurrently. Critical sections, SRW locks, condition variables and `Sleep` do not block per thread yet. See `docs/runtime/threads.md`.
|
||||
- Added decoding and Metal shader translation for the sixteen Wave32 VOPC 64-bit integer compares (#215). They read VGPR pairs, known even-aligned SGPR pairs or sign-extended inline integers and write the Wave32 VCC mask. The guide-derived oracle passes on native Metal (4,640 cases in 3,818 programs on a local Apple M5 under API and shader validation); acceptance is pending.
|
||||
- Added XADD and CMPXCHG for 8- to 64-bit register and memory destinations, and the LOCK prefix on their memory forms (#198). LOCK anywhere else, CMPXCHG8B and CMPXCHG16B stay rejected. Both engines run the new forms on the shared semantics, one instruction at a time, so a locked instruction is indivisible today and LOCK changes no result; `docs/cpu/instruction-registry.md` states the ordering, alignment, compare-failure and fault rules a guest scheduler must preserve. A failed compare still writes the destination, so it faults on memory that cannot be written. Nothing is lowered to ARM64 atomic instructions, and no multi-thread behaviour is established. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, with 62 LLVM-assembled fixtures and five new tests in `x86_atomic.rs`; not compared with x86 hardware and awaiting independent review.
|
||||
- Added CPUID with a fixed, host-independent guest contract (#130). It reports a synthetic processor with the vendor string `Xenora guest` and sets a feature bit only when every instruction of that feature is implemented: CMOV, POPCNT, LZCNT and long mode today. SSE and SSE2 are not reported while parts of them, such as RSQRTPS and MFENCE, are still rejected, so the table is truthful about Xenora and not a plausible hardware model. Unlisted leaves return zeros. `tests/cpu_features.rs` pins every leaf in both engines, requires each reported feature's instructions among the executed fixtures, and holds a refused witness instruction for 31 unreported features. `docs/cpu/instruction-registry.md` gives the table and the rule for reporting a new feature. Not compared with a processor; awaiting independent review.
|
||||
@@ -199,8 +213,12 @@ remains unsupported.
|
||||
native DBT.
|
||||
|
||||
### Fixed
|
||||
- Fixed `DuplicateHandle` and `GetThreadId` naming the main thread from other guest threads, `OwningThread` in critical sections always holding the main thread's ID, the callback-depth limit being shared by all guest threads, and pending one-time initializations being unbounded.
|
||||
- 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).
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
|
||||
//! Synthetic interpreter and DBT timings.
|
||||
//!
|
||||
//! Set `XENORA_DBT_BENCH_JSON=<path>` to also write the results as one JSON
|
||||
//! document (format version 1). The text output does not change. Values the
|
||||
//! benchmark cannot determine, such as the git revision outside a checkout,
|
||||
//! are written as `null`.
|
||||
//!
|
||||
//! The benchmark target disables Cargo's test harness. To run the percentile
|
||||
//! unit tests, build with
|
||||
//! `cargo rustc --locked -p xenora-loader --bench dbt_bench --message-format=json -- --test`
|
||||
@@ -10,7 +15,7 @@
|
||||
use std::hint::black_box;
|
||||
use std::time::{Duration, Instant};
|
||||
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, Register};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::dbt::{DbtEngine, DbtMetrics};
|
||||
use xenora_loader::memory::MemoryPermissions;
|
||||
use xenora_loader::pe::{
|
||||
IMAGE_FILE_MACHINE_AMD64, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ, PE32_PLUS_MAGIC, ParsedPe,
|
||||
@@ -103,19 +108,215 @@ fn percentile(sorted: &[Duration], fraction: f64) -> Duration {
|
||||
lower + (upper - lower).mul_f64(rank.fract())
|
||||
}
|
||||
|
||||
fn report(label: &str, samples: &mut [Duration]) {
|
||||
/// Order statistics of one timing series, shared by the text and JSON reports.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Summary {
|
||||
samples: usize,
|
||||
median: Duration,
|
||||
min: Duration,
|
||||
max: Duration,
|
||||
p95: Duration,
|
||||
p99: Duration,
|
||||
iqr: Duration,
|
||||
mips: f64,
|
||||
}
|
||||
|
||||
fn summarize(samples: &mut [Duration]) -> Summary {
|
||||
samples.sort_unstable();
|
||||
let median = percentile(samples, 0.50);
|
||||
let p95 = percentile(samples, 0.95);
|
||||
let p99 = percentile(samples, 0.99);
|
||||
let iqr = percentile(samples, 0.75) - percentile(samples, 0.25);
|
||||
let min = samples[0];
|
||||
let max = samples[samples.len() - 1];
|
||||
let mips = INSTRUCTIONS as f64 / median.as_secs_f64() / 1_000_000.0;
|
||||
println!(
|
||||
"{label}: {} samples, median {median:?}, min {min:?}, max {max:?}, p95 {p95:?}, p99 {p99:?}, IQR {iqr:?}, median {mips:.2} MIPS",
|
||||
samples.len()
|
||||
);
|
||||
Summary {
|
||||
samples: samples.len(),
|
||||
median,
|
||||
min: samples[0],
|
||||
max: samples[samples.len() - 1],
|
||||
p95: percentile(samples, 0.95),
|
||||
p99: percentile(samples, 0.99),
|
||||
iqr: percentile(samples, 0.75) - percentile(samples, 0.25),
|
||||
mips: INSTRUCTIONS as f64 / median.as_secs_f64() / 1_000_000.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn report_line(label: &str, s: &Summary) -> String {
|
||||
format!(
|
||||
"{label}: {} samples, median {:?}, min {:?}, max {:?}, p95 {:?}, p99 {:?}, IQR {:?}, median {:.2} MIPS",
|
||||
s.samples, s.median, s.min, s.max, s.p95, s.p99, s.iqr, s.mips
|
||||
)
|
||||
}
|
||||
|
||||
/// Facts about the run that are not timings. `None` means the benchmark could not
|
||||
/// determine the value.
|
||||
struct RunInfo {
|
||||
unix_time: Option<u64>,
|
||||
cpu: Option<String>,
|
||||
os: &'static str,
|
||||
os_version: Option<String>,
|
||||
arch: &'static str,
|
||||
revision: Option<String>,
|
||||
dirty: Option<bool>,
|
||||
debug_assertions: bool,
|
||||
guest_code_bytes: usize,
|
||||
warmup: usize,
|
||||
}
|
||||
|
||||
fn command_output(program: &str, args: &[&str]) -> Option<String> {
|
||||
let output = std::process::Command::new(program)
|
||||
.args(args)
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
Some(String::from_utf8(output.stdout).ok()?.trim().to_owned())
|
||||
}
|
||||
|
||||
fn run_info(guest_code_bytes: usize, warmup: usize) -> RunInfo {
|
||||
let non_empty = |value: Option<String>| value.filter(|v| !v.is_empty());
|
||||
RunInfo {
|
||||
unix_time: std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.ok()
|
||||
.map(|d| d.as_secs()),
|
||||
cpu: non_empty(command_output(
|
||||
"sysctl",
|
||||
&["-n", "machdep.cpu.brand_string"],
|
||||
)),
|
||||
os: std::env::consts::OS,
|
||||
os_version: non_empty(command_output("sw_vers", &["-productVersion"])),
|
||||
arch: std::env::consts::ARCH,
|
||||
revision: non_empty(command_output("git", &["rev-parse", "HEAD"])),
|
||||
dirty: command_output("git", &["status", "--porcelain", "--untracked-files=no"])
|
||||
.map(|status| !status.is_empty()),
|
||||
debug_assertions: cfg!(debug_assertions),
|
||||
guest_code_bytes,
|
||||
warmup,
|
||||
}
|
||||
}
|
||||
|
||||
fn json_string(value: &str) -> String {
|
||||
let mut out = String::with_capacity(value.len() + 2);
|
||||
out.push('"');
|
||||
for c in value.chars() {
|
||||
match c {
|
||||
'"' => out.push_str("\\\""),
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
out
|
||||
}
|
||||
|
||||
fn json_option<T>(value: Option<T>, render: impl FnOnce(T) -> String) -> String {
|
||||
value.map_or_else(|| "null".to_owned(), render)
|
||||
}
|
||||
|
||||
/// JSON has no infinity or NaN, so a non-finite rate (a zero median) is `null`.
|
||||
fn json_f64(value: f64) -> String {
|
||||
if value.is_finite() {
|
||||
format!("{value}")
|
||||
} else {
|
||||
"null".to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
fn json_object(fields: &[(&str, String)]) -> String {
|
||||
let body: Vec<String> = fields
|
||||
.iter()
|
||||
.map(|(key, value)| format!("{}:{value}", json_string(key)))
|
||||
.collect();
|
||||
format!("{{{}}}", body.join(","))
|
||||
}
|
||||
|
||||
fn json_summary(s: &Summary) -> String {
|
||||
json_object(&[
|
||||
("samples", s.samples.to_string()),
|
||||
("median_ns", s.median.as_nanos().to_string()),
|
||||
("min_ns", s.min.as_nanos().to_string()),
|
||||
("max_ns", s.max.as_nanos().to_string()),
|
||||
("p95_ns", s.p95.as_nanos().to_string()),
|
||||
("p99_ns", s.p99.as_nanos().to_string()),
|
||||
("iqr_ns", s.iqr.as_nanos().to_string()),
|
||||
("median_mips", json_f64(s.mips)),
|
||||
])
|
||||
}
|
||||
|
||||
fn json_document(
|
||||
info: &RunInfo,
|
||||
interpreter: &Summary,
|
||||
cold: &Summary,
|
||||
warm: &Summary,
|
||||
metrics: &DbtMetrics,
|
||||
) -> String {
|
||||
let string = |value: &String| json_string(value);
|
||||
json_object(&[
|
||||
("format_version", "1".to_owned()),
|
||||
("benchmark", json_string("dbt_bench")),
|
||||
("unix_time", json_option(info.unix_time, |t| t.to_string())),
|
||||
(
|
||||
"host",
|
||||
json_object(&[
|
||||
("cpu", json_option(info.cpu.as_ref(), string)),
|
||||
("os", json_string(info.os)),
|
||||
("os_version", json_option(info.os_version.as_ref(), string)),
|
||||
("arch", json_string(info.arch)),
|
||||
]),
|
||||
),
|
||||
(
|
||||
"source",
|
||||
json_object(&[
|
||||
("revision", json_option(info.revision.as_ref(), string)),
|
||||
("dirty", json_option(info.dirty, |d| d.to_string())),
|
||||
]),
|
||||
),
|
||||
(
|
||||
"build",
|
||||
json_object(&[("debug_assertions", info.debug_assertions.to_string())]),
|
||||
),
|
||||
(
|
||||
"workload",
|
||||
json_object(&[
|
||||
("name", json_string("add_rax_chain")),
|
||||
("guest_instructions", INSTRUCTIONS.to_string()),
|
||||
("guest_code_bytes", info.guest_code_bytes.to_string()),
|
||||
("instruction_budget", BUDGET.to_string()),
|
||||
("warmup_rounds", info.warmup.to_string()),
|
||||
]),
|
||||
),
|
||||
(
|
||||
"timings",
|
||||
json_object(&[
|
||||
("interpreter", json_summary(interpreter)),
|
||||
("cold_dbt", json_summary(cold)),
|
||||
("warm_dbt", json_summary(warm)),
|
||||
]),
|
||||
),
|
||||
(
|
||||
"cold_dbt_metrics",
|
||||
json_object(&[
|
||||
("blocks_compiled", metrics.blocks_compiled.to_string()),
|
||||
("cache_hits", metrics.cache_hits.to_string()),
|
||||
("cache_misses", metrics.cache_misses.to_string()),
|
||||
(
|
||||
"native_bytes_emitted",
|
||||
metrics.native_bytes_emitted.to_string(),
|
||||
),
|
||||
("dbt_dispatches", metrics.dbt_dispatches.to_string()),
|
||||
(
|
||||
"instructions_executed",
|
||||
metrics.instructions_executed.to_string(),
|
||||
),
|
||||
(
|
||||
"interpreter_fallbacks",
|
||||
metrics.interpreter_fallbacks.to_string(),
|
||||
),
|
||||
("service_calls", metrics.service_calls.to_string()),
|
||||
]),
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@@ -190,14 +391,24 @@ fn main() {
|
||||
"Percentiles describe this synthetic workload on this host; tail estimates vary with sample count."
|
||||
);
|
||||
println!("Even sample counts use the midpoint of the two middle values for the median.");
|
||||
report("Interpreter", &mut interpreter);
|
||||
report("Cold DBT", &mut cold);
|
||||
report("Warm DBT", &mut warm);
|
||||
let interpreter = summarize(&mut interpreter);
|
||||
let cold = summarize(&mut cold);
|
||||
let warm = summarize(&mut warm);
|
||||
println!("{}", report_line("Interpreter", &interpreter));
|
||||
println!("{}", report_line("Cold DBT", &cold));
|
||||
println!("{}", report_line("Warm DBT", &warm));
|
||||
let metrics = cold_metrics.unwrap();
|
||||
println!(
|
||||
"Cold DBT compiled {} blocks and emitted {} native bytes in {} dispatches",
|
||||
metrics.blocks_compiled, metrics.native_bytes_emitted, metrics.dbt_dispatches
|
||||
);
|
||||
|
||||
if let Some(path) = std::env::var_os("XENORA_DBT_BENCH_JSON") {
|
||||
let info = run_info(code.len(), warmup_count);
|
||||
let document = json_document(&info, &interpreter, &cold, &warm, &metrics);
|
||||
std::fs::write(&path, document + "\n").expect("write XENORA_DBT_BENCH_JSON");
|
||||
println!("JSON results written to {}", path.to_string_lossy());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -233,4 +444,140 @@ mod tests {
|
||||
let samples = [10, 20, 100].map(Duration::from_micros);
|
||||
assert_eq!(percentile(&samples, 0.50), Duration::from_micros(20));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_strings_escape_quotes_backslashes_and_controls() {
|
||||
use super::json_string;
|
||||
|
||||
assert_eq!(json_string("plain"), r#""plain""#);
|
||||
assert_eq!(json_string(r#"a"b\c"#), r#""a\"b\\c""#);
|
||||
assert_eq!(json_string("l1\nl2\r\t"), r#""l1\nl2\r\t""#);
|
||||
assert_eq!(json_string("\u{1}\u{1f}"), r#""\u0001\u001f""#);
|
||||
// Non-ASCII text needs no escape in UTF-8 JSON.
|
||||
assert_eq!(json_string("Zażółć"), "\"Zażółć\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_values_and_non_finite_rates_are_null() {
|
||||
use super::{json_f64, json_option};
|
||||
|
||||
assert_eq!(json_option(None::<u64>, |v| v.to_string()), "null");
|
||||
assert_eq!(json_option(Some(7_u64), |v| v.to_string()), "7");
|
||||
assert_eq!(json_f64(f64::INFINITY), "null");
|
||||
assert_eq!(json_f64(f64::NAN), "null");
|
||||
assert_eq!(json_f64(12.5), "12.5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_has_every_field_with_the_summary_values() {
|
||||
fn fixed_summary(median_us: u64) -> super::Summary {
|
||||
use super::Duration;
|
||||
super::Summary {
|
||||
samples: 3,
|
||||
median: Duration::from_micros(median_us),
|
||||
min: Duration::from_micros(10),
|
||||
max: Duration::from_micros(100),
|
||||
p95: Duration::from_nanos(92_000),
|
||||
p99: Duration::from_nanos(98_400),
|
||||
iqr: Duration::from_micros(45),
|
||||
mips: 500.25,
|
||||
}
|
||||
}
|
||||
|
||||
fn fixed_info() -> super::RunInfo {
|
||||
super::RunInfo {
|
||||
unix_time: Some(1_700_000_000),
|
||||
cpu: Some("Test \"CPU\"\\1".to_owned()),
|
||||
os: "macos",
|
||||
os_version: None,
|
||||
arch: "aarch64",
|
||||
revision: Some("0123abcd".to_owned()),
|
||||
dirty: Some(false),
|
||||
debug_assertions: false,
|
||||
guest_code_bytes: 40_011,
|
||||
warmup: 10,
|
||||
}
|
||||
}
|
||||
|
||||
use super::{DbtMetrics, INSTRUCTIONS, json_document};
|
||||
|
||||
let metrics = DbtMetrics {
|
||||
blocks_compiled: 626,
|
||||
cache_hits: 0,
|
||||
cache_misses: 626,
|
||||
native_bytes_emitted: 245_168,
|
||||
dbt_dispatches: 626,
|
||||
instructions_executed: 10_002,
|
||||
interpreter_fallbacks: 1,
|
||||
service_calls: 0,
|
||||
};
|
||||
let document = json_document(
|
||||
&fixed_info(),
|
||||
&fixed_summary(20),
|
||||
&fixed_summary(30),
|
||||
&fixed_summary(40),
|
||||
&metrics,
|
||||
);
|
||||
let summary = |median: &str| {
|
||||
format!(
|
||||
r#"{{"samples":3,"median_ns":{median},"min_ns":10000,"max_ns":100000,"p95_ns":92000,"p99_ns":98400,"iqr_ns":45000,"median_mips":500.25}}"#
|
||||
)
|
||||
};
|
||||
let expected = format!(
|
||||
concat!(
|
||||
r#"{{"format_version":1,"benchmark":"dbt_bench","unix_time":1700000000,"#,
|
||||
r#""host":{{"cpu":"Test \"CPU\"\\1","os":"macos","os_version":null,"arch":"aarch64"}},"#,
|
||||
r#""source":{{"revision":"0123abcd","dirty":false}},"#,
|
||||
r#""build":{{"debug_assertions":false}},"#,
|
||||
r#""workload":{{"name":"add_rax_chain","guest_instructions":{},"guest_code_bytes":40011,"instruction_budget":20000,"warmup_rounds":10}},"#,
|
||||
r#""timings":{{"interpreter":{},"cold_dbt":{},"warm_dbt":{}}},"#,
|
||||
r#""cold_dbt_metrics":{{"blocks_compiled":626,"cache_hits":0,"cache_misses":626,"native_bytes_emitted":245168,"dbt_dispatches":626,"instructions_executed":10002,"interpreter_fallbacks":1,"service_calls":0}}}}"#,
|
||||
),
|
||||
INSTRUCTIONS,
|
||||
summary("20000"),
|
||||
summary("30000"),
|
||||
summary("40000"),
|
||||
);
|
||||
assert_eq!(document, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_report_keeps_its_format() {
|
||||
fn fixed_summary(median_us: u64) -> super::Summary {
|
||||
use super::Duration;
|
||||
super::Summary {
|
||||
samples: 3,
|
||||
median: Duration::from_micros(median_us),
|
||||
min: Duration::from_micros(10),
|
||||
max: Duration::from_micros(100),
|
||||
p95: Duration::from_nanos(92_000),
|
||||
p99: Duration::from_nanos(98_400),
|
||||
iqr: Duration::from_micros(45),
|
||||
mips: 500.25,
|
||||
}
|
||||
}
|
||||
|
||||
use super::report_line;
|
||||
|
||||
assert_eq!(
|
||||
report_line("Cold DBT", &fixed_summary(20)),
|
||||
"Cold DBT: 3 samples, median 20µs, min 10µs, max 100µs, p95 92µs, p99 98.4µs, IQR 45µs, median 500.25 MIPS"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summary_matches_the_percentile_helper() {
|
||||
use super::{Duration, INSTRUCTIONS, summarize};
|
||||
|
||||
let mut samples = [100, 10, 30, 20].map(Duration::from_micros);
|
||||
let s = summarize(&mut samples);
|
||||
assert_eq!(s.samples, 4);
|
||||
assert_eq!(s.median, Duration::from_micros(25));
|
||||
assert_eq!(s.min, Duration::from_micros(10));
|
||||
assert_eq!(s.max, Duration::from_micros(100));
|
||||
assert_eq!(s.p95, Duration::from_nanos(89_500));
|
||||
assert_eq!(s.p99, Duration::from_nanos(97_900));
|
||||
assert_eq!(s.iqr, Duration::from_micros(30));
|
||||
assert_eq!(s.mips, INSTRUCTIONS as f64 / 25e-6 / 1e6);
|
||||
}
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
@@ -173,6 +173,12 @@ pub enum ExitReason {
|
||||
SimdException,
|
||||
/// A host service changed a register the Win64 ABI requires it to preserve.
|
||||
ServiceAbiViolation,
|
||||
/// A service has to wait; it had no effect and runs again later.
|
||||
GuestBlocked,
|
||||
/// A service completed and asked the scheduler for a turn.
|
||||
GuestYield,
|
||||
/// The running guest thread ended itself.
|
||||
GuestThreadExited,
|
||||
}
|
||||
|
||||
impl fmt::Display for ExitReason {
|
||||
@@ -191,6 +197,9 @@ impl fmt::Display for ExitReason {
|
||||
Self::ServiceAbiViolation => {
|
||||
write!(f, "host service changed a nonvolatile guest register")
|
||||
}
|
||||
Self::GuestBlocked => write!(f, "guest thread is waiting"),
|
||||
Self::GuestYield => write!(f, "guest thread gave up its turn"),
|
||||
Self::GuestThreadExited => write!(f, "guest thread exited"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,6 +84,29 @@ impl DbtEngine {
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
max_instructions: usize,
|
||||
) -> ExecutionResult {
|
||||
self.run_bounded(cpu, memory, max_instructions, true)
|
||||
}
|
||||
|
||||
/// As [`Self::run`], but stop at the first block boundary that reaches the
|
||||
/// budget. Repeated slices reuse whole blocks instead of compiling a
|
||||
/// shortened one at every cutoff. The budget may be exceeded by less than
|
||||
/// one block.
|
||||
pub(crate) fn run_slice(
|
||||
&mut self,
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
max_instructions: usize,
|
||||
) -> ExecutionResult {
|
||||
self.run_bounded(cpu, memory, max_instructions, false)
|
||||
}
|
||||
|
||||
fn run_bounded(
|
||||
&mut self,
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
max_instructions: usize,
|
||||
exact: bool,
|
||||
) -> ExecutionResult {
|
||||
let mut instructions_count = 0;
|
||||
|
||||
@@ -119,7 +142,11 @@ impl DbtEngine {
|
||||
}
|
||||
|
||||
// Look up or translate block at cpu.rip
|
||||
let block_limit = (max_instructions - instructions_count).min(MAX_BLOCK_INSTRUCTIONS);
|
||||
let block_limit = if exact {
|
||||
(max_instructions - instructions_count).min(MAX_BLOCK_INSTRUCTIONS)
|
||||
} else {
|
||||
MAX_BLOCK_INSTRUCTIONS
|
||||
};
|
||||
let mut block = self.get_or_compile_block(cpu.rip, memory, block_limit);
|
||||
// A decode failure can belong to a later instruction in the block.
|
||||
// Execute the current instruction alone so earlier effects retire
|
||||
@@ -335,6 +362,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 +617,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 +670,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);
|
||||
}
|
||||
|
||||
@@ -196,8 +196,16 @@ fn trampoline_address(index: usize) -> u64 {
|
||||
}
|
||||
|
||||
const CALLBACK_RETURN: u64 = IMPORT_TRAMPOLINE_BASE_VA - IMPORT_TRAMPOLINE_STRIDE;
|
||||
/// Nested guest callbacks allowed in one guest thread.
|
||||
const MAX_CALLBACK_DEPTH: usize = 32;
|
||||
|
||||
fn callback_depth(memory: &GuestMemory, teb: u64) -> usize {
|
||||
memory
|
||||
.callback_frames
|
||||
.range((teb, 0)..=(teb, u64::MAX))
|
||||
.count()
|
||||
}
|
||||
|
||||
pub(crate) struct GuestCallback {
|
||||
pub(crate) entry: u64,
|
||||
pub(crate) context: u64,
|
||||
@@ -264,6 +272,8 @@ pub(crate) struct CallbackFrame {
|
||||
|
||||
/// Registry for resolving and binding import symbols to guest trampoline VAs.
|
||||
pub struct ImportRegistry {
|
||||
/// Set by the standard services so a call can end the caller's turn.
|
||||
pub(crate) hooks: Option<Arc<crate::services::threads::SchedulerHooks>>,
|
||||
// (lower-case module, name) -> service index. Symbol names keep their case.
|
||||
services: HashMap<(String, ImportName), usize>,
|
||||
handlers: Vec<ServiceDescriptor>,
|
||||
@@ -282,6 +292,7 @@ impl Default for ImportRegistry {
|
||||
impl ImportRegistry {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
hooks: None,
|
||||
services: HashMap::new(),
|
||||
handlers: Vec::new(),
|
||||
callback_dispatchers: HashMap::new(),
|
||||
@@ -609,7 +620,7 @@ impl ImportRegistry {
|
||||
args: [u64; 4],
|
||||
) -> Result<(), ExitReason> {
|
||||
let key = (cpu.gs_base, slot + 8);
|
||||
if memory.callback_frames.len() >= MAX_CALLBACK_DEPTH
|
||||
if callback_depth(memory, cpu.gs_base) >= MAX_CALLBACK_DEPTH
|
||||
|| memory.callback_frames.contains_key(&key)
|
||||
{
|
||||
return Err(ExitReason::ServiceAbiViolation);
|
||||
@@ -725,7 +736,7 @@ impl ImportRegistry {
|
||||
}
|
||||
if let Some(dispatcher) = self.callback_dispatchers.get(&service_idx) {
|
||||
let key = (cpu.gs_base, after);
|
||||
if memory.callback_frames.len() >= MAX_CALLBACK_DEPTH
|
||||
if callback_depth(memory, cpu.gs_base) >= MAX_CALLBACK_DEPTH
|
||||
|| memory.callback_frames.contains_key(&key)
|
||||
{
|
||||
return Err(ExitReason::ServiceAbiViolation);
|
||||
@@ -766,6 +777,9 @@ impl ImportRegistry {
|
||||
cpu.set(Register::Rax, value);
|
||||
cpu.set(Register::Rsp, after);
|
||||
cpu.rip = ret_addr;
|
||||
if self.hooks.as_ref().is_some_and(|h| h.switch_requested()) {
|
||||
return Err(ExitReason::GuestYield);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ pub mod reloc;
|
||||
pub mod runtime;
|
||||
#[rustfmt::skip]
|
||||
pub mod runtime_table;
|
||||
pub mod scheduler;
|
||||
pub mod services;
|
||||
pub mod softfloat;
|
||||
pub mod startup;
|
||||
|
||||
+247
-5
@@ -95,6 +95,8 @@ enum AllocationKind {
|
||||
ImageOrStatic,
|
||||
Virtual,
|
||||
Heap(u64),
|
||||
/// Stack, guard or TEB of a guest thread; only the scheduler frees it.
|
||||
Thread,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -382,6 +384,19 @@ impl GuestMemory {
|
||||
Ok(destination)
|
||||
}
|
||||
|
||||
pub(crate) fn map_thread_region(
|
||||
&mut self,
|
||||
base: u64,
|
||||
size: usize,
|
||||
permissions: MemoryPermissions,
|
||||
) -> Result<u64, MemoryError> {
|
||||
self.map_dynamic_allocation(base, size, permissions, AllocationKind::Thread)
|
||||
}
|
||||
|
||||
pub(crate) fn release_thread_region(&mut self, base: u64) -> bool {
|
||||
self.release_dynamic_allocation(base, AllocationKind::Thread)
|
||||
}
|
||||
|
||||
pub(crate) fn release_virtual_allocation(&mut self, base: u64) -> bool {
|
||||
self.release_dynamic_allocation(base, AllocationKind::Virtual)
|
||||
}
|
||||
@@ -419,6 +434,12 @@ impl GuestMemory {
|
||||
/// byte must be mapped and every region must grant `required` (`None` bypasses
|
||||
/// permission checks for the loader). The whole range is checked before any byte
|
||||
/// is copied, so a failed access never partially reads or writes.
|
||||
///
|
||||
/// A failed access reports the lowest address it may not touch, which is the
|
||||
/// start of the access only when its first byte fails. An access that begins in
|
||||
/// a mapped page and runs into an unmapped or forbidden one therefore reports
|
||||
/// the first byte of that page, as an x86 page fault reports the linear address
|
||||
/// that could not be translated or accessed.
|
||||
fn resolve(
|
||||
&self,
|
||||
address: u64,
|
||||
@@ -452,7 +473,10 @@ impl GuestMemory {
|
||||
Some(_) => region.permissions.execute,
|
||||
};
|
||||
if let (false, Some(required)) = (permitted, required) {
|
||||
return Err(MemoryError::PermissionViolation { address, required });
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address: cursor,
|
||||
required,
|
||||
});
|
||||
}
|
||||
let take = (end.min(region_end) - cursor) as usize;
|
||||
pieces.push((index, (cursor - region.base) as usize, take));
|
||||
@@ -461,7 +485,7 @@ impl GuestMemory {
|
||||
return Ok(pieces);
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
Err(MemoryError::UnmappedAddress(cursor))
|
||||
}
|
||||
|
||||
fn read_checked(
|
||||
@@ -506,9 +530,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.
|
||||
@@ -627,3 +662,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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Deterministic cooperative scheduler for guest threads.
|
||||
//!
|
||||
//! One host thread runs one guest thread at a time, in first-in, first-out
|
||||
//! order, for a bounded number of instructions. The same program, quantum and
|
||||
//! clock always interleave the same way. Guest threads never run concurrently,
|
||||
//! so nothing here relies on a guest memory-ordering model.
|
||||
//!
|
||||
//! A service that has to wait returns [`ExitReason::GuestBlocked`] without any
|
||||
//! effect and with RIP still on its trampoline. The scheduler runs that call
|
||||
//! again when something it may wait for has changed, oldest waiter first.
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason};
|
||||
use crate::dbt::DbtEngine;
|
||||
use crate::memory::GuestMemory;
|
||||
use crate::services::ServicesState;
|
||||
use crate::services::threads::{RunState, THREAD_RETURN};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Default instructions a thread runs before the next one gets a turn.
|
||||
pub const DEFAULT_QUANTUM: usize = 1024;
|
||||
|
||||
/// Why scheduling stopped.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Outcome {
|
||||
/// The main thread executed HLT, the synthetic process exit.
|
||||
Halted,
|
||||
/// Every thread ended.
|
||||
AllThreadsExited,
|
||||
/// No thread can run and no wait has a deadline.
|
||||
Deadlock {
|
||||
blocked: Vec<u32>,
|
||||
suspended: Vec<u32>,
|
||||
},
|
||||
BudgetExhausted,
|
||||
/// A thread stopped for a reason the guest cannot handle.
|
||||
Fault {
|
||||
thread: u32,
|
||||
reason: ExitReason,
|
||||
rip: u64,
|
||||
},
|
||||
}
|
||||
|
||||
/// Result of one scheduled run.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ScheduleReport {
|
||||
pub outcome: Outcome,
|
||||
/// Guest instructions and service calls, including repeated waits.
|
||||
pub instructions: usize,
|
||||
/// Turns given to threads.
|
||||
pub turns: usize,
|
||||
/// Largest number of guest threads alive at once.
|
||||
pub peak_threads: usize,
|
||||
/// Main thread state when it last stopped.
|
||||
pub main: CpuState,
|
||||
}
|
||||
|
||||
pub struct Scheduler {
|
||||
state: Arc<ServicesState>,
|
||||
quantum: usize,
|
||||
}
|
||||
|
||||
enum Turn {
|
||||
Continue,
|
||||
Stop(Outcome),
|
||||
}
|
||||
|
||||
impl Scheduler {
|
||||
/// `quantum` is at least one instruction; a turn ends at the first block
|
||||
/// boundary that reaches it.
|
||||
pub fn new(state: Arc<ServicesState>, quantum: usize) -> Self {
|
||||
Self {
|
||||
state,
|
||||
quantum: quantum.max(1),
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `main` and every thread it creates. Only one scheduler may be
|
||||
/// attached to a service state at a time. Created threads still alive at
|
||||
/// the end are terminated with code 0 and reclaimed, so a run that had any
|
||||
/// cannot be continued.
|
||||
pub fn run(
|
||||
&self,
|
||||
engine: &mut DbtEngine,
|
||||
memory: &mut GuestMemory,
|
||||
main: &CpuState,
|
||||
budget: usize,
|
||||
) -> Result<ScheduleReport, ExitReason> {
|
||||
let main_id = self.state.attach_scheduler(main)?;
|
||||
let mut report = ScheduleReport {
|
||||
outcome: Outcome::BudgetExhausted,
|
||||
instructions: 0,
|
||||
turns: 0,
|
||||
peak_threads: 1,
|
||||
main: main.clone(),
|
||||
};
|
||||
while report.instructions < budget {
|
||||
match self.turn(engine, memory, main_id, budget, &mut report) {
|
||||
Turn::Continue => {}
|
||||
Turn::Stop(outcome) => {
|
||||
report.outcome = outcome;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if report.outcome == Outcome::BudgetExhausted && self.all_ended() {
|
||||
report.outcome = Outcome::AllThreadsExited;
|
||||
}
|
||||
let continues = report.outcome == Outcome::BudgetExhausted;
|
||||
self.state
|
||||
.detach_scheduler(memory, continues.then_some(&report.main));
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
fn turn(
|
||||
&self,
|
||||
engine: &mut DbtEngine,
|
||||
memory: &mut GuestMemory,
|
||||
main_id: u32,
|
||||
budget: usize,
|
||||
report: &mut ScheduleReport,
|
||||
) -> Turn {
|
||||
if let Some(outcome) = self.wake(engine, memory, main_id, budget, report) {
|
||||
return Turn::Stop(outcome);
|
||||
}
|
||||
let Some(id) = self.next_ready() else {
|
||||
// A spent budget may have left waiters untried, and must not sleep.
|
||||
if report.instructions >= budget {
|
||||
return Turn::Continue;
|
||||
}
|
||||
return self.idle();
|
||||
};
|
||||
report.turns += 1;
|
||||
let turn = self.take_credit(id).unwrap_or(self.quantum);
|
||||
let limit = turn.min(budget.saturating_sub(report.instructions));
|
||||
if limit == 0 {
|
||||
self.requeue(id);
|
||||
return Turn::Continue;
|
||||
}
|
||||
let before = report.instructions;
|
||||
let stop = self.run_thread(engine, memory, id, main_id, limit, report);
|
||||
match stop {
|
||||
Stop::Outcome(outcome) => Turn::Stop(outcome),
|
||||
Stop::Ended => Turn::Continue,
|
||||
Stop::Blocked => {
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
table.sequence += 1;
|
||||
let sequence = table.sequence;
|
||||
if let Some(thread) = table.threads.get_mut(&id) {
|
||||
thread.run = RunState::Blocked(sequence);
|
||||
}
|
||||
Turn::Continue
|
||||
}
|
||||
Stop::Preempted { front } => {
|
||||
// Signaling keeps the caller's turn, but never renews it.
|
||||
let left = turn.saturating_sub(report.instructions - before);
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
if let Some(thread) = table.threads.get_mut(&id) {
|
||||
if front && left > 0 {
|
||||
thread.credit = Some(left);
|
||||
table.queue.push_front(id);
|
||||
} else {
|
||||
table.queue.push_back(id);
|
||||
}
|
||||
}
|
||||
Turn::Continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn all_ended(&self) -> bool {
|
||||
let table = self.state.threads.lock().expect("guest thread table");
|
||||
table.threads.is_empty()
|
||||
}
|
||||
|
||||
/// Put back a thread that got no turn.
|
||||
fn requeue(&self, id: u32) {
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
table.queue.push_front(id);
|
||||
}
|
||||
|
||||
fn take_credit(&self, id: u32) -> Option<usize> {
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
table.threads.get_mut(&id)?.credit.take()
|
||||
}
|
||||
|
||||
/// Remove and return the first thread that can run.
|
||||
fn next_ready(&self) -> Option<u32> {
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
let position = table
|
||||
.queue
|
||||
.iter()
|
||||
.position(|id| table.threads.get(id).is_some_and(|t| t.suspend == 0))?;
|
||||
table.queue.remove(position)
|
||||
}
|
||||
|
||||
/// Run the pending call of every blocked thread, oldest first. A thread that
|
||||
/// ends with its call may be what an older one waits for, so that repeats
|
||||
/// the pass.
|
||||
fn wake(
|
||||
&self,
|
||||
engine: &mut DbtEngine,
|
||||
memory: &mut GuestMemory,
|
||||
main_id: u32,
|
||||
budget: usize,
|
||||
report: &mut ScheduleReport,
|
||||
) -> Option<Outcome> {
|
||||
loop {
|
||||
let mut ended = false;
|
||||
for id in self.blocked(report) {
|
||||
if report.instructions >= budget {
|
||||
return None;
|
||||
}
|
||||
match self.run_thread(engine, memory, id, main_id, 1, report) {
|
||||
Stop::Outcome(outcome) => return Some(outcome),
|
||||
Stop::Blocked => {}
|
||||
Stop::Ended => ended = true,
|
||||
Stop::Preempted { .. } => {
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
if let Some(thread) = table.threads.get_mut(&id) {
|
||||
thread.run = RunState::Ready;
|
||||
table.queue.push_back(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !ended {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocked threads that are not suspended, oldest first.
|
||||
fn blocked(&self, report: &mut ScheduleReport) -> Vec<u32> {
|
||||
let table = self.state.threads.lock().expect("guest thread table");
|
||||
report.peak_threads = report.peak_threads.max(table.threads.len());
|
||||
let mut blocked: Vec<(u64, u32)> = table
|
||||
.threads
|
||||
.iter()
|
||||
.filter(|(_, thread)| thread.suspend == 0)
|
||||
.filter_map(|(&id, thread)| match thread.run {
|
||||
RunState::Blocked(sequence) => Some((sequence, id)),
|
||||
RunState::Ready => None,
|
||||
})
|
||||
.collect();
|
||||
blocked.sort_unstable();
|
||||
blocked.into_iter().map(|(_, id)| id).collect()
|
||||
}
|
||||
|
||||
/// Nothing can run: advance to the next deadline or stop.
|
||||
fn idle(&self) -> Turn {
|
||||
let table = self.state.threads.lock().expect("guest thread table");
|
||||
if table.threads.is_empty() {
|
||||
return Turn::Stop(Outcome::AllThreadsExited);
|
||||
}
|
||||
if let Some(deadline) = table.next_deadline() {
|
||||
drop(table);
|
||||
let now = self.state.clock.performance_count();
|
||||
self.state.clock.sleep(deadline.saturating_sub(now));
|
||||
return Turn::Continue;
|
||||
}
|
||||
let mut blocked = Vec::new();
|
||||
let mut suspended = Vec::new();
|
||||
for (&id, thread) in &table.threads {
|
||||
if thread.suspend > 0 {
|
||||
suspended.push(id);
|
||||
} else {
|
||||
blocked.push(id);
|
||||
}
|
||||
}
|
||||
Turn::Stop(Outcome::Deadlock { blocked, suspended })
|
||||
}
|
||||
|
||||
fn run_thread(
|
||||
&self,
|
||||
engine: &mut DbtEngine,
|
||||
memory: &mut GuestMemory,
|
||||
id: u32,
|
||||
main_id: u32,
|
||||
limit: usize,
|
||||
report: &mut ScheduleReport,
|
||||
) -> Stop {
|
||||
let cpu = {
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
table.threads.get_mut(&id).and_then(|t| t.cpu.take())
|
||||
};
|
||||
let Some(mut cpu) = cpu else {
|
||||
return Stop::Ended;
|
||||
};
|
||||
self.state.hooks.take_switch();
|
||||
let result = engine.run_slice(&mut cpu, memory, limit);
|
||||
// The engine does not count a call that stops it.
|
||||
let stopped = matches!(
|
||||
result.exit_reason,
|
||||
ExitReason::GuestYield | ExitReason::GuestBlocked | ExitReason::GuestThreadExited
|
||||
);
|
||||
report.instructions += result.instructions_executed + usize::from(stopped);
|
||||
let rip = cpu.rip;
|
||||
let returned = (rip == THREAD_RETURN && id != main_id)
|
||||
.then(|| cpu.get(crate::cpu::Register::Rax) as u32);
|
||||
if id == main_id {
|
||||
report.main = cpu.clone();
|
||||
}
|
||||
let exit = {
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
let Some(thread) = table.threads.get_mut(&id) else {
|
||||
return Stop::Ended;
|
||||
};
|
||||
thread.cpu = Some(cpu);
|
||||
thread.exit
|
||||
};
|
||||
if let Some(code) = exit.or(returned) {
|
||||
self.state.end_thread(id, code, memory);
|
||||
return Stop::Ended;
|
||||
}
|
||||
match result.exit_reason {
|
||||
ExitReason::StepLimitExceeded => Stop::Preempted { front: false },
|
||||
ExitReason::GuestYield => Stop::Preempted {
|
||||
front: !self.state.hooks.take_switch(),
|
||||
},
|
||||
ExitReason::GuestBlocked => Stop::Blocked,
|
||||
ExitReason::Halt if id == main_id => Stop::Outcome(Outcome::Halted),
|
||||
reason => Stop::Outcome(Outcome::Fault {
|
||||
thread: id,
|
||||
reason,
|
||||
rip,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Stop {
|
||||
Blocked,
|
||||
Ended,
|
||||
Preempted { front: bool },
|
||||
Outcome(Outcome),
|
||||
}
|
||||
@@ -20,6 +20,7 @@ mod platform_fixture;
|
||||
mod synch;
|
||||
pub mod sysinfo;
|
||||
mod task_fixture;
|
||||
pub(crate) mod threads;
|
||||
mod winsock;
|
||||
|
||||
use crate::runtime::HResult;
|
||||
@@ -193,6 +194,8 @@ pub struct ServicesState {
|
||||
objects: Mutex<ObjectState>,
|
||||
last_errors: Mutex<BTreeMap<u64, u32>>,
|
||||
synch: Mutex<synch::Synch>,
|
||||
pub(crate) threads: Mutex<threads::ThreadTable>,
|
||||
pub(crate) hooks: Arc<threads::SchedulerHooks>,
|
||||
/// Functions registered with `atexit`, run in reverse order by `_cexit`.
|
||||
atexit: Mutex<Vec<u64>>,
|
||||
winsock: Mutex<winsock::Winsock>,
|
||||
@@ -217,6 +220,8 @@ impl ServicesState {
|
||||
objects: Mutex::new(ObjectState::default()),
|
||||
last_errors: Mutex::default(),
|
||||
synch: Mutex::default(),
|
||||
threads: Mutex::default(),
|
||||
hooks: Arc::default(),
|
||||
atexit: Mutex::default(),
|
||||
winsock: Mutex::default(),
|
||||
task_fixture: Mutex::default(),
|
||||
@@ -294,11 +299,26 @@ impl ServicesState {
|
||||
/// hand-written fixture services.
|
||||
pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<ServicesState>) {
|
||||
crate::runtime_table::register(registry, &state);
|
||||
registry.hooks = Some(Arc::clone(&state.hooks));
|
||||
threads::register(registry, &state);
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "GetThreadId", move |args, cpu, mem| {
|
||||
let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
if handle == CURRENT_THREAD {
|
||||
return Ok(u64::from(s.thread_id_of(cpu.gs_base)));
|
||||
}
|
||||
let thread = s.objects.lock().expect("guest object state");
|
||||
if let Some(GuestObject::Waitable { state, access }) = thread.handles.get(&handle)
|
||||
&& let events::Waitable::Thread { id, .. } =
|
||||
&*state.lock().expect("guest waitable state")
|
||||
{
|
||||
return if access & THREAD_QUERY_RIGHTS == 0 {
|
||||
s.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0)
|
||||
} else {
|
||||
Ok(u64::from(*id))
|
||||
};
|
||||
}
|
||||
if let Err(error) = thread.check_access(handle, THREAD_QUERY_RIGHTS) {
|
||||
return s.fail(cpu.gs_base, error, 0);
|
||||
}
|
||||
@@ -324,8 +344,12 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
|
||||
if inherit != 0 || options & !DUPLICATE_SAME_ACCESS != 0 || source == CURRENT_PROCESS {
|
||||
return s.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
let worker = s.current_worker(cpu.gs_base);
|
||||
let mut thread = s.objects.lock().expect("guest object state");
|
||||
let (granted, mut object) = if source == CURRENT_THREAD {
|
||||
let (granted, mut object) = if let (CURRENT_THREAD, Some(state)) = (source, worker) {
|
||||
let access = threads::THREAD_ALL_ACCESS;
|
||||
(access, GuestObject::Waitable { state, access })
|
||||
} else if source == CURRENT_THREAD {
|
||||
(
|
||||
THREAD_SUPPORTED_RIGHTS,
|
||||
GuestObject::Thread(THREAD_SUPPORTED_RIGHTS),
|
||||
@@ -664,7 +688,7 @@ pub(crate) mod handlers {
|
||||
}
|
||||
|
||||
pub fn get_current_thread_id(context: &mut ServiceContext<'_>) -> Outcome<u32> {
|
||||
Ok(context.state.thread_id)
|
||||
Ok(context.state.thread_id_of(context.teb))
|
||||
}
|
||||
|
||||
pub fn open_thread(
|
||||
@@ -674,21 +698,41 @@ pub(crate) mod handlers {
|
||||
id: u32,
|
||||
) -> Outcome<u64> {
|
||||
let state = context.state;
|
||||
if id != state.thread_id {
|
||||
let worker = state.worker_object(id);
|
||||
let main = id == state.thread_id && state.main_thread_alive();
|
||||
if !main && worker.is_none() {
|
||||
return state.fail(context.teb, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
if inherit || access & !THREAD_SUPPORTED_RIGHTS != 0 {
|
||||
let supported = THREAD_SUPPORTED_RIGHTS
|
||||
| if worker.is_some() {
|
||||
threads::WORKER_RIGHTS
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if inherit || access & !supported != 0 {
|
||||
return state.fail(context.teb, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
let mut thread = state.objects.lock().expect("guest object state");
|
||||
let Some(handle) = thread.next_handle() else {
|
||||
return state.fail(context.teb, ERROR_NOT_ENOUGH_MEMORY, 0);
|
||||
};
|
||||
thread.insert_handle(handle, GuestObject::Thread(access));
|
||||
let object = match worker {
|
||||
Some(state) => GuestObject::Waitable { state, access },
|
||||
None => GuestObject::Thread(access),
|
||||
};
|
||||
thread.insert_handle(handle, object);
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
pub fn get_thread_priority(context: &mut ServiceContext<'_>, handle: u64) -> Outcome<i32> {
|
||||
// Only the main thread has a priority; a worker must not change it.
|
||||
if handle == CURRENT_THREAD && context.state.current_worker(context.teb).is_some() {
|
||||
return context.state.fail(
|
||||
context.teb,
|
||||
ERROR_NOT_SUPPORTED,
|
||||
THREAD_PRIORITY_ERROR_RETURN as i32,
|
||||
);
|
||||
}
|
||||
let thread = context.state.objects.lock().expect("guest object state");
|
||||
if let Err(error) = thread.check_access(handle, THREAD_QUERY_RIGHTS) {
|
||||
return context
|
||||
@@ -703,6 +747,10 @@ pub(crate) mod handlers {
|
||||
handle: u64,
|
||||
priority: i32,
|
||||
) -> Outcome<bool> {
|
||||
// Only the main thread has a priority; a worker must not change it.
|
||||
if handle == CURRENT_THREAD && context.state.current_worker(context.teb).is_some() {
|
||||
return context.state.fail(context.teb, ERROR_NOT_SUPPORTED, false);
|
||||
}
|
||||
let state = context.state;
|
||||
let mut thread = state.objects.lock().expect("guest object state");
|
||||
if let Err(error) = thread.check_access(handle, THREAD_SET_RIGHTS) {
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Unnamed event, semaphore and mutex objects and waits that can resolve without a guest scheduler.
|
||||
//! Unnamed event, semaphore and mutex objects and waits. A wait that cannot
|
||||
//! resolve at once blocks the guest thread if a scheduler is attached, and is
|
||||
//! unsupported otherwise.
|
||||
|
||||
use super::threads::PendingWait;
|
||||
use super::{
|
||||
ERROR_ACCESS_DENIED, ERROR_INVALID_HANDLE, ERROR_INVALID_PARAMETER, ERROR_NOACCESS,
|
||||
ERROR_NOT_ENOUGH_MEMORY, ERROR_NOT_SUPPORTED, GuestObject, KERNEL32, ServicesState,
|
||||
@@ -13,11 +16,14 @@ use std::sync::{Arc, Mutex};
|
||||
|
||||
const SYNCH_API: &str = "api-ms-win-core-synch-l1-1-0.dll";
|
||||
const EVENT_MODIFY_STATE: u32 = 0x0002;
|
||||
const SYNCHRONIZE: u32 = 0x0010_0000;
|
||||
pub(super) const SYNCHRONIZE: u32 = 0x0010_0000;
|
||||
const EVENT_ALL_ACCESS: u32 = 0x001f_0003;
|
||||
const WAIT_OBJECT_0: u64 = 0;
|
||||
const INFINITE: u32 = u32::MAX;
|
||||
const TICKS_PER_MILLI: u64 = 10_000;
|
||||
const WAIT_TIMEOUT: u64 = 258;
|
||||
const WAIT_FAILED: u64 = u32::MAX as u64;
|
||||
const WAIT_ABANDONED_0: u64 = 0x80;
|
||||
|
||||
const SEMAPHORE_ALL_ACCESS: u32 = 0x001f_0003;
|
||||
const SEMAPHORE_MODIFY_STATE: u32 = 2;
|
||||
@@ -40,6 +46,13 @@ pub(super) enum Waitable {
|
||||
Mutex {
|
||||
owner: Option<u64>,
|
||||
recursion: u32,
|
||||
/// The owner ended without releasing it.
|
||||
abandoned: bool,
|
||||
},
|
||||
/// Signaled for good once the guest thread has ended.
|
||||
Thread {
|
||||
id: u32,
|
||||
exit_code: Option<u32>,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -49,21 +62,30 @@ impl Waitable {
|
||||
Self::Event { signaled, .. } => *signaled,
|
||||
Self::Semaphore { count, .. } => *count > 0,
|
||||
Self::Mutex { owner, .. } => owner.is_none_or(|owner| owner == teb),
|
||||
Self::Thread { exit_code, .. } => exit_code.is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
fn consume(&mut self, teb: u64) {
|
||||
/// Take the signal; true if it was an abandoned mutex.
|
||||
fn consume(&mut self, teb: u64) -> bool {
|
||||
match self {
|
||||
Self::Event {
|
||||
manual_reset,
|
||||
signaled,
|
||||
} => *signaled = *manual_reset,
|
||||
Self::Semaphore { count, .. } => *count -= 1,
|
||||
Self::Mutex { owner, recursion } => {
|
||||
Self::Mutex {
|
||||
owner,
|
||||
recursion,
|
||||
abandoned,
|
||||
} => {
|
||||
*owner = Some(teb);
|
||||
*recursion += 1;
|
||||
return std::mem::take(abandoned);
|
||||
}
|
||||
Self::Thread { .. } => {}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn at_recursion_limit(&self) -> bool {
|
||||
@@ -100,6 +122,7 @@ fn insert_mutex(
|
||||
let object = Waitable::Mutex {
|
||||
owner: initial_owner.then_some(teb),
|
||||
recursion: u32::from(initial_owner),
|
||||
abandoned: false,
|
||||
};
|
||||
insert_waitable(state, teb, object, access)
|
||||
}
|
||||
@@ -150,6 +173,9 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
return state.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0);
|
||||
}
|
||||
*current = signaled;
|
||||
if signaled {
|
||||
state.hooks.signal();
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
}
|
||||
@@ -202,6 +228,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
return release.fail(cpu.gs_base, ERROR_NOACCESS, 0);
|
||||
}
|
||||
*count += amount;
|
||||
release.hooks.signal();
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
@@ -244,7 +271,10 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
return release.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
};
|
||||
let mut state = state.lock().expect("guest waitable state");
|
||||
let Waitable::Mutex { owner, recursion } = &mut *state else {
|
||||
let Waitable::Mutex {
|
||||
owner, recursion, ..
|
||||
} = &mut *state
|
||||
else {
|
||||
return release.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
};
|
||||
if *owner != Some(cpu.gs_base) {
|
||||
@@ -253,6 +283,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
*recursion -= 1;
|
||||
if *recursion == 0 {
|
||||
*owner = None;
|
||||
release.hooks.signal();
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
@@ -263,6 +294,9 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
] {
|
||||
let single = Arc::clone(state);
|
||||
registry.register(KERNEL32, symbol, move |args, cpu, mem| {
|
||||
if let Some(result) = resume_wait(&single, cpu.gs_base) {
|
||||
return result;
|
||||
}
|
||||
let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let timeout = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
if extended && args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32 != 0 {
|
||||
@@ -277,6 +311,9 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
] {
|
||||
let multiple = Arc::clone(state);
|
||||
registry.register(KERNEL32, symbol, move |args, cpu, mem| {
|
||||
if let Some(result) = resume_wait(&multiple, cpu.gs_base) {
|
||||
return result;
|
||||
}
|
||||
let count = args.get(0, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let address = args.get(1, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let all = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32 != 0;
|
||||
@@ -363,21 +400,75 @@ fn wait_for_objects(
|
||||
None => return state.fail(teb, ERROR_INVALID_HANDLE, WAIT_FAILED),
|
||||
}
|
||||
}
|
||||
let mut ready = Vec::with_capacity(handles.len());
|
||||
for (index, event) in waitables.into_iter().enumerate() {
|
||||
if event.lock().expect("guest waitable state").is_ready(teb) {
|
||||
ready.push((index, event));
|
||||
if let Some(result) = try_satisfy(&waitables, all, teb) {
|
||||
return result;
|
||||
}
|
||||
if timeout == 0 {
|
||||
return Ok(WAIT_TIMEOUT);
|
||||
}
|
||||
if !state.hooks.is_attached() {
|
||||
return state.fail(teb, ERROR_NOT_SUPPORTED, WAIT_FAILED);
|
||||
}
|
||||
// Keep the objects themselves: closing a handle or changing the guest's
|
||||
// handle array does not change a wait already in progress.
|
||||
let deadline = (timeout != INFINITE).then(|| {
|
||||
state
|
||||
.clock
|
||||
.performance_count()
|
||||
.saturating_add(u64::from(timeout) * TICKS_PER_MILLI)
|
||||
});
|
||||
let pending = PendingWait {
|
||||
objects: waitables.into_iter().map(Arc::clone).collect(),
|
||||
all,
|
||||
deadline,
|
||||
};
|
||||
state
|
||||
.threads
|
||||
.lock()
|
||||
.expect("guest thread table")
|
||||
.waits
|
||||
.insert(teb, pending);
|
||||
Err(ExitReason::GuestBlocked)
|
||||
}
|
||||
|
||||
/// Continue the wait this thread is blocked in, if any. Waiters are retried
|
||||
/// directly after a signal, so an object found signaled once the deadline has
|
||||
/// passed was signaled too late and is left alone.
|
||||
fn resume_wait(state: &ServicesState, teb: u64) -> Option<Result<u64, ExitReason>> {
|
||||
let mut table = state.threads.lock().expect("guest thread table");
|
||||
let pending = table.waits.get(&teb)?;
|
||||
let expired = pending
|
||||
.deadline
|
||||
.is_some_and(|deadline| state.clock.performance_count() >= deadline);
|
||||
let result = if expired {
|
||||
Some(Ok(WAIT_TIMEOUT))
|
||||
} else {
|
||||
let objects: Vec<&Arc<Mutex<Waitable>>> = pending.objects.iter().collect();
|
||||
try_satisfy(&objects, pending.all, teb)
|
||||
};
|
||||
if result.is_some() {
|
||||
table.waits.remove(&teb);
|
||||
}
|
||||
Some(result.unwrap_or(Err(ExitReason::GuestBlocked)))
|
||||
}
|
||||
|
||||
/// Consume the objects if the wait is satisfied now.
|
||||
fn try_satisfy(
|
||||
waitables: &[&Arc<Mutex<Waitable>>],
|
||||
all: bool,
|
||||
teb: u64,
|
||||
) -> Option<Result<u64, ExitReason>> {
|
||||
let mut ready = Vec::with_capacity(waitables.len());
|
||||
for (index, object) in waitables.iter().enumerate() {
|
||||
if object.lock().expect("guest waitable state").is_ready(teb) {
|
||||
ready.push((index, object));
|
||||
if !all {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ready.is_empty() || (all && ready.len() != handles.len()) {
|
||||
return if timeout == 0 {
|
||||
Ok(WAIT_TIMEOUT)
|
||||
} else {
|
||||
state.fail(teb, ERROR_NOT_SUPPORTED, WAIT_FAILED)
|
||||
};
|
||||
if ready.is_empty() || (all && ready.len() != waitables.len()) {
|
||||
return None;
|
||||
}
|
||||
if ready.iter().any(|(_, object)| {
|
||||
object
|
||||
@@ -386,11 +477,42 @@ fn wait_for_objects(
|
||||
.at_recursion_limit()
|
||||
}) {
|
||||
// Windows raises STATUS_MUTANT_LIMIT_EXCEEDED; exceptions are unsupported.
|
||||
return Err(ExitReason::IllegalInstruction(0xFE));
|
||||
return Some(Err(ExitReason::IllegalInstruction(0xFE)));
|
||||
}
|
||||
let first = ready[0].0;
|
||||
for (_, event) in ready {
|
||||
event.lock().expect("guest waitable state").consume(teb);
|
||||
let first = ready[0].0 as u64;
|
||||
let mut abandoned = None;
|
||||
for (index, object) in ready {
|
||||
if object.lock().expect("guest waitable state").consume(teb) {
|
||||
abandoned.get_or_insert(index as u64);
|
||||
}
|
||||
}
|
||||
Some(Ok(match abandoned {
|
||||
Some(index) => WAIT_ABANDONED_0 + index,
|
||||
None => WAIT_OBJECT_0 + first,
|
||||
}))
|
||||
}
|
||||
|
||||
impl ServicesState {
|
||||
/// Release every mutex owned by a guest thread that has ended.
|
||||
pub(super) fn abandon_mutexes(&self, teb: u64) {
|
||||
let objects = self.objects.lock().expect("guest object state");
|
||||
let table = self.threads.lock().expect("guest thread table");
|
||||
let handles = objects.handles.values().filter_map(|object| match object {
|
||||
GuestObject::Waitable { state, .. } => Some(state),
|
||||
_ => None,
|
||||
});
|
||||
// A waiter keeps an object alive after its last handle is closed.
|
||||
let waiting = table.waits.values().flat_map(|wait| &wait.objects);
|
||||
for object in handles.chain(waiting) {
|
||||
if let Waitable::Mutex {
|
||||
owner,
|
||||
recursion,
|
||||
abandoned,
|
||||
} = &mut *object.lock().expect("guest waitable state")
|
||||
&& *owner == Some(teb)
|
||||
{
|
||||
(*owner, *recursion, *abandoned) = (None, 0, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(WAIT_OBJECT_0 + first as u64)
|
||||
}
|
||||
@@ -3,9 +3,10 @@
|
||||
//! Critical sections, slim reader/writer locks, condition variables, one-time
|
||||
//! initialization, interlocked singly linked lists and thread-local storage.
|
||||
//!
|
||||
//! Ownership is keyed by the calling guest TEB. No guest scheduler exists yet,
|
||||
//! so an operation that would have to block another guest thread stops the
|
||||
//! guest with the runtime-limit fault instead of pretending to synchronize.
|
||||
//! Ownership is keyed by the calling guest TEB. These objects do not block
|
||||
//! through the guest scheduler yet, so an operation that would have to wait for
|
||||
//! another guest thread stops the guest with the runtime-limit fault instead of
|
||||
//! pretending to synchronize.
|
||||
|
||||
use super::{
|
||||
ERROR_INVALID_PARAMETER, ERROR_NOT_ENOUGH_MEMORY, ERROR_NOT_SUPPORTED, KERNEL32, ServicesState,
|
||||
@@ -37,6 +38,9 @@ const CRITICAL_SECTION_NO_DEBUG_INFO: u32 = 0x0100_0000;
|
||||
const MAX_CRITICAL_SECTIONS: usize = 4096;
|
||||
|
||||
const MAX_SRW_LOCKS: usize = 4096;
|
||||
const MAX_PENDING_INIT_ONCE: usize = 4096;
|
||||
/// Owner of a lock whose thread ended while holding it. Never a TEB address.
|
||||
const ENDED_THREAD: u64 = u64::MAX;
|
||||
const CONDITION_VARIABLE_LOCKMODE_SHARED: u32 = 1;
|
||||
|
||||
const INIT_ONCE_CHECK_ONLY: u32 = 1;
|
||||
@@ -161,6 +165,33 @@ pub(super) struct Synch {
|
||||
}
|
||||
|
||||
impl Synch {
|
||||
/// Drop the thread-local values of a guest thread that has ended, without
|
||||
/// running FLS callbacks. Locks it held stay held: its TEB address may be
|
||||
/// reused, and the next thread there must not own them.
|
||||
pub(super) fn retire_thread(&mut self, teb: u64) {
|
||||
self.tls_values.retain(|&(owner, _), _| owner != teb);
|
||||
self.fls_values.retain(|&(owner, _), _| owner != teb);
|
||||
for section in self.sections.values_mut() {
|
||||
if section.owner == Some(teb) {
|
||||
section.owner = Some(ENDED_THREAD);
|
||||
}
|
||||
}
|
||||
for lock in self.srw.values_mut() {
|
||||
if lock.exclusive == Some(teb) {
|
||||
lock.exclusive = Some(ENDED_THREAD);
|
||||
}
|
||||
if let Some(count) = lock.shared.remove(&teb) {
|
||||
let held = lock.shared.entry(ENDED_THREAD).or_default();
|
||||
*held = held.saturating_add(count);
|
||||
}
|
||||
}
|
||||
for owner in self.init_once_pending.values_mut() {
|
||||
if *owner == teb {
|
||||
*owner = ENDED_THREAD;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn section(&mut self, address: u64) -> Result<&mut CriticalSection, ExitReason> {
|
||||
// Using an uninitialized critical section is undefined; report it.
|
||||
self.sections.get_mut(&address).map_or_else(unsupported, Ok)
|
||||
@@ -228,6 +259,7 @@ fn enter_section(
|
||||
address: u64,
|
||||
teb: u64,
|
||||
) -> Result<bool, ExitReason> {
|
||||
let thread_id = state.thread_id_of(teb);
|
||||
let mut synch = state.synch.lock().expect("guest synchronization state");
|
||||
let section = synch.section(address)?;
|
||||
match section.owner {
|
||||
@@ -237,7 +269,7 @@ fn enter_section(
|
||||
}
|
||||
section.owner = Some(teb);
|
||||
section.recursion += 1;
|
||||
mirror_section(memory, address, section, state.thread_id)?;
|
||||
mirror_section(memory, address, section, thread_id)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
@@ -247,6 +279,7 @@ fn leave_section(
|
||||
address: u64,
|
||||
teb: u64,
|
||||
) -> Result<(), ExitReason> {
|
||||
let thread_id = state.thread_id_of(teb);
|
||||
let mut synch = state.synch.lock().expect("guest synchronization state");
|
||||
let section = synch.section(address)?;
|
||||
if section.owner != Some(teb) {
|
||||
@@ -256,7 +289,7 @@ fn leave_section(
|
||||
if section.recursion == 0 {
|
||||
section.owner = None;
|
||||
}
|
||||
mirror_section(memory, address, section, state.thread_id)
|
||||
mirror_section(memory, address, section, thread_id)
|
||||
}
|
||||
|
||||
/// Check that a pointer-sized synchronization object is readable and writable.
|
||||
@@ -611,8 +644,9 @@ fn register_srw_and_conditions(registry: &mut ImportRegistry, state: &Arc<Servic
|
||||
}
|
||||
}
|
||||
|
||||
/// A zero timeout releases and reacquires the lock, which no other guest
|
||||
/// thread can observe, then reports the timeout. Longer sleeps would block.
|
||||
/// A zero timeout releases and reacquires the lock within one service call, so
|
||||
/// no other guest thread can observe it, then reports the timeout. Longer sleeps
|
||||
/// would block.
|
||||
fn sleep_result(state: &ServicesState, teb: u64, timeout: u32) -> Result<u64, ExitReason> {
|
||||
if timeout == 0 {
|
||||
state.fail(teb, ERROR_TIMEOUT, 0)
|
||||
@@ -666,6 +700,9 @@ fn register_init_once(registry: &mut ImportRegistry, state: &Arc<ServicesState>)
|
||||
s.fail(teb, ERROR_GEN_FAILURE, 0)
|
||||
}
|
||||
0 if value == 0 => {
|
||||
if synch.init_once_pending.len() >= MAX_PENDING_INIT_ONCE {
|
||||
return unsupported();
|
||||
}
|
||||
mem.write_u32(pending, 1).map_err(fault)?;
|
||||
mem.write_u64(once, INIT_ONCE_PENDING).map_err(fault)?;
|
||||
synch.init_once_pending.insert(once, teb);
|
||||
@@ -727,6 +764,9 @@ fn register_init_once(registry: &mut ImportRegistry, state: &Arc<ServicesState>)
|
||||
return unsupported();
|
||||
}
|
||||
let mut synch = s.synch.lock().expect("guest synchronization state");
|
||||
if synch.init_once_pending.len() >= MAX_PENDING_INIT_ONCE {
|
||||
return unsupported();
|
||||
}
|
||||
mem.write_u64(scratch, 0).map_err(fault)?;
|
||||
mem.write_u64(once, INIT_ONCE_PENDING).map_err(fault)?;
|
||||
synch.init_once_pending.insert(once, teb);
|
||||
|
||||
@@ -0,0 +1,590 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Guest thread table and the thread services.
|
||||
//!
|
||||
//! A guest thread is a CPU context, a guarded stack and a TEB. It is not a host
|
||||
//! thread: [`crate::scheduler`] runs one guest thread at a time on one host
|
||||
//! thread. Without an attached scheduler `CreateThread` reports
|
||||
//! `ERROR_NOT_SUPPORTED`, no thread object exists, and waits behave as they do
|
||||
//! for a single thread.
|
||||
|
||||
use super::events::{SYNCHRONIZE, Waitable};
|
||||
use super::{
|
||||
CURRENT_THREAD, ERROR_ACCESS_DENIED, ERROR_INVALID_HANDLE, ERROR_INVALID_PARAMETER,
|
||||
ERROR_NOACCESS, ERROR_NOT_ENOUGH_MEMORY, ERROR_NOT_SUPPORTED, GuestObject, KERNEL32, PAGE_SIZE,
|
||||
PROCESS_THREADS_V1, ServicesState, THREAD_QUERY_RIGHTS,
|
||||
};
|
||||
use crate::cpu::{CpuState, ExitReason, Register};
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use crate::memory::{ALLOCATION_GRANULARITY, GuestMemory, MemoryError, MemoryPermissions};
|
||||
use std::collections::{BTreeMap, BTreeSet, VecDeque};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// Most guest threads alive at once, the main thread included.
|
||||
pub const MAX_THREADS: usize = 64;
|
||||
/// Stack of a thread created with a zero size.
|
||||
pub const DEFAULT_STACK: u64 = 256 * 1024;
|
||||
const MAX_STACK: u64 = 8 * 1024 * 1024;
|
||||
/// Highest suspend count (MAXIMUM_SUSPEND_COUNT).
|
||||
const MAX_SUSPEND: u32 = 127;
|
||||
/// GetExitCodeThread result while the thread runs.
|
||||
const STILL_ACTIVE: u32 = 259;
|
||||
const CREATE_SUSPENDED: u32 = 4;
|
||||
const STACK_SIZE_PARAM_IS_A_RESERVATION: u32 = 0x0001_0000;
|
||||
pub(super) const THREAD_ALL_ACCESS: u32 = 0x001F_FFFF;
|
||||
const THREAD_TERMINATE: u32 = 1;
|
||||
const THREAD_SUSPEND_RESUME: u32 = 2;
|
||||
/// Rights that exist only on worker thread objects.
|
||||
pub(super) const WORKER_RIGHTS: u32 = THREAD_TERMINATE | THREAD_SUSPEND_RESUME;
|
||||
const ERROR_SIGNAL_REFUSED: u32 = 156;
|
||||
|
||||
/// Each thread slot holds a guard page, the stack, a guard page and the TEB.
|
||||
const THREAD_AREA: u64 = 0x0000_0006_0000_0000;
|
||||
const THREAD_STRIDE: u64 = 0x0100_0000;
|
||||
const TEB_OFFSET: u64 = 0x00F0_0000;
|
||||
const TEB_SIZE: u64 = 0x2000;
|
||||
const TEB_STACK_BASE: u64 = 0x08;
|
||||
const TEB_STACK_LIMIT: u64 = 0x10;
|
||||
const TEB_SELF: u64 = 0x30;
|
||||
|
||||
/// Return address of a thread's start routine. Nothing is mapped there.
|
||||
pub(crate) const THREAD_RETURN: u64 = 0xFFFF_FFFF_FFFE_0000;
|
||||
|
||||
/// How a service asked the scheduler to act after it completed.
|
||||
const SWITCH_NONE: u8 = 0;
|
||||
const SWITCH_SIGNAL: u8 = 1;
|
||||
const SWITCH_YIELD: u8 = 2;
|
||||
|
||||
/// Shared between the services, the import dispatcher and the scheduler.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct SchedulerHooks {
|
||||
attached: AtomicBool,
|
||||
switch: AtomicU8,
|
||||
}
|
||||
|
||||
impl SchedulerHooks {
|
||||
pub(crate) fn is_attached(&self) -> bool {
|
||||
self.attached.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// An object other threads may wait for changed.
|
||||
pub(super) fn signal(&self) {
|
||||
if self.is_attached() {
|
||||
self.switch.fetch_max(SWITCH_SIGNAL, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
fn yield_turn(&self) {
|
||||
self.switch.store(SWITCH_YIELD, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// Whether the dispatcher should stop the current thread after the call.
|
||||
pub(crate) fn switch_requested(&self) -> bool {
|
||||
self.switch.load(Ordering::SeqCst) != SWITCH_NONE
|
||||
}
|
||||
|
||||
/// Take the request; true if the thread gives up its turn.
|
||||
pub(crate) fn take_switch(&self) -> bool {
|
||||
self.switch.swap(SWITCH_NONE, Ordering::SeqCst) == SWITCH_YIELD
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum RunState {
|
||||
Ready,
|
||||
/// Waiting in a service; the sequence number orders waiters.
|
||||
Blocked(u64),
|
||||
}
|
||||
|
||||
pub(crate) struct GuestThread {
|
||||
teb: u64,
|
||||
/// Taken by the scheduler while the thread runs.
|
||||
pub(crate) cpu: Option<CpuState>,
|
||||
pub(crate) run: RunState,
|
||||
pub(crate) suspend: u32,
|
||||
/// What is left of a turn the thread interrupted by signaling.
|
||||
pub(crate) credit: Option<usize>,
|
||||
object: Arc<Mutex<Waitable>>,
|
||||
slot: Option<u64>,
|
||||
allocations: Vec<u64>,
|
||||
/// Set by ExitThread and TerminateThread.
|
||||
pub(crate) exit: Option<u32>,
|
||||
}
|
||||
|
||||
/// Objects a blocked thread waits for, captured when it first blocked.
|
||||
pub(super) struct PendingWait {
|
||||
pub(super) objects: Vec<Arc<Mutex<Waitable>>>,
|
||||
pub(super) all: bool,
|
||||
pub(super) deadline: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct ThreadTable {
|
||||
pub(crate) threads: BTreeMap<u32, GuestThread>,
|
||||
/// Ready threads in the order they run.
|
||||
pub(crate) queue: VecDeque<u32>,
|
||||
pub(super) waits: BTreeMap<u64, PendingWait>,
|
||||
/// Main thread wait of a run that stopped on its budget, and the context
|
||||
/// that continues it.
|
||||
continued: Option<(CpuState, PendingWait)>,
|
||||
slots: BTreeSet<u64>,
|
||||
last_id: u32,
|
||||
pub(crate) sequence: u64,
|
||||
}
|
||||
|
||||
impl ThreadTable {
|
||||
fn id_of(&self, teb: u64) -> Option<u32> {
|
||||
self.threads
|
||||
.iter()
|
||||
.find(|(_, thread)| thread.teb == teb)
|
||||
.map(|(&id, _)| id)
|
||||
}
|
||||
|
||||
fn by_object(&mut self, object: &Arc<Mutex<Waitable>>) -> Option<&mut GuestThread> {
|
||||
self.threads
|
||||
.values_mut()
|
||||
.find(|thread| Arc::ptr_eq(&thread.object, object))
|
||||
}
|
||||
|
||||
/// Earliest deadline of any wait that is not suspended away.
|
||||
pub(crate) fn next_deadline(&self) -> Option<u64> {
|
||||
self.threads
|
||||
.values()
|
||||
.filter(|thread| thread.suspend == 0 && thread.run != RunState::Ready)
|
||||
.filter_map(|thread| self.waits.get(&thread.teb)?.deadline)
|
||||
.min()
|
||||
}
|
||||
}
|
||||
|
||||
/// Arguments of CreateThread.
|
||||
struct ThreadRequest {
|
||||
stack: u64,
|
||||
start: u64,
|
||||
parameter: u64,
|
||||
suspended: bool,
|
||||
/// `stack` is the reservation rather than the initial commitment.
|
||||
reservation: bool,
|
||||
id_output: u64,
|
||||
}
|
||||
|
||||
fn map_thread(
|
||||
memory: &mut GuestMemory,
|
||||
base: u64,
|
||||
stack: u64,
|
||||
allocations: &mut Vec<u64>,
|
||||
) -> Result<(), MemoryError> {
|
||||
let low = base + PAGE_SIZE;
|
||||
let top = low + stack;
|
||||
let teb = base + TEB_OFFSET;
|
||||
for (address, size, permissions) in [
|
||||
(base, PAGE_SIZE, MemoryPermissions::NO_ACCESS),
|
||||
(low, stack, MemoryPermissions::READ_WRITE),
|
||||
(top, PAGE_SIZE, MemoryPermissions::NO_ACCESS),
|
||||
(teb, TEB_SIZE, MemoryPermissions::READ_WRITE),
|
||||
] {
|
||||
allocations.push(memory.map_thread_region(address, size as usize, permissions)?);
|
||||
}
|
||||
// A recycled TEB address must not inherit the previous thread's errno.
|
||||
let errno = memory.crt_errno_address(teb)?;
|
||||
memory.write_u32_bypass(errno, 0)?;
|
||||
memory.write_u64_bypass(teb + TEB_STACK_BASE, top)?;
|
||||
memory.write_u64_bypass(teb + TEB_STACK_LIMIT, low)?;
|
||||
memory.write_u64_bypass(teb + TEB_SELF, teb)
|
||||
}
|
||||
|
||||
impl ServicesState {
|
||||
/// Adopt the calling context as the main guest thread.
|
||||
pub(crate) fn attach_scheduler(&self, main: &CpuState) -> Result<u32, ExitReason> {
|
||||
let mut table = self.threads.lock().expect("guest thread table");
|
||||
if self.hooks.attached.swap(true, Ordering::SeqCst) {
|
||||
return Err(ExitReason::ServiceAbiViolation);
|
||||
}
|
||||
// IDs are never reused, even by a later run.
|
||||
table.last_id = table.last_id.max(self.thread_id);
|
||||
table.threads.insert(
|
||||
self.thread_id,
|
||||
GuestThread {
|
||||
teb: main.gs_base,
|
||||
cpu: Some(main.clone()),
|
||||
run: RunState::Ready,
|
||||
suspend: 0,
|
||||
credit: None,
|
||||
object: Arc::new(Mutex::new(Waitable::Thread {
|
||||
id: self.thread_id,
|
||||
exit_code: None,
|
||||
})),
|
||||
slot: None,
|
||||
allocations: Vec::new(),
|
||||
exit: None,
|
||||
},
|
||||
);
|
||||
table.queue.push_back(self.thread_id);
|
||||
if let Some((context, wait)) = table.continued.take()
|
||||
&& context == *main
|
||||
{
|
||||
table.waits.insert(main.gs_base, wait);
|
||||
}
|
||||
Ok(self.thread_id)
|
||||
}
|
||||
|
||||
/// Reclaim every created thread. The main thread keeps its per-thread state.
|
||||
/// `continues` is its context if the run stopped on its budget; its pending
|
||||
/// wait is then kept for that context.
|
||||
pub(crate) fn detach_scheduler(&self, memory: &mut GuestMemory, continues: Option<&CpuState>) {
|
||||
let workers: Vec<u32> = {
|
||||
let table = self.threads.lock().expect("guest thread table");
|
||||
let worker = |(&id, thread): (&u32, &GuestThread)| thread.slot.map(|_| id);
|
||||
table.threads.iter().filter_map(worker).collect()
|
||||
};
|
||||
for id in workers {
|
||||
self.end_thread(id, 0, memory);
|
||||
}
|
||||
let mut table = self.threads.lock().expect("guest thread table");
|
||||
if let Some(context) = continues {
|
||||
let wait = table.waits.remove(&context.gs_base);
|
||||
table.continued = wait.map(|wait| (context.clone(), wait));
|
||||
}
|
||||
table.threads.clear();
|
||||
table.queue.clear();
|
||||
table.waits.clear();
|
||||
drop(table);
|
||||
self.hooks.switch.store(SWITCH_NONE, Ordering::SeqCst);
|
||||
self.hooks.attached.store(false, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// Record a thread's exit code, signal its object and reclaim its state.
|
||||
pub(crate) fn end_thread(&self, id: u32, code: u32, memory: &mut GuestMemory) {
|
||||
let thread = {
|
||||
let mut table = self.threads.lock().expect("guest thread table");
|
||||
let Some(thread) = table.threads.remove(&id) else {
|
||||
return;
|
||||
};
|
||||
table.queue.retain(|&queued| queued != id);
|
||||
table.waits.remove(&thread.teb);
|
||||
if let Some(slot) = thread.slot {
|
||||
table.slots.remove(&slot);
|
||||
}
|
||||
thread
|
||||
};
|
||||
if let Waitable::Thread { exit_code, .. } =
|
||||
&mut *thread.object.lock().expect("guest waitable state")
|
||||
{
|
||||
*exit_code = Some(code);
|
||||
}
|
||||
self.abandon_mutexes(thread.teb);
|
||||
self.retire_thread_last_error(thread.teb);
|
||||
self.synch
|
||||
.lock()
|
||||
.expect("guest synchronization state")
|
||||
.retire_thread(thread.teb);
|
||||
memory
|
||||
.callback_frames
|
||||
.retain(|&(teb, _), _| teb != thread.teb);
|
||||
for base in thread.allocations {
|
||||
memory.release_thread_region(base);
|
||||
}
|
||||
self.hooks.signal();
|
||||
}
|
||||
|
||||
/// ID of the guest thread whose TEB is `teb`.
|
||||
pub(super) fn thread_id_of(&self, teb: u64) -> u32 {
|
||||
self.threads
|
||||
.lock()
|
||||
.expect("guest thread table")
|
||||
.id_of(teb)
|
||||
.unwrap_or(self.thread_id)
|
||||
}
|
||||
|
||||
/// Whether the main thread can still be named by its ID.
|
||||
pub(super) fn main_thread_alive(&self) -> bool {
|
||||
let table = self.threads.lock().expect("guest thread table");
|
||||
!self.hooks.is_attached() || table.threads.contains_key(&self.thread_id)
|
||||
}
|
||||
|
||||
/// Thread object for an ID, if that thread is alive and not the main thread.
|
||||
pub(super) fn worker_object(&self, id: u32) -> Option<Arc<Mutex<Waitable>>> {
|
||||
let table = self.threads.lock().expect("guest thread table");
|
||||
table
|
||||
.threads
|
||||
.get(&id)
|
||||
.filter(|thread| thread.slot.is_some())
|
||||
.map(|thread| Arc::clone(&thread.object))
|
||||
}
|
||||
|
||||
/// Thread object of the calling worker, or `None` in the main thread.
|
||||
pub(super) fn current_worker(&self, teb: u64) -> Option<Arc<Mutex<Waitable>>> {
|
||||
let table = self.threads.lock().expect("guest thread table");
|
||||
let thread = table.threads.get(&table.id_of(teb)?)?;
|
||||
thread.slot.map(|_| Arc::clone(&thread.object))
|
||||
}
|
||||
|
||||
fn create_thread(
|
||||
&self,
|
||||
teb: u64,
|
||||
memory: &mut GuestMemory,
|
||||
request: &ThreadRequest,
|
||||
) -> Result<u64, ExitReason> {
|
||||
if request.id_output != 0 && memory.check_write(request.id_output, 4).is_err() {
|
||||
return self.fail(teb, ERROR_NOACCESS, 0);
|
||||
}
|
||||
// Without the reservation flag the size is an initial commitment, and
|
||||
// the reservation is at least the default.
|
||||
let stack = if request.stack == 0 || !request.reservation {
|
||||
request.stack.max(DEFAULT_STACK)
|
||||
} else {
|
||||
request.stack
|
||||
};
|
||||
let Some(stack) = stack
|
||||
.checked_next_multiple_of(ALLOCATION_GRANULARITY)
|
||||
.filter(|&size| size <= MAX_STACK)
|
||||
else {
|
||||
return self.fail(teb, ERROR_NOT_ENOUGH_MEMORY, 0);
|
||||
};
|
||||
let mut objects = self.objects.lock().expect("guest object state");
|
||||
let mut table = self.threads.lock().expect("guest thread table");
|
||||
let handle = objects.next_handle();
|
||||
let id = table.last_id.checked_add(4);
|
||||
let (Some(handle), Some(id), true) = (handle, id, table.threads.len() < MAX_THREADS) else {
|
||||
return self.fail(teb, ERROR_NOT_ENOUGH_MEMORY, 0);
|
||||
};
|
||||
// A slot the guest has mapped something into is skipped.
|
||||
let mut prepared = None;
|
||||
for slot in (0..2 * MAX_THREADS as u64).filter(|slot| !table.slots.contains(slot)) {
|
||||
let base = THREAD_AREA + slot * THREAD_STRIDE;
|
||||
let mut allocations = Vec::new();
|
||||
// The start routine is entered as if called: RSP is 8 modulo 16,
|
||||
// and above it are the return address and a 32-byte home area.
|
||||
let rsp = base + PAGE_SIZE + stack - 40;
|
||||
let mapped = map_thread(memory, base, stack, &mut allocations)
|
||||
.and_then(|()| memory.write_u64(rsp, THREAD_RETURN));
|
||||
if mapped.is_ok() {
|
||||
prepared = Some((slot, base, rsp, allocations));
|
||||
break;
|
||||
}
|
||||
for base in allocations {
|
||||
memory.release_thread_region(base);
|
||||
}
|
||||
if !matches!(mapped, Err(MemoryError::OverlappingRegion { .. })) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some((slot, base, rsp, allocations)) = prepared else {
|
||||
return self.fail(teb, ERROR_NOT_ENOUGH_MEMORY, 0);
|
||||
};
|
||||
if request.id_output != 0 {
|
||||
memory
|
||||
.write_u32(request.id_output, id)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
let mut cpu = CpuState::new(request.start, rsp);
|
||||
cpu.gs_base = base + TEB_OFFSET;
|
||||
cpu.set(Register::Rcx, request.parameter);
|
||||
let object = Arc::new(Mutex::new(Waitable::Thread {
|
||||
id,
|
||||
exit_code: None,
|
||||
}));
|
||||
objects.insert_handle(
|
||||
handle,
|
||||
GuestObject::Waitable {
|
||||
state: Arc::clone(&object),
|
||||
access: THREAD_ALL_ACCESS,
|
||||
},
|
||||
);
|
||||
table.slots.insert(slot);
|
||||
table.last_id = id;
|
||||
table.threads.insert(
|
||||
id,
|
||||
GuestThread {
|
||||
teb: base + TEB_OFFSET,
|
||||
cpu: Some(cpu),
|
||||
run: RunState::Ready,
|
||||
suspend: u32::from(request.suspended),
|
||||
credit: None,
|
||||
object,
|
||||
slot: Some(slot),
|
||||
allocations,
|
||||
exit: None,
|
||||
},
|
||||
);
|
||||
table.queue.push_back(id);
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
/// Thread object and granted rights behind a handle.
|
||||
fn thread_handle(&self, teb: u64, handle: u64) -> Result<(Arc<Mutex<Waitable>>, u32), u32> {
|
||||
if handle == CURRENT_THREAD {
|
||||
let mut table = self.threads.lock().expect("guest thread table");
|
||||
let id = table.id_of(teb).ok_or(ERROR_INVALID_HANDLE)?;
|
||||
let thread = table.threads.get_mut(&id).ok_or(ERROR_INVALID_HANDLE)?;
|
||||
return Ok((Arc::clone(&thread.object), THREAD_ALL_ACCESS));
|
||||
}
|
||||
let objects = self.objects.lock().expect("guest object state");
|
||||
match objects.handles.get(&handle) {
|
||||
Some(GuestObject::Waitable { state, access })
|
||||
if matches!(
|
||||
*state.lock().expect("guest waitable state"),
|
||||
Waitable::Thread { .. }
|
||||
) =>
|
||||
{
|
||||
Ok((Arc::clone(state), *access))
|
||||
}
|
||||
// Handles to the main thread from OpenThread name no object.
|
||||
Some(GuestObject::Thread(_)) => Err(ERROR_NOT_SUPPORTED),
|
||||
_ => Err(ERROR_INVALID_HANDLE),
|
||||
}
|
||||
}
|
||||
|
||||
/// Change another thread's suspend count and return the previous one.
|
||||
fn change_suspend(&self, teb: u64, handle: u64, resume: bool) -> Result<u64, ExitReason> {
|
||||
const FAILED: u64 = u32::MAX as u64;
|
||||
let (object, access) = match self.thread_handle(teb, handle) {
|
||||
Ok(found) => found,
|
||||
Err(error) => return self.fail(teb, error, FAILED),
|
||||
};
|
||||
if access & THREAD_SUSPEND_RESUME == 0 {
|
||||
return self.fail(teb, ERROR_ACCESS_DENIED, FAILED);
|
||||
}
|
||||
let mut table = self.threads.lock().expect("guest thread table");
|
||||
let Some(thread) = table.by_object(&object) else {
|
||||
return self.fail(teb, ERROR_ACCESS_DENIED, FAILED); // terminated
|
||||
};
|
||||
let previous = thread.suspend;
|
||||
if resume {
|
||||
thread.suspend = previous.saturating_sub(1);
|
||||
} else if previous >= MAX_SUSPEND {
|
||||
return self.fail(teb, ERROR_SIGNAL_REFUSED, FAILED);
|
||||
} else {
|
||||
thread.suspend = previous + 1;
|
||||
}
|
||||
drop(table);
|
||||
self.hooks.signal();
|
||||
Ok(u64::from(previous))
|
||||
}
|
||||
|
||||
fn terminate(
|
||||
&self,
|
||||
teb: u64,
|
||||
handle: u64,
|
||||
code: u32,
|
||||
memory: &mut GuestMemory,
|
||||
) -> Result<u64, ExitReason> {
|
||||
let (object, access) = match self.thread_handle(teb, handle) {
|
||||
Ok(found) => found,
|
||||
Err(error) => return self.fail(teb, error, 0),
|
||||
};
|
||||
if access & THREAD_TERMINATE == 0 {
|
||||
return self.fail(teb, ERROR_ACCESS_DENIED, 0);
|
||||
}
|
||||
let mut table = self.threads.lock().expect("guest thread table");
|
||||
let Some(id) = table
|
||||
.threads
|
||||
.iter()
|
||||
.find(|(_, thread)| Arc::ptr_eq(&thread.object, &object))
|
||||
.map(|(&id, _)| id)
|
||||
else {
|
||||
return self.fail(teb, ERROR_ACCESS_DENIED, 0); // already terminated
|
||||
};
|
||||
let thread = table.threads.get_mut(&id).expect("thread found above");
|
||||
if thread.teb == teb {
|
||||
thread.exit = Some(code);
|
||||
return Err(ExitReason::GuestThreadExited);
|
||||
}
|
||||
drop(table);
|
||||
self.end_thread(id, code, memory);
|
||||
Ok(1)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "CreateThread", move |args, cpu, memory| {
|
||||
let arg = |index| args.get(index, memory).map_err(ExitReason::MemoryFault);
|
||||
let attributes = arg(0)?;
|
||||
let flags = arg(4)? as u32;
|
||||
let request = ThreadRequest {
|
||||
stack: arg(1)?,
|
||||
start: arg(2)?,
|
||||
parameter: arg(3)?,
|
||||
suspended: flags & CREATE_SUSPENDED != 0,
|
||||
reservation: flags & STACK_SIZE_PARAM_IS_A_RESERVATION != 0,
|
||||
id_output: arg(5)?,
|
||||
};
|
||||
if !s.hooks.is_attached() || attributes != 0 {
|
||||
return s.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
if flags & !(CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION) != 0 {
|
||||
return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
s.create_thread(cpu.gs_base, memory, &request)
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "ExitThread", move |args, cpu, _| {
|
||||
let mut table = s.threads.lock().expect("guest thread table");
|
||||
let Some(id) = table.id_of(cpu.gs_base) else {
|
||||
return Err(ExitReason::IllegalInstruction(0xFE));
|
||||
};
|
||||
table.threads.get_mut(&id).expect("thread found above").exit = Some(args.rcx as u32);
|
||||
Err(ExitReason::GuestThreadExited)
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "TerminateThread", move |args, cpu, memory| {
|
||||
s.terminate(cpu.gs_base, args.rcx, args.rdx as u32, memory)
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "GetExitCodeThread", move |args, cpu, memory| {
|
||||
let (object, access) = match s.thread_handle(cpu.gs_base, args.rcx) {
|
||||
Ok(found) => found,
|
||||
Err(error) => return s.fail(cpu.gs_base, error, 0),
|
||||
};
|
||||
if access & THREAD_QUERY_RIGHTS == 0 {
|
||||
return s.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0);
|
||||
}
|
||||
let code = match &*object.lock().expect("guest waitable state") {
|
||||
Waitable::Thread { exit_code, .. } => exit_code.unwrap_or(STILL_ACTIVE),
|
||||
_ => return s.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0),
|
||||
};
|
||||
if memory.write_u32(args.rdx, code).is_err() {
|
||||
return s.fail(cpu.gs_base, ERROR_NOACCESS, 0);
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
for (symbol, resume) in [("SuspendThread", false), ("ResumeThread", true)] {
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, symbol, move |args, cpu, _| {
|
||||
s.change_suspend(cpu.gs_base, args.rcx, resume)
|
||||
});
|
||||
}
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "SwitchToThread", move |_, cpu, _| {
|
||||
let table = s.threads.lock().expect("guest thread table");
|
||||
let current = table.id_of(cpu.gs_base);
|
||||
let other = table.threads.iter().any(|(&id, thread)| {
|
||||
Some(id) != current && thread.run == RunState::Ready && thread.suspend == 0
|
||||
});
|
||||
drop(table);
|
||||
if other {
|
||||
s.hooks.yield_turn();
|
||||
}
|
||||
Ok(u64::from(other))
|
||||
});
|
||||
|
||||
for symbol in [
|
||||
"CreateThread",
|
||||
"ExitThread",
|
||||
"TerminateThread",
|
||||
"GetExitCodeThread",
|
||||
"SuspendThread",
|
||||
"ResumeThread",
|
||||
"SwitchToThread",
|
||||
] {
|
||||
registry.alias(PROCESS_THREADS_V1, KERNEL32, symbol);
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
const _: () = assert!(THREAD_ALL_ACCESS & SYNCHRONIZE != 0);
|
||||
}
|
||||
+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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -373,6 +373,8 @@ pub fn execute(
|
||||
Encoding::OpRegImm => write_reg(cpu, insn.reg, size, insn.imm),
|
||||
_ => write_rm(cpu, memory, insn, insn.imm & mask(size))?,
|
||||
},
|
||||
// A non-temporal store is an ordinary store: there is no cache to bypass.
|
||||
Op::Movnti => write_rm(cpu, memory, insn, read_reg(cpu, insn.reg, size))?,
|
||||
Op::Movzx => {
|
||||
let value = read_rm(cpu, memory, insn)?;
|
||||
write_reg(cpu, insn.reg, size, value);
|
||||
@@ -603,6 +605,10 @@ pub fn execute(
|
||||
cpu.gpr[RSP] = sp.wrapping_add(8).wrapping_add(insn.imm);
|
||||
}
|
||||
Op::Nop => {}
|
||||
// Every load and store of an instruction completes before the next
|
||||
// instruction starts, on one host thread, so guest accesses are already
|
||||
// totally ordered and a fence has nothing further to enforce.
|
||||
Op::Lfence | Op::Mfence | Op::Sfence => {}
|
||||
Op::Cpuid => {
|
||||
// The leaf is EAX and the subleaf ECX. Each result is a 32-bit
|
||||
// register write, so the upper halves are cleared.
|
||||
|
||||
+173
-133
@@ -78,6 +78,7 @@ pub enum Op {
|
||||
Movdqa,
|
||||
Movdqu,
|
||||
Movntdq,
|
||||
Movnti,
|
||||
Movntps,
|
||||
Movss,
|
||||
Movsd,
|
||||
@@ -155,6 +156,9 @@ pub enum Op {
|
||||
Pinsrw,
|
||||
Pextrw,
|
||||
Ldmxcsr,
|
||||
Lfence,
|
||||
Mfence,
|
||||
Sfence,
|
||||
Stmxcsr,
|
||||
Sqrtps,
|
||||
Sqrtpd,
|
||||
@@ -211,7 +215,7 @@ pub enum Op {
|
||||
}
|
||||
|
||||
impl Op {
|
||||
pub const ALL: &[Op] = &[Op::Add, Op::Or, Op::Adc, Op::Sbb, Op::And, Op::Sub, Op::Xor, Op::Cmp, Op::Test, Op::Inc, Op::Dec, Op::Neg, Op::Not, Op::Mov, Op::Movzx, Op::Movsx, Op::Movsxd, Op::Lea, Op::Xchg, Op::Xadd, Op::Cmpxchg, Op::Bswap, Op::Cwde, Op::Cdq, Op::Rol, Op::Ror, Op::Rcl, Op::Rcr, Op::Shl, Op::Shr, Op::Sar, Op::Mul, Op::Imul, Op::Imul2, Op::Div, Op::Idiv, Op::Cmov, Op::Setcc, Op::Bt, Op::Bts, Op::Btr, Op::Btc, Op::Bsf, Op::Bsr, Op::Popcnt, Op::Tzcnt, Op::Lzcnt, Op::Push, Op::Pop, Op::Leave, Op::Call, Op::Jmp, Op::Jcc, Op::Ret, Op::Nop, Op::Hlt, Op::Syscall, Op::Clc, Op::Stc, Op::Cmc, Op::Cpuid, Op::Cld, Op::Std, Op::Movs, Op::Stos, Op::Movaps, Op::Movups, Op::Movdqa, Op::Movdqu, Op::Movntdq, Op::Movntps, Op::Movss, Op::Movsd, Op::Movq, Op::Movd, Op::Movlps, Op::Movhps, Op::Movmskps, Op::Movmskpd, Op::Pmovmskb, Op::Pand, Op::Pandn, Op::Por, Op::Pxor, Op::Punpcklbw, Op::Punpcklwd, Op::Punpckldq, Op::Packsswb, Op::Pcmpgtb, Op::Pcmpgtw, Op::Pcmpgtd, Op::Packuswb, Op::Punpckhbw, Op::Punpckhwd, Op::Punpckhdq, Op::Packssdw, Op::Punpcklqdq, Op::Punpckhqdq, Op::Pcmpeqb, Op::Pcmpeqw, Op::Pcmpeqd, Op::Paddq, Op::Pmullw, Op::Psubusb, Op::Psubusw, Op::Pminub, Op::Paddusb, Op::Paddusw, Op::Pmaxub, Op::Pavgb, Op::Pavgw, Op::Pmulhuw, Op::Pmulhw, Op::Psubsb, Op::Psubsw, Op::Pminsw, Op::Paddsb, Op::Paddsw, Op::Pmaxsw, Op::Pmuludq, Op::Pmaddwd, Op::Psadbw, Op::Psubb, Op::Psubw, Op::Psubd, Op::Psubq, Op::Paddb, Op::Paddw, Op::Paddd, Op::Psrlw, Op::Psraw, Op::Psllw, Op::Psrld, Op::Psrad, Op::Pslld, Op::Psrlq, Op::Psllq, Op::Psrldq, Op::Pslldq, Op::Pshufd, Op::Pshufhw, Op::Pshuflw, Op::Shufps, Op::Shufpd, Op::Pinsrw, Op::Pextrw, Op::Ldmxcsr, Op::Stmxcsr, Op::Sqrtps, Op::Sqrtpd, Op::Sqrtss, Op::Sqrtsd, Op::Addps, Op::Addpd, Op::Addss, Op::Addsd, Op::Mulps, Op::Mulpd, Op::Mulss, Op::Mulsd, Op::Subps, Op::Subpd, Op::Subss, Op::Subsd, Op::Minps, Op::Minpd, Op::Minss, Op::Minsd, Op::Divps, Op::Divpd, Op::Divss, Op::Divsd, Op::Maxps, Op::Maxpd, Op::Maxss, Op::Maxsd, Op::Cmpps, Op::Cmppd, Op::Cmpss, Op::Cmpsd, Op::Ucomiss, Op::Comiss, Op::Ucomisd, Op::Comisd, Op::Cvtps2pd, Op::Cvtpd2ps, Op::Cvtss2sd, Op::Cvtsd2ss, Op::Cvtdq2ps, Op::Cvtps2dq, Op::Cvttps2dq, Op::Cvttpd2dq, Op::Cvtdq2pd, Op::Cvtpd2dq, Op::Cvtsi2ss, Op::Cvttss2si, Op::Cvtss2si, Op::Cvtsi2sd, Op::Cvttsd2si, Op::Cvtsd2si];
|
||||
pub const ALL: &[Op] = &[Op::Add, Op::Or, Op::Adc, Op::Sbb, Op::And, Op::Sub, Op::Xor, Op::Cmp, Op::Test, Op::Inc, Op::Dec, Op::Neg, Op::Not, Op::Mov, Op::Movzx, Op::Movsx, Op::Movsxd, Op::Lea, Op::Xchg, Op::Xadd, Op::Cmpxchg, Op::Bswap, Op::Cwde, Op::Cdq, Op::Rol, Op::Ror, Op::Rcl, Op::Rcr, Op::Shl, Op::Shr, Op::Sar, Op::Mul, Op::Imul, Op::Imul2, Op::Div, Op::Idiv, Op::Cmov, Op::Setcc, Op::Bt, Op::Bts, Op::Btr, Op::Btc, Op::Bsf, Op::Bsr, Op::Popcnt, Op::Tzcnt, Op::Lzcnt, Op::Push, Op::Pop, Op::Leave, Op::Call, Op::Jmp, Op::Jcc, Op::Ret, Op::Nop, Op::Hlt, Op::Syscall, Op::Clc, Op::Stc, Op::Cmc, Op::Cpuid, Op::Cld, Op::Std, Op::Movs, Op::Stos, Op::Movaps, Op::Movups, Op::Movdqa, Op::Movdqu, Op::Movntdq, Op::Movnti, Op::Movntps, Op::Movss, Op::Movsd, Op::Movq, Op::Movd, Op::Movlps, Op::Movhps, Op::Movmskps, Op::Movmskpd, Op::Pmovmskb, Op::Pand, Op::Pandn, Op::Por, Op::Pxor, Op::Punpcklbw, Op::Punpcklwd, Op::Punpckldq, Op::Packsswb, Op::Pcmpgtb, Op::Pcmpgtw, Op::Pcmpgtd, Op::Packuswb, Op::Punpckhbw, Op::Punpckhwd, Op::Punpckhdq, Op::Packssdw, Op::Punpcklqdq, Op::Punpckhqdq, Op::Pcmpeqb, Op::Pcmpeqw, Op::Pcmpeqd, Op::Paddq, Op::Pmullw, Op::Psubusb, Op::Psubusw, Op::Pminub, Op::Paddusb, Op::Paddusw, Op::Pmaxub, Op::Pavgb, Op::Pavgw, Op::Pmulhuw, Op::Pmulhw, Op::Psubsb, Op::Psubsw, Op::Pminsw, Op::Paddsb, Op::Paddsw, Op::Pmaxsw, Op::Pmuludq, Op::Pmaddwd, Op::Psadbw, Op::Psubb, Op::Psubw, Op::Psubd, Op::Psubq, Op::Paddb, Op::Paddw, Op::Paddd, Op::Psrlw, Op::Psraw, Op::Psllw, Op::Psrld, Op::Psrad, Op::Pslld, Op::Psrlq, Op::Psllq, Op::Psrldq, Op::Pslldq, Op::Pshufd, Op::Pshufhw, Op::Pshuflw, Op::Shufps, Op::Shufpd, Op::Pinsrw, Op::Pextrw, Op::Ldmxcsr, Op::Lfence, Op::Mfence, Op::Sfence, Op::Stmxcsr, Op::Sqrtps, Op::Sqrtpd, Op::Sqrtss, Op::Sqrtsd, Op::Addps, Op::Addpd, Op::Addss, Op::Addsd, Op::Mulps, Op::Mulpd, Op::Mulss, Op::Mulsd, Op::Subps, Op::Subpd, Op::Subss, Op::Subsd, Op::Minps, Op::Minpd, Op::Minss, Op::Minsd, Op::Divps, Op::Divpd, Op::Divss, Op::Divsd, Op::Maxps, Op::Maxpd, Op::Maxss, Op::Maxsd, Op::Cmpps, Op::Cmppd, Op::Cmpss, Op::Cmpsd, Op::Ucomiss, Op::Comiss, Op::Ucomisd, Op::Comisd, Op::Cvtps2pd, Op::Cvtpd2ps, Op::Cvtss2sd, Op::Cvtsd2ss, Op::Cvtdq2ps, Op::Cvtps2dq, Op::Cvttps2dq, Op::Cvttpd2dq, Op::Cvtdq2pd, Op::Cvtpd2dq, Op::Cvtsi2ss, Op::Cvttss2si, Op::Cvtss2si, Op::Cvtsi2sd, Op::Cvttsd2si, Op::Cvtsd2si];
|
||||
|
||||
/// Lower-case mnemonic stem.
|
||||
pub const fn name(self) -> &'static str {
|
||||
@@ -286,6 +290,7 @@ impl Op {
|
||||
Op::Movdqa => "movdqa",
|
||||
Op::Movdqu => "movdqu",
|
||||
Op::Movntdq => "movntdq",
|
||||
Op::Movnti => "movnti",
|
||||
Op::Movntps => "movntps",
|
||||
Op::Movss => "movss",
|
||||
Op::Movsd => "movsd",
|
||||
@@ -363,6 +368,9 @@ impl Op {
|
||||
Op::Pinsrw => "pinsrw",
|
||||
Op::Pextrw => "pextrw",
|
||||
Op::Ldmxcsr => "ldmxcsr",
|
||||
Op::Lfence => "lfence",
|
||||
Op::Mfence => "mfence",
|
||||
Op::Sfence => "sfence",
|
||||
Op::Stmxcsr => "stmxcsr",
|
||||
Op::Sqrtps => "sqrtps",
|
||||
Op::Sqrtpd => "sqrtpd",
|
||||
@@ -492,6 +500,7 @@ impl Op {
|
||||
Op::Movdqa => 0,
|
||||
Op::Movdqu => 0,
|
||||
Op::Movntdq => 0,
|
||||
Op::Movnti => 0,
|
||||
Op::Movntps => 0,
|
||||
Op::Movss => 0,
|
||||
Op::Movsd => 0,
|
||||
@@ -569,6 +578,9 @@ impl Op {
|
||||
Op::Pinsrw => 0,
|
||||
Op::Pextrw => 0,
|
||||
Op::Ldmxcsr => 0,
|
||||
Op::Lfence => 0,
|
||||
Op::Mfence => 0,
|
||||
Op::Sfence => 0,
|
||||
Op::Stmxcsr => 0,
|
||||
Op::Sqrtps => 0,
|
||||
Op::Sqrtpd => 0,
|
||||
@@ -698,6 +710,7 @@ impl Op {
|
||||
Op::Movdqa => 0,
|
||||
Op::Movdqu => 0,
|
||||
Op::Movntdq => 0,
|
||||
Op::Movnti => 0,
|
||||
Op::Movntps => 0,
|
||||
Op::Movss => 0,
|
||||
Op::Movsd => 0,
|
||||
@@ -775,6 +788,9 @@ impl Op {
|
||||
Op::Pinsrw => 0,
|
||||
Op::Pextrw => 0,
|
||||
Op::Ldmxcsr => 0,
|
||||
Op::Lfence => 0,
|
||||
Op::Mfence => 0,
|
||||
Op::Sfence => 0,
|
||||
Op::Stmxcsr => 0,
|
||||
Op::Sqrtps => 0,
|
||||
Op::Sqrtpd => 0,
|
||||
@@ -904,6 +920,7 @@ impl Op {
|
||||
Op::Movdqa => 0,
|
||||
Op::Movdqu => 0,
|
||||
Op::Movntdq => 0,
|
||||
Op::Movnti => 0,
|
||||
Op::Movntps => 0,
|
||||
Op::Movss => 0,
|
||||
Op::Movsd => 0,
|
||||
@@ -981,6 +998,9 @@ impl Op {
|
||||
Op::Pinsrw => 0,
|
||||
Op::Pextrw => 0,
|
||||
Op::Ldmxcsr => 0,
|
||||
Op::Lfence => 0,
|
||||
Op::Mfence => 0,
|
||||
Op::Sfence => 0,
|
||||
Op::Stmxcsr => 0,
|
||||
Op::Sqrtps => 0,
|
||||
Op::Sqrtpd => 0,
|
||||
@@ -1110,6 +1130,7 @@ impl Op {
|
||||
Op::Movdqa => 0,
|
||||
Op::Movdqu => 0,
|
||||
Op::Movntdq => 0,
|
||||
Op::Movnti => 0,
|
||||
Op::Movntps => 0,
|
||||
Op::Movss => 0,
|
||||
Op::Movsd => 0,
|
||||
@@ -1187,6 +1208,9 @@ impl Op {
|
||||
Op::Pinsrw => 0,
|
||||
Op::Pextrw => 0,
|
||||
Op::Ldmxcsr => 0,
|
||||
Op::Lfence => 0,
|
||||
Op::Mfence => 0,
|
||||
Op::Sfence => 0,
|
||||
Op::Stmxcsr => 0,
|
||||
Op::Sqrtps => 0,
|
||||
Op::Sqrtpd => 0,
|
||||
@@ -1316,6 +1340,7 @@ impl Op {
|
||||
Op::Movdqa => false,
|
||||
Op::Movdqu => false,
|
||||
Op::Movntdq => false,
|
||||
Op::Movnti => false,
|
||||
Op::Movntps => false,
|
||||
Op::Movss => false,
|
||||
Op::Movsd => false,
|
||||
@@ -1393,6 +1418,9 @@ impl Op {
|
||||
Op::Pinsrw => false,
|
||||
Op::Pextrw => false,
|
||||
Op::Ldmxcsr => false,
|
||||
Op::Lfence => false,
|
||||
Op::Mfence => false,
|
||||
Op::Sfence => false,
|
||||
Op::Stmxcsr => false,
|
||||
Op::Sqrtps => false,
|
||||
Op::Sqrtpd => false,
|
||||
@@ -1522,6 +1550,7 @@ impl Op {
|
||||
Op::Movdqa => false,
|
||||
Op::Movdqu => false,
|
||||
Op::Movntdq => false,
|
||||
Op::Movnti => false,
|
||||
Op::Movntps => false,
|
||||
Op::Movss => false,
|
||||
Op::Movsd => false,
|
||||
@@ -1599,6 +1628,9 @@ impl Op {
|
||||
Op::Pinsrw => false,
|
||||
Op::Pextrw => false,
|
||||
Op::Ldmxcsr => false,
|
||||
Op::Lfence => false,
|
||||
Op::Mfence => false,
|
||||
Op::Sfence => false,
|
||||
Op::Stmxcsr => false,
|
||||
Op::Sqrtps => true,
|
||||
Op::Sqrtpd => true,
|
||||
@@ -1728,6 +1760,7 @@ impl Op {
|
||||
Op::Movdqa => true,
|
||||
Op::Movdqu => true,
|
||||
Op::Movntdq => true,
|
||||
Op::Movnti => false,
|
||||
Op::Movntps => true,
|
||||
Op::Movss => true,
|
||||
Op::Movsd => true,
|
||||
@@ -1805,6 +1838,9 @@ impl Op {
|
||||
Op::Pinsrw => true,
|
||||
Op::Pextrw => true,
|
||||
Op::Ldmxcsr => false,
|
||||
Op::Lfence => false,
|
||||
Op::Mfence => false,
|
||||
Op::Sfence => false,
|
||||
Op::Stmxcsr => false,
|
||||
Op::Sqrtps => true,
|
||||
Op::Sqrtpd => true,
|
||||
@@ -1862,7 +1898,7 @@ impl Op {
|
||||
}
|
||||
}
|
||||
|
||||
pub static FORMS: [Form; 388] = [
|
||||
pub static FORMS: [Form; 392] = [
|
||||
Form { op: Op::Movsxd, encoding: Encoding::RegRm, size: OperandSize::Wide, immediate: Immediate::None, source: 4, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Push, encoding: Encoding::OpReg, size: OperandSize::Quad, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Pop, encoding: Encoding::OpReg, size: OperandSize::Quad, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
@@ -1956,6 +1992,7 @@ pub static FORMS: [Form; 388] = [
|
||||
Form { op: Op::Movdqu, encoding: Encoding::XmmRm, size: OperandSize::Xmm, immediate: Immediate::None, source: 16, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: true, lockable: false },
|
||||
Form { op: Op::Movdqu, encoding: Encoding::RmXmm, size: OperandSize::Xmm, immediate: Immediate::None, source: 16, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: true, lockable: false },
|
||||
Form { op: Op::Movntdq, encoding: Encoding::RmXmm, size: OperandSize::Xmm, immediate: Immediate::None, source: 16, has_modrm: true, memory_only: true, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Movnti, encoding: Encoding::RmReg, size: OperandSize::Wide, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: true, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Movntps, encoding: Encoding::RmXmm, size: OperandSize::Xmm, immediate: Immediate::None, source: 16, has_modrm: true, memory_only: true, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Movntps, encoding: Encoding::RmXmm, size: OperandSize::Xmm, immediate: Immediate::None, source: 16, has_modrm: true, memory_only: true, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Movss, encoding: Encoding::XmmRm, size: OperandSize::Xmm, immediate: Immediate::None, source: 4, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
@@ -2065,6 +2102,9 @@ pub static FORMS: [Form; 388] = [
|
||||
Form { op: Op::Pextrw, encoding: Encoding::RegXmmImm, size: OperandSize::Wide, immediate: Immediate::Byte, source: 16, has_modrm: true, memory_only: false, register_only: true, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Ldmxcsr, encoding: Encoding::Rm, size: OperandSize::None, immediate: Immediate::None, source: 4, has_modrm: true, memory_only: true, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Stmxcsr, encoding: Encoding::Rm, size: OperandSize::None, immediate: Immediate::None, source: 4, has_modrm: true, memory_only: true, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Lfence, encoding: Encoding::RmUnread, size: OperandSize::None, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: true, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Mfence, encoding: Encoding::RmUnread, size: OperandSize::None, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: true, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Sfence, encoding: Encoding::RmUnread, size: OperandSize::None, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: true, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Sqrtps, encoding: Encoding::XmmRm, size: OperandSize::Xmm, immediate: Immediate::None, source: 16, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Sqrtpd, encoding: Encoding::XmmRm, size: OperandSize::Xmm, immediate: Immediate::None, source: 16, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Sqrtss, encoding: Encoding::XmmRm, size: OperandSize::Xmm, immediate: Immediate::None, source: 4, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
@@ -2255,47 +2295,47 @@ pub static FORMS: [Form; 388] = [
|
||||
|
||||
/// Form per ModRM digit; 65535 marks an unsupported digit.
|
||||
pub static GROUPS: [[u16; 8]; 22] = [
|
||||
[260, 269, 278, 287, 296, 305, 314, 323],
|
||||
[261, 270, 279, 288, 297, 306, 315, 324],
|
||||
[262, 271, 280, 289, 298, 307, 316, 325],
|
||||
[264, 273, 282, 291, 300, 309, 318, 327],
|
||||
[265, 274, 283, 292, 301, 310, 319, 328],
|
||||
[266, 275, 284, 293, 302, 311, 320, 329],
|
||||
[6, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
[346, 347, 348, 349, 350, 351, 65535, 352],
|
||||
[353, 354, 355, 356, 357, 358, 65535, 359],
|
||||
[350, 351, 352, 353, 354, 355, 65535, 356],
|
||||
[357, 358, 359, 360, 361, 362, 65535, 363],
|
||||
[40, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
[41, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
[360, 361, 362, 363, 364, 365, 65535, 366],
|
||||
[367, 368, 369, 370, 371, 372, 65535, 373],
|
||||
[374, 375, 376, 377, 378, 379, 65535, 380],
|
||||
[381, 382, 383, 384, 385, 386, 65535, 387],
|
||||
[18, 65535, 330, 331, 332, 333, 334, 335],
|
||||
[19, 65535, 336, 337, 338, 339, 340, 341],
|
||||
[342, 343, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
[344, 345, 48, 65535, 49, 65535, 5, 65535],
|
||||
[364, 365, 366, 367, 368, 369, 65535, 370],
|
||||
[371, 372, 373, 374, 375, 376, 65535, 377],
|
||||
[378, 379, 380, 381, 382, 383, 65535, 384],
|
||||
[385, 386, 387, 388, 389, 390, 65535, 391],
|
||||
[18, 65535, 334, 335, 336, 337, 338, 339],
|
||||
[19, 65535, 340, 341, 342, 343, 344, 345],
|
||||
[346, 347, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
[348, 349, 48, 65535, 49, 65535, 5, 65535],
|
||||
[35, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
[65535, 65535, 200, 201, 65535, 65535, 65535, 65535],
|
||||
[65535, 65535, 65535, 65535, 326, 327, 328, 329],
|
||||
[65535, 65535, 172, 65535, 174, 65535, 176, 65535],
|
||||
[65535, 65535, 178, 65535, 180, 65535, 182, 65535],
|
||||
[65535, 65535, 184, 187, 65535, 65535, 186, 188],
|
||||
[65535, 65535, 201, 202, 65535, 203, 204, 205],
|
||||
[65535, 65535, 65535, 65535, 330, 331, 332, 333],
|
||||
[65535, 65535, 173, 65535, 175, 65535, 177, 65535],
|
||||
[65535, 65535, 179, 65535, 181, 65535, 183, 65535],
|
||||
[65535, 65535, 185, 188, 65535, 65535, 187, 189],
|
||||
];
|
||||
|
||||
pub static ONE_BYTE: [Entry; 256] = [
|
||||
Entry::Form(254), Entry::Form(255), Entry::Form(256), Entry::Form(257),
|
||||
Entry::Form(258), Entry::Form(259), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(263), Entry::Form(264), Entry::Form(265), Entry::Form(266),
|
||||
Entry::Form(267), Entry::Form(268), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(272), Entry::Form(273), Entry::Form(274), Entry::Form(275),
|
||||
Entry::Form(276), Entry::Form(277), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(281), Entry::Form(282), Entry::Form(283), Entry::Form(284),
|
||||
Entry::Form(285), Entry::Form(286), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(290), Entry::Form(291), Entry::Form(292), Entry::Form(293),
|
||||
Entry::Form(294), Entry::Form(295), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(299), Entry::Form(300), Entry::Form(301), Entry::Form(302),
|
||||
Entry::Form(303), Entry::Form(304), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(308), Entry::Form(309), Entry::Form(310), Entry::Form(311),
|
||||
Entry::Form(312), Entry::Form(313), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(317), Entry::Form(318), Entry::Form(319), Entry::Form(320),
|
||||
Entry::Form(321), Entry::Form(322), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(258), Entry::Form(259), Entry::Form(260), Entry::Form(261),
|
||||
Entry::Form(262), Entry::Form(263), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(267), Entry::Form(268), Entry::Form(269), Entry::Form(270),
|
||||
Entry::Form(271), Entry::Form(272), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(276), Entry::Form(277), Entry::Form(278), Entry::Form(279),
|
||||
Entry::Form(280), Entry::Form(281), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(285), Entry::Form(286), Entry::Form(287), Entry::Form(288),
|
||||
Entry::Form(289), Entry::Form(290), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(294), Entry::Form(295), Entry::Form(296), Entry::Form(297),
|
||||
Entry::Form(298), Entry::Form(299), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(303), Entry::Form(304), Entry::Form(305), Entry::Form(306),
|
||||
Entry::Form(307), Entry::Form(308), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(312), Entry::Form(313), Entry::Form(314), Entry::Form(315),
|
||||
Entry::Form(316), Entry::Form(317), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(321), Entry::Form(322), Entry::Form(323), Entry::Form(324),
|
||||
Entry::Form(325), Entry::Form(326), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2351,14 +2391,14 @@ pub static TWO_BYTE: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Form(54), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(84), Entry::Form(85), Entry::Form(103), Entry::Form(105),
|
||||
Entry::Form(194), Entry::Form(196), Entry::Form(107), Entry::Form(109),
|
||||
Entry::Form(84), Entry::Form(85), Entry::Form(104), Entry::Form(106),
|
||||
Entry::Form(195), Entry::Form(197), Entry::Form(108), Entry::Form(110),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Group(16),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(80), Entry::Form(81), Entry::Unsupported, Entry::Form(93),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(234), Entry::Form(235),
|
||||
Entry::Form(80), Entry::Form(81), Entry::Unsupported, Entry::Form(94),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(238), Entry::Form(239),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2367,10 +2407,10 @@ pub static TWO_BYTE: [Entry; 256] = [
|
||||
Entry::Form(12), Entry::Form(12), Entry::Form(12), Entry::Form(12),
|
||||
Entry::Form(12), Entry::Form(12), Entry::Form(12), Entry::Form(12),
|
||||
Entry::Form(12), Entry::Form(12), Entry::Form(12), Entry::Form(12),
|
||||
Entry::Form(111), Entry::Form(202), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(115), Entry::Form(118), Entry::Form(121), Entry::Form(124),
|
||||
Entry::Form(206), Entry::Form(210), Entry::Form(238), Entry::Form(242),
|
||||
Entry::Form(214), Entry::Form(218), Entry::Form(222), Entry::Form(226),
|
||||
Entry::Form(112), Entry::Form(206), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(116), Entry::Form(119), Entry::Form(122), Entry::Form(125),
|
||||
Entry::Form(210), Entry::Form(214), Entry::Form(242), Entry::Form(246),
|
||||
Entry::Form(218), Entry::Form(222), Entry::Form(226), Entry::Form(230),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2395,8 +2435,8 @@ pub static TWO_BYTE: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(62), Entry::Form(63),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Group(18), Entry::Form(75),
|
||||
Entry::Form(67), Entry::Form(68), Entry::Form(64), Entry::Form(65),
|
||||
Entry::Form(78), Entry::Form(79), Entry::Form(230), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(192), Entry::Unsupported,
|
||||
Entry::Form(78), Entry::Form(79), Entry::Form(234), Entry::Form(93),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(193), Entry::Unsupported,
|
||||
Entry::Form(66), Entry::Form(66), Entry::Form(66), Entry::Form(66),
|
||||
Entry::Form(66), Entry::Form(66), Entry::Form(66), Entry::Form(66),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2418,14 +2458,14 @@ pub static TWO_BYTE_66: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(86), Entry::Form(87), Entry::Form(104), Entry::Form(106),
|
||||
Entry::Form(195), Entry::Form(197), Entry::Form(108), Entry::Form(110),
|
||||
Entry::Form(86), Entry::Form(87), Entry::Form(105), Entry::Form(107),
|
||||
Entry::Form(196), Entry::Form(198), Entry::Form(109), Entry::Form(111),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(82), Entry::Form(83), Entry::Unsupported, Entry::Form(94),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(236), Entry::Form(237),
|
||||
Entry::Form(82), Entry::Form(83), Entry::Unsupported, Entry::Form(95),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(240), Entry::Form(241),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2434,18 +2474,18 @@ pub static TWO_BYTE_66: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(112), Entry::Form(203), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(116), Entry::Form(119), Entry::Form(122), Entry::Form(125),
|
||||
Entry::Form(207), Entry::Form(211), Entry::Form(239), Entry::Form(243),
|
||||
Entry::Form(215), Entry::Form(219), Entry::Form(223), Entry::Form(227),
|
||||
Entry::Form(126), Entry::Form(127), Entry::Form(128), Entry::Form(129),
|
||||
Entry::Form(130), Entry::Form(131), Entry::Form(132), Entry::Form(133),
|
||||
Entry::Form(134), Entry::Form(135), Entry::Form(136), Entry::Form(137),
|
||||
Entry::Form(138), Entry::Form(139), Entry::Form(101), Entry::Form(88),
|
||||
Entry::Form(189), Entry::Group(19), Entry::Group(20), Entry::Group(21),
|
||||
Entry::Form(140), Entry::Form(141), Entry::Form(142), Entry::Unsupported,
|
||||
Entry::Form(113), Entry::Form(207), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(117), Entry::Form(120), Entry::Form(123), Entry::Form(126),
|
||||
Entry::Form(211), Entry::Form(215), Entry::Form(243), Entry::Form(247),
|
||||
Entry::Form(219), Entry::Form(223), Entry::Form(227), Entry::Form(231),
|
||||
Entry::Form(127), Entry::Form(128), Entry::Form(129), Entry::Form(130),
|
||||
Entry::Form(131), Entry::Form(132), Entry::Form(133), Entry::Form(134),
|
||||
Entry::Form(135), Entry::Form(136), Entry::Form(137), Entry::Form(138),
|
||||
Entry::Form(139), Entry::Form(140), Entry::Form(102), Entry::Form(88),
|
||||
Entry::Form(190), Entry::Group(19), Entry::Group(20), Entry::Group(21),
|
||||
Entry::Form(141), Entry::Form(142), Entry::Form(143), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(102), Entry::Form(89),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(103), Entry::Form(89),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2462,22 +2502,22 @@ pub static TWO_BYTE_66: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(231), Entry::Unsupported,
|
||||
Entry::Form(198), Entry::Form(199), Entry::Form(193), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(235), Entry::Unsupported,
|
||||
Entry::Form(199), Entry::Form(200), Entry::Form(194), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Form(171), Entry::Form(177), Entry::Form(183),
|
||||
Entry::Form(143), Entry::Form(144), Entry::Form(100), Entry::Form(113),
|
||||
Entry::Form(145), Entry::Form(146), Entry::Form(147), Entry::Form(114),
|
||||
Entry::Form(148), Entry::Form(149), Entry::Form(150), Entry::Form(117),
|
||||
Entry::Form(151), Entry::Form(173), Entry::Form(179), Entry::Form(152),
|
||||
Entry::Form(153), Entry::Form(154), Entry::Form(245), Entry::Form(92),
|
||||
Entry::Form(155), Entry::Form(156), Entry::Form(157), Entry::Form(120),
|
||||
Entry::Form(158), Entry::Form(159), Entry::Form(160), Entry::Form(123),
|
||||
Entry::Unsupported, Entry::Form(175), Entry::Form(181), Entry::Form(185),
|
||||
Entry::Form(161), Entry::Form(162), Entry::Form(163), Entry::Unsupported,
|
||||
Entry::Form(164), Entry::Form(165), Entry::Form(166), Entry::Form(167),
|
||||
Entry::Form(168), Entry::Form(169), Entry::Form(170), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Form(172), Entry::Form(178), Entry::Form(184),
|
||||
Entry::Form(144), Entry::Form(145), Entry::Form(101), Entry::Form(114),
|
||||
Entry::Form(146), Entry::Form(147), Entry::Form(148), Entry::Form(115),
|
||||
Entry::Form(149), Entry::Form(150), Entry::Form(151), Entry::Form(118),
|
||||
Entry::Form(152), Entry::Form(174), Entry::Form(180), Entry::Form(153),
|
||||
Entry::Form(154), Entry::Form(155), Entry::Form(249), Entry::Form(92),
|
||||
Entry::Form(156), Entry::Form(157), Entry::Form(158), Entry::Form(121),
|
||||
Entry::Form(159), Entry::Form(160), Entry::Form(161), Entry::Form(124),
|
||||
Entry::Unsupported, Entry::Form(176), Entry::Form(182), Entry::Form(186),
|
||||
Entry::Form(162), Entry::Form(163), Entry::Form(164), Entry::Unsupported,
|
||||
Entry::Form(165), Entry::Form(166), Entry::Form(167), Entry::Form(168),
|
||||
Entry::Form(169), Entry::Form(170), Entry::Form(171), Entry::Unsupported,
|
||||
];
|
||||
|
||||
pub static TWO_BYTE_F3: [Entry; 256] = [
|
||||
@@ -2485,14 +2525,14 @@ pub static TWO_BYTE_F3: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(95), Entry::Form(96), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(96), Entry::Form(97), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(248), Entry::Unsupported,
|
||||
Entry::Form(249), Entry::Form(250), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(252), Entry::Unsupported,
|
||||
Entry::Form(253), Entry::Form(254), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2501,18 +2541,18 @@ pub static TWO_BYTE_F3: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Form(204), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Form(208), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(208), Entry::Form(212), Entry::Form(240), Entry::Form(244),
|
||||
Entry::Form(216), Entry::Form(220), Entry::Form(224), Entry::Form(228),
|
||||
Entry::Form(212), Entry::Form(216), Entry::Form(244), Entry::Form(248),
|
||||
Entry::Form(220), Entry::Form(224), Entry::Form(228), Entry::Form(232),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Form(90),
|
||||
Entry::Form(190), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(191), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(99), Entry::Form(91),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(100), Entry::Form(91),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2529,7 +2569,7 @@ pub static TWO_BYTE_F3: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(69), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(70), Entry::Form(71), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(232), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(236), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2538,7 +2578,7 @@ pub static TWO_BYTE_F3: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(246), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(250), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2552,60 +2592,60 @@ pub static TWO_BYTE_F2: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(97), Entry::Form(98), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(98), Entry::Form(99), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(255), Entry::Unsupported,
|
||||
Entry::Form(256), Entry::Form(257), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Form(209), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(213), Entry::Form(217), Entry::Form(245), Entry::Unsupported,
|
||||
Entry::Form(221), Entry::Form(225), Entry::Form(229), Entry::Form(233),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(192), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(237), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(251), Entry::Unsupported,
|
||||
Entry::Form(252), Entry::Form(253), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Form(205), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(209), Entry::Form(213), Entry::Form(241), Entry::Unsupported,
|
||||
Entry::Form(217), Entry::Form(221), Entry::Form(225), Entry::Form(229),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(191), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(233), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(247), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
@@ -199,15 +199,15 @@ fn reported_features_have_all_their_instructions_in_the_fixtures() {
|
||||
fn unreported_features_each_have_an_instruction_that_is_refused() {
|
||||
// (feature, leaf, result register, bit, an instruction of that feature)
|
||||
let witnesses: &[(&str, u32, usize, u32, &[u8])] = &[
|
||||
("FPU", 1, EDX, 0, &[0xD9, 0xE8]), // fld1
|
||||
("TSC", 1, EDX, 4, &[0x0F, 0x31]), // rdtsc
|
||||
("CX8", 1, EDX, 8, &[0x0F, 0xC7, 0x0E]), // cmpxchg8b [rsi]
|
||||
("CLFSH", 1, EDX, 19, &[0x0F, 0xAE, 0x3E]), // clflush [rsi]
|
||||
("MMX", 1, EDX, 23, &[0x0F, 0x77]), // emms
|
||||
("FXSR", 1, EDX, 24, &[0x0F, 0xAE, 0x06]), // fxsave [rsi]
|
||||
("SSE", 1, EDX, 25, &[0x0F, 0x52, 0xC1]), // rsqrtps xmm0, xmm1
|
||||
("SSE2", 1, EDX, 26, &[0x0F, 0xAE, 0xF0]), // mfence
|
||||
("SSE3", 1, ECX, 0, &[0xF2, 0x0F, 0x7C, 0xC1]), // haddps xmm0, xmm1
|
||||
("FPU", 1, EDX, 0, &[0xD9, 0xE8]), // fld1
|
||||
("TSC", 1, EDX, 4, &[0x0F, 0x31]), // rdtsc
|
||||
("CX8", 1, EDX, 8, &[0x0F, 0xC7, 0x0E]), // cmpxchg8b [rsi]
|
||||
("CLFSH", 1, EDX, 19, &[0x0F, 0xAE, 0x3E]), // clflush [rsi]
|
||||
("MMX", 1, EDX, 23, &[0x0F, 0x77]), // emms
|
||||
("FXSR", 1, EDX, 24, &[0x0F, 0xAE, 0x06]), // fxsave [rsi]
|
||||
("SSE", 1, EDX, 25, &[0x0F, 0x52, 0xC1]), // rsqrtps xmm0, xmm1
|
||||
("SSE2", 1, EDX, 26, &[0x66, 0x0F, 0xF7, 0xC1]), // maskmovdqu xmm0, xmm1
|
||||
("SSE3", 1, ECX, 0, &[0xF2, 0x0F, 0x7C, 0xC1]), // haddps xmm0, xmm1
|
||||
(
|
||||
"PCLMULQDQ",
|
||||
1,
|
||||
@@ -222,17 +222,17 @@ fn unreported_features_each_have_an_instruction_that_is_refused() {
|
||||
("SSE4.2", 1, ECX, 20, &[0xF2, 0x0F, 0x38, 0xF1, 0xC1]), // crc32 eax, ecx
|
||||
("MOVBE", 1, ECX, 22, &[0x0F, 0x38, 0xF0, 0x06]), // movbe eax, [rsi]
|
||||
("AESNI", 1, ECX, 25, &[0x66, 0x0F, 0x38, 0xDC, 0xC1]), // aesenc xmm0, xmm1
|
||||
("XSAVE", 1, ECX, 26, &[0x0F, 0x01, 0xD0]), // xgetbv
|
||||
("AVX", 1, ECX, 28, &[0xC5, 0xF4, 0x58, 0xC2]), // vaddps ymm0, ymm1, ymm2
|
||||
("XSAVE", 1, ECX, 26, &[0x0F, 0x01, 0xD0]), // xgetbv
|
||||
("AVX", 1, ECX, 28, &[0xC5, 0xF4, 0x58, 0xC2]), // vaddps ymm0, ymm1, ymm2
|
||||
("F16C", 1, ECX, 29, &[0xC4, 0xE2, 0x79, 0x13, 0xC1]), // vcvtph2ps xmm0, xmm1
|
||||
("RDRAND", 1, ECX, 30, &[0x0F, 0xC7, 0xF0]), // rdrand eax
|
||||
("RDRAND", 1, ECX, 30, &[0x0F, 0xC7, 0xF0]), // rdrand eax
|
||||
("BMI1", 7, EBX, 3, &[0xC4, 0xE2, 0x70, 0xF2, 0xC2]), // andn eax, ecx, edx
|
||||
("AVX2", 7, EBX, 5, &[0xC5, 0xF5, 0xFE, 0xC2]), // vpaddd ymm0, ymm1, ymm2
|
||||
("AVX2", 7, EBX, 5, &[0xC5, 0xF5, 0xFE, 0xC2]), // vpaddd ymm0, ymm1, ymm2
|
||||
("BMI2", 7, EBX, 8, &[0xC4, 0xE2, 0x73, 0xF6, 0xC2]), // mulx eax, ecx, edx
|
||||
("RDSEED", 7, EBX, 18, &[0x0F, 0xC7, 0xF8]), // rdseed eax
|
||||
("RDSEED", 7, EBX, 18, &[0x0F, 0xC7, 0xF8]), // rdseed eax
|
||||
("ADX", 7, EBX, 19, &[0x66, 0x0F, 0x38, 0xF6, 0xC1]), // adcx eax, ecx
|
||||
("SHA", 7, EBX, 29, &[0x0F, 0x38, 0xC9, 0xC1]), // sha1msg1 xmm0, xmm1
|
||||
("LAHF/SAHF", 0x8000_0001, ECX, 0, &[0x9F]), // lahf
|
||||
("SHA", 7, EBX, 29, &[0x0F, 0x38, 0xC9, 0xC1]), // sha1msg1 xmm0, xmm1
|
||||
("LAHF/SAHF", 0x8000_0001, ECX, 0, &[0x9F]), // lahf
|
||||
("PREFETCHW", 0x8000_0001, ECX, 8, &[0x0F, 0x0D, 0x0E]), // prefetchw [rsi]
|
||||
("SYSCALL/SYSRET", 0x8000_0001, EDX, 11, &[0x48, 0x0F, 0x07]), // sysretq
|
||||
("RDTSCP", 0x8000_0001, EDX, 27, &[0x0F, 0x01, 0xF9]), // rdtscp
|
||||
|
||||
@@ -1365,6 +1365,33 @@ mov_moffs8_store: rax=77 m0=00000000 => m0=00000077 f=*
|
||||
thirteen_byte_fs_add_imm32: rax=10 rbx=8 fs120=0000000000000000 => fs120=4433221100000000 f=cPazso
|
||||
";
|
||||
|
||||
/// Single-thread baseline for the fences (#199). Each engine completes every
|
||||
/// load and store of an instruction before the next instruction starts, so the
|
||||
/// cases only require that a fence changes nothing and that accesses on either
|
||||
/// side of it happen in program order. Nothing here involves a second thread.
|
||||
const FENCES: &str = r"
|
||||
@ mov [rdi], rax; mfence; mov rbx, [rdi]
|
||||
488907 0faef0 488b1f
|
||||
SDM 2B MFENCE
|
||||
mfence_store_is_visible_to_a_later_load: rdi=D rax=1122334455667788 m0=0000000000000000 => rbx=1122334455667788 m0=8877665544332211 f=*
|
||||
@ mov [rdi], rax; sfence; mov rbx, [rdi+8]
|
||||
488907 0faef8 488b5f08
|
||||
SDM 2B SFENCE
|
||||
sfence_after_a_store_keeps_other_memory: rdi=D rax=1 m0=0000000000000000 m8=aabbccddeeff0011 => rbx=1100ffeeddccbbaa m0=0100000000000000 f=*
|
||||
@ mov rbx, [rdi]; lfence; mov [rdi], rax
|
||||
488b1f 0faee8 488907
|
||||
SDM 2B LFENCE
|
||||
lfence_load_precedes_a_later_store: rdi=D rax=5 m0=0200000000000000 => rbx=2 m0=0500000000000000 f=*
|
||||
@ mfence; lfence; sfence
|
||||
0faef0 0faee8 0faef8
|
||||
SDM 2B MFENCE; 2B LFENCE; 2B SFENCE
|
||||
fences_change_no_register_or_flag: rax=1122334455667788 rbx=99aabbccddeeff00 => f=*
|
||||
@ .byte 0x0f,0xae,0xf5; .byte 0x0f,0xae,0xeb; .byte 0x0f,0xae,0xff
|
||||
0faef5 0faeeb 0faeff
|
||||
SDM 2B MFENCE; 2B LFENCE; 2B SFENCE (the r/m field is ignored)
|
||||
fences_ignore_the_rm_field: rax=1122334455667788 => f=*
|
||||
";
|
||||
|
||||
const MEMORY_FAULTS: &str = r"
|
||||
@ mov r8d, 1; add al, bl; mov rcx, [rsi]; mov r9d, 2
|
||||
41b801000000 00d8 !488b0e 41b902000000
|
||||
@@ -1505,7 +1532,7 @@ jump_to_unmapped_faults_at_target: rbx=U => rax=1 rip=U f=* ! PFX U
|
||||
jump_to_data_page_faults_at_target: rbx=D+40 => rip=D+40 f=* ! PFX D+40
|
||||
";
|
||||
|
||||
const DEFECT_STRADDLING_FAULT_ADDRESS: &str = r"
|
||||
const STRADDLING_FAULT_ADDRESS: &str = r"
|
||||
@ mov rcx, [rsi-4]
|
||||
!488b4efc
|
||||
SDM 3A 5.7 (the address with no translation); 3A 7.15 Interrupt 14
|
||||
@@ -2646,11 +2673,9 @@ const GROUPS: &[(&str, &str)] = &[
|
||||
("strings", STRINGS),
|
||||
("fs_gs", FS_GS),
|
||||
("decoding", DECODING),
|
||||
("fences", FENCES),
|
||||
("memory_faults", MEMORY_FAULTS),
|
||||
(
|
||||
"defect_straddling_fault_address",
|
||||
DEFECT_STRADDLING_FAULT_ADDRESS,
|
||||
),
|
||||
("straddling_fault_address", STRADDLING_FAULT_ADDRESS),
|
||||
("defect_noncanonical_address", DEFECT_NONCANONICAL_ADDRESS),
|
||||
("packed_integer_sse2", PACKED_INTEGER_SSE2),
|
||||
("packed_integer_beyond_sse2", PACKED_INTEGER_BEYOND_SSE2),
|
||||
@@ -2710,7 +2735,6 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("mov_moffs64_load", 0),
|
||||
("mov_moffs8_store", 0),
|
||||
("movddup_movsldup_movshdup", 0),
|
||||
("movdqa_movaps_aligned_store_and_load", 3),
|
||||
("mpsadbw", 0),
|
||||
("pabs_min_is_unchanged", 0),
|
||||
("packusdw", 0),
|
||||
@@ -3428,15 +3452,19 @@ fn decoding() {
|
||||
check_group(DECODING);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fences() {
|
||||
check_group(FENCES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_faults() {
|
||||
check_group(MEMORY_FAULTS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "known defect (#155): a page-crossing fault reports the start of the access"]
|
||||
fn defect_straddling_fault_address() {
|
||||
check_group(DEFECT_STRADDLING_FAULT_ADDRESS);
|
||||
fn straddling_fault_address() {
|
||||
check_group(STRADDLING_FAULT_ADDRESS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -96,10 +96,11 @@ fn crt_handlers_validate_memory_boundaries() {
|
||||
0x1008
|
||||
)))
|
||||
);
|
||||
// The destination 0x1005..0x1009 is mapped up to 0x1008.
|
||||
assert_eq!(
|
||||
call("memmove", 0x1005, 0x1000, 4, &mut memory),
|
||||
Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(
|
||||
0x1005
|
||||
0x1008
|
||||
)))
|
||||
);
|
||||
let mut bytes = [0; 8];
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Guest 4 KiB page boundaries on a host with larger pages (#175).
|
||||
//!
|
||||
//! Apple Silicon uses 16 KiB host pages, so four guest pages share one host
|
||||
//! page and host page protection cannot separate them. Guest memory is checked
|
||||
//! in software, byte by byte, and is never mapped with host protections. These
|
||||
//! tests lay 4 KiB guest pages across two spans of the detected host page size
|
||||
//! and require the same results at every guest page boundary, whether or not it
|
||||
//! is also a host page boundary.
|
||||
//!
|
||||
//! The expected fault address is the first byte, in address order, that the
|
||||
//! access may not touch: the linear address with no translation or without the
|
||||
//! needed right. This is the reading of the Intel SDM used by the page-fault
|
||||
//! cases in `cpu_known_answers.rs` (Volume 3A, Sections 5.7 and 7.15, Interrupt
|
||||
//! 14). Every expectation below is a literal address or a table written from
|
||||
//! that rule, not a value read back from the memory model. Nothing here was
|
||||
//! compared with x86 hardware.
|
||||
|
||||
use xenora_loader::services::sysinfo::HostCapabilities;
|
||||
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P};
|
||||
|
||||
const GUEST_PAGE: u64 = 0x1000;
|
||||
/// Aligned to every host page size up to 1 GiB.
|
||||
const BASE: u64 = 0x4000_0000;
|
||||
|
||||
fn host_page() -> u64 {
|
||||
let size = HostCapabilities::detect()
|
||||
.page_size
|
||||
.expect("the host reports a page size");
|
||||
assert_eq!(size % GUEST_PAGE, 0, "host page size {size:#x}");
|
||||
size
|
||||
}
|
||||
|
||||
/// Guest page boundaries strictly inside two host pages starting at `BASE`.
|
||||
/// On a 16 KiB host that is seven boundaries, one of them a host page boundary.
|
||||
fn boundaries() -> Vec<u64> {
|
||||
let pages = 2 * host_page() / GUEST_PAGE;
|
||||
(1..pages).map(|page| BASE + page * GUEST_PAGE).collect()
|
||||
}
|
||||
|
||||
fn unmapped(address: u64) -> MemoryError {
|
||||
MemoryError::UnmappedAddress(address)
|
||||
}
|
||||
|
||||
fn violation(address: u64, required: &'static str) -> MemoryError {
|
||||
MemoryError::PermissionViolation { address, required }
|
||||
}
|
||||
|
||||
/// The page below `boundary`, filled with 0x5a, and optionally the page above
|
||||
/// it, filled with 0xa5.
|
||||
fn pages_around(boundary: u64, below: P, above: Option<P>) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(boundary - GUEST_PAGE, 0x1000, below, &[0x5a; 0x1000])
|
||||
.unwrap();
|
||||
if let Some(above) = above {
|
||||
memory
|
||||
.map_region_with_data(boundary, 0x1000, above, &[0xa5; 0x1000])
|
||||
.unwrap();
|
||||
}
|
||||
memory
|
||||
}
|
||||
|
||||
/// The 16 bytes centred on `boundary`, read without permission checks.
|
||||
fn bytes_around(memory: &GuestMemory, boundary: u64) -> (u64, u64) {
|
||||
(
|
||||
memory.read_u64_bypass(boundary - 8).unwrap(),
|
||||
memory.read_u64_bypass(boundary).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
const BELOW: u64 = 0x5a5a_5a5a_5a5a_5a5a;
|
||||
const ABOVE: u64 = 0xa5a5_a5a5_a5a5_a5a5;
|
||||
|
||||
#[test]
|
||||
fn apple_silicon_host_pages_hold_four_guest_pages() {
|
||||
let size = host_page();
|
||||
if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
|
||||
assert_eq!(size, 0x4000);
|
||||
assert_eq!(boundaries().len(), 7);
|
||||
assert!(boundaries().contains(&(BASE + 0x4000)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_guest_page_in_a_host_page_keeps_its_own_permissions() {
|
||||
// (permissions, read allowed, write allowed, execute allowed)
|
||||
let kinds = [
|
||||
(P::READ_WRITE, true, true, false),
|
||||
(P::READ_ONLY, true, false, false),
|
||||
(P::NO_ACCESS, false, false, false),
|
||||
(P::READ_EXECUTE, true, false, true),
|
||||
];
|
||||
let pages = 2 * host_page() / GUEST_PAGE;
|
||||
let mut memory = GuestMemory::new();
|
||||
for page in 0..pages {
|
||||
let fill = [page as u8 + 1; 0x1000];
|
||||
let kind = kinds[page as usize % kinds.len()].0;
|
||||
memory
|
||||
.map_region_with_data(BASE + page * GUEST_PAGE, 0x1000, kind, &fill)
|
||||
.unwrap();
|
||||
}
|
||||
for page in 0..pages {
|
||||
let (_, read, write, execute) = kinds[page as usize % kinds.len()];
|
||||
let fill = page as u8 + 1;
|
||||
let first = BASE + page * GUEST_PAGE;
|
||||
for address in [first, first + 0xFFF] {
|
||||
let expected = |allowed, required| {
|
||||
if allowed {
|
||||
Ok(fill)
|
||||
} else {
|
||||
Err(violation(address, required))
|
||||
}
|
||||
};
|
||||
assert_eq!(memory.read_u8(address), expected(read, "read"));
|
||||
assert_eq!(
|
||||
memory.fetch_instruction_byte(address),
|
||||
expected(execute, "execute")
|
||||
);
|
||||
assert_eq!(
|
||||
memory.write_u8(address, fill),
|
||||
expected(write, "write").map(|_| ())
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(memory.read_u8(BASE - 1), Err(unmapped(BASE - 1)));
|
||||
let end = BASE + pages * GUEST_PAGE;
|
||||
assert_eq!(memory.read_u8(end), Err(unmapped(end)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn access_across_adjacent_guest_pages_lands_in_both() {
|
||||
for boundary in boundaries() {
|
||||
let mut memory = pages_around(boundary, P::READ_WRITE, Some(P::READ_WRITE));
|
||||
memory
|
||||
.write_u64(boundary - 3, 0x8877_6655_4433_2211)
|
||||
.unwrap();
|
||||
assert_eq!(memory.read_u64(boundary - 3), Ok(0x8877_6655_4433_2211));
|
||||
// Little endian: three bytes below the boundary, five above it.
|
||||
assert_eq!(
|
||||
bytes_around(&memory, boundary),
|
||||
(0x3322_115a_5a5a_5a5a, 0xa5a5_a588_7766_5544),
|
||||
"boundary {boundary:#x}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crossing_into_an_unmapped_page_faults_at_its_first_byte() {
|
||||
for boundary in boundaries() {
|
||||
let mut memory = pages_around(boundary, P::READ_WRITE, None);
|
||||
let fault = Err(unmapped(boundary));
|
||||
for back in 1..8u64 {
|
||||
let start = boundary - back;
|
||||
let context = format!("boundary {boundary:#x}, start -{back}");
|
||||
assert_eq!(memory.read_u64(start).map(|_| ()), fault, "{context}");
|
||||
assert_eq!(memory.write_u64(start, 0), fault, "{context}");
|
||||
assert_eq!(memory.write_u64_bypass(start, 0), fault, "{context}");
|
||||
assert_eq!(memory.read_u64_bypass(start).map(|_| ()), fault);
|
||||
}
|
||||
for (back, width) in [(1u64, 2usize), (3, 4), (15, 16), (1, 0x1001)] {
|
||||
let mut buffer = vec![0u8; width];
|
||||
assert_eq!(memory.read_bytes(boundary - back, &mut buffer), fault);
|
||||
assert_eq!(memory.write_bytes(boundary - back, &buffer), fault);
|
||||
}
|
||||
// The failed stores wrote nothing below the boundary, and the last
|
||||
// access that fits still succeeds.
|
||||
assert_eq!(memory.read_u64(boundary - 8), Ok(BELOW));
|
||||
// An access that does not touch the mapped page faults at its own
|
||||
// first byte.
|
||||
assert_eq!(memory.read_u64(boundary).map(|_| ()), fault);
|
||||
assert_eq!(
|
||||
memory.read_u64(boundary + 5).map(|_| ()),
|
||||
Err(unmapped(boundary + 5))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn starting_in_an_unmapped_page_faults_at_the_access_start() {
|
||||
for boundary in boundaries() {
|
||||
// Only the page above the boundary exists.
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(boundary, 0x1000, P::READ_WRITE, &[0xa5; 0x1000])
|
||||
.unwrap();
|
||||
for back in 1..8u64 {
|
||||
let start = boundary - back;
|
||||
assert_eq!(memory.read_u64(start).map(|_| ()), Err(unmapped(start)));
|
||||
assert_eq!(memory.write_u64(start, 0), Err(unmapped(start)));
|
||||
}
|
||||
assert_eq!(memory.read_u64(boundary), Ok(ABOVE));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crossing_into_a_page_without_the_right_faults_at_its_first_byte() {
|
||||
for boundary in boundaries() {
|
||||
// A store into a read-only page.
|
||||
let mut memory = pages_around(boundary, P::READ_WRITE, Some(P::READ_ONLY));
|
||||
for back in 1..8u64 {
|
||||
assert_eq!(
|
||||
memory.write_u64(boundary - back, 0),
|
||||
Err(violation(boundary, "write")),
|
||||
"boundary {boundary:#x}, start -{back}"
|
||||
);
|
||||
assert!(memory.read_u64(boundary - back).is_ok());
|
||||
}
|
||||
assert_eq!(bytes_around(&memory, boundary), (BELOW, ABOVE));
|
||||
|
||||
// A load from a page with no access.
|
||||
let memory = pages_around(boundary, P::READ_ONLY, Some(P::NO_ACCESS));
|
||||
for back in 1..8u64 {
|
||||
assert_eq!(
|
||||
memory.read_u64(boundary - back).map(|_| ()),
|
||||
Err(violation(boundary, "read")),
|
||||
"boundary {boundary:#x}, start -{back}"
|
||||
);
|
||||
}
|
||||
assert_eq!(memory.read_u64(boundary - 8), Ok(BELOW));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lowest_failing_byte_decides_the_fault() {
|
||||
for boundary in boundaries() {
|
||||
// Forbidden first page, unmapped second page: the first byte fails.
|
||||
let mut memory = pages_around(boundary, P::READ_ONLY, None);
|
||||
assert_eq!(
|
||||
memory.write_u64(boundary - 4, 0),
|
||||
Err(violation(boundary - 4, "write"))
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64(boundary - 4).map(|_| ()),
|
||||
Err(unmapped(boundary))
|
||||
);
|
||||
|
||||
// Writable, then read-only, then unmapped: a store over all three
|
||||
// stops at the read-only page, a load at the unmapped one.
|
||||
let mut memory = pages_around(boundary, P::READ_WRITE, Some(P::READ_ONLY));
|
||||
let mut buffer = vec![0u8; 0x1008];
|
||||
assert_eq!(
|
||||
memory.write_bytes(boundary - 4, &buffer),
|
||||
Err(violation(boundary, "write"))
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_bytes(boundary - 4, &mut buffer),
|
||||
Err(unmapped(boundary + GUEST_PAGE))
|
||||
);
|
||||
assert_eq!(bytes_around(&memory, boundary), (BELOW, ABOVE));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_highest_guest_page_boundaries_do_not_wrap() {
|
||||
// The last page that can be mapped ends one page below 2^64.
|
||||
let top = u64::MAX - 0xFFF; // 0xffff_ffff_ffff_f000
|
||||
let mut memory = pages_around(top, P::READ_WRITE, None);
|
||||
assert_eq!(
|
||||
memory.map_region(top, 0x1000, P::READ_WRITE),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(memory.read_u64(top - 8), Ok(BELOW));
|
||||
assert_eq!(memory.read_u64(top - 4).map(|_| ()), Err(unmapped(top)));
|
||||
assert_eq!(memory.write_u64(top - 4, 0), Err(unmapped(top)));
|
||||
// An access whose end passes 2^64 is an overflow wherever it starts.
|
||||
assert_eq!(memory.read_u64(u64::MAX - 6), Err(MemoryError::Overflow));
|
||||
assert_eq!(
|
||||
memory.write_u64(u64::MAX - 6, 0),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(memory.read_u64(top - 8), Ok(BELOW));
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
//! Expected behavior follows x86-64 data access rules: an access is valid when
|
||||
//! every byte it touches is mapped with the required permission, whether or not
|
||||
//! it is aligned or crosses into an adjacent mapping. A faulting access changes
|
||||
//! nothing.
|
||||
//! nothing and reports the lowest address it may not touch (#175).
|
||||
|
||||
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P};
|
||||
|
||||
@@ -56,7 +56,7 @@ fn region_end_is_exclusive() {
|
||||
lone.map_region(A, 0x1000, P::READ_ONLY).unwrap();
|
||||
assert_eq!(
|
||||
lone.read_u32(A + 0xFFD),
|
||||
Err(MemoryError::UnmappedAddress(A + 0xFFD))
|
||||
Err(MemoryError::UnmappedAddress(A + 0x1000))
|
||||
);
|
||||
assert_eq!(
|
||||
lone.read_u8(A - 1),
|
||||
@@ -90,7 +90,7 @@ fn spanning_into_a_gap_fails_without_partial_write() {
|
||||
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
|
||||
assert_eq!(
|
||||
m.write_u64(A + 0xFFC, u64::MAX),
|
||||
Err(MemoryError::UnmappedAddress(A + 0xFFC))
|
||||
Err(MemoryError::UnmappedAddress(A + 0x1000))
|
||||
);
|
||||
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x1111_1111));
|
||||
}
|
||||
@@ -101,7 +101,7 @@ fn spanning_into_a_forbidden_region_fails_atomically() {
|
||||
assert_eq!(
|
||||
m.write_u64(A + 0xFFC, u64::MAX),
|
||||
Err(MemoryError::PermissionViolation {
|
||||
address: A + 0xFFC,
|
||||
address: A + 0x1000,
|
||||
required: "write"
|
||||
})
|
||||
);
|
||||
@@ -123,7 +123,7 @@ fn loader_bypass_ignores_permissions_but_not_mapping() {
|
||||
assert_eq!(m.read_u32(A), Ok(7));
|
||||
assert_eq!(
|
||||
m.write_u64_bypass(A + 0x1FFC, 0),
|
||||
Err(MemoryError::UnmappedAddress(A + 0x1FFC))
|
||||
Err(MemoryError::UnmappedAddress(A + 0x2000))
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -158,7 +158,7 @@ fn probe_distinguishes_aliases_from_unavailable_services() {
|
||||
|
||||
for (index, (rva, name)) in [
|
||||
(0x1180u64, "GetCurrentProcess"),
|
||||
(0x11a0u64, "CreateThread"),
|
||||
(0x11a0u64, "TerminateProcess"),
|
||||
(0x11c0u64, "getcurrentprocess"),
|
||||
]
|
||||
.into_iter()
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Synthetic guest calls through the standard import registry. Expectations use
|
||||
//! Microsoft's public CloseHandle, DuplicateHandle and synchronization contracts:
|
||||
//! https://learn.microsoft.com/windows/win32/api/handleapi/nf-handleapi-closehandle
|
||||
//! https://learn.microsoft.com/windows/win32/api/handleapi/nf-handleapi-duplicatehandle
|
||||
//! https://learn.microsoft.com/windows/win32/sync/synchronization-object-security-and-access-rights
|
||||
//!
|
||||
//! Capacity, rejected rights escalation and failed-output nonmutation are Xenora
|
||||
//! subset policies, not claims about every Windows handle implementation. The
|
||||
//! current runtime avoids stale aliases with increasing IDs, not generations.
|
||||
|
||||
mod support;
|
||||
|
||||
use support::{Guest, SCRATCH, SCRATCH_LEN};
|
||||
use xenora_loader::memory::MemoryPermissions;
|
||||
|
||||
const IMPORTS: &[(&str, &str)] = &[
|
||||
("kernel32.dll", "GetLastError"),
|
||||
("kernel32.dll", "CreateEventW"),
|
||||
("kernel32.dll", "CreateSemaphoreW"),
|
||||
("kernel32.dll", "SetEvent"),
|
||||
("kernel32.dll", "ReleaseSemaphore"),
|
||||
("kernel32.dll", "WaitForSingleObject"),
|
||||
("kernel32.dll", "CloseHandle"),
|
||||
("kernel32.dll", "DuplicateHandle"),
|
||||
("kernel32.dll", "GetCurrentThread"),
|
||||
("kernel32.dll", "GetCurrentThreadId"),
|
||||
("kernel32.dll", "GetThreadId"),
|
||||
];
|
||||
|
||||
const CURRENT_PROCESS: u64 = u64::MAX;
|
||||
const SAME_ACCESS: u64 = 2;
|
||||
const MODIFY: u64 = 2;
|
||||
const SYNCHRONIZE: u64 = 0x0010_0000;
|
||||
const WAIT_TIMEOUT: u64 = 258;
|
||||
const WAIT_FAILED: u64 = u32::MAX as u64;
|
||||
const INVALID_HANDLE: u64 = 6;
|
||||
const ACCESS_DENIED: u64 = 5;
|
||||
const NOACCESS: u64 = 998;
|
||||
const SENTINEL: u64 = 0xABCD_1234_5678_90EF;
|
||||
// Xenora's bounded object table, not a Windows limit.
|
||||
const CAPACITY: usize = 1024;
|
||||
|
||||
fn event(guest: &mut Guest) -> u64 {
|
||||
let handle = guest.call("CreateEventW", &[0, 0, 0, 0]);
|
||||
assert_ne!(handle, 0);
|
||||
handle
|
||||
}
|
||||
|
||||
fn duplicate(guest: &mut Guest, source: u64, output: u64, rights: u64, options: u64) -> u64 {
|
||||
guest.call(
|
||||
"DuplicateHandle",
|
||||
&[
|
||||
CURRENT_PROCESS,
|
||||
source,
|
||||
CURRENT_PROCESS,
|
||||
output,
|
||||
rights,
|
||||
0,
|
||||
options,
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn copy(guest: &mut Guest, source: u64, rights: u64, options: u64) -> u64 {
|
||||
guest.memory.write_u64(SCRATCH, SENTINEL).unwrap();
|
||||
assert_eq!(duplicate(guest, source, SCRATCH, rights, options), 1);
|
||||
let handle = guest.u64_at(SCRATCH);
|
||||
assert_ne!(handle, 0);
|
||||
assert_ne!(handle, source);
|
||||
assert_ne!(handle, SENTINEL);
|
||||
handle
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reclaimed_capacity_never_revives_closed_handles() {
|
||||
let mut guest = Guest::new(IMPORTS, &[]);
|
||||
let handles: Vec<_> = (0..CAPACITY).map(|_| event(&mut guest)).collect();
|
||||
assert_eq!(guest.call("CreateEventW", &[0, 0, 0, 0]), 0);
|
||||
assert_eq!(guest.error(), 8); // ERROR_NOT_ENOUGH_MEMORY
|
||||
|
||||
// Release one slot at a time while the table stays otherwise full.
|
||||
for old in handles {
|
||||
assert_eq!(guest.call("CloseHandle", &[old]), 1);
|
||||
let replacement = event(&mut guest);
|
||||
assert_ne!(replacement, old);
|
||||
assert_eq!(guest.call("SetEvent", &[old]), 0);
|
||||
assert_eq!(guest.error(), INVALID_HANDLE);
|
||||
assert_eq!(guest.call("CloseHandle", &[old]), 0);
|
||||
assert_eq!(guest.error(), INVALID_HANDLE);
|
||||
// Neither stale operation may signal or destroy the replacement.
|
||||
assert_eq!(
|
||||
guest.call("WaitForSingleObject", &[replacement, 0]),
|
||||
WAIT_TIMEOUT
|
||||
);
|
||||
assert_eq!(guest.call("SetEvent", &[replacement]), 1);
|
||||
assert_eq!(guest.call("WaitForSingleObject", &[replacement, 0]), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicates_share_signal_state_but_keep_independent_rights_and_lifetimes() {
|
||||
let mut guest = Guest::new(IMPORTS, &[]);
|
||||
let source = event(&mut guest);
|
||||
let waiter = copy(&mut guest, source, SYNCHRONIZE, 0);
|
||||
let setter = copy(&mut guest, source, MODIFY, 0);
|
||||
|
||||
assert_eq!(guest.call("SetEvent", &[waiter]), 0);
|
||||
assert_eq!(guest.error(), ACCESS_DENIED);
|
||||
assert_eq!(
|
||||
guest.call("WaitForSingleObject", &[source, 0]),
|
||||
WAIT_TIMEOUT
|
||||
);
|
||||
assert_eq!(guest.call("SetEvent", &[setter]), 1);
|
||||
assert_eq!(guest.call("WaitForSingleObject", &[setter, 0]), WAIT_FAILED);
|
||||
assert_eq!(guest.error(), ACCESS_DENIED);
|
||||
// A denied wait must not consume the auto-reset event's signal.
|
||||
assert_eq!(guest.call("WaitForSingleObject", &[waiter, 0]), 0);
|
||||
assert_eq!(
|
||||
guest.call("WaitForSingleObject", &[source, 0]),
|
||||
WAIT_TIMEOUT
|
||||
);
|
||||
|
||||
assert_eq!(guest.call("CloseHandle", &[source]), 1);
|
||||
assert_eq!(guest.call("SetEvent", &[setter]), 1);
|
||||
assert_eq!(guest.call("WaitForSingleObject", &[waiter, 0]), 0);
|
||||
// SAME_ACCESS ignores desired access, and must retain the reduced rights.
|
||||
let second_waiter = copy(&mut guest, waiter, u64::MAX, SAME_ACCESS);
|
||||
assert_eq!(guest.call("CloseHandle", &[waiter]), 1);
|
||||
assert_eq!(guest.call("SetEvent", &[second_waiter]), 0);
|
||||
assert_eq!(guest.error(), ACCESS_DENIED);
|
||||
assert_eq!(guest.call("SetEvent", &[setter]), 1);
|
||||
assert_eq!(guest.call("CloseHandle", &[setter]), 1);
|
||||
assert_eq!(guest.call("WaitForSingleObject", &[second_waiter, 0]), 0);
|
||||
assert_eq!(
|
||||
guest.call("WaitForSingleObject", &[second_waiter, 0]),
|
||||
WAIT_TIMEOUT
|
||||
);
|
||||
assert_eq!(guest.call("CloseHandle", &[second_waiter]), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_duplicate_outputs_leave_memory_source_and_capacity_unchanged() {
|
||||
let mut guest = Guest::new(IMPORTS, &[]);
|
||||
let source = event(&mut guest);
|
||||
let readonly = 0x6_0000;
|
||||
guest
|
||||
.memory
|
||||
.map_region(readonly, 8, MemoryPermissions::READ_ONLY)
|
||||
.unwrap();
|
||||
guest
|
||||
.memory
|
||||
.write_u64(SCRATCH + SCRATCH_LEN - 8, SENTINEL)
|
||||
.unwrap();
|
||||
assert_eq!(guest.call("SetEvent", &[source]), 1);
|
||||
|
||||
for output in [0, readonly, 0xDEAD_0000, SCRATCH + SCRATCH_LEN - 4] {
|
||||
// Repeated failures must not fill the table with unreachable duplicates.
|
||||
for _ in 0..CAPACITY {
|
||||
assert_eq!(duplicate(&mut guest, source, output, 0, SAME_ACCESS), 0);
|
||||
assert_eq!(guest.error(), NOACCESS);
|
||||
}
|
||||
}
|
||||
assert_eq!(guest.u64_at(readonly), 0);
|
||||
assert_eq!(guest.u64_at(SCRATCH + SCRATCH_LEN - 8), SENTINEL);
|
||||
assert_eq!(guest.call("WaitForSingleObject", &[source, 0]), 0);
|
||||
assert_eq!(
|
||||
guest.call("WaitForSingleObject", &[source, 0]),
|
||||
WAIT_TIMEOUT
|
||||
);
|
||||
// All remaining slots must still be available after the failed calls.
|
||||
for _ in 1..CAPACITY {
|
||||
event(&mut guest);
|
||||
}
|
||||
assert_eq!(guest.call("CreateEventW", &[0, 0, 0, 0]), 0);
|
||||
assert_eq!(guest.error(), 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_types_and_rights_escalation_preserve_objects_and_output() {
|
||||
let mut guest = Guest::new(IMPORTS, &[]);
|
||||
let source = event(&mut guest);
|
||||
let semaphore = guest.call("CreateSemaphoreW", &[0, 1, 2, 0]);
|
||||
assert_ne!(semaphore, 0);
|
||||
assert_eq!(guest.call("SetEvent", &[semaphore]), 0);
|
||||
assert_eq!(guest.error(), INVALID_HANDLE);
|
||||
assert_eq!(guest.call("ReleaseSemaphore", &[source, 1, 0]), 0);
|
||||
assert_eq!(guest.error(), INVALID_HANDLE);
|
||||
for handle in [source, semaphore] {
|
||||
assert_eq!(guest.call("GetThreadId", &[handle]), 0);
|
||||
assert_eq!(guest.error(), INVALID_HANDLE);
|
||||
}
|
||||
assert_eq!(guest.call("WaitForSingleObject", &[semaphore, 0]), 0);
|
||||
assert_eq!(
|
||||
guest.call("WaitForSingleObject", &[semaphore, 0]),
|
||||
WAIT_TIMEOUT
|
||||
);
|
||||
assert_eq!(
|
||||
guest.call("WaitForSingleObject", &[source, 0]),
|
||||
WAIT_TIMEOUT
|
||||
);
|
||||
|
||||
let waiter = copy(&mut guest, source, SYNCHRONIZE, 0);
|
||||
guest.memory.write_u64(SCRATCH, SENTINEL).unwrap();
|
||||
assert_eq!(duplicate(&mut guest, waiter, SCRATCH, MODIFY, 0), 0);
|
||||
assert_eq!(guest.error(), ACCESS_DENIED);
|
||||
assert_eq!(guest.u64_at(SCRATCH), SENTINEL);
|
||||
assert_eq!(guest.call("SetEvent", &[source]), 1);
|
||||
assert_eq!(guest.call("WaitForSingleObject", &[waiter, 0]), 0);
|
||||
assert_eq!(guest.call("CloseHandle", &[waiter]), 1);
|
||||
assert_eq!(duplicate(&mut guest, waiter, SCRATCH, 0, SAME_ACCESS), 0);
|
||||
assert_eq!(guest.error(), INVALID_HANDLE);
|
||||
assert_eq!(guest.u64_at(SCRATCH), SENTINEL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_pseudo_handle_survives_real_duplicate_closure() {
|
||||
let mut guest = Guest::new(IMPORTS, &[]);
|
||||
let pseudo = guest.call("GetCurrentThread", &[]);
|
||||
let id = guest.call("GetCurrentThreadId", &[]);
|
||||
let first = copy(&mut guest, pseudo, 0x0800, 0); // THREAD_QUERY_LIMITED_INFORMATION
|
||||
assert_eq!(guest.call("GetThreadId", &[first]), id);
|
||||
assert_eq!(guest.call("CloseHandle", &[first]), 1);
|
||||
let second = copy(&mut guest, pseudo, 0x0800, 0);
|
||||
assert_ne!(first, second);
|
||||
assert_eq!(guest.call("GetThreadId", &[first]), 0);
|
||||
assert_eq!(guest.error(), INVALID_HANDLE);
|
||||
assert_eq!(guest.call("GetThreadId", &[second]), id);
|
||||
assert_eq!(guest.call("GetThreadId", &[pseudo]), id);
|
||||
assert_eq!(guest.call("CloseHandle", &[second]), 1);
|
||||
assert_eq!(guest.call("GetThreadId", &[pseudo]), id);
|
||||
}
|
||||
@@ -0,0 +1,933 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Guest thread scheduler tests.
|
||||
//!
|
||||
//! The workloads are original C programs compiled for x86-64 Windows (see
|
||||
//! `threads/compile.py`), bound through a real import table and executed as
|
||||
//! translated guest code. Expected values are computed here or stated by the
|
||||
//! public Win32 documentation, not taken from the scheduler.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Register};
|
||||
use xenora_loader::dbt::{DbtEngine, DbtMetrics};
|
||||
use xenora_loader::imports::ImportRegistry;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::pe::ParsedPe;
|
||||
use xenora_loader::scheduler::{DEFAULT_QUANTUM, Outcome, ScheduleReport, Scheduler};
|
||||
use xenora_loader::services::{Clock, MockClock, ServicesState, register_standard_services};
|
||||
|
||||
const BASE: u64 = 0x1_4000_0000;
|
||||
const TEXT_RVA: u32 = 0x1000;
|
||||
const TEXT_RAW: usize = 0x200;
|
||||
const TEXT_LEN: usize = 0x4000;
|
||||
const IDATA_RVA: u32 = 0x8000;
|
||||
const IDATA_RAW: usize = TEXT_RAW + TEXT_LEN;
|
||||
const IDATA_LEN: usize = 0x2000;
|
||||
const STACK: u64 = 0x8_0000;
|
||||
const STACK_LEN: usize = 0x1_0000;
|
||||
const TEB: u64 = 0x7_0000;
|
||||
const SHARED: u64 = 0x5_0000;
|
||||
const COUNTER: u64 = SHARED + 256;
|
||||
/// First guest thread slot: guard page, stack, guard page, TEB.
|
||||
const FIRST_SLOT: u64 = 0x6_0000_0000;
|
||||
const BUDGET: usize = 20_000_000;
|
||||
const MAIN_ID: u32 = 0x4104;
|
||||
/// Host services of the test programs: advance the clock by RCX milliseconds,
|
||||
/// and try to run a second scheduler.
|
||||
const ADVANCE: u64 = 0x6_0000;
|
||||
const NESTED: u64 = 0x6_0010;
|
||||
|
||||
fn return_to_guest(cpu: &mut CpuState, memory: &mut GuestMemory) -> Result<(), ExitReason> {
|
||||
let rsp = cpu.get(Register::Rsp);
|
||||
cpu.rip = memory.read_u64(rsp).map_err(ExitReason::MemoryFault)?;
|
||||
cpu.set(Register::Rsp, rsp + 8);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Program {
|
||||
code: Vec<u8>,
|
||||
entries: BTreeMap<&'static str, usize>,
|
||||
imports: Vec<(&'static str, usize)>,
|
||||
}
|
||||
|
||||
fn program() -> Program {
|
||||
let mut program = Program {
|
||||
code: Vec::new(),
|
||||
entries: BTreeMap::new(),
|
||||
imports: Vec::new(),
|
||||
};
|
||||
for line in include_str!("threads/program.txt").lines() {
|
||||
let parts: Vec<&str> = line.split(' ').collect();
|
||||
match parts[0] {
|
||||
"entry" => {
|
||||
program.entries.insert(parts[1], parts[2].parse().unwrap());
|
||||
}
|
||||
"import" => program.imports.push((parts[1], parts[2].parse().unwrap())),
|
||||
_ => program.code.extend(
|
||||
(0..parts[1].len())
|
||||
.step_by(2)
|
||||
.map(|at| u8::from_str_radix(&parts[1][at..at + 2], 16).unwrap()),
|
||||
),
|
||||
}
|
||||
}
|
||||
program
|
||||
}
|
||||
|
||||
/// Build a PE image whose entry point is `call main; hlt`.
|
||||
fn image(main: &str) -> Vec<u8> {
|
||||
let program = program();
|
||||
let mut pe = vec![0u8; IDATA_RAW + IDATA_LEN];
|
||||
fn put(pe: &mut [u8], at: usize, bytes: &[u8]) {
|
||||
pe[at..at + bytes.len()].copy_from_slice(bytes);
|
||||
}
|
||||
let start = program.code.len().next_multiple_of(16);
|
||||
assert!(start + 16 <= TEXT_LEN);
|
||||
put(&mut pe, 0, b"MZ");
|
||||
put(&mut pe, 0x3C, &0x80u32.to_le_bytes());
|
||||
put(&mut pe, 0x80, b"PE\0\0");
|
||||
put(&mut pe, 0x84, &0x8664u16.to_le_bytes());
|
||||
put(&mut pe, 0x86, &2u16.to_le_bytes());
|
||||
put(&mut pe, 0x94, &240u16.to_le_bytes());
|
||||
let optional = 0x98;
|
||||
put(&mut pe, optional, &0x20Bu16.to_le_bytes());
|
||||
put(
|
||||
&mut pe,
|
||||
optional + 16,
|
||||
&(TEXT_RVA + start as u32).to_le_bytes(),
|
||||
);
|
||||
put(&mut pe, optional + 24, &BASE.to_le_bytes());
|
||||
put(&mut pe, optional + 32, &0x1000u32.to_le_bytes());
|
||||
put(&mut pe, optional + 36, &0x200u32.to_le_bytes());
|
||||
put(&mut pe, optional + 56, &0x10000u32.to_le_bytes());
|
||||
put(&mut pe, optional + 60, &0x200u32.to_le_bytes());
|
||||
put(&mut pe, optional + 108, &16u32.to_le_bytes());
|
||||
put(&mut pe, optional + 120, &IDATA_RVA.to_le_bytes());
|
||||
put(&mut pe, optional + 124, &0x100u32.to_le_bytes());
|
||||
for (index, (name, rva, raw, len, flags)) in [
|
||||
(b".text", TEXT_RVA, TEXT_RAW, TEXT_LEN, 0x6000_0020u32),
|
||||
(b".idat", IDATA_RVA, IDATA_RAW, IDATA_LEN, 0xC000_0040),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let section = optional + 240 + 40 * index;
|
||||
put(&mut pe, section, name);
|
||||
put(&mut pe, section + 8, &(len as u32).to_le_bytes());
|
||||
put(&mut pe, section + 12, &rva.to_le_bytes());
|
||||
put(&mut pe, section + 16, &(len as u32).to_le_bytes());
|
||||
put(&mut pe, section + 20, &(raw as u32).to_le_bytes());
|
||||
put(&mut pe, section + 36, &flags.to_le_bytes());
|
||||
}
|
||||
put(&mut pe, TEXT_RAW, &program.code);
|
||||
let displacement = program.entries[main] as i32 - (start as i32 + 5);
|
||||
put(&mut pe, TEXT_RAW + start, &[0xE8]);
|
||||
put(&mut pe, TEXT_RAW + start + 1, &displacement.to_le_bytes());
|
||||
put(&mut pe, TEXT_RAW + start + 5, &[0xF4]);
|
||||
|
||||
let file = |rva: u32| IDATA_RAW + (rva - IDATA_RVA) as usize;
|
||||
let mut names: Vec<&str> = program.imports.iter().map(|import| import.0).collect();
|
||||
names.sort_unstable();
|
||||
names.dedup();
|
||||
let mut next = IDATA_RVA + 20 * (names.len() as u32 + 1);
|
||||
let mut take = |len: usize| {
|
||||
let rva = next;
|
||||
next = (next + len as u32 + 7) & !7;
|
||||
rva
|
||||
};
|
||||
let mut slots = BTreeMap::new();
|
||||
for (index, name) in names.iter().enumerate() {
|
||||
let module: &[u8] = if *name == "_errno" {
|
||||
b"api-ms-win-crt-runtime-l1-1-0.dll"
|
||||
} else {
|
||||
b"KERNEL32.dll"
|
||||
};
|
||||
let module_rva = take(module.len() + 1);
|
||||
put(&mut pe, file(module_rva), module);
|
||||
let hint = take(name.len() + 3);
|
||||
put(&mut pe, file(hint) + 2, name.as_bytes());
|
||||
let (lookup, slot) = (take(16), take(16));
|
||||
put(&mut pe, file(lookup), &u64::from(hint).to_le_bytes());
|
||||
put(&mut pe, file(slot), &u64::from(hint).to_le_bytes());
|
||||
let descriptor = file(IDATA_RVA) + 20 * index;
|
||||
put(&mut pe, descriptor, &lookup.to_le_bytes());
|
||||
put(&mut pe, descriptor + 12, &module_rva.to_le_bytes());
|
||||
put(&mut pe, descriptor + 16, &slot.to_le_bytes());
|
||||
slots.insert(*name, slot);
|
||||
}
|
||||
for (name, offset) in &program.imports {
|
||||
let displacement = slots[name].wrapping_sub(TEXT_RVA + *offset as u32 + 4);
|
||||
put(&mut pe, TEXT_RAW + offset, &displacement.to_le_bytes());
|
||||
}
|
||||
pe
|
||||
}
|
||||
|
||||
struct Run {
|
||||
report: ScheduleReport,
|
||||
memory: GuestMemory,
|
||||
clock: Arc<MockClock>,
|
||||
metrics: DbtMetrics,
|
||||
state: Arc<ServicesState>,
|
||||
}
|
||||
|
||||
impl Run {
|
||||
fn out(&self, index: u64) -> u64 {
|
||||
self.memory.read_u64(SHARED + 8 * index).unwrap()
|
||||
}
|
||||
|
||||
fn outs(&self, count: u64) -> Vec<u64> {
|
||||
(0..count).map(|index| self.out(index)).collect()
|
||||
}
|
||||
|
||||
fn halted(self) -> Self {
|
||||
assert_eq!(self.report.outcome, Outcome::Halted);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
struct Guest {
|
||||
memory: GuestMemory,
|
||||
engine: DbtEngine,
|
||||
cpu: CpuState,
|
||||
state: Arc<ServicesState>,
|
||||
clock: Arc<MockClock>,
|
||||
}
|
||||
|
||||
fn guest(main: &str) -> Guest {
|
||||
let bytes = image(main);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
let mut loaded = pe.load_into_memory(&bytes).unwrap();
|
||||
let memory = &mut loaded.memory;
|
||||
for (base, len) in [(SHARED, 0x1000), (STACK, STACK_LEN), (TEB, 0x2000)] {
|
||||
memory
|
||||
.map_region(base, len, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
}
|
||||
let clock = Arc::new(MockClock::new(1_000_000));
|
||||
let state = Arc::new(ServicesState::new(clock.clone()));
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, Arc::clone(&state));
|
||||
registry.bind_imports(&pe, &bytes, BASE, memory).unwrap();
|
||||
let mut engine = DbtEngine::new(1024 * 1024).unwrap();
|
||||
engine.set_import_registry(registry);
|
||||
let time = clock.clone();
|
||||
engine.register_service(ADVANCE, move |cpu, memory| {
|
||||
time.advance(cpu.get(Register::Rcx) * 10_000);
|
||||
return_to_guest(cpu, memory)
|
||||
});
|
||||
let mut cpu = CpuState::new(loaded.entry_point, STACK + STACK_LEN as u64 - 0x100);
|
||||
cpu.gs_base = TEB;
|
||||
Guest {
|
||||
memory: loaded.memory,
|
||||
engine,
|
||||
cpu,
|
||||
state,
|
||||
clock,
|
||||
}
|
||||
}
|
||||
|
||||
fn run_with(main: &str, quantum: usize, budget: usize) -> Run {
|
||||
let mut guest = guest(main);
|
||||
let report = Scheduler::new(Arc::clone(&guest.state), quantum)
|
||||
.run(&mut guest.engine, &mut guest.memory, &guest.cpu, budget)
|
||||
.unwrap();
|
||||
Run {
|
||||
report,
|
||||
memory: guest.memory,
|
||||
clock: guest.clock,
|
||||
metrics: guest.engine.metrics,
|
||||
state: guest.state,
|
||||
}
|
||||
}
|
||||
|
||||
fn run(main: &str) -> Run {
|
||||
run_with(main, DEFAULT_QUANTUM, BUDGET)
|
||||
}
|
||||
|
||||
const QUANTA: [usize; 6] = [1, 2, 7, 64, 1024, 1_000_000];
|
||||
const FAILED: u64 = u32::MAX as u64;
|
||||
|
||||
fn fibonacci(n: u32) -> u64 {
|
||||
(0..n)
|
||||
.fold((0u64, 1u64), |(a, b), _| (b, a.wrapping_add(b)))
|
||||
.0
|
||||
}
|
||||
|
||||
fn collatz_steps(mut value: u64) -> u64 {
|
||||
let mut steps = 0;
|
||||
while value != 1 {
|
||||
value = if value % 2 == 1 {
|
||||
3 * value + 1
|
||||
} else {
|
||||
value / 2
|
||||
};
|
||||
steps += 1;
|
||||
}
|
||||
steps
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threads_run_independent_functions_and_report_exit_codes() {
|
||||
for quantum in QUANTA {
|
||||
let run = run_with("main_independent", quantum, BUDGET).halted();
|
||||
assert_eq!(
|
||||
run.outs(7),
|
||||
[fibonacci(80), collatz_steps(97), 0, 11, 22, 1, 1],
|
||||
"quantum {quantum}"
|
||||
);
|
||||
assert_eq!(run.report.peak_threads, 3);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn atomic_and_locked_counters_lose_no_update() {
|
||||
for quantum in QUANTA {
|
||||
for main in ["main_atomic", "main_mutex"] {
|
||||
let run = run_with(main, quantum, BUDGET).halted();
|
||||
assert_eq!(run.outs(2), [0, 800], "{main} quantum {quantum}");
|
||||
assert_eq!(run.report.peak_threads, 5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsynchronized_counters_do_lose_updates() {
|
||||
// Shows that the threads really interleave: the locked version above has
|
||||
// the same read, yield, write sequence.
|
||||
let run = run("main_racy").halted();
|
||||
assert!(run.out(1) < 800, "{}", run.out(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blocked_thread_resumes_when_it_is_signaled() {
|
||||
let expected = (1..=50u64).fold(0u64, |sum, value| sum.wrapping_mul(31).wrapping_add(value));
|
||||
for quantum in QUANTA {
|
||||
let run = run_with("main_producer", quantum, BUDGET).halted();
|
||||
assert_eq!(run.outs(2), [expected, 1], "quantum {quantum}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_signal_releases_the_oldest_waiter_only() {
|
||||
for quantum in [64, 1024, 1_000_000] {
|
||||
let run = run_with("main_fifo", quantum, BUDGET).halted();
|
||||
// Nobody ran before the signal; the setter cannot take it back.
|
||||
assert_eq!(
|
||||
[run.out(8), run.out(9), run.out(10)],
|
||||
[0, 258, 1],
|
||||
"quantum {quantum}"
|
||||
);
|
||||
assert_eq!(run.outs(4), [10, 11, 12, 13], "quantum {quantum}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timeouts_follow_the_clock_exactly() {
|
||||
let run = run("main_timeout").halted();
|
||||
assert_eq!(run.outs(3), [258, 258, 0]);
|
||||
// 250 ms in 100 ns units, and no further sleep.
|
||||
assert_eq!(run.clock.performance_count(), 2_500_000);
|
||||
let run = run_with("main_signal_before_timeout", 1024, BUDGET).halted();
|
||||
assert_eq!(run.outs(2), [0, 258]);
|
||||
assert_eq!(run.clock.performance_count(), 400_000 + 1_000_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_local_state_is_isolated() {
|
||||
for quantum in QUANTA {
|
||||
let run = run_with("main_isolated", quantum, BUDGET).halted();
|
||||
assert_eq!(
|
||||
run.outs(7),
|
||||
[1, 1, 1, 1, 1234, 0xAAAA, 1],
|
||||
"quantum {quantum}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_and_termination_follow_the_documented_results() {
|
||||
let run = run("main_lifecycle").halted();
|
||||
assert_eq!(
|
||||
run.outs(16),
|
||||
[
|
||||
0, 0xC0DE, // ExitThread
|
||||
259, 258, // STILL_ACTIVE, WAIT_TIMEOUT
|
||||
1, 0, 77, // TerminateThread, signaled, its code
|
||||
0, 5, 77, // already terminated: ERROR_ACCESS_DENIED, code kept
|
||||
1, FAILED, 6, // closed: WAIT_FAILED, ERROR_INVALID_HANDLE
|
||||
0, 0, 0, // OpenThread fails; nothing ran after ExitThread
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suspended_threads_do_not_run() {
|
||||
let run = run("main_suspend");
|
||||
// The program ends by suspending itself, with nobody left to resume it.
|
||||
assert_eq!(
|
||||
run.report.outcome,
|
||||
Outcome::Deadlock {
|
||||
blocked: vec![],
|
||||
suspended: vec![MAIN_ID]
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
run.outs(15),
|
||||
[
|
||||
0, 1, 2, // created suspended, then suspended again, then resumed once
|
||||
258, 1, 0, 1, // still suspended; resumed; ended; ran
|
||||
FAILED, 5, // an ended thread cannot be suspended
|
||||
1, 0, // resumed and joined through an opened handle
|
||||
0, 5, 0, // which may not query or terminate
|
||||
0, // main never resumed itself
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hundreds_of_threads_leave_nothing_behind() {
|
||||
for quantum in [7, 1024] {
|
||||
let run = run_with("main_churn", quantum, BUDGET).halted();
|
||||
assert_eq!(run.outs(2), [600, 600], "quantum {quantum}");
|
||||
assert_eq!(run.report.peak_threads, 2, "one slot is reused");
|
||||
for offset in [0, 0x1000, 0x2_0000, 0xF0_0000] {
|
||||
assert!(
|
||||
run.memory.read_u8(FIRST_SLOT + offset).is_err(),
|
||||
"{offset:#x} is still mapped"
|
||||
);
|
||||
assert!(
|
||||
run.memory
|
||||
.read_u8(FIRST_SLOT + 0x100_0000 + offset)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
assert_eq!(run.state.last_error(FIRST_SLOT + 0xF0_0000), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_creation_is_bounded_and_validated() {
|
||||
let run = run("main_limit");
|
||||
// The main thread counts towards the limit of 64. The waiters never end.
|
||||
assert_eq!(run.outs(5), [63, 8, 0, 0, 87]);
|
||||
assert_eq!(run.report.outcome, Outcome::Halted);
|
||||
assert!(
|
||||
run.memory.read_u8(FIRST_SLOT + 0x1000).is_err(),
|
||||
"reclaimed at exit"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deadlock_is_reported_with_its_threads() {
|
||||
let run = run("main_deadlock");
|
||||
assert_eq!(
|
||||
run.report.outcome,
|
||||
Outcome::Deadlock {
|
||||
blocked: vec![MAIN_ID, MAIN_ID + 4],
|
||||
suspended: vec![]
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mutex_owned_by_an_ended_thread_is_reported_abandoned_once() {
|
||||
let run = run("main_abandoned").halted();
|
||||
// WAIT_ABANDONED_0 + 1, released, then an ordinary acquisition.
|
||||
assert_eq!(run.outs(3), [0x81, 1, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stack_overflow_faults_in_the_guard_page_of_that_thread() {
|
||||
let run = run("main_overflow");
|
||||
let Outcome::Fault {
|
||||
thread,
|
||||
reason,
|
||||
rip,
|
||||
} = run.report.outcome
|
||||
else {
|
||||
panic!("{:?}", run.report.outcome);
|
||||
};
|
||||
assert_eq!(thread, MAIN_ID + 4);
|
||||
assert!((BASE..BASE + 0x8000).contains(&rip));
|
||||
let ExitReason::MemoryFault(error) = reason else {
|
||||
panic!("{reason:?}")
|
||||
};
|
||||
let text = format!("{error:?}");
|
||||
assert!(text.contains("PermissionViolation"), "{text}");
|
||||
// A 256 KiB stack with frames of at least 512 bytes.
|
||||
assert!((100..512).contains(&run.out(0)), "{}", run.out(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wait_keeps_the_objects_it_was_given() {
|
||||
for quantum in QUANTA {
|
||||
let run = run_with("main_captured", quantum, BUDGET).halted();
|
||||
// Object 1, the semaphore, whose only permit the wait consumed.
|
||||
assert_eq!(run.outs(2), [1, 258], "quantum {quantum}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_process_ends_with_its_main_thread_but_not_with_exit_thread() {
|
||||
let run = run("main_outlived").halted();
|
||||
assert!(
|
||||
run.memory.read_u8(FIRST_SLOT + 0x1000).is_err(),
|
||||
"the spinning thread is gone"
|
||||
);
|
||||
let run = run_with("main_exits_first", 1024, BUDGET);
|
||||
assert_eq!(run.report.outcome, Outcome::AllThreadsExited);
|
||||
assert_eq!(run.outs(2), [258, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scheduling_is_deterministic_and_bounded() {
|
||||
for main in ["main_racy", "main_mutex", "main_isolated", "main_churn"] {
|
||||
for quantum in [1, 64, 1024] {
|
||||
let (first, second) = (
|
||||
run_with(main, quantum, BUDGET),
|
||||
run_with(main, quantum, BUDGET),
|
||||
);
|
||||
assert_eq!(first.report, second.report, "{main} quantum {quantum}");
|
||||
assert_eq!(first.outs(32), second.outs(32), "{main} quantum {quantum}");
|
||||
}
|
||||
}
|
||||
for budget in [0, 1, 100, 5000] {
|
||||
let run = run_with("main_atomic", 64, budget);
|
||||
assert_eq!(run.report.outcome, Outcome::BudgetExhausted);
|
||||
assert!(
|
||||
run.report.instructions <= budget + 64,
|
||||
"{}",
|
||||
run.report.instructions
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_quanta_do_not_fill_the_code_cache() {
|
||||
// Compiled code must not depend on where turns happened to end.
|
||||
let blocks = |quantum| {
|
||||
run_with("main_independent", quantum, BUDGET)
|
||||
.metrics
|
||||
.blocks_compiled
|
||||
};
|
||||
let whole = blocks(1_000_000);
|
||||
for quantum in [1, 2, 3, 5, 7, 11, 13, 64] {
|
||||
assert_eq!(blocks(quantum), whole, "quantum {quantum}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_scheduler_nothing_pretends_to_create_threads() {
|
||||
let mut guest = guest("main_independent");
|
||||
let result = guest.engine.run(&mut guest.cpu, &mut guest.memory, BUDGET);
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(
|
||||
guest.memory.read_u64(SHARED + 392).unwrap(),
|
||||
0,
|
||||
"CreateThread returned null"
|
||||
);
|
||||
assert_eq!(
|
||||
guest.memory.read_u64(SHARED + 16).unwrap(),
|
||||
FAILED,
|
||||
"the wait failed"
|
||||
);
|
||||
assert_eq!(guest.state.last_error(TEB), 6);
|
||||
|
||||
let mut waiting = self::guest("main_timeout");
|
||||
waiting
|
||||
.engine
|
||||
.run(&mut waiting.cpu, &mut waiting.memory, BUDGET);
|
||||
assert_eq!(waiting.memory.read_u64(SHARED).unwrap(), FAILED);
|
||||
assert_eq!(waiting.clock.performance_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finished_run_detaches_its_scheduler() {
|
||||
let mut guest = guest("main_timeout");
|
||||
for _ in 0..2 {
|
||||
let scheduler = Scheduler::new(Arc::clone(&guest.state), 1024);
|
||||
let report = scheduler
|
||||
.run(&mut guest.engine, &mut guest.memory, &guest.cpu, BUDGET)
|
||||
.unwrap();
|
||||
assert_eq!(report.outcome, Outcome::Halted);
|
||||
assert_ne!(report.main.get(Register::Rsp), 0);
|
||||
}
|
||||
assert_eq!(guest.memory.read_u64(COUNTER).unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_scheduler_cannot_attach_while_one_runs() {
|
||||
let mut guest = guest("main_nested");
|
||||
let state = Arc::clone(&guest.state);
|
||||
guest.engine.register_service(NESTED, move |cpu, memory| {
|
||||
let mut engine = DbtEngine::new(1024 * 1024).unwrap();
|
||||
let nested = Scheduler::new(Arc::clone(&state), 1024).run(&mut engine, memory, cpu, BUDGET);
|
||||
assert_eq!(nested.err(), Some(ExitReason::ServiceAbiViolation));
|
||||
memory
|
||||
.write_u64(SHARED, 1)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
return_to_guest(cpu, memory)
|
||||
});
|
||||
let report = Scheduler::new(Arc::clone(&guest.state), 1024)
|
||||
.run(&mut guest.engine, &mut guest.memory, &guest.cpu, BUDGET)
|
||||
.unwrap();
|
||||
// The refused attempt leaves the running scheduler attached.
|
||||
assert_eq!(report.outcome, Outcome::Halted);
|
||||
assert_eq!(guest.memory.read_u64(SHARED).unwrap(), 1);
|
||||
assert_eq!(guest.memory.read_u64(SHARED + 8).unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_signal_after_the_deadline_is_not_taken_by_the_expired_wait() {
|
||||
for quantum in QUANTA {
|
||||
let run = run_with("main_expired_wait", quantum, BUDGET).halted();
|
||||
// WAIT_TIMEOUT, the signaling thread ends, and the auto-reset signal is
|
||||
// still there once.
|
||||
assert_eq!(run.outs(4), [258, 0, 0, 258], "quantum {quantum}");
|
||||
assert_eq!(run.clock.performance_count(), 1_000_000);
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `main_continued_wait` until `budget` is spent.
|
||||
fn first_part(budget: usize) -> (Guest, ScheduleReport) {
|
||||
let mut guest = guest("main_continued_wait");
|
||||
let report = Scheduler::new(Arc::clone(&guest.state), 1024)
|
||||
.run(&mut guest.engine, &mut guest.memory, &guest.cpu, budget)
|
||||
.unwrap();
|
||||
(guest, report)
|
||||
}
|
||||
|
||||
/// Smallest budget with which the wait has been called.
|
||||
fn budget_that_blocks() -> usize {
|
||||
(1..200)
|
||||
.find(|&budget| first_part(budget).0.engine.metrics.service_calls >= 2)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_continued_run_keeps_the_pending_wait() {
|
||||
let blocks = budget_that_blocks();
|
||||
for budget in [blocks, blocks + 1] {
|
||||
let (mut guest, report) = first_part(budget);
|
||||
assert_eq!(report.outcome, Outcome::BudgetExhausted);
|
||||
guest.clock.advance(6_000_000);
|
||||
// Neither the timeout nor the objects are taken again.
|
||||
guest.memory.write_u64(SHARED + 8 * 49, 0xBAD).unwrap();
|
||||
let report = Scheduler::new(Arc::clone(&guest.state), 1024)
|
||||
.run(&mut guest.engine, &mut guest.memory, &report.main, BUDGET)
|
||||
.unwrap();
|
||||
assert_eq!(report.outcome, Outcome::Halted);
|
||||
assert_eq!(guest.memory.read_u64(SHARED).unwrap(), 258);
|
||||
assert_eq!(guest.clock.performance_count(), 10_000_000);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_from_another_context_does_not_inherit_a_pending_wait() {
|
||||
let (mut guest, _) = first_part(budget_that_blocks());
|
||||
let report = Scheduler::new(Arc::clone(&guest.state), 1024)
|
||||
.run(&mut guest.engine, &mut guest.memory, &guest.cpu, BUDGET)
|
||||
.unwrap();
|
||||
assert_eq!(report.outcome, Outcome::Halted);
|
||||
guest.clock.advance(6_000_000);
|
||||
let begun = guest.clock.performance_count();
|
||||
Scheduler::new(Arc::clone(&guest.state), 1024)
|
||||
.run(&mut guest.engine, &mut guest.memory, &guest.cpu, BUDGET)
|
||||
.unwrap();
|
||||
assert_eq!(guest.clock.performance_count(), begun + 10_000_000);
|
||||
|
||||
let (mut guest, _) = first_part(budget_that_blocks());
|
||||
guest.clock.advance(6_000_000);
|
||||
Scheduler::new(Arc::clone(&guest.state), 1024)
|
||||
.run(&mut guest.engine, &mut guest.memory, &guest.cpu, BUDGET)
|
||||
.unwrap();
|
||||
assert_eq!(guest.clock.performance_count(), 16_000_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exhausted_run_neither_sleeps_nor_reports_a_deadlock() {
|
||||
let blocks = budget_that_blocks();
|
||||
for budget in 1..=blocks + 1 {
|
||||
let (guest, report) = first_part(budget);
|
||||
assert_eq!(report.outcome, Outcome::BudgetExhausted, "{budget}");
|
||||
assert_eq!(guest.clock.performance_count(), 0, "{budget}");
|
||||
}
|
||||
// One retry more: there is budget left for the result of the sleep.
|
||||
assert_eq!(
|
||||
first_part(blocks + 2).0.clock.performance_count(),
|
||||
10_000_000
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thread_that_ends_with_its_wait_is_noticed_at_once() {
|
||||
for quantum in QUANTA {
|
||||
// Neither a deadlock nor the longer timeout of the thread waiting for it.
|
||||
let run = run_with("main_ends_in_a_wait", quantum, BUDGET).halted();
|
||||
assert_eq!(run.outs(3), [0, 0, 258], "quantum {quantum}");
|
||||
assert_eq!(run.clock.performance_count(), 1_000_000);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thread_that_ended_cannot_be_opened_by_its_id() {
|
||||
for quantum in QUANTA {
|
||||
let run = run_with("main_reopened", quantum, BUDGET);
|
||||
assert_eq!(run.report.outcome, Outcome::AllThreadsExited);
|
||||
// ERROR_INVALID_PARAMETER.
|
||||
assert_eq!(run.outs(4), [1, 1, 0, 87], "quantum {quantum}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_signaled_object_goes_to_the_waiting_thread() {
|
||||
for quantum in [256, 1024, 1_000_000] {
|
||||
let run = run_with("main_handoff", quantum, BUDGET).halted();
|
||||
// Not available again, and the waiter has not run when the call
|
||||
// returns: for a mutex, a semaphore and an event.
|
||||
assert_eq!(
|
||||
run.outs(11),
|
||||
[258, 0, 1, 258, 1, 2, 258, 2, 3, 0, 1],
|
||||
"quantum {quantum}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_suspended_waiter_takes_nothing() {
|
||||
for quantum in QUANTA {
|
||||
let run = run_with("main_suspended_waiter", quantum, BUDGET).halted();
|
||||
assert_eq!(run.outs(4), [0, 0, 0, 1], "quantum {quantum}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opened_handles_carry_only_their_rights() {
|
||||
let run = run("main_rights").halted();
|
||||
assert_eq!(
|
||||
run.outs(13),
|
||||
[
|
||||
FAILED, 5, 0, 5, 1, 259, // query only
|
||||
0, 1, 0, FAILED, 5, 0, // suspend only
|
||||
1,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_privileged_halt_in_a_worker_is_a_fault_not_a_process_exit() {
|
||||
let run = run("main_worker_halts");
|
||||
assert!(
|
||||
matches!(
|
||||
run.report.outcome,
|
||||
Outcome::Fault { thread, reason: ExitReason::Halt, .. } if thread == MAIN_ID + 4
|
||||
),
|
||||
"{:?}",
|
||||
run.report.outcome
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_stacks_are_reused() {
|
||||
let run = run("main_reuse").halted();
|
||||
assert_eq!(run.memory.read_u64(COUNTER).unwrap(), 50);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_signals_do_not_starve_ready_threads() {
|
||||
for quantum in [1, 7, 64, 1024, 10_000] {
|
||||
let run = run_with("main_starve", quantum, 1_000_000).halted();
|
||||
assert_eq!(run.out(0), 1, "quantum {quantum}");
|
||||
// The main thread gave up its turn after about one quantum.
|
||||
assert!(run.out(1) <= quantum as u64, "{} at {quantum}", run.out(1));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locks_of_an_ended_thread_are_not_inherited() {
|
||||
for quantum in QUANTA {
|
||||
let run = run_with("main_orphaned_locks", quantum, BUDGET);
|
||||
// The second worker runs in the first one's slot. It owns nothing, and
|
||||
// completing an initialization it did not begin fails.
|
||||
assert_eq!(run.outs(5), [1, 1, 0, 0, 0], "quantum {quantum}");
|
||||
assert_eq!(run.out(7), 0);
|
||||
match run.report.outcome {
|
||||
Outcome::Halted => assert_eq!(run.out(5), 0),
|
||||
Outcome::Fault { thread, .. } => assert_eq!(thread, MAIN_ID + 8),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reader_writer_lock_of_an_ended_thread_cannot_be_released_by_another() {
|
||||
for main in ["main_orphaned_exclusive", "main_orphaned_shared"] {
|
||||
let run = run(main);
|
||||
assert!(
|
||||
matches!(run.report.outcome, Outcome::Fault { thread, .. } if thread == MAIN_ID + 8),
|
||||
"{main}: {:?}",
|
||||
run.report.outcome
|
||||
);
|
||||
assert_eq!(run.memory.read_u32(SHARED + 548).unwrap(), 0, "{main}");
|
||||
}
|
||||
assert_eq!(run("main_orphaned_shared").outs(2), [1, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_initializations_are_bounded() {
|
||||
let run = run_with("main_pending_bound", 1024, 200_000_000);
|
||||
assert!(
|
||||
matches!(run.report.outcome, Outcome::Fault { .. }),
|
||||
"{:?}",
|
||||
run.report.outcome
|
||||
);
|
||||
assert_eq!(run.memory.read_u64(COUNTER).unwrap(), 4096);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_worker_can_duplicate_its_own_pseudo_handle() {
|
||||
let run = run("main_duplicate").halted();
|
||||
assert_eq!(
|
||||
run.outs(9),
|
||||
[
|
||||
1, 1, 258, 1, // a real handle to the worker itself
|
||||
0, 50, // it has no priority to set
|
||||
0, 44, // signaled, with its exit code
|
||||
0, // the main thread's priority is unchanged
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_small_commitment_keeps_the_default_reservation() {
|
||||
let run = run("main_small_commit").halted();
|
||||
assert_eq!(run.out(0), (1..=200).sum::<u64>());
|
||||
let slot = |index: u64| run.memory.read_u64(SHARED + 264 + 8 * index).unwrap();
|
||||
assert!(
|
||||
slot(0) - slot(1) > 100_000,
|
||||
"the recursion really used the stack"
|
||||
);
|
||||
// With the flag the size is the reservation, rounded up to 64 KiB.
|
||||
let run = self::run("main_small_reservation");
|
||||
assert!(
|
||||
matches!(run.report.outcome, Outcome::Fault { .. }),
|
||||
"{:?}",
|
||||
run.report.outcome
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guest_allocations_cannot_block_or_free_thread_memory() {
|
||||
let run = run("main_area_taken").halted();
|
||||
assert_eq!(run.outs(3), [FIRST_SLOT, 1, 1]);
|
||||
let run = self::run("main_free_stack").halted();
|
||||
assert_eq!(run.outs(2), [0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threads_can_be_ended_in_every_state() {
|
||||
for quantum in [256, 1024, 1_000_000] {
|
||||
let run = run_with("main_terminations", quantum, BUDGET).halted();
|
||||
assert_eq!(
|
||||
run.outs(11),
|
||||
[
|
||||
1, 60, 0, // blocked: ended, and its wait consumed nothing
|
||||
1, 0, 61, 0, // suspended, then by itself; neither ran on
|
||||
0x80, 0, // both mutexes abandoned under wait-all, then normal
|
||||
FAILED, 156, // the 128th suspension is refused
|
||||
],
|
||||
"quantum {quantum}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_small_budget_stops_cleanly() {
|
||||
for main in ["main_limit", "main_mutex", "main_fifo"] {
|
||||
for quantum in [1, 64, 1024] {
|
||||
for budget in (1..1500).step_by(29) {
|
||||
let run = run_with(main, quantum, budget);
|
||||
assert!(!matches!(run.report.outcome, Outcome::Deadlock { .. }));
|
||||
// One block and one pass of retries may follow the limit.
|
||||
assert!(
|
||||
run.report.instructions < budget + 32,
|
||||
"{main} {quantum} {budget}: {}",
|
||||
run.report.instructions
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retrying_many_waiters_stays_within_the_budget() {
|
||||
// Up to 63 threads wait at once; a pass over all of them must stop.
|
||||
for budget in (1500..12_000).step_by(211) {
|
||||
let run = run_with("main_limit", 64, budget);
|
||||
assert!(!matches!(run.report.outcome, Outcome::Deadlock { .. }));
|
||||
assert!(
|
||||
run.report.instructions < budget + 32,
|
||||
"{budget}: {}",
|
||||
run.report.instructions
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_that_stopped_on_its_budget_keeps_main_thread_state() {
|
||||
let mut guest = guest("main_keeps_state");
|
||||
let mut cpu = guest.cpu.clone();
|
||||
let mut runs = 0;
|
||||
loop {
|
||||
let report = Scheduler::new(Arc::clone(&guest.state), 64)
|
||||
.run(&mut guest.engine, &mut guest.memory, &cpu, 500)
|
||||
.unwrap();
|
||||
runs += 1;
|
||||
if report.outcome == Outcome::Halted {
|
||||
break;
|
||||
}
|
||||
assert_eq!(report.outcome, Outcome::BudgetExhausted);
|
||||
cpu = report.main;
|
||||
}
|
||||
assert!(runs > 10, "{runs}");
|
||||
assert_eq!(guest.memory.read_u64(SHARED).unwrap(), 88);
|
||||
assert_eq!(guest.memory.read_u64(SHARED + 8).unwrap(), 77);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_ids_are_not_reused_by_a_later_run() {
|
||||
let mut first = guest("main_worker_halts");
|
||||
let mut threads = Vec::new();
|
||||
for _ in 0..3 {
|
||||
let report = Scheduler::new(Arc::clone(&first.state), 1024)
|
||||
.run(&mut first.engine, &mut first.memory, &first.cpu, BUDGET)
|
||||
.unwrap();
|
||||
let Outcome::Fault { thread, .. } = report.outcome else {
|
||||
panic!("{:?}", report.outcome);
|
||||
};
|
||||
threads.push(thread);
|
||||
}
|
||||
assert_eq!(threads, [MAIN_ID + 4, MAIN_ID + 8, MAIN_ID + 12]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn service_calls_that_end_a_turn_are_counted() {
|
||||
for (main, calls) in [
|
||||
("main_signals", 1000),
|
||||
("main_independent", 5),
|
||||
("main_mutex", 100),
|
||||
("main_fifo", 10),
|
||||
("main_churn", 100),
|
||||
("main_exits_first", 3),
|
||||
] {
|
||||
for quantum in QUANTA {
|
||||
let run = run_with(main, quantum, BUDGET);
|
||||
assert!(run.metrics.service_calls >= calls, "{main} {quantum}");
|
||||
assert_eq!(
|
||||
run.report.instructions,
|
||||
run.metrics.instructions_executed + run.metrics.service_calls,
|
||||
"{main} quantum {quantum}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compile the guest thread programs with clang and list their code.
|
||||
|
||||
generate write program.txt next to this file
|
||||
--check recompile in memory and fail if the committed listing differs
|
||||
|
||||
program.txt holds one line per item: `code <hex>`, `entry <name> <offset>` and
|
||||
`import <name> <offset>` for each 32-bit RIP-relative reference to an import
|
||||
slot. Nothing is executed and no linker is needed: the test places the code and
|
||||
fills in the references. Only clang and the Python standard library are used.
|
||||
"""
|
||||
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
OUT = HERE / "program.txt"
|
||||
FLAGS = ["-target", "x86_64-pc-windows-msvc", "-O1", "-ffreestanding", "-fno-builtin", "-nostdinc",
|
||||
"-fno-stack-protector", "-fno-asynchronous-unwind-tables", "-mno-implicit-float",
|
||||
"-fno-jump-tables", "-fno-optimize-sibling-calls", "-fno-ident", "-Wno-infinite-recursion"]
|
||||
REL32 = range(4, 10) # IMAGE_REL_AMD64_REL32 to REL32_5
|
||||
|
||||
|
||||
def listing():
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
obj = Path(directory, "program.obj")
|
||||
subprocess.run(["clang", *FLAGS, "-c", HERE / "program.c", "-o", obj], check=True)
|
||||
data = obj.read_bytes()
|
||||
machine, sections, _, symbols_at, symbol_count, optional, _ = struct.unpack_from("<HHIIIHH", data)
|
||||
assert machine == 0x8664
|
||||
strings = symbols_at + 18 * symbol_count
|
||||
|
||||
def name_at(raw):
|
||||
if raw[:4] == b"\0\0\0\0":
|
||||
start = strings + struct.unpack_from("<I", raw, 4)[0]
|
||||
return data[start:data.index(b"\0", start)].decode()
|
||||
return raw.rstrip(b"\0").decode()
|
||||
|
||||
symbols, index = {}, 0
|
||||
while index < symbol_count:
|
||||
raw = data[symbols_at + 18 * index:symbols_at + 18 * (index + 1)]
|
||||
value, section, _, storage, extra = struct.unpack_from("<IhHBB", raw, 8)
|
||||
symbols[index] = (name_at(raw[:8]), value, section, storage)
|
||||
index += 1 + extra
|
||||
text = None
|
||||
for number in range(sections):
|
||||
fields = struct.unpack_from("<8sIIIIIIHHI", data, 20 + optional + 40 * number)
|
||||
name, size = fields[0].rstrip(b"\0").decode(), fields[3]
|
||||
if name == ".text":
|
||||
text = (number + 1, size, fields[4], fields[5], fields[7])
|
||||
elif size and name in (".data", ".rdata", ".bss"):
|
||||
sys.exit(f"unexpected {name} of {size} bytes")
|
||||
number, size, at, relocations_at, count = text
|
||||
code = bytearray(data[at:at + size])
|
||||
imports = []
|
||||
for index in range(count):
|
||||
offset, symbol, kind = struct.unpack_from("<IIH", data, relocations_at + 10 * index)
|
||||
target, value, section, _ = symbols[symbol]
|
||||
if kind not in REL32:
|
||||
sys.exit(f"relocation type {kind} against {target}")
|
||||
trailing = kind - 4
|
||||
if section == number:
|
||||
addend = struct.unpack_from("<i", code, offset)[0]
|
||||
struct.pack_into("<i", code, offset, value + addend - (offset + 4 + trailing))
|
||||
elif target.startswith("__imp_") and trailing == 0:
|
||||
imports.append((target[6:], offset))
|
||||
else:
|
||||
sys.exit(f"unresolved reference to {target}")
|
||||
lines = [f"entry {name} {value}" for name, value, section, storage in sorted(symbols.values())
|
||||
if section == number and storage == 2 and name.startswith("main_")]
|
||||
lines += [f"import {name} {offset}" for name, offset in imports]
|
||||
lines += [f"code {code[i:i + 32].hex()}" for i in range(0, len(code), 32)]
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) != 2 or argv[1] not in ("generate", "--check"):
|
||||
sys.exit("usage: compile.py generate|--check")
|
||||
text = listing()
|
||||
if argv[1] == "generate":
|
||||
OUT.write_text(text)
|
||||
elif OUT.read_text() != text:
|
||||
sys.exit("program.txt differs from the compiler output")
|
||||
print(f"{text.count('entry ')} programs, {text.count('import ')} import references, {32 * text.count('code ')} bytes")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv)
|
||||
@@ -0,0 +1,806 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
// Original guest programs for the thread scheduler tests. Each `main_*`
|
||||
// function is run as the main guest thread and stores what it observed in the
|
||||
// shared block, which the test maps at a fixed address.
|
||||
|
||||
typedef unsigned long long u64;
|
||||
typedef unsigned int u32;
|
||||
typedef void *HANDLE;
|
||||
typedef u32 (*START)(void *);
|
||||
|
||||
#define IMPORT __declspec(dllimport)
|
||||
IMPORT HANDLE CreateThread(void *, u64, START, void *, u32, u32 *);
|
||||
IMPORT void ExitThread(u32);
|
||||
IMPORT int TerminateThread(HANDLE, u32);
|
||||
IMPORT int GetExitCodeThread(HANDLE, u32 *);
|
||||
IMPORT u32 SuspendThread(HANDLE);
|
||||
IMPORT u32 ResumeThread(HANDLE);
|
||||
IMPORT int SwitchToThread(void);
|
||||
IMPORT u32 GetCurrentThreadId(void);
|
||||
IMPORT u32 GetThreadId(HANDLE);
|
||||
IMPORT HANDLE OpenThread(u32, int, u32);
|
||||
IMPORT u32 WaitForSingleObject(HANDLE, u32);
|
||||
IMPORT u32 WaitForMultipleObjects(u32, const HANDLE *, int, u32);
|
||||
IMPORT HANDLE CreateEventA(void *, int, int, const char *);
|
||||
IMPORT int SetEvent(HANDLE);
|
||||
IMPORT HANDLE CreateMutexA(void *, int, const char *);
|
||||
IMPORT int ReleaseMutex(HANDLE);
|
||||
IMPORT HANDLE CreateSemaphoreA(void *, int, int, const char *);
|
||||
IMPORT int ReleaseSemaphore(HANDLE, int, int *);
|
||||
IMPORT int CloseHandle(HANDLE);
|
||||
IMPORT u32 GetLastError(void);
|
||||
IMPORT void SetLastError(u32);
|
||||
IMPORT u32 TlsAlloc(void);
|
||||
IMPORT void *TlsGetValue(u32);
|
||||
IMPORT int TlsSetValue(u32, void *);
|
||||
IMPORT int *_errno(void);
|
||||
IMPORT void InitializeCriticalSection(void *);
|
||||
IMPORT void EnterCriticalSection(void *);
|
||||
IMPORT int TryEnterCriticalSection(void *);
|
||||
IMPORT void LeaveCriticalSection(void *);
|
||||
IMPORT void AcquireSRWLockExclusive(void *);
|
||||
IMPORT void AcquireSRWLockShared(void *);
|
||||
IMPORT void ReleaseSRWLockExclusive(void *);
|
||||
IMPORT void ReleaseSRWLockShared(void *);
|
||||
IMPORT u32 TryAcquireSRWLockExclusive(void *);
|
||||
IMPORT u32 TryAcquireSRWLockShared(void *);
|
||||
IMPORT int InitOnceBeginInitialize(void *, u32, int *, void **);
|
||||
IMPORT int InitOnceComplete(void *, u32, void *);
|
||||
IMPORT int DuplicateHandle(HANDLE, HANDLE, HANDLE, HANDLE *, u32, int, u32);
|
||||
IMPORT int SetThreadPriority(HANDLE, int);
|
||||
IMPORT int GetThreadPriority(HANDLE);
|
||||
IMPORT void *VirtualAlloc(void *, u64, u32, u32);
|
||||
IMPORT int VirtualFree(void *, u64, u32);
|
||||
|
||||
#define INFINITE 0xFFFFFFFFu
|
||||
#define THREAD(n) ((void *)(u64)(n))
|
||||
struct shared {
|
||||
volatile u64 out[32];
|
||||
volatile u64 counter;
|
||||
volatile u64 slots[16];
|
||||
HANDLE handles[16];
|
||||
HANDLE a, b, c;
|
||||
volatile u32 tls;
|
||||
volatile u32 flag;
|
||||
u64 section[5], srw, once;
|
||||
};
|
||||
#define S ((struct shared *)0x50000)
|
||||
|
||||
static HANDLE spawn(START start, u64 parameter) {
|
||||
return CreateThread(0, 0, start, THREAD(parameter), 0, 0);
|
||||
}
|
||||
|
||||
static void join(HANDLE thread) {
|
||||
WaitForSingleObject(thread, INFINITE);
|
||||
CloseHandle(thread);
|
||||
}
|
||||
|
||||
// --- independent functions and exit codes --------------------------------
|
||||
static u32 fibonacci(void *n) {
|
||||
u64 a = 0, b = 1;
|
||||
for (u64 i = 0; i < (u64)n; i++) {
|
||||
u64 next = a + b;
|
||||
a = b;
|
||||
b = next;
|
||||
}
|
||||
S->out[0] = a;
|
||||
return 11;
|
||||
}
|
||||
|
||||
static u32 collatz(void *n) {
|
||||
u64 value = (u64)n, steps = 0;
|
||||
while (value != 1) {
|
||||
value = value & 1 ? 3 * value + 1 : value >> 1;
|
||||
steps++;
|
||||
}
|
||||
S->out[1] = steps;
|
||||
return 22;
|
||||
}
|
||||
|
||||
void main_independent(void) {
|
||||
u32 id = 0, code = 0;
|
||||
S->handles[0] = CreateThread(0, 0, fibonacci, THREAD(80), 0, &id);
|
||||
S->handles[1] = spawn(collatz, 97);
|
||||
S->out[2] = WaitForMultipleObjects(2, S->handles, 1, INFINITE);
|
||||
GetExitCodeThread(S->handles[0], &code);
|
||||
S->out[3] = code;
|
||||
GetExitCodeThread(S->handles[1], &code);
|
||||
S->out[4] = code;
|
||||
S->out[5] = id == GetThreadId(S->handles[0]);
|
||||
S->out[6] = id != GetCurrentThreadId();
|
||||
}
|
||||
|
||||
// --- shared counters -------------------------------------------------------
|
||||
#define ROUNDS 200
|
||||
// Uses the previous value, so the compiler emits LOCK XADD.
|
||||
static u32 atomic_worker(void *unused) {
|
||||
u64 seen = 0;
|
||||
for (int i = 0; i < ROUNDS; i++) {
|
||||
seen |= __atomic_fetch_add(&S->counter, 1, __ATOMIC_SEQ_CST);
|
||||
if ((i & 7) == 0) SwitchToThread();
|
||||
}
|
||||
return (u32)seen;
|
||||
}
|
||||
|
||||
static u32 racy_worker(void *unused) {
|
||||
for (int i = 0; i < ROUNDS; i++) {
|
||||
u64 value = S->counter;
|
||||
SwitchToThread();
|
||||
S->counter = value + 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static u32 mutex_worker(void *unused) {
|
||||
for (int i = 0; i < ROUNDS; i++) {
|
||||
WaitForSingleObject(S->a, INFINITE);
|
||||
u64 value = S->counter;
|
||||
SwitchToThread();
|
||||
S->counter = value + 1;
|
||||
ReleaseMutex(S->a);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void run_four(START start) {
|
||||
for (int i = 0; i < 4; i++) S->handles[i] = spawn(start, i);
|
||||
S->out[0] = WaitForMultipleObjects(4, S->handles, 1, INFINITE);
|
||||
S->out[1] = S->counter;
|
||||
}
|
||||
void main_atomic(void) { run_four(atomic_worker); }
|
||||
void main_racy(void) { run_four(racy_worker); }
|
||||
void main_mutex(void) {
|
||||
S->a = CreateMutexA(0, 0, 0);
|
||||
run_four(mutex_worker);
|
||||
}
|
||||
|
||||
// --- blocking and resuming -------------------------------------------------
|
||||
static u32 consumer(void *unused) {
|
||||
u64 sum = 0;
|
||||
for (int i = 0; i < 50; i++) {
|
||||
WaitForSingleObject(S->a, INFINITE);
|
||||
sum = sum * 31 + S->slots[0];
|
||||
SetEvent(S->b);
|
||||
}
|
||||
S->out[0] = sum;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void main_producer(void) {
|
||||
S->a = CreateEventA(0, 0, 0, 0);
|
||||
S->b = CreateEventA(0, 0, 0, 0);
|
||||
HANDLE thread = spawn(consumer, 0);
|
||||
for (int i = 0; i < 50; i++) {
|
||||
S->slots[0] = i + 1;
|
||||
SetEvent(S->a);
|
||||
WaitForSingleObject(S->b, INFINITE);
|
||||
}
|
||||
join(thread);
|
||||
S->out[1] = 1;
|
||||
}
|
||||
|
||||
static u32 ordered_waiter(void *index) {
|
||||
WaitForSingleObject(S->a, INFINITE);
|
||||
u64 position = __atomic_fetch_add(&S->counter, 1, __ATOMIC_SEQ_CST);
|
||||
S->out[position] = (u64)index;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// One auto-reset signal releases exactly one waiter, and the setter cannot
|
||||
// take it back from a thread that was already waiting.
|
||||
void main_fifo(void) {
|
||||
S->a = CreateEventA(0, 0, 0, 0);
|
||||
for (int i = 0; i < 4; i++) S->handles[i] = spawn(ordered_waiter, 10 + i);
|
||||
for (int i = 0; i < 20; i++) SwitchToThread();
|
||||
S->out[8] = S->counter;
|
||||
SetEvent(S->a);
|
||||
S->out[9] = WaitForSingleObject(S->a, 0);
|
||||
for (int i = 0; i < 20; i++) SwitchToThread();
|
||||
S->out[10] = S->counter;
|
||||
for (int i = 0; i < 3; i++) SetEvent(S->a);
|
||||
WaitForMultipleObjects(4, S->handles, 1, INFINITE);
|
||||
}
|
||||
|
||||
void main_timeout(void) {
|
||||
S->a = CreateEventA(0, 1, 0, 0);
|
||||
S->out[0] = WaitForSingleObject(S->a, 250);
|
||||
S->out[1] = WaitForSingleObject(S->a, 0);
|
||||
SetEvent(S->a);
|
||||
S->out[2] = WaitForSingleObject(S->a, 250);
|
||||
}
|
||||
|
||||
static u32 late_signal(void *unused) {
|
||||
WaitForSingleObject(S->b, 40);
|
||||
SetEvent(S->a);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void main_signal_before_timeout(void) {
|
||||
S->a = CreateEventA(0, 0, 0, 0);
|
||||
S->b = CreateEventA(0, 0, 0, 0);
|
||||
HANDLE thread = spawn(late_signal, 0);
|
||||
S->out[0] = WaitForSingleObject(S->a, 100);
|
||||
S->out[1] = WaitForSingleObject(S->a, 100);
|
||||
join(thread);
|
||||
}
|
||||
|
||||
// --- per-thread state ------------------------------------------------------
|
||||
static u32 isolated(void *index) {
|
||||
u64 n = (u64)index;
|
||||
u32 clean = GetLastError() == 0 && TlsGetValue(S->tls) == 0 && *_errno() == 0;
|
||||
TlsSetValue(S->tls, THREAD(n * 1000 + 7));
|
||||
*_errno() = (int)n + 40;
|
||||
SetLastError((u32)n + 500);
|
||||
u32 id = GetCurrentThreadId();
|
||||
for (int i = 0; i < 10; i++) SwitchToThread();
|
||||
u32 error = GetLastError();
|
||||
u32 good = clean && error == n + 500 && TlsGetValue(S->tls) == THREAD(n * 1000 + 7)
|
||||
&& *_errno() == (int)n + 40 && id == GetCurrentThreadId();
|
||||
S->slots[n] = id;
|
||||
return good;
|
||||
}
|
||||
|
||||
void main_isolated(void) {
|
||||
S->tls = TlsAlloc();
|
||||
TlsSetValue(S->tls, THREAD(0xAAAA));
|
||||
SetLastError(1234);
|
||||
u32 ids = 1;
|
||||
for (int i = 0; i < 4; i++) S->handles[i] = spawn(isolated, i);
|
||||
WaitForMultipleObjects(4, S->handles, 1, INFINITE);
|
||||
for (int i = 0; i < 4; i++) {
|
||||
u32 code = 0;
|
||||
GetExitCodeThread(S->handles[i], &code);
|
||||
S->out[i] = code;
|
||||
ids &= S->slots[i] == GetThreadId(S->handles[i]);
|
||||
for (int j = 0; j < i; j++) ids &= S->slots[i] != S->slots[j];
|
||||
}
|
||||
S->out[4] = GetLastError();
|
||||
S->out[5] = (u64)TlsGetValue(S->tls);
|
||||
S->out[6] = ids;
|
||||
}
|
||||
|
||||
// --- lifecycle -------------------------------------------------------------
|
||||
static u32 exits(void *code) {
|
||||
ExitThread((u32)(u64)code);
|
||||
S->out[15] = 1; // never reached
|
||||
return 99;
|
||||
}
|
||||
|
||||
static u32 spins(void *unused) {
|
||||
for (;;) S->counter++;
|
||||
}
|
||||
|
||||
void main_lifecycle(void) {
|
||||
u32 code = 0;
|
||||
S->a = CreateEventA(0, 1, 0, 0);
|
||||
HANDLE ended = spawn(exits, 0xC0DE);
|
||||
S->out[0] = WaitForSingleObject(ended, INFINITE);
|
||||
GetExitCodeThread(ended, &code);
|
||||
S->out[1] = code;
|
||||
HANDLE spinning = spawn(spins, 0);
|
||||
SwitchToThread();
|
||||
GetExitCodeThread(spinning, &code);
|
||||
S->out[2] = code; // STILL_ACTIVE
|
||||
S->out[3] = WaitForSingleObject(spinning, 0);
|
||||
S->out[4] = TerminateThread(spinning, 77);
|
||||
S->out[5] = WaitForSingleObject(spinning, INFINITE);
|
||||
GetExitCodeThread(spinning, &code);
|
||||
S->out[6] = code;
|
||||
S->out[7] = TerminateThread(spinning, 78);
|
||||
S->out[8] = GetLastError();
|
||||
GetExitCodeThread(spinning, &code);
|
||||
S->out[9] = code;
|
||||
S->out[10] = CloseHandle(spinning);
|
||||
S->out[11] = WaitForSingleObject(spinning, 0);
|
||||
S->out[12] = GetLastError();
|
||||
HANDLE opened = OpenThread(0x00100040, 0, GetThreadId(ended));
|
||||
S->out[13] = (u64)opened; // an ended thread has no ID
|
||||
}
|
||||
|
||||
static u32 marks(void *unused) {
|
||||
S->flag = 1;
|
||||
return 5;
|
||||
}
|
||||
|
||||
void main_suspend(void) {
|
||||
HANDLE thread = CreateThread(0, 0x20000, marks, 0, 4, 0);
|
||||
for (int i = 0; i < 10; i++) SwitchToThread();
|
||||
S->out[0] = S->flag;
|
||||
S->out[1] = SuspendThread(thread);
|
||||
S->out[2] = ResumeThread(thread);
|
||||
S->out[3] = WaitForSingleObject(thread, 10);
|
||||
S->out[4] = ResumeThread(thread);
|
||||
S->out[5] = WaitForSingleObject(thread, INFINITE);
|
||||
S->out[6] = S->flag;
|
||||
S->out[7] = SuspendThread(thread);
|
||||
S->out[8] = GetLastError();
|
||||
u32 id = GetThreadId(thread);
|
||||
HANDLE other = CreateThread(0, 0, marks, 0, 4, &id);
|
||||
HANDLE opened = OpenThread(0x00100002, 0, id);
|
||||
S->out[9] = ResumeThread(opened);
|
||||
S->out[10] = WaitForSingleObject(opened, INFINITE);
|
||||
u32 code = 0;
|
||||
S->out[11] = GetExitCodeThread(opened, &code);
|
||||
S->out[12] = GetLastError(); // the handle has no query right
|
||||
S->out[13] = TerminateThread(opened, 1);
|
||||
for (int i = 0; i < 200; i++) {
|
||||
if (SuspendThread(THREAD(-2)) == 0xFFFFFFFF) break;
|
||||
S->out[14]++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
#define CYCLES 600
|
||||
static u32 short_lived(void *index) {
|
||||
u32 clean = GetLastError() == 0 && TlsGetValue(S->tls) == 0 && *_errno() == 0;
|
||||
SetLastError(9);
|
||||
TlsSetValue(S->tls, index);
|
||||
*_errno() = 33;
|
||||
S->counter += clean;
|
||||
return (u32)(u64)index;
|
||||
}
|
||||
|
||||
void main_churn(void) {
|
||||
S->tls = TlsAlloc();
|
||||
u64 right = 0;
|
||||
for (u64 i = 1; i <= CYCLES; i++) {
|
||||
u32 code = 0;
|
||||
HANDLE thread = spawn(short_lived, i);
|
||||
WaitForSingleObject(thread, INFINITE);
|
||||
GetExitCodeThread(thread, &code);
|
||||
right += code == i;
|
||||
CloseHandle(thread);
|
||||
}
|
||||
S->out[0] = right;
|
||||
S->out[1] = S->counter;
|
||||
}
|
||||
|
||||
void main_limit(void) {
|
||||
u64 made = 0;
|
||||
S->a = CreateEventA(0, 1, 0, 0);
|
||||
for (int i = 0; i < 100; i++) {
|
||||
HANDLE thread = CreateThread(0, 0x10000, ordered_waiter, 0, 0, 0);
|
||||
if (!thread) break;
|
||||
made++;
|
||||
CloseHandle(thread);
|
||||
}
|
||||
S->out[0] = made;
|
||||
S->out[1] = GetLastError();
|
||||
S->out[2] = (u64)CreateThread(0, 0x10000000, marks, 0, 0, 0);
|
||||
S->out[3] = (u64)CreateThread(0, 0, marks, 0, 0x80, 0);
|
||||
S->out[4] = GetLastError();
|
||||
}
|
||||
|
||||
// --- failures --------------------------------------------------------------
|
||||
static u32 locks_b_then_a(void *unused) {
|
||||
WaitForSingleObject(S->b, INFINITE);
|
||||
SetEvent(S->c);
|
||||
WaitForSingleObject(S->a, INFINITE);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void main_deadlock(void) {
|
||||
S->a = CreateMutexA(0, 1, 0);
|
||||
S->b = CreateMutexA(0, 0, 0);
|
||||
S->c = CreateEventA(0, 0, 0, 0);
|
||||
spawn(locks_b_then_a, 0);
|
||||
WaitForSingleObject(S->c, INFINITE);
|
||||
WaitForSingleObject(S->b, INFINITE);
|
||||
}
|
||||
|
||||
static u32 abandons(void *unused) {
|
||||
WaitForSingleObject(S->a, INFINITE);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void main_abandoned(void) {
|
||||
S->a = CreateMutexA(0, 0, 0);
|
||||
S->handles[0] = CreateEventA(0, 1, 0, 0);
|
||||
S->handles[1] = S->a;
|
||||
join(spawn(abandons, 0));
|
||||
S->out[0] = WaitForMultipleObjects(2, S->handles, 0, INFINITE);
|
||||
S->out[1] = ReleaseMutex(S->a);
|
||||
S->out[2] = WaitForSingleObject(S->a, INFINITE);
|
||||
}
|
||||
|
||||
static u64 recurse(volatile u64 *previous) {
|
||||
volatile u64 frame[64];
|
||||
frame[0] = (u64)previous;
|
||||
S->out[0]++;
|
||||
return recurse(frame) + frame[0];
|
||||
}
|
||||
static u32 overflows(void *unused) { return (u32)recurse(0); }
|
||||
void main_overflow(void) { join(spawn(overflows, 0)); }
|
||||
|
||||
static u32 changes_the_wait(void *unused) {
|
||||
for (int i = 0; i < 100; i++) SwitchToThread(); // main blocks first
|
||||
CloseHandle(S->a);
|
||||
S->handles[0] = S->handles[1] = S->c;
|
||||
ReleaseSemaphore(S->b, 1, 0);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The wait keeps the objects it was given.
|
||||
void main_captured(void) {
|
||||
S->a = CreateEventA(0, 1, 0, 0);
|
||||
S->b = CreateSemaphoreA(0, 0, 5, 0);
|
||||
S->c = CreateEventA(0, 1, 1, 0);
|
||||
S->handles[0] = S->a;
|
||||
S->handles[1] = S->b;
|
||||
HANDLE thread = spawn(changes_the_wait, 0);
|
||||
S->out[0] = WaitForMultipleObjects(2, S->handles, 0, INFINITE);
|
||||
join(thread);
|
||||
S->out[1] = WaitForSingleObject(S->b, 0);
|
||||
}
|
||||
|
||||
void main_outlived(void) {
|
||||
spawn(spins, 0);
|
||||
SwitchToThread();
|
||||
}
|
||||
|
||||
static u32 last_one(void *unused) {
|
||||
S->out[0] = WaitForSingleObject(S->a, 30);
|
||||
S->out[1] = 1;
|
||||
return 0;
|
||||
}
|
||||
void main_exits_first(void) {
|
||||
S->a = CreateEventA(0, 0, 0, 0);
|
||||
spawn(last_one, 0);
|
||||
ExitThread(3);
|
||||
}
|
||||
|
||||
// --- hand-off and rights ---------------------------------------------------
|
||||
static u32 takes(void *unused) {
|
||||
WaitForSingleObject(S->a, INFINITE);
|
||||
S->counter++;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void settle(void) {
|
||||
for (int i = 0; i < 30; i++) SwitchToThread();
|
||||
}
|
||||
|
||||
// An object signaled while a thread waits belongs to that thread, which has
|
||||
// not run yet when the signaling call returns.
|
||||
void main_handoff(void) {
|
||||
S->a = CreateMutexA(0, 1, 0);
|
||||
spawn(takes, 0);
|
||||
settle();
|
||||
ReleaseMutex(S->a);
|
||||
S->out[0] = WaitForSingleObject(S->a, 0);
|
||||
S->out[1] = S->counter;
|
||||
settle();
|
||||
S->out[2] = S->counter;
|
||||
|
||||
S->a = CreateSemaphoreA(0, 0, 5, 0);
|
||||
spawn(takes, 0);
|
||||
settle();
|
||||
ReleaseSemaphore(S->a, 1, 0);
|
||||
S->out[3] = WaitForSingleObject(S->a, 0);
|
||||
S->out[4] = S->counter;
|
||||
settle();
|
||||
S->out[5] = S->counter;
|
||||
|
||||
S->a = CreateEventA(0, 0, 0, 0);
|
||||
spawn(takes, 0);
|
||||
settle();
|
||||
SetEvent(S->a);
|
||||
S->out[6] = WaitForSingleObject(S->a, 0);
|
||||
S->out[7] = S->counter;
|
||||
settle();
|
||||
S->out[8] = S->counter;
|
||||
|
||||
// Signaling does not cost the caller its turn.
|
||||
spawn(marks, 0);
|
||||
SetEvent(S->a);
|
||||
S->out[9] = S->flag;
|
||||
settle();
|
||||
S->out[10] = S->flag;
|
||||
}
|
||||
|
||||
// A suspended thread does not take what it waits for.
|
||||
void main_suspended_waiter(void) {
|
||||
S->a = CreateSemaphoreA(0, 0, 5, 0);
|
||||
HANDLE thread = spawn(takes, 0);
|
||||
settle();
|
||||
S->out[0] = SuspendThread(thread);
|
||||
ReleaseSemaphore(S->a, 1, 0);
|
||||
settle();
|
||||
S->out[1] = WaitForSingleObject(S->a, 0);
|
||||
S->out[2] = S->counter;
|
||||
ReleaseSemaphore(S->a, 1, 0);
|
||||
ResumeThread(thread);
|
||||
join(thread);
|
||||
S->out[3] = S->counter;
|
||||
}
|
||||
|
||||
void main_rights(void) {
|
||||
S->a = CreateEventA(0, 1, 0, 0);
|
||||
HANDLE thread = spawn(takes, 0);
|
||||
u32 id = GetThreadId(thread), code = 0;
|
||||
HANDLE query = OpenThread(0x00100040, 0, id);
|
||||
HANDLE suspend = OpenThread(0x00000002, 0, id);
|
||||
S->out[0] = SuspendThread(query);
|
||||
S->out[1] = GetLastError();
|
||||
S->out[2] = TerminateThread(query, 1);
|
||||
S->out[3] = GetLastError();
|
||||
S->out[4] = GetExitCodeThread(query, &code);
|
||||
S->out[5] = code;
|
||||
S->out[6] = SuspendThread(suspend);
|
||||
S->out[7] = ResumeThread(suspend);
|
||||
S->out[8] = GetExitCodeThread(suspend, &code);
|
||||
S->out[9] = WaitForSingleObject(suspend, 0);
|
||||
S->out[10] = GetLastError();
|
||||
S->out[11] = GetThreadId(suspend);
|
||||
SetEvent(S->a);
|
||||
join(thread);
|
||||
S->out[12] = GetThreadId(query) == id; // the object outlives the thread
|
||||
}
|
||||
|
||||
static u32 halts(void *unused) {
|
||||
__asm__ volatile("hlt");
|
||||
return 0;
|
||||
}
|
||||
void main_worker_halts(void) { join(spawn(halts, 0)); }
|
||||
|
||||
static u32 reports_stack(void *unused) {
|
||||
volatile u64 local = 0;
|
||||
if (!S->slots[0]) S->slots[0] = (u64)&local;
|
||||
S->counter += S->slots[0] == (u64)&local;
|
||||
return 0;
|
||||
}
|
||||
void main_reuse(void) {
|
||||
for (int i = 0; i < 50; i++) join(spawn(reports_stack, 0));
|
||||
}
|
||||
|
||||
// Signaling over and over must not starve a thread that is ready to run.
|
||||
void main_starve(void) {
|
||||
S->a = CreateEventA(0, 0, 0, 0);
|
||||
spawn(marks, 0);
|
||||
u64 signals = 0;
|
||||
while (!S->flag) {
|
||||
SetEvent(S->a);
|
||||
signals++;
|
||||
}
|
||||
S->out[0] = S->flag;
|
||||
S->out[1] = signals;
|
||||
}
|
||||
|
||||
// --- locks of an ended thread ----------------------------------------------
|
||||
static u32 takes_locks(void *unused) {
|
||||
int pending = 0;
|
||||
EnterCriticalSection(S->section);
|
||||
S->out[0] = S->section[2] == GetCurrentThreadId(); // OwningThread
|
||||
AcquireSRWLockExclusive(&S->srw);
|
||||
S->out[1] = InitOnceBeginInitialize(&S->once, 0, &pending, 0) && pending;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static u32 inherits_locks(void *unused) {
|
||||
u32 local = 0;
|
||||
S->out[2] = TryEnterCriticalSection(S->section);
|
||||
S->out[3] = TryAcquireSRWLockExclusive(&S->srw) & 0xFF;
|
||||
S->out[4] = TryAcquireSRWLockShared(&S->srw) & 0xFF;
|
||||
S->out[5] = InitOnceComplete(&S->once, 0, 0);
|
||||
S->out[6] = (u64)&local;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void main_orphaned_locks(void) {
|
||||
InitializeCriticalSection(S->section);
|
||||
join(spawn(takes_locks, 0));
|
||||
S->out[7] = TryEnterCriticalSection(S->section);
|
||||
join(spawn(inherits_locks, 0));
|
||||
}
|
||||
|
||||
static u32 begins_once(void *where) {
|
||||
int pending = 0;
|
||||
InitOnceBeginInitialize(where, 0, &pending, 0);
|
||||
return 0;
|
||||
}
|
||||
void main_pending_bound(void) {
|
||||
char *block = VirtualAlloc(0, 0x10000, 0x3000, 4);
|
||||
for (u64 i = 0; i < 5000; i++) {
|
||||
join(spawn(begins_once, (u64)block + 8 * i));
|
||||
S->counter++;
|
||||
}
|
||||
}
|
||||
|
||||
// --- identity --------------------------------------------------------------
|
||||
static u32 duplicates_itself(void *unused) {
|
||||
HANDLE copy = 0;
|
||||
u32 code = 0;
|
||||
S->out[0] = DuplicateHandle(THREAD(-1), THREAD(-2), THREAD(-1), ©, 0, 0, 2);
|
||||
S->out[1] = GetThreadId(copy) == GetCurrentThreadId();
|
||||
S->out[2] = WaitForSingleObject(copy, 0);
|
||||
S->out[3] = GetExitCodeThread(copy, &code) && code == 259;
|
||||
S->out[4] = SetThreadPriority(THREAD(-2), 2);
|
||||
S->out[5] = GetLastError();
|
||||
S->handles[0] = copy;
|
||||
return 44;
|
||||
}
|
||||
|
||||
void main_duplicate(void) {
|
||||
u32 code = 0;
|
||||
join(spawn(duplicates_itself, 0));
|
||||
S->out[6] = WaitForSingleObject(S->handles[0], 0);
|
||||
GetExitCodeThread(S->handles[0], &code);
|
||||
S->out[7] = code;
|
||||
S->out[8] = (u64)GetThreadPriority(THREAD(-2));
|
||||
}
|
||||
|
||||
// --- stacks ----------------------------------------------------------------
|
||||
// Every frame's address is used by its callee, so this stays recursive.
|
||||
static u64 deep(u64 n, volatile u64 *caller) {
|
||||
volatile u64 frame[64];
|
||||
frame[0] = n;
|
||||
frame[1] = (u64)caller;
|
||||
return n ? deep(n - 1, frame) + frame[0] : (S->slots[1] = (u64)frame, 0);
|
||||
}
|
||||
static u32 recurses(void *n) {
|
||||
volatile u64 top = 0;
|
||||
S->slots[0] = (u64)⊤
|
||||
S->out[0] = deep((u64)n, &top);
|
||||
return 1;
|
||||
}
|
||||
// 200 frames of over 512 bytes need more than 100 KB.
|
||||
void main_small_commit(void) { join(CreateThread(0, 4096, recurses, THREAD(200), 0, 0)); }
|
||||
void main_small_reservation(void) { join(CreateThread(0, 4096, recurses, THREAD(200), 0x10000, 0)); }
|
||||
|
||||
void main_area_taken(void) {
|
||||
S->out[0] = (u64)VirtualAlloc(THREAD(0x600000000), 0x10000, 0x3000, 4);
|
||||
HANDLE thread = spawn(marks, 0);
|
||||
S->out[1] = thread != 0;
|
||||
join(thread);
|
||||
S->out[2] = S->flag;
|
||||
}
|
||||
|
||||
static u32 frees_itself(void *unused) {
|
||||
u64 local = 0;
|
||||
S->out[0] = VirtualFree(THREAD(((u64)&local & ~0xFFFFFFull) + 0x1000), 0, 0x8000);
|
||||
S->out[1] = VirtualFree(THREAD(((u64)&local & ~0xFFFFFFull) + 0xF00000), 0, 0x8000);
|
||||
return 0;
|
||||
}
|
||||
void main_free_stack(void) { join(spawn(frees_itself, 0)); }
|
||||
|
||||
// --- ending threads in every state -------------------------------------------
|
||||
static u32 waits_forever(void *unused) {
|
||||
WaitForSingleObject(S->a, INFINITE);
|
||||
S->flag = 9;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static u32 terminates_itself(void *unused) {
|
||||
TerminateThread(THREAD(-2), 61);
|
||||
S->flag = 9;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static u32 owns_both(void *unused) {
|
||||
WaitForMultipleObjects(2, S->handles, 1, INFINITE);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void main_terminations(void) {
|
||||
u32 code = 0;
|
||||
S->a = CreateEventA(0, 0, 0, 0);
|
||||
HANDLE blocked = spawn(waits_forever, 0);
|
||||
settle();
|
||||
S->out[0] = TerminateThread(blocked, 60);
|
||||
GetExitCodeThread(blocked, &code);
|
||||
S->out[1] = code;
|
||||
SetEvent(S->a); // nobody is left to consume it
|
||||
S->out[2] = WaitForSingleObject(S->a, 0);
|
||||
HANDLE suspended = CreateThread(0, 0, waits_forever, 0, 4, 0);
|
||||
S->out[3] = TerminateThread(suspended, 62);
|
||||
S->out[4] = WaitForSingleObject(suspended, INFINITE);
|
||||
HANDLE itself = spawn(terminates_itself, 0);
|
||||
WaitForSingleObject(itself, INFINITE);
|
||||
GetExitCodeThread(itself, &code);
|
||||
S->out[5] = code;
|
||||
S->out[6] = S->flag;
|
||||
S->handles[0] = CreateMutexA(0, 0, 0);
|
||||
S->handles[1] = CreateMutexA(0, 0, 0);
|
||||
join(spawn(owns_both, 0));
|
||||
S->out[7] = WaitForMultipleObjects(2, S->handles, 1, INFINITE);
|
||||
ReleaseMutex(S->handles[0]);
|
||||
ReleaseMutex(S->handles[1]);
|
||||
S->out[8] = WaitForMultipleObjects(2, S->handles, 1, INFINITE);
|
||||
HANDLE limit = CreateThread(0, 0, marks, 0, 4, 0);
|
||||
for (int i = 0; i < 126; i++) SuspendThread(limit);
|
||||
S->out[9] = SuspendThread(limit);
|
||||
S->out[10] = GetLastError();
|
||||
TerminateThread(limit, 0);
|
||||
}
|
||||
|
||||
void main_keeps_state(void) {
|
||||
S->tls = TlsAlloc();
|
||||
TlsSetValue(S->tls, THREAD(77));
|
||||
SetLastError(88);
|
||||
for (volatile u64 i = 0; i < 3000; i++) {}
|
||||
S->out[0] = GetLastError();
|
||||
S->out[1] = (u64)TlsGetValue(S->tls);
|
||||
}
|
||||
|
||||
void main_signals(void) {
|
||||
S->a = CreateEventA(0, 1, 0, 0);
|
||||
for (volatile u64 i = 0; i < 1000; i++) SetEvent(S->a);
|
||||
}
|
||||
|
||||
static u32 holds_exclusive(void *unused) { AcquireSRWLockExclusive(&S->srw); return 0; }
|
||||
static u32 holds_shared(void *unused) { AcquireSRWLockShared(&S->srw); return 0; }
|
||||
static u32 releases_exclusive(void *unused) { ReleaseSRWLockExclusive(&S->srw); return S->flag = 1; }
|
||||
static u32 releases_shared(void *unused) { ReleaseSRWLockShared(&S->srw); return S->flag = 1; }
|
||||
void main_orphaned_exclusive(void) {
|
||||
join(spawn(holds_exclusive, 0));
|
||||
join(spawn(releases_exclusive, 0));
|
||||
}
|
||||
void main_orphaned_shared(void) {
|
||||
join(spawn(holds_shared, 0));
|
||||
S->out[0] = TryAcquireSRWLockShared(&S->srw) & 0xFF; // sharing is still possible
|
||||
S->out[1] = TryAcquireSRWLockExclusive(&S->srw) & 0xFF;
|
||||
join(spawn(releases_shared, 0));
|
||||
}
|
||||
|
||||
// Host services the test registers at fixed addresses.
|
||||
#define ADVANCE ((void (*)(u64))0x60000)
|
||||
#define NESTED ((void (*)(void))0x60010)
|
||||
|
||||
// --- a signal after the deadline belongs to nobody -------------------------
|
||||
static u32 signals_too_late(void *unused) {
|
||||
while (!S->flag) SwitchToThread();
|
||||
settle();
|
||||
ADVANCE(100);
|
||||
SetEvent(S->a);
|
||||
return 0;
|
||||
}
|
||||
void main_expired_wait(void) {
|
||||
S->a = CreateEventA(0, 0, 0, 0);
|
||||
HANDLE late = spawn(signals_too_late, 0);
|
||||
S->flag = 1;
|
||||
S->out[0] = WaitForSingleObject(S->a, 50);
|
||||
S->out[1] = WaitForSingleObject(late, INFINITE);
|
||||
S->out[2] = WaitForSingleObject(S->a, 0);
|
||||
S->out[3] = WaitForSingleObject(S->a, 0);
|
||||
}
|
||||
|
||||
void main_continued_wait(void) {
|
||||
S->a = CreateEventA(0, 1, 0, 0);
|
||||
S->handles[0] = S->a;
|
||||
S->out[0] = WaitForMultipleObjects(1, S->handles, 1, 1000);
|
||||
S->out[1] = 1;
|
||||
}
|
||||
|
||||
static u32 reopens(void *id) {
|
||||
settle();
|
||||
S->out[2] = (u64)OpenThread(0x40, 0, (u32)(u64)id);
|
||||
S->out[3] = GetLastError();
|
||||
return 0;
|
||||
}
|
||||
void main_reopened(void) {
|
||||
u32 id = GetCurrentThreadId();
|
||||
S->out[0] = OpenThread(0x40, 0, id) != 0;
|
||||
S->out[1] = spawn(reopens, id) != 0;
|
||||
ExitThread(3);
|
||||
}
|
||||
|
||||
// A tail call: the wait returns straight to the end of the thread.
|
||||
static u32 ends_in_a_wait(HANDLE event, u32 unused) {
|
||||
__attribute__((musttail)) return WaitForSingleObject(event, 50);
|
||||
}
|
||||
void main_ends_in_a_wait(void) {
|
||||
u32 code = 0;
|
||||
S->a = CreateEventA(0, 1, 0, 0);
|
||||
S->handles[0] = spawn((START)(void *)ends_in_a_wait, (u64)S->a);
|
||||
S->out[0] = WaitForSingleObject(S->handles[0], INFINITE);
|
||||
S->handles[1] = spawn((START)(void *)ends_in_a_wait, (u64)S->a);
|
||||
S->out[1] = WaitForSingleObject(S->handles[1], 1000);
|
||||
GetExitCodeThread(S->handles[1], &code);
|
||||
S->out[2] = code;
|
||||
}
|
||||
|
||||
void main_nested(void) {
|
||||
NESTED();
|
||||
S->out[1] = WaitForSingleObject(spawn(collatz, 97), INFINITE);
|
||||
}
|
||||
@@ -0,0 +1,700 @@
|
||||
entry main_abandoned 4784
|
||||
entry main_area_taken 8960
|
||||
entry main_atomic 432
|
||||
entry main_captured 5152
|
||||
entry main_churn 3936
|
||||
entry main_continued_wait 11232
|
||||
entry main_deadlock 4560
|
||||
entry main_duplicate 8288
|
||||
entry main_ends_in_a_wait 11552
|
||||
entry main_exits_first 5584
|
||||
entry main_expired_wait 10928
|
||||
entry main_fifo 1520
|
||||
entry main_free_stack 9120
|
||||
entry main_handoff 5744
|
||||
entry main_independent 0
|
||||
entry main_isolated 2256
|
||||
entry main_keeps_state 10176
|
||||
entry main_lifecycle 2896
|
||||
entry main_limit 4272
|
||||
entry main_mutex 896
|
||||
entry main_nested 11792
|
||||
entry main_orphaned_exclusive 10432
|
||||
entry main_orphaned_locks 7632
|
||||
entry main_orphaned_shared 10656
|
||||
entry main_outlived 5520
|
||||
entry main_overflow 5056
|
||||
entry main_pending_bound 8064
|
||||
entry main_producer 1184
|
||||
entry main_racy 672
|
||||
entry main_reopened 11328
|
||||
entry main_reuse 7280
|
||||
entry main_rights 6720
|
||||
entry main_signal_before_timeout 2032
|
||||
entry main_signals 10320
|
||||
entry main_small_commit 8736
|
||||
entry main_small_reservation 8880
|
||||
entry main_starve 7472
|
||||
entry main_suspend 3424
|
||||
entry main_suspended_waiter 6432
|
||||
entry main_terminations 9312
|
||||
entry main_timeout 1904
|
||||
entry main_worker_halts 7184
|
||||
import CreateThread 50
|
||||
import WaitForMultipleObjects 142
|
||||
import GetExitCodeThread 167
|
||||
import GetThreadId 232
|
||||
import GetCurrentThreadId 257
|
||||
import CreateThread 451
|
||||
import WaitForMultipleObjects 534
|
||||
import SwitchToThread 590
|
||||
import CreateThread 691
|
||||
import WaitForMultipleObjects 774
|
||||
import SwitchToThread 831
|
||||
import CreateMutexA 914
|
||||
import CreateThread 936
|
||||
import WaitForMultipleObjects 1014
|
||||
import WaitForSingleObject 1075
|
||||
import SwitchToThread 1082
|
||||
import ReleaseMutex 1089
|
||||
import CreateEventA 1196
|
||||
import CreateThread 1273
|
||||
import SetEvent 1288
|
||||
import WaitForSingleObject 1295
|
||||
import WaitForSingleObject 1365
|
||||
import CloseHandle 1374
|
||||
import WaitForSingleObject 1427
|
||||
import SetEvent 1434
|
||||
import CreateEventA 1539
|
||||
import CreateThread 1566
|
||||
import SwitchToThread 1638
|
||||
import SetEvent 1680
|
||||
import WaitForSingleObject 1696
|
||||
import SetEvent 1758
|
||||
import WaitForMultipleObjects 1814
|
||||
import WaitForSingleObject 1863
|
||||
import CreateEventA 1924
|
||||
import WaitForSingleObject 1939
|
||||
import SetEvent 1995
|
||||
import CreateEventA 2041
|
||||
import CreateThread 2118
|
||||
import WaitForSingleObject 2136
|
||||
import CloseHandle 2197
|
||||
import WaitForSingleObject 2227
|
||||
import SetEvent 2241
|
||||
import TlsAlloc 2279
|
||||
import TlsSetValue 2304
|
||||
import SetLastError 2315
|
||||
import CreateThread 2331
|
||||
import WaitForMultipleObjects 2412
|
||||
import GetExitCodeThread 2422
|
||||
import GetThreadId 2429
|
||||
import GetLastError 2568
|
||||
import TlsGetValue 2591
|
||||
import GetLastError 2659
|
||||
import TlsGetValue 2676
|
||||
import TlsSetValue 2715
|
||||
import _errno 2725
|
||||
import SetLastError 2740
|
||||
import GetCurrentThreadId 2751
|
||||
import SwitchToThread 2760
|
||||
import GetLastError 2777
|
||||
import TlsGetValue 2812
|
||||
import _errno 2823
|
||||
import GetCurrentThreadId 2834
|
||||
import _errno 2875
|
||||
import CreateEventA 2932
|
||||
import CreateThread 2971
|
||||
import WaitForSingleObject 2993
|
||||
import GetExitCodeThread 3021
|
||||
import SwitchToThread 3089
|
||||
import TerminateThread 3135
|
||||
import GetLastError 3226
|
||||
import CloseHandle 3269
|
||||
import GetThreadId 3319
|
||||
import OpenThread 3335
|
||||
import ExitThread 3382
|
||||
import CreateThread 3471
|
||||
import SwitchToThread 3486
|
||||
import SuspendThread 3528
|
||||
import ResumeThread 3550
|
||||
import WaitForSingleObject 3572
|
||||
import GetLastError 3666
|
||||
import GetThreadId 3688
|
||||
import CreateThread 3730
|
||||
import OpenThread 3748
|
||||
import GetExitCodeThread 3809
|
||||
import TerminateThread 3846
|
||||
import TlsAlloc 3954
|
||||
import CreateThread 3976
|
||||
import WaitForSingleObject 3983
|
||||
import GetExitCodeThread 3995
|
||||
import CloseHandle 4002
|
||||
import GetLastError 4171
|
||||
import TlsGetValue 4188
|
||||
import SetLastError 4206
|
||||
import TlsSetValue 4222
|
||||
import _errno 4228
|
||||
import _errno 4257
|
||||
import CreateEventA 4302
|
||||
import CreateThread 4329
|
||||
import CloseHandle 4336
|
||||
import GetLastError 4427
|
||||
import CreateMutexA 4568
|
||||
import CreateEventA 4621
|
||||
import CreateThread 4666
|
||||
import WaitForSingleObject 4681
|
||||
import WaitForSingleObject 4736
|
||||
import SetEvent 4757
|
||||
import CreateMutexA 4799
|
||||
import CreateEventA 4826
|
||||
import CreateThread 4887
|
||||
import WaitForSingleObject 4897
|
||||
import CloseHandle 4916
|
||||
import WaitForMultipleObjects 4941
|
||||
import ReleaseMutex 4965
|
||||
import WaitForSingleObject 5043
|
||||
import CreateThread 5094
|
||||
import WaitForSingleObject 5111
|
||||
import CloseHandle 5120
|
||||
import CreateEventA 5161
|
||||
import CreateSemaphoreA 5203
|
||||
import CreateThread 5306
|
||||
import WaitForMultipleObjects 5334
|
||||
import WaitForSingleObject 5351
|
||||
import CloseHandle 5370
|
||||
import SwitchToThread 5422
|
||||
import CloseHandle 5456
|
||||
import ReleaseSemaphore 5502
|
||||
import CreateThread 5557
|
||||
import SwitchToThread 5563
|
||||
import CreateEventA 5600
|
||||
import CreateThread 5645
|
||||
import ExitThread 5656
|
||||
import WaitForSingleObject 5699
|
||||
import CreateMutexA 5762
|
||||
import CreateThread 5807
|
||||
import SwitchToThread 5819
|
||||
import ReleaseMutex 5840
|
||||
import WaitForSingleObject 5856
|
||||
import CreateSemaphoreA 5941
|
||||
import CreateThread 5986
|
||||
import ReleaseSemaphore 6024
|
||||
import WaitForSingleObject 6040
|
||||
import CreateEventA 6114
|
||||
import CreateThread 6159
|
||||
import SetEvent 6192
|
||||
import WaitForSingleObject 6208
|
||||
import CreateThread 6311
|
||||
import SetEvent 6325
|
||||
import WaitForSingleObject 6403
|
||||
import CreateSemaphoreA 6454
|
||||
import CreateThread 6499
|
||||
import SwitchToThread 6514
|
||||
import SuspendThread 6539
|
||||
import ReleaseSemaphore 6571
|
||||
import WaitForSingleObject 6609
|
||||
import ReleaseSemaphore 6661
|
||||
import ResumeThread 6670
|
||||
import CloseHandle 6689
|
||||
import CreateEventA 6751
|
||||
import CreateThread 6796
|
||||
import GetThreadId 6808
|
||||
import OpenThread 6825
|
||||
import SuspendThread 6864
|
||||
import GetLastError 6886
|
||||
import TerminateThread 6913
|
||||
import GetExitCodeThread 6943
|
||||
import ResumeThread 7003
|
||||
import WaitForSingleObject 7039
|
||||
import GetThreadId 7080
|
||||
import SetEvent 7107
|
||||
import CloseHandle 7127
|
||||
import CreateThread 7222
|
||||
import WaitForSingleObject 7239
|
||||
import CloseHandle 7248
|
||||
import CreateThread 7308
|
||||
import WaitForSingleObject 7315
|
||||
import CloseHandle 7322
|
||||
import CreateEventA 7492
|
||||
import CreateThread 7537
|
||||
import SetEvent 7556
|
||||
import InitializeCriticalSection 7648
|
||||
import CreateThread 7679
|
||||
import WaitForSingleObject 7698
|
||||
import CloseHandle 7715
|
||||
import TryEnterCriticalSection 7732
|
||||
import EnterCriticalSection 7828
|
||||
import GetCurrentThreadId 7842
|
||||
import AcquireSRWLockExclusive 7871
|
||||
import InitOnceBeginInitialize 7892
|
||||
import TryEnterCriticalSection 7955
|
||||
import TryAcquireSRWLockExclusive 7976
|
||||
import TryAcquireSRWLockShared 7998
|
||||
import InitOnceComplete 8025
|
||||
import VirtualAlloc 8103
|
||||
import CreateThread 8120
|
||||
import WaitForSingleObject 8127
|
||||
import CloseHandle 8134
|
||||
import InitOnceBeginInitialize 8264
|
||||
import CreateThread 8335
|
||||
import WaitForSingleObject 8345
|
||||
import CloseHandle 8364
|
||||
import GetExitCodeThread 8405
|
||||
import GetThreadPriority 8430
|
||||
import DuplicateHandle 8538
|
||||
import GetThreadId 8559
|
||||
import GetCurrentThreadId 8567
|
||||
import WaitForSingleObject 8595
|
||||
import GetExitCodeThread 8621
|
||||
import SetThreadPriority 8668
|
||||
import GetLastError 8684
|
||||
import CreateThread 8780
|
||||
import WaitForSingleObject 8797
|
||||
import CloseHandle 8806
|
||||
import CreateThread 8924
|
||||
import WaitForSingleObject 8941
|
||||
import CloseHandle 8950
|
||||
import VirtualAlloc 8994
|
||||
import CreateThread 9039
|
||||
import WaitForSingleObject 9072
|
||||
import CloseHandle 9081
|
||||
import CreateThread 9158
|
||||
import WaitForSingleObject 9175
|
||||
import CloseHandle 9184
|
||||
import VirtualFree 9237
|
||||
import CreateEventA 9345
|
||||
import CreateThread 9390
|
||||
import SwitchToThread 9405
|
||||
import TerminateThread 9433
|
||||
import GetExitCodeThread 9461
|
||||
import SetEvent 9501
|
||||
import WaitForSingleObject 9516
|
||||
import CreateThread 9562
|
||||
import CreateMutexA 9706
|
||||
import CloseHandle 9796
|
||||
import WaitForMultipleObjects 9803
|
||||
import ReleaseMutex 9852
|
||||
import SuspendThread 9946
|
||||
import SuspendThread 9966
|
||||
import GetLastError 9982
|
||||
import TerminateThread 10003
|
||||
import WaitForSingleObject 10051
|
||||
import TerminateThread 10098
|
||||
import WaitForMultipleObjects 10156
|
||||
import TlsAlloc 10182
|
||||
import TlsSetValue 10207
|
||||
import SetLastError 10218
|
||||
import GetLastError 10276
|
||||
import TlsGetValue 10299
|
||||
import CreateEventA 10340
|
||||
import SetEvent 10377
|
||||
import CreateThread 10468
|
||||
import WaitForSingleObject 10487
|
||||
import CloseHandle 10504
|
||||
import AcquireSRWLockExclusive 10587
|
||||
import ReleaseSRWLockExclusive 10619
|
||||
import CreateThread 10692
|
||||
import WaitForSingleObject 10711
|
||||
import CloseHandle 10728
|
||||
import TryAcquireSRWLockShared 10745
|
||||
import TryAcquireSRWLockExclusive 10767
|
||||
import AcquireSRWLockShared 10859
|
||||
import ReleaseSRWLockShared 10891
|
||||
import CreateEventA 10946
|
||||
import CreateThread 10991
|
||||
import WaitForSingleObject 11020
|
||||
import SwitchToThread 11139
|
||||
import SwitchToThread 11172
|
||||
import SetEvent 11212
|
||||
import CreateEventA 11251
|
||||
import WaitForMultipleObjects 11295
|
||||
import GetCurrentThreadId 11335
|
||||
import OpenThread 11353
|
||||
import CreateThread 11406
|
||||
import ExitThread 11433
|
||||
import SwitchToThread 11474
|
||||
import OpenThread 11506
|
||||
import GetLastError 11520
|
||||
import CreateEventA 11582
|
||||
import CreateThread 11621
|
||||
import WaitForSingleObject 11648
|
||||
import GetExitCodeThread 11749
|
||||
import WaitForSingleObject 11784
|
||||
import CreateThread 11839
|
||||
import WaitForSingleObject 11853
|
||||
code 56574883ec38c744243400000000c744243000000000488d4424344889442428
|
||||
code c7442420000000004c8d05f1000000488b350000000041b95000000031c931d2
|
||||
code ffd6488904258801050048c744242800000000c7442420000000004c8d050e01
|
||||
code 000041b96100000031c931d2ffd64889042590010500ba88010500b902000000
|
||||
code 41b80100000041b9ffffffffff150000000089c04889042510000500488b0c25
|
||||
code 88010500488b3d00000000488d7424304889f2ffd78b44243048890425180005
|
||||
code 00488b0c25900105004889f2ffd78b44243048890425200005008b742434488b
|
||||
code 0c2588010500ff150000000031c939c60f94c148890c25280005008b742434ff
|
||||
code 150000000031c939c60f95c148890c25300005004883c4385f5ec30f1f440000
|
||||
code 4885c974314883f9014883d100b80100000031d26666662e0f1f840000000000
|
||||
code 4989d14901c14989c04889c24c89c848ffc975eceb034531c04c890425000005
|
||||
code 00b80b000000c3660f1f84000000000031c04883f90174254889ca0f1f440000
|
||||
code 4c8d044949ffc048d1eaf6c101490f45d048ffc04889d14883fa0175e3488904
|
||||
code 2508000500b816000000c30f1f4400005657534883ec3031f6488d3d80000000
|
||||
code 488b1d00000000660f1f84000000000048c744242800000000c7442420000000
|
||||
code 0031c931d24989f84989f1ffd3488904f58801050048ffc64883fe0475d2ba88
|
||||
code 010500b90400000041b80100000041b9ffffffffff150000000089c048890425
|
||||
code 00000500488b04250001050048890425080005004883c4305b5f5ec30f1f4000
|
||||
code 41565657534883ec2831f6488b3d0000000031dbeb17662e0f1f840000000000
|
||||
code 4c09f6ffc381fbc8000000741941be01000000f04c0fc1342500010500f6c307
|
||||
code 75deffd7ebda89f04883c4285b5f5e415ec366666666662e0f1f840000000000
|
||||
code 5657534883ec3031f6488d3d80000000488b1d00000000660f1f840000000000
|
||||
code 48c744242800000000c74424200000000031c931d24989f84989f1ffd3488904
|
||||
code f58801050048ffc64883fe0475d2ba88010500b90400000041b80100000041b9
|
||||
code ffffffffff150000000089c04889042500000500488b04250001050048890425
|
||||
code 080005004883c4305b5f5ec30f1f40005657534883ec20bec8000000488b3d00
|
||||
code 000000666666662e0f1f840000000000488b1c2500010500ffd748ffc348891c
|
||||
code 2500010500ffce75e731c04883c4205b5f5ec3666666662e0f1f840000000000
|
||||
code 5657534883ec3031f631c931d24531c0ff15000000004889042508020500488d
|
||||
code 3d7b000000488b1d000000000f1f400048c744242800000000c7442420000000
|
||||
code 0031c931d24989f84989f1ffd3488904f58801050048ffc64883fe0475d2ba88
|
||||
code 010500b90400000041b80100000041b9ffffffffff150000000089c048890425
|
||||
code 00000500488b04250001050048890425080005004883c4305b5f5ec30f1f4000
|
||||
code 415741565657534883ec20bec8000000488b3d00000000488b1d000000004c8b
|
||||
code 350000000066662e0f1f840000000000488b0c2508020500baffffffffffd74c
|
||||
code 8b3c2500010500ffd349ffc74c893c2500010500488b0c250802050041ffd6ff
|
||||
code ce75cd31c04883c4205b5f5e415e415fc36666666666662e0f1f840000000000
|
||||
code 41565657534883ec38488b350000000031c931d24531c04531c9ffd648890425
|
||||
code 0802050031c931d24531c04531c9ffd6488904251002050048c7442428000000
|
||||
code 00c7442420000000004c8d059000000031c931d24531c9ff15000000004889c6
|
||||
code bf01000000488b1d000000004c8b3500000000666666662e0f1f840000000000
|
||||
code 48893c2508010500488b0c2508020500ffd3488b0c2510020500baffffffff41
|
||||
code ffd648ffc74883ff3375d54889f1baffffffffff15000000004889f1ff150000
|
||||
code 000048c7042508000500010000004883c4385b5f5e415ec30f1f840000000000
|
||||
code 41565657534883ec28be3200000031ff488b1d000000004c8b35000000006690
|
||||
code 488b0c2508020500baffffffffffd34889f848c1e0054829f84889c748033c25
|
||||
code 08010500488b0c251002050041ffd6ffce75cd48893c250000050031c04883c4
|
||||
code 285b5f5e415ec3660f1f8400000000005657534883ec3031c931d24531c04531
|
||||
code c9ff15000000004889042508020500be0a000000488d3d15010000488b1d0000
|
||||
code 000066666666662e0f1f84000000000048c744242800000000c7442420000000
|
||||
code 0031c931d24989f84989f1ffd3488904f53801050048ffc64883fe0e75d2bf14
|
||||
code 000000488b3500000000660f1f440000ffd6ffcf75fa488b0425000105004889
|
||||
code 042540000500488b0c2508020500ff1500000000488b0c250802050031d2ff15
|
||||
code 0000000089c04889042548000500bf14000000666666662e0f1f840000000000
|
||||
code ffd6ffcf75fa488b0425000105004889042550000500be03000000488b3d0000
|
||||
code 000066666666662e0f1f840000000000488b0c2508020500ffd7ffce75f2ba88
|
||||
code 010500b90400000041b80100000041b9ffffffffff15000000004883c4305b5f
|
||||
code 5ec366666666662e0f1f840000000000564883ec204889ce488b0c2508020500
|
||||
code baffffffffff1500000000b801000000f0480fc1042500010500488934c50000
|
||||
code 050031c04883c4205ec3660f1f440000564883ec2031c9ba010000004531c045
|
||||
code 31c9ff15000000004889042508020500488b35000000004889c1bafa000000ff
|
||||
code d689c04889042500000500488b0c250802050031d2ffd689c048890425080005
|
||||
code 00488b0c2508020500ff1500000000488b0c2508020500bafa000000ffd689c0
|
||||
code 48890425100005004883c4205ec3669056574883ec38488b350000000031c931
|
||||
code d24531c04531c9ffd6488904250802050031c931d24531c04531c9ffd6488904
|
||||
code 251002050048c744242800000000c7442420000000004c8d056300000031c931
|
||||
code d24531c9ff15000000004889c6488b0c2508020500488b3d00000000ba640000
|
||||
code 00ffd789c04889042500000500488b0c2508020500ba64000000ffd789c04889
|
||||
code 0425080005004889f1baffffffffffd74889f1ff15000000004883c4385f5ec3
|
||||
code 4883ec28488b0c2510020500ba28000000ff1500000000488b0c2508020500ff
|
||||
code 150000000031c04883c428c30f1f40004157415641554154565755534883ec38
|
||||
code bb08010500ff1500000000890425200205008b0c2520020500baaaaa0000ff15
|
||||
code 00000000b9d2040000ff150000000031f6488d3d380100004c8b350000000090
|
||||
code 48c744242800000000c74424200000000031c931d24989f84989f141ffd64889
|
||||
code 84f38000000048ffc64883fe0475d1bf01000000ba88010500b90400000041b8
|
||||
code 0100000041b9ffffffffff15000000004531f64c8b3d000000004c8b25000000
|
||||
code 004531edeb13662e0f1f84000000000049ffc54983fd04746d89fdc744243400
|
||||
code 0000004a8b8ceb80000000488d54243441ffd78b4424344a8984ebf8feffff4a
|
||||
code 8b34eb4a8b8ceb8000000041ffd489c031ff4839c6400f94c721ef4d85ed74b0
|
||||
code 31c066666666662e0f1f8400000000004a8b0ceb483b0cc3410f44fe48ffc049
|
||||
code 39c575eceb8aff150000000089c048890425200005008b0c2520020500ff1500
|
||||
code 000000488904252800050089f848890425300005004883c4385b5d5f5e415c41
|
||||
code 5d415e415fc3662e0f1f840000000000415741564154565755534883ec204889
|
||||
code ceff150000000085c075168b0c2520020500ff15000000004885c00f84b80000
|
||||
code 004531f64869dee80300004883cb078b0c25200205004889daff150000000044
|
||||
code 8d7e28ff15000000004489388d8ef4010000ff1500000000bd0a000000ff1500
|
||||
code 00000089c74c8b25000000000f1f400041ffd4ffcd75f9ff150000000089c048
|
||||
code 8d8ef40100004839c10f94c031ed4184c6742b8b0c2520020500ff1500000000
|
||||
code 4839d87519ff1500000000443938750eff150000000031ed39c7400f94c589f8
|
||||
code 488904f50801050089e84883c4205b5d5f5e415c415e415fc3ff150000000083
|
||||
code 3800410f94c6e939ffffff0f1f4400004157415641545657534883ec38c74424
|
||||
code 340000000031c9ba010000004531c04531c9ff15000000004889042508020500
|
||||
code 48c744242800000000c7442420000000004c8d0598010000488b1d0000000041
|
||||
code b9dec0000031c931d2ffd34889c64c8b35000000004889c1baffffffff41ffd6
|
||||
code 89c048890425000005004c8b3d00000000488d7c24344889f14889fa41ffd78b
|
||||
code 442434488904250800050048c744242800000000c7442420000000004c8d054d
|
||||
code 01000031c931d24531c9ffd34889c3ff15000000004889d94889fa41ffd78b44
|
||||
code 243448890425100005004889d931d241ffd689c048890425180005004c8b2500
|
||||
code 0000004889d9ba4d00000041ffd4489848890425200005004889d9baffffffff
|
||||
code 41ffd689c048890425280005004889d94889fa41ffd78b442434488904253000
|
||||
code 05004889d9ba4e00000041ffd4489848890425380005004c8b250000000041ff
|
||||
code d489c048890425400005004889d94889fa41ffd78b4424344889042548000500
|
||||
code 4889d9ff1500000000489848890425500005004889d931d241ffd689c0488904
|
||||
code 255800050041ffd489c048890425600005004889f1ff1500000000b940001000
|
||||
code 31d24189c0ff150000000048890425680005004883c4385b5f5e415c415e415f
|
||||
code c36666666666662e0f1f8400000000004883ec28ff150000000048c704257800
|
||||
code 050001000000b8630000004883c428c348ff042500010500ebf6660f1f440000
|
||||
code 415741565657534883ec4048c744242800000000c7442420040000004c8d05bd
|
||||
code 010000ba0000020031c94531c9ff15000000004889c6bf0a000000488b1d0000
|
||||
code 000066666666662e0f1f840000000000ffd3ffcf75fa8b042524020500488904
|
||||
code 2500000500488b3d000000004889f1ffd789c04889042508000500488b1d0000
|
||||
code 00004889f1ffd389c048890425100005004c8b35000000004889f1ba0a000000
|
||||
code 41ffd689c048890425180005004889f1ffd389c048890425200005004889f1ba
|
||||
code ffffffff41ffd689c048890425280005008b0425240205004889042530000500
|
||||
code 4889f1ffd789c048890425380005004c8b3d0000000041ffd789c04889042540
|
||||
code 0005004889f1ff150000000089442438488d4424384889442428c74424200400
|
||||
code 00004c8d05b700000031c931d24531c9ff1500000000448b442438b902001000
|
||||
code 31d2ff15000000004889c64889c1ffd389c048890425480005004889f1baffff
|
||||
code ffff41ffd689c04889042550000500c744243c00000000488d54243c4889f1ff
|
||||
code 15000000004898488904255800050041ffd789c048890425600005004889f1ba
|
||||
code 01000000ff15000000004898488904256800050048c7c1feffffffffd783f8ff
|
||||
code 740848ff0425700005004883c4405b5f5e415e415fc3662e0f1f840000000000
|
||||
code c704252402050001000000b805000000c36666666666662e0f1f840000000000
|
||||
code 4157415641554154565755534883ec38ff150000000089042520020500be0100
|
||||
code 00004531ff4c8b25000000004c8b2d00000000488d5c2434488b2d0000000048
|
||||
code 8b3d00000000662e0f1f840000000000c74424340000000048c7442428000000
|
||||
code 00c74424200000000031c931d24c8d056c0000004989f141ffd44989c64889c1
|
||||
code baffffffff41ffd54c89f14889daffd58b44243431c94839c60f94c14901cf4c
|
||||
code 89f1ffd748ffc64881fe5902000075a04c893c2500000500488b042500010500
|
||||
code 48890425080005004883c4385b5d5f5e415c415d415e415fc30f1f8000000000
|
||||
code 56574883ec284889ceff150000000085c075128b0c2520020500ff1500000000
|
||||
code 4885c0743a31ffb909000000ff15000000008b0c25200205004889f2ff150000
|
||||
code 0000ff1500000000c7002100000048013c250001050089f04883c4285f5ec3ff
|
||||
code 150000000031ff833800400f94c7ebb741574156565755534883ec384531f631
|
||||
code c9ba010000004531c04531c9ff15000000004889042508020500bd6300000048
|
||||
code 8d354af6ffff488b1d000000004c8b3d000000006666662e0f1f840000000000
|
||||
code 48c744242800000000c744242000000000ba0000010031c94989f04531c9ffd3
|
||||
code 4889c74885c0740949ffc64889f941ffd783ed010f92c04885ff740484c074c0
|
||||
code 4c89342500000500488b3d00000000ffd789c0488904250800050048c7442428
|
||||
code 00000000c744242000000000488d35cdfdffffba0000001031c94989f04531c9
|
||||
code ffd3488904251000050048c744242800000000c74424208000000031c931d249
|
||||
code 89f04531c9ffd34889042518000500ffd789c048890425200005004883c4385b
|
||||
code 5d5f5e415e415fc30f1f840000000000564883ec30488b350000000031c9ba01
|
||||
code 0000004531c0ffd6488904250802050031c931d24531c0ffd648890425100205
|
||||
code 0031c931d24531c04531c9ff1500000000488904251802050048c74424280000
|
||||
code 0000c7442420000000004c8d053f00000031c931d24531c9ff1500000000488b
|
||||
code 0c2518020500488b3500000000baffffffffffd6488b0c2510020500baffffff
|
||||
code ffffd64883c4305ec30f1f8000000000564883ec20488b0c2510020500488b35
|
||||
code 00000000baffffffffffd6488b0c2518020500ff1500000000488b0c25080205
|
||||
code 00baffffffffffd631c04883c4205ec356574883ec3831c931d24531c0ff1500
|
||||
code 000000488904250802050031c9ba010000004531c04531c9ff15000000004889
|
||||
code 042588010500488b042508020500488904259001050048c744242800000000c7
|
||||
code 442420000000004c8d059200000031c931d24531c9ff15000000004889c6488b
|
||||
code 3d000000004889c1baffffffffffd74889f1ff1500000000ba88010500b90200
|
||||
code 00004531c041b9ffffffffff150000000089c04889042500000500488b0c2508
|
||||
code 020500ff150000000048984889042508000500488b0c2508020500baffffffff
|
||||
code ffd789c048890425100005004883c4385f5ec3666666662e0f1f840000000000
|
||||
code 4883ec28488b0c2508020500baffffffffff150000000031c04883c428c36690
|
||||
code 564883ec3048c744242800000000c7442420000000004c8d053300000031c931
|
||||
code d24531c9ff15000000004889c64889c1baffffffffff15000000004889f1ff15
|
||||
code 000000004883c4305ec3660f1f4400004883ec2831c9e8451a00004883c428c3
|
||||
code 56574883ec38488b350000000031c9ba010000004531c04531c9ffd648890425
|
||||
code 0802050031c931d241b8050000004531c9ff1500000000488904251002050031
|
||||
code c9ba0100000041b8010000004531c9ffd64889042518020500488b0425080205
|
||||
code 004889042588010500488b042510020500488904259001050048c74424280000
|
||||
code 0000c7442420000000004c8d056f00000031c931d24531c9ff15000000004889
|
||||
code c6ba88010500b9020000004531c041b9ffffffffff150000000089c048890425
|
||||
code 00000500488b3d000000004889f1baffffffffffd74889f1ff1500000000488b
|
||||
code 0c251002050031d2ffd789c048890425080005004883c4385f5ec30f1f440000
|
||||
code 56574883ec28be64000000488b3d0000000066666666662e0f1f840000000000
|
||||
code ffd7ffce75fa488b0c2508020500ff1500000000488b04251802050048890425
|
||||
code 900105004889042588010500488b0c2510020500ba010000004531c0ff150000
|
||||
code 000031c04883c4285f5ec30f1f4400004883ec3848c744242800000000c74424
|
||||
code 20000000004c8d05a4f7ffff31c931d24531c9ff1500000000ff150000000048
|
||||
code 83c438c36666662e0f1f8400000000004883ec3831c931d24531c04531c9ff15
|
||||
code 00000000488904250802050048c744242800000000c7442420000000004c8d05
|
||||
code 2c00000031c931d24531c9ff1500000000b903000000ff15000000004883c438
|
||||
code c36666666666662e0f1f8400000000004883ec28488b0c2508020500ba1e0000
|
||||
code 00ff150000000089c0488904250000050048c70425080005000100000031c048
|
||||
code 83c428c36666662e0f1f84000000000056574883ec3831c9ba010000004531c0
|
||||
code ff1500000000488904250802050048c744242800000000c7442420000000004c
|
||||
code 8d054a02000031c931d24531c9ff1500000000bf1e000000488b350000000090
|
||||
code ffd6ffcf75fa488b0c2508020500ff1500000000488b0c250802050031d2ff15
|
||||
code 0000000089c04889042500000500488b0425000105004889042508000500bf1e
|
||||
code 000000666666662e0f1f840000000000ffd6ffcf75fa488b0425000105004889
|
||||
code 04251000050031c931d241b8050000004531c9ff150000000048890425080205
|
||||
code 0048c744242800000000c7442420000000004c8d059701000031c931d24531c9
|
||||
code ff1500000000bf1e0000000f1f440000ffd6ffcf75fa488b0c2508020500ba01
|
||||
code 0000004531c0ff1500000000488b0c250802050031d2ff150000000089c04889
|
||||
code 042518000500488b0425000105004889042520000500bf1e0000000f1f440000
|
||||
code ffd6ffcf75fa488b042500010500488904252800050031c931d24531c04531c9
|
||||
code ff1500000000488904250802050048c744242800000000c7442420000000004c
|
||||
code 8d05ea00000031c931d24531c9ff1500000000bf1e0000000f1f840000000000
|
||||
code ffd6ffcf75fa488b0c2508020500ff1500000000488b0c250802050031d2ff15
|
||||
code 0000000089c04889042530000500488b0425000105004889042538000500bf1e
|
||||
code 000000666666662e0f1f840000000000ffd6ffcf75fa488b0425000105004889
|
||||
code 04254000050048c744242800000000c7442420000000004c8d05a2f6ffff31c9
|
||||
code 31d24531c9ff1500000000488b0c2508020500ff15000000008b042524020500
|
||||
code 4889042548000500bf1e0000000f1f00ffd6ffcf75fa8b042524020500488904
|
||||
code 25500005004883c4385f5ec30f1f40004883ec28488b0c2508020500baffffff
|
||||
code ffff150000000048ff04250001050031c04883c428c3662e0f1f840000000000
|
||||
code 5657534883ec3031c931d241b8050000004531c9ff1500000000488904250802
|
||||
code 050048c744242800000000c7442420000000004c8d0596ffffff31c931d24531
|
||||
code c9ff15000000004889c6bb1e000000488b3d00000000662e0f1f840000000000
|
||||
code ffd7ffcb75fa4889f1ff150000000089c04889042500000500488b0c25080205
|
||||
code 00ba010000004531c0ff1500000000bb1e0000006666662e0f1f840000000000
|
||||
code ffd7ffcb75fa488b0c2508020500488b3d0000000031d2ffd789c04889042508
|
||||
code 000500488b0425000105004889042510000500488b0c2508020500ba01000000
|
||||
code 4531c0ff15000000004889f1ff15000000004889f1baffffffffffd74889f1ff
|
||||
code 1500000000488b04250001050048890425180005004883c4305b5f5ec30f1f00
|
||||
code 4157415641554154565755534883ec3831c9ba010000004531c04531c9ff1500
|
||||
code 000000488904250802050048c744242800000000c7442420000000004c8d056d
|
||||
code feffff31c931d24531c9ff15000000004889c74889c1ff150000000089c6c744
|
||||
code 2434000000004c8b3500000000b94000100031d24189c041ffd64889c3b90200
|
||||
code 000031d24189f041ffd64989c6488b2d000000004889d9ffd589c04889042500
|
||||
code 0005004c8b2d0000000041ffd589c048890425080005004889d9ba01000000ff
|
||||
code 15000000004898488904251000050041ffd589c048890425180005004c8b2500
|
||||
code 0000004c8d7c24344889d94c89fa41ffd4489848890425200005008b44243448
|
||||
code 890425280005004c89f1ffd589c048890425300005004c89f1ff150000000089
|
||||
code c048890425380005004c89f14c89fa41ffd4489848890425400005004c8b3d00
|
||||
code 0000004c89f131d241ffd789c0488904254800050041ffd589c0488904255000
|
||||
code 05004c89f14c8b350000000041ffd689c04889042558000500488b0c25080205
|
||||
code 00ff15000000004889f9baffffffff41ffd74889f9ff15000000004889d941ff
|
||||
code d631c939f00f94c148890c25600005004883c4385b5d5f5e415c415d415e415f
|
||||
code c36666666666662e0f1f840000000000564883ec3048c744242800000000c744
|
||||
code 2420000000004c8d053300000031c931d24531c9ff15000000004889c64889c1
|
||||
code baffffffffff15000000004889f1ff15000000004883c4305ec3660f1f440000
|
||||
code f431c0c36666662e0f1f8400000000004157415641545657534883ec38bb3200
|
||||
code 0000488d35670000004c8b35000000004c8b3d000000004c8b25000000006690
|
||||
code 48c744242800000000c74424200000000031c931d24989f04531c941ffd64889
|
||||
code c74889c1baffffffff41ffd74889f941ffd4ffcb75ca4883c4385b5f5e415c41
|
||||
code 5e415fc36666662e0f1f8400000000005048c704240000000048833c25080105
|
||||
code 00004889e075084889042508010500488b0c250801050031d24839c10f94c248
|
||||
code 0114250001050031c059c30f1f44000056574883ec3831f631c931d24531c045
|
||||
code 31c9ff1500000000488904250802050048c744242800000000c7442420000000
|
||||
code 004c8d05d8f1ffff31c931d24531c9ff1500000000833c252402050000752831
|
||||
code f6488b3d000000000f1f840000000000488b0c2508020500ffd748ffc6833c25
|
||||
code 240205000074e98b042524020500488904250000050048893425080005004883
|
||||
code c4385f5ec366662e0f1f84000000000041565657534883ec38b928020500ff15
|
||||
code 0000000048c744242800000000c7442420000000004c8d0584000000488b3d00
|
||||
code 00000031c931d24531c9ffd74889c6488b1d000000004889c1baffffffffffd3
|
||||
code 4c8b35000000004889f141ffd6b928020500ff15000000004898488904253800
|
||||
code 050048c744242800000000c7442420000000004c8d05a600000031c931d24531
|
||||
code c9ffd74889c64889c1baffffffffffd34889f141ffd64883c4385b5f5e415ec3
|
||||
code 564883ec30c744242c00000000b928020500ff1500000000488b342538020500
|
||||
code ff150000000089c031c94839c60f94c148890c2500000500b950020500ff1500
|
||||
code 0000004c8d44242cb95802050031d24531c9ff150000000085c00f95c0837c24
|
||||
code 2c000f95c120c10fb6c1488904250800050031c04883c4305ec3660f1f440000
|
||||
code 4883ec28c744242400000000b928020500ff1500000000489848890425100005
|
||||
code 00b950020500ff15000000000fb6c04889042518000500b950020500ff150000
|
||||
code 00000fb6c04889042520000500b95802050031d24531c0ff1500000000489848
|
||||
code 89042528000500488d442424488904253000050031c04883c428c30f1f440000
|
||||
code 41574156415541545657534883ec304531f6ba0000010031c941b80030000041
|
||||
code b904000000ff15000000004889c6488d3d7b0000004c8b3d000000004c8b2500
|
||||
code 0000004c8b2d00000000660f1f4400004e8d0c3648c744242800000000c74424
|
||||
code 200000000031c931d24989f841ffd74889c34889c1baffffffff41ffd44889d9
|
||||
code 41ffd548ff0425000105004983c6084981fe409c000075b84883c4305b5f5e41
|
||||
code 5c415d415e415fc30f1f8400000000004883ec28c7442424000000004c8d4424
|
||||
code 2431d24531c9ff150000000031c04883c428c3666666662e0f1f840000000000
|
||||
code 56574883ec38c74424340000000048c744242800000000c7442420000000004c
|
||||
code 8d058a00000031c931d24531c9ff15000000004889c6488b3d000000004889c1
|
||||
code baffffffffffd74889f1ff1500000000488b0c258801050031d2ffd789c04889
|
||||
code 042530000500488b0c2588010500488d542434ff15000000008b442434488904
|
||||
code 253800050048c7c1feffffffff1500000000489848890425400005004883c438
|
||||
code 5f5ec3666666662e0f1f840000000000564883ec5048c744244000000000c744
|
||||
code 244c00000000c744243002000000c744242800000000c7442420000000004c8d
|
||||
code 4c244048c7c1ffffffff48c7c2feffffff49c7c0ffffffffff15000000004898
|
||||
code 4889042500000500488b4c2440ff150000000089c6ff150000000031c939c60f
|
||||
code 94c148890c2508000500488b4c244031d2ff150000000089c048890425100005
|
||||
code 00488b4c2440488d54244cff150000000085c00f95c0817c244c030100000f94
|
||||
code c120c10fb6c1488904251800050048c7c1feffffffba02000000ff1500000000
|
||||
code 48984889042520000500ff150000000089c04889042528000500488b44244048
|
||||
code 89042588010500b82c0000004883c4505ec366666666662e0f1f840000000000
|
||||
code 564883ec3048c744242800000000c7442420000000004c8d0533000000ba0010
|
||||
code 000041b9c800000031c9ff15000000004889c64889c1baffffffffff15000000
|
||||
code 004889f1ff15000000004883c4305ec34883ec2848c744242000000000488d54
|
||||
code 24204889142508010500e8010c00004889042500000500b8010000004883c428
|
||||
code c36666666666662e0f1f840000000000564883ec3048c744242800000000c744
|
||||
code 2420000001004c8d05a3ffffffba0010000041b9c800000031c9ff1500000000
|
||||
code 4889c64889c1baffffffffff15000000004889f1ff15000000004883c4305ec3
|
||||
code 564883ec3048b90000000006000000ba0000010041b80030000041b904000000
|
||||
code ff1500000000488904250000050048c744242800000000c7442420000000004c
|
||||
code 8d05faebffff31c931d24531c9ff15000000004889c631c04885f60f95c04889
|
||||
code 0425080005004889f1baffffffffff15000000004889f1ff15000000008b0425
|
||||
code 2402050048890425100005004883c4305ec366666666662e0f1f840000000000
|
||||
code 564883ec3048c744242800000000c7442420000000004c8d053300000031c931
|
||||
code d24531c9ff15000000004889c64889c1baffffffffff15000000004889f1ff15
|
||||
code 000000004883c4305ec3660f1f44000056574883ec2848c74424200000000048
|
||||
code 8d7424204881e6000000ff488d8e00100000488b3d0000000031d241b8008000
|
||||
code 00ffd7489848890425000005004881ce0000f0004889f131d241b800800000ff
|
||||
code d74898488904250800050031c04883c4285f5ec36666662e0f1f840000000000
|
||||
code 4157415641545657534883ec38c74424340000000031c931d24531c04531c9ff
|
||||
code 1500000000488904250802050048c744242800000000c7442420000000004c8d
|
||||
code 058b02000031c931d24531c9ff15000000004889c7be1e000000488b1d000000
|
||||
code 006666666666662e0f1f840000000000ffd3ffce75fa4c8b25000000004889f9
|
||||
code ba3c00000041ffd4489848890425000005004c8b3d00000000488d7424344889
|
||||
code f94889f241ffd78b4424344889042508000500488b0c2508020500ff15000000
|
||||
code 00488b0c25080205004c8b350000000031d241ffd689c0488904251000050048
|
||||
code c744242800000000c7442420040000004c8d05d9010000488b1d0000000031c9
|
||||
code 31d24531c9ffd34889c74889c1ba3e00000041ffd44898488904251800050048
|
||||
code 89f9baffffffff41ffd689c0488904252000050048c744242800000000c74424
|
||||
code 20000000004c8d05b401000031c931d24531c9ffd34889c74889c1baffffffff
|
||||
code 41ffd64889f94889f241ffd78b44243448890425280005008b04252402050048
|
||||
code 89042530000500488b350000000031c931d24531c0ffd6488904258801050031
|
||||
code c931d24531c0ffd6488904259001050048c744242800000000c7442420000000
|
||||
code 004c8d056801000031c931d24531c9ffd34889c64889c1baffffffff41ffd648
|
||||
code 89f1ff1500000000488b3500000000ba88010500b90200000041b80100000041
|
||||
code b9ffffffffffd689c04889042538000500488b0c2588010500488b3d00000000
|
||||
code ffd7488b0c2590010500ffd7ba88010500b90200000041b80100000041b9ffff
|
||||
code ffffffd689c0488904254000050048c744242800000000c7442420040000004c
|
||||
code 8d057ae8ffff31c931d24531c9ffd34889c6bf7e000000488b1d000000006690
|
||||
code 4889f1ffd3ffcf75f74889f1ff150000000089c04889042548000500ff150000
|
||||
code 000089c048890425500005004889f131d2ff15000000004883c4385b5f5e415c
|
||||
code 415e415fc366662e0f1f8400000000004883ec28488b0c2508020500baffffff
|
||||
code ffff1500000000c70425240205000900000031c04883c428c30f1f8000000000
|
||||
code 4883ec2848c7c1feffffffba3d000000ff1500000000c7042524020500090000
|
||||
code 0031c04883c428c30f1f8400000000004883ec28ba88010500b90200000041b8
|
||||
code 0100000041b9ffffffffff150000000031c04883c428c3660f1f840000000000
|
||||
code 4883ec28ff1500000000890425200205008b0c2520020500ba4d000000ff1500
|
||||
code 000000b958000000ff150000000048c744242000000000488b442420483db70b
|
||||
code 0000771e6666662e0f1f84000000000048ff442420488b442420483db80b0000
|
||||
code 72eeff150000000089c048890425000005008b0c2520020500ff150000000048
|
||||
code 890425080005004883c428c30f1f4000564883ec3031c9ba010000004531c045
|
||||
code 31c9ff1500000000488904250802050048c744242800000000488b442428483d
|
||||
code e70300007726488b35000000000f1f00488b0c2508020500ffd648ff44242848
|
||||
code 8b442428483de803000072e44883c4305ec366666666662e0f1f840000000000
|
||||
code 41565657534883ec3848c744242800000000c7442420000000004c8d056f0000
|
||||
code 00488b3d0000000031c931d24531c9ffd74889c6488b1d000000004889c1baff
|
||||
code ffffffffd34c8b35000000004889f141ffd648c744242800000000c744242000
|
||||
code 0000004c8d054600000031c931d24531c9ffd74889c64889c1baffffffffffd3
|
||||
code 4889f141ffd64883c4385b5f5e415ec34883ec28b950020500ff150000000031
|
||||
code c04883c428c3662e0f1f8400000000004883ec28b950020500ff1500000000c7
|
||||
code 04252402050001000000b8010000004883c428c36666662e0f1f840000000000
|
||||
code 41565657534883ec3848c744242800000000c7442420000000004c8d059f0000
|
||||
code 00488b3d0000000031c931d24531c9ffd74889c6488b1d000000004889c1baff
|
||||
code ffffffffd34c8b35000000004889f141ffd6b950020500ff15000000000fb6c0
|
||||
code 4889042500000500b950020500ff15000000000fb6c0488904250800050048c7
|
||||
code 44242800000000c7442420000000004c8d054a00000031c931d24531c9ffd748
|
||||
code 89c64889c1baffffffffffd34889f141ffd64883c4385b5f5e415ec30f1f4000
|
||||
code 4883ec28b950020500ff150000000031c04883c428c3662e0f1f840000000000
|
||||
code 4883ec28b950020500ff1500000000c704252402050001000000b80100000048
|
||||
code 83c428c36666662e0f1f84000000000056574883ec3831c931d24531c04531c9
|
||||
code ff1500000000488904250802050048c744242800000000c7442420000000004c
|
||||
code 8d058a00000031c931d24531c9ff15000000004889c6c7042524020500010000
|
||||
code 00488b0c2508020500488b3d00000000ba32000000ffd789c048890425000005
|
||||
code 004889f1baffffffffffd789c04889042508000500488b0c250802050031d2ff
|
||||
code d789c04889042510000500488b0c250802050031d2ffd789c048890425180005
|
||||
code 004883c4385f5ec30f1f84000000000056574883ec28833c252402050000751c
|
||||
code 488b3500000000660f1f840000000000ffd6833c25240205000074f4be1e0000
|
||||
code 00488b3d000000000f1f840000000000ffd7ffce75fab800000600b964000000
|
||||
code ffd0488b0c2508020500ff150000000031c04883c4285f5ec30f1f8000000000
|
||||
code 4883ec2831c9ba010000004531c04531c9ff1500000000488904250802050048
|
||||
code 89042588010500ba88010500b90100000041b80100000041b9e8030000ff1500
|
||||
code 00000089c0488904250000050048c7042508000500010000004883c428c36690
|
||||
code 564883ec30ff150000000089c6b94000000031d24189c0ff150000000031c948
|
||||
code 85c00f95c148890c25000005004189f148c744242800000000c7442420000000
|
||||
code 004c8d053800000031c931d2ff150000000031c94885c00f95c148890c250800
|
||||
code 0500b903000000ff15000000004883c4305ec3666666662e0f1f840000000000
|
||||
code 5657534883ec204889cebf1e000000488b1d00000000662e0f1f840000000000
|
||||
code ffd3ffcf75fab94000000031d24189f0ff15000000004889042510000500ff15
|
||||
code 0000000089c0488904251800050031c04883c4205b5f5ec30f1f840000000000
|
||||
code 5657534883ec40c744243c0000000031c9ba010000004531c04531c9ff150000
|
||||
code 0000488904250802050048c744242800000000c744242000000000488d359e00
|
||||
code 0000488b3d0000000031c931d24989f04989c1ffd74889042588010500488b1d
|
||||
code 000000004889c1baffffffffffd389c048890425000005004c8b0c2508020500
|
||||
code 48c744242800000000c74424200000000031c931d24989f0ffd7488904259001
|
||||
code 05004889c1bae8030000ffd389c04889042508000500488b0c2590010500488d
|
||||
code 54243cff15000000008b44243c48890425100005004883c4405b5f5ec30f1f00
|
||||
code ba3200000048ff25000000000f1f40004883ec38b810000600ffd048c7442428
|
||||
code 00000000c7442420000000004c8d053dd3ffff41b96100000031c931d2ff1500
|
||||
code 0000004889c1baffffffffff150000000089c048890425080005004883c438c3
|
||||
code 4881ec2802000048894c242048ff042500000500488d4c2420e8e2ffffff4803
|
||||
code 4424204881c428020000c30f1f4400004881ec2802000048894c242048895424
|
||||
code 284885c9741a48ffc9488d542420e8ddffffff48034424204881c428020000c3
|
||||
code 488d442420488904251001050031c04881c428020000c3
|
||||
@@ -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))
|
||||
);
|
||||
}
|
||||
@@ -96,7 +96,9 @@ def cases():
|
||||
out += ["mov ah, bl", "mov dl, ch", "mov bh, 0x21", "xchg ah, bl", "mov sil, dil",
|
||||
"movabs r15, 0x8877665544332211", "mov rcx, -2", "bswap ebx", "bswap r9",
|
||||
"cbw", "cwde", "cdqe", "cwd", "cdq", "cqo", "clc", "stc", "cmc", "nop", "cpuid",
|
||||
"nop dword ptr [rax + 8]", "pause", "push r9", "push rbx", "push -5", "push 0x12345678",
|
||||
"nop dword ptr [rax + 8]", "pause", "lfence", "mfence", "sfence",
|
||||
f"movnti {mem(32)}, ebx", f"movnti {mem(64)}, rbx",
|
||||
f"movnti {mem(32)}, r9d", f"movnti {mem(64)}, r14", "push r9", "push rbx", "push -5", "push 0x12345678",
|
||||
f"push {mem(64)}", "pop rbx", "pop r12", f"pop {mem(64)}", "leave"]
|
||||
# The accumulator short form of XCHG: 91..97, and 90 with REX.B.
|
||||
for index in range(1, 16):
|
||||
|
||||
@@ -1117,6 +1117,13 @@ f5 | cmc
|
||||
0f a2 | cpuid
|
||||
0f 1f 40 08 | nop dword ptr [rax + 8]
|
||||
f3 90 | pause
|
||||
0f ae e8 | lfence
|
||||
0f ae f0 | mfence
|
||||
0f ae f8 | sfence
|
||||
0f c3 5c be 10 | movnti dword ptr [rsi + 4*rdi + 16], ebx
|
||||
48 0f c3 5c be 10 | movnti qword ptr [rsi + 4*rdi + 16], rbx
|
||||
44 0f c3 4c be 10 | movnti dword ptr [rsi + 4*rdi + 16], r9d
|
||||
4c 0f c3 74 be 10 | movnti qword ptr [rsi + 4*rdi + 16], r14
|
||||
41 51 | push r9
|
||||
53 | push rbx
|
||||
6a fb | push -5
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -637,7 +637,8 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
..none
|
||||
})
|
||||
}
|
||||
"mov" | "movabs" => {
|
||||
// MOVNTI stores like MOV; the non-temporal hint changes no result.
|
||||
"mov" | "movabs" | "movnti" => {
|
||||
let value = read(m, places[1], bits);
|
||||
write(m, places[0], value);
|
||||
Outcome::Done(none)
|
||||
@@ -738,7 +739,8 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
m.flags.cf = !m.flags.cf;
|
||||
Outcome::Done(none)
|
||||
}
|
||||
"nop" | "pause" => Outcome::Done(none),
|
||||
// The fences order memory accesses and compute nothing.
|
||||
"nop" | "pause" | "lfence" | "mfence" | "sfence" => Outcome::Done(none),
|
||||
"cpuid" => {
|
||||
// Xenora's guest CPUID contract, restated: the vendor "Xenora guest"
|
||||
// and the four features whose every instruction exists, CMOV and
|
||||
@@ -1234,6 +1236,10 @@ fn undeclared_and_ambiguous_encodings_are_rejected() {
|
||||
&[0x66, 0x63, 0xC1], // 16-bit movsxd
|
||||
&[0xF3, 0x41, 0x90], // F3 on xchg r8, rax
|
||||
&[0x8D, 0xC0], // lea with a register operand
|
||||
&[0x0F, 0xAE, 0x2E], // 0F AE /5 with a memory operand
|
||||
&[0x0F, 0xAE, 0x36], // 0F AE /6 with a memory operand
|
||||
&[0x0F, 0xC3, 0xC1], // movnti with a register destination
|
||||
&[0x66, 0x0F, 0xC3, 0x06], // 66 with movnti
|
||||
&[0x0F, 0xA3, 0x06], // bt [rsi], eax
|
||||
&[0xC6, 0xC8, 0x01], // C6 /1
|
||||
&[0xFF, 0xF8], // FF /7
|
||||
|
||||
@@ -108,6 +108,7 @@ movups = { ref = "sdm MOVUPS" }
|
||||
movdqa = { ref = "sdm MOVDQA" }
|
||||
movdqu = { ref = "sdm MOVDQU" }
|
||||
movntdq = { ref = "sdm MOVNTDQ" }
|
||||
movnti = { ref = "sdm MOVNTI" }
|
||||
movntps = { ref = "sdm MOVNTPS/MOVNTPD" }
|
||||
movss = { ref = "sdm MOVSS" }
|
||||
movsd = { ref = "sdm MOVSD (scalar double)" }
|
||||
@@ -185,6 +186,9 @@ shufpd = { ref = "sdm SHUFPD" }
|
||||
pinsrw = { ref = "sdm PINSRW" }
|
||||
pextrw = { ref = "sdm PEXTRW" }
|
||||
ldmxcsr = { ref = "sdm LDMXCSR" }
|
||||
lfence = { ref = "sdm LFENCE" }
|
||||
mfence = { ref = "sdm MFENCE" }
|
||||
sfence = { ref = "sdm SFENCE" }
|
||||
stmxcsr = { ref = "sdm STMXCSR" }
|
||||
|
||||
# Floating point. Every form can raise a SIMD floating-point exception.
|
||||
@@ -950,6 +954,14 @@ size = "x"
|
||||
src = "x"
|
||||
memory_only = true
|
||||
|
||||
[[form]]
|
||||
op = "movnti"
|
||||
map = "0f"
|
||||
opcode = 0xC3
|
||||
enc = "rm_reg"
|
||||
size = "y"
|
||||
memory_only = true
|
||||
|
||||
[[form]]
|
||||
op = "movntps"
|
||||
map = "0f"
|
||||
@@ -1967,6 +1979,36 @@ size = "n"
|
||||
src = "d"
|
||||
memory_only = true
|
||||
|
||||
# The fences are the register forms of digits 5 to 7; the r/m field is ignored.
|
||||
# The memory forms of those digits (the XSAVE family and CLFLUSH) are not
|
||||
# declared.
|
||||
[[form]]
|
||||
op = "lfence"
|
||||
map = "0f"
|
||||
opcode = 0xAE
|
||||
digit = 5
|
||||
enc = "rm_unread"
|
||||
size = "n"
|
||||
register_only = true
|
||||
|
||||
[[form]]
|
||||
op = "mfence"
|
||||
map = "0f"
|
||||
opcode = 0xAE
|
||||
digit = 6
|
||||
enc = "rm_unread"
|
||||
size = "n"
|
||||
register_only = true
|
||||
|
||||
[[form]]
|
||||
op = "sfence"
|
||||
map = "0f"
|
||||
opcode = 0xAE
|
||||
digit = 7
|
||||
enc = "rm_unread"
|
||||
size = "n"
|
||||
register_only = true
|
||||
|
||||
# SSE and SSE2 floating-point forms. RCP and RSQRT approximations are not
|
||||
# architecturally exact and are left out.
|
||||
|
||||
|
||||
+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),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,7 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
|
||||
- [Guest experiment guide](../experiments/x1/README.md) — Bounded x86-64 execution, executable loading, experimental services, native compute, and offscreen rendering.
|
||||
- [x86-64 instruction registry](cpu/instruction-registry.md) — Shared decoder, generated tables, semantics, native lowering and how to add a verified instruction form.
|
||||
- [Runtime service registry](runtime/registry.md) and [generated coverage](runtime/services.md) — Import resolution, typed Win64 adapters and how to add a tested service.
|
||||
- [Guest threads](runtime/threads.md) — Deterministic scheduler, thread services, limits and tests.
|
||||
- [Guest CPU research](research/cpu-boundary.md) — Public specifications and unresolved console requirements.
|
||||
- [Synthetic import fixtures](../tests/compat_fixtures/README.md) — Reproducible PE32+ builds and expected service behavior.
|
||||
|
||||
@@ -43,6 +44,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.
|
||||
|
||||
@@ -60,6 +60,14 @@ These rules hold for both engines and are what a guest scheduler has to preserve
|
||||
|
||||
The SDM cases for these forms in `tests/cpu_known_answers.rs` were written before this implementation, by another contributor. `tests/x86_atomic.rs` adds the LOCK rules, both compare outcomes at every width, unaligned operands and faults. None of it has been compared with x86 hardware, and nothing here establishes multi-thread behaviour.
|
||||
|
||||
## Memory ordering and fences
|
||||
|
||||
Guest memory accesses are totally ordered today. Each engine runs one guest instruction at a time on one host thread, and every load and store of an instruction completes before the next instruction starts. There is no store buffer and nothing is reordered, so a load always sees the latest earlier store. That is stronger than the ordering the Intel SDM (Vol. 3A, "Memory Ordering") gives a real processor, where a store may sit in a buffer while later loads from other locations run.
|
||||
|
||||
MFENCE, LFENCE and SFENCE (`0F AE` with a register ModRM byte and digit 6, 5 or 7; the SDM states that the r/m field is ignored) are therefore accepted and change no register, flag or memory. They have nothing left to enforce. Non-temporal stores are ordinary stores, so SFENCE has no weakly ordered store to wait for either. The memory forms that share those digits, the XSAVE family and CLFLUSH, stay rejected.
|
||||
|
||||
This holds only while guest threads do not run on several host threads. ARM64 orders memory more weakly than x86, so an engine that ran guest threads in parallel would have to restore x86's ordering for ordinary accesses and give the fences a real effect. Nothing here provides or tests that. `tests/cpu_known_answers.rs` holds the single-thread cases: a store, a fence and a later load in program order, and no change to any other state. None of it has been compared with x86 hardware.
|
||||
|
||||
## String instructions
|
||||
|
||||
MOVS and STOS exist for 8-, 16-, 32- and 64-bit elements, alone and with REP (F3), together with the direction flag and CLD and STD. `CpuState::df` holds the flag. It is not one of the six status flags the registry tracks.
|
||||
@@ -86,7 +94,7 @@ CPUID (`0F A2`) returns a fixed table that never reads the host. It describes a
|
||||
|
||||
A feature bit is set only when every instruction of that feature is implemented. That is stricter than "some of it works", and it has consequences:
|
||||
|
||||
- SSE and SSE2 are not reported, although most of their instructions exist, because parts are still rejected: RSQRTPS and MFENCE, for example. BMI1 is not reported although TZCNT exists, because ANDN does not. The x87 FPU, MMX, FXSAVE, CMPXCHG8B, the time-stamp counter, LAHF and SYSRET are absent too.
|
||||
- SSE and SSE2 are not reported, although most of their instructions exist, because parts are still rejected: RSQRTPS and MASKMOVDQU, for example. BMI1 is not reported although TZCNT exists, because ANDN does not. The x87 FPU, MMX, FXSAVE, CMPXCHG8B, the time-stamp counter, LAHF and SYSRET are absent too.
|
||||
- The table is therefore truthful about Xenora, not plausible as hardware: every real 64-bit processor reports the FPU and SSE2. A guest that tests a bit before using a feature avoids it; a guest that assumes SSE2 because it runs in 64-bit mode still gets every form that exists and an illegal-instruction exit for one that does not.
|
||||
- A leaf that is not listed returns zeros, whatever the subleaf. Intel processors answer a leaf above the highest basic one with that leaf's data instead; software is expected to read the highest leaf first.
|
||||
|
||||
@@ -96,4 +104,4 @@ A feature bit is set only when every instruction of that feature is implemented.
|
||||
|
||||
## Rejected on purpose
|
||||
|
||||
LOCK except as described above, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, SHLD, SHRD, LODS, CMPS, SCAS, REPE and REPNE, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B, CMPXCHG16B and fences. The DBT also refuses raw SYSCALL.
|
||||
LOCK except as described above, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, SHLD, SHRD, LODS, CMPS, SCAS, REPE and REPNE, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B and CMPXCHG16B. The DBT also refuses raw SYSCALL.
|
||||
+4
-4
@@ -254,7 +254,7 @@ created with default security attributes. `SetEvent` signals an event,
|
||||
`ResetEvent` clears it, and `CloseHandle` invalidates the handle.
|
||||
`WaitForSingleObject` consumes an auto-reset signal once, leaves a manual-reset
|
||||
signal set, and reports `WAIT_TIMEOUT` when a zero-timeout poll finds no signal.
|
||||
A wait that would block returns `WAIT_FAILED` with `ERROR_NOT_SUPPORTED`.
|
||||
Without an attached thread scheduler, a wait that would block returns `WAIT_FAILED` with `ERROR_NOT_SUPPORTED`; with one it blocks the calling guest thread ([guest threads](runtime/threads.md)).
|
||||
Thread and event handles are distinct types in the same bounded table.
|
||||
Event duplicates share signal state and keep the event alive independently.
|
||||
A duplicate can retain or reduce its rights. Waiting requires synchronize
|
||||
@@ -280,15 +280,15 @@ thread, identified by its TEB. The owner can acquire the mutex again, and
|
||||
each acquisition needs a matching `ReleaseMutex`. Another thread sees the
|
||||
mutex as unsignaled. A release by a thread that is not the owner fails with
|
||||
`ERROR_NOT_OWNER`. Waits, duplicates and wait-all treat mutexes like the
|
||||
other waitable objects. Abandonment on thread exit is not modeled, because
|
||||
guest threads do not exit yet.
|
||||
other waitable objects. A mutex whose owner thread ended
|
||||
is reported once as abandoned.
|
||||
|
||||
See Microsoft's [event object documentation](https://learn.microsoft.com/windows/win32/sync/event-objects).
|
||||
|
||||
### Locks, one-time initialization and thread-local storage
|
||||
|
||||
These services keep their state in the runtime and key ownership by guest
|
||||
TEB. There is no guest scheduler, so any call that would block stops the
|
||||
TEB. These objects do not block through the guest scheduler yet, so any call that would block stops the
|
||||
guest with the runtime-limit fault (`IllegalInstruction(0xFE)`) rather than
|
||||
reporting success. Guest code reaches that fault by entering a critical
|
||||
section owned by another thread, acquiring a held SRW lock, or beginning a
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
# Guest threads
|
||||
|
||||
`crates/loader/src/scheduler.rs` runs guest threads deterministically on one host thread. A guest thread is a CPU context, a guarded stack and a TEB; it is never a host thread. Guest threads never execute at the same time, so no guest memory-ordering model is relied on (#199).
|
||||
|
||||
## Scheduling
|
||||
|
||||
- Threads run in first-in, first-out order for a quantum of guest instructions. A turn ends at the first translated-block boundary that reaches the quantum, so small quanta do not compile extra blocks.
|
||||
- The same program, quantum and clock always interleave the same way.
|
||||
- A service that has to wait returns `GuestBlocked` with no effect and RIP still on its trampoline. The scheduler runs the call again at each turn, oldest waiter first. Each retry counts towards the instruction budget, and so does every call that ends a turn.
|
||||
- A timed wait is over once its deadline has passed. An object signaled after that stays signaled.
|
||||
- Signaling an event, semaphore or mutex stops the caller so that waiters are served first. It keeps what is left of its turn and cannot renew it, so repeated signals do not starve other threads.
|
||||
- With nothing ready and budget left, the clock sleeps until the earliest deadline. With no deadline either, the run ends with `Outcome::Deadlock` and the blocked and suspended thread IDs.
|
||||
- A fault in any thread ends the run with `Outcome::Fault` and that thread's ID. HLT ends the process only in the main thread.
|
||||
|
||||
## Memory
|
||||
|
||||
Each thread slot at `0x6_0000_0000 + n * 0x100_0000` holds a guard page, the stack, a guard page and the TEB. Stacks reserve 256 KiB by default, whatever the PE header asks. A nonzero size without `STACK_SIZE_PARAM_IS_A_RESERVATION` is an initial commitment and keeps at least that reservation; with the flag it is the reservation, rounded up to 64 KiB and at most 8 MiB. At most 64 threads live at once, the main thread included, and all thread memory together is bounded by 64 MiB. The guest cannot free it, and a slot the guest has mapped something into is skipped.
|
||||
|
||||
Ending a thread releases its memory and slot and drops its last error, TLS and FLS values, callback frames and pending wait. A 4-byte `errno` cell per used slot stays mapped and is zeroed for the next thread. Critical sections, SRW locks and one-time initializations it held stay held by nobody, so a thread that reuses its TEB address does not inherit them. A run keeps the main thread's state, so one that stopped on its budget can continue if no other thread was alive; a wait it was in continues with the same objects and deadline when the run starts from the reported main thread context, and is dropped otherwise. Thread IDs are never reused.
|
||||
|
||||
## Services
|
||||
|
||||
`CreateThread`, `ExitThread`, `TerminateThread`, `GetExitCodeThread`, `SuspendThread`, `ResumeThread`, `SwitchToThread`, and thread handles in `GetThreadId`, `OpenThread`, `DuplicateHandle`, `CloseHandle`, `WaitForSingleObject` and `WaitForMultipleObjects`. Blocking waits with timeouts work for threads, events, semaphores and mutexes. A wait keeps the objects it was given when it blocked. A mutex whose owner ended is reported once as abandoned.
|
||||
|
||||
All are partial. Without an attached scheduler `CreateThread` fails with `ERROR_NOT_SUPPORTED` and waits behave as before.
|
||||
|
||||
## Not supported
|
||||
|
||||
- Blocking on critical sections, SRW locks and one-time initialization still stops the guest, and a condition-variable sleep with a timeout still fails with `ERROR_NOT_SUPPORTED`. These are the second part of #323.
|
||||
- `Sleep`, `XTaskQueueDispatch` and `WSAPoll` still delay every guest thread. `XTaskQueueDispatch` uses host time, so interleaving is not deterministic across it.
|
||||
- The mock clock advances only when nothing can run or a service sleeps, so a guest that spins until a timed wait expires uses up its budget.
|
||||
- PE static TLS and DLL thread-attach and detach callbacks for new threads, and FLS callbacks at thread exit.
|
||||
- Waiting on a handle to the main thread or on a pseudo handle, thread priorities of worker threads, APCs and alertable waits, security attributes and inherited handles.
|
||||
- A wait is not satisfied while its thread is suspended.
|
||||
- Faults are not delivered to the guest (no SEH).
|
||||
|
||||
## Tests
|
||||
|
||||
`crates/loader/tests/runtime_threads.rs` runs C programs from `tests/threads/program.c`, compiled for x86-64 Windows by `compile.py` with clang, as translated guest code at several quanta. `compile.py --check` rebuilds the committed listing.
|
||||
@@ -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
|
||||
Reference in new issue
Block a user