#include #include #include #include #include #include #include #include #include #include namespace { constexpr UINT kMessage = WM_APP + 1; constexpr WPARAM kPayload = 42; decltype(&DefWindowProcA) g_def_window_proc; bool g_received_message = false; std::atomic g_callback_called{false}; struct ScopedModule { HMODULE handle = nullptr; ScopedModule() = default; explicit ScopedModule(HMODULE h) : handle(h) {} ~ScopedModule() { if (handle) { FreeLibrary(handle); } } ScopedModule(const ScopedModule&) = delete; ScopedModule& operator=(const ScopedModule&) = delete; explicit operator bool() const { return handle != nullptr; } HMODULE get() const { return handle; } }; LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { if (message == kMessage) { g_received_message = wparam == kPayload; return 0; } return g_def_window_proc(window, message, wparam, lparam); } void CALLBACK notification_callback(BOOLEAN, PVOID) { g_callback_called.store(true); } HMODULE load_bridge(const wchar_t* dll) { wchar_t executable[MAX_PATH]; const DWORD length = GetModuleFileNameW(nullptr, executable, MAX_PATH); if (!length || length == MAX_PATH) { return nullptr; } const std::wstring path(executable, length); const auto expected = path.substr(0, path.find_last_of(L"\\/") + 1) + dll; HMODULE module = LoadLibraryW(expected.c_str()); if (!module) { std::fwprintf(stderr, L"FAIL: could not load built bridge %ls (error %lu)\n", expected.c_str(), GetLastError()); return nullptr; } wchar_t actual[MAX_PATH]; const DWORD actual_length = GetModuleFileNameW(module, actual, MAX_PATH); if (!actual_length || actual_length == MAX_PATH) { const DWORD err = GetLastError(); FreeLibrary(module); std::fwprintf(stderr, L"FAIL: could not query path for bridge %ls (error %lu)\n", expected.c_str(), err); return nullptr; } if (CompareStringOrdinal(expected.c_str(), -1, actual, -1, TRUE) != CSTR_EQUAL) { FreeLibrary(module); std::fwprintf(stderr, L"FAIL: bridge %ls resolved to unexpected path %ls\n", expected.c_str(), actual); return nullptr; } return module; } template Function lookup(HMODULE module, const char* name) { return std::bit_cast(GetProcAddress(module, name)); } bool test_window() { const ScopedModule window(load_bridge(L"ext-ms-win-rtcore-ntuser-window-l1-1-0.dll")); const ScopedModule window_ansi(load_bridge(L"ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0.dll")); const ScopedModule message(load_bridge(L"ext-ms-win-rtcore-ntuser-message-l1-1-0.dll")); const ScopedModule message_ansi(load_bridge(L"ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0.dll")); if (!window || !window_ansi || !message || !message_ansi) { return false; } const auto show = lookup(window.get(), "ShowWindow"); const auto create = lookup(window_ansi.get(), "CreateWindowExA"); const auto register_class = lookup(window_ansi.get(), "RegisterClassExA"); g_def_window_proc = lookup(window_ansi.get(), "DefWindowProcA"); const auto translate = lookup(message.get(), "TranslateMessage"); const auto peek = lookup(message_ansi.get(), "PeekMessageA"); const auto dispatch = lookup(message_ansi.get(), "DispatchMessageA"); if (!show || !create || !register_class || !g_def_window_proc || !translate || !peek || !dispatch) { return false; } WNDCLASSEXA cls{}; cls.cbSize = sizeof(cls); cls.lpfnWndProc = window_proc; cls.hInstance = GetModuleHandleW(nullptr); cls.lpszClassName = "BetterXenBridgeConformance"; if (!register_class(&cls)) { return false; } const HWND hwnd = create(0, cls.lpszClassName, "BetterXen Win32 Bridge", WS_OVERLAPPEDWINDOW, 0, 0, 100, 100, nullptr, nullptr, cls.hInstance, nullptr); if (hwnd) { show(hwnd, SW_HIDE); if (!IsWindowVisible(hwnd) && PostMessageA(hwnd, kMessage, kPayload, 0)) { MSG msg{}; while (!g_received_message && peek(&msg, hwnd, 0, 0, PM_REMOVE)) { translate(&msg); dispatch(&msg); } } } const bool destroyed = hwnd && DestroyWindow(hwnd); const bool unregistered = UnregisterClassA(cls.lpszClassName, cls.hInstance); return g_received_message && destroyed && unregistered; } using RegisterNotification = ULONG (WINAPI*)(decltype(¬ification_callback), PVOID, PVOID*); using UnregisterNotification = VOID (WINAPI*)(PVOID); struct PsmLogCounts { size_t state_registered = 0; size_t constrained_registered = 0; size_t state_unregistered = 0; size_t state_foreign = 0; size_t state_unknown = 0; size_t constrained_unregistered = 0; size_t constrained_foreign = 0; size_t constrained_unknown = 0; }; int64_t query_file_size(const char* path) { HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (f == INVALID_HANDLE_VALUE) { return 0; } LARGE_INTEGER size{}; const bool ok = GetFileSizeEx(f, &size) != 0; CloseHandle(f); return ok && size.QuadPart > 0 ? size.QuadPart : 0; } bool count_psm_log_events(const char* path, int64_t start_offset, PsmLogCounts& out) { HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (f == INVALID_HANDLE_VALUE) { std::fprintf(stderr, "FAIL: could not open PSM log %s (error %lu)\n", path, GetLastError()); return false; } LARGE_INTEGER size{}; if (!GetFileSizeEx(f, &size) || size.QuadPart < start_offset) { CloseHandle(f); std::fprintf(stderr, "FAIL: invalid PSM log size for %s\n", path); return false; } const int64_t delta = size.QuadPart - start_offset; if (delta <= 0 || delta > (64LL << 20)) { CloseHandle(f); std::fprintf(stderr, "FAIL: unexpected PSM log delta (%lld bytes)\n", static_cast(delta)); return false; } LARGE_INTEGER seek{}; seek.QuadPart = start_offset; if (!SetFilePointerEx(f, seek, nullptr, FILE_BEGIN)) { CloseHandle(f); return false; } std::string data(static_cast(delta), '\0'); size_t total_read = 0; while (total_read < data.size()) { DWORD chunk = 0; const DWORD want = static_cast(data.size() - total_read); if (!ReadFile(f, data.data() + total_read, want, &chunk, nullptr) || chunk == 0) { break; } total_read += chunk; } CloseHandle(f); data.resize(total_read); size_t pos = 0; while (pos < data.size()) { size_t nl = data.find('\n', pos); if (nl == std::string::npos) { nl = data.size(); } const std::string line = data.substr(pos, nl - pos); pos = nl + 1; if (line.find("\"sub\":\"win32_bridge\"") == std::string::npos) { continue; } if (line.find("\"event\":\"RegisterAppStateChangeNotification\"") != std::string::npos && line.find("\"detail\":\"registered_offline\"") != std::string::npos) { ++out.state_registered; } else if (line.find("\"event\":\"RegisterAppConstrainedChangeNotification\"") != std::string::npos && line.find("\"detail\":\"registered_offline\"") != std::string::npos) { ++out.constrained_registered; } else if (line.find("\"event\":\"UnregisterAppStateChangeNotification\"") != std::string::npos) { if (line.find("\"detail\":\"unregistered\"") != std::string::npos) { ++out.state_unregistered; } else if (line.find("\"detail\":\"foreign_token\"") != std::string::npos) { ++out.state_foreign; } else if (line.find("\"detail\":\"unknown_token\"") != std::string::npos) { ++out.state_unknown; } } else if (line.find("\"event\":\"UnregisterAppConstrainedChangeNotification\"") != std::string::npos) { if (line.find("\"detail\":\"unregistered\"") != std::string::npos) { ++out.constrained_unregistered; } else if (line.find("\"detail\":\"foreign_token\"") != std::string::npos) { ++out.constrained_foreign; } else if (line.find("\"detail\":\"unknown_token\"") != std::string::npos) { ++out.constrained_unknown; } } } return true; } bool test_psm() { char log_path[MAX_PATH]{}; bool created_temp_log = false; const DWORD existing_len = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path)); if (existing_len == 0 || existing_len >= sizeof(log_path)) { char temp_dir[MAX_PATH]{}; const DWORD dir_len = GetTempPathA(sizeof(temp_dir), temp_dir); if (dir_len == 0 || dir_len >= sizeof(temp_dir) || GetTempFileNameA(temp_dir, "bxp", 0, log_path) == 0) { std::fprintf(stderr, "FAIL: could not create temporary PSM log file\n"); return false; } if (!SetEnvironmentVariableA("BX_LOG_FILE", log_path)) { DeleteFileA(log_path); return false; } created_temp_log = true; } const int64_t log_start_offset = query_file_size(log_path); bool ok = false; { const ScopedModule state_dll(load_bridge(L"api-ms-win-core-psm-appnotify-l1-1-0.dll")); const ScopedModule constrained_dll(load_bridge(L"api-ms-win-core-psm-appnotify-l1-1-1.dll")); if (state_dll && constrained_dll) { const auto register_state = lookup( state_dll.get(), "RegisterAppStateChangeNotification"); const auto unregister_state = lookup( state_dll.get(), "UnregisterAppStateChangeNotification"); const auto register_constrained = lookup( constrained_dll.get(), "RegisterAppConstrainedChangeNotification"); const auto unregister_constrained = lookup( constrained_dll.get(), "UnregisterAppConstrainedChangeNotification"); if (register_state && unregister_state && register_constrained && unregister_constrained) { PVOID token = reinterpret_cast(1); PVOID token2 = reinterpret_cast(1); const bool args_ok = register_state(nullptr, nullptr, &token) == ERROR_INVALID_PARAMETER && !token && register_state(notification_callback, nullptr, nullptr) == ERROR_INVALID_PARAMETER && register_constrained(nullptr, nullptr, &token2) == ERROR_INVALID_PARAMETER && !token2 && register_constrained(notification_callback, nullptr, nullptr) == ERROR_INVALID_PARAMETER; constexpr size_t kThreads = 4; constexpr size_t kRegistrationsPerThread = 16; constexpr size_t kPerFamily = kThreads * kRegistrationsPerThread; struct Tokens { PVOID state{}; PVOID constrained{}; }; std::array, kThreads> tokens{}; std::array workers; std::atomic success{args_ok}; for (size_t i = 0; i < workers.size(); ++i) { workers[i] = std::thread([&, i] { for (auto& entry : tokens[i]) { const auto state_status = register_state(notification_callback, &entry, &entry.state); const auto constrained_status = register_constrained(notification_callback, &entry, &entry.constrained); if (state_status != ERROR_SUCCESS || constrained_status != ERROR_SUCCESS || !entry.state || !entry.constrained) { success.store(false); } // Cross-family unregister calls must log foreign_token and leave live tokens intact. unregister_constrained(entry.state); unregister_state(entry.constrained); // Valid unregister followed by duplicate unregister on each family. unregister_state(entry.state); unregister_state(entry.state); unregister_constrained(entry.constrained); unregister_constrained(entry.constrained); } }); } for (auto& worker : workers) { worker.join(); } // Null and arbitrary invalid tokens must classify as unknown_token, not foreign_token. unregister_state(nullptr); unregister_constrained(reinterpret_cast(0x1234)); std::unordered_set seen; bool unique_ok = true; for (const auto& entries : tokens) { for (const auto& entry : entries) { if (!seen.insert(entry.state).second || !seen.insert(entry.constrained).second) { unique_ok = false; } } } PsmLogCounts counts{}; const bool log_read_ok = count_psm_log_events(log_path, log_start_offset, counts); const bool counts_ok = log_read_ok && counts.state_registered == kPerFamily && counts.constrained_registered == kPerFamily && counts.state_unregistered == kPerFamily && counts.state_foreign == kPerFamily && counts.state_unknown == kPerFamily + 1 && counts.constrained_unregistered == kPerFamily && counts.constrained_foreign == kPerFamily && counts.constrained_unknown == kPerFamily + 1; if (log_read_ok && !counts_ok) { std::fprintf( stderr, "FAIL: PSM log count mismatch: state(reg=%zu unreg=%zu foreign=%zu unknown=%zu) " "constrained(reg=%zu unreg=%zu foreign=%zu unknown=%zu)\n", counts.state_registered, counts.state_unregistered, counts.state_foreign, counts.state_unknown, counts.constrained_registered, counts.constrained_unregistered, counts.constrained_foreign, counts.constrained_unknown); } ok = success.load() && unique_ok && !g_callback_called.load() && counts_ok; } } } if (created_temp_log) { DeleteFileA(log_path); } return ok; } } // namespace int main() { if (!test_window()) { std::fprintf(stderr, "FAIL: Win32 bridge window or message pump (error %lu)\n", GetLastError()); return 1; } if (!test_psm()) { std::fprintf(stderr, "FAIL: PSM bridge registration lifecycle\n"); return 2; } std::puts("PASS: test_win32_bridge (hidden window, message pump, 128 PSM registrations, per-event log verified)"); return 0; }