Compare commits

..
Author SHA1 Message Date
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 974d1fc62c ci: retrigger 2026-11-24 13:13:14 -06: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
12 changed files with 241 additions and 204 deletions

No files matched your search

-2
View File
@@ -52,8 +52,6 @@ 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,7 +35,6 @@
__pycache__/
*.pyc
/diagnostics/probe/
/diagnostics/gta6-candidate-*/
/diagnostics/gta6-check/
+1 -4
View File
@@ -10,10 +10,8 @@ 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,9 +21,9 @@ remains unsupported.
### Fixed
- 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 a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
### Added
- 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.
@@ -199,7 +197,6 @@ 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 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,10 +10,3 @@ 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 -1
View File
@@ -309,7 +309,7 @@ These require a Metal-capable Apple Silicon Mac.
scripts/test-gpu.sh
```
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths. The full semantic-review batch defaults to a 300-second timeout; set `XENORA_SEMANTIC_TIMEOUT` to raise or lower it for a slower or faster host. On macOS, the script uses a Python 3 fallback when GNU `timeout` is unavailable.
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths. The full semantic-review batch defaults to a 300-second timeout; set `XENORA_SEMANTIC_TIMEOUT` to raise or lower it for a slower or faster host.
### Verify guest execution
+2 -5
View File
@@ -6,9 +6,6 @@ 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") => {
@@ -49,7 +46,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 = DEFAULT_REPORT_DIR.to_string();
let mut report_dir = "diagnostics/gta6-candidate-e95020b2".to_string();
let mut i = 2;
while i < args.len() {
@@ -376,7 +373,7 @@ fn run_imports_generate_cli(args: &[String]) -> ExitCode {
}
fn run_imports_sync_cli(args: &[String]) -> ExitCode {
let mut report_dir = DEFAULT_REPORT_DIR.to_string();
let mut report_dir = "diagnostics/gta6-candidate-e95020b2".to_string();
let mut check_mode = false;
let mut i = 0;
-27
View File
@@ -1,27 +0,0 @@
// 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]);
}
@@ -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);
}
+1 -2
View File
@@ -70,8 +70,7 @@ 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. Without `--report` it writes to `diagnostics/probe`,
where `xenora imports sync` also looks. `missing_imports.csv` lists unresolved ordinary keys
without guest execution. `missing_imports.csv` lists unresolved ordinary keys
with their import address table relative virtual addresses. The full inventory,
`imports.csv`, marks each entry `ordinary` or `delayed` in its `import_table`
column and records whether each key is registered, its implementation
+3 -6
View File
@@ -17,13 +17,10 @@ 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(encoding="utf-8").splitlines():
for line in (Path("artifacts") / filename).read_text().splitlines():
entry = json.loads(line)
if entry.get("executable"):
executables.add(entry["executable"])
@@ -35,11 +32,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], encoding="utf-8").strip()
archs = subprocess.check_output(["lipo", "-archs", path], text=True).strip()
print(archs, flush=True)
if archs != "arm64":
raise SystemExit(f"Non-ARM64 build artifact: {path}")
linkage = subprocess.check_output(["otool", "-L", path], encoding="utf-8")
linkage = subprocess.check_output(["otool", "-L", path], text=True)
print(linkage, end="", flush=True)
if any(name in linkage.casefold() for name in ("vulkan", "moltenvk")):
raise SystemExit(f"Unexpected graphics linkage: {path}")
-37
View File
@@ -13,43 +13,6 @@ export CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-4}
# allow slower hosts to raise it without editing the script.
export XENORA_SEMANTIC_TIMEOUT=${XENORA_SEMANTIC_TIMEOUT:-300s}
# macOS does not ship GNU timeout. Python 3 is already a project requirement,
# so use a small POSIX-compatible fallback rather than making coreutils a
# prerequisite for the native suite.
if ! command -v timeout >/dev/null 2>&1; then
timeout() {
duration=$1
shift
python3 - "$duration" "$@" <<'PY'
import os
import re
import signal
import subprocess
import sys
text = sys.argv[1]
match = re.fullmatch(r"(\d+(?:\.\d+)?)([smh]?)", text)
if match is None:
print(f"timeout: invalid duration {text!r}", file=sys.stderr)
raise SystemExit(2)
seconds = float(match.group(1)) * {"": 1, "s": 1, "m": 60, "h": 3600}[match.group(2)]
try:
process = subprocess.Popen(sys.argv[2:], start_new_session=True)
except FileNotFoundError as error:
print(f"timeout: {error}", file=sys.stderr)
raise SystemExit(127)
try:
code = process.wait(timeout=seconds)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
print(f"timeout: command exceeded {seconds:g} seconds", file=sys.stderr)
raise SystemExit(124)
raise SystemExit(code)
PY
}
fi
cargo test --locked -p xenora-metal --features gpu-tests --test native_compute --no-run
timeout 30s cargo test --locked -p xenora-metal --features gpu-tests --test native_compute -- \
--nocapture --test-threads=1
-112
View File
@@ -1,112 +0,0 @@
# 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()