mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 11:40:43 +00:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8df13ae976 | ||
|
|
00eb6971e9 | ||
|
|
281d92bfb5 | ||
|
|
0115af5c04 | ||
|
|
5b7ffec90a | ||
|
|
48c5d20aa9 | ||
|
|
8049c36f51 | ||
|
|
c91036f879 | ||
|
|
adf10db015 | ||
|
|
d01627b3de |
No files matched your search
@@ -41,6 +41,8 @@ jobs:
|
||||
python3 crates/isa/generate_semantics.py --check
|
||||
python3 scripts/audit/semantic_coverage.py --check
|
||||
python3 scripts/audit/status.py --check
|
||||
# The generated status check must not depend on the host locale encoding.
|
||||
LC_ALL=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0 python3 scripts/audit/status.py --check
|
||||
for fixture in x2 x3 x4; do
|
||||
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
|
||||
done
|
||||
@@ -50,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
|
||||
@@ -65,7 +69,7 @@ jobs:
|
||||
cargo test --locked --workspace
|
||||
cargo test --locked --manifest-path experiments/x1/Cargo.toml
|
||||
scripts/audit/dependencies.sh
|
||||
scripts/audit/claims.sh
|
||||
LC_ALL=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0 scripts/audit/claims.sh
|
||||
- name: Inspect native CLI
|
||||
run: |
|
||||
cargo build --locked -p xenora
|
||||
|
||||
@@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Changed
|
||||
- Relocation reports now build their type histogram once per image, avoiding a tree lookup for every entry. Target checks and fixup order are unchanged; synthetic regressions and an opt-in relocation timing test cover the change (#109).
|
||||
- Moved the six supported gfx1030 SOPP compute control forms into the semantic registry, preserving instruction decoding and shader lowering. Part of #215.
|
||||
- Moved gfx1030 `s_mov_b32` (SOP1) into the semantic registry, preserving its existing decode domain and shader output. The move operand rule retains explicit VCC and EXEC half destinations. Part of #215.
|
||||
- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215.
|
||||
@@ -188,6 +189,7 @@ 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 import binding writing some slots before finding an unresolved import, and service calls taking effect before an unreadable return address was noticed. A service that changes a nonvolatile register, including XMM6 to XMM15, now stops the guest (part of #201).
|
||||
- Fixed older import-generator templates that reported success for unimplemented wrappers, used a nonexistent exit reason, and read floating-point arguments from integer registers.
|
||||
@@ -197,6 +199,7 @@ remains unsupported.
|
||||
- Fixed 32-bit guest stores and loads in the native DBT (MOV 89/8B and C7 /0), which accessed eight bytes: stores overwrote the next four guest bytes and accesses at the end of a mapping faulted. RIP-relative operands of byte moves and extensions, which were read as RBP-relative, and LEA with a segment prefix, which added the segment base, are fixed too.
|
||||
- Fixed an x86 prefix-length test that read an untracked fuzz artifact and so failed on every fresh checkout; its input is now inline.
|
||||
- Fixed agent-queue `apply_actions` crashing on comment-only decisions (claim refusals) by skipping no-op `gh issue edit` calls; accept `summary --now` after the subcommand; grant the audit job `pull-requests: read` so live audits can list open PRs (issue #180).
|
||||
- Fixed `scripts/audit/status.py` and the Python embedded in `scripts/audit/claims.sh` reading and writing tracked files in the process locale encoding instead of UTF-8: under an ASCII or cp1252 locale the status check crashed on `docs/claims.toml` or reported a spurious `xenora-progress.svg` difference. Both scripts now pass `encoding="utf-8"`, as the rest of `scripts/` does, the two write sites also pin `newline="\n"` so a Windows host cannot turn tracked LF files into CRLF when it regenerates them, and CI runs the two checks again under a non-UTF-8 locale so the requirement stays enforced.
|
||||
|
||||
- Generated CRT adapters now report unsupported calls when the required guest ABI or runtime behavior is missing.
|
||||
|
||||
|
||||
+234
-1
@@ -163,7 +163,6 @@ pub fn apply_relocations(
|
||||
let reloc_type = (entry_val >> 12) as u8;
|
||||
let offset_in_page = (entry_val & 0x0FFF) as u32;
|
||||
|
||||
*report.type_counts.entry(reloc_type).or_insert(0) += 1;
|
||||
report.total_entries += 1;
|
||||
|
||||
match reloc_type {
|
||||
@@ -221,6 +220,17 @@ pub fn apply_relocations(
|
||||
read_bytes += block_size as usize;
|
||||
}
|
||||
|
||||
// Only these two types can reach a successful return. Build the public
|
||||
// histogram once instead of searching its tree for every relocation.
|
||||
for (kind, count) in [
|
||||
(IMAGE_REL_BASED_ABSOLUTE, report.skipped_absolute),
|
||||
(IMAGE_REL_BASED_DIR64, report.applied_dir64),
|
||||
] {
|
||||
if count != 0 {
|
||||
report.type_counts.insert(kind, count);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
@@ -274,3 +284,226 @@ fn find_reloc_directory(
|
||||
Ok(Some((reloc_rva, reloc_size)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::memory::MemoryPermissions;
|
||||
use crate::pe::PeSection;
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
const PREFERRED: u64 = 0x140000000;
|
||||
const LOADED: u64 = PREFERRED + 0x200000;
|
||||
const DATA_RVA: u32 = 0x1000;
|
||||
const DIRECTORY_RVA: u32 = 0x10000000;
|
||||
const DIRECTORY_OFFSET: usize = 0x200;
|
||||
|
||||
// Original synthetic directory, laid out from Microsoft's PE Format,
|
||||
// .reloc section: eight-byte block headers and two-byte type/offset words.
|
||||
// https://learn.microsoft.com/windows/win32/debug/pe-format#the-reloc-section-image-only
|
||||
// Header fields and metadata are supplied directly: PE parsing is not timed.
|
||||
fn fixture(blocks: &[(u32, Vec<u16>)], data: &[u8]) -> (ParsedPe, Vec<u8>, GuestMemory) {
|
||||
let mut bytes = vec![0u8; DIRECTORY_OFFSET];
|
||||
bytes[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes());
|
||||
bytes[0x94..0x96].copy_from_slice(&240u16.to_le_bytes());
|
||||
bytes[0x104..0x108].copy_from_slice(&16u32.to_le_bytes());
|
||||
bytes[0x130..0x134].copy_from_slice(&DIRECTORY_RVA.to_le_bytes());
|
||||
for (page, entries) in blocks {
|
||||
bytes.extend_from_slice(&page.to_le_bytes());
|
||||
bytes.extend_from_slice(&(8u32 + entries.len() as u32 * 2).to_le_bytes());
|
||||
for entry in entries {
|
||||
bytes.extend_from_slice(&entry.to_le_bytes());
|
||||
}
|
||||
}
|
||||
let size = (bytes.len() - DIRECTORY_OFFSET) as u32;
|
||||
bytes[0x134..0x138].copy_from_slice(&size.to_le_bytes());
|
||||
let pe = ParsedPe {
|
||||
machine: 0x8664,
|
||||
number_of_sections: 1,
|
||||
time_date_stamp: 0,
|
||||
image_base: PREFERRED,
|
||||
section_alignment: 4096,
|
||||
file_alignment: 512,
|
||||
size_of_image: DIRECTORY_RVA + size.max(4096),
|
||||
size_of_headers: 512,
|
||||
entry_point_rva: 0,
|
||||
sections: vec![PeSection {
|
||||
name: ".reloc".into(),
|
||||
virtual_address: DIRECTORY_RVA,
|
||||
virtual_size: size,
|
||||
raw_data_ptr: DIRECTORY_OFFSET as u32,
|
||||
raw_data_size: size,
|
||||
characteristics: 0x40000040,
|
||||
permissions: MemoryPermissions::READ_ONLY,
|
||||
}],
|
||||
};
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
LOADED + u64::from(DATA_RVA),
|
||||
data.len(),
|
||||
MemoryPermissions::READ_ONLY,
|
||||
data,
|
||||
)
|
||||
.unwrap();
|
||||
(pe, bytes, memory)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_padding_and_rebases_read_only_targets() {
|
||||
for (preferred, initial, expected) in [
|
||||
(PREFERRED, 0x140001234, 0x140201234),
|
||||
(LOADED + 0x200000, 0x140001234, 0x13fe01234),
|
||||
(LOADED - 8, u64::MAX - 3, 4),
|
||||
(LOADED + 8, 3, u64::MAX - 4),
|
||||
] {
|
||||
let (mut pe, bytes, mut memory) =
|
||||
fixture(&[(DATA_RVA, vec![0x0fff, 0xa000])], &initial.to_le_bytes());
|
||||
pe.image_base = preferred;
|
||||
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
|
||||
assert_eq!(memory.read_u64(LOADED + 0x1000).unwrap(), expected);
|
||||
assert_eq!(report.total_entries, 2);
|
||||
assert_eq!(report.applied_dir64, 1);
|
||||
assert_eq!(report.skipped_absolute, 1);
|
||||
assert_eq!(report.type_counts, BTreeMap::from([(0, 1), (10, 1)]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn histogram_omits_types_that_did_not_occur() {
|
||||
for (entries, counts) in [
|
||||
(vec![], BTreeMap::new()),
|
||||
(vec![0x0fff, 0x0000], BTreeMap::from([(0, 2)])),
|
||||
(vec![0xa000, 0xa008], BTreeMap::from([(10, 2)])),
|
||||
] {
|
||||
let (pe, bytes, mut memory) = fixture(&[(DATA_RVA, entries)], &[0; 16]);
|
||||
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
|
||||
assert_eq!(report.type_counts, counts);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_duplicate_and_overlapping_entry_order() {
|
||||
let (pe, bytes, mut memory) = fixture(
|
||||
&[(DATA_RVA, vec![0xa000, 0xa000, 0xa004, 0x0000])],
|
||||
&[0; 16],
|
||||
);
|
||||
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
|
||||
// Two additions of 0x200000 at offset zero, then one at offset four.
|
||||
let mut actual = [0; 16];
|
||||
memory.read_bytes(LOADED + 0x1000, &mut actual).unwrap();
|
||||
assert_eq!(
|
||||
actual,
|
||||
[0, 0, 0x40, 0, 0, 0, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
||||
);
|
||||
assert_eq!(report.type_counts, BTreeMap::from([(0, 1), (10, 3)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_fields_observe_prior_carries_in_directory_order() {
|
||||
let initial = [255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0];
|
||||
for (entries, expected) in [
|
||||
(vec![0xa000, 0xa004], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]),
|
||||
(vec![0xa004, 0xa000], [0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]),
|
||||
] {
|
||||
let (mut pe, bytes, mut memory) = fixture(&[(DATA_RVA, entries)], &initial);
|
||||
pe.image_base = LOADED - 1;
|
||||
apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
|
||||
let mut actual = [0; 12];
|
||||
memory.read_bytes(LOADED + 0x1000, &mut actual).unwrap();
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_prior_writes_and_rejects_unsupported_types() {
|
||||
let (pe, bytes, mut memory) = fixture(&[(DATA_RVA, vec![0xa000, 0xf008])], &[0; 16]);
|
||||
assert_eq!(
|
||||
apply_relocations(&pe, &bytes, LOADED, &mut memory),
|
||||
Err(RelocationError::UnsupportedRelocationType(15))
|
||||
);
|
||||
assert_eq!(memory.read_u64(LOADED + 0x1000).unwrap(), 0x200000);
|
||||
assert_eq!(memory.read_u64(LOADED + 0x1008).unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_delta_keeps_the_empty_report_without_parsing() {
|
||||
let (mut pe, _, mut memory) = fixture(&[], &[0; 8]);
|
||||
pe.image_base = LOADED;
|
||||
assert_eq!(
|
||||
apply_relocations(&pe, &[], LOADED, &mut memory).unwrap(),
|
||||
RelocationReport::default()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual relocation timing run; release build on an otherwise idle host"]
|
||||
fn relocation_profile() {
|
||||
for pages in [1u32, 128] {
|
||||
for padding_every in [0usize, 2, 1] {
|
||||
let blocks: Vec<_> = (0..pages)
|
||||
.map(|page| {
|
||||
let entries = (0..512)
|
||||
.map(|slot| {
|
||||
let padding = padding_every != 0 && slot % padding_every == 0;
|
||||
(if padding { 0 } else { 0xa000 }) | (slot as u16 * 8)
|
||||
})
|
||||
.collect();
|
||||
(DATA_RVA + page * 4096, entries)
|
||||
})
|
||||
.collect();
|
||||
let (pe, bytes, initial) = fixture(&blocks, &vec![0; pages as usize * 4096]);
|
||||
let mut samples = Vec::new();
|
||||
for run in 0..36 {
|
||||
let mut memory = initial.clone();
|
||||
let start = Instant::now();
|
||||
let report = black_box(
|
||||
apply_relocations(
|
||||
black_box(&pe),
|
||||
black_box(&bytes),
|
||||
LOADED,
|
||||
black_box(&mut memory),
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
let elapsed = start.elapsed().as_secs_f64() * 1e6;
|
||||
assert_eq!(report.total_entries, pages as usize * 512);
|
||||
let padding = match padding_every {
|
||||
0 => 0,
|
||||
2 => report.total_entries / 2,
|
||||
_ => report.total_entries,
|
||||
};
|
||||
assert_eq!(report.skipped_absolute, padding);
|
||||
assert_eq!(report.applied_dir64, report.total_entries - padding);
|
||||
// Check every output against the fixture's independently specified pattern.
|
||||
for slot in 0..pages as usize * 512 {
|
||||
let expected = if padding_every != 0 && slot % padding_every == 0 {
|
||||
0
|
||||
} else {
|
||||
0x200000
|
||||
};
|
||||
assert_eq!(
|
||||
memory.read_u64(LOADED + 0x1000 + slot as u64 * 8).unwrap(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
if run >= 5 {
|
||||
samples.push(elapsed);
|
||||
}
|
||||
}
|
||||
samples.sort_by(f64::total_cmp);
|
||||
let mean = samples.iter().sum::<f64>() / samples.len() as f64;
|
||||
let variance =
|
||||
samples.iter().map(|s| (s - mean).powi(2)).sum::<f64>() / samples.len() as f64;
|
||||
println!(
|
||||
"pages={pages} padding_every={padding_every} n={} median_us={:.3} variance_us2={variance:.3} min_us={:.3} max_us={:.3}",
|
||||
samples.len(),
|
||||
samples[samples.len() / 2],
|
||||
samples[0],
|
||||
samples[samples.len() - 1]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import sys
|
||||
import tomllib
|
||||
|
||||
registry = Path("docs/claims.toml")
|
||||
claims = tomllib.loads(registry.read_text())["claim"]
|
||||
claims = tomllib.loads(registry.read_text(encoding="utf-8"))["claim"]
|
||||
classes = {}
|
||||
errors = []
|
||||
claim_id = re.compile(r"\bCLAIM-[A-Z0-9]+(?:-[A-Z0-9]+)*\b")
|
||||
@@ -37,10 +37,10 @@ files = [Path("README.md"), Path("AGENTS.md"), *Path("docs").rglob("*"),
|
||||
for source in files:
|
||||
if source == registry or source.suffix not in {".md", ".toml", ".rs"}:
|
||||
continue
|
||||
for reference in set(claim_id.findall(source.read_text())) - classes.keys():
|
||||
for reference in set(claim_id.findall(source.read_text(encoding="utf-8"))) - classes.keys():
|
||||
errors.append(f"{source}: unregistered {reference}")
|
||||
|
||||
status = tomllib.loads(Path("docs/status.toml").read_text())
|
||||
status = tomllib.loads(Path("docs/status.toml").read_text(encoding="utf-8"))
|
||||
for feature in status["feature"]:
|
||||
verification = feature.get("hardware_verification", "")
|
||||
if verification.casefold() != "verified":
|
||||
|
||||
@@ -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}")
|
||||
|
||||
@@ -18,7 +18,7 @@ def table(headers, rows):
|
||||
|
||||
|
||||
def replace_block(path, name, body, check):
|
||||
original = path.read_text()
|
||||
original = path.read_text(encoding="utf-8")
|
||||
start = f"<!-- status:{name}:start -->\n"
|
||||
stop = f"\n<!-- status:{name}:end -->"
|
||||
head, _, tail = original.partition(start)
|
||||
@@ -30,7 +30,7 @@ def replace_block(path, name, body, check):
|
||||
if check:
|
||||
print(f"{path}: status table differs from docs/status.toml", file=sys.stderr)
|
||||
return False
|
||||
path.write_text(updated)
|
||||
path.write_text(updated, encoding="utf-8", newline="\n")
|
||||
return True
|
||||
|
||||
|
||||
@@ -90,12 +90,12 @@ def render_progress(status):
|
||||
|
||||
|
||||
def check_asset(path, svg, check):
|
||||
if path.exists() and path.read_text() == svg:
|
||||
if path.exists() and path.read_text(encoding="utf-8") == svg:
|
||||
return True
|
||||
if check:
|
||||
print(f"{path}: progress graphic differs from docs/status.toml", file=sys.stderr)
|
||||
return False
|
||||
path.write_text(svg)
|
||||
path.write_text(svg, encoding="utf-8", newline="\n")
|
||||
return True
|
||||
|
||||
|
||||
@@ -105,8 +105,8 @@ def main():
|
||||
check = parser.parse_args().check
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
docs = root / "docs"
|
||||
status = tomllib.loads((docs / "status.toml").read_text())
|
||||
claims = tomllib.loads((docs / "claims.toml").read_text())
|
||||
status = tomllib.loads((docs / "status.toml").read_text(encoding="utf-8"))
|
||||
claims = tomllib.loads((docs / "claims.toml").read_text(encoding="utf-8"))
|
||||
classes = {claim["id"]: claim["class"] for claim in claims["claim"]}
|
||||
|
||||
features = table(
|
||||
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user