Compare commits

...
Author SHA1 Message Date
ates cd72ef8ec3 [M2-E3] gameinput: implement device-callback lifecycle and SetFocusPolicy (#481)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 23:47:28 +03:00
Ateş 52e786664d Merge pull request #476 from jelly013/track-d/445-guest-shader-bridge
[M2-D] dxbc-accc: reach Windows guests as bx_shader_bridge.dll (#445)
2026-11-26 23:40:30 +03:00
Ateş b22ec27c79 Merge pull request #477 from sahib453/track-a/474-staging-ownership
[Track A] Keep system32 shim staging from overwriting files it did not create (#474)
2026-11-26 23:39:16 +03:00
sahib453 0749dcf236 Address review: stub visibility, link entries, partial staging
A bottle that launched from a different prefix fails the run only when
the staged shims cannot be found with the same contents there; a
private stub linking back to the managed prefix is accepted. The
destination entry is inspected without following links, so a dangling
symbolic link is a foreign entry and is left alone. New files are
installed without replacing anything. Temporary copies are all written
first and each installed file is recorded in the manifest before the
next, so a later failure leaves earlier files owned.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 02:06:27 +05:30
jelly013 238daa6b25 dxbc-accc: tighten the guest build and check from review
guest/build.sh:
- Always build into, and copy from, <repo>/target, whatever
  CARGO_TARGET_DIR says, so a stale DLL can no longer be packaged.
- Resolve cargo and rustc through rustup, check that this rustc has std
  for x86_64-pc-windows-gnu, and print which rustc was used.
- Check the whole Export Address Table the way build-shims.sh does:
  every populated entry must be a direct RVA owned by one of the three
  names, so an ordinal-only extra or a forwarder fails. Imports must be
  Wine-provided system DLLs from an allowlist.

guest/check_bridge.c:
- Load the DLL by full path from the EXE's own directory.
- Check the exact DXIL and ACCC chunk sizes and the root signature
  flag, derived from the program's own chunk-table walk, and the
  digest against header bytes 4..20 for every container.
- Add a container with trailing bytes, checking that only the declared
  container is reported and copied.

The README documents how a calling shim must locate the bridge: by
full path from its own directory, not by bare name. It also records
that CI does not build the bridge yet.

Refs #445

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 21:27:51 +01:00
jelly013 7815a947e5 Merge remote-tracking branch 'upstream/main' into track-d/445-guest-shader-bridge
Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 21:27:01 +01:00
Jelly 99bfbc26ef [M2-E2] Offline XGameSave and XPackage through QueryApiImpl (#472)
QueryApiImpl now serves offline XGameSave and XPackage as COM IUnknown
objects under BetterXen synthetic keys (shims/xgameruntime/synthetic_keys.h),
backed by bottle-local storage. Public Microsoft.GDK.Windows com_dispatch.cpp
wiring remains tracked in #468.

- XGameSave: provider init, containers, updates, blob writes, async submit
  and read, enumeration, and parent-child handle cascade close. Saves are
  isolated per SCID under C:\bx_pls\<exe_hash>\saves\<scid_hash>\ with
  atomic temp-file + MoveFileExW replacement, cross-process named mutex
  serialization, FILE_SHARE_DELETE readers, strict BXGS format validation,
  256-byte blob-name limits counted toward the 16 MiB update cap, and
  E_GS_OUT_OF_LOCAL_STORAGE mapping.
- XPackage: treats the running executable's directory as the installed
  package (BXPKG<16 hex> identifier, XPackageKind::Game, and mount queries).
- Lifetimes & XAsync: generic AsyncOp support with runtime generation guard
  before execute(), disjoint handle tag ranges, and full handle/result
  cleanup on final XGameRuntimeUninitialize.
- Tests: tests/conformance/test_xgameruntime_saves covering round-trip,
  SCID isolation, crafted corrupt files, atomic replace, 64 threaded +
  160 cross-process submits, uninitialize memory release, and UTF-8 paths.

Refs #468

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 23:21:19 +03:00
sahib453 1ec92916b9 Keep system32 shim staging from overwriting files it did not create
Fixes the three points of #474 in bx-cli run. Staging records what it
wrote in a .bx-staged manifest (one SHA-256 per file) and replaces only
files listed there and unchanged since; any other same-named file stops
the run before anything is written. For a named bottle the prefix is
re-resolved after the run and a launch in a different prefix is
reported and fails the run. When initialization uses the whole
--timeout the guest is not started. Adds 9 unit tests.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 01:19:53 +05:30
jelly013 9d504d12d7 dxbc-accc: reach Windows guests as bx_shader_bridge.dll
Shims that see shader bytecode run as x86-64 PE32+ DLLs inside
CrossOver and cannot load the arm64 host library. Build this same crate
for x86_64-pc-windows-gnu instead: its cdylib becomes
bx_shader_bridge.dll, exporting exactly the three bx_shader_bridge.h
entry points, with no MinGW runtime DLL dependency. There is no second
implementation to keep in sync.

guest/build.sh builds the DLL, checks its exports and imports, and
builds check_bridge.exe, a C guest program compiled against the frozen
header. It sends a real DXC SM 6.6 blob and seven synthetic containers
through the DLL, checks classification, prepare and free, and prints a
DXIL vs. ACCC count. It passes under CrossOver 26.3 in a prefix and a
D3DMetal bottle.

The abi/defs export list, staging in build-shims and the d3d12_xs PSO
hook (#466) are separate changes.

Closes #445

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 20:43:56 +01:00
Ateş f7fb52bc56 Merge pull request #455 from Scarlet-Noble/track-f/453-d3dmetal-gpu-limits
[M2-F] D3DMetal GPU limits research and test_d3dmetal_gpu_limits fixture (#453)
2026-11-26 22:22:22 +03:00
atharvranjan ec2170d480 Merge main into track-f/453-d3dmetal-gpu-limits
Bring in main at cc5ce59 and resolve three documentation conflicts:

- CHANGELOG.md: keep the #453 entry above the entries added on main.
- docs/README.md: keep both new research links (swapchain references
  and D3DMetal GPU limits).
- docs/roadmap.md: take main's milestone table, including the verified
  M0/M1 status and the expanded M2 row, and append only the two
  measured-constraint links from this branch to the M2 and M3 rows.

No source, shader, header or research-note content changes relative to
either parent.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 13:16:44 -06:00
Ateş cc5ce59d21 Merge pull request #463 from MacosPorters/track-f/m2-docs-sync
[M2-F] Update README and roadmap for M1 completion and M2 kickoff
2026-11-26 21:35:40 +03:00
ates 61fc3590b2 Merge remote-tracking branch 'origin/main' into track-f/m2-docs-sync
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 21:34:31 +03:00
Ateş 58fc63c7ec Merge pull request #462 from MacosPorters/track-e/456-query-api-impl-dispatch
[M2-E] Public GDK COM QueryApiImpl dispatch in xgameruntime.dll (#456)
2026-11-26 21:33:40 +03:00
ates 600a0ab08f Merge remote-tracking branch 'origin/main' into track-f/m2-docs-sync
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 21:31:51 +03:00
ates cda66a57f2 Merge remote-tracking branch 'origin/main' into track-e/456-query-api-impl-dispatch
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 21:31:48 +03:00
ates a5c1995f21 Link Wave 2 M2 issues (#464-#469) in README progress board
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 21:25:25 +03:00
atharvranjan 868444ed30 Merge pull request #458 from Scarlet-Noble/track-a/457-system32-staging
[M1-A] Stage xgameruntime.dll and its shim imports into system32 (#457)
2026-11-26 12:22:56 -06:00
atharvranjan 510b6d1d66 Supervise wineboot and tolerate partial shim folders in system32 staging (#457)
A --shims folder without xgameruntime.dll made every bx-cli run fail; it is now reported and skipped.

wineboot --init ran before the signal handlers and outside --timeout, so Ctrl-C during a first run left wineserver and its services running. It now runs under the supervisor and shares the --timeout budget.

The temporary staging file name is now per process, so concurrent runs cannot publish each other's partial write.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 12:22:42 -06:00
ates 92c2ff7add Update README and roadmap for M1 completion and M2 kickoff
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 21:19:26 +03:00
ates 39baf092a3 Wire offline IXUser change-event and query slots in com_dispatch
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 21:17:41 +03:00
ates 0a30562cde Implement public GDK COM QueryApiImpl dispatch in xgameruntime.dll (#456)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 21:15:21 +03:00
Vicente Abarca fb56805459 Stage xgameruntime.dll and its shim imports into system32 (#457)
GDK titles load the runtime with LoadLibraryExW(L"xgameruntime.dll",
NULL, LOAD_LIBRARY_SEARCH_SYSTEM32), which never searches WINEPATH, so
the bootstrap failed with E_GAMERUNTIME_DLL_NOT_FOUND before the #441
loader exports were reached.

bx-cli run now copies xgameruntime.dll into the environment's
drive_c/windows/system32 before launch. It also copies every BetterXen
shim that DLL imports, found with bx-probe (today bx_runtime_veh.dll),
because the restricted search also applies to a DLL's own imports.
Copies are idempotent and replaced through a rename, and bx-cli prints
what it staged. A bare --prefix with no system32 is initialized with
wineboot --init under the same isolated environment. A bottle with no
system32 fails with a hint.

Adds 8 unit tests for staging and the dependency walk, and
tests/conformance/test_system32_staging with a --expect-missing
negative control.

Signed-off-by: Vicente Abarca <135478656+Scarlet-Noble@users.noreply.github.com>
2026-11-26 15:00:38 -03:00
Vicente Abarca 1eb963d883 Address review of test_d3dmetal_gpu_limits and its note (#453)
Fixture:
- check_lock64 keeps its upload buffer alive until the list that copies
  from it has run.
- The spin lock takes an acquire DeviceMemoryBarrier after winning the
  lock, before reading the data, as well as the release barrier.
- A check that fails partway through recording closes and resets the
  list (abandon) instead of leaving stale commands for the next check.
- wave.control checks what D3D12 guarantees: one wave width for every
  thread, and lane indices forming a permutation within each wave, with
  waves identified by WaveReadLaneFirst(id.x). It no longer assumes
  lane == i % width.
- Skips with exit 77 when shader model 6.6 is unavailable or the query
  fails.
- submit checks Signal, SetEventOnCompletion and the Reset calls.
  Resources the GPU may still use are leaked rather than released after
  a hung or removed queue.

Note: the measured constraints are separated from the reports taken
from a commercial title. The reports move to an "Unverified reports
(not evidence)" section, each with the synthetic workload that would
verify it. The M2-gate inference is dropped, and the roadmap rows link
only the measured section. The results are re-measured after the fixes:
with the acquire fence, the 64-try cap drops 96-108 of 512 updates. The
1024-try cap is still exact.

Signed-off-by: Vicente Abarca <135478656+Scarlet-Noble@users.noreply.github.com>
2026-11-26 14:53:44 -03:00
Ateş ac0fd2e502 Merge pull request #454 from MacosPorters/track-a/408-bx-cli-supervision
[M1-A1] Supervised timeout, cleanup and trace summary for bx-cli run
2026-11-26 20:45:44 +03:00
ates 73c190d725 Merge remote-tracking branch 'origin/main' into HEAD
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 20:43:46 +03:00
ates f3c2b7fe34 Re-resolve bottle prefix on timeout/signal cleanup for managed first-launch stubs
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 20:43:20 +03:00
Ateş 4333a7cc5e Merge pull request #452 from skakwy/track-a/437-api-set-shims
Add API-set resolution fixture and ADR 0007 (#437)
2026-11-26 20:42:35 +03:00
ates 66e9351410 Require valid module lookups in test_apiset_resolution and accept ADR 0007
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 20:42:05 +03:00
Ateş 060083cc56 Merge pull request #441 from devil8blade/track-e/439-xgameruntime-dynamic-api-impl
[M1-E3][ABI] Dynamic GDK loader exports in xgameruntime.dll
2026-11-26 20:36:09 +03:00
Vicente Abarca 120a5ec5f6 Document D3DMetal GPU limits and add test_d3dmetal_gpu_limits (#453)
Adds docs/research/d3dmetal-gpu-limits.md: the D3DMetal and Apple GPU
constraints a shader translator has to handle (wave64 splitting, 64-bit
atomics and lock emulation, the 32 KiB mesh output limit, an Apple
shader compiler crash on early-merged output stores, and
OpenExistingHeapFromAddress). Each item is marked as either measured by
the new fixture or reported from local builds of a commercial title. It
is linked from the M2 and M3 roadmap rows and from the docs index.

Adds tests/conformance/test_d3dmetal_gpu_limits: an original D3D12
compute fixture that talks to the host d3d12.dll directly. It has four
original HLSL kernels with committed DXC 1.9.2609 output, and
shaders/compile.sh regenerates them. Expected values are computed on
the CPU.

On an Apple M3 Pro (macOS 27.2.1, CodeWeavers Wine 11.0 built from
source, D3DMetal 4.0b3) the WaveSize(64) pipeline and the kernels using
SM 6.6 64-bit atomics are created but never run. The bounded lock
emulation is exact at a 1024-try cap and drops updates at 64 tries.

Signed-off-by: Vicente Abarca <135478656+Scarlet-Noble@users.noreply.github.com>
2026-11-26 14:32:09 -03:00
atharvranjan 7d7249ee8b Clean up the bottle CrossOver actually launches; limit --backend to bottles
- Locate --bottle through CrossOver's CXBottle module with the launch's
  environment, so CX_BOTTLE_PATH, configured paths and managed bottles are
  stopped correctly. Refuse to launch if it cannot be located.
- Require --bottle for --backend: a bare prefix loads Wine's own D3D12.

Both reproduced by atesahmet0 on #454.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 11:19:36 -06:00
atharvranjan d0395a61da Add supervised timeout and cleanup to bx-cli run (#408)
- --timeout, and cleanup on timeout, SIGINT, SIGTERM or SIGHUP: stop the
  launcher process group, then wineserver for the selected bottle or prefix.
  wineserver -k exit 1 (nothing running) is accepted only if -w succeeds.
- Pass shim overrides with bin/wine --dll and --backend with --env in bottle
  mode, because bin/wine discards WINEDLLOVERRIDES and applies bottle
  settings over the environment. First found by jelly013.
- Print the trace summary after a run with --log.
- Record the libc dependency and a one-host D3D12 swapchain observation.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 11:01:28 -06:00
skakwyandClaude Sonnet 5.5 2eb59e033b Add API-set resolution fixture and ADR 0007 (#437)
test_apiset_resolution imports one export from each of the six win32_bridge
API-set DLLs through the PE import directory and reports, per name, whether a
BetterXen shim file or a host module serves it, and which module the import
address table slot is bound to. --expect host (default) or --expect shim
selects the outcome that passes.

On CrossOver 26.0 all six names are served by the host (twinapi.appcore.dll
for PSM, user32.dll for ntuser) and +loaddll shows no Loaded record for any
shim file. ADR 0007 proposes relying on Wine's built-ins and records that
evidence; a CrossOver 26.3 re-run is still needed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: skakwy <nils_0805@icloud.com>
2026-11-26 17:53:14 +01:00
Ateş eec56dd028 Merge pull request #448 from MacosPorters/track-f/446-boot-texture-computer
[M1-F2] Exercise the texture computer in test_integration_boot
2026-11-26 19:27:14 +03:00
devil8blade e7899574ab Keep XErrorReport logs valid UTF-8 and record loader provenance
Invalid bytes are written as \u00XX and a multi-byte character is not
split when the detail buffer fills. The six loader prototypes are
recorded as BetterXen-defined. The two changelog notes are one entry.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 16:25:51 +00:00
atharvranjan 486f7b197f Check full footprints and keep one Fixed changelog section
Also verify footprint format, width, height and depth, call Release through
the computer's own vtable, and state the release check precisely.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 10:11:04 -06:00
atharvranjan 390e85fc8d Exercise the texture computer in test_integration_boot
The fixture passed a null descriptor to XGCreateTextureComputer and reported
the stage as pending, although #415 implemented it. Create a 100x50 two-mip
RGBA8 computer, check its layout against hand-computed values, require the
suggested layout to be linear and require release to free the object.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 10:09:10 -06:00
devil8blade 18178da12c Address review: surface unsupported QueryApiImpl in trace, null out on failure
Unsupported and mismatched QueryApiImpl queries keep their structured log
and also call BX_STUB_LOG so bx-cli trace lists them. Failure paths clear
the output pointer. XErrorReport uses the public void signature.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 16:05:11 +00:00
Ateş bfa80dee8b Merge pull request #440 from MacosPorters/track-a/438-trace-summary
Report sampled CLWB bounds and guest crashes in bx-cli trace
2026-11-26 18:47:38 +03:00
ates 829a94fa2f bx-cli: print clwb VEH traps : 0 when no CLWB records exist
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 18:47:28 +03:00
devil8blade 2e895e0f9b Export GDK dynamic loader entry points from xgameruntime.dll
The static loader resolves InitializeApiImpl, InitializeApiImplEx,
InitializeApiImplEx2, UninitializeApiImpl, QueryApiImpl, and XErrorReport
with GetProcAddress. Those initialize entry points share the existing
runtime refcount with XGameRuntimeInitialize and
XGameRuntimeInitializeWithOptions. UninitializeApiImpl releases that same
state. QueryApiImpl dispatches the offline families this DLL already
implements and logs any other class or interface. XErrorReport records
the code and message and does not terminate the process.

Closes #439

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 15:38:34 +00:00
Ateş 02b8924de7 Merge pull request #427 from MacosPorters/track-b/412-xmem-physical
[M1-B2] Map xmem physical pages into shared aliases
2026-11-26 18:31:10 +03:00
ates 925311e852 Merge main and address PR #427 review findings
- Wire physical-page accounting into xmem.cpp via shims/xmem/xmem_accounting.h so XMemGetWorkingSetStatistics and bx_xmem_get_internal_stats report allocated_physical_bytes and enforce one shared title memory budget across heap, virtual, and physical allocations.
- Require exact full-span coverage in unmap_span; empty or partially mapped spans now fail with ERROR_INVALID_PARAMETER without disturbing existing views.
- Document Win32 AWE-modeled synthetic signatures (AllocateUserPhysicalPages / FreeUserPhysicalPages in memoryapi.h) and intra-span duplicate-tag aliasing vs duplicate-tag free rejection.
- Expand test_xmem_physical to cover working-set stats, shared cap enforcement, invalid flags, intra-span duplicate-tag aliasing, duplicate and stale free non-mutation, and partial/empty unmap rejection.
- Resolve CHANGELOG.md conflict with origin/main.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 18:30:37 +03:00
Ateş f7194d0255 Merge pull request #431 from MacosPorters/track-a/410-win32-bridge
[M1-A3] Cover Win32 bridges and track offline PSM registrations
2026-11-26 18:20:03 +03:00
ates 7ea4f1f6ca Merge main and address PR #431 review findings
- Replace std::mutex/std::unordered_set + -fexceptions in psm_appnotify.cpp with a Win32 SRWLOCK and HeapAlloc open-addressed token set, keeping -fno-exceptions and reducing both PSM DLLs from ~2.4 MB back to 118 KB.
- Tag state (PSM1) and constrained (PSM2) tokens so cross-family unregisters log foreign_token while duplicate, null, or arbitrary invalid tokens log unknown_token.
- Fix load_bridge to call FreeLibrary on path mismatch or path-query failure without leaking the module handle or reporting a stale GetLastError().
- Verify exact per-(event, detail) JSONL counts inside test_win32_bridge (both with caller-provided BX_LOG_FILE and a self-managed temp log).
- Resolve CHANGELOG.md conflict with origin/main.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 18:19:30 +03:00
Ateş bd8edd8f70 Merge pull request #429 from MacosPorters/track-e/419-audio-input
Implement bounded audio queues and GameInput ordinal 1 COM stub
2026-11-26 18:09:00 +03:00
ates 058bc981dc Merge main and address PR #429 review findings
- Reject ApuAlloc before ApuCreateHeap is called and reset used=0 explicitly on heap creation
- Validate max_streams > 0 and record it on DSP connections in XDspConnectWithMaximumStreamLimit
- Expand test_audio_input to cover pre-heap ApuAlloc failure, single-output ApuAlloc, zero max_streams rejection, and GameInput v0 QueryInterface/method dispatch
- Resolve CHANGELOG.md merge conflict with main

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 18:08:53 +03:00
ates a8c4dbb77e Report sampled CLWB bounds and guest crashes in bx-cli trace
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 18:08:33 +03:00
Ateş d8b83818c1 Merge pull request #430 from MacosPorters/track-a/409-veh-clwb-crash-log
[M1-A2] Cover CLWB addressing and log unhandled guest exceptions
2026-11-26 18:01:49 +03:00
ates 0a2544cd51 Merge main and address review feedback on REX decoding, crash write isolation, and marker constant
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 18:01:41 +03:00
Ateş 0082d16b1e Merge pull request #424 from MacosPorters/track-b/411-xmem-core
[M1-B1] Enforce xmem title memory budgets
2026-11-26 17:19:59 +03:00
ates 4c7f1c5aff Merge main, sanitize console memory attributes in XMemVirtualAlloc, and zero larger stats tail
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 17:19:52 +03:00
Ateş d72350c854 Merge pull request #426 from MacosPorters/track-b/413-xcrdapi-dstorage
[M1-B3] Exercise asynchronous storage through XCRDAPI
2026-11-26 17:17:27 +03:00
ates 035c93e4d6 Merge main, guard closed handle in GetFileInformation, reject ambiguous requests, and expand tests
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 17:17:19 +03:00
Ateş b93fecf20a Merge pull request #422 from MacosPorters/track-e/418-offline-gdk-runtime
[M1-E1] Implement offline xgameruntime task queues and services
2026-11-26 17:13:59 +03:00
ates e79b0b9648 Merge branch 'main' into track-e/418-offline-gdk-runtime
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 17:13:52 +03:00
Ateş 1d94ca41e0 Merge pull request #435 from devil8blade/track-c/415-xg-xs-texture-address
[M1-C2] xg_xs.dll texture address computer MVP (XGCreateTextureComputer & XGSuggestSwizzleMode)
2026-11-26 17:04:31 +03:00
ates 044f2b628b Merge main and accept E_POINTER for null descriptor probe in test_integration_boot
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 17:04:09 +03:00
Ateş 856321f13d Merge pull request #436 from jelly013/track-d/417-d3dmetal-harness
[M1-D2] D3DMetal isolation harness via utmapp/d3dmetal-native
2026-11-26 17:02:13 +03:00
devil8blade f9ecde4e95 xg_xs: stage overlapping copies and split the size contract
Stage a source span before an in-place pitch change so later rows stay
intact. Report a D3D12 copy_end beside the aligned allocation span, and
look up mip offsets from a table built at creation.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 13:45:46 +00:00
Ateş baca93ce4e Merge pull request #434 from sahib453/track-c/414-d3d12-xs-proxy
[M1-C1] D3D12XboxCreateDevice logging COM proxy over host d3d12.dll
2026-11-26 16:16:33 +03:00
ates 8d7f856a83 Merge main, guard shaderless DXBC for D3DMetal 3.0, and log feature level
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 16:16:03 +03:00
jelly013 8fcc15596a [M1-D2] Fail on framework init errors, device removal and held pipes
Address review feedback on the D3DMetal harness failure handling:

- The probe reports `init_failed` (exit 3) when d3dmetal-native cannot
  initialize a framework that was found; the harness judges it FAIL.
  Exit 77 (SKIP) is now reserved for the CLI finding no framework.
- The fence wait checks for UINT64_MAX before treating the fence as
  complete and reports GetDeviceRemovedReason() as `device_removed`.
- Output collection shares the probe deadline: pipes are read in
  chunks over a channel, so a descendant that inherits stdout/stderr
  cannot keep the harness waiting past the timeout plus a short drain
  grace; such a run is judged incomplete.

The probe protocol is bumped to version 2.

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 14:13:55 +01:00
Ateş b8edfc18ba Merge pull request #428 from sahib453/track-f/420-integration-boot
[M1-F1] Add test_integration_boot synthetic boot fixture linking all 16 shims
2026-11-26 16:10:54 +03:00
ates 3f90a73deb Chain unhandled exception filter and clarify clwb form count
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 16:10:47 +03:00
jelly013 0b55f9fefe [M1-D2] Add D3DMetal isolation harness via d3dmetal-native
Add the opt-in d3dmetal-harness crate (bx-d3dmetal-harness) that runs a
user-supplied D3DMetal.framework outside CrossOver/Wine through
utmapp/d3dmetal-native, so D3D12 faults can be attributed to D3DMetal or
to Wine.

D3DMetal ships x86_64-only, so an x86_64 probe hosts it under Rosetta 2
while the arm64 harness locates the framework, checks Mach-O archs, runs
the probe with a cleared environment and timeout, and judges the readback
of an original SM 6.6 DXIL compute kernel against host-computed values.
Without a framework the harness reports SKIP; default builds and tests
need neither D3DMetal nor the probe.

Record d3dmetal-native, directx-native and DXC per file in the upstream
registry and component reuse matrix.

Closes #417

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 13:47:05 +01:00
devil8blade ce5a0a6e43 xg_xs: log unimplemented layouts and round BC footprints
Name TEXTURE1D, TEXTURE3D, and MSAA in the unimplemented log, and
include the SW_64KB mode in tiled vtable traces. Footprints now use
D3D12 block-rounded dimensions, and tiled CopyFromSubresource is tested.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 10:44:47 +00:00
devil8blade d7cd155924 xg_xs: add linear 2D texture address computer
Implement XGCreateTextureComputer and XGSuggestSwizzleMode for
linear RGBA8 and BC1 through BC7 layouts. RDNA 2 SW_64KB_S/D/R
modes return E_NOTIMPL and do not write addresses.

Closes #415

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 10:32:22 +00:00
Ateş fadc89b023 Merge pull request #423 from devil8blade/track-d/416-dxbc-accc-fspx
[M1-D1] dxbc-accc FSPX section parser and C ABI bridge
2026-11-26 11:30:47 +03:00
ates c38be3e256 Merge branch 'main' into track-d/416-dxbc-accc-fspx
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 11:27:53 +03:00
ates 5e002c409f docs(agents): remove contributor clean-room rule
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 11:14:13 +03:00
devil8blade 78a29fac05 Measure DXIL BitcodeOffset from DxilBitcodeHeader
BitcodeOffset is relative to the header at program byte 8. Offset 16
places the bitcode just after the 24-byte header, and offset 15 is
rejected.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 08:11:34 +00:00
devil8blade c70b951aab Reject a DXIL header whose bitcode size is zero
A DxilProgramHeader must declare a non-empty bitcode range that fits
in SizeInUint32 words, and that declared size only has to fit in the
chunk.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 08:10:24 +00:00
ates 44387cd9f6 Merge branch 'main' into track-e/418-offline-gdk-runtime
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 11:07:04 +03:00
devil8blade ca2877c61d Bound FSPX sections and require a DXIL program header
Reject FSPX tables above 64 sections before pairwise checks. Accept a
DXIL chunk only when it carries a DxilProgramHeader, and share one
stage rule so a later FSPX stage fills an earlier gap.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 08:01:58 +00:00
sahib453 4b19d48994 Merge upstream main and keep both changelog entries
Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-26 13:28:25 +05:30
sahib453 8208127bc0 Merge upstream main and keep both changelog entries
Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-26 13:28:25 +05:30
sahib453 c70e544660 Implement D3D12XboxCreateDevice as a logging COM proxy over host d3d12.dll
d3d12_xs.dll (M1-C1, #414) now creates a device through the host
D3D12CreateDevice and returns a proxy covering ID3D12Device through
ID3D12Device10, ID3D12CommandQueue, ID3D12CommandAllocator and
ID3D12GraphicsCommandList through 7 (the levels the mingw-w64 d3d12.h
declares). Child objects are returned as proxies and translated back
for the host; pipeline-state creation logs shader container metadata;
unsupported interface levels and slots past the public vtable log via
BX_VTABLE_STUB_LOG. Pass-through methods are generated by
shims/d3d12_xs/tools/gen_proxy.py. Adds tests/conformance/test_d3d12_xs.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-26 13:28:05 +05:30
ates 7d5d76f001 docs: place progress tracker above architecture in README
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 10:54:55 +03:00
ates 40ba0632b1 docs: add visual M0-M6 and Track A-F progress tracker to README
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 10:54:55 +03:00
Ateş 0bfd08eb12 Merge pull request #432 from MacosPorters/docs/issue-template-zen
docs: add required Zen purpose field to track-handoff issue template
2026-11-26 10:40:59 +03:00
ates d97b856e93 docs: add required Zen purpose field to track-handoff issue template
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 10:40:05 +03:00
ates cee636193a Cover Win32 bridges and track offline PSM registrations
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 10:13:12 +03:00
ates 134eee3a28 Cover CLWB addressing and log unhandled guest exceptions
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 10:13:12 +03:00
ates 43f32acb82 Implement bounded audio queues and GameInput COM stub
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 10:06:36 +03:00
sahib453 d186440216 Add test_integration_boot synthetic boot fixture linking all 16 shims
Adds tests/conformance/test_integration_boot (M1-F1, #420): an original
x86-64 PE32+ program whose import directory names every BetterXen shim
DLL and which walks a startup-shaped sequence through reverse-order
shutdown, emitting one JSON checkpoint and one bx_log_emit record per
stage with status pass, pending or fail. Pending marks an M0 stub or a
host-answered import, never counts as a pass, and fails under --strict.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-26 12:26:30 +05:30
ates 88fa2d1a99 Deliver queued callbacks on xgameruntime shutdown
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 09:53:14 +03:00
ates ab696f1f07 Map xmem physical pages into shared aliases
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 09:52:04 +03:00
ates 0b0e23e10a Exercise asynchronous storage through XCRDAPI
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 09:49:04 +03:00
ates 19c240edd5 Enforce xmem title memory budgets
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 09:38:59 +03:00
devil8blade 3feba31a33 Parse synthetic FSPX sections and export the shader C ABI
dxbc-accc reads FSPX section tables inside ACCC chunks, bounds-checks
section descriptors, stage config, and RDNA 2 code ranges, and exports
bx_shader_inspect, bx_shader_prepare_for_d3dmetal, and
bx_shader_free_buffer. DXIL containers pass through; ACCC-only
containers return unsupported and log the inspection.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 06:29:13 +00:00
ates 8742734a0a Implement offline xgameruntime task queues and services
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 09:18:48 +03:00
Ateş a51271d125 Merge pull request #421 from MacosPorters/docs/agents-onboarding
docs: add first-time contributor onboarding flow to AGENTS.md
2026-11-26 08:37:16 +03:00
ates 4fc5d9e5a4 docs: add first-time contributor onboarding flow to AGENTS.md
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 08:31:41 +03:00
atharvranjan f2c42ba110 Merge pull request #406 from MacosPorters/m0/hybrid-foundation
M0: Overhaul repo into clean 6-track parallel hybrid foundation (ADR 0006)
2026-11-25 23:06:36 -06:00
ates 30e551a161 Overhaul repo into clean 6-track hybrid M0 workspace and retire legacy native files
Rebases onto origin/main and retires the paused in-tree native-first workspace, legacy scripts, legacy CI, and native-only docs per ADR 0006 (preserving full history permanently at Git tag native-first-final).

Addresses all maintainer review findings on PR #406:
- Isolate CrossOver/Wine child process environment in bx-cli (env_clear + minimal allowlist + opt-in --inherit-env, with unit tests)
- Replace naive objdump grep in scripts/build-shims.sh with strict PE Export Directory verification (exact names, ordinals, forwarders, 0 extra exports, 0 forbidden MinGW imports across all 16 DLLs / 102 exports)
- Restore global * @MacosPorters/maintainers fallback in .github/CODEOWNERS alongside per-track rules
- Restore independent-verification, claims/evidence-class, provenance-first, and contributor clean-room protections in AGENTS.md
- Unify docs/roadmap.md, CONTRIBUTING.md, README.md, docs/README.md, THIRD_PARTY_NOTICES.md, and CHANGELOG.md around Milestones M0-M6 and ADR 0006

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 07:59:27 +03:00
atharvranjan d9333d272f Merge pull request #396 from IamHeavyLazer/feature/353-hybrid-measurement-protocol
docs: define hybrid workloads and measurement protocol
2026-11-25 16:26:56 -06:00
atharvranjan 395aaeb4e7 Merge pull request #379 from erkinemreta1/docs/354-crossover-licensing
Record CrossOver component licenses and redistribution boundaries
2026-11-25 16:13:15 -06:00
HeavyLazer efb63a37d4 docs: define hybrid workloads and measurement protocol
Signed-off-by: HeavyLazer <iamheavylazer@gmail.com>
2026-11-25 23:12:40 +01:00
erkinemreta1 35cdf56e80 Address the independent review of the licensing note
Record the public CrossOver EULA and its section 2/3 terms, correct the
source-page inventory (no DXMT or VKD3D-Proton), cite DXMT's MIT
LICENSE.OLD and VKD3D-Proton's COPYING, soften the MoltenVK NOTICE
claim, add the reviewed pins and name the D3DMetal third-party source.

Signed-off-by: erkinemreta1 <erkinemreta1@users.noreply.github.com>
2026-11-26 00:12:18 +03:00
atharvranjan db3bdb5a5c Merge pull request #380 from MacosPorters/remove-agent-pr-checks
Remove the agent-pr-checks workflow
2026-11-25 14:48:58 -06:00
atharvranjan 9b20f78a06 Remove agent-pr-checks tests and docs 2026-11-25 14:41:35 -06:00
erkinemreta1 b39780b421 Fold the reported D3DMetal reading into the licensing note
Record the third-party 4.0 License.pdf summary as evidence class D,
unconfirmed against Apple's own copy, and keep D3DMetal user-supplied
and never bundled. Update the licenses.md row and the changelog entry
to match.

Signed-off-by: erkinemreta1 <erkinemreta1@users.noreply.github.com>
2026-11-25 23:39:44 +03:00
erkinemreta1 f8f497b578 Record CrossOver component licenses and redistribution boundaries
Add docs/research/crossover-licensing.md with the license text read for
each component, its source link and the redistribution status, plus a
matching section in docs/licenses.md. D3DMetal, Rosetta 2 and the
CrossOver product terms stay unknown with the missing document named.

Closes #354

Signed-off-by: erkinemreta1 <erkinemreta1@users.noreply.github.com>
2026-11-25 23:39:27 +03:00
atharvranjan 77cec214c0 Merge pull request #378 from MacosPorters/planning/hybrid-first-transition
Transition to a CrossOver-based hybrid direction with progressive planning; archive native work
2026-11-25 14:32:48 -06:00
atharvranjan 953254a435 Remove the agent-pr-checks workflow 2026-11-25 14:30:07 -06:00
atharvranjan 39b628d60d Fix a link in the archived README milestones 2026-11-25 14:23:04 -06:00
atharvranjan 1d70633958 Keep the local Agent Spawning section out of the shared engineering rules
That section was an uncommitted local addition and is not part of main.
2026-11-25 14:22:57 -06:00
atharvranjan a9f55b51f7 State that the native-first-final tag marks the last main commit before the transition 2026-11-25 14:22:38 -06:00
atharvranjan 722388a46d Record the planning transition in the changelog
CrossOver-based hybrid direction, rewritten engineering rules, native work paused and archived, upstream registry and research records.
2026-11-25 14:22:17 -06:00
atharvranjan e7ff293eba Record primary-source verification and finalize the Phase 1 backlog
Add the hybrid research record and a primary-source re-check (CodeWeavers, Apple, DXMT, Wine, Rust toolchain), rename the roadmap's parked section to Parked ideas, and add the matching changelog and docs index entries. Unrelated local work stays uncommitted.
2026-11-25 14:22:09 -06:00
atharvranjan dfaaa07df4 Update README, CONTRIBUTING, docs index, changelog and template for progressive planning
Only this task's hunks are committed; unrelated local edits remain uncommitted.
2026-11-25 14:21:53 -06:00
atharvranjan 962b83c731 Extend the upstream registry with unreviewed candidates
llvm-mingw, Sikarugir, macOS Wine builds, Mythic and Playdock, metadata only.
2026-11-25 14:21:47 -06:00
atharvranjan 7fff77c801 Simplify the roadmap to one active phase and archive the native issue backlog
Five provisional phases with only Phase 1 active, parked ideas, Phase 1 completion criteria, a simple project board guide, the retired H0 to H7 breakdown, and an index of the closed native issues with preserved findings and contributor attribution.
2026-11-25 14:21:47 -06:00
atharvranjan c3684a1ae8 Add progressive planning rules to the engineering rules
Only the current phase has a milestone and open issues; future ideas are parked in the roadmap; issues carry evidence, reuse assessment and validation; no native-only issues.
2026-11-25 14:21:47 -06:00
atharvranjan d561595599 Replace issue templates and add a pull request template
Hybrid task, bug, research, performance, validation and documentation forms with problem, context, scope, dependencies, acceptance, validation and licensing sections. Fix invalid YAML in the agent-task template.
2026-11-25 14:21:47 -06:00
atharvranjan 8cab0b1de8 Describe the hybrid direction in README, CONTRIBUTING, docs index and changelog
Only this task's hunks are committed; unrelated local edits to CHANGELOG.md and docs/README.md remain uncommitted.
2026-11-25 14:21:40 -06:00
atharvranjan d2367dca30 Add the upstream research registry and component reuse matrix
Public-documentation review (evidence class D, nothing executed) of CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, FEX, VIctory, VIctory-macOS and PortWatch with license, pin and reuse decisions. VIctory-family projects are excluded from reuse on provenance grounds.
2026-11-25 14:20:55 -06:00
atharvranjan 60ad6c779e Add the CrossOver-based hybrid roadmap and archive the native-first plan
Add docs/roadmap.md (phases H0 to H7, critical path), ADR 0005 (accepted direction; proposed architecture and unverified assumptions kept separate), the deferred native roadmap and the project board setup guide. Archive the native-first plan and the seven retired milestones. Mark the PortWatch review as superseded in part.
2026-11-25 14:20:55 -06:00
atharvranjan ffc7056d26 Rewrite engineering rules for the CrossOver-based hybrid direction
Replace the native-first prohibition on Wine, CrossOver, Rosetta and MoltenVK with dependency, reuse, licensing and provenance rules. Keep the honesty, independent-verification, clean-room, claiming, changelog and subagent rules. CLAUDE.md remains a symlink to AGENTS.md. Resolves #345 once reviewed.
2026-11-25 14:20:55 -06:00
atharvranjan 9923e59114 Merge pull request #296 from maridogolpeador/app/252-open-command
app: add Command-O and show file-picker errors (#252)
2026-11-25 12:08:20 -06:00
atharvranjan feba95fe39 Merge origin/main into app/252-open-command
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 11:52:31 -06:00
atharvranjan a275de6e2e Merge pull request #295 from maridogolpeador/app/251-inspection-request-order
app: keep inspection results tied to the latest selection (#251)
2026-11-25 11:51:15 -06:00
atharvranjan 25986845da Merge origin/main into app/251-inspection-request-order
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 11:46:03 -06:00
atharvranjan df9652740b Merge pull request #309 from soggyramennoodle/task/255-startup-diagnostics
Report trusted fixture startup progress
2026-11-25 11:42:21 -06:00
atharvranjan 1ca491d8d0 Merge pull request #297 from maridogolpeador/docs/260-texture-format-inventory
docs: inventory texture formats and layouts by stage (#260)
2026-11-25 11:42:08 -06:00
atharvranjan 964a8296f2 Merge pull request #294 from atesahmet0/task/154-cpu-coverage-map
Add the verified CPU/loader coverage map
2026-11-25 11:41:54 -06:00
atharvranjan d8a8c96408 Merge pull request #338 from Thxlx/perf/89-arm64-constant-load
perf: shorten ARM64 loads for zero-extended constants
2026-11-25 11:40:55 -06:00
atharvranjan 50321b3f14 Merge pull request #337 from Thxlx/docs/299-avx-contract 2026-11-25 10:56:04 -06:00
Thilo Schaeffer 1fe07f45ee test: clarify ARM64 assembler offset units
Signed-off-by: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com>
2026-11-25 17:45:05 +01:00
Thilo Schaeffer d486d21813 docs: clarify AVX exception policy and Intel references
Signed-off-by: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com>
2026-11-25 17:45:04 +01:00
Thilo Schaeffer 4c92c88b29 perf: shorten ARM64 loads for zero-extended constants
Signed-off-by: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com>
2026-11-25 17:31:03 +01:00
Thilo Schaeffer 478e9218ac docs: specify the guest AVX and AVX2 contract
Signed-off-by: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com>
2026-11-25 17:21:18 +01:00
Adeeb Rahman 8d2662dcd7 Preserve startup report delivery and worker errors
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-25 09:56:31 -05:00
Adeeb Rahman fe1bf568c8 Merge BetterXen main
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-25 09:51:45 -05:00
maridogolpeador 873652d685 app: run inspection reads on a Dispatch queue, not a concurrency worker (#251)
Review follow-up. The reader blocks on file I/O, and in the
--smoke-inspection-order check on its gate semaphore. Inside
Task.detached that blocked a Swift concurrency worker; with a
single-worker cooperative pool the released newer read could not start
while the older one waited, and the check timed out. The read now runs
on DispatchQueue.global(qos: .userInitiated) and is bridged back with
withCheckedContinuation. The request-number guard is unchanged.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:38:12 -03:00
ates 84f561b12b Fix the documented known-answer count command
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-25 16:14:50 +03:00
maridogolpeador 2b113a2e5e docs: separate host API coverage from guest reachability and link sources (#260)
Review follow-up. The Guest column credited the descriptor-table SRVs,
which tests call directly from Rust and the interface contract says
are not yet wired to guest imports. The table now has a Host graphics
API column for them and keeps Guest for paths an original PE fixture
reaches through imported services: today only RGBA8, through the
synthetic xenora.dll texture services of the Gate 5 fixture. Every
repository path is now a relative link, and each format row links the
exact Khronos DFS 1.3 section and Microsoft or Apple page it relies on.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:44 -03:00
maridogolpeador 9a26e1ee36 docs: inventory texture formats and layouts by stage (#260)
Add docs/research/texture-formats.md, built from BetterXen main. For
RGBA8, BC1-BC7 and Depth32Float it separates container recognition,
CPU decoding, layout conversion, native Metal upload and readback,
translated sampling and guest reachability, linking the implementing
files and tests for each cell, including the packed BC footprints from

It cross-references #208 and #209 rather than opening duplicate tasks,
records console layouts, console descriptors and asset or audio
containers as unknowns, and ranks three proposed follow-ups with an
original-fixture recipe, an independent source of expected values and
an owner each. Deferred formats with no demonstrated need are listed.

docs/README.md indexes the page. Research only; no code changed.

Ported from XenoraOSS/Xenora#427 and re-checked against BetterXen main.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:43 -03:00
maridogolpeador c84b80b24f app: route Command-O to the focused window's importer (#252)
Review follow-up. The command set a shared Boolean, so with every
window closed there was no importer to present it, and with several
windows each one bound the same flag. Each ContentView now owns its
importer state and publishes an open action with focusedSceneValue;
OpenExecutableCommand reads it with @FocusedValue, calls it for the
focused window and is disabled when no window provides it. The
inspector button uses the same per-window action. InspectionModel no
longer holds the importer flag; requestImport only clears the previous
selection error.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:31 -03:00
maridogolpeador ae804f0530 app: gate the inspection-order smoke check instead of sleeping (#251)
Review follow-up. The check used fixed 300/700 ms pauses, so on a
loaded host a late stale read could arrive after an assertion, or the
newer read could finish before the busy-state check. The injected
reader now blocks until the check releases that file, and the check
waits on InspectionModel.finishedReads, which counts every finished
read whether it was published or discarded. A five-second deadline
bounds the wait without deciding the order.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:31 -03:00
maridogolpeador 64e7b16983 app: add Command-O and show file-picker errors (#252)
The inspector had an Open Executable… button but no app-level Open
command, and the file importer's completion ignored failures, so a
picker error was never shown.

- File > Open Executable… with Command-O, after New Window. It calls
  the same requestImport() as the button, so it opens the same
  read-only importer and the chosen file reaches inspect(), the path
  shared with drag and drop and Finder Open With.
- importFinished(_:) handles the importer result: success inspects,
  a user cancellation (CocoaError.userCancelled) shows nothing, and any
  other failure is shown in red with the error's description. The
  message clears on the next request or selection.
- --smoke-import-result checks cancellation, a shown failure and its
  clearing without opening files; scripts/build-app.sh runs it after
  --smoke. It fails with the previous importer handling and without the
  cancellation check.

Opening a file still never starts guest execution, the DBT or the JIT.

Ported from XenoraOSS/Xenora#424.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:31 -03:00
maridogolpeador 1ea898b4bf app: keep inspection results tied to the latest selection (#251)
InspectionModel.inspect started a detached read per call and published
status, report and busy whenever any of them finished. A slow first
inspection that completed after a fast second one replaced the newer
report and status, and could clear busy while the newer read was still
running.

- Each inspect call takes a request number; a completion is applied
  only while it is still the latest, so stale success and stale failure
  are discarded. Picker, drag and drop and Finder Open With all go
  through inspect and share this.
- A new selection clears the previous report, and a failed inspection
  of the latest file is shown in red above its report.
- The read is unchanged: size checked before reading, balanced
  security-scoped access, nothing executed. The reader is injectable
  only for the smoke check.
- --smoke-inspection-order drives the model with an injected slow and
  fast reader: slow then fast with either outcome, and busy held for the
  newer request while an older read finishes. scripts/build-app.sh runs
  it after --smoke. All four checks fail without the change.

Ported from XenoraOSS/Xenora#423.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:31 -03:00
ates 7946968cc4 Address coverage review and merge current main
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-25 16:03:49 +03:00
atharvranjan 67b8cff9df Merge pull request #326 from MacosPorters/claude/pr-294-review-nftzfu
Rewrite the README around the development phases and launch target
2026-11-25 05:59:17 -06:00
atharvranjan 51c23a2f38 Merge pull request #293 from maridogolpeador/ci/248-app-build
ci: build and smoke-test BetterXen.app on native ARM64 runners (#248)
2026-11-25 05:58:01 -06:00
Claude 7d97e67448 Rewrite the README around the development phases and launch target
Reorganize the README around the six development phases and the first
launchable application tracker, add colour-coded Mermaid diagrams and
registry-derived charts, a repository overview and a contributing
section, and correct the texture-sampling and recompiler wording.

Signed-off-by: Claude <noreply@anthropic.com>
2026-11-25 11:53:09 +00:00
atharvranjan d9261db887 Merge pull request #325 from MacosPorters/repo/add-codeowners
Add CODEOWNERS and replace
2026-11-25 04:39:37 -06:00
atharvranjan 5c0c82b3f9 Add a fast repository hygiene check
Add hygiene.yml and scripts/audit/docs_hygiene.py: fail on merge-conflict
markers, broken relative Markdown links and invalid workflow YAML, and
warn (advisory) when source changes lack a changelog entry.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 04:24:36 -06:00
atharvranjan b71db3c25a Remove the pull request template
Delete .github/PULL_REQUEST_TEMPLATE.md and update CONTRIBUTING.md and
the changelog to match.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 04:23:03 -06:00
atharvranjan 566f803111 Remove the PR template check
Delete the pr-template workflow, its checker script and tests, and the
CI step that ran those tests. Update CONTRIBUTING.md and the changelog.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 04:18:06 -06:00
atharvranjan 857c16fcf7 Merge origin/main into repo/add-codeowners
Resolve conflicts in favor of main's development phases and roadmap
text. Keep the game-title wording and PE-Vulkan project renames, the
PortWatch research notes and their docs index link.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 04:16:38 -06:00
atharvranjan 4f5c6913f5 Replace game-title and upstream-project names in our own docs
Use generic 'commercial title' wording for our own references to a
specific game, rename the ignored diagnostics folders to
title-candidate-* and title-check, and refer to the upstream PE/Vulkan
project as 'PE-Vulkan project' in prose. Third-party URLs and repository
paths are unchanged to keep provenance accurate. Also adds the native
macOS development phases and PortWatch research notes already in the
working tree.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 04:12:59 -06:00
Adeeb Rahman e4ddb05a1a Run startup draw check on native Metal hardware
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-25 00:27:42 -05:00
Adeeb Rahman d33a7c6941 Report trusted fixture startup progress
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-25 00:23:04 -05:00
maridogolpeador 4e838207fe ci: check the printed dependency listing and reject empty or failed listings (#248)
Review follow-up. build-app.sh now runs otool -L once in a checked
assignment, prints that output and parses the same text, so a failing
or empty listing fails the gate instead of skipping the loop. Every
Swift executable links libSystem, so an empty list is an error.
Bundle-relative entries (@rpath, @executable_path, @loader_path) get
their own message. The changelog entry now separates the designed CI
behaviour from what has been verified locally.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 02:09:22 -03:00
ates b40bbae1da Refresh the coverage map at merged main b2654e9
The branch now contains main b2654e9, which includes the merged DBT
cache-identity pull and the migration-benchmark checks, so the map pins
its single gate run to that revision: the former self-modifying-code
defect test executes and passes in both DBT engines (cpu_known_answers
50 passed, 0 ignored) and the workspace gate reports 116 result lines
with 1015 passed, 0 failed and 34 ignored. The ignore taxonomy in the
map names all three kinds from their own messages: Metal-gated,
LLVM-gated (gfx1030 AMDGPU target) and manual timing runs.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-25 08:07:53 +03:00
maridogolpeador b04b41f26a ci: build and smoke-test BetterXen.app on native ARM64 runners (#248)
The CI workflow built and inspected the CLI but never ran
scripts/build-app.sh, so a Swift compile, link or smoke failure in app/
passed CI.

- ci.yml: a second job, "Native app build and smoke", on the same
  macos-26 image, pinned Rust toolchain and CARGO_BUILD_JOBS as the Rust
  job. It verifies an arm64 host without Rosetta, prints the Xcode and
  Swift versions and runs scripts/build-app.sh. The Rust job is
  unchanged.
- build-app.sh: after the lipo check, print file and otool -L for the
  executable and fail if it links anything outside /System/Library/ and
  /usr/lib/.

No Metal fixture runs in the new job; --smoke probes the C interface
and the trusted fixture's headers only. The same change was proposed
upstream as XenoraOSS/Xenora#426.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 01:59:03 -03:00
ates 3dd3ef06e2 Merge main into CPU coverage map
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-25 07:58:15 +03:00
atharvranjan b2654e93a4 Merge pull request #292 from MacosPorters/fix/migration-benchmark-checks
Run benchmark report tests in CI and record migration integration
2026-11-24 22:52:27 -06:00
ates fee956293d Add the verified CPU/loader coverage map
Document what the CPU and loader tests verify, per operation family, in
docs/testing/cpu-coverage.md: the declared-form inventory (213 operations,
403 forms, 498 opcode slots from the validated registry), the per-operation
engine split (93 native-lowered, 120 shared-semantic, with the conditional
width and encoding gates), a per-artifact evidence table with exact pass
counts from one full workspace gate run on Apple M5, the reconciliation of
the eight operations covered by model tests instead of the assembly-fixture
corpus, and a recorded note that three advisory qa cpu-inventory
unsupported-catalog rows are stale against the implemented and tested forms.
Also updates the docs/README.md description line and adds the CHANGELOG
entry under [Unreleased].

Closes #154.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-25 07:52:19 +03:00
atharvranjan 146d2dd467 Correct Win64 call-entry alignment wording
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:46:05 -06:00
atharvranjan a0d9b85dbf Run benchmark report tests in workspace CI and record migration review
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:42:19 -06:00
atharvranjan 5366b93986 Merge pull request #269 from MacosPorters/archive/pull/371/head
Validate DBT caches with executable generations and source revalidation
2026-11-24 22:31:00 -06:00
atharvranjan 50c392111d Merge pull request #266 from MacosPorters/archive/pull/352/head
bench: measure Metal startup in fresh processes and repeated runs (#178)
2026-11-24 22:26:04 -06:00
atharvranjan f43a07ce31 Synchronize cache generation fix with the integrated hosted C runtime
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:25:18 -06:00
atharvranjan 10fd1cd4be Merge pull request #265 from MacosPorters/archive/pull/346/head
metal: budgeted staged RGBA8 texture upload into Private storage (#144)
2026-11-24 22:24:24 -06:00
atharvranjan 95aa10c60f Merge pull request #278 from MacosPorters/archive/pull/394/head
Pack block-compressed texture mip chains by subresource
2026-11-24 22:24:17 -06:00
atharvranjan 873b4fd4a9 Integrate PR #266 and distinguish imported benchmark evidence
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:19:01 -06:00
atharvranjan 120878de2d Integrate PR #265 bounded native Metal texture staging
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:16:37 -06:00
atharvranjan d26af53cef Merge pull request #283 from MacosPorters/archive/pull/420/head
loader: add the Gate A2 hosted C program and its test (#419)
2026-11-24 22:15:23 -06:00
atharvranjan b6ebaaad5e Merge pull request #282 from MacosPorters/archive/pull/418/head
loader: add files for a hosted C program: fopen, fclose, fgets and perror (#402)
2026-11-24 22:11:50 -06:00
atharvranjan aba82cdb77 Integrate PR #278 packed texture footprints
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:11:44 -06:00
atharvranjan 44ac976291 Retain cache-hit assertions with generation-triggered source revalidation
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:10:24 -06:00
atharvranjan d71efe0495 Integrate Gate A2 and verify native compiler architecture before execution
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:09:39 -06:00
atharvranjan 0bd8e19aac Merge pull request #281 from MacosPorters/archive/pull/401/head
loader: add standard output and printf formatting for a hosted C program (#400)
2026-11-24 22:08:23 -06:00
atharvranjan a1744a2754 Integrate PR #282 file streams with the combined runtime registry
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:05:58 -06:00
atharvranjan e93509ef5b Merge pull request #280 from MacosPorters/archive/pull/399/head
loader: add exit, _exit and abort for a hosted C program (#395)
2026-11-24 22:04:34 -06:00
atharvranjan 8344e299c9 Merge pull request #277 from MacosPorters/archive/pull/393/head
loader: add program arguments for a hosted C program (#392)
2026-11-24 22:04:27 -06:00
atharvranjan 433dc43695 Merge pull request #273 from MacosPorters/archive/pull/385/head
loader: add nine C runtime startup services a hosted C program imports (#382)
2026-11-24 22:04:19 -06:00
atharvranjan c18f9ffa7f Integrate PR #281 with existing startup and argument services
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:04:16 -06:00
atharvranjan a0f2d833aa Merge pull request #276 from MacosPorters/archive/pull/390/head
loader: add VirtualProtect, VirtualQuery and __C_specific_handler as stubs (#388)
2026-11-24 22:04:10 -06:00
atharvranjan 61afca42c9 Merge pull request #279 from MacosPorters/archive/pull/397/head
loader: run LOOP, LOOPE, LOOPNE and JRCXZ (#396)
2026-11-24 22:04:02 -06:00
atharvranjan be19e4e28f Merge pull request #275 from MacosPorters/archive/pull/389/head
loader: run LAHF and SAHF and report them in CPUID (#387)
2026-11-24 22:03:56 -06:00
atharvranjan 33ccf7fd55 Merge pull request #271 from MacosPorters/archive/pull/381/head
loader: add FNINIT and the x87 control, status and tag words (#378)
2026-11-24 22:03:49 -06:00
atharvranjan bb62353cfe Merge pull request #274 from MacosPorters/archive/pull/386/head
loader: raise #GP for instructions longer than 15 bytes (#384)
2026-11-24 22:03:42 -06:00
atharvranjan 1f2e7d3bb6 Merge pull request #272 from MacosPorters/archive/pull/383/head
bench: compare two dbt_bench JSON results (#114)
2026-11-24 22:03:34 -06:00
atharvranjan b5b646a58d Warm differential-test caches within the same guest address space
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:02:34 -06:00
atharvranjan acb3839351 Integrate PR #280 process termination and exit callbacks
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:00:19 -06:00
atharvranjan f9d5838091 Integrate PR #277 with the combined typed runtime services
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:59:43 -06:00
atharvranjan 4314071ac7 Validate DBT cache identity with executable generations instead of byte scans
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:59:14 -06:00
atharvranjan 4173a781af Integrate PR #273 and regenerate the combined runtime registry
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:48 -06:00
atharvranjan 4e15e5f43b Synchronize PR #275 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:16 -06:00
atharvranjan cf4010ba94 Synchronize PR #271 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:14 -06:00
atharvranjan b9e6a9d365 Synchronize PR #274 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:12 -06:00
atharvranjan a1a1020ebd Synchronize PR #272 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:10 -06:00
atharvranjan e755ee94ed Merge pull request #264 from MacosPorters/archive/pull/340/head
benchmarks: measure gfx1030 metadata identification
2026-11-24 21:57:34 -06:00
atharvranjan 2f68ee9d4a Integrate PR #276 with explicit unsupported-service behavior
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:57:08 -06:00
atharvranjan e7a2159c82 Carry benchmark harness lint correction into the integration candidate
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:54:03 -06:00
atharvranjan 98e9420b7f Integrate PR #279 and retain all newly supported known answers
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:51:45 -06:00
atharvranjan 238b5a001b Keep benchmark fixture tests lint-clean without a benchmark harness
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:51:38 -06:00
atharvranjan e289318132 Merge pull request #267 from MacosPorters/archive/pull/359/head
loader: draw nothing for zero-instance flat draws and reject unsupported ones (#148)
2026-11-24 21:49:39 -06:00
atharvranjan 99ed89787e Integrate PR #275 preserving FNINIT and existing shift expectations
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:49:30 -06:00
atharvranjan 522560d0a2 Integrate PR #271 while preserving BetterXen terminology
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:48:34 -06:00
atharvranjan f685b54e32 Merge pull request #268 from MacosPorters/archive/pull/369/head
loader: add Win64 service ABI preservation tests (#201)
2026-11-24 21:48:28 -06:00
atharvranjan 0690a3ecb4 Merge pull request #284 from MacosPorters/archive/pull/422/head
loader: copy mid-size TLS templates into the zeroed block (#111)
2026-11-24 21:48:22 -06:00
atharvranjan 7286989296 Merge pull request #270 from MacosPorters/archive/pull/374/head
Fix ARM64 variable shift register encoding
2026-11-24 21:47:03 -06:00
atharvranjan d28d539a90 Integrate PR #274 instruction-length fault handling
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:46:54 -06:00
atharvranjan 8c4b2344df Integrate PR #272 benchmark comparison mode
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:46:50 -06:00
atharvranjan a75d018435 Integrate PR #264 and run identification fixture in workspace tests
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:46:15 -06:00
atharvranjan 4652eb08cb Integrate PR #267 with current native runtime
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:45:36 -06:00
atharvranjan d1bcd0249d Integrate PR #268 and clarify Win64 shadow-space expectations
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:44:49 -06:00
atharvranjan 097bb0b5b8 Merge commit '19f63a0' into integration/pr-284
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:43:15 -06:00
atharvranjan 2d77b35e56 Merge remote-tracking branch 'origin/main' into integration/pr-284
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 21:43:15 -06:00
atharvranjan 19f63a0985 Merge remote-tracking branch 'origin/main' into integration/pr-270
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:42:09 -06:00
atharvranjan 45322af82e Merge pull request #288 from MacosPorters/foc
Define BetterXen development phases and record migration repairs
2026-11-24 21:41:11 -06:00
atharvranjan aa9a961ef4 Remove README contributor avatar section
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:37:38 -06:00
atharvranjan 10347dc21b Document BetterXen development phases and migration check repairs
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:34:55 -06:00
atharvranjan 4d530392d1 Merge pull request #285 from MacosPorters/repo/add-codeowners
Add CODEOWNERS requiring maintainer review
2026-11-24 21:30:10 -06:00
atharvranjan f02eb2678e Add CODEOWNERS requiring maintainer review
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:21:45 -06:00
atharvranjan 19a905c30e Document migration archive refs as tags
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:01:27 -06:00
atharvranjan bfe0bbfaf7 Rename project and native applications to BetterXen
Update active repository links and coordination settings while retaining upstream history, notices, legacy library names and guest interfaces. Document the independent-copy migration and its limits.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 20:51:08 -06:00
Ranveer Soni 5442503d57 Merge pull request #421 from devil8blade/cursor/shader-cse-142
shader: opt-in IR common-subexpression elimination (#142)
2026-11-25 07:44:42 +05:30
devil8blade f0c61c7a91 loader: copy mid-size TLS templates into the zeroed block (#111)
Templates from 64 KiB up to 1 MiB were staged in a second buffer and
copied again into the thread block. Proving those bytes readable, then
copying them into the block that is already zeroed, avoids that buffer
and still maps nothing when the template cannot be read. Smaller
templates and templates of 1 MiB or more keep the single staged read,
which measured as fast or faster.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-24 21:01:31 -05:00
devil8blade 0caca18634 shader: opt-in IR common-subexpression elimination (#142)
Reuse the first equivalent pure vector unary or binary when
CompileOptions::eliminate_common_subexpressions is set. The flag defaults
off, so existing output stays byte-identical. Loads, stores, constant
definitions, lane masks, merges, branches and other side-effecting or
mask-dependent ops are not reused. Constant folding still runs first.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-24 20:49:19 -05:00
zachdoxsee 81a32e3ec6 Merge task/402-crt-files into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:33:07 +01:00
zachdoxsee 8edf3abf53 Merge task/395-crt-exit into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:33:07 +01:00
zachdoxsee 0c397c5957 Merge upstream/main into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:32:58 +01:00
zachdoxsee 417b19c859 Merge task/382-crt-startup into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:32:58 +01:00
Ranveer Soni 4cc703d566 Merge branch 'main' into fix/84-dbt-stale-code-cache 2026-11-25 07:02:16 +05:30
zachdoxsee 5ae43a3cb8 Merge task/400-standard-output (with upstream main) into task/402-crt-files
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:27:10 +01:00
zachdoxsee ab73969135 Merge upstream main into task/395-crt-exit
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:27:10 +01:00
zachdoxsee 8ee0304237 Merge upstream main into task/400-standard-output
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:27:04 +01:00
zachdoxsee 42cdb7d122 Merge upstream main into task/382-crt-startup
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:27:04 +01:00
Ranveer Soni 2ea75603be Merge pull request #338 from LanaCodes-Boop/runtime/guest-clock-fixtures
loader: stop the mock clock wrapping and test time services against one clock (#204)
2026-11-25 06:56:35 +05:30
Ranveer Soni 6fc06dccff Merge branch 'main' into runtime/guest-clock-fixtures 2026-11-25 06:56:20 +05:30
Ranveer Soni a1295d5a48 Merge pull request #331 from zachdoxsee/task/329-gate-a1
loader: add process exit and the Gate A1 compiled C program (#329)
2026-11-25 06:55:50 +05:30
zachdoxsee 0a17f0cb73 loader: add the Gate A2 hosted C program and its test (#419)
An original C program, tests/compat_fixtures/gate_a2.c, is built from
source 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 uses argc and argv, the heap, qsort, printf, a file
written with fprintf and read back with fgets, atexit, and a return from
main. Expected output is recomputed in Rust, not read back from a run.
Control variants end in a failed check, in exit(42) and in abort().

The test fails, and does not skip, when the compiler is missing, so the CI
workflow installs mingw-w64. Nothing from mingw-w64 is stored in the
repository.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:25:26 +01:00
Ranveer Soni 20d7b9ece4 Merge pull request #376 from GDemay/perf/105-contiguous-data-access
loader: avoid resolver allocations in guest data access
2026-11-25 06:46:38 +05:30
zachdoxsee db80c0b3e3 Merge task/402-crt-files into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:16:20 +01:00
zachdoxsee db46390fa9 Merge task/395-crt-exit into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:16:20 +01:00
zachdoxsee a9abc36eef Merge task/392-program-arguments into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:16:20 +01:00
zachdoxsee 972bc0a35c Merge task/388-must-exist-stubs into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:16:20 +01:00
zachdoxsee c0e90338d1 Merge task/382-crt-startup into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:16:19 +01:00
zachdoxsee e32c85ff12 Merge task/378-fninit into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:51 +01:00
zachdoxsee d409c26458 Merge task/329-gate-a1 into task/419-gate-a2
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:51 +01:00
zachdoxsee e57386950b Move the changelog entry down the list
Every merge to main adds its entry at the head of the Added list, and so did
this branch, so each of those merges put this branch in conflict over one
line. The entry is unchanged; it now sits lower down, in a place of its own.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:01 +01:00
zachdoxsee 1fafc2e43f Merge task/400-standard-output into task/402-crt-files
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:01 +01:00
zachdoxsee 0aeb2b69a9 Merge task/329-gate-a1 into task/395-crt-exit
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:01 +01:00
zachdoxsee 1342878c49 Move the changelog entry down the list
Every merge to main adds its entry at the head of the Added list, and so did
this branch, so each of those merges put this branch in conflict over one
line. The entry is unchanged; it now sits lower down, in a place of its own.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:01 +01:00
zachdoxsee d6c9f846f0 Move the changelog entry down the list
Every merge to main adds its entry at the head of the Added list, and so did
this branch, so each of those merges put this branch in conflict over one
line. The entry is unchanged; it now sits lower down, in a place of its own.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:01 +01:00
zachdoxsee 34e99b3745 Move the changelog entry down the list
Every merge to main adds its entry at the head of the Added list, and so did
this branch, so each of those merges put this branch in conflict over one
line. The entry is unchanged; it now sits lower down, in a place of its own.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:01 +01:00
zachdoxsee d5fa319f56 Move the changelog entry down the list
Every merge to main adds its entry at the head of the Added list, and so did
this branch, so each of those merges put this branch in conflict over one
line. The entry is unchanged; it now sits lower down, in a place of its own.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:00 +01:00
zachdoxsee e5d83e87ac Move the changelog entry down the list
Every merge to main adds its entry at the head of the Added list, and so did
this branch, so each of those merges put this branch in conflict over one
line. The entry is unchanged; it now sits lower down, in a place of its own.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:00 +01:00
zachdoxsee 985d3b9e78 Move the changelog entry down the list
Every merge to main adds its entry at the head of the Added list, and so did
this branch, so each of those merges put this branch in conflict over one
line. The entry is unchanged; it now sits lower down, in a place of its own.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:00 +01:00
zachdoxsee 0929d0214b Move the changelog entry down the list
Every merge to main adds its entry at the head of the Added list, and so did
this branch, so each of those merges put this branch in conflict over one
line. The entry is unchanged; it now sits lower down, in a place of its own.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:00 +01:00
zachdoxsee 43f8287c92 Merge task/400-standard-output (with upstream main) into task/402-crt-files
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:10:52 +01:00
zachdoxsee a91c7fa39d Merge task/329-gate-a1 (with upstream main) into task/395-crt-exit
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:10:52 +01:00
zachdoxsee 22425287e2 Merge upstream main into task/392-program-arguments
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:10:46 +01:00
zachdoxsee 874c7c7a63 Merge upstream main into task/400-standard-output
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:10:46 +01:00
zachdoxsee f30e4af4eb Merge upstream main into task/388-must-exist-stubs
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:10:46 +01:00
zachdoxsee 501117c4d8 Merge upstream main into task/378-fninit
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:10:46 +01:00
zachdoxsee 3d796f51cf Merge upstream main into task/382-crt-startup
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:10:46 +01:00
zachdoxsee 66f7127553 Merge upstream main into task/329-gate-a1
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:10:46 +01:00
Ranveer Soni 714eaf49e2 Merge pull request #330 from devil8blade/cursor/shader-const-fold-141-5c9c
shader: opt-in IR constant folding with known-answer tests (#141)
2026-11-25 06:40:20 +05:30
devil8blade c93b505223 shader: opt-in IR constant folding with known-answer tests (#141)
Add CompileOptions::fold_constants and compile_with so pure vector unary
and binary ops between constants can fold after verification. Default
compile keeps the historical IR. Floating-point folding still uses the
exact positive-normal rules. Covered by hand-computed known-answer tests
and a fold-on versus fold-off check.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-25 01:05:13 +00:00
Ranveer Soni d8f7f2cb13 Merge pull request #380 from vedantdadhich21/fix/noncanonical-address-gp
fix(loader): raise GP for non-canonical data addresses (#379)
2026-11-25 06:34:40 +05:30
Ranveer Soni 042c08c855 Merge pull request #337 from zachdoxsee/task/333-pe-headers
loader: map the PE headers at the image base (#333)
2026-11-25 06:33:39 +05:30
Ranveer Soni 7e4ccd1e97 Merge pull request #316 from soggyramennoodle/feat/runtime-fuzz-bench
Runtime fuzzing, dispatch benchmarks, CRT string scans and MSVC name decoding
2026-11-25 06:32:53 +05:30
Ranveer Soni 96c772edc5 Merge pull request #398 from maridogolpeador/loader/121-shld-shrd
loader: add SHLD and SHRD, the double-precision shifts (#121)
2026-11-25 06:31:45 +05:30
zachdoxsee 0236ec6ba9 loader: a failed fopen leaves the drive untouched (#402)
fopen created a missing file before it allocated the FILE object, so a
failed allocation left an empty file behind. The FILE object is now
allocated first and released again if the drive cannot take the file.
A test fills the heap and checks that neither a new file appears nor an
existing one loses its contents.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:00:04 +01:00
zachdoxsee 48d22f533b Merge task/329-gate-a1 (with upstream main) into task/395-crt-exit
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:57:12 +01:00
zachdoxsee 52e7e3808d Merge task/400-standard-output (with upstream main) into task/402-crt-files
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:57:12 +01:00
zachdoxsee 464393e02a Merge upstream main into task/400-standard-output
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:56:59 +01:00
zachdoxsee aae04a2956 Merge upstream main into task/392-program-arguments
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:56:51 +01:00
zachdoxsee 721073169c Merge upstream main into task/388-must-exist-stubs
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:56:51 +01:00
zachdoxsee 26148f49f6 Merge upstream main into task/378-fninit
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:56:51 +01:00
zachdoxsee e81382de37 Merge upstream main into task/382-crt-startup
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:56:51 +01:00
zachdoxsee 496938aef4 Merge upstream main into task/333-pe-headers
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:56:51 +01:00
zachdoxsee 9d94c0f40a Merge upstream main into task/329-gate-a1
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:56:40 +01:00
zachdoxsee 4e18000798 Merge upstream main into task/329-gate-a1
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:56:31 +01:00
Ranveer Soni 8c188b04c9 Merge pull request #377 from katherinebytes/codex/cpu-differential-corpus
Test 524 seeded x86-64 programs on the interpreter and native DBT
2026-11-25 06:24:35 +05:30
Ranveer Soni 9eb75522f0 Merge pull request #375 from Arths17/test/194-c7-immediate-store
test: add known answers for C6 and C7 immediate stores (#194)
2026-11-25 06:23:04 +05:30
Ranveer Soni 3f41f7406b Merge pull request #339 from jelly013/phase3b-runtime
runtime: add a deterministic guest thread scheduler (#323, part 1)
2026-11-25 06:22:00 +05:30
zachdoxsee 1c8d7a40de loader: add files for a hosted C program: fopen, fclose, fgets and perror (#402)
A program built with the mingw-w64 runtime imports fopen, fclose, fgets
and perror, and writes to the stream fopen returns with fprintf, fwrite
and fputs. The four did not resolve, and the output functions accepted
only stdout and stderr.

Adds the four services and file streams for the output functions. 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. Text mode,
the default, translates line ends as the fopen documentation describes.

Built on the standard streams from #400. Part of Gate A2.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:49:52 +01:00
zachdoxsee afe8d16d9e loader: add standard output and printf formatting for a hosted C program (#400)
A program built with the mingw-w64 runtime prints through
__stdio_common_vfprintf on the stream __acrt_iob_func(1) returns, and
through fwrite, fputs, fflush and setvbuf. None resolved, and there was
nowhere for standard output to go that a host or a test could read.

Adds a formatting engine for the narrow printf family (d, i, u, o, x, X,
c, s, p and %% with their flags, width, precision and size prefixes), the
three standard streams, those six services, and capture of stdout and
stderr through ServicesState. Floating-point and wide conversions, a
locale, files and input are not modelled and stop the guest.

The engine is compared with the host C library's snprintf on 2,600
generated cases whose result ISO C defines.

Part of Gate A2.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:25:20 +01:00
maridogolpeador 67023d292b loader: add SHLD and SHRD, the double-precision shifts (#121)
Both engines refused SHLD and SHRD (0F A4/A5, 0F AC/AD) as illegal
instructions. They are now declared in the x86 registry and run on the
shared semantics for 16-, 32- and 64-bit register and memory
destinations, with the count in an 8-bit immediate or in CL.

- instructions.toml, x86_table.rs (generated), generate_x86.py,
  x86_decode.rs: the two operations and two operand encodings,
  rm_reg_imm and rm_reg_cl (ModRM destination, reg source, count).
- x86_exec.rs: the destination is shifted with the vacated bits filled
  from the source register. The count is masked to five bits (six for
  64-bit operands), a masked count of zero changes nothing, CF takes the
  last bit shifted out, ZF/SF/PF follow the result and OF is set only
  for a count of one. A 16-bit count above 16 is undefined in the SDM;
  the flags are kept and no test relies on the result.
- cpu_known_answers.rs: eight SDM-derived cases move from refused to
  verified.
- tests/x86: 72 assembled SHLD and SHRD instructions, with a
  bit-at-a-time reference in x86_integer.rs. A destination the
  reference marks undefined now skips the memory operand check too.
- docs/cpu/instruction-registry.md, CHANGELOG.md.

Nothing is lowered to ARM64.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-24 20:47:45 -03:00
zachdoxsee d326e929a9 loader: add exit, _exit and abort for a hosted C program (#395)
A C program ends through the C runtime's exit, not ExitProcess, and a
program built with the mingw-w64 runtime imports exit, _exit and abort.
None resolved, so the loader refused the program before its entry point.

exit calls the functions registered with atexit and _crt_atexit, most
recently registered first, then ends the guest with ProcessExit(status).
_exit ends it with its status and abort with exit code 3; neither calls a
registered function. All three use the cleanup behind ExitProcess.

Built on the process exit from #329. Part of Gate A2.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 00:47:33 +01:00
Adeeb Rahman 324eab08c3 Merge remote-tracking branch 'origin/main' into feat/runtime-fuzz-bench
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 18:32:27 -05:00
Bartosz Szczepański 149869a053 loader: run LOOP, LOOPE, LOOPNE and JRCXZ (#396)
The four rel8 forms E0 to E3 are declared in the instruction registry and
run through the shared semantics in both engines (Intel SDM Vol. 2A,
LOOP/LOOPcc and Jcc). The count is RCX: LOOP decrements it without
changing a flag and branches while the result is not zero, LOOPE also
needs ZF set and LOOPNE ZF clear, and JRCXZ branches on a zero RCX and
changes nothing. Each ends a translated block. The address-size prefix
stays rejected, so JECXZ and the ECX-counted forms are still refused.

The three known answers recorded as refused by #155 are verified, with
eleven more cases. 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, and JRCXZ against every single-bit RCX value.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-25 00:12:33 +01:00
katherinebytes a6b0e89cac Pack block-compressed texture mip chains by subresource
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 22:40:57 +00:00
zachdoxsee 32251af4c8 loader: add program arguments for a hosted C program (#392)
A program built with the mingw-w64 runtime gets argc, argv and envp for
main from __p___argc, __p___argv, __p__environ, _configure_narrow_argv
and _initialize_narrow_environment. None resolved, so the loader refused
the program before its entry point, and a host could not say what the
program's arguments are.

The five services are added to the typed registry, and
ServicesState::set_program_arguments lets a host supply argv. The
environment table is empty.

Part of Gate A2.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 23:40:27 +01:00
Bartosz Szczepański 1c6bd25723 loader: run LAHF and SAHF and report them in CPUID (#387)
LAHF (9F) and SAHF (9E) are declared in the instruction registry and run
through the shared semantics in both engines (Intel SDM Vol. 2A LAHF,
Vol. 2B SAHF): LAHF writes AH = SF:ZF:0:AF:0:PF:1:CF and keeps the rest of
RAX, SAHF loads SF, ZF, AF, PF and CF from AH and leaves OF unchanged.
With both implemented, guest CPUID reports leaf 8000_0001h ECX bit 0.

The four known answers recorded as refused by #155 are verified, with
twelve more cases. Both instructions join the clang-assembled integer
fixtures and the independent bit-level reference, and cpu_features.rs
moves LAHF/SAHF from the refused witnesses to the reported features.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 23:32:17 +01:00
zachdoxsee 007ad360e9 loader: add VirtualProtect, VirtualQuery and __C_specific_handler as stubs (#388)
A program built with the mingw-w64 runtime imports all three and does not
call them on a normal run. Without them the loader refused the program
before its entry point.

They are declared stub in the typed registry. A call stops the guest with
the runtime-limit fault and writes nothing, so a program that needs one
stops there and cannot run on with a made-up result.

Part of Gate A2.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 23:30:09 +01:00
Bartosz Szczepański 0d6cef6c4e loader: raise #GP for instructions longer than 15 bytes (#384)
The shared decoder already stopped before fetching a 16th byte, but it
reported the instruction as unsupported, so both engines exited with an
illegal instruction. It now returns DecodeError::TooLong, which maps to
ExitReason::GeneralProtection (Intel SDM Vol. 3A, 7.15). The DBT retries a
block that fails this way one instruction at a time, as it already does for
illegal instructions and fetch faults, so earlier instructions in the block
complete and the fault reports the overlong instruction's RIP.

The known answer recorded as a defect by #155 is enabled, with three more
cases, and two page-end tests check that no 16th byte is fetched.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 23:16:49 +01:00
zachdoxsee 64a0cb1596 loader: add nine C runtime startup services a hosted C program imports (#382)
A program built with the mingw-w64 runtime imports _set_app_type,
_set_new_mode, _configthreadlocale, __setusermatherr,
_set_invalid_parameter_handler, __p__fmode, __p__commode, signal and
SetUnhandledExceptionFilter, and memcpy through
api-ms-win-crt-private-l1-1-0.dll. None resolved, so the loader refused
the program before its entry point.

Each service records what it is given and returns what its public
documentation says. Nothing acts on a recorded value yet, so all nine
are declared partial in the typed registry.

Part of Gate A2.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 23:14:10 +01:00
Bartosz Szczepański 53e5e38a4e bench: compare two dbt_bench JSON results (#114)
With XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json> set,
dbt_bench reads two documents written through XENORA_DBT_BENCH_JSON and
compares them instead of running. For the interpreter and cold and warm
DBT it prints both medians, the change, and whether the change exceeds
the larger recorded IQR, and it lists changed cold DBT counters.

It refuses, with exit status 1 and the differing field named, to compare
runs whose CPU, OS or architecture differ or are unknown, or whose
workload, sample or warmup counts, debug assertions or build label
differ. The new optional XENORA_DBT_BENCH_BUILD_LABEL records build
settings the benchmark cannot observe, such as LTO; version 1 documents
without it count as unlabelled.

The documents are read by a small RFC 8259 reader in the bench file, so
no dependency is added. Unit tests cover the reader, reading back an
exported document, the report lines, and every refusal rule.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 23:08:04 +01:00
zachdoxsee 47a819e05b loader: add FNINIT and the x87 control, status and tag words (#378)
The decoder refused FNINIT (DB E3), which the mingw-w64 C runtime runs
once before main. Guest state gains the x87 control, status and tag
words, and FNINIT sets them to the Intel SDM values 037F, 0 and FFFF.
Both engines run the shared semantics.

The registry gains a form key, rm, that pins a register-only form to one
ModRM byte: the other bytes of DB /4 are different instructions. No other
x87 instruction is added and CPUID still reports no FPU.

Part of Gate A2.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 23:01:33 +01:00
Guillaume Demay 7d28fc89de loader: avoid resolver allocations for contiguous data access
Signed-off-by: Guillaume Demay <guillaumedemay@hotmail.fr>
2026-11-24 22:56:32 +01:00
Vedant Dadhich 9a29bd9c37 fix(loader): raise GP for non-canonical data addresses
Check canonical 48-bit address ranges in shared interpreter accesses, 16-byte SIMD paths, and every native DBT memory helper. Enable and expand the architectural known-answer group across operand widths, vector accesses, segment-base wrapping, boundary crossings, and valid canonical endpoints.

Signed-off-by: Vedant Dadhich <vedantdadhich21@gmail.com>
2026-11-25 03:21:14 +05:30
jelly013 38359969cd Merge main into phase3b-runtime
Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 22:44:09 +01:00
zachdoxsee 652c6ae02f Merge upstream main into the C6/C7 immediate-store tests branch
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 22:24:27 +01:00
zachdoxsee 0529c62226 Merge upstream main into task/333-pe-headers
Any conflict was in CHANGELOG.md, where every entry is kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 22:24:13 +01:00
zachdoxsee e6fa931264 Merge upstream main into task/329-gate-a1
Any conflict was in CHANGELOG.md, where every entry is kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 22:24:13 +01:00
Zach Doxsee 3b47c21bb0 Merge pull request #348 from 1Bartosz/cpu/195-adc-sbb-dbt
loader: run ADC and SBB register and immediate forms natively in the DBT (#195)
2026-11-24 22:20:44 +01:00
Zach Doxsee 9a62d86a89 Merge pull request #362 from katherinebytes/codex/metal-compute-pipeline-cache
Reuse bounded Metal compute pipelines
2026-11-24 22:20:29 +01:00
Zach Doxsee 4b32c532fe Merge pull request #370 from vedantdadhich21/fix/portable-gpu-timeout
Scripts: run GPU tests without GNU timeout
2026-11-24 22:20:20 +01:00
Arthur Lacoste af1b84ad75 loader: fix needless_range_loop in Win64 ABI tests (#201)
Address review feedback from zachdoxsee on PR #369: replace index-only XMM range loops with iterator-based loops so strict clippy passes on Rust 1.100.

Signed-off-by: Arthur Lacoste <arthurlacoste@users.noreply.github.com>
2026-11-24 22:14:29 +01:00
Arthur Lacoste cf438e25aa Merge remote-tracking branch 'origin/main' into runtime/win64-service-abi-201
# Conflicts:
#	CHANGELOG.md
2026-11-24 22:13:14 +01:00
katherinebytes bd46504a97 Add a seeded CPU differential corpus
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 21:11:03 +00:00
zachdoxsee cc4dd092cf Merge upstream main into task/333-pe-headers
Any conflict was in CHANGELOG.md, where every entry is kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 22:01:29 +01:00
zachdoxsee 04ee981103 Merge upstream main into task/329-gate-a1
Any conflict was in CHANGELOG.md, where every entry is kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 22:01:29 +01:00
Zach Doxsee bbc84c0da0 Merge pull request #373 from 1Bartosz/bench/112-json-export
bench: export dbt_bench results as JSON (#112)
2026-11-24 21:57:25 +01:00
Bartosz Szczepański d2f77cdea3 Merge upstream main into cpu/195-adc-sbb-dbt
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 21:55:01 +01:00
Zach Doxsee 3a36379db4 Merge pull request #342 from Swastickc/qa/cpu-test-selection-159
qa: measure CPU test runtime and add deterministic test-target shards (#159)
2026-11-24 21:53:45 +01:00
Zach Doxsee 147e2a9f1a Merge pull request #372 from GDemay/perf/104-allocation-free-fetch
loader: avoid allocations when fetching instruction bytes
2026-11-24 21:53:30 +01:00
katherinebytes a7fa8b0d65 Retry the ARM64 CI run
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 20:47:35 +00:00
zachdoxsee fd0e73bc28 Merge upstream main into task/333-pe-headers
Conflict in CHANGELOG.md only: every entry is kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 21:43:49 +01:00
zachdoxsee 35de41bd5f Merge upstream main into task/329-gate-a1
Conflict in CHANGELOG.md only: every entry is kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 21:43:49 +01:00
Zach Doxsee e6b657a2e9 Merge pull request #341 from sahib453/task/175-page-boundary-faults
loader: report the first inaccessible byte of a page-crossing guest fault (#175)
2026-11-24 21:43:08 +01:00
Zach Doxsee c05e631c6d Merge pull request #343 from sahib453/task/78-tls-callback-metadata
loader: reject malformed TLS callback metadata and unusable callback stacks (#78)
2026-11-24 21:42:51 +01:00
atharvranjan 6bac25f099 test: add known answers for C6 and C7 immediate stores (#194)
Covers byte to qword widths, SIB and displacement forms, imm32 sign extension, register forms and store faults. Both engines already agree.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 14:35:48 -06:00
plokhi d35c278284 Clarify ARM64 encoding audit coverage
Signed-off-by: plokhi <37208555+Plokhi@users.noreply.github.com>
2026-11-24 21:33:37 +01:00
Zach Doxsee 34a583b101 Merge pull request #356 from sahib453/task/76-tls-pointer-array
loader: give the thread a TLS pointer array separate from its data (#76)
2026-11-24 21:32:15 +01:00
Bartosz Szczepański 061c28b405 bench: export dbt_bench results as JSON (#112)
dbt_bench printed its results only as text. With
XENORA_DBT_BENCH_JSON=<path> set it now also writes one JSON document:
host CPU, OS and architecture, git revision and dirty state, debug
assertions, the workload and sample counts, median, min, max, p95, p99,
IQR and MIPS for the interpreter and cold and warm DBT, and the cold
DBT counters. Values the benchmark cannot determine are null.

The statistics are computed once in a Summary that feeds both the text
line and the JSON, so the two cannot disagree. The text output and the
timed work are unchanged, and no dependency is added.

Unit tests cover string escaping, null handling, the whole document for
fixed inputs and the text line format.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 21:22:58 +01:00
zachdoxsee 3b52215a30 Merge upstream main into task/175-page-boundary-faults
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 21:20:41 +01:00
Guillaume Demay 0214a7bab5 loader: avoid allocations when fetching instruction bytes
Signed-off-by: Guillaume Demay <guillaumedemay@hotmail.fr>
2026-11-24 21:20:28 +01:00
plokhi fbec436b89 Fix ARM64 variable shift register encoding
Signed-off-by: plokhi <37208555+Plokhi@users.noreply.github.com>
2026-11-24 21:19:38 +01:00
zachdoxsee 47b526fba9 Merge the TLS pointer array branch into task/78-tls-callback-metadata
Brings in #356, which is merged first, along with main. Conflicts:
CHANGELOG.md, where every entry is kept, and crates/loader/src/tls.rs,
where the new read_callbacks function and the TLS_ARRAY_SIZE constant
were added at the same place; both are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 21:19:10 +01:00
zachdoxsee c68e3ccb4c Merge upstream main into task/78-tls-callback-metadata
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 21:17:57 +01:00
atharvranjan e856f080d1 dbt: retranslate cached blocks when guest code changes (#84)
Each cached block keeps the guest bytes it was translated from and is compared with the current executable bytes on every lookup.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 14:17:40 -06:00
zachdoxsee fb6282ceb2 Merge upstream main into task/76-tls-pointer-array
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 21:16:38 +01:00
Zach Doxsee bb6a9f6912 Merge pull request #361 from sahib453/task/125-movnti
loader: add MOVNTI, the non-temporal store of a general register (#125)
2026-11-24 21:15:11 +01:00
Zach Doxsee a7e3e1e42c Merge pull request #358 from sahib453/task/199-fences
loader: accept MFENCE, LFENCE and SFENCE and document guest memory ordering (#199)
2026-11-24 21:14:51 +01:00
Zach Doxsee 9c76bf16f0 Merge pull request #357 from Arths17/test/205-handle-lifetime
test: cover guest handle lifetime and failed-call nonmutation (#205)
2026-11-24 21:14:37 +01:00
Vedant Dadhich 2f28a5adbb Scripts: run GPU tests without GNU timeout
stock macOS does not provide the timeout command used by scripts/test-gpu.sh. Add a Python 3 fallback that preserves duration parsing, process-group termination and exit status 124, while continuing to use GNU timeout when it is available.

Signed-off-by: Vedant Dadhich <vedantdadhich21@gmail.com>
2026-11-25 01:38:11 +05:30
Bartosz Szczepański 788de1e83b Merge upstream main into cpu/195-adc-sbb-dbt
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 21:08:00 +01:00
Zach Doxsee 7dd1329866 Merge pull request #367 from jelly013/probe-default-folder
cli: use a neutral default folder for probe reports (#364)
2026-11-24 21:07:02 +01:00
Zach Doxsee 4b579af70d Merge pull request #360 from 1Bartosz/perf/116-release-lto
build: use fat LTO and one codegen unit for release builds (#116)
2026-11-24 21:06:47 +01:00
zachdoxsee b4f45573cf Merge the updated fences branch into task/125-movnti
Brings the branch up to main after #366 and #368, with #358, which is
merged first. No conflicts.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 21:05:39 +01:00
zachdoxsee 0766307acc Merge upstream main into task/199-fences
Brings the branch up to main after #366 and #368. No conflicts.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 21:05:39 +01:00
Zach Doxsee 9dfdfd1134 Merge pull request #365 from Arths17/fix/363-native-audit-utf8
Read native audit JSON as UTF-8
2026-11-24 21:05:34 +01:00
zachdoxsee ce8d16e367 Merge upstream main into test/205-handle-lifetime
Conflict in CHANGELOG.md only: both new entries are kept.

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

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 21:02:54 +01:00
Zach Doxsee 3c8b6bad97 Merge pull request #366 from vedantdadhich21/fix/gpu-semantic-timeout
Scripts: allow longer Metal semantic-review runs
2026-11-24 21:01:35 +01:00
Zach Doxsee d4c29cd7dd Merge pull request #368 from izdat-sl4w/fix/unsigned-jcc-boundaries
cpu: pin the unsigned Jcc conditions at their boundaries
2026-11-24 20:59:17 +01:00
Arthur Lacoste 7246ab5ea6 loader: add Win64 service ABI preservation tests (#201)
Add dispatch and DBT-backed runtime service tests that verify Win64 callee entry alignment, caller-owned shadow space, return state, and preservation of nonvolatile GPRs/XMM registers across registered service calls.

AI-Assisted: Codex (GPT-5) helped draft the tests; I reviewed the diff and ran fmt/clippy(loader)/loader tests locally.
Signed-off-by: Arthur Lacoste <arthurlacoste@users.noreply.github.com>
2026-11-24 20:57:41 +01:00
zachdoxsee 938cbd3028 Merge upstream main and the fences branch into task/125-movnti
Conflicts: CHANGELOG.md and the rejected-encodings list in
x86_integer.rs, where both sides are kept; the case list in
tests/x86/assemble.py, which now has the fences followed by MOVNTI; and
the generated x86_table.rs and tests/x86/integer.txt, rebuilt with
generate_x86.py and assemble.py from the merged sources.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 20:56:21 +01:00
zachdoxsee c9505e53e2 Merge upstream main into task/199-fences
Conflicts: CHANGELOG.md, where both entries are kept; the generated
crates/loader/src/x86_table.rs, rebuilt with generate_x86.py from the
merged instructions.toml; and one sentence of
docs/cpu/instruction-registry.md, where the list of rejected
instructions now drops both RCL/RCR (from #351) and the fences.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 20:54:40 +01:00
Zach Doxsee 02eb8046a1 Merge pull request #355 from sahib453/task/118-xchg-accumulator
loader: add the accumulator short form of XCHG (#118)
2026-11-24 20:46:47 +01:00
Zach Doxsee 4a0b5d4ded Merge pull request #344 from sahib453/task/128-exact-unmasked-overflow
loader: set only the overflow flag for an exact unmasked overflow (#128)
2026-11-24 20:46:33 +01:00
atharvranjan 00eb6971e9 Preserve UTF-8 native inspection output
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 13:45:16 -06:00
Bartosz Szczepański c3b0025977 Merge upstream main into perf/116-release-lto
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 20:44:30 +01:00
Bartosz Szczepański 1013746e17 Merge upstream main into cpu/195-adc-sbb-dbt
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 20:44:24 +01:00
izdat-sl4w 7c88e5d655 cpu: pin the unsigned Jcc conditions at their boundaries
The native DBT had no test for the 0x70..=0x7F or the 0F 80..=8F block
at all. These four conditions are the ones an ARM64 condition code
cannot provide directly: SUBS sets C when a subtraction does not
borrow, so x86 CF is its inverse, and ARM64's HI and LS are defined on
that same inverted carry.

Three tests derive CF and ZF from the operands (Intel SDM Volume 1,
3.4.3.1), then check JB, JAE, JBE and JA in the short and the near
encoding at both ends of the 32-bit and 64-bit ranges, with SUB as well
as CMP, and with the compare and the branch in separate translated
blocks. Inverting the borrow polarity in the lowering makes all three
fail.

Closes #64

Signed-off-by: izdat-sl4w <76667566+izdat-sl4w@users.noreply.github.com>
2026-11-24 20:43:54 +01:00
zachdoxsee bb318ed2ba Merge upstream main into task/118-xchg-accumulator
Conflicts in CHANGELOG.md, where both new entries are kept, and in the
generated crates/loader/src/x86_table.rs, which is rebuilt with
generate_x86.py from the merged instructions.toml.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 20:41:29 +01:00
zachdoxsee b1b57cf16a Merge upstream main into task/128-exact-unmasked-overflow
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 20:40:31 +01:00
Zach Doxsee cdcc55c33e Merge pull request #351 from sahib453/task/121-rcl-rcr
loader: add RCL and RCR, the rotates through carry (#121)
2026-11-24 20:39:46 +01:00
Zach Doxsee 0730f4dbbf Merge pull request #353 from sahib453/task/69-rex-before-prefix
loader: ignore a REX prefix that is followed by a legacy prefix (#69)
2026-11-24 20:39:22 +01:00
Zach Doxsee 6f27da3ccc Merge pull request #354 from 1Bartosz/perf/92-imm-materialization
loader: load ARM64 constants with the fewest wide moves (#92)
2026-11-24 20:39:00 +01:00
zachdoxsee 6236996f41 Merge upstream main into perf/92-imm-materialization
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 20:32:35 +01:00
Zach Doxsee 05f2526d27 Merge pull request #345 from katherinebytes/codex/dbt-benchmark-percentiles
Report p95, p99 and IQR in the DBT benchmark
2026-11-24 20:31:23 +01:00
jelly013 e5aca73c55 cli: use a neutral default folder for probe reports
`xenora probe` and `xenora imports sync` defaulted to a folder named after
one commercial game. Give both one shared default, `diagnostics/probe`, and
ignore it in Git. Keep the old ignore rules so existing local reports stay
out of commits.

Closes #364

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 20:31:13 +01:00
atharvranjan 281d92bfb5 Read native audit JSON as UTF-8
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 13:28:35 -06:00
Zach Doxsee 5131de9cd6 Merge pull request #350 from katherinebytes/codex/bc1-tile-row-linearization
Copy tiled BC1 data by tile row
2026-11-24 20:27:49 +01:00
Vedant Dadhich fec13fa27a Scripts: allow longer Metal semantic-review runs
The full semantic-review batch can exceed the hard-coded 120-second timeout on a cold Apple Silicon host. A local M1 acceptance run exited 124 while tests were still progressing; the same batch passed with a longer limit. Add XENORA_SEMANTIC_TIMEOUT, default it to 300 seconds, and document the override.

Signed-off-by: Vedant Dadhich <vedantdadhich21@gmail.com>
2026-11-25 00:57:15 +05:30
katherinebytes 68503a674c Explain DBT benchmark medians and test invocation
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 19:23:26 +00:00
katherinebytes 82cb66e80f Document the BC1 tile row bounds
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 19:23:26 +00:00
katherinebytes 06dbe2946d Merge upstream main for the DBT benchmark
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 19:22:23 +00:00
zachdoxsee 685217e61b Merge upstream main into task/333-pe-headers
Conflict in CHANGELOG.md only: every entry is kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 20:21:39 +01:00
zachdoxsee a0d4b7bf5d Merge upstream main into task/329-gate-a1
Conflict in CHANGELOG.md only: every entry is kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 20:21:39 +01:00
zachdoxsee 14d5083f0f Merge upstream main into codex/bc1-tile-row-linearization
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 20:20:44 +01:00
Zach Doxsee 0115af5c04 Merge pull request #332 from vedantdadhich21/docs/gfx1030-form-acceptance
Docs: define gfx1030 form acceptance
2026-11-24 20:19:26 +01:00
katherinebytes 9ddb708cdf Merge upstream main for the compute pipeline cache
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 19:15:39 +00:00
Zach Doxsee 5b7ffec90a Merge pull request #347 from Arths17/task/109-relocation-overhead
loader: avoid per-entry relocation histogram lookups
2026-11-24 20:15:11 +01:00
Zach Doxsee 48c5d20aa9 Merge pull request #335 from izdat-sl4w/fix/audit-utf8-locale
audit: read and write tracked files as UTF-8
2026-11-24 20:14:57 +01:00
izdat-sl4w 8049c36f51 audit: pin LF newlines in the generated status writes
Path.write_text opens with newline=None, so on Windows a regeneration
would translate the tracked LF files to CRLF and show a spurious diff.
Both write sites now pass newline="\n", which leaves the bytes
identical on macOS and Linux.

Signed-off-by: izdat-sl4w <76667566+izdat-sl4w@users.noreply.github.com>
2026-11-24 20:14:45 +01:00
sahib453 94783fa603 docs: take the fences off the rejected-on-purpose list (#199)
The instruction registry document listed fences among the forms
rejected on purpose. This branch accepts them and explains why in the
new memory-ordering section, so the list no longer names them.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-25 00:44:40 +05:30
izdat-sl4w c91036f879 Merge main into fix/audit-utf8-locale
Signed-off-by: izdat-sl4w <76667566+izdat-sl4w@users.noreply.github.com>
2026-11-24 20:14:30 +01:00
sahib453 c1cea65e17 docs: take RCL and RCR off the rejected-on-purpose list (#121)
The instruction registry document listed RCL and RCR among the forms
rejected on purpose. This branch implements them, so the list no longer
names them. SHLD and SHRD stay on it.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-25 00:44:28 +05:30
atharvranjan 974d1fc62c ci: retrigger 2026-11-24 13:13:14 -06:00
katherinebytes 6f1ac2a906 Reuse Metal compute pipelines
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 19:12:15 +00:00
sahib453 223a754eb7 loader: add MOVNTI, the non-temporal store of a general register (#125)
Both engines refused MOVNTI (0F C3 /r) as an illegal instruction. It is
the SSE2 move still missing next to the XMM moves already implemented.

- instructions.toml, x86_table.rs (generated): MOVNTI for 32- and
  64-bit operands with a memory destination only.
- x86_exec.rs: an ordinary store of the register, as the other
  non-temporal stores already are.
- cpu_known_answers.rs: the SDM-derived case that ends in a MOVNTI
  moves from refused to verified.
- tests/x86: four assembled instructions with the text-only reference;
  the register form and the 66 prefix join the rejected encodings.

MASKMOVDQU stays rejected and SSE2 stays unreported by CPUID.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-25 00:40:02 +05:30
Bartosz Szczepański 3d19c756e2 build: use fat LTO and one codegen unit for release builds (#116)
Release and bench builds used Cargo's defaults: no cross-crate LTO and
16 codegen units. Fat LTO with a single codegen unit lets the
interpreter and DBT hot paths inline across crates.

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

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 20:08:43 +01:00
Swastickc 729e1b4cb1 loader: draw nothing for zero-instance flat draws and reject unsupported ones (#148)
Flat DrawInstanced ignored InstanceCount, StartInstanceLocation and
StartVertexLocation, so a zero-instance draw still drew and a changed
start vertex drew the first triangle. Zero instances or fewer than three
vertices now draw nothing; other unsupported parameters fail with
GraphicsError::Unsupported. Vertex reads use the range-checked
read_resource, so a view past its buffer or an overflowing guest address
fails with IndexOutOfRange.

Add tests/repeated_frames.rs: repeated reset, record, close and execute
frames with hand-derived pixels on the software reference backend.

Signed-off-by: Swastickc <28708247+Swastickc@users.noreply.github.com>
2026-11-25 00:34:19 +05:30
sahib453 d195978903 loader: accept MFENCE, LFENCE and SFENCE and document guest memory ordering (#199)
Both engines refused the three fences as illegal instructions, and no
document said what ordering guest memory accesses have.

- instructions.toml, x86_table.rs (generated): the register forms of
  0F AE digits 5, 6 and 7. The memory forms stay undeclared.
- x86_exec.rs: a fence changes nothing. Each engine runs one guest
  instruction at a time on one host thread and completes its loads and
  stores before the next, so accesses are already totally ordered.
- docs/cpu/instruction-registry.md: states that ordering, why the
  fences are no-ops under it, and that it holds only while guest
  threads do not run on several host threads.
- Tests: five single-thread known-answer cases, three assembled
  fixtures, two rejected memory forms, and MASKMOVDQU as the refused
  SSE2 instruction in cpu_features.rs now that MFENCE runs.

No multi-thread behaviour is established.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-25 00:25:27 +05:30
zachdoxsee 830f93ff14 loader: address review of process exit and the Gate A1 program (#329)
- An ExitProcess call in a TLS callback is a normal startup outcome with
  its status. The remaining callbacks and the entry point do not run.
- Exit closes Winsock sockets and task-queue handles as well as kernel
  objects, and open_handle_count counts all three tables.
- Startup reserves the page holding the entry-return and callback-return
  addresses, so an image mapped over them is refused and a guest
  allocation there fails.
- The Gate A1 program checks unequal memcmp results and compares the
  bytes it read back without memcmp.
- The gate test builds in a directory of its own per test process.
- The build script checks its tools and their libraries with file,
  lipo -archs and otool -L.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 19:55:20 +01:00
zachdoxsee 4962f054c8 Merge upstream main into task/329-gate-a1
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 19:47:49 +01:00
zachdoxsee 67dfb18166 loader: address review of the PE header mapping (#333)
- Check the mapping budget before anything is mapped, and map the header
  bytes straight from the file instead of copying them first.
- Refuse bytes that are not the PE32+ headers that were parsed: the
  optional header magic and size, the section count, the preferred base
  and SizeOfHeaders must agree before anything is patched.
- Write the load base into the mapped ImageBase field after relocations
  are applied, so a DIR64 entry aimed at that field cannot move it twice.
- Describe the ImageBase rewrite as Xenora's policy, and document the
  zero fill past SizeOfHeaders and the stricter page rule.

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

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

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-25 00:17:10 +05:30
Arths17 6106c37912 test: cover guest handle lifetime and failed-call nonmutation
Signed-off-by: Arths17 <166588440+Arths17@users.noreply.github.com>
2026-11-24 12:46:32 -06:00
zachdoxsee d2491dee07 Merge upstream main into task/333-pe-headers
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 19:43:39 +01:00
sahib453 823a5812a0 loader: add the accumulator short form of XCHG (#118)
Both engines refused XCHG with the register in the opcode (91 to 97,
and 90 with REX.B) as an illegal instruction. Assemblers choose this
form whenever one operand is the accumulator.

- instructions.toml, x86_table.rs (generated): one form per opcode 91
  to 97. A row of eight would have to start at 90, which is NOP.
- x86_decode.rs: 90 stays NOP without REX.B and decodes as the 91 form
  with register r8 when REX.B is set. F3 before it is rejected.
- x86_exec.rs: exchange the accumulator with the named register at 16,
  32 and 64 bits.
- cpu_known_answers.rs: three SDM-derived cases move from refused to
  verified.
- tests/x86: 20 assembled instructions, checked by the existing
  text-only reference. `xchg r8, rax` leaves the rejected list.

Nothing is lowered to ARM64.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-25 00:09:31 +05:30
jelly013 c1ca4ea140 runtime: fix timed waits, continued runs and budget accounting
Let a wait whose deadline has passed time out instead of taking a later
signal. Keep the main thread's pending wait, with its objects and deadline,
when a run that stopped on its budget continues from the same context. Count
every call that ends a turn, and neither sleep nor report a deadlock with a
spent budget.

Retry blocked threads again when one of them ends in the pass, so that a
thread waiting for it is not reported as deadlocked or timed out. Refuse to
open an ended main thread by its ID. Test that a second scheduler cannot
attach while one runs.

Addresses review of #339.
Refs #323

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 19:34:59 +01:00
Bartosz Szczepański 710a2e1e73 loader: load ARM64 constants with the fewest wide moves (#92)
load_imm_64 emitted MOVZ for halfword 0 and then MOVK for zero
halfwords it could skip, and never used MOVN, so a small negative
constant took four instructions. It now starts from MOVZ or MOVN,
whichever leaves more halfwords already correct, at the first halfword
that differs, and adds MOVK only for the remaining differing halfwords.

On Apple M5 the DBT benchmark emits 245,168 instead of 290,184 native
bytes for its 626 blocks (-15.5%) and the 1,048 integer fixture
instructions 128,724 instead of 145,732 (-11.7%). Benchmark run times
did not change measurably.

Tests check the sequences against llvm-mc encodings and execute the
edge values plus 512 seeded values, in X0 and X9, on the host through
the JIT, checking both the loaded value and the instruction count.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 19:31:02 +01:00
sahib453 de92766b29 loader: ignore a REX prefix that is followed by a legacy prefix (#69)
A REX prefix takes effect only immediately before the opcode (Intel SDM
Vol. 2A, 2.2.1). The decoder took the byte after the first REX as the
opcode, so `48 66 01 D8` was refused as an illegal instruction where it
should run as `add ax, bx`.

- x86_decode.rs: a REX byte followed by an operand-size, address-size,
  segment, LOCK or repeat prefix is dropped and prefix reading goes on.
  The dropped byte still counts toward the instruction length.
- cpu_known_answers.rs: the SDM-derived case moves from refused to
  verified, with three more for an ignored REX.B, an ignored REX.W
  before a segment prefix, and a later REX that does apply.

Two REX bytes in a row and the address-size prefix stay rejected.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-25 00:00:15 +05:30
Swastickc b09d96fd62 bench: measure Metal startup in fresh processes and repeated runs (#178)
Add `xenora-bench startup`. It checks one manifest fixture against the
independent reference, then times it phase by phase in two regimes: a
series of fresh child processes that each create the Metal device and
queue, translate and run the fixture once, and one process that
repeats the run. Phases are launch to main, device and queue,
translation, library, pipeline, submission, GPU and readback, reported
as median, p90, p99 and maximum, with raw fresh samples in launch
order.

Every sample must produce the expected output. A wrong output, a
failed or hung child (killed after 60 s) or a damaged sample line
stops the run before any result is written. Children inherit the
environment so the recorded MTL_* validation state applies to both
regimes.

Document the method and one recorded release run on an Apple M4 in
docs/testing/benchmarks.md, and add a changelog entry. Measurement
only.

Signed-off-by: Swastickc <28708247+Swastickc@users.noreply.github.com>
2026-11-24 23:59:59 +05:30
sahib453 4d44765363 loader: add RCL and RCR, the rotates through carry (#121)
Both engines refused RCL and RCR (group 2, digits 2 and 3) as illegal
instructions. They are now declared in the x86 registry and run on the
shared semantics for 8-, 16-, 32- and 64-bit register and memory
operands, with a count of one, CL or an immediate.

- instructions.toml, x86_table.rs (generated): the two operations, with
  CF as an input.
- x86_exec.rs: rotation over the operand plus CF. The masked count is
  reduced modulo the operand width plus one, CF takes the last bit
  rotated out, and OF is set only for a count of one.
- cpu_known_answers.rs: fourteen SDM-derived cases move from refused to
  verified, and the shift sweep runs both instructions at every width.
- tests/x86: 80 assembled RCL and RCR instructions, with a single-step
  reference in x86_integer.rs. `rcl al, 1` leaves the rejected list.

Nothing is lowered to ARM64. SHLD and SHRD stay rejected.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-24 23:54:26 +05:30
katherinebytes 6de750b152 Copy tiled BC1 data by tile row
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 18:22:19 +00:00
Bartosz Szczepański c95e175210 loader: run ADC and SBB register and immediate forms natively in the DBT (#195)
The DBT now lowers the 32- and 64-bit register and immediate forms of
ADC and SBB to ADCS and SBCS instead of calling the shared semantics.
The guest CF is moved into the host carry first, inverted for SBB
because SBCS subtracts NOT C while SBB subtracts CF. Memory forms and
8- and 16-bit forms stay on the shared semantics.

Adds the ADCS and SBCS encodings to the ARM64 assembler, checked
against llvm-mc, and tests/x86_carry_chain.rs: 256-bit add and
subtract chains of 64- and 32-bit limbs, in one block and split one
block per limb, against widening u128/i128 reference arithmetic in
both engines, plus 128-bit immediate increments and decrements and the
sbb reg, reg carry mask.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 19:12:29 +01:00
atharvranjan adf10db015 loader: build relocation type counts once per image
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 12:04:05 -06:00
Swastickc 6814d78230 metal: budgeted staged RGBA8 texture upload into Private storage (#144)
Add an opt-in staged upload beside the existing direct upload.
plan_staged_upload splits a full RGBA8 upload into submissions of
whole-row bands that never exceed a StagingBudget. It rejects missing,
duplicate or out-of-range mip levels, wrong mip sizes, short row
pitches or byte buffers, and budgets smaller than one row before any
Metal object exists.

MetalRgba8Texture::upload_staged fills a Private-storage texture
through one reused Shared staging buffer with blit copies, and reuses
the buffer only after the previous command buffer completed with
status Completed. read_back copies any mip back as tight RGBA8 bytes
through a blit. A Private texture refuses upload_mip with an error.

Enable objc2-metal's MTLBlitCommandEncoder feature for the blit
encoder; Cargo.lock is unchanged.

Signed-off-by: Swastickc <28708247+Swastickc@users.noreply.github.com>
2026-11-24 23:32:49 +05:30
katherinebytes 4e4a6b36be Report DBT benchmark percentiles and warmup
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 17:55:12 +00:00
sahib453 403a67747f loader: set only the overflow flag for an exact unmasked overflow (#128)
With the overflow exception unmasked, an overflow whose result is exact
before the exponent is bounded set the MXCSR precision flag as well as
the overflow flag. The Intel SDM (Vol. 1, D.4.2.3, Table D-16) reports
precision there only if rounding with an unbounded exponent is inexact.

- softfloat.rs: Control reads the overflow mask, and round() reports
  precision on an unmasked overflow only when the result was rounded.
  The masked response is unchanged.
- cpu_known_answers.rs: the five exact-overflow cases are no longer an
  ignored defect, three more cover the other rounding modes, and the
  scalar and conversion sweeps now compare the precision flag here.
- docs/cpu/instruction-registry.md: the behaviour is no longer listed
  as unasserted.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-24 23:25:07 +05:30
sahib453 509811aad0 loader: reject malformed TLS callback metadata and unusable callback stacks (#78)
The TLS directory parser accepted or misread several malformed callback
lists without an error, and the callback runner could overflow on a
small stack top.

- A non-zero AddressOfCallbacks outside every section, or 4 GiB or more
  above the image base, is refused. It used to mean "no callbacks" or
  read the list from an unrelated place.
- The list must reach its null entry inside its section. The section's
  zero-filled tail counts as zero; bytes that follow in the file do not.
- More than 64 callbacks is an error, not a silent cut.
- execute_tls_callbacks refuses a stack top that is not 16-byte aligned
  or cannot hold the entry frame, before any callback runs.
- A file cut inside the TLS data-directory entry no longer panics.

TlsError gains four variants. Twelve unit tests use original headers
and code and also cover the argument registers, the entry and return
stack pointer, callback order and the instruction budget.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-24 23:19:19 +05:30
Vedant Dadhich dc3b02b62f Merge latest main into docs/gfx1030-form-acceptance
# Conflicts:
#	CHANGELOG.md
2026-11-24 23:14:13 +05:30
Vedant Dadhich d847d7ea6e Docs: clarify gfx1030 acceptance terminology
Address review feedback: introduce AMD RDNA2 desktop GPU (gfx1030) before the internal codename, define the LLVM three-way decoder check, document the Apple M5 status spelling, use GitHub logins in acceptance records, and mark the independence rule as proposed pending maintainer confirmation.

Signed-off-by: Vedant Dadhich <vedantdadhich21@gmail.com>
2026-11-24 23:11:55 +05:30
Swastickc b9372408c8 qa: measure CPU test runtime and add deterministic test-target shards (#159)
Add scripts/cpu-tests.sh, which lists the default-feature workspace test
targets, runs shard K of N of them in a fixed round-robin order, and checks
that N shards cover every target exactly once. It fails when Cargo cannot
build the workspace instead of running a partial list. The full gate
(cargo test --locked --workspace) and scripts/test-gpu.sh are unchanged.

Record the measured gate cost and the selected-versus-full comparison in
docs/testing/cpu-coverage.md, index it in docs/README.md, and add a
changelog entry.

Signed-off-by: Swastickc <28708247+Swastickc@users.noreply.github.com>
2026-11-24 23:11:18 +05:30
sahib453 8b67479526 loader: report the first inaccessible byte of a page-crossing guest fault (#175)
A guest access that starts in a mapped 4 KiB page and runs into an
unmapped or forbidden one reported the start of the access. It now
reports the lowest address the access may not touch, which is what the
Intel SDM page-fault cases from #155 expect. Which accesses succeed is
unchanged, and a failed access still reads and writes nothing.

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

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-24 23:09:42 +05:30
elforeign 0fdb995892 isa, decoder, shader, ref: VOP3A encodings of eleven VOP2 integer forms and the sixteen integer compares (#215) (#311)
* isa, decoder: VOP3 encodings of the eleven registry VOP2 integer forms (#215)

Eleven [[encoding_variant]] entries re-encode the VOP2 integer forms as
VOP3A (_e64) under operand rule vop3_vgpr2: two VGPR sources, no
modifiers, SRC2 the unused inline zero. Opcodes from the pinned XML,
checked against llvm-mc. Decoder known words and per-bit rejections.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* fixtures, decoder, shader: LLVM-assembled fixture and goldens for the eleven VOP3 VOP2 variants (#215)

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* ref, validation: independent guide-derived oracle for VOP3 integer VOP2 forms and Wave32 VOP3 compares (#215)

crates/ref and tests/validation/independent_ref.rs decode and run the eleven
VOP3A (_e64) integer VOP2 forms and the sixteen V_CMP_*_{I32,U32}_e64 compares
writing a 32-bit lane mask to one SGPR (s0-s105) or vcc_lo, derived from the
AMD RDNA 2 guide only. New suites vop3_integer.rs and vop3_compare.rs, with
ignored native Metal parts.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa, decoder, shader: add VOP3A encodings for the sixteen integer compares (#215)

Sixteen gfx1030 Wave32 integer compares gain their VOP3A (_e64) encoding
as registry variants, with an explicit SGPR mask destination (guide 3.9,
13.3.3; pinned XML OPR_SREG), VCCZ branching through vcc_lo and
translation errors for reads of runtime-only SGPR results.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* fixtures, shader, validation: VOP3A compare fixture and native Metal runs (#215)

A fixture with all sixteen VOP3A integer compares (vcc_lo destination,
runtime s_cbranch_vccz) ties the new variants to fixture coverage, with
IR and MSL goldens. The VOP3 integer and compare Metal oracles now run in
the GPU gate: the translator they waited for is in this branch.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* changelog: VOP3A integer and compare encodings (#215)

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* shader, fixtures, docs: e64 compare names in the IR; status rows for the 27 VOP3A forms (#215)

The IR names a VOP3A compare by its _e64 mnemonic and prints its SGPR
destination; VOPC output is unchanged. The compare fixture now uses a
mid-range second source (so swapped unsigned opcodes change the golden)
and one plain SGPR destination. docs/status.toml and the rendered
instruction table list the 27 new forms.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* docs: use a recognized lowering phrase for the VOP3A integer rows (#215)

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa: VOP3A variants exist only for the 32-bit VOPC compares (#215)

After main gained the 16-bit compares (#327), the dispatch test expected a
VOP3A encoding for every non-64-bit compare. Only the 32-bit ones have one.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

---------

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 11:38:44 -06:00
Vedant Dadhich b55a4c24ef Merge main into docs/gfx1030-form-acceptance
# Conflicts:
#	CHANGELOG.md
2026-11-24 23:08:10 +05:30
ates 1dcf722323 benchmarks: measure gfx1030 metadata identification
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 20:36:15 +03:00
zachdoxsee 48e1e5c8c1 Merge upstream main into task/329-gate-a1
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 18:24:36 +01:00
zachdoxsee 6947fe7ff6 Merge upstream main into task/333-pe-headers
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 18:22:23 +01:00
LanaCodes-Boop 94732d90ca Merge remote-tracking branch 'upstream/main' into runtime/guest-clock-fixtures
Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 14:22:11 -03:00
LanaCodes-Boop 1e8893a6bf loader: stop the mock clock wrapping and test time services against one clock (#204)
Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>
2026-11-24 14:21:14 -03:00
elforeign d7f7d586d3 gpu: bind a texture and sampler to guest draws through descriptor tables (#303) (#336)
* gpu: bind a texture and sampler to guest draws through descriptor tables (#303)

A guest command list had no way to bind a texture: GraphicsCommand stopped
at vertex and index buffers. This adds the smallest D3D12-shaped binding the
translated image_sample_lz pixel stage needs: shader-visible CBV_SRV_UAV and
sampler heaps, CreateShaderResourceView for one-level RGBA8 and BC1 2D
textures, a point/clamp CreateSampler, a root signature with one pixel-stage
SRV table and one sampler table, and SetDescriptorHeaps and
SetGraphicsRootDescriptorTable. Everything else fails explicitly before any
draw.

The native path hands the bound level to a textured backend.
NativeCompute::render_rgba8_sampled_bc1 binds a BC1 level natively to
fragment texture 0 and sampler 0. The software reference point-samples with
clamp addressing.

BC1 fixtures use only endpoint colours. Apple's hardware decoder gives
171/84 for the interpolated palette entries where the spec-exact decoder
gives 170/85.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* gpu: tighten guest texture binding after independent review (#303)

The independent review found binding rules that diverged from D3D12:
changing descriptor heaps kept tables bound in the old heaps, setting the
same root signature again cleared its tables, and unsupported draw shapes
were drawn as one triangle. Now heap changes and a different root signature
invalidate tables, while redundant sets keep them. Table bases are checked
against the bound heap of their type when bound. Textured draws other than
one instance of three vertices fail, and zero vertices or instances draw
nothing.

Descriptor handle offsets can no longer carry into another heap's ID. SRVs
of array or multi-level textures are rejected. A texture whose state
excludes pixel-shader reads is not sampled. Vertex buffer offsets are
overflow-checked. The tests now cover swapped root parameters, a second
sampler slot, off-centre and out-of-range coordinates, state transitions,
draw shapes and resource bounds.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* loader: format the guest texture test (#303)

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* gpu: close the review's remaining texture-binding gaps (#303)

The re-review found three partial fixes. The public software reference
could overflow on a huge viewport. A texture in a combined write and read
state could be sampled. The sampler-slot test used two identical filled
slots. The viewport is now bounded to 4096 pixels. A sampled texture must be
COMMON or a read-only state that includes PIXEL_SHADER_RESOURCE. The sampler
heap now leaves its middle slot empty. The docs now state the start-instance
rule and when table bases are checked.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

---------

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 11:21:03 -06:00
zachdoxsee b8fbdf35b9 loader: map the PE headers at the image base (#333)
Windows maps the first SizeOfHeaders bytes of an image read-only at its
base, and programs read them: the mingw-w64 C runtime walks its own
section table before main. The loader mapped sections only, so that read
faulted.

Map the headers in whole 4 KiB pages before the sections, with the
optional header's ImageBase field set to the base the image is loaded
at. Refuse the load with PeError::InvalidHeaderSize when SizeOfHeaders
ends before the section table, runs past the file, or its pages reach
into a section. The header pages count toward the mapping budget.
ParsedPe::parse is unchanged.

The hand-built image in pe_mapping_limits.rs wrote SizeOfHeaders as
zero; it now writes a valid value.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 18:15:56 +01:00
izdat-sl4w d01627b3de audit: read and write tracked files as UTF-8
The generated-status check and the claims audit called
Path.read_text()/write_text() without encoding=, so they used the process
locale encoding. Under an ASCII locale the status check raises
UnicodeDecodeError on docs/claims.toml, and under cp1252 it reports a
spurious xenora-progress.svg difference, so a current tree fails the
documented checkout command. Both scripts now pass encoding="utf-8", as
the rest of scripts/ does, and CI runs the two checks again under a
non-UTF-8 locale so the requirement stays enforced.

Closes #334

Signed-off-by: izdat-sl4w <76667566+izdat-sl4w@users.noreply.github.com>
2026-11-24 18:09:21 +01:00
Vedant Dadhich 291c9807ee Docs: define gfx1030 form acceptance
Add the promotion rule for moving desktop gfx1030 forms from local CPU and Metal results to fixture verified. The rule records clean-commit evidence, independent-runner requirements, exact commands, raw-log location, review-log summaries, failure handling and status regeneration. This is documentation only: no status rows, tests or fixtures change. Part of #302.

Signed-off-by: Vedant Dadhich <vedantdadhich21@gmail.com>
2026-11-24 22:24:18 +05:30
jelly013 84866956b9 runtime: add a deterministic guest thread scheduler
Run guest threads on one host thread with independent CPU contexts, guarded
stacks and TEBs, in first-in, first-out order with bounded turns that end at
translated-block boundaries. Add CreateThread, ExitThread, TerminateThread,
GetExitCodeThread, SuspendThread, ResumeThread and SwitchToThread, and let
waits on threads, events, semaphores and mutexes block only the caller.
Report deadlocks, abandoned mutexes and per-thread faults.

Reclaim per-thread state at thread end without passing held locks to a thread
that reuses the TEB address, and bound pending one-time initializations.
Guest threads never run concurrently. Critical sections, SRW locks,
condition variables and Sleep do not block per thread yet.

Verify with C programs compiled for x86-64 Windows and run as translated
guest code at several quanta.

Refs #323

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 17:47:01 +01:00
zachdoxsee 47cb26ebdd loader: add process exit and the Gate A1 compiled C program (#329)
A guest can now end its process. kernel32.dll!ExitProcess stops execution
with the new ExitReason::ProcessExit(status), keeping all 32 bits of the
status, and never ends the host. A returning entry point does the same
with EAX: startup puts an exit address under the entry point. The exit
closes every guest handle, and the DbtEngine that ran the guest executes
no further guest instruction.

Gate A1 is an original C program with no C library linked. The test
builds it from source with clang and an LLD, runs it through
run_synthetic_startup, the standard services and the DBT at four
optimization levels, and checks its exit status, report, files and
memory against values recomputed in Rust. Three controls must fail in
the stated way. Gate A stays open until the hosted milestone, A2.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 17:42:09 +01:00
Ranveer Soni 1d363c3c34 Merge pull request #328 from elforeign/task/215-vop2-vcc
isa, decoder, shader, ref: the four VOP2 VCC-reading integer forms through the semantic registry (#215)
2026-11-24 22:02:56 +05:30
Adeeb RahmanandCursor eaeab25590 Record corrected runtime_services fuzz campaign evidence
Withdraw the unreachable-dispatch campaign counts and replace them with
the post-fix 300-second run (96,589 inputs, 4,008 coverage edges) plus
the XMemAlloc OOM that campaign found.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-24 11:28:48 -05:00
elforeign e74ebbe30b Merge remote-tracking branch 'origin/main' into task/215-vop2-vcc
# Conflicts:
#	CHANGELOG.md
#	crates/decoder/tests/gfx1030.rs
#	crates/isa/src/semantics_gen.rs
#	docs/assets/xenora-progress.svg
#	docs/shaders/semantic-coverage.md
#	docs/shaders/semantic-registry.md
#	scripts/assemble-fixture.sh
2026-11-24 10:27:02 -06:00
elforeign 26eba92b87 docs: record the VOP2 VCC-reading forms' Metal readback (#215)
scripts/test-gpu.sh now runs vop2_vcc_matches_guide_on_native_metal,
which passes under API and shader validation.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 10:26:42 -06:00
Ranveer Soni 05143d6295 Merge pull request #327 from elforeign/task/215-vopc16-xlate
isa, decoder, shader: translate the twelve VOPC 16-bit integer compares (#215)
2026-11-24 21:54:09 +05:30
elforeign d6a65b2940 Merge remote-tracking branch 'origin/main' into task/215-vop2-vcc
# Conflicts:
#	CHANGELOG.md
2026-11-24 10:24:07 -06:00
elforeign 1cc7f01fec Merge remote-tracking branch 'origin/main' into task/215-vop2-vcc
# Conflicts:
#	crates/isa/generate_semantics.py
#	crates/isa/src/semantics_gen.rs
#	docs/shaders/semantic-coverage.md
#	docs/shaders/semantic-registry.md
2026-11-24 10:23:59 -06:00
Adeeb RahmanandCursor 8d19006c32 Bound XMemAlloc through the virtual memory budget
The fixed fuzz harness reached service handlers and immediately found a
libFuzzer OOM: XMemAlloc mapped unbounded ImageOrStatic regions, so a
~3.7 GiB request tried to malloc host storage. Overflowing sizes still
fail closed, and successful sizes use map_virtual_allocation.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-24 11:23:12 -05:00
elforeign 6a4fc7cce1 docs: record the VOPC 16-bit compare Metal readback (#215)
scripts/test-gpu.sh now runs vopc16_match_the_guide_on_native_metal:
1,572 cases in 1,420 programs pass under API and shader validation.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 10:23:09 -06:00
elforeign b5b24347e9 Merge remote-tracking branch 'origin/main' into task/215-vopc16-xlate
# Conflicts:
#	CHANGELOG.md
#	crates/isa/src/semantics_gen.rs
#	docs/shaders/semantic-coverage.md
2026-11-24 10:20:34 -06:00
elforeign f8eb976102 isa, decoder, shader: translate the twelve VOPC 16-bit integer compares (#215)
v_cmp_{lt,eq,le,gt,ne,ge}_{i16,u16}_e32 (opcodes 137-142, 169-174) now
compile for gfx1030: both operands use bits 15:0 of the VGPR, SGPR or
VCC_LO source, inline integers at 16 bits, literals rejected, writing the
Wave32 VCC mask. The B1 oracle's last native Metal skip is removed.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 10:20:28 -06:00
Adeeb RahmanandCursor 84221ac715 Fail closed on overflowing XMemAlloc sizes
The fuzz harness now reaches service handlers; a u64::MAX-sized request
panicked in debug builds while aligning to a page. Treat unrepresentable
sizes as allocation failure.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-24 11:20:11 -05:00
Adeeb RahmanandCursor 673e2a4556 Merge origin/main into feat/runtime-fuzz-bench
Sync with main after #215/#198/#130 landings. Keep the guest string-scan
changelog entry alongside the upstream SOP1 registry note, and correct the
runtime_services fuzz harness so corpus bytes drive dispatch instead of the
65,536-byte writable fill (withdrawing the earlier campaign counts).

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-24 11:20:11 -05:00
Ranveer Soni bbb59324c0 Merge pull request #326 from zachdoxsee/task/129-rep-strings
loader: add MOVS, STOS, REP and the direction flag (#129)
2026-11-24 21:49:55 +05:30
elforeign 34b16ca65c Merge remote-tracking branch 'origin/main' into task/215-vop2-vcc
# Conflicts:
#	CHANGELOG.md
#	crates/isa/src/semantics_gen.rs
#	crates/shader/src/lib.rs
#	docs/assets/xenora-progress.svg
#	docs/shaders/semantic-coverage.md
#	docs/shaders/semantic-registry.md
#	scripts/assemble-fixture.sh
2026-11-24 10:17:48 -06:00
Ranveer Soni fd0e427c7b Merge pull request #325 from elforeign/task/215-sopp-control
isa, decoder, shader: move the SOPP control forms into the semantic registry (#215)
2026-11-24 21:46:55 +05:30
zachdoxsee 314d1f5874 loader: add MOVS, STOS, REP and the direction flag (#129)
Declare MOVS and STOS for 8- to 64-bit elements through a new string
encoding that accepts REP, and add the direction flag with CLD and STD.

A REP form runs one element per step and stays on the instruction until
RCX is zero. Every element therefore counts against the step budget, a
repeat can stop part-way and resume, and a fault keeps the elements
already done. FS and GS apply to the MOVS source only. Both engines use
the shared semantics; there is no bulk-copy path.

Fourteen SDM-derived cases already in cpu_known_answers.rs move from
refused to verified, and ten more are now refused at their second
instruction because CLD runs. tests/cpu_rep.rs adds a byte-array model
over every form, direction and count.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 17:14:46 +01:00
elforeign 7adb978683 Merge remote-tracking branch 'origin/main' into task/215-vop2-vcc
# Conflicts:
#	CHANGELOG.md
#	crates/decoder/src/lib.rs
#	crates/decoder/tests/gfx1030.rs
#	crates/isa/generate_semantics.py
#	crates/isa/semantics/rdna2.toml
#	crates/isa/src/semantics_gen.rs
#	crates/shader/src/lib.rs
#	crates/shader/tests/compiler.rs
#	docs/README.md
#	docs/assets/xenora-progress.svg
#	docs/shaders/semantic-coverage.md
#	docs/shaders/semantic-registry.md
#	scripts/assemble-fixture.sh
2026-11-24 10:13:25 -06:00
elforeign 9d5de05055 Merge remote-tracking branch 'origin/main' into task/215-sopp-control
# Conflicts:
#	crates/isa/src/semantics_gen.rs
#	docs/shaders/instruction-coverage.md
#	docs/shaders/semantic-coverage.md
2026-11-24 10:11:20 -06:00
Ranveer Soni 3348d34e6f Merge pull request #324 from elforeign/task/215-vopc64-xlate
isa, decoder, shader: translate the sixteen VOPC 64-bit integer compares (#215)
2026-11-24 21:38:36 +05:30
elforeign 8e9ec8b9d1 isa, decoder, shader, ref: the four VOP2 VCC-reading integer forms through the semantic registry (#215)
v_cndmask_b32, v_add_co_ci_u32, v_sub_co_ci_u32 and v_subrev_co_ci_u32
(VOP2 e32, Wave32) read VCC_LO as the per-lane select or carry-in; the
co_ci forms write the carry-out to VCC_LO. An independent guide-derived
oracle, tests/validation/tests/vop2_vcc.rs, checks both CPU interpreters;
its native Metal half is ignored until the lead runs it.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 10:06:08 -06:00
elforeign b54f5ef0aa Merge remote-tracking branch 'origin/main' into task/215-sopp-control 2026-11-24 10:05:53 -06:00
elforeign 4d5207afd8 Merge remote-tracking branch 'origin/main' into task/215-sopp-control
# Conflicts:
#	crates/decoder/src/lib.rs
#	crates/isa/generate_semantics.py
#	crates/isa/src/lib.rs
#	crates/isa/src/semantics.rs
#	crates/isa/src/semantics_gen.rs
#	docs/shaders/instruction-coverage.md
#	docs/shaders/semantic-coverage.md
2026-11-24 10:05:52 -06:00
elforeign 27daa701c1 Merge remote-tracking branch 'origin/main' into task/215-vopc64-xlate
# Conflicts:
#	CHANGELOG.md
2026-11-24 10:05:34 -06:00
elforeign c985c3fa17 docs: record the VOPC 64-bit compare Metal readback (#215)
scripts/test-gpu.sh now runs vopc64_match_the_guide_on_native_metal:
4,640 cases in 3,818 programs pass under API and shader validation.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 10:04:35 -06:00
Ranveer Soni 6ad1602a3d Merge pull request #321 from zachdoxsee/task/198-changelog-entry
changelog: restore the XADD, CMPXCHG and LOCK entry (#198)
2026-11-24 21:34:08 +05:30
Ranveer Soni 82cafe9664 Merge branch 'main' into task/198-changelog-entry 2026-11-24 21:33:31 +05:30
Ranveer Soni bf2c279dc7 Merge pull request #322 from zachdoxsee/task/130-cpuid-contract
loader: add CPUID with a truthful guest feature contract (#130)
2026-11-24 21:33:00 +05:30
elforeign 3521dca45b Merge remote-tracking branch 'origin/main' into task/215-vopc64-xlate
# Conflicts:
#	CHANGELOG.md
#	crates/isa/src/semantics_gen.rs
#	docs/assets/xenora-progress.svg
#	docs/shaders/semantic-coverage.md
#	scripts/assemble-fixture.sh
#	scripts/test-gpu.sh
2026-11-24 10:01:32 -06:00
elforeign 131c8669cf isa, decoder, shader: move the SOPP control forms into the semantic registry (#215)
The six supported gfx1030 SOPP compute control forms are now described in
crates/isa/semantics/rdna2/sopp.toml, and the decoder and shader dispatch
from the registry. A sweep over all 128 SOPP opcodes, 13 SIMM16 values and
two stream positions (3,328 records) is identical before and after.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 10:00:42 -06:00
elforeign 2c8c63cf65 isa, decoder, shader: translate the sixteen VOPC 64-bit integer compares (#215)
v_cmp_{f,lt,eq,le,gt,ne,ge,t}_{i64,u64}_e32 (opcodes 160-167, 224-231) now
compile for gfx1030: VGPR pairs, even-aligned SGPR pairs and sign-extended
inline integers, writing the Wave32 VCC mask. The 16-bit compares stay
rejected; their native Metal oracle keeps its skip.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 10:00:42 -06:00
zachdoxsee da16b36499 loader: add CPUID with a truthful guest feature contract (#130)
CPUID returns a fixed table that never reads the host: a synthetic
vendor, and a feature bit only when every instruction of that feature
is implemented. Today that is CMOV, POPCNT, LZCNT and long mode. SSE
and SSE2 stay unreported while parts of them are rejected. Unlisted
leaves return zeros.

tests/cpu_features.rs pins every leaf in both engines, requires each
reported feature's instruction set among the executed fixtures, and
holds a refused witness instruction for each unreported feature, so a
bit cannot be set early or forgotten later.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 16:59:50 +01:00
zachdoxsee 061568a6ee changelog: restore the XADD, CMPXCHG and LOCK entry (#198)
The merge of main into the branch of #320 kept only main's side of the
changelog conflict, so the entry for that change did not reach main.
Put it back. No code changes.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 16:58:07 +01:00
Ranveer Soni a03188315d Merge pull request #320 from zachdoxsee/task/198-atomic-rmw
loader: add XADD, CMPXCHG and LOCK on their memory forms (#198)
2026-11-24 21:25:42 +05:30
Ranveer Soni 95f6b52d9f Merge branch 'main' into task/198-atomic-rmw 2026-11-24 21:24:32 +05:30
Ranveer Soni 7499d6f6c3 Merge pull request #318 from elforeign/task/215-vop1-xlate
isa, decoder, shader: the six VOP1 integer forms through the semantic registry, Metal-verifying the B3 oracle (#215)
2026-11-24 21:22:04 +05:30
zachdoxsee 3a3f0c52af loader: add XADD, CMPXCHG and LOCK on their memory forms (#198)
Declare XADD and CMPXCHG in the instruction registry for 8- to 64-bit
register and memory destinations. The LOCK prefix is accepted on the
forms the registry marks lockable and only with a memory destination;
every other use stays an illegal instruction.

Both engines run the new forms on the shared semantics. A failed
CMPXCHG still writes its destination, so it faults on memory that
cannot be written, and a fault changes nothing. The registry document
states the ordering, alignment, compare-failure and fault rules a guest
scheduler has to preserve. Nothing is lowered to ARM64 atomics.

Fourteen SDM-derived cases already in cpu_known_answers.rs move from
refused to verified. Adds 62 LLVM-assembled fixtures with reference
arms, generator checks for the lock key and tests/x86_atomic.rs.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 16:46:01 +01:00
elforeign 989bb79d6c Merge remote-tracking branch 'origin/main' into task/215-vop1-xlate
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	crates/isa/generate_semantics.py
#	crates/isa/src/semantics_gen.rs
#	crates/shader/src/lib.rs
#	docs/shaders/semantic-coverage.md
#	docs/shaders/semantic-registry.md
2026-11-24 09:45:44 -06:00
elforeign d157f802d3 docs: record the VOP1 integer Metal readback (#215)
scripts/test-gpu.sh now runs the oracle on native Metal: 752 cases in
613 programs pass under API and shader validation. Also states which half
of the oracle checks values and which checks rejection offsets (review nit).

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 09:44:19 -06:00
Ranveer Soni fb0544652b Merge pull request #317 from elforeign/task/215-smov
isa, decoder, shader: move s_mov_b32 into the semantic registry (#215)
2026-11-24 21:13:46 +05:30
elforeign 61943d23b6 Merge remote-tracking branch 'origin/main' into task/215-vop1-xlate
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 09:42:01 -06:00
elforeign 947d6e4eaf isa, decoder, shader: the six VOP1 integer forms through the semantic registry (#215)
The B3 oracle (#309) checks v_not_b32, v_bfrev_b32, v_ffbh_u32,
v_ffbl_b32, v_ffbh_i32 and v_swap_b32 against the guide on both CPU
interpreters, but its native Metal half was skipped because the
translator did not accept the forms. This adds the VOP1 registry file and
operand rule, decoder dispatch, IR and MSL lowering (v_swap_b32 writes
both VGPRs, each merged under EXEC), fixture and goldens, and removes
the oracle's skip from scripts/test-gpu.sh.

A new CPU test checks that the compiler accepts every case of the
oracle and rejects each of its rejections at the same word.
v_mov_b32 stays hand-written.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 09:41:08 -06:00
elforeign bdcdd57c55 docs: s_mov_b32 is now a registry SOP1 form (#215)
Review finding: the scalar ALU page still called it hand-written.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 09:39:39 -06:00
elforeign 5b894777ce Merge remote-tracking branch 'origin/main' into task/215-smov 2026-11-24 09:37:41 -06:00
elforeign dc44c5c64b isa, decoder, shader: move s_mov_b32 into the semantic registry (#215)
s_mov_b32 was the last hand-written SOP1 decode path. It becomes
ScalarUnaryOp::MovB32 under a new sop1_move operand rule that matches the
old hand-written domain exactly (it accepts more SDST and SSRC0 classes
than sop1_sgpr, which other unary forms keep).

A decode sweep of 33,664 s_mov_b32 words shows no behaviour change: the
21,010 accepted words differ only in the instruction's name and the 12,654
rejections are identical. IR and MSL goldens are unchanged.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 09:37:41 -06:00
Adeeb Rahman b49d50e34e Decode MSVC decorated names for import diagnostics
Add a clean-room decoder for the common decoration grammar, show its
output in generator manifests, and test it against names clang mangles
for x86_64-pc-windows-msvc.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
(cherry picked from commit 506e09c909e75c92ef8a0050df67fc79f787028a)
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 10:33:26 -05:00
Adeeb Rahman e0a6dae554 Benchmark guest service dispatch and scan CRT strings in blocks
Add correctness-gated guest loops that time services through the
import table. Scan string lengths 256 units at a time, falling back to
single units at mapping boundaries to keep exact faults.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
(cherry picked from commit b9f6afb20c7541c69464e2e771396269961a8a49)
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 10:33:26 -05:00
Adeeb Rahman b3a6a57a8e Fuzz the standard guest service registry
Drive random service call sequences with adversarial arguments and
check memory and register invariants after every call. The libFuzzer
target and a stable replay test share one driver.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
(cherry picked from commit 3027b9eb06904793c464b80490aa3903bfe7e173)
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 10:33:26 -05:00
Ranveer Soni b9f6985d57 Merge pull request #315 from zachdoxsee/task/244-delay-imports
loader: report delay-loaded PE imports in the static probe (#244)
2026-11-24 21:01:45 +05:30
zachdoxsee db40a1307d loader, cli: bound delay-load tables by their declared size (#244)
Address review on the delay-import probe change:

- Read only descriptors inside the delay import directory's declared
  size, and require that size to hold the terminating empty descriptor.
- Require each descriptor's DLL name, import address table and import
  name table to be present and to start in section data, with a
  diagnostic naming the missing field.
- Leave delayed rows out of the xenora imports sync backlog, so its
  totals stay ordinary-only.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 16:28:02 +01:00
zachdoxsee b174b45bed loader: report delay-loaded PE imports in the static probe (#244)
Read the PE32+ delay-load directory (data directory 13) with a bounded
parser and list each delay-loaded import in imports.csv, marked by a new
import_table column. Ordinary totals and missing_imports.csv are
unchanged; the JSON report counts delayed slots and DLLs separately and
carries a diagnostic for truncated, out-of-range or unsupported tables.

Adds an original fixture with ordinary and delayed imports, generated by
fixtures/pe/delay-imports.py and cross-checked with llvm-readobj.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 16:25:14 +01:00
Ranveer Soni 7504a5d48d Merge pull request #305 from LanaCodes-Boop/runtime/last-error-per-thread
loader: retire a guest thread's last error and test the per-TEB contract (#202)
2026-11-24 20:53:03 +05:30
Ranveer Soni 2b858ab7c6 Merge branch 'main' into runtime/last-error-per-thread 2026-11-24 20:52:39 +05:30
Ranveer Soni 076f3e52aa Merge pull request #313 from elforeign/task/215-gpu-skip
scripts: restore the VOP1 oracle's GPU gate skip (#215)
2026-11-24 20:51:33 +05:30
Ranveer Soni e17e3bfc63 Merge pull request #314 from elforeign/task/215-sopk-oracle
isa, decoder, shader, ref: the sixteen SOPK integer forms through the semantic registry (#215)
2026-11-24 20:50:46 +05:30
Ranveer Soni 1915e2374c Merge pull request #297 from Swastickc/task/196-bit-scan-bit-test
loader: lower BSF, BSR and register BT in the ARM64 DBT (#196)
2026-11-24 20:49:54 +05:30
elforeign 6545a25b7b Merge remote-tracking branch 'origin/main' into task/215-sopk-oracle 2026-11-24 09:12:11 -06:00
LanaCodes-Boop d5514aa9d8 Merge main into runtime/last-error-per-thread
Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>
2026-11-24 12:10:25 -03:00
LanaCodes-Boop 7623fde0e7 loader: retire a guest thread's last error and test the per-TEB contract (#202)
main keeps the last error per TEB since #310. This adds the missing
retirement step, so a reused TEB address starts at zero, and two
conformance tests: a successful call keeps a nonzero error, and one
thread's failure does not reach another.

Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>
2026-11-24 12:10:20 -03:00
Ranveer Soni f2e6db03a9 Update README.md 2026-11-24 20:39:34 +05:30
LanaCodes-Boop 3a14bd98ab Merge main into runtime/last-error-per-thread
main gained per-TEB last-error handling in #310. The conflicts in
CHANGELOG.md, services.rs and runtime_services.rs are resolved to main's
version, which drops this branch's separate thread-context mechanism.

Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>
2026-11-24 12:08:04 -03:00
elforeign d31b8ef20c scripts: restore the VOP1 oracle's GPU gate skip (#215)
The merge of #309 kept only the wide-compare skip, so scripts/test-gpu.sh
runs vop1_integer_forms_match_the_guide_on_native_metal, which fails until
the translator implements the VOP1 integer forms.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 09:07:18 -06:00
elforeign 81cfe69143 Merge remote-tracking branch 'origin/main' into task/215-sopk-oracle
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 09:06:03 -06:00
elforeign 91fe3f345b isa: cmov reads SCC in the registry validator (#215)
A form declared operation = "cmov" without carry_in = "scc" passed
validation and would have generated a move that never writes D. The new
generator test fails without the fix.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 09:05:49 -06:00
Ranveer Soni 0a722d2e60 Merge pull request #310 from soggyramennoodle/feat/system-runtime-expansion
System runtime: Win32 services, CRT, sync, guest callbacks and sysinfo
2026-11-24 20:30:19 +05:30
Ranveer Soni 738b518a26 Merge branch 'main' into feat/system-runtime-expansion 2026-11-24 20:29:27 +05:30
elforeign 0cf4e8a9e9 docs: status rows for the sixteen SOPK forms (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:58:43 -06:00
Ranveer Soni 9f8dc3a912 Merge pull request #309 from elforeign/task/215-vop1-int-oracle
ref, validation: independent oracle for six VOP1 integer forms (#215)
2026-11-24 20:27:25 +05:30
Ranveer Soni d6f21217a2 Merge branch 'main' into task/215-vop1-int-oracle 2026-11-24 20:27:11 +05:30
Ranveer Soni 9478795696 Merge pull request #308 from elforeign/task/215-vopc-wide-oracle
ref, validation: independent oracle for the Wave32 16-bit and 64-bit integer compares (#215)
2026-11-24 20:26:40 +05:30
elforeign d8c117cdd3 docs: SOPK contract, coverage and changelog (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:55:52 -06:00
elforeign 9ef9537540 isa, decoder, shader: SOPK integer forms through the semantic registry (#215)
Declares s_movk_i32, s_cmovk_i32, s_cmpk_{eq,lg,gt,ge,lt,le}_{i32,u32},
s_addk_i32 and s_mulk_i32 as registry data under the new operand rules
sopk_sgpr and sopk_compare (SDST s0-s105 only, SIMM16 never a literal),
with the operations mov and cmov, the sext_simm16 primitive and an XML
check of the 16-bit immediate. The decoder dispatches them through the
generated ScalarImmediateOp and ScalarImmediateCompareOp (the fixed
0xbbfd0000 fence keeps its own decoding) and the translator folds them
into its scalar state like SOP2 and SOPC, refusing writes to s0-s7.

The guide-derived oracle in tests/validation/tests/sopk.rs is unchanged.
Adds IR and MSL goldens for the new fixture, LLVM-checked decoder words,
a known answer, an isa dispatch test and generator unit tests.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:55:52 -06:00
elforeign 081f9c9e06 fixtures: add an original SOPK scalar-immediate fixture (#215)
Uses all sixteen s_*k_* integer forms: the twelve s_cmpk compares split
signed from unsigned SIMM16 extension, s_addk_i32 sets SCC on signed
overflow, s_mulk_i32 leaves it alone and s_cmovk_i32 moves only while
SCC is set. The expected input ^ 0x40008275 is worked out by hand in the
file from guide section 12.2.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:55:52 -06:00
Adeeb RahmanandCursor 17fa47f058 Add CRT onexit tables, atexit and _cexit
Exit functions are guest code run through callback tasks in reverse
registration order. Table storage lives on the default guest heap.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-24 09:52:50 -05:00
elforeign 3250ae8fd1 Merge remote-tracking branch 'origin/main' into task/215-vop1-int-oracle 2026-11-24 08:51:35 -06:00
elforeign 6ff79431bc validation: swap rejections for v0, honest pending-load labels (#215)
v_swap_b32 gains rejections for v0 as SRC0 and as VDST under full EXEC.
Its outstanding-load case is a VDST read, so it is labelled as one. The
GPU gate skip names #215.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:51:35 -06:00
elforeign c1fc4d373f Merge remote-tracking branch 'origin/main' into task/215-vopc-wide-oracle 2026-11-24 08:50:10 -06:00
elforeign 1b4911ffea validation, docs: close the wide-compare review gaps (#215)
A CPU test checks that the production compiler still rejects all 28
forms, and each 64-bit form gains a rejection for v255 as VSRC1 after an
inline integer (dropping that check in the second interpreter now fails
the rejection test). Docs and counts follow.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:50:10 -06:00
Adeeb Rahman 6c460f7c1c Merge upstream main a2a6a56 into system runtime branch
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 09:48:20 -05:00
Adeeb RahmanandCursor 8d7f7fadb4 Add guest system information, calendar time and sleeping
The guest sees a configurable simulated machine, kept separate from the
detected host hardware. Sleeping goes through the injectable clock.
Move the PE fixture harness into a shared test support module.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-24 09:48:16 -05:00
Ranveer Soni a2a6a56222 Update README.md 2026-11-24 20:17:47 +05:30
elforeign fbe1d3c4d1 Merge remote-tracking branch 'origin/main' into task/215-sopk-oracle 2026-11-24 08:47:37 -06:00
elforeign 8f67a9680d scripts, changelog: VOP1 integer oracle; skip its Metal test until the translator lands (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:46:52 -06:00
elforeign 74af0d8eb9 scripts: skip the wide-compare Metal oracle in the GPU gate until the translator lands (#215)
The ignored native Metal test fails today because the translator rejects
the 16- and 64-bit compares; scripts/test-gpu.sh runs every ignored
semantic-review test, so it skips this one by name.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:46:52 -06:00
elforeign 4bc268c931 Merge remote-tracking branch 'origin/main' into task/215-vop1-int-oracle 2026-11-24 08:45:35 -06:00
elforeign 0b00fb378d docs, validation: document the 16-bit and 64-bit compare oracle subset (#215)
vector-compare.md gains section 2a for the subset the reference
interpreters accept, and no longer says the reference rejects these
forms. vopc_f_t.rs stops listing the 64-bit F/T opcodes as unsupported:
the reference accepts them now, and the check passed only because v2 of
the v[1:2] pair was uninitialized.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:44:01 -06:00
elforeign d5437c1c18 Merge remote-tracking branch 'origin/main' into task/215-vopc-wide-oracle 2026-11-24 08:43:19 -06:00
Ranveer Soni ad4d07492d Merge pull request #299 from jelly013/task/155-cpu-known-answers
test(loader): x86-64 architectural known answers from the Intel SDM (#155)
2026-11-24 20:12:42 +05:30
Ranveer Soni 65bf3ec3fc Merge pull request #293 from Swastickc/task/290-shared-gpu-context
ffi: share one Metal device and queue across frame-loop sessions (#290)
2026-11-24 20:12:20 +05:30
Ranveer Soni 0afae6fa45 Merge pull request #304 from elforeign/task/215-m27
isa, decoder, shader: move the six VOP2 logical and shift forms into the registry (#215)
2026-11-24 20:11:45 +05:30
Adeeb Rahman 143429ceeb Merge upstream main a2cc14d into system runtime branch
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 09:41:43 -05:00
Adeeb RahmanandCursor 1eae910ce1 Let services call guest code and continue after it returns
Add callback tasks to the import dispatcher. A task runs guest callbacks
on a reserved stack frame, checks the nonvolatile registers after each,
and returns to the original caller. Use it for qsort, qsort_s, bsearch,
bsearch_s, _initterm, _initterm_e, InitOnceExecuteOnce and FlsFree
cleanup callbacks.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-24 09:41:39 -05:00
jelly013 c586a4a82a test(loader): tighten the x86-64 known answers after review (#155)
Pin MXCSR for a flushed exact tiny result, PE for unmasked overflow and
underflow, and run the sweeps with each exception unmasked alone. Require a
refused form to stop at its exact instruction with all state unchanged,
assert the cached DBT run hits the cache, and check the fallback counter for
every straight-line case. Add a faulting zero-count memory shift.

The tighter checks expose one more defect, kept as an ignored test: an exact
unmasked overflow sets PE as well as OE.

Correct the chronology: 700 table cases were written before the CPU source
was read, and the other cases and the sweeps afterwards. The message of
1c5c320 says otherwise.

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 15:41:20 +01:00
elforeign 9e35434f63 Merge remote-tracking branch 'origin/main' into task/215-sopk-oracle
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:41:06 -06:00
LanaCodes-Boop 6e64737021 loader: keep a guest last error per modeled thread context (#202)
ServicesState held one process-wide last-error value, so every modeled
guest thread would have read and overwritten the same slot. The running
context now owns the live slot and the others are parked by identifier,
bounded at 1,024. No guest thread is scheduled: the embedder switches
contexts between service calls.

Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>
2026-11-24 11:41:05 -03:00
elforeign 8b0b62a771 validation: close SOPK test gaps from review
Compares now run with both SCC values before, so an implementation that
only flips SCC fails. New checks: a taken s_cmovk_i32 initializes an
unwritten SDST, s_cmovk_i32 without SCC is refused, the forms write no
SGPR but SDST, and s_waitcnt_vscnt null with a nonzero count is refused.
The opcode comment now lists 17 and 20 as unlisted.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:40:55 -06:00
elforeign d658907fd7 Merge remote-tracking branch 'origin/main' into task/215-m27
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	crates/decoder/src/lib.rs
#	crates/isa/semantics/rdna2/vop2.toml
#	crates/isa/src/lib.rs
#	crates/isa/src/semantics_gen.rs
#	crates/shader/src/lib.rs
#	docs/shaders/semantic-coverage.md
2026-11-24 08:38:00 -06:00
elforeign a2cc14d223 isa, decoder, shader, scripts: split the semantic registry per family and add encoding variants (#215) (#300)
* isa, decoder, shader: move the twelve Wave32 VOPC compares into the semantic registry (#215)

The v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32 forms from #239 are now
registry data under a new vopc_vcc operand rule (SRC0 a vector_source,
VSRC1 a VGPR, destination implicitly vcc_lo). The decoder dispatches them
through the generated VectorCompareOp instead of a hand-written opcode
table, and the hand-written VectorCompareOp struct in xenora-isa is gone.
No behaviour change: goldens, known answers and the LLVM oracle are
unchanged.

The vocabulary gains vcc = "lane_mask", allowed exactly for the VOPC rule
and required to account for the XML's implicit VCC output, and wave =
"wave32", now allowed exactly for that rule (its one entry point is the
Wave32 compute fixture ABI) and still rejected elsewhere. exec must stay
unchanged, so v_cmpx cannot be declared.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* test(vopc): independent oracle for v_cmp_{f,t}_{i32,u32}_e32 (#215)

The registry stage adds the four constant 32-bit integer VOPC compares,
which nothing could check: the reference and the second interpreter both
rejected them. Derive them from the RDNA 2 guide only (12.9 Table 61:
D = 0 / D = 1; 3.9: VCC[n] = EXEC[n] & test, fully written) under the
#239 Wave32 contract, so T writes EXEC_LO masked to existing lanes, F
writes 0, and sources keep the allowlist and initialization rules.

vopc_f_t.rs covers every SRC0 class, aliasing, full, partial and empty
EXEC with a stale VCC_LO, a partial final wave, s_cbranch_vccz on both
edges and the rejections; the native Metal part is ignored until the
translator side lands. known_answers no longer expects F and T to be
rejected.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa, decoder, shader: v_cmp_{f,t}_{i32,u32} through the semantic registry (#215)

Adds the four constant Wave32 VOPC compares as registry forms with the
relations f and t (guide Table 59 offsets 0 and 7), valid only for the
vopc_vcc rule, backed by false_b32/true_b32 primitives. They keep the
#239 contract: sources are decoded and checked as for every compare,
VCC_LO := EXEC & existing lanes & test, fully written, and the mask is
lane-derived. Their MSL wave mask reads no operand bits. A new
LLVM-assembled fixture covers F clearing a stale VCC, T and F under
partial EXEC, T reading vcc_lo and runtime s_cbranch_vccz on both
results; the oracle merged from task/215-vopc-oracle supplies the
reference side.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* test(vopc): cover EXEC preservation, known-0 branch, pending loads (#215)

Review found four ways F/T could be wrong and still pass: clearing EXEC
under partial EXEC, treating the empty-EXEC result as lane-derived,
ignoring an outstanding load on a source, and decoding opcode 200. Add a
case or rejection for each; each was shown failing with that break.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa: check VOPC relations against the Table 59 opcode layout and the VCC write direction (#215)

Review fixes. A VOPC compare's opcode must equal its group base (128
signed, 192 unsigned) plus its relation's Table 59 offset, so a row such
as V_CMP_T_I32 with relation f is rejected instead of lowering to false.
A lane_mask form now needs exactly one fieldless XML VCC operand that is
written and not read. The generator tests render the real F/T rows, and
the vector-compare doc names the file each count comes from.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa: split the semantic registry into one file per encoding family (#215)

crates/isa/semantics/rdna2.toml keeps the schema, architecture, snapshot
hash, cited documents and field meanings, and lists the family files under
`include`: rdna2/{sop2,sopc,sop1,vop2,vopc}.toml, each holding only the
operand rules and forms of the family it is named after. The generator
merges them in include order, and rejects a form or rule of another
family, a rule declared twice, root keys in a family file and a missing or
repeated include. The merged registry equals the former single file, and
semantics_gen.rs is byte-identical (generate_semantics.py --check passes
unchanged). The coverage report and the RDNA2 planner read the merged
registry; their output is unchanged. Parallel work on different families
no longer edits the same file.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa, decoder, shader: registry encoding variants; v_add_nc_u32_e64 as the first (#215)

An [[encoding_variant]] re-encodes a declared form in another family: it
names the form, the family, its opcode there and that encoding's operand
rule, and inherits the rest. The XML check runs on the inherited
declaration, and the generator rejects variants of undeclared forms, in
the form's own family, duplicates, rules that cannot encode the form and
forms that use a variant-only rule. It emits from_<family>_word and
<family>_assembly_name on the base enum and one FORMS row per variant.

rdna2/vop3.toml declares the vop3_vgpr2 rule (the subset the hand-written
decoder accepted: VGPR sources, no modifiers, unused SRC2) and the VOP3
encoding of V_ADD_NC_U32. The decoder dispatches it through
VectorAluOp::from_vop3_word into Instruction::VectorAluVop3, which replaces
AddNoCarryU32; the shader lowers it through the VOP2 form's template and
still admits only v_add_nc_u32_e64 inside a runtime s_cbranch_vccz region.
Goldens, known answers and the LLVM oracle are unchanged.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa, scripts: review fixes for the registry split and encoding variants (#215)

- Includes must be `<root stem>/<family>.toml`, so a family file cannot
  live outside the registry directory or be aliased past the repeat
  guard. The coverage report (and through it the RDNA2 planner) now uses
  the generator's loader, so the family-file guards apply to every
  consumer.
- A variant's explicit XML operand formats, destination included, must
  equal its base encoding's; malformed variant fields are diagnosed
  instead of raising.
- Variants get their own generated enum (VectorAluVop3Op: from_word,
  base, assembly_name, semantics), so Instruction::VectorAluVop3 cannot
  name an undeclared encoding and formatting cannot panic.
- The planner no longer counts a variant-only operand rule as a rule that
  can host new forms of its family (V_FMA_F32 was shown as reuse-ready).
- The isa test checks that no first word of another 64-bit family
  (VOP3B) selects a VOP3 variant; docs describe the variant files.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa, scripts: second round of registry review fixes (#215)

- A family file must be a regular file directly in the registry
  directory: links (and so second names for one file) are rejected.
- Variant operand formats are compared by role (destination, then the
  sources in rule order), not by XML row order.
- Malformed spec and verify values are diagnosed instead of raising.
- vop3_vgpr2 declares variant_only = true in the data; the planner reads
  that flag instead of inferring it from which entries use the rule.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa: third round of registry review fixes (#215)

- The family directory must not be a link, and two includes must not be
  hard links to one file.
- The role-based format comparison skips malformed rules (they keep their
  rule diagnostic instead of raising), and its test now reproduces the
  row-order case the old comparison got wrong.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa: fourth round of registry review fixes (#215)

A self-referential family-directory link is reported instead of raising,
a malformed rule destination field is a rule diagnostic in the XML check
too, and the row-order test asserts a fully valid registry so it catches
the old row-order comparison.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa, scripts: registry loader and variant validation give diagnostics, not tracebacks (#215)

- A standalone registry (no include) no longer needs a family directory.
- A variant of an incomplete form reports the form instead of a KeyError.
- A non-array encoding_variant, or a non-table entry, is a diagnostic in
  the loader, the validator and the coverage report.
Each case has a test that fails on the previous code. The split-registry
test now compares the whole merged result with a hand concatenation, and
vop3.toml cites guide 12.7.1 for the VOP3 opcode offset.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa, scripts: two more registry crash paths become diagnostics (#215)

- A variant whose first duplicate base form is incomplete: the completeness
  check and the XML check now use the same base row (no KeyError).
- qa rdna2 inventory and rank report a malformed encoding_variant (missing
  'of', non-string operands) as an error with exit 2, not a traceback; the
  coverage reader checks the field types.
Each has a test that fails on the previous code.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

---------

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:37:03 -06:00
elforeign 9500ed17e5 ref, validation: independent oracle for the SOPK integer forms
Adds s_movk_i32, s_cmovk_i32, s_cmpk_{eq,lg,gt,ge,lt,le}_{i32,u32},
s_addk_i32 and s_mulk_i32 (guide 12.2, 13.1.2) to the reference
interpreter and the second interpreter, each written from the guide
separately, and a guide-derived test that runs both. SDST is limited to
s0-s105; every other SOPK opcode and SDST stays refused.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:37:00 -06:00
elforeign 980436a963 Merge commit '263284f' into task/215-m27 2026-11-24 08:35:57 -06:00
elforeign d6b751976d docs, shader, isa: review fixes for the VOP2 logical and shift move (#215)
The registry doc states where a reversed shift takes its count and which
side masks it, and that a family may have several operand rules; the
runtime-region rejection message and a test comment no longer call the
six forms hand-written.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:35:00 -06:00
elforeign 263284ff4f isa, scripts: two more registry crash paths become diagnostics (#215)
- A variant whose first duplicate base form is incomplete: the completeness
  check and the XML check now use the same base row (no KeyError).
- qa rdna2 inventory and rank report a malformed encoding_variant (missing
  'of', non-string operands) as an error with exit 2, not a traceback; the
  coverage reader checks the field types.
Each has a test that fails on the previous code.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:34:00 -06:00
Adeeb Rahman 02f06bbbe8 Merge upstream main eb85731 into system runtime branch
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 09:33:14 -05:00
Adeeb RahmanandCursor ac6f9daff3 Add guest mutexes, locks, one-time init, SLists and TLS slots
Ownership is keyed by guest TEB. Operations that would block another
guest thread stop with the runtime-limit fault because no guest
scheduler exists. Also stop the import generator from overriding the
semaphore handlers with stubs, and check every generator standard
service against the loader registry.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-24 09:33:07 -05:00
elforeign e1e261ea82 isa, decoder, shader: move the six VOP2 logical and shift forms into the registry (#215)
v_and_b32, v_or_b32, v_xor_b32, v_lshlrev_b32, v_lshrrev_b32 and
v_ashrrev_i32 (_e32) are now registry forms under a new operand rule
vop2_vgpr2: both sources VGPRs, the subset the hand-written decoder
accepted. The rule shares the VectorAluOp enum with vop2_vgpr; the
generator renders one enum per shared rule set and an operand_rule()
the decoder dispatches on. VectorBinary gains And, Or, Xor and the three
shifts with the count masked to S0[4:0]; the shifts declare reversed
sources, and the generator now checks the XML count format on SRC0 for
reversed forms. The six hand-written Instruction variants, decoder arms
and shader Binary variants are removed; the runtime-region allowlist
admits exactly the same six forms.

No behaviour change: 132,608 VOP2/VOP1/SOP1 words decode to the same
text, length and error before and after; the MSL goldens are unchanged.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:30:54 -06:00
elforeign f4c4b5f9d0 Merge remote-tracking branch 'origin/main' into task/215-vop1-int-oracle
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:29:04 -06:00
elforeign c5238a83a3 Tighten the VOP1 checks the review found weak
A fresh review showed that the swap max-register cases saw only one of
the two writes, the flag cases could not see a VCC rotation, the swap
SRC0 sweep could pass on a failed SGPR read, and no case read or wrote a
VGPR with a load outstanding. Add the other-register reads, a partial
VCC_LO seed, a decode-level check of every swap SRC0 selector and twelve
pending-load rejections.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:28:45 -06:00
elforeign de536c033b Merge remote-tracking branch 'origin/main' into task/215-registry-split 2026-11-24 08:27:07 -06:00
elforeign eb85731d5d metal: retire command buffers on completion (#135) (#301)
* metal: time each host stage of a compute dispatch

The Apple M5 benchmark shows ~215 us host wall per translated dispatch
against ~1.4 us of GPU time, with ~170 us unexplained around submission.
Record buffer allocation, encoding, commit, waitUntilCompleted and
readback in RunProfile and export them, with the remainder, in the
benchmark's results.json and a new report table, so the cost can be
attributed before changing command-buffer retirement (#135).

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* metal: retire command buffers on completion (#135)

Every compute dispatch committed and then blocked in waitUntilCompleted,
which the stage timers show is ~94% of the host time not spent compiling
(launch ~78 us and wake ~58 us around ~7 us of GPU work on an M5 Pro).
A caller with several dispatches paid that round trip for each one.

Add submit_words, which commits without blocking and returns a
Submission token, and wait, which collects the result. Command buffers
now use unretained references: an in-flight table owns the pipeline,
buffers, textures and sampler until Metal reports the buffer Completed
or Error. A sweep on every submit and wait then frees those resources,
keeping the result for a live token and discarding it for a dropped
one. At most 16 submissions hold GPU resources; the next submit
returns an in-flight limit error instead of blocking. The existing
synchronous calls run as submit plus wait and keep their results and
error names. The benchmark adds a batched row: 8 dispatches with one
wait each versus 8 synchronous runs.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

---------

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:26:36 -06:00
elforeign 06ded40d54 isa, scripts: registry loader and variant validation give diagnostics, not tracebacks (#215)
- A standalone registry (no include) no longer needs a family directory.
- A variant of an incomplete form reports the form instead of a KeyError.
- A non-array encoding_variant, or a non-table entry, is a diagnostic in
  the loader, the validator and the coverage report.
Each case has a test that fails on the previous code. The split-registry
test now compares the whole merged result with a hand concatenation, and
vop3.toml cites guide 12.7.1 for the VOP3 opcode offset.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:26:23 -06:00
elforeign 22e1864b36 Clarify what the VOP1 rejection sweeps establish
The guide-only cross-check noted that the opcode sweep cannot isolate why
a form is refused and that the SRC0 rejections are the accepted subset,
not a guide limit; say so. Also name the bit-position pattern type for
clippy.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:24:53 -06:00
elforeign 21da49b109 Merge remote-tracking branch 'origin/main' into task/215-registry-split
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
#	crates/decoder/src/lib.rs
#	crates/isa/generate_semantics.py
#	crates/isa/semantics/rdna2.toml
#	crates/isa/src/lib.rs
#	crates/isa/src/semantics.rs
#	crates/isa/src/semantics_gen.rs
#	crates/isa/tests/semantics.rs
#	docs/shaders/semantic-coverage.md
#	docs/shaders/vector-compare.md
#	tests/semantics_generator/test_generate_semantics.py
2026-11-24 08:24:19 -06:00
elforeign 175335e1f6 Add a guide-derived oracle for the VOP1 integer forms
Issue #215 slice S12: the reference and the second interpreter now decode
and run v_not_b32, v_bfrev_b32, v_ffbh_u32, v_ffbl_b32, v_ffbh_i32 (SRC0:
SGPR, vcc_lo, inline integer, literal or VGPR) and v_swap_b32 (VGPR SRC0),
all _e32, from the RDNA 2 ISA guide section 12.8 pseudocode. The new
vop1_integer test checks both against expectations written separately from
the guide, and checks that both refuse the other SRC0 selectors and every
other VOP1 opcode at the same word. Float forms, lane-crossing and
M0-relative forms, and V_SAT_PK_U8_I16 (its guide entry does not define
sat8) stay unsupported.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:22:51 -06:00
elforeign b37a859cd6 isa, decoder, shader: Wave32 VOPC integer compares through the semantic registry, plus v_cmp_{f,t}_{i32,u32} (#215) (#295)
* isa, decoder, shader: move the twelve Wave32 VOPC compares into the semantic registry (#215)

The v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32 forms from #239 are now
registry data under a new vopc_vcc operand rule (SRC0 a vector_source,
VSRC1 a VGPR, destination implicitly vcc_lo). The decoder dispatches them
through the generated VectorCompareOp instead of a hand-written opcode
table, and the hand-written VectorCompareOp struct in xenora-isa is gone.
No behaviour change: goldens, known answers and the LLVM oracle are
unchanged.

The vocabulary gains vcc = "lane_mask", allowed exactly for the VOPC rule
and required to account for the XML's implicit VCC output, and wave =
"wave32", now allowed exactly for that rule (its one entry point is the
Wave32 compute fixture ABI) and still rejected elsewhere. exec must stay
unchanged, so v_cmpx cannot be declared.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* test(vopc): independent oracle for v_cmp_{f,t}_{i32,u32}_e32 (#215)

The registry stage adds the four constant 32-bit integer VOPC compares,
which nothing could check: the reference and the second interpreter both
rejected them. Derive them from the RDNA 2 guide only (12.9 Table 61:
D = 0 / D = 1; 3.9: VCC[n] = EXEC[n] & test, fully written) under the
#239 Wave32 contract, so T writes EXEC_LO masked to existing lanes, F
writes 0, and sources keep the allowlist and initialization rules.

vopc_f_t.rs covers every SRC0 class, aliasing, full, partial and empty
EXEC with a stale VCC_LO, a partial final wave, s_cbranch_vccz on both
edges and the rejections; the native Metal part is ignored until the
translator side lands. known_answers no longer expects F and T to be
rejected.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa, decoder, shader: v_cmp_{f,t}_{i32,u32} through the semantic registry (#215)

Adds the four constant Wave32 VOPC compares as registry forms with the
relations f and t (guide Table 59 offsets 0 and 7), valid only for the
vopc_vcc rule, backed by false_b32/true_b32 primitives. They keep the
#239 contract: sources are decoded and checked as for every compare,
VCC_LO := EXEC & existing lanes & test, fully written, and the mask is
lane-derived. Their MSL wave mask reads no operand bits. A new
LLVM-assembled fixture covers F clearing a stale VCC, T and F under
partial EXEC, T reading vcc_lo and runtime s_cbranch_vccz on both
results; the oracle merged from task/215-vopc-oracle supplies the
reference side.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* test(vopc): cover EXEC preservation, known-0 branch, pending loads (#215)

Review found four ways F/T could be wrong and still pass: clearing EXEC
under partial EXEC, treating the empty-EXEC result as lane-derived,
ignoring an outstanding load on a source, and decoding opcode 200. Add a
case or rejection for each; each was shown failing with that break.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa: check VOPC relations against the Table 59 opcode layout and the VCC write direction (#215)

Review fixes. A VOPC compare's opcode must equal its group base (128
signed, 192 unsigned) plus its relation's Table 59 offset, so a row such
as V_CMP_T_I32 with relation f is rejected instead of lowering to false.
A lane_mask form now needs exactly one fieldless XML VCC operand that is
written and not read. The generator tests render the real F/T rows, and
the vector-compare doc names the file each count comes from.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

---------

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:22:04 -06:00
Adeeb Rahman 81868436b8 Merge upstream main 714efd8 into system runtime branch
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 09:19:19 -05:00
elforeign 714efd873b qa: rank RDNA2 expansion batches by forms unlocked per missing piece of work (#215) (#298)
Adds `qa rdna2 rank`: each undeclared identified form gets an unlock key
from its XML identity and operand shape (encoding variant of a declared
form, new operand rule, or new primitive), forms are grouped by key and
the groups ranked by count over a documented planning cost (1, 2, 4).
Claimed families and paths are excluded, float groups are marked and can
be left out with --no-float, and the output is deterministic. Reuses the
planner's inventory and claim parsing; writes nothing unless --out.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:18:13 -06:00
elforeign 06d895ec23 test(vopc): close review gaps in the 64-bit oracle (#215)
The fresh review found the independent interpreter accepted v255 as a
VSRC1 pair base when SRC0 was an SGPR pair (and overflowed at run time),
and that four checks could pass with a wrong implementation: overlapping
and highest pairs decided by the high dword alone, a second wave equal
to the first, and a known-zero vccz branch over an unread SGPR. Fix the
interpreter, add both rejections, and make each case observable.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:14:28 -06:00
Adeeb Rahman 6b55d76a14 Carry analog triggers in extended guest controller snapshots
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 09:12:02 -05:00
elforeign a359956033 refactor(ref): keep Op::Compare for 32-bit forms, add Op::WideCompare (#215)
The decoder's gfx1030 test builds Op::Compare from its own decode, so
adding a width argument broke that crate's test build. Keep the 32-bit
variant as it was and carry 16- and 64-bit forms in a new variant that
shares the same evaluation.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:11:54 -06:00
elforeign 625e26affc isa: fourth round of registry review fixes (#215)
A self-referential family-directory link is reported instead of raising,
a malformed rule destination field is a rule diagnostic in the XML check
too, and the row-order test asserts a fully valid registry so it catches
the old row-order comparison.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:10:51 -06:00
Adeeb Rahman b8b42c73bf Feed macOS GameController snapshots to the interactive guest
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 09:10:35 -05:00
elforeign 01a8445412 test(vopc): check pair halves with no active lane; tighten guide notes (#215)
A reference that checked only the low register of a 64-bit pair still
passed every case, because an executing lane reads both halves anyway.
The difference shows only when EXEC_LO enables just absent lanes, so add
that rejection per 64-bit form. The guide-only cross-check also pointed
out that odd SGPR bases are illegal per 3.6.3 (not unsettled), that the
negative inline bit patterns are a reading of Table 20, and that "empty
EXEC reads nothing" is the contract's rule; say so in the module notes.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:10:26 -06:00
elforeign 06614f2219 isa: third round of registry review fixes (#215)
- The family directory must not be a link, and two includes must not be
  hard links to one file.
- The role-based format comparison skips malformed rules (they keep their
  rule diagnostic instead of raising), and its test now reproduces the
  row-order case the old comparison got wrong.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:09:16 -06:00
Adeeb Rahman e984cfc099 Feed native playback refills through the runtime PCM queue
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 09:09:16 -05:00
Adeeb Rahman 3ca4c8586c Render PCM playback blocks with silence and accurate underrun counts
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 09:08:10 -05:00
elforeign 93d26d6e45 test(vopc): independent oracle for 16- and 64-bit integer compares (#215)
B1 adds v_cmp_{lt..ge}_{i16,u16}_e32 and v_cmp_{f..t}_{i64,u64}_e32 as
registry forms. To check them without trusting the registry, decoder or
shader, both interpreters now decode and evaluate the 28 forms from the
RDNA 2 guide alone: 16-bit forms read bits 15:0 and ignore the upper
half, 64-bit forms read register pairs low dword first, inline integers
keep their value at the operand width, and VCC_LO = EXEC & lanes & test.
Points the guide does not settle (literals, vcc as a pair, odd SGPR
bases, v255 as a pair base) are rejected. vopc_wide.rs derives the
expected lanes per form: 6212 cases on each interpreter, 1128 rejections.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:08:00 -06:00
Adeeb Rahman 7f80767810 Refill a bounded native audio playback window
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 09:07:08 -05:00
elforeign 846589abce isa, scripts: second round of registry review fixes (#215)
- A family file must be a regular file directly in the registry
  directory: links (and so second names for one file) are rejected.
- Variant operand formats are compared by role (destination, then the
  sources in rule order), not by XML row order.
- Malformed spec and verify values are diagnosed instead of raising.
- vop3_vgpr2 declares variant_only = true in the data; the planner reads
  that flag instead of inferring it from which entries use the rule.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:06:26 -06:00
Adeeb Rahman 1edcbb651d Verify native audio mixing and sample-rate conversion offline
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 09:06:17 -05:00
Adeeb Rahman efe9fdeb8d Select and verify the native playback output device
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 09:05:17 -05:00
Adeeb Rahman ccaa92ce3a Verify sequential native PCM buffer playback
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 09:04:21 -05:00
Adeeb Rahman 243a2d2c58 Discover host audio output devices through Core Audio
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 09:03:33 -05:00
Adeeb Rahman 149f9389f9 Report native audio output format and presentation latency
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 09:02:43 -05:00
jelly013 1c5c320437 test(loader): x86-64 architectural known answers from the Intel SDM (#155)
Add 727 cases and definition-based sweeps for the guest CPU, derived from
the Intel SDM (revision 093) before the CPU code was read. The interpreter
and the DBT run the same cases.

588 cases are verified, 133 use forms both engines refuse, and four ignored
tests state open defects: stale DBT blocks after the guest rewrites code,
the address of a page-crossing fault, and the fault class of a
non-canonical address and of an instruction over 15 bytes.

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 15:02:24 +01:00
Adeeb Rahman 7c3499d5a2 Play original guest PCM through the native macOS audio engine
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 09:01:49 -05:00
elforeign 6bc88d6c51 isa, scripts: review fixes for the registry split and encoding variants (#215)
- Includes must be `<root stem>/<family>.toml`, so a family file cannot
  live outside the registry directory or be aliased past the repeat
  guard. The coverage report (and through it the RDNA2 planner) now uses
  the generator's loader, so the family-file guards apply to every
  consumer.
- A variant's explicit XML operand formats, destination included, must
  equal its base encoding's; malformed variant fields are diagnosed
  instead of raising.
- Variants get their own generated enum (VectorAluVop3Op: from_word,
  base, assembly_name, semantics), so Instruction::VectorAluVop3 cannot
  name an undeclared encoding and formatting cannot panic.
- The planner no longer counts a variant-only operand rule as a rule that
  can host new forms of its family (V_FMA_F32 was shown as reuse-ready).
- The isa test checks that no first word of another 64-bit family
  (VOP3B) selects a VOP3 variant; docs describe the variant files.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:01:18 -06:00
Adeeb Rahman 7d3c004285 Preserve PCM frame boundaries and apply float sample gain
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:59:52 -05:00
Adeeb Rahman 105bf8a65c Add local fixture profiles and selection notifications
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:58:40 -05:00
Adeeb Rahman 9da73f8ad8 Expose fixture save quota usage and platform capabilities
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:57:03 -05:00
Adeeb Rahman 9241630f6c Add quota-checked save slots for original guest fixtures
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:56:19 -05:00
Adeeb Rahman 542684612d Add process-local platform lifecycle identity and settings
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:55:17 -05:00
Adeeb Rahman f9a7d99638 Drain terminated manual GDK queues with canceled callbacks
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:54:10 -05:00
elforeign 516976fb9f isa, decoder, shader: registry encoding variants; v_add_nc_u32_e64 as the first (#215)
An [[encoding_variant]] re-encodes a declared form in another family: it
names the form, the family, its opcode there and that encoding's operand
rule, and inherits the rest. The XML check runs on the inherited
declaration, and the generator rejects variants of undeclared forms, in
the form's own family, duplicates, rules that cannot encode the form and
forms that use a variant-only rule. It emits from_<family>_word and
<family>_assembly_name on the base enum and one FORMS row per variant.

rdna2/vop3.toml declares the vop3_vgpr2 rule (the subset the hand-written
decoder accepted: VGPR sources, no modifiers, unused SRC2) and the VOP3
encoding of V_ADD_NC_U32. The decoder dispatches it through
VectorAluOp::from_vop3_word into Instruction::VectorAluVop3, which replaces
AddNoCarryU32; the shader lowers it through the VOP2 form's template and
still admits only v_add_nc_u32_e64 inside a runtime s_cbranch_vccz region.
Goldens, known answers and the LLVM oracle are unchanged.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 07:53:50 -06:00
Adeeb Rahman 32e41e3890 Schedule delayed GDK callbacks on manual ports
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:52:34 -05:00
Adeeb Rahman bf56047db9 Wait for manual GDK callbacks with bounded dispatch deadlines
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:51:29 -05:00
Adeeb Rahman fa2e89cc06 Dispatch queued GDK callbacks through translated guest execution
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:50:31 -05:00
elforeign 2384bed8b4 isa: split the semantic registry into one file per encoding family (#215)
crates/isa/semantics/rdna2.toml keeps the schema, architecture, snapshot
hash, cited documents and field meanings, and lists the family files under
`include`: rdna2/{sop2,sopc,sop1,vop2,vopc}.toml, each holding only the
operand rules and forms of the family it is named after. The generator
merges them in include order, and rejects a form or rule of another
family, a rule declared twice, root keys in a family file and a missing or
repeated include. The merged registry equals the former single file, and
semantics_gen.rs is byte-identical (generate_semantics.py --check passes
unchanged). The coverage report and the RDNA2 planner read the merged
registry; their output is unchanged. Parallel work on different families
no longer edits the same file.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 07:49:07 -06:00
Adeeb Rahman b8fae106af Queue bounded GDK guest callbacks on shared ports
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:48:46 -05:00
Swastick Chowdhury 547b10250d loader: lower BSF, BSR and register BT in the ARM64 DBT (#196)
BSF, BSR and BT were decoded and executed by the interpreter, but every
occurrence of them in a translated block fell back to the shared semantics,
because `is_native` did not list them. The static probe therefore counted
them among the instructions the ARM64 DBT does not support.

Lower them to ARM64:

- BSF writes the index of the lowest set bit of the source and BSR the index
  of the highest set bit. The lowest set bit is the highest set bit of the
  reversed value, so BSF is `RBIT` followed by `CLZ`, and BSR is 63 minus the
  leading zero count.
- A zero source sets the zero flag and leaves the destination undefined, so
  the destination keeps its value. The interpreter and the independent
  reference apply the same rule, and the reference marks the destination as
  undefined so it is not compared.
- BT sets the carry flag from the tested bit, with the bit index masked to
  the operand width. The bit string is not modified.

Only the `0F A3` form of BT is lowered. The `0F BA` group form takes an
immediate index and may write memory, so it stays on the shared semantics and
is not advertised as natively supported.

The new encodings of RBIT, CLZ and LSLV were cross-checked against LLVM 23.1.6
`llvm-mc -show-encoding`.

The BSF, BSR and BT fixtures in `tests/x86/integer.txt` already cover the
16-bit, 32-bit and 64-bit forms with register and memory sources, and the
fixture test asserts that a native form never reaches the shared-semantics
helper, so those fixtures now exercise the new native path against the
independent reference. A new test pins the zero source, the highest bit, the
operand widths, the flag results and the masked bit index.

Closes #196

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 19:17:53 +05:30
Adeeb Rahman 4b370efa12 Expose shared ports for manual GDK composite queues
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:47:43 -05:00
Adeeb Rahman f6c87de433 Add manual GDK task queue handle ownership
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:46:45 -05:00
Adeeb Rahman 0b6ab43ad4 Apply task deadlines to cooperative background work
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:45:32 -05:00
Adeeb Rahman aa93665b97 Allow cooperative cancellation of running runtime tasks
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:44:37 -05:00
Adeeb Rahman 565c144a39 Run runtime tasks on a managed background worker
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:43:38 -05:00
elforeign ef90105a26 isa: check VOPC relations against the Table 59 opcode layout and the VCC write direction (#215)
Review fixes. A VOPC compare's opcode must equal its group base (128
signed, 192 unsigned) plus its relation's Table 59 offset, so a row such
as V_CMP_T_I32 with relation f is rejected instead of lowering to false.
A lane_mask form now needs exactly one fieldless XML VCC operand that is
written and not read. The generator tests render the real F/T rows, and
the vector-compare doc names the file each count comes from.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 07:43:08 -06:00
Adeeb Rahman ed33b57c8d Exercise manual asynchronous tasks through original guest services
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:42:27 -05:00
Adeeb Rahman 9e2c7b6e0b Add bounded manual work and completion ports for runtime tasks
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:41:17 -05:00
elforeign e95b0a055d Merge commit '8909b99' into task/215-vopc 2026-11-24 07:40:30 -06:00
Adeeb Rahman 88e7dad8b2 Verify UDP polling wakes on a concurrent send
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:40:20 -05:00
Adeeb Rahman 7ff88bc3f4 Support bounded positive timeouts in guest UDP polling
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:39:27 -05:00
elforeign 8909b99ece test(vopc): cover EXEC preservation, known-0 branch, pending loads (#215)
Review found four ways F/T could be wrong and still pass: clearing EXEC
under partial EXEC, treating the empty-EXEC result as lane-derived,
ignoring an outstanding load on a source, and decoding opcode 200. Add a
case or rejection for each; each was shown failing with that break.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 07:39:24 -06:00
elforeign b559fb575c isa, decoder, shader: v_cmp_{f,t}_{i32,u32} through the semantic registry (#215)
Adds the four constant Wave32 VOPC compares as registry forms with the
relations f and t (guide Table 59 offsets 0 and 7), valid only for the
vopc_vcc rule, backed by false_b32/true_b32 primitives. They keep the
#239 contract: sources are decoded and checked as for every compare,
VCC_LO := EXEC & existing lanes & test, fully written, and the mask is
lane-derived. Their MSL wave mask reads no operand bits. A new
LLVM-assembled fixture covers F clearing a stale VCC, T and F under
partial EXEC, T reading vcc_lo and runtime s_cbranch_vccz on both
results; the oracle merged from task/215-vopc-oracle supplies the
reference side.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 07:38:55 -06:00
Adeeb Rahman 0109aea9ea Report synthetic UDP socket type and datagram limit
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:38:28 -05:00
elforeign f916998f10 Merge branch 'task/215-vopc-oracle' into task/215-vopc 2026-11-24 07:37:55 -06:00
Adeeb Rahman ce2a753d2f Expose guest UDP local and peer addresses
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:37:34 -05:00
Swastick Chowdhury e3bbc955bc ffi: share one Metal device and queue across frame-loop sessions (#290)
Each frame-loop session opened its own Metal command queue. The GPU
driver allocates a per-queue working set on the first command buffer
(about 45 MiB on an Apple M5 with validation) and frees it
asynchronously 10-50 ms after the queue is released, so the footprint
read right after a session ended swung by about 50 MiB and the
repeated-sessions footprint test failed intermittently (5 of 30 runs).
There was no leak. Sessions now share one process-wide NativeCompute,
which is Send + Sync, so the working set is allocated once and kept.

Remove the settled_footprint wait added in #292: the original test
measures the immediate footprint again. Add a 50-session regression
test (completion, pause and resume, destroy while running) and a
concurrent two-session test for shared-queue correctness and session
isolation.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 19:07:18 +05:30
Adeeb Rahman 342fcbd17d Format guest IPv4 addresses through Winsock inet_ntop
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:36:38 -05:00
Adeeb Rahman 7a91e11742 Report immediate Winsock UDP readiness through WSAPoll
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:35:53 -05:00
Adeeb Rahman e3cd65cb79 Build guest UDP endpoints through Winsock address conversion
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:34:40 -05:00
elforeign 1ac4f82d7a test(vopc): independent oracle for v_cmp_{f,t}_{i32,u32}_e32 (#215)
The registry stage adds the four constant 32-bit integer VOPC compares,
which nothing could check: the reference and the second interpreter both
rejected them. Derive them from the RDNA 2 guide only (12.9 Table 61:
D = 0 / D = 1; 3.9: VCC[n] = EXEC[n] & test, fully written) under the
#239 Wave32 contract, so T writes EXEC_LO masked to existing lanes, F
writes 0, and sources keep the allowlist and initialization rules.

vopc_f_t.rs covers every SRC0 class, aliasing, full, partial and empty
EXEC with a stale VCC_LO, a partial final wave, s_cbranch_vccz on both
edges and the rejections; the native Metal part is ignored until the
translator side lands. known_answers no longer expects F and T to be
rejected.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 07:34:38 -06:00
elforeign 544ee8de83 isa, decoder, shader: move the twelve Wave32 VOPC compares into the semantic registry (#215)
The v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32 forms from #239 are now
registry data under a new vopc_vcc operand rule (SRC0 a vector_source,
VSRC1 a VGPR, destination implicitly vcc_lo). The decoder dispatches them
through the generated VectorCompareOp instead of a hand-written opcode
table, and the hand-written VectorCompareOp struct in xenora-isa is gone.
No behaviour change: goldens, known answers and the LLVM oracle are
unchanged.

The vocabulary gains vcc = "lane_mask", allowed exactly for the VOPC rule
and required to account for the XML's implicit VCC output, and wave =
"wave32", now allowed exactly for that rule (its one entry point is the
Wave32 compute fixture ABI) and still rejected elsewhere. exec must stay
unchanged, so v_cmpx cannot be declared.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 07:33:50 -06:00
Adeeb Rahman 731f9448c3 Verify guest UDP loopback over bound Winsock imports
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:33:38 -05:00
Adeeb Rahman 198242e5e4 Deliver bounded UDP datagrams inside guest loopback
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:32:34 -05:00
Adeeb Rahman aacd160626 Add bounded guest Winsock startup and UDP socket lifecycle
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:30:55 -05:00
Adeeb Rahman 8343e0cdc6 Report host file read failures through distinct VFS statuses
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:29:28 -05:00
Adeeb Rahman 2128e8e81f Merge remote-tracking branch 'origin/main' into feat/system-runtime-expansion
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 08:28:20 -05:00
Adeeb Rahman 73764899c2 Isolate Win32 last-error state by guest thread
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:27:46 -05:00
Ranveer Soni 6d073a99b5 Merge pull request #294 from ranveersoni98/feat/infra-phase3-compat
Feat/infra phase3 compat
2026-11-24 18:57:23 +05:30
Ranveer Soni 60bfaff97e wip(qa): checkpoint compatibility gap analysis
Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 18:55:53 +05:30
Adeeb Rahman 51269bb714 Isolate CRT errno by guest thread within the address space
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:25:33 -05:00
Adeeb Rahman c1e6646bf2 Use typed HRESULT results at the guest graphics boundary
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:24:10 -05:00
Ranveer Soni b29a504506 feat(qa): add typed runtime service inventory from services.txt.
Report implemented, partial and stub services separately from API-set aliases; do not invent independent verification.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 18:53:27 +05:30
Adeeb Rahman 2647ba0f14 Keep ordinal identity in the import-list generator
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:22:58 -05:00
Ranveer Soni b2a36e9c16 feat(qa): add authoritative x86 CPU inventory from the instruction registry.
Replace heuristic opcode scanning for Phase III planning with generate_x86.load over instructions.toml, native/shared partitions from dbt.rs, and a separate unsupported catalog.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 18:52:37 +05:30
Adeeb Rahman 2367414be5 Preserve typed import identities in probe and sync reports
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:20:01 -05:00
Adeeb Rahman 1d0b0d1547 Generate documented ordinal aliases for typed runtime services
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:18:16 -05:00
Adeeb Rahman fbb487384f Resolve registered ordinals through guest module handles
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:16:53 -05:00
Adeeb Rahman ac13c59b7d Track built-in guest module references and revoke released exports
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:15:06 -05:00
Adeeb Rahman d12b50075b Exercise standard kernel services through an exact-byte CLI fixture
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:13:22 -05:00
Adeeb Rahman dd1d1f27e6 Register standard runtime services in the trusted CLI worker
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:11:50 -05:00
Adeeb Rahman 19465370d1 Report emitted adapters and stubs separately from catalog tiers
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:10:40 -05:00
Adeeb Rahman 5617b883b9 Execute emitted CRT and stub handlers in generated conformance tests
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:09:03 -05:00
Adeeb Rahman 3922f56d68 Cover CRT boundary faults and atomic overlapping moves
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 08:07:05 -05:00
Adeeb Rahman 017b303e79 Merge remote-tracking branch 'origin/main' into feat/system-runtime-expansion
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>

# Conflicts:
#	CHANGELOG.md
#	crates/import-gen/src/codegen.rs
#	crates/loader/src/imports.rs
#	crates/loader/src/services.rs
2026-11-24 08:07:05 -05:00
Ranveer Soni c7351c846d Merge pull request #291 from Swastickc/task/289-segment-tests
loader: restore and complete FS/GS segment-override tests (#289)
2026-11-24 18:13:09 +05:30
Ranveer Soni 78d52c0eeb Merge pull request #292 from Swastickc/task/290-footprint-settle
test(ffi): read a settled memory footprint in the frame-loop test (#290)
2026-11-24 18:12:55 +05:30
Ranveer Soni 4ebbd4767f Merge pull request #288 from jelly013/cpu-runtime-continuation
CPU and runtime: shared x86-64 decoder, SSE2, exact floating point and typed imports
2026-11-24 18:12:23 +05:30
Swastick Chowdhury 5a6a3b3e4f test(ffi): read a settled memory footprint in the frame-loop test (#290)
After a session is destroyed, Metal returns its memory asynchronously;
an immediate reading can sit up to about 45 MiB above the floor it
returns to within a second. Read the footprint until two consecutive
readings agree within 1 MiB (at most 5 s) for both the baseline and the
final sample. The 16 MiB threshold and Metal validation are unchanged,
and an injected per-session leak still fails the test.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 18:08:35 +05:30
Swastick Chowdhury 8cae9772b6 loader: restore and complete FS/GS segment-override tests (#289)
Restore the six #280 regression tests that the merge resolving #280's
conflict with #283 removed. Add FS and GS RIP-relative loads and stores
with positive and negative displacements, a differential run comparing
the native DBT and interpreter registers and memory bytes, and
RIP-relative faults reporting the segment-adjusted address. Make the
existing differential test compare both paths' memory.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 18:08:32 +05:30
jelly013 13c259027b Merge upstream main (#286, #287) into CPU/runtime continuation
Keep the probe truncation test and the bounds check on section offsets from

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
#286, with imports on the shared parser.
2026-11-24 13:35:58 +01:00
jelly013 42825b223b Merge upstream main (#280, #281, #282, #283) into CPU/runtime continuation
Keep every upstream test and the new assembler forms. Keep the shared
decoder and lowering, which already cover the merged MOVZX, MOVSX and
segment fixes, and adopt upstream's rule that GS applies when FS and GS
overrides are combined. Add segment regressions for RIP-relative operands,
negative displacements and fault addresses in both engines.

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 13:33:18 +01:00
Ranveer Soni 4db0b9c530 Merge pull request #286 from Swastickc/task/270-probe-truncated-names
loader: stop the static probe panicking on truncated PE names (#270)
2026-11-24 18:01:12 +05:30
Ranveer Soni 2b97a66db9 Merge pull request #287 from Swastickc/task/284-native-app-gate6
app: audio PCM streaming and virtual filesystem integration (#284)
2026-11-24 18:00:58 +05:30
jelly013 280cd492fe runtime: one import resolver and typed service adapters
Parse import directories with one bounded parser shared by the static probe
and the binder, and resolve imports through one registry lookup. Refuse
conflicting registrations, keep ordinals apart from names, match API sets
exactly, and bind only when every import resolves.

Generate typed Win64 adapters, metadata and a coverage report from a
declarative service registry. Pass floating-point arguments and results in
XMM registers, and stop the guest if a service changes a nonvolatile
register. Make unimplemented generated wrappers fail explicitly.

Verify 20 services by calling them from translated guest code through bound
import slots, and the parser on damaged tables.

Refs #201, #270

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 13:29:40 +01:00
Swastick Chowdhury b0984673d8 app: audio PCM streaming and virtual filesystem integration (#284)
Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:57:54 +05:30
Ranveer Soni c6a354bca5 Merge pull request #285 from ranveersoni98/feat/rdna2-planner-opt
feat(qa): tighten RDNA2 planning filters, manifests and claim exclusion
2026-11-24 17:57:31 +05:30
Swastick Chowdhury c4d0b6c000 loader: stop the static probe panicking on truncated PE names (#270)
`probe_pe_bytes` panicked on a truncated PE instead of returning an error or
reporting the import as unreadable.

The cause was in `crates/loader/src/probe.rs`. `rva_to_offset` maps an RVA to
a file offset using the section header, so on a truncated file the computed
offset can point past the end of the buffer. The loop that finds the
terminating NUL then stopped at `bytes.len()`, leaving `no > end`, and the
slice `bytes[no..end]` panicked with "range start index 1632 out of range for
slice of length 1556".

Fix both name reads:

- `rva_to_offset` now returns `None` when the computed offset is at or past
  the end of the file, because such an offset is not readable. This applies to
  every caller, so the relocation, TLS, thunk and disassembly paths are
  covered by the same rule.
- A new `read_c_string` helper reads a NUL-terminated string and returns
  `None` when the string starts outside the buffer. It replaces the
  hand-written scan in the DLL-name read and in the symbol-name read, which
  also had an unchecked `ho + 2` for the two-byte import hint.

A name that cannot be read is reported as `UNKNOWN.dll` or `UNKNOWN_SYM`,
which is what the probe already did when the RVA did not resolve at all. The
probe stays read-only and still performs no guest execution.

Add a regression test that truncates the in-repo `fixtures/pe/trusted-runner.exe`
at every length from 1 to the file size and asserts that `probe_pe_bytes`
never panics. The reported range was 1,556 to 1,665 bytes; the sweep covers
the whole file, so it also covers the other name and thunk reads that the
report noted might share the pattern. The test fails against the unmodified
probe with the reported panic and passes with this change.

Closes #270

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:57:26 +05:30
Ranveer Soni 9d83e09aa6 feat(qa): tighten RDNA2 planning filters, manifests and claim exclusion.
Add family/status filters, compact output, Codex manifests, path-only vs family claim scoping, and coverage reconcile without inflating counts.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:56:13 +05:30
Ranveer Soni 3bdc43d3ad Merge pull request #281 from Swastickc/task/66-movsx-movzx
loader: implement MOVZX and MOVSX in the interpreter (#66)
2026-11-24 17:47:21 +05:30
Ranveer Soni fa434d7174 Merge pull request #282 from Swastickc/task/279-native-app-gate5
app: persistent GPU resources, dynamic texture updates, and resource retirement (#279)
2026-11-24 17:46:43 +05:30
Ranveer Soni ed657ad802 Merge pull request #280 from Swastickc/task/72-segment-override
loader: add the FS and GS segment base to RIP-relative operands in the DBT (#72)
2026-11-24 17:46:25 +05:30
Ranveer Soni b49ec43ddc Merge branch 'main' into task/72-segment-override 2026-11-24 17:46:11 +05:30
Ranveer Soni d00c787544 Merge pull request #283 from Swastickc/task/65-movsx-dest-width
loader: clear the upper half of a 32-bit MOVSX destination (#65)
2026-11-24 17:45:40 +05:30
jelly013 5e7c21bc86 Merge upstream main (QA tooling) into CPU/runtime continuation
Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 13:13:17 +01:00
jelly013 4f4d977807 cpu: add exact SSE and SSE2 floating point
Add the scalar and packed binary32 and binary64 arithmetic, compares and
conversions, computed exactly and rounded once in software. Follow MXCSR
rounding, sticky flags, denormals-are-zero, flush-to-zero, tininess after
rounding and x86 NaN selection. Stop on unmasked exceptions without a
result. Host floating point is not used, and no form is lowered to NEON.

Verify 6,824 vectors computed with exact fractions by an independent Python
reference in both engines, and round-to-nearest results against the host.
List the behaviour that is implemented but left unasserted.

Refs #127, #128

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 13:11:07 +01:00
Swastick Chowdhury f6dfe58695 loader: implement MOVZX and MOVSX in the interpreter (#66)
The native DBT translator implements the four extension opcodes MOVZX r32/r64,
r/m8 (0F B6), MOVZX r32/r64, r/m16 (0F B7), MOVSX r32/r64, r/m8 (0F BE) and
MOVSX r32/r64, r/m16 (0F BF), with both register and memory source operands.
The interpreter implemented none of them: its 0x0F handler covered only SYSCALL
(0F 05) and BSWAP (0F C8..CF), so any of the four opcodes exited with
IllegalInstruction and the two execution paths accepted different instruction
sets for the same bytes.

Implement them in the interpreter:

- The source width follows the opcode, so 0F B6 and 0F BE read one byte and
  0F B7 and 0F BF read one word.
- The destination width follows REX.W. Without REX.W the destination is 32
  bits and its upper half is cleared; with REX.W it is 64 bits.
- MOVZX zero-extends, so both destination widths hold the same value.
- MOVSX sign-extends to the destination width, so a 32-bit destination keeps
  the sign in bits 31:0 with the upper half cleared, while a 64-bit
  destination keeps the sign extension across all 64 bits.

The effective-address computation shared by the memory forms of MOV,
MOVZX and MOVSX is extracted into an `effective_address` method so both
instruction families use one implementation. That is a pure refactor: the
address computation itself is unchanged.

Add six regression tests in crates/loader/tests/bootstrap.rs covering the
register and the memory source forms independently, both destination widths,
and the sign-extension boundary values. Every encoding was produced by LLVM
23.1.6 llvm-mc -show-encoding and the expected values follow the Intel SDM
rules for MOVZX and MOVSX.

All six tests fail against the unmodified interpreter and pass with this
change.

A related defect in the native DBT translator was found while writing these
tests: its MOVSX paths sign-extend to 64 bits unconditionally, so a 32-bit
destination keeps the sign extension in bits 63:32 instead of having them
cleared. That belongs to #65, which permits the translator files, and is
reported there rather than fixed here.

Closes #66

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:37:02 +05:30
Swastick Chowdhury b12aa502a2 loader: add the FS and GS segment base to RIP-relative operands in the DBT (#72)
The native DBT translator computed the RIP-relative address and passed it
straight to the memory helper, without adding the FS or GS segment base. The
non-RIP-relative path went through emit_effective_address, which does add it,
so the two paths in the same translator disagreed with each other, and the
interpreter in crates/loader/src/cpu.rs disagreed with both.

Per the Intel SDM Volume 3A, section 3.4.4, "When FS and GS segment overrides
are used in 64-bit mode, their respective base addresses are used in the
linear address calculation: (FS or GS).base + index + displacement", and the
AMD64 Architecture Programmer's Manual Volume 1, section 2.2.3.3, "Use of the
FS or GS prefix causes their respective segment bases to be added to the
effective address calculation." The base is added for every addressing form,
so the RIP-relative form needs it too.

The segment base is a runtime guest value, so it cannot be folded into the
translation-time immediate. The addition is factored into emit_segment_base,
which reads the base from the guest CPU state at run time, and is now called
from the RIP-relative MOV paths as well as from emit_effective_address.

Add six regression tests in the dbt test module:

- fs_segment_override_adds_the_fs_base_to_the_address: a segment-relative
  store and load land at the FS base plus the displacement, not at the bare
  displacement.
- gs_segment_override_adds_the_gs_base_to_the_address: the GS base is used,
  and a distinct FS base is left untouched.
- rip_relative_segment_override_adds_the_segment_base: the RIP-relative form
  adds the segment base. This test fails without the fix.
- segment_relative_access_to_an_unmapped_address_faults: a segment-relative
  access outside the mapped regions faults and reports the segment-adjusted
  address.
- interpreter_and_native_dbt_agree_on_segment_relative_addressing: the same
  program runs through the interpreter and the native DBT and produces the same
  state and the same memory writes.
- redundant_fs_and_gs_overrides_are_handled_the_same_by_both_paths: an
  instruction carrying both an FS and a GS override is architecturally
  undefined, so this pins the local rule that both paths prefer GS and that
  they agree with each other.

Every encoding was produced by LLVM 23.1.6 llvm-mc -show-encoding, and the
expected addresses were derived from the SDM rule above.

Closes #72

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:36:38 +05:30
Swastick Chowdhury 20780eab24 loader: clear the upper half of a 32-bit MOVSX destination (#65)
The native DBT translator sign-extended to 64 bits unconditionally and stored
the full 64-bit result, so a 32-bit MOVSX destination kept the sign extension
in bits 63:32 instead of having them cleared.

Before, both MOVSX paths did this:

    asm.sxtb_64(X9, X9);   // or sxth_64
    asm.str_uoff_64(X9, X19, (reg_idx as u32) * 8);

`sxtb_64` is `SBFM Xd, Xn, #0, #7`, which sign-extends the byte to 64 bits,
and `str_uoff_64` writes all 64 bits of the destination register.

That is correct for the REX.W form `movsbq rax, bl`, but the Intel SDM
requires a 32-bit result for the 32-bit destination form `movsbl eax, bl`. The
translator therefore left `rax = 0xFFFFFFFFFFFFFFFF` where the architecture
requires `rax = 0x00000000FFFFFFFF`.

Select the sign-extension width from REX.W:

- REX.W set: keep the 64-bit extension, which is already correct.
- REX.W clear: sign-extend to 32 bits, which also clears bits 63:32 of the
  destination because the 32-bit form writes a W register.

This needs two new assembler instructions, `sxtb_32` and `sxth_32`, which are
the 32-bit forms of the existing `sxtb_64` and `sxth_64`:

    sxtb_32: SBFM Wd, Wn, #0, #7   (0x13001c00)
    sxth_32: SBFM Wd, Wn, #0, #15  (0x13003c00)

Both encodings were confirmed against LLVM 23.1.6 `llvm-mc -triple=aarch64
-show-encoding`.

The MOVZX paths are unchanged: a zero extension produces the same value at
both destination widths, because the 32-bit form already clears the upper half.

Add three regression tests in the dbt test module covering the register and
memory source forms and the byte and word sources, each at both destination
widths. Every encoding was produced by LLVM 23.1.6 llvm-mc -show-encoding and
the expected values follow the Intel SDM rules for MOVSX.

All three tests fail against the unmodified translator and pass with this
change.

Closes #65

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:35:49 +05:30
Swastick Chowdhury 259b3054e1 app: persistent GPU resources, dynamic texture updates, and resource retirement (#279)
Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:34:01 +05:30
Adeeb Rahman d777adecf3 Merge remote-tracking branch 'origin/main' into feat/system-runtime-expansion
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 06:58:30 -05:00
Ranveer Soni f685edebfb feat(qa): wire coverage history and branch-sync into the qa CLI.
Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:27:35 +05:30
Ranveer Soni c0cb3e72be feat(qa): add RDNA2 coverage history snapshots and stale-branch reports.
Persists inventory snapshots between revisions and classifies ahead,
behind and diverged contributor branches.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:27:35 +05:30
Ranveer Soni a27d63bfab docs(coordination): refresh infrastructure QA ledger for Phase II.
Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:33 +05:30
Ranveer Soni 0f7658bb5b docs(changelog): record Phase II infrastructure automation CLIs.
Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:33 +05:30
Ranveer Soni 313430c1c6 docs(testing): document Phase II qa and release CLI workflows.
Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:33 +05:30
Ranveer Soni 63cf3595cd test(qa): smoke-test qa and release CLIs against real commands.
Covers shlex orchestration, live RDNA2 inventory and negative
readiness exit codes.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:32 +05:30
Ranveer Soni 050df307a1 feat(release): build release-readiness reports with SBOM and evidence.
Combines Mach-O, bundle, codesign, checksum and dependency inventory
checks into one non-publishing readiness report.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:32 +05:30
Ranveer Soni 7a5176497a feat(qa): detect claim collisions across renames and deletions.
Parses git name-status lines so renamed and deleted paths are handled
in shared-file collision reports.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:32 +05:30
Ranveer Soni f4005501bc feat(qa): compare recorded benchmarks with identity and noise guards.
Rejects mismatched workload/host/toolchain pairs and ignores median
moves inside a configurable noise floor.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:32 +05:30
Ranveer Soni f175a10033 feat(qa): scan CPU opcode and import coverage from existing sources.
Produces machine-readable inventories, interpreter-vs-DBT gaps and
prioritized blocker manifests without changing runtime policy.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:32 +05:30
Ranveer Soni c651a9d320 feat(qa): add unified verification profiles with stale evidence detection.
Runs existing repository commands serially, preserves exit codes and
fingerprints sources so outdated reports fail closed.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:32 +05:30
Ranveer Soni 22bafeb0b2 feat(qa): add read-only RDNA2 expansion planning over live inventories.
Discovers unsupported forms dynamically from the AMD snapshot, registry,
decoder tables and status evidence without editing GPU production code.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:32 +05:30
Ranveer Soni f56d3c9862 feat(release): add python3 -m release CLI entrypoints.
Wraps arch, linkage, bundle, manifest, license and readiness commands
for packaging checks without publishing releases.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:32 +05:30
Ranveer Soni 48f44cac3d feat(qa): add operational python3 -m qa CLI.
Exposes orchestration, PR validation, conflict prediction, RDNA2
planning, verification profiles, CPU coverage and env diagnostics.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:32 +05:30
Ranveer Soni 8410e3d0e8 test(qa): cover environment diagnostic helpers.
Positive and negative checks for host arch, Rosetta, rustc host, Swift,
LLVM, worktree cleanliness and branch sync.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:32 +05:30
jelly013 dce37dab18 cpu: add SSE2 state, moves and packed integer forms
Add XMM0-XMM15 and MXCSR to the guest state and extend the registry with
mandatory prefixes, so the shared decoder covers the SSE and SSE2 moves and
packed integer operations. Reject opcodes where 0x66 could be both an
operand size and a mandatory prefix.

Translate operations with identical NEON lane semantics to ARM64; other
forms call the shared semantics and are counted. Raise a distinct
general-protection exit for misaligned 16-byte operands and reserved MXCSR
bits. Floating-point arithmetic is not implemented.

Verify 374 LLVM-assembled instructions against a byte-array reference that
reads only their assembly text, and mixed sequences between the engines.

Refs #124, #125, #126, #128

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 12:53:35 +01:00
Adeeb Rahman a7a0235c79 Merge remote-tracking branch 'origin/main' into feat/system-runtime-expansion
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>

# Conflicts:
#	CHANGELOG.md
#	crates/loader/src/memory.rs
2026-11-24 06:48:06 -05:00
jelly013 70f1793a4c Merge upstream main (#278 and QA tooling) into CPU/runtime continuation
Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 12:44:40 +01:00
Ranveer Soni 19bea60d25 Merge pull request #278 from Swastickc/task/276-native-app-gate4
app: interactive guest execution with input handling and dynamic rendering (#276)
2026-11-24 17:11:42 +05:30
Ranveer Soni f70e6d0534 Merge branch 'main' into task/276-native-app-gate4 2026-11-24 17:11:30 +05:30
Swastick Chowdhury 223fe253c9 app: interactive guest execution with input handling and dynamic rendering (#276)
Add interactive guest execution with dynamic input handling and rendering
(Gate 4) through the versioned C runtime interface. The guest fixture
(fixtures/pe/interactive.exe, generated by fixtures/pe/interactive.py)
runs on a dedicated session-owned thread and polls host input snapshots
via xenora.dll!input_poll. It steers its rendered column position (0..3)
on native Metal and submits frames with xenora.dll!frame_submit(column).

Add xenora_session_start_interactive_loop, xenora_session_send_input,
xenora_session_queue_input, and xenora_session_get_recorded_frame to the
C interface, plus input masks (XENORA_INPUT_*) and xenora_input_state.
Pre-queuing inputs enables deterministic replay across independent
sessions without physical interaction.

Xenora.app gains interactive frame-loop controls (Interactive 300 frames,
Left, Right, Release) and a --smoke-interactive CLI flag. Four GPU
acceptance tests verify input-driven state changes, reproducible frame
sequences across deterministic replays, clean release/focus behavior
without stuck keys, and prompt join on session destruction.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:09:04 +05:30
Ranveer Soni 62be091197 docs(coordination): fill infrastructure QA ledger with commit SHAs.
Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:19 +05:30
Ranveer Soni cf288dd940 docs(changelog): note infrastructure QA tooling and agent-queue smoke fixes.
Records advisory scripts/qa and scripts/release helpers plus the live
smoke-driven agent-queue apply/audit fixes.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:19 +05:30
Ranveer Soni 9f57d8b3bb docs(testing): index infrastructure QA and release tooling.
Adds the tooling README and links from docs/README.md for new
coordination and infrastructure documents.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:19 +05:30
Ranveer Soni 5d4d15d596 feat(release): build checksum manifests and license inventories.
SHA-256 artifact manifests with evidence validation and deterministic
dependency license listings for release packaging.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 95ddc28518 feat(release): verify ARM64 Mach-O arch, linkage and app bundles.
Rejects non-arm64 lipo output, forbidden Vulkan/MoltenVK linkage and
incomplete .app layouts; diagnoses unsigned codesign output.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 9cc4a965c4 feat(qa): predict claim file-scope conflicts before editing.
Read-only overlap checks against held claims so contributors can avoid
collisions without posting /claim.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 9b767186a2 feat(qa): add Apple Silicon environment diagnostic helpers.
Checks host arch, Rosetta translation, rustc host triple, Swift/LLVM
presence and branch sync state from caller-supplied command outputs.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 823007888f feat(qa): compare orchestration history and emit handoff reports.
Detects newly failed suites, summarizes contributor progress and flags
tracked build artifacts in read-only health checks.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 881c2a2e52 feat(qa): analyze existing benchmark samples for percentiles.
Computes median, p95, p99, IQR and thresholded median regressions
without modifying benchmark workloads.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 475b27e5d4 feat(qa): add advisory PR scope, DCO and artifact validators.
Standalone checks for ownership scope, Signed-off-by trailers, build
artifacts, changelog presence and evidence SHA identity.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni cac93574ce feat(qa): add structured multi-suite test orchestration reports.
Records durations, exit codes, ignored/unexecuted suites, CPU/GPU
separation, failure excerpts and reproduction commands.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 085b0e28e5 feat(qa): preserve command exit status for orchestration pipes.
Provides the contract that failed commands stay failed even when their
stdout contains a greppable success token.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 835689e5df docs(coordination): add infrastructure QA campaign ledger.
Tracks commits, smoke status and limitations for the QA tooling campaign.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 55e1818ccd docs(coordination): record agent-queue disposable smoke evidence.
Documents live Actions results for claim, overlap refusal, release,
progress, denial and a successful audit (#180).

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 44ea8133fc fix(ci): grant agent-queue audit pull-requests:read.
Live smoke audits failed on gh pr list without this permission.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 756597a6b4 fix(agent-queue): accept summary --now after the subcommand.
Actions passes --now after summary; parent-only argparse rejected that
and failed the live audit smoke run.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
jelly013 02f9ad9a34 cpu: share one generated decoder and store guest flags
Add a declarative x86-64 instruction registry with a validating generator,
and decode through its tables in the static probe, the interpreter and the
native DBT. Move integer semantics into shared reviewed primitives and
extend them to 8-, 16-, 32- and 64-bit register and memory operands.

Store all six arithmetic flags in the guest state so they survive helper
calls and block boundaries, and correct unsigned branch conditions. Lower
common forms to ARM64; other forms call the shared semantics and are
counted. Report probe support from the decoder that executes.

Verify 985 LLVM-assembled instructions against a bit-level reference that
reads only their assembly text, and random sequences between the engines.

Refs #64, #65, #66, #68, #70, #71, #73, #118, #119, #120, #121, #122,

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
#123, #194, #195, #196
2026-11-24 12:36:52 +01:00
Ranveer Soni 4038cdbe41 docs(coordination): record infrastructure QA ownership manifest.
Lists hard exclusions, active claims, approved tooling paths and
existing scripts that must be wrapped rather than duplicated (#180).

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 16:57:34 +05:30
Ranveer Soni 51b60381c5 test(agent-queue): add read-only claim conflict prediction coverage.
Exercises claim_problem against overlap, area and dependency failures
without mutating queue state, matching live claim refusal text.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 16:57:34 +05:30
Ranveer Soni 2593f73f29 fix(agent-queue): skip no-op gh issue edit on comment-only actions.
Claim refusals and other comment-only decisions crashed apply_actions
because the edit argv already had five tokens before any label flags.
Caught by the disposable smoke repository on live Actions.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 16:57:34 +05:30
jelly013 5ab561b0e8 cpu: correct the sign- and zero-extension family
Implement MOVZX, MOVSX (0F B6/B7/BE/BF) and MOVSXD (63) for register and
checked memory operands in the interpreter and the native DBT, and report
their exact lengths in the static probe. Cover 16-, 32- and 64-bit
destinations, legacy high-byte registers and RIP-relative operands.

Fix the DBT SXTW encoding, 32-bit accesses that touched eight bytes,
RIP-relative byte and extension operands, and LEA with a segment prefix.
Make the prefix-length regression independent of an untracked file and
correct the campaign ledger.

Refs #65, #66, #67, #68, #69, #117

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 12:20:01 +01:00
Ranveer Soni 3f3f154d2d Merge pull request #275 from elforeign/task/215-vop2
isa, decoder, shader: twelve VOP2 vector integer forms through the semantic registry (#215)
2026-11-24 16:48:47 +05:30
jelly013 56febbb655 Merge upstream main (#272, #273, #274) into CPU/runtime continuation
Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 12:17:05 +01:00
elforeign 4d68733f3c Merge remote-tracking branch 'origin/main' into task/215-vop2 2026-11-24 05:12:54 -06:00
Ranveer Soni d22f046bf9 Merge pull request #274 from Swastickc/task/266-native-app-gate3
app: persistent guest rendering with pause, resume and stop (#266)
2026-11-24 16:42:33 +05:30
Ranveer Soni 430f63e27d Merge branch 'main' into task/266-native-app-gate3 2026-11-24 16:42:24 +05:30
elforeign ce29b87770 Merge remote-tracking branch 'origin/main' into task/215-vop2 2026-11-24 05:11:31 -06:00
elforeign ad424d690a isa, validation: reject undeclared implicit XML operands; runtime vcc_lo for VOP2 (#215)
Review follow-up: the generator now rejects a form whose XML lists an
implicit operand other than SCC (for example the VCC carry of
v_add_co_ci_u32 or the VCC select of v_cndmask_b32), since the
vocabulary can only declare VCC and EXEC unchanged. New known-answer
tests read a lane-derived vcc_lo as VOP2 SRC0 (also on native Metal)
and require the forms to be refused inside a runtime s_cbranch_vccz skip
region. The LLVM comparison normalises inline SRC0 for the registry VOP2
forms as for VOPC; docs and counts follow.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 05:11:31 -06:00
Swastick Chowdhury 9e47234e92 app: persistent guest rendering with pause, resume and stop (#266)
Add persistent frame-loop guest rendering (Gate 3) through the versioned
C runtime interface. The guest fixture (fixtures/pe/frame-loop.exe,
generated by fixtures/pe/frame-loop.py) runs on a dedicated guest thread,
calling xenora.dll!frame_submit(index) until commanded to halt. Each frame
is rendered on native Metal, verified against the geometry strip rule, and
returned as read-back RGBA8 buffers.

Add xenora_session_start_frame_loop, xenora_session_pause_frame_loop,
xenora_session_resume_frame_loop, xenora_session_stop_frame_loop, and
xenora_session_frame_loop_status to the C interface, plus new states.
Destroying a live session safely stops and joins the guest loop without
holding the global session lock.

Xenora.app gains persistent frame-loop controls (start 300 frames, pause,
resume, stop) and displays live frames with their index and completion
count. Add --smoke-loop CLI flag and wire the five GPU acceptance tests
into scripts/test-gpu.sh.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 16:37:34 +05:30
elforeign 5ba0496c63 isa, decoder, shader: twelve VOP2 vector integer forms through the semantic registry (#215)
Adds v_mul_{i32_i24,hi_i32_i24,u32_u24,hi_u32_u24}, v_min/max_{i32,u32},
v_xnor_b32 and v_{add,sub,subrev}_nc_u32 as registry data under a new
vop2_vgpr operand rule (VGPR destination; SRC0 a VGPR, s0-s105, vcc_lo,
an inline integer or a literal; VGPR VSRC1). Vector forms select a
per-lane VectorBinary from their declared operation and signedness, and
the shader lowers each VectorBinary through one typed MSL template; SUBREV
declares source_order = reversed. Variant names are now unique per
generated enum. The decoder shares the VOPC SRC0 decode, and the
translator binds a result to the slot it was pushed at, since operand
constants may now be pushed first. The oracle merged from
task/215-vop2-oracle supplies the reference side; a new LLVM-assembled
fixture computes every lane from its own input.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 05:06:48 -06:00
Ranveer Soni cd224d86f4 Merge pull request #272 from Swastickc/task/63-rex-x-sib
loader: extend the SIB index register with REX.X, not REX.R (#63)
2026-11-24 16:29:21 +05:30
Ranveer Soni dd4bcb30eb Merge pull request #273 from elforeign/task/215-sop2-arith
isa, decoder: sixteen SOP2 integer forms through the semantic registry (#215)
2026-11-24 16:29:07 +05:30
Ranveer Soni 0836936011 docs(cpu): add campaign progress ledger
Add docs/coordination/cpu-campaign-ledger.md tracking the Xenora native
CPU/runtime expansion campaign: starting commit, current commit, completed
batches, new forms and the remaining implementation plan.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 16:27:58 +05:30
elforeign aef29ff65d Merge branch 'task/215-vop2-oracle' into task/215-vop2 2026-11-24 04:57:47 -06:00
elforeign 3392c226ce validation: SCC stays unset across SOP2 forms that do not write it; compiler rejections at the SOP2 word (#215)
Review follow-up: four programs run BFM, MUL or MUL_HI and then CSELECT
with SCC never written, and every interpreter and the compiler must
refuse the CSELECT. The native test now also requires the compiler to
reject each program at the same word as the interpreters, so a later
failure cannot stand in (shown by a translator that turns an unset SCC
into false, which only this check catches).

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:56:28 -06:00
Ranveer Soni bfd14e4c50 feat(dbt): implement native ARM64 MOVSXD register lowering
Add SXTW to the ARM64 assembler (encoding 0x93407D00 | Wn<<5 | Xd, verified
against llvm-mc 23.1.6) and a 0x63 arm to the DBT's compile_block that loads
the source word, emits SXTW into the destination register and stores it.
Sixth test executes the instruction through the native DBT.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 16:26:24 +05:30
elforeign 72bf5f7e32 validation: VOP2 integer review gaps: reserved SRC0, literal under empty EXEC, VCC under partial EXEC (#215)
A Codex review found three ways a defective interpreter would still pass:
selectors 209-232 were never refused (a negative inline range one too
long passed), the literal was never decoded with EXEC = 0, and VCC was
only checked under full EXEC, so a VCC write limited to active lanes
went unseen. Each now has cases; a reference accepting selector 209 and
one ANDing VCC_LO with EXEC were both shown failing.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:55:51 -06:00
Swastick Chowdhury 78df3a5c6b loader: extend the SIB index register with REX.X, not REX.R (#63)
The interpreter used REX.R to extend the SIB index field and ignored REX.X
entirely, so the two paths disagreed with the native DBT translator, which
already extends the index with REX.X.

Two defects are fixed in the SIB branch of the MOV r/m effective-address
computation:

- The index register is now extended by REX.X. REX.R extends the ModRM reg
  field and must not affect the index.
- A SIB index field of 100b selects r12 when REX.X is set, and means "no
  index register" only when REX.X is clear.

REX.X is decoded from the REX prefix into the typed Prefixes struct.

Add regression tests covering an extended index register including r12, an
independent REX.R and REX.X combination, both prefix bits set together, and
the no-index case. Every encoding was produced by LLVM 23.1.6 llvm-mc and the
expected addresses were derived from the Intel SDM SIB rules.

The three REX.X tests fail against the unfixed interpreter and pass with the
fix; the no-index test passes in both cases.

Closes #63

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 16:24:57 +05:30
elforeign 133c9df448 Merge remote-tracking branch 'origin/main' into task/215-sop2-arith 2026-11-24 04:54:47 -06:00
elforeign a6d354fb2a validation: rustfmt the VOP2 integer oracle (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:52:53 -06:00
elforeign 00f79c10d2 isa, decoder, shader: sixteen SOP2 integer forms through the semantic registry (#215)
Adds s_min/max_{i32,u32}, s_cselect_b32, s_bfm_b32, s_mul_i32,
s_mul_hi_{u32,i32}, s_bfe_{u32,i32}, s_absdiff_i32 and
s_lshl1..4_add_u32 as registry data over new shared primitives. The
vocabulary gains a selected_src0 SCC effect (min and max: S0 won the
strict compare), the select's SCC input (carry_in = scc, required for
cselect), a declared shift_amount for the shift-and-add forms, and a
check that BFE's S1 descriptor is unsigned in the XML. The generated
ScalarAluOp::evaluate now returns an optional SCC, so forms whose XML
shows no SCC output leave it unchanged in the translator. The decoder
picks them up through the generated SOP2 table; the oracle merged from
task/215-sop2-arith-oracle supplies the reference side. A new
LLVM-assembled fixture chains all sixteen.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:51:33 -06:00
elforeign 95a8c61f1b ref, validation: twelve VOP2 integer forms in both interpreters (#215)
The VOP2 decode in both interpreters accepted only a VGPR as SRC0, so
the 24-bit multiplies, MIN/MAX, XNOR and the no-carry add/sub forms
also take an SGPR, vcc_lo, an inline integer or a literal through the
VOPC source decode, now shared. The reference uses exact i64
arithmetic; the second interpreter a shift-and-add multiplier with
Euclidean division for the high half, sign-flipped unsigned order for
MIN/MAX and the ripple adder for add and subtract. Neither writes VCC
or SCC, and inactive lanes keep VDST. The earlier hand-written VOP2
forms keep their VGPR-only SRC0.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:51:02 -06:00
Ranveer Soni 7e09c9ce63 feat(cpu): implement MOVSX/MOVSXD (0x63) semantics in the interpreter
Add the 0x63 arm to the software interpreter (issue #117): with REX.W it
sign-extends the 32-bit source into the destination (MOVSXD r64, r/m32);
without REX.W it writes the 32-bit destination register and zeroes the
upper half. REX.R and REX.B extend the destination and source registers.
Five interpreter known-answer tests cover negative and positive sign
extension, upper-half zeroing and register extension.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 16:19:38 +05:30
elforeign 31627363f1 validation: guide-derived per-lane oracle for twelve VOP2 integer forms (#215)
Expected values for the 24-bit multiplies, MIN/MAX, XNOR and the no-carry
add/sub forms come from the RDNA 2 guide section 12.7 only, checked per
lane over boundary operands, every SRC0 kind, aliasing, v255, partial and
empty EXEC, a partial final wave and VCC/SCC seeds. Both interpreters
reject these forms today, so the reference and independent tests fail
until they gain the forms.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:49:32 -06:00
Ranveer Soni 9cd6f43a62 fix(cpu): bound interpreter segment prefix run by the architectural instruction length
Integrate the missing instruction-length correction into the upstream Prefixes
architecture (issue #69): the interpreter now tracks the instruction length in
execute_instruction and returns Err(IllegalInstruction) when the legacy
segment prefix run or the REX fetch would exceed the 15-byte architectural
limit, preserving the upstream Prefixes struct and interfaces. Regression
tests unchanged (x86_prefix_length.rs).

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 16:15:18 +05:30
Ranveer Soni 7a3b197215 Merge branch 'main' of https://github.com/ranveersoni98/Xenora 2026-11-24 16:12:51 +05:30
Ranveer Soni ee2d29a65c Merge pull request #271 from Swastickc/task/267-app-inspect
app: open a PE executable and show read-only compatibility diagnostics (#267)
2026-11-24 16:12:12 +05:30
Ranveer Soni 83ef49c258 Merge branch 'main' into task/267-app-inspect 2026-11-24 16:11:56 +05:30
elforeign 84b6fb4d50 Merge branch 'task/215-sop2-arith-oracle' into task/215-sop2-arith 2026-11-24 04:41:40 -06:00
elforeign b98380c1b0 Merge branch 'task/215-sop2-arith-oracle' into task/215-vop2-oracle 2026-11-24 04:41:22 -06:00
Ranveer Soni bc629f5321 Merge branch 'origin/main' — typed Prefixes struct in cpu.rs (completes #62)
Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 16:09:58 +05:30
Ranveer Soni a953ba9d37 fix(cpu): enforce bounded prefix and architectural instruction length in probe, interpreter and DBT
Add crates/loader/src/x86_decode.rs with the shared architectural limit
MAX_INSTRUCTION_LEN (15 bytes) and segment_prefix_len. Bounded the legacy
segment prefix runs in the static probe, the software interpreter and the
native DBT so overlong prefix runs decode as illegal instructions instead of
consuming past the architectural limit, and the probe now rejects any decoded
record longer than 15 bytes. Regression tests cover the overlong prefix run,
prefix-count lengths, the minimized fuzz-artifact input, and interpreter and
DBT rejections (issue #69).

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 16:09:41 +05:30
Swastick Chowdhury 7fa240f7ba app: open a PE executable and show read-only compatibility diagnostics (#267)
Add xenora_inspect_executable to the C interface: a bounded, read-only
report from the static probe and loader validation (hash, headers,
sections, imports not provided by the standard runtime services, DBT
coverage of the bounded disassembly, relocation and TLS counts). Nothing
in the file is executed. A probe panic becomes a report labelled as a
Xenora defect (#270). Xenora.app opens files via Open Executable..., drag
and drop, and Finder (alternate viewer for Windows executables).

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 16:09:15 +05:30
elforeign 0e9211cd42 validation: s105 operands for the SOP2 integer forms; s_min_i32 is no longer an unsupported example (#215)
A review found that every passing sop2_arith case wrote s8-s10, so an
interpreter refusing a high destination would pass; s105 now appears as
destination, either source and all three. known_answers used s_min_i32
as an opcode outside the subset; it is supported now, so s_cselect_b64
takes its place.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:38:51 -06:00
elforeign c41e034fa1 ref, validation: 16 SOP2 integer forms in both interpreters (#215)
xenora_ref and independent_ref now run s_min/max_{i32,u32},
s_cselect_b32, s_bfm_b32, s_mul_i32, s_bfe_{u32,i32}, s_absdiff_i32,
s_lshl1..4_add_u32 and s_mul_hi_{u32,i32} as the RDNA 2 ISA guide 12.1
describes, so the guide-derived sop2_arith expectations pass on both.
CSELECT reads SCC and is refused when SCC was never written; CSELECT,
BFM, MUL_I32 and MUL_HI leave SCC unchanged. The second interpreter
uses bit loops, a ripple adder and shift-and-add products rather than
the reference's host arithmetic.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:36:31 -06:00
Ranveer Soni 7977dd4bf2 Merge pull request #268 from elforeign/task/215-sop1
isa, decoder: eleven SOP1 unary forms through the semantic registry (#215)
2026-11-24 16:06:11 +05:30
Ranveer Soni cd948d4a14 Merge pull request #269 from Swastickc/task/62-prefix-struct
loader: group interpreter instruction prefixes into a typed struct (#62)
2026-11-24 16:05:46 +05:30
elforeign a2c696b551 validation: guide-derived expectations for 16 SOP2 integer forms (#215)
Expected D and SCC for s_min/max_{i32,u32}, s_cselect_b32, s_bfm_b32,
s_mul_i32, s_bfe_{u32,i32}, s_absdiff_i32, s_lshl1..4_add_u32 and
s_mul_hi_{u32,i32}, written from the RDNA 2 ISA guide (12.1 and the
section 5 tables) before either interpreter supports them, so both fail
here. A separate guide-only table agrees on all 5086 shared inputs.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:34:26 -06:00
Swastick Chowdhury d6189ae3ea loader: group interpreter instruction prefixes into a typed struct (#62)
Replace the #[allow(clippy::too_many_arguments)] on execute_mov_rm with a
Prefixes struct that carries rex_w, rex_r, rex_b, seg_gs and seg_fs. The
interpreter decodes the prefixes once per instruction and passes the struct to
the helpers that need them, so the lint is satisfied by construction instead
of suppressed.

Add a regression test module that pins the prefix and register-extension
behaviour of the interpreter: REX.R and REX.B selecting the expected ModRM
reg and rm registers, the two bits extending independent fields, a move
without REX.W staying 32-bit wide, and the FS prefix adding the FS base.
The test was run against unmodified main first and passed there, so the
refactor is shown to preserve semantics.

Closes #62

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 16:02:10 +05:30
elforeign e6eece6983 validation: require the compiler's SOP1 rejections at the SOP1 word (#215)
Review follow-up: the native test only checked that compilation failed,
so a regressed destination guard still passed when a later instruction
read an uninitialized SGPR (shown by allowing vcc_lo as a destination).
It now requires a decode error at the SOP1 offset. Also check that no
registry form duplicates a hand-written decoder form.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:30:44 -06:00
elforeign 1a78265ede Merge remote-tracking branch 'origin/main' into task/215-sop1
# Conflicts:
#	CHANGELOG.md
2026-11-24 04:27:26 -06:00
elforeign 2e0e5a36f6 isa, decoder, shader: SOP1 unary integer forms through the semantic registry (#215)
Adds eleven SOP1 forms as registry data: complement, bit reverse, bit
counts, find-first and find-last searches, sign extension and absolute
value. Sign extension declares source_bits, which the generator checks
against the XML's 8- and 16-bit source operands; forms whose XML shows
no SCC output must declare SCC unchanged. The decoder dispatches them
through the generated SOP1 table after s_mov_b32, and the translator
folds them with ScalarUnaryOp::evaluate. The separately written oracle
from task/215-sop1-oracle supplies the reference side.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:27:14 -06:00
Ranveer Soni ece0fc27eb Merge pull request #265 from Swastickc/task/263-native-app-gate2
app: show the trusted fixture's guest-driven Metal frame (Gate 2, #263)
2026-11-24 15:56:25 +05:30
Swastick Chowdhury 82f2d9e9e6 app: show the trusted fixture's guest-driven Metal frame (#263)
Add xenora_session_run_trusted_fixture to the C interface. It runs only
the embedded trusted PE fixture through DBT startup; the guest's
fixture_draw import compiles the x9 RDNA2 shaders to MSL and renders on
native Metal. The 4x3 RGBA8 read-back is returned only when the guest
halts with the runner's expected results and every pixel equals the
pixel shader's export. Xenora.app shows the frame; --smoke-frame prints
it. Add a gpu-tests test run by scripts/test-gpu.sh.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:56:07 +05:30
elforeign 391367a531 Merge branch 'task/215-sop1-oracle' into task/215-sop1 2026-11-24 04:23:47 -06:00
Ranveer Soni e71a3da525 Merge pull request #264 from elforeign/task/215-stage-d
isa, decoder: SOPC integer compares through the semantic registry (#215 stage D)
2026-11-24 15:52:40 +05:30
elforeign b96511bfc5 validation: cover s105 in the SOP1 unary cases (#215)
Review found that every register operand was s8 or s10, so a decoder that
dropped the top bit of SDST or SSRC0 would pass. s105 now appears as source,
destination and both.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:22:34 -06:00
elforeign 84bb80d910 ref, validation: evaluate eleven SOP1 unary forms in both interpreters (#215)
Both interpreters now run s_not/brev/bcnt0/bcnt1/ff0/ff1/flbit(_b32)/
sext_i8/sext_i16/abs with SDST s0-s105. Not-found searches return -1,
s_flbit_i32 returns -1 for 0 and -1, abs keeps 0x80000000, and only NOT,
BCNT0, BCNT1 and ABS write SCC (D != 0). The reference uses host bit
intrinsics; the second interpreter works from an explicit bit array and
arithmetic, so they do not share an evaluation path.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:20:56 -06:00
elforeign 9edf644d77 Merge remote-tracking branch 'origin/main' into task/215-stage-d 2026-11-24 04:20:17 -06:00
elforeign b5d0382e89 semantics, docs: review follow-ups for the SOPC compares (#215)
Malformed relations and operand rules are diagnostics instead of
Python exceptions; the fixture now really carries a SOPC literal (LLVM
had encoded 0xffffffff as inline -1); the reference-interpreter table
and registry field table describe the current forms; the docs and
changelog state separately that the 348 rejections run on the CPU
interpreters and the compiler, not on Metal.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:20:16 -06:00
elforeign b705104403 validation: guide-derived expectations for eleven SOP1 unary forms (#215)
D and SCC for s_not/brev/bcnt0/bcnt1/ff0/ff1/flbit(_b32)/sext_i8/sext_i16/abs
are written from the RDNA 2 ISA guide (12.3 pseudocode and examples, Tables 12
and 14 for SCC) before either interpreter implements them.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:19:31 -06:00
Ranveer Soni f148b51a48 Merge pull request #262 from Swastickc/task/261-native-app-gate1
app: native macOS shell and versioned C runtime interface (Gate 1, #261)
2026-11-24 15:46:34 +05:30
elforeign c979870b3a Merge remote-tracking branch 'origin/main' into task/215-stage-d 2026-11-24 04:16:09 -06:00
elforeign cd59e081d9 isa, decoder: SOPC integer compares through the semantic registry (#215 stage D)
Adds a compare operation with a declared relation and the sopc_scalar
operand rule, so all twelve s_cmp_*_{i32,u32} forms are registry data.
The decoder dispatches them through the generated OP table and the
translator resolves SCC with ScalarCompareOp::test; the hand-written
s_cmp_eq_u32 path and its opcode constant are gone. A new LLVM-assembled
fixture records every compare's SCC, and the separately written oracle
from task/215-stage-d-oracle supplies the reference side.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:16:09 -06:00
Ranveer Soni 0bfb12fd17 Merge branch 'main' into task/261-native-app-gate1 2026-11-24 15:45:49 +05:30
Swastick Chowdhury c6d0986da2 app: add native macOS shell and versioned C runtime interface (#261)
Add crates/ffi, a static library exposing a version 1 C interface with
opaque generation-checked session handles, stable status codes and
panic containment. It can create and destroy sessions and parse the
bundled trusted PE fixture; no guest code runs. Add a minimal SwiftUI
app (Swift Package Manager) that links it, and scripts/build-app.sh to
build an ad-hoc signed, arm64-only Xenora.app and run its smoke check.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:43:08 +05:30
Ranveer Soni 9a9422c7da Merge pull request #260 from elforeign/task/215-stage-c
isa: eight SOP2 logical and shift forms through the semantic registry (#215 stage C)
2026-11-24 15:41:50 +05:30
elforeign da41b6420d Merge branch 'task/215-stage-d-oracle' into task/215-stage-d 2026-11-24 04:10:54 -06:00
elforeign 3f710928af validation: close four blind spots in the stage D cases (#215)
Review found cases that a broken implementation would still pass: an inline
or literal value that compares like its neighbour against both registers, an
extra write to the SCC-setting scratch SGPR s12, and rejections accepted at
any offset. Inline and literal cases now also compare a value with itself,
s12 is read back, and every rejection must happen at the SOPC word.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:10:00 -06:00
elforeign 2fdf01fbb3 ref, validation: evaluate the twelve SOPC integer compares in both interpreters (#215)
Both interpreters now run s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}: SCC = S0 <rel>
S1, signed for opcodes 0-5 and unsigned for 6-11, with no SGPR written. The
reference keeps Op::CompareEqual for the two EQ opcodes (its public shape is
used by other crates' tests) and adds Op::ScalarCompare for the rest, reusing
the VOPC relation; the second interpreter orders signed operands by flipping
the sign bits, so the two do not share the comparison code.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:08:32 -06:00
elforeign de00cb2bfd Merge remote-tracking branch 'origin/main' into task/215-stage-c 2026-11-24 04:08:15 -06:00
elforeign d8f9669280 semantics: require exact XML number formats and a sane count width (#215)
Review follow-up: a shift count must be FMT_NUM_U32 and other sources
must have the format their signedness implies, so a float format no
longer passes; a negative shift_count_bits is a diagnostic instead of a
crash. The stage C rows cite the guide pages where the forms are listed,
and the scalar ALU page names which suite covers which forms.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:08:15 -06:00
elforeign 19b2e9b5d5 semantics: dispatch through a generated OP-indexed table (#215)
With 17 forms the generated match on the masked word cost about 0.4 ns
(4 %) more per decoded SOP2 instruction than main. The generator now
emits a fixed-bits test plus a static table indexed by the OP field,
both derived from the XML snapshot and checked to select exactly the
same words; decoding is back to main's speed (10.05 ns).

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:07:17 -06:00
Ranveer Soni bb6bc52c95 Merge pull request #258 from Swastickc/task/80-pe-mapping-limits
loader: bound total mapped PE image size before allocation (#80)
2026-11-24 15:37:11 +05:30
Ranveer Soni ba6bbb2e4a Merge pull request #259 from Swastickc/task/77-teb-startup-bounds
loader: validate startup stack and TEB layout before mapping (#77)
2026-11-24 15:36:51 +05:30
elforeign 705b074a08 validation: guide-derived expectations for the stage D scalar compares (#215)
SCC for s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32} is written from the RDNA 2 ISA
guide (12.4, 13.1.4, 5.3) before either interpreter implements the new forms,
with cases for both branch edges, unchanged SGPRs and rejected operands.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:05:59 -06:00
elforeign d3c1150854 changelog: stage C SOP2 forms through the registry (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:04:22 -06:00
elforeign a81d62ffe3 decoder: map the stage C SOP2 operations onto the reference in the consistency test (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:04:00 -06:00
Swastick Chowdhury bb1372cd70 loader: validate startup stack and TEB layout before mapping (#77)
Replace the saturating TEB address with checked arithmetic and reject a
stack below address zero, an overflowing TEB range, or a TEB overlapping
the stack before the image is parsed. Name the Win64 TEB field offsets
and add unit tests for layout validation and field placement.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:33:38 +05:30
elforeign 8d53d82981 Merge branch 'task/215-stage-c-oracle' into task/215-stage-c 2026-11-24 04:03:01 -06:00
elforeign ba2cfc2a00 validation: close two blind spots in the stage C cases (#215)
Review found that one register operand per inline constant hides some wrong
inline values (ANDN2 with s8 = 0x80000f0f cannot tell 16 from 0), and that the
odd-opcode check used a misaligned SGPR pair. Each inline now runs against a
word and its complement, and the 64-bit neighbours read aligned pairs.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:02:10 -06:00
elforeign b13ab327f2 ref, validation: evaluate the stage C SOP2 forms in both interpreters (#215)
The reference interpreter and the second, independent interpreter now run
s_andn2/orn2/nand/nor/xnor_b32, s_lshl/lshr_b32 and s_ashr_i32 per the RDNA 2
guide: shifts use only S1[4:0] and every form sets SCC = (D != 0). The two use
different arithmetic (host bit ops vs per-bit and power-of-two evaluation),
so they cannot share a mistake with each other or with the expectations.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:00:28 -06:00
Swastick Chowdhury e7cb8db14f loader: bound total mapped PE image size before allocation (#80)
Sum max(VirtualSize, SizeOfRawData) over all sections and reject images
above a 256 MiB loader budget with SectionMappingError(AllocationFailed)
before any host allocation. Adds pe_mapping_limits tests.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:29:34 +05:30
elforeign e7795d0e5a validation: guide-derived expectations for the stage C SOP2 forms (#215)
Expected D and SCC for s_andn2/orn2/nand/nor/xnor_b32, s_lshl/lshr_b32 and
s_ashr_i32 are written from the RDNA 2 ISA guide (12.1, 5.3) before either
interpreter implements them, so the implementation cannot shape the oracle.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:57:55 -06:00
Ranveer Soni 3ff9ddde24 Merge pull request #255 from Swastickc/task/82-memory-boundaries
loader: check guest memory accesses across region boundaries (#82)
2026-11-24 15:25:18 +05:30
elforeign ff191d89bd isa: declare eight more SOP2 logical and shift forms in the registry (#215 stage C, WIP)
Adds andn2, orn2, nand, nor, xnor, lshl, lshr and ashr as registry
primitives with a declared shift-count width that the generator applies
as a mask and checks against the XML's unsigned count operand. The forms
reach the decoder and translator through the generated dispatch with no
per-form Rust. The independent oracle side lands separately.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:55:00 -06:00
Ranveer Soni 4039be8ee2 Merge pull request #256 from elforeign/task/215-s1-operand-domains
test(validation): independent operand-domain verification for SOP2/VOPC (#215 stage E)
2026-11-24 15:24:48 +05:30
Ranveer Soni 898b79dc84 Merge pull request #253 from Swastickc/task/81-reloc-validation
loader: validate base relocation directory, blocks and targets (#81)
2026-11-24 15:24:29 +05:30
Ranveer Soni 30d20c8f33 Merge pull request #254 from Swastickc/task/79-clippy-as-chunks
loader: use as_chunks for PE section headers (Clippy fix, #79 follow-up)
2026-11-24 15:24:21 +05:30
Swastick Chowdhury 0687a8add6 loader: check guest memory accesses across region boundaries (#82)
Route reads, writes, instruction fetches and loader bypass writes through
one resolver. Accesses may span adjacent mapped regions when each grants
the required permission; the whole range is checked before any byte is
copied, so failed accesses change nothing; address wraparound returns
Overflow. Adds memory_validation tests.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:22:14 +05:30
elforeign 791b736b0e changelog: note the operand-domain verification harness (#215 stage E)
Contributors need to know the harness exists, what it covers and that
its expectations are spec-derived, not hardware results.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:51:06 -06:00
elforeign fcda9c09bd Merge remote-tracking branch 'origin/main' into task/215-s1-operand-domains
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:50:44 -06:00
elforeign ad5a6f9c53 validation: operand-domain harness for SOP2 and VOPC forms (part of #215, stage E)
The nine SOP2 forms and twelve VOPC integer compares had known answers
for a few chosen inputs only. This harness generates their operand
domains (boundary values, 64-bit carry and borrow chains observing both
words, aliased registers, every integer inline constant, literals, s105
and v255, partial and zero EXEC with VCC seeded to -1, VCCZ through
s_cbranch_vccz, 32 distinct lane inputs) and runs each case on the
reference interpreter and on native Metal against expectations written
out from the public RDNA 2 guide in oracle.rs, which imports no Xenora
crate. Rejections cover a missing literal word (as truncated) and
encodings outside Xenora's subset (two literal selectors, VCC/TTMP/M0/
EXEC destinations, float inline constants), at the expected offset.

4788 cases and 498 rejections. Failures are listed per family. The
Metal part compiles its 1777 distinct programs on four threads: 16 s
with a cold shader cache on an M5 Pro, against 47 s on one thread.

The oracle agrees with an independent guide-only table on 436 of 440
cases; the other 4 are s_subb_u32 with S1 = 0xffffffff and SCC set,
where the guide leaves the width of S1 + SCC open. The oracle reads it
at full width and keeps those cases in their own family.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:50:44 -06:00
Ranveer Soni f856671b6d Merge pull request #252 from elforeign/feat/semantic-registry
isa, decoder: declarative semantic registry with generated SOP2 dispatch (#215 stages A+B)
2026-11-24 15:14:41 +05:30
Swastick Chowdhury e1317322e1 loader: use as_chunks for PE section headers (#79 follow-up)
Rust 1.100 Clippy rejects chunks_exact with a constant size
(chunks_exact_to_as_chunks), which fails the pinned
cargo clippy -D warnings gate on main since #250. No behavior change.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:14:00 +05:30
Swastick Chowdhury 92fd955a8d loader: validate base relocation directory, blocks and targets (#81)
Read the relocation directory only when NumberOfRvaAndSizes covers it,
reject odd block sizes and trailing partial block headers, keep DIR64
targets inside SizeOfImage, and check the directory end offset. Adds
relocation_validation tests for positive, negative and zero rebasing and
each malformed case.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:13:12 +05:30
elforeign 0609012903 docs: bring the registry guide in line with the post-review rules (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:41:10 -06:00
elforeign dffa50cd9c semantics: run the generator unit tests in CI and fail clearly below Python 3.11 (#215)
Align the merged generator tests with the pinned documents and the
complete unsupported list, add tests for the rules added after review,
run them in the existing CI step next to the coverage tests, and give
the coverage script the same explicit Python 3.11 error as the
generator instead of a traceback.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:40:52 -06:00
elforeign b541dce0cc Merge branch 'feat/semantic-registry-s4' into feat/semantic-registry 2026-11-24 03:40:09 -06:00
elforeign 52ecece126 docs, tests: semantic registry contributor guide and generator unit tests (#215)
Contributors had no written path for adding a form through the registry,
and the generator's rejection rules had no direct tests: a disabled check
would only show up if the real registry happened to break it.

The new unit tests feed small in-memory registries and a hand-written
snapshot that each break one rule, check that the real registry passes,
that render is deterministic and independent of key order, and that the
CLI's validate, generate and --check modes exit as documented. Each of
44 deliberate generator mutations makes at least one test fail.

The guide covers the files, every field and its allowed values, what the
validator checks, what the generator does not do, the commands, and a
worked example on s_addc_u32.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:39:17 -06:00
elforeign 440856a997 semantics: pin cited documents and reject a boolean schema; reject duplicate generated rows in coverage (#215)
Follow-up to the independent review: a citation can no longer point at
another file, schema = true no longer passes as 1, the coverage reader
fails on a duplicated FORM_IDS row, and 'not yet' lowering is not
counted.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:38:49 -06:00
elforeign 1eeb614ea2 Merge remote-tracking branch 'origin/main' into feat/semantic-registry 2026-11-24 03:36:34 -06:00
elforeign afd936b20b semantics: close validation gaps found in review; check generated files in CI (#215)
The generator now rejects float widths, reserved variant names,
out-of-range pages and opcodes, Wave32 restrictions the decoder cannot
enforce yet, operand rules whose unsupported list differs from what the
decoder rejects, and undeclared or empty guide documents. The coverage
report reads decoder support from the compiled FORM_IDS table instead of
the registry, needs a decoding row before counting reference or Metal
evidence, and fails on unimplemented lowering. CI runs both --check
modes and the coverage unit tests so a stale generated file fails.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:36:18 -06:00
Ranveer Soni 6772205213 Merge pull request #251 from Swastickc/task/83-jit-capacity
loader: check JIT page size and capacity arithmetic (#83)
2026-11-24 15:04:40 +05:30
Ranveer Soni 4b5e2b690d Merge pull request #250 from Swastickc/task/79-pe-validation
loader: validate PE headers, section ranges and entry point (#79)
2026-11-24 15:04:31 +05:30
Ranveer Soni ee6c9ac067 fix(docs): synchronize generated status tables
Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 15:03:22 +05:30
elforeign 1680e6b19c docs: describe the semantic registry and link the coverage report (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:32:41 -06:00
elforeign 3eef0ecfa8 Merge remote-tracking branch 'origin/main' into feat/semantic-registry 2026-11-24 03:32:10 -06:00
Swastick Chowdhury 999de9f2df loader: validate PE headers, section ranges and entry point (#79)
Fix two parser panics found by the pe_parse fuzz target: a truncated
PE32+ optional header and unchecked RVA range arithmetic. Also require
the 112-byte fixed optional header, check section table and raw data
bounds, reject overlapping sections and require the entry point to lie in
an executable section. Adds pe_validation regression tests built from
original synthetic images.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:02:00 +05:30
elforeign e616583c3f audit: add the semantic coverage report (#215 stage F slice)
Counts identified, encoding-validated, declared, decoder, IR/MSL,
reference and Metal evidence per encoding family, reading evidence only
from docs/status.toml so registry requirements never count as results.
Unrecognized inputs fail instead of being skipped. --check never writes.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:31:57 -06:00
Swastick Chowdhury 025f9dfd21 loader: check JIT page size and capacity arithmetic (#83)
Reject a failed, zero or non-power-of-two page size, and use checked
arithmetic for page rounding, emitted instruction length and code-cache
capacity. Adds unit tests for each overflow and boundary case.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:01:50 +05:30
Ranveer Soni d8c02270ee stuff 2026-11-24 15:01:17 +05:30
Ranveer Soni 08c4451e68 docs: add draw, blend and depth contract sections to the interface contracts 2026-11-24 15:01:17 +05:30
Ranveer Soni 2ab189ddbe docs: refresh the engineering progress page for the current state 2026-11-24 15:01:17 +05:30
Ranveer Soni fa94b56ba3 docs: refresh the documentation index for the current state 2026-11-24 15:01:17 +05:30
Ranveer Soni 385e7a0729 readme: refresh the closing statement with the current research focus 2026-11-24 15:01:17 +05:30
Ranveer Soni 819699e8a7 readme: refresh the build, test and verification sections 2026-11-24 15:01:17 +05:30
Ranveer Soni 4404e3f4bb readme: refresh texture support and current limitations for the current state 2026-11-24 15:01:17 +05:30
Ranveer Soni d35cea8eff readme: refresh the architecture section for the current graphics passes 2026-11-24 15:01:17 +05:30
Ranveer Soni 8a69f80aa0 readme: add blend pass, indexed draws and depth pass as verified graphics work 2026-11-24 15:01:17 +05:30
Ranveer Soni c21d9ba92a readme: update milestone table statuses for the current state 2026-11-24 15:01:17 +05:30
Ranveer Soni e06242f2e0 readme: refresh the header and project summary for the current state 2026-11-24 15:01:17 +05:30
elforeign c9e3394eb3 isa, decoder: generate SOP2 dispatch from the semantic registry (#215 stage A+B)
generate_semantics.py validates the registry against its closed
vocabulary and the pinned XML snapshot (opcode, family, SCC input and
output, operand widths and signed formats) and emits static Rust tables.
The decoder now selects SOP2 operations through the generated from_word
match, and ScalarAluOp's mnemonic, SCC read and evaluation come from the
registry through shared primitives instead of hand-written per-opcode
code. The nine SOP2 opcode entries leave generate_rdna2.py.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:27:07 -06:00
Ranveer Soni 72d2ceb967 Merge pull request #249 from elforeign/task/156-cpu-decode-fuzz
fuzz: bounded CPU decoder fuzz target
2026-11-24 14:56:13 +05:30
elforeign 358ddc5eba isa: pin the semantic registry schema and Rust vocabulary (#215 stage A)
Freeze the registry format and typed vocabulary first so the parallel
slices (verification harness, coverage report, docs) can build against
them. The nine SOP2 forms are declared as data; the generator, validation
and decoder wiring follow.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:22:05 -06:00
elforeign 09cf27186c fuzz: add bounded cpu_decode target for the static probe decoder
Issue #156 asks for a bounded, non-executing fuzz target for the CPU
decoder. No public single-instruction decode API exists, so the target
wraps up to 4096 fuzz bytes as the code section of a fixed, original
PE32+ header and runs the public read-only probe_pe_bytes twice with a
bounded ProbeConfig. It asserts identical reports, the 15-byte x86
instruction limit, and that each record lies in and matches the input.
A startup self-check (nop; ret must decode to two records) stops a run
whose synthetic header no longer reaches the decoder.

A 600 s campaign found one decoder defect (unlimited segment prefixes
give instructions over 15 bytes), reported on #74 and not fixed here.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:19:21 -06:00
Ranveer Soni 9ac1343e34 Merge pull request #248 from elforeign/task/193-blending
gpu: native blend pass with per-draw blend state and write masks (#193)
2026-11-24 14:41:20 +05:30
elforeign 078afd4591 ref: bound the blend reference extent and parse rounding flags strictly (#193)
The second independent review found that an extent such as [usize::MAX, 1]
passed the overflow check and then panicked in the allocation, and that any
flag character other than 'e' silently granted the native tolerance. The
reference now accepts 1..=4096 pixels, the native limit, and the parser
rejects unknown flags.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:09:23 -06:00
elforeign 4741409de1 Merge remote-tracking branch 'origin/main' into task/193-blending
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
#	crates/metal/src/compute.rs
#	crates/metal/src/lib.rs
#	crates/metal/src/render.rs
#	crates/ref/src/lib.rs
2026-11-24 03:06:27 -06:00
elforeign 6cbe976990 gpu: address independent review of the blend pass (#193)
The review found that the CPU blend reference multiplied an unchecked extent
before allocating, that only the second draw of each case varied its state,
and that the docs did not say Min/Max ignore the factors.

- The reference rejects empty or overflowing extents, with a unit test.
- New clean-room case first_draw_blended: a blended, masked first draw
  under a differently configured second draw (re-derived in a fresh
  session that reproduced the first 38 cases exactly).
- Doc and changelog wording now state the coverage scope precisely.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:06:03 -06:00
Ranveer Soni 857bec29e1 Merge pull request #247 from elforeign/task/192-indexed-draws
gpu: indexed draws with base vertex, native Metal and loader (#192)
2026-11-24 14:32:46 +05:30
elforeign 7b6c6fd92c Merge remote-tracking branch 'origin/main' into task/193-blending
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 03:01:19 -06:00
elforeign 28846561ab gpu: native blend pass with per-draw blend state and write mask (#193)
Blending and colour write masks had no native path or check. Add
NativeCompute::render_blend: flat triangles drawn in order into an RGBA8
target, each with its own write mask and either blending disabled or
separate RGB and alpha factors and operations (one pipeline per draw,
since both are pipeline state in Metal).

xenora-ref gains an exact blend reference that also reports which
channels need rounding. Expected images were derived independently in a
clean room from the public Metal blend equations. The tolerance was fixed
before measuring: exact channels must match, rounded channels may differ
by 1.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:01:09 -06:00
elforeign 817a95b419 loader: test a vertex-buffer offset and zero-count backend calls; split recording and execution errors in the changelog (#192)
The second independent review asked for coverage of a nonzero vertex-buffer
offset and proof that zero-count draws never reach the backend, and for the
changelog to say which errors recording raises and which execution raises.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:58:29 -06:00
elforeign 33c025a785 Merge remote-tracking branch 'origin/main' into task/192-indexed-draws
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 02:55:08 -06:00
elforeign c0cbc2f787 gpu: tighten the indexed-draw contract after independent review (#192)
The review found that a raw primitive-restart index could pass the native
range check with a negative base vertex, that the loader ignored instance
parameters and could wrap a guest address, and that coverage missed flat
multi-triangle draws, an unadjusted textured draw and 32-bit indices above
16 bits.

- Native and CPU reference reject the raw restart value whatever the base.
- The loader rejects index counts other than 0 or 3 first, more than one
  instance and a nonzero start instance, and checks guest address
  arithmetic through the last byte read.
- Three clean-room cases added (re-derived in a fresh session, which also
  reproduced the first 13); native error checks now name each reason, and
  the loader error test proves no rejected draw reaches the backend.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:54:55 -06:00
Ranveer Soni e8b0a380e9 Merge pull request #246 from elforeign/task/157-pe-parse-fuzz
fuzz: bounded PE parser fuzz target
2026-11-24 14:24:24 +05:30
elforeign df3b9674a3 Merge remote-tracking branch 'origin/main' into task/157-pe-parse-fuzz
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 02:51:15 -06:00
elforeign db50deb9f7 fuzz: add bounded PE parser fuzz target
Add a pe_parse cargo-fuzz target that feeds malformed bytes to
ParsedPe::parse and rva_to_file_offset and, only when the summed
section mapping size and SizeOfImage are at most 64 MiB, to the checked
load_into_memory mapping step. No guest code is executed.

Refs #157

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:51:05 -06:00
elforeign 76679a9c05 changelog: keep the Added list without blank lines
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:47:59 -06:00
elforeign 6785cb04e3 Merge remote-tracking branch 'origin/main' into task/192-indexed-draws
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 02:47:49 -06:00
elforeign 99c8331576 gpu: indexed draws with base vertex, native Metal and loader (#192)
Indexed draws had no contract: the loader had no index buffer command and
the Metal backend only drew non-indexed triangles. Add a bounded one:

- NativeCompute::render_indexed issues real drawIndexedPrimitives calls on
  a 16- or 32-bit index buffer with a start index and signed base vertex,
  optionally sampling a natively uploaded BC1 texture.
- The loader gains SetIndexBuffer (DXGI R16_UINT/R32_UINT only) and
  DrawIndexedInstanced, which fetches one triangle through the index
  buffer and base vertex and feeds the existing one-triangle backend.
- Both reject bad formats, offsets and counts, indices past the buffer and
  any index + base vertex outside the vertex buffer before drawing.
- xenora-ref gains an index-fetch reference over the depth rasteriser.

Expected images and fetch lists were derived independently (clean room)
from public D3D12, Metal and BC1 documentation.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:46:58 -06:00
Ranveer Soni 077a215d49 Merge pull request #243 from elforeign/task/138-threadgroup-sizing
metal: measure threadgroup sizing; keep the 64-thread default (#138)
2026-11-24 14:08:26 +05:30
Ranveer Soni 3c710b53ba Merge pull request #242 from atesahmet0/task/200-indirect-control
Verify indirect CALL and JMP target fetch, stack and retirement
2026-11-24 14:06:31 +05:30
Ranveer Soni 4886e9cd80 Merge pull request #241 from atesahmet0/task/86-precise-faults
Preserve precise guest fault state and retired instructions
2026-11-24 14:06:25 +05:30
elforeign 4dc10ae437 metal: check the requested group width directly; report all bench runs
The independent review noted that a 65-thread grid at width 1024 would also
pass if the width were clamped to the grid, so threads now also report
dispatch_threads_per_threadgroup. The changelog now gives all three benchmark
runs, including the slower first one.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:34:06 -06:00
elforeign 16debc8fdb Merge remote-tracking branch 'origin/main' into task/138-threadgroup-sizing
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 02:31:44 -06:00
elforeign ee8347a39f metal: explicit threadgroup widths, measured against the default (#138)
Expose a bounded way to dispatch at a chosen width so every legal
configuration can be checked for identical known answers, including grids
that do not divide evenly, and timed against the default policy. On an
Apple M5 Pro widths 64-256 tie (median 58.8 us GPU), 512 is 6% slower and
1024 about 2x, so the default of 64 stays. run() keeps its signature; the
sized path is a separate private helper.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:31:33 -06:00
Ranveer Soni 6689761db3 Merge pull request #240 from elforeign/task/191-depth-attachment
metal: depth attachment known-answer rendering (#191)
2026-11-24 14:00:29 +05:30
ates 7aa8166cf2 Verify indirect CALL and JMP target fetch, stack and retirement
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 11:30:08 +03:00
ates c107f3a43f Preserve precise guest fault state and retired instructions
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 11:30:08 +03:00
elforeign b041952437 Merge remote-tracking branch 'origin/main' into task/191-depth-attachment
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 02:29:02 -06:00
Ranveer Soni ae80d7fd8f Merge pull request #238 from elforeign/fix/vop3-interp-length
isa: VOP3 interpolation attribute fields never select a literal
2026-11-24 13:58:26 +05:30
Ranveer Soni d57e9c031c Merge pull request #239 from elforeign/feat/vopc-compare
shader: Wave32 VOPC integer compares with VCC/EXEC rules
2026-11-24 13:58:02 +05:30
elforeign 924d68afbc metal: take the BC1 upload type in depth passes, gate BC per case
An independent review found that DepthPass accepted a Bc1Subresource, whose
public fields let a caller pair a short slice with a larger pitch before
replaceRegion. Take the validated Bc1Upload instead. Supply the texture only
to the textured case so a device without BC support fails that case alone.
The CPU reference now rejects depth outside 0..=1 since it does not clip,
and checks the texture size with checked arithmetic.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:27:43 -06:00
elforeign 840eca0a29 metal: depth attachment known-answer rendering (#191)
Draw ordered triangles with an optional Depth32Float attachment, per-draw
compare function and write enable, and read back colour and stored depth,
so depth compare, clear, write enable and disabled depth can each be
checked against independently derived values. One draw samples an original
BC1 texture through the native BC1 path, so the BC upload is exercised by
rendering, not only by compute readback.

Also adds the missing changelog lines for PR #224 (BC7) and PR #231 (#172).

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:23:31 -06:00
elforeign 0749330868 shader: Wave32 VOPC integer compares with VCC/EXEC rules
Adds v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32 across the chain: opcodes
generated from the pinned AMD XML, one typed VectorCompare instruction
(relation + signedness, table-driven decode), the reference interpreter,
the independent semantic-review interpreter, typed IR and MSL.

Rules (RDNA 2 ISA guide 3.9, 2.1, 3.3; contract in
docs/shaders/vector-compare.md): VCC_LO[n] = EXEC_LO[n] & test(lane n),
always fully written, so empty EXEC gives 0 and reads no source; VCC_HI
becomes unknown; EXEC, SCC and VGPRs are unchanged. A lane-derived
VCC_LO may feed only s_cbranch_vccz, v_mov_b32 vN, vcc_lo and another
compare's SRC0, so EXEC never becomes data-dependent. A runtime
s_cbranch_vccz is wave-uniform: the skipped code may hold only integer
vector ALU instructions with initialized destinations, checked whether
or not it is taken, and lowers to selects at the join.

The Metal kernel makes no SIMD-group, threadgroup or barrier assumption:
each thread rebuilds its RDNA wave's mask by recomputing the 32 lanes'
operands from their input words, bounded by threads_per_grid. The
reference now runs lockstep Wave32 waves; absent lanes of a final
partial wave contribute 0.

Verified with an original LLVM-assembled fixture and 251 programs
(every form on 10 boundary values in both operand orders, partial and
empty EXEC, both runtime branch edges in one dispatch, mask chains,
32 pinned rejections) against exact integer definitions. Translator,
reference and second interpreter agree on CPU; all 252 programs match
on native Metal with validation; LLVM agrees on every encoding.
Breaking any implementation (signedness, EXEC masking, empty EXEC,
absent-lane bound, join polarity or uniformity) fails the tests.

Fixes #186

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:22:19 -06:00
elforeign 2ddd2a2485 isa: VOP3 interpolation attribute fields never select a literal
identify() treated SRC0 = 255 as the literal selector in every VOP3 form
with the LITERAL extension, so six interpolation forms (v_interp_p1_f32,
v_interp_p2_f32, v_interp_mov_f32 in VOP3, v_interp_p1ll_f16,
v_interp_p1lv_f16, v_interp_p2_f16) were read as 12 bytes. In these
forms SRC0 is not an operand selector: the RDNA 2 ISA guide, section
10.4.2, says SRC0 "is treated as a set of bit-fields" {attr_word,
attr_chan, attr}, and the XML gives its operand type as OPR_ATTR. LLVM
23.1.6 decodes all six as 8 bytes.

Fields typed OPR_ATTR are now skipped when looking for a literal. VGPR-
only sources are unchanged: LLVM still reads v_permlane16_b32 and
v_movrels_b32 with selector 255 as 12 bytes (invalid operand), and the
new test pins that too. The corpus check's six pinned mismatch rows
are gone: v_interp_mov_f32 now agrees fully and the other five are
operand_flagged (same form and length, LLVM flags the operand).

The new test fails on the old rule.

Fixes #235

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:20:01 -06:00
Ranveer Soni 0e7fa4aa93 Merge pull request #234 from elforeign/task/209-llvm-corpus
test(isa): independent LLVM corpus check of gfx1030 identification (#209)
2026-11-24 13:38:57 +05:30
Ranveer Soni 1ee557bdc4 Merge pull request #233 from atesahmet0/task/197-bswap
Implement 32-bit and 64-bit BSWAP in both CPU engines
2026-11-24 13:38:32 +05:30
elforeign fa4d4b9d71 Merge remote-tracking branch 'origin/main' into task/209-llvm-corpus 2026-11-24 02:06:03 -06:00
elforeign bf3cca0718 isa: independent LLVM corpus check of gfx1030 identification (#209)
Issue #209 asks for LLVM-generated original samples beyond the existing
oracle cases, with measured coverage and unresolved differences. The
corpus has 317 original instructions assembled by llvm-mc and 6,574 byte
probes built from every metadata form's identifying bits: one with zero
operands, one per extension selector its family can carry, and two with
random operand bits. llvm-objdump decodes each probe, giving LLVM's
instruction and the bytes its decoder consumed (llvm-mc --disassemble
re-encodes, which hides consumed length for MIMG NSA).

The test compares identify with every row and pins per-source class
counts, the 130 disagreeing rows and a digest of the random probes, so
any metadata change fails until reviewed. Disagreements are reported, not
fixed: 18 MIMG names LLVM does not know, 6 VOP3 interpolation forms whose
attribute field 255 is read as a literal, and 21 extension cases on
operand-less or SGPR-pair instructions.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:05:58 -06:00
Ranveer Soni a86100c00d Merge pull request #231 from elforeign/task/172-extension-word-negative
test(isa): gfx1030 extension-word negative tests (#172)
2026-11-24 13:33:40 +05:30
ates 044f036ea5 Implement 32-bit and 64-bit BSWAP in both CPU engines
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 10:57:26 +03:00
elforeign 79947ec998 Merge remote-tracking branch 'origin/main' into task/172-extension-word-negative 2026-11-24 01:55:01 -06:00
Ranveer Soni 17fe880bdc Merge pull request #230 from elforeign/feat/sop2-signed-add-sub
shader: add s_add_i32 and s_sub_i32 with signed-overflow SCC (follow-up to #185)
2026-11-24 13:24:39 +05:30
elforeign e93e4e1e2a isa: negative tests for gfx1030 extension words (#172)
Issue #172 asks for independent truncated and invalid literal, SDWA, DPP
and NSA cases, and for length recognition to be kept apart from semantic
validity. Every case starts from bytes llvm-mc assembled from an original
instruction; expected results come from LLVM's disassembly of the cut or
altered bytes, not from the decoder.

Covers 62 proper prefixes of 18 literal/SDWA/DPP/NSA instructions with the
exact length each needs, 7 extension selectors on forms that do not allow
them, two reserved control values that keep their trailer length, and 8
back-to-back pairs whose second instruction starts after the trailer. An
ignored test re-checks every source encoding with LLVM.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:54:22 -06:00
elforeign 425327a0f2 shader: add s_add_i32 and s_sub_i32 with signed-overflow SCC
#185 left both forms unsupported because the pinned XML says only
"carry-out" for them. The AMD RDNA 2 ISA reference guide (GPUOpen,
section 12.1 SOP2 Instructions, p. 101-102, and section 5.3 Scalar
Condition Code, p. 33) defines SCC for both as signed overflow:
add overflows when the operands share a sign that the result lacks;
subtract when the operands' signs differ and the result's sign differs
from S0's. The guide also confirms the unsigned rules used in #185.

Adds both forms to the generated opcodes, the decoder, the reference
(exact signed result must fit in i32), the independent interpreter (the
guide's sign-bit rule over its ripple adder) and the translator, plus
400 boundary programs, eight hand-worked overflow and no-overflow cases
(-1 + 1 and 0 - 1 carry or borrow but do not overflow) and two signed
overflows in the scalar ALU fixture. Inverting the overflow rule in any
one implementation fails three tests. s_min_i32 and the other SOP2
forms stay unsupported.

Refs #185

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:48:52 -06:00
Ranveer Soni 1212280ab8 Merge pull request #224 from elforeign/task/171-bc7-decoder
feat(texture): BC7 block decoder, all eight modes, with independent vectors (#171)
2026-11-24 13:13:55 +05:30
Ranveer Soni c6665ebfb4 Merge pull request #229 from elforeign/feat/sop2-scalar-alu
shader: SOP2 scalar add, subtract and bitwise forms with SCC (fixes #185)
2026-11-24 13:13:32 +05:30
elforeign 96e2baeb75 Merge remote-tracking branch 'origin/main' into feat/sop2-scalar-alu
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 01:40:26 -06:00
Ranveer Soni b9be341dfc Merge pull request #227 from elforeign/feat/test-inventory
audit: compare Cargo test inventories between two commits
2026-11-24 13:09:55 +05:30
elforeign b2391b4de4 Merge remote-tracking branch 'origin/main' into feat/sop2-scalar-alu
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:39:50 -06:00
Ranveer Soni ecc109a7e2 Merge pull request #225 from elforeign/ci/pr-template-check
ci: require pull requests to follow the PR template
2026-11-24 13:09:07 +05:30
Ranveer Soni 67e6565fc2 Merge branch 'main' into ci/pr-template-check 2026-11-24 13:08:58 +05:30
elforeign 994efd38f9 shader: decode and execute SOP2 scalar add, subtract and bitwise forms
Adds s_add_u32, s_sub_u32, s_addc_u32, s_subb_u32, s_and_b32, s_or_b32
and s_xor_b32 across the chain: generated opcodes from the pinned AMD
XML, a typed ScalarAlu instruction, decoding, the reference interpreter,
the independent semantic-review interpreter and the translator, which
resolves scalar state and SCC as it already does for s_mov/s_cmp.
v_mov_b32_e32 may now read a normal SGPR, so results reach vector code
as constants.

SCC: the XML states carry-out for additions, carry-in for ADDC/SUBB and
nonzero results for bitwise forms. For subtraction it says carry-out
without fixing the polarity; LLVM's lowering of usubo and of 64-bit
subtraction to s_sub_u32/s_subb_u32 requires SCC to be the borrow.
s_add_i32/s_sub_i32 stay unsupported: no pinned source settles whether
their SCC is the carry or signed overflow.

Verified with an original LLVM-assembled fixture and 1,400 boundary
programs (every form, 10x10 operands, SCC clear and set) against exact
integer definitions; translator, reference (exact integers) and
independent interpreter (bit-serial ripple adder) all agree, and all
1,401 programs match on native Metal with validation. LLVM agrees on
every encoding. Breaking any one implementation fails the tests.

Fixes #185
Independent review fixes: both interpreters now require a known SGPR
for v_mov_b32 from an SGPR even in an inactive lane, as translation
does; alias, literal and inline cases also assert the translated result
and run on Metal; rejections are pinned to the SOP2 word's offset; GPU
status is recorded as local evidence with acceptance pending.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:38:54 -06:00
Ranveer Soni aac0f31b93 Merge pull request #226 from elforeign/docs/readme-contributors
docs: add contributors section to README
2026-11-24 13:08:35 +05:30
elforeign ef0e472d5d docs: add contributors section to README
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:37:56 -06:00
elforeign 1784836639 audit: compare Cargo test inventories between two commits
Testing the old #166 and #165 heads silently ran without 12 BC texture
tests that main already had, because those heads predated the merge
that added them; nothing flagged the smaller inventory.

scripts/audit/test_inventory.py lists every test (and the ignored set)
of a base and a candidate commit, each in a temporary detached worktree
it always removes, and reports removed, added, newly ignored and newly
un-ignored tests keyed by package, target and name. Unexplained losses
exit 1; an --allow file with a reason per key explains intended ones.

951189c -> 5450612: removed 12 (all xenora-texture bc_formats), exit 1.
0cac6c4 -> 0cac6c4: 219 tests each side, no change, exit 0.

Fixes #208

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:37:54 -06:00
Ranveer Soni 68fc4e25dc Merge branch 'main' into task/171-bc7-decoder 2026-11-24 13:07:25 +05:30
Ranveer Soni cdaff0a391 Merge pull request #223 from elforeign/task/169-metal-bc4-bc5
feat(metal): native BC4 and BC5 UNORM/SNORM upload and readback (#169)
2026-11-24 13:06:51 +05:30
Ranveer Soni 184149561a Merge pull request #222 from elforeign/docs/plain-reply-claims
docs: claim by plain reply, one-week stale rule
2026-11-24 13:06:34 +05:30
Ranveer Soni e83475be17 Merge pull request #216 from elforeign/feat/gpu-compatibility-expansion
isa: fix isolated-branch inspection and verified form count (follow-up to #166)
2026-11-24 13:06:13 +05:30
elforeign fa55066699 ci: fail pull requests whose description skips the PR template
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:35:54 -06:00
elforeign f25060e891 changelog: restore the gfx1030 metadata and shader inspection entries
The upstream merge of main into this branch (01deb3f) resolved the
CHANGELOG conflict by dropping this PR's three entries;
documented_form_counts_match_the_generated_table caught it.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:35:27 -06:00
elforeign 9318e68840 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:34:37 -06:00
elforeign abd6698a66 Merge remote-tracking branch 'origin/main' into task/171-bc7-decoder 2026-11-24 01:32:50 -06:00
elforeign 5f8867bd30 Merge remote-tracking branch 'origin/main' into task/169-metal-bc4-bc5 2026-11-24 01:32:50 -06:00
Ranveer Soni 5ca90bfac0 Merge pull request #221 from atesahmet0/task/177-probe-report-consistency
Test probe report consistency across JSON, Markdown, and CSV
2026-11-24 12:59:38 +05:30
elforeign 7cc35ffd41 Merge remote-tracking branch 'origin/main' into task/169-metal-bc4-bc5
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 01:28:23 -06:00
elforeign 57f10c1d7c Merge remote-tracking branch 'origin/main' into task/171-bc7-decoder
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
#	crates/texture/src/lib.rs
2026-11-24 01:26:50 -06:00
elforeign 76620e274b texture: iterate texels directly in the BC7 tests
Strict Clippy (needless_range_loop) rejects indexing the output by the
loop counter; the assertions are unchanged.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:26:34 -06:00
elforeign 240302fabe texture: add a BC7 block decoder from the Khronos BPTC text (#171)
Issue #171 asks for bounded BC7 decoding with independent vectors for
partitions, endpoint precision and indices. All eight modes are decoded:
the partition and anchor tables are extracted mechanically from Khronos
Data Format Specification 1.3 section 20.1, and blocks with a zero low
byte decode to zero as that section requires.

Hand-derived tests cover each mode's distinctive field (P-bits, shared
P-bits, anchors, rotation, index selection, the section's own mode 2
bit-position example), and 430 known-answer vectors come from a separate
clean-room reference decoder. CPU only; no Metal BC7 path is claimed.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:25:45 -06:00
Ranveer Soni 01deb3f8a8 Merge branch 'main' into feat/gpu-compatibility-expansion 2026-11-24 12:55:06 +05:30
Ranveer Soni e6b9a27242 Merge pull request #218 from elforeign/task/168-bc23-audit
test(metal): BC2/BC3 edge blocks, invalid payloads and capability reporting (follow-up to #214)
2026-11-24 12:54:35 +05:30
elforeign 8fdb569052 docs: claim by plain reply, one-week stale rule
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:23:57 -06:00
Ranveer Soni e79bd1ccaf Merge pull request #220 from elforeign/task/170-bc6h-subset
feat(texture): bounded BC6H subset decoder (single-subset modes) (#170)
2026-11-24 12:51:55 +05:30
Ranveer Soni 066bc3fc83 Merge pull request #217 from elforeign/feat/agent-task-queue
agent queue: command-only triggers, durable claim replay and review fixes (follow-up to #165)
2026-11-24 12:47:00 +05:30
ates a533d8107e Test cross-format probe reports against fixture counts and offsets
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 10:16:45 +03:00
elforeign 3109b620fd texture: decode the single-subset BC6H modes
#170 asks for a documented, bounded BC6H subset with explicit rejection
of what is not implemented. This adds a CPU decoder for the four
single-subset modes (Khronos 3, 7, 11 and 15; Microsoft 11 to 14) in
signed and unsigned form, written from the Khronos Data Format 1.3 text
(Tables 121 and 122, unquantization and final unquantization). Reserved
modes decode to zero as the specification requires; the ten two-subset
modes return Bc6hError::UnsupportedMode, and BC6H_SUPPORTED_MODES lists
coverage by mode.

Tests use hand-derived values (saturation to 65504 and -65504, the
11-bit transform wrap, both reversed-bit fields, signed -32768 to
negative infinity) and 128 known-answer vectors from a separate
clean-room reference decoder, 16 per supported and reserved mode.
Flipping the reversed bit order, dropping the wrap mask, using 31/64
for signed data, a 4-bit anchor, accepting mode 0 or not zeroing
reserved modes each fails the tests.

Refs #170

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:16:24 -06:00
elforeign 878f554dcd Merge task/168-bc23-audit into task/169-metal-bc4-bc5
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
#	crates/metal/tests/native/texture_bc_alpha.rs
2026-11-24 01:12:31 -06:00
elforeign 46e2d36064 metal: compare non-interpolated BC4/BC5 codes exactly
The full-texel check applied the two-code tolerance to every channel, so
an endpoint or six-value fixed code outside the anchors could be off by
two and still pass. Each texel's tolerance now comes from its own index:
zero for stored and fixed codes and constant channels, two only for
interpolated codes. A readback kernel that lowers near-maximum red by two
now fails the BC4 and BC5 UNORM tests.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:12:20 -06:00
elforeign d94121bbb0 metal: compare non-interpolated BC2/BC3 codes exactly
An independent review of the #214 tests found that the full-texel check
applied the two-code interpolation tolerance to every channel, so an
endpoint, a BC2 alpha nibble or BC3's fixed 0 or 255 outside the anchors
could be off by two and still pass. The tolerance now comes from each
texel's own indices: zero for stored and fixed codes, two only for
interpolated ones. A readback kernel that lowers near-opaque alpha by two
now fails all three tests. The 1.14-code bound is stated as 8/7.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:11:43 -06:00
elforeign ef4fbba797 Merge upstream main into task/169-metal-bc4-bc5
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:08:59 -06:00
elforeign 97ea2541bb metal: cover BC2/BC3 edge blocks and report missing BC support apart
The section 12 audit of #214 found three gaps: no level narrower than a
block row (Metal's zero-stride single-row upload) or of 1x1, no checks
for zero extents or oversized and block-count-mismatched payloads, and a
missing BC capability surfaced the same way as an implementation fault.

Adds a 5x3 and 1x1 GPU test with hand-derived anchors, the extra upload
rejections, and MetalError::is_capability_unavailable; the GPU tests now
print CAPABILITY UNAVAILABLE or IMPLEMENTATION FAILURE. Rounding the
texture to whole blocks, accepting oversized payloads, or a device
without BC support each makes the tests fail with the matching message.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:08:34 -06:00
elforeign f1ec653b91 Merge remote-tracking branch 'origin/main' into feat/agent-task-queue
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:06:04 -06:00
elforeign b1ab08c09d agent queue: apply claim checks when /reassign creates a claim
/reassign turned a ready task into a claim without the dependency and
file-overlap checks /claim applies, so a maintainer reassignment could
grant two overlapping claims. Run the same checks for the new holder.

Refs #211

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:05:47 -06:00
elforeign 6b479a6617 agent queue: fix review findings in replies, verification and issue forms
From independent review of the queue follow-up:
- Bot replies echoed user text (/blocked reasons, /reassign logins,
  file patterns) verbatim. Markers count when the bot posts them, so a
  reason containing an approval or done marker became a bot marker and
  could approve an acceptance command or hide another user's claim.
  Echoed text now has angle brackets and backticks escaped.
- /verified accepted a 7-character prefix and ignored extra arguments;
  a commit with the same short prefix is cheap to make. Require exactly
  one full 40-character SHA, with one parser shared by decide and the
  check.
- After a verification, the job looked up the check run by the pull
  request head SHA, but pull_request_target runs carry the base branch
  SHA, so it found nothing and || true hid it. The verify job now
  evaluates the same advisory check itself and no longer needs
  actions: write.
- The issue form renders Files inside a ```text fence and the parser
  took "text" as a path, so any two form-created tasks overlapped.
  Fence lines are skipped.
- A command still unanswered after lease_hours now gets a "Not decided"
  reply (window 2 x lease_hours) instead of being dropped silently.

Each fix has a test shown to fail with the fix reverted.

Refs #210, #211

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:05:28 -06:00
elforeign 7a10d7eac8 metal: cover BC4/BC5 edge blocks and invalid payloads
Section 12's audit asks for levels that are not whole blocks and for
rejected payloads. Adds a 5x3 (single block row, zero Metal stride) and
1x1 GPU test over BC4/BC5 UNORM and SNORM with hand-derived anchors, the
zero-extent and wrong-length upload rejections, and routes the GPU reads
through the shared capability-aware unwrap. Rounding the texture to whole
blocks, accepting oversized payloads, or a device without BC support each
makes the tests fail with the matching message.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:03:48 -06:00
elforeign 0e51ddda76 Merge test/metal-bc2-bc3 into the BC4/BC5 branch
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 01:02:47 -06:00
elforeign b5a462fb54 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:02:17 -06:00
elforeign 09e0bea55d shaders, isa: tighten inspection wording and review-found test gaps
From independent review:
- The summary said "not executable" for instructions that merely have
  no semantic decoding; a decoded program can still fail compilation.
  Say "without semantic decoding".
- When identification stops early, a branch target past the identified
  prefix was reported invalid although its boundaries are unknown;
  report it as unverified.
- The VOP3 and VOP3P literal probes used 1.0, which LLVM encodes as an
  inline constant (8 bytes), so neither exercised a literal. Use
  0x3f800001 and 0x3c01 and assert the 12-byte encoding and trailer.
- The coverage JSON test now also checks the document's shape.

Refs #183, #184

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:01:38 -06:00
elforeign 1260e07ba1 metal: cover BC2/BC3 edge blocks and report missing BC support apart
The section 12 audit of #214 found three gaps: no level narrower than a
block row (Metal's zero-stride single-row upload) or of 1x1, no checks
for zero extents or oversized and block-count-mismatched payloads, and a
missing BC capability surfaced the same way as an implementation fault.

Adds a 5x3 and 1x1 GPU test with hand-derived anchors, the extra upload
rejections, and MetalError::is_capability_unavailable; the GPU tests now
print CAPABILITY UNAVAILABLE or IMPLEMENTATION FAILURE. Rounding the
texture to whole blocks, accepting oversized payloads, or a device
without BC support each makes the tests fail with the matching message.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:01:26 -06:00
elforeign e70780f30a Merge remote-tracking branch 'origin/main' into feat/agent-task-queue
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 01:00:40 -06:00
elforeign ef481368d6 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 01:00:40 -06:00
Ranveer Soni 0cac6c4fcf Merge pull request #214 from elforeign/test/metal-bc2-bc3
test(metal): BC2/BC3 upload and sampling conformance (#168)
2026-11-24 12:30:21 +05:30
elforeign 3a598a83e1 shaders: assert add.bin inspects as 7 semantic instructions
Refs #183

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:59:45 -06:00
Ranveer Soni b69d4b97c6 Merge pull request #166 from elforeign/feat/gpu-compatibility-expansion
isa: complete gfx1030 instruction metadata and identification
2026-11-24 12:26:27 +05:30
Ranveer Soni 97598903e2 Merge branch 'main' into feat/gpu-compatibility-expansion 2026-11-24 12:26:13 +05:30
elforeign 9fda5aab18 agent queue: re-run the check only after an accepted verification
The verify job re-ran the pull request check after any /verified
comment, including refused ones: the author's own, a non-verifier's, a
stale or unknown head or a malformed SHA. decide now marks only an
accepted verification of the current head, and the job re-runs the check
only when should-rerun confirms it. A test checks that what re-runs the
check is exactly what the check counts.

Replay decides a comment listed twice only once. Tests cover duplicate
and out-of-order listings, and every arrival order of a five-claim burst
grants exactly one of two overlapping claims.

Fixes #210, fixes #211

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:56:00 -06:00
Ranveer Soni af68f7da74 Merge pull request #165 from elforeign/feat/agent-task-queue
coordination: agent task queue for cpu, gpu, runtime, shared and qa work
2026-11-24 12:25:45 +05:30
Ranveer Soni dcf723e49d Merge branch 'main' into feat/agent-task-queue 2026-11-24 12:25:28 +05:30
elforeign 6d7523f5d1 Merge upstream main into test/metal-bc2-bc3
Resolves the CHANGELOG.md conflict with the claim-rules entry; both
entries are kept.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:55:23 -06:00
elforeign cf2d0cfb0b isa, shaders: test that coverage totals and documented counts match FORMS
At 5450612 the generated table held 1,460 forms while the docs and PR
said 1,465; 1493dcf added the five literal-only forms the LLVM oracle
found, so the table, xenora shaders coverage (text and JSON) and docs
now agree on 1,465 across 21 families. Nothing checked that they stay
in step. Test the JSON and text totals and per-family sum against
FORMS and SEMANTIC_FORMS, and the counts stated in docs/research/rdna2.md
and CHANGELOG.md against FORMS.len().

The branch inspection fix for #183 is the previous commit 9640269.

Fixes #183, fixes #184

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:54:07 -06:00
elforeign 585edd313f metal: upload and read BC4 and BC5 blocks natively
BC4 and BC5 had CPU decoders (#167) but no native Metal path, so nothing
showed that single- and dual-channel blocks reach the GPU and decode as
the specifications describe, signed formats included. This adds a pitched
BcChannelUpload (8-byte BC4 or 16-byte BC5 blocks, sharing the pitch
rules) and NativeCompute::read_bc_channel_upload, which places the blocks
in BC4_R/BC5_RG UNORM or SNORM textures behind the BC capability check.
Signed texels are read back as channel * 127 in two's-complement bytes.

The GPU tests cover six- and eight-value interpolation, equal and extreme
endpoints (stored -128 reads as -1.0, as specified), red-green order,
padded row and slice pitches, two layers and two mips: 232 texels against
the CPU decoders and hand-derived anchors. On an Apple M5 Pro interpolated
codes lie within 1.71 codes of the exact values and two codes of the
truncating CPU reference, which set the tolerances. Uploading SNORM as
UNORM, BC5 as BC4, scaling signed readback by 128 or swapping red and
green each fails the tests.

Refs #169

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:53:30 -06:00
Adeeb Rahman c4ce9a4e38 Resolve named exports from built-in guest modules
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:53:16 -05:00
Adeeb Rahman 791bfc6be9 Merge remote-tracking branch 'origin/main' into feat/system-runtime-expansion
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 01:52:41 -05:00
elforeign 69812d97c0 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 00:52:10 -06:00
Ranveer Soni e86eedf583 Merge pull request #213 from elforeign/docs/claim-before-work
docs: require claiming an issue before starting work
2026-11-24 12:20:55 +05:30
Adeeb Rahman 2de0483142 Share guest file positions across duplicated handles
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:50:28 -05:00
Adeeb Rahman 6ecbd14915 Enumerate the synthetic guest namespace through typed search handles
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:49:25 -05:00
elforeign 59ee786a12 metal: upload and read BC2 and BC3 blocks natively
BC2 and BC3 had CPU decoders (#167) but no native Metal path, so nothing
showed that the original 16-byte blocks reach the GPU and decode as the
specifications describe. This adds a pitched BcAlphaUpload with the BC1
upload's validation (shared, now measured in 16-byte blocks) and
NativeCompute::read_bc_alpha_upload, which places the blocks in BC2_RGBA
or BC3_RGBA textures behind the existing BC capability check.

The GPU tests cover explicit 4-bit alpha, six- and eight-value
interpolated alpha (equal endpoints included), descending, ascending and
equal colour endpoints, padded row and slice pitches, two layers and two
mips. Texels are compared with the CPU decoders and hand-derived anchors.
On an Apple M5 Pro interpolated values lie within 1.14 codes of the exact
values, two codes at most from the truncating CPU reference, which sets
the tolerance. Uploading BC3 as BC2, BC2 as BC1, or ignoring the row
pitch each fails the tests.

Refs #168

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:49:17 -06:00
elforeign 5df1f9146f docs: require claiming an issue before starting work
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:48:25 -06:00
Adeeb Rahman 3c9b8d988b Move closed guest files and report namespace attributes
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:47:34 -05:00
Adeeb Rahman ab598f0820 Manage directories and closed files in the guest namespace
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:46:24 -05:00
elforeign e37c8566c6 agent queue: start runs only for commands and replay cancelled claims
Every pull request comment started the verify job, which gathered state
and re-ran the pull request check, so ordinary review discussion re-ran
verification. Gate the verify job on comments that start with /verified
and the claim job on comments that start with /.

Claim runs share one concurrency group with cancel-in-progress: false.
GitHub keeps one waiting run per group and cancels it when a newer run
queues, so with the run deciding only its own comment, a /claim posted
while another claim was being decided could be dropped without a reply.
Each run now replays every command of the last lease_hours that has no
bot reply, oldest first, updating labels in memory between commands; the
hourly audit does the same, so a cancelled run's command is answered by
the run that replaced it at the latest within the hour. Replies carry a
done marker that counts only from the Actions bot.

The pull request check is advisory until a live smoke test and the
migration of existing issues: problems are a warning and the job passes.

Tests model the concurrency group (the old event-only design loses the
cancelled claim; replay answers all four commands), in-order overlap
decisions, bot-only markers and the workflow triggers.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:46:21 -06:00
Adeeb Rahman 2bc08a1851 Seek and resize files on the synthetic guest drive
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:45:02 -05:00
Adeeb Rahman 6a60749939 Provide bounded synchronous guest file IO on a synthetic drive
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:43:49 -05:00
Adeeb Rahman dcf7122082 Merge remote-tracking branch 'origin/main' into feat/system-runtime-expansion
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:43:24 -05:00
Ranveer Soni 48e42d6d4b Merge pull request #182 from atesahmet0/fix/75-static-probe-c7
Fix C7 instruction boundaries and trusted fixture probe reporting
2026-11-24 12:12:44 +05:30
Adeeb Rahman 06bdf189e4 Add counted guest semaphores to immediate waits
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:41:24 -05:00
elforeign 964026901f shaders: decode inspected instructions at their stream offset
xenora shaders inspect passed each identified instruction to decode() on
its own. decode() checks that every branch target lands on an instruction
in the stream it was given, and a lone branch has no other instruction to
land on, so every supported s_branch and s_cbranch_* was reported as
"unsupported operands" (3 of 15 rows in bitwise-branch.bin).

Add decode_at(), which decodes one instruction at its real stream offset
without the stream-wide target check, and DecodedInstruction::branch_target().
inspect now identifies the whole stream first and checks each branch
target against those boundaries, reporting a bad target separately.
decode() is rebuilt on decode_at() with unchanged behaviour.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:40:55 -06:00
Adeeb Rahman 9b22c664bb Handle non-alertable extended guest event waits
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:39:46 -05:00
elforeign 98bbe57471 Merge remote-tracking branch 'origin/main' into feat/agent-task-queue
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 00:38:58 -06:00
elforeign 5baa630ff0 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 00:38:51 -06:00
Adeeb Rahman 654e4c28b5 Resolve immediate guest waits on multiple events
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:38:04 -05:00
Adeeb Rahman b861348667 Support 64-bit integer conversion in the guest CRT
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:36:13 -05:00
Adeeb Rahman a4a2425bcc Parse Windows long integers in the guest CRT
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:35:00 -05:00
Adeeb Rahman edba4df430 Expose guest CRT errno and report allocation failures
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:33:03 -05:00
ates 60f4f38da1 Fix C7 instruction boundaries and trusted fixture probe reporting
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 09:32:34 +03:00
Adeeb Rahman f992721fda Back CRT allocation imports with the default guest heap
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:31:29 -05:00
Adeeb Rahman 8e29b54919 Track allocations owned by private guest heaps
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:30:00 -05:00
Adeeb Rahman 43f54ff1d2 Merge remote-tracking branch 'origin/main' into feat/system-runtime-expansion
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 01:29:30 -05:00
Ranveer Soni 951189c61b Merge pull request #167 from elforeign/feat/texture-bc-formats
texture: BC2, BC3, BC4 and BC5 CPU block decoders
2026-11-24 11:58:17 +05:30
Adeeb Rahman cd01d04a96 Resize default guest heap blocks with transactional failure
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:27:52 -05:00
Adeeb Rahman 6b068a225d Expose a bounded default process heap to Win64 guests
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:26:23 -05:00
Adeeb Rahman fa6a52ab93 Catalog Win64 wide string and byte move signatures
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:24:40 -05:00
Adeeb Rahman 4c1ac39c7e Support Win64 wide string length and comparison
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:23:47 -05:00
Adeeb Rahman d76c7d061c Compare CRT byte strings through checked guest reads
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:22:38 -05:00
Adeeb Rahman 7134523a08 Run CRT byte memory operations through checked guest spans
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:21:38 -05:00
elforeign 1493dcf83b isa: check identification against LLVM and add literal-only forms
The extension-word length rules were written by hand because the XML
gives none, so they needed an outside oracle. An LLVM test now compares
names and lengths for one instruction per family and extension word.
It found five instructions the XML lists only under a literal encoding,
which the first table omitted; they are now base forms that always carry
a literal.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:20:26 -06:00
Adeeb Rahman e4b1898b00 Serve bounded CRT byte string lengths through the guest registry
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:20:22 -05:00
Adeeb Rahman 7130da2635 Reject generated CRT calls without a guest ABI adapter
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:18:57 -05:00
Adeeb Rahman 7599de0e01 Check Win64 service stack argument offsets
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:17:52 -05:00
Adeeb Rahman 86467c2f6c Add guest events with shared duplicate handles
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:17:00 -05:00
Adeeb Rahman 58d0d5a088 Expand guest timing and thread handle services
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 01:12:35 -05:00
elforeign 54506125d4 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
# Conflicts:
#	CHANGELOG.md
2026-11-24 00:11:41 -06:00
elforeign 7c89ed62a2 changelog: record BC2-BC5 CPU block decoders
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:11:35 -06:00
elforeign b9b0a40101 Merge remote-tracking branch 'origin/main' into feat/agent-task-queue
# Conflicts:
#	CHANGELOG.md
2026-11-24 00:11:26 -06:00
elforeign f19d57967d Merge remote-tracking branch 'origin/main' into feat/texture-bc-formats 2026-11-24 00:11:08 -06:00
elforeign 62c933051b isa: generate complete gfx1030 instruction metadata and identification
The decoder knew 25 hand-matched forms, so any other instruction stopped
decoding with no record of what it was or how long it was. A two-stage
generator now reduces AMD's public RDNA 2 XML to all 1,460 base forms,
with a committed snapshot so CI can check the generated table offline.
identify() finds any form's exact length, including literal, SDWA, DPP
and NSA words, and the shaders CLI reports discovered against executable
forms so metadata coverage is never read as GPU support.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:11:00 -06:00
elforeign e35df04069 Expand the agent task queue to cpu/gpu/runtime/shared/qa with deterministic checks
The queue now has three engineering tracks plus shared and qa work. Queue
rules move from shell/awk in workflows into a standard-library Python package
so they are testable offline: claim decisions (dependencies, cycles, file
overlap, area permission), leases renewed only by the holder, reassign and
release, acceptance-command approval by hash, pull request ownership/overlap/
stale/verification checks and a machine-readable summary. Workflows apply the
decisions with minimal permissions, never put user text in run blocks and
never check out pull request code. The sync script fetches the real upstream
so interface changes during work are reported.

Not yet run on GitHub.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:09:38 -06:00
Ranveer Soni c88359b379 stuff 2026-11-24 11:37:34 +05:30
Ranveer Soni c12ad2e2f8 feat: expand X19 native ARM64 DBT and guest CPU runtime
Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 11:34:39 +05:30
elforeign ef1a94ce71 texture: add BC2, BC3, BC4 and BC5 block decoders
Adds spec-derived CPU decoders (UNORM and SNORM for BC4/BC5) with
truncating integer interpolation and hand-computed tests, so later
texture work has verified references for these formats.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:01:14 -06:00
elforeign a89f9d8d06 coordination: add GitHub issue task queue for parallel agents
CPU and GPU work proceed in parallel, largely through coding agents.
Tasks posted as issues with owned file lists and an acceptance command
can be claimed through a serialised workflow, so work is picked up
without relaying prompts by hand and two claims never edit one file.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-23 23:58:25 -06:00
Ranveer Soni 93bd04c70f feat(imports): automated API compatibility generation pipeline and metadata ingestion (X18) 2026-11-24 10:50:57 +05:30
Ranveer Soni 0329e683b5 Merge pull request #61 from ranveersoni98/feat/x15-xbox-runtime
feat: Xenora X15–X17.1 runtime and Metal graphics
2026-11-24 09:54:16 +05:30
Ranveer Soni 0be6220e47 feat(add): x17things, as well as more d3d12 testing 2026-11-24 09:49:53 +05:30
Ranveer Soni e3c082ca9d Add synthetic PE32+ guest runtime support 2026-11-24 07:15:26 +05:30
Ranveer Soni 9cf09cb823 chore: preserve X14.5 probe and documentation updates
Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 07:03:55 +05:30
Andre EncarnacaoandClaude Opus 5.5 6722c041d1 fix: restore a compiling, green main (#60)
The static PE probe commit left main failing CI at every step after formatting:

- cargo fmt: apply rustfmt to cli/main.rs, loader/probe.rs and
  loader/tests/probe_static.rs.
- clippy: collapse the four nested if / if-let blocks in probe.rs into
  let-chains (edition 2024); no behaviour change.
- build: make the probe library match its two callers.
  run_probe_and_export now takes the PE bytes and a ProbeConfig (the
  CLI's config was previously ignored in favour of the default),
  ProbeReport.pe is renamed to ProbeReport.parsed, and
  pe::IMAGE_SCN_CNT_CODE (0x00000020, PE/COFF section flag) is added.
- tests: gate test_guest_dbt_first_rendered_frame_with_metal behind a new
  xenora-loader gpu-tests feature. CI's paravirtual Metal device lacks
  Apple family 7; the two CPU-only DBT tests in the same file keep
  running in CI. scripts/test-gpu.sh now runs the gated test.

Signed-off-by: Andre Encarnacao <andreencar@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 06:57:07 +05:30
Ranveer Soni 11e95b9e54 feat(loader): add static PE compatibility probe
- Add a read-only probe command that inventories PE metadata, imports, relocations, TLS, and entry-point instruction coverage
- Export compatibility diagnostics as CSV, JSON, and Markdown
2026-11-23 22:13:06 +05:30
Ranveer Soni cc8c71ce86 feat: work on jit and x13 (#59) 2026-11-23 22:06:04 +05:30
Ranveer Soni 585aa5fc2d feat: add RDNA2 image sampling and x86-64 guest execution (#58) 2026-11-23 21:13:02 +05:30
Ranveer Soni da1027c9a1 Merge pull request #57 from ranveersoni98/feat/x10-texture-sampling
X10: Native Metal texture sampling foundation
2026-11-23 20:03:04 +05:30
358 changed files with 28975 additions and 21875 deletions

No files matched your search

+34
View File
@@ -0,0 +1,34 @@
# Global fallback: every file in the repository requires maintainer review.
* @MacosPorters/maintainers
# Frozen cross-track ABI contracts (fast-tracked [ABI] PRs)
/abi/ @MacosPorters/maintainers
/Cargo.toml @MacosPorters/maintainers
/shims/CMakeLists.txt @MacosPorters/maintainers
# Track A: Host launcher, CrossOver/Rosetta runner, runtime VEH & Win32 forwarders
/launcher/ @MacosPorters/maintainers
/shims/runtime_veh/ @MacosPorters/maintainers
/shims/win32_bridge/ @MacosPorters/maintainers
/scripts/build-shims.sh @MacosPorters/maintainers
# Track B: Memory (xmem) & Storage (XCRDAPI / DirectStorage)
/shims/xmem/ @MacosPorters/maintainers
/shims/xcrdapi/ @MacosPorters/maintainers
# Track C: Graphics (d3d12_xs, xg_xs, FidelityFX/BVH hooks)
/shims/d3d12_xs/ @MacosPorters/maintainers
/shims/xg_xs/ @MacosPorters/maintainers
/shims/ffx_bvh_hooks/ @MacosPorters/maintainers
# Track D: Shader pipeline (DXBC/DXIL/ACCC/FSPX & RDNA2 transpiler)
/shader-transpiler/ @MacosPorters/maintainers
# Track E: Platform runtime (xgameruntime), Input (GameInput) & Audio/DSP
/shims/xgameruntime/ @MacosPorters/maintainers
/shims/gameinput/ @MacosPorters/maintainers
/shims/audio/ @MacosPorters/maintainers
# Track F: Conformance tests & documentation
/tests/conformance/ @MacosPorters/maintainers
/docs/ @MacosPorters/maintainers
+30 -15
View File
@@ -1,42 +1,57 @@
name: Bug report
description: Report a reproducible defect in Xenora or XenoMetal.
description: A reproducible defect.
title: "bug: "
labels: [bug]
body:
- type: markdown
attributes:
value: |
Use synthetic or authorized inputs only. For vulnerabilities, follow SECURITY.md. Remove personal paths, credentials and private data from logs.
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue. For vulnerabilities follow SECURITY.md.'
- type: textarea
id: description
attributes:
label: Description
description: What went wrong? Identify the affected subsystem and expected behavior.
description: 'What went wrong and what you expected.'
validations:
required: true
- type: textarea
id: steps
attributes:
label: Reproduction steps
description: Include exact commands and a minimal, legally distributable input if applicable.
description: 'Exact commands and a minimal, legally distributable input.'
validations:
required: true
- type: textarea
id: environment
attributes:
label: Environment
description: Commit, macOS, Apple GPU, RAM, Rust, Xcode and relevant tool versions. Include sanitized doctor output if available.
description: 'Commit, macOS, chip, memory, CrossOver and Rosetta 2 versions, graphics backend. Remove personal paths and credentials.'
validations:
required: true
- type: textarea
id: output
id: scope
attributes:
label: Actual output and diagnostics
description: Include expected versus actual results, validation-layer messages and relevant logs.
- type: checkboxes
id: confirmation
label: Scope and dependencies
description: 'Affected area; related issues.'
validations:
required: false
- type: textarea
id: acceptance
attributes:
label: Confirmation
options:
- label: I searched for existing reports and have not included sensitive or unauthorized material.
required: true
label: Acceptance criteria
description: 'When is this fixed?'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation requirements
description: 'How to confirm the fix independently.'
validations:
required: true
- type: textarea
id: licensing
attributes:
label: Licensing and provenance
description: 'Only if third-party code or a dependency is involved.'
validations:
required: false
+50
View File
@@ -0,0 +1,50 @@
name: Documentation
description: Fix, add or restructure documentation.
title: "docs: "
labels: [documentation]
body:
- type: markdown
attributes:
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
- type: textarea
id: problem
attributes:
label: Problem
description: 'What is unclear, wrong or missing.'
validations:
required: true
- type: textarea
id: context
attributes:
label: Technical context
description: 'Pages and sources involved.'
validations:
required: true
- type: textarea
id: scope
attributes:
label: Scope
description: 'Files to change; update docs/README.md if pages are added or moved.'
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Dependencies
description: 'None if none.'
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: 'Claims are scoped to their evidence; links work.'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation requirements
description: 'scripts/audit/docs_hygiene.py and claims audit pass.'
validations:
required: true
-31
View File
@@ -1,31 +0,0 @@
name: Feature proposal
description: Propose a compiler, graphics, tooling or other project enhancement.
title: "feat: "
labels: [enhancement]
body:
- type: textarea
id: problem
attributes:
label: Problem or gap
description: Which limitation does this feature address?
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Proposed approach
description: Explain the intended behavior and affected components. Link relevant public specifications when available.
validations:
required: true
- type: textarea
id: criteria
attributes:
label: Acceptance criteria
description: What observable results and tests would demonstrate completion?
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives and trade-offs
description: Include limitations, dependency costs or impacts on native ARM64 and Metal if relevant.
-31
View File
@@ -1,31 +0,0 @@
name: Hardware verification report
description: Submit real hardware test results for Xenora.
title: "hardware: "
labels: [needs-verification]
body:
- type: textarea
id: environment
attributes:
label: Test environment
description: Commit, Apple chip/GPU, RAM, macOS, Xcode/Metal version, Rust version, validation settings. Do not include serial numbers or registry IDs.
validations:
required: true
- type: textarea
id: commands
attributes:
label: Commands and inputs
description: Include exact commands and synthetic or authorized fixture identifiers.
validations:
required: true
- type: textarea
id: results
attributes:
label: Results
description: Report actual output, pass/fail/skip counts, and limitations. Compilation alone does not prove execution.
validations:
required: true
- type: textarea
id: performance
attributes:
label: Performance data (optional)
description: Include repetitions, warm-up, timing method, validation state and variability if reporting measurements.
+57
View File
@@ -0,0 +1,57 @@
name: Hybrid engineering task
description: Integration, configuration, diagnostics or tooling around CrossOver.
title: "task: "
labels: [track: hybrid]
body:
- type: markdown
attributes:
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
- type: textarea
id: problem
attributes:
label: Problem
description: 'What is missing or wrong, and why it matters for the hybrid architecture.'
validations:
required: true
- type: textarea
id: context
attributes:
label: Technical context
description: 'Versions (macOS, chip, CrossOver, Rosetta 2, graphics backend), related issues, upstream references.'
validations:
required: true
- type: textarea
id: scope
attributes:
label: Scope
description: 'What is in and out. Avoid duplicating what CrossOver already provides.'
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Dependencies
description: "Blocking issues or decisions; write 'none' if none."
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: 'Observable, checkable results.'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation requirements
description: 'How an independent contributor verifies it; commands, workloads, evidence class.'
validations:
required: true
- type: textarea
id: licensing
attributes:
label: Licensing and provenance
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
validations:
required: true
+57
View File
@@ -0,0 +1,57 @@
name: Performance investigation
description: Measure or improve performance with evidence.
title: "perf: "
labels: [performance,track: hybrid]
body:
- type: markdown
attributes:
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue. Do not promise gains before measuring.'
- type: textarea
id: problem
attributes:
label: Problem and metric
description: 'Which metric (average FPS, 1% low, frame-time percentiles, CPU or GPU use, memory, startup, shader compile latency) and why.'
validations:
required: true
- type: textarea
id: context
attributes:
label: Technical context
description: 'Workload, hardware (reference: M4, 24 GB), software versions, settings.'
validations:
required: true
- type: textarea
id: scope
attributes:
label: Scope
description: 'Measurement only, or change as well.'
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Dependencies
description: 'Measurement protocol (#353) and baseline (#355).'
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: 'Measured before-and-after under equivalent conditions, with variance.'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation requirements
description: 'Correctness and rendering equivalence verified before the result counts.'
validations:
required: true
- type: textarea
id: licensing
attributes:
label: Licensing and provenance
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
validations:
required: true
+37 -22
View File
@@ -1,42 +1,57 @@
name: Technical research
description: Record an ISA, Metal or publicly documented graphics research finding.
name: Upstream research or dependency evaluation
description: Assess a project, component or license from public sources.
title: "research: "
labels: [research]
labels: [research,track: hybrid]
body:
- type: markdown
attributes:
value: Use only public, authorized sources. Do not link to leaked SDKs, private documentation or unauthorized game content.
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
- type: textarea
id: question
id: problem
attributes:
label: Research question or finding
label: Question
description: 'The decision this research informs.'
validations:
required: true
- type: textarea
id: sources
id: context
attributes:
label: Sources and applicability
description: URLs, specification sections or revision, exact architecture and license/provenance if relevant.
label: Technical context
description: 'What is already known; link docs/research/upstream-registry.md entries.'
validations:
required: true
- type: dropdown
id: evidence
- type: textarea
id: scope
attributes:
label: Evidence class (highest applicable)
options:
- A - Measured on named hardware
- B - Normative source for exact target
- C - Normative source for related target
- D - Non-normative official material
- E - Independent software behavior
- F - Uncorroborated community claim
- U - Unknown or assumption
label: Scope
description: 'Which versions or components; desk research or execution.'
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Dependencies
description: 'Other issues or decisions; execution may need a maintainer-approved environment.'
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: 'Each claim cites vendor or upstream documentation, or a recorded observation of a stated version; unknowns stay marked unknown.'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation, limitations and proposed next steps
description: Distinguish Apple or desktop RDNA observations from Xbox behavior.
label: Validation requirements
description: 'Independent re-derivation and evidence class (A to U).'
validations:
required: true
- type: textarea
id: licensing
attributes:
label: Licensing and provenance
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
validations:
required: true
+90
View File
@@ -0,0 +1,90 @@
name: Parallel track handoff issue
description: Self-contained engineering task scoped to one BetterXen track (A-F) for conflict-free parallel work.
title: "[M1-X0] "
labels: ["track: hybrid"]
body:
- type: markdown
attributes:
value: |
Use this template to hand off work to contributors across Tracks A-F.
Keep file scopes disjoint so 5-8+ contributors can work concurrently without merge conflicts.
Never include proprietary game files, names, hashes, or leaked material in issues or PRs.
- type: textarea
id: zen
attributes:
label: Zen
description: 1–2 plain-English sentences explaining the core purpose of this issue and why it matters.
placeholder: Enable guest allocations to stay within a 16 GiB Mac's unified memory budget so bring-up never OOMs.
validations:
required: true
- type: dropdown
id: track
attributes:
label: Track
options:
- "Track A — Host Launcher, VEH & Win32 Bridge"
- "Track B — Memory (xmem) & Storage (XCRDAPI)"
- "Track C — Graphics (d3d12_xs, xg_xs, DXR/FFX)"
- "Track D — Shader Pipeline (DXBC/DXIL/ACCC)"
- "Track E — Platform (xgameruntime), Input & Audio"
- "Track F — Conformance, QA & Performance"
- "ABI Freeze — Shared Contract (abi/)"
validations:
required: true
- type: dropdown
id: milestone
attributes:
label: Milestone
options:
- "M0 — Repo, ABI & Cross-Build"
- "M1 — Boot to D3D12XboxCreateDevice"
- "M2 — First Frame & Shader Format Gate"
- "M3 — Full Shaders, Streaming & Texture Correctness"
- "M4 — 3D Rendering, DXR/BVH & Input"
- "M5 — Audio, Saves & Stability"
- "M6 — Shader Cache, 16 GB Optimization & Polish"
validations:
required: true
- type: textarea
id: file_scope
attributes:
label: Exclusive file scope
description: Exact directories/files this issue may modify. Do not overlap with other active issues.
placeholder: |
- `shims/xmem/**`
- `tests/conformance/test_xmem/**`
validations:
required: true
- type: textarea
id: api_contract
attributes:
label: Exact API / export / COM contract
description: Exported symbols (referencing `abi/defs/*.def`), COM interface IIDs/vtable slots, or CLI flags to implement.
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Hard dependencies
description: Blocking `[ABI]` or prerequisite issues (`none` if immediately claimable).
value: "none"
validations:
required: true
- type: textarea
id: synthetic_test
attributes:
label: Required synthetic conformance test
description: Clean-room synthetic test in `tests/conformance/` or `cargo test` proving correctness.
validations:
required: true
- type: textarea
id: exit_criteria
attributes:
label: Definition of done
description: Exact commands that must succeed locally and in CI.
placeholder: |
- `cargo fmt --all -- --check && cargo clippy --workspace --all-targets -- -D warnings && cargo test --workspace`
- `scripts/build-shims.sh` (all DLL export checks pass)
- Synthetic conformance binary passes under CrossOver/Wine
validations:
required: true
+57
View File
@@ -0,0 +1,57 @@
name: Testing and validation
description: Add or run a validation for a workload or behaviour.
title: "validate: "
labels: [needs-verification,track: hybrid]
body:
- type: markdown
attributes:
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
- type: textarea
id: problem
attributes:
label: Problem
description: 'What is missing or wrong, and why it matters for the hybrid architecture.'
validations:
required: true
- type: textarea
id: context
attributes:
label: Technical context
description: 'Versions (macOS, chip, CrossOver, Rosetta 2, graphics backend), related issues, upstream references.'
validations:
required: true
- type: textarea
id: scope
attributes:
label: Scope
description: 'What is in and out. Avoid duplicating what CrossOver already provides.'
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Dependencies
description: "Blocking issues or decisions; write 'none' if none."
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: 'Observable, checkable results.'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation requirements
description: 'How an independent contributor verifies it; commands, workloads, evidence class.'
validations:
required: true
- type: textarea
id: licensing
attributes:
label: Licensing and provenance
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
validations:
required: true
-37
View File
@@ -1,37 +0,0 @@
## Summary
<!-- What changes, and why? Link an issue if relevant. -->
## Implementation and evidence
<!-- Describe affected subsystems, architecture assumptions, specification sections and upstream provenance where applicable. -->
## Verification
<!-- List actual commands and outcomes. Include hardware, validation-layer state and pass/fail/skip counts for GPU tests. Mark unrun checks explicitly. -->
| Check | Result / evidence |
| --- | --- |
| Formatting and lint | |
| Unit / integration tests | |
| GPU / differential tests | |
| Fuzzing / mutation / benchmarks, if relevant | |
## Compatibility and limitations
<!-- Note unsupported behavior, regressions, interface changes, performance effects and remaining uncertainty. -->
## Checklist
- [ ] I reviewed the changes and disclosed material AI assistance below, if applicable.
- [ ] The change preserves native ARM64 and Metal-first requirements.
- [ ] I added relevant tests or explained why they are not applicable.
- [ ] I did not report skipped or unrun tests as passing.
- [ ] I updated applicable documentation, claims and status records.
- [ ] Third-party code and fixtures have verified licenses and provenance, or none were added.
- [ ] No restricted materials, credentials or private data are included.
- [ ] My commits are signed off under the DCO.
## AI assistance
<!-- Describe material assistance and the checks you personally performed, or state none. -->
+29
View File
@@ -0,0 +1,29 @@
## Related issue
Closes #
## Summary
## Technical changes
## Tests performed
Commands, versions, pass/fail/skip counts and hardware. A skipped test is not a pass.
## Performance impact
Measured before and after under equivalent conditions, or "none expected" with reason.
## Compatibility impact
Workloads, macOS or CrossOver versions and hardware affected. Do not claim support that was not tested.
## Known limitations
## Third-party code attribution
Source repository, exact commit, license, modifications. "None" if none.
## Dependency and licensing considerations
New or changed dependencies, license compatibility with GPL-3.0-or-later, redistribution limits (proprietary components are never bundled). DCO: commits are signed off.
-62
View File
@@ -1,62 +0,0 @@
name: Native Rust checks
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
concurrency:
group: native-rust-${{ github.ref }}
cancel-in-progress: true
jobs:
native-rust:
name: ARM64 CPU and build checks
runs-on: macos-26
timeout-minutes: 15
env:
CARGO_BUILD_JOBS: 3
PYTHONDONTWRITEBYTECODE: 1
CARGO_BUILD_TARGET: aarch64-apple-darwin
RUSTUP_TOOLCHAIN: 1.100.0-aarch64-apple-darwin
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Verify runner architecture
run: |
uname -m
test "$(uname -m)" = arm64
test "$(sysctl -n sysctl.proc_translated)" = 0
- name: Install native Rust
run: |
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy
rustc -vV
- name: Check generated status and PE fixtures
run: |
python3 scripts/audit/status.py --check
for fixture in x2 x3 x4; do
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
done
- name: Check formatting and lint
run: |
cargo fmt --all -- --check
cargo clippy --locked --workspace --all-targets -- -D warnings
cargo fmt --manifest-path experiments/x1/Cargo.toml -- --check
cargo clippy --locked --manifest-path experiments/x1/Cargo.toml --all-targets --all-features -- -D warnings
- name: Run CPU tests and dependency checks
run: |
cargo test --locked --workspace
cargo test --locked --manifest-path experiments/x1/Cargo.toml
scripts/audit/dependencies.sh
scripts/audit/claims.sh
- name: Inspect native CLI
run: |
cargo build --locked -p xenora
binary=target/aarch64-apple-darwin/debug/xenora
file "$binary"
test "$(lipo -archs "$binary")" = arm64
otool -L "$binary"
+53
View File
@@ -0,0 +1,53 @@
name: Hybrid build and shim checks
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
concurrency:
group: hybrid-ci-${{ github.ref }}
cancel-in-progress: true
jobs:
arm64-host-and-shims:
name: ARM64 host Rust + x86-64 PE32+ shims
runs-on: macos-26
timeout-minutes: 15
env:
CARGO_BUILD_JOBS: 3
CARGO_BUILD_TARGET: aarch64-apple-darwin
RUSTUP_TOOLCHAIN: 1.100.0-aarch64-apple-darwin
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Verify Apple Silicon runner
run: |
test "$(uname -m)" = arm64
test "$(sysctl -n sysctl.proc_translated)" = 0
- name: Install Rust toolchain
run: |
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy
rustc -vV
- name: Check ARM64 Rust workspace (launcher + shader-transpiler)
run: |
cargo fmt --all -- --check
cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
cargo build --locked -p bx-cli
binary=target/aarch64-apple-darwin/debug/bx-cli
file "$binary"
test "$(lipo -archs "$binary")" = arm64
- name: Install mingw-w64 and CMake
env:
HOMEBREW_NO_AUTO_UPDATE: 1
HOMEBREW_NO_INSTALL_CLEANUP: 1
run: |
brew install mingw-w64 cmake
x86_64-w64-mingw32-g++ --version | head -n 1
- name: Cross-compile all x86-64 PE32+ shim DLLs and verify exports
run: scripts/build-shims.sh
+43
View File
@@ -0,0 +1,43 @@
name: Repository hygiene
# Fast checks on tracked files that need no Rust toolchain and no network:
# merge-conflict markers, broken relative Markdown links and invalid workflow
# YAML (scripts/audit/docs_hygiene.py). A second, advisory step warns when
# source or script changes arrive without a CHANGELOG.md update; it never fails.
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
concurrency:
group: hygiene-${{ github.ref }}
cancel-in-progress: true
jobs:
hygiene:
name: Repository hygiene
runs-on: ubuntu-24.04-arm
timeout-minutes: 5
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
fetch-depth: 0
- name: Install PyYAML
run: python3 -c 'import yaml' 2>/dev/null || python3 -m pip install --user --break-system-packages pyyaml
- name: Check documentation and workflow files
run: python3 scripts/audit/docs_hygiene.py --require-yaml
- name: Remind about the changelog (advisory)
if: github.event_name == 'pull_request'
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: |
changed="$(git diff --name-only "$BASE_SHA"...HEAD || true)"
if printf '%s\n' "$changed" | grep -Eq '^(abi|launcher|shims|shader-transpiler|scripts|tests)/' \
&& ! printf '%s\n' "$changed" | grep -qx 'CHANGELOG.md'; then
echo "::warning title=Changelog::Source or script files changed without a CHANGELOG.md update."
fi
+6 -8
View File
@@ -1,10 +1,9 @@
# Rust and local builds
/target/
/experiments/x1/target/
/build/
/build-shims/
/cmake-build-*/
/fuzz/target/
/fuzz/artifacts/
/local-runs/
# macOS / Xcode local state
.DS_Store
@@ -20,8 +19,6 @@
*.profraw
*.profdata
# Keep Cargo.lock, source fixtures, reviewed golden files and documentation tracked.
# Local AI agent tooling
.agents/
.claude/
@@ -29,9 +26,10 @@
.cursor/
.gemini/
# Local gate evidence and intermediate fixture objects
# Local gate evidence and ignored probes
/artifacts/
/tests/validation/target/
__pycache__/
*.pyc
/diagnostics/probe/
/diagnostics/title-candidate-*/
/diagnostics/title-check/
+120 -64
View File
@@ -1,87 +1,143 @@
# Xenora engineering rules
# BetterXen Engineering & Agent Rules
### Native Apple Silicon
These rules apply to every human contributor and coding agent (`CLAUDE.md` is a symlink to this file). Strategic decisions are recorded in `docs/adr/0005-crossover-hybrid-direction.md` and `docs/adr/0006-retire-in-tree-native-workspace.md`; the single authoritative roadmap is `docs/roadmap.md`.
Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dependencies, Wine, CrossOver, Windows compatibility layers, OpenGL fallback rendering, or unnecessary graphics abstraction layers.
---
- SPIR-V is permitted as a compiler intermediate representation. It does not justify a Vulkan runtime.
- All host executables and native dependencies must support ARM64. Verify with file, lipo -archs and otool -L.
- Never run Intel binaries through Rosetta, even temporarily. Never add a dependency that requires Rosetta to build or run. If a dependency cannot run natively, find an alternative or document the limitation.
- The guest architecture being decoded may be x86-64, but Xenora itself runs natively on ARM64.
- Support M1 through M5 and future generations through runtime capability detection. Do not assume all Apple GPUs share capabilities.
- Use aarch64-apple-darwin as the Rust target.
## 0. First-Time Contributor Onboarding
### Honesty and evidence
If the user asks to contribute, get started, or pick a task (even with a short prompt like *"help me contribute"*), walk them through this exact end-to-end flow:
- Never report a test as passed unless it ran and passed. Never count a skipped test as GPU verification.
- Never invent benchmark results, hardware compatibility, API names, instruction encodings, hardware capabilities or implementation status.
- Never claim a clean build unless the commands actually succeeded.
- Never present planned features as working. State clearly that game execution is not supported unless demonstrated.
- Never replace GPU tests with mocks and then claim GPU support.
- Unknown information is classified as unknown and becomes a documented research task.
- Every hardware claim carries an evidence class (section 9). Never present a lower-class claim as if it were a higher-class one.
- Never claim "verified on Xbox hardware". Xenora has no Xbox hardware access. Agreement with a spec-derived reference is not agreement with Xbox hardware, and docs must say so.
- Do not hide errors behind fallbacks. Do not translate unsupported instructions into silent no-ops. Do not weaken or delete tests to make them pass. Do not change mutation counting, tolerances or gate definitions to improve a score.
1. **Preflight host & tools:**
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`.
- If `mingw-w64`, `cmake`, or `gh` is missing on macOS, ask permission before running `brew install mingw-w64 cmake gh`.
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`).
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor` to report Apple Silicon, Rosetta 2, CrossOver, and toolchain readiness.
- Verify whether the user has push access or needs a fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
2. **Discover & pick an unclaimed issue:**
- Query ready issues in the active milestone:
```sh
gh issue list --repo MacosPorters/betterxen --state open --label "status: ready" --json number,title,labels,assignees
```
- Inspect comments and open PRs on candidate issues to filter out any issue that already has an active claim (< 7 days old).
- Present the unclaimed options in plain English (recommending 1–2 good starting issues matching the user's background) and wait for the user to choose one before coding.
3. **Claim & isolate:**
- Post `Claiming — branch: track-<a..f>/<issue>-<slug>` on the chosen issue and create that branch (or `git worktree`) off `origin/main`.
4. **Implement strictly in scope:**
- Read the full issue body (`gh issue view <issue> --repo MacosPorters/betterxen`) and the relevant contracts in `abi/defs/` and `abi/include/`.
- Edit **only** files inside the issue's **Exclusive file scope** (plus `CHANGELOG.md`). Add new synthetic C++ conformance tests under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake).
5. **Verify locally (including hosts without CrossOver):**
- Run every command in Section 8 and fix all warnings/failures before stopping.
- **No CrossOver installed?** The contributor can still run all ARM64 Rust checks, `scripts/build-shims.sh` (verifying all 16 PE32+ DLLs and exact exports), and `python3 scripts/audit/docs_hygiene.py`. Report honestly in the PR that live CrossOver execution was not run locally and needs verification on a CrossOver host—never report an unrun check as passed.
6. **Review & submit PR:**
- Present a concise summary of changes and exact verification outputs, and ask explicit user permission before running `git commit -s` (DCO sign-off, zero AI trailers), pushing, and opening a PR (`Closes #<issue>`).
- After opening the PR, watch CI (`gh pr checks --watch`) until both `Hybrid build and shim checks` and `Repository hygiene` pass.
### Independence of verification
---
- The agent that writes a component does not certify it. The two independent reviewers (section 5) re-derive expectations from primary sources and are not told the implementers' conclusions as ground truth.
- The same faulty code must never produce both the expected and the actual values in a test.
## 1. Direction & Architecture
### Legal and clean-room
- **Hybrid-first on Apple Silicon:** CrossOver 26.3+ (externally installed), Wine runtime APIs, Rosetta 2 (`ROSETTA_ADVERTISE_AVX=1`), and D3DMetal 3.0 (subject to license terms) form the external compatibility foundation. DXMT, DXVK, VKD3D-Proton, MoltenVK, and `utmapp/d3dmetal-native` may be evaluated and used where license-compatible and technically justified.
- **BetterXen's in-tree scope:**
- `abi/` — Frozen cross-DLL C headers (`abi/include/*.h`) and canonical `.def` export tables (`abi/defs/*.def`).
- `launcher/` — Native **ARM64** macOS Rust CLI (`bx-cli`), PE32+ import classifier (`bx-probe`), and JSONL trace aggregator (`bx-telemetry`).
- `shims/` — Cross-compiled **x86-64 Windows PE32+** Xbox Game OS shim DLLs (C++20 via `x86_64-w64-mingw32-g++` + CMake, statically linked against GCC/C++/winpthread so Wine bottles need zero extra MinGW runtime DLLs).
- `shader-transpiler/` — Rust shader container classifier (`dxbc-accc`) and RDNA 2 (`gfx1030`) transpiler pipeline (expanded on demand per the M2 shader-format gate).
- `tests/conformance/` — Clean-room synthetic x86-64 PE32+ test binaries (auto-discovered via `test_*/CMakeLists.txt`).
- **Retired native-first code:** The earlier native-first workspace was retired from `main` per ADR 0006 and remains preserved permanently at Git tag `native-first-final`. Do not open native-only issues; if hybrid work requires an independent component (such as RDNA 2 decoding), file a focused track issue.
- **No unverified compatibility assumptions:** This is an active engineering foundation, not a verified Xbox game compatibility stack. Do not assume CrossOver, Rosetta 2, or D3DMetal provide Xbox runtime behavior without measurement.
- Use only publicly accessible documentation and authorized materials. Never obtain or use leaked SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, or proprietary game binaries and shader collections. Do not attempt to bypass documentation access restrictions.
- Contributors who have seen leaked or confidential Xbox materials must not contribute. State this in CONTRIBUTING.md and require a DCO sign-off (Signed-off-by) on contributions.
- Include a plain statement in docs/legal.md: Xenora does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation. Add a note that this is not legal advice and that contributors should know their local laws, including anti-circumvention provisions such as DMCA section 1201.
- Before copying or adapting any upstream code: verify the exact license of that file (not just the repo), check GPL-3.0-or-later compatibility, preserve copyright notices, record source repository and exact commit, document modifications, include required attribution. Never remove upstream copyright notices. If licensing is uncertain, stop using that code until resolved.
- Keep Xenora's emulator implementation original. Never copy, port, translate or adapt emulator source from Leonida, KyTx, AnyPS5 or similar projects.
- Validate the technical compatibility and safety of user-provided files. Do not ask for ownership receipts, accounts or acquisition provenance as part of file loading. Contributor provenance and licensing obligations still apply.
- Never place restricted material in the repository or its Git history.
- Do not push, publish, or change remote visibility without explicit user authorization. Prepare locally and report readiness.
---
### Quality
## 2. Parallel Track Ownership (5–8+ Concurrent Contributors / Agents)
No AI slop (section 29).
Every feature issue belongs to **one track** and defines an **exclusive file scope**. Stay strictly inside your issue's file scope to avoid merge conflicts across concurrent contributors and agents:
Read docs/interfaces.md and docs/progress.md before implementation.
| Track | Exclusive Directories | Responsibility |
| --- | --- | --- |
| **ABI Gate** | `abi/` | Frozen headers & `.def` files (small `[ABI]` PRs merged first) |
| **Track A** | `launcher/`, `shims/runtime_veh/`, `shims/win32_bridge/`, `scripts/build-shims.sh` | ARM64 CLI/runner (with `env_clear()` isolation), `clwb` VEH trap, ADX tripwire, JSONL telemetry, Win32/PSM forwarders |
| **Track B** | `shims/xmem/`, `shims/xcrdapi/` | `xmem.dll` (virtual/physical/scatter allocator, Lockhart 8–10 GB budget) & `XCRDAPI.dll` (DirectStorage) |
| **Track C** | `shims/d3d12_xs/`, `shims/xg_xs/`, `shims/ffx_bvh_hooks/` | Xbox D3D12 COM proxy → D3DMetal 3.0, `PresentX`, RDNA 2 texture tiling (`XG`), DXR/BVH4 & FidelityFX hooks |
| **Track D** | `shader-transpiler/` | `DXBC`/`DXIL`/`ACCC`/`FSPX` parser, RDNA 2 → DXIL/MSL transpiler, shader cache, `d3dmetal-native` harness |
| **Track E** | `shims/xgameruntime/`, `shims/gameinput/`, `shims/audio/` | Offline GDK runtime, `GameInput.dll` (`@1`), `AcpHal.dll`, `xapu.dll`, `chad.dll` |
| **Track F** | `tests/conformance/`, `docs/` | Synthetic PE32+ conformance tests, integration fixture, benchmarks, documentation |
## Changelog maintenance
### Cross-Track `[ABI]` Rule
- Never edit another track's directory inside a feature PR.
- If your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first. Once merged, both provider and consumer tracks implement against the frozen contract in parallel.
- When adding a new conformance test, create `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` — CMake auto-discovers `test_*` directories without editing `tests/conformance/CMakeLists.txt`.
- At the start of every engineering task, read `CHANGELOG.md` alongside the relevant project documentation. Review the existing `[Unreleased]` entries before implementation to avoid duplicating completed work.
- Update the changelog in the same task for every meaningful addition, modification, fix, removal or security change, including work implemented by another agent. Use `Added`, `Changed`, `Fixed`, `Removed` or `Security` as appropriate.
- Write concise entries that explain the effect for users or contributors. Distinguish implemented behavior, local verification and independent acceptance. Never invent release dates, versions, benchmark results, passing tests or compatibility claims.
- Omit trivial formatting and intermediate steps unless they materially affect maintainability. Keep unreleased changes under `[Unreleased]` until a release is authorized.
- Before concluding the task, check whether the changelog needs an update and make it when warranted. Rewrite historical entries only to correct factual errors. Preserve existing content when tightening the prose.
---
## Public documentation and terminology
## 3. Native Apple Silicon Host & Runtime Isolation
- Write public documentation so readers can understand it without earlier agent conversations. Keep `README.md` and `docs/README.md` accessible to new contributors.
- Introduce descriptive names before internal identifiers such as X1, G10 or P2-04. Define specialist abbreviations on first meaningful use.
- Write changelog entries around actual behavior and its effect on users or contributors. Distinguish implementation, synthetic demonstrations, independent verification and real Xbox execution.
- Review terminology whenever editing documentation. Use concise, precise explanations and preserve evidence scope.
- Update `docs/README.md` whenever you add, remove, rename or substantially reorganize documentation.
- **ARM64 host binaries:** BetterXen's own host executables (`bx-cli`, etc.) must be native `arm64`-only (`aarch64-apple-darwin`); verify with `file` and `lipo -archs`. Only guest shim DLLs under `shims/` and conformance EXEs under `tests/conformance/` target x86-64 Windows PE32+.
- **Apple Silicon generations:** Support M1 through M5 and future generations via runtime capability detection; do not hardcode single-generation GPU or RAM assumptions (default to Lockhart memory limits on 16 GiB hosts).
- **Child environment isolation:** `bx-cli run` must isolate the child CrossOver/Wine process (`env_clear()` + minimal explicit allowlist; `--inherit-env` opt-in only) so host credentials and stray variables never leak into guest processes.
- **Build concurrency:** Use at most four Cargo/CMake build jobs across simultaneous local builds, with one GPU workload at a time.
## Subagent reasoning
---
**Every spawned subagent must use LOW reasoning effort.** Explicitly select LOW and verify the resolved configuration. Never use Medium, High or Extra High. If LOW cannot be guaranteed, proceed without that subagent. The lead agent may use the user-selected reasoning setting.
## 4. Dependencies, Licensing & Provenance
## Checkout commands
- Before integrating or copying any third-party code: verify the **per-file** license (not just repository metadata), confirm compatibility with `GPL-3.0-or-later` and every selected component, preserve copyright notices, record the upstream repository and exact commit/version, document modifications, and record the entry in `docs/research/upstream-registry.md` and `docs/research/component-reuse-matrix.md`. If licensing is uncertain, do not use it until resolved.
- Never bundle, modify, or redistribute proprietary components (CrossOver binaries, D3DMetal, Rosetta 2, Apple tools) unless their license explicitly allows it. Never bypass licensing or activation requirements of any dependency.
- **Provenance first:** Exclude anything derived from leaked proprietary material or unauthorized software. A project's license being GPL does not clear material it was built from or for. Projects whose stated purpose depends on leaked or unauthorized builds (including VIctory, PE-Vulkan, KyTx, AnyPS5, and similar efforts) are never adopted as code, shader, asset, or tooling sources without a recorded per-file provenance and license audit. Game-specific, asset-specific, and decryption-related code is never adopted.
- Format: `cargo fmt --all -- --check`
- Lint: `cargo clippy --workspace --all-targets -- -D warnings`
- Test: `cargo test --workspace`
- Verify the synthetic fixtures: `scripts/assemble-fixture.sh --check`
- Run native GPU correctness: `scripts/test-gpu.sh`
- Run the three RDNA-to-Metal fixtures: `scripts/demo.sh`
- Run independent CPU validation: `cargo test --locked -p xenora-semantic-review`
- Run the correctness-gated benchmark suite: `scripts/benchmark.sh` (idle machine, release, validation off)
- Run source mutation on decoder/shader/ref: `scripts/mutation.sh` (R2 owns triage)
- Check generated status tables: `python3 scripts/audit/status.py --check`.
- Check claims and dependency direction: `scripts/audit/claims.sh` and `scripts/audit/dependencies.sh`
- Fuzz one CPU-only parser at a time: `scripts/fuzz.sh <instruction_stream|fixture|reference>` (600 seconds by default).
---
Keep generated and gate logs under ignored `artifacts/`. Use at most four Cargo build jobs across two simultaneous CPU-heavy jobs, with one GPU job and one fuzz or mutation campaign at a time.
## 5. Honesty, Evidence & Independent Verification
## Ownership
- **Never fabricate verification:** Never report a test as passed unless it ran and passed on this revision. Never count a skipped test or unavailable tool as a pass. Never invent benchmark results, API names, encodings, hardware capabilities, or compatibility claims.
- **No silent fallbacks:** Do not hide errors behind silent no-ops. Every unimplemented shim export must call `BX_STUB_LOG(dll, sym)` and every unimplemented COM vtable slot must call `BX_VTABLE_STUB_LOG(iface, slot, method)` so `bx-cli trace` surfaces exact blockers. Do not weaken or delete tests to make them pass.
- **Evidence classes & hardware claims:** Classify evidence per `docs/claims.toml`. Never claim "verified on Xbox hardware" — BetterXen has no Xbox hardware access; agreement with a public specification or Apple Silicon run is not Xbox hardware verification.
- **Independence of verification:** The agent or contributor who writes a component does not independently certify it. Independent reviewers re-derive expectations from primary sources and are not told the implementer's conclusions as ground truth. The same faulty code must never produce both the expected and actual values in a test.
- **Milestone completion:** A milestone is complete only when every exit condition has recorded evidence — never from commit counts, lines of code, or isolated stubs.
Xbox and claims owns public console research. ISA owns the decoder and oracle fixtures. Compiler owns the parser, IR and MSL. Metal owns the native GPU backend. Testing owns the independent reference and fixture validation. Infrastructure owns shared Cargo configuration, policies and the CPU boundary. R1 independently audits claims and release evidence. R2 independently validates semantic expectations and mutation results.
---
## 6. Legal & Clean-Room Rules
- Use only publicly accessible documentation, publicly licensed software, and authorized synthetic workloads. Never obtain, paste, or commit leaked executables or SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, unauthorized assets or source code, or proprietary game builds and shader collections.
- **Legal boundary (`docs/legal.md`):** BetterXen does not circumvent console security or DRM and does not load encrypted or protected content. Validate technical compatibility and safety of user-provided files; do not ask for ownership receipts, accounts, or acquisition provenance as part of file loading.
- Never place restricted material, personal paths, or secrets in the repository or its Git history.
---
## 7. Claiming, Git Safety & Changelog
1. **Check before coding:** Read every comment on the issue and check open PRs. Never claim over an active claim.
2. **Claim in plain text:** Reply `Claiming — branch: track-<a..f>/<issue>-<slug>` on the issue (earliest claim wins; stale after 7 days without commits/PR).
3. **Isolate with branches or worktrees:**
```sh
git worktree add ../wt-<issue> -b track-<a..f>/<issue>-<slug> origin/main
```
4. **Link & sign off:** Put `Closes #<issue>` in the PR description and sign off every commit (`git commit -s`, DCO).
5. **Git safety:** Never commit, push, or change remote visibility without explicit user authorization. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
6. **Changelog & docs index:** Read `CHANGELOG.md` before starting and update `[Unreleased]` for every meaningful addition, change, fix, removal, or security update. Update `docs/README.md` whenever documentation is added, removed, or reorganized.
7. **Subagent reasoning:** When spawning helper subagents in automated workflows, keep subagent reasoning effort low unless the user explicitly asks otherwise.
---
## 8. Verification Commands (Run Before Every Handoff / PR)
```sh
# 1. ARM64 Rust workspace (launcher + shader-transpiler)
cargo fmt --all -- --check
cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
cargo build --locked -p bx-cli && lipo -archs target/debug/bx-cli # must print: arm64
# 2. Cross-compile all 16 x86-64 PE32+ shim DLLs + auto-discovered conformance EXEs
# (strictly verifies .edata Export Directory names, ordinals, forwarders, 0 extra exports, 0 MinGW runtime DLL deps)
scripts/build-shims.sh
# 3. Live synthetic PE32+ conformance tests inside CrossOver 26.3 + Rosetta 2
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_veh_clwb.exe
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_shim_exports.exe
target/debug/bx-cli trace /tmp/bx-test.jsonl
# 4. Repository Markdown link & hygiene check
python3 scripts/audit/docs_hygiene.py
```
+435
View File
@@ -10,7 +10,435 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Added
- Implemented the `IGameInput` v0 device-callback lifecycle (`RegisterDeviceCallback`, `StopCallback`, `UnregisterCallback`) and `SetFocusPolicy` in `shims/gameinput/gameinput.cpp` (#481). `RegisterDeviceCallback` validates `callbackFunc`, `inputKind`, `statusFilter`, and `enumerationKind` (`0..=2`), allocates unique monotonic `GameInputCallbackToken` handles under `SRWLOCK`, and supports optional null `callbackToken` output pointers; `StopCallback` marks active registrations stopped while keeping them unregisterable once via `UnregisterCallback`; `SetFocusPolicy` records focus-policy flags without stub noise. Expanded `test_audio_input.exe` to cover validation, token uniqueness, stop/unregister idempotence, and focus-policy calls.
- `dxbc-accc` now reaches Windows guests as `bx_shader_bridge.dll`, the x86-64 Windows build of the same crate (#445). It exports exactly the three `bx_shader_bridge.h` entry points and needs no MinGW runtime DLL. `shader-transpiler/crates/dxbc-accc/guest/build.sh` builds the DLL and checks its exports and imports. It also builds `check_bridge.exe`, a C guest program compiled against the frozen header, which sends a real DXC SM 6.6 blob and eight synthetic containers (DXIL with and without trailing bytes, `ACCC`/`FSPX` v1 and v0, dual, legacy `SHEX`, malformed) through the DLL loaded by full path. It checks classification (exact chunk sizes, root signature flag, header digest, declared size), prepare (only the declared container is copied), free, and prints a DXIL vs. `ACCC` count. The build script always uses `<repo>/target` and rustup's toolchain, and checks the whole Export Address Table and an import allowlist. On one Apple M5 Pro with CrossOver 26.3, in a prefix and a D3DMetal bottle, it reported `dxil=3 accc_only=2 dual=1 legacy=1 invalid=2` and passed. Synthetic containers only. Staging the DLL in `build-shims`, an `abi/defs` export list, and the `d3d12_xs` PSO hook (#466) are separate changes.
- `xgameruntime.dll!QueryApiImpl` now serves offline `XGameSave` and `XPackage` as COM `IUnknown` objects under BetterXen synthetic keys (#468, not yet closed). A title linked against Microsoft's `xgameruntime.lib` does not request these keys. Every synthetic key and COM slot order now lives in `shims/xgameruntime/synthetic_keys.h`, the single place to find or replace them. Signatures, structure layouts, `E_GS_*` values and container-name rules follow the public Microsoft Learn reference.
- **XGameSave:** provider init, containers, updates, blob writes, submit and read (both asynchronous), enumeration and the close calls. Saves are separated by SCID: each container is one file under `C:\bx_pls\<hash>\saves\<SCID hash>\`, replaced atomically on submit. A named mutex per SCID directory serializes access across threads and processes. Damaged files (truncated, trailing bytes, duplicate or NUL-bearing names) read as `ERROR_FILE_CORRUPT`, and enumeration skips them and unreadable files with a log line. Offline choices where the reference is silent (16 MiB including blob names, 256-byte blob names, no sync, retry after a failed submit) are listed in `game_save.cpp`.
- **XPackage:** the running executable's directory stands in for the installed package: a stable `BXPKG…` identifier, `XPackageKind::Game` for it, and `XPackageMount` / mount-path queries that return that directory.
- **Lifetimes:** the last uninitialize closes every XGameSave and XPackage handle and drops unconsumed results. Closing a provider closes its containers and their updates. Each handle type has its own value range. An operation queued before an uninitialize completes with `E_GAMERUNTIME_NOT_INITIALIZED` without running.
- **Async:** results of the new operations go through the existing XAsync engine, including `XAsyncGetResultSize`, cancellation and reuse rules. A cancel that arrives after an operation started no longer reports `E_ABORT` for work that was done. An unconsumed result is kept until its block is reused or the runtime is uninitialized.
- **Tests:** `tests/conformance/test_xgameruntime_saves/` covers both families through `QueryApiImpl`, with its own copies of the keys, slot numbers, structure layouts and storage format. It checks:
- name rules, the write and read round trip, and the size limits;
- SCID isolation and enumeration;
- crafted damaged files, a failed replace that keeps the old save, and a successful one that replaces the file;
- 64 threaded and 160 cross-process concurrent submits;
- uninitialize with pending work, stale handles and released memory, and a non-ASCII executable directory.
Each of eleven injected faults (non-atomic write, missing or per-process lock, ignored SCID, no-op close, lax parsing, uncounted names, retained results, stale work running, children kept after a provider close) makes it fail.
- **Not done:** validation against a caller linked to Microsoft's `xgameruntime.lib`, since these keys are BetterXen's own. `abi/defs/xgameruntime.def` is unchanged (49 exports).
- Added `docs/research/d3dmetal-gpu-limits.md` and `tests/conformance/test_d3dmetal_gpu_limits/` (#453). The fixture is an original D3D12 compute test that loads the host `d3d12.dll` directly, with four original HLSL kernels and committed DXC 1.9.2609 output (`shaders/compile.sh` regenerates them). It skips with exit 77 below shader model 6.6. Required checks:
- a kernel without `WaveSize` runs, and its lane indices form a permutation within each wave;
- a per-texel spin lock with acquire and release fences and a 1024-try cap emulates 64-bit add and max with no dropped update and exact values.
Everything else is printed as `OBSERVED:` lines. On one Apple M3 Pro (macOS 27.2.1, CodeWeavers Wine 11.0 built from source, D3DMetal 4.0b3), three runs gave the same outcomes, with 4/4 required checks passing each time:
- the `[WaveSize(64)]` pipeline is created but never runs;
- kernels using SM 6.6 64-bit atomics, on a typed UAV or a raw buffer, are created but never run, although the device reports support for them; a plain-store marker beside the atomics shows the skip;
- a 64-try lock cap drops 96–108 of 512 updates.
The note links only these measured items from the M2 and M3 roadmap rows. Observations reported from a commercial title are kept in a separate "not evidence" section, each with the synthetic workload that would verify it. This is a local implementer run, not on CrossOver 26.3 and not independently reproduced.
- Updated `README.md` and `docs/roadmap.md` to record Milestone M0 and Milestone M1 (`#17`, 16/16 issues) as verified complete on synthetic workloads and activate Milestone M2 (`#18`, First Rendered Frame & Shader Format Gate).
- Implemented clean-room COM `IUnknown` vtable dispatch in `xgameruntime.dll!QueryApiImpl` for the core public Microsoft PC GDK (`Microsoft.GDK.Windows 2610.0.9661`) interface families (`XAsync`/`XTaskQueue`/`XThread`, `XGameRuntimeIsFeatureAvailable`, `XSystem`, `XError`, `XPersistentLocalStorage`, `XUser`, `XStore`, `XGameUi`, `XNetworking`, `XGame`), with auto-logging `BX_VTABLE_STUB_LOG` fallback on unimplemented slots. Validated live on CrossOver 26.3 with an independently authored caller linked against Microsoft's public `xgameruntime.lib` (#456).
- `bx-cli run` now stages the shims a guest loads by system-directory search into the prefix's or bottle's `drive_c/windows/system32` before launch (#457). GDK titles load `xgameruntime.dll` with `LoadLibraryExW(..., LOAD_LIBRARY_SEARCH_SYSTEM32)`, which never searches `WINEPATH`. The bootstrap therefore reported `E_GAMERUNTIME_DLL_NOT_FOUND` before the #441 loader exports could be reached.
- **What is staged:** `xgameruntime.dll` and, found through `bx-probe`, every BetterXen shim it imports (today `bx_runtime_veh.dll`). The same restricted search applies to a DLL's own imports, so staging the runtime alone fails unless the guest happened to load the logger first.
- **How:** copies are idempotent: an identical file is left alone, a different one is replaced through a rename. `bx-cli` prints what it staged.
- **Uninitialized environments:** a bare `--prefix` without `system32` is initialized with `wineboot --init` under the same isolated environment. A bottle without one fails with a hint. Neither case is ever skipped silently.
- **Partial shim folders:** a `--shims` folder without `xgameruntime.dll` prints a notice and the run continues without staging, as it did before staging existed.
- **Supervision:** `--timeout`, SIGINT, SIGTERM and SIGHUP also cover the `wineboot --init` step, so an interrupted first run does not leave `wineserver` running.
- **Tests:** 8 unit tests cover staging and the dependency walk. `tests/conformance/test_system32_staging/` makes the `LOAD_LIBRARY_SEARCH_SYSTEM32` load and requires BetterXen's shim, from `system32`, exporting `QueryApiImpl`, and the same module for `SYSTEM32 | APPLICATION_DIR`. `--expect-missing` is the negative control for an unstaged prefix.
- **Local result:** on one Apple M3 Pro (macOS 27.2.1) with CodeWeavers Wine 11.0 built from source, so not CrossOver 26.3, and with the staging done by hand: the control passed and the unstaged run failed as expected. Staging the runtime alone still failed, which is how the dependency rule was found. Staging both passed 4/4 in two runs. `bx-cli run` itself was not run, since CrossOver is not installed on that host.
- `bx-cli run` gained `--timeout <secs>`, cleanup of the launcher process group and the selected bottle or prefix on timeout, SIGINT, SIGTERM or SIGHUP (including re-resolving managed bottles whose first launch creates a private stub), `--backend` (bottle mode only), and a printed trace summary after a run with `--log`. The bottle to stop is located through CrossOver itself, so bottles outside the default directory are covered. A normal exit does not stop the environment. Recorded a one-host observation that D3D12 swapchains stay referenced under D3DMetal (#408).
- Added `test_apiset_resolution`, a conformance fixture that statically imports the six API-set `win32_bridge` names and reports which module serves each (`--expect host|shim`), and accepted ADR 0007 recording that CrossOver 26.0 and 26.3 answer them via built-ins (`twinapi.appcore.dll` / `user32.dll`) (#437).
- Added file-mapping-backed 64 KiB and 2 MiB physical pages, contiguous and scatter aliases (including intra-span duplicate-tag aliasing), exact-span unmap validation, physical region queries (`bx_xmem_query_region`), and shared working-set accounting / combined title memory budget enforcement across heap, virtual, and physical allocations in `xmem.dll`. Synthetic `XMemAllocatePhysicalPages` / `XMemFreePhysicalPages` signatures follow Win32 AWE (`memoryapi.h`) pending a public console flag encoding (#412).
- Added Win32 bridge conformance coverage for a hidden window, message dispatch, concurrent PSM registrations, and per-event JSONL log verification. Offline PSM registration tokens are tracked without C++ exceptions using disjoint family tags so cross-family unregisters log `foreign_token` and retired or invalid tokens log `unknown_token` (#410).
- `xgameruntime.dll` exports BetterXen-defined `InitializeApiImpl`, `InitializeApiImplEx`, `InitializeApiImplEx2`, `UninitializeApiImpl`, `QueryApiImpl`, and `XErrorReport` so a static loader can resolve them. No public prototype for those six names was found. The documented `XGameRuntimeInitialize`, `XGameRuntimeUninitialize`, `XGameRuntimeInitializeWithOptions`, and `XGameRuntimeOptions` behavior is what the shared refcount follows. `QueryApiImpl` rejects a missing output or id, clears the output pointer on failure, dispatches the offline families this DLL already implements, and logs any other class through `BX_STUB_LOG` before `E_NOINTERFACE`. `XErrorReport` is `void` and writes only valid UTF-8, replacing an invalid byte with `\u00XX` and truncating on a character boundary. The DLL has 49 exports. This is not an Xbox hardware result (#439).
- Implemented synthetic APU heap mappings, per-connection APU and DSP queues, and the GameInput ordinal 1 COM stub. Added an audio/input conformance executable covering all four shim DLLs (#419).
- Added structured unhandled exception logging with module-relative addresses and x64 registers, and expanded the CLWB conformance test to require six traps across ModRM, SIB, REX and RIP-relative operands (#409).
- Enforced the configured title memory cap for default heap allocations and virtual commits in `xmem.dll`. Added working-set accounting and a synthetic fixture for alignment, commit overlap, decommit, release, and memory transfer (#411).
- Added a BetterXen-only DirectStorage conformance interface for asynchronous uncompressed file and memory transfers, status arrays, and completion events in `XCRDAPI.dll` (#413).
- Implemented offline `xgameruntime.dll` task queues and async completion, local user handles, synthetic game-license queries, console identity, and bottle-local storage (#418). Added a synthetic conformance executable for Lockhart and Anaconda launches. Only the marked conformance title receives an active synthetic SKU. The build also produces an unmarked control with the same executable name. Queue shutdown delivers accepted callbacks, and bottle-local storage is keyed by executable path.
- `xg_xs.dll` computes linear 2D layouts for `R8G8B8A8` and BC1 through BC7 (`XGCreateTextureComputer`, `XGSuggestSwizzleMode`, and COM `IXGTextureAddressComputer`). Row pitch uses the public D3D12 256-byte alignment and each subresource is placed on the public 512-byte alignment. `GetResourceLayout` reports that aligned allocation span in `total_bytes` (512 for a 1x1 RGBA8 texture) and a separate D3D12-style `copy_end` on each footprint (4 for that same texture). Sizes are overflow-checked, null pointers return `E_POINTER`, and copies stay inside the caller buffers. `SW_64KB_S`, `SW_64KB_D`, and `SW_64KB_R` return `E_NOTIMPL` and write no address. Synthetic `test_xg_xs.exe` checks hand-computed mip offsets, alignment, refcounts, and a byte-identical copy round trip. This is not an Xbox hardware result (#415).
- `d3dmetal-harness` (`bx-d3dmetal-harness`) is an opt-in harness that runs a user-supplied `D3DMetal.framework` outside CrossOver/Wine through `utmapp/d3dmetal-native` (MIT, `af1ee17`), so D3D12 faults can be attributed to D3DMetal or to Wine. D3DMetal is x86_64-only, so an x86_64 probe (`probe/`, built separately with `build-probe.sh`) hosts it under Rosetta 2. The arm64 harness finds the framework (`--framework`, then `$D3DMETAL_FRAMEWORK_PATH`, then CrossOver's copy) and checks both binaries' Mach-O architectures. It runs the probe with a cleared environment and a timeout, then judges the readback against values it computes itself. It reports SKIP (exit 77) only when no framework exists. An explicit path that does not resolve, a framework that fails to initialize, device removal, and probe output held open past the timeout are failures. The probe runs an original SM 6.6 compute kernel compiled with DXC 1.9.2609 and fills the output buffer with a sentinel first, so "kernel did not run" is told apart from "wrong values". On one Apple M5 Pro (macOS 27.2.1) with CrossOver 26.3's D3DMetal 3.0, all 16 D3D12 steps succeeded and 256/256 words matched. This is a local implementer run, not independently reproduced. The live test is `#[ignore]`d and fails when its prerequisites are missing. d3dmetal-native, directx-native and DXC are recorded per file in the upstream registry and reuse matrix. d3dmetal-native's D3DMetal binary patcher is not used (#417).
- `dxbc-accc` parses a synthetic FSPX section table inside DXBC `ACCC` chunks (section descriptors, section 1 stage configuration using the `bx_shader_stage_t` values, and section 6 RDNA 2 code bounds) and returns a parse error for truncated or out-of-range input instead of panicking. A table may declare at most 64 sections. A `DXIL` chunk is accepted only when it is a `DxilProgramHeader` from the public DirectXShaderCompiler layout. It exports `bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, and `bx_shader_free_buffer` with the layouts in `abi/include/bx_shader_bridge.h`. `bx_shader_inspect` fills that struct without logging. `bx_shader_prepare_for_d3dmetal` copies the `container_size` prefix when that DXIL header is present, including when the container also has a malformed FSPX table. An empty `DXIL` chunk is rejected. ACCC-only input returns `BX_SHADER_ERR_UNSUPPORTED` and writes one stderr inspection line. The first FSPX table that declares a stage supplies it. A failed stderr write does not panic. RDNA 2 bytes are not translated to DXIL. The section layout is synthetic and is not a console container specification or an Xbox hardware result (#416).
- Added a visual `Progress Tracker` section to `README.md` with an M0–M6 Mermaid milestone pipeline, a Track A–F live status board (`🟩`/`🟨`/`⬜`), and direct GitHub label links for open M1 issues.
- Added a required `Zen` field to `.github/ISSUE_TEMPLATE/track-handoff.yml` so every track handoff issue states its core purpose briefly in plain English up front.
- Added Section 0 (`First-Time Contributor Onboarding`) to `AGENTS.md` (`CLAUDE.md` symlink) giving coding agents a turnkey step-by-step onboarding flow (preflight, `bx-cli doctor`, unclaimed `status: ready` issue discovery, claiming, scoped implementation, local verification including hosts without CrossOver, DCO commit, and PR CI watching).
- Overhauled the repository into a clean 6-track parallel hybrid workspace (Milestone M0) designed for 5–8+ concurrent contributors and coding agents: added frozen cross-DLL ABI headers and canonical `.def` export tables (`abi/`), native ARM64 Rust workspace (`launcher/crates/{bx-cli,bx-probe,bx-telemetry}` with `env_clear()` child environment isolation, and `shader-transpiler/crates/dxbc-accc`), CMake + `mingw-w64` superbuild (`shims/`, `scripts/build-shims.sh`) producing 16 standalone x86-64 PE32+ shim DLLs (`bx_runtime_veh.dll` with working `clwb` VEH trap and JSONL logger, `xmem.dll`, `XCRDAPI.dll`, `d3d12_xs.dll`, `xg_xs.dll`, `xgameruntime.dll`, `GameInput.dll`, `AcpHal.dll`, `xapu.dll`, `chad.dll`, and PSM/ntuser forwarders) with strict PE Export Directory verification (exact names, ordinals, forwarders, zero extra exports, zero dynamic MinGW runtime dependencies), auto-discovered synthetic PE32+ conformance tests (`tests/conformance/`), `.github/workflows/hybrid-ci.yml`, `.github/ISSUE_TEMPLATE/track-handoff.yml`, `docs/adr/0006-retire-in-tree-native-workspace.md`, `docs/architecture/parallel-tracks.md`, and `docs/issues/wave-1-backlog.md`. Unified `docs/roadmap.md`, `CONTRIBUTING.md`, `AGENTS.md`, `README.md`, and `.github/CODEOWNERS` (retaining global `* @MacosPorters/maintainers` fallback and full provenance/independent-verification rules). Verified locally on Apple M5 (macOS 27.2.1, CrossOver 26.3, Rosetta 2) with all Rust checks, strict 16-DLL export verification, and live `test_veh_clwb.exe` + `test_shim_exports.exe` smoke tests passing.
- Documented the original Windows workload set and Phase 1 hybrid measurement protocol (#353), including receipt-field sources, percentile definitions, negative controls and independent reproduction requirements. The protocol identifies the unmerged runner candidate and its missing raw traces and measurements; it adds no execution or compatibility claim.
- Added the upstream research registry and component reuse matrix (`docs/research/`), a public-documentation review (evidence class D, nothing executed) of CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, FEX, VIctory, VIctory-macOS and PortWatch. VIctory-family projects are excluded from reuse on provenance grounds. The GitHub project board is not yet configured because the token lacks the `project` scope (#346).
- Added hybrid research records: `docs/research/hybrid-backlog-research-2026-11-25.md` (findings and registry candidates, from search summaries) and `docs/research/primary-source-verification-2026-11-25.md` (re-check against CodeWeavers, Apple, DXMT and Wine primary pages). It confirms CrossOver's backend list, finds no public documentation of `CX_GRAPHICS_BACKEND`, and records that two Apple notices on Rosetta's end disagree; D3DMetal's license text and CrossOver's Rosetta and ARM64 plans remain unverified. Eleven issues created from the research were reviewed the same day: #364 and #365 stay in Phase 1, the others are parked and recorded under "Parked ideas" in the roadmap. Rust 1.100.0 (already installed) is the required toolchain; the default `stable` was 1.94.1. Planning only; nothing was installed or run.
- Added `docs/research/crossover-licensing.md`, a per-component license and redistribution record for the hybrid direction: CrossOver itself, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, Apple's Game Porting Toolkit repository, D3DMetal and Rosetta 2, each with the exact text read or the missing document named, plus an entry in `docs/licenses.md` (#354). Nothing is bundled or redistributed; the D3DMetal text (third-party copy, not confirmed against Apple's) and Rosetta 2 terms remain unverified, and CrossOver 26.3.0's FOSS inventory is unknown. Research only; no code or dependency change.
- Added File > Open Executable… with Command-O to the app (#252). It opens the focused window's read-only file importer, the same one as that window's button, and is disabled when no window can present it; each window keeps its own importer, so with several windows only the focused one shows the picker. The chosen file goes through the same inspection path as the button, drag and drop and Finder Open With; nothing is executed. A file-importer failure is now shown in red with the system's description instead of being ignored, a cancelled picker shows nothing, and the message clears on the next selection. `BetterXen --smoke-import-result`, run by `scripts/build-app.sh`, checks cancellation, a shown failure and its clearing; it fails on the previous importer handling. Checked locally on Apple Silicon in the running app (Command-O and the menu item open the picker, cancel shows no error, a second Command-O opens it again, with two windows only the focused one presents it, and with every window closed the menu item is disabled); not yet independently reviewed.
- Added `docs/research/texture-formats.md`, an inventory of the texture formats and layouts BetterXen handles (#260). For BC1–BC7, RGBA8 and Depth32Float it separates container recognition, CPU decoding, layout conversion, native Metal upload and readback, translated sampling, the host-side D3D12-shaped API (called from Rust, not wired to guest imports) and guest reachability through imported services, and links each cell's implementing files and tests and each format's exact public specification sections, including the packed BC footprints from #241. It cross-references #208 and #209 instead of opening duplicate tasks, lists console layouts, console descriptors and asset or audio containers as unknowns, and ranks three proposed follow-ups with fixture recipes and owners. Research only; no implementation changed.
- Rewrote the README around the six development phases and the first-launchable-application target (#311), with colour-coded Mermaid diagrams (system flow, milestone roadmap, CPU, runtime-service and shader-form charts built from the generated registries), badges, a repository overview, a contributing section and corrected texture-sampling wording. The older X1–X25 capability map is kept in a collapsible section. The diagrams were not render-tested locally.
- Added a fast "Repository hygiene" check (`.github/workflows/hygiene.yml`, `scripts/audit/docs_hygiene.py`). It runs on Ubuntu without a Rust toolchain or network access and fails only on merge-conflict markers, broken relative Markdown links and invalid workflow YAML in tracked files. A separate advisory step warns, without failing, when source or script changes have no changelog entry. A local run over the 626 tracked files found no problems, and planted failures of each kind were caught; it has not yet run on GitHub.
- Documented the proposed guest AVX/AVX2 state and decoding contract and specified an original integer fixture with known results and fault controls (#299).
- Implemented `D3D12XboxCreateDevice` in `d3d12_xs.dll` (#414, M1-C1): it creates a device through the host `d3d12.dll` (`D3D12CreateDevice`) and returns an auto-logging COM proxy. Proxied are `ID3D12Device` through `ID3D12Device10`, `ID3D12CommandQueue`, `ID3D12CommandAllocator` and `ID3D12GraphicsCommandList` through `7`, which is as far as the mingw-w64 14.0.0 `<d3d12.h>` declares; `ID3D12Device11` and command lists `8`–`10` named in the issue are not proxied. A proxy answers only the interface levels its host object implements, hands child objects back as proxies, translates proxies passed back in (command-list creation and reset, `ExecuteCommandLists`, bundles, residency calls), and keeps `GetDevice` on the proxy device. Pass-through methods are generated by `shims/d3d12_xs/tools/gen_proxy.py` from the toolchain header's method signatures. `CreateGraphicsPipelineState` and `CreateComputePipelineState` log each shader stage's size, magic and DXBC chunk FourCCs, and reject malformed or shaderless DXBC containers (`E_INVALIDARG`) before forwarding so they cannot crash D3DMetal 3.0; the stream form logs only its size. An interface level the host lacks logs through `BX_VTABLE_STUB_LOG` and returns `E_NOTIMPL`, as do 32 padded slots placed after each public vtable; console-only method names and the creation-parameter layout are not defined in `abi/`, so the parameter block is not interpreted and no console-only interface is implemented. With `BX_TRACE_D3D=1` every proxied call is logged. Interfaces the proxy does not model are served by the host object unproxied and logged as `qi_unproxied`. Added `tests/conformance/test_d3d12_xs/` (device, queue, allocator, list, fence-confirmed execution, reset, empty root signature round trip, rejected shaderless container with its log record). Run locally on an Apple M5 Pro (macOS 27.0, Rosetta 2) under CrossOver Preview build 20261006 by invoking its Wine loader directly with the environment `bx-cli run` sets: 40 checks passed, 0 skipped; the host device reported `ID3D12Device9` as its highest interface. Two deliberate breakages of the shim (no command-list translation, host device returned from `GetDevice`) made the test fail. Not run through `bx-cli run`, not on CrossOver 26.3, and the Direct3D backend behind that Wine build's `d3d12.dll` was not identified, so nothing here is a D3DMetal result.
- Added `tests/conformance/test_integration_boot/` (#420, M1-F1): an original synthetic x86-64 PE32+ boot fixture whose import directory names all 16 shim DLLs and which walks a startup-shaped sequence (AVX2 + FMA, three `clwb` forms, `xmem.dll`, `xgameruntime.dll`, PSM notifications, a hidden window pumped through the `ntuser` forwarders, `XCRDAPI.dll`, `AcpHal.dll`, `xapu.dll`, `chad.dll`, `GameInput.dll` ordinal 1, `xg_xs.dll`, `d3d12_xs.dll`) followed by reverse-order shutdown. Each of 21 stages prints a JSON checkpoint and a `bx_log_emit` record with status `pass`, `pending` or `fail`; `pending` marks an M0 stub's `E_NOTIMPL`/null answer or a host-answered import, is never counted as a pass, and becomes a failure with `--strict` or `BX_INTEGRATION_STRICT=1`. `scripts/build-shims.sh` builds it and still verifies all 16 DLLs. Run locally on an Apple M5 Pro (macOS 27.0, Rosetta 2) under CrossOver Preview build 20261006 by invoking its Wine loader directly with the same isolated environment `bx-cli run` sets: 13 pass, 8 pending, 0 fail, exit 0; `--strict` exits 1. It was not run through `bx-cli run` (the CLI only looks for `/Applications/CrossOver.app`) and not on CrossOver 26.3. That run found that this Wine build answers the two `api-ms-win-core-psm-appnotify-*` and four `ext-ms-win-rtcore-ntuser-*` import names itself instead of loading the BetterXen shims: the window stage still passes through `user32`, while PSM registration returns `ERROR_CALL_NOT_IMPLEMENTED` (reported as pending). The device, DirectStorage, AcpHal, GameInput and texture-computer stages are pending on their M0 stubs, and `D3D12XboxCreateDevice` and `XGCreateTextureComputer` are only probed with a null descriptor because no descriptor layout is defined in `abi/`.
### Removed
- Retired the paused in-tree native-first workspace (`crates/`, `app/`, `benchmarks/`, `experiments/`, `fixtures/`, `fuzz/`, `licenses/`, legacy native scripts, legacy `.github/workflows/ci.yml`, `agent_queue`, legacy `tests/*` outside `tests/conformance/`, and native-only docs) from `main` per ADR 0006; the full native-first history remains permanently preserved at Git tag `native-first-final`.
- Removed the "Agent PR checks" workflow (`.github/workflows/agent-pr-checks.yml`), its section in `docs/coordination/agent-tasks.md` and the four workflow tests in `tests/agent_queue/test_workflows_cli.py` that only exercised it. Pull requests are no longer checked for `Closes #N`, task file patterns or `/verified` comments; the claims workflow and its tests are unchanged. The agent queue Python tests pass locally (85 tests).
- Removed the "PR template" check (`.github/workflows/pr-template.yml`, `scripts/pr_template_check.py` and its tests) and its CI test step. Also removed `.github/PULL_REQUEST_TEMPLATE.md`. Pull request descriptions are no longer validated or pre-filled; CONTRIBUTING.md still asks for the same information and the claim-first rule still applies.
### Changed
- Replaced the native-first development plan with a CrossOver-based hybrid roadmap (`docs/roadmap.md`: five provisional phases, only Phase 1 active; the earlier H0 to H7 breakdown is archived) and an accepted-direction ADR 0005. No hybrid component exists yet and no Xbox title is shown to run; this is planning and research scheduling only, and no phase is verified complete.
- Rewrote the engineering rules in `AGENTS.md` (`CLAUDE.md` is a symlink to it) to permit CrossOver, Wine-based infrastructure, Rosetta 2 and D3DMetal subject to licensing, while keeping the honesty, independent-verification, provenance and clean-room rules and adding dependency and reuse rules. Resolves #345.
- Native work is preserved and paused: tag `native-first-final` marks the last `main` commit before this change, `docs/research/native-roadmap.md`, and archived native-first plan and milestones under `docs/archive/`. GitHub backlog: all native issues except four with assigned contributors and open pull requests were closed as not planned and indexed in `docs/research/native-issue-archive.md`; future-phase issues were parked in the roadmap; only the Phase 1 milestone is open.
- Replaced the issue templates with hybrid task, bug, research, performance, validation and documentation forms and added a pull request template. Fixed invalid YAML in the agent-task template. README, CONTRIBUTING and the docs index now describe the hybrid direction.
- Replaced our own references to a specific commercial game title (README non-affiliation line, research and integration notes, ignored diagnostics folder names) with generic "commercial title" wording. The ignored folder names are now `diagnostics/title-candidate-*` and `diagnostics/title-check`. Third-party repository names, URLs and code-span paths in research notes are unchanged so their provenance stays accurate. Our own prose references to the upstream project formerly named in the research notes now read "PE-Vulkan project". Added the PortWatch native-macOS research notes. No behavior change.
- TLS setup now copies templates from 64 KiB up to 1 MiB straight into the zeroed thread data block, after checking that every template byte is readable, instead of staging them in a second buffer (#111). The pointer array and data block layout, the TLS index write and the error for an unreadable template are unchanged, and nothing is mapped when the template cannot be read. On an Apple M2 Pro, median setup time for original synthetic templates over 31 interleaved samples fell by 21.7 % at 64 KiB, 19.0 % at 256 KiB and 14.2 % at 768 KiB. Smaller and larger templates keep the single staged read and showed no change beyond run-to-run variation.
- Removed the contributor avatar section from the README.
- Added `.github/CODEOWNERS` so pull requests request review from the `MacosPorters/maintainers` team. With the `main` branch rule that requires code-owner review, a maintainer must approve each change before it merges.
- Repaired destination issue links in 20 migrated PR descriptions while retaining the imported text, attribution and contributor certifications. Template and review requirements remain in place.
- Moved 163 unused migration PR refs from branches to verified archive tags, retaining the 22 open-PR branches. Historical refs no longer clutter the branch list or produce recent-push PR prompts.
- Renamed the project branding and native app and primary CLI package/binary to BetterXen (`betterxen`), and updated active repository links to `MacosPorters/betterxen`. Legacy `xenora-*` library packages and synthetic guest ABI names remain for compatibility. Upstream licenses, notices and historical evidence are retained.
- Guest `strlen`, `strnlen`, `wcslen` and `wcsnlen` scan memory in 256-unit blocks, falling back to single units at mapping boundaries so faults still report the first inaccessible unit. On Apple M2 Pro the 63-byte `strlen` workload went from 1,990 ns to 223 ns per call (median of 10 batches, on a machine that was not idle).
- The native ARM64 DBT now runs the 32- and 64-bit register and immediate forms of ADC and SBB itself instead of falling back to the shared interpreter (#195). The guest CF is moved into the host carry before ADCS or SBCS, inverted for SBB because SBCS subtracts NOT C while SBB subtracts CF. Memory forms and 8- and 16-bit forms still use the shared semantics. `tests/x86_carry_chain.rs` runs 256-bit add and subtract chains of 64- and 32-bit limbs, in one block and split one block per limb, against widening `u128`/`i128` reference arithmetic in both engines, plus immediate 128-bit increments and decrements and the `sbb reg, reg` carry mask. Locally verified on Apple M5 only.
- Removed the temporary region-list allocation from each instruction-byte fetch while preserving lookup order, execute-permission checks and error behavior (part of #104).
- Release and bench builds now use fat link-time optimization with one codegen unit (#116). On a local Apple M5, `dbt_bench` medians over five alternating runs dropped by about 6 % for the interpreter (903 to 845 µs) and about 9 % for cold DBT (1.155 to 1.046 ms), while warm DBT (cache hits) became about 2 % slower (21.83-22.08 to 22.29-22.54 µs over four further runs). The `xenora` binary shrank from 2.73 to 2.11 MB. A clean release build of the workspace takes about 14 s instead of 6 s. Debug and test builds are unchanged.
- The ARM64 assembler uses one 32-bit `MOVN` for zero-extended constants such as `0xFFFF1234` that previously took two wide moves (#89). On an Apple M1 Pro, a synthetic workload with 4,096 affected loads emitted 163,920 native bytes, down from 180,304 (9.1%). The native tests verify the encoding and the full 64-bit register result.
- The ARM64 assembler loads 64-bit constants with the fewest MOVZ or MOVN plus MOVK instructions (#92). It no longer emits MOVK for zero halfwords and starts from MOVN when more halfwords are 0xFFFF than zero, so small negative values take one instruction instead of four. On Apple M5 the DBT benchmark emits 245,168 instead of 290,184 native bytes for its 626 blocks (-15.5%) and the 1,048 integer fixture instructions 128,724 instead of 145,732 (-11.7%); benchmark run times did not change measurably. New tests check the sequences against LLVM encodings and execute 1,056 of them on the host through the JIT.
- Resolve the tiled BC1 mip and array layer once per linearization and copy contiguous block runs within each tile row. Partial edge blocks are retained and padding slots are skipped. Closes #349.
- Changed the default report folder of `xenora probe` and `xenora imports sync` to `diagnostics/probe`, which Git ignores (#364). Anyone relying on the earlier default has to pass `--report`.
- Relocation reports now build their type histogram once per image, avoiding a tree lookup for every entry. Target checks and fixup order are unchanged; synthetic regressions and an opt-in relocation timing test cover the change (#109).
- Moved the six supported gfx1030 SOPP compute control forms into the semantic registry, preserving instruction decoding and shader lowering. Part of #215.
- Moved gfx1030 `s_mov_b32` (SOP1) into the semantic registry, preserving its existing decode domain and shader output. The move operand rule retains explicit VCC and EXEC half destinations. Part of #215.
- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215.
- Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches.
- Reuse up to 16 native Metal compute pipelines per context for repeated shader source and entry points. Pending dispatches retain their pipelines through completion, including after eviction. Dispatch profiles report zero library and pipeline setup time when a cached pipeline is reused. Closes #132.
- Avoided resolver allocations for permitted guest data reads and writes contained in one mapping, preserving checked fallback for split spans and faults (#105).
- 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
- `bx-cli run` system32 shim staging (#474). Staging now records what it wrote in a `.bx-staged` manifest in the prefix's `system32` (one SHA-256 per file) and replaces only regular files that are listed there and still have the recorded hash. Any other same-named entry the bottle already had, including a symbolic link that points nowhere, or one changed since it was staged, is never modified or deleted: staging stops with an error naming it before anything is written. New files are installed without replacing anything, so an entry that appears after the checks is protected too. All temporary copies are written before the first file is put in place, and each installed file is recorded in the manifest before the next one is touched, so a failure part-way leaves the earlier files owned rather than orphaned. A byte-identical existing file is left alone and not claimed. For a named bottle, the prefix is resolved again after the run; if CrossOver launched the bottle elsewhere, the run fails only when the staged shims cannot be found with the same contents in that prefix's `system32` (a private stub of a managed bottle that links back to the managed prefix is accepted and reported). When prefix initialization uses the whole `--timeout`, the guest is no longer started and the message names initialization (exit 124). Copies staged by an earlier `bx-cli` have no manifest entry and are treated as the bottle's own, so after upgrading a changed shim needs that stale copy removed by hand once. Staged files are still not removed after a run. Covered by 15 new unit tests (32 `bx-cli` tests pass); twelve deliberate breakages each failed a test. A reviewer ran the first revision on CrossOver 26.3 with a managed-only bottle and found the false failure, dangling-link and partial-failure cases fixed here; this revision has not itself been run under CrossOver.
- Fixed `bx-cli run --bottle` losing the shim DLL overrides: CrossOver's `bin/wine` discards `WINEDLLOVERRIDES`, so they are now passed with `--dll` (found by jelly013) (#408).
- `test_integration_boot.exe` now creates a real texture address computer, checks a two-mip layout against hand-computed values and requires the final `Release` to return 0, instead of reporting that stage as pending after a null-descriptor probe (#446).
- `bx-cli trace` reports the highest sampled CLWB total as a lower bound, labels counterless CLWB records as samples, and lists unhandled exceptions with their code, module base, RVA, and RIP (#438).
- Fixed the app's executable inspector so a late result from an earlier selection can no longer replace a newer one (#251). Each selection from the file picker, drag and drop or Finder Open With now takes a request number, and only the latest request may publish its report and status or clear the busy state. The previous report is cleared when a new file is chosen, and a failed inspection of the latest file is shown in red above its report. The read itself is unchanged: size checked before reading, balanced security-scoped access, nothing executed. `BetterXen --smoke-inspection-order`, run by `scripts/build-app.sh`, drives the model with an injected reader that blocks until the check releases each file, so the check (not timing) decides which read finishes first; it checks a stale success, a stale failure and a busy state held for the newer request, and all four checks fail without the change. Checked locally on Apple Silicon; not yet independently reviewed.
- Startup reports now reject existing destinations before guest execution, surface journal write failures, and preserve late errors alongside signal termination.
- 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
- Added opt-in `betterxen run --startup-report <path>` JSON diagnostics with the last observed startup stage, fixture verification outcome and preserved failure or termination detail (#255).
- Added a `Native app build and smoke` CI job (#248). On the same native `macos-26` runner image and pinned Rust toolchain as the Rust checks, it runs `scripts/build-app.sh`, which builds the locked C ABI library and the Swift app together, bundles and ad-hoc signs `BetterXen.app`, and runs its `--smoke` check, so a Swift compile, link or smoke failure is designed to fail CI (implemented and verified locally; not yet shown on a CI run). `scripts/build-app.sh` also prints `file` and a single `otool -L` listing for the executable, fails if that listing fails or is empty, and fails if the executable links any library outside `/System/Library/` and `/usr/lib/`, naming bundle-relative (`@rpath`, `@executable_path`, `@loader_path`) entries separately (checked locally against stubbed failing, empty, bundle-relative and non-system listings). The job is an app build and smoke result; it runs no Metal fixture and is not GPU verification.
- Added a CPU and loader coverage map (#154) with decoder inventory, native and shared execution paths, and test counts from a pinned Apple M5 run.
- 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.
- Added a BetterXen development phase plan based on current source, pending PRs and existing acceptance records, linked from both contributor entry points. It separates baseline reconciliation, hosted C execution, guest threading, translated rendering, application integration and measured optimization; no new runtime or compatibility acceptance is claimed.
- Added `tests/runtime_clock.rs`, which reads the performance counter, its frequency, both tick counts, the unbiased interrupt time and the system time from one injected clock and checks that they report the same elapsed time in their own units, after a host advance and after a guest `Sleep`, and that none of them decreases up to and past the end of the clock (#204). Expected values are worked out by hand from the documented units. Timed waits still return without consuming clock time.
- Added opt-in shader IR constant folding (`CompileOptions::fold_constants` / `compile_with`) for pure vector unary and binary ops whose operands are already constants (#141). Floating-point ops still use the exact positive-normal rules; loads, stores, lane masks, merges and branches are never folded. Default `compile` keeps the historical IR. Covered by hand-computed known-answer compiler tests (shifts by 32/33, ashr, min_i32 vs min_u32, mul_hi_i32_i24, ffbh_i32, exact float fold, load-derived float non-fold, and verify rejection of inexact constant float add) with a fold-on versus fold-off check, plus an MSL template drift check over every foldable op.
- 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 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).
- Added the VOP3A (`_e64`) encodings of eleven gfx1030 VOP2 integer forms (`v_mul_{i32_i24,hi_i32_i24,u32_u24,hi_u32_u24}`, `v_{min,max}_{i32,u32}`, `v_xnor_b32`, `v_sub_nc_u32`, `v_subrev_nc_u32`) and of the sixteen Wave32 integer compares (explicit SGPR mask destination, `s_cbranch_vccz` through `vcc_lo`, a translation error for reads of runtime-only SGPR results) as semantic-registry encoding variants, with VGPR sources only. New fixtures `vop3-integer` and `vop3-compare` with IR and MSL goldens, and an independent guide-derived oracle (`tests/validation/tests/vop3_{integer,compare}.rs`) that agrees on both reference interpreters and on native Metal. Part of #215.
- Added `scripts/cpu-tests.sh`, which lists the default-feature workspace test targets and runs
deterministic shards of them (`--shard K/N`), with `--check N` showing every target lands in
exactly one shard. It does not replace `cargo test --locked --workspace` or
`scripts/test-gpu.sh`. `docs/testing/cpu-coverage.md` records local CPU gate timings on one
Apple M4 host (about 40 s wall time; one loader target takes about 19 s) and shows that the 2- and
3-shard unions match the full gate's 681 passed and 34 ignored tests (#159).
- Added guest texture binding through D3D12-style descriptor tables (#303): shader-visible CBV_SRV_UAV and sampler heaps, `CreateShaderResourceView` for one-level RGBA8 and BC1 2D textures, a point/clamp `CreateSampler`, a root signature with one pixel-stage SRV table and one sampler table, and `SetDescriptorHeaps`/`SetGraphicsRootDescriptorTable` in `crates/loader/src/graphics.rs`, plus `NativeCompute::render_rgba8_sampled_bc1`. Verified locally on an Apple M5 Pro under Metal validation: a guest draw with the translated `image_sample_lz` pixel stage matches the software reference and hand-derived images on 16 of 16 pixels for two RGBA8 textures and 64 of 64 for an 8×8 BC1 texture. A wrong descriptor slot changes the image, off-centre and out-of-range coordinates point-sample with clamping, and a rejected binding, draw shape or resource state never reaches the backend. The software reference samples BC1 with the spec-exact decoder, while Apple's hardware rounds BC1's interpolated palette entries differently (171/84 against 170/85), so the BC1 fixtures use only endpoint colours. Not yet reachable from guest imports. Not yet independently accepted.
- Added MOVNTI, the SSE2 non-temporal store of a 32- or 64-bit general register to memory (part of #125). Both engines used to stop on it with an illegal-instruction exit. It is an ordinary store, as the other non-temporal stores already are; the register form and the 66 prefix stay rejected, and a destination that cannot be written faults without changing state. The SDM-derived case `movdqa_movaps_aligned_store_and_load` in `cpu_known_answers.rs`, which ends in a MOVNTI, moved from refused to verified, and `tests/x86/integer.txt` gains four assembled instructions checked by the text-only reference in `x86_integer.rs`. MASKMOVDQU stays rejected and SSE2 stays unreported by CPUID. Not compared with x86 hardware; awaiting independent review.
- Added MFENCE, LFENCE and SFENCE and documented the ordering of guest memory accesses (part of #199). Both engines used to stop on a fence with an illegal-instruction exit. Each engine runs one guest instruction at a time on one host thread and completes its loads and stores before the next, so accesses are already totally ordered and the fences change nothing; `docs/cpu/instruction-registry.md` states this and that it holds only while guest threads do not run on several host threads. Five single-thread cases in `cpu_known_answers.rs` and three assembled fixtures cover them, and the memory forms that share the opcode stay rejected. SSE2 is still not reported by CPUID because other SSE2 instructions are rejected; the refused SSE2 instruction that `cpu_features.rs` holds is now MASKMOVDQU. No multi-thread behaviour is established, and nothing was compared with x86 hardware; awaiting independent review.
- Added the accumulator short form of XCHG, opcodes 91 to 97 and 90 with REX.B, at 16, 32 and 64 bits (part of #118). Assemblers choose this form whenever one operand is the accumulator, and both engines used to stop on it with an illegal-instruction exit. A 16-bit exchange keeps the upper 48 bits of both registers, a 32-bit one clears both upper halves, and `49 90` exchanges RAX with R8 while plain `90` stays NOP. Both engines run the shared semantics; nothing is lowered to ARM64. Three SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/x86/integer.txt` gains 20 assembled instructions checked by the text-only reference in `x86_integer.rs`. F3 before this form, 16-bit PUSH and POP and LODSW stay rejected. Not compared with x86 hardware; awaiting independent review.
- Added SHLD and SHRD, the double-precision shifts (`0F A4`/`0F A5` and `0F AC`/`0F AD`), for 16-, 32- and 64-bit register and memory destinations with the count in an 8-bit immediate or in CL (part of #121). The count is masked to five bits (six for 64-bit operands); a masked count of zero changes nothing, the vacated bits are filled from the source register, CF receives the last bit shifted out of the destination, ZF, SF and PF follow the result, OF is set only for a count of one (a sign change) and AF is undefined. A 16-bit count above 16 leaves the result and flags undefined in the Intel SDM; Xenora keeps every flag and writes the bits of the 32-bit concatenation, and no test relies on that. The registry gained the operand encodings `rm_reg_imm` and `rm_reg_cl`. Both engines run the shared semantics; nothing is lowered to ARM64. Eight SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/x86/integer.txt` gains 72 assembled SHLD and SHRD instructions, checked by a bit-at-a-time reference in `x86_integer.rs` and by the faulting read-modify-write test. Not compared with x86 hardware; awaiting independent review.
- Added RCL and RCR, the rotates through the carry flag, for 8-, 16-, 32- and 64-bit register and memory operands with a count of one, CL or an immediate (part of #121). The count is masked to five bits (six for 64-bit operands) and then reduced modulo 9 or 17 for 8- and 16-bit operands; a masked count of zero changes nothing, CF receives the last bit rotated out, and OF is set only for a count of one. Both engines run the shared semantics; nothing is lowered to ARM64. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and its shift sweep now runs both instructions at every width, count and carry against its bit-loop model. `tests/x86/integer.txt` gains 80 assembled RCL and RCR instructions, checked by the single-step reference in `x86_integer.rs`. SHLD and SHRD stay rejected. Not compared with x86 hardware; awaiting independent review.
- Added four Wave32 gfx1030 VOP2 select and carry forms through the semantic registry. Conditional select, add with carry and both subtract orders with borrow use a per-lane VCC bit and have a guide-derived oracle that passes on both CPU interpreters and on native Metal (local Apple M5, API and shader validation); independent acceptance is pending. Part of #215.
- Added decoding and Metal shader translation for twelve Wave32 VOPC 16-bit integer compares (#215). The signed and unsigned forms compare the low 16 bits of each source and write the Wave32 VCC mask. CPU verification covers 1,572 compiler acceptance cases and 408 rejections from the guide-derived oracle, which also passes on native Metal (1,572 cases in 1,420 programs on a local Apple M5 under API and shader validation); acceptance is pending.
- Added MOVS and STOS for 8- to 64-bit elements, with and without REP, and the direction flag with CLD and STD (#129). A REP form runs one element per step and stays on the instruction until RCX is zero, so every element counts against the step budget, a repeat can stop part-way and resume, a zero count touches nothing, and a fault keeps the elements already done with RSI, RDI and RCX at the one that faulted. An FS or GS override applies to the MOVS source only. Both engines run these on the shared semantics with no bulk-copy path, so large copies are slow. LODS, CMPS, SCAS, REPE, REPNE and the address-size override stay rejected. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/cpu_rep.rs` adds a byte-array model over every form, direction and count; not compared with x86 hardware and awaiting independent review.
- Added a deterministic guest thread scheduler (first part of #323): independent CPU contexts, guarded stacks and TEBs on one host thread, with bounded turns, `CreateThread`, `ExitThread`, `TerminateThread`, `GetExitCodeThread`, `SuspendThread`, `ResumeThread` and `SwitchToThread`. With a scheduler attached, `WaitForSingleObject` and `WaitForMultipleObjects` block only the calling guest thread, with timeouts, on threads, events, semaphores and mutexes; abandoned mutexes, deadlocks and per-thread faults are reported. Guest threads never run concurrently. Critical sections, SRW locks, condition variables and `Sleep` do not block per thread yet. See `docs/runtime/threads.md`.
- Added decoding and Metal shader translation for the sixteen Wave32 VOPC 64-bit integer compares (#215). They read VGPR pairs, known even-aligned SGPR pairs or sign-extended inline integers and write the Wave32 VCC mask. The guide-derived oracle passes on native Metal (4,640 cases in 3,818 programs on a local Apple M5 under API and shader validation); acceptance is pending.
- Added XADD and CMPXCHG for 8- to 64-bit register and memory destinations, and the LOCK prefix on their memory forms (#198). LOCK anywhere else, CMPXCHG8B and CMPXCHG16B stay rejected. Both engines run the new forms on the shared semantics, one instruction at a time, so a locked instruction is indivisible today and LOCK changes no result; `docs/cpu/instruction-registry.md` states the ordering, alignment, compare-failure and fault rules a guest scheduler must preserve. A failed compare still writes the destination, so it faults on memory that cannot be written. Nothing is lowered to ARM64 atomic instructions, and no multi-thread behaviour is established. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, with 62 LLVM-assembled fixtures and five new tests in `x86_atomic.rs`; not compared with x86 hardware and awaiting independent review.
- Added CPUID with a fixed, host-independent guest contract (#130). It reports a synthetic processor with the vendor string `Xenora guest` and sets a feature bit only when every instruction of that feature is implemented: CMOV, POPCNT, LZCNT and long mode today. SSE and SSE2 are not reported while parts of them, such as RSQRTPS and MFENCE, are still rejected, so the table is truthful about Xenora and not a plausible hardware model. Unlisted leaves return zeros. `tests/cpu_features.rs` pins every leaf in both engines, requires each reported feature's instructions among the executed fixtures, and holds a refused witness instruction for 31 unreported features. `docs/cpu/instruction-registry.md` gives the table and the rule for reporting a new feature. Not compared with a processor; awaiting independent review.
- Added six Wave32 gfx1030 VOP1 integer forms through the semantic registry, including bit scans and a two-register swap under EXEC (AMD RDNA 2 ISA guide section 12.8, #215). The compiler accepts 752 guide-derived cases and rejects 610 programs at the oracle’s expected offsets. Native Metal verification and independent acceptance are pending.
- Added delay-loaded imports to the static PE probe (#244). `xenora probe --mode static` now reads the PE32+ delay-load directory and lists each delay-loaded import in `imports.csv` with its DLL, symbol or ordinal, and delay import address table slot. A new `import_table` column, inserted after `iat_rva`, marks every row `ordinary` or `delayed`; `import_kind` stays the last column. The existing totals and `missing_imports.csv` still cover ordinary imports only, and the JSON report adds `delayed_imports`, `delayed_imported_dlls_count` and `delay_import_error`. The table is bounded by the directory's declared size, which must hold the empty descriptor that ends it, and each descriptor's DLL name, import address table and import name table must be present and start in section data. A table that breaks these rules, is truncated, sets a reserved attribute bit or uses the earlier virtual-address descriptor form is reported with the entries read before the problem. `xenora imports sync` leaves delayed rows out of its backlog. Inspection stays static: nothing is bound or executed. Covered by an original fixture (`fixtures/pe/delay-imports.exe`, generated by `fixtures/pe/delay-imports.py`) whose imports were cross-checked locally with `llvm-readobj --coff-imports` from LLVM 23.1.6; awaiting independent review.
- Added the sixteen gfx1030 SOPK integer forms through the semantic registry: `s_movk_i32`, `s_cmovk_i32`, `s_cmpk_{eq,lg,gt,ge,lt,le}_{i32,u32}`, `s_addk_i32` and `s_mulk_i32` (AMD guide sections 12.2 and 13.1.2), with SDST s0-s105 only and SIMM16 sign-extended (zero-extended for the unsigned compares). The registry gained the operand rules `sopk_sgpr` and `sopk_compare` and the operations `mov` and `cmov`; the decoder and the scalar translation fold them like SOP2 and SOPC. An independent guide-derived oracle (`tests/validation/tests/sopk.rs`, 4,184 cases and 398 rejections on both CPU interpreters and native Metal), an LLVM-assembled fixture `scalar-immediate.s` with IR and MSL goldens, and the LLVM three-way decoder check cover them (part of #215).
- Added an independent guide-derived oracle for the Wave32 16-bit (`v_cmp_{lt..ge}_{i16,u16}_e32`) and 64-bit (`v_cmp_{f..t}_{i64,u64}_e32`) integer compares in the reference and the second interpreter (6,212 lane cases, 1,208 rejections; contract in `docs/shaders/vector-compare.md` section 2a). Part of #215.
- Added `python3 -m qa rdna2 rank` to the read-only RDNA2 planner: it groups undeclared gfx1030 forms by the piece of work that would unlock them (an encoding variant of a declared form, a new operand rule, or a new primitive, from XML identity and operand shape only) and ranks the groups by forms per estimated cost, excluding claimed scopes, with `--no-float` to leave out floating-point groups until the FP contract exists (part of #215).
- Added authoritative read-only x86-64 CPU inventory CLI (`python3 -m qa cpu-inventory`) over `crates/loader/x86/instructions.toml` via `generate_x86.load`, with opcode-map/prefix/operand summaries, native vs shared-semantic operation partitions from `dbt.rs`, fixture mnemonic evidence and a separate unsupported catalog. Does not count candidates as implemented. Covered by `tests/qa/test_cpu_inventory.py`.
- Added typed runtime inventory CLI (`python3 -m qa runtime-inventory`) over `crates/loader/runtime/services.txt`, reporting implemented/partial/stub services separately from API-set aliases and leaving independently-verified empty unless recorded. Covered by `tests/qa/test_runtime_inventory.py`.
- Added `crates/loader/tests/cpu_known_answers.rs` (#155): 736 x86-64 cases whose results, flags, MXCSR state and faults come from the Intel SDM, with the AMD APM for some MXCSR flags, plus arithmetic, shift, packed-integer, multiply, divide and floating-point sweeps computed from the manuals' definitions. 700 cases were written before the CPU source was read; the rest and the sweeps came afterwards. The interpreter and the DBT both run them; the DBT route (ARM64 code or Rust helper) is confirmed by the fallback counter for straight-line cases and predicted for the others. 592 cases are verified, 133 use forms both engines refuse, and eleven, plus a self-modifying-code test, record open defects in five ignored tests: the reported address of a page-crossing fault, the fault class of a non-canonical address and of an instruction over 15 bytes, PE set by an exact unmasked overflow, and DBT blocks that stay cached after the guest rewrites them. Not compared with x86 hardware; awaiting independent review.
- Added a typed runtime service registry (`crates/loader/runtime/services.txt`) and `xenora-runtime-gen`, which generates Win64 argument and result adapters, static metadata and a coverage report. It covers 20 services: 16 existing kernel32 services moved to typed handlers, and `sqrt`, `sqrtf`, `fabs` and `fabsf` with arguments and results in XMM registers. Conflicting keys, unlisted API sets, unsupported types and behaviour without an existing test are rejected. See `docs/runtime/registry.md`.
- Added SSE and SSE2 floating point in scalar and packed, binary32 and binary64 forms: add, subtract, multiply, divide, minimum, maximum, square root, compares, COMI/UCOMI and the conversions between formats and integers (parts of #127 and #128; awaiting independent review). `crates/loader/src/softfloat.rs` computes every result exactly and rounds once, with MXCSR rounding modes, sticky flags, denormals-are-zero, flush-to-zero, tininess after rounding and x86 NaN rules; host floating point is not used because ARM64 differs. An unmasked exception exits with `SimdException` and leaves everything but MXCSR unchanged. RCP, RSQRT and MMX conversions are rejected, and no floating-point form is translated to NEON yet.
- Added 6,824 floating-point vectors computed with exact fractions by `tests/x86/float_reference.py`, run through both engines from registers and memory and through the packed forms, and more than two million round-to-nearest results compared with the host's IEEE 754 hardware.
- Added XMM0-XMM15 and MXCSR to the guest CPU state, and the SSE and SSE2 moves and packed integer forms: aligned, unaligned, scalar, half and non-temporal moves, MOVD/MOVQ, sign-mask extraction, bitwise operations, wrapping and saturating arithmetic, compares, minimum, maximum, average, multiplies, PSADBW, packs, unpacks, shifts, shuffles, PINSRW, PEXTRW, LDMXCSR and STMXCSR (parts of #124, #125, #126 and #128; awaiting independent review). Operations with identical NEON lane semantics are translated to ARM64; the rest call the shared semantics. Misaligned 16-byte operands and reserved MXCSR bits raise a distinct general-protection exit. MXCSR is state only: floating-point arithmetic is not implemented.
- Added 374 LLVM-assembled vector instructions with a byte-array reference, compared with both engines over 23,936 states, plus alignment, fault, width and mixed-sequence tests.
- Added a declarative x86-64 instruction registry (`crates/loader/x86/instructions.toml`) and its generator, `crates/loader/generate_x86.py`, with `validate`, `generate` and `--check` modes. The static probe, the interpreter and the native DBT now share one decoder driven by its tables, so instruction boundaries, rejected forms and reported support agree. Overlapping encodings, such as a sign extension claiming the MOV-immediate opcodes, fail validation. See `docs/cpu/instruction-registry.md`.
- Added integer instructions for 8-, 16-, 32- and 64-bit register and checked memory operands: the eight ALU operations, TEST, INC, DEC, NEG, NOT, XCHG, ROL, ROR, SHL, SHR, SAR, MUL, IMUL, DIV, IDIV, CMOVcc, SETcc, BT, BTS, BTR, BTC, BSF, BSR, POPCNT, TZCNT, LZCNT, CBW/CWD families, PUSH, POP, LEAVE, RET imm16 and flag instructions, with parity and auxiliary-carry flags and a distinct divide-error exit (parts of #65, #66, #68, #70, #71, #73, #118 to #123, #194 to #196; awaiting independent review). Forms the DBT does not lower to ARM64 call the same Rust semantics and are counted.
- Added 985 LLVM-assembled integer instructions with a bit-level reference that reads only their assembly text, compared with the interpreter and the DBT over 47,280 states, plus 4,000 random instruction sequences compared between the engines.
- Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215.
- Added MOVZX, MOVSX (0F B6/B7/BE/BF) and MOVSXD (63) for register and checked memory operands in the interpreter and the native DBT, with exact lengths in the static probe (parts of #65, #66, #67, #68 and #117; awaiting independent review). Covered: 16-, 32- and 64-bit destinations, AH/CH/DH/BH without REX, FS/GS bases and RIP-relative operands. Other 0x66 forms are rejected instead of running at the wrong width. Known-answer encodings come from the LLVM assembler; MOV immediates (B8-BF) have regressions proving they are never read as sign extensions.
- Added FNINIT (`DB E3`), the one instruction a C program built with the mingw-w64 runtime needs that the decoder refused (#378, part of Gate A2). Guest state gains the x87 control, status and tag words in `CpuState::x87`, and FNINIT sets them to the Intel SDM values `037F`, `0` and `FFFF`. Both engines run the shared semantics; nothing is lowered to ARM64 and the host's floating-point state is never touched. The registry gains a form key, `rm`, that pins a register-only form to one ModRM byte, because the other bytes of `DB /4` are different instructions. No other x87 instruction exists: FNSTCW, FLDCW, FNCLEX, FWAIT and all x87 arithmetic stay rejected, there are no x87 data registers, nothing can read the three words back, and CPUID still reports no FPU. Nine SDM-derived cases in `cpu_known_answers.rs`, whose harness now starts every case with the three words away from their reset values and requires every other instruction to keep them, one assembled fixture checked by the text-only reference in `x86_integer.rs`, and a sweep of every ModRM byte under opcodes `D8` to `DF` in both engines cover it. Not compared with x86 hardware; awaiting independent review.
- Added Phase II infrastructure CLIs under `scripts/qa` and `scripts/release` (#277): read-only RDNA2 expansion planning over live inventories, unified verification profiles with stale-evidence detection, CPU/runtime coverage scans, benchmark regression comparisons that reject incompatible identities, git rename/delete scope collision reports, and release-readiness reports with SBOM/checksum/bundle checks. Covered by `tests/qa` and `tests/release`; advisory until reviewed.
- Added advisory infrastructure QA helpers under `scripts/qa/` and `scripts/release/` (issue #277): exit-status-preserving orchestration with JSON reports, PR scope/DCO/artifact checks, benchmark percentile analysis over existing samples, environment and repository health diagnostics, ARM64 Mach-O/bundle/codesign helpers, and checksum manifests. Covered by `tests/qa/` and `tests/release/`; checks stay advisory until reviewed.
- Recorded agent-queue live smoke evidence for issue #180 against the disposable private repository `ranveersoni98/xenora-agent-queue-smoke`, including claim grant, overlap refusal, release, not-ready denial, progress renew and a successful audit dispatch after fixing comment-only `apply_actions` and audit permissions/argparse issues.
- Added twelve gfx1030 VOP2 vector integer forms through the semantic registry: `v_mul_i32_i24`, `v_mul_hi_i32_i24`, `v_mul_u32_u24`, `v_mul_hi_u32_u24`, `v_min_i32`, `v_max_i32`, `v_min_u32`, `v_max_u32`, `v_xnor_b32`, `v_add_nc_u32`, `v_sub_nc_u32` and `v_subrev_nc_u32` (AMD guide section 12.7), with SRC0 a VGPR, an SGPR, `vcc_lo`, an inline integer or a literal. The registry gained a `vop2_vgpr` operand rule, the vector operations `mul24` and `mul_hi24`, a declared `source_order` for SUBREV, and a per-lane `VectorBinary` that selects one reusable MSL template per operation. Both reference interpreters, written separately from the guide, run the same twelve forms and are checked against 2,040 guide-derived cases, each asserting every lane of a 7-, 32- or 45-lane dispatch (partial, empty and full EXEC), on both CPU interpreters and on native Metal; 575 rejected programs are refused by both interpreters and by the compiler at the same word. A new LLVM-assembled fixture computes every lane from its own input. Part of #215.
- Moved the twelve Wave32 VOPC integer compares from #239 into the semantic registry (operand rule `vopc_vcc`, `vcc = "lane_mask"`, `wave = "wave32"`) with no behaviour change, and added `v_cmp_f_i32`, `v_cmp_t_i32`, `v_cmp_f_u32` and `v_cmp_t_u32` as registry forms under the same Wave32 VCC/EXEC contract, verified by an independent guide-derived oracle (`tests/validation/tests/vopc_f_t.rs`), a new LLVM-assembled fixture and native Metal (part of #215). `v_cmpx_*`, the VOP3 encoding and Wave64 stay unsupported.
- Split the gfx1030 semantic registry into one file per encoding family (`crates/isa/semantics/rdna2/{sop2,sopc,sop1,vop2,vopc,vop3}.toml`, included in order by `rdna2.toml`; the split left the generated tables byte-identical), and added registry encoding variants: another encoding of a declared form is pure data. `v_add_nc_u32_e64` is now the first VOP3 variant of `v_add_nc_u32` (operand rule `vop3_vgpr2`), replacing its hand-written decoder and instruction with no behaviour change (part of #215).
- Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215.
- Added guest mutexes, critical sections, SRW locks, condition variables, synchronous one-time initialization, interlocked SLists, and TLS and FLS slots. Ownership is per guest thread (TEB). Calls that would have to block stop the guest with an explicit runtime-limit fault, because there is no guest scheduler yet. An original PE32+ fixture calls every service through its import table, using two guest TEBs. See `docs/interfaces.md`.
- Added an MSVC decorated-name decoder (`xenora_import_gen::demangle`), and import manifests now show undecorated names for C++ imports that need manual engineering. Unsupported constructs return no result rather than a guess. Tests decode names mangled independently by clang for `x86_64-pc-windows-msvc`.
- Added a guest service dispatch benchmark (`cargo bench -p xenora-loader --bench service_dispatch`). It runs correctness-gated guest loops that call services through the import table under the DBT; see `docs/testing/benchmarks.md`.
- Added a `runtime_services` fuzz target (`scripts/fuzz.sh runtime_services`) and a stable-toolchain replay test sharing the same driver. Both call random sequences of the standard guest services with zero, all-ones, writable, read-only, executable, unmapped, raw and earlier-result arguments, and check after every call that read-only and code memory are unchanged and nonvolatile registers are preserved. Writable guest memory is filled from a deterministic pattern so corpus bytes are reserved for dispatch. An earlier 300-second campaign's input and edge counts are withdrawn: that run exhausted each input while filling the 65,536-byte writable region and never reached the dispatch loop. After the harness fix, a local 300-second campaign on Apple Silicon (`scripts/fuzz.sh runtime_services 300`) ran 96,589 inputs (4,008 coverage edges, 9,940 features) without a crash; the first minutes also found a ~3.7 GiB `XMemAlloc` host OOM, which is now fixed by failing closed on overflowing sizes and routing mappings through the virtual allocation budget. Services that wait on real time or reach native Metal are excluded.
- Added guest system information, memory status, calendar time conversion, interrupt time and sleeping. The guest sees a configurable simulated machine (`GuestSystemProfile`, one processor by default), kept separate from the detected host hardware (`HostCapabilities`). Sleeping goes through the injectable clock, so tests advance time deterministically. An original PE32+ fixture verifies `SYSTEM_INFO`, `MEMORYSTATUSEX` and `SYSTEMTIME` layouts and leap-year handling against dates computed independently.
- Added services that call guest code and continue when it returns. The import dispatcher can run a sequence of guest callbacks on a checked stack frame, verifying the Win64 nonvolatile registers after each one. The CRT uses this for `qsort`, `qsort_s`, `bsearch`, `bsearch_s`, `_initterm`, `_initterm_e`, onexit tables, `atexit` and `_cexit`. Kernel32 uses it for `InitOnceExecuteOnce` and `FlsFree` cleanup callbacks. Original guest comparators and initializers in a PE32+ fixture verify ordering, stop-on-failure and register preservation.
- Fixed the import generator classifying the synchronization API-set entries for `CreateSemaphoreA`, `CreateSemaphoreW` and `ReleaseSemaphore` as stubs, which overrode the runtime handlers. A CLI test now checks that every generator entry marked as a standard service resolves to a registered, non-stub loader handler.
- Added guest module lookup and named symbol resolution for built-in Kernel32 and UCRT services.
- Added process exit and the first Gate A milestone, A1 (#329). `kernel32.dll!ExitProcess` stops the guest with the new `ExitReason::ProcessExit(status)`, carrying all 32 bits of the status, and never ends the host; a returning entry point does the same with EAX. The exit closes every guest handle, including Winsock sockets and task-queue handles, and the engine that ran the guest executes nothing further. A TLS callback that exits ends startup with that exit as its outcome, and the remaining callbacks and the entry point do not run. Startup reserves the page holding the return addresses the engine intercepts, so an image mapped over them is refused. `atexit` functions are not run. A1 is an original C program with no C library linked (`tests/compat_fixtures/gate_a1.c`): `crates/loader/tests/gate_a1.rs` builds it from source with clang and an LLD on every run, executes it through the loader, the standard services and the DBT at `-O0`, `-O1`, `-O2` and `-Os`, and checks its exit status, its report, its files and its memory against values recomputed in Rust. `docs/testing/gate-a.md` records what A1 shows and that Gate A stays open until the hosted milestone, A2, passes. Verified locally with two compilers; awaiting independent review.
- Added same-process guest file handle duplication with a shared file position.
- Added guest file and directory enumeration with typed search handles.
- Added closed-file moves and file and directory attribute queries on the synthetic guest drive.
- 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.
- Added the C runtime's `exit`, `_exit` and `abort` (#395, part of Gate A2), on top of the process exit from #329. A C program ends through `exit`, not `ExitProcess`, and a program built with the mingw-w64 runtime imports all three; the loader refused it before its entry point because they did not resolve. `exit` calls the functions registered with `atexit` and `_crt_atexit`, most recently registered first, and then ends the guest with `ExitReason::ProcessExit(status)`; `_exit` ends it with its status and `abort` with exit code 3, and neither calls a registered function. All three go through the same cleanup as `ExitProcess` and never end the host. A function registered while `exit` runs is called next, as ISO C requires; `exit` called again from a registered function, which ISO C leaves undefined, runs the remaining functions once and ends with the later status. All three are partial: no stream is flushed because there are none, `abort` prints no message and calls no `SIGABRT` handler, and thread-local destructors are not run. Nine tests in `crt_exit.rs` call them from guest code. `docs/testing/gate-a.md` now describes A2 as in progress and not passing. Not compared with Windows; awaiting independent review.
- Added immediate wait-any and wait-all for guest event handles.
- Added guest CRT signed and unsigned 64-bit conversions for narrow and wide strings.
- Added command-line arguments for a hosted C program (#392, part of Gate A2): the C runtime services `__p___argc`, `__p___argv`, `__p__environ`, `_configure_narrow_argv` and `_initialize_narrow_environment`, and a host method, `ServicesState::set_program_arguments`, that supplies the program's `argv`. A program built with the mingw-w64 runtime gets `argc`, `argv` and `envp` for `main` through these five, and the loader refused it before its entry point because they did not resolve. After configuration the guest finds the host's arguments in `__argc` and `__argv`, each NUL-terminated, with a null pointer after the last; with no host input it gets one empty argument, as ISO C specifies. The host method refuses a NUL byte, more than 32,767 bytes in all, and a call after the guest has built its table. The three variables are documented and the two initialization functions are not, so their behaviour is Xenora's: no code page, no wildcard expansion, and an empty environment table. All five are `partial`. Four tests in `runtime_services.rs` call the services from guest code and compare what the guest sees with what the test supplied. Not compared with Windows; awaiting independent review.
- Added bounded guest CRT long-integer parsing for byte and wide strings.
- Added standard output for a hosted C program (#400, part of Gate A2): a `printf` formatting engine, the standard streams, and capture of what the guest writes to `stdout` and `stderr`. The services are `__acrt_iob_func`, `__stdio_common_vfprintf` (what `printf` and `fprintf` call in a program built with the mingw-w64 runtime), `fwrite`, `fputs`, `fflush` and `setvbuf`; a host reads the output through `ServicesState::standard_output` and `standard_error`. The engine handles the flags, width, precision and size prefixes of `d`, `i`, `u`, `o`, `x`, `X`, `c`, `s`, `p` and `%%` as Microsoft's format specification page and ISO C describe, reading arguments from the guest's `va_list`. The standard streams are text-mode streams, so a line feed is captured as carriage return and line feed. Floating-point and wide conversions, a locale object, other streams and files are not modelled and stop the guest with the runtime-limit fault instead of printing something wrong; `%n` and unknown conversions return -1 with `EINVAL`. All six services are `partial`. The engine's output matches the host C library's `snprintf` on 2,600 generated cases whose result ISO C defines (`crates/loader/tests/printf/reference.py`), with hand-written cases for the Windows-specific rules, and seven tests in `runtime_services.rs` call the services from guest code. Not compared with Windows; awaiting independent review.
- Added guest CRT errno accessors and allocation failure reporting for the synthetic main thread.
- Added nine C runtime services that a C program's startup code calls or imports before `main`, and one alias (#382, part of Gate A2): `_set_app_type`, `_set_new_mode`, `_configthreadlocale`, `__setusermatherr`, `_set_invalid_parameter_handler`, `__p__fmode`, `__p__commode`, `signal` and `SetUnhandledExceptionFilter`, plus `memcpy` through `api-ms-win-crt-private-l1-1-0.dll`. A program built with the mingw-w64 runtime imports all of them, and the loader refused it before its entry point because they did not resolve. Each records what it is given and returns what its public documentation says: the previous mode, setting or handler, the documented failure value, or the address of the guest variables `_fmode` and `_commode`. All nine are declared `partial` in the typed registry because nothing acts on a recorded value: no handler or filter is ever called, no signal is raised, there is no locale, and nothing reads `_fmode` yet. `ServicesState` gains two read-only accessors, `crt_app_type` and `crt_user_math_error`. Five tests in `runtime_services.rs` call the services from guest code through a bound import table. Not compared with Windows; awaiting independent review.
- Added guest CRT allocation, zeroed array allocation, resizing, and release.
- Added private guest heap creation and destruction with per-heap allocation ownership.
- Added default guest heap reallocation with data preservation and an in-place-only option.
- Added the synthetic default process heap with allocation, size queries, and release.
- Added `VirtualProtect`, `VirtualQuery` and `__C_specific_handler` as `stub` services so that a C program built with the mingw-w64 runtime can bind its imports (#388, part of Gate A2). Such a program imports all three and does not call them on a normal run; without them the loader refused it before its entry point. A call to any of them stops the guest with the runtime-limit fault (`IllegalInstruction(0xFE)`) and writes nothing, so a program that needs one stops there and cannot run on with a made-up result. No page protection is changed, no region is described and no exception is dispatched. The service generator's API-set table gains `api-ms-win-crt-private-l1-1-0.dll` for `ucrtbase.dll`, which is inferred and not taken from a document that names it. Two tests in `runtime_services.rs` call the stubs from guest code and check how they resolve. Not compared with Windows; awaiting independent review.
- Added Win64 signatures for wide-string length and comparison and overlapping byte moves to the import catalog.
- Added guest CRT wide-string length and comparison using Windows 16-bit code units.
- Added checked guest CRT byte string comparison with `strcmp` and `strncmp`.
- Added bounded guest CRT byte fill, copy, move, and comparison services.
- Added guest CRT string length services for UCRT and its string API set.
- Added unnamed guest events with manual and automatic reset, signaling, immediate waits, and same-process handle duplication.
- Added same-process duplication of synthetic thread handles with independent closure.
- Added a rights-checked `GetThreadId` query for handles to the synthetic guest thread.
- Added 32-bit and 64-bit millisecond uptime queries for synthetic Windows guests.
- Added high-resolution elapsed-time queries for synthetic Windows guests through `QueryPerformanceCounter` and `QueryPerformanceFrequency`.
- Added audio PCM streaming and sandboxed virtual filesystem (VFS) integration to the native application runtime (Gate 6, #284). The C interface gains audio management functions (`xenora_session_audio_init`, `xenora_session_audio_submit`, `xenora_session_audio_read`, `xenora_session_audio_status`, `xenora_session_audio_set_volume`) and virtual filesystem functions (`xenora_session_vfs_set_root`, `xenora_session_vfs_open`, `xenora_session_vfs_read`, `xenora_session_vfs_seek`, `xenora_session_vfs_close`, `xenora_session_run_audio_vfs_fixture`). The audio subsystem implements a bounded ring buffer supporting configurable sample rates, channel configurations, PCM formats (S16LE, F32LE), volume attenuation, mute, and buffer underrun tracking. The virtual filesystem operates within an explicitly configured, sandboxed directory root (`fixtures/assets`), strictly rejecting path traversal attempts (`..`, absolute paths, null bytes) and invalid or stale handles, while supporting sequential and seekable file reads (`XENORA_SEEK_SET`, `XENORA_SEEK_CUR`, `XENORA_SEEK_END`). An original PE fixture (`fixtures/pe/audio_vfs.exe`, generated by `fixtures/pe/audio_vfs.py` using only the supported ARM64 DBT instruction subset) opens `asset.bin` (generated by `fixtures/assets/generate.py`), loads a 2x2 RGBA texture and 256 PCM audio samples via VFS, initializes audio, submits the PCM audio queue, and renders the loaded texture on Metal. Verified with unit tests, four Metal acceptance tests in `crates/ffi/tests/audio_vfs.rs`, UI controls and a `--smoke-audio-vfs` CLI in `Xenora.app`.
- Added persistent GPU resources, dynamic texture updates, and resource retirement to the native application (Gate 5, #279). The C interface gains `xenora_resource`, resource types (`XENORA_RESOURCE_TYPE_*`), `xenora_session_create_texture`, `xenora_session_update_texture`, `xenora_session_destroy_resource`, `xenora_session_resource_info`, `xenora_session_render_textured`, and `xenora_session_run_textured_fixture`. Persistent GPU resources (textures) are explicitly allocated and owned by the execution session, surviving across execution slices without re-allocation. Dynamic texture subregion updates modify GPU texture contents in-place on native Metal. Resource retirement is completion-aware: destroying a resource held by in-flight GPU execution marks it retired and safely defers destruction until in-flight work completes, while rejecting subsequent caller queries with typed error codes. An original PE fixture (`fixtures/pe/textured.exe`, generated by `fixtures/pe/textured.py` using only the supported ARM64 DBT instruction subset) creates a persistent 2x2 texture via `xenora.dll!texture_create`, renders frame 0, updates pixels via `xenora.dll!texture_update`, renders frame 1, and retires the resource via `xenora.dll!texture_destroy`. Xenora.app gains "Run textured fixture" controls and `--smoke-resources`. Six GPU acceptance tests with Metal validation verify persistent texture lifecycle across multiple frames, dynamic 1x1 and 2x1 subregion updates on native Metal, completion-aware deferred retirement, rejection of invalid/stale/double-destroyed handles, slot reuse across 200 cycles without leaking, and full guest fixture execution. Wired acceptance tests into `scripts/test-gpu.sh`.
- Added interactive guest execution with dynamic input handling and rendering to the native application (Gate 4, #276). The C interface gains `xenora_session_start_interactive_loop`, `xenora_session_send_input`, `xenora_session_queue_input`, and `xenora_session_get_recorded_frame`, along with input masks (`XENORA_INPUT_*`) and `xenora_input_state`. The original interactive guest fixture (`fixtures/pe/interactive.exe`, generated by `fixtures/pe/interactive.py` using only the supported ARM64 DBT instruction subset) polls host input via `xenora.dll!input_poll` and steers its rendered column position (0..3) on native Metal. Xenora.app gains interactive frame-loop controls ("Interactive (300 frames)", "◀ Left", "▶ Right", "Release") and `--smoke-interactive`. Four GPU acceptance tests with Metal validation verify that input events drive guest state and pixel geometry, deterministic input replay reproduces identical frame sequences across multiple sessions, key release and focus loss cleanly hold position without stuck keys, and destroying an interactive session joins promptly. Wired the interactive tests into `scripts/test-gpu.sh`.
- Added persistent guest rendering with pause, resume and stop to the native application (Gate 3, #266). The C interface gains `xenora_session_start_frame_loop`, `xenora_session_pause_frame_loop`, `xenora_session_resume_frame_loop`, `xenora_session_stop_frame_loop`, and `xenora_session_frame_loop_status`, plus new states (`XENORA_LOOP_*`). The guest fixture (`fixtures/pe/frame-loop.exe`, generated by `fixtures/pe/frame-loop.py` without external toolchains) runs on a session-owned thread and repeatedly calls `xenora.dll!frame_submit` until told to halt; each frame is rendered on native Metal, checked per pixel against geometric expectations, and returned via read-back RGBA8 buffers. Destroying a running or paused session safely stops its loop outside the global session lock. Xenora.app gains persistent frame-loop controls ("Start 300 frames", "Pause", "Resume", "Stop") and displays live frames with their frame index. Five GPU acceptance tests with Metal API and GPU validation verify frame ordering over 300 frames, live sampling across 2,000 frames without backwards progression, pause/resume/stop lifecycle, prompt join on session destruction, and stable memory footprint across repeated sessions. Added `--smoke-loop` to Xenora.app and wired the acceptance tests into `scripts/test-gpu.sh`.
- Added read-only executable inspection to the native app (#267). Xenora.app can open a PE file with Open Executable…, by dropping it on the window, or from Finder (it registers as an alternate viewer for Windows executables). The new C function `xenora_inspect_executable` returns a text report built from the existing static probe and loader validation: file size and SHA-256, header facts, whether `ParsedPe::parse` accepts the file, sections, imports not provided by Xenora's standard runtime services, the bounded static disassembly's count of instructions the ARM64 DBT does not support with the first one's address, and relocation and TLS counts. Nothing in the file is executed, and executing opened files remains unavailable pending #257. Inputs over 256 MiB are refused before reading. A panic inside the probe is reported as a Xenora defect instead of crashing the app; the new truncation test found one in `probe_pe_bytes` (truncations of `trusted-runner.exe` to 1,556–1,665 bytes slice past the end of the file while reading an import name), reported as #270 and not fixed here. Checked with the x1 executables in `experiments/x1/fixtures`, which the app does not embed, with malformed inputs, and in the window through the Finder open path and the Open panel; drag and drop was not exercised.
- Added eleven gfx1030 SOP1 unary forms through the semantic registry: `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`, `s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`, `s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32` (AMD guide section 12.3). Searches that find nothing return -1, `s_abs_i32` of 0x80000000 stays 0x80000000, and only NOT, BCNT0, BCNT1 and ABS write SCC. The registry gained these primitives, a `sop1_sgpr` operand rule, and a declared `source_bits` for sign extension that is checked against the XML's 8- and 16-bit source operands. The reference and independent semantic-review interpreters, written separately from the guide, evaluate the same eleven forms and are checked against 4,126 guide-derived cases on both CPU interpreters and on native Metal with validation; 231 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all eleven. Part of #215.
- Showed the first guest-driven frame in the native app (Gate 2, #263). The C interface gains `xenora_session_run_trusted_fixture`, which runs only the embedded trusted PE fixture: its x86-64 code is translated and executed, its `xenora.dll!fixture_draw` call compiles the x9 RDNA2 shader fixtures to MSL and renders on the native Metal device, and the 4×3 RGBA8 read-back is returned only if the guest halts with the CLI runner's expected results and every pixel equals the pixel shader's export, (1, 0, 0, 1) as opaque red. Xenora.app's "Run trusted fixture" button shows that frame, and `--smoke-frame` prints it. A `gpu-tests` test, run by `scripts/test-gpu.sh`, executes the fixture three times through the interface with Metal validation enabled. The frame is a read-back image, not drawable presentation, and no caller-supplied executable can run. Verified on one Apple Silicon Mac; the window was checked by screenshot.
- Added a minimal native macOS application shell and its Rust interface (Gate 1 of the native application work). `crates/ffi` builds a static library with a versioned C interface (`crates/ffi/include/xenora.h`, version 1): opaque, generation-checked 64-bit session handles (never pointers), at most 64 live sessions, stable status codes, and panics caught at the boundary. Version 1 can only create and destroy sessions and parse the bundled trusted PE fixture; it executes no guest code. `app/` is a SwiftUI app built with Swift Package Manager that shows the interface version and the fixture's section count and entry point. `scripts/build-app.sh` builds an ad-hoc-signed, arm64-only `build/Xenora.app` with no entitlements and runs its `--smoke` check. Six Rust tests cover invalid, stale and double-destroyed handles, version mismatch, null outputs, 4,000 concurrent create and destroy cycles, and header/constant agreement. The CLI and headless workflows are unchanged. Verified locally on one Apple Silicon Mac (macOS 27.2.1, Swift 6.4, Rust 1.100.0); not yet run in CI.
- Added the gfx1030 SOPC compares `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}` through the semantic registry, which replaces the hand-written `s_cmp_eq_u32` path. Each sets only SCC to whether the relation holds with SSRC0 on the left (AMD guide section 12.4); the registry gained a `compare` operation with a declared `relation` and a `sopc_scalar` operand rule. `Instruction::ScalarCompareEqU32` is now `Instruction::ScalarCompare { op: ScalarCompareOp, .. }`; `s_cmp_eq_u32` behaves as before. The reference and independent semantic-review interpreters, written separately from the guide, evaluate all twelve, checked against 7,824 guide-derived cases on both CPU interpreters and on native Metal with validation; 348 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all twelve. Two literal selectors stay rejected. Part of #215, stage D.
- Added eight gfx1030 SOP2 forms through the semantic registry alone: `s_andn2_b32`, `s_orn2_b32`, `s_nand_b32`, `s_nor_b32`, `s_xnor_b32`, `s_lshl_b32`, `s_lshr_b32` and `s_ashr_i32`, each with SCC = result != 0. Each is one registry entry with no per-form Rust; the registry gained these primitives and a declared shift-count width (`shift_count_bits = 5`, so shifts use S1[4:0] as in the AMD guide, section 12.1), which the generator applies as a mask and checks against the XML's unsigned count operand. The reference interpreter and the independent semantic-review interpreter, written separately from the guide, now evaluate the same eight forms and are checked against 6,896 guide-derived cases; a new LLVM-assembled fixture (`fixtures/rdna2/scalar-logic.s`) runs on CPU and native Metal with validation. A NULL destination (s125) stays rejected. Part of #215, stage C.
- Added an independent operand-domain verification harness for the 9 supported SOP2 scalar ALU forms and 12 VOPC integer compares (`tests/validation/tests/operand_domains.rs`, part of #215 stage E): 4,788 generated cases (boundary values, 64-bit carry and borrow chains, aliased registers, every integer inline constant, literals, s105 and v255, partial and zero EXEC, VCCZ) and 498 rejections (missing literal words, and encodings outside Xenora's supported subset) run on `xenora_ref` and, as an ignored test picked up by `scripts/test-gpu.sh`, on native Metal. Expected values come from the public AMD RDNA 2 guide's pseudocode, written out in the test without Xenora code; this is agreement with a spec-derived reference, not with Xbox hardware. Local verification only: 32 deliberate code breaks were each caught; the guide leaves the width of `S1 + SCC` in `s_subb_u32` open, and those 8 cases are kept in their own family.
- Added a declarative semantic registry for gfx1030 instruction forms (`crates/isa/semantics/rdna2.toml`, schema 1) and its generator, `crates/isa/generate_semantics.py`, with `validate`, `generate` and `--check` modes. The generator checks every declaration against a closed vocabulary and the pinned AMD XML snapshot (opcode, family, SCC input and output, operand widths and signed formats), rejects contradictory, incomplete or duplicate definitions, and emits static Rust tables marked as generated. The nine SOP2 forms moved onto it with no change in behaviour: the decoder's SOP2 dispatch and `ScalarAluOp`'s mnemonic, SCC read and evaluation are now generated, and evaluation goes through shared primitives instead of per-opcode code. All existing SOP2 tests, including the native Metal known answers and the LLVM comparison, pass unchanged. Decoding speed is unchanged (10.2 ns before, 10.1 ns after, per SOP2 instruction, release build on an Apple M5 Pro). Also added `scripts/audit/semantic_coverage.py`, which generates `docs/shaders/semantic-coverage.md`: per-family counts of identified, declared, decoded, lowered, reference-verified and Metal-verified forms, taking evidence only from `docs/status.toml`. Part of #215, stages A and B.
- Added a native Metal blend pass, `NativeCompute::render_blend`: up to 16 flat-coloured triangles drawn in order into an RGBA8 target, each with its own colour write mask (any subset of R, G, B, A) and either blending disabled or separate RGB and alpha blend factors (Zero, One, source and destination colour and alpha, and their one-minus forms) and operations (Add, Subtract, ReverseSubtract, and Min and Max, which take the unweighted values). Checked on the GPU with Metal validation in 39 passes over two original overlapping triangles: a clear-only pass; blending disabled; each source factor with the destination term zeroed and each destination factor with the source term zeroed; every operation; additive clamping; separate alpha factors; a separate alpha operation; eight write masks (each channel alone, RGB, none, RGBA, and RG with blending); and a pass whose first draw is itself blended and masked. Colours are compared per channel against images derived independently (in exact fractions) from the public Metal blend equations, which a new CPU reference in `xenora-ref` also reproduces. The tolerance was fixed before measuring: channels whose exact result is a whole 8-bit value must match exactly, and channels that need rounding may differ by 1. On an Apple M5 Pro every rounded channel matched round-to-nearest exactly. Synthetic fixtures only; no console blend state is involved.
- Added indexed triangle draws. Native Metal: `NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an RGBA8 target; a draw can sample an original BC1 texture uploaded natively. Before encoding anything it rejects the whole pass for a bad index count, an index range past the buffer, any `index + base vertex` outside the vertex buffer, and, as this API's policy, a raw all-ones index (the primitive-restart value, which Metal does not define for triangle lists). Loader: a synthetic, CPU-side index buffer binding (resource handle and offset, the view running to the end of the resource) with `cmd_set_index_buffer` and `cmd_draw_indexed_instanced`, which fetch one triangle, drawn once, through the index buffer, start index and base vertex and pass it to the existing one-triangle backend; each drawn triangle replaces the previous output. Recording rejects formats other than DXGI `R16_UINT` and `R32_UINT`, offsets not aligned to the index size or past the resource, and unknown resources. Execution checks each draw in turn, so earlier draws have already rendered when a later one fails: index counts other than 0 or 3, more than one instance or a nonzero start instance, a missing index buffer, indices past the buffer and an `index + base vertex` outside the vertex buffer are typed errors; a valid zero index or instance count draws nothing. All-ones indices are ordinary indices there. Checked on the GPU with Metal validation in 16 passes (both index sizes, 32-bit indices above 16 bits, odd 16-bit start, positive and negative base vertex, reversed winding, flat and textured two-triangle draws, draw order, BC1-textured draws), compared per pixel against images derived independently from the geometry, the public D3D12 and Metal index semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces; the loader's fetch is checked against literal positions with synthetic guest-backed buffers and through the native Metal renderer. Synthetic fixtures only; no console index-buffer views, guest programs or console draw state are involved.
- Added a `cpu_decode` cargo-fuzz target for the static x86-64 decoder used by the read-only PE probe. It places up to 4,096 fuzz bytes as the code section of a fixed, original PE32+ header and runs `probe_pe_bytes` twice with a bounded `ProbeConfig` (4,096 bytes, 2,048 instructions, 1,024 worklist entries); nothing is executed. It checks that the two reports are identical and that every decoded instruction is 1 to 15 bytes long, lies inside the code and matches the input bytes. A startup self-check aborts the run if the synthetic header stops reaching the decoder. A 600-second local campaign (nightly cargo-fuzz, one fork-mode worker, seeded from instruction bytes in the loader's probe tests; about 2.38 million executions, coverage 1,350 edges) found one decoder defect, reported to the CPU owner on #74 and not fixed here: the probe accepts unlimited FS/GS segment prefixes and reports instructions longer than 15 bytes (minimized input: 16 bytes of `0x65`). Run it with `rustup run nightly cargo fuzz run cpu_decode`; `scripts/fuzz.sh` does not list it yet.
- Added a `pe_parse` cargo-fuzz target that feeds malformed bytes to the PE32+ parser (`ParsedPe::parse`, `rva_to_file_offset`) and, only when the summed section mapping size and `SizeOfImage` are both at most 64 MiB, to the checked guest-memory mapping step (`load_into_memory`); nothing is executed. A 600-second local campaign (nightly cargo-fuzz, fork mode, seeded from the repository's synthetic PE fixtures, about 120,000 executions, coverage 267 edges) found two loader panics, reported to the CPU owner and not fixed here: truncated optional headers panic on out-of-range slices in `parse`, and `rva_to_file_offset` overflows `u32` when a section's address plus size exceeds 4 GiB. Run it with `rustup run nightly cargo fuzz run pe_parse`; `scripts/fuzz.sh` does not list it yet.
- Added `NativeCompute::run_words_with_group_width` and `max_group_width` to run a trusted kernel at an explicit threadgroup width, rejecting zero and widths above the device or pipeline limit. Native tests check 91 legal width and grid-size pairs (widths 1 to 1,024, including non-divisible grids) against independently computed outputs, and confirm the dispatched group sizes, including trimmed last groups. On an Apple M5 Pro, in three release runs of a 4,096-thread integer-mixing kernel (30 samples per width), widths 64, 128 and 256 were within 0.3 % of each other in two runs, at a median of 58.8 µs of GPU time. Width 512 was 5 to 6 % slower and width 1,024 about twice as slow in all three runs. The first run was about 4.7 times slower overall for reasons not determined, and in it 128 and 256 were 3 to 4 % faster than 64. The default width of 64 is unchanged. This was measured on one device and one workload.
- Added a native Metal depth pass, `NativeCompute::render_depth`: up to 16 triangles drawn in order into an RGBA8 target with an optional `Depth32Float` attachment, a chosen clear depth, a per-draw depth compare function (all eight) and depth write enable. A pass without an attachment accepts only `DepthState::DISABLED`. Colour and the stored depth are both read back; the depth values are returned as the texture read gives them, without numeric conversion. A draw can sample an original BC1 texture whose blocks are uploaded to a native `BC1_RGBA` texture without CPU decoding, gated on `supportsBCTextureCompression`. Checked on the GPU with Metal validation in 30 passes of original overlapping triangles: clear, every compare function at three depths, write enabled and disabled, depth test disabled (`Always` without writes) with an attachment and no attachment at all, and a BC1-textured draw. Colour and depth are compared per pixel against expectations derived independently from the geometry, the Metal compare semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces. These are synthetic fixtures only; no console depth formats or guest render state are involved.
- Added a CPU BC7 block decoder in `xenora-texture` for all eight modes, with explicit handling of the invalid all-zero mode byte. It is checked by hand-derived tests and 430 known-answer vectors from a separate clean-room reference written from the Khronos Data Format Specification (merged in PR #224 without a changelog entry).
- Added independent negative tests for gfx1030 extension words: truncated literal, SDWA, DPP16, DPP8 and MIMG NSA trailers (62 prefixes of 18 LLVM-assembled instructions), disallowed extensions, and length recognition kept apart from semantic validity. Tests only, with no decoder change (merged in PR #231 without a changelog entry).
- Added the gfx1030 Wave32 VOPC compares `v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32`. VCC_LO is EXEC_LO & the per-lane test, always fully written, so empty EXEC gives 0. A compare result can feed `s_cbranch_vccz`, `v_mov_b32_e32 vN, vcc_lo` and another compare's source; nothing else, so EXEC never becomes data-dependent. A data-dependent `s_cbranch_vccz` is a wave-uniform branch over integer vector ALU code, lowered to a select at the join. The Metal kernel builds each mask by recomputing the 32 lanes of its own RDNA wave, with no SIMD-group, threadgroup or barrier assumption. The reference now runs lockstep Wave32 waves. Verified on an LLVM-assembled fixture plus 251 original programs (boundary operands, partial and empty EXEC, both branch edges, a partial final wave) against exact integer definitions: translator, reference and second interpreter agree on CPU, and all 252 match on native Metal with validation. LLVM agrees on every encoding. VOP3, SDWA, DPP, `v_cmpx` and Wave64 stay rejected. See `docs/shaders/vector-compare.md`.
- Added the gfx1030 SOP2 forms `s_add_i32` and `s_sub_i32`, with SCC as signed overflow as defined in the AMD RDNA 2 ISA guide (sections 5.3 and 12.1). They are checked on CPU and on native Metal with validation on 400 boundary programs, four immediate-operand overflows and the scalar ALU fixture, plus eight hand-worked overflow and no-overflow cases on CPU.
- Added the gfx1030 SOP2 scalar forms `s_add_u32`, `s_sub_u32`, `s_addc_u32`, `s_subb_u32`, `s_and_b32`, `s_or_b32` and `s_xor_b32`. They are decoded, executed by the reference and independent interpreters, and resolved by the translator, with SCC as carry, borrow or nonzero result. `v_mov_b32_e32` can now read a normal SGPR. Verified on 1,400 original operand vectors plus an LLVM-assembled fixture, on CPU and on native Metal with validation. The other SOP2 forms stay unsupported. See `docs/shaders/scalar-alu.md`.
- Added `scripts/audit/test_inventory.py`, which lists the Cargo test inventory of two commits in temporary detached worktrees and reports removed, added, newly ignored and newly un-ignored tests, failing on any loss not explained in an `--allow` file. Run against the old PR #166 head 5450612 and main 951189c, it reports the 12 BC texture tests that head was missing (exit 1); the same commit against itself reports no change. Default features only; see `docs/testing/test-inventory.md`.
- Added complete gfx1030 instruction metadata generated from AMD's public RDNA 2 XML: 1,465 base forms across 21 encoding families with fields, operands, flags and allowed extension words. A committed, normalised snapshot lets `crates/isa/generate_rdna2_meta.py --check` verify the generated table offline; CI runs it.
- Added `xenora_isa::meta::identify`, which finds any gfx1030 instruction's form and exact length, including literal, SDWA, DPP and NSA words, and rejects truncated, unassigned and disallowed-extension encodings. It agrees with every LLVM-assembled fixture and with LLVM 23.1.6 on a probe set covering each family and extension word. Identification does not make an instruction executable: `SEMANTIC_FORMS` lists the forms with semantic decoding (46 as of the VOPC compares).
- Added `xenora shaders coverage [--json]` and `xenora shaders inspect <file>` for per-family coverage and stream listings that separate decoding failures from unsupported semantics. Each instruction is decoded at its stream offset and branch targets are checked against the whole stream's boundaries, so supported branches are no longer misreported as unsupported operands. `xenora_decoder::decode_at` decodes a single instruction for such callers.
- Added an agent task queue for the cpu, gpu, runtime, shared and qa areas: an *Agent task* issue form with priority and interface fields, a workflow that decides `/claim`, `/release`, `/reassign`, `/progress`, `/blocked`, `/unblock` and `/approve-acceptance` comments one at a time (dependency, cycle and file-overlap checks, 24-hour leases renewed by progress), a pull request check (linked claimed task, file ownership, overlap with other pull requests, independent `/verified <head sha>`), `scripts/agent-queue.sh` and `scripts/agent-sync.sh` (upstream fetch every 12 minutes, task branches in separate worktrees) and a machine-readable queue summary. The rules are standard-library Python in `scripts/agent_queue/` with unit tests in `tests/agent_queue/`; issue text is never executed and acceptance commands need maintainer approval. Only comments that start with a command start a job, so ordinary pull request comments never re-run verification, and only an accepted `/verified <full head sha>` evaluates the check again; and each claim run decides every unanswered command in order, so commands whose pending runs GitHub cancelled are still answered. See `docs/coordination/agent-tasks.md`. Unit tests pass locally; the workflows have not run on GitHub yet, and the pull request check stays advisory (it never blocks a merge) until a live smoke test and the migration of existing issues are done.
- Added explicit claim-before-work rules for contributors and coding agents to `AGENTS.md`, `CONTRIBUTING.md` and the pull request template: check for existing claims, claim with `/claim`, keep a 24-hour lease alive with `/progress`, `/release` when stopping, and link the claimed issue. Without the claim workflow, the earliest valid claim comment wins.
- Added a CPU decoder for a bounded subset of BC6H (signed and unsigned HDR) in
`xenora-texture`: the four single-subset modes (Khronos modes 3, 7, 11 and 15, Microsoft
modes 11 to 14), listed in `BC6H_SUPPORTED_MODES`, plus the reserved modes, which decode to
zero as specified. The ten two-subset modes are rejected with `Bc6hError::UnsupportedMode`
and are not implemented. Tests check hand-derived values and 128 known-answer vectors from a
separate clean-room reference decoder.
- Added native Metal upload and readback of BC4 and BC5 textures (UNORM and SNORM):
`xenora-texture` gains a pitched `BcChannelUpload`, and `NativeCompute::read_bc_channel_upload`
sends the original blocks to `BC4_R*` or `BC5_RG*` textures when the device reports BC
support, failing with `supportsBCTextureCompression` otherwise. GPU tests cover six- and
eight-value interpolation, equal and extreme endpoints (signed -128 reads as -1.0), red-green
channel order, padded row and slice pitches, two layers and two mips against the CPU decoders
and hand-derived anchors. On an Apple M5 Pro interpolated codes were within 1.71 codes of the
exact values and up to two codes from the truncating CPU reference.
Edge levels of 5×3 and 1×1 and invalid payloads (zero extents, short, oversized or
block-count-mismatched buffers) are covered.
- Added native Metal upload and readback of BC2 and BC3 textures: `xenora-texture` gains a
pitched `BcAlphaUpload` for 16-byte blocks, and `NativeCompute::read_bc_alpha_upload` sends
the original blocks to `BC2_RGBA` or `BC3_RGBA` textures when the device reports BC support.
GPU tests cover explicit and interpolated (six- and eight-value) alpha, both colour endpoint
orders, padded row and slice pitches, two layers and two mips against the CPU decoders and
hand-derived anchors. On an Apple M5 Pro the native decoder's interpolated values were within
8/7 (about 1.14) codes of the exact values, so up to two codes from the truncating CPU reference.
Edge levels of 5×3 (one block row) and 1×1 are covered, invalid payloads (zero extents,
short, oversized or block-count-mismatched buffers, bad pitches) are rejected before upload,
and `MetalError::is_capability_unavailable` separates a device without BC support from an
implementation failure.
- Added CPU block decoders for BC2, BC3, BC4 and BC5 (UNORM and SNORM) in `xenora-texture`, with tests whose expected texels were derived by hand from the Microsoft and Khronos block-compression specifications. Interpolated values truncate toward zero, as the existing BC1 decoder does; GPU upload and sampling of these formats are not implemented yet.
- Added `dbt::tests::sib_store_executes_through_the_native_dbt`, an independent DBT execution
test that runs the SIB store form `mov [rsp + 0x20], rbx` through the native ARM64 DBT and
verifies the value lands in guest memory.
- Added 8/16-bit MOV memory-operand support (opcodes 0x88/0x8A, register-to-memory and
memory-to-register) to the native ARM64 DBT.
- Added GS/FS legacy segment prefix support to the native DBT and the bounded x86-64
interpreter, including `CpuState.gs_base`/`CpuState.fs_base` offsets added to the effective
address computation.
- Added Win64 TEB allocation and `gs_base` initialization to synthetic guest startup.
### Changed
- Registering an import key twice is now an error instead of silently replacing the first service, ordinals are distinct from names, and API sets in the import generator match exactly instead of by prefix.
- `GetSystemTimeAsFileTime` now stops the guest on a null pointer, as on any other invalid pointer, instead of setting the last error.
- Simplified the claim rules in `AGENTS.md`, `CONTRIBUTING.md` and the pull request template at the maintainer's request: claim an issue by replying on it in plain words, never claim over an existing claim, and treat a claim as stale only after about one week without a pull request. The task-queue lease (`lease_hours` in `.github/agent-queue.json`) is now 168 hours to match, and `docs/coordination/agent-tasks.md` marks the queue commands as optional.
- The static PE probe now marks x86-64 SIB memory addressing as DBT-supported, matching the
native DBT.
### Fixed
- `MockClock::advance` no longer wraps the FILETIME. A large advance made the synthetic wall clock run backwards while the performance count beside it stopped at its maximum; both now stop at their maximum (#204).
- Fixed `DuplicateHandle` and `GetThreadId` naming the main thread from other guest threads, `OwningThread` in critical sections always holding the main thread's ID, the callback-depth limit being shared by all guest threads, and pending one-time initializations being unbounded.
- Fixed the address reported when a guest memory access faults part-way across a 4 KiB page boundary (#175). An access that starts in a mapped page and runs into an unmapped or forbidden one now reports the first byte it may not touch; it used to report the start of the access. An access whose first byte fails reports the same address as before, and a failed access still reads and writes nothing. Three Intel SDM page-fault cases in `cpu_known_answers.rs` moved from open defect to verified on both engines. `crates/loader/tests/memory_page_boundaries.rs` checks permissions, adjacent pages, address overflow and the fault address at every 4 KiB guest boundary across two host pages (16 KiB each on Apple Silicon). Guest memory is checked in software, so the host page size does not affect these results. Four #82 expectations and one CRT `memmove` expectation that pinned the start address were corrected. Not compared with x86 hardware; awaiting independent review.
- Fixed the native dependency audit reading Cargo JSON and inspection-tool output in the process locale encoding; it now reads and reports UTF-8 paths and diagnostics under an ASCII locale (#363).
- Fixed a latent ARM64 `LSLV` encoding bug that forced bit 1 of the shift-count register field (part of #131). The dynamic binary translator uses `X10` in its only call, which already has that bit set. `RBIT`, `CLZ` and `LSLV` now panic on out-of-range register numbers before emitting an instruction. Encoding tests use words checked against LLVM's assembler.
- Fixed flat (untextured) guest `DrawInstanced` draws in the synthetic D3D12-style graphics context (#148). A draw with zero instances or fewer than three vertices now draws nothing. A non-zero start vertex or start instance, more than one instance or more than three vertices now fails with `GraphicsError::Unsupported` instead of drawing the view's first triangle. Vertex reads stay inside the vertex buffer, so a view past its end, or one whose guest address would overflow, fails with `IndexOutOfRange` instead of reading neighbouring guest memory or panicking. `crates/loader/tests/repeated_frames.rs` runs these through repeated reset, record, close and execute frames on the software reference backend, with hand-derived pixels; no native Metal result is claimed.
- Made the static probe and the binder share one bounded import parser, after the truncated-name fix for #270. Truncated, unterminated, empty or non-ASCII names, reserved bits and endless tables are reported by the probe and refused by the binder.
- Fixed TLS callback metadata that was accepted or misread without an error (#78). A non-zero `AddressOfCallbacks` outside the image's sections, or 4 GiB or more above the image base, is now refused; it used to mean "no callbacks" or read the list from an unrelated place. The callback list must reach its null entry inside its section, where the section's zero-filled tail counts, and a list of more than 64 callbacks is refused where it used to be cut short. `execute_tls_callbacks` refuses a stack top that is not 16-byte aligned or cannot hold the entry frame, which used to overflow a subtraction, and a file cut inside the TLS data-directory entry no longer panics the parser. `TlsError` gains four variants for these cases. Twelve unit tests in `crates/loader/src/tls.rs` use original headers and code, and also check the argument registers, the stack pointer at entry and after return, callback order and the instruction budget. Expectations come from Microsoft's public PE Format and x64 calling convention pages; nothing ran on Windows, and independent review is pending.
- Fixed the thread's TLS pointer naming the TLS data itself (#76). Compiled code loads the pointer from the thread environment block, indexes it by the module's TLS index to get the address of the data block, and then adds a variable's offset; the loader had mapped the data where the pointer array belongs, so the first eight bytes of the template were used as the block address. `setup_tls` now maps a pointer array at the thread's TLS base and the data block one page above it, and stores the block address in the slot of the index it assigns. `crates/loader/tests/tls_layout.rs` follows that access sequence through guest memory for a template with zero fill, a rebased image and a zero-fill-only directory. The data block of the fixture harness can now be at most 60 KiB, down from 64 KiB, before it would meet the thread environment block. Alignment requests above 4 KiB and more than one module's TLS are not handled. The access sequence follows Microsoft's public PE Format page; nothing ran on Windows, and independent review is pending.
- Fixed the MXCSR flags of an unmasked floating-point overflow whose result is exact before the exponent is bounded, such as the largest binary32 value times two (#128). Only the overflow flag is set; the precision flag used to be set as well although nothing was rounded. A masked overflow still sets both flags and delivers infinity or the largest finite value, and an unmasked overflow that is also inexact still sets both. Five Intel SDM cases in `cpu_known_answers.rs` moved from open defect to verified on both engines, with three more for the other rounding modes, and the scalar and conversion sweeps now compare the precision flag in this case as well. Not compared with x86 hardware; awaiting independent review.
- Fixed the decoder refusing an instruction whose REX prefix is followed by a legacy prefix (#69). Such a REX is ignored, as the Intel SDM (Vol. 2A, 2.2.1) specifies, so `48 66 01 D8` now runs as `add ax, bx`; it used to stop the guest with an illegal-instruction exit. The ignored byte still counts toward the instruction's length, and a REX that directly precedes the opcode behaves as before. The interpreter, the DBT and the static probe share the decoder. One SDM-derived case in `cpu_known_answers.rs` moved from refused to verified and three were added, for an ignored REX.B, an ignored REX.W before a segment prefix, and a later REX that does apply. Two REX bytes in a row and the address-size prefix stay rejected. Not compared with x86 hardware; awaiting independent review.
- Fixed import binding writing some slots before finding an unresolved import, and service calls taking effect before an unreadable return address was noticed. A service that changes a nonvolatile register, including XMM6 to XMM15, now stops the guest (part of #201).
- Fixed older import-generator templates that reported success for unimplemented wrappers, used a nonexistent exit reason, and read floating-point arguments from integer registers.
- Fixed guest flags in the native DBT (#64, #70). They lived only in host NZCV, so they were lost across helper calls and block boundaries and register ADD, SUB and XOR set none. JB, JAE, JBE and JA used ARM carry polarity, which is inverted for subtraction. Flags are now stored in the guest state.
- Fixed the static probe reporting support for forms an engine rejects, including NOP, TEST, most conditional branches and the FF group in the interpreter.
- Fixed the native DBT's `SXTW` encoding, which set bit 3 of the source register and was right only for registers that already had it set; the previous test used such a register by chance.
- Fixed 32-bit guest stores and loads in the native DBT (MOV 89/8B and C7 /0), which accessed eight bytes: stores overwrote the next four guest bytes and accesses at the end of a mapping faulted. RIP-relative operands of byte moves and extensions, which were read as RBP-relative, and LEA with a segment prefix, which added the segment base, are fixed too.
- Fixed an x86 prefix-length test that read an untracked fuzz artifact and so failed on every fresh checkout; its input is now inline.
- Fixed agent-queue `apply_actions` crashing on comment-only decisions (claim refusals) by skipping no-op `gh issue edit` calls; accept `summary --now` after the subcommand; grant the audit job `pull-requests: read` so live audits can list open PRs (issue #180).
- Fixed `scripts/audit/status.py` and the Python embedded in `scripts/audit/claims.sh` reading and writing tracked files in the process locale encoding instead of UTF-8: under an ASCII or cp1252 locale the status check crashed on `docs/claims.toml` or reported a spurious `xenora-progress.svg` difference. Both scripts now pass `encoding="utf-8"`, as the rest of `scripts/` does, the two write sites also pin `newline="\n"` so a Windows host cannot turn tracked LF files into CRLF when it regenerates them, and CI runs the two checks again under a non-UTF-8 locale so the requirement stays enforced.
- Generated CRT adapters now report unsupported calls when the required guest ABI or runtime behavior is missing.
- Win64 service argument decoding reports a guest memory error when a stack argument offset overflows.
- Fixed `xenora_isa::meta::identify` reading six VOP3 interpolation forms (`v_interp_p1_f32_e64`, `v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`, `v_interp_p1ll_f16`, `v_interp_p1lv_f16`, `v_interp_p2_f16`) as 12 bytes when SRC0 is 255. In these forms SRC0 holds attribute bit-fields, not an operand selector (AMD RDNA 2 ISA guide section 10.4.2; XML operand type `OPR_ATTR`), so SRC0 = 255 no longer adds a literal word. The six corpus probes are now 8 bytes, as LLVM 23.1.6 also decodes them. The six pinned `mismatch` rows in the LLVM corpus check are gone: one now agrees fully, and five are `operand_flagged` (same instruction and length; LLVM flags an operand).
- Updated `test_probe_static_analysis_does_not_execute_code`: the SIB store `mov [rsp + 0x20],
rbx` at RVA 0x1004 is now genuinely supported by the native DBT (verified by the independent
execution test above), so the probe reports no blocker for this program.
- Added `test_probe_static_analysis_detects_genuinely_unsupported_instruction` with a new
synthetic fixture containing an INT3 at RVA 0x1004, preserving blocker-detection coverage
for genuinely unsupported DBT instructions.
## [X18] - Automated Import Compatibility Generation & Metadata Ingestion
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
remains unsupported.
### Added
- Added `xenora-import-gen` deterministic code generation crate and `xenora imports generate <--pe <exe> | --csv <file>> [--out <dir>]` CLI command. Automatically extracts imported symbols from PE executables or CSV manifests, classifies them against a built-in offline database of documented public Win32/CRT and ISO C specifications without consuming AI tokens or network resources, maps compatible CRT functions to native macOS libc ABI adapters with guest memory bounds checking, generates logged Win32 service stubs, generates deterministic conformance test suites, and produces coverage reports in both Markdown and CSV format.
- Added automated metadata ingestion (`ingest_standard_system_headers`) and `xenora imports metadata sync` command capable of parsing real POSIX/C system headers into typed `MetadataCatalog` definitions (188 entries).
- Added `xenora imports verify` automated behavioral verification runner checking CRT math, string, and memory bounds invariants across 12 independent behavioral test cases.
- Added explicit failure semantics for unsupported stubs returning `ExitReason::IllegalInstruction(0xFE)` rather than fabricated success.
- Added public registration helper `ImportRegistry::register_with_status` and runtime integration test verifying generated bindings and stub failure semantics.
- Added 8-bit and 16-bit guest memory access helpers (`read_u8`, `write_u8`, `read_u16`, `write_u16`) to `xenora-loader::GuestMemory`.
- Added guest-facing D3D12-style graphics runtime interfaces (`GraphicsContext`, `GraphicsDevice`, `GraphicsCommandQueue`, `GraphicsCommandAllocator`, `GraphicsCommandList`, `GraphicsResource`) with explicit backend selection (`GraphicsBackendId::MetalNative` vs `GraphicsBackendId::SoftwareReference`). Original PE32+ integration tests verify device creation, generation-checked handle ownership, command recording, barriers, and presentation.
- Connected guest execution via ARM64 DBT and IAT dispatch to native Apple Silicon Metal rendering (`test_guest_dbt_graphics_pipeline_metal_render_dual_inputs`), proving that different guest vertex positions and clear colors produce distinct, verified GPU-rendered framebuffers with active Metal validation on Apple M5.
- Added explicit test graphics service exports (`xenora_fixture.dll!CreateGraphicsDevice`, `xenora_fixture.dll!SubmitGuestDraw`) cleanly separated from unsupported production Xbox ABI claims.
- Added control-flow-aware x86-64 static PE probe using worklist CFG traversal, eliminating false-positive startup blocker reports on unreachable INT3 padding.
- Added `xenora imports sync` command with `--check` verification mode for automated, idempotent import compatibility backlog generation.
- Added current-process handle and ID queries and a readable priority boost policy for the synthetic guest process. Original PE fixtures verify Win64 arguments, state changes and errors through imported calls.
- Static import reports identify canonical bindings, API-set aliases, implemented and partial handlers, existing stubs, and missing services.
- Added a single startup path for original PE32+ fixtures that maps and rebases the image, binds imports before running thread-local storage callbacks, then enters the guest.
- The static PE probe compares ordinary imports with the standard synthetic registry and exports unresolved DLL, symbol or ordinal, and import slot addresses to `missing_imports.csv`.
- Added synthetic PE32+ runtime support for 64-bit base relocations, thread-local storage setup and callbacks, Windows x64 calling convention arguments, and import binding to a limited service registry. The Xbox-style allocation service maps guest memory. Its free entry point remains a stub.
- Extended native ARM64 dynamic binary translation with selected memory addressing, immediate stores, register increments and decrements, and indirect control flow through guest import slots.
- Added runtime fixtures for rebasing, ordered callbacks, deterministic timing, guest memory allocation, and mock import dispatch. The GPU gate checks every pixel from a native offscreen draw through a synthetic import.
- Added a static PE compatibility probe that exports section, relocation, thread-local storage, import and bounded x86-64 entry-point analysis. Synthetic tests cover inspection and report export.
- Added native Apple Silicon ARM64 Dynamic Binary Translation (DBT) engine (`DbtEngine`) with basic block decoding, native ARM64 code lowering, and W^X-compliant JIT code cache (`JitMemory`) utilizing macOS `MAP_JIT` and `pthread_jit_write_protect_np`.
- Added an ARM64 machine instruction assembler (`Arm64Assembler`) supporting register/immediate arithmetic, logical operations, memory loads/stores, branch/call/ret control flow, and calling convention preservation.
- Added synthetic guest graphics service dispatch connecting guest x86-64 execution through native ARM64 translated blocks directly to Xenora's Metal graphics pipeline (`NativeCompute::render_rgba8`), producing and independently checking the first guest-rendered frame.
- Added Scale-Index-Base (SIB) memory addressing mode support to `xenora-loader`'s x86-64 interpreter (`[base + index*scale + disp]`) for general-purpose memory operand resolution.
- Added synthetic test fixture `test_sib_addressing_mode` verifying SIB stack-relative memory loads and stores in software interpretation.
- Added `xenora-loader` crate providing standalone PE32+ (64-bit Portable Executable) parsing, isolated guest virtual memory with strict page permissions (Read/Write/Execute), bounded software x86-64 instruction interpreter (`CpuState`, `Interpreter`, `RFlags`), and read-only diagnostic triage (`triage_file`, `triage_bytes`).
- Added CLI inspect command (`xenora inspect <path>`) for read-only PE32+ header and section structure examination.
- Added comprehensive integration tests verifying synthetic PE32+ image mapping, register arithmetic, stack push/pop, subroutine calls/returns, deterministic unsupported opcode rejection, memory fault on unmapped access, and execution budget enforcement.
- Added native Metal sampler abstraction (`MetalSampler`) supporting nearest-neighbor minification/magnification filtering, clamp-to-edge addressing, normalized coordinates, validated LOD bounds, and explicit `SamplerDesc` mapping.
- Added native Metal RGBA8 2D texture allocation, mip upload validation (`MetalRgba8Texture`, `Rgba8MipLevel`, `Rgba8TextureDesc`), and texture/sampler pipeline binding definitions (`BoundSampledTexture`, `BindingSlot`) for future translated shader stages.
- Added an independent pure-Rust CPU texture sampling reference for deterministic RGBA8 2D textures with nearest-neighbor filtering, normalized UV coordinates, clamp-to-edge addressing, explicit mip selection, and bounds validation.
@@ -47,6 +475,13 @@ remains unsupported.
### Fixed
- Fixed the intermittent failure of the frame-loop memory-footprint test (#290). Each frame-loop session opened its own Metal command queue. The first command buffer on a queue makes the GPU driver allocate a working set for it (about 45 MiB on an Apple M5 with Metal validation), and the driver frees it asynchronously 10–50 ms after the queue is released, so the process footprint read right after a session ended depended on how far that release had got. Measured immediately after each of 50 destroys, it ranged from 45 to 96 MiB; the unchanged test failed 5 times in 30 runs, with up to 26 MiB of apparent growth. There was no leak: one second after each destroy the footprint was back at the same floor every time. Frame-loop sessions now share one process-wide Metal device and command queue, so the working set is allocated once and kept: the same readings stay within 93–98 MiB across 50 sessions, and the unchanged test passed 30 runs in a row (largest growth 0.31 MiB). The cost is that the process keeps that GPU memory (about 50 MiB with validation, 58 MiB total footprint without) after its first frame loop. A new 50-session test (normal completion, pause and resume, destroy while running) checks the readings stay within 16 MiB; it fails without the fix.
- Stop ignoring `fixtures/pe/trusted-runner.exe`. The runner embeds it with `include_bytes!`, so ignoring the file made a fresh checkout fail to compile.
- Corrected the ARM64 STP pre-index encoder, which had a hardcoded -32-byte immediate and therefore adjusted the host stack by the wrong amount once the translator frame grew to 48 bytes. The wrong frame silently corrupted the caller's stack and caused SIGSEGV in every native translation test. Emitter encodings are now checked against LLVM's assembler, and a test asserts that each translated block opens and closes the same 48-byte frame.
- Translated guest memory faults now stop the block before it commits further architectural effects. A faulting push, call or store leaves guest RSP and registers unchanged, the reported instruction count covers only completed work, and guest RIP identifies the faulting instruction. Previously the block continued after the helper recorded a fault, so later instructions and writes still took effect.
- Compute the static PE probe SHA-256 from the full input, including trailing bytes.
- Report TLS callbacks that halt or exhaust their execution budget as failures. Reject unsupported 32-bit increment and decrement forms in the native translator.
- Reject unknown guest experiment arguments with a nonzero exit status.
- Validate branch targets, buffer bindings, and program termination throughout a shader fixture, including instructions skipped by a resolved branch.
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+2 -2
View File
@@ -1,6 +1,6 @@
# Code of Conduct
Xenora welcomes contributors with different backgrounds and experience levels. Discussions should be about the technical work and conducted with respect.
BetterXen welcomes contributors with different backgrounds and experience levels. Discussions should be about the technical work and conducted with respect.
## Expected behavior
@@ -19,4 +19,4 @@ If possible, use an available private contact channel for a repository maintaine
Maintainers may remove content, limit participation or block accounts when necessary to protect the community. Responses should be proportionate to the behavior and protect the privacy of affected people. Do not retaliate against anyone reporting a concern in good faith.
This policy applies to repository issues, pull requests, discussions and other spaces officially managed by Xenora.
This policy applies to repository issues, pull requests, discussions and other spaces officially managed by BetterXen.
+33 -40
View File
@@ -1,59 +1,52 @@
# Contributing to Xenora
# Contributing to BetterXen
Xenora is an experimental Xbox Series X|S recompilation framework for Apple Silicon. Its graphics subsystem, XenoMetal, targets native Metal execution. Contributions should improve verified behavior rather than expand untested claims.
BetterXen is a modular, CrossOver-based Xbox Series (`Scarlett`) compatibility layer for Apple Silicon macOS. Contributions are organized into **6 parallel tracks** so 5–8+ human contributors and coding agents can work simultaneously without merge conflicts.
## Getting started
## Active Work & Track Ownership
- Read `README.md` and, when present, `AGENTS.md`, `docs/interfaces.md`, `docs/status.toml` and the relevant architecture decisions.
- Discuss substantial changes in an issue before implementing them; small fixes do not require prior approval.
- Use a native ARM64 macOS environment with Rust and the appropriate Xcode/Metal tools. LLVM AMDGPU tools are needed for ISA fixture generation; extra tooling depends on the subsystem.
- Keep changes focused and preserve existing public interfaces unless a change is justified and documented.
The single authoritative plan is [docs/roadmap.md](docs/roadmap.md) (Milestones M0–M6), supported by [docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md) and the ready-to-claim Wave 1 issues in [docs/issues/wave-1-backlog.md](docs/issues/wave-1-backlog.md). The earlier native-first workspace was retired from `main` per [ADR 0006](docs/adr/0006-retire-in-tree-native-workspace.md) and remains preserved permanently at Git tag `native-first-final`.
## Development and verification
1. Pick an open unclaimed issue on your track (A–F) using `.github/ISSUE_TEMPLATE/track-handoff.yml`.
2. Check all comments and open PRs, then claim in plain text (`Claiming — branch: track-<a..f>/<issue>-<slug>`). A claim with no commits or PR after 7 days is stale and may be taken over with a reply saying so.
3. Work in a dedicated branch or `git worktree` and stay strictly inside the issue's **exclusive file scope**.
4. If your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first. Once merged, both tracks implement in parallel.
5. Add new synthetic PE32+ conformance binaries under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake — no shared-file edits needed).
When the Cargo workspace exists, run from its root:
## Development & Verification
Requirements on Apple Silicon macOS: Rust 1.85+ (`aarch64-apple-darwin`), `mingw-w64` & `cmake` (`brew install mingw-w64 cmake`), Python 3.11+, Rosetta 2, and CrossOver 26.3+ (externally installed, never bundled).
Run these checks before opening a PR:
```sh
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace
cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
cargo build --locked -p bx-cli && lipo -archs target/debug/bx-cli
scripts/build-shims.sh
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_veh_clwb.exe
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_shim_exports.exe
python3 scripts/audit/docs_hygiene.py
```
Follow repository documentation for actual GPU tests, fuzzing, mutation testing and benchmarks. Report commands, versions, pass/fail/skip counts and hardware used. A successful shader compile is not successful GPU execution. Do not report unavailable tools or skipped tests as passes.
Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/skip counts. Never report a skipped test or unavailable tool as a pass.
For an instruction or compiler change, cite the applicable ISA section, state the exact architecture, document operand and execution-mask semantics, and add tests for encodings, edge cases, unsupported cases and independent expected results. Where applicable, verify the resulting MSL through actual Metal execution. Do not convert unsupported instructions into silent no-ops.
## Clean-Room, Licensing & Provenance Policy
For a performance change, provide reproducible before-and-after results using equivalent inputs, hardware and settings. For a new dependency, explain why it is needed, verify its license and native ARM64 compatibility, and record its provenance.
- Use publicly accessible specifications, publicly licensed software, and independently authored synthetic workloads only. Never submit leaked executables or SDKs, confidential Xbox documentation, firmware, keys, proprietary game binaries, or unauthorized shader dumps.
- Under BetterXen's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs.
- Before incorporating third-party code, verify **per-file** license compatibility with `GPL-3.0-or-later`, record provenance in [docs/research/upstream-registry.md](docs/research/upstream-registry.md) and [docs/research/component-reuse-matrix.md](docs/research/component-reuse-matrix.md), preserve copyright notices, and update [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). Public visibility or a GPL license does not clear code derived from leaked material.
- Never bundle or redistribute proprietary components (CrossOver, D3DMetal, Rosetta 2).
- Never claim Xbox hardware verification (BetterXen has no Xbox hardware access) or independent certification of your own work; classify evidence per [docs/claims.toml](docs/claims.toml).
## Research and clean-room policy
## Pull Requests & DCO Sign-Off
Use publicly accessible specifications and authorized materials only. Do not submit leaked SDKs, confidential documentation, firmware, keys, proprietary game binaries or unauthorized shader dumps. Under Xenora's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs.
Distinguish desktop RDNA behavior from Xbox-specific behavior. Cite primary sources with exact applicable architectures and record uncertainties using the project's evidence classification when available. Tests on Apple GPUs do not establish verification on Xbox hardware.
Xenora implements its own Rust guest runtime, decoder, typed IR, shader
compiler and native Metal backend from public technical specifications
and independently derived tests. Contributions must not copy, port or
adapt code, decoder tables, internal metadata or implementation
architecture from other emulators. External results can inform test
selection. Author the resulting code and fixtures independently.
Before incorporating third-party code, verify per-file license compatibility with GPL-3.0-or-later, record the exact upstream revision and original paths, preserve copyright notices and document changes. Update applicable attribution records. Public visibility alone is not proof of authorization or license compatibility.
## Pull requests
- Branch from the current main branch, keep commits focused, and link relevant issues.
- Include a clear explanation, tests and any documentation/status updates. Separate unverified work from supported behavior.
- Disclose material AI assistance and personally review generated changes. AI output is not an authoritative source, test oracle or substitute for independent review.
- Never include secrets, personal paths, credentials or private data in patches or logs.
- Do not claim approval from an independent reviewer unless one has actually reviewed the change.
Sign off each commit under the [Developer Certificate of Origin](https://developercertificate.org/):
- Branch from `main`, keep changes focused inside your track scope, link the issue with `Closes #<number>`, update [CHANGELOG.md](CHANGELOG.md) under `[Unreleased]`, and update [docs/README.md](docs/README.md) when adding or reorganizing docs.
- Disclose material AI assistance and personally review generated changes. Never include secrets, personal paths, or credentials in patches or logs.
- Sign off every commit under the [Developer Certificate of Origin](https://developercertificate.org/):
```sh
git commit -s -m "Describe the change"
```
Use your configured Git identity and a privacy-preserving email address if desired. Sign-off is your certification of the contribution; do not sign off work on another person's behalf. Contributions are subject to the repository license and any applicable, compatible third-party notices.
For security-sensitive findings, see [SECURITY.md](SECURITY.md). Community expectations are in [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
See [AGENTS.md](AGENTS.md), [docs/legal.md](docs/legal.md), [SECURITY.md](SECURITY.md), and [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
Generated
+32 -126
View File
@@ -3,130 +3,36 @@
version = 4
[[package]]
name = "bitflags"
version = "2.13.2"
name = "bx-cli"
version = "0.2.0"
dependencies = [
"bx-probe",
"bx-telemetry",
"dxbc-accc",
"libc",
]
[[package]]
name = "bx-probe"
version = "0.2.0"
[[package]]
name = "bx-telemetry"
version = "0.2.0"
[[package]]
name = "d3dmetal-harness"
version = "0.2.0"
dependencies = [
"dxbc-accc",
]
[[package]]
name = "dxbc-accc"
version = "0.2.0"
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "dispatch2"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
dependencies = [
"bitflags",
"objc2",
]
[[package]]
name = "objc2"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"
dependencies = [
"objc2-encode",
]
[[package]]
name = "objc2-core-foundation"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
dependencies = [
"bitflags",
"dispatch2",
"objc2",
]
[[package]]
name = "objc2-encode"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
[[package]]
name = "objc2-foundation"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [
"bitflags",
"objc2",
]
[[package]]
name = "objc2-metal"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"
dependencies = [
"bitflags",
"objc2",
"objc2-core-foundation",
"objc2-foundation",
]
[[package]]
name = "xenora"
version = "0.1.0"
dependencies = [
"xenora-metal",
"xenora-ref",
"xenora-shader",
]
[[package]]
name = "xenora-benchmarks"
version = "0.1.0"
dependencies = [
"xenora-metal",
"xenora-ref",
"xenora-shader",
]
[[package]]
name = "xenora-decoder"
version = "0.1.0"
dependencies = [
"xenora-isa",
"xenora-ref",
]
[[package]]
name = "xenora-isa"
version = "0.1.0"
[[package]]
name = "xenora-metal"
version = "0.1.0"
dependencies = [
"objc2",
"objc2-foundation",
"objc2-metal",
"xenora-shader",
"xenora-texture",
]
[[package]]
name = "xenora-ref"
version = "0.1.0"
[[package]]
name = "xenora-semantic-review"
version = "0.1.0"
dependencies = [
"xenora-metal",
"xenora-ref",
"xenora-shader",
]
[[package]]
name = "xenora-shader"
version = "0.1.0"
dependencies = [
"xenora-decoder",
]
[[package]]
name = "xenora-texture"
version = "0.1.0"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
+14 -3
View File
@@ -1,12 +1,23 @@
[workspace]
members = ["crates/*", "tests/validation", "benchmarks"]
members = [
"launcher/crates/bx-cli",
"launcher/crates/bx-probe",
"launcher/crates/bx-telemetry",
"shader-transpiler/crates/d3dmetal-harness",
"shader-transpiler/crates/dxbc-accc",
]
exclude = ["legacy-native"]
resolver = "3"
[workspace.package]
version = "0.1.0"
version = "0.2.0"
edition = "2024"
license = "GPL-3.0-or-later"
rust-version = "1.100"
rust-version = "1.85"
[workspace.lints.rust]
unsafe_op_in_unsafe_fn = "deny"
[profile.release]
lto = "thin"
codegen-units = 1
+165 -325
View File
@@ -1,394 +1,234 @@
# Xenora
<div align="center">
**Experimental Xbox Series X|S emulation research for Apple Silicon Macs.**
# BetterXen
Xenora is an open-source project written primarily in Rust, exploring native Xbox Series X|S compatibility on ARM64 macOS.
**Modular Xbox Series (`Scarlett`) compatibility layer for Apple Silicon macOS — built on CrossOver, Rosetta 2, and D3DMetal 3.0.**
The project combines a bounded x86-64 guest execution environment, Portable Executable (PE32+) loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend.
[![Hybrid build and shim checks](https://github.com/MacosPorters/betterxen/actions/workflows/hybrid-ci.yml/badge.svg?branch=main)](https://github.com/MacosPorters/betterxen/actions/workflows/hybrid-ci.yml)
[![Repository hygiene](https://github.com/MacosPorters/betterxen/actions/workflows/hygiene.yml/badge.svg?branch=main)](https://github.com/MacosPorters/betterxen/actions/workflows/hygiene.yml)
![Platform: Apple Silicon](https://img.shields.io/badge/platform-Apple%20Silicon%20(ARM64)-1f6feb?logo=apple&logoColor=white)
![Graphics: D3DMetal 3.0](https://img.shields.io/badge/graphics-D3DMetal%203.0%20%2F%20Metal-8957e5)
![Stack: Rust + C++20 PE32+](https://img.shields.io/badge/stack-Rust%20%2B%20C%2B%2B20%20PE32%2B-dea584)
![Status: experimental](https://img.shields.io/badge/status-experimental%20(M2)-0969da)
![License: GPL-3.0-or-later](https://img.shields.io/badge/license-GPL--3.0--or--later-2ea043)
**No Wine. No CrossOver. No Rosetta. No Vulkan runtime.**
</div>
Xenora is still experimental. It currently executes independently authored synthetic guest programs and shaders. **Commercial Xbox games, including Grand Theft Auto VI, do not boot.** Authentic Xbox executable loading and system-service compatibility remain unsupported.
> [!IMPORTANT]
> **Experimental status.** BetterXen is an active, open-source compatibility engineering project with **Milestone M0 and Milestone M1 verified complete** on synthetic PE32+ workloads under CrossOver 26.3 + Rosetta 2, and **Milestone M2** (`First Rendered Frame & Shader Format Gate`) currently active. **Commercial Xbox game execution is not yet supported.** CrossOver, Rosetta 2, and D3DMetal are externally installed dependencies and are never bundled or redistributed.
[![Native Rust checks](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml)
BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Rosetta 2**, and **D3DMetal 3.0** on Apple Silicon:
- **Native ARM64 macOS tooling** (`launcher/`, Rust) for host diagnostics, PE32+ static probing, CrossOver bottle orchestration, and structured trace aggregation.
- **Cross-compiled x86-64 Windows PE32+ shim DLLs** (`shims/`, C++20 via `mingw-w64`) implementing Xbox runtime APIs (`xmem`, `XCRDAPI`, `d3d12_xs`, `xg_xs`, `xgameruntime`, `GameInput`, `AcpHal`/`xapu`/`chad`, Win32/PSM forwarders, and a `clwb` Vectored Exception Handler).
- **Shader pipeline** (`shader-transpiler/`, Rust) for classifying `DXBC` containers (`DXIL` vs. `ACCC`/`FSPX` RDNA 2 machine code) and handling console shader translation where required.
> [!CAUTION]
> **Clean-room and anti-piracy policy.** BetterXen strictly opposes piracy and does not distribute copyrighted game files, firmware, decryption keys, or DRM circumvention tooling. Zero proprietary binaries, assets, or leaked materials are permitted in this repository or its Git history. All in-repo tests use independently authored synthetic PE32+ workloads.
---
## What works today?
## Progress Tracker
Xenora has progressed from executing individual x86-64 instructions to running original PE32+ guest programs that interact with translated GPU workloads on Apple Silicon.
The latest verified milestone includes **translated gfx1030 vertex and pixel shaders executing through native Apple Metal**, with rendered pixels compared against independently calculated reference results.
### Development milestones
| Milestone | Implementation | Status |
| --- | --- | --- |
| X1 — Guest CPU | Bounded x86-64 instruction execution on ARM64 macOS | Verified |
| X2 — Executable loading | Loading original fixed-base PE32+ test executables | Verified |
| X3 — GPU compute | Guest-submitted Metal compute workloads and readback | Verified |
| X4 — Metal rendering | Guest-driven offscreen rendering using authored Metal shaders | Verified |
| X5 — Guest execution expansion | Additional bounded CPU execution and fixture coverage | Implemented |
| X6 — Guest control flow | Nested calls, returns, checked memory and synthetic PE execution | Verified |
| X7 — Imported services | Named imports, guest-to-host service dispatch and result validation | Verified |
| X8 — Translated compute | Original gfx1030 compute shaders executing on Metal, partial Wave32 handling and BC1 readback | Verified subset |
| X9 — Translated graphics | Persistent resource handles, translated vertex/pixel stages and offscreen Metal rendering | Verified subset |
| X10 — Texture sampling | Translate RDNA2 image instructions, implement samplers, mipmapping and guest-backed texture bindings | Planned |
| X11 — Graphics pipeline | Multiple draw calls, vertex buffers, index buffers, depth/stencil testing, blending and render targets | Planned |
| X12 — Wave execution | Expand Wave32/Wave64 semantics, divergent control flow, cross-lane operations, LDS and barriers | Planned |
| X13 — Advanced shaders | Mesh, geometry and additional compute shader capabilities with verified Metal execution | Planned |
| X14 — CPU recompilation | Introduce an ARM64 dynamic recompiler (JIT) for supported x86-64 instructions, with interpreter fallback | Planned |
| X15 — Executable compatibility | PE relocations, TLS, DLL loading, exception handling, imports and executable initialization | Planned |
| X16 — Guest memory and threading | Virtual memory mapping, thread scheduling, synchronization primitives and atomic operations | Planned |
| X17 — System services | Implement a tested subset of Xbox-compatible runtime APIs, memory services, filesystem access and application lifecycle | Planned |
| X18 — Graphics API translation | Translate supported Xbox graphics commands, resource descriptors, command queues, barriers and fences into Metal operations | Planned |
| X19 — Advanced GPU features | Indirect rendering, asynchronous compute, additional texture formats and ray-tracing compatibility research | Planned |
| X20 — Integrated guest runtime | Connect CPU recompilation, executable loading, system services and graphics translation into one persistent runtime | Planned |
| X21 — Application compatibility | Execute increasingly complex independently authored applications through the complete guest CPU and GPU pipeline | Planned |
| X22 — First application boot | Establish a reproducible startup and error-reporting path for supported game-like applications | Planned |
| X23 — Initial game compatibility | Investigate startup and execution of legally supported game software, identifying missing runtime and graphics behavior | Long-term goal |
| X24 — Gameplay and performance | Expand rendering correctness, input, audio, memory management, shader caching and execution performance | Long-term goal |
| X25 — Running games | Achieve reproducible, stable execution of compatible games on native Apple Silicon macOS using Metal | Long-term goal |
**Roadmap note:** X10–X25 are proposed engineering milestones, not completed implementations or a guaranteed sequence. Actual priorities will change as compatibility testing reveals new blockers. Successfully completing one milestone does not guarantee that a particular game will run.
All existing verification refers to independently authored synthetic programs and shaders. Commercial-game compatibility remains unverified.
See the [X9 acceptance matrix](docs/testing/x9-acceptance.md) for specific tests, results and unsupported behavior.
## Native graphics translation
Xenora's graphics pipeline translates a supported subset of AMD RDNA 2 instructions into Metal Shading Language.
The translation process is:
> *Tracks engineering milestones and synthetic conformance progress only — not commercial game compatibility percentages.*
```mermaid
flowchart LR
M0["M0: Foundation & Shims\n(Verified Complete)"]:::done
M1["M1: Boot to D3D12\n(Verified Complete — 16/16)"]:::done
M2["M2: First Frame &\nShader Gate\n(Active — Milestone #18)"]:::active
M3["M3: Shaders &\nTexture Tiling"]:::planned
M4["M4: 3D, DXR/BVH\n& Input"]:::planned
M5["M5: Audio, Saves\n& Stability"]:::planned
M6["M6: Cache & 16 GB\nOptimization"]:::planned
flowchart TD
A["Original gfx1030 Machine Code"]
B["RDNA2 ISA Decoder"]
C["Validated Shader IR"]
D["Metal Shader Generation (MSL)"]
E["Native Metal Pipeline"]
F["Apple Silicon GPU"]
G["GPU Readback"]
H["Independent CPU Validation"]
M0 --> M1 --> M2 --> M3 --> M4 --> M5 --> M6
A --> B
B --> C
C --> D
D --> E
E --> F
F --> G
G --> H
classDef done fill:#dafbe1,stroke:#1a7f37,color:#0f5323,stroke-width:2px
classDef active fill:#ddf4ff,stroke:#0969da,color:#0a3069,stroke-width:2px
classDef planned fill:#f6f8fa,stroke:#8c959f,color:#57606a
```
The initial implementation focused on compute shaders. X9 extends this to actual translated **vertex and fragment/pixel shader stages**.
Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
### Translated rendering
### Active Milestone — [M2: First Rendered Frame & Shader Format Gate](https://github.com/MacosPorters/betterxen/milestone/18)
The current graphics subset supports:
| Track | Focus | Visual Status | Live Issues |
| --- | --- | --- | --- |
| **Track A** | `system32` shim staging (`#457` / PR `#458` merged), AMD-only VEH emulation (`#451`), Track A/F runner integration (`#407`) | `🟩🟨🟨` *(#458 merged; #451, #407 active)* | [View Track A](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+A%22) |
| **Track B** | `XCRDAPI.dll` DirectStorage GPU-buffer & batch transfers (`#467`) | `⬜` *(1 ready)* | [View Track B](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+B%22) |
| **Track C** | `d3d12_xs` `D3D12ConfigureVirtualMemoryX` + placed resources (`#464`), `PresentX` swapchain bridge (`#465`), D3D workload fixes (`#450`) | `⬜⬜⬜` *(3 ready)* | [View Track C](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+C%22) |
| **Track D** | `dxbc-accc` Windows guest bridge (`#445`), M2 Shader Format Gate ADR & PSO hook (`#466`) | `⬜⬜` *(2 ready)* | [View Track D](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+D%22) |
| **Track E** | Public GDK COM `QueryApiImpl` dispatch (`#456` / PR `#462` merged), offline `XGameSave` + `XPackage` COM dispatch (`#468`) | `🟩⬜` *(#462 merged, 1 ready)* | [View Track E](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+E%22) |
| **Track F** | D3DMetal GPU limits fixture (`#453` / PR #455), M2 first-frame + shader-gate exit fixture (`#469`) | `🟨⬜` *(PR #455 approved, 1 ready)* | [View Track F](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+F%22) |
- Original gfx1030 vertex and pixel shader fixtures.
- Decoding and translation into Metal shader functions.
- Vertex position transformation.
- Constant-color output and clipping.
- Interpolated vertex attributes.
- Offscreen RGBA8 render targets.
- Native GPU readback and pixel-by-pixel validation.
- Explicit rejection of unsupported shader forms.
`🟩` Merged & verified · `🟨` PR open / in review · `⬜` Open & ready to claim
These are genuine translated shader stages, not merely demonstrations using handwritten Metal vertex and fragment programs.
### Milestone Roadmap (M0 → M6)
The current rendering tests are deliberately narrow: original fixtures, a single triangle per draw, and controlled shader inputs and outputs.
| Milestone | Scope | Status |
| --- | --- | --- |
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 cross-compiled PE32+ shims, live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | 🟢 **Verified complete (`#406`)** |
| **M1 — Boot to `D3D12XboxCreateDevice`** | Full startup shim coverage (`xmem` physical/scatter pages, `XCRDAPI` async file reads, `d3d12_xs` auto-logging COM proxy, offline `xgameruntime` + dynamic loader exports, audio queue stubs, supervised `bx-cli run`, ADR 0007, `test_integration_boot` 19 pass / 2 pending / 0 fail) | 🟢 **Verified complete ([Milestone #17](https://github.com/MacosPorters/betterxen/milestone/17))** |
| **M2 — First Frame & Shader Gate** | Reversible `system32` staging, public GDK COM `QueryApiImpl` dispatch, `PresentX` → `IDXGISwapChain3::Present` via D3DMetal 3.0, `dxbc-accc` Windows bridge, D3DMetal GPU limits, and Shader Format Gate ADR | 🔵 **Active ([Milestone #18](https://github.com/MacosPorters/betterxen/milestone/18))** |
| **M3 — Shaders, Streaming & Textures** | DirectStorage decompression, RDNA 2 `xg_xs` texture deswizzling, full shader pipeline | ⚪ Planned |
| **M4 — 3D Rendering, DXR/BVH & Input** | BVH4 rehydration → live D3DMetal 3.0 DXR rebuild, PC FidelityFX/MetalFX upscaling shim, full `GameInput` | ⚪ Planned |
| **M5 — Audio, Saves & Stability** | Software audio/DSP decoding (`AcpHal`/`xapu`/`chad`), `PersistentLocalStorage`, multi-hour soak stability | ⚪ Planned |
| **M6 — Cache, 16 GB Tuning & Polish** | Persistent PSO/shader disk cache, Lockhart 16 GB unified memory optimization, Metal System Trace tuning | ⚪ Planned |
### Verified Apple M5 results
See [docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md) and [docs/roadmap.md](docs/roadmap.md) for full details.
The X9 native Metal acceptance run reported **20 passing tests, zero failures and zero ignored tests**, with Metal API and GPU validation enabled.
Representative checks include:
| Test | Verified behavior |
| --- | --- |
| Constant-color rendering | 12 red pixels and 12 clear pixels |
| Vertex transformation | 3 rendered pixels versus 7 for a pass-through control |
| Perspective interpolation | Exact checks of 16 pixels and another 16 after swapping vertex color channels |
| BC1 texture handling | 33 texels across selected mip levels and array layers |
| Guest rendering | PE32+ guest receives and checks the translated render output |
The expected results were calculated independently of the production shader translation path.
**Important:** Correct output for these fixtures does not prove general RDNA2 compatibility or correctness for arbitrary Xbox shaders.
## Persistent GPU resources
X9 introduces a bounded GPU resource-management system for synthetic guest programs.
The implementation includes:
- Generation-checked guest resource handles.
- Buffer creation, updates, reuse and destruction.
- Checked buffer views and memory permissions.
- Repeated compute submissions.
- Resource lifetime validation.
- Snapshot behavior for queued submissions.
- Rejection of stale handles and malformed resource requests.
- Guest-visible readback and result verification.
The original X9 PE fixtures exercise these services through the guest execution environment.
The resource system remains experimental. Native GPU work already in flight during resource release, persistent Metal texture residency across guest calls, and general asynchronous execution are not yet implemented.
## Texture support
Xenora includes an original BC1 texture-processing path.
Implemented and tested functionality includes:
- Validated mip levels and array layers.
- Pitched texture uploads.
- Block-compressed texture handling.
- Native Metal texture readback.
- Edge-block and transparency tests.
- Invalid descriptor and bounds rejection.
**Translated texture-sampling instructions are not yet implemented.**
The existing texture readback path uses an authored Metal kernel. It should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
Xbox-specific texture layouts and additional compression formats require further research and validation.
---
## Architecture
Xenora is organized around three connected subsystems: guest execution, shader translation and native GPU execution.
Rosetta 2 executes x86-64 CPU code (including AVX/AVX2/FMA/F16C/BMI1/BMI2/128-bit VAES when launched with `ROSETTA_ADVERTISE_AVX=1`), CrossOver/Wine provides Win32/NT/CRT/XAudio2/WinHTTP, and D3DMetal 3.0 translates Direct3D 12 + DXR onto Metal. BetterXen supplies the modular Xbox Game OS shims, `clwb` exception handling, shader bridge, and ARM64 orchestration around that stack.
```mermaid
flowchart TD
subgraph Guest["Guest execution"]
A["Original PE32+ test program"]
B["Bounded x86-64 interpreter"]
C["Synthetic imported services"]
D["Validated GPU resources and commands"]
Guest["Scarlett x86-64 PE32+ Executable"]
A --> B
B --> C
C --> D
subgraph Shims["BetterXen x86-64 Wine Shims (Cross-Compiled on macOS)"]
VEH["bx_runtime_veh.dll (clwb VEH trap, JSONL trace, Lockhart cap)"]
XMem["xmem.dll (Physical/Virtual/Scatter Allocator)"]
DS["XCRDAPI.dll (DirectStorage Async I/O)"]
D3DX["d3d12_xs.dll + xg_xs.dll (Xbox D3D12 COM Proxy & RDNA2 Tiling)"]
XGR["xgameruntime.dll + GameInput.dll + Audio/DSP"]
Bridge["PSM AppNotify & ntuser Win32 Forwarders"]
end
subgraph Shader["RDNA2 shader translation"]
E["Original gfx1030 shader bytes"]
F["ISA decoder"]
G["Validated intermediate representation"]
H["MSL generation"]
E --> F
F --> G
G --> H
subgraph Shaders["Shader & DXR Bridge"]
DXIL["DXIL Fast Path (SM 6.5/6.6)"]
ACCC["ACCC / FSPX RDNA2 Transpiler"]
end
subgraph Metal["Native Apple Metal"]
I["Compute or render pipeline"]
J["Apple Silicon GPU"]
K["GPU readback"]
D --> I
H --> I
I --> J
J --> K
subgraph External["External Foundation (User-Installed)"]
Wine["CrossOver 26.3 / Wine (Win32, CRT, XAudio2, WinHTTP)"]
Rosetta["Rosetta 2 (ROSETTA_ADVERTISE_AVX=1)"]
D3DM["D3DMetal 3.0 (D3D12 + DXR on Apple Silicon Metal)"]
end
subgraph Validation["Correctness verification"]
L["Independent CPU reference"]
M{"Expected output matches?"}
CLI["bx-cli (Native ARM64 macOS Launcher, Probe & Telemetry)"]
E --> L
L --> M
K --> M
end
Guest --> Shims
D3DX --> DXIL --> D3DM
D3DX --> ACCC --> D3DM
XMem --> Wine
DS --> Wine
XGR --> Wine
Bridge --> Wine
VEH --> Rosetta
Wine --> Rosetta
CLI -.->|"Launches, sets overrides, summarizes traces"| External
```
Xenora's host execution environment is native ARM64. The guest architecture being interpreted is x86-64.
---
The project does not currently provide a general-purpose x86-64 dynamic recompiler or a complete Xbox operating-system implementation.
## Repository Layout
See [Interface Contracts](docs/interfaces.md) for the documented execution and resource boundaries.
The repository is organized into disjoint track directories around a single frozen `abi/` contract so **5–8+ contributors (and coding agents)** can work concurrently with minimal merge conflicts.
| Directory | Track | Stack | Contents |
| --- | --- | --- | --- |
| [`abi/`](abi/README.md) | Shared (frozen) | C headers + `.def` | Versioned cross-DLL headers (`bx_config.h`, `bx_log.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical export tables for all 16 shim DLLs |
| `launcher/` | Track A | Rust (`arm64`) | `bx-cli` (`doctor`, `probe`, `shader`, `trace`, `run`), `bx-probe` (PE32+ import classifier), `bx-telemetry` (JSONL trace aggregator) |
| `shims/runtime_veh/` | Track A | C++20 (`x86_64` PE) | `bx_runtime_veh.dll`: `clwb` VEH trap, `adcx`/`adox` tripwire, Lockhart/Anaconda memory profile config, structured JSONL logging |
| `shims/win32_bridge/` | Track A | C++20 (`x86_64` PE) | `api-ms-win-core-psm-appnotify-l1-1-0/1.dll` stubs and `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders; CrossOver answers these API-set names itself for static imports, so the files are not loaded that way ([ADR 0007](docs/adr/0007-api-set-shims-under-crossover.md)) |
| `shims/xmem/`, `shims/xcrdapi/` | Track B | C++20 (`x86_64` PE) | `xmem.dll` (13 Xbox memory APIs + internal region stats) and `XCRDAPI.dll` (`DStorageGetFactory` async I/O) |
| `shims/d3d12_xs/`, `shims/xg_xs/`, `shims/ffx_bvh_hooks/` | Track C | C++20 (`x86_64` PE) | Xbox D3D12 COM proxy over D3DMetal 3.0, RDNA 2 texture tiling (`XG`), and future FidelityFX/BVH4 hooks |
| `shader-transpiler/` | Track D | Rust (`arm64`) | `dxbc-accc` (`DXBC`/`DXIL`/`ACCC`/`FSPX` classifier), future RDNA 2 transpiler & `d3dmetal-native` isolation harness |
| `shims/xgameruntime/`, `shims/gameinput/`, `shims/audio/` | Track E | C++20 (`x86_64` PE) | Offline GDK runtime (`xgameruntime.dll`), `GameInput.dll` (`@1`), and `AcpHal.dll`/`xapu.dll`/`chad.dll` |
| [`tests/conformance/`](tests/conformance/README.md) | Track F | C++20 (`x86_64` PE) | Auto-discovered clean-room synthetic PE32+ test binaries (`test_*/CMakeLists.txt`) |
---
## Current limitations
Xenora is an engineering research project, not a working commercial-game emulator.
The following remain unsupported or incomplete:
| Subsystem | Outstanding work |
| --- | --- |
| Guest CPU | Broad x86-64 instruction coverage, multithreading and performant dynamic recompilation |
| Executable loader | General relocations, TLS, DLL initialization and authentic Xbox startup |
| Xbox runtime | Console-specific services, system APIs, filesystem and application lifecycle |
| RDNA2 shaders | General control flow, broader instructions, Wave64, cross-lane operations and mesh stages |
| Graphics | Translated texture sampling, broader resource binding, synchronization and general draw workloads |
| Textures | Authentic Xbox memory layouts and broader compressed-format support |
| Performance | Production-scale workloads, CPU/GPU profiling and optimized execution |
| Game compatibility | No demonstrated execution of commercial Xbox titles |
Xenora's current shader fixtures target a bounded subset of desktop gfx1030 behavior. This is not equivalent to complete Xbox Series GPU compatibility.
Progress is measured by reproducible tests rather than estimated game compatibility percentages.
---
## Building Xenora
## Quick Start
### Requirements
- Apple Silicon Mac running native ARM64 macOS.
- Rust toolchain with `aarch64-apple-darwin` support.
- Xcode and Metal development tools.
- Python 3.11 or newer.
- LLVM with AMDGPU support for applicable shader-fixture assembly and verification.
- **Apple Silicon Mac** running native ARM64 macOS with **Rosetta 2** and **CrossOver 26.3+** (external install).
- **Rust toolchain** (`aarch64-apple-darwin`, Rust 1.85+ / 1.100.0).
- **`mingw-w64` & `cmake`** (`brew install mingw-w64 cmake`) for cross-compiling x86-64 Windows PE32+ shims on macOS.
- **Python 3.11+** for export verification and repository hygiene checks.
The recorded Apple M5 environment uses Rust 1.100.0 and Xcode 27.2.
### Clone
### Build & Verify
```sh
git clone https://github.com/ranveersoni98/Xenora.git
cd Xenora
```
git clone https://github.com/MacosPorters/betterxen.git
cd betterxen
### Build
```sh
scripts/bootstrap.sh
cargo build --locked -p xenora
```
### Run core tests
```sh
# 1. Build & test the native ARM64 Rust workspace (launcher + shader-transpiler)
cargo fmt --all -- --check
cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace
cargo build -p bx-cli
# 2. Check host Apple Silicon, Rosetta 2, CrossOver, D3DMetal, and mingw-w64 readiness
target/debug/bx-cli doctor
# 3. Cross-compile all 16 x86-64 PE32+ shim DLLs + conformance binaries
# (automatically verifies every abi/defs/*.def export and zero MinGW runtime DLL deps)
scripts/build-shims.sh
# 4. Run live synthetic PE32+ conformance tests inside CrossOver + Rosetta 2
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_veh_clwb.exe
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_shim_exports.exe
target/debug/bx-cli trace /tmp/bx-test.jsonl
# 5. Check Markdown links & repository hygiene
python3 scripts/audit/docs_hygiene.py
```
### Run native Metal tests
### `bx-cli` Commands
These require a Metal-capable Apple Silicon Mac.
```sh
scripts/test-gpu.sh
```
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths.
### Verify guest execution
```sh
cargo test --locked \
--manifest-path experiments/x1/Cargo.toml \
--target aarch64-apple-darwin \
--features metal
```
Run the original guest resource integration tests:
```sh
tests/compat_fixtures/verify-resources.sh
```
The X9 verification script builds synthetic PE fixtures, executes guest resource and rendering workloads, compares reported output and exercises negative cases.
Additional checks:
```sh
tests/compat_fixtures/verify.sh
tests/compat_fixtures/verify-compute.sh
scripts/assemble-fixture.sh --check
scripts/demo.sh
```
Some verification paths require additional tools. Refer to the relevant test scripts and documentation before interpreting a missing dependency as a test failure.
### Test evidence
Testing distinguishes between:
- **CPU correctness:** Independent expected values and bounded execution.
- **Shader compilation:** Decoding, lowering and valid generated Metal source.
- **Native GPU execution:** Actual GPU work and checked readback.
- **Guest integration:** Original test executables invoking GPU services and checking results.
- **Unsupported behavior:** Explicit rejections and documented missing functionality.
Compiling a shader is not equivalent to proving its GPU output is correct.
The [X9 acceptance report](docs/testing/x9-acceptance.md) documents verified outcomes and unresolved work.
---
## Roadmap
Future development will focus on expanding the complete execution path instead of treating synthetic demonstration milestones as evidence of commercial-game compatibility.
### Near-term priorities
1. **Graphics compatibility:** Extend shader translation, texture sampling, resource bindings, multi-draw rendering and synchronization.
2. **Guest execution:** Improve the PE loader, CPU instruction coverage, runtime services and execution correctness.
3. **Performance:** Investigate efficient ARM64 guest execution, graphics pipeline caching, profiling and GPU resource lifetime management.
Longer-term research includes authentic Xbox application interfaces and significantly broader GPU behavior.
MetalFX upscaling and other presentation optimizations may become useful once substantial workloads render correctly. They are not substitutes for correct guest execution or shader translation.
There is no announced commercial-game support date.
---
## Contributors wanted
**Xenora is looking for developers interested in native Apple Silicon systems programming, graphics translation and emulation research.**
This is an ambitious project, and there's a great deal of work that would benefit from experienced contributors and independent reviewers.
Particularly useful areas include:
| Area | Potential contributions |
| Command | Purpose |
| --- | --- |
| Apple Metal | Rendering, resource management, synchronization, GPU debugging and profiling |
| AMD RDNA2 | ISA decoding, wave semantics, shader execution and correctness tests |
| Compiler engineering | Shader intermediate representations, lowering, optimization and code generation |
| ARM64 / x86-64 | Guest CPU execution, instruction semantics, memory models and future JIT research |
| Rust | Runtime architecture, concurrency, safety, tests and tooling |
| macOS | Apple Silicon compatibility, native debugging and hardware validation |
| Testing | Independent reference implementations, fuzzing, regression tests and reproducible GPU fixtures |
| `bx-cli doctor` | Inspects Apple Silicon host, RAM (recommends `lockhart` on 16 GB Macs or `anaconda` on 32 GB+), Rosetta 2, CrossOver, D3DMetal, and `mingw-w64` |
| `bx-cli probe <pe32+>` | Static PE32+ import scanner that classifies every imported DLL into Tracks A–E or Wine built-ins |
| `bx-cli shader <blob>` | Classifies a `DXBC` shader container (`DXIL` vs. legacy `SHDR`/`SHEX` vs. `ACCC`/`FSPX`) |
| `bx-cli run --exe <path> ...` | Launches a PE32+ binary under CrossOver/Wine with `env_clear()` host isolation (`--inherit-env` opt-in), `ROSETTA_ADVERTISE_AVX=1`, `WINEDLLOVERRIDES`, `BX_PROFILE`, and JSONL trace capture |
| `bx-cli trace <log.jsonl>` | Aggregates `bx_runtime_veh.dll` logs (unimplemented API counts, COM vtable misses, `clwb` VEH traps, ADX tripwires) |
You don't need to be an expert in every subsystem.
---
Code review, small targeted fixes, independent test cases and technical criticism are all valuable contributions.
## Contributing with Humans & Coding Agents
### Getting involved
BetterXen is built for **parallel work across 5–8+ contributors and coding agents** (`AGENTS.md` — symlinked as `CLAUDE.md` — holds the full ruleset):
1. Read [CONTRIBUTING.md](CONTRIBUTING.md) and the relevant architecture documentation.
2. Review the [current acceptance results](docs/testing/x9-acceptance.md).
3. Open a [GitHub issue](https://github.com/ranveersoni98/Xenora/issues) to discuss a feature, bug, or research question.
4. Submit focused pull requests with reproducible tests and documented limitations.
1. **Pick a track & claim an issue** from [docs/issues/wave-1-backlog.md](docs/issues/wave-1-backlog.md) (or GitHub Issues using `.github/ISSUE_TEMPLATE/track-handoff.yml`). Reply `Claiming — branch: track-<a..f>/<issue>-<slug>` before coding.
2. **Isolate your branch or worktree:** `git worktree add ../wt-<issue> -b track-<a..f>/<issue>-<slug> origin/main`.
3. **Stay inside your issue's exclusive file scope:** Never edit another track's directory inside a feature PR. Need a new cross-DLL helper? Open a small `[ABI]` PR touching only `abi/` first.
4. **Add a conflict-free conformance test:** Drop `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` — CMake auto-discovers `test_*` directories with zero edits to shared files.
5. **Run the verification commands above**, update [CHANGELOG.md](CHANGELOG.md) under `[Unreleased]`, sign off commits (DCO `Signed-off-by`), and open a PR with `Closes #<issue>`.
Contributions must follow the project's original-implementation and clean-room research policies. Do not submit proprietary game files, leaked SDK materials, console keys or unauthorized shader dumps.
See [AGENTS.md](AGENTS.md), [CONTRIBUTING.md](CONTRIBUTING.md), [docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md), and [docs/README.md](docs/README.md).
AI-assisted development has been used in Xenora. All contributions, including AI-assisted code, are expected to undergo human review and independent verification.
---
**The goal is to build a trustworthy native Apple Silicon compatibility framework, one verifiable subsystem at a time.**
## Current Verified Scope & Limitations
- **Verified (local Apple M5, macOS 27.2.1, CrossOver 26.3, Rosetta 2):**
- Native ARM64 `bx-cli`, `bx-probe`, `bx-telemetry`, and `dxbc-accc` unit tests.
- All 16 x86-64 PE32+ shim DLLs cross-compile with zero warnings, pass strict PE Export Directory verification (102 exact names, ordinals, forwarders, 0 extra exports), and carry zero dynamic MinGW runtime dependencies.
- `test_veh_clwb.exe` executes AVX2+FMA, traps and skips `clwb` via `bx_runtime_veh.dll`, and exercises starter `XMemAlloc`/`XMemTransferMemory` under CrossOver/Wine.
- `test_shim_exports.exe` loads all 16 shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine.
- **Not yet implemented (M1–M6):**
- `d3d12_xs.dll` COM device/command-list/PSO proxy and `PresentX` swapchain presentation.
- `xmem.dll` physical/scatter page mapping and `XCRDAPI.dll` async DirectStorage queues.
- `xg_xs.dll` RDNA 2 texture tiling/deswizzling and DXR/BVH4 rehydration interception.
- Console `ACCC`/`FSPX` RDNA 2 → DXIL/MSL shader transpilation (gated on M2).
- Real software audio/DSP decoding behind `AcpHal`/`xapu`/`chad` and full `GameInput` polling.
- Commercial Xbox game execution.
---
## Historical Native-First Research
The earlier paused native-first implementation (independent x86-64 interpreter/ARM64 DBT, bounded `gfx1030` RDNA 2 → MSL translator, native Metal backend, and Swift app) was retired from `main` per [ADR 0006](docs/adr/0006-retire-in-tree-native-workspace.md) and remains preserved permanently in Git history at tag `native-first-final`.
---
## License
Xenora is licensed under the [GNU General Public License v3 or later](LICENSE).
BetterXen is licensed under the [GNU General Public License v3 or later](LICENSE). See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) and [docs/legal.md](docs/legal.md) for attribution and legal scope.
See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for third-party attribution and [docs/legal.md](docs/legal.md) for the project's research and legal boundaries.
Xenora is an independent open-source project and is not affiliated with Microsoft, Xbox, Rockstar Games or Apple.
---
**Built for Apple Silicon. Powered by Rust and Metal. Open to contributors.**
BetterXen is an independent open-source project and is not affiliated with Microsoft, Xbox, Apple, CodeWeavers, or any game publisher.
+2 -2
View File
@@ -2,13 +2,13 @@
## Scope
Xenora is experimental and is not currently represented as a security-hardened runtime. Treat shaders, binary containers, caches and native library inputs as untrusted. Do not use it to process untrusted content in a sensitive environment.
BetterXen is experimental and is not currently represented as a security-hardened runtime. Treat shaders, binary containers, caches and native library inputs as untrusted. Do not use it to process untrusted content in a sensitive environment.
The project does not promise a fixed security support window at this stage. Report issues against a specific revision, preferably reproduced on current `main` where safe.
## Reporting vulnerabilities
Use [GitHub private vulnerability reporting](https://github.com/ranveersoni98/Xenora/security/advisories/new), if enabled. If it is unavailable, request a private reporting channel without disclosing exploit details publicly. Do not open a public issue containing sensitive vulnerability details, credentials, or private data.
Use [GitHub private vulnerability reporting](https://github.com/MacosPorters/betterxen/security/advisories/new), if enabled. If it is unavailable, request a private reporting channel without disclosing exploit details publicly. Do not open a public issue containing sensitive vulnerability details, credentials, or private data.
Include the affected commit, environment, affected component, expected and actual behavior, impact and a minimal, authorized reproduction. Use synthetic inputs wherever possible. Do not attach protected content, leaked SDK material or proprietary shaders.
+3 -3
View File
@@ -1,9 +1,9 @@
# Getting help
Start with the [README](README.md) and the relevant documentation in the repository, if available. Xenora is an experimental research project, not a commercial game compatibility service.
Start with the [README](README.md) and the relevant documentation in the repository, if available. BetterXen is an experimental research project, not a commercial game compatibility service.
- Use [GitHub Issues](https://github.com/ranveersoni98/Xenora/issues) for reproducible bugs, feature proposals, research findings and hardware verification reports.
- Use [GitHub Discussions](https://github.com/ranveersoni98/Xenora/discussions) for general questions if Discussions is enabled. Otherwise, search existing issues before filing a relevant question.
- Use [GitHub Issues](https://github.com/MacosPorters/betterxen/issues) for reproducible bugs, feature proposals, research findings and hardware verification reports.
- Use [GitHub Discussions](https://github.com/MacosPorters/betterxen/discussions) for general questions if Discussions is enabled. Otherwise, search existing issues before filing a relevant question.
- Follow [SECURITY.md](SECURITY.md) for security-sensitive reports.
Include the exact revision, host architecture, macOS version, relevant tool versions, steps to reproduce and sanitized output. Do not share personal paths, private account information, protected game assets, credentials or confidential material. If the reported feature is not yet implemented, identify it as a request rather than a regression.
+10 -12
View File
@@ -1,17 +1,15 @@
# Third-party notices
| Component | Version | License | Origin and notice |
|---|---|---|---|
| AMD RDNA 2 machine-readable ISA | 2026-02-20, schema 1.1.1 | MIT | Generated opcode masks derive from the AMD source identified in the [RDNA 2 research notes](docs/research/rdna2.md). [AMD license and copyright](crates/isa/LICENSE-AMD). |
| bitflags | 2.13.2 | MIT selected | [Upstream revision](https://github.com/bitflags/bitflags/tree/80ce9b545acb0bd42150695fc351889cac1d8eb4), [MIT license and copyright](licenses/bitflags-LICENSE-MIT). |
| objc2 | 0.6.5 | MIT | [Upstream revision](https://github.com/madsmtm/objc2/tree/d7d2fa23ceaa5e6096c923b081040e5d81b3b9df), [upstream licensing notice](licenses/objc2-LICENSE.md). |
| objc2-encode | 4.1.0 | MIT | [Upstream revision](https://github.com/madsmtm/objc2/tree/8d214f5477365ffcbcbb7de058c86ed9a518efb7), [upstream licensing notice](licenses/objc2-LICENSE.md). |
| objc2-foundation | 0.3.2 | MIT | [Upstream revision](https://github.com/madsmtm/objc2/tree/7b1abfd750a2cacaea71d6a56ecfb83cb7de560b), [upstream licensing notice](licenses/objc2-LICENSE.md). |
| objc2-core-foundation | 0.3.2 | MIT selected | [Upstream revision](https://github.com/madsmtm/objc2/tree/7b1abfd750a2cacaea71d6a56ecfb83cb7de560b), [upstream licensing notice](licenses/objc2-LICENSE.md). |
| objc2-metal | 0.3.2 | MIT selected | [Upstream revision](https://github.com/madsmtm/objc2/tree/7b1abfd750a2cacaea71d6a56ecfb83cb7de560b), [upstream licensing notice](licenses/objc2-LICENSE.md). |
The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) currently has **zero external crates.io dependencies** and is original `GPL-3.0-or-later` source.
Cargo resolves the Rust packages from crates.io at the source checksums in [Cargo.lock](Cargo.lock). The upstream objc2 notice discusses the derivation of bindings from Apple SDKs and an open question under Apple’s SDK terms. The maintainer confirmed upstream’s published license position in [issue #895](https://github.com/madsmtm/objc2/issues/895). No Apple SDK files or dependency crate archives ship in this repository. The [upstream MIT text](licenses/objc2-LICENSE-MIT.txt) is an unmodified copy from [objc2 commit ee9a7ad](https://github.com/madsmtm/objc2/blob/ee9a7ada2131f5944b8750428e265c15632f2a19/LICENSE-MIT.txt), added after the locked source revisions. Preserve it and the pinned licensing notice. See the [G11 review](docs/licenses.md#runtime-redistribution-review) for unresolved attribution and SDK questions.
`bx-cli` links the unmodified `libc` 0.2.191 crate (`ccc2ff4aaab962f7fde7b8edda7379c045b1ca12`) for POSIX process groups and signals, under its MIT option. Preserve the Rust Project Developers notice and permission text.
[LLVM 23.1.6](https://github.com/llvm/llvm-project/tree/5b10d2d74929eae78912771222c9855af97496f4) is used as an external fixture tool under Apache-2.0 WITH LLVM-exception. Xcode and Metal are separate Apple tools under Apple's license terms.
## External Host Tools & Runtime Dependencies (Never Bundled)
The [isolated fuzz workspace](fuzz/Cargo.lock) resolves developer-only dependencies, including [libfuzzer-sys](https://github.com/rust-fuzz/libfuzzer/tree/719e4efb9b8857ebaa782ae59376c8cbb78fed0f). See the [fuzz dependency inventory](docs/licenses.md#fuzz-development-dependencies) for locked revisions and selected licenses.
| Component | Role | Licensing & Provenance |
| --- | --- | --- |
| CrossOver / Wine | External macOS Windows compatibility runtime | Proprietary product with FOSS subcomponents; externally installed by the user and never bundled. See [docs/research/crossover-licensing.md](docs/research/crossover-licensing.md). |
| Apple D3DMetal & Rosetta 2 | External Direct3D-to-Metal and x86-64 translation | Proprietary Apple components under Apple's license terms; externally installed and never bundled. |
| `mingw-w64` & CMake | Developer cross-compilation toolchain for x86-64 PE32+ shims | Installed externally via Homebrew (`brew install mingw-w64 cmake`) for building `shims/` and `tests/conformance/`. |
Historical third-party notices for the retired native-first workspace (including AMD RDNA 2 ISA metadata, `bitflags`, and `objc2-*`) remain preserved at Git tag `native-first-final` and are summarized in [docs/licenses.md](docs/licenses.md).
+10
View File
@@ -0,0 +1,10 @@
# BetterXen Frozen ABI Contracts (`abi/`)
This directory holds the **only shared interface boundary** across BetterXen's six parallel development tracks.
## Rules for Contributors
1. **ABI-First Changes:** If one track needs a new cross-DLL helper, config flag, or export symbol, open a small, focused `[ABI]` pull request touching only `abi/`.
2. **Zero File Collisions:** Never edit another track's implementation directory in an `[ABI]` PR. Once the `[ABI]` PR merges to `main`, both provider and consumer tracks implement in parallel.
3. **Versioned Contracts:** Increment `BX_ABI_VERSION` in `abi/include/bx_config.h` on any breaking struct or signature change.
4. **Canonical `.def` Exports:** Every DLL under `shims/` links directly against its corresponding `abi/defs/<name>.def`. CI verifies the built PE32+ export table matches these `.def` files.
+11
View File
@@ -0,0 +1,11 @@
LIBRARY AcpHal.dll
EXPORTS
AcpHalCreate
AcpHalAllocateShapeContexts
AcpHalReleaseShapeContexts
ApuCreateHeap
ApuAlloc
ApuFree
ApuIsVirtualAddressValid
ApuMapApuAddress
ApuMapVirtualAddress
+3
View File
@@ -0,0 +1,3 @@
LIBRARY GameInput.dll
EXPORTS
GameInputCreate @1
+3
View File
@@ -0,0 +1,3 @@
LIBRARY XCRDAPI.dll
EXPORTS
DStorageGetFactory
@@ -0,0 +1,4 @@
LIBRARY api-ms-win-core-psm-appnotify-l1-1-0.dll
EXPORTS
RegisterAppStateChangeNotification
UnregisterAppStateChangeNotification
@@ -0,0 +1,4 @@
LIBRARY api-ms-win-core-psm-appnotify-l1-1-1.dll
EXPORTS
RegisterAppConstrainedChangeNotification
UnregisterAppConstrainedChangeNotification
+8
View File
@@ -0,0 +1,8 @@
LIBRARY bx_runtime_veh.dll
EXPORTS
bx_log_emit
bx_log_unimpl_api
bx_log_unimpl_vtable
bx_get_runtime_config
bx_veh_install
bx_veh_get_clwb_trap_count
+7
View File
@@ -0,0 +1,7 @@
LIBRARY chad.dll
EXPORTS
XDspActivate
XDspDeactivate
XDspConnectWithMaximumStreamLimit
XDspDisconnect
XDspSubmitCommand
+6
View File
@@ -0,0 +1,6 @@
LIBRARY d3d12_xs.dll
EXPORTS
D3D12XboxCreateDevice
D3D12ConfigureVirtualMemoryX
D3D12SerializeVersionedRootSignature
D3D12CreateRootSignatureDeserializer
@@ -0,0 +1,4 @@
LIBRARY ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0.dll
EXPORTS
DispatchMessageA = user32.DispatchMessageA
PeekMessageA = user32.PeekMessageA
@@ -0,0 +1,3 @@
LIBRARY ext-ms-win-rtcore-ntuser-message-l1-1-0.dll
EXPORTS
TranslateMessage = user32.TranslateMessage
@@ -0,0 +1,5 @@
LIBRARY ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0.dll
EXPORTS
CreateWindowExA = user32.CreateWindowExA
DefWindowProcA = user32.DefWindowProcA
RegisterClassExA = user32.RegisterClassExA
@@ -0,0 +1,3 @@
LIBRARY ext-ms-win-rtcore-ntuser-window-l1-1-0.dll
EXPORTS
ShowWindow = user32.ShowWindow
+7
View File
@@ -0,0 +1,7 @@
LIBRARY xapu.dll
EXPORTS
XApuConnect
XApuDisconnect
XApuEnqueueCommand
XApuDequeueResult
XApuGetResultCount
+4
View File
@@ -0,0 +1,4 @@
LIBRARY xg_xs.dll
EXPORTS
XGCreateTextureComputer
XGSuggestSwizzleMode
+51
View File
@@ -0,0 +1,51 @@
LIBRARY xgameruntime.dll
EXPORTS
XGameRuntimeInitialize
XGameRuntimeInitializeWithOptions
XGameRuntimeUninitialize
XTaskQueueCreate
XTaskQueueCloseHandle
XTaskQueueDispatch
XTaskQueueSubmitCallback
XTaskQueueGetCurrentProcessTaskQueue
XAsyncGetStatus
XAsyncGetResultSize
XAsyncCancel
XUserAddAsync
XUserAddResult
XUserCloseHandle
XUserGetId
XUserGetGamertag
XUserGetTokenAndSignatureAsync
XUserGetTokenAndSignatureResultSize
XUserGetTokenAndSignatureResult
XUserResolvePrivilegeWithUiAsync
XUserResolvePrivilegeWithUiResult
XStoreCreateContext
XStoreCloseContextHandle
XStoreQueryGameLicenseAsync
XStoreQueryGameLicenseResult
XStoreAcquireLicenseForPackageAsync
XStoreAcquireLicenseForPackageResult
XStoreAcquireLicenseForDurablesAsync
XStoreAcquireLicenseForDurablesResult
XStoreQueryEntitledProductsAsync
XStoreQueryEntitledProductsResult
XStoreQueryAssociatedProductsAsync
XStoreQueryAssociatedProductsResult
XSystemGetConsoleId
XSystemGetDeviceType
XSystemGetXboxLiveSandboxId
XPersistentLocalStorageGetPathSize
XPersistentLocalStorageGetPath
XPersistentLocalStorageGetSpaceInfo
XGameUiShowPlayerProfileCardAsync
XGameUiShowTextEntryAsync
XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync
XNetworkingQuerySecurityInformationForUrlAsync
InitializeApiImpl
InitializeApiImplEx
InitializeApiImplEx2
UninitializeApiImpl
QueryApiImpl
XErrorReport
+17
View File
@@ -0,0 +1,17 @@
LIBRARY xmem.dll
EXPORTS
XMemAlloc
XMemAllocDefault
XMemAllocatePhysicalPages
XMemFree
XMemFreeDefault
XMemFreePhysicalPages
XMemGetWorkingSetStatistics
XMemIsToolsMemAvailable
XMemMapPhysicalPages
XMemMapPhysicalPagesScatter
XMemTransferMemory
XMemVirtualAlloc
XMemVirtualQuery
bx_xmem_query_region
bx_xmem_get_internal_stats
+48
View File
@@ -0,0 +1,48 @@
#ifndef BETTERXEN_BX_CONFIG_H
#define BETTERXEN_BX_CONFIG_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define BX_ABI_VERSION 1u
/* Environment variables configured by bx-cli when launching under CrossOver/Wine. */
#define BX_ENV_PROFILE "BX_PROFILE" /* "lockhart" (default) | "anaconda" */
#define BX_ENV_LOG_FILE "BX_LOG_FILE" /* Path to JSONL/text trace log inside guest */
#define BX_ENV_LOG_LEVEL "BX_LOG_LEVEL" /* "error" | "warn" | "info" | "trace" */
#define BX_ENV_TRACE_D3D "BX_TRACE_D3D" /* "1" to trace every COM call */
#define BX_ENV_SHADER_DUMP_DIR "BX_SHADER_DUMP_DIR" /* Optional local dump dir for shader blobs */
#define BX_ENV_MEM_LIMIT_MB "BX_MEM_LIMIT_MB" /* Override reported title working-set cap */
#define BX_ENV_RT_MODE "BX_RT_MODE" /* "rebuild" | "bypass" */
typedef enum bx_hardware_profile {
BX_PROFILE_LOCKHART = 0, /* Series S memory budget (~8-10 GB; default on 16 GB hosts) */
BX_PROFILE_ANACONDA = 1 /* Series X memory budget (~13.5 GB; opt-in on 32 GB+ hosts) */
} bx_hardware_profile_t;
typedef enum bx_log_level {
BX_LOG_ERROR = 0,
BX_LOG_WARN = 1,
BX_LOG_INFO = 2,
BX_LOG_TRACE = 3
} bx_log_level_t;
typedef struct bx_runtime_config {
uint32_t abi_version;
bx_hardware_profile_t profile;
bx_log_level_t log_level;
uint64_t title_memory_limit_bytes;
uint32_t trace_d3d;
uint32_t enable_clwb_veh;
uint32_t enable_adx_tripwire;
uint32_t reserved;
} bx_runtime_config_t;
#ifdef __cplusplus
}
#endif
#endif /* BETTERXEN_BX_CONFIG_H */
+27
View File
@@ -0,0 +1,27 @@
#ifndef BETTERXEN_BX_LOG_H
#define BETTERXEN_BX_LOG_H
#include <stdint.h>
#include "bx_config.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* Structured runtime diagnostics exported by bx_runtime_veh.dll and consumed
* by all other BetterXen shim DLLs (via dynamic lookup or import library).
*/
void bx_log_emit(bx_log_level_t level, const char* subsystem, const char* event, const char* detail);
void bx_log_unimpl_api(const char* dll_name, const char* symbol_name);
void bx_log_unimpl_vtable(const char* iface_name, uint32_t slot_index, const char* method_name);
const bx_runtime_config_t* bx_get_runtime_config(void);
#define BX_STUB_LOG(dll, sym) bx_log_unimpl_api((dll), (sym))
#define BX_VTABLE_STUB_LOG(iface, slot, method) bx_log_unimpl_vtable((iface), (slot), (method))
#ifdef __cplusplus
}
#endif
#endif /* BETTERXEN_BX_LOG_H */
+83
View File
@@ -0,0 +1,83 @@
#ifndef BETTERXEN_BX_SHADER_BRIDGE_H
#define BETTERXEN_BX_SHADER_BRIDGE_H
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* C ABI contract between Track C (d3d12_xs.dll) and Track D (shader-transpiler).
* Used at Create*PipelineState / CreateStateObject time to inspect shader blobs
* (DXBC+DXIL vs DXBC+ACCC/FSPX RDNA2 ISA) and translate console-compiled shaders
* into D3DMetal-consumable DXIL (or report unsupported forms cleanly).
*/
typedef enum bx_shader_kind {
BX_SHADER_UNKNOWN = 0,
BX_SHADER_DXBC_DXIL = 1, /* Standard DXIL inside DXBC container (fast path to D3DMetal) */
BX_SHADER_DXBC_LEGACY = 2, /* Legacy SM5 SHDR/SHEX inside DXBC */
BX_SHADER_DXBC_ACCC = 3, /* Console-compiled AMD RDNA2 (ACCC / FSPX) without DXIL */
BX_SHADER_DXBC_DUAL = 4 /* Contains both DXIL and ACCC chunks */
} bx_shader_kind_t;
typedef enum bx_shader_stage {
BX_STAGE_UNKNOWN = 0,
BX_STAGE_PIXEL = 1,
BX_STAGE_VERTEX = 2,
BX_STAGE_GEOM = 3,
BX_STAGE_HULL = 4,
BX_STAGE_DOMAIN = 5,
BX_STAGE_COMPUTE = 6,
BX_STAGE_LIBRARY = 7,
BX_STAGE_MESH = 8,
BX_STAGE_AMP = 9
} bx_shader_stage_t;
typedef struct bx_shader_inspection {
bx_shader_kind_t kind;
bx_shader_stage_t stage;
uint32_t shader_model_major;
uint32_t shader_model_minor;
uint32_t container_size;
uint32_t dxil_chunk_size;
uint32_t accc_chunk_size;
uint32_t has_root_signature;
uint8_t digest_hash[16]; /* DXBC header digest or SHA-like key for caching */
} bx_shader_inspection_t;
typedef enum bx_shader_status {
BX_SHADER_OK = 0,
BX_SHADER_ERR_INVALID_BLOB = 1,
BX_SHADER_ERR_UNSUPPORTED = 2,
BX_SHADER_ERR_TRANSLATE = 3,
BX_SHADER_ERR_OOM = 4
} bx_shader_status_t;
/* Inspect a raw shader bytecode blob without allocating. */
bx_shader_status_t bx_shader_inspect(
const uint8_t* bytes,
size_t len,
bx_shader_inspection_t* out_info
);
/*
* Convert an incoming console shader blob into a D3DMetal-compatible DXBC/DXIL blob.
* On BX_SHADER_OK, caller must free `*out_bytes` with `bx_shader_free_buffer`.
*/
bx_shader_status_t bx_shader_prepare_for_d3dmetal(
const uint8_t* in_bytes,
size_t in_len,
uint8_t** out_bytes,
size_t* out_len
);
void bx_shader_free_buffer(uint8_t* ptr, size_t len);
#ifdef __cplusplus
}
#endif
#endif /* BETTERXEN_BX_SHADER_BRIDGE_H */
+43
View File
@@ -0,0 +1,43 @@
#ifndef BETTERXEN_BX_XMEM_INTERNAL_H
#define BETTERXEN_BX_XMEM_INTERNAL_H
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* Internal cross-DLL contract between Track B (xmem.dll) and Track C (d3d12_xs.dll).
* Allows d3d12_xs placed-resource and virtual-memory translation to query allocations
* created through XMemVirtualAlloc / XMemAllocatePhysicalPages / XMemMapPhysicalPages.
*/
typedef struct bx_xmem_region_info {
uint64_t base_va;
uint64_t size_bytes;
uint64_t page_size_bytes;
uint32_t protect_flags;
uint32_t mem_type_flags;
uint64_t physical_tag;
} bx_xmem_region_info_t;
typedef struct bx_xmem_stats {
uint64_t title_limit_bytes;
uint64_t committed_virtual_bytes;
uint64_t allocated_physical_bytes;
uint64_t peak_committed_bytes;
} bx_xmem_stats_t;
/* Query the XMem region covering `va`. Returns 1 if tracked, 0 otherwise. */
int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info);
/* Snapshot current XMem usage against the active Lockhart/Anaconda cap. */
void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats);
#ifdef __cplusplus
}
#endif
#endif /* BETTERXEN_BX_XMEM_INTERNAL_H */
-19
View File
@@ -1,19 +0,0 @@
[package]
name = "xenora-benchmarks"
description = "Correctness-gated native Metal benchmark harness for the Phase 01 corpus"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[[bin]]
name = "xenora-bench"
path = "src/main.rs"
[dependencies]
xenora-shader = { path = "../crates/shader" }
xenora-ref = { path = "../crates/ref" }
xenora-metal = { path = "../crates/metal" }
-51
View File
@@ -1,51 +0,0 @@
# Benchmark corpus for the Phase 01 correctness-gated harness.
#
# Supported subset: `[[fixture]]` tables with string and integer-array values.
# A shader is timed only after it passes correctness in the same run. `sizes`
# are word counts for the one-invocation-per-word synthetic ABI.
# See docs/testing/benchmarks.md for the protocol and metadata fields.
[[fixture]]
name = "add"
stage = "compute"
source = "translated-rdna"
path = "fixtures/rdna2/add.bin"
input = [0, 1, 4294967295, 3989547400]
expected = [305419896, 305419897, 305419895, 0]
sizes = [4, 64, 256, 1024, 4096]
[[fixture]]
name = "bitwise-branch"
stage = "compute"
source = "translated-rdna"
path = "fixtures/rdna2/bitwise-branch.bin"
input = [0, 1, 4294967295, 3989547400]
expected = [305419896, 305419897, 315315847, 318723824]
sizes = [4, 64, 256, 1024, 4096]
[[fixture]]
name = "float-exact"
stage = "compute"
source = "translated-rdna"
path = "fixtures/rdna2/float-exact.bin"
input = [0, 1, 4294967295, 3989547400]
expected = [1091305472, 1091305472, 1092616192, 1092616192]
sizes = [4, 64, 256, 1024, 4096]
[[fixture]]
name = "or"
stage = "compute"
source = "translated-rdna"
path = "fixtures/rdna2/or.bin"
input = [0, 1, 4294967295, 2153054378, 2141912917, 2147483648, 5570730]
expected = [2153054378, 2153054379, 4294967295, 2153054378, 4294967295, 2153054378, 2153054378]
sizes = [7, 64, 256, 1024, 4096]
[[fixture]]
name = "shifts"
stage = "compute"
source = "translated-rdna"
path = "fixtures/rdna2/shifts.bin"
input = [0, 1, 2, 30, 31, 32, 33, 63, 64, 2147483648, 2147483681, 4294967295]
expected = [2, 1073741830, 536870924, 3221225474, 2147483649, 2, 1073741830, 2147483649, 2, 2, 1073741830, 2147483649]
sizes = [12, 64, 256, 1024, 4096]
@@ -1,18 +0,0 @@
{
"run_id": "run-1795338391",
"timestamp": "unix:1795338391",
"device": "Apple M5",
"host_arch": "aarch64",
"os_version": "27.3",
"os_build": "26C5047e",
"rustc": "rustc 1.100.0 (0ef1bc386 2026-11-09) (Homebrew)",
"xcode": "Xcode 27.2",
"commit": "a34dadcbc06b696eae0d7b743845f4a2c9e67996",
"profile": "release",
"api_validation": "0",
"shader_validation": "0",
"power": "Battery Power",
"thermal": "no warnings recorded",
"reps": 7,
"warmup": 2
}
@@ -1,53 +0,0 @@
# Xenora benchmark report
Generated by `xenora-bench`. Every timed fixture passed its correctness test in this run. Timings are single command-buffer samples; see `docs/testing/benchmarks.md` for the protocol.
## Environment
| Field | Value |
| --- | --- |
| Device | Apple M5 |
| Host arch | aarch64 |
| macOS | 27.3 |
| Build | 26C5047e |
| Rust | rustc 1.100.0 (0ef1bc386 2026-11-09) (Homebrew) |
| Xcode | Xcode 27.2 |
| Commit | a34dadcbc06b696eae0d7b743845f4a2c9e67996 |
| Profile | release |
| API validation | 0 |
| Shader validation | 0 |
| Power source | Battery Power |
| Thermal | no warnings recorded |
| Repetitions | 7 measured, 2 warm-up |
> **Protocol note.** The machine was not confirmed on AC power. The [benchmark protocol](../../../../docs/testing/benchmarks.md) requires AC power, so these timings are not protocol-compliant release evidence.
## Coverage
| Fixture | Stage | Source | Status |
| --- | --- | --- | --- |
| add | compute | translated-rdna | benchmarked |
| bitwise-branch | compute | translated-rdna | benchmarked |
| float-exact | compute | translated-rdna | benchmarked |
## Timings
Durations in microseconds. `compile` is the Rust decode/IR/MSL pipeline, `library` and `pipeline` are Metal compilation stages, `gpu` is the command-buffer GPU time, and `host` is the wall time of one dispatch. Values are medians with interquartile range; minimum and maximum are in `results.json`.
| Fixture | Words | compile | library | pipeline | gpu | host | IQR(gpu) | zero-gpu |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| add | 4 | 5.42 | 15.04 | 36.33 | 6.08 | 525.50 | 0.29 | 0% |
| add | 64 | 4.54 | 11.83 | 28.17 | 6.08 | 529.92 | 0.06 | 0% |
| add | 256 | 4.46 | 11.42 | 27.33 | 5.88 | 519.17 | 0.19 | 0% |
| add | 1024 | 4.42 | 11.21 | 26.88 | 6.12 | 524.38 | 0.13 | 0% |
| add | 4096 | 4.38 | 11.17 | 27.92 | 6.25 | 523.58 | 0.08 | 0% |
| bitwise-branch | 4 | 11.38 | 13.00 | 28.96 | 6.12 | 509.37 | 0.00 | 0% |
| bitwise-branch | 64 | 7.75 | 11.33 | 26.92 | 6.12 | 526.50 | 0.02 | 0% |
| bitwise-branch | 256 | 7.71 | 11.21 | 26.62 | 6.00 | 513.71 | 0.02 | 0% |
| bitwise-branch | 1024 | 7.54 | 11.25 | 26.58 | 6.25 | 519.62 | 0.02 | 0% |
| bitwise-branch | 4096 | 7.58 | 11.21 | 27.25 | 6.21 | 523.33 | 0.04 | 0% |
| float-exact | 4 | 9.12 | 12.08 | 27.12 | 6.17 | 510.67 | 0.10 | 0% |
| float-exact | 64 | 8.58 | 11.46 | 26.50 | 6.04 | 523.79 | 0.06 | 0% |
| float-exact | 256 | 8.58 | 11.12 | 26.46 | 6.04 | 514.92 | 0.08 | 0% |
| float-exact | 1024 | 8.67 | 11.12 | 26.29 | 6.21 | 520.67 | 0.08 | 0% |
| float-exact | 4096 | 8.67 | 11.17 | 26.46 | 6.25 | 514.67 | 0.08 | 0% |
@@ -1,46 +0,0 @@
{
"fixtures": [
{
"name": "add",
"stage": "compute",
"source": "translated-rdna",
"status": "benchmarked",
"reason": "",
"sizes": [
{ "words": 4, "compile": { "median": 5.417000000e-6, "min": 4.875000000e-6, "max": 7.833000000e-6, "q1": 4.979500000e-6, "q3": 6.250500000e-6, "reps": 7 }, "library": { "median": 1.504200000e-5, "min": 1.254200000e-5, "max": 2.141700000e-5, "q1": 1.339600000e-5, "q3": 1.706300000e-5, "reps": 7 }, "pipeline": { "median": 3.633300000e-5, "min": 3.175000000e-5, "max": 4.900000000e-5, "q1": 3.245800000e-5, "q3": 4.106200000e-5, "reps": 7 }, "gpu": { "median": 6.083333574e-6, "min": 5.791662261e-6, "max": 6.125002983e-6, "q1": 5.833335308e-6, "q3": 6.124995707e-6, "reps": 7 }, "host": { "median": 5.255000000e-4, "min": 5.083750000e-4, "max": 5.870000000e-4, "q1": 5.120210000e-4, "q3": 5.354790000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 64, "compile": { "median": 4.542000000e-6, "min": 4.417000000e-6, "max": 4.584000000e-6, "q1": 4.500000000e-6, "q3": 4.562500000e-6, "reps": 7 }, "library": { "median": 1.183300000e-5, "min": 1.158300000e-5, "max": 1.204200000e-5, "q1": 1.172900000e-5, "q3": 1.191650000e-5, "reps": 7 }, "pipeline": { "median": 2.816700000e-5, "min": 2.779200000e-5, "max": 3.250000000e-5, "q1": 2.814550000e-5, "q3": 2.933350000e-5, "reps": 7 }, "gpu": { "median": 6.083333574e-6, "min": 5.750000128e-6, "max": 6.125002983e-6, "q1": 6.041664165e-6, "q3": 6.104164640e-6, "reps": 7 }, "host": { "median": 5.299160000e-4, "min": 4.869160000e-4, "max": 5.916250000e-4, "q1": 5.180835000e-4, "q3": 5.309585000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 256, "compile": { "median": 4.459000000e-6, "min": 4.375000000e-6, "max": 7.542000000e-6, "q1": 4.458000000e-6, "q3": 4.521000000e-6, "reps": 7 }, "library": { "median": 1.141700000e-5, "min": 1.120900000e-5, "max": 1.412500000e-5, "q1": 1.133350000e-5, "q3": 1.147900000e-5, "reps": 7 }, "pipeline": { "median": 2.733400000e-5, "min": 2.695800000e-5, "max": 2.758400000e-5, "q1": 2.706250000e-5, "q3": 2.750000000e-5, "reps": 7 }, "gpu": { "median": 5.875001079e-6, "min": 5.750000128e-6, "max": 6.000002031e-6, "q1": 5.791665899e-6, "q3": 5.979163689e-6, "reps": 7 }, "host": { "median": 5.191670000e-4, "min": 5.010000000e-4, "max": 5.346670000e-4, "q1": 5.137080000e-4, "q3": 5.276670000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 1024, "compile": { "median": 4.417000000e-6, "min": 4.250000000e-6, "max": 7.583000000e-6, "q1": 4.354500000e-6, "q3": 4.521000000e-6, "reps": 7 }, "library": { "median": 1.120900000e-5, "min": 1.091700000e-5, "max": 1.300000000e-5, "q1": 1.110400000e-5, "q3": 1.129150000e-5, "reps": 7 }, "pipeline": { "median": 2.687500000e-5, "min": 2.666600000e-5, "max": 3.350000000e-5, "q1": 2.670800000e-5, "q3": 2.716650000e-5, "reps": 7 }, "gpu": { "median": 6.124995707e-6, "min": 6.041664165e-6, "max": 6.208334526e-6, "q1": 6.062498869e-6, "q3": 6.187499821e-6, "reps": 7 }, "host": { "median": 5.243750000e-4, "min": 4.802500000e-4, "max": 6.343750000e-4, "q1": 5.193130000e-4, "q3": 5.442295000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 4096, "compile": { "median": 4.375000000e-6, "min": 4.250000000e-6, "max": 4.500000000e-6, "q1": 4.333000000e-6, "q3": 4.416500000e-6, "reps": 7 }, "library": { "median": 1.116600000e-5, "min": 1.095800000e-5, "max": 1.145900000e-5, "q1": 1.106250000e-5, "q3": 1.120800000e-5, "reps": 7 }, "pipeline": { "median": 2.791700000e-5, "min": 2.716700000e-5, "max": 3.229100000e-5, "q1": 2.743700000e-5, "q3": 2.833300000e-5, "reps": 7 }, "gpu": { "median": 6.249996659e-6, "min": 6.125002983e-6, "max": 6.250003935e-6, "q1": 6.166665116e-6, "q3": 6.250000297e-6, "reps": 7 }, "host": { "median": 5.235830000e-4, "min": 5.008330000e-4, "max": 5.484590000e-4, "q1": 5.165830000e-4, "q3": 5.246875000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 }
]
},
{
"name": "bitwise-branch",
"stage": "compute",
"source": "translated-rdna",
"status": "benchmarked",
"reason": "",
"sizes": [
{ "words": 4, "compile": { "median": 1.137500000e-5, "min": 8.125000000e-6, "max": 1.562500000e-5, "q1": 8.875000000e-6, "q3": 1.214650000e-5, "reps": 7 }, "library": { "median": 1.300000000e-5, "min": 1.150000000e-5, "max": 2.495800000e-5, "q1": 1.214600000e-5, "q3": 1.556200000e-5, "reps": 7 }, "pipeline": { "median": 2.895800000e-5, "min": 2.704200000e-5, "max": 5.566600000e-5, "q1": 2.762500000e-5, "q3": 3.600050000e-5, "reps": 7 }, "gpu": { "median": 6.124995707e-6, "min": 6.083333574e-6, "max": 6.208334526e-6, "q1": 6.124995707e-6, "q3": 6.125002983e-6, "reps": 7 }, "host": { "median": 5.093750000e-4, "min": 4.334590000e-4, "max": 5.999590000e-4, "q1": 4.986045000e-4, "q3": 5.409170000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 64, "compile": { "median": 7.750000000e-6, "min": 7.542000000e-6, "max": 7.917000000e-6, "q1": 7.625000000e-6, "q3": 7.771000000e-6, "reps": 7 }, "library": { "median": 1.133300000e-5, "min": 1.100000000e-5, "max": 1.158300000e-5, "q1": 1.127100000e-5, "q3": 1.141650000e-5, "reps": 7 }, "pipeline": { "median": 2.691600000e-5, "min": 2.641700000e-5, "max": 2.754200000e-5, "q1": 2.679150000e-5, "q3": 2.706200000e-5, "reps": 7 }, "gpu": { "median": 6.124995707e-6, "min": 6.000002031e-6, "max": 6.166665116e-6, "q1": 6.104164640e-6, "q3": 6.125002983e-6, "reps": 7 }, "host": { "median": 5.265000000e-4, "min": 4.912500000e-4, "max": 5.496250000e-4, "q1": 5.206460000e-4, "q3": 5.289170000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 256, "compile": { "median": 7.708000000e-6, "min": 7.583000000e-6, "max": 7.917000000e-6, "q1": 7.625000000e-6, "q3": 7.771000000e-6, "reps": 7 }, "library": { "median": 1.120900000e-5, "min": 1.091600000e-5, "max": 1.170900000e-5, "q1": 1.104150000e-5, "q3": 1.127100000e-5, "reps": 7 }, "pipeline": { "median": 2.662500000e-5, "min": 2.637500000e-5, "max": 2.679100000e-5, "q1": 2.652050000e-5, "q3": 2.666650000e-5, "reps": 7 }, "gpu": { "median": 6.000002031e-6, "min": 5.999994755e-6, "max": 6.124995707e-6, "q1": 6.000002031e-6, "q3": 6.020833098e-6, "reps": 7 }, "host": { "median": 5.137080000e-4, "min": 5.058750000e-4, "max": 5.431250000e-4, "q1": 5.129375000e-4, "q3": 5.265415000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 1024, "compile": { "median": 7.542000000e-6, "min": 7.416000000e-6, "max": 1.337500000e-5, "q1": 7.458500000e-6, "q3": 7.645500000e-6, "reps": 7 }, "library": { "median": 1.125000000e-5, "min": 1.091700000e-5, "max": 1.137500000e-5, "q1": 1.100000000e-5, "q3": 1.127100000e-5, "reps": 7 }, "pipeline": { "median": 2.658300000e-5, "min": 2.641700000e-5, "max": 2.945900000e-5, "q1": 2.652100000e-5, "q3": 2.668750000e-5, "reps": 7 }, "gpu": { "median": 6.250003935e-6, "min": 6.166665116e-6, "max": 6.250003935e-6, "q1": 6.229165592e-6, "q3": 6.250003935e-6, "reps": 7 }, "host": { "median": 5.196250000e-4, "min": 4.705420000e-4, "max": 5.796250000e-4, "q1": 4.989585000e-4, "q3": 5.451670000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 4096, "compile": { "median": 7.583000000e-6, "min": 7.458000000e-6, "max": 7.625000000e-6, "q1": 7.541500000e-6, "q3": 7.604500000e-6, "reps": 7 }, "library": { "median": 1.120900000e-5, "min": 1.100000000e-5, "max": 1.129200000e-5, "q1": 1.114600000e-5, "q3": 1.127050000e-5, "reps": 7 }, "pipeline": { "median": 2.725000000e-5, "min": 2.645900000e-5, "max": 3.054200000e-5, "q1": 2.693750000e-5, "q3": 2.866700000e-5, "reps": 7 }, "gpu": { "median": 6.208334526e-6, "min": 6.166672392e-6, "max": 6.333335477e-6, "q1": 6.208330888e-6, "q3": 6.250003935e-6, "reps": 7 }, "host": { "median": 5.233330000e-4, "min": 4.921660000e-4, "max": 5.424170000e-4, "q1": 5.017080000e-4, "q3": 5.346455000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 }
]
},
{
"name": "float-exact",
"stage": "compute",
"source": "translated-rdna",
"status": "benchmarked",
"reason": "",
"sizes": [
{ "words": 4, "compile": { "median": 9.125000000e-6, "min": 8.667000000e-6, "max": 1.658300000e-5, "q1": 8.812500000e-6, "q3": 1.385400000e-5, "reps": 7 }, "library": { "median": 1.208400000e-5, "min": 1.141600000e-5, "max": 1.837500000e-5, "q1": 1.166650000e-5, "q3": 1.229150000e-5, "reps": 7 }, "pipeline": { "median": 2.712500000e-5, "min": 2.662500000e-5, "max": 2.866700000e-5, "q1": 2.677050000e-5, "q3": 2.743750000e-5, "reps": 7 }, "gpu": { "median": 6.166665116e-6, "min": 5.958332622e-6, "max": 6.250003935e-6, "q1": 6.125002983e-6, "q3": 6.229165592e-6, "reps": 7 }, "host": { "median": 5.106660000e-4, "min": 4.910840000e-4, "max": 6.143750000e-4, "q1": 5.022500000e-4, "q3": 5.370625000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 64, "compile": { "median": 8.583000000e-6, "min": 8.541000000e-6, "max": 1.425000000e-5, "q1": 8.583000000e-6, "q3": 8.687500000e-6, "reps": 7 }, "library": { "median": 1.145800000e-5, "min": 1.116700000e-5, "max": 1.187500000e-5, "q1": 1.131200000e-5, "q3": 1.164600000e-5, "reps": 7 }, "pipeline": { "median": 2.650000000e-5, "min": 2.620800000e-5, "max": 2.725000000e-5, "q1": 2.631300000e-5, "q3": 2.700000000e-5, "reps": 7 }, "gpu": { "median": 6.041671440e-6, "min": 5.916670489e-6, "max": 6.125002983e-6, "q1": 6.041664165e-6, "q3": 6.104164640e-6, "reps": 7 }, "host": { "median": 5.237920000e-4, "min": 4.042920000e-4, "max": 5.358750000e-4, "q1": 5.191665000e-4, "q3": 5.336665000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 256, "compile": { "median": 8.583000000e-6, "min": 8.500000000e-6, "max": 8.834000000e-6, "q1": 8.562000000e-6, "q3": 8.708500000e-6, "reps": 7 }, "library": { "median": 1.112500000e-5, "min": 1.091600000e-5, "max": 1.129200000e-5, "q1": 1.110450000e-5, "q3": 1.120850000e-5, "reps": 7 }, "pipeline": { "median": 2.645900000e-5, "min": 2.629200000e-5, "max": 2.658400000e-5, "q1": 2.641650000e-5, "q3": 2.652100000e-5, "reps": 7 }, "gpu": { "median": 6.041664165e-6, "min": 5.999994755e-6, "max": 6.083333574e-6, "q1": 6.000002031e-6, "q3": 6.083333574e-6, "reps": 7 }, "host": { "median": 5.149170000e-4, "min": 5.000000000e-4, "max": 5.907500000e-4, "q1": 5.053955000e-4, "q3": 5.300000000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 1024, "compile": { "median": 8.667000000e-6, "min": 8.500000000e-6, "max": 8.792000000e-6, "q1": 8.583500000e-6, "q3": 8.791500000e-6, "reps": 7 }, "library": { "median": 1.112500000e-5, "min": 1.104100000e-5, "max": 1.120900000e-5, "q1": 1.106250000e-5, "q3": 1.114600000e-5, "reps": 7 }, "pipeline": { "median": 2.629200000e-5, "min": 2.612500000e-5, "max": 2.637500000e-5, "q1": 2.625000000e-5, "q3": 2.635400000e-5, "reps": 7 }, "gpu": { "median": 6.208327250e-6, "min": 6.000002031e-6, "max": 6.250003935e-6, "q1": 6.145830412e-6, "q3": 6.229169230e-6, "reps": 7 }, "host": { "median": 5.206670000e-4, "min": 5.023330000e-4, "max": 5.300840000e-4, "q1": 5.051045000e-4, "q3": 5.258955000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
{ "words": 4096, "compile": { "median": 8.667000000e-6, "min": 8.458000000e-6, "max": 8.750000000e-6, "q1": 8.542000000e-6, "q3": 8.687500000e-6, "reps": 7 }, "library": { "median": 1.116700000e-5, "min": 1.100000000e-5, "max": 1.133400000e-5, "q1": 1.108350000e-5, "q3": 1.125000000e-5, "reps": 7 }, "pipeline": { "median": 2.645800000e-5, "min": 2.595900000e-5, "max": 2.691600000e-5, "q1": 2.641700000e-5, "q3": 2.658350000e-5, "reps": 7 }, "gpu": { "median": 6.250003935e-6, "min": 6.166665116e-6, "max": 6.375004887e-6, "q1": 6.250000297e-6, "q3": 6.333331839e-6, "reps": 7 }, "host": { "median": 5.146670000e-4, "min": 4.975000000e-4, "max": 5.337500000e-4, "q1": 5.105415000e-4, "q3": 5.209795000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 }
]
}
]
}
@@ -1,18 +0,0 @@
{
"run_id": "run-1795352394",
"timestamp": "unix:1795352394",
"device": "Apple M5",
"host_arch": "aarch64",
"os_version": "27.3",
"os_build": "26C5047e",
"rustc": "rustc 1.100.0 (0ef1bc386 2026-11-09) (Homebrew)",
"xcode": "Xcode 27.2",
"commit": "cc0daa79e63c468e748f0333bd1314224752893a",
"profile": "release",
"api_validation": "0",
"shader_validation": "0",
"power": "AC Power",
"thermal": "no warnings recorded",
"reps": 21,
"warmup": 2
}
@@ -1,51 +0,0 @@
# Xenora benchmark report
Generated by `xenora-bench`. Every timed fixture passed its correctness test in this run. Timings are single command-buffer samples; see `docs/testing/benchmarks.md` for the protocol.
## Environment
| Field | Value |
| --- | --- |
| Device | Apple M5 |
| Host arch | aarch64 |
| macOS | 27.3 |
| Build | 26C5047e |
| Rust | rustc 1.100.0 (0ef1bc386 2026-11-09) (Homebrew) |
| Xcode | Xcode 27.2 |
| Commit | cc0daa79e63c468e748f0333bd1314224752893a |
| Profile | release |
| API validation | 0 |
| Shader validation | 0 |
| Power source | AC Power |
| Thermal | no warnings recorded |
| Repetitions | 21 measured, 2 warm-up |
## Coverage
| Fixture | Stage | Source | Status |
| --- | --- | --- | --- |
| add | compute | translated-rdna | benchmarked |
| bitwise-branch | compute | translated-rdna | benchmarked |
| float-exact | compute | translated-rdna | benchmarked |
## Timings
Durations in microseconds. `compile` is the Rust decode/IR/MSL pipeline, `library` and `pipeline` are Metal compilation stages, `gpu` is the command-buffer GPU time, and `host` is the wall time of one dispatch. Values are medians with interquartile range; minimum and maximum are in `results.json`.
| Fixture | Words | compile | library | pipeline | gpu | host | IQR(gpu) | zero-gpu |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| add | 4 | 5.08 | 13.42 | 32.50 | 87.62 | 375.33 | 103.62 | 0% |
| add | 64 | 4.42 | 11.79 | 28.25 | 3.63 | 407.79 | 36.54 | 0% |
| add | 256 | 4.17 | 10.96 | 26.79 | 1.38 | 231.25 | 2.25 | 0% |
| add | 1024 | 4.25 | 11.17 | 26.54 | 1.46 | 218.25 | 0.08 | 0% |
| add | 4096 | 4.46 | 11.67 | 27.62 | 3.38 | 237.71 | 17.63 | 0% |
| bitwise-branch | 4 | 7.71 | 11.04 | 26.29 | 1.33 | 214.29 | 0.08 | 0% |
| bitwise-branch | 64 | 8.71 | 11.92 | 27.83 | 2.08 | 213.12 | 4.25 | 0% |
| bitwise-branch | 256 | 7.58 | 10.71 | 26.00 | 1.37 | 216.38 | 0.04 | 0% |
| bitwise-branch | 1024 | 7.62 | 10.67 | 26.08 | 1.42 | 212.58 | 0.08 | 0% |
| bitwise-branch | 4096 | 7.62 | 11.12 | 26.58 | 1.58 | 236.17 | 25.75 | 0% |
| float-exact | 4 | 8.54 | 10.88 | 25.62 | 1.33 | 212.00 | 0.08 | 0% |
| float-exact | 64 | 8.71 | 11.00 | 26.21 | 1.38 | 215.33 | 1.25 | 0% |
| float-exact | 256 | 8.62 | 10.83 | 25.83 | 1.37 | 213.88 | 0.08 | 0% |
| float-exact | 1024 | 8.54 | 11.00 | 25.92 | 1.50 | 213.67 | 0.04 | 0% |
| float-exact | 4096 | 8.54 | 10.88 | 26.04 | 1.50 | 228.00 | 30.25 | 0% |
@@ -1,46 +0,0 @@
{
"fixtures": [
{
"name": "add",
"stage": "compute",
"source": "translated-rdna",
"status": "benchmarked",
"reason": "",
"sizes": [
{ "words": 4, "compile": { "median": 5.083000000e-6, "min": 4.167000000e-6, "max": 4.425000000e-5, "q1": 4.375000000e-6, "q3": 7.458000000e-6, "reps": 21 }, "library": { "median": 1.341700000e-5, "min": 1.087500000e-5, "max": 3.879200000e-5, "q1": 1.150000000e-5, "q3": 1.762500000e-5, "reps": 21 }, "pipeline": { "median": 3.250000000e-5, "min": 2.666700000e-5, "max": 5.920800000e-5, "q1": 2.979200000e-5, "q3": 4.262500000e-5, "reps": 21 }, "gpu": { "median": 8.762499965e-5, "min": 5.625000085e-6, "max": 2.230416667e-4, "q1": 1.562500074e-5, "q3": 1.192500004e-4, "reps": 21 }, "host": { "median": 3.753330000e-4, "min": 2.814590000e-4, "max": 5.746250000e-4, "q1": 3.609170000e-4, "q3": 4.326250000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 64, "compile": { "median": 4.416000000e-6, "min": 4.083000000e-6, "max": 5.792000000e-6, "q1": 4.292000000e-6, "q3": 4.542000000e-6, "reps": 21 }, "library": { "median": 1.179100000e-5, "min": 1.075000000e-5, "max": 1.741600000e-5, "q1": 1.116700000e-5, "q3": 1.312500000e-5, "reps": 21 }, "pipeline": { "median": 2.825000000e-5, "min": 2.591700000e-5, "max": 3.758400000e-5, "q1": 2.770800000e-5, "q3": 3.100000000e-5, "reps": 21 }, "gpu": { "median": 3.625000318e-6, "min": 3.125000148e-6, "max": 3.708750000e-4, "q1": 3.208333510e-6, "q3": 3.974999981e-5, "reps": 21 }, "host": { "median": 4.077910000e-4, "min": 2.125000000e-4, "max": 8.305420000e-4, "q1": 3.319170000e-4, "q3": 4.473340000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 256, "compile": { "median": 4.167000000e-6, "min": 4.083000000e-6, "max": 4.333000000e-6, "q1": 4.166000000e-6, "q3": 4.208000000e-6, "reps": 21 }, "library": { "median": 1.095800000e-5, "min": 1.054200000e-5, "max": 1.154200000e-5, "q1": 1.062500000e-5, "q3": 1.116600000e-5, "reps": 21 }, "pipeline": { "median": 2.679200000e-5, "min": 2.583400000e-5, "max": 3.391600000e-5, "q1": 2.612500000e-5, "q3": 2.716600000e-5, "reps": 21 }, "gpu": { "median": 1.375000465e-6, "min": 1.291666194e-6, "max": 5.875000170e-6, "q1": 1.374999556e-6, "q3": 3.625000318e-6, "reps": 21 }, "host": { "median": 2.312500000e-4, "min": 2.123750000e-4, "max": 7.405830000e-4, "q1": 2.190830000e-4, "q3": 6.997080000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 1024, "compile": { "median": 4.250000000e-6, "min": 4.083000000e-6, "max": 6.292000000e-6, "q1": 4.167000000e-6, "q3": 4.333000000e-6, "reps": 21 }, "library": { "median": 1.116700000e-5, "min": 1.054200000e-5, "max": 1.583400000e-5, "q1": 1.075000000e-5, "q3": 1.133300000e-5, "reps": 21 }, "pipeline": { "median": 2.654200000e-5, "min": 2.566700000e-5, "max": 3.695800000e-5, "q1": 2.583300000e-5, "q3": 2.758300000e-5, "reps": 21 }, "gpu": { "median": 1.458333827e-6, "min": 1.375000465e-6, "max": 5.999999303e-6, "q1": 1.416667146e-6, "q3": 1.500000508e-6, "reps": 21 }, "host": { "median": 2.182500000e-4, "min": 2.122920000e-4, "max": 5.624590000e-4, "q1": 2.162090000e-4, "q3": 2.354590000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 4096, "compile": { "median": 4.458000000e-6, "min": 4.125000000e-6, "max": 1.104100000e-5, "q1": 4.250000000e-6, "q3": 4.833000000e-6, "reps": 21 }, "library": { "median": 1.166700000e-5, "min": 1.083300000e-5, "max": 7.970800000e-5, "q1": 1.120900000e-5, "q3": 1.337500000e-5, "reps": 21 }, "pipeline": { "median": 2.762500000e-5, "min": 2.645800000e-5, "max": 7.595800000e-5, "q1": 2.683300000e-5, "q3": 3.045800000e-5, "reps": 21 }, "gpu": { "median": 3.375000233e-6, "min": 1.375000465e-6, "max": 3.787499918e-5, "q1": 1.499999598e-6, "q3": 1.912500011e-5, "reps": 21 }, "host": { "median": 2.377080000e-4, "min": 2.014170000e-4, "max": 5.690830000e-4, "q1": 2.298750000e-4, "q3": 3.332910000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 }
]
},
{
"name": "bitwise-branch",
"stage": "compute",
"source": "translated-rdna",
"status": "benchmarked",
"reason": "",
"sizes": [
{ "words": 4, "compile": { "median": 7.709000000e-6, "min": 7.416000000e-6, "max": 1.133300000e-5, "q1": 7.542000000e-6, "q3": 8.083000000e-6, "reps": 21 }, "library": { "median": 1.104100000e-5, "min": 1.054100000e-5, "max": 1.454200000e-5, "q1": 1.079200000e-5, "q3": 1.112500000e-5, "reps": 21 }, "pipeline": { "median": 2.629200000e-5, "min": 2.554100000e-5, "max": 3.658400000e-5, "q1": 2.612500000e-5, "q3": 2.637500000e-5, "reps": 21 }, "gpu": { "median": 1.333332875e-6, "min": 1.291666194e-6, "max": 1.926666664e-4, "q1": 1.291667104e-6, "q3": 1.374999556e-6, "reps": 21 }, "host": { "median": 2.142920000e-4, "min": 2.040840000e-4, "max": 4.722500000e-4, "q1": 2.110840000e-4, "q3": 2.197500000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 64, "compile": { "median": 8.708000000e-6, "min": 7.584000000e-6, "max": 4.979100000e-5, "q1": 7.834000000e-6, "q3": 1.245800000e-5, "reps": 21 }, "library": { "median": 1.191700000e-5, "min": 1.075000000e-5, "max": 7.475000000e-5, "q1": 1.141700000e-5, "q3": 1.362500000e-5, "reps": 21 }, "pipeline": { "median": 2.783400000e-5, "min": 2.591700000e-5, "max": 5.308300000e-5, "q1": 2.716700000e-5, "q3": 2.954100000e-5, "reps": 21 }, "gpu": { "median": 2.083333129e-6, "min": 1.249999514e-6, "max": 4.854166673e-5, "q1": 1.333333785e-6, "q3": 5.583333405e-6, "reps": 21 }, "host": { "median": 2.131250000e-4, "min": 1.608750000e-4, "max": 4.971250000e-4, "q1": 1.936660000e-4, "q3": 2.450420000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 256, "compile": { "median": 7.583000000e-6, "min": 7.416000000e-6, "max": 7.750000000e-6, "q1": 7.500000000e-6, "q3": 7.625000000e-6, "reps": 21 }, "library": { "median": 1.070900000e-5, "min": 1.050000000e-5, "max": 1.104100000e-5, "q1": 1.062500000e-5, "q3": 1.079200000e-5, "reps": 21 }, "pipeline": { "median": 2.600000000e-5, "min": 2.541700000e-5, "max": 2.670800000e-5, "q1": 2.583300000e-5, "q3": 2.625000000e-5, "reps": 21 }, "gpu": { "median": 1.374999556e-6, "min": 1.291666194e-6, "max": 1.458333827e-6, "q1": 1.333332875e-6, "q3": 1.375000465e-6, "reps": 21 }, "host": { "median": 2.163750000e-4, "min": 2.042920000e-4, "max": 2.393750000e-4, "q1": 2.125830000e-4, "q3": 2.197080000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 1024, "compile": { "median": 7.625000000e-6, "min": 7.500000000e-6, "max": 7.875000000e-6, "q1": 7.500000000e-6, "q3": 7.625000000e-6, "reps": 21 }, "library": { "median": 1.066700000e-5, "min": 1.050000000e-5, "max": 1.091700000e-5, "q1": 1.058400000e-5, "q3": 1.083400000e-5, "reps": 21 }, "pipeline": { "median": 2.608300000e-5, "min": 2.533300000e-5, "max": 3.291700000e-5, "q1": 2.558300000e-5, "q3": 2.620800000e-5, "reps": 21 }, "gpu": { "median": 1.416667146e-6, "min": 1.374999556e-6, "max": 9.749999663e-6, "q1": 1.375000465e-6, "q3": 1.458332918e-6, "reps": 21 }, "host": { "median": 2.125830000e-4, "min": 1.951250000e-4, "max": 4.068340000e-4, "q1": 2.102090000e-4, "q3": 2.148750000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 4096, "compile": { "median": 7.625000000e-6, "min": 7.417000000e-6, "max": 3.583300000e-5, "q1": 7.584000000e-6, "q3": 8.375000000e-6, "reps": 21 }, "library": { "median": 1.112500000e-5, "min": 1.062500000e-5, "max": 4.820800000e-5, "q1": 1.079200000e-5, "q3": 1.212500000e-5, "reps": 21 }, "pipeline": { "median": 2.658400000e-5, "min": 2.570900000e-5, "max": 1.125830000e-4, "q1": 2.595800000e-5, "q3": 2.954200000e-5, "reps": 21 }, "gpu": { "median": 1.583332960e-6, "min": 1.374999556e-6, "max": 6.262500028e-5, "q1": 1.416667146e-6, "q3": 2.716666677e-5, "reps": 21 }, "host": { "median": 2.361670000e-4, "min": 1.970840000e-4, "max": 5.112080000e-4, "q1": 2.251670000e-4, "q3": 2.410000000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 }
]
},
{
"name": "float-exact",
"stage": "compute",
"source": "translated-rdna",
"status": "benchmarked",
"reason": "",
"sizes": [
{ "words": 4, "compile": { "median": 8.542000000e-6, "min": 8.292000000e-6, "max": 1.233400000e-5, "q1": 8.417000000e-6, "q3": 8.875000000e-6, "reps": 21 }, "library": { "median": 1.087500000e-5, "min": 1.050000000e-5, "max": 1.500000000e-5, "q1": 1.079100000e-5, "q3": 1.120800000e-5, "reps": 21 }, "pipeline": { "median": 2.562500000e-5, "min": 2.520900000e-5, "max": 3.454100000e-5, "q1": 2.554200000e-5, "q3": 2.575000000e-5, "reps": 21 }, "gpu": { "median": 1.333333785e-6, "min": 1.291666194e-6, "max": 1.797083332e-4, "q1": 1.291667104e-6, "q3": 1.374999556e-6, "reps": 21 }, "host": { "median": 2.120000000e-4, "min": 2.052920000e-4, "max": 4.474160000e-4, "q1": 2.097500000e-4, "q3": 2.153330000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 64, "compile": { "median": 8.708000000e-6, "min": 8.416000000e-6, "max": 3.125000000e-5, "q1": 8.500000000e-6, "q3": 9.625000000e-6, "reps": 21 }, "library": { "median": 1.100000000e-5, "min": 1.058400000e-5, "max": 5.441600000e-5, "q1": 1.075000000e-5, "q3": 1.225000000e-5, "reps": 21 }, "pipeline": { "median": 2.620800000e-5, "min": 2.516700000e-5, "max": 7.550000000e-5, "q1": 2.533300000e-5, "q3": 2.858300000e-5, "reps": 21 }, "gpu": { "median": 1.375000465e-6, "min": 1.291666194e-6, "max": 4.275000083e-5, "q1": 1.375000465e-6, "q3": 2.625000889e-6, "reps": 21 }, "host": { "median": 2.153330000e-4, "min": 1.642920000e-4, "max": 4.004580000e-4, "q1": 2.005830000e-4, "q3": 2.202080000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 256, "compile": { "median": 8.625000000e-6, "min": 8.208000000e-6, "max": 8.750000000e-6, "q1": 8.459000000e-6, "q3": 8.667000000e-6, "reps": 21 }, "library": { "median": 1.083400000e-5, "min": 1.066700000e-5, "max": 1.120900000e-5, "q1": 1.075000000e-5, "q3": 1.104200000e-5, "reps": 21 }, "pipeline": { "median": 2.583300000e-5, "min": 2.504200000e-5, "max": 3.329200000e-5, "q1": 2.529100000e-5, "q3": 2.595900000e-5, "reps": 21 }, "gpu": { "median": 1.374999556e-6, "min": 1.291666194e-6, "max": 7.387500045e-5, "q1": 1.291666194e-6, "q3": 1.375000465e-6, "reps": 21 }, "host": { "median": 2.138750000e-4, "min": 1.780830000e-4, "max": 2.769590000e-4, "q1": 1.977920000e-4, "q3": 2.193750000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 1024, "compile": { "median": 8.542000000e-6, "min": 8.292000000e-6, "max": 1.145900000e-5, "q1": 8.458000000e-6, "q3": 8.666000000e-6, "reps": 21 }, "library": { "median": 1.100000000e-5, "min": 1.062500000e-5, "max": 1.925000000e-5, "q1": 1.083400000e-5, "q3": 1.108300000e-5, "reps": 21 }, "pipeline": { "median": 2.591600000e-5, "min": 2.516700000e-5, "max": 3.541700000e-5, "q1": 2.579200000e-5, "q3": 2.612500000e-5, "reps": 21 }, "gpu": { "median": 1.499999598e-6, "min": 1.374999556e-6, "max": 1.624999641e-6, "q1": 1.458332918e-6, "q3": 1.500000508e-6, "reps": 21 }, "host": { "median": 2.136670000e-4, "min": 1.936670000e-4, "max": 4.228330000e-4, "q1": 2.092920000e-4, "q3": 2.170420000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
{ "words": 4096, "compile": { "median": 8.542000000e-6, "min": 8.292000000e-6, "max": 1.158300000e-5, "q1": 8.459000000e-6, "q3": 8.750000000e-6, "reps": 21 }, "library": { "median": 1.087500000e-5, "min": 1.066700000e-5, "max": 3.562500000e-5, "q1": 1.083400000e-5, "q3": 1.145800000e-5, "reps": 21 }, "pipeline": { "median": 2.604200000e-5, "min": 2.508300000e-5, "max": 1.914590000e-4, "q1": 2.550000000e-5, "q3": 2.625000000e-5, "reps": 21 }, "gpu": { "median": 1.500000508e-6, "min": 1.416666237e-6, "max": 6.304166618e-5, "q1": 1.458332918e-6, "q3": 3.170833315e-5, "reps": 21 }, "host": { "median": 2.280000000e-4, "min": 1.988340000e-4, "max": 8.358750000e-4, "q1": 2.237090000e-4, "q3": 2.523330000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 }
]
}
]
}
-743
View File
@@ -1,743 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Correctness-gated benchmark harness for the Phase 01 corpus.
//!
//! Reads `benchmarks/manifest.toml`, verifies every fixture against the
//! independent reference and the native GPU before timing it, then writes
//! metadata, raw JSON and a generated markdown report. A fixture that fails
//! correctness is excluded and listed as such; it is never timed.
use std::error::Error;
use std::fmt::Write as _;
use std::fs;
use std::path::PathBuf;
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};
use xenora_metal::NativeCompute;
use xenora_shader::{Architecture, ENTRY_POINT, compile};
const WARMUP_REPS: usize = 2;
const DEFAULT_REPS: usize = 7;
#[derive(Debug, Clone)]
struct Fixture {
name: String,
stage: String,
source: String,
path: String,
input: Vec<u32>,
expected: Vec<u32>,
sizes: Vec<usize>,
}
#[derive(Debug, Clone, Default)]
struct Stats {
median: f64,
min: f64,
max: f64,
q1: f64,
q3: f64,
reps: usize,
}
impl Stats {
fn from_samples(mut samples: Vec<f64>) -> Self {
if samples.is_empty() {
return Self::default();
}
samples.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
let n = samples.len();
let median = percentile(&samples, 0.5);
Self {
median,
min: samples[0],
max: samples[n - 1],
q1: percentile(&samples, 0.25),
q3: percentile(&samples, 0.75),
reps: n,
}
}
}
fn percentile(sorted: &[f64], fraction: f64) -> f64 {
if sorted.is_empty() {
return 0.0;
}
let position = fraction * (sorted.len() - 1) as f64;
let lower = position.floor() as usize;
let upper = position.ceil() as usize;
if lower == upper {
sorted[lower]
} else {
let weight = position - lower as f64;
sorted[lower] * (1.0 - weight) + sorted[upper] * weight
}
}
#[derive(Debug, Clone)]
struct SizeResult {
words: usize,
compile: Stats,
library: Stats,
pipeline: Stats,
gpu: Stats,
host: Stats,
/// Fraction of samples whose GPU timestamp delta was zero.
gpu_zero_fraction: f64,
}
#[derive(Debug, Clone)]
struct FixtureResult {
name: String,
stage: String,
source: String,
status: String,
reason: String,
sizes: Vec<SizeResult>,
}
fn main() -> Result<(), Box<dyn Error>> {
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" => {
output = PathBuf::from(args.next().ok_or("--output needs a path")?);
}
"--reps" => {
reps = args
.next()
.ok_or("--reps needs a count")?
.parse()
.map_err(|_| "--reps must be a positive integer")?;
}
"--help" | "-h" => {
println!("usage: xenora-bench [--output DIR] [--reps N]");
return Ok(());
}
other => return Err(format!("unknown argument {other}").into()),
}
}
if reps == 0 {
return Err("--reps must be at least 1".into());
}
let manifest_text = fs::read_to_string("benchmarks/manifest.toml")?;
let fixtures = parse_manifest(&manifest_text)?;
if fixtures.is_empty() {
return Err("manifest lists no fixtures".into());
}
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
let device = metal.device_name();
let metadata = Metadata::collect(&device, reps);
let mut results = Vec::with_capacity(fixtures.len());
for fixture in &fixtures {
results.push(run_fixture(&metal, fixture, reps));
}
let run_id = metadata.run_id.clone();
let hardware_dir = slug(&device);
let run_dir = output.join(&hardware_dir).join(&run_id);
fs::create_dir_all(&run_dir)?;
fs::write(run_dir.join("metadata.json"), metadata.to_json())?;
fs::write(run_dir.join("results.json"), results_json(&results))?;
fs::write(
run_dir.join("report.md"),
report_markdown(&metadata, &results),
)?;
println!("Benchmark results written to {}", run_dir.display());
for result in &results {
println!(
" {:<16} {:<10} {}",
result.name,
result.status,
if result.reason.is_empty() {
String::new()
} else {
format!("({})", result.reason)
}
);
}
let excluded = results.iter().filter(|r| r.status != "benchmarked").count();
if excluded > 0 {
return Err(format!("{excluded} fixture(s) excluded from timing").into());
}
Ok(())
}
fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> FixtureResult {
let mut result = FixtureResult {
name: fixture.name.clone(),
stage: fixture.stage.clone(),
source: fixture.source.clone(),
status: "not-implemented".to_string(),
reason: String::new(),
sizes: Vec::new(),
};
let code = match fs::read(&fixture.path) {
Ok(code) => code,
Err(error) => {
result.status = "excluded".to_string();
result.reason = format!("cannot read {}: {error}", fixture.path);
return result;
}
};
let compiled = match compile(Architecture::Gfx1030, &code) {
Ok(compiled) => compiled,
Err(error) => {
result.status = "excluded".to_string();
result.reason = format!("compile failed: {error}");
return result;
}
};
// Independent reference on the declared base input.
let reference = match xenora_ref::execute(&code, &fixture.input) {
Ok(reference) => reference,
Err(error) => {
result.status = "excluded".to_string();
result.reason = format!("reference execution failed: {error}");
return result;
}
};
if reference != fixture.expected {
result.status = "excluded".to_string();
result.reason = "reference disagrees with hand-derived expected values".to_string();
return result;
}
// Native correctness at the smallest declared size before any timing.
let base_words = *fixture.sizes.first().unwrap_or(&fixture.input.len());
let base_input = expand(&fixture.input, base_words);
let base_expected = expand(&fixture.expected, base_words);
match metal.run_words(&compiled.msl, ENTRY_POINT, &base_input) {
Ok(actual) if actual == base_expected => {}
Ok(_) => {
result.status = "excluded".to_string();
result.reason = "GPU output disagrees with known answers".to_string();
return result;
}
Err(error) => {
result.status = "excluded".to_string();
result.reason = format!("GPU execution failed: {error}");
return result;
}
}
let mut sizes = Vec::with_capacity(fixture.sizes.len());
for &words in &fixture.sizes {
let input = expand(&fixture.input, words);
let expected = expand(&fixture.expected, words);
let mut compile_samples = Vec::with_capacity(reps);
let mut library_samples = Vec::with_capacity(reps);
let mut pipeline_samples = Vec::with_capacity(reps);
let mut gpu_samples = Vec::with_capacity(reps);
let mut host_samples = Vec::with_capacity(reps);
let mut gpu_zero = 0usize;
let mut mismatch = None;
for rep in 0..(WARMUP_REPS + reps) {
let compile_start = std::time::Instant::now();
let recompiled = match compile(Architecture::Gfx1030, &code) {
Ok(compiled) => compiled,
Err(error) => {
mismatch = Some(format!("compile failed at {words} words: {error}"));
break;
}
};
let compile_seconds = compile_start.elapsed().as_secs_f64();
let profile = match metal.run_words_profiled(&recompiled.msl, ENTRY_POINT, &input) {
Ok(profile) => profile,
Err(error) => {
mismatch = Some(format!("GPU run failed at {words} words: {error}"));
break;
}
};
if profile.output != expected {
mismatch = Some(format!("GPU mismatch at {words} words"));
break;
}
if rep < WARMUP_REPS {
continue;
}
compile_samples.push(compile_seconds);
library_samples.push(profile.library_seconds);
pipeline_samples.push(profile.pipeline_seconds);
gpu_samples.push(profile.gpu_seconds);
host_samples.push(profile.host_seconds);
if profile.gpu_seconds <= 0.0 {
gpu_zero += 1;
}
}
if let Some(reason) = mismatch {
result.status = "excluded".to_string();
result.reason = reason;
return result;
}
let measured = gpu_samples.len();
sizes.push(SizeResult {
words,
compile: Stats::from_samples(compile_samples),
library: Stats::from_samples(library_samples),
pipeline: Stats::from_samples(pipeline_samples),
gpu: Stats::from_samples(gpu_samples),
host: Stats::from_samples(host_samples),
gpu_zero_fraction: if measured == 0 {
0.0
} else {
gpu_zero as f64 / measured as f64
},
});
}
result.sizes = sizes;
result.status = "benchmarked".to_string();
result
}
fn expand(base: &[u32], words: usize) -> Vec<u32> {
(0..words).map(|i| base[i % base.len()]).collect()
}
// --- Manifest parsing (documented subset: [[fixture]] tables, string and int arrays) ---
fn parse_manifest(text: &str) -> Result<Vec<Fixture>, String> {
let mut fixtures = Vec::new();
let mut current: Option<Fixture> = None;
for (line_no, raw) in text.lines().enumerate() {
let line = raw.split('#').next().unwrap_or("").trim();
if line.is_empty() {
continue;
}
if line == "[[fixture]]" {
if let Some(fixture) = current.take() {
fixtures.push(finish(fixture, line_no)?);
}
current = Some(Fixture {
name: String::new(),
stage: String::new(),
source: String::new(),
path: String::new(),
input: Vec::new(),
expected: Vec::new(),
sizes: Vec::new(),
});
continue;
}
let Some(fixture) = current.as_mut() else {
return Err(format!(
"line {}: key outside a [[fixture]] table",
line_no + 1
));
};
let (key, value) = line
.split_once('=')
.ok_or_else(|| format!("line {}: expected key = value", line_no + 1))?;
let key = key.trim();
let value = value.trim();
match key {
"name" => fixture.name = parse_string(value)?,
"stage" => fixture.stage = parse_string(value)?,
"source" => fixture.source = parse_string(value)?,
"path" => fixture.path = parse_string(value)?,
"input" => fixture.input = parse_int_array(value)?,
"expected" => fixture.expected = parse_int_array(value)?,
"sizes" => {
fixture.sizes = parse_int_array(value)?
.into_iter()
.map(|n| n as usize)
.collect();
}
other => return Err(format!("line {}: unknown key {other}", line_no + 1)),
}
}
if let Some(fixture) = current.take() {
fixtures.push(finish(fixture, 0)?);
}
Ok(fixtures)
}
fn finish(fixture: Fixture, line_no: usize) -> Result<Fixture, String> {
let context = if fixture.name.is_empty() {
format!("fixture ending near line {line_no}")
} else {
format!("fixture {}", fixture.name)
};
if fixture.name.is_empty()
|| fixture.stage.is_empty()
|| fixture.source.is_empty()
|| fixture.path.is_empty()
{
return Err(format!("{context}: missing required string field"));
}
if fixture.input.is_empty() || fixture.expected.len() != fixture.input.len() {
return Err(format!(
"{context}: input and expected must be equal-length"
));
}
if fixture.sizes.is_empty() || fixture.sizes.contains(&0) {
return Err(format!(
"{context}: sizes must be a nonempty list of positive integers"
));
}
Ok(fixture)
}
fn parse_string(value: &str) -> Result<String, String> {
let trimmed = value.trim();
let inner = trimmed
.strip_prefix('"')
.and_then(|v| v.strip_suffix('"'))
.ok_or_else(|| format!("expected a quoted string, got {trimmed}"))?;
Ok(inner.to_string())
}
fn parse_int_array(value: &str) -> Result<Vec<u32>, String> {
let trimmed = value.trim();
let inner = trimmed
.strip_prefix('[')
.and_then(|v| v.strip_suffix(']'))
.ok_or_else(|| format!("expected an integer array, got {trimmed}"))?;
if inner.trim().is_empty() {
return Ok(Vec::new());
}
inner
.split(',')
.map(|item| {
item.trim()
.parse::<u32>()
.map_err(|_| format!("invalid integer {}", item.trim()))
})
.collect()
}
// --- Metadata and output ---
struct Metadata {
run_id: String,
timestamp: String,
device: String,
host_arch: String,
os_version: String,
os_build: String,
rustc: String,
xcode: String,
commit: String,
profile: String,
api_validation: String,
shader_validation: String,
power: String,
thermal: String,
reps: usize,
warmup: usize,
}
impl Metadata {
fn collect(device: &str, reps: usize) -> Self {
let seconds = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
Self {
run_id: format!("run-{seconds}"),
timestamp: format!("unix:{seconds}"),
device: device.to_string(),
host_arch: std::env::consts::ARCH.to_string(),
os_version: command_line("sw_vers", &["-productVersion"]),
os_build: command_line("sw_vers", &["-buildVersion"]),
rustc: command_line("rustc", &["-vV"])
.lines()
.next()
.unwrap_or("unknown")
.to_string(),
xcode: command_line("xcodebuild", &["-version"])
.lines()
.next()
.unwrap_or("unknown")
.to_string(),
commit: command_line("git", &["rev-parse", "HEAD"]),
profile: if cfg!(debug_assertions) {
"debug"
} else {
"release"
}
.to_string(),
api_validation: env_or("MTL_DEBUG_LAYER"),
shader_validation: env_or("MTL_SHADER_VALIDATION"),
power: power_source(),
thermal: thermal_state(),
reps,
warmup: WARMUP_REPS,
}
}
fn to_json(&self) -> String {
format!(
"{{\n \"run_id\": {},\n \"timestamp\": {},\n \"device\": {},\n \"host_arch\": {},\n \"os_version\": {},\n \"os_build\": {},\n \"rustc\": {},\n \"xcode\": {},\n \"commit\": {},\n \"profile\": {},\n \"api_validation\": {},\n \"shader_validation\": {},\n \"power\": {},\n \"thermal\": {},\n \"reps\": {},\n \"warmup\": {}\n}}\n",
json_str(&self.run_id),
json_str(&self.timestamp),
json_str(&self.device),
json_str(&self.host_arch),
json_str(&self.os_version),
json_str(&self.os_build),
json_str(&self.rustc),
json_str(&self.xcode),
json_str(&self.commit),
json_str(&self.profile),
json_str(&self.api_validation),
json_str(&self.shader_validation),
json_str(&self.power),
json_str(&self.thermal),
self.reps,
self.warmup
)
}
}
fn command_line(program: &str, args: &[&str]) -> String {
match Command::new(program).args(args).output() {
Ok(output) if output.status.success() => {
String::from_utf8_lossy(&output.stdout).trim().to_string()
}
_ => "unavailable".to_string(),
}
}
fn env_or(key: &str) -> String {
std::env::var(key).unwrap_or_else(|_| "unset".to_string())
}
/// Report the power source line from `pmset`, or `unavailable` off macOS.
fn power_source() -> String {
let output = command_line("pmset", &["-g", "batt"]);
for line in output.lines() {
let line = line.trim();
if line.contains("AC Power") {
return "AC Power".to_string();
}
if line.contains("Battery Power") {
return "Battery Power".to_string();
}
}
"unavailable".to_string()
}
/// Report the CPU thermal and speed limits from `pmset`, compactly.
fn thermal_state() -> String {
let output = command_line("pmset", &["-g", "therm"]);
let mut parts = Vec::new();
for line in output.lines() {
let line = line.trim();
for key in ["CPU_Scheduler_Limit", "CPU_Speed_Limit"] {
if let Some(value) = line.strip_prefix(key) {
parts.push(format!("{key}{}", value.trim()));
}
}
}
if !parts.is_empty() {
parts.join(", ")
} else if output.contains("No thermal warning level has been recorded") {
"no warnings recorded".to_string()
} else {
"unavailable".to_string()
}
}
fn slug(device: &str) -> String {
device
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() {
c.to_ascii_lowercase()
} else {
'-'
}
})
.collect::<String>()
.trim_matches('-')
.to_string()
}
fn json_str(value: &str) -> String {
let mut out = String::with_capacity(value.len() + 2);
out.push('"');
for c in value.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => {
let _ = write!(out, "\\u{:04x}", c as u32);
}
c => out.push(c),
}
}
out.push('"');
out
}
fn stats_json(stats: &Stats) -> String {
format!(
"{{ \"median\": {:.9e}, \"min\": {:.9e}, \"max\": {:.9e}, \"q1\": {:.9e}, \"q3\": {:.9e}, \"reps\": {} }}",
stats.median, stats.min, stats.max, stats.q1, stats.q3, stats.reps
)
}
fn results_json(results: &[FixtureResult]) -> String {
let mut out = String::from("{\n \"fixtures\": [\n");
for (index, result) in results.iter().enumerate() {
let _ = writeln!(
out,
" {{\n \"name\": {},\n \"stage\": {},\n \"source\": {},\n \"status\": {},\n \"reason\": {},\n \"sizes\": [",
json_str(&result.name),
json_str(&result.stage),
json_str(&result.source),
json_str(&result.status),
json_str(&result.reason)
);
for (size_index, size) in result.sizes.iter().enumerate() {
let _ = writeln!(
out,
" {{ \"words\": {}, \"compile\": {}, \"library\": {}, \"pipeline\": {}, \"gpu\": {}, \"host\": {}, \"gpu_zero_fraction\": {:.4} }}{}",
size.words,
stats_json(&size.compile),
stats_json(&size.library),
stats_json(&size.pipeline),
stats_json(&size.gpu),
stats_json(&size.host),
size.gpu_zero_fraction,
if size_index + 1 == result.sizes.len() {
""
} else {
","
}
);
}
let _ = writeln!(
out,
" ]\n }}{}",
if index + 1 == results.len() { "" } else { "," }
);
}
out.push_str(" ]\n}\n");
out
}
fn report_markdown(metadata: &Metadata, results: &[FixtureResult]) -> String {
let mut out = String::new();
let _ = writeln!(out, "# Xenora benchmark report");
let _ = writeln!(out);
let _ = writeln!(
out,
"Generated by `xenora-bench`. Every timed fixture passed its correctness test in this run. \
Timings are single command-buffer samples; see `docs/testing/benchmarks.md` for the protocol."
);
let _ = writeln!(out);
let _ = writeln!(out, "## Environment");
let _ = writeln!(out);
let _ = writeln!(out, "| Field | Value |");
let _ = writeln!(out, "| --- | --- |");
for (key, value) in [
("Device", metadata.device.as_str()),
("Host arch", metadata.host_arch.as_str()),
("macOS", metadata.os_version.as_str()),
("Build", metadata.os_build.as_str()),
("Rust", metadata.rustc.as_str()),
("Xcode", metadata.xcode.as_str()),
("Commit", metadata.commit.as_str()),
("Profile", metadata.profile.as_str()),
("API validation", metadata.api_validation.as_str()),
("Shader validation", metadata.shader_validation.as_str()),
("Power source", metadata.power.as_str()),
("Thermal", metadata.thermal.as_str()),
] {
let _ = writeln!(out, "| {key} | {} |", value.replace('|', "\\|"));
}
let _ = writeln!(
out,
"| Repetitions | {} measured, {} warm-up |",
metadata.reps, metadata.warmup
);
if metadata.power != "AC Power" {
let _ = writeln!(out);
let _ = writeln!(
out,
"> **Protocol note.** The machine was not confirmed on AC power. \
The benchmark protocol in `docs/testing/benchmarks.md` requires AC power, \
so these timings are not protocol-compliant release evidence."
);
}
let _ = writeln!(out);
let _ = writeln!(out, "## Coverage");
let _ = writeln!(out);
let _ = writeln!(out, "| Fixture | Stage | Source | Status |");
let _ = writeln!(out, "| --- | --- | --- | --- |");
for result in results {
let status = if result.reason.is_empty() {
result.status.clone()
} else {
format!("{} ({})", result.status, result.reason)
};
let _ = writeln!(
out,
"| {} | {} | {} | {} |",
result.name,
result.stage,
result.source,
status.replace('|', "\\|")
);
}
let _ = writeln!(out);
let _ = writeln!(out, "## Timings");
let _ = writeln!(out);
let _ = writeln!(
out,
"Durations in microseconds. `compile` is the Rust decode/IR/MSL pipeline, \
`library` and `pipeline` are Metal compilation stages, `gpu` is the command-buffer \
GPU time, and `host` is the wall time of one dispatch. Values are medians with \
interquartile range; minimum and maximum are in `results.json`."
);
let _ = writeln!(out);
let _ = writeln!(
out,
"| Fixture | Words | compile | library | pipeline | gpu | host | IQR(gpu) | zero-gpu |"
);
let _ = writeln!(
out,
"| --- | --- | --- | --- | --- | --- | --- | --- | --- |"
);
for result in results.iter().filter(|r| r.status == "benchmarked") {
for size in &result.sizes {
let _ = writeln!(
out,
"| {} | {} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.0}% |",
result.name,
size.words,
size.compile.median * 1e6,
size.library.median * 1e6,
size.pipeline.median * 1e6,
size.gpu.median * 1e6,
size.host.median * 1e6,
(size.gpu.q3 - size.gpu.q1) * 1e6,
size.gpu_zero_fraction * 100.0
);
}
}
out
}
-14
View File
@@ -1,14 +0,0 @@
[package]
name = "xenora"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[dependencies]
xenora-metal = { path = "../metal" }
xenora-ref = { path = "../ref" }
xenora-shader = { path = "../shader" }
-67
View File
@@ -1,67 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use std::error::Error;
use xenora_metal::NativeCompute;
use xenora_shader::{Architecture, ENTRY_POINT, compile};
const INPUT: [u32; 4] = [0, 1, u32::MAX, 3_989_547_400];
struct Fixture {
name: &'static str,
code: &'static [u8],
expected: [u32; 4],
}
const FIXTURES: [Fixture; 3] = [
Fixture {
name: "add",
code: include_bytes!("../../../fixtures/rdna2/add.bin"),
expected: [305_419_896, 305_419_897, 305_419_895, 0],
},
Fixture {
name: "bitwise-branch",
code: include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin"),
expected: [305_419_896, 305_419_897, 315_315_847, 318_723_824],
},
Fixture {
name: "float-exact",
code: include_bytes!("../../../fixtures/rdna2/float-exact.bin"),
expected: [0x410c_0000, 0x410c_0000, 0x4120_0000, 0x4120_0000],
},
];
pub fn run() -> Result<(), Box<dyn Error>> {
let metal = NativeCompute::new()?;
println!("Metal device: {}", metal.device_name());
for fixture in FIXTURES {
run_fixture(&metal, fixture)?;
}
Ok(())
}
fn run_fixture(metal: &NativeCompute, fixture: Fixture) -> Result<(), Box<dyn Error>> {
let Fixture {
name,
code,
expected,
} = fixture;
println!("Fixture {name}");
let compiled = compile(Architecture::Gfx1030, code)?;
println!(
"Disassembly\n{}\nIR\n{}\nMSL\n{}",
compiled.disassembly, compiled.ir, compiled.msl
);
let reference = xenora_ref::execute(code, &INPUT)?;
if reference != expected {
return Err(format!("reference mismatch: {reference:?} != {expected:?}").into());
}
let actual = metal.run_words(&compiled.msl, ENTRY_POINT, &INPUT)?;
if actual != reference || actual != expected {
return Err(format!("Metal mismatch: {actual:?} != {expected:?}").into());
}
println!("Metal, reference and known answers match: {actual:?}");
Ok(())
}
-29
View File
@@ -1,29 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
mod demo;
use std::process::ExitCode;
fn main() -> ExitCode {
match std::env::args().nth(1).as_deref() {
Some("info") => {
println!(
"Xenora {} ({})",
env!("CARGO_PKG_VERSION"),
std::env::consts::ARCH
);
ExitCode::SUCCESS
}
Some("demo") => match demo::run() {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("demo: {error}");
ExitCode::FAILURE
}
},
_ => {
eprintln!("usage: xenora <info|demo>");
ExitCode::from(2)
}
}
}
-16
View File
@@ -1,16 +0,0 @@
[package]
name = "xenora-decoder"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
publish = false
[dependencies]
xenora-isa = { path = "../isa" }
[dev-dependencies]
xenora-ref = { path = "../ref" }
[lints]
workspace = true
-500
View File
@@ -1,500 +0,0 @@
//! Decoder for Xenora's bounded little-endian gfx1030 instruction stream.
use std::fmt;
pub use xenora_isa::{
Architecture, ExportTarget, Instruction, InterpolationPhase, ScalarSource, VectorSource,
};
use xenora_isa::{
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0,
S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32,
V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32,
V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
};
/// A successfully decoded instruction and its location in the input stream.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DecodedInstruction {
/// Byte offset from the start of the stream.
pub offset: usize,
/// Total size in bytes, including any literal word.
pub byte_len: u8,
/// The decoded instruction and operand fields.
pub instruction: Instruction,
}
impl fmt::Display for DecodedInstruction {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{:04x}: {}", self.offset, self.instruction)
}
}
/// Decoder failures classified for callers.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DecodeErrorKind {
/// An instruction, second word or literal extends past the available input.
Truncated {
/// Number of bytes required at the instruction start.
needed: u8,
/// Number of bytes available at the instruction start.
available: usize,
},
/// No supported opcode pattern matches the first word.
UnsupportedOpcode {
/// First instruction word in host integer order.
word: u32,
},
/// A supported opcode uses an operand or modifier outside the subset.
UnsupportedForm {
/// Opcode mnemonic.
mnemonic: &'static str,
/// Details of the unsupported or reserved fields.
detail: &'static str,
},
/// A forward branch leaves the stream or lands inside an instruction.
InvalidBranchTarget {
/// Destination byte offset from the start of the stream.
target: usize,
},
}
/// A decoder error and the offset of the offending instruction.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DecodeError {
/// Byte offset from the start of the stream.
pub offset: usize,
/// Decoder-specific failure.
pub kind: DecodeErrorKind,
}
impl fmt::Display for DecodeError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "gfx1030 decode at byte 0x{:x}: ", self.offset)?;
match self.kind {
DecodeErrorKind::Truncated { needed, available } => {
write!(
formatter,
"instruction requires {needed} bytes, found {available}"
)
}
DecodeErrorKind::UnsupportedOpcode { word } => {
write!(formatter, "unsupported opcode in 0x{word:08x}")
}
DecodeErrorKind::UnsupportedForm { mnemonic, detail } => {
write!(formatter, "unsupported {mnemonic} form: {detail}")
}
DecodeErrorKind::InvalidBranchTarget { target } => {
write!(
formatter,
"branch target 0x{target:x} is outside instruction boundaries"
)
}
}
}
}
impl std::error::Error for DecodeError {}
/// Decodes a stream of instructions. Program termination, memory hazards and
/// register initialization are checked by later stages.
///
/// # Errors
///
/// Returns the failing byte offset for a truncated instruction, unsupported
/// opcode, unsupported form or invalid branch target. An empty stream
/// decodes to an empty list.
pub fn decode(
architecture: Architecture,
bytes: &[u8],
) -> Result<Vec<DecodedInstruction>, DecodeError> {
let decode_instruction = match architecture {
Architecture::Gfx1030 => decode_gfx1030,
};
let mut result = Vec::new();
let mut offset = 0;
while offset < bytes.len() {
let (instruction, byte_len) = decode_instruction(&bytes[offset..], offset)
.map_err(|kind| DecodeError { offset, kind })?;
result.push(DecodedInstruction {
offset,
byte_len,
instruction,
});
offset += usize::from(byte_len);
}
for decoded in &result {
if let Instruction::Branch { target }
| Instruction::BranchSccZero { target }
| Instruction::BranchExecZero { target }
| Instruction::BranchVccZero { target } = decoded.instruction
&& result
.binary_search_by_key(&target, |item| item.offset)
.is_err()
{
return Err(DecodeError {
offset: decoded.offset,
kind: DecodeErrorKind::InvalidBranchTarget { target },
});
}
}
Ok(result)
}
fn word(bytes: &[u8], end: u8) -> Result<u32, DecodeErrorKind> {
let end_index = usize::from(end);
let Some(word) = bytes
.get(end_index - 4..end_index)
.and_then(|word| <[u8; 4]>::try_from(word).ok())
else {
return Err(DecodeErrorKind::Truncated {
needed: end,
available: bytes.len(),
});
};
Ok(u32::from_le_bytes(word))
}
fn unsupported(mnemonic: &'static str, detail: &'static str) -> DecodeErrorKind {
DecodeErrorKind::UnsupportedForm { mnemonic, detail }
}
fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), DecodeErrorKind> {
let first = word(bytes, 4)?;
if BUFFER_LOAD_DWORD.matches(first) {
let len = BUFFER_LOAD_DWORD.byte_len();
let second = word(bytes, len)?;
let (data, index, resource) = buffer_operands(first, second, "buffer_load_dword")?;
return Ok((
Instruction::BufferLoadDword {
data,
index,
resource,
},
len,
));
}
if BUFFER_STORE_DWORD.matches(first) {
let len = BUFFER_STORE_DWORD.byte_len();
let second = word(bytes, len)?;
let (data, index, resource) = buffer_operands(first, second, "buffer_store_dword")?;
return Ok((
Instruction::BufferStoreDword {
data,
index,
resource,
},
len,
));
}
if EXP.matches(first) {
let len = EXP.byte_len();
let sources = word(bytes, len)?.to_le_bytes();
// RDNA 2 ISA Table 56. Match all operand and reserved bits, including
// the four enable bits, compression, DONE and valid-mask flags.
let target = match first & 0x03ff_ffff {
0x08cf => ExportTarget::Position0,
0x020f => ExportTarget::Parameter0,
0x180f => ExportTarget::RenderTarget0,
_ => {
return Err(unsupported(
"exp",
"expected full uncompressed POS0 done, PARAM0, or MRT0 done vm",
));
}
};
return Ok((Instruction::Export { target, sources }, len));
}
for (opcode, phase) in [
(V_INTERP_P1_F32, InterpolationPhase::First),
(V_INTERP_P2_F32, InterpolationPhase::Second),
] {
if opcode.matches(first) {
return Ok((
Instruction::Interpolate {
phase,
dst: (first >> 18) as u8,
coordinate: first as u8,
attribute: ((first >> 10) & 0x3f) as u8,
component: ((first >> 8) & 3) as u8,
},
opcode.byte_len(),
));
}
}
if V_MOV_B32.matches(first) {
return move_b32(first, bytes);
}
if V_ADD_NC_U32.matches(first) {
let len = V_ADD_NC_U32.byte_len();
let second = word(bytes, len)?;
return Ok((add_u32(first, second)?, len));
}
if S_MOV_B32.matches(first) {
let dst = ((first >> 16) & 0x7f) as u8;
if !matches!(dst, 0..=107 | 126..=127) {
return Err(unsupported(
"s_mov_b32",
"expected a normal SGPR or EXEC/VCC destination",
));
}
let (src, len) = scalar_source(first as u8, bytes, "s_mov_b32")?;
return Ok((Instruction::ScalarMoveB32 { dst, src }, len));
}
if S_CMP_EQ_U32.matches(first) {
let src0_bits = first as u8;
let src1_bits = (first >> 8) as u8;
if src0_bits == 255 && src1_bits == 255 {
return Err(unsupported(
"s_cmp_eq_u32",
"only one source may select a literal",
));
}
let (src0, len0) = scalar_source(src0_bits, bytes, "s_cmp_eq_u32")?;
let (src1, len1) = scalar_source(src1_bits, bytes, "s_cmp_eq_u32")?;
return Ok((
Instruction::ScalarCompareEqU32 { src0, src1 },
len0.max(len1),
));
}
if S_BRANCH.matches(first) {
let target = branch_target(first, offset, "s_branch")?;
return Ok((Instruction::Branch { target }, S_BRANCH.byte_len()));
}
if S_CBRANCH_SCC0.matches(first) {
let target = branch_target(first, offset, "s_cbranch_scc0")?;
return Ok((
Instruction::BranchSccZero { target },
S_CBRANCH_SCC0.byte_len(),
));
}
if S_CBRANCH_EXECZ.matches(first) {
let target = branch_target(first, offset, "s_cbranch_execz")?;
return Ok((
Instruction::BranchExecZero { target },
S_CBRANCH_EXECZ.byte_len(),
));
}
if S_CBRANCH_VCCZ.matches(first) {
let target = branch_target(first, offset, "s_cbranch_vccz")?;
return Ok((
Instruction::BranchVccZero { target },
S_CBRANCH_VCCZ.byte_len(),
));
}
if V_LSHLREV_B32.matches(first) {
let (dst, src0, src1) = vop2_registers(first, "v_lshlrev_b32_e32")?;
return Ok((
Instruction::VectorLshlrevB32 { dst, src0, src1 },
V_LSHLREV_B32.byte_len(),
));
}
if V_ASHRREV_I32.matches(first) {
let (dst, src0, src1) = vop2_registers(first, "v_ashrrev_i32_e32")?;
return Ok((
Instruction::VectorAshrrevI32 { dst, src0, src1 },
V_ASHRREV_I32.byte_len(),
));
}
if V_LSHRREV_B32.matches(first) {
let (dst, src0, src1) = vop2_registers(first, "v_lshrrev_b32_e32")?;
return Ok((
Instruction::VectorLshrrevB32 { dst, src0, src1 },
V_LSHRREV_B32.byte_len(),
));
}
if V_AND_B32.matches(first) {
let (dst, src0, src1) = vop2_registers(first, "v_and_b32_e32")?;
return Ok((
Instruction::VectorAndB32 { dst, src0, src1 },
V_AND_B32.byte_len(),
));
}
if V_OR_B32.matches(first) {
let (dst, src0, src1) = vop2_registers(first, "v_or_b32_e32")?;
return Ok((
Instruction::VectorOrB32 { dst, src0, src1 },
V_OR_B32.byte_len(),
));
}
if V_XOR_B32.matches(first) {
let (dst, src0, src1) = vop2_registers(first, "v_xor_b32_e32")?;
return Ok((
Instruction::VectorXorB32 { dst, src0, src1 },
V_XOR_B32.byte_len(),
));
}
if V_ADD_F32.matches(first) {
let (dst, src0, src1) = vop2_registers(first, "v_add_f32_e32")?;
return Ok((
Instruction::VectorAddF32 { dst, src0, src1 },
V_ADD_F32.byte_len(),
));
}
if V_MUL_F32.matches(first) {
let (dst, src0, src1) = vop2_registers(first, "v_mul_f32_e32")?;
return Ok((
Instruction::VectorMulF32 { dst, src0, src1 },
V_MUL_F32.byte_len(),
));
}
if S_WAITCNT.matches(first) {
return scalar_form(
first,
S_WAITCNT.byte_len(),
0xbf8c_3f70,
Instruction::WaitLoad,
"expected vmcnt(0) alone",
);
}
if S_WAITCNT_VSCNT.matches(first) {
return scalar_form(
first,
S_WAITCNT_VSCNT.byte_len(),
0xbbfd_0000,
Instruction::WaitStore,
"expected null, 0",
);
}
if S_ENDPGM.matches(first) {
return scalar_form(
first,
S_ENDPGM.byte_len(),
0xbf81_0000,
Instruction::EndProgram,
"expected zero immediate",
);
}
Err(DecodeErrorKind::UnsupportedOpcode { word: first })
}
fn scalar_source(
bits: u8,
bytes: &[u8],
mnemonic: &'static str,
) -> Result<(ScalarSource, u8), DecodeErrorKind> {
let value = u32::from(bits);
match bits {
0..=105 => Ok((ScalarSource::Register(bits), 4)),
128..=192 => Ok((ScalarSource::Immediate(value - 128), 4)),
193..=208 => Ok((ScalarSource::Immediate(192u32.wrapping_sub(value)), 4)),
255 => Ok((ScalarSource::Immediate(word(bytes, 8)?), 8)),
_ => Err(unsupported(
mnemonic,
"expected a normal SGPR, inline integer or literal",
)),
}
}
fn branch_target(
first: u32,
offset: usize,
mnemonic: &'static str,
) -> Result<usize, DecodeErrorKind> {
let displacement = first as u16 as i16;
let words = usize::try_from(displacement)
.map_err(|_| unsupported(mnemonic, "expected a forward branch"))?;
offset
.checked_add(4 + words * 4)
.ok_or_else(|| unsupported(mnemonic, "target byte offset overflowed"))
}
fn vop2_registers(first: u32, mnemonic: &'static str) -> Result<(u8, u8, u8), DecodeErrorKind> {
if first & 0x100 == 0 {
return Err(unsupported(
mnemonic,
"expected two unmodified VGPR sources",
));
}
Ok(((first >> 17) as u8, first as u8, (first >> 9) as u8))
}
fn buffer_operands(
first: u32,
second: u32,
mnemonic: &'static str,
) -> Result<(u8, u8, u8), DecodeErrorKind> {
// OFFSET, OFFEN, IDXEN, GLC, DLC, LDS and the reserved bit before OP.
const ADDRESS_MODE_MASK: u32 = 0x0003_ffff;
const IDXEN: u32 = 1 << 13;
// SOFFSET is inline zero. TFE, SLC and the reserved high operand bit are zero.
if first & ADDRESS_MODE_MASK != IDXEN || second & 0xffe0_0000 != 0x8000_0000 {
return Err(unsupported(
mnemonic,
"expected idxen alone with zero offsets",
));
}
let index = second as u8;
let data = (second >> 8) as u8;
let resource = ((second >> 16) & 0x1f) as u8 * 4;
// AMD RDNA 2 ISA §3.6.2. A resource descriptor requires four normal SGPRs.
if resource > 102 {
return Err(unsupported(
mnemonic,
"resource descriptor must fit in normal SGPRs",
));
}
Ok((data, index, resource))
}
fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKind> {
let dst = (first >> 17) as u8;
let source = first & 0x1ff;
let base_len = V_MOV_B32.byte_len();
let (src, len) = match source {
128..=192 => (VectorSource::Immediate(source - 128), base_len),
193..=208 => (
VectorSource::Immediate(192u32.wrapping_sub(source)),
base_len,
),
// AMD RDNA 2 ISA Table 77: VOP1 source selector 242 supplies +1.0f.
242 => (VectorSource::Immediate(0x3f80_0000), base_len),
255 => {
let len = base_len + 4;
(VectorSource::Immediate(word(bytes, len)?), len)
}
256..=511 => (VectorSource::Register(source as u8), base_len),
_ => {
return Err(unsupported(
"v_mov_b32_e32",
"expected a VGPR, inline integer, inline +1.0f or literal",
));
}
};
Ok((Instruction::MoveB32 { dst, src }, len))
}
fn add_u32(first: u32, second: u32) -> Result<Instruction, DecodeErrorKind> {
let src0 = second & 0x1ff;
let src1 = (second >> 9) & 0x1ff;
// All output and input modifiers are clear. The unused third source uses
// the gfx1030 assembler's inline-zero operand encoding.
if first & 0xff00 != 0 || second >> 18 != 128 || src0 < 256 || src1 < 256 {
return Err(unsupported(
"v_add_nc_u32_e64",
"expected two VGPR sources and no modifiers",
));
}
Ok(Instruction::AddNoCarryU32 {
dst: first as u8,
src0: src0 as u8,
src1: src1 as u8,
})
}
fn scalar_form(
word: u32,
byte_len: u8,
expected: u32,
instruction: Instruction,
detail: &'static str,
) -> Result<(Instruction, u8), DecodeErrorKind> {
if word == expected {
Ok((instruction, byte_len))
} else {
Err(unsupported(instruction.mnemonic(), detail))
}
}
-699
View File
@@ -1,699 +0,0 @@
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use xenora_decoder::{
Architecture, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction, ScalarSource,
VectorSource, decode,
};
use xenora_ref::{BranchCondition, Op, Source, VectorAlu};
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
const BITWISE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
const SHIFT_FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/shifts.bin");
const OR_FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/or.bin");
const FLOAT_FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/float-exact.bin");
#[test]
fn decodes_each_fixture_instruction_with_offset_and_length() {
let instructions = decode(Architecture::Gfx1030, FIXTURE).unwrap();
let wanted = [
(
0,
8,
Instruction::BufferLoadDword {
data: 1,
index: 0,
resource: 0,
},
),
(8, 4, Instruction::WaitLoad),
(
12,
8,
Instruction::MoveB32 {
dst: 2,
src: VectorSource::Immediate(0x1234_5678),
},
),
(
20,
8,
Instruction::AddNoCarryU32 {
dst: 1,
src0: 1,
src1: 2,
},
),
(
28,
8,
Instruction::BufferStoreDword {
data: 1,
index: 0,
resource: 4,
},
),
(36, 4, Instruction::WaitStore),
(40, 4, Instruction::EndProgram),
]
.map(|(offset, byte_len, instruction)| DecodedInstruction {
offset,
byte_len,
instruction,
});
assert_eq!(instructions, wanted);
}
#[test]
fn every_non_boundary_prefix_reports_the_incomplete_instruction() {
let lengths = [8, 4, 8, 8, 8, 4, 4];
let mut offset = 0;
for len in lengths {
for available in 1..len {
let prefix = &FIXTURE[..offset + usize::from(available)];
let needed = if available < 4 { 4 } else { len };
assert_eq!(
decode(Architecture::Gfx1030, prefix).unwrap_err(),
DecodeError {
offset,
kind: DecodeErrorKind::Truncated {
needed,
available: usize::from(available),
},
}
);
assert_eq!(xenora_ref::decode(prefix).unwrap_err().offset, offset);
}
offset += usize::from(len);
}
}
#[test]
fn rejects_other_opcodes_and_noncanonical_operands() {
let cases: &[(&[u32], &str)] = &[
(&[0xe030_0000, 0x8000_0100], "buffer_load_dword"),
(&[0xe070_2000, 0x8101_0100], "buffer_store_dword"),
(&[0xe070_2000, 0x801b_0100], "buffer_store_dword"),
(&[0xbf8c_3f71], "s_waitcnt"),
(&[0xbbfd_0001], "s_waitcnt_vscnt"),
(&[0x7e04_0200], "v_mov_b32_e32"),
(&[0x7e04_02fa, 0], "v_mov_b32_e32"),
(&[0xd525_8001, 0x0202_0501], "v_add_nc_u32_e64"),
(&[0xd525_0001, 0x0202_0480], "v_add_nc_u32_e64"),
(&[0xbf81_0001], "s_endpgm"),
(&[0xbefc_0387], "s_mov_b32"),
(&[0xbf06_87fe], "s_cmp_eq_u32"),
(&[0xbf06_ffff, 0], "s_cmp_eq_u32"),
(&[0xbf82_ffff], "s_branch"),
(&[0xbf84_fffe], "s_cbranch_scc0"),
(&[0x3602_0680], "v_and_b32_e32"),
(&[0x3803_fe80], "v_or_b32_e32"),
(&[0x3803_fe08], "v_or_b32_e32"),
(&[0x3803_feff, 0xdead_beef], "v_or_b32_e32"),
(&[0x3803_fefa, 0xff00_e401], "v_or_b32_e32"),
(&[0x3803_fef9, 0x0606_0601], "v_or_b32_e32"),
(&[0x3402_0480], "v_lshlrev_b32_e32"),
(&[0x2dff_fe08], "v_lshrrev_b32_e32"),
(&[0x3402_04ff, 0xdead_beef], "v_lshlrev_b32_e32"),
(&[0x2dff_fefa, 0xff00_e401], "v_lshrrev_b32_e32"),
(&[0x3402_04f9, 0x0606_0601], "v_lshlrev_b32_e32"),
(&[0x1002_06f2], "v_mul_f32_e32"),
];
for (words, mnemonic) in cases {
let bytes: Vec<_> = words.iter().flat_map(|word| word.to_le_bytes()).collect();
let error = decode(Architecture::Gfx1030, &bytes).unwrap_err();
assert_eq!(error.offset, 0);
assert_eq!(xenora_ref::decode(&bytes).unwrap_err().offset, 0);
assert!(matches!(
error.kind,
DecodeErrorKind::UnsupportedForm { mnemonic: actual, .. } if actual == *mnemonic
));
}
assert_eq!(xenora_ref::decode(&[0xff; 4]).unwrap_err().offset, 0);
assert_eq!(
decode(Architecture::Gfx1030, &[0xff; 4]).unwrap_err().kind,
DecodeErrorKind::UnsupportedOpcode { word: 0xffff_ffff }
);
}
#[test]
fn rejects_targets_at_eof_or_inside_a_literal() {
for (words, target) in [
([0xbf82_0002u32, 0x7e04_02ff, 0x1234_5678], 12),
([0xbf84_0001u32, 0x7e04_02ff, 0x1234_5678], 8),
] {
let bytes: Vec<_> = words.iter().flat_map(|word| word.to_le_bytes()).collect();
assert_eq!(
decode(Architecture::Gfx1030, &bytes).unwrap_err(),
DecodeError {
offset: 0,
kind: DecodeErrorKind::InvalidBranchTarget { target },
}
);
}
}
#[test]
fn accepts_zero_displacement_to_the_following_instruction() {
let bytes = [0, 0, 0x82, 0xbf, 0, 0, 0x81, 0xbf];
let instructions = decode(Architecture::Gfx1030, &bytes).unwrap();
assert_eq!(
instructions[0].instruction,
Instruction::Branch { target: 4 }
);
}
#[test]
fn scalar_sources_keep_literal_width_and_register_class() {
// s_mov_b32 s10, 0x11223344 and s_cmp_eq_u32 s10, 0x11223344.
let words = [0xbe8a_03ffu32, 0x1122_3344, 0xbf06_ff0a, 0x1122_3344];
let bytes: Vec<_> = words.iter().flat_map(|word| word.to_le_bytes()).collect();
let decoded = decode(Architecture::Gfx1030, &bytes).unwrap();
assert_eq!(decoded[0].byte_len, 8);
assert_eq!(decoded[1].offset, 8);
assert_eq!(decoded[1].byte_len, 8);
assert_eq!(
decoded[1].instruction.to_string(),
"s_cmp_eq_u32 s10, 0x11223344"
);
assert_eq!(
decode(Architecture::Gfx1030, &bytes[..12]).unwrap_err(),
DecodeError {
offset: 8,
kind: DecodeErrorKind::Truncated {
needed: 8,
available: 4
},
}
);
}
fn reference_source(vector: VectorSource) -> Source {
match vector {
VectorSource::Register(reg) => Source::Register(reg),
VectorSource::Immediate(bits) => Source::Immediate(bits),
}
}
fn reference_scalar(scalar: ScalarSource) -> Source {
match scalar {
ScalarSource::Register(reg) => Source::Register(reg),
ScalarSource::Immediate(bits) => Source::Immediate(bits),
}
}
fn reference_op(instruction: Instruction) -> Op {
match instruction {
Instruction::BufferLoadDword {
data,
index,
resource,
} => Op::Load {
data,
index,
resource,
},
Instruction::BufferStoreDword {
data,
index,
resource,
} => Op::Store {
data,
index,
resource,
},
Instruction::WaitLoad => Op::WaitRead,
Instruction::WaitStore => Op::WaitWrite,
Instruction::MoveB32 { dst, src } => Op::Move(dst, reference_source(src)),
Instruction::AddNoCarryU32 { dst, src0, src1 } => Op::Add(dst, src0, src1),
Instruction::ScalarMoveB32 { dst, src } => Op::ScalarMove(dst, reference_scalar(src)),
Instruction::ScalarCompareEqU32 { src0, src1 } => {
Op::CompareEqual(reference_scalar(src0), reference_scalar(src1))
}
Instruction::BranchSccZero { target } => Op::Branch {
target,
condition: BranchCondition::SccZero,
},
Instruction::BranchExecZero { target } => Op::Branch {
target,
condition: BranchCondition::ExecZero,
},
Instruction::BranchVccZero { target } => Op::Branch {
target,
condition: BranchCondition::VccZero,
},
Instruction::Branch { target } => Op::Branch {
target,
condition: BranchCondition::Always,
},
Instruction::VectorAndB32 { dst, src0, src1 } => {
Op::Vector(VectorAlu::And, dst, src0, src1)
}
Instruction::VectorLshlrevB32 { dst, src0, src1 } => {
Op::Vector(VectorAlu::ShiftLeft, dst, src0, src1)
}
Instruction::VectorAshrrevI32 { dst, src0, src1 } => {
Op::Vector(VectorAlu::ArithmeticShiftRight, dst, src0, src1)
}
Instruction::VectorLshrrevB32 { dst, src0, src1 } => {
Op::Vector(VectorAlu::ShiftRight, dst, src0, src1)
}
Instruction::VectorOrB32 { dst, src0, src1 } => Op::Vector(VectorAlu::Or, dst, src0, src1),
Instruction::VectorXorB32 { dst, src0, src1 } => {
Op::Vector(VectorAlu::Xor, dst, src0, src1)
}
Instruction::VectorAddF32 { dst, src0, src1 } => {
Op::Vector(VectorAlu::FloatAdd, dst, src0, src1)
}
Instruction::VectorMulF32 { dst, src0, src1 } => {
Op::Vector(VectorAlu::FloatMultiply, dst, src0, src1)
}
Instruction::Export { .. } | Instruction::Interpolate { .. } => {
panic!("compute reference matrix received a graphics instruction")
}
Instruction::EndProgram => Op::End,
}
}
#[test]
#[ignore = "requires LLVM with the gfx1030 AMDGPU target"]
fn compares_fixture_instructions_against_llvm() {
let high_registers: &[u8] = &[
0xfe, 0x03, 0xfe, 0x7f, 0xff, 0, 0x25, 0xd5, 0x80, 0xff, 0x03, 0x02, 0, 0, 0x81, 0xbf,
];
let matrix = assemble_matrix();
let mut forms = std::collections::BTreeSet::new();
let mut count = 0;
for fixture in [
FIXTURE,
BITWISE_FIXTURE,
FLOAT_FIXTURE,
OR_FIXTURE,
SHIFT_FIXTURE,
include_bytes!("../../../fixtures/rdna2/ashr.bin"),
high_registers,
&matrix,
] {
count += compare_against_llvm(fixture, &mut forms);
}
assert_eq!(forms.len(), 21, "forms compared: {forms:?}");
eprintln!(
"{count} three-way instruction comparisons across {} forms",
forms.len()
);
}
fn assemble_matrix() -> Vec<u8> {
// Cover register banks and extrema, immediate classes in both scalar
// compare positions, zero displacement and branches over literal words.
let mut assembly = String::from(
"
buffer_load_dword v255, v128, s[100:103], 0 idxen
buffer_store_dword v128, v255, s[96:99], 0 idxen
v_and_b32_e32 v255, v128, v254
v_xor_b32_e32 v128, v255, v127
v_or_b32_e32 v255, v255, v255
v_or_b32_e32 v0, v0, v0
v_lshlrev_b32_e32 v255, v128, v0
v_lshrrev_b32_e32 v0, v255, v128
v_ashrrev_i32_e32 v255, v0, v1
v_add_f32_e32 v255, v254, v128
v_mul_f32_e32 v128, v127, v255
s_mov_b32 s105, s104
s_mov_b32 s0, 0xdeadbeef
s_cmp_eq_u32 s105, s0
s_cmp_eq_u32 s105, 0xdeadbeef
s_cmp_eq_u32 0xdeadbeef, s105
s_cmp_eq_u32 -16, 64
s_cmp_eq_u32 -16, s105
s_cmp_eq_u32 s105, -16
s_cmp_eq_u32 -16, 0xdeadbeef
s_cmp_eq_u32 0xdeadbeef, -16
s_cbranch_scc0 0
s_mov_b32 exec_lo, 0
s_mov_b32 exec_hi, -1
s_mov_b32 vcc_lo, 0
s_mov_b32 vcc_hi, -1
s_cbranch_execz 0
s_cbranch_vccz 0
s_branch 2
v_mov_b32_e32 v128, 0x12345678
v_mov_b32_e32 v255, lit(0x1)
s_mov_b32 s105, lit(0x1)
s_cmp_eq_u32 s105, lit(0x1)
",
);
use std::fmt::Write as _;
for value in -16..=64 {
writeln!(assembly, "v_mov_b32_e32 v255, {value}").unwrap();
writeln!(assembly, "s_mov_b32 s105, {value}").unwrap();
writeln!(assembly, "s_cmp_eq_u32 {value}, {value}").unwrap();
}
assembly.push_str("s_endpgm\n");
let output = llvm_mc(&[], assembly.as_bytes());
assert_llvm_success(&output);
let stdout = String::from_utf8(output.stdout).unwrap();
let encodings: Vec<_> = stdout
.lines()
.filter_map(|line| line.split_once("; encoding: ["))
.map(|(_, encoding)| encoding_bytes(encoding))
.collect();
assert_eq!(
encodings.len(),
assembly
.lines()
.filter(|line| !line.trim().is_empty())
.count(),
"LLVM must encode every matrix row"
);
encodings.into_iter().flatten().collect()
}
fn encoding_bytes(encoding: &str) -> Vec<u8> {
encoding
.trim_end_matches(']')
.split(',')
.map(|byte| u8::from_str_radix(byte.trim().trim_start_matches("0x"), 16).unwrap())
.collect()
}
fn llvm_mc(mode: &[&str], input: &[u8]) -> std::process::Output {
let executable = std::env::var_os("LLVM_BIN").map_or_else(
|| PathBuf::from("llvm-mc"),
|directory| PathBuf::from(directory).join("llvm-mc"),
);
let mut child = Command::new(executable)
.args(mode)
.args([
"-show-encoding",
"-triple=amdgcn-amd-amdhsa",
"-mcpu=gfx1030",
"-mattr=+wavefrontsize32",
])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("launch llvm-mc (provide its directory in LLVM_BIN or put it on PATH)");
child.stdin.take().unwrap().write_all(input).unwrap();
child.wait_with_output().unwrap()
}
fn assert_llvm_success(output: &std::process::Output) {
assert!(
output.status.success() && output.stderr.is_empty(),
"llvm-mc failed or emitted diagnostics: {}",
String::from_utf8_lossy(&output.stderr)
);
}
fn compare_against_llvm(
fixture: &[u8],
forms: &mut std::collections::BTreeSet<&'static str>,
) -> usize {
let output = llvm_disassemble(fixture);
assert_llvm_success(&output);
let stdout = String::from_utf8(output.stdout).unwrap();
let llvm: Vec<_> = stdout
.lines()
.filter_map(|line| line.split_once("; encoding: ["))
.collect();
let xenora = decode(Architecture::Gfx1030, fixture).unwrap();
assert_eq!(llvm.len(), xenora.len());
let reference = xenora_ref::decode(fixture).unwrap();
let count = llvm.len();
assert_eq!(count, reference.len());
let mut llvm_offset = 0;
for (((assembly, encoding), decoded), reference) in llvm.into_iter().zip(xenora).zip(reference)
{
let llvm_bytes = encoding_bytes(encoding);
let llvm_end = llvm_offset + llvm_bytes.len();
assert_eq!(decoded.offset, llvm_offset);
assert_eq!(reference.offset, llvm_offset);
assert_eq!(usize::from(decoded.byte_len), llvm_bytes.len());
assert_eq!(reference.byte_len, llvm_bytes.len());
assert_eq!(llvm_bytes, fixture[llvm_offset..llvm_end]);
let assembly = normalize_llvm_assembly(assembly.trim(), llvm_end);
assert_eq!(
decoded.instruction.to_string(),
assembly,
"LLVM at {llvm_offset:#x}"
);
assert_eq!(
reference.op,
reference_op(decoded.instruction),
"reference at {llvm_offset:#x}"
);
forms.insert(decoded.instruction.mnemonic());
llvm_offset = llvm_end;
}
assert_eq!(llvm_offset, fixture.len());
count
}
fn llvm_disassemble(fixture: &[u8]) -> std::process::Output {
let input = fixture
.iter()
.map(|byte| format!("0x{byte:02x} "))
.collect::<String>();
llvm_mc(&["-disassemble"], input.as_bytes())
}
#[test]
#[ignore = "requires LLVM with the gfx1030 AMDGPU target"]
fn distinguishes_llvm_invalid_encodings_from_xenora_subset_rejections() {
let malformed: &[&[u32]] = &[
&[0xffff_ffff],
&[0xe030_2000],
&[0xd525_0001],
&[0xd51a_0001],
&[0xd516_0001],
];
let outside_subset: &[&[u32]] = &[
&[0x7e04_0200], // VOP1 SGPR source
&[0x3803_fe80], // OR with an inline SRC0
&[0x3803_fe08], // OR with an SGPR SRC0
&[0x3803_feff, 0xdead_beef], // OR with a literal SRC0
&[0x3803_fefa, 0xff00_e401], // OR DPP
&[0x3803_fef9, 0x0606_0601], // OR SDWA
&[0xd51c_0001, 0x0203_ff01], // OR e64
&[0x3402_0480], // Shift with inline SRC0
&[0x2dff_fe08], // Shift with SGPR SRC0
&[0x3402_04ff, 0xdead_beef], // Shift with literal SRC0
&[0x2dff_fefa, 0xff00_e401], // Shift DPP
&[0x3402_04f9, 0x0606_0601], // Shift SDWA
&[0xd51a_0001, 0x0202_0501], // Left shift e64
&[0xd516_0001, 0x0202_0501], // Right shift e64
&[0x3602_0680], // VOP2 inline source
&[0xbf8c_3f71], // Different wait counter
&[0xbf82_ffff], // Backward branch
&[0xbf82_0001, 0xbf81_0000], // Branch to EOF
&[0xbf84_0001, 0x7e04_02ff, 0x1234_5678, 0xbf81_0000], // Branch into literal
];
for (words, llvm_accepts) in malformed
.iter()
.map(|words| (words, false))
.chain(outside_subset.iter().map(|words| (words, true)))
{
let bytes: Vec<_> = words.iter().flat_map(|word| word.to_le_bytes()).collect();
assert_eq!(decode(Architecture::Gfx1030, &bytes).unwrap_err().offset, 0);
assert_eq!(xenora_ref::decode(&bytes).unwrap_err().offset, 0);
let output = llvm_disassemble(&bytes);
if llvm_accepts {
assert_llvm_success(&output);
assert!(!output.stdout.is_empty());
} else {
assert!(
String::from_utf8_lossy(&output.stderr).contains("invalid instruction encoding")
);
assert!(output.stdout.is_empty());
}
}
eprintln!(
"{} malformed and {} out-of-subset LLVM probes",
malformed.len(),
outside_subset.len()
);
}
fn literal_bits(text: &str) -> Option<u32> {
let digits = text
.strip_prefix("lit(")?
.strip_suffix(')')?
.strip_prefix("0x")?;
u32::from_str_radix(digits, 16).ok()
}
fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
let (mnemonic, operands) = assembly.split_once(' ').unwrap_or((assembly, ""));
match mnemonic {
"s_waitcnt_vscnt" if operands == "null, 0x0" => format!("{mnemonic} null, 0"),
"s_branch" | "s_cbranch_scc0" | "s_cbranch_execz" | "s_cbranch_vccz" => {
let displacement: usize = operands.parse().unwrap();
let target = next_offset + displacement * 4;
format!("{mnemonic} -> 0x{target:04x}")
}
"v_mov_b32_e32" => {
let (destination, source) = operands.split_once(", ").unwrap();
let normalized = match source {
"1.0" => "0x3f800000".to_owned(),
literal if literal_bits(literal).is_some() => {
format!("0x{:x}", literal_bits(literal).unwrap())
}
_ => source.parse::<i32>().map_or_else(
|_| source.to_owned(),
|value| format!("0x{:x}", value as u32),
),
};
format!("{mnemonic} {destination}, {normalized}")
}
"s_mov_b32" | "s_cmp_eq_u32" => {
let (left, right) = operands.split_once(", ").unwrap();
let scalar = |operand: &str| match literal_bits(operand) {
Some(bits) => match bits as i32 {
inline @ -16..=64 => inline.to_string(),
_ => format!("0x{bits:x}"),
},
None => operand.to_owned(),
};
format!("{mnemonic} {}, {}", scalar(left), scalar(right))
}
_ => assembly.to_owned(),
}
}
#[test]
fn displays_decoded_instructions_and_decode_errors() {
let decoded = DecodedInstruction {
offset: 0x1a,
byte_len: 4,
instruction: Instruction::EndProgram,
};
assert_eq!(decoded.to_string(), "001a: s_endpgm");
for (error, expected) in [
(
DecodeError {
offset: 0x10,
kind: DecodeErrorKind::Truncated {
needed: 8,
available: 4,
},
},
"gfx1030 decode at byte 0x10: instruction requires 8 bytes, found 4",
),
(
DecodeError {
offset: 0,
kind: DecodeErrorKind::UnsupportedOpcode { word: 0xdead_beef },
},
"gfx1030 decode at byte 0x0: unsupported opcode in 0xdeadbeef",
),
(
DecodeError {
offset: 0,
kind: DecodeErrorKind::UnsupportedForm {
mnemonic: "s_mov_b32",
detail: "expected a normal SGPR or EXEC/VCC destination",
},
},
"gfx1030 decode at byte 0x0: unsupported s_mov_b32 form: expected a normal SGPR or EXEC/VCC destination",
),
(
DecodeError {
offset: 0,
kind: DecodeErrorKind::InvalidBranchTarget { target: 0x20 },
},
"gfx1030 decode at byte 0x0: branch target 0x20 is outside instruction boundaries",
),
] {
assert_eq!(error.to_string(), expected);
}
}
#[test]
fn decodes_inline_negative_and_register_sources() {
// s_mov_b32 s10, 5; s_mov_b32 s11, -3; v_mov_b32_e32 v2, 5;
// v_mov_b32_e32 v2, -3; v_mov_b32_e32 v2, v1.
let words = [
0xbe8a_0385u32,
0xbe8b_03c3,
0x7e04_0285,
0x7e04_02c3,
0x7e04_0301,
];
let bytes: Vec<_> = words.iter().flat_map(|word| word.to_le_bytes()).collect();
let decoded = decode(Architecture::Gfx1030, &bytes).unwrap();
assert_eq!(
decoded[0].instruction,
Instruction::ScalarMoveB32 {
dst: 10,
src: ScalarSource::Immediate(5)
}
);
assert_eq!(
decoded[1].instruction,
Instruction::ScalarMoveB32 {
dst: 11,
src: ScalarSource::Immediate(0xffff_fffd)
}
);
assert_eq!(
decoded[2].instruction,
Instruction::MoveB32 {
dst: 2,
src: VectorSource::Immediate(5)
}
);
assert_eq!(
decoded[3].instruction,
Instruction::MoveB32 {
dst: 2,
src: VectorSource::Immediate(0xffff_fffd)
}
);
assert_eq!(
decoded[4].instruction,
Instruction::MoveB32 {
dst: 2,
src: VectorSource::Register(1)
}
);
}
#[test]
fn accepts_scalar_destination_105_and_vgpr_zero_add_sources() {
// s_mov_b32 s105, 0 is the highest normal SGPR destination.
let valid = 0xbee9_0380u32.to_le_bytes();
assert_eq!(
decode(Architecture::Gfx1030, &valid).unwrap()[0].instruction,
Instruction::ScalarMoveB32 {
dst: 105,
src: ScalarSource::Immediate(0)
}
);
// s_mov_b32 ttmp0, 0 selects a privileged destination.
let invalid = 0xbeec_0380u32.to_le_bytes();
assert_eq!(
decode(Architecture::Gfx1030, &invalid).unwrap_err().kind,
DecodeErrorKind::UnsupportedForm {
mnemonic: "s_mov_b32",
detail: "expected a normal SGPR or EXEC/VCC destination",
}
);
// v_add_nc_u32_e64 v1, v0, v0 uses selector 256 (V0) for both sources.
let words = [0xd525_0001u32, 0x0202_0100];
let bytes: Vec<_> = words.iter().flat_map(|word| word.to_le_bytes()).collect();
assert_eq!(
decode(Architecture::Gfx1030, &bytes).unwrap()[0].instruction,
Instruction::AddNoCarryU32 {
dst: 1,
src0: 0,
src1: 0
}
);
}
-86
View File
@@ -1,86 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_decoder::{
Architecture, DecodeError, DecodeErrorKind, DecodedInstruction, ExportTarget, Instruction,
InterpolationPhase, decode,
};
#[test]
fn decodes_export_registers_and_interpolation_fields_in_byte_order() {
// Derived with llvm-mc -triple=amdgcn -mcpu=gfx1030 -show-encoding:
// exp param0, v255, v128, v15, v1
// v_interp_p1_f32 v255, v254, attr31.z
// v_interp_p2_f32 v128, v255, attr1.w
let bytes = [
0x0f, 0x02, 0x00, 0xf8, 0xff, 0x80, 0x0f, 0x01, 0xfe, 0x7e, 0xfc, 0xcb, 0xff, 0x07, 0x01,
0xca,
];
assert_eq!(
decode(Architecture::Gfx1030, &bytes).unwrap(),
[
DecodedInstruction {
offset: 0,
byte_len: 8,
instruction: Instruction::Export {
target: ExportTarget::Parameter0,
sources: [255, 128, 15, 1],
},
},
DecodedInstruction {
offset: 8,
byte_len: 4,
instruction: Instruction::Interpolate {
phase: InterpolationPhase::First,
dst: 255,
coordinate: 254,
attribute: 31,
component: 2,
},
},
DecodedInstruction {
offset: 12,
byte_len: 4,
instruction: Instruction::Interpolate {
phase: InterpolationPhase::Second,
dst: 128,
coordinate: 255,
attribute: 1,
component: 3,
},
},
],
);
}
#[test]
fn rejects_truncated_export_and_each_invalid_operand_field() {
let valid = 0xf800_180fu32;
let bytes = valid.to_le_bytes();
assert_eq!(
decode(Architecture::Gfx1030, &bytes).unwrap_err(),
DecodeError {
offset: 0,
kind: DecodeErrorKind::Truncated {
needed: 8,
available: 4
},
},
);
for bit in 0..26 {
let mut bytes = [0; 8];
bytes[..4].copy_from_slice(&(valid ^ (1 << bit)).to_le_bytes());
assert!(
matches!(
decode(Architecture::Gfx1030, &bytes),
Err(DecodeError {
offset: 0,
kind: DecodeErrorKind::UnsupportedForm {
mnemonic: "exp",
..
},
}),
),
"export bit {bit}"
);
}
}
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2026 Advanced Micro Devices, Inc., or its affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-118
View File
@@ -1,118 +0,0 @@
#!/usr/bin/env python3
"""Generate first-word opcode matches from the pinned, public AMD RDNA 2 XML."""
import hashlib
import sys
from pathlib import Path
from xml.etree import ElementTree
SOURCE_SHA256 = "d671ecbc36543674ab59e9b2feffd56718fd2137e7ad913c314f2e2508b9f4f7"
VARIANTS = (
("BUFFER_LOAD_DWORD", "ENC_MUBUF"),
("BUFFER_STORE_DWORD", "ENC_MUBUF"),
("S_WAITCNT", "ENC_SOPP"),
("S_WAITCNT_VSCNT", "ENC_SOPK"),
("V_MOV_B32", "ENC_VOP1"),
("V_ADD_NC_U32", "ENC_VOP3"),
("S_ENDPGM", "ENC_SOPP"),
("S_MOV_B32", "ENC_SOP1"),
("S_CMP_EQ_U32", "ENC_SOPC"),
("S_CBRANCH_SCC0", "ENC_SOPP"),
("S_CBRANCH_EXECZ", "ENC_SOPP"),
("S_CBRANCH_VCCZ", "ENC_SOPP"),
("S_BRANCH", "ENC_SOPP"),
("V_LSHLREV_B32", "ENC_VOP2"),
("V_LSHRREV_B32", "ENC_VOP2"),
("V_ASHRREV_I32", "ENC_VOP2"),
("V_AND_B32", "ENC_VOP2"),
("V_OR_B32", "ENC_VOP2"),
("V_XOR_B32", "ENC_VOP2"),
("V_ADD_F32", "ENC_VOP2"),
("V_MUL_F32", "ENC_VOP2"),
("EXP", "ENC_EXP"),
("V_INTERP_P1_F32", "ENC_VINTRP"),
("V_INTERP_P2_F32", "ENC_VINTRP"),
)
def read_field(encoding, name):
fields = encoding.findall("MicrocodeFormat/BitMap/Field")
field = next(field for field in fields if field.findtext("FieldName") == name)
ranges = field.findall("BitLayout/Range")
return sorted(
(int(item.findtext("BitOffset")), int(item.findtext("BitCount")))
for item in ranges
)
def bits_to_word(value, ranges):
word = 0
mask = 0
for offset, size in ranges:
low_mask = (1 << size) - 1
word |= (value & low_mask) << offset
mask |= low_mask << offset
value >>= size
if value or mask >= (1 << 32):
raise ValueError("encoding field does not fit in the first word")
return mask, word
def main(xml_path):
data = Path(xml_path).read_bytes()
if hashlib.sha256(data).hexdigest() != SOURCE_SHA256:
raise ValueError("RDNA 2 XML does not match the approved input SHA-256")
root = ElementTree.fromstring(data)
isa = root.find("ISA")
encodings = {entry.findtext("EncodingName"): entry for entry in isa.findall("Encodings/Encoding")}
instructions = {
entry.findtext("InstructionName"): entry for entry in isa.findall("Instructions/Instruction")
}
print("// Generated by crates/isa/generate_rdna2.py. See docs/research/rdna2.md.")
print("// Source: AMD RDNA 2 XML, 2026-02-20, schema 1.1.1.")
print("// Copyright (c) 2026 Advanced Micro Devices, Inc., or its affiliates.")
print("// SPDX-License-Identifier: MIT")
print()
print("use super::Opcode;")
print()
for instruction_name, encoding_name in VARIANTS:
encoding = encodings[encoding_name]
variant = next(
variant
for variant in instructions[instruction_name].findall("InstructionEncodings/InstructionEncoding")
if variant.findtext("EncodingName") == encoding_name
and variant.findtext("EncodingCondition") == "default"
)
opcode = int(variant.findtext("Opcode"))
identifiers = [
int(ident.text, 2) for ident in encoding.findall("EncodingIdentifiers/EncodingIdentifier")
]
prefix_mask, _ = bits_to_word(0, read_field(encoding, "ENCODING"))
prefixes = {identifier & prefix_mask for identifier in identifiers}
if len(prefixes) != 1:
raise ValueError(f"{encoding_name} has an ambiguous encoding prefix")
# EXP identifies the export instruction through the encoding prefix alone.
if encoding_name == "ENC_EXP" and opcode == 0:
opcode_mask, opcode_bits = 0, 0
else:
opcode_mask, opcode_bits = bits_to_word(opcode, read_field(encoding, "OP"))
mask = prefix_mask | opcode_mask
bits = prefixes.pop() | opcode_bits
if bits not in {identifier & mask for identifier in identifiers}:
raise ValueError(f"{instruction_name} is absent from {encoding_name} identifiers")
size = int(encoding.findtext("BitCount")) // 8
print(
f"pub const {instruction_name}: Opcode = Opcode {{\n"
f" mask: 0x{mask:08x},\n"
f" bits: 0x{bits:08x},\n"
f" bytes: {size},\n"
"};"
)
if __name__ == "__main__":
if len(sys.argv) != 2:
raise SystemExit("usage: generate_rdna2.py amdgpu_isa_rdna2.xml")
main(sys.argv[1])
-281
View File
@@ -1,281 +0,0 @@
//! Typed operands and instruction forms for the bounded gfx1030 compute and graphics subsets.
use std::fmt;
mod rdna2;
pub use rdna2::{
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0,
S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32,
V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32,
V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
};
/// Selects the instruction encoding independently of the container and execution ABI.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Architecture {
/// LLVM's gfx1030 target for AMD RDNA 2.
Gfx1030,
}
/// A generated first-word opcode pattern and its base length, before literal extensions.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Opcode {
mask: u32,
bits: u32,
bytes: u8,
}
impl Opcode {
/// Checks the format and opcode bits. The decoder must still validate operands.
pub fn matches(self, word: u32) -> bool {
word & self.mask == self.bits
}
/// Returns the base instruction size in bytes.
pub fn byte_len(self) -> u8 {
self.bytes
}
}
/// A 32-bit source for an unmodified vector move.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VectorSource {
/// VGPR index.
Register(u8),
/// Inline integer or literal word, represented by its bits.
Immediate(u32),
}
impl fmt::Display for VectorSource {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Register(register) => write!(formatter, "v{register}"),
Self::Immediate(value) => write!(formatter, "0x{value:x}"),
}
}
}
/// A scalar 32-bit source.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ScalarSource {
/// A normal SGPR index.
Register(u8),
/// Inline integer or literal word, represented by its bits.
Immediate(u32),
}
impl fmt::Display for ScalarSource {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::Register(register) => write!(formatter, "s{register}"),
Self::Immediate(value) => match value as i32 {
integer @ -16..=64 => write!(formatter, "{integer}"),
_ => write!(formatter, "0x{value:x}"),
},
}
}
}
/// Output targeted by a supported uncompressed four-component export.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ExportTarget {
/// Vertex clip position.
Position0,
/// Vertex parameter slot zero.
Parameter0,
/// Pixel color attachment zero.
RenderTarget0,
}
/// Phase of a pixel parameter interpolation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum InterpolationPhase {
/// Initialize the destination with the base and I-coordinate terms.
First,
/// Add the J-coordinate term to the destination.
Second,
}
/// Instruction forms accepted by the gfx1030 decoder.
///
/// Vector operations use VGPR indices and scalar operations use SGPR indices.
/// The buffer `resource` is the first SGPR of its four-word descriptor.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[allow(missing_docs)]
pub enum Instruction {
/// Indexed 32-bit buffer read into a VGPR.
BufferLoadDword { data: u8, index: u8, resource: u8 },
/// Indexed 32-bit buffer write from a VGPR.
BufferStoreDword { data: u8, index: u8, resource: u8 },
/// `s_waitcnt vmcnt(0)`.
WaitLoad,
/// `s_waitcnt_vscnt null, 0`.
WaitStore,
/// VOP1 unmodified 32-bit vector move.
MoveB32 { dst: u8, src: VectorSource },
/// VOP3 unsigned 32-bit addition with no carry or input/output modifiers.
AddNoCarryU32 { dst: u8, src0: u8, src1: u8 },
/// SOP1 32-bit move to a normal SGPR or an EXEC/VCC half.
ScalarMoveB32 { dst: u8, src: ScalarSource },
/// SOPC 32-bit equality comparison writing SCC.
ScalarCompareEqU32 {
src0: ScalarSource,
src1: ScalarSource,
},
/// SOPP jump to a stream byte offset when SCC is clear.
BranchSccZero { target: usize },
/// SOPP jump when the Wave32 execution mask is empty.
BranchExecZero { target: usize },
/// SOPP jump when the Wave32 vector condition mask is empty.
BranchVccZero { target: usize },
/// SOPP unconditional jump to a stream byte offset.
Branch { target: usize },
/// VOP2 logical left shift with the count in src0.
VectorLshlrevB32 { dst: u8, src0: u8, src1: u8 },
/// VOP2 logical right shift with the count in src0.
VectorLshrrevB32 { dst: u8, src0: u8, src1: u8 },
/// VOP2 arithmetic right shift with the count in src0.
VectorAshrrevI32 { dst: u8, src0: u8, src1: u8 },
/// VOP2 bitwise AND.
VectorAndB32 { dst: u8, src0: u8, src1: u8 },
/// VOP2 bitwise OR.
VectorOrB32 { dst: u8, src0: u8, src1: u8 },
/// VOP2 bitwise XOR.
VectorXorB32 { dst: u8, src0: u8, src1: u8 },
/// VOP2 single-precision addition. Execution requires an explicit FP mode.
VectorAddF32 { dst: u8, src0: u8, src1: u8 },
/// VOP2 single-precision multiplication. Execution requires an explicit FP mode.
VectorMulF32 { dst: u8, src0: u8, src1: u8 },
/// Full, uncompressed four-component graphics export.
Export {
target: ExportTarget,
sources: [u8; 4],
},
/// Parameter interpolation with a source barycentric coordinate and an attribute component.
Interpolate {
phase: InterpolationPhase,
dst: u8,
coordinate: u8,
attribute: u8,
component: u8,
},
/// Terminates the wave and waits for outstanding memory operations.
EndProgram,
}
impl Instruction {
/// Returns the mnemonic for the exact encoding family represented.
pub fn mnemonic(self) -> &'static str {
match self {
Self::BufferLoadDword { .. } => "buffer_load_dword",
Self::BufferStoreDword { .. } => "buffer_store_dword",
Self::WaitLoad => "s_waitcnt",
Self::WaitStore => "s_waitcnt_vscnt",
Self::MoveB32 { .. } => "v_mov_b32_e32",
Self::AddNoCarryU32 { .. } => "v_add_nc_u32_e64",
Self::ScalarMoveB32 { .. } => "s_mov_b32",
Self::ScalarCompareEqU32 { .. } => "s_cmp_eq_u32",
Self::BranchSccZero { .. } => "s_cbranch_scc0",
Self::BranchExecZero { .. } => "s_cbranch_execz",
Self::BranchVccZero { .. } => "s_cbranch_vccz",
Self::Branch { .. } => "s_branch",
Self::VectorLshlrevB32 { .. } => "v_lshlrev_b32_e32",
Self::VectorLshrrevB32 { .. } => "v_lshrrev_b32_e32",
Self::VectorAshrrevI32 { .. } => "v_ashrrev_i32_e32",
Self::VectorAndB32 { .. } => "v_and_b32_e32",
Self::VectorOrB32 { .. } => "v_or_b32_e32",
Self::VectorXorB32 { .. } => "v_xor_b32_e32",
Self::VectorAddF32 { .. } => "v_add_f32_e32",
Self::VectorMulF32 { .. } => "v_mul_f32_e32",
Self::Export { .. } => "exp",
Self::Interpolate {
phase: InterpolationPhase::First,
..
} => "v_interp_p1_f32_e32",
Self::Interpolate {
phase: InterpolationPhase::Second,
..
} => "v_interp_p2_f32_e32",
Self::EndProgram => "s_endpgm",
}
}
}
impl fmt::Display for Instruction {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.mnemonic())?;
match *self {
Self::BufferLoadDword {
data,
index,
resource,
}
| Self::BufferStoreDword {
data,
index,
resource,
} => {
let last = u16::from(resource) + 3;
write!(
formatter,
" v{data}, v{index}, s[{resource}:{last}], 0 idxen"
)
}
Self::WaitLoad => formatter.write_str(" vmcnt(0)"),
Self::WaitStore => formatter.write_str(" null, 0"),
Self::MoveB32 { dst, src } => write!(formatter, " v{dst}, {src}"),
Self::AddNoCarryU32 { dst, src0, src1 }
| Self::VectorLshlrevB32 { dst, src0, src1 }
| Self::VectorLshrrevB32 { dst, src0, src1 }
| Self::VectorAshrrevI32 { dst, src0, src1 }
| Self::VectorAndB32 { dst, src0, src1 }
| Self::VectorOrB32 { dst, src0, src1 }
| Self::VectorXorB32 { dst, src0, src1 }
| Self::VectorAddF32 { dst, src0, src1 }
| Self::VectorMulF32 { dst, src0, src1 } => {
write!(formatter, " v{dst}, v{src0}, v{src1}")
}
Self::ScalarMoveB32 { dst, src } => match dst {
106 => write!(formatter, " vcc_lo, {src}"),
107 => write!(formatter, " vcc_hi, {src}"),
126 => write!(formatter, " exec_lo, {src}"),
127 => write!(formatter, " exec_hi, {src}"),
_ => write!(formatter, " s{dst}, {src}"),
},
Self::ScalarCompareEqU32 { src0, src1 } => write!(formatter, " {src0}, {src1}"),
Self::Branch { target }
| Self::BranchSccZero { target }
| Self::BranchExecZero { target }
| Self::BranchVccZero { target } => {
write!(formatter, " -> 0x{target:04x}")
}
Self::Export {
target,
sources: [a, b, c, d],
} => {
let (name, flags) = match target {
ExportTarget::Position0 => ("pos0", " done"),
ExportTarget::Parameter0 => ("param0", ""),
ExportTarget::RenderTarget0 => ("mrt0", " done vm"),
};
write!(formatter, " {name}, v{a}, v{b}, v{c}, v{d}{flags}")
}
Self::Interpolate {
dst,
coordinate,
attribute,
component,
..
} => {
let channel = ["x", "y", "z", "w"]
.get(usize::from(component))
.ok_or(fmt::Error)?;
write!(
formatter,
" v{dst}, v{coordinate}, attr{attribute}.{channel}"
)
}
Self::EndProgram => Ok(()),
}
}
}
-127
View File
@@ -1,127 +0,0 @@
// Generated by crates/isa/generate_rdna2.py. See docs/research/rdna2.md.
// Source: AMD RDNA 2 XML, 2026-02-20, schema 1.1.1.
// Copyright (c) 2026 Advanced Micro Devices, Inc., or its affiliates.
// SPDX-License-Identifier: MIT
use super::Opcode;
pub const BUFFER_LOAD_DWORD: Opcode = Opcode {
mask: 0xfffc0000,
bits: 0xe0300000,
bytes: 8,
};
pub const BUFFER_STORE_DWORD: Opcode = Opcode {
mask: 0xfffc0000,
bits: 0xe0700000,
bytes: 8,
};
pub const S_WAITCNT: Opcode = Opcode {
mask: 0xffff0000,
bits: 0xbf8c0000,
bytes: 4,
};
pub const S_WAITCNT_VSCNT: Opcode = Opcode {
mask: 0xff800000,
bits: 0xbb800000,
bytes: 4,
};
pub const V_MOV_B32: Opcode = Opcode {
mask: 0xfe01fe00,
bits: 0x7e000200,
bytes: 4,
};
pub const V_ADD_NC_U32: Opcode = Opcode {
mask: 0xffff0000,
bits: 0xd5250000,
bytes: 8,
};
pub const S_ENDPGM: Opcode = Opcode {
mask: 0xffff0000,
bits: 0xbf810000,
bytes: 4,
};
pub const S_MOV_B32: Opcode = Opcode {
mask: 0xff80ff00,
bits: 0xbe800300,
bytes: 4,
};
pub const S_CMP_EQ_U32: Opcode = Opcode {
mask: 0xffff0000,
bits: 0xbf060000,
bytes: 4,
};
pub const S_CBRANCH_SCC0: Opcode = Opcode {
mask: 0xffff0000,
bits: 0xbf840000,
bytes: 4,
};
pub const S_CBRANCH_EXECZ: Opcode = Opcode {
mask: 0xffff0000,
bits: 0xbf880000,
bytes: 4,
};
pub const S_CBRANCH_VCCZ: Opcode = Opcode {
mask: 0xffff0000,
bits: 0xbf860000,
bytes: 4,
};
pub const S_BRANCH: Opcode = Opcode {
mask: 0xffff0000,
bits: 0xbf820000,
bytes: 4,
};
pub const V_LSHLREV_B32: Opcode = Opcode {
mask: 0xfe000000,
bits: 0x34000000,
bytes: 4,
};
pub const V_LSHRREV_B32: Opcode = Opcode {
mask: 0xfe000000,
bits: 0x2c000000,
bytes: 4,
};
pub const V_ASHRREV_I32: Opcode = Opcode {
mask: 0xfe000000,
bits: 0x30000000,
bytes: 4,
};
pub const V_AND_B32: Opcode = Opcode {
mask: 0xfe000000,
bits: 0x36000000,
bytes: 4,
};
pub const V_OR_B32: Opcode = Opcode {
mask: 0xfe000000,
bits: 0x38000000,
bytes: 4,
};
pub const V_XOR_B32: Opcode = Opcode {
mask: 0xfe000000,
bits: 0x3a000000,
bytes: 4,
};
pub const V_ADD_F32: Opcode = Opcode {
mask: 0xfe000000,
bits: 0x06000000,
bytes: 4,
};
pub const V_MUL_F32: Opcode = Opcode {
mask: 0xfe000000,
bits: 0x10000000,
bytes: 4,
};
pub const EXP: Opcode = Opcode {
mask: 0xfc000000,
bits: 0xf8000000,
bytes: 8,
};
pub const V_INTERP_P1_F32: Opcode = Opcode {
mask: 0xfc030000,
bits: 0xc8000000,
bytes: 4,
};
pub const V_INTERP_P2_F32: Opcode = Opcode {
mask: 0xfc030000,
bits: 0xc8010000,
bytes: 4,
};
-52
View File
@@ -1,52 +0,0 @@
[package]
name = "xenora-metal"
description = "Bounded native Metal execution for Xenora graphics fixtures"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[features]
gpu-tests = []
[[test]]
name = "native_compute"
path = "tests/native_compute.rs"
required-features = ["gpu-tests"]
[[test]]
name = "sampler_texture"
path = "tests/sampler_texture.rs"
[dev-dependencies]
xenora-shader = { path = "../shader" }
[target.'cfg(all(target_arch = "aarch64", target_os = "macos"))'.dependencies]
xenora-texture = { path = "../texture" }
objc2 = "=0.6.5"
objc2-foundation = { version = "=0.3.2", default-features = false, features = ["std", "NSError", "NSString"] }
objc2-metal = { version = "=0.3.2", default-features = false, features = [
"std",
"MTLAllocation",
"MTLBuffer",
"MTLCommandBuffer",
"MTLCommandEncoder",
"MTLCommandQueue",
"MTLComputeCommandEncoder",
"MTLComputePipeline",
"MTLDevice",
"MTLLibrary",
"MTLPixelFormat",
"MTLPipeline",
"MTLRenderCommandEncoder",
"MTLRenderPass",
"MTLRenderPipeline",
"MTLResource",
"MTLSampler",
"MTLTexture",
"MTLTypes",
"objc2-core-foundation",
] }
-670
View File
@@ -1,670 +0,0 @@
use std::ffi::c_void;
use std::fmt;
use std::mem::size_of_val;
use std::ptr::{NonNull, copy_nonoverlapping};
use std::time::Instant;
use objc2::rc::{Retained, autoreleasepool};
use objc2::runtime::{NSObjectProtocol, ProtocolObject};
use objc2::sel;
use objc2_foundation::NSString;
use objc2_metal::{
MTLBuffer, MTLCommandBuffer, MTLCommandBufferStatus, MTLCommandEncoder, MTLCommandQueue,
MTLCompileOptions, MTLComputeCommandEncoder, MTLComputePipelineState,
MTLCreateSystemDefaultDevice, MTLDevice, MTLFunction, MTLGPUFamily, MTLLibrary,
MTLMathFloatingPointFunctions, MTLMathMode, MTLOrigin, MTLPixelFormat, MTLRegion,
MTLResourceOptions, MTLShaderValidation, MTLSize, MTLStorageMode, MTLTexture,
MTLTextureDescriptor, MTLTextureUsage,
};
use xenora_texture::{Bc1Upload, TiledBc1};
#[path = "render.rs"]
mod render;
const MAX_THREADS_PER_GROUP: usize = 64;
const MAX_GROUPS: usize = 64;
const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP;
const MAX_SOURCE_BYTES: usize = 64 * 1024;
const BC1_READBACK: &str = r"
#include <metal_stdlib>
using namespace metal;
kernel void read_bc1(texture2d<float, access::read> image [[texture(0)]],
device uint *output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
uint width = image.get_width();
uint4 channels = uint4(round(image.read(uint2(index % width, index / width)) * 255.0f));
output[index] = channels.r | (channels.g << 8u) | (channels.b << 16u) | (channels.a << 24u);
}
";
enum ComputeInput<'a> {
Words(&'a [u32]),
Texture(&'a ProtocolObject<dyn MTLTexture>, usize),
SampledTexture {
texture: &'a ProtocolObject<dyn MTLTexture>,
sampler: &'a ProtocolObject<dyn objc2_metal::MTLSamplerState>,
coords: &'a [u32],
},
}
impl ComputeInput<'_> {
fn len(&self) -> usize {
match self {
Self::Words(words) => words.len(),
Self::Texture(_, pixels) => *pixels,
Self::SampledTexture { coords, .. } => coords.len() / 2,
}
}
}
/// Host-provided backing bytes for one synthetic guest resource.
pub struct GuestBuffer<'a> {
pub format: u32,
pub bytes: &'a [u8],
}
impl GuestBuffer<'_> {
/// The synthetic ABI's format identifier for little-endian 32-bit words.
pub const U32_LE: u32 = 1;
}
/// The synthetic guest's selection of an input range from a resource table.
#[derive(Debug, Clone, Copy)]
pub struct GuestBufferView {
/// Zero-based index in the supplied resource table.
pub handle: usize,
/// Input slot in the fixture ABI. Only slot zero accepts guest data.
pub binding: u32,
pub byte_offset: usize,
pub byte_len: usize,
}
/// Failure at a named operation in the native Metal backend.
#[derive(Debug)]
pub struct MetalError {
pub operation: &'static str,
pub detail: String,
}
impl MetalError {
pub(crate) fn new(operation: &'static str, detail: impl Into<String>) -> Self {
Self {
operation,
detail: detail.into(),
}
}
}
impl fmt::Display for MetalError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{}: {}", self.operation, self.detail)
}
}
impl std::error::Error for MetalError {}
/// One compiled-and-dispatched kernel with its measured stage timings.
///
/// Durations come from monotonic host clocks for the compiler stages and from
/// the command buffer's GPU start and end timestamps for `gpu_seconds`. They
/// measure a single submission and are not a benchmark distribution.
#[derive(Debug, Clone)]
pub struct RunProfile {
pub library_seconds: f64,
pub pipeline_seconds: f64,
pub gpu_seconds: f64,
pub host_seconds: f64,
pub output: Vec<u32>,
}
/// A native Metal device and its command queue for the fixture ABI.
pub struct NativeCompute {
device: Retained<ProtocolObject<dyn MTLDevice>>,
queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,
}
impl NativeCompute {
/// Open the default Apple GPU and create a retained-resource command queue.
///
/// # Errors
///
/// Returns an error if discovery, the capability check, or queue creation fails.
pub fn new() -> Result<Self, MetalError> {
autoreleasepool(|_| {
let device = MTLCreateSystemDefaultDevice().ok_or_else(|| {
MetalError::new("MTLCreateSystemDefaultDevice", "no Metal device")
})?;
// Apple family 7 documents nonuniform threadgroups, which this ABI needs.
if !device.supportsFamily(MTLGPUFamily::Apple7) {
return Err(MetalError::new(
"supportsFamily",
"Apple family 7 capabilities are required",
));
}
let queue = device
.newCommandQueue()
.ok_or_else(|| MetalError::new("newCommandQueue", "queue creation failed"))?;
Ok(Self { device, queue })
})
}
/// Report the selected device's registered name.
pub fn device_name(&self) -> String {
autoreleasepool(|_| self.device.name().to_string())
}
/// Access the underlying native Metal device protocol object.
#[inline]
pub fn device(&self) -> &ProtocolObject<dyn MTLDevice> {
&self.device
}
/// Access the underlying native Metal command queue protocol object.
#[inline]
pub fn queue(&self) -> &ProtocolObject<dyn MTLCommandQueue> {
&self.queue
}
/// Read an original synthetic BC1 subresource with a native Metal texture.
///
/// The fixed compute kernel returns row-major RGBA8 texels. Each returned
/// word stores red in the least significant byte and alpha in the highest.
///
/// # Errors
///
/// Returns an error if the subresource is invalid, exceeds the 4096-texel
/// limit, BC texture compression is unavailable, or Metal execution fails.
pub fn read_tiled_bc1(
&self,
tiled: &TiledBc1<'_>,
layer: usize,
mip: u32,
) -> Result<Vec<u32>, MetalError> {
let (width, height) = tiled
.mip_extent(mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
let pixels = self.validate_bc1_extent(width, height)?;
let blocks = tiled
.linearize(layer, mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
self.read_bc1_blocks(&blocks, width.div_ceil(4) * 8, width, height, pixels)
}
/// Sample a native Metal RGBA8 texture using a native Metal sampler on Apple Silicon GPU.
///
/// Accepts normalized float UV coordinates.
/// Executes an authored compute fixture sampling the texture at `[[texture(0)]]` using
/// the sampler at `[[sampler(0)]]`, reading coordinates from `[[buffer(0)]]`, and writing
/// row-major RGBA8 texels to `[[buffer(1)]]`.
///
/// # Errors
///
/// Returns an error if the number of sample points exceeds maximum allowable limits,
/// or if Metal compilation, dispatch or completion fails.
pub fn sample_rgba8(
&self,
texture: &crate::texture_pipeline::MetalRgba8Texture,
sampler: &crate::sampler::MetalSampler,
uv_coords: &[[f32; 2]],
) -> Result<Vec<u32>, MetalError> {
const SAMPLER_KERNEL: &str = r#"
#include <metal_stdlib>
using namespace metal;
kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
sampler s [[sampler(0)]],
device const float2 *coords [[buffer(0)]],
device uint *output [[buffer(1)]],
uint id [[thread_position_in_grid]]) {
float4 color = tex.sample(s, coords[id], level(0.0f));
uint4 channels = uint4(round(color * 255.0f));
output[id] = channels.r | (channels.g << 8u) | (channels.b << 16u) | (channels.a << 24u);
}
"#;
if uv_coords.is_empty() || uv_coords.len() > MAX_GRID_WORDS {
return Err(MetalError::new(
"sample bounds",
format!(
"expected 1..={MAX_GRID_WORDS} sample points, got {}",
uv_coords.len()
),
));
}
let words: Vec<u32> = uv_coords
.iter()
.flat_map(|[u, v]| [u.to_bits(), v.to_bits()])
.collect();
validate_source(SAMPLER_KERNEL, &["sample_rgba8"])?;
autoreleasepool(|_| {
self.run(
SAMPLER_KERNEL,
"sample_rgba8",
ComputeInput::SampledTexture {
texture: texture.raw(),
sampler: sampler.raw(),
coords: &words,
},
)
.map(|profile| profile.output)
})
}
/// Read a selected subresource from a validated pitched BC1 upload.
///
/// Output matches [`Self::read_tiled_bc1`]. Metal receives the upload's
/// block-row stride and reads only the selected level's logical blocks.
///
/// # Errors
///
/// Returns an error for an invalid layer or mip, out-of-policy size,
/// unavailable BC compression, or Metal setup or execution failure.
pub fn read_bc1_upload(
&self,
upload: &Bc1Upload<'_>,
layer: usize,
mip: u32,
) -> Result<Vec<u32>, MetalError> {
let level = upload
.subresource(layer, mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
let pixels = self.validate_bc1_extent(level.width, level.height)?;
self.read_bc1_blocks(
level.bytes,
level.row_pitch,
level.width,
level.height,
pixels,
)
}
fn validate_bc1_extent(&self, width: usize, height: usize) -> Result<usize, MetalError> {
let pixels = width
.checked_mul(height)
.filter(|pixels| (1..=MAX_GRID_WORDS).contains(pixels))
.ok_or_else(|| MetalError::new("texture bounds", "expected 1..=4096 texels"))?;
if !self.device.supportsBCTextureCompression() {
return Err(MetalError::new(
"supportsBCTextureCompression",
"BC1 is unavailable",
));
}
Ok(pixels)
}
fn read_bc1_blocks(
&self,
blocks: &[u8],
row_pitch: usize,
width: usize,
height: usize,
pixels: usize,
) -> Result<Vec<u32>, MetalError> {
autoreleasepool(|_| {
// SAFETY: The positive bounded dimensions and supported BC1 format
// describe a 2D texture with just its base level.
let descriptor = unsafe {
MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped(
MTLPixelFormat::BC1_RGBA,
width,
height,
false,
)
};
descriptor.setStorageMode(MTLStorageMode::Shared);
descriptor.setUsage(MTLTextureUsage::ShaderRead);
let texture = self
.device
.newTextureWithDescriptor(&descriptor)
.ok_or_else(|| {
MetalError::new("newTextureWithDescriptor", "BC1 allocation failed")
})?;
let region = MTLRegion {
origin: MTLOrigin { x: 0, y: 0, z: 0 },
size: MTLSize {
width,
height,
depth: 1,
},
};
// Apple documents a zero stride for a single compressed block row.
let bytes_per_row = if height <= 4 { 0 } else { row_pitch };
// SAFETY: The region spans the whole level, including any partial
// edge block. Both callers validate that the input holds all rows
// of complete BC1 blocks at the supplied, block-aligned stride.
unsafe {
texture.replaceRegion_mipmapLevel_withBytes_bytesPerRow(
region,
0,
NonNull::from(blocks).cast(),
bytes_per_row,
);
}
self.run(
BC1_READBACK,
"read_bc1",
ComputeInput::Texture(&texture, pixels),
)
.map(|profile| profile.output)
})
}
/// Run trusted MSL with read-only words at buffer 0 and output words at buffer 1.
///
/// The kernel must use one invocation per word and restrict its memory accesses
/// to these bindings and ranges. Run this inside a child process with a wall
/// deadline. The backend caps resources and dispatch size but does not verify
/// the MSL, its control flow, or its termination.
///
/// # Errors
///
/// Returns an error for out-of-policy input sizes, compilation, resource setup,
/// dispatch or completion failure.
pub fn run_words(
&self,
source: &str,
entry: &str,
input: &[u32],
) -> Result<Vec<u32>, MetalError> {
self.run_words_profiled(source, entry, input)
.map(|profile| profile.output)
}
/// Resolve a synthetic guest input view and run the trusted fixture kernel.
///
/// The validated word range is copied into its own Metal buffer at slot zero.
/// Slot one receives a separate output buffer with the same number of words.
/// The trusted-kernel requirements of [`Self::run_words`] also apply here.
///
/// # Errors
///
/// Returns an error for unsupported bindings or formats, invalid handles or
/// ranges, or any error from [`Self::run_words`].
pub fn run_guest_words(
&self,
source: &str,
entry: &str,
resources: &[GuestBuffer<'_>],
view: GuestBufferView,
) -> Result<Vec<u32>, MetalError> {
if view.binding != 0 {
return Err(MetalError::new(
"guest buffer binding",
"expected input slot 0",
));
}
let buffer = resources
.get(view.handle)
.ok_or_else(|| MetalError::new("guest buffer handle", "handle is not in the table"))?;
if buffer.format != GuestBuffer::U32_LE {
return Err(MetalError::new("guest buffer format", "expected U32_LE"));
}
let word_size = size_of::<u32>();
if !view.byte_offset.is_multiple_of(word_size)
|| !view.byte_len.is_multiple_of(word_size)
|| !(1..=MAX_GRID_WORDS).contains(&(view.byte_len / word_size))
{
return Err(MetalError::new(
"guest buffer bounds",
format!("expected an aligned range of 1..={MAX_GRID_WORDS} words"),
));
}
let bytes = view
.byte_offset
.checked_add(view.byte_len)
.and_then(|end| buffer.bytes.get(view.byte_offset..end))
.ok_or_else(|| MetalError::new("guest buffer bounds", "range exceeds the resource"))?;
let words: Vec<_> = bytes
.as_chunks::<{ size_of::<u32>() }>()
.0
.iter()
.copied()
.map(u32::from_le_bytes)
.collect();
self.run_words(source, entry, &words)
}
/// Run trusted MSL and report the measured compilation and execution stages.
///
/// Applies the same bounds and completion checks as [`Self::run_words`].
///
/// # Errors
///
/// Returns an error for out-of-policy input sizes, compilation, resource setup,
/// dispatch or completion failure.
pub fn run_words_profiled(
&self,
source: &str,
entry: &str,
input: &[u32],
) -> Result<RunProfile, MetalError> {
if !(1..=MAX_GRID_WORDS).contains(&input.len()) {
return Err(MetalError::new(
"dispatch bounds",
format!("expected 1..={MAX_GRID_WORDS} words, got {}", input.len()),
));
}
validate_source(source, &[entry])?;
autoreleasepool(|_| self.run(source, entry, ComputeInput::Words(input)))
}
fn run(
&self,
source: &str,
entry: &str,
input: ComputeInput<'_>,
) -> Result<RunProfile, MetalError> {
let host_start = Instant::now();
let options = compile_options()?;
let library_start = Instant::now();
let library = self.compile_library(source, &options)?;
let library_seconds = library_start.elapsed().as_secs_f64();
let function = find_function(&library, entry)?;
let pipeline_start = Instant::now();
let pipeline = self
.device
.newComputePipelineStateWithFunction_error(&function)
.map_err(|error| {
MetalError::new(
"newComputePipelineStateWithFunction",
error.localizedDescription().to_string(),
)
})?;
let pipeline_seconds = pipeline_start.elapsed().as_secs_f64();
verify_shader_validation(&pipeline)?;
let width = MAX_THREADS_PER_GROUP
.min(input.len())
.min(self.device.maxThreadsPerThreadgroup().width)
.min(pipeline.maxTotalThreadsPerThreadgroup());
if width == 0 || input.len().div_ceil(width) > MAX_GROUPS {
return Err(MetalError::new(
"dispatch bounds",
"device or pipeline would require too many groups",
));
}
let byte_len = input.len() * size_of::<u32>();
if byte_len > self.device.maxBufferLength() {
return Err(MetalError::new(
"buffer bounds",
"fixture exceeds device buffer limit",
));
}
let input_buffer = match input {
ComputeInput::Words(words) => Some(self.new_buffer(words)?),
ComputeInput::SampledTexture { coords, .. } => Some(self.new_buffer(coords)?),
ComputeInput::Texture(..) => None,
};
let mut words = vec![0xA5A5_A5A5; input.len()];
let output_buffer = self.new_buffer(&words)?;
let command = self
.queue
.commandBuffer()
.ok_or_else(|| MetalError::new("commandBuffer", "command buffer creation failed"))?;
let encoder = command.computeCommandEncoder().ok_or_else(|| {
MetalError::new("computeCommandEncoder", "compute encoder creation failed")
})?;
encoder.setComputePipelineState(&pipeline);
// SAFETY: All resources are live, initialized, and were allocated by
// this device. The kernel uses one input at index zero and writes the
// separate output buffer at index one. Both buffer offsets are zero.
unsafe {
match input {
ComputeInput::Texture(texture, _) => {
encoder.setTexture_atIndex(Some(texture), 0);
}
ComputeInput::SampledTexture {
texture, sampler, ..
} => {
encoder.setTexture_atIndex(Some(texture), 0);
encoder.setSamplerState_atIndex(Some(sampler), 0);
}
ComputeInput::Words(..) => {}
}
if let Some(buffer) = input_buffer.as_deref() {
encoder.setBuffer_offset_atIndex(Some(buffer), 0, 0);
}
encoder.setBuffer_offset_atIndex(Some(&output_buffer), 0, 1);
}
encoder.dispatchThreads_threadsPerThreadgroup(size(input.len()), size(width));
encoder.endEncoding();
complete_command(&command)?;
let gpu_seconds = command.GPUEndTime() - command.GPUStartTime();
let host_seconds = host_start.elapsed().as_secs_f64();
// SAFETY: Metal copied the initialized words into distinct shared storage.
// The GPU finished before the CPU touches that storage. Both ranges are
// valid for byte_len bytes and don't overlap. A byte copy requires no
// additional alignment and all u32 bit patterns are valid.
unsafe {
copy_nonoverlapping(
output_buffer.contents().cast::<u8>().as_ptr(),
words.as_mut_ptr().cast::<u8>(),
byte_len,
);
}
Ok(RunProfile {
library_seconds,
pipeline_seconds,
gpu_seconds,
host_seconds,
output: words,
})
}
fn compile_library(
&self,
source: &str,
options: &MTLCompileOptions,
) -> Result<Retained<ProtocolObject<dyn MTLLibrary>>, MetalError> {
self.device
.newLibraryWithSource_options_error(&NSString::from_str(source), Some(options))
.map_err(|error| {
MetalError::new(
"newLibraryWithSource",
error.localizedDescription().to_string(),
)
})
}
fn new_buffer(
&self,
words: &[u32],
) -> Result<Retained<ProtocolObject<dyn MTLBuffer>>, MetalError> {
let bytes = NonNull::from(words).cast::<c_void>();
// SAFETY: Metal reads exactly size_of_val(words) bytes from the live,
// initialized slice and makes its own copy within this call.
unsafe {
self.device.newBufferWithBytes_length_options(
bytes,
size_of_val(words),
MTLResourceOptions::StorageModeShared,
)
}
.ok_or_else(|| MetalError::new("newBufferWithBytes", "shared buffer allocation failed"))
}
}
fn validate_source(source: &str, entries: &[&str]) -> Result<(), MetalError> {
if source.is_empty()
|| source.len() > MAX_SOURCE_BYTES
|| entries.iter().any(|entry| entry.is_empty())
{
return Err(MetalError::new(
"source bounds",
"expected nonempty entries and source of at most 64 KiB",
));
}
Ok(())
}
pub(crate) fn compile_options() -> Result<Retained<MTLCompileOptions>, MetalError> {
let options = MTLCompileOptions::new();
if !options.respondsToSelector(sel!(setMathMode:))
|| !options.respondsToSelector(sel!(setMathFloatingPointFunctions:))
{
return Err(MetalError::new(
"MTLCompileOptions",
"this Metal runtime lacks explicit safe and precise math options",
));
}
options.setMathMode(MTLMathMode::Safe);
options.setMathFloatingPointFunctions(MTLMathFloatingPointFunctions::Precise);
Ok(options)
}
fn find_function(
library: &ProtocolObject<dyn MTLLibrary>,
entry: &str,
) -> Result<Retained<ProtocolObject<dyn MTLFunction>>, MetalError> {
library
.newFunctionWithName(&NSString::from_str(entry))
.ok_or_else(|| MetalError::new("newFunctionWithName", format!("missing entry {entry}")))
}
fn complete_command(command: &ProtocolObject<dyn MTLCommandBuffer>) -> Result<(), MetalError> {
command.commit();
command.waitUntilCompleted();
if command.status() != MTLCommandBufferStatus::Completed {
let error = command.error().map_or_else(
|| format!("unexpected command status {:?}", command.status()),
|error| error.localizedDescription().to_string(),
);
return Err(MetalError::new("waitUntilCompleted", error));
}
Ok(())
}
fn verify_shader_validation(
pipeline: &ProtocolObject<dyn MTLComputePipelineState>,
) -> Result<(), MetalError> {
if std::env::var("MTL_SHADER_VALIDATION").as_deref() != Ok("1") {
return Ok(());
}
if !pipeline.respondsToSelector(sel!(shaderValidation)) {
return Err(MetalError::new(
"shaderValidation",
"the runtime lacks the pipeline state query",
));
}
// SAFETY: The selector exists and this newly created pipeline is private
// to the current thread. The non-atomic property is read before encoding.
if unsafe { pipeline.shaderValidation() } != MTLShaderValidation::Enabled {
return Err(MetalError::new(
"shaderValidation",
"shader validation requested but inactive for the pipeline",
));
}
Ok(())
}
fn size(width: usize) -> MTLSize {
MTLSize {
width,
height: 1,
depth: 1,
}
}
-25
View File
@@ -1,25 +0,0 @@
//! Bounded execution of trusted Metal compute kernels and render stages.
#[cfg(not(all(target_arch = "aarch64", target_os = "macos")))]
compile_error!("Xenora's Metal backend requires ARM64 macOS");
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
mod compute;
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
pub mod sampler;
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
pub mod texture_pipeline;
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
pub use compute::{GuestBuffer, GuestBufferView, MetalError, NativeCompute, RunProfile};
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
pub use sampler::MetalSampler;
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
pub use texture_pipeline::{
BindingSlot, BoundSampledTexture, MetalRgba8Texture, Rgba8MipLevel,
Rgba8TextureDesc as MetalRgba8TextureDesc,
};
-202
View File
@@ -1,202 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use std::ptr::NonNull;
use objc2::rc::autoreleasepool;
use objc2::runtime::{NSObjectProtocol, ProtocolObject};
use objc2::sel;
use objc2_metal::{
MTLClearColor, MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue, MTLDevice, MTLLoadAction,
MTLOrigin, MTLPixelFormat, MTLPrimitiveType, MTLRegion, MTLRenderCommandEncoder,
MTLRenderPassDescriptor, MTLRenderPipelineDescriptor, MTLRenderPipelineState,
MTLShaderValidation, MTLSize, MTLStorageMode, MTLStoreAction, MTLTexture, MTLTextureDescriptor,
MTLTextureUsage, MTLViewport,
};
use super::{
MetalError, NativeCompute, compile_options, complete_command, find_function, validate_source,
};
const MAX_PIXELS: usize = 4096;
const PIXEL_FORMAT: MTLPixelFormat = MTLPixelFormat::RGBA8Unorm;
impl NativeCompute {
/// Draw one triangle with trusted MSL into a cleared RGBA8Unorm target.
///
/// The entries are ordered vertex, then fragment. Vertex slot zero holds
/// three clip-space float4 positions. Vertex slot one holds three float4
/// RGBA colors. The stages must restrict accesses to these inputs and
/// the single color output. Use only trusted MSL in a process with a wall
/// deadline. The returned bytes are tightly packed in top-to-bottom rows.
///
/// # Errors
///
/// Returns an error for non-finite inputs, invalid source or extent, or
/// Metal compilation, setup or completion failure.
pub fn render_rgba8(
&self,
source: &str,
entries: [&str; 2],
vertices: &[[f32; 4]; 3],
colors: &[[f32; 4]; 3],
[width, height]: [usize; 2],
clear: [u8; 4],
) -> Result<Vec<u8>, MetalError> {
let pixels = width
.checked_mul(height)
.filter(|&count| (1..=MAX_PIXELS).contains(&count))
.ok_or_else(|| MetalError::new("render bounds", "expected 1..=4096 pixels"))?;
validate_source(source, &entries)?;
if vertices
.iter()
.chain(colors)
.flatten()
.any(|value| !value.is_finite())
{
return Err(MetalError::new(
"render input",
"expected finite vertex data",
));
}
autoreleasepool(|_| {
let options = compile_options()?;
let library = self.compile_library(source, &options)?;
let vertex = find_function(&library, entries[0])?;
let fragment = find_function(&library, entries[1])?;
let descriptor = MTLRenderPipelineDescriptor::new();
descriptor.setVertexFunction(Some(&vertex));
descriptor.setFragmentFunction(Some(&fragment));
// SAFETY: Slot zero is the only color attachment for this pipeline.
unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(0) }
.setPixelFormat(PIXEL_FORMAT);
let pipeline = self
.device
.newRenderPipelineStateWithDescriptor_error(&descriptor)
.map_err(|error| {
MetalError::new(
"newRenderPipelineStateWithDescriptor",
error.localizedDescription().to_string(),
)
})?;
verify_render_validation(&pipeline)?;
// SAFETY: The nonzero dimensions are bounded by MAX_PIXELS, and
// RGBA8Unorm is a renderable format on the selected Apple family.
let texture_descriptor = unsafe {
MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped(
PIXEL_FORMAT,
width,
height,
false,
)
};
texture_descriptor.setStorageMode(MTLStorageMode::Shared);
texture_descriptor.setUsage(MTLTextureUsage::RenderTarget);
let texture = self
.device
.newTextureWithDescriptor(&texture_descriptor)
.ok_or_else(|| {
MetalError::new(
"newTextureWithDescriptor",
"render target allocation failed",
)
})?;
let pass = MTLRenderPassDescriptor::renderPassDescriptor();
// SAFETY: Slot zero is the only color attachment for this pass.
let attachment = unsafe { pass.colorAttachments().objectAtIndexedSubscript(0) };
attachment.setTexture(Some(&texture));
attachment.setLoadAction(MTLLoadAction::Clear);
let [red, green, blue, alpha] = clear.map(|value| f64::from(value) / 255.0);
attachment.setClearColor(MTLClearColor {
red,
green,
blue,
alpha,
});
attachment.setStoreAction(MTLStoreAction::Store);
let positions = self.new_buffer(
vertices
.map(|vertex| vertex.map(f32::to_bits))
.as_flattened(),
)?;
let colors =
self.new_buffer(colors.map(|color| color.map(f32::to_bits)).as_flattened())?;
let command = self.queue.commandBuffer().ok_or_else(|| {
MetalError::new("commandBuffer", "render command buffer creation failed")
})?;
let encoder = command
.renderCommandEncoderWithDescriptor(&pass)
.ok_or_else(|| {
MetalError::new(
"renderCommandEncoderWithDescriptor",
"render encoder creation failed",
)
})?;
encoder.setRenderPipelineState(&pipeline);
encoder.setViewport(MTLViewport {
originX: 0.0,
originY: 0.0,
width: width as f64,
height: height as f64,
znear: 0.0,
zfar: 1.0,
});
// SAFETY: Both buffers come from this device and each holds three
// float4s. The trusted vertex entry may read only these records.
// The render target format matches that of the pipeline.
unsafe {
encoder.setVertexBuffer_offset_atIndex(Some(&positions), 0, 0);
encoder.setVertexBuffer_offset_atIndex(Some(&colors), 0, 1);
encoder.drawPrimitives_vertexStart_vertexCount(MTLPrimitiveType::Triangle, 0, 3);
}
encoder.endEncoding();
complete_command(&command)?;
let region = MTLRegion {
origin: MTLOrigin { x: 0, y: 0, z: 0 },
size: MTLSize {
width,
height,
depth: 1,
},
};
let mut output = vec![0; pixels * 4];
// SAFETY: GPU writes have completed, and the initialized output
// allocation fits the entire shared texture with tightly packed rows.
unsafe {
texture.getBytes_bytesPerRow_fromRegion_mipmapLevel(
NonNull::from(output.as_mut_slice()).cast(),
width * 4,
region,
0,
);
}
Ok(output)
})
}
}
fn verify_render_validation(
pipeline: &ProtocolObject<dyn MTLRenderPipelineState>,
) -> Result<(), MetalError> {
if std::env::var("MTL_SHADER_VALIDATION").as_deref() != Ok("1") {
return Ok(());
}
if !pipeline.respondsToSelector(sel!(shaderValidation)) {
return Err(MetalError::new(
"shaderValidation",
"the runtime lacks the render pipeline state query",
));
}
// SAFETY: The selector exists and the newly created pipeline is private
// to this thread. Its non-atomic property is read before encoding.
if unsafe { pipeline.shaderValidation() } != MTLShaderValidation::Enabled {
return Err(MetalError::new(
"shaderValidation",
"shader validation requested but inactive for the render pipeline",
));
}
Ok(())
}
-97
View File
@@ -1,97 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Native Apple Metal sampler state abstraction.
//!
//! Provides safe creation and ownership of native Metal `MTLSamplerState` objects
//! configured from validated [`SamplerDesc`].
use objc2::rc::{Retained, autoreleasepool};
use objc2::runtime::ProtocolObject;
use objc2_metal::{
MTLDevice, MTLSamplerAddressMode, MTLSamplerDescriptor, MTLSamplerMinMagFilter,
MTLSamplerMipFilter, MTLSamplerState,
};
use xenora_texture::{AddressMode, FilterMode, SamplerDesc, SamplerError};
use crate::MetalError;
/// Safe wrapper owning a native Metal sampler state object.
#[derive(Debug, Clone)]
pub struct MetalSampler {
sampler: Retained<ProtocolObject<dyn MTLSamplerState>>,
desc: SamplerDesc,
}
impl MetalSampler {
/// Create a native Metal sampler from a [`SamplerDesc`] on the provided Metal device.
///
/// # Errors
///
/// Returns [`MetalError`] if descriptor validation fails or if Metal fails
/// to create the sampler state.
pub fn new(
device: &ProtocolObject<dyn MTLDevice>,
desc: SamplerDesc,
) -> Result<Self, MetalError> {
desc.validate()
.map_err(|err: SamplerError| MetalError::new("sampler validation", err.to_string()))?;
autoreleasepool(|_| {
let descriptor = MTLSamplerDescriptor::new();
let min_filter = match desc.min_filter {
FilterMode::Nearest => MTLSamplerMinMagFilter::Nearest,
};
let mag_filter = match desc.mag_filter {
FilterMode::Nearest => MTLSamplerMinMagFilter::Nearest,
};
let mip_filter = match desc.mip_filter {
FilterMode::Nearest => MTLSamplerMipFilter::Nearest,
};
let s_address = match desc.address_u {
AddressMode::ClampToEdge => MTLSamplerAddressMode::ClampToEdge,
};
let t_address = match desc.address_v {
AddressMode::ClampToEdge => MTLSamplerAddressMode::ClampToEdge,
};
descriptor.setMinFilter(min_filter);
descriptor.setMagFilter(mag_filter);
descriptor.setMipFilter(mip_filter);
descriptor.setSAddressMode(s_address);
descriptor.setTAddressMode(t_address);
descriptor.setRAddressMode(MTLSamplerAddressMode::ClampToEdge);
// Normalized coordinates: normalized UV sampling in [0.0, 1.0].
descriptor.setNormalizedCoordinates(true);
// Validated LOD bounds.
descriptor.setLodMinClamp(desc.min_lod);
descriptor.setLodMaxClamp(desc.max_lod);
let sampler = device
.newSamplerStateWithDescriptor(&descriptor)
.ok_or_else(|| {
MetalError::new(
"newSamplerStateWithDescriptor",
"failed to create Metal sampler state",
)
})?;
Ok(Self { sampler, desc })
})
}
/// Access the underlying native Metal sampler state protocol object.
#[inline]
pub fn raw(&self) -> &ProtocolObject<dyn MTLSamplerState> {
&self.sampler
}
/// Access the source sampler descriptor.
#[inline]
pub fn desc(&self) -> &SamplerDesc {
&self.desc
}
}
-330
View File
@@ -1,330 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Native Apple Metal RGBA8 texture upload and pipeline binding foundation.
//!
//! Provides validated RGBA8 2D texture allocation, mip upload, and binding definitions
//! for compute kernels and future translated pixel shader stages.
use std::ffi::c_void;
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,
};
use xenora_texture::{SamplerError, TextureMetadata};
use crate::MetalError;
use crate::sampler::MetalSampler;
/// Bytes per RGBA8 texel.
pub const RGBA8_TEXEL_BYTES: usize = 4;
/// Upper limit on total pixels per texture to prevent bounded resource overflow.
pub const MAX_TEXTURE_PIXELS: usize = 16384 * 16384;
/// Subresource mip level data descriptor for RGBA8 upload.
#[derive(Debug, Clone, Copy)]
pub struct Rgba8MipLevel<'a> {
pub level: u32,
pub width: usize,
pub height: usize,
pub row_pitch: usize,
pub bytes: &'a [u8],
}
impl<'a> Rgba8MipLevel<'a> {
/// Create a tightly packed mip level descriptor.
pub fn new_packed(level: u32, width: usize, height: usize, bytes: &'a [u8]) -> Self {
let row_pitch = width * RGBA8_TEXEL_BYTES;
Self {
level,
width,
height,
row_pitch,
bytes,
}
}
}
/// Description of an RGBA8 2D texture to allocate on Metal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Rgba8TextureDesc {
pub width: usize,
pub height: usize,
pub mips: u32,
}
impl Rgba8TextureDesc {
pub fn new(width: usize, height: usize, mips: u32) -> Result<Self, MetalError> {
let meta = TextureMetadata::new(width, height, mips).map_err(|err: SamplerError| {
MetalError::new("texture metadata validation", err.to_string())
})?;
let total_pixels = width
.checked_mul(height)
.ok_or_else(|| MetalError::new("texture dimensions", "pixel count overflow"))?;
if total_pixels > MAX_TEXTURE_PIXELS {
return Err(MetalError::new(
"texture bounds",
"texture exceeds maximum allowable pixels",
));
}
Ok(Self {
width: meta.width,
height: meta.height,
mips: meta.mips,
})
}
/// Compute expected dimensions for a given mip level.
pub fn mip_extent(&self, level: u32) -> Result<(usize, usize), MetalError> {
if level >= self.mips {
return Err(MetalError::new(
"mip level bounds",
"mip level index is out of bounds",
));
}
let mip_w = (self.width >> level).max(1);
let mip_h = (self.height >> level).max(1);
Ok((mip_w, mip_h))
}
}
/// Safe wrapper owning a native Metal RGBA8 2D texture.
#[derive(Debug, Clone)]
pub struct MetalRgba8Texture {
texture: Retained<ProtocolObject<dyn MTLTexture>>,
desc: Rgba8TextureDesc,
}
impl MetalRgba8Texture {
/// Allocate an empty native Metal RGBA8 2D texture with storage mode Shared and ShaderRead usage.
pub fn allocate(
device: &ProtocolObject<dyn MTLDevice>,
desc: Rgba8TextureDesc,
) -> Result<Self, MetalError> {
autoreleasepool(|_| {
// SAFETY: Validated non-zero dimensions within MAX_TEXTURE_PIXELS and RGBA8Unorm format.
let descriptor = unsafe {
MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped(
MTLPixelFormat::RGBA8Unorm,
desc.width,
desc.height,
desc.mips > 1,
)
};
if desc.mips > 1 {
// SAFETY: desc.mips is validated by TextureMetadata to not exceed max_mip_levels.
unsafe {
descriptor.setMipmapLevelCount(desc.mips as usize);
}
}
descriptor.setStorageMode(MTLStorageMode::Shared);
descriptor.setResourceOptions(MTLResourceOptions::StorageModeShared);
descriptor.setUsage(MTLTextureUsage::ShaderRead);
let texture = device
.newTextureWithDescriptor(&descriptor)
.ok_or_else(|| {
MetalError::new(
"newTextureWithDescriptor",
"failed to allocate RGBA8 Metal texture",
)
})?;
Ok(Self { texture, desc })
})
}
/// Upload a single validated mip level into this texture.
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 {
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
),
));
}
autoreleasepool(|_| {
let region = MTLRegion {
origin: MTLOrigin { x: 0, y: 0, z: 0 },
size: MTLSize {
width: mip.width,
height: mip.height,
depth: 1,
},
};
let ptr = NonNull::new(mip.bytes.as_ptr() as *mut c_void).ok_or_else(|| {
MetalError::new("pointer", "null data pointer for texture upload")
})?;
// SAFETY: The bounds check verifies that mip.bytes has at least
// `mip.row_pitch * mip.height` bytes, the region size matches mip dimensions,
// the mip level is within the texture's allocated mip count, and the pointer is valid.
unsafe {
self.texture
.replaceRegion_mipmapLevel_withBytes_bytesPerRow(
region,
mip.level as usize,
ptr,
mip.row_pitch,
);
}
Ok(())
})
}
/// Allocate and populate an RGBA8 2D texture from a set of mip levels.
pub fn upload(
device: &ProtocolObject<dyn MTLDevice>,
desc: Rgba8TextureDesc,
mips: &[Rgba8MipLevel<'_>],
) -> Result<Self, MetalError> {
let texture = Self::allocate(device, desc)?;
for mip in mips {
texture.upload_mip(mip)?;
}
Ok(texture)
}
/// Access the underlying native Metal texture protocol object.
#[inline]
pub fn raw(&self) -> &ProtocolObject<dyn MTLTexture> {
&self.texture
}
/// Access the texture descriptor.
#[inline]
pub fn desc(&self) -> &Rgba8TextureDesc {
&self.desc
}
}
/// Resource binding indices and lifetime conventions for sampling pipelines.
///
/// In the Xenora fixture ABI and translated shader conventions:
/// - Metal textures are bound to `[[texture(slot)]]`.
/// - Metal samplers are bound to `[[sampler(slot)]]`.
///
/// Under future RDNA2-to-Metal shader translation:
/// - An image resource descriptor (`T#`) maps to a `texture2d` binding.
/// - A sampler descriptor (`S#`) maps to a `sampler` binding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BindingSlot {
pub index: u32,
}
impl BindingSlot {
pub const fn new(index: u32) -> Self {
Self { index }
}
}
/// A validated texture-sampler pair ready for pipeline binding.
///
/// This struct holds strong references to the native Metal texture and sampler,
/// verifying that LOD ranges and explicit mip levels are consistent before
/// submitting draw or compute work.
#[derive(Debug, Clone)]
pub struct BoundSampledTexture {
texture: MetalRgba8Texture,
sampler: MetalSampler,
texture_slot: BindingSlot,
sampler_slot: BindingSlot,
}
impl BoundSampledTexture {
/// Bind a texture and sampler together to specified shader slots.
///
/// # Errors
///
/// Returns [`MetalError`] if the sampler's explicit mip or LOD constraints
/// are out of bounds for the texture's mip chain.
pub fn bind(
texture: MetalRgba8Texture,
sampler: MetalSampler,
texture_slot: BindingSlot,
sampler_slot: BindingSlot,
) -> Result<Self, MetalError> {
let meta = TextureMetadata::new(
texture.desc().width,
texture.desc().height,
texture.desc().mips,
)
.map_err(|err: SamplerError| MetalError::new("texture metadata", err.to_string()))?;
sampler
.desc()
.validate_against_texture(&meta)
.map_err(|err: SamplerError| {
MetalError::new("sampler texture compatibility", err.to_string())
})?;
Ok(Self {
texture,
sampler,
texture_slot,
sampler_slot,
})
}
#[inline]
pub fn texture(&self) -> &MetalRgba8Texture {
&self.texture
}
#[inline]
pub fn sampler(&self) -> &MetalSampler {
&self.sampler
}
#[inline]
pub fn texture_slot(&self) -> BindingSlot {
self.texture_slot
}
#[inline]
pub fn sampler_slot(&self) -> BindingSlot {
self.sampler_slot
}
}
Binary file not shown.
-9
View File
@@ -1,9 +0,0 @@
# SPDX-License-Identifier: GPL-3.0-or-later
.text
buffer_load_dword v1, v0, s[0:3], 0 idxen
s_waitcnt vmcnt(0)
v_mov_b32_e32 v2, 0x01020304
v_xor_b32_e32 v1, v1, v2
buffer_store_dword v1, v0, s[4:7], 0 idxen
s_waitcnt_vscnt null, 0
s_endpgm
-137
View File
@@ -1,137 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_metal::{GuestBuffer, GuestBufferView, NativeCompute};
use xenora_shader::{Architecture, ENTRY_POINT, compile};
const CODE: &[u8] = include_bytes!("../fixtures/guest-buffer-xor.bin");
const INPUT: GuestBufferView = GuestBufferView {
handle: 1,
binding: 0,
byte_offset: 4,
byte_len: 16,
};
const PAYLOAD: &[u8] = &[
0xde, 0xad, 0xbe, 0xef, // prefix outside the view
0x00, 0x00, 0x00, 0x00, // 0x00000000
0xff, 0xff, 0xff, 0xff, // 0xffffffff
0x44, 0x33, 0x22, 0x11, // 0x11223344
0x04, 0x03, 0x02, 0x01, // 0x01020304
0xca, 0xfe, 0xf0, 0x0d, // suffix outside the view
];
#[test]
fn translated_shader_reads_validated_guest_buffer() {
let context = NativeCompute::new().expect("native Metal device and queue");
let shader = compile(Architecture::Gfx1030, CODE).expect("translate original gfx1030 shader");
let table = [
GuestBuffer {
format: GuestBuffer::U32_LE,
bytes: &[0x55; PAYLOAD.len()],
},
GuestBuffer {
format: GuestBuffer::U32_LE,
bytes: PAYLOAD,
},
];
let readback = context
.run_guest_words(&shader.msl, ENTRY_POINT, &table, INPUT)
.expect("complete translated Metal dispatch");
let bytes: Vec<_> = readback.into_iter().flat_map(u32::to_le_bytes).collect();
// Independent known answers: XOR each selected guest word with 0x01020304.
assert_eq!(
bytes,
[
0x04, 0x03, 0x02, 0x01, 0xfb, 0xfc, 0xfd, 0xfe, 0x40, 0x30, 0x20, 0x10, 0x00, 0x00,
0x00, 0x00,
]
);
println!("Translated guest buffer readback: {bytes:02x?}");
}
#[test]
fn rejects_invalid_guest_buffer_before_compilation() {
let context = NativeCompute::new().expect("native Metal device and queue");
let oversized = [0; 16_388];
let table = [
GuestBuffer {
format: 99,
bytes: PAYLOAD,
},
GuestBuffer {
format: GuestBuffer::U32_LE,
bytes: PAYLOAD,
},
GuestBuffer {
format: GuestBuffer::U32_LE,
bytes: &oversized,
},
];
let cases = [
(
GuestBufferView {
binding: 1,
..INPUT
},
"guest buffer binding",
),
(
GuestBufferView { handle: 3, ..INPUT },
"guest buffer handle",
),
(
GuestBufferView { handle: 0, ..INPUT },
"guest buffer format",
),
(
GuestBufferView {
byte_offset: 1,
..INPUT
},
"guest buffer bounds",
),
(
GuestBufferView {
byte_len: 3,
..INPUT
},
"guest buffer bounds",
),
(
GuestBufferView {
byte_len: 0,
..INPUT
},
"guest buffer bounds",
),
(
GuestBufferView {
handle: 2,
byte_offset: 0,
byte_len: oversized.len(),
..INPUT
},
"guest buffer bounds",
),
(
GuestBufferView {
byte_offset: 12,
..INPUT
},
"guest buffer bounds",
),
(
GuestBufferView {
byte_offset: usize::MAX & !3,
..INPUT
},
"guest buffer bounds",
),
];
for (view, operation) in cases {
let error = context
.run_guest_words("invalid MSL", ENTRY_POINT, &table, view)
.expect_err("guest view must fail before Metal compilation");
assert_eq!(error.operation, operation, "{view:?}");
}
}
-54
View File
@@ -1,54 +0,0 @@
use super::context;
const WIDTH: usize = 8;
const HEIGHT: usize = 6;
const RENDER_SOURCE: &str = r"
#include <metal_stdlib>
using namespace metal;
vertex float4 cover_viewport(uint vertex_id [[vertex_id]]) {
float x = vertex_id == 1u ? 3.0f : -1.0f;
float y = vertex_id == 2u ? 3.0f : -1.0f;
return float4(x, y, 0.5f, 1.0f);
}
fragment float4 draw_pattern(float4 position [[position]]) {
uint x = uint(position.x);
uint y = uint(position.y);
if (x == y) {
discard_fragment();
}
return float4(y < 3u, x >= 4u, ((x ^ y) & 1u) != 0u, 1.0f);
}
";
#[test]
fn offscreen_vertex_and_fragment() {
let pixels = context()
.render_rgba8(
RENDER_SOURCE,
["cover_viewport", "draw_pattern"],
&[[0.0; 4]; 3],
&[[0.0; 4]; 3],
[WIDTH, HEIGHT],
[255, 255, 0, 255],
)
.expect("draw native offscreen fixture");
assert_eq!(pixels.len(), WIDTH * HEIGHT * 4);
for (index, pixel) in pixels.as_chunks::<4>().0.iter().enumerate() {
let x = index % WIDTH;
let y = index / WIDTH;
let expected = if x == y {
[255, 255, 0, 255]
} else {
[
if y < 3 { 255 } else { 0 },
if x >= 4 { 255 } else { 0 },
if (x + y) % 2 == 1 { 255 } else { 0 },
255,
]
};
assert_eq!(*pixel, expected, "pixel ({x}, {y})");
}
println!("checked {} RGBA8 pixels", WIDTH * HEIGHT);
}
-135
View File
@@ -1,135 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_texture::{Bc1Upload, Bc1UploadDesc, TiledBc1};
use super::context;
#[test]
fn samples_selected_bc1_layer_and_mip() {
// Each 9×5 layer has two tiles for mip zero and one for mip one.
// Color words are BC1 endpoint zero except for the transparent block,
// where the ascending endpoints and selector three give transparent black.
let red = [0, 248, 0, 0, 0, 0, 0, 0];
let green = [224, 7, 0, 0, 0, 0, 0, 0];
let blue = [31, 0, 0, 0, 0, 0, 0, 0];
let white = [255, 255, 0, 0, 0, 0, 0, 0];
let clear = [0, 0, 255, 255, 255, 255, 255, 255];
let yellow = [224, 255, 0, 0, 0, 0, 0, 0];
let black = [0; 8];
let blocks = [
black, black, black, black, black, black, black, black, black, black, black, black, red,
green, white, clear, blue, black, yellow, black, green, black, black, black,
];
let texture = TiledBc1::new(blocks.as_flattened(), 9, 5, 2, 2).unwrap();
let context = context();
let pixels = context.read_tiled_bc1(&texture, 1, 0).unwrap();
let upper = [
0xff00_00ff,
0xff00_00ff,
0xff00_00ff,
0xff00_00ff,
0xff00_ff00,
0xff00_ff00,
0xff00_ff00,
0xff00_ff00,
0xffff_0000,
];
let lower = [
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0,
0,
0,
0,
0xff00_ffff,
];
let expected: Vec<_> = upper.repeat(4).into_iter().chain(lower).collect();
assert_eq!(pixels, expected);
assert_eq!(
context.read_tiled_bc1(&texture, 1, 1).unwrap(),
[0xff00_ff00; 8]
);
assert_eq!(
context.read_tiled_bc1(&texture, 0, 1).unwrap(),
[0xff00_0000; 8]
);
assert_eq!(
context
.read_tiled_bc1(&texture, 2, 0)
.unwrap_err()
.operation,
"texture subresource"
);
assert_eq!(
context
.read_tiled_bc1(&texture, 0, 2)
.unwrap_err()
.operation,
"texture subresource"
);
println!(
"device={} checked 61 RGBA8 texels from three subresources",
context.device_name()
);
}
#[test]
fn samples_pitched_bc1_upload_across_mips_and_layers() {
let red = [0, 248, 0, 0, 0, 0, 0, 0];
let green = [224, 7, 0, 0, 0, 0, 0, 0];
let blue = [31, 0, 0, 0, 0, 0, 0, 0];
let white = [255, 255, 0, 0, 0, 0, 0, 0];
let clear = [0, 0, 255, 255, 255, 255, 255, 255];
// Seven physical blocks per subresource. A base level consumes the
// first two blocks of both rows, and mip 1 consumes only block zero.
let pad = red;
let blocks = [
[blue, blue, pad, blue, blue, pad, pad],
[green, pad, pad, pad, pad, pad, pad],
[red, green, pad, blue, white, pad, pad],
[clear, pad, pad, pad, pad, pad, pad],
];
let upload = Bc1Upload::new(
blocks.as_flattened().as_flattened(),
Bc1UploadDesc {
width: 5,
height: 5,
mips: 2,
layers: 2,
format: 1,
usage: 1,
row_pitch: 24,
slice_pitch: 56,
},
)
.unwrap();
let gpu = context();
let upper = [
0xff00_00ff,
0xff00_00ff,
0xff00_00ff,
0xff00_00ff,
0xff00_ff00,
];
let bottom = [
0xffff_0000,
0xffff_0000,
0xffff_0000,
0xffff_0000,
0xffff_ffff,
];
let expected: Vec<_> = upper.repeat(4).into_iter().chain(bottom).collect();
assert_eq!(gpu.read_bc1_upload(&upload, 1, 0).unwrap(), expected);
assert_eq!(gpu.read_bc1_upload(&upload, 1, 1).unwrap(), [0; 4]);
assert_eq!(
gpu.read_bc1_upload(&upload, 0, 1).unwrap(),
[0xff00_ff00; 4]
);
assert_eq!(
gpu.read_bc1_upload(&upload, 2, 0).unwrap_err().operation,
"texture subresource"
);
println!("checked 33 RGBA8 texels from pitched BC1 subresources");
}
@@ -1,90 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_metal::sampler::MetalSampler;
use xenora_metal::texture_pipeline::{
BindingSlot, BoundSampledTexture, MetalRgba8Texture, Rgba8MipLevel, Rgba8TextureDesc,
};
use xenora_texture::SamplerDesc;
use super::context;
#[test]
fn native_gpu_rgba8_sampling_matches_cpu_reference() {
let gpu = context();
// 1. Prepare a 2x2 texture with four distinct RGBA8 pixels.
// Pixel layout:
// (0, 0): Red [255, 0, 0, 255] -> word: 0xff0000ff
// (1, 0): Green [ 0, 255, 0, 255] -> word: 0xff00ff00
// (0, 1): Blue [ 0, 0, 255, 255] -> word: 0xffff0000
// (1, 1): White [255, 255, 255, 255] -> word: 0xffffffff
let red_word = 0xff00_00ff_u32;
let green_word = 0xff00_ff00_u32;
let blue_word = 0xffff_0000_u32;
let white_word = 0xffff_ffff_u32;
let texels_level0: [u8; 16] = [
255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
];
let tex_desc = Rgba8TextureDesc::new(2, 2, 1).expect("valid 2x2 texture desc");
let mip0 = Rgba8MipLevel::new_packed(0, 2, 2, &texels_level0);
let texture = MetalRgba8Texture::upload(gpu.device(), tex_desc, &[mip0])
.expect("upload RGBA8 2x2 texture to Metal");
// 2. Create native Metal sampler with nearest filtering and clamp-to-edge addressing.
let sampler_desc = SamplerDesc::nearest_clamp();
let sampler =
MetalSampler::new(gpu.device(), sampler_desc).expect("create native Metal sampler");
// 3. Verify binding descriptor
let bound = BoundSampledTexture::bind(
texture.clone(),
sampler.clone(),
BindingSlot::new(0),
BindingSlot::new(0),
)
.expect("valid pipeline binding");
assert_eq!(bound.texture_slot().index, 0);
assert_eq!(bound.sampler_slot().index, 0);
// 4. Test coordinates including interior points, texel boundaries, and edge clamping.
let uv_coords = [
// (0, 0) interior -> Red
[0.25_f32, 0.25],
// (1, 0) interior -> Green
[0.75, 0.25],
// (0, 1) interior -> Blue
[0.25, 0.75],
// (1, 1) interior -> White
[0.75, 0.75],
// Clamped negative U and V (< 0.0) -> clamps to (0, 0) -> Red
[-0.5, -0.5],
// Clamped excess U and V (> 1.0) -> clamps to (1, 1) -> White
[1.5, 1.5],
// Clamped mixed: U < 0.0, V > 1.0 -> clamps to (0, 1) -> Blue
[-0.2, 1.8],
// Clamped mixed: U > 1.0, V < 0.0 -> clamps to (1, 0) -> Green
[1.2, -0.3],
];
let expected_words = [
red_word, green_word, blue_word, white_word, red_word, white_word, blue_word, green_word,
];
// 5. Dispatch on the native Apple Silicon GPU.
let actual_words = gpu
.sample_rgba8(&texture, &sampler, &uv_coords)
.expect("Metal GPU texture sampling dispatch");
assert_eq!(
actual_words, expected_words,
"Native Apple GPU sampling output must match expected pixel words"
);
println!(
"device={} verified {} texture sampling points across interior and clamped coords on Apple Silicon GPU",
gpu.device_name(),
uv_coords.len()
);
}
@@ -1,184 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
use super::context;
const ENTRIES: [&str; 2] = [VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT];
const POSITIONS: [[f32; 4]; 3] = [
[-1.0, -1.0, 0.5, 1.0],
[3.0, -1.0, 0.5, 1.0],
[-1.0, 3.0, 0.5, 1.0],
];
const CLEAR: [u8; 4] = [19, 43, 93, 251];
#[test]
fn translated_constant_pixel_shader() {
let compiled = compile_graphics(
Architecture::Gfx1030,
include_bytes!("../../../../fixtures/rdna2/x9-constant-vs.bin"),
include_bytes!("../../../../fixtures/rdna2/x9-constant-ps.bin"),
)
.expect("compile constant graphics fixture");
let gpu = context();
// This triangle falls entirely past the right clipping plane.
let offscreen = POSITIONS.map(|[_, y, z, w]| [2.0, y, z, w]);
for (positions, pixel) in [(&POSITIONS, [255, 0, 0, 255]), (&offscreen, CLEAR)] {
let actual = gpu
.render_rgba8(
&compiled.msl,
ENTRIES,
positions,
&[[0.0; 4]; 3],
[4, 3],
CLEAR,
)
.expect("draw translated constant pixel shader");
assert_eq!(actual, pixel.repeat(12));
}
}
#[test]
fn translated_varying_pixel_shader() {
let compiled = compile_graphics(
Architecture::Gfx1030,
include_bytes!("../../../../fixtures/rdna2/x9-varying-vs.bin"),
include_bytes!("../../../../fixtures/rdna2/x9-varying-ps.bin"),
)
.expect("compile varying graphics fixture");
// Double the second vertex's homogeneous coordinates to keep the
// projected triangle fixed but vary its perspective interpolation weight.
let mut positions = POSITIONS;
positions[1] = positions[1].map(|component| 2.0 * component);
let colors = [
[0.0, 0.0, 0.0, 1.0],
[128.0 / 255.0, 0.0, 64.0 / 255.0, 1.0],
[0.0, 128.0 / 255.0, 64.0 / 255.0, 1.0],
];
let gpu = context();
let actual = gpu
.render_rgba8(&compiled.msl, ENTRIES, &positions, &colors, [4, 4], CLEAR)
.expect("draw translated varying pixel shader");
// The triangle legs span eight pixels from the bottom-left viewport
// corner. At pixel centers the second and third vertex's affine
// weights are (2x+1)/16 and (7-2y)/16. Dividing each by its clip W
// and normalizing gives the perspective weights below. The odd
// denominator makes nearest-byte conversion unambiguous.
let expected: Vec<u8> = (0..4)
.flat_map(|y| {
(0..4).flat_map(move |x| {
let u = 2 * x + 1;
let v = 2 * (7 - 2 * y);
let sum = 32 - u;
let byte = |value| ((value + sum / 2) / sum) as u8;
[byte(128 * u), byte(128 * v), byte(64 * (u + v)), 255]
})
})
.collect();
assert_eq!(actual, expected);
let swapped_colors = colors.map(|[r, g, b, a]| [g, r, b, a]);
let swapped = gpu
.render_rgba8(
&compiled.msl,
ENTRIES,
&positions,
&swapped_colors,
[4, 4],
CLEAR,
)
.expect("draw the same translated shader with red and green vertex data swapped");
let mut expected_swapped = expected.clone();
for pixel in expected_swapped.as_chunks_mut::<4>().0 {
pixel.swap(0, 1);
}
assert_ne!(expected_swapped, expected);
assert_eq!(swapped, expected_swapped);
println!("checked 16 perspective-interpolated RGBA8 pixels per color input");
}
#[test]
fn translated_render_rejects_out_of_policy_inputs() {
let gpu = context();
for extent in [[0, 1], [64, 65], [usize::MAX, 2]] {
let error = gpu
.render_rgba8("unused", ENTRIES, &POSITIONS, &[[0.0; 4]; 3], extent, CLEAR)
.expect_err("invalid dimensions must fail before MSL compilation");
assert_eq!(error.operation, "render bounds");
}
let error = gpu
.render_rgba8(
"unused",
ENTRIES,
&POSITIONS,
&[[f32::NAN; 4]; 3],
[1, 1],
CLEAR,
)
.expect_err("non-finite colors must fail before MSL compilation");
assert_eq!(error.operation, "render input");
}
#[test]
fn transformed_vertex_shader_draws_three_interior_pixels() {
let constant_ps = include_bytes!("../../../../fixtures/rdna2/x9-constant-ps.bin");
let transformed = compile_graphics(
Architecture::Gfx1030,
include_bytes!("../../../../fixtures/rdna2/x9-transform-vs.bin"),
constant_ps,
)
.expect("compile position transform");
let passthrough = compile_graphics(
Architecture::Gfx1030,
include_bytes!("../../../../fixtures/rdna2/x9-constant-vs.bin"),
constant_ps,
)
.expect("compile pass-through control");
let positions = [
[-1.5, -1.0, 0.5, 1.0],
[0.5, -1.0, 0.5, 1.0],
[-1.5, 2.0, 0.5, 1.0],
];
// Scaling x and y by half and biasing x by one quarter places the
// vertices at (1, 3), (3, 3), and (1, 0) in this 4x4 viewport.
// A sample center is inside exactly when 1 < x < 3 and
// 3*(x-1)/2 < y < 3. No edge crosses a sample center.
let mut expected = [CLEAR; 16];
for index in [5, 9, 10] {
expected[index] = [255, 0, 0, 255];
}
let gpu = context();
let colors = [[0.0; 4]; 3];
let transformed_pixels = gpu
.render_rgba8(
&transformed.msl,
ENTRIES,
&positions,
&colors,
[4, 4],
CLEAR,
)
.expect("draw translated transform");
assert_eq!(transformed_pixels, expected.as_flattened());
let passthrough_pixels = gpu
.render_rgba8(
&passthrough.msl,
ENTRIES,
&positions,
&colors,
[4, 4],
CLEAR,
)
.expect("draw unchanged positions through pass-through control");
// Without the transform, the diagonal extends from (-1, -2) to (3, 4)
// and the viewport clips both the left and upper edges of the triangle.
let mut expected_passthrough = [CLEAR; 16];
for index in [0, 4, 8, 9, 12, 13, 14] {
expected_passthrough[index] = [255, 0, 0, 255];
}
assert_eq!(passthrough_pixels, expected_passthrough.as_flattened());
println!("checked 3 covered pixels and 13 clear pixels from translated vertex arithmetic");
}
-190
View File
@@ -1,190 +0,0 @@
use xenora_metal::NativeCompute;
#[path = "native/guest_buffer.rs"]
mod guest_buffer;
#[path = "native/offscreen.rs"]
mod offscreen;
#[path = "native/texture.rs"]
mod texture;
#[path = "native/texture_sampling.rs"]
mod texture_sampling;
#[path = "native/translated_render.rs"]
mod translated_render;
const KERNEL_HEADER: &str = r"
#include <metal_stdlib>
using namespace metal;
kernel void fixture(device const uint *input [[buffer(0)]],
device uint *output [[buffer(1)]],
uint id [[thread_position_in_grid]],
uint local [[thread_index_in_threadgroup]],
uint group_size [[threads_per_threadgroup]]) {
";
fn fixture(body: &str) -> String {
format!("{KERNEL_HEADER}{body}\n}}")
}
fn context() -> NativeCompute {
NativeCompute::new().expect("native Metal device and queue")
}
fn verify_words(body: &str, input: &[u32], expected: &[u32]) {
let actual = context()
.run_words(&fixture(body), "fixture", input)
.expect("compiled and completed native Metal dispatch");
assert_eq!(actual, expected);
}
#[test]
fn integer_multiplication() {
let context = context();
println!(
"device={} api_validation_requested={} shader_validation_requested={}",
context.device_name(),
std::env::var("MTL_DEBUG_LAYER").as_deref() == Ok("1"),
std::env::var("MTL_SHADER_VALIDATION").as_deref() == Ok("1")
);
let values = [0, 1, 2, 3, u32::MAX, 0x8000_0000, 0x4000_0000];
let input: Vec<_> = values.into_iter().cycle().take(131).collect();
let expected: Vec<_> = input.iter().map(|&value| value.wrapping_mul(7)).collect();
let actual = context
.run_words(&fixture("output[id] = input[id] * 7u;"), "fixture", &input)
.expect("compiled and completed native Metal dispatch");
assert_eq!(actual, expected);
println!(
"checked {} output words in a nonuniform grid",
expected.len()
);
}
#[test]
fn vector_addition() {
verify_words(
"output[id] = input[id] + input[id ^ 1u];",
&[u32::MAX, 2, 0x8000_0000, 0x8000_0001, 123, 42, 0, 0],
&[1, 1, 1, 1, 165, 165, 0, 0],
);
}
#[test]
fn bitwise_operations() {
let input = [0, 1, u32::MAX, 0x8000_0000, 0x1122_3344, 0x5555_AAAA];
let expected = input.map(|value| ((value & 0x0F0F_0000) >> 8) ^ (!value & 0xFF));
verify_words(
"output[id] = ((input[id] & 0x0f0f0000u) >> 8u) ^ (~input[id] & 0xffu);",
&input,
&expected,
);
}
#[test]
fn copy_across_distinct_bindings() {
let input = [0x0123_4567, 0, u32::MAX, 0x8000_0000, 0x89AB_CDEF];
verify_words("output[id] = input[id];", &input, &input);
}
#[test]
fn exactly_representable_floating_point_arithmetic() {
let input = [0.0_f32, 0.5, -0.5, 1.25, -2.0, 1024.0];
let expected = [0.25_f32, 1.25, -0.75, 2.75, -3.75, 2048.25];
verify_words(
"output[id] = as_type<uint>(as_type<float>(input[id]) * 2.0f + 0.25f);",
&input.map(f32::to_bits),
&expected.map(f32::to_bits),
);
}
#[test]
fn conditional_branching() {
verify_words(
r"
if (input[id] > 10u) {
output[id] = input[id] - 10u;
} else {
output[id] = input[id] * 4u;
}
",
&[0, 10, 11, 3, u32::MAX, 17],
&[0, 40, 1, 12, u32::MAX - 10, 7],
);
}
#[test]
fn synchronized_threadgroup_memory() {
let input: Vec<_> = (100..228).collect();
let expected: Vec<_> = (0..input.len()).map(|index| input[index ^ 1]).collect();
verify_words(
r"
threadgroup uint stored[64];
stored[local] = input[id];
threadgroup_barrier(mem_flags::mem_threadgroup);
uint neighbor = local ^ 1u;
output[id] = neighbor < group_size ? stored[neighbor] : 0u;
",
&input,
&expected,
);
}
#[test]
fn threadgroup_atomic_addition() {
verify_words(
r"
threadgroup atomic_uint sum;
if (local == 0u) {
atomic_store_explicit(&sum, 0u, memory_order_relaxed);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
atomic_fetch_add_explicit(&sum, input[id], memory_order_relaxed);
threadgroup_barrier(mem_flags::mem_threadgroup);
output[id] = atomic_load_explicit(&sum, memory_order_relaxed);
",
&[5, 0, 2, 1, 17, 4, 3, 8],
&[40; 8],
);
}
#[test]
fn simdgroup_reduction() {
let input: Vec<_> = (0..128).map(|index| 1 + (index & 1)).collect();
// The historical M5 probe measured 32 lanes. Every pair sums to 3,
// so a complete 32-lane SIMD group of this input sums to 48.
verify_words("output[id] = simd_sum(input[id]);", &input, &[48; 128]);
}
#[test]
fn multiple_submissions() {
let context = context();
let source = fixture("output[id] = input[id] + id;");
let first = context.run_words(&source, "fixture", &[1, 2, 3]).unwrap();
let second = context
.run_words(&source, "fixture", &[5, 4, u32::MAX, 2])
.unwrap();
assert_eq!(first, [1, 3, 5]);
assert_eq!(second, [5, 5, 1, 5]);
}
#[test]
fn errors_propagate() {
let context = context();
let source = fixture("output[id] = input[id];");
let error = context
.run_words("not valid MSL", "fixture", &[25])
.expect_err("invalid source must fail");
assert_eq!(error.operation, "newLibraryWithSource");
assert!(!error.detail.is_empty());
let error = context
.run_words(&source, "nonexistent_entry", &[25])
.expect_err("missing entry must fail");
assert_eq!(error.operation, "newFunctionWithName");
let error = context
.run_words(&source, "fixture", &[])
.expect_err("empty dispatch must fail");
assert_eq!(error.operation, "dispatch bounds");
let error = context
.run_words(&source, "fixture", &[0; 4097])
.expect_err("excessive dispatch must fail");
assert_eq!(error.operation, "dispatch bounds");
}
-102
View File
@@ -1,102 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_metal::texture_pipeline::{BindingSlot, Rgba8MipLevel, Rgba8TextureDesc};
use xenora_texture::{AddressMode, FilterMode, SamplerDesc, TextureMetadata};
#[test]
fn test_valid_sampler_desc_and_lod() {
let sampler_desc = SamplerDesc::nearest_clamp().with_lod_range(0.0, 5.0);
assert!(sampler_desc.validate().is_ok());
assert_eq!(sampler_desc.min_filter, FilterMode::Nearest);
assert_eq!(sampler_desc.mag_filter, FilterMode::Nearest);
assert_eq!(sampler_desc.address_u, AddressMode::ClampToEdge);
assert_eq!(sampler_desc.address_v, AddressMode::ClampToEdge);
assert_eq!(sampler_desc.min_lod, 0.0);
assert_eq!(sampler_desc.max_lod, 5.0);
}
#[test]
fn test_invalid_sampler_configurations() {
let invalid_order = SamplerDesc::nearest_clamp().with_lod_range(4.0, 2.0);
assert!(invalid_order.validate().is_err());
let negative_lod = SamplerDesc::nearest_clamp().with_lod_range(-1.0, 2.0);
assert!(negative_lod.validate().is_err());
let nan_lod = SamplerDesc::nearest_clamp().with_lod_range(f32::NAN, 2.0);
assert!(nan_lod.validate().is_err());
}
#[test]
fn test_rgba8_texture_desc_validation() {
// Valid 4x4 with 3 mips (4x4, 2x2, 1x1)
let desc = Rgba8TextureDesc::new(4, 4, 3);
assert!(desc.is_ok());
let desc = desc.unwrap();
assert_eq!(desc.mip_extent(0).unwrap(), (4, 4));
assert_eq!(desc.mip_extent(1).unwrap(), (2, 2));
assert_eq!(desc.mip_extent(2).unwrap(), (1, 1));
assert!(desc.mip_extent(3).is_err());
// Non-power-of-two 3x3 has max 2 mips
let npot = Rgba8TextureDesc::new(3, 3, 2);
assert!(npot.is_ok());
let npot = npot.unwrap();
assert_eq!(npot.mip_extent(0).unwrap(), (3, 3));
assert_eq!(npot.mip_extent(1).unwrap(), (1, 1));
// Exceeding max mips for 3x3
assert!(Rgba8TextureDesc::new(3, 3, 3).is_err());
// Zero dimensions
assert!(Rgba8TextureDesc::new(0, 4, 1).is_err());
assert!(Rgba8TextureDesc::new(4, 0, 1).is_err());
assert!(Rgba8TextureDesc::new(4, 4, 0).is_err());
}
#[test]
fn test_rgba8_mip_level_pitch_and_length_validation() {
// Mip 0 for 2x2: width 2, height 2, tight pitch 8 bytes, total 16 bytes.
let valid_data = [0u8; 16];
let mip = Rgba8MipLevel::new_packed(0, 2, 2, &valid_data);
assert_eq!(mip.row_pitch, 8);
assert_eq!(mip.bytes.len(), 16);
// Explicit pitch with padding: width 2, row_pitch 12, height 2 -> needs 24 bytes.
let padded_data = [0u8; 24];
let padded_mip = Rgba8MipLevel {
level: 0,
width: 2,
height: 2,
row_pitch: 12,
bytes: &padded_data,
};
assert_eq!(padded_mip.row_pitch, 12);
}
#[test]
fn test_invalid_resource_and_sampler_combinations() {
let texture_desc = Rgba8TextureDesc::new(8, 8, 3).unwrap();
let meta =
TextureMetadata::new(texture_desc.width, texture_desc.height, texture_desc.mips).unwrap();
// Sampler requesting explicit mip 3 when texture only has 3 mips (indices 0, 1, 2)
let invalid_mip_sampler = SamplerDesc::nearest_clamp().with_explicit_mip(3);
assert!(invalid_mip_sampler.validate_against_texture(&meta).is_err());
// Sampler with min_lod 3.0 when texture only has 3 mips
let invalid_lod_sampler = SamplerDesc::nearest_clamp().with_lod_range(3.0, 5.0);
assert!(invalid_lod_sampler.validate_against_texture(&meta).is_err());
// Valid sampler against this texture
let valid_sampler = SamplerDesc::nearest_clamp().with_lod_range(0.0, 2.0);
assert!(valid_sampler.validate_against_texture(&meta).is_ok());
}
#[test]
fn test_binding_slot_construction() {
let tex_slot = BindingSlot::new(0);
let samp_slot = BindingSlot::new(1);
assert_eq!(tex_slot.index, 0);
assert_eq!(samp_slot.index, 1);
}
-10
View File
@@ -1,10 +0,0 @@
[package]
name = "xenora-ref"
description = "Independent CPU reference for Xenora synthetic RDNA fixtures"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[lints]
workspace = true
-615
View File
@@ -1,615 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent CPU execution of the synthetic gfx1030 fixture subset and reference sampling.
pub mod texture_sampling;
use std::fmt;
const MAX_CODE_BYTES: usize = 1024;
const MAX_INPUT_WORDS: usize = 4096;
#[derive(Debug, PartialEq, Eq)]
pub struct ReferenceError {
pub offset: usize,
pub detail: &'static str,
}
impl fmt::Display for ReferenceError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "reference byte {:#x}: {}", self.offset, self.detail)
}
}
impl std::error::Error for ReferenceError {}
/// Register index or immediate bits. The opcode determines the register bank.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Source {
Register(u8),
Immediate(u32),
}
/// Operations decoded independently by the reference interpreter.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Op {
Load {
data: u8,
index: u8,
resource: u8,
},
Store {
data: u8,
index: u8,
resource: u8,
},
WaitRead,
WaitWrite,
Move(u8, Source),
Add(u8, u8, u8),
ScalarMove(u8, Source),
CompareEqual(Source, Source),
Branch {
target: usize,
condition: BranchCondition,
},
Vector(VectorAlu, u8, u8, u8),
End,
}
/// Scalar condition tested by a forward branch.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BranchCondition {
/// Take the branch unconditionally.
Always,
/// Take the branch when SCC is clear.
SccZero,
/// Take the branch when the low half of VCC is clear.
VccZero,
/// Take the branch when the low half of EXEC is clear.
ExecZero,
}
/// VOP2 operations decoded by the reference interpreter.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VectorAlu {
ShiftLeft,
ShiftRight,
ArithmeticShiftRight,
And,
Or,
Xor,
FloatAdd,
FloatMultiply,
}
/// Execute original little-endian gfx1030 bytes with the synthetic binding ABI.
///
/// Each dispatched lane reads the corresponding input word and may write only
/// its own output word. Integer operations are exact modulo 2^32.
pub fn execute(code: &[u8], input: &[u32]) -> Result<Vec<u32>, ReferenceError> {
if input.is_empty() || input.len() > MAX_INPUT_WORDS {
return Err(error(0, "input word count outside reference limits"));
}
if code.len() > MAX_CODE_BYTES {
return Err(error(0, "instruction stream exceeds reference limit"));
}
let program = decode(code)?;
for instruction in &program {
match instruction.op {
Op::End if instruction.offset + instruction.byte_len != code.len() => {
return Err(error(
instruction.offset + instruction.byte_len,
"trailing code after s_endpgm",
));
}
Op::Load {
index, resource, ..
} if (index, resource) != (0, 0) => {
return Err(error(
instruction.offset,
"load outside synthetic binding ABI",
));
}
Op::Store {
index, resource, ..
} if (index, resource) != (0, 4) => {
return Err(error(
instruction.offset,
"store outside synthetic binding ABI",
));
}
_ => {}
}
}
if !program
.last()
.is_some_and(|instruction| instruction.op == Op::End)
{
return Err(error(code.len(), "missing s_endpgm"));
}
input
.iter()
.enumerate()
.map(|(index, &word)| execute_lane(&program, word, index % 32))
.collect()
}
fn error(offset: usize, detail: &'static str) -> ReferenceError {
ReferenceError { offset, detail }
}
/// An operation and its span in the original byte stream.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DecodedInstruction {
pub offset: usize,
pub byte_len: usize,
pub op: Op,
}
/// Decode the supported gfx1030 subset without applying the execution ABI.
///
/// AMD RDNA 2 ISA guide, Instruction Encoding. Identify the forms by bytes
/// and independently extract their variable fields.
///
/// # Errors
///
/// Returns the failing byte offset for an unsupported, truncated
/// or invalid instruction stream.
pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
let mut program = Vec::new();
let mut offset = 0;
while let Some(bytes) = code.get(offset..).filter(|bytes| !bytes.is_empty()) {
let (op, length) = match bytes {
[
0,
0x20,
opcode @ (0x30 | 0x70),
0xe0,
index,
data,
group @ 0..=25,
0x80,
..,
] => {
let (data, index, resource) = (*data, *index, *group * 4);
let op = if *opcode == 0x30 {
Op::Load {
data,
index,
resource,
}
} else {
Op::Store {
data,
index,
resource,
}
};
(op, 8)
}
[0x70, 0x3f, 0x8c, 0xbf, ..] => (Op::WaitRead, 4),
[0x00, 0x00, 0xfd, 0xbb, ..] => (Op::WaitWrite, 4),
[0x00, 0x00, 0x81, 0xbf, ..] => (Op::End, 4),
[
source,
3,
destination @ (0x80..=0xeb | 0xfe..=0xff),
0xbe,
tail @ ..,
] => {
let (source, length) = decode_scalar(*source, tail, offset)?;
(Op::ScalarMove(destination & 0x7f, source), length)
}
[left, right, 6, 0xbf, tail @ ..] if (*left, *right) != (255, 255) => {
let (left, left_length) = decode_scalar(*left, tail, offset)?;
let (right, right_length) = decode_scalar(*right, tail, offset)?;
(Op::CompareEqual(left, right), left_length.max(right_length))
}
[lo, hi, opcode @ (0x82 | 0x84 | 0x86 | 0x88), 0xbf, ..] => {
let words = i16::from_le_bytes([*lo, *hi]);
let words = usize::try_from(words).map_err(|_| error(offset, "backward branch"))?;
(
Op::Branch {
target: offset + 4 + words * 4,
condition: match opcode {
0x84 => BranchCondition::SccZero,
0x86 => BranchCondition::VccZero,
0x88 => BranchCondition::ExecZero,
_ => BranchCondition::Always,
},
},
4,
)
}
[first, second, third, opcode, ..]
if matches!(
opcode & 0xfe,
0x06 | 0x10 | 0x2c | 0x30 | 0x34 | 0x36 | 0x38 | 0x3a
) && second & 1 != 0 =>
{
let kind = match opcode & 0xfe {
0x06 => VectorAlu::FloatAdd,
0x10 => VectorAlu::FloatMultiply,
0x34 => VectorAlu::ShiftLeft,
0x2c => VectorAlu::ShiftRight,
0x30 => VectorAlu::ArithmeticShiftRight,
0x36 => VectorAlu::And,
0x38 => VectorAlu::Or,
_ => VectorAlu::Xor,
};
let dst = (third >> 1) | ((opcode & 1) << 7);
let src1 = (second >> 1) | ((third & 1) << 7);
(Op::Vector(kind, dst, *first, src1), 4)
}
[dst, 0, 0x25, 0xd5, lo, middle, hi @ 2..=3, 0x02, ..] if middle & 1 == 1 => {
let src1 = (middle >> 1) | ((hi & 1) << 7);
(Op::Add(*dst, *lo, src1), 8)
}
[lo, packed, upper, tag @ 0x7e..=0x7f, tail @ ..]
if packed & 0xfe == 2 && upper & 1 == 0 =>
{
let dst = (upper >> 1) | ((tag & 1) << 7);
let selector = u16::from(*lo) | (u16::from(packed & 1) << 8);
let (src, length) = match selector {
128..=192 => (Source::Immediate(u32::from(selector - 128)), 4),
193..=208 => (
Source::Immediate(0_u32.wrapping_sub(u32::from(selector - 192))),
4,
),
242 => (Source::Immediate(1.0f32.to_bits()), 4),
255 => {
let literal = tail
.first_chunk::<4>()
.ok_or_else(|| error(offset, "truncated literal"))?;
(Source::Immediate(u32::from_le_bytes(*literal)), 8)
}
256..=511 => (Source::Register(*lo), 4),
_ => return Err(error(offset, "unsupported VOP1 source")),
};
(Op::Move(dst, src), length)
}
_ => {
return Err(error(
offset,
"unsupported or truncated gfx1030 instruction",
));
}
};
program.push(DecodedInstruction {
offset,
byte_len: length,
op,
});
offset += length;
}
for instruction in &program {
if let Op::Branch { target, .. } = instruction.op
&& program
.binary_search_by_key(&target, |item| item.offset)
.is_err()
{
return Err(error(
instruction.offset,
"branch target is not an instruction boundary",
));
}
}
Ok(program)
}
fn decode_scalar(
selector: u8,
tail: &[u8],
offset: usize,
) -> Result<(Source, usize), ReferenceError> {
match selector {
0..=105 => Ok((Source::Register(selector), 4)),
128..=192 => Ok((Source::Immediate(u32::from(selector - 128)), 4)),
193..=208 => Ok((
Source::Immediate(0u32.wrapping_sub(u32::from(selector - 192))),
4,
)),
255 => {
let literal = tail
.first_chunk::<4>()
.ok_or_else(|| error(offset, "truncated scalar literal"))?;
Ok((Source::Immediate(u32::from_le_bytes(*literal)), 8))
}
_ => Err(error(offset, "unsupported scalar source")),
}
}
fn vector_alu(op: VectorAlu, a: u32, b: u32, offset: usize) -> Result<u32, ReferenceError> {
let error = || {
error(
offset,
"float operation outside positive, normal, exact binary32 domain",
)
};
match op {
VectorAlu::ShiftLeft => return Ok(b << (a & 31)),
VectorAlu::ShiftRight => return Ok(b >> (a & 31)),
VectorAlu::ArithmeticShiftRight => return Ok(((b as i32) >> (a & 31)) as u32),
VectorAlu::And => return Ok(a & b),
VectorAlu::Or => return Ok(a | b),
VectorAlu::Xor => return Ok(a ^ b),
_ => {}
}
let (a, b) = (f32::from_bits(a), f32::from_bits(b));
if !a.is_normal() || !b.is_normal() || a.is_sign_negative() || b.is_sign_negative() {
return Err(error());
}
let (a, b) = (f64::from(a), f64::from(b));
let exact = match op {
VectorAlu::FloatAdd => {
let sum = a + b;
// Recover the smaller input to detect even a binary64 addition rounding.
if sum - a.max(b) != a.min(b) {
return Err(error());
}
sum
}
VectorAlu::FloatMultiply => a * b, // Two 24-bit significands fit in binary64.
VectorAlu::ShiftLeft
| VectorAlu::ShiftRight
| VectorAlu::ArithmeticShiftRight
| VectorAlu::And
| VectorAlu::Or
| VectorAlu::Xor => unreachable!(),
};
let result = exact as f32;
if !result.is_normal() || f64::from(result) != exact {
return Err(error());
}
Ok(result.to_bits())
}
fn execute_lane(
program: &[DecodedInstruction],
input: u32,
lane: usize,
) -> Result<u32, ReferenceError> {
let mut registers = [None; 256];
let mut scalars = [None; 128];
let mut exec = u32::MAX;
scalars[126] = Some(exec);
let mut scc = None;
let mut target = 0;
let mut pending_read = None;
let mut pending_write = None;
let mut output = None;
for &DecodedInstruction { offset, op, .. } in program {
if offset < target {
continue;
}
let read_scalar = |source| match source {
Source::Register(reg) => scalars[usize::from(reg)]
.ok_or_else(|| error(offset, "read from uninitialized SGPR")),
Source::Immediate(value) => Ok(value),
};
let read = |register: u8| {
if register == 0 {
return Err(error(offset, "v0 is reserved for the resource index"));
}
if pending_read == Some(register) {
return Err(error(offset, "VGPR read before load wait"));
}
registers[usize::from(register)]
.ok_or_else(|| error(offset, "read from uninitialized VGPR"))
};
if exec != u32::MAX {
match op {
Op::Move(dst, _) | Op::Add(dst, ..) | Op::Vector(_, dst, ..) => {
if exec != 0 && registers[usize::from(dst)].is_none() {
return Err(error(offset, "partial EXEC requires an initialized VGPR"));
}
if exec & (1 << lane) == 0 {
continue;
}
}
Op::Load { .. } | Op::Store { .. } => {
return Err(error(offset, "vector memory requires full Wave32 EXEC"));
}
_ => {}
}
}
let set = match op {
Op::Load { data: dst, .. } => {
if dst == 0 || pending_read.is_some() {
return Err(error(
offset,
"invalid load destination or overlapping load",
));
}
pending_read = Some(dst);
None
}
Op::Store { data: src, .. } => {
let value = read(src)?;
if pending_write.is_some() || output.is_some() {
return Err(error(offset, "multiple writes to the output"));
}
pending_write = Some(value);
None
}
Op::WaitRead => pending_read.take().map(|dst| (dst, input)),
Op::WaitWrite => {
if let Some(value) = pending_write.take() {
output = Some(value);
}
None
}
Op::Move(dst, Source::Register(src)) => Some((dst, read(src)?)),
Op::Move(dst, Source::Immediate(value)) => Some((dst, value)),
Op::Add(dst, lhs, rhs) => Some((dst, read(lhs)?.wrapping_add(read(rhs)?))),
Op::ScalarMove(dst, src) => {
if dst < 8 {
return Err(error(offset, "write to a reserved resource SGPR"));
}
let value = read_scalar(src)?;
if dst == 126 {
exec = value;
}
scalars[usize::from(dst)] = Some(value);
None
}
Op::CompareEqual(lhs, rhs) => {
scc = Some(read_scalar(lhs)? == read_scalar(rhs)?);
None
}
Op::Branch {
target: destination,
condition,
} => {
let take_branch = match condition {
BranchCondition::Always => true,
BranchCondition::SccZero => {
!scc.ok_or_else(|| error(offset, "branch with uninitialized SCC"))?
}
BranchCondition::VccZero => scalars[106] == Some(0),
BranchCondition::ExecZero => exec == 0,
};
if condition == BranchCondition::VccZero && scalars[106].is_none() {
return Err(error(offset, "branch with uninitialized VCC_LO"));
}
if take_branch {
target = destination;
}
None
}
Op::Vector(operator, dst, lhs, rhs) => {
Some((dst, vector_alu(operator, read(lhs)?, read(rhs)?, offset)?))
}
Op::End => {
if pending_read.is_some() || pending_write.is_some() {
return Err(error(offset, "outstanding transfer at termination"));
}
return output.ok_or_else(|| error(offset, "lane did not write its output"));
}
};
if let Some((dst, value)) = set {
if dst == 0 || pending_read == Some(dst) {
return Err(error(offset, "write to immutable or pending VGPR"));
}
registers[usize::from(dst)] = Some(value);
}
}
Err(error(0, "missing decoded termination"))
}
#[cfg(test)]
mod tests {
use super::*;
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
#[test]
fn computes_the_independent_known_answers() {
let input = [0, 1, u32::MAX, 0u32.wrapping_sub(0x1234_5678)];
let expected = [0x1234_5678, 0x1234_5679, 0x1234_5677, 0];
assert_eq!(execute(FIXTURE, &input), Ok(expected.to_vec()));
}
#[test]
fn executes_both_scalar_branch_outcomes() {
let fixture = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
let inputs = [0, u32::MAX, 0x1234_5678];
assert_eq!(
execute(fixture, &inputs),
Ok(vec![0x1234_5678, 0x12cb_5687, 0x1200_5600])
);
let mut equal = *fixture;
equal[17] = 0x87; // Compare s8 with 7, so the SCC-zero edge is not taken.
assert_eq!(execute(&equal, &inputs), Ok(vec![0; 3]));
}
#[test]
fn rejects_invalid_branch_even_when_not_taken() {
let fixture = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
let mut invalid = *fixture;
invalid[17] = 0x87;
invalid[20] = 3; // Target byte 36, the VOP1 literal.
assert_eq!(
execute(&invalid, &[0]).unwrap_err().detail,
"branch target is not an instruction boundary"
);
invalid[20..22].copy_from_slice(&(-1i16).to_le_bytes());
assert_eq!(
execute(&invalid, &[0]).unwrap_err().detail,
"backward branch"
);
}
#[test]
fn executes_exact_float_fixture_and_rejects_subnormal_operand() {
let fixture = include_bytes!("../../../fixtures/rdna2/float-exact.bin");
assert_eq!(
execute(fixture, &[0, u32::MAX]),
Ok(vec![0x410c_0000, 0x4120_0000])
);
let mut broken = *fixture;
broken[36..40].copy_from_slice(&1u32.to_le_bytes());
assert_eq!(
execute(&broken, &[0]).unwrap_err().detail,
"float operation outside positive, normal, exact binary32 domain"
);
}
#[test]
fn rejects_truncated_programs_and_trailing_bytes() {
for length in 0..FIXTURE.len() {
assert!(
execute(&FIXTURE[..length], &[0]).is_err(),
"length {length}"
);
}
let mut trailing = FIXTURE.to_vec();
trailing.push(0);
assert_eq!(execute(&trailing, &[0]).unwrap_err().offset, FIXTURE.len());
}
#[test]
fn rejects_access_before_wait() {
let mut no_read_wait = FIXTURE.to_vec();
no_read_wait.drain(8..12);
assert_eq!(
execute(&no_read_wait, &[1]).unwrap_err().detail,
"VGPR read before load wait"
);
let mut no_write_wait = FIXTURE.to_vec();
no_write_wait.drain(36..40);
assert_eq!(
execute(&no_write_wait, &[1]).unwrap_err().detail,
"outstanding transfer at termination"
);
}
#[test]
fn decodes_high_register_indices() {
// V_MOV_B32 v255, v254 and V_ADD_NC_U32 v255, v128, v255.
let code = [
0xfe, 0x03, 0xfe, 0x7f, 0xff, 0, 0x25, 0xd5, 0x80, 0xff, 0x03, 0x02, 0, 0, 0x81, 0xbf,
];
assert_eq!(
decode(&code),
Ok(vec![
DecodedInstruction {
offset: 0,
byte_len: 4,
op: Op::Move(255, Source::Register(254))
},
DecodedInstruction {
offset: 4,
byte_len: 8,
op: Op::Add(255, 128, 255)
},
DecodedInstruction {
offset: 12,
byte_len: 4,
op: Op::End
},
])
);
}
}
-479
View File
@@ -1,479 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent pure-Rust CPU reference for deterministic RGBA8 2D texture sampling.
//!
//! # Coordinate Mapping and Filtering
//!
//! Sampling operates on normalized `(u, v)` coordinates using nearest-neighbor filtering
//! and clamp-to-edge addressing:
//!
//! 1. Non-finite coordinates (`NaN`, `+Inf`, `-Inf`) are rejected with [`SamplingError::NonFiniteCoordinates`].
//! 2. Coordinates are clamped to the unit interval:
//! `u_clamped = u.clamp(0.0, 1.0)`
//! `v_clamped = v.clamp(0.0, 1.0)`
//! 3. For a mip level with dimensions `(W, H)`:
//! `x = min(floor(u_clamped * W), W - 1)`
//! `y = min(floor(v_clamped * H), H - 1)`
//! At exact texel boundaries where `u * W` is an integer, standard IEEE 754 `floor`
//! deterministically assigns the boundary to the right/lower texel (for example, with `W = 2`,
//! `u = 0.5` maps to `x = 1`), while `u = 1.0` maps to `x = 1` via edge clamping.
use std::fmt;
/// Bytes per RGBA8 texel.
pub const RGBA8_TEXEL_BYTES: usize = 4;
/// Errors produced during CPU texture sampling reference execution.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SamplingError {
/// Texture width or height is zero or exceeds limits.
InvalidDimensions,
/// Mip count is zero or exceeds maximum possible for dimensions.
InvalidMipCount,
/// Specified mip level index is out of bounds.
MipOutOfBounds,
/// Row pitch is smaller than tight row bytes (`width * 4`) or unaligned.
InvalidRowPitch,
/// Buffer offset causes an overflow or unaligned read.
InvalidOffset,
/// Underlying data buffer is smaller than required by descriptor layout.
BufferTooSmall,
/// Input coordinates contained NaN or infinity.
NonFiniteCoordinates,
}
impl fmt::Display for SamplingError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidDimensions => write!(f, "invalid texture dimensions"),
Self::InvalidMipCount => write!(f, "invalid mip count"),
Self::MipOutOfBounds => write!(f, "selected mip index is out of bounds"),
Self::InvalidRowPitch => write!(f, "invalid row pitch for mip level"),
Self::InvalidOffset => write!(f, "invalid buffer offset"),
Self::BufferTooSmall => write!(f, "buffer is too small for texture layout"),
Self::NonFiniteCoordinates => write!(f, "non-finite texture coordinates"),
}
}
}
impl std::error::Error for SamplingError {}
/// Mip-level layout specification for 2D RGBA8 sampling.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MipLayout {
pub width: usize,
pub height: usize,
pub offset: usize,
pub row_pitch: usize,
}
/// Description of a 2D RGBA8 texture with an explicit mip chain.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Rgba8TextureDesc {
pub width: usize,
pub height: usize,
pub mips: u32,
pub mip_layouts: Vec<MipLayout>,
}
impl Rgba8TextureDesc {
/// Create a descriptor with tightly packed row-major mip levels consecutively arranged.
pub fn new_packed(width: usize, height: usize, mips: u32) -> Result<Self, SamplingError> {
let max_mips = max_mip_levels(width, height)?;
if mips == 0 || mips > max_mips {
return Err(SamplingError::InvalidMipCount);
}
let mut mip_layouts = Vec::with_capacity(mips as usize);
let mut current_offset = 0usize;
for mip in 0..mips {
let mip_w = (width >> mip).max(1);
let mip_h = (height >> mip).max(1);
let row_pitch = mip_w
.checked_mul(RGBA8_TEXEL_BYTES)
.ok_or(SamplingError::InvalidDimensions)?;
let level_bytes = row_pitch
.checked_mul(mip_h)
.ok_or(SamplingError::InvalidDimensions)?;
mip_layouts.push(MipLayout {
width: mip_w,
height: mip_h,
offset: current_offset,
row_pitch,
});
current_offset = current_offset
.checked_add(level_bytes)
.ok_or(SamplingError::InvalidDimensions)?;
}
Ok(Self {
width,
height,
mips,
mip_layouts,
})
}
/// Validates internal consistency and returns the total required byte size.
pub fn required_size(&self) -> Result<usize, SamplingError> {
let max_mips = max_mip_levels(self.width, self.height)?;
if self.mips == 0 || self.mips > max_mips || self.mip_layouts.len() != self.mips as usize {
return Err(SamplingError::InvalidMipCount);
}
let mut total_end = 0usize;
for (i, layout) in self.mip_layouts.iter().enumerate() {
let expected_w = (self.width >> i).max(1);
let expected_h = (self.height >> i).max(1);
if layout.width != expected_w || layout.height != expected_h {
return Err(SamplingError::InvalidDimensions);
}
let tight_pitch = layout
.width
.checked_mul(RGBA8_TEXEL_BYTES)
.ok_or(SamplingError::InvalidDimensions)?;
if layout.row_pitch < tight_pitch {
return Err(SamplingError::InvalidRowPitch);
}
let level_size = layout
.row_pitch
.checked_mul(layout.height)
.ok_or(SamplingError::InvalidDimensions)?;
let level_end = layout
.offset
.checked_add(level_size)
.ok_or(SamplingError::InvalidOffset)?;
total_end = total_end.max(level_end);
}
Ok(total_end)
}
}
/// Calculate maximum allowable mip levels for a given width and height.
///
/// For arbitrary positive dimensions, the maximum mip count is:
/// `floor(log2(max(width, height))) + 1`
pub fn max_mip_levels(width: usize, height: usize) -> Result<u32, SamplingError> {
if width == 0 || height == 0 {
return Err(SamplingError::InvalidDimensions);
}
let max_dim = width.max(height);
let levels = usize::BITS - max_dim.leading_zeros();
Ok(levels)
}
/// Sample an RGBA8 texel deterministically from raw texture bytes using nearest-neighbor
/// filtering, clamp-to-edge addressing and explicit mip selection.
pub fn sample_rgba8_2d(
data: &[u8],
desc: &Rgba8TextureDesc,
mip: u32,
u: f32,
v: f32,
) -> Result<[u8; 4], SamplingError> {
if !u.is_finite() || !v.is_finite() {
return Err(SamplingError::NonFiniteCoordinates);
}
let required = desc.required_size()?;
if data.len() < required {
return Err(SamplingError::BufferTooSmall);
}
if mip >= desc.mips {
return Err(SamplingError::MipOutOfBounds);
}
let layout = desc
.mip_layouts
.get(mip as usize)
.ok_or(SamplingError::MipOutOfBounds)?;
// Clamp to edge [0.0, 1.0]
let u_clamped = u.clamp(0.0, 1.0);
let v_clamped = v.clamp(0.0, 1.0);
// Nearest-neighbor discrete texel coordinates:
// floor(coord * dim) clamped to [0, dim - 1]
let tex_x = ((u_clamped as f64 * layout.width as f64).floor() as usize).min(layout.width - 1);
let tex_y = ((v_clamped as f64 * layout.height as f64).floor() as usize).min(layout.height - 1);
let row_start = layout
.offset
.checked_add(
tex_y
.checked_mul(layout.row_pitch)
.ok_or(SamplingError::InvalidOffset)?,
)
.ok_or(SamplingError::InvalidOffset)?;
let texel_offset = row_start
.checked_add(
tex_x
.checked_mul(RGBA8_TEXEL_BYTES)
.ok_or(SamplingError::InvalidOffset)?,
)
.ok_or(SamplingError::InvalidOffset)?;
let bytes = data
.get(texel_offset..texel_offset + RGBA8_TEXEL_BYTES)
.ok_or(SamplingError::BufferTooSmall)?;
Ok([bytes[0], bytes[1], bytes[2], bytes[3]])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_four_distinct_texels_in_2x2() {
// 2x2 RGBA8 image:
// Top-left: [255, 0, 0, 255] (Red)
// Top-right: [0, 255, 0, 255] (Green)
// Bottom-left: [0, 0, 255, 255] (Blue)
// Bottom-right: [255, 255, 0, 255] (Yellow)
let pixels: [u8; 16] = [
255, 0, 0, 255, // (0, 0)
0, 255, 0, 255, // (1, 0)
0, 0, 255, 255, // (0, 1)
255, 255, 0, 255, // (1, 1)
];
let desc = Rgba8TextureDesc::new_packed(2, 2, 1).unwrap();
// Sample centers of each texel:
assert_eq!(
sample_rgba8_2d(&pixels, &desc, 0, 0.25, 0.25).unwrap(),
[255, 0, 0, 255]
);
assert_eq!(
sample_rgba8_2d(&pixels, &desc, 0, 0.75, 0.25).unwrap(),
[0, 255, 0, 255]
);
assert_eq!(
sample_rgba8_2d(&pixels, &desc, 0, 0.25, 0.75).unwrap(),
[0, 0, 255, 255]
);
assert_eq!(
sample_rgba8_2d(&pixels, &desc, 0, 0.75, 0.75).unwrap(),
[255, 255, 0, 255]
);
}
#[test]
fn test_normalized_uv_sampling() {
let pixels: [u8; 16] = [
10, 10, 10, 255, // (0, 0)
20, 20, 20, 255, // (1, 0)
30, 30, 30, 255, // (0, 1)
40, 40, 40, 255, // (1, 1)
];
let desc = Rgba8TextureDesc::new_packed(2, 2, 1).unwrap();
// Within (0, 0) region [0.0, 0.5)
assert_eq!(
sample_rgba8_2d(&pixels, &desc, 0, 0.1, 0.1).unwrap(),
[10, 10, 10, 255]
);
// Within (1, 1) region [0.5, 1.0]
assert_eq!(
sample_rgba8_2d(&pixels, &desc, 0, 0.9, 0.9).unwrap(),
[40, 40, 40, 255]
);
}
#[test]
fn test_clamp_to_edge() {
let pixels: [u8; 16] = [
1, 1, 1, 255, 2, 2, 2, 255, // row 0
3, 3, 3, 255, 4, 4, 4, 255, // row 1
];
let desc = Rgba8TextureDesc::new_packed(2, 2, 1).unwrap();
// Negative coordinates clamp to 0.0 -> (0, 0)
assert_eq!(
sample_rgba8_2d(&pixels, &desc, 0, -5.0, -10.0).unwrap(),
[1, 1, 1, 255]
);
// Coordinates > 1.0 clamp to 1.0 -> (1, 1)
assert_eq!(
sample_rgba8_2d(&pixels, &desc, 0, 10.0, 50.0).unwrap(),
[4, 4, 4, 255]
);
// Mixed clamping
assert_eq!(
sample_rgba8_2d(&pixels, &desc, 0, -1.0, 2.0).unwrap(),
[3, 3, 3, 255]
);
}
#[test]
fn test_boundary_coordinates() {
let pixels: [u8; 16] = [
11, 11, 11, 255, 22, 22, 22, 255, 33, 33, 33, 255, 44, 44, 44, 255,
];
let desc = Rgba8TextureDesc::new_packed(2, 2, 1).unwrap();
// Exactly 0.0 -> texel 0
assert_eq!(
sample_rgba8_2d(&pixels, &desc, 0, 0.0, 0.0).unwrap(),
[11, 11, 11, 255]
);
// Exactly 0.5 -> 0.5 * 2 = 1.0 -> texel 1
assert_eq!(
sample_rgba8_2d(&pixels, &desc, 0, 0.5, 0.0).unwrap(),
[22, 22, 22, 255]
);
assert_eq!(
sample_rgba8_2d(&pixels, &desc, 0, 0.0, 0.5).unwrap(),
[33, 33, 33, 255]
);
// Exactly 1.0 -> clamped to texel 1
assert_eq!(
sample_rgba8_2d(&pixels, &desc, 0, 1.0, 1.0).unwrap(),
[44, 44, 44, 255]
);
}
#[test]
fn test_multiple_mip_levels() {
// Mip 0: 2x2 (16 bytes), Mip 1: 1x1 (4 bytes)
let mut data = vec![0u8; 20];
data[0..16].copy_from_slice(&[1, 0, 0, 255, 2, 0, 0, 255, 3, 0, 0, 255, 4, 0, 0, 255]);
data[16..20].copy_from_slice(&[99, 99, 99, 255]);
let desc = Rgba8TextureDesc::new_packed(2, 2, 2).unwrap();
assert_eq!(desc.mip_layouts.len(), 2);
assert_eq!(desc.mip_layouts[0].offset, 0);
assert_eq!(desc.mip_layouts[1].offset, 16);
// Mip 0 samples the 2x2 texels
assert_eq!(
sample_rgba8_2d(&data, &desc, 0, 0.75, 0.75).unwrap(),
[4, 0, 0, 255]
);
// Mip 1 samples the single 1x1 texel across all UVs
assert_eq!(
sample_rgba8_2d(&data, &desc, 1, 0.1, 0.1).unwrap(),
[99, 99, 99, 255]
);
assert_eq!(
sample_rgba8_2d(&data, &desc, 1, 0.9, 0.9).unwrap(),
[99, 99, 99, 255]
);
}
#[test]
fn test_invalid_dimensions() {
assert_eq!(
Rgba8TextureDesc::new_packed(0, 4, 1).unwrap_err(),
SamplingError::InvalidDimensions
);
assert_eq!(
Rgba8TextureDesc::new_packed(4, 0, 1).unwrap_err(),
SamplingError::InvalidDimensions
);
assert_eq!(
Rgba8TextureDesc::new_packed(4, 4, 0).unwrap_err(),
SamplingError::InvalidMipCount
);
// 4x4 has at most 3 mips (4x4, 2x2, 1x1)
assert_eq!(
Rgba8TextureDesc::new_packed(4, 4, 4).unwrap_err(),
SamplingError::InvalidMipCount
);
}
#[test]
fn test_non_power_of_two_max_mips() {
// For 3x3, max(3, 3) = 3. floor(log2(3)) + 1 = 1 + 1 = 2 mips (3x3 and 1x1).
assert_eq!(max_mip_levels(3, 3).unwrap(), 2);
// Valid 2-mip descriptor
let desc = Rgba8TextureDesc::new_packed(3, 3, 2).unwrap();
assert_eq!(desc.mip_layouts.len(), 2);
assert_eq!(desc.mip_layouts[0].width, 3);
assert_eq!(desc.mip_layouts[0].height, 3);
assert_eq!(desc.mip_layouts[1].width, 1);
assert_eq!(desc.mip_layouts[1].height, 1);
// 3 mips is invalid for 3x3
assert_eq!(
Rgba8TextureDesc::new_packed(3, 3, 3).unwrap_err(),
SamplingError::InvalidMipCount
);
}
#[test]
fn test_invalid_pitches() {
let desc = Rgba8TextureDesc {
width: 4,
height: 4,
mips: 1,
mip_layouts: vec![MipLayout {
width: 4,
height: 4,
offset: 0,
row_pitch: 12, // Tight pitch is 4 * 4 = 16, so 12 is invalid!
}],
};
let dummy = vec![0u8; 64];
assert_eq!(
sample_rgba8_2d(&dummy, &desc, 0, 0.5, 0.5).unwrap_err(),
SamplingError::InvalidRowPitch
);
}
#[test]
fn test_truncated_data() {
let desc = Rgba8TextureDesc::new_packed(2, 2, 1).unwrap();
// 2x2 requires 16 bytes; provide only 15
let short_data = vec![0u8; 15];
assert_eq!(
sample_rgba8_2d(&short_data, &desc, 0, 0.0, 0.0).unwrap_err(),
SamplingError::BufferTooSmall
);
}
#[test]
fn test_invalid_mip_indices() {
let data = vec![0u8; 16];
let desc = Rgba8TextureDesc::new_packed(2, 2, 1).unwrap();
assert_eq!(
sample_rgba8_2d(&data, &desc, 1, 0.0, 0.0).unwrap_err(),
SamplingError::MipOutOfBounds
);
assert_eq!(
sample_rgba8_2d(&data, &desc, 5, 0.0, 0.0).unwrap_err(),
SamplingError::MipOutOfBounds
);
}
#[test]
fn test_non_finite_coordinates() {
let data = vec![0u8; 16];
let desc = Rgba8TextureDesc::new_packed(2, 2, 1).unwrap();
assert_eq!(
sample_rgba8_2d(&data, &desc, 0, f32::NAN, 0.0).unwrap_err(),
SamplingError::NonFiniteCoordinates
);
assert_eq!(
sample_rgba8_2d(&data, &desc, 0, 0.0, f32::NAN).unwrap_err(),
SamplingError::NonFiniteCoordinates
);
assert_eq!(
sample_rgba8_2d(&data, &desc, 0, f32::INFINITY, 0.5).unwrap_err(),
SamplingError::NonFiniteCoordinates
);
assert_eq!(
sample_rgba8_2d(&data, &desc, 0, 0.5, f32::NEG_INFINITY).unwrap_err(),
SamplingError::NonFiniteCoordinates
);
}
}
-186
View File
@@ -1,186 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_ref::{DecodedInstruction, Op, ReferenceError, Source, VectorAlu, decode, execute};
const ADD: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
const WAIT_READ: [u8; 4] = [0x70, 0x3f, 0x8c, 0xbf];
fn bytes(words: &[u32]) -> Vec<u8> {
words.iter().flat_map(|word| word.to_le_bytes()).collect()
}
#[test]
fn decodes_high_vop2_operands_and_integer_immediates() {
// AMD RDNA 2 ISA §13: VOP2 packs its second input and destination
// across byte boundaries. Selectors 195 and 208 encode -3 and -16.
// The original assembly operands were checked with gfx1030 llvm-mc.
let code = bytes(&[
0x37ff_fd81, // v_and_b32_e32 v255, v129, v254
0x7e04_02c3, // v_mov_b32_e32 v2, -3
0xbe88_03d0, // s_mov_b32 s8, -16
0xbf06_ff08,
0x1234_5678, // s_cmp_eq_u32 s8, 0x12345678
]);
assert_eq!(
decode(&code),
Ok(vec![
DecodedInstruction {
offset: 0,
byte_len: 4,
op: Op::Vector(VectorAlu::And, 255, 129, 254),
},
DecodedInstruction {
offset: 4,
byte_len: 4,
op: Op::Move(2, Source::Immediate(0xffff_fffd)),
},
DecodedInstruction {
offset: 8,
byte_len: 4,
op: Op::ScalarMove(8, Source::Immediate(0xffff_fff0)),
},
DecodedInstruction {
offset: 12,
byte_len: 8,
op: Op::CompareEqual(Source::Register(8), Source::Immediate(0x1234_5678)),
},
])
);
}
#[test]
fn enforces_inclusive_input_and_code_limits() {
let input_limit_error = ReferenceError {
offset: 0,
detail: "input word count outside reference limits",
};
assert_eq!(execute(ADD, &[]), Err(input_limit_error));
assert_eq!(execute(ADD, &[1; 4096]), Ok(vec![0x1234_5679; 4096]));
assert_eq!(
execute(ADD, &[1; 4097]),
Err(ReferenceError {
offset: 0,
detail: "input word count outside reference limits",
})
);
let padding_words = (1024 - ADD.len()) / WAIT_READ.len();
let padded = [WAIT_READ.repeat(padding_words), ADD.to_vec()].concat();
assert_eq!(padded.len(), 1024);
assert_eq!(execute(&padded, &[1]), Ok(vec![0x1234_5679]));
let oversized = [WAIT_READ.as_slice(), &padded].concat();
assert_eq!(
execute(&oversized, &[1]),
Err(ReferenceError {
offset: 0,
detail: "instruction stream exceeds reference limit",
})
);
}
#[test]
fn rejects_valid_instruction_words_after_end_and_reports_their_offset() {
let end = &ADD[ADD.len() - 4..];
let code = [ADD, &WAIT_READ, end].concat();
let error = execute(&code, &[1]).unwrap_err();
assert_eq!(
error,
ReferenceError {
offset: ADD.len(),
detail: "trailing code after s_endpgm",
}
);
assert_eq!(
error.to_string(),
"reference byte 0x2c: trailing code after s_endpgm"
);
}
#[test]
fn preserves_the_index_register_and_rejects_overlapping_loads() {
let mut writes_index = ADD.to_vec();
writes_index[5] = 0; // Load into v0, the fixture ABI's index register.
assert_eq!(
execute(&writes_index, &[1]),
Err(ReferenceError {
offset: 0,
detail: "invalid load destination or overlapping load",
})
);
let mut second_load = ADD[..8].to_vec();
second_load[5] = 2; // Distinct destination, still before the first load wait.
let overlaps = [&ADD[..8], &second_load, &ADD[8..]].concat();
assert_eq!(
execute(&overlaps, &[1]),
Err(ReferenceError {
offset: 8,
detail: "invalid load destination or overlapping load",
})
);
}
#[test]
fn rejects_a_second_output_store_before_and_after_the_wait() {
let store = &ADD[28..36];
for offset in [36, 40] {
let code = [&ADD[..offset], store, &ADD[offset..]].concat();
assert_eq!(
execute(&code, &[1]),
Err(ReferenceError {
offset,
detail: "multiple writes to the output",
})
);
}
}
#[test]
fn protects_descriptor_sgprs_but_allows_ordinary_sgprs() {
let code = |dst_word: u32| [dst_word.to_le_bytes().as_slice(), ADD].concat();
assert_eq!(
execute(&code(0xbe87_0381), &[1]), // s_mov_b32 s7, 1
Err(ReferenceError {
offset: 0,
detail: "write to a reserved resource SGPR",
})
);
assert_eq!(
execute(&code(0xbe89_0381), &[1]), // s_mov_b32 s9, 1
Ok(vec![0x1234_5679])
);
}
#[test]
fn rejects_either_out_of_domain_operand_even_if_the_product_is_normal() {
fn multiply(a: u32, b: u32) -> Result<Vec<u32>, ReferenceError> {
let code = bytes(&[
0x7e04_02ff,
a, // v_mov_b32_e32 v2, <literal>
0x7e06_02ff,
b, // v_mov_b32_e32 v3, <literal>
0x1002_0702, // v_mul_f32_e32 v1, v2, v3
]);
execute(&[code.as_slice(), &ADD[28..]].concat(), &[0])
}
let one = 1.0f32.to_bits();
let large_normal = 0x7e80_0000; // 2^126.
let subnormal = 0x0000_0001; // 2^-149, yielding exact 2^-23 with large_normal.
let negative_one = (-1.0f32).to_bits();
assert_eq!(multiply(large_normal, one), Ok(vec![large_normal]));
for (a, b) in [
(subnormal, large_normal),
(large_normal, subnormal),
(negative_one, one),
(one, negative_one),
] {
assert_eq!(
multiply(a, b),
Err(ReferenceError {
offset: 16,
detail: "float operation outside positive, normal, exact binary32 domain",
})
);
}
}
-340
View File
@@ -1,340 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use std::fmt::Write;
use xenora_decoder::{
DecodedInstruction, ExportTarget, Instruction, InterpolationPhase, VectorSource,
};
use super::{Architecture, Binary, CompileError, CompiledShader, Value, decode_fixture};
/// Entry point of the translated vertex stage.
pub const VERTEX_ENTRY_POINT: &str = "xenora_vertex";
/// Entry point of the translated pixel stage.
pub const PIXEL_ENTRY_POINT: &str = "xenora_pixel";
#[derive(Clone, Copy, PartialEq, Eq)]
enum Stage {
Vertex,
Pixel,
}
impl Stage {
fn name(self) -> &'static str {
match self {
Self::Vertex => "vertex",
Self::Pixel => "pixel",
}
}
}
#[derive(Clone, Copy)]
enum Float4Input {
Position,
Color,
}
#[derive(Clone, Copy)]
enum Op {
VertexInput(Float4Input, u8),
Constant(u32),
Interpolate(u8),
Binary(Binary, Value, Value),
}
struct Export {
offset: usize,
values: [Value; 4],
}
#[derive(Default)]
struct StageIr {
values: Vec<(Option<usize>, Op)>,
position: Option<Export>,
parameter: Option<Export>,
color: Option<Export>,
}
impl StageIr {
fn push(&mut self, offset: Option<usize>, op: Op) -> Value {
let value = Value(self.values.len());
self.values.push((offset, op));
value
}
}
/// Compiles a linked synthetic gfx1030 pipeline with one RGBA8 color attachment.
///
/// Vertex VGPRs 0–3 receive one clip-space position from buffer 0 and VGPRs 4–7
/// receive one color from buffer 1. Each buffer contains one float4 per
/// vertex. Pixel VGPRs 0 and 1 are reserved for the I and J barycentric
/// coordinates. Adjacent interpolation pairs for PARAM0 lower to Metal's
/// center-perspective interpolation under this ABI. Vertex FP32 addition and
/// multiplication use separate operations and require the backend's safe and
/// precise Metal math modes.
pub fn compile_graphics(
architecture: Architecture,
vertex: &[u8],
pixel: &[u8],
) -> Result<CompiledShader, CompileError> {
let compile_stage = |stage: Stage, bytes: &[u8]| {
let result = decode_fixture(architecture, bytes).and_then(|decoded| {
let lifted = lift(stage, &decoded, bytes.len())?;
Ok((decoded, lifted))
});
result.map_err(|error| CompileError::GraphicsStage {
stage: stage.name(),
error: Box::new(error),
})
};
let (vertex_decoded, vertex) = compile_stage(Stage::Vertex, vertex)?;
let (pixel_decoded, pixel) = compile_stage(Stage::Pixel, pixel)?;
let position = vertex.position.as_ref().ok_or(CompileError::GraphicsLink {
reason: "vertex stage requires a POS0 export",
})?;
let color = pixel.color.as_ref().ok_or(CompileError::GraphicsLink {
reason: "pixel stage requires an MRT0 export",
})?;
let parameter = vertex.parameter.as_ref();
let interpolates = pixel
.values
.iter()
.any(|(_, op)| matches!(op, Op::Interpolate(_)));
if parameter.is_some() != interpolates {
return Err(CompileError::GraphicsLink {
reason: "vertex PARAM0 export and pixel attr0 interpolation must both be present or absent",
});
}
let mut disassembly = String::new();
for (name, instructions) in [("vertex", vertex_decoded), ("pixel", pixel_decoded)] {
let _ = writeln!(disassembly, "{name}:");
for instruction in instructions {
let _ = writeln!(disassembly, "{instruction}");
}
}
let mut ir = String::from("vertex:\n");
let mut msl = String::from(
"#include <metal_stdlib>\nusing namespace metal;\n\n\
struct VertexOutput {\n float4 position [[position]];\n",
);
if parameter.is_some() {
msl.push_str(" float4 parameter [[user(locn0), center_perspective]];\n");
}
let _ = write!(
msl,
"}};\n\nvertex VertexOutput {VERTEX_ENTRY_POINT}(\n uint vertex_id [[vertex_id]],\n device const float4* positions [[buffer(0)]],\n device const float4* colors [[buffer(1)]]) {{\n"
);
emit_values(&vertex, &mut ir, &mut msl);
msl.push_str(" VertexOutput output;\n");
emit_export(position, "pos0", "output.position", &mut ir, &mut msl);
if let Some(parameter) = parameter {
emit_export(parameter, "param0", "output.parameter", &mut ir, &mut msl);
}
msl.push_str(
" return output;\n}\n\nstruct PixelOutput {\n float4 color [[color(0)]];\n};\n\n",
);
let parameter = if interpolates {
"VertexOutput input [[stage_in]]"
} else {
""
};
let _ = write!(
msl,
"fragment PixelOutput {PIXEL_ENTRY_POINT}({parameter}) {{\n PixelOutput output;\n"
);
ir.push_str("pixel:\n");
emit_values(&pixel, &mut ir, &mut msl);
emit_export(color, "mrt0", "output.color", &mut ir, &mut msl);
msl.push_str(" return output;\n}\n");
Ok(CompiledShader {
disassembly,
ir,
msl,
})
}
fn lift(
stage: Stage,
decoded: &[DecodedInstruction],
length: usize,
) -> Result<StageIr, CompileError> {
let mut ir = StageIr::default();
let mut registers = [None; 256];
if stage == Stage::Vertex {
let (positions, remaining) = registers.split_at_mut(4);
for (slots, input) in [
(positions, Float4Input::Position),
(&mut remaining[..4], Float4Input::Color),
] {
for (component, register) in slots.iter_mut().enumerate() {
*register = Some(ir.push(None, Op::VertexInput(input, component as u8)));
}
}
}
let mut instructions = decoded.iter();
let mut exporting = false;
while let Some(&DecodedInstruction {
instruction,
offset,
..
}) = instructions.next()
{
let error = |reason| CompileError::Verify { offset, reason };
let read = |register: u8| {
registers[usize::from(register)]
.ok_or_else(|| error("source VGPR is uninitialized or reserved"))
};
match instruction {
Instruction::MoveB32 { dst, src } if !exporting => {
if stage == Stage::Pixel && dst < 2 {
return Err(error("pixel VGPRs 0 and 1 are reserved for interpolation"));
}
let value = match src {
VectorSource::Register(register) => read(register)?,
VectorSource::Immediate(bits) if f32::from_bits(bits).is_finite() => {
ir.push(Some(offset), Op::Constant(bits))
}
VectorSource::Immediate(_) => {
return Err(error("graphics move requires finite FP32 bits"));
}
};
registers[usize::from(dst)] = Some(value);
}
Instruction::VectorAddF32 { dst, src0, src1 }
| Instruction::VectorMulF32 { dst, src0, src1 }
if stage == Stage::Vertex && !exporting =>
{
let operator = match instruction {
Instruction::VectorAddF32 { .. } => Binary::FloatAdd,
_ => Binary::FloatMul,
};
let value = ir.push(Some(offset), Op::Binary(operator, read(src0)?, read(src1)?));
registers[usize::from(dst)] = Some(value);
}
Instruction::Interpolate {
phase: InterpolationPhase::First,
dst,
coordinate: 0,
attribute: 0,
component,
} if stage == Stage::Pixel && dst >= 2 && !exporting => {
// Accept only an adjacent, matching pair. The intermediate
// interpolation result is never observable independently.
let expected = Instruction::Interpolate {
phase: InterpolationPhase::Second,
dst,
coordinate: 1,
attribute: 0,
component,
};
let second = instructions
.next()
.ok_or_else(|| error("missing matching second interpolation phase"))?;
if second.instruction != expected {
return Err(CompileError::Verify {
offset: second.offset,
reason: "expected matching second interpolation phase",
});
}
registers[usize::from(dst)] =
Some(ir.push(Some(offset), Op::Interpolate(component)));
}
Instruction::Export {
target,
sources: [a, b, c, d],
} => {
let slot = match (stage, target) {
(Stage::Vertex, ExportTarget::Position0) => &mut ir.position,
(Stage::Vertex, ExportTarget::Parameter0) => &mut ir.parameter,
(Stage::Pixel, ExportTarget::RenderTarget0) => &mut ir.color,
_ => return Err(error("export target is invalid for this stage")),
};
if slot.is_some() {
return Err(error("export target is written more than once"));
}
*slot = Some(Export {
offset,
values: [read(a)?, read(b)?, read(c)?, read(d)?],
});
exporting = true;
}
Instruction::EndProgram => {
if let Some(next) = instructions.next() {
return Err(CompileError::Verify {
offset: next.offset,
reason: "instruction follows program termination",
});
}
return Ok(ir);
}
_ => {
return Err(error(
"instruction is unsupported at this point in the graphics stage",
));
}
}
}
Err(CompileError::Verify {
offset: length,
reason: "missing program termination",
})
}
fn emit_values(stage: &StageIr, ir: &mut String, msl: &mut String) {
if stage
.values
.iter()
.any(|(_, op)| matches!(op, Op::Binary(..)))
{
msl.push_str(" #pragma clang fp contract(off)\n #pragma clang fp reassociate(off)\n");
}
for (index, &(offset, op)) in stage.values.iter().enumerate() {
let value = Value(index);
let (operation, expression) = match op {
Op::VertexInput(input, component) => {
let buffer = match input {
Float4Input::Position => "positions",
Float4Input::Color => "colors",
};
(
format!("load.vertex.f32 {buffer}[{component}]"),
format!("{buffer}[vertex_id][{component}]"),
)
}
Op::Constant(bits) => (
format!("const.f32 0x{bits:08x}"),
format!("as_type<float>(0x{bits:08x}u)"),
),
Op::Binary(operator, left, right) => {
let (mnemonic, symbol) = operator.operator();
(
format!("{mnemonic} {left}, {right}"),
format!("{left} {symbol} {right}"),
)
}
Op::Interpolate(component) => (
format!("interpolate.center_perspective.f32 attr0[{component}]"),
format!("input.parameter[{component}]"),
),
};
if let Some(offset) = offset {
let _ = write!(ir, "{offset:04x}: ");
}
let _ = writeln!(ir, "{value} = {operation}");
let _ = writeln!(msl, " float {value} = {expression};");
}
}
fn emit_export(export: &Export, target: &str, field: &str, ir: &mut String, msl: &mut String) {
let [a, b, c, d] = export.values;
let offset = export.offset;
let _ = writeln!(
ir,
"{offset:04x}: export.f32x4 {target}, {a}, {b}, {c}, {d}"
);
let _ = writeln!(msl, " {field} = float4({a}, {b}, {c}, {d});");
}
-680
View File
@@ -1,680 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Verified compilation for Xenora's synthetic compute and graphics ABIs.
use std::fmt::{self, Write};
mod graphics;
pub use graphics::{PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
pub use xenora_decoder::Architecture;
use xenora_decoder::{DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorSource};
/// Entry point of all kernels produced by this compiler.
pub const ENTRY_POINT: &str = "xenora_compute";
const MAX_CODE_BYTES: usize = 1024;
#[derive(Debug)]
pub struct CompiledShader {
pub disassembly: String,
pub ir: String,
pub msl: String,
}
#[derive(Debug)]
pub enum CompileError {
InvalidLength {
bytes: usize,
},
Decode(DecodeError),
GraphicsStage {
stage: &'static str,
error: Box<CompileError>,
},
GraphicsLink {
reason: &'static str,
},
Verify {
offset: usize,
reason: &'static str,
},
}
impl fmt::Display for CompileError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidLength { bytes } => write!(
formatter,
"fixture length must be a nonzero multiple of four up to {MAX_CODE_BYTES} bytes, got {bytes}"
),
Self::Decode(error) => error.fmt(formatter),
Self::GraphicsStage { stage, error } => write!(formatter, "{stage} shader: {error}"),
Self::GraphicsLink { reason } => write!(formatter, "graphics linking: {reason}"),
Self::Verify { offset, reason } => {
write!(
formatter,
"shader verification at byte 0x{offset:x}: {reason}"
)
}
}
}
}
impl std::error::Error for CompileError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Decode(error) => Some(error),
Self::GraphicsStage { error, .. } => Some(error),
_ => None,
}
}
}
#[derive(Clone, Copy)]
struct Value(usize);
impl fmt::Display for Value {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "t{}", self.0)
}
}
#[derive(Clone, Copy)]
enum Op {
Load,
Constant(u32),
Binary(Binary, Value, Value),
MergeLanes {
mask: u32,
active: Value,
inactive: Value,
},
Store(Value),
ScalarBranch {
target: usize,
taken: bool,
},
}
#[derive(Clone, Copy)]
enum Binary {
Add,
ShiftLeft,
ShiftRight,
ArithmeticShiftRight,
And,
Or,
Xor,
FloatAdd,
FloatMul,
}
impl Binary {
fn operator(self) -> (&'static str, &'static str) {
match self {
Self::Add => ("add.u32", "+"),
Self::ShiftLeft => ("lshl.b32", "<<"),
Self::ShiftRight => ("lshr.b32", ">>"),
Self::ArithmeticShiftRight => ("ashr.i32", ">>"),
Self::And => ("and.b32", "&"),
Self::Or => ("or.b32", "|"),
Self::Xor => ("xor.b32", "^"),
Self::FloatAdd => ("add.f32", "+"),
Self::FloatMul => ("mul.f32", "*"),
}
}
}
// Each bit is either known zero, known one or unconstrained.
#[derive(Clone, Copy)]
struct KnownBits {
zero: u32,
one: u32,
values: Option<[u32; 2]>,
}
impl KnownBits {
const UNKNOWN: Self = Self {
zero: 0,
one: 0,
values: None,
};
fn constant(value: u32) -> Self {
Self {
zero: !value,
one: value,
values: Some([value; 2]),
}
}
fn and(self, other: Self) -> Self {
Self {
zero: self.zero | other.zero,
one: self.one & other.one,
values: None,
}
}
fn or(self, other: Self) -> Self {
Self {
zero: self.zero & other.zero,
one: self.one | other.one,
values: None,
}
}
fn xor(self, other: Self) -> Self {
Self {
zero: (self.zero & other.zero) | (self.one & other.one),
one: (self.zero & other.one) | (self.one & other.zero),
values: None,
}
}
fn positive_normal_candidates(self) -> Option<[f32; 2]> {
let values = match self.values {
Some(values) => values,
None => {
let unknown = !(self.zero | self.one);
if unknown.count_ones() > 1 {
return None;
}
[self.one, self.one | unknown]
}
};
let candidates = values.map(f32::from_bits);
candidates
.iter()
.all(|n| n.is_normal() && n.is_sign_positive())
.then_some(candidates)
}
}
fn exact_float_result(operator: Binary, left: KnownBits, right: KnownBits) -> Option<KnownBits> {
let left = left.positive_normal_candidates()?;
let right = right.positive_normal_candidates()?;
let mut zero = u32::MAX;
let mut one = u32::MAX;
let mut results = Vec::with_capacity(4);
for a in left.map(f64::from) {
for b in right.map(f64::from) {
let exact = match operator {
Binary::FloatAdd => a + b,
Binary::FloatMul => a * b,
_ => return None,
};
let value = exact as f32;
if !value.is_normal() || f64::from(value) != exact {
return None;
}
// Binary64 can round away the smaller operand of a widely separated
// binary32 sum. Require that subtraction recovers the smaller input.
if matches!(operator, Binary::FloatAdd) && exact - a.max(b) != a.min(b) {
return None;
}
let bits = value.to_bits();
zero &= !bits;
one &= bits;
if !results.contains(&bits) {
results.push(bits);
}
}
}
let values = match results.as_slice() {
[only] => Some([*only; 2]),
[first, second] => Some([*first, *second]),
_ => None,
};
Some(KnownBits { zero, one, values })
}
/// Compiles explicitly tagged raw machine code to a synthetic Metal compute kernel.
///
/// Bind equal-length disjoint input and output word buffers and dispatch one
/// invocation per word in a one-dimensional grid.
pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShader, CompileError> {
let decoded = decode_fixture(architecture, bytes)?;
let operations = lift(&decoded, bytes.len())?;
let disassembly = decoded.iter().map(|line| format!("{line}\n")).collect();
let mut ir = String::new();
let mut msl = format!(
"#include <metal_stdlib>\nusing namespace metal;\nkernel void {ENTRY_POINT}(\n device const uint* input [[buffer(0)]],\n device uint* output [[buffer(1)]],\n uint index [[thread_position_in_grid]]) {{\n"
);
if operations.iter().any(|(_, operation)| {
matches!(
operation,
Op::Binary(Binary::FloatAdd | Binary::FloatMul, _, _)
)
}) {
msl.push_str(" #pragma clang fp contract(off)\n #pragma clang fp reassociate(off)\n");
}
for (index, (offset, operation)) in operations.into_iter().enumerate() {
let dest = Value(index);
let (step, statement) = match operation {
Op::Load => (
format!("{dest} = load.u32 input[index]"),
format!("uint {dest} = input[index];"),
),
Op::Constant(value) => (
format!("{dest} = const.u32 0x{value:08x}"),
format!("uint {dest} = 0x{value:08x}u;"),
),
Op::Binary(operator, left, right) => {
let (mnemonic, symbol) = operator.operator();
let expression = match operator {
Binary::FloatAdd | Binary::FloatMul => format!(
"as_type<uint>(as_type<float>({left}) {symbol} as_type<float>({right}))"
),
Binary::ArithmeticShiftRight => {
format!("as_type<uint>(as_type<int>({left}) {symbol} ({right} & 31u))")
}
Binary::ShiftLeft | Binary::ShiftRight => {
format!("{left} {symbol} ({right} & 31u)")
}
_ => format!("{left} {symbol} {right}"),
};
(
format!("{dest} = {mnemonic} {left}, {right}"),
format!("uint {dest} = {expression};"),
)
}
Op::ScalarBranch { target, taken } => {
let _ = writeln!(
ir,
"{offset:04x}: branch.uniform 0x{target:04x} taken={taken}"
);
continue;
}
Op::MergeLanes {
mask,
active,
inactive,
} => (
format!("{dest} = merge.lanes mask=0x{mask:08x}, {active}, {inactive}"),
format!(
"uint {dest} = ((0x{mask:08x}u >> (index & 31u)) & 1u) != 0u ? {active} : {inactive};"
),
),
Op::Store(value) => (
format!("store.u32 output[index], {value}"),
format!("output[index] = {value};"),
),
};
// Writing to a String is infallible.
let _ = writeln!(ir, "{offset:04x}: {step}");
let _ = writeln!(msl, " {statement}");
}
msl.push_str("}\n");
Ok(CompiledShader {
disassembly,
ir,
msl,
})
}
fn decode_fixture(
architecture: Architecture,
bytes: &[u8],
) -> Result<Vec<DecodedInstruction>, CompileError> {
if bytes.is_empty() || bytes.len() > MAX_CODE_BYTES || !bytes.len().is_multiple_of(4) {
return Err(CompileError::InvalidLength { bytes: bytes.len() });
}
xenora_decoder::decode(architecture, bytes).map_err(CompileError::Decode)
}
fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, Op)>, CompileError> {
let mut operations = Vec::new();
let mut registers = [None; 256];
let mut facts = Vec::<KnownBits>::new();
let mut pending_load = None;
let mut stored = false;
let mut store_pending = false;
let mut scalars = [None; 128];
let mut exec = u32::MAX; // The fixture starts with full Wave32 EXEC.
scalars[126] = Some(exec);
let mut scc = None;
let mut skip_before = 0;
// Every decoded instruction must satisfy the fixture layout and binding
// contract, even when a known branch skips it.
for (index, instruction) in decoded.iter().enumerate() {
let offset = instruction.offset;
let reason = match instruction.instruction {
Instruction::Branch { target }
| Instruction::BranchSccZero { target }
| Instruction::BranchExecZero { target }
| Instruction::BranchVccZero { target }
if target <= offset
|| decoded
.binary_search_by_key(&target, |instruction| instruction.offset)
.is_err() =>
{
"branch target must be a forward instruction boundary"
}
Instruction::BufferLoadDword {
index, resource, ..
} if (index, resource) != (0, 0) => "unsupported resource or buffer index",
Instruction::BufferStoreDword {
index, resource, ..
} if (index, resource) != (0, 4) => "unsupported resource or buffer index",
Instruction::Export { .. } | Instruction::Interpolate { .. } => {
"graphics instruction is unsupported in a compute fixture"
}
Instruction::EndProgram if index + 1 != decoded.len() => {
return Err(CompileError::Verify {
offset: decoded[index + 1].offset,
reason: "instruction follows program termination",
});
}
_ => continue,
};
return Err(CompileError::Verify { offset, reason });
}
for instruction in decoded {
let offset = instruction.offset;
let error = |reason| CompileError::Verify { offset, reason };
let read = |register: u8| {
registers[usize::from(register)].ok_or_else(|| {
error("source register is uninitialized, pending a load wait, or reserved for indexing")
})
};
if offset < skip_before {
continue;
}
let read_scalar = |source| match source {
ScalarSource::Immediate(value) => Ok(value),
ScalarSource::Register(register) => scalars
.get(usize::from(register))
.copied()
.flatten()
.ok_or_else(|| error("scalar source has no known value")),
};
// Scalar instructions and waits still execute when all lanes are inactive.
if exec == 0 {
match instruction.instruction {
Instruction::MoveB32 { .. }
| Instruction::AddNoCarryU32 { .. }
| Instruction::VectorLshlrevB32 { .. }
| Instruction::VectorLshrrevB32 { .. }
| Instruction::VectorAshrrevI32 { .. }
| Instruction::VectorAndB32 { .. }
| Instruction::VectorOrB32 { .. }
| Instruction::VectorXorB32 { .. }
| Instruction::VectorAddF32 { .. }
| Instruction::VectorMulF32 { .. } => continue,
_ => {}
}
}
if exec != u32::MAX
&& matches!(
instruction.instruction,
Instruction::BufferLoadDword { .. } | Instruction::BufferStoreDword { .. }
)
{
return Err(error("vector memory requires full Wave32 EXEC"));
}
let next = Value(operations.len());
let (dest, operation) = match instruction.instruction {
Instruction::BufferLoadDword { data, .. } => {
let slot = usize::from(data);
if data == 0 || pending_load.is_some() {
return Err(error(
"load writes the index register or another load is outstanding",
));
}
registers[slot] = None;
pending_load = Some((slot, next));
(None, Op::Load)
}
Instruction::BufferStoreDword { data, .. } => {
if stored {
return Err(error("only one output store is supported"));
}
stored = true;
store_pending = true;
(None, Op::Store(read(data)?))
}
Instruction::WaitLoad => {
if let Some((register, value)) = pending_load.take() {
registers[register] = Some(value);
}
continue;
}
Instruction::WaitStore => {
store_pending = false;
continue;
}
Instruction::MoveB32 {
dst,
src: VectorSource::Register(src),
} => {
let value = read(src)?;
let slot = usize::from(dst);
if dst == 0 || pending_load.is_some_and(|(register, _)| register == slot) {
return Err(error(
"move writes the index register or replaces a pending load",
));
}
registers[slot] = Some(merge_lanes(
&mut operations,
&mut facts,
offset,
exec,
value,
registers[slot],
)?);
continue;
}
Instruction::MoveB32 {
dst,
src: VectorSource::Immediate(value),
} => (Some(dst), Op::Constant(value)),
Instruction::AddNoCarryU32 { dst, src0, src1 } => {
(Some(dst), Op::Binary(Binary::Add, read(src0)?, read(src1)?))
}
Instruction::VectorLshlrevB32 { dst, src0, src1 } => (
Some(dst),
Op::Binary(Binary::ShiftLeft, read(src1)?, read(src0)?),
),
Instruction::VectorAshrrevI32 { dst, src0, src1 } => (
Some(dst),
Op::Binary(Binary::ArithmeticShiftRight, read(src1)?, read(src0)?),
),
Instruction::VectorLshrrevB32 { dst, src0, src1 } => (
Some(dst),
Op::Binary(Binary::ShiftRight, read(src1)?, read(src0)?),
),
Instruction::VectorAndB32 { dst, src0, src1 } => {
(Some(dst), Op::Binary(Binary::And, read(src0)?, read(src1)?))
}
Instruction::VectorOrB32 { dst, src0, src1 } => {
(Some(dst), Op::Binary(Binary::Or, read(src0)?, read(src1)?))
}
Instruction::VectorXorB32 { dst, src0, src1 } => {
(Some(dst), Op::Binary(Binary::Xor, read(src0)?, read(src1)?))
}
Instruction::ScalarMoveB32 { dst, src } => {
let value = read_scalar(src)?;
if dst < 8 {
return Err(error("scalar move would modify a resource descriptor"));
}
if dst == 126 {
exec = value;
}
let slot = scalars
.get_mut(usize::from(dst))
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
*slot = Some(value);
continue;
}
Instruction::ScalarCompareEqU32 { src0, src1 } => {
scc = Some(read_scalar(src0)? == read_scalar(src1)?);
continue;
}
Instruction::BranchSccZero { target }
| Instruction::BranchExecZero { target }
| Instruction::BranchVccZero { target } => {
let taken = match instruction.instruction {
Instruction::BranchSccZero { .. } => {
!scc.ok_or_else(|| error("conditional branch reads uninitialized SCC"))?
}
Instruction::BranchVccZero { .. } => {
scalars[106]
.ok_or_else(|| error("conditional branch reads uninitialized VCC_LO"))?
== 0
}
_ => exec == 0,
};
if taken {
skip_before = target;
}
(None, Op::ScalarBranch { target, taken })
}
Instruction::Branch { target } => {
skip_before = target;
(
None,
Op::ScalarBranch {
target,
taken: true,
},
)
}
Instruction::VectorAddF32 { dst, src0, src1 } => (
Some(dst),
Op::Binary(Binary::FloatAdd, read(src0)?, read(src1)?),
),
Instruction::VectorMulF32 { dst, src0, src1 } => (
Some(dst),
Op::Binary(Binary::FloatMul, read(src0)?, read(src1)?),
),
Instruction::Export { .. } | Instruction::Interpolate { .. } => {
return Err(error(
"graphics instruction is unsupported in a compute fixture",
));
}
Instruction::EndProgram => {
if !stored || store_pending || pending_load.is_some() {
return Err(error(
"termination requires one completed store and no pending loads",
));
}
return Ok(operations);
}
};
let value_bits = match operation {
Op::Constant(bits) => KnownBits::constant(bits),
Op::Binary(Binary::And, left, right) => facts[left.0].and(facts[right.0]),
Op::Binary(Binary::Or, left, right) => facts[left.0].or(facts[right.0]),
Op::Binary(Binary::Xor, left, right) => facts[left.0].xor(facts[right.0]),
Op::Binary(operator @ (Binary::FloatAdd | Binary::FloatMul), left, right) => {
exact_float_result(operator, facts[left.0], facts[right.0])
.ok_or_else(|| error("FP32 operation is not proven exact for positive normal operands and results"))?
}
_ => KnownBits::UNKNOWN,
};
facts.push(value_bits);
operations.push((offset, operation));
if let Some(dest) = dest {
let slot = usize::from(dest);
if dest == 0 || pending_load.is_some_and(|(register, _)| register == slot) {
return Err(error(
"instruction writes the index register or replaces a pending load",
));
}
registers[slot] = Some(merge_lanes(
&mut operations,
&mut facts,
offset,
exec,
next,
registers[slot],
)?);
}
}
Err(CompileError::Verify {
offset: code_len,
reason: "missing program termination",
})
}
// Keeping a value for inactive lanes requires a previously initialized destination.
fn merge_lanes(
operations: &mut Vec<(usize, Op)>,
facts: &mut Vec<KnownBits>,
offset: usize,
mask: u32,
active: Value,
inactive: Option<Value>,
) -> Result<Value, CompileError> {
if mask == u32::MAX {
return Ok(active);
}
let inactive = inactive.ok_or(CompileError::Verify {
offset,
reason: "partial EXEC requires an initialized vector destination",
})?;
let next = Value(operations.len());
operations.push((
offset,
Op::MergeLanes {
mask,
active,
inactive,
},
));
facts.push(KnownBits {
zero: facts[active.0].zero & facts[inactive.0].zero,
one: facts[active.0].one & facts[inactive.0].one,
values: None,
});
Ok(next)
}
#[cfg(test)]
mod tests {
use super::{Binary, KnownBits, exact_float_result};
#[test]
fn propagates_known_bits_through_integer_operators() {
let left = KnownBits::constant(0b1100);
let right = KnownBits::constant(0b1010);
let and = left.and(right);
assert_eq!((and.zero, and.one), (!0b1000, 0b1000));
let xor = left.xor(right);
assert_eq!((xor.zero, xor.one), (!0b0110, 0b0110));
}
#[test]
fn rejects_unbounded_or_invalid_float_operands() {
let one = KnownBits::constant(1.0f32.to_bits());
let varying = KnownBits::UNKNOWN
.and(KnownBits::constant(0x0040_0000))
.xor(one);
assert_eq!(varying.positive_normal_candidates(), Some([1.0, 1.5]));
assert_eq!(one.and(one).positive_normal_candidates(), Some([1.0; 2]));
assert!(KnownBits::UNKNOWN.positive_normal_candidates().is_none());
for invalid in [0x8000_0000, 0xbf80_0000, 1, 0x7f80_0000] {
assert!(
KnownBits::constant(invalid)
.positive_normal_candidates()
.is_none()
);
}
}
#[test]
fn keeps_only_bits_shared_by_every_exact_result() {
let operand = KnownBits::UNKNOWN
.and(KnownBits::constant(0x0040_0000))
.xor(KnownBits::constant(1.0f32.to_bits()));
let sum = exact_float_result(Binary::FloatAdd, operand, operand).unwrap();
// The sums 2, 2.5 and 3 differ only in the two highest fraction bits.
assert_eq!(sum.zero, 0xbf9f_ffff);
assert_eq!(sum.one, 0x4000_0000);
assert!(sum.values.is_none());
}
}
-267
View File
@@ -1,267 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_shader::{Architecture, CompileError, compile};
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
#[test]
fn compiles_original_fixture() {
let result = compile(Architecture::Gfx1030, FIXTURE).unwrap();
assert_eq!(result.ir, include_str!("../../../fixtures/golden/add.ir"));
assert_eq!(
result.msl,
include_str!("../../../fixtures/golden/add.metal")
);
}
#[test]
fn load_wait_is_required_before_using_loaded_data() {
let mut code = FIXTURE.to_vec();
code.drain(8..12);
assert!(matches!(
compile(Architecture::Gfx1030, &code),
Err(CompileError::Verify { offset: 16, .. })
));
}
#[test]
fn store_wait_is_required_before_termination() {
let mut code = FIXTURE.to_vec();
code.drain(36..40);
assert!(matches!(
compile(Architecture::Gfx1030, &code),
Err(CompileError::Verify { offset: 36, .. })
));
}
#[test]
fn rejects_unaligned_length_before_decoding() {
assert!(matches!(
compile(Architecture::Gfx1030, &FIXTURE[..FIXTURE.len() - 1]),
Err(CompileError::InvalidLength { .. })
));
}
const BRANCH: &[u8] = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
const FLOAT: &[u8] = include_bytes!("../../../fixtures/rdna2/float-exact.bin");
#[test]
fn uniform_branch_selects_each_known_path() {
let taken = compile(Architecture::Gfx1030, BRANCH).unwrap();
assert_eq!(
taken.ir,
include_str!("../../../fixtures/golden/bitwise-branch.ir")
);
assert_eq!(
taken.msl,
include_str!("../../../fixtures/golden/bitwise-branch.metal")
);
let mut equal = BRANCH.to_vec();
equal[17] = 0x87; // Compare s8 with 7 instead of 6.
let fallthrough = compile(Architecture::Gfx1030, &equal).unwrap();
assert!(fallthrough.ir.contains("branch.uniform 0x0020 taken=false"));
assert!(!fallthrough.ir.contains("and.b32"));
assert!(fallthrough.ir.contains("const.u32 0x00000000"));
}
#[test]
fn rejects_branch_into_a_literal_word() {
let mut invalid = BRANCH.to_vec();
invalid[20] = 3; // Branch to byte 36, inside the literal move at byte 32.
assert!(matches!(
compile(Architecture::Gfx1030, &invalid),
Err(CompileError::Decode(error)) if error.offset == 20
));
}
#[test]
fn compiles_only_proven_exact_float_operations() {
let result = compile(Architecture::Gfx1030, FLOAT).unwrap();
assert_eq!(
result.ir,
include_str!("../../../fixtures/golden/float-exact.ir")
);
assert_eq!(
result.msl,
include_str!("../../../fixtures/golden/float-exact.metal")
);
let mut invalid = FLOAT.to_vec();
invalid[16..20].copy_from_slice(&0x007f_ffffu32.to_le_bytes());
assert!(matches!(
compile(Architecture::Gfx1030, &invalid),
Err(CompileError::Verify { offset: 40, .. })
));
}
#[test]
fn enforces_the_fixture_size_limit_before_decoding() {
assert!(matches!(
compile(Architecture::Gfx1030, &[]),
Err(CompileError::InvalidLength { bytes: 0 })
));
let mut code = FIXTURE.to_vec();
// Prepend redundant s_waitcnt vmcnt(0) instructions to reach 1024 bytes.
code.splice(
..0,
[0x70, 0x3f, 0x8c, 0xbf].repeat((1024 - FIXTURE.len()) / 4),
);
assert!(compile(Architecture::Gfx1030, &code).is_ok());
code.extend_from_slice(&[0; 4]);
assert!(matches!(
compile(Architecture::Gfx1030, &code),
Err(CompileError::InvalidLength { bytes: 1028 })
));
}
#[test]
fn preserves_the_decoder_diagnostic_and_error_source() {
let error = compile(Architecture::Gfx1030, &[0xff; 4]).unwrap_err();
let expected = "gfx1030 decode at byte 0x0: unsupported opcode in 0xffffffff";
assert_eq!(error.to_string(), expected);
assert_eq!(
std::error::Error::source(&error).unwrap().to_string(),
expected
);
}
#[test]
fn rejects_register_moves_into_index_and_outstanding_load_destinations() {
for (offset, instruction) in [
(12, [0x01, 0x03, 0x00, 0x7e]), // v_mov_b32_e32 v0, v1
(24, [0x02, 0x03, 0x02, 0x7e]), // v_mov_b32_e32 v1, v2
] {
let mut code = FIXTURE.to_vec();
if offset == 24 {
// Move the load wait after the register move. v2 is initialized.
code.drain(8..12);
code.splice(16..16, instruction);
} else {
code.splice(offset..offset, instruction);
}
let expected_offset = if offset == 24 { 16 } else { offset };
assert!(matches!(
compile(Architecture::Gfx1030, &code),
Err(CompileError::Verify {
offset,
reason: "move writes the index register or replaces a pending load",
}) if offset == expected_offset
));
}
}
#[test]
fn refuses_to_terminate_with_an_outstanding_load() {
let mut code = FIXTURE.to_vec();
// Add a second input load after the completed store. An output exists,
// but the new load still needs its own wait.
code.splice(40..40, FIXTURE[..8].iter().copied());
assert!(matches!(
compile(Architecture::Gfx1030, &code),
Err(CompileError::Verify {
offset: 48,
reason: "termination requires one completed store and no pending loads",
})
));
}
#[test]
fn protects_reserved_scalar_resource_registers() {
let mut code = FIXTURE.to_vec();
code.splice(..0, 0xbe87_0380u32.to_le_bytes()); // s_mov_b32 s7, 0
assert!(matches!(
compile(Architecture::Gfx1030, &code),
Err(CompileError::Verify {
offset: 0,
reason: "scalar move would modify a resource descriptor",
})
));
code[2] = 0x88; // s8 is outside both resource descriptors.
assert!(compile(Architecture::Gfx1030, &code).is_ok());
}
#[test]
fn proves_a_float_product_using_multiplication() {
let mut code: Vec<_> = [
0x7e02_02ffu32, // v_mov_b32_e32 v1, 0x4e800000 (2^30)
0x4e80_0000,
0x7e04_02ff, // v_mov_b32_e32 v2, 0x40000000 (2.0)
0x4000_0000,
0x1006_0501, // v_mul_f32_e32 v3, v1, v2
]
.into_iter()
.flat_map(u32::to_le_bytes)
.collect();
code.extend_from_slice(&FIXTURE[28..]);
code[25] = 3; // Store v3.
// The product 2^31 is exact, while 2^30 + 2 is not representable.
let shader = compile(Architecture::Gfx1030, &code).unwrap();
assert!(shader.ir.contains("mul.f32 t0, t1"));
assert!(
shader
.msl
.contains("as_type<float>(t0) * as_type<float>(t1)")
);
}
#[test]
fn rejects_load_into_index_or_before_waiting_on_previous_load() {
let mut code = FIXTURE.to_vec();
code[5] = 0; // Load into reserved v0.
assert!(matches!(
compile(Architecture::Gfx1030, &code),
Err(CompileError::Verify { offset: 0, .. })
));
let mut code = FIXTURE.to_vec();
code.splice(8..8, FIXTURE[..8].iter().copied());
assert!(matches!(
compile(Architecture::Gfx1030, &code),
Err(CompileError::Verify { offset: 8, .. })
));
}
#[test]
fn checks_fixture_layout_and_bindings_even_in_skipped_code() {
for (prefix, expected_offset, expected_reason) in [
(
&[0xbf82_0001u32, 0xbf81_0000][..], // Skip an early s_endpgm.
8,
"instruction follows program termination",
),
(
&[0xbf82_0002, 0xe030_2000, 0x8001_0100], // Skip load from s[4:7].
4,
"unsupported resource or buffer index",
),
(
&[0xbf82_0002, 0xe070_2000, 0x8000_0100], // Skip store to s[0:3].
4,
"unsupported resource or buffer index",
),
] {
let code: Vec<_> = prefix
.iter()
.copied()
.flat_map(u32::to_le_bytes)
.chain(FIXTURE.iter().copied())
.collect();
assert!(matches!(
compile(Architecture::Gfx1030, &code),
Err(CompileError::Verify { offset, reason })
if offset == expected_offset && reason == expected_reason
));
}
// A structurally valid instruction on the skipped path need not read an
// initialized register. Here v_mov_b32_e32 v1, v255 never runs.
let code: Vec<_> = [0xbf82_0001u32, 0x7e02_03ff]
.into_iter()
.flat_map(u32::to_le_bytes)
.chain(FIXTURE.iter().copied())
.collect();
let compiled = compile(Architecture::Gfx1030, &code).unwrap();
assert!(compiled.ir.contains("branch.uniform 0x0008 taken=true"));
assert!(compiled.msl.contains("uint t1 = input[index];"));
assert!(compiled.msl.contains("output[index] = t3;"));
}
-132
View File
@@ -1,132 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_shader::{Architecture::Gfx1030, CompileError, compile, compile_graphics};
const CONSTANT_VS: &[u8] = include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin");
const CONSTANT_PS: &[u8] = include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin");
const VARYING_VS: &[u8] = include_bytes!("../../../fixtures/rdna2/x9-varying-vs.bin");
const VARYING_PS: &[u8] = include_bytes!("../../../fixtures/rdna2/x9-varying-ps.bin");
const TRANSFORM_VS: &[u8] = include_bytes!("../../../fixtures/rdna2/x9-transform-vs.bin");
const END: &[u8] = &[0x00, 0x00, 0x81, 0xbf];
#[test]
fn links_constant_and_varying_graphics_fixtures() {
let constant = compile_graphics(Gfx1030, CONSTANT_VS, CONSTANT_PS).unwrap();
assert!(
constant
.disassembly
.contains("exp mrt0, v8, v9, v9, v8 done vm")
);
assert!(constant.ir.contains("export.f32x4 mrt0, t0, t1, t1, t0"));
assert!(constant.msl.contains("fragment PixelOutput xenora_pixel()"));
let varying = compile_graphics(Gfx1030, VARYING_VS, VARYING_PS).unwrap();
assert!(varying.ir.contains("export.f32x4 param0, t4, t5, t6, t7"));
assert!(varying.ir.contains("export.f32x4 mrt0, t0, t1, t2, t3"));
assert!(
varying
.msl
.contains("float4 parameter [[user(locn0), center_perspective]]")
);
for component in 0..4 {
assert!(varying.ir.contains(&format!(
"interpolate.center_perspective.f32 attr0[{component}]"
)));
}
}
#[test]
fn preserves_transform_operands_and_keeps_vertex_arithmetic_unfused() {
let shader = compile_graphics(Gfx1030, TRANSFORM_VS, CONSTANT_PS).unwrap();
assert!(shader.ir.contains("0010: t10 = mul.f32 t0, t8"));
assert!(shader.ir.contains("0014: t11 = mul.f32 t1, t8"));
assert!(shader.ir.contains("0018: t12 = add.f32 t10, t9"));
assert!(
shader
.ir
.contains("001c: export.f32x4 pos0, t12, t11, t2, t3")
);
assert!(
shader
.msl
.contains(" #pragma clang fp contract(off)\n #pragma clang fp reassociate(off)")
);
}
#[test]
fn refuses_unlinked_or_missing_exports() {
for (vertex, pixel, expected) in [
(VARYING_VS, CONSTANT_PS, "PARAM0"),
(CONSTANT_VS, VARYING_PS, "PARAM0"),
(END, CONSTANT_PS, "POS0"),
(CONSTANT_VS, END, "MRT0"),
] {
let error = compile_graphics(Gfx1030, vertex, pixel).unwrap_err();
assert!(matches!(error, CompileError::GraphicsLink { .. }));
assert!(error.to_string().contains(expected), "{error}");
}
}
#[test]
fn refuses_invalid_export_sources_stage_and_placement() {
let mut uninitialized = CONSTANT_VS.to_vec();
uninitialized[4] = 8;
let mut duplicate = CONSTANT_VS[..8].to_vec();
duplicate.extend_from_slice(CONSTANT_VS);
let mut trailing = CONSTANT_VS.to_vec();
trailing.extend_from_slice(END);
let mut misplaced_move = CONSTANT_VS[..8].to_vec();
misplaced_move.extend_from_slice(&CONSTANT_PS[..4]);
misplaced_move.extend_from_slice(END);
for (vertex, expected_offset, message) in [
(
&uninitialized[..],
0,
"source VGPR is uninitialized or reserved",
),
(&duplicate[..], 8, "export target is written more than once"),
(&trailing[..], 12, "instruction follows program termination"),
(&misplaced_move[..], 8, "instruction is unsupported"),
(&CONSTANT_VS[..8], 8, "missing program termination"),
(CONSTANT_PS, 8, "export target is invalid for this stage"),
] {
let error = compile_graphics(Gfx1030, vertex, CONSTANT_PS).unwrap_err();
assert_stage_error(&error, "vertex", expected_offset, message);
}
}
#[test]
fn refuses_unsupported_interpolation_and_graphics_resources() {
for (index, replacement, expected_offset, expected) in [
(0, 1, 0, "instruction is unsupported"),
(1, 4, 0, "instruction is unsupported"),
(4, 2, 4, "matching second interpolation phase"),
(5, 1, 4, "matching second interpolation phase"),
(6, 0x25, 4, "matching second interpolation phase"),
] {
let mut pixel = VARYING_PS.to_vec();
pixel[index] = replacement;
let error = compile_graphics(Gfx1030, VARYING_VS, &pixel).unwrap_err();
assert_stage_error(&error, "pixel", expected_offset, expected);
}
let resource_instruction = &include_bytes!("../../../fixtures/rdna2/add.bin")[..8];
let error = compile_graphics(Gfx1030, resource_instruction, CONSTANT_PS).unwrap_err();
assert_stage_error(&error, "vertex", 0, "instruction is unsupported");
let error = compile(Gfx1030, CONSTANT_VS).unwrap_err();
assert!(matches!(error, CompileError::Verify { offset: 0, .. }));
}
fn assert_stage_error(error: &CompileError, stage: &str, offset: usize, message: &str) {
let CompileError::GraphicsStage {
stage: actual_stage,
error: cause,
} = error
else {
panic!("expected stage-specific error, found {error}");
};
assert_eq!(*actual_stage, stage);
assert!(
matches!(cause.as_ref(), CompileError::Verify { offset: actual, reason } if *actual == offset && reason.contains(message)),
"{error}"
);
}
-270
View File
@@ -1,270 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Synthetic texture layout for original fixtures.
//!
//! Each array layer stores its mip levels consecutively. Each level stores
//! row-major 2×2 tiles of BC1 blocks. Edge tiles have full storage, including
//! padding blocks. This layout is defined by Xenora's fixtures.
#![forbid(unsafe_code)]
pub mod sampler;
mod upload;
pub use sampler::{AddressMode, FilterMode, SamplerDesc, SamplerError, TextureMetadata};
pub use upload::{Bc1Subresource, Bc1Upload, Bc1UploadDesc};
const BLOCK_BYTES: usize = 8;
const TILE_BLOCKS: usize = 2;
#[derive(Debug, PartialEq, Eq)]
pub enum TextureError {
InvalidLayout,
SizeOverflow,
OutOfBounds,
InvalidByteLength,
AllocationFailed,
}
#[derive(Debug)]
pub struct TiledBc1<'a> {
bytes: &'a [u8],
width: usize,
height: usize,
mips: u32,
layers: usize,
layer_bytes: usize,
}
impl<'a> TiledBc1<'a> {
pub fn new(
bytes: &'a [u8],
width: usize,
height: usize,
mips: u32,
layers: usize,
) -> Result<Self, TextureError> {
let max_mips = usize::BITS - width.max(height).leading_zeros();
if width == 0 || height == 0 || layers == 0 || mips == 0 || mips > max_mips {
return Err(TextureError::InvalidLayout);
}
let layer_bytes = (0..mips).try_fold(0usize, |total, mip| {
total
.checked_add(mip_bytes(width, height, mip)?)
.ok_or(TextureError::SizeOverflow)
})?;
let size = layer_bytes
.checked_mul(layers)
.ok_or(TextureError::SizeOverflow)?;
if size != bytes.len() {
return Err(TextureError::InvalidByteLength);
}
Ok(Self {
bytes,
width,
height,
mips,
layers,
layer_bytes,
})
}
/// Returns the logical texel dimensions of an existing mip level.
pub fn mip_extent(&self, mip: u32) -> Result<(usize, usize), TextureError> {
if mip >= self.mips {
return Err(TextureError::OutOfBounds);
}
Ok(((self.width >> mip).max(1), (self.height >> mip).max(1)))
}
/// Copies one subresource as tightly packed row-major BC1 block rows.
/// Padded tile slots are excluded, including at partial texel blocks.
pub fn linearize(&self, layer: usize, mip: u32) -> Result<Vec<u8>, TextureError> {
if layer >= self.layers {
return Err(TextureError::OutOfBounds);
}
self.mip_extent(mip)?;
let (width, height) = mip_blocks(self.width, self.height, mip);
let mut blocks = Vec::new();
// Construction checked the larger, padded byte count.
blocks
.try_reserve_exact(width * height * BLOCK_BYTES)
.map_err(|_| TextureError::AllocationFailed)?;
for y in 0..height {
for x in 0..width {
blocks.extend_from_slice(&self.block(layer, mip, x, y)?);
}
}
Ok(blocks)
}
/// Reads a block by its logical block coordinates, excluding tile padding.
pub fn block(
&self,
layer: usize,
mip: u32,
x: usize,
y: usize,
) -> Result<[u8; BLOCK_BYTES], TextureError> {
if layer >= self.layers || mip >= self.mips {
return Err(TextureError::OutOfBounds);
}
let (width, height) = mip_blocks(self.width, self.height, mip);
if x >= width || y >= height {
return Err(TextureError::OutOfBounds);
}
let mut base = layer * self.layer_bytes;
for prior in 0..mip {
base += mip_bytes(self.width, self.height, prior)?;
}
// Construction checked the full padded size for every level and layer.
let tile = (y / TILE_BLOCKS) * width.div_ceil(TILE_BLOCKS) + x / TILE_BLOCKS;
let within_tile = (y % TILE_BLOCKS) * TILE_BLOCKS + x % TILE_BLOCKS;
let offset = base + (tile * TILE_BLOCKS.pow(2) + within_tile) * BLOCK_BYTES;
self.bytes
.get(offset..offset + BLOCK_BYTES)
.and_then(|bytes| bytes.try_into().ok())
.ok_or(TextureError::InvalidByteLength)
}
}
fn mip_blocks(width: usize, height: usize, mip: u32) -> (usize, usize) {
(
(width >> mip).max(1).div_ceil(4),
(height >> mip).max(1).div_ceil(4),
)
}
fn mip_bytes(width: usize, height: usize, mip: u32) -> Result<usize, TextureError> {
let (width, height) = mip_blocks(width, height, mip);
width
.div_ceil(TILE_BLOCKS)
.checked_mul(height.div_ceil(TILE_BLOCKS))
.and_then(|tiles| tiles.checked_mul(TILE_BLOCKS.pow(2) * BLOCK_BYTES))
.ok_or(TextureError::SizeOverflow)
}
/// Expands a BC1 block to 16 row-major RGBA8 texels using integer interpolation.
/// See Microsoft's Direct3D 10 documentation for the BC1 palette and indices.
pub fn decode_bc1(block: [u8; BLOCK_BYTES]) -> [[u8; 4]; 16] {
let [a, b, c, d, i, j, k, l] = block;
let first = u16::from_le_bytes([a, b]);
let second = u16::from_le_bytes([c, d]);
let mut palette = [rgb565(first), rgb565(second), [0; 4], [0; 4]];
let opaque = first > second;
for channel in 0..3 {
let a = u16::from(palette[0][channel]);
let b = u16::from(palette[1][channel]);
if opaque {
palette[2][channel] = ((2 * a + b) / 3) as u8;
palette[3][channel] = ((a + 2 * b) / 3) as u8;
} else {
palette[2][channel] = ((a + b) / 2) as u8;
}
}
palette[2][3] = 255;
if opaque {
palette[3][3] = 255;
}
let indices = u32::from_le_bytes([i, j, k, l]);
std::array::from_fn(|texel| palette[((indices >> (2 * texel)) & 3) as usize])
}
fn rgb565(color: u16) -> [u8; 4] {
let r = ((color >> 11) & 31) as u8;
let g = ((color >> 5) & 63) as u8;
let b = (color & 31) as u8;
[
(r << 3) | (r >> 2),
(g << 2) | (g >> 4),
(b << 3) | (b >> 2),
255,
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_edges_and_mips_across_layers() {
// 9×5 has 3×2 logical blocks in two tiles, followed by a 4×2
// mip in one tile. Repeating byte values identify physical slots.
let bytes: Vec<_> = (0..24).flat_map(|marker| [marker; 8]).collect();
let tex = TiledBc1::new(&bytes, 9, 5, 2, 2).unwrap();
assert_eq!(tex.block(0, 0, 1, 1), Ok([3; 8]));
assert_eq!(tex.block(0, 0, 2, 1), Ok([6; 8]));
assert_eq!(tex.block(0, 1, 0, 0), Ok([8; 8]));
assert_eq!(tex.block(1, 0, 0, 0), Ok([12; 8]));
assert_eq!(tex.block(1, 1, 0, 0), Ok([20; 8]));
assert_eq!(tex.block(0, 0, 3, 0), Err(TextureError::OutOfBounds));
assert_eq!(tex.block(0, 2, 0, 0), Err(TextureError::OutOfBounds));
assert_eq!(tex.block(2, 0, 0, 0), Err(TextureError::OutOfBounds));
assert_eq!(tex.mip_extent(1), Ok((4, 2)));
let logical_blocks = [[12; 8], [13; 8], [16; 8], [14; 8], [15; 8], [18; 8]];
assert_eq!(tex.linearize(1, 0).unwrap(), logical_blocks.as_flattened());
assert_eq!(tex.linearize(1, 1).unwrap(), [20; 8]);
assert_eq!(tex.linearize(2, 0), Err(TextureError::OutOfBounds));
}
#[test]
fn rejects_truncation_invalid_mips_and_overflow() {
assert_eq!(
TiledBc1::new(&[0; 31], 4, 4, 1, 1).unwrap_err(),
TextureError::InvalidByteLength
);
assert_eq!(
TiledBc1::new(&[], 1, 1, 2, 1).unwrap_err(),
TextureError::InvalidLayout
);
assert_eq!(
TiledBc1::new(&[], usize::MAX, usize::MAX, 1, 1).unwrap_err(),
TextureError::SizeOverflow
);
}
#[test]
fn advances_to_the_next_tile_row() {
let bytes: Vec<_> = (0..16).flat_map(|marker| [marker; 8]).collect();
let texture = TiledBc1::new(&bytes, 9, 9, 1, 1).unwrap();
assert_eq!(texture.block(0, 0, 0, 2), Ok([8; 8]));
assert_eq!(texture.block(0, 0, 2, 2), Ok([12; 8]));
}
#[test]
fn decodes_opaque_and_transparent_bc1_palettes() {
let opaque = decode_bc1([0, 0xf8, 31, 0, 0xe4, 0xe4, 0xe4, 0xe4]);
let transparent = decode_bc1([31, 0, 0, 0xf8, 0xe4, 0xe4, 0xe4, 0xe4]);
assert_eq!(
opaque.as_slice(),
[
[255, 0, 0, 255],
[0, 0, 255, 255],
[170, 0, 85, 255],
[85, 0, 170, 255]
]
.repeat(4)
);
assert_eq!(
transparent.as_slice(),
[
[0, 0, 255, 255],
[255, 0, 0, 255],
[127, 0, 127, 255],
[0; 4]
]
.repeat(4)
);
}
#[test]
fn decodes_a_block_from_a_selected_layer_and_mip() {
let mut bytes = [0; 128];
// A 5×5 layer has one 32-byte tile per mip. Layer 1, mip 1
// starts at byte 96. Only that block is filled with opaque green.
bytes[96..104].copy_from_slice(&[224, 7, 0, 0, 0, 0, 0, 0]);
let texture = TiledBc1::new(&bytes, 5, 5, 2, 2).unwrap();
assert_eq!(
decode_bc1(texture.block(1, 1, 0, 0).unwrap()),
[[0, 255, 0, 255]; 16]
);
}
}
-264
View File
@@ -1,264 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Reusable texture sampler descriptor and validation.
//!
//! Provides typed definitions and validation for texture samplers independent of
//! Metal or GPU-specific runtime types.
use std::fmt;
/// Filter mode for texture sampling.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FilterMode {
/// Nearest-neighbor point sampling.
Nearest,
}
/// Address/wrap mode for texture sampling along a coordinate axis.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AddressMode {
/// Clamp coordinates to the edge of the texture (`[0.0, 1.0]`).
ClampToEdge,
}
/// Errors returned when constructing or validating a sampler descriptor.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SamplerError {
/// The requested filter mode is not supported.
UnsupportedFilterMode,
/// The requested addressing mode is not supported.
UnsupportedAddressMode,
/// Minimum LOD is greater than maximum LOD.
InvalidLodRange,
/// Explicit mip selection or bounds exceed texture metadata.
MipOutOfBounds,
/// Texture metadata dimensions are invalid (e.g. zero width or height).
InvalidTextureDimensions,
/// Texture mip count is zero.
InvalidTextureMipCount,
}
impl fmt::Display for SamplerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnsupportedFilterMode => write!(f, "unsupported sampler filter mode"),
Self::UnsupportedAddressMode => write!(f, "unsupported sampler address mode"),
Self::InvalidLodRange => write!(f, "min_lod must not be greater than max_lod"),
Self::MipOutOfBounds => write!(f, "selected mip or lod exceeds texture mip count"),
Self::InvalidTextureDimensions => write!(f, "invalid texture dimensions"),
Self::InvalidTextureMipCount => write!(f, "texture mip count must be at least 1"),
}
}
}
impl std::error::Error for SamplerError {}
/// Minimal metadata describing a target texture for sampler validation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TextureMetadata {
pub width: usize,
pub height: usize,
pub mips: u32,
}
impl TextureMetadata {
pub fn new(width: usize, height: usize, mips: u32) -> Result<Self, SamplerError> {
if width == 0 || height == 0 {
return Err(SamplerError::InvalidTextureDimensions);
}
if mips == 0 {
return Err(SamplerError::InvalidTextureMipCount);
}
let max_mips = usize::BITS - width.max(height).leading_zeros();
if mips > max_mips {
return Err(SamplerError::MipOutOfBounds);
}
Ok(Self {
width,
height,
mips,
})
}
}
/// Reusable, typed sampler descriptor.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SamplerDesc {
pub min_filter: FilterMode,
pub mag_filter: FilterMode,
pub mip_filter: FilterMode,
pub address_u: AddressMode,
pub address_v: AddressMode,
pub min_lod: f32,
pub max_lod: f32,
pub explicit_mip: Option<u32>,
}
impl Default for SamplerDesc {
fn default() -> Self {
Self::nearest_clamp()
}
}
impl SamplerDesc {
/// Create a standard nearest-neighbor, clamp-to-edge sampler.
pub const fn nearest_clamp() -> Self {
Self {
min_filter: FilterMode::Nearest,
mag_filter: FilterMode::Nearest,
mip_filter: FilterMode::Nearest,
address_u: AddressMode::ClampToEdge,
address_v: AddressMode::ClampToEdge,
min_lod: 0.0,
max_lod: f32::MAX,
explicit_mip: None,
}
}
/// Builder for setting an explicit mip level.
pub const fn with_explicit_mip(mut self, mip: u32) -> Self {
self.explicit_mip = Some(mip);
self
}
/// Builder for setting LOD range.
pub const fn with_lod_range(mut self, min_lod: f32, max_lod: f32) -> Self {
self.min_lod = min_lod;
self.max_lod = max_lod;
self
}
/// Validates the sampler descriptor on its own.
pub fn validate(&self) -> Result<(), SamplerError> {
if !self.min_lod.is_finite()
|| !self.max_lod.is_finite()
|| self.min_lod < 0.0
|| self.min_lod > self.max_lod
{
return Err(SamplerError::InvalidLodRange);
}
Ok(())
}
/// Validates the sampler descriptor against specific texture metadata.
pub fn validate_against_texture(&self, texture: &TextureMetadata) -> Result<(), SamplerError> {
self.validate()?;
if texture.width == 0 || texture.height == 0 {
return Err(SamplerError::InvalidTextureDimensions);
}
if texture.mips == 0 {
return Err(SamplerError::InvalidTextureMipCount);
}
if let Some(explicit_mip) = self.explicit_mip
&& explicit_mip >= texture.mips
{
return Err(SamplerError::MipOutOfBounds);
}
if self.min_lod >= texture.mips as f32 {
return Err(SamplerError::MipOutOfBounds);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_valid_nearest_clamp_descriptor() {
let sampler = SamplerDesc::nearest_clamp();
assert_eq!(sampler.validate(), Ok(()));
assert_eq!(sampler.min_filter, FilterMode::Nearest);
assert_eq!(sampler.mag_filter, FilterMode::Nearest);
assert_eq!(sampler.address_u, AddressMode::ClampToEdge);
assert_eq!(sampler.address_v, AddressMode::ClampToEdge);
}
#[test]
fn test_valid_mip_selection() {
let meta = TextureMetadata::new(16, 16, 4).unwrap();
let sampler = SamplerDesc::nearest_clamp().with_explicit_mip(2);
assert_eq!(sampler.validate_against_texture(&meta), Ok(()));
let sampler_zero = SamplerDesc::nearest_clamp().with_explicit_mip(0);
assert_eq!(sampler_zero.validate_against_texture(&meta), Ok(()));
let sampler_last = SamplerDesc::nearest_clamp().with_explicit_mip(3);
assert_eq!(sampler_last.validate_against_texture(&meta), Ok(()));
}
#[test]
fn test_invalid_mip_selection() {
let meta = TextureMetadata::new(16, 16, 4).unwrap();
let sampler = SamplerDesc::nearest_clamp().with_explicit_mip(4);
assert_eq!(
sampler.validate_against_texture(&meta),
Err(SamplerError::MipOutOfBounds)
);
let sampler_large = SamplerDesc::nearest_clamp().with_explicit_mip(100);
assert_eq!(
sampler_large.validate_against_texture(&meta),
Err(SamplerError::MipOutOfBounds)
);
}
#[test]
fn test_invalid_dimensions() {
assert_eq!(
TextureMetadata::new(0, 16, 1),
Err(SamplerError::InvalidTextureDimensions)
);
assert_eq!(
TextureMetadata::new(16, 0, 1),
Err(SamplerError::InvalidTextureDimensions)
);
assert_eq!(
TextureMetadata::new(16, 16, 0),
Err(SamplerError::InvalidTextureMipCount)
);
// 16x16 has max 5 mips (16, 8, 4, 2, 1)
assert_eq!(
TextureMetadata::new(16, 16, 6),
Err(SamplerError::MipOutOfBounds)
);
}
#[test]
fn test_malformed_lod_range() {
let invalid_order = SamplerDesc::nearest_clamp().with_lod_range(3.0, 1.0);
assert_eq!(invalid_order.validate(), Err(SamplerError::InvalidLodRange));
let negative_lod = SamplerDesc::nearest_clamp().with_lod_range(-1.0, 2.0);
assert_eq!(negative_lod.validate(), Err(SamplerError::InvalidLodRange));
let nan_lod = SamplerDesc::nearest_clamp().with_lod_range(f32::NAN, 2.0);
assert_eq!(nan_lod.validate(), Err(SamplerError::InvalidLodRange));
}
#[test]
fn test_lod_exceeds_texture_mips() {
let meta = TextureMetadata::new(8, 8, 3).unwrap();
let high_lod = SamplerDesc::nearest_clamp().with_lod_range(3.0, 5.0);
assert_eq!(
high_lod.validate_against_texture(&meta),
Err(SamplerError::MipOutOfBounds)
);
}
#[test]
fn test_non_power_of_two_metadata() {
// 3x3 has max 2 mips (floor(log2(3)) + 1 = 2)
let meta = TextureMetadata::new(3, 3, 2).unwrap();
assert_eq!(meta.mips, 2);
assert_eq!(
TextureMetadata::new(3, 3, 3),
Err(SamplerError::MipOutOfBounds)
);
}
}
-185
View File
@@ -1,185 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use super::{BLOCK_BYTES, TextureError, mip_blocks};
/// A layer-major BC1 upload with one common pitch for every mip.
/// Each mip occupies exactly one slice, including any trailing padding.
#[derive(Clone, Copy, Debug)]
pub struct Bc1UploadDesc {
pub width: usize,
pub height: usize,
pub mips: u32,
pub layers: usize,
pub format: u32,
pub usage: u32,
pub row_pitch: usize,
pub slice_pitch: usize,
}
#[derive(Debug)]
pub struct Bc1Upload<'a> {
bytes: &'a [u8],
desc: Bc1UploadDesc,
}
#[derive(Debug)]
pub struct Bc1Subresource<'a> {
pub bytes: &'a [u8],
pub width: usize,
pub height: usize,
pub row_pitch: usize,
}
impl<'a> Bc1Upload<'a> {
pub fn new(bytes: &'a [u8], desc: Bc1UploadDesc) -> Result<Self, TextureError> {
let max_mips = usize::BITS - desc.width.max(desc.height).leading_zeros();
if desc.format != 1
|| desc.usage != 1
|| desc.width == 0
|| desc.height == 0
|| desc.layers == 0
|| desc.mips == 0
|| desc.mips > max_mips
{
return Err(TextureError::InvalidLayout);
}
let (blocks_x, blocks_y) = mip_blocks(desc.width, desc.height, 0);
let tight_row = blocks_x
.checked_mul(BLOCK_BYTES)
.ok_or(TextureError::SizeOverflow)?;
if desc.row_pitch < tight_row || !desc.row_pitch.is_multiple_of(BLOCK_BYTES) {
return Err(TextureError::InvalidLayout);
}
let minimum_slice = desc
.row_pitch
.checked_mul(blocks_y)
.ok_or(TextureError::SizeOverflow)?;
if desc.slice_pitch < minimum_slice || !desc.slice_pitch.is_multiple_of(BLOCK_BYTES) {
return Err(TextureError::InvalidLayout);
}
let size = desc
.slice_pitch
.checked_mul(desc.mips as usize)
.and_then(|size| size.checked_mul(desc.layers))
.ok_or(TextureError::SizeOverflow)?;
if bytes.len() != size {
return Err(TextureError::InvalidByteLength);
}
Ok(Self { bytes, desc })
}
pub fn subresource(&self, layer: usize, mip: u32) -> Result<Bc1Subresource<'a>, TextureError> {
if layer >= self.desc.layers || mip >= self.desc.mips {
return Err(TextureError::OutOfBounds);
}
// Construction proved that the complete array fits in the source span.
let offset = (layer * self.desc.mips as usize + mip as usize) * self.desc.slice_pitch;
let width = (self.desc.width >> mip).max(1);
let height = (self.desc.height >> mip).max(1);
let rows = height.div_ceil(4);
Ok(Bc1Subresource {
bytes: &self.bytes[offset..offset + rows * self.desc.row_pitch],
width,
height,
row_pitch: self.desc.row_pitch,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
const DESC: Bc1UploadDesc = Bc1UploadDesc {
width: 5,
height: 5,
mips: 2,
layers: 2,
format: 1,
usage: 1,
row_pitch: 24,
slice_pitch: 56,
};
#[test]
fn selects_mips_and_layers_with_partial_blocks_and_padding() {
let mut bytes = [0; 224];
bytes[144..152].fill(0x9a); // Layer 1, mip 0, row 1, block 1.
bytes[168..176].copy_from_slice(&[0, 0, 255, 255, 255, 255, 255, 255]);
let upload = Bc1Upload::new(&bytes, DESC).unwrap();
let base = upload.subresource(1, 0).unwrap();
assert_eq!((base.width, base.height, base.row_pitch), (5, 5, 24));
assert_eq!(base.bytes.len(), 48);
assert_eq!(base.bytes[32..40], [0x9a; 8]);
let small = upload.subresource(1, 1).unwrap();
assert_eq!((small.width, small.height, small.bytes.len()), (2, 2, 24));
assert_eq!(
crate::decode_bc1(small.bytes[..8].try_into().unwrap()),
[[0; 4]; 16]
);
assert_eq!(upload.subresource(0, 1).unwrap().bytes, [0; 24]);
assert_eq!(
upload.subresource(0, 2).unwrap_err(),
TextureError::OutOfBounds
);
assert_eq!(
upload.subresource(2, 0).unwrap_err(),
TextureError::OutOfBounds
);
}
#[test]
fn rejects_invalid_uploads_before_indexing() {
let bytes = [0; 224];
for desc in [
Bc1UploadDesc { format: 2, ..DESC },
Bc1UploadDesc { usage: 2, ..DESC },
Bc1UploadDesc { mips: 4, ..DESC },
Bc1UploadDesc { layers: 0, ..DESC },
Bc1UploadDesc {
row_pitch: 8,
..DESC
},
Bc1UploadDesc {
row_pitch: 17,
..DESC
},
Bc1UploadDesc {
slice_pitch: 40,
..DESC
},
Bc1UploadDesc {
slice_pitch: 49,
..DESC
},
] {
assert_eq!(
Bc1Upload::new(&bytes, desc).unwrap_err(),
TextureError::InvalidLayout
);
}
assert_eq!(
Bc1Upload::new(&bytes[..223], DESC).unwrap_err(),
TextureError::InvalidByteLength
);
for desc in [
Bc1UploadDesc {
width: usize::MAX,
..DESC
},
Bc1UploadDesc {
row_pitch: usize::MAX - 7,
..DESC
},
Bc1UploadDesc {
layers: usize::MAX,
..DESC
},
] {
assert_eq!(
Bc1Upload::new(&bytes, desc).unwrap_err(),
TextureError::SizeOverflow
);
}
}
}
+27 -42
View File
@@ -1,50 +1,35 @@
# Xenora documentation
# BetterXen Documentation
## Getting started
## Getting Started & Architecture
Start with the [project README](../README.md) for scope and build commands,
then read the [interface contracts](interfaces.md). Reproduce an
[original guest test program](../experiments/x1/README.md) or run the
[independent validation suite](../tests/validation/README.md) before changing
either path. The [changelog](../CHANGELOG.md) records notable changes.
- [Project README](../README.md) — Overview, quick start, `bx-cli` commands, and verified scope.
- [Roadmap](roadmap.md) — Single authoritative plan (Milestones M0–M6) and completion gates.
- [Parallel Track Architecture](architecture/parallel-tracks.md) — 6-track directory ownership, ABI freeze rule, and multi-agent Git workflow.
- [Wave 1 Parallel Backlog](issues/wave-1-backlog.md) — Non-overlapping starter issues across Tracks A–F.
- [Frozen ABI Contracts](../abi/README.md) — Cross-DLL C headers (`abi/include/`) and canonical `.def` export tables (`abi/defs/`).
- [Synthetic Conformance Suite](../tests/conformance/README.md) — Auto-discovered PE32+ conformance binaries.
- [Changelog](../CHANGELOG.md) — Unreleased and historical changes.
## Architecture and technical design
## Architecture Decision Records
- [Interface contracts](interfaces.md) — Shader inputs, guest services, native command submission, and synthetic textures.
- [Fixture memory model](adr/0003-demo-memory-model.md) and [CPU boundary](adr/0004-cpu-boundary.md) — Buffer bindings, guest address translation, and dependency direction.
- [ADR 0005: CrossOver-based hybrid direction](adr/0005-crossover-hybrid-direction.md) — Pivot to CrossOver + Rosetta 2 + D3DMetal as the external foundation.
- [ADR 0006: Retire in-tree native-first workspace](adr/0006-retire-in-tree-native-workspace.md) — Retirement of paused native code/scripts/docs from `main` (preserved at Git tag `native-first-final`).
- [ADR 0007: API-set win32_bridge shims under CrossOver](adr/0007-api-set-shims-under-crossover.md) — Accepted: CrossOver answers the six API-set import names itself, so the shims are not loaded for static imports.
## RDNA 2 decoding and shader translation
## Research, Testing & Licensing
- [Instruction coverage](shaders/instruction-coverage.md) — Desktop gfx1030 instruction forms, operand limits, and CPU and GPU results.
- [Metal Shading Language generation](shaders/msl.md) and [independent CPU reference](shaders/reference-interpreter.md) — Translation rules and separate CPU execution models.
- [Hybrid Workloads & Measurement Protocol](testing/hybrid-workloads.md) — Original Windows workloads, receipt fields, timing conventions, and negative controls.
- [CrossOver Licensing & Redistribution Boundaries](research/crossover-licensing.md) — Per-component license review for CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, D3DMetal, and Rosetta 2.
- [Upstream Research Registry](research/upstream-registry.md) & [Component Reuse Matrix](research/component-reuse-matrix.md) — Public upstream evaluation and provenance screening.
- [Primary-Source Verification (2026-11-25)](research/primary-source-verification-2026-11-25.md) & [Hybrid Backlog Research Record](research/hybrid-backlog-research-2026-11-25.md) — Vendor documentation verification notes.
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — One-host observation to check before M2 presentation work.
- [D3DMetal GPU Limits](research/d3dmetal-gpu-limits.md) — Constraints a shader translator targeting D3DMetal must handle, measured by the `test_d3dmetal_gpu_limits` fixture (`WaveSize(64)` and SM 6.6 64-bit atomics not run, bounded lock emulation), plus unverified reports kept separate as leads (#453).
- [Public Technical References](research/sources.md), [Xbox GDK Notes](research/xbox-gdk.md), [RDNA 2 Notes](research/rdna2.md), and [Shader Containers](research/shader-containers.md) — Public specification references for shim and shader work.
## Native Metal backend
## Governance, Security & Legal
- [Compute interface](interfaces.md#gfx1030-compute-fixtures) — Resource limits, dispatch, completion, and profiling.
- [Apple GPU evidence](research/apple-gpu.md) and [host lab record](research/host-lab.md) — Observed behavior and historical floating-point results.
## Guest CPU and runtime experiments
- [Guest experiment guide](../experiments/x1/README.md) — Bounded x86-64 execution, executable loading, experimental services, native compute, and offscreen rendering.
- [Guest CPU research](research/cpu-boundary.md) — Public specifications and unresolved console requirements.
- [Synthetic import fixtures](../tests/compat_fixtures/README.md) — Reproducible PE32+ builds and expected service behavior.
## Testing, validation, and benchmarks
- [Engineering progress](progress.md) — Verification commands, metric definitions, and open release gates.
- [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.
- [Mutation testing](testing/mutation.md) and [benchmark protocol](testing/benchmarks.md) — Test sensitivity, benchmark inputs, and timing requirements.
## Research and engineering decisions
- [Public sources](research/sources.md), [RDNA 2 notes](research/rdna2.md), and [Xbox GPU evidence](research/xbox-gpu.md) — Specifications, evidence scope, and unknown console behavior.
- [Shader inputs](research/shader-containers.md) and [risk register](risk-register.md) — Input provenance and unresolved engineering risks.
- [Synthetic integration and upstream evidence](research/synthetic-integration.md) — Audited source snapshots and remaining commercial startup prerequisites.
## Security, licensing, and contributions
- [Threat model](threat-model.md) and [security reporting](../SECURITY.md) — Execution limits and disclosure instructions.
- [Legal scope](legal.md), [dependency licensing](licenses.md), and [third-party notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution findings.
- [Contribution guidelines](../CONTRIBUTING.md) — Original authorship, Developer Certificate of Origin sign-off, and evidence requirements.
- [Engineering & Agent Rules](../AGENTS.md) (`CLAUDE.md` symlink) — Mandatory rules for human contributors and coding agents.
- [Contributing Guidelines](../CONTRIBUTING.md) — Claiming, verification, clean-room policy, and DCO sign-off.
- [Claims & Evidence Classes](claims.toml) — Evidence classification definitions (classes A–D, U).
- [Legal Scope](legal.md), [Dependency Licensing](licenses.md), and [Third-Party Notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution boundaries.
- [Threat Model](threat-model.md) & [Security Policy](../SECURITY.md) — Isolation boundaries and vulnerability reporting.
-7
View File
@@ -1,7 +0,0 @@
# 0003. Use disjoint lane-indexed buffers for the first fixture
For the synthetic compute fixture, the resource beginning at SGPR 0 denotes the read-only input words and the one beginning at SGPR 4 denotes the output words. VGPR 0 starts at the lane index and must remain unchanged when used as a resource index. Each allocation has the same word count, and each dispatched invocation accesses only its own lane's word. The fixture ABI provides no raw resource descriptor bits or guest virtual addresses.
The compiler must reject descriptor forms, offsets, index changes and control flow outside this contract. Both engines must honor the load dependency and completion order. The host reads output after command completion. Supporting shared writable buffers will require a new ordering and aliasing contract.
AMD RDNA 2 specifies implicit outstanding memory waits at program termination (class B, CLAIM-RDNA2-TRANSFER-WAITS). This fixture policy requires explicit corresponding wait instructions before termination to keep the bounded execution model auditable. See the [RDNA 2 source notes](../research/rdna2.md).
-7
View File
@@ -1,7 +0,0 @@
# 0004. Keep CPU recompilation outside the graphics dependency graph
Phase 01 accepts synthetic shader code and explicit buffer bindings. A later guest CPU runtime will submit graphics commands using opaque resource handles, addresses, lengths and access modes. The graphics side will resolve addresses through checked mappings, retain resources through command completion and return fence completions or interrupt events via the command interface. CPU code may consume that interface. Graphics crates may depend on shared boundary types and graphics crates only, with no dependency on guest CPU or host x86-specific code.
Keep guest address arithmetic separate from host virtual addresses. Validate ranges before constructing a Metal view and retain the backing allocation for all queued users. Define aliasing and synchronization before supporting shared writable mappings. The first fixture uses independent input and output buffers and has no guest virtual address space.
See [CPU research](../research/cpu-boundary.md) for the host and guest evidence and [the interface contract](../interfaces.md) for the current fixture.
@@ -0,0 +1,41 @@
# ADR 0005: CrossOver-based hybrid direction
Status: **Accepted (strategic direction).** Accepted by the maintainers' planning directive of 2026-11-25. The proposed technical architecture below is **not** accepted or verified; each integration still needs validation.
## Context
BetterXen was developed native-first: an independent x86-64 decoder, interpreter, ARM64 translator, runtime, shader compiler and Metal backend, verified only on synthetic programs and shaders. No Xbox title runs on it. The maintainers decided to focus all active engineering on a hybrid architecture and to pause native work.
## Accepted strategic direction
- CrossOver is the primary compatibility foundation, installed externally.
- Hybrid is the only active development direction. Native research is preserved (tag `native-first-final` marks the last `main` commit before this change; the code stays in the workspace) and paused; resuming needs an explicit maintainer decision.
- Reuse established infrastructure; build independent replacements only for demonstrated limitations.
- The engineering rules in `AGENTS.md` (and `CLAUDE.md`, a symlink) were rewritten accordingly, replacing the former prohibition on Wine, CrossOver, Rosetta and MoltenVK.
## Proposed technical architecture (not accepted)
BetterXen provides integration, configuration, environment management, diagnostics, reproducible testing, benchmarking and measured optimization around CrossOver. Within CrossOver, the intended layers are Wine-based runtime APIs, Rosetta 2 for x86-64 translation and D3DMetal or DXMT for graphics, on Apple Silicon (ARM64, Metal, unified memory). The exact responsibility boundary is decided in #351, at the end of Phase 1.
## Unverified integration assumptions
- That CrossOver, Rosetta 2, D3DMetal or DXMT run any authorized workload BetterXen needs. Assumed not until measured (#355).
- That CrossOver offers supported interfaces for bottle management, configuration, launching and diagnostics (#350).
- Rosetta 2's support lifetime and D3DMetal's license terms (#349, #354).
- That any of this provides Xbox runtime compatibility. It is assumed not to.
## Verified implementation capabilities
None for the hybrid architecture. Verified native-research capabilities (synthetic evidence only) are unchanged and listed in `docs/progress.md`.
## Planning consequence
Planning is progressive: Phase 1 (research, feasibility and baseline) is the only active phase; later phases are provisional and defined from its findings. Native work is paused indefinitely.
## Consequences
Positive: reuse of mature infrastructure. Negative: dependence on a proprietary vendor and on Rosetta 2 availability; limited ability to modify closed components; the former "No Wine, No CrossOver, No Rosetta" project identity is retired for active work. Anything derived from leaked or unauthorized material stays excluded, including projects built for such inputs (see the upstream registry).
## Alternatives considered
Continue native-first; maintain both tracks at 75/25; a generic Wine-based stack without CrossOver.
@@ -0,0 +1,20 @@
# ADR 0006: Retire in-tree native-first workspace to tag `native-first-final`
Status: **Accepted.** Owner directive amending [ADR 0005](0005-crossover-hybrid-direction.md).
## Context
ADR 0005 pivoted BetterXen's active engineering track to a CrossOver-based hybrid architecture for Apple Silicon while keeping the paused native-first implementation (`crates/`, `app/`, `benchmarks/`, `experiments/`, `fixtures/`, `fuzz/`, legacy scripts, legacy CI, and legacy native docs) in-tree.
Keeping two unrelated Rust workspaces, ~20 native-only scripts, dual CI workflows, and hundreds of paused native files in-tree creates maintenance drag, broken script assumptions, and onboarding noise for contributors and coding agents working on the 6-track hybrid architecture.
## Decision
- **Retire the in-tree native-first codebase, scripts, workflows, and native-only documentation from `main`.**
- **Preserve the complete native-first history permanently at Git tag `native-first-final`.** Nothing is lost; any future work that needs an archived component (for example, RDNA 2 decoder tables if Milestone M2 activates Branch D2 shader transpilation) can selectively inspect or retrieve it from `native-first-final`.
- Keep only active hybrid source, frozen cross-track contracts (`abi/`), native ARM64 tooling (`launcher/`), x86-64 PE32+ shims (`shims/`), shader classification/transpilation (`shader-transpiler/`), auto-discovered conformance binaries (`tests/conformance/`), repository hygiene checks (`scripts/audit/docs_hygiene.py`), and active governance/hybrid documentation (`docs/`).
## Consequences
- **Positive:** Single Cargo workspace at repo root; single build/CI surface (`hybrid-ci.yml` + `hygiene.yml`); zero broken legacy scripts; clean 6-track ownership for 5–8+ concurrent contributors and coding agents.
- **Negative:** Native-only open pull requests targeting the retired `crates/` layout are superseded by the hybrid track; revisiting native-first execution requires checking out `native-first-final` or filing a focused hybrid issue.
@@ -0,0 +1,45 @@
# ADR 0007: API-set win32_bridge shims are not reached under CrossOver
Status: **Accepted** (2026-11-26, issue #437). Independently verified on CrossOver 26.0 and CrossOver 26.3 on Apple Silicon.
## Context
`shims/win32_bridge/` builds six DLLs named after Windows API sets:
`api-ms-win-core-psm-appnotify-l1-1-0`, `api-ms-win-core-psm-appnotify-l1-1-1` and four `ext-ms-win-rtcore-ntuser-*` forwarders to `user32.dll`. A guest that imports those names statically is expected to load the BetterXen files placed next to the EXE. #437 reports that under CrossOver 26.3 it does not: Wine answers the names itself, even with `WINEDLLOVERRIDES=<name>=n,b` and the shim files in the EXE's directory.
## Evidence
`tests/conformance/test_apiset_resolution` imports one export from each of the six DLLs through the PE import directory, then reports for every name the module that owns the name and the module the loader bound the import address table slot to.
Run on an Apple M-series Mac, macOS 27.2.1, Rosetta 2, **CrossOver 26.0 (`26.0.0.39794`)**, bare prefix, with the override list from `bx-cli` (`SHIM_DLL_OVERRIDES`) and `build-shims/bin` as the EXE directory:
| Import name | Served by | Module that owns the name | Module the import is bound to |
| --- | --- | --- | --- |
| `api-ms-win-core-psm-appnotify-l1-1-0` | host | `c:\windows\system32\twinapi.appcore.dll` | same |
| `api-ms-win-core-psm-appnotify-l1-1-1` | host | `c:\windows\system32\twinapi.appcore.dll` | same |
| `ext-ms-win-rtcore-ntuser-message-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
| `ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
| `ext-ms-win-rtcore-ntuser-window-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
| `ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
`WINEDEBUG=+loaddll` shows `Loaded` records for `user32.dll` and `twinapi.appcore.dll` (both builtin) and none for any of the six shim files. `--expect shim` fails 0/6, so the fixture does distinguish the two outcomes.
This behaviour was independently reproduced on **CrossOver 26.3** on Apple Silicon (`bx-cli run` with the shim directory and direct loader runs with `WINEDEBUG=+loaddll`), yielding the exact same 6/6 host resolution (`twinapi.appcore.dll` and `user32.dll`, both builtin, with no `Loaded` records for the six shim files) and `--expect shim` exiting 1. The internal Wine mechanism is not claimed here; this records observed loader behaviour.
## Decision
Rely on Wine's built-ins. Under CrossOver the six API-set shims are not part of the supported path: the host answers window and message calls through `user32.dll` and PSM registration through `twinapi.appcore.dll`.
- The six DLLs stay in the tree, built and export-checked, and are still exercised by explicit full-path loads (#431).
- No attempt is made to make them win name resolution. That would depend on undocumented Wine API-set behaviour (#350) and, within this issue's scope, on patching or redistributing CrossOver or Wine components, which is out of scope.
- Offline PSM behaviour that a title needs must live somewhere a static import actually reaches. This ADR does not choose that place.
## Consequences
- `test_apiset_resolution` records the current behaviour (`--expect host`) and fails when it changes. If a CrossOver build starts loading the shims, run it with `--expect shim` and revisit this ADR.
- `test_integration_boot` continues to report `shim_backing` as pending for these six names under CrossOver.
- Documentation describes the bridges as Windows-only stubs that CrossOver does not load for static imports.
## Not claimed
Nothing here shows Xbox title compatibility, behaviour on Xbox hardware, or behaviour on CrossOver builds outside 26.0 and 26.3. Evidence class: local Apple Silicon runs.
Loaded 100 of 358 files, more files were not shown because too many files have changed in this diff. Show more