Return ApuFree blocks to the APU heap stand-in #1414

Merged
tedin7 merged 3 commits from upstream-pr/1421 into main 2026-11-24 11:42:19 +00:00
tedin7 commented 2026-11-24 11:11:22 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T11:11:22Z.


Change

The AcpHal stand-in (permissive mode) served ApuAlloc with a bump allocator and ApuFree was a logged no-op, so a long run of allocate and free cycles (for example streaming audio banks) ends in E_OUTOFMEMORY. The heap is now a first-fit free list with coalescing in a static table of 4096 extents, guarded by one SRW lock. ApuFree returns the block and merges it with free neighbours. While nothing is freed the offsets match the old bump allocator.

Behaviour chosen where the console's codes are not public (documented in docs/startup-runtime.md): size 0 or a non power-of-two alignment is E_INVALIDARG (before: size 0 succeeded, a bad alignment was silently set to 16; 0 and below 16 still mean 16); ApuFree(NULL) stays S_OK; an address that does not start a live block (unknown, interior, already freed) is E_INVALIDARG and changes nothing; a reused block is zeroed like fresh heap memory. A refused call leaves heap and outputs unchanged. Size and alignment stay 32-bit. AcpHalAllocateShapeContexts is untouched (separate work).

The diff is a bit over the usual size: acphal.cpp is about 100 lines, the rest is the test, one CMake entry and two short docs.

Verification

AI-assisted (Claude Code); commands listed were executed locally. Linux, clang++-19 (mingw target) for the DLL, mingw g++ 14 for the test, Wine:

  • New test startup_acphal_apu_free (tests/startup_acphal_apu_free.cpp) against this branch: 8 of 8 runs print ok.
  • Same test against origin/main's acphal.cpp: 35 failures (churn, coalescing, size 0, alignment, foreign frees).
  • Mutations of the new code, each must fail: ApuFree no-op (fails reuse and coalescing), no merge with next, no merge with previous, no zeroing (4 failures), no lock (2 failures in 8 of 8 runs; the lock check is an exact invariant: an interval map of all live blocks plus a whole-heap block at the end).
  • python3 -B tests/docs_links_check.py and tests/bidi_controls_check.py: pass. x2w_pipe.py preflight: WARN only (doc overlaps, rebased).

To run on the Windows node (not run here, no MSVC): ctest --preset dev --no-tests=error -R '^(startup_acphal_apu_free|startup_stubs)$' -V. This test is outside --preset pr if that preset lists only a subset.

Evidence and follow-up

No fixture data: the test builds its own heap with ApuCreateHeap and checks the block layout from the exports. Follow-ups, separate PRs: AcpHalAllocateShapeContexts for context types other than 4 (E_NOTIMPL); ApuIsVirtualAddressValid still tests the whole heap range, not live blocks.

Checklist

  • This pull request covers one reviewable behavior.
  • I included the exact command and result for every check I ran.
  • I considered a negative control or failure case for a new fixture.
  • I updated README/docs when a capability or build requirement changed.
  • I did not include game files, dumps, distribution links or secrets.
<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:6580466750 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1421). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T11:11:22Z. --- ## Change The AcpHal stand-in (permissive mode) served `ApuAlloc` with a bump allocator and `ApuFree` was a logged no-op, so a long run of allocate and free cycles (for example streaming audio banks) ends in `E_OUTOFMEMORY`. The heap is now a first-fit free list with coalescing in a static table of 4096 extents, guarded by one SRW lock. `ApuFree` returns the block and merges it with free neighbours. While nothing is freed the offsets match the old bump allocator. Behaviour chosen where the console's codes are not public (documented in docs/startup-runtime.md): size 0 or a non power-of-two alignment is `E_INVALIDARG` (before: size 0 succeeded, a bad alignment was silently set to 16; 0 and below 16 still mean 16); `ApuFree(NULL)` stays `S_OK`; an address that does not start a live block (unknown, interior, already freed) is `E_INVALIDARG` and changes nothing; a reused block is zeroed like fresh heap memory. A refused call leaves heap and outputs unchanged. Size and alignment stay 32-bit. `AcpHalAllocateShapeContexts` is untouched (separate work). The diff is a bit over the usual size: acphal.cpp is about 100 lines, the rest is the test, one CMake entry and two short docs. ## Verification AI-assisted (Claude Code); commands listed were executed locally. Linux, clang++-19 (mingw target) for the DLL, mingw g++ 14 for the test, Wine: - New test `startup_acphal_apu_free` (tests/startup_acphal_apu_free.cpp) against this branch: 8 of 8 runs print `ok`. - Same test against origin/main's acphal.cpp: 35 failures (churn, coalescing, size 0, alignment, foreign frees). - Mutations of the new code, each must fail: ApuFree no-op (fails reuse and coalescing), no merge with next, no merge with previous, no zeroing (4 failures), no lock (2 failures in 8 of 8 runs; the lock check is an exact invariant: an interval map of all live blocks plus a whole-heap block at the end). - `python3 -B tests/docs_links_check.py` and `tests/bidi_controls_check.py`: pass. x2w_pipe.py preflight: WARN only (doc overlaps, rebased). To run on the Windows node (not run here, no MSVC): `ctest --preset dev --no-tests=error -R '^(startup_acphal_apu_free|startup_stubs)$' -V`. This test is outside `--preset pr` if that preset lists only a subset. ## Evidence and follow-up No fixture data: the test builds its own heap with `ApuCreateHeap` and checks the block layout from the exports. Follow-ups, separate PRs: `AcpHalAllocateShapeContexts` for context types other than 4 (E_NOTIMPL); `ApuIsVirtualAddressValid` still tests the whole heap range, not live blocks. ## Checklist - [x] This pull request covers one reviewable behavior. - [x] I included the exact command and result for every check I ran. - [x] I considered a negative control or failure case for a new fixture. - [x] I updated README/docs when a capability or build requirement changed. - [x] I did not include game files, dumps, distribution links or secrets.
upstream-sync closed this pull request 2026-11-24 12:02:52 +00:00
chatgpt-codex-connector[bot commented 2026-11-24 12:02:53 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T11:22:47Z.

Review: COMMENTED


💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 64b6d2d325

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6038310264 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1421#pullrequestreview-6038310264). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T11:22:47Z. **Review:** COMMENTED --- <!-- codex-review-receipt:v1 --> ### 💡 Codex Review Here are some automated review suggestions for this pull request. **Reviewed commit:** `64b6d2d325` <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review". If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". </details>
R0Y00 commented 2026-11-24 12:02:53 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T11:25:41Z.

Review: CHANGES_REQUESTED


The Windows Release allocator fixture passed on 64b6d2d. The new lock still does not protect heap publication: ApuCreateHeap tests and assigns heap_base before taking it. Two first-time callers can commit two allocations, then reset the extent table while another caller already holds a block. Make heap creation and publication one locked operation, with the base, size and initial free extent visible together. Add a first-creation concurrency or repeat-init check which proves a live block survives competing heap creation.

Please also keep the earlier fallback to 16-byte alignment for non-power-of-two values in this reuse PR unless there is evidence for changing that public input contract. The 2 GiB alignment control assumes an address-space placement the process does not control. Use a guaranteed no-fit request to cover that path.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6038353157 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1421#pullrequestreview-6038353157). Originally posted by [R0Y00](https://github.com/R0Y00) on 2026-11-24T11:25:41Z. **Review:** CHANGES_REQUESTED --- The Windows Release allocator fixture passed on 64b6d2d. The new lock still does not protect heap publication: ApuCreateHeap tests and assigns heap_base before taking it. Two first-time callers can commit two allocations, then reset the extent table while another caller already holds a block. Make heap creation and publication one locked operation, with the base, size and initial free extent visible together. Add a first-creation concurrency or repeat-init check which proves a live block survives competing heap creation. Please also keep the earlier fallback to 16-byte alignment for non-power-of-two values in this reuse PR unless there is evidence for changing that public input contract. The 2 GiB alignment control assumes an address-space placement the process does not control. Use a guaranteed no-fit request to cover that path.
tedin7 commented 2026-11-24 12:02:53 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T11:29:34Z.

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6038402024 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1421#pullrequestreview-6038402024). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T11:29:34Z. **Review:** COMMENTED --- _No description provided._
tedin7 commented 2026-11-24 12:02:53 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T11:29:36Z.

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6038402391 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1421#pullrequestreview-6038402391). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T11:29:36Z. **Review:** COMMENTED --- _No description provided._
R0Y00 commented 2026-11-24 12:02:53 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T11:42:01Z.

Review: APPROVED


Re-reviewed the heap publication fix and alignment fallback. Windows Release startup_acphal_apu_free passed on this head, including the concurrent create and repeat-init controls.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6038556047 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1421#pullrequestreview-6038556047). Originally posted by [R0Y00](https://github.com/R0Y00) on 2026-11-24T11:42:01Z. **Review:** APPROVED --- Re-reviewed the heap publication fix and alignment fallback. Windows Release startup_acphal_apu_free passed on this head, including the concurrent create and repeat-init controls.
tedin7 commented 2026-11-24 12:03:14 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T11:16:48Z.


Verified on Windows Server 2025 (Build 26100, MSVC 14.44.35207) at commit 64b6d2d3:

  • Debug (--preset dev): ctest --preset dev -R '^startup_acphal_apu_free$' --no-tests=error --output-on-failure — 1/1 passed (0.15s)
  • Release /O2 (--preset release): ctest --preset release -R '^startup_acphal_apu_free$' --no-tests=error --output-on-failure — 1/1 passed (0.04s)
<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7129892203 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1421#issuecomment-7129892203). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T11:16:48Z. --- Verified on Windows Server 2025 (Build 26100, MSVC 14.44.35207) at commit `64b6d2d3`: - **Debug (`--preset dev`)**: `ctest --preset dev -R '^startup_acphal_apu_free$' --no-tests=error --output-on-failure` — **1/1 passed** (0.15s) - **Release `/O2` (`--preset release`)**: `ctest --preset release -R '^startup_acphal_apu_free$' --no-tests=error --output-on-failure` — **1/1 passed** (0.04s)
chatgpt-codex-connector[bot commented 2026-11-24 12:03:15 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T11:16:54Z.


Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-24T11:22:50.344700Z 64b6d2d Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7129894390 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1421#issuecomment-7129894390). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T11:16:54Z. --- <!-- codex-pull-request-review-summary --> <!-- codex-review-state:v1 {"code_review":{"commit_sha":"64b6d2d32545e4de6cdb3c1df4a07ed77564a217","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} --> <details> <summary><strong>Codex Review Summary</strong>: ✅ Completed</summary> This comment shows the latest Codex review activity on this pull request. | Review | Status | Commit | Review trigger | | --- | --- | --- | --- | | 📝 **Code Review** | ✅ **Completed** <relative-time datetime="2026-11-24T11:22:50.344700Z">2026-11-24T11:22:50.344700Z</relative-time> | `64b6d2d` | Draft marked ready | <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review" or "@codex security review". Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. </details> </details>
tedin7 commented 2026-11-24 12:03:17 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T11:37:49Z.


@R0Y00 f9033a9b covers all three points. (a) ApuCreateHeap now allocates, sets the size, builds the initial free extent and publishes heap_base under heap_lock in one step; a repeat call finds the heap and changes nothing. New first_creation test: 4 threads race the first creation, each allocates right after, all blocks are distinct, a repeat creation leaves them live, a later allocation does not reuse them, and all free. (b) A non-power-of-two alignment (24, 3, 0xFFFFFFFF) means 16 again, as before; the test checks 16-byte alignment. (c) The placement-dependent 2 GiB check is replaced by a request of usable+16 bytes at 2 GiB alignment, which cannot fit wherever the heap lands, and leaves outputs untouched. Windows Server 2025 Debug and Release: startup_acphal_apu_free 1/1.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7130344588 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1421#issuecomment-7130344588). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T11:37:49Z. --- @R0Y00 f9033a9b covers all three points. (a) ApuCreateHeap now allocates, sets the size, builds the initial free extent and publishes heap_base under heap_lock in one step; a repeat call finds the heap and changes nothing. New first_creation test: 4 threads race the first creation, each allocates right after, all blocks are distinct, a repeat creation leaves them live, a later allocation does not reuse them, and all free. (b) A non-power-of-two alignment (24, 3, 0xFFFFFFFF) means 16 again, as before; the test checks 16-byte alignment. (c) The placement-dependent 2 GiB check is replaced by a request of usable+16 bytes at 2 GiB alignment, which cannot fit wherever the heap lands, and leaves outputs untouched. Windows Server 2025 Debug and Release: startup_acphal_apu_free 1/1.
chatgpt-codex-connector[bot commented 2026-11-24 12:03:21 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T11:22:47Z.

Code review location: tests/startup_acphal_apu_free.cpp; line 146

@@ -0,0 +1,273 @@
+// Source-built check of the AcpHal stand-in APU heap (src/startup_stubs/acphal.cpp): ApuFree returns blocks,
+// neighbours coalesce, bad requests leave the heap alone and concurrent callers never get overlapping blocks.
+// Usage: startup_acphal_apu_free <AcpHal.dll>
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#include <windows.h>
+
+#include <atomic>
+#include <cstdint>
+#include <cstdio>
+#include <cstring>
+#include <iterator>
+#include <map>
+#include <mutex>
+#include <thread>
+#include <vector>
+
+namespace {
+using u64 = std::uint64_t;
+using AllocFn = long(__cdecl*)(void**, std::uint32_t*, u64, u64, u64);
+using FreeFn = long(__cdecl*)(void*);
+using CreateFn = long(__cdecl*)(u64, u64);
+using MapFn = std::uint32_t(__cdecl*)(void*);
+
+constexpr long ok = 0, invalid = static_cast<long>(0x80070057), no_memory = static_cast<long>(0x8007000E),
+               no_pointer = static_cast<long>(0x80004003);
+constexpr u64 heap_size = 0x200000, first_offset = 0x10000, usable = heap_size - first_offset;
+
+AllocFn alloc_fn;
+FreeFn free_fn;
+MapFn map_fn;
+int failures;
+
+void check(bool condition, const char* what)
+{
+    if (condition) return;
+    std::printf("FAIL: %s\n", what);
+    ++failures;
+}
+
+long take(void** out, u64 size, u64 alignment = 16, std::uint32_t* apu = nullptr) { return alloc_fn(out, apu, size, alignment, 0); }
+
+void* take_ok(u64 size, u64 alignment = 16)
+{
+    void* p = nullptr;
+    const long hr = take(&p, size, alignment);
+    check(hr == ok && p, "allocation succeeds");
+    return p;
+}
+
+// The whole heap is free again exactly when one block of the full usable size fits at the first offset.
+void check_empty(const char* where)
+{
+    std::uint32_t apu = 0;
+    void* p = nullptr;
+    const long hr = take(&p, usable, 16, &apu);
+    if (hr != ok || !p || apu != first_offset) {
+        std::printf("FAIL: heap not whole after %s (hr=0x%08lx apu=0x%x)\n", where, static_cast<unsigned long>(hr), apu);
+        ++failures;
+        return;
+    }
+    check(free_fn(p) == ok, "whole-heap block frees");
+}
+
+void churn_beyond_capacity()
+{
+    void* a = take_ok(0x100000, 4096);
+    void* b = nullptr;
+    check(take(&b, 0x100000, 4096) == no_memory && !b, "two 1 MiB blocks do not fit while the first is live");
+    check(free_fn(a) == ok, "free first");
+    for (int round = 0; round < 64; ++round) {  // 64 MiB handed out in total, over 30 times the heap
+        void* p = take_ok(0x100000, 4096);
+        check(p == a, "same block comes back");
+        if (!p) return;
+        check(free_fn(p) == ok, "churn free");
+    }
+    check_empty("churn");
+}
+
+void reuse_and_alignment()
+{
+    for (u64 alignment : {16u, 256u, 4096u, 65536u}) {
+        void* keep = take_ok(0x30, 16);
+        void* a = take_ok(0x2000, alignment);
+        void* after = take_ok(0x30, 16);
+        check(reinterpret_cast<std::uintptr_t>(a) % alignment == 0, "alignment honoured");
+        std::memset(a, 0xAA, 0x2000);
+        check(free_fn(a) == ok, "free");
+        void* again = take_ok(0x2000, alignment);
+        check(again == a, "same size returns the freed block");
+        bool zero = true;
+        for (int i = 0; i < 0x2000; ++i) zero = zero && static_cast<unsigned char*>(again)[i] == 0;
+        check(zero, "reused block is zeroed like fresh heap memory");
+        check(free_fn(again) == ok, "free again");
+        void* smaller = take_ok(0x1000, alignment);
+        check(smaller >= a && static_cast<unsigned char*>(smaller) + 0x1000 <= static_cast<unsigned char*>(a) + 0x2000,
+              "smaller request lands inside the freed block");
+        std::uint32_t apu = 0;
+        void* mapped = nullptr;
+        check(take(&mapped, 0x40, 64, &apu) == ok && map_fn(mapped) == apu && apu, "APU address maps back to the block");
+        for (void* p : {keep, after, smaller, mapped}) check(free_fn(p) == ok, "cleanup free");
+        check_empty("reuse");
+    }
+}
+
+void coalescing()
+{
+    constexpr u64 part = 0x10000;
+    void* a = take_ok(part);
+    void* b = take_ok(part);
+    void* c = take_ok(part);
+    void* rest = take_ok(usable - 3 * part);  // fills the heap: only A, B, C can ever be free
+    auto* base = static_cast<unsigned char*>(a);
+    check(b == base + part && c == base + 2 * part, "A, B and C are contiguous");
+    check(free_fn(a) == ok && free_fn(c) == ok, "free A and C");
+    void* big = nullptr;
+    check(take(&big, 3 * part) == no_memory && !big, "A+B+C does not fit while B is live");
+    check(free_fn(b) == ok, "free B");
+    big = take_ok(3 * part);
+    check(big == a, "A+B+C is one block at A");
+    check(free_fn(big) == ok && free_fn(rest) == ok, "cleanup");
+    check_empty("coalescing");
+    void* x = take_ok(part);  // reverse order, middle first
+    void* y = take_ok(part);
+    void* z = take_ok(part);
+    check(free_fn(y) == ok && free_fn(z) == ok && free_fn(x) == ok, "free middle, last, first");
+    check_empty("coalescing reverse");
+}
+
+void bad_requests()
+{
+    const void* const sentinel = reinterpret_cast<void*>(0x1234);
+    void* out = const_cast<void*>(sentinel);
+    std::uint32_t apu = 0xDEADBEEF;
+    check(free_fn(nullptr) == ok, "free(null) is a no-op");
+    check(take(nullptr, 64) == no_pointer, "null output");
+    check(take(&out, usable + 16, 16, &apu) == no_memory && !out && apu == 0xDEADBEEF, "larger than the heap");
+    out = const_cast<void*>(sentinel);
+    check(take(&out, 0xFFFFFFFFull, 16, &apu) == no_memory && !out, "size near 2^32");
+    check(take(&out, ~u64{0}, 16, &apu) == no_memory && !out, "size 2^64-1 is cut to 32 bits");
+    check(take(&out, 0, 16, &apu) == invalid && !out && apu == 0xDEADBEEF, "size 0");
+    check(take(&out, 0x100000000ull, 16, &apu) == invalid && !out, "size 2^32 is size 0");
+    check(take(&out, 64, 24, &apu) == invalid && !out && apu == 0xDEADBEEF, "alignment 24");
+    check(take(&out, 64, 0xFFFFFFFFull, &apu) == invalid && !out, "alignment 2^32-1");
+    check(take(&out, 64, 0x80000000ull, &apu) == no_memory && !out, "alignment 2 GiB cannot be met");

P2 Badge Make the large-alignment refusal test placement-independent

If the heap straddles a 2 GiB virtual-address boundary, this allocation can legitimately succeed: a heap base of 0x1ffff0000 puts its first usable byte at 0x200000000, which already satisfies the requested alignment. A Linux probe of the extracted allocator/test logic reproduced this success and five cascading test failures, because this assertion also leaves the unexpectedly successful allocation unreleased. Derive the expected result from the actual heap placement or construct a guaranteed exhaustion case instead of assuming that alignment larger than the heap implies failure.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4679252606 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1421#discussion_r4679252606). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T11:22:47Z. **Code review location:** `tests/startup_acphal_apu_free.cpp`; line 146 ~~~~diff @@ -0,0 +1,273 @@ +// Source-built check of the AcpHal stand-in APU heap (src/startup_stubs/acphal.cpp): ApuFree returns blocks, +// neighbours coalesce, bad requests leave the heap alone and concurrent callers never get overlapping blocks. +// Usage: startup_acphal_apu_free <AcpHal.dll> +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include <windows.h> + +#include <atomic> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <iterator> +#include <map> +#include <mutex> +#include <thread> +#include <vector> + +namespace { +using u64 = std::uint64_t; +using AllocFn = long(__cdecl*)(void**, std::uint32_t*, u64, u64, u64); +using FreeFn = long(__cdecl*)(void*); +using CreateFn = long(__cdecl*)(u64, u64); +using MapFn = std::uint32_t(__cdecl*)(void*); + +constexpr long ok = 0, invalid = static_cast<long>(0x80070057), no_memory = static_cast<long>(0x8007000E), + no_pointer = static_cast<long>(0x80004003); +constexpr u64 heap_size = 0x200000, first_offset = 0x10000, usable = heap_size - first_offset; + +AllocFn alloc_fn; +FreeFn free_fn; +MapFn map_fn; +int failures; + +void check(bool condition, const char* what) +{ + if (condition) return; + std::printf("FAIL: %s\n", what); + ++failures; +} + +long take(void** out, u64 size, u64 alignment = 16, std::uint32_t* apu = nullptr) { return alloc_fn(out, apu, size, alignment, 0); } + +void* take_ok(u64 size, u64 alignment = 16) +{ + void* p = nullptr; + const long hr = take(&p, size, alignment); + check(hr == ok && p, "allocation succeeds"); + return p; +} + +// The whole heap is free again exactly when one block of the full usable size fits at the first offset. +void check_empty(const char* where) +{ + std::uint32_t apu = 0; + void* p = nullptr; + const long hr = take(&p, usable, 16, &apu); + if (hr != ok || !p || apu != first_offset) { + std::printf("FAIL: heap not whole after %s (hr=0x%08lx apu=0x%x)\n", where, static_cast<unsigned long>(hr), apu); + ++failures; + return; + } + check(free_fn(p) == ok, "whole-heap block frees"); +} + +void churn_beyond_capacity() +{ + void* a = take_ok(0x100000, 4096); + void* b = nullptr; + check(take(&b, 0x100000, 4096) == no_memory && !b, "two 1 MiB blocks do not fit while the first is live"); + check(free_fn(a) == ok, "free first"); + for (int round = 0; round < 64; ++round) { // 64 MiB handed out in total, over 30 times the heap + void* p = take_ok(0x100000, 4096); + check(p == a, "same block comes back"); + if (!p) return; + check(free_fn(p) == ok, "churn free"); + } + check_empty("churn"); +} + +void reuse_and_alignment() +{ + for (u64 alignment : {16u, 256u, 4096u, 65536u}) { + void* keep = take_ok(0x30, 16); + void* a = take_ok(0x2000, alignment); + void* after = take_ok(0x30, 16); + check(reinterpret_cast<std::uintptr_t>(a) % alignment == 0, "alignment honoured"); + std::memset(a, 0xAA, 0x2000); + check(free_fn(a) == ok, "free"); + void* again = take_ok(0x2000, alignment); + check(again == a, "same size returns the freed block"); + bool zero = true; + for (int i = 0; i < 0x2000; ++i) zero = zero && static_cast<unsigned char*>(again)[i] == 0; + check(zero, "reused block is zeroed like fresh heap memory"); + check(free_fn(again) == ok, "free again"); + void* smaller = take_ok(0x1000, alignment); + check(smaller >= a && static_cast<unsigned char*>(smaller) + 0x1000 <= static_cast<unsigned char*>(a) + 0x2000, + "smaller request lands inside the freed block"); + std::uint32_t apu = 0; + void* mapped = nullptr; + check(take(&mapped, 0x40, 64, &apu) == ok && map_fn(mapped) == apu && apu, "APU address maps back to the block"); + for (void* p : {keep, after, smaller, mapped}) check(free_fn(p) == ok, "cleanup free"); + check_empty("reuse"); + } +} + +void coalescing() +{ + constexpr u64 part = 0x10000; + void* a = take_ok(part); + void* b = take_ok(part); + void* c = take_ok(part); + void* rest = take_ok(usable - 3 * part); // fills the heap: only A, B, C can ever be free + auto* base = static_cast<unsigned char*>(a); + check(b == base + part && c == base + 2 * part, "A, B and C are contiguous"); + check(free_fn(a) == ok && free_fn(c) == ok, "free A and C"); + void* big = nullptr; + check(take(&big, 3 * part) == no_memory && !big, "A+B+C does not fit while B is live"); + check(free_fn(b) == ok, "free B"); + big = take_ok(3 * part); + check(big == a, "A+B+C is one block at A"); + check(free_fn(big) == ok && free_fn(rest) == ok, "cleanup"); + check_empty("coalescing"); + void* x = take_ok(part); // reverse order, middle first + void* y = take_ok(part); + void* z = take_ok(part); + check(free_fn(y) == ok && free_fn(z) == ok && free_fn(x) == ok, "free middle, last, first"); + check_empty("coalescing reverse"); +} + +void bad_requests() +{ + const void* const sentinel = reinterpret_cast<void*>(0x1234); + void* out = const_cast<void*>(sentinel); + std::uint32_t apu = 0xDEADBEEF; + check(free_fn(nullptr) == ok, "free(null) is a no-op"); + check(take(nullptr, 64) == no_pointer, "null output"); + check(take(&out, usable + 16, 16, &apu) == no_memory && !out && apu == 0xDEADBEEF, "larger than the heap"); + out = const_cast<void*>(sentinel); + check(take(&out, 0xFFFFFFFFull, 16, &apu) == no_memory && !out, "size near 2^32"); + check(take(&out, ~u64{0}, 16, &apu) == no_memory && !out, "size 2^64-1 is cut to 32 bits"); + check(take(&out, 0, 16, &apu) == invalid && !out && apu == 0xDEADBEEF, "size 0"); + check(take(&out, 0x100000000ull, 16, &apu) == invalid && !out, "size 2^32 is size 0"); + check(take(&out, 64, 24, &apu) == invalid && !out && apu == 0xDEADBEEF, "alignment 24"); + check(take(&out, 64, 0xFFFFFFFFull, &apu) == invalid && !out, "alignment 2^32-1"); + check(take(&out, 64, 0x80000000ull, &apu) == no_memory && !out, "alignment 2 GiB cannot be met"); ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Make the large-alignment refusal test placement-independent** If the heap straddles a 2 GiB virtual-address boundary, this allocation can legitimately succeed: a heap base of `0x1ffff0000` puts its first usable byte at `0x200000000`, which already satisfies the requested alignment. A Linux probe of the extracted allocator/test logic reproduced this success and five cascading test failures, because this assertion also leaves the unexpectedly successful allocation unreleased. Derive the expected result from the actual heap placement or construct a guaranteed exhaustion case instead of assuming that alignment larger than the heap implies failure. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
chatgpt-codex-connector[bot commented 2026-11-24 12:03:21 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T11:22:47Z.

Code review location: docs/startup-runtime.md; line 475

@@ -463,6 +463,29 @@ format and Windows build. A skip is neither a pass nor a failure. Every wait is
 Not established: the layout of the console audio command queue (`xapu.cpp` is not decoded
 here), what is audible (no capture-path check), and any hardware or driver glitch count.
 
+## APU heap stand-in
+
+With `X2W_AUDIO_PERMISSIVE=1`, `AcpHal.dll` serves `ApuAlloc` from the heap that `ApuCreateHeap` commits. The
+heap is a first-fit free list in a static table of 4096 extents, guarded by one lock. `ApuFree` gives a
+block back and merges it with free neighbours, so streaming code that allocates and frees repeatedly no
+longer exhausts the heap. While nothing has been freed the offsets are the ones a bump allocator hands out.
+
+- A block is aligned in address (a power of two, 16 at least; 0 means 16). Size and alignment are 32 bits.
+- Null output is `E_POINTER`; size 0 or an alignment that is not a power of two is `E_INVALIDARG`; no
+  room, or a full extent table, is `E_OUTOFMEMORY`. A refused call leaves the heap and its outputs as they were.

P2 Badge Correct the failure-output preservation guarantee

For a refused allocation with an already-populated virtual-address output, this guarantee is false: ApuAlloc unconditionally assigns memory to *virtual_address, clearing the previous value to null on failure. Only the optional APU-address output remains unchanged, and the new bad_requests() assertions explicitly require the virtual output to become null. Callers relying on this documented preservation contract can therefore lose an existing pointer during error handling. Document the actual null-on-failure behavior or update the implementation and tests to honor the promise.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4679252620 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1421#discussion_r4679252620). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T11:22:47Z. **Code review location:** `docs/startup-runtime.md`; line 475 ~~~~diff @@ -463,6 +463,29 @@ format and Windows build. A skip is neither a pass nor a failure. Every wait is Not established: the layout of the console audio command queue (`xapu.cpp` is not decoded here), what is audible (no capture-path check), and any hardware or driver glitch count. +## APU heap stand-in + +With `X2W_AUDIO_PERMISSIVE=1`, `AcpHal.dll` serves `ApuAlloc` from the heap that `ApuCreateHeap` commits. The +heap is a first-fit free list in a static table of 4096 extents, guarded by one lock. `ApuFree` gives a +block back and merges it with free neighbours, so streaming code that allocates and frees repeatedly no +longer exhausts the heap. While nothing has been freed the offsets are the ones a bump allocator hands out. + +- A block is aligned in address (a power of two, 16 at least; 0 means 16). Size and alignment are 32 bits. +- Null output is `E_POINTER`; size 0 or an alignment that is not a power of two is `E_INVALIDARG`; no + room, or a full extent table, is `E_OUTOFMEMORY`. A refused call leaves the heap and its outputs as they were. ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Correct the failure-output preservation guarantee** For a refused allocation with an already-populated virtual-address output, this guarantee is false: `ApuAlloc` unconditionally assigns `memory` to `*virtual_address`, clearing the previous value to null on failure. Only the optional APU-address output remains unchanged, and the new `bad_requests()` assertions explicitly require the virtual output to become null. Callers relying on this documented preservation contract can therefore lose an existing pointer during error handling. Document the actual null-on-failure behavior or update the implementation and tests to honor the promise. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
tedin7 commented 2026-11-24 12:03:22 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T11:29:34Z.

Code review location: tests/startup_acphal_apu_free.cpp; line 146

@@ -0,0 +1,273 @@
+// Source-built check of the AcpHal stand-in APU heap (src/startup_stubs/acphal.cpp): ApuFree returns blocks,
+// neighbours coalesce, bad requests leave the heap alone and concurrent callers never get overlapping blocks.
+// Usage: startup_acphal_apu_free <AcpHal.dll>
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#include <windows.h>
+
+#include <atomic>
+#include <cstdint>
+#include <cstdio>
+#include <cstring>
+#include <iterator>
+#include <map>
+#include <mutex>
+#include <thread>
+#include <vector>
+
+namespace {
+using u64 = std::uint64_t;
+using AllocFn = long(__cdecl*)(void**, std::uint32_t*, u64, u64, u64);
+using FreeFn = long(__cdecl*)(void*);
+using CreateFn = long(__cdecl*)(u64, u64);
+using MapFn = std::uint32_t(__cdecl*)(void*);
+
+constexpr long ok = 0, invalid = static_cast<long>(0x80070057), no_memory = static_cast<long>(0x8007000E),
+               no_pointer = static_cast<long>(0x80004003);
+constexpr u64 heap_size = 0x200000, first_offset = 0x10000, usable = heap_size - first_offset;
+
+AllocFn alloc_fn;
+FreeFn free_fn;
+MapFn map_fn;
+int failures;
+
+void check(bool condition, const char* what)
+{
+    if (condition) return;
+    std::printf("FAIL: %s\n", what);
+    ++failures;
+}
+
+long take(void** out, u64 size, u64 alignment = 16, std::uint32_t* apu = nullptr) { return alloc_fn(out, apu, size, alignment, 0); }
+
+void* take_ok(u64 size, u64 alignment = 16)
+{
+    void* p = nullptr;
+    const long hr = take(&p, size, alignment);
+    check(hr == ok && p, "allocation succeeds");
+    return p;
+}
+
+// The whole heap is free again exactly when one block of the full usable size fits at the first offset.
+void check_empty(const char* where)
+{
+    std::uint32_t apu = 0;
+    void* p = nullptr;
+    const long hr = take(&p, usable, 16, &apu);
+    if (hr != ok || !p || apu != first_offset) {
+        std::printf("FAIL: heap not whole after %s (hr=0x%08lx apu=0x%x)\n", where, static_cast<unsigned long>(hr), apu);
+        ++failures;
+        return;
+    }
+    check(free_fn(p) == ok, "whole-heap block frees");
+}
+
+void churn_beyond_capacity()
+{
+    void* a = take_ok(0x100000, 4096);
+    void* b = nullptr;
+    check(take(&b, 0x100000, 4096) == no_memory && !b, "two 1 MiB blocks do not fit while the first is live");
+    check(free_fn(a) == ok, "free first");
+    for (int round = 0; round < 64; ++round) {  // 64 MiB handed out in total, over 30 times the heap
+        void* p = take_ok(0x100000, 4096);
+        check(p == a, "same block comes back");
+        if (!p) return;
+        check(free_fn(p) == ok, "churn free");
+    }
+    check_empty("churn");
+}
+
+void reuse_and_alignment()
+{
+    for (u64 alignment : {16u, 256u, 4096u, 65536u}) {
+        void* keep = take_ok(0x30, 16);
+        void* a = take_ok(0x2000, alignment);
+        void* after = take_ok(0x30, 16);
+        check(reinterpret_cast<std::uintptr_t>(a) % alignment == 0, "alignment honoured");
+        std::memset(a, 0xAA, 0x2000);
+        check(free_fn(a) == ok, "free");
+        void* again = take_ok(0x2000, alignment);
+        check(again == a, "same size returns the freed block");
+        bool zero = true;
+        for (int i = 0; i < 0x2000; ++i) zero = zero && static_cast<unsigned char*>(again)[i] == 0;
+        check(zero, "reused block is zeroed like fresh heap memory");
+        check(free_fn(again) == ok, "free again");
+        void* smaller = take_ok(0x1000, alignment);
+        check(smaller >= a && static_cast<unsigned char*>(smaller) + 0x1000 <= static_cast<unsigned char*>(a) + 0x2000,
+              "smaller request lands inside the freed block");
+        std::uint32_t apu = 0;
+        void* mapped = nullptr;
+        check(take(&mapped, 0x40, 64, &apu) == ok && map_fn(mapped) == apu && apu, "APU address maps back to the block");
+        for (void* p : {keep, after, smaller, mapped}) check(free_fn(p) == ok, "cleanup free");
+        check_empty("reuse");
+    }
+}
+
+void coalescing()
+{
+    constexpr u64 part = 0x10000;
+    void* a = take_ok(part);
+    void* b = take_ok(part);
+    void* c = take_ok(part);
+    void* rest = take_ok(usable - 3 * part);  // fills the heap: only A, B, C can ever be free
+    auto* base = static_cast<unsigned char*>(a);
+    check(b == base + part && c == base + 2 * part, "A, B and C are contiguous");
+    check(free_fn(a) == ok && free_fn(c) == ok, "free A and C");
+    void* big = nullptr;
+    check(take(&big, 3 * part) == no_memory && !big, "A+B+C does not fit while B is live");
+    check(free_fn(b) == ok, "free B");
+    big = take_ok(3 * part);
+    check(big == a, "A+B+C is one block at A");
+    check(free_fn(big) == ok && free_fn(rest) == ok, "cleanup");
+    check_empty("coalescing");
+    void* x = take_ok(part);  // reverse order, middle first
+    void* y = take_ok(part);
+    void* z = take_ok(part);
+    check(free_fn(y) == ok && free_fn(z) == ok && free_fn(x) == ok, "free middle, last, first");
+    check_empty("coalescing reverse");
+}
+
+void bad_requests()
+{
+    const void* const sentinel = reinterpret_cast<void*>(0x1234);
+    void* out = const_cast<void*>(sentinel);
+    std::uint32_t apu = 0xDEADBEEF;
+    check(free_fn(nullptr) == ok, "free(null) is a no-op");
+    check(take(nullptr, 64) == no_pointer, "null output");
+    check(take(&out, usable + 16, 16, &apu) == no_memory && !out && apu == 0xDEADBEEF, "larger than the heap");
+    out = const_cast<void*>(sentinel);
+    check(take(&out, 0xFFFFFFFFull, 16, &apu) == no_memory && !out, "size near 2^32");
+    check(take(&out, ~u64{0}, 16, &apu) == no_memory && !out, "size 2^64-1 is cut to 32 bits");
+    check(take(&out, 0, 16, &apu) == invalid && !out && apu == 0xDEADBEEF, "size 0");
+    check(take(&out, 0x100000000ull, 16, &apu) == invalid && !out, "size 2^32 is size 0");
+    check(take(&out, 64, 24, &apu) == invalid && !out && apu == 0xDEADBEEF, "alignment 24");
+    check(take(&out, 64, 0xFFFFFFFFull, &apu) == invalid && !out, "alignment 2^32-1");
+    check(take(&out, 64, 0x80000000ull, &apu) == no_memory && !out, "alignment 2 GiB cannot be met");

Fixed in 71fbc403: probed the actual heap base and derived big_align_fits from whether a 2 GiB boundary falls within [probe_addr, probe_addr + usable), freeing the block if it succeeds. Verified on Win2025 (Debug 0.12s, Release /O2 0.04s).

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4679331460 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1421#discussion_r4679331460). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T11:29:34Z. **Code review location:** `tests/startup_acphal_apu_free.cpp`; line 146 ~~~~diff @@ -0,0 +1,273 @@ +// Source-built check of the AcpHal stand-in APU heap (src/startup_stubs/acphal.cpp): ApuFree returns blocks, +// neighbours coalesce, bad requests leave the heap alone and concurrent callers never get overlapping blocks. +// Usage: startup_acphal_apu_free <AcpHal.dll> +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include <windows.h> + +#include <atomic> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <iterator> +#include <map> +#include <mutex> +#include <thread> +#include <vector> + +namespace { +using u64 = std::uint64_t; +using AllocFn = long(__cdecl*)(void**, std::uint32_t*, u64, u64, u64); +using FreeFn = long(__cdecl*)(void*); +using CreateFn = long(__cdecl*)(u64, u64); +using MapFn = std::uint32_t(__cdecl*)(void*); + +constexpr long ok = 0, invalid = static_cast<long>(0x80070057), no_memory = static_cast<long>(0x8007000E), + no_pointer = static_cast<long>(0x80004003); +constexpr u64 heap_size = 0x200000, first_offset = 0x10000, usable = heap_size - first_offset; + +AllocFn alloc_fn; +FreeFn free_fn; +MapFn map_fn; +int failures; + +void check(bool condition, const char* what) +{ + if (condition) return; + std::printf("FAIL: %s\n", what); + ++failures; +} + +long take(void** out, u64 size, u64 alignment = 16, std::uint32_t* apu = nullptr) { return alloc_fn(out, apu, size, alignment, 0); } + +void* take_ok(u64 size, u64 alignment = 16) +{ + void* p = nullptr; + const long hr = take(&p, size, alignment); + check(hr == ok && p, "allocation succeeds"); + return p; +} + +// The whole heap is free again exactly when one block of the full usable size fits at the first offset. +void check_empty(const char* where) +{ + std::uint32_t apu = 0; + void* p = nullptr; + const long hr = take(&p, usable, 16, &apu); + if (hr != ok || !p || apu != first_offset) { + std::printf("FAIL: heap not whole after %s (hr=0x%08lx apu=0x%x)\n", where, static_cast<unsigned long>(hr), apu); + ++failures; + return; + } + check(free_fn(p) == ok, "whole-heap block frees"); +} + +void churn_beyond_capacity() +{ + void* a = take_ok(0x100000, 4096); + void* b = nullptr; + check(take(&b, 0x100000, 4096) == no_memory && !b, "two 1 MiB blocks do not fit while the first is live"); + check(free_fn(a) == ok, "free first"); + for (int round = 0; round < 64; ++round) { // 64 MiB handed out in total, over 30 times the heap + void* p = take_ok(0x100000, 4096); + check(p == a, "same block comes back"); + if (!p) return; + check(free_fn(p) == ok, "churn free"); + } + check_empty("churn"); +} + +void reuse_and_alignment() +{ + for (u64 alignment : {16u, 256u, 4096u, 65536u}) { + void* keep = take_ok(0x30, 16); + void* a = take_ok(0x2000, alignment); + void* after = take_ok(0x30, 16); + check(reinterpret_cast<std::uintptr_t>(a) % alignment == 0, "alignment honoured"); + std::memset(a, 0xAA, 0x2000); + check(free_fn(a) == ok, "free"); + void* again = take_ok(0x2000, alignment); + check(again == a, "same size returns the freed block"); + bool zero = true; + for (int i = 0; i < 0x2000; ++i) zero = zero && static_cast<unsigned char*>(again)[i] == 0; + check(zero, "reused block is zeroed like fresh heap memory"); + check(free_fn(again) == ok, "free again"); + void* smaller = take_ok(0x1000, alignment); + check(smaller >= a && static_cast<unsigned char*>(smaller) + 0x1000 <= static_cast<unsigned char*>(a) + 0x2000, + "smaller request lands inside the freed block"); + std::uint32_t apu = 0; + void* mapped = nullptr; + check(take(&mapped, 0x40, 64, &apu) == ok && map_fn(mapped) == apu && apu, "APU address maps back to the block"); + for (void* p : {keep, after, smaller, mapped}) check(free_fn(p) == ok, "cleanup free"); + check_empty("reuse"); + } +} + +void coalescing() +{ + constexpr u64 part = 0x10000; + void* a = take_ok(part); + void* b = take_ok(part); + void* c = take_ok(part); + void* rest = take_ok(usable - 3 * part); // fills the heap: only A, B, C can ever be free + auto* base = static_cast<unsigned char*>(a); + check(b == base + part && c == base + 2 * part, "A, B and C are contiguous"); + check(free_fn(a) == ok && free_fn(c) == ok, "free A and C"); + void* big = nullptr; + check(take(&big, 3 * part) == no_memory && !big, "A+B+C does not fit while B is live"); + check(free_fn(b) == ok, "free B"); + big = take_ok(3 * part); + check(big == a, "A+B+C is one block at A"); + check(free_fn(big) == ok && free_fn(rest) == ok, "cleanup"); + check_empty("coalescing"); + void* x = take_ok(part); // reverse order, middle first + void* y = take_ok(part); + void* z = take_ok(part); + check(free_fn(y) == ok && free_fn(z) == ok && free_fn(x) == ok, "free middle, last, first"); + check_empty("coalescing reverse"); +} + +void bad_requests() +{ + const void* const sentinel = reinterpret_cast<void*>(0x1234); + void* out = const_cast<void*>(sentinel); + std::uint32_t apu = 0xDEADBEEF; + check(free_fn(nullptr) == ok, "free(null) is a no-op"); + check(take(nullptr, 64) == no_pointer, "null output"); + check(take(&out, usable + 16, 16, &apu) == no_memory && !out && apu == 0xDEADBEEF, "larger than the heap"); + out = const_cast<void*>(sentinel); + check(take(&out, 0xFFFFFFFFull, 16, &apu) == no_memory && !out, "size near 2^32"); + check(take(&out, ~u64{0}, 16, &apu) == no_memory && !out, "size 2^64-1 is cut to 32 bits"); + check(take(&out, 0, 16, &apu) == invalid && !out && apu == 0xDEADBEEF, "size 0"); + check(take(&out, 0x100000000ull, 16, &apu) == invalid && !out, "size 2^32 is size 0"); + check(take(&out, 64, 24, &apu) == invalid && !out && apu == 0xDEADBEEF, "alignment 24"); + check(take(&out, 64, 0xFFFFFFFFull, &apu) == invalid && !out, "alignment 2^32-1"); + check(take(&out, 64, 0x80000000ull, &apu) == no_memory && !out, "alignment 2 GiB cannot be met"); ~~~~ --- Fixed in 71fbc403: probed the actual heap base and derived `big_align_fits` from whether a 2 GiB boundary falls within `[probe_addr, probe_addr + usable)`, freeing the block if it succeeds. Verified on Win2025 (Debug 0.12s, Release /O2 0.04s).
tedin7 commented 2026-11-24 12:03:22 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T11:29:36Z.

Code review location: docs/startup-runtime.md; line 475

@@ -463,6 +463,29 @@ format and Windows build. A skip is neither a pass nor a failure. Every wait is
 Not established: the layout of the console audio command queue (`xapu.cpp` is not decoded
 here), what is audible (no capture-path check), and any hardware or driver glitch count.
 
+## APU heap stand-in
+
+With `X2W_AUDIO_PERMISSIVE=1`, `AcpHal.dll` serves `ApuAlloc` from the heap that `ApuCreateHeap` commits. The
+heap is a first-fit free list in a static table of 4096 extents, guarded by one lock. `ApuFree` gives a
+block back and merges it with free neighbours, so streaming code that allocates and frees repeatedly no
+longer exhausts the heap. While nothing has been freed the offsets are the ones a bump allocator hands out.
+
+- A block is aligned in address (a power of two, 16 at least; 0 means 16). Size and alignment are 32 bits.
+- Null output is `E_POINTER`; size 0 or an alignment that is not a power of two is `E_INVALIDARG`; no
+  room, or a full extent table, is `E_OUTOFMEMORY`. A refused call leaves the heap and its outputs as they were.

Fixed in 71fbc403: updated docs/startup-runtime.md to state that a refused call leaves the heap and optional APU-address output unchanged and writes null to the virtual-address output when non-null.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4679331747 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1421#discussion_r4679331747). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T11:29:36Z. **Code review location:** `docs/startup-runtime.md`; line 475 ~~~~diff @@ -463,6 +463,29 @@ format and Windows build. A skip is neither a pass nor a failure. Every wait is Not established: the layout of the console audio command queue (`xapu.cpp` is not decoded here), what is audible (no capture-path check), and any hardware or driver glitch count. +## APU heap stand-in + +With `X2W_AUDIO_PERMISSIVE=1`, `AcpHal.dll` serves `ApuAlloc` from the heap that `ApuCreateHeap` commits. The +heap is a first-fit free list in a static table of 4096 extents, guarded by one lock. `ApuFree` gives a +block back and merges it with free neighbours, so streaming code that allocates and frees repeatedly no +longer exhausts the heap. While nothing has been freed the offsets are the ones a bump allocator hands out. + +- A block is aligned in address (a power of two, 16 at least; 0 means 16). Size and alignment are 32 bits. +- Null output is `E_POINTER`; size 0 or an alignment that is not a power of two is `E_INVALIDARG`; no + room, or a full extent table, is `E_OUTOFMEMORY`. A refused call leaves the heap and its outputs as they were. ~~~~ --- Fixed in 71fbc403: updated `docs/startup-runtime.md` to state that a refused call leaves the heap and optional APU-address output unchanged and writes null to the virtual-address output when non-null.
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
R0Y00/Xbox2Windows!1414
No description provided.