Compare commits

..
Author SHA1 Message Date
zachdoxsee fb6282ceb2 Merge upstream main into task/76-tls-pointer-array
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 21:16:38 +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
sahib453 782c49167c loader: give the thread a TLS pointer array separate from its data (#76)
The harness stores the thread's TLS base in the TEB's TLS pointer field,
and setup_tls mapped the thread's copy of the template at that address.
Compiled code indexes that pointer by the module's TLS index to find the
data block, so it took the first eight bytes of the template for the
block address.

- tls.rs: setup_tls maps a pointer array at the thread's TLS base and
  the data block one page above it, and stores the block address in the
  slot of the index it assigns. startup.rs is unchanged.
- tests/tls_layout.rs: follows the access sequence through guest memory
  for a template with zero fill, a rebased image and a zero-fill-only
  directory, and checks the image's template is left alone.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-25 00:17:10 +05:30
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
12 changed files with 555 additions and 10 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,7 +201,9 @@ remains unsupported.
native DBT.
### Fixed
- 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 thread's TLS pointer naming the TLS data itself (#76). Compiled code loads the pointer from the thread environment block, indexes it by the module's TLS index to get the address of the data block, and then adds a variable's offset; the loader had mapped the data where the pointer array belongs, so the first eight bytes of the template were used as the block address. `setup_tls` now maps a pointer array at the thread's TLS base and the data block one page above it, and stores the block address in the slot of the index it assigns. `crates/loader/tests/tls_layout.rs` follows that access sequence through guest memory for a template with zero fill, a rebased image and a zero-fill-only directory. The data block of the fixture harness can now be at most 60 KiB, down from 64 KiB, before it would meet the thread environment block. Alignment requests above 4 KiB and more than one module's TLS are not handled. The access sequence follows Microsoft's public PE Format page; nothing ran on Windows, and independent review is pending.
- Fixed the MXCSR flags of an unmasked floating-point overflow whose result is exact before the exponent is bounded, such as the largest binary32 value times two (#128). Only the overflow flag is set; the precision flag used to be set as well although nothing was rounded. A masked overflow still sets both flags and delivers infinity or the largest finite value, and an unmasked overflow that is also inexact still sets both. Five Intel SDM cases in `cpu_known_answers.rs` moved from open defect to verified on both engines, with three more for the other rounding modes, and the scalar and conversion sweeps now compare the precision flag in this case as well. Not compared with x86 hardware; awaiting independent review.
- Fixed the decoder refusing an instruction whose REX prefix is followed by a legacy prefix (#69). Such a REX is ignored, as the Intel SDM (Vol. 2A, 2.2.1) specifies, so `48 66 01 D8` now runs as `add ax, bx`; it used to stop the guest with an illegal-instruction exit. The ignored byte still counts toward the instruction's length, and a REX that directly precedes the opcode behaves as before. The interpreter, the DBT and the static probe share the decoder. One SDM-derived case in `cpu_known_answers.rs` moved from refused to verified and three were added, for an ignored REX.B, an ignored REX.W before a segment prefix, and a later REX that does apply. Two REX bytes in a row and the address-size prefix stay rejected. Not compared with x86 hardware; awaiting independent review.
- Fixed import binding writing some slots before finding an unresolved import, and service calls taking effect before an unreadable return address was noticed. A service that changes a nonvolatile register, including XMM6 to XMM15, now stops the guest (part of #201).
+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]);
}
+25 -4
View File
@@ -144,9 +144,20 @@ pub fn parse_tls_directory(bytes: &[u8], pe: &ParsedPe) -> Result<Option<TlsDire
}))
}
/// Bytes reserved at `thread_tls_base` for the thread's TLS pointer array.
const TLS_ARRAY_SIZE: usize = 0x1000;
/// Set up TLS runtime state in guest memory:
/// 1. Assign TLS index (e.g. 0) at `index_address`.
/// 2. Allocate and initialize per-thread TLS storage from the template.
/// 1. Assign TLS index 0 at `index_address`.
/// 2. Map the thread's TLS pointer array at `thread_tls_base`.
/// 3. Map the thread's data block one page above it, initialized from the
/// template and zero fill, and store its address in the array slot of the
/// index.
///
/// `thread_tls_base` is the value the thread environment block holds as its
/// TLS pointer. Compiled code loads that pointer, indexes it by the module's
/// TLS index to find the data block, and then adds a variable's offset, so the
/// array and the data are separate regions.
pub fn setup_tls(
tls: &TlsDirectory,
loaded_base: u64,
@@ -187,15 +198,25 @@ pub fn setup_tls(
memory.read_bytes(actual_start, &mut template_data)?;
}
// Allocate per-thread TLS block
// Allocate the pointer array and the per-thread TLS block.
let block_base = thread_tls_base
.checked_add(TLS_ARRAY_SIZE as u64)
.ok_or(MemoryError::Overflow)?;
let page_size = 4096;
let map_size = (total_size + page_size - 1) & !(page_size - 1);
memory.map_region_with_data(
memory.map_region(
thread_tls_base,
TLS_ARRAY_SIZE,
MemoryPermissions::READ_WRITE,
)?;
memory.map_region_with_data(
block_base,
map_size,
MemoryPermissions::READ_WRITE,
&template_data,
)?;
// Slot 0 belongs to the index assigned above.
memory.write_u64(thread_tls_base, block_base)?;
}
Ok(())
@@ -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);
}
+130
View File
@@ -0,0 +1,130 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Thread-local storage layout as compiled code reads it (#76).
//!
//! Microsoft's public PE Format page ("The .tls Section") describes the
//! access: load the address of the thread's TLS array from the thread
//! environment block, load the module's TLS index from the address the TLS
//! directory names, use the index times the pointer size as an offset into
//! the array to get the address of the module's data block, then add the
//! variable's offset in the template. The block starts as a copy of the
//! template followed by `SizeOfZeroFill` zero bytes.
//!
//! The startup harness stores the `thread_tls_base` it passes to `setup_tls`
//! in the TEB's TLS pointer field, so these tests start from that value and
//! follow the same steps through guest memory. The directory and template are
//! original. Nothing here ran on Windows.
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P, TlsDirectory, setup_tls};
const IMAGE: u64 = 0x1_4000_0000;
const TEMPLATE: u64 = IMAGE + 0x3000;
const INDEX: u64 = IMAGE + 0x4000;
const THREAD_TLS: u64 = 0x3_0000_0000;
/// Read as a pointer, the first eight bytes are the template's own address, so
/// a layout that takes the data for the array still finds readable memory.
const TEMPLATE_BYTES: [u8; 20] = [
0x00, 0x30, 0x00, 0x40, 0x01, 0x00, 0x00, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,
0xA1, 0xB2, 0xC3, 0xD4,
];
fn directory(template_len: u64, zero_fill: u32) -> TlsDirectory {
TlsDirectory {
raw_data_start_va: TEMPLATE,
raw_data_end_va: TEMPLATE + template_len,
index_address: INDEX,
size_of_zero_fill: zero_fill,
..TlsDirectory::default()
}
}
/// An image with the template in read-only data and a writable index that
/// does not start at zero.
fn image(base: u64) -> GuestMemory {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
TEMPLATE - IMAGE + base,
0x1000,
P::READ_ONLY,
&TEMPLATE_BYTES,
)
.unwrap();
memory
.map_region_with_data(INDEX - IMAGE + base, 0x1000, P::READ_WRITE, &[0xFF; 8])
.unwrap();
memory
}
/// The address of the module's data block, found the way compiled code does.
fn block_address(memory: &GuestMemory, teb_tls_pointer: u64, index_address: u64) -> u64 {
let index = u64::from(memory.read_u32(index_address).unwrap());
memory.read_u64(teb_tls_pointer + index * 8).unwrap()
}
#[test]
fn the_tls_array_slot_leads_to_a_copy_of_the_template() {
let mut memory = image(IMAGE);
setup_tls(&directory(20, 12), IMAGE, IMAGE, &mut memory, THREAD_TLS).unwrap();
assert_eq!(memory.read_u32(INDEX), Ok(0));
let block = block_address(&memory, THREAD_TLS, INDEX);
assert_ne!(block, THREAD_TLS, "the array is not the data block");
assert_ne!(block, TEMPLATE, "the block is the thread's own copy");
let mut data = [0xEEu8; 32];
memory.read_bytes(block, &mut data).unwrap();
assert_eq!(data[..20], TEMPLATE_BYTES);
assert_eq!(data[20..], [0u8; 12]);
}
#[test]
fn the_thread_block_is_writable_and_separate_from_the_template() {
let mut memory = image(IMAGE);
setup_tls(&directory(20, 12), IMAGE, IMAGE, &mut memory, THREAD_TLS).unwrap();
let block = block_address(&memory, THREAD_TLS, INDEX);
memory.write_u64(block + 8, 0x0102_0304_0506_0708).unwrap();
assert_eq!(memory.read_u64(block + 8), Ok(0x0102_0304_0506_0708));
// The image's template is the initial value for later threads.
let mut template = [0u8; 20];
memory.read_bytes(TEMPLATE, &mut template).unwrap();
assert_eq!(template, TEMPLATE_BYTES);
// The array slot still names the block after the block is written.
assert_eq!(block_address(&memory, THREAD_TLS, INDEX), block);
}
#[test]
fn a_rebased_image_uses_its_loaded_addresses() {
let loaded = IMAGE + 0x20_0000;
let mut memory = image(loaded);
setup_tls(&directory(20, 0), loaded, IMAGE, &mut memory, THREAD_TLS).unwrap();
let index_address = INDEX - IMAGE + loaded;
assert_eq!(memory.read_u32(index_address), Ok(0));
let block = block_address(&memory, THREAD_TLS, index_address);
let mut data = [0u8; 20];
memory.read_bytes(block, &mut data).unwrap();
assert_eq!(data, TEMPLATE_BYTES);
}
#[test]
fn a_zero_fill_only_directory_gets_a_zeroed_block() {
let mut memory = image(IMAGE);
setup_tls(&directory(0, 24), IMAGE, IMAGE, &mut memory, THREAD_TLS).unwrap();
let block = block_address(&memory, THREAD_TLS, INDEX);
let mut data = [0xEEu8; 24];
memory.read_bytes(block, &mut data).unwrap();
assert_eq!(data, [0u8; 24]);
}
#[test]
fn an_inverted_template_range_is_rejected_before_anything_is_mapped() {
let mut memory = image(IMAGE);
let mut inverted = directory(20, 0);
inverted.raw_data_end_va = TEMPLATE - 1;
assert!(setup_tls(&inverted, IMAGE, IMAGE, &mut memory, THREAD_TLS).is_err());
assert_eq!(
memory.read_u64(THREAD_TLS),
Err(MemoryError::UnmappedAddress(THREAD_TLS))
);
}
+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()