1#include "../Logger.h"
2#include "../Networking.h"
3#include "../DiagnosticUploadBudget.h"
4#include <cstdio>
5#include <filesystem>
6#include <stdexcept>
7#include <string>
8#include <vector>
9#include <fstream>
10#include <csignal>
11#include <crtdbg.h>
12#include <intrin.h>
13
14namespace
15{
16 struct Send { bool trace; std::string text; int level; std::string stack; };
17 std::vector<Send> sends;
18 int flushes = 0;
19 int closes = 0;
20 bool acceptReports = true;
21 std::uint32_t nextReceipt = 1;
22 std::uint32_t lastReceipt = 0;
23 void Check(bool value, const char* message)
24 {
25 if (!value) throw std::runtime_error(message);
26 }
27}
28
29#include "BiometerDiagnosticsTests.h"
30
31
32RakNet::SystemAddress::SystemAddress() {}
35{
36 if (!acceptReports) return false;
38 return true;
39}
41{
42 sends.push_back({ true, contents, -1, "" });
43 lastReceipt = requestReceipt ? nextReceipt++ : 0;
44 return requestReceipt ? lastReceipt : 1;
45}
49{
56}
57
58static DWORD WINAPI AccessViolation(
void*)
59{
60 volatile int* address = nullptr;
61 *address = 42;
62 return 0;
63}
64
65static void NativeBoundary()
66{
67 __try { AccessViolation(nullptr); }
69 {
70 TerminateProcess(GetCurrentProcess(), GetExceptionCode());
71 }
72}
73
74static int CrashChild(const std::string& mode)
75{
76 SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS);
77 _CrtSetReportMode(_CRT_ASSERT, 0);
78 _CrtSetReportMode(_CRT_ERROR, 0);
80 logger.
Log(
"Context saved before deliberate test fault");
81 for (int i = 0; i < 70; ++i)
82 logger.
AddToCallStack((
"test breadcrumb " + std::to_string(i)).c_str());
83 if (mode == "fastfail") __fastfail(FAST_FAIL_FATAL_APP_EXIT);
84 if (mode == "killed") TerminateProcess(GetCurrentProcess(), 77);
85 if (mode == "native") AccessViolation(nullptr);
86 if (mode == "boundary") NativeBoundary();
87 if (mode == "worker")
88 {
89 HANDLE thread = CreateThread(nullptr, 0, AccessViolation, nullptr, 0, nullptr);
90 WaitForSingleObject(thread, INFINITE);
91 }
92 if (mode == "terminate") std::terminate();
93 if (mode == "cpp") throw std::runtime_error("Unhandled child exception");
94 if (mode == "abort") std::abort();
95 if (mode == "invalid")
96 {
97 char shortBuffer[2];
98 strcpy_s(shortBuffer, "Deliberately oversized input");
99 }
100 if (mode == "outofmemory")
101 {
102 logger.
RecordCrash(
"Texture allocation failed",
static_cast<unsigned long>(E_OUTOFMEMORY));
103 TerminateProcess(GetCurrentProcess(), static_cast<UINT>(E_OUTOFMEMORY));
104 }
105 return 0;
106}
107
108static void CheckCrashAndReplay(const std::filesystem::path& executable,
109 const std::filesystem::path& root, const char* mode)
110{
111 const auto directory =
root / mode;
112 std::filesystem::create_directories(directory);
113 std::string command = "\"" + executable.string() + "\" " + mode;
114 STARTUPINFOA startup = {};
115 startup.cb = sizeof startup;
116 PROCESS_INFORMATION process = {};
117 Check(CreateProcessA(nullptr, command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW,
118 nullptr, directory.string().c_str(), &startup, &process) != FALSE, "Could not launch fault-test child");
119 const DWORD wait = WaitForSingleObject(process.hProcess, 15000);
120 if (wait != WAIT_OBJECT_0) TerminateProcess(process.hProcess, 1);
122 GetExitCodeProcess(process.hProcess, &exitCode);
123 CloseHandle(process.hThread);
124 CloseHandle(process.hProcess);
125 Check(wait == WAIT_OBJECT_0 && exitCode != 0, "Fault-test child hung or did not fail");
126 std::filesystem::path marker;
127 for (const auto& entry : std::filesystem::directory_iterator(directory))
128 if (entry.path().extension() == ".pending" && entry.file_size() > 0) marker = entry.path();
129 Check(!marker.empty(), "Crash did not leave a pending report");
130 auto trace = marker;
131 trace.replace_extension();
132 std::ifstream file(trace, std::ios::binary);
133 const std::string contents((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
134 const bool bypassedHandler = std::string(mode) == "fastfail" || std::string(mode) == "killed";
135 if (bypassedHandler)
136 Check(contents.find("Context saved before deliberate test fault") != std::string::npos &&
137 contents.find("FATAL:") == std::string::npos, "Bypass test unexpectedly ran a crash handler");
138 else Check(contents.find("FATAL:") != std::string::npos &&
139 contents.find("Simulated call stack") != std::string::npos &&
140 contents.find(" --> test breadcrumb 69\r\n") != std::string::npos &&
141 contents.find(" --> test breadcrumb 6\r\n") != std::string::npos &&
142 contents.find(" --> test breadcrumb 5\r\n") == std::string::npos,
143 "Crash trace omitted fatal details or the complete breadcrumb ring");
144 if (!bypassedHandler)
145 Check(contents.find("Memory bytes: virtual total=") != std::string::npos &&
146 contents.find("Process memory bytes: private=") != std::string::npos,
147 "Crash trace omitted process/address-space memory diagnostics");
148 if (std::string(mode) == "outofmemory")
149 Check(contents.find("0x8007000e") != std::string::npos,
150 "Out-of-memory HRESULT was not preserved");
151 if (std::string(mode) == "native" || std::string(mode) == "boundary" || std::string(mode) == "worker")
152 Check(contents.find("0xc0000005") != std::string::npos &&
153 contents.find("Registers: EIP=") != std::string::npos &&
154 contents.find("Fault module:") != std::string::npos, "Native context was lost");
155
156
157 HANDLE traceHandle = CreateFileA(trace.string().c_str(), FILE_WRITE_ATTRIBUTES,
158 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
159 FILETIME oldTime = { 0, 1 };
160 Check(traceHandle != INVALID_HANDLE_VALUE && SetFileTime(traceHandle, &oldTime, nullptr, nullptr), "Could not age test trace");
161 CloseHandle(traceHandle);
162 std::filesystem::current_path(directory);
163 {
167 Check(std::filesystem::exists(trace), "Retention deleted an unsent crash trace");
168 sends.clear();
169 acceptReports = false;
171 Check(sends.empty() && std::filesystem::exists(marker), "Failed send discarded pending crash");
172 acceptReports = true;
174 Check(sends.size() == 2 && !sends[0].trace && sends[0].level ==
Logger::Fatal && sends[1].trace &&
175 (bypassedHandler ? sends[0].text.find("Unclean client exit; no exception captured") != std::string::npos :
176 sends[0].stack.find("test breadcrumb 69") != std::string::npos) && sends[1].text == contents,
177 "Restart did not send the saved fatal packet and exact trace in order");
178 Check(std::filesystem::exists(marker), "Queuing a send prematurely deleted the marker");
179 const auto oldReceipt = lastReceipt;
182 Check(std::filesystem::exists(marker), "Stale ACK deleted pending report");
184 Check(!std::filesystem::exists(marker) && std::filesystem::exists(trace),
185 "ACK did not clear marker while preserving local trace");
187 }
188 std::filesystem::current_path(root);
189 printf("PASS: %s fault, durable diagnostics, retention, retry, and ACK handling.\n", mode);
190}
191
192int main(
int argc,
char** argv)
193{
194 if (argc == 2) return CrashChild(argv[1]);
195 try
196 {
198 Check(budget.
CanSend(100),
"First diagnostic was delayed");
200 Check(!budget.
CanSend(120100),
"Unacknowledged trace allowed another allocation");
202 Check(!budget.
CanSend(120100),
"Unrelated ACK released the upload budget");
204 Check(!budget.
CanSend(60099) && budget.
CanSend(60100),
"ACK bypassed the cooldown or cooldown never expired");
205 budget.
Sent(60100, 0);
206 Check(!budget.
CanSend(60101) && budget.
CanSend(120100),
"Failed trace queue did not get a bounded retry");
207 budget.
Sent(120100, 8);
209 Check(budget.
CanSend(120101),
"Reconnect remained blocked by a lost connection's receipt");
210 budget.
Sent(120101, 9);
212 Check(!budget.
CanSend(240101),
"Stale receipt released the new connection's trace");
213 puts("PASS: Routine upload cooldown, outstanding ACK, failed queue, and reconnect policy.");
214 const auto executable = std::filesystem::absolute(argv[0]);
215
216 const auto testDirectory = std::filesystem::absolute("trace-test-data-" + std::to_string(GetCurrentProcessId()));
217 std::filesystem::create_directories(testDirectory);
218 std::filesystem::current_path(testDirectory);
219 RunBiometerDiagnosticTests();
220 {
226 auto sample = HealthyBiometerSample();
227 monitor.
Observe(sample, 0, emit);
228 sample.current = sample.integrated = -14449059;
229 monitor.
Observe(sample, 100, emit);
230 Check(sends.size() == 2 && !sends[0].trace && sends[0].level ==
Logger::Error && sends[1].trace &&
231 sends[0].text.find("BIOMETER cause=invalid-result-bpm") == 0,
232 "Biometer fault did not send a nonfatal error followed by its trace");
233 Check(sends[1].text.find("BIOMETER sample") != std::string::npos &&
234 sends[1].text.find("current=-14449059 ") != std::string::npos &&
235 sends[1].text.find("g=(0,1,0)") != std::string::npos,
236 "Server trace omitted the biometer calculation evidence");
237 for (
unsigned frame = 101; frame < 300; ++frame) monitor.
Observe(sample, frame, emit);
238 Check(sends.size() == 2 && flushes == 0 && closes == 0,
239 "Biometer reporting spammed uploads, blocked rendering, or disconnected the game");
240 }
241 sends.clear();
242 puts("PASS: Biometer fault uses the real Logger error/trace forwarding path without blocking or flooding.");
243 {
247 Check(sends.empty(), "Logging before networking initialization attempted a send");
249 acceptReports = false;
251 Check(sends.empty(), "Disconnected error attempted a trace upload");
252 acceptReports = true;
253 logger.
Log(
"Context before error");
255 Check(sends.size() == 2 && !sends[0].trace && sends[0].level ==
Logger::Error && sends[1].trace,
256 "Error did not send a report followed by a trace file");
257 Check(sends[1].text.find("Context before error") != std::string::npos &&
258 sends[1].text.find("ERROR: First recoverable error") != std::string::npos,
259 "Trace omitted prior context or the triggering error");
261 "Recoverable error waited for delivery, closed networking, or lost severity");
263 for (int i = 0; i < 1477; ++i)
264 logger.
Log((
"Repeated packet error " + std::to_string(i)).c_str(),
Logger::Error);
265 Check(sends.size() == 2 && lastReceipt != 0,
266 "Repeated errors queued more full traces while a trace awaited acknowledgment");
269 Check(sends.size() == 2, "Fast ACK permitted a burst of full-trace uploads");
272 Check(sends.size() == 2, "Info or Warning unexpectedly uploaded a trace");
274 Check(sends.size() == 3 && !sends[2].trace && sends[2].level ==
Logger::Debug,
275 "Debug report behavior changed");
277 Check(sends.size() == 4 && sends[3].trace && flushes == 1,
278 "Explicit/fatal trace upload no longer waits by default");
279 Check(sends[3].text.find("Second recoverable error") != std::string::npos &&
280 sends[3].text.find("Repeated packet error 1476") != std::string::npos &&
281 sends[3].text.find("Error immediately after ACK") != std::string::npos,
282 "Throttling lost errors from the local trace");
283 const std::string longMessage(8192, 'x');
286 Check(sends.back().trace && sends.back().text.find(longMessage) != std::string::npos,
287 "Long error message was lost or triggered CRT termination");
290 Check(sends.back().trace &&
291 sends.back().text.find("Geometry allocation failed (0x8007000e -") != std::string::npos &&
292 sends.back().text.find("Memory bytes: processQuery=ok private=") != std::string::npos &&
293 sends.back().text.find("largestFreeBlock=") != std::string::npos &&
294 sends.back().text.find("GPUlocalQuery=0x80004002") != std::string::npos,
295 "Recoverable OOM omitted memory evidence or treated an absent GPU query as success");
296 }
297 puts("PASS: Bounded error/trace pairs, all local occurrences, explicit uploads, and severity behavior.");
298 for (const auto& entry : std::filesystem::directory_iterator(testDirectory))
299 Check(entry.path().extension() != ".pending", "Normal shutdown left a crash marker");
300
301
302 {
303 const auto legacyTrace = testDirectory / "trace_legacy.log";
304 const auto legacyMarker = testDirectory / "trace_legacy.log.pending";
305 { std::ofstream trace(legacyTrace); trace << "Last activity before abrupt exit"; }
306 { std::ofstream marker(legacyMarker); }
307 { std::ofstream trace("trace_live.log"); trace << "A second client is still running"; }
308 HANDLE live = CreateFileA("trace_live.log.pending", GENERIC_WRITE, FILE_SHARE_READ,
309 nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr);
310 Check(live != INVALID_HANDLE_VALUE, "Could not create live marker");
314 sends.clear();
316 Check(sends.size() == 2 && sends[0].text.find("Unclean client exit") != std::string::npos &&
317 sends[1].text == "Last activity before abrupt exit", "Legacy unclean exit not recovered");
319 Check(!std::filesystem::exists(legacyMarker), "Legacy marker not acknowledged");
321 CloseHandle(live);
322 DeleteFileA("trace_live.log.pending");
323 DeleteFileA("trace_live.log");
324 }
325 for (const char* mode : { "native", "boundary", "worker", "terminate", "cpp", "abort", "invalid", "fastfail", "killed", "outofmemory" })
326 CheckCrashAndReplay(executable, testDirectory, mode);
327 return 0;
328 }
329 catch (const std::exception& error)
330 {
331 fprintf(stderr, "FAIL: %s\n", error.what());
332 return 1;
333 }
334}
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
SCRIPT_CONTROL SCRIPT_STATE const void DWORD
void Observe(const Sample &sample, std::uint64_t now, Emit emit)
void Sent(std::uint64_t now, std::uint32_t receipt)
void Confirm(std::uint32_t receipt)
bool CanSend(std::uint64_t now) const
void Log(const char *msg, Level level=Info, int errorCode=0)
void AddToCallStack(const char *msg)
void SetNetworkingPointer(Networking *prmNetworking)
static long __stdcall HandleNativeException(struct _EXCEPTION_POINTERS *exception)
void RecordCrash(const char *reason, unsigned long code=0, struct _EXCEPTION_POINTERS *exception=nullptr) noexcept
void SendPendingCrashReports()
void SendTraceFile(bool waitForDelivery=true) const
void ConfirmTraceDelivery(std::uint32_t receipt)
std::uint32_t SendTraceFile(const char *fileContents, bool requestReceipt=false) const
bool SendErrorReport(SErrorPacket *pData) const
const wchar_t * ErrorString(HRESULT code)
HRESULT ClientToggleFullscreen()