Compare commits

..
Author SHA1 Message Date
Ranveer Soni 82cafe9664 Merge branch 'main' into task/198-changelog-entry 2026-11-24 21:33:31 +05:30
Ranveer Soni bf2c279dc7 Merge pull request #322 from zachdoxsee/task/130-cpuid-contract
loader: add CPUID with a truthful guest feature contract (#130)
2026-11-24 21:33:00 +05:30
zachdoxsee da16b36499 loader: add CPUID with a truthful guest feature contract (#130)
CPUID returns a fixed table that never reads the host: a synthetic
vendor, and a feature bit only when every instruction of that feature
is implemented. Today that is CMOV, POPCNT, LZCNT and long mode. SSE
and SSE2 stay unreported while parts of them are rejected. Unlisted
leaves return zeros.

tests/cpu_features.rs pins every leaf in both engines, requires each
reported feature's instruction set among the executed fixtures, and
holds a refused witness instruction for each unreported feature, so a
bit cannot be set early or forgotten later.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 16:59:50 +01:00
zachdoxsee 061568a6ee changelog: restore the XADD, CMPXCHG and LOCK entry (#198)
The merge of main into the branch of #320 kept only main's side of the
changelog conflict, so the entry for that change did not reach main.
Put it back. No code changes.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 16:58:07 +01:00
Ranveer Soni a03188315d Merge pull request #320 from zachdoxsee/task/198-atomic-rmw
loader: add XADD, CMPXCHG and LOCK on their memory forms (#198)
2026-11-24 21:25:42 +05:30
Ranveer Soni 95f6b52d9f Merge branch 'main' into task/198-atomic-rmw 2026-11-24 21:24:32 +05:30
Ranveer Soni 7499d6f6c3 Merge pull request #318 from elforeign/task/215-vop1-xlate
isa, decoder, shader: the six VOP1 integer forms through the semantic registry, Metal-verifying the B3 oracle (#215)
2026-11-24 21:22:04 +05:30
zachdoxsee 3a3f0c52af loader: add XADD, CMPXCHG and LOCK on their memory forms (#198)
Declare XADD and CMPXCHG in the instruction registry for 8- to 64-bit
register and memory destinations. The LOCK prefix is accepted on the
forms the registry marks lockable and only with a memory destination;
every other use stays an illegal instruction.

Both engines run the new forms on the shared semantics. A failed
CMPXCHG still writes its destination, so it faults on memory that
cannot be written, and a fault changes nothing. The registry document
states the ordering, alignment, compare-failure and fault rules a guest
scheduler has to preserve. Nothing is lowered to ARM64 atomics.

Fourteen SDM-derived cases already in cpu_known_answers.rs move from
refused to verified. Adds 62 LLVM-assembled fixtures with reference
arms, generator checks for the lock key and tests/x86_atomic.rs.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 16:46:01 +01:00
elforeign 989bb79d6c Merge remote-tracking branch 'origin/main' into task/215-vop1-xlate
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	crates/isa/generate_semantics.py
#	crates/isa/src/semantics_gen.rs
#	crates/shader/src/lib.rs
#	docs/shaders/semantic-coverage.md
#	docs/shaders/semantic-registry.md
2026-11-24 09:45:44 -06:00
elforeign d157f802d3 docs: record the VOP1 integer Metal readback (#215)
scripts/test-gpu.sh now runs the oracle on native Metal: 752 cases in
613 programs pass under API and shader validation. Also states which half
of the oracle checks values and which checks rejection offsets (review nit).

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 09:44:19 -06:00
Ranveer Soni fb0544652b Merge pull request #317 from elforeign/task/215-smov
isa, decoder, shader: move s_mov_b32 into the semantic registry (#215)
2026-11-24 21:13:46 +05:30
elforeign 61943d23b6 Merge remote-tracking branch 'origin/main' into task/215-vop1-xlate
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 09:42:01 -06:00
elforeign 947d6e4eaf isa, decoder, shader: the six VOP1 integer forms through the semantic registry (#215)
The B3 oracle (#309) checks v_not_b32, v_bfrev_b32, v_ffbh_u32,
v_ffbl_b32, v_ffbh_i32 and v_swap_b32 against the guide on both CPU
interpreters, but its native Metal half was skipped because the
translator did not accept the forms. This adds the VOP1 registry file and
operand rule, decoder dispatch, IR and MSL lowering (v_swap_b32 writes
both VGPRs, each merged under EXEC), fixture and goldens, and removes
the oracle's skip from scripts/test-gpu.sh.

A new CPU test checks that the compiler accepts every case of the
oracle and rejects each of its rejections at the same word.
v_mov_b32 stays hand-written.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 09:41:08 -06:00
elforeign bdcdd57c55 docs: s_mov_b32 is now a registry SOP1 form (#215)
Review finding: the scalar ALU page still called it hand-written.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 09:39:39 -06:00
elforeign 5b894777ce Merge remote-tracking branch 'origin/main' into task/215-smov 2026-11-24 09:37:41 -06:00
elforeign dc44c5c64b isa, decoder, shader: move s_mov_b32 into the semantic registry (#215)
s_mov_b32 was the last hand-written SOP1 decode path. It becomes
ScalarUnaryOp::MovB32 under a new sop1_move operand rule that matches the
old hand-written domain exactly (it accepts more SDST and SSRC0 classes
than sop1_sgpr, which other unary forms keep).

A decode sweep of 33,664 s_mov_b32 words shows no behaviour change: the
21,010 accepted words differ only in the instruction's name and the 12,654
rejections are identical. IR and MSL goldens are unchanged.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 09:37:41 -06:00
Ranveer Soni b9f6985d57 Merge pull request #315 from zachdoxsee/task/244-delay-imports
loader: report delay-loaded PE imports in the static probe (#244)
2026-11-24 21:01:45 +05:30
zachdoxsee db40a1307d loader, cli: bound delay-load tables by their declared size (#244)
Address review on the delay-import probe change:

- Read only descriptors inside the delay import directory's declared
  size, and require that size to hold the terminating empty descriptor.
- Require each descriptor's DLL name, import address table and import
  name table to be present and to start in section data, with a
  diagnostic naming the missing field.
- Leave delayed rows out of the xenora imports sync backlog, so its
  totals stay ordinary-only.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 16:28:02 +01:00
zachdoxsee b174b45bed loader: report delay-loaded PE imports in the static probe (#244)
Read the PE32+ delay-load directory (data directory 13) with a bounded
parser and list each delay-loaded import in imports.csv, marked by a new
import_table column. Ordinary totals and missing_imports.csv are
unchanged; the JSON report counts delayed slots and DLLs separately and
carries a diagnostic for truncated, out-of-range or unsupported tables.

Adds an original fixture with ordinary and delayed imports, generated by
fixtures/pe/delay-imports.py and cross-checked with llvm-readobj.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 16:25:14 +01:00
Ranveer Soni 7504a5d48d Merge pull request #305 from LanaCodes-Boop/runtime/last-error-per-thread
loader: retire a guest thread's last error and test the per-TEB contract (#202)
2026-11-24 20:53:03 +05:30
Ranveer Soni 2b858ab7c6 Merge branch 'main' into runtime/last-error-per-thread 2026-11-24 20:52:39 +05:30
Ranveer Soni 076f3e52aa Merge pull request #313 from elforeign/task/215-gpu-skip
scripts: restore the VOP1 oracle's GPU gate skip (#215)
2026-11-24 20:51:33 +05:30
Ranveer Soni e17e3bfc63 Merge pull request #314 from elforeign/task/215-sopk-oracle
isa, decoder, shader, ref: the sixteen SOPK integer forms through the semantic registry (#215)
2026-11-24 20:50:46 +05:30
Ranveer Soni 1915e2374c Merge pull request #297 from Swastickc/task/196-bit-scan-bit-test
loader: lower BSF, BSR and register BT in the ARM64 DBT (#196)
2026-11-24 20:49:54 +05:30
LanaCodes-Boop d5514aa9d8 Merge main into runtime/last-error-per-thread
Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>
2026-11-24 12:10:25 -03:00
LanaCodes-Boop 7623fde0e7 loader: retire a guest thread's last error and test the per-TEB contract (#202)
main keeps the last error per TEB since #310. This adds the missing
retirement step, so a reused TEB address starts at zero, and two
conformance tests: a successful call keeps a nonzero error, and one
thread's failure does not reach another.

Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>
2026-11-24 12:10:20 -03:00
LanaCodes-Boop 3a14bd98ab Merge main into runtime/last-error-per-thread
main gained per-TEB last-error handling in #310. The conflicts in
CHANGELOG.md, services.rs and runtime_services.rs are resolved to main's
version, which drops this branch's separate thread-context mechanism.

Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>
2026-11-24 12:08:04 -03:00
elforeign d31b8ef20c scripts: restore the VOP1 oracle's GPU gate skip (#215)
The merge of #309 kept only the wide-compare skip, so scripts/test-gpu.sh
runs vop1_integer_forms_match_the_guide_on_native_metal, which fails until
the translator implements the VOP1 integer forms.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 09:07:18 -06:00
LanaCodes-Boop 6e64737021 loader: keep a guest last error per modeled thread context (#202)
ServicesState held one process-wide last-error value, so every modeled
guest thread would have read and overwritten the same slot. The running
context now owns the live slot and the others are parked by identifier,
bounded at 1,024. No guest thread is scheduled: the embedder switches
contexts between service calls.

Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>
2026-11-24 11:41:05 -03:00
Swastick Chowdhury 547b10250d loader: lower BSF, BSR and register BT in the ARM64 DBT (#196)
BSF, BSR and BT were decoded and executed by the interpreter, but every
occurrence of them in a translated block fell back to the shared semantics,
because `is_native` did not list them. The static probe therefore counted
them among the instructions the ARM64 DBT does not support.

Lower them to ARM64:

- BSF writes the index of the lowest set bit of the source and BSR the index
  of the highest set bit. The lowest set bit is the highest set bit of the
  reversed value, so BSF is `RBIT` followed by `CLZ`, and BSR is 63 minus the
  leading zero count.
- A zero source sets the zero flag and leaves the destination undefined, so
  the destination keeps its value. The interpreter and the independent
  reference apply the same rule, and the reference marks the destination as
  undefined so it is not compared.
- BT sets the carry flag from the tested bit, with the bit index masked to
  the operand width. The bit string is not modified.

Only the `0F A3` form of BT is lowered. The `0F BA` group form takes an
immediate index and may write memory, so it stays on the shared semantics and
is not advertised as natively supported.

The new encodings of RBIT, CLZ and LSLV were cross-checked against LLVM 23.1.6
`llvm-mc -show-encoding`.

The BSF, BSR and BT fixtures in `tests/x86/integer.txt` already cover the
16-bit, 32-bit and 64-bit forms with register and memory sources, and the
fixture test asserts that a native form never reaches the shared-semantics
helper, so those fixtures now exercise the new native path against the
independent reference. A new test pins the zero source, the highest bit, the
operand widths, the flag results and the masked bit index.

Closes #196

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 19:17:53 +05:30
55 changed files with 4165 additions and 676 deletions

No files matched your search

+5
View File
@@ -10,11 +10,16 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Changed
- 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.
- 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.
### Added
- 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.
- Added six Wave32 gfx1030 VOP1 integer forms through the semantic registry, including bit scans and a two-register swap under EXEC (AMD RDNA 2 ISA guide section 12.8, #215). The compiler accepts 752 guide-derived cases and rejects 610 programs at the oracle’s expected offsets. Native Metal verification and independent acceptance are pending.
- Added delay-loaded imports to the static PE probe (#244). `xenora probe --mode static` now reads the PE32+ delay-load directory and lists each delay-loaded import in `imports.csv` with its DLL, symbol or ordinal, and delay import address table slot. A new `import_table` column, inserted after `iat_rva`, marks every row `ordinary` or `delayed`; `import_kind` stays the last column. The existing totals and `missing_imports.csv` still cover ordinary imports only, and the JSON report adds `delayed_imports`, `delayed_imported_dlls_count` and `delay_import_error`. The table is bounded by the directory's declared size, which must hold the empty descriptor that ends it, and each descriptor's DLL name, import address table and import name table must be present and start in section data. A table that breaks these rules, is truncated, sets a reserved attribute bit or uses the earlier virtual-address descriptor form is reported with the entries read before the problem. `xenora imports sync` leaves delayed rows out of its backlog. Inspection stays static: nothing is bound or executed. Covered by an original fixture (`fixtures/pe/delay-imports.exe`, generated by `fixtures/pe/delay-imports.py`) whose imports were cross-checked locally with `llvm-readobj --coff-imports` from LLVM 23.1.6; awaiting independent review.
- Added the sixteen gfx1030 SOPK integer forms through the semantic registry: `s_movk_i32`, `s_cmovk_i32`, `s_cmpk_{eq,lg,gt,ge,lt,le}_{i32,u32}`, `s_addk_i32` and `s_mulk_i32` (AMD guide sections 12.2 and 13.1.2), with SDST s0-s105 only and SIMM16 sign-extended (zero-extended for the unsigned compares). The registry gained the operand rules `sopk_sgpr` and `sopk_compare` and the operations `mov` and `cmov`; the decoder and the scalar translation fold them like SOP2 and SOPC. An independent guide-derived oracle (`tests/validation/tests/sopk.rs`, 4,184 cases and 398 rejections on both CPU interpreters and native Metal), an LLVM-assembled fixture `scalar-immediate.s` with IR and MSL goldens, and the LLVM three-way decoder check cover them (part of #215).
- Added an independent guide-derived oracle for the Wave32 16-bit (`v_cmp_{lt..ge}_{i16,u16}_e32`) and 64-bit (`v_cmp_{f..t}_{i64,u64}_e32`) integer compares in the reference and the second interpreter (6,212 lane cases, 1,208 rejections; contract in `docs/shaders/vector-compare.md` section 2a). The decoder and translator still reject these forms, and native Metal agreement is not yet shown. Part of #215.
- Added `python3 -m qa rdna2 rank` to the read-only RDNA2 planner: it groups undeclared gfx1030 forms by the piece of work that would unlock them (an encoding variant of a declared form, a new operand rule, or a new primitive, from XML identity and operand shape only) and ranks the groups by forms per estimated cost, excluding claimed scopes, with `--no-float` to leave out floating-point groups until the FP contract exists (part of #215).
+9 -3
View File
@@ -454,10 +454,16 @@ fn run_imports_sync(
let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
let mut lines = csv_text.lines();
let has_import_kind = lines
.next()
.is_some_and(|header| header.ends_with(",import_kind"));
let header = lines.next().unwrap_or_default();
let has_import_kind = header.ends_with(",import_kind");
// Binding does not resolve delay-loaded imports, so the backlog omits them.
let table_column = header
.split(',')
.position(|column| column == "import_table");
for line in lines {
if table_column.and_then(|index| line.split(',').nth(index)) == Some("delayed") {
continue;
}
// Format: "module","symbol",0xRVA,category,registered,status,is_alias,"canonical",priority,cluster
// We re-query the live registry rather than trusting cached status.
let fields: Vec<&str> = line.splitn(10, ',').collect();
+35
View File
@@ -0,0 +1,35 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! `xenora imports sync` over a probe report that lists delay-loaded imports.
use std::process::Command;
#[test]
fn backlog_leaves_out_delay_loaded_imports() {
// `fixtures/pe/delay-imports.py` writes two ordinary imports from
// `fixture-ordinary.dll` and three delay-loaded ones from two other DLLs.
let fixture = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../fixtures/pe/delay-imports.exe"
);
let report = std::env::temp_dir().join(format!("xenora-sync-delayed-{}", std::process::id()));
let xenora = |arguments: &[&str]| {
let status = Command::new(env!("CARGO_BIN_EXE_xenora"))
.args(arguments)
.arg("--report")
.arg(&report)
.status()
.unwrap();
assert!(status.success(), "{arguments:?}");
};
xenora(&["probe", "--pe", fixture]);
xenora(&["imports", "sync"]);
let listed = std::fs::read_to_string(report.join("imports.csv")).unwrap();
let backlog = std::fs::read_to_string(report.join("import_backlog.md")).unwrap();
std::fs::remove_dir_all(report).unwrap();
assert_eq!(listed.matches(",delayed,").count(), 3);
assert!(backlog.contains("| **Total** | 2 |"), "{backlog}");
assert!(backlog.contains("fixture-ordinary.dll"), "{backlog}");
assert!(!backlog.contains("fixture-delay"), "{backlog}");
}
+33 -19
View File
@@ -5,17 +5,17 @@ use std::fmt;
pub use xenora_isa::{
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp,
VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSource,
VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSource, VectorSwapOp, VectorUnaryOp,
};
use xenora_isa::{
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32,
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32,
V_INTERP_P1_F32, V_INTERP_P2_F32, V_MOV_B32, V_MUL_F32, VCC_LO,
};
use xenora_isa::meta::EncodingFamily;
pub use xenora_isa::semantics::VectorBinary;
use xenora_isa::semantics::{FORM_IDS, OperandRule};
pub use xenora_isa::semantics::{VectorBinary, VectorUnary};
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
/// operand combination: the hand-written forms below followed by every form of
@@ -40,7 +40,7 @@ const fn concat_forms<const N: usize>() -> [(&'static str, EncodingFamily); N] {
}
/// Decoded forms not yet described by the semantic registry.
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 17] = [
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 16] = [
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
("EXP", EncodingFamily::Exp),
@@ -50,7 +50,6 @@ const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 17] = [
("S_CBRANCH_SCC0", EncodingFamily::Sopp),
("S_CBRANCH_VCCZ", EncodingFamily::Sopp),
("S_ENDPGM", EncodingFamily::Sopp),
("S_MOV_B32", EncodingFamily::Sop1),
("S_WAITCNT", EncodingFamily::Sopp),
("S_WAITCNT_VSCNT", EncodingFamily::Sopk),
("V_ADD_F32", EncodingFamily::Vop2),
@@ -317,6 +316,23 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
if V_MOV_B32.matches(first) {
return move_b32(first, bytes);
}
// AMD RDNA 2 ISA guide 13.3.2: VDST occupies bits 17–24 and SRC0 bits 0–8.
if let Some(op) = VectorUnaryOp::from_word(first) {
let dst = (first >> 17) as u8;
let (src, len) = vector_src0(first, bytes, op.assembly_name())?;
return Ok((Instruction::VectorUnary { op, dst, src }, len));
}
if let Some(op) = VectorSwapOp::from_word(first) {
if first & 0x100 == 0 {
return Err(unsupported(
op.assembly_name(),
"expected a VGPR SRC0 for writeback",
));
}
let dst = (first >> 17) as u8;
let src = first as u8;
return Ok((Instruction::VectorSwap { op, dst, src }, 4));
}
if let Some(op) = VectorCompareOp::from_word(first) {
return vector_compare(op, first, bytes);
}
@@ -324,23 +340,21 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
let second = word(bytes, 8)?;
return Ok((vop3_vgpr2(op, first, second)?, 8));
}
if S_MOV_B32.matches(first) {
let dst = ((first >> 16) & 0x7f) as u8;
if !matches!(dst, 0..=107 | 126..=127) {
return Err(unsupported(
"s_mov_b32",
"expected a normal SGPR or EXEC/VCC destination",
));
}
let (src, len) = scalar_source(first as u8, bytes, "s_mov_b32")?;
return Ok((Instruction::ScalarMoveB32 { dst, src }, len));
}
if let Some(op) = ScalarUnaryOp::from_word(first) {
// SOP1: SSRC0 in bits 0-7, SDST in bits 16-22.
let mnemonic = op.mnemonic();
let dst = ((first >> 16) & 0x7f) as u8;
if dst > 105 {
return Err(unsupported(mnemonic, "expected a normal SGPR destination"));
match op.semantics().operands {
OperandRule::Sop1Move if !matches!(dst, 0..=107 | 126..=127) => {
return Err(unsupported(
mnemonic,
"expected a normal SGPR or EXEC/VCC destination",
));
}
OperandRule::Sop1Sgpr if dst > 105 => {
return Err(unsupported(mnemonic, "expected a normal SGPR destination"));
}
_ => {}
}
let (src, len) = scalar_source(first as u8, bytes, mnemonic)?;
return Ok((Instruction::ScalarUnary { op, dst, src }, len));
@@ -664,7 +678,7 @@ fn vector_compare(
Ok((Instruction::VectorCompare { op, src0, src1 }, len))
}
/// The 9-bit SRC0 of a VOPC or VOP2 word: a VGPR, `s0-s105`, `vcc_lo`, an
/// The 9-bit SRC0 of a VOP1, VOP2 or VOPC word: a VGPR, `s0-s105`, `vcc_lo`, an
/// inline integer -16..64 or a literal word; everything else is unsupported.
fn vector_src0(
first: u32,
+33 -13
View File
@@ -5,12 +5,12 @@ use std::process::{Command, Stdio};
use xenora_decoder::{
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
ScalarAluOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op,
VectorSource, decode, decode_at,
VectorSource, VectorUnaryOp, decode, decode_at,
};
use xenora_isa::semantics::Signedness;
use xenora_ref::{
BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarImmediate, ScalarUnary,
Source, VectorAlu, VectorInteger,
Source, VectorAlu, VectorInteger, VectorUnary,
};
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
@@ -330,6 +330,22 @@ fn reference_op(instruction: Instruction) -> Op {
src: VectorSource::Scalar(src),
} => Op::MoveScalar(dst, src),
Instruction::MoveB32 { dst, src } => Op::Move(dst, reference_source(src)),
Instruction::VectorUnary { op, dst, src } => Op::VectorUnary(
match op {
VectorUnaryOp::NotB32 => VectorUnary::Not,
VectorUnaryOp::BfrevB32 => VectorUnary::ReverseBits,
VectorUnaryOp::FfbhU32 => VectorUnary::FindFirstOneFromMsb,
VectorUnaryOp::FfblB32 => VectorUnary::FindFirstOneFromLsb,
VectorUnaryOp::FfbhI32 => VectorUnary::FindSignChange,
},
dst,
match src {
VectorSource::Register(reg) => CompareSource::Vector(reg),
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
VectorSource::Immediate(bits) => CompareSource::Immediate(bits),
},
),
Instruction::VectorSwap { dst, src, .. } => Op::Swap(dst, src),
Instruction::ScalarAlu {
op,
dst,
@@ -382,9 +398,10 @@ fn reference_op(instruction: Instruction) -> Op {
src0,
src1,
} => Op::Add(dst, src0, src1),
Instruction::ScalarMoveB32 { dst, src } => Op::ScalarMove(dst, reference_scalar(src)),
Instruction::ScalarUnary { op, dst, src } => Op::ScalarUnary(
match op {
Instruction::ScalarUnary { op, dst, src } => {
let src = reference_scalar(src);
let unary = match op {
ScalarUnaryOp::MovB32 => return Op::ScalarMove(dst, src),
ScalarUnaryOp::NotB32 => ScalarUnary::Not,
ScalarUnaryOp::BrevB32 => ScalarUnary::ReverseBits,
ScalarUnaryOp::Bcnt0I32B32 => ScalarUnary::CountZeros,
@@ -396,10 +413,9 @@ fn reference_op(instruction: Instruction) -> Op {
ScalarUnaryOp::SextI32I8 => ScalarUnary::SignExtendByte,
ScalarUnaryOp::SextI32I16 => ScalarUnary::SignExtendShort,
ScalarUnaryOp::AbsI32 => ScalarUnary::Absolute,
},
dst,
reference_scalar(src),
),
};
Op::ScalarUnary(unary, dst, src)
}
Instruction::ScalarCompare { op, src0, src1 } => {
let (src0, src1) = (reference_scalar(src0), reference_scalar(src1));
// The reference keeps CompareEqual for EQ and uses its VOPC relation
@@ -568,12 +584,13 @@ fn compares_fixture_instructions_against_llvm() {
include_bytes!("../../../fixtures/rdna2/vector-integer.bin"),
include_bytes!("../../../fixtures/rdna2/vector-compare.bin"),
include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"),
include_bytes!("../../../fixtures/rdna2/vector-unary.bin"),
high_registers,
&matrix,
] {
count += compare_against_llvm(fixture, &mut forms);
}
assert_eq!(forms.len(), 120, "forms compared: {forms:?}");
assert_eq!(forms.len(), 126, "forms compared: {forms:?}");
eprintln!(
"{count} three-way instruction comparisons across {} forms",
forms.len()
@@ -991,14 +1008,16 @@ fn decodes_inline_negative_and_register_sources() {
let decoded = decode(Architecture::Gfx1030, &bytes).unwrap();
assert_eq!(
decoded[0].instruction,
Instruction::ScalarMoveB32 {
Instruction::ScalarUnary {
op: ScalarUnaryOp::MovB32,
dst: 10,
src: ScalarSource::Immediate(5)
}
);
assert_eq!(
decoded[1].instruction,
Instruction::ScalarMoveB32 {
Instruction::ScalarUnary {
op: ScalarUnaryOp::MovB32,
dst: 11,
src: ScalarSource::Immediate(0xffff_fffd)
}
@@ -1032,7 +1051,8 @@ fn accepts_scalar_destination_105_and_vgpr_zero_add_sources() {
let valid = 0xbee9_0380u32.to_le_bytes();
assert_eq!(
decode(Architecture::Gfx1030, &valid).unwrap()[0].instruction,
Instruction::ScalarMoveB32 {
Instruction::ScalarUnary {
op: ScalarUnaryOp::MovB32,
dst: 105,
src: ScalarSource::Immediate(0)
}
+97 -8
View File
@@ -61,7 +61,7 @@ OPERATIONS = {
"mul": "Multiply", "mul_hi": "MultiplyHigh", "bfe": "BitfieldExtract",
"absdiff": "AbsoluteDifference", "lshl_add": "ShiftLeftAdd",
"mul24": "Multiply24", "mul_hi24": "MultiplyHigh24",
"mov": "Move", "cmov": "ConditionalMove",
"mov": "Move", "cmov": "ConditionalMove", "swap": "Swap",
}
# Unary operations read one source; they need an operand rule of the unary kind.
UNARY = {"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "flbit", "sext", "abs"}
@@ -97,7 +97,7 @@ COMPARE_PRIMITIVES = {
# the signedness their primitive names, and their S1 is an unsigned count.
LOGICAL = {
"and", "or", "xor", "andn2", "orn2", "nand", "nor", "xnor",
"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "cselect", "bfm",
"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "cselect", "bfm", "swap",
}
ARITHMETIC = {
"add", "sub", "min", "max", "mul", "mul_hi", "bfe", "absdiff", "lshl_add", "mul24", "mul_hi24",
@@ -143,7 +143,7 @@ WAVE = {"any": "Any", "wave32": "Wave32"}
# wave size: the lane-mask compares, whose one entry point is the Wave32
# compute fixture ABI (docs/shaders/vector-compare.md section 2). Every other
# kind must be "any".
WAVE_BY_KIND = {"vector_compare": "wave32"}
WAVE_BY_KIND = {"vector_compare": "wave32", "vector_unary": "wave32", "vector_swap": "wave32"}
EVIDENCE = {
"reference": "Reference",
"independent": "Independent",
@@ -184,6 +184,7 @@ PRIMITIVES = {
("lshl", "bitwise"): ("nonzero", "lshl_nonzero_b32", False),
("lshr", "unsigned"): ("nonzero", "lshr_nonzero_b32", False),
("ashr", "signed"): ("nonzero", "ashr_nonzero_i32", False),
("mov", "bitwise"): ("unchanged", "mov_b32", False),
("not", "bitwise"): ("nonzero", "not_nonzero_b32", False),
("brev", "bitwise"): ("unchanged", "brev_b32", False),
("bcnt0", "bitwise"): ("nonzero", "bcnt0_nonzero_b32", False),
@@ -258,7 +259,45 @@ UNSUPPORTED_COMBOS = {
# VOP3 rules also name source classes and encoding fields they refuse.
VOP3_COMBOS = {"src_sgpr", "src_inline", "src_literal", "modifiers", "src2"}
ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null"} | VOP3_COMBOS
VECTOR_UNARY_PRIMITIVES = {
("not", "bitwise"): "Not",
("brev", "bitwise"): "ReverseBits",
("flbit", "unsigned"): "FindHighUnsigned",
("ff1", "bitwise"): "FindLow",
("flbit", "signed"): "FindHighSigned",
}
OPERAND_RULES = {
"vop1_vgpr": {
"rust": "Vop1Vgpr",
"enum": "VectorUnaryOp",
"shape": {
"family": "VOP1",
"dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255},
"src": [{"field": "SRC0", "class": "vector_source"}],
"max_literals": 1,
},
"unsupported": {
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline",
"src_special",
},
"kind": "vector_unary",
},
"vop1_swap": {
"rust": "Vop1Swap",
"enum": "VectorSwapOp",
"shape": {
"family": "VOP1",
"dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255},
"src": [{"field": "SRC0", "class": "vgpr"}],
"max_literals": 0,
},
"unsupported": {
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
"src_float_inline", "src_special", "src_literal",
},
"kind": "vector_swap",
},
"sop2_sgpr": {
"rust": "Sop2Sgpr",
"enum": "ScalarAluOp",
@@ -303,6 +342,18 @@ OPERAND_RULES = {
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo != "two_literals"},
"kind": "unary",
},
"sop1_move": {
"rust": "Sop1Move",
"enum": "ScalarUnaryOp",
"shape": {
"family": "SOP1",
"dst": {"field": "SDST", "class": "sgpr_or_vcc_exec"},
"src": [{"field": "SSRC0", "class": "scalar_source"}],
"max_literals": 1,
},
"unsupported": UNSUPPORTED_COMBOS - {"two_literals", "dst_vcc", "dst_exec"},
"kind": "unary",
},
"sopk_sgpr": {
"rust": "SopkSgpr",
"enum": "ScalarImmediateOp",
@@ -637,7 +688,10 @@ def _check_xml(form, rule, snapshot, errors):
expected = bits if type(bits) is int else form["width"]
if size != expected:
errors.append(f"{label}: {field} is {size} bits in the XML, declared {expected}")
if (is_input, is_output) != (is_source, not is_source):
# The XML marks both swap operands as outputs. Guide 12.8 also
# reads both old values before assigning either result.
direction = (False, True) if _rule_kind(form) == "vector_swap" else (is_source, not is_source)
if (is_input, is_output) != direction:
errors.append(f"{label}: {field} direction disagrees with the XML")
if field == count_field:
if data_format != "FMT_NUM_U32":
@@ -808,10 +862,16 @@ def validate(registry, snapshot):
if form["carry_in"] != "none":
errors.append(f"{label}: carry_in {form['carry_in']} contradicts compare")
primitive = (scc, None, False)
elif _rule_kind(form) == "vector":
elif _rule_kind(form) in ("vector", "vector_unary", "vector_swap"):
if RELATION_KEY in form:
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
lowering = VECTOR_PRIMITIVES.get((form["operation"], form["signedness"]))
key = (form["operation"], form["signedness"])
table = {
"vector": VECTOR_PRIMITIVES,
"vector_unary": VECTOR_UNARY_PRIMITIVES,
"vector_swap": {("swap", "bitwise"): "Swap"},
}[_rule_kind(form)]
lowering = table.get(key)
primitive = None if lowering is None else ("unchanged", lowering, False)
else:
if RELATION_KEY in form:
@@ -839,7 +899,11 @@ def validate(registry, snapshot):
elif form["operands"] in OPERAND_RULES and OPERAND_RULES[form["operands"]]["kind"] != (
(_rule_kind(form) if _rule_kind(form) in ("vector_compare", "immediate_compare") else "compare")
if form["operation"] == "compare"
else "unary" if form["operation"] in UNARY
else "vector_swap" if form["operation"] == "swap"
else "vector_unary" if _rule_kind(form) == "vector_unary" and form["operation"] in UNARY
else "unary" if form["operation"] in UNARY or (
form["operation"] == "mov" and form["family"] == "SOP1"
)
else "vector" if _rule_kind(form) == "vector" and form["operation"] not in UNARY
else "immediate" if _rule_kind(form) == "immediate"
else "alu"
@@ -1027,7 +1091,7 @@ def render(registry, snapshot):
"use crate::primitive;",
"use crate::semantics::{",
" CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,",
" Signedness, SpecRef, VectorBinary, Wave,",
" Signedness, SpecRef, VectorBinary, VectorUnary, Wave,",
"};",
"use crate::CompareRelation;",
"",
@@ -1274,6 +1338,31 @@ def _render_enum(rule_name, forms, snapshot, positions):
" }]",
" }",
]
if kind in ("vector_unary", "vector_swap"):
out += [
"",
" /// Assembler name of the 32-bit VOP1 encoding.",
" pub const fn assembly_name(self) -> &'static str {",
" match self {",
]
suffix = "_e32" if kind == "vector_unary" else ""
out += [f" Self::{form['variant']} => \"{form['name'].lower()}{suffix}\"," for form in forms]
out += [" }", " }"]
if kind == "vector_swap":
return out + ["}"]
if kind == "vector_unary":
out += [
"",
" /// Per-lane integer operation selected by the registry.",
" pub const fn lowering(self) -> VectorUnary {",
" match self {",
]
out += [
f" Self::{form['variant']} => "
f"VectorUnary::{VECTOR_UNARY_PRIMITIVES[(form['operation'], form['signedness'])]},"
for form in forms
]
return out + [" }", " }", "}"]
if kind == "immediate":
out += [
"",
+2 -1
View File
@@ -21,6 +21,7 @@ include = [
"rdna2/sopc.toml",
"rdna2/sopk.toml",
"rdna2/sop1.toml",
"rdna2/vop1.toml",
"rdna2/vop2.toml",
"rdna2/vopc.toml",
"rdna2/vop3.toml",
@@ -47,7 +48,7 @@ file = "amdgpu_isa_rdna2.xml"
# width operand and result width in bits
# scc unchanged | carry_out | borrow | signed_overflow | nonzero | relation | selected_src0
# vcc, exec unchanged (stated, not implied) | lane_mask (vcc of a Wave32 VOPC compare)
# wave any | wave32 (wave32 exactly for the VOPC lane-mask compares)
# wave any | wave32 (wave32 for VOPC compares and VOP1 integer forms)
# operands a key of [operand_rules]
# spec references; at least one guide section with a page
# verify evidence required before the form counts as verified
+32
View File
@@ -15,6 +15,38 @@ unsupported = [
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", "src_special",
]
# Guide sections 5.3 and 12.3. VCC and EXEC halves can be explicit
# destinations; the move has no implicit mask or SCC effects.
[operand_rules.sop1_move]
family = "SOP1"
dst = { field = "SDST", class = "sgpr_or_vcc_exec" }
src = [{ field = "SSRC0", class = "scalar_source" }]
max_literals = 1
unsupported = [
"dst_ttmp", "dst_m0", "dst_null",
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", "src_special",
]
[[form]]
name = "S_MOV_B32"
family = "SOP1"
opcode = 3
variant = "MovB32"
operation = "mov"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_move"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_NOT_B32"
family = "SOP1"
+123
View File
@@ -0,0 +1,123 @@
# Wave32 VOP1 integer forms, AMD RDNA 2 ISA guide 12.8.
[operand_rules.vop1_vgpr]
family = "VOP1"
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
src = [{ field = "SRC0", class = "vector_source" }]
max_literals = 1
unsupported = [
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
]
# Both operands are read and written by swap; SRC0 must select a VGPR.
[operand_rules.vop1_swap]
family = "VOP1"
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
src = [{ field = "SRC0", class = "vgpr" }]
max_literals = 0
unsupported = [
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
"src_float_inline", "src_special", "src_literal",
]
[[form]]
name = "V_NOT_B32"
family = "VOP1"
opcode = 55
variant = "NotB32"
operation = "not"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "wave32"
operands = "vop1_vgpr"
spec = [{ document = "guide", section = "12.8", page = 143 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_BFREV_B32"
family = "VOP1"
opcode = 56
variant = "BfrevB32"
operation = "brev"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "wave32"
operands = "vop1_vgpr"
spec = [{ document = "guide", section = "12.8", page = 143 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_FFBH_U32"
family = "VOP1"
opcode = 57
variant = "FfbhU32"
operation = "flbit"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "wave32"
operands = "vop1_vgpr"
spec = [{ document = "guide", section = "12.8", page = 143 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_FFBL_B32"
family = "VOP1"
opcode = 58
variant = "FfblB32"
operation = "ff1"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "wave32"
operands = "vop1_vgpr"
spec = [{ document = "guide", section = "12.8", page = 143 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_FFBH_I32"
family = "VOP1"
opcode = 59
variant = "FfbhI32"
operation = "flbit"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "wave32"
operands = "vop1_vgpr"
spec = [{ document = "guide", section = "12.8", page = 144 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_SWAP_B32"
family = "VOP1"
opcode = 101
variant = "SwapB32"
operation = "swap"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "wave32"
operands = "vop1_swap"
spec = [{ document = "guide", section = "12.8", page = 149 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
+18 -8
View File
@@ -20,7 +20,7 @@ pub use rdna2::{
};
pub use semantics_gen::{
ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarUnaryOp,
VectorAluOp, VectorAluVop3Op, VectorCompareOp,
VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSwapOp, VectorUnaryOp,
};
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
@@ -155,6 +155,14 @@ pub enum Instruction {
WaitStore,
/// VOP1 unmodified 32-bit vector move.
MoveB32 { dst: u8, src: VectorSource },
/// VOP1 unary integer operation with a single VGPR result.
VectorUnary {
op: VectorUnaryOp,
dst: u8,
src: VectorSource,
},
/// VOP1 register swap. Both operands are inputs and outputs.
VectorSwap { op: VectorSwapOp, dst: u8, src: u8 },
/// VOP3 encoding of a registry VOP2 integer operation (operand rule
/// `vop3_vgpr2`): two VGPR sources and no input or output modifiers.
VectorAluVop3 {
@@ -163,10 +171,8 @@ pub enum Instruction {
src0: u8,
src1: u8,
},
/// SOP1 32-bit move to a normal SGPR or an EXEC/VCC half.
ScalarMoveB32 { dst: u8, src: ScalarSource },
/// SOP1 32-bit unary integer operation writing a normal SGPR (s0-s105) and,
/// for some operations, SCC.
/// SOP1 32-bit unary integer operation. The move also allows an explicit
/// VCC or EXEC half destination. Some unary operations write SCC.
ScalarUnary {
op: ScalarUnaryOp,
dst: u8,
@@ -281,8 +287,9 @@ impl Instruction {
Self::WaitLoad => "s_waitcnt",
Self::WaitStore => "s_waitcnt_vscnt",
Self::MoveB32 { .. } => "v_mov_b32_e32",
Self::VectorUnary { op, .. } => op.assembly_name(),
Self::VectorSwap { op, .. } => op.assembly_name(),
Self::VectorAluVop3 { op, .. } => op.assembly_name(),
Self::ScalarMoveB32 { .. } => "s_mov_b32",
Self::ScalarUnary { op, .. } => op.mnemonic(),
Self::ScalarAlu { op, .. } => op.mnemonic(),
Self::ScalarCompare { op, .. } => op.mnemonic(),
@@ -333,7 +340,10 @@ impl fmt::Display for Instruction {
}
Self::WaitLoad => formatter.write_str(" vmcnt(0)"),
Self::WaitStore => formatter.write_str(" null, 0"),
Self::MoveB32 { dst, src } => write!(formatter, " v{dst}, {src}"),
Self::MoveB32 { dst, src } | Self::VectorUnary { dst, src, .. } => {
write!(formatter, " v{dst}, {src}")
}
Self::VectorSwap { dst, src, .. } => write!(formatter, " v{dst}, v{src}"),
Self::VectorAluVop3 {
dst, src0, src1, ..
}
@@ -341,7 +351,7 @@ impl fmt::Display for Instruction {
| Self::VectorMulF32 { dst, src0, src1 } => {
write!(formatter, " v{dst}, v{src0}, v{src1}")
}
Self::ScalarMoveB32 { dst, src } | Self::ScalarUnary { dst, src, .. } => {
Self::ScalarUnary { dst, src, .. } => {
write!(formatter, " {}, {src}", ScalarDestination(dst))
}
Self::ScalarAlu {
+5
View File
@@ -331,3 +331,8 @@ pub const fn lshl_add_carry_u32(a: u32, b: u32, shift: u32) -> (u32, bool) {
let sum = ((a as u64) << shift) + b as u64;
(sum as u32, sum >> 32 != 0)
}
/// A bitwise copy of the source (RDNA 2 guide section 12.3).
pub(crate) const fn mov_b32(src: u32) -> u32 {
src
}
+24
View File
@@ -94,6 +94,23 @@ pub enum Operation {
Move,
/// SOPK: SDST receives the sign-extended SIMM16 when SCC is set.
ConditionalMove,
/// Swap the two old per-lane VGPR values (guide 12.8).
Swap,
}
/// Per-lane integer operation with one input and one result.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VectorUnary {
/// Bitwise complement.
Not,
/// Reverse bit order.
ReverseBits,
/// Count leading zeros, or return all ones for zero.
FindHighUnsigned,
/// Count trailing zeros, or return all ones for zero.
FindLow,
/// Count leading sign bits, or return all ones if every bit matches.
FindHighSigned,
}
/// The per-lane integer operation a vector form lowers to. One reusable MSL
@@ -208,6 +225,9 @@ pub enum OperandRule {
/// SOP1 unary: SDST is s0-s105; SSRC0 is s0-s105, an inline integer -16..64 or
/// a literal word. Everything else is rejected as unsupported.
Sop1Sgpr,
/// SOP1 move: the same sources as Sop1Sgpr, with VCC and EXEC halves
/// also allowed as explicit destinations.
Sop1Move,
/// SOPK integer: SDST is s0-s105 and, except for compares, written (never s0-s7,
/// which hold resource descriptors); SIMM16 is the 16-bit immediate. The word
/// never takes a literal. Everything else is rejected as unsupported.
@@ -230,6 +250,10 @@ pub enum OperandRule {
/// VOP2 vector, VGPR sources only: VDST is v0-v255; SRC0 and VSRC1 are VGPRs.
/// Everything else (SGPR, inline, literal SRC0) is rejected as unsupported.
Vop2Vgpr2,
/// VOP1 unary: VGPR VDST and the same SRC0 domain as VOP2.
Vop1Vgpr,
/// VOP1 swap: VDST and SRC0 each read and write a VGPR.
Vop1Swap,
}
/// Evidence a form needs before it counts as verified.
File diff suppressed because it is too large. Load diff
-1
View File
@@ -144,7 +144,6 @@ fn scalar_unary_dispatch_selects_exactly_the_registry_sop1_forms() {
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
}
// s_mov_b32 (opcode 3) stays hand-written, so it must not be dispatched here.
dispatch_selects_exactly(EncodingFamily::Sop1, |word| {
ScalarUnaryOp::from_word(word).map(|op| op.semantics().name)
});
+10 -4
View File
@@ -7,8 +7,9 @@
differs. Never writes.
Rejects unknown keys and vocabulary, overlapping encodings, digit and plain
forms sharing an opcode, operand constraints that contradict each other, and
flags declared both written and undefined. Standard library only (Python 3.11+).
forms sharing an opcode, operand constraints that contradict each other, LOCK
on a form that cannot write memory, and flags declared both written and
undefined. Standard library only (Python 3.11+).
"""
import sys
@@ -26,7 +27,7 @@ RUST = HERE / "src/x86_table.rs"
TOP_KEYS = {"schema", "architecture", "documents", "operation", "alu", "form", "group"}
OPERATION_KEYS = {"reads", "writes", "undefined", "conditional", "terminator", "faults", "ref"}
FORM_KEYS = {"op", "map", "prefix", "opcode", "count", "digit", "enc", "size", "imm", "src",
"memory_only", "register_only", "no_rex_b", "unaligned"}
"memory_only", "register_only", "no_rex_b", "unaligned", "lock"}
GROUP_KEYS = {"map", "opcodes", "digits"}
FLAGS = ["cf", "zf", "sf", "of", "pf", "af"]
MAPS = {"1": "ONE_BYTE", "0f": "TWO_BYTE"}
@@ -63,6 +64,8 @@ ENCS = {
"reg_xmm": ("RegXmm", True, {""}),
"reg_xmm_imm": ("RegXmmImm", True, {"ub"}),
}
# Encodings whose ModRM operand is the destination, so LOCK can apply to it.
RM_DESTINATIONS = {"rm_reg", "rm", "rm_imm", "rm_one", "rm_cl"}
# Encodings whose ModRM operand is an XMM register or memory of the source width.
XMM_RM = {"xmm_rm", "rm_xmm", "xmm_rm_imm", "rm_imm_xmm", "reg_xmm", "reg_xmm_imm"}
# One-byte opcodes that are prefixes or the two-byte escape, never instructions.
@@ -171,6 +174,8 @@ def load(text):
if (form["size"] == "x") != (form["enc"] in XMM_RM - {"reg_xmm", "reg_xmm_imm"}
or form["enc"] == "xmm_gpr_imm"):
fail(f"{where}: XMM size does not match the encoding")
if form.get("lock") and (form["enc"] not in RM_DESTINATIONS or form.get("register_only")):
fail(f"{where}: LOCK needs a memory destination")
if form.get("unaligned") and form["src"] != "x":
fail(f"{where}: alignment applies only to 16-byte operands")
if form["prefix"] and form["map"] != "0f":
@@ -266,7 +271,8 @@ def generate(operations, forms):
f"memory_only: {str(bool(form.get('memory_only'))).lower()}, "
f"register_only: {str(bool(form.get('register_only'))).lower()}, "
f"no_rex_b: {str(bool(form.get('no_rex_b'))).lower()}, "
f"unaligned: {str(bool(form.get('unaligned'))).lower()} }},")
f"unaligned: {str(bool(form.get('unaligned'))).lower()}, "
f"lockable: {str(bool(form.get('lock'))).lower()} }},")
out += ["];", ""]
groups = []
+20
View File
@@ -306,6 +306,26 @@ impl Arm64Assembler {
);
}
/// RBIT Xd, Xn: reverse the bit order of the source.
pub fn rbit_64(&mut self, xd: u8, xn: u8) {
self.emit(0xdac0_0000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f));
}
/// CLZ Xd, Xn: count the leading zero bits of the source.
pub fn clz_64(&mut self, xd: u8, xn: u8) {
self.emit(0xdac0_1000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f));
}
/// LSLV Xd, Xn, Xm: shift the source left by the amount in Xm.
pub fn lslv_64(&mut self, xd: u8, xn: u8, xm: u8) {
self.emit(
0x9ac2_2000
| ((u32::from(xm) & 0x1f) << 16)
| ((u32::from(xn) & 0x1f) << 5)
| (u32::from(xd) & 0x1f),
);
}
/// LDR Qt, [Xn, #offset] (offset a multiple of 16)
pub fn ldr_q_uoff(&mut self, qt: u8, xn: u8, offset: u32) {
self.emit(
+29
View File
@@ -123,6 +123,35 @@ impl CpuState {
}
}
/// CPUID leaf 1, EDX: CMOVcc.
pub const CPUID_CMOV: u32 = 1 << 15;
/// CPUID leaf 1, ECX: POPCNT.
pub const CPUID_POPCNT: u32 = 1 << 23;
/// CPUID leaf 0x8000_0001, ECX: LZCNT.
pub const CPUID_LZCNT: u32 = 1 << 5;
/// CPUID leaf 0x8000_0001, EDX: 64-bit mode.
pub const CPUID_LONG_MODE: u32 = 1 << 29;
/// What the guest's CPUID returns in EAX, EBX, ECX and EDX.
///
/// The table is fixed and never reads the host. It names a synthetic
/// processor, not an Intel or AMD product, and sets a feature bit only when
/// every instruction of that feature is implemented. A leaf that is not
/// listed returns zeros.
pub fn cpuid(leaf: u32, _subleaf: u32) -> [u32; 4] {
let word = |text: &[u8; 4]| u32::from_le_bytes(*text);
match leaf {
// Highest basic leaf, then "Xenora guest" in EBX, EDX, ECX.
0 => [1, word(b"Xeno"), word(b"uest"), word(b"ra g")],
// No family, model or stepping: this is no shipped processor.
1 => [0, 0, CPUID_POPCNT, CPUID_CMOV],
// Highest extended leaf.
0x8000_0000 => [0x8000_0001, 0, 0, 0],
0x8000_0001 => [0, 0, CPUID_LZCNT, CPUID_LONG_MODE],
_ => [0; 4],
}
}
/// Termination reason for guest execution.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExitReason {
+85
View File
@@ -330,10 +330,18 @@ pub fn is_translatable(insn: &Insn) -> bool {
/// [`DbtMetrics::interpreter_fallbacks`].
pub fn is_native(insn: &Insn) -> bool {
let wide = matches!(insn.size, 4 | 8);
// The bit scans work on any register or memory source, and the bit test
// needs the index in a register.
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,
Op::Inc | Op::Dec | Op::Neg | Op::Not => wide,
Op::Cmov => wide,
Op::Bsf | Op::Bsr => scanned,
// Only the `0F A3` form has the bit index in a register. The `0F BA`
// group form takes an immediate index and may write memory, so it
// stays on the shared semantics.
Op::Bt => scanned && insn.encoding == Encoding::RmReg,
Op::Pop => insn.encoding == Encoding::OpReg,
Op::Mov
| Op::Movzx
@@ -500,6 +508,18 @@ impl Emitter<'_> {
}
}
/// Zero-extend the low `size` bytes of `xd` to the full 64-bit register.
///
/// An operation narrower than the register reads only the low bytes of its
/// source, so the bits above them must not take part in a bit scan.
fn zero_extend(&mut self, xd: u8, size: u8) {
match size {
8 => {}
4 => self.asm.mov_reg_32(xd, xd),
_ => self.asm.uxth_32(xd, xd),
}
}
/// Effective address into X1, clobbering X9.
fn effective_address(&mut self, operand: &MemOperand, with_segment: bool) {
let asm = &mut *self.asm;
@@ -1032,6 +1052,71 @@ impl Emitter<'_> {
self.load_condition(insn.condition);
self.store_rm(insn, X12, completed);
}
Op::Bsf | Op::Bsr => {
// BSF and BSR write the index of the lowest or the highest set
// bit of the source into the destination and set the zero flag
// when the source is zero (Intel SDM Volume 2B, "BSF" and
// "BSR"). A zero source leaves the destination undefined, so
// the destination keeps its value, which is the same rule the
// interpreter and the reference apply.
self.load_rm(X9, insn, completed);
self.zero_extend(X9, insn.size);
match insn.op {
// The lowest set bit is the highest set bit of the
// reversed value, so its index is the leading zero count
// of the reversed value.
Op::Bsf => {
self.asm.rbit_64(X10, X9);
self.asm.clz_64(X10, X10);
}
// The highest set bit sits at 63 minus the leading zero
// count.
_ => {
self.asm.clz_64(X10, X9);
self.asm.movz_64(X13, 63, 0);
self.asm.sub_reg_64(X10, X13, X10);
}
}
self.load_reg(X11, insn.reg);
self.asm.tst_reg_64(X9, X9);
// CSEL takes the first operand when the condition holds, so
// the index is the value that replaces the destination.
self.asm.csel_64(X11, X10, X11, Condition::Ne);
match insn.size {
// A 16-bit destination keeps the bits above it, so the
// register is merged rather than replaced.
2 => self.store_reg(insn.reg, insn.size, X11),
// A 32-bit or 64-bit destination is written in full. The
// index has no bits above the operand width, so this
// matches the interpreter's 32-bit write, and a zero
// source keeps the whole register unchanged.
_ => self.asm.str_uoff_64(X11, X19, reg_offset(insn.reg.index)),
}
if flags {
// The zero flag is set when the source is zero. The other
// flags are undefined and keep their value.
self.asm.cset_32(X12, Condition::Eq);
self.asm.strb_uoff(X12, X19, ZF);
}
}
Op::Bt => {
// BT sets the carry flag from the tested bit and leaves the
// other flags undefined (Intel SDM Volume 2B, "BT"). The bit
// index comes from the register operand and is masked to the
// operand width.
self.load_rm(X9, insn, completed);
self.zero_extend(X9, insn.size);
self.load_reg(X10, insn.reg);
self.asm.load_imm_64(X13, u64::from(8 * insn.size - 1));
self.asm.and_reg_64(X10, X10, X13);
self.asm.load_imm_64(X11, 1);
self.asm.lslv_64(X11, X11, X10);
self.asm.tst_reg_64(X9, X11);
if flags {
self.asm.cset_32(X12, Condition::Ne);
self.asm.strb_uoff(X12, X19, CF);
}
}
Op::Cmov => {
self.load_rm(X10, insn, completed);
self.load_reg(X9, insn.reg);
+145 -2
View File
@@ -3,6 +3,10 @@
//! Bounded parser for the PE32+ import directory (Microsoft PE format,
//! "The .idata Section"). Binding and static inspection both use it, so they
//! agree on which imports an image has and how they are named.
//!
//! Static inspection also reads the delay-load directory ("Delay-Load Import
//! Tables (Image Only)"). Binding does not: the PE format leaves those imports
//! to a delay-load helper that runs inside the image on first use.
use std::fmt;
@@ -14,6 +18,9 @@ pub const MAX_IMPORTS: usize = 65_536;
pub const MAX_NAME_LEN: usize = 4096;
const DESCRIPTOR_LEN: u32 = 20;
const DELAY_DESCRIPTOR_LEN: u32 = 32;
/// Delay-load attribute bit 0: the descriptor's address fields are RVAs.
const DELAY_RVA_BASED: u32 = 1;
const ORDINAL_FLAG: u64 = 1 << 63;
/// How an import names its target. A symbol that happens to be spelled like an
@@ -42,6 +49,24 @@ pub struct ImportEntry {
pub iat_rva: u32,
}
/// A delay-load descriptor field that must hold an RVA.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DelayField {
DllName,
AddressTable,
NameTable,
}
impl fmt::Display for DelayField {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::DllName => "DLL name",
Self::AddressTable => "import address table",
Self::NameTable => "import name table",
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ImportTableError {
/// A structure at this RVA is not fully backed by section data.
@@ -56,6 +81,25 @@ pub enum ImportTableError {
ReservedBits {
rva: u32,
},
/// The delay-load descriptor at this RVA sets reserved attribute bits.
DelayReservedBits {
rva: u32,
},
/// The delay-load descriptor at this RVA has `RvaBased` clear, the earlier
/// form whose address fields are virtual addresses. It is not read.
DelayVirtualAddresses {
rva: u32,
},
/// The delay-load descriptor at this RVA leaves a required field zero.
DelayFieldMissing {
rva: u32,
field: DelayField,
},
/// The declared delay-load directory ends at this RVA before its empty
/// descriptor.
DelayDirectoryEnd {
rva: u32,
},
TooManyDescriptors,
TooManyImports,
}
@@ -63,7 +107,10 @@ pub enum ImportTableError {
impl fmt::Display for ImportTableError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::OutOfBounds { rva } => write!(f, "import data at RVA 0x{rva:08x} is truncated"),
Self::OutOfBounds { rva } => write!(
f,
"import data at RVA 0x{rva:08x} is truncated or outside the section data"
),
Self::MalformedName { rva } => write!(f, "malformed import name at RVA 0x{rva:08x}"),
Self::ReservedBits { rva } => {
write!(
@@ -71,6 +118,21 @@ impl fmt::Display for ImportTableError {
"reserved bits set in the import lookup at RVA 0x{rva:08x}"
)
}
Self::DelayReservedBits { rva } => write!(
f,
"reserved attribute bits set in the delay-load descriptor at RVA 0x{rva:08x}"
),
Self::DelayVirtualAddresses { rva } => write!(
f,
"delay-load descriptor at RVA 0x{rva:08x} holds virtual addresses, not RVAs, and is not read"
),
Self::DelayFieldMissing { rva, field } => {
write!(f, "delay-load descriptor at RVA 0x{rva:08x} has no {field}")
}
Self::DelayDirectoryEnd { rva } => write!(
f,
"delay-load directory ends at RVA 0x{rva:08x} before its empty descriptor"
),
Self::TooManyDescriptors => write!(f, "more than {MAX_DESCRIPTORS} import descriptors"),
Self::TooManyImports => write!(f, "more than {MAX_IMPORTS} imported symbols"),
}
@@ -159,7 +221,7 @@ fn collect<F: Fn(u32) -> Option<usize>>(
return Ok(());
}
let module = reader.name(name_rva)?;
collect_symbols(reader, &module, lookup_rva, address_rva, entries)?;
collect_symbols(reader, &module, lookup_rva, address_rva, false, entries)?;
descriptor = descriptor
.checked_add(DESCRIPTOR_LEN)
.ok_or(ImportTableError::OutOfBounds { rva: descriptor })?;
@@ -167,11 +229,88 @@ fn collect<F: Fn(u32) -> Option<usize>>(
Err(ImportTableError::TooManyDescriptors)
}
/// Parse the delay-load directory of `directory_size` bytes at `directory_rva`.
///
/// Only descriptors that lie wholly inside the declared directory are read,
/// and the directory must hold the empty descriptor that ends the table.
/// Each entry's `iat_rva` is its slot in the delay import address table.
/// Returns every import before the first problem, and the problem.
pub fn parse_delay_imports(
bytes: &[u8],
directory_rva: u32,
directory_size: u32,
rva_to_offset: impl Fn(u32) -> Option<usize>,
) -> (Vec<ImportEntry>, Option<ImportTableError>) {
let reader = Reader {
bytes,
rva_to_offset,
};
let mut entries = Vec::new();
let error = collect_delayed(&reader, directory_rva, directory_size, &mut entries).err();
(entries, error)
}
fn collect_delayed<F: Fn(u32) -> Option<usize>>(
reader: &Reader<'_, F>,
directory_rva: u32,
directory_size: u32,
entries: &mut Vec<ImportEntry>,
) -> Result<(), ImportTableError> {
let end = directory_rva
.checked_add(directory_size)
.ok_or(ImportTableError::OutOfBounds { rva: directory_rva })?;
let mut descriptor = directory_rva;
for _ in 0..MAX_DESCRIPTORS {
if end - descriptor < DELAY_DESCRIPTOR_LEN {
return Err(ImportTableError::DelayDirectoryEnd { rva: end });
}
let fields = reader.array::<{ DELAY_DESCRIPTOR_LEN as usize }>(descriptor)?;
// The table ends with an empty descriptor.
if fields == [0; DELAY_DESCRIPTOR_LEN as usize] {
return Ok(());
}
let attributes = reader.u32(descriptor)?;
if attributes & !DELAY_RVA_BASED != 0 {
return Err(ImportTableError::DelayReservedBits { rva: descriptor });
}
if attributes & DELAY_RVA_BASED == 0 {
return Err(ImportTableError::DelayVirtualAddresses { rva: descriptor });
}
let name_rva = reader.u32(descriptor + 4)?;
let address_rva = reader.u32(descriptor + 12)?;
let names_rva = reader.u32(descriptor + 16)?;
// All three are required. The address table holds thunk addresses, so
// it cannot stand in for a missing name table.
for (field, rva) in [
(DelayField::DllName, name_rva),
(DelayField::AddressTable, address_rva),
(DelayField::NameTable, names_rva),
] {
if rva == 0 {
return Err(ImportTableError::DelayFieldMissing {
rva: descriptor,
field,
});
}
}
// Each must also start in section data, whether or not an import uses it.
reader.array::<1>(name_rva)?;
reader.array::<8>(address_rva)?;
reader.array::<8>(names_rva)?;
let module = reader.name(name_rva)?;
collect_symbols(reader, &module, names_rva, address_rva, true, entries)?;
// The declared end bounds this sum.
descriptor += DELAY_DESCRIPTOR_LEN;
}
Err(ImportTableError::TooManyDescriptors)
}
fn collect_symbols<F: Fn(u32) -> Option<usize>>(
reader: &Reader<'_, F>,
module: &str,
lookup_rva: u32,
address_rva: u32,
slots_on_disk: bool,
entries: &mut Vec<ImportEntry>,
) -> Result<(), ImportTableError> {
// Without a lookup table the address table holds the same entries on disk.
@@ -194,6 +333,10 @@ fn collect_symbols<F: Fn(u32) -> Option<usize>>(
return Err(ImportTableError::TooManyImports);
}
let iat_rva = at(address_rva)?;
if slots_on_disk {
// A delay-load slot starts out holding its thunk's address.
reader.array::<8>(iat_rva)?;
}
let name = if value & ORDINAL_FLAG != 0 {
let ordinal = value & !ORDINAL_FLAG;
ImportName::Ordinal(
+113 -28
View File
@@ -11,7 +11,9 @@
//! startup blockers.
use crate::dbt::{is_native, is_translatable};
use crate::import_table::{ImportName, ImportTableError, parse_imports};
use crate::import_table::{
ImportEntry, ImportName, ImportTableError, parse_delay_imports, parse_imports,
};
use crate::imports::{ImportRegistry, ServiceStatus};
use crate::memory::MemoryPermissions;
use crate::pe::{IMAGE_FILE_MACHINE_AMD64, PE32_PLUS_MAGIC, ParsedPe, PeError, PeSection};
@@ -678,6 +680,11 @@ pub struct ProbeReport {
pub imports: Vec<ImportedSymbol>,
/// Why the import table could not be read to its end.
pub import_error: Option<ImportTableError>,
/// Delay-loaded imports before the first malformed entry, if any. Binding
/// does not resolve them, so `imports` and its totals leave them out.
pub delayed_imports: Vec<ImportedSymbol>,
/// Why the delay-load import tables could not be read to their end.
pub delay_import_error: Option<ImportTableError>,
pub instruction_records: Vec<InstructionRecord>,
pub first_unsupported_dbt_insn: Option<InstructionRecord>,
}
@@ -822,6 +829,30 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
} else {
0
};
// The delay import descriptor is data directory 13. It exists only when
// NumberOfRvaAndSizes covers it.
let (delay_dir_rva, delay_dir_size) = if size_of_optional_header >= 224
&& u32::from_le_bytes(
bytes[opt_offset + 108..opt_offset + 112]
.try_into()
.unwrap(),
) > 13
{
(
u32::from_le_bytes(
bytes[opt_offset + 216..opt_offset + 220]
.try_into()
.unwrap(),
),
u32::from_le_bytes(
bytes[opt_offset + 220..opt_offset + 224]
.try_into()
.unwrap(),
),
)
} else {
(0, 0)
};
let section_table_offset = opt_offset + size_of_optional_header;
let section_header_size = 40;
@@ -960,35 +991,40 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
&mut registry,
Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))),
);
// Binding accepts only bytes backed by section data; match it exactly.
let backed_offset = |rva: u32| {
sections.iter().find_map(|section| {
let offset = rva.checked_sub(section.virtual_address)?;
(offset < section.raw_data_size)
.then(|| (section.raw_data_ptr as usize).checked_add(offset as usize))?
})
};
let (entries, import_error) = if import_dir_rva == 0 {
(Vec::new(), None)
} else {
// Binding accepts only bytes backed by section data; match it exactly.
parse_imports(bytes, import_dir_rva, |rva| {
sections.iter().find_map(|section| {
let offset = rva.checked_sub(section.virtual_address)?;
(offset < section.raw_data_size)
.then(|| (section.raw_data_ptr as usize).checked_add(offset as usize))?
})
})
parse_imports(bytes, import_dir_rva, backed_offset)
};
let imports: Vec<ImportedSymbol> = entries
.into_iter()
.map(|entry| {
let binding = registry.resolve(&entry.module, &entry.name);
ImportedSymbol {
category: ProbeReport::categorize_dll(&entry.module),
dll: entry.module,
symbol: entry.name.to_string(),
import_name: entry.name,
iat_rva: entry.iat_rva,
is_supported: binding.is_some(),
service_status: binding.map(|service| service.status),
canonical_module: binding.map(|service| service.module.clone()),
canonical_symbol: binding.map(|service| service.symbol.clone()),
}
})
.collect();
let (delayed_entries, delay_import_error) = if delay_dir_rva == 0 {
(Vec::new(), None)
} else {
parse_delay_imports(bytes, delay_dir_rva, delay_dir_size, backed_offset)
};
let describe = |entry: ImportEntry| {
let binding = registry.resolve(&entry.module, &entry.name);
ImportedSymbol {
category: ProbeReport::categorize_dll(&entry.module),
dll: entry.module,
symbol: entry.name.to_string(),
import_name: entry.name,
iat_rva: entry.iat_rva,
is_supported: binding.is_some(),
service_status: binding.map(|service| service.status),
canonical_module: binding.map(|service| service.module.clone()),
canonical_symbol: binding.map(|service| service.symbol.clone()),
}
};
let imports: Vec<ImportedSymbol> = entries.into_iter().map(&describe).collect();
let delayed_imports: Vec<ImportedSymbol> = delayed_entries.into_iter().map(&describe).collect();
// 4. Control-Flow-Aware Static Disassembly
//
@@ -1124,6 +1160,8 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
tls,
imports,
import_error,
delayed_imports,
delay_import_error,
instruction_records,
first_unsupported_dbt_insn,
})
@@ -1142,7 +1180,7 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
// 1. imports.csv
let mut imports_csv = String::from(
"module,symbol_or_ordinal,iat_rva,category,registered_binding,implementation_status,is_alias,canonical_module,startup_priority,startup_cluster,trusted_runner_binding,import_kind\n",
"module,symbol_or_ordinal,iat_rva,import_table,category,registered_binding,implementation_status,is_alias,canonical_module,startup_priority,startup_cluster,trusted_runner_binding,import_kind\n",
);
let mut missing_csv = String::from("module,symbol_or_ordinal,iat_rva,import_kind\n");
let mut modules = BTreeSet::new();
@@ -1186,7 +1224,7 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
let canonical = canonical.replace('"', "\"\"");
let _ = writeln!(
imports_csv,
"{key},{},{},{status},{is_alias},\"{canonical}\",{priority},{cluster},{trusted_binding},{import_kind}",
"{key},ordinary,{},{},{status},{is_alias},\"{canonical}\",{priority},{cluster},{trusted_binding},{import_kind}",
imp.category, imp.is_supported
);
if !imp.is_supported {
@@ -1194,6 +1232,34 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
missing += 1;
}
}
// Delay-loaded imports follow the ordinary rows. Binding does not resolve
// them, so they stay out of every ordinary total, the startup clusters and
// `missing_imports.csv`.
let mut delayed_modules = BTreeSet::new();
for imp in &report.delayed_imports {
delayed_modules.insert(imp.dll.to_ascii_lowercase());
let is_ordinal = matches!(imp.import_name, ImportName::Ordinal(_));
let import_kind = if is_ordinal { "ordinal" } else { "name" };
let module = imp.dll.replace('"', "\"\"");
let symbol = imp.symbol.replace('"', "\"\"");
let canonical = imp.canonical_module.as_deref().unwrap_or("");
let is_alias = imp.canonical_module.is_some() && !imp.dll.eq_ignore_ascii_case(canonical);
let canonical = canonical.replace('"', "\"\"");
let (priority, cluster) = imp.startup_priority();
let _ = writeln!(
imports_csv,
"\"{module}\",\"{symbol}\",0x{:08x},delayed,{},{},{},{is_alias},\"{canonical}\",{priority},{cluster},false,{import_kind}",
imp.iat_rva,
imp.category,
imp.is_supported,
imp.coverage_label()
);
}
let delayed_slots = report.delayed_imports.len();
let delayed_dlls = delayed_modules.len();
let delay_error = report
.delay_import_error
.map_or_else(|| "none".to_string(), |error| error.to_string());
fs::write(out.join("imports.csv"), imports_csv)?;
fs::write(out.join("missing_imports.csv"), missing_csv)?;
@@ -1250,6 +1316,9 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
"stub_slots": {stubs},
"recognized_unsupported_slots": {unsupported},
"missing_handler_slots": {unknown},
"delayed_imports": {delayed_slots},
"delayed_imported_dlls_count": {delayed_dlls},
"delay_import_error": "{delay_error}",
"total_relocations": {},
"dir64_relocations": {},
"tls_callbacks_count": {},
@@ -1381,6 +1450,16 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
"- **Import table is malformed**: {error}. Only the imports before it are listed, and binding refuses the image.\n"
);
}
let _ = writeln!(
md,
"- **Delay-Loaded Import Slots**: `{delayed_slots}` across `{delayed_dlls}` DLLs. They are marked `delayed` in `imports.csv` and are not part of the counts above or of `missing_imports.csv`: binding does not resolve them, and the PE format leaves them to the image's delay-load helper.\n"
);
if let Some(error) = &report.delay_import_error {
let _ = writeln!(
md,
"- **Delay-load import table is malformed**: {error}. Only the delay-loaded imports before it are listed.\n"
);
}
if trusted_runner_slots > 0 {
let _ = writeln!(
md,
@@ -1425,6 +1504,12 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
distinct_imports.len(),
unique_symbols.len()
);
if delayed_slots > 0 {
let _ = writeln!(
matrix,
"\nThe delay-load import tables contain {delayed_slots} more slots across {delayed_dlls} DLLs. They are not counted in this document."
);
}
let _ = writeln!(
matrix,
"\nRegistered slots include {implemented} implemented, {partial} partial, and {stubs} stubs. They reference {} canonical registered services through {aliases} alias slots. The {missing} unresolved slots include {unsupported} explicitly tracked unsupported APIs and {unknown} other missing handlers.",
+15
View File
@@ -251,6 +251,21 @@ impl ServicesState {
.unwrap_or(0)
}
/// Forget the last-error value of a guest thread that has ended, so a
/// later thread given the same TEB address starts at zero. Returns
/// whether a nonzero value was dropped.
///
/// Each service call names its own TEB and the values sit behind one
/// lock, so calls for different threads may run concurrently. Retire a
/// TEB only once no service call for that thread is still running.
pub fn retire_thread_last_error(&self, teb: u64) -> bool {
self.last_errors
.lock()
.expect("guest last-error state")
.remove(&teb)
.is_some()
}
fn set_last_error(&self, teb: u64, error: u32) {
let mut errors = self.last_errors.lock().expect("guest last-error state");
if error == 0 {
+20 -2
View File
@@ -50,6 +50,8 @@ pub struct Form {
pub no_rex_b: bool,
/// A 16-byte memory operand may have any alignment.
pub unaligned: bool,
/// The LOCK prefix is accepted when the ModRM operand is memory.
pub lockable: bool,
}
/// Opcode table entry.
@@ -167,6 +169,9 @@ pub struct Insn {
pub imm: u64,
/// Condition code for Jcc, CMOVcc and SETcc.
pub condition: u8,
/// Carries a LOCK prefix. Set only for a lockable form with a memory
/// destination.
pub lock: bool,
}
impl Insn {
@@ -231,8 +236,9 @@ impl<E, F: FnMut(u64) -> Result<u8, E>> Cursor<F> {
/// Decode one instruction at `rip`. `fetch` supplies the byte at an address and
/// is called only for bytes that belong to the instruction, in order.
///
/// Forms the registry does not declare, LOCK, address-size overrides and an
/// ignored segment override after FS or GS are rejected rather than approximated.
/// Forms the registry does not declare, LOCK anywhere but on a lockable form
/// with a memory destination, address-size overrides and an ignored segment
/// override after FS or GS are rejected rather than approximated.
pub fn decode<E>(
rip: u64,
fetch: impl FnMut(u64) -> Result<u8, E>,
@@ -246,6 +252,7 @@ pub fn decode<E>(
let mut operand_size = false;
let mut rep = false;
let mut repne = false;
let mut lock = false;
let mut segment = None;
let mut byte = cursor.u8()?;
loop {
@@ -267,6 +274,11 @@ pub fn decode<E>(
byte = cursor.u8()?;
continue;
}
0xF0 => {
lock = true;
byte = cursor.u8()?;
continue;
}
// CS, DS, ES and SS overrides have no effect in 64-bit mode. After
// FS or GS their meaning is not relied on, so it is rejected.
0x26 | 0x2E | 0x36 | 0x3E if segment.is_none() => {
@@ -413,6 +425,11 @@ pub fn decode<E>(
} else if matches!(form.encoding, Encoding::OpReg | Encoding::OpRegImm) {
reg = register(opcode & 7, rex_b, size);
}
// LOCK is an invalid opcode unless the instruction is lockable and its
// destination is memory (Intel SDM Vol. 2, "LOCK").
if lock && !(form.lockable && matches!(rm, Some(RmOperand::Mem(_)))) {
return Err(DecodeError::Unsupported(0xF0));
}
let mut imm = match form.immediate {
Immediate::None => 0,
@@ -449,6 +466,7 @@ pub fn decode<E>(
reg,
imm,
condition: opcode & 0xF,
lock,
})
}
+39 -1
View File
@@ -10,7 +10,7 @@
//! the state unchanged. Flags that the architecture leaves undefined keep their
//! previous value, which is permitted but not something guests may rely on.
use crate::cpu::{CpuState, ExitReason, RFlags, Register};
use crate::cpu::{CpuState, ExitReason, RFlags, Register, cpuid};
use crate::memory::GuestMemory;
use crate::x86_decode::{Encoding, Insn, MemOperand, RegOperand, RmOperand, Segment};
use crate::x86_simd;
@@ -19,6 +19,7 @@ use crate::x86_table::Op;
const RAX: usize = Register::Rax as usize;
const RCX: usize = Register::Rcx as usize;
const RDX: usize = Register::Rdx as usize;
const RBX: usize = Register::Rbx as usize;
const RSP: usize = Register::Rsp as usize;
const RBP: usize = Register::Rbp as usize;
@@ -369,6 +370,35 @@ pub fn execute(
write_rm(cpu, memory, insn, b)?;
write_reg(cpu, insn.reg, size, a);
}
Op::Xadd => {
let (a, b) = operands(cpu, memory, insn)?;
let (value, flags) = add(a, b, false, size);
write_rm(cpu, memory, insn, value)?;
// The source is loaded before the destination is stored, so a
// register added to itself keeps the sum.
if insn.rm != Some(RmOperand::Reg(insn.reg)) {
write_reg(cpu, insn.reg, size, a);
}
cpu.flags = flags;
}
Op::Cmpxchg => {
let (destination, source) = operands(cpu, memory, insn)?;
let expected = cpu.gpr[RAX] & mask(size);
let (_, flags) = sub(expected, destination, false, size);
// The destination is written whether or not the values match, so a
// mismatch on memory that cannot be written still faults.
let matched = expected == destination;
write_rm(
cpu,
memory,
insn,
if matched { source } else { destination },
)?;
if !matched {
write_reg(cpu, accumulator(RAX), size, destination);
}
cpu.flags = flags;
}
Op::Bswap => {
let value = read_reg(cpu, insn.reg, size).swap_bytes() >> (64 - 8 * u32::from(size));
write_reg(cpu, insn.reg, size, value);
@@ -544,6 +574,14 @@ pub fn execute(
cpu.gpr[RSP] = sp.wrapping_add(8).wrapping_add(insn.imm);
}
Op::Nop => {}
Op::Cpuid => {
// The leaf is EAX and the subleaf ECX. Each result is a 32-bit
// register write, so the upper halves are cleared.
let values = cpuid(cpu.gpr[RAX] as u32, cpu.gpr[RCX] as u32);
for (register, value) in [RAX, RBX, RCX, RDX].into_iter().zip(values) {
cpu.gpr[register] = u64::from(value);
}
}
Op::Clc => cpu.flags.cf = false,
Op::Stc => cpu.flags.cf = true,
Op::Cmc => cpu.flags.cf = !cpu.flags.cf,
File diff suppressed because it is too large. Load diff
+282
View File
@@ -0,0 +1,282 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! The guest CPUID contract (issue #130).
//!
//! CPUID reports a fixed synthetic processor. A feature bit is set only when
//! every instruction of that feature is implemented, so each bit that is set
//! is checked against instructions that run, and each bit software commonly
//! tests that is clear has a witness instruction of that feature which both
//! engines refuse. The witness must be removed before its bit can be set.
//!
//! Bit positions and the feature each instruction belongs to are from the
//! Intel SDM Vol. 2, CPUID and the instruction entries. Encodings were
//! assembled with `clang -target x86_64-apple-macos` and read with `objdump`.
use xenora_loader::cpu::{
CPUID_CMOV, CPUID_LONG_MODE, CPUID_LZCNT, CPUID_POPCNT, CpuState, ExitReason, Interpreter,
RFlags, cpuid,
};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
use xenora_loader::x86_decode::decode;
const ENTRY: u64 = 0x1000;
const RAX: usize = 0;
const RCX: usize = 1;
const RDX: usize = 2;
const RBX: usize = 3;
const RSI: usize = 6;
/// Index of a CPUID result, which come in the order EAX, EBX, ECX, EDX.
const EBX: usize = 1;
const ECX: usize = 2;
const EDX: usize = 3;
fn image(code: &[u8]) -> GuestMemory {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
.unwrap();
memory
}
/// Final state and exit reason from the interpreter, then from the DBT.
fn both(cpu: &CpuState, code: &[u8], budget: usize) -> [(&'static str, CpuState, ExitReason); 2] {
let mut memory = image(code);
let interpreted = Interpreter::new(cpu.clone(), &mut memory, budget).run();
let mut memory = image(code);
let mut state = cpu.clone();
let translated = DbtEngine::new(64 * 1024)
.unwrap()
.run(&mut state, &mut memory, budget);
[
(
"interpreter",
interpreted.final_state,
interpreted.exit_reason,
),
("DBT", translated.final_state, translated.exit_reason),
]
}
const SET: RFlags = RFlags {
cf: true,
zf: true,
sf: true,
of: true,
pf: true,
af: true,
};
#[test]
fn every_leaf_returns_its_documented_values() {
// (leaf, subleaf, [EAX, EBX, ECX, EDX])
let leaves: &[(u32, u32, [u32; 4])] = &[
// Highest basic leaf 1, and "Xeno", "uest", "ra g" as little-endian text.
(0, 0, [1, 0x6F6E_6558, 0x7473_6575, 0x6720_6172]),
// POPCNT is ECX bit 23 and CMOV is EDX bit 15. No signature.
(1, 0, [0, 0, 0x0080_0000, 0x0000_8000]),
(1, 0xFFFF_FFFF, [0, 0, 0x0080_0000, 0x0000_8000]),
// Highest extended leaf.
(0x8000_0000, 0, [0x8000_0001, 0, 0, 0]),
// LZCNT is ECX bit 5 and long mode is EDX bit 29.
(0x8000_0001, 0, [0, 0, 0x0000_0020, 0x2000_0000]),
(0x8000_0001, 7, [0, 0, 0x0000_0020, 0x2000_0000]),
// Everything else, above or between the highest leaves, is zeros.
(2, 0, [0; 4]),
(4, 0, [0; 4]),
(6, 0, [0; 4]),
(7, 0, [0; 4]),
(7, 1, [0; 4]),
(0xB, 0, [0; 4]),
(0xD, 1, [0; 4]),
(0x16, 0, [0; 4]),
(0x4000_0000, 0, [0; 4]),
(0x7FFF_FFFF, 0, [0; 4]),
(0x8000_0002, 0, [0; 4]),
(0x8000_0008, 0, [0; 4]),
(0xFFFF_FFFF, 0, [0; 4]),
];
for &(leaf, subleaf, wanted) in leaves {
// Only EAX and ECX select the leaf: the upper halves are noise.
let mut cpu = CpuState::new(ENTRY, 0);
for (index, register) in cpu.gpr.iter_mut().enumerate() {
*register = 0xA5A5_0000_1111_0000 + index as u64;
}
cpu.gpr[RAX] = 0xDEAD_BEEF_0000_0000 | u64::from(leaf);
cpu.gpr[RCX] = 0xFEED_FACE_0000_0000 | u64::from(subleaf);
cpu.flags = SET;
// Each result is a 32-bit register write, so it clears the upper half.
// CPUID changes no flag and no other register.
let mut expected = cpu.clone();
expected.rip = ENTRY + 2;
for (register, value) in [RAX, RBX, RCX, RDX].into_iter().zip(wanted) {
expected.gpr[register] = u64::from(value);
}
for (engine, state, exit) in both(&cpu, &[0x0F, 0xA2], 1) {
let what = format!("leaf {leaf:#x} subleaf {subleaf:#x} on the {engine}");
assert_eq!(exit, ExitReason::StepLimitExceeded, "{what}");
assert_eq!(state, expected, "{what}");
}
// The function a runtime service would read agrees with the instruction.
assert_eq!(cpuid(leaf, subleaf), wanted, "leaf {leaf:#x}");
}
let [_, ebx, ecx, edx] = cpuid(0, 0);
let vendor: Vec<u8> = [ebx, edx, ecx]
.into_iter()
.flat_map(u32::to_le_bytes)
.collect();
assert_eq!(vendor, b"Xenora guest");
assert_eq!(
(CPUID_POPCNT, CPUID_CMOV, CPUID_LZCNT, CPUID_LONG_MODE),
(1 << 23, 1 << 15, 1 << 5, 1 << 29)
);
}
#[test]
fn reported_features_have_all_their_instructions_in_the_fixtures() {
// `tests/x86_integer.rs` runs every line of this file through both engines
// against an independent reference. Here each reported feature must have
// its whole instruction set among those lines.
let fixture = include_str!("x86/integer.txt");
let decodable = |text: &str| {
let line = fixture
.lines()
.find(|line| line.split_once(" | ").is_some_and(|(_, asm)| asm == text))
.unwrap_or_else(|| panic!("no fixture for {text}"));
let code: Vec<u8> = line
.split_once(" | ")
.unwrap()
.0
.split(' ')
.map(|byte| u8::from_str_radix(byte, 16).unwrap())
.collect();
decode(ENTRY, |at| {
code.get((at - ENTRY) as usize).copied().ok_or(())
})
.unwrap_or_else(|error| panic!("{text}: {error:?}"));
};
let memory = |bits: u32| {
let width = match bits {
16 => "word",
32 => "dword",
_ => "qword",
};
format!("{width} ptr [rsi + 4*rdi + 16]")
};
// 16-, 32- and 64-bit destinations (RBX and R10) from a register and from memory.
let sizes = [
(16, "bx", "r9w", "r10w"),
(32, "ebx", "r9d", "r10d"),
(64, "rbx", "r9", "r10"),
];
assert_ne!(cpuid(1, 0)[EDX] & CPUID_CMOV, 0);
for condition in "o no b ae e ne be a s ns p np l ge le g".split(' ') {
for (bits, low, source, high) in sizes {
decodable(&format!("cmov{condition} {low}, {source}"));
decodable(&format!("cmov{condition} {high}, {}", memory(bits)));
}
}
for (feature, bit, name) in [
(cpuid(1, 0)[ECX], CPUID_POPCNT, "popcnt"),
(cpuid(0x8000_0001, 0)[ECX], CPUID_LZCNT, "lzcnt"),
] {
assert_ne!(feature & bit, 0, "{name}");
for (bits, low, source, high) in sizes {
decodable(&format!("{name} {low}, {source}"));
decodable(&format!("{name} {high}, {}", memory(bits)));
}
}
// Long mode: 64-bit operands and the registers only it has.
assert_ne!(cpuid(0x8000_0001, 0)[EDX] & CPUID_LONG_MODE, 0);
decodable("add r9, r12");
decodable("movabs r15, 0x8877665544332211");
}
#[test]
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
(
"PCLMULQDQ",
1,
ECX,
1,
&[0x66, 0x0F, 0x3A, 0x44, 0xC1, 0x00],
), // pclmulqdq xmm0, xmm1, 0
("SSSE3", 1, ECX, 9, &[0x66, 0x0F, 0x38, 0x00, 0xC1]), // pshufb xmm0, xmm1
("FMA", 1, ECX, 12, &[0xC4, 0xE2, 0x71, 0x98, 0xC2]), // vfmadd132ps xmm0, xmm1, xmm2
("CMPXCHG16B", 1, ECX, 13, &[0x48, 0x0F, 0xC7, 0x0E]), // cmpxchg16b [rsi]
("SSE4.1", 1, ECX, 19, &[0x66, 0x0F, 0x38, 0x40, 0xC1]), // pmulld xmm0, xmm1
("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
("F16C", 1, ECX, 29, &[0xC4, 0xE2, 0x79, 0x13, 0xC1]), // vcvtph2ps xmm0, xmm1
("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
("BMI2", 7, EBX, 8, &[0xC4, 0xE2, 0x73, 0xF6, 0xC2]), // mulx eax, ecx, edx
("RDSEED", 7, EBX, 18, &[0x0F, 0xC7, 0xF8]), // rdseed eax
("ADX", 7, EBX, 19, &[0x66, 0x0F, 0x38, 0xF6, 0xC1]), // adcx eax, ecx
("SHA", 7, EBX, 29, &[0x0F, 0x38, 0xC9, 0xC1]), // sha1msg1 xmm0, xmm1
("LAHF/SAHF", 0x8000_0001, ECX, 0, &[0x9F]), // lahf
("PREFETCHW", 0x8000_0001, ECX, 8, &[0x0F, 0x0D, 0x0E]), // prefetchw [rsi]
("SYSCALL/SYSRET", 0x8000_0001, EDX, 11, &[0x48, 0x0F, 0x07]), // sysretq
("RDTSCP", 0x8000_0001, EDX, 27, &[0x0F, 0x01, 0xF9]), // rdtscp
];
for &(feature, leaf, register, bit, code) in witnesses {
assert_eq!(
cpuid(leaf, 0)[register] >> bit & 1,
0,
"{feature} is reported"
);
let mut padded = code.to_vec();
padded.extend([0x90; 8]);
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RSI] = ENTRY;
for (engine, state, exit) in both(&cpu, &padded, 1) {
assert!(
matches!(exit, ExitReason::IllegalInstruction(_)),
"{feature}: {code:02X?} ran on the {engine} ({exit:?}); report the feature only \
once all of it is implemented"
);
assert_eq!(state, cpu, "{feature} on the {engine}");
}
}
}
#[test]
fn a_guest_can_use_an_instruction_after_testing_its_feature_bit() {
// mov eax, 1
// cpuid
// bt ecx, 23 ; POPCNT
// jnc done
// popcnt rax, rsi
// done: hlt
let code = [
0xB8, 0x01, 0x00, 0x00, 0x00, 0x0F, 0xA2, 0x0F, 0xBA, 0xE1, 0x17, 0x73, 0x05, 0xF3, 0x48,
0x0F, 0xB8, 0xC6, 0xF4,
];
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RSI] = 0xF0F0_0000_0000_0001;
for (engine, state, exit) in both(&cpu, &code, 16) {
assert_eq!(exit, ExitReason::Halt, "{engine}");
// Nine bits are set in RSI. Leaf 1 leaves EAX zero, so a skipped
// POPCNT would show as 0.
assert_eq!(state.gpr[RAX], 9, "{engine}");
assert_eq!(state.rip, ENTRY + code.len() as u64, "{engine}");
}
}
-14
View File
@@ -2672,15 +2672,9 @@ const UNSUPPORTED: &[(&str, usize)] = &[
("cmpxchg16b_not_equal", 0),
("cmpxchg16b_unaligned_is_gp", 0),
("cmpxchg16b_unaligned_without_lock_is_gp", 0),
("cmpxchg32_equal", 0),
("cmpxchg64_memory_equal_without_lock", 0),
("cmpxchg64_memory_not_equal", 0),
("cmpxchg64_memory_not_equal_without_lock", 0),
("cmpxchg8_not_equal_loads_al", 0),
("cmpxchg8b_equal", 0),
("cmpxchg8b_equal_without_lock", 0),
("cmpxchg8b_not_equal", 0),
("cmpxchg_mismatch_still_writes", 0),
("crc32c_byte_and_qword_forms_agree", 0),
("crc32c_check_string", 0),
("dpps_mask", 0),
@@ -2689,8 +2683,6 @@ const UNSUPPORTED: &[(&str, usize)] = &[
("fs_addr32_truncates_before_adding_base", 0),
("fs_rep_movsb_overrides_source_only", 0),
("fs_rep_movsb_overrides_source_only_df_clear", 0),
("gs_lock_xadd", 0),
("gs_xadd_without_lock", 0),
("haddps_hsubpd_addsubps", 0),
("insertps_zero_mask", 0),
("jecxz_tests_low_32_bits", 1),
@@ -2783,12 +2775,6 @@ const UNSUPPORTED: &[(&str, usize)] = &[
("shrd32_by8", 0),
("shrd64_by1_sign_change", 0),
("shrd64_cl64_is_count_zero", 0),
("xadd32_reg_reg", 0),
("xadd64_memory", 0),
("xadd64_memory_without_lock", 0),
("xadd64_same_register_doubles", 0),
("xadd8_al_ah", 0),
("xadd_readonly_page_keeps_register", 0),
("xchg_ax_r9w_preserves_both_uppers", 0),
("xchg_eax_ebx_clears_both_uppers", 0),
("xchg_rax_r8_is_not_nop", 0),
+419
View File
@@ -0,0 +1,419 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Static probe reports for delay-loaded PE imports.
//!
//! The expected names and slot RVAs are read off the layout that
//! `fixtures/pe/delay-imports.py` writes, not from the parser.
//! `llvm-readobj --coff-imports` from LLVM 23.1.6 lists the same imports in
//! the same order, with the address tables at RVA 0x2050, 0x3000 and 0x3020.
use std::collections::BTreeMap;
use xenora_loader::import_table::{DelayField, ImportTableError, parse_delay_imports};
use xenora_loader::probe::{
ImportedSymbol, ProbeConfig, ProbeReport, probe_pe_bytes, run_probe_and_export,
};
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/delay-imports.exe");
/// DLL, symbol or ordinal, and import address table slot RVA.
type Row = (&'static str, &'static str, u32);
const ORDINARY: [Row; 2] = [
("fixture-ordinary.dll", "OrdinaryByName", 0x2050),
("fixture-ordinary.dll", "Ordinal#3", 0x2058),
];
const DELAYED: [Row; 3] = [
("fixture-delay-a.dll", "DelayedAlpha", 0x3000),
("fixture-delay-a.dll", "Ordinal#7", 0x3008),
("fixture-delay-b.dll", "DelayedBeta", 0x3020),
];
// File offsets in the fixture.
const NUMBER_OF_RVA_AND_SIZES: usize = 0x98 + 108;
const DELAY_DIRECTORY_ENTRY: usize = 0x98 + 216;
const DELAY_DIRECTORY_SIZE: usize = DELAY_DIRECTORY_ENTRY + 4;
const RDATA_RAW_SIZE: usize = 0x188 + 40 + 16;
/// The delay-load directory is at RVA 0x2200; `.rdata` maps RVA 0x2000 to 0x600.
const FIRST_DESCRIPTOR: usize = 0x800;
const SECOND_DESCRIPTOR: usize = 0x820;
fn rows(imports: &[ImportedSymbol]) -> Vec<(&str, &str, u32)> {
imports
.iter()
.map(|import| (import.dll.as_str(), import.symbol.as_str(), import.iat_rva))
.collect()
}
fn put(pe: &mut [u8], offset: usize, value: u32) {
pe[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
}
/// Probe `pe` and return the report with the text files it exports.
fn export(pe: &[u8], name: &str) -> (ProbeReport, BTreeMap<&'static str, String>) {
let dir =
std::env::temp_dir().join(format!("xenora-probe-delay-{name}-{}", std::process::id()));
let report = run_probe_and_export(pe, &dir, &ProbeConfig::default()).unwrap();
let files = [
"imports.csv",
"missing_imports.csv",
"candidate_static_report.json",
"candidate_static_report.md",
"runtime_gap_matrix.md",
]
.into_iter()
.map(|file| (file, std::fs::read_to_string(dir.join(file)).unwrap()))
.collect();
std::fs::remove_dir_all(dir).unwrap();
(report, files)
}
fn json_field(json: &str, name: &str) -> String {
let prefix = format!("\"{name}\": ");
json.lines()
.find_map(|line| line.trim().strip_prefix(&prefix))
.unwrap_or_else(|| panic!("no {name} in the JSON report"))
.trim_end_matches(',')
.trim_matches('"')
.to_string()
}
#[test]
fn ordinary_and_delayed_imports_are_reported_apart() {
let (report, files) = export(FIXTURE, "fixture");
assert_eq!(rows(&report.imports), ORDINARY);
assert_eq!(rows(&report.delayed_imports), DELAYED);
assert_eq!(report.import_error, None);
assert_eq!(report.delay_import_error, None);
let mut lines = files["imports.csv"].lines();
let header = lines.next().unwrap();
assert!(header.starts_with("module,symbol_or_ordinal,iat_rva,import_table,"));
assert!(header.ends_with(",import_kind"));
let columns = header.split(',').count();
// The first four columns and the last one of every row.
let listed: Vec<String> = lines
.map(|line| {
let fields: Vec<&str> = line.split(',').collect();
assert_eq!(fields.len(), columns, "{line}");
format!("{},{}", fields[..4].join(","), fields[columns - 1])
})
.collect();
assert_eq!(
listed,
[
"\"fixture-ordinary.dll\",\"OrdinaryByName\",0x00002050,ordinary,name",
"\"fixture-ordinary.dll\",\"Ordinal#3\",0x00002058,ordinary,ordinal",
"\"fixture-delay-a.dll\",\"DelayedAlpha\",0x00003000,delayed,name",
"\"fixture-delay-a.dll\",\"Ordinal#7\",0x00003008,delayed,ordinal",
"\"fixture-delay-b.dll\",\"DelayedBeta\",0x00003020,delayed,name",
]
);
// Neither fixture DLL has a handler, so both ordinary imports are missing.
// The delayed ones are not the binder's to resolve and stay off its list.
assert_eq!(
files["missing_imports.csv"].lines().collect::<Vec<_>>(),
[
"module,symbol_or_ordinal,iat_rva,import_kind",
"\"fixture-ordinary.dll\",\"OrdinaryByName\",0x00002050,name",
"\"fixture-ordinary.dll\",\"Ordinal#3\",0x00002058,ordinal",
]
);
let json = &files["candidate_static_report.json"];
for (name, expected) in [
("total_imports", "2"),
("imported_dlls_count", "1"),
("unresolved_imports", "2"),
("distinct_import_keys", "2"),
("delayed_imports", "3"),
("delayed_imported_dlls_count", "2"),
("delay_import_error", "none"),
] {
assert_eq!(json_field(json, name), expected, "{name}");
}
let md = &files["candidate_static_report.md"];
assert!(md.contains("- **Total Imported Thunks**: `2`"));
assert!(md.contains("- **Delay-Loaded Import Slots**: `3` across `2` DLLs."));
assert!(!md.contains("Delay-load import table is malformed"));
assert!(
files["runtime_gap_matrix.md"]
.contains("The delay-load import tables contain 3 more slots across 2 DLLs.")
);
}
#[test]
fn inspection_decodes_the_entry_point_and_follows_no_delay_slot() {
let report = probe_pe_bytes(FIXTURE, &ProbeConfig::default()).unwrap();
// The entry point is a lone RET at RVA 0x1000. The three delay-load slots
// hold the addresses of INT3 stubs at 0x1010, 0x1018 and 0x1020. Reaching
// one would mean the probe followed a slot, so none may be decoded.
let decoded: Vec<(u32, &[u8])> = report
.instruction_records
.iter()
.map(|record| (record.rva, record.bytes.as_slice()))
.collect();
assert_eq!(decoded, [(0x1000, &[0xc3][..])]);
}
#[test]
fn image_without_a_delay_directory_keeps_its_ordinary_imports() {
// `fixtures/pe/trusted-runner.py` writes one import, `xenora.dll!fixture_draw`,
// with its slot at RVA 0x2040 and no delay import descriptor.
let runner = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
let (report, files) = export(runner, "runner");
assert_eq!(
rows(&report.imports),
[("xenora.dll", "fixture_draw", 0x2040)]
);
assert_eq!(report.import_error, None);
assert!(report.delayed_imports.is_empty());
assert_eq!(report.delay_import_error, None);
let listed: Vec<&str> = files["imports.csv"].lines().skip(1).collect();
assert_eq!(listed.len(), 1);
assert!(listed[0].starts_with("\"xenora.dll\",\"fixture_draw\",0x00002040,ordinary,"));
let json = &files["candidate_static_report.json"];
assert_eq!(json_field(json, "total_imports"), "1");
assert_eq!(json_field(json, "imported_dlls_count"), "1");
assert_eq!(json_field(json, "delayed_imports"), "0");
assert_eq!(json_field(json, "delayed_imported_dlls_count"), "0");
assert_eq!(json_field(json, "delay_import_error"), "none");
assert!(!files["runtime_gap_matrix.md"].contains("delay-load"));
}
#[test]
fn delay_directory_beyond_the_declared_count_is_not_read() {
// With 13 data directories the header has no delay import descriptor, so
// the bytes at its offset mean nothing.
let mut pe = FIXTURE.to_vec();
put(&mut pe, NUMBER_OF_RVA_AND_SIZES, 13);
let report = probe_pe_bytes(&pe, &ProbeConfig::default()).unwrap();
assert_eq!(rows(&report.imports), ORDINARY);
assert!(report.delayed_imports.is_empty());
assert_eq!(report.delay_import_error, None);
}
#[test]
fn malformed_delay_tables_are_diagnosed_and_ordinary_imports_kept() {
type Case = (
&'static str,
fn(&mut Vec<u8>),
usize,
ImportTableError,
&'static str,
);
// (name, damage, delayed imports still listed, error, message)
let cases: [Case; 13] = [
(
"directory-out-of-range",
|pe| put(pe, DELAY_DIRECTORY_ENTRY, 0x9000),
0,
ImportTableError::OutOfBounds { rva: 0x9000 },
"import data at RVA 0x00009000 is truncated or outside the section data",
),
(
// `.rdata` keeps 0x230 bytes: the first descriptor and half the second.
"section-data-ends-inside-descriptor",
|pe| put(pe, RDATA_RAW_SIZE, 0x230),
2,
ImportTableError::OutOfBounds { rva: 0x2220 },
"import data at RVA 0x00002220 is truncated or outside the section data",
),
(
// The file ends where `.data` and its address tables would begin.
"file-ends-before-address-table",
|pe| pe.truncate(0xa00),
0,
ImportTableError::OutOfBounds { rva: 0x3000 },
"import data at RVA 0x00003000 is truncated or outside the section data",
),
(
"name-table-out-of-range",
|pe| put(pe, FIRST_DESCRIPTOR + 16, 0x9000),
0,
ImportTableError::OutOfBounds { rva: 0x9000 },
"import data at RVA 0x00009000 is truncated or outside the section data",
),
(
"address-table-out-of-range",
|pe| put(pe, SECOND_DESCRIPTOR + 12, 0x9000),
2,
ImportTableError::OutOfBounds { rva: 0x9000 },
"import data at RVA 0x00009000 is truncated or outside the section data",
),
(
// The second DLL's name table becomes the empty entry that ends the
// first one, at RVA 0x2110, so no import reads the address table.
"address-table-out-of-range-without-imports",
|pe| {
put(pe, SECOND_DESCRIPTOR + 16, 0x2110);
put(pe, SECOND_DESCRIPTOR + 12, 0x9000);
},
2,
ImportTableError::OutOfBounds { rva: 0x9000 },
"import data at RVA 0x00009000 is truncated or outside the section data",
),
(
"dll-name-out-of-range",
|pe| put(pe, SECOND_DESCRIPTOR + 4, 0x9000),
2,
ImportTableError::OutOfBounds { rva: 0x9000 },
"import data at RVA 0x00009000 is truncated or outside the section data",
),
(
// RVA 0x2028 is zero padding after the ordinary import directory.
"dll-name-empty",
|pe| put(pe, SECOND_DESCRIPTOR + 4, 0x2028),
2,
ImportTableError::MalformedName { rva: 0x2028 },
"malformed import name at RVA 0x00002028",
),
(
"dll-name-missing",
|pe| put(pe, SECOND_DESCRIPTOR + 4, 0),
2,
ImportTableError::DelayFieldMissing {
rva: 0x2220,
field: DelayField::DllName,
},
"delay-load descriptor at RVA 0x00002220 has no DLL name",
),
(
"address-table-missing",
|pe| put(pe, FIRST_DESCRIPTOR + 12, 0),
0,
ImportTableError::DelayFieldMissing {
rva: 0x2200,
field: DelayField::AddressTable,
},
"delay-load descriptor at RVA 0x00002200 has no import address table",
),
(
"name-table-missing",
|pe| put(pe, SECOND_DESCRIPTOR + 16, 0),
2,
ImportTableError::DelayFieldMissing {
rva: 0x2220,
field: DelayField::NameTable,
},
"delay-load descriptor at RVA 0x00002220 has no import name table",
),
(
"reserved-attribute-bit",
|pe| put(pe, FIRST_DESCRIPTOR, 3),
0,
ImportTableError::DelayReservedBits { rva: 0x2200 },
"reserved attribute bits set in the delay-load descriptor at RVA 0x00002200",
),
(
"virtual-address-form",
|pe| put(pe, SECOND_DESCRIPTOR, 0),
2,
ImportTableError::DelayVirtualAddresses { rva: 0x2220 },
"delay-load descriptor at RVA 0x00002220 holds virtual addresses, not RVAs, and is not read",
),
];
for (name, damage, listed, error, message) in cases {
let mut pe = FIXTURE.to_vec();
damage(&mut pe);
let (report, files) = export(&pe, name);
assert_eq!(rows(&report.imports), ORDINARY, "{name}");
assert_eq!(report.import_error, None, "{name}");
assert_eq!(rows(&report.delayed_imports), DELAYED[..listed], "{name}");
assert_eq!(report.delay_import_error, Some(error), "{name}");
assert_eq!(error.to_string(), message, "{name}");
let json = &files["candidate_static_report.json"];
assert_eq!(json_field(json, "total_imports"), "2", "{name}");
assert_eq!(
json_field(json, "delayed_imports"),
listed.to_string(),
"{name}"
);
assert_eq!(json_field(json, "delay_import_error"), message, "{name}");
assert!(
files["candidate_static_report.md"].contains(&format!(
"- **Delay-load import table is malformed**: {message}. Only the delay-loaded imports before it are listed."
)),
"{name}"
);
}
}
#[test]
fn declared_directory_size_bounds_the_table() {
// The fixture declares 96 bytes at RVA 0x2200: two descriptors and the
// empty one. A descriptor counts only if the declared size holds all of
// it, and the size must reach the empty descriptor.
let end = |rva| Some(ImportTableError::DelayDirectoryEnd { rva });
for (size, listed, error) in [
(0, 0, end(0x2200)),
(31, 0, end(0x221f)),
(32, 2, end(0x2220)),
(63, 2, end(0x223f)),
(64, 3, end(0x2240)),
(95, 3, end(0x225f)),
(96, 3, None),
(97, 3, None),
(0x1000, 3, None),
// The directory would run past the end of the address space.
(
u32::MAX,
0,
Some(ImportTableError::OutOfBounds { rva: 0x2200 }),
),
] {
let mut pe = FIXTURE.to_vec();
put(&mut pe, DELAY_DIRECTORY_SIZE, size);
let report = probe_pe_bytes(&pe, &ProbeConfig::default()).unwrap();
assert_eq!(rows(&report.imports), ORDINARY, "size {size}");
assert_eq!(
rows(&report.delayed_imports),
DELAYED[..listed],
"size {size}"
);
assert_eq!(report.delay_import_error, error, "size {size}");
}
assert_eq!(
ImportTableError::DelayDirectoryEnd { rva: 0x2240 }.to_string(),
"delay-load directory ends at RVA 0x00002240 before its empty descriptor"
);
}
#[test]
fn endless_delay_table_is_refused() {
// Every descriptor RVA maps onto the same 32 bytes, so the table never
// reaches its empty entry within the megabyte it declares. The descriptor
// names module "a" at RVA 0x1000, an empty name table at RVA 0x2000 and an
// address table at RVA 0x3000.
let mut bytes = vec![0u8; 48];
put(&mut bytes, 0, 1);
put(&mut bytes, 4, 0x1000);
put(&mut bytes, 12, 0x3000);
put(&mut bytes, 16, 0x2000);
bytes[32] = b'a';
let (imports, error) = parse_delay_imports(&bytes, 0x10_0000, 0x10_0000, |rva| match rva {
0x1000..0x1002 => Some(32 + (rva - 0x1000) as usize),
0x2000..0x2008 => Some(40 + (rva - 0x2000) as usize),
0x3000..0x3008 => Some(40 + (rva - 0x3000) as usize),
0x10_0000.. => Some((rva % 32) as usize),
_ => None,
});
assert!(imports.is_empty());
assert_eq!(error, Some(ImportTableError::TooManyDescriptors));
}
#[test]
fn probe_never_panics_on_a_truncated_delay_fixture() {
for len in 1..=FIXTURE.len() {
// The probe may reject the file or report unreadable imports, but it
// must not panic.
let _ = probe_pe_bytes(&FIXTURE[..len], &ProbeConfig::default());
}
}
+54 -4
View File
@@ -120,17 +120,24 @@ fn build(imports: &[(&str, Symbol)]) -> Image {
}
fn standard(clock: u64) -> (ImportRegistry, Arc<MockClock>) {
let clock = Arc::new(MockClock::new(clock));
let mut registry = ImportRegistry::new();
register_standard_services(&mut registry, Arc::new(ServicesState::new(clock.clone())));
let (registry, clock, _) = standard_with_state(clock);
(registry, clock)
}
fn standard_with_state(clock: u64) -> (ImportRegistry, Arc<MockClock>, Arc<ServicesState>) {
let clock = Arc::new(MockClock::new(clock));
let state = Arc::new(ServicesState::new(clock.clone()));
let mut registry = ImportRegistry::new();
register_standard_services(&mut registry, state.clone());
(registry, clock, state)
}
/// A guest whose image imports every generated service from its own library.
struct Guest {
engine: DbtEngine,
memory: GuestMemory,
clock: Arc<MockClock>,
state: Arc<ServicesState>,
teb: u64,
/// Upper halves and XMM lanes of unrelated arguments hold this pattern.
xmm: [u128; 4],
@@ -151,7 +158,7 @@ impl Guest {
memory
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
.unwrap();
let (mut registry, clock) = standard(0x01DA_0000_1234_5678);
let (mut registry, clock, state) = standard_with_state(0x01DA_0000_1234_5678);
let bound = registry
.bind_imports(&pe, &image.bytes, BASE, &mut memory)
.unwrap();
@@ -162,6 +169,7 @@ impl Guest {
engine,
memory,
clock,
state,
teb: 0,
xmm: [0xAAAA_BBBB_CCCC_DDDD_EEEE_FFFF_0123_4567; 4],
}
@@ -554,6 +562,48 @@ fn last_error_isolated_across_guest_thread_switches() {
assert_eq!(guest.last_error(), 6);
}
/// The last-error code is documented as kept per thread, and most functions
/// set it only when they fail (errhandlingapi.h GetLastError).
#[test]
fn a_successful_call_keeps_another_threads_error_and_its_own() {
let mut guest = Guest::new();
guest.teb = 0x10000;
assert_eq!(guest.call("VirtualAlloc", &[0, 0, 0x3000, 4]), 0);
assert_eq!(guest.last_error(), 87); // ERROR_INVALID_PARAMETER
guest.teb = 0x20000;
guest.call("SetLastError", &[0xFFFF_FFFF]);
assert_eq!(guest.call("GetCurrentProcess", &[]), PROCESS);
assert_eq!(guest.call("GetCurrentThreadId", &[]), 0x4104);
assert_eq!(
guest.last_error(),
0xFFFF_FFFF,
"success keeps a nonzero error"
);
guest.teb = 0x10000;
assert_eq!(guest.last_error(), 87);
}
#[test]
fn a_retired_thread_starts_clean_when_its_teb_address_is_reused() {
let mut guest = Guest::new();
guest.teb = 0x10000;
guest.call("SetLastError", &[998]);
guest.teb = 0x20000;
guest.call("CloseHandle", &[0x1234]);
assert!(guest.state.retire_thread_last_error(0x10000));
assert!(!guest.state.retire_thread_last_error(0x10000));
assert!(
!guest.state.retire_thread_last_error(0x30000),
"a thread that never failed holds no value"
);
assert_eq!(guest.last_error(), 6, "the other thread is untouched");
guest.teb = 0x10000;
assert_eq!(guest.last_error(), 0);
guest.call("SetLastError", &[5]);
assert_eq!(guest.last_error(), 5);
}
#[test]
fn last_error_is_set_by_failures_and_by_the_guest() {
let mut guest = Guest::new();
+17 -2
View File
@@ -84,9 +84,18 @@ def cases():
f"mov {mem(bits)}, {reg(2, bits)}", f"mov {reg(14, bits)}, 0x5a",
f"mov {mem(bits)}, 0x5a", f"xchg {reg(3, bits)}, {reg(9, bits)}",
f"xchg {mem(bits)}, {reg(2, bits)}"]
for op in ("xadd", "cmpxchg"):
for bits in (8, 16, 32, 64):
# Destination RAX always matches the accumulator; a register with
# itself keeps the sum. LOCK is valid only with a memory destination.
out += [f"{op} {reg(3, bits)}, {reg(1, bits)}", f"{op} {reg(9, bits)}, {reg(12, bits)}",
f"{op} {reg(0, bits)}, {reg(2, bits)}", f"{op} {reg(3, bits)}, {reg(3, bits)}",
f"{op} {mem(bits)}, {reg(2, bits)}", f"lock {op} {mem(bits)}, {reg(2, bits)}",
f"lock {op} {mem(bits)}, {reg(0, bits)}"]
out += [f"{op} ah, bl", f"{op} cl, dh", f"{op} {mem(8)}, ch"]
out += ["mov ah, bl", "mov dl, ch", "mov bh, 0x21", "xchg ah, bl", "mov sil, dil",
"movabs r15, 0x8877665544332211", "mov rcx, -2", "bswap ebx", "bswap r9",
"cbw", "cwde", "cdqe", "cwd", "cdq", "cqo", "clc", "stc", "cmc", "nop",
"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",
f"push {mem(64)}", "pop rbx", "pop r12", f"pop {mem(64)}", "leave"]
return list(dict.fromkeys(out))
@@ -163,7 +172,13 @@ def assemble(lines):
subprocess.run(["clang", "-target", "x86_64-apple-macos", "-c", source, "-o", obj], check=True)
# One line per instruction: objdump never wraps its raw bytes.
listing = subprocess.run(["objdump", "-d", obj], check=True, capture_output=True, text=True).stdout
rows = [m.group(1).split() for m in re.finditer(r"^\s*[0-9a-f]+:\s((?:[0-9a-f]{2}\s)+)", listing, re.M)]
rows, prefix = [], []
for match in re.finditer(r"^\s*[0-9a-f]+:\s((?:[0-9a-f]{2}\s)+)(.*)$", listing, re.M):
row = prefix + match.group(1).split()
# objdump lists a leading LOCK prefix on a row of its own.
prefix = row if match.group(2).strip() == "lock" else []
if not prefix:
rows.append(row)
if len(rows) != len(lines):
sys.exit(f"{len(lines)} instructions assembled to {len(rows)} rows")
return "".join(f"{' '.join(row)} | {line}\n" for row, line in zip(rows, lines))
+63
View File
@@ -953,6 +953,68 @@ c7 44 be 10 5a 00 00 00 | mov dword ptr [rsi + 4*rdi + 16], 0x5a
48 c7 44 be 10 5a 00 00 00 | mov qword ptr [rsi + 4*rdi + 16], 0x5a
49 87 d9 | xchg rbx, r9
48 87 54 be 10 | xchg qword ptr [rsi + 4*rdi + 16], rdx
0f c0 cb | xadd bl, cl
45 0f c0 e1 | xadd r9b, r12b
0f c0 d0 | xadd al, dl
0f c0 db | xadd bl, bl
0f c0 54 be 10 | xadd byte ptr [rsi + 4*rdi + 16], dl
f0 0f c0 54 be 10 | lock xadd byte ptr [rsi + 4*rdi + 16], dl
f0 0f c0 44 be 10 | lock xadd byte ptr [rsi + 4*rdi + 16], al
66 0f c1 cb | xadd bx, cx
66 45 0f c1 e1 | xadd r9w, r12w
66 0f c1 d0 | xadd ax, dx
66 0f c1 db | xadd bx, bx
66 0f c1 54 be 10 | xadd word ptr [rsi + 4*rdi + 16], dx
66 f0 0f c1 54 be 10 | lock xadd word ptr [rsi + 4*rdi + 16], dx
66 f0 0f c1 44 be 10 | lock xadd word ptr [rsi + 4*rdi + 16], ax
0f c1 cb | xadd ebx, ecx
45 0f c1 e1 | xadd r9d, r12d
0f c1 d0 | xadd eax, edx
0f c1 db | xadd ebx, ebx
0f c1 54 be 10 | xadd dword ptr [rsi + 4*rdi + 16], edx
f0 0f c1 54 be 10 | lock xadd dword ptr [rsi + 4*rdi + 16], edx
f0 0f c1 44 be 10 | lock xadd dword ptr [rsi + 4*rdi + 16], eax
48 0f c1 cb | xadd rbx, rcx
4d 0f c1 e1 | xadd r9, r12
48 0f c1 d0 | xadd rax, rdx
48 0f c1 db | xadd rbx, rbx
48 0f c1 54 be 10 | xadd qword ptr [rsi + 4*rdi + 16], rdx
f0 48 0f c1 54 be 10 | lock xadd qword ptr [rsi + 4*rdi + 16], rdx
f0 48 0f c1 44 be 10 | lock xadd qword ptr [rsi + 4*rdi + 16], rax
0f c0 dc | xadd ah, bl
0f c0 f1 | xadd cl, dh
0f c0 6c be 10 | xadd byte ptr [rsi + 4*rdi + 16], ch
0f b0 cb | cmpxchg bl, cl
45 0f b0 e1 | cmpxchg r9b, r12b
0f b0 d0 | cmpxchg al, dl
0f b0 db | cmpxchg bl, bl
0f b0 54 be 10 | cmpxchg byte ptr [rsi + 4*rdi + 16], dl
f0 0f b0 54 be 10 | lock cmpxchg byte ptr [rsi + 4*rdi + 16], dl
f0 0f b0 44 be 10 | lock cmpxchg byte ptr [rsi + 4*rdi + 16], al
66 0f b1 cb | cmpxchg bx, cx
66 45 0f b1 e1 | cmpxchg r9w, r12w
66 0f b1 d0 | cmpxchg ax, dx
66 0f b1 db | cmpxchg bx, bx
66 0f b1 54 be 10 | cmpxchg word ptr [rsi + 4*rdi + 16], dx
66 f0 0f b1 54 be 10 | lock cmpxchg word ptr [rsi + 4*rdi + 16], dx
66 f0 0f b1 44 be 10 | lock cmpxchg word ptr [rsi + 4*rdi + 16], ax
0f b1 cb | cmpxchg ebx, ecx
45 0f b1 e1 | cmpxchg r9d, r12d
0f b1 d0 | cmpxchg eax, edx
0f b1 db | cmpxchg ebx, ebx
0f b1 54 be 10 | cmpxchg dword ptr [rsi + 4*rdi + 16], edx
f0 0f b1 54 be 10 | lock cmpxchg dword ptr [rsi + 4*rdi + 16], edx
f0 0f b1 44 be 10 | lock cmpxchg dword ptr [rsi + 4*rdi + 16], eax
48 0f b1 cb | cmpxchg rbx, rcx
4d 0f b1 e1 | cmpxchg r9, r12
48 0f b1 d0 | cmpxchg rax, rdx
48 0f b1 db | cmpxchg rbx, rbx
48 0f b1 54 be 10 | cmpxchg qword ptr [rsi + 4*rdi + 16], rdx
f0 48 0f b1 54 be 10 | lock cmpxchg qword ptr [rsi + 4*rdi + 16], rdx
f0 48 0f b1 44 be 10 | lock cmpxchg qword ptr [rsi + 4*rdi + 16], rax
0f b0 dc | cmpxchg ah, bl
0f b0 f1 | cmpxchg cl, dh
0f b0 6c be 10 | cmpxchg byte ptr [rsi + 4*rdi + 16], ch
88 dc | mov ah, bl
88 ea | mov dl, ch
b7 21 | mov bh, 0x21
@@ -972,6 +1034,7 @@ f8 | clc
f9 | stc
f5 | cmc
90 | nop
0f a2 | cpuid
0f 1f 40 08 | nop dword ptr [rax + 8]
f3 90 | pause
41 51 | push r9
+376
View File
@@ -0,0 +1,376 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! XADD, CMPXCHG and the LOCK prefix (issue #198).
//!
//! Expected values follow the operation sections of the Intel SDM Vol. 2 for
//! XADD, CMPXCHG and LOCK, stated here as literal results. Encodings were
//! assembled with `clang -target x86_64-apple-macos` and read with `objdump`.
//! Nothing was compared with x86 hardware.
//!
//! Both engines run one guest instruction at a time on one host thread, so
//! these tests establish the single-thread results that any later guest
//! scheduler has to preserve. They say nothing about concurrent execution.
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags};
use xenora_loader::dbt::{DbtEngine, is_native};
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
use xenora_loader::x86_decode::decode;
const ENTRY: u64 = 0x1000;
/// Two writable pages. Nothing is mapped after them unless a test says so.
const DATA: u64 = 0x4000;
const PAGE: u64 = 0x1000;
const END: u64 = DATA + 2 * PAGE;
const RAX: usize = 0;
const RCX: usize = 1;
const RDX: usize = 2;
const RBX: usize = 3;
const RSI: usize = 6;
fn image(code: &[u8]) -> GuestMemory {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
.unwrap();
memory
.map_region(DATA, 2 * PAGE as usize, MemoryPermissions::READ_WRITE)
.unwrap();
memory
}
fn data(memory: &GuestMemory) -> Vec<u8> {
let mut out = vec![0; 2 * PAGE as usize];
memory.read_bytes(DATA, &mut out).unwrap();
out
}
struct Run {
name: &'static str,
cpu: CpuState,
exit: ExitReason,
memory: GuestMemory,
/// Instructions the DBT ran on the shared semantics.
helpers: usize,
}
/// The interpreter and the DBT, each from its own copy of `cpu` and `memory`.
fn both(cpu: &CpuState, memory: &GuestMemory, budget: usize) -> [Run; 2] {
let mut interpreted = memory.clone();
let result = Interpreter::new(cpu.clone(), &mut interpreted, budget).run();
let mut translated = memory.clone();
let mut engine = DbtEngine::new(64 * 1024).unwrap();
let mut state = cpu.clone();
let native = engine.run(&mut state, &mut translated, budget);
[
Run {
name: "interpreter",
cpu: result.final_state,
exit: result.exit_reason,
memory: interpreted,
helpers: 0,
},
Run {
name: "DBT",
cpu: native.final_state,
exit: native.exit_reason,
memory: translated,
helpers: engine.metrics.interpreter_fallbacks,
},
]
}
fn flags(cf: bool, zf: bool, sf: bool, of: bool, pf: bool, af: bool) -> RFlags {
RFlags {
cf,
zf,
sf,
of,
pf,
af,
}
}
fn low(bits: u32) -> u64 {
u64::MAX >> (64 - bits)
}
#[test]
fn lock_is_accepted_only_on_xadd_and_cmpxchg_with_a_memory_destination() {
let accepted: &[&[u8]] = &[
&[0xF0, 0x0F, 0xC1, 0x0E], // lock xadd [rsi], ecx
&[0xF0, 0x0F, 0xB1, 0x0E], // lock cmpxchg [rsi], ecx
&[0x66, 0xF0, 0x0F, 0xC1, 0x0E], // lock xadd [rsi], cx, in LLVM's prefix order
&[0xF0, 0x66, 0x0F, 0xC1, 0x0E], // the same with LOCK first
&[0x65, 0xF0, 0x0F, 0xB0, 0x0E], // lock cmpxchg gs:[rsi], cl
&[0xF0, 0x48, 0x0F, 0xC1, 0x0E], // lock xadd [rsi], rcx
];
for code in accepted {
let lock = code.iter().position(|byte| *byte == 0xF0).unwrap();
let mut unlocked = code.to_vec();
unlocked.remove(lock);
let insn = decode(ENTRY, |at| {
code.get((at - ENTRY) as usize).copied().ok_or(())
})
.unwrap();
assert!(insn.lock && !is_native(&insn), "{code:02X?}");
assert_eq!(usize::from(insn.len), code.len(), "{code:02X?}");
// The accumulator matches the operand, so each exchange stores RCX.
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RAX] = 0x2122_2324_2526_2728;
cpu.gpr[RCX] = 0x1112_1314_1516_1718;
cpu.gpr[RSI] = DATA + 0x40;
let mut memory = image(code);
memory
.write_u64(DATA + 0x40, 0x2122_2324_2526_2728)
.unwrap();
let mut plain = image(&unlocked);
plain.write_u64(DATA + 0x40, 0x2122_2324_2526_2728).unwrap();
// LOCK changes no result here: only the instruction is a byte longer.
for (locked, wanted) in both(&cpu, &memory, 1).iter().zip(both(&cpu, &plain, 1)) {
assert_eq!(locked.exit, ExitReason::StepLimitExceeded, "{code:02X?}");
assert_eq!(locked.cpu.rip, ENTRY + code.len() as u64, "{code:02X?}");
let mut shifted = wanted.cpu.clone();
shifted.rip += 1;
assert_eq!(locked.cpu, shifted, "{code:02X?} on the {}", locked.name);
assert_eq!(data(&locked.memory), data(&wanted.memory), "{code:02X?}");
assert_ne!(data(&locked.memory), data(&memory), "{code:02X?}");
}
}
let rejected: &[&[u8]] = &[
&[0xF0, 0x0F, 0xC1, 0xC8], // lock xadd eax, ecx: register destination
&[0xF0, 0x0F, 0xB1, 0xCB], // lock cmpxchg ebx, ecx: register destination
&[0xF0, 0x01, 0x0E], // lock add [rsi], ecx: outside the locked subset
&[0xF0, 0x87, 0x0E], // lock xchg [rsi], ecx: outside the locked subset
&[0xF0, 0x0F, 0xC7, 0x0E], // lock cmpxchg8b [rsi]: not implemented
&[0xF0, 0x8B, 0x06], // lock mov eax, [rsi]: never lockable
&[0xF0, 0x90], // lock nop
];
for code in rejected {
let mut padded = code.to_vec();
padded.extend([0x90; 8]);
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RSI] = DATA;
let memory = image(&padded);
for run in both(&cpu, &memory, 1) {
assert!(
matches!(run.exit, ExitReason::IllegalInstruction(_)),
"{code:02X?} on the {}: {:?}",
run.name,
run.exit
);
assert_eq!(run.cpu, cpu, "{code:02X?}");
assert_eq!(data(&run.memory), data(&memory), "{code:02X?}");
}
}
}
#[test]
fn compare_and_exchange_takes_each_branch_at_every_width() {
// Destination [rsi] or RBX, source RCX, accumulator RAX.
let forms: &[(&[u8], u32, bool)] = &[
(&[0xF0, 0x0F, 0xB0, 0x0E], 8, true), // lock cmpxchg [rsi], cl
(&[0x66, 0xF0, 0x0F, 0xB1, 0x0E], 16, true), // lock cmpxchg [rsi], cx
(&[0xF0, 0x0F, 0xB1, 0x0E], 32, true), // lock cmpxchg [rsi], ecx
(&[0xF0, 0x48, 0x0F, 0xB1, 0x0E], 64, true), // lock cmpxchg [rsi], rcx
(&[0x0F, 0xB0, 0xCB], 8, false), // cmpxchg bl, cl
(&[0x66, 0x0F, 0xB1, 0xCB], 16, false), // cmpxchg bx, cx
(&[0x0F, 0xB1, 0xCB], 32, false), // cmpxchg ebx, ecx
(&[0x48, 0x0F, 0xB1, 0xCB], 64, false), // cmpxchg rbx, rcx
];
const ACCUMULATOR: u64 = 0x1111_2222_3333_4444;
const SOURCE: u64 = 0xAAAA_BBBB_CCCC_DDDD;
const ABOVE: u64 = 0x5555_6666_7777_8888;
for &(code, bits, in_memory) in forms {
let mask = low(bits);
for matches in [true, false] {
// The destination holds the accumulator's low bits, or differs in
// bit 0, under bits the operation must not read.
let old = (ABOVE & !mask) | ((ACCUMULATOR ^ u64::from(!matches)) & mask);
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RAX] = ACCUMULATOR;
cpu.gpr[RCX] = SOURCE;
cpu.gpr[RBX] = old;
cpu.gpr[RSI] = DATA + 0x80;
// accumulator - destination is 0, or -1 when the destination is
// one more. Start from the opposite flags so each must be written.
let after = if matches {
flags(false, true, false, false, true, false)
} else {
flags(true, false, true, false, true, true)
};
cpu.flags = flags(
!after.cf, !after.zf, !after.sf, !after.of, !after.pf, !after.af,
);
let mut memory = image(code);
memory.write_u64(DATA + 0x80, old).unwrap();
// A match stores the source. A mismatch stores the old value back
// and loads it into the accumulator. An 8- or 16-bit register write
// keeps the bits above it, a 32-bit one clears them, and a memory
// write touches only its own bytes.
let stored = if matches { SOURCE & mask } else { old & mask };
let merged = |before: u64, value: u64| match bits {
32 => value,
_ => (before & !mask) | value,
};
let mut wanted = cpu.clone();
wanted.rip = ENTRY + code.len() as u64;
wanted.flags = after;
if !matches {
wanted.gpr[RAX] = merged(ACCUMULATOR, old & mask);
}
let wanted_memory = if in_memory {
(old & !mask) | stored
} else {
wanted.gpr[RBX] = merged(old, stored);
old
};
for run in both(&cpu, &memory, 1) {
let what = format!("{code:02X?} matches={matches} on the {}", run.name);
assert_eq!(run.exit, ExitReason::StepLimitExceeded, "{what}");
assert_eq!(run.cpu, wanted, "{what}");
assert_eq!(
run.memory.read_u64(DATA + 0x80).unwrap(),
wanted_memory,
"{what}"
);
}
}
}
}
#[test]
fn locked_operands_may_be_unaligned_and_span_two_regions() {
// No alignment is required of a locked operand (SDM Vol. 2, "LOCK"). The
// last address straddles the data and a second writable region after it.
let spanning = |code: &[u8]| {
let mut memory = image(code);
memory
.map_region(END, PAGE as usize, MemoryPermissions::READ_WRITE)
.unwrap();
memory
};
for at in [DATA + 1, DATA + 0x33, DATA + PAGE - 3, END - 8, END - 3] {
// lock xadd [rsi], rcx
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RCX] = 0x0000_0001_0000_0003;
cpu.gpr[RSI] = at;
let mut memory = spanning(&[0xF0, 0x48, 0x0F, 0xC1, 0x0E]);
memory.write_u64(at, 0xFFFF_FFFF_FFFF_FFFE).unwrap();
for run in both(&cpu, &memory, 1) {
assert_eq!(run.exit, ExitReason::StepLimitExceeded, "{at:#x}");
assert_eq!(run.cpu.gpr[RCX], 0xFFFF_FFFF_FFFF_FFFE, "{at:#x}");
assert_eq!(
run.memory.read_u64(at).unwrap(),
0x0000_0001_0000_0001,
"{at:#x}"
);
// 0xFFFF_FFFF_FFFF_FFFE + 0x0000_0001_0000_0003 carries out of bit
// 63 and bit 3; the sum is positive, nonzero and ends in 0x01.
assert_eq!(
run.cpu.flags,
flags(true, false, false, false, false, true),
"{at:#x}"
);
}
// lock cmpxchg [rsi], rcx, with a matching accumulator
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RAX] = 0x8877_6655_4433_2211;
cpu.gpr[RCX] = 0x0102_0304_0506_0708;
cpu.gpr[RSI] = at;
let mut memory = spanning(&[0xF0, 0x48, 0x0F, 0xB1, 0x0E]);
memory.write_u64(at, 0x8877_6655_4433_2211).unwrap();
for run in both(&cpu, &memory, 1) {
assert_eq!(run.exit, ExitReason::StepLimitExceeded, "{at:#x}");
assert_eq!(run.cpu.gpr[RAX], 0x8877_6655_4433_2211, "{at:#x}");
assert_eq!(
run.memory.read_u64(at).unwrap(),
0x0102_0304_0506_0708,
"{at:#x}"
);
}
}
}
#[test]
fn a_fault_on_any_byte_of_the_operand_changes_nothing() {
let xadd: &[u8] = &[0xF0, 0x48, 0x0F, 0xC1, 0x0E]; // lock xadd [rsi], rcx
let cmpxchg: &[u8] = &[0xF0, 0x48, 0x0F, 0xB1, 0x0E]; // lock cmpxchg [rsi], rcx
// The last three bytes of writable memory, then five bytes that are
// unmapped or read-only.
let at = END - 3;
for code in [xadd, cmpxchg] {
for read_only_tail in [false, true] {
// Accumulators that match and that do not match the operand's
// writable bytes: a failed compare needs the write access too.
for accumulator in [0x0000_0000_00CC_BBAA_u64, 7] {
let mut memory = image(code);
memory.write_bytes(at, &[0xAA, 0xBB, 0xCC]).unwrap();
if read_only_tail {
memory
.map_region(END, PAGE as usize, MemoryPermissions::READ_ONLY)
.unwrap();
}
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RAX] = accumulator;
cpu.gpr[RCX] = 0x1122_3344_5566_7788;
cpu.gpr[RSI] = at;
cpu.flags = flags(true, false, true, false, true, false);
for run in both(&cpu, &memory, 1) {
let what = format!(
"{code:02X?} tail read-only={read_only_tail} rax={accumulator:#x} on the {}",
run.name
);
assert!(
matches!(run.exit, ExitReason::MemoryFault(_)),
"{what}: {:?}",
run.exit
);
assert_eq!(run.cpu, cpu, "{what}");
assert_eq!(data(&run.memory), data(&memory), "{what}");
}
}
}
}
}
#[test]
fn compare_and_swap_loop_retries_then_fetch_and_add_follows() {
// retry: lea rcx, [rax + 1]
// lock cmpxchg [rsi], rcx
// jne retry
// mov edx, 5
// lock xadd [rsi], rdx
// hlt
let code = [
0x48, 0x8D, 0x48, 0x01, 0xF0, 0x48, 0x0F, 0xB1, 0x0E, 0x75, 0xF5, 0xBA, 0x05, 0x00, 0x00,
0x00, 0xF0, 0x48, 0x0F, 0xC1, 0x16, 0xF4,
];
const COUNTER: u64 = DATA + 0x100;
let mut cpu = CpuState::new(ENTRY, 0);
// A stale expectation: the first exchange fails and reloads RAX, the
// second succeeds.
cpu.gpr[RAX] = 0xDEAD;
cpu.gpr[RSI] = COUNTER;
let mut memory = image(&code);
memory.write_u64(COUNTER, 41).unwrap();
for run in both(&cpu, &memory, 64) {
assert_eq!(run.exit, ExitReason::Halt, "{}", run.name);
assert_eq!(run.cpu.gpr[RAX], 41, "{}", run.name);
assert_eq!(run.cpu.gpr[RCX], 42, "{}", run.name);
// XADD returns the value before its addition.
assert_eq!(run.cpu.gpr[RDX], 42, "{}", run.name);
assert_eq!(run.memory.read_u64(COUNTER).unwrap(), 47, "{}", run.name);
assert_eq!(run.cpu.rip, ENTRY + code.len() as u64, "{}", run.name);
// Two exchanges and one addition, none lowered to ARM64 yet.
if run.name == "DBT" {
assert_eq!(run.helpers, 3);
}
}
}
+143
View File
@@ -305,6 +305,8 @@ enum Outcome {
}
fn reference(m: &mut Machine, text: &str) -> Outcome {
// LOCK changes no result on a machine that runs one instruction at a time.
let text = text.strip_prefix("lock ").unwrap_or(text);
let (name, rest) = text.split_once(' ').unwrap_or((text, ""));
let places: Vec<Place> = if rest.is_empty() || name == "lea" || name == "nop" {
Vec::new()
@@ -659,6 +661,28 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
write(m, places[1], a);
Outcome::Done(none)
}
"xadd" => {
// TEMP := SRC + DEST; SRC := DEST; DEST := TEMP.
let (a, b) = (read(m, places[0], bits), read(m, places[1], bits));
let sum = arithmetic(m, a, b, false, false, bits);
write(m, places[1], a);
write(m, places[0], sum);
Outcome::Done(none)
}
"cmpxchg" => {
// The accumulator is compared with DEST as CMP would. On a match
// DEST := SRC; otherwise accumulator := DEST and DEST := DEST.
let accumulator = read(m, rax(bits), bits);
let (destination, source) = (read(m, places[0], bits), read(m, places[1], bits));
arithmetic(m, accumulator, destination, true, false, bits);
if accumulator == destination {
write(m, places[0], source);
} else {
write(m, rax(bits), destination);
write(m, places[0], destination);
}
Outcome::Done(none)
}
"bswap" => {
let value = read(m, places[0], bits);
let bytes = bits / 8;
@@ -705,6 +729,24 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
Outcome::Done(none)
}
"nop" | "pause" => Outcome::Done(none),
"cpuid" => {
// Xenora's guest CPUID contract, restated: the vendor "Xenora guest"
// and the four features whose every instruction exists, CMOV and
// POPCNT in leaf 1, LZCNT and long mode in leaf 0x8000_0001.
let word = |text: &[u8; 4]| u32::from_le_bytes(*text);
let values = match m.gpr[RAX] as u32 {
0 => [1, word(b"Xeno"), word(b"uest"), word(b"ra g")],
1 => [0, 0, 1 << 23, 1 << 15],
0x8000_0000 => [0x8000_0001, 0, 0, 0],
0x8000_0001 => [0, 0, 1 << 5, 1 << 29],
_ => [0; 4],
};
// EAX, EBX, ECX and EDX, each zero-extended.
for (index, value) in [0, 3, 1, 2].into_iter().zip(values) {
m.gpr[index] = u64::from(value);
}
Outcome::Done(none)
}
"push" => {
m.pushed = read(m, places[0], 64) as u64;
m.gpr[4] -= 8;
@@ -1298,6 +1340,107 @@ fn division_accepts_exactly_the_representable_quotients() {
}
}
/// The bit scans and the bit test keep the destination and the flags where
/// the architecture puts them.
///
/// The expectations come from the Intel SDM Volume 2B, "BSF", "BSR" and "BT":
/// BSF writes the index of the lowest set bit of the source and BSR the index
/// of the highest set bit, and both set the zero flag when the source is
/// zero, in which case the destination is undefined and keeps its value. BT
/// sets the carry flag from the tested bit, leaves the other flags alone and
/// masks the bit index to the operand width.
///
/// The encodings are `bsf rbx, r9` (49 0F BC D9), `bsr rbx, r9` (49 0F BD
/// D9), `bt rbx, r9` (4C 0F A3 CB), `bsf ebx, r9d` (41 0F BC D9),
/// `bsr ebx, r9d` (41 0F BD D9), `bt ebx, r9d` (44 0F A3 CB), `bsf bx, r9w`
/// (66 41 0F BC D9) and `bt bx, r9w` (66 44 0F A3 CB), as produced by LLVM
/// 23.1.6 `llvm-mc -show-encoding`.
#[test]
fn bit_scans_and_bit_tests_follow_the_architecture() {
const BSF64: &[u8] = &[0x49, 0x0F, 0xBC, 0xD9]; // bsf rbx, r9
const BSR64: &[u8] = &[0x49, 0x0F, 0xBD, 0xD9]; // bsr rbx, r9
const BT64: &[u8] = &[0x4C, 0x0F, 0xA3, 0xCB]; // bt rbx, r9
const BSF32: &[u8] = &[0x41, 0x0F, 0xBC, 0xD9]; // bsf ebx, r9d
const BSR32: &[u8] = &[0x41, 0x0F, 0xBD, 0xD9]; // bsr ebx, r9d
const BT32: &[u8] = &[0x44, 0x0F, 0xA3, 0xCB]; // bt ebx, r9d
const BSF16: &[u8] = &[0x66, 0x41, 0x0F, 0xBC, 0xD9]; // bsf bx, r9w
const BT16: &[u8] = &[0x66, 0x44, 0x0F, 0xA3, 0xCB]; // bt bx, r9w
/// A machine with R9 and RBX set and every other register zero.
fn machine(source: u64, destination: u64) -> Machine {
let mut gpr = [0; 16];
gpr[3] = destination;
gpr[9] = source;
Machine {
gpr,
flags: Flags::default(),
operand: 0,
pushed: 0,
top: STACK_TOP,
}
}
// The lowest set bit of the source is the index BSF writes.
let (state, _, _) = run_both(&machine(0x0000_0000_0000_0028, 0xFFFF), BSF64, 1);
assert_eq!(state.gpr[3], 3);
assert!(!state.flags.zf);
// The highest set bit of the source is the index BSR writes.
let (state, _, _) = run_both(&machine(0x8000_0000_0000_0028, 0xFFFF), BSR64, 1);
assert_eq!(state.gpr[3], 63);
assert!(!state.flags.zf);
// A zero source sets the zero flag and leaves the destination alone.
let (state, _, _) = run_both(&machine(0, 0xFFFF_FFFF_FFFF_FFFF), BSF64, 1);
assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_FFFF);
assert!(state.flags.zf);
let (state, _, _) = run_both(&machine(0, 0xFFFF_FFFF_FFFF_FFFF), BSR64, 1);
assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_FFFF);
assert!(state.flags.zf);
// A 32-bit destination holds a 32-bit index and clears the half above it.
let (state, _, _) = run_both(&machine(0x0000_0028, 0xFFFF_FFFF_FFFF_FFFF), BSF32, 1);
assert_eq!(state.gpr[3], 3);
let (state, _, _) = run_both(&machine(0x8000_0000, 0xFFFF_FFFF_FFFF_FFFF), BSR32, 1);
assert_eq!(state.gpr[3], 31);
// A 16-bit destination keeps the bits above it.
let (state, _, _) = run_both(&machine(0x0100, 0xFFFF_FFFF_FFFF_FFFF), BSF16, 1);
assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_0008);
// BT reports the tested bit in the carry flag and leaves the bit string
// alone.
let (state, _, _) = run_both(&machine(1, 0b1010), BT64, 1);
assert!(state.flags.cf);
assert_eq!(state.gpr[3], 0b1010);
let (state, _, _) = run_both(&machine(0, 0b1010), BT64, 1);
assert!(!state.flags.cf);
assert_eq!(state.gpr[3], 0b1010);
// The bit index is masked to the operand width, so 64 selects bit 0 of a
// 64-bit bit string and 32 selects bit 0 of a 32-bit one.
let (state, _, _) = run_both(&machine(64, 0b1), BT64, 1);
assert!(state.flags.cf);
let (state, _, _) = run_both(&machine(32, 0b1), BT32, 1);
assert!(state.flags.cf);
let (state, _, _) = run_both(&machine(16, 0b1), BT16, 1);
assert!(state.flags.cf);
// The bit scans and the register form of the bit test are lowered to
// ARM64 instead of falling back to the shared semantics.
for code in [BSF64, BSR64, BT64, BSF32, BSR32, BT32, BSF16, BT16] {
let insn = decode(ENTRY, |address| {
code.get((address - ENTRY) as usize).copied().ok_or(())
})
.expect("decode");
assert!(is_native(&insn), "{code:02X?} is not native");
let mut engine = DbtEngine::new(64 * 1024).unwrap();
let (mut cpu, mut memory) = load(&machine(0x28, 0), code);
engine.run(&mut cpu, &mut memory, 1);
assert_eq!(engine.metrics.interpreter_fallbacks, 0, "{code:02X?}");
}
}
#[test]
fn pop_rsp_and_push_rsp_use_the_architectural_stack_pointer() {
let machine = Random(17).machine();
+45
View File
@@ -10,6 +10,9 @@
# decodable; a form counts as implemented only once its operation has semantics
# and independent tests. Forms not listed here are rejected.
#
# lock = true accepts the LOCK prefix (F0) when the ModRM operand is memory.
# Every other use of LOCK is rejected, as the architecture's #UD.
#
# prefix is a mandatory prefix: "66", "f3" or "f2". SSE forms use size x (XMM)
# and give the ModRM operand width in src: x = 16 bytes, q = 8, d = 4, w = 2.
# A 16-byte memory operand must be aligned unless unaligned = true.
@@ -48,6 +51,8 @@ movsx = { ref = "sdm MOVSX/MOVSXD" }
movsxd = { ref = "sdm MOVSX/MOVSXD" }
lea = { ref = "sdm LEA" }
xchg = { ref = "sdm XCHG" }
xadd = { writes = "cf zf sf of pf af", ref = "sdm XADD" }
cmpxchg = { writes = "cf zf sf of pf af", ref = "sdm CMPXCHG" }
bswap = { ref = "sdm BSWAP" }
cwde = { ref = "sdm CBW/CWDE/CDQE" }
cdq = { ref = "sdm CWD/CDQ/CQO" }
@@ -85,6 +90,7 @@ syscall = { terminator = true, ref = "sdm SYSCALL" }
clc = { writes = "cf", ref = "sdm CLC" }
stc = { writes = "cf", ref = "sdm STC" }
cmc = { reads = "cf", writes = "cf", ref = "sdm CMC" }
cpuid = { ref = "sdm CPUID" }
# SSE and SSE2 moves and packed integer operations. None reads or writes RFLAGS.
movaps = { ref = "sdm MOVAPS" }
@@ -562,6 +568,13 @@ opcode = 0x05
enc = "none"
size = "n"
[[form]]
op = "cpuid"
map = "0f"
opcode = 0xA2
enc = "none"
size = "n"
[[form]]
op = "movzx"
map = "0f"
@@ -674,6 +687,38 @@ enc = "rm_reg"
size = "v"
register_only = true
[[form]]
op = "cmpxchg"
map = "0f"
opcode = 0xB0
enc = "rm_reg"
size = "b"
lock = true
[[form]]
op = "cmpxchg"
map = "0f"
opcode = 0xB1
enc = "rm_reg"
size = "v"
lock = true
[[form]]
op = "xadd"
map = "0f"
opcode = 0xC0
enc = "rm_reg"
size = "b"
lock = true
[[form]]
op = "xadd"
map = "0f"
opcode = 0xC1
enc = "rm_reg"
size = "v"
lock = true
# Groups whose digits select an operation: [opcode, size, immediate, encoding].
[[group]]
map = "0f"
+90 -26
View File
@@ -9,8 +9,8 @@ pub use graphics::{PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
pub use xenora_decoder::Architecture;
use xenora_decoder::{
DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorAluOp, VectorAluVop3Op,
VectorBinary, VectorCompareOp, VectorSource,
DecodeError, DecodedInstruction, Instruction, ScalarSource, ScalarUnaryOp, VectorAluOp,
VectorAluVop3Op, VectorBinary, VectorCompareOp, VectorSource, VectorUnary,
};
/// SGPR index of `vcc_lo`.
@@ -92,6 +92,7 @@ enum Op {
Load,
Constant(u32),
Binary(Binary, Value, Value),
Unary(VectorUnary, Value),
MergeLanes {
mask: u32,
active: Value,
@@ -129,6 +130,7 @@ impl Op {
match self {
Self::Load | Self::Constant(_) | Self::ScalarBranch { .. } => Vec::new(),
Self::Binary(_, left, right) => vec![left, right],
Self::Unary(_, source) => vec![source],
Self::MergeLanes {
active, inactive, ..
} => vec![active, inactive],
@@ -149,6 +151,21 @@ impl Op {
match self {
Self::Load => format!("input[{index}]"),
Self::Constant(value) => format!("0x{value:08x}u"),
Self::Unary(op, source) => {
let src = name(source);
// AMD guide 12.8: all three scans return -1 if no bit matches.
match op {
VectorUnary::Not => format!("~{src}"),
VectorUnary::ReverseBits => format!("reverse_bits({src})"),
VectorUnary::FindHighUnsigned => {
format!("{src} == 0u ? 0xffffffffu : clz({src})")
}
VectorUnary::FindLow => format!("{src} == 0u ? 0xffffffffu : ctz({src})"),
VectorUnary::FindHighSigned => format!(
"({src} == 0u || {src} == 0xffffffffu) ? 0xffffffffu : clz({src} ^ (0u - ({src} >> 31u)))"
),
}
}
Self::Binary(operator, left, right) => {
let (left, right) = (name(left), name(right));
let (_, symbol) = operator.operator();
@@ -440,6 +457,19 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
format!("{dest} = const.u32 0x{value:08x}"),
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
),
Op::Unary(operator, source) => {
let mnemonic = match operator {
VectorUnary::Not => "not.b32",
VectorUnary::ReverseBits => "brev.b32",
VectorUnary::FindHighUnsigned => "ffbh.u32",
VectorUnary::FindLow => "ffbl.b32",
VectorUnary::FindHighSigned => "ffbh.i32",
};
(
format!("{dest} = {mnemonic} {source}"),
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
)
}
Op::Binary(operator, left, right) => (
format!("{dest} = {} {left}, {right}", operator.operator().0),
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
@@ -726,6 +756,25 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
.flatten()
.ok_or_else(|| error("scalar source has no known value")),
};
let read_vector = |source, operations: &mut Vec<_>, facts: &mut Vec<_>| {
Ok(match source {
VectorSource::Register(register) => read(register)?,
VectorSource::Scalar(register) if usize::from(register) == VCC_LO => {
match (lane_vcc, scalars[VCC_LO]) {
(Some(mask), _) => mask,
(None, Some(bits)) => constant(operations, facts, offset, bits),
(None, None) => {
return Err(error("vector ALU reads uninitialized VCC_LO"));
}
}
}
VectorSource::Scalar(register) => {
let bits = read_scalar(ScalarSource::Register(register))?;
constant(operations, facts, offset, bits)
}
VectorSource::Immediate(bits) => constant(operations, facts, offset, bits),
})
};
// Scalar instructions and waits still execute when all lanes are inactive.
if exec == 0 {
match instruction.instruction {
@@ -733,7 +782,9 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
| Instruction::VectorAluVop3 { .. }
| Instruction::VectorAddF32 { .. }
| Instruction::VectorMulF32 { .. }
| Instruction::VectorAlu { .. } => continue,
| Instruction::VectorAlu { .. }
| Instruction::VectorUnary { .. }
| Instruction::VectorSwap { .. } => continue,
_ => {}
}
}
@@ -848,8 +899,12 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
Op::Binary(Binary::Vector(op.lowering()), left, right),
)
}
Instruction::ScalarMoveB32 { dst, src } => {
let value = read_scalar(src)?;
Instruction::ScalarUnary {
op: op @ ScalarUnaryOp::MovB32,
dst,
src,
} => {
let (value, _) = op.evaluate(read_scalar(src)?);
if dst < 8 {
return Err(error("scalar move would modify a resource descriptor"));
}
@@ -1033,27 +1088,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
src0,
src1,
} => {
let src0 = match src0 {
VectorSource::Register(register) => read(register)?,
VectorSource::Scalar(register) if usize::from(register) == VCC_LO => {
match (lane_vcc, scalars[VCC_LO]) {
(Some(mask), _) => mask,
(None, Some(bits)) => {
constant(&mut operations, &mut facts, offset, bits)
}
(None, None) => {
return Err(error("vector ALU reads uninitialized VCC_LO"));
}
}
}
VectorSource::Scalar(register) => {
let bits = read_scalar(ScalarSource::Register(register))?;
constant(&mut operations, &mut facts, offset, bits)
}
VectorSource::Immediate(bits) => {
constant(&mut operations, &mut facts, offset, bits)
}
};
let src0 = read_vector(src0, &mut operations, &mut facts)?;
let src1 = read(src1)?;
let (left, right) = if op.swaps_sources() {
(src1, src0)
@@ -1065,6 +1100,35 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
Op::Binary(Binary::Vector(op.lowering()), left, right),
)
}
Instruction::VectorUnary { op, dst, src } => {
let source = read_vector(src, &mut operations, &mut facts)?;
(Some(dst), Op::Unary(op.lowering(), source))
}
Instruction::VectorSwap { dst, src, .. } => {
// Guide 12.8: capture both old values before updating either VGPR.
// read() also rejects v0 and registers with outstanding loads.
let old_dst = read(dst)?;
let old_src = read(src)?;
if dst != src {
registers[usize::from(dst)] = Some(merge_lanes(
&mut operations,
&mut facts,
offset,
exec,
old_src,
Some(old_dst),
)?);
registers[usize::from(src)] = Some(merge_lanes(
&mut operations,
&mut facts,
offset,
exec,
old_dst,
Some(old_src),
)?);
}
continue;
}
Instruction::VectorAddF32 { dst, src0, src1 } => (
Some(dst),
Op::Binary(Binary::FloatAdd, read(src0)?, read(src1)?),
+14
View File
@@ -391,3 +391,17 @@ fn vector_compares_lower_to_per_thread_wave_masks_and_selects() {
include_str!("../../../fixtures/golden/vector-compare.metal")
);
}
#[test]
fn vop1_integer_fixture_lowers_unary_and_masked_swap() {
let code = include_bytes!("../../../fixtures/rdna2/vector-unary.bin");
let compiled = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
compiled.ir,
include_str!("../../../fixtures/golden/vector-unary.ir")
);
assert_eq!(
compiled.msl,
include_str!("../../../fixtures/golden/vector-unary.metal")
);
}
+1
View File
@@ -25,6 +25,7 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
- [Semantic coverage](shaders/semantic-coverage.md) — Generated per-family counts of identified, declared, decoded, lowered and verified gfx1030 forms.
- [SOP2 scalar ALU](shaders/scalar-alu.md) — Supported scalar add, subtract and bitwise forms, their SCC rules and sources.
- [Semantic registry](shaders/semantic-registry.md) — How to add an instruction form: registry fields, validation, generation and the independence rule.
- [VOP1 vector unary and swap](shaders/vector-unary.md) — Wave32 integer bit operations, register exchange, and operand limits.
- [VOPC integer compares](shaders/vector-compare.md) — Wave32 compare forms, the VCC/EXEC contract, runtime `s_cbranch_vccz` and the Metal mapping.
- [Metal Shading Language generation](shaders/msl.md) and [independent CPU reference](shaders/reference-interpreter.md) — Translation rules and separate CPU execution models.
+4 -4
View File
@@ -1,17 +1,17 @@
<svg xmlns="http://www.w3.org/2000/svg" width="530" height="185" viewBox="0 0 530 185" role="img" aria-labelledby="title description">
<title id="title">Xenora · recorded progress</title>
<desc id="description">Decoded gfx1030 forms: 120 of 120. Accepted Metal forms · Apple M5: 18 of 120. Accepted guest milestones · X1–X4: 4 of 4</desc>
<desc id="description">Decoded gfx1030 forms: 126 of 126. Accepted Metal forms · Apple M5: 18 of 126. Accepted guest milestones · X1–X4: 4 of 4</desc>
<rect x="1" y="1" width="528" height="183" rx="10" fill="#18212a" stroke="#516171"/>
<g font-family="system-ui,sans-serif" fill="#eaf0f5">
<text x="20" y="29" font-size="13" font-weight="700">RECORDED FIXTURE PROGRESS</text>
<text x="20" y="58" font-size="13">Decoded gfx1030 forms</text>
<text x="510" y="58" font-size="13" text-anchor="end">120 / 120</text>
<text x="510" y="58" font-size="13" text-anchor="end">126 / 126</text>
<rect x="20" y="65" width="490" height="4" rx="2" fill="#3c4a58"/>
<rect x="20" y="65" width="490.00" height="4" rx="2" fill="#88c6bd"/>
<text x="20" y="96" font-size="13">Accepted Metal forms · Apple M5</text>
<text x="510" y="96" font-size="13" text-anchor="end">18 / 120</text>
<text x="510" y="96" font-size="13" text-anchor="end">18 / 126</text>
<rect x="20" y="103" width="490" height="4" rx="2" fill="#3c4a58"/>
<rect x="20" y="103" width="73.50" height="4" rx="2" fill="#88c6bd"/>
<rect x="20" y="103" width="70.00" height="4" rx="2" fill="#88c6bd"/>
<text x="20" y="134" font-size="13">Accepted guest milestones · X1–X4</text>
<text x="510" y="134" font-size="13" text-anchor="end">4 / 4</text>
<rect x="20" y="141" width="490" height="4" rx="2" fill="#3c4a58"/>

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

+37 -1
View File
@@ -45,6 +45,42 @@ XMM registers live in `CpuState::xmm`, lane 0 in the low bits, and MXCSR in `Cpu
None of it has been compared with x86 hardware.
## Locked instructions
XADD and CMPXCHG exist for 8-, 16-, 32- and 64-bit register and memory destinations. The LOCK prefix (F0) is accepted on exactly the forms the registry marks `lock = true`, and only when the destination is memory. Today those are the memory forms of XADD and CMPXCHG. LOCK anywhere else is an illegal instruction, as the Intel SDM (Vol. 2, "LOCK") specifies for a register destination or an instruction that cannot be locked. LOCK on the other instructions the SDM allows (ADD, ADC, AND, BTC, BTR, BTS, DEC, INC, NEG, NOT, OR, SBB, SUB, XOR and XCHG), CMPXCHG8B and CMPXCHG16B are not implemented and stay rejected.
These rules hold for both engines and are what a guest scheduler has to preserve:
- **Ordering.** Each engine runs one guest instruction at a time on one host thread, and an instruction either completes or changes nothing. A locked instruction is therefore indivisible and totally ordered with every other guest access, and LOCK changes no result: the locked and unlocked encodings leave identical state. A scheduler that switches guest threads only between instructions keeps this. One that runs guest threads on several host threads does not, and must first make each locked instruction atomic against every access to its operand, with x86's ordering rather than ARM64's weaker one. Nothing here provides or tests that.
- **Alignment.** A locked operand may have any alignment and may span two mapped regions.
- **Compare failure.** CMPXCHG compares the accumulator with the destination as CMP would and sets all six status flags from it. On a match it stores the source and leaves the accumulator alone. On a mismatch it loads the destination into the accumulator and stores the destination's old value back, so the destination is written either way and a mismatch on memory that cannot be written still faults. With a 32-bit register destination both stores clear the upper half of that register, following the SDM's operation text.
- **Faults.** If any byte of the operand cannot be read or written, the instruction faults before memory, registers or flags change.
- **Lowering.** The DBT runs these forms on the shared semantics. They are not lowered to ARM64 atomic instructions, which could only be judged against concurrent guest threads.
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.
## Guest CPUID
CPUID (`0F A2`) returns a fixed table that never reads the host. It describes a synthetic processor: the vendor string is `Xenora guest`, not Intel's or AMD's, and leaf 1 reports no family, model or stepping.
| Leaf (EAX) | EAX | EBX | ECX | EDX |
| --- | --- | --- | --- | --- |
| 0 | 1, the highest basic leaf | `Xeno` | `uest` | `ra g` |
| 1 | 0 | 0 | POPCNT (bit 23) | CMOV (bit 15) |
| 0x8000_0000 | 0x8000_0001, the highest extended leaf | 0 | 0 | 0 |
| 0x8000_0001 | 0 | 0 | LZCNT (bit 5) | long mode (bit 29) |
| any other | 0 | 0 | 0 | 0 |
A feature bit is set only when every instruction of that feature is implemented. That is stricter than "some of it works", and it has consequences:
- SSE and SSE2 are not reported, although most of their instructions exist, because parts are still rejected: RSQRTPS and 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.
- 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.
`xenora_loader::cpu::cpuid` is the one copy of the table. A runtime service that reports processor features should read it rather than keep its own list.
`tests/cpu_features.rs` pins every leaf in both engines. For each reported feature it requires the feature's whole instruction set among the fixtures that `tests/x86_integer.rs` executes. For each feature software commonly tests that is not reported, it holds one instruction of that feature that both engines must refuse. To report a new feature: implement all of its instructions, remove its witness, add its instruction list to the reported set, then set the bit. The pairing of instructions with feature bits follows the Intel SDM; nothing was compared with a processor.
## Rejected on purpose
LOCK, 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, RCL, RCR, SHLD, SHRD, string instructions, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, atomics 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, RCL, RCR, SHLD, SHRD, string instructions, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B, CMPXCHG16B and fences. The DBT also refuses raw SYSCALL.
+31 -10
View File
@@ -69,16 +69,37 @@ storage, invokes its callbacks and runs the entry point. The fixture entry point
uses a Win64-aligned stack and terminates with HLT. The result includes the loaded
guest memory and the entry execution outcome.
`xenora probe --mode static` inventories ordinary PE imports without guest
execution. `missing_imports.csv` lists unresolved keys with their import address
table relative virtual addresses. The full inventory records whether each key is registered, its implementation
status, and the canonical module behind API-set aliases. Runtime-loaded modules
and services require separate analysis. The coverage matrix groups unresolved
imports by shared startup prerequisites. Static imports do not reveal call
order. The JSON report counts import slots, DLL and symbol keys, distinct
names with DLL-scoped ordinals, and canonical registered handlers separately.
The unresolved total includes explicitly tracked unsupported APIs and other
missing handlers. Existing stubs remain visible in the full inventory.
`xenora probe --mode static` inventories ordinary and delay-loaded PE imports
without guest execution. `missing_imports.csv` lists unresolved ordinary keys
with their import address table relative virtual addresses. The full inventory,
`imports.csv`, marks each entry `ordinary` or `delayed` in its `import_table`
column and records whether each key is registered, its implementation
status, and the canonical module behind API-set aliases. Modules and services
loaded by other means at run time require separate analysis. The coverage matrix
groups unresolved ordinary imports by shared startup prerequisites. Static
imports do not reveal call order. The JSON report counts import slots, DLL and
symbol keys, distinct names with DLL-scoped ordinals, and canonical registered
handlers separately. The unresolved total includes explicitly tracked
unsupported APIs and other missing handlers. Existing stubs remain visible in
the full inventory.
Delay-loaded imports come from the PE32+ delay-load directory, data directory
13 in Microsoft's PE format. The probe reports each one with its DLL, symbol or
ordinal, and slot in the delay import address table, after the ordinary rows.
Binding does not resolve them: the PE format leaves that to a delay-load helper
inside the image. The totals above and `missing_imports.csv` therefore cover
ordinary imports only, and the JSON report counts delayed slots and DLLs in
`delayed_imports` and `delayed_imported_dlls_count`. `xenora imports sync`
leaves delayed rows out of its backlog for the same reason.
The probe reads only descriptors that lie wholly inside the directory's
declared size, and expects that size to hold the empty descriptor that ends the
table. It reads descriptors whose `RvaBased` attribute is set, and requires each
one's DLL name, import address table and import name table to be present and to
start in section data. A table that breaks one of these rules, sets a reserved
attribute bit, is truncated, or uses the earlier virtual-address descriptor form
is reported in `delay_import_error` and in the Markdown report, together with
the entries read before it.
The synthetic process registry supports the current-process pseudo handle and
its process ID. The priority boost setter and getter record and query a guest
+6
View File
@@ -121,6 +121,12 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
| `v_ashrrev_i32_e32` | Two VGPR sources and one VGPR destination | `31FFFF01` | yes | yes | three-way passed | MSL signed right shift with a five-bit count | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cbranch_execz` | Nonnegative signed dword displacement | `BF880001` | yes | yes | three-way passed | resolved Wave32 EXEC_LO zero check | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cbranch_vccz` | Nonnegative signed dword displacement | `BF860001` | yes | yes | three-way passed | resolved Wave32 VCC_LO zero check, or a wave-uniform join select after a vector compare | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_not_b32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; bitwise complement | `7E046F01` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_bfrev_b32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; reverse bit order | `7E067101` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_ffbh_u32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count leading zeros, or -1 for zero | `7E087302` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_ffbl_b32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count trailing zeros, or -1 for zero | `7E0A7501` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_ffbh_i32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count leading sign bits, or -1 if all bits match | `7E0C7702` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_swap_b32` | VOP1, Wave32; VGPR VDST and SRC0; exchange the old values of VDST and SRC0 | `7E02CB02` | yes | yes | three-way passed | per-thread exchange of both register values with lane merges under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_mul_i32_i24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of sext(S0[23:0]) * sext(S1[23:0]) | `120402C3` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_mul_hi_i32_i24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = bits 63:32 of sext(S0[23:0]) * sext(S1[23:0]) | `14060208` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_mul_u32_u24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of S0[23:0] * S1[23:0] | `160802FF 00123456` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
+3 -2
View File
@@ -189,8 +189,9 @@ Eleven 32-bit SOP1 forms are declared in the registry (operand rule
(0xffffffff); `s_flbit_i32` returns -1 for both 0 and -1; sign extension reads
S0[7:0] or S0[15:0]; `s_abs_i32` of 0x80000000 is 0x80000000. Only NOT, BCNT0,
BCNT1 and ABS write SCC, as D != 0; the other seven leave it unchanged.
`s_mov_b32` stays hand-written, because it also accepts EXEC and VCC halves as
destinations. As for SOP2, destinations s0-s7 are refused when a fixture runs
`s_mov_b32` is the twelfth registry SOP1 form, under its own operand rule
`sop1_move`, because it also accepts EXEC and VCC halves as destinations (the
domain the hand-written decoder accepted before #215 moved it). As for SOP2, destinations s0-s7 are refused when a fixture runs
(they hold its buffer descriptors), and float inline constants are rejected.
`tests/validation/tests/sop1_unary.rs` checks 4,126 cases, with expected values
+6 -3
View File
@@ -24,19 +24,19 @@ acceptance remain outside the verified count. All results concern synthetic fixt
| MUBUF | 75 | 2 | 0 | 2 | 2 | 2 | 2 | 2 | 0 |
| SCRATCH | 22 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| SMEM | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| SOP1 | 65 | 12 | 11 | 12 | 12 | 12 | 1 | 1 | 11 |
| SOP1 | 65 | 12 | 12 | 12 | 12 | 12 | 1 | 1 | 11 |
| SOP2 | 51 | 33 | 33 | 33 | 33 | 33 | 0 | 0 | 12 |
| SOPC | 18 | 12 | 12 | 12 | 12 | 12 | 1 | 1 | 7 |
| SOPK | 27 | 17 | 16 | 17 | 17 | 17 | 1 | 1 | 5 |
| SOPP | 36 | 6 | 0 | 6 | 6 | 6 | 4 | 4 | 0 |
| VINTRP | 3 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 |
| VOP1 | 81 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
| VOP1 | 81 | 7 | 6 | 7 | 7 | 7 | 1 | 1 | 11 |
| VOP2 | 47 | 20 | 18 | 20 | 20 | 20 | 7 | 7 | 11 |
| VOP3 | 416 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 12 |
| VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| VOPC | 190 | 16 | 16 | 16 | 16 | 16 | 0 | 0 | 7 |
| **Total** | 1465 | 120 | 107 | 124 | 120 | 120 | 18 | 18 | 65 |
| **Total** | 1465 | 126 | 114 | 130 | 126 | 126 | 18 | 18 | 76 |
## Unsupported operand variants
@@ -44,11 +44,14 @@ The table counts distinct variant names per family across registry operand rules
| Family | Operand rule | Unsupported variants |
| --- | --- | --- |
| SOP1 | `sop1_move` | `dst_m0`, `dst_null`, `dst_ttmp`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc` |
| SOP1 | `sop1_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc` |
| SOP2 | `sop2_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` |
| SOPC | `sopc_scalar` | `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` |
| SOPK | `sopk_compare` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc` |
| SOPK | `sopk_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc` |
| VOP1 | `vop1_swap` | `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
| VOP1 | `vop1_vgpr` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
| VOP2 | `vop2_vgpr` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
| VOP2 | `vop2_vgpr2` | `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
| VOP3 | `vop3_vgpr2` | `modifiers`, `src2`, `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
+11 -3
View File
@@ -109,7 +109,7 @@ error.
| `family` | Encoding family; must match the XML base encoding | e.g. `SOP2` |
| `opcode` | Opcode; must match the XML | non-negative integer |
| `variant` | Rust enum variant of the typed operation | CamelCase, e.g. `AddU32` |
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor`, `lshl`, `lshr`, `ashr`, `min`, `max`, `cselect`, `bfm`, `mul`, `mul_hi`, `bfe`, `absdiff`, `lshl_add`, `mul24`, `mul_hi24` (vector only), `mov` and `cmov` (SOPK only), `compare` and the SOP1 unaries |
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor`, `lshl`, `lshr`, `ashr`, `min`, `max`, `cselect`, `bfm`, `mul`, `mul_hi`, `bfe`, `absdiff`, `lshl_add`, `mul24`, `mul_hi24` (vector only), `mov` (SOP1 and SOPK), `cmov` (SOPK only), `compare` and the SOP1 unaries |
| `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (always `bitwise` for the logical operations, `cselect` and `bfm`; never for the arithmetic ones, `add`, `sub`, `min`, `max`, `mul`, `mul_hi`, `bfe`, `absdiff` and `lshl_add`; shifts take their primitive's signedness) |
| `carry_in` | Whether the form reads SCC: carry-in, borrow-in or the select condition | `none`, `scc` (`scc` only for unsigned `add` and `sub`, and required for `cselect`) |
| `width` | Operand and result width in bits | `32` |
@@ -119,8 +119,8 @@ error.
| `shift_amount` | `lshl_add` only: the fixed left shift of S0 before the add | `1` to `4`; required for `lshl_add`, rejected elsewhere |
| `shift_count_bits` | Shifts only: the low bits of the count source used as the count: S1, or S0 for a vector form with `source_order = "reversed"`. Scalar forms mask it in the generated evaluation, vector forms in their MSL template; the XML must list the count source as unsigned | `5` (log2 of `width`); required for shifts, rejected elsewhere |
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `relation` (SOPC and SOPK compares only), `selected_src0` (min and max: S0 won the strict compare, so a tie gives 0), `unchanged` |
| `vcc`, `exec` | Effect on VCC and EXEC, stated rather than implied | `unchanged`; `vcc` is `lane_mask` exactly for the VOPC compares (VCC_LO bit n = EXEC[n] & test, fully written; VCC_HI unknown afterwards, see [vector-compare.md](vector-compare.md)); `exec` must be `unchanged` (no EXEC-writing contract yet) |
| `wave` | Wave sizes the form is valid in | `wave32` exactly for the VOPC compares (their one entry point is the Wave32 compute fixture ABI, vector-compare.md section 2), `any` for everything else; the decoder has no wave-size input, so no other form may claim `wave32` |
| `vcc`, `exec` | Implicit effect on VCC and EXEC | `unchanged`; `vcc` is `lane_mask` exactly for the VOPC compares (VCC_LO bit n = EXEC[n] & test, fully written; VCC_HI unknown afterwards, see [vector-compare.md](vector-compare.md)); `exec` must be `unchanged` (explicit destinations are covered by the operand rule) |
| `wave` | Wave sizes the form is valid in | `wave32` for VOPC compares and VOP1 integer forms in the Wave32 compute fixture ABI, `any` for other registry forms |
| `operands` | Name of an `[operand_rules]` entry for the same family | e.g. `sop2_sgpr` |
| `spec` | References `{ document, section, page }` | at least one `guide` reference with a page above 0 |
| `verify` | Evidence the form needs before it counts as verified | `reference`, `independent`, `metal`, `llvm_encoding` |
@@ -154,6 +154,14 @@ fixes the `scc` value:
| `cmov` / `signed` (SOPK only) | `unchanged` | `sext_simm16` | required |
| `compare` / `signed` or `unsigned` | `relation` | `eq_b32`, `ne_b32` (for both signednesses), `gt_i32`/`gt_u32`, `ge_*`, `lt_*`, `le_*` | no |
SOP1 unary forms share `ScalarUnaryOp`. The `sop1_sgpr` rule accepts
destination encodings 0–105. The `sop1_move` rule for `s_mov_b32` also accepts
106–107 (VCC halves) and 126–127 (EXEC halves) as explicit destinations.
Both rules accept source registers s0–s105, inline integers −16 through 64,
and one literal dword. The move copies the source and leaves SCC unchanged.
The destination vocabulary preserves the original decoder subset of the
RDNA 2 guide sections 5.3 and 12.3.
Vector forms (operand rules `vop2_vgpr` and `vop2_vgpr2`, kind `vector`; both
generate the one `VectorAluOp` enum, whose `operand_rule()` tells the decoder
which rule a form uses) use a separate table:
+38
View File
@@ -0,0 +1,38 @@
# Wave32 vector unary integer operations and swap
Xenora translates six gfx1030 VOP1 integer forms for the synthetic Wave32 compute
ABI. The AMD RDNA 2 ISA Reference Guide defines the operations in section 12.8,
the encoding in section 13.3.2, and the execution mask (EXEC) in section 3.3.
| Form | Result in each active lane |
| --- | --- |
| `v_not_b32_e32` | Complement all 32 bits. |
| `v_bfrev_b32_e32` | Reverse the order of the 32 bits. |
| `v_ffbh_u32_e32` | Count leading zeros. Return all ones if the source is zero. |
| `v_ffbl_b32_e32` | Count trailing zeros. Return all ones if the source is zero. |
| `v_ffbh_i32_e32` | Count leading bits equal to the sign bit. Return all ones if all bits match. |
| `v_swap_b32` | Exchange the old values of two vector general-purpose registers (VGPRs). A register swapped with itself keeps its value. |
The unary forms accept a VGPR, scalar register `s0`–`s105`, `vcc_lo` (the low
half of the vector condition code), inline integer `-16`–`64`, or a literal
word as SRC0. Swap requires a VGPR as SRC0 because it writes both operands.
Both operands of swap must be initialized when EXEC is nonzero. The compute
ABI reserves `v0` for indexing and requires waiting for buffer loads before
using or overwriting their destination. Inactive lanes retain their old
values. The six forms leave EXEC, VCC and the scalar condition code (SCC)
unchanged.
The compiler emits per-thread Metal Shading Language for unary operations.
For swap it captures both old values in the intermediate representation before
updating either register binding. Under partial EXEC, each register receives
its own lane merge.
The [guide-derived oracle](../../tests/validation/tests/vop1_integer.rs) checks
the 752 accepted cases' outputs against its expected values on each CPU
interpreter and, through the translator, on native Metal (Apple M5, API and
shader validation on: 752 cases in 613 programs). A CPU test checks that the
compiler accepts every case and refuses each of the 610 rejected programs at
the same instruction offset as the interpreters. The
[LLVM-assembled fixture](../../fixtures/rdna2/vector-unary.s) exercises all
six forms with a partial EXEC swap. Independent acceptance of the
translator is pending. Xbox hardware agreement is unknown.
+72
View File
@@ -1334,6 +1334,78 @@ recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_not_b32_e32"
encoding = "VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; bitwise complement"
representation = "`7E046F01`"
lowering = "per-thread unary integer operation with a lane merge under partial EXEC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_bfrev_b32_e32"
encoding = "VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; reverse bit order"
representation = "`7E067101`"
lowering = "per-thread unary integer operation with a lane merge under partial EXEC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_ffbh_u32_e32"
encoding = "VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count leading zeros, or -1 for zero"
representation = "`7E087302`"
lowering = "per-thread unary integer operation with a lane merge under partial EXEC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_ffbl_b32_e32"
encoding = "VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count trailing zeros, or -1 for zero"
representation = "`7E0A7501`"
lowering = "per-thread unary integer operation with a lane merge under partial EXEC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_ffbh_i32_e32"
encoding = "VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count leading sign bits, or -1 if all bits match"
representation = "`7E0C7702`"
lowering = "per-thread unary integer operation with a lane merge under partial EXEC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_swap_b32"
encoding = "VOP1, Wave32; VGPR VDST and SRC0; exchange the old values of VDST and SRC0"
representation = "`7E02CB02`"
lowering = "per-thread exchange of both register values with lane merges under partial EXEC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_mul_i32_i24_e32"
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of sext(S0[23:0]) * sext(S1[23:0])"
+12
View File
@@ -0,0 +1,12 @@
0000: t0 = load.u32 input[index]
000c: t1 = not.b32 t0
0018: t2 = merge.lanes mask=0xaaaaaaaa, t1, t0
0018: t3 = merge.lanes mask=0xaaaaaaaa, t0, t1
0020: t4 = brev.b32 t2
0024: t5 = ffbh.u32 t3
0028: t6 = ffbl.b32 t2
002c: t7 = ffbh.i32 t3
0030: t8 = xor.b32 t4, t5
0034: t9 = xor.b32 t6, t8
0038: t10 = xor.b32 t7, t9
003c: store.u32 output[index], t10
+19
View File
@@ -0,0 +1,19 @@
#include <metal_stdlib>
using namespace metal;
kernel void xenora_compute(
device const uint* input [[buffer(0)]],
device uint* output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
uint t0 = input[index];
uint t1 = ~t0;
uint t2 = ((0xaaaaaaaau >> (index & 31u)) & 1u) != 0u ? t1 : t0;
uint t3 = ((0xaaaaaaaau >> (index & 31u)) & 1u) != 0u ? t0 : t1;
uint t4 = reverse_bits(t2);
uint t5 = t3 == 0u ? 0xffffffffu : clz(t3);
uint t6 = t2 == 0u ? 0xffffffffu : ctz(t2);
uint t7 = (t3 == 0u || t3 == 0xffffffffu) ? 0xffffffffu : clz(t3 ^ (0u - (t3 >> 31u)));
uint t8 = t4 ^ t5;
uint t9 = t6 ^ t8;
uint t10 = t7 ^ t9;
output[index] = t10;
}
Binary file not shown.
+125
View File
@@ -0,0 +1,125 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Generate the original PE32+ delay-load import fixture without an x86 toolchain.
The image has one ordinary import DLL and two delay-loaded DLLs, each with a
named import and one of them with an import by ordinal. It follows Microsoft's
PE format specification ("The .idata Section" and "Delay-Load Import Tables
(Image Only)"). It is for static inspection: the entry point returns at once and
nothing calls an import.
"""
import argparse
from pathlib import Path
from struct import pack_into
BASE = 0x140000000
TEXT, RDATA, DATA = 0x1000, 0x2000, 0x3000
# File offset of each section's data, after the 0x400-byte headers.
RAW = {TEXT: 0x400, RDATA: 0x600, DATA: 0xA00}
ORDINAL = 1 << 63
# Ordinary imports, in .rdata.
IMPORT_DIRECTORY = RDATA
LOOKUP, IAT = RDATA + 0x30, RDATA + 0x50
ORDINARY_DLL, ORDINARY_NAME = RDATA + 0x70, RDATA + 0x90
# Delay-load names and name tables, in .rdata before their directory so that a
# file cut inside the directory still holds everything the first entry names.
NAMES_A, NAMES_B = RDATA + 0x100, RDATA + 0x118
DELAY_DLL_A, DELAY_DLL_B = RDATA + 0x130, RDATA + 0x150
DELAY_NAME_A, DELAY_NAME_B = RDATA + 0x170, RDATA + 0x190
DELAY_DIRECTORY = RDATA + 0x200
# Delay-load address tables and module handles, in writable .data.
DELAY_IAT_A, DELAY_IAT_B = DATA, DATA + 0x20
HANDLE_A, HANDLE_B = DATA + 0x40, DATA + 0x48
# Each delay-load address slot starts out pointing at its own stub.
STUBS = (TEXT + 0x10, TEXT + 0x18, TEXT + 0x20)
def fixture():
data = bytearray(0xC00)
def offset(rva):
section = rva & ~0xFFF
return RAW[section] + rva - section
def put(rva, layout, *values):
pack_into(layout, data, offset(rva), *values)
def text(rva, value):
data[offset(rva):offset(rva) + len(value) + 1] = value + b"\0"
data[:2] = b"MZ"
pack_into("<I", data, 0x3C, 0x80)
data[0x80:0x84] = b"PE\0\0"
# AMD64, three sections, 240-byte optional header; relocations stripped,
# executable, large-address-aware.
pack_into("<HHIIIHH", data, 0x84, 0x8664, 3, 0, 0, 0, 240, 0x23)
opt = 0x98
pack_into("<H", data, opt, 0x20B)
pack_into("<III", data, opt + 4, 0x200, 0x600, 0)
pack_into("<IIQII", data, opt + 16, TEXT, TEXT, BASE, 0x1000, 0x200)
pack_into("<HHHHHH", data, opt + 40, 6, 0, 0, 0, 6, 0)
pack_into("<II", data, opt + 56, 0x4000, 0x400)
# Console subsystem; NX compatible at a fixed base.
pack_into("<HH", data, opt + 68, 3, 0x100)
pack_into("<QQQQII", data, opt + 72, 0x10000, 0x1000, 0x10000, 0x1000, 0, 16)
# Import table, import address table and delay import descriptor.
for index, rva, size in (
(1, IMPORT_DIRECTORY, 40),
(12, IAT, 24),
(13, DELAY_DIRECTORY, 96),
):
pack_into("<II", data, opt + 112 + index * 8, rva, size)
sections = (
(b".text", TEXT, 0x200, 0x60000020),
(b".rdata", RDATA, 0x400, 0x40000040),
(b".data", DATA, 0x200, 0xC0000040),
)
for index, (name, rva, size, characteristics) in enumerate(sections):
pack_into(
"<8sIIIIIIHHI", data, opt + 240 + 40 * index, name, size, rva,
size, offset(rva), 0, 0, 0, 0, characteristics,
)
# Entry returns. The stubs are INT3 because the fixture is never run.
data[offset(TEXT)] = 0xC3
for stub in STUBS:
data[offset(stub)] = 0xCC
# One ordinary DLL: a named import and ordinal 3.
put(IMPORT_DIRECTORY, "<IIIII", LOOKUP, 0, 0, ORDINARY_DLL, IAT)
for table in (LOOKUP, IAT):
put(table, "<QQQ", ORDINARY_NAME, ORDINAL | 3, 0)
text(ORDINARY_DLL, b"fixture-ordinary.dll")
text(ORDINARY_NAME + 2, b"OrdinaryByName")
# Two delay-loaded DLLs. Attributes bit 0 marks the fields as RVAs.
put(DELAY_DIRECTORY, "<IIIIIIII",
1, DELAY_DLL_A, HANDLE_A, DELAY_IAT_A, NAMES_A, 0, 0, 0)
put(DELAY_DIRECTORY + 32, "<IIIIIIII",
1, DELAY_DLL_B, HANDLE_B, DELAY_IAT_B, NAMES_B, 0, 0, 0)
put(NAMES_A, "<QQQ", DELAY_NAME_A, ORDINAL | 7, 0)
put(NAMES_B, "<QQ", DELAY_NAME_B, 0)
text(DELAY_DLL_A, b"fixture-delay-a.dll")
text(DELAY_DLL_B, b"fixture-delay-b.dll")
text(DELAY_NAME_A + 2, b"DelayedAlpha")
text(DELAY_NAME_B + 2, b"DelayedBeta")
put(DELAY_IAT_A, "<QQQ", BASE + STUBS[0], BASE + STUBS[1], 0)
put(DELAY_IAT_B, "<QQ", BASE + STUBS[2], 0)
return data
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
path = Path(__file__).with_suffix(".exe")
if args.check:
if path.read_bytes() != fixture():
parser.exit(1, f"fixture bytes differ from generator: {path}\n")
else:
path.write_bytes(fixture())
Binary file not shown.
+21
View File
@@ -0,0 +1,21 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Wave32 VOP1 integer forms (AMD RDNA 2 ISA guide 12.8).
// Exchange the input and its complement in odd lanes, then use both values
// and all three bit scans to form the output.
.text
buffer_load_dword v1, v0, s[0:3], 0 idxen
s_waitcnt vmcnt(0)
v_not_b32_e32 v2, v1
s_mov_b32 exec_lo, 0xaaaaaaaa
v_swap_b32 v1, v2
s_mov_b32 exec_lo, -1
v_bfrev_b32_e32 v3, v1
v_ffbh_u32_e32 v4, v2
v_ffbl_b32_e32 v5, v1
v_ffbh_i32_e32 v6, v2
v_xor_b32_e32 v7, v3, v4
v_xor_b32_e32 v7, v5, v7
v_xor_b32_e32 v7, v6, v7
buffer_store_dword v7, v0, s[4:7], 0 idxen
s_waitcnt_vscnt null, 0
s_endpgm
+1 -1
View File
@@ -12,7 +12,7 @@ case "${1:-}" in
esac
for name in add bitwise-branch float-exact or shifts ashr \
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary scalar-arith scalar-immediate vector-integer vector-compare-ft; do
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary scalar-arith scalar-immediate vector-integer vector-compare-ft vector-unary; do
"$llvm_bin/llvm-mc" -triple=amdgcn-amd-amdhsa -mcpu=gfx1030 -mattr=+wavefrontsize32 \
-filetype=obj "fixtures/rdna2/$name.s" -o "$scratch/$name.o"
"$llvm_bin/llvm-objcopy" -O binary --only-section=.text "$scratch/$name.o" "$scratch/$name.bin"
+2 -1
View File
@@ -53,6 +53,7 @@ timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test audio_
# Native Metal known answers of the independent semantic review, including SOP2 scalar ALU
# and VOPC compares.
cargo test --locked -p xenora-semantic-review --no-run
# Oracles whose translator side has not landed are skipped by name until it does.
# Oracles whose translator side has not landed are skipped by name until it does
# (#215: the PR that translates the forms removes its skip).
timeout 120s cargo test --locked -p xenora-semantic-review -- --ignored --nocapture --test-threads=1 \
--skip vopc_wide_match_the_guide_on_native_metal
+22 -4
View File
@@ -843,10 +843,20 @@ fn other_vop1_opcodes_stay_unsupported() {
}
#[test]
#[ignore = "requires a native Metal device with API and shader validation, and the translator's VOP1 integer forms (skipped by scripts/test-gpu.sh until then)"]
fn vop1_integer_forms_match_the_guide_on_native_metal() {
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
fn compiler_matches_the_vop1_integer_operand_domain() {
let cases = checked_cases();
for case in &cases {
compile(Architecture::Gfx1030, &case.code)
.unwrap_or_else(|error| panic!("compiler rejected {}: {error:?}", case.label));
}
check_compiler_rejections();
eprintln!(
"vop1_integer: {} compiler cases and {REJECTIONS} rejections",
cases.len()
);
}
fn check_compiler_rejections() {
for (label, code, offset) in rejections() {
// Refused at the same word as by the interpreters, so a later failure
// cannot stand in.
@@ -857,7 +867,15 @@ fn vop1_integer_forms_match_the_guide_on_native_metal() {
};
assert_eq!(at, offset, "compiler rejected {label} elsewhere");
}
}
#[test]
#[ignore = "requires a native Metal device with API and shader validation"]
fn vop1_integer_forms_match_the_guide_on_native_metal() {
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
let cases = checked_cases();
check_compiler_rejections();
let (failures, programs) = harness::check_metal(&cases);
failures.assert_none("native Metal disagrees with the guide");
eprintln!(
+12
View File
@@ -67,6 +67,18 @@ class GenerateX86(unittest.TestCase):
self.rejects(self.form('op = "movq"\nmap = "0f"\nprefix = "66"\nopcode = 0xF0\nenc = "xmm_rm"\nsize = "x"\nsrc = "q"\nunaligned = true'), "alignment applies")
self.rejects(self.form('op = "nop"\nprefix = "66"\nopcode = 0xD7\nenc = "none"\nsize = "n"'), "map 0f")
def test_lock_needs_a_memory_destination(self):
# Not a form without ModRM, not one whose ModRM operand is the source,
# and not one that takes only a register.
message = "LOCK needs a memory destination"
self.rejects(self.form('op = "nop"\nopcode = 0xD7\nenc = "none"\nsize = "n"\nlock = true'), message)
self.rejects(self.form('op = "mov"\nopcode = 0xD7\nenc = "reg_rm"\nsize = "v"\nlock = true'), message)
self.rejects(self.form('op = "xadd"\nopcode = 0xD7\nenc = "rm_reg"\nsize = "v"\nregister_only = true\nlock = true'), message)
def test_only_xadd_and_cmpxchg_are_lockable(self):
_, forms = generate_x86.load(REGISTRY)
self.assertEqual({form["op"] for form in forms if form.get("lock")}, {"cmpxchg", "xadd"})
def test_unknown_vocabulary_is_rejected(self):
self.rejects(self.form('op = "frob"\nopcode = 0xD7\nenc = "none"\nsize = "n"'), "unknown op")
self.rejects(self.form('op = "nop"\nopcode = 0xD7\nenc = "none"\nsize = "z"'), "unknown size")