mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 17:30:43 +00:00
Compare commits
30
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
36c4fbd520 | ||
|
|
c3b0025977 | ||
|
|
cdcc55c33e | ||
|
|
0730f4dbbf | ||
|
|
6f27da3ccc | ||
|
|
6236996f41 | ||
|
|
05f2526d27 | ||
|
|
5131de9cd6 | ||
|
|
68503a674c | ||
|
|
82cb66e80f | ||
|
|
06dbe2946d | ||
|
|
14d5083f0f | ||
|
|
0115af5c04 | ||
|
|
5b7ffec90a | ||
|
|
48c5d20aa9 | ||
|
|
8049c36f51 | ||
|
|
c91036f879 | ||
|
|
c1cea65e17 | ||
|
|
3d19c756e2 | ||
|
|
710a2e1e73 | ||
|
|
de92766b29 | ||
|
|
4d44765363 | ||
|
|
6de750b152 | ||
|
|
adf10db015 | ||
|
|
4e4a6b36be | ||
|
|
dc3b02b62f | ||
|
|
d847d7ea6e | ||
|
|
b55a4c24ef | ||
|
|
d01627b3de | ||
|
|
291c9807ee |
No files matched your search
@@ -41,6 +41,8 @@ jobs:
|
||||
python3 crates/isa/generate_semantics.py --check
|
||||
python3 scripts/audit/semantic_coverage.py --check
|
||||
python3 scripts/audit/status.py --check
|
||||
# The generated status check must not depend on the host locale encoding.
|
||||
LC_ALL=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0 python3 scripts/audit/status.py --check
|
||||
for fixture in x2 x3 x4; do
|
||||
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
|
||||
done
|
||||
@@ -65,7 +67,7 @@ jobs:
|
||||
cargo test --locked --workspace
|
||||
cargo test --locked --manifest-path experiments/x1/Cargo.toml
|
||||
scripts/audit/dependencies.sh
|
||||
scripts/audit/claims.sh
|
||||
LC_ALL=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0 scripts/audit/claims.sh
|
||||
- name: Inspect native CLI
|
||||
run: |
|
||||
cargo build --locked -p xenora
|
||||
|
||||
+8
-10
@@ -10,6 +10,10 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Changed
|
||||
- Release and bench builds now use fat link-time optimization with one codegen unit (#116). On a local Apple M5, `dbt_bench` medians over five alternating runs dropped by about 6 % for the interpreter (903 to 845 µs) and about 9 % for cold DBT (1.155 to 1.046 ms), while warm DBT (cache hits) became about 2 % slower (21.83-22.08 to 22.29-22.54 µs over four further runs). The `xenora` binary shrank from 2.73 to 2.11 MB. A clean release build of the workspace takes about 14 s instead of 6 s. Debug and test builds are unchanged.
|
||||
- The ARM64 assembler loads 64-bit constants with the fewest MOVZ or MOVN plus MOVK instructions (#92). It no longer emits MOVK for zero halfwords and starts from MOVN when more halfwords are 0xFFFF than zero, so small negative values take one instruction instead of four. On Apple M5 the DBT benchmark emits 245,168 instead of 290,184 native bytes for its 626 blocks (-15.5%) and the 1,048 integer fixture instructions 128,724 instead of 145,732 (-11.7%); benchmark run times did not change measurably. New tests check the sequences against LLVM encodings and execute 1,056 of them on the host through the JIT.
|
||||
- Resolve the tiled BC1 mip and array layer once per linearization and copy contiguous block runs within each tile row. Partial edge blocks are retained and padding slots are skipped. Closes #349.
|
||||
- Relocation reports now build their type histogram once per image, avoiding a tree lookup for every entry. Target checks and fixup order are unchanged; synthetic regressions and an opt-in relocation timing test cover the change (#109).
|
||||
- Moved the six supported gfx1030 SOPP compute control forms into the semantic registry, preserving instruction decoding and shader lowering. Part of #215.
|
||||
- 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.
|
||||
@@ -17,18 +21,10 @@ remains unsupported.
|
||||
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
|
||||
|
||||
### Added
|
||||
- Added an opt-in, budgeted staged upload for RGBA8 textures (#144). `MetalRgba8Texture::upload_staged` fills a
|
||||
Private-storage texture through one reused Shared staging buffer that never exceeds a `StagingBudget`. It
|
||||
copies whole-row bands with a blit encoder and reuses the buffer only after the previous command buffer has
|
||||
completed with status Completed. `plan_staged_upload` rejects missing, duplicate or out-of-range mip levels,
|
||||
wrong mip sizes, short row pitches or byte buffers, and budgets smaller than one row, all before any Metal
|
||||
object is created. A blit `read_back` returns any mip as tight RGBA8 bytes. On one Apple M4 under Metal API
|
||||
validation, readback matched independently built patterns for every level of a padded 37×19, six-level
|
||||
texture under four budgets, and matched the existing direct `upload`. Staging is slower than the direct path
|
||||
(2048² with 12 mips, release build: 2.1 ms direct, 2.7 ms with a 4 MiB budget, 17.8 ms with 256 KiB), so
|
||||
`upload` and its callers are unchanged. Not yet independently accepted.
|
||||
- Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302).
|
||||
- Added the VOP3A (`_e64`) encodings of eleven gfx1030 VOP2 integer forms (`v_mul_{i32_i24,hi_i32_i24,u32_u24,hi_u32_u24}`, `v_{min,max}_{i32,u32}`, `v_xnor_b32`, `v_sub_nc_u32`, `v_subrev_nc_u32`) and of the sixteen Wave32 integer compares (explicit SGPR mask destination, `s_cbranch_vccz` through `vcc_lo`, a translation error for reads of runtime-only SGPR results) as semantic-registry encoding variants, with VGPR sources only. New fixtures `vop3-integer` and `vop3-compare` with IR and MSL goldens, and an independent guide-derived oracle (`tests/validation/tests/vop3_{integer,compare}.rs`) that agrees on both reference interpreters and on native Metal. Part of #215.
|
||||
- Added guest texture binding through D3D12-style descriptor tables (#303): shader-visible CBV_SRV_UAV and sampler heaps, `CreateShaderResourceView` for one-level RGBA8 and BC1 2D textures, a point/clamp `CreateSampler`, a root signature with one pixel-stage SRV table and one sampler table, and `SetDescriptorHeaps`/`SetGraphicsRootDescriptorTable` in `crates/loader/src/graphics.rs`, plus `NativeCompute::render_rgba8_sampled_bc1`. Verified locally on an Apple M5 Pro under Metal validation: a guest draw with the translated `image_sample_lz` pixel stage matches the software reference and hand-derived images on 16 of 16 pixels for two RGBA8 textures and 64 of 64 for an 8×8 BC1 texture. A wrong descriptor slot changes the image, off-centre and out-of-range coordinates point-sample with clamping, and a rejected binding, draw shape or resource state never reaches the backend. The software reference samples BC1 with the spec-exact decoder, while Apple's hardware rounds BC1's interpolated palette entries differently (171/84 against 170/85), so the BC1 fixtures use only endpoint colours. Not yet reachable from guest imports. Not yet independently accepted.
|
||||
- Added RCL and RCR, the rotates through the carry flag, for 8-, 16-, 32- and 64-bit register and memory operands with a count of one, CL or an immediate (part of #121). The count is masked to five bits (six for 64-bit operands) and then reduced modulo 9 or 17 for 8- and 16-bit operands; a masked count of zero changes nothing, CF receives the last bit rotated out, and OF is set only for a count of one. Both engines run the shared semantics; nothing is lowered to ARM64. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and its shift sweep now runs both instructions at every width, count and carry against its bit-loop model. `tests/x86/integer.txt` gains 80 assembled RCL and RCR instructions, checked by the single-step reference in `x86_integer.rs`. SHLD and SHRD stay rejected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added four Wave32 gfx1030 VOP2 select and carry forms through the semantic registry. Conditional select, add with carry and both subtract orders with borrow use a per-lane VCC bit and have a guide-derived oracle that passes on both CPU interpreters and on native Metal (local Apple M5, API and shader validation); independent acceptance is pending. Part of #215.
|
||||
- Added decoding and Metal shader translation for twelve Wave32 VOPC 16-bit integer compares (#215). The signed and unsigned forms compare the low 16 bits of each source and write the Wave32 VCC mask. CPU verification covers 1,572 compiler acceptance cases and 408 rejections from the guide-derived oracle, which also passes on native Metal (1,572 cases in 1,420 programs on a local Apple M5 under API and shader validation); acceptance is pending.
|
||||
- Added MOVS and STOS for 8- to 64-bit elements, with and without REP, and the direction flag with CLD and STD (#129). A REP form runs one element per step and stays on the instruction until RCX is zero, so every element counts against the step budget, a repeat can stop part-way and resume, a zero count touches nothing, and a fault keeps the elements already done with RSI, RDI and RCX at the one that faulted. An FS or GS override applies to the MOVS source only. Both engines run these on the shared semantics with no bulk-copy path, so large copies are slow. LODS, CMPS, SCAS, REPE, REPNE and the address-size override stay rejected. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/cpu_rep.rs` adds a byte-array model over every form, direction and count; not compared with x86 hardware and awaiting independent review.
|
||||
@@ -198,6 +194,7 @@ remains unsupported.
|
||||
|
||||
### Fixed
|
||||
- Made the static probe and the binder share one bounded import parser, after the truncated-name fix for #270. Truncated, unterminated, empty or non-ASCII names, reserved bits and endless tables are reported by the probe and refused by the binder.
|
||||
- Fixed the decoder refusing an instruction whose REX prefix is followed by a legacy prefix (#69). Such a REX is ignored, as the Intel SDM (Vol. 2A, 2.2.1) specifies, so `48 66 01 D8` now runs as `add ax, bx`; it used to stop the guest with an illegal-instruction exit. The ignored byte still counts toward the instruction's length, and a REX that directly precedes the opcode behaves as before. The interpreter, the DBT and the static probe share the decoder. One SDM-derived case in `cpu_known_answers.rs` moved from refused to verified and three were added, for an ignored REX.B, an ignored REX.W before a segment prefix, and a later REX that does apply. Two REX bytes in a row and the address-size prefix stay rejected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Fixed import binding writing some slots before finding an unresolved import, and service calls taking effect before an unreadable return address was noticed. A service that changes a nonvolatile register, including XMM6 to XMM15, now stops the guest (part of #201).
|
||||
- Fixed older import-generator templates that reported success for unimplemented wrappers, used a nonexistent exit reason, and read floating-point arguments from integer registers.
|
||||
- Fixed guest flags in the native DBT (#64, #70). They lived only in host NZCV, so they were lost across helper calls and block boundaries and register ADD, SUB and XOR set none. JB, JAE, JBE and JA used ARM carry polarity, which is inverted for subtraction. Flags are now stored in the guest state.
|
||||
@@ -206,6 +203,7 @@ remains unsupported.
|
||||
- Fixed 32-bit guest stores and loads in the native DBT (MOV 89/8B and C7 /0), which accessed eight bytes: stores overwrote the next four guest bytes and accesses at the end of a mapping faulted. RIP-relative operands of byte moves and extensions, which were read as RBP-relative, and LEA with a segment prefix, which added the segment base, are fixed too.
|
||||
- Fixed an x86 prefix-length test that read an untracked fuzz artifact and so failed on every fresh checkout; its input is now inline.
|
||||
- Fixed agent-queue `apply_actions` crashing on comment-only decisions (claim refusals) by skipping no-op `gh issue edit` calls; accept `summary --now` after the subcommand; grant the audit job `pull-requests: read` so live audits can list open PRs (issue #180).
|
||||
- Fixed `scripts/audit/status.py` and the Python embedded in `scripts/audit/claims.sh` reading and writing tracked files in the process locale encoding instead of UTF-8: under an ASCII or cp1252 locale the status check crashed on `docs/claims.toml` or reported a spurious `xenora-progress.svg` difference. Both scripts now pass `encoding="utf-8"`, as the rest of `scripts/` does, the two write sites also pin `newline="\n"` so a Windows host cannot turn tracked LF files into CRLF when it regenerates them, and CI runs the two checks again under a non-UTF-8 locale so the requirement stays enforced.
|
||||
|
||||
- Generated CRT adapters now report unsupported calls when the required guest ABI or runtime behavior is missing.
|
||||
|
||||
|
||||
@@ -10,3 +10,10 @@ rust-version = "1.100"
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_op_in_unsafe_fn = "deny"
|
||||
|
||||
# Whole-program optimization for release and bench builds (#116). On an Apple M5 the
|
||||
# interpreter ran about 6 % and cold DBT about 9 % faster in `dbt_bench`, at the cost of
|
||||
# slower release builds. Debug and test builds are unaffected.
|
||||
[profile.release]
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
@@ -1,5 +1,12 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Synthetic interpreter and DBT timings.
|
||||
//!
|
||||
//! The benchmark target disables Cargo's test harness. To run the percentile
|
||||
//! unit tests, build with
|
||||
//! `cargo rustc --locked -p xenora-loader --bench dbt_bench --message-format=json -- --test`
|
||||
//! and run the executable named by the benchmark's compiler-artifact message.
|
||||
|
||||
use std::hint::black_box;
|
||||
use std::time::{Duration, Instant};
|
||||
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, Register};
|
||||
@@ -88,14 +95,25 @@ fn check(result: ExecutionResult) {
|
||||
assert_eq!(result.final_state.get(Register::Rax), ADDS as u64);
|
||||
}
|
||||
|
||||
fn percentile(sorted: &[Duration], fraction: f64) -> Duration {
|
||||
// Interpolate between adjacent values at rank (n - 1) * fraction.
|
||||
let rank = (sorted.len() - 1) as f64 * fraction;
|
||||
let lower = sorted[rank.floor() as usize];
|
||||
let upper = sorted[rank.ceil() as usize];
|
||||
lower + (upper - lower).mul_f64(rank.fract())
|
||||
}
|
||||
|
||||
fn report(label: &str, samples: &mut [Duration]) {
|
||||
samples.sort_unstable();
|
||||
let median = samples[samples.len() / 2];
|
||||
let median = percentile(samples, 0.50);
|
||||
let p95 = percentile(samples, 0.95);
|
||||
let p99 = percentile(samples, 0.99);
|
||||
let iqr = percentile(samples, 0.75) - percentile(samples, 0.25);
|
||||
let min = samples[0];
|
||||
let max = samples[samples.len() - 1];
|
||||
let mips = INSTRUCTIONS as f64 / median.as_secs_f64() / 1_000_000.0;
|
||||
println!(
|
||||
"{label}: {} samples, median {median:?}, min {min:?}, max {max:?}, median {mips:.2} MIPS",
|
||||
"{label}: {} samples, median {median:?}, min {min:?}, max {max:?}, p95 {p95:?}, p99 {p99:?}, IQR {iqr:?}, median {mips:.2} MIPS",
|
||||
samples.len()
|
||||
);
|
||||
}
|
||||
@@ -104,6 +122,8 @@ fn main() {
|
||||
let sample_count = std::env::var("XENORA_DBT_BENCH_SAMPLES")
|
||||
.map_or(101, |value| value.parse::<usize>().expect("sample count"));
|
||||
assert!(sample_count > 0);
|
||||
let warmup_count = std::env::var("XENORA_DBT_BENCH_WARMUP")
|
||||
.map_or(10, |value| value.parse::<usize>().expect("warmup count"));
|
||||
|
||||
let mut code = vec![0x48, 0xB8, 0, 0, 0, 0, 0, 0, 0, 0]; // mov rax, 0
|
||||
for _ in 0..ADDS {
|
||||
@@ -124,38 +144,52 @@ fn main() {
|
||||
let mut warm = Vec::with_capacity(sample_count);
|
||||
let mut cold_metrics = None;
|
||||
|
||||
for _ in 0..sample_count {
|
||||
for record in
|
||||
std::iter::repeat_n(false, warmup_count).chain(std::iter::repeat_n(true, sample_count))
|
||||
{
|
||||
let mut interp = Interpreter::new(initial_cpu.clone(), &mut loaded.memory, BUDGET);
|
||||
let start = Instant::now();
|
||||
let result = black_box(interp.run());
|
||||
interpreter.push(start.elapsed());
|
||||
let interpreter_time = start.elapsed();
|
||||
check(result);
|
||||
|
||||
let mut dbt = DbtEngine::new(4 * 1024 * 1024).unwrap();
|
||||
let mut cpu = initial_cpu.clone();
|
||||
let start = Instant::now();
|
||||
let result = black_box(dbt.run(&mut cpu, &mut loaded.memory, BUDGET));
|
||||
cold.push(start.elapsed());
|
||||
let cold_time = start.elapsed();
|
||||
check(result);
|
||||
assert!(dbt.metrics.blocks_compiled > 0);
|
||||
assert_eq!(dbt.metrics.cache_hits, 0);
|
||||
assert_eq!(dbt.metrics.cache_misses, dbt.metrics.blocks_compiled);
|
||||
cold_metrics = Some(dbt.metrics);
|
||||
let metrics = dbt.metrics;
|
||||
|
||||
let mut cpu = initial_cpu.clone();
|
||||
let start = Instant::now();
|
||||
let result = black_box(dbt.run(&mut cpu, &mut loaded.memory, BUDGET));
|
||||
warm.push(start.elapsed());
|
||||
let warm_time = start.elapsed();
|
||||
check(result);
|
||||
assert_eq!(
|
||||
Some(dbt.metrics.blocks_compiled),
|
||||
cold_metrics.map(|m| m.blocks_compiled)
|
||||
);
|
||||
assert_eq!(dbt.metrics.blocks_compiled, metrics.blocks_compiled);
|
||||
assert_eq!(dbt.metrics.cache_hits, dbt.metrics.blocks_compiled);
|
||||
assert_eq!(dbt.metrics.cache_misses, dbt.metrics.blocks_compiled);
|
||||
|
||||
if record {
|
||||
interpreter.push(interpreter_time);
|
||||
cold.push(cold_time);
|
||||
warm.push(warm_time);
|
||||
cold_metrics = Some(metrics);
|
||||
}
|
||||
}
|
||||
|
||||
println!("{INSTRUCTIONS} guest instructions per sample, final RAX={ADDS}");
|
||||
println!("{warmup_count} warmup rounds excluded (XENORA_DBT_BENCH_WARMUP, default 10)");
|
||||
println!(
|
||||
"Cold DBT includes translation with a fresh engine; warm DBT reuses that engine's cache."
|
||||
);
|
||||
println!(
|
||||
"Percentiles describe this synthetic workload on this host; tail estimates vary with sample count."
|
||||
);
|
||||
println!("Even sample counts use the midpoint of the two middle values for the median.");
|
||||
report("Interpreter", &mut interpreter);
|
||||
report("Cold DBT", &mut cold);
|
||||
report("Warm DBT", &mut warm);
|
||||
@@ -165,3 +199,38 @@ fn main() {
|
||||
metrics.blocks_compiled, metrics.native_bytes_emitted, metrics.dbt_dispatches
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn single_sample_has_no_spread() {
|
||||
use super::{Duration, percentile};
|
||||
|
||||
let samples = [Duration::from_micros(50)];
|
||||
for fraction in [0.25, 0.50, 0.75, 0.95, 0.99] {
|
||||
assert_eq!(percentile(&samples, fraction), samples[0]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn percentiles_interpolate_across_even_samples() {
|
||||
use super::{Duration, percentile};
|
||||
|
||||
let samples = [10, 20, 30, 100].map(Duration::from_micros);
|
||||
assert_eq!(percentile(&samples, 0.50), Duration::from_micros(25));
|
||||
assert_eq!(percentile(&samples, 0.95), Duration::from_nanos(89_500));
|
||||
assert_eq!(percentile(&samples, 0.99), Duration::from_nanos(97_900));
|
||||
assert_eq!(
|
||||
percentile(&samples, 0.75) - percentile(&samples, 0.25),
|
||||
Duration::from_nanos(30_000)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn median_uses_the_middle_of_odd_samples() {
|
||||
use super::{Duration, percentile};
|
||||
|
||||
let samples = [10, 20, 100].map(Duration::from_micros);
|
||||
assert_eq!(percentile(&samples, 0.50), Duration::from_micros(20));
|
||||
}
|
||||
}
|
||||
+128
-14
@@ -582,22 +582,35 @@ impl Arm64Assembler {
|
||||
self.emit(0xf2800000 | (hw << 21) | ((imm16 as u32) << 5) | (xd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// Load a full 64-bit constant into register Xd.
|
||||
pub fn load_imm_64(&mut self, xd: u8, val: u64) {
|
||||
let w0 = (val & 0xffff) as u16;
|
||||
let w1 = ((val >> 16) & 0xffff) as u16;
|
||||
let w2 = ((val >> 32) & 0xffff) as u16;
|
||||
let w3 = ((val >> 48) & 0xffff) as u16;
|
||||
/// MOVN (64-bit with shift): MOVN Xd, #imm16, LSL #shift writes
|
||||
/// NOT (imm16 << shift), so every other halfword becomes 0xFFFF.
|
||||
pub fn movn_64(&mut self, xd: u8, imm16: u16, shift_idx: u8) {
|
||||
let hw = (shift_idx & 3) as u32;
|
||||
self.emit(0x92800000 | (hw << 21) | ((imm16 as u32) << 5) | (xd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
self.movz_64(xd, w0, 0);
|
||||
if w1 != 0 || (w2 == 0 && w3 == 0) {
|
||||
self.movk_64(xd, w1, 1);
|
||||
/// Load a full 64-bit constant into register Xd with the fewest MOVZ or
|
||||
/// MOVN plus MOVK instructions: one for each halfword that differs from
|
||||
/// the background the first instruction leaves, and always at least one.
|
||||
/// MOVZ leaves zero halfwords and MOVN leaves 0xFFFF ones, so MOVN is used
|
||||
/// when more halfwords are 0xFFFF than zero.
|
||||
pub fn load_imm_64(&mut self, xd: u8, val: u64) {
|
||||
let halves: [u16; 4] = std::array::from_fn(|i| (val >> (16 * i)) as u16);
|
||||
let zeros = halves.iter().filter(|&&h| h == 0).count();
|
||||
let ones = halves.iter().filter(|&&h| h == 0xffff).count();
|
||||
let background = if ones > zeros { 0xffff } else { 0 };
|
||||
// The first halfword that differs from the background, or halfword 0
|
||||
// when none does (val is 0 or all ones).
|
||||
let first = halves.iter().position(|&h| h != background).unwrap_or(0);
|
||||
if background == 0 {
|
||||
self.movz_64(xd, halves[first], first as u8);
|
||||
} else {
|
||||
self.movn_64(xd, !halves[first], first as u8);
|
||||
}
|
||||
if w2 != 0 || w3 != 0 {
|
||||
self.movk_64(xd, w2, 2);
|
||||
}
|
||||
if w3 != 0 {
|
||||
self.movk_64(xd, w3, 3);
|
||||
for (index, &half) in halves.iter().enumerate().skip(first + 1) {
|
||||
if half != background {
|
||||
self.movk_64(xd, half, index as u8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -786,4 +799,105 @@ mod tests {
|
||||
asm.str_uoff_32(X0, X19, 136);
|
||||
assert_eq!(asm.instructions(), &[0xf90013f5, 0xf9404269, 0xb9008a60]);
|
||||
}
|
||||
|
||||
/// Constants at the halfword boundaries the MOVZ/MOVN choice depends on.
|
||||
const IMMEDIATE_EDGES: [u64; 16] = [
|
||||
0,
|
||||
1,
|
||||
0xffff,
|
||||
0x1_0000,
|
||||
0x8000_0000,
|
||||
0xffff_ffff,
|
||||
0x1_0000_0000,
|
||||
0x1234_0000_0000_0000,
|
||||
0x0000_0001_0000_0005,
|
||||
0x1234_5678_9abc_def0,
|
||||
0x7fff_ffff_ffff_ffff,
|
||||
0x8000_0000_0000_0000,
|
||||
0xffff_0000_ffff_ffff,
|
||||
0xffff_ffff_edcc_5678,
|
||||
0xffff_ffff_ffff_1234,
|
||||
u64::MAX,
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn immediate_sequences_match_llvm_encodings() {
|
||||
// llvm-mc -triple=aarch64-apple-macos -show-encoding.
|
||||
let cases: &[(u64, &[u32])] = &[
|
||||
(0, &[0xd2800000]), // movz x0, #0
|
||||
(u64::MAX, &[0x92800000]), // movn x0, #0
|
||||
(0xffff_ffff_ffff_1234, &[0x929db960]), // movn x0, #0xedcb
|
||||
(0x1234_0000_0000_0000, &[0xd2e24680]), // movz x0, #0x1234, lsl #48
|
||||
(0xffff_0000_ffff_ffff, &[0x92dfffe0]), // movn x0, #0xffff, lsl #32
|
||||
(0x0000_0001_0000_0005, &[0xd28000a0, 0xf2c00020]), // movz #5; movk #1, lsl #32
|
||||
// movn x0, #0xa987; movk x0, #0xedcc, lsl #16
|
||||
(0xffff_ffff_edcc_5678, &[0x929530e0, 0xf2bdb980]),
|
||||
];
|
||||
for &(value, expected) in cases {
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.load_imm_64(X0, value);
|
||||
assert_eq!(asm.instructions(), expected, "{value:#x}");
|
||||
}
|
||||
// movz x9, #0xdef0; movk x9, #0x9abc, lsl #16; #0x5678, lsl #32;
|
||||
// #0x1234, lsl #48
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.load_imm_64(X9, 0x1234_5678_9abc_def0);
|
||||
assert_eq!(
|
||||
asm.instructions(),
|
||||
&[0xd29bde09, 0xf2b35789, 0xf2cacf09, 0xf2e24689]
|
||||
);
|
||||
}
|
||||
|
||||
/// Fewest MOVZ/MOVN/MOVK instructions for `value`: every halfword that is
|
||||
/// neither zero (after MOVZ) nor 0xFFFF (after MOVN), and at least one.
|
||||
fn shortest_wide_move(value: u64) -> usize {
|
||||
let halves = (0..4).map(|i| (value >> (16 * i)) & 0xffff);
|
||||
let not_zero = halves.clone().filter(|&h| h != 0).count();
|
||||
let not_ones = halves.filter(|&h| h != 0xffff).count();
|
||||
not_zero.min(not_ones).max(1)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn immediates_run_on_the_host_and_use_the_fewest_wide_moves() {
|
||||
let mut values = IMMEDIATE_EDGES.to_vec();
|
||||
let mut state = 0x9e37_79b9_7f4a_7c15u64;
|
||||
for _ in 0..512 {
|
||||
state ^= state >> 12;
|
||||
state ^= state << 25;
|
||||
state ^= state >> 27;
|
||||
let raw = state.wrapping_mul(0x2545_f491_4f6c_dd1d);
|
||||
// Force some halfwords to zero or all ones so both MOVZ and MOVN
|
||||
// sequences of every length occur.
|
||||
let mut value = raw;
|
||||
for half in 0..4 {
|
||||
match (raw >> (60 - 2 * half)) & 3 {
|
||||
0 => value &= !(0xffff << (16 * half)),
|
||||
1 => value |= 0xffff << (16 * half),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
values.push(value);
|
||||
}
|
||||
let mut jit = crate::jit::JitMemory::new(64 * 1024).unwrap();
|
||||
for value in values {
|
||||
for register in [X0, X9] {
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.load_imm_64(register, value);
|
||||
assert_eq!(
|
||||
asm.instructions().len(),
|
||||
shortest_wide_move(value),
|
||||
"{value:#x}"
|
||||
);
|
||||
if register != X0 {
|
||||
asm.mov_reg_64(X0, register);
|
||||
}
|
||||
asm.ret();
|
||||
let entry = jit.emit_block(asm.instructions()).unwrap();
|
||||
// SAFETY: the block is a complete AAPCS64 leaf function that
|
||||
// writes only X0 (and X9, a caller-saved register) and returns.
|
||||
let function: extern "C" fn() -> u64 = unsafe { std::mem::transmute(entry) };
|
||||
assert_eq!(function(), value, "{value:#x} in x{register}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+234
-1
@@ -163,7 +163,6 @@ pub fn apply_relocations(
|
||||
let reloc_type = (entry_val >> 12) as u8;
|
||||
let offset_in_page = (entry_val & 0x0FFF) as u32;
|
||||
|
||||
*report.type_counts.entry(reloc_type).or_insert(0) += 1;
|
||||
report.total_entries += 1;
|
||||
|
||||
match reloc_type {
|
||||
@@ -221,6 +220,17 @@ pub fn apply_relocations(
|
||||
read_bytes += block_size as usize;
|
||||
}
|
||||
|
||||
// Only these two types can reach a successful return. Build the public
|
||||
// histogram once instead of searching its tree for every relocation.
|
||||
for (kind, count) in [
|
||||
(IMAGE_REL_BASED_ABSOLUTE, report.skipped_absolute),
|
||||
(IMAGE_REL_BASED_DIR64, report.applied_dir64),
|
||||
] {
|
||||
if count != 0 {
|
||||
report.type_counts.insert(kind, count);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
@@ -274,3 +284,226 @@ fn find_reloc_directory(
|
||||
Ok(Some((reloc_rva, reloc_size)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::memory::MemoryPermissions;
|
||||
use crate::pe::PeSection;
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
const PREFERRED: u64 = 0x140000000;
|
||||
const LOADED: u64 = PREFERRED + 0x200000;
|
||||
const DATA_RVA: u32 = 0x1000;
|
||||
const DIRECTORY_RVA: u32 = 0x10000000;
|
||||
const DIRECTORY_OFFSET: usize = 0x200;
|
||||
|
||||
// Original synthetic directory, laid out from Microsoft's PE Format,
|
||||
// .reloc section: eight-byte block headers and two-byte type/offset words.
|
||||
// https://learn.microsoft.com/windows/win32/debug/pe-format#the-reloc-section-image-only
|
||||
// Header fields and metadata are supplied directly: PE parsing is not timed.
|
||||
fn fixture(blocks: &[(u32, Vec<u16>)], data: &[u8]) -> (ParsedPe, Vec<u8>, GuestMemory) {
|
||||
let mut bytes = vec![0u8; DIRECTORY_OFFSET];
|
||||
bytes[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes());
|
||||
bytes[0x94..0x96].copy_from_slice(&240u16.to_le_bytes());
|
||||
bytes[0x104..0x108].copy_from_slice(&16u32.to_le_bytes());
|
||||
bytes[0x130..0x134].copy_from_slice(&DIRECTORY_RVA.to_le_bytes());
|
||||
for (page, entries) in blocks {
|
||||
bytes.extend_from_slice(&page.to_le_bytes());
|
||||
bytes.extend_from_slice(&(8u32 + entries.len() as u32 * 2).to_le_bytes());
|
||||
for entry in entries {
|
||||
bytes.extend_from_slice(&entry.to_le_bytes());
|
||||
}
|
||||
}
|
||||
let size = (bytes.len() - DIRECTORY_OFFSET) as u32;
|
||||
bytes[0x134..0x138].copy_from_slice(&size.to_le_bytes());
|
||||
let pe = ParsedPe {
|
||||
machine: 0x8664,
|
||||
number_of_sections: 1,
|
||||
time_date_stamp: 0,
|
||||
image_base: PREFERRED,
|
||||
section_alignment: 4096,
|
||||
file_alignment: 512,
|
||||
size_of_image: DIRECTORY_RVA + size.max(4096),
|
||||
size_of_headers: 512,
|
||||
entry_point_rva: 0,
|
||||
sections: vec![PeSection {
|
||||
name: ".reloc".into(),
|
||||
virtual_address: DIRECTORY_RVA,
|
||||
virtual_size: size,
|
||||
raw_data_ptr: DIRECTORY_OFFSET as u32,
|
||||
raw_data_size: size,
|
||||
characteristics: 0x40000040,
|
||||
permissions: MemoryPermissions::READ_ONLY,
|
||||
}],
|
||||
};
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
LOADED + u64::from(DATA_RVA),
|
||||
data.len(),
|
||||
MemoryPermissions::READ_ONLY,
|
||||
data,
|
||||
)
|
||||
.unwrap();
|
||||
(pe, bytes, memory)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_padding_and_rebases_read_only_targets() {
|
||||
for (preferred, initial, expected) in [
|
||||
(PREFERRED, 0x140001234, 0x140201234),
|
||||
(LOADED + 0x200000, 0x140001234, 0x13fe01234),
|
||||
(LOADED - 8, u64::MAX - 3, 4),
|
||||
(LOADED + 8, 3, u64::MAX - 4),
|
||||
] {
|
||||
let (mut pe, bytes, mut memory) =
|
||||
fixture(&[(DATA_RVA, vec![0x0fff, 0xa000])], &initial.to_le_bytes());
|
||||
pe.image_base = preferred;
|
||||
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
|
||||
assert_eq!(memory.read_u64(LOADED + 0x1000).unwrap(), expected);
|
||||
assert_eq!(report.total_entries, 2);
|
||||
assert_eq!(report.applied_dir64, 1);
|
||||
assert_eq!(report.skipped_absolute, 1);
|
||||
assert_eq!(report.type_counts, BTreeMap::from([(0, 1), (10, 1)]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn histogram_omits_types_that_did_not_occur() {
|
||||
for (entries, counts) in [
|
||||
(vec![], BTreeMap::new()),
|
||||
(vec![0x0fff, 0x0000], BTreeMap::from([(0, 2)])),
|
||||
(vec![0xa000, 0xa008], BTreeMap::from([(10, 2)])),
|
||||
] {
|
||||
let (pe, bytes, mut memory) = fixture(&[(DATA_RVA, entries)], &[0; 16]);
|
||||
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
|
||||
assert_eq!(report.type_counts, counts);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_duplicate_and_overlapping_entry_order() {
|
||||
let (pe, bytes, mut memory) = fixture(
|
||||
&[(DATA_RVA, vec![0xa000, 0xa000, 0xa004, 0x0000])],
|
||||
&[0; 16],
|
||||
);
|
||||
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
|
||||
// Two additions of 0x200000 at offset zero, then one at offset four.
|
||||
let mut actual = [0; 16];
|
||||
memory.read_bytes(LOADED + 0x1000, &mut actual).unwrap();
|
||||
assert_eq!(
|
||||
actual,
|
||||
[0, 0, 0x40, 0, 0, 0, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
||||
);
|
||||
assert_eq!(report.type_counts, BTreeMap::from([(0, 1), (10, 3)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_fields_observe_prior_carries_in_directory_order() {
|
||||
let initial = [255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0];
|
||||
for (entries, expected) in [
|
||||
(vec![0xa000, 0xa004], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]),
|
||||
(vec![0xa004, 0xa000], [0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]),
|
||||
] {
|
||||
let (mut pe, bytes, mut memory) = fixture(&[(DATA_RVA, entries)], &initial);
|
||||
pe.image_base = LOADED - 1;
|
||||
apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
|
||||
let mut actual = [0; 12];
|
||||
memory.read_bytes(LOADED + 0x1000, &mut actual).unwrap();
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_prior_writes_and_rejects_unsupported_types() {
|
||||
let (pe, bytes, mut memory) = fixture(&[(DATA_RVA, vec![0xa000, 0xf008])], &[0; 16]);
|
||||
assert_eq!(
|
||||
apply_relocations(&pe, &bytes, LOADED, &mut memory),
|
||||
Err(RelocationError::UnsupportedRelocationType(15))
|
||||
);
|
||||
assert_eq!(memory.read_u64(LOADED + 0x1000).unwrap(), 0x200000);
|
||||
assert_eq!(memory.read_u64(LOADED + 0x1008).unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_delta_keeps_the_empty_report_without_parsing() {
|
||||
let (mut pe, _, mut memory) = fixture(&[], &[0; 8]);
|
||||
pe.image_base = LOADED;
|
||||
assert_eq!(
|
||||
apply_relocations(&pe, &[], LOADED, &mut memory).unwrap(),
|
||||
RelocationReport::default()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual relocation timing run; release build on an otherwise idle host"]
|
||||
fn relocation_profile() {
|
||||
for pages in [1u32, 128] {
|
||||
for padding_every in [0usize, 2, 1] {
|
||||
let blocks: Vec<_> = (0..pages)
|
||||
.map(|page| {
|
||||
let entries = (0..512)
|
||||
.map(|slot| {
|
||||
let padding = padding_every != 0 && slot % padding_every == 0;
|
||||
(if padding { 0 } else { 0xa000 }) | (slot as u16 * 8)
|
||||
})
|
||||
.collect();
|
||||
(DATA_RVA + page * 4096, entries)
|
||||
})
|
||||
.collect();
|
||||
let (pe, bytes, initial) = fixture(&blocks, &vec![0; pages as usize * 4096]);
|
||||
let mut samples = Vec::new();
|
||||
for run in 0..36 {
|
||||
let mut memory = initial.clone();
|
||||
let start = Instant::now();
|
||||
let report = black_box(
|
||||
apply_relocations(
|
||||
black_box(&pe),
|
||||
black_box(&bytes),
|
||||
LOADED,
|
||||
black_box(&mut memory),
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
let elapsed = start.elapsed().as_secs_f64() * 1e6;
|
||||
assert_eq!(report.total_entries, pages as usize * 512);
|
||||
let padding = match padding_every {
|
||||
0 => 0,
|
||||
2 => report.total_entries / 2,
|
||||
_ => report.total_entries,
|
||||
};
|
||||
assert_eq!(report.skipped_absolute, padding);
|
||||
assert_eq!(report.applied_dir64, report.total_entries - padding);
|
||||
// Check every output against the fixture's independently specified pattern.
|
||||
for slot in 0..pages as usize * 512 {
|
||||
let expected = if padding_every != 0 && slot % padding_every == 0 {
|
||||
0
|
||||
} else {
|
||||
0x200000
|
||||
};
|
||||
assert_eq!(
|
||||
memory.read_u64(LOADED + 0x1000 + slot as u64 * 8).unwrap(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
if run >= 5 {
|
||||
samples.push(elapsed);
|
||||
}
|
||||
}
|
||||
samples.sort_by(f64::total_cmp);
|
||||
let mean = samples.iter().sum::<f64>() / samples.len() as f64;
|
||||
let variance =
|
||||
samples.iter().map(|s| (s - mean).powi(2)).sum::<f64>() / samples.len() as f64;
|
||||
println!(
|
||||
"pages={pages} padding_every={padding_every} n={} median_us={:.3} variance_us2={variance:.3} min_us={:.3} max_us={:.3}",
|
||||
samples.len(),
|
||||
samples[samples.len() / 2],
|
||||
samples[0],
|
||||
samples[samples.len() - 1]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -237,6 +237,15 @@ impl<E, F: FnMut(u64) -> Result<u8, E>> Cursor<F> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `byte` is a legacy prefix: an operand-size, address-size, segment,
|
||||
/// LOCK or repeat prefix (Intel SDM Vol. 2A, 2.1.1).
|
||||
fn is_legacy_prefix(byte: u8) -> bool {
|
||||
matches!(
|
||||
byte,
|
||||
0x26 | 0x2E | 0x36 | 0x3E | 0x64 | 0x65 | 0x66 | 0x67 | 0xF0 | 0xF2 | 0xF3
|
||||
)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
///
|
||||
@@ -258,9 +267,22 @@ pub fn decode<E>(
|
||||
let mut repne = false;
|
||||
let mut lock = false;
|
||||
let mut segment = None;
|
||||
let mut rex = 0;
|
||||
let mut byte = cursor.u8()?;
|
||||
loop {
|
||||
let selected = match byte {
|
||||
// REX applies only immediately before the opcode. One that is
|
||||
// followed by a legacy prefix is ignored (Intel SDM Vol. 2A, 2.2.1).
|
||||
0x40..=0x4F => {
|
||||
let next = cursor.u8()?;
|
||||
if !is_legacy_prefix(next) {
|
||||
rex = byte;
|
||||
byte = next;
|
||||
break;
|
||||
}
|
||||
byte = next;
|
||||
continue;
|
||||
}
|
||||
0x64 => Segment::Fs,
|
||||
0x65 => Segment::Gs,
|
||||
0x66 => {
|
||||
@@ -299,10 +321,6 @@ pub fn decode<E>(
|
||||
byte = cursor.u8()?;
|
||||
}
|
||||
|
||||
let rex = if byte & 0xF0 == 0x40 { byte } else { 0 };
|
||||
if rex != 0 {
|
||||
byte = cursor.u8()?;
|
||||
}
|
||||
let (rex_w, rex_r, rex_x, rex_b) =
|
||||
(rex & 8 != 0, (rex & 4) << 1, (rex & 2) << 2, (rex & 1) << 3);
|
||||
|
||||
|
||||
@@ -241,6 +241,25 @@ fn shift(op: Op, value: u64, count: u64, size: u8, old: RFlags) -> Option<(u64,
|
||||
flags.cf = signed >> (count - 1) & 1 != 0;
|
||||
(signed >> count) as u64
|
||||
}
|
||||
Op::Rcl | Op::Rcr => {
|
||||
// The carry flag is one more bit above the operand, so the rotation
|
||||
// is over `bits + 1` positions and the count is reduced modulo that.
|
||||
let width = bits + 1;
|
||||
let ring = wide | u128::from(old.cf) << bits;
|
||||
let by = count % width;
|
||||
let left = if op == Op::Rcl {
|
||||
by
|
||||
} else {
|
||||
(width - by) % width
|
||||
};
|
||||
let rotated = if left == 0 {
|
||||
ring
|
||||
} else {
|
||||
ring << left | ring >> (width - left)
|
||||
};
|
||||
flags.cf = rotated >> bits & 1 != 0;
|
||||
rotated as u64
|
||||
}
|
||||
_ => {
|
||||
let by = count % bits;
|
||||
let left = if op == Op::Rol {
|
||||
@@ -268,7 +287,7 @@ fn shift(op: Op, value: u64, count: u64, size: u8, old: RFlags) -> Option<(u64,
|
||||
// OF is defined only for a count of one.
|
||||
if count == 1 {
|
||||
flags.of = match op {
|
||||
Op::Shl | Op::Rol => (result & top != 0) != flags.cf,
|
||||
Op::Shl | Op::Rol | Op::Rcl => (result & top != 0) != flags.cf,
|
||||
Op::Shr => value & top != 0,
|
||||
Op::Sar => false,
|
||||
_ => (result & top != 0) != (result & (top >> 1) != 0),
|
||||
@@ -419,7 +438,7 @@ pub fn execute(
|
||||
if negative { mask(size) } else { 0 },
|
||||
);
|
||||
}
|
||||
Op::Rol | Op::Ror | Op::Shl | Op::Shr | Op::Sar => {
|
||||
Op::Rol | Op::Ror | Op::Rcl | Op::Rcr | Op::Shl | Op::Shr | Op::Sar => {
|
||||
let (a, count) = operands(cpu, memory, insn)?;
|
||||
match shift(insn.op, a, count, size, cpu.flags) {
|
||||
Some((value, flags)) => {
|
||||
|
||||
@@ -34,6 +34,8 @@ pub enum Op {
|
||||
Cdq,
|
||||
Rol,
|
||||
Ror,
|
||||
Rcl,
|
||||
Rcr,
|
||||
Shl,
|
||||
Shr,
|
||||
Sar,
|
||||
@@ -209,7 +211,7 @@ pub enum Op {
|
||||
}
|
||||
|
||||
impl Op {
|
||||
pub const ALL: &[Op] = &[Op::Add, Op::Or, Op::Adc, Op::Sbb, Op::And, Op::Sub, Op::Xor, Op::Cmp, Op::Test, Op::Inc, Op::Dec, Op::Neg, Op::Not, Op::Mov, Op::Movzx, Op::Movsx, Op::Movsxd, Op::Lea, Op::Xchg, Op::Xadd, Op::Cmpxchg, Op::Bswap, Op::Cwde, Op::Cdq, Op::Rol, Op::Ror, Op::Shl, Op::Shr, Op::Sar, Op::Mul, Op::Imul, Op::Imul2, Op::Div, Op::Idiv, Op::Cmov, Op::Setcc, Op::Bt, Op::Bts, Op::Btr, Op::Btc, Op::Bsf, Op::Bsr, Op::Popcnt, Op::Tzcnt, Op::Lzcnt, Op::Push, Op::Pop, Op::Leave, Op::Call, Op::Jmp, Op::Jcc, Op::Ret, Op::Nop, Op::Hlt, Op::Syscall, Op::Clc, Op::Stc, Op::Cmc, Op::Cpuid, Op::Cld, Op::Std, Op::Movs, Op::Stos, Op::Movaps, Op::Movups, Op::Movdqa, Op::Movdqu, Op::Movntdq, Op::Movntps, Op::Movss, Op::Movsd, Op::Movq, Op::Movd, Op::Movlps, Op::Movhps, Op::Movmskps, Op::Movmskpd, Op::Pmovmskb, Op::Pand, Op::Pandn, Op::Por, Op::Pxor, Op::Punpcklbw, Op::Punpcklwd, Op::Punpckldq, Op::Packsswb, Op::Pcmpgtb, Op::Pcmpgtw, Op::Pcmpgtd, Op::Packuswb, Op::Punpckhbw, Op::Punpckhwd, Op::Punpckhdq, Op::Packssdw, Op::Punpcklqdq, Op::Punpckhqdq, Op::Pcmpeqb, Op::Pcmpeqw, Op::Pcmpeqd, Op::Paddq, Op::Pmullw, Op::Psubusb, Op::Psubusw, Op::Pminub, Op::Paddusb, Op::Paddusw, Op::Pmaxub, Op::Pavgb, Op::Pavgw, Op::Pmulhuw, Op::Pmulhw, Op::Psubsb, Op::Psubsw, Op::Pminsw, Op::Paddsb, Op::Paddsw, Op::Pmaxsw, Op::Pmuludq, Op::Pmaddwd, Op::Psadbw, Op::Psubb, Op::Psubw, Op::Psubd, Op::Psubq, Op::Paddb, Op::Paddw, Op::Paddd, Op::Psrlw, Op::Psraw, Op::Psllw, Op::Psrld, Op::Psrad, Op::Pslld, Op::Psrlq, Op::Psllq, Op::Psrldq, Op::Pslldq, Op::Pshufd, Op::Pshufhw, Op::Pshuflw, Op::Shufps, Op::Shufpd, Op::Pinsrw, Op::Pextrw, Op::Ldmxcsr, Op::Stmxcsr, Op::Sqrtps, Op::Sqrtpd, Op::Sqrtss, Op::Sqrtsd, Op::Addps, Op::Addpd, Op::Addss, Op::Addsd, Op::Mulps, Op::Mulpd, Op::Mulss, Op::Mulsd, Op::Subps, Op::Subpd, Op::Subss, Op::Subsd, Op::Minps, Op::Minpd, Op::Minss, Op::Minsd, Op::Divps, Op::Divpd, Op::Divss, Op::Divsd, Op::Maxps, Op::Maxpd, Op::Maxss, Op::Maxsd, Op::Cmpps, Op::Cmppd, Op::Cmpss, Op::Cmpsd, Op::Ucomiss, Op::Comiss, Op::Ucomisd, Op::Comisd, Op::Cvtps2pd, Op::Cvtpd2ps, Op::Cvtss2sd, Op::Cvtsd2ss, Op::Cvtdq2ps, Op::Cvtps2dq, Op::Cvttps2dq, Op::Cvttpd2dq, Op::Cvtdq2pd, Op::Cvtpd2dq, Op::Cvtsi2ss, Op::Cvttss2si, Op::Cvtss2si, Op::Cvtsi2sd, Op::Cvttsd2si, Op::Cvtsd2si];
|
||||
pub const ALL: &[Op] = &[Op::Add, Op::Or, Op::Adc, Op::Sbb, Op::And, Op::Sub, Op::Xor, Op::Cmp, Op::Test, Op::Inc, Op::Dec, Op::Neg, Op::Not, Op::Mov, Op::Movzx, Op::Movsx, Op::Movsxd, Op::Lea, Op::Xchg, Op::Xadd, Op::Cmpxchg, Op::Bswap, Op::Cwde, Op::Cdq, Op::Rol, Op::Ror, Op::Rcl, Op::Rcr, Op::Shl, Op::Shr, Op::Sar, Op::Mul, Op::Imul, Op::Imul2, Op::Div, Op::Idiv, Op::Cmov, Op::Setcc, Op::Bt, Op::Bts, Op::Btr, Op::Btc, Op::Bsf, Op::Bsr, Op::Popcnt, Op::Tzcnt, Op::Lzcnt, Op::Push, Op::Pop, Op::Leave, Op::Call, Op::Jmp, Op::Jcc, Op::Ret, Op::Nop, Op::Hlt, Op::Syscall, Op::Clc, Op::Stc, Op::Cmc, Op::Cpuid, Op::Cld, Op::Std, Op::Movs, Op::Stos, Op::Movaps, Op::Movups, Op::Movdqa, Op::Movdqu, Op::Movntdq, Op::Movntps, Op::Movss, Op::Movsd, Op::Movq, Op::Movd, Op::Movlps, Op::Movhps, Op::Movmskps, Op::Movmskpd, Op::Pmovmskb, Op::Pand, Op::Pandn, Op::Por, Op::Pxor, Op::Punpcklbw, Op::Punpcklwd, Op::Punpckldq, Op::Packsswb, Op::Pcmpgtb, Op::Pcmpgtw, Op::Pcmpgtd, Op::Packuswb, Op::Punpckhbw, Op::Punpckhwd, Op::Punpckhdq, Op::Packssdw, Op::Punpcklqdq, Op::Punpckhqdq, Op::Pcmpeqb, Op::Pcmpeqw, Op::Pcmpeqd, Op::Paddq, Op::Pmullw, Op::Psubusb, Op::Psubusw, Op::Pminub, Op::Paddusb, Op::Paddusw, Op::Pmaxub, Op::Pavgb, Op::Pavgw, Op::Pmulhuw, Op::Pmulhw, Op::Psubsb, Op::Psubsw, Op::Pminsw, Op::Paddsb, Op::Paddsw, Op::Pmaxsw, Op::Pmuludq, Op::Pmaddwd, Op::Psadbw, Op::Psubb, Op::Psubw, Op::Psubd, Op::Psubq, Op::Paddb, Op::Paddw, Op::Paddd, Op::Psrlw, Op::Psraw, Op::Psllw, Op::Psrld, Op::Psrad, Op::Pslld, Op::Psrlq, Op::Psllq, Op::Psrldq, Op::Pslldq, Op::Pshufd, Op::Pshufhw, Op::Pshuflw, Op::Shufps, Op::Shufpd, Op::Pinsrw, Op::Pextrw, Op::Ldmxcsr, Op::Stmxcsr, Op::Sqrtps, Op::Sqrtpd, Op::Sqrtss, Op::Sqrtsd, Op::Addps, Op::Addpd, Op::Addss, Op::Addsd, Op::Mulps, Op::Mulpd, Op::Mulss, Op::Mulsd, Op::Subps, Op::Subpd, Op::Subss, Op::Subsd, Op::Minps, Op::Minpd, Op::Minss, Op::Minsd, Op::Divps, Op::Divpd, Op::Divss, Op::Divsd, Op::Maxps, Op::Maxpd, Op::Maxss, Op::Maxsd, Op::Cmpps, Op::Cmppd, Op::Cmpss, Op::Cmpsd, Op::Ucomiss, Op::Comiss, Op::Ucomisd, Op::Comisd, Op::Cvtps2pd, Op::Cvtpd2ps, Op::Cvtss2sd, Op::Cvtsd2ss, Op::Cvtdq2ps, Op::Cvtps2dq, Op::Cvttps2dq, Op::Cvttpd2dq, Op::Cvtdq2pd, Op::Cvtpd2dq, Op::Cvtsi2ss, Op::Cvttss2si, Op::Cvtss2si, Op::Cvtsi2sd, Op::Cvttsd2si, Op::Cvtsd2si];
|
||||
|
||||
/// Lower-case mnemonic stem.
|
||||
pub const fn name(self) -> &'static str {
|
||||
@@ -240,6 +242,8 @@ impl Op {
|
||||
Op::Cdq => "cdq",
|
||||
Op::Rol => "rol",
|
||||
Op::Ror => "ror",
|
||||
Op::Rcl => "rcl",
|
||||
Op::Rcr => "rcr",
|
||||
Op::Shl => "shl",
|
||||
Op::Shr => "shr",
|
||||
Op::Sar => "sar",
|
||||
@@ -444,6 +448,8 @@ impl Op {
|
||||
Op::Cdq => 0,
|
||||
Op::Rol => 0,
|
||||
Op::Ror => 0,
|
||||
Op::Rcl => 1,
|
||||
Op::Rcr => 1,
|
||||
Op::Shl => 0,
|
||||
Op::Shr => 0,
|
||||
Op::Sar => 0,
|
||||
@@ -648,6 +654,8 @@ impl Op {
|
||||
Op::Cdq => 0,
|
||||
Op::Rol => 0,
|
||||
Op::Ror => 0,
|
||||
Op::Rcl => 0,
|
||||
Op::Rcr => 0,
|
||||
Op::Shl => 0,
|
||||
Op::Shr => 0,
|
||||
Op::Sar => 0,
|
||||
@@ -852,6 +860,8 @@ impl Op {
|
||||
Op::Cdq => 0,
|
||||
Op::Rol => 9,
|
||||
Op::Ror => 9,
|
||||
Op::Rcl => 9,
|
||||
Op::Rcr => 9,
|
||||
Op::Shl => 31,
|
||||
Op::Shr => 31,
|
||||
Op::Sar => 31,
|
||||
@@ -1056,6 +1066,8 @@ impl Op {
|
||||
Op::Cdq => 0,
|
||||
Op::Rol => 0,
|
||||
Op::Ror => 0,
|
||||
Op::Rcl => 0,
|
||||
Op::Rcr => 0,
|
||||
Op::Shl => 32,
|
||||
Op::Shr => 32,
|
||||
Op::Sar => 32,
|
||||
@@ -1260,6 +1272,8 @@ impl Op {
|
||||
Op::Cdq => false,
|
||||
Op::Rol => false,
|
||||
Op::Ror => false,
|
||||
Op::Rcl => false,
|
||||
Op::Rcr => false,
|
||||
Op::Shl => false,
|
||||
Op::Shr => false,
|
||||
Op::Sar => false,
|
||||
@@ -1464,6 +1478,8 @@ impl Op {
|
||||
Op::Cdq => false,
|
||||
Op::Rol => false,
|
||||
Op::Ror => false,
|
||||
Op::Rcl => false,
|
||||
Op::Rcr => false,
|
||||
Op::Shl => false,
|
||||
Op::Shr => false,
|
||||
Op::Sar => false,
|
||||
@@ -1668,6 +1684,8 @@ impl Op {
|
||||
Op::Cdq => false,
|
||||
Op::Rol => false,
|
||||
Op::Ror => false,
|
||||
Op::Rcl => false,
|
||||
Op::Rcr => false,
|
||||
Op::Shl => false,
|
||||
Op::Shr => false,
|
||||
Op::Sar => false,
|
||||
@@ -1844,7 +1862,7 @@ impl Op {
|
||||
}
|
||||
}
|
||||
|
||||
pub static FORMS: [Form; 369] = [
|
||||
pub static FORMS: [Form; 381] = [
|
||||
Form { op: Op::Movsxd, encoding: Encoding::RegRm, size: OperandSize::Wide, immediate: Immediate::None, source: 4, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Push, encoding: Encoding::OpReg, size: OperandSize::Quad, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Pop, encoding: Encoding::OpReg, size: OperandSize::Quad, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
@@ -2186,31 +2204,43 @@ pub static FORMS: [Form; 369] = [
|
||||
Form { op: Op::Dec, encoding: Encoding::Rm, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Rol, encoding: Encoding::RmImm, size: OperandSize::Byte, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Ror, encoding: Encoding::RmImm, size: OperandSize::Byte, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Rcl, encoding: Encoding::RmImm, size: OperandSize::Byte, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Rcr, encoding: Encoding::RmImm, size: OperandSize::Byte, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Shl, encoding: Encoding::RmImm, size: OperandSize::Byte, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Shr, encoding: Encoding::RmImm, size: OperandSize::Byte, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Sar, encoding: Encoding::RmImm, size: OperandSize::Byte, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Rol, encoding: Encoding::RmImm, size: OperandSize::Variable, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Ror, encoding: Encoding::RmImm, size: OperandSize::Variable, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Rcl, encoding: Encoding::RmImm, size: OperandSize::Variable, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Rcr, encoding: Encoding::RmImm, size: OperandSize::Variable, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Shl, encoding: Encoding::RmImm, size: OperandSize::Variable, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Shr, encoding: Encoding::RmImm, size: OperandSize::Variable, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Sar, encoding: Encoding::RmImm, size: OperandSize::Variable, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Rol, encoding: Encoding::RmOne, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Ror, encoding: Encoding::RmOne, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Rcl, encoding: Encoding::RmOne, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Rcr, encoding: Encoding::RmOne, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Shl, encoding: Encoding::RmOne, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Shr, encoding: Encoding::RmOne, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Sar, encoding: Encoding::RmOne, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Rol, encoding: Encoding::RmOne, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Ror, encoding: Encoding::RmOne, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Rcl, encoding: Encoding::RmOne, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Rcr, encoding: Encoding::RmOne, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Shl, encoding: Encoding::RmOne, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Shr, encoding: Encoding::RmOne, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Sar, encoding: Encoding::RmOne, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Rol, encoding: Encoding::RmCl, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Ror, encoding: Encoding::RmCl, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Rcl, encoding: Encoding::RmCl, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Rcr, encoding: Encoding::RmCl, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Shl, encoding: Encoding::RmCl, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Shr, encoding: Encoding::RmCl, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Sar, encoding: Encoding::RmCl, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Rol, encoding: Encoding::RmCl, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Ror, encoding: Encoding::RmCl, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Rcl, encoding: Encoding::RmCl, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Rcr, encoding: Encoding::RmCl, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Shl, encoding: Encoding::RmCl, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Shr, encoding: Encoding::RmCl, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Sar, encoding: Encoding::RmCl, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
@@ -2222,14 +2252,14 @@ pub static GROUPS: [[u16; 8]; 22] = [
|
||||
[254, 263, 272, 281, 290, 299, 308, 317],
|
||||
[255, 264, 273, 282, 291, 300, 309, 318],
|
||||
[6, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
[339, 340, 65535, 65535, 341, 342, 65535, 343],
|
||||
[344, 345, 65535, 65535, 346, 347, 65535, 348],
|
||||
[339, 340, 341, 342, 343, 344, 65535, 345],
|
||||
[346, 347, 348, 349, 350, 351, 65535, 352],
|
||||
[33, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
[34, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
[349, 350, 65535, 65535, 351, 352, 65535, 353],
|
||||
[354, 355, 65535, 65535, 356, 357, 65535, 358],
|
||||
[359, 360, 65535, 65535, 361, 362, 65535, 363],
|
||||
[364, 365, 65535, 65535, 366, 367, 65535, 368],
|
||||
[353, 354, 355, 356, 357, 358, 65535, 359],
|
||||
[360, 361, 362, 363, 364, 365, 65535, 366],
|
||||
[367, 368, 369, 370, 371, 372, 65535, 373],
|
||||
[374, 375, 376, 377, 378, 379, 65535, 380],
|
||||
[18, 65535, 323, 324, 325, 326, 327, 328],
|
||||
[19, 65535, 329, 330, 331, 332, 333, 334],
|
||||
[335, 336, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
|
||||
@@ -1307,6 +1307,18 @@ addr32_sum_wraps_at_32_bits: rbx=ffff0000 rcx=10000+D rax=0 m0=44332211 => rax=1
|
||||
486601d8
|
||||
SDM 2A 2.2.1
|
||||
rex_not_adjacent_to_opcode_is_ignored: rax=112233445566ffff rbx=1 => rax=1122334455660000 f=CPAZso
|
||||
@ .byte 0x41,0x66,0x01,0xd8
|
||||
416601d8
|
||||
SDM 2A 2.2.1
|
||||
ignored_rex_b_does_not_select_r8: rax=112233445566ffff rbx=1 r8=5 => rax=1122334455660000 f=CPAZso
|
||||
@ .byte 0x48,0x64,0x8b,0x03
|
||||
48648b03
|
||||
SDM 2A 2.2.1; 1 3.4.1.1
|
||||
ignored_rex_w_before_segment_prefix_loads_32_bits: rax=ffffffffffffffff rbx=8 fs8=1122334455667788 => rax=44332211 f=*
|
||||
@ .byte 0x41,0x66,0x41,0x01,0xd8
|
||||
41664101d8
|
||||
SDM 2A 2.2.1
|
||||
rex_after_ignored_rex_applies: rax=7 rbx=1 r8=112233445566ffff => r8=1122334455660000 f=CPAZso
|
||||
@ .byte 0x66,0x48,0x01,0xd8
|
||||
664801d8
|
||||
SDM 2A 2.2.1.2
|
||||
@@ -2720,22 +2732,9 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("ptest_flags", 0),
|
||||
("push16_moves_rsp_by_two", 0),
|
||||
("pushfq_popfq_status_round_trip", 0),
|
||||
("rcl16_by16", 0),
|
||||
("rcl16_by17_is_identity", 0),
|
||||
("rcl32_by31", 0),
|
||||
("rcl32_cl32_affects_nothing_but_extension", 0),
|
||||
("rcl64_by63", 0),
|
||||
("rcl8_by1_clear_carry_in", 0),
|
||||
("rcl8_by1_set_carry_in_preserves_szap", 0),
|
||||
("rcl8_by8", 0),
|
||||
("rcl8_by9_is_identity", 0),
|
||||
("rcpps_special_values", 0),
|
||||
("rcpss_relative_error_bound", 0),
|
||||
("rcpss_rsqrtss_signal_nothing", 0),
|
||||
("rcr64_by1", 0),
|
||||
("rcr8_by10_is_by_one_mod_9", 0),
|
||||
("rcr8_by1_clear_carry_in", 0),
|
||||
("rcr8_by1_set_carry_in", 0),
|
||||
("rep_lodsb_source_fault", 1),
|
||||
("rep_movsb_addr32_uses_32bit_registers", 1),
|
||||
("repe_cmpsb_fault_restores_flags", 1),
|
||||
@@ -2746,7 +2745,6 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("repne_scasb_finds_byte", 1),
|
||||
("repne_scasb_finds_byte_df_clear", 0),
|
||||
("repne_scasd_exhausts_count", 1),
|
||||
("rex_not_adjacent_to_opcode_is_ignored", 0),
|
||||
("roundps_uses_mxcsr_rc", 0),
|
||||
("roundsd_suppress_precision", 0),
|
||||
("roundss_imm_modes", 0),
|
||||
@@ -2757,7 +2755,6 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("shld32_by4", 0),
|
||||
("shld32_cl32_is_count_zero", 0),
|
||||
("shld64_by63", 0),
|
||||
("shr_rcr_128bit_right_shift", 1),
|
||||
("shrd32_by8", 0),
|
||||
("shrd64_by1_sign_change", 0),
|
||||
("shrd64_cl64_is_count_zero", 0),
|
||||
@@ -4044,11 +4041,7 @@ fn shift_and_rotate_sweep_matches_operation_pseudocode() {
|
||||
runs += bench.runs;
|
||||
}
|
||||
}
|
||||
let wanted: Vec<String> = ["rcl", "rcr"]
|
||||
.iter()
|
||||
.flat_map(|op| WIDTHS.map(|bits| format!("{op}{bits}")))
|
||||
.collect();
|
||||
assert_eq!(refused, wanted, "unsupported shift forms changed");
|
||||
assert_eq!(refused, Vec::<String>::new(), "a shift form is refused");
|
||||
println!("{runs} engine runs");
|
||||
}
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ def cases():
|
||||
for bits in (8, 16, 32, 64):
|
||||
out += [f"{op} {reg(1, bits)}", f"{op} {reg(9, bits)}", f"{op} {mem(bits)}"]
|
||||
out.append(f"{op} ch")
|
||||
for op in "rol ror shl shr sar".split():
|
||||
for op in "rol ror rcl rcr shl shr sar".split():
|
||||
for bits in (8, 16, 32, 64):
|
||||
for count in ("1", "3", "7", "cl"):
|
||||
out += [f"{op} {reg(3, bits)}, {count}", f"{op} {mem(bits)}, {count}"]
|
||||
|
||||
@@ -547,6 +547,86 @@ d3 4c be 10 | ror dword ptr [rsi + 4*rdi + 16], cl
|
||||
48 d3 4c be 10 | ror qword ptr [rsi + 4*rdi + 16], cl
|
||||
49 c1 cd 3f | ror r13, 63
|
||||
49 c1 cd 00 | ror r13, 0
|
||||
d0 d3 | rcl bl, 1
|
||||
d0 54 be 10 | rcl byte ptr [rsi + 4*rdi + 16], 1
|
||||
c0 d3 03 | rcl bl, 3
|
||||
c0 54 be 10 03 | rcl byte ptr [rsi + 4*rdi + 16], 3
|
||||
c0 d3 07 | rcl bl, 7
|
||||
c0 54 be 10 07 | rcl byte ptr [rsi + 4*rdi + 16], 7
|
||||
d2 d3 | rcl bl, cl
|
||||
d2 54 be 10 | rcl byte ptr [rsi + 4*rdi + 16], cl
|
||||
41 c0 d5 07 | rcl r13b, 7
|
||||
41 c0 d5 00 | rcl r13b, 0
|
||||
66 d1 d3 | rcl bx, 1
|
||||
66 d1 54 be 10 | rcl word ptr [rsi + 4*rdi + 16], 1
|
||||
66 c1 d3 03 | rcl bx, 3
|
||||
66 c1 54 be 10 03 | rcl word ptr [rsi + 4*rdi + 16], 3
|
||||
66 c1 d3 07 | rcl bx, 7
|
||||
66 c1 54 be 10 07 | rcl word ptr [rsi + 4*rdi + 16], 7
|
||||
66 d3 d3 | rcl bx, cl
|
||||
66 d3 54 be 10 | rcl word ptr [rsi + 4*rdi + 16], cl
|
||||
66 41 c1 d5 0f | rcl r13w, 15
|
||||
66 41 c1 d5 00 | rcl r13w, 0
|
||||
d1 d3 | rcl ebx, 1
|
||||
d1 54 be 10 | rcl dword ptr [rsi + 4*rdi + 16], 1
|
||||
c1 d3 03 | rcl ebx, 3
|
||||
c1 54 be 10 03 | rcl dword ptr [rsi + 4*rdi + 16], 3
|
||||
c1 d3 07 | rcl ebx, 7
|
||||
c1 54 be 10 07 | rcl dword ptr [rsi + 4*rdi + 16], 7
|
||||
d3 d3 | rcl ebx, cl
|
||||
d3 54 be 10 | rcl dword ptr [rsi + 4*rdi + 16], cl
|
||||
41 c1 d5 1f | rcl r13d, 31
|
||||
41 c1 d5 00 | rcl r13d, 0
|
||||
48 d1 d3 | rcl rbx, 1
|
||||
48 d1 54 be 10 | rcl qword ptr [rsi + 4*rdi + 16], 1
|
||||
48 c1 d3 03 | rcl rbx, 3
|
||||
48 c1 54 be 10 03 | rcl qword ptr [rsi + 4*rdi + 16], 3
|
||||
48 c1 d3 07 | rcl rbx, 7
|
||||
48 c1 54 be 10 07 | rcl qword ptr [rsi + 4*rdi + 16], 7
|
||||
48 d3 d3 | rcl rbx, cl
|
||||
48 d3 54 be 10 | rcl qword ptr [rsi + 4*rdi + 16], cl
|
||||
49 c1 d5 3f | rcl r13, 63
|
||||
49 c1 d5 00 | rcl r13, 0
|
||||
d0 db | rcr bl, 1
|
||||
d0 5c be 10 | rcr byte ptr [rsi + 4*rdi + 16], 1
|
||||
c0 db 03 | rcr bl, 3
|
||||
c0 5c be 10 03 | rcr byte ptr [rsi + 4*rdi + 16], 3
|
||||
c0 db 07 | rcr bl, 7
|
||||
c0 5c be 10 07 | rcr byte ptr [rsi + 4*rdi + 16], 7
|
||||
d2 db | rcr bl, cl
|
||||
d2 5c be 10 | rcr byte ptr [rsi + 4*rdi + 16], cl
|
||||
41 c0 dd 07 | rcr r13b, 7
|
||||
41 c0 dd 00 | rcr r13b, 0
|
||||
66 d1 db | rcr bx, 1
|
||||
66 d1 5c be 10 | rcr word ptr [rsi + 4*rdi + 16], 1
|
||||
66 c1 db 03 | rcr bx, 3
|
||||
66 c1 5c be 10 03 | rcr word ptr [rsi + 4*rdi + 16], 3
|
||||
66 c1 db 07 | rcr bx, 7
|
||||
66 c1 5c be 10 07 | rcr word ptr [rsi + 4*rdi + 16], 7
|
||||
66 d3 db | rcr bx, cl
|
||||
66 d3 5c be 10 | rcr word ptr [rsi + 4*rdi + 16], cl
|
||||
66 41 c1 dd 0f | rcr r13w, 15
|
||||
66 41 c1 dd 00 | rcr r13w, 0
|
||||
d1 db | rcr ebx, 1
|
||||
d1 5c be 10 | rcr dword ptr [rsi + 4*rdi + 16], 1
|
||||
c1 db 03 | rcr ebx, 3
|
||||
c1 5c be 10 03 | rcr dword ptr [rsi + 4*rdi + 16], 3
|
||||
c1 db 07 | rcr ebx, 7
|
||||
c1 5c be 10 07 | rcr dword ptr [rsi + 4*rdi + 16], 7
|
||||
d3 db | rcr ebx, cl
|
||||
d3 5c be 10 | rcr dword ptr [rsi + 4*rdi + 16], cl
|
||||
41 c1 dd 1f | rcr r13d, 31
|
||||
41 c1 dd 00 | rcr r13d, 0
|
||||
48 d1 db | rcr rbx, 1
|
||||
48 d1 5c be 10 | rcr qword ptr [rsi + 4*rdi + 16], 1
|
||||
48 c1 db 03 | rcr rbx, 3
|
||||
48 c1 5c be 10 03 | rcr qword ptr [rsi + 4*rdi + 16], 3
|
||||
48 c1 db 07 | rcr rbx, 7
|
||||
48 c1 5c be 10 07 | rcr qword ptr [rsi + 4*rdi + 16], 7
|
||||
48 d3 db | rcr rbx, cl
|
||||
48 d3 5c be 10 | rcr qword ptr [rsi + 4*rdi + 16], cl
|
||||
49 c1 dd 3f | rcr r13, 63
|
||||
49 c1 dd 00 | rcr r13, 0
|
||||
d0 e3 | shl bl, 1
|
||||
d0 64 be 10 | shl byte ptr [rsi + 4*rdi + 16], 1
|
||||
c0 e3 03 | shl bl, 3
|
||||
|
||||
@@ -397,7 +397,7 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
write(m, places[0], (1u128 << bits) - 1 - a);
|
||||
Outcome::Done(none)
|
||||
}
|
||||
"shl" | "shr" | "sar" | "rol" | "ror" => {
|
||||
"shl" | "shr" | "sar" | "rol" | "ror" | "rcl" | "rcr" => {
|
||||
let count = match rest.split(", ").nth(1) {
|
||||
Some("cl") => u32::from(m.gpr[1] as u8),
|
||||
_ => read(m, places[1], 8) as u32,
|
||||
@@ -405,13 +405,22 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
let start = read(m, places[0], bits);
|
||||
let mut value = start;
|
||||
let top = 1u128 << (bits - 1);
|
||||
let mut carry = m.flags.cf;
|
||||
for _ in 0..count {
|
||||
let carry_in = m.flags.cf;
|
||||
let mut carry = carry_in;
|
||||
// RCL and RCR rotate through CF, so `bits + 1` steps come round again.
|
||||
let steps = if matches!(name, "rcl" | "rcr") {
|
||||
count % (bits + 1)
|
||||
} else {
|
||||
count
|
||||
};
|
||||
for _ in 0..steps {
|
||||
// One step at a time, as the SDM loop does.
|
||||
let (high, low) = (bit(value, bits - 1), bit(value, 0));
|
||||
(value, carry) = match name {
|
||||
"shl" => (truncate(value * 2, bits), high),
|
||||
"rol" => (truncate(value * 2, bits) + u128::from(high), high),
|
||||
"rcl" => (truncate(value * 2, bits) + u128::from(carry), high),
|
||||
"rcr" => (value / 2 + if carry { top } else { 0 }, low),
|
||||
"shr" => (value / 2, low),
|
||||
"sar" => (value / 2 + if high { top } else { 0 }, low),
|
||||
_ => (value / 2 + if low { top } else { 0 }, low),
|
||||
@@ -424,7 +433,8 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
let (msb, next) = (bit(value, bits - 1), bit(value, bits - 2));
|
||||
if count == 1 {
|
||||
m.flags.of = match name {
|
||||
"shl" | "rol" => msb != carry,
|
||||
"shl" | "rol" | "rcl" => msb != carry,
|
||||
"rcr" => bit(start, bits - 1) != carry_in,
|
||||
"shr" => bit(start, bits - 1),
|
||||
"sar" => false,
|
||||
_ => msb != next,
|
||||
@@ -1225,7 +1235,6 @@ fn undeclared_and_ambiguous_encodings_are_rejected() {
|
||||
&[0x41, 0x90], // xchg r8, rax
|
||||
&[0x8D, 0xC0], // lea with a register operand
|
||||
&[0x0F, 0xA3, 0x06], // bt [rsi], eax
|
||||
&[0xC0, 0xD0, 0x01], // rcl al, 1
|
||||
&[0xC6, 0xC8, 0x01], // C6 /1
|
||||
&[0xFF, 0xF8], // FF /7
|
||||
&[0xFE, 0xD0], // FE /2
|
||||
|
||||
@@ -61,6 +61,8 @@ cwde = { ref = "sdm CBW/CWDE/CDQE" }
|
||||
cdq = { ref = "sdm CWD/CDQ/CQO" }
|
||||
rol = { writes = "cf of", conditional = true, ref = "sdm RCL/RCR/ROL/ROR" }
|
||||
ror = { writes = "cf of", conditional = true, ref = "sdm RCL/RCR/ROL/ROR" }
|
||||
rcl = { reads = "cf", writes = "cf of", conditional = true, ref = "sdm RCL/RCR/ROL/ROR" }
|
||||
rcr = { reads = "cf", writes = "cf of", conditional = true, ref = "sdm RCL/RCR/ROL/ROR" }
|
||||
shl = { writes = "cf zf sf of pf", undefined = "af", conditional = true, ref = "sdm SAL/SAR/SHL/SHR" }
|
||||
shr = { writes = "cf zf sf of pf", undefined = "af", conditional = true, ref = "sdm SAL/SAR/SHL/SHR" }
|
||||
sar = { writes = "cf zf sf of pf", undefined = "af", conditional = true, ref = "sdm SAL/SAR/SHL/SHR" }
|
||||
@@ -779,7 +781,7 @@ digits = { 0 = "inc", 1 = "dec" }
|
||||
|
||||
[[group]]
|
||||
opcodes = [[0xC0, "b", "ib", "rm_imm"], [0xC1, "v", "ib", "rm_imm"], [0xD0, "b", "", "rm_one"], [0xD1, "v", "", "rm_one"], [0xD2, "b", "", "rm_cl"], [0xD3, "v", "", "rm_cl"]]
|
||||
digits = { 0 = "rol", 1 = "ror", 4 = "shl", 5 = "shr", 7 = "sar" }
|
||||
digits = { 0 = "rol", 1 = "ror", 2 = "rcl", 3 = "rcr", 4 = "shl", 5 = "shr", 7 = "sar" }
|
||||
|
||||
# SSE and SSE2 moves and packed integer forms.
|
||||
|
||||
|
||||
@@ -33,7 +33,6 @@ objc2-metal = { version = "=0.3.2", default-features = false, features = [
|
||||
"std",
|
||||
"MTLAllocation",
|
||||
"MTLArgument",
|
||||
"MTLBlitCommandEncoder",
|
||||
"MTLBuffer",
|
||||
"MTLCommandBuffer",
|
||||
"MTLCommandEncoder",
|
||||
|
||||
@@ -11,9 +11,8 @@ use std::ptr::NonNull;
|
||||
use objc2::rc::{Retained, autoreleasepool};
|
||||
use objc2::runtime::ProtocolObject;
|
||||
use objc2_metal::{
|
||||
MTLBlitCommandEncoder, MTLBuffer, MTLCommandBuffer, MTLCommandBufferStatus, MTLCommandEncoder,
|
||||
MTLCommandQueue, MTLDevice, MTLOrigin, MTLPixelFormat, MTLRegion, MTLResourceOptions, MTLSize,
|
||||
MTLStorageMode, MTLTexture, MTLTextureDescriptor, MTLTextureUsage,
|
||||
MTLDevice, MTLOrigin, MTLPixelFormat, MTLRegion, MTLResourceOptions, MTLSize, MTLStorageMode,
|
||||
MTLTexture, MTLTextureDescriptor, MTLTextureUsage,
|
||||
};
|
||||
use xenora_texture::{SamplerError, TextureMetadata};
|
||||
|
||||
@@ -101,9 +100,6 @@ impl Rgba8TextureDesc {
|
||||
pub struct MetalRgba8Texture {
|
||||
texture: Retained<ProtocolObject<dyn MTLTexture>>,
|
||||
desc: Rgba8TextureDesc,
|
||||
/// Shared storage, which `replaceRegion` may write. Private textures are
|
||||
/// filled only through `upload_staged`.
|
||||
cpu_writable: bool,
|
||||
}
|
||||
|
||||
impl MetalRgba8Texture {
|
||||
@@ -112,19 +108,6 @@ impl MetalRgba8Texture {
|
||||
device: &ProtocolObject<dyn MTLDevice>,
|
||||
desc: Rgba8TextureDesc,
|
||||
) -> Result<Self, MetalError> {
|
||||
Self::allocate_with_storage(device, desc, MTLStorageMode::Shared)
|
||||
}
|
||||
|
||||
fn allocate_with_storage(
|
||||
device: &ProtocolObject<dyn MTLDevice>,
|
||||
desc: Rgba8TextureDesc,
|
||||
storage: MTLStorageMode,
|
||||
) -> Result<Self, MetalError> {
|
||||
let options = if storage == MTLStorageMode::Private {
|
||||
MTLResourceOptions::StorageModePrivate
|
||||
} else {
|
||||
MTLResourceOptions::StorageModeShared
|
||||
};
|
||||
autoreleasepool(|_| {
|
||||
// SAFETY: Validated non-zero dimensions within MAX_TEXTURE_PIXELS and RGBA8Unorm format.
|
||||
let descriptor = unsafe {
|
||||
@@ -141,8 +124,8 @@ impl MetalRgba8Texture {
|
||||
descriptor.setMipmapLevelCount(desc.mips as usize);
|
||||
}
|
||||
}
|
||||
descriptor.setStorageMode(storage);
|
||||
descriptor.setResourceOptions(options);
|
||||
descriptor.setStorageMode(MTLStorageMode::Shared);
|
||||
descriptor.setResourceOptions(MTLResourceOptions::StorageModeShared);
|
||||
descriptor.setUsage(MTLTextureUsage::ShaderRead);
|
||||
|
||||
let texture = device
|
||||
@@ -154,25 +137,51 @@ impl MetalRgba8Texture {
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(Self {
|
||||
texture,
|
||||
desc,
|
||||
cpu_writable: storage == MTLStorageMode::Shared,
|
||||
})
|
||||
Ok(Self { texture, desc })
|
||||
})
|
||||
}
|
||||
|
||||
/// Upload a single validated mip level into this texture.
|
||||
///
|
||||
/// Only Shared-storage textures from `allocate` or `upload` accept CPU writes.
|
||||
pub fn upload_mip(&self, mip: &Rgba8MipLevel<'_>) -> Result<(), MetalError> {
|
||||
if !self.cpu_writable {
|
||||
let (expected_w, expected_h) = self.desc.mip_extent(mip.level)?;
|
||||
if mip.width != expected_w || mip.height != expected_h {
|
||||
return Err(MetalError::new(
|
||||
"texture storage",
|
||||
"a Private-storage texture is filled only by upload_staged",
|
||||
"mip dimensions",
|
||||
format!(
|
||||
"mip level {} expected {}x{}, got {}x{}",
|
||||
mip.level, expected_w, expected_h, mip.width, mip.height
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let tight_pitch = mip
|
||||
.width
|
||||
.checked_mul(RGBA8_TEXEL_BYTES)
|
||||
.ok_or_else(|| MetalError::new("row pitch", "row pitch overflow"))?;
|
||||
if mip.row_pitch < tight_pitch {
|
||||
return Err(MetalError::new(
|
||||
"row pitch",
|
||||
format!(
|
||||
"row pitch {} smaller than tight pitch {}",
|
||||
mip.row_pitch, tight_pitch
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let min_bytes = mip
|
||||
.row_pitch
|
||||
.checked_mul(mip.height)
|
||||
.ok_or_else(|| MetalError::new("mip bytes", "byte length calculation overflow"))?;
|
||||
if mip.bytes.len() < min_bytes {
|
||||
return Err(MetalError::new(
|
||||
"mip buffer bounds",
|
||||
format!(
|
||||
"buffer length {} is less than required {}",
|
||||
mip.bytes.len(),
|
||||
min_bytes
|
||||
),
|
||||
));
|
||||
}
|
||||
validate_mip(&self.desc, mip)?;
|
||||
|
||||
autoreleasepool(|_| {
|
||||
let region = MTLRegion {
|
||||
@@ -218,148 +227,6 @@ impl MetalRgba8Texture {
|
||||
Ok(texture)
|
||||
}
|
||||
|
||||
/// Allocate a Private-storage RGBA8 texture and fill every mip level through
|
||||
/// a reused Shared staging buffer that never exceeds `budget`.
|
||||
///
|
||||
/// The plan from [`plan_staged_upload`] is built, and every input checked,
|
||||
/// before any Metal object is created. Each submission copies its rows into
|
||||
/// the staging buffer, blits them into the texture and waits until the
|
||||
/// command buffer has completed. Only a `Completed` status lets the buffer be
|
||||
/// reused; any other status is returned as an error.
|
||||
pub fn upload_staged(
|
||||
device: &ProtocolObject<dyn MTLDevice>,
|
||||
queue: &ProtocolObject<dyn MTLCommandQueue>,
|
||||
desc: Rgba8TextureDesc,
|
||||
mips: &[Rgba8MipLevel<'_>],
|
||||
budget: StagingBudget,
|
||||
) -> Result<(Self, StagedUploadReport), MetalError> {
|
||||
let plan = plan_staged_upload(&desc, mips, budget)?;
|
||||
let staging_len = plan.iter().map(|s| s.staging_bytes).max().unwrap_or(0);
|
||||
let texture = Self::allocate_with_storage(device, desc, MTLStorageMode::Private)?;
|
||||
let staging = device
|
||||
.newBufferWithLength_options(staging_len, MTLResourceOptions::StorageModeShared)
|
||||
.ok_or_else(|| MetalError::new("newBufferWithLength", "staging allocation failed"))?;
|
||||
let mut copied = 0;
|
||||
for submission in &plan {
|
||||
for copy in &submission.copies {
|
||||
let mip = mips
|
||||
.iter()
|
||||
.find(|mip| mip.level == copy.level)
|
||||
.ok_or_else(|| MetalError::new("staged upload", "planned level missing"))?;
|
||||
let tight = mip.width * RGBA8_TEXEL_BYTES;
|
||||
for row in 0..copy.rows {
|
||||
let src = &mip.bytes[(copy.first_row + row) * mip.row_pitch..][..tight];
|
||||
let offset = copy.staging_offset + row * tight;
|
||||
// SAFETY: The plan keeps offset + tight within staging_len, the
|
||||
// buffer is Shared and CPU-visible, and the previous submission
|
||||
// has completed, so the GPU no longer reads these bytes.
|
||||
unsafe {
|
||||
let dst = staging.contents().cast::<u8>().as_ptr().add(offset);
|
||||
std::ptr::copy_nonoverlapping(src.as_ptr(), dst, tight);
|
||||
}
|
||||
}
|
||||
copied += copy.rows * tight;
|
||||
}
|
||||
autoreleasepool(|_| texture.encode_staged(queue, &staging, submission))?;
|
||||
}
|
||||
let report = StagedUploadReport {
|
||||
submissions: plan.len(),
|
||||
peak_staging_bytes: staging_len,
|
||||
bytes_copied: copied,
|
||||
};
|
||||
Ok((texture, report))
|
||||
}
|
||||
|
||||
fn encode_staged(
|
||||
&self,
|
||||
queue: &ProtocolObject<dyn MTLCommandQueue>,
|
||||
staging: &ProtocolObject<dyn MTLBuffer>,
|
||||
submission: &StagedSubmission,
|
||||
) -> Result<(), MetalError> {
|
||||
let command = queue
|
||||
.commandBuffer()
|
||||
.ok_or_else(|| MetalError::new("commandBuffer", "command buffer creation failed"))?;
|
||||
let blit = command
|
||||
.blitCommandEncoder()
|
||||
.ok_or_else(|| MetalError::new("blitCommandEncoder", "blit encoder creation failed"))?;
|
||||
for copy in &submission.copies {
|
||||
let (width, _) = self.desc.mip_extent(copy.level)?;
|
||||
let pitch = width * RGBA8_TEXEL_BYTES;
|
||||
// SAFETY: The plan validated the level, the row range within the mip and
|
||||
// the staging range within the buffer. The command buffer retains both
|
||||
// resources, and the caller waits for completion before reusing staging.
|
||||
unsafe {
|
||||
blit.copyFromBuffer_sourceOffset_sourceBytesPerRow_sourceBytesPerImage_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin(
|
||||
staging,
|
||||
copy.staging_offset,
|
||||
pitch,
|
||||
pitch * copy.rows,
|
||||
MTLSize { width, height: copy.rows, depth: 1 },
|
||||
&self.texture,
|
||||
0,
|
||||
copy.level as usize,
|
||||
MTLOrigin { x: 0, y: copy.first_row, z: 0 },
|
||||
);
|
||||
}
|
||||
}
|
||||
blit.endEncoding();
|
||||
command.commit();
|
||||
command.waitUntilCompleted();
|
||||
check_completed(&command)
|
||||
}
|
||||
|
||||
/// Copy one mip level back into tightly packed RGBA8 bytes through a blit.
|
||||
///
|
||||
/// Works for Shared and Private textures and shares no code with the upload
|
||||
/// paths, so tests can compare its output with independently built pixels.
|
||||
pub fn read_back(
|
||||
&self,
|
||||
device: &ProtocolObject<dyn MTLDevice>,
|
||||
queue: &ProtocolObject<dyn MTLCommandQueue>,
|
||||
level: u32,
|
||||
) -> Result<Vec<u8>, MetalError> {
|
||||
let (width, height) = self.desc.mip_extent(level)?;
|
||||
let pitch = width * RGBA8_TEXEL_BYTES;
|
||||
let len = pitch * height;
|
||||
autoreleasepool(|_| {
|
||||
let buffer = device
|
||||
.newBufferWithLength_options(len, MTLResourceOptions::StorageModeShared)
|
||||
.ok_or_else(|| {
|
||||
MetalError::new("newBufferWithLength", "readback allocation failed")
|
||||
})?;
|
||||
let command = queue.commandBuffer().ok_or_else(|| {
|
||||
MetalError::new("commandBuffer", "command buffer creation failed")
|
||||
})?;
|
||||
let blit = command.blitCommandEncoder().ok_or_else(|| {
|
||||
MetalError::new("blitCommandEncoder", "blit encoder creation failed")
|
||||
})?;
|
||||
// SAFETY: The level is in range, the source region is the whole mip and
|
||||
// the destination buffer holds exactly pitch * height bytes.
|
||||
unsafe {
|
||||
blit.copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toBuffer_destinationOffset_destinationBytesPerRow_destinationBytesPerImage(
|
||||
&self.texture,
|
||||
0,
|
||||
level as usize,
|
||||
MTLOrigin { x: 0, y: 0, z: 0 },
|
||||
MTLSize { width, height, depth: 1 },
|
||||
&buffer,
|
||||
0,
|
||||
pitch,
|
||||
len,
|
||||
);
|
||||
}
|
||||
blit.endEncoding();
|
||||
command.commit();
|
||||
command.waitUntilCompleted();
|
||||
check_completed(&command)?;
|
||||
// SAFETY: The command buffer completed, so the Shared buffer holds len
|
||||
// initialized bytes and the GPU no longer writes it.
|
||||
let bytes =
|
||||
unsafe { std::slice::from_raw_parts(buffer.contents().cast::<u8>().as_ptr(), len) };
|
||||
Ok(bytes.to_vec())
|
||||
})
|
||||
}
|
||||
|
||||
/// Access the underlying native Metal texture protocol object.
|
||||
#[inline]
|
||||
pub fn raw(&self) -> &ProtocolObject<dyn MTLTexture> {
|
||||
@@ -373,198 +240,6 @@ impl MetalRgba8Texture {
|
||||
}
|
||||
}
|
||||
|
||||
/// Upper bound on the staging bytes one staged upload holds at a time.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StagingBudget {
|
||||
max_bytes: usize,
|
||||
}
|
||||
|
||||
impl StagingBudget {
|
||||
/// A budget of `max_bytes`, which must be a non-zero multiple of the RGBA8
|
||||
/// texel size so every staged row starts on a texel boundary.
|
||||
pub fn new(max_bytes: usize) -> Result<Self, MetalError> {
|
||||
if max_bytes == 0 || !max_bytes.is_multiple_of(RGBA8_TEXEL_BYTES) {
|
||||
return Err(MetalError::new(
|
||||
"staging budget",
|
||||
format!("budget {max_bytes} must be a non-zero multiple of {RGBA8_TEXEL_BYTES}"),
|
||||
));
|
||||
}
|
||||
Ok(Self { max_bytes })
|
||||
}
|
||||
|
||||
/// The largest staging allocation this budget allows.
|
||||
#[must_use]
|
||||
pub fn max_bytes(&self) -> usize {
|
||||
self.max_bytes
|
||||
}
|
||||
}
|
||||
|
||||
/// One blit of whole rows of one mip level from the staging buffer.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StagedCopy {
|
||||
pub level: u32,
|
||||
pub first_row: usize,
|
||||
pub rows: usize,
|
||||
/// Byte offset of the first row in the staging buffer. Rows are packed tightly.
|
||||
pub staging_offset: usize,
|
||||
}
|
||||
|
||||
/// The copies that share one staging fill and one command buffer.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct StagedSubmission {
|
||||
pub copies: Vec<StagedCopy>,
|
||||
/// Staging bytes this submission uses, never more than the budget.
|
||||
pub staging_bytes: usize,
|
||||
}
|
||||
|
||||
/// What a staged upload did, measured from the executed plan.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StagedUploadReport {
|
||||
/// Command buffers committed and completed.
|
||||
pub submissions: usize,
|
||||
/// Size of the one staging buffer, the most staging memory held at once.
|
||||
pub peak_staging_bytes: usize,
|
||||
/// Texel bytes copied into the texture.
|
||||
pub bytes_copied: usize,
|
||||
}
|
||||
|
||||
/// Split a full RGBA8 upload into budget-sized submissions of whole rows.
|
||||
///
|
||||
/// Every level `0..desc.mips` must appear exactly once, because a Private
|
||||
/// texture has no defined contents for a level nobody writes. Each mip is
|
||||
/// checked like [`MetalRgba8Texture::upload_mip`] checks it. The budget must hold
|
||||
/// at least one row of the widest level. Rows are packed in level order, and a
|
||||
/// submission closes when the next row would exceed the budget.
|
||||
pub fn plan_staged_upload(
|
||||
desc: &Rgba8TextureDesc,
|
||||
mips: &[Rgba8MipLevel<'_>],
|
||||
budget: StagingBudget,
|
||||
) -> Result<Vec<StagedSubmission>, MetalError> {
|
||||
let mut by_level: Vec<Option<&Rgba8MipLevel<'_>>> = vec![None; desc.mips as usize];
|
||||
for mip in mips {
|
||||
validate_mip(desc, mip)?;
|
||||
let slot = &mut by_level[mip.level as usize];
|
||||
if slot.is_some() {
|
||||
return Err(MetalError::new(
|
||||
"staged upload",
|
||||
format!("mip level {} appears more than once", mip.level),
|
||||
));
|
||||
}
|
||||
*slot = Some(mip);
|
||||
}
|
||||
let mut plan = Vec::new();
|
||||
let mut current = StagedSubmission {
|
||||
copies: Vec::new(),
|
||||
staging_bytes: 0,
|
||||
};
|
||||
for (level, mip) in by_level.iter().enumerate() {
|
||||
let mip = mip.ok_or_else(|| {
|
||||
MetalError::new("staged upload", format!("mip level {level} is missing"))
|
||||
})?;
|
||||
let pitch = mip.width * RGBA8_TEXEL_BYTES;
|
||||
if pitch > budget.max_bytes {
|
||||
return Err(MetalError::new(
|
||||
"staging budget",
|
||||
format!(
|
||||
"budget {} is smaller than one {pitch}-byte row of mip level {level}",
|
||||
budget.max_bytes
|
||||
),
|
||||
));
|
||||
}
|
||||
let mut row = 0;
|
||||
while row < mip.height {
|
||||
let fit = (budget.max_bytes - current.staging_bytes) / pitch;
|
||||
if fit == 0 {
|
||||
// Unreachable after the row check above, but an empty submission
|
||||
// that cannot take one row must never loop.
|
||||
if current.copies.is_empty() {
|
||||
return Err(MetalError::new(
|
||||
"staging budget",
|
||||
"a row does not fit an empty staging buffer",
|
||||
));
|
||||
}
|
||||
plan.push(std::mem::replace(
|
||||
&mut current,
|
||||
StagedSubmission {
|
||||
copies: Vec::new(),
|
||||
staging_bytes: 0,
|
||||
},
|
||||
));
|
||||
continue;
|
||||
}
|
||||
let rows = fit.min(mip.height - row);
|
||||
current.copies.push(StagedCopy {
|
||||
level: mip.level,
|
||||
first_row: row,
|
||||
rows,
|
||||
staging_offset: current.staging_bytes,
|
||||
});
|
||||
current.staging_bytes += rows * pitch;
|
||||
row += rows;
|
||||
}
|
||||
}
|
||||
if !current.copies.is_empty() {
|
||||
plan.push(current);
|
||||
}
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
fn check_completed(command: &ProtocolObject<dyn MTLCommandBuffer>) -> Result<(), MetalError> {
|
||||
let status = command.status();
|
||||
if status != MTLCommandBufferStatus::Completed {
|
||||
let detail = command.error().map_or_else(
|
||||
|| format!("unexpected command status {status:?}"),
|
||||
|error| error.localizedDescription().to_string(),
|
||||
);
|
||||
return Err(MetalError::new("waitUntilCompleted", detail));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check one mip level against the texture description and return its tight row pitch.
|
||||
fn validate_mip(desc: &Rgba8TextureDesc, mip: &Rgba8MipLevel<'_>) -> Result<usize, MetalError> {
|
||||
let (expected_w, expected_h) = desc.mip_extent(mip.level)?;
|
||||
if mip.width != expected_w || mip.height != expected_h {
|
||||
return Err(MetalError::new(
|
||||
"mip dimensions",
|
||||
format!(
|
||||
"mip level {} expected {}x{}, got {}x{}",
|
||||
mip.level, expected_w, expected_h, mip.width, mip.height
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let tight_pitch = mip
|
||||
.width
|
||||
.checked_mul(RGBA8_TEXEL_BYTES)
|
||||
.ok_or_else(|| MetalError::new("row pitch", "row pitch overflow"))?;
|
||||
if mip.row_pitch < tight_pitch {
|
||||
return Err(MetalError::new(
|
||||
"row pitch",
|
||||
format!(
|
||||
"row pitch {} smaller than tight pitch {}",
|
||||
mip.row_pitch, tight_pitch
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let min_bytes = mip
|
||||
.row_pitch
|
||||
.checked_mul(mip.height)
|
||||
.ok_or_else(|| MetalError::new("mip bytes", "byte length calculation overflow"))?;
|
||||
if mip.bytes.len() < min_bytes {
|
||||
return Err(MetalError::new(
|
||||
"mip buffer bounds",
|
||||
format!(
|
||||
"buffer length {} is less than required {}",
|
||||
mip.bytes.len(),
|
||||
min_bytes
|
||||
),
|
||||
));
|
||||
}
|
||||
Ok(tight_pitch)
|
||||
}
|
||||
|
||||
/// Resource binding indices and lifetime conventions for sampling pipelines.
|
||||
///
|
||||
/// In the Xenora fixture ABI and translated shader conventions:
|
||||
@@ -653,150 +328,3 @@ impl BoundSampledTexture {
|
||||
self.sampler_slot
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn copy(level: u32, first_row: usize, rows: usize, staging_offset: usize) -> StagedCopy {
|
||||
StagedCopy {
|
||||
level,
|
||||
first_row,
|
||||
rows,
|
||||
staging_offset,
|
||||
}
|
||||
}
|
||||
|
||||
fn levels<'a>(desc: &Rgba8TextureDesc, bytes: &'a [u8]) -> Vec<Rgba8MipLevel<'a>> {
|
||||
(0..desc.mips)
|
||||
.map(|level| {
|
||||
let (w, h) = desc.mip_extent(level).unwrap();
|
||||
Rgba8MipLevel::new_packed(level, w, h, &bytes[..w * h * RGBA8_TEXEL_BYTES])
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn plan(desc: Rgba8TextureDesc, budget: usize) -> Vec<StagedSubmission> {
|
||||
let bytes = vec![0; desc.width * desc.height * RGBA8_TEXEL_BYTES];
|
||||
plan_staged_upload(
|
||||
&desc,
|
||||
&levels(&desc, &bytes),
|
||||
StagingBudget::new(budget).unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn error(desc: Rgba8TextureDesc, mips: &[Rgba8MipLevel<'_>], budget: usize) -> String {
|
||||
plan_staged_upload(&desc, mips, StagingBudget::new(budget).unwrap())
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn budget_must_be_a_non_zero_texel_multiple() {
|
||||
assert!(StagingBudget::new(0).is_err());
|
||||
assert!(StagingBudget::new(6).is_err());
|
||||
assert_eq!(StagingBudget::new(8).unwrap().max_bytes(), 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_split_into_budget_sized_submissions() {
|
||||
// 8 texels × 4 bytes = 32 bytes per row; a 64-byte budget holds two rows.
|
||||
let desc = Rgba8TextureDesc::new(8, 4, 1).unwrap();
|
||||
let plan = plan(desc, 64);
|
||||
assert_eq!(plan.len(), 2);
|
||||
assert_eq!(plan[0].copies, [copy(0, 0, 2, 0)]);
|
||||
assert_eq!(plan[1].copies, [copy(0, 2, 2, 0)]);
|
||||
assert!(plan.iter().all(|s| s.staging_bytes == 64));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_submission_packs_every_level_when_it_fits() {
|
||||
// Levels 8×4, 4×2, 2×1: 128 + 32 + 8 = 168 bytes.
|
||||
let desc = Rgba8TextureDesc::new(8, 4, 3).unwrap();
|
||||
let plan = plan(desc, 168);
|
||||
assert_eq!(plan.len(), 1);
|
||||
assert_eq!(
|
||||
plan[0].copies,
|
||||
[copy(0, 0, 4, 0), copy(1, 0, 2, 128), copy(2, 0, 1, 160)]
|
||||
);
|
||||
assert_eq!(plan[0].staging_bytes, 168);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_submission_closes_when_the_next_row_does_not_fit() {
|
||||
// A 40-byte budget holds one 32-byte row of level 0, then two 16-byte rows of
|
||||
// level 1 and the single 8-byte row of level 2 together.
|
||||
let desc = Rgba8TextureDesc::new(8, 4, 3).unwrap();
|
||||
let plan = plan(desc, 40);
|
||||
assert_eq!(plan.len(), 5);
|
||||
for (row, submission) in plan[..4].iter().enumerate() {
|
||||
assert_eq!(submission.copies, [copy(0, row, 1, 0)]);
|
||||
assert_eq!(submission.staging_bytes, 32);
|
||||
}
|
||||
assert_eq!(plan[4].copies, [copy(1, 0, 2, 0), copy(2, 0, 1, 32)]);
|
||||
assert_eq!(plan[4].staging_bytes, 40);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_row_is_planned_once_within_budget() {
|
||||
for (w, h, mips) in [(1, 1, 1), (37, 19, 6), (64, 3, 7), (5, 128, 8)] {
|
||||
let desc = Rgba8TextureDesc::new(w, h, mips).unwrap();
|
||||
let widest = w * RGBA8_TEXEL_BYTES;
|
||||
for budget in [
|
||||
widest,
|
||||
widest + 4,
|
||||
3 * widest,
|
||||
w * h * RGBA8_TEXEL_BYTES * 2,
|
||||
] {
|
||||
let mut next_row = vec![0; mips as usize];
|
||||
for submission in plan(desc, budget) {
|
||||
assert!(submission.staging_bytes <= budget);
|
||||
let mut offset = 0;
|
||||
for c in &submission.copies {
|
||||
let (mw, _) = desc.mip_extent(c.level).unwrap();
|
||||
assert_eq!(c.first_row, next_row[c.level as usize]);
|
||||
assert_eq!(c.staging_offset, offset);
|
||||
assert!(c.rows > 0);
|
||||
offset += c.rows * mw * RGBA8_TEXEL_BYTES;
|
||||
next_row[c.level as usize] += c.rows;
|
||||
}
|
||||
assert_eq!(offset, submission.staging_bytes);
|
||||
}
|
||||
for level in 0..mips {
|
||||
assert_eq!(next_row[level as usize], desc.mip_extent(level).unwrap().1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_partial_and_malformed_uploads_before_planning() {
|
||||
let desc = Rgba8TextureDesc::new(8, 4, 2).unwrap();
|
||||
let bytes = vec![0; 8 * 4 * RGBA8_TEXEL_BYTES];
|
||||
let mips = levels(&desc, &bytes);
|
||||
|
||||
let missing = error(desc, &mips[..1], 1024);
|
||||
assert!(missing.contains("mip level 1 is missing"), "{missing}");
|
||||
|
||||
let duplicate = error(desc, &[mips[0], mips[1], mips[1]], 1024);
|
||||
assert!(duplicate.contains("more than once"), "{duplicate}");
|
||||
|
||||
let out_of_range = Rgba8MipLevel::new_packed(2, 2, 1, &bytes[..8]);
|
||||
let range = error(desc, &[mips[0], mips[1], out_of_range], 1024);
|
||||
assert!(range.contains("out of bounds"), "{range}");
|
||||
|
||||
let wrong_size = Rgba8MipLevel::new_packed(1, 4, 1, &bytes[..16]);
|
||||
assert!(error(desc, &[mips[0], wrong_size], 1024).contains("expected 4x2"));
|
||||
|
||||
let mut short_pitch = mips[0];
|
||||
short_pitch.row_pitch = 28;
|
||||
assert!(error(desc, &[short_pitch, mips[1]], 1024).contains("row pitch"));
|
||||
|
||||
let short_bytes = Rgba8MipLevel::new_packed(0, 8, 4, &bytes[..127]);
|
||||
assert!(error(desc, &[short_bytes, mips[1]], 1024).contains("buffer length"));
|
||||
|
||||
let small = error(desc, &mips, 28);
|
||||
assert!(small.contains("smaller than one 32-byte row"), "{small}");
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use xenora_metal::texture_pipeline::{Rgba8TextureDesc, StagingBudget, plan_staged_upload};
|
||||
use xenora_metal::{MetalRgba8Texture, Rgba8MipLevel};
|
||||
use xenora_texture::{Bc1Upload, Bc1UploadDesc, TiledBc1};
|
||||
|
||||
use super::context;
|
||||
@@ -135,162 +133,3 @@ fn samples_pitched_bc1_upload_across_mips_and_layers() {
|
||||
);
|
||||
println!("checked 33 RGBA8 texels from pitched BC1 subresources");
|
||||
}
|
||||
|
||||
/// Texel bytes chosen so neighbouring texels, rows and levels all differ, built
|
||||
/// without any Xenora code so the readback has an independent expectation.
|
||||
fn pattern_texel(level: u32, x: usize, y: usize) -> [u8; 4] {
|
||||
let level = level as usize;
|
||||
[
|
||||
(x * 7 + level * 50) as u8,
|
||||
(y * 13 + level) as u8,
|
||||
((x ^ y) * 3) as u8,
|
||||
(255 - level * 9) as u8,
|
||||
]
|
||||
}
|
||||
|
||||
fn tight_pattern(level: u32, width: usize, height: usize) -> Vec<u8> {
|
||||
(0..height)
|
||||
.flat_map(|y| (0..width).flat_map(move |x| pattern_texel(level, x, y)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Each row padded by `pad` bytes of 0xEE, which must never reach the texture.
|
||||
fn padded_pattern(level: u32, width: usize, height: usize, pad: usize) -> Vec<u8> {
|
||||
let tight = tight_pattern(level, width, height);
|
||||
tight
|
||||
.chunks(width * 4)
|
||||
.flat_map(|row| row.iter().copied().chain(std::iter::repeat_n(0xEE, pad)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn padded_levels(desc: Rgba8TextureDesc, pad: usize) -> Vec<(usize, usize, Vec<u8>)> {
|
||||
(0..desc.mips)
|
||||
.map(|level| {
|
||||
let (w, h) = desc.mip_extent(level).unwrap();
|
||||
(w, h, padded_pattern(level, w, h, pad))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn mip_views(levels: &[(usize, usize, Vec<u8>)], pad: usize) -> Vec<Rgba8MipLevel<'_>> {
|
||||
levels
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(level, (w, h, bytes))| Rgba8MipLevel {
|
||||
level: level as u32,
|
||||
width: *w,
|
||||
height: *h,
|
||||
row_pitch: w * 4 + pad,
|
||||
bytes,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_upload_matches_the_source_under_every_budget() {
|
||||
let gpu = context();
|
||||
// 37×19 has six levels, down to 1×1, and odd sizes at every level.
|
||||
let desc = Rgba8TextureDesc::new(37, 19, 6).unwrap();
|
||||
let pad = 12;
|
||||
let levels = padded_levels(desc, pad);
|
||||
let mips = mip_views(&levels, pad);
|
||||
let total: usize = levels.iter().map(|(w, h, _)| w * h * 4).sum();
|
||||
let widest_row = 37 * 4;
|
||||
// One submission, several bands, a single row per band, and a budget that
|
||||
// leaves a remainder at every level.
|
||||
for budget in [total, 3 * widest_row, widest_row, widest_row + 4] {
|
||||
let budget = StagingBudget::new(budget).unwrap();
|
||||
let plan = plan_staged_upload(&desc, &mips, budget).unwrap();
|
||||
let (texture, report) =
|
||||
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget)
|
||||
.unwrap();
|
||||
assert_eq!(report.submissions, plan.len());
|
||||
assert!(report.peak_staging_bytes <= budget.max_bytes());
|
||||
assert_eq!(report.bytes_copied, total);
|
||||
if budget.max_bytes() == total {
|
||||
assert_eq!(report.submissions, 1);
|
||||
} else {
|
||||
assert!(report.submissions > 1);
|
||||
}
|
||||
for level in 0..desc.mips {
|
||||
let (w, h) = desc.mip_extent(level).unwrap();
|
||||
let actual = texture.read_back(gpu.device(), gpu.queue(), level).unwrap();
|
||||
assert_eq!(
|
||||
actual,
|
||||
tight_pattern(level, w, h),
|
||||
"budget {} level {level}",
|
||||
budget.max_bytes()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_and_direct_uploads_produce_the_same_texels() {
|
||||
let gpu = context();
|
||||
let desc = Rgba8TextureDesc::new(16, 9, 5).unwrap();
|
||||
let levels = padded_levels(desc, 0);
|
||||
let mips = mip_views(&levels, 0);
|
||||
let direct = MetalRgba8Texture::upload(gpu.device(), desc, &mips).unwrap();
|
||||
let budget = StagingBudget::new(16 * 4 * 2).unwrap();
|
||||
let (staged, _) =
|
||||
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget).unwrap();
|
||||
for level in 0..desc.mips {
|
||||
let (w, h) = desc.mip_extent(level).unwrap();
|
||||
let expected = tight_pattern(level, w, h);
|
||||
assert_eq!(
|
||||
direct.read_back(gpu.device(), gpu.queue(), level).unwrap(),
|
||||
expected
|
||||
);
|
||||
assert_eq!(
|
||||
staged.read_back(gpu.device(), gpu.queue(), level).unwrap(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_upload_handles_a_single_texel() {
|
||||
let gpu = context();
|
||||
let desc = Rgba8TextureDesc::new(1, 1, 1).unwrap();
|
||||
let texel = pattern_texel(0, 0, 0);
|
||||
let mips = [Rgba8MipLevel::new_packed(0, 1, 1, &texel)];
|
||||
let budget = StagingBudget::new(4).unwrap();
|
||||
let (texture, report) =
|
||||
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget).unwrap();
|
||||
assert_eq!((report.submissions, report.peak_staging_bytes), (1, 4));
|
||||
assert_eq!(
|
||||
texture.read_back(gpu.device(), gpu.queue(), 0).unwrap(),
|
||||
texel
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_upload_rejects_bad_input_before_touching_the_gpu() {
|
||||
let gpu = context();
|
||||
let desc = Rgba8TextureDesc::new(8, 4, 2).unwrap();
|
||||
let levels = padded_levels(desc, 0);
|
||||
let mips = mip_views(&levels, 0);
|
||||
let small = StagingBudget::new(28).unwrap();
|
||||
let error = MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, small)
|
||||
.unwrap_err();
|
||||
assert!(!error.is_capability_unavailable());
|
||||
assert!(
|
||||
error.to_string().contains("smaller than one 32-byte row"),
|
||||
"{error}"
|
||||
);
|
||||
let budget = StagingBudget::new(1024).unwrap();
|
||||
let missing =
|
||||
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips[..1], budget)
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
missing.to_string().contains("mip level 1 is missing"),
|
||||
"{missing}"
|
||||
);
|
||||
|
||||
// A Private texture refuses CPU writes instead of failing inside Metal.
|
||||
let (texture, _) =
|
||||
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget).unwrap();
|
||||
let refused = texture.upload_mip(&mips[0]).unwrap_err();
|
||||
assert!(refused.to_string().contains("Private-storage"), "{refused}");
|
||||
}
|
||||
+47
-10
@@ -27,6 +27,8 @@ pub use upload::{
|
||||
|
||||
const BLOCK_BYTES: usize = 8;
|
||||
const TILE_BLOCKS: usize = 2;
|
||||
const TILE_ROW_BYTES: usize = TILE_BLOCKS * BLOCK_BYTES;
|
||||
const TILE_BYTES: usize = TILE_BLOCKS * TILE_ROW_BYTES;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum TextureError {
|
||||
@@ -91,19 +93,30 @@ impl<'a> TiledBc1<'a> {
|
||||
/// Copies one subresource as tightly packed row-major BC1 block rows.
|
||||
/// Padded tile slots are excluded, including at partial texel blocks.
|
||||
pub fn linearize(&self, layer: usize, mip: u32) -> Result<Vec<u8>, TextureError> {
|
||||
if layer >= self.layers {
|
||||
if layer >= self.layers || mip >= self.mips {
|
||||
return Err(TextureError::OutOfBounds);
|
||||
}
|
||||
self.mip_extent(mip)?;
|
||||
let (width, height) = mip_blocks(self.width, self.height, mip);
|
||||
let base = self.mip_base(layer, mip)?;
|
||||
let tile_row_stride = width.div_ceil(TILE_BLOCKS) * TILE_BYTES;
|
||||
let full_tiles = width / TILE_BLOCKS;
|
||||
let edge_bytes = (width % TILE_BLOCKS) * BLOCK_BYTES;
|
||||
let mut blocks = Vec::new();
|
||||
// Construction checked the larger, padded byte count.
|
||||
blocks
|
||||
.try_reserve_exact(width * height * BLOCK_BYTES)
|
||||
.map_err(|_| TextureError::AllocationFailed)?;
|
||||
// Construction requires the exact padded length, so each selected tile row is in bounds.
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
blocks.extend_from_slice(&self.block(layer, mip, x, y)?);
|
||||
let row_start =
|
||||
base + (y / TILE_BLOCKS) * tile_row_stride + (y % TILE_BLOCKS) * TILE_ROW_BYTES;
|
||||
for tile in 0..full_tiles {
|
||||
let start = row_start + tile * TILE_BYTES;
|
||||
blocks.extend_from_slice(&self.bytes[start..start + TILE_ROW_BYTES]);
|
||||
}
|
||||
if edge_bytes != 0 {
|
||||
let start = row_start + full_tiles * TILE_BYTES;
|
||||
blocks.extend_from_slice(&self.bytes[start..start + edge_bytes]);
|
||||
}
|
||||
}
|
||||
Ok(blocks)
|
||||
@@ -124,19 +137,24 @@ impl<'a> TiledBc1<'a> {
|
||||
if x >= width || y >= height {
|
||||
return Err(TextureError::OutOfBounds);
|
||||
}
|
||||
let mut base = layer * self.layer_bytes;
|
||||
for prior in 0..mip {
|
||||
base += mip_bytes(self.width, self.height, prior)?;
|
||||
}
|
||||
let base = self.mip_base(layer, mip)?;
|
||||
// Construction checked the full padded size for every level and layer.
|
||||
let tile = (y / TILE_BLOCKS) * width.div_ceil(TILE_BLOCKS) + x / TILE_BLOCKS;
|
||||
let within_tile = (y % TILE_BLOCKS) * TILE_BLOCKS + x % TILE_BLOCKS;
|
||||
let offset = base + (tile * TILE_BLOCKS.pow(2) + within_tile) * BLOCK_BYTES;
|
||||
let offset = base + tile * TILE_BYTES + within_tile * BLOCK_BYTES;
|
||||
self.bytes
|
||||
.get(offset..offset + BLOCK_BYTES)
|
||||
.and_then(|bytes| bytes.try_into().ok())
|
||||
.ok_or(TextureError::InvalidByteLength)
|
||||
}
|
||||
|
||||
fn mip_base(&self, layer: usize, mip: u32) -> Result<usize, TextureError> {
|
||||
let mut base = layer * self.layer_bytes;
|
||||
for prior in 0..mip {
|
||||
base += mip_bytes(self.width, self.height, prior)?;
|
||||
}
|
||||
Ok(base)
|
||||
}
|
||||
}
|
||||
|
||||
fn mip_blocks(width: usize, height: usize, mip: u32) -> (usize, usize) {
|
||||
@@ -151,7 +169,7 @@ fn mip_bytes(width: usize, height: usize, mip: u32) -> Result<usize, TextureErro
|
||||
width
|
||||
.div_ceil(TILE_BLOCKS)
|
||||
.checked_mul(height.div_ceil(TILE_BLOCKS))
|
||||
.and_then(|tiles| tiles.checked_mul(TILE_BLOCKS.pow(2) * BLOCK_BYTES))
|
||||
.and_then(|tiles| tiles.checked_mul(TILE_BYTES))
|
||||
.ok_or(TextureError::SizeOverflow)
|
||||
}
|
||||
|
||||
@@ -216,6 +234,7 @@ mod tests {
|
||||
assert_eq!(tex.linearize(1, 0).unwrap(), logical_blocks.as_flattened());
|
||||
assert_eq!(tex.linearize(1, 1).unwrap(), [20; 8]);
|
||||
assert_eq!(tex.linearize(2, 0), Err(TextureError::OutOfBounds));
|
||||
assert_eq!(tex.linearize(0, 2), Err(TextureError::OutOfBounds));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -242,6 +261,24 @@ mod tests {
|
||||
assert_eq!(texture.block(0, 0, 2, 2), Ok([12; 8]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linearizes_odd_tile_edges_in_each_layer() {
|
||||
// A 21×21 texture uses 9, 4 and 1 tiles across the three mips.
|
||||
// Mip 1 is 10×10 texels, so only nine of its sixteen slots are logical.
|
||||
let block = |slot: u8| [slot, 1, 2, 3, 4, 5, 6, !slot];
|
||||
let bytes: Vec<_> = (0..112).flat_map(block).collect();
|
||||
let texture = TiledBc1::new(&bytes, 21, 21, 3, 2).unwrap();
|
||||
for (layer, first_slot) in [(0, 36), (1, 92)] {
|
||||
let expected: Vec<_> = [0, 1, 4, 2, 3, 6, 8, 9, 12]
|
||||
.into_iter()
|
||||
.flat_map(|slot| block(first_slot + slot))
|
||||
.collect();
|
||||
assert_eq!(texture.linearize(layer, 1).unwrap(), expected);
|
||||
let last_mip: Vec<_> = (16..20).flat_map(|slot| block(first_slot + slot)).collect();
|
||||
assert_eq!(texture.linearize(layer, 2).unwrap(), last_mip);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_opaque_and_transparent_bc1_palettes() {
|
||||
let opaque = decode_bc1([0, 0xf8, 31, 0, 0xe4, 0xe4, 0xe4, 0xe4]);
|
||||
|
||||
@@ -40,6 +40,8 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
|
||||
|
||||
## Testing, validation, and benchmarks
|
||||
|
||||
- [Testing and acceptance index](testing/README.md) — Entry point for test procedures, evidence and review records.
|
||||
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](testing/shader-form-acceptance.md) — Independence, command, log and promotion rules for fixture-verified instruction forms.
|
||||
- [Engineering progress](progress.md) — Verification commands, metric definitions, and open release gates.
|
||||
- [Test inventory comparison](testing/test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
|
||||
- [Persistent resource and translated rendering acceptance](testing/x9-acceptance.md) — Pinned upstream tests, native ARM64 results and unsupported cases.
|
||||
|
||||
@@ -95,4 +95,4 @@ A feature bit is set only when every instruction of that feature is implemented.
|
||||
|
||||
## Rejected on purpose
|
||||
|
||||
LOCK except as described above, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, RCL, RCR, SHLD, SHRD, LODS, CMPS, SCAS, REPE and REPNE, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B, CMPXCHG16B and fences. The DBT also refuses raw SYSCALL.
|
||||
LOCK except as described above, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, SHLD, SHRD, LODS, CMPS, SCAS, REPE and REPNE, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B, CMPXCHG16B and fences. The DBT also refuses raw SYSCALL.
|
||||
@@ -0,0 +1,9 @@
|
||||
# Testing and acceptance
|
||||
|
||||
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](shader-form-acceptance.md) — Rule and evidence required to promote a form from local results to `fixture verified`.
|
||||
- [Test inventory comparison](test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
|
||||
- [Persistent resource and translated rendering acceptance](x9-acceptance.md) — Native ARM64 results and unsupported cases.
|
||||
- [Baseline acceptance](phase-02-baseline.md) and [Phase 01 assurance](phase01-assurance.md) — Candidate-specific evidence.
|
||||
- [Independent reviews](review-log.md) — Review findings and acceptance records.
|
||||
- [Mutation testing](mutation.md) and [benchmark protocol](benchmarks.md) — Sensitivity and timing requirements.
|
||||
- [Infrastructure QA tooling](infrastructure/README.md) — Advisory orchestration, PR validation, benchmark analysis and release checks.
|
||||
@@ -1,5 +1,12 @@
|
||||
# Independent review
|
||||
|
||||
## gfx1030 form acceptance
|
||||
|
||||
Use the [AMD RDNA2 desktop GPU (gfx1030) form acceptance rule](shader-form-acceptance.md) for entries that
|
||||
promote instruction forms to `fixture verified`. Record only completed runs with
|
||||
a named commit, independent runner, host, exact commands and real counts. Raw
|
||||
logs stay under ignored `artifacts/acceptance/<commit>/`.
|
||||
|
||||
## R1. First synthetic compute checkpoint, 2026-11-22
|
||||
|
||||
Reviewed the integrated working tree before a candidate commit. The findings below cover the first checkpoint.
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
# AMD RDNA2 desktop GPU (gfx1030) form acceptance
|
||||
|
||||
This is the promotion rule for AMD RDNA2 desktop GPU (`gfx1030`) instruction
|
||||
forms in [`docs/status.toml`](../status.toml). It implements the documentation
|
||||
step of [#302](https://github.com/ranveersoni98/Xenora/issues/302). It does not
|
||||
claim Xbox-hardware verification or commercial-game compatibility.
|
||||
|
||||
The **LLVM three-way decoder check** is the ignored `llvm-mc` comparison in
|
||||
[`crates/decoder/tests/gfx1030.rs`](../../crates/decoder/tests/gfx1030.rs). It
|
||||
compares Xenora's decoder with LLVM's gfx1030 decoder over the fixture and
|
||||
probe encodings; it is encoding evidence, not GPU-semantics evidence.
|
||||
|
||||
## Status meanings
|
||||
|
||||
| Status | Meaning |
|
||||
| --- | --- |
|
||||
| `local known-answer test passed` | The implementation's CPU known-answer test passed locally. This is not independent acceptance. |
|
||||
| `local Apple M5 readback passed; acceptance pending` | A local native Metal readback passed with validation, but the independence and evidence rules below are incomplete. |
|
||||
| `fixture verified on Apple M5` | The host-qualified spelling used by three existing rows. `scripts/audit/status.py` treats it as equivalent to `fixture verified`; existing rows do not need re-acceptance solely for this wording. New entries should normally use `fixture verified` and record the host in the review log. |
|
||||
| `fixture verified` | The form or documented family batch passed independent acceptance at a named commit, with CPU, LLVM and native Metal evidence recorded. |
|
||||
|
||||
A skipped test is not a pass. A shader compile without readback is not GPU
|
||||
verification. Agreement with a spec-derived reference is not agreement with
|
||||
Xbox hardware.
|
||||
|
||||
## Independence
|
||||
|
||||
> **Proposed policy, pending maintainer confirmation.** The independence rule in
|
||||
> this section is the proposal from #302. Do not use it to promote forms until
|
||||
> the maintainer confirms or revises it.
|
||||
|
||||
The person running the acceptance pass must not be the author of the pull
|
||||
request that added the form being accepted. The runner may use the existing
|
||||
tests and commands, but must record their own results and review the evidence.
|
||||
If the maintainer runs the pass for forms they authored, the review-log entry
|
||||
must say so explicitly; that exception is not silent self-certification.
|
||||
|
||||
The expected values used by the test must remain independent of the production
|
||||
decoder, translator or Metal backend. Do not change fixtures, thresholds or test
|
||||
filters to make a form pass.
|
||||
|
||||
## Acceptance procedure
|
||||
|
||||
1. **Use a clean named commit.** Start from a clean checkout of `main` at the
|
||||
commit being accepted. Record the full commit hash. Do not accept a working
|
||||
tree with uncommitted changes.
|
||||
2. **Name the scope.** List each form, or a family batch with an explicit list of
|
||||
forms, covered by the pass. A family name alone is not enough.
|
||||
3. **Run the standard gates.** Format, Clippy, workspace tests, fixture checks,
|
||||
the LLVM three-way decoder check and the native GPU suite must pass. Record
|
||||
exact commands, environment variables and pass/fail/skip counts.
|
||||
4. **Run the form's CPU and Metal tests.** The CPU known-answer/reference tests
|
||||
and the native Metal readback must both pass. Metal API and shader validation
|
||||
must be enabled. Use a targeted test filter where useful, but keep the full
|
||||
standard-gate result for the same commit.
|
||||
5. **Check negative cases.** Unsupported encodings, malformed inputs and any
|
||||
documented rejection cases for the form must still pass.
|
||||
6. **Save raw logs.** Put raw output under ignored
|
||||
`artifacts/acceptance/<commit>/`. Do not commit raw logs.
|
||||
7. **Write the review-log summary.** Add an entry to
|
||||
[`review-log.md`](review-log.md) with the commit, runner's GitHub login, host,
|
||||
scope, exact commands or log path, and CPU/LLVM/Metal results. A reviewer
|
||||
confirms the entry if the runner is not the maintainer.
|
||||
8. **Promote only passed forms.** Change `cpu` and `gpu` in `docs/status.toml`
|
||||
only for forms covered by a passing entry. Regenerate the status tables and
|
||||
progress graphic, then run `python3 scripts/audit/status.py --check`.
|
||||
|
||||
## Standard gate set
|
||||
|
||||
Run on native Apple Silicon. The exact host and tool versions belong in the
|
||||
review-log entry.
|
||||
|
||||
```sh
|
||||
export CARGO_BUILD_JOBS=2
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --locked --workspace --all-targets --all-features -- -D warnings
|
||||
cargo test --locked --workspace
|
||||
scripts/assemble-fixture.sh --check
|
||||
LLVM_BIN="$(brew --prefix llvm)/bin" \
|
||||
cargo test --locked -p xenora-decoder --test gfx1030 -- --include-ignored --nocapture
|
||||
cargo test --locked -p xenora-semantic-review
|
||||
scripts/test-gpu.sh
|
||||
python3 scripts/audit/status.py --check
|
||||
```
|
||||
|
||||
For a targeted semantic-review pass, record the filter and use the same Metal
|
||||
validation environment as `scripts/test-gpu.sh`:
|
||||
|
||||
```sh
|
||||
cargo test --locked -p xenora-semantic-review <cpu-test-filter>
|
||||
MTL_DEBUG_LAYER=1 \
|
||||
MTL_SHADER_VALIDATION=1 \
|
||||
MTL_SHADER_VALIDATION_REPORT_TO_STDERR=1 \
|
||||
MTL_SHADER_VALIDATION_ABORT_ON_FAULT=1 \
|
||||
cargo test --locked -p xenora-semantic-review <native-metal-test-filter> \
|
||||
-- --ignored --exact --nocapture --test-threads=1
|
||||
```
|
||||
|
||||
A targeted filter does not replace the standard gate set; it attributes the
|
||||
result to a form or family batch.
|
||||
|
||||
## Review-log entry
|
||||
|
||||
Use one row per commit and scope. Add rows to
|
||||
[`review-log.md`](review-log.md); keep raw output only in `artifacts/`.
|
||||
|
||||
| Date | Commit | Runner (GitHub login) | Host and tools | Forms or batch | Commands / raw log | CPU | LLVM | Metal | Review |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| YYYY-MM-DD | full SHA | @login | Mac, macOS, Xcode, Rust, LLVM | explicit form list | exact commands and `artifacts/acceptance/<commit>/` path | pass/fail/skip counts | pass/fail counts | pass/fail/skip counts; validation on | reviewer GitHub login or maintainer exception |
|
||||
|
||||
Do not write `pass` without counts. Do not count a skipped native test as Metal
|
||||
evidence.
|
||||
|
||||
## Promotion and failures
|
||||
|
||||
After a passing entry, set the accepted rows to `fixture verified` and regenerate:
|
||||
|
||||
```sh
|
||||
python3 scripts/audit/status.py
|
||||
python3 scripts/audit/status.py --check
|
||||
```
|
||||
|
||||
If any required check fails or skips, leave the form pending. Record the commit,
|
||||
host, command and failure in the review log, and open a separate issue for the
|
||||
failure. Do not weaken the test or change the expected result in the acceptance
|
||||
pass.
|
||||
|
||||
The automated status-check enforcement proposed in #302 is a separate change.
|
||||
Until it lands, reviewers must enforce the review-log requirement manually.
|
||||
@@ -10,7 +10,7 @@ import sys
|
||||
import tomllib
|
||||
|
||||
registry = Path("docs/claims.toml")
|
||||
claims = tomllib.loads(registry.read_text())["claim"]
|
||||
claims = tomllib.loads(registry.read_text(encoding="utf-8"))["claim"]
|
||||
classes = {}
|
||||
errors = []
|
||||
claim_id = re.compile(r"\bCLAIM-[A-Z0-9]+(?:-[A-Z0-9]+)*\b")
|
||||
@@ -37,10 +37,10 @@ files = [Path("README.md"), Path("AGENTS.md"), *Path("docs").rglob("*"),
|
||||
for source in files:
|
||||
if source == registry or source.suffix not in {".md", ".toml", ".rs"}:
|
||||
continue
|
||||
for reference in set(claim_id.findall(source.read_text())) - classes.keys():
|
||||
for reference in set(claim_id.findall(source.read_text(encoding="utf-8"))) - classes.keys():
|
||||
errors.append(f"{source}: unregistered {reference}")
|
||||
|
||||
status = tomllib.loads(Path("docs/status.toml").read_text())
|
||||
status = tomllib.loads(Path("docs/status.toml").read_text(encoding="utf-8"))
|
||||
for feature in status["feature"]:
|
||||
verification = feature.get("hardware_verification", "")
|
||||
if verification.casefold() != "verified":
|
||||
|
||||
@@ -18,7 +18,7 @@ def table(headers, rows):
|
||||
|
||||
|
||||
def replace_block(path, name, body, check):
|
||||
original = path.read_text()
|
||||
original = path.read_text(encoding="utf-8")
|
||||
start = f"<!-- status:{name}:start -->\n"
|
||||
stop = f"\n<!-- status:{name}:end -->"
|
||||
head, _, tail = original.partition(start)
|
||||
@@ -30,7 +30,7 @@ def replace_block(path, name, body, check):
|
||||
if check:
|
||||
print(f"{path}: status table differs from docs/status.toml", file=sys.stderr)
|
||||
return False
|
||||
path.write_text(updated)
|
||||
path.write_text(updated, encoding="utf-8", newline="\n")
|
||||
return True
|
||||
|
||||
|
||||
@@ -90,12 +90,12 @@ def render_progress(status):
|
||||
|
||||
|
||||
def check_asset(path, svg, check):
|
||||
if path.exists() and path.read_text() == svg:
|
||||
if path.exists() and path.read_text(encoding="utf-8") == svg:
|
||||
return True
|
||||
if check:
|
||||
print(f"{path}: progress graphic differs from docs/status.toml", file=sys.stderr)
|
||||
return False
|
||||
path.write_text(svg)
|
||||
path.write_text(svg, encoding="utf-8", newline="\n")
|
||||
return True
|
||||
|
||||
|
||||
@@ -105,8 +105,8 @@ def main():
|
||||
check = parser.parse_args().check
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
docs = root / "docs"
|
||||
status = tomllib.loads((docs / "status.toml").read_text())
|
||||
claims = tomllib.loads((docs / "claims.toml").read_text())
|
||||
status = tomllib.loads((docs / "status.toml").read_text(encoding="utf-8"))
|
||||
claims = tomllib.loads((docs / "claims.toml").read_text(encoding="utf-8"))
|
||||
classes = {claim["id"]: claim["class"] for claim in claims["claim"]}
|
||||
|
||||
features = table(
|
||||
|
||||
Reference in new issue
Block a user