From bfde3acaa1a0995340f580d0e36286a883b7388c Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:14:22 +1000 Subject: [PATCH 01/10] docs: close an open code fence in experiments.md The cpu_native_acphal_hal example block had no closing fence, so the ApuFree section after it, and the text up to the next bare fence, rendered as code and their links were not checked. --- docs/experiments.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/experiments.md b/docs/experiments.md index efca64a674..2913bd0852 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -10329,6 +10329,7 @@ On success the caller exits with `0x8AC`, also with `CPU_CRC_TEST_LIVE_WORKER=1` ```powershell ctest --preset dev --no-tests=error -R '^cpu_native_acphal_hal$' -V ctest --preset release --no-tests=error -R '^cpu_native_acphal_hal$' -V +``` ### ApuFree in the AcpHal stand-in From 4bf9fde5f1298f89d65db5e62c92a671eaf1fd3b Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:58:18 +1000 Subject: [PATCH 02/10] gh #1145 atom 1: count XMA context and XApu command activity in the stand-ins Opt-in with X2W_AUDIO_ACTIVITY=1. AcpHal watches the XMA context array it allocates and counts contexts filled, changed and cleared, plus HAL slot2 submits by type; xapu counts XApuEnqueueCommand calls by command class with no cap. Each DLL logs a line per second when a count moved and has an experimental export with the totals. Off, nothing runs. --- src/startup_stubs/acphal.cpp | 168 ++++++++++++++++++++++++++++++++++ src/startup_stubs/acphal.def | 1 + src/startup_stubs/local_log.h | 10 ++ src/startup_stubs/xapu.cpp | 88 ++++++++++++++++++ src/startup_stubs/xapu.def | 1 + 5 files changed, 268 insertions(+) diff --git a/src/startup_stubs/acphal.cpp b/src/startup_stubs/acphal.cpp index c6c25a4fe9..7289b38846 100644 --- a/src/startup_stubs/acphal.cpp +++ b/src/startup_stubs/acphal.cpp @@ -6,6 +6,8 @@ #include "startup_stubs/local_log.h" #include +#include +#include #include X2W_TRAP_EXPORT(2, AcpHalReleaseShapeContexts) @@ -110,6 +112,139 @@ bool heap_give(const void* virtual_address) return done; } +// Activity counter (#1145), off unless X2W_AUDIO_ACTIVITY=1. It watches the XMA context array that +// AcpHalAllocateShapeContexts hands out and counts how its 64-byte contexts change, without reading any field +// in them: a context that goes from all zero to nonzero is filled, one that changes while nonzero is changed, +// one that returns to all zero is cleared. A thread compares the array with a copy about every 10 ms, so a +// context written across a sample counts twice, and one filled and cleared between two samples not at all. +// HAL slot2 submits are counted by their type argument. Once a second, if a count moved, one line gives the +// counts since the previous line. Off, nothing here runs: no thread, no read of caller memory, no line. +bool activity_on() noexcept { return x2w_local::env_on("X2W_AUDIO_ACTIVITY"); } + +constexpr std::size_t context_words = 64 / sizeof(u64); +constexpr unsigned submit_types = 8; // types 0..7 one by one, then all other types together +struct Activity { + u64 filled, changed, cleared; + u64 submits[submit_types + 1]; +}; +SRWLOCK activity_lock = SRWLOCK_INIT; // guards the five below +const volatile u64* watched; // the XMA contexts, or null +u64* shadow; // their words at the last sample +std::uint32_t watched_count, live; +Activity activity; +volatile LONG activity_started; // set with the first counted event, never cleared + +// Compares the watched contexts with the copy and counts the ones that moved. Hold activity_lock. +void sample_locked() noexcept +{ + live = 0; + for (std::uint32_t c = 0; watched && c < watched_count; ++c) { + bool was = false, now = false, moved = false; + for (std::size_t w = 0; w < context_words; ++w) { + const u64 value = watched[c * context_words + w]; // one aligned 8-byte load, never torn + u64& old = shadow[c * context_words + w]; + was = was || old; + now = now || value; + moved = moved || value != old; + old = value; + } + live += now; + if (moved) ++(!was ? activity.filled : now ? activity.changed : activity.cleared); + } +} + +DWORD WINAPI activity_thread(void*) +{ + Activity reported{}; + ULONGLONG last = GetTickCount64(); + for (;;) { + Sleep(10); + AcquireSRWLockExclusive(&activity_lock); + sample_locked(); + const Activity now = activity; + const std::uint32_t live_now = live, count = watched_count; + ReleaseSRWLockExclusive(&activity_lock); + if (GetTickCount64() - last < 1000) continue; + last = GetTickCount64(); + if (!std::memcmp(&now, &reported, sizeof(now))) continue; + char types[256] = ""; + std::size_t used = 0; + u64 submits = 0; + for (unsigned t = 0; t <= submit_types; ++t) { + const u64 n = now.submits[t] - reported.submits[t]; + submits += n; + if (!n || used >= sizeof(types)) continue; + used += static_cast(t < submit_types ? std::snprintf(types + used, sizeof(types) - used, " %u=%llu", t, n) + : std::snprintf(types + used, sizeof(types) - used, " other=%llu", n)); + } + x2w_local::logf("x2w-audio xma-activity t=%.1f s: contexts filled=%llu changed=%llu cleared=%llu live=%u/%u; " + "hal submits=%llu by type%s", + x2w_local::process_seconds(), now.filled - reported.filled, now.changed - reported.changed, + now.cleared - reported.cleared, live_now, count, submits, types); + reported = now; + } +} + +// Starts the sampler with the first counted event. Hold activity_lock. +void start_locked() noexcept +{ + if (activity_started) return; + activity_started = 1; + if (HANDLE thread = CreateThread(nullptr, 0, activity_thread, nullptr, 0, nullptr)) + CloseHandle(thread); + else + x2w_local::logf("x2w-audio xma-activity: sampler thread not started (error %lu)", GetLastError()); +} + +// Watches a newly allocated XMA array; its content now is the baseline. The caller's last error is kept. +void watch(unsigned char* contexts, std::uint32_t count) noexcept +{ + const DWORD error = GetLastError(); + auto* copy = new (std::nothrow) u64[std::size_t{count} * context_words]; + AcquireSRWLockExclusive(&activity_lock); + sample_locked(); // an earlier array's last changes still count + delete[] shadow; + shadow = copy; + watched = copy ? reinterpret_cast(contexts) : nullptr; + watched_count = copy ? count : 0; + if (copy) std::memcpy(copy, contexts, std::size_t{count} * 64); + start_locked(); + ReleaseSRWLockExclusive(&activity_lock); + x2w_local::logf(copy ? "x2w-audio xma-activity: watching %u contexts" : "x2w-audio xma-activity: no memory to watch %u contexts", + count); + SetLastError(error); +} + +// ApuFree of the watched array: its last changes count, then watching stops before the block can be reused. +void unwatch(const void* block) noexcept +{ + if (!activity_started) return; + const DWORD error = GetLastError(); + AcquireSRWLockExclusive(&activity_lock); + const bool hit = watched && static_cast(watched) == block; + if (hit) { + sample_locked(); + watched = nullptr; + watched_count = live = 0; + delete[] shadow; + shadow = nullptr; + } + ReleaseSRWLockExclusive(&activity_lock); + if (hit) x2w_local::logf("x2w-audio xma-activity: contexts freed, no longer watched"); + SetLastError(error); +} + +void count_submit(unsigned type) noexcept +{ + if (!activity_on()) return; + const DWORD error = GetLastError(); + AcquireSRWLockExclusive(&activity_lock); + ++activity.submits[type < submit_types ? type : submit_types]; + start_locked(); + ReleaseSRWLockExclusive(&activity_lock); + SetLastError(error); +} + // AcpHal object (not COM: slot 0 is the first method). Seen: slot 0 (0x1000, 0x1000) -> HRESULT, a // connect with two queue lengths; slot 2 (type, id, frame, &value, 0) -> HRESULT, a command submit. // Both succeed and are logged; every other slot traps and names itself. @@ -127,6 +262,7 @@ long __stdcall hal_connect(void*, unsigned commands, unsigned messages) } long __stdcall hal_submit(void*, unsigned type, u64 id, unsigned frame, const unsigned* input, u64 extra) { + count_submit(type); static LONG calls; if (x2w_local::first_calls(calls, 16)) x2w_local::logf("x2w-audio AcpHal::slot2(submit) type=%u id=0x%llx frame=0x%x input=%p [0x%x] extra=0x%llx -> S_OK", type, @@ -222,6 +358,7 @@ extern "C" __declspec(noinline) long AcpHalAllocateShapeContexts(u64 rcx, u64 rd x2w_local::logf("x2w-audio XMA contexts: %u x 64 bytes at %p (apu 0x%x)", counts[i], static_cast(memory), apu[i]); } + if (allocated[4] && activity_on()) watch(arrays[4], counts[4]); return 0; } @@ -278,6 +415,7 @@ extern "C" __declspec(noinline) long ApuFree(void* virtual_address) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "ApuFree", 5, reinterpret_cast(virtual_address), 0, 0, 0, _ReturnAddress()); if (!virtual_address) return 0; + unwatch(virtual_address); const long hr = heap_give(virtual_address) ? 0 : static_cast(0x80070057); static LONG calls; if (FAILED(hr) || x2w_local::first_calls(calls, 4)) @@ -322,3 +460,33 @@ extern "C" __declspec(noinline) std::uint32_t ApuMapVirtualAddress(void* virtual if (x2w_local::first_calls(calls, 4)) x2w_local::logf("x2w-audio ApuMapVirtualAddress %p -> 0x%x", virtual_address, result); return result; } + +// Experimental export for the source-built check (tests/startup_acphal_xma_activity.cpp): samples now and writes the +// totals since start to out[0..14]: contexts watched, contexts live, filled, changed, cleared, HAL submits, then +// submits of types 0..7 and of all other types. With X2W_AUDIO_ACTIVITY off it writes zeros and returns FALSE. +extern "C" BOOL WINAPI x2w_acphal_xma_activity(ULONGLONG* out) +{ + if (!out) return FALSE; + const bool on = activity_on(); + Activity now{}; + std::uint32_t count = 0, live_now = 0; + if (on) { + AcquireSRWLockExclusive(&activity_lock); + sample_locked(); + now = activity; + count = watched_count; + live_now = live; + ReleaseSRWLockExclusive(&activity_lock); + } + out[0] = count; + out[1] = live_now; + out[2] = now.filled; + out[3] = now.changed; + out[4] = now.cleared; + out[5] = 0; + for (unsigned t = 0; t <= submit_types; ++t) { + out[5] += now.submits[t]; + out[6 + t] = now.submits[t]; + } + return on; +} diff --git a/src/startup_stubs/acphal.def b/src/startup_stubs/acphal.def index 70a0480079..d316315427 100644 --- a/src/startup_stubs/acphal.def +++ b/src/startup_stubs/acphal.def @@ -9,3 +9,4 @@ EXPORTS ApuIsVirtualAddressValid ApuMapApuAddress ApuMapVirtualAddress + x2w_acphal_xma_activity diff --git a/src/startup_stubs/local_log.h b/src/startup_stubs/local_log.h index bea306fde9..228cfb44e8 100644 --- a/src/startup_stubs/local_log.h +++ b/src/startup_stubs/local_log.h @@ -50,6 +50,16 @@ inline bool first_calls(volatile LONG& counter, LONG limit) noexcept return false; } +// Seconds since this process was created: one time base for lines from different stand-in DLLs. +inline double process_seconds() noexcept +{ + FILETIME created{}, exited{}, kernel{}, user{}, now{}; + if (!GetProcessTimes(GetCurrentProcess(), &created, &exited, &kernel, &user)) return 0; + GetSystemTimeAsFileTime(&now); + const auto ticks = [](const FILETIME& t) { return (std::uint64_t{t.dwHighDateTime} << 32) | t.dwLowDateTime; }; + return ticks(now) > ticks(created) ? static_cast(ticks(now) - ticks(created)) / 1e7 : 0.0; +} + // Number of contiguous readable bytes at start, up to bytes, found by touching one byte per page. // VirtualQuery is not used for this: on the title's multi-gigabyte regions one query takes about a // millisecond (it walks the region to size it). A bad pointer costs a first-chance exception, so diff --git a/src/startup_stubs/xapu.cpp b/src/startup_stubs/xapu.cpp index d3cbc51986..6c97b2b153 100644 --- a/src/startup_stubs/xapu.cpp +++ b/src/startup_stubs/xapu.cpp @@ -214,6 +214,74 @@ long decode_packet(Connection& conn, const unsigned char* c, std::uint32_t& byte return hr_ok; } #endif + +// Activity counter (#1145), off unless X2W_AUDIO_ACTIVITY=1: every XApuEnqueueCommand call, counted by command class, +// taken as the first UINT32 of the command (a stand-in convention, like the result type above), with no cap. +// Classes 0..15 are counted one by one and larger ones together; a command that cannot be read and a call with an +// unknown handle are counted apart. Once a second, if a count moved, one line gives the counts since the previous +// line. Off, nothing here runs: no thread, no read of the command, no line. +constexpr unsigned command_classes = 16; +struct CommandCounts { + u64 by_class[command_classes + 1]; // the last entry: every larger class + u64 unreadable, rejected; +}; +SRWLOCK count_lock = SRWLOCK_INIT; // guards the two below +CommandCounts command_counts; +bool counting_started; + +bool activity_on() noexcept { return x2w_local::env_on("X2W_AUDIO_ACTIVITY"); } + +DWORD WINAPI activity_thread(void*) +{ + CommandCounts reported{}; + for (;;) { + Sleep(1000); + AcquireSRWLockShared(&count_lock); + const CommandCounts now = command_counts; + ReleaseSRWLockShared(&count_lock); + if (!std::memcmp(&now, &reported, sizeof(now))) continue; + char classes[320] = ""; + std::size_t used = 0; + u64 commands = now.unreadable - reported.unreadable; + for (unsigned c = 0; c <= command_classes; ++c) { + const u64 n = now.by_class[c] - reported.by_class[c]; + commands += n; + if (!n || used >= sizeof(classes)) continue; + used += static_cast(c < command_classes ? std::snprintf(classes + used, sizeof(classes) - used, " %u=%llu", c, n) + : std::snprintf(classes + used, sizeof(classes) - used, " other=%llu", n)); + } + x2w_local::logf("x2w-audio xapu-activity t=%.1f s: commands=%llu by class%s unreadable=%llu; rejected=%llu", + x2w_local::process_seconds(), commands, classes, now.unreadable - reported.unreadable, + now.rejected - reported.rejected); + reported = now; + } +} + +// Counts one XApuEnqueueCommand call; the caller's last error is kept. +void count_command(long hr, const void* command) noexcept +{ + if (!activity_on()) return; + const DWORD error = GetLastError(); + const bool readable = hr != hr_handle && x2w_local::readable(command, sizeof(std::uint32_t)); + const std::uint32_t command_class = readable ? *static_cast(command) : 0; + AcquireSRWLockExclusive(&count_lock); + if (hr == hr_handle) + ++command_counts.rejected; + else if (!readable) + ++command_counts.unreadable; + else + ++command_counts.by_class[command_class < command_classes ? command_class : command_classes]; + const bool start = !counting_started; + counting_started = true; + ReleaseSRWLockExclusive(&count_lock); + if (start) { + if (HANDLE thread = CreateThread(nullptr, 0, activity_thread, nullptr, 0, nullptr)) + CloseHandle(thread); + else + x2w_local::logf("x2w-audio xapu-activity: report thread not started (error %lu)", GetLastError()); + } + SetLastError(error); +} } // namespace extern "C" __declspec(noinline) long XApuConnect(u64 rcx, u64 rdx, u64 r8, u64 r9) @@ -359,6 +427,7 @@ extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8 #endif } ReleaseSRWLockExclusive(&connection_lock); + count_command(hr, reinterpret_cast(rdx)); static LONG calls; if (x2w_local::first_calls(calls, 24)) { char command[3 * 0x60 + 1]; @@ -397,3 +466,22 @@ extern "C" __declspec(noinline) long XApuDisconnect(u64 rcx, u64 rdx, u64 r8, u6 x2w_local::logf("x2w-audio XApuDisconnect handle=0x%llx -> S_OK", rcx); return hr_ok; } + +// Experimental export for the source-built check (tests/startup_acphal_xma_activity.cpp): writes the totals since +// start to out[0..18]: commands of classes 0..15, of larger classes, unreadable commands, calls with an unknown +// handle. With X2W_AUDIO_ACTIVITY off it writes zeros and returns FALSE. +extern "C" BOOL WINAPI x2w_xapu_command_counts(ULONGLONG* out) +{ + if (!out) return FALSE; + const bool on = activity_on(); + CommandCounts now{}; + if (on) { + AcquireSRWLockShared(&count_lock); + now = command_counts; + ReleaseSRWLockShared(&count_lock); + } + for (unsigned c = 0; c <= command_classes; ++c) out[c] = now.by_class[c]; + out[command_classes + 1] = now.unreadable; + out[command_classes + 2] = now.rejected; + return on; +} diff --git a/src/startup_stubs/xapu.def b/src/startup_stubs/xapu.def index 16136a6e78..548adb4c96 100644 --- a/src/startup_stubs/xapu.def +++ b/src/startup_stubs/xapu.def @@ -5,3 +5,4 @@ EXPORTS XApuDisconnect XApuEnqueueCommand XApuGetResultCount + x2w_xapu_command_counts From 1249f1252e173a4abf1fe9a623d7cd34e8a5fcc5 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:01:29 +1000 Subject: [PATCH 03/10] gh #1145 atom 2: add startup_acphal_xma_activity A source-built caller fills, changes and clears XMA contexts, submits HAL commands and enqueues XApu commands. The on case checks the exact counts from the exports and the logged lines, and that a freed and reused array is no longer counted; the none case writes only next to the contexts and must count 0; the off case reports nothing. Results, outputs, last errors and context bytes must match with the counter on and off. --- CMakeLists.txt | 8 + tests/startup_acphal_xma_activity.cpp | 456 ++++++++++++++++++++++++++ 2 files changed, 464 insertions(+) create mode 100644 tests/startup_acphal_xma_activity.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 417d155511..d3332a558d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -923,6 +923,14 @@ target_compile_features(startup_chad_check PRIVATE cxx_std_17) add_dependencies(startup_chad_check startup_stub_chad) add_test(NAME startup_chad_check COMMAND startup_chad_check "$") set_tests_properties(startup_chad_check PROPERTIES TIMEOUT 60) +# Activity counter of the AcpHal and XApu stand-ins (X2W_AUDIO_ACTIVITY=1): exact counts, a zero-write control, and +# the same results with the counter on and off (docs/startup-runtime.md). +add_executable(startup_acphal_xma_activity tests/startup_acphal_xma_activity.cpp) +target_compile_features(startup_acphal_xma_activity PRIVATE cxx_std_17) +add_dependencies(startup_acphal_xma_activity startup_stub_acphal startup_stub_xapu) +add_test(NAME startup_acphal_xma_activity COMMAND startup_acphal_xma_activity "$" + "$") +set_tests_properties(startup_acphal_xma_activity PROPERTIES TIMEOUT 60) # BMP writer of the draw dumps (src/startup_stubs/draw_bmp.h); the mutated runs are negative controls. add_executable(startup_draw_bmp_check tests/startup_draw_bmp.cpp) diff --git a/tests/startup_acphal_xma_activity.cpp b/tests/startup_acphal_xma_activity.cpp new file mode 100644 index 0000000000..6b4bc7177c --- /dev/null +++ b/tests/startup_acphal_xma_activity.cpp @@ -0,0 +1,456 @@ +// Source-built check of the activity counter in the AcpHal and XApu stand-ins (src/startup_stubs/acphal.cpp and +// xapu.cpp, X2W_AUDIO_ACTIVITY=1, docs/startup-runtime.md). One caller script fills, changes and clears XMA contexts, +// submits HAL commands and enqueues XApu commands. Each case runs in a child process of its own: +// on counter on: the exports and the logged lines report exactly what the script did, and a freed and +// reused context array is no longer counted +// none counter on, but the caller writes only next to the contexts and sends nothing: every count is 0 and no +// activity line is logged +// off counter unset, same script as on: the exports report nothing and no line is logged +// Every call's result, output and last error, and the final context bytes, must be the same with the counter on and +// off. The 64-byte context stride and the command class (first UINT32) are stand-in conventions, not a console layout. +// Usage: startup_acphal_xma_activity +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using u64 = std::uint64_t; +using CreateHeapFn = long(__cdecl*)(u64, u64); +using AllocFn = long(__cdecl*)(void**, std::uint32_t*, u64, u64, u64); +using FreeFn = long(__cdecl*)(void*); +using HalCreateFn = long(__cdecl*)(void**); +using ShapeAllocFn = long(__cdecl*)(void*); +using HalConnectFn = long(__stdcall*)(void*, unsigned, unsigned); +using HalSubmitFn = long(__stdcall*)(void*, unsigned, u64, unsigned, const unsigned*, u64); +using ConnectFn = long(__cdecl*)(const void*, void*, u64*); +using EnqueueFn = long(__cdecl*)(u64, const void*, u64, u64); +using CountFn = std::uint32_t(__cdecl*)(u64, u64); +using DequeueFn = long(__cdecl*)(u64, void*); +using DisconnectFn = long(__cdecl*)(u64); +using ActivityFn = BOOL(WINAPI*)(ULONGLONG*); + +constexpr std::uint32_t contexts = 350; +constexpr int acphal_fields = 15, xapu_fields = 19; +// x2w_acphal_xma_activity: watched, live, filled, changed, cleared, HAL submits, submits of type 0..7, other types. +enum { watched = 0, live = 1, filled = 2, changed = 3, cleared = 4, submits = 5, submit_type0 = 6, submit_other = 14 }; +// x2w_xapu_command_counts: classes 0..15, larger classes, unreadable commands, unknown handles. +enum { class_other = 16, unreadable = 17, rejected = 18 }; + +struct ShapeContexts { + std::uint32_t counts[6]{}; + unsigned char* arrays[6]{}; + std::uint32_t apu[6]{}; +}; +static_assert(sizeof(ShapeContexts) == 0x60, "ShapeContexts layout"); + +struct Api { + CreateHeapFn create_heap; + AllocFn alloc; + FreeFn free; + HalCreateFn hal_create; + ShapeAllocFn shape_alloc; + ConnectFn connect; + EnqueueFn enqueue; + CountFn result_count; + DequeueFn dequeue; + DisconnectFn disconnect; + ActivityFn acphal_activity; + ActivityFn xapu_counts; +}; + +int failures; +std::string transcript; // every result, output and last error, compared between the on and off runs + +void check(bool condition, const char* what) +{ + if (condition) return; + std::printf("FAIL: %s\n", what); + ++failures; +} + +// Calls are made with a sentinel last error, so a stand-in that changes the caller's last error shows up. +void note(const char* what, long hr, unsigned long long value = 0) +{ + char line[160]; + std::snprintf(line, sizeof(line), "%s hr=0x%08lx value=0x%llx last_error=%lu\n", what, static_cast(hr), value, + GetLastError()); + transcript += line; +} +void sentinel() { SetLastError(0x5A5A); } + +// One aligned 8-byte store, so the sampler sees the context before or after it, never half written. +void store(unsigned char* base, std::uint32_t context, unsigned word, u64 value) +{ + InterlockedExchange64(reinterpret_cast(base + context * 64u + word * 8u), static_cast(value)); +} + +struct Snapshot { + BOOL on = FALSE; + ULONGLONG v[xapu_fields > acphal_fields ? xapu_fields : acphal_fields]; +}; + +Snapshot take(ActivityFn fn) +{ + Snapshot s; + for (auto& x : s.v) x = 0xA5A5A5A5A5A5A5A5ull; // the export must overwrite every field, on or off + s.on = fn(s.v); + return s; +} + +// Every field is zero except the listed ones. +void expect(const char* label, const Snapshot& s, BOOL on, int fields, std::initializer_list> nonzero) +{ + bool good = s.on == on; + for (int i = 0; i < fields; ++i) { + u64 want = 0; + for (const auto& f : nonzero) + if (f.first == i) want = f.second; + good = good && s.v[i] == want; + } + if (good) return; + std::printf("FAIL: %s: returned %d, fields", label, s.on); + for (int i = 0; i < fields; ++i) std::printf(" %llu", s.v[i]); + std::printf("\n"); + ++failures; +} + +std::string read_file(const char* path) +{ + std::string text; + HANDLE file = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr); + if (file == INVALID_HANDLE_VALUE) return text; + char buffer[4096]; + DWORD got = 0; + while (ReadFile(file, buffer, sizeof(buffer), &got, nullptr) && got) text.append(buffer, got); + CloseHandle(file); + return text; +} + +// Sums the name=value tokens of the activity lines in the log, keyed "xma." or "xapu."; zero sums are +// dropped. A bare number names a submit type (xma) or a command class (xapu). The live=n/m token is not a count. +std::map activity_sums(const std::string& log, int* lines) +{ + std::map sums; + *lines = 0; + std::size_t at = 0; + while (at < log.size()) { + std::size_t end = log.find('\n', at); + if (end == std::string::npos) end = log.size(); + const std::string line = log.substr(at, end - at); + at = end + 1; + const char* kind = line.find("x2w-audio xma-activity t=") != std::string::npos ? "xma." + : line.find("x2w-audio xapu-activity t=") != std::string::npos ? "xapu." + : nullptr; + if (!kind) continue; + ++*lines; + std::size_t pos = line.find(" s: "); + while (pos != std::string::npos && pos < line.size()) { + const std::size_t start = pos + 1; + pos = line.find(' ', start); + std::string token = line.substr(start, pos == std::string::npos ? std::string::npos : pos - start); + while (!token.empty() && (token.back() == ';' || token.back() == '\r')) token.pop_back(); + const std::size_t eq = token.find('='); + if (eq == std::string::npos || token.find('/') != std::string::npos) continue; + sums[kind + token.substr(0, eq)] += std::strtoull(token.c_str() + eq + 1, nullptr, 10); + } + } + for (auto it = sums.begin(); it != sums.end();) it = it->second ? std::next(it) : sums.erase(it); + return sums; +} + +std::string describe(const std::map& sums) +{ + std::string text; + for (const auto& s : sums) text += " " + s.first + "=" + std::to_string(s.second); + return text; +} + +int activity_lines(const char* log_path) +{ + int lines = 0; + activity_sums(read_file(log_path), &lines); + return lines; +} + +// The caller script of the on and off cases. Snapshots are taken between phases, so each context moves once +// between two samples whatever the sampler thread does in between. +void script(const Api& api, bool on) +{ + sentinel(); + note("ApuCreateHeap", api.create_heap(0x200000, 0)); + void* hal = nullptr; + sentinel(); + note("AcpHalCreate", api.hal_create(&hal), hal != nullptr); + if (!hal) return check(false, "AcpHalCreate returns an object"); + auto* const* table = *reinterpret_cast(hal); + auto hal_connect = reinterpret_cast(table[0]); + auto hal_submit = reinterpret_cast(table[2]); + sentinel(); + note("AcpHal connect", hal_connect(hal, 0x1000, 0x1000)); + ShapeContexts ctx{}; + ctx.counts[4] = contexts; + sentinel(); + note("AcpHalAllocateShapeContexts", api.shape_alloc(&ctx), ctx.apu[4]); + unsigned char* const base = ctx.arrays[4]; + if (!base) return check(false, "XMA contexts allocated"); + expect("before any write", take(api.acphal_activity), on, acphal_fields, {{watched, on ? contexts : 0}}); + + // Fill 5 contexts, one word each; context 349 uses its last word. + store(base, 0, 0, 0x1111); + store(base, 1, 3, 0x2222); + store(base, 2, 0, 0x3333); + store(base, 100, 5, 0x4444); + store(base, 349, 7, 0x5555); + expect("after 5 fills", take(api.acphal_activity), on, acphal_fields, + on ? std::initializer_list>{{watched, contexts}, {live, 5}, {filled, 5}} + : std::initializer_list>{}); + // Change 3 live contexts: the same word, the last word, another word. + store(base, 0, 0, 0x1112); + store(base, 1, 7, 0x2223); + store(base, 100, 2, 0x4445); + expect("after 3 changes", take(api.acphal_activity), on, acphal_fields, + on ? std::initializer_list>{{watched, contexts}, {live, 5}, {filled, 5}, {changed, 3}} + : std::initializer_list>{}); + // Clear 2 contexts. + store(base, 2, 0, 0); + store(base, 349, 7, 0); + expect("after 2 clears", take(api.acphal_activity), on, acphal_fields, + on ? std::initializer_list>{{watched, contexts}, {live, 3}, {filled, 5}, {changed, 3}, {cleared, 2}} + : std::initializer_list>{}); + + const unsigned input = 0x12345678u; + for (unsigned type : {1u, 1u, 3u, 12u}) { + sentinel(); + note("AcpHal submit", hal_submit(hal, type, 0x1234, 2, &input, 0), type); + } + const auto after_submits = take(api.acphal_activity); + expect("after 4 HAL submits", after_submits, on, acphal_fields, + on ? std::initializer_list>{{watched, contexts}, {live, 3}, {filled, 5}, {changed, 3}, {cleared, 2}, + {submits, 4}, {submit_type0 + 1, 2}, {submit_type0 + 3, 1}, {submit_other, 1}} + : std::initializer_list>{}); + + unsigned char connect_input[0x18]{}, connect_output[0x10]{}; + u64 handle = 0; + sentinel(); + note("XApuConnect", api.connect(connect_input, connect_output, &handle), handle); + unsigned char command[0x60]{}; + for (std::uint32_t command_class : {1u, 1u, 2u, 1u, 2u, 0x20u}) { + std::memcpy(command, &command_class, sizeof(command_class)); + sentinel(); + note("XApuEnqueueCommand", api.enqueue(handle, command, 0, 0), command_class); + } + sentinel(); + note("XApuEnqueueCommand null command", api.enqueue(handle, nullptr, 0, 0)); + std::uint32_t one = 1; + std::memcpy(command, &one, sizeof(one)); + sentinel(); + note("XApuEnqueueCommand unknown handle", api.enqueue(handle + 0x100, command, 0, 0)); + sentinel(); + const std::uint32_t pending = api.result_count(handle, 0); + note("XApuGetResultCount", 0, pending); + for (int i = 0; i < 8; ++i) { + unsigned char result[0x58]; + std::memset(result, 0xCC, sizeof(result)); + sentinel(); + const long hr = api.dequeue(handle, result); + unsigned sum = 0; + for (unsigned char b : result) sum += b; + note("XApuDequeueResult", hr, sum); + } + sentinel(); + note("XApuDisconnect", api.disconnect(handle)); + expect("XApu commands", take(api.xapu_counts), on, xapu_fields, + on ? std::initializer_list>{{1, 3}, {2, 2}, {class_other, 1}, {unreadable, 1}, {rejected, 1}} + : std::initializer_list>{}); + + unsigned hash = 2166136261u; // FNV-1a of the context bytes: the counter never writes caller memory + for (std::uint32_t i = 0; i < contexts * 64; ++i) hash = (hash ^ base[i]) * 16777619u; + sentinel(); + note("context bytes", 0, hash); + + // Freed contexts stop being watched; the block that comes back is not counted. + sentinel(); + note("ApuFree contexts", api.free(base)); + void* again = nullptr; + std::uint32_t again_apu = 0; + sentinel(); + note("ApuAlloc same size", api.alloc(&again, &again_apu, contexts * 64, 64, 0), again_apu); + sentinel(); + note("same block", 0, again == base); + if (again) { + auto* p = static_cast(again); + store(p, 0, 0, 0x6666); + store(p, 5, 1, 0x7777); + store(p, 300, 7, 0x8888); + Sleep(50); // several sampler periods + } + expect("after free and reuse", take(api.acphal_activity), on, acphal_fields, + on ? std::initializer_list>{{filled, 5}, {changed, 3}, {cleared, 2}, {submits, 4}, + {submit_type0 + 1, 2}, {submit_type0 + 3, 1}, {submit_other, 1}} + : std::initializer_list>{}); +} + +// Zero-write control: the counter is on, the caller writes only to the block after the contexts and sends nothing. +void script_none(const Api& api) +{ + api.create_heap(0x200000, 0); + void* hal = nullptr; + check(api.hal_create(&hal) == 0 && hal, "AcpHalCreate"); + ShapeContexts ctx{}; + ctx.counts[4] = contexts; + check(api.shape_alloc(&ctx) == 0 && ctx.arrays[4], "AcpHalAllocateShapeContexts"); + void* next = nullptr; + std::uint32_t next_apu = 0; + check(api.alloc(&next, &next_apu, 0x1000, 64, 0) == 0 && next, "ApuAlloc after the contexts"); + // The control writes the 64 bytes right after the last context, so it is only meaningful if they are adjacent. + check(next_apu == ctx.apu[4] + contexts * 64, "the next block starts right after the last context"); + if (next) { + store(static_cast(next), 0, 0, 0x9999); + store(static_cast(next), 0, 7, 0x9999); + } + unsigned char connect_input[0x18]{}, connect_output[0x10]{}; + u64 handle = 0; + check(api.connect(connect_input, connect_output, &handle) == 0, "XApuConnect"); + check(api.disconnect(handle) == 0, "XApuDisconnect"); + Sleep(50); + expect("zero-write control", take(api.acphal_activity), TRUE, acphal_fields, {{watched, contexts}}); + expect("zero-write control XApu", take(api.xapu_counts), TRUE, xapu_fields, {}); +} + +int run_case(const char* name, const char* acphal_path, const char* xapu_path, const char* transcript_path) +{ + HMODULE acphal = LoadLibraryA(acphal_path), xapu = LoadLibraryA(xapu_path); + if (!acphal || !xapu) return std::printf("FAIL: cannot load the stand-ins\n"), 2; + Api api{}; + api.create_heap = reinterpret_cast(GetProcAddress(acphal, "ApuCreateHeap")); + api.alloc = reinterpret_cast(GetProcAddress(acphal, "ApuAlloc")); + api.free = reinterpret_cast(GetProcAddress(acphal, "ApuFree")); + api.hal_create = reinterpret_cast(GetProcAddress(acphal, "AcpHalCreate")); + api.shape_alloc = reinterpret_cast(GetProcAddress(acphal, "AcpHalAllocateShapeContexts")); + api.acphal_activity = reinterpret_cast(GetProcAddress(acphal, "x2w_acphal_xma_activity")); + api.connect = reinterpret_cast(GetProcAddress(xapu, "XApuConnect")); + api.enqueue = reinterpret_cast(GetProcAddress(xapu, "XApuEnqueueCommand")); + api.result_count = reinterpret_cast(GetProcAddress(xapu, "XApuGetResultCount")); + api.dequeue = reinterpret_cast(GetProcAddress(xapu, "XApuDequeueResult")); + api.disconnect = reinterpret_cast(GetProcAddress(xapu, "XApuDisconnect")); + api.xapu_counts = reinterpret_cast(GetProcAddress(xapu, "x2w_xapu_command_counts")); + if (!api.create_heap || !api.alloc || !api.free || !api.hal_create || !api.shape_alloc || !api.acphal_activity || !api.connect || + !api.enqueue || !api.result_count || !api.dequeue || !api.disconnect || !api.xapu_counts) + return std::printf("FAIL: missing export\n"), 2; + char log_path[MAX_PATH] = ""; + GetEnvironmentVariableA("X2W_TRAP_LOG", log_path, MAX_PATH); + check(api.acphal_activity(nullptr) == FALSE && api.xapu_counts(nullptr) == FALSE, "the exports refuse a null output"); + + if (!std::strcmp(name, "none")) { + script_none(api); + Sleep(1500); // longer than the report interval: an unchanged count writes no line + check(activity_lines(log_path) == 0, "zero-write control logs no activity line"); + } else { + const bool on = !std::strcmp(name, "on"); + script(api, on); + if (on) { + const std::map want = { + {"xma.filled", 5}, {"xma.changed", 3}, {"xma.cleared", 2}, {"xma.submits", 4}, {"xma.1", 2}, + {"xma.3", 1}, {"xma.other", 1}, {"xapu.commands", 7}, {"xapu.1", 3}, {"xapu.2", 2}, + {"xapu.other", 1}, {"xapu.unreadable", 1}, {"xapu.rejected", 1}}; + std::map got; + int lines = 0; + for (int waited = 0; waited <= 5000; waited += 100) { // a line comes about a second after a change + got = activity_sums(read_file(log_path), &lines); + if (got == want) break; + Sleep(100); + } + if (got != want) { + std::printf("FAIL: logged activity lines (%d) sum to%s\n expected%s\n", lines, describe(got).c_str(), + describe(want).c_str()); + ++failures; + } + } else { + Sleep(1500); + check(activity_lines(log_path) == 0, "counter off logs no activity line"); + check(read_file(log_path).find("-activity") == std::string::npos, "counter off logs nothing about activity"); + } + HANDLE out = CreateFileA(transcript_path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr); + DWORD wrote = 0; + check(out != INVALID_HANDLE_VALUE && WriteFile(out, transcript.data(), static_cast(transcript.size()), &wrote, nullptr) && + wrote == transcript.size(), + "transcript written"); + if (out != INVALID_HANDLE_VALUE) CloseHandle(out); + } + std::printf(failures ? "case %s: %d failure(s)\n" : "case %s: ok\n", name, failures); + return failures ? 1 : 0; +} + +DWORD spawn(const char* self, const char* name, const char* acphal, const char* xapu, const std::string& dir) +{ + const std::string log = dir + "\\" + name + ".log", out = dir + "\\" + name + ".txt"; + SetEnvironmentVariableA("X2W_AUDIO_PERMISSIVE", "1"); + SetEnvironmentVariableA("X2W_AUDIO_ACTIVITY", std::strcmp(name, "off") ? "1" : nullptr); + SetEnvironmentVariableA("X2W_TRAP_LOG", log.c_str()); + std::string cmd = std::string("\"") + self + "\" --case " + name + " \"" + acphal + "\" \"" + xapu + "\" \"" + out + "\""; + // The child writes to this process's stdout and stderr, so its lines reach the CTest log. + STARTUPINFOA si{}; + si.cb = sizeof(si); + si.dwFlags = STARTF_USESTDHANDLES; + si.hStdInput = GetStdHandle(STD_INPUT_HANDLE); + si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); + si.hStdError = GetStdHandle(STD_ERROR_HANDLE); + for (HANDLE h : {si.hStdOutput, si.hStdError}) SetHandleInformation(h, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); + std::fflush(stdout); + PROCESS_INFORMATION pi{}; + if (!CreateProcessA(nullptr, cmd.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &si, &pi)) return 0xFFFFFFFFu; + DWORD code = 0xFFFFFFFEu; + if (WaitForSingleObject(pi.hProcess, 30000) == WAIT_OBJECT_0) GetExitCodeProcess(pi.hProcess, &code); + else TerminateProcess(pi.hProcess, 0xFFFFFFFDu); // our own child, by handle + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + return code; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc == 6 && !std::strcmp(argv[1], "--case")) return run_case(argv[2], argv[3], argv[4], argv[5]); + if (argc != 3) return std::printf("usage: startup_acphal_xma_activity \n"), 2; + char temp[MAX_PATH]; + if (!GetTempPathA(MAX_PATH, temp)) return std::printf("FAIL: no temp folder\n"), 2; + const std::string dir = std::string(temp) + "x2w_xma_activity_" + std::to_string(GetCurrentProcessId()); + if (!CreateDirectoryA(dir.c_str(), nullptr)) return std::printf("FAIL: cannot create %s\n", dir.c_str()), 2; + char self[MAX_PATH]; + GetModuleFileNameA(nullptr, self, MAX_PATH); + for (const char* name : {"on", "none", "off"}) { + const DWORD code = spawn(self, name, argv[1], argv[2], dir); + if (code) { + std::printf("FAIL: case %s exited 0x%08lx\n", name, static_cast(code)); + ++failures; + } + } + const std::string on = read_file((dir + "\\on.txt").c_str()), off = read_file((dir + "\\off.txt").c_str()); + check(!on.empty(), "the on case wrote a transcript"); + if (on != off) { + std::size_t at = 0; + while (at < on.size() && at < off.size() && on[at] == off[at]) ++at; + const std::size_t line = on.rfind('\n', at) == std::string::npos ? 0 : on.rfind('\n', at) + 1; + std::printf("FAIL: results differ with the counter on and off, first at: on '%s' off '%s'\n", + on.substr(line, on.find('\n', line) - line).c_str(), off.substr(line, off.find('\n', line) - line).c_str()); + ++failures; + } + for (const char* file : {"on.log", "none.log", "off.log", "on.txt", "off.txt"}) DeleteFileA((dir + "\\" + file).c_str()); + RemoveDirectoryA(dir.c_str()); + std::printf(failures ? "startup_acphal_xma_activity: %d failure(s)\n" : "startup_acphal_xma_activity: ok\n", failures); + return failures ? 1 : 0; +} From dd331fa892e082d1bede2d9597d25cda8e27b958 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:02:31 +1000 Subject: [PATCH 04/10] gh #1145 atom 3: document the audio activity counter Adds the X2W_AUDIO_ACTIVITY switch, an Activity counter section under the APU heap stand-in with the line formats and limits, and an experiments entry with the reproduction command for startup_acphal_xma_activity. --- docs/experiments.md | 13 +++++++++++++ docs/startup-runtime.md | 38 +++++++++++++++++++++++++++++++++++++- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/docs/experiments.md b/docs/experiments.md index 2913bd0852..aa01a42f31 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -10335,6 +10335,19 @@ ctest --preset release --no-tests=error -R '^cpu_native_acphal_hal$' -V The desktop `AcpHal.dll` stand-in (not the fixture provider above) now returns `ApuAlloc` blocks on `ApuFree` through a first-fit free list with coalescing, so repeated allocate and free cycles no longer exhaust the heap. It is a stand-in contract only: the console's error codes, alignment limits and zero-size behaviour are not public, and the codes chosen are listed in [startup-runtime.md](startup-runtime.md#apu-heap-stand-in). The source-built check is `ctest --preset dev --no-tests=error -R '^startup_acphal_apu_free$' -V`. +### XMA context activity in the AcpHal stand-in + +With `X2W_AUDIO_PERMISSIVE=1` and `X2W_AUDIO_ACTIVITY=1`, the desktop `AcpHal.dll` and `xapu.dll` stand-ins count what a caller does with the audio processor. This is a first measurement for [issue #1145](https://github.com/R0Y00/Xbox2Windows/issues/1145), before any decoding. AcpHal compares the XMA context array it allocated with a copy about every 10 ms and counts contexts filled (all zero to nonzero), changed and cleared, plus HAL slot2 submits by type. xapu counts `XApuEnqueueCommand` calls by command class with no cap. Each DLL logs a line per second when a count moved; the experimental exports `x2w_acphal_xma_activity` and `x2w_xapu_command_counts` return the totals. Line formats and limits are in [startup-runtime.md](startup-runtime.md#activity-counter). + +`startup_acphal_xma_activity` runs one source-built caller script in three child processes. With the counter on, the caller fills 5 contexts, changes 3 and clears 2, submits 4 HAL commands of types 1, 1, 3 and 12, and enqueues 6 XApu commands of classes 1, 2 and 0x20, one null command and one command on an unknown handle. The exports and the summed log lines must give exactly those counts, and an array freed and allocated again must not be counted. The zero-write control writes only the 64 bytes after the last context and sends nothing: every count must be 0 and no line may be logged. With the counter off, the exports report nothing and no line is logged. Every result, output, last error and the final context bytes must match between the on and off runs. + +```powershell +cmake --build --preset release --target startup_acphal_xma_activity +ctest --preset release --no-tests=error -R '^startup_acphal_xma_activity$' -V +``` + +The 64-byte context stride and the command class (the first `UINT32` of a command) are stand-in conventions, not console contracts. The counter identifies no field inside a context, such as an enable flag, decodes nothing, and does not establish which counted event starts playback. + ### XApu command-queue caller and recorder A source-built caller ([`xapu_queue_caller.asm`](../tests/cpu/xapu_queue_caller.asm)) imports the five `xapu.dll` command-queue functions by name (`XApuConnect`, `XApuEnqueueCommand`, `XApuGetResultCount`, `XApuDequeueResult`, `XApuDisconnect`), plus `finish_exe` from `cpu_exe_io.dll`, and starts through [`exe_startup.asm`](../tests/cpu/exe_startup.asm). A test-only recording provider ([`xapu_queue_provider.cpp`](../tests/cpu/xapu_queue_provider.cpp)) serves the five names. This is not a production `xapu.dll`, and this change adds no binding. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 043429b30c..f3ba2db407 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1272,6 +1272,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_HIDE_TITLE_WINDOW=1` (`run.sh --hide-title-window`) | once a present has reached the output window, hides the title's own window; dialogs stay visible, and the window is shown again when a present misses the output window, until the next present reaches it ([Output window and fallback diagnostics](#output-window-and-fallback-diagnostics)). Keyboard input to the title after the hide is not measured. Off by default on every host | | `X2W_DRAW_DUMP_FRAME=`, `X2W_DRAW_DUMP_DIR` | Full-resolution RGB snapshots of single-sample RGBA8/BGRA8 UNORM or sRGB targets after translated draws. A later present writes completed queue-fenced copies. At most 48 copies are pending or written; a copy whose fence reports device removal (`UINT64_MAX`) is released unwritten and frees its slot (`src/startup_stubs/draw_dump_tracking.h`, `ctest --preset dev --no-tests=error -R '^startup_dump_fence_(removed_control_)?warp$' -V`; the control must fail). | | `X2W_AUDIO_PERMISSIVE=1` | enables the audio stand-ins. Without a DSP provider, `XDspActivate` clears valid outputs and reports unavailable resources, and failed `XDspSubmitCommand` calls leave the sequence unchanged. `XDspDeactivate` and `XDspDisconnect` refuse null and unknown handles with `E_INVALIDARG`. | +| `X2W_AUDIO_ACTIVITY=1` | with `X2W_AUDIO_PERMISSIVE=1`, counts XMA context changes, HAL submits and XApu commands, and logs a line per second when a count moved ([Activity counter](#activity-counter)) | | `X2W_RUNTIME_PROXY=1` | proxies the gaming runtime and logs every call. Rewrites regular-IAT `GetProcAddress` and a direct `xgameruntime.dll!QueryApiImpl` import on the main EXE and on DLLs that share its directory (package helpers). Dynamic `QueryApiImpl` / `InitializeApiImpl*` are wrapped only when the provider module's basename is `xgameruntime.dll`. `LdrRegisterDllNotification` only flags that another scan is needed. A worker holds each matching module live while rewriting after linking. Loading a helper and immediately calling it can precede the scan. The enabled proxy stays loaded until process exit. Delay-import IAT slots are not rewritten. Skips this stand-in's own `GetProcAddress` IAT so the hook does not recurse (`src/startup_stubs/runtime_gpa_patch.h`, `ctest --preset dev --no-tests=error -R '^startup_runtime_gpa_patch(_name_only_control)?$'`, and the control must print `FAIL:`; Windows also runs `startup_runtime_proxy_scope` for a late-loaded helper through the real loader) | | `X2W_FAKE_USER=1` | answers the user, gamertag and save APIs for one local user, and creates one offline store context for that user | | `X2W_RUNTIME_LOCAL=1` | with `X2W_RUNTIME_PROXY` and `X2W_FAKE_USER`, for a host where the system gaming runtime cannot initialize (no Gaming Services). The first failed `InitializeApiImpl*` is reported as `S_OK`, and every later initialization call returns `S_OK` without calling the real export. Once initialization failure is latched, a failed real `QueryApiImpl` call can fall back only with an exact match of both GUIDs to a supported provider/interface pair for user (including gamertag), game save, package, title, connectivity or store. Persistent local storage uses its existing fake-user gate and requires its exact provider GUID and IID. Unmatched failed queries keep the real HRESULT. The proxy clears a writable output on failure only when fake user is enabled and the initialization failure is latched. A local object's `QueryInterface` accepts only `IID_IUnknown` and the IID it was created for. The local answers above apply, calls that carry the local user or store handle fail as before, and other unanswered methods return `E_NOTIMPL`. `XUserAddAsync` and async operations completed on behalf of a local answer require the real runtime's `QueryApiImpl` to return the XAsync provider (`073b7dcb`). Those operations complete with `S_OK` through XAsync, or return the query failure if XAsync is unavailable (`ctest --preset dev --no-tests=error -R '^startup_runtime_local(_control)?$'`, and the control must print `FAIL:`). | @@ -2226,7 +2227,8 @@ observed callers. The experimental mode echoes any 32-bit type value at `+0x00` (including unobserved types such as `4`) rather than rejecting it, while keeping payload bytes outside `+0x00` and `+0x04` zero (`+0x34` carries decoded bytes only in the optional Opus build below). Handles are never reused, and each connection's queue buffer is released on `XApuDisconnect`. Default non-permissive mode still traps on every export -(`ctest --preset dev --no-tests=error -R '^startup_xapu_queue$' -V`). +(`ctest --preset dev --no-tests=error -R '^startup_xapu_queue$' -V`). With `X2W_AUDIO_ACTIVITY=1` it also counts +commands by class (see [Activity counter](#activity-counter)). The default build does not depend on libopus. Configuring with `-DX2W_WITH_OPUS=ON` (and `Opus_DIR` pointing at an installed libopus CMake package) links libopus into `xapu.dll`. The stand-ins link the static MSVC runtime, so libopus @@ -2315,6 +2317,40 @@ address validity/mapping exports, then runs 4 threads of 1000 rounds against an ctest --preset dev --no-tests=error -R '^startup_acphal_apu_free$' -V ``` +### Activity counter + +With `X2W_AUDIO_ACTIVITY=1` as well, the stand-ins count what a caller does with the audio processor without +decoding anything. `AcpHal.dll` keeps a copy of the XMA context array that `AcpHalAllocateShapeContexts` hands out and +compares the array with it about every 10 ms. Each 64-byte context is taken as a whole and no field in it is read: one +that goes from all zero to nonzero counts as filled, one that changes while nonzero as changed, one that returns to all +zero as cleared. HAL slot2 submits are counted by their type argument. `xapu.dll` counts every `XApuEnqueueCommand` +call by command class, taken as the first `UINT32` of the command, with no cap; unreadable commands and unknown handles +are counted apart. Not counted: in an `X2W_WITH_OPUS` build with `X2W_XAPU_TYPED_COMPLETIONS=1`, a type 3 +command too short to decode, which returns `E_POINTER` before the count. +Once a second, each DLL logs one line with the counts since its previous line, only when a count +moved. With the fixture's caller, for example: + +``` +x2w-audio xma-activity t=1.0 s: contexts filled=5 changed=3 cleared=2 live=3/350; hal submits=4 by type 1=2 3=1 other=1 +x2w-audio xapu-activity t=1.0 s: commands=7 by class 1=3 2=2 other=1 unreadable=1; rejected=1 +``` + +`t` is seconds since the process started, the same base in both DLLs. A context written across a sample counts twice, +and one filled and cleared between two samples is not counted. `ApuFree` of the array ends the count before the block +can be reused. The totals are also returned by the experimental exports `x2w_acphal_xma_activity` and +`x2w_xapu_command_counts`. The 64-byte stride and the command class are stand-in conventions, not a console layout, and +no field inside a context, such as an enable flag, is identified. With the variable unset nothing runs: no thread, no +read of caller memory, no line. + +The source-built check runs one caller script in three child processes: counter on (the exports and the logged lines +give exactly what the script did, and an array freed and allocated again is no longer counted), counter on with a caller +that writes only the 64 bytes after the last context and sends nothing (every count 0, no line), and counter off (no +count, no line). Every result, output, last error and the final context bytes must match between the on and off runs: + +``` +ctest --preset release --no-tests=error -R '^startup_acphal_xma_activity$' -V +``` + ## Uniform first-lane reads The startup shader translator accepts `v_readfirstlane_b32` in straight-line code with the From ace22feda9ccc70940d4262433426d22e0316e6d Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:27:41 +1000 Subject: [PATCH 05/10] gh #1145 review round 1: assert block reuse, share expectations, fit CTest timeout The on and off cases now check that ApuAlloc of the same size returns the freed context block, so the not-counted-after-reuse check cannot pass on some other block. expect_on() replaces the repeated on/off expectation lists without changing them. Each case waits 15 s, so all three fit in the 60 s CTest timeout. --- tests/startup_acphal_xma_activity.cpp | 50 +++++++++++++++------------ 1 file changed, 27 insertions(+), 23 deletions(-) diff --git a/tests/startup_acphal_xma_activity.cpp b/tests/startup_acphal_xma_activity.cpp index 6b4bc7177c..7f24fbfa6c 100644 --- a/tests/startup_acphal_xma_activity.cpp +++ b/tests/startup_acphal_xma_activity.cpp @@ -111,8 +111,10 @@ Snapshot take(ActivityFn fn) return s; } +using Fields = std::initializer_list>; // (field, value) pairs + // Every field is zero except the listed ones. -void expect(const char* label, const Snapshot& s, BOOL on, int fields, std::initializer_list> nonzero) +void expect(const char* label, const Snapshot& s, BOOL on, int fields, Fields nonzero) { bool good = s.on == on; for (int i = 0; i < fields; ++i) { @@ -128,6 +130,12 @@ void expect(const char* label, const Snapshot& s, BOOL on, int fields, std::init ++failures; } +// The fields expected with the counter on; with it off the export returns FALSE and every field must be zero. +void expect_on(const char* label, const Snapshot& s, bool on, int fields, Fields when_on) +{ + expect(label, s, on, fields, on ? when_on : Fields{}); +} + std::string read_file(const char* path) { std::string text; @@ -207,7 +215,7 @@ void script(const Api& api, bool on) note("AcpHalAllocateShapeContexts", api.shape_alloc(&ctx), ctx.apu[4]); unsigned char* const base = ctx.arrays[4]; if (!base) return check(false, "XMA contexts allocated"); - expect("before any write", take(api.acphal_activity), on, acphal_fields, {{watched, on ? contexts : 0}}); + expect_on("before any write", take(api.acphal_activity), on, acphal_fields, {{watched, contexts}}); // Fill 5 contexts, one word each; context 349 uses its last word. store(base, 0, 0, 0x1111); @@ -215,22 +223,19 @@ void script(const Api& api, bool on) store(base, 2, 0, 0x3333); store(base, 100, 5, 0x4444); store(base, 349, 7, 0x5555); - expect("after 5 fills", take(api.acphal_activity), on, acphal_fields, - on ? std::initializer_list>{{watched, contexts}, {live, 5}, {filled, 5}} - : std::initializer_list>{}); + expect_on("after 5 fills", take(api.acphal_activity), on, acphal_fields, + {{watched, contexts}, {live, 5}, {filled, 5}}); // Change 3 live contexts: the same word, the last word, another word. store(base, 0, 0, 0x1112); store(base, 1, 7, 0x2223); store(base, 100, 2, 0x4445); - expect("after 3 changes", take(api.acphal_activity), on, acphal_fields, - on ? std::initializer_list>{{watched, contexts}, {live, 5}, {filled, 5}, {changed, 3}} - : std::initializer_list>{}); + expect_on("after 3 changes", take(api.acphal_activity), on, acphal_fields, + {{watched, contexts}, {live, 5}, {filled, 5}, {changed, 3}}); // Clear 2 contexts. store(base, 2, 0, 0); store(base, 349, 7, 0); - expect("after 2 clears", take(api.acphal_activity), on, acphal_fields, - on ? std::initializer_list>{{watched, contexts}, {live, 3}, {filled, 5}, {changed, 3}, {cleared, 2}} - : std::initializer_list>{}); + expect_on("after 2 clears", take(api.acphal_activity), on, acphal_fields, + {{watched, contexts}, {live, 3}, {filled, 5}, {changed, 3}, {cleared, 2}}); const unsigned input = 0x12345678u; for (unsigned type : {1u, 1u, 3u, 12u}) { @@ -238,10 +243,9 @@ void script(const Api& api, bool on) note("AcpHal submit", hal_submit(hal, type, 0x1234, 2, &input, 0), type); } const auto after_submits = take(api.acphal_activity); - expect("after 4 HAL submits", after_submits, on, acphal_fields, - on ? std::initializer_list>{{watched, contexts}, {live, 3}, {filled, 5}, {changed, 3}, {cleared, 2}, - {submits, 4}, {submit_type0 + 1, 2}, {submit_type0 + 3, 1}, {submit_other, 1}} - : std::initializer_list>{}); + expect_on("after 4 HAL submits", after_submits, on, acphal_fields, + {{watched, contexts}, {live, 3}, {filled, 5}, {changed, 3}, {cleared, 2}, {submits, 4}, {submit_type0 + 1, 2}, + {submit_type0 + 3, 1}, {submit_other, 1}}); unsigned char connect_input[0x18]{}, connect_output[0x10]{}; u64 handle = 0; @@ -273,9 +277,8 @@ void script(const Api& api, bool on) } sentinel(); note("XApuDisconnect", api.disconnect(handle)); - expect("XApu commands", take(api.xapu_counts), on, xapu_fields, - on ? std::initializer_list>{{1, 3}, {2, 2}, {class_other, 1}, {unreadable, 1}, {rejected, 1}} - : std::initializer_list>{}); + expect_on("XApu commands", take(api.xapu_counts), on, xapu_fields, + {{1, 3}, {2, 2}, {class_other, 1}, {unreadable, 1}, {rejected, 1}}); unsigned hash = 2166136261u; // FNV-1a of the context bytes: the counter never writes caller memory for (std::uint32_t i = 0; i < contexts * 64; ++i) hash = (hash ^ base[i]) * 16777619u; @@ -291,6 +294,7 @@ void script(const Api& api, bool on) note("ApuAlloc same size", api.alloc(&again, &again_apu, contexts * 64, 64, 0), again_apu); sentinel(); note("same block", 0, again == base); + check(again == base, "ApuAlloc of the same size returns the freed context block"); if (again) { auto* p = static_cast(again); store(p, 0, 0, 0x6666); @@ -298,10 +302,9 @@ void script(const Api& api, bool on) store(p, 300, 7, 0x8888); Sleep(50); // several sampler periods } - expect("after free and reuse", take(api.acphal_activity), on, acphal_fields, - on ? std::initializer_list>{{filled, 5}, {changed, 3}, {cleared, 2}, {submits, 4}, - {submit_type0 + 1, 2}, {submit_type0 + 3, 1}, {submit_other, 1}} - : std::initializer_list>{}); + expect_on("after free and reuse", take(api.acphal_activity), on, acphal_fields, + {{filled, 5}, {changed, 3}, {cleared, 2}, {submits, 4}, {submit_type0 + 1, 2}, {submit_type0 + 3, 1}, + {submit_other, 1}}); } // Zero-write control: the counter is on, the caller writes only to the block after the contexts and sends nothing. @@ -414,7 +417,8 @@ DWORD spawn(const char* self, const char* name, const char* acphal, const char* PROCESS_INFORMATION pi{}; if (!CreateProcessA(nullptr, cmd.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &si, &pi)) return 0xFFFFFFFFu; DWORD code = 0xFFFFFFFEu; - if (WaitForSingleObject(pi.hProcess, 30000) == WAIT_OBJECT_0) GetExitCodeProcess(pi.hProcess, &code); + // 15 s per case keeps all three inside the CTest TIMEOUT of 60 s, so a hung case is named, not killed with the parent. + if (WaitForSingleObject(pi.hProcess, 15000) == WAIT_OBJECT_0) GetExitCodeProcess(pi.hProcess, &code); else TerminateProcess(pi.hProcess, 0xFFFFFFFDu); // our own child, by handle CloseHandle(pi.hThread); CloseHandle(pi.hProcess); From 691a15e019e3b1849e3b6c02ab9b8d625b9804b4 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:37:15 +1000 Subject: [PATCH 06/10] gh #1145 review round 2107-1: observe activity inside calls, no sampler threads; add unload case --- CMakeLists.txt | 5 +- docs/experiments.md | 4 +- docs/startup-runtime.md | 52 ++++++++------ src/startup_stubs/acphal.cpp | 100 ++++++++++++++------------ src/startup_stubs/xapu.cpp | 83 +++++++++++---------- tests/startup_acphal_xma_activity.cpp | 74 ++++++++++++++++--- 6 files changed, 199 insertions(+), 119 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index d3332a558d..9cb978aaa0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -923,8 +923,9 @@ target_compile_features(startup_chad_check PRIVATE cxx_std_17) add_dependencies(startup_chad_check startup_stub_chad) add_test(NAME startup_chad_check COMMAND startup_chad_check "$") set_tests_properties(startup_chad_check PROPERTIES TIMEOUT 60) -# Activity counter of the AcpHal and XApu stand-ins (X2W_AUDIO_ACTIVITY=1): exact counts, a zero-write control, and -# the same results with the counter on and off (docs/startup-runtime.md). +# Activity counter of the AcpHal and XApu stand-ins (X2W_AUDIO_ACTIVITY=1): exact counts, a zero-write control, the +# same results with the counter on and off, and a caller that unloads both DLLs and must exit cleanly +# (docs/startup-runtime.md). add_executable(startup_acphal_xma_activity tests/startup_acphal_xma_activity.cpp) target_compile_features(startup_acphal_xma_activity PRIVATE cxx_std_17) add_dependencies(startup_acphal_xma_activity startup_stub_acphal startup_stub_xapu) diff --git a/docs/experiments.md b/docs/experiments.md index aa01a42f31..3c9254238c 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -10337,9 +10337,9 @@ The desktop `AcpHal.dll` stand-in (not the fixture provider above) now returns ` ### XMA context activity in the AcpHal stand-in -With `X2W_AUDIO_PERMISSIVE=1` and `X2W_AUDIO_ACTIVITY=1`, the desktop `AcpHal.dll` and `xapu.dll` stand-ins count what a caller does with the audio processor. This is a first measurement for [issue #1145](https://github.com/R0Y00/Xbox2Windows/issues/1145), before any decoding. AcpHal compares the XMA context array it allocated with a copy about every 10 ms and counts contexts filled (all zero to nonzero), changed and cleared, plus HAL slot2 submits by type. xapu counts `XApuEnqueueCommand` calls by command class with no cap. Each DLL logs a line per second when a count moved; the experimental exports `x2w_acphal_xma_activity` and `x2w_xapu_command_counts` return the totals. Line formats and limits are in [startup-runtime.md](startup-runtime.md#activity-counter). +With `X2W_AUDIO_PERMISSIVE=1` and `X2W_AUDIO_ACTIVITY=1`, the desktop `AcpHal.dll` and `xapu.dll` stand-ins count what a caller does with the audio processor. This is a first measurement for [issue #1145](https://github.com/R0Y00/Xbox2Windows/issues/1145), before any decoding. AcpHal compares the XMA context array it allocated with a copy inside the calls that count, at most once per 10 ms, and counts contexts filled (all zero to nonzero), changed and cleared, plus HAL slot2 submits by type. xapu counts `XApuEnqueueCommand` calls by command class with no cap. Neither DLL starts a thread; each logs at most a line per second, from a counted call, when a count moved; the experimental exports `x2w_acphal_xma_activity` and `x2w_xapu_command_counts` return the totals. Line formats and limits are in [startup-runtime.md](startup-runtime.md#activity-counter). -`startup_acphal_xma_activity` runs one source-built caller script in three child processes. With the counter on, the caller fills 5 contexts, changes 3 and clears 2, submits 4 HAL commands of types 1, 1, 3 and 12, and enqueues 6 XApu commands of classes 1, 2 and 0x20, one null command and one command on an unknown handle. The exports and the summed log lines must give exactly those counts, and an array freed and allocated again must not be counted. The zero-write control writes only the 64 bytes after the last context and sends nothing: every count must be 0 and no line may be logged. With the counter off, the exports report nothing and no line is logged. Every result, output, last error and the final context bytes must match between the on and off runs. +`startup_acphal_xma_activity` runs one source-built caller script in three child processes, plus an unload case. With the counter on, the caller fills 5 contexts, changes 3 and clears 2, submits 4 HAL commands of types 1, 1, 3 and 12, and enqueues 6 XApu commands of classes 1, 2 and 0x20, one null command and one command on an unknown handle. The exports and the summed log lines must give exactly those counts, and an array freed and allocated again must not be counted. The zero-write control writes only the 64 bytes after the last context and sends nothing: every count must be 0 and no line may be logged. With the counter off, the exports report nothing and no line is logged. Every result, output, last error and the final context bytes must match between the on and off runs. The unload case allocates the contexts a second time without `ApuFree`, then frees both DLLs, checks that they are unmapped, waits 1.5 s and must exit 0. ```powershell cmake --build --preset release --target startup_acphal_xma_activity diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index f3ba2db407..a301c64834 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1272,7 +1272,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_HIDE_TITLE_WINDOW=1` (`run.sh --hide-title-window`) | once a present has reached the output window, hides the title's own window; dialogs stay visible, and the window is shown again when a present misses the output window, until the next present reaches it ([Output window and fallback diagnostics](#output-window-and-fallback-diagnostics)). Keyboard input to the title after the hide is not measured. Off by default on every host | | `X2W_DRAW_DUMP_FRAME=`, `X2W_DRAW_DUMP_DIR` | Full-resolution RGB snapshots of single-sample RGBA8/BGRA8 UNORM or sRGB targets after translated draws. A later present writes completed queue-fenced copies. At most 48 copies are pending or written; a copy whose fence reports device removal (`UINT64_MAX`) is released unwritten and frees its slot (`src/startup_stubs/draw_dump_tracking.h`, `ctest --preset dev --no-tests=error -R '^startup_dump_fence_(removed_control_)?warp$' -V`; the control must fail). | | `X2W_AUDIO_PERMISSIVE=1` | enables the audio stand-ins. Without a DSP provider, `XDspActivate` clears valid outputs and reports unavailable resources, and failed `XDspSubmitCommand` calls leave the sequence unchanged. `XDspDeactivate` and `XDspDisconnect` refuse null and unknown handles with `E_INVALIDARG`. | -| `X2W_AUDIO_ACTIVITY=1` | with `X2W_AUDIO_PERMISSIVE=1`, counts XMA context changes, HAL submits and XApu commands, and logs a line per second when a count moved ([Activity counter](#activity-counter)) | +| `X2W_AUDIO_ACTIVITY=1` | with `X2W_AUDIO_PERMISSIVE=1`, counts XMA context changes, HAL submits and XApu commands, and logs at most a line per second when a count moved ([Activity counter](#activity-counter)) | | `X2W_RUNTIME_PROXY=1` | proxies the gaming runtime and logs every call. Rewrites regular-IAT `GetProcAddress` and a direct `xgameruntime.dll!QueryApiImpl` import on the main EXE and on DLLs that share its directory (package helpers). Dynamic `QueryApiImpl` / `InitializeApiImpl*` are wrapped only when the provider module's basename is `xgameruntime.dll`. `LdrRegisterDllNotification` only flags that another scan is needed. A worker holds each matching module live while rewriting after linking. Loading a helper and immediately calling it can precede the scan. The enabled proxy stays loaded until process exit. Delay-import IAT slots are not rewritten. Skips this stand-in's own `GetProcAddress` IAT so the hook does not recurse (`src/startup_stubs/runtime_gpa_patch.h`, `ctest --preset dev --no-tests=error -R '^startup_runtime_gpa_patch(_name_only_control)?$'`, and the control must print `FAIL:`; Windows also runs `startup_runtime_proxy_scope` for a late-loaded helper through the real loader) | | `X2W_FAKE_USER=1` | answers the user, gamertag and save APIs for one local user, and creates one offline store context for that user | | `X2W_RUNTIME_LOCAL=1` | with `X2W_RUNTIME_PROXY` and `X2W_FAKE_USER`, for a host where the system gaming runtime cannot initialize (no Gaming Services). The first failed `InitializeApiImpl*` is reported as `S_OK`, and every later initialization call returns `S_OK` without calling the real export. Once initialization failure is latched, a failed real `QueryApiImpl` call can fall back only with an exact match of both GUIDs to a supported provider/interface pair for user (including gamertag), game save, package, title, connectivity or store. Persistent local storage uses its existing fake-user gate and requires its exact provider GUID and IID. Unmatched failed queries keep the real HRESULT. The proxy clears a writable output on failure only when fake user is enabled and the initialization failure is latched. A local object's `QueryInterface` accepts only `IID_IUnknown` and the IID it was created for. The local answers above apply, calls that carry the local user or store handle fail as before, and other unanswered methods return `E_NOTIMPL`. `XUserAddAsync` and async operations completed on behalf of a local answer require the real runtime's `QueryApiImpl` to return the XAsync provider (`073b7dcb`). Those operations complete with `S_OK` through XAsync, or return the query failure if XAsync is unavailable (`ctest --preset dev --no-tests=error -R '^startup_runtime_local(_control)?$'`, and the control must print `FAIL:`). | @@ -2319,33 +2319,39 @@ ctest --preset dev --no-tests=error -R '^startup_acphal_apu_free$' -V ### Activity counter -With `X2W_AUDIO_ACTIVITY=1` as well, the stand-ins count what a caller does with the audio processor without -decoding anything. `AcpHal.dll` keeps a copy of the XMA context array that `AcpHalAllocateShapeContexts` hands out and -compares the array with it about every 10 ms. Each 64-byte context is taken as a whole and no field in it is read: one -that goes from all zero to nonzero counts as filled, one that changes while nonzero as changed, one that returns to all -zero as cleared. HAL slot2 submits are counted by their type argument. `xapu.dll` counts every `XApuEnqueueCommand` -call by command class, taken as the first `UINT32` of the command, with no cap; unreadable commands and unknown handles -are counted apart. Not counted: in an `X2W_WITH_OPUS` build with `X2W_XAPU_TYPED_COMPLETIONS=1`, a type 3 +With `X2W_AUDIO_ACTIVITY=1` as well, the stand-ins count what a caller does with the audio processor without decoding +anything. `AcpHal.dll` keeps a copy of the XMA context array that `AcpHalAllocateShapeContexts` hands out and compares +the array with it inside the calls that count (HAL submits, `AcpHalAllocateShapeContexts`, `ApuFree` of the array and +`x2w_acphal_xma_activity`), at most once per 10 ms. Each 64-byte context is taken as a whole and no field in it is read: one that +goes from all zero to nonzero counts as filled, one that changes while nonzero as changed, one that returns to all zero +as cleared. HAL slot2 submits are counted by their type argument. `xapu.dll` counts every `XApuEnqueueCommand` call by +command class, taken as the first `UINT32` of the command, with no cap; unreadable commands and unknown handles are +counted apart; `commands=` is the classes plus the unreadable commands, and `rejected=` calls are not in it. Not counted: in an `X2W_WITH_OPUS` build with `X2W_XAPU_TYPED_COMPLETIONS=1`, a type 3 command too short to decode, which returns `E_POINTER` before the count. -Once a second, each DLL logs one line with the counts since its previous line, only when a count -moved. With the fixture's caller, for example: +Neither DLL +starts a thread: the first counted call at least a second after a DLL's previous line logs one line with the counts +since then, only when a count moved, so nothing of either DLL runs after a caller unloads it. Changes made after the +last counted call are not logged. With the fixture's caller, for example: ``` -x2w-audio xma-activity t=1.0 s: contexts filled=5 changed=3 cleared=2 live=3/350; hal submits=4 by type 1=2 3=1 other=1 -x2w-audio xapu-activity t=1.0 s: commands=7 by class 1=3 2=2 other=1 unreadable=1; rejected=1 +x2w-audio xma-activity t=1.1 s: contexts filled=5 changed=3 cleared=2 live=0/0; hal submits=4 by type 1=2 3=1 other=1 +x2w-audio xapu-activity t=1.1 s: commands=7 by class 1=3 2=2 other=1 unreadable=1; rejected=1 (not in commands) ``` -`t` is seconds since the process started, the same base in both DLLs. A context written across a sample counts twice, -and one filled and cleared between two samples is not counted. `ApuFree` of the array ends the count before the block -can be reused. The totals are also returned by the experimental exports `x2w_acphal_xma_activity` and -`x2w_xapu_command_counts`. The 64-byte stride and the command class are stand-in conventions, not a console layout, and -no field inside a context, such as an enable flag, is identified. With the variable unset nothing runs: no thread, no -read of caller memory, no line. - -The source-built check runs one caller script in three child processes: counter on (the exports and the logged lines -give exactly what the script did, and an array freed and allocated again is no longer counted), counter on with a caller -that writes only the 64 bytes after the last context and sends nothing (every count 0, no line), and counter off (no -count, no line). Every result, output, last error and the final context bytes must match between the on and off runs: +`t` is seconds since the process started, the same base in both DLLs; the fixture's line comes after its `ApuFree`, so +no context is watched (`live=0/0`). A context written across a sample counts twice, and one filled and cleared between +two samples is not counted. `ApuFree` of the array ends the count before the block can be reused, and a second +`AcpHalAllocateShapeContexts` samples the old array once more and then watches only the new one. The totals are also +returned by the experimental exports `x2w_acphal_xma_activity` and `x2w_xapu_command_counts`. The 64-byte stride and the +command class are stand-in conventions, not a console layout, and no field inside a context, such as an enable flag, is +identified. With the variable unset nothing runs: no read of caller memory, no line. + +The source-built check runs four child processes: counter on (the exports and the logged lines give exactly what the +caller script did, and an array freed and allocated again is no longer counted), counter on with a caller that writes +only the 64 bytes after the last context and sends nothing (every count 0, no line), counter off (no count, no line), +and an unload case. That one allocates the contexts twice without `ApuFree` (the old array's unsampled change counts, +later ones do not), then frees both DLLs, checks that they are unmapped, waits 1.5 s and must exit 0. Every result, +output, last error and the final context bytes must match between the on and off runs: ``` ctest --preset release --no-tests=error -R '^startup_acphal_xma_activity$' -V diff --git a/src/startup_stubs/acphal.cpp b/src/startup_stubs/acphal.cpp index 7289b38846..61738b995e 100644 --- a/src/startup_stubs/acphal.cpp +++ b/src/startup_stubs/acphal.cpp @@ -115,10 +115,13 @@ bool heap_give(const void* virtual_address) // Activity counter (#1145), off unless X2W_AUDIO_ACTIVITY=1. It watches the XMA context array that // AcpHalAllocateShapeContexts hands out and counts how its 64-byte contexts change, without reading any field // in them: a context that goes from all zero to nonzero is filled, one that changes while nonzero is changed, -// one that returns to all zero is cleared. A thread compares the array with a copy about every 10 ms, so a -// context written across a sample counts twice, and one filled and cleared between two samples not at all. -// HAL slot2 submits are counted by their type argument. Once a second, if a count moved, one line gives the -// counts since the previous line. Off, nothing here runs: no thread, no read of caller memory, no line. +// one that returns to all zero is cleared. HAL slot2 submits are counted by their type argument. There is no thread: +// the array is compared with a copy inside the calls that count (a HAL submit, AcpHalAllocateShapeContexts, ApuFree of +// the array, x2w_acphal_xma_activity), at most once per 10 ms except where a call below says it samples now. A context +// written across a sample counts twice, and one filled and cleared between two samples not at all. The first of those +// calls at least a second after the previous line writes one line with the counts since then, if a count moved. +// Nothing here runs outside a call into this DLL, so a caller that unloads it leaves no code of it running. Off, +// nothing here runs: no read of caller memory, no line. bool activity_on() noexcept { return x2w_local::env_on("X2W_AUDIO_ACTIVITY"); } constexpr std::size_t context_words = 64 / sizeof(u64); @@ -127,11 +130,12 @@ struct Activity { u64 filled, changed, cleared; u64 submits[submit_types + 1]; }; -SRWLOCK activity_lock = SRWLOCK_INIT; // guards the five below +SRWLOCK activity_lock = SRWLOCK_INIT; // guards the eight below const volatile u64* watched; // the XMA contexts, or null u64* shadow; // their words at the last sample std::uint32_t watched_count, live; -Activity activity; +Activity activity, reported; // the counts now and at the last line +ULONGLONG last_sample, last_line; // GetTickCount64 of the last sample and of the last line (or the first event) volatile LONG activity_started; // set with the first counted event, never cleared // Compares the watched contexts with the copy and counts the ones that moved. Hold activity_lock. @@ -153,47 +157,44 @@ void sample_locked() noexcept } } -DWORD WINAPI activity_thread(void*) +// Samples the contexts (always when now is set, else at most once per 10 ms); if the last line is at least a second old +// and a count moved, writes the next line into text and returns true. Hold activity_lock; log the text after +// releasing it. +bool poll_locked(bool now, char (&text)[512]) noexcept { - Activity reported{}; - ULONGLONG last = GetTickCount64(); - for (;;) { - Sleep(10); - AcquireSRWLockExclusive(&activity_lock); + const ULONGLONG tick = GetTickCount64(); + if (now || tick - last_sample >= 10) { sample_locked(); - const Activity now = activity; - const std::uint32_t live_now = live, count = watched_count; - ReleaseSRWLockExclusive(&activity_lock); - if (GetTickCount64() - last < 1000) continue; - last = GetTickCount64(); - if (!std::memcmp(&now, &reported, sizeof(now))) continue; - char types[256] = ""; - std::size_t used = 0; - u64 submits = 0; - for (unsigned t = 0; t <= submit_types; ++t) { - const u64 n = now.submits[t] - reported.submits[t]; - submits += n; - if (!n || used >= sizeof(types)) continue; - used += static_cast(t < submit_types ? std::snprintf(types + used, sizeof(types) - used, " %u=%llu", t, n) - : std::snprintf(types + used, sizeof(types) - used, " other=%llu", n)); - } - x2w_local::logf("x2w-audio xma-activity t=%.1f s: contexts filled=%llu changed=%llu cleared=%llu live=%u/%u; " - "hal submits=%llu by type%s", - x2w_local::process_seconds(), now.filled - reported.filled, now.changed - reported.changed, - now.cleared - reported.cleared, live_now, count, submits, types); - reported = now; + last_sample = tick; } + if (tick - last_line < 1000) return false; + last_line = tick; + if (!std::memcmp(&activity, &reported, sizeof(activity))) return false; + char types[256] = ""; + std::size_t used = 0; + u64 submits = 0; + for (unsigned t = 0; t <= submit_types; ++t) { + const u64 n = activity.submits[t] - reported.submits[t]; + submits += n; + if (!n || used >= sizeof(types)) continue; + used += static_cast(t < submit_types ? std::snprintf(types + used, sizeof(types) - used, " %u=%llu", t, n) + : std::snprintf(types + used, sizeof(types) - used, " other=%llu", n)); + } + std::snprintf(text, sizeof(text), + "x2w-audio xma-activity t=%.1f s: contexts filled=%llu changed=%llu cleared=%llu live=%u/%u; " + "hal submits=%llu by type%s", + x2w_local::process_seconds(), activity.filled - reported.filled, activity.changed - reported.changed, + activity.cleared - reported.cleared, live, watched_count, submits, types); + reported = activity; + return true; } -// Starts the sampler with the first counted event. Hold activity_lock. +// The first counted event starts the one-second line interval. Hold activity_lock. void start_locked() noexcept { if (activity_started) return; activity_started = 1; - if (HANDLE thread = CreateThread(nullptr, 0, activity_thread, nullptr, 0, nullptr)) - CloseHandle(thread); - else - x2w_local::logf("x2w-audio xma-activity: sampler thread not started (error %lu)", GetLastError()); + last_line = GetTickCount64(); } // Watches a newly allocated XMA array; its content now is the baseline. The caller's last error is kept. @@ -201,8 +202,9 @@ void watch(unsigned char* contexts, std::uint32_t count) noexcept { const DWORD error = GetLastError(); auto* copy = new (std::nothrow) u64[std::size_t{count} * context_words]; + char text[512]; AcquireSRWLockExclusive(&activity_lock); - sample_locked(); // an earlier array's last changes still count + const bool line = poll_locked(true, text); // samples now: an earlier array's last changes still count delete[] shadow; shadow = copy; watched = copy ? reinterpret_cast(contexts) : nullptr; @@ -210,6 +212,7 @@ void watch(unsigned char* contexts, std::uint32_t count) noexcept if (copy) std::memcpy(copy, contexts, std::size_t{count} * 64); start_locked(); ReleaseSRWLockExclusive(&activity_lock); + if (line) x2w_local::logf("%s", text); x2w_local::logf(copy ? "x2w-audio xma-activity: watching %u contexts" : "x2w-audio xma-activity: no memory to watch %u contexts", count); SetLastError(error); @@ -220,16 +223,18 @@ void unwatch(const void* block) noexcept { if (!activity_started) return; const DWORD error = GetLastError(); + char text[512]; AcquireSRWLockExclusive(&activity_lock); const bool hit = watched && static_cast(watched) == block; + const bool line = poll_locked(hit, text); // samples now if the watched array is freed if (hit) { - sample_locked(); watched = nullptr; watched_count = live = 0; delete[] shadow; shadow = nullptr; } ReleaseSRWLockExclusive(&activity_lock); + if (line) x2w_local::logf("%s", text); if (hit) x2w_local::logf("x2w-audio xma-activity: contexts freed, no longer watched"); SetLastError(error); } @@ -238,10 +243,13 @@ void count_submit(unsigned type) noexcept { if (!activity_on()) return; const DWORD error = GetLastError(); + char text[512]; AcquireSRWLockExclusive(&activity_lock); ++activity.submits[type < submit_types ? type : submit_types]; start_locked(); + const bool line = poll_locked(false, text); ReleaseSRWLockExclusive(&activity_lock); + if (line) x2w_local::logf("%s", text); SetLastError(error); } @@ -461,23 +469,27 @@ extern "C" __declspec(noinline) std::uint32_t ApuMapVirtualAddress(void* virtual return result; } -// Experimental export for the source-built check (tests/startup_acphal_xma_activity.cpp): samples now and writes the -// totals since start to out[0..14]: contexts watched, contexts live, filled, changed, cleared, HAL submits, then -// submits of types 0..7 and of all other types. With X2W_AUDIO_ACTIVITY off it writes zeros and returns FALSE. +// Experimental export for the source-built check (tests/startup_acphal_xma_activity.cpp): samples now, writes the line +// if one is due, as a counted call does, and writes the totals since start to out[0..14]: contexts watched, contexts +// live, filled, changed, cleared, HAL submits, then submits of types 0..7 and of all other types. With +// X2W_AUDIO_ACTIVITY off it writes zeros and returns FALSE. extern "C" BOOL WINAPI x2w_acphal_xma_activity(ULONGLONG* out) { if (!out) return FALSE; const bool on = activity_on(); Activity now{}; std::uint32_t count = 0, live_now = 0; + char text[512]; + bool line = false; if (on) { AcquireSRWLockExclusive(&activity_lock); - sample_locked(); + line = poll_locked(true, text); now = activity; count = watched_count; live_now = live; ReleaseSRWLockExclusive(&activity_lock); } + if (line) x2w_local::logf("%s", text); out[0] = count; out[1] = live_now; out[2] = now.filled; diff --git a/src/startup_stubs/xapu.cpp b/src/startup_stubs/xapu.cpp index 6c97b2b153..88dbd335ae 100644 --- a/src/startup_stubs/xapu.cpp +++ b/src/startup_stubs/xapu.cpp @@ -218,43 +218,51 @@ long decode_packet(Connection& conn, const unsigned char* c, std::uint32_t& byte // Activity counter (#1145), off unless X2W_AUDIO_ACTIVITY=1: every XApuEnqueueCommand call, counted by command class, // taken as the first UINT32 of the command (a stand-in convention, like the result type above), with no cap. // Classes 0..15 are counted one by one and larger ones together; a command that cannot be read and a call with an -// unknown handle are counted apart. Once a second, if a count moved, one line gives the counts since the previous -// line. Off, nothing here runs: no thread, no read of the command, no line. +// unknown handle are counted apart. commands= in the line is the classes plus the unreadable ones; rejected calls are +// not in it. There is no thread: the first counted call (or x2w_xapu_command_counts) at least a second after the +// previous line writes one line with the counts since then, if a count moved, so nothing here runs outside a call into +// this DLL. Off, nothing here runs: no read of the command, no line. constexpr unsigned command_classes = 16; struct CommandCounts { u64 by_class[command_classes + 1]; // the last entry: every larger class u64 unreadable, rejected; }; -SRWLOCK count_lock = SRWLOCK_INIT; // guards the two below -CommandCounts command_counts; +SRWLOCK count_lock = SRWLOCK_INIT; // guards the four below +CommandCounts command_counts, reported; // the counts now and at the last line +ULONGLONG last_line; // GetTickCount64 of the last line, or of the first counted call bool counting_started; bool activity_on() noexcept { return x2w_local::env_on("X2W_AUDIO_ACTIVITY"); } -DWORD WINAPI activity_thread(void*) +// If the last line is at least a second old and a count moved, writes the next line into text and returns true. +// Hold count_lock exclusively; log the text after releasing it. +bool poll_locked(char (&text)[512]) noexcept { - CommandCounts reported{}; - for (;;) { - Sleep(1000); - AcquireSRWLockShared(&count_lock); - const CommandCounts now = command_counts; - ReleaseSRWLockShared(&count_lock); - if (!std::memcmp(&now, &reported, sizeof(now))) continue; - char classes[320] = ""; - std::size_t used = 0; - u64 commands = now.unreadable - reported.unreadable; - for (unsigned c = 0; c <= command_classes; ++c) { - const u64 n = now.by_class[c] - reported.by_class[c]; - commands += n; - if (!n || used >= sizeof(classes)) continue; - used += static_cast(c < command_classes ? std::snprintf(classes + used, sizeof(classes) - used, " %u=%llu", c, n) - : std::snprintf(classes + used, sizeof(classes) - used, " other=%llu", n)); - } - x2w_local::logf("x2w-audio xapu-activity t=%.1f s: commands=%llu by class%s unreadable=%llu; rejected=%llu", - x2w_local::process_seconds(), commands, classes, now.unreadable - reported.unreadable, - now.rejected - reported.rejected); - reported = now; + const ULONGLONG tick = GetTickCount64(); + if (!counting_started) { + counting_started = true; + last_line = tick; + } + if (tick - last_line < 1000) return false; + last_line = tick; + const CommandCounts& now = command_counts; + if (!std::memcmp(&now, &reported, sizeof(now))) return false; + char classes[320] = ""; + std::size_t used = 0; + u64 commands = now.unreadable - reported.unreadable; + for (unsigned c = 0; c <= command_classes; ++c) { + const u64 n = now.by_class[c] - reported.by_class[c]; + commands += n; + if (!n || used >= sizeof(classes)) continue; + used += static_cast(c < command_classes ? std::snprintf(classes + used, sizeof(classes) - used, " %u=%llu", c, n) + : std::snprintf(classes + used, sizeof(classes) - used, " other=%llu", n)); } + std::snprintf(text, sizeof(text), + "x2w-audio xapu-activity t=%.1f s: commands=%llu by class%s unreadable=%llu; rejected=%llu (not in commands)", + x2w_local::process_seconds(), commands, classes, now.unreadable - reported.unreadable, + now.rejected - reported.rejected); + reported = now; + return true; } // Counts one XApuEnqueueCommand call; the caller's last error is kept. @@ -264,6 +272,7 @@ void count_command(long hr, const void* command) noexcept const DWORD error = GetLastError(); const bool readable = hr != hr_handle && x2w_local::readable(command, sizeof(std::uint32_t)); const std::uint32_t command_class = readable ? *static_cast(command) : 0; + char text[512]; AcquireSRWLockExclusive(&count_lock); if (hr == hr_handle) ++command_counts.rejected; @@ -271,15 +280,9 @@ void count_command(long hr, const void* command) noexcept ++command_counts.unreadable; else ++command_counts.by_class[command_class < command_classes ? command_class : command_classes]; - const bool start = !counting_started; - counting_started = true; + const bool line = poll_locked(text); ReleaseSRWLockExclusive(&count_lock); - if (start) { - if (HANDLE thread = CreateThread(nullptr, 0, activity_thread, nullptr, 0, nullptr)) - CloseHandle(thread); - else - x2w_local::logf("x2w-audio xapu-activity: report thread not started (error %lu)", GetLastError()); - } + if (line) x2w_local::logf("%s", text); SetLastError(error); } } // namespace @@ -467,19 +470,23 @@ extern "C" __declspec(noinline) long XApuDisconnect(u64 rcx, u64 rdx, u64 r8, u6 return hr_ok; } -// Experimental export for the source-built check (tests/startup_acphal_xma_activity.cpp): writes the totals since -// start to out[0..18]: commands of classes 0..15, of larger classes, unreadable commands, calls with an unknown +// Experimental export for the source-built check (tests/startup_acphal_xma_activity.cpp): writes the line if one is +// due, as a counted call does, and the totals since start to out[0..18]: commands of classes 0..15, of larger classes, unreadable commands, calls with an unknown // handle. With X2W_AUDIO_ACTIVITY off it writes zeros and returns FALSE. extern "C" BOOL WINAPI x2w_xapu_command_counts(ULONGLONG* out) { if (!out) return FALSE; const bool on = activity_on(); CommandCounts now{}; + char text[512]; + bool line = false; if (on) { - AcquireSRWLockShared(&count_lock); + AcquireSRWLockExclusive(&count_lock); + line = poll_locked(text); now = command_counts; - ReleaseSRWLockShared(&count_lock); + ReleaseSRWLockExclusive(&count_lock); } + if (line) x2w_local::logf("%s", text); for (unsigned c = 0; c <= command_classes; ++c) out[c] = now.by_class[c]; out[command_classes + 1] = now.unreadable; out[command_classes + 2] = now.rejected; diff --git a/tests/startup_acphal_xma_activity.cpp b/tests/startup_acphal_xma_activity.cpp index 7f24fbfa6c..81079cda14 100644 --- a/tests/startup_acphal_xma_activity.cpp +++ b/tests/startup_acphal_xma_activity.cpp @@ -6,6 +6,11 @@ // none counter on, but the caller writes only next to the contexts and sends nothing: every count is 0 and no // activity line is logged // off counter unset, same script as on: the exports report nothing and no line is logged +// unload counter on: AcpHalAllocateShapeContexts runs again without an ApuFree (the old array's last changes count, +// later ones do not, the new array is counted), then the caller unloads both DLLs and stays alive for 1.5 s; +// it must exit 0, so nothing of either DLL may run after FreeLibrary +// The stand-ins log a due activity line only inside a call into them, so the cases call the exports before they read +// the log. // Every call's result, output and last error, and the final context bytes, must be the same with the counter on and // off. The 64-byte context stride and the command class (first UINT32) are stand-in conventions, not a console layout. // Usage: startup_acphal_xma_activity @@ -194,8 +199,8 @@ int activity_lines(const char* log_path) return lines; } -// The caller script of the on and off cases. Snapshots are taken between phases, so each context moves once -// between two samples whatever the sampler thread does in between. +// The caller script of the on and off cases. Snapshots are taken between phases and no other counted call runs while +// the contexts are written, so each context moves once between two samples. void script(const Api& api, bool on) { sentinel(); @@ -300,7 +305,7 @@ void script(const Api& api, bool on) store(p, 0, 0, 0x6666); store(p, 5, 1, 0x7777); store(p, 300, 7, 0x8888); - Sleep(50); // several sampler periods + Sleep(50); // several 10 ms sample periods } expect_on("after free and reuse", take(api.acphal_activity), on, acphal_fields, {{filled, 5}, {changed, 3}, {cleared, 2}, {submits, 4}, {submit_type0 + 1, 2}, {submit_type0 + 3, 1}, @@ -334,6 +339,47 @@ void script_none(const Api& api) expect("zero-write control XApu", take(api.xapu_counts), TRUE, xapu_fields, {}); } +// The unload case. Nothing in it is compared with another run. +void script_unload(const Api& api, HMODULE acphal, HMODULE xapu) +{ + check(api.create_heap(0x200000, 0) == 0, "ApuCreateHeap"); + void* hal = nullptr; + check(api.hal_create(&hal) == 0 && hal, "AcpHalCreate"); + if (!hal) return; + auto hal_submit = reinterpret_cast((*reinterpret_cast(hal))[2]); + const unsigned input = 0; + check(hal_submit(hal, 1, 0x1234, 2, &input, 0) == 0, "AcpHal submit"); + ShapeContexts first{}, second{}; + first.counts[4] = contexts; + second.counts[4] = 4; + check(api.shape_alloc(&first) == 0 && first.arrays[4], "first AcpHalAllocateShapeContexts"); + if (!first.arrays[4]) return; + store(first.arrays[4], 0, 0, 0x1111); // not sampled yet: the re-run's last sample of this array counts it + check(api.shape_alloc(&second) == 0 && second.arrays[4] && second.arrays[4] != first.arrays[4], + "AcpHalAllocateShapeContexts again, without ApuFree, gives another array"); + if (!second.arrays[4]) return; + store(first.arrays[4], 1, 0, 0x2222); // the old array is no longer watched + store(second.arrays[4], 3, 7, 0x3333); // the new one is, up to its last word + expect("re-run without ApuFree", take(api.acphal_activity), TRUE, acphal_fields, + {{watched, 4}, {live, 1}, {filled, 2}, {submits, 1}, {submit_type0 + 1, 1}}); + unsigned char connect_input[0x18]{}, connect_output[0x10]{}, command[0x60]{}; + u64 handle = 0; + command[0] = 1; + check(api.connect(connect_input, connect_output, &handle) == 0, "XApuConnect"); + api.enqueue(handle, command, 0, 0); + expect("XApu command before unload", take(api.xapu_counts), TRUE, xapu_fields, {{1, 1}}); + // Unloading must really unmap both images, else the wait below proves nothing. + const void* const code[] = {reinterpret_cast(api.create_heap), reinterpret_cast(api.enqueue)}; + check(FreeLibrary(acphal) && FreeLibrary(xapu), "FreeLibrary of both stand-ins"); + for (const void* address : code) { + HMODULE still = nullptr; + check(!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + static_cast(address), &still), + "the stand-in is unloaded after FreeLibrary"); + } + Sleep(1500); // past a 10 ms sample period and a 1 s line interval: a leftover thread of either DLL would run now +} + int run_case(const char* name, const char* acphal_path, const char* xapu_path, const char* transcript_path) { HMODULE acphal = LoadLibraryA(acphal_path), xapu = LoadLibraryA(xapu_path); @@ -358,9 +404,13 @@ int run_case(const char* name, const char* acphal_path, const char* xapu_path, c GetEnvironmentVariableA("X2W_TRAP_LOG", log_path, MAX_PATH); check(api.acphal_activity(nullptr) == FALSE && api.xapu_counts(nullptr) == FALSE, "the exports refuse a null output"); - if (!std::strcmp(name, "none")) { + if (!std::strcmp(name, "unload")) { + script_unload(api, acphal, xapu); + } else if (!std::strcmp(name, "none")) { script_none(api); - Sleep(1500); // longer than the report interval: an unchanged count writes no line + Sleep(1500); // longer than the line interval: an unchanged count writes no line + take(api.acphal_activity); + take(api.xapu_counts); check(activity_lines(log_path) == 0, "zero-write control logs no activity line"); } else { const bool on = !std::strcmp(name, "on"); @@ -372,7 +422,9 @@ int run_case(const char* name, const char* acphal_path, const char* xapu_path, c {"xapu.other", 1}, {"xapu.unreadable", 1}, {"xapu.rejected", 1}}; std::map got; int lines = 0; - for (int waited = 0; waited <= 5000; waited += 100) { // a line comes about a second after a change + for (int waited = 0; waited <= 5000; waited += 100) { // a call a second after the last line writes the next + take(api.acphal_activity); + take(api.xapu_counts); got = activity_sums(read_file(log_path), &lines); if (got == want) break; Sleep(100); @@ -384,6 +436,8 @@ int run_case(const char* name, const char* acphal_path, const char* xapu_path, c } } else { Sleep(1500); + take(api.acphal_activity); + take(api.xapu_counts); check(activity_lines(log_path) == 0, "counter off logs no activity line"); check(read_file(log_path).find("-activity") == std::string::npos, "counter off logs nothing about activity"); } @@ -417,8 +471,8 @@ DWORD spawn(const char* self, const char* name, const char* acphal, const char* PROCESS_INFORMATION pi{}; if (!CreateProcessA(nullptr, cmd.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &si, &pi)) return 0xFFFFFFFFu; DWORD code = 0xFFFFFFFEu; - // 15 s per case keeps all three inside the CTest TIMEOUT of 60 s, so a hung case is named, not killed with the parent. - if (WaitForSingleObject(pi.hProcess, 15000) == WAIT_OBJECT_0) GetExitCodeProcess(pi.hProcess, &code); + // 12 s per case keeps all four inside the CTest TIMEOUT of 60 s, so a hung case is named, not killed with the parent. + if (WaitForSingleObject(pi.hProcess, 12000) == WAIT_OBJECT_0) GetExitCodeProcess(pi.hProcess, &code); else TerminateProcess(pi.hProcess, 0xFFFFFFFDu); // our own child, by handle CloseHandle(pi.hThread); CloseHandle(pi.hProcess); @@ -436,7 +490,7 @@ int main(int argc, char** argv) if (!CreateDirectoryA(dir.c_str(), nullptr)) return std::printf("FAIL: cannot create %s\n", dir.c_str()), 2; char self[MAX_PATH]; GetModuleFileNameA(nullptr, self, MAX_PATH); - for (const char* name : {"on", "none", "off"}) { + for (const char* name : {"on", "none", "off", "unload"}) { const DWORD code = spawn(self, name, argv[1], argv[2], dir); if (code) { std::printf("FAIL: case %s exited 0x%08lx\n", name, static_cast(code)); @@ -453,7 +507,7 @@ int main(int argc, char** argv) on.substr(line, on.find('\n', line) - line).c_str(), off.substr(line, off.find('\n', line) - line).c_str()); ++failures; } - for (const char* file : {"on.log", "none.log", "off.log", "on.txt", "off.txt"}) DeleteFileA((dir + "\\" + file).c_str()); + for (const char* file : {"on.log", "none.log", "off.log", "unload.log", "on.txt", "off.txt"}) DeleteFileA((dir + "\\" + file).c_str()); RemoveDirectoryA(dir.c_str()); std::printf(failures ? "startup_acphal_xma_activity: %d failure(s)\n" : "startup_acphal_xma_activity: ok\n", failures); return failures ? 1 : 0; From c6a72cd0d37cd263a39bc01267e6c556a00bf1bb Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:49:49 +1000 Subject: [PATCH 07/10] gh #1145 review round 2107-2: start the line interval at the last written line; fix comments --- docs/experiments.md | 2 +- docs/startup-runtime.md | 22 ++++++++++++---------- src/startup_stubs/acphal.cpp | 18 ++++++++++-------- src/startup_stubs/xapu.cpp | 24 ++++++++++++------------ tests/startup_acphal_xma_activity.cpp | 2 +- 5 files changed, 36 insertions(+), 32 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 3c9254238c..13c470b0bb 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -10337,7 +10337,7 @@ The desktop `AcpHal.dll` stand-in (not the fixture provider above) now returns ` ### XMA context activity in the AcpHal stand-in -With `X2W_AUDIO_PERMISSIVE=1` and `X2W_AUDIO_ACTIVITY=1`, the desktop `AcpHal.dll` and `xapu.dll` stand-ins count what a caller does with the audio processor. This is a first measurement for [issue #1145](https://github.com/R0Y00/Xbox2Windows/issues/1145), before any decoding. AcpHal compares the XMA context array it allocated with a copy inside the calls that count, at most once per 10 ms, and counts contexts filled (all zero to nonzero), changed and cleared, plus HAL slot2 submits by type. xapu counts `XApuEnqueueCommand` calls by command class with no cap. Neither DLL starts a thread; each logs at most a line per second, from a counted call, when a count moved; the experimental exports `x2w_acphal_xma_activity` and `x2w_xapu_command_counts` return the totals. Line formats and limits are in [startup-runtime.md](startup-runtime.md#activity-counter). +With `X2W_AUDIO_PERMISSIVE=1` and `X2W_AUDIO_ACTIVITY=1`, the desktop `AcpHal.dll` and `xapu.dll` stand-ins count what a caller does with the audio processor. This is a first measurement for [issue #1145](https://github.com/R0Y00/Xbox2Windows/issues/1145), before any decoding. AcpHal compares the XMA context array it allocated with a copy inside the calls that count, at most once per 10 ms, and counts contexts filled (all zero to nonzero), changed and cleared, plus HAL slot2 submits by type. xapu counts `XApuEnqueueCommand` calls by command class with no cap. Neither DLL starts a thread; each logs at most a line per second, from a counted call at least a second after its previous line, when a count moved (later counts wait for a later call); the experimental exports `x2w_acphal_xma_activity` and `x2w_xapu_command_counts` return the totals. Line formats and limits are in [startup-runtime.md](startup-runtime.md#activity-counter). `startup_acphal_xma_activity` runs one source-built caller script in three child processes, plus an unload case. With the counter on, the caller fills 5 contexts, changes 3 and clears 2, submits 4 HAL commands of types 1, 1, 3 and 12, and enqueues 6 XApu commands of classes 1, 2 and 0x20, one null command and one command on an unknown handle. The exports and the summed log lines must give exactly those counts, and an array freed and allocated again must not be counted. The zero-write control writes only the 64 bytes after the last context and sends nothing: every count must be 0 and no line may be logged. With the counter off, the exports report nothing and no line is logged. Every result, output, last error and the final context bytes must match between the on and off runs. The unload case allocates the contexts a second time without `ApuFree`, then frees both DLLs, checks that they are unmapped, waits 1.5 s and must exit 0. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index a301c64834..931c866873 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2321,17 +2321,19 @@ ctest --preset dev --no-tests=error -R '^startup_acphal_apu_free$' -V With `X2W_AUDIO_ACTIVITY=1` as well, the stand-ins count what a caller does with the audio processor without decoding anything. `AcpHal.dll` keeps a copy of the XMA context array that `AcpHalAllocateShapeContexts` hands out and compares -the array with it inside the calls that count (HAL submits, `AcpHalAllocateShapeContexts`, `ApuFree` of the array and -`x2w_acphal_xma_activity`), at most once per 10 ms. Each 64-byte context is taken as a whole and no field in it is read: one that -goes from all zero to nonzero counts as filled, one that changes while nonzero as changed, one that returns to all zero -as cleared. HAL slot2 submits are counted by their type argument. `xapu.dll` counts every `XApuEnqueueCommand` call by -command class, taken as the first `UINT32` of the command, with no cap; unreadable commands and unknown handles are -counted apart; `commands=` is the classes plus the unreadable commands, and `rejected=` calls are not in it. Not counted: in an `X2W_WITH_OPUS` build with `X2W_XAPU_TYPED_COMPLETIONS=1`, a type 3 +the array with it inside the calls that count (HAL submits, `AcpHalAllocateShapeContexts`, every `ApuFree` once counting +started and `x2w_acphal_xma_activity`), at most once per 10 ms. Each 64-byte context is taken as a whole and no field in +it is read: one that goes from all zero to nonzero counts as filled, one that changes while nonzero as changed, one that +returns to all zero as cleared. HAL slot2 submits are counted by their type argument. `xapu.dll` counts every +`XApuEnqueueCommand` call by command class, taken as the first `UINT32` of the command, with no cap; unreadable commands +and unknown handles are counted apart; `commands=` is the classes plus the unreadable commands, and `rejected=` calls +are not in it. Not counted: in an `X2W_WITH_OPUS` build with `X2W_XAPU_TYPED_COMPLETIONS=1`, a type 3 command too short to decode, which returns `E_POINTER` before the count. -Neither DLL -starts a thread: the first counted call at least a second after a DLL's previous line logs one line with the counts -since then, only when a count moved, so nothing of either DLL runs after a caller unloads it. Changes made after the -last counted call are not logged. With the fixture's caller, for example: +Neither DLL starts a thread: a counted call at least a second after a DLL's previous line (or its first +counted call) logs the next line, with the counts since that line, only when a count moved, so nothing of either DLL +runs after a caller unloads it. Until then the counts wait for a later call: counts from the last second before a +caller's final call, and changes after it, are not logged, though the exports still return them. With the fixture's +caller, for example: ``` x2w-audio xma-activity t=1.1 s: contexts filled=5 changed=3 cleared=2 live=0/0; hal submits=4 by type 1=2 3=1 other=1 diff --git a/src/startup_stubs/acphal.cpp b/src/startup_stubs/acphal.cpp index 61738b995e..214c7dfbf2 100644 --- a/src/startup_stubs/acphal.cpp +++ b/src/startup_stubs/acphal.cpp @@ -116,10 +116,11 @@ bool heap_give(const void* virtual_address) // AcpHalAllocateShapeContexts hands out and counts how its 64-byte contexts change, without reading any field // in them: a context that goes from all zero to nonzero is filled, one that changes while nonzero is changed, // one that returns to all zero is cleared. HAL slot2 submits are counted by their type argument. There is no thread: -// the array is compared with a copy inside the calls that count (a HAL submit, AcpHalAllocateShapeContexts, ApuFree of -// the array, x2w_acphal_xma_activity), at most once per 10 ms except where a call below says it samples now. A context -// written across a sample counts twice, and one filled and cleared between two samples not at all. The first of those -// calls at least a second after the previous line writes one line with the counts since then, if a count moved. +// the array is compared with a copy inside the calls that count (a HAL submit, AcpHalAllocateShapeContexts, every +// ApuFree once counting started, x2w_acphal_xma_activity), at most once per 10 ms except where a call below says it +// samples now. A context written across a sample counts twice, and one filled and cleared between two samples not at +// all. Such a call at least a second after the previous line (or the first counted event) writes the next line, with +// the counts since that line, if a count moved; until then the counts wait for a later call. // Nothing here runs outside a call into this DLL, so a caller that unloads it leaves no code of it running. Off, // nothing here runs: no read of caller memory, no line. bool activity_on() noexcept { return x2w_local::env_on("X2W_AUDIO_ACTIVITY"); } @@ -135,7 +136,8 @@ const volatile u64* watched; // the XMA contexts, or null u64* shadow; // their words at the last sample std::uint32_t watched_count, live; Activity activity, reported; // the counts now and at the last line -ULONGLONG last_sample, last_line; // GetTickCount64 of the last sample and of the last line (or the first event) +ULONGLONG last_sample, last_line; // GetTickCount64 of the last sample and of the last line written + // (or of the first counted event) volatile LONG activity_started; // set with the first counted event, never cleared // Compares the watched contexts with the copy and counts the ones that moved. Hold activity_lock. @@ -167,9 +169,8 @@ bool poll_locked(bool now, char (&text)[512]) noexcept sample_locked(); last_sample = tick; } - if (tick - last_line < 1000) return false; + if (tick - last_line < 1000 || !std::memcmp(&activity, &reported, sizeof(activity))) return false; last_line = tick; - if (!std::memcmp(&activity, &reported, sizeof(activity))) return false; char types[256] = ""; std::size_t used = 0; u64 submits = 0; @@ -218,7 +219,8 @@ void watch(unsigned char* contexts, std::uint32_t count) noexcept SetLastError(error); } -// ApuFree of the watched array: its last changes count, then watching stops before the block can be reused. +// Every ApuFree once counting started: samples (now, if the block is the watched array) and may write the line. ApuFree +// of the watched array: its last changes count, then watching stops before the block can be reused. void unwatch(const void* block) noexcept { if (!activity_started) return; diff --git a/src/startup_stubs/xapu.cpp b/src/startup_stubs/xapu.cpp index 88dbd335ae..a9db5b5061 100644 --- a/src/startup_stubs/xapu.cpp +++ b/src/startup_stubs/xapu.cpp @@ -216,12 +216,13 @@ long decode_packet(Connection& conn, const unsigned char* c, std::uint32_t& byte #endif // Activity counter (#1145), off unless X2W_AUDIO_ACTIVITY=1: every XApuEnqueueCommand call, counted by command class, -// taken as the first UINT32 of the command (a stand-in convention, like the result type above), with no cap. -// Classes 0..15 are counted one by one and larger ones together; a command that cannot be read and a call with an -// unknown handle are counted apart. commands= in the line is the classes plus the unreadable ones; rejected calls are -// not in it. There is no thread: the first counted call (or x2w_xapu_command_counts) at least a second after the -// previous line writes one line with the counts since then, if a count moved, so nothing here runs outside a call into -// this DLL. Off, nothing here runs: no read of the command, no line. +// taken as the first UINT32 of the command (a stand-in convention, like the result type above), with no cap. Classes +// 0..15 are counted one by one and larger ones together; a command that cannot be read and a call with an unknown +// handle are counted apart. commands= in the line is the classes plus the unreadable ones; rejected calls are not in +// it. There is no thread: a counted call (or x2w_xapu_command_counts) at least a second after the previous line (or the +// first such call) writes the next line, with the counts since that line, if a count moved; until then the counts wait +// for a later call. Nothing here runs outside a call into this DLL. Off, nothing here runs: no read of the command, no +// line. constexpr unsigned command_classes = 16; struct CommandCounts { u64 by_class[command_classes + 1]; // the last entry: every larger class @@ -229,7 +230,7 @@ struct CommandCounts { }; SRWLOCK count_lock = SRWLOCK_INIT; // guards the four below CommandCounts command_counts, reported; // the counts now and at the last line -ULONGLONG last_line; // GetTickCount64 of the last line, or of the first counted call +ULONGLONG last_line; // GetTickCount64 of the last line written, or of the first counted call or counter-on export call bool counting_started; bool activity_on() noexcept { return x2w_local::env_on("X2W_AUDIO_ACTIVITY"); } @@ -243,10 +244,9 @@ bool poll_locked(char (&text)[512]) noexcept counting_started = true; last_line = tick; } - if (tick - last_line < 1000) return false; - last_line = tick; const CommandCounts& now = command_counts; - if (!std::memcmp(&now, &reported, sizeof(now))) return false; + if (tick - last_line < 1000 || !std::memcmp(&now, &reported, sizeof(now))) return false; + last_line = tick; char classes[320] = ""; std::size_t used = 0; u64 commands = now.unreadable - reported.unreadable; @@ -471,8 +471,8 @@ extern "C" __declspec(noinline) long XApuDisconnect(u64 rcx, u64 rdx, u64 r8, u6 } // Experimental export for the source-built check (tests/startup_acphal_xma_activity.cpp): writes the line if one is -// due, as a counted call does, and the totals since start to out[0..18]: commands of classes 0..15, of larger classes, unreadable commands, calls with an unknown -// handle. With X2W_AUDIO_ACTIVITY off it writes zeros and returns FALSE. +// due, as a counted call does, and the totals since start to out[0..18]: commands of classes 0..15, of larger classes, +// unreadable commands, calls with an unknown handle. With X2W_AUDIO_ACTIVITY off it writes zeros and returns FALSE. extern "C" BOOL WINAPI x2w_xapu_command_counts(ULONGLONG* out) { if (!out) return FALSE; diff --git a/tests/startup_acphal_xma_activity.cpp b/tests/startup_acphal_xma_activity.cpp index 81079cda14..6983c5d14b 100644 --- a/tests/startup_acphal_xma_activity.cpp +++ b/tests/startup_acphal_xma_activity.cpp @@ -422,7 +422,7 @@ int run_case(const char* name, const char* acphal_path, const char* xapu_path, c {"xapu.other", 1}, {"xapu.unreadable", 1}, {"xapu.rejected", 1}}; std::map got; int lines = 0; - for (int waited = 0; waited <= 5000; waited += 100) { // a call a second after the last line writes the next + for (int waited = 0; waited <= 5000; waited += 100) { // a call a second after the start writes the line take(api.acphal_activity); take(api.xapu_counts); got = activity_sums(read_file(log_path), &lines); From 83be47087a1f2c08a477454c38958bd7df478a2e Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:52:49 +1000 Subject: [PATCH 08/10] audio: count unreadable XApu commands on the early E_POINTER path main's XApuEnqueueCommand now refuses a null or unreadable command header with E_POINTER before the activity counter runs, so the unreadable count never moved. Count those calls as unreadable on that path. A call refused for a full ring (E_OUTOFMEMORY) is still counted by its command class. --- src/startup_stubs/xapu.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/startup_stubs/xapu.cpp b/src/startup_stubs/xapu.cpp index a9db5b5061..fa397519b0 100644 --- a/src/startup_stubs/xapu.cpp +++ b/src/startup_stubs/xapu.cpp @@ -395,6 +395,7 @@ extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8 static LONG bad_cmd_calls; if (x2w_local::first_calls(bad_cmd_calls, 2)) x2w_local::logf("x2w-audio XApuEnqueueCommand handle=0x%llx -> E_POINTER", rcx); + count_command(hr_pointer, nullptr); // a header this call refuses as unreadable counts as unreadable return hr_pointer; } QueueEntry entry{}; From b8cbea6ce995097c79af70afa0ac267468c08957 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:30:35 +1000 Subject: [PATCH 09/10] gh #1145 rebase: give the fixture's XApuConnect a nonzero buffer size XApuConnect now refuses a size of 0 at input +0x0C (#2288), so the fixture's commands all landed on an unknown handle. --- tests/startup_acphal_xma_activity.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/startup_acphal_xma_activity.cpp b/tests/startup_acphal_xma_activity.cpp index 6983c5d14b..335dea77f7 100644 --- a/tests/startup_acphal_xma_activity.cpp +++ b/tests/startup_acphal_xma_activity.cpp @@ -97,6 +97,13 @@ void note(const char* what, long hr, unsigned long long value = 0) } void sentinel() { SetLastError(0x5A5A); } +// XApuConnect refuses a shared buffer size of 0 (the u32 at input +0x0C) with E_INVALIDARG; 4 KiB is enough here. +void set_buffer_size(unsigned char* connect_input) +{ + const std::uint32_t bytes = 0x1000; + std::memcpy(connect_input + 0x0C, &bytes, sizeof(bytes)); +} + // One aligned 8-byte store, so the sampler sees the context before or after it, never half written. void store(unsigned char* base, std::uint32_t context, unsigned word, u64 value) { @@ -253,6 +260,7 @@ void script(const Api& api, bool on) {submit_type0 + 3, 1}, {submit_other, 1}}); unsigned char connect_input[0x18]{}, connect_output[0x10]{}; + set_buffer_size(connect_input); u64 handle = 0; sentinel(); note("XApuConnect", api.connect(connect_input, connect_output, &handle), handle); @@ -331,6 +339,7 @@ void script_none(const Api& api) store(static_cast(next), 0, 7, 0x9999); } unsigned char connect_input[0x18]{}, connect_output[0x10]{}; + set_buffer_size(connect_input); u64 handle = 0; check(api.connect(connect_input, connect_output, &handle) == 0, "XApuConnect"); check(api.disconnect(handle) == 0, "XApuDisconnect"); @@ -363,6 +372,7 @@ void script_unload(const Api& api, HMODULE acphal, HMODULE xapu) expect("re-run without ApuFree", take(api.acphal_activity), TRUE, acphal_fields, {{watched, 4}, {live, 1}, {filled, 2}, {submits, 1}, {submit_type0 + 1, 1}}); unsigned char connect_input[0x18]{}, connect_output[0x10]{}, command[0x60]{}; + set_buffer_size(connect_input); u64 handle = 0; command[0] = 1; check(api.connect(connect_input, connect_output, &handle) == 0, "XApuConnect"); From cdab51a05579a18fe88c4bff722189830ae94b30 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Sat, 28 Nov 2026 10:59:59 +1000 Subject: [PATCH 10/10] audio: count the short decode command that XApuEnqueueCommand refuses before the queue In an X2W_WITH_OPUS build with typed completions, a type 3 command too short to decode returned E_POINTER before count_command. Count it by its class, as the other E_POINTER refusals after the header read are, and pin it in startup_acphal_xma_activity with a type 3 header that ends where free address space begins (X2W_PROBE_PRECHECK=1 refuses the tail without a fault). --- docs/experiments.md | 2 +- docs/startup-runtime.md | 4 ++-- src/startup_stubs/xapu.cpp | 1 + tests/startup_acphal_xma_activity.cpp | 30 ++++++++++++++++++++++++--- 4 files changed, 31 insertions(+), 6 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 887c35b9e9..af61c01aff 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -12058,7 +12058,7 @@ The desktop `AcpHal.dll` stand-in (not the fixture provider above) now returns ` With `X2W_AUDIO_PERMISSIVE=1` and `X2W_AUDIO_ACTIVITY=1`, the desktop `AcpHal.dll` and `xapu.dll` stand-ins count what a caller does with the audio processor. This is a first measurement for [issue #1145](https://github.com/R0Y00/Xbox2Windows/issues/1145), before any decoding. AcpHal compares the XMA context array it allocated with a copy inside the calls that count, at most once per 10 ms, and counts contexts filled (all zero to nonzero), changed and cleared, plus HAL slot2 submits by type. xapu counts `XApuEnqueueCommand` calls by command class with no cap. Neither DLL starts a thread; each logs at most a line per second, from a counted call at least a second after its previous line, when a count moved (later counts wait for a later call); the experimental exports `x2w_acphal_xma_activity` and `x2w_xapu_command_counts` return the totals. Line formats and limits are in [startup-runtime.md](startup-runtime.md#activity-counter). -`startup_acphal_xma_activity` runs one source-built caller script in three child processes, plus an unload case. With the counter on, the caller fills 5 contexts, changes 3 and clears 2, submits 4 HAL commands of types 1, 1, 3 and 12, and enqueues 6 XApu commands of classes 1, 2 and 0x20, one null command and one command on an unknown handle. The exports and the summed log lines must give exactly those counts, and an array freed and allocated again must not be counted. The zero-write control writes only the 64 bytes after the last context and sends nothing: every count must be 0 and no line may be logged. With the counter off, the exports report nothing and no line is logged. Every result, output, last error and the final context bytes must match between the on and off runs. The unload case allocates the contexts a second time without `ApuFree`, then frees both DLLs, checks that they are unmapped, waits 1.5 s and must exit 0. +`startup_acphal_xma_activity` runs one source-built caller script in three child processes, plus an unload case. With the counter on, the caller fills 5 contexts, changes 3 and clears 2, submits 4 HAL commands of types 1, 1, 3 and 12, and enqueues 6 XApu commands of classes 1, 2 and 0x20, one null command, one command on an unknown handle and one type 3 command whose 8-byte header ends where free address space begins, sent with `X2W_XAPU_TYPED_COMPLETIONS=1` (every case sets `X2W_PROBE_PRECHECK=1`, so the free tail is refused without a fault). An `X2W_WITH_OPUS` build refuses that one with `E_POINTER` as too short to decode, and it must still count as class 3; only that build tells a counted refusal from an uncounted one. The exports and the summed log lines must give exactly those counts, and an array freed and allocated again must not be counted. The zero-write control writes only the 64 bytes after the last context and sends nothing: every count must be 0 and no line may be logged. With the counter off, the exports report nothing and no line is logged. Every result, output, last error and the final context bytes must match between the on and off runs. The unload case allocates the contexts a second time without `ApuFree`, then frees both DLLs, checks that they are unmapped, waits 1.5 s and must exit 0. ```powershell cmake --build --preset release --target startup_acphal_xma_activity diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 5754081b81..b4856edc91 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -3144,8 +3144,8 @@ it is read: one that goes from all zero to nonzero counts as filled, one that ch returns to all zero as cleared. HAL slot2 submits are counted by their type argument. `xapu.dll` counts every `XApuEnqueueCommand` call by command class, taken as the first `UINT32` of the command, with no cap; unreadable commands and unknown handles are counted apart; `commands=` is the classes plus the unreadable commands, and `rejected=` calls -are not in it. Not counted: in an `X2W_WITH_OPUS` build with `X2W_XAPU_TYPED_COMPLETIONS=1`, a type 3 -command too short to decode, which returns `E_POINTER` before the count. +are not in it. In an `X2W_WITH_OPUS` build with `X2W_XAPU_TYPED_COMPLETIONS=1`, a type 3 command too short to decode +returns `E_POINTER` before the queue and is still counted, as class 3. Neither DLL starts a thread: a counted call at least a second after a DLL's previous line (or its first counted call) logs the next line, with the counts since that line, only when a count moved, so nothing of either DLL runs after a caller unloads it. Until then the counts wait for a later call: counts from the last second before a diff --git a/src/startup_stubs/xapu.cpp b/src/startup_stubs/xapu.cpp index 47dea35a9e..8232d2bfcb 100644 --- a/src/startup_stubs/xapu.cpp +++ b/src/startup_stubs/xapu.cpp @@ -555,6 +555,7 @@ extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8 if (decode && !x2w_local::readable(reinterpret_cast(rdx), decode_command_size)) { x2w_audio::saturating_add(opus_counts.refused_short_command); x2w_local::logf("x2w-audio XApuEnqueueCommand handle=0x%llx short decode command -> E_POINTER", rcx); + count_command(hr_pointer, reinterpret_cast(rdx)); // its header was read: counted as class 3 return hr_pointer; } #endif diff --git a/tests/startup_acphal_xma_activity.cpp b/tests/startup_acphal_xma_activity.cpp index 335dea77f7..08c9ae7c72 100644 --- a/tests/startup_acphal_xma_activity.cpp +++ b/tests/startup_acphal_xma_activity.cpp @@ -276,6 +276,29 @@ void script(const Api& api, bool on) std::memcpy(command, &one, sizeof(one)); sentinel(); note("XApuEnqueueCommand unknown handle", api.enqueue(handle + 0x100, command, 0, 0)); + // A type 3 command whose 8-byte header ends where free address space begins (the rest of the page's allocation + // granule), sent with typed completions on. An X2W_WITH_OPUS build refuses it with E_POINTER before the queue, as + // too short to decode, and must still count it as class 3; without Opus it is queued like any other command. + // X2W_PROBE_PRECHECK=1 (every case) refuses the free tail without touching it, so no fault is taken. Typed + // completions are set for this call only. + SYSTEM_INFO system{}; + GetSystemInfo(&system); + auto* page = static_cast( + VirtualAlloc(nullptr, system.dwPageSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + MEMORY_BASIC_INFORMATION after{}; + const bool free_after = + page && VirtualQuery(page + system.dwPageSize, &after, sizeof(after)) && after.State == MEM_FREE; + check(free_after, "free address space after the short command"); + if (free_after) { + unsigned char* short_command = page + system.dwPageSize - 8; + const std::uint32_t three = 3; + std::memcpy(short_command, &three, sizeof(three)); + SetEnvironmentVariableA("X2W_XAPU_TYPED_COMPLETIONS", "1"); + sentinel(); + note("XApuEnqueueCommand short type 3 command", api.enqueue(handle, short_command, 0, 0)); + SetEnvironmentVariableA("X2W_XAPU_TYPED_COMPLETIONS", nullptr); + } + if (page) VirtualFree(page, 0, MEM_RELEASE); sentinel(); const std::uint32_t pending = api.result_count(handle, 0); note("XApuGetResultCount", 0, pending); @@ -291,7 +314,7 @@ void script(const Api& api, bool on) sentinel(); note("XApuDisconnect", api.disconnect(handle)); expect_on("XApu commands", take(api.xapu_counts), on, xapu_fields, - {{1, 3}, {2, 2}, {class_other, 1}, {unreadable, 1}, {rejected, 1}}); + {{1, 3}, {2, 2}, {3, 1}, {class_other, 1}, {unreadable, 1}, {rejected, 1}}); unsigned hash = 2166136261u; // FNV-1a of the context bytes: the counter never writes caller memory for (std::uint32_t i = 0; i < contexts * 64; ++i) hash = (hash ^ base[i]) * 16777619u; @@ -428,8 +451,8 @@ int run_case(const char* name, const char* acphal_path, const char* xapu_path, c if (on) { const std::map want = { {"xma.filled", 5}, {"xma.changed", 3}, {"xma.cleared", 2}, {"xma.submits", 4}, {"xma.1", 2}, - {"xma.3", 1}, {"xma.other", 1}, {"xapu.commands", 7}, {"xapu.1", 3}, {"xapu.2", 2}, - {"xapu.other", 1}, {"xapu.unreadable", 1}, {"xapu.rejected", 1}}; + {"xma.3", 1}, {"xma.other", 1}, {"xapu.commands", 8}, {"xapu.1", 3}, {"xapu.2", 2}, + {"xapu.3", 1}, {"xapu.other", 1}, {"xapu.unreadable", 1}, {"xapu.rejected", 1}}; std::map got; int lines = 0; for (int waited = 0; waited <= 5000; waited += 100) { // a call a second after the start writes the line @@ -467,6 +490,7 @@ DWORD spawn(const char* self, const char* name, const char* acphal, const char* const std::string log = dir + "\\" + name + ".log", out = dir + "\\" + name + ".txt"; SetEnvironmentVariableA("X2W_AUDIO_PERMISSIVE", "1"); SetEnvironmentVariableA("X2W_AUDIO_ACTIVITY", std::strcmp(name, "off") ? "1" : nullptr); + SetEnvironmentVariableA("X2W_PROBE_PRECHECK", "1"); // the short command's free tail is refused, not touched SetEnvironmentVariableA("X2W_TRAP_LOG", log.c_str()); std::string cmd = std::string("\"") + self + "\" --case " + name + " \"" + acphal + "\" \"" + xapu + "\" \"" + out + "\""; // The child writes to this process's stdout and stderr, so its lines reach the CTest log.