Compare commits

...
Author SHA1 Message Date
ates a402287474 research: publish Workstream B D3DMetal memory findings (#473)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 01:21:20 +03:00
atharvranjan 8cc2f8ffbc research: publish Workstream A memory allocation and resource correctness findings (#473)
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 15:44:08 -06:00
atharvranjan 9ae6d1ee70 research: record independent D3DMetal memory probes for #473
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 13:31:00 -06: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
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
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
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
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
3058 changed files with 282456 additions and 74 deletions

No files matched your search

+25 -1
View File
@@ -10,9 +10,33 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Added
- `bx-cli run` gained `--timeout <secs>`, cleanup of the launcher process group and the selected bottle or prefix on timeout, SIGINT, SIGTERM or SIGHUP, `--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 Workstream A research for #473: hashed historical evidence, corrected M4 footprint/retirement probes, matched pooling traces, texture/alias readbacks and an ownership feasibility matrix. Urgent-pressure stops and accepted invalid placement calls remain explicit failures/limitations. Pooling reduced measured allocation-call cost but did not establish a general application benefit; physical zero-copy and independent acceptance remain unestablished. Production shims, ABI and #464 are unchanged.
- Added the collaborative D3DMetal memory research workspace for #473, with an original six-check standalone probe, an isolated CrossOver runner and two raw Apple M4 run records. This host returned E_NOTIMPL for both existing-memory heap opens, while custom L0 heaps and fence-synchronized persistent-map buffer readback matched. Physical zero-copy, memory overhead, other Apple Silicon generations and independent acceptance remain unverified; #464 production implementation is unchanged.
- 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).
+16 -16
View File
@@ -9,13 +9,13 @@
![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(M0)-d29922)
![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)
</div>
> [!IMPORTANT]
> **Experimental status.** BetterXen is an active, open-source compatibility engineering project currently at **Milestone M0** (cross-compiled shim foundation and live CrossOver/Rosetta smoke tests verified on synthetic PE32+ workloads). **Commercial Xbox game execution is not yet supported.** CrossOver, Rosetta 2, and D3DMetal are externally installed dependencies and are never bundled or redistributed.
> **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.
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.
@@ -33,9 +33,9 @@ BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Ro
```mermaid
flowchart LR
M0["M0: Foundation & Shims\n(Merged #406)"]:::done
M1["M1: Boot to D3D12\n(Active — Milestone #17)"]:::active
M2["M2: First Frame &\nShader Gate"]:::planned
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
@@ -50,16 +50,16 @@ flowchart LR
Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
### Active Milestone — [M1: Startup Shims to `D3D12XboxCreateDevice`](https://github.com/MacosPorters/betterxen/milestone/17)
### Active Milestone — [M2: First Rendered Frame & Shader Format Gate](https://github.com/MacosPorters/betterxen/milestone/18)
| Track | Focus | Visual Status | Live Issues |
| --- | --- | --- | --- |
| **Track A** | `bx-cli` supervision, `clwb` VEH + crash dumper, Win32 bridge | `🟨🟨🟨` *(3/3 PRs open)* | [View Track A](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+A%22) |
| **Track B** | `xmem.dll` core + physical/scatter pages, `XCRDAPI.dll` DirectStorage | `🟨🟨🟨` *(3/3 PRs open)* | [View Track B](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+B%22) |
| **Track C** | `d3d12_xs.dll` COM proxy (D3DMetal 3.0), `xg_xs.dll` texture computer | `⬜⬜` *(needs contributors!)* | [View Track C](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+C%22) |
| **Track D** | `dxbc-accc` FSPX C ABI bridge, `d3dmetal-native` harness | `🟨⬜` *(1 PR open, 1 ready)* | [View Track D](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+D%22) |
| **Track E** | `xgameruntime.dll` offline GDK, `AcpHal`/`xapu`/`chad`, `GameInput` | `🟨🟨` *(2/2 PRs open)* | [View Track E](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+E%22) |
| **Track F** | End-to-end synthetic boot fixture (`test_integration_boot`) | `🟨` *(1/1 PR open)* | [View Track F](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+F%22) |
| **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) |
`🟩` Merged & verified · `🟨` PR open / in review · `⬜` Open & ready to claim
@@ -67,9 +67,9 @@ Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
| 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`) | 🟢 **Merged (`#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`, audio queue stubs) | 🔵 **Active ([Milestone #17](https://github.com/MacosPorters/betterxen/milestone/17))** |
| **M2 — First Frame & Shader Gate** | `PresentX` → `IDXGISwapChain3::Present` via D3DMetal 3.0; inspect runtime shaders to select DXIL fast path vs. `ACCC`/`FSPX` RDNA 2 transpilation | ⚪ Planned |
| **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 |
@@ -132,7 +132,7 @@ The repository is organized into disjoint track directories around a single froz
| [`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 |
| `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 |
+6
View File
@@ -43,3 +43,9 @@ EXPORTS
XGameUiShowTextEntryAsync
XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync
XNetworkingQuerySecurityInformationForUrlAsync
InitializeApiImpl
InitializeApiImplEx
InitializeApiImplEx2
UninitializeApiImpl
QueryApiImpl
XErrorReport
+6
View File
@@ -14,14 +14,20 @@
- [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.
## Research, Testing & Licensing
- [Workstream A Memory and Resource Research](research/d3dmetal-zero-copy/allocation-profiling/README.md) — Historical evidence inventory, footprint/retirement correction, xmem feasibility, pooling and texture protocols; local observations and explicit review/pressure limitations for #473.
- [D3DMetal Unified-Memory and Zero-Copy Research](research/d3dmetal-zero-copy/README.md) — Shared six-check synthetic probe, per-host raw logs and evidence limits for #473 / #464.
- [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.
## Governance, Security & Legal
@@ -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.
+1 -1
View File
@@ -9,7 +9,7 @@ BetterXen is organized so **5 to 8+ contributors** can develop the CrossOver-bas
| `abi/` | Shared (frozen) | C headers + `.def` | Cross-DLL contracts (`bx_log.h`, `bx_config.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical DLL export lists |
| `launcher/` | Track A | Rust (`aarch64-apple-darwin`) | Native ARM64 macOS CLI (`bx-cli`), PE32+ static probe (`bx-probe`), JSONL trace aggregator (`bx-telemetry`) |
| `shims/runtime_veh/` | Track A | C++20 (`mingw-w64`) | `bx_runtime_veh.dll`: `clwb` VEH handler, `adcx`/`adox` tripwire, Lockhart/Anaconda config, JSONL trace logger |
| `shims/win32_bridge/` | Track A | C++20 (`mingw-w64`) | PSM AppNotify stubs + `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders |
| `shims/win32_bridge/` | Track A | C++20 (`mingw-w64`) | PSM AppNotify stubs + `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders; not loaded for static imports under CrossOver ([ADR 0007](../adr/0007-api-set-shims-under-crossover.md)) |
| `shims/xmem/` | Track B | C++20 (`mingw-w64`) | `xmem.dll`: physical/virtual/scatter memory allocator, `__XMemAllocationHooks__`, 16 GB Lockhart cap |
| `shims/xcrdapi/` | Track B | C++20 (`mingw-w64`) | `XCRDAPI.dll`: DirectStorage async I/O factory, queues, and decompression |
| `shims/d3d12_xs/` | Track C1 | C++20 (`mingw-w64`) | `d3d12_xs.dll`: Xbox D3D12 COM proxy over Wine `d3d12.dll` (D3DMetal 3.0), `PresentX`, placed resources |
+169
View File
@@ -0,0 +1,169 @@
# D3DMetal and Apple GPU limits for a shader translator
Constraints that a translator emitting shaders for D3DMetal on Apple Silicon has to
handle (#453). Writing the translator is out of scope.
The note has two parts:
- [Measured constraints](#measured-constraints) come from
`tests/conformance/test_d3dmetal_gpu_limits`, an original synthetic D3D12 compute
fixture checked against values computed on the CPU. These are the only items the
roadmap links to. They are a local Apple Silicon run by the implementer, class A for
the stated host only, not independently reproduced.
- [Unverified reports](#unverified-reports-not-evidence) are observations a contributor
posted on #453 from local builds of another project running a commercial title. They are
**not evidence** under [AGENTS.md](../../AGENTS.md) §5–6 and must not steer the plan
until a synthetic workload reproduces them. They are kept only as leads for writing such
workloads.
Nothing here is an Xbox hardware result, and nothing generalizes beyond the D3DMetal
version named.
## Measured constraints
### `WaveSize(64)` is created but not run
`wave.control` (no `WaveSize`) and `wave.wavesize64` (`[WaveSize(64)]`, SM 6.6) record,
for each thread, the wave width, its lane index and the dispatch index of its wave's first
lane.
The control passes the check D3D12 actually guarantees: every thread reports the same
width, and within each wave the lane indices are a permutation of `0..W-1`. No particular
thread-to-lane order is assumed. On D3DMetal 4.0b3:
- the device reports `WaveLaneCountMin = WaveLaneCountMax = 32`;
- the control runs at width 32;
- the wave64 pipeline is **created without error but never runs**: its output buffer keeps
the sentinel.
So a translator cannot rely on pipeline creation failing. A program written for a 64-lane
wave has to be emitted as 32-lane code, with its two halves made to agree wherever the
original wave acted as one.
### Kernels using SM 6.6 64-bit atomics are created but not run
`atomic64.image` runs a 64-bit `InterlockedAdd` (low halves carrying into the high half)
and an `InterlockedMax` (decided by the high half) on a `RWTexture2D<uint64_t>` over
`DXGI_FORMAT_R32G32_UINT`. `atomic64.buffer` runs the same operations on a raw buffer. Each
kernel also writes a plain 64-bit marker next to its atomics, which shows whether the kernel
ran at all. On D3DMetal 4.0b3:
- The device reports `AtomicInt64OnTypedResourceSupported` and
`AtomicInt64OnDescriptorHeapResourceSupported` as supported, and both pipelines are
created without error.
- Neither kernel runs. The atomic results and the markers all read back as their initial
zeros, on the texture and on the raw buffer alike.
- A throwaway variant with the atomics removed but the markers kept wrote 8/8 markers.
That shows the readback path is sound and the skip comes from the atomics.
So these kernels are silently skipped, on raw buffers as well as images. This is
consistent with d3dmetal-native's `d3d12-atomic64-test` reading back zeros in the
[d3dmetal-harness](../../shader-transpiler/crates/d3dmetal-harness/README.md) evaluation
on D3DMetal 3.0. A translator has to lower 64-bit atomics to 32-bit operations.
### Lock-based emulation needs a sufficient retry cap and both fences
`lock64.cap64` and `lock64.cap1024` emulate both operations with a per-texel lock word,
with 32 contending threads per texel and a bounded number of tries:
1. take the lock with `InterlockedCompareExchange` 0→1;
2. `DeviceMemoryBarrier()` (**acquire**: the data reads are ordered after taking the lock;
`globallycoherent` gives visibility, not ordering);
3. update the two 32-bit halves;
4. `DeviceMemoryBarrier()` (**release**);
5. free the lock with `InterlockedExchange`.
A thread that runs out of tries counts a drop instead of spinning on. The 1024-try run is
required to drop nothing and to match the CPU reference exactly. The 64-try run is
reported. On D3DMetal 4.0b3, in three runs each:
- **1024 tries:** nothing dropped, 16/16 values exact, about 15,000–18,000 tries in all.
- **64 tries:** 96–108 of 512 updates dropped.
So a low cap trades a hang for silently lost updates. With 32 contending threads, 64 tries
is already too low.
The loop shape matters. The critical section sits **inside** the retry loop, so a lane
that wins finishes it in the same iteration, and no lane waits for another lane to leave a
loop. The fixture does not run the classic shape (`while (!acquire()) {}` followed by the
critical section). There, the winning lane can be parked at the loop's reconvergence point
behind the lanes still spinning, and on a GPU without independent forward progress for
each thread that could hang the queue. Apple's shader converter prints `Warning:
Undefined: Shader might rely on forward progress/persistent thread` even for the safe
shape.
## Fixture results
A local run by the implementer on 2026-11-26. Class A for this host only; not
independently reproduced, not CrossOver 26.3, and not an Xbox hardware result.
| | |
| --- | --- |
| Host | Apple M3 Pro, macOS 27.2.1 (26B131), Rosetta 2 |
| Wine | CodeWeavers Wine 11.0 built from CodeWeavers' published source; CrossOver itself was not installed |
| D3DMetal | 4.0b3 from Apple's Game Porting Toolkit (x86_64; SHA-256 of the binary starts with `b16aab78127d`), user-supplied |
| Shaders | DXC 1.9.2609 via `shaders/compile.sh`; the same DXC reproduces the d3dmetal-harness `fill_cs66` container byte for byte (SHA-256 `7df11b63…`) |
| Command | `ROSETTA_ADVERTISE_AVX=1 WINEDLLOVERRIDES="d3d12,d3d12core,dxgi=b" wine build-shims/bin/test_d3dmetal_gpu_limits.exe` in a fresh prefix |
| Runs | 3, identical outcomes apart from the 64-try drop counts; exit 0, `SUMMARY: 4 required checks, 0 failed` each time |
| Check | Outcome |
| --- | --- |
| `device.shader_model` | 6.6 (the fixture skips with exit 77 below 6.6) |
| `wave.reported` | `WaveOps=1`, lane count min 32, max 32 |
| `wave.control` | ran at width 32, lanes a permutation within each wave (required: pass) |
| `wave.wavesize64` | created but not run (output still sentinel) |
| `atomic64.reported` | typed and descriptor-heap 64-bit atomics reported as supported |
| `atomic64.buffer` | not run: marker 0/8, atomic values 16/16 still zero |
| `atomic64.image` | not run: marker 0/8, atomic values 16/16 still zero |
| `lock64.cap64` | 108, 96 and 108 of 512 updates dropped (values not compared) |
| `lock64.cap1024` | 0 of 512 dropped, 16/16 values exact (required: pass) |
Still to do for the issue's validation requirement: an independent run on CrossOver 26.3
(D3DMetal 3.0) by another contributor.
## Unverified reports (not evidence)
Reported on #453 from local VIctory-macOS-based builds running a commercial title on one
host. None of this is a BetterXen measurement, no code or shader from that project is
used, and none of it may be cited by the roadmap or a milestone gate. Each item names the
synthetic workload that would turn it into evidence.
- **Splitting wave64 programs.** Operations that need care when the two halves must agree:
- wave reductions;
- first-lane and indexed lane reads;
- the 64-bit lane mask read as data;
- cross-half permutes;
- scalar values spilled into vector lanes;
- group barriers, which are only safe where both halves provably reach them.
The reporter found a uniformity analysis of the program's values, with barriers placed
only after uniform branches, made most such programs translate exactly. Where agreement
cannot be proven and each half runs as its own wave, a group sync that not every lane
reaches must become a memory fence without the group wait. *Workload needed:* SM 6.6
wave64-style kernels with each of these patterns, checked half by half.
- **Helper lanes in a spin lock.** In a pixel shader, helper lanes must not take part in
such a lock: their atomics have no effect, so they never win and spin to the cap. This
was reported as a hard queue hang with no macOS GPU timeout logged. A cap of 2^16 was
reported to hang while 2^10 did not; whether the cap or the helper lanes caused it was not
separated. *Workload needed:* a pixel shader with a lock-protected 64-bit update across
triangle edges.
- **Mesh output size.** Metal refuses mesh pipelines whose per-vertex outputs exceed 32,768
bytes, counting the aligned layout (distances, position, then outputs in register order,
each aligned to its own size). A refused pipeline submitted anyway was reported to hang
the queue under Wine. *Workload needed:* mesh shaders whose output size crosses 32 KiB
only once alignment is counted.
- **Apple shader compiler crash.** `MTLCompilerService` was reported to crash in register
allocation on mesh pipelines whose pixel shader writes several render targets. The
reported cause was output stores merged before all their values are defined, and the
reported fix was emitting each output row's stores after its values. *Workload needed:* a
mesh and pixel pair with several render targets and late-computed outputs.
- **No zero-copy heaps.** D3DMetal 4.0b3 was reported to answer
`ID3D12Device3::OpenExistingHeapFromAddress` with "Not implemented". *Workload needed:*
a fixture that calls it on a page-aligned allocation.
## Regenerating the shaders
`tests/conformance/test_d3dmetal_gpu_limits/shaders/compile.sh` regenerates the committed
headers with Microsoft's DXC release v1.9.2609 (`dxc_2026_09_29.zip`, SHA-256
`ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1`, the same package the
d3dmetal-harness records), running `bin/x64/dxc.exe` under a Wine loader.
@@ -0,0 +1,3 @@
# Preserve Windows stdout/stderr bytes as recorded, including CRLF line endings.
results/**/stdout.txt -text whitespace=cr-at-eol
results/**/stderr.txt -text whitespace=cr-at-eol
@@ -0,0 +1,95 @@
# D3DMetal unified-memory and zero-copy research
Collaborative research for [#473](https://github.com/MacosPorters/betterxen/issues/473), informing [#464](https://github.com/MacosPorters/betterxen/issues/464). Maintainer-agreed participants are @Arths17, @skakwy and @CarReal8917; participation is not an exclusive claim. The shared branch is [`research/d3dmetal-zero-copy`](https://github.com/MacosPorters/betterxen/tree/research/d3dmetal-zero-copy). It is based on `origin/main` commit `f7fb52bc56f671f9da7109f8aef8d3f04de59aee` and is not being merged into main.
This directory contains an original synthetic probe, a runner, separate run records and [consolidated findings](findings.md). It neither imports nor tests the production `xmem` or `d3d12_xs` implementation. @devil8blade retains the implementation of #464. Findings here do not certify that implementation or establish Xbox compatibility.
## Build and run
Requirements: Apple Silicon macOS, an externally installed licensed CrossOver with D3DMetal, supported Rosetta 2, Python 3.11+, and native ARM64 MinGW-w64 cross-compiler tools. Nothing proprietary is downloaded or bundled. The compiler is an ARM64 host executable; its output is a Windows x86-64 guest executable.
Use an existing **win64** CrossOver bottle. The runner copies it into a fresh scratch directory, changes only that temporary copy, builds outside the checkout, selects D3DMetal, runs with `ROSETTA_ADVERTISE_AVX=1`, and enforces a **30-second** process timeout. No BetterXen shim directory is added to the search path. It prints the resolved `d3d12.dll` path and checks that `d3d12_xs.dll` is absent. The original bottle and the checkout are not written by the runner.
```sh
# Fetch this branch even in a clone that normally fetches only main.
git fetch origin research/d3dmetal-zero-copy:refs/remotes/origin/research/d3dmetal-zero-copy
git worktree add --detach ../betterxen-zero-copy origin/research/d3dmetal-zero-copy
cd ../betterxen-zero-copy
python3 docs/research/d3dmetal-zero-copy/run.py \
--bottle "/absolute/path/to/an/existing/CrossOver/bottle" \
--scratch /tmp/bx-uma-verify/run-01
```
The scratch directory must not exist. `--crossover /Applications/CrossOver.app` and `--compiler x86_64-w64-mingw32-g++` select non-default installations. Existing bottle configuration can affect a run; record relevant settings and verify the loaded backend. The runner uses a small child-environment allowlist and never forwards host credential variables.
The runner invokes this compilation, with absolute scratch paths in the actual receipt:
```sh
x86_64-w64-mingw32-g++ -std=c++20 -O2 -static -static-libgcc -static-libstdc++ \
-Wall -Wextra -Werror probe.cpp -o probe.exe -lkernel32
```
Outputs are `probe.cpp`, `probe.exe`, `receipt.json`, `stdout.txt` and `stderr.txt`. The receipt records source/executable SHA-256, compiler command/result, PE format/imports, host, software, environment and run outcome. Temporary bottle contents are removed after its private wineserver is stopped. The caller removes the remaining scratch files **after preserving the selected research records**.
Two launch attempts in the initial experiment stopped before the probe because the host ClamAV database was absent. For the original executable compiled locally from this source, the temporary bottle uses `AllowUntrusted=1` and `AntiVirusScan=untrusted`; the source bottle's scanner settings are unchanged. This does not bypass any dependency license or activation requirement.
## Fixed six-check baseline
Do not change these checks to improve an outcome. Unsupported HRESULTs and not-run paths are evidence, not passes. Exit 0 means no observed data/submission mismatch; it does **not** mean every capability is supported. Inspect each printed result.
| Check | Fixed experiment |
| --- | --- |
| 1: device | Obtain `ID3D12Device3`; query `ARCHITECTURE1` (`UMA`, `CacheCoherentUMA`, `TileBasedRenderer`, `IsolatedMMU`) and `D3D12_OPTIONS.ResourceHeapTier`. |
| 2: existing memory | `OpenExistingHeapFromAddress` on 64 KiB `VirtualAlloc` (`MEM_COMMIT\|MEM_RESERVE`, `PAGE_READWRITE`); `OpenExistingHeapFromFileMapping` on 64 KiB anonymous read/write mapping. Print HRESULTs; if supported, place a buffer and check CPU writes by GPU readback with no staging upload. |
| 3: custom/placement | Six heap cases: WRITE_BACK/L0/ALLOW_ALL; WRITE_COMBINE/L0/ALLOW_ALL; WRITE_BACK/L0 with each of the three ALLOW_ONLY restrictions; WRITE_BACK/L1/ALLOW_ALL control. Place a UAV-capable buffer and 64×64 RGBA8 texture together on one WRITE_BACK/L0 heap at disjoint allocation-info-aligned offsets; run `WriteToSubresource`/`ReadFromSubresource` round-trip. |
| 4: persistent Map | Two CPU→GPU copies with different magic pairs, followed by UPLOAD→placed GPU copy and direct CPU read through the original pointer. Fence after each; no buffer Unmap/remap or CPU→GPU staging upload in the forward direction. |
| 5: latency | WRITE_BACK/L0 at 64 KiB and 256 MiB; WRITE_COMBINE/L0 at 256 MiB; UPLOAD at 256 MiB, in that order. Touch each 64 KiB interval before timing, then 5 warmups and 40 timed submissions. Every iteration updates offsets 0 and size−64, copies 64 bytes from each end to READBACK and checks all 32 words after its fence. Print total ms, average ms/submit, N/40 and warmup matches. |
| 6: dirty pages | 64 KiB `MEM_WRITE_WATCH`; write bytes at offsets 0 and 16384; `GetWriteWatch(WRITE_WATCH_FLAG_RESET,...)`; print return, count, granularity and dirty offsets. |
All CUSTOM test heaps use explicit CPU-page and memory-pool properties; UPLOAD uses the standard heap type. The six creation cases use 2 MiB heaps, mixed placement uses 2 MiB, and the persistent coherence buffer uses a 64 KiB heap. The latency tests use exactly the named buffer/heap sizes and copy only 128 bytes per submit. READBACK buffers are 128 bytes. Latency includes CPU writes, command-list reset/encoding, transitions, queue submission, fence wait, device-status query and comparison; it is not GPU-only time. Prefault and warmups are excluded. No API-validation or verbose loader tracing is enabled in the timed baseline.
The 64 KiB prefault stride follows the requested experiment; it does not touch every physical 16 KiB host page in the 256 MiB region. A separately named, fully resident memory-overhead experiment is needed before interpreting resident allocation sizes.
## Synchronization and lifetime
The CPU finishes stores and executes an x86 store fence before submission. Each submission has its own D3D12 fence value and a bounded event wait. CUSTOM buffers transition from COMMON to COPY_SOURCE/COPY_DEST and back; UPLOAD stays GENERIC_READ and READBACK stays COPY_DEST. The CPU overwrites or reads GPU-used memory only after the previous fence. Resources remain mapped until release, with placed resources destroyed before their heaps. Wrapping allocations, mapping views and mapping handles are retained through any successful visibility test and released after resources and GPU completion.
The texture is in COMMON, mapped with a null output pointer before the CPU subresource methods, then unmapped after that separate round-trip. A CPU texture round-trip is not a GPU texture coherence test. The baseline does not test simultaneous CPU/GPU access, atomic interoperability, console flush APIs, multiple queues, aliasing barriers, resource reuse while work is in flight, render-target/depth texture placement, other formats or texture GPU readback.
These rules follow the public [Map contract](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-map), [resource barriers](https://learn.microsoft.com/en-us/windows/win32/direct3d12/using-resource-barriers-to-synchronize-resource-states-in-direct3d-12) and [CPU texture access requirements](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-writetosubresource). They do not establish console semantics.
## Backend receipt and supplemental investigations
A selected setting is insufficient to identify the backend. For a **separate, untimed diagnostic** use a new scratch directory:
```sh
python3 docs/research/d3dmetal-zero-copy/run.py \
--bottle "/absolute/path/to/an/existing/CrossOver/bottle" \
--scratch /tmp/bx-uma-verify/backend-receipt --receipt-only
```
This mode only creates a device, repeats existing-memory wrapping, and pauses for 10 seconds to permit OS loaded-library inspection; it does not replace or change the six-check baseline. The runner enables `--debugmsg -all,+loaddll,+d3d12`. Inspect the specific probe PID with `lsof -n -p <pid>` or `vmmap <pid>` and preserve the app's `apple_gptk/.../d3d12.dll`, `dxgi.dll` and `D3DMetal.framework` paths. Sample only the intended process, not another contributor's Wine session. Avoid including account names or personal paths in committed diagnostics; disclose any excerpts/redactions. The initial runtime inspection is recorded as an excerpt in its run directory.
Supplemental experiments must be versioned separately and must not alter baseline sizes, checks or iteration counts. Follow-up work includes:
- Resident/physical memory at allocation, prefault, submission and retirement; record measurement tool, baselines, page residency, compression, pressure and variability. Virtual size alone is insufficient.
- Copy profiling that distinguishes shared storage, full-buffer shadow copies and dirty-page copies. Similar small-copy latency is consistent with sharing but does not prove physical aliasing or absence of internal copies.
- GPU texture readback/coherence by format/layout and render/depth usage. Buffer success does not establish these.
- Dirty-page fallback with reset/rearming races, alignment, coalescing, explicit copies, budget accounting and concurrent writes. Baseline `GetWriteWatch` success does not establish a working fallback.
## Independent results and acceptance
Create a new `results/<date>-<chip>-<contributor>-<run>/` directory for every run. Retain raw benchmark stdout/stderr unedited (the local `.gitattributes` preserves their Windows CRLF bytes), exact software/hardware receipts, timeout/exit status, backend evidence, source revision/hash and run limitations. Do not commit the executable, bottle, caches, proprietary frameworks or credentials. A result owner may append new runs; do not rewrite another contributor's measurements. DCO-sign commits with the contributor's existing Git identity and push normally without force. If another contributor updated the shared branch, fetch and reconcile before pushing.
An independent reviewer must re-derive expected values and API legality from primary sources. The author of this probe has not certified it independently. Require independent results from at least two contributors on at least two Apple Silicon generations, with repeated sessions before scaling claims. M1–M5 are coverage targets, not measured support. Follow the full evidence checklist in #473; unresolved mechanisms remain class U. Hardware readbacks are local class A observations, not independent acceptance or Xbox hardware validation.
## Provenance and primary sources
`probe.cpp` and `run.py` are newly authored synthetic research under the repository's GPL-3.0-or-later license. No upstream implementation or emulator code was copied. MinGW-w64 14.0.0 headers and GCC 16.2.0 are externally installed build tools on the initial host. CrossOver 26.3.0.39832, D3DMetal 3.0 and Rosetta 2 are externally installed runtime components; nothing proprietary is redistributed. Existing [upstream registry](../upstream-registry.md) and [reuse matrix](../component-reuse-matrix.md) cover runtime research; this work adds no vendored dependency. Review exact file licenses and update those records before adopting any future third-party source.
Public API references used to author and review the experiments:
- [Architecture1 flags](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_feature_data_architecture1) and [heap properties](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_heap_properties).
- [OpenExistingHeapFromAddress](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device3-openexistingheapfromaddress) and [OpenExistingHeapFromFileMapping](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device3-openexistingheapfromfilemapping).
- [CreatePlacedResource](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource), [Map](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-map), [WriteToSubresource](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-writetosubresource) and [ReadFromSubresource](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-readfromsubresource).
- [GetWriteWatch](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-getwritewatch).
@@ -0,0 +1,55 @@
# Workstream A memory and allocation research
Research for [#473](https://github.com/MacosPorters/betterxen/issues/473), on an isolated worktree based on `9ae6d1ee7092b6021aad075531f50ba60de4fd53`. This work does not change production shims, ABI, main or the six-check baseline. No commit/push has been authorized. Local runs are author observations, not independent acceptance or Xbox compatibility.
Start with the [research report](report.md) and [existing evidence inventory](inventory/README.md), [ownership feasibility matrix](inverted-ownership.md), [resource/lifetime contract](../gpu-correctness/contracts/resource-placement-lifetime.md), [optional allocator assessment](allocator-assessment.md) and [texture fixtures](../gpu-correctness/textures-and-resources/README.md). See [footprint findings](footprint-findings.md), [pooling findings](pooling-findings.md) and [texture/alias findings](../gpu-correctness/textures-and-resources/findings.md). Findings and review status are tracked in #473.
## Local protocol A2
`run.py` is an A-local harness; shared helpers and shared protocol files remain unchanged pending reciprocal coordination. `support.h` reuses the preserved original supplemental queue/buffer and full-consumption shader logic, formatted for readability, with shader capture added. It does not run B's dirty-page/coherence/tracking suite. The historical code's exact original bytes/hashes remain in `inventory/frozen-phase2/`.
Requirements: native ARM64 macOS, licensed externally installed CrossOver/D3DMetal/Rosetta, existing win64 bottle, native MinGW-w64 C++20 compiler, Python 3.11+, public Apple Command Line Tools. Compilation uses `-O2 -static -static-libgcc -static-libstdc++ -Wall -Wextra -Werror`; observer uses `xcrun clang++ -arch arm64`. Exact commands, native-tool architecture/linkage, source/executable/shader hashes and environment are retained in each receipt. The observed Wine compiler warns that optimization flag 0x8000 is ignored; no compiler optimization claim is inferred.
```sh
python3 docs/research/d3dmetal-zero-copy/allocation-profiling/run.py \
--bottle "/absolute/path/to/an/existing/win64/bottle" \
--scratch /tmp/bx473-a-memory-run --suite memory
python3 docs/research/d3dmetal-zero-copy/allocation-profiling/run.py \
--bottle "/absolute/path/to/an/existing/win64/bottle" \
--scratch /tmp/bx473-a-pool-run --suite pool
python3 docs/research/d3dmetal-zero-copy/allocation-profiling/run.py \
--bottle "/absolute/path/to/an/existing/win64/bottle" \
--scratch /tmp/bx473-a-texture-run --suite texture
```
Each scratch directory must be new and outside the checkout. Add `--smoke` for a reduced harness check, recorded separately. The runner copies the source bottle privately, selects D3DMetal, sets ROSETTA_ADVERTISE_AVX=1 and WINEDEBUG=-all, rejects a loaded d3d12_xs shim in the guest and captures loaded framework/DLL/Rosetta paths at a paused checkpoint. It records missing tools and failures. It stops only its private Wine server and checks the source configuration unchanged. It does not download/install or redistribute proprietary components. Disposable bottle scanner/trust settings permit the original locally built probe; source bottle settings are untouched.
One A process owns `/tmp/betterxen-473-gpu.lock` for a batch. Other contributors must coordinate the single-GPU-workload rule; this local advisory lock cannot exclude unrelated applications. No profiling/polling is performed inside allocation API timing windows. A process timeout is 240 seconds; GPU fence waits are bounded at 10 seconds. The initial A2 sweep used free-percentage guards only and was interrupted after observing kernel pressure level 2. A-local-2.1 additionally required kern.memorystatus_vm_pressure_level=0 before each case and at each snapshot. After the requester freed memory and explicitly allowed bounded continuation, A-local-2.2 added an explicit --allow-warning profile that permits level 1 while still stopping at >=2; its receipts record that selection. Default behavior still requires level 0. Warning-profile observations are not relabeled as normal-pressure evidence. It retains the 30%/25% free-percentage guards, but does not interpret those percentages as an OS pressure class. Unreadable pressure also stops the run. The partial A2 profile is not a completed two-session sweep. Existing swap/background load is retained in receipts; no idle-machine benchmark claim is made.
## Footprint correction
For two sessions, run each of 64/256/1024 MiB in a fresh process using CPU-only without graphics, graphics-warmed CPU allocation control, CUSTOM/WB/L0 and UPLOAD. Reverse size/type order in the second session. No optional >1 GiB allocation is part of this run. The graphics cases reuse the historical full-consumption checksum shader, write every source word and validate 256 checksum words after the fence; checksum agreement is not byte-exact evidence for every source word.
Checkpoints: warmed baseline, settled baseline, allocation/placement, Map, full initialization, full GPU consumption, resource release, disposal of command/output/pipeline objects, settled retirement, device release. CPU controls explicitly report GPU consumption not run. DLL/framework handles remain loaded at device release; it is not process exit or a guarantee of runtime-pool reclamation.
At each paused stage retain three proc_pid_rusage snapshots, `footprint -f bytes --swapped`, `vmmap -summary`, mapped-pointer `vmmap -w PID ADDRESS` where applicable, `vm_stat`, memory-pressure and swap readings. Tools execute sequentially, so readings can differ. Three samples at one pause are correlated snapshots, not three independent sessions. Virtual range size, RSS, physical-footprint accounting and graphics retention are reported separately; do not add categories or infer physical page identity.
## Pooling and retirement trace
Compare per-resource CUSTOM/WB/L0 heaps against one 32 MiB heap with placed suballocations, using matched seeds, buffer descriptions/alignment and GPU work. Three fresh-process pairs alternate case order. Each has two warmup cycles and ten measured cycles over 24 live slots with non-aligned requested sizes 65540, 262148, 393220 and 1048580 bytes. Allocate all, verify, free even slots, refill with seeded varied sizes, verify again, free all and check free-list coalescing. No grow/unbounded allocation occurs.
Each ALLOC retains heap/suballocation, placement and Map API timings; FREE retains resource and backing/free-list costs. Initialization, I/O and GPU work are outside these API samples. Cycle time includes them and is descriptive; the live snapshot pause is explicitly subtracted. A one-time pooled heap setup is separately recorded and must be included when comparing first-use costs. No benchmark improvement is promised.
Logical records track live payload, allocation-aligned live bytes, reserved backing, alignment waste, free space and largest free span. Individual heaps have no reusable cross-heap free span; report this as not applicable. Pool slack and logical fragmentation are not process footprint. GPU readback checks leading/trailing guards and an interior region for each live buffer, not every byte. A real gate-delayed queued copy verifies that the allocator withholds a pending range; it opens the gate before waiting and frees only after completion. The trace also rejects a fictitious future retirement value as a policy control. Every reused placed resource is activated; command list reset occurs after completed work and before resources are released. B's independent barrier/fence review remains required.
## Host ceiling and reduced profiles
The requester set a 23 GB RAM-use ceiling. A-local-2.2 records a conservative non-file-cache occupied estimate derived from physical RAM minus free and file-backed pages in vm_stat; this is not an exact Activity Monitor value. Before starting a case it reserves headroom below 23,000,000,000 bytes for twice the source plus 512 MiB (memory suite), or 512 MiB (small suites). It stops at paused checkpoints if the remaining margin falls below 256 MiB. This observation-based guard cannot control concurrent applications; the fixed source/slab caps and urgent-pressure stop remain necessary. A skipped case is recorded as not-run and makes the profile incomplete. No 2 GiB extension is used.
Use --allow-warning only with the requester's explicitly permitted warning-pressure conditions; otherwise default normal-pressure gating remains in force. A ceiling is not a target. Keep all actual reservations, pressure signals, swap changes and raw failures visible.
For the pool omitted-copy control, add --negative-control to --suite pool; the guest must fail with the specific trace guard/interior mismatch. The harness validates that expected failure separately. The texture matrix currently fails its negative-rejection gate on this runtime; all two sessions still run, and the batch returns failure. --suite alias performs the separate valid buffer-inheritance follow-up.
## Bottle receipt correction
Source review found that the historical/plain string insertion of AllowUntrusted matched the commented Bottle heading before the actual section. A22 run receipts preserve that malformed requested-setting line rather than claiming it was applied correctly; the appended scanner setting and actual loaded backend are separately recorded. Current run.py anchors the insertion to the actual section line and checks its construction without writing the source bottle. This configuration-only correction was made after the GPU runs; a post-correction launch is not claimed. Exact prior executed runner snapshots remain in every run bundle.
@@ -0,0 +1,19 @@
# Optional allocator reference assessment
Reviewed 2026-11-26: AMD's [D3D12 Memory Allocator](https://github.com/GPUOpen-LibrariesAndSDKs/D3D12MemoryAllocator/tree/600949266be004553f74c9ef809384380a9d44cf), exact commit `600949266be004553f74c9ef809384380a9d44cf`; the pinned header reports version 3.3.0. This is a public, general-purpose GPUOpen allocation library, with no game/console material used in this assessment.
The exact files reviewed were [LICENSE.txt](https://github.com/GPUOpen-LibrariesAndSDKs/D3D12MemoryAllocator/blob/600949266be004553f74c9ef809384380a9d44cf/LICENSE.txt), [include/D3D12MemAlloc.h](https://github.com/GPUOpen-LibrariesAndSDKs/D3D12MemoryAllocator/blob/600949266be004553f74c9ef809384380a9d44cf/include/D3D12MemAlloc.h) (Git blob `b685a5cd6188519606efaf039cd88c2faffa261a`) and [src/D3D12MemAlloc.cpp](https://github.com/GPUOpen-LibrariesAndSDKs/D3D12MemoryAllocator/blob/600949266be004553f74c9ef809384380a9d44cf/src/D3D12MemAlloc.cpp) (blob `b7ba60a3a4deb0ed466b235b7c5298f91ba5c976`). Both source files carry the full AMD 2019–2026 MIT notice. The MIT grant permits use/modification/distribution while requiring preservation of its notice; it is compatible with inclusion in a GPL-3.0-or-later work under those obligations. This does not license CrossOver/D3DMetal/Rosetta or change their external status.
No source from this project is copied, compiled, linked, modified or adopted here. A's small first-fit trace allocator is original experimental code, not an alternative production allocator. Exact registry/reuse-matrix entries and preserved upstream notices are required before any future source integration; that would be a separately scoped decision.
| Requirement | Pinned source/API assessment | What remains unmeasured |
| --- | --- | --- |
| CUSTOM WB/WC L0 pools | POOL_DESC accepts D3D12_HEAP_PROPERTIES and heap flags; configurable block size/counts provide a plausible fit. | CreatePool/resource behavior under this exact CrossOver/D3DMetal build. |
| Placed buffers/textures | Existing allocator handles resource allocation alignment and heap-tier separation; alias resources are documented. | Our mixed/RT/depth cases through the allocator, not merely raw D3D12. |
| Pool bounds and accounting | Explicit block sizing and max counts can bound reservations; detailed statistics distinguish allocations, blocks and unused ranges. | Memory cost and latency against the A trace; its budget reports are DXGI estimates, not physical residency or BetterXen's unified title budget. |
| Fragmentation | Multiple allocation algorithms/statistics and defragmentation support exist. | BetterXen workloads, fixed-pointer constraints and migration cost. Moving a guest-visible mapped allocation cannot silently preserve pointer identity. |
| Fence retirement | Caller must ensure GPU use is complete before freeing/reassigning allocation/resource storage. Library allocation ownership is not a substitute for application queue/fence tracking. | Multi-queue retirement integration and stress. |
| Inverted CPU ownership | Resource Map remains a public D3D12 operation; allocator metadata cannot add requested CPU-VA or arbitrary scatter/section alias semantics. | No evidence that this library solves the infeasible rows in the [ownership matrix](inverted-ownership.md). |
| Portability/toolchain | Header has a path for externally supplied D3D12-compatible headers; implementation explicitly handles MinGW variants. | No local allocator build/runtime test performed. |
Recommendation: retain it as the first reuse candidate if production pooling is justified, then run the same trace against an externally built pinned version before selecting it. Raw-D3D12 pooling results cannot be presented as this allocator's performance, fragmentation quality or CrossOver compatibility. Documentation/source assessment is class D (project evidence); public D3D12 contracts are class B. Independent review and runtime qualification remain pending.
@@ -0,0 +1,90 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Recalculate descriptive A-local-2 statistics from raw receipts/logs, without editing them."""
import argparse
import hashlib
import json
import math
from pathlib import Path
import re
import statistics
def distribution(values):
s=sorted(values)
if not s: return None
return dict(n=len(s),median=statistics.median(s),minimum=s[0],maximum=s[-1],
p10=s[max(0,math.ceil(len(s)*.1)-1)],p90=s[max(0,math.ceil(len(s)*.9)-1)])
def fields(line):
return dict(re.findall(r'(\w+)=([^\s]+)',line))
def analyze(base,allow_partial=False):
receipt=json.loads((base/'receipt.json').read_text())
result=dict(protocol=receipt['protocol'],suite=receipt['suite'],receipt_sha256=hashlib.sha256((base/'receipt.json').read_bytes()).hexdigest(),
review='author-run; independent acceptance pending',not_run=receipt.get('not_run',[]),cases=[],tool_failures={k:v['exit'] for k,v in receipt['tools'].items() if v['exit']})
for case in receipt['cases']:
name=case['name'];root=base/name;raw=(root/'stdout.txt').read_bytes();out=raw.decode()
if case['exit']!=case.get('expected_exit',0) or case['timed_out']:
if not allow_partial: raise ValueError('unsatisfied case '+name)
result['cases'].append(dict(name=name,exit=case['exit'],status='incomplete or failed; not counted as passed',harness_error=case.get('harness_error'),snapshots=len(case['snapshots']),outcomes=[l for l in out.splitlines() if l.startswith(('OUTCOME ','NEGATIVE','END '))]))
continue
for output,digest in case.get('outputs',{}).items():
if hashlib.sha256((root/output).read_bytes()).hexdigest()!=digest:raise ValueError('changed output '+name+'/'+output)
c=dict(name=name,exit=case['exit'],seconds=case['seconds'],backend=case.get('backend_paths_excerpt',[]))
if receipt['suite']=='memory':
stages={}
for snap in case['snapshots']:
values=[x['data'] for x in snap['samples'] if x.get('exit')==0 and x.get('data',{}).get('return')==0]
if len(values)!=3:raise ValueError('missing native accounting samples')
stage=dict(physical_footprint_bytes=statistics.median(x['phys_footprint'] for x in values),
resident_bytes=statistics.median(x['resident_size'] for x in values))
for tool in ['footprint','vmmap','pressure','swap']:
stage[tool+'_exit']=snap[tool]['exit']
ptr=int(snap['marker'].split('cpu_ptr=')[1],16)
if ptr:stage.update(cpu_pointer_hex=hex(ptr),cpu_pointer_mod_64KiB=ptr%65536,cpu_pointer_mod_2MiB=ptr%2097152)
stages[snap['phase']]=stage
if len(stages)!=10:raise ValueError('incomplete memory checkpoints')
baseline=stages['baseline']['physical_footprint_bytes']
for v in stages.values():v['delta_baseline_bytes']=v['physical_footprint_bytes']-baseline
c.update(args=case['args'],stages=stages)
if case['args'][0] not in ['cpu','cpu-plain'] and 'checksum_matches=256/256' not in out:raise ValueError('missing full consumption checksum')
elif receipt['suite']=='pool':
alloc=[fields(l) for l in out.splitlines() if l.startswith('ALLOC ')]
frees=[fields(l) for l in out.splitlines() if l.startswith('FREE ')]
if case.get('expected_exit')==1:
if 'END failure reason=trace guard/interior mismatch' not in out:raise ValueError('negative control reason')
c['negative_control']='omitted copy detected'
else:
c['allocation_ms']={k:distribution([float(v[k]) for v in alloc if int(v['iteration'])>=0]) for k in ['heap_or_suballoc_ms','placement_ms','map_ms']}
c['free_ms']={k:distribution([float(v[k]) for v in frees if int(v['iteration'])>=0]) for k in ['resource_ms','backing_or_freelist_ms']}
c['cycle_ms']=distribution([float(fields(l)['ms']) for l in out.splitlines() if l.startswith('CYCLE ') and int(fields(l)['iteration'])>=0])
c['fragmentation']=[fields(l) for l in out.splitlines() if l.startswith('FRAGMENT ')]
checks=[fields(l) for l in out.splitlines() if l.startswith('READBACK ')]
if len(checks)!=24:raise ValueError('missing trace readback checks')
for x in checks:
a,b=map(int,x['matches'].split('/'))
if a!=b:raise ValueError('readback mismatch')
if 'withheld=1' not in out or 'DELAYED_RETIRE' not in out:raise ValueError('missing delayed retirement')
if c['cycle_ms']['n']!=10 or c['allocation_ms']['map_ms']['n']!=360:raise ValueError('wrong trace sample count')
c['readback_checks']=len(checks)
elif receipt['suite']=='alias':
c['rounds']=[fields(l) for l in out.splitlines() if l.startswith('BUFFER_INHERIT ')]
if len(c['rounds'])!=3:raise ValueError('missing inheritance rounds')
for row in c['rounds']:
for key in ['source_matches','inherited_matches','disjoint_guard_matches']:
if row[key]!='16384/16384':raise ValueError('inheritance mismatch')
c['addresses']=[fields(l) for l in out.splitlines() if l.startswith('ALIAS_RESOURCE ')]
else:
c['outcomes']=[l for l in out.splitlines() if l.startswith(('OUTCOME ','NEGATIVE ','FOOTPRINT '))]
result['cases'].append(c)
return result
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('scratch',type=Path);p.add_argument('--allow-partial',action='store_true');p.add_argument('--output',required=True,type=Path);args=p.parse_args()
result=analyze(args.scratch,args.allow_partial);args.output.write_text(json.dumps(result,indent=2)+'\n');print(result['suite'],len(result['cases']),'cases; tool failures',result['tool_failures'])
if __name__=='__main__':main()
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Append a redacted diagnostic copy and hash manifest; original bytes stay untouched."""
import argparse
import hashlib
import json
from pathlib import Path
def main():
ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('scratch',type=Path);ap.add_argument('destination',type=Path);args=ap.parse_args()
src=args.scratch.resolve();dst=args.destination.resolve()
if dst.exists():ap.error('append-only destination must be new')
dst.mkdir(parents=True)
manifest=dict(originals_unchanged=True,redaction='JSON diagnostics replace local home-directory prefix with <HOME>; raw stdout/stderr unchanged',files=[])
for p in sorted(src.rglob('*')):
if not p.is_file() or p.is_symlink():continue
rel=p.relative_to(src)
if p.suffix=='.exe' or p.name=='observe' or any(v.startswith('.wine') or v=='bottle' for v in rel.parts):continue
original=p.read_bytes();data=original
if p.suffix=='.json':data=data.replace(str(Path.home()).encode(),b'<HOME>')
target=dst/rel;target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(data)
manifest['files'].append(dict(path=rel.as_posix(),bytes=len(data),original_sha256=hashlib.sha256(original).hexdigest(),archived_sha256=hashlib.sha256(data).hexdigest(),redacted=original!=data))
(dst/'archive-manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
print('Archived',len(manifest['files']),'files to',dst)
if __name__=='__main__':main()
@@ -0,0 +1,56 @@
# Physical-footprint observations and limits
The historical data inventory and corrected A2 data below are author observations on one Apple M4 with 24 GiB, macOS 27.0 (26A428), CrossOver 26.3.0.39832 and loaded D3DMetal 3.0. They are not independent acceptance. The original six baseline experiments remain unchanged.
## Existing data and correction
The historical 18-case profile has two fresh-process repeats at 64/256/1024 MiB for graphics-warmed CPU allocation, CUSTOM/WB/L0 and UPLOAD. Its baseline is about 340–341 MiB, dropping about 40 MiB by the next checkpoint. It fully writes the source and runs a checksum shader across all source words. However, it leaves command/pipeline/output objects live at its release checkpoint. It does not establish retention after their disposal. Exact historical sources/receipts and the earlier timeout are preserved in the [inventory](inventory/README.md).
The A2 correction disposes warm-up command objects before its settled baseline and separates resource release, command/pipeline/output disposal, a 500 ms settled interval and device release. It adds CPU-only processes without any D3D12 device, alongside matched graphics-warmed CPU allocation controls. Loaded-library evidence is collected separately at a paused stage, and exact-pointer vmmap is added.
The [first A2 profile](../results/2026-11-26-apple-m4-arths17-a2-memory-partial/receipt.json) completed 12 cases: four types at three sizes. The second session was interrupted after the host reported kernel pressure level 2; it is incomplete, not a pass. Operator stop, raw logs, shader bytes/hashes, failed/missing diagnostic and exact executed source snapshots are preserved. Later checking identified the actual Wine engine as `wine-11.0-8726-g2e2f5fca349`; the original runner's nonexistent `wine64 --version` lookup failed with exit 127, so its CrossOver version was known but its engine-version field was missing. Do not rewrite that receipt as a success.
## First-session accounting
MiB are 2^20 bytes. Each number below is the median of three correlated proc_pid_rusage readings at one paused checkpoint, not three independent sessions. Deltas are from that process's settled baseline. Values are rounded only in this table; raw bytes remain in the logs.
| Type | Requested MiB | Baseline MiB | After full initialization delta MiB | After full GPU consumption delta MiB | After settled complete retirement delta MiB |
| --- | ---: | ---: | ---: | ---: | ---: |
| CPU-only | 64 | 13.26 | 64.16 | 64.17 (GPU not run) | 0.03 |
| CPU with graphics warmed | 64 | 300.78 | 64.71 | 64.71 (GPU not run) | 0.57 |
| CUSTOM WB/L0 | 64 | 300.62 | 0.09 | 40.50 | 0.19 |
| UPLOAD | 64 | 300.21 | 0.09 | 40.54 | 0.22 |
| CPU-only | 256 | 13.15 | 256.59 | 256.59 (GPU not run) | 0.07 |
| CPU with graphics warmed | 256 | 300.46 | 256.54 | 257.18 (GPU not run) | 0.78 |
| CUSTOM WB/L0 | 256 | 300.38 | 256.58 | 297.04 | 256.74 |
| UPLOAD | 256 | 301.12 | 256.52 | 296.86 | 256.54 |
| CPU-only | 1024 | 13.19 | 1026.28 | 1026.28 (GPU not run) | 0.26 |
| CPU with graphics warmed | 1024 | 300.17 | 1026.73 | 1026.73 (GPU not run) | 0.90 |
| CUSTOM WB/L0 | 1024 | 301.36 | 1026.51 | 1066.96 | 1026.66 |
| UPLOAD | 1024 | 301.04 | 1025.98 | 1066.34 | 1026.04 |
The CPU control releases its large charge; larger graphics allocations remain mostly process-accounted at complete retirement and device release. This is stronger retirement scoping than the historical resource-release checkpoint, but still does not isolate runtime/driver caching or prove a leak. The device-release checkpoint leaves the process and loaded DLL/framework alive.
The 64 MiB graphics allocations add little charge at creation/initialization. Their mapped pointers lie in a 256 MiB IOAccelerator virtual region in this run. Larger allocations have separate pointer-specific regions. This supports an existing-pool explanation, rather than a linear assumption that every allocation creates a new equally sized physical charge. It does not prove which physical pages back the data.
## Accounting is not residency or page identity
The same first-session 1 GiB WB case reports approximately 1368 MiB physical-footprint accounting at GPU completion, but only 448 MiB resident size. The graphics-warmed CPU control has about 1327 MiB footprint accounting and 53 MiB RSS at that checkpoint. System compression/swap and the sequential sampling windows confound physical-residency interpretation. A near-1x size slope is an accounting observation, not proof of unique physical allocation, no duplication, or absence of copies elsewhere.
The exact mapped CPU pointers also refute an unqualified alignment assumption: the 64 MiB WB/UPLOAD pointers were 16384 modulo 65536, and the 256/1024 MiB WB/UPLOAD pointers were 49152 modulo 65536. Heap/resource placement alignment is not CPU-pointer alignment. See the [ownership matrix](inverted-ownership.md).
`footprint`, `vmmap`, native accounting and system-pressure tools measure different categories at different times. Virtual address ranges, resident pages, process ledger charges and driver-retained memory must not be summed or relabeled as physical page identity. Profiler permissions/timeouts and missing tools remain explicit outcomes.
## Pressure correction and remaining evidence
The initial guard used memory_pressure -Q free percentage only. The kernel subsequently reported pressure level 2 even with 51% reported free. Apple's [XNU documentation](https://github.com/apple-oss-distributions/xnu/blob/main/doc/vm/memorystatus_notify.md) calls level 2 urgent/warning-equivalent. This host's pressure state during earlier stages was not recorded by that stronger signal, so it is unknown. Existing swap and substantial background CPU load were recorded and limit interpretation.
A-local-2.1 adds kernel-level receipts and requires normal pressure at case and stage boundaries, with retained free-percentage guards. Fresh normal-pressure sessions and reciprocal review are required before treating the profile as reproducibly settled. The partial A2 results remain valid records of the workload under their stated conditions, not a completed repeated profile or a controlled benchmark.
Physical page identity remains unestablished. No result here certifies physical zero-copy, console coherence or #464. Independent review must inspect pinned source, exact shader/PE identities, full raw snapshots, failure paths and controls rather than accepting this interpretation.
## Bounded continuation and remaining repeats
After the requester freed memory and allowed bounded warning-pressure work under a 23 GB ceiling, [A-local-2.2 continuation](../results/2026-11-26-apple-m4-arths17-a22-memory-pressure-stop/receipt.json) completed six processes: all four 64 MiB controls/types and both CPU 256 MiB controls. The next WB 256 MiB process was killed at a paused checkpoint when kernel pressure returned to 2. Its exit -9 and harness stop reason are preserved, not a completed GPU result. The private Wine server was stopped and the source bottle configuration remained unchanged. No additional 1 GiB source was started in this continuation.
The maximum recorded conservative non-file-cache occupied estimate in completed snapshots was 21,187,198,976 bytes, below the 23,000,000,000-byte ceiling; this is a sampled metric, not a guarantee about unobserved intervals or an exact Activity Monitor value. The urgent-pressure guard stopped the profile independently of that ceiling. Both profiles remain explicitly partial. Further repeated large/normal-pressure characterization remains open rather than forcing execution under urgent pressure.
@@ -0,0 +1,17 @@
# Evidence handoff for placed-resource integration
This narrow handoff informs [#464](https://github.com/MacosPorters/betterxen/issues/464) and [PR #486](https://github.com/MacosPorters/betterxen/pull/486) without changing or certifying production code. The PR's `vmem.h` and `vmem.cpp` were read at `6308fdc0462d14f1f0b732e21dbc45329fb034c9`; this is boundary inspection, not a full independent implementation review. Its reported CrossOver 26.2/vkd3d runs are not the CrossOver 26.3/D3DMetal 3.0 environment used here.
| Integration question | Evidence-supported handoff |
| --- | --- |
| Can caller-owned xmem memory be wrapped? | Both existing-memory heap opens returned E_NOTIMPL in published version-scoped baseline observations. Keep this explicit; no bridge has been demonstrated. |
| What does mapped ownership provide? | A D3D12-owned WB/L0 buffer exposes a persistent CPU pointer and supports observed synchronized buffer access/alias inheritance. This is a candidate allocation provider, not evidence that arbitrary fixed/pre-device/scatter mappings are satisfied. |
| Can heap alignment be used as CPU alignment? | No. A2 mapped-pointer receipts include 16384 and 49152 modulo 65536 despite 64 KiB heap/resource alignment. Validate the actual requested CPU contract separately. |
| Does the configured block preserve an old address? | The inspected PR publishes a newly mapped cpu_pointer. That is not proof of an alias at existing base_va or preservation of its previous allocation contents/attributes. Distinguish the BetterXen-defined synthetic configuration from a verified console ABI. |
| May successful creation validate placement? | The M4 runtime accepted misaligned/out-of-bounds creation calls that were never GPU-used. Validate allocation-info alignment and bounds before forwarding. The PR's create_placed has explicit checks; no claim is made that this audit independently certifies all edge cases. |
| What do texture results cover? | Correct mixed-heap mip copies and RT/depth clear/alias readbacks in the tested configurations. Opaque texture layout, raw guest-pointer aliasing, sampling, console tiling and other formats remain separate. |
| What is released from the budget? | Logical heap/slice accounting and observed host/driver retention are separate quantities. Resource, command and device release checkpoints can retain graphics charges. Avoid calling that a proven leak or immediate physical reclamation. |
| Does pooling justify adoption? | It reduces the allocation-call component in this synthetic trace, with cold setup/slack costs and small/noisy cycle differences. It is not a demonstrated production speedup or memory reduction. |
| What may be claimed about copies? | Synchronized access, same-address alias behavior, footprint slopes and region labels do not establish physical page identity or universal absence of copies. The inspected PR's stronger “true shared”/“no extra copy” language is not established by #473. |
The maintainer's #464 claim remains respected. No forced ADR/ABI sequence, new dependency/blocking gate, production patch or approval of PR #486 is implied. Independent acceptance of A and actual source/raw review of B are pending. The underlying research is limited to original synthetic workloads on stated versions, with no Xbox hardware or game-execution claim.
@@ -0,0 +1,41 @@
# Existing evidence inventory
This is Workstream A's inventory for [#473](https://github.com/MacosPorters/betterxen/issues/473), based on research revision `9ae6d1ee7092b6021aad075531f50ba60de4fd53`. The baseline source hash is `33e90bfee89e812f48990613cd74ced56473e5c3fc5d973f2ba1116090646a0c` and has not changed. [manifest.json](manifest.json) records original and archived SHA-256 hashes for each preserved historical file. The exact final supplemental source is in [frozen-phase2](frozen-phase2/README.md). Its historical proposed commands do not constitute a new shared protocol or authorization to run B's modes.
## Available records
| Evidence | Availability and review limits |
| --- | --- |
| Original M4 baseline, two sessions | Pinned branch source, two raw runs and receipts already published; first executable hash missing; no new independent certification |
| M4 `p2-memory-final` | 18 cases: CPU allocation control, WB/L0, UPLOAD; 64/256/1024 MiB, two fresh-process repeats; all recorded exit 0. Source/runner hashes match frozen final bytes. All footprint/vmmap stage commands recorded exit 0. CPU control initializes a graphics context before its baseline: it is not a process without graphics. |
| M4 `p2-functional-final` | 23 cases: identity, shader coherence, omitted-dispatch negative control, CPU write-watch, texture, 18 dirty-stride cases. All expected exits recorded, including negative control exit 1. A inventories but does not take ownership of B's tests or accept their conclusions. |
| M4 `p2-acceptance` | Historical name only: 22 earlier author-run cases, not independent acceptance. Probe/runner source hashes differ from the available final source. Executable retained locally; exact earlier source bytes not recovered. Not final-source reproducibility evidence. |
| M4 `p2-memory` | One CPU 64 MiB process killed at timeout (exit -9). Failure preserved. Earlier source bytes not recovered; method corrected in later runs. |
| Development logs | Identity/coherence/texture/watch stdout/stderr remain at the original scratch root; inventory hashes supplement the archived bundles. No complete development launch receipt; do not promote to final evidence. |
| 2elliti M5 report | [Comment](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7201953364): five reported baseline runs; launcher/bottle/timeout differ, later runs polled, backend evidence partial. Separately written private probe unavailable. Source/raw evidence requested. |
| atesahmet0 M5 report | [Comment](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7202142335): 1 GiB footprint/region excerpts, dirty-stride timings, adapter/heap/write-watch data. No accessible pinned supplemental source or complete raw distributions linked; requested. Physical-sharing conclusions exceed the accounting/timing evidence. |
| CarReal8917 B implementation | No pinned B revision or raw handoff in the five comments read at start. Confirmation and source/receipts requested in #473. No alias with another account assumed. |
Archives under `../../results/2026-11-26-apple-m4-arths17-historical-*` contain original stdout/stderr bytes, receipts and tool outputs, excluding executables and bottles. JSON diagnostics replace the original home-directory prefix with `<HOME>`; manifest retains both original and redacted hashes. Original evidence and executable bytes remain locally unmodified. Embedded source paths are historical, not a promise that those paths exist on another host. No proprietary DLL/framework is archived.
Two new harness preparation failures are also preserved: the first nonexistent wine64 lookup interrupted setup, and the next strict -Werror build detected unused header helpers. No guest ran in either. The first setup attempt has source hashes but no copied source snapshot; later attempts save exact source bytes before compiling. The fixed inline helpers and correct wineloader version command are exercised in subsequent runs.
## Objective classification before new experiments
| Objective | Classification | Next justified work |
| --- | --- | --- |
| Fixed six baseline checks | Already tested; requires independent source review/reproduction | Preserve unchanged; obtain M5 source/raw receipts and B review |
| Footprint sizes/CPU controls | Already tested; requires methodological correction | Baseline drops ~40 MiB; small allocations can use existing pools; add settled baseline and full retirement instead of repeating identical protocol |
| Physical page identity / excluded copies | Unsupported or currently untestable with these tools | Process accounting and region labels cannot identify all physical backing or copies outside the sampled process/window |
| Pointer-specific region evidence | Requires additional experimentation | Old M4 vmmap is summary-only; retain exact mapped-pointer region at paused checkpoints |
| Full resource retirement | Requires additional experimentation | Historical release leaves command/shader objects alive; dispose them and separately record device release |
| Inverted ownership/xmem requirements | Requires additional experimentation and requirement derivation | Inspect pinned public in-tree contracts; requested VA, reservation/decommit, attributes, aliases/scatter and pre-device allocations need explicit limits |
| Pooling/allocation latency | Requires additional experimentation | Matched individual/pool resource traces; raw allocation/placement/Map/free samples, retained memory and logical fragmentation |
| Fence-safe recycling/aliasing | Requires additional experimentation | Fixed traces, guards, readback, delayed reuse; no intentional in-flight destruction or unsafe writes |
| RGBA8 65x37 UNKNOWN CPU write + GPU readback | Already tested; requires independent review/reproduction | 2405/2405 pixels recorded, padded pitch 512; preserve original evidence |
| ROW_MAJOR DEFAULT cross-adapter control | Already tested; requires independent review/reproduction | Creation and GPU upload/readback recorded; do not rerun identical case without a review need |
| Mixed placement, RT/depth, formats/mips, storage classes | Requires additional experimentation | Extend texture matrix using public API restrictions and exact readbacks; do not infer sampling from copies |
| AMD allocator | Requires additional research | Exact-pin, per-file license/provenance and feature review; no integration authorized by evaluation |
| B copy/bandwidth/coherence/tracking | Requires independent reproduction after pinned handoff | B implementation responsibility; no duplicate fixture development by A |
Hardware logs are local class A observations within their workloads, public API contracts class B, unobserved mechanisms class U. Historical shaders were compiled at runtime but their exact compiled bytecode hashes were not archived; this is a receipt gap, not filled by new builds. The new memory fixture saves its own shader source and bytecode. All new A implementation remains author-run and independently unaccepted until reciprocal review. No Xbox hardware or game compatibility is established.
@@ -0,0 +1,3 @@
# Frozen historical source snapshot
The [original README bytes](README.md.txt) are preserved unchanged as text, because their relative links and proposed paths describe the original location. This is an inventory snapshot, not an adopted shared protocol. Exact sources and hashes are in [the inventory manifest](../manifest.json). Some historical participant/protocol wording has been superseded by the revised two-workstream plan in #473.
@@ -0,0 +1,81 @@
# Phase-two standardized supplemental protocol 1
Research [#473](https://github.com/MacosPorters/betterxen/issues/473). Read the [source/API review](review.md) and [separate concurrent-experiment assessment](concurrent-review.md). The original six experiments in `../probe.cpp` and their runner are frozen and unchanged. These additions do not touch #464, production shims, ABI or main.
## Identical reproduction
Use native ARM64 MinGW-w64, Python 3.11+, Apple Command Line Tools, licensed CrossOver/D3DMetal and supported Rosetta. The runner builds a Windows x86-64 probe and a native ARM64 process-accounting observer, uses a private copy of an existing win64 bottle, and writes only to a new scratch directory. Preserve source revision/hash, compiler/runtime receipts and raw logs; remove scratch after archiving evidence. No proprietary binaries are committed.
```sh
git fetch origin research/d3dmetal-zero-copy:refs/remotes/origin/research/d3dmetal-zero-copy
git worktree add --detach ../betterxen-zero-copy-p2 origin/research/d3dmetal-zero-copy
cd ../betterxen-zero-copy-p2
python3 docs/research/d3dmetal-zero-copy/phase2/run.py \
--bottle "/absolute/path/to/an/existing/CrossOver/bottle" \
--scratch /tmp/bx-uma-verify/phase2-run
```
Default modes are identity, shader coherence, omitted-dispatch negative control, write-watch, textures, dirty-page scaling and memory footprint. Expected exit is 1 only for the deliberate negative control, and it must specifically report a GPU checksum mismatch. Other failures/timeouts are retained and never treated as passes. Source hash, PE/observer hashes, exact compiler commands, host/software versions and child environment are in receipt.json; every case has unedited stdout/stderr and case.json. `--modes identity,coherence,negative-control,watch,texture,dirty` and `--modes memory` split the suite into serial batches when convenient; do not run GPU batches concurrently.
The common profile is identical on **16 GiB and 24 GiB** hosts: 64, 256 and 1024 MiB, one allocation per fresh process, two repeats per size/type. CPU-only VirtualAlloc is the accounting control; CUSTOM/WRITE_BACK/L0 and standard UPLOAD are the graphics cases. `--large` adds 2048 MiB only when installed RAM is at least 24 GiB; never extrapolate an unrun case. A 4 GiB allocation is intentionally outside the common profile. Review recorded pressure/swap/compression and stop/reduce the study rather than forcing an allocation under pressure; label reduced profiles, do not mix them silently. Close unrelated heavy applications when practical and record background load. Tools run outside timed latency windows.
Compilation (the receipt records actual absolute paths):
```sh
x86_64-w64-mingw32-g++ -std=c++20 -O2 -static -static-libgcc -static-libstdc++ \
-Wall -Wextra -Werror phase2/probe.cpp -o phase2.exe -lkernel32
xcrun clang++ -std=c++20 -O2 -arch arm64 -Wall -Wextra -Werror \
phase2/observe.cpp -o observe
file phase2.exe observe
lipo -archs observe
otool -L observe
```
The HLSL is original, embedded in the source, compiled at runtime through the externally installed d3dcompiler_47.dll (cs_5_0; optimization-level-3 requested). Preserve compiler diagnostics: this Wine compiler reports that it ignores flag 0x8000, so no claim is made that the requested optimization was applied. The application loads host d3d12.dll directly and rejects a loaded d3d12_xs.dll. Environment uses an allowlist, ROSETTA_ADVERTISE_AVX=1, CX_GRAPHICS_BACKEND=d3dmetal and WINEDEBUG=-all. The copied bottle alone receives the locally compiled executable's trust/scanner configuration. Original bottle configuration is checked unchanged.
## 1. Physical footprint and overhead
Each memory process warms the shader, queue and fixed 64 KiB output before the baseline sample. The requested large source is then created, mapped, **fully written word-by-word** using index-mixed data, consumed by a full-allocation GPU shader read, fence-waited and released. A CPU-only control skips the GPU source pass explicitly. The shader reduces the entire allocation into 256 checksum words; validation is a checksum test, not a byte-for-byte proof for every source word.
At each handshake point—baseline, created, mapped, fully_initialized, gpu_complete, released—the guest pauses with no GPU work pending. The host resolves the process mapping the unique scratch PE, excluding wineserver's open file handle. It records:
- Three proc_pid_rusage(RUSAGE_INFO_V4) snapshots: physical footprint, resident/wired size, pageins and lifetime maximum; native observer return codes are retained.
- `footprint -p PID -f bytes` and `vmmap -summary PID`, each with bounded timeout and full stdout/stderr.
- `vm_stat` and `memory_pressure -Q`, to identify changing compression/swap/pressure.
- A separate loaded-library excerpt proving the app's D3DMetal DLL/framework; unrelated personal paths are not needed for this receipt.
These are API/process accounting measurements, not a physical-page identity test. Report deltas from each process's baseline and slopes across sizes, with both repeats and the CPU control. Do not add shared/RSS/footprint categories together or call a region label proof of sharing. Allocation caches and driver accounting may survive release. A near-1x slope supports a small *observed process-accounted* overhead; it does not exclude transient copies or memory charged elsewhere. Permission failures of footprint/vmmap remain visible; proc_pid_rusage is a separate signal, not a fabricated replacement for a failed tool.
## 2. Dirty-page scaling
Use a 256 MiB source in WB/L0, WC/L0 and UPLOAD, with 4096- and 16384-byte strides. Fully initialize once. For each stride modify k={0,1,64,4096,all} page-first words, evenly spread including endpoints when k>1. Thus all=65536 for 4 KiB and all=16384 for 16 KiB. Here “dirty” means application-modified strides, not a claim about the driver's actual tracking granularity. Each new write uses an iteration-specific pattern; k=0 changes nothing. Changes from previous k cases remain part of the expected state, so there is no hidden reset that dirties the full allocation between cases.
Three fresh-process sessions rotate k order and alternate heap order. Each k has 5 warmups + 30 recorded iterations. All sources use GENERIC_READ, including CUSTOM, with the same pre-recorded two-copy command list and no source transitions. CPU writes/store fence occur outside the timed window, and their cost is recorded separately as dirty_cpu_ms. Only ExecuteCommandLists + Signal + fence wait are timed as ms; command encoding, device-status check and validation are outside it. Readback checks the first and final stride's first 64 bytes. An additional untimed shader reads all page-first words and validates 256 independent output words against a CPU checksum, so modifying interior pages is not ignored.
Publish all per-iteration samples, median and nearest-rank p10/p90; compare per-session medians rather than pooling correlated samples without disclosure. The untimed verification uses another serialized queue; each submission completes before any subsequent CPU access or queue use. No concurrent queue accesses occur. Flat timing cannot exclude copies on CPU faults, at other API points or below noise; a slope cannot by itself distinguish copies from tracking/cache costs. No lsof/ps/vmmap polling runs during these cases.
## 3. Direct shader access and synchronized coherence
Persistent WB/L0 input (64 KiB) and UAV-capable WB/L0 output (64 KiB). Three rounds overwrite all 16384 input words and poison the 256-word output. After CPU store completion, 256 shader invocations read the input directly through a root SRV and write checksums through a root UAV. Output transitions COMMON→UNORDERED_ACCESS→COMMON; a queue fence completes before direct CPU reads from the same original output pointer. All 256 outputs must match each round. No CopyBufferRegion or CPU→GPU staging upload is used in this mode. The omitted-dispatch control must fail against the poison pattern. This establishes synchronized shader usability, not physical zero-copy or concurrent atomic coherence.
## 4. GPU texture readback and layout limits
Use an intentionally non-aligned width: 65×37 RGBA8, one mip/slice. UNKNOWN texture on CUSTOM WB/L0 is mapped with ppData=nullptr, filled with WriteToSubresource in COMMON, transitioned to COPY_SOURCE and GPU-copied into a READBACK buffer using GetCopyableFootprints. Respect returned row pitch/offset; check exactly 2405 pixel words after the fence. Padding is not interpreted as pixels. A single cold elapsed time is recorded but is not a throughput benchmark or a comparison of layout speed.
The ROW_MAJOR control uses a DEFAULT heap with SHARED|SHARED_CROSS_ADAPTER and a resource with ALLOW_CROSS_ADAPTER. It is filled from a footprint-pitched UPLOAD buffer by GPU copy, then GPU-copied to READBACK and compared. Map is explicitly not called on this CPU-inaccessible control. If shared/cross-adapter creation is unsupported, record the HRESULT and not-run path. No portability inference comes from the earlier development variant that omitted required flags; that variant was corrected before protocol-1 acceptance evidence.
This does not establish texture sampling/render/depth correctness, opaque-layout pointer aliasing, arbitrary formats/mips or a requirement that all textures internally copy. Public restrictions and buffer/texture ownership implications are in the review.
## 5. Adapter and heap-property identification
Match DXGI to **the actual D3D12 device LUID** using GetAdapterLuid and EnumAdapterByLuid, not an assumed adapter index. Record GetDesc2 name, IDs, flags and exact byte counts; these are advertised values, not physical memory measurements. Query architecture flags, heap tier, cross-adapter row-major and standard-swizzle support. Log GetCustomHeapProperties(0, DEFAULT/UPLOAD/READBACK), including Type, CPUPageProperty, MemoryPoolPreference and both node masks. Record guest page size/allocation granularity alongside the native observer's host page size. Loaded-library evidence, not adapter branding alone, identifies the backend.
## 6. Write-watch boundaries
Allocate a separate 64 KiB VirtualAlloc MEM_WRITE_WATCH region. Reset before each disjoint case; write one byte at {0}, {4096}, {12288}, {16383}, {16384}, {0,4096}, {0,4096,8192,12288}, {12288,16384}, {16383,16384}. Report dirty offsets, return/count/granularity and an immediate second query showing the reset state. There are no other threads writing during reset/query. These tests cover separate 4 KiB subpages in one 16 KiB interval and both sides of the 16 KiB boundary. They exercise CPU tracking only; GPU write-watch tracking remains untested and cannot be inferred from IsolatedMMU=false.
## Evidence and provenance
Source and native observer are original GPL-3.0-or-later research, using externally installed Microsoft-compatible headers/runtime APIs and Apple's public local SDK interfaces. No upstream implementation, restricted SDK, shader corpus, game code, proprietary compiler or runtime binary is copied into this directory. Existing runtime/toolchain research provenance remains in the [registry](../../upstream-registry.md) and [reuse matrix](../../component-reuse-matrix.md); any future vendored third-party code requires a per-file review before adoption.
Archive results by chip/contributor/run, preserving numerical logs; disclose any home-path redaction in host diagnostics. Keep the exact input source hashes and execution outcome. Hardware results are local class A evidence; public D3D12 contracts class B; physical aliasing/internal mechanisms and unmeasured generations remain class U. New probe authors do not independently certify their own code. Another contributor must review the implementation and run the same revision before independent acceptance.
@@ -0,0 +1,11 @@
# Concurrent visibility: exploratory only
The proposed CPU-after-submit/GPU-spin and GPU-store/CPU-spin experiment intentionally omits the synchronization used by ordinary D3D12 applications. It is excluded from this protocol's executables and acceptance gates. No result from it is claimed here.
Microsoft's [Map contract](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-map) requires the CPU to finish writes before GPU execution in the persistent-map usage model and cautions against assuming CPU/GPU atomic guarantees. A CPU store fence, volatile load or a shader barrier alone does not create an API-guaranteed interprocessor rendezvous. [ALLOW_SIMULTANEOUS_ACCESS](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_resource_flags) is not permission for conflicting concurrent CPU/GPU writes to the same location.
A positive result would not prove a mid-flight observation: the GPU may start after the CPU store, commands may be delayed or serialized, and an implementation may synchronize/copy at a different point. A negative result would not prove shadow copying: CPU/GPU cache behavior, compiler hoisting, shader scheduling and unsupported atomic/visibility assumptions can all prevent progress. Neither outcome establishes physical page identity.
Any future exploratory implementation must be separate, explicitly opted into, bounded in shader iterations and process duration, and must preserve its exact compiled shader, scheduling evidence and outcomes without counting them as conformance passes/failures. A bounded spin may still monopolize a device or encounter watchdog limits; do not make an unbounded poll part of the shared suite. Establish actual GPU start/progress independently before interpreting apparent mid-flight behavior, and keep any conclusion conditional on that evidence.
The standard test instead completes CPU stores before dispatch, waits on a queue fence after the shader, and reads the existing mapped output pointer. This tests application-usable synchronized coherence without claiming to identify its physical implementation.
@@ -0,0 +1,15 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original macOS process accounting observer; native ARM64 only.
#include <libproc.h>
#include <sys/resource.h>
#include <cstdio>
#include <cstdlib>
#include <cerrno>
#include <unistd.h>
int main(int argc,char** argv){
if(argc!=2)return 2;
rusage_info_v4 r{};int pid=std::atoi(argv[1]);
int rc=proc_pid_rusage(pid,RUSAGE_INFO_V4,reinterpret_cast<rusage_info_t*>(&r));
std::printf("{\"pid\":%d,\"return\":%d,\"errno\":%d,\"host_page_size\":%d,\"phys_footprint\":%llu,\"resident_size\":%llu,\"wired_size\":%llu,\"pageins\":%llu,\"max_phys_footprint\":%llu}\n",pid,rc,rc?errno:0,getpagesize(),r.ri_phys_footprint,r.ri_resident_size,r.ri_wired_size,r.ri_pageins,r.ri_lifetime_max_phys_footprint);
return rc?1:0;
}
@@ -0,0 +1,264 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Supplemental original synthetic tests; baseline ../probe.cpp is unchanged.
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#include <d3d12.h>
#include <dxgi1_4.h>
#include <d3dcompiler.h>
#include <emmintrin.h>
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#include <string>
#include <vector>
template<class T> struct Ref{
T* p=nullptr;Ref()=default;Ref(const Ref&)=delete;Ref& operator=(const Ref&)=delete;
~Ref(){clear();} void clear(){if(p){p->Release();p=nullptr;}}
T* operator->()const{return p;} void** out(){return reinterpret_cast<void**>(&p);}
};
static void require(HRESULT h,const char* name){
if(FAILED(h)){std::printf("FAIL %s HRESULT=0x%08lX\n",name,(unsigned long)h);throw std::runtime_error(name);}
}
static void report(HRESULT h,const char* name){std::printf("API %s HRESULT=0x%08lX\n",name,(unsigned long)h);}
template<class T> static T symbol(HMODULE m,const char* name){
FARPROC p=GetProcAddress(m,name);if(!p)throw std::runtime_error(name);
T result;static_assert(sizeof(result)==sizeof(p));std::memcpy(&result,&p,sizeof(p));return result;
}
static double ticks(){LARGE_INTEGER t;QueryPerformanceCounter(&t);return double(t.QuadPart);}
static double frequency(){LARGE_INTEGER t;QueryPerformanceFrequency(&t);return double(t.QuadPart);}
static D3D12_HEAP_PROPERTIES properties(D3D12_HEAP_TYPE type){
D3D12_HEAP_PROPERTIES p{};p.Type=type;p.CreationNodeMask=1;p.VisibleNodeMask=1;return p;
}
static D3D12_RESOURCE_DESC bufferDesc(UINT64 bytes,D3D12_RESOURCE_FLAGS flags=D3D12_RESOURCE_FLAG_NONE){
D3D12_RESOURCE_DESC r{};r.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;r.Width=bytes;r.Height=1;r.DepthOrArraySize=1;r.MipLevels=1;r.SampleDesc.Count=1;r.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;r.Flags=flags;return r;
}
struct Context{
HMODULE dll=nullptr;Ref<ID3D12Device3> device;
Context(){
dll=LoadLibraryA("d3d12.dll");if(!dll)throw std::runtime_error("LoadLibrary d3d12");
char path[2048]{};GetModuleFileNameA(dll,path,sizeof(path));std::printf("D3D12_DLL %s\n",path);
using Create=HRESULT(WINAPI*)(IUnknown*,D3D_FEATURE_LEVEL,REFIID,void**);
require(symbol<Create>(dll,"D3D12CreateDevice")(nullptr,D3D_FEATURE_LEVEL_11_0,__uuidof(ID3D12Device3),device.out()),"CreateDevice3");
bool shim=GetModuleHandleA("d3d12_xs.dll")!=nullptr;std::printf("SHIM_LOADED %d\n",shim);if(shim)throw std::runtime_error("shim contamination");
}
};
struct Queue{
ID3D12Device3* d;Ref<ID3D12CommandQueue> q;Ref<ID3D12CommandAllocator> allocator;Ref<ID3D12GraphicsCommandList> list;Ref<ID3D12Fence> fence;
HANDLE event=nullptr;UINT64 value=0;
explicit Queue(ID3D12Device3* device):d(device){
D3D12_COMMAND_QUEUE_DESC desc{};desc.Type=D3D12_COMMAND_LIST_TYPE_DIRECT;
require(d->CreateCommandQueue(&desc,__uuidof(ID3D12CommandQueue),q.out()),"CreateCommandQueue");
require(d->CreateCommandAllocator(desc.Type,__uuidof(ID3D12CommandAllocator),allocator.out()),"CreateCommandAllocator");
require(d->CreateCommandList(0,desc.Type,allocator.p,nullptr,__uuidof(ID3D12GraphicsCommandList),list.out()),"CreateCommandList");
require(list->Close(),"initial Close");require(d->CreateFence(0,D3D12_FENCE_FLAG_NONE,__uuidof(ID3D12Fence),fence.out()),"CreateFence");
event=CreateEventW(nullptr,FALSE,FALSE,nullptr);if(!event)throw std::runtime_error("CreateEvent");
}
~Queue(){if(event)CloseHandle(event);}
void begin(){require(allocator->Reset(),"allocator Reset");require(list->Reset(allocator.p,nullptr),"list Reset");}
void transition(ID3D12Resource* r,D3D12_RESOURCE_STATES a,D3D12_RESOURCE_STATES b){
if(a==b)return;
D3D12_RESOURCE_BARRIER x{};x.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;x.Transition.pResource=r;x.Transition.StateBefore=a;x.Transition.StateAfter=b;x.Transition.Subresource=D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;list->ResourceBarrier(1,&x);
}
void close(){require(list->Close(),"Close");}
void executeClosed(){
ID3D12CommandList* lists[]={list.p};q->ExecuteCommandLists(1,lists);require(q->Signal(fence.p,++value),"Signal");
UINT64 completed=fence->GetCompletedValue();if(completed==~UINT64(0))throw std::runtime_error("device removed fence");
if(completed<value){require(fence->SetEventOnCompletion(value,event),"SetEventOnCompletion");DWORD w=WaitForSingleObject(event,10000);if(w!=WAIT_OBJECT_0)throw std::runtime_error("fence timeout");}
}
void finish(){close();_mm_sfence();executeClosed();require(d->GetDeviceRemovedReason(),"GetDeviceRemovedReason");}
};
struct Buffer{
Ref<ID3D12Heap> heap;Ref<ID3D12Resource> resource;void* cpu=nullptr;UINT64 size=0;
void allocate(ID3D12Device3* d,UINT64 bytes,const std::string& type,bool uav=false){
size=bytes;auto desc=bufferDesc(bytes,uav?D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS:D3D12_RESOURCE_FLAG_NONE);
auto state=uav?D3D12_RESOURCE_STATE_COMMON:D3D12_RESOURCE_STATE_GENERIC_READ;
if(type=="upload"||type=="readback"){
if(uav)throw std::runtime_error("UAV on upload/readback forbidden in this probe");
auto p=properties(type=="upload"?D3D12_HEAP_TYPE_UPLOAD:D3D12_HEAP_TYPE_READBACK);
if(type=="readback")state=D3D12_RESOURCE_STATE_COPY_DEST;
require(d->CreateCommittedResource(&p,D3D12_HEAP_FLAG_NONE,&desc,state,nullptr,__uuidof(ID3D12Resource),resource.out()),"committed buffer");
}else{
D3D12_HEAP_DESC hd{};hd.SizeInBytes=(bytes+65535)&~UINT64(65535);hd.Alignment=65536;hd.Properties=properties(D3D12_HEAP_TYPE_CUSTOM);hd.Properties.CPUPageProperty=type=="wc"?D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE:D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;hd.Properties.MemoryPoolPreference=D3D12_MEMORY_POOL_L0;
require(d->CreateHeap(&hd,__uuidof(ID3D12Heap),heap.out()),"custom heap");
require(d->CreatePlacedResource(heap.p,0,&desc,state,nullptr,__uuidof(ID3D12Resource),resource.out()),"placed buffer");
}
}
void map(){require(resource->Map(0,nullptr,&cpu),"Map buffer");if(!cpu)throw std::runtime_error("null buffer pointer");}
void release(){cpu=nullptr;resource.clear();heap.clear();}
};
static void identity(Context& c){
using Factory=HRESULT(WINAPI*)(UINT,REFIID,void**);
HMODULE dxgi=LoadLibraryA("dxgi.dll");if(!dxgi)throw std::runtime_error("dxgi load");
Ref<IDXGIFactory4> f;require(symbol<Factory>(dxgi,"CreateDXGIFactory2")(0,__uuidof(IDXGIFactory4),f.out()),"factory4");
LUID luid=c.device->GetAdapterLuid();Ref<IDXGIAdapter2> a;require(f->EnumAdapterByLuid(luid,__uuidof(IDXGIAdapter2),a.out()),"adapter by device LUID");
DXGI_ADAPTER_DESC2 ad{};require(a->GetDesc2(&ad),"GetDesc2");char name[512]{};WideCharToMultiByte(CP_UTF8,0,ad.Description,-1,name,sizeof(name),nullptr,nullptr);
std::printf("ADAPTER description=%s vendor=0x%04X device=0x%04X subsystem=0x%08X revision=%u flags=%u dedicated_video_bytes=%llu dedicated_system_bytes=%llu shared_system_bytes=%llu luid=%08lX:%08lX\n",name,ad.VendorId,ad.DeviceId,ad.SubSysId,ad.Revision,ad.Flags,(unsigned long long)ad.DedicatedVideoMemory,(unsigned long long)ad.DedicatedSystemMemory,(unsigned long long)ad.SharedSystemMemory,(unsigned long)luid.HighPart,(unsigned long)luid.LowPart);
D3D12_FEATURE_DATA_D3D12_OPTIONS opts{};require(c.device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS,&opts,sizeof(opts)),"options");std::printf("OPTIONS ResourceHeapTier=%d CrossAdapterRowMajorTextureSupported=%d StandardSwizzle64KBSupported=%d\n",opts.ResourceHeapTier,opts.CrossAdapterRowMajorTextureSupported,opts.StandardSwizzle64KBSupported);
D3D12_FEATURE_DATA_ARCHITECTURE1 arch{};require(c.device->CheckFeatureSupport(D3D12_FEATURE_ARCHITECTURE1,&arch,sizeof(arch)),"architecture1");std::printf("ARCH UMA=%d CacheCoherentUMA=%d TileBasedRenderer=%d IsolatedMMU=%d\n",arch.UMA,arch.CacheCoherentUMA,arch.TileBasedRenderer,arch.IsolatedMMU);
for(auto type:{D3D12_HEAP_TYPE_DEFAULT,D3D12_HEAP_TYPE_UPLOAD,D3D12_HEAP_TYPE_READBACK}){
auto p=c.device->GetCustomHeapProperties(0,type);std::printf("CUSTOM_PROPERTIES input_type=%d Type=%d CPUPageProperty=%d MemoryPoolPreference=%d CreationNodeMask=%u VisibleNodeMask=%u\n",type,p.Type,p.CPUPageProperty,p.MemoryPoolPreference,p.CreationNodeMask,p.VisibleNodeMask);
}
SYSTEM_INFO si{};GetSystemInfo(&si);std::printf("GUEST_PAGE_SIZE %lu ALLOCATION_GRANULARITY %lu\n",si.dwPageSize,si.dwAllocationGranularity);
}
struct Shader{
Ref<ID3D12RootSignature> root;Ref<ID3D12PipelineState> pipeline;
static constexpr const char* code=R"HLSL(
ByteAddressBuffer source : register(t0);
RWByteAddressBuffer result : register(u0);
cbuffer Parameters : register(b0) { uint count; uint salt; uint wordStride; };
[numthreads(64,1,1)]
void main(uint3 tid : SV_DispatchThreadID) {
uint accum=0;
for(uint i=tid.x; i<count; i+=256) accum ^= source.Load(i*wordStride*4)+salt;
result.Store(tid.x*4,accum);
}
)HLSL";
explicit Shader(Context& c){
HMODULE compiler=LoadLibraryA("d3dcompiler_47.dll");if(!compiler)throw std::runtime_error("d3dcompiler47 unavailable");
char path[2048]{};GetModuleFileNameA(compiler,path,sizeof(path));std::printf("SHADER_COMPILER %s\n",path);
using Compile=HRESULT(WINAPI*)(LPCVOID,SIZE_T,LPCSTR,const D3D_SHADER_MACRO*,ID3DInclude*,LPCSTR,LPCSTR,UINT,UINT,ID3DBlob**,ID3DBlob**);
Ref<ID3DBlob> binary,error;
HRESULT h=symbol<Compile>(compiler,"D3DCompile")(code,std::strlen(code),"original-phase2.hlsl",nullptr,nullptr,"main","cs_5_0",D3DCOMPILE_OPTIMIZATION_LEVEL3,0,&binary.p,&error.p);
if(error.p)std::printf("COMPILER_LOG %.*s\n",(int)error->GetBufferSize(),(const char*)error->GetBufferPointer());
require(h,"D3DCompile cs5_0");
std::printf("SHADER_BYTECODE bytes=%zu magic=%.4s\n",binary->GetBufferSize(),(char*)binary->GetBufferPointer());
D3D12_ROOT_PARAMETER params[3]{};
params[0].ParameterType=D3D12_ROOT_PARAMETER_TYPE_SRV;params[0].Descriptor.ShaderRegister=0;
params[1].ParameterType=D3D12_ROOT_PARAMETER_TYPE_UAV;params[1].Descriptor.ShaderRegister=0;
params[2].ParameterType=D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;params[2].Constants.ShaderRegister=0;params[2].Constants.Num32BitValues=3;
D3D12_ROOT_SIGNATURE_DESC desc{};desc.NumParameters=3;desc.pParameters=params;
using Serialize=HRESULT(WINAPI*)(const D3D12_ROOT_SIGNATURE_DESC*,D3D_ROOT_SIGNATURE_VERSION,ID3DBlob**,ID3DBlob**);
Ref<ID3DBlob> serialized,serializeError;require(symbol<Serialize>(c.dll,"D3D12SerializeRootSignature")(&desc,D3D_ROOT_SIGNATURE_VERSION_1,&serialized.p,&serializeError.p),"serialize root");
require(c.device->CreateRootSignature(0,serialized->GetBufferPointer(),serialized->GetBufferSize(),__uuidof(ID3D12RootSignature),root.out()),"CreateRootSignature");
D3D12_COMPUTE_PIPELINE_STATE_DESC pd{};pd.pRootSignature=root.p;pd.CS={binary->GetBufferPointer(),binary->GetBufferSize()};require(c.device->CreateComputePipelineState(&pd,__uuidof(ID3D12PipelineState),pipeline.out()),"CreateComputePipelineState");
}
void dispatch(Queue& q,Buffer& src,Buffer& dst,UINT count,UINT salt,UINT stride){
q.begin();q.transition(dst.resource.p,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
q.list->SetPipelineState(pipeline.p);q.list->SetComputeRootSignature(root.p);q.list->SetComputeRootShaderResourceView(0,src.resource->GetGPUVirtualAddress());q.list->SetComputeRootUnorderedAccessView(1,dst.resource->GetGPUVirtualAddress());UINT values[]={count,salt,stride};q.list->SetComputeRoot32BitConstants(2,3,values,0);q.list->Dispatch(4,1,1);
q.transition(dst.resource.p,D3D12_RESOURCE_STATE_UNORDERED_ACCESS,D3D12_RESOURCE_STATE_COMMON);q.finish();
}
};
static uint32_t pattern(UINT64 i,UINT seed){uint32_t x=uint32_t(i)^seed;x^=x>>16;x*=0x7FEB352Du;x^=x>>15;x*=0x846CA68Bu;return x^(x>>16);}
static void compare(const char* label,const std::array<uint32_t,256>& expected,void* cpu){
auto p=static_cast<volatile uint32_t*>(cpu);size_t n=0;for(size_t i=0;i<256;++i)n+=p[i]==expected[i];std::printf("VERIFY %s matches=%zu/256 first_actual=%08X first_expected=%08X\n",label,n,p[0],expected[0]);if(n!=256)throw std::runtime_error("GPU checksum mismatch");
}
static void stage(const char* name,void* pointer=nullptr){
std::printf("STAGE %s cpu_ptr=%p\n",name,pointer);
// Host snapshots happen while no GPU work is pending; never in latency windows.
if(std::getchar()==EOF)throw std::runtime_error("stage handshake lost");
}
static void coherent(Context& c,bool omitDispatch=false){
Shader shader(c);Queue q(c.device.p);Buffer src,dst;src.allocate(c.device.p,65536,"wb");src.map();dst.allocate(c.device.p,65536,"wb",true);dst.map();
for(UINT round=0;round<3;++round){
auto p=static_cast<volatile uint32_t*>(src.cpu);std::array<uint32_t,256> expected{};UINT salt=0x100103u*(round+1);
for(UINT i=0;i<16384;++i){uint32_t v=pattern(i,0x3412198u+round);p[i]=v;expected[i%256]^=v+salt;}
// Poison result on CPU before every dispatch so an omitted shader cannot pass.
auto output=static_cast<volatile uint32_t*>(dst.cpu);for(UINT i=0;i<256;++i)output[i]=0xDEADC0DEu;_mm_sfence();
if(!omitDispatch)shader.dispatch(q,src,dst,16384,salt,1);
compare("direct_shader_same_cpu_pointer",expected,dst.cpu);
std::printf("COHERENCE_ROUND %u input_ptr=%p output_ptr=%p shader_read_words=16384 shader_written_words=256\n",round,src.cpu,dst.cpu);
}
}
static void memory(Context& c,const std::string& type,UINT64 bytes){
// Warm shader, queue and tiny result resources BEFORE the baseline snapshot.
Shader shader(c);Queue q(c.device.p);Buffer small,out;small.allocate(c.device.p,65536,"upload");small.map();std::memset(small.cpu,0,65536);out.allocate(c.device.p,65536,"wb",true);out.map();shader.dispatch(q,small,out,1,0,1);small.release();
std::printf("MEMORY type=%s bytes=%llu\n",type.c_str(),bytes);stage("baseline");
Buffer src;void* cpu=nullptr;
if(type=="cpu"){cpu=VirtualAlloc(nullptr,bytes,MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE);if(!cpu)throw std::runtime_error("VirtualAlloc control");}
else src.allocate(c.device.p,bytes,type);
stage("created");
if(type!="cpu"){src.map();cpu=src.cpu;}stage("mapped",cpu);
auto p=static_cast<volatile uint32_t*>(cpu);std::array<uint32_t,256> expected{};UINT64 words=bytes/4;
for(UINT64 i=0;i<words;++i){uint32_t value=pattern(i,0x24681357u);p[i]=value;expected[i%256]^=value+0x10101u;}_mm_sfence();
stage("fully_initialized",cpu);
if(type!="cpu"){shader.dispatch(q,src,out,UINT(words),0x10101u,1);compare("full_allocation_shader_read",expected,out.cpu);}else std::puts("GPU_PASS NOT_RUN CPU_control");
stage("gpu_complete",cpu);
if(type=="cpu")VirtualFree(cpu,0,MEM_RELEASE);else src.release();
stage("released");
}
static void dirty(Context& c,const std::string& type,UINT stride,UINT session){
const UINT64 bytes=268435456;const UINT pages=UINT(bytes/stride);Shader shader(c);Queue copy(c.device.p),verify(c.device.p);Buffer src,out,read;
src.allocate(c.device.p,bytes,type);src.map();out.allocate(c.device.p,65536,"wb",true);out.map();read.allocate(c.device.p,128,"readback");read.map();
std::memset(src.cpu,0,bytes);_mm_sfence();std::vector<uint32_t> pageValues(pages,0);
// Both heap types use identical GENERIC_READ source states and no source barriers.
copy.begin();copy.list->CopyBufferRegion(read.resource.p,0,src.resource.p,0,64);copy.list->CopyBufferRegion(read.resource.p,64,src.resource.p,bytes-stride,64);copy.close();
std::vector<UINT> ks={0,1,64,4096,pages};std::rotate(ks.begin(),ks.begin()+session%ks.size(),ks.end());
for(UINT k:ks){
std::vector<double> times;int matches=0;
for(int iteration=-5;iteration<30;++iteration){
double dirtyStart=ticks();
for(UINT j=0;j<k;++j){UINT page=k==1?0:UINT(UINT64(j)*(pages-1)/(k-1));uint32_t value=pattern(UINT64(page)+UINT64(iteration+5)*pages,0xAB3000u+session*17+k);*reinterpret_cast<volatile uint32_t*>(static_cast<unsigned char*>(src.cpu)+UINT64(page)*stride)=value;pageValues[page]=value;}
_mm_sfence();double dirtyMs=(ticks()-dirtyStart)*1000.0/frequency();double start=ticks();copy.executeClosed();double ms=(ticks()-start)*1000.0/frequency();require(c.device->GetDeviceRemovedReason(),"dirty device status");
auto rp=static_cast<volatile uint32_t*>(read.cpu);bool sentinels=rp[0]==pageValues[0]&&rp[16]==pageValues[pages-1];for(int i=1;i<16;++i)sentinels=sentinels&&rp[i]==0&&rp[16+i]==0;
std::array<uint32_t,256> expected{};for(UINT i=0;i<pages;++i)expected[i%256]^=pageValues[i]+0x321u;
// Additional full page-first-word validation is outside the timed window.
shader.dispatch(verify,src,out,pages,0x321u,stride/4);
auto op=static_cast<volatile uint32_t*>(out.cpu);bool all=sentinels;for(UINT i=0;i<256;++i)all=all&&op[i]==expected[i];
if(iteration>=0){times.push_back(ms);matches+=all;std::printf("DIRTY_SAMPLE type=%s stride=%u session=%u k=%u iteration=%d dirty_cpu_ms=%.6f ms=%.6f match=%d\n",type.c_str(),stride,session,k,iteration,dirtyMs,ms,all);}
if(!all)throw std::runtime_error("dirty page validation");
}
std::sort(times.begin(),times.end());std::printf("DIRTY_RESULT type=%s bytes=%llu stride=%u total_pages=%u session=%u k=%u n=30 median_ms=%.6f p10_ms=%.6f p90_ms=%.6f matches=%d/30\n",type.c_str(),bytes,stride,pages,session,k,(times[14]+times[15])/2,times[2],times[26],matches);
}
}
static void watch(){
auto p=static_cast<unsigned char*>(VirtualAlloc(nullptr,65536,MEM_COMMIT|MEM_RESERVE|MEM_WRITE_WATCH,PAGE_READWRITE));if(!p)throw std::runtime_error("writewatch allocation");
const std::vector<std::vector<UINT>> cases={{0},{4096},{12288},{16383},{16384},{0,4096},{0,4096,8192,12288},{12288,16384},{16383,16384}};
for(size_t c=0;c<cases.size();++c){
require(HRESULT_FROM_WIN32(ResetWriteWatch(p,65536)),"ResetWriteWatch");
for(UINT off:cases[c])*reinterpret_cast<volatile unsigned char*>(p+off)=0x6B;
PVOID addresses[64]{};ULONG_PTR count=64;DWORD gran=0;UINT rc=GetWriteWatch(WRITE_WATCH_FLAG_RESET,p,65536,addresses,&count,&gran);
std::printf("WATCH case=%zu writes=",c);for(UINT off:cases[c])std::printf("%u,",off);std::printf(" return=%u count=%llu granularity=%lu dirty=",rc,(unsigned long long)count,gran);if(!rc)for(ULONG_PTR i=0;i<count;++i)std::printf("%llu,",(unsigned long long)(static_cast<unsigned char*>(addresses[i])-p));std::puts("");if(rc)throw std::runtime_error("GetWriteWatch failed");
count=64;gran=0;rc=GetWriteWatch(0,p,65536,addresses,&count,&gran);std::printf("WATCH_AFTER_RESET case=%zu return=%u count=%llu granularity=%lu\n",c,rc,(unsigned long long)count,gran);if(rc||count)throw std::runtime_error("writewatch reset not empty");
}
VirtualFree(p,0,MEM_RELEASE);
}
static void textures(Context& c){
Queue q(c.device.p);
for(auto layout:{D3D12_TEXTURE_LAYOUT_UNKNOWN,D3D12_TEXTURE_LAYOUT_ROW_MAJOR}){
D3D12_RESOURCE_DESC td{};td.Dimension=D3D12_RESOURCE_DIMENSION_TEXTURE2D;td.Width=65;td.Height=37;td.DepthOrArraySize=1;td.MipLevels=1;td.Format=DXGI_FORMAT_R8G8B8A8_UNORM;td.SampleDesc.Count=1;td.Layout=layout;
if(layout==D3D12_TEXTURE_LAYOUT_ROW_MAJOR)td.Flags=D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER;
auto ai=c.device->GetResourceAllocationInfo(0,1,&td);std::printf("TEXTURE layout=%d allocation_bytes=%llu alignment=%llu\n",layout,ai.SizeInBytes,ai.Alignment);
if(ai.SizeInBytes==~UINT64(0)||!ai.Alignment){std::puts("TEXTURE_UNSUPPORTED allocation info invalid");continue;}
Ref<ID3D12Heap> h;D3D12_HEAP_DESC hd{};hd.SizeInBytes=ai.SizeInBytes;hd.Alignment=ai.Alignment;hd.Properties=properties(D3D12_HEAP_TYPE_CUSTOM);hd.Properties.CPUPageProperty=D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;hd.Properties.MemoryPoolPreference=D3D12_MEMORY_POOL_L0;
if(layout==D3D12_TEXTURE_LAYOUT_ROW_MAJOR){hd.Properties=properties(D3D12_HEAP_TYPE_DEFAULT);hd.Flags=D3D12_HEAP_FLAG_SHARED|D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER;}
HRESULT heapResult=c.device->CreateHeap(&hd,__uuidof(ID3D12Heap),h.out());report(heapResult,"texture heap");if(FAILED(heapResult)){if(layout==D3D12_TEXTURE_LAYOUT_UNKNOWN)require(heapResult,"required UNKNOWN texture heap");std::puts("TEXTURE_NOT_RUN heap unsupported");continue;}Ref<ID3D12Resource> t;HRESULT created=c.device->CreatePlacedResource(h.p,0,&td,D3D12_RESOURCE_STATE_COMMON,nullptr,__uuidof(ID3D12Resource),t.out());report(created,"placed texture");if(FAILED(created))continue;
// UNKNOWN: request access without asking runtime to disclose opaque layout.
void* pointer=nullptr;HRESULT mapped=layout==D3D12_TEXTURE_LAYOUT_UNKNOWN?t->Map(0,nullptr,nullptr):S_OK;if(layout==D3D12_TEXTURE_LAYOUT_UNKNOWN)report(mapped,"texture Map");else std::puts("TEXTURE Map NOT_RUN CPU-inaccessible DEFAULT cross-adapter heap");std::printf("TEXTURE layout=%d returned_cpu_ptr=%p pointer_requested=%d\n",layout,pointer,0);if(FAILED(mapped))continue;
std::vector<uint32_t> input(65*37);for(UINT i=0;i<input.size();++i)input[i]=pattern(i,0x12345678u);
if(layout==D3D12_TEXTURE_LAYOUT_UNKNOWN){HRESULT w=t->WriteToSubresource(0,nullptr,input.data(),65*4,65*37*4);report(w,"WriteToSubresource");require(w,"required UNKNOWN CPU write");}
D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{};UINT rows=0;UINT64 rowBytes=0,total=0;c.device->GetCopyableFootprints(&td,0,1,0,&fp,&rows,&rowBytes,&total);std::printf("TEXTURE_FOOTPRINT layout=%d rows=%u row_bytes=%llu row_pitch=%u total_bytes=%llu offset=%llu\n",layout,rows,rowBytes,fp.Footprint.RowPitch,total,fp.Offset);
Buffer upload;if(layout==D3D12_TEXTURE_LAYOUT_ROW_MAJOR){
upload.allocate(c.device.p,total,"upload");upload.map();std::memset(upload.cpu,0,total);for(UINT y=0;y<37;++y)std::memcpy(static_cast<unsigned char*>(upload.cpu)+fp.Offset+UINT64(y)*fp.Footprint.RowPitch,input.data()+y*65,260);_mm_sfence();
D3D12_TEXTURE_COPY_LOCATION fromUpload{},toTexture{};fromUpload.pResource=upload.resource.p;fromUpload.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;fromUpload.PlacedFootprint=fp;toTexture.pResource=t.p;toTexture.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
q.begin();q.transition(t.p,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_DEST);q.list->CopyTextureRegion(&toTexture,0,0,0,&fromUpload,nullptr);q.transition(t.p,D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_COMMON);q.finish();
}
Buffer read;read.allocate(c.device.p,total,"readback");read.map();std::memset(read.cpu,0xA7,total);
D3D12_TEXTURE_COPY_LOCATION from{},to{};from.pResource=t.p;from.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;from.SubresourceIndex=0;to.pResource=read.resource.p;to.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;to.PlacedFootprint=fp;
double start=ticks();q.begin();q.transition(t.p,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_SOURCE);q.list->CopyTextureRegion(&to,0,0,0,&from,nullptr);q.transition(t.p,D3D12_RESOURCE_STATE_COPY_SOURCE,D3D12_RESOURCE_STATE_COMMON);q.finish();double ms=(ticks()-start)*1000.0/frequency();
size_t matches=0;for(UINT y=0;y<37;++y)for(UINT x=0;x<65;++x){auto row=reinterpret_cast<volatile uint32_t*>(static_cast<unsigned char*>(read.cpu)+fp.Offset+UINT64(y)*fp.Footprint.RowPitch);matches+=row[x]==input[y*65+x];}
std::printf("TEXTURE_GPU_READBACK layout=%d matches=%zu/2405 ms=%.6f\n",layout,matches,ms);if(matches!=2405)throw std::runtime_error("texture GPU mismatch");if(layout==D3D12_TEXTURE_LAYOUT_UNKNOWN)t->Unmap(0,nullptr);
}
}
int main(int argc,char** argv){
setvbuf(stdout,nullptr,_IONBF,0);
try{
if(argc<2)throw std::runtime_error("usage: phase2 identity|coherence|watch|texture|memory TYPE BYTES|dirty TYPE STRIDE SESSION");
std::printf("PHASE2 protocol=1 mode=%s guest_pid=%lu\n",argv[1],GetCurrentProcessId());
if(std::string(argv[1])=="watch"){watch();std::puts("END success");return 0;}
Context c;
if(std::string(argv[1])=="identity")identity(c);
else if(std::string(argv[1])=="coherence")coherent(c);
else if(std::string(argv[1])=="negative-control")coherent(c,true);
else if(std::string(argv[1])=="texture")textures(c);
else if(std::string(argv[1])=="memory"&&argc==4)memory(c,argv[2],std::strtoull(argv[3],nullptr,10));
else if(std::string(argv[1])=="dirty"&&argc==5)dirty(c,argv[2],UINT(std::strtoul(argv[3],nullptr,10)),UINT(std::strtoul(argv[4],nullptr,10)));
else throw std::runtime_error("invalid mode or arguments");
std::puts("END success");return 0;
}catch(const std::exception& e){std::printf("END failure reason=%s\n",e.what());return 1;}
}
@@ -0,0 +1,50 @@
# Review of the M5 report and baseline source
Reviewed 2026-11-26: [2elliti's comment](https://github.com/MacosPorters/betterxen/issues/473#issuecomment-7201953364) and the actual [baseline source at 9ae6d1e](https://github.com/MacosPorters/betterxen/blob/9ae6d1ee7092b6021aad075531f50ba60de4fd53/docs/research/d3dmetal-zero-copy/probe.cpp). Public API expectations were re-derived from the Microsoft pages below, rather than treating either contributor's conclusions as ground truth. This is a technical source audit, not independent certification of the original author's probe or of the new supplemental code.
## What the M5 report establishes
The reported M5 has 17179869184 bytes RAM, macOS 27.0.1 (26A434), and CrossOver 26.3.0.39832. The report says the baseline source hash matched and all non-timing outcomes agreed with the M4 across five runs. The M5 used win10_64, bx-cli from cc5ce59, an empty shim directory and a 90-second timeout. Our M4 used the shared runner, win11_64 and 30 seconds. The M5 captured libd3dshared, which CrossOver also uses when D3DMetal is disabled; that alone does not identify the D3D12 backend. Its backend attribution therefore remains partial as the author states. This review did not obtain the private second probe or independently inspect the reported M5 raw logs: numerical M5 values below are attributed reports, not newly verified hardware measurements.
| Run | WB 64 KiB | WB 256 MiB | WC 256 MiB | UPLOAD 256 MiB |
| --- | ---: | ---: | ---: | ---: |
| M4 initial | 0.515898 | 0.773432 | 0.294052 | 0.252970 |
| M4 shared runner | 0.288957 | 0.299042 | 0.249347 | 0.204955 |
| M5 reported 1 | 0.607320 | 0.638232 | 0.449325 | 0.244737 |
| M5 reported 2 | 0.542233 | 0.663497 | 0.476485 | 0.233453 |
| M5 reported 3, OS polling | 0.430563 | 0.416307 | 0.419900 | 0.460607 |
| M5 reported 4, OS polling | 0.467363 | 0.615115 | 0.491113 | 0.244192 |
| M5 reported 5, OS polling | 0.479218 | 0.483435 | 0.466577 | 0.285473 |
Units: average ms/submit; each reported row had 40/40 timed and 5/5 warmup matches. Heap rankings are not stable. Different launch protocols, background polling, one chip of each type and large within-host variation prevent a generational speed comparison. A reproduction of the same source also reproduces any source defect; it is not an independently implemented oracle. The independent second M5 probe's reported AMD Compatibility Mode identity is a useful lead, not proof of physical GPU topology or a second independent data check for CUSTOM WB/L0, which that probe skipped.
## Claim-by-claim API and source assessment
| Material claim | Re-derived assessment and public primary reference |
| --- | --- |
| CPU-visible L0 CUSTOM heaps are UMA-only | Incorrect; 2elliti's correction is supported. For UMA=false, UPLOAD maps to WRITE_COMBINE/L0 and READBACK to WRITE_BACK/L0. DEFAULT maps to NOT_AVAILABLE/L1. Successful L0 creation does not establish awareness of physical unified memory. [GetCustomHeapProperties](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-getcustomheapproperties%28uint_d3d12_heap_type%29). |
| L1 control distinguishes physical architectures | It does not. L1 is unavailable on UMA; CPU-visible L1 is invalid on NUMA. E_INVALIDARG is the observed runtime result, not a promise that every implementation must return exactly that HRESULT. [Memory pools](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_memory_pool), [heap properties](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_heap_properties). |
| Check 5 measures allocation-sized transfer cost | Source inspection confirms only two 64-byte copies. The allocation's size changes the final source address, not copied byte count. Its timer also includes CPU stores, reset/encoding, barriers, fence wait and verification. [CopyBufferRegion](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12graphicscommandlist-copybufferregion). |
| UPLOAD and CUSTOM benchmark times are directly comparable | Source inspection confirms two source-state transitions for CUSTOM and none for UPLOAD. GENERIC_READ includes COPY_SOURCE and UPLOAD must remain in it. The baseline cannot fairly rank heap types. Supplemental dirty tests use GENERIC_READ for all sources and reuse pre-recorded command lists with no source barriers. [Resource states and barriers](https://learn.microsoft.com/en-us/windows/win32/direct3d12/using-resource-barriers-to-synchronize-resource-states-in-direct3d-12). |
| The timing rules out full-allocation copies | Too strong as a general mechanism claim. 256 MiB / 120 billion bytes/s is about 2.237 ms, but 120 GB/s was not measured here and is not a D3D12 guarantee. Read/write traffic, work overlap, caching, residency, compression and copying before the timing window matter. The source only establishes the observed elapsed times. Neither a theoretical bandwidth estimate nor flat timing proves physical sharing. |
| Persistent-map coherence proves physical aliasing | No. Public D3D12 permits persistent mapping of CPU-accessible resources with application synchronization. CPU stores must complete before GPU execution, and the CPU must wait for GPU completion before reading its results. The baseline's fence-separated visibility can also be implemented by copies. [Map](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-map), [SetEventOnCompletion](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12fence-seteventoncompletion). |
| UNKNOWN texture Map supplies no ordinary texel pointer | The baseline asks for no pointer at all: ppData=nullptr. Thus it never measured a pointer-return failure. Microsoft describes opaque layouts as precluding pointer disclosure for normal texel manipulation; Map with null ppData enables the CPU subresource methods. Do not infer an ordinary guest-pointer alias for such textures. [Map](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-map). |
| Every texture therefore requires an explicit staging copy | Not established. WriteToSubresource permits CPU texture updates and documents possible near-zero-copy UMA optimizations. That does not guarantee the implementation's internal mechanism. Texture GPU readback must be tested separately, with layout/format constraints; ROW_MAJOR is not a general substitute for opaque layout. [WriteToSubresource](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-writetosubresource), [ReadFromSubresource](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-readfromsubresource). |
| ROW_MAJOR creation success on an ordinary CPU-visible heap is portable evidence | No. The layout documentation requires a cross-adapter shared heap and limits textures to 2D, one mip/slice, 64 KiB alignment, no MSAA, no depth/stencil, no YUV. Phase two uses a DEFAULT shared-cross-adapter heap and ALLOW_CROSS_ADAPTER resource for this separate staging-copy control. It never reports a fabricated Map result when Map was not called. [Texture layouts](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_texture_layout), [shared heaps](https://learn.microsoft.com/en-us/windows/win32/direct3d12/shared-heaps), [resource flags](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_resource_flags). |
| 0/16384 write-watch writes test 4 KiB subpages | No; they address different 16 KiB intervals. Separate tests at 4096, 8192, 12288 and the 16383/16384 boundary are required. GetWriteWatch reports dirty page addresses and its own granularity; reset tests must exclude concurrent writes. [GetWriteWatch](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-getwritewatch). |
| IsolatedMMU=false proves GPU writes cannot be reported by write-watch | Too categorical. TRUE indicates GPU honoring of CPU page-table properties; FALSE supplies no such guarantee. A translation implementation could still cause CPU-side bookkeeping or copies that mark pages. A fallback must not rely on GPU writes being tracked, but absence of tracking cannot be inferred as a universal measured fact from this flag. [Architecture1](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_feature_data_architecture1). |
| 1x/2x footprint or a vmmap region label proves allocation identity | It does not. These are process-accounting observations influenced by graphics/driver charging, shared mappings, compression, allocator caches and sampling. A controlled slope across fully initialized sizes can reveal overhead in the observed accounting domain, but cannot identify physical pages or uncharged driver allocations. Microsoft's DXGI memory descriptions/budgets are also not a physical-page aliasing API. [DXGI adapter description](https://learn.microsoft.com/en-us/windows/win32/api/dxgi1_2/ns-dxgi1_2-dxgi_adapter_desc2), [QueryVideoMemoryInfo](https://learn.microsoft.com/en-us/windows/win32/api/dxgi1_4/nf-dxgi1_4-idxgiadapter3-queryvideomemoryinfo). |
| Dirty-k timing slope alone identifies internal dirty-page copies | No. It can expose a cost correlated with changed pages, but CPU page faults/tracking, cache behavior, transfer at other times and scheduling are alternative explanations. Phase two records dirty-write time separately, times identical submit/fence work and validates checksums outside the window. |
| OpenExistingHeapFrom* is the natural bridge on this installed stack | These public diagnostic APIs can expose system-memory heaps, but both observed versions returned E_NOTIMPL. Availability in Microsoft documentation does not imply implementation by D3DMetal. [Address API](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device3-openexistingheapfromaddress), [mapping API](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device3-openexistingheapfromfilemapping). |
The shared-heaps page itself has inconsistent wording about CPU page properties for cross-adapter heaps (a paragraph mentions WRITE_COMBINE; the subsequent limitations require DEFAULT or NOT_AVAILABLE/L0). This suite uses the unambiguous DEFAULT option, does not attempt CPU Map on that control, and does not generalize its result to CPU-visible shared heaps.
## Additional baseline audit observations
- Its six checks remain unchanged. Unsupported HRESULTs often return from a helper without incrementing the mismatch counter; exit 0 is not all-capabilities-supported. Read each result rather than the final counter alone.
- Its 64 KiB prefault stride does not fully initialize the intervening host pages. Phase-two footprint tests write every 32-bit word with an index-mixed pattern instead.
- The buffer coherence test performs copies, not shader reads/writes. The new shader test poisons the result before each dispatch, then validates three separate data rounds. An omitted-dispatch negative control must be detected.
- Resources remain live through their fences. The baseline uses disjoint placed-resource regions rather than switching overlapping aliases. CreatePlacedResource's advanced model permits non-overlapping use without the simple model's activation bookkeeping; it does not excuse missing barriers when memory is actually aliased. [CreatePlacedResource](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource).
- No GPU texture readback, arbitrary-memory integration, lifetime stress, memory-overhead study, GPU write-watch tracking or valid concurrent CPU/GPU atomic protocol can be inferred from the baseline.
The proposed concurrent-visibility experiment is assessed separately in [concurrent-review.md](concurrent-review.md). It is not a conformance gate and is not executed by the standardized synchronized suite.
@@ -0,0 +1,222 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Protocol 1 supplemental suite, separate from all six frozen baseline checks."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import plistlib
import shutil
import signal
import subprocess
import threading
import time
from datetime import datetime, timezone
def sha(p):
return hashlib.sha256(p.read_bytes()).hexdigest()
def capture(cmd, env, cwd, timeout=15):
start = time.monotonic()
try:
p = subprocess.run([str(x) for x in cmd], env=env, cwd=cwd,
capture_output=True, timeout=timeout)
return {"command": [str(x) for x in cmd], "exit": p.returncode,
"stdout": p.stdout.decode(errors="replace"),
"stderr": p.stderr.decode(errors="replace"),
"elapsed_seconds": time.monotonic() - start}
except subprocess.TimeoutExpired as e:
return {"command": [str(x) for x in cmd], "exit": 124, "timeout": True,
"stdout": (e.stdout or b"").decode(errors="replace"),
"stderr": (e.stderr or b"").decode(errors="replace")}
def main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--bottle", required=True, type=Path)
ap.add_argument("--scratch", required=True, type=Path)
ap.add_argument("--modes", default="identity,coherence,negative-control,watch,texture,dirty,memory")
ap.add_argument("--sessions", type=int, default=3, choices=[1, 2, 3])
ap.add_argument("--memory-repeats", type=int, default=2, choices=[1, 2, 3])
ap.add_argument("--large", action="store_true", help="also 2 GiB footprint cases; requires >=24 GiB RAM")
ap.add_argument("--crossover", type=Path, default=Path("/Applications/CrossOver.app"))
args = ap.parse_args()
src = Path(__file__).resolve().parent
repo = src.parents[3]
base = args.scratch.expanduser().resolve()
if base.exists() or base == repo or repo in base.parents:
ap.error("scratch must be a new directory outside the checkout")
bottle = args.bottle.expanduser().resolve()
if not (bottle / "cxbottle.conf").is_file():
ap.error("bottle must be an existing CrossOver bottle")
original = (bottle / "cxbottle.conf").read_bytes()
if b'"WineArch" = "win64"' not in original:
ap.error("requires win64 bottle")
modes = args.modes.split(",")
if set(modes) - {"identity", "coherence", "negative-control", "watch", "texture", "dirty", "memory"}:
ap.error("unknown mode")
base.mkdir(parents=True, mode=0o700)
env = {k: os.environ[k] for k in ["HOME", "USER", "LOGNAME", "PATH", "LANG", "LC_ALL", "DISPLAY"] if k in os.environ}
env.update(TMPDIR=str(base) + "/", ROSETTA_ADVERTISE_AVX="1", CX_GRAPHICS_BACKEND="d3dmetal", WINEDEBUG="-all")
cx = args.crossover.resolve() / "Contents/SharedSupport/CrossOver"
wine = cx / "bin/wine"
exe = base / "phase2.exe"
observer = base / "observe"
receipt = {"protocol": 1, "recorded_utc": datetime.now(timezone.utc).isoformat(),
"modes": modes, "sessions": args.sessions, "memory_repeats": args.memory_repeats,
"environment": {k: env[k] for k in ["ROSETTA_ADVERTISE_AVX", "CX_GRAPHICS_BACKEND", "WINEDEBUG"]},
"source_hashes": {p.name: sha(p) for p in src.iterdir() if p.suffix in [".cpp", ".py"]},
"baseline_sha256": sha(src.parent / "probe.cpp"), "tools": {}, "cases": []}
commands = {
"chip": ["sysctl", "-n", "machdep.cpu.brand_string"],
"ram": ["sysctl", "-n", "hw.memsize"], "macos": ["sw_vers"],
"host_page_size": ["sysctl", "-n", "hw.pagesize"],
"crossover": [wine, "--version"], "rosetta": ["pkgutil", "--pkg-info", "com.apple.pkg.RosettaUpdateAuto"],
"gcc": ["x86_64-w64-mingw32-g++", "--version"],
"clang": ["xcrun", "clang++", "--version"], "sdk": ["xcrun", "--show-sdk-version"],
"pressure_before": ["memory_pressure", "-Q"], "vm_before": ["vm_stat"],
"load_before": ["ps", "-axo", "pid,pcpu,comm"],
"build_pe": ["x86_64-w64-mingw32-g++", "-std=c++20", "-O2", "-static", "-static-libgcc", "-static-libstdc++", "-Wall", "-Wextra", "-Werror", src / "probe.cpp", "-o", exe, "-lkernel32"],
"build_observer": ["xcrun", "clang++", "-std=c++20", "-O2", "-arch", "arm64", "-Wall", "-Wextra", "-Werror", src / "observe.cpp", "-o", observer],
"binary_formats": ["file", exe, observer], "observer_arch": ["lipo", "-archs", observer],
"observer_links": ["otool", "-L", observer],
}
for name, cmd in commands.items():
receipt["tools"][name] = capture(cmd, env, base, timeout=45)
if name.startswith("build_") and receipt["tools"][name]["exit"]:
(base / "receipt.json").write_text(json.dumps(receipt, indent=2))
raise RuntimeError(receipt["tools"][name])
receipt["binary_hashes"] = {"phase2.exe": sha(exe), "observe": sha(observer)}
ram = int(receipt["tools"]["ram"]["stdout"].strip())
if args.large and ram < 24 * 1024**3:
ap.error("--large requires >=24 GiB; common profile is identical on 16/24 GiB hosts")
framework = cx / "lib64/apple_gptk/external/D3DMetal.framework/Versions/A/Resources"
receipt["framework"] = {p.name: plistlib.loads(p.read_bytes()) for p in framework.glob("*.plist")}
for p in [cx / "lib64/apple_gptk/wine/x86_64-windows/d3d12.dll", cx / "lib/wine/x86_64-windows/d3dcompiler_47.dll"]:
receipt.setdefault("installed_dll_hashes", {})[str(p)] = sha(p)
temp = base / "bottle"
shutil.copytree(bottle, temp, symlinks=True)
conf = original.decode().replace("[Bottle]", '[Bottle]\n"AllowUntrusted" = "1"', 1)
conf += '\n[EnvironmentVariables]\n"CX_GRAPHICS_BACKEND" = "d3dmetal"\n[CrossOver]\n"AntiVirusScan" = "untrusted"\n'
(temp / "cxbottle.conf").write_text(conf)
receipt["source_bottle_config_sha256"] = hashlib.sha256(original).hexdigest()
receipt["temporary_bottle_config"] = {"template": "inherited; inspect source config", "architecture": "win64", "backend": "d3dmetal", "no_update": True, "AntiVirusScan": "untrusted", "AllowUntrusted": 1}
common = [str(wine), "--bottle", str(temp), "--no-update", "--no-gui", str(exe)]
backend_seen = False
def run_case(name, argv, memory=False):
nonlocal backend_seen
case = base / name
case.mkdir()
metadata = {"expected_exit": 1 if argv[0] == "negative-control" else 0, "name": name, "args": argv, "command": common + argv, "timeout_seconds": 150 if memory else 90, "snapshots": []}
stdout = case / "stdout.txt"
stderr = case / "stderr.txt"
timed_out = threading.Event()
start = time.monotonic()
with stdout.open("wb") as out, stderr.open("wb") as err:
p = subprocess.Popen(common + argv, env=env, cwd=case, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=err, start_new_session=True)
def expire():
timed_out.set()
try:
os.killpg(p.pid, signal.SIGKILL)
except ProcessLookupError:
pass
timer = threading.Timer(metadata["timeout_seconds"], expire)
timer.start()
hostpid = None
try:
for line in p.stdout:
out.write(line)
out.flush()
if not line.startswith(b"STAGE "):
continue
if hostpid is None:
found = capture(["lsof", "-t", "-a", "-c", "phase2.exe", str(exe)], env, base)
candidates = sorted({int(x) for x in found["stdout"].split() if x.isdigit()})
if len(candidates) != 1:
metadata["pid_lookup"] = found
raise RuntimeError("need exactly one process mapping this scratch PE")
hostpid = candidates[0]
metadata["host_pid"] = hostpid
phase = line.decode().split()[1]
snap = {"phase": phase, "marker": line.decode().strip(), "samples": []}
for _ in range(3):
sample = capture([observer, str(hostpid)], env, base)
try:
sample["data"] = json.loads(sample["stdout"])
except json.JSONDecodeError:
pass
snap["samples"].append(sample)
for tool, command in {
"footprint": ["footprint", "-p", str(hostpid), "-f", "bytes"],
"vmmap": ["vmmap", "-summary", str(hostpid)],
"vmstat": ["vm_stat"], "pressure": ["memory_pressure", "-Q"],
}.items():
result = capture(command, env, base, timeout=12)
(case / f"{phase}-{tool}.json").write_text(json.dumps(result, indent=2))
snap[tool] = {"exit": result["exit"], "file": f"{phase}-{tool}.json"}
if not backend_seen:
result = capture(["lsof", "-n", "-p", str(hostpid)], env, base)
metadata["backend_paths_excerpt"] = ["/" + line.split("/", 1)[1] for line in result["stdout"].splitlines() if any(key in line for key in ["apple_gptk/wine/x86_64-windows/d3d12.dll", "apple_gptk/wine/x86_64-windows/dxgi.dll", "D3DMetal.framework/Versions/A/D3DMetal", "/rosetta/runtime"])]
backend_seen = any("/D3DMetal" in path for path in metadata["backend_paths_excerpt"])
metadata["snapshots"].append(snap)
p.stdin.write(b"\n")
p.stdin.flush()
p.wait()
except BaseException:
try:
os.killpg(p.pid, signal.SIGKILL)
except ProcessLookupError:
pass
p.wait()
raise
finally:
timer.cancel()
metadata.update(exit=p.returncode, timed_out=timed_out.is_set(), elapsed_seconds=time.monotonic() - start)
(case / "case.json").write_text(json.dumps(metadata, indent=2))
receipt["cases"].append(metadata)
(base / "receipt.json").write_text(json.dumps(receipt, indent=2))
if argv[0] == "negative-control":
metadata["negative_control_detected"] = b"END failure reason=GPU checksum mismatch" in stdout.read_bytes()
if not metadata["negative_control_detected"]:
raise RuntimeError("negative control did not detect an omitted dispatch")
print(name, "exit", metadata["exit"], "expected", metadata["expected_exit"], "timeout", metadata["timed_out"], flush=True)
try:
for mode in ["identity", "coherence", "negative-control", "watch", "texture"]:
if mode in modes:
run_case(mode, [mode])
if "dirty" in modes:
for session in range(args.sessions):
for stride in [4096, 16384]:
# Alternate heap order; no background OS polling during latency cases.
types = ["wb", "wc", "upload"]
if session % 2:
types.reverse()
for heap in types:
run_case(f"dirty-{heap}-{stride}-s{session}", ["dirty", heap, str(stride), str(session)])
if "memory" in modes:
for repeat in range(args.memory_repeats):
for size in [64, 256, 1024] + ([2048] if args.large else []):
for heap in ["cpu", "wb", "upload"]:
run_case(f"memory-{heap}-{size}MiB-r{repeat}", ["memory", heap, str(size * 1024**2)], memory=True)
finally:
receipt["tools"]["pressure_after"] = capture(["memory_pressure", "-Q"], env, base)
receipt["tools"]["vm_after"] = capture(["vm_stat"], env, base)
receipt["source_bottle_config_unchanged"] = (bottle / "cxbottle.conf").read_bytes() == original
stop = dict(env, WINEPREFIX=str(temp))
receipt["server_stop"] = capture([cx / "bin/wineserver", "-k"], stop, base)
receipt["server_wait"] = capture([cx / "bin/wineserver", "-w"], stop, base)
shutil.rmtree(temp)
(base / "receipt.json").write_text(json.dumps(receipt, indent=2) + "\n")
failures = [c["name"] for c in receipt["cases"] if c["exit"] != c["expected_exit"] or c["timed_out"]]
print("Completed", len(receipt["cases"]), "cases; failures:", failures)
return bool(failures)
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Derive inspectable summaries from protocol-1 raw logs; never rewrite inputs."""
import argparse
import json
from pathlib import Path
import re
import statistics
def fields(line):
return dict(re.findall(r"(\w+)=([^ ]+)", line))
def summarize(root):
result = {"memory": [], "dirty": [], "runs": []}
for receipt in sorted(root.rglob("receipt.json")):
doc = json.loads(receipt.read_text())
if doc.get("protocol") != 1:
continue
result["runs"].append({"path": str(receipt.relative_to(root)),
"source_hashes": doc["source_hashes"],
"baseline_sha256": doc["baseline_sha256"]})
for path in sorted(root.rglob("case.json")):
case = json.loads(path.read_text())
result.setdefault("outcomes", []).append({"path": str(path.relative_to(root)),
"exit": case["exit"], "expected_exit": case.get("expected_exit", 0),
"timed_out": case["timed_out"]})
if case["name"].startswith("memory-") and case.get("snapshots"):
stages = {}
for snapshot in case["snapshots"]:
data = [sample["data"] for sample in snapshot["samples"]
if sample.get("data", {}).get("return") == 0]
if data:
stages[snapshot["phase"]] = {key: statistics.median(d[key] for d in data)
for key in ["phys_footprint", "resident_size", "wired_size", "pageins"]}
baseline = stages["baseline"]["phys_footprint"]
result["memory"].append({"name": case["name"], "args": case["args"], "stages": stages,
"footprint_delta_bytes": {phase: values["phys_footprint"] - baseline for phase, values in stages.items()}})
stdout = path.with_name("stdout.txt")
if stdout.exists():
lines = stdout.read_text().splitlines()
samples = [fields(line) for line in lines if line.startswith("DIRTY_SAMPLE ")]
for line in lines:
if not line.startswith("DIRTY_RESULT "):
continue
row = fields(line)
row["case"] = case["name"]
matching = [s for s in samples if s["k"] == row["k"]]
cpu = [float(s["dirty_cpu_ms"]) for s in matching if "dirty_cpu_ms" in s]
row["median_dirty_cpu_ms"] = statistics.median(cpu) if cpu else None
result["dirty"].append(row)
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("root", type=Path)
args = parser.parse_args()
print(json.dumps(summarize(args.root), indent=2))
if __name__ == "__main__":
main()
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,25 @@
# Inverted ownership feasibility
This requirement matrix informs [#464](https://github.com/MacosPorters/betterxen/issues/464) without modifying or certifying it. The inspected in-tree contracts are pinned at research revision `9ae6d1ee7092b6021aad075531f50ba60de4fd53`: `abi/include/bx_xmem_internal.h`, `shims/xmem/xmem.cpp`, `shims/xmem/physical_pages.cpp` and `abi/defs/xmem.def`. They describe BetterXen's implementation, not an independently verified console allocation contract. Memory-attribute meanings not established by public evidence remain unknown.
A D3D12-owned mapped buffer is a candidate provider for a subset of allocations. It is not a general replacement for the present xmem allocation engines.
| Requirement | Evidence / feasibility | Necessary fallback or further work |
| --- | --- | --- |
| Ordinary CPU-visible byte allocation | Persistent buffer Map supported in baseline; A2 full-consumption checks add accounting evidence. Candidate within live resource lifetime. | Keep owner/resource metadata and explicit synchronization; independent acceptance pending. |
| 64-byte alignment of XMemAllocDefault | Existing xmem heap returns 64-byte-aligned data. Biased byte slices can potentially satisfy this inside a sufficiently sized buffer. | Validate buffer offsets and bounds; do not change production in this research. |
| 64 KiB resource placement | GetResourceAllocationInfo and aligned heap offsets determine GPU placement. | Not a CPU-pointer alignment guarantee. |
| 64 KiB CPU pointer | New M4 64 MiB WB and UPLOAD maps observed at 16 KiB modulo 64 KiB. Unconditionally handing out the base does not satisfy this requirement. | Overallocate and bias byte slices only where guest/GPU address-offset contracts permit it; otherwise CPU-owned allocation and explicit transfer. |
| 2 MiB CPU alignment/page size | Physical-page engine supports flagged 2 MiB sections; no D3D12 Map promise provides this CPU alignment or page identity. | Preserve section-backed path; extra padding alone does not provide physical-page semantics. |
| Requested CPU virtual address | CreateHeap/CreatePlacedResource/Map provide no requested CPU-VA parameter. XMemVirtualAlloc and physical map paths accept one. | VirtualAlloc/placeholder/section mechanism; logged explicit graphics transfer where needed. Do not relocate a guest allocation silently. |
| Reserve now, commit/decommit later | In-tree XMemVirtualAlloc forwards MEM_RESERVE/COMMIT/RESET and tracks commits; decommits are reconciled with VirtualQuery. A mapped D3D12 buffer is not an interchangeable reservation. | Keep CPU VA reservation path. GPU reserved resources are a separate GPU-VA concept, not proof of CPU-VA equivalence. |
| Win32 protection/guard/cache flags | In-tree xmem normalizes a subset of page protections and flags. CPU cache property selection exists in CUSTOM heaps, not a general VirtualProtect/page-guard contract. | Preserve unsupported combinations on CPU path, retain original attributes rather than infer their console meaning. |
| Caller-owned allocation made before device creation | No D3D12 buffer can exist before its device. Both existing-memory heap opens returned E_NOTIMPL in published baseline observations on these runtime versions. | CPU allocation plus explicit copy; do not move a live pointer after creating the device. |
| Physical tags and multiple CPU aliases | Physical engine owns file-mapping sections, stable tags and independently placed CPU views. Public D3D12 GPU heap aliasing does not expose equivalent section handles or arbitrary CPU aliases. | Retain section-backed pages and translation/copy boundary; alias correctness is not solved by Map. |
| Scatter mappings/reordered page views | In-tree contiguous/scatter entry points both route through section/placeholder view logic; D3D12 Map alone exposes no equivalent requested CPU scatter mapping. | Preserve engine; future bridging requires a demonstrated interface, not pointer arithmetic. |
| xmem region query | Current bx_xmem_query_region describes physical mapped views, verifies MEM_MAPPED, and returns page tag/protection/type. Ordinary virtual and D3D12 allocations are not automatically registered. | Any future cross-DLL provider metadata would need separate maintainer/ABI work outside #473. |
| Unified logical budget | Current xmem tracks virtual commits/heap bytes/physical pages; D3D12 allocations outside it are not automatically included. | One logical owner/charge, bounded slab reservation and retirement accounting; host footprint/headroom tracked separately. Do not double-charge a live slice and its slab. |
| GPU lifetime while guest frees pointer | Resource/heap/mapped pointer must survive last GPU use; A tests explicit delayed retirement. | Queue/fence retirement records, no reuse or pointer access after disposal. Multi-queue/reference stress remains open. |
| Texture placed over arbitrary CPU pointer | UNKNOWN texture layouts are opaque; buffer sharing does not supply a raw texel alias or console tile mapping. | Explicit texture upload/readback APIs and format/layout handling; do not assume every internal texture path copies. |
[Resource and lifetime contracts](../gpu-correctness/contracts/resource-placement-lifetime.md) link primary D3D12 documentation. Local observations are class A within their workloads; public API constraints class B; compatibility with unverified console semantics and physical backing remain class U. No production adoption is recommended solely from these synthetic checks.
@@ -0,0 +1,110 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Workstream A protocol A2: correct baseline and retirement scope, not a copy
// detector.
#include "support.h"
#include <memory>
static void stage(const char *name, void *cpu = nullptr) {
std::printf("STAGE %s cpu_ptr=%p\n", name, cpu);
if (std::getchar() == EOF)
throw std::runtime_error("stage handshake lost");
}
int main(int argc, char **argv) {
setvbuf(stdout, nullptr, _IONBF, 0);
try {
if (argc != 3)
throw std::runtime_error("usage: memory cpu|cpu-plain|wb|upload BYTES");
std::string type = argv[1];
UINT64 bytes = std::strtoull(argv[2], nullptr, 10);
if (bytes != 64 * 1024 * 1024ULL && bytes != 256 * 1024 * 1024ULL &&
bytes != 1024 * 1024 * 1024ULL)
throw std::runtime_error("size outside common profile");
if (type != "cpu" && type != "cpu-plain" && type != "wb" &&
type != "upload")
throw std::runtime_error("type");
std::printf("MEMORY_A protocol=2 type=%s bytes=%llu\n", type.c_str(),
bytes);
std::unique_ptr<Context> c;
std::unique_ptr<Shader> shader;
std::unique_ptr<Queue> q;
Buffer output;
if (type != "cpu-plain") {
c = std::make_unique<Context>();
shader = std::make_unique<Shader>(*c);
q = std::make_unique<Queue>(c->device.p);
Buffer tiny;
tiny.allocate(c->device.p, 65536, "upload");
tiny.map();
std::memset(tiny.cpu, 0, 65536);
output.allocate(c->device.p, 65536, "wb", true);
output.map();
shader->dispatch(*q, tiny, output, 1, 0, 1);
// Dispose the warm-up command objects before baseline; keep matched
// pipeline/output.
q.reset();
tiny.release();
q = std::make_unique<Queue>(c->device.p);
}
stage("warm_baseline");
Sleep(500);
stage("baseline");
Buffer src;
void *cpu = nullptr;
if (type == "cpu" || type == "cpu-plain") {
cpu = VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE);
if (!cpu)
throw std::runtime_error("VirtualAlloc");
} else
src.allocate(c->device.p, bytes, type);
stage("created");
if (src.resource.p) {
src.map();
cpu = src.cpu;
}
stage("mapped", cpu);
auto p = static_cast<volatile uint32_t *>(cpu);
std::array<uint32_t, 256> expected{};
for (UINT64 i = 0; i < bytes / 4; ++i) {
uint32_t v = pattern(i, 0x24681357u);
p[i] = v;
expected[i % 256] ^= v + 0x10101u;
}
_mm_sfence();
stage("fully_initialized", cpu);
if (src.resource.p) {
shader->dispatch(*q, src, output, UINT(bytes / 4), 0x10101u, 1);
size_t matches = 0;
for (UINT i = 0; i < 256; ++i)
matches +=
static_cast<volatile uint32_t *>(output.cpu)[i] == expected[i];
std::printf(
"VERIFY full_consumption checksum_matches=%zu/256 words=%llu\n",
matches, bytes / 4);
if (matches != 256)
throw std::runtime_error("full-consumption checksum mismatch");
} else
std::puts("GPU_CONSUMPTION NOT_RUN CPU_allocation_control");
stage("gpu_complete", cpu);
if (src.resource.p)
src.release();
else if (!VirtualFree(cpu, 0, MEM_RELEASE))
throw std::runtime_error("VirtualFree");
cpu = nullptr;
stage("resources_released");
// Fence already completed; dispose all
// command-list/allocator/queue/fence/pipeline resources.
q.reset();
output.release();
shader.reset();
stage("commands_retired");
Sleep(500);
stage("retired_settled");
c.reset();
stage("device_released");
std::puts("END success");
return 0;
} catch (const std::exception &e) {
std::printf("END failure reason=%s\n", e.what());
return 1;
}
}
@@ -0,0 +1,23 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original macOS process accounting observer; native ARM64 only.
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <libproc.h>
#include <sys/resource.h>
#include <unistd.h>
int main(int argc, char **argv) {
if (argc != 2)
return 2;
rusage_info_v4 r{};
int pid = std::atoi(argv[1]);
int rc = proc_pid_rusage(pid, RUSAGE_INFO_V4,
reinterpret_cast<rusage_info_t *>(&r));
std::printf("{\"pid\":%d,\"return\":%d,\"errno\":%d,\"host_page_size\":%d,"
"\"phys_footprint\":%llu,\"resident_size\":%llu,\"wired_size\":%"
"llu,\"pageins\":%llu,\"max_phys_footprint\":%llu}\n",
pid, rc, rc ? errno : 0, getpagesize(), r.ri_phys_footprint,
r.ri_resident_size, r.ri_wired_size, r.ri_pageins,
r.ri_lifetime_max_phys_footprint);
return rc ? 1 : 0;
}
@@ -0,0 +1,356 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original bounded allocation trace. Not a production allocator.
#include "support.h"
#include <memory>
#include <random>
static constexpr UINT64 slabBytes = 32ULL * 1024 * 1024;
static constexpr int slots = 24;
static void stage(const char *phase) {
std::printf("STAGE %s cpu_ptr=0\n", phase);
if (std::getchar() == EOF)
throw std::runtime_error("stage handshake lost");
}
static double milliseconds(double start) {
return (ticks() - start) * 1000 / frequency();
}
struct Span {
UINT64 offset, size;
};
struct FreeList {
std::vector<Span> free{{0, slabBytes}};
UINT64 take(UINT64 size, UINT64 align) {
for (size_t i = 0; i < free.size(); ++i) {
Span old = free[i];
UINT64 start = (old.offset + align - 1) / align * align;
if (start < old.offset || start - old.offset > old.size ||
size > old.size - (start - old.offset))
continue;
free.erase(free.begin() + i);
if (start > old.offset)
free.push_back({old.offset, start - old.offset});
if (start + size < old.offset + old.size)
free.push_back({start + size, old.offset + old.size - start - size});
return start;
}
throw std::runtime_error("bounded slab exhausted");
}
void give(UINT64 offset, UINT64 size) {
free.push_back({offset, size});
std::sort(free.begin(), free.end(),
[](auto a, auto b) { return a.offset < b.offset; });
std::vector<Span> merged;
for (auto v : free) {
if (!merged.empty() &&
merged.back().offset + merged.back().size > v.offset)
throw std::runtime_error("overlapping free span");
if (!merged.empty() &&
merged.back().offset + merged.back().size == v.offset)
merged.back().size += v.size;
else
merged.push_back(v);
}
free = merged;
}
};
struct Allocation {
Ref<ID3D12Heap> heap;
Ref<ID3D12Resource> resource;
void *cpu = nullptr;
UINT64 bytes = 0, reserved = 0, offset = 0;
UINT seed = 0;
};
struct Trace {
Context c;
std::unique_ptr<Queue> q;
Ref<ID3D12Heap> slab;
FreeList free;
std::array<Allocation, slots> live;
Buffer read;
bool pooled, omit = false;
UINT seed;
std::mt19937 rng;
double heapSetup = 0;
UINT64 peakLive = 0, peakReserved = 0;
Trace(bool pool, UINT s, bool omitCopy)
: pooled(pool), omit(omitCopy), seed(s), rng(s) {
q = std::make_unique<Queue>(c.device.p);
read.allocate(c.device.p, slots * 192, "readback");
read.map();
std::printf("TRACE mode=%s seed=%u slab_bytes=%llu slots=%d "
"pre_setup_ms=%.6f warmups=2 timed=10\n",
pooled ? "pooled" : "individual", seed, pooled ? slabBytes : 0,
slots, heapSetup);
}
void createHeap(UINT64 bytes, Ref<ID3D12Heap> &heap) {
D3D12_HEAP_DESC d{};
d.SizeInBytes = bytes;
d.Alignment = 65536;
d.Properties = properties(D3D12_HEAP_TYPE_CUSTOM);
d.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
d.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
d.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS;
require(c.device->CreateHeap(&d, __uuidof(ID3D12Heap), heap.out()),
"trace CreateHeap");
}
void allocate(int slot, int iteration, int phase) {
auto &a = live[slot];
if (a.resource.p)
throw std::runtime_error("occupied slot");
const UINT64 sizes[] = {65540, 262148, 1048580, 393220};
a.bytes = sizes[rng() % 4];
a.seed = seed ^ UINT(iteration + 11) * 0x1020301u ^ UINT(slot) * 0x9001u ^
UINT(phase) * 0xB3u;
auto desc = bufferDesc(a.bytes);
auto ai = c.device->GetResourceAllocationInfo(0, 1, &desc);
if (!ai.Alignment || ai.SizeInBytes == ~UINT64(0))
throw std::runtime_error("buffer allocation info");
a.reserved = ai.SizeInBytes;
double start = ticks();
if (pooled)
a.offset = free.take(ai.SizeInBytes, ai.Alignment);
else
createHeap(ai.SizeInBytes, a.heap);
double heapMs = milliseconds(start);
start = ticks();
require(c.device->CreatePlacedResource(
pooled ? slab.p : a.heap.p, a.offset, &desc,
D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
__uuidof(ID3D12Resource), a.resource.out()),
"trace placement");
double placeMs = milliseconds(start);
start = ticks();
D3D12_RANGE empty{0, 0};
require(a.resource->Map(0, &empty, &a.cpu), "trace Map");
double mapMs = milliseconds(start);
if (!a.cpu)
throw std::runtime_error("trace null map");
auto p = static_cast<volatile uint32_t *>(a.cpu);
for (UINT64 i = 0; i < a.bytes / 4; ++i)
p[i] = pattern(i, a.seed);
_mm_sfence();
std::printf("ALLOC iteration=%d phase=%d slot=%d bytes=%llu reserved=%llu "
"offset=%llu alignment=%llu heap_or_suballoc_ms=%.6f "
"placement_ms=%.6f map_ms=%.6f warmup=%d\n",
iteration, phase, slot, a.bytes, a.reserved, a.offset,
ai.Alignment, heapMs, placeMs, mapMs, iteration < 0);
}
void stats(int iteration, const char *phase) {
UINT64 payload = 0, reserved = 0, totalFree = 0, largest = 0;
for (auto &a : live)
if (a.resource.p) {
payload += a.bytes;
reserved += a.reserved;
}
if (pooled)
for (auto s : free.free) {
totalFree += s.size;
largest = std::max(largest, s.size);
}
UINT64 backing = pooled ? slabBytes : reserved;
peakLive = std::max(peakLive, payload);
peakReserved = std::max(peakReserved, backing);
std::printf("FRAGMENT iteration=%d phase=%s live_payload=%llu "
"live_reserved=%llu backing_reserved=%llu alignment_waste=%llu "
"total_free=%llu largest_free=%llu free_span_count=%zu\n",
iteration, phase, payload, reserved, backing,
reserved - payload, totalFree, largest,
pooled ? free.free.size() : 0);
}
void verify(int iteration, int phase) {
// Every recycled placed resource is explicitly activated; no inheritance is
// assumed.
q->begin();
auto rb = static_cast<unsigned char *>(read.cpu);
std::memset(rb, 0xA7, slots * 192);
for (int slot = 0; slot < slots; ++slot) {
auto &a = live[slot];
if (!a.resource.p)
continue;
D3D12_RESOURCE_BARRIER alias{};
alias.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING;
alias.Aliasing.pResourceAfter = a.resource.p;
q->list->ResourceBarrier(1, &alias);
if (!omit)
for (int part = 0; part < 3; ++part) {
UINT64 src = part == 0 ? 0
: part == 1 ? (a.bytes / 2 / 4) * 4
: a.bytes - 64;
q->list->CopyBufferRegion(read.resource.p, slot * 192 + part * 64,
a.resource.p, src, 64);
}
}
_mm_sfence();
q->finish();
int matches = 0, expected = 0;
for (int slot = 0; slot < slots; ++slot) {
auto &a = live[slot];
if (!a.resource.p)
continue;
for (int part = 0; part < 3; ++part) {
UINT64 src = part == 0 ? 0
: part == 1 ? (a.bytes / 2 / 4) * 4
: a.bytes - 64;
auto p =
reinterpret_cast<volatile uint32_t *>(rb + slot * 192 + part * 64);
for (int i = 0; i < 16; ++i) {
++expected;
matches += p[i] == pattern(src / 4 + i, a.seed);
}
}
}
std::printf("READBACK iteration=%d phase=%d matches=%d/%d fence=%llu "
"completed=%llu\n",
iteration, phase, matches, expected, q->value,
q->fence->GetCompletedValue());
if (matches != expected)
throw std::runtime_error("trace guard/interior mismatch");
// Complete list retirement precedes free-list reuse; a fence alone is not
// ref-count evidence.
q->begin();
q->close();
}
void release(int slot, int iteration) {
auto &a = live[slot];
if (!a.resource.p)
return;
UINT64 completed = q->fence->GetCompletedValue();
if (completed < q->value)
throw std::runtime_error("premature reuse rejected");
double start = ticks();
a.resource->Unmap(0, nullptr);
a.cpu = nullptr;
a.resource.clear();
double resourceMs = milliseconds(start);
start = ticks();
if (pooled)
free.give(a.offset, a.reserved);
else
a.heap.clear();
double backingMs = milliseconds(start);
std::printf(
"FREE iteration=%d slot=%d resource_ms=%.6f "
"backing_or_freelist_ms=%.6f retire_fence=%llu completed=%llu\n",
iteration, slot, resourceMs, backingMs, q->value, completed);
}
void delayedRetirement() {
allocate(0, -3, 0);
auto &a = live[0];
Ref<ID3D12Fence> gate;
require(c.device->CreateFence(0, D3D12_FENCE_FLAG_NONE,
__uuidof(ID3D12Fence), gate.out()),
"retirement gate");
struct OpenGate {
ID3D12Fence *f;
~OpenGate() { f->Signal(1); }
} cleanup{gate.p};
q->begin();
D3D12_RESOURCE_BARRIER activation{};
activation.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING;
activation.Aliasing.pResourceAfter = a.resource.p;
q->list->ResourceBarrier(1, &activation);
q->list->CopyBufferRegion(read.resource.p, 0, a.resource.p, 0, 64);
q->close();
_mm_sfence();
require(q->q->Wait(gate.p, 1), "queue gate wait");
ID3D12CommandList *lists[] = {q->list.p};
q->q->ExecuteCommandLists(1, lists);
UINT64 target = ++q->value;
require(q->q->Signal(q->fence.p, target), "retirement signal");
UINT64 completed = q->fence->GetCompletedValue();
bool withheld = completed < target;
// No free, overwrite, or second resource activation occurs while this range
// is pending.
require(gate->Signal(1), "open retirement gate");
require(q->fence->SetEventOnCompletion(target, q->event),
"retirement event");
if (WaitForSingleObject(q->event, 10000) != WAIT_OBJECT_0)
throw std::runtime_error("retirement wait timeout");
std::printf(
"DELAYED_RETIRE target=%llu before=%llu withheld=%d after=%llu\n",
target, completed, withheld, q->fence->GetCompletedValue());
if (!withheld)
throw std::runtime_error("pending range was not withheld");
for (int i = 0; i < 16; ++i)
if (static_cast<volatile uint32_t *>(read.cpu)[i] != pattern(i, a.seed))
throw std::runtime_error("delayed readback mismatch");
q->begin();
q->close();
release(0, -3);
}
void run() {
stage("baseline");
if (pooled) {
double start = ticks();
createHeap(slabBytes, slab);
heapSetup = milliseconds(start);
}
std::printf("POOL_SETUP mode=%s heap_ms=%.6f reserved_bytes=%llu\n",
pooled ? "pooled" : "individual", heapSetup,
pooled ? slabBytes : 0);
stage("heap_ready");
delayedRetirement();
for (int iteration = -2; iteration < 10; ++iteration) {
double start = ticks();
for (int i = 0; i < slots; ++i)
allocate(i, iteration, 0);
stats(iteration, "full");
verify(iteration, 0);
for (int i = 0; i < slots; i += 2)
release(i, iteration);
stats(iteration, "holes");
// Before the next real fence, a fictitious future retirement value must
// be rejected.
UINT64 completed = q->fence->GetCompletedValue(), future = q->value + 1;
bool withheld = completed < future;
std::printf("RETIRE_POLICY future=%llu completed=%llu withheld=%d\n",
future, completed, withheld);
if (!withheld)
throw std::runtime_error("retire policy control");
for (int i = 0; i < slots; i += 2)
allocate(i, iteration, 1);
stats(iteration, "refill");
verify(iteration, 1);
if (iteration == 0) {
double pause = ticks();
stage("live");
start += ticks() - pause;
}
for (int i = 0; i < slots; ++i)
release(i, iteration);
stats(iteration, "empty");
if (pooled && (free.free.size() != 1 || free.free[0].offset ||
free.free[0].size != slabBytes))
throw std::runtime_error("free-list failed to coalesce");
std::printf("CYCLE iteration=%d ms=%.6f warmup=%d\n", iteration,
milliseconds(start), iteration < 0);
}
stage("resources_released");
q.reset();
read.release();
slab.clear();
stage("commands_retired");
Sleep(500);
stage("retired_settled");
std::printf("TRACE_END peak_logical_live=%llu peak_reserved=%llu\n",
peakLive, peakReserved);
}
};
int main(int argc, char **argv) {
setvbuf(stdout, nullptr, _IONBF, 0);
try {
if (argc != 3)
throw std::runtime_error("usage: pool individual|pooled|omit SEED");
std::string mode = argv[1];
if (mode != "individual" && mode != "pooled" && mode != "omit")
throw std::runtime_error("mode");
Trace trace(mode != "individual", UINT(std::strtoul(argv[2], nullptr, 10)),
mode == "omit");
trace.run();
std::puts("END success");
return 0;
} catch (const std::exception &e) {
std::printf("END failure reason=%s\n", e.what());
return 1;
}
}
@@ -0,0 +1,35 @@
# Allocation, pooling, fragmentation and retirement
Local author observations on the M4/CrossOver/D3DMetal environment recorded by the [corrected trace receipt](../results/2026-11-26-apple-m4-arths17-a22-pool-corrected/receipt.json). Independent acceptance is pending. The trace is an original bounded experimental allocator, not production code or an evaluation run of AMD's allocator.
## Comparison
Six fresh processes form three matched seeded pairs (473, 474, 475). Each uses 24 buffer slots, two warmup cycles, ten timed cycles, and exactly the same live sizes/data/GPU readback work in both modes. Individual mode creates a CUSTOM/WB/L0 heap per allocation; pooled mode places resources in a 32 MiB slab. Each measured process has 360 allocation samples and 360 frees; samples within cycles are correlated. Reported distributions, raw samples, seeds and executed sources are retained. No background profiler runs inside the API windows.
| Seed | Individual heap creation median ms | Pool suballocation median ms | Individual placement median ms | Pool placement median ms | Individual cycle median ms | Pool cycle median ms |
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
| 473 | 0.01250 | 0.00010 | 0.00070 | 0.00100 | 12.62715 | 12.47335 |
| 474 | 0.01230 | 0.00010 | 0.00070 | 0.00090 | 12.33830 | 11.90645 |
| 475 | 0.01265 | 0.00010 | 0.00070 | 0.00100 | 12.68280 | 12.33040 |
Cold pooled heap setup was separately 6.5561, 6.8396 and 6.5303 ms. Do not omit that cost when discussing first use. Map median was near the reporting floor in both modes. Whole cycles include initialization, raw-log output, GPU copies/fence waits, validation and free-list operations, so they are not isolated allocator timings. The live snapshot pause is subtracted. Zero/near-zero API samples reflect measurement precision and call overhead, not zero execution cost.
Within this workload, replacing repeated heap creation with a free-list operation reduces the measured allocation-call component. The cycle difference is small, placement is slightly costlier, the host is busy and uses the explicit warning-pressure profile. An earlier preserved pair even had the opposite whole-cycle ordering (12.2991 versus 15.8891 ms). These data do not establish a stable application-level speedup or a production benefit. No title/framerate or cross-generation claim is supported.
## Memory and fragmentation
The first trace version created its pooled heap before the baseline. Its raw runs remain [preserved](../results/2026-11-26-apple-m4-arths17-a22-pool-first-pair/receipt.json), with [continuation pairs](../results/2026-11-26-apple-m4-arths17-a22-pool-pre-correction/receipt.json). Their API samples are inspectable, but baseline deltas hide slab creation. The corrected source moves slab creation after a matched baseline and adds heap_ready. Its initial TRACE line still contains the pre-allocation setup value 0; actual cost is the subsequent POOL_SETUP record. Current source renames that initial field pre_setup_ms only; the timing results above are tied to the exact archived executed source. The later omitted-copy control exercises the source after that logging-only rename.
In corrected seed 473, individual baseline was 34.58 MiB and heap_ready 34.67 MiB; pool baseline was 34.49 MiB and heap_ready 66.73 MiB. Thus the one-time slab charge is visible. At the live checkpoint both are about 332 MiB, and after command/slab/readback release both remain about 292 MiB. This shared accounting behavior does not establish a memory saving from pooling or identify the retained backing. The three pairs have similar absolute readings; all raw tool categories and RSS/footprint distinctions remain available.
The pool reserves 32 MiB irrespective of live payload. Individual heaps reserve the sum of resource allocation sizes. In seed 473's first measured holes checkpoint, both have 5,963,824 live requested bytes and 6,750,208 live allocation-aligned bytes, so alignment waste is 786,384 bytes. The pool has 26,804,224 free bytes in 13 spans, with largest span 22,675,456 bytes. Individual heaps do not have a reusable cross-heap free span; their printed zeros are not evidence of zero fragmentation.
Every cycle records full/holes/refill/empty snapshots and checks that all free spans coalesce back to one 32 MiB range. The trace demonstrates bounded recycling and quantifies logical slack/waste. It does not saturate arbitrary allocation patterns or establish a general fragmentation bound. The fixed slab is deliberately oversized for this trace; an adaptive production allocator could behave differently. Logical payload/slab/slack statistics are not physical memory measurements.
## Resource retirement and checks
Each process has 24 successful guard/interior readbacks (two phases in each of 12 cycles), plus a separate real gate-delayed copy. Before releasing the gate, the completion fence is below the retirement target and the allocation is withheld. After opening the gate and waiting with a timeout, readback matches before any release/reuse. A separate future-value policy control is also retained. This is a bounded one-queue retirement fixture, not exhaustive multi-queue lifetime certification.
The [omitted-copy negative control](../results/2026-11-26-apple-m4-arths17-a22-pool-negative/receipt.json) deliberately leaves poisoned readback in place and must exit 1 specifically for a guard/interior mismatch. It is a control success only if that exact failure is observed; it is not a passing GPU data path. Production changes and AMD allocator integration remain outside this task.
Recommendation: pooling is a plausible candidate for amortizing heap-creation overhead, with a measured cold reservation/setup cost and a required bounded slack/retirement policy. It is not yet a demonstrated overall memory/performance improvement. Prefer evaluating the [established allocator candidate](allocator-assessment.md) against the same trace before designing production machinery.
@@ -0,0 +1,57 @@
# Workstream A research report
BetterXen [#473](https://github.com/MacosPorters/betterxen/issues/473), 2026-11-26. This is local, original synthetic research on Apple M4 with 24 GiB. Independent acceptance remains pending. The objective is a defensible memory architecture, not proof of zero-copy. No production shim, ABI, main-branch file or original baseline probe was changed.
## Findings that affect the architecture
A D3D12-owned mapped buffer is a viable candidate for selected graphics allocations in the observed configuration. It is not a replacement for arbitrary xmem virtual/physical/scatter semantics. New Map-pointer receipts are not always 64 KiB aligned, even when heap placement is. Valid overlapping buffer placements exhibited the expected application-level data inheritance, but this does not identify physical pages or wrap an arbitrary existing allocation.
Process footprint depends on allocation size, prior runtime charging and retirement scope. Small allocations can use already charged regions; larger graphics allocations can remain process-accounted after resources, command objects and the device are released. RSS and footprint accounting can differ sharply under compression/swap. Neither a near-1x slope nor SM=SHM establishes unique physical backing or the absence of internal copies.
Pooling reduces the measured heap-creation component in a matched synthetic trace, but has a separately measured cold setup cost, reserved slack and noisy whole-cycle differences. It has not demonstrated a general application-level performance or memory improvement. The candidate architecture should not assume pooling is beneficial before workload-specific measurements and independent review.
Valid texture/mip/mixed-placement and RT/depth clear/alias readbacks matched in two new sessions. The overall texture matrix nevertheless failed its negative-rejection gate: the runtime accepted misaligned and out-of-bounds creation calls that were never GPU-used. Caller-side validation remains necessary. Invalid-call acceptance is not by itself proof of a runtime conformance defect because the public contract imposes preconditions without promising every rejection HRESULT.
## Deliverables and evidence
| Deliverable | Current evidence and status |
| --- | --- |
| Physical memory analysis | [Footprint findings](footprint-findings.md): historical two-repeat profile, corrected retirement checkpoints, controls, compression/pressure limits and interrupted attempt. Raw tool outputs are append-only. |
| Inverted ownership | [Requirement matrix](inverted-ownership.md): requested addresses, CPU alignment, attributes, reservation/decommit, aliases/scatter, pre-device allocations, budget and lifetime. Distinguishes in-tree implementation from unverified console semantics. |
| Allocation/pooling comparison | [Three corrected matched pairs](pooling-findings.md), raw API samples/distributions and separately timed cold heap setup. No stable production improvement claimed. |
| Fragmentation/retirement | Deterministic sizes/seeds, guard/interior GPU checks, logical free-span/waste/slack records, coalescing and a real gate-delayed retirement case. Multi-queue and arbitrary workloads remain open. |
| Texture/resource correctness | [Version-scoped matrix](../gpu-correctness/textures-and-resources/findings.md): three formats/three mips/WB/WC/DEFAULT, disjoint guards, RT/depth aliases and valid buffer inheritance. Failed negatives retained. |
| Shared versus GPU-optimized storage | Conditional guidance below; matched bandwidth and actual internal Metal storage modes remain unmeasured, requiring B's contribution. |
| Optional allocator reuse | [Exact-pin, per-file assessment](allocator-assessment.md) of AMD D3D12 Memory Allocator. No source adopted or runtime qualification claimed. |
| Independent review of B | [Pending](review-handoff.md): M5 comments reviewed as attributed reports; pinned B implementation/raw handoff and critical reproduction not yet available. |
| Recommended architecture | Candidate ownership split and explicit fallbacks below; no production adoption decision. |
| Limitations and fallbacks | [Inventory/gaps](inventory/README.md), ownership matrix, pressure interruptions, negative outcomes and unresolved mechanisms remain explicit. |
| #464 handoff | [Narrow evidence note](handoff-464.md), including current PR #486 source boundary at a pinned revision. No implementation changes or certification. |
## Candidate memory architecture
Keep a CPU-owned family for pre-device allocations, requested virtual addresses, reservations/decommit, section-backed physical tags/aliases/scatter views and unsupported attributes. Where graphics must consume those bytes, preserve an explicit, logged transfer path rather than silently relocating guest pointers or claiming unsupported wrapping.
Evaluate a D3D12-owned mapped-buffer family only for allocations whose CPU address, alignment, ownership and lifetime requirements it actually satisfies. Maintain resource ownership through every live pointer and last GPU use. Biased byte suballocation can be investigated for alignment, but does not automatically satisfy separately placed-resource offsets or CPU/GPU alias contracts. Retain explicit fallback mechanisms for incompatible rows in the matrix.
Use one logical budget with clearly separated live payload, reserved slabs, alignment waste, pending retirement and cached storage. Track host headroom/pressure and observed runtime retention separately. Logical release must not be presented as immediate physical reclamation, and a slice plus its slab must not be double charged. Bound pooling/caching rather than growing until pressure forces eviction.
Separate texture storage from raw mapped-buffer ownership. The tested CPU-subresource and DEFAULT upload/readback paths are usable candidates for their observed formats. For CPU-frequent buffers/textures, choose a valid CPU-visible path by measured access requirements; for GPU-owned resources evaluate DEFAULT with explicit transfers where needed. The A data cannot rank WB, WC and DEFAULT bandwidth or reveal D3DMetal's Metal storage mode. Combine correctness/accounting with B's measured copy/coherence/bandwidth tradeoffs before choosing by resource class.
Reuse established allocation infrastructure if it satisfies demonstrated requirements. The optional AMD allocator assessment is a starting point; production integration requires its own pinned build/runtime comparison, provenance/registry work and approval. The original trace free list is not a proposed production replacement.
## Environment and methodological limits
Recorded host: Apple M4, 25769803776 bytes unified RAM, macOS 27.0 build 26A428; CrossOver 26.3.0.39832 (cxoffice-26.3.0rc2), Wine engine wine-11.0-8726-g2e2f5fca349; loaded D3DMetal 3.0, SourceVersion 32047000000000; Rosetta receipt 1.0.0.0.1788432274. Tool receipts include native ARM64 GCC 16.2.0/MinGW-w64 14.0.0_3, Apple clang 17.0.0, SDK 26.2 and Python 3.14.3. Host page size is 16384 bytes. Own observer and CLI architecture/linkage checks are retained.
The host was not idle and had existing swap. A large sweep was interrupted when the stronger kernel pressure signal reported urgent; it remains incomplete. The bounded continuation completed six smaller/control processes and stopped automatically before proceeding with the WB 256 MiB graphics case when urgent pressure recurred. Large corrected repeats remain open. After the requester freed memory and authorized bounded continuation, runs explicitly used the warning-pressure profile, with urgent/critical stops and a conservative 23 GB host-headroom ceiling. No optional 2 GiB extension was run. The ceiling is a guard, not a target or a claim to control other applications. Three readings at one pause are correlated snapshots, not independent repetitions. Repeated runs on the same host do not establish cross-generation acceptance.
Hardware observations are local class A within their workloads; public API contracts class B; allocator project-source assessment class D; physical mechanisms, untested configurations and console compatibility class U. No Xbox hardware or commercial game execution was tested. Shared baseline sources and historical failures are preserved. No result is independently accepted merely because the author wrote both a probe and this report.
## Review and publication dependency
Exact executed sources, hashes, commands, raw data and review questions are in the append-only bundles and [handoff](review-handoff.md). B must independently review and reproduce A's critical findings; A must inspect and reproduce B's actual pinned implementation. Those steps remain open. New source publication also requires the requester's separate authorization to commit/push. No commit or push has occurred, and this report does not certify #464 or recommend adoption on the strength of synthetic success alone.
## Local validation
[Validation logs and receipts](../results/2026-11-26-apple-m4-arths17-a-verification/verification.json) record formatting, Clippy, 66 passed Rust tests with one existing ignored test, all 16 strict PE32+ shim/export checks, ARM64 CLI format/linkage and the two unchanged baseline CPU conformance programs (test_veh_clwb and test_shim_exports). Documentation hygiene passed with a temporary index containing candidate files, without changing the real index. Archive/source hash checks and Python/C++ formatting/compilation checks are retained. These engineering checks do not independently accept the new research or turn the texture negative failures into passes.
@@ -0,0 +1,32 @@
# Reciprocal review status and reproduction handoff
Workstream A owns allocation/footprint and resource/lifetime fixtures. Workstream B owns copy/bandwidth, compute/coherence, synchronization and tracking implementation. B's implementation has not been re-created by A. A's footprint shader/queue support reuses the frozen historical implementation; it is not a newly commissioned B workstream.
## What has been reviewed
A read all five #473 comments present at start, including the complete revised plan, the six-check pinned baseline, the actual retained M4 supplemental sources/raw receipts, M5 report/review notes and the architectural discussion. M5 claim analysis distinguishes public contracts from attributed observations. The common baseline timings copy only endpoints, and different CUSTOM/UPLOAD barriers prevent ranking heap types. Process accounting, region labels and flat timings do not prove page identity. UMA=0 does not invalidate CPU-visible L0 heaps. The historical UNKNOWN texture Map requested no pointer, so it did not test a pointer-return failure.
These are A's source/documentation assessments, not independent certification of A's own baseline or supplemental implementation. See the [inventory](inventory/README.md) for the missing earlier source bytes, compiled historical shader identities, partial M5 backend receipt and unavailable private probe.
## B review is pending
As of the last #473 poll, no accessible pinned CarReal8917 B source/raw handoff or contributor confirmation was available. A requested pinned source, raw logs/distributions, active-backend receipts and review notes through #473. Other contributors' M5 comments are not assumed to belong to CarReal. Therefore A has not completed independent implementation review or critical M4 reproduction of B. No agreement or independent acceptance is inferred from matching prose or reported numbers.
After a B handoff arrives: inspect the pinned actual source, independently derive API/data expectations, inspect individual samples/failures and backend evidence, identify confounds, reproduce only critical cases that resolve a specific uncertainty, and record disagreements and unknowns separately. Do not silently modify B's fixtures or overlap B-owned paths.
## Review A independently
The exact executed sources, commands, source/PE/shader hashes and raw stdout/stderr are in append-only `../results/2026-11-26-apple-m4-arths17-*` bundles. Each source snapshot/receipt pins bytes independently of the mutable working tree. Archives preserve raw stdout/stderr; JSON diagnostic copies explicitly redact the local home prefix, retaining original and archived hashes. Build/runtime binaries and bottle copies are not published. No commit/push has yet been authorized, so new sources are currently local; a remote fetchable revision is pending separate requester authorization.
One-command harness reproduction is in [README.md](README.md); choose the default normal-pressure profile or explicitly record an authorized warning-pressure profile. Respect the 23 GB conservative host-headroom guard and the single-GPU-workload rule. Do not turn the texture matrix's observed nonzero exits into passing status. The omitted-copy pool control must fail specifically for the expected mismatch.
Independent B review requests:
- Re-derive placed-resource allocation alignment/bounds, texture transfer layouts/mip extents and per-subresource CPU access from Microsoft documentation.
- Inspect resource states, alias activation/post-activation RT/depth initialization, full-buffer inheritance under the advanced model, CPU store completion, queue-gate cleanup and fence/command retirement.
- Reproduce critical pointer-alignment, buffer-inheritance, invalid-creation observations and representative mip/RT/depth cases on M5; retain unsupported/failure outcomes.
- Audit footprint baseline/retirement definitions, correlated snapshots versus fresh sessions, compression/RSS/process-ledger distinctions, pool setup/reservation/slack and cold/warm timing boundaries.
- Check raw per-allocation/per-free samples and per-session distributions; do not treat aggregate sample counts as independent machines or rank heaps from unmatched barriers.
- Independently evaluate whether the requirement matrix justifies any proposed architecture, with all required fallbacks and unresolved console semantics explicit.
Author-run, reported, reproduced and independently accepted are distinct statuses. Every new A result remains author-run/unaccepted. Peer review and source publication are outstanding dependencies, not completed deliverables.
@@ -0,0 +1,238 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Workstream A local harness, version 2. Does not change shared protocols."""
import argparse
import fcntl
import hashlib
import json
import os
from pathlib import Path
import plistlib
import re
import shutil
import signal
import subprocess
import threading
import time
from datetime import datetime, timezone
def sha(p):
return hashlib.sha256(p.read_bytes()).hexdigest()
def capture(cmd, env, cwd, timeout=20):
start = time.monotonic()
try:
p = subprocess.run([str(v) for v in cmd], env=env, cwd=cwd,
capture_output=True, timeout=timeout)
return dict(command=[str(v) for v in cmd], exit=p.returncode,
stdout=p.stdout.decode(errors='replace'),
stderr=p.stderr.decode(errors='replace'), seconds=time.monotonic()-start)
except OSError as e:
return dict(command=[str(v) for v in cmd], exit=127, stdout='', stderr=str(e))
except subprocess.TimeoutExpired as e:
return dict(command=[str(v) for v in cmd], exit=124, timeout=True,
stdout=(e.stdout or b'').decode(errors='replace'),
stderr=(e.stderr or b'').decode(errors='replace'))
def main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('--bottle', required=True, type=Path)
ap.add_argument('--scratch', required=True, type=Path)
ap.add_argument('--suite', choices=['memory', 'pool', 'texture', 'alias'], required=True)
ap.add_argument('--smoke', action='store_true')
ap.add_argument('--sessions',type=int,choices=[1,2,3],default=3,help='pool sessions')
ap.add_argument('--session-start',type=int,choices=[0,1,2],default=0,help='pool trace session offset for nonduplicating continuation')
ap.add_argument('--allow-warning', action='store_true', help='explicitly permit kernel warning level 1; urgent/critical still stop')
ap.add_argument('--negative-control', action='store_true', help='pool omitted-copy control only; expected exit 1')
args = ap.parse_args()
if args.negative_control and args.suite != 'pool':
ap.error('--negative-control only applies to pool')
src = Path(__file__).resolve().parent
repo = src.parents[3]
base = args.scratch.expanduser().resolve()
if base.exists() or base == repo or repo in base.parents:
ap.error('scratch must be new and outside checkout')
bottle = args.bottle.expanduser().resolve()
original = (bottle/'cxbottle.conf').read_bytes()
if b'"WineArch" = "win64"' not in original:
ap.error('requires win64 bottle')
lock = open('/tmp/betterxen-473-gpu.lock', 'a')
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
ap.error('another Workstream A GPU batch owns the lock')
base.mkdir(mode=0o700)
env = {k: os.environ[k] for k in ['HOME', 'USER', 'LOGNAME', 'PATH', 'LANG', 'LC_ALL'] if k in os.environ}
env.update(TMPDIR=str(base)+'/', ROSETTA_ADVERTISE_AVX='1', CX_GRAPHICS_BACKEND='d3dmetal', WINEDEBUG='-all')
cx = Path('/Applications/CrossOver.app/Contents/SharedSupport/CrossOver')
wine = cx/'bin/wine'
source = src/(args.suite+'.cpp') if args.suite in ['memory','pool'] else src.parent/'gpu-correctness/textures-and-resources'/('probe.cpp' if args.suite=='texture' else 'alias.cpp')
exe, observer = base/'a-probe.exe', base/'observe'
receipt = dict(protocol='A-local-2.2', suite=args.suite, allow_warning=args.allow_warning, utc=datetime.now(timezone.utc).isoformat(),
ram_ceiling_bytes=23000000000, independent_review='pending', environment={k: env[k] for k in ['ROSETTA_ADVERTISE_AVX', 'CX_GRAPHICS_BACKEND', 'WINEDEBUG']},
sources={str(p.relative_to(repo)): sha(p) for p in [source, src/'support.h', src/'observe.cpp', Path(__file__)]},
baseline_sha256=sha(src.parent/'probe.cpp'), tools={}, cases=[])
snapshot=base/'source';snapshot.mkdir()
for source_path in [source, src/'support.h', src/'observe.cpp', Path(__file__)]:
destination = snapshot/source_path.relative_to(repo)
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source_path, destination)
def save():
(base/'receipt.json').write_text(json.dumps(receipt, indent=2)+'\n')
cmds = {
'chip': ['sysctl','-n','machdep.cpu.brand_string'], 'ram':['sysctl','-n','hw.memsize'],
'host':['uname','-m'], 'macos':['sw_vers'], 'page':['sysctl','-n','hw.pagesize'],
'swap_before':['sysctl','vm.swapusage'], 'pressure_before':['memory_pressure','-Q'], 'vm_before':['vm_stat'],
'load_before':['ps','-axo','pid,pcpu,comm'], 'wine_version':[wine,'--version'],
'wine_build':[cx/'bin/wineloader','--version'],
'kernel_pressure_before':['sysctl','-n','kern.memorystatus_vm_pressure_level'],
'rosetta':['pkgutil','--pkg-info','com.apple.pkg.RosettaUpdateAuto'],
'gcc':['x86_64-w64-mingw32-g++','--version'], 'clang':['xcrun','clang++','--version'],
'sdk':['xcrun','--show-sdk-version'], 'python':['python3','--version'],
'compiler_arch':['file',str(Path(shutil.which('x86_64-w64-mingw32-g++')).resolve())],
'compiler_lipo':['lipo','-archs',str(Path(shutil.which('x86_64-w64-mingw32-g++')).resolve())],
'compiler_links':['otool','-L',str(Path(shutil.which('x86_64-w64-mingw32-g++')).resolve())],
'build_pe':['x86_64-w64-mingw32-g++','-std=c++20','-O2','-static','-static-libgcc','-static-libstdc++','-Wall','-Wextra','-Werror',source,'-o',exe,'-lkernel32'],
'build_observer':['xcrun','clang++','-std=c++20','-O2','-arch','arm64','-Wall','-Wextra','-Werror',src/'observe.cpp','-o',observer],
'formats':['file',exe,observer], 'observer_arch':['lipo','-archs',observer], 'observer_links':['otool','-L',observer],
}
for name, cmd in cmds.items():
receipt['tools'][name]=capture(cmd,env,base,60)
save()
if name.startswith('build_') and receipt['tools'][name]['exit']:
raise RuntimeError(receipt['tools'][name])
receipt['binaries']={p.name:sha(p) for p in [exe,observer]}
resources=cx/'lib64/apple_gptk/external/D3DMetal.framework/Versions/A/Resources'
receipt['framework']={p.name:plistlib.loads(p.read_bytes()) for p in resources.glob('*.plist')}
receipt['runtime_hashes']={str(p):sha(p) for p in [cx/'lib64/apple_gptk/wine/x86_64-windows/d3d12.dll', cx/'lib/wine/x86_64-windows/d3dcompiler_47.dll']}
temp=base/'bottle'
shutil.copytree(bottle,temp,symlinks=True)
conf=re.sub(r'(?m)^\[Bottle\]\s*$', '[Bottle]\n"AllowUntrusted" = "1"', original.decode(), count=1)
conf+='\n[EnvironmentVariables]\n"CX_GRAPHICS_BACKEND" = "d3dmetal"\n[CrossOver]\n"AntiVirusScan" = "untrusted"\n'
(temp/'cxbottle.conf').write_text(conf)
receipt['bottle_original_sha256']=hashlib.sha256(original).hexdigest()
receipt['bottle_settings']=[line.strip() for line in conf.splitlines() if re.match(r'"(WineArch|Template|WindowsVersion|Version|CX_GRAPHICS_BACKEND|AllowUntrusted|AntiVirusScan)"',line)]
common=[str(wine),'--bottle',str(temp),'--no-update','--no-gui',str(exe)]
def headroom():
vm=capture(['vm_stat'],env,base)
ram=capture(['sysctl','-n','hw.memsize'],env,base)
page=re.search(r'page size of (\d+) bytes',vm['stdout'])
free=re.search(r'Pages free:\s+(\d+)',vm['stdout'])
filebacked=re.search(r'File-backed pages:\s+(\d+)',vm['stdout'])
if vm['exit'] or ram['exit'] or not all([page,free,filebacked]):
raise RuntimeError('cannot measure host RAM headroom')
# Report the metric precisely; this is not a claim to match Activity Monitor.
used=max(0,int(ram['stdout'])-(int(free[1])+int(filebacked[1]))*int(page[1]))
return dict(metric='physical RAM minus free and file-backed pages; conservative non-file-cache occupied estimate',
occupied_bytes=used,ceiling_bytes=23000000000,available_below_ceiling_bytes=23000000000-used,vm_stat=vm,ram=ram)
def run(name, argv, expected_exit=0):
memory=headroom()
reserve=512*1024**2+(2*int(argv[1]) if args.suite=='memory' else 0)
if memory['available_below_ceiling_bytes']<reserve:
receipt.setdefault('not_run',[]).append(dict(name=name,reason='23 GB headroom guard; no guest started',headroom=memory,required_reserve_bytes=reserve));save();return
kernel_pressure=capture(['sysctl','-n','kern.memorystatus_vm_pressure_level'],env,base)
if kernel_pressure['exit'] or not kernel_pressure['stdout'].strip().isdigit() or int(kernel_pressure['stdout'].strip())>(1 if args.allow_warning else 0):
receipt['stop_reason']={'kernel_pressure_gate_before':name,'reading':kernel_pressure};save()
raise RuntimeError('kernel memory pressure exceeds explicitly selected profile; no case started')
pressure=capture(['memory_pressure','-Q'],env,base)
match=re.search(r'free percentage: (\d+)%',pressure['stdout'])
if pressure['exit'] or not match or int(match[1])<30:
receipt['stop_reason']={'pressure_gate_before':name,'reading':pressure};save()
raise RuntimeError('memory pressure headroom below 30% or unreadable')
case=base/name;case.mkdir()
metadata=dict(name=name,args=argv,expected_exit=expected_exit,command=common+argv,timeout_seconds=240,pressure_before=pressure,kernel_pressure_before=kernel_pressure,ram_before=memory,snapshots=[])
receipt['cases'].append(metadata);save()
expired=threading.Event()
start=time.monotonic()
with (case/'stdout.txt').open('wb') as out,(case/'stderr.txt').open('wb') as err:
p=subprocess.Popen(common+argv,env=env,cwd=case,stdout=subprocess.PIPE,stderr=err,stdin=subprocess.PIPE,start_new_session=True)
def kill():
try: os.killpg(p.pid,signal.SIGKILL)
except ProcessLookupError: pass
def expire():
expired.set();kill()
timer=threading.Timer(240,expire);timer.start()
pid=None
try:
for line in p.stdout:
out.write(line);out.flush()
if not line.startswith(b'STAGE '):continue
if pid is None:
found=capture(['lsof','-t','-a','-c','a-probe.exe',str(exe)],env,base)
candidates=sorted({int(x) for x in found['stdout'].split() if x.isdigit()})
if len(candidates)!=1:raise RuntimeError('ambiguous PE PID: '+repr(found))
pid=candidates[0];metadata['host_pid']=pid
libs=capture(['lsof','-n','-p',str(pid)],env,base)
metadata['backend_paths_excerpt']=['/'+line.split('/',1)[-1] for line in libs['stdout'].splitlines() if any(x in line for x in ['apple_gptk/wine/x86_64-windows/d3d12.dll','D3DMetal.framework/Versions/A/D3DMetal','/rosetta/runtime'])]
metadata['backend_lsof_exit']=libs['exit']
phase=line.decode().split()[1]
snap=dict(phase=phase,marker=line.decode().strip(),samples=[],ram=headroom())
if snap['ram']['available_below_ceiling_bytes']<256*1024**2:
raise RuntimeError('stop before 23 GB host occupied-memory ceiling')
for _ in range(3):
result=capture([observer,str(pid)],env,base)
if not result['exit']:result['data']=json.loads(result['stdout'])
snap['samples'].append(result)
commands={'footprint':['footprint','-p',str(pid),'-f','bytes','--swapped'],
'vmmap':['vmmap','-summary',str(pid)], 'vmstat':['vm_stat'],
'pressure':['memory_pressure','-Q'],'swap':['sysctl','vm.swapusage'],
'kernel_pressure':['sysctl','-n','kern.memorystatus_vm_pressure_level']}
ptr=re.search(rb'cpu_ptr=([0-9A-Fa-f]+)',line)
if ptr and int(ptr[1],16):commands['pointer_vmmap']=['vmmap','-w',str(pid),'0x'+ptr[1].decode()]
for tool,cmd in commands.items():
result=capture(cmd,env,base,15)
filename=f'{phase}-{tool}.json';(case/filename).write_text(json.dumps(result,indent=2)+'\n')
snap[tool]=dict(exit=result['exit'],file=filename)
if tool=='kernel_pressure' and (result['exit'] or not result['stdout'].strip().isdigit() or int(result['stdout'].strip())>(1 if args.allow_warning else 0)):
raise RuntimeError('kernel pressure changed; stop this case without resuming guest')
if tool=='pressure':
m=re.search(r'free percentage: (\d+)%',result['stdout'])
if result['exit'] or not m or int(m[1])<25:raise RuntimeError('stage pressure safety stop')
metadata['snapshots'].append(snap);save()
p.stdin.write(b'\n');p.stdin.flush()
p.wait()
except BaseException as e:
metadata['harness_error']=repr(e);kill();p.wait();raise
finally:
timer.cancel();metadata.update(exit=p.returncode,timed_out=expired.is_set(),seconds=time.monotonic()-start)
metadata['outputs']={f.name:sha(f) for f in case.iterdir() if f.is_file()}
(case/'case.json').write_text(json.dumps(metadata,indent=2)+'\n');save()
print(name,'exit',metadata['exit'],'timeout',metadata['timed_out'],flush=True)
if metadata['timed_out']:raise RuntimeError('case timed out: '+name)
if metadata['exit']!=expected_exit:
receipt.setdefault('failed_cases',[]).append(name);save()
if args.suite not in ['texture','alias']:raise RuntimeError('case failed: '+name)
if expected_exit and b'END failure reason=trace guard/interior mismatch' not in (case/'stdout.txt').read_bytes():
raise RuntimeError('negative control failed for an unexpected reason')
try:
if args.suite=='memory':
for repeat in range(1 if args.smoke else 2):
sizes=[64] if args.smoke else [64,256,1024]
types=['wb'] if args.smoke else ['cpu-plain','cpu','wb','upload']
if repeat%2:types.reverse();sizes.reverse()
for size in sizes:
for typ in types:run(f'memory-{typ}-{size}MiB-r{repeat}',[typ,str(size*1024**2)])
elif args.suite=='pool' and args.negative_control:
run('pool-omitted-copy-control',['omit','473'],1)
elif args.suite=='pool':
for session in range(args.session_start,args.session_start+(1 if args.smoke else args.sessions)):
modes=['individual','pooled'] if session%2==0 else ['pooled','individual']
for mode in modes:run(f'pool-{mode}-s{session}',[mode,str(473+session)])
else:
for session in range(1 if args.smoke else 2):run(f'{args.suite}-s{session}',[str(session)])
finally:
for name,cmd in {'pressure_after':['memory_pressure','-Q'],'vm_after':['vm_stat'],'swap_after':['sysctl','vm.swapusage'],'kernel_pressure_after':['sysctl','-n','kern.memorystatus_vm_pressure_level']}.items():receipt['tools'][name]=capture(cmd,env,base)
stop=dict(env,WINEPREFIX=str(temp))
receipt['server_stop']=capture([cx/'bin/wineserver','-k'],stop,base)
receipt['server_wait']=capture([cx/'bin/wineserver','-w'],stop,base)
receipt['source_bottle_unchanged']=(bottle/'cxbottle.conf').read_bytes()==original
shutil.rmtree(temp);save()
return int(bool(receipt.get('failed_cases') or receipt.get('not_run')))
if __name__=='__main__':
raise SystemExit(main())
@@ -0,0 +1,390 @@
#pragma once
// SPDX-License-Identifier: GPL-3.0-or-later
// Supplemental original synthetic tests; baseline ../probe.cpp is unchanged.
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <d3d12.h>
#include <d3dcompiler.h>
#include <dxgi1_4.h>
#include <emmintrin.h>
#include <stdexcept>
#include <string>
#include <vector>
#include <windows.h>
template <class T> struct Ref {
T *p = nullptr;
Ref() = default;
Ref(const Ref &) = delete;
Ref &operator=(const Ref &) = delete;
~Ref() { clear(); }
void clear() {
if (p) {
p->Release();
p = nullptr;
}
}
T *operator->() const { return p; }
void **out() { return reinterpret_cast<void **>(&p); }
};
inline void require(HRESULT h, const char *name) {
if (FAILED(h)) {
std::printf("FAIL %s HRESULT=0x%08lX\n", name, (unsigned long)h);
throw std::runtime_error(name);
}
}
inline void report(HRESULT h, const char *name) {
std::printf("API %s HRESULT=0x%08lX\n", name, (unsigned long)h);
}
template <class T> static T symbol(HMODULE m, const char *name) {
FARPROC p = GetProcAddress(m, name);
if (!p)
throw std::runtime_error(name);
T result;
static_assert(sizeof(result) == sizeof(p));
std::memcpy(&result, &p, sizeof(p));
return result;
}
inline double ticks() {
LARGE_INTEGER t;
QueryPerformanceCounter(&t);
return double(t.QuadPart);
}
inline double frequency() {
LARGE_INTEGER t;
QueryPerformanceFrequency(&t);
return double(t.QuadPart);
}
inline D3D12_HEAP_PROPERTIES properties(D3D12_HEAP_TYPE type) {
D3D12_HEAP_PROPERTIES p{};
p.Type = type;
p.CreationNodeMask = 1;
p.VisibleNodeMask = 1;
return p;
}
static D3D12_RESOURCE_DESC
bufferDesc(UINT64 bytes,
D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) {
D3D12_RESOURCE_DESC r{};
r.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
r.Width = bytes;
r.Height = 1;
r.DepthOrArraySize = 1;
r.MipLevels = 1;
r.SampleDesc.Count = 1;
r.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
r.Flags = flags;
return r;
}
struct Context {
HMODULE dll = nullptr;
Ref<ID3D12Device3> device;
Context() {
dll = LoadLibraryA("d3d12.dll");
if (!dll)
throw std::runtime_error("LoadLibrary d3d12");
char path[2048]{};
GetModuleFileNameA(dll, path, sizeof(path));
std::printf("D3D12_DLL %s\n", path);
using Create =
HRESULT(WINAPI *)(IUnknown *, D3D_FEATURE_LEVEL, REFIID, void **);
require(symbol<Create>(dll, "D3D12CreateDevice")(
nullptr, D3D_FEATURE_LEVEL_11_0, __uuidof(ID3D12Device3),
device.out()),
"CreateDevice3");
bool shim = GetModuleHandleA("d3d12_xs.dll") != nullptr;
std::printf("SHIM_LOADED %d\n", shim);
if (shim)
throw std::runtime_error("shim contamination");
}
};
struct Queue {
ID3D12Device3 *d;
Ref<ID3D12CommandQueue> q;
Ref<ID3D12CommandAllocator> allocator;
Ref<ID3D12GraphicsCommandList> list;
Ref<ID3D12Fence> fence;
HANDLE event = nullptr;
UINT64 value = 0;
explicit Queue(ID3D12Device3 *device) : d(device) {
D3D12_COMMAND_QUEUE_DESC desc{};
desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
require(d->CreateCommandQueue(&desc, __uuidof(ID3D12CommandQueue), q.out()),
"CreateCommandQueue");
require(d->CreateCommandAllocator(
desc.Type, __uuidof(ID3D12CommandAllocator), allocator.out()),
"CreateCommandAllocator");
require(d->CreateCommandList(0, desc.Type, allocator.p, nullptr,
__uuidof(ID3D12GraphicsCommandList),
list.out()),
"CreateCommandList");
require(list->Close(), "initial Close");
require(d->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence),
fence.out()),
"CreateFence");
event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
if (!event)
throw std::runtime_error("CreateEvent");
}
~Queue() {
if (event)
CloseHandle(event);
}
void begin() {
require(allocator->Reset(), "allocator Reset");
require(list->Reset(allocator.p, nullptr), "list Reset");
}
void transition(ID3D12Resource *r, D3D12_RESOURCE_STATES a,
D3D12_RESOURCE_STATES b) {
if (a == b)
return;
D3D12_RESOURCE_BARRIER x{};
x.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
x.Transition.pResource = r;
x.Transition.StateBefore = a;
x.Transition.StateAfter = b;
x.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
list->ResourceBarrier(1, &x);
}
void close() { require(list->Close(), "Close"); }
void executeClosed() {
ID3D12CommandList *lists[] = {list.p};
q->ExecuteCommandLists(1, lists);
require(q->Signal(fence.p, ++value), "Signal");
UINT64 completed = fence->GetCompletedValue();
if (completed == ~UINT64(0))
throw std::runtime_error("device removed fence");
if (completed < value) {
require(fence->SetEventOnCompletion(value, event),
"SetEventOnCompletion");
DWORD w = WaitForSingleObject(event, 10000);
if (w != WAIT_OBJECT_0)
throw std::runtime_error("fence timeout");
}
}
void finish() {
close();
_mm_sfence();
executeClosed();
require(d->GetDeviceRemovedReason(), "GetDeviceRemovedReason");
}
};
struct Buffer {
Ref<ID3D12Heap> heap;
Ref<ID3D12Resource> resource;
void *cpu = nullptr;
UINT64 size = 0;
void allocate(ID3D12Device3 *d, UINT64 bytes, const std::string &type,
bool uav = false) {
size = bytes;
auto desc =
bufferDesc(bytes, uav ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS
: D3D12_RESOURCE_FLAG_NONE);
auto state =
uav ? D3D12_RESOURCE_STATE_COMMON : D3D12_RESOURCE_STATE_GENERIC_READ;
if (type == "upload" || type == "readback") {
if (uav)
throw std::runtime_error(
"UAV on upload/readback forbidden in this probe");
auto p = properties(type == "upload" ? D3D12_HEAP_TYPE_UPLOAD
: D3D12_HEAP_TYPE_READBACK);
if (type == "readback")
state = D3D12_RESOURCE_STATE_COPY_DEST;
require(d->CreateCommittedResource(&p, D3D12_HEAP_FLAG_NONE, &desc, state,
nullptr, __uuidof(ID3D12Resource),
resource.out()),
"committed buffer");
} else {
D3D12_HEAP_DESC hd{};
hd.SizeInBytes = (bytes + 65535) & ~UINT64(65535);
hd.Alignment = 65536;
hd.Properties = properties(D3D12_HEAP_TYPE_CUSTOM);
hd.Properties.CPUPageProperty =
type == "wc" ? D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE
: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
hd.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
require(d->CreateHeap(&hd, __uuidof(ID3D12Heap), heap.out()),
"custom heap");
require(d->CreatePlacedResource(heap.p, 0, &desc, state, nullptr,
__uuidof(ID3D12Resource), resource.out()),
"placed buffer");
}
}
void map() {
require(resource->Map(0, nullptr, &cpu), "Map buffer");
if (!cpu)
throw std::runtime_error("null buffer pointer");
}
void release() {
cpu = nullptr;
resource.clear();
heap.clear();
}
};
[[maybe_unused]] inline void identity(Context &c) {
using Factory = HRESULT(WINAPI *)(UINT, REFIID, void **);
HMODULE dxgi = LoadLibraryA("dxgi.dll");
if (!dxgi)
throw std::runtime_error("dxgi load");
Ref<IDXGIFactory4> f;
require(symbol<Factory>(dxgi, "CreateDXGIFactory2")(
0, __uuidof(IDXGIFactory4), f.out()),
"factory4");
LUID luid = c.device->GetAdapterLuid();
Ref<IDXGIAdapter2> a;
require(f->EnumAdapterByLuid(luid, __uuidof(IDXGIAdapter2), a.out()),
"adapter by device LUID");
DXGI_ADAPTER_DESC2 ad{};
require(a->GetDesc2(&ad), "GetDesc2");
char name[512]{};
WideCharToMultiByte(CP_UTF8, 0, ad.Description, -1, name, sizeof(name),
nullptr, nullptr);
std::printf(
"ADAPTER description=%s vendor=0x%04X device=0x%04X subsystem=0x%08X "
"revision=%u flags=%u dedicated_video_bytes=%llu "
"dedicated_system_bytes=%llu shared_system_bytes=%llu luid=%08lX:%08lX\n",
name, ad.VendorId, ad.DeviceId, ad.SubSysId, ad.Revision, ad.Flags,
(unsigned long long)ad.DedicatedVideoMemory,
(unsigned long long)ad.DedicatedSystemMemory,
(unsigned long long)ad.SharedSystemMemory, (unsigned long)luid.HighPart,
(unsigned long)luid.LowPart);
D3D12_FEATURE_DATA_D3D12_OPTIONS opts{};
require(c.device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &opts,
sizeof(opts)),
"options");
std::printf(
"OPTIONS ResourceHeapTier=%d CrossAdapterRowMajorTextureSupported=%d "
"StandardSwizzle64KBSupported=%d\n",
opts.ResourceHeapTier, opts.CrossAdapterRowMajorTextureSupported,
opts.StandardSwizzle64KBSupported);
D3D12_FEATURE_DATA_ARCHITECTURE1 arch{};
require(c.device->CheckFeatureSupport(D3D12_FEATURE_ARCHITECTURE1, &arch,
sizeof(arch)),
"architecture1");
std::printf(
"ARCH UMA=%d CacheCoherentUMA=%d TileBasedRenderer=%d IsolatedMMU=%d\n",
arch.UMA, arch.CacheCoherentUMA, arch.TileBasedRenderer,
arch.IsolatedMMU);
for (auto type : {D3D12_HEAP_TYPE_DEFAULT, D3D12_HEAP_TYPE_UPLOAD,
D3D12_HEAP_TYPE_READBACK}) {
auto p = c.device->GetCustomHeapProperties(0, type);
std::printf(
"CUSTOM_PROPERTIES input_type=%d Type=%d CPUPageProperty=%d "
"MemoryPoolPreference=%d CreationNodeMask=%u VisibleNodeMask=%u\n",
type, p.Type, p.CPUPageProperty, p.MemoryPoolPreference,
p.CreationNodeMask, p.VisibleNodeMask);
}
SYSTEM_INFO si{};
GetSystemInfo(&si);
std::printf("GUEST_PAGE_SIZE %lu ALLOCATION_GRANULARITY %lu\n", si.dwPageSize,
si.dwAllocationGranularity);
}
struct Shader {
Ref<ID3D12RootSignature> root;
Ref<ID3D12PipelineState> pipeline;
static constexpr const char *code = R"HLSL(
ByteAddressBuffer source : register(t0);
RWByteAddressBuffer result : register(u0);
cbuffer Parameters : register(b0) { uint count; uint salt; uint wordStride; };
[numthreads(64,1,1)]
void main(uint3 tid : SV_DispatchThreadID) {
uint accum=0;
for(uint i=tid.x; i<count; i+=256) accum ^= source.Load(i*wordStride*4)+salt;
result.Store(tid.x*4,accum);
}
)HLSL";
explicit Shader(Context &c) {
HMODULE compiler = LoadLibraryA("d3dcompiler_47.dll");
if (!compiler)
throw std::runtime_error("d3dcompiler47 unavailable");
char path[2048]{};
GetModuleFileNameA(compiler, path, sizeof(path));
std::printf("SHADER_COMPILER %s\n", path);
using Compile = HRESULT(WINAPI *)(
LPCVOID, SIZE_T, LPCSTR, const D3D_SHADER_MACRO *, ID3DInclude *,
LPCSTR, LPCSTR, UINT, UINT, ID3DBlob **, ID3DBlob **);
Ref<ID3DBlob> binary, error;
HRESULT h = symbol<Compile>(compiler, "D3DCompile")(
code, std::strlen(code), "original-phase2.hlsl", nullptr, nullptr,
"main", "cs_5_0", D3DCOMPILE_OPTIMIZATION_LEVEL3, 0, &binary.p,
&error.p);
if (error.p)
std::printf("COMPILER_LOG %.*s\n", (int)error->GetBufferSize(),
(const char *)error->GetBufferPointer());
require(h, "D3DCompile cs5_0");
std::printf("SHADER_BYTECODE bytes=%zu magic=%.4s\n",
binary->GetBufferSize(), (char *)binary->GetBufferPointer());
FILE *bytecode = std::fopen("consumption.dxbc", "wb");
if (!bytecode ||
std::fwrite(binary->GetBufferPointer(), 1, binary->GetBufferSize(),
bytecode) != binary->GetBufferSize())
throw std::runtime_error("archive shader");
std::fclose(bytecode);
FILE *hlsl = std::fopen("consumption.hlsl", "wb");
if (!hlsl)
throw std::runtime_error("archive HLSL");
std::fwrite(code, 1, std::strlen(code), hlsl);
std::fclose(hlsl);
D3D12_ROOT_PARAMETER params[3]{};
params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV;
params[0].Descriptor.ShaderRegister = 0;
params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
params[1].Descriptor.ShaderRegister = 0;
params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
params[2].Constants.ShaderRegister = 0;
params[2].Constants.Num32BitValues = 3;
D3D12_ROOT_SIGNATURE_DESC desc{};
desc.NumParameters = 3;
desc.pParameters = params;
using Serialize =
HRESULT(WINAPI *)(const D3D12_ROOT_SIGNATURE_DESC *,
D3D_ROOT_SIGNATURE_VERSION, ID3DBlob **, ID3DBlob **);
Ref<ID3DBlob> serialized, serializeError;
require(symbol<Serialize>(c.dll, "D3D12SerializeRootSignature")(
&desc, D3D_ROOT_SIGNATURE_VERSION_1, &serialized.p,
&serializeError.p),
"serialize root");
require(c.device->CreateRootSignature(
0, serialized->GetBufferPointer(), serialized->GetBufferSize(),
__uuidof(ID3D12RootSignature), root.out()),
"CreateRootSignature");
D3D12_COMPUTE_PIPELINE_STATE_DESC pd{};
pd.pRootSignature = root.p;
pd.CS = {binary->GetBufferPointer(), binary->GetBufferSize()};
require(c.device->CreateComputePipelineState(
&pd, __uuidof(ID3D12PipelineState), pipeline.out()),
"CreateComputePipelineState");
}
void dispatch(Queue &q, Buffer &src, Buffer &dst, UINT count, UINT salt,
UINT stride) {
q.begin();
q.transition(dst.resource.p, D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
q.list->SetPipelineState(pipeline.p);
q.list->SetComputeRootSignature(root.p);
q.list->SetComputeRootShaderResourceView(
0, src.resource->GetGPUVirtualAddress());
q.list->SetComputeRootUnorderedAccessView(
1, dst.resource->GetGPUVirtualAddress());
UINT values[] = {count, salt, stride};
q.list->SetComputeRoot32BitConstants(2, 3, values, 0);
q.list->Dispatch(4, 1, 1);
q.transition(dst.resource.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
D3D12_RESOURCE_STATE_COMMON);
q.finish();
}
};
inline uint32_t pattern(UINT64 i, UINT seed) {
uint32_t x = uint32_t(i) ^ seed;
x ^= x >> 16;
x *= 0x7FEB352Du;
x ^= x >> 15;
x *= 0x846CA68Bu;
return x ^ (x >> 16);
}
@@ -0,0 +1,48 @@
# Workstream B copy, memory and synchronization research
This supplement to [#473](https://github.com/MacosPorters/betterxen/issues/473) uses only synthetic buffers and the installed public D3D12 interfaces. The six baseline cases are frozen. See the [baseline](../README.md) and [measured findings](findings.md). [Contracts](../gpu-correctness/contracts/synchronization-mapping-tracking.md) and the [independent A review](review-a.md) accompany these experiments. No production shim or ABI participates.
## Reproduce
Use a licensed CrossOver installation on Apple Silicon, Rosetta and a local win64 CrossOver bottle. The runner clones the bottle, records settings and source bottle configuration hash, and stops the private server on return. Each graphics case checks loaded D3DMetal DLL/framework paths before running the workload. Each case has a 45-second timeout and individual fence waits have a 5-second timeout. The host lock serializes runs from both workstreams when they use the common local lock path. Launch filters environment variables and copies only the external HLSL source into the compute guest's working directory.
```sh
probe_dir=docs/research/d3dmetal-zero-copy/copy-detection
python3 "$probe_dir/run.py" --group small --bottle "/path/to/win64/bottle" --scratch /tmp/b473-small
python3 "$probe_dir/run.py" --group compute --seed 473 --bottle "/path/to/win64/bottle" --scratch /tmp/b473-compute
python3 "$probe_dir/run.py" --group sweep --seed 473 --bottle "/path/to/win64/bottle" --scratch /tmp/b473-sweep
python3 "$probe_dir/summarize.py" /tmp/b473-compute /tmp/b473-sweep
```
Each scratch path must be new. A build-only invocation omits the bottle and uses `--group build`. Repeat with a new seed and fresh scratch directory. The default profile requires normal kernel pressure. A separately labeled `--allow-warning` case can run at Warning while still stopping at Urgent. Pressure and compression are recorded outside benchmark windows. Treat stopped and partial runs as incomplete. [XNU pressure levels](https://github.com/apple-oss-distributions/xnu/blob/main/doc/vm/memorystatus_notify.md).
## Measurements
- The copy sweep uses 1, 16 and 64 MiB with WB, WC and standard UPLOAD sources, a matching READBACK output, and 4 KiB or 16 KiB write strides. CUSTOM buffers begin in COMMON and use legal promotion/decay. UPLOAD remains GENERIC_READ. The workload uses the same READBACK destinations, command lists and fence path for each source heap.
- Each case has three warmups and twelve timed iterations. Case and page order use the receipt seed. The first three pages in the seeded order cover the first word, an interior word and the last stride's first word. Cases range from zero modified pages to one word per page in the measured allocation. Genuine whole-buffer rewrites are separate cases. Allocation, initialization and output poisoning are outside the write, encoding and submission intervals.
- Constant-size GPU work copies three words. Full GPU work copies the allocation and validates every word, including unchanged words inside modified pages. The full workload brackets the copy with D3D12 timestamp queries. GPU rates use useful copy payload bytes divided by query elapsed time. Empty command lists and signal-only waits provide host controls. Omitted copies keep poisoned output, including in the timestamped no-copy case.
- Record CPU write (including store fence), reset and encoding, Execute call, queue Signal call, fence arm/wait, end-to-end submission/completion, and validation separately. The CPU bandwidth loop measures whole-allocation memset and a one-stream checksum scan after that write. Report these as effective workload rates with cache and prior-write effects.
- The separate [compute and tracking fixture](../gpu-correctness/coherence-and-tracking/README.md) measures direct shader access, wide reads with compact output, sparse reads and store-only throughput. Compiled DXBC remains in the scratch receipt with its SHA-256.
Compare excess elapsed time and variation across fixed-workload slices, sizes, write counts and strides separately. Sparse CPU writes can change cache ownership, trigger first access or write-combine effects, and create synchronization overhead without a byte-for-byte copy. Full-buffer reads can move data inside a backend before the first GPU counter query or during later work outside it. The elapsed-time distributions can constrain added cost in the measured scenario. They cannot identify physical page identity, pin a copy to a stage based only on correlation, or exclude work that is deferred, overlapped, restricted to referenced ranges, or charged elsewhere. No theoretical Apple memory bandwidth is assumed.
One host run can expose a regression or specific measured behavior. A stable comparison needs repeat sessions, reported dispersion and actual backend verification. Timestamp results at or below zero are reported as unavailable. Query overhead is visible in the timestamped omitted-copy case. Graphics pipeline and validation work, cache effects and the admitted host pressure limit GB/s comparisons to the defined workloads. [D3D12 timing](https://learn.microsoft.com/en-us/windows/win32/direct3d12/timing).
## Device-side timing with Instruments
The tested D3D12 timestamp resolves leave the output unchanged. Use a separate Metal System Trace recording to time GPU work. This needs the installed Apple Xcode and its Instruments permissions. The wrapper attaches to the verified synthetic guest process before releasing the backend handshake. Keep traced host timing apart from the uninstrumented measurements.
```sh
probe_dir=docs/research/d3dmetal-zero-copy/copy-detection
scratch=/tmp/b473-metal-wb
python3 "$probe_dir/trace.py" wb --group compute --seed 947 --bottle "/path/to/win64/bottle" --scratch "$scratch"
trace=$(find "$scratch" -maxdepth 2 -name 'gpu.trace' -print)
export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
xcrun xctrace export --input "$trace" --xpath '/trace-toc/run[@number="1"]/data/table[@schema="metal-gpu-intervals"]' --output "$scratch/gpu-intervals.xml"
xcrun xctrace export --input "$trace" --xpath '/trace-toc/run[@number="1"]/data/table[@schema="metal-application-encoders-list"]' --output "$scratch/metal-encoders.xml"
python3 "$probe_dir/summarize-trace.py" "$scratch" "$scratch/gpu-intervals.xml" "$scratch/metal-encoders.xml"
```
Repeat serially with `wc`, `upload-wb`, `default`, `copy-wb`, `copy-wc`, or `copy-upload` as the wrapper's first argument and use a fresh scratch directory each time. The copy workload moves 64 MiB to READBACK, compares every word, and varies the two endpoints. All traced inputs retain three warmups and twelve measured iterations in their own process.
The parser requires a complete, unique sequence of matching Metal command-buffer and encoder IDs for the verified probe PID, along with successful output oracles and matching guest/encoder/GPU interval counts. For the shader it uses active Compute intervals and excludes staging and omitted dispatches. The denominator is the GPU interval duration. Report useful bytes per interval, which includes shader work and cache effects. It does not count physical bus traffic. The full trace and XML exports stay in the local scratch directory because the template can include unrelated host processes. The archived JSON extracts contain only the synthetic guest's matched intervals. [Apple Instruments Metal analysis](https://developer.apple.com/documentation/xcode/analyzing-the-performance-of-your-metal-app).
@@ -0,0 +1,99 @@
# Workstream B findings for #473
Two M5 sessions reproduced synchronized direct SRV/UAV access on the tested CUSTOM WB and WC heaps. The placement and tracking failures impose API boundaries on a BetterXen design. The copy timing shows configuration- and session-dependent latency and leaves physical page identity and internal copies unresolved.
## Host, runtime and receipts
Apple M5, 16 GiB unified RAM, 16 KiB host pages, macOS 27.2.1 build 26B131, CrossOver 26.3.0.39832, Wine 11.0-8726-g2e2f5fca349, D3DMetal 3.0 and Rosetta 1.0.0.0.1793943009 with `ROSETTA_ADVERTISE_AVX=1`. Compiled with native ARM64 MinGW GCC 16.2.0 to x86-64 PE32+. The loaded GPTK D3D12 DLL, D3DMetal framework and Rosetta runtime were verified for each graphics probe process. The write-watch-only probe did not load D3D12. Runs used a temporary clone of a Win64 bottle. Pressures were Warning with substantial compression and swap, including about 6–8 GiB of swap at performance-group start. The sessions describe this host under those conditions.
| Group | Archive |
| --- | --- |
| Normal-pressure preflight | [No workload started](../results/2026-11-27-apple-m5-atesahmet0-b-small-01/receipt.json) |
| Placement and tracking | [First session](../results/2026-11-27-apple-m5-atesahmet0-b-small-02/receipt.json), [second and clock check](../results/2026-11-27-apple-m5-atesahmet0-b-small-03/receipt.json), [clock confirmation](../results/2026-11-27-apple-m5-atesahmet0-b-small-05/03-clock/stdout.txt) |
| Copy and CPU rates | [Seed 473](../results/2026-11-27-apple-m5-atesahmet0-b-sweep-01/receipt.json), [seed 947](../results/2026-11-27-apple-m5-atesahmet0-b-sweep-02/receipt.json) |
| Compute | [Seed 473](../results/2026-11-27-apple-m5-atesahmet0-b-compute-01/receipt.json), [seed 947](../results/2026-11-27-apple-m5-atesahmet0-b-compute-02/receipt.json) |
| Metal System Trace | [Urgent stop before guest workload](../results/2026-11-27-apple-m5-atesahmet0-b-trace-01/receipt.json) |
| A same-source reproduction | [Alias](../results/2026-11-27-apple-m5-atesahmet0-b-a-alias-01/receipt.json), [texture](../results/2026-11-27-apple-m5-atesahmet0-b-a-texture-01/receipt.json), [review](review-a.md) |
## Hidden-copy detection
The two seeded sweeps used 1, 16 and 64 MiB across WB/WC/UPLOAD and both strides, 18 guest processes per session. All 5040 measured copy/control iterations matched their oracle, including poison checks. Each session also recorded 216 CPU measurements and 216 empty/signal-only measurements. Warmups and individual distributions are in the archives.
The following rows show 64 MiB WB with a 12-byte GPU copy and two distinct write strides. Times are medians in microseconds. Full rewrite touches every byte. A word per page writes 64 KiB of data at 4 KiB stride or 16 KiB at 16 KiB stride.
| Seed | Stride | No writes | One page | 64 pages | One word per page | Full rewrite | CPU write, word per page / full rewrite |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| 473 | 4 KiB | 184 | 364 | 224 | 364 | 463 | 165 / 1296 |
| 947 | 4 KiB | 181 | 393 | 383 | 188 | 377 | 160 / 1241 |
| 473 | 16 KiB | 249 | 364 | 236 | 377 | 446 | 42 / 1618 |
| 947 | 16 KiB | 360 | 355 | 371 | 373 | 406 | 38 / 1286 |
WB 64 MiB full-rewrite small-copy completion increased versus the no-write case in these four comparisons. The increase ranged from 46 to 279 µs, with different baselines. The word-per-page cases show substantial differences between seeds and strides, including nearly flat repetition and nonmonotonic behavior. Across all 64 MiB sources and both seeds the small clean-copy medians span 181–401 µs. A measured explicit full-allocation GPU copy at that size took about 2.09–2.36 ms median in the no-write cases. The small-copy path therefore does not show a serialized copy with the cost of that explicit full READBACK workload. That comparison does not rule out a faster or overlapped backend copy, copy outside the measured interval, or work restricted to referenced pages. The returns also fit cache ownership, page activity, queue scheduling, and host pressure as alternative contributors. Full-byte CPU write time is visible before submission and varies independently of it.
The earlier M5 report touched one word per 4 KiB and verified only endpoints. The historical M4 timing likewise used endpoint copies, with a separate checksum run. The current 64 MiB sweep validates endpoint/interior sentinels or every copied word and distinguishes whole-byte rewrites. There is no validated upper bound at 256 MiB or across other D3DMetal versions. There is also no direct evidence that the CPU and GPU mappings identify the same physical pages.
## Timing and effective bandwidth
Each table entry is the range of case medians across both seeds, both strides and three source heap types. Full GPU copies use the no-write case with an identical READBACK destination. Rates are decimal GB/s.
| Size | CPU checksum read | CPU memset write | GPU copy payload / fence interval |
| --- | ---: | ---: | ---: |
| 1 MiB | 8.91–17.53 | 32.36–88.12 | 2.07–4.60 |
| 16 MiB | 16.03–16.55 | 58.90–76.30 | 5.56–20.41 |
| 64 MiB | 15.74–16.51 | 47.70–56.38 | 28.38–32.33 |
Empty submit medians across both sessions were 0.30–0.60 µs for reset/encode/close, 1.80–2.95 µs for Execute, 0.20–0.30 µs for Signal, 40.25–55.05 µs for fence arm/wait and 42.60–58.30 µs total. Signal-only was 43.00–59.90 µs. These controls expose the fixed host synchronization scale and are not blindly subtracted from each workload.
D3D12 timestamp duration was unavailable. The runtime reported a 60 Hz timestamp query frequency. Regular query pairs were zero-initialized and read back 0/0. A separate fence-separated clock check at roughly 153 ms left **both distinct poison slots unchanged** even when their respective query was resolved. The old diagnostic printed the arithmetic difference of those sentinels as 16666.667 µs. The corrected clock confirmation reproduced the unchanged sentinels after about 158 ms and reported no GPU duration. The first Metal System Trace recorded a paused target and stopped at Urgent before the workload. After pressure recovered, separate captures succeeded. Fence-interval rates include all queue work and scheduling in the interval and are not device-only bandwidth. See the [clock stdout](../results/2026-11-27-apple-m5-atesahmet0-b-small-03/03-clock/stdout.txt).
## Direct shader access and persistent mapping
Each of four configurations ran six modes, twelve measured iterations and three warmups per mode, in each of two sessions. All 576 measured comparisons and their warmups were exact. That includes the two direct CUSTOM outputs and the UPLOAD→WB control using the original mapped pointers through every round. The DEFAULT control used explicit staging. Output remained poisoned when dispatch was omitted.
The table reports median submission-to-fence completion in µs for seed 473 / 947. The full-read kernel reads 4 MiB and writes a compact result. Store-only writes 4 MiB. The sparse kernels read 4096 or 1024 bytes across the same 4 MiB allocation and write equally sized results.
| Source → destination | Full read | Sparse 4 KiB | Sparse 16 KiB | Store only | Omitted dispatch |
| --- | ---: | ---: | ---: | ---: | ---: |
| WB → WB | 314 / 572 | 204 / 189 | 188 / 200 | 308 / 488 | 60 / 48 |
| WC → WC | 535 / 502 | 178 / 175 | 191 / 180 | 506 / 393 | 57 / 52 |
| UPLOAD → WB | 322 / 524 | 203 / 191 | 185 / 186 | 258 / 500 | 56 / 51 |
| DEFAULT → DEFAULT | 275 / 217 | 228 / 180 | 222 / 167 | 326 / 253 | 268 / 233 |
WB's full-read rate is approximately 13.3 / 7.3 GB/s and its store-only rate is 13.6 / 8.6 GB/s on the fence interval. WC's are approximately 7.8 / 8.4 and 8.3 / 10.7 GB/s. DEFAULT includes dependent readback in its fence interval. The staged and direct cases share shader commands while differing in transfer and barrier work. Sparse operations are completion-latency dominated. Useful-byte rates in these cases cannot be converted into physical transaction bandwidth or an intrinsic ranking of heap types. The shader compiler reported ignoring requested optimization flag 0x8000, with the same DXBC hash in all four modes and both sessions. An independent Python expression regenerated the two reported word values in each of the 720 samples including warmups and confirmed each pair.
The CPU finishes stores before GPU access, and observes writes after a queue fence. No test relies on concurrent CPU/GPU access, mapped-pointer atomics, or a console cache contract. [Synchronization and mapping contracts](../gpu-correctness/contracts/synchronization-mapping-tracking.md).
## GPU intervals from Metal System Trace
Each configuration used a separate attached Instruments capture. The analysis joins the verified probe PID's GPU work to the Metal application's encoder IDs. All 75 shader dispatches and 15 omitted controls per configuration were accounted for. Staging and readback blits remain outside the reported shader intervals. Some blits run on a trace channel named Compute, so the analysis distinguishes blits and shaders by encoder type and matching command-buffer and encoder IDs.
The table reports GPU duration median and median absolute deviation in µs for 12 measured iterations, followed by median useful payload rates in decimal GB/s. Each case has three additional warmups. Full read includes the compact dependent output. Store-only has no shader input loads.
| Heap source → output | Full read µs median ± MAD | Full read GB/s | Store-only µs median ± MAD | Store-only GB/s | Sparse read 4 / 16 KiB stride µs |
| --- | ---: | ---: | ---: | ---: | ---: |
| WB → WB | 110.23 ± 1.56 | 38.05 | 51.02 ± 3.08 | 82.21 | 6.75 / 3.92 |
| WC → WC | 106.00 ± 0.81 | 39.57 | 39.85 ± 8.40 | 105.25 | 4.98 / 1.98 |
| UPLOAD → WB | 104.54 ± 5.10 | 40.12 | 28.23 ± 4.29 | 148.62 | 6.60 / 5.71 |
| DEFAULT → DEFAULT | 32.12 ± 0.92 | 130.56 | 18.83 ± 0.04 | 222.70 | 1.83 / 1.25 |
The 64 MiB full-copy profile used the same 15 copy workloads per source heap, identical READBACK destinations and explicit fences. It verified all 16777216 words per copy. WB, WC and UPLOAD median GPU intervals were 1319.44, 1236.90 and 1476.63 µs, respectively. Median payload rates were 50.88, 54.26 and 45.87 GB/s. The MADs were 180.56, 191.69 and 299.42 µs. The first UPLOAD guest completed its checks but Instruments did not save its capture within the original timeout. The separate retry saved and matched all 15 intervals. The instrumented copy fixture uses a different data initialization from the uninstrumented sweep. Compare only the same kind of measurement.
These are per-encoder device-side timings, with GPU execution, cache and trace effects included. Application payload divided by duration does not reveal physical memory transactions. An individual interval can be much longer than its case's median, and cells come from separate single captures on a pressured host. Inspect the individual samples before using the rates for design decisions. The substantial difference between the two write-only workloads with WB output is a direct cross-capture reproducibility limit.
[WB trace](../results/2026-11-27-apple-m5-atesahmet0-b-trace-02/gpu-samples.json), [WC trace](../results/2026-11-27-apple-m5-atesahmet0-b-metal-wc/gpu-samples.json), [UPLOAD→WB trace](../results/2026-11-27-apple-m5-atesahmet0-b-metal-upload-wb/gpu-samples.json), [DEFAULT trace](../results/2026-11-27-apple-m5-atesahmet0-b-metal-default/gpu-samples.json), [WB copy trace](../results/2026-11-27-apple-m5-atesahmet0-b-metal-copy-wb/gpu-samples.json), [WC copy trace](../results/2026-11-27-apple-m5-atesahmet0-b-metal-copy-wc/gpu-samples.json), [UPLOAD copy trace](../results/2026-11-27-apple-m5-atesahmet0-b-metal-copy-upload-retry/gpu-samples.json).
## Alignment and write tracking
The first independent M5 placement probe found CPU Map remainders of 16384 for WB/WC/UPLOAD and 0 for the VirtualAlloc control. A later fresh process returned 0 for the valid maps. The same-source alias runs returned 32768 and 16384. All checked valid GPU VAs remained 64 KiB aligned. For invalid creation only, a 64 KiB heap accepted offsets 1 and 65536, and a 128 KiB heap accepted offset 1 with the allocation span otherwise in bounds. None of these resources was used after the creation call. Caller alignment and bounds validation remain required.
A CPU-only watch-enabled allocation gave exact 4096-byte page sets through eleven phases in each small group. Same-host-page subpages were distinguishable, boundary stores appeared at 12288 and 16384, query and separate reset cleared tracking, and rearming captured later stores including a same-value write. A read did not set a dirty bit. The watch-enabled allocation could not be wrapped by D3D12 (E_NOTIMPL). IsolatedMMU was false. General GPU-write tracking and coherence on a foreign Map pointer remain unestablished.
## BetterXen handoff
1. Use D3D12-owned CPU-visible buffers as a candidate for allocations whose alignment, lifetime and ownership contracts match the actual returned pointer. Keep heap-relative validation, CPU pointer checks and fence-delayed reuse explicit. A mapped aligned slice does not automatically give a legal corresponding placed-resource offset.
2. Use the ordinary texture layout, initialization, state and copy rules for opaque textures. The M4/M5 mixed and alias fixtures establish the reported functional subcases. They do not establish raw pointer equivalence or general texture inheritance.
3. Keep device-owned and predevice CPU-owned memory paths explicit. Existing-memory import returned E_NOTIMPL in the tested cases. Write-watch may reduce CPU-to-GPU explicit-copy work with controlled writer ownership, rearming and retry handling. GPU-to-CPU synchronization requires a fence and a supported visibility/transfer contract.
4. Use one logical budget and monitor separate process-accounting or runtime-retention measurements. A's large runs observe retained charges and incomplete repeats. No Class A evidence here proves a leak or a universal retention amount.
5. Preserve #464's scope. [PR #486](https://github.com/MacosPorters/betterxen/pull/486) reports vkd3d execution and already guards placement. Its statements about physical sharing and absence of copies exceed the scope established by this research.
Outstanding items include repeated GPU traces at normal pressure, independent repetition of B on M4, normal-pressure sensitivity, same-host accounting repeats for large allocations, generalized GPU-write tracking, any stronger physical-page or copy-mechanism claim, and reciprocal acceptance of the architecture handoff. Workstream B's own runs are author-run. The A review records separate source analysis, same-source M5 reproduction, and separately implemented placement verification.
@@ -0,0 +1,303 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "support.h"
#include <algorithm>
#include <bit>
#include <numeric>
#include <random>
#include <vector>
constexpr UINT MiB = 1024 * 1024;
constexpr UINT placement = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
static void placement_probe(Device& d) {
const auto desc = buffer_desc(placement, D3D12_RESOURCE_FLAG_NONE);
const auto alloc = d.device->GetResourceAllocationInfo(0, 1, &desc);
for (const auto& [heap_size, offset] : {
std::pair{UINT64(placement), 0ull}, std::pair{UINT64(placement), 1ull},
std::pair{UINT64(placement), UINT64(placement)}, std::pair{UINT64(2 * placement), 1ull}}) {
auto heap = d.heap(Heap::wb, heap_size);
Com<ID3D12Resource> resource;
const HRESULT hr = d.device->CreatePlacedResource(heap.get(), offset, &desc,
D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), resource.out());
const bool aligned = alloc.Alignment && offset % alloc.Alignment == 0;
const bool in_bounds = offset <= heap_size && alloc.SizeInBytes <= heap_size - offset;
const bool legal = aligned && in_bounds;
std::printf("PLACEMENT offset=%llu heap=%llu size=%llu alignment=%llu aligned=%d in_bounds=%d eligible=%d hr=%08lx object=%d\n",
offset, heap_size, alloc.SizeInBytes, alloc.Alignment, aligned, in_bounds, legal,
static_cast<unsigned long>(hr), resource.get() != nullptr);
// Creation-only negatives: no Map, GPU VA lookup, command recording, or submission.
if (!legal) continue;
check(hr, "valid placement");
void* pointer = nullptr;
check(resource->Map(0, nullptr, &pointer), "valid placement Map");
if (!pointer) throw std::runtime_error("valid placement Map returned null");
const auto addr = reinterpret_cast<uintptr_t>(pointer);
std::printf("MAP heap=wb size=%u cpu_mod16k=%llu cpu_mod64k=%llu gpu_mod64k=%llu\n",
placement, UINT64(addr % 16384), UINT64(addr % placement),
resource->GetGPUVirtualAddress() % placement);
resource->Unmap(0, nullptr);
}
for (const auto& [kind, name] : {std::pair{Heap::wb, "wb"}, {Heap::wc, "wc"}, {Heap::upload, "upload"}}) {
Buffer buffer(d, kind, 4 * MiB, kind == Heap::upload
? D3D12_RESOURCE_STATE_GENERIC_READ : D3D12_RESOURCE_STATE_COMMON);
const auto addr = reinterpret_cast<uintptr_t>(buffer.map());
std::printf("MAP heap=%s size=%u cpu_mod16k=%llu cpu_mod64k=%llu gpu_mod64k=%llu\n",
name, 4 * MiB, UINT64(addr % 16384), UINT64(addr % placement),
buffer.resource->GetGPUVirtualAddress() % placement);
}
void* ptr = VirtualAlloc(nullptr, placement, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (!ptr) throw std::runtime_error("VirtualAlloc alignment control");
std::printf("MAP heap=virtualalloc size=%u cpu_mod64k=%llu\n",
placement, UINT64(reinterpret_cast<uintptr_t>(ptr) % placement));
if (!VirtualFree(ptr, 0, MEM_RELEASE)) throw std::runtime_error("VirtualFree");
}
static void clock_probe(Device& d) {
Queue queue(d);
Timestamp stamp(d, queue);
const UINT64 poison[] = {0x9cde12154b320001ull, 0x9cde12154b320002ull};
std::memcpy(stamp.output.pointer, poison, sizeof(poison));
_mm_sfence();
const auto start = ticks();
queue.begin();
stamp.start(queue);
queue.list->ResolveQueryData(stamp.queries.get(), D3D12_QUERY_TYPE_TIMESTAMP, 0, 1,
stamp.output.resource.get(), 0);
queue.close();
queue.execute();
const UINT64 early = stamp.data[0];
const UINT64 untouched = stamp.data[1];
Sleep(150);
queue.begin();
queue.list->EndQuery(stamp.queries.get(), D3D12_QUERY_TYPE_TIMESTAMP, 1);
queue.list->ResolveQueryData(stamp.queries.get(), D3D12_QUERY_TYPE_TIMESTAMP, 1, 1,
stamp.output.resource.get(), sizeof(UINT64));
queue.close();
queue.execute();
UINT64 gpu_calibration = 0, cpu_calibration = 0;
const HRESULT hr = queue.queue->GetClockCalibration(&gpu_calibration, &cpu_calibration);
const bool resolved_first = early != poison[0];
const bool resolved_last = stamp.data[1] != poison[1];
const double gpu_us = resolved_first && resolved_last ? stamp.elapsed() : -1;
std::printf("CLOCK cpu_elapsed_us=%.3f first=%llu expected_poison_first=%llu untouched=%llu "
"expected_poison_last=%llu last=%llu resolved_first=%d resolved_last=%d gpu_elapsed_us=%.3f "
"calibration_hr=%08lx calibration_gpu=%llu calibration_cpu=%llu\n",
us(ticks() - start), early, poison[0], untouched, poison[1], stamp.data[1],
resolved_first, resolved_last, gpu_us, static_cast<unsigned long>(hr), gpu_calibration, cpu_calibration);
if (untouched != poison[1]) throw std::runtime_error("query resolve overwrote untouched slot");
}
static uint32_t repeated_byte(uint8_t value) {
return 0x01010101u * value;
}
struct Case {
UINT dirty;
bool full_write;
bool full_read;
bool omit;
};
static void sweep(Device& d, Heap kind, UINT bytes, UINT stride, UINT seed) {
// Buffers in COMMON promote to COPY_SOURCE and decay at each completed Execute.
// UPLOAD stays GENERIC_READ, which includes COPY_SOURCE.
Buffer src(d, kind, bytes, kind == Heap::upload ? D3D12_RESOURCE_STATE_GENERIC_READ
: D3D12_RESOURCE_STATE_COMMON);
Buffer dst(d, Heap::readback, bytes, D3D12_RESOURCE_STATE_COPY_DEST);
auto* in = src.map();
auto* out = dst.map();
Queue q(d);
Timestamp stamp(d, q);
const UINT words = bytes / 4;
const UINT pages = bytes / stride;
const UINT page_words = stride / 4;
const UINT offsets[] = {0, words / 2, words - page_words};
std::vector<UINT> order(pages);
std::iota(order.begin(), order.end(), 0u);
std::mt19937 random(seed);
// Fix endpoint and interior coverage. Randomize the remaining pages and case order.
std::shuffle(order.begin(), order.end(), random);
for (UINT i = 0; i < 3; ++i)
std::iter_swap(order.begin() + i, std::find(order.begin(), order.end(), offsets[i] / page_words));
std::vector<Case> cases;
for (bool full_read : {false, true}) {
for (UINT dirty : {0u, 1u, std::min(64u, pages), pages}) {
if (dirty == pages && cases.back().dirty == pages) continue;
cases.push_back({dirty, false, full_read, false});
}
cases.push_back({pages, true, full_read, false});
cases.push_back({pages, false, full_read, true});
}
std::shuffle(cases.begin(), cases.end(), random);
for (const Case test : cases) {
constexpr uint8_t initial = 0x27;
constexpr uint32_t poison = 0xefefefefu;
std::memset(in, initial, bytes);
_mm_sfence();
std::vector<bool> changed(pages);
for (UINT i = 0; i < test.dirty; ++i) changed[order[i]] = true;
const UINT copied_words = test.full_read ? words : 3;
for (int i = -3; i < 12; ++i) {
const auto byte = uint8_t(0x60 + i);
std::memset(out, 0xef, copied_words * 4u);
_mm_sfence();
const auto write_start = ticks();
if (test.full_write) {
std::memset(in, byte, bytes);
} else {
for (UINT j = 0; j < test.dirty; ++j)
in[order[j] * page_words] = repeated_byte(byte);
}
_mm_sfence();
const auto written = ticks();
q.begin();
if (test.full_read) stamp.start(q);
if (!test.omit) {
if (test.full_read) {
q.list->CopyBufferRegion(dst.resource.get(), 0, src.resource.get(), 0, bytes);
} else {
for (UINT j = 0; j < 3; ++j)
q.list->CopyBufferRegion(dst.resource.get(), j * 4u,
src.resource.get(), offsets[j] * 4u, 4);
}
}
if (test.full_read) stamp.end(q);
q.close();
const auto encoded = ticks();
const auto latency = q.execute();
const auto validate_start = ticks();
bool ok = true;
uint32_t first_expected = 0, last_expected = 0;
UINT matches = 0;
for (UINT j = 0; j < copied_words; ++j) {
const UINT index = test.full_read ? j : offsets[j];
const bool modified = test.full_write ||
(index % page_words == 0 && changed[index / page_words]);
const auto expected = test.omit ? poison : repeated_byte(modified ? byte : initial);
if (!j) first_expected = expected;
if (j == copied_words - 1) last_expected = expected;
const auto actual = out[j];
if (ok && actual != expected) {
std::printf("MISMATCH index=%u expected=%08x actual=%08x\n", index, expected, actual);
ok = false;
}
matches += actual == expected;
}
const auto verified = ticks();
const double gpu_us = test.full_read ? stamp.elapsed() : -1;
std::printf("COPY bytes=%u stride=%u seed=%u dirty=%u full_write=%d full_read=%d omit=%d iter=%d "
"cpu_written=%u gpu_payload=%u gpu_tick_begin=%llu gpu_tick_end=%llu cpu_write_us=%.3f encode_us=%.3f execute_us=%.3f "
"signal_us=%.3f wait_us=%.3f completion_us=%.3f gpu_us=%.3f validation_us=%.3f "
"expected=%08x,%08x actual=%08x,%08x matches=%u/%u\n",
bytes, stride, seed, test.dirty, test.full_write, test.full_read, test.omit, i,
test.full_write ? bytes : test.dirty * 4, test.omit ? 0 : copied_words * 4,
test.full_read ? stamp.data[0] : 0, test.full_read ? stamp.data[1] : 0,
us(written - write_start), us(encoded - written), latency.execute, latency.signal,
latency.wait, latency.total, gpu_us, us(verified - validate_start),
first_expected, last_expected, out[0], out[copied_words - 1], matches, copied_words);
if (!ok) throw std::runtime_error("copy/omit oracle");
}
}
for (int i = -3; i < 12; ++i) {
const auto byte = uint8_t(0x40 + i);
const auto write_start = ticks();
std::memset(in, byte, bytes);
_mm_sfence();
const auto written = ticks();
uint64_t sum = 0;
for (UINT j = 0; j < words; ++j) sum += in[j];
const auto read = ticks();
const auto expected = uint64_t(repeated_byte(byte)) * words;
std::printf("CPU bytes=%u iter=%d write_us=%.3f read_us=%.3f sum=%llu expected=%llu\n",
bytes, i, us(written - write_start), us(read - written),
static_cast<unsigned long long>(sum), static_cast<unsigned long long>(expected));
if (sum != expected) throw std::runtime_error("CPU bandwidth oracle");
}
for (int i = -3; i < 12; ++i) {
const auto start = ticks();
q.begin();
q.close();
const auto encoded = ticks();
const auto latency = q.execute();
const auto signal_only = q.execute(false);
std::printf("EMPTY iter=%d encode_us=%.3f execute_us=%.3f signal_us=%.3f wait_us=%.3f "
"completion_us=%.3f signal_only_us=%.3f\n", i, us(encoded - start),
latency.execute, latency.signal, latency.wait, latency.total, signal_only.total);
}
}
static void trace_copy(Device& d, Heap kind) {
constexpr UINT bytes = 64 * MiB;
constexpr UINT count = bytes / 4;
Buffer src(d, kind, bytes, kind == Heap::upload ? D3D12_RESOURCE_STATE_GENERIC_READ
: D3D12_RESOURCE_STATE_COMMON);
Buffer dst(d, Heap::readback, bytes, D3D12_RESOURCE_STATE_COPY_DEST);
auto* in = src.map();
auto* out = dst.map();
for (UINT j = 0; j < count; ++j) in[j] = j ^ 0x5A3367F9u;
Queue q(d);
for (int i = -3; i < 12; ++i) {
const UINT salt = 0xC6D2B000u + UINT(i + 3);
in[0] = salt;
in[count - 1] = ~salt;
std::memset(out, 0x5D, bytes);
_mm_sfence();
q.begin();
q.list->CopyBufferRegion(dst.resource.get(), 0, src.resource.get(), 0, bytes);
q.close();
const auto latency = q.execute();
UINT matches = (out[0] == salt) + (out[count - 1] == ~salt);
for (UINT j = 1; j < count - 1; ++j) matches += out[j] == (j ^ 0x5A3367F9u);
std::printf("TRACE_COPY iter=%d gpu_payload=%u completion_us=%.3f "
"actual=%08x,%08x expected=%08x,%08x matches=%u/%u\n",
i, bytes, latency.total, out[0], out[count - 1], salt, ~salt, matches, count);
if (matches != count) throw std::runtime_error("trace copy oracle");
}
}
static Heap parse_heap(const std::string& name) {
if (name == "wb") return Heap::wb;
if (name == "wc") return Heap::wc;
if (name == "upload") return Heap::upload;
throw std::runtime_error("unknown heap");
}
int main(int argc, char** argv) {
setvbuf(stdout, nullptr, _IONBF, 0);
try {
if (argc != 2 && argc != 3 && argc != 6)
throw std::runtime_error("usage: probe placement | clock | trace-copy HEAP | sweep HEAP MIB STRIDE SEED");
Device device;
receipt_pause();
if (argc == 2 && std::string(argv[1]) == "placement") {
placement_probe(device);
} else if (argc == 2 && std::string(argv[1]) == "clock") {
clock_probe(device);
} else if (argc == 3 && std::string(argv[1]) == "trace-copy") {
trace_copy(device, parse_heap(argv[2]));
} else if (argc == 6 && std::string(argv[1]) == "sweep") {
const std::string name = argv[2];
const auto mib = std::stoul(argv[3]);
const auto stride = std::stoul(argv[4]);
const auto seed = std::stoul(argv[5]);
if (!std::has_single_bit(mib) || mib > 64 || (stride != 4096 && stride != 16384))
throw std::runtime_error("sweep bounds");
std::printf("CONFIG heap=%s MiB=%lu stride=%lu seed=%lu warmups=3 measured=12\n",
name.c_str(), mib, stride, seed);
sweep(device, parse_heap(name),
UINT(mib) * MiB, UINT(stride), UINT(seed));
} else {
throw std::runtime_error("unknown mode");
}
std::puts("END complete");
return 0;
} catch (const std::exception& e) {
std::fprintf(stderr, "END failure: %s\n", e.what());
return 1;
}
}
@@ -0,0 +1,40 @@
# Independent review of Workstream A
Reviewed source and executed snapshots at [8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8](https://github.com/MacosPorters/betterxen/commit/8cc2f8ffbc4368e38950c2e037fee4ce12fa88b8). The published receipts identify the guest builds and retain raw M4 results. I recalculated source snapshot hashes and inspected the command paths and original stdout. M5 reproduction status is recorded separately below.
## Placement and resource correctness
| Evidence | Independent expectation and assessment |
| --- | --- |
| WB mapped CPU pointer alignment | Microsoft specifies alignment for heap-relative placement. Nothing in the Map contract equates CPU and GPU virtual addresses or makes the CPU address 64 KiB aligned. In A's two raw buffer-alias runs, CPU pointers ended in `4000` modulo `10000` (hex). That is 16384 modulo 65536. The GPU VAs were multiples of 65536. Independently written B placement code reproduced the distinction on M5. |
| Two invalid creations | A's 64 KiB buffer at offset 1 is misaligned and its allocation span also exceeds the heap by one byte. The aligned offset 65536 lies at the end of the 64 KiB heap and leaves zero bytes for the nonempty buffer. A's two M4 logs show successful returns for both and E_INVALIDARG for a texture on a buffer-only heap. A submitted neither invalid buffer. B separately reproduced the buffer returns on M5. Compare against a valid offset 0. |
| Same-offset buffer aliases | The placed buffers have the same known layout, while the guard range is wholly disjoint. The advanced-model alias barrier orders the write and second resource's COPY_SOURCE read in one submitted list. The explicit COMMON transitions scope each use, the fence follows all copies, and the guard exercises a displaced range. The expected pointer and GPU VA deltas are 0 and 65536 respectively. The two raw runs show the correct deltas and 16384/16384 for each of source, inherited and guard readbacks in each of three rounds. The seed steps 0x101 each round and 0x10000 each session. These results demonstrate application-visible addresses and GPU data inheritance for these whole-buffer ranges. The backend's backing pages and arbitrary CPU aliases remain unresolved. |
| Mixed mip textures | The three mips have dimensions 65×37, 32×18 and 16×9, totaling 3125 texels. This yields 3125 useful bytes for R8_UNORM and 12500 for RGBA8 or R32_UINT. Distinguish 512-byte copy-placement offsets and 256-byte row pitches from allocation alignment and actual texel widths. WB/WC use per-mip Map with null output and WriteToSubresource in COMMON. DEFAULT uses a staged copy. The readback transition and fence are explicit, and guard writes finish before the subsequent steps. Both raw runs record all nine useful-byte and guard checks exact. Byte count excludes padding. The test does not assert texture sampling or raw texture Map pointer results. |
| RGBA8 and depth alias clears | The fixture activates each RT/DS alias and then clears in RENDER_TARGET or DEPTH_WRITE, respectively. Readbacks are distinct and the transition to COPY_SOURCE orders the transfer. RGBA8 clear tuples are (1,0,1,1) and (0,1,1,1), equivalent to little-endian words 0xffff00ff and 0xffffff00. Depth 0.5 and 0.25 correspond to 0x3f000000 and 0x3e800000. Both M4 logs show 2405/2405 per alias for WB and DEFAULT. Each alias is reinitialized. This tests separated activation and clear, so it leaves texture data inheritance, stencil and rasterized depth open. |
[Microsoft placed resources](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource), [buffer footprints](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-getcopyablefootprints), [memory aliasing and data inheritance](https://learn.microsoft.com/en-us/windows/win32/direct3d12/memory-aliasing-and-data-inheritance).
One harness limitation: A's normal successful runs wait before object teardown. After a fence failure, the shared Queue helper throws with possible outstanding work, unwinding local resources before the parent terminates the guest. That error path should use explicit retirement or disposable-process teardown in future fixtures. It does not change the reported results with valid fences.
## Physical accounting
The corrected A2 source retires allocation, command and shader objects, then releases the device. It also includes truly CPU-only and graphics-warmed CPU controls. That materially improves the earlier release checkpoint. The A2 bundle contains 12 completed cases and an interrupted later case. A22 includes a second distinct pressure stop and cannot be pooled as a full repeat of A2.
A's three in-stage readings are correlated samples within one process. The 64 MiB heap observations can fit existing driver accounting, while the 256 MiB and 1 GiB cases add a charge close to requested size and retain most of that charge after teardown. The same large case has process-ledger footprint and RSS that differ substantially. These observations establish accounting over the observed lifetime, with incomplete independent repetitions, under reported compression and swap. They leave driver pools, caching, mappings billed elsewhere, transient copies and actual physical-page identity open. A dropped CPU-only allocation is a useful control for process accounting, but carries no information about uncharged GPU domains.
The historical M5 1 GiB fixture copied chunks into one readback region and compared the final chunk's first word. Its command stream requests consumption of the entire buffer, while its oracle directly verifies just that last word. This limits what it can establish about actual work performed. The retained output has no complete independent set of vmmap stages and no raw timing samples for the two dirty runs. Keep the prior comment's numbers as attributed historical results.
## Pooling and #464
A's corrected pool trace distinguishes warm allocation/free call timing from cold setup and unused slab capacity. Its real delayed-retirement gate is more meaningful than a future value inserted into the CPU model. The omitted-copy exit is the expected guard/interior mismatch. A smaller warm call cost on the one M4 does not by itself quantify whole-application residency, fragmentation or retained driver memory.
At [PR #486 head 6308fdc](https://github.com/MacosPorters/betterxen/pull/486), the code already validates a 64 KiB grid, resource allocation alignment and the overflow-safe heap span. The reported PR execution is CrossOver 26.2 vkd3d. Treat this M5 D3DMetal study as research for the implementation, without attributing its results to the PR executable. The PR publishes a Map address. Any 64 KiB or larger xmem alignment promise, fixed-address reservation, alias/scatter view or pre-device ownership requirement must be validated independently. Budget logical bytes separately from the driver-retention envelope.
## Same-source reproduction on M5
At the pinned A revision, I rebuilt both sources with their A-local runner, MinGW GCC 16.2.0 and Apple clang 21. The archived source hashes match A's originals. The file hashes of the rebuilt PEs differ, as expected for separate builds. Both sessions loaded the D3DMetal framework and GPTK D3D12, as confirmed by the loaded-library receipt. Host pressure was Warning.
- Both buffer sessions exited 0 and matched all 18 arrays of 16384 words across the source, inherited and guard outputs. The overlapping pairs had equal CPU and GPU virtual addresses. The disjoint CPU and GPU deltas were both 65536 bytes. Map remainders were 32768 and 16384. See the [alias reproduction](../results/2026-11-27-apple-m5-atesahmet0-b-a-alias-01/receipt.json).
- Each texture session matched all nine mixed-heap data and guard comparisons and all eight render/depth clears. Each exited 1 at the same invalid-placement rejection gate. Wrong heap flags still returned E_INVALIDARG. This is a reproduced failure in the full fixture and reproduced positive results in the named valid subcases. See the [texture reproduction](../results/2026-11-27-apple-m5-atesahmet0-b-a-texture-01/receipt.json).
- The independently implemented B placement case additionally used offset 1 in a 128 KiB heap, making the span fit while keeping alignment invalid. The backend returned S_OK. In a separate session the valid maps happened to be 64 KiB aligned. This variation reinforces the need to check each actual CPU address. Invalid resources had no Map, GPU address lookup or submission. See the [isolated placement controls](../results/2026-11-27-apple-m5-atesahmet0-b-small-03/00-placement/stdout.txt).
- Physical-memory accounting and pooling received source and raw-data review. I did not repeat the large M4 accounting profile under the M5's Warning/Urgent conditions. I independently recomputed three native receipt checkpoints. The 1 GiB CPU-only control was charged 13.19 MiB (settled baseline), 1039.47 MiB (initialization) and 13.45 MiB (device-release checkpoint without a device). The WB graphics process was charged 301.36 MiB (baseline), 1368.32 MiB (GPU-complete) and 1328.02 MiB (after device release). The 64 MiB WB process returned from 341.13 MiB after GPU use to 300.79 MiB after device release, near its 300.62 MiB baseline. These are distinct workload-scoped accounting outcomes. See the [A2 raw accounting receipt](../results/2026-11-26-apple-m4-arths17-a2-memory-partial/receipt.json).
@@ -0,0 +1,273 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Build and run B-local probes in a temporary CrossOver bottle."""
import argparse
import fcntl
import hashlib
import json
import os
import plistlib
import random
import re
import shutil
import signal
import subprocess
import time
from datetime import datetime, timezone
from pathlib import Path
HERE = Path(__file__).resolve().parent
REPO = HERE.parents[3]
COHERENCE = HERE.parent / 'gpu-correctness' / 'coherence-and-tracking'
CROSSOVER = Path('/Applications/CrossOver.app/Contents/SharedSupport/CrossOver')
WINE = CROSSOVER / 'bin/wine'
FRAMEWORK = CROSSOVER / 'lib64/apple_gptk/external/D3DMetal.framework/Versions/A'
APPLE_GPTK_DLL = CROSSOVER / 'lib64/apple_gptk/wine/x86_64-windows/d3d12.dll'
COMPILER_DLL = CROSSOVER / 'lib/wine/x86_64-windows/d3dcompiler_47.dll'
BASELINE_SHA = '33e90bfee89e812f48990613cd74ced56473e5c3fc5d973f2ba1116090646a0c'
COMPILER = 'x86_64-w64-mingw32-g++'
def sha(path):
with path.open('rb') as source:
return hashlib.file_digest(source, 'sha256').hexdigest()
def capture(cmd, env, cwd, timeout=15):
argv = [str(arg) for arg in cmd]
try:
result = subprocess.run(argv, env=env, cwd=cwd, text=True,
errors='replace', capture_output=True, timeout=timeout)
return dict(command=argv, exit=result.returncode, stdout=result.stdout, stderr=result.stderr)
except (OSError, subprocess.TimeoutExpired) as failure:
return dict(command=argv, exit=None, failure=repr(failure))
def pressure(env, cwd, max_level):
kernel = capture(['sysctl', '-n', 'kern.memorystatus_vm_pressure_level'], env, cwd)
free = capture(['memory_pressure', '-Q'], env, cwd)
match = re.search(r'free percentage: (\d+)%', free.get('stdout', ''))
level = kernel.get('stdout', '').strip()
ok = (kernel['exit'] == free['exit'] == 0 and level.isdigit()
and int(level) <= max_level and match and int(match[1]) >= 30)
return dict(allowed=bool(ok), max_kernel_level=max_level, kernel=kernel, free=free,
swap=capture(['sysctl', 'vm.swapusage'], env, cwd),
vm=capture(['vm_stat'], env, cwd))
def cases_for(group, seed):
if group == 'small':
return [('copy', ['placement']), ('coherence', ['watch']), ('coherence', ['wrap-watch']), ('copy', ['clock'])]
if group == 'compute':
names = ['wb', 'wc', 'upload-wb', 'default']
random.Random(seed).shuffle(names)
return [('coherence', [name]) for name in names]
matrix = [('copy', ['sweep', heap, str(size), str(stride), str(seed)])
for heap in ['wb', 'wc', 'upload'] for size in [1, 16, 64]
for stride in [4096, 16384]]
random.Random(seed).shuffle(matrix)
return matrix
def ready(process, path, timeout):
while time.monotonic() < timeout:
if b'BACKEND_READY' in path.read_bytes():
return
if process.poll() is not None:
raise RuntimeError('guest exited before backend marker')
time.sleep(0.05)
raise TimeoutError('backend marker')
def backend(exe, env, cwd):
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
found = capture(['lsof', '-t', '-a', '-c', exe.name, str(exe)], env, cwd, 2)
pids = {p for p in found.get('stdout', '').split() if p.isdigit()}
if len(pids) == 1:
pid = pids.pop()
libs = capture(['lsof', '-n', '-p', pid], env, cwd, 3)
markers = ('apple_gptk/wine/x86_64-windows/d3d12.dll',
'D3DMetal.framework/Versions/A/D3DMetal', '/rosetta/runtime',
'd3d12_xs.dll')
paths = [line[line.index('/'):] for line in libs.get('stdout', '').splitlines()
if '/' in line and any(marker in line for marker in markers)]
verified = (libs['exit'] == 0 and all(any(m in path for path in paths) for m in markers[:2])
and not any(markers[-1] in path for path in paths))
return dict(verified=verified, guest_pid=pid, lsof_exit=libs['exit'], paths=paths)
time.sleep(0.05)
return dict(verified=False, message='could not identify unique probe PID', lookup=found)
def run_case(command, exe, label, has_gpu, case, env, max_level):
case.mkdir()
if label == 'coherence' and has_gpu:
shader = case.parent / 'source' / (COHERENCE / 'access.hlsl').relative_to(REPO)
shutil.copy2(shader, case)
result = dict(command=command, timeout_seconds=45, exit=None)
deadline = time.monotonic() + result['timeout_seconds']
stdout = case / 'stdout.txt'
process = None
try:
with stdout.open('wb') as out, (case / 'stderr.txt').open('wb') as err:
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=out, stderr=err,
env=env, cwd=case, start_new_session=True)
if has_gpu:
ready(process, stdout, min(deadline, time.monotonic() + 20))
result['backend'] = backend(exe, env, case)
if not result['backend']['verified']:
raise RuntimeError('active D3DMetal verification failed before workload')
result['pressure_ready'] = pressure(env, case, max_level)
if not result['pressure_ready']['allowed']:
raise RuntimeError('pressure gate at paused device before workload')
process.stdin.write(b'\n')
process.stdin.flush()
result['exit'] = process.wait(timeout=max(0, deadline - time.monotonic()))
except BaseException as failure:
result['error'] = repr(failure)
if process is not None:
if process.poll() is None:
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
result['exit'] = process.wait(timeout=5)
if isinstance(failure, KeyboardInterrupt):
result['interrupted'] = True
finally:
result['output_hashes'] = {p.name: sha(p) for p in case.iterdir() if p.is_file()}
(case / 'case.json').write_text(json.dumps(result, indent=2) + '\n')
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--bottle', type=Path)
parser.add_argument('--scratch', type=Path, required=True)
parser.add_argument('--group', choices=['build', 'small', 'compute', 'sweep'], required=True)
parser.add_argument('--seed', type=int, default=473)
parser.add_argument('--allow-warning', action='store_true')
args = parser.parse_args()
if not 0 <= args.seed < 2**32:
parser.error('seed must fit uint32')
if args.group != 'build' and not args.bottle:
parser.error('a win64 CrossOver bottle is required for execution')
root = args.scratch.expanduser().resolve()
if root == REPO or REPO in root.parents:
parser.error('scratch must be outside the checkout')
root.mkdir(mode=0o700)
env = {k: os.environ[k] for k in ['HOME', 'USER', 'LOGNAME', 'PATH', 'LANG', 'LC_ALL'] if k in os.environ}
env.update(TMPDIR=str(root) + '/', ROSETTA_ADVERTISE_AVX='1',
CX_GRAPHICS_BACKEND='d3dmetal', WINEDEBUG='-all')
receipt = dict(protocol='B-local-1', group=args.group, seed=args.seed,
utc=datetime.now(timezone.utc).isoformat(), independent_review='pending',
environment={k: env[k] for k in ['ROSETTA_ADVERTISE_AVX', 'CX_GRAPHICS_BACKEND', 'WINEDEBUG']},
commands={}, cases=[])
source_files = [Path(__file__), HERE / 'support.h', HERE / 'probe.cpp',
COHERENCE / 'probe.cpp', COHERENCE / 'access.hlsl']
receipt['sources'] = {}
for path in source_files:
relative = path.resolve().relative_to(REPO)
snapshot = root / 'source' / relative
snapshot.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(path, snapshot)
receipt['sources'][str(relative)] = sha(snapshot)
def save():
(root / 'receipt.json').write_text(json.dumps(receipt, indent=2) + '\n')
executables = {}
tools = {'git': ['git', '-C', REPO, 'rev-parse', 'HEAD'], 'hardware': ['sysctl', '-n',
'machdep.cpu.brand_string', 'hw.memsize', 'hw.pagesize'],
'os': ['sw_vers'], 'host': ['uname', '-m'], 'cpu_load': ['uptime'],
'rosetta': ['pkgutil', '--pkg-info', 'com.apple.pkg.RosettaUpdateAuto'],
'compiler': [COMPILER, '--version'], 'compiler_arch': ['file', '-L', shutil.which(COMPILER) or COMPILER],
'cx_version': [WINE, '--version'],
'wine_engine': [CROSSOVER / 'bin/wineloader', '--version'],
'python': ['python3', '--version']}
for name, subcommand in tools.items():
receipt['commands'][name] = capture(subcommand, env, root)
receipt['baseline_sha256'] = sha(HERE.parent / 'probe.cpp')
if receipt['baseline_sha256'] != BASELINE_SHA:
save()
raise RuntimeError('frozen baseline hash differs')
receipt['framework'] = plistlib.loads((FRAMEWORK / 'Resources/Info.plist').read_bytes())
receipt['runtime_sha256'] = {str(p): sha(p) for p in [APPLE_GPTK_DLL, COMPILER_DLL]}
max_level = int(args.allow_warning)
receipt['pressure_before'] = pressure(env, root, max_level)
save()
for name, path in [('copy', HERE), ('coherence', COHERENCE)]:
exe = root / ('b-' + name + '.exe')
source = root / 'source' / (path / 'probe.cpp').relative_to(REPO)
cmd = [COMPILER, '-std=c++20', '-O2', '-static', '-static-libgcc', '-static-libstdc++',
'-Wall', '-Wextra', '-Werror', source, '-o', exe]
result = capture(cmd, env, root, 60)
receipt['commands']['build_' + name] = result
save()
if result['exit'] != 0:
return 1
executables[name] = exe
receipt.setdefault('executables', {})[name] = dict(filename=exe.name, sha256=sha(exe),
format=capture(['file', exe], env, root))
save()
if args.group == 'build':
return 0
receipt['pressure_before_bottle'] = pressure(env, root, max_level)
if not receipt['pressure_before_bottle']['allowed']:
receipt['stop_reason'] = 'pressure gate before bottle clone; execution did not start'
save()
return 2
lock = open('/tmp/betterxen-473-gpu.lock', 'a')
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
bottle = args.bottle.expanduser().resolve()
config = bottle / 'cxbottle.conf'
original = config.read_text()
if '"WineArch" = "win64"' not in original:
raise RuntimeError('requires a win64 bottle')
receipt['bottle_input_sha256'] = sha(config)
private = root / 'bottle'
succeeded = True
try:
shutil.copytree(bottle, private, symlinks=True)
clone_config = re.sub(r'(?m)^\[Bottle\]\s*$', '[Bottle]\n"AllowUntrusted" = "1"',
original, count=1)
clone_config += '\n[EnvironmentVariables]\n"CX_GRAPHICS_BACKEND" = "d3dmetal"\n'
clone_config += '\n[CrossOver]\n"AntiVirusScan" = "untrusted"\n'
(private / 'cxbottle.conf').write_text(clone_config)
receipt['bottle_settings'] = [line for line in clone_config.splitlines() if re.match(
r'"(WineArch|Template|WindowsVersion|CX_GRAPHICS_BACKEND|AllowUntrusted|AntiVirusScan)"', line)]
receipt['case_order'] = cases_for(args.group, args.seed)
for index, (label, argv) in enumerate(receipt['case_order']):
before = pressure(env, root, max_level)
case = root / ('%02d-' % index + '-'.join(argv))
item = dict(directory=case.name, pressure_before=before)
receipt['cases'].append(item)
if not before['allowed']:
receipt['stop_reason'] = 'pressure gate before ' + case.name
succeeded = False
break
exe = executables[label]
command = [str(WINE), '--bottle', str(private), '--no-update', '--no-gui',
'--workdir', str(case), str(exe), *argv]
result = run_case(command, exe, label, argv != ['watch'], case, env, max_level)
after = pressure(env, root, max_level)
item.update(run=result, pressure_after=after)
save()
succeeded &= result['exit'] == 0 and 'error' not in result
if result.get('interrupted') or not after['allowed']:
receipt['stop_reason'] = 'interruption or pressure gate after ' + case.name
succeeded = False
break
finally:
if private.is_dir():
stop_env = env | {'WINEPREFIX': str(private), 'CX_BOTTLE_PATH': str(private)}
receipt['commands']['private_wineserver_stop'] = capture(
[CROSSOVER / 'bin/wineserver', '-k'], stop_env, root, 10)
shutil.rmtree(private)
receipt['bottle_unchanged'] = sha(config) == receipt['bottle_input_sha256']
save()
return 0 if succeeded else 1
if __name__ == '__main__':
raise SystemExit(main())
@@ -0,0 +1,120 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Match task-only Metal intervals to exact synthetic guest samples."""
import argparse
from collections import defaultdict
import json
from pathlib import Path
from statistics import median
import xml.etree.ElementTree as ET
def table(path, pid):
root = ET.parse(path)
elements = {e.attrib['id']: e for e in root.iter() if 'id' in e.attrib}
schema = [col.findtext('mnemonic') for col in root.findall('.//schema/col')]
def resolve(element):
if 'ref' in element.attrib:
return elements[element.attrib['ref']]
return element
rows = []
for raw in root.findall('.//row'):
row = dict(zip(schema, map(resolve, raw), strict=True))
process = row['process'].find('pid')
if process is None or resolve(process).text != str(pid):
continue
rows.append({k: e.text or e.get('fmt') for k, e in row.items()})
return rows
def key(row):
return [int(row['cmdbuffer-id']), int(row['encoder-id'])]
def summarize(run, gpu_path, encoding_path):
receipt = json.loads((run / 'receipt.json').read_text())
case, = receipt['cases']
outcome = case['run']
if outcome['exit'] != 0 or not outcome['backend']['verified']:
raise ValueError('successful guest and verified backend required')
pid = int(outcome['backend']['guest_pid'])
stdout = run / case['directory'] / 'stdout.txt'
compute = False
guest = []
omitted = 0
for line in stdout.read_text().splitlines():
name, _, fields = line.partition(' ')
if name not in ('COMPUTE', 'TRACE_COPY'):
continue
row = dict(x.split('=', 1) for x in fields.split())
actual, expected = map(int, row['matches'].split('/'))
if actual != expected:
raise ValueError('guest output mismatch')
if name == 'COMPUTE':
compute = True
if row['mode'] == 'omitted':
omitted += 1
continue
guest.append(row)
label = 'Compute Command ' if compute else 'Blit Command '
encoders = [r for r in table(encoding_path, pid)
if r['event-type'] == 'Encoding' and r['encoder-label'].startswith(label)]
encoder_keys = {tuple(key(r)) for r in encoders}
# The GPU channel may be named Compute even for a Blit encoder. Identify
# commands by the encoder's type and pair of IDs, irrespective of nesting.
gpu = [r for r in table(gpu_path, pid)
if r['state'] == 'Active' and tuple(key(r)) in encoder_keys]
gpu.sort(key=lambda r: int(r['start']))
encoders.sort(key=lambda r: int(r['start']))
if not len(guest) == len(gpu) == len(encoders) or not guest:
raise ValueError(f'Unmatched sample, GPU or encoder counts: {len(guest)}, {len(gpu)}, {len(encoders)}')
if [key(row) for row in gpu] != [key(row) for row in encoders]:
raise ValueError('Metal command-buffer and encoder sequence disagrees')
if len({tuple(key(row)) for row in gpu}) != len(gpu):
raise ValueError('Duplicate command or encoder pair')
samples = []
grouped = defaultdict(list)
for expected, device, cpu in zip(guest, gpu, encoders, strict=True):
samples.append(dict(mode=expected.get('mode', 'copy'), iter=int(expected['iter']),
workload_payload=int(expected.get('gpu_payload', '0')),
read_bytes=int(expected.get('read_bytes', '0')),
written_bytes=int(expected.get('written_bytes', '0')),
guest_completion_us=float(expected['completion_us']),
ids=key(device), channel=device['channel-name'],
nested_depth=int(device['event-depth']), encoder_label=cpu['encoder-label'],
gpu_start_ns=int(device['start']), gpu_duration_ns=int(device['duration']),
metal_encode_ns=int(cpu['duration']), comparison=expected['matches']))
if samples[-1]['iter'] >= 0:
grouped[samples[-1]['mode']].append(samples[-1])
distributions = {}
for mode, values in grouped.items():
if len(values) != 12:
raise ValueError(f'Incorrect measured sample count for {mode}')
durations = [s['gpu_duration_ns'] / 1000 for s in values]
mid = median(durations)
distributions[mode] = dict(n=len(values), median_gpu_us=mid,
minimum_gpu_us=min(durations), maximum_gpu_us=max(durations),
mad_gpu_us=median(abs(x - mid) for x in durations),
payload_GB_s={field: median(s[field] / s['gpu_duration_ns'] for s in values)
for field in ('workload_payload', 'read_bytes', 'written_bytes')
if values[0][field]})
return dict(guest_pid=pid, case=case['directory'], matched_intervals=len(gpu),
omitted_dispatch_guest_samples=omitted, distributions=distributions,
samples=samples)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('scratch', type=Path)
parser.add_argument('gpu_intervals', type=Path)
parser.add_argument('encoders', type=Path)
args = parser.parse_args()
print(json.dumps(summarize(args.scratch, args.gpu_intervals, args.encoders), indent=2))
if __name__ == '__main__':
main()
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Summarize raw measured iterations without pooling independent sessions."""
import argparse
import json
import statistics
from pathlib import Path
def distribution(values):
if not values:
return None
ordered = sorted(values)
n = len(ordered)
return dict(n=n, min=ordered[0], p10=ordered[(n - 1) // 10],
median=statistics.median(ordered), p90=ordered[((n - 1) * 9 + 9) // 10],
max=ordered[-1], mad=statistics.median(
abs(x - statistics.median(ordered)) for x in ordered))
def summarize(path):
receipt = json.loads((path / 'receipt.json').read_text())
metrics = {}
rows = []
for item in receipt['cases']:
case = item['directory']
run = item.get('run', {})
stdout = path / case / 'stdout.txt'
cases = []
metrics[case] = dict(exit=run.get('exit'), backend=run.get('backend'),
error=run.get('error'), samples=cases)
if not stdout.is_file():
continue
for line in stdout.read_text().splitlines():
name, _, fields = line.partition(' ')
if name not in {'COPY', 'CPU', 'COMPUTE', 'EMPTY'}:
continue
row = dict(field.split('=', 1) for field in fields.split())
if int(row['iter']) < 0:
continue
keys = ('bytes', 'stride', 'dirty', 'full_write', 'full_read', 'omit', 'mode')
identity = (case, name, tuple((k, row[k]) for k in keys if k in row))
rows.append((identity, row))
groups = {}
for identity, row in rows:
groups.setdefault(identity, []).append(row)
for (case, name, group), samples in groups.items():
times = {k: distribution([float(s[k]) for s in samples if float(s[k]) >= 0])
for k in samples[0] if k.endswith('_us')}
rates = {}
for payload, timer, label in [
('bytes', 'write_us', 'cpu_write'), ('bytes', 'read_us', 'cpu_read'),
('gpu_payload', 'gpu_us', 'gpu_copy'), ('read_bytes', 'gpu_us', 'gpu_read_with_output'),
('written_bytes', 'gpu_us', 'gpu_write_with_input'),
('gpu_payload', 'completion_us', 'copy_end_to_end'),
('read_bytes', 'completion_us', 'shader_read_end_to_end'),
('written_bytes', 'completion_us', 'shader_write_end_to_end'),
]:
if payload not in samples[0] or timer not in samples[0]:
continue
if label == 'gpu_copy' and group and dict(group).get('full_read') != '1':
continue
vals = [int(s[payload]) / float(s[timer]) / 1000 for s in samples
if int(s[payload]) > 0 and float(s[timer]) > 0]
if vals:
rates[label] = distribution(vals)
comparisons = [s['matches'].split('/') for s in samples if 'matches' in s]
metrics[case]['samples'].append(dict(kind=name, factors=dict(group), n=len(samples),
exact_iterations=sum(a == b for a, b in comparisons) if comparisons else None,
timestamp_invalid=sum(float(s['gpu_us']) <= 0 for s in samples) if 'gpu_us' in samples[0] else None,
microseconds=times, decimal_GB_s=rates))
return dict(directory=path.name, group=receipt['group'], seed=receipt['seed'],
stop_reason=receipt.get('stop_reason'), cases=metrics)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('run', nargs='+', type=Path)
args = parser.parse_args()
print(json.dumps([summarize(path) for path in args.run], indent=2))
if __name__ == '__main__':
main()
@@ -0,0 +1,240 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <windows.h>
#include <d3d12.h>
#include <immintrin.h>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#include <string>
#include <utility>
template <typename T> class Com {
T* ptr = nullptr;
public:
Com() = default;
~Com() { if (ptr) ptr->Release(); }
Com(const Com&) = delete;
Com& operator=(const Com&) = delete;
Com(Com&& other) noexcept : ptr(std::exchange(other.ptr, nullptr)) {}
Com& operator=(Com&& other) noexcept {
std::swap(ptr, other.ptr);
return *this;
}
T* get() const { return ptr; }
T* operator->() const { return ptr; }
void** out() { return reinterpret_cast<void**>(&ptr); }
};
inline void check(HRESULT hr, const char* name) {
if (SUCCEEDED(hr)) return;
std::fprintf(stderr, "%s hr=%08lx\n", name, static_cast<unsigned long>(hr));
throw std::runtime_error(name);
}
inline long long ticks() {
LARGE_INTEGER value;
QueryPerformanceCounter(&value);
return value.QuadPart;
}
inline double us(long long delta) {
static const double frequency = [] {
LARGE_INTEGER value;
QueryPerformanceFrequency(&value);
return double(value.QuadPart);
}();
return double(delta) * 1e6 / frequency;
}
inline D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags) {
D3D12_RESOURCE_DESC desc{};
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
desc.Width = bytes;
desc.Height = 1;
desc.DepthOrArraySize = 1;
desc.MipLevels = 1;
desc.SampleDesc.Count = 1;
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
desc.Flags = flags;
return desc;
}
enum class Heap { wb, wc, upload, readback, gpu };
inline D3D12_HEAP_PROPERTIES properties(Heap kind) {
D3D12_HEAP_PROPERTIES prop{};
prop.CreationNodeMask = prop.VisibleNodeMask = 1;
switch (kind) {
case Heap::wb:
case Heap::wc:
prop.Type = D3D12_HEAP_TYPE_CUSTOM;
prop.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
prop.CPUPageProperty = kind == Heap::wb
? D3D12_CPU_PAGE_PROPERTY_WRITE_BACK : D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE;
break;
case Heap::upload: prop.Type = D3D12_HEAP_TYPE_UPLOAD; break;
case Heap::readback: prop.Type = D3D12_HEAP_TYPE_READBACK; break;
case Heap::gpu: prop.Type = D3D12_HEAP_TYPE_DEFAULT; break;
}
return prop;
}
struct Device {
HMODULE dll = LoadLibraryW(L"d3d12.dll");
Com<ID3D12Device> device;
Device() {
if (!dll || GetModuleHandleW(L"d3d12_xs.dll"))
throw std::runtime_error("host d3d12.dll or shim gate");
auto create = reinterpret_cast<decltype(&D3D12CreateDevice)>(
reinterpret_cast<void*>(GetProcAddress(dll, "D3D12CreateDevice")));
if (!create) throw std::runtime_error("D3D12CreateDevice symbol");
check(create(nullptr, D3D_FEATURE_LEVEL_11_0, __uuidof(ID3D12Device),
device.out()), "D3D12CreateDevice");
char path[MAX_PATH]{};
GetModuleFileNameA(dll, path, MAX_PATH);
D3D12_FEATURE_DATA_ARCHITECTURE1 arch{};
const HRESULT result = device->CheckFeatureSupport(D3D12_FEATURE_ARCHITECTURE1,
&arch, sizeof(arch));
std::printf("DEVICE dll=%s shim=0 architecture_hr=%08lx uma=%d coherent=%d isolated_mmu=%d\n",
path, static_cast<unsigned long>(result), arch.UMA,
arch.CacheCoherentUMA, arch.IsolatedMMU);
}
Com<ID3D12Heap> heap(Heap kind, UINT64 bytes) {
D3D12_HEAP_DESC desc{};
desc.SizeInBytes = bytes;
desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
desc.Properties = properties(kind);
desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS;
Com<ID3D12Heap> result;
check(device->CreateHeap(&desc, __uuidof(ID3D12Heap), result.out()), "CreateHeap");
return result;
}
};
struct Buffer {
Com<ID3D12Heap> backing;
Com<ID3D12Resource> resource;
void* pointer = nullptr;
Buffer(Device& d, Heap kind, UINT64 bytes, D3D12_RESOURCE_STATES state,
D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) {
const auto desc = buffer_desc(bytes, flags);
if (kind == Heap::wb || kind == Heap::wc) {
const auto alloc = d.device->GetResourceAllocationInfo(0, 1, &desc);
backing = d.heap(kind, alloc.SizeInBytes);
check(d.device->CreatePlacedResource(backing.get(), 0, &desc, state, nullptr,
__uuidof(ID3D12Resource), resource.out()), "CreatePlacedResource");
} else {
const auto prop = properties(kind);
check(d.device->CreateCommittedResource(&prop, D3D12_HEAP_FLAG_NONE, &desc,
state, nullptr, __uuidof(ID3D12Resource), resource.out()),
"CreateCommittedResource");
}
}
~Buffer() { if (pointer) resource->Unmap(0, nullptr); }
uint32_t* map() {
check(resource->Map(0, nullptr, &pointer), "Map");
if (!pointer) throw std::runtime_error("Map returned null");
return static_cast<uint32_t*>(pointer);
}
};
struct Queue {
Com<ID3D12CommandQueue> queue;
Com<ID3D12CommandAllocator> allocator;
Com<ID3D12GraphicsCommandList> list;
Com<ID3D12Fence> fence;
HANDLE event = nullptr;
UINT64 value = 0;
ID3D12Device* device;
explicit Queue(Device& d) : device(d.device.get()) {
D3D12_COMMAND_QUEUE_DESC desc{};
desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
check(device->CreateCommandQueue(&desc, __uuidof(ID3D12CommandQueue), queue.out()), "CreateCommandQueue");
check(device->CreateCommandAllocator(desc.Type, __uuidof(ID3D12CommandAllocator), allocator.out()), "CreateCommandAllocator");
check(device->CreateCommandList(0, desc.Type, allocator.get(), nullptr,
__uuidof(ID3D12GraphicsCommandList), list.out()), "CreateCommandList");
check(list->Close(), "initial Close");
check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), fence.out()), "CreateFence");
event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
if (!event) throw std::runtime_error("CreateEvent");
}
~Queue() { CloseHandle(event); }
void begin() {
check(allocator->Reset(), "allocator Reset");
check(list->Reset(allocator.get(), nullptr), "list Reset");
}
void transition(ID3D12Resource* resource, D3D12_RESOURCE_STATES from,
D3D12_RESOURCE_STATES to) {
D3D12_RESOURCE_BARRIER barrier{};
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
barrier.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, from, to};
list->ResourceBarrier(1, &barrier);
}
void alias(ID3D12Resource* before, ID3D12Resource* after) {
D3D12_RESOURCE_BARRIER barrier{};
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING;
barrier.Aliasing = {before, after};
list->ResourceBarrier(1, &barrier);
}
void close() { check(list->Close(), "Close command list"); }
struct Latency { double execute, signal, wait, total; };
Latency execute(bool submit = true) {
ID3D12CommandList* lists[] = {list.get()};
const auto start = ticks();
if (submit) queue->ExecuteCommandLists(1, lists);
const auto executed = ticks();
// A signal/event failure leaves work in flight. Terminate the disposable
// guest without unwinding resources that may still be referenced.
const HRESULT signal = queue->Signal(fence.get(), ++value);
const auto signalled = ticks();
const HRESULT arm = SUCCEEDED(signal) ? fence->SetEventOnCompletion(value, event) : signal;
const DWORD wait = SUCCEEDED(arm) ? WaitForSingleObject(event, 5000) : WAIT_FAILED;
const auto complete = ticks();
if (wait != WAIT_OBJECT_0 || fence->GetCompletedValue() < value ||
fence->GetCompletedValue() == UINT64_MAX) {
std::fprintf(stderr, "fence failure signal=%08lx arm=%08lx wait=%lu completed=%llu target=%llu\n",
static_cast<unsigned long>(signal), static_cast<unsigned long>(arm),
static_cast<unsigned long>(wait), fence->GetCompletedValue(), value);
std::fflush(nullptr);
ExitProcess(2);
}
check(device->GetDeviceRemovedReason(), "GetDeviceRemovedReason");
return {us(executed - start), us(signalled - executed), us(complete - signalled),
us(complete - start)};
}
};
inline void receipt_pause() {
std::puts("BACKEND_READY");
if (std::getchar() == EOF) throw std::runtime_error("backend receipt handshake");
}
struct Timestamp {
Com<ID3D12QueryHeap> queries;
Buffer output;
UINT64 hz = 0;
const UINT64* data;
Timestamp(Device& d, Queue& q)
: output(d, Heap::readback, 16, D3D12_RESOURCE_STATE_COPY_DEST) {
const D3D12_QUERY_HEAP_DESC desc{D3D12_QUERY_HEAP_TYPE_TIMESTAMP, 2, 0};
check(d.device->CreateQueryHeap(&desc, __uuidof(ID3D12QueryHeap), queries.out()), "timestamp heap");
check(q.queue->GetTimestampFrequency(&hz), "GetTimestampFrequency");
if (!hz) throw std::runtime_error("zero GPU timestamp frequency");
data = reinterpret_cast<const UINT64*>(output.map());
std::printf("TIMESTAMP hertz=%llu\n", hz);
}
void start(Queue& q) { q.list->EndQuery(queries.get(), D3D12_QUERY_TYPE_TIMESTAMP, 0); }
void end(Queue& q) {
q.list->EndQuery(queries.get(), D3D12_QUERY_TYPE_TIMESTAMP, 1);
q.list->ResolveQueryData(queries.get(), D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, output.resource.get(), 0);
}
double elapsed() const {
if (data[1] <= data[0]) return -1;
return double(data[1] - data[0]) * 1e6 / double(hz);
}
};
@@ -0,0 +1,69 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""One Instruments capture attached to the verified synthetic guest."""
import importlib.util
import json
import subprocess
import sys
import time
from pathlib import Path
if len(sys.argv) < 2:
sys.exit('Provide a trace case followed by the run.py options.')
selection = sys.argv.pop(1)
if selection in {'wb', 'wc', 'upload-wb', 'default'}:
workload = ('coherence', [selection])
elif selection.startswith('copy-') and selection[5:] in {'wb', 'wc', 'upload'}:
workload = ('copy', ['trace-copy', selection[5:]])
else:
sys.exit('Select wb, wc, upload-wb, default, copy-wb, copy-wc or copy-upload.')
runner_path = Path(__file__).resolve().with_name('run.py')
spec = importlib.util.spec_from_file_location("b_runner", runner_path)
runner = importlib.util.module_from_spec(spec)
spec.loader.exec_module(runner)
detect = runner.backend
trace = None
args = None
log_file = None
def attach(exe, env, cwd):
global trace, args, log_file
result = detect(exe, env, cwd)
if not result["verified"]:
return result
# Attach only to the verified private guest, before releasing its handshake.
args = ["xcrun", "xctrace", "record", "--template", "Metal System Trace",
"--attach", result["guest_pid"], "--time-limit", "5s",
"--no-prompt", "--output", str(cwd / "gpu.trace")]
log_file = cwd / "xctrace-output.txt"
trace_env = env | {"DEVELOPER_DIR": "/Applications/Xcode.app/Contents/Developer"}
with log_file.open("wb") as log:
trace = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=log,
stderr=subprocess.STDOUT, env=trace_env, cwd=cwd,
start_new_session=True)
deadline = time.monotonic() + 8
while time.monotonic() < deadline and trace.poll() is None:
if b"Ctrl-C" in log_file.read_bytes():
time.sleep(0.3)
break
time.sleep(0.1)
return result
runner.backend = attach
runner.cases_for = lambda group, seed: [workload]
status = 1
try:
status = runner.main()
finally:
if trace:
try:
result_code = trace.wait(30)
except subprocess.TimeoutExpired:
trace.terminate()
result_code = trace.wait(5)
receipt = {"command": args, "exit": result_code, "xcrun_developer_dir":
"/Applications/Xcode.app/Contents/Developer", "log": log_file.name,
"trace_exists": (log_file.parent / "gpu.trace").exists()}
(log_file.parent / "xctrace.json").write_text(json.dumps(receipt, indent=2) + "\n")
if result_code and status == 0:
status = result_code
sys.exit(status)
@@ -0,0 +1,55 @@
# Version-scoped findings
Research issue [#473](https://github.com/MacosPorters/betterxen/issues/473); methodology and limitations are in the [research README](README.md). This is a one-host observation, independent of #464's production implementation. The newly written probe still needs independent source review and reproduction by another contributor.
## Recorded host and runtime
Both sessions used Apple M4; unified RAM 25769803776 bytes (24 GiB); macOS 27.0, build 26A428; CrossOver public 26.3.0, product 26.3.0.39832, build tag cxoffice-26.3.0rc2, timestamp 20260715T103801Z; D3DMetal framework short/build version 3.0, SourceVersion 32047000000000; Rosetta package 1.0.0.0.1788432274; Windows 11 template win11_64 / WineArch win64; native ARM64 GCC 16.2.0 / MinGW-w64 14.0.0_3. The source bottle was copied into a temporary private prefix. ROSETTA_ADVERTISE_AVX=1 and CX_GRAPHICS_BACKEND=d3dmetal were set; timed runs had WINEDEBUG=-all.
Loaded-library inspection in a separate diagnostic confirmed the app's apple_gptk D3D12 DLL, DXGI DLL, D3DMetal framework and Rosetta runtime. The guest reported no d3d12_xs.dll. No timed-run stderr or method-specific D3DMetal log message was emitted. Unsupported calls returned their printed HRESULTs.
## Baseline outcomes
These exact outcomes agreed in both local sessions:
| Experiment | Observation | Evidence scope |
| --- | --- | --- |
| Architecture | UMA=0, CacheCoherentUMA=0, TileBasedRenderer=0, IsolatedMMU=0; ResourceHeapTier=2 | API-reported values, not a description of the Mac's physical topology |
| Existing-memory opens | Address and mapping both 0x80004001 (E_NOTIMPL) | CPU visibility through these heaps not tested because no heap opened |
| CUSTOM heaps | All five WRITE_BACK/WRITE_COMBINE L0 cases 0x00000000; WRITE_BACK/L1 control 0x80070057 (E_INVALIDARG) | Creation only for restricted heap cases; no render/depth texture usage tested |
| Mixed placement | UAV-capable 64 KiB buffer at 0; 64×64 RGBA8 texture at 65536; both alive on one heap | Texture CPU round-trip 4096/4096 words; no GPU texture readback |
| CPU→GPU persistent map | 11223344/A1B2C3D4 then 55AA00FF/F00DBA5E both matched | Fence-separated buffer copies; no Unmap/remap or staging upload |
| GPU→CPU persistent map | C001D00D/9E3779B9 matched at original CPU pointer | GPU copy from UPLOAD, fence, direct CPU read |
| Dirty-page tracking | Return 0; count 2; granularity 4096; offsets 0 and 16384 | Single allocation/reset query; fallback correctness not established |
Hardware execution is local class A evidence within these workloads. Public D3D12 API contracts are class B; internal sharing/copy mechanism and cross-generation behavior are class U. These are not independent acceptance or Xbox compatibility claims.
## Latency observations
Each row has 5/5 warmup matches and 40/40 timed matches. Size increases by 4096× between the two WRITE_BACK cases. Each submission copies just 128 bytes; timings include CPU encoding, fence synchronization and validation.
| Session | Case | Total ms / 40 | Average ms/submit | Exact matches |
| --- | --- | ---: | ---: | ---: |
| Initial | WRITE_BACK/L0 64 KiB | 20.635900 | 0.515898 | 40/40 |
| Initial | WRITE_BACK/L0 256 MiB | 30.937300 | 0.773432 | 40/40 |
| Initial | WRITE_COMBINE/L0 256 MiB | 11.762100 | 0.294052 | 40/40 |
| Initial | UPLOAD 256 MiB | 10.118800 | 0.252970 | 40/40 |
| Shared-runner verification | WRITE_BACK/L0 64 KiB | 11.558300 | 0.288957 | 40/40 |
| Shared-runner verification | WRITE_BACK/L0 256 MiB | 11.961700 | 0.299042 | 40/40 |
| Shared-runner verification | WRITE_COMBINE/L0 256 MiB | 9.973900 | 0.249347 | 40/40 |
| Shared-runner verification | UPLOAD 256 MiB | 8.198200 | 0.204955 | 40/40 |
The two sizes do not show latency proportional to the 4096× size difference in these sessions. This is consistent with shared storage or a sparse-copy mechanism; it does not establish O(1) behavior generally, physical aliasing, or guaranteed zero-copy. The machine was not idle; a background C++ language-service process was observed using about one CPU core before the initial run. Session variation is substantial, and no statistical confidence or performance improvement is claimed.
## Raw records
- [Initial stdout](results/2026-11-26-apple-m4-arths17-initial/stdout.txt), [stderr](results/2026-11-26-apple-m4-arths17-initial/stderr.txt), [receipt](results/2026-11-26-apple-m4-arths17-initial/receipt.json), [backend excerpt and launch notes](results/2026-11-26-apple-m4-arths17-initial/backend-receipt.txt).
- [Shared-runner stdout](results/2026-11-26-apple-m4-arths17-runner/stdout.txt), [stderr](results/2026-11-26-apple-m4-arths17-runner/stderr.txt), [receipt](results/2026-11-26-apple-m4-arths17-runner/receipt.json). This run records the exact published source hash and executed PE hash. The initial executable was not retained/hashed before the diagnostic extension was added; its incomplete receipt is explicitly marked.
## Unresolved work for the collaborators
1. Independently review the probe against public contracts and reproduce the same source revision on another Apple Silicon generation; append independent raw logs and repeated timing sessions.
2. Measure resident/physical memory and internal copy activity in a separately named supplemental experiment. Neither was measured here. A 64 KiB prefault stride does not make every host page resident; do not infer a second 256 MiB allocation from virtual size or these timings.
3. Establish GPU texture coherence/readback, format/layout and render/depth restrictions separately. The current texture check is only a CPU round-trip.
4. Verify lifetime/reuse, dirty-page rearming/reset races and explicit fallback copying where necessary. The baseline only serializes accesses with per-submission fences.
5. Give #464 evidence-scoped recommendations: these runtime versions reject both caller-memory wrapping APIs, while host-allocated custom L0 heaps support the observed buffer access. This does not supply an arbitrary-xmem-to-heap bridge, justify silent fallbacks or permit console flush operations to become no-ops.
@@ -0,0 +1,26 @@
# Direct compute coherence and write-watch
The [B runner](../../copy-detection/README.md) builds this original C++20 guest and runs the original HLSL through the installed d3dcompiler_47 DLL with `main`, `cs_5_0` and requests optimization level 3. The tested compiler emits a diagnostic that it ignores flag 0x8000. The runner records compiler/module identity and DXBC hashes. It retains stdout/stderr, pipeline and device errors, the exact HLSL and every comparison.
## Correctness and throughput
The shader consumes a CPU-written dataset through a raw root SRV and writes a raw root UAV. WB and WC trials keep each pointer mapped through dataset changes and fence-separated GPU output reads. An UPLOAD-to-WB trial and a fully staged DEFAULT-to-DEFAULT trial provide controls. DEFAULT staging and poison copies finish before the measured dispatch. Any output staging copy is ordered by a UAV-to-COPY_SOURCE transition and sits outside the GPU timestamp pair.
For a result slot `i`, the CPU independently enumerates the conceptual input word indices, regenerates input values from the seed, performs a widened sum and reduces it modulo 2^32. GPU arithmetic is unsigned 32-bit. Sample extremes, mismatch positions and exact match counts are retained. Poisoning each prior output detects stale data. The omitted dispatch control compares against the poison so the predicted negative behavior is explicit. The separate frozen historical shader probe uses an intentionally failing omitted-dispatch oracle.
The four configurations use identical dispatch shapes, but staging and command encoding differ between direct and DEFAULT output. Compare useful GPU payload rates using the GPU timestamp interval. Submission/fence timings include each configuration's actual transfer and barrier commands.
| Workload | Input reads | Output writes |
| --- | --- | --- |
| Both | Every word in 4 MiB | Every result word in 4 MiB |
| Full read | Every word in 4 MiB | 256 KiB of dependent output |
| Sparse 4 KiB | One word per 4 KiB of 4 MiB | 4 KiB of dependent output |
| Sparse 16 KiB | One word per 16 KiB of 4 MiB | 1 KiB of dependent output |
| Write | Zero input loads by uniform zero iteration count | Every result word in 4 MiB |
| Omitted | Zero | Zero, and CPU verifies unchanged poison |
The read workloads include shader indexing, accumulation and an observable output. Rates apply to those workloads and do not measure isolated memory-pin bandwidth or hardware counters for physical transactions.
## Write tracking
A CPU-only guest tests a fresh allocation, one subpage, nonresetting queries, adjacent 4 KiB writes, both sides of a 16 KiB boundary, automatic and separate reset, rearming, read-only and same-value store. A separate D3D12 process attempts to wrap the actual watch-enabled region and reports capability and exact HRESULT. GPU tracking remains untested if the region cannot be imported. The fixture does not apply GetWriteWatch to a foreign pointer. [Tracking and synchronization contract](../contracts/synchronization-mapping-tracking.md).
@@ -0,0 +1,21 @@
// SPDX-License-Identifier: GPL-3.0-or-later
ByteAddressBuffer source : register(t0);
RWByteAddressBuffer target : register(u0);
cbuffer Params : register(b0) {
uint outputs;
uint strideWords;
uint readsPerOutput;
uint seed;
};
[numthreads(64, 1, 1)]
void main(uint index : SV_DispatchThreadID) {
if (index >= outputs)
return;
uint result = seed + index * 37u;
// At stride one the wave reads consecutive words for each iteration.
for (uint n = 0; n < readsPerOutput; ++n)
result += source.Load(4u * strideWords * (index + n * outputs));
target.Store(4u * index, result ^ 0xa5c35a3cu);
}
@@ -0,0 +1,267 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "../../copy-detection/support.h"
#include <d3dcompiler.h>
#include <algorithm>
#include <array>
#include <vector>
constexpr UINT capacity = 4 * 1024 * 1024;
constexpr UINT words = capacity / 4;
constexpr UINT poison = 0x6ba8fa03u;
static void watch() {
constexpr UINT size = 65536;
auto* ptr = static_cast<unsigned char*>(VirtualAlloc(nullptr, size,
MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE));
if (!ptr) throw std::runtime_error("VirtualAlloc MEM_WRITE_WATCH");
SYSTEM_INFO system{};
GetSystemInfo(&system);
std::printf("WATCH guest_page=%lu allocation_granularity=%lu cpu_mod16k=%llu\n",
system.dwPageSize, system.dwAllocationGranularity,
UINT64(reinterpret_cast<uintptr_t>(ptr) % 16384));
bool exact = true;
auto expect = [&](const char* label, DWORD flags, const std::vector<UINT>& expected) {
std::array<void*, 64> addresses{};
ULONG_PTR count = addresses.size();
DWORD granularity = 0;
const UINT status = GetWriteWatch(flags, ptr, size, addresses.data(), &count, &granularity);
std::vector<UINT> actual;
if (!status && count <= addresses.size())
for (ULONG_PTR i = 0; i < count; ++i)
actual.push_back(UINT(static_cast<unsigned char*>(addresses[i]) - ptr));
std::sort(actual.begin(), actual.end());
std::printf("WATCH phase=%s rc=%u granularity=%lu count=%llu actual=",
label, status, granularity, UINT64(count));
for (const auto offset : actual) std::printf("%u,", offset);
std::printf(" expected=");
for (const auto offset : expected) std::printf("%u,", offset);
std::puts("");
if (status || count > addresses.size() || granularity != 4096 || actual != expected)
exact = false;
};
auto* mapped = static_cast<volatile unsigned char*>(ptr);
expect("fresh", 0, {});
mapped[4096] = 1;
expect("only_second_guest_page", 0, {4096});
expect("query_without_reset", 0, {4096});
mapped[8192] = 2;
expect("second_and_third", WRITE_WATCH_FLAG_RESET, {4096, 8192});
expect("after_query_reset", 0, {});
mapped[4096] = 3;
expect("same_page_rearmed", WRITE_WATCH_FLAG_RESET, {4096});
mapped[16383] = 4;
mapped[16384] = 5;
expect("host_boundary", 0, {12288, 16384});
const UINT reset = ResetWriteWatch(ptr, size);
std::printf("WATCH ResetWriteWatch rc=%u\n", reset);
if (reset) throw std::runtime_error("ResetWriteWatch");
expect("after_explicit_reset", 0, {});
const auto read = mapped[16384];
std::printf("WATCH read_only value=%u\n", UINT(read));
expect("after_read_only", 0, {});
mapped[16384] = 5;
expect("same_value_store_after_reset", WRITE_WATCH_FLAG_RESET, {16384});
expect("final_empty", 0, {});
if (!VirtualFree(ptr, 0, MEM_RELEASE)) throw std::runtime_error("VirtualFree");
if (!exact) throw std::runtime_error("watch page oracle");
}
static void wrap_watch(Device& d) {
constexpr UINT size = 65536;
Com<ID3D12Device3> dev;
check(d.device->QueryInterface(__uuidof(ID3D12Device3), dev.out()), "ID3D12Device3");
void* pointer = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE);
if (!pointer) throw std::runtime_error("VirtualAlloc wrapper control");
HRESULT hr;
{
Com<ID3D12Heap> heap;
hr = dev->OpenExistingHeapFromAddress(pointer, __uuidof(ID3D12Heap), heap.out());
std::printf("WATCH_WRAP hr=%08lx object=%d gpu_writes=NOT_RUN\n",
static_cast<unsigned long>(hr), heap.get() != nullptr);
}
if (!VirtualFree(pointer, 0, MEM_RELEASE)) throw std::runtime_error("VirtualFree");
if (SUCCEEDED(hr)) throw std::runtime_error("wrapper available; GPU tracking remains untested");
}
struct Pipeline {
Com<ID3D12RootSignature> root;
Com<ID3D12PipelineState> pso;
explicit Pipeline(Device& d) {
auto* compiler = LoadLibraryW(L"d3dcompiler_47.dll");
if (!compiler) throw std::runtime_error("D3DCompiler 47");
char path[MAX_PATH]{};
GetModuleFileNameA(compiler, path, MAX_PATH);
std::printf("SHADER compiler=%s profile=cs_5_0 flags=O3\n", path);
FILE* file = std::fopen("access.hlsl", "rb");
if (!file) throw std::runtime_error("open HLSL");
std::array<char, 8192> hlsl{};
const size_t length = std::fread(hlsl.data(), 1, hlsl.size(), file);
std::fclose(file);
if (!length || length == hlsl.size()) throw std::runtime_error("HLSL length");
auto compile = reinterpret_cast<decltype(&D3DCompile)>(
reinterpret_cast<void*>(GetProcAddress(compiler, "D3DCompile")));
auto serialize = reinterpret_cast<decltype(&D3D12SerializeRootSignature)>(
reinterpret_cast<void*>(GetProcAddress(d.dll, "D3D12SerializeRootSignature")));
if (!compile || !serialize) throw std::runtime_error("shader tool symbols");
Com<ID3DBlob> shader, errors;
const auto hr = compile(hlsl.data(), length, "access.hlsl", nullptr, nullptr,
"main", "cs_5_0", D3DCOMPILE_OPTIMIZATION_LEVEL3, 0,
reinterpret_cast<ID3DBlob**>(shader.out()),
reinterpret_cast<ID3DBlob**>(errors.out()));
if (errors.get()) std::fwrite(errors->GetBufferPointer(), 1, errors->GetBufferSize(), stderr);
check(hr, "D3DCompile");
file = std::fopen("access.dxbc", "wb");
if (!file) throw std::runtime_error("open shader receipt");
const size_t written = std::fwrite(shader->GetBufferPointer(), 1, shader->GetBufferSize(), file);
if (std::fclose(file) || written != shader->GetBufferSize())
throw std::runtime_error("write shader receipt");
D3D12_ROOT_PARAMETER params[3]{};
params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV;
params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
params[2].Constants.Num32BitValues = 4;
D3D12_ROOT_SIGNATURE_DESC signature{3, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
Com<ID3DBlob> blob, root_errors;
check(serialize(&signature, D3D_ROOT_SIGNATURE_VERSION_1,
reinterpret_cast<ID3DBlob**>(blob.out()),
reinterpret_cast<ID3DBlob**>(root_errors.out())), "serialize root");
check(d.device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(),
__uuidof(ID3D12RootSignature), root.out()), "root signature");
D3D12_COMPUTE_PIPELINE_STATE_DESC desc{};
desc.pRootSignature = root.get();
desc.CS = {shader->GetBufferPointer(), shader->GetBufferSize()};
check(d.device->CreateComputePipelineState(&desc, __uuidof(ID3D12PipelineState), pso.out()),
"compute PSO");
}
};
static uint32_t input_word(UINT index, UINT seed) {
return (index ^ (seed * 0x01010301u)) + index * 17u;
}
static void compute(Device& d, Heap input_kind, Heap output_kind) {
using State = D3D12_RESOURCE_STATES;
constexpr State common = D3D12_RESOURCE_STATE_COMMON;
constexpr State generic = D3D12_RESOURCE_STATE_GENERIC_READ;
constexpr State uav = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
constexpr State copy_dest = D3D12_RESOURCE_STATE_COPY_DEST;
constexpr State copy_src = D3D12_RESOURCE_STATE_COPY_SOURCE;
Buffer source(d, input_kind, capacity, input_kind == Heap::upload ? generic : common);
Buffer target(d, output_kind, capacity, common, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
Buffer readback(d, Heap::readback, capacity, copy_dest);
Buffer stage(d, Heap::upload, capacity, generic);
const bool direct_output = output_kind != Heap::gpu;
auto* cpu_source = input_kind == Heap::gpu ? stage.map() : source.map();
auto* cpu_result = direct_output ? target.map() : readback.map();
auto* stage_data = input_kind == Heap::gpu ? cpu_source : stage.map();
Pipeline shader(d);
Queue q(d);
Timestamp timing(d, q);
struct Work { const char* name; UINT outputs, stride, reads; bool omit; };
for (const auto work : {Work{"both", words, 1, 1, false},
Work{"full_read", words / 16, 1, 16, false},
Work{"sparse_read_4k", words / 1024, 1024, 1, false},
Work{"sparse_read_16k", words / 4096, 4096, 1, false},
Work{"write", words, 1, 0, false},
Work{"omitted", words, 1, 1, true}}) {
for (int iteration = -3; iteration < 12; ++iteration) {
const UINT seed = 407 + UINT(iteration + 3) * 13u;
for (UINT j = 0; j < words; ++j) cpu_source[j] = input_word(j, seed);
if (direct_output) std::fill_n(cpu_result, work.outputs, poison);
_mm_sfence();
// DEFAULT controls stage data and poison in a separate, fenced list.
if (input_kind == Heap::gpu) {
q.begin();
q.list->CopyBufferRegion(source.resource.get(), 0, stage.resource.get(), 0, capacity);
q.close();
q.execute();
}
if (!direct_output) {
std::fill_n(stage_data, work.outputs, poison);
_mm_sfence();
q.begin();
q.list->CopyBufferRegion(target.resource.get(), 0, stage.resource.get(), 0,
work.outputs * 4u);
q.close();
q.execute();
}
const auto start = ticks();
q.begin();
q.transition(target.resource.get(), common, uav);
q.list->SetPipelineState(shader.pso.get());
q.list->SetComputeRootSignature(shader.root.get());
q.list->SetComputeRootShaderResourceView(0, source.resource->GetGPUVirtualAddress());
q.list->SetComputeRootUnorderedAccessView(1, target.resource->GetGPUVirtualAddress());
const UINT constants[] = {work.outputs, work.stride, work.reads, seed};
q.list->SetComputeRoot32BitConstants(2, 4, constants, 0);
timing.start(q);
if (!work.omit) q.list->Dispatch((work.outputs + 63) / 64, 1, 1);
timing.end(q);
if (!direct_output) {
q.transition(target.resource.get(), uav, copy_src);
q.list->CopyBufferRegion(readback.resource.get(), 0, target.resource.get(), 0,
work.outputs * 4u);
q.transition(target.resource.get(), copy_src, common);
} else {
q.transition(target.resource.get(), uav, common);
}
q.close();
const auto encoded = ticks();
const auto latency = q.execute();
UINT matches = 0;
uint32_t first_expected = 0, last_expected = 0;
for (UINT j = 0; j < work.outputs; ++j) {
// Reconstruct the conceptual indices and input values without
// consulting either mapped buffer. Use a widened sum and reduce
// modulo 2^32 once to model unsigned shader overflow.
uint64_t sum = uint64_t(j) * 37 + seed;
for (UINT n = 0; n < work.reads; ++n)
sum += input_word(work.stride * (j + n * work.outputs), seed);
const uint32_t expected = work.omit ? poison : uint32_t(sum) ^ 0xa5c35a3cu;
if (!j) first_expected = expected;
if (j == work.outputs - 1) last_expected = expected;
if (matches == j && cpu_result[j] != expected)
std::printf("MISMATCH index=%u actual=%08x expected=%08x\n", j, cpu_result[j], expected);
matches += cpu_result[j] == expected;
}
std::printf("COMPUTE mode=%s iter=%d seed=%u direct_out=%d read_bytes=%u written_bytes=%u "
"gpu_tick_begin=%llu gpu_tick_end=%llu encode_us=%.3f execute_us=%.3f signal_us=%.3f wait_us=%.3f completion_us=%.3f gpu_us=%.3f "
"expected=%08x,%08x actual=%08x,%08x matches=%u/%u\n",
work.name, iteration, seed, direct_output,
work.omit ? 0 : work.outputs * work.reads * 4u,
work.omit ? 0 : work.outputs * 4u, timing.data[0], timing.data[1], us(encoded - start),
latency.execute, latency.signal, latency.wait, latency.total, timing.elapsed(),
first_expected, last_expected, cpu_result[0], cpu_result[work.outputs - 1],
matches, work.outputs);
if (matches != work.outputs) throw std::runtime_error("compute or poison oracle");
}
}
}
int main(int argc, char** argv) {
setvbuf(stdout, nullptr, _IONBF, 0);
try {
if (argc != 2) throw std::runtime_error("usage: probe watch|wrap-watch|wb|wc|upload-wb|default");
const std::string mode = argv[1];
if (mode == "watch") {
watch();
} else {
Device device;
receipt_pause();
if (mode == "wrap-watch") wrap_watch(device);
else if (mode == "wb") compute(device, Heap::wb, Heap::wb);
else if (mode == "wc") compute(device, Heap::wc, Heap::wc);
else if (mode == "upload-wb") compute(device, Heap::upload, Heap::wb);
else if (mode == "default") compute(device, Heap::gpu, Heap::gpu);
else throw std::runtime_error("unknown mode");
}
std::puts("END complete");
return 0;
} catch (const std::exception& e) {
std::fprintf(stderr, "END failure: %s\n", e.what());
return 1;
}
}
@@ -0,0 +1,35 @@
# Resource, placement and lifetime contract
Workstream A's public-contract derivation for [#473](https://github.com/MacosPorters/betterxen/issues/473), read 2026-11-26. Class B describes API contracts, not console semantics or implementation certification. B's independent synchronization review is requested and pending. A-local helper code is isolated; it is not an agreed replacement for shared helpers.
## Ownership and addressing
[CreatePlacedResource](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource) takes a heap-relative offset, with resource allocation alignment and bounds. It accepts no requested CPU virtual address. [GetResourceAllocationInfo](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-getresourceallocationinfo%28uint_uint_constd3d12_resource_desc%29) gives adapter/resource allocation size and alignment; these are not CPU Map-pointer guarantees. Ordinary buffers round their allocation size to 64 KiB; texture requirements depend on the adapter.
[Map](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-map) supports persistent mapping until the resource's final reference is released. It does not promise normal pointer capabilities or a fixed address across unnested maps. The allocation owner must retain the resource and heap for any live guest pointer; callers cannot free or decommit an interior mapped pointer using ordinary VirtualFree. A 64 KiB heap offset and a 64 KiB-aligned CPU pointer are different conditions.
## Placement, aliases and initialization
For a simple alias model, activate the resource with an aliasing barrier, invalidate overlapping resources and initialize render/depth resources after activation. Full clear or full-subresource copies satisfy the required initialization. An alias switch has no implicit data-inheritance assumption. A's texture alias fixture uses two render/depth resources at the same heap offset in one command list, clears each after its own activation and reads each before the next activation. Disjoint buffer/texture cases retain and verify a separate buffer guard.
The API also has an advanced model: an ExecuteCommandLists boundary can provide alias-ordering guarantees between separate invocations. This does not excuse concurrent overlapping access or eliminate required texture initialization. A's fixtures explicitly issue aliasing barriers to keep their intended use inspectable. [CreatePlacedResource remarks](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource).
## Retirement and synchronization handoff
CPU writes finish before GPU submission. CPU reads, overwrites, destruction and allocator reuse occur only after completion of the last queue fence using that range. A's allocation trace holds a real queued copy behind a short CPU-signaled gate, observes its retirement value still pending, withholds the allocation, releases the gate and waits with a timeout before validating/releasing. This tests the fixture's delayed-retirement policy; it does not exhaust every multi-queue lifetime case. No unsafe free or data race is deliberately executed.
[CreateHeap](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createheap) requires the GPU to stop using the heap before its final reference is released; placed resources hold heap references. Process-accounted memory after resource release alone cannot distinguish application references, runtime caches and driver retention. The corrected accounting fixture records resource release, disposal of all command objects/output/pipeline, a settled retirement checkpoint and device release separately. A high remaining footprint is not by itself a leak.
B owns common mapping/synchronization/tracking contracts and implementation. Review requested: CPU store completion, transition states, fence error paths, alias activation, reset/retirement ordering and queue-gate cleanup. A owns resource lifetime scenarios and observed accounting, not general CPU/GPU atomic interoperability. No concurrent CPU/GPU polling test is included.
## Texture copies and storage
[GetCopyableFootprints](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-getcopyablefootprints) returns copy-buffer offsets, padded row pitches and unpadded row bytes. These describe transfer layouts, not opaque texture backing. Fixtures test offsets in 512-byte units, row pitches in 256-byte units and exact pixel bytes without interpreting padding as texels. CPU texture writes occur in COMMON; GPU reads use COPY_SOURCE and readback buffers stay COPY_DEST.
[Texture layouts](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_texture_layout) distinguish UNKNOWN from restricted cross-adapter ROW_MAJOR. Ordinary opaque textures do not expose a conventional texel pointer through Map; requesting a null output pointer is not an experiment proving pointer-return failure. The historical valid ROW_MAJOR control uses a shared cross-adapter DEFAULT heap and ALLOW_CROSS_ADAPTER, one mip/slice, no depth/MSAA. Ordinary UPLOAD/READBACK textures are excluded by the [heap-type contract](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_heap_type).
Apple's [storage-mode documentation](https://developer.apple.com/documentation/metal/choosing-a-resource-storage-mode-for-apple-gpus) distinguishes CPU/GPU-accessible shared resources from GPU-only private resources even on unified-memory hardware. That is a Metal contract; it does not establish which Metal mode an opaque D3DMetal D3D12 heap uses. DEFAULT versus CUSTOM is a D3D12 test comparison, not a measurement of the underlying Metal storage mode.
## Buffer data inheritance scope
The separate buffer fixture uses overlapping placed buffers with fully defined ROW_MAJOR layouts and compatible buffer states, an explicit alias barrier between each GPU write/read use, and full source initialization. It alternates the writer and verifies inherited data plus a disjoint guard. The expectation is derived from [Memory Aliasing and Data Inheritance](https://learn.microsoft.com/en-us/windows/win32/direct3d12/memory-aliasing-and-data-inheritance), rather than from the simple model's no-inheritance assumption. Its passing observations remain subject to B's independent source/contract review.
@@ -0,0 +1,33 @@
# Synchronization, mapping and write tracking
Workstream B contract review for [#473](https://github.com/MacosPorters/betterxen/issues/473) and [#464](https://github.com/MacosPorters/betterxen/issues/464). Public D3D12 and Windows contracts are class B. The [probe and result guide](../../copy-detection/README.md) records version-scoped local observations and the status of reciprocal review.
## Ordering and lifetime
- Finish CPU stores before the GPU submission that can read them. For this x86-64 guest, the fixtures order the stores before submission with an SFENCE. The caller owns ordering between CPU producer threads and the thread that submits. For CPU reads of GPU-written data, wait for the fence value signaled on the consuming or writing queue. Treat a failed wait, timeout or device-removed fence as a failed run. [Map contract](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-map).
- On one queue, place the fence signal after the relevant execution. A CPU-side fence signal cannot establish GPU completion. Across queues, signal the producing queue and wait on the consuming queue before dependent commands. Keep the queue-specific resource state requirements and use one progress timeline per fence where possible. [Multi-engine synchronization](https://learn.microsoft.com/en-us/windows/win32/direct3d12/user-mode-heap-synchronization).
- Persistent mapping of CPU-accessible resources is supported. Keep the resource alive as long as the pointer is used and retire commands before reclaiming memory or overwriting ranges still in use. Map and Unmap ranges convey CPU access information for tools. Persistent access does not wait for the GPU, guarantee a stable pointer across resource destruction, or imply concurrent CPU/GPU atomic interoperability. Use Map with a null output for CPU subresource access to opaque textures where the API supports it. [Map](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-map), [WriteToSubresource](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-writetosubresource).
- Complete outstanding GPU use before releasing heaps, resources, descriptors, command allocators or mapped storage they reference. For reusing an overlapping span, retire the last use and apply the aliasing rules for the new resource. For GPU-queued reuse without a CPU wait, enforce the dependency on the participating queues. [Resource barriers](https://learn.microsoft.com/en-us/windows/win32/direct3d12/using-resource-barriers-to-synchronize-resource-states-in-direct3d-12), [placed-resource usage](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource).
## States and aliases used in this research
| Operation | Contract used |
| --- | --- |
| Buffer copied from or read as a shader resource | Use COPY_SOURCE or NON_PIXEL_SHADER_RESOURCE. COMMON buffers may promote implicitly to these read states. Implicitly promoted buffers decay at completed ExecuteCommandLists operation boundaries. STANDARD UPLOAD remains GENERIC_READ, which includes these states. |
| GPU copy into readback | READBACK stays COPY_DEST. Map may remain live and CPU consumes bytes after the fence. |
| Shader UAV output | Transition to UNORDERED_ACCESS before the dispatch. Transition from UAV to COPY_SOURCE before a dependent readback copy, or restore COMMON for the next submission. When dependent UAV accesses remain in UAV state, order them with a UAV barrier. |
| Mixed placed buffer and texture | Use heap tier and flags appropriate to both resources. Use allocation-info alignment and size for the heap span. Use copyable footprints for buffer offsets and row pitches, and apply states per resource or subresource as needed. |
| Overlapping render/depth textures | Activate the new alias at the execution boundary or via the appropriate alias barrier. In the simple model, initialize each RT/DS resource after activation using an allowed clear, discard or full subresource copy before other uses. |
| Buffer alias inheritance | The advanced model permits inheritance in documented compatible overlapping layouts. Establish ordering with an alias barrier inside one Execute operation or with the documented separate Execute operation boundary. Verify distinct guard data and do not extrapolate across layouts. |
[Resource state promotion, decay and barrier rules](https://learn.microsoft.com/en-us/windows/win32/direct3d12/using-resource-barriers-to-synchronize-resource-states-in-direct3d-12), [aliasing and data inheritance](https://learn.microsoft.com/en-us/windows/win32/direct3d12/memory-aliasing-and-data-inheritance), [placed-resource lifetime and initialization](resource-placement-lifetime.md).
D3D12 placement alignment constrains a heap-relative byte offset. Validate candidate offsets and spans before creation with checks equivalent to `offset % alignment == 0`, `offset <= heap_size` and `allocation_size <= heap_size - offset`. A CPU virtual pointer has its own alignment. Biasing a CPU pointer within a mapped buffer can align that pointer, but a separately placed resource at the matching biased heap offset may violate placement requirements. A constant whole-heap offset on a 64 KiB grid cannot change the mapped base's remainder. [CreatePlacedResource](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource).
## Write tracking
GetWriteWatch and ResetWriteWatch require a region reserved with VirtualAlloc and MEM_WRITE_WATCH. Use returned granularity and address offsets, and track application ownership of each dirty range. To use these pages as the source of an explicit selective copy, quiesce writers or establish coherent per-range ownership over collection, reset, snapshot/copy, and reuse. A separate GetWriteWatch followed by ResetWriteWatch can drop writes in the middle. Combining collection and reset still leaves races with data copying when writers can modify the same bytes concurrently. Retry paths must retain or conservatively restore dirty coverage. [GetWriteWatch](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-getwritewatch), [ResetWriteWatch](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-resetwritewatch).
A 4 KiB guest report can distinguish stores within a 16 KiB host page. That observation describes the Windows API on the tested Wine version. It does not establish the tracking implementation's physical granularity. A D3D12 Map address has no demonstrated MEM_WRITE_WATCH allocation contract. GPU stores remain untracked unless an independently validated mechanism is available. IsolatedMMU TRUE states a GPU guarantee regarding CPU page-table properties, with documented granularity and false-positive caveats. FALSE supplies no guarantee and cannot establish a universal absence of GPU-related dirty reports. Application-managed flags or shader instrumentation can cover known writers and ranges. Arbitrary GPU writes require a separate supported mechanism or conservative copies. [Architecture1](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_feature_data_architecture1).
Apple's public Metal shared resource contract governs applications that create resources with that storage mode and coordinate access. It cannot identify an opaque D3D12 translation's storage or exclude internal copies. [Metal shared storage](https://developer.apple.com/documentation/metal/mtlstoragemode/shared).
@@ -0,0 +1,15 @@
# Texture and placed-resource fixtures
Workstream A extends the frozen baseline and preserved M4 supplemental texture check for [#473](https://github.com/MacosPorters/betterxen/issues/473). [The inventory](../../allocation-profiling/inventory/README.md) records the already tested 65x37 RGBA8 one-mip UNKNOWN and valid ROW_MAJOR cross-adapter controls; their identical experiments are not newly commissioned here. [Resource/lifetime notes](../contracts/resource-placement-lifetime.md) derive expected behavior from primary D3D12 documentation. Independent review is pending.
Run `../../allocation-profiling/run.py --suite texture` with the documented `--bottle` and a fresh external `--scratch` directory. It compiles this original `probe.cpp`, performs two fresh-process sessions with different datasets, and archives raw results, exact source/PE hashes, commands, backend evidence and failures. `--smoke` performs one session. No shader is needed by these copy/clear cases, so shader hashes are not applicable.
New cases use 65x37 textures with three mip levels in RGBA8, R8_UNORM and R32_UINT, on CUSTOM/WB/L0, CUSTOM/WC/L0 and DEFAULT heaps. Each texture coexists with a disjoint 64 KiB buffer on the same Tier-2 heap. Every buffer guard word and every actual mip texel byte is compared after GPU readback. CPU-visible textures use per-subresource Map with a null output pointer and WriteToSubresource in COMMON. DEFAULT textures are initialized through a footprint-pitched UPLOAD buffer. Copy footprints use a nonzero 512-byte base offset, padded row pitches and separately checked unpadded row sizes. These transfer layouts do not reveal opaque texture storage.
Separate RGBA8 render-target and D32_FLOAT depth cases place two resources at the same heap offset on WB and DEFAULT heaps. Within one command list, activate A, clear/initialize it, copy it out, then activate B with an A-to-B aliasing barrier, clear B and copy it out. Exact endpoint colors (0/1) and exactly representable depth values (0.5/0.25) have fixed expected bits. No previous alias contents are assumed. This tests clear/copy/alias behavior, not rasterized depth testing, stencil or sampled filtering.
Negative creation checks ask for misaligned and out-of-bounds buffer placements and a texture on a buffer-only heap. An unexpected success is a recorded runtime-contract discrepancy, never permission to use that invalid resource. Unsupported creation/CPU-access paths print exact HRESULT and explicit not-run status; exit 0 alone does not mean every configuration worked. Read each outcome.
Sampling, render pipelines, MSAA, compressed/planar formats, arrays/3D, stencil, texture reinterpretation and console tiling are not covered by these fixtures. They remain explicit gaps, and are not inferred from successful copies or clears. In particular, neither a null ppData request nor readback agreement establishes that raw xmem pointers alias texture pixels. DEFAULT versus CUSTOM cases do not identify D3DMetal's internal Metal storage mode or measure its bandwidth.
The follow-up alias.cpp (run with --suite alias) tests valid buffer data inheritance under the advanced model, with two overlapping buffers and a disjoint guard, three changing GPU-write rounds per session and no raw CPU alias dereference used as a GPU oracle. Exact Map-pointer/GPU-VA relations are recorded as observations. See [findings](findings.md) for the distinction between the passing positive readbacks and failed negative-rejection gate.
@@ -0,0 +1,127 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Buffer data inheritance under the D3D12 advanced aliasing model; GPU copies
// only.
#include "../../allocation-profiling/support.h"
static void activate(Queue &q, ID3D12Resource *before, ID3D12Resource *after) {
D3D12_RESOURCE_BARRIER b{};
b.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING;
b.Aliasing.pResourceBefore = before;
b.Aliasing.pResourceAfter = after;
q.list->ResourceBarrier(1, &b);
}
static void stage(const char *name) {
std::printf("STAGE %s cpu_ptr=0\n", name);
if (std::getchar() == EOF)
throw std::runtime_error("handshake");
}
int main(int argc, char **argv) {
setvbuf(stdout, nullptr, _IONBF, 0);
try {
if (argc != 2)
throw std::runtime_error("usage: alias SESSION");
UINT session = UINT(std::strtoul(argv[1], nullptr, 10));
Context c;
stage("baseline");
Ref<ID3D12Heap> heap;
D3D12_HEAP_DESC hd{};
hd.SizeInBytes = 131072;
hd.Alignment = 65536;
hd.Properties = properties(D3D12_HEAP_TYPE_CUSTOM);
hd.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
hd.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
hd.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS;
require(c.device->CreateHeap(&hd, __uuidof(ID3D12Heap), heap.out()),
"alias heap");
Ref<ID3D12Resource> placed[3];
auto desc = bufferDesc(65536);
for (int i = 0; i < 3; ++i) {
UINT64 offset = i == 2 ? 65536 : 0;
require(c.device->CreatePlacedResource(
heap.p, offset, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
__uuidof(ID3D12Resource), placed[i].out()),
"alias placed buffer");
void *pointer = nullptr;
require(placed[i]->Map(0, nullptr, &pointer),
"alias Map pointer receipt");
std::printf(
"ALIAS_RESOURCE index=%d heap_offset=%llu cpu_ptr=%p gpu_va=%llu\n",
i, offset, pointer, placed[i]->GetGPUVirtualAddress());
}
Buffer source, guardSource, read;
source.allocate(c.device.p, 65536, "upload");
source.map();
guardSource.allocate(c.device.p, 65536, "upload");
guardSource.map();
read.allocate(c.device.p, 3 * 65536, "readback");
read.map();
Queue q(c.device.p);
UINT discrepancies = 0;
for (UINT round = 0; round < 3; ++round) {
UINT salt = 0x13579BDFu + session * 0x10000u + round * 0x101u;
auto u = static_cast<volatile uint32_t *>(source.cpu);
auto g = static_cast<volatile uint32_t *>(guardSource.cpu);
for (UINT i = 0; i < 16384; ++i) {
u[i] = i * 1664525u + salt;
g[i] = i ^ 0xC1A0BEEFu;
}
_mm_sfence();
std::memset(read.cpu, 0xA7, 3 * 65536);
// Alternate which overlapping buffer receives the new full-subresource
// GPU write.
int from = round % 2, to = 1 - from;
q.begin();
activate(q, nullptr, placed[from].p);
activate(q, nullptr, placed[2].p);
q.transition(placed[from].p, D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_STATE_COPY_DEST);
q.list->CopyBufferRegion(placed[from].p, 0, source.resource.p, 0, 65536);
q.transition(placed[from].p, D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_COPY_SOURCE);
q.list->CopyBufferRegion(read.resource.p, 0, placed[from].p, 0, 65536);
q.transition(placed[from].p, D3D12_RESOURCE_STATE_COPY_SOURCE,
D3D12_RESOURCE_STATE_COMMON);
q.transition(placed[2].p, D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_STATE_COPY_DEST);
q.list->CopyBufferRegion(placed[2].p, 0, guardSource.resource.p, 0,
65536);
q.transition(placed[2].p, D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_COPY_SOURCE);
activate(q, placed[from].p, placed[to].p);
q.transition(placed[to].p, D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_STATE_COPY_SOURCE);
q.list->CopyBufferRegion(read.resource.p, 65536, placed[to].p, 0, 65536);
q.transition(placed[to].p, D3D12_RESOURCE_STATE_COPY_SOURCE,
D3D12_RESOURCE_STATE_COMMON);
q.list->CopyBufferRegion(read.resource.p, 131072, placed[2].p, 0, 65536);
q.transition(placed[2].p, D3D12_RESOURCE_STATE_COPY_SOURCE,
D3D12_RESOURCE_STATE_COMMON);
q.finish();
auto p = static_cast<volatile uint32_t *>(read.cpu);
UINT a = 0, b = 0, gmatch = 0;
for (UINT i = 0; i < 16384; ++i) {
UINT expected = i * 1664525u + salt;
a += p[i] == expected;
b += p[16384 + i] == expected;
gmatch += p[32768 + i] == (i ^ 0xC1A0BEEFu);
}
std::printf("BUFFER_INHERIT session=%u round=%u from=%d to=%d "
"source_matches=%u/16384 inherited_matches=%u/16384 "
"disjoint_guard_matches=%u/16384 first_source=%08X "
"first_inherited=%08X expected=%08X\n",
session, round, from, to, a, b, gmatch, p[0], p[16384], salt);
discrepancies += a != 16384 || b != 16384 || gmatch != 16384;
}
q.begin();
q.close();
for (auto &p : placed)
p->Unmap(0, nullptr);
stage("gpu_complete");
if (discrepancies)
throw std::runtime_error("buffer data inheritance mismatch");
std::puts("END success");
return 0;
} catch (const std::exception &e) {
std::printf("END failure reason=%s\n", e.what());
return 1;
}
}
@@ -0,0 +1,32 @@
# Texture, placement and alias observations
Local author results on Apple M4, CrossOver 26.3.0.39832, Wine engine 11.0-8726-g2e2f5fca349 and loaded D3DMetal 3.0. Two fresh processes used changing input datasets. [Raw matrix records](../../results/2026-11-26-apple-m4-arths17-a22-texture-matrix/receipt.json) include source/PE hashes and backend receipts. Independent review/reproduction remains pending.
| Configuration | Exact observed data | Scope |
| --- | --- | --- |
| UNKNOWN RGBA8, 65x37, three mips, disjoint buffer on same heap | WB/WC/DEFAULT each matched 12500/12500 texel bytes and 16384/16384 buffer guard words per session | WB/WC use per-mip CPU subresource writes; DEFAULT uses GPU upload; all use GPU readback |
| UNKNOWN R8_UNORM, same dimensions/mips/mixed placement | Each heap type matched 3125/3125 texel bytes and all guards in each session | Padded 256-byte row pitches, no padding treated as pixels |
| UNKNOWN R32_UINT, same dimensions/mips/mixed placement | Each heap type matched 12500/12500 texel bytes and all guards in each session | Bit-exact integer texture copies, not sampling |
| Overlapping RGBA8 render targets, WB/DEFAULT | Both aliases matched 2405/2405 pixels after distinct endpoint-color clears in each session | Explicit alias barrier and post-activation clear, then copy/readback |
| Overlapping D32_FLOAT depth resources, WB/DEFAULT | Both aliases matched 2405/2405 words for exactly representable 0.5/0.25 clears in each session | Depth clear/copy only; no stencil or rasterized depth comparison |
| Buffer placement at offset 1 | S_OK in both sessions | Caller-invalid alignment; never GPU-used |
| 64 KiB buffer at offset 65536 in 64 KiB heap | S_OK in both sessions | Caller-invalid bounds; never GPU-used |
| Texture on buffer-only heap | E_INVALIDARG in both sessions | Negative creation observed rejected |
All valid positive cases above matched, but each overall matrix process exited 1 because two negative creation calls unexpectedly succeeded. No failures were removed or reclassified. The first smoke process stopped at the first such acceptance and is [preserved separately](../../results/2026-11-26-apple-m4-arths17-a22-texture-first-failure/receipt.json). The later source logs all negative outcomes before reporting the same failing gate.
Interpret this carefully: [CreatePlacedResource](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource) imposes valid offset/alignment/bounds preconditions on callers. It does not promise a specific rejection HRESULT for every invalid call without validation tooling. Therefore these observations show that S_OK is insufficient as an application validation boundary; they do not independently prove a runtime conformance bug or permission to use invalid placements. The unchanged failed negative-rejection gate is explicit in the report.
## Buffer inheritance follow-up
The invalid acceptances prompted a separate valid test of whether correct overlapping placements preserve the public buffer-alias contract. [Microsoft's memory-aliasing/data-inheritance documentation](https://learn.microsoft.com/en-us/windows/win32/direct3d12/memory-aliasing-and-data-inheritance) describes inheritance for defined layouts and compatible resource states. This fixture uses the advanced model and explicit A-to-B/B-to-A alias barriers.
[Two fresh processes](../../results/2026-11-26-apple-m4-arths17-a22-buffer-inheritance/receipt.json) each performed three changing GPU-copy/alias/readback rounds. Two 64 KiB buffers at heap offset 0 returned identical CPU Map pointers and GPU virtual addresses; a disjoint buffer at offset 65536 returned corresponding +65536 addresses. Every source and inherited buffer matched 16384/16384 words in all rounds, and all disjoint guard words matched. No CPU alias dereference is used to manufacture the GPU result. Both processes exited 0.
This establishes the observed application-level buffer alias behavior for this configuration. It neither identifies physical pages nor supplies arbitrary requested CPU addresses, independent section handles or xmem scatter aliases. B must independently review the advanced-model expectation and barriers before acceptance. The RT/depth fixture reinitializes each alias; it does not test texture data inheritance.
## Storage choices and untested cases
CPU-visible and DEFAULT texture paths both produced correct copies/clears in this matrix. No matched bandwidth, sampling/rendering performance, physical texture-footprint comparison or internal Metal storage-mode identification was performed. B's bandwidth/copy/coherence evidence is still required for storage recommendations. A successful buffer map is not a raw pointer to UNKNOWN-layout texels; Map is called with null ppData for CPU texture access.
The historical valid ROW_MAJOR shared-cross-adapter one-mip control remains in the evidence inventory; no identical repeat was needed here. Ordinary ROW_MAJOR CPU-visible heaps, arbitrary format reinterpretation, compressed/planar formats, arrays/3D, MSAA, stencil, sampled filtering and console tiling remain unsupported by this evidence. Do not treat not-run configurations as successes or generalize these synthetic readbacks to Xbox workloads.
@@ -0,0 +1,425 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original Workstream A placement/texture fixtures; no production shim is
// loaded.
#include "../../allocation-profiling/support.h"
#include <memory>
static void stage(const char *name) {
std::printf("STAGE %s cpu_ptr=0\n", name);
if (std::getchar() == EOF)
throw std::runtime_error("handshake");
}
static UINT64 alignUp(UINT64 n, UINT64 a) { return (n + a - 1) / a * a; }
static D3D12_HEAP_PROPERTIES heapProperties(const std::string &type) {
if (type == "default")
return properties(D3D12_HEAP_TYPE_DEFAULT);
auto p = properties(D3D12_HEAP_TYPE_CUSTOM);
p.CPUPageProperty = type == "wc" ? D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE
: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
p.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
return p;
}
static void activate(Queue &q, ID3D12Resource *after,
ID3D12Resource *before = nullptr) {
D3D12_RESOURCE_BARRIER b{};
b.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING;
b.Aliasing.pResourceBefore = before;
b.Aliasing.pResourceAfter = after;
q.list->ResourceBarrier(1, &b);
}
static D3D12_RESOURCE_DESC textureDesc(DXGI_FORMAT format,
D3D12_RESOURCE_FLAGS flags, UINT mips) {
D3D12_RESOURCE_DESC d{};
d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
d.Width = 65;
d.Height = 37;
d.DepthOrArraySize = 1;
d.MipLevels = UINT16(mips);
d.Format = format;
d.SampleDesc.Count = 1;
d.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
d.Flags = flags;
return d;
}
static void copyOut(Queue &q, ID3D12Resource *texture, UINT sub,
ID3D12Resource *read,
const D3D12_PLACED_SUBRESOURCE_FOOTPRINT &fp) {
D3D12_TEXTURE_COPY_LOCATION from{}, to{};
from.pResource = texture;
from.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
from.SubresourceIndex = sub;
to.pResource = read;
to.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
to.PlacedFootprint = fp;
q.list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr);
}
static void copyIn(Queue &q, ID3D12Resource *texture, UINT sub,
ID3D12Resource *upload,
const D3D12_PLACED_SUBRESOURCE_FOOTPRINT &fp) {
D3D12_TEXTURE_COPY_LOCATION from{}, to{};
from.pResource = upload;
from.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
from.PlacedFootprint = fp;
to.pResource = texture;
to.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
to.SubresourceIndex = sub;
q.list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr);
}
static unsigned char dataset(UINT x, UINT y, UINT sub, UINT channel,
UINT round) {
return static_cast<unsigned char>(
(x * 17 + y * 29 + sub * 71 + channel * 43 + round * 53) ^ 0x96);
}
static bool supportedFormat(Context &c, DXGI_FORMAT format, bool rt = false,
bool depth = false) {
D3D12_FEATURE_DATA_FORMAT_SUPPORT f{};
f.Format = format;
HRESULT hr = c.device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &f,
sizeof(f));
std::printf(
"FORMAT format=%u HRESULT=0x%08lX support1=0x%08X support2=0x%08X\n",
format, (unsigned long)hr, unsigned(f.Support1), unsigned(f.Support2));
bool supported =
SUCCEEDED(hr) && (f.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D);
if (rt)
supported = supported && (f.Support1 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET);
if (depth)
supported = supported && (f.Support1 & D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL);
if (!supported)
std::puts("OUTCOME unsupported advertised_format_support");
return supported;
}
static void mixed(Context &c, const std::string &type, DXGI_FORMAT format,
UINT bpp, UINT round) {
if (!supportedFormat(c, format))
return;
auto d = textureDesc(format, D3D12_RESOURCE_FLAG_NONE, 3);
auto ai = c.device->GetResourceAllocationInfo(0, 1, &d);
auto bd = bufferDesc(65536);
auto bi = c.device->GetResourceAllocationInfo(0, 1, &bd);
std::printf("CASE mixed type=%s format=%u mips=3 texture_size=%llu "
"texture_alignment=%llu\n",
type.c_str(), format, ai.SizeInBytes, ai.Alignment);
if (!ai.Alignment || ai.SizeInBytes == ~UINT64(0)) {
std::puts("OUTCOME unsupported allocation_info");
return;
}
UINT64 offset = alignUp(bi.SizeInBytes, ai.Alignment);
Ref<ID3D12Heap> heap;
D3D12_HEAP_DESC hd{};
hd.Properties = heapProperties(type);
hd.Alignment = std::max(ai.Alignment, bi.Alignment);
hd.SizeInBytes = alignUp(offset + ai.SizeInBytes, hd.Alignment);
HRESULT hr = c.device->CreateHeap(&hd, __uuidof(ID3D12Heap), heap.out());
report(hr, "mixed CreateHeap");
if (FAILED(hr)) {
std::puts("OUTCOME unsupported heap");
return;
}
Ref<ID3D12Resource> guard, t;
require(c.device->CreatePlacedResource(heap.p, 0, &bd,
D3D12_RESOURCE_STATE_COMMON, nullptr,
__uuidof(ID3D12Resource), guard.out()),
"mixed guard");
hr = c.device->CreatePlacedResource(heap.p, offset, &d,
D3D12_RESOURCE_STATE_COMMON, nullptr,
__uuidof(ID3D12Resource), t.out());
report(hr, "mixed texture");
if (FAILED(hr)) {
std::puts("OUTCOME unsupported texture");
return;
}
std::printf("PLACEMENT guard_offset=0 guard_size=%llu texture_offset=%llu "
"heap_bytes=%llu disjoint=1\n",
bi.SizeInBytes, offset, hd.SizeInBytes);
std::array<D3D12_PLACED_SUBRESOURCE_FOOTPRINT, 3> fp{};
UINT rows[3]{};
UINT64 rowBytes[3]{}, total = 0;
c.device->GetCopyableFootprints(&d, 0, 3, 512, fp.data(), rows, rowBytes,
&total);
if (total == ~UINT64(0))
throw std::runtime_error("copy footprints");
for (UINT m = 0; m < 3; ++m)
total = std::max(total, fp[m].Offset +
UINT64(fp[m].Footprint.Height - 1) *
fp[m].Footprint.RowPitch +
rowBytes[m]);
Buffer upload, read, guardUpload, guardRead;
upload.allocate(c.device.p, total, "upload");
upload.map();
read.allocate(c.device.p, total, "readback");
read.map();
guardUpload.allocate(c.device.p, 65536, "upload");
guardUpload.map();
guardRead.allocate(c.device.p, 65536, "readback");
guardRead.map();
std::memset(upload.cpu, 0xDA, total);
std::memset(read.cpu, 0xA7, total);
auto gu = static_cast<volatile uint32_t *>(guardUpload.cpu);
for (UINT i = 0; i < 65536 / 4; ++i)
gu[i] = 0xF1A20000u + i + round;
std::array<std::vector<unsigned char>, 3> expected;
for (UINT m = 0; m < 3; ++m) {
UINT width = std::max(1u, 65u >> m), height = std::max(1u, 37u >> m);
expected[m].resize(width * height * bpp);
if (fp[m].Offset % 512 || fp[m].Footprint.RowPitch % 256 ||
rowBytes[m] != width * bpp || rows[m] != height)
throw std::runtime_error("unexpected footprint contract");
std::printf("FOOTPRINT mip=%u offset=%llu rows=%u row_bytes=%llu "
"row_pitch=%u total=%llu\n",
m, fp[m].Offset, rows[m], rowBytes[m], fp[m].Footprint.RowPitch,
total);
for (UINT y = 0; y < height; ++y)
for (UINT x = 0; x < width; ++x)
for (UINT b = 0; b < bpp; ++b) {
auto v = dataset(x, y, m, b, round);
expected[m][(y * width + x) * bpp + b] = v;
static_cast<unsigned char *>(
upload.cpu)[fp[m].Offset + UINT64(y) * fp[m].Footprint.RowPitch +
x * bpp + b] = v;
}
}
Queue q(c.device.p);
q.begin();
activate(q, guard.p);
activate(q, t.p);
q.transition(guard.p, D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_STATE_COPY_DEST);
q.list->CopyBufferRegion(guard.p, 0, guardUpload.resource.p, 0, 65536);
q.transition(guard.p, D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_COMMON);
q.finish();
if (type != "default") {
for (UINT m = 0; m < 3; ++m) {
hr = t->Map(m, nullptr, nullptr);
report(hr, "mixed Map null pointer");
if (FAILED(hr)) {
std::puts("OUTCOME unsupported CPU_texture_Map");
return;
}
UINT width = std::max(1u, 65u >> m), height = std::max(1u, 37u >> m);
hr = t->WriteToSubresource(m, nullptr, expected[m].data(), width * bpp,
width * height * bpp);
report(hr, "mixed WriteToSubresource");
t->Unmap(m, nullptr);
if (FAILED(hr)) {
std::puts("OUTCOME unsupported CPU_texture_write");
return;
}
}
} else {
q.begin();
q.transition(t.p, D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_STATE_COPY_DEST);
for (UINT m = 0; m < 3; ++m)
copyIn(q, t.p, m, upload.resource.p, fp[m]);
q.transition(t.p, D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_COMMON);
q.finish();
}
_mm_sfence();
q.begin();
q.transition(t.p, D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_STATE_COPY_SOURCE);
for (UINT m = 0; m < 3; ++m)
copyOut(q, t.p, m, read.resource.p, fp[m]);
q.transition(t.p, D3D12_RESOURCE_STATE_COPY_SOURCE,
D3D12_RESOURCE_STATE_COMMON);
q.transition(guard.p, D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_STATE_COPY_SOURCE);
q.list->CopyBufferRegion(guardRead.resource.p, 0, guard.p, 0, 65536);
q.transition(guard.p, D3D12_RESOURCE_STATE_COPY_SOURCE,
D3D12_RESOURCE_STATE_COMMON);
q.finish();
UINT64 matches = 0, count = 0;
for (UINT m = 0; m < 3; ++m) {
UINT width = std::max(1u, 65u >> m), height = std::max(1u, 37u >> m);
for (UINT y = 0; y < height; ++y)
for (UINT x = 0; x < width * bpp; ++x) {
++count;
matches +=
static_cast<volatile unsigned char *>(
read.cpu)[fp[m].Offset + UINT64(y) * fp[m].Footprint.RowPitch +
x] == expected[m][y * width * bpp + x];
}
}
UINT guards = 0;
for (UINT i = 0; i < 65536 / 4; ++i)
guards += static_cast<volatile uint32_t *>(guardRead.cpu)[i] ==
0xF1A20000u + i + round;
std::printf("OUTCOME mixed type=%s format=%u bytes_match=%llu/%llu "
"guard_words=%u/16384\n",
type.c_str(), format, matches, count, guards);
if (matches != count || guards != 16384)
throw std::runtime_error("mixed texture/guard mismatch");
}
static void clearAlias(Context &c, const std::string &type, bool depth) {
auto d =
textureDesc(depth ? DXGI_FORMAT_D32_FLOAT : DXGI_FORMAT_R8G8B8A8_UNORM,
depth ? D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL
: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET,
1);
if (!supportedFormat(c, d.Format, !depth, depth))
return;
auto ai = c.device->GetResourceAllocationInfo(0, 1, &d);
std::printf("CASE clear_alias type=%s depth=%d size=%llu alignment=%llu\n",
type.c_str(), depth, ai.SizeInBytes, ai.Alignment);
if (!ai.Alignment || ai.SizeInBytes == ~UINT64(0)) {
std::puts("OUTCOME unsupported allocation_info");
return;
}
Ref<ID3D12Heap> heap;
D3D12_HEAP_DESC hd{};
hd.Properties = heapProperties(type);
hd.Alignment = ai.Alignment;
hd.SizeInBytes = ai.SizeInBytes;
hd.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES;
HRESULT hr = c.device->CreateHeap(&hd, __uuidof(ID3D12Heap), heap.out());
report(hr, "clear heap");
if (FAILED(hr)) {
std::puts("OUTCOME unsupported clear_heap");
return;
}
Ref<ID3D12Resource> textures[2];
for (int i = 0; i < 2; ++i) {
hr = c.device->CreatePlacedResource(
heap.p, 0, &d, D3D12_RESOURCE_STATE_COMMON, nullptr,
__uuidof(ID3D12Resource), textures[i].out());
report(hr, "clear alias texture");
if (FAILED(hr)) {
std::puts("OUTCOME unsupported clear_texture");
return;
}
}
Ref<ID3D12DescriptorHeap> views;
D3D12_DESCRIPTOR_HEAP_DESC vd{};
vd.Type =
depth ? D3D12_DESCRIPTOR_HEAP_TYPE_DSV : D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
vd.NumDescriptors = 2;
require(c.device->CreateDescriptorHeap(&vd, __uuidof(ID3D12DescriptorHeap),
views.out()),
"clear views");
auto start = views->GetCPUDescriptorHandleForHeapStart();
UINT inc = c.device->GetDescriptorHandleIncrementSize(vd.Type);
D3D12_CPU_DESCRIPTOR_HANDLE handles[2] = {{start.ptr}, {start.ptr + inc}};
for (int i = 0; i < 2; ++i)
if (depth)
c.device->CreateDepthStencilView(textures[i].p, nullptr, handles[i]);
else
c.device->CreateRenderTargetView(textures[i].p, nullptr, handles[i]);
D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{};
UINT rows = 0;
UINT64 rowBytes = 0, total = 0;
c.device->GetCopyableFootprints(&d, 0, 1, 0, &fp, &rows, &rowBytes, &total);
Buffer read[2];
for (auto &b : read) {
b.allocate(c.device.p, total, "readback");
b.map();
std::memset(b.cpu, 0xA7, total);
}
Queue q(c.device.p);
q.begin();
for (int i = 0; i < 2; ++i) {
activate(q, textures[i].p, i ? textures[0].p : nullptr);
auto state = depth ? D3D12_RESOURCE_STATE_DEPTH_WRITE
: D3D12_RESOURCE_STATE_RENDER_TARGET;
q.transition(textures[i].p, D3D12_RESOURCE_STATE_COMMON, state);
if (depth)
q.list->ClearDepthStencilView(handles[i], D3D12_CLEAR_FLAG_DEPTH,
i ? 0.25f : 0.5f, 0, 0, nullptr);
else {
FLOAT color[4] = {i ? 0.0f : 1.0f, i ? 1.0f : 0.0f, 1.0f, 1.0f};
q.list->ClearRenderTargetView(handles[i], color, 0, nullptr);
}
q.transition(textures[i].p, state, D3D12_RESOURCE_STATE_COPY_SOURCE);
copyOut(q, textures[i].p, 0, read[i].resource.p, fp);
q.transition(textures[i].p, D3D12_RESOURCE_STATE_COPY_SOURCE,
D3D12_RESOURCE_STATE_COMMON);
}
q.finish();
for (int i = 0; i < 2; ++i) {
UINT expected = depth ? (i ? 0x3E800000u : 0x3F000000u)
: (i ? 0xFFFFFF00u : 0xFFFF00FFu);
UINT matches = 0;
for (UINT y = 0; y < 37; ++y) {
auto p = reinterpret_cast<volatile uint32_t *>(
static_cast<unsigned char *>(read[i].cpu) + fp.Offset +
UINT64(y) * fp.Footprint.RowPitch);
for (UINT x = 0; x < 65; ++x)
matches += p[x] == expected;
}
std::printf("OUTCOME clear_alias type=%s depth=%d alias=%d expected=%08X "
"matches=%u/2405\n",
type.c_str(), depth, i, expected, matches);
if (matches != 2405)
throw std::runtime_error("clear/alias mismatch");
}
}
static UINT rejectedPlacements(Context &c) {
UINT violations = 0;
Ref<ID3D12Heap> h;
D3D12_HEAP_DESC hd{};
hd.Properties = heapProperties("wb");
hd.SizeInBytes = 65536;
hd.Alignment = 65536;
hd.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS;
require(c.device->CreateHeap(&hd, __uuidof(ID3D12Heap), h.out()),
"negative heap");
auto b = bufferDesc(65536);
for (UINT64 offset : {1ULL, 65536ULL}) {
Ref<ID3D12Resource> r;
HRESULT hr = c.device->CreatePlacedResource(
h.p, offset, &b, D3D12_RESOURCE_STATE_COMMON, nullptr,
__uuidof(ID3D12Resource), r.out());
std::printf("NEGATIVE placement offset=%llu HRESULT=0x%08lX rejected=%d\n",
offset, (unsigned long)hr, FAILED(hr));
if (SUCCEEDED(hr))
++violations;
}
auto t = textureDesc(DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE, 1);
Ref<ID3D12Resource> r;
HRESULT hr = c.device->CreatePlacedResource(
h.p, 0, &t, D3D12_RESOURCE_STATE_COMMON, nullptr,
__uuidof(ID3D12Resource), r.out());
std::printf("NEGATIVE texture_on_buffer_only HRESULT=0x%08lX rejected=%d\n",
(unsigned long)hr, FAILED(hr));
if (SUCCEEDED(hr))
++violations;
std::printf("NEGATIVE_SUMMARY unexpected_successes=%u/3\n", violations);
return violations;
}
int main(int argc, char **argv) {
setvbuf(stdout, nullptr, _IONBF, 0);
try {
if (argc != 2)
throw std::runtime_error("usage: textures ROUND");
UINT round = UINT(std::strtoul(argv[1], nullptr, 10));
Context c;
identity(c);
stage("baseline");
D3D12_FEATURE_DATA_D3D12_OPTIONS opts{};
require(c.device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &opts,
sizeof(opts)),
"heap tier");
if (opts.ResourceHeapTier < D3D12_RESOURCE_HEAP_TIER_2)
std::puts("MIXED NOT_RUN tier_below_2");
else
for (const std::string type : {"wb", "wc", "default"}) {
mixed(c, type, DXGI_FORMAT_R8G8B8A8_UNORM, 4, round);
mixed(c, type, DXGI_FORMAT_R8_UNORM, 1, round);
mixed(c, type, DXGI_FORMAT_R32_UINT, 4, round);
}
for (const std::string type : {"wb", "default"}) {
clearAlias(c, type, false);
clearAlias(c, type, true);
}
UINT violations = rejectedPlacements(c);
stage("resources_released");
if (violations)
throw std::runtime_error("invalid creations accepted");
std::puts("END success");
return 0;
} catch (const std::exception &e) {
std::printf("END failure reason=%s\n", e.what());
return 1;
}
}
+253
View File
@@ -0,0 +1,253 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original synthetic public-D3D12 research probe; issue #473.
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#include <d3d12.h>
#include <tlhelp32.h>
#include <emmintrin.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <vector>
#include <utility>
template<class T> struct Ptr {
T* p=nullptr;
Ptr()=default; Ptr(const Ptr&)=delete; Ptr& operator=(const Ptr&)=delete;
~Ptr(){if(p)p->Release();}
T* operator->()const{return p;}
explicit operator bool()const{return p!=nullptr;}
void** out(){return reinterpret_cast<void**>(&p);}
};
static int failures=0;
static bool hr(const char* label,HRESULT h){
std::printf("%s HRESULT=0x%08lX\n",label,static_cast<unsigned long>(h));
return SUCCEEDED(h);
}
static D3D12_HEAP_PROPERTIES props(D3D12_HEAP_TYPE type,D3D12_CPU_PAGE_PROPERTY cpu=D3D12_CPU_PAGE_PROPERTY_UNKNOWN,D3D12_MEMORY_POOL pool=D3D12_MEMORY_POOL_UNKNOWN){
D3D12_HEAP_PROPERTIES p{};p.Type=type;p.CPUPageProperty=cpu;p.MemoryPoolPreference=pool;p.CreationNodeMask=1;p.VisibleNodeMask=1;return p;
}
static D3D12_RESOURCE_DESC buffer(UINT64 n,D3D12_RESOURCE_FLAGS flags=D3D12_RESOURCE_FLAG_NONE){
D3D12_RESOURCE_DESC d{};d.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;d.Width=n;d.Height=1;d.DepthOrArraySize=1;d.MipLevels=1;d.SampleDesc.Count=1;d.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;d.Flags=flags;return d;
}
static bool heap(ID3D12Device3* d,UINT64 size,D3D12_CPU_PAGE_PROPERTY cpu,D3D12_MEMORY_POOL pool,D3D12_HEAP_FLAGS flags,Ptr<ID3D12Heap>& h,const char* label){
D3D12_HEAP_DESC desc{};desc.SizeInBytes=size;desc.Properties=props(D3D12_HEAP_TYPE_CUSTOM,cpu,pool);desc.Alignment=65536;desc.Flags=flags;
return hr(label,d->CreateHeap(&desc,__uuidof(ID3D12Heap),h.out()));
}
static bool committed(ID3D12Device3* d,UINT64 n,D3D12_HEAP_TYPE type,D3D12_RESOURCE_STATES state,Ptr<ID3D12Resource>& r,const char* label){
auto p=props(type);auto b=buffer(n);
return hr(label,d->CreateCommittedResource(&p,D3D12_HEAP_FLAG_NONE,&b,state,nullptr,__uuidof(ID3D12Resource),r.out()));
}
struct Engine {
ID3D12Device3* dev;
Ptr<ID3D12CommandQueue> queue;Ptr<ID3D12CommandAllocator> alloc;Ptr<ID3D12GraphicsCommandList> list;Ptr<ID3D12Fence> fence;
HANDLE event=nullptr;UINT64 sequence=0;
explicit Engine(ID3D12Device3* d):dev(d){}
~Engine(){if(event)CloseHandle(event);}
bool init(){
D3D12_COMMAND_QUEUE_DESC q{};q.Type=D3D12_COMMAND_LIST_TYPE_DIRECT;
if(!hr("queue",dev->CreateCommandQueue(&q,__uuidof(ID3D12CommandQueue),queue.out())))return false;
if(!hr("allocator",dev->CreateCommandAllocator(q.Type,__uuidof(ID3D12CommandAllocator),alloc.out())))return false;
if(!hr("command_list",dev->CreateCommandList(0,q.Type,alloc.p,nullptr,__uuidof(ID3D12GraphicsCommandList),list.out())))return false;
if(!hr("initial_close",list->Close()))return false;
if(!hr("fence",dev->CreateFence(0,D3D12_FENCE_FLAG_NONE,__uuidof(ID3D12Fence),fence.out())))return false;
event=CreateEventW(nullptr,FALSE,FALSE,nullptr);
std::printf("fence_event success=%d error=%lu\n",event!=nullptr,event?0:GetLastError());return event!=nullptr;
}
bool begin(){
HRESULT h=alloc->Reset();if(FAILED(h))return hr("allocator.Reset",h);
h=list->Reset(alloc.p,nullptr);if(FAILED(h))return hr("list.Reset",h);return true;
}
void transition(ID3D12Resource* r,D3D12_RESOURCE_STATES from,D3D12_RESOURCE_STATES to){
if(from==to)return;
D3D12_RESOURCE_BARRIER b{};b.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;b.Transition.pResource=r;b.Transition.StateBefore=from;b.Transition.StateAfter=to;b.Transition.Subresource=D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;list->ResourceBarrier(1,&b);
}
bool submit(){
HRESULT h=list->Close();if(FAILED(h))return hr("list.Close",h);
_mm_sfence();
ID3D12CommandList* lists[]={list.p};queue->ExecuteCommandLists(1,lists);
h=queue->Signal(fence.p,++sequence);if(FAILED(h))return hr("queue.Signal",h);
if(fence->GetCompletedValue()<sequence){
h=fence->SetEventOnCompletion(sequence,event);if(FAILED(h))return hr("fence.SetEventOnCompletion",h);
DWORD w=WaitForSingleObject(event,5000);if(w!=WAIT_OBJECT_0){std::printf("fence_wait result=0x%08lX last_error=%lu\n",w,GetLastError());return false;}
}
h=dev->GetDeviceRemovedReason();if(FAILED(h))return hr("device_removed",h);return true;
}
bool readEnds(ID3D12Resource* source,UINT64 n,D3D12_RESOURCE_STATES state,ID3D12Resource* dest){
if(!begin())return false;
const bool needsBarrier=(state & D3D12_RESOURCE_STATE_COPY_SOURCE)==0;
if(needsBarrier)transition(source,state,D3D12_RESOURCE_STATE_COPY_SOURCE);
list->CopyBufferRegion(dest,0,source,0,64);
list->CopyBufferRegion(dest,64,source,n-64,64);
if(needsBarrier)transition(source,D3D12_RESOURCE_STATE_COPY_SOURCE,state);
return submit();
}
};
static void modules(){
HANDLE s=CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,GetCurrentProcessId());
MODULEENTRY32 m{};m.dwSize=sizeof(m);
if(s!=INVALID_HANDLE_VALUE){
if(Module32First(s,&m))do{
if(strstr(m.szModule,"d3d12")||strstr(m.szModule,"dxgi"))std::printf("module %s path=%s\n",m.szModule,m.szExePath);
}while(Module32Next(s,&m));CloseHandle(s);
}
std::printf("d3d12_xs_loaded=%d\n",GetModuleHandleA("d3d12_xs.dll")!=nullptr);
}
static void wrapping(ID3D12Device3* d,Engine* e){
std::puts("[2] Existing-memory wrapping (64 KiB)");
void* mem=VirtualAlloc(nullptr,65536,MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE);
std::printf("VirtualAlloc success=%d error=%lu\n",mem!=nullptr,mem?0:GetLastError());
HANDLE mapping=CreateFileMappingW(INVALID_HANDLE_VALUE,nullptr,PAGE_READWRITE,0,65536,nullptr);
std::printf("CreateFileMappingW success=%d error=%lu\n",mapping!=nullptr,mapping?0:GetLastError());
void* view=mapping?MapViewOfFile(mapping,FILE_MAP_ALL_ACCESS,0,0,65536):nullptr;
if(mapping)std::printf("MapViewOfFile success=%d error=%lu\n",view!=nullptr,view?0:GetLastError());
{
Ptr<ID3D12Heap> a,f;
if(mem)hr("OpenExistingHeapFromAddress",d->OpenExistingHeapFromAddress(mem,__uuidof(ID3D12Heap),a.out()));
if(mapping)hr("OpenExistingHeapFromFileMapping",d->OpenExistingHeapFromFileMapping(mapping,__uuidof(ID3D12Heap),f.out()));
for(int i=0;i<2;++i){
ID3D12Heap* h=i?f.p:a.p;auto* cpu=static_cast<volatile uint32_t*>(i?view:mem);
const char* label=i?"file_mapping_visibility":"address_visibility";
if(!h){std::printf("%s NOT_RUN (heap open failed)\n",label);continue;}
if(!cpu||!e){std::printf("%s NOT_RUN (missing CPU view or queue)\n",label);continue;}
Ptr<ID3D12Resource> placed,readback;auto b=buffer(65536);
if(!hr(label,d->CreatePlacedResource(h,0,&b,D3D12_RESOURCE_STATE_COMMON,nullptr,__uuidof(ID3D12Resource),placed.out())))continue;
if(!committed(d,128,D3D12_HEAP_TYPE_READBACK,D3D12_RESOURCE_STATE_COPY_DEST,readback,"wrap_readback"))continue;
void* p=nullptr;D3D12_RANGE range{0,128};if(!hr("wrap_readback.Map",readback->Map(0,&range,&p)))continue;
cpu[0]=0x13579BDFu;cpu[(65536-64)/4]=0x2468ACE0u;_mm_sfence();
bool submitted=e->readEnds(placed.p,65536,D3D12_RESOURCE_STATE_COMMON,readback.p);
auto* actual=static_cast<volatile uint32_t*>(p);bool ok=submitted&&actual[0]==0x13579BDFu&&actual[16]==0x2468ACE0u;
std::printf("%s actual=%08X,%08X expected=13579BDF,2468ACE0 match=%d\n",label,actual[0],actual[16],ok);if(!ok)++failures;
}
}
if(view)UnmapViewOfFile(view);
if(mapping)CloseHandle(mapping);
if(mem)VirtualFree(mem,0,MEM_RELEASE);
}
static void placement(ID3D12Device3* d){
std::puts("[3] CUSTOM heap creation (size=2097152 alignment=65536)");
const D3D12_HEAP_FLAGS flags[]={D3D12_HEAP_FLAG_NONE,D3D12_HEAP_FLAG_NONE,D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS,D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES,D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES,D3D12_HEAP_FLAG_NONE};
const char* labels[]={"WRITE_BACK/L0/ALLOW_ALL","WRITE_COMBINE/L0/ALLOW_ALL","WRITE_BACK/L0/ALLOW_ONLY_BUFFERS","WRITE_BACK/L0/ALLOW_ONLY_NON_RT_DS_TEXTURES","WRITE_BACK/L0/ALLOW_ONLY_RT_DS_TEXTURES","WRITE_BACK/L1/ALLOW_ALL control"};
for(int i=0;i<6;++i){Ptr<ID3D12Heap> h;heap(d,2097152,i==1?D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE:D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,i==5?D3D12_MEMORY_POOL_L1:D3D12_MEMORY_POOL_L0,flags[i],h,labels[i]);}
Ptr<ID3D12Heap> h;if(!heap(d,2097152,D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,D3D12_MEMORY_POOL_L0,D3D12_HEAP_FLAG_NONE,h,"mixed_heap")){std::puts("mixed placement NOT_RUN");return;}
Ptr<ID3D12Resource> b,t;auto bd=buffer(65536,D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
bool bok=hr("placed_UAV_buffer offset=0",d->CreatePlacedResource(h.p,0,&bd,D3D12_RESOURCE_STATE_COMMON,nullptr,__uuidof(ID3D12Resource),b.out()));
D3D12_RESOURCE_DESC td{};td.Dimension=D3D12_RESOURCE_DIMENSION_TEXTURE2D;td.Width=64;td.Height=64;td.DepthOrArraySize=1;td.MipLevels=1;td.Format=DXGI_FORMAT_R8G8B8A8_UNORM;td.SampleDesc.Count=1;td.Layout=D3D12_TEXTURE_LAYOUT_UNKNOWN;
auto ba=d->GetResourceAllocationInfo(0,1,&bd);auto ta=d->GetResourceAllocationInfo(0,1,&td);
if(!ta.Alignment||ba.SizeInBytes==~UINT64(0)||ta.SizeInBytes==~UINT64(0)){std::puts("invalid allocation info; texture NOT_RUN");return;}
UINT64 off=(ba.SizeInBytes+ta.Alignment-1)/ta.Alignment*ta.Alignment;
std::printf("buffer allocation size=%llu alignment=%llu; texture size=%llu alignment=%llu offset=%llu\n",ba.SizeInBytes,ba.Alignment,ta.SizeInBytes,ta.Alignment,off);
bool tok=hr("placed_RGBA8_texture same_heap",d->CreatePlacedResource(h.p,off,&td,D3D12_RESOURCE_STATE_COMMON,nullptr,__uuidof(ID3D12Resource),t.out()));
std::printf("mixed_buffer_and_texture_live=%d\n",bok&&tok);
if(!tok)return;
HRESULT mapped=t->Map(0,nullptr,nullptr);if(!hr("texture.Map(null ppData)",mapped)){std::puts("texture roundtrip NOT_RUN");return;}
std::vector<uint32_t> input(4096),output(4096,0xDEADBEEFu);for(size_t i=0;i<input.size();++i)input[i]=0x8A31C57Fu^(uint32_t(i)*0x0103070Bu);
HRESULT w=t->WriteToSubresource(0,nullptr,input.data(),256,16384);hr("texture.WriteToSubresource",w);
HRESULT r=t->ReadFromSubresource(output.data(),256,16384,0,nullptr);hr("texture.ReadFromSubresource",r);
size_t matches=0;for(size_t i=0;i<input.size();++i)matches+=input[i]==output[i];
std::printf("texture roundtrip exact_words=%zu/4096 match=%d\n",matches,SUCCEEDED(w)&&SUCCEEDED(r)&&matches==4096);
if(FAILED(w)||FAILED(r)||matches!=4096)++failures;
// The texture test is separate from the persistent buffer tests.
t->Unmap(0,nullptr);
}
static void coherence(ID3D12Device3* d,Engine& e){
std::puts("[4] Bidirectional persistent Map; no Unmap or remap");
Ptr<ID3D12Heap> h;Ptr<ID3D12Resource> b,readback,upload;
if(!heap(d,65536,D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,D3D12_MEMORY_POOL_L0,D3D12_HEAP_FLAG_NONE,h,"coherence_heap"))return;
auto bd=buffer(65536,D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
if(!hr("coherence_placed_UAV_buffer",d->CreatePlacedResource(h.p,0,&bd,D3D12_RESOURCE_STATE_COMMON,nullptr,__uuidof(ID3D12Resource),b.out())))return;
if(!committed(d,128,D3D12_HEAP_TYPE_READBACK,D3D12_RESOURCE_STATE_COPY_DEST,readback,"coherence_readback"))return;
if(!committed(d,65536,D3D12_HEAP_TYPE_UPLOAD,D3D12_RESOURCE_STATE_GENERIC_READ,upload,"coherence_upload"))return;
void *cp=nullptr,*rp=nullptr,*up=nullptr;D3D12_RANGE rr{0,128},none{0,0};
if(!hr("placed.Map",b->Map(0,nullptr,&cp)))return;
if(!hr("readback.Map",readback->Map(0,&rr,&rp)))return;
if(!hr("upload.Map",upload->Map(0,&none,&up)))return;
auto* cpu=static_cast<volatile uint32_t*>(cp);auto* actual=static_cast<volatile uint32_t*>(rp);
const uint32_t values[3][2]={{0x11223344u,0xA1B2C3D4u},{0x55AA00FFu,0xF00DBA5Eu},{0xC001D00Du,0x9E3779B9u}};
for(int i=0;i<2;++i){
cpu[0]=values[i][0];cpu[1]=values[i][1];_mm_sfence();
bool submitted=e.readEnds(b.p,65536,D3D12_RESOURCE_STATE_COMMON,readback.p);
bool ok=submitted&&actual[0]==values[i][0]&&actual[1]==values[i][1];
std::printf("CPU->GPU round=%d expected=%08X,%08X actual=%08X,%08X match=%d\n",i+1,values[i][0],values[i][1],actual[0],actual[1],ok);if(!ok)++failures;
}
auto* src=static_cast<volatile uint32_t*>(up);src[0]=values[2][0];src[1]=values[2][1];_mm_sfence();
if(!e.begin())return;
e.transition(b.p,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_DEST);
e.list->CopyBufferRegion(b.p,0,upload.p,0,8);
e.transition(b.p,D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_COMMON);
bool submitted=e.submit();bool ok=submitted&&cpu[0]==values[2][0]&&cpu[1]==values[2][1];
std::printf("GPU->CPU same_cpu_ptr expected=%08X,%08X actual=%08X,%08X match=%d\n",values[2][0],values[2][1],cpu[0],cpu[1],ok);if(!ok)++failures;
}
static void benchmark(ID3D12Device3* d,Engine& e,const char* label,UINT64 n,bool isUpload,D3D12_CPU_PAGE_PROPERTY property){
std::printf("[5] BENCH %s size=%llu warmup=5 timed=40\n",label,n);
Ptr<ID3D12Heap> h;Ptr<ID3D12Resource> b,r;
D3D12_RESOURCE_STATES state=isUpload?D3D12_RESOURCE_STATE_GENERIC_READ:D3D12_RESOURCE_STATE_COMMON;
if(isUpload){if(!committed(d,n,D3D12_HEAP_TYPE_UPLOAD,state,b,"bench_upload"))return;}
else{
if(!heap(d,n,property,D3D12_MEMORY_POOL_L0,D3D12_HEAP_FLAG_NONE,h,"bench_heap"))return;
auto bd=buffer(n);if(!hr("bench_placed_buffer",d->CreatePlacedResource(h.p,0,&bd,state,nullptr,__uuidof(ID3D12Resource),b.out())))return;
}
if(!committed(d,128,D3D12_HEAP_TYPE_READBACK,D3D12_RESOURCE_STATE_COPY_DEST,r,"bench_readback"))return;
void *bp=nullptr,*rp=nullptr;D3D12_RANGE none{0,0},read{0,128};
if(!hr("bench_source.Map",b->Map(0,&none,&bp)))return;
if(!hr("bench_readback.Map",r->Map(0,&read,&rp)))return;
auto* bytes=static_cast<volatile unsigned char*>(bp);
for(UINT64 i=0;i<n;i+=65536)bytes[i]=0x5A;
_mm_sfence();
std::printf("prefault stride=65536 touches=%llu\n",n/65536);
auto* first=static_cast<volatile uint32_t*>(bp);auto* last=reinterpret_cast<volatile uint32_t*>(static_cast<unsigned char*>(bp)+n-64);auto* actual=static_cast<volatile uint32_t*>(rp);
LARGE_INTEGER frequency{},start{},end{};QueryPerformanceFrequency(&frequency);
int warmMatches=0,timedMatches=0;double total=0;
for(int i=-5;i<40;++i){
uint32_t value=0xB1630000u+uint32_t(i+5)*0x00010307u;
if(i==0)QueryPerformanceCounter(&start);
for(int j=0;j<16;++j){first[j]=value^uint32_t(j)*0x01010101u;last[j]=(~value)^uint32_t(j)*0x0103070Bu;}
_mm_sfence();
bool ok=e.readEnds(b.p,n,state,r.p);if(!ok){std::puts("BENCH aborted (submission failed)");++failures;return;}
for(int j=0;j<16;++j)ok=ok&&actual[j]==(value^uint32_t(j)*0x01010101u)&&actual[16+j]==((~value)^uint32_t(j)*0x0103070Bu);
if(i<0)warmMatches+=ok;else timedMatches+=ok;
if(!ok)std::printf("BENCH mismatch iteration=%d first=%08X expected=%08X last=%08X expected=%08X\n",i,actual[0],value,actual[16],~value);
}
QueryPerformanceCounter(&end);total=1000.0*double(end.QuadPart-start.QuadPart)/double(frequency.QuadPart);
std::printf("BENCH_RESULT %s bytes=%llu total_ms=%.6f avg_ms_per_submit=%.6f exact_matches=%d/40 warmup_matches=%d/5\n",label,n,total,total/40,timedMatches,warmMatches);
if(timedMatches!=40||warmMatches!=5)++failures;
}
static void writewatch(){
std::puts("[6] MEM_WRITE_WATCH 65536 bytes; writes at 0 and 16384");
void* p=VirtualAlloc(nullptr,65536,MEM_COMMIT|MEM_RESERVE|MEM_WRITE_WATCH,PAGE_READWRITE);
std::printf("writewatch.VirtualAlloc success=%d error=%lu\n",p!=nullptr,p?0:GetLastError());if(!p)return;
auto* bytes=static_cast<volatile unsigned char*>(p);bytes[0]=0x61;bytes[16384]=0x72;
PVOID addresses[64]{};ULONG_PTR count=64;DWORD granularity=0;
UINT rc=GetWriteWatch(WRITE_WATCH_FLAG_RESET,p,65536,addresses,&count,&granularity);
std::printf("GetWriteWatch return=%u dirty_page_count=%llu granularity=%lu\n",rc,static_cast<unsigned long long>(count),granularity);
if(rc==0)for(ULONG_PTR i=0;i<count&&i<64;++i)std::printf("dirty_page[%llu] offset=%llu\n",static_cast<unsigned long long>(i),static_cast<unsigned long long>(static_cast<unsigned char*>(addresses[i])-static_cast<unsigned char*>(p)));
VirtualFree(p,0,MEM_RELEASE);
}
int main(int argc,char**){
setvbuf(stdout,nullptr,_IONBF,0);std::puts("Independent standalone D3D12 UMA probe; C++20; sizeof(void*)=8 expected");
std::printf("sizeof(void*)=%zu\n",sizeof(void*));
HMODULE dll=LoadLibraryA("d3d12.dll");if(!dll){std::printf("LoadLibraryA(d3d12.dll) failed error=%lu\n",GetLastError());writewatch();return 2;}
char path[32768]{};GetModuleFileNameA(dll,path,sizeof(path));std::printf("LoadLibraryA(d3d12.dll) path=%s\n",path);
using Create=HRESULT(WINAPI*)(IUnknown*,D3D_FEATURE_LEVEL,REFIID,void**);
FARPROC symbol=GetProcAddress(dll,"D3D12CreateDevice");
Create create=nullptr;static_assert(sizeof(create)==sizeof(symbol));std::memcpy(&create,&symbol,sizeof(create));
if(!create){std::printf("GetProcAddress failed error=%lu\n",GetLastError());writewatch();return 2;}
Ptr<ID3D12Device> base;
if(!hr("D3D12CreateDevice FL11_0",create(nullptr,D3D_FEATURE_LEVEL_11_0,__uuidof(ID3D12Device),base.out()))){writewatch();return 2;}
Ptr<ID3D12Device3> d;if(!hr("QueryInterface ID3D12Device3",base->QueryInterface(__uuidof(ID3D12Device3),d.out()))){writewatch();return 2;}
modules();if(argc>1){wrapping(d.p,nullptr);std::puts("backend receipt pause 10 seconds");Sleep(10000);return 0;}std::puts("[1] Device capability queries, NodeIndex=0");
D3D12_FEATURE_DATA_ARCHITECTURE1 a{};
if(hr("D3D12_FEATURE_ARCHITECTURE1",d->CheckFeatureSupport(D3D12_FEATURE_ARCHITECTURE1,&a,sizeof(a))))std::printf("UMA=%d CacheCoherentUMA=%d TileBasedRenderer=%d IsolatedMMU=%d\n",a.UMA,a.CacheCoherentUMA,a.TileBasedRenderer,a.IsolatedMMU);
D3D12_FEATURE_DATA_D3D12_OPTIONS o{};
if(hr("D3D12_FEATURE_D3D12_OPTIONS",d->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS,&o,sizeof(o))))std::printf("ResourceHeapTier=%d\n",int(o.ResourceHeapTier));
Engine e(d.p);bool ready=e.init();wrapping(d.p,ready?&e:nullptr);placement(d.p);
if(ready){
coherence(d.p,e);
benchmark(d.p,e,"CUSTOM/WRITE_BACK/L0/64KiB",65536,false,D3D12_CPU_PAGE_PROPERTY_WRITE_BACK);
benchmark(d.p,e,"CUSTOM/WRITE_BACK/L0/256MiB",268435456,false,D3D12_CPU_PAGE_PROPERTY_WRITE_BACK);
benchmark(d.p,e,"CUSTOM/WRITE_COMBINE/L0/256MiB",268435456,false,D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE);
benchmark(d.p,e,"UPLOAD/256MiB",268435456,true,D3D12_CPU_PAGE_PROPERTY_UNKNOWN);
}else{std::puts("[4,5] NOT_RUN: queue initialization failed");++failures;}
writewatch();std::printf("END observed_data_or_submission_failures=%d (unsupported HRESULTs reported separately)\n",failures);return failures?1:0;
}
@@ -0,0 +1,34 @@
{
"utc": "2026-11-26T20:49:42.427567+00:00",
"ceiling_bytes": 23000000000,
"interpretation": "ceiling, not target; no optional >1 GiB source. VM-stat metric and process receipts are estimates, not an exact Activity Monitor reading",
"commands": [
{
"command": [
"vm_stat"
],
"exit": 0,
"stdout": "Mach Virtual Memory Statistics: (page size of 16384 bytes)\nPages free: 19620.\nPages active: 482635.\nPages inactive: 481510.\nPages speculative: 272.\nPages throttled: 0.\nPages wired down: 169036.\nPages purgeable: 3979.\n\"Translation faults\": 2446688112.\nPages copy-on-write: 98266035.\nPages zero filled: 1696847247.\nPages reactivated: 189173409.\nPages purged: 19494563.\nFile-backed pages: 253058.\nAnonymous pages: 711359.\nPages stored in compressor: 1396774.\nPages occupied by compressor: 381078.\nDecompressions: 152095693.\nCompressions: 190696104.\nPageins: 47601585.\nPageouts: 921199.\nSwapins: 1682593.\nSwapouts: 2468999.\n",
"stderr": ""
},
{
"command": [
"memory_pressure",
"-Q"
],
"exit": 0,
"stdout": "The system has 25769803776 (1572864 pages with a page size of 16384).\nSystem-wide memory free percentage: 63%\n",
"stderr": ""
},
{
"command": [
"sysctl",
"-n",
"kern.memorystatus_vm_pressure_level"
],
"exit": 0,
"stdout": "1\n",
"stderr": ""
}
]
}
@@ -0,0 +1,134 @@
-- The C compiler identification is GNU 16.2.0
-- The CXX compiler identification is GNU 16.2.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /opt/homebrew/bin/x86_64-w64-mingw32-gcc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /opt/homebrew/bin/x86_64-w64-mingw32-g++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done (0.7s)
-- Generating done (0.1s)
-- Build files have been written to: <HOME>/betterxen-473-a/build-shims
[ 2%] Building CXX object runtime_veh/CMakeFiles/bx_runtime_veh.dir/runtime_veh.cpp.obj
[ 2%] Building CXX object win32_bridge/CMakeFiles/ntuser_msg_1_0.dir/empty_forwarder.cpp.obj
[ 4%] Linking CXX shared library ../bin/ext-ms-win-rtcore-ntuser-message-l1-1-0.dll
[ 4%] Built target ntuser_msg_1_0
[ 5%] Building CXX object win32_bridge/CMakeFiles/ntuser_msg_ansi_1_0.dir/empty_forwarder.cpp.obj
[ 7%] Linking CXX shared library ../bin/bx_runtime_veh.dll
[ 7%] Built target bx_runtime_veh
[ 8%] Building CXX object win32_bridge/CMakeFiles/ntuser_win_1_0.dir/empty_forwarder.cpp.obj
[ 10%] Linking CXX shared library ../bin/ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0.dll
[ 10%] Built target ntuser_msg_ansi_1_0
[ 11%] Building CXX object win32_bridge/CMakeFiles/ntuser_win_ansi_1_0.dir/empty_forwarder.cpp.obj
[ 13%] Linking CXX shared library ../bin/ext-ms-win-rtcore-ntuser-window-l1-1-0.dll
[ 13%] Built target ntuser_win_1_0
[ 14%] Building CXX object xmem/CMakeFiles/xmem.dir/xmem.cpp.obj
[ 15%] Linking CXX shared library ../bin/ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0.dll
[ 15%] Built target ntuser_win_ansi_1_0
[ 17%] Building CXX object xcrdapi/CMakeFiles/xcrdapi.dir/xcrdapi.cpp.obj
[ 18%] Building CXX object xmem/CMakeFiles/xmem.dir/physical_pages.cpp.obj
[ 20%] Linking CXX shared library ../bin/XCRDAPI.dll
[ 20%] Built target xcrdapi
[ 21%] Building CXX object xg_xs/CMakeFiles/xg_xs.dir/xg_xs.cpp.obj
[ 23%] Linking CXX shared library ../bin/xmem.dll
[ 23%] Built target xmem
[ 24%] Building CXX object xgameruntime/CMakeFiles/xgameruntime.dir/xgameruntime.cpp.obj
[ 26%] Linking CXX shared library ../bin/xg_xs.dll
[ 26%] Built target xg_xs
[ 27%] Building CXX object gameinput/CMakeFiles/gameinput.dir/gameinput.cpp.obj
[ 28%] Linking CXX shared library ../bin/GameInput.dll
[ 28%] Built target gameinput
[ 30%] Building CXX object xgameruntime/CMakeFiles/xgameruntime.dir/task_queue.cpp.obj
[ 31%] Building CXX object xgameruntime/CMakeFiles/xgameruntime.dir/com_dispatch.cpp.obj
[ 33%] Building CXX object audio/CMakeFiles/acphal.dir/acphal.cpp.obj
[ 34%] Linking CXX shared library ../bin/xgameruntime.dll
[ 34%] Built target xgameruntime
[ 36%] Building CXX object audio/CMakeFiles/xapu.dir/xapu.cpp.obj
[ 37%] Linking CXX shared library ../bin/AcpHal.dll
[ 37%] Built target acphal
[ 39%] Building CXX object audio/CMakeFiles/chad.dir/chad.cpp.obj
[ 40%] Linking CXX shared library ../bin/xapu.dll
[ 40%] Built target xapu
[ 42%] Building CXX object conformance/test_d3dmetal_gpu_limits/CMakeFiles/test_d3dmetal_gpu_limits.dir/main.cpp.obj
[ 43%] Linking CXX shared library ../bin/chad.dll
[ 43%] Built target chad
[ 44%] Building CXX object conformance/test_shim_exports/CMakeFiles/test_shim_exports.dir/main.cpp.obj
[ 46%] Linking CXX executable ../../bin/test_shim_exports.exe
[ 46%] Built target test_shim_exports
[ 47%] Building CXX object conformance/test_system32_staging/CMakeFiles/test_system32_staging.dir/main.cpp.obj
[ 49%] Linking CXX executable ../../bin/test_d3dmetal_gpu_limits.exe
[ 49%] Built target test_d3dmetal_gpu_limits
[ 50%] Building CXX object conformance/test_veh_clwb/CMakeFiles/test_veh_clwb.dir/main.cpp.obj
[ 52%] Linking CXX executable ../../bin/test_system32_staging.exe
[ 52%] Built target test_system32_staging
[ 53%] Building CXX object conformance/test_veh_clwb/CMakeFiles/test_veh_unhandled.dir/main_unhandled.cpp.obj
[ 55%] Linking CXX executable ../../bin/test_veh_clwb.exe
[ 55%] Built target test_veh_clwb
[ 56%] Building CXX object conformance/test_xcrdapi/CMakeFiles/test_xcrdapi.dir/main.cpp.obj
[ 57%] Linking CXX executable ../../bin/test_veh_unhandled.exe
[ 57%] Built target test_veh_unhandled
[ 59%] Building CXX object conformance/test_xg_xs/CMakeFiles/test_xg_xs.dir/main.cpp.obj
[ 60%] Linking CXX executable ../../bin/test_xcrdapi.exe
[ 60%] Built target test_xcrdapi
[ 62%] Building CXX object conformance/test_xgameruntime/CMakeFiles/test_xgameruntime.dir/main.cpp.obj
[ 63%] Linking CXX executable ../../bin/test_xg_xs.exe
[ 63%] Built target test_xg_xs
[ 65%] Building CXX object conformance/test_xgameruntime/CMakeFiles/test_xgameruntime_unentitled.dir/main.cpp.obj
[ 66%] Linking CXX executable ../../bin/test_xgameruntime.exe
[ 66%] Built target test_xgameruntime
[ 68%] Building CXX object conformance/test_xmem/CMakeFiles/test_xmem.dir/main.cpp.obj
[ 69%] Linking CXX executable ../../bin/unentitled/test_xgameruntime.exe
[ 69%] Built target test_xgameruntime_unentitled
[ 71%] Building CXX object conformance/test_xmem_physical/CMakeFiles/test_xmem_physical.dir/main.cpp.obj
[ 72%] Linking CXX executable ../../bin/test_xmem.exe
[ 72%] Built target test_xmem
[ 73%] Building CXX object win32_bridge/CMakeFiles/psm_appnotify_1_0.dir/psm_appnotify.cpp.obj
[ 75%] Linking CXX executable ../../bin/test_xmem_physical.exe
[ 75%] Built target test_xmem_physical
[ 76%] Building CXX object win32_bridge/CMakeFiles/psm_appnotify_1_1.dir/psm_appnotify.cpp.obj
[ 78%] Linking CXX shared library ../bin/api-ms-win-core-psm-appnotify-l1-1-0.dll
[ 78%] Built target psm_appnotify_1_0
[ 79%] Building CXX object d3d12_xs/CMakeFiles/d3d12_xs.dir/d3d12_xs.cpp.obj
[ 81%] Linking CXX shared library ../bin/api-ms-win-core-psm-appnotify-l1-1-1.dll
[ 81%] Built target psm_appnotify_1_1
[ 82%] Building CXX object d3d12_xs/CMakeFiles/d3d12_xs.dir/proxy.cpp.obj
[ 84%] Building CXX object d3d12_xs/CMakeFiles/d3d12_xs.dir/proxy_generated.cpp.obj
[ 85%] Building CXX object conformance/test_audio_input/CMakeFiles/test_audio_input.dir/main.cpp.obj
[ 86%] Linking CXX shared library ../bin/d3d12_xs.dll
[ 86%] Built target d3d12_xs
[ 88%] Building CXX object conformance/test_win32_bridge/CMakeFiles/test_win32_bridge.dir/main.cpp.obj
[ 89%] Linking CXX executable ../../bin/test_audio_input.exe
[ 89%] Built target test_audio_input
[ 91%] Building CXX object conformance/test_apiset_resolution/CMakeFiles/test_apiset_resolution.dir/main.cpp.obj
[ 92%] Linking CXX executable ../../bin/test_apiset_resolution.exe
[ 92%] Built target test_apiset_resolution
[ 94%] Building CXX object conformance/test_d3d12_xs/CMakeFiles/test_d3d12_xs.dir/main.cpp.obj
[ 95%] Linking CXX executable ../../bin/test_win32_bridge.exe
[ 95%] Built target test_win32_bridge
[ 97%] Building CXX object conformance/test_integration_boot/CMakeFiles/test_integration_boot.dir/main.cpp.obj
[ 98%] Linking CXX executable ../../bin/test_d3d12_xs.exe
[ 98%] Built target test_d3d12_xs
[100%] Linking CXX executable ../../bin/test_integration_boot.exe
[100%] Built target test_integration_boot
=== Verifying built PE32+ DLL Export Directories against abi/defs/*.def ===
OK AcpHal.dll (9 exact exports verified)
OK GameInput.dll (1 exact exports verified)
OK XCRDAPI.dll (1 exact exports verified)
OK api-ms-win-core-psm-appnotify-l1-1-0.dll (2 exact exports verified)
OK api-ms-win-core-psm-appnotify-l1-1-1.dll (2 exact exports verified)
OK bx_runtime_veh.dll (6 exact exports verified)
OK chad.dll (5 exact exports verified)
OK d3d12_xs.dll (4 exact exports verified)
OK ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0.dll (2 exact exports verified)
OK ext-ms-win-rtcore-ntuser-message-l1-1-0.dll (1 exact exports verified)
OK ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0.dll (3 exact exports verified)
OK ext-ms-win-rtcore-ntuser-window-l1-1-0.dll (1 exact exports verified)
OK xapu.dll (5 exact exports verified)
OK xg_xs.dll (2 exact exports verified)
OK xgameruntime.dll (49 exact exports verified)
OK xmem.dll (15 exact exports verified)
Verified 16 PE32+ shim DLLs (108 exact exports, 0 extra, 0 forbidden MinGW imports) in <HOME>/betterxen-473-a/build-shims/bin
@@ -0,0 +1,2 @@
Compiling bx-cli v0.2.0 (<HOME>/betterxen-473-a/launcher/crates/bx-cli)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.42s
@@ -0,0 +1,7 @@
Checking dxbc-accc v0.2.0 (<HOME>/betterxen-473-a/shader-transpiler/crates/dxbc-accc)
Compiling libc v0.2.191
Checking d3dmetal-harness v0.2.0 (<HOME>/betterxen-473-a/shader-transpiler/crates/d3dmetal-harness)
Checking bx-probe v0.2.0 (<HOME>/betterxen-473-a/launcher/crates/bx-probe)
Checking bx-telemetry v0.2.0 (<HOME>/betterxen-473-a/launcher/crates/bx-telemetry)
Checking bx-cli v0.2.0 (<HOME>/betterxen-473-a/launcher/crates/bx-cli)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.29s
@@ -0,0 +1,142 @@
Compiling dxbc-accc v0.2.0 (<HOME>/betterxen-473-a/shader-transpiler/crates/dxbc-accc)
Compiling d3dmetal-harness v0.2.0 (<HOME>/betterxen-473-a/shader-transpiler/crates/d3dmetal-harness)
Compiling bx-telemetry v0.2.0 (<HOME>/betterxen-473-a/launcher/crates/bx-telemetry)
Compiling bx-probe v0.2.0 (<HOME>/betterxen-473-a/launcher/crates/bx-probe)
Compiling libc v0.2.191
Compiling bx-cli v0.2.0 (<HOME>/betterxen-473-a/launcher/crates/bx-cli)
Finished `test` profile [unoptimized + debuginfo] target(s) in 2.81s
Running unittests src/main.rs (target/debug/deps/bx_cli-2151914d755a0d54)
running 18 tests
test stage::tests::system32_is_under_drive_c ... ok
test stage::tests::closure_follows_shim_imports_only ... ok
test stage::tests::uninitialized_prefix_is_an_error_not_a_skip ... ok
test stage::tests::copies_then_leaves_identical_copy_alone ... ok
test tests::bottle_mode_passes_overrides_and_backend_as_launcher_options ... ok
test tests::converts_unix_path_to_wine_z_drive ... ok
test tests::formats_clwb_summary_lines ... ok
test tests::isolated_env_strips_secrets_and_pins_path ... ok
test tests::parses_run_arguments ... ok
test stage::tests::missing_shim_is_reported_and_nothing_is_staged ... ok
test stage::tests::writes_only_inside_system32 ... ok
test stage::tests::stages_the_runtime_and_its_shim_dependency ... ok
test stage::tests::replaces_an_older_copy ... ok
test supervise::tests::classifies_exit_timeout_and_signal ... ok
test tests::a_timeout_cleans_up_a_bottle_outside_the_default_directory ... ok
test supervise::tests::an_idle_server_is_accepted_only_when_the_wait_succeeds ... ok
test supervise::tests::a_timeout_stops_children_that_ignore_sigterm ... ok
test tests::a_timeout_cleans_up_a_managed_bottle_private_stub_created_on_first_launch ... ok
test result: ok. 18 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.65s
Running unittests src/lib.rs (target/debug/deps/bx_probe-395eaa3c3f91592a)
running 1 test
test tests::classifies_tracks_accurately ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running unittests src/lib.rs (target/debug/deps/bx_telemetry-314c6b3d802f702b)
running 4 tests
test tests::aggregates_stub_and_veh_events ... ok
test tests::uses_highest_counter_from_sampled_clwb_records ... ok
test tests::preserves_clwb_record_count_without_valid_counters ... ok
test tests::collects_unhandled_exceptions_in_log_order ... ok
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running unittests src/lib.rs (target/debug/deps/d3dmetal_harness-be2050e4ff5342c1)
running 22 tests
test kernel::tests::no_expected_word_equals_the_sentinel ... ok
test framework::tests::environment_wins_over_crossover ... ok
test framework::tests::resolves_directory_or_binary ... ok
test macho::tests::rejects_unknown_truncated_and_oversized_headers ... ok
test framework::tests::unresolved_request_does_not_fall_back ... ok
test framework::tests::crossover_default_then_absent ... ok
test macho::tests::universal_32_and_64_bit_entries ... ok
test kernel::tests::matches_independently_computed_values ... ok
test framework::tests::explicit_path_wins_over_environment_and_crossover ... ok
test macho::tests::thin_x86_64_and_arm64 ... ok
test report::tests::device_removal_is_reported_with_its_reason ... ok
test report::tests::init_failure_and_failed_steps_take_precedence ... ok
test report::tests::rejects_malformed_and_unversioned_output ... ok
test report::tests::parses_a_complete_report ... ok
test report::tests::reports_every_mismatch_and_the_first_one ... ok
test report::tests::untouched_sentinel_means_the_kernel_did_not_run ... ok
test report::tests::unfinished_or_foreign_dispatch_is_incomplete ... ok
test tests::rejects_a_framework_without_an_x86_64_slice ... ok
test tests::embedded_kernel_is_an_sm_6_6_compute_dxil_container ... ok
test runner::tests::passes_the_framework_and_only_allowlisted_environment ... ok
test runner::tests::kills_a_probe_that_exceeds_the_timeout ... ok
test runner::tests::a_descendant_holding_the_pipes_cannot_outlast_the_deadline ... ok
test result: ok. 22 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.51s
Running unittests src/main.rs (target/debug/deps/bx_d3dmetal_harness-11f25afb9b566af7)
running 2 tests
test tests::parses_run_options ... ok
test tests::rejects_bad_options ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running tests/live_d3dmetal.rs (target/debug/deps/live_d3dmetal-6d63df8591429451)
running 1 test
test sm_6_6_compute_readback_matches_host_values ... ignored, needs a user-supplied D3DMetal.framework and BX_D3DMETAL_PROBE
test result: ok. 0 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running unittests src/lib.rs (target/debug/deps/dxbc_accc-919debdd3ca67e95)
running 19 tests
bx-shader event=prepare status=unsupported detail=no_dxil_passthrough kind=accc_only(3) stage=compute(6) sm_major=6 sm_minor=0 container_size=148 dxil_chunk_size=0 accc_chunk_size=104 has_root_signature=0 digest=abababababababababababababababab fspx=1 fspx_version=1 sections=0@64+8,1@72+12,6@84+16,7@100+4 rdna_off=84 rdna_size=16
test tests::c_abi_legacy_is_unsupported_and_invalid_inputs_allocate_nothing ... ok
test tests::classifies_synthetic_dxil_cs_6_6 ... ok
test tests::c_abi_zero_bitcode_dxil_returns_invalid ... ok
test tests::c_abi_inspect_and_passthrough_round_trip ... ok
test tests::dxil_bitcode_offset_is_relative_to_bitcode_header ... ok
test tests::classifies_synthetic_legacy_shdr ... ok
bx-shader event=prepare status=unsupported detail=no_dxil_passthrough kind=accc_only(3) stage=compute(6) sm_major=6 sm_minor=0 container_size=112 dxil_chunk_size=0 accc_chunk_size=40 has_root_signature=0 digest=abababababababababababababababab fspx=1 fspx_version=1 sections=none rdna_off=none rdna_size=none
test tests::classifies_synthetic_accc_fspx_magic_only ... ok
test tests::c_abi_empty_dxil_chunk_returns_invalid ... ok
test tests::dxil_stage_wins_over_fspx_stage_in_dual_container ... ok
test tests::c_abi_accc_only_is_unsupported_and_logged ... ok
test tests::extracts_synthetic_fspx_sections_stage_and_rdna_bounds ... ok
test tests::prepare_copies_container_size_not_trailing_bytes ... ok
test tests::prepare_passes_dxil_through_when_fspx_is_malformed ... ok
test tests::rejects_invalid_magic_and_short_headers ... ok
test tests::later_fspx_stage_is_used_when_earlier_table_has_none ... ok
test tests::rejects_truncated_tables_and_chunk_bounds ... ok
test tests::rejects_malformed_fspx_sections ... ok
test tests::truncated_prefixes_do_not_panic ... ok
test tests::fspx_section_count_is_bounded ... ok
test result: ok. 19 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests bx_probe
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests bx_telemetry
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests d3dmetal_harness
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests dxbc_accc
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
@@ -0,0 +1,5 @@
target/debug/bx-cli: Mach-O 64-bit executable arm64
arm64
target/debug/bx-cli:
/usr/lib/libiconv.2.dylib (compatibility version 7.0.0, current version 7.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1356.0.0)
@@ -0,0 +1,2 @@
docs hygiene: 2706 tracked files checked, 0 problem(s)
Validated candidate with temporary index; real index untouched.
@@ -0,0 +1,35 @@
{
"archived_files_hash_verified": 2481,
"baseline_source_sha256": "33e90bfee89e812f48990613cd74ced56473e5c3fc5d973f2ba1116090646a0c",
"proprietary_runtime_binaries": "none found in research package paths",
"source_hashes": {
"allocation-profiling/README.md": "739daa7a30f46776c9a71a8182793de903306df29a61a3e9d55119aa067d347f",
"allocation-profiling/allocator-assessment.md": "d277277ba0ae6b1c79e578bc339739435e8c6113ffc508692021f78225710918",
"allocation-profiling/analyze.py": "4720f4090d2d70f8cbc8d435c22ad72381c5038e01687c961c37d263e44c36c9",
"allocation-profiling/archive.py": "98e14b282e52793b2d6efae8d05f044ee39f2d110bef611b012ee1ac8e2608e1",
"allocation-profiling/footprint-findings.md": "8411ee8be5eadfc76d928f52ae94d3070064ff1da682748b73d718e0d6d57450",
"allocation-profiling/handoff-464.md": "0c470279b1f67b01c96beeadf43f28f44734237547c6a5d3bfc258e11876ff4f",
"allocation-profiling/inventory/README.md": "acb326d25398f4cd4eceb75d51019572d70638c7536feab4ce532063479e44b4",
"allocation-profiling/inventory/frozen-phase2/README.md": "efda0c4097029cea2e53b844937a8f4814a476ba8a94db6be536bd2a8f47c58a",
"allocation-profiling/inventory/frozen-phase2/concurrent-review.md": "b261ced32e02ae3044800e6a68f4c84b7d290fb1e02f7d1592ad29c76eb6c8ee",
"allocation-profiling/inventory/frozen-phase2/observe.cpp": "83ab36da38de6f6ac2f4e1f2fade3ad2f9abbe95b4750f2f17e17d4bd8451cd6",
"allocation-profiling/inventory/frozen-phase2/probe.cpp": "fbe300e6b9f9b88a061ef80778a7ffbb712a82d0720002693b0892d1329bee9e",
"allocation-profiling/inventory/frozen-phase2/review.md": "6c445ea1865dab70088873de4db1dc202b46aaa0984c4496299d5a732ac23637",
"allocation-profiling/inventory/frozen-phase2/run.py": "97f5b9cdaa402cfa91a67054388dd087804dcd20d22cee736ef797534269fccc",
"allocation-profiling/inventory/frozen-phase2/summarize.py": "0f13e8f3db5837e4e579e2ab1e78b284a7321b52c51a8bc8f18fb62f010703da",
"allocation-profiling/inverted-ownership.md": "e381557d84b2d45b68ecca8e4ea5e9c353b0a1d9c5bcea0cdd09d9455a9de79c",
"allocation-profiling/memory.cpp": "d3747cdefb77bdaa0a570871895dc5cdf9683c4e807eff383d7444425184cf74",
"allocation-profiling/observe.cpp": "2bb6647b16bcd9c47d2e75467fbd3e54e1cb8c00ad72b08d7ed76564e07b6475",
"allocation-profiling/pool.cpp": "a265b5f78ab854f1f6936605f872b6cff4abecce6ce71e3d184b1a6605df1989",
"allocation-profiling/pooling-findings.md": "e31a7a64ae935341ff56deba2c0aa109d9a2ed06bc2fa73c4110f750aea571a1",
"allocation-profiling/report.md": "78fcccb2c8b9b4962ab327ef830711f6f049459ffcc084ecdae72abdc8eb48aa",
"allocation-profiling/review-handoff.md": "6e3cbbb7203792655b3df419d8bb7d1275c358ff7b86b49d1603f36002908934",
"allocation-profiling/run.py": "8c7ea0b1ed5046ad25a5830d2c2c0982fa24a09ddb34dfae5edc5ce1a117878a",
"allocation-profiling/support.h": "df6ba2201c120c80e3ce26ae0b1d21d05ea69149e0ff25c88b0abb8e1446ae69",
"gpu-correctness/contracts/resource-placement-lifetime.md": "bbbc82d5ca2e6e8c7aa66de6003f16f4861d3bb93bfbb665d688e18e2b61dfc6",
"gpu-correctness/textures-and-resources/README.md": "56332fbc04985873d712fbf4bfa1dce61f9467f4ea82144c1925bac5dcab11c2",
"gpu-correctness/textures-and-resources/alias.cpp": "4034866cc66761076ab0ea87c7928b9d4f17bcb244adfae79c95078e4dfb614e",
"gpu-correctness/textures-and-resources/findings.md": "fd76afc2a6a0b5a976cda763a517861c36926f1bfbe69a59281edadcba8d9412",
"gpu-correctness/textures-and-resources/probe.cpp": "e9658020c77523916999f870ec595686fb1fe52d8271a8738dffe1dade07073a"
}
}
@@ -0,0 +1,63 @@
{
"utc": "2026-11-26T20:41:44.800058+00:00",
"status": "supplemental host observation; no guest workload executed",
"commands": [
{
"command": [
"/Applications/CrossOver.app/Contents/SharedSupport/CrossOver/bin/wineloader",
"--version"
],
"exit": 0,
"stdout": "wine-11.0-8726-g2e2f5fca349\n",
"stderr": ""
},
{
"command": [
"sysctl",
"-n",
"kern.memorystatus_vm_pressure_level"
],
"exit": 0,
"stdout": "1\n",
"stderr": ""
},
{
"command": [
"memory_pressure",
"-Q"
],
"exit": 0,
"stdout": "The system has 25769803776 (1572864 pages with a page size of 16384).\nSystem-wide memory free percentage: 61%\n",
"stderr": ""
},
{
"command": [
"sysctl",
"vm.swapusage"
],
"exit": 0,
"stdout": "vm.swapusage: total = 6144.00M used = 5180.38M free = 963.62M (encrypted)\n",
"stderr": ""
},
{
"command": [
"lipo",
"-archs",
"/opt/homebrew/Cellar/mingw-w64/14.0.0_3/toolchain-x86_64/bin/x86_64-w64-mingw32-g++"
],
"exit": 0,
"stdout": "arm64\n",
"stderr": ""
},
{
"command": [
"otool",
"-L",
"/opt/homebrew/Cellar/mingw-w64/14.0.0_3/toolchain-x86_64/bin/x86_64-w64-mingw32-g++"
],
"exit": 0,
"stdout": "/opt/homebrew/Cellar/mingw-w64/14.0.0_3/toolchain-x86_64/bin/x86_64-w64-mingw32-g++:\n\t/usr/lib/libiconv.2.dylib (compatibility version 7.0.0, current version 7.0.0)\n\t/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 2200.27.0)\n\t/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1359.0.0)\n",
"stderr": ""
}
]
}
@@ -0,0 +1,45 @@
{
"utc": "2026-11-26T20:59:11.067328+00:00",
"scope": "unchanged baseline CPU-only conformance; not GPU or Workstream A independent acceptance",
"cases": [
{
"name": "test_veh_clwb",
"command": [
"<HOME>/betterxen-473-a/target/debug/bx-cli",
"run",
"--prefix",
"/tmp/bx473-cpu-conformance/prefix",
"--shims",
"<HOME>/betterxen-473-a/build-shims/bin",
"--timeout",
"30",
"--log",
"/tmp/bx473-cpu-conformance/test_veh_clwb.jsonl",
"--exe",
"<HOME>/betterxen-473-a/build-shims/bin/test_veh_clwb.exe"
],
"exit": 0
},
{
"name": "test_shim_exports",
"command": [
"<HOME>/betterxen-473-a/target/debug/bx-cli",
"run",
"--prefix",
"/tmp/bx473-cpu-conformance/prefix",
"--shims",
"<HOME>/betterxen-473-a/build-shims/bin",
"--timeout",
"30",
"--log",
"/tmp/bx473-cpu-conformance/test_shim_exports.jsonl",
"--exe",
"<HOME>/betterxen-473-a/build-shims/bin/test_shim_exports.exe"
],
"exit": 0
}
],
"stop_exit": 1,
"wait_exit": 0,
"source_bottle_config_unchanged": true
}
@@ -0,0 +1,2 @@
bx-cli: already current /tmp/bx473-cpu-conformance/prefix/drive_c/windows/system32/bx_runtime_veh.dll
bx-cli: already current /tmp/bx473-cpu-conformance/prefix/drive_c/windows/system32/xgameruntime.dll
@@ -0,0 +1,6 @@
PASS: test_shim_exports (25 checks verified)
Trace summary of /tmp/bx473-cpu-conformance/test_shim_exports.jsonl:
Trace events : 1
clwb VEH traps : 0
ADX illegal ops : 0
@@ -0,0 +1 @@
{"ts_ms":521468327,"tid":36,"level":"INFO","sub":"runtime_veh","event":"attached","detail":"profile=lockhart"}
@@ -0,0 +1,2 @@
bx-cli: replaced /tmp/bx473-cpu-conformance/prefix/drive_c/windows/system32/bx_runtime_veh.dll
bx-cli: replaced /tmp/bx473-cpu-conformance/prefix/drive_c/windows/system32/xgameruntime.dll
@@ -0,0 +1,8 @@
CLWB traps observed: 6
xmem stats: limit=8192 MB committed=8192 bytes
PASS: test_veh_clwb
Trace summary of /tmp/bx473-cpu-conformance/test_veh_clwb.jsonl:
Trace events : 4
clwb VEH traps : at least 4 (sampled)
ADX illegal ops : 0
@@ -0,0 +1,4 @@
{"ts_ms":521464307,"tid":36,"level":"INFO","sub":"runtime_veh","event":"attached","detail":"profile=lockhart"}
{"ts_ms":521464309,"tid":36,"level":"INFO","sub":"runtime_veh","event":"clwb_trapped","detail":"rip=0x0000000140008715 len=4 total_traps=1"}
{"ts_ms":521464310,"tid":36,"level":"INFO","sub":"runtime_veh","event":"clwb_trapped","detail":"rip=0x0000000140008719 len=5 total_traps=2"}
{"ts_ms":521464310,"tid":36,"level":"INFO","sub":"runtime_veh","event":"clwb_trapped","detail":"rip=0x0000000140008729 len=5 total_traps=4"}
@@ -0,0 +1,151 @@
{
"status": "local verification; not independent acceptance",
"commands": [
{
"command": "cargo fmt --all -- --check",
"exit": 0
},
{
"command": "CARGO_BUILD_JOBS=2 cargo clippy --locked --workspace --all-targets -- -D warnings",
"exit": 0
},
{
"command": "CARGO_BUILD_JOBS=2 cargo test --locked --workspace",
"exit": 0,
"passed": 66,
"failed": 0,
"ignored": 1
},
{
"command": "BX_BUILD_JOBS=2 scripts/build-shims.sh",
"exit": 0,
"shim_dlls": 16,
"exact_exports": 108
},
{
"command": "CARGO_BUILD_JOBS=2 cargo build --locked -p bx-cli; file/lipo/otool target/debug/bx-cli",
"exit": 0,
"architecture": "arm64"
},
{
"command": "python3 scripts/audit/docs_hygiene.py --require-yaml with temporary index including candidate files",
"exit": 0,
"real_git_index_changed": false
}
],
"files": [
{
"path": "cargo-fmt.txt",
"original_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"archived_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"home_path_redacted": false
},
{
"path": "cargo-clippy.txt",
"original_sha256": "6aaf5f4c9a7ffae65ab7ace312852d5f1f67fd65802dc710b09613c903f19583",
"archived_sha256": "fda20f022b8084a8ea8e492579c8f22842ba48a812bcabe7afb7f6226e52706b",
"home_path_redacted": true
},
{
"path": "cargo-test.txt",
"original_sha256": "66f32380e82dd8c0ec08c844e11faaebd200c3d3ba1f7697d42bda9a4e45782e",
"archived_sha256": "01c7976665860f72a578de5fc4e5e881bb6117ad8f149416f155dab57d3ffd45",
"home_path_redacted": true
},
{
"path": "build-shims.txt",
"original_sha256": "d9cbe50fd72f9cb19eb03ff670cc8d174647c64e83a8ae7d92c3374f37af0485",
"archived_sha256": "83f4903a19e525128e515fd329a65b38b9d0b3f405b87f3bc401c868af2d110c",
"home_path_redacted": true
},
{
"path": "cargo-build-cli.txt",
"original_sha256": "3b4101fc411435c3c728e66d214beed08f30f0b5f5842cc310e0c430098c54b6",
"archived_sha256": "e5fc11e28ee08f276c2ebe25d7c71a04fdc2f130d34ee3e15b7704cf504258b8",
"home_path_redacted": true
},
{
"path": "cli-architecture.txt",
"original_sha256": "7d202b53ca40b3df4fe07b9933ea0a5672077473018c6ad9a1fc192eedbbb52b",
"archived_sha256": "7d202b53ca40b3df4fe07b9933ea0a5672077473018c6ad9a1fc192eedbbb52b",
"home_path_redacted": false
},
{
"path": "docs-hygiene-final.txt",
"original_sha256": "2732bf7bf4dd589f80067d7408e18e60bb454968ab951698cf544f4e3094e46b",
"archived_sha256": "2732bf7bf4dd589f80067d7408e18e60bb454968ab951698cf544f4e3094e46b",
"home_path_redacted": false
},
{
"path": "hash-audit.json",
"original_sha256": "0a1c3846353f9f4c71a0717b39246ec67990127538d5dcfaafada33e1b3dc9d3",
"archived_sha256": "0a1c3846353f9f4c71a0717b39246ec67990127538d5dcfaafada33e1b3dc9d3",
"home_path_redacted": false
},
{
"path": "host-followup.json",
"original_sha256": "b262d86f4d40b733abb38804eb51dd68dc411fdf7d1452404a337e83661cd0cc",
"archived_sha256": "b262d86f4d40b733abb38804eb51dd68dc411fdf7d1452404a337e83661cd0cc",
"home_path_redacted": false
},
{
"path": "23gb-cap-receipt.json",
"original_sha256": "8dee3dbc7494fa67c34a78732e05e79e1b604ae34fbf6d97f9d300afe500c5e9",
"archived_sha256": "8dee3dbc7494fa67c34a78732e05e79e1b604ae34fbf6d97f9d300afe500c5e9",
"home_path_redacted": false
},
{
"path": "test_shim_exports-stderr.txt",
"original_sha256": "fe6fe9d95d7b86f1474402208a1d7b1c3ddd1be1fb3091c873356157a4d6d485",
"archived_sha256": "fe6fe9d95d7b86f1474402208a1d7b1c3ddd1be1fb3091c873356157a4d6d485",
"home_path_redacted": false
},
{
"path": "test_veh_clwb-stdout.txt",
"original_sha256": "dfb2b1a587f0b0249af05ddd32d151bfd99696c6501a9520793af01a3ec046e6",
"archived_sha256": "dfb2b1a587f0b0249af05ddd32d151bfd99696c6501a9520793af01a3ec046e6",
"home_path_redacted": false
},
{
"path": "test_veh_clwb.jsonl",
"original_sha256": "bca91c4ae5c9c4c5a8a1813d56d0d972fc1f8a0ff1858ea1ff309c2d984d93e5",
"archived_sha256": "bca91c4ae5c9c4c5a8a1813d56d0d972fc1f8a0ff1858ea1ff309c2d984d93e5",
"home_path_redacted": false
},
{
"path": "test_shim_exports-stdout.txt",
"original_sha256": "62cc84b4c5b68a0b338b8d42ec3ca6cd01db6aa520f63b9bff0b1ba4fc94f173",
"archived_sha256": "62cc84b4c5b68a0b338b8d42ec3ca6cd01db6aa520f63b9bff0b1ba4fc94f173",
"home_path_redacted": false
},
{
"path": "test_shim_exports.jsonl",
"original_sha256": "898843eaf10aa33637833ba7331be166136197a375c78fe2d389d29504051c76",
"archived_sha256": "898843eaf10aa33637833ba7331be166136197a375c78fe2d389d29504051c76",
"home_path_redacted": false
},
{
"path": "test_veh_clwb-stderr.txt",
"original_sha256": "0b02b527929196a2b4377a0fdb298acd6bb7ff15d941c45f00f18f82be00030c",
"archived_sha256": "0b02b527929196a2b4377a0fdb298acd6bb7ff15d941c45f00f18f82be00030c",
"home_path_redacted": false
},
{
"path": "receipt.json",
"original_sha256": "62fb59a5d4b65c0aa2b7c6f3826fb62f02eb0156cfac08566155300cc6324157",
"archived_sha256": "5e1865e388a8a1a47cd230182d1a26defa5852dbc62a40fe0ccb3c38672ffc95",
"home_path_redacted": true
}
],
"notes": [
"Initial tracked-only documentation check reported the untracked new index link as missing; final temporary-index candidate check passed.",
"Initial setup/compiler failures and pressure interruptions are retained separately.",
"Post-run Bottle section insertion correction was checked structurally; a post-correction guest launch is not claimed.",
"No native-first GPU suite was run from the retired native workspace; no ignored test counts as GPU verification."
],
"cpu_conformance": {
"test_veh_clwb": 0,
"test_shim_exports": 0,
"scope": "unchanged baseline CPU programs; not a GPU or independent Workstream A certification"
}
}
@@ -0,0 +1,41 @@
{
"originals_unchanged": true,
"redaction": "JSON diagnostics replace local home-directory prefix with <HOME>; raw stdout/stderr unchanged",
"files": [
{
"path": "receipt.json",
"bytes": 54583,
"original_sha256": "c03015fc49bd289c5a6c67d35797df3137fdd71d76a7640f37ee9bf261d39dee",
"archived_sha256": "dd2da05ebf1727632cae49b458432cc65780f39509f35b563e2471e978fa7ab0",
"redacted": true
},
{
"path": "source/memory.cpp",
"bytes": 3797,
"original_sha256": "d3747cdefb77bdaa0a570871895dc5cdf9683c4e807eff383d7444425184cf74",
"archived_sha256": "d3747cdefb77bdaa0a570871895dc5cdf9683c4e807eff383d7444425184cf74",
"redacted": false
},
{
"path": "source/observe.cpp",
"bytes": 906,
"original_sha256": "2bb6647b16bcd9c47d2e75467fbd3e54e1cb8c00ad72b08d7ed76564e07b6475",
"archived_sha256": "2bb6647b16bcd9c47d2e75467fbd3e54e1cb8c00ad72b08d7ed76564e07b6475",
"redacted": false
},
{
"path": "source/run.py",
"bytes": 11788,
"original_sha256": "de45f1509dcf5f8536176a4befe6456130d1020964c21b70706de9c4a65460eb",
"archived_sha256": "de45f1509dcf5f8536176a4befe6456130d1020964c21b70706de9c4a65460eb",
"redacted": false
},
{
"path": "source/support.h",
"bytes": 14678,
"original_sha256": "18795b461034a39103db578471a7c932e1ade49e80f4cf92574c815880f8751c",
"archived_sha256": "18795b461034a39103db578471a7c932e1ade49e80f4cf92574c815880f8751c",
"redacted": false
}
]
}
@@ -0,0 +1,215 @@
{
"protocol": "A-local-2",
"suite": "memory",
"utc": "2026-11-26T20:27:34.436329+00:00",
"independent_review": "pending",
"environment": {
"ROSETTA_ADVERTISE_AVX": "1",
"CX_GRAPHICS_BACKEND": "d3dmetal",
"WINEDEBUG": "-all"
},
"sources": {
"docs/research/d3dmetal-zero-copy/allocation-profiling/memory.cpp": "d3747cdefb77bdaa0a570871895dc5cdf9683c4e807eff383d7444425184cf74",
"docs/research/d3dmetal-zero-copy/allocation-profiling/support.h": "18795b461034a39103db578471a7c932e1ade49e80f4cf92574c815880f8751c",
"docs/research/d3dmetal-zero-copy/allocation-profiling/observe.cpp": "2bb6647b16bcd9c47d2e75467fbd3e54e1cb8c00ad72b08d7ed76564e07b6475",
"docs/research/d3dmetal-zero-copy/allocation-profiling/run.py": "de45f1509dcf5f8536176a4befe6456130d1020964c21b70706de9c4a65460eb"
},
"baseline_sha256": "33e90bfee89e812f48990613cd74ced56473e5c3fc5d973f2ba1116090646a0c",
"tools": {
"chip": {
"command": [
"sysctl",
"-n",
"machdep.cpu.brand_string"
],
"exit": 0,
"stdout": "Apple M4\n",
"stderr": "",
"seconds": 0.0027015000232495368
},
"ram": {
"command": [
"sysctl",
"-n",
"hw.memsize"
],
"exit": 0,
"stdout": "25769803776\n",
"stderr": "",
"seconds": 0.0022199160302989185
},
"host": {
"command": [
"uname",
"-m"
],
"exit": 0,
"stdout": "arm64\n",
"stderr": "",
"seconds": 0.002099250035826117
},
"macos": {
"command": [
"sw_vers"
],
"exit": 0,
"stdout": "ProductName:\t\tmacOS\nProductVersion:\t\t27.0\nBuildVersion:\t\t26A428\n",
"stderr": "",
"seconds": 0.007060375006403774
},
"page": {
"command": [
"sysctl",
"-n",
"hw.pagesize"
],
"exit": 0,
"stdout": "16384\n",
"stderr": "",
"seconds": 0.0023932079784572124
},
"swap_before": {
"command": [
"sysctl",
"vm.swapusage"
],
"exit": 0,
"stdout": "vm.swapusage: total = 9216.00M used = 7723.38M free = 1492.62M (encrypted)\n",
"stderr": "",
"seconds": 0.0022041249903850257
},
"pressure_before": {
"command": [
"memory_pressure",
"-Q"
],
"exit": 0,
"stdout": "The system has 25769803776 (1572864 pages with a page size of 16384).\nSystem-wide memory free percentage: 67%\n",
"stderr": "",
"seconds": 0.0021060419967398047
},
"vm_before": {
"command": [
"vm_stat"
],
"exit": 0,
"stdout": "Mach Virtual Memory Statistics: (page size of 16384 bytes)\nPages free: 15258.\nPages active: 509205.\nPages inactive: 508837.\nPages speculative: 451.\nPages throttled: 0.\nPages wired down: 144529.\nPages purgeable: 4257.\n\"Translation faults\": 2192588579.\nPages copy-on-write: 97114814.\nPages zero filled: 1659357931.\nPages reactivated: 186249435.\nPages purged: 19163016.\nFile-backed pages: 370508.\nAnonymous pages: 647985.\nPages stored in compressor: 1210022.\nPages occupied by compressor: 355871.\nDecompressions: 146116435.\nCompressions: 183379486.\nPageins: 46889443.\nPageouts: 920818.\nSwapins: 1510131.\nSwapouts: 2396612.\n",
"stderr": "",
"seconds": 0.002023209002800286
},
"load_before": {
"command": [
"ps",
"-axo",
"pid,pcpu,comm"
],
"exit": 0,
"stdout": " PID %CPU COMM\n 1 0.0 /sbin/launchd\n 339 0.0 /usr/libexec/logd\n 342 0.0 /usr/libexec/UserEventAgent\n 344 0.0 /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/FSEvents.framework/Versions/A/Support/fseventsd\n 345 0.0 /System/Library/PrivateFrameworks/MediaRemote.framework/Support/mediaremoted\n 349 0.0 /usr/sbin/systemstats\n 353 0.0 /usr/libexec/configd\n 355 0.0 /System/Library/CoreServices/powerd.bundle/powerd\n 356 0.0 /usr/libexec/IOMFB_bics_daemon\n 360 0.0 /usr/libexec/remoted\n 364 0.0 /System/Library/PrivateFrameworks/CoreSpeech.framework/corespeechd_system\n 366 0.0 /usr/libexec/watchdogd\n 369 0.0 /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/Metadata.framework/Versions/A/Support/mds\n 371 0.0 /usr/libexec/kernelmanagerd\n 372 0.0 /usr/libexec/diskarbitrationd\n 376 0.0 /usr/sbin/syslogd\n 378 0.0 /usr/libexec/thermalmonitord\n 379 0.0 /System/Library/PrivateFrameworks/CoreDuetContext.framework/Resources/contextstored\n 380 0.0 /usr/libexec/xprotectd\n 381 0.1 /usr/libexec/opendirectoryd\n 382 0.0 /System/Library/PrivateFrameworks/ApplePushService.framework/apsd\n 383 0.0 /System/Library/CoreServices/launchservicesd\n 384 0.0 /usr/libexec/timed\n 385 0.0 /System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/Resources/usbmuxd\n 386 0.0 /usr/sbin/securityd\n 388 0.0 /usr/libexec/locationd\n 389 0.0 /usr/libexec/nesessionmanager\n 391 0.0 autofsd\n 392 0.0 /usr/libexec/dasd\n 393 0.0 /System/Library/PrivateFrameworks/Heimdal.framework/Helpers/kdc\n 396 0.0 /usr/sbin/distnoted\n 399 0.0 /System/Library/CoreServices/logind\n 400 0.0 /System/Library/PrivateFrameworks/GenerationalStorage.framework/Versions/A/Support/revisiond\n 401 0.0 /usr/sbin/KernelEventAgent\n 403 0.0 /usr/libexec/usermanagerd\n 406 0.0 /usr/sbin/notifyd\n 408 0.1 /usr/libexec/corebrightnessd\n 409 0.0 /System/Library/Frameworks/CoreMediaIO.framework/Versions/A/Resources/com.apple.cmio.registerassistantservice\n 412 13.4 /System/Library/PrivateFrameworks/SkyLight.framework/Resources/WindowServer\n 413 0.0 /System/Library/PrivateFrameworks/TCC.framework/Support/tccd\n 415 0.0 /usr/sbin/cfprefsd\n 416 0.0 /System/Library/CoreServices/loginwindow.app/Contents/MacOS/loginwindow\n 417 0.0 /usr/libexec/runningboardd\n 449 0.0 /System/Library/CoreServices/coreservicesd\n 461 0.1 /usr/libexec/clocksyncd\n 462 0.0 /System/Library/PrivateFrameworks/CoreAnalytics.framework/Support/analyticsd\n 463 0.0 /usr/libexec/lsd\n 465 0.0 /usr/sbin/mDNSResponder\n 469 0.0 /usr/libexec/apfsd\n 479 0.0 /usr/libexec/airportd\n 481 0.0 /usr/libexec/symptomsd\n 485 0.0 /System/Library/PrivateFrameworks/BiomeStreams.framework/Support/biomed\n 491 0.0 /System/Library/PrivateFrameworks/SystemStatusServer.framework/Support/systemstatusd\n 495 0.0 /usr/libexec/eligibilityd\n 499 0.0 /System/Library/CoreServices/TimeMachine/backupd\n 501 0.0 /usr/libexec/ApplicationFirewall/socketfilterfw\n 502 0.0 /usr/sbin/distnoted\n 503 0.0 /System/Library/Frameworks/Security.framework/Versions/A/XPCServices/authd.xpc/Contents/MacOS/authd\n 504 0.0 /usr/sbin/mDNSResponderHelper\n 505 0.0 /usr/libexec/syspolicyd\n 507 0.0 /usr/sbin/distnoted\n 509 0.0 /System/Library/PrivateFrameworks/BackgroundTaskManagement.framework/Resources/backgroundtaskmanagementd\n 514 0.0 /usr/sbin/distnoted\n 515 0.0 /usr/sbin/WirelessRadioManagerd\n 520 0.0 /usr/sbin/distnoted\n 528 0.0 /usr/libexec/com.apple.cmio.videodriverkithostextension.systemextension/Contents/MacOS/com.apple.cmio.videodriverkithostextension\n 530 0.0 /usr/libexec/cameracaptured\n 531 0.0 /usr/libexec/searchpartyd\n 532 0.0 /System/Library/Frameworks/CoreMediaIO.framework/Versions/A/Resources/UVCAssistant.systemextension/Contents/MacOS/UVCAssistant\n 533 0.0 /usr/sbin/coreaudiod\n 539 0.0 /usr/libexec/gamepolicyd\n 544 0.0 /usr/sbin/distnoted\n 549 0.0 /System/Library/CoreServices/appleeventsd\n 551 0.0 Core Audio Driver (BlackHole2ch.driver)\n 562 0.0 /System/Library/CoreServices/Software Update.app/Contents/Resources/suhelperd\n 570 0.0 /usr/sbin/distnoted\n 574 0.0 Core Audio Driver (VoicemodAudioDevice.driver)\n 576 0.0 /usr/libexec/modelmanagerd\n 578 0.0 /System/Library/Frameworks/LocalAuthentication.framework/Support/coreauthd\n 583 0.0 /usr/sbin/distnoted\n 584 0.0 /System/Library/DriverExtensions/com.apple.DriverKit-IOUserDockChannelSerial.dext/com.apple.DriverKit-IOUserDockChannelSerial\n 585 0.2 /System/Library/DriverExtensions/com.apple.DriverKit-AppleBCMWLAN.dext/com.apple.DriverKit-AppleBCMWLAN\n 586 0.0 /System/Library/DriverExtensions/com.apple.AppleUserHIDDrivers.dext/com.apple.AppleUserHIDDrivers\n 588 0.0 /usr/sbin/distnoted\n 592 0.0 /usr/libexec/audiomxd\n 599 0.0 /usr/Line truncated
"stderr": "",
"seconds": 0.016771959024481475
},
"wine_version": {
"command": [
"/Applications/CrossOver.app/Contents/SharedSupport/CrossOver/bin/wine",
"--version"
],
"exit": 0,
"stdout": "Product Name: CrossOver\nPublic Version: 26.3.0\nProduct Version: 26.3.0.39832\nBuild Tag: cxoffice-26.3.0rc2\nBuild Timestamp: 20260715T103801Z\n",
"stderr": "",
"seconds": 0.011262500018347055
},
"wine_build": {
"command": [
"/Applications/CrossOver.app/Contents/SharedSupport/CrossOver/bin/wine64",
"--version"
],
"exit": 127,
"stdout": "",
"stderr": "[Errno 2] No such file or directory: '/Applications/CrossOver.app/Contents/SharedSupport/CrossOver/bin/wine64'"
},
"rosetta": {
"command": [
"pkgutil",
"--pkg-info",
"com.apple.pkg.RosettaUpdateAuto"
],
"exit": 0,
"stdout": "package-id: com.apple.pkg.RosettaUpdateAuto\nversion: 1.0.0.0.1788432274\nvolume: /\nlocation: /\ninstall-time: 1791147684\n",
"stderr": "",
"seconds": 0.0960673340014182
},
"gcc": {
"command": [
"x86_64-w64-mingw32-g++",
"--version"
],
"exit": 0,
"stdout": "x86_64-w64-mingw32-g++ (GCC) 16.2.0\nCopyright (C) 2026 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n",
"stderr": "",
"seconds": 0.007127082964871079
},
"clang": {
"command": [
"xcrun",
"clang++",
"--version"
],
"exit": 0,
"stdout": "Apple clang version 17.0.0 (clang-1700.6.3.2)\nTarget: arm64-apple-darwin27.0.0\nThread model: posix\nInstalledDir: /Library/Developer/CommandLineTools/usr/bin\n",
"stderr": "",
"seconds": 0.017876834026537836
},
"sdk": {
"command": [
"xcrun",
"--show-sdk-version"
],
"exit": 0,
"stdout": "26.2\n",
"stderr": "",
"seconds": 0.00819662498543039
},
"python": {
"command": [
"python3",
"--version"
],
"exit": 0,
"stdout": "Python 3.14.3\n",
"stderr": "",
"seconds": 0.010497957991901785
},
"compiler_arch": {
"command": [
"file",
"/opt/homebrew/Cellar/mingw-w64/14.0.0_3/toolchain-x86_64/bin/x86_64-w64-mingw32-g++"
],
"exit": 0,
"stdout": "/opt/homebrew/Cellar/mingw-w64/14.0.0_3/toolchain-x86_64/bin/x86_64-w64-mingw32-g++: Mach-O 64-bit executable arm64\n",
"stderr": "",
"seconds": 0.003512167022563517
},
"build_pe": {
"command": [
"x86_64-w64-mingw32-g++",
"-std=c++20",
"-O2",
"-static",
"-static-libgcc",
"-static-libstdc++",
"-Wall",
"-Wextra",
"-Werror",
"<HOME>/betterxen-473-a/docs/research/d3dmetal-zero-copy/allocation-profiling/memory.cpp",
"-o",
"/private/tmp/bx473-a2-memory-smoke-02/a-probe.exe",
"-lkernel32"
],
"exit": 1,
"stdout": "",
"stderr": "In file included from <HOME>/betterxen-473-a/docs/research/d3dmetal-zero-copy/allocation-profiling/memory.cpp:4:\n<HOME>/betterxen-473-a/docs/research/d3dmetal-zero-copy/allocation-profiling/support.h:59:15: error: 'double frequency()' defined but not used [-Werror=unused-function]\n 59 | static double frequency() {\n | ^~~~~~~~~\n<HOME>/betterxen-473-a/docs/research/d3dmetal-zero-copy/allocation-profiling/support.h:54:15: error: 'double ticks()' defined but not used [-Werror=unused-function]\n 54 | static double ticks() {\n | ^~~~~\n<HOME>/betterxen-473-a/docs/research/d3dmetal-zero-copy/allocation-profiling/support.h:42:13: error: 'void report(HRESULT, const char*)' defined but not used [-Werror=unused-function]\n 42 | static void report(HRESULT h, const char *name) {\n | ^~~~~~\ncc1plus: all warnings being treated as errors\n",
"seconds": 1.0881754159927368
}
},
"cases": []
}
@@ -0,0 +1,110 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Workstream A protocol A2: correct baseline and retirement scope, not a copy
// detector.
#include "support.h"
#include <memory>
static void stage(const char *name, void *cpu = nullptr) {
std::printf("STAGE %s cpu_ptr=%p\n", name, cpu);
if (std::getchar() == EOF)
throw std::runtime_error("stage handshake lost");
}
int main(int argc, char **argv) {
setvbuf(stdout, nullptr, _IONBF, 0);
try {
if (argc != 3)
throw std::runtime_error("usage: memory cpu|cpu-plain|wb|upload BYTES");
std::string type = argv[1];
UINT64 bytes = std::strtoull(argv[2], nullptr, 10);
if (bytes != 64 * 1024 * 1024ULL && bytes != 256 * 1024 * 1024ULL &&
bytes != 1024 * 1024 * 1024ULL)
throw std::runtime_error("size outside common profile");
if (type != "cpu" && type != "cpu-plain" && type != "wb" &&
type != "upload")
throw std::runtime_error("type");
std::printf("MEMORY_A protocol=2 type=%s bytes=%llu\n", type.c_str(),
bytes);
std::unique_ptr<Context> c;
std::unique_ptr<Shader> shader;
std::unique_ptr<Queue> q;
Buffer output;
if (type != "cpu-plain") {
c = std::make_unique<Context>();
shader = std::make_unique<Shader>(*c);
q = std::make_unique<Queue>(c->device.p);
Buffer tiny;
tiny.allocate(c->device.p, 65536, "upload");
tiny.map();
std::memset(tiny.cpu, 0, 65536);
output.allocate(c->device.p, 65536, "wb", true);
output.map();
shader->dispatch(*q, tiny, output, 1, 0, 1);
// Dispose the warm-up command objects before baseline; keep matched
// pipeline/output.
q.reset();
tiny.release();
q = std::make_unique<Queue>(c->device.p);
}
stage("warm_baseline");
Sleep(500);
stage("baseline");
Buffer src;
void *cpu = nullptr;
if (type == "cpu" || type == "cpu-plain") {
cpu = VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE);
if (!cpu)
throw std::runtime_error("VirtualAlloc");
} else
src.allocate(c->device.p, bytes, type);
stage("created");
if (src.resource.p) {
src.map();
cpu = src.cpu;
}
stage("mapped", cpu);
auto p = static_cast<volatile uint32_t *>(cpu);
std::array<uint32_t, 256> expected{};
for (UINT64 i = 0; i < bytes / 4; ++i) {
uint32_t v = pattern(i, 0x24681357u);
p[i] = v;
expected[i % 256] ^= v + 0x10101u;
}
_mm_sfence();
stage("fully_initialized", cpu);
if (src.resource.p) {
shader->dispatch(*q, src, output, UINT(bytes / 4), 0x10101u, 1);
size_t matches = 0;
for (UINT i = 0; i < 256; ++i)
matches +=
static_cast<volatile uint32_t *>(output.cpu)[i] == expected[i];
std::printf(
"VERIFY full_consumption checksum_matches=%zu/256 words=%llu\n",
matches, bytes / 4);
if (matches != 256)
throw std::runtime_error("full-consumption checksum mismatch");
} else
std::puts("GPU_CONSUMPTION NOT_RUN CPU_allocation_control");
stage("gpu_complete", cpu);
if (src.resource.p)
src.release();
else if (!VirtualFree(cpu, 0, MEM_RELEASE))
throw std::runtime_error("VirtualFree");
cpu = nullptr;
stage("resources_released");
// Fence already completed; dispose all
// command-list/allocator/queue/fence/pipeline resources.
q.reset();
output.release();
shader.reset();
stage("commands_retired");
Sleep(500);
stage("retired_settled");
c.reset();
stage("device_released");
std::puts("END success");
return 0;
} catch (const std::exception &e) {
std::printf("END failure reason=%s\n", e.what());
return 1;
}
}
@@ -0,0 +1,23 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original macOS process accounting observer; native ARM64 only.
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <libproc.h>
#include <sys/resource.h>
#include <unistd.h>
int main(int argc, char **argv) {
if (argc != 2)
return 2;
rusage_info_v4 r{};
int pid = std::atoi(argv[1]);
int rc = proc_pid_rusage(pid, RUSAGE_INFO_V4,
reinterpret_cast<rusage_info_t *>(&r));
std::printf("{\"pid\":%d,\"return\":%d,\"errno\":%d,\"host_page_size\":%d,"
"\"phys_footprint\":%llu,\"resident_size\":%llu,\"wired_size\":%"
"llu,\"pageins\":%llu,\"max_phys_footprint\":%llu}\n",
pid, rc, rc ? errno : 0, getpagesize(), r.ri_phys_footprint,
r.ri_resident_size, r.ri_wired_size, r.ri_pageins,
r.ri_lifetime_max_phys_footprint);
return rc ? 1 : 0;
}
@@ -0,0 +1,194 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Workstream A local harness, version 2. Does not change shared protocols."""
import argparse
import fcntl
import hashlib
import json
import os
from pathlib import Path
import plistlib
import re
import shutil
import signal
import subprocess
import threading
import time
from datetime import datetime, timezone
def sha(p):
return hashlib.sha256(p.read_bytes()).hexdigest()
def capture(cmd, env, cwd, timeout=20):
start = time.monotonic()
try:
p = subprocess.run([str(v) for v in cmd], env=env, cwd=cwd,
capture_output=True, timeout=timeout)
return dict(command=[str(v) for v in cmd], exit=p.returncode,
stdout=p.stdout.decode(errors='replace'),
stderr=p.stderr.decode(errors='replace'), seconds=time.monotonic()-start)
except OSError as e:
return dict(command=[str(v) for v in cmd], exit=127, stdout='', stderr=str(e))
except subprocess.TimeoutExpired as e:
return dict(command=[str(v) for v in cmd], exit=124, timeout=True,
stdout=(e.stdout or b'').decode(errors='replace'),
stderr=(e.stderr or b'').decode(errors='replace'))
def main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('--bottle', required=True, type=Path)
ap.add_argument('--scratch', required=True, type=Path)
ap.add_argument('--suite', choices=['memory', 'pool', 'texture'], required=True)
ap.add_argument('--smoke', action='store_true')
args = ap.parse_args()
src = Path(__file__).resolve().parent
repo = src.parents[3]
base = args.scratch.expanduser().resolve()
if base.exists() or base == repo or repo in base.parents:
ap.error('scratch must be new and outside checkout')
bottle = args.bottle.expanduser().resolve()
original = (bottle/'cxbottle.conf').read_bytes()
if b'"WineArch" = "win64"' not in original:
ap.error('requires win64 bottle')
lock = open('/tmp/betterxen-473-gpu.lock', 'a')
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
ap.error('another Workstream A GPU batch owns the lock')
base.mkdir(mode=0o700)
env = {k: os.environ[k] for k in ['HOME', 'USER', 'LOGNAME', 'PATH', 'LANG', 'LC_ALL'] if k in os.environ}
env.update(TMPDIR=str(base)+'/', ROSETTA_ADVERTISE_AVX='1', CX_GRAPHICS_BACKEND='d3dmetal', WINEDEBUG='-all')
cx = Path('/Applications/CrossOver.app/Contents/SharedSupport/CrossOver')
wine = cx/'bin/wine'
source = src/(args.suite+'.cpp') if args.suite != 'texture' else src.parent/'gpu-correctness/textures-and-resources/probe.cpp'
exe, observer = base/'a-probe.exe', base/'observe'
receipt = dict(protocol='A-local-2', suite=args.suite, utc=datetime.now(timezone.utc).isoformat(),
independent_review='pending', environment={k: env[k] for k in ['ROSETTA_ADVERTISE_AVX', 'CX_GRAPHICS_BACKEND', 'WINEDEBUG']},
sources={str(p.relative_to(repo)): sha(p) for p in [source, src/'support.h', src/'observe.cpp', Path(__file__)]},
baseline_sha256=sha(src.parent/'probe.cpp'), tools={}, cases=[])
snapshot=base/'source';snapshot.mkdir()
for source_path in [source, src/'support.h', src/'observe.cpp', Path(__file__)]:
shutil.copy2(source_path, snapshot/source_path.name)
def save():
(base/'receipt.json').write_text(json.dumps(receipt, indent=2)+'\n')
cmds = {
'chip': ['sysctl','-n','machdep.cpu.brand_string'], 'ram':['sysctl','-n','hw.memsize'],
'host':['uname','-m'], 'macos':['sw_vers'], 'page':['sysctl','-n','hw.pagesize'],
'swap_before':['sysctl','vm.swapusage'], 'pressure_before':['memory_pressure','-Q'], 'vm_before':['vm_stat'],
'load_before':['ps','-axo','pid,pcpu,comm'], 'wine_version':[wine,'--version'],
'wine_build':[cx/'bin/wine64','--version'],
'rosetta':['pkgutil','--pkg-info','com.apple.pkg.RosettaUpdateAuto'],
'gcc':['x86_64-w64-mingw32-g++','--version'], 'clang':['xcrun','clang++','--version'],
'sdk':['xcrun','--show-sdk-version'], 'python':['python3','--version'],
'compiler_arch':['file',str(Path(shutil.which('x86_64-w64-mingw32-g++')).resolve())],
'build_pe':['x86_64-w64-mingw32-g++','-std=c++20','-O2','-static','-static-libgcc','-static-libstdc++','-Wall','-Wextra','-Werror',source,'-o',exe,'-lkernel32'],
'build_observer':['xcrun','clang++','-std=c++20','-O2','-arch','arm64','-Wall','-Wextra','-Werror',src/'observe.cpp','-o',observer],
'formats':['file',exe,observer], 'observer_arch':['lipo','-archs',observer], 'observer_links':['otool','-L',observer],
}
for name, cmd in cmds.items():
receipt['tools'][name]=capture(cmd,env,base,60)
save()
if name.startswith('build_') and receipt['tools'][name]['exit']:
raise RuntimeError(receipt['tools'][name])
receipt['binaries']={p.name:sha(p) for p in [exe,observer]}
resources=cx/'lib64/apple_gptk/external/D3DMetal.framework/Versions/A/Resources'
receipt['framework']={p.name:plistlib.loads(p.read_bytes()) for p in resources.glob('*.plist')}
receipt['runtime_hashes']={str(p):sha(p) for p in [cx/'lib64/apple_gptk/wine/x86_64-windows/d3d12.dll', cx/'lib/wine/x86_64-windows/d3dcompiler_47.dll']}
temp=base/'bottle'
shutil.copytree(bottle,temp,symlinks=True)
conf=original.decode().replace('[Bottle]','[Bottle]\n"AllowUntrusted" = "1"',1)
conf+='\n[EnvironmentVariables]\n"CX_GRAPHICS_BACKEND" = "d3dmetal"\n[CrossOver]\n"AntiVirusScan" = "untrusted"\n'
(temp/'cxbottle.conf').write_text(conf)
receipt['bottle_original_sha256']=hashlib.sha256(original).hexdigest()
receipt['bottle_settings']=[line.strip() for line in conf.splitlines() if re.match(r'"(WineArch|Template|WindowsVersion|Version|CX_GRAPHICS_BACKEND|AllowUntrusted|AntiVirusScan)"',line)]
common=[str(wine),'--bottle',str(temp),'--no-update','--no-gui',str(exe)]
def run(name, argv):
pressure=capture(['memory_pressure','-Q'],env,base)
match=re.search(r'free percentage: (\d+)%',pressure['stdout'])
if pressure['exit'] or not match or int(match[1])<30:
receipt['stop_reason']={'pressure_gate_before':name,'reading':pressure};save()
raise RuntimeError('memory pressure headroom below 30% or unreadable')
case=base/name;case.mkdir()
metadata=dict(name=name,args=argv,command=common+argv,timeout_seconds=240,pressure_before=pressure,snapshots=[])
receipt['cases'].append(metadata);save()
expired=threading.Event()
start=time.monotonic()
with (case/'stdout.txt').open('wb') as out,(case/'stderr.txt').open('wb') as err:
p=subprocess.Popen(common+argv,env=env,cwd=case,stdout=subprocess.PIPE,stderr=err,stdin=subprocess.PIPE,start_new_session=True)
def kill():
try: os.killpg(p.pid,signal.SIGKILL)
except ProcessLookupError: pass
def expire():
expired.set();kill()
timer=threading.Timer(240,expire);timer.start()
pid=None
try:
for line in p.stdout:
out.write(line);out.flush()
if not line.startswith(b'STAGE '):continue
if pid is None:
found=capture(['lsof','-t','-a','-c','a-probe.exe',str(exe)],env,base)
candidates=sorted({int(x) for x in found['stdout'].split() if x.isdigit()})
if len(candidates)!=1:raise RuntimeError('ambiguous PE PID: '+repr(found))
pid=candidates[0];metadata['host_pid']=pid
libs=capture(['lsof','-n','-p',str(pid)],env,base)
metadata['backend_paths_excerpt']=[line.split('/',1)[-1] for line in libs['stdout'].splitlines() if any(x in line for x in ['apple_gptk/wine/x86_64-windows/d3d12.dll','D3DMetal.framework/Versions/A/D3DMetal','/rosetta/runtime'])]
metadata['backend_lsof_exit']=libs['exit']
phase=line.decode().split()[1]
snap=dict(phase=phase,marker=line.decode().strip(),samples=[])
for _ in range(3):
result=capture([observer,str(pid)],env,base)
if not result['exit']:result['data']=json.loads(result['stdout'])
snap['samples'].append(result)
commands={'footprint':['footprint','-p',str(pid),'-f','bytes','--swapped'],
'vmmap':['vmmap','-summary',str(pid)], 'vmstat':['vm_stat'],
'pressure':['memory_pressure','-Q'],'swap':['sysctl','vm.swapusage']}
ptr=re.search(rb'cpu_ptr=([0-9A-Fa-f]+)',line)
if ptr and int(ptr[1],16):commands['pointer_vmmap']=['vmmap','-w',str(pid),'0x'+ptr[1].decode()]
for tool,cmd in commands.items():
result=capture(cmd,env,base,15)
filename=f'{phase}-{tool}.json';(case/filename).write_text(json.dumps(result,indent=2)+'\n')
snap[tool]=dict(exit=result['exit'],file=filename)
if tool=='pressure':
m=re.search(r'free percentage: (\d+)%',result['stdout'])
if result['exit'] or not m or int(m[1])<25:raise RuntimeError('stage pressure safety stop')
metadata['snapshots'].append(snap);save()
p.stdin.write(b'\n');p.stdin.flush()
p.wait()
except BaseException as e:
metadata['harness_error']=repr(e);kill();p.wait();raise
finally:
timer.cancel();metadata.update(exit=p.returncode,timed_out=expired.is_set(),seconds=time.monotonic()-start)
metadata['outputs']={f.name:sha(f) for f in case.iterdir() if f.is_file()}
(case/'case.json').write_text(json.dumps(metadata,indent=2)+'\n');save()
print(name,'exit',metadata['exit'],'timeout',metadata['timed_out'],flush=True)
if metadata['exit'] or metadata['timed_out']:raise RuntimeError('case failed: '+name)
try:
if args.suite=='memory':
for repeat in range(1 if args.smoke else 2):
sizes=[64] if args.smoke else [64,256,1024]
types=['wb'] if args.smoke else ['cpu-plain','cpu','wb','upload']
if repeat%2:types.reverse();sizes.reverse()
for size in sizes:
for typ in types:run(f'memory-{typ}-{size}MiB-r{repeat}',[typ,str(size*1024**2)])
elif args.suite=='pool':
for session in range(1 if args.smoke else 3):
modes=['individual','pooled'] if session%2==0 else ['pooled','individual']
for mode in modes:run(f'pool-{mode}-s{session}',[mode,str(473+session)])
else:
for session in range(1 if args.smoke else 2):run(f'texture-s{session}',[str(session)])
finally:
for name,cmd in {'pressure_after':['memory_pressure','-Q'],'vm_after':['vm_stat'],'swap_after':['sysctl','vm.swapusage']}.items():receipt['tools'][name]=capture(cmd,env,base)
stop=dict(env,WINEPREFIX=str(temp))
receipt['server_stop']=capture([cx/'bin/wineserver','-k'],stop,base)
receipt['server_wait']=capture([cx/'bin/wineserver','-w'],stop,base)
receipt['source_bottle_unchanged']=(bottle/'cxbottle.conf').read_bytes()==original
shutil.rmtree(temp);save()
return 0
if __name__=='__main__':
raise SystemExit(main())
@@ -0,0 +1,390 @@
#pragma once
// SPDX-License-Identifier: GPL-3.0-or-later
// Supplemental original synthetic tests; baseline ../probe.cpp is unchanged.
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <d3d12.h>
#include <d3dcompiler.h>
#include <dxgi1_4.h>
#include <emmintrin.h>
#include <stdexcept>
#include <string>
#include <vector>
#include <windows.h>
template <class T> struct Ref {
T *p = nullptr;
Ref() = default;
Ref(const Ref &) = delete;
Ref &operator=(const Ref &) = delete;
~Ref() { clear(); }
void clear() {
if (p) {
p->Release();
p = nullptr;
}
}
T *operator->() const { return p; }
void **out() { return reinterpret_cast<void **>(&p); }
};
static void require(HRESULT h, const char *name) {
if (FAILED(h)) {
std::printf("FAIL %s HRESULT=0x%08lX\n", name, (unsigned long)h);
throw std::runtime_error(name);
}
}
static void report(HRESULT h, const char *name) {
std::printf("API %s HRESULT=0x%08lX\n", name, (unsigned long)h);
}
template <class T> static T symbol(HMODULE m, const char *name) {
FARPROC p = GetProcAddress(m, name);
if (!p)
throw std::runtime_error(name);
T result;
static_assert(sizeof(result) == sizeof(p));
std::memcpy(&result, &p, sizeof(p));
return result;
}
static double ticks() {
LARGE_INTEGER t;
QueryPerformanceCounter(&t);
return double(t.QuadPart);
}
static double frequency() {
LARGE_INTEGER t;
QueryPerformanceFrequency(&t);
return double(t.QuadPart);
}
static D3D12_HEAP_PROPERTIES properties(D3D12_HEAP_TYPE type) {
D3D12_HEAP_PROPERTIES p{};
p.Type = type;
p.CreationNodeMask = 1;
p.VisibleNodeMask = 1;
return p;
}
static D3D12_RESOURCE_DESC
bufferDesc(UINT64 bytes,
D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) {
D3D12_RESOURCE_DESC r{};
r.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
r.Width = bytes;
r.Height = 1;
r.DepthOrArraySize = 1;
r.MipLevels = 1;
r.SampleDesc.Count = 1;
r.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
r.Flags = flags;
return r;
}
struct Context {
HMODULE dll = nullptr;
Ref<ID3D12Device3> device;
Context() {
dll = LoadLibraryA("d3d12.dll");
if (!dll)
throw std::runtime_error("LoadLibrary d3d12");
char path[2048]{};
GetModuleFileNameA(dll, path, sizeof(path));
std::printf("D3D12_DLL %s\n", path);
using Create =
HRESULT(WINAPI *)(IUnknown *, D3D_FEATURE_LEVEL, REFIID, void **);
require(symbol<Create>(dll, "D3D12CreateDevice")(
nullptr, D3D_FEATURE_LEVEL_11_0, __uuidof(ID3D12Device3),
device.out()),
"CreateDevice3");
bool shim = GetModuleHandleA("d3d12_xs.dll") != nullptr;
std::printf("SHIM_LOADED %d\n", shim);
if (shim)
throw std::runtime_error("shim contamination");
}
};
struct Queue {
ID3D12Device3 *d;
Ref<ID3D12CommandQueue> q;
Ref<ID3D12CommandAllocator> allocator;
Ref<ID3D12GraphicsCommandList> list;
Ref<ID3D12Fence> fence;
HANDLE event = nullptr;
UINT64 value = 0;
explicit Queue(ID3D12Device3 *device) : d(device) {
D3D12_COMMAND_QUEUE_DESC desc{};
desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
require(d->CreateCommandQueue(&desc, __uuidof(ID3D12CommandQueue), q.out()),
"CreateCommandQueue");
require(d->CreateCommandAllocator(
desc.Type, __uuidof(ID3D12CommandAllocator), allocator.out()),
"CreateCommandAllocator");
require(d->CreateCommandList(0, desc.Type, allocator.p, nullptr,
__uuidof(ID3D12GraphicsCommandList),
list.out()),
"CreateCommandList");
require(list->Close(), "initial Close");
require(d->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence),
fence.out()),
"CreateFence");
event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
if (!event)
throw std::runtime_error("CreateEvent");
}
~Queue() {
if (event)
CloseHandle(event);
}
void begin() {
require(allocator->Reset(), "allocator Reset");
require(list->Reset(allocator.p, nullptr), "list Reset");
}
void transition(ID3D12Resource *r, D3D12_RESOURCE_STATES a,
D3D12_RESOURCE_STATES b) {
if (a == b)
return;
D3D12_RESOURCE_BARRIER x{};
x.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
x.Transition.pResource = r;
x.Transition.StateBefore = a;
x.Transition.StateAfter = b;
x.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
list->ResourceBarrier(1, &x);
}
void close() { require(list->Close(), "Close"); }
void executeClosed() {
ID3D12CommandList *lists[] = {list.p};
q->ExecuteCommandLists(1, lists);
require(q->Signal(fence.p, ++value), "Signal");
UINT64 completed = fence->GetCompletedValue();
if (completed == ~UINT64(0))
throw std::runtime_error("device removed fence");
if (completed < value) {
require(fence->SetEventOnCompletion(value, event),
"SetEventOnCompletion");
DWORD w = WaitForSingleObject(event, 10000);
if (w != WAIT_OBJECT_0)
throw std::runtime_error("fence timeout");
}
}
void finish() {
close();
_mm_sfence();
executeClosed();
require(d->GetDeviceRemovedReason(), "GetDeviceRemovedReason");
}
};
struct Buffer {
Ref<ID3D12Heap> heap;
Ref<ID3D12Resource> resource;
void *cpu = nullptr;
UINT64 size = 0;
void allocate(ID3D12Device3 *d, UINT64 bytes, const std::string &type,
bool uav = false) {
size = bytes;
auto desc =
bufferDesc(bytes, uav ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS
: D3D12_RESOURCE_FLAG_NONE);
auto state =
uav ? D3D12_RESOURCE_STATE_COMMON : D3D12_RESOURCE_STATE_GENERIC_READ;
if (type == "upload" || type == "readback") {
if (uav)
throw std::runtime_error(
"UAV on upload/readback forbidden in this probe");
auto p = properties(type == "upload" ? D3D12_HEAP_TYPE_UPLOAD
: D3D12_HEAP_TYPE_READBACK);
if (type == "readback")
state = D3D12_RESOURCE_STATE_COPY_DEST;
require(d->CreateCommittedResource(&p, D3D12_HEAP_FLAG_NONE, &desc, state,
nullptr, __uuidof(ID3D12Resource),
resource.out()),
"committed buffer");
} else {
D3D12_HEAP_DESC hd{};
hd.SizeInBytes = (bytes + 65535) & ~UINT64(65535);
hd.Alignment = 65536;
hd.Properties = properties(D3D12_HEAP_TYPE_CUSTOM);
hd.Properties.CPUPageProperty =
type == "wc" ? D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE
: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
hd.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
require(d->CreateHeap(&hd, __uuidof(ID3D12Heap), heap.out()),
"custom heap");
require(d->CreatePlacedResource(heap.p, 0, &desc, state, nullptr,
__uuidof(ID3D12Resource), resource.out()),
"placed buffer");
}
}
void map() {
require(resource->Map(0, nullptr, &cpu), "Map buffer");
if (!cpu)
throw std::runtime_error("null buffer pointer");
}
void release() {
cpu = nullptr;
resource.clear();
heap.clear();
}
};
[[maybe_unused]] static void identity(Context &c) {
using Factory = HRESULT(WINAPI *)(UINT, REFIID, void **);
HMODULE dxgi = LoadLibraryA("dxgi.dll");
if (!dxgi)
throw std::runtime_error("dxgi load");
Ref<IDXGIFactory4> f;
require(symbol<Factory>(dxgi, "CreateDXGIFactory2")(
0, __uuidof(IDXGIFactory4), f.out()),
"factory4");
LUID luid = c.device->GetAdapterLuid();
Ref<IDXGIAdapter2> a;
require(f->EnumAdapterByLuid(luid, __uuidof(IDXGIAdapter2), a.out()),
"adapter by device LUID");
DXGI_ADAPTER_DESC2 ad{};
require(a->GetDesc2(&ad), "GetDesc2");
char name[512]{};
WideCharToMultiByte(CP_UTF8, 0, ad.Description, -1, name, sizeof(name),
nullptr, nullptr);
std::printf(
"ADAPTER description=%s vendor=0x%04X device=0x%04X subsystem=0x%08X "
"revision=%u flags=%u dedicated_video_bytes=%llu "
"dedicated_system_bytes=%llu shared_system_bytes=%llu luid=%08lX:%08lX\n",
name, ad.VendorId, ad.DeviceId, ad.SubSysId, ad.Revision, ad.Flags,
(unsigned long long)ad.DedicatedVideoMemory,
(unsigned long long)ad.DedicatedSystemMemory,
(unsigned long long)ad.SharedSystemMemory, (unsigned long)luid.HighPart,
(unsigned long)luid.LowPart);
D3D12_FEATURE_DATA_D3D12_OPTIONS opts{};
require(c.device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &opts,
sizeof(opts)),
"options");
std::printf(
"OPTIONS ResourceHeapTier=%d CrossAdapterRowMajorTextureSupported=%d "
"StandardSwizzle64KBSupported=%d\n",
opts.ResourceHeapTier, opts.CrossAdapterRowMajorTextureSupported,
opts.StandardSwizzle64KBSupported);
D3D12_FEATURE_DATA_ARCHITECTURE1 arch{};
require(c.device->CheckFeatureSupport(D3D12_FEATURE_ARCHITECTURE1, &arch,
sizeof(arch)),
"architecture1");
std::printf(
"ARCH UMA=%d CacheCoherentUMA=%d TileBasedRenderer=%d IsolatedMMU=%d\n",
arch.UMA, arch.CacheCoherentUMA, arch.TileBasedRenderer,
arch.IsolatedMMU);
for (auto type : {D3D12_HEAP_TYPE_DEFAULT, D3D12_HEAP_TYPE_UPLOAD,
D3D12_HEAP_TYPE_READBACK}) {
auto p = c.device->GetCustomHeapProperties(0, type);
std::printf(
"CUSTOM_PROPERTIES input_type=%d Type=%d CPUPageProperty=%d "
"MemoryPoolPreference=%d CreationNodeMask=%u VisibleNodeMask=%u\n",
type, p.Type, p.CPUPageProperty, p.MemoryPoolPreference,
p.CreationNodeMask, p.VisibleNodeMask);
}
SYSTEM_INFO si{};
GetSystemInfo(&si);
std::printf("GUEST_PAGE_SIZE %lu ALLOCATION_GRANULARITY %lu\n", si.dwPageSize,
si.dwAllocationGranularity);
}
struct Shader {
Ref<ID3D12RootSignature> root;
Ref<ID3D12PipelineState> pipeline;
static constexpr const char *code = R"HLSL(
ByteAddressBuffer source : register(t0);
RWByteAddressBuffer result : register(u0);
cbuffer Parameters : register(b0) { uint count; uint salt; uint wordStride; };
[numthreads(64,1,1)]
void main(uint3 tid : SV_DispatchThreadID) {
uint accum=0;
for(uint i=tid.x; i<count; i+=256) accum ^= source.Load(i*wordStride*4)+salt;
result.Store(tid.x*4,accum);
}
)HLSL";
explicit Shader(Context &c) {
HMODULE compiler = LoadLibraryA("d3dcompiler_47.dll");
if (!compiler)
throw std::runtime_error("d3dcompiler47 unavailable");
char path[2048]{};
GetModuleFileNameA(compiler, path, sizeof(path));
std::printf("SHADER_COMPILER %s\n", path);
using Compile = HRESULT(WINAPI *)(
LPCVOID, SIZE_T, LPCSTR, const D3D_SHADER_MACRO *, ID3DInclude *,
LPCSTR, LPCSTR, UINT, UINT, ID3DBlob **, ID3DBlob **);
Ref<ID3DBlob> binary, error;
HRESULT h = symbol<Compile>(compiler, "D3DCompile")(
code, std::strlen(code), "original-phase2.hlsl", nullptr, nullptr,
"main", "cs_5_0", D3DCOMPILE_OPTIMIZATION_LEVEL3, 0, &binary.p,
&error.p);
if (error.p)
std::printf("COMPILER_LOG %.*s\n", (int)error->GetBufferSize(),
(const char *)error->GetBufferPointer());
require(h, "D3DCompile cs5_0");
std::printf("SHADER_BYTECODE bytes=%zu magic=%.4s\n",
binary->GetBufferSize(), (char *)binary->GetBufferPointer());
FILE *bytecode = std::fopen("consumption.dxbc", "wb");
if (!bytecode ||
std::fwrite(binary->GetBufferPointer(), 1, binary->GetBufferSize(),
bytecode) != binary->GetBufferSize())
throw std::runtime_error("archive shader");
std::fclose(bytecode);
FILE *hlsl = std::fopen("consumption.hlsl", "wb");
if (!hlsl)
throw std::runtime_error("archive HLSL");
std::fwrite(code, 1, std::strlen(code), hlsl);
std::fclose(hlsl);
D3D12_ROOT_PARAMETER params[3]{};
params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV;
params[0].Descriptor.ShaderRegister = 0;
params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
params[1].Descriptor.ShaderRegister = 0;
params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
params[2].Constants.ShaderRegister = 0;
params[2].Constants.Num32BitValues = 3;
D3D12_ROOT_SIGNATURE_DESC desc{};
desc.NumParameters = 3;
desc.pParameters = params;
using Serialize =
HRESULT(WINAPI *)(const D3D12_ROOT_SIGNATURE_DESC *,
D3D_ROOT_SIGNATURE_VERSION, ID3DBlob **, ID3DBlob **);
Ref<ID3DBlob> serialized, serializeError;
require(symbol<Serialize>(c.dll, "D3D12SerializeRootSignature")(
&desc, D3D_ROOT_SIGNATURE_VERSION_1, &serialized.p,
&serializeError.p),
"serialize root");
require(c.device->CreateRootSignature(
0, serialized->GetBufferPointer(), serialized->GetBufferSize(),
__uuidof(ID3D12RootSignature), root.out()),
"CreateRootSignature");
D3D12_COMPUTE_PIPELINE_STATE_DESC pd{};
pd.pRootSignature = root.p;
pd.CS = {binary->GetBufferPointer(), binary->GetBufferSize()};
require(c.device->CreateComputePipelineState(
&pd, __uuidof(ID3D12PipelineState), pipeline.out()),
"CreateComputePipelineState");
}
void dispatch(Queue &q, Buffer &src, Buffer &dst, UINT count, UINT salt,
UINT stride) {
q.begin();
q.transition(dst.resource.p, D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
q.list->SetPipelineState(pipeline.p);
q.list->SetComputeRootSignature(root.p);
q.list->SetComputeRootShaderResourceView(
0, src.resource->GetGPUVirtualAddress());
q.list->SetComputeRootUnorderedAccessView(
1, dst.resource->GetGPUVirtualAddress());
UINT values[] = {count, salt, stride};
q.list->SetComputeRoot32BitConstants(2, 3, values, 0);
q.list->Dispatch(4, 1, 1);
q.transition(dst.resource.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
D3D12_RESOURCE_STATE_COMMON);
q.finish();
}
};
static uint32_t pattern(UINT64 i, UINT seed) {
uint32_t x = uint32_t(i) ^ seed;
x ^= x >> 16;
x *= 0x7FEB352Du;
x ^= x >> 15;
x *= 0x846CA68Bu;
return x ^ (x >> 16);
}
@@ -0,0 +1,14 @@
{
"command": [
"footprint",
"-p",
"54264",
"-f",
"bytes",
"--swapped"
],
"exit": 0,
"stdout": "================================================================================\na-probe.exe [54264]: 64-bit (translated) Footprint: 313498816 B (4096 bytes per page)\n================================================================================\n\n Dirty (Swapped) Clean Reclaimable Regions Category\n --- --- --- --- --- ---\n270155776 B 0 B 0 B 245760 B 25 IOAccelerator (graphics)\n 13979648 B 0 B 0 B 0 B 203 Untagged\n 5869568 B 0 B 421888 B 0 B 188 WINE_RESERVE\n 5079040 B 0 B 0 B 0 B 1 Malloc Nano\n 2576384 B 0 B 0 B 0 B 1 Rosetta JIT\n 2247872 B 0 B 0 B 0 B 1 page table\n 2154496 B 0 B 0 B 0 B 7 Malloc Small\n 2088960 B 0 B 0 B 0 B 512 Rosetta Generic\n 2072576 B 0 B 0 B 0 B 4 Malloc Medium\n 1871872 B 0 B 0 B 0 B 620 __DATA_CONST\n 1643874 B 0 B 0 B 0 B 600 __DATA\n 1073152 B 0 B 0 B 0 B 19 Malloc Tiny\n 634520 B 0 B 0 B 0 B 523 __DATA_DIRTY\n 524288 B 0 B 0 B 0 B 1 Rosetta IndirectBranch\n 315392 B 0 B 13828096 B 0 B 145 mapped file\n 307200 B 0 B 0 B 0 B 36 Malloc Metadata\n 278528 B 0 B 0 B 0 B 2 Rosetta Arena\n 196608 B 0 B 0 B 0 B 13 Stack\n 98304 B 0 B 0 B 0 B 7 IOKit\n 82406 B 0 B 0 B 0 B 1356 unused dyld shared cache area\n 65536 B 0 B 0 B 0 B 2 IOAccelerator\n 40960 B 0 B 0 B 0 B 14 Rosetta Thread Context\n 32768 B 0 B 0 B 0 B 1 Activity Tracing\n 31248 B 0 B 0 B 0 B 1 __OBJC_RW\n 28672 B 0 B 0 B 0 B 14 Rosetta Return Stack\n 16384 B 0 B 0 B 0 B 2 WINE_TOP_DOWN\n 8192 B 0 B 0 B 0 B 1 OS Alloc Once\n 8192 B 0 B 0 B 0 B 3 CoreGraphics\n 4112 B 0 B 0 B 0 B 4 __TPRO_CONST\n 4096 B 0 B 2387968 B 0 B 653 __TEXT\n 4096 B 0 B 0 B 0 B 2 Malloc Large\n 4096 B 0 B 0 B 0 B 1 Foundation\n 0 B 0 B 303104 B 0 B 25 __LINKEDIT\n 0 B 0 B 0 B 0 B 1 __OBJC_RO\n 0 B 0 B 0 B 0 B 1 __FONT_DATA\n 0 B 0 B 0 B 0 B 1 IOSurface\n 0 B 0 B 0 B 0 B 1 __CTF\n --- --- --- --- --- ---\n313498816 B 0 B 16941056 B 245760 B 4993 TOTAL\n\nAuxiliary data:\n phys_footprint: 314752192 B\n phys_footprint_peak: 356567752 B\n\n",
"stderr": "",
"seconds": 0.04744024999672547
}
@@ -0,0 +1,10 @@
{
"command": [
"memory_pressure",
"-Q"
],
"exit": 0,
"stdout": "The system has 25769803776 (1572864 pages with a page size of 16384).\nSystem-wide memory free percentage: 52%\n",
"stderr": "",
"seconds": 0.002565750037319958
}
@@ -0,0 +1,10 @@
{
"command": [
"sysctl",
"vm.swapusage"
],
"exit": 0,
"stdout": "vm.swapusage: total = 6144.00M used = 5396.44M free = 747.56M (encrypted)\n",
"stderr": "",
"seconds": 0.0022907499806024134
}
@@ -0,0 +1,11 @@
{
"command": [
"vmmap",
"-summary",
"54264"
],
"exit": 0,
"stdout": "Process: a-probe.exe [54264]\nPath: CrossOver.app/Contents/SharedSupport/CrossOver/lib/wine/x86_64-unix/wine\nLoad Address: 0x200000000\nIdentifier: wine\nVersion: 11.0 (0)\nCode Type: X86-64 (translated)\nPlatform: macOS\nParent Process: launchd [1]\nTarget Type: live task (Roots Present)\n\nDate/Time: 2026-11-26 14:35:28.656 -0600\nLaunch Time: 2026-11-26 14:35:23.671 -0600\nOS Version: macOS 27.0 (26A428)\nReport Version: 7\nAnalysis Tool: /usr/bin/vmmap\n\nPhysical footprint: 300.2M\nPhysical footprint (peak): 340.0M\nIdle exit: untracked\n----\n\nReadOnly portion of Libraries: Total=943.4M resident=441.6M(47%) swapped_out_or_unallocated=501.8M(53%)\nWritable regions: Total=1.6G written=22.1M(1%) resident=88.3M(6%) swapped_out=64K(0%) unallocated=1.5G(94%)\n\n VIRTUAL RESIDENT DIRTY SWAPPED VOLATILE NONVOL EMPTY REGION \nREGION TYPE SIZE SIZE SIZE SIZE SIZE SIZE SIZE COUNT (non-coalesced) \n=========== ======= ======== ===== ======= ======== ====== ===== ======= \nActivity Tracing 256K 8K 32K 0K 0K 8K 0K 1 \nCoreGraphics 8K 8K 8K 0K 0K 0K 0K 2 \nCoreGraphics (reserved) 8K 0K 0K 0K 0K 0K 0K 1 reserved VM address space (unallocated)\nFoundation 16K 4K 4K 0K 0K 0K 0K 1 \nGuard 385.0G 0K 0K 0K 0K 0K 0K 1 \nIOAccelerator 64K 64K 64K 0K 0K 0K 0K 2 \nIOAccelerator (graphics) 257.9M 64.4M 257.6M 0K 0K 64.4M 0K 25 \nIOKit 96K 84K 96K 0K 0K 4K 0K 7 \nIOSurface 16K 0K 0K 0K 0K 0K 0K 1 \nMalloc Guard Page 288K 0K 0K 0K 0K 0K 0K 18 see MALLOC ZONE table below\nMalloc Large (reserved) 14.0M 0K 0K 0K 0K 0K 0K 1 see MALLOC ZONE table below\nMalloc Large metadata 16K 4K 4K 0K 0K 0K 0K 1 see MALLOC ZONE table below\nMalloc Medium 384.0M 1988K 1988K 0K 0K 0K 0K 3 see MALLOC ZONE table below\nMalloc Medium (empty) 128.0M 36K 36K 0K 0K 0K 0K 1 see MALLOC ZONE table below\nMalloc Metadata 348K 300K 300K 0K 0K 0K 0K 18 see MALLOC ZONE table below\nMalloc Nano 512.0M 4960K 4960K 0K 0K 0K 0K 1 see MALLOC ZONE table below\nMalloc Small 32.0M 2072K 2072K 0K 0K 0K 0K 4 see MALLOC ZONE table below\nMalloc Small (empty) 24.0M 32K 32K 0K 0K 0K 0K 3 see MALLOC ZONE table below\nMalloc Tiny 14.0M 988K 988K 0K 0K 0K 0K 14 see MALLOC ZONE table below\nMalloc Tiny (empty) 5120K 60K 60K 0K 0K 0K 0K 5 see MALLOC ZONE table below\nOS Alloc Once 8K 8K 8K 0K 0K 0K 0K 1 \nRosetta Arena 4096K 272K 272K 0K 0K 0K 0K 2 \nRosetta Generic 2072K 2040K 2040K 0K 0K 0K 0K 512 \nRosetta IndirectBranch 512K 512K 512K 0K 0K 0K 0K 1 \nRosetta JIT 128.0M 2516K 2516K 0K 0K 0K 0K 1 \nRosetta Return Stack 140K 28K 28K 0K 0K 0K 0K 14 \nRosetta Thread Context 140K 40K 40K 0K 0K 0K 0K 14 \nStack 10.6M 192K 192K 0K 0K 0K 0K 7 \nStack Guard 56.0M 0K 0K 0K 0K 0K 0K 6 \nUntagged 32.3M 13.2M 13.2M 0K 0K 0K 0K 180 \nUntagged (reserved) 8224K 0K 0K 0K 0K 0K 0K 6 reserved VM address space (unallocated)\nWINE_RESERVE 8.0G 6144K Line truncated
"stderr": "",
"seconds": 3.2293729159864597
}
@@ -0,0 +1,9 @@
{
"command": [
"vm_stat"
],
"exit": 0,
"stdout": "Mach Virtual Memory Statistics: (page size of 16384 bytes)\nPages free: 101216.\nPages active: 356648.\nPages inactive: 352031.\nPages speculative: 3775.\nPages throttled: 0.\nPages wired down: 176067.\nPages purgeable: 4528.\n\"Translation faults\": 2325611309.\nPages copy-on-write: 97440723.\nPages zero filled: 1678189876.\nPages reactivated: 187873092.\nPages purged: 19293116.\nFile-backed pages: 255556.\nAnonymous pages: 456898.\nPages stored in compressor: 1951178.\nPages occupied by compressor: 544414.\nDecompressions: 147970082.\nCompressions: 186320676.\nPageins: 47228644.\nPageouts: 921009.\nSwapins: 1663216.\nSwapouts: 2468999.\n",
"stderr": "",
"seconds": 0.002861917018890381
}
@@ -0,0 +1,14 @@
{
"command": [
"footprint",
"-p",
"54264",
"-f",
"bytes",
"--swapped"
],
"exit": 0,
"stdout": "================================================================================\na-probe.exe [54264]: 64-bit (translated) Footprint: 314446024 B (4096 bytes per page)\n================================================================================\n\n Dirty (Swapped) Clean Reclaimable Regions Category\n --- --- --- --- --- ---\n270155776 B 270057472 B 0 B 0 B 25 IOAccelerator (graphics)\n 14241792 B 12517376 B 0 B 0 B 202 Untagged\n 5869568 B 5644288 B 421888 B 0 B 188 WINE_RESERVE\n 5087232 B 2461696 B 0 B 0 B 1 Malloc Nano\n 2953416 B 0 B 0 B 0 B 1 page table\n 2613248 B 1671168 B 0 B 0 B 1 Rosetta JIT\n 2183168 B 1302528 B 0 B 0 B 9 Malloc Small\n 2097152 B 1327104 B 0 B 0 B 514 Rosetta Generic\n 2072576 B 2023424 B 0 B 0 B 4 Malloc Medium\n 1871872 B 1806336 B 0 B 0 B 620 __DATA_CONST\n 1643874 B 1103727 B 0 B 0 B 600 __DATA\n 1073152 B 356352 B 0 B 0 B 19 Malloc Tiny\n 585324 B 229685 B 0 B 0 B 523 __DATA_DIRTY\n 524288 B 0 B 0 B 0 B 1 Rosetta IndirectBranch\n 315392 B 262144 B 13836288 B 0 B 145 mapped file\n 307200 B 114688 B 0 B 0 B 36 Malloc Metadata\n 278528 B 90112 B 0 B 0 B 2 Rosetta Arena\n 176128 B 65536 B 0 B 0 B 11 Stack\n 82450 B 55132 B 0 B 0 B 1356 unused dyld shared cache area\n 73728 B 0 B 0 B 0 B 5 IOKit\n 65536 B 0 B 0 B 0 B 2 IOAccelerator\n 36864 B 0 B 0 B 0 B 12 Rosetta Thread Context\n 32768 B 16384 B 0 B 0 B 1 Activity Tracing\n 31248 B 0 B 0 B 0 B 1 __OBJC_RW\n 24576 B 0 B 0 B 0 B 12 Rosetta Return Stack\n 16384 B 4096 B 0 B 0 B 2 WINE_TOP_DOWN\n 8192 B 0 B 0 B 0 B 1 OS Alloc Once\n 8192 B 0 B 0 B 0 B 3 CoreGraphics\n 4112 B 0 B 0 B 0 B 4 __TPRO_CONST\n 4096 B 0 B 2387968 B 0 B 653 __TEXT\n 4096 B 0 B 0 B 0 B 2 Malloc Large\n 4096 B 4096 B 0 B 0 B 1 Foundation\n 0 B 0 B 303104 B 0 B 25 __LINKEDIT\n 0 B 0 B 0 B 0 B 1 __OBJC_RO\n 0 B 0 B 0 B 0 B 1 __FONT_DATA\n 0 B 0 B 0 B 0 B 1 IOSurface\n 0 B 0 B 0 B 0 B 1 __CTF\n --- --- --- --- --- ---\n314446024 B 301113344 B 16949248 B 0 B 4988 TOTAL\n\nAuxiliary data:\n phys_footprint: 315699400 B\n phys_footprint_peak: 1391537328 B\n\n",
"stderr": "",
"seconds": 0.04962712503038347
}
@@ -0,0 +1,10 @@
{
"command": [
"memory_pressure",
"-Q"
],
"exit": 0,
"stdout": "The system has 25769803776 (1572864 pages with a page size of 16384).\nSystem-wide memory free percentage: 50%\n",
"stderr": "",
"seconds": 0.0024615000002086163
}
@@ -0,0 +1,10 @@
{
"command": [
"sysctl",
"vm.swapusage"
],
"exit": 0,
"stdout": "vm.swapusage: total = 6144.00M used = 5324.38M free = 819.62M (encrypted)\n",
"stderr": "",
"seconds": 0.0026407919940538704
}
@@ -0,0 +1,11 @@
{
"command": [
"vmmap",
"-summary",
"54264"
],
"exit": 0,
"stdout": "Process: a-probe.exe [54264]\nPath: CrossOver.app/Contents/SharedSupport/CrossOver/lib/wine/x86_64-unix/wine\nLoad Address: 0x200000000\nIdentifier: wine\nVersion: 11.0 (0)\nCode Type: X86-64 (translated)\nPlatform: macOS\nParent Process: launchd [1]\nTarget Type: live task (Roots Present)\n\nDate/Time: 2026-11-26 14:35:57.476 -0600\nLaunch Time: 2026-11-26 14:35:23.671 -0600\nOS Version: macOS 27.0 (26A428)\nReport Version: 7\nAnalysis Tool: /usr/bin/vmmap\n\nPhysical footprint: 301.1M\nPhysical footprint (peak): 1.3G\nIdle exit: untracked\n----\n\nReadOnly portion of Libraries: Total=943.4M resident=441.6M(47%) swapped_out_or_unallocated=501.8M(53%)\nWritable regions: Total=1.6G written=23.1M(1%) resident=75.6M(5%) swapped_out=271.2M(17%) unallocated=1.2G(78%)\n\n VIRTUAL RESIDENT DIRTY SWAPPED VOLATILE NONVOL EMPTY REGION \nREGION TYPE SIZE SIZE SIZE SIZE SIZE SIZE SIZE COUNT (non-coalesced) \n=========== ======= ======== ===== ======= ======== ====== ===== ======= \nActivity Tracing 256K 8K 16K 16K 0K 8K 0K 1 \nCoreGraphics 8K 8K 8K 0K 0K 0K 0K 2 \nCoreGraphics (reserved) 8K 0K 0K 0K 0K 0K 0K 1 reserved VM address space (unallocated)\nFoundation 16K 0K 0K 4K 0K 0K 0K 1 \nGuard 385.0G 0K 0K 0K 0K 0K 0K 1 \nIOAccelerator 64K 64K 64K 0K 0K 0K 0K 2 \nIOAccelerator (graphics) 257.9M 64.4M 96K 257.5M 0K 64.4M 240K 25 \nIOKit 72K 60K 72K 0K 0K 4K 0K 5 \nIOSurface 16K 0K 0K 0K 0K 0K 0K 1 \nMalloc Guard Page 288K 0K 0K 0K 0K 0K 0K 18 see MALLOC ZONE table below\nMalloc Large (reserved) 14.0M 0K 0K 0K 0K 0K 0K 1 see MALLOC ZONE table below\nMalloc Large metadata 16K 4K 4K 0K 0K 0K 0K 1 see MALLOC ZONE table below\nMalloc Medium 384.0M 40K 40K 1948K 0K 0K 0K 3 see MALLOC ZONE table below\nMalloc Medium (empty) 128.0M 8K 8K 28K 0K 0K 0K 1 see MALLOC ZONE table below\nMalloc Metadata 348K 188K 188K 112K 0K 0K 0K 18 see MALLOC ZONE table below\nMalloc Nano 512.0M 2564K 2564K 2404K 0K 0K 0K 1 see MALLOC ZONE table below\nMalloc Small 32.0M 844K 844K 1236K 0K 0K 0K 4 see MALLOC ZONE table below\nMalloc Small (empty) 40.0M 16K 16K 36K 0K 0K 0K 5 see MALLOC ZONE table below\nMalloc Tiny 14.0M 644K 644K 344K 0K 0K 0K 14 see MALLOC ZONE table below\nMalloc Tiny (empty) 5120K 56K 56K 4K 0K 0K 0K 5 see MALLOC ZONE table below\nOS Alloc Once 8K 8K 8K 0K 0K 0K 0K 1 \nRosetta Arena 4096K 184K 184K 88K 0K 0K 0K 2 \nRosetta Generic 2080K 752K 752K 1296K 0K 0K 0K 514 \nRosetta IndirectBranch 512K 512K 512K 0K 0K 0K 0K 1 \nRosetta JIT 128.0M 920K 920K 1632K 0K 0K 0K 1 \nRosetta Return Stack 120K 24K 24K 0K 0K 0K 0K 12 \nRosetta Thread Context 120K 36K 36K 0K 0K 0K 0K 12 \nStack 10.0M 108K 108K 64K 0K 0K 0K 6 \nStack Guard 56.0M 0K 0K 0K 0K 0K 0K 5 \nUntagged 32.3M 1576K 1576K 11.9M 0K 0K 0K 180 \nUntagged (reserved) 4128K 0K 0K 0K 0K 0K 0K 5 reserved VM address space (unallocated)\nWINE_RESERVE 8.0G 632KLine truncated
"stderr": "",
"seconds": 3.0419938749982975
}
@@ -0,0 +1,9 @@
{
"command": [
"vm_stat"
],
"exit": 0,
"stdout": "Mach Virtual Memory Statistics: (page size of 16384 bytes)\nPages free: 183713.\nPages active: 291694.\nPages inactive: 302535.\nPages speculative: 5282.\nPages throttled: 0.\nPages wired down: 184848.\nPages purgeable: 5065.\n\"Translation faults\": 2335365326.\nPages copy-on-write: 97480789.\nPages zero filled: 1679810944.\nPages reactivated: 188120298.\nPages purged: 19325198.\nFile-backed pages: 264307.\nAnonymous pages: 335204.\nPages stored in compressor: 2017082.\nPages occupied by compressor: 566079.\nDecompressions: 148051979.\nCompressions: 186635799.\nPageins: 47253764.\nPageouts: 921026.\nSwapins: 1667656.\nSwapouts: 2468999.\n",
"stderr": "",
"seconds": 0.003136750019621104
}
@@ -0,0 +1,10 @@
ByteAddressBuffer source : register(t0);
RWByteAddressBuffer result : register(u0);
cbuffer Parameters : register(b0) { uint count; uint salt; uint wordStride; };
[numthreads(64,1,1)]
void main(uint3 tid : SV_DispatchThreadID) {
uint accum=0;
for(uint i=tid.x; i<count; i+=256) accum ^= source.Load(i*wordStride*4)+salt;
result.Store(tid.x*4,accum);
}
@@ -0,0 +1,14 @@
{
"command": [
"footprint",
"-p",
"54264",
"-f",
"bytes",
"--swapped"
],
"exit": 0,
"stdout": "================================================================================\na-probe.exe [54264]: 64-bit (translated) Footprint: 314273800 B (4096 bytes per page)\n================================================================================\n\n Dirty (Swapped) Clean Reclaimable Regions Category\n --- --- --- --- --- ---\n270155776 B 0 B 0 B 245760 B 25 IOAccelerator (graphics)\n 14241792 B 0 B 0 B 0 B 203 Untagged\n 5869568 B 0 B 421888 B 0 B 188 WINE_RESERVE\n 5087232 B 0 B 0 B 0 B 1 Malloc Nano\n 2822152 B 0 B 0 B 0 B 1 page table\n 2580480 B 0 B 0 B 0 B 1 Rosetta JIT\n 2162688 B 0 B 0 B 0 B 8 Malloc Small\n 2093056 B 0 B 0 B 0 B 513 Rosetta Generic\n 2072576 B 0 B 0 B 0 B 4 Malloc Medium\n 1871872 B 0 B 0 B 0 B 620 __DATA_CONST\n 1643874 B 0 B 0 B 0 B 600 __DATA\n 1073152 B 0 B 0 B 0 B 19 Malloc Tiny\n 568949 B 0 B 0 B 0 B 523 __DATA_DIRTY\n 524288 B 0 B 0 B 0 B 1 Rosetta IndirectBranch\n 315392 B 0 B 13828096 B 0 B 145 mapped file\n 307200 B 0 B 0 B 0 B 36 Malloc Metadata\n 278528 B 0 B 0 B 0 B 2 Rosetta Arena\n 176128 B 0 B 0 B 0 B 11 Stack\n 98304 B 0 B 0 B 0 B 7 IOKit\n 82441 B 0 B 0 B 0 B 1356 unused dyld shared cache area\n 65536 B 0 B 0 B 0 B 2 IOAccelerator\n 40960 B 0 B 0 B 0 B 14 Rosetta Thread Context\n 32768 B 0 B 0 B 0 B 1 Activity Tracing\n 31248 B 0 B 0 B 0 B 1 __OBJC_RW\n 28672 B 0 B 0 B 0 B 14 Rosetta Return Stack\n 16384 B 0 B 0 B 0 B 2 WINE_TOP_DOWN\n 8192 B 0 B 0 B 0 B 1 OS Alloc Once\n 8192 B 0 B 0 B 0 B 3 CoreGraphics\n 4112 B 0 B 0 B 0 B 4 __TPRO_CONST\n 4096 B 0 B 2387968 B 0 B 653 __TEXT\n 4096 B 0 B 0 B 0 B 2 Malloc Large\n 4096 B 0 B 0 B 0 B 1 Foundation\n 0 B 0 B 303104 B 0 B 25 __LINKEDIT\n 0 B 0 B 0 B 0 B 1 __OBJC_RO\n 0 B 0 B 0 B 0 B 1 __FONT_DATA\n 0 B 0 B 0 B 0 B 1 IOSurface\n 0 B 0 B 0 B 0 B 1 __CTF\n --- --- --- --- --- ---\n314273800 B 0 B 16941056 B 245760 B 4993 TOTAL\n\nAuxiliary data:\n phys_footprint: 315527176 B\n phys_footprint_peak: 356567752 B\n\n",
"stderr": "",
"seconds": 0.052247790968976915
}
@@ -0,0 +1,10 @@
{
"command": [
"memory_pressure",
"-Q"
],
"exit": 0,
"stdout": "The system has 25769803776 (1572864 pages with a page size of 16384).\nSystem-wide memory free percentage: 54%\n",
"stderr": "",
"seconds": 0.0025075830053538084
}
@@ -0,0 +1,10 @@
{
"command": [
"sysctl",
"vm.swapusage"
],
"exit": 0,
"stdout": "vm.swapusage: total = 6144.00M used = 5396.44M free = 747.56M (encrypted)\n",
"stderr": "",
"seconds": 0.0023569579934701324
}
@@ -0,0 +1,11 @@
{
"command": [
"vmmap",
"-summary",
"54264"
],
"exit": 0,
"stdout": "Process: a-probe.exe [54264]\nPath: CrossOver.app/Contents/SharedSupport/CrossOver/lib/wine/x86_64-unix/wine\nLoad Address: 0x200000000\nIdentifier: wine\nVersion: 11.0 (0)\nCode Type: X86-64 (translated)\nPlatform: macOS\nParent Process: launchd [1]\nTarget Type: live task (Roots Present)\n\nDate/Time: 2026-11-26 14:35:32.852 -0600\nLaunch Time: 2026-11-26 14:35:23.671 -0600\nOS Version: macOS 27.0 (26A428)\nReport Version: 7\nAnalysis Tool: /usr/bin/vmmap\n\nPhysical footprint: 300.9M\nPhysical footprint (peak): 340.0M\nIdle exit: untracked\n----\n\nReadOnly portion of Libraries: Total=943.4M resident=441.6M(47%) swapped_out_or_unallocated=501.8M(53%)\nWritable regions: Total=2.6G written=22.9M(1%) resident=89.0M(3%) swapped_out=64K(0%) unallocated=2.5G(97%)\n\n VIRTUAL RESIDENT DIRTY SWAPPED VOLATILE NONVOL EMPTY REGION \nREGION TYPE SIZE SIZE SIZE SIZE SIZE SIZE SIZE COUNT (non-coalesced) \n=========== ======= ======== ===== ======= ======== ====== ===== ======= \nActivity Tracing 256K 8K 32K 0K 0K 8K 0K 1 \nCoreGraphics 8K 8K 8K 0K 0K 0K 0K 2 \nCoreGraphics (reserved) 8K 0K 0K 0K 0K 0K 0K 1 reserved VM address space (unallocated)\nFoundation 16K 4K 4K 0K 0K 0K 0K 1 \nGuard 385.0G 0K 0K 0K 0K 0K 0K 1 \nIOAccelerator 64K 64K 64K 0K 0K 0K 0K 2 \nIOAccelerator (graphics) 257.9M 64.4M 257.6M 0K 0K 64.4M 0K 25 \nIOKit 96K 84K 96K 0K 0K 4K 0K 7 \nIOSurface 16K 0K 0K 0K 0K 0K 0K 1 \nMalloc Guard Page 288K 0K 0K 0K 0K 0K 0K 18 see MALLOC ZONE table below\nMalloc Large (reserved) 14.0M 0K 0K 0K 0K 0K 0K 1 see MALLOC ZONE table below\nMalloc Large metadata 16K 4K 4K 0K 0K 0K 0K 1 see MALLOC ZONE table below\nMalloc Medium 384.0M 1988K 1988K 0K 0K 0K 0K 3 see MALLOC ZONE table below\nMalloc Medium (empty) 128.0M 36K 36K 0K 0K 0K 0K 1 see MALLOC ZONE table below\nMalloc Metadata 348K 300K 300K 0K 0K 0K 0K 18 see MALLOC ZONE table below\nMalloc Nano 512.0M 4968K 4968K 0K 0K 0K 0K 1 see MALLOC ZONE table below\nMalloc Small 32.0M 2072K 2072K 0K 0K 0K 0K 4 see MALLOC ZONE table below\nMalloc Small (empty) 32.0M 40K 40K 0K 0K 0K 0K 4 see MALLOC ZONE table below\nMalloc Tiny 14.0M 988K 988K 0K 0K 0K 0K 14 see MALLOC ZONE table below\nMalloc Tiny (empty) 5120K 60K 60K 0K 0K 0K 0K 5 see MALLOC ZONE table below\nOS Alloc Once 8K 8K 8K 0K 0K 0K 0K 1 \nRosetta Arena 4096K 272K 272K 0K 0K 0K 0K 2 \nRosetta Generic 2076K 2044K 2044K 0K 0K 0K 0K 513 \nRosetta IndirectBranch 512K 512K 512K 0K 0K 0K 0K 1 \nRosetta JIT 128.0M 2520K 2520K 0K 0K 0K 0K 1 \nRosetta Return Stack 140K 28K 28K 0K 0K 0K 0K 14 \nRosetta Thread Context 140K 40K 40K 0K 0K 0K 0K 14 \nStack 10.0M 172K 172K 0K 0K 0K 0K 6 \nStack Guard 56.0M 0K 0K 0K 0K 0K 0K 5 \nUntagged 32.3M 13.5M 13.5M 0K 0K 0K 0K 180 \nUntagged (reserved) 8224K 0K 0K 0K 0K 0K 0K 6 reserved VM address space (unallocated)\nWINE_RESERVE 8.0G 6144K Line truncated
"stderr": "",
"seconds": 4.344917624955997
}
@@ -0,0 +1,9 @@
{
"command": [
"vm_stat"
],
"exit": 0,
"stdout": "Mach Virtual Memory Statistics: (page size of 16384 bytes)\nPages free: 95685.\nPages active: 369536.\nPages inactive: 367761.\nPages speculative: 942.\nPages throttled: 0.\nPages wired down: 164523.\nPages purgeable: 10328.\n\"Translation faults\": 2326687255.\nPages copy-on-write: 97448149.\nPages zero filled: 1678382003.\nPages reactivated: 187884738.\nPages purged: 19293118.\nFile-backed pages: 255290.\nAnonymous pages: 482949.\nPages stored in compressor: 1951454.\nPages occupied by compressor: 535704.\nDecompressions: 147971725.\nCompressions: 186322605.\nPageins: 47232046.\nPageouts: 921014.\nSwapins: 1663220.\nSwapouts: 2468999.\n",
"stderr": "",
"seconds": 0.0030907500186003745
}
@@ -0,0 +1,14 @@
{
"command": [
"footprint",
"-p",
"54264",
"-f",
"bytes",
"--swapped"
],
"exit": 0,
"stdout": "================================================================================\na-probe.exe [54264]: 64-bit (translated) Footprint: 314446024 B (4096 bytes per page)\n================================================================================\n\n Dirty (Swapped) Clean Reclaimable Regions Category\n --- --- --- --- --- ---\n270155776 B 270057472 B 0 B 0 B 25 IOAccelerator (graphics)\n 14241792 B 12517376 B 0 B 0 B 202 Untagged\n 5869568 B 5644288 B 421888 B 0 B 188 WINE_RESERVE\n 5087232 B 2461696 B 0 B 0 B 1 Malloc Nano\n 2953416 B 0 B 0 B 0 B 1 page table\n 2613248 B 1671168 B 0 B 0 B 1 Rosetta JIT\n 2183168 B 1302528 B 0 B 0 B 9 Malloc Small\n 2097152 B 1327104 B 0 B 0 B 514 Rosetta Generic\n 2072576 B 2023424 B 0 B 0 B 4 Malloc Medium\n 1871872 B 1806336 B 0 B 0 B 620 __DATA_CONST\n 1643874 B 1099631 B 0 B 0 B 600 __DATA\n 1073152 B 356352 B 0 B 0 B 19 Malloc Tiny\n 585324 B 229685 B 0 B 0 B 523 __DATA_DIRTY\n 524288 B 0 B 0 B 0 B 1 Rosetta IndirectBranch\n 315392 B 262144 B 13836288 B 0 B 145 mapped file\n 307200 B 114688 B 0 B 0 B 36 Malloc Metadata\n 278528 B 90112 B 0 B 0 B 2 Rosetta Arena\n 176128 B 65536 B 0 B 0 B 11 Stack\n 82450 B 55132 B 0 B 0 B 1356 unused dyld shared cache area\n 73728 B 0 B 0 B 0 B 5 IOKit\n 65536 B 0 B 0 B 0 B 2 IOAccelerator\n 36864 B 0 B 0 B 0 B 12 Rosetta Thread Context\n 32768 B 16384 B 0 B 0 B 1 Activity Tracing\n 31248 B 0 B 0 B 0 B 1 __OBJC_RW\n 24576 B 0 B 0 B 0 B 12 Rosetta Return Stack\n 16384 B 4096 B 0 B 0 B 2 WINE_TOP_DOWN\n 8192 B 0 B 0 B 0 B 1 OS Alloc Once\n 8192 B 0 B 0 B 0 B 3 CoreGraphics\n 4112 B 0 B 0 B 0 B 4 __TPRO_CONST\n 4096 B 0 B 2387968 B 0 B 653 __TEXT\n 4096 B 0 B 0 B 0 B 2 Malloc Large\n 4096 B 4096 B 0 B 0 B 1 Foundation\n 0 B 0 B 303104 B 0 B 25 __LINKEDIT\n 0 B 0 B 0 B 0 B 1 __OBJC_RO\n 0 B 0 B 0 B 0 B 1 __FONT_DATA\n 0 B 0 B 0 B 0 B 1 IOSurface\n 0 B 0 B 0 B 0 B 1 __CTF\n --- --- --- --- --- ---\n314446024 B 301109248 B 16949248 B 0 B 4988 TOTAL\n\nAuxiliary data:\n phys_footprint: 315699400 B\n phys_footprint_peak: 1391537328 B\n\n",
"stderr": "",
"seconds": 0.07671083294553682
}
@@ -0,0 +1,10 @@
{
"command": [
"memory_pressure",
"-Q"
],
"exit": 0,
"stdout": "The system has 25769803776 (1572864 pages with a page size of 16384).\nSystem-wide memory free percentage: 52%\n",
"stderr": "",
"seconds": 0.003495541983284056
}
@@ -0,0 +1,10 @@
{
"command": [
"sysctl",
"vm.swapusage"
],
"exit": 0,
"stdout": "vm.swapusage: total = 6144.00M used = 5324.38M free = 819.62M (encrypted)\n",
"stderr": "",
"seconds": 0.002628665999509394
}
Loaded 100 of 3058 files, more files were not shown because too many files have changed in this diff. Show more