Compare commits

..
Author SHA1 Message Date
zachdoxsee 3b52215a30 Merge upstream main into task/175-page-boundary-faults
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 21:20:41 +01:00
Zach Doxsee bb6a9f6912 Merge pull request #361 from sahib453/task/125-movnti
loader: add MOVNTI, the non-temporal store of a general register (#125)
2026-11-24 21:15:11 +01:00
Zach Doxsee a7e3e1e42c Merge pull request #358 from sahib453/task/199-fences
loader: accept MFENCE, LFENCE and SFENCE and document guest memory ordering (#199)
2026-11-24 21:14:51 +01:00
Zach Doxsee 9c76bf16f0 Merge pull request #357 from Arths17/test/205-handle-lifetime
test: cover guest handle lifetime and failed-call nonmutation (#205)
2026-11-24 21:14:37 +01:00
Zach Doxsee 7dd1329866 Merge pull request #367 from jelly013/probe-default-folder
cli: use a neutral default folder for probe reports (#364)
2026-11-24 21:07:02 +01:00
Zach Doxsee 4b579af70d Merge pull request #360 from 1Bartosz/perf/116-release-lto
build: use fat LTO and one codegen unit for release builds (#116)
2026-11-24 21:06:47 +01:00
Zach Doxsee 9dfdfd1134 Merge pull request #365 from Arths17/fix/363-native-audit-utf8
Read native audit JSON as UTF-8
2026-11-24 21:05:34 +01:00
zachdoxsee ce8d16e367 Merge upstream main into test/205-handle-lifetime
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 21:05:23 +01:00
atharvranjan 8df13ae976 ci: retrigger 2026-11-24 14:02:59 -06:00
Bartosz Szczepański 36c4fbd520 changelog: state the warm DBT cost of fat LTO (#116)
Review re-measurement on Apple M5 showed warm DBT about 2% slower
under fat LTO with one codegen unit in four of four alternating runs.
The entry said it was unchanged.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 21:02:54 +01:00
atharvranjan 00eb6971e9 Preserve UTF-8 native inspection output
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 13:45:16 -06:00
Bartosz Szczepański c3b0025977 Merge upstream main into perf/116-release-lto
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 20:44:30 +01:00
jelly013 e5aca73c55 cli: use a neutral default folder for probe reports
`xenora probe` and `xenora imports sync` defaulted to a folder named after
one commercial game. Give both one shared default, `diagnostics/probe`, and
ignore it in Git. Keep the old ignore rules so existing local reports stay
out of commits.

Closes #364

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 20:31:13 +01:00
atharvranjan 281d92bfb5 Read native audit JSON as UTF-8
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 13:28:35 -06:00
atharvranjan 974d1fc62c ci: retrigger 2026-11-24 13:13:14 -06:00
Bartosz Szczepański 3d19c756e2 build: use fat LTO and one codegen unit for release builds (#116)
Release and bench builds used Cargo's defaults: no cross-crate LTO and
16 codegen units. Fat LTO with a single codegen unit lets the
interpreter and DBT hot paths inline across crates.

On Apple M5, dbt_bench medians over five alternating rounds of 101
samples drop from 903 to 845 us for the interpreter (-6%) and from
1.155 to 1.046 ms for cold DBT (-9%, faster in all five rounds); warm
DBT is unchanged. The xenora binary shrinks from 2.73 to 2.11 MB. A
clean release build of the workspace takes 14.0 s instead of 5.9 s.
Debug and test builds keep the dev profile and are unaffected.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 20:08:43 +01:00
Arths17 6106c37912 test: cover guest handle lifetime and failed-call nonmutation
Signed-off-by: Arths17 <166588440+Arths17@users.noreply.github.com>
2026-11-24 12:46:32 -06:00
sahib453 8b67479526 loader: report the first inaccessible byte of a page-crossing guest fault (#175)
A guest access that starts in a mapped 4 KiB page and runs into an
unmapped or forbidden one reported the start of the access. It now
reports the lowest address the access may not touch, which is what the
Intel SDM page-fault cases from #155 expect. Which accesses succeed is
unchanged, and a failed access still reads and writes nothing.

- memory.rs: resolve() reports the failing byte for both
  UnmappedAddress and PermissionViolation.
- tests/memory_page_boundaries.rs: permissions, adjacent pages, address
  overflow and the fault address at every 4 KiB guest boundary across
  two host pages (16 KiB each on Apple Silicon).
- cpu_known_answers.rs: the three page-crossing fault cases are no
  longer an ignored defect; they pass on both engines.
- memory_validation.rs, generated_runtime_integration.rs: five
  expectations that pinned the start address now name the first
  inaccessible byte.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-24 23:09:42 +05:30
15 changed files with 696 additions and 22 deletions

No files matched your search

+2
View File
@@ -52,6 +52,8 @@ jobs:
sh -n scripts/agent-queue.sh scripts/agent-sync.sh
- name: Test pull request template check
run: PYTHONPATH=scripts python3 -m unittest discover -s tests/pr_template
- name: Test native audit JSON decoding
run: python3 -m unittest discover -s tests/audit
- name: Test semantic registry generator and coverage report
run: |
python3 -m unittest discover -s tests/semantics_generator
+1
View File
@@ -35,6 +35,7 @@
__pycache__/
*.pyc
/diagnostics/probe/
/diagnostics/gta6-candidate-*/
/diagnostics/gta6-check/
+5
View File
@@ -10,8 +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.
- Changed the default report folder of `xenora probe` and `xenora imports sync` to `diagnostics/probe`, which Git ignores (#364). Anyone relying on the earlier default has to pass `--report`.
- 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.
@@ -23,6 +25,7 @@ remains unsupported.
- Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing.
### Added
- Added synthetic guest handle-lifetime regression tests (#205) for capacity reuse, stale handles, duplicate rights and lifetime, wrong object types, thread pseudo handles and failed-output nonmutation. Runtime behavior is unchanged; independent acceptance is pending.
- Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302).
- Added the VOP3A (`_e64`) encodings of eleven gfx1030 VOP2 integer forms (`v_mul_{i32_i24,hi_i32_i24,u32_u24,hi_u32_u24}`, `v_{min,max}_{i32,u32}`, `v_xnor_b32`, `v_sub_nc_u32`, `v_subrev_nc_u32`) and of the sixteen Wave32 integer compares (explicit SGPR mask destination, `s_cbranch_vccz` through `vcc_lo`, a translation error for reads of runtime-only SGPR results) as semantic-registry encoding variants, with VGPR sources only. New fixtures `vop3-integer` and `vop3-compare` with IR and MSL goldens, and an independent guide-derived oracle (`tests/validation/tests/vop3_{integer,compare}.rs`) that agrees on both reference interpreters and on native Metal. Part of #215.
- Added 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.
@@ -198,6 +201,8 @@ remains unsupported.
native DBT.
### Fixed
- Fixed the address reported when a guest memory access faults part-way across a 4 KiB page boundary (#175). An access that starts in a mapped page and runs into an unmapped or forbidden one now reports the first byte it may not touch; it used to report the start of the access. An access whose first byte fails reports the same address as before, and a failed access still reads and writes nothing. Three Intel SDM page-fault cases in `cpu_known_answers.rs` moved from open defect to verified on both engines. `crates/loader/tests/memory_page_boundaries.rs` checks permissions, adjacent pages, address overflow and the fault address at every 4 KiB guest boundary across two host pages (16 KiB each on Apple Silicon). Guest memory is checked in software, so the host page size does not affect these results. Four #82 expectations and one CRT `memmove` expectation that pinned the start address were corrected. Not compared with x86 hardware; awaiting independent review.
- Fixed the native dependency audit reading Cargo JSON and inspection-tool output in the process locale encoding; it now reads and reports UTF-8 paths and diagnostics under an ASCII locale (#363).
- Made the static probe and the binder share one bounded import parser, after the truncated-name fix for #270. Truncated, unterminated, empty or non-ASCII names, reserved bits and endless tables are reported by the probe and refused by the binder.
- Fixed the MXCSR flags of an unmasked floating-point overflow whose result is exact before the exponent is bounded, such as the largest binary32 value times two (#128). Only the overflow flag is set; the precision flag used to be set as well although nothing was rounded. A masked overflow still sets both flags and delivers infinity or the largest finite value, and an unmasked overflow that is also inexact still sets both. Five Intel SDM cases in `cpu_known_answers.rs` moved from open defect to verified on both engines, with three more for the other rounding modes, and the scalar and conversion sweeps now compare the precision flag in this case as well. Not compared with x86 hardware; awaiting independent review.
- Fixed the decoder refusing an instruction whose REX prefix is followed by a legacy prefix (#69). Such a REX is ignored, as the Intel SDM (Vol. 2A, 2.2.1) specifies, so `48 66 01 D8` now runs as `add ax, bx`; it used to stop the guest with an illegal-instruction exit. The ignored byte still counts toward the instruction's length, and a REX that directly precedes the opcode behaves as before. The interpreter, the DBT and the static probe share the decoder. One SDM-derived case in `cpu_known_answers.rs` moved from refused to verified and three were added, for an ignored REX.B, an ignored REX.W before a segment prefix, and a later REX that does apply. Two REX bytes in a row and the address-size prefix stay rejected. Not compared with x86 hardware; awaiting independent review.
+7
View File
@@ -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
+5 -2
View File
@@ -6,6 +6,9 @@ mod shaders;
use std::process::ExitCode;
/// Where `probe` writes and `imports sync` reads without `--report`.
const DEFAULT_REPORT_DIR: &str = "diagnostics/probe";
fn main() -> ExitCode {
match std::env::args().nth(1).as_deref() {
Some("info") => {
@@ -46,7 +49,7 @@ fn main() -> ExitCode {
let args: Vec<String> = std::env::args().collect();
let mut pe_path: Option<String> = None;
let mut mode = "static".to_string();
let mut report_dir = "diagnostics/gta6-candidate-e95020b2".to_string();
let mut report_dir = DEFAULT_REPORT_DIR.to_string();
let mut i = 2;
while i < args.len() {
@@ -373,7 +376,7 @@ fn run_imports_generate_cli(args: &[String]) -> ExitCode {
}
fn run_imports_sync_cli(args: &[String]) -> ExitCode {
let mut report_dir = "diagnostics/gta6-candidate-e95020b2".to_string();
let mut report_dir = DEFAULT_REPORT_DIR.to_string();
let mut check_mode = false;
let mut i = 0;
+27
View File
@@ -0,0 +1,27 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Default report folder of `xenora probe` and `xenora imports sync`.
use std::process::Command;
#[test]
fn probe_and_sync_use_the_same_default_folder() {
let fixture = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../fixtures/pe/delay-imports.exe"
);
let folder = std::env::temp_dir().join(format!("xenora-default-{}", std::process::id()));
std::fs::create_dir(&folder).unwrap();
for arguments in [&["probe", "--pe", fixture][..], &["imports", "sync"]] {
let status = Command::new(env!("CARGO_BIN_EXE_xenora"))
.args(arguments)
.current_dir(&folder)
.status()
.unwrap();
assert!(status.success(), "{arguments:?}");
}
let written = ["imports.csv", "import_backlog.md"]
.map(|name| folder.join("diagnostics/probe").join(name).is_file());
std::fs::remove_dir_all(folder).unwrap();
assert_eq!(written, [true, true]);
}
+11 -2
View File
@@ -419,6 +419,12 @@ impl GuestMemory {
/// byte must be mapped and every region must grant `required` (`None` bypasses
/// permission checks for the loader). The whole range is checked before any byte
/// is copied, so a failed access never partially reads or writes.
///
/// A failed access reports the lowest address it may not touch, which is the
/// start of the access only when its first byte fails. An access that begins in
/// a mapped page and runs into an unmapped or forbidden one therefore reports
/// the first byte of that page, as an x86 page fault reports the linear address
/// that could not be translated or accessed.
fn resolve(
&self,
address: u64,
@@ -452,7 +458,10 @@ impl GuestMemory {
Some(_) => region.permissions.execute,
};
if let (false, Some(required)) = (permitted, required) {
return Err(MemoryError::PermissionViolation { address, required });
return Err(MemoryError::PermissionViolation {
address: cursor,
required,
});
}
let take = (end.min(region_end) - cursor) as usize;
pieces.push((index, (cursor - region.base) as usize, take));
@@ -461,7 +470,7 @@ impl GuestMemory {
return Ok(pieces);
}
}
Err(MemoryError::UnmappedAddress(address))
Err(MemoryError::UnmappedAddress(cursor))
}
fn read_checked(
+4 -8
View File
@@ -1532,7 +1532,7 @@ jump_to_unmapped_faults_at_target: rbx=U => rax=1 rip=U f=* ! PFX U
jump_to_data_page_faults_at_target: rbx=D+40 => rip=D+40 f=* ! PFX D+40
";
const DEFECT_STRADDLING_FAULT_ADDRESS: &str = r"
const STRADDLING_FAULT_ADDRESS: &str = r"
@ mov rcx, [rsi-4]
!488b4efc
SDM 3A 5.7 (the address with no translation); 3A 7.15 Interrupt 14
@@ -2675,10 +2675,7 @@ const GROUPS: &[(&str, &str)] = &[
("decoding", DECODING),
("fences", FENCES),
("memory_faults", MEMORY_FAULTS),
(
"defect_straddling_fault_address",
DEFECT_STRADDLING_FAULT_ADDRESS,
),
("straddling_fault_address", STRADDLING_FAULT_ADDRESS),
("defect_noncanonical_address", DEFECT_NONCANONICAL_ADDRESS),
("packed_integer_sse2", PACKED_INTEGER_SSE2),
("packed_integer_beyond_sse2", PACKED_INTEGER_BEYOND_SSE2),
@@ -3466,9 +3463,8 @@ fn memory_faults() {
}
#[test]
#[ignore = "known defect (#155): a page-crossing fault reports the start of the access"]
fn defect_straddling_fault_address() {
check_group(DEFECT_STRADDLING_FAULT_ADDRESS);
fn straddling_fault_address() {
check_group(STRADDLING_FAULT_ADDRESS);
}
#[test]
@@ -96,10 +96,11 @@ fn crt_handlers_validate_memory_boundaries() {
0x1008
)))
);
// The destination 0x1005..0x1009 is mapped up to 0x1008.
assert_eq!(
call("memmove", 0x1005, 0x1000, 4, &mut memory),
Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(
0x1005
0x1008
)))
);
let mut bytes = [0; 8];
@@ -0,0 +1,274 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Guest 4 KiB page boundaries on a host with larger pages (#175).
//!
//! Apple Silicon uses 16 KiB host pages, so four guest pages share one host
//! page and host page protection cannot separate them. Guest memory is checked
//! in software, byte by byte, and is never mapped with host protections. These
//! tests lay 4 KiB guest pages across two spans of the detected host page size
//! and require the same results at every guest page boundary, whether or not it
//! is also a host page boundary.
//!
//! The expected fault address is the first byte, in address order, that the
//! access may not touch: the linear address with no translation or without the
//! needed right. This is the reading of the Intel SDM used by the page-fault
//! cases in `cpu_known_answers.rs` (Volume 3A, Sections 5.7 and 7.15, Interrupt
//! 14). Every expectation below is a literal address or a table written from
//! that rule, not a value read back from the memory model. Nothing here was
//! compared with x86 hardware.
use xenora_loader::services::sysinfo::HostCapabilities;
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P};
const GUEST_PAGE: u64 = 0x1000;
/// Aligned to every host page size up to 1 GiB.
const BASE: u64 = 0x4000_0000;
fn host_page() -> u64 {
let size = HostCapabilities::detect()
.page_size
.expect("the host reports a page size");
assert_eq!(size % GUEST_PAGE, 0, "host page size {size:#x}");
size
}
/// Guest page boundaries strictly inside two host pages starting at `BASE`.
/// On a 16 KiB host that is seven boundaries, one of them a host page boundary.
fn boundaries() -> Vec<u64> {
let pages = 2 * host_page() / GUEST_PAGE;
(1..pages).map(|page| BASE + page * GUEST_PAGE).collect()
}
fn unmapped(address: u64) -> MemoryError {
MemoryError::UnmappedAddress(address)
}
fn violation(address: u64, required: &'static str) -> MemoryError {
MemoryError::PermissionViolation { address, required }
}
/// The page below `boundary`, filled with 0x5a, and optionally the page above
/// it, filled with 0xa5.
fn pages_around(boundary: u64, below: P, above: Option<P>) -> GuestMemory {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(boundary - GUEST_PAGE, 0x1000, below, &[0x5a; 0x1000])
.unwrap();
if let Some(above) = above {
memory
.map_region_with_data(boundary, 0x1000, above, &[0xa5; 0x1000])
.unwrap();
}
memory
}
/// The 16 bytes centred on `boundary`, read without permission checks.
fn bytes_around(memory: &GuestMemory, boundary: u64) -> (u64, u64) {
(
memory.read_u64_bypass(boundary - 8).unwrap(),
memory.read_u64_bypass(boundary).unwrap(),
)
}
const BELOW: u64 = 0x5a5a_5a5a_5a5a_5a5a;
const ABOVE: u64 = 0xa5a5_a5a5_a5a5_a5a5;
#[test]
fn apple_silicon_host_pages_hold_four_guest_pages() {
let size = host_page();
if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
assert_eq!(size, 0x4000);
assert_eq!(boundaries().len(), 7);
assert!(boundaries().contains(&(BASE + 0x4000)));
}
}
#[test]
fn each_guest_page_in_a_host_page_keeps_its_own_permissions() {
// (permissions, read allowed, write allowed, execute allowed)
let kinds = [
(P::READ_WRITE, true, true, false),
(P::READ_ONLY, true, false, false),
(P::NO_ACCESS, false, false, false),
(P::READ_EXECUTE, true, false, true),
];
let pages = 2 * host_page() / GUEST_PAGE;
let mut memory = GuestMemory::new();
for page in 0..pages {
let fill = [page as u8 + 1; 0x1000];
let kind = kinds[page as usize % kinds.len()].0;
memory
.map_region_with_data(BASE + page * GUEST_PAGE, 0x1000, kind, &fill)
.unwrap();
}
for page in 0..pages {
let (_, read, write, execute) = kinds[page as usize % kinds.len()];
let fill = page as u8 + 1;
let first = BASE + page * GUEST_PAGE;
for address in [first, first + 0xFFF] {
let expected = |allowed, required| {
if allowed {
Ok(fill)
} else {
Err(violation(address, required))
}
};
assert_eq!(memory.read_u8(address), expected(read, "read"));
assert_eq!(
memory.fetch_instruction_byte(address),
expected(execute, "execute")
);
assert_eq!(
memory.write_u8(address, fill),
expected(write, "write").map(|_| ())
);
}
}
assert_eq!(memory.read_u8(BASE - 1), Err(unmapped(BASE - 1)));
let end = BASE + pages * GUEST_PAGE;
assert_eq!(memory.read_u8(end), Err(unmapped(end)));
}
#[test]
fn access_across_adjacent_guest_pages_lands_in_both() {
for boundary in boundaries() {
let mut memory = pages_around(boundary, P::READ_WRITE, Some(P::READ_WRITE));
memory
.write_u64(boundary - 3, 0x8877_6655_4433_2211)
.unwrap();
assert_eq!(memory.read_u64(boundary - 3), Ok(0x8877_6655_4433_2211));
// Little endian: three bytes below the boundary, five above it.
assert_eq!(
bytes_around(&memory, boundary),
(0x3322_115a_5a5a_5a5a, 0xa5a5_a588_7766_5544),
"boundary {boundary:#x}"
);
}
}
#[test]
fn crossing_into_an_unmapped_page_faults_at_its_first_byte() {
for boundary in boundaries() {
let mut memory = pages_around(boundary, P::READ_WRITE, None);
let fault = Err(unmapped(boundary));
for back in 1..8u64 {
let start = boundary - back;
let context = format!("boundary {boundary:#x}, start -{back}");
assert_eq!(memory.read_u64(start).map(|_| ()), fault, "{context}");
assert_eq!(memory.write_u64(start, 0), fault, "{context}");
assert_eq!(memory.write_u64_bypass(start, 0), fault, "{context}");
assert_eq!(memory.read_u64_bypass(start).map(|_| ()), fault);
}
for (back, width) in [(1u64, 2usize), (3, 4), (15, 16), (1, 0x1001)] {
let mut buffer = vec![0u8; width];
assert_eq!(memory.read_bytes(boundary - back, &mut buffer), fault);
assert_eq!(memory.write_bytes(boundary - back, &buffer), fault);
}
// The failed stores wrote nothing below the boundary, and the last
// access that fits still succeeds.
assert_eq!(memory.read_u64(boundary - 8), Ok(BELOW));
// An access that does not touch the mapped page faults at its own
// first byte.
assert_eq!(memory.read_u64(boundary).map(|_| ()), fault);
assert_eq!(
memory.read_u64(boundary + 5).map(|_| ()),
Err(unmapped(boundary + 5))
);
}
}
#[test]
fn starting_in_an_unmapped_page_faults_at_the_access_start() {
for boundary in boundaries() {
// Only the page above the boundary exists.
let mut memory = GuestMemory::new();
memory
.map_region_with_data(boundary, 0x1000, P::READ_WRITE, &[0xa5; 0x1000])
.unwrap();
for back in 1..8u64 {
let start = boundary - back;
assert_eq!(memory.read_u64(start).map(|_| ()), Err(unmapped(start)));
assert_eq!(memory.write_u64(start, 0), Err(unmapped(start)));
}
assert_eq!(memory.read_u64(boundary), Ok(ABOVE));
}
}
#[test]
fn crossing_into_a_page_without_the_right_faults_at_its_first_byte() {
for boundary in boundaries() {
// A store into a read-only page.
let mut memory = pages_around(boundary, P::READ_WRITE, Some(P::READ_ONLY));
for back in 1..8u64 {
assert_eq!(
memory.write_u64(boundary - back, 0),
Err(violation(boundary, "write")),
"boundary {boundary:#x}, start -{back}"
);
assert!(memory.read_u64(boundary - back).is_ok());
}
assert_eq!(bytes_around(&memory, boundary), (BELOW, ABOVE));
// A load from a page with no access.
let memory = pages_around(boundary, P::READ_ONLY, Some(P::NO_ACCESS));
for back in 1..8u64 {
assert_eq!(
memory.read_u64(boundary - back).map(|_| ()),
Err(violation(boundary, "read")),
"boundary {boundary:#x}, start -{back}"
);
}
assert_eq!(memory.read_u64(boundary - 8), Ok(BELOW));
}
}
#[test]
fn the_lowest_failing_byte_decides_the_fault() {
for boundary in boundaries() {
// Forbidden first page, unmapped second page: the first byte fails.
let mut memory = pages_around(boundary, P::READ_ONLY, None);
assert_eq!(
memory.write_u64(boundary - 4, 0),
Err(violation(boundary - 4, "write"))
);
assert_eq!(
memory.read_u64(boundary - 4).map(|_| ()),
Err(unmapped(boundary))
);
// Writable, then read-only, then unmapped: a store over all three
// stops at the read-only page, a load at the unmapped one.
let mut memory = pages_around(boundary, P::READ_WRITE, Some(P::READ_ONLY));
let mut buffer = vec![0u8; 0x1008];
assert_eq!(
memory.write_bytes(boundary - 4, &buffer),
Err(violation(boundary, "write"))
);
assert_eq!(
memory.read_bytes(boundary - 4, &mut buffer),
Err(unmapped(boundary + GUEST_PAGE))
);
assert_eq!(bytes_around(&memory, boundary), (BELOW, ABOVE));
}
}
#[test]
fn the_highest_guest_page_boundaries_do_not_wrap() {
// The last page that can be mapped ends one page below 2^64.
let top = u64::MAX - 0xFFF; // 0xffff_ffff_ffff_f000
let mut memory = pages_around(top, P::READ_WRITE, None);
assert_eq!(
memory.map_region(top, 0x1000, P::READ_WRITE),
Err(MemoryError::Overflow)
);
assert_eq!(memory.read_u64(top - 8), Ok(BELOW));
assert_eq!(memory.read_u64(top - 4).map(|_| ()), Err(unmapped(top)));
assert_eq!(memory.write_u64(top - 4, 0), Err(unmapped(top)));
// An access whose end passes 2^64 is an overflow wherever it starts.
assert_eq!(memory.read_u64(u64::MAX - 6), Err(MemoryError::Overflow));
assert_eq!(
memory.write_u64(u64::MAX - 6, 0),
Err(MemoryError::Overflow)
);
assert_eq!(memory.read_u64(top - 8), Ok(BELOW));
}
+5 -5
View File
@@ -5,7 +5,7 @@
//! Expected behavior follows x86-64 data access rules: an access is valid when
//! every byte it touches is mapped with the required permission, whether or not
//! it is aligned or crosses into an adjacent mapping. A faulting access changes
//! nothing.
//! nothing and reports the lowest address it may not touch (#175).
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P};
@@ -56,7 +56,7 @@ fn region_end_is_exclusive() {
lone.map_region(A, 0x1000, P::READ_ONLY).unwrap();
assert_eq!(
lone.read_u32(A + 0xFFD),
Err(MemoryError::UnmappedAddress(A + 0xFFD))
Err(MemoryError::UnmappedAddress(A + 0x1000))
);
assert_eq!(
lone.read_u8(A - 1),
@@ -90,7 +90,7 @@ fn spanning_into_a_gap_fails_without_partial_write() {
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
assert_eq!(
m.write_u64(A + 0xFFC, u64::MAX),
Err(MemoryError::UnmappedAddress(A + 0xFFC))
Err(MemoryError::UnmappedAddress(A + 0x1000))
);
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x1111_1111));
}
@@ -101,7 +101,7 @@ fn spanning_into_a_forbidden_region_fails_atomically() {
assert_eq!(
m.write_u64(A + 0xFFC, u64::MAX),
Err(MemoryError::PermissionViolation {
address: A + 0xFFC,
address: A + 0x1000,
required: "write"
})
);
@@ -123,7 +123,7 @@ fn loader_bypass_ignores_permissions_but_not_mapping() {
assert_eq!(m.read_u32(A), Ok(7));
assert_eq!(
m.write_u64_bypass(A + 0x1FFC, 0),
Err(MemoryError::UnmappedAddress(A + 0x1FFC))
Err(MemoryError::UnmappedAddress(A + 0x2000))
);
}
@@ -0,0 +1,233 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Synthetic guest calls through the standard import registry. Expectations use
//! Microsoft's public CloseHandle, DuplicateHandle and synchronization contracts:
//! https://learn.microsoft.com/windows/win32/api/handleapi/nf-handleapi-closehandle
//! https://learn.microsoft.com/windows/win32/api/handleapi/nf-handleapi-duplicatehandle
//! https://learn.microsoft.com/windows/win32/sync/synchronization-object-security-and-access-rights
//!
//! Capacity, rejected rights escalation and failed-output nonmutation are Xenora
//! subset policies, not claims about every Windows handle implementation. The
//! current runtime avoids stale aliases with increasing IDs, not generations.
mod support;
use support::{Guest, SCRATCH, SCRATCH_LEN};
use xenora_loader::memory::MemoryPermissions;
const IMPORTS: &[(&str, &str)] = &[
("kernel32.dll", "GetLastError"),
("kernel32.dll", "CreateEventW"),
("kernel32.dll", "CreateSemaphoreW"),
("kernel32.dll", "SetEvent"),
("kernel32.dll", "ReleaseSemaphore"),
("kernel32.dll", "WaitForSingleObject"),
("kernel32.dll", "CloseHandle"),
("kernel32.dll", "DuplicateHandle"),
("kernel32.dll", "GetCurrentThread"),
("kernel32.dll", "GetCurrentThreadId"),
("kernel32.dll", "GetThreadId"),
];
const CURRENT_PROCESS: u64 = u64::MAX;
const SAME_ACCESS: u64 = 2;
const MODIFY: u64 = 2;
const SYNCHRONIZE: u64 = 0x0010_0000;
const WAIT_TIMEOUT: u64 = 258;
const WAIT_FAILED: u64 = u32::MAX as u64;
const INVALID_HANDLE: u64 = 6;
const ACCESS_DENIED: u64 = 5;
const NOACCESS: u64 = 998;
const SENTINEL: u64 = 0xABCD_1234_5678_90EF;
// Xenora's bounded object table, not a Windows limit.
const CAPACITY: usize = 1024;
fn event(guest: &mut Guest) -> u64 {
let handle = guest.call("CreateEventW", &[0, 0, 0, 0]);
assert_ne!(handle, 0);
handle
}
fn duplicate(guest: &mut Guest, source: u64, output: u64, rights: u64, options: u64) -> u64 {
guest.call(
"DuplicateHandle",
&[
CURRENT_PROCESS,
source,
CURRENT_PROCESS,
output,
rights,
0,
options,
],
)
}
fn copy(guest: &mut Guest, source: u64, rights: u64, options: u64) -> u64 {
guest.memory.write_u64(SCRATCH, SENTINEL).unwrap();
assert_eq!(duplicate(guest, source, SCRATCH, rights, options), 1);
let handle = guest.u64_at(SCRATCH);
assert_ne!(handle, 0);
assert_ne!(handle, source);
assert_ne!(handle, SENTINEL);
handle
}
#[test]
fn reclaimed_capacity_never_revives_closed_handles() {
let mut guest = Guest::new(IMPORTS, &[]);
let handles: Vec<_> = (0..CAPACITY).map(|_| event(&mut guest)).collect();
assert_eq!(guest.call("CreateEventW", &[0, 0, 0, 0]), 0);
assert_eq!(guest.error(), 8); // ERROR_NOT_ENOUGH_MEMORY
// Release one slot at a time while the table stays otherwise full.
for old in handles {
assert_eq!(guest.call("CloseHandle", &[old]), 1);
let replacement = event(&mut guest);
assert_ne!(replacement, old);
assert_eq!(guest.call("SetEvent", &[old]), 0);
assert_eq!(guest.error(), INVALID_HANDLE);
assert_eq!(guest.call("CloseHandle", &[old]), 0);
assert_eq!(guest.error(), INVALID_HANDLE);
// Neither stale operation may signal or destroy the replacement.
assert_eq!(
guest.call("WaitForSingleObject", &[replacement, 0]),
WAIT_TIMEOUT
);
assert_eq!(guest.call("SetEvent", &[replacement]), 1);
assert_eq!(guest.call("WaitForSingleObject", &[replacement, 0]), 0);
}
}
#[test]
fn duplicates_share_signal_state_but_keep_independent_rights_and_lifetimes() {
let mut guest = Guest::new(IMPORTS, &[]);
let source = event(&mut guest);
let waiter = copy(&mut guest, source, SYNCHRONIZE, 0);
let setter = copy(&mut guest, source, MODIFY, 0);
assert_eq!(guest.call("SetEvent", &[waiter]), 0);
assert_eq!(guest.error(), ACCESS_DENIED);
assert_eq!(
guest.call("WaitForSingleObject", &[source, 0]),
WAIT_TIMEOUT
);
assert_eq!(guest.call("SetEvent", &[setter]), 1);
assert_eq!(guest.call("WaitForSingleObject", &[setter, 0]), WAIT_FAILED);
assert_eq!(guest.error(), ACCESS_DENIED);
// A denied wait must not consume the auto-reset event's signal.
assert_eq!(guest.call("WaitForSingleObject", &[waiter, 0]), 0);
assert_eq!(
guest.call("WaitForSingleObject", &[source, 0]),
WAIT_TIMEOUT
);
assert_eq!(guest.call("CloseHandle", &[source]), 1);
assert_eq!(guest.call("SetEvent", &[setter]), 1);
assert_eq!(guest.call("WaitForSingleObject", &[waiter, 0]), 0);
// SAME_ACCESS ignores desired access, and must retain the reduced rights.
let second_waiter = copy(&mut guest, waiter, u64::MAX, SAME_ACCESS);
assert_eq!(guest.call("CloseHandle", &[waiter]), 1);
assert_eq!(guest.call("SetEvent", &[second_waiter]), 0);
assert_eq!(guest.error(), ACCESS_DENIED);
assert_eq!(guest.call("SetEvent", &[setter]), 1);
assert_eq!(guest.call("CloseHandle", &[setter]), 1);
assert_eq!(guest.call("WaitForSingleObject", &[second_waiter, 0]), 0);
assert_eq!(
guest.call("WaitForSingleObject", &[second_waiter, 0]),
WAIT_TIMEOUT
);
assert_eq!(guest.call("CloseHandle", &[second_waiter]), 1);
}
#[test]
fn failed_duplicate_outputs_leave_memory_source_and_capacity_unchanged() {
let mut guest = Guest::new(IMPORTS, &[]);
let source = event(&mut guest);
let readonly = 0x6_0000;
guest
.memory
.map_region(readonly, 8, MemoryPermissions::READ_ONLY)
.unwrap();
guest
.memory
.write_u64(SCRATCH + SCRATCH_LEN - 8, SENTINEL)
.unwrap();
assert_eq!(guest.call("SetEvent", &[source]), 1);
for output in [0, readonly, 0xDEAD_0000, SCRATCH + SCRATCH_LEN - 4] {
// Repeated failures must not fill the table with unreachable duplicates.
for _ in 0..CAPACITY {
assert_eq!(duplicate(&mut guest, source, output, 0, SAME_ACCESS), 0);
assert_eq!(guest.error(), NOACCESS);
}
}
assert_eq!(guest.u64_at(readonly), 0);
assert_eq!(guest.u64_at(SCRATCH + SCRATCH_LEN - 8), SENTINEL);
assert_eq!(guest.call("WaitForSingleObject", &[source, 0]), 0);
assert_eq!(
guest.call("WaitForSingleObject", &[source, 0]),
WAIT_TIMEOUT
);
// All remaining slots must still be available after the failed calls.
for _ in 1..CAPACITY {
event(&mut guest);
}
assert_eq!(guest.call("CreateEventW", &[0, 0, 0, 0]), 0);
assert_eq!(guest.error(), 8);
}
#[test]
fn wrong_types_and_rights_escalation_preserve_objects_and_output() {
let mut guest = Guest::new(IMPORTS, &[]);
let source = event(&mut guest);
let semaphore = guest.call("CreateSemaphoreW", &[0, 1, 2, 0]);
assert_ne!(semaphore, 0);
assert_eq!(guest.call("SetEvent", &[semaphore]), 0);
assert_eq!(guest.error(), INVALID_HANDLE);
assert_eq!(guest.call("ReleaseSemaphore", &[source, 1, 0]), 0);
assert_eq!(guest.error(), INVALID_HANDLE);
for handle in [source, semaphore] {
assert_eq!(guest.call("GetThreadId", &[handle]), 0);
assert_eq!(guest.error(), INVALID_HANDLE);
}
assert_eq!(guest.call("WaitForSingleObject", &[semaphore, 0]), 0);
assert_eq!(
guest.call("WaitForSingleObject", &[semaphore, 0]),
WAIT_TIMEOUT
);
assert_eq!(
guest.call("WaitForSingleObject", &[source, 0]),
WAIT_TIMEOUT
);
let waiter = copy(&mut guest, source, SYNCHRONIZE, 0);
guest.memory.write_u64(SCRATCH, SENTINEL).unwrap();
assert_eq!(duplicate(&mut guest, waiter, SCRATCH, MODIFY, 0), 0);
assert_eq!(guest.error(), ACCESS_DENIED);
assert_eq!(guest.u64_at(SCRATCH), SENTINEL);
assert_eq!(guest.call("SetEvent", &[source]), 1);
assert_eq!(guest.call("WaitForSingleObject", &[waiter, 0]), 0);
assert_eq!(guest.call("CloseHandle", &[waiter]), 1);
assert_eq!(duplicate(&mut guest, waiter, SCRATCH, 0, SAME_ACCESS), 0);
assert_eq!(guest.error(), INVALID_HANDLE);
assert_eq!(guest.u64_at(SCRATCH), SENTINEL);
}
#[test]
fn thread_pseudo_handle_survives_real_duplicate_closure() {
let mut guest = Guest::new(IMPORTS, &[]);
let pseudo = guest.call("GetCurrentThread", &[]);
let id = guest.call("GetCurrentThreadId", &[]);
let first = copy(&mut guest, pseudo, 0x0800, 0); // THREAD_QUERY_LIMITED_INFORMATION
assert_eq!(guest.call("GetThreadId", &[first]), id);
assert_eq!(guest.call("CloseHandle", &[first]), 1);
let second = copy(&mut guest, pseudo, 0x0800, 0);
assert_ne!(first, second);
assert_eq!(guest.call("GetThreadId", &[first]), 0);
assert_eq!(guest.error(), INVALID_HANDLE);
assert_eq!(guest.call("GetThreadId", &[second]), id);
assert_eq!(guest.call("GetThreadId", &[pseudo]), id);
assert_eq!(guest.call("CloseHandle", &[second]), 1);
assert_eq!(guest.call("GetThreadId", &[pseudo]), id);
}
+2 -1
View File
@@ -70,7 +70,8 @@ uses a Win64-aligned stack and terminates with HLT. The result includes the load
guest memory and the entry execution outcome.
`xenora probe --mode static` inventories ordinary and delay-loaded PE imports
without guest execution. `missing_imports.csv` lists unresolved ordinary keys
without guest execution. Without `--report` it writes to `diagnostics/probe`,
where `xenora imports sync` also looks. `missing_imports.csv` lists unresolved ordinary keys
with their import address table relative virtual addresses. The full inventory,
`imports.csv`, marks each entry `ordinary` or `delayed` in its `import_table`
column and records whether each key is registered, its implementation
+6 -3
View File
@@ -17,10 +17,13 @@ python3 - <<'PY'
import json
from pathlib import Path
import subprocess
import sys
sys.stdout.reconfigure(encoding="utf-8")
executables = set()
for filename in ("native-build.jsonl", "native-tests.jsonl"):
for line in (Path("artifacts") / filename).read_text().splitlines():
for line in (Path("artifacts") / filename).read_text(encoding="utf-8").splitlines():
entry = json.loads(line)
if entry.get("executable"):
executables.add(entry["executable"])
@@ -32,11 +35,11 @@ if not executables:
raise SystemExit("No Cargo executable or loadable dependency artifacts found.")
for path in sorted(executables):
subprocess.run(["file", path], check=True)
archs = subprocess.check_output(["lipo", "-archs", path], text=True).strip()
archs = subprocess.check_output(["lipo", "-archs", path], encoding="utf-8").strip()
print(archs, flush=True)
if archs != "arm64":
raise SystemExit(f"Non-ARM64 build artifact: {path}")
linkage = subprocess.check_output(["otool", "-L", path], text=True)
linkage = subprocess.check_output(["otool", "-L", path], encoding="utf-8")
print(linkage, end="", flush=True)
if any(name in linkage.casefold() for name in ("vulkan", "moltenvk")):
raise SystemExit(f"Unexpected graphics linkage: {path}")
+112
View File
@@ -0,0 +1,112 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Exercise native audit JSON decoding and inspection under an ASCII locale."""
import json
import os
from pathlib import Path
import platform
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
SCRIPT = (ROOT / "scripts/audit/native.sh").read_text(encoding="utf-8")
AUDIT = SCRIPT.split("python3 - <<'PY'\n", 1)[1].rsplit("\nPY", 1)[0]
# Reader-only cases stop before the native executable inspection.
READER = AUDIT.split("\nif not executables:", 1)[0]
class NativeJsonTests(unittest.TestCase):
def run_audit(self, streams, code=READER):
with tempfile.TemporaryDirectory() as directory:
artifacts = Path(directory) / "artifacts"
artifacts.mkdir()
for name, payload in zip(
("native-build.jsonl", "native-tests.jsonl"), streams, strict=True
):
(artifacts / name).write_bytes(payload)
return subprocess.run(
[
sys.executable,
"-c",
"import locale\n"
"assert locale.getencoding().lower() in ('ascii', 'us-ascii')\n"
+ code
+ "\nprint(json.dumps(sorted(executables)))\n",
],
cwd=directory,
env={
**os.environ,
"LC_ALL": "C",
"PYTHONCOERCECLOCALE": "0",
"PYTHONUTF8": "0",
},
capture_output=True,
encoding="utf-8",
check=False,
)
def test_utf8_in_each_cargo_stream(self):
for stream in (0, 1):
with self.subTest(stream=stream):
entry = {
"executable": "/synthetic/caf\u00e9/bin",
"filenames": ["/synthetic/caf\u00e9/lib.dylib"],
"message": {"rendered": "synthetic diagnostic: \u03bb"},
}
streams = [b'{}\n', b'{}\n']
streams[stream] = (json.dumps(entry, ensure_ascii=False) + "\n").encode(
"utf-8"
)
result = self.run_audit(streams)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(
json.loads(result.stdout),
["/synthetic/caf\u00e9/bin", "/synthetic/caf\u00e9/lib.dylib"],
)
def test_ascii_streams_keep_deduplicated_artifacts(self):
entry = b'{"executable":"/synthetic/bin","filenames":["/synthetic/lib.so","/synthetic/lib.rlib"]}\n'
result = self.run_audit([entry, entry])
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(
json.loads(result.stdout), ["/synthetic/bin", "/synthetic/lib.so"]
)
def test_invalid_utf8_is_rejected(self):
result = self.run_audit([b'{"executable":"\xff"}\n', b'{}\n'])
self.assertNotEqual(result.returncode, 0)
self.assertIn("UnicodeDecodeError", result.stderr)
@unittest.skipUnless(
sys.platform == "darwin" and platform.machine() == "arm64",
"requires native ARM64 macOS inspection tools",
)
def test_native_inspection_of_unicode_path_under_ascii_locale(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
source = root / "fixture.c"
source.write_text("int main(void) { return 0; }\n", encoding="utf-8")
binary = root / "caf\u00e9"
subprocess.run(
["/usr/bin/clang", "-arch", "arm64", str(source), "-o", str(binary)],
check=True,
capture_output=True,
)
entry = (
json.dumps({"executable": str(binary)}, ensure_ascii=False) + "\n"
).encode("utf-8")
for stream in (0, 1):
with self.subTest(stream=stream):
streams = [b'{}\n', b'{}\n']
streams[stream] = entry
result = self.run_audit(streams, code=AUDIT)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn(str(binary), result.stdout)
self.assertIn("Checked 1 native executables", result.stdout)
if __name__ == "__main__":
unittest.main()