mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-28 13:41:12 +00:00
Compare commits
60
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
146d2dd467 | ||
|
|
a0d9b85dbf | ||
|
|
5366b93986 | ||
|
|
50c392111d | ||
|
|
f43a07ce31 | ||
|
|
10fd1cd4be | ||
|
|
95aa10c60f | ||
|
|
873b4fd4a9 | ||
|
|
120878de2d | ||
|
|
d26af53cef | ||
|
|
b6ebaaad5e | ||
|
|
aba82cdb77 | ||
|
|
44ac976291 | ||
|
|
d71efe0495 | ||
|
|
0bd8e19aac | ||
|
|
a1744a2754 | ||
|
|
e93509ef5b | ||
|
|
8344e299c9 | ||
|
|
433dc43695 | ||
|
|
a0f2d833aa | ||
|
|
61afca42c9 | ||
|
|
be19e4e28f | ||
|
|
33ccf7fd55 | ||
|
|
bb62353cfe | ||
|
|
1f2e7d3bb6 | ||
|
|
b5b646a58d | ||
|
|
4314071ac7 | ||
|
|
4e15e5f43b | ||
|
|
cf4010ba94 | ||
|
|
b9e6a9d365 | ||
|
|
a1a1020ebd | ||
|
|
e755ee94ed | ||
|
|
e289318132 | ||
|
|
f685b54e32 | ||
|
|
0690a3ecb4 | ||
|
|
7286989296 | ||
|
|
81a32e3ec6 | ||
|
|
8edf3abf53 | ||
|
|
0c397c5957 | ||
|
|
417b19c859 | ||
|
|
4cc703d566 | ||
|
|
5ae43a3cb8 | ||
|
|
0a17f0cb73 | ||
|
|
db80c0b3e3 | ||
|
|
db46390fa9 | ||
|
|
a9abc36eef | ||
|
|
972bc0a35c | ||
|
|
c0e90338d1 | ||
|
|
e32c85ff12 | ||
|
|
d409c26458 | ||
|
|
1fafc2e43f | ||
|
|
d6c9f846f0 | ||
|
|
43f8287c92 | ||
|
|
0236ec6ba9 | ||
|
|
52e7e3808d | ||
|
|
1c8d7a40de | ||
|
|
a6b0e89cac | ||
|
|
e856f080d1 | ||
|
|
b09d96fd62 | ||
|
|
6814d78230 |
No files matched your search
@@ -35,6 +35,19 @@ jobs:
|
||||
run: |
|
||||
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy
|
||||
rustc -vV
|
||||
- name: Install the Gate A2 C toolchain
|
||||
# crates/loader/tests/gate_a2.rs builds a hosted C program from source
|
||||
# with mingw-w64 and fails, never skips, when the compiler is missing.
|
||||
env:
|
||||
HOMEBREW_NO_AUTO_UPDATE: 1
|
||||
HOMEBREW_NO_INSTALL_CLEANUP: 1
|
||||
run: |
|
||||
brew install mingw-w64
|
||||
compiler="$(brew --prefix mingw-w64)/bin/x86_64-w64-mingw32-gcc"
|
||||
file -bL "$compiler" | grep arm64
|
||||
lipo -archs "$compiler" | grep arm64
|
||||
otool -L "$compiler"
|
||||
"$compiler" --version | head -1
|
||||
- name: Check generated status and PE fixtures
|
||||
run: |
|
||||
python3 crates/isa/generate_rdna2_meta.py --check
|
||||
|
||||
+27
-1
@@ -33,12 +33,33 @@ remains unsupported.
|
||||
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
|
||||
|
||||
### Fixed
|
||||
- Restored the DBT benchmark report-test fixture after the cache-invalidation counter was added. Its existing percentile, JSON and comparison tests now run in ordinary workspace CI instead of requiring a separate benchmark test-harness command.
|
||||
- DBT cache hits now compare an executable-generation token instead of rereading every instruction byte. Address-space or executable-memory changes trigger byte and execute-permission revalidation before a translation can be reused; changed code is retranslated. Ordinary data writes retain the fast path. Tests cover cloned spaces, loader bypass writes, split writes, remapping and bounded cache exhaustion. Same-dispatch self-modification and discarded-code reclamation remain unsupported.
|
||||
- Gate A2 checks the cross-compiler driver before invoking it, then checks its helpers before fixture compilation. CI also verifies the driver architecture before requesting its version.
|
||||
- Non-canonical 64-bit guest data addresses now raise `#GP` instead of a memory fault in both the interpreter and native DBT, including accesses that cross the canonical-address boundary. The synthetic architectural test is enabled again.
|
||||
- An instruction longer than 15 bytes now stops both engines with a general-protection fault instead of an illegal-instruction exit (#384; Intel SDM Vol. 3A, 7.15). The decoder still stops before fetching a 16th byte, and the DBT translates the faulting instruction on its own so the instructions before it in a block complete first. The `defect_overlong_instruction` known answer from #155 is now verified, with three more cases.
|
||||
- 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
|
||||
- Recorded the migrated PR integration decisions, native verification and scope exclusions in the testing documentation.
|
||||
- Added `xenora-bench startup` (#178), which measures Metal startup in fresh processes and in repeated
|
||||
submissions within one process, phase by phase (launch, device and queue, translation, library, pipeline,
|
||||
submission, GPU, readback), with median, p90, p99 and maximum. Every sample must produce the fixture's
|
||||
expected output, or the run stops without writing results. `docs/testing/benchmarks.md` records one
|
||||
release run on an Apple M4: a fresh process took about 43 ms (median), 36 ms of it creating the Metal
|
||||
device and queue, while repeated runs in one process needed about 0.2 ms of host submission. Measurement
|
||||
only; nothing was optimized.
|
||||
- Added an opt-in, budgeted staged upload for RGBA8 textures (#144). `MetalRgba8Texture::upload_staged` fills a
|
||||
Private-storage texture through one reused Shared staging buffer that never exceeds a `StagingBudget`. It
|
||||
copies whole-row bands with a blit encoder and reuses the buffer only after the previous command buffer has
|
||||
completed with status Completed. `plan_staged_upload` rejects missing, duplicate or out-of-range mip levels,
|
||||
wrong mip sizes, short row pitches or byte buffers, and budgets smaller than one row, all before any Metal
|
||||
object is created. A blit `read_back` returns any mip as tight RGBA8 bytes. On one Apple M4 under Metal API
|
||||
validation, readback matched independently built patterns for every level of a padded 37×19, six-level
|
||||
texture under four budgets, and matched the existing direct `upload`. Staging is slower than the direct path
|
||||
(2048² with 12 mips, release build: 2.1 ms direct, 2.7 ms with a 4 MiB budget, 17.8 ms with 256 KiB), so
|
||||
`upload` and its callers are unchanged. Not yet independently accepted.
|
||||
- The gfx1030 identification benchmark fixture now runs as an ordinary integration test, so workspace tests check LLVM-derived names, families, lengths and byte boundaries without invoking a timing run.
|
||||
- Added a CPU benchmark for gfx1030 metadata identification (#173). It verifies instruction boundaries on a mixed-family stream assembled with LLVM and reports first-pass and repeated-pass throughput.
|
||||
- Added a Win64 ABI regression showing that a service may write the caller-allocated shadow space. Existing negative controls cover nonvolatile XMM-register corruption; the unchanged-home-slot test now describes its handler rather than implying an ABI preservation requirement.
|
||||
@@ -48,10 +69,11 @@ remains unsupported.
|
||||
- Added opt-in shader IR common-subexpression elimination (`CompileOptions::eliminate_common_subexpressions` / `compile_with`) that reuses the first result of an equivalent pure vector unary or binary (#142). Equivalence is the same operation and the same operand values in the same order; constant operands match by bit pattern. Loads, stores, constant definitions, lane masks, merges, branches and other side-effecting or execution-mask-dependent ops are left in place. The pass runs after constant folding, so folded results stay constants and a later pure op on two equal folded constants can still be reused. Default `compile` keeps the historical IR. Covered by hand-derived known-answer compiler tests for reuse (and/xor, not, exact float add), for rejected loads, swapped subtracts, lane masks, lane merges and VCC selects, and for the four combinations with constant folding (1 + 2 = 3, and 1.0 + 2.0 = 3.0), and a check that the 13 golden fixtures, none of which repeats an expression, compile unchanged with the pass on. No speedup is claimed.
|
||||
- The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review.
|
||||
- Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify 16-byte-aligned call entry (`RSP % 16 == 8`), caller-owned 32-byte shadow space accessibility/integrity, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
|
||||
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify stack alignment before CALL and at callee entry (`RSP % 16 == 8`), accessibility of the caller-allocated 32-byte shadow space, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
|
||||
- `dbt_bench` can compare two of its JSON documents when `XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json>` is set (#114). It prints each median with its change and whether the change exceeds the larger recorded IQR, and lists changed DBT counters. It refuses, with exit status 1 and the differing field named, to compare runs from different CPUs, operating systems or architectures, with unknown host fields, or with different workloads, sample counts, debug assertions or build labels. A new optional `XENORA_DBT_BENCH_BUILD_LABEL` records build settings the benchmark cannot see, such as LTO. No benchmark runs in this mode.
|
||||
- LAHF and SAHF run in both engines, and guest CPUID reports them in leaf `8000_0001h`, ECX bit 0 (#387; Intel SDM Vol. 2A LAHF, Vol. 2B SAHF). The DBT runs them through the shared semantics. The four known answers from #155 that both engines refused are now verified, with twelve more cases, and the independent reference in `tests/x86_integer.rs` covers both instructions.
|
||||
- LOOP, LOOPE, LOOPNE and JRCXZ run in both engines (#396; Intel SDM Vol. 2A, LOOP/LOOPcc and Jcc). The count is RCX; the address-size prefix stays rejected, so JECXZ and the ECX-counted forms are still refused. The DBT runs them through the shared semantics and ends its block at each. The three known answers from #155 that both engines refused are now verified, with eleven more cases, and `tests/cpu_loop.rs` checks a loop that spans translated blocks against a step-by-step model for every count, ZF match point and step budget.
|
||||
- Added checked, per-mip copy footprints for synthetic block-compressed texture arrays. Contributors can pack tight block rows or repack entire chains with independent row and placement alignment, and pass selected BC1–BC5 levels to the existing Metal readers (#391).
|
||||
- `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=<path>` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged.
|
||||
- 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).
|
||||
@@ -129,10 +151,14 @@ remains unsupported.
|
||||
|
||||
- Added nested guest directories and checked file deletion on the synthetic drive.
|
||||
|
||||
- Added the second Gate A milestone, A2 (#419): an original hosted C program, `tests/compat_fixtures/gate_a2.c`, built from source by the new test `crates/loader/tests/gate_a2.rs` with the mingw-w64 C runtime (UCRT) and run through the loader, the standard services and the ARM64 DBT. The runtime's own startup code runs before `main`. The program takes `argc` and `argv`, sorts heap data with `qsort`, prints with `printf`, writes a report with `fprintf` and reads it back with `fgets`, registers a function with `atexit` and returns from `main`. At `-O0`, `-O1`, `-O2` and `-Os` it ends with exit status 0, and its captured output and its report match, byte for byte, text recomputed in Rust. Seven more tests cover other arguments, four wrong command lines, a step budget that is too small, and control variants that end in a failed check, in `exit(42)` and in `abort()`. The test needs mingw-w64 on the host and fails, not skips, without it, so the CI workflow now installs it. Nothing from mingw-w64 is stored in the repository. Local runs used mingw-w64 14.0.0 with GCC 16.2.0. This is one program and one C runtime, compared by hand with a native build of the same source and not with Windows or x86 hardware; `docs/testing/gate-a.md` lists what it does not show. Awaiting independent review.
|
||||
|
||||
- Added file seeking and end-of-file resizing on the synthetic guest drive.
|
||||
|
||||
- Added a bounded synthetic guest drive with synchronous file open, read, write, and size queries.
|
||||
|
||||
- Added files for a hosted C program (#402, part of Gate A2): `fopen`, `fclose`, `fgets` and `perror`, and file streams for the output services from #400, so `fprintf`, `fwrite` and `fputs` write to a file `fopen` returned. The files are the ones on the in-memory `C:` drive behind `CreateFileW`, so a file written through a C stream is the file `ReadFile` reads, and the reverse. `fopen` takes `r`, `w` or `a` with `+`, `b` and `t` as Microsoft's page describes them; text mode, the default, stores a line feed as carriage return and line feed, reads the pair back as a line feed and ends input at `CTRL+Z`. Failures return their documented results; the `errno` values beyond `EINVAL` for a null or empty argument are Xenora's choice. Nothing is buffered, there is no seeking, a C stream takes no part in Win32 sharing, and the other mode characters are refused. All four services are `partial`. Eight tests in `runtime_services.rs`, four in the new `crt_files.rs` that cross-check with `ReadFile` and `WriteFile`, and a unit test of the mode strings cover it. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added unnamed guest semaphores with checked release and immediate mixed-object waits.
|
||||
|
||||
- Added non-alertable extended event waits through both Win64 wait APIs.
|
||||
|
||||
+17
-2
@@ -162,10 +162,21 @@ struct BatchResult {
|
||||
pipelined: Stats,
|
||||
}
|
||||
|
||||
mod startup;
|
||||
mod startup_report;
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
// Taken before anything else so a fresh startup child can report the time
|
||||
// from its parent's spawn to `main`.
|
||||
let entered = SystemTime::now();
|
||||
let mut args = std::env::args().skip(1).peekable();
|
||||
match args.peek().map(String::as_str) {
|
||||
Some("startup") => return startup::run(args.skip(1)),
|
||||
Some("startup-child") => return startup::child(entered, args.skip(1)),
|
||||
_ => {}
|
||||
}
|
||||
let mut output = PathBuf::from("benchmarks/results");
|
||||
let mut reps = DEFAULT_REPS;
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"--output" => {
|
||||
@@ -179,7 +190,11 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
.map_err(|_| "--reps must be a positive integer")?;
|
||||
}
|
||||
"--help" | "-h" => {
|
||||
println!("usage: xenora-bench [--output DIR] [--reps N]");
|
||||
println!(
|
||||
"usage: xenora-bench [--output DIR] [--reps N]\n \
|
||||
xenora-bench startup [--fixture NAME] [--words N] [--processes N] \
|
||||
[--reps N] [--output DIR]"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
other => return Err(format!("unknown argument {other}").into()),
|
||||
|
||||
@@ -0,0 +1,405 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Metal startup distributions: fresh processes versus repeated submissions (#178).
|
||||
//!
|
||||
//! `xenora-bench startup` checks one manifest fixture against the independent
|
||||
//! reference, then measures it two ways:
|
||||
//!
|
||||
//! - **Fresh process.** It launches its own executable `--processes` times. Each
|
||||
//! child creates the Metal device and queue, translates the fixture, runs it
|
||||
//! once with `run_words_profiled`, checks the output and prints one sample line.
|
||||
//! - **Repeated.** In this process it creates one device, then translates and runs
|
||||
//! the same fixture `--reps` times. The first run is reported on its own.
|
||||
//!
|
||||
//! Every sample must produce the expected words. One wrong output, failed child or
|
||||
//! unparsable sample line stops the run before anything is written. The
|
||||
//! numbers describe this host only; two distributions do not explain each other.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, ENTRY_POINT, compile};
|
||||
|
||||
use crate::startup_report::Report;
|
||||
use crate::{Fixture, Metadata, expand, parse_manifest, percentile, slug};
|
||||
|
||||
const DEFAULT_PROCESSES: usize = 30;
|
||||
const DEFAULT_REPS: usize = 100;
|
||||
/// A fresh process that has not exited by then is killed and fails the run.
|
||||
const CHILD_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Phases of one run, in seconds. `spawn_to_main` exists only for fresh processes.
|
||||
pub(crate) const PHASES: [&str; 8] = [
|
||||
"spawn_to_main",
|
||||
"device",
|
||||
"translate",
|
||||
"library",
|
||||
"pipeline",
|
||||
"submit",
|
||||
"gpu",
|
||||
"readback",
|
||||
];
|
||||
|
||||
/// One run's phase timings, indexed like [`PHASES`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Default)]
|
||||
pub(crate) struct Sample(pub(crate) [f64; PHASES.len()]);
|
||||
|
||||
impl Sample {
|
||||
fn line(&self) -> String {
|
||||
let fields: Vec<String> = PHASES
|
||||
.iter()
|
||||
.zip(self.0)
|
||||
.map(|(name, value)| format!("{name}={value:e}"))
|
||||
.collect();
|
||||
format!("startup-sample {}", fields.join(" "))
|
||||
}
|
||||
|
||||
/// Parses exactly the line [`Sample::line`] prints: every phase once, in order.
|
||||
pub(crate) fn parse(line: &str) -> Result<Self, String> {
|
||||
let rest = line
|
||||
.strip_prefix("startup-sample ")
|
||||
.ok_or("missing startup-sample prefix")?;
|
||||
let fields: Vec<&str> = rest.split(' ').collect();
|
||||
if fields.len() != PHASES.len() {
|
||||
return Err(format!(
|
||||
"expected {} fields, got {}",
|
||||
PHASES.len(),
|
||||
fields.len()
|
||||
));
|
||||
}
|
||||
let mut sample = Self::default();
|
||||
for (i, (field, name)) in fields.iter().zip(PHASES).enumerate() {
|
||||
let value = field
|
||||
.strip_prefix(name)
|
||||
.and_then(|v| v.strip_prefix('='))
|
||||
.ok_or_else(|| format!("field {i} is not {name}=<seconds>"))?;
|
||||
let value: f64 = value.parse().map_err(|_| format!("bad {name} value"))?;
|
||||
if !value.is_finite() || value < 0.0 {
|
||||
return Err(format!("{name} must be finite and non-negative"));
|
||||
}
|
||||
sample.0[i] = value;
|
||||
}
|
||||
Ok(sample)
|
||||
}
|
||||
}
|
||||
|
||||
/// Median, tail and extremes of one phase.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub(crate) struct Summary {
|
||||
pub(crate) n: usize,
|
||||
pub(crate) min: f64,
|
||||
pub(crate) median: f64,
|
||||
pub(crate) p90: f64,
|
||||
pub(crate) p99: f64,
|
||||
pub(crate) max: f64,
|
||||
}
|
||||
|
||||
pub(crate) fn summarize(values: &[f64]) -> Option<Summary> {
|
||||
if values.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut sorted = values.to_vec();
|
||||
sorted.sort_by(f64::total_cmp);
|
||||
Some(Summary {
|
||||
n: sorted.len(),
|
||||
min: sorted[0],
|
||||
median: percentile(&sorted, 0.5),
|
||||
p90: percentile(&sorted, 0.9),
|
||||
p99: percentile(&sorted, 0.99),
|
||||
max: sorted[sorted.len() - 1],
|
||||
})
|
||||
}
|
||||
|
||||
struct Options {
|
||||
fixture: Option<String>,
|
||||
words: Option<usize>,
|
||||
processes: usize,
|
||||
reps: usize,
|
||||
output: PathBuf,
|
||||
}
|
||||
|
||||
fn count(value: Option<String>, flag: &str) -> Result<usize, String> {
|
||||
let n: usize = value
|
||||
.ok_or_else(|| format!("{flag} needs a count"))?
|
||||
.parse()
|
||||
.map_err(|_| format!("{flag} must be a positive integer"))?;
|
||||
if n == 0 {
|
||||
return Err(format!("{flag} must be at least 1"));
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn parse_options(mut args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
let mut options = Options {
|
||||
fixture: None,
|
||||
words: None,
|
||||
processes: DEFAULT_PROCESSES,
|
||||
reps: DEFAULT_REPS,
|
||||
output: PathBuf::from("artifacts/startup"),
|
||||
};
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"--fixture" => options.fixture = Some(args.next().ok_or("--fixture needs a name")?),
|
||||
"--words" => options.words = Some(count(args.next(), "--words")?),
|
||||
"--processes" => options.processes = count(args.next(), "--processes")?,
|
||||
"--reps" => options.reps = count(args.next(), "--reps")?,
|
||||
"--output" => {
|
||||
options.output = PathBuf::from(args.next().ok_or("--output needs a path")?);
|
||||
}
|
||||
other => return Err(format!("unknown startup argument {other}")),
|
||||
}
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
/// The fixture to time and its word count, after the reference agrees with it.
|
||||
fn select(options: &Options) -> Result<(Fixture, usize), Box<dyn Error>> {
|
||||
let fixtures = parse_manifest(&fs::read_to_string("benchmarks/manifest.toml")?)?;
|
||||
let fixture = match &options.fixture {
|
||||
Some(name) => fixtures.into_iter().find(|f| &f.name == name),
|
||||
None => fixtures.into_iter().next(),
|
||||
}
|
||||
.ok_or("fixture not found in benchmarks/manifest.toml")?;
|
||||
let code = fs::read(&fixture.path)?;
|
||||
let reference = xenora_ref::execute(&code, &fixture.input).map_err(|e| e.to_string())?;
|
||||
if reference != fixture.expected {
|
||||
return Err("reference disagrees with hand-derived expected values".into());
|
||||
}
|
||||
let words = options
|
||||
.words
|
||||
.unwrap_or_else(|| *fixture.sizes.first().unwrap_or(&fixture.input.len()));
|
||||
Ok((fixture, words))
|
||||
}
|
||||
|
||||
/// Translates and runs the fixture once on `metal`, checking the output.
|
||||
fn run_once(
|
||||
metal: &NativeCompute,
|
||||
fixture: &Fixture,
|
||||
words: usize,
|
||||
sample: &mut Sample,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
let input = expand(&fixture.input, words);
|
||||
let expected = expand(&fixture.expected, words);
|
||||
let start = Instant::now();
|
||||
let code = fs::read(&fixture.path)?;
|
||||
let compiled = compile(Architecture::Gfx1030, &code).map_err(|e| e.to_string())?;
|
||||
sample.0[2] = start.elapsed().as_secs_f64();
|
||||
let profile = metal
|
||||
.run_words_profiled(&compiled.msl, ENTRY_POINT, &input)
|
||||
.map_err(|e| e.to_string())?;
|
||||
if profile.output != expected {
|
||||
return Err(format!("{} output disagrees with known answers", fixture.name).into());
|
||||
}
|
||||
sample.0[3] = profile.library_seconds;
|
||||
sample.0[4] = profile.pipeline_seconds;
|
||||
sample.0[5] = profile.host_seconds - profile.library_seconds - profile.pipeline_seconds;
|
||||
sample.0[6] = profile.gpu_seconds;
|
||||
sample.0[7] = profile.readback_seconds;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn unix_nanos(time: SystemTime) -> u128 {
|
||||
time.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_nanos())
|
||||
}
|
||||
|
||||
/// Entry point of one fresh child process, called first thing in `main`.
|
||||
///
|
||||
/// `entered` is the wall-clock time at `main`; the parent passes the wall-clock
|
||||
/// time just before it spawned this process.
|
||||
pub(crate) fn child(
|
||||
entered: SystemTime,
|
||||
mut args: impl Iterator<Item = String>,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
let spawned: u128 = args.next().ok_or("missing spawn time")?.parse()?;
|
||||
let options = parse_options(args)?;
|
||||
let (fixture, words) = select(&options)?;
|
||||
let mut sample = Sample::default();
|
||||
sample.0[0] = unix_nanos(entered).saturating_sub(spawned) as f64 / 1e9;
|
||||
let start = Instant::now();
|
||||
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
|
||||
sample.0[1] = start.elapsed().as_secs_f64();
|
||||
run_once(&metal, &fixture, words, &mut sample)?;
|
||||
println!("{}", sample.line());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn forwarded(fixture: &Fixture, words: usize) -> Vec<String> {
|
||||
vec![
|
||||
"--fixture".into(),
|
||||
fixture.name.clone(),
|
||||
"--words".into(),
|
||||
words.to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
/// Runs one fresh child and returns its spawn-to-exit wall time and stdout.
|
||||
///
|
||||
/// The child inherits this process's environment on purpose, so its `MTL_*`
|
||||
/// validation settings are the ones the run's metadata records.
|
||||
fn spawn_child(
|
||||
exe: &std::path::Path,
|
||||
fixture: &Fixture,
|
||||
words: usize,
|
||||
) -> Result<(f64, String), Box<dyn Error>> {
|
||||
let started = Instant::now();
|
||||
let spawned = unix_nanos(SystemTime::now());
|
||||
let mut child = Command::new(exe)
|
||||
.arg("startup-child")
|
||||
.arg(spawned.to_string())
|
||||
.args(forwarded(fixture, words))
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()?;
|
||||
// Drain both pipes while waiting, so a child that writes more than a pipe
|
||||
// buffer (validation logs, for example) cannot block and look like a hang.
|
||||
let drain = |pipe: Option<Box<dyn std::io::Read + Send>>| {
|
||||
std::thread::spawn(move || {
|
||||
let mut text = String::new();
|
||||
if let Some(mut pipe) = pipe {
|
||||
let _ = pipe.read_to_string(&mut text);
|
||||
}
|
||||
text
|
||||
})
|
||||
};
|
||||
let out = drain(child.stdout.take().map(|p| Box::new(p) as _));
|
||||
let err = drain(child.stderr.take().map(|p| Box::new(p) as _));
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
if started.elapsed() > CHILD_TIMEOUT {
|
||||
child.kill()?;
|
||||
child.wait()?;
|
||||
return Err(format!("no exit within {} s", CHILD_TIMEOUT.as_secs()).into());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
};
|
||||
let seconds = started.elapsed().as_secs_f64();
|
||||
let stdout = out.join().map_err(|_| "stdout reader panicked")?;
|
||||
let stderr = err.join().map_err(|_| "stderr reader panicked")?;
|
||||
if !status.success() {
|
||||
return Err(format!("{status}: {}", stderr.trim()).into());
|
||||
}
|
||||
Ok((seconds, stdout))
|
||||
}
|
||||
|
||||
/// Runs both regimes and writes `startup.json` and `report.md`.
|
||||
pub(crate) fn run(args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>> {
|
||||
let options = parse_options(args)?;
|
||||
let (fixture, words) = select(&options)?;
|
||||
let exe = std::env::current_exe()?;
|
||||
|
||||
let mut fresh = Vec::with_capacity(options.processes);
|
||||
let mut wall = Vec::with_capacity(options.processes);
|
||||
for i in 0..options.processes {
|
||||
let (seconds, stdout) = spawn_child(&exe, &fixture, words)
|
||||
.map_err(|e| format!("fresh process {i} failed: {e}"))?;
|
||||
wall.push(seconds);
|
||||
let line = stdout
|
||||
.lines()
|
||||
.find(|l| l.starts_with("startup-sample "))
|
||||
.ok_or_else(|| format!("fresh process {i} printed no sample"))?;
|
||||
fresh.push(Sample::parse(line).map_err(|e| format!("fresh process {i}: {e}"))?);
|
||||
}
|
||||
|
||||
let mut first = Sample::default();
|
||||
let start = Instant::now();
|
||||
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
|
||||
first.0[1] = start.elapsed().as_secs_f64();
|
||||
run_once(&metal, &fixture, words, &mut first)?;
|
||||
let mut repeated = Vec::with_capacity(options.reps);
|
||||
for _ in 0..options.reps {
|
||||
let mut sample = Sample::default();
|
||||
run_once(&metal, &fixture, words, &mut sample)?;
|
||||
repeated.push(sample);
|
||||
}
|
||||
|
||||
let metadata = Metadata::collect(&metal.device_name(), options.reps);
|
||||
let dir = options
|
||||
.output
|
||||
.join(slug(&metadata.device))
|
||||
.join(&metadata.run_id);
|
||||
fs::create_dir_all(&dir)?;
|
||||
fs::write(dir.join("metadata.json"), metadata.to_json())?;
|
||||
let report = Report {
|
||||
fixture: &fixture.name,
|
||||
words,
|
||||
fresh: &fresh,
|
||||
wall: &wall,
|
||||
first: &first,
|
||||
repeated: &repeated,
|
||||
};
|
||||
fs::write(dir.join("startup.json"), report.json())?;
|
||||
let markdown = report.markdown(&metadata);
|
||||
fs::write(dir.join("report.md"), &markdown)?;
|
||||
println!("{markdown}");
|
||||
println!("Startup results written to {}", dir.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sample_lines_round_trip() {
|
||||
let sample = Sample([0.5, 1e-3, 2.5e-4, 0.0, 7.0, 1e-9, 3.25, 42.0]);
|
||||
assert_eq!(Sample::parse(&sample.line()), Ok(sample));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sample_lines_reject_damaged_input() {
|
||||
let line = Sample([1.0; PHASES.len()]).line();
|
||||
assert!(Sample::parse(&line.replacen("startup-sample", "sample", 1)).is_err());
|
||||
assert!(Sample::parse(&line.replacen("device=", "devise=", 1)).is_err());
|
||||
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=-1e0", 1)).is_err());
|
||||
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=NaN", 1)).is_err());
|
||||
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=x", 1)).is_err());
|
||||
assert!(Sample::parse(line.rsplit_once(' ').unwrap().0).is_err());
|
||||
assert!(Sample::parse(&format!("{line} extra=1")).is_err());
|
||||
// Phases out of order are refused even when every name is present.
|
||||
let swapped = line
|
||||
.replacen("device=", "TMP=", 1)
|
||||
.replacen("translate=", "device=", 1)
|
||||
.replacen("TMP=", "translate=", 1);
|
||||
assert!(Sample::parse(&swapped).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summary_uses_interpolated_percentiles() {
|
||||
// 1..=100: position 0.9 * 99 = 89.1 lies between 90 and 91, and
|
||||
// 0.99 * 99 = 98.01 between 99 and 100.
|
||||
let values: Vec<f64> = (1..=100).rev().map(f64::from).collect();
|
||||
let s = summarize(&values).unwrap();
|
||||
assert_eq!((s.n, s.min, s.max), (100, 1.0, 100.0));
|
||||
assert!((s.median - 50.5).abs() < 1e-9);
|
||||
assert!((s.p90 - 90.1).abs() < 1e-9);
|
||||
assert!((s.p99 - 99.01).abs() < 1e-9);
|
||||
assert_eq!(summarize(&[]), None);
|
||||
let one = summarize(&[3.0]).unwrap();
|
||||
assert_eq!(
|
||||
(one.median, one.p90, one.p99, one.max),
|
||||
(3.0, 3.0, 3.0, 3.0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_reject_bad_counts_and_flags() {
|
||||
let parse = |args: &[&str]| parse_options(args.iter().map(|s| s.to_string()));
|
||||
let defaults = parse(&[]).unwrap();
|
||||
assert_eq!(
|
||||
(defaults.processes, defaults.reps),
|
||||
(DEFAULT_PROCESSES, DEFAULT_REPS)
|
||||
);
|
||||
let set = parse(&["--processes", "3", "--reps", "5", "--words", "64"]).unwrap();
|
||||
assert_eq!((set.processes, set.reps, set.words), (3, 5, Some(64)));
|
||||
assert!(parse(&["--processes", "0"]).is_err());
|
||||
assert!(parse(&["--reps", "-1"]).is_err());
|
||||
assert!(parse(&["--words"]).is_err());
|
||||
assert!(parse(&["--fast"]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! JSON and markdown output of `xenora-bench startup` (#178).
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use crate::startup::{PHASES, Sample, Summary, summarize};
|
||||
use crate::{Metadata, json_str};
|
||||
|
||||
pub(crate) struct Report<'a> {
|
||||
pub(crate) fixture: &'a str,
|
||||
pub(crate) words: usize,
|
||||
pub(crate) fresh: &'a [Sample],
|
||||
pub(crate) wall: &'a [f64],
|
||||
pub(crate) first: &'a Sample,
|
||||
pub(crate) repeated: &'a [Sample],
|
||||
}
|
||||
|
||||
fn column(samples: &[Sample], phase: usize) -> Vec<f64> {
|
||||
samples.iter().map(|s| s.0[phase]).collect()
|
||||
}
|
||||
|
||||
fn summary_json(summary: Option<Summary>) -> String {
|
||||
summary.map_or_else(
|
||||
|| "null".to_string(),
|
||||
|s| {
|
||||
format!(
|
||||
"{{\"n\": {}, \"min\": {:e}, \"median\": {:e}, \"p90\": {:e}, \"p99\": {:e}, \"max\": {:e}}}",
|
||||
s.n, s.min, s.median, s.p90, s.p99, s.max
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
impl Report<'_> {
|
||||
pub(crate) fn json(&self) -> String {
|
||||
let mut out = format!(
|
||||
"{{\n \"fixture\": {},\n \"words\": {},\n \"process_wall\": {},\n",
|
||||
json_str(self.fixture),
|
||||
self.words,
|
||||
summary_json(summarize(self.wall))
|
||||
);
|
||||
for (regime, samples) in [("fresh", self.fresh), ("repeated", self.repeated)] {
|
||||
let _ = writeln!(out, " \"{regime}\": {{");
|
||||
for (i, phase) in PHASES.iter().enumerate() {
|
||||
let comma = if i + 1 < PHASES.len() { "," } else { "" };
|
||||
let summary = if regime == "repeated" && i < 2 {
|
||||
None
|
||||
} else {
|
||||
summarize(&column(samples, i))
|
||||
};
|
||||
let _ = writeln!(out, " \"{phase}\": {}{comma}", summary_json(summary));
|
||||
}
|
||||
out.push_str(" },\n");
|
||||
}
|
||||
let first: Vec<String> = PHASES
|
||||
.iter()
|
||||
.zip(self.first.0)
|
||||
.skip(1)
|
||||
.map(|(p, v)| format!("\"{p}\": {v:e}"))
|
||||
.collect();
|
||||
let _ = writeln!(out, " \"first_in_process\": {{{}}},", first.join(", "));
|
||||
// Raw fresh-process samples in launch order, so a cold first process
|
||||
// (for example an empty Metal shader cache) stays visible.
|
||||
let rows: Vec<String> = self
|
||||
.fresh
|
||||
.iter()
|
||||
.zip(self.wall)
|
||||
.map(|(sample, wall)| {
|
||||
let phases: Vec<String> = sample.0.iter().map(|v| format!("{v:e}")).collect();
|
||||
format!("[{}, {wall:e}]", phases.join(", "))
|
||||
})
|
||||
.collect();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" \"fresh_samples_columns\": [{}, \"process_wall\"],\n \"fresh_samples\": [\n {}\n ]\n}}",
|
||||
PHASES
|
||||
.iter()
|
||||
.map(|p| json_str(p))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", "),
|
||||
rows.join(",\n ")
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn markdown(&self, metadata: &Metadata) -> String {
|
||||
let ms = |v: f64| format!("{:.3}", v * 1e3);
|
||||
let mut out = format!(
|
||||
"# Metal startup: `{}`, {} words\n\nDevice {}, {} build, commit `{}`, API validation `{}`, shader validation `{}`, power `{}`, thermal `{}`.\n\nAll values in milliseconds. Fresh: {} processes. Repeated: {} runs after the first in one process. Every sample produced the expected output.\n\n| Phase | Fresh median | Fresh p90 | Fresh p99 | Fresh max | First in process | Repeated median | Repeated p90 | Repeated p99 | Repeated max |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n",
|
||||
self.fixture,
|
||||
self.words,
|
||||
metadata.device,
|
||||
metadata.profile,
|
||||
metadata.commit,
|
||||
metadata.api_validation,
|
||||
metadata.shader_validation,
|
||||
metadata.power,
|
||||
metadata.thermal,
|
||||
self.fresh.len(),
|
||||
self.repeated.len(),
|
||||
);
|
||||
for (i, phase) in PHASES.iter().enumerate() {
|
||||
let fresh = summarize(&column(self.fresh, i));
|
||||
let repeated = (i >= 2)
|
||||
.then(|| summarize(&column(self.repeated, i)))
|
||||
.flatten();
|
||||
let cells = |s: Option<Summary>| {
|
||||
s.map_or_else(
|
||||
|| "– | – | – | –".to_string(),
|
||||
|s| {
|
||||
format!(
|
||||
"{} | {} | {} | {}",
|
||||
ms(s.median),
|
||||
ms(s.p90),
|
||||
ms(s.p99),
|
||||
ms(s.max)
|
||||
)
|
||||
},
|
||||
)
|
||||
};
|
||||
let first = if i == 0 {
|
||||
"–".to_string()
|
||||
} else {
|
||||
ms(self.first.0[i])
|
||||
};
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| `{phase}` | {} | {first} | {} |",
|
||||
cells(fresh),
|
||||
cells(repeated)
|
||||
);
|
||||
}
|
||||
if let Some(s) = summarize(self.wall) {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| process wall (spawn to exit) | {} | {} | {} | {} | – | – | – | – | – |",
|
||||
ms(s.median),
|
||||
ms(s.p90),
|
||||
ms(s.p99),
|
||||
ms(s.max)
|
||||
);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -14,8 +14,9 @@
|
||||
//! refused, with exit status 1, unless both runs used the same host, workload,
|
||||
//! build settings and sample counts.
|
||||
//!
|
||||
//! The benchmark target disables Cargo's test harness. To run the percentile
|
||||
//! unit tests, build with
|
||||
//! Report, comparison and percentile tests run in ordinary workspace tests
|
||||
//! through `tests/dbt_benchmark_report.rs`. The benchmark target itself disables
|
||||
//! Cargo's test harness. To run its tests directly, build with
|
||||
//! `cargo rustc --locked -p xenora-loader --bench dbt_bench --message-format=json -- --test`
|
||||
//! and run the executable named by the benchmark's compiler-artifact message.
|
||||
|
||||
@@ -982,6 +983,7 @@ mod tests {
|
||||
blocks_compiled: 626,
|
||||
cache_hits: 0,
|
||||
cache_misses: 626,
|
||||
blocks_invalidated: 0,
|
||||
native_bytes_emitted: 245_168,
|
||||
dbt_dispatches: 626,
|
||||
instructions_executed: 10_002,
|
||||
|
||||
@@ -117,8 +117,9 @@ service kernel32.dll GetSystemTimeAsFileTime(time: out<8>) -> void
|
||||
test system_time_comes_from_the_injected_clock
|
||||
|
||||
# Standard streams and formatted output for a hosted C program. Output to
|
||||
# stdout and stderr is captured; any other stream, input, floating-point and
|
||||
# wide conversions stop the guest with the runtime-limit fault.
|
||||
# stdout and stderr is captured, and a stream from fopen is a file. A pointer
|
||||
# that is no stream, reading stdin, and floating-point and wide conversions
|
||||
# stop the guest with the runtime-limit fault.
|
||||
|
||||
service ucrtbase.dll __acrt_iob_func(index: u32) -> ptr
|
||||
handler standard_stream
|
||||
@@ -140,7 +141,7 @@ service ucrtbase.dll fwrite(buffer: ptr, size: u64, count: u64, stream: ptr) ->
|
||||
handler fwrite
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails 0 with errno EINVAL for a null buffer or stream; stops the guest for a stream other than stdout or stderr
|
||||
fails 0 with errno EINVAL for a null buffer or stream, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream
|
||||
ref stdio.h fwrite
|
||||
test fwrite_and_fputs_write_to_the_captured_standard_streams
|
||||
|
||||
@@ -148,7 +149,7 @@ service ucrtbase.dll fputs(text: ptr, stream: ptr) -> i32
|
||||
handler fputs
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails EOF with errno EINVAL for a null string or stream; stops the guest for a stream other than stdout or stderr
|
||||
fails EOF with errno EINVAL for a null string or stream, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream
|
||||
ref stdio.h fputs
|
||||
test fwrite_and_fputs_write_to_the_captured_standard_streams
|
||||
|
||||
@@ -156,7 +157,7 @@ service ucrtbase.dll fflush(stream: ptr) -> i32
|
||||
handler fflush
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails stops the guest for a stream that is not a standard stream
|
||||
fails stops the guest for a pointer that is no stream
|
||||
ref stdio.h fflush
|
||||
test fflush_and_setvbuf_return_their_documented_results
|
||||
|
||||
@@ -164,10 +165,44 @@ service ucrtbase.dll setvbuf(stream: ptr, buffer: ptr, mode: i32, size: u64) ->
|
||||
handler setvbuf
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails -1 with errno EINVAL for a null stream, an unknown mode or a size outside 2 to INT_MAX; stops the guest for a stream that is not a standard stream
|
||||
fails -1 with errno EINVAL for a null stream, an unknown mode or a size outside 2 to INT_MAX; stops the guest for a pointer that is no stream
|
||||
ref stdio.h setvbuf
|
||||
test fflush_and_setvbuf_return_their_documented_results
|
||||
|
||||
# Files for a hosted C program, on the in-memory drive the handle services use.
|
||||
|
||||
service ucrtbase.dll fopen(name: ptr, mode: ptr) -> ptr
|
||||
handler fopen
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails null with errno EINVAL, ENOENT, EACCES, EMFILE, ENOSPC or ENOMEM
|
||||
ref stdio.h fopen
|
||||
test a_file_written_through_a_stream_reads_back_line_by_line
|
||||
|
||||
service ucrtbase.dll fclose(stream: ptr) -> i32
|
||||
handler fclose
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails EOF with errno EINVAL for a null stream; stops the guest for a standard stream or a pointer that is no stream
|
||||
ref stdio.h fclose
|
||||
test a_file_written_through_a_stream_reads_back_line_by_line
|
||||
|
||||
service ucrtbase.dll fgets(buffer: ptr, count: i32, stream: ptr) -> ptr
|
||||
handler fgets
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails null at end of file; null with errno EINVAL or EBADF; stops the guest for stdin or a pointer that is no stream
|
||||
ref stdio.h fgets
|
||||
test fgets_reads_lines_within_its_count
|
||||
|
||||
service ucrtbase.dll perror(message: ptr) -> void
|
||||
handler perror
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails never
|
||||
ref stdio.h perror
|
||||
test perror_writes_the_message_and_the_error_text_to_stderr
|
||||
|
||||
service kernel32.dll GetLastError() -> u32
|
||||
handler get_last_error
|
||||
status partial
|
||||
|
||||
+278
-17
@@ -15,7 +15,7 @@ use crate::memory::GuestMemory;
|
||||
use crate::x86_decode::{Encoding, Insn, MemOperand, RegOperand, RmOperand, Segment, decode};
|
||||
use crate::x86_exec;
|
||||
use crate::x86_table::{FORMS, Op};
|
||||
use std::collections::HashMap;
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
const MAX_BLOCK_INSTRUCTIONS: usize = 16;
|
||||
|
||||
@@ -29,6 +29,9 @@ pub struct DbtMetrics {
|
||||
pub blocks_compiled: usize,
|
||||
pub cache_hits: usize,
|
||||
pub cache_misses: usize,
|
||||
/// Cached blocks discarded because their guest bytes or executable mappings
|
||||
/// changed. Each also counts as a cache miss.
|
||||
pub blocks_invalidated: usize,
|
||||
pub native_bytes_emitted: usize,
|
||||
pub dbt_dispatches: usize,
|
||||
pub instructions_executed: usize,
|
||||
@@ -37,11 +40,42 @@ pub struct DbtMetrics {
|
||||
pub service_calls: usize,
|
||||
}
|
||||
|
||||
/// A translated block and its executable-memory generation.
|
||||
///
|
||||
/// Guest stores into executable memory (Intel SDM Vol. 3A 11.6), executable
|
||||
/// mapping changes and another address space invalidate the retained token.
|
||||
/// An unchanged token takes a constant-time check. After a generation or address
|
||||
/// space change, bytes and execute permissions are revalidated once before an
|
||||
/// identical translation may be reused in that generation.
|
||||
/// Validation occurs at dispatch boundaries: a store into the currently running
|
||||
/// block's later instructions still needs a separate dispatch-boundary design.
|
||||
struct CachedBlock {
|
||||
code: *const u8,
|
||||
generation: Arc<()>,
|
||||
start: u64,
|
||||
source: Box<[u8]>,
|
||||
}
|
||||
|
||||
impl CachedBlock {
|
||||
fn is_current(&mut self, memory: &GuestMemory) -> bool {
|
||||
if memory.code_is_current(&self.generation) {
|
||||
return true;
|
||||
}
|
||||
if !self.source.iter().enumerate().all(|(offset, &byte)| {
|
||||
matches!(memory.fetch_instruction_byte(self.start.wrapping_add(offset as u64)), Ok(current) if current == byte)
|
||||
}) {
|
||||
return false;
|
||||
}
|
||||
self.generation = memory.code_generation();
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Dynamic Binary Translator and native execution runtime.
|
||||
pub struct DbtEngine {
|
||||
jit: JitMemory,
|
||||
block_cache: HashMap<u64, *const u8>,
|
||||
limited_block_cache: HashMap<(u64, usize), *const u8>,
|
||||
block_cache: HashMap<u64, CachedBlock>,
|
||||
limited_block_cache: HashMap<(u64, usize), CachedBlock>,
|
||||
assembler: Arm64Assembler,
|
||||
/// Decoded instructions that emitted helper calls point into.
|
||||
decoded_blocks: Vec<Box<[Insn]>>,
|
||||
@@ -245,26 +279,34 @@ impl DbtEngine {
|
||||
block_limit: usize,
|
||||
) -> Result<*const u8, ExitReason> {
|
||||
if block_limit == MAX_BLOCK_INSTRUCTIONS {
|
||||
if let Some(&fn_ptr) = self.block_cache.get(&rip) {
|
||||
self.metrics.cache_hits += 1;
|
||||
return Ok(fn_ptr);
|
||||
if let Some(cached) = self.block_cache.get_mut(&rip) {
|
||||
if cached.is_current(memory) {
|
||||
self.metrics.cache_hits += 1;
|
||||
return Ok(cached.code);
|
||||
}
|
||||
self.metrics.blocks_invalidated += 1;
|
||||
}
|
||||
self.metrics.cache_misses += 1;
|
||||
let compiled_ptr = self.compile_block(rip, memory, block_limit)?;
|
||||
self.block_cache.insert(rip, compiled_ptr);
|
||||
return Ok(compiled_ptr);
|
||||
let compiled = self.compile_block(rip, memory, block_limit)?;
|
||||
let code = compiled.code;
|
||||
self.block_cache.insert(rip, compiled);
|
||||
return Ok(code);
|
||||
}
|
||||
|
||||
// Keep budget-limited blocks separate so they cannot shorten a later run.
|
||||
let key = (rip, block_limit);
|
||||
if let Some(&fn_ptr) = self.limited_block_cache.get(&key) {
|
||||
self.metrics.cache_hits += 1;
|
||||
return Ok(fn_ptr);
|
||||
if let Some(cached) = self.limited_block_cache.get_mut(&key) {
|
||||
if cached.is_current(memory) {
|
||||
self.metrics.cache_hits += 1;
|
||||
return Ok(cached.code);
|
||||
}
|
||||
self.metrics.blocks_invalidated += 1;
|
||||
}
|
||||
self.metrics.cache_misses += 1;
|
||||
let compiled_ptr = self.compile_block(rip, memory, block_limit)?;
|
||||
self.limited_block_cache.insert(key, compiled_ptr);
|
||||
Ok(compiled_ptr)
|
||||
let compiled = self.compile_block(rip, memory, block_limit)?;
|
||||
let code = compiled.code;
|
||||
self.limited_block_cache.insert(key, compiled);
|
||||
Ok(code)
|
||||
}
|
||||
|
||||
fn compile_block(
|
||||
@@ -272,7 +314,7 @@ impl DbtEngine {
|
||||
start_rip: u64,
|
||||
memory: &GuestMemory,
|
||||
block_limit: usize,
|
||||
) -> Result<*const u8, ExitReason> {
|
||||
) -> Result<CachedBlock, ExitReason> {
|
||||
// Decode the whole block first: lowering needs to know whether a later
|
||||
// instruction observes the flags an earlier one produces.
|
||||
let mut decoded = Vec::with_capacity(block_limit);
|
||||
@@ -351,8 +393,17 @@ impl DbtEngine {
|
||||
.map_err(|_| ExitReason::JitCacheExhausted)?;
|
||||
self.metrics.blocks_compiled += 1;
|
||||
self.metrics.native_bytes_emitted += asm.instructions().len() * 4;
|
||||
let source = (0..rip.wrapping_sub(start_rip))
|
||||
.map(|offset| memory.fetch_instruction_byte(start_rip.wrapping_add(offset)))
|
||||
.collect::<Result<Box<[u8]>, _>>()
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
self.decoded_blocks.push(insns);
|
||||
Ok(emitted)
|
||||
Ok(CachedBlock {
|
||||
code: emitted,
|
||||
generation: memory.code_generation(),
|
||||
start: start_rip,
|
||||
source,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1569,6 +1620,216 @@ mod tests {
|
||||
)
|
||||
}
|
||||
|
||||
/// `mov eax, imm32; hlt`, with the immediate at `ENTRY + 1`.
|
||||
fn mov_eax(imm: u8) -> [u8; 6] {
|
||||
[0xB8, imm, 0x00, 0x00, 0x00, 0xF4]
|
||||
}
|
||||
|
||||
fn writable_fixture(code: &[u8]) -> (DbtEngine, GuestMemory) {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
ENTRY,
|
||||
code.len(),
|
||||
MemoryPermissions::READ_WRITE_EXECUTE,
|
||||
code,
|
||||
)
|
||||
.unwrap();
|
||||
(DbtEngine::new(64 * 1024).unwrap(), memory)
|
||||
}
|
||||
|
||||
fn rax_after_run(engine: &mut DbtEngine, memory: &mut GuestMemory, limit: usize) -> u64 {
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
let result = engine.run(&mut cpu, memory, limit);
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
cpu.get(Register::Rax)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_code_stays_cached() {
|
||||
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
|
||||
assert_eq!(engine.metrics.blocks_compiled, 1);
|
||||
assert_eq!(engine.metrics.cache_hits, 1);
|
||||
assert_eq!(engine.metrics.blocks_invalidated, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_writes_and_allocations_do_not_invalidate_executable_code() {
|
||||
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
|
||||
memory
|
||||
.map_region(ENTRY + 0x1000, 8, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
|
||||
for value in 0..64 {
|
||||
memory.write_u64(ENTRY + 0x1000, value).unwrap();
|
||||
let allocation = memory
|
||||
.map_virtual_allocation(0, 4096, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
assert!(memory.release_virtual_allocation(allocation));
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
|
||||
}
|
||||
assert_eq!(engine.metrics.blocks_compiled, 1);
|
||||
assert_eq!(engine.metrics.cache_hits, 64);
|
||||
assert_eq!(engine.metrics.blocks_invalidated, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cloned_address_spaces_diverge_when_executable_code_changes() {
|
||||
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
|
||||
let mut cloned = memory.clone();
|
||||
assert_eq!(rax_after_run(&mut engine, &mut cloned, 16), 1);
|
||||
memory.write_u8(ENTRY + 1, 7).unwrap();
|
||||
assert_eq!(rax_after_run(&mut engine, &mut cloned, 16), 1);
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 7);
|
||||
// A deep clone shares the proven identical executable snapshot. The
|
||||
// write in the original space must still force retranslation there.
|
||||
assert_eq!(engine.metrics.blocks_compiled, 2);
|
||||
assert_eq!(engine.metrics.cache_hits, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executable_bypass_writes_invalidate_cached_translations() {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
ENTRY,
|
||||
8,
|
||||
MemoryPermissions::READ_EXECUTE,
|
||||
&[0xB8, 1, 0, 0, 0, 0xF4, 0, 0],
|
||||
)
|
||||
.unwrap();
|
||||
let mut engine = DbtEngine::new(64 * 1024).unwrap();
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
|
||||
assert!(memory.write_u32(ENTRY + 1, 9).is_err());
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
|
||||
assert_eq!(engine.metrics.blocks_invalidated, 0);
|
||||
memory
|
||||
.write_u64_bypass(ENTRY, u64::from_le_bytes([0xB8, 2, 0, 0, 0, 0xF4, 0, 0]))
|
||||
.unwrap();
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 2);
|
||||
memory.write_u32_bypass(ENTRY + 1, 3).unwrap();
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 3);
|
||||
assert_eq!(engine.metrics.blocks_invalidated, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executable_writes_crossing_regions_invalidate_cached_translations() {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, 2, MemoryPermissions::READ_WRITE_EXECUTE, &[0xB8, 1])
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
ENTRY + 2,
|
||||
4,
|
||||
MemoryPermissions::READ_WRITE_EXECUTE,
|
||||
&[0, 0, 0, 0xF4],
|
||||
)
|
||||
.unwrap();
|
||||
let mut engine = DbtEngine::new(64 * 1024).unwrap();
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
|
||||
memory.write_u32(ENTRY + 1, 9).unwrap();
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 9);
|
||||
assert_eq!(engine.metrics.blocks_invalidated, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remapped_non_executable_memory_cannot_reuse_a_translation() {
|
||||
let mut memory = GuestMemory::new();
|
||||
let base = memory
|
||||
.map_virtual_allocation(0, 4096, MemoryPermissions::READ_WRITE_EXECUTE)
|
||||
.unwrap();
|
||||
memory.write_bytes(base, &mov_eax(1)).unwrap();
|
||||
let mut engine = DbtEngine::new(64 * 1024).unwrap();
|
||||
let mut cpu = CpuState::new(base, 0);
|
||||
assert_eq!(
|
||||
engine.run(&mut cpu, &mut memory, 16).exit_reason,
|
||||
ExitReason::Halt
|
||||
);
|
||||
assert!(memory.release_virtual_allocation(base));
|
||||
assert_eq!(
|
||||
memory.map_virtual_allocation(base, 4096, MemoryPermissions::READ_WRITE),
|
||||
Ok(base)
|
||||
);
|
||||
memory.write_bytes(base, &mov_eax(1)).unwrap();
|
||||
let mut cpu = CpuState::new(base, 0);
|
||||
assert!(matches!(
|
||||
engine.run(&mut cpu, &mut memory, 16).exit_reason,
|
||||
ExitReason::MemoryFault(_)
|
||||
));
|
||||
assert_eq!(engine.metrics.blocks_invalidated, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_code_rewrites_report_bounded_jit_cache_exhaustion() {
|
||||
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
|
||||
for value in 0..16_384u32 {
|
||||
memory.write_u32(ENTRY + 1, value).unwrap();
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
let result = engine.run(&mut cpu, &mut memory, 16);
|
||||
if result.exit_reason == ExitReason::JitCacheExhausted {
|
||||
return;
|
||||
}
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(cpu.get(Register::Rax), u64::from(value));
|
||||
}
|
||||
panic!("rewritten blocks unexpectedly avoided the bounded JIT capacity");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewritten_code_is_translated_again() {
|
||||
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
|
||||
memory.write_bytes(ENTRY + 1, &[2]).unwrap();
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 2);
|
||||
assert_eq!(engine.metrics.blocks_compiled, 2);
|
||||
assert_eq!(engine.metrics.blocks_invalidated, 1);
|
||||
// The new translation is cached in turn.
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 2);
|
||||
assert_eq!(engine.metrics.blocks_compiled, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewriting_the_last_byte_of_a_block_is_detected() {
|
||||
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
|
||||
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
|
||||
// HLT becomes NOP, so the block now runs off the end of the mapping.
|
||||
memory.write_bytes(ENTRY + 5, &[0x90]).unwrap();
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
let result = engine.run(&mut cpu, &mut memory, 16);
|
||||
assert!(matches!(result.exit_reason, ExitReason::MemoryFault(_)));
|
||||
assert_eq!(engine.metrics.blocks_invalidated, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn budget_limited_block_is_checked_against_current_bytes() {
|
||||
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
|
||||
for expected in [1, 3] {
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
let result = engine.run(&mut cpu, &mut memory, 1);
|
||||
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded);
|
||||
assert_eq!(cpu.get(Register::Rax), expected);
|
||||
memory.write_bytes(ENTRY + 1, &[3]).unwrap();
|
||||
}
|
||||
assert_eq!(engine.metrics.blocks_invalidated, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_address_space_does_not_reuse_a_block() {
|
||||
let (mut engine, mut first) = writable_fixture(&mov_eax(1));
|
||||
let (_, mut second) = writable_fixture(&mov_eax(7));
|
||||
assert_eq!(rax_after_run(&mut engine, &mut first, 16), 1);
|
||||
assert_eq!(rax_after_run(&mut engine, &mut second, 16), 7);
|
||||
|
||||
let mut unmapped = GuestMemory::new();
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
let result = engine.run(&mut cpu, &mut unmapped, 16);
|
||||
assert!(matches!(result.exit_reason, ExitReason::MemoryFault(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_block_obeys_remaining_budget() {
|
||||
let code = [
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
//! Provides isolated, page-aligned guest virtual memory with permission checking
|
||||
//! (Read, Write, Execute) and bounds enforcement without host OS mapping tricks.
|
||||
|
||||
use std::{fmt, ops::Range};
|
||||
use std::{fmt, ops::Range, sync::Arc};
|
||||
|
||||
pub(crate) const ALLOCATION_GRANULARITY: u64 = 65_536;
|
||||
|
||||
@@ -119,8 +119,13 @@ impl MappedRegion {
|
||||
}
|
||||
|
||||
/// Guest virtual memory address space.
|
||||
#[derive(Default, Clone)]
|
||||
#[derive(Default)]
|
||||
pub struct GuestMemory {
|
||||
// A retained token identifies a validated executable snapshot. Independent
|
||||
// address spaces get distinct tokens. A deep clone may share its identical
|
||||
// snapshot; an executable mutation detaches only the changed address space.
|
||||
// Cached translations retain tokens, preventing allocator-address reuse.
|
||||
executable_generation: Arc<()>,
|
||||
regions: Vec<MappedRegion>,
|
||||
private_heaps: std::collections::BTreeSet<u64>,
|
||||
private_heap_serial: u64,
|
||||
@@ -130,7 +135,32 @@ pub struct GuestMemory {
|
||||
std::collections::BTreeMap<(u64, u64), crate::imports::CallbackFrame>,
|
||||
}
|
||||
|
||||
impl Clone for GuestMemory {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
executable_generation: Arc::clone(&self.executable_generation),
|
||||
regions: self.regions.clone(),
|
||||
private_heaps: self.private_heaps.clone(),
|
||||
private_heap_serial: self.private_heap_serial,
|
||||
crt_errno: self.crt_errno.clone(),
|
||||
callback_frames: self.callback_frames.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl GuestMemory {
|
||||
pub(crate) fn code_generation(&self) -> Arc<()> {
|
||||
Arc::clone(&self.executable_generation)
|
||||
}
|
||||
|
||||
pub(crate) fn code_is_current(&self, generation: &Arc<()>) -> bool {
|
||||
Arc::ptr_eq(&self.executable_generation, generation)
|
||||
}
|
||||
|
||||
fn invalidate_executable_code(&mut self) {
|
||||
self.executable_generation = Arc::new(());
|
||||
}
|
||||
|
||||
/// Create a new empty guest address space.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
@@ -197,6 +227,9 @@ impl GuestMemory {
|
||||
allocation,
|
||||
});
|
||||
self.regions.sort_by_key(|r| r.base);
|
||||
if permissions.execute && size != 0 {
|
||||
self.invalidate_executable_code();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -256,8 +289,14 @@ impl GuestMemory {
|
||||
if !self.private_heaps.remove(&heap) {
|
||||
return false;
|
||||
}
|
||||
let executable = self.regions.iter().any(|region| {
|
||||
region.allocation == AllocationKind::Heap(heap) && region.permissions.execute
|
||||
});
|
||||
self.regions
|
||||
.retain(|region| region.allocation != AllocationKind::Heap(heap));
|
||||
if executable {
|
||||
self.invalidate_executable_code();
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
@@ -377,10 +416,14 @@ impl GuestMemory {
|
||||
if size < previous {
|
||||
region.data.shrink_to_fit();
|
||||
}
|
||||
let executable = region.permissions.execute;
|
||||
if destination != base {
|
||||
region.base = destination;
|
||||
self.regions.sort_by_key(|region| region.base);
|
||||
}
|
||||
if executable && (size != previous || destination != base) {
|
||||
self.invalidate_executable_code();
|
||||
}
|
||||
Ok(destination)
|
||||
}
|
||||
|
||||
@@ -420,7 +463,10 @@ impl GuestMemory {
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
self.regions.remove(index);
|
||||
let removed = self.regions.remove(index);
|
||||
if removed.permissions.execute && !removed.data.is_empty() {
|
||||
self.invalidate_executable_code();
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
@@ -510,11 +556,16 @@ impl GuestMemory {
|
||||
required: Option<&'static str>,
|
||||
) -> Result<(), MemoryError> {
|
||||
let mut done = 0;
|
||||
let mut executable = false;
|
||||
for (index, offset, take) in self.resolve(address, src.len(), required)? {
|
||||
executable |= take != 0 && self.regions[index].permissions.execute;
|
||||
self.regions[index].data[offset..offset + take]
|
||||
.copy_from_slice(&src[done..done + take]);
|
||||
done += take;
|
||||
}
|
||||
if executable {
|
||||
self.invalidate_executable_code();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -524,6 +575,9 @@ impl GuestMemory {
|
||||
&& self.regions[index].permissions.write
|
||||
{
|
||||
self.regions[index].data[range].copy_from_slice(src);
|
||||
if !src.is_empty() && self.regions[index].permissions.execute {
|
||||
self.invalidate_executable_code();
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
self.write_checked(address, src, Some("write"))
|
||||
|
||||
@@ -8,7 +8,7 @@ use crate::runtime::{Call, Parameter, Return, ServiceContext, ServiceMetadata};
|
||||
use crate::services::{ServicesState, handlers};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub static SERVICES: [ServiceMetadata; 43] = [
|
||||
pub static SERVICES: [ServiceMetadata; 47] = [
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "SetProcessPriorityBoost",
|
||||
@@ -170,7 +170,7 @@ pub static SERVICES: [ServiceMetadata; 43] = [
|
||||
result: "u64",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "0 with errno EINVAL for a null buffer or stream; stops the guest for a stream other than stdout or stderr",
|
||||
failure: "0 with errno EINVAL for a null buffer or stream, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream",
|
||||
reference: "stdio.h fwrite",
|
||||
tests: &["fwrite_and_fputs_write_to_the_captured_standard_streams"],
|
||||
},
|
||||
@@ -181,7 +181,7 @@ pub static SERVICES: [ServiceMetadata; 43] = [
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "EOF with errno EINVAL for a null string or stream; stops the guest for a stream other than stdout or stderr",
|
||||
failure: "EOF with errno EINVAL for a null string or stream, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream",
|
||||
reference: "stdio.h fputs",
|
||||
tests: &["fwrite_and_fputs_write_to_the_captured_standard_streams"],
|
||||
},
|
||||
@@ -192,7 +192,7 @@ pub static SERVICES: [ServiceMetadata; 43] = [
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "stops the guest for a stream that is not a standard stream",
|
||||
failure: "stops the guest for a pointer that is no stream",
|
||||
reference: "stdio.h fflush",
|
||||
tests: &["fflush_and_setvbuf_return_their_documented_results"],
|
||||
},
|
||||
@@ -203,10 +203,54 @@ pub static SERVICES: [ServiceMetadata; 43] = [
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "-1 with errno EINVAL for a null stream, an unknown mode or a size outside 2 to INT_MAX; stops the guest for a stream that is not a standard stream",
|
||||
failure: "-1 with errno EINVAL for a null stream, an unknown mode or a size outside 2 to INT_MAX; stops the guest for a pointer that is no stream",
|
||||
reference: "stdio.h setvbuf",
|
||||
tests: &["fflush_and_setvbuf_return_their_documented_results"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "fopen",
|
||||
parameters: &[Parameter { name: "name", kind: "ptr" }, Parameter { name: "mode", kind: "ptr" }],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "null with errno EINVAL, ENOENT, EACCES, EMFILE, ENOSPC or ENOMEM",
|
||||
reference: "stdio.h fopen",
|
||||
tests: &["a_file_written_through_a_stream_reads_back_line_by_line"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "fclose",
|
||||
parameters: &[Parameter { name: "stream", kind: "ptr" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "EOF with errno EINVAL for a null stream; stops the guest for a standard stream or a pointer that is no stream",
|
||||
reference: "stdio.h fclose",
|
||||
tests: &["a_file_written_through_a_stream_reads_back_line_by_line"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "fgets",
|
||||
parameters: &[Parameter { name: "buffer", kind: "ptr" }, Parameter { name: "count", kind: "i32" }, Parameter { name: "stream", kind: "ptr" }],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "null at end of file; null with errno EINVAL or EBADF; stops the guest for stdin or a pointer that is no stream",
|
||||
reference: "stdio.h fgets",
|
||||
tests: &["fgets_reads_lines_within_its_count"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "perror",
|
||||
parameters: &[Parameter { name: "message", kind: "ptr" }],
|
||||
result: "void",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
|
||||
failure: "never",
|
||||
reference: "stdio.h perror",
|
||||
tests: &["perror_writes_the_message_and_the_error_text_to_stderr"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "GetLastError",
|
||||
@@ -643,6 +687,41 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "fopen", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::fopen(&mut context, a0, a1)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "fclose", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::fclose(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "fgets", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.i32(1)?;
|
||||
let a2 = call.u64(2)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::fgets(&mut context, a0, a1, a2)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "perror", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let () = handlers::perror(&mut context, a0)?;
|
||||
Ok(0)
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "GetLastError", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let _ = args;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
mod crt;
|
||||
mod crt_arguments;
|
||||
mod crt_callbacks;
|
||||
mod crt_files;
|
||||
mod crt_format;
|
||||
mod crt_startup;
|
||||
mod crt_streams;
|
||||
@@ -937,17 +938,18 @@ pub(crate) mod handlers {
|
||||
.map_err(ExitReason::MemoryFault)
|
||||
}
|
||||
|
||||
// Standard streams and formatted output (#400). `crt_streams.rs` holds
|
||||
// the rules; a documented failure sets errno to EINVAL here.
|
||||
// Streams, files and formatted output (#400, #402). `crt_streams.rs` and
|
||||
// `crt_files.rs` hold the rules; a failure that has an errno value sets it
|
||||
// here. The stream state is always locked before the object state.
|
||||
|
||||
fn or_einval<T>(
|
||||
fn or_errno<T>(
|
||||
context: &mut ServiceContext<'_>,
|
||||
outcome: crt_streams::Outcome<T>,
|
||||
) -> Outcome<T> {
|
||||
match outcome? {
|
||||
Ok(value) => Ok(value),
|
||||
Err(crt_streams::Invalid(value)) => {
|
||||
crt::set_errno(context.memory, context.teb, crt::EINVAL)?;
|
||||
Err(crt_streams::Failed(value, errno)) => {
|
||||
crt::set_errno(context.memory, context.teb, errno)?;
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
@@ -965,15 +967,20 @@ pub(crate) mod handlers {
|
||||
locale: u64,
|
||||
arguments: u64,
|
||||
) -> Outcome<i32> {
|
||||
let outcome = context.state.crt_streams().print(
|
||||
context.memory,
|
||||
options,
|
||||
stream,
|
||||
format,
|
||||
locale,
|
||||
arguments,
|
||||
);
|
||||
or_einval(context, outcome)
|
||||
let outcome = {
|
||||
let mut streams = context.state.crt_streams();
|
||||
let mut drive = context.state.objects.lock().expect("guest object state");
|
||||
streams.print(
|
||||
context.memory,
|
||||
&mut drive,
|
||||
options,
|
||||
stream,
|
||||
format,
|
||||
locale,
|
||||
arguments,
|
||||
)
|
||||
};
|
||||
or_errno(context, outcome)
|
||||
}
|
||||
|
||||
pub fn fwrite(
|
||||
@@ -983,20 +990,21 @@ pub(crate) mod handlers {
|
||||
count: u64,
|
||||
stream: u64,
|
||||
) -> Outcome<u64> {
|
||||
let outcome =
|
||||
context
|
||||
.state
|
||||
.crt_streams()
|
||||
.write_items(context.memory, buffer, size, count, stream);
|
||||
or_einval(context, outcome)
|
||||
let outcome = {
|
||||
let mut streams = context.state.crt_streams();
|
||||
let mut drive = context.state.objects.lock().expect("guest object state");
|
||||
streams.write_items(context.memory, &mut drive, buffer, size, count, stream)
|
||||
};
|
||||
or_errno(context, outcome)
|
||||
}
|
||||
|
||||
pub fn fputs(context: &mut ServiceContext<'_>, text: u64, stream: u64) -> Outcome<i32> {
|
||||
let outcome = context
|
||||
.state
|
||||
.crt_streams()
|
||||
.put_string(context.memory, text, stream);
|
||||
or_einval(context, outcome)
|
||||
let outcome = {
|
||||
let mut streams = context.state.crt_streams();
|
||||
let mut drive = context.state.objects.lock().expect("guest object state");
|
||||
streams.put_string(context.memory, &mut drive, text, stream)
|
||||
};
|
||||
or_errno(context, outcome)
|
||||
}
|
||||
|
||||
pub fn fflush(context: &mut ServiceContext<'_>, stream: u64) -> Outcome<i32> {
|
||||
@@ -1011,7 +1019,49 @@ pub(crate) mod handlers {
|
||||
size: u64,
|
||||
) -> Outcome<i32> {
|
||||
let outcome = context.state.crt_streams().set_buffer(stream, mode, size);
|
||||
or_einval(context, outcome)
|
||||
or_errno(context, outcome)
|
||||
}
|
||||
|
||||
pub fn fopen(context: &mut ServiceContext<'_>, name: u64, mode: u64) -> Outcome<u64> {
|
||||
let outcome = {
|
||||
let mut streams = context.state.crt_streams();
|
||||
let mut drive = context.state.objects.lock().expect("guest object state");
|
||||
streams.open(context.memory, &mut drive, name, mode)
|
||||
};
|
||||
or_errno(context, outcome)
|
||||
}
|
||||
|
||||
pub fn fclose(context: &mut ServiceContext<'_>, stream: u64) -> Outcome<i32> {
|
||||
let outcome = context.state.crt_streams().close(context.memory, stream);
|
||||
or_errno(context, outcome)
|
||||
}
|
||||
|
||||
pub fn fgets(
|
||||
context: &mut ServiceContext<'_>,
|
||||
buffer: u64,
|
||||
count: i32,
|
||||
stream: u64,
|
||||
) -> Outcome<u64> {
|
||||
let outcome = {
|
||||
let mut streams = context.state.crt_streams();
|
||||
let drive = context.state.objects.lock().expect("guest object state");
|
||||
streams.get_line(context.memory, &drive, buffer, count, stream)
|
||||
};
|
||||
or_errno(context, outcome)
|
||||
}
|
||||
|
||||
pub fn perror(context: &mut ServiceContext<'_>, message: u64) -> Outcome<()> {
|
||||
let address = context
|
||||
.memory
|
||||
.crt_errno_address(context.teb)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
let errno = context
|
||||
.memory
|
||||
.read_u32(address)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
let mut streams = context.state.crt_streams();
|
||||
let mut drive = context.state.objects.lock().expect("guest object state");
|
||||
streams.report(context.memory, &mut drive, message, errno)
|
||||
}
|
||||
|
||||
pub fn get_last_error(context: &mut ServiceContext<'_>) -> Outcome<u32> {
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! The C runtime's file streams: what `fopen` opens.
|
||||
//!
|
||||
//! A stream reads and writes a file on the in-memory `C:` drive that the
|
||||
//! handle services in `files.rs` also use, as the C runtime sits on Win32
|
||||
//! files on Windows. The rules are from the Microsoft Learn pages "fopen,
|
||||
//! _wfopen", "fclose, _fcloseall", "fgets, fgetws" and "perror, _wperror".
|
||||
//!
|
||||
//! Modes: `r`, `w` or `a`, then any of `+`, `b` and `t`. In text mode, which
|
||||
//! is the default as `_fmode` starts as `_O_TEXT`, "LF characters are
|
||||
//! translated to CR-LF combinations on output", "CR-LF combinations are
|
||||
//! translated into single line feeds on input", and "CTRL+Z is interpreted as
|
||||
//! an end-of-file character on input".
|
||||
//!
|
||||
//! Nothing is buffered: a write reaches the drive at once. There is no
|
||||
//! seeking, so the only positions are the start, the end, and wherever the
|
||||
//! last read or write left off.
|
||||
|
||||
use super::ObjectState;
|
||||
use super::files::DriveEntry;
|
||||
use crate::memory::{GuestMemory, PROCESS_HEAP};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// errno.h values.
|
||||
pub(super) const ENOENT: u32 = 2;
|
||||
pub(super) const EBADF: u32 = 9;
|
||||
pub(super) const ENOMEM: u32 = 12;
|
||||
pub(super) const EACCES: u32 = 13;
|
||||
pub(super) const EINVAL: u32 = 22;
|
||||
pub(super) const EMFILE: u32 = 24;
|
||||
pub(super) const ENOSPC: u32 = 28;
|
||||
|
||||
/// The most streams `fopen` keeps open at once.
|
||||
pub(super) const MAX_OPEN_STREAMS: usize = 64;
|
||||
/// `CTRL+Z`, which ends the input of a text-mode stream.
|
||||
const CTRL_Z: u8 = 0x1A;
|
||||
|
||||
/// The text `perror` prints for an `errno` value. The page gives the text for
|
||||
/// a missing file in its example; the others are the usual C library wording
|
||||
/// and are Xenora's choice.
|
||||
pub(super) fn error_text(errno: u32) -> &'static str {
|
||||
match errno {
|
||||
0 => "No error",
|
||||
ENOENT => "No such file or directory",
|
||||
EBADF => "Bad file descriptor",
|
||||
ENOMEM => "Not enough space",
|
||||
EACCES => "Permission denied",
|
||||
EINVAL => "Invalid argument",
|
||||
EMFILE => "Too many open files",
|
||||
ENOSPC => "No space left on device",
|
||||
_ => "Unknown error",
|
||||
}
|
||||
}
|
||||
|
||||
struct Mode {
|
||||
readable: bool,
|
||||
writable: bool,
|
||||
/// Every write goes to the end of the file.
|
||||
append: bool,
|
||||
/// The file must already exist.
|
||||
existing: bool,
|
||||
/// The file's contents are destroyed on opening.
|
||||
truncate: bool,
|
||||
text: bool,
|
||||
}
|
||||
|
||||
/// `r`, `w` or `a` first, then `+`, `b` and `t` in any order, each at most
|
||||
/// once and not both `b` and `t`. Anything else is not a mode this runtime
|
||||
/// opens, including the other characters the page lists.
|
||||
fn parse_mode(mode: &[u8]) -> Option<Mode> {
|
||||
let (&kind, rest) = mode.split_first()?;
|
||||
let (mut update, mut binary, mut text) = (false, false, false);
|
||||
for &byte in rest {
|
||||
let seen = match byte {
|
||||
b'+' => &mut update,
|
||||
b'b' => &mut binary,
|
||||
b't' => &mut text,
|
||||
_ => return None,
|
||||
};
|
||||
if std::mem::replace(seen, true) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if binary && text {
|
||||
return None;
|
||||
}
|
||||
let (readable, writable, append, existing, truncate) = match kind {
|
||||
b'r' => (true, update, false, true, false),
|
||||
b'w' => (update, true, false, false, true),
|
||||
b'a' => (update, true, true, false, false),
|
||||
_ => return None,
|
||||
};
|
||||
Some(Mode {
|
||||
readable,
|
||||
writable,
|
||||
append,
|
||||
existing,
|
||||
truncate,
|
||||
text: !binary,
|
||||
})
|
||||
}
|
||||
|
||||
struct FileStream {
|
||||
path: String,
|
||||
/// Where the next read, or the next write of a stream that does not
|
||||
/// append, takes place.
|
||||
position: u64,
|
||||
readable: bool,
|
||||
writable: bool,
|
||||
append: bool,
|
||||
text: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct FileStreams {
|
||||
/// Open streams by the guest address of their `FILE` object.
|
||||
open: BTreeMap<u64, FileStream>,
|
||||
}
|
||||
|
||||
impl FileStreams {
|
||||
pub(super) fn contains(&self, file: u64) -> bool {
|
||||
self.open.contains_key(&file)
|
||||
}
|
||||
|
||||
/// `fopen`. Returns the guest address of a new `FILE` object, or the
|
||||
/// `errno` value of the failure.
|
||||
pub(super) fn open(
|
||||
&mut self,
|
||||
memory: &mut GuestMemory,
|
||||
drive: &mut ObjectState,
|
||||
name: &[u8],
|
||||
mode: &[u8],
|
||||
) -> Result<u64, u32> {
|
||||
// An empty name or mode is an invalid parameter: neither is a mode
|
||||
// nor a name the drive accepts. Xenora's choice: so is any other mode
|
||||
// it does not open and any other name the drive rejects.
|
||||
let mode = parse_mode(mode).ok_or(EINVAL)?;
|
||||
let path = ObjectState::drive_path(name).ok_or(EINVAL)?;
|
||||
if self.open.len() >= MAX_OPEN_STREAMS {
|
||||
return Err(EMFILE);
|
||||
}
|
||||
let create = match drive.drive_entry(&path) {
|
||||
DriveEntry::Directory => return Err(EACCES),
|
||||
DriveEntry::File => false,
|
||||
DriveEntry::Missing { .. } if mode.existing => return Err(ENOENT),
|
||||
DriveEntry::Missing { parent: false } => return Err(ENOENT),
|
||||
DriveEntry::Missing { parent: true } => true,
|
||||
};
|
||||
// The FILE object is allocated before the drive is touched, so a
|
||||
// failed fopen neither creates a file nor destroys the contents of
|
||||
// one.
|
||||
let file = memory
|
||||
.map_heap_allocation(PROCESS_HEAP, 8)
|
||||
.map_err(|_| ENOMEM)?;
|
||||
if create && !drive.drive_create(&path) {
|
||||
memory.release_heap_allocation(PROCESS_HEAP, file);
|
||||
return Err(ENOSPC);
|
||||
}
|
||||
if mode.truncate {
|
||||
drive.drive_truncate(&path);
|
||||
}
|
||||
self.open.insert(
|
||||
file,
|
||||
FileStream {
|
||||
path,
|
||||
position: 0,
|
||||
readable: mode.readable,
|
||||
writable: mode.writable,
|
||||
append: mode.append,
|
||||
text: mode.text,
|
||||
},
|
||||
);
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// `fclose`. False when `file` is not an open stream.
|
||||
pub(super) fn close(&mut self, memory: &mut GuestMemory, file: u64) -> bool {
|
||||
if self.open.remove(&file).is_none() {
|
||||
return false;
|
||||
}
|
||||
memory.release_heap_allocation(PROCESS_HEAP, file);
|
||||
true
|
||||
}
|
||||
|
||||
/// Write to an open stream, in its mode. Returns the `errno` value of a
|
||||
/// failure, with nothing written.
|
||||
pub(super) fn write(
|
||||
&mut self,
|
||||
drive: &mut ObjectState,
|
||||
file: u64,
|
||||
bytes: &[u8],
|
||||
) -> Result<(), u32> {
|
||||
let stream = self.open.get_mut(&file).ok_or(EBADF)?;
|
||||
if !stream.writable {
|
||||
return Err(EBADF);
|
||||
}
|
||||
let stored: Vec<u8> = if stream.text {
|
||||
let mut stored = Vec::with_capacity(bytes.len());
|
||||
for &byte in bytes {
|
||||
if byte == b'\n' {
|
||||
stored.push(b'\r');
|
||||
}
|
||||
stored.push(byte);
|
||||
}
|
||||
stored
|
||||
} else {
|
||||
bytes.to_vec()
|
||||
};
|
||||
// "All write operations occur at the end of the file."
|
||||
if stream.append {
|
||||
stream.position = drive.drive_file(&stream.path).ok_or(EBADF)?.len() as u64;
|
||||
}
|
||||
match drive.drive_write(&stream.path, stream.position, &stored) {
|
||||
Some(true) => {
|
||||
stream.position += stored.len() as u64;
|
||||
Ok(())
|
||||
}
|
||||
Some(false) => Err(ENOSPC),
|
||||
// The file was deleted or moved while the stream was open.
|
||||
None => Err(EBADF),
|
||||
}
|
||||
}
|
||||
|
||||
/// `fgets`: up to `limit` characters, ending after a newline. `None` is
|
||||
/// end of file with nothing read.
|
||||
pub(super) fn read_line(
|
||||
&mut self,
|
||||
drive: &ObjectState,
|
||||
file: u64,
|
||||
limit: usize,
|
||||
) -> Result<Option<Vec<u8>>, u32> {
|
||||
let stream = self.open.get_mut(&file).ok_or(EBADF)?;
|
||||
if !stream.readable {
|
||||
return Err(EBADF);
|
||||
}
|
||||
let data = drive.drive_file(&stream.path).ok_or(EBADF)?;
|
||||
let mut at = usize::try_from(stream.position).map_or(data.len(), |at| at.min(data.len()));
|
||||
let ended = at == data.len() || (stream.text && data[at] == CTRL_Z);
|
||||
if limit == 0 {
|
||||
// No room to read a character: an empty line unless the stream
|
||||
// has ended.
|
||||
return Ok((!ended).then(Vec::new));
|
||||
}
|
||||
let mut line = Vec::new();
|
||||
while line.len() < limit && at < data.len() {
|
||||
let mut byte = data[at];
|
||||
if stream.text {
|
||||
if byte == CTRL_Z {
|
||||
break;
|
||||
}
|
||||
if byte == b'\r' && data.get(at + 1) == Some(&b'\n') {
|
||||
at += 1;
|
||||
byte = b'\n';
|
||||
}
|
||||
}
|
||||
at += 1;
|
||||
line.push(byte);
|
||||
if byte == b'\n' {
|
||||
break;
|
||||
}
|
||||
}
|
||||
stream.position = at as u64;
|
||||
Ok((!line.is_empty()).then_some(line))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::parse_mode;
|
||||
|
||||
/// The six access types of the `fopen` page, each alone and with `t` or
|
||||
/// `b`, and what the page says of each.
|
||||
#[test]
|
||||
fn modes_follow_the_fopen_page() {
|
||||
// (mode, readable, writable, append, must exist, truncates)
|
||||
for (mode, readable, writable, append, existing, truncate) in [
|
||||
("r", true, false, false, true, false),
|
||||
("w", false, true, false, false, true),
|
||||
("a", false, true, true, false, false),
|
||||
("r+", true, true, false, true, false),
|
||||
("w+", true, true, false, false, true),
|
||||
("a+", true, true, true, false, false),
|
||||
] {
|
||||
for (suffix, text) in [("", true), ("t", true), ("b", false)] {
|
||||
let mut spellings = vec![format!("{mode}{suffix}")];
|
||||
if mode.len() == 2 && !suffix.is_empty() {
|
||||
// "rb+" is the same mode as "r+b".
|
||||
spellings.push(format!("{}{suffix}+", &mode[..1]));
|
||||
}
|
||||
for spelling in spellings {
|
||||
let parsed = parse_mode(spelling.as_bytes())
|
||||
.unwrap_or_else(|| panic!("{spelling} is a mode"));
|
||||
assert_eq!(
|
||||
(
|
||||
parsed.readable,
|
||||
parsed.writable,
|
||||
parsed.append,
|
||||
parsed.existing,
|
||||
parsed.truncate,
|
||||
parsed.text
|
||||
),
|
||||
(readable, writable, append, existing, truncate, text),
|
||||
"{spelling}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
// "If t or b is prefixed to the argument, the function fails." The
|
||||
// other mode characters the page lists are not opened here, and
|
||||
// neither is anything that is not a mode.
|
||||
for mode in [
|
||||
"",
|
||||
"t",
|
||||
"b",
|
||||
"tr",
|
||||
"br",
|
||||
"+r",
|
||||
"x",
|
||||
"rw",
|
||||
"wr",
|
||||
"ra",
|
||||
"rbt",
|
||||
"rtb",
|
||||
"r++",
|
||||
"rbb",
|
||||
"wtt",
|
||||
"wx",
|
||||
"w+x",
|
||||
"rc",
|
||||
"rn",
|
||||
"rN",
|
||||
"rS",
|
||||
"rR",
|
||||
"wT",
|
||||
"wD",
|
||||
"r,ccs=UTF-8",
|
||||
"R",
|
||||
"W",
|
||||
"r ",
|
||||
" r",
|
||||
"rb+t",
|
||||
] {
|
||||
assert!(parse_mode(mode.as_bytes()).is_none(), "{mode:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! The standard streams of a hosted C program, and where their output goes.
|
||||
//! The streams of a hosted C program, and where their output goes.
|
||||
//!
|
||||
//! `__acrt_iob_func` hands out the `FILE` objects for `stdin`, `stdout` and
|
||||
//! `stderr`. What the guest writes to `stdout` and to `stderr` is kept in two
|
||||
@@ -12,10 +12,15 @@
|
||||
//! binary mode file I/O" and "fwrite"). The buffers hold the bytes after that
|
||||
//! replacement, which is what the operating system would be handed.
|
||||
//!
|
||||
//! A stream that `fopen` returned is a file on the in-memory drive; its rules
|
||||
//! are in `crt_files.rs`.
|
||||
//!
|
||||
//! Output is never held back: there is no buffering to flush or to configure.
|
||||
//! Any other stream, and input, are not modelled, and using one stops the
|
||||
//! guest with the runtime-limit fault.
|
||||
//! A pointer that is no stream, reading `stdin` and closing a standard stream
|
||||
//! are not modelled and stop the guest with the runtime-limit fault.
|
||||
|
||||
use super::ObjectState;
|
||||
use super::crt_files::{self, EBADF, EINVAL, FileStreams};
|
||||
use super::crt_format::{self, FormatError, Source};
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::memory::{GuestMemory, MemoryError, PROCESS_HEAP};
|
||||
@@ -26,6 +31,8 @@ const RUNTIME_LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE);
|
||||
const FILE_BYTES: u64 = 8;
|
||||
/// The most a format string or one `fwrite` or `fputs` may hold.
|
||||
const MAX_TRANSFER: u64 = 1 << 20;
|
||||
/// The longest file name or mode string `fopen` reads, in bytes.
|
||||
const MAX_NAME: u64 = 260;
|
||||
/// The most each captured stream keeps. Writing past it stops the guest.
|
||||
pub const MAX_CAPTURED_OUTPUT: usize = 16 << 20;
|
||||
|
||||
@@ -45,6 +52,8 @@ enum Stream {
|
||||
Input,
|
||||
Output,
|
||||
Error,
|
||||
/// A stream `fopen` returned, by the address of its `FILE` object.
|
||||
File(u64),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -53,13 +62,15 @@ pub(super) struct StandardStreams {
|
||||
files: Option<u64>,
|
||||
output: Vec<u8>,
|
||||
error: Vec<u8>,
|
||||
/// The streams `fopen` has open.
|
||||
opened: FileStreams,
|
||||
}
|
||||
|
||||
/// What a service returns when its documentation gives a failure result and
|
||||
/// an `errno` value: the handler sets `errno` to `EINVAL` and returns this.
|
||||
pub(super) struct Invalid<T>(pub T);
|
||||
/// What a service returns when it fails with a result and an `errno` value:
|
||||
/// the handler sets `errno` to the second field and returns the first.
|
||||
pub(super) struct Failed<T>(pub T, pub u32);
|
||||
|
||||
pub(super) type Outcome<T> = Result<Result<T, Invalid<T>>, ExitReason>;
|
||||
pub(super) type Outcome<T> = Result<Result<T, Failed<T>>, ExitReason>;
|
||||
|
||||
fn fault(error: MemoryError) -> ExitReason {
|
||||
ExitReason::MemoryFault(error)
|
||||
@@ -125,19 +136,19 @@ impl StandardStreams {
|
||||
Ok(base + FILE_BYTES * u64::from(index))
|
||||
}
|
||||
|
||||
/// Which standard stream a non-null `FILE*` is. Any other pointer is a
|
||||
/// stream this runtime does not have.
|
||||
/// Which stream a non-null `FILE*` is: a standard stream, or one `fopen`
|
||||
/// returned. Any other pointer is no stream.
|
||||
fn stream(&self, file: u64) -> Result<Stream, ExitReason> {
|
||||
let base = self.files.ok_or(RUNTIME_LIMIT)?;
|
||||
match file.wrapping_sub(base) {
|
||||
0 => Ok(Stream::Input),
|
||||
8 => Ok(Stream::Output),
|
||||
16 => Ok(Stream::Error),
|
||||
match self.files.map(|base| file.wrapping_sub(base)) {
|
||||
Some(0) => Ok(Stream::Input),
|
||||
Some(8) => Ok(Stream::Output),
|
||||
Some(16) => Ok(Stream::Error),
|
||||
_ if self.opened.contains(file) => Ok(Stream::File(file)),
|
||||
_ => Err(RUNTIME_LIMIT),
|
||||
}
|
||||
}
|
||||
|
||||
/// A stream that can be written: `stdout` or `stderr`.
|
||||
/// A stream that may be written. Writing `stdin` is not modelled.
|
||||
fn writable(&self, file: u64) -> Result<Stream, ExitReason> {
|
||||
match self.stream(file)? {
|
||||
Stream::Input => Err(RUNTIME_LIMIT),
|
||||
@@ -145,13 +156,20 @@ impl StandardStreams {
|
||||
}
|
||||
}
|
||||
|
||||
/// Append to a captured stream, in text mode: each line feed becomes a
|
||||
/// carriage return and a line feed.
|
||||
fn write(&mut self, stream: Stream, bytes: &[u8]) -> Result<(), ExitReason> {
|
||||
/// Write to a stream. A standard stream is captured in text mode: each
|
||||
/// line feed becomes a carriage return and a line feed. A file stream can
|
||||
/// fail, with the `errno` value in the inner result and nothing written.
|
||||
fn write(
|
||||
&mut self,
|
||||
drive: &mut ObjectState,
|
||||
stream: Stream,
|
||||
bytes: &[u8],
|
||||
) -> Result<Result<(), u32>, ExitReason> {
|
||||
let captured = match stream {
|
||||
Stream::Output => &mut self.output,
|
||||
Stream::Error => &mut self.error,
|
||||
Stream::Input => return Err(RUNTIME_LIMIT),
|
||||
Stream::File(file) => return Ok(self.opened.write(drive, file, bytes)),
|
||||
};
|
||||
let feeds = bytes.iter().filter(|byte| **byte == b'\n').count();
|
||||
if bytes.len() + feeds > MAX_CAPTURED_OUTPUT - captured.len() {
|
||||
@@ -163,14 +181,16 @@ impl StandardStreams {
|
||||
}
|
||||
captured.push(byte);
|
||||
}
|
||||
Ok(())
|
||||
Ok(Ok(()))
|
||||
}
|
||||
|
||||
/// `__stdio_common_vfprintf`. Returns the number of characters written,
|
||||
/// before the text-mode replacement.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn print(
|
||||
&mut self,
|
||||
memory: &GuestMemory,
|
||||
drive: &mut ObjectState,
|
||||
options: u64,
|
||||
file: u64,
|
||||
format: u64,
|
||||
@@ -179,7 +199,7 @@ impl StandardStreams {
|
||||
) -> Outcome<i32> {
|
||||
// A null stream or format: the function returns -1 and sets errno.
|
||||
if file == 0 || format == 0 {
|
||||
return Ok(Err(Invalid(-1)));
|
||||
return Ok(Err(Failed(-1, EINVAL)));
|
||||
}
|
||||
if options & !IGNORED_OPTIONS != 0 || locale != 0 {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
@@ -198,25 +218,29 @@ impl StandardStreams {
|
||||
// Windows calls the invalid parameter handler for an invalid
|
||||
// format. Xenora's choice for when execution continues: nothing
|
||||
// is written and the result is that of a null format.
|
||||
Err(FormatError::Invalid) => return Ok(Err(Invalid(-1))),
|
||||
Err(FormatError::Invalid) => return Ok(Err(Failed(-1, EINVAL))),
|
||||
Err(FormatError::Unsupported | FormatError::TooLong) => return Err(RUNTIME_LIMIT),
|
||||
Err(FormatError::Fault(error)) => return Err(fault(error)),
|
||||
};
|
||||
self.write(stream, &text)?;
|
||||
Ok(Ok(text.len() as i32))
|
||||
// "A negative value if an output error occurs."
|
||||
Ok(match self.write(drive, stream, &text)? {
|
||||
Ok(()) => Ok(text.len() as i32),
|
||||
Err(errno) => Err(Failed(-1, errno)),
|
||||
})
|
||||
}
|
||||
|
||||
/// `fwrite`. Returns the number of whole items written.
|
||||
pub(super) fn write_items(
|
||||
&mut self,
|
||||
memory: &GuestMemory,
|
||||
drive: &mut ObjectState,
|
||||
buffer: u64,
|
||||
size: u64,
|
||||
count: u64,
|
||||
file: u64,
|
||||
) -> Outcome<u64> {
|
||||
if buffer == 0 || file == 0 {
|
||||
return Ok(Err(Invalid(0)));
|
||||
return Ok(Err(Failed(0, EINVAL)));
|
||||
}
|
||||
let stream = self.writable(file)?;
|
||||
let Some(length) = size
|
||||
@@ -230,8 +254,12 @@ impl StandardStreams {
|
||||
}
|
||||
let mut bytes = vec![0; length as usize];
|
||||
memory.read_bytes(buffer, &mut bytes).map_err(fault)?;
|
||||
self.write(stream, &bytes)?;
|
||||
Ok(Ok(count))
|
||||
// Fewer items than `count` means an error. A failed write here
|
||||
// writes none of them.
|
||||
Ok(match self.write(drive, stream, &bytes)? {
|
||||
Ok(()) => Ok(count),
|
||||
Err(errno) => Err(Failed(0, errno)),
|
||||
})
|
||||
}
|
||||
|
||||
/// `fputs`. Writes the string without its terminator and returns a
|
||||
@@ -239,19 +267,22 @@ impl StandardStreams {
|
||||
pub(super) fn put_string(
|
||||
&mut self,
|
||||
memory: &GuestMemory,
|
||||
drive: &mut ObjectState,
|
||||
text: u64,
|
||||
file: u64,
|
||||
) -> Outcome<i32> {
|
||||
if text == 0 || file == 0 {
|
||||
return Ok(Err(Invalid(-1)));
|
||||
return Ok(Err(Failed(-1, EINVAL)));
|
||||
}
|
||||
let stream = self.writable(file)?;
|
||||
let bytes = c_string(memory, text, MAX_TRANSFER + 1).map_err(fault)?;
|
||||
if bytes.len() as u64 > MAX_TRANSFER {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
}
|
||||
self.write(stream, &bytes)?;
|
||||
Ok(Ok(0))
|
||||
Ok(match self.write(drive, stream, &bytes)? {
|
||||
Ok(()) => Ok(0),
|
||||
Err(errno) => Err(Failed(-1, errno)),
|
||||
})
|
||||
}
|
||||
|
||||
/// `fflush`. A null stream means every open stream. Nothing is ever held
|
||||
@@ -267,7 +298,7 @@ impl StandardStreams {
|
||||
/// no effect.
|
||||
pub(super) fn set_buffer(&self, file: u64, mode: i32, size: u64) -> Outcome<i32> {
|
||||
if file == 0 {
|
||||
return Ok(Err(Invalid(-1)));
|
||||
return Ok(Err(Failed(-1, EINVAL)));
|
||||
}
|
||||
self.stream(file)?;
|
||||
let valid = match mode {
|
||||
@@ -277,6 +308,105 @@ impl StandardStreams {
|
||||
IOFBF | IOLBF => (2..=i32::MAX as u64).contains(&size),
|
||||
_ => false,
|
||||
};
|
||||
Ok(if valid { Ok(0) } else { Err(Invalid(-1)) })
|
||||
Ok(if valid {
|
||||
Ok(0)
|
||||
} else {
|
||||
Err(Failed(-1, EINVAL))
|
||||
})
|
||||
}
|
||||
|
||||
/// `fopen`. Returns the new `FILE*`, or null with the `errno` value.
|
||||
pub(super) fn open(
|
||||
&mut self,
|
||||
memory: &mut GuestMemory,
|
||||
drive: &mut ObjectState,
|
||||
name: u64,
|
||||
mode: u64,
|
||||
) -> Outcome<u64> {
|
||||
// A null name or mode is an invalid parameter, as an empty one is.
|
||||
if name == 0 || mode == 0 {
|
||||
return Ok(Err(Failed(0, EINVAL)));
|
||||
}
|
||||
let name = c_string(memory, name, MAX_NAME + 1).map_err(fault)?;
|
||||
let mode = c_string(memory, mode, MAX_NAME + 1).map_err(fault)?;
|
||||
if name.len() as u64 > MAX_NAME || mode.len() as u64 > MAX_NAME {
|
||||
return Ok(Err(Failed(0, EINVAL)));
|
||||
}
|
||||
Ok(self
|
||||
.opened
|
||||
.open(memory, drive, &name, &mode)
|
||||
.map_err(|errno| Failed(0, errno)))
|
||||
}
|
||||
|
||||
/// `fclose`. Returns 0, or `EOF` with `EINVAL` for a null stream. Closing
|
||||
/// a standard stream is not modelled.
|
||||
pub(super) fn close(&mut self, memory: &mut GuestMemory, file: u64) -> Outcome<i32> {
|
||||
if file == 0 {
|
||||
return Ok(Err(Failed(-1, EINVAL)));
|
||||
}
|
||||
match self.stream(file)? {
|
||||
Stream::File(file) => {
|
||||
self.opened.close(memory, file);
|
||||
Ok(Ok(0))
|
||||
}
|
||||
_ => Err(RUNTIME_LIMIT),
|
||||
}
|
||||
}
|
||||
|
||||
/// `fgets`. Returns `buffer`, or null at end of file or on an error.
|
||||
pub(super) fn get_line(
|
||||
&mut self,
|
||||
memory: &mut GuestMemory,
|
||||
drive: &ObjectState,
|
||||
buffer: u64,
|
||||
count: i32,
|
||||
file: u64,
|
||||
) -> Outcome<u64> {
|
||||
if buffer == 0 || file == 0 || count <= 0 {
|
||||
return Ok(Err(Failed(0, EINVAL)));
|
||||
}
|
||||
let file = match self.stream(file)? {
|
||||
Stream::File(file) => file,
|
||||
// Reading the standard input is not modelled.
|
||||
Stream::Input => return Err(RUNTIME_LIMIT),
|
||||
// The output streams cannot be read.
|
||||
Stream::Output | Stream::Error => return Ok(Err(Failed(0, EBADF))),
|
||||
};
|
||||
// Up to count - 1 characters, and then the terminator.
|
||||
let limit = ((count - 1) as u64).min(MAX_TRANSFER) as usize;
|
||||
let mut line = match self.opened.read_line(drive, file, limit) {
|
||||
Ok(Some(line)) => line,
|
||||
// End of file with nothing read: null, and the buffer is left
|
||||
// alone.
|
||||
Ok(None) => return Ok(Ok(0)),
|
||||
Err(errno) => return Ok(Err(Failed(0, errno))),
|
||||
};
|
||||
line.push(0);
|
||||
memory.write_bytes(buffer, &line).map_err(fault)?;
|
||||
Ok(Ok(buffer))
|
||||
}
|
||||
|
||||
/// `perror`: the message, a colon and a space when there is a message,
|
||||
/// then the text for `errno` and a newline, to `stderr`.
|
||||
pub(super) fn report(
|
||||
&mut self,
|
||||
memory: &GuestMemory,
|
||||
drive: &mut ObjectState,
|
||||
message: u64,
|
||||
errno: u32,
|
||||
) -> Result<(), ExitReason> {
|
||||
let mut text = Vec::new();
|
||||
if message != 0 {
|
||||
text = c_string(memory, message, MAX_TRANSFER + 1).map_err(fault)?;
|
||||
if text.len() as u64 > MAX_TRANSFER {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
}
|
||||
}
|
||||
if !text.is_empty() {
|
||||
text.extend_from_slice(b": ");
|
||||
}
|
||||
text.extend_from_slice(crt_files::error_text(errno).as_bytes());
|
||||
text.push(b'\n');
|
||||
self.write(drive, Stream::Error, &text).map(|_| ())
|
||||
}
|
||||
}
|
||||
@@ -625,3 +625,89 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
}
|
||||
|
||||
/// What a path names on the drive, for the C runtime's file streams.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum DriveEntry {
|
||||
File,
|
||||
Directory,
|
||||
/// Nothing has this name. `parent` says whether its directory exists.
|
||||
Missing {
|
||||
parent: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// The drive as the C runtime's file streams (`crt_files.rs`) use it. They read
|
||||
/// and write the same files as the handle services above. A stream is not a
|
||||
/// handle: it takes no part in sharing, and a file it has open can be deleted
|
||||
/// or moved, after which its operations fail.
|
||||
impl super::ObjectState {
|
||||
/// A narrow file name as the drive stores it: ASCII, either slash, any
|
||||
/// case, with or without `C:\`. `None` for a name the drive rejects.
|
||||
pub(super) fn drive_path(name: &[u8]) -> Option<String> {
|
||||
if !name.is_ascii() {
|
||||
return None;
|
||||
}
|
||||
let path = String::from_utf8_lossy(name)
|
||||
.replace('/', "\\")
|
||||
.to_ascii_lowercase();
|
||||
let path = path.strip_prefix("c:\\").unwrap_or(&path).to_owned();
|
||||
path.split('\\').all(valid_component).then_some(path)
|
||||
}
|
||||
|
||||
pub(super) fn drive_entry(&self, path: &str) -> DriveEntry {
|
||||
if self.files.contains_key(path) {
|
||||
DriveEntry::File
|
||||
} else if self.directories.contains(path) {
|
||||
DriveEntry::Directory
|
||||
} else {
|
||||
let parent = parent(path);
|
||||
DriveEntry::Missing {
|
||||
parent: parent.is_empty() || self.directories.contains(parent),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create an empty file. False when the drive already holds as many files
|
||||
/// as it can.
|
||||
pub(super) fn drive_create(&mut self, path: &str) -> bool {
|
||||
if self.files.len() >= MAX_FILES {
|
||||
return false;
|
||||
}
|
||||
self.files.insert(path.to_owned(), Vec::new());
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn drive_file(&self, path: &str) -> Option<&[u8]> {
|
||||
self.files.get(path).map(Vec::as_slice)
|
||||
}
|
||||
|
||||
/// Empty a file. False when it does not exist.
|
||||
pub(super) fn drive_truncate(&mut self, path: &str) -> bool {
|
||||
self.files.get_mut(path).map(Vec::clear).is_some()
|
||||
}
|
||||
|
||||
/// Write `bytes` at `position`, growing the file as needed. `None` when
|
||||
/// the file does not exist; `Some(false)`, with nothing written, when the
|
||||
/// write would pass the drive's size bound.
|
||||
pub(super) fn drive_write(&mut self, path: &str, position: u64, bytes: &[u8]) -> Option<bool> {
|
||||
let used: usize = self.files.values().map(Vec::len).sum();
|
||||
let data = self.files.get_mut(path)?;
|
||||
let Some(end) = position
|
||||
.checked_add(bytes.len() as u64)
|
||||
.filter(|end| *end <= MAX_BYTES as u64)
|
||||
else {
|
||||
return Some(false);
|
||||
};
|
||||
let (start, end) = (position as usize, end as usize);
|
||||
let growth = end.saturating_sub(data.len());
|
||||
if growth > MAX_BYTES - used {
|
||||
return Some(false);
|
||||
}
|
||||
if growth != 0 {
|
||||
data.resize(end, 0);
|
||||
}
|
||||
data[start..end].copy_from_slice(bytes);
|
||||
Some(true)
|
||||
}
|
||||
}
|
||||
@@ -5723,10 +5723,9 @@ fn interpreter_executes_modified_code_after_a_jump() {
|
||||
assert_eq!(self_modified_result(Engine::Interpreter), wanted);
|
||||
}
|
||||
|
||||
/// Known defect: the DBT keeps running the block it translated before the store.
|
||||
/// The DBT must not keep running the block it translated before the store (#84).
|
||||
#[test]
|
||||
#[ignore = "known defect (#155): the DBT keeps translated blocks after the guest rewrites their code"]
|
||||
fn defect_dbt_executes_modified_code_after_a_jump() {
|
||||
fn dbt_executes_modified_code_after_a_jump() {
|
||||
for engine in [Engine::Dbt, Engine::DbtStepped] {
|
||||
let wanted = (1, 2, ExitReason::Halt);
|
||||
assert_eq!(self_modified_result(engine), wanted, "{engine:?}");
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! C runtime file streams and the Win32 file services on one drive (issue
|
||||
//! #402). On Windows the C runtime's streams sit on Win32 files, so a file
|
||||
//! written through one is the file read through the other.
|
||||
//!
|
||||
//! In text mode a C stream writes each line feed as a carriage return and a
|
||||
//! line feed and reads the pair back as a line feed (Microsoft Learn, "fopen,
|
||||
//! _wfopen"). `ReadFile` and `WriteFile` transfer bytes as they are. Expected
|
||||
//! bytes are what each test wrote, with that translation applied by hand.
|
||||
|
||||
mod support;
|
||||
|
||||
use support::*;
|
||||
use xenora_loader::cpu::ExitReason;
|
||||
|
||||
const KERNEL32: &str = "kernel32.dll";
|
||||
const UCRT: &str = "ucrtbase.dll";
|
||||
|
||||
const IMPORTS: &[(&str, &str)] = &[
|
||||
(KERNEL32, "CreateFileW"),
|
||||
(KERNEL32, "ReadFile"),
|
||||
(KERNEL32, "WriteFile"),
|
||||
(KERNEL32, "CloseHandle"),
|
||||
(KERNEL32, "CreateDirectoryW"),
|
||||
(KERNEL32, "DeleteFileW"),
|
||||
(UCRT, "fopen"),
|
||||
(UCRT, "fclose"),
|
||||
(UCRT, "fgets"),
|
||||
(UCRT, "fputs"),
|
||||
(UCRT, "_errno"),
|
||||
(UCRT, "malloc"),
|
||||
(UCRT, "free"),
|
||||
];
|
||||
|
||||
const GENERIC_READ: u64 = 0x8000_0000;
|
||||
const GENERIC_WRITE: u64 = 0x4000_0000;
|
||||
const CREATE_ALWAYS: u64 = 2;
|
||||
const OPEN_EXISTING: u64 = 3;
|
||||
const INVALID_HANDLE: u64 = u64::MAX;
|
||||
const ENOENT: u32 = 2;
|
||||
const EBADF: u32 = 9;
|
||||
const ENOMEM: u32 = 12;
|
||||
const EACCES: u32 = 13;
|
||||
|
||||
// Scratch layout: a wide name, a narrow name, a mode, a transfer buffer and a
|
||||
// count.
|
||||
const WIDE: u64 = SCRATCH;
|
||||
const NARROW: u64 = SCRATCH + 0x200;
|
||||
const MODE: u64 = SCRATCH + 0x300;
|
||||
const BUFFER: u64 = SCRATCH + 0x400;
|
||||
const COUNT: u64 = SCRATCH + 0x800;
|
||||
|
||||
fn guest() -> Guest {
|
||||
Guest::new(IMPORTS, &[])
|
||||
}
|
||||
|
||||
fn narrow(guest: &mut Guest, at: u64, text: &str) -> u64 {
|
||||
guest.memory.write_bytes(at, text.as_bytes()).unwrap();
|
||||
guest.memory.write_u8(at + text.len() as u64, 0).unwrap();
|
||||
at
|
||||
}
|
||||
|
||||
fn wide(guest: &mut Guest, text: &str) -> u64 {
|
||||
let units: Vec<u8> = text
|
||||
.encode_utf16()
|
||||
.chain([0])
|
||||
.flat_map(u16::to_le_bytes)
|
||||
.collect();
|
||||
guest.memory.write_bytes(WIDE, &units).unwrap();
|
||||
WIDE
|
||||
}
|
||||
|
||||
fn errno(guest: &mut Guest) -> u32 {
|
||||
let address = guest.call("_errno", &[]);
|
||||
guest.u32_at(address)
|
||||
}
|
||||
|
||||
fn fopen(guest: &mut Guest, name: &str, mode: &str) -> u64 {
|
||||
let name = narrow(guest, NARROW, name);
|
||||
let mode = narrow(guest, MODE, mode);
|
||||
guest.call("fopen", &[name, mode])
|
||||
}
|
||||
|
||||
/// `CreateFileW` with no sharing restriction on later opens.
|
||||
fn create_file(guest: &mut Guest, name: &str, access: u64, disposition: u64) -> u64 {
|
||||
let name = wide(guest, name);
|
||||
guest.call("CreateFileW", &[name, access, 3, 0, disposition, 0, 0])
|
||||
}
|
||||
|
||||
/// Everything `ReadFile` returns for a file, up to 256 bytes.
|
||||
fn read_through_win32(guest: &mut Guest, name: &str) -> Vec<u8> {
|
||||
let handle = create_file(guest, name, GENERIC_READ, OPEN_EXISTING);
|
||||
assert_ne!(handle, INVALID_HANDLE, "{name}");
|
||||
assert_eq!(guest.call("ReadFile", &[handle, BUFFER, 256, COUNT, 0]), 1);
|
||||
let count = guest.u32_at(COUNT) as usize;
|
||||
let mut bytes = vec![0; count];
|
||||
guest.memory.read_bytes(BUFFER, &mut bytes).unwrap();
|
||||
assert_eq!(guest.call("CloseHandle", &[handle]), 1);
|
||||
bytes
|
||||
}
|
||||
|
||||
fn write_through_win32(guest: &mut Guest, name: &str, bytes: &[u8]) {
|
||||
let handle = create_file(guest, name, GENERIC_WRITE, CREATE_ALWAYS);
|
||||
assert_ne!(handle, INVALID_HANDLE, "{name}");
|
||||
guest.memory.write_bytes(BUFFER, bytes).unwrap();
|
||||
let count = bytes.len() as u64;
|
||||
assert_eq!(
|
||||
guest.call("WriteFile", &[handle, BUFFER, count, COUNT, 0]),
|
||||
1
|
||||
);
|
||||
assert_eq!(u64::from(guest.u32_at(COUNT)), count);
|
||||
assert_eq!(guest.call("CloseHandle", &[handle]), 1);
|
||||
}
|
||||
|
||||
fn put(guest: &mut Guest, stream: u64, text: &str) -> u32 {
|
||||
let text = narrow(guest, BUFFER, text);
|
||||
guest.call("fputs", &[text, stream]) as u32
|
||||
}
|
||||
|
||||
/// One `fgets` of up to 127 characters.
|
||||
fn get(guest: &mut Guest, stream: u64) -> Option<Vec<u8>> {
|
||||
if guest.call("fgets", &[BUFFER, 128, stream]) == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut bytes = vec![0; 128];
|
||||
guest.memory.read_bytes(BUFFER, &mut bytes).unwrap();
|
||||
let end = bytes.iter().position(|byte| *byte == 0).unwrap();
|
||||
bytes.truncate(end);
|
||||
Some(bytes)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_written_through_a_c_stream_is_read_through_win32() {
|
||||
let mut guest = guest();
|
||||
// Text mode stores a carriage return before each line feed.
|
||||
let stream = fopen(&mut guest, "from-c.txt", "w");
|
||||
assert_ne!(stream, 0);
|
||||
assert_eq!(put(&mut guest, stream, "line one\nline two\n"), 0);
|
||||
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
|
||||
assert_eq!(
|
||||
read_through_win32(&mut guest, "C:\\from-c.txt"),
|
||||
b"line one\r\nline two\r\n"
|
||||
);
|
||||
// Binary mode stores what was written.
|
||||
let stream = fopen(&mut guest, "from-c.bin", "wb");
|
||||
assert_eq!(put(&mut guest, stream, "raw\nbytes"), 0);
|
||||
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
|
||||
assert_eq!(read_through_win32(&mut guest, "from-c.bin"), b"raw\nbytes");
|
||||
// Nothing is held back: the bytes are on the drive before fclose.
|
||||
let stream = fopen(&mut guest, "unflushed.bin", "wb");
|
||||
assert_eq!(put(&mut guest, stream, "now"), 0);
|
||||
assert_eq!(read_through_win32(&mut guest, "unflushed.bin"), b"now");
|
||||
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_written_through_win32_is_read_through_a_c_stream() {
|
||||
let mut guest = guest();
|
||||
write_through_win32(&mut guest, "C:\\from-win32.txt", b"win32\r\ndata\nlast");
|
||||
// Text mode reads the pair as one line feed and leaves a lone one alone.
|
||||
let stream = fopen(&mut guest, "from-win32.txt", "r");
|
||||
assert_ne!(stream, 0);
|
||||
assert_eq!(get(&mut guest, stream).as_deref(), Some(&b"win32\n"[..]));
|
||||
assert_eq!(get(&mut guest, stream).as_deref(), Some(&b"data\n"[..]));
|
||||
assert_eq!(get(&mut guest, stream).as_deref(), Some(&b"last"[..]));
|
||||
assert_eq!(get(&mut guest, stream), None);
|
||||
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
|
||||
// Binary mode reads the bytes as they are.
|
||||
let stream = fopen(&mut guest, "from-win32.txt", "rb");
|
||||
assert_eq!(get(&mut guest, stream).as_deref(), Some(&b"win32\r\n"[..]));
|
||||
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
|
||||
// A file Win32 created is there for "r", and "w" destroys its contents
|
||||
// for Win32 too.
|
||||
let stream = fopen(&mut guest, "from-win32.txt", "w");
|
||||
assert_ne!(stream, 0);
|
||||
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
|
||||
assert!(read_through_win32(&mut guest, "from-win32.txt").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directories_are_not_files_and_hold_files() {
|
||||
let mut guest = guest();
|
||||
let name = wide(&mut guest, "C:\\folder");
|
||||
assert_eq!(guest.call("CreateDirectoryW", &[name, 0]), 1);
|
||||
// A directory cannot be opened as a stream, for reading or writing.
|
||||
for mode in ["r", "w", "a", "r+"] {
|
||||
assert_eq!(fopen(&mut guest, "folder", mode), 0, "{mode}");
|
||||
assert_eq!(errno(&mut guest), EACCES, "{mode}");
|
||||
}
|
||||
// A file inside it can, by either slash.
|
||||
let stream = fopen(&mut guest, "folder/inside.txt", "wb");
|
||||
assert_ne!(stream, 0);
|
||||
assert_eq!(put(&mut guest, stream, "in"), 0);
|
||||
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
|
||||
assert_eq!(
|
||||
read_through_win32(&mut guest, "c:\\FOLDER\\inside.txt"),
|
||||
b"in"
|
||||
);
|
||||
// A directory that does not exist has no files.
|
||||
assert_eq!(fopen(&mut guest, "nowhere\\inside.txt", "w"), 0);
|
||||
assert_eq!(errno(&mut guest), ENOENT);
|
||||
}
|
||||
|
||||
/// A C stream is not a Win32 handle: it does not stop the file being deleted.
|
||||
/// Once the file is gone the stream's operations fail with `EBADF`, and
|
||||
/// closing it still succeeds. This is Xenora's behaviour, not Windows's,
|
||||
/// where the open stream would keep the file from being deleted.
|
||||
#[test]
|
||||
fn a_stream_whose_file_was_deleted_fails_cleanly() {
|
||||
let mut guest = guest();
|
||||
let stream = fopen(&mut guest, "gone.txt", "w+b");
|
||||
assert_ne!(stream, 0);
|
||||
assert_eq!(put(&mut guest, stream, "data\n"), 0);
|
||||
let name = wide(&mut guest, "C:\\gone.txt");
|
||||
assert_eq!(guest.call("DeleteFileW", &[name]), 1);
|
||||
assert_eq!(put(&mut guest, stream, "more"), u32::MAX);
|
||||
assert_eq!(errno(&mut guest), EBADF);
|
||||
assert_eq!(get(&mut guest, stream), None);
|
||||
assert_eq!(errno(&mut guest), EBADF);
|
||||
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
|
||||
// The closed stream is no stream any more.
|
||||
let exit = guest.fails("fclose", &[stream]);
|
||||
assert_eq!(exit, RUNTIME_LIMIT);
|
||||
assert!(matches!(exit, ExitReason::IllegalInstruction(0xFE)));
|
||||
// And the name is free again.
|
||||
assert_eq!(fopen(&mut guest, "gone.txt", "r"), 0);
|
||||
assert_eq!(errno(&mut guest), ENOENT);
|
||||
}
|
||||
|
||||
/// A `FILE` object comes from the process heap. When the heap has no room for
|
||||
/// one, `fopen` fails with `ENOMEM` and has neither created the file nor
|
||||
/// destroyed the contents of an existing one. The heap holds 4,096 blocks.
|
||||
#[test]
|
||||
fn an_fopen_that_cannot_allocate_leaves_the_drive_alone() {
|
||||
let mut guest = guest();
|
||||
write_through_win32(&mut guest, "kept.txt", b"keep me");
|
||||
// Fill the heap one byte at a time until it refuses.
|
||||
let mut blocks = Vec::new();
|
||||
loop {
|
||||
let block = guest.call("malloc", &[1]);
|
||||
if block == 0 {
|
||||
break;
|
||||
}
|
||||
blocks.push(block);
|
||||
assert!(blocks.len() <= 4096, "the heap never filled");
|
||||
}
|
||||
for (name, mode) in [
|
||||
("new.txt", "w"),
|
||||
("new.txt", "a"),
|
||||
("kept.txt", "w"),
|
||||
("kept.txt", "r"),
|
||||
] {
|
||||
assert_eq!(fopen(&mut guest, name, mode), 0, "{name} {mode}");
|
||||
assert_eq!(errno(&mut guest), ENOMEM, "{name} {mode}");
|
||||
}
|
||||
// With room for one block again: the new file was never created, and the
|
||||
// existing one still has its contents.
|
||||
guest.call("free", &[blocks.pop().unwrap()]);
|
||||
assert_eq!(fopen(&mut guest, "new.txt", "r"), 0);
|
||||
assert_eq!(errno(&mut guest), ENOENT);
|
||||
assert_eq!(read_through_win32(&mut guest, "kept.txt"), b"keep me");
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Run the benchmark's report, comparison and percentile tests in normal CI.
|
||||
//! Timing runs remain confined to the standalone benchmark entry point.
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[path = "../benches/dbt_bench.rs"]
|
||||
mod benchmark;
|
||||
@@ -0,0 +1,440 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Gate A2 (issue #419): a hosted C program, built from source by this test
|
||||
//! with the mingw-w64 C runtime and run through the loader, the standard
|
||||
//! services and the ARM64 DBT.
|
||||
//!
|
||||
//! "Hosted" means the C runtime's own startup code runs before `main`, and
|
||||
//! the program uses the standard C library as an ordinary program does:
|
||||
//! command-line arguments, heap memory, `qsort` with a callback, `printf`, a
|
||||
//! file written with `fprintf` and read back with `fgets`, `atexit`, and a
|
||||
//! return from `main`.
|
||||
//!
|
||||
//! `tests/compat_fixtures/build-gate-a2.sh` compiles
|
||||
//! `tests/compat_fixtures/gate_a2.c` with `x86_64-w64-mingw32-gcc`, so the
|
||||
//! test needs mingw-w64 on the host. It fails, and does not skip, when the
|
||||
//! compiler is missing.
|
||||
//!
|
||||
//! Every expected value is recomputed here, in Rust, from the description of
|
||||
//! the program: nothing is read back from a run and asserted. The host
|
||||
//! arithmetic and the guest arithmetic share no code. The program also
|
||||
//! checks its own results and exits with the number of the first check that
|
||||
//! fails, and three control variants end in three other ways, so a runtime
|
||||
//! that reported success for everything would fail this test.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use xenora_loader::cpu::ExitReason;
|
||||
use xenora_loader::imports::ImportRegistry;
|
||||
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
|
||||
use xenora_loader::startup::{StartupLayout, StartupResult, run_synthetic_startup};
|
||||
|
||||
const REPORT: &str = "C:\\gate-a2-report.txt";
|
||||
const COUNT: usize = 48;
|
||||
const SEED: u32 = 2026;
|
||||
const LABEL: &str = "xenora";
|
||||
const ARGUMENTS: [&str; 3] = ["gate-a2.exe", "2026", LABEL];
|
||||
const BUDGET: usize = 2_000_000;
|
||||
|
||||
/// Build every variant once and return the output directory.
|
||||
fn built() -> &'static Path {
|
||||
static OUT: OnceLock<PathBuf> = OnceLock::new();
|
||||
OUT.get_or_init(|| {
|
||||
// One directory per test process: two `cargo test` runs that share a
|
||||
// target directory must not write and read the same files.
|
||||
let out = PathBuf::from(env!("CARGO_TARGET_TMPDIR"))
|
||||
.join(format!("gate-a2-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&out);
|
||||
let script = concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../tests/compat_fixtures/build-gate-a2.sh"
|
||||
);
|
||||
let build = Command::new("sh")
|
||||
.arg(script)
|
||||
.arg(&out)
|
||||
.output()
|
||||
.expect("run tests/compat_fixtures/build-gate-a2.sh");
|
||||
assert!(
|
||||
build.status.success(),
|
||||
"the Gate A2 program did not build; it needs mingw-w64 \
|
||||
(x86_64-w64-mingw32-gcc):\n{}{}",
|
||||
String::from_utf8_lossy(&build.stdout),
|
||||
String::from_utf8_lossy(&build.stderr)
|
||||
);
|
||||
let toolchain = std::fs::read_to_string(out.join("toolchain.txt")).unwrap();
|
||||
println!("Gate A2 built with:\n{toolchain}");
|
||||
out
|
||||
})
|
||||
}
|
||||
|
||||
struct Outcome {
|
||||
result: StartupResult,
|
||||
state: Arc<ServicesState>,
|
||||
}
|
||||
|
||||
impl Outcome {
|
||||
fn output(&self) -> String {
|
||||
String::from_utf8(self.state.standard_output()).expect("ASCII output")
|
||||
}
|
||||
|
||||
fn errors(&self) -> String {
|
||||
String::from_utf8(self.state.standard_error()).expect("ASCII output")
|
||||
}
|
||||
}
|
||||
|
||||
/// Run one built variant through the real startup path with the standard
|
||||
/// services and the given command line, loaded away from its preferred base
|
||||
/// so its relocations matter.
|
||||
fn run_with(name: &str, arguments: Option<&[&str]>, budget: usize) -> Outcome {
|
||||
let bytes = std::fs::read(built().join(format!("{name}.exe"))).unwrap();
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
|
||||
if let Some(arguments) = arguments {
|
||||
state.set_program_arguments(arguments).unwrap();
|
||||
}
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, Arc::clone(&state));
|
||||
let layout = StartupLayout {
|
||||
image_base: 0x2_5000_0000,
|
||||
stack_top: 0x2_0001_0000,
|
||||
tls_base: 0x3_0000_0000,
|
||||
};
|
||||
let result = run_synthetic_startup(&bytes, layout, registry, budget)
|
||||
.unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
Outcome { result, state }
|
||||
}
|
||||
|
||||
fn run(name: &str) -> Outcome {
|
||||
run_with(name, Some(&ARGUMENTS), BUDGET)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// What the program computes, restated independently
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// The program's generator: a linear congruential step, then bits 8 to 23.
|
||||
fn values(seed: u32) -> Vec<u32> {
|
||||
let mut state = seed;
|
||||
(0..COUNT)
|
||||
.map(|_| {
|
||||
state = state.wrapping_mul(1_103_515_245).wrapping_add(12_345);
|
||||
(state >> 8) & 0xFFFF
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 64-bit FNV-1a over each value's four bytes, low byte first.
|
||||
fn checksum(values: &[u32]) -> u64 {
|
||||
values
|
||||
.iter()
|
||||
.flat_map(|value| value.to_le_bytes())
|
||||
.fold(14_695_981_039_346_656_037, |sum, byte| {
|
||||
(sum ^ u64::from(byte)).wrapping_mul(1_099_511_628_211)
|
||||
})
|
||||
}
|
||||
|
||||
struct Expected {
|
||||
/// Standard output of a complete run, with the line ends a text-mode
|
||||
/// stream produces.
|
||||
output: String,
|
||||
/// The report file as it is stored on the drive.
|
||||
report: String,
|
||||
/// What the program prints before its first self-check on the data.
|
||||
arguments: String,
|
||||
sorted_line: String,
|
||||
}
|
||||
|
||||
/// How many checks the program counts on a complete run: five on its
|
||||
/// arguments, one for the allocation, 47 on the sort order, one on the total,
|
||||
/// the first `fopen`, five on writing the report, fifteen on reading it back
|
||||
/// and one for the missing file.
|
||||
const CHECKS: u32 = 5 + 1 + 47 + 1 + 1 + 5 + 15 + 1;
|
||||
|
||||
fn expected() -> Expected {
|
||||
let unsorted = values(SEED);
|
||||
let mut sorted = unsorted.clone();
|
||||
sorted.sort_unstable();
|
||||
let total: u64 = unsorted.iter().map(|value| u64::from(*value)).sum();
|
||||
let (min, max) = (sorted[0], sorted[COUNT - 1]);
|
||||
// A text-mode stream stores each line feed as a carriage return and a
|
||||
// line feed.
|
||||
let arguments = format!(
|
||||
"gate a2: 3 arguments\r\n argv[0] = \"gate-a2.exe\"\r\n argv[1] = \"{SEED}\"\r\n \
|
||||
argv[2] = \"{LABEL}\"\r\n"
|
||||
);
|
||||
let sorted_line = format!("sorted {COUNT} values: min {min}, max {max}, total {total}\r\n");
|
||||
let output = format!(
|
||||
"{arguments}{sorted_line}checksum before {:016x}, after {:016x}\r\nreport \
|
||||
gate-a2-report.txt read back and verified\r\natexit: {CHECKS} checks passed\r\n",
|
||||
checksum(&unsorted),
|
||||
checksum(&sorted)
|
||||
);
|
||||
let report = format!("label {LABEL}\r\ntotal {total}\r\nrange {min} {max}\r\nend\r\n");
|
||||
Expected {
|
||||
output,
|
||||
report,
|
||||
arguments,
|
||||
sorted_line,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_restated_program_is_not_trivial() {
|
||||
// The generator really produces varied data, the sort really changes it,
|
||||
// and the two checksums really differ: the expected text is not built
|
||||
// from degenerate values.
|
||||
let unsorted = values(SEED);
|
||||
let mut sorted = unsorted.clone();
|
||||
sorted.sort_unstable();
|
||||
assert_ne!(unsorted, sorted);
|
||||
assert_ne!(checksum(&unsorted), checksum(&sorted));
|
||||
let mut distinct = sorted.clone();
|
||||
distinct.dedup();
|
||||
assert!(distinct.len() > COUNT / 2);
|
||||
assert_eq!(CHECKS, 76);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The gate
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_program_runs_to_its_exit_at_every_optimization_level() {
|
||||
let wanted = expected();
|
||||
for name in ["gate-a2-O0", "gate-a2-O1", "gate-a2-O2", "gate-a2-Os"] {
|
||||
let outcome = run(name);
|
||||
let result = &outcome.result;
|
||||
let state = &outcome.state;
|
||||
|
||||
// It returned from main, and the C runtime turned that into exit(0).
|
||||
assert_eq!(
|
||||
result.execution.exit_reason,
|
||||
ExitReason::ProcessExit(0),
|
||||
"{name}: stdout {:?}, stderr {:?}",
|
||||
outcome.output(),
|
||||
outcome.errors()
|
||||
);
|
||||
assert_eq!(state.exit_status(), Some(0), "{name}");
|
||||
|
||||
// Standard output, byte for byte, including the line the function
|
||||
// registered with atexit printed after main returned.
|
||||
assert_eq!(outcome.output(), wanted.output, "{name}");
|
||||
assert_eq!(outcome.errors(), "", "{name}");
|
||||
|
||||
// The report file is on the drive as the program wrote it, and the
|
||||
// file it looked for was not created.
|
||||
let report = state.file_contents(REPORT).expect("a report");
|
||||
assert_eq!(String::from_utf8(report).unwrap(), wanted.report, "{name}");
|
||||
assert_eq!(
|
||||
state.file_contents("C:\\gate-a2-missing.txt"),
|
||||
None,
|
||||
"{name}"
|
||||
);
|
||||
assert_eq!(state.open_handle_count(), 0, "{name}");
|
||||
|
||||
// It was loaded, relocated and bound by the real startup path, and
|
||||
// ran as translated ARM64 code. The C runtime's startup code is most
|
||||
// of what runs.
|
||||
assert!(
|
||||
result.bound_imports >= 40,
|
||||
"{name}: {}",
|
||||
result.bound_imports
|
||||
);
|
||||
assert!(result.relocations.applied_dir64 > 0, "{name}");
|
||||
let metrics = &result.dbt_metrics;
|
||||
assert!(
|
||||
metrics.blocks_compiled > 0 && metrics.native_bytes_emitted > 0,
|
||||
"{name}"
|
||||
);
|
||||
assert!(metrics.instructions_executed > 5_000, "{name}");
|
||||
assert!(metrics.service_calls > 60, "{name}");
|
||||
println!(
|
||||
"{name}: {} imports bound, {} guest instructions, {} of them through the shared \
|
||||
semantics, {} service calls",
|
||||
result.bound_imports,
|
||||
metrics.instructions_executed,
|
||||
metrics.interpreter_fallbacks,
|
||||
metrics.service_calls
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_arguments_give_other_results() {
|
||||
// A different seed and label change the data, the checksums and the
|
||||
// report, so the expected text above is not a constant the runtime could
|
||||
// echo.
|
||||
let outcome = run_with("gate-a2-O1", Some(&["a2", "7", "seven"]), BUDGET);
|
||||
assert_eq!(
|
||||
outcome.result.execution.exit_reason,
|
||||
ExitReason::ProcessExit(0)
|
||||
);
|
||||
let unsorted = values(7);
|
||||
let mut sorted = unsorted.clone();
|
||||
sorted.sort_unstable();
|
||||
let total: u64 = unsorted.iter().map(|value| u64::from(*value)).sum();
|
||||
let output = outcome.output();
|
||||
assert!(
|
||||
output.starts_with(
|
||||
"gate a2: 3 arguments\r\n argv[0] = \"a2\"\r\n argv[1] = \"7\"\r\n argv[2] = \
|
||||
\"seven\"\r\n"
|
||||
),
|
||||
"{output:?}"
|
||||
);
|
||||
assert!(
|
||||
output.contains(&format!(
|
||||
"sorted {COUNT} values: min {}, max {}, total {total}\r\n",
|
||||
sorted[0],
|
||||
sorted[COUNT - 1]
|
||||
)),
|
||||
"{output:?}"
|
||||
);
|
||||
assert!(
|
||||
output.contains(&format!(
|
||||
"checksum before {:016x}, after {:016x}\r\n",
|
||||
checksum(&unsorted),
|
||||
checksum(&sorted)
|
||||
)),
|
||||
"{output:?}"
|
||||
);
|
||||
let report = outcome.state.file_contents(REPORT).unwrap();
|
||||
assert_eq!(
|
||||
String::from_utf8(report).unwrap(),
|
||||
format!(
|
||||
"label seven\r\ntotal {total}\r\nrange {} {}\r\nend\r\n",
|
||||
sorted[0],
|
||||
sorted[COUNT - 1]
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_arguments_fail_the_check_that_looks_at_them() {
|
||||
// (arguments, exit status, the lines printed before the failure)
|
||||
let cases: [(Option<&[&str]>, u32, &str); 4] = [
|
||||
// No host arguments: one empty argument, so the count is wrong.
|
||||
(None, 11, "gate a2: 1 arguments\r\n argv[0] = \"\"\r\n"),
|
||||
(
|
||||
Some(&["a2", "5"]),
|
||||
11,
|
||||
"gate a2: 2 arguments\r\n argv[0] = \"a2\"\r\n argv[1] = \"5\"\r\n",
|
||||
),
|
||||
// A seed that is not a number.
|
||||
(
|
||||
Some(&["a2", "5x", "label"]),
|
||||
13,
|
||||
"gate a2: 3 arguments\r\n argv[0] = \"a2\"\r\n argv[1] = \"5x\"\r\n argv[2] = \
|
||||
\"label\"\r\n",
|
||||
),
|
||||
// An empty label.
|
||||
(
|
||||
Some(&["a2", "5", ""]),
|
||||
14,
|
||||
"gate a2: 3 arguments\r\n argv[0] = \"a2\"\r\n argv[1] = \"5\"\r\n argv[2] = \
|
||||
\"\"\r\n",
|
||||
),
|
||||
];
|
||||
for (arguments, status, printed) in cases {
|
||||
let outcome = run_with("gate-a2-O1", arguments, BUDGET);
|
||||
let what = format!("{arguments:?}");
|
||||
assert_eq!(
|
||||
outcome.result.execution.exit_reason,
|
||||
ExitReason::ProcessExit(status),
|
||||
"{what}"
|
||||
);
|
||||
// The failed check says so on standard error, and the function
|
||||
// registered with atexit still runs, because main returned. It
|
||||
// reports the checks that passed before the failure: registering
|
||||
// itself, and then one for each argument check before this one.
|
||||
assert_eq!(
|
||||
outcome.errors(),
|
||||
format!("gate a2: check {status} failed\r\n"),
|
||||
"{what}"
|
||||
);
|
||||
let passed = status - 10;
|
||||
assert_eq!(
|
||||
outcome.output(),
|
||||
format!("{printed}atexit: {passed} checks passed\r\n"),
|
||||
"{what}"
|
||||
);
|
||||
assert_eq!(outcome.state.file_contents(REPORT), None, "{what}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_expectation_exits_with_the_number_of_the_failed_check() {
|
||||
// The variant expects the sorted total to be one more than it is.
|
||||
// Everything before that check passes, and nothing after it runs.
|
||||
let wanted = expected();
|
||||
let outcome = run("gate-a2-break");
|
||||
assert_eq!(
|
||||
outcome.result.execution.exit_reason,
|
||||
ExitReason::ProcessExit(22)
|
||||
);
|
||||
assert_eq!(outcome.state.exit_status(), Some(22));
|
||||
assert_eq!(outcome.errors(), "gate a2: check 22 failed\r\n");
|
||||
// Five argument checks, the allocation and 47 comparisons passed.
|
||||
assert_eq!(
|
||||
outcome.output(),
|
||||
format!("{}atexit: 53 checks passed\r\n", wanted.arguments)
|
||||
);
|
||||
assert_eq!(outcome.state.file_contents(REPORT), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_half_way_runs_the_registered_function_and_nothing_after() {
|
||||
// The variant calls exit(42) after the sort. The status is exit's, the
|
||||
// function registered with atexit runs, and the report is never written.
|
||||
let wanted = expected();
|
||||
let outcome = run("gate-a2-exit");
|
||||
assert_eq!(
|
||||
outcome.result.execution.exit_reason,
|
||||
ExitReason::ProcessExit(42)
|
||||
);
|
||||
assert_eq!(outcome.state.exit_status(), Some(42));
|
||||
assert_eq!(outcome.errors(), "");
|
||||
let output = outcome.output();
|
||||
assert!(
|
||||
output.starts_with(&format!("{}{}", wanted.arguments, wanted.sorted_line)),
|
||||
"{output:?}"
|
||||
);
|
||||
// Through check 22: 5 + 1 + 47 + 1.
|
||||
assert!(
|
||||
output.ends_with("atexit: 54 checks passed\r\n"),
|
||||
"{output:?}"
|
||||
);
|
||||
assert!(!output.contains("report "), "{output:?}");
|
||||
assert_eq!(outcome.state.file_contents(REPORT), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn abort_half_way_runs_no_registered_function() {
|
||||
// The variant calls abort() after the sort: exit code 3, and the function
|
||||
// registered with atexit does not run.
|
||||
let wanted = expected();
|
||||
let outcome = run("gate-a2-abort");
|
||||
assert_eq!(
|
||||
outcome.result.execution.exit_reason,
|
||||
ExitReason::ProcessExit(3)
|
||||
);
|
||||
assert_eq!(outcome.state.exit_status(), Some(3));
|
||||
let output = outcome.output();
|
||||
assert!(
|
||||
output.starts_with(&format!("{}{}", wanted.arguments, wanted.sorted_line)),
|
||||
"{output:?}"
|
||||
);
|
||||
assert!(!output.contains("atexit:"), "{output:?}");
|
||||
assert_eq!(outcome.state.file_contents(REPORT), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_step_budget_that_is_too_small_is_not_an_exit() {
|
||||
let outcome = run_with("gate-a2-O1", Some(&ARGUMENTS), 200);
|
||||
assert_eq!(
|
||||
outcome.result.execution.exit_reason,
|
||||
ExitReason::StepLimitExceeded
|
||||
);
|
||||
assert_eq!(outcome.state.exit_status(), None);
|
||||
assert_eq!(outcome.output(), "");
|
||||
assert_eq!(outcome.state.file_contents(REPORT), None);
|
||||
}
|
||||
@@ -1031,6 +1031,557 @@ fn captured_output_is_bounded() {
|
||||
assert_eq!(guest.state.standard_error(), b"xx");
|
||||
}
|
||||
|
||||
const ENOENT: u32 = 2;
|
||||
const EBADF: u32 = 9;
|
||||
const EMFILE: u32 = 24;
|
||||
const ENOSPC: u32 = 28;
|
||||
/// Where the file tests put a name, a mode and the buffer `fgets` fills.
|
||||
const NAME: u64 = TEXT + 0x1000;
|
||||
const MODE: u64 = TEXT + 0x1200;
|
||||
const LINE: u64 = TEXT + 0x2000;
|
||||
/// What the buffer holds before `fgets` is called.
|
||||
const UNTOUCHED: u8 = 0xEE;
|
||||
|
||||
/// `fopen(name, mode)`, with both strings placed in guest memory.
|
||||
fn open(guest: &mut Guest, name: &str, mode: &str) -> u64 {
|
||||
let name = place(guest, NAME, name.as_bytes());
|
||||
let mode = place(guest, MODE, mode.as_bytes());
|
||||
guest.call("fopen", &[name, mode])
|
||||
}
|
||||
|
||||
/// `fopen` that must succeed.
|
||||
fn opened(guest: &mut Guest, name: &str, mode: &str) -> u64 {
|
||||
let stream = open(guest, name, mode);
|
||||
assert_ne!(stream, 0, "fopen({name:?}, {mode:?})");
|
||||
stream
|
||||
}
|
||||
|
||||
fn close(guest: &mut Guest, stream: u64) {
|
||||
assert_eq!(guest.call("fclose", &[stream]) & 0xFFFF_FFFF, 0);
|
||||
}
|
||||
|
||||
/// Write `text` to a stream with `fwrite`, one item per byte.
|
||||
fn write(guest: &mut Guest, stream: u64, text: &[u8]) {
|
||||
guest.memory.write_bytes(TEXT + 0x4000, text).unwrap();
|
||||
let count = text.len() as u64;
|
||||
assert_eq!(
|
||||
guest.call("fwrite", &[TEXT + 0x4000, 1, count, stream]),
|
||||
count
|
||||
);
|
||||
}
|
||||
|
||||
/// Create or replace a file with exactly these bytes.
|
||||
fn store(guest: &mut Guest, name: &str, bytes: &[u8]) {
|
||||
let stream = opened(guest, name, "wb");
|
||||
write(guest, stream, bytes);
|
||||
close(guest, stream);
|
||||
}
|
||||
|
||||
/// `fgets(LINE, count, stream)`: the string it stored, or `None` for a null
|
||||
/// result. Either way, the bytes it had no reason to write must be untouched.
|
||||
fn line(guest: &mut Guest, stream: u64, count: u64) -> Option<Vec<u8>> {
|
||||
let room = (count as usize).min(0x400) + 16;
|
||||
guest
|
||||
.memory
|
||||
.write_bytes(LINE, &vec![UNTOUCHED; room])
|
||||
.unwrap();
|
||||
let result = guest.call("fgets", &[LINE, count, stream]);
|
||||
let mut after = vec![0; room];
|
||||
guest.memory.read_bytes(LINE, &mut after).unwrap();
|
||||
if result == 0 {
|
||||
assert!(
|
||||
after.iter().all(|byte| *byte == UNTOUCHED),
|
||||
"buffer written"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
assert_eq!(result, LINE, "fgets returns its buffer");
|
||||
let end = after
|
||||
.iter()
|
||||
.position(|byte| *byte == 0)
|
||||
.expect("terminator");
|
||||
assert!(end < count as usize, "more than count - 1 characters");
|
||||
assert!(after[end + 1..].iter().all(|byte| *byte == UNTOUCHED));
|
||||
Some(after[..end].to_vec())
|
||||
}
|
||||
|
||||
/// Every line of a file, read with `fgets` in the given mode.
|
||||
fn lines(guest: &mut Guest, name: &str, mode: &str) -> Vec<Vec<u8>> {
|
||||
let stream = opened(guest, name, mode);
|
||||
let mut all = Vec::new();
|
||||
while let Some(text) = line(guest, stream, 96) {
|
||||
all.push(text);
|
||||
// A read that does not advance must fail, not loop for ever.
|
||||
assert!(all.len() <= 64, "{name}: fgets never reaches the end");
|
||||
}
|
||||
close(guest, stream);
|
||||
all
|
||||
}
|
||||
|
||||
/// What the Gate A2 program does with a file: `fopen` for writing, `fprintf`,
|
||||
/// `fclose`, `fopen` for reading, `fgets`, `fclose`. `fgets` reads "to and
|
||||
/// including the first newline character, to the end of the stream, or until
|
||||
/// the number of characters read is equal to numChars - 1", and returns null
|
||||
/// at end of file (Microsoft Learn). Expected text is what the test wrote.
|
||||
#[test]
|
||||
fn a_file_written_through_a_stream_reads_back_line_by_line() {
|
||||
let (mut guest, streams) = stdio_guest();
|
||||
let file = opened(&mut guest, "gate-a2.txt", "w");
|
||||
assert!(!streams.contains(&file));
|
||||
let one = place(&mut guest, STRINGS, b"one");
|
||||
let first: &[u8] = b"sum 12345 hex a2 text one\n";
|
||||
let count = print(
|
||||
&mut guest,
|
||||
file,
|
||||
b"sum %llu hex %x text %s\n",
|
||||
&[12345, 0xa2, one],
|
||||
);
|
||||
assert_eq!(count, first.len() as u64);
|
||||
let second = place(&mut guest, STRINGS + 0x40, b"second line\n");
|
||||
assert_eq!(guest.call("fputs", &[second, file]) & 0xFFFF_FFFF, 0);
|
||||
write(&mut guest, file, b"third");
|
||||
assert_eq!(guest.call("fflush", &[file]) & 0xFFFF_FFFF, 0);
|
||||
close(&mut guest, file);
|
||||
// File output is not standard output.
|
||||
assert!(guest.state.standard_output().is_empty());
|
||||
assert!(guest.state.standard_error().is_empty());
|
||||
|
||||
let file = opened(&mut guest, "gate-a2.txt", "r");
|
||||
assert_eq!(line(&mut guest, file, 96).as_deref(), Some(first));
|
||||
assert_eq!(
|
||||
line(&mut guest, file, 96).as_deref(),
|
||||
Some(&b"second line\n"[..])
|
||||
);
|
||||
// The last line has no newline: it ends at the end of the stream.
|
||||
assert_eq!(line(&mut guest, file, 96).as_deref(), Some(&b"third"[..]));
|
||||
assert_eq!(line(&mut guest, file, 96), None);
|
||||
assert_eq!(line(&mut guest, file, 96), None);
|
||||
close(&mut guest, file);
|
||||
assert_eq!(guest.errno(), 0);
|
||||
}
|
||||
|
||||
/// The access types of the `fopen` page: "r" fails "if the file doesn't
|
||||
/// exist"; with "w", "if the given file exists, its contents are destroyed";
|
||||
/// "a" "creates the file if it doesn't exist" and "all write operations occur
|
||||
/// at the end of the file"; "r+" needs the file to exist; "w+" and "a+" also
|
||||
/// read. A null or empty name or mode returns null with `EINVAL`.
|
||||
#[test]
|
||||
fn fopen_modes_follow_the_documentation() {
|
||||
let (mut guest, _) = stdio_guest();
|
||||
guest.set_errno(0);
|
||||
for mode in ["r", "r+", "rb", "rt"] {
|
||||
assert_eq!(open(&mut guest, "missing.txt", mode), 0, "{mode}");
|
||||
assert_eq!(guest.errno(), ENOENT, "{mode}");
|
||||
guest.set_errno(0);
|
||||
}
|
||||
|
||||
// "w" creates the file, and opening it again destroys what it held.
|
||||
store(&mut guest, "w.txt", b"old contents\n");
|
||||
assert_eq!(lines(&mut guest, "w.txt", "rb"), [b"old contents\n"]);
|
||||
let file = opened(&mut guest, "w.txt", "w");
|
||||
close(&mut guest, file);
|
||||
assert!(lines(&mut guest, "w.txt", "rb").is_empty());
|
||||
|
||||
// "a" creates the file, keeps what it holds and writes at its end.
|
||||
for text in [&b"1\n"[..], b"2\n"] {
|
||||
let file = opened(&mut guest, "a.txt", "ab");
|
||||
write(&mut guest, file, text);
|
||||
close(&mut guest, file);
|
||||
}
|
||||
assert_eq!(lines(&mut guest, "a.txt", "rb"), [b"1\n", b"2\n"]);
|
||||
|
||||
// "r+" keeps the contents and writes from the start.
|
||||
store(&mut guest, "plus.txt", b"abcdef\n");
|
||||
let file = opened(&mut guest, "plus.txt", "r+b");
|
||||
write(&mut guest, file, b"XY");
|
||||
// Reading continues where the write left off.
|
||||
assert_eq!(line(&mut guest, file, 96).as_deref(), Some(&b"cdef\n"[..]));
|
||||
close(&mut guest, file);
|
||||
assert_eq!(lines(&mut guest, "plus.txt", "rb"), [b"XYcdef\n"]);
|
||||
|
||||
// "w+" may be read; right after a write it is at the end of the file. A
|
||||
// "w" stream may not be read at all.
|
||||
let file = opened(&mut guest, "wplus.txt", "w+b");
|
||||
write(&mut guest, file, b"data\n");
|
||||
assert_eq!(line(&mut guest, file, 96), None);
|
||||
assert_eq!(guest.errno(), 0);
|
||||
close(&mut guest, file);
|
||||
let file = opened(&mut guest, "wplus.txt", "w");
|
||||
assert_eq!(line(&mut guest, file, 96), None);
|
||||
assert_eq!(guest.errno(), EBADF);
|
||||
guest.set_errno(0);
|
||||
close(&mut guest, file);
|
||||
|
||||
// "a+" reads from the start (Xenora's choice; ISO C leaves the initial
|
||||
// position to the implementation) and still writes at the end.
|
||||
store(&mut guest, "aplus.txt", b"one\ntwo\n");
|
||||
let file = opened(&mut guest, "aplus.txt", "a+b");
|
||||
assert_eq!(line(&mut guest, file, 96).as_deref(), Some(&b"one\n"[..]));
|
||||
write(&mut guest, file, b"three\n");
|
||||
close(&mut guest, file);
|
||||
assert_eq!(
|
||||
lines(&mut guest, "aplus.txt", "rb"),
|
||||
[&b"one\n"[..], b"two\n", b"three\n"]
|
||||
);
|
||||
|
||||
// One file by any spelling the drive accepts: either slash, any case,
|
||||
// with or without the drive.
|
||||
store(&mut guest, "Name.TXT", b"same\n");
|
||||
for name in ["name.txt", "NAME.txt", "C:\\name.txt", "c:/Name.Txt"] {
|
||||
assert_eq!(lines(&mut guest, name, "r"), [b"same\n"], "{name}");
|
||||
}
|
||||
|
||||
// Null and empty names and modes, modes that are not modes, a name the
|
||||
// drive rejects, and a name that is too long.
|
||||
guest.set_errno(0);
|
||||
let name = place(&mut guest, NAME, b"w.txt");
|
||||
let mode = place(&mut guest, MODE, b"r");
|
||||
for args in [[0, mode], [name, 0]] {
|
||||
assert_eq!(guest.call("fopen", &args), 0, "{args:x?}");
|
||||
assert_eq!(guest.errno(), STDIO_EINVAL, "{args:x?}");
|
||||
guest.set_errno(0);
|
||||
}
|
||||
let long = "x".repeat(261);
|
||||
for (name, mode) in [
|
||||
("", "r"),
|
||||
("w.txt", ""),
|
||||
("w.txt", "tr"),
|
||||
("w.txt", "br"),
|
||||
("w.txt", "rw"),
|
||||
("w.txt", "rbt"),
|
||||
("w.txt", "r++"),
|
||||
("w.txt", "wx"),
|
||||
("w.txt", "r,ccs=UTF-8"),
|
||||
("w.txt", "R"),
|
||||
("bad*name", "w"),
|
||||
("a\\..\\b", "w"),
|
||||
("con", "w"),
|
||||
(long.as_str(), "w"),
|
||||
] {
|
||||
assert_eq!(open(&mut guest, name, mode), 0, "{name:?} {mode:?}");
|
||||
assert_eq!(guest.errno(), STDIO_EINVAL, "{name:?} {mode:?}");
|
||||
guest.set_errno(0);
|
||||
}
|
||||
// A refused "w" destroyed nothing.
|
||||
assert_eq!(lines(&mut guest, "plus.txt", "rb"), [b"XYcdef\n"]);
|
||||
// A directory that does not exist.
|
||||
for mode in ["w", "a", "r"] {
|
||||
assert_eq!(open(&mut guest, "nodir\\file.txt", mode), 0, "{mode}");
|
||||
assert_eq!(guest.errno(), ENOENT, "{mode}");
|
||||
guest.set_errno(0);
|
||||
}
|
||||
}
|
||||
|
||||
/// "LF characters are translated to CR-LF combinations on output", "CR-LF
|
||||
/// combinations are translated into single line feeds on input", and "CTRL+Z
|
||||
/// is interpreted as an end-of-file character on input" in text mode; binary
|
||||
/// mode suppresses the translations. Without `t` or `b` the mode is text,
|
||||
/// the initial `_fmode` (Microsoft Learn, fopen).
|
||||
#[test]
|
||||
fn text_and_binary_streams_translate_as_documented() {
|
||||
let (mut guest, _) = stdio_guest();
|
||||
for mode in ["w", "wt"] {
|
||||
let file = opened(&mut guest, "text.txt", mode);
|
||||
write(&mut guest, file, b"a\nb\n");
|
||||
// fwrite's result did not count the carriage returns.
|
||||
close(&mut guest, file);
|
||||
// Read back untranslated, the file holds CR-LF pairs.
|
||||
assert_eq!(
|
||||
lines(&mut guest, "text.txt", "rb"),
|
||||
[b"a\r\n", b"b\r\n"],
|
||||
"{mode}"
|
||||
);
|
||||
for read in ["r", "rt"] {
|
||||
assert_eq!(lines(&mut guest, "text.txt", read), [b"a\n", b"b\n"]);
|
||||
}
|
||||
}
|
||||
// Formatted output and fputs are translated like fwrite.
|
||||
let file = opened(&mut guest, "text.txt", "w");
|
||||
assert_eq!(print(&mut guest, file, b"%d\n", &[7]), 2);
|
||||
let text = place(&mut guest, STRINGS, b"s\n");
|
||||
assert_eq!(guest.call("fputs", &[text, file]) & 0xFFFF_FFFF, 0);
|
||||
close(&mut guest, file);
|
||||
assert_eq!(lines(&mut guest, "text.txt", "rb"), [b"7\r\n", b"s\r\n"]);
|
||||
|
||||
// Binary output is stored as written.
|
||||
store(&mut guest, "binary.bin", b"x\ny");
|
||||
assert_eq!(lines(&mut guest, "binary.bin", "rb"), [&b"x\n"[..], b"y"]);
|
||||
|
||||
// CTRL+Z ends a text stream and is data to a binary one. A carriage
|
||||
// return that no line feed follows is kept.
|
||||
store(&mut guest, "ctrlz.bin", b"one\r\ntw\ro\x1Athree\n");
|
||||
assert_eq!(
|
||||
lines(&mut guest, "ctrlz.bin", "r"),
|
||||
[&b"one\n"[..], b"tw\ro"]
|
||||
);
|
||||
assert_eq!(
|
||||
lines(&mut guest, "ctrlz.bin", "rb"),
|
||||
[&b"one\r\n"[..], b"tw\ro\x1Athree\n"]
|
||||
);
|
||||
// A text stream that begins with CTRL+Z has nothing to read.
|
||||
store(&mut guest, "empty.bin", b"\x1Arest");
|
||||
assert!(lines(&mut guest, "empty.bin", "r").is_empty());
|
||||
}
|
||||
|
||||
/// `fgets` stores at most `numChars - 1` characters and a terminator, and
|
||||
/// "if str or stream is a null pointer, or numChars is less than or equal to
|
||||
/// zero", sets `errno` to `EINVAL` and returns null (Microsoft Learn).
|
||||
#[test]
|
||||
fn fgets_reads_lines_within_its_count() {
|
||||
let (mut guest, [input, out, _]) = stdio_guest();
|
||||
store(&mut guest, "lines.bin", b"abcdefgh\nxy");
|
||||
let file = opened(&mut guest, "lines.bin", "rb");
|
||||
assert_eq!(line(&mut guest, file, 4).as_deref(), Some(&b"abc"[..]));
|
||||
assert_eq!(line(&mut guest, file, 4).as_deref(), Some(&b"def"[..]));
|
||||
assert_eq!(line(&mut guest, file, 2).as_deref(), Some(&b"g"[..]));
|
||||
// A count of 1 has room for the terminator only and reads nothing.
|
||||
assert_eq!(line(&mut guest, file, 1).as_deref(), Some(&b""[..]));
|
||||
// The newline is kept, and reading stops after it. The count is an int.
|
||||
let count = 0xFFFF_FFFF_0000_0060;
|
||||
assert_eq!(
|
||||
line(&mut guest, file, count & 0xFFFF_FFFF).as_deref(),
|
||||
Some(&b"h\n"[..])
|
||||
);
|
||||
guest.memory.write_bytes(LINE, &[UNTOUCHED; 8]).unwrap();
|
||||
assert_eq!(guest.call("fgets", &[LINE, count, file]), LINE);
|
||||
assert_eq!(
|
||||
guest.memory.read_u32(LINE).unwrap(),
|
||||
u32::from_le_bytes(*b"xy\0\xEE")
|
||||
);
|
||||
// At the end of the file every count returns null.
|
||||
for count in [96, 2, 1] {
|
||||
assert_eq!(line(&mut guest, file, count), None, "{count}");
|
||||
}
|
||||
assert_eq!(guest.errno(), 0);
|
||||
|
||||
guest.set_errno(0);
|
||||
for args in [
|
||||
[0, 96, file],
|
||||
[LINE, 96, 0],
|
||||
[LINE, 0, file],
|
||||
[LINE, 0xFFFF_FFFF, file],
|
||||
[LINE, 0x8000_0000, file],
|
||||
] {
|
||||
assert_eq!(guest.call("fgets", &args), 0, "{args:x?}");
|
||||
assert_eq!(guest.errno(), STDIO_EINVAL, "{args:x?}");
|
||||
guest.set_errno(0);
|
||||
}
|
||||
close(&mut guest, file);
|
||||
|
||||
// A stream that was not opened for reading, and standard output.
|
||||
let writer = opened(&mut guest, "lines.bin", "ab");
|
||||
for stream in [writer, out] {
|
||||
assert_eq!(guest.call("fgets", &[LINE, 96, stream]), 0);
|
||||
assert_eq!(guest.errno(), EBADF);
|
||||
guest.set_errno(0);
|
||||
}
|
||||
close(&mut guest, writer);
|
||||
// Standard input, a closed stream and a pointer that never was one.
|
||||
for stream in [input, writer, TEXT] {
|
||||
assert_eq!(
|
||||
guest.run("fgets", &[LINE, 96, stream]).1,
|
||||
LIMIT,
|
||||
"{stream:#x}"
|
||||
);
|
||||
}
|
||||
// A buffer that cannot be written is a fault.
|
||||
let file = opened(&mut guest, "lines.bin", "rb");
|
||||
let exit = guest.run("fgets", &[0x9_0000_0000, 96, file]).1;
|
||||
assert!(matches!(exit, ExitReason::MemoryFault(_)), "{exit:?}");
|
||||
}
|
||||
|
||||
/// Output to a stream that was opened only for reading fails with the error
|
||||
/// result of each function, and so does output the drive has no room for.
|
||||
/// The `errno` values are Xenora's choice: `EBADF` and `ENOSPC`.
|
||||
#[test]
|
||||
fn file_output_that_cannot_be_written_fails_and_writes_nothing() {
|
||||
let (mut guest, _) = stdio_guest();
|
||||
store(&mut guest, "fixed.bin", b"keep\n");
|
||||
let file = opened(&mut guest, "fixed.bin", "rb");
|
||||
guest.set_errno(0);
|
||||
let (count, exit) = print_with(&mut guest, MINGW_OPTIONS, file, b"%d", &[1]);
|
||||
assert_eq!((count, exit), (STDIO_MINUS_ONE, ExitReason::Halt));
|
||||
assert_eq!(guest.errno(), EBADF);
|
||||
guest.set_errno(0);
|
||||
let text = place(&mut guest, STRINGS, b"text");
|
||||
assert_eq!(guest.call("fwrite", &[text, 1, 4, file]), 0);
|
||||
assert_eq!(guest.errno(), EBADF);
|
||||
guest.set_errno(0);
|
||||
assert_eq!(
|
||||
guest.call("fputs", &[text, file]) & 0xFFFF_FFFF,
|
||||
STDIO_MINUS_ONE
|
||||
);
|
||||
assert_eq!(guest.errno(), EBADF);
|
||||
guest.set_errno(0);
|
||||
close(&mut guest, file);
|
||||
assert_eq!(lines(&mut guest, "fixed.bin", "rb"), [b"keep\n"]);
|
||||
|
||||
// The drive holds 16 MiB in all. Fifteen whole megabytes and most of the
|
||||
// sixteenth fit beside the five bytes above.
|
||||
const CHUNK: u64 = 1 << 20;
|
||||
guest
|
||||
.memory
|
||||
.write_bytes(TEXT, &vec![b'x'; CHUNK as usize])
|
||||
.unwrap();
|
||||
let file = opened(&mut guest, "big.bin", "wb");
|
||||
for _ in 0..15 {
|
||||
assert_eq!(guest.call("fwrite", &[TEXT, 1, CHUNK, file]), CHUNK);
|
||||
}
|
||||
assert_eq!(guest.call("fwrite", &[TEXT, 1, CHUNK - 5, file]), CHUNK - 5);
|
||||
assert_eq!(guest.errno(), 0);
|
||||
// Not one more byte, through any of the three.
|
||||
assert_eq!(guest.call("fwrite", &[TEXT, 1, 1, file]), 0);
|
||||
assert_eq!(guest.errno(), ENOSPC);
|
||||
guest.set_errno(0);
|
||||
let (count, _) = print_with(&mut guest, MINGW_OPTIONS, file, b"y", &[]);
|
||||
assert_eq!(count, STDIO_MINUS_ONE);
|
||||
assert_eq!(guest.errno(), ENOSPC);
|
||||
guest.set_errno(0);
|
||||
close(&mut guest, file);
|
||||
// Emptying the big file makes room again.
|
||||
let file = opened(&mut guest, "big.bin", "wb");
|
||||
assert_eq!(guest.call("fwrite", &[TEXT, 1, 1, file]), 1);
|
||||
close(&mut guest, file);
|
||||
}
|
||||
|
||||
/// `fclose` "returns 0 if the stream is successfully closed" and, for a null
|
||||
/// stream, sets `errno` to `EINVAL` and returns `EOF` (Microsoft Learn). At
|
||||
/// most 64 streams are open at once (Xenora's bound), and the 65th `fopen`
|
||||
/// fails with `EMFILE`.
|
||||
#[test]
|
||||
fn open_streams_are_bounded_and_fclose_releases_them() {
|
||||
let (mut guest, [input, out, err]) = stdio_guest();
|
||||
store(&mut guest, "shared.bin", b"x\n");
|
||||
let mut open_streams: Vec<u64> = (0..64)
|
||||
.map(|_| opened(&mut guest, "shared.bin", "rb"))
|
||||
.collect();
|
||||
let mut distinct = open_streams.clone();
|
||||
distinct.sort_unstable();
|
||||
distinct.dedup();
|
||||
assert_eq!(distinct.len(), 64, "each stream has its own FILE object");
|
||||
guest.set_errno(0);
|
||||
for mode in ["rb", "wb", "ab"] {
|
||||
assert_eq!(open(&mut guest, "shared.bin", mode), 0, "{mode}");
|
||||
assert_eq!(guest.errno(), EMFILE, "{mode}");
|
||||
guest.set_errno(0);
|
||||
}
|
||||
// The refused "wb" destroyed nothing, and each stream has its own
|
||||
// position.
|
||||
assert_eq!(
|
||||
line(&mut guest, open_streams[0], 96).as_deref(),
|
||||
Some(&b"x\n"[..])
|
||||
);
|
||||
assert_eq!(line(&mut guest, open_streams[0], 96), None);
|
||||
assert_eq!(
|
||||
line(&mut guest, open_streams[1], 96).as_deref(),
|
||||
Some(&b"x\n"[..])
|
||||
);
|
||||
|
||||
// Closing one makes room for one.
|
||||
let last = open_streams.pop().unwrap();
|
||||
close(&mut guest, last);
|
||||
let again = opened(&mut guest, "shared.bin", "rb");
|
||||
assert_eq!(open(&mut guest, "shared.bin", "rb"), 0);
|
||||
assert_eq!(guest.errno(), EMFILE);
|
||||
guest.set_errno(0);
|
||||
|
||||
// fflush and setvbuf accept an open file stream.
|
||||
assert_eq!(guest.call("fflush", &[again]) & 0xFFFF_FFFF, 0);
|
||||
assert_eq!(guest.call("setvbuf", &[again, 0, 4, 0]) & 0xFFFF_FFFF, 0);
|
||||
|
||||
assert_eq!(guest.call("fclose", &[0]) & 0xFFFF_FFFF, STDIO_MINUS_ONE);
|
||||
assert_eq!(guest.errno(), STDIO_EINVAL);
|
||||
guest.set_errno(0);
|
||||
// A closed stream is no stream to any function, and closing a standard
|
||||
// stream is not modelled.
|
||||
close(&mut guest, again);
|
||||
for symbol in ["fclose", "fflush"] {
|
||||
assert_eq!(guest.run(symbol, &[again]).1, LIMIT, "{symbol}");
|
||||
}
|
||||
let (_, exit) = print_with(&mut guest, MINGW_OPTIONS, again, b"x", &[]);
|
||||
assert_eq!(exit, LIMIT);
|
||||
for stream in [input, out, err, TEXT] {
|
||||
assert_eq!(guest.run("fclose", &[stream]).1, LIMIT, "{stream:#x}");
|
||||
}
|
||||
for stream in open_streams {
|
||||
close(&mut guest, stream);
|
||||
}
|
||||
assert_eq!(guest.errno(), 0);
|
||||
}
|
||||
|
||||
/// `perror` "prints an error message to stderr": the message "followed by a
|
||||
/// colon, then by the system error message for the last library call that
|
||||
/// produced the error, and finally by a newline character"; "if message is a
|
||||
/// null pointer or a pointer to a null string, perror prints only the system
|
||||
/// error message". The page's example prints "No such file or directory"
|
||||
/// for a missing file; the other texts are Xenora's.
|
||||
#[test]
|
||||
fn perror_writes_the_message_and_the_error_text_to_stderr() {
|
||||
let (mut guest, _) = stdio_guest();
|
||||
guest.set_errno(0);
|
||||
// The failure the Gate A2 program would report.
|
||||
assert_eq!(open(&mut guest, "nosuchf.ile", "r"), 0);
|
||||
let message = place(&mut guest, STRINGS, b"perror says open failed");
|
||||
guest.call("perror", &[message]);
|
||||
assert_eq!(
|
||||
guest.state.standard_error(),
|
||||
b"perror says open failed: No such file or directory\r\n"
|
||||
);
|
||||
// perror does not change errno.
|
||||
assert_eq!(guest.errno(), ENOENT);
|
||||
assert!(guest.state.standard_output().is_empty());
|
||||
|
||||
let empty = place(&mut guest, STRINGS + 0x80, b"");
|
||||
let mut expected = guest.state.standard_error();
|
||||
for (errno, message, text) in [
|
||||
(ENOENT, 0, &b"No such file or directory\r\n"[..]),
|
||||
(ENOENT, empty, b"No such file or directory\r\n"),
|
||||
(0, message, b"perror says open failed: No error\r\n"),
|
||||
(STDIO_EINVAL, 0, b"Invalid argument\r\n"),
|
||||
(EBADF, 0, b"Bad file descriptor\r\n"),
|
||||
(EMFILE, 0, b"Too many open files\r\n"),
|
||||
(ENOSPC, 0, b"No space left on device\r\n"),
|
||||
(13, 0, b"Permission denied\r\n"),
|
||||
(12, 0, b"Not enough space\r\n"),
|
||||
(999, 0, b"Unknown error\r\n"),
|
||||
] {
|
||||
guest.set_errno(errno);
|
||||
guest.call("perror", &[message]);
|
||||
expected.extend_from_slice(text);
|
||||
assert_eq!(guest.state.standard_error(), expected, "errno {errno}");
|
||||
assert_eq!(guest.errno(), errno);
|
||||
}
|
||||
// An unreadable message is a fault and prints nothing.
|
||||
let exit = guest.run("perror", &[0x9_0000_0000]).1;
|
||||
assert!(matches!(exit, ExitReason::MemoryFault(_)), "{exit:?}");
|
||||
assert_eq!(guest.state.standard_error(), expected);
|
||||
}
|
||||
|
||||
/// The module and symbol pairs a program built with mingw-w64 14.0.0 (UCRT)
|
||||
/// imports the four file services by.
|
||||
#[test]
|
||||
fn file_services_resolve_as_mingw_w64_imports_them() {
|
||||
let (registry, _) = standard(0);
|
||||
let named = |name: &str| ImportName::Name(name.to_owned());
|
||||
const STDIO: &str = "api-ms-win-crt-stdio-l1-1-0.dll";
|
||||
const RUNTIME: &str = "api-ms-win-crt-runtime-l1-1-0.dll";
|
||||
for (module, symbol) in [
|
||||
(STDIO, "fopen"),
|
||||
(STDIO, "fclose"),
|
||||
(STDIO, "fgets"),
|
||||
(RUNTIME, "perror"),
|
||||
] {
|
||||
let service = registry
|
||||
.resolve(module, &named(symbol))
|
||||
.unwrap_or_else(|| panic!("{module}!{symbol}"));
|
||||
let target = registry.resolve("ucrtbase.dll", &named(symbol)).unwrap();
|
||||
assert!(std::ptr::eq(service, target), "{symbol}");
|
||||
assert_eq!(service.status, ServiceStatus::Partial, "{symbol}");
|
||||
}
|
||||
assert!(registry.resolve(RUNTIME, &named("fopen")).is_none());
|
||||
assert!(registry.resolve(STDIO, &named("perror")).is_none());
|
||||
}
|
||||
|
||||
/// The module and symbol pairs a program built with mingw-w64 14.0.0 (UCRT)
|
||||
/// imports these six services by, read from such a program's import table.
|
||||
#[test]
|
||||
|
||||
@@ -33,6 +33,7 @@ objc2-metal = { version = "=0.3.2", default-features = false, features = [
|
||||
"std",
|
||||
"MTLAllocation",
|
||||
"MTLArgument",
|
||||
"MTLBlitCommandEncoder",
|
||||
"MTLBuffer",
|
||||
"MTLCommandBuffer",
|
||||
"MTLCommandEncoder",
|
||||
|
||||
@@ -11,8 +11,9 @@ use std::ptr::NonNull;
|
||||
use objc2::rc::{Retained, autoreleasepool};
|
||||
use objc2::runtime::ProtocolObject;
|
||||
use objc2_metal::{
|
||||
MTLDevice, MTLOrigin, MTLPixelFormat, MTLRegion, MTLResourceOptions, MTLSize, MTLStorageMode,
|
||||
MTLTexture, MTLTextureDescriptor, MTLTextureUsage,
|
||||
MTLBlitCommandEncoder, MTLBuffer, MTLCommandBuffer, MTLCommandBufferStatus, MTLCommandEncoder,
|
||||
MTLCommandQueue, MTLDevice, MTLOrigin, MTLPixelFormat, MTLRegion, MTLResourceOptions, MTLSize,
|
||||
MTLStorageMode, MTLTexture, MTLTextureDescriptor, MTLTextureUsage,
|
||||
};
|
||||
use xenora_texture::{SamplerError, TextureMetadata};
|
||||
|
||||
@@ -100,6 +101,9 @@ impl Rgba8TextureDesc {
|
||||
pub struct MetalRgba8Texture {
|
||||
texture: Retained<ProtocolObject<dyn MTLTexture>>,
|
||||
desc: Rgba8TextureDesc,
|
||||
/// Shared storage, which `replaceRegion` may write. Private textures are
|
||||
/// filled only through `upload_staged`.
|
||||
cpu_writable: bool,
|
||||
}
|
||||
|
||||
impl MetalRgba8Texture {
|
||||
@@ -108,6 +112,19 @@ impl MetalRgba8Texture {
|
||||
device: &ProtocolObject<dyn MTLDevice>,
|
||||
desc: Rgba8TextureDesc,
|
||||
) -> Result<Self, MetalError> {
|
||||
Self::allocate_with_storage(device, desc, MTLStorageMode::Shared)
|
||||
}
|
||||
|
||||
fn allocate_with_storage(
|
||||
device: &ProtocolObject<dyn MTLDevice>,
|
||||
desc: Rgba8TextureDesc,
|
||||
storage: MTLStorageMode,
|
||||
) -> Result<Self, MetalError> {
|
||||
let options = if storage == MTLStorageMode::Private {
|
||||
MTLResourceOptions::StorageModePrivate
|
||||
} else {
|
||||
MTLResourceOptions::StorageModeShared
|
||||
};
|
||||
autoreleasepool(|_| {
|
||||
// SAFETY: Validated non-zero dimensions within MAX_TEXTURE_PIXELS and RGBA8Unorm format.
|
||||
let descriptor = unsafe {
|
||||
@@ -124,8 +141,8 @@ impl MetalRgba8Texture {
|
||||
descriptor.setMipmapLevelCount(desc.mips as usize);
|
||||
}
|
||||
}
|
||||
descriptor.setStorageMode(MTLStorageMode::Shared);
|
||||
descriptor.setResourceOptions(MTLResourceOptions::StorageModeShared);
|
||||
descriptor.setStorageMode(storage);
|
||||
descriptor.setResourceOptions(options);
|
||||
descriptor.setUsage(MTLTextureUsage::ShaderRead);
|
||||
|
||||
let texture = device
|
||||
@@ -137,51 +154,25 @@ impl MetalRgba8Texture {
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(Self { texture, desc })
|
||||
Ok(Self {
|
||||
texture,
|
||||
desc,
|
||||
cpu_writable: storage == MTLStorageMode::Shared,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Upload a single validated mip level into this texture.
|
||||
///
|
||||
/// Only Shared-storage textures from `allocate` or `upload` accept CPU writes.
|
||||
pub fn upload_mip(&self, mip: &Rgba8MipLevel<'_>) -> Result<(), MetalError> {
|
||||
let (expected_w, expected_h) = self.desc.mip_extent(mip.level)?;
|
||||
if mip.width != expected_w || mip.height != expected_h {
|
||||
if !self.cpu_writable {
|
||||
return Err(MetalError::new(
|
||||
"mip dimensions",
|
||||
format!(
|
||||
"mip level {} expected {}x{}, got {}x{}",
|
||||
mip.level, expected_w, expected_h, mip.width, mip.height
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let tight_pitch = mip
|
||||
.width
|
||||
.checked_mul(RGBA8_TEXEL_BYTES)
|
||||
.ok_or_else(|| MetalError::new("row pitch", "row pitch overflow"))?;
|
||||
if mip.row_pitch < tight_pitch {
|
||||
return Err(MetalError::new(
|
||||
"row pitch",
|
||||
format!(
|
||||
"row pitch {} smaller than tight pitch {}",
|
||||
mip.row_pitch, tight_pitch
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let min_bytes = mip
|
||||
.row_pitch
|
||||
.checked_mul(mip.height)
|
||||
.ok_or_else(|| MetalError::new("mip bytes", "byte length calculation overflow"))?;
|
||||
if mip.bytes.len() < min_bytes {
|
||||
return Err(MetalError::new(
|
||||
"mip buffer bounds",
|
||||
format!(
|
||||
"buffer length {} is less than required {}",
|
||||
mip.bytes.len(),
|
||||
min_bytes
|
||||
),
|
||||
"texture storage",
|
||||
"a Private-storage texture is filled only by upload_staged",
|
||||
));
|
||||
}
|
||||
validate_mip(&self.desc, mip)?;
|
||||
|
||||
autoreleasepool(|_| {
|
||||
let region = MTLRegion {
|
||||
@@ -227,6 +218,148 @@ impl MetalRgba8Texture {
|
||||
Ok(texture)
|
||||
}
|
||||
|
||||
/// Allocate a Private-storage RGBA8 texture and fill every mip level through
|
||||
/// a reused Shared staging buffer that never exceeds `budget`.
|
||||
///
|
||||
/// The plan from [`plan_staged_upload`] is built, and every input checked,
|
||||
/// before any Metal object is created. Each submission copies its rows into
|
||||
/// the staging buffer, blits them into the texture and waits until the
|
||||
/// command buffer has completed. Only a `Completed` status lets the buffer be
|
||||
/// reused; any other status is returned as an error.
|
||||
pub fn upload_staged(
|
||||
device: &ProtocolObject<dyn MTLDevice>,
|
||||
queue: &ProtocolObject<dyn MTLCommandQueue>,
|
||||
desc: Rgba8TextureDesc,
|
||||
mips: &[Rgba8MipLevel<'_>],
|
||||
budget: StagingBudget,
|
||||
) -> Result<(Self, StagedUploadReport), MetalError> {
|
||||
let plan = plan_staged_upload(&desc, mips, budget)?;
|
||||
let staging_len = plan.iter().map(|s| s.staging_bytes).max().unwrap_or(0);
|
||||
let texture = Self::allocate_with_storage(device, desc, MTLStorageMode::Private)?;
|
||||
let staging = device
|
||||
.newBufferWithLength_options(staging_len, MTLResourceOptions::StorageModeShared)
|
||||
.ok_or_else(|| MetalError::new("newBufferWithLength", "staging allocation failed"))?;
|
||||
let mut copied = 0;
|
||||
for submission in &plan {
|
||||
for copy in &submission.copies {
|
||||
let mip = mips
|
||||
.iter()
|
||||
.find(|mip| mip.level == copy.level)
|
||||
.ok_or_else(|| MetalError::new("staged upload", "planned level missing"))?;
|
||||
let tight = mip.width * RGBA8_TEXEL_BYTES;
|
||||
for row in 0..copy.rows {
|
||||
let src = &mip.bytes[(copy.first_row + row) * mip.row_pitch..][..tight];
|
||||
let offset = copy.staging_offset + row * tight;
|
||||
// SAFETY: The plan keeps offset + tight within staging_len, the
|
||||
// buffer is Shared and CPU-visible, and the previous submission
|
||||
// has completed, so the GPU no longer reads these bytes.
|
||||
unsafe {
|
||||
let dst = staging.contents().cast::<u8>().as_ptr().add(offset);
|
||||
std::ptr::copy_nonoverlapping(src.as_ptr(), dst, tight);
|
||||
}
|
||||
}
|
||||
copied += copy.rows * tight;
|
||||
}
|
||||
autoreleasepool(|_| texture.encode_staged(queue, &staging, submission))?;
|
||||
}
|
||||
let report = StagedUploadReport {
|
||||
submissions: plan.len(),
|
||||
peak_staging_bytes: staging_len,
|
||||
bytes_copied: copied,
|
||||
};
|
||||
Ok((texture, report))
|
||||
}
|
||||
|
||||
fn encode_staged(
|
||||
&self,
|
||||
queue: &ProtocolObject<dyn MTLCommandQueue>,
|
||||
staging: &ProtocolObject<dyn MTLBuffer>,
|
||||
submission: &StagedSubmission,
|
||||
) -> Result<(), MetalError> {
|
||||
let command = queue
|
||||
.commandBuffer()
|
||||
.ok_or_else(|| MetalError::new("commandBuffer", "command buffer creation failed"))?;
|
||||
let blit = command
|
||||
.blitCommandEncoder()
|
||||
.ok_or_else(|| MetalError::new("blitCommandEncoder", "blit encoder creation failed"))?;
|
||||
for copy in &submission.copies {
|
||||
let (width, _) = self.desc.mip_extent(copy.level)?;
|
||||
let pitch = width * RGBA8_TEXEL_BYTES;
|
||||
// SAFETY: The plan validated the level, the row range within the mip and
|
||||
// the staging range within the buffer. The command buffer retains both
|
||||
// resources, and the caller waits for completion before reusing staging.
|
||||
unsafe {
|
||||
blit.copyFromBuffer_sourceOffset_sourceBytesPerRow_sourceBytesPerImage_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin(
|
||||
staging,
|
||||
copy.staging_offset,
|
||||
pitch,
|
||||
pitch * copy.rows,
|
||||
MTLSize { width, height: copy.rows, depth: 1 },
|
||||
&self.texture,
|
||||
0,
|
||||
copy.level as usize,
|
||||
MTLOrigin { x: 0, y: copy.first_row, z: 0 },
|
||||
);
|
||||
}
|
||||
}
|
||||
blit.endEncoding();
|
||||
command.commit();
|
||||
command.waitUntilCompleted();
|
||||
check_completed(&command)
|
||||
}
|
||||
|
||||
/// Copy one mip level back into tightly packed RGBA8 bytes through a blit.
|
||||
///
|
||||
/// Works for Shared and Private textures and shares no code with the upload
|
||||
/// paths, so tests can compare its output with independently built pixels.
|
||||
pub fn read_back(
|
||||
&self,
|
||||
device: &ProtocolObject<dyn MTLDevice>,
|
||||
queue: &ProtocolObject<dyn MTLCommandQueue>,
|
||||
level: u32,
|
||||
) -> Result<Vec<u8>, MetalError> {
|
||||
let (width, height) = self.desc.mip_extent(level)?;
|
||||
let pitch = width * RGBA8_TEXEL_BYTES;
|
||||
let len = pitch * height;
|
||||
autoreleasepool(|_| {
|
||||
let buffer = device
|
||||
.newBufferWithLength_options(len, MTLResourceOptions::StorageModeShared)
|
||||
.ok_or_else(|| {
|
||||
MetalError::new("newBufferWithLength", "readback allocation failed")
|
||||
})?;
|
||||
let command = queue.commandBuffer().ok_or_else(|| {
|
||||
MetalError::new("commandBuffer", "command buffer creation failed")
|
||||
})?;
|
||||
let blit = command.blitCommandEncoder().ok_or_else(|| {
|
||||
MetalError::new("blitCommandEncoder", "blit encoder creation failed")
|
||||
})?;
|
||||
// SAFETY: The level is in range, the source region is the whole mip and
|
||||
// the destination buffer holds exactly pitch * height bytes.
|
||||
unsafe {
|
||||
blit.copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toBuffer_destinationOffset_destinationBytesPerRow_destinationBytesPerImage(
|
||||
&self.texture,
|
||||
0,
|
||||
level as usize,
|
||||
MTLOrigin { x: 0, y: 0, z: 0 },
|
||||
MTLSize { width, height, depth: 1 },
|
||||
&buffer,
|
||||
0,
|
||||
pitch,
|
||||
len,
|
||||
);
|
||||
}
|
||||
blit.endEncoding();
|
||||
command.commit();
|
||||
command.waitUntilCompleted();
|
||||
check_completed(&command)?;
|
||||
// SAFETY: The command buffer completed, so the Shared buffer holds len
|
||||
// initialized bytes and the GPU no longer writes it.
|
||||
let bytes =
|
||||
unsafe { std::slice::from_raw_parts(buffer.contents().cast::<u8>().as_ptr(), len) };
|
||||
Ok(bytes.to_vec())
|
||||
})
|
||||
}
|
||||
|
||||
/// Access the underlying native Metal texture protocol object.
|
||||
#[inline]
|
||||
pub fn raw(&self) -> &ProtocolObject<dyn MTLTexture> {
|
||||
@@ -240,6 +373,198 @@ impl MetalRgba8Texture {
|
||||
}
|
||||
}
|
||||
|
||||
/// Upper bound on the staging bytes one staged upload holds at a time.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StagingBudget {
|
||||
max_bytes: usize,
|
||||
}
|
||||
|
||||
impl StagingBudget {
|
||||
/// A budget of `max_bytes`, which must be a non-zero multiple of the RGBA8
|
||||
/// texel size so every staged row starts on a texel boundary.
|
||||
pub fn new(max_bytes: usize) -> Result<Self, MetalError> {
|
||||
if max_bytes == 0 || !max_bytes.is_multiple_of(RGBA8_TEXEL_BYTES) {
|
||||
return Err(MetalError::new(
|
||||
"staging budget",
|
||||
format!("budget {max_bytes} must be a non-zero multiple of {RGBA8_TEXEL_BYTES}"),
|
||||
));
|
||||
}
|
||||
Ok(Self { max_bytes })
|
||||
}
|
||||
|
||||
/// The largest staging allocation this budget allows.
|
||||
#[must_use]
|
||||
pub fn max_bytes(&self) -> usize {
|
||||
self.max_bytes
|
||||
}
|
||||
}
|
||||
|
||||
/// One blit of whole rows of one mip level from the staging buffer.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StagedCopy {
|
||||
pub level: u32,
|
||||
pub first_row: usize,
|
||||
pub rows: usize,
|
||||
/// Byte offset of the first row in the staging buffer. Rows are packed tightly.
|
||||
pub staging_offset: usize,
|
||||
}
|
||||
|
||||
/// The copies that share one staging fill and one command buffer.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct StagedSubmission {
|
||||
pub copies: Vec<StagedCopy>,
|
||||
/// Staging bytes this submission uses, never more than the budget.
|
||||
pub staging_bytes: usize,
|
||||
}
|
||||
|
||||
/// What a staged upload did, measured from the executed plan.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StagedUploadReport {
|
||||
/// Command buffers committed and completed.
|
||||
pub submissions: usize,
|
||||
/// Size of the one staging buffer, the most staging memory held at once.
|
||||
pub peak_staging_bytes: usize,
|
||||
/// Texel bytes copied into the texture.
|
||||
pub bytes_copied: usize,
|
||||
}
|
||||
|
||||
/// Split a full RGBA8 upload into budget-sized submissions of whole rows.
|
||||
///
|
||||
/// Every level `0..desc.mips` must appear exactly once, because a Private
|
||||
/// texture has no defined contents for a level nobody writes. Each mip is
|
||||
/// checked like [`MetalRgba8Texture::upload_mip`] checks it. The budget must hold
|
||||
/// at least one row of the widest level. Rows are packed in level order, and a
|
||||
/// submission closes when the next row would exceed the budget.
|
||||
pub fn plan_staged_upload(
|
||||
desc: &Rgba8TextureDesc,
|
||||
mips: &[Rgba8MipLevel<'_>],
|
||||
budget: StagingBudget,
|
||||
) -> Result<Vec<StagedSubmission>, MetalError> {
|
||||
let mut by_level: Vec<Option<&Rgba8MipLevel<'_>>> = vec![None; desc.mips as usize];
|
||||
for mip in mips {
|
||||
validate_mip(desc, mip)?;
|
||||
let slot = &mut by_level[mip.level as usize];
|
||||
if slot.is_some() {
|
||||
return Err(MetalError::new(
|
||||
"staged upload",
|
||||
format!("mip level {} appears more than once", mip.level),
|
||||
));
|
||||
}
|
||||
*slot = Some(mip);
|
||||
}
|
||||
let mut plan = Vec::new();
|
||||
let mut current = StagedSubmission {
|
||||
copies: Vec::new(),
|
||||
staging_bytes: 0,
|
||||
};
|
||||
for (level, mip) in by_level.iter().enumerate() {
|
||||
let mip = mip.ok_or_else(|| {
|
||||
MetalError::new("staged upload", format!("mip level {level} is missing"))
|
||||
})?;
|
||||
let pitch = mip.width * RGBA8_TEXEL_BYTES;
|
||||
if pitch > budget.max_bytes {
|
||||
return Err(MetalError::new(
|
||||
"staging budget",
|
||||
format!(
|
||||
"budget {} is smaller than one {pitch}-byte row of mip level {level}",
|
||||
budget.max_bytes
|
||||
),
|
||||
));
|
||||
}
|
||||
let mut row = 0;
|
||||
while row < mip.height {
|
||||
let fit = (budget.max_bytes - current.staging_bytes) / pitch;
|
||||
if fit == 0 {
|
||||
// Unreachable after the row check above, but an empty submission
|
||||
// that cannot take one row must never loop.
|
||||
if current.copies.is_empty() {
|
||||
return Err(MetalError::new(
|
||||
"staging budget",
|
||||
"a row does not fit an empty staging buffer",
|
||||
));
|
||||
}
|
||||
plan.push(std::mem::replace(
|
||||
&mut current,
|
||||
StagedSubmission {
|
||||
copies: Vec::new(),
|
||||
staging_bytes: 0,
|
||||
},
|
||||
));
|
||||
continue;
|
||||
}
|
||||
let rows = fit.min(mip.height - row);
|
||||
current.copies.push(StagedCopy {
|
||||
level: mip.level,
|
||||
first_row: row,
|
||||
rows,
|
||||
staging_offset: current.staging_bytes,
|
||||
});
|
||||
current.staging_bytes += rows * pitch;
|
||||
row += rows;
|
||||
}
|
||||
}
|
||||
if !current.copies.is_empty() {
|
||||
plan.push(current);
|
||||
}
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
fn check_completed(command: &ProtocolObject<dyn MTLCommandBuffer>) -> Result<(), MetalError> {
|
||||
let status = command.status();
|
||||
if status != MTLCommandBufferStatus::Completed {
|
||||
let detail = command.error().map_or_else(
|
||||
|| format!("unexpected command status {status:?}"),
|
||||
|error| error.localizedDescription().to_string(),
|
||||
);
|
||||
return Err(MetalError::new("waitUntilCompleted", detail));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check one mip level against the texture description and return its tight row pitch.
|
||||
fn validate_mip(desc: &Rgba8TextureDesc, mip: &Rgba8MipLevel<'_>) -> Result<usize, MetalError> {
|
||||
let (expected_w, expected_h) = desc.mip_extent(mip.level)?;
|
||||
if mip.width != expected_w || mip.height != expected_h {
|
||||
return Err(MetalError::new(
|
||||
"mip dimensions",
|
||||
format!(
|
||||
"mip level {} expected {}x{}, got {}x{}",
|
||||
mip.level, expected_w, expected_h, mip.width, mip.height
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let tight_pitch = mip
|
||||
.width
|
||||
.checked_mul(RGBA8_TEXEL_BYTES)
|
||||
.ok_or_else(|| MetalError::new("row pitch", "row pitch overflow"))?;
|
||||
if mip.row_pitch < tight_pitch {
|
||||
return Err(MetalError::new(
|
||||
"row pitch",
|
||||
format!(
|
||||
"row pitch {} smaller than tight pitch {}",
|
||||
mip.row_pitch, tight_pitch
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let min_bytes = mip
|
||||
.row_pitch
|
||||
.checked_mul(mip.height)
|
||||
.ok_or_else(|| MetalError::new("mip bytes", "byte length calculation overflow"))?;
|
||||
if mip.bytes.len() < min_bytes {
|
||||
return Err(MetalError::new(
|
||||
"mip buffer bounds",
|
||||
format!(
|
||||
"buffer length {} is less than required {}",
|
||||
mip.bytes.len(),
|
||||
min_bytes
|
||||
),
|
||||
));
|
||||
}
|
||||
Ok(tight_pitch)
|
||||
}
|
||||
|
||||
/// Resource binding indices and lifetime conventions for sampling pipelines.
|
||||
///
|
||||
/// In the Xenora fixture ABI and translated shader conventions:
|
||||
@@ -328,3 +653,150 @@ impl BoundSampledTexture {
|
||||
self.sampler_slot
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn copy(level: u32, first_row: usize, rows: usize, staging_offset: usize) -> StagedCopy {
|
||||
StagedCopy {
|
||||
level,
|
||||
first_row,
|
||||
rows,
|
||||
staging_offset,
|
||||
}
|
||||
}
|
||||
|
||||
fn levels<'a>(desc: &Rgba8TextureDesc, bytes: &'a [u8]) -> Vec<Rgba8MipLevel<'a>> {
|
||||
(0..desc.mips)
|
||||
.map(|level| {
|
||||
let (w, h) = desc.mip_extent(level).unwrap();
|
||||
Rgba8MipLevel::new_packed(level, w, h, &bytes[..w * h * RGBA8_TEXEL_BYTES])
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn plan(desc: Rgba8TextureDesc, budget: usize) -> Vec<StagedSubmission> {
|
||||
let bytes = vec![0; desc.width * desc.height * RGBA8_TEXEL_BYTES];
|
||||
plan_staged_upload(
|
||||
&desc,
|
||||
&levels(&desc, &bytes),
|
||||
StagingBudget::new(budget).unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn error(desc: Rgba8TextureDesc, mips: &[Rgba8MipLevel<'_>], budget: usize) -> String {
|
||||
plan_staged_upload(&desc, mips, StagingBudget::new(budget).unwrap())
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn budget_must_be_a_non_zero_texel_multiple() {
|
||||
assert!(StagingBudget::new(0).is_err());
|
||||
assert!(StagingBudget::new(6).is_err());
|
||||
assert_eq!(StagingBudget::new(8).unwrap().max_bytes(), 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_split_into_budget_sized_submissions() {
|
||||
// 8 texels × 4 bytes = 32 bytes per row; a 64-byte budget holds two rows.
|
||||
let desc = Rgba8TextureDesc::new(8, 4, 1).unwrap();
|
||||
let plan = plan(desc, 64);
|
||||
assert_eq!(plan.len(), 2);
|
||||
assert_eq!(plan[0].copies, [copy(0, 0, 2, 0)]);
|
||||
assert_eq!(plan[1].copies, [copy(0, 2, 2, 0)]);
|
||||
assert!(plan.iter().all(|s| s.staging_bytes == 64));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_submission_packs_every_level_when_it_fits() {
|
||||
// Levels 8×4, 4×2, 2×1: 128 + 32 + 8 = 168 bytes.
|
||||
let desc = Rgba8TextureDesc::new(8, 4, 3).unwrap();
|
||||
let plan = plan(desc, 168);
|
||||
assert_eq!(plan.len(), 1);
|
||||
assert_eq!(
|
||||
plan[0].copies,
|
||||
[copy(0, 0, 4, 0), copy(1, 0, 2, 128), copy(2, 0, 1, 160)]
|
||||
);
|
||||
assert_eq!(plan[0].staging_bytes, 168);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_submission_closes_when_the_next_row_does_not_fit() {
|
||||
// A 40-byte budget holds one 32-byte row of level 0, then two 16-byte rows of
|
||||
// level 1 and the single 8-byte row of level 2 together.
|
||||
let desc = Rgba8TextureDesc::new(8, 4, 3).unwrap();
|
||||
let plan = plan(desc, 40);
|
||||
assert_eq!(plan.len(), 5);
|
||||
for (row, submission) in plan[..4].iter().enumerate() {
|
||||
assert_eq!(submission.copies, [copy(0, row, 1, 0)]);
|
||||
assert_eq!(submission.staging_bytes, 32);
|
||||
}
|
||||
assert_eq!(plan[4].copies, [copy(1, 0, 2, 0), copy(2, 0, 1, 32)]);
|
||||
assert_eq!(plan[4].staging_bytes, 40);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_row_is_planned_once_within_budget() {
|
||||
for (w, h, mips) in [(1, 1, 1), (37, 19, 6), (64, 3, 7), (5, 128, 8)] {
|
||||
let desc = Rgba8TextureDesc::new(w, h, mips).unwrap();
|
||||
let widest = w * RGBA8_TEXEL_BYTES;
|
||||
for budget in [
|
||||
widest,
|
||||
widest + 4,
|
||||
3 * widest,
|
||||
w * h * RGBA8_TEXEL_BYTES * 2,
|
||||
] {
|
||||
let mut next_row = vec![0; mips as usize];
|
||||
for submission in plan(desc, budget) {
|
||||
assert!(submission.staging_bytes <= budget);
|
||||
let mut offset = 0;
|
||||
for c in &submission.copies {
|
||||
let (mw, _) = desc.mip_extent(c.level).unwrap();
|
||||
assert_eq!(c.first_row, next_row[c.level as usize]);
|
||||
assert_eq!(c.staging_offset, offset);
|
||||
assert!(c.rows > 0);
|
||||
offset += c.rows * mw * RGBA8_TEXEL_BYTES;
|
||||
next_row[c.level as usize] += c.rows;
|
||||
}
|
||||
assert_eq!(offset, submission.staging_bytes);
|
||||
}
|
||||
for level in 0..mips {
|
||||
assert_eq!(next_row[level as usize], desc.mip_extent(level).unwrap().1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_partial_and_malformed_uploads_before_planning() {
|
||||
let desc = Rgba8TextureDesc::new(8, 4, 2).unwrap();
|
||||
let bytes = vec![0; 8 * 4 * RGBA8_TEXEL_BYTES];
|
||||
let mips = levels(&desc, &bytes);
|
||||
|
||||
let missing = error(desc, &mips[..1], 1024);
|
||||
assert!(missing.contains("mip level 1 is missing"), "{missing}");
|
||||
|
||||
let duplicate = error(desc, &[mips[0], mips[1], mips[1]], 1024);
|
||||
assert!(duplicate.contains("more than once"), "{duplicate}");
|
||||
|
||||
let out_of_range = Rgba8MipLevel::new_packed(2, 2, 1, &bytes[..8]);
|
||||
let range = error(desc, &[mips[0], mips[1], out_of_range], 1024);
|
||||
assert!(range.contains("out of bounds"), "{range}");
|
||||
|
||||
let wrong_size = Rgba8MipLevel::new_packed(1, 4, 1, &bytes[..16]);
|
||||
assert!(error(desc, &[mips[0], wrong_size], 1024).contains("expected 4x2"));
|
||||
|
||||
let mut short_pitch = mips[0];
|
||||
short_pitch.row_pitch = 28;
|
||||
assert!(error(desc, &[short_pitch, mips[1]], 1024).contains("row pitch"));
|
||||
|
||||
let short_bytes = Rgba8MipLevel::new_packed(0, 8, 4, &bytes[..127]);
|
||||
assert!(error(desc, &[short_bytes, mips[1]], 1024).contains("buffer length"));
|
||||
|
||||
let small = error(desc, &mips, 28);
|
||||
assert!(small.contains("smaller than one 32-byte row"), "{small}");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use xenora_metal::texture_pipeline::{Rgba8TextureDesc, StagingBudget, plan_staged_upload};
|
||||
use xenora_metal::{MetalRgba8Texture, Rgba8MipLevel};
|
||||
use xenora_texture::{Bc1Upload, Bc1UploadDesc, TiledBc1};
|
||||
|
||||
use super::context;
|
||||
@@ -133,3 +135,162 @@ fn samples_pitched_bc1_upload_across_mips_and_layers() {
|
||||
);
|
||||
println!("checked 33 RGBA8 texels from pitched BC1 subresources");
|
||||
}
|
||||
|
||||
/// Texel bytes chosen so neighbouring texels, rows and levels all differ, built
|
||||
/// without any Xenora code so the readback has an independent expectation.
|
||||
fn pattern_texel(level: u32, x: usize, y: usize) -> [u8; 4] {
|
||||
let level = level as usize;
|
||||
[
|
||||
(x * 7 + level * 50) as u8,
|
||||
(y * 13 + level) as u8,
|
||||
((x ^ y) * 3) as u8,
|
||||
(255 - level * 9) as u8,
|
||||
]
|
||||
}
|
||||
|
||||
fn tight_pattern(level: u32, width: usize, height: usize) -> Vec<u8> {
|
||||
(0..height)
|
||||
.flat_map(|y| (0..width).flat_map(move |x| pattern_texel(level, x, y)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Each row padded by `pad` bytes of 0xEE, which must never reach the texture.
|
||||
fn padded_pattern(level: u32, width: usize, height: usize, pad: usize) -> Vec<u8> {
|
||||
let tight = tight_pattern(level, width, height);
|
||||
tight
|
||||
.chunks(width * 4)
|
||||
.flat_map(|row| row.iter().copied().chain(std::iter::repeat_n(0xEE, pad)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn padded_levels(desc: Rgba8TextureDesc, pad: usize) -> Vec<(usize, usize, Vec<u8>)> {
|
||||
(0..desc.mips)
|
||||
.map(|level| {
|
||||
let (w, h) = desc.mip_extent(level).unwrap();
|
||||
(w, h, padded_pattern(level, w, h, pad))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn mip_views(levels: &[(usize, usize, Vec<u8>)], pad: usize) -> Vec<Rgba8MipLevel<'_>> {
|
||||
levels
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(level, (w, h, bytes))| Rgba8MipLevel {
|
||||
level: level as u32,
|
||||
width: *w,
|
||||
height: *h,
|
||||
row_pitch: w * 4 + pad,
|
||||
bytes,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_upload_matches_the_source_under_every_budget() {
|
||||
let gpu = context();
|
||||
// 37×19 has six levels, down to 1×1, and odd sizes at every level.
|
||||
let desc = Rgba8TextureDesc::new(37, 19, 6).unwrap();
|
||||
let pad = 12;
|
||||
let levels = padded_levels(desc, pad);
|
||||
let mips = mip_views(&levels, pad);
|
||||
let total: usize = levels.iter().map(|(w, h, _)| w * h * 4).sum();
|
||||
let widest_row = 37 * 4;
|
||||
// One submission, several bands, a single row per band, and a budget that
|
||||
// leaves a remainder at every level.
|
||||
for budget in [total, 3 * widest_row, widest_row, widest_row + 4] {
|
||||
let budget = StagingBudget::new(budget).unwrap();
|
||||
let plan = plan_staged_upload(&desc, &mips, budget).unwrap();
|
||||
let (texture, report) =
|
||||
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget)
|
||||
.unwrap();
|
||||
assert_eq!(report.submissions, plan.len());
|
||||
assert!(report.peak_staging_bytes <= budget.max_bytes());
|
||||
assert_eq!(report.bytes_copied, total);
|
||||
if budget.max_bytes() == total {
|
||||
assert_eq!(report.submissions, 1);
|
||||
} else {
|
||||
assert!(report.submissions > 1);
|
||||
}
|
||||
for level in 0..desc.mips {
|
||||
let (w, h) = desc.mip_extent(level).unwrap();
|
||||
let actual = texture.read_back(gpu.device(), gpu.queue(), level).unwrap();
|
||||
assert_eq!(
|
||||
actual,
|
||||
tight_pattern(level, w, h),
|
||||
"budget {} level {level}",
|
||||
budget.max_bytes()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_and_direct_uploads_produce_the_same_texels() {
|
||||
let gpu = context();
|
||||
let desc = Rgba8TextureDesc::new(16, 9, 5).unwrap();
|
||||
let levels = padded_levels(desc, 0);
|
||||
let mips = mip_views(&levels, 0);
|
||||
let direct = MetalRgba8Texture::upload(gpu.device(), desc, &mips).unwrap();
|
||||
let budget = StagingBudget::new(16 * 4 * 2).unwrap();
|
||||
let (staged, _) =
|
||||
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget).unwrap();
|
||||
for level in 0..desc.mips {
|
||||
let (w, h) = desc.mip_extent(level).unwrap();
|
||||
let expected = tight_pattern(level, w, h);
|
||||
assert_eq!(
|
||||
direct.read_back(gpu.device(), gpu.queue(), level).unwrap(),
|
||||
expected
|
||||
);
|
||||
assert_eq!(
|
||||
staged.read_back(gpu.device(), gpu.queue(), level).unwrap(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_upload_handles_a_single_texel() {
|
||||
let gpu = context();
|
||||
let desc = Rgba8TextureDesc::new(1, 1, 1).unwrap();
|
||||
let texel = pattern_texel(0, 0, 0);
|
||||
let mips = [Rgba8MipLevel::new_packed(0, 1, 1, &texel)];
|
||||
let budget = StagingBudget::new(4).unwrap();
|
||||
let (texture, report) =
|
||||
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget).unwrap();
|
||||
assert_eq!((report.submissions, report.peak_staging_bytes), (1, 4));
|
||||
assert_eq!(
|
||||
texture.read_back(gpu.device(), gpu.queue(), 0).unwrap(),
|
||||
texel
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_upload_rejects_bad_input_before_touching_the_gpu() {
|
||||
let gpu = context();
|
||||
let desc = Rgba8TextureDesc::new(8, 4, 2).unwrap();
|
||||
let levels = padded_levels(desc, 0);
|
||||
let mips = mip_views(&levels, 0);
|
||||
let small = StagingBudget::new(28).unwrap();
|
||||
let error = MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, small)
|
||||
.unwrap_err();
|
||||
assert!(!error.is_capability_unavailable());
|
||||
assert!(
|
||||
error.to_string().contains("smaller than one 32-byte row"),
|
||||
"{error}"
|
||||
);
|
||||
let budget = StagingBudget::new(1024).unwrap();
|
||||
let missing =
|
||||
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips[..1], budget)
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
missing.to_string().contains("mip level 1 is missing"),
|
||||
"{missing}"
|
||||
);
|
||||
|
||||
// A Private texture refuses CPU writes instead of failing inside Metal.
|
||||
let (texture, _) =
|
||||
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget).unwrap();
|
||||
let refused = texture.upload_mip(&mips[0]).unwrap_err();
|
||||
assert!(refused.to_string().contains("Private-storage"), "{refused}");
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
#![cfg(all(feature = "gpu-tests", target_arch = "aarch64", target_os = "macos"))]
|
||||
|
||||
use xenora_metal::{MetalError, NativeCompute};
|
||||
use xenora_texture::{
|
||||
BcAlphaFormat, BcChannelFormat, BcCopyAlignment, BcFormat, BcTextureDesc, BcTextureLayout,
|
||||
PackedBcUpload,
|
||||
};
|
||||
|
||||
const EXTENTS: [(usize, usize); 4] = [(9, 5), (4, 2), (2, 1), (1, 1)];
|
||||
const BLOCK_COUNTS: [usize; 4] = [6, 1, 1, 1];
|
||||
|
||||
// Zero selector bits pick the first endpoint. These RGB565 endpoints encode
|
||||
// exact red, green, blue and white.
|
||||
const COLORS: [[u8; 2]; 4] = [[0x00, 0xf8], [0xe0, 0x07], [0x1f, 0x00], [0xff, 0xff]];
|
||||
const PIXELS: [[u8; 4]; 4] = [
|
||||
[255, 0, 0, 255],
|
||||
[0, 255, 0, 255],
|
||||
[0, 0, 255, 255],
|
||||
[255, 255, 255, 255],
|
||||
];
|
||||
|
||||
fn append_block(bytes: &mut Vec<u8>, format: BcFormat, variant: usize) {
|
||||
let color = COLORS[variant];
|
||||
let color_block = [color[0], color[1], 0, 0, 0, 0, 0, 0];
|
||||
let endpoint_block = |first| [first, 0, 0, 0, 0, 0, 0, 0];
|
||||
match format {
|
||||
BcFormat::Bc1 => bytes.extend(color_block),
|
||||
BcFormat::BcAlpha(format) => {
|
||||
bytes.extend(match format {
|
||||
BcAlphaFormat::Bc2 => [0xff; 8],
|
||||
BcAlphaFormat::Bc3 => endpoint_block(255),
|
||||
});
|
||||
bytes.extend(color_block);
|
||||
}
|
||||
BcFormat::BcChannel(format) => match format {
|
||||
BcChannelFormat::Bc4Unorm => bytes.extend(endpoint_block(PIXELS[variant][0])),
|
||||
BcChannelFormat::Bc5Unorm => {
|
||||
bytes.extend(endpoint_block(PIXELS[variant][0]));
|
||||
bytes.extend(endpoint_block(PIXELS[variant][1]));
|
||||
}
|
||||
BcChannelFormat::Bc4Snorm => bytes.extend(endpoint_block([129, 127, 0, 64][variant])),
|
||||
BcChannelFormat::Bc5Snorm => {
|
||||
bytes.extend(endpoint_block([129, 127, 0, 64][variant]));
|
||||
bytes.extend(endpoint_block([127, 129, 64, 0][variant]));
|
||||
}
|
||||
},
|
||||
_ => unreachable!("native readback fixture covers BC1–BC5"),
|
||||
}
|
||||
}
|
||||
|
||||
fn expected_words(format: BcFormat, layer: usize, mip: usize) -> Vec<u32> {
|
||||
let (width, height) = EXTENTS[mip];
|
||||
let mut result = Vec::new();
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
// The base image has a 3×2 physical block grid. Small levels
|
||||
// have a single block even when either texel extent is below 4.
|
||||
let variant = ((y / 4) * 3 + x / 4 + layer * 2 + mip) % 4;
|
||||
let rgba = match format {
|
||||
BcFormat::Bc1 | BcFormat::BcAlpha(_) => PIXELS[variant],
|
||||
BcFormat::BcChannel(BcChannelFormat::Bc4Unorm) => [PIXELS[variant][0], 0, 0, 255],
|
||||
BcFormat::BcChannel(BcChannelFormat::Bc5Unorm) => {
|
||||
[PIXELS[variant][0], PIXELS[variant][1], 0, 255]
|
||||
}
|
||||
BcFormat::BcChannel(BcChannelFormat::Bc4Snorm) => {
|
||||
[[129, 127, 0, 64][variant], 0, 0, 127]
|
||||
}
|
||||
BcFormat::BcChannel(BcChannelFormat::Bc5Snorm) => [
|
||||
[129, 127, 0, 64][variant],
|
||||
[127, 129, 64, 0][variant],
|
||||
0,
|
||||
127,
|
||||
],
|
||||
_ => unreachable!("native readback fixture covers BC1–BC5"),
|
||||
};
|
||||
result.push(u32::from_le_bytes(rgba));
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn read(
|
||||
gpu: &NativeCompute,
|
||||
upload: &PackedBcUpload<'_>,
|
||||
layer: usize,
|
||||
mip: u32,
|
||||
) -> Result<Vec<u32>, MetalError> {
|
||||
match upload.format() {
|
||||
BcFormat::Bc1 => gpu.read_bc1_upload(&upload.as_bc1(layer, mip).unwrap(), 0, 0),
|
||||
BcFormat::BcAlpha(_) => {
|
||||
gpu.read_bc_alpha_upload(&upload.as_bc_alpha(layer, mip).unwrap(), 0, 0)
|
||||
}
|
||||
BcFormat::BcChannel(_) => {
|
||||
gpu.read_bc_channel_upload(&upload.as_bc_channel(layer, mip).unwrap(), 0, 0)
|
||||
}
|
||||
_ => unreachable!("native readback fixture covers BC1–BC5"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packed_and_aligned_bc_uploads_return_known_pixels_on_metal() {
|
||||
let gpu = NativeCompute::new().expect("native Metal device and queue");
|
||||
for format in [
|
||||
BcFormat::Bc1,
|
||||
BcFormat::BcAlpha(BcAlphaFormat::Bc2),
|
||||
BcFormat::BcAlpha(BcAlphaFormat::Bc3),
|
||||
BcFormat::BcChannel(BcChannelFormat::Bc4Unorm),
|
||||
BcFormat::BcChannel(BcChannelFormat::Bc4Snorm),
|
||||
BcFormat::BcChannel(BcChannelFormat::Bc5Unorm),
|
||||
BcFormat::BcChannel(BcChannelFormat::Bc5Snorm),
|
||||
] {
|
||||
let desc = BcTextureDesc {
|
||||
width: 9,
|
||||
height: 5,
|
||||
mips: 4,
|
||||
layers: 2,
|
||||
format,
|
||||
};
|
||||
let tight = BcTextureLayout::new(desc, BcCopyAlignment::TIGHT).unwrap();
|
||||
let aligned = BcTextureLayout::new(
|
||||
desc,
|
||||
BcCopyAlignment {
|
||||
row: 256,
|
||||
placement: 512,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let mut source = Vec::new();
|
||||
for layer in 0..2 {
|
||||
for (mip, block_count) in BLOCK_COUNTS.into_iter().enumerate() {
|
||||
for n in 0..block_count {
|
||||
append_block(&mut source, format, (n + layer * 2 + mip) % 4);
|
||||
}
|
||||
}
|
||||
}
|
||||
let tight_upload = PackedBcUpload::new(&tight, &source).unwrap();
|
||||
let mut staged = vec![0xff; aligned.byte_len()];
|
||||
tight_upload.repack_into(&aligned, &mut staged).unwrap();
|
||||
let aligned_upload = PackedBcUpload::new(&aligned, &staged).unwrap();
|
||||
|
||||
for (name, upload) in [("tight", &tight_upload), ("aligned", &aligned_upload)] {
|
||||
for layer in 0..2 {
|
||||
for mip in 0..EXTENTS.len() {
|
||||
let actual = read(&gpu, upload, layer, mip as u32).unwrap_or_else(|error| {
|
||||
if error.is_capability_unavailable() {
|
||||
panic!("CAPABILITY UNAVAILABLE: {error}");
|
||||
}
|
||||
panic!("IMPLEMENTATION FAILURE: {format:?} {name} {layer}/{mip}: {error}");
|
||||
});
|
||||
assert_eq!(
|
||||
actual,
|
||||
expected_words(format, layer, mip),
|
||||
"{format:?} {name} layer {layer}, mip {mip}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Linear copy footprints for independently authored block-compressed textures.
|
||||
//!
|
||||
//! For example, a 5×3 BC1 level has two 8-byte blocks forming one 16-byte row.
|
||||
//! Its 2×1 mip takes a single 8-byte block. In a tight layout the levels occupy
|
||||
//! 24 bytes; either can be borrowed directly from the same payload.
|
||||
//!
|
||||
//! ```
|
||||
//! use xenora_texture::{BcCopyAlignment, BcFormat, BcTextureDesc, BcTextureLayout, PackedBcUpload};
|
||||
//!
|
||||
//! let layout = BcTextureLayout::new(
|
||||
//! BcTextureDesc { width: 5, height: 3, mips: 2, layers: 1, format: BcFormat::Bc1 },
|
||||
//! BcCopyAlignment::TIGHT,
|
||||
//! )?;
|
||||
//! let mut bytes = vec![0; layout.byte_len()];
|
||||
//! layout.write_tight(&mut bytes, 0, 1, &[0x55; 8])?;
|
||||
//! let upload = PackedBcUpload::new(&layout, &bytes)?;
|
||||
//! assert_eq!(upload.subresource(0, 1)?.bytes, &[0x55; 8]);
|
||||
//! # Ok::<(), xenora_texture::TextureError>(())
|
||||
//! ```
|
||||
|
||||
use super::{
|
||||
BLOCK_BYTES, Bc1Subresource, Bc1Upload, Bc1UploadDesc, BcAlphaFormat, BcAlphaUpload,
|
||||
BcAlphaUploadDesc, BcChannelFormat, BcChannelUpload, BcChannelUploadDesc, TextureError,
|
||||
mip_blocks,
|
||||
};
|
||||
|
||||
/// Block encoding carried by the layout. The layout handles bytes without decoding texels.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BcFormat {
|
||||
Bc1,
|
||||
BcAlpha(BcAlphaFormat),
|
||||
BcChannel(BcChannelFormat),
|
||||
Bc6hUfloat,
|
||||
Bc6hSfloat,
|
||||
Bc7,
|
||||
}
|
||||
|
||||
impl BcFormat {
|
||||
pub const fn block_bytes(self) -> usize {
|
||||
match self {
|
||||
Self::Bc1 => BLOCK_BYTES,
|
||||
Self::BcChannel(format) => format.block_bytes(),
|
||||
Self::BcAlpha(_) => BcAlphaUpload::BLOCK_BYTES,
|
||||
Self::Bc6hUfloat | Self::Bc6hSfloat | Self::Bc7 => 16,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Dimensions and encoding of a 2D texture or texture array.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct BcTextureDesc {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub mips: u32,
|
||||
pub layers: usize,
|
||||
pub format: BcFormat,
|
||||
}
|
||||
|
||||
/// Row and subresource placement alignments, in bytes. Each must be a nonzero
|
||||
/// power of two. Alignments smaller than a block are raised to its size.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct BcCopyAlignment {
|
||||
pub row: usize,
|
||||
pub placement: usize,
|
||||
}
|
||||
|
||||
impl BcCopyAlignment {
|
||||
pub const TIGHT: Self = Self {
|
||||
row: 1,
|
||||
placement: 1,
|
||||
};
|
||||
}
|
||||
|
||||
/// Logical dimensions and physical storage for one mip in one layer.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct BcFootprint {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub offset: usize,
|
||||
pub row_bytes: usize,
|
||||
pub row_pitch: usize,
|
||||
pub block_rows: usize,
|
||||
/// Full pitched rows, including the final row's padding.
|
||||
pub byte_len: usize,
|
||||
}
|
||||
|
||||
/// Layer-major storage with one footprint per mip. Layers share the same
|
||||
/// layout. Placement padding precedes each subresource as needed and there
|
||||
/// is no trailing placement padding at the end of the final layer.
|
||||
#[derive(Debug)]
|
||||
pub struct BcTextureLayout {
|
||||
desc: BcTextureDesc,
|
||||
mips: Vec<BcFootprint>,
|
||||
layer_stride: usize,
|
||||
byte_len: usize,
|
||||
}
|
||||
|
||||
impl BcTextureLayout {
|
||||
pub fn new(desc: BcTextureDesc, alignment: BcCopyAlignment) -> Result<Self, TextureError> {
|
||||
let max_mips = usize::BITS - desc.width.max(desc.height).leading_zeros();
|
||||
if desc.width == 0
|
||||
|| desc.height == 0
|
||||
|| desc.layers == 0
|
||||
|| desc.mips == 0
|
||||
|| desc.mips > max_mips
|
||||
|| !alignment.row.is_power_of_two()
|
||||
|| !alignment.placement.is_power_of_two()
|
||||
{
|
||||
return Err(TextureError::InvalidLayout);
|
||||
}
|
||||
|
||||
let block_bytes = desc.format.block_bytes();
|
||||
let row_alignment = alignment.row.max(block_bytes);
|
||||
let placement_alignment = alignment.placement.max(block_bytes);
|
||||
let mut mips = Vec::new();
|
||||
mips.try_reserve_exact(desc.mips as usize)
|
||||
.map_err(|_| TextureError::AllocationFailed)?;
|
||||
|
||||
let mut layer_len: usize = 0;
|
||||
for mip in 0..desc.mips {
|
||||
let (blocks_x, block_rows) = mip_blocks(desc.width, desc.height, mip);
|
||||
let row_bytes = blocks_x
|
||||
.checked_mul(block_bytes)
|
||||
.ok_or(TextureError::SizeOverflow)?;
|
||||
let row_pitch = align_up(row_bytes, row_alignment)?;
|
||||
let offset = align_up(layer_len, placement_alignment)?;
|
||||
let byte_len = row_pitch
|
||||
.checked_mul(block_rows)
|
||||
.ok_or(TextureError::SizeOverflow)?;
|
||||
layer_len = offset
|
||||
.checked_add(byte_len)
|
||||
.ok_or(TextureError::SizeOverflow)?;
|
||||
mips.push(BcFootprint {
|
||||
width: (desc.width >> mip).max(1),
|
||||
height: (desc.height >> mip).max(1),
|
||||
offset,
|
||||
row_bytes,
|
||||
row_pitch,
|
||||
block_rows,
|
||||
byte_len,
|
||||
});
|
||||
}
|
||||
|
||||
// A single layer never needs padding after its last mip.
|
||||
let layer_stride = if desc.layers == 1 {
|
||||
layer_len
|
||||
} else {
|
||||
align_up(layer_len, placement_alignment)?
|
||||
};
|
||||
let byte_len = layer_stride
|
||||
.checked_mul(desc.layers - 1)
|
||||
.and_then(|prefix| prefix.checked_add(layer_len))
|
||||
.ok_or(TextureError::SizeOverflow)?;
|
||||
Ok(Self {
|
||||
desc,
|
||||
mips,
|
||||
layer_stride,
|
||||
byte_len,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn byte_len(&self) -> usize {
|
||||
self.byte_len
|
||||
}
|
||||
|
||||
pub fn footprint(&self, layer: usize, mip: u32) -> Result<BcFootprint, TextureError> {
|
||||
if layer >= self.desc.layers {
|
||||
return Err(TextureError::OutOfBounds);
|
||||
}
|
||||
let footprint = self
|
||||
.mips
|
||||
.get(mip as usize)
|
||||
.ok_or(TextureError::OutOfBounds)?;
|
||||
Ok(self.at_layer(*footprint, layer))
|
||||
}
|
||||
|
||||
/// Writes tightly packed block rows to one subresource. Clears that
|
||||
/// subresource's row padding and leaves the rest of the payload alone.
|
||||
/// The destination must include exactly this layout's full byte span.
|
||||
pub fn write_tight(
|
||||
&self,
|
||||
dst: &mut [u8],
|
||||
layer: usize,
|
||||
mip: u32,
|
||||
src: &[u8],
|
||||
) -> Result<(), TextureError> {
|
||||
let fp = self.footprint(layer, mip)?;
|
||||
if dst.len() != self.byte_len || src.len() != fp.row_bytes * fp.block_rows {
|
||||
return Err(TextureError::InvalidByteLength);
|
||||
}
|
||||
|
||||
let dst = &mut dst[fp.offset..fp.offset + fp.byte_len];
|
||||
dst.fill(0);
|
||||
copy_rows(src, fp.row_bytes, dst, fp.row_pitch, fp.row_bytes);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn at_layer(&self, mut footprint: BcFootprint, layer: usize) -> BcFootprint {
|
||||
// Construction checked the span through the end of the final layer.
|
||||
footprint.offset += self.layer_stride * layer;
|
||||
footprint
|
||||
}
|
||||
}
|
||||
|
||||
/// A validated, borrowed payload. Padding bytes in its input may be arbitrary.
|
||||
#[derive(Debug)]
|
||||
pub struct PackedBcUpload<'a> {
|
||||
layout: &'a BcTextureLayout,
|
||||
bytes: &'a [u8],
|
||||
}
|
||||
|
||||
impl<'a> PackedBcUpload<'a> {
|
||||
pub fn new(layout: &'a BcTextureLayout, bytes: &'a [u8]) -> Result<Self, TextureError> {
|
||||
if bytes.len() != layout.byte_len {
|
||||
return Err(TextureError::InvalidByteLength);
|
||||
}
|
||||
Ok(Self { layout, bytes })
|
||||
}
|
||||
|
||||
pub fn format(&self) -> BcFormat {
|
||||
self.layout.desc.format
|
||||
}
|
||||
|
||||
/// Borrows the selected block rows, including their row padding.
|
||||
pub fn subresource(&self, layer: usize, mip: u32) -> Result<Bc1Subresource<'a>, TextureError> {
|
||||
let fp = self.layout.footprint(layer, mip)?;
|
||||
Ok(Bc1Subresource {
|
||||
bytes: &self.bytes[fp.offset..fp.offset + fp.byte_len],
|
||||
width: fp.width,
|
||||
height: fp.height,
|
||||
row_pitch: fp.row_pitch,
|
||||
})
|
||||
}
|
||||
|
||||
/// Copies every logical block to an equivalent layout and zeroes its padding.
|
||||
/// The source and destination must have the same dimensions, mip and layer
|
||||
/// counts, and block encoding. A rejected copy leaves the destination intact.
|
||||
pub fn repack_into(
|
||||
&self,
|
||||
layout: &BcTextureLayout,
|
||||
dst: &mut [u8],
|
||||
) -> Result<(), TextureError> {
|
||||
if self.layout.desc != layout.desc {
|
||||
return Err(TextureError::InvalidLayout);
|
||||
}
|
||||
if dst.len() != layout.byte_len {
|
||||
return Err(TextureError::InvalidByteLength);
|
||||
}
|
||||
|
||||
dst.fill(0);
|
||||
for layer in 0..layout.desc.layers {
|
||||
for (&source, &target) in self.layout.mips.iter().zip(&layout.mips) {
|
||||
let source = self.layout.at_layer(source, layer);
|
||||
let target = layout.at_layer(target, layer);
|
||||
copy_rows(
|
||||
&self.bytes[source.offset..source.offset + source.byte_len],
|
||||
source.row_pitch,
|
||||
&mut dst[target.offset..target.offset + target.byte_len],
|
||||
target.row_pitch,
|
||||
source.row_bytes,
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adapts one BC1 subresource to the existing single-upload reader, without copying.
|
||||
pub fn as_bc1(&self, layer: usize, mip: u32) -> Result<Bc1Upload<'a>, TextureError> {
|
||||
if self.layout.desc.format != BcFormat::Bc1 {
|
||||
return Err(TextureError::InvalidLayout);
|
||||
}
|
||||
let view = self.subresource(layer, mip)?;
|
||||
Bc1Upload::new(
|
||||
view.bytes,
|
||||
Bc1UploadDesc {
|
||||
width: view.width,
|
||||
height: view.height,
|
||||
mips: 1,
|
||||
layers: 1,
|
||||
format: 1,
|
||||
usage: 1,
|
||||
row_pitch: view.row_pitch,
|
||||
slice_pitch: view.bytes.len(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Adapts one BC2 or BC3 subresource to the existing reader, without copying.
|
||||
pub fn as_bc_alpha(&self, layer: usize, mip: u32) -> Result<BcAlphaUpload<'a>, TextureError> {
|
||||
let BcFormat::BcAlpha(format) = self.layout.desc.format else {
|
||||
return Err(TextureError::InvalidLayout);
|
||||
};
|
||||
let view = self.subresource(layer, mip)?;
|
||||
BcAlphaUpload::new(
|
||||
view.bytes,
|
||||
BcAlphaUploadDesc {
|
||||
width: view.width,
|
||||
height: view.height,
|
||||
mips: 1,
|
||||
layers: 1,
|
||||
format,
|
||||
row_pitch: view.row_pitch,
|
||||
slice_pitch: view.bytes.len(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Adapts one BC4 or BC5 subresource to the existing reader, without copying.
|
||||
pub fn as_bc_channel(
|
||||
&self,
|
||||
layer: usize,
|
||||
mip: u32,
|
||||
) -> Result<BcChannelUpload<'a>, TextureError> {
|
||||
let BcFormat::BcChannel(format) = self.layout.desc.format else {
|
||||
return Err(TextureError::InvalidLayout);
|
||||
};
|
||||
let view = self.subresource(layer, mip)?;
|
||||
BcChannelUpload::new(
|
||||
view.bytes,
|
||||
BcChannelUploadDesc {
|
||||
width: view.width,
|
||||
height: view.height,
|
||||
mips: 1,
|
||||
layers: 1,
|
||||
format,
|
||||
row_pitch: view.row_pitch,
|
||||
slice_pitch: view.bytes.len(),
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn align_up(value: usize, alignment: usize) -> Result<usize, TextureError> {
|
||||
value
|
||||
.checked_next_multiple_of(alignment)
|
||||
.ok_or(TextureError::SizeOverflow)
|
||||
}
|
||||
|
||||
fn copy_rows(src: &[u8], src_pitch: usize, dst: &mut [u8], dst_pitch: usize, row_bytes: usize) {
|
||||
for (src_row, dst_row) in src
|
||||
.chunks_exact(src_pitch)
|
||||
.zip(dst.chunks_exact_mut(dst_pitch))
|
||||
{
|
||||
dst_row[..row_bytes].copy_from_slice(&src_row[..row_bytes]);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
mod bc;
|
||||
mod bc6h;
|
||||
mod bc7;
|
||||
mod footprint;
|
||||
pub mod sampler;
|
||||
mod upload;
|
||||
pub use bc::{
|
||||
@@ -19,6 +20,9 @@ pub use bc6h::{
|
||||
BC6H_SUPPORTED_MODES, Bc6hError, bc6h_mode, decode_bc6h_sfloat, decode_bc6h_ufloat,
|
||||
};
|
||||
pub use bc7::{BC7_SUPPORTED_MODES, bc7_mode, decode_bc7};
|
||||
pub use footprint::{
|
||||
BcCopyAlignment, BcFootprint, BcFormat, BcTextureDesc, BcTextureLayout, PackedBcUpload,
|
||||
};
|
||||
pub use sampler::{AddressMode, FilterMode, SamplerDesc, SamplerError, TextureMetadata};
|
||||
pub use upload::{
|
||||
Bc1Subresource, Bc1Upload, Bc1UploadDesc, BcAlphaFormat, BcAlphaUpload, BcAlphaUploadDesc,
|
||||
|
||||
@@ -0,0 +1,375 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use xenora_texture::{
|
||||
Bc1Upload, Bc1UploadDesc, BcAlphaFormat, BcChannelFormat, BcCopyAlignment, BcFootprint,
|
||||
BcFormat, BcTextureDesc, BcTextureLayout, PackedBcUpload, TextureError,
|
||||
};
|
||||
|
||||
const DESC: BcTextureDesc = BcTextureDesc {
|
||||
width: 13,
|
||||
height: 9,
|
||||
mips: 4,
|
||||
layers: 2,
|
||||
format: BcFormat::Bc1,
|
||||
};
|
||||
|
||||
const ALIGNED: BcCopyAlignment = BcCopyAlignment {
|
||||
row: 32,
|
||||
placement: 128,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn hand_calculated_footprints_cover_partial_blocks_and_layer_padding() {
|
||||
let tight = BcTextureLayout::new(DESC, BcCopyAlignment::TIGHT).unwrap();
|
||||
let aligned = BcTextureLayout::new(DESC, ALIGNED).unwrap();
|
||||
// 13×9 has four blocks across and three down. 6×4 takes two blocks.
|
||||
// Both 3×2 and 1×1 take one block each.
|
||||
let levels = [(13, 9, 32, 3), (6, 4, 16, 1), (3, 2, 8, 1), (1, 1, 8, 1)];
|
||||
for (layout, offsets, stride, pitches) in [
|
||||
(&tight, [0, 96, 112, 120], 128, [32, 16, 8, 8]),
|
||||
(&aligned, [0, 128, 256, 384], 512, [32; 4]),
|
||||
] {
|
||||
for layer in 0..2 {
|
||||
for (mip, (width, height, row_bytes, block_rows)) in levels.into_iter().enumerate() {
|
||||
let row_pitch = pitches[mip];
|
||||
assert_eq!(
|
||||
layout.footprint(layer, mip as u32),
|
||||
Ok(BcFootprint {
|
||||
width,
|
||||
height,
|
||||
offset: stride * layer + offsets[mip],
|
||||
row_bytes,
|
||||
row_pitch,
|
||||
block_rows,
|
||||
byte_len: row_pitch * block_rows,
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(tight.byte_len(), 256);
|
||||
assert_eq!(aligned.byte_len(), 928);
|
||||
assert_eq!(aligned.footprint(2, 0), Err(TextureError::OutOfBounds));
|
||||
assert_eq!(aligned.footprint(0, 4), Err(TextureError::OutOfBounds));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compact_chain_uses_block_rows_instead_of_reserving_base_size_for_every_mip() {
|
||||
let desc = BcTextureDesc {
|
||||
width: 1024,
|
||||
height: 1024,
|
||||
mips: 11,
|
||||
layers: 1,
|
||||
..DESC
|
||||
};
|
||||
let layout = BcTextureLayout::new(desc, BcCopyAlignment::TIGHT).unwrap();
|
||||
assert_eq!(layout.byte_len(), 699_064);
|
||||
assert_eq!(layout.footprint(0, 10).unwrap().offset, 699_056);
|
||||
let compact = vec![0; layout.byte_len()];
|
||||
PackedBcUpload::new(&layout, &compact).unwrap();
|
||||
let fixed_slice = Bc1UploadDesc {
|
||||
width: 1024,
|
||||
height: 1024,
|
||||
mips: 11,
|
||||
layers: 1,
|
||||
format: 1,
|
||||
usage: 1,
|
||||
row_pitch: 2048,
|
||||
slice_pitch: 524_288,
|
||||
};
|
||||
assert_eq!(
|
||||
Bc1Upload::new(&compact, fixed_slice).unwrap_err(),
|
||||
TextureError::InvalidByteLength
|
||||
);
|
||||
let fixed = vec![0; 5_767_168];
|
||||
let fixed_upload = Bc1Upload::new(&fixed, fixed_slice).unwrap();
|
||||
assert_eq!(fixed_upload.subresource(0, 10).unwrap().bytes.len(), 2048);
|
||||
let aligned = BcTextureLayout::new(
|
||||
desc,
|
||||
BcCopyAlignment {
|
||||
row: 256,
|
||||
placement: 512,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(aligned.byte_len(), 705_280);
|
||||
assert_eq!(aligned.footprint(0, 10).unwrap().offset, 705_024);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_write_clears_its_row_padding_and_preserves_neighbors() {
|
||||
let layout = BcTextureLayout::new(BcTextureDesc { width: 9, ..DESC }, ALIGNED).unwrap();
|
||||
let src: Vec<u8> = (1..=72).collect(); // Three 24-byte rows.
|
||||
let mut dst = vec![0xcc; layout.byte_len()];
|
||||
layout.write_tight(&mut dst, 1, 0, &src).unwrap();
|
||||
let mut expected = vec![0xcc; dst.len()];
|
||||
expected[512..608].fill(0);
|
||||
expected[512..536].copy_from_slice(&src[..24]);
|
||||
expected[544..568].copy_from_slice(&src[24..48]);
|
||||
expected[576..600].copy_from_slice(&src[48..]);
|
||||
assert_eq!(dst, expected);
|
||||
let view = PackedBcUpload::new(&layout, &dst).unwrap();
|
||||
let level = view.subresource(1, 0).unwrap();
|
||||
assert_eq!(level.bytes, &dst[512..608]);
|
||||
assert!(std::ptr::eq(level.bytes.as_ptr(), dst[512..].as_ptr()));
|
||||
assert_eq!((level.width, level.height, level.row_pitch), (9, 9, 32));
|
||||
let legacy = view.as_bc1(1, 0).unwrap().subresource(0, 0).unwrap();
|
||||
assert!(std::ptr::eq(legacy.bytes.as_ptr(), level.bytes.as_ptr()));
|
||||
assert_eq!(legacy.bytes.len(), 96);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repack_ignores_dirty_source_padding_and_zeroes_both_kinds_of_target_padding() {
|
||||
let tight = BcTextureLayout::new(DESC, BcCopyAlignment::TIGHT).unwrap();
|
||||
let aligned = BcTextureLayout::new(DESC, ALIGNED).unwrap();
|
||||
let tight_bytes: Vec<u8> = (0..=255).collect();
|
||||
// Independent byte map from the paper footprints above.
|
||||
let spans = [
|
||||
(0, 0, 96),
|
||||
(96, 128, 16),
|
||||
(112, 256, 8),
|
||||
(120, 384, 8),
|
||||
(128, 512, 96),
|
||||
(224, 640, 16),
|
||||
(240, 768, 8),
|
||||
(248, 896, 8),
|
||||
];
|
||||
let mut dirty_aligned = vec![0xab; 928];
|
||||
let mut clean_aligned = vec![0; 928];
|
||||
for (src, dst, len) in spans {
|
||||
dirty_aligned[dst..dst + len].copy_from_slice(&tight_bytes[src..src + len]);
|
||||
clean_aligned[dst..dst + len].copy_from_slice(&tight_bytes[src..src + len]);
|
||||
}
|
||||
|
||||
let input = PackedBcUpload::new(&aligned, &dirty_aligned).unwrap();
|
||||
let mut compact = vec![0xcc; tight.byte_len()];
|
||||
input.repack_into(&tight, &mut compact).unwrap();
|
||||
assert_eq!(compact, tight_bytes);
|
||||
|
||||
let mut output = vec![0xcc; aligned.byte_len()];
|
||||
input.repack_into(&aligned, &mut output).unwrap();
|
||||
assert_eq!(output, clean_aligned);
|
||||
output.fill(0xcc);
|
||||
PackedBcUpload::new(&tight, &compact)
|
||||
.unwrap()
|
||||
.repack_into(&aligned, &mut output)
|
||||
.unwrap();
|
||||
assert_eq!(output, clean_aligned);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_sizes_before_writing_and_requires_the_same_encoding() {
|
||||
let layout = BcTextureLayout::new(DESC, ALIGNED).unwrap();
|
||||
let mut bytes = vec![0xab; layout.byte_len()];
|
||||
assert_eq!(
|
||||
layout.write_tight(&mut bytes, 0, 3, &[0; 7]),
|
||||
Err(TextureError::InvalidByteLength)
|
||||
);
|
||||
assert_eq!(
|
||||
layout.write_tight(&mut bytes, 0, 3, &[0; 9]),
|
||||
Err(TextureError::InvalidByteLength)
|
||||
);
|
||||
assert_eq!(
|
||||
layout.write_tight(&mut bytes[..927], 0, 3, &[0; 8]),
|
||||
Err(TextureError::InvalidByteLength)
|
||||
);
|
||||
assert_eq!(
|
||||
layout.write_tight(&mut bytes, 2, 3, &[0; 8]),
|
||||
Err(TextureError::OutOfBounds)
|
||||
);
|
||||
assert!(bytes.iter().all(|byte| *byte == 0xab));
|
||||
|
||||
for len in [0, 927, 929] {
|
||||
assert_eq!(
|
||||
PackedBcUpload::new(&layout, &vec![0; len]).unwrap_err(),
|
||||
TextureError::InvalidByteLength
|
||||
);
|
||||
}
|
||||
let upload = PackedBcUpload::new(&layout, &bytes).unwrap();
|
||||
for incompatible in [
|
||||
BcTextureDesc {
|
||||
format: BcFormat::BcChannel(BcChannelFormat::Bc4Unorm),
|
||||
..DESC
|
||||
},
|
||||
BcTextureDesc { width: 14, ..DESC },
|
||||
BcTextureDesc { height: 10, ..DESC },
|
||||
BcTextureDesc { mips: 3, ..DESC },
|
||||
BcTextureDesc { layers: 1, ..DESC },
|
||||
] {
|
||||
let target = BcTextureLayout::new(incompatible, ALIGNED).unwrap();
|
||||
let mut dst = vec![0xcc; target.byte_len()];
|
||||
assert_eq!(
|
||||
upload.repack_into(&target, &mut dst),
|
||||
Err(TextureError::InvalidLayout)
|
||||
);
|
||||
assert!(dst.iter().all(|byte| *byte == 0xcc));
|
||||
}
|
||||
let mut short = vec![0xcc; 927];
|
||||
assert_eq!(
|
||||
upload.repack_into(&layout, &mut short),
|
||||
Err(TextureError::InvalidByteLength)
|
||||
);
|
||||
assert!(short.iter().all(|byte| *byte == 0xcc));
|
||||
assert_eq!(
|
||||
upload.as_bc_alpha(0, 0).unwrap_err(),
|
||||
TextureError::InvalidLayout
|
||||
);
|
||||
assert_eq!(
|
||||
upload.as_bc_channel(0, 0).unwrap_err(),
|
||||
TextureError::InvalidLayout
|
||||
);
|
||||
assert_eq!(upload.as_bc1(0, 4).unwrap_err(), TextureError::OutOfBounds);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_descriptors_and_overflowing_footprints() {
|
||||
for desc in [
|
||||
BcTextureDesc { width: 0, ..DESC },
|
||||
BcTextureDesc { height: 0, ..DESC },
|
||||
BcTextureDesc { mips: 0, ..DESC },
|
||||
BcTextureDesc { mips: 5, ..DESC },
|
||||
BcTextureDesc { layers: 0, ..DESC },
|
||||
] {
|
||||
assert_eq!(
|
||||
BcTextureLayout::new(desc, ALIGNED).unwrap_err(),
|
||||
TextureError::InvalidLayout
|
||||
);
|
||||
}
|
||||
for (row, placement) in [(0, 1), (1, 0), (3, 1), (1, 3)] {
|
||||
assert_eq!(
|
||||
BcTextureLayout::new(DESC, BcCopyAlignment { row, placement }).unwrap_err(),
|
||||
TextureError::InvalidLayout
|
||||
);
|
||||
}
|
||||
for desc in [
|
||||
BcTextureDesc {
|
||||
width: usize::MAX,
|
||||
..DESC
|
||||
},
|
||||
BcTextureDesc {
|
||||
height: usize::MAX,
|
||||
..DESC
|
||||
},
|
||||
BcTextureDesc {
|
||||
layers: usize::MAX,
|
||||
..DESC
|
||||
},
|
||||
] {
|
||||
assert_eq!(
|
||||
BcTextureLayout::new(desc, ALIGNED).unwrap_err(),
|
||||
TextureError::SizeOverflow
|
||||
);
|
||||
}
|
||||
let highest_bit = 1 << (usize::BITS - 1);
|
||||
for alignment in [
|
||||
BcCopyAlignment {
|
||||
row: highest_bit,
|
||||
placement: 1,
|
||||
},
|
||||
BcCopyAlignment {
|
||||
row: 1,
|
||||
placement: highest_bit,
|
||||
},
|
||||
] {
|
||||
assert_eq!(
|
||||
BcTextureLayout::new(DESC, alignment).unwrap_err(),
|
||||
TextureError::SizeOverflow
|
||||
);
|
||||
}
|
||||
// Even an unusually large placement alignment needs no trailing space
|
||||
// after a sole subresource.
|
||||
let one = BcTextureDesc {
|
||||
mips: 1,
|
||||
layers: 1,
|
||||
..DESC
|
||||
};
|
||||
let layout = BcTextureLayout::new(
|
||||
one,
|
||||
BcCopyAlignment {
|
||||
row: 1,
|
||||
placement: highest_bit,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(layout.byte_len(), 96);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_block_sizes_match_a_byte_by_byte_layout_oracle() {
|
||||
let formats = [
|
||||
(BcFormat::Bc1, 8),
|
||||
(BcFormat::BcAlpha(BcAlphaFormat::Bc2), 16),
|
||||
(BcFormat::BcAlpha(BcAlphaFormat::Bc3), 16),
|
||||
(BcFormat::BcChannel(BcChannelFormat::Bc4Unorm), 8),
|
||||
(BcFormat::BcChannel(BcChannelFormat::Bc4Snorm), 8),
|
||||
(BcFormat::BcChannel(BcChannelFormat::Bc5Unorm), 16),
|
||||
(BcFormat::BcChannel(BcChannelFormat::Bc5Snorm), 16),
|
||||
(BcFormat::Bc6hUfloat, 16),
|
||||
(BcFormat::Bc6hSfloat, 16),
|
||||
(BcFormat::Bc7, 16),
|
||||
];
|
||||
for (format, block_bytes) in formats {
|
||||
for (width, height) in [
|
||||
(1_usize, 1_usize),
|
||||
(1, 37),
|
||||
(37, 1),
|
||||
(4, 4),
|
||||
(5, 9),
|
||||
(17, 13),
|
||||
] {
|
||||
for (row, placement) in [(1, 1), (32, 16), (16, 128), (64, 512)] {
|
||||
let mips = usize::BITS - width.max(height).leading_zeros();
|
||||
let desc = BcTextureDesc {
|
||||
width,
|
||||
height,
|
||||
mips,
|
||||
layers: 3,
|
||||
format,
|
||||
};
|
||||
let layout =
|
||||
BcTextureLayout::new(desc, BcCopyAlignment { row, placement }).unwrap();
|
||||
let tight = BcTextureLayout::new(desc, BcCopyAlignment::TIGHT).unwrap();
|
||||
let mut expected = Vec::new();
|
||||
let mut source = Vec::new();
|
||||
for layer in 0..3 {
|
||||
let (mut w, mut h) = (width, height);
|
||||
for mip in 0..mips {
|
||||
while expected.len() % placement != 0 {
|
||||
expected.push(0);
|
||||
}
|
||||
let start = expected.len();
|
||||
let mut tight_level = Vec::new();
|
||||
for y in (0..h).step_by(4) {
|
||||
let row_start = expected.len();
|
||||
for x in (0..w).step_by(4) {
|
||||
for i in 0..block_bytes {
|
||||
let byte =
|
||||
(1 + layer * 51 + mip as usize * 7 + x + 3 * y + i) as u8;
|
||||
expected.push(byte);
|
||||
tight_level.push(byte);
|
||||
}
|
||||
}
|
||||
while (expected.len() - row_start) % row != 0 {
|
||||
expected.push(0);
|
||||
}
|
||||
}
|
||||
let fp = layout.footprint(layer, mip).unwrap();
|
||||
assert_eq!(
|
||||
(fp.offset, fp.offset + fp.byte_len),
|
||||
(start, expected.len())
|
||||
);
|
||||
source.extend(tight_level);
|
||||
(w, h) = ((w / 2).max(1), (h / 2).max(1));
|
||||
}
|
||||
}
|
||||
let upload = PackedBcUpload::new(&tight, &source).unwrap();
|
||||
let mut bytes = vec![0xff; layout.byte_len()];
|
||||
upload.repack_into(&layout, &mut bytes).unwrap();
|
||||
assert_eq!(
|
||||
bytes, expected,
|
||||
"{format:?}, {width}×{height}, {row}/{placement}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -45,6 +45,7 @@ Historical phase checkpoints retain their original evidence scope.
|
||||
|
||||
## Testing, validation, and benchmarks
|
||||
|
||||
- [Migrated pull-request integration review](testing/migration-pr-review.md) — Merge decisions, integration fixes, native verification and excluded concurrent work.
|
||||
- [Testing and acceptance index](testing/README.md) — Entry point for test procedures, evidence and review records.
|
||||
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](testing/shader-form-acceptance.md) — Independence, command, log and promotion rules for fixture-verified instruction forms.
|
||||
- [Engineering progress](progress.md) — Verification commands, metric definitions, and open release gates.
|
||||
@@ -52,7 +53,7 @@ Historical phase checkpoints retain their original evidence scope.
|
||||
- [Test inventory comparison](testing/test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
|
||||
- [Persistent resource and translated rendering acceptance](testing/x9-acceptance.md) — Pinned upstream tests, native ARM64 results and unsupported cases.
|
||||
- [Baseline acceptance](testing/phase-02-baseline.md), [Phase 01 assurance](testing/phase01-assurance.md), and [independent reviews](testing/review-log.md) — Candidate-specific results and release findings.
|
||||
- [Gate A: a compiled C program](testing/gate-a.md) — The two milestones, what the A1 test checks and what it does not show.
|
||||
- [Gate A: a compiled C program](testing/gate-a.md) — The two milestones, what the A1 and A2 tests check and what they do not show.
|
||||
- [Mutation testing](testing/mutation.md) and [benchmark protocol](testing/benchmarks.md) — Test sensitivity, benchmark inputs, and timing requirements.
|
||||
|
||||
## Research and engineering decisions
|
||||
|
||||
+53
-3
@@ -389,9 +389,9 @@ Everything else that is not modelled stops the guest with the runtime-limit
|
||||
fault and writes nothing, so that nothing is printed wrongly: the
|
||||
floating-point types (`e`, `f`, `g`, `a`), wide characters and strings (`C`,
|
||||
`S`, `lc`, `ls`), a locale object, option bits other than the three that do
|
||||
not affect these conversions, any stream other than `stdout` and `stderr`
|
||||
(files do not exist yet, and `stdin` cannot be written), an index above 2,
|
||||
more than 1 MiB in one call, and output past the 16 MiB bound.
|
||||
not affect these conversions, a pointer that is no stream, writing `stdin`,
|
||||
an index above 2, more than 1 MiB in one call, and output past the 16 MiB
|
||||
bound.
|
||||
|
||||
Choices where the documentation leaves room, each marked in the source:
|
||||
`%p` prints sixteen upper-case hexadecimal digits; `0` pads a character and
|
||||
@@ -399,6 +399,56 @@ a string as it pads a number; a precision also limits `(null)`; `%#.0o` of
|
||||
zero prints `0`, which is ISO C's rule. All six services are `partial`. None
|
||||
of this has been compared with Windows.
|
||||
|
||||
### Files through the C runtime
|
||||
|
||||
`fopen`, `fclose` and `fgets` give a hosted C program files, and the output
|
||||
services above (`__stdio_common_vfprintf`, `fwrite`, `fputs`, `fflush`,
|
||||
`setvbuf`) accept a stream `fopen` returned as well as `stdout` and `stderr`.
|
||||
The files are the ones on the in-memory `C:` drive described under
|
||||
"Synthetic guest files": a file written through a C stream is the file
|
||||
`ReadFile` reads, and the reverse.
|
||||
|
||||
| Service | Behaviour |
|
||||
| --- | --- |
|
||||
| `fopen(name, mode)` | Opens a file and returns its `FILE*`, or null with `errno` set. `r` needs the file to exist; `w` creates it or destroys its contents; `a` creates it and makes every write go to its end; `+` adds the other direction; `b` or `t` selects binary or text |
|
||||
| `fclose(stream)` | Closes the stream and returns 0; `EOF` with `EINVAL` for a null stream |
|
||||
| `fgets(buffer, count, stream)` | Reads up to `count - 1` characters, stopping after a newline, which it keeps, and adds a terminator. Returns the buffer, or null at end of file or on an error |
|
||||
| `perror(message)` | Writes the message, `: `, the text for `errno` and a newline to `stderr`; only the text when the message is null or empty |
|
||||
|
||||
A stream is in text mode unless its mode has `b`: a line feed is stored as a
|
||||
carriage return and a line feed, the pair is read back as a line feed, and
|
||||
`CTRL+Z` ends the input. Names are ASCII, with either slash, in any case,
|
||||
with or without `C:\`, as the drive accepts them.
|
||||
|
||||
`errno` after a failed `fopen`: `EINVAL` for a null or empty name or mode, a
|
||||
mode this runtime does not open, and a name the drive rejects; `ENOENT` when
|
||||
the file or its directory does not exist; `EACCES` for a directory; `EMFILE`
|
||||
when 64 streams are already open; `ENOSPC` when the drive holds its 256
|
||||
files; `ENOMEM` when the `FILE` object cannot be allocated. Output to a
|
||||
stream that was not opened for writing, and reading one not opened for
|
||||
reading, fail with `EBADF`; output the drive has no room for fails with
|
||||
`ENOSPC`. A failed write writes nothing.
|
||||
|
||||
What is not provided, and what is Xenora's choice:
|
||||
|
||||
- **Not provided:** the mode characters `x`, `c`, `n`, `N`, `S`, `R`, `T`,
|
||||
`D` and `ccs=`, which are refused; `fread`, `fseek`, `ftell`, `rewind`,
|
||||
`feof`, `ferror`, `fscanf`; reading `stdin` and closing a standard stream,
|
||||
which stop the guest.
|
||||
- **No buffering.** A write reaches the drive at once, so the rule that a
|
||||
`+` stream needs `fflush` or a seek between writing and reading does not
|
||||
apply.
|
||||
- **No sharing.** A C stream is not a Win32 handle. It does not stop
|
||||
`DeleteFileW` or `MoveFileW`, and ignores a handle's sharing mode. After
|
||||
its file is deleted a stream's reads and writes fail with `EBADF`.
|
||||
- **Choices:** the `errno` values above other than `EINVAL` for a null or
|
||||
empty argument, which is documented; an `a+` stream reads from the start;
|
||||
every `perror` text except "No such file or directory", which is the one
|
||||
Microsoft's page shows.
|
||||
|
||||
All four services are `partial`. None of this has been compared with
|
||||
Windows.
|
||||
|
||||
### CRT integer conversion
|
||||
|
||||
UCRT and the CRT conversion API set expose strtol, strtoul, wcstol, and
|
||||
|
||||
+14
-10
@@ -6,14 +6,14 @@ A declared service is not a claim of compatibility. `implemented` and `partial`
|
||||
|
||||
| Measure | Count |
|
||||
| --- | ---: |
|
||||
| Services with a declared ABI | 43 |
|
||||
| Generated adapters | 43 |
|
||||
| Unique handler implementations | 43 |
|
||||
| Services with a declared ABI | 47 |
|
||||
| Generated adapters | 47 |
|
||||
| Unique handler implementations | 47 |
|
||||
| Implemented | 7 |
|
||||
| Partial | 33 |
|
||||
| Partial | 37 |
|
||||
| Stub | 3 |
|
||||
| Conformance-tested through guest dispatch | 43 |
|
||||
| API-set aliases (not services) | 43 |
|
||||
| Conformance-tested through guest dispatch | 47 |
|
||||
| API-set aliases (not services) | 47 |
|
||||
| Independently accepted | 0 |
|
||||
|
||||
| Service | Signature | Status | Failure |
|
||||
@@ -32,10 +32,14 @@ A declared service is not a claim of compatibility. `implemented` and `partial`
|
||||
| `kernel32.dll!GetSystemTimeAsFileTime` | `(time: out<8>) -> void` | implemented | guest fault on an invalid pointer |
|
||||
| `ucrtbase.dll!__acrt_iob_func` | `(index: u32) -> ptr` | partial | stops the guest for an index above 2 or when the streams cannot be allocated |
|
||||
| `ucrtbase.dll!__stdio_common_vfprintf` | `(options: u64, stream: ptr, format: ptr, locale: ptr, arguments: ptr) -> i32` | partial | -1 with errno EINVAL for a null stream or format or an invalid format; stops the guest for what is not modelled |
|
||||
| `ucrtbase.dll!fwrite` | `(buffer: ptr, size: u64, count: u64, stream: ptr) -> u64` | partial | 0 with errno EINVAL for a null buffer or stream; stops the guest for a stream other than stdout or stderr |
|
||||
| `ucrtbase.dll!fputs` | `(text: ptr, stream: ptr) -> i32` | partial | EOF with errno EINVAL for a null string or stream; stops the guest for a stream other than stdout or stderr |
|
||||
| `ucrtbase.dll!fflush` | `(stream: ptr) -> i32` | partial | stops the guest for a stream that is not a standard stream |
|
||||
| `ucrtbase.dll!setvbuf` | `(stream: ptr, buffer: ptr, mode: i32, size: u64) -> i32` | partial | -1 with errno EINVAL for a null stream, an unknown mode or a size outside 2 to INT_MAX; stops the guest for a stream that is not a standard stream |
|
||||
| `ucrtbase.dll!fwrite` | `(buffer: ptr, size: u64, count: u64, stream: ptr) -> u64` | partial | 0 with errno EINVAL for a null buffer or stream, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream |
|
||||
| `ucrtbase.dll!fputs` | `(text: ptr, stream: ptr) -> i32` | partial | EOF with errno EINVAL for a null string or stream, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream |
|
||||
| `ucrtbase.dll!fflush` | `(stream: ptr) -> i32` | partial | stops the guest for a pointer that is no stream |
|
||||
| `ucrtbase.dll!setvbuf` | `(stream: ptr, buffer: ptr, mode: i32, size: u64) -> i32` | partial | -1 with errno EINVAL for a null stream, an unknown mode or a size outside 2 to INT_MAX; stops the guest for a pointer that is no stream |
|
||||
| `ucrtbase.dll!fopen` | `(name: ptr, mode: ptr) -> ptr` | partial | null with errno EINVAL, ENOENT, EACCES, EMFILE, ENOSPC or ENOMEM |
|
||||
| `ucrtbase.dll!fclose` | `(stream: ptr) -> i32` | partial | EOF with errno EINVAL for a null stream; stops the guest for a standard stream or a pointer that is no stream |
|
||||
| `ucrtbase.dll!fgets` | `(buffer: ptr, count: i32, stream: ptr) -> ptr` | partial | null at end of file; null with errno EINVAL or EBADF; stops the guest for stdin or a pointer that is no stream |
|
||||
| `ucrtbase.dll!perror` | `(message: ptr) -> void` | partial | never |
|
||||
| `kernel32.dll!GetLastError` | `() -> u32` | partial | never |
|
||||
| `kernel32.dll!SetLastError` | `(code: u32) -> void` | partial | never |
|
||||
| `ucrtbase.dll!__p___argc` | `() -> ptr` | partial | stops the guest when the variable cannot be allocated |
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# Testing and acceptance
|
||||
|
||||
- [Migrated pull-request integration review](migration-pr-review.md) — Merge decisions, fixes, native verification and remaining scope limits.
|
||||
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](shader-form-acceptance.md) — Rule and evidence required to promote a form from local results to `fixture verified`.
|
||||
- [Test inventory comparison](test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
|
||||
- [Persistent resource and translated rendering acceptance](x9-acceptance.md) — Native ARM64 results and unsupported cases.
|
||||
|
||||
@@ -76,6 +76,88 @@ cargo build --release -p xenora-benchmarks
|
||||
MTL_DEBUG_LAYER=0 MTL_SHADER_VALIDATION=0 ./target/release/xenora-bench --reps 7
|
||||
```
|
||||
|
||||
## Startup distributions
|
||||
|
||||
`xenora-bench startup` measures what it costs to get one fixture result from
|
||||
Metal, in two regimes:
|
||||
|
||||
- **Fresh process.** The harness launches its own executable `--processes`
|
||||
times (default 30), one after another. Each child creates the Metal device and
|
||||
queue, translates the fixture, runs it once and checks the output.
|
||||
- **Repeated.** The harness process creates one device, runs the fixture once
|
||||
(reported as *first in process*), then translates and runs it `--reps` more
|
||||
times (default 100).
|
||||
|
||||
The fixture is the first one in `benchmarks/manifest.toml` unless `--fixture`
|
||||
names another, at its smallest declared size unless `--words` sets one. The
|
||||
independent reference must agree with the hand-derived expected values first,
|
||||
and every sample in both regimes must produce the expected words. A wrong
|
||||
output, a child that fails or does not exit within 60 seconds, or a damaged
|
||||
sample line stops the run before anything is written.
|
||||
|
||||
| Phase | Source | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `spawn_to_main` | wall clock, parent before spawn to child `main` | Process launch and Rust runtime start (fresh only) |
|
||||
| `device` | host monotonic clock | `NativeCompute::new`: device and queue (fresh, and once in the repeated process) |
|
||||
| `translate` | host monotonic clock | Read the fixture and run `xenora-shader::compile` |
|
||||
| `library` | `RunProfile` | `newLibraryWithSource` |
|
||||
| `pipeline` | `RunProfile` | Compute pipeline state creation |
|
||||
| `submit` | `RunProfile` | `host` minus `library` and `pipeline`: buffers, encode, commit, wait |
|
||||
| `gpu` | `GPUEndTime - GPUStartTime` | Command-buffer GPU execution |
|
||||
| `readback` | `RunProfile` | Copy the output words back |
|
||||
| process wall | host monotonic clock in the parent | Spawn to exit of one fresh child |
|
||||
|
||||
The report gives median, p90, p99 and maximum per phase. Percentiles
|
||||
interpolate linearly, so with 30 processes p99 lies between the two largest
|
||||
samples. `startup.json` also keeps every fresh sample in launch order.
|
||||
Children inherit the parent's environment, so the `MTL_*` validation values in
|
||||
`metadata.json` apply to both regimes. Results go to the ignored
|
||||
`artifacts/startup/<hardware>/<run-id>/` unless `--output` says otherwise.
|
||||
|
||||
```sh
|
||||
cargo build --release -p xenora-benchmarks
|
||||
MTL_DEBUG_LAYER=0 MTL_SHADER_VALIDATION=0 ./target/release/xenora-bench startup
|
||||
```
|
||||
|
||||
### Recorded run
|
||||
|
||||
This is the imported contributor's record for the named source revision.
|
||||
The integration review does not reproduce or independently accept the full
|
||||
measurement protocol below.
|
||||
|
||||
Run `1795544761`, Apple M4, release build of `0fdb995` plus this harness, API
|
||||
and shader validation off, AC power, no thermal warnings, started right after
|
||||
the release build. Fixture `add`, 4 words, 30 fresh processes, 100 repeated
|
||||
runs. All values in milliseconds.
|
||||
|
||||
| Phase | Fresh median | Fresh p90 | Fresh p99 | Fresh max | First in process | Repeated median | Repeated p90 | Repeated p99 | Repeated max |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| `spawn_to_main` | 2.746 | 3.133 | 5.325 | 6.198 | – | – | – | – | – |
|
||||
| `device` | 35.762 | 38.770 | 41.060 | 41.864 | 32.802 | – | – | – | – |
|
||||
| `translate` | 0.061 | 0.071 | 0.084 | 0.089 | 0.067 | 0.016 | 0.023 | 0.041 | 0.043 |
|
||||
| `library` | 0.402 | 0.434 | 18.595 | 25.976 | 0.399 | 0.006 | 0.010 | 0.018 | 0.019 |
|
||||
| `pipeline` | 0.363 | 0.401 | 0.623 | 0.708 | 0.342 | 0.013 | 0.021 | 0.031 | 0.043 |
|
||||
| `submit` | 1.665 | 1.894 | 1.951 | 1.953 | 1.647 | 0.214 | 0.384 | 0.440 | 3.941 |
|
||||
| `gpu` | 0.007 | 0.008 | 0.010 | 0.011 | 0.008 | 0.007 | 0.008 | 0.061 | 1.742 |
|
||||
| `readback` | 0.001 | 0.001 | 0.002 | 0.002 | 0.001 | < 0.001 | < 0.001 | < 0.001 | < 0.001 |
|
||||
| process wall (spawn to exit) | 43.225 | 46.770 | 68.236 | 75.958 | – | – | – | – | – |
|
||||
|
||||
Observations, without causal claims:
|
||||
|
||||
- Device and queue creation is the largest fresh-process phase, about 36 ms of a
|
||||
43 ms median process. Within one process it is paid once.
|
||||
- The `library` tail came from the first child launched after the build
|
||||
(25.976 ms; the other 29 were 0.36–0.45 ms). A second run immediately after,
|
||||
`1795544763`, had a fresh `library` maximum of 0.446 ms, with `device` median
|
||||
36.414 ms and process-wall median 44.111 ms. This fits an on-disk Metal
|
||||
compilation cache, but the run does not show that.
|
||||
- After the first run in a process, `library` and `pipeline` fall to about
|
||||
0.01 ms and `submit` to about 0.2 ms. The `gpu` time for this 4-word kernel is
|
||||
at timer scale in both regimes.
|
||||
|
||||
Two runs on one host do not describe other Apple GPU generations, sustained
|
||||
load, other fixtures or larger word counts.
|
||||
|
||||
## Limitations
|
||||
|
||||
The corpus currently covers three synthetic gfx1030 compute fixtures under the
|
||||
|
||||
+54
-17
@@ -8,7 +8,7 @@ when both pass.
|
||||
| Milestone | What it is | Status |
|
||||
| --- | --- | --- |
|
||||
| A1 | An original C program with no C library linked, importing documented `kernel32.dll` and `ucrtbase.dll` functions, run through the loader and the ARM64 DBT with proper process exit | Passes locally; awaiting independent review |
|
||||
| A2 | A hosted C program: a real C runtime startup, the standard C library, `argc` and `argv`, stdio and formatted output, normal exit and runtime cleanup | In progress; does not pass |
|
||||
| A2 | A hosted C program: a real C runtime startup, the standard C library, `argc` and `argv`, stdio and formatted output, normal exit and runtime cleanup | Passes locally; awaiting independent review |
|
||||
|
||||
## A1
|
||||
|
||||
@@ -47,22 +47,59 @@ whose entry point returns its status gives the same result as `ExitProcess`.
|
||||
|
||||
## A2
|
||||
|
||||
In progress. It does not pass, and there is no A2 test in the repository yet.
|
||||
The program is [`tests/compat_fixtures/gate_a2.c`](../../tests/compat_fixtures/gate_a2.c).
|
||||
Its build configuration and provenance are in
|
||||
[`tests/compat_fixtures/README.md`](../../tests/compat_fixtures/README.md#gate-a2-a-hosted-c-program).
|
||||
The gate is `crates/loader/tests/gate_a2.rs`:
|
||||
|
||||
The target is an original C program built with the mingw-w64 runtime (UCRT),
|
||||
whose own startup code runs before `main`. Such a program needs pieces that
|
||||
are being added one issue at a time. This page records only what is in the
|
||||
tree it is part of:
|
||||
```sh
|
||||
cargo test --locked -p xenora-loader --test gate_a2 -- --nocapture
|
||||
```
|
||||
|
||||
| Piece | State here |
|
||||
| --- | --- |
|
||||
| Normal exit: `exit` with its `atexit` functions, `_exit` and `abort` | Present (#395), on top of the process exit A1 added |
|
||||
| The PE headers mapped at the image base, which the startup code reads | Separate change (#333) |
|
||||
| `FNINIT`, the one instruction the startup code needs that was refused | Separate change (#378) |
|
||||
| The C runtime startup calls, and the functions a program imports but does not call | Separate changes (#382, #388) |
|
||||
| `argc`, `argv` and the environment table | Separate change (#392) |
|
||||
| Standard streams, files and formatted output | Not started |
|
||||
| The A2 program itself, its build and its test | Not started |
|
||||
"Hosted" means the program is linked with a real C runtime, whose own startup
|
||||
code runs before `main`. Here that runtime is mingw-w64's, in its UCRT
|
||||
flavour: the startup objects and a little of GCC's support library are linked
|
||||
into the executable, and the C library itself is imported by name from the
|
||||
Universal C Runtime's API-set DLLs and from `kernel32.dll`. Xenora's services
|
||||
answer those imports. Nothing from Windows is loaded.
|
||||
|
||||
Until the last two rows exist nothing here shows a hosted C program running,
|
||||
and A2 must not be reported as passing.
|
||||
The test builds the program from source with `x86_64-w64-mingw32-gcc`. It
|
||||
fails, and does not skip, when that compiler is missing. It then runs each
|
||||
build through `run_synthetic_startup` with `register_standard_services`,
|
||||
loaded away from its preferred base, with the command line
|
||||
`gate-a2.exe 2026 xenora` set through `ServicesState::set_program_arguments`.
|
||||
It checks, at `-O0`, `-O1`, `-O2` and `-Os`:
|
||||
|
||||
- every import is bound (50 at each level with the toolchain used locally; the test prints the count) and base relocations are applied;
|
||||
- the guest ends with `ExitReason::ProcessExit(0)`: `main` returned and the runtime's startup code passed its result to `exit`;
|
||||
- captured standard output equals, byte for byte, text recomputed in Rust from the description of the program, including the line a function registered with `atexit` prints after `main` has returned; standard error is empty;
|
||||
- the report file the program wrote with `fprintf` and `fputs` is on the in-memory drive with the recomputed contents, the file it looked for was not created, and no handle is left open;
|
||||
- it ran as translated code, with service calls.
|
||||
|
||||
The program checks its own results as well: it prints its arguments, fills
|
||||
heap memory from a small generator, sorts it with `qsort` and a callback,
|
||||
checksums it before and after, writes the report, reads it back with `fgets`,
|
||||
`strtoul` and `strtoull`, and confirms that a missing file is reported. It
|
||||
exits with the number of the first check that fails, and counts the checks
|
||||
that passed; a complete run counts 76.
|
||||
|
||||
Seven more tests guard against a runtime that reports success for everything:
|
||||
|
||||
- another seed and label give another output and another report;
|
||||
- four wrong command lines each fail the check that looks at them, with that check's number as the exit status and its message on standard error;
|
||||
- a variant with one wrong expectation exits with 22;
|
||||
- a variant that calls `exit(42)` half way ends with 42, its `atexit` function still runs, and the report is never written;
|
||||
- a variant that calls `abort()` half way ends with 3 and its `atexit` function does not run;
|
||||
- a step budget that is too small is not an exit;
|
||||
- the Rust restatement of the program is itself checked not to be degenerate.
|
||||
|
||||
### What A2 does not show
|
||||
|
||||
- It is one program and one C runtime: mingw-w64 14.0.0 with GCC 16.2.0 locally. A program built with Microsoft's compiler starts differently and imports other functions; none has been tried. A larger program can need instructions and services this one does not.
|
||||
- The same source built natively with Apple clang prints the same text once carriage returns are removed. That comparison was made by hand and is not part of the test. Nothing was compared with Windows or with x86 hardware.
|
||||
- No floating point is formatted and no input is read. `printf` refuses the floating-point and wide-character conversions, and `stdin` and the `scanf` family do not exist.
|
||||
- Most services the program calls are marked partial in the registry. No locale exists, no signal handler or exception filter is ever called, the environment table is empty, and a C stream is unbuffered and has no seek. They did what this program needs.
|
||||
- `VirtualProtect`, `VirtualQuery` and `__C_specific_handler` are stubs that stop the guest if called. The program imports them and never calls them.
|
||||
- It runs in the DBT only, on one guest thread.
|
||||
- It reaches the guest through a test, not through `xenora run`.
|
||||
- Nothing here concerns a commercial game or an Xbox launch environment.
|
||||
@@ -0,0 +1,96 @@
|
||||
# Migrated pull-request integration review
|
||||
|
||||
Reviewed on November 24, 2026 (America/Chicago). The initial inventory contained
|
||||
23 open pull requests under `Arths17`, including the development-plan PR.
|
||||
Twenty-two were merged after their updated heads passed the applicable GitHub
|
||||
checks. Imported records retain their original author attribution and commits.
|
||||
|
||||
The maintainer authorized per-merge admin overrides for the review restriction.
|
||||
The ARM64 build/test requirement, one-approval rule, code-owner review requirement
|
||||
and enforcement for admins remain configured. Failed or pending checks were
|
||||
resolved before merging. The conditional `verify` comment job is normally skipped;
|
||||
that skip is not independent semantic verification.
|
||||
|
||||
## Results
|
||||
|
||||
All links below refer to the BetterXen repository.
|
||||
|
||||
| PR | Result | Integration work |
|
||||
| --- | --- | --- |
|
||||
| [#263](https://github.com/MacosPorters/betterxen/pull/263) | Pending | Pending: overlaps the contributor's live PR #290, excluded by the maintainer. |
|
||||
| [#264](https://github.com/MacosPorters/betterxen/pull/264) | Merged; checks passed | Identification fixture runs in ordinary tests; benchmark-harness lint fixed. |
|
||||
| [#265](https://github.com/MacosPorters/betterxen/pull/265) | Merged; checks passed | Bounded native texture staging; planner and Metal readback tests. |
|
||||
| [#266](https://github.com/MacosPorters/betterxen/pull/266) | Merged; checks passed | Startup measurement harness; unit tests and correctness smoke run. |
|
||||
| [#267](https://github.com/MacosPorters/betterxen/pull/267) | Merged; checks passed | Bounded flat draws and repeated-frame regressions. |
|
||||
| [#268](https://github.com/MacosPorters/betterxen/pull/268) | Merged; checks passed | Windows x64 calling conventions; writable-home-slot regression and nonvolatile vector-register negative controls. |
|
||||
| [#269](https://github.com/MacosPorters/betterxen/pull/269) | Merged; checks passed | Executable generations with source revalidation; original cache assertions preserved. |
|
||||
| [#270](https://github.com/MacosPorters/betterxen/pull/270) | Merged; checks passed | ARM64 shift encoding and operand checks; draft marked ready. |
|
||||
| [#271](https://github.com/MacosPorters/betterxen/pull/271) | Merged; checks passed | Floating-point unit initialization, combined decoder generation and preserved tests. |
|
||||
| [#272](https://github.com/MacosPorters/betterxen/pull/272) | Merged; checks passed | Dynamic binary translation (DBT) report comparison and input validation. |
|
||||
| [#273](https://github.com/MacosPorters/betterxen/pull/273) | Merged; checks passed | C startup service integration and registry regeneration. |
|
||||
| [#274](https://github.com/MacosPorters/betterxen/pull/274) | Merged; checks passed | Instruction-length faults and precise retirement. |
|
||||
| [#275](https://github.com/MacosPorters/betterxen/pull/275) | Merged; checks passed | Flag-transfer instructions; combined fixtures and supported-case expectations retained. |
|
||||
| [#276](https://github.com/MacosPorters/betterxen/pull/276) | Merged; checks passed | Explicitly unsupported service stubs and combined registry. |
|
||||
| [#277](https://github.com/MacosPorters/betterxen/pull/277) | Merged; checks passed | Guest arguments and environment with combined services. |
|
||||
| [#278](https://github.com/MacosPorters/betterxen/pull/278) | Merged; checks passed | Packed texture footprints; CPU and native GPU checks. |
|
||||
| [#279](https://github.com/MacosPorters/betterxen/pull/279) | Merged; checks passed | Loop instructions; regenerated tables and corrected description to 3,600 comparisons. |
|
||||
| [#280](https://github.com/MacosPorters/betterxen/pull/280) | Merged; checks passed | Process termination and exit callbacks. |
|
||||
| [#281](https://github.com/MacosPorters/betterxen/pull/281) | Merged; checks passed | Formatted output integrated with startup and arguments. |
|
||||
| [#282](https://github.com/MacosPorters/betterxen/pull/282) | Merged; checks passed | File streams; combined registry and dependency readiness. |
|
||||
| [#283](https://github.com/MacosPorters/betterxen/pull/283) | Merged; checks passed | Hosted C fixture; driver architecture checked before execution. |
|
||||
| [#284](https://github.com/MacosPorters/betterxen/pull/284) | Merged; checks passed | Thread-local storage (TLS) template-copy integration and preserved changelog entries. |
|
||||
| [#288](https://github.com/MacosPorters/betterxen/pull/288) | Merged; checks passed | Development phases, README and migration-check record. |
|
||||
|
||||
PR #263 remains open to avoid competing with the contributor's live PR #290.
|
||||
PR #290 was excluded from branch edits, reviews and merge operations as requested.
|
||||
Its filesystem security and integration acceptance are left to that workstream.
|
||||
|
||||
## Verification and evidence scope
|
||||
|
||||
The integrated runtime candidate was
|
||||
`5366b9398668128fdbb0b0879840dfa072bfa352`. Its GitHub native Rust workflow passed,
|
||||
including workspace formatting, strict Clippy, tests and the hosted C fixture.
|
||||
Local native results below concern the reported Apple M4 host running macOS 27.0
|
||||
(class A host observations); they establish no Xbox-hardware or commercial-game
|
||||
execution result.
|
||||
|
||||
| Check | Observed result |
|
||||
| --- | --- |
|
||||
| `scripts/test-gpu.sh` | 124 passed, 0 failed; 2 manual timing tests ignored. Metal API and GPU validation enabled. |
|
||||
| Packed block-compressed texture GPU target | 1 passed, 0 failed, 0 ignored, with both validation layers enabled. |
|
||||
| `scripts/demo.sh` | All three original fixtures matched Metal, reference and known-answer outputs. |
|
||||
| `scripts/audit/native.sh` | 110 executables/loadable dependencies checked with `file`, `lipo` and `otool`; ARM64 architecture and permitted linkage checks passed. |
|
||||
| Status, claims and dependency audits | Passed. |
|
||||
|
||||
The cache fix also passed an isolated local workspace run at `44ac976`: 917
|
||||
passed, 0 failed, 35 ignored, plus strict Clippy. Its three alternating CPU
|
||||
benchmark pairs used native release executables and identical original inputs:
|
||||
per-run warm medians were 87.334–88.333 microseconds with per-byte validation and
|
||||
15.625–18.791 microseconds with generation validation. Machine idleness was not
|
||||
controlled. These measurements do not close the formal performance gate; their
|
||||
candidate scope and cold results are recorded in PR #269.
|
||||
|
||||
A supplemental benchmark test-harness command exposed a missing initialization
|
||||
for the newly added cache-invalidation counter. The follow-up initializes that
|
||||
fixture and runs the existing report, JSON, comparison and percentile tests via
|
||||
an ordinary integration-test target, preserving their assertions. This lets
|
||||
workspace CI detect future benchmark-test compilation failures. All 14 existing
|
||||
tests passed through both the ordinary integration target and the documented
|
||||
manual harness command; strict workspace Clippy passed as well.
|
||||
|
||||
Raw final native logs, cache benchmark JSON and the PR-state inventory are kept
|
||||
under ignored `artifacts/pr-integration/` in the lead checkout. PR checks and merge
|
||||
records remain linked from each GitHub record.
|
||||
|
||||
## Remaining acceptance
|
||||
|
||||
This is an integration and execution record. Independent semantic and security
|
||||
acceptance remains separate from implementer-run checks and administrative merge
|
||||
permission. No release gates were redefined or releases created. Commercial Xbox
|
||||
game execution remains unsupported.
|
||||
|
||||
Active-block self-modifying code is tracked separately in
|
||||
[issue #291](https://github.com/MacosPorters/betterxen/issues/291); native-code cache
|
||||
reclamation remains [issue #95](https://github.com/MacosPorters/betterxen/issues/95).
|
||||
The source fixture programs, desktop instruction evidence and native Mac results
|
||||
retain their existing boundaries.
|
||||
@@ -110,3 +110,54 @@ Provenance. The source, the name lists and the script were written for BetterXen
|
||||
and are GPL-3.0-or-later. Nothing from a Windows SDK, a C runtime or another
|
||||
project is compiled or linked. The compiler and linker are LLVM projects
|
||||
under the Apache License 2.0 with LLVM exceptions; they are tools, not inputs.
|
||||
|
||||
## Gate A2: a hosted C program
|
||||
|
||||
`gate_a2.c` is an original C program that uses the standard C library as an
|
||||
ordinary program does. It includes only `<stdio.h>`, `<stdlib.h>` and
|
||||
`<string.h>`. It prints its arguments, fills heap memory from a small
|
||||
generator, sorts it with `qsort` and a callback, checksums it, writes a
|
||||
report with `fprintf` and `fputs`, reads it back with `fgets`, `strtoul` and
|
||||
`strtoull`, confirms that a missing file is reported, registers a function
|
||||
with `atexit`, and returns from `main`. It checks every result itself and
|
||||
exits with the number of the first check that fails. It uses no floating
|
||||
point and reads no input.
|
||||
|
||||
`build-gate-a2.sh [output directory]` builds it. `cargo test -p xenora-loader
|
||||
--test gate_a2` runs that script and then runs the result through
|
||||
`run_synthetic_startup`, the standard services and the DBT. No built
|
||||
executable is committed: the test builds from source every time, in CI too.
|
||||
The test fails, and does not skip, when the compiler is missing.
|
||||
|
||||
Compiler configuration:
|
||||
|
||||
| Step | Command |
|
||||
| --- | --- |
|
||||
| Compile and link | `x86_64-w64-mingw32-gcc -O<level> -Wall -Wextra -Werror -o <name>.exe gate_a2.c` |
|
||||
|
||||
It is built at `-O0`, `-O1`, `-O2` and `-Os`, and three more times at `-O1` as
|
||||
controls: `GATE_BREAK` (one wrong expectation), `GATE_EXIT` (`exit(42)` half
|
||||
way) and `GATE_ABORT` (`abort()` half way).
|
||||
|
||||
Tools. `MINGW_GCC` defaults to Homebrew's mingw-w64 when it is installed and
|
||||
otherwise to the `x86_64-w64-mingw32-gcc` on `PATH`. The toolchain must use
|
||||
the Universal C Runtime, which Homebrew's does; a toolchain built for the
|
||||
older `msvcrt.dll` produces a program that imports other functions. On macOS
|
||||
the script requires the compiler driver, the compiler proper, the assembler
|
||||
and the linker, and every library they load that is a file on disk, to be
|
||||
ARM64: it checks each with `file` and `lipo -archs`, and each library
|
||||
`otool -L` lists with `lipo -archs`. It writes the compiler version to
|
||||
`toolchain.txt`, which the test prints, and what the native checks looked at
|
||||
to `toolchain-native.txt`. The test builds into a directory of its own for
|
||||
each test process under the Cargo target directory.
|
||||
|
||||
Provenance. The source and the script were written for Xenora and are
|
||||
GPL-3.0-or-later. Unlike the Gate A1 program, each built executable contains
|
||||
code that is not Xenora's: mingw-w64's startup objects and a little of GCC's
|
||||
support library, as any program built with that toolchain does. Neither is
|
||||
stored in the repository or in its history; the executables are test output.
|
||||
mingw-w64's `COPYING` file says its runtime is under the Zope Public License
|
||||
2.1 except for parts marked as public domain, BSD or LGPL; GCC's support
|
||||
library is GPL-3.0-or-later with the GCC Runtime Library Exception. The C
|
||||
library itself is not linked: the program imports it by name, and Xenora's
|
||||
own services answer.
|
||||
Executable
+96
@@ -0,0 +1,96 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#
|
||||
# Build the Gate A2 program, tests/compat_fixtures/gate_a2.c, as x86-64 PE32+
|
||||
# executables linked with the mingw-w64 C runtime (UCRT flavour). The
|
||||
# runtime's own startup code runs before main, which is what makes the program
|
||||
# "hosted".
|
||||
#
|
||||
# build-gate-a2.sh [output directory] default: artifacts/gate-a2
|
||||
#
|
||||
# Tool, native to the host:
|
||||
# MINGW_GCC an x86_64-w64-mingw32-gcc. Default: Homebrew mingw-w64 if
|
||||
# installed, otherwise the one on PATH.
|
||||
#
|
||||
# Nothing from mingw-w64 is stored in the repository. Each built executable
|
||||
# contains that project's startup objects and a little of GCC's support
|
||||
# library, as any program built with it does; the executables are test
|
||||
# output and are not committed.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/../.."
|
||||
root=$PWD
|
||||
src="$root/tests/compat_fixtures/gate_a2.c"
|
||||
out=${1:-"$root/artifacts/gate-a2"}
|
||||
|
||||
gcc=${MINGW_GCC:-}
|
||||
if [ -z "$gcc" ]; then
|
||||
gcc=/opt/homebrew/opt/mingw-w64/bin/x86_64-w64-mingw32-gcc
|
||||
[ -x "$gcc" ] || gcc=$(command -v x86_64-w64-mingw32-gcc || true)
|
||||
fi
|
||||
if [ -z "$gcc" ] || [ ! -x "$gcc" ]; then
|
||||
echo "missing tool: x86_64-w64-mingw32-gcc (set MINGW_GCC, or install mingw-w64)" >&2
|
||||
exit 1
|
||||
fi
|
||||
# AGENTS.md: host tools must be ARM64, checked with file, lipo -archs and
|
||||
# otool -L. The driver is a symbolic link into the toolchain; the compiler
|
||||
# proper, the assembler and the linker it runs are checked as well.
|
||||
native=
|
||||
check_native_tool() {
|
||||
tool=$1
|
||||
case "$(file -bL "$tool")" in
|
||||
*arm64*) ;;
|
||||
*) echo "ARM64 tool required (file): $tool" >&2; exit 1 ;;
|
||||
esac
|
||||
case "$(lipo -archs "$tool")" in
|
||||
*arm64*) ;;
|
||||
*) echo "ARM64 tool required (lipo): $tool" >&2; exit 1 ;;
|
||||
esac
|
||||
for library in $(otool -L "$tool" | awk 'NR > 1 { print $1 }'); do
|
||||
[ -f "$library" ] || continue
|
||||
case "$(lipo -archs "$library")" in
|
||||
*arm64*) ;;
|
||||
*) echo "ARM64 library required by $tool: $library" >&2; exit 1 ;;
|
||||
esac
|
||||
native="$native $library: $(lipo -archs "$library")
|
||||
"
|
||||
done
|
||||
native="$native$tool: $(file -bL "$tool")
|
||||
"
|
||||
}
|
||||
if [ "$(uname -s)" = Darwin ]; then
|
||||
# Check the driver before asking it about helpers: even -print-prog-name
|
||||
# executes the binary and must never start an Intel-only compiler.
|
||||
check_native_tool "$gcc"
|
||||
for helper in cc1 as ld collect2; do
|
||||
path=$("$gcc" -print-prog-name="$helper")
|
||||
case "$path" in
|
||||
/*) ;;
|
||||
*) path=$(command -v "$path" || true) ;;
|
||||
esac
|
||||
if [ -z "$path" ] || [ ! -x "$path" ]; then
|
||||
echo "missing compiler helper: $helper" >&2
|
||||
exit 1
|
||||
fi
|
||||
check_native_tool "$path"
|
||||
done
|
||||
fi
|
||||
|
||||
mkdir -p "$out"
|
||||
cd "$out"
|
||||
{
|
||||
"$gcc" --version | head -1
|
||||
printf 'target: %s\n' "$("$gcc" -dumpmachine)"
|
||||
} > toolchain.txt
|
||||
printf '%s' "$native" > toolchain-native.txt
|
||||
|
||||
# name, optimization level, extra definition
|
||||
build() {
|
||||
"$gcc" "-$2" -Wall -Wextra -Werror ${3:+"-D$3"} -o "$1.exe" "$src"
|
||||
}
|
||||
for level in O0 O1 O2 Os; do
|
||||
build "gate-a2-$level" "$level" ""
|
||||
done
|
||||
# Controls: a wrong expectation, exit() half way, abort() half way.
|
||||
build gate-a2-break O1 GATE_BREAK
|
||||
build gate-a2-exit O1 GATE_EXIT
|
||||
build gate-a2-abort O1 GATE_ABORT
|
||||
@@ -0,0 +1,157 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later */
|
||||
|
||||
/*
|
||||
* Gate A2 (issue #419): a hosted C program. Original code written for Xenora.
|
||||
*
|
||||
* It is built with a real C runtime's startup code, which runs before main,
|
||||
* and uses the standard C library the way an ordinary program does:
|
||||
* command-line arguments, heap memory, sorting with a callback, formatted
|
||||
* output, a file written and read back, a function registered with atexit,
|
||||
* and a normal return from main.
|
||||
*
|
||||
* Every result is checked by the program itself. The exit status is 0 when
|
||||
* every check passed and otherwise names the first one that failed, so a
|
||||
* runtime that computes something wrongly cannot report success.
|
||||
*
|
||||
* It needs no floating point and no input.
|
||||
*
|
||||
* Control variants, selected at build time, each end in a different way so
|
||||
* that the test can tell a real pass from a runtime that reports success for
|
||||
* everything:
|
||||
* GATE_BREAK expects a wrong total, so check 22 fails
|
||||
* GATE_EXIT calls exit(42) half way, without returning from main
|
||||
* GATE_ABORT calls abort() half way
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define COUNT 48
|
||||
|
||||
static unsigned checks_passed;
|
||||
static const char *report_name = "gate-a2-report.txt";
|
||||
|
||||
static void say_goodbye(void) {
|
||||
/* Runs from exit, after main has returned. */
|
||||
printf("atexit: %u checks passed\n", checks_passed);
|
||||
}
|
||||
|
||||
static int by_value(const void *left, const void *right) {
|
||||
unsigned a = *(const unsigned *)left, b = *(const unsigned *)right;
|
||||
return (a > b) - (a < b);
|
||||
}
|
||||
|
||||
/* A linear congruential generator, so the data does not depend on a library. */
|
||||
static unsigned next_value(unsigned *state) {
|
||||
*state = *state * 1103515245u + 12345u;
|
||||
return (*state >> 8) & 0xffffu;
|
||||
}
|
||||
|
||||
static unsigned long long checksum(const unsigned *values, size_t count) {
|
||||
unsigned long long sum = 14695981039346656037ull; /* FNV-1a, 64-bit */
|
||||
for (size_t i = 0; i < count; i++) {
|
||||
for (int shift = 0; shift < 32; shift += 8) {
|
||||
sum ^= (values[i] >> shift) & 0xffu;
|
||||
sum *= 1099511628211ull;
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
#define CHECK(code, condition) \
|
||||
do { \
|
||||
if (!(condition)) { \
|
||||
fprintf(stderr, "gate a2: check %d failed\n", (code)); \
|
||||
return (code); \
|
||||
} \
|
||||
checks_passed++; \
|
||||
} while (0)
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
CHECK(10, atexit(say_goodbye) == 0);
|
||||
|
||||
/* Arguments: a program name, a seed and a label. */
|
||||
printf("gate a2: %d arguments\n", argc);
|
||||
for (int i = 0; i < argc; i++) printf(" argv[%d] = \"%s\"\n", i, argv[i]);
|
||||
CHECK(11, argc == 3);
|
||||
CHECK(12, argv[argc] == NULL);
|
||||
char *end = NULL;
|
||||
unsigned long seed = strtoul(argv[1], &end, 10);
|
||||
CHECK(13, end != argv[1] && *end == '\0');
|
||||
const char *label = argv[2];
|
||||
CHECK(14, strlen(label) > 0 && strlen(label) < 32);
|
||||
|
||||
/* Heap memory, filled, sorted through a callback and verified. */
|
||||
unsigned *values = malloc(COUNT * sizeof *values);
|
||||
CHECK(20, values != NULL);
|
||||
unsigned state = (unsigned)seed;
|
||||
unsigned long long total = 0;
|
||||
for (size_t i = 0; i < COUNT; i++) {
|
||||
values[i] = next_value(&state);
|
||||
total += values[i];
|
||||
}
|
||||
unsigned long long before = checksum(values, COUNT);
|
||||
qsort(values, COUNT, sizeof *values, by_value);
|
||||
unsigned long long sorted_total = 0;
|
||||
for (size_t i = 0; i < COUNT; i++) {
|
||||
if (i > 0) CHECK(21, values[i - 1] <= values[i]);
|
||||
sorted_total += values[i];
|
||||
}
|
||||
#ifdef GATE_BREAK
|
||||
CHECK(22, sorted_total == total + 1);
|
||||
#else
|
||||
CHECK(22, sorted_total == total);
|
||||
#endif
|
||||
unsigned long long after = checksum(values, COUNT);
|
||||
printf("sorted %d values: min %u, max %u, total %llu\n",
|
||||
COUNT, values[0], values[COUNT - 1], total);
|
||||
printf("checksum before %016llx, after %016llx\n", before, after);
|
||||
|
||||
#ifdef GATE_EXIT
|
||||
/* The registered function still runs, and nothing after this does. */
|
||||
exit(42);
|
||||
#endif
|
||||
#ifdef GATE_ABORT
|
||||
/* Nothing registered runs, and the status is abort's. */
|
||||
abort();
|
||||
#endif
|
||||
|
||||
/* A file written with formatted output. */
|
||||
FILE *report = fopen(report_name, "w");
|
||||
if (report == NULL) {
|
||||
perror(report_name);
|
||||
return 30;
|
||||
}
|
||||
checks_passed++;
|
||||
CHECK(31, fprintf(report, "label %s\n", label) > 0);
|
||||
CHECK(32, fprintf(report, "total %llu\n", total) > 0);
|
||||
CHECK(33, fprintf(report, "range %u %u\n", values[0], values[COUNT - 1]) > 0);
|
||||
CHECK(34, fputs("end\n", report) >= 0);
|
||||
CHECK(35, fclose(report) == 0);
|
||||
|
||||
/* The same file read back line by line and compared. */
|
||||
report = fopen(report_name, "r");
|
||||
CHECK(40, report != NULL);
|
||||
char line[96];
|
||||
CHECK(41, fgets(line, sizeof line, report) != NULL);
|
||||
CHECK(42, strncmp(line, "label ", 6) == 0);
|
||||
CHECK(43, strlen(line) == 6 + strlen(label) + 1);
|
||||
CHECK(44, strncmp(line + 6, label, strlen(label)) == 0 && line[strlen(line) - 1] == '\n');
|
||||
CHECK(45, fgets(line, sizeof line, report) != NULL);
|
||||
CHECK(46, strncmp(line, "total ", 6) == 0);
|
||||
CHECK(47, strtoull(line + 6, &end, 10) == total && *end == '\n');
|
||||
CHECK(48, fgets(line, sizeof line, report) != NULL);
|
||||
CHECK(49, strncmp(line, "range ", 6) == 0);
|
||||
CHECK(50, strtoul(line + 6, &end, 10) == values[0] && *end == ' ');
|
||||
CHECK(51, strtoul(end, &end, 10) == values[COUNT - 1] && *end == '\n');
|
||||
CHECK(52, fgets(line, sizeof line, report) != NULL && strcmp(line, "end\n") == 0);
|
||||
CHECK(53, fgets(line, sizeof line, report) == NULL);
|
||||
CHECK(54, fclose(report) == 0);
|
||||
|
||||
/* A file that does not exist is reported, not opened. */
|
||||
CHECK(60, fopen("gate-a2-missing.txt", "r") == NULL);
|
||||
|
||||
free(values);
|
||||
printf("report %s read back and verified\n", report_name);
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user