diff --git a/CMakeLists.txt b/CMakeLists.txt index 017d003eea..8a2bace6fc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1043,6 +1043,15 @@ 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, 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) +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/docs/experiments.md b/docs/experiments.md index 6c30d84af6..af61c01aff 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -12048,11 +12048,25 @@ 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 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 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, 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 +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 b5e2e009fd..b4856edc91 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1622,6 +1622,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_DRAW_DUMP_FRAME=`, `X2W_DRAW_DUMP_DIR`, `X2W_DRAW_DUMP_PIXEL=,` | 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). With `X2W_DRAW_DUMP_PIXEL`, each copy covers one texel instead and the present writes `pixel_history.txt` in `X2W_DRAW_DUMP_DIR`: one line per translated draw with `draw=`, `frame=`, `x=`, `y=`, `key=`, `count=`, `format=`, `raw=` and, for an 8-bit four-channel target, `rgba=`. The bounded history names the last draw that changed the texel (`src/startup_stubs/pixel_history.h`, `ctest --preset dev --no-tests=error -R '^startup_pixel_history_' -V`). | | `X2W_TEARDOWN_REPORT=1`, `X2W_TEARDOWN_NO_GUARD=` | Test accounting for the caches whose destructors run during the module's CRT teardown (`src/startup_stubs/d3d12_teardown.h`, #2572). With `X2W_TEARDOWN_REPORT`, each destroyed cache writes one `x2w-teardown detached= released=` line to stderr with `WriteFile`, because a stdio buffer would not be flushed from a CRT teardown. `X2W_TEARDOWN_NO_GUARD` names a cache whose detach at process exit becomes an ordinary release again: the negative control `startup_teardown_unload` runs against itself, where the termination check has to fail. Unset, both change nothing and no line is written. | | `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 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:`). | @@ -3024,7 +3025,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 @@ -3132,6 +3134,48 @@ 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 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. 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 +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 +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; 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 +``` + ## Uniform first-lane reads The startup shader translator accepts `v_readfirstlane_b32` in straight-line code with the diff --git a/src/startup_stubs/acphal.cpp b/src/startup_stubs/acphal.cpp index 9f3bdaa930..8e66537537 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) @@ -152,6 +154,149 @@ 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. 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, 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"); } + +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 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, reported; // the counts now and at the last line +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. +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); + } +} + +// 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 +{ + const ULONGLONG tick = GetTickCount64(); + if (now || tick - last_sample >= 10) { + sample_locked(); + last_sample = tick; + } + if (tick - last_line < 1000 || !std::memcmp(&activity, &reported, sizeof(activity))) return false; + last_line = tick; + 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; +} + +// The first counted event starts the one-second line interval. Hold activity_lock. +void start_locked() noexcept +{ + if (activity_started) return; + activity_started = 1; + last_line = GetTickCount64(); +} + +// 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]; + char text[512]; + AcquireSRWLockExclusive(&activity_lock); + 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; + watched_count = copy ? count : 0; + 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); +} + +// 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; + 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) { + 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); +} + +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); +} + // 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. @@ -169,6 +314,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, @@ -271,6 +417,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; } @@ -350,6 +497,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)) @@ -396,3 +544,37 @@ 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, 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); + 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; + 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 2a7fdf77d5..adf23de6ce 100644 --- a/src/startup_stubs/local_log.h +++ b/src/startup_stubs/local_log.h @@ -53,6 +53,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; +} + // First-chance exceptions stop the whole process while a debugger is attached, so a probe or a copy that is // refused before it touches an unmapped address is worth a query. faults_avoided counts those refusals; the // totals line of the render heartbeat prints it. diff --git a/src/startup_stubs/xapu.cpp b/src/startup_stubs/xapu.cpp index 8648ffe1a1..8232d2bfcb 100644 --- a/src/startup_stubs/xapu.cpp +++ b/src/startup_stubs/xapu.cpp @@ -317,6 +317,77 @@ long decode_packet(Connection& conn, const unsigned char* c, QueueEntry& entry, 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. 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 + u64 unreadable, rejected; +}; +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 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"); } + +// 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 +{ + const ULONGLONG tick = GetTickCount64(); + if (!counting_started) { + counting_started = true; + last_line = tick; + } + const CommandCounts& now = command_counts; + 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; + 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. +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; + char text[512]; + 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 line = poll_locked(text); + ReleaseSRWLockExclusive(&count_lock); + if (line) x2w_local::logf("%s", text); + SetLastError(error); +} } // namespace extern "C" __declspec(noinline) long XApuConnect(u64 rcx, u64 rdx, u64 r8, u64 r9) @@ -466,6 +537,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{}; @@ -483,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 @@ -556,6 +629,7 @@ extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8 x2w_audio::saturating_add(opus_counts.refused_out_of_memory); } #endif + count_command(hr, reinterpret_cast(rdx)); static LONG calls; if (x2w_local::first_calls(calls, 24)) { char command[3 * 0x60 + 1]; @@ -600,3 +674,26 @@ extern "C" __declspec(noinline) long XApuDisconnect(u64 rcx, u64 rdx, u64 r8, u6 #endif return hr_ok; } + +// 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) { + AcquireSRWLockExclusive(&count_lock); + line = poll_locked(text); + now = command_counts; + 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; + 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 diff --git a/tests/startup_acphal_xma_activity.cpp b/tests/startup_acphal_xma_activity.cpp new file mode 100644 index 0000000000..08c9ae7c72 --- /dev/null +++ b/tests/startup_acphal_xma_activity.cpp @@ -0,0 +1,548 @@ +// 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 +// 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 +#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); } + +// 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) +{ + 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; +} + +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, Fields 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; +} + +// 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; + 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 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(); + 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_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); + store(base, 1, 3, 0x2222); + store(base, 2, 0, 0x3333); + store(base, 100, 5, 0x4444); + store(base, 349, 7, 0x5555); + 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_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_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}) { + sentinel(); + note("AcpHal submit", hal_submit(hal, type, 0x1234, 2, &input, 0), type); + } + const auto after_submits = take(api.acphal_activity); + 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]{}; + set_buffer_size(connect_input); + 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)); + // 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); + 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_on("XApu commands", take(api.xapu_counts), on, xapu_fields, + {{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; + 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); + 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); + store(p, 5, 1, 0x7777); + store(p, 300, 7, 0x8888); + 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}, + {submit_other, 1}}); +} + +// 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]{}; + set_buffer_size(connect_input); + 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, {}); +} + +// 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]{}; + set_buffer_size(connect_input); + 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); + 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, "unload")) { + script_unload(api, acphal, xapu); + } else if (!std::strcmp(name, "none")) { + script_none(api); + 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"); + 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", 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 + take(api.acphal_activity); + take(api.xapu_counts); + 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); + 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"); + } + 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_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. + 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; + // 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); + 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", "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)); + ++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", "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; +}