Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : *
3 : * Permission is hereby granted, free of charge, to any person obtaining
4 : * a copy of this software and associated documentation files (the
5 : * "Software"), to deal in the Software without restriction, including
6 : * without limitation the rights to use, copy, modify, merge, publish,
7 : * distribute, sublicense, and/or sell copies of the Software, and to
8 : * permit persons to whom the Software is furnished to do so, subject to
9 : * the following conditions:
10 : *
11 : * The above copyright notice and this permission notice shall be included
12 : * in all copies or substantial portions of the Software.
13 : *
14 : * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 : * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 : * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 : * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18 : * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19 : * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20 : * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 : */
22 :
23 : #include "precompiled.h"
24 :
25 : #include "debug.h"
26 :
27 : #include "lib/alignment.h"
28 : #include "lib/app_hooks.h"
29 : #include "lib/fnv_hash.h"
30 : #include "lib/os_path.h"
31 : #include "lib/path.h"
32 : #include "lib/secure_crt.h"
33 : #include "lib/sysdep/sysdep.h"
34 : #include "lib/utf8.h"
35 :
36 : #include <algorithm>
37 : #include <cerrno>
38 : #include <cstdarg>
39 : #include <cstdio>
40 : #include <cstdlib>
41 : #include <cstring>
42 : #include <cwchar>
43 : #include <string>
44 : #include <utility>
45 :
46 : namespace
47 : {
48 :
49 : // (NB: this may appear obscene, but deep stack traces have been
50 : // observed to take up > 256 KiB)
51 : constexpr std::size_t MESSAGE_SIZE = 512 * KiB / sizeof(wchar_t);
52 : wchar_t g_MessageBuffer[MESSAGE_SIZE];
53 :
54 : } // anonymous namespace
55 :
56 : static const StatusDefinition debugStatusDefinitions[] = {
57 : { ERR::SYM_NO_STACK_FRAMES_FOUND, L"No stack frames found" },
58 : { ERR::SYM_UNRETRIEVABLE_STATIC, L"Value unretrievable (stored in external module)" },
59 : { ERR::SYM_UNRETRIEVABLE, L"Value unretrievable" },
60 : { ERR::SYM_TYPE_INFO_UNAVAILABLE, L"Error getting type_info" },
61 : { ERR::SYM_INTERNAL_ERROR, L"Exception raised while processing a symbol" },
62 : { ERR::SYM_UNSUPPORTED, L"Symbol type not (fully) supported" },
63 : { ERR::SYM_CHILD_NOT_FOUND, L"Symbol does not have the given child" },
64 : { ERR::SYM_NESTING_LIMIT, L"Symbol nesting too deep or infinite recursion" },
65 : { ERR::SYM_SINGLE_SYMBOL_LIMIT, L"Symbol has produced too much output" },
66 : { INFO::SYM_SUPPRESS_OUTPUT, L"Symbol was suppressed" }
67 : };
68 : STATUS_ADD_DEFINITIONS(debugStatusDefinitions);
69 :
70 : #undef debug_printf // allowing #defining it out
71 0 : void debug_printf(const char* fmt, ...)
72 : {
73 0 : char buf[16384];
74 :
75 0 : va_list ap;
76 0 : va_start(ap, fmt);
77 0 : const int numChars = vsprintf_s(buf, ARRAY_SIZE(buf), fmt, ap);
78 0 : if (numChars < 0)
79 0 : debug_break(); // poor man's assert - avoid infinite loop because ENSURE also uses debug_printf
80 0 : va_end(ap);
81 :
82 0 : debug_puts(buf);
83 0 : }
84 :
85 : //-----------------------------------------------------------------------------
86 :
87 0 : Status debug_WriteCrashlog(const wchar_t* text)
88 : {
89 : // (avoid infinite recursion and/or reentering this function if it
90 : // fails/reports an error)
91 0 : enum State
92 : {
93 : IDLE,
94 : BUSY,
95 : FAILED
96 : };
97 :
98 0 : static std::atomic<State> state{ IDLE };
99 :
100 0 : State initial{ IDLE };
101 0 : if(!state.compare_exchange_strong(initial, BUSY))
102 : return ERR::REENTERED; // NOWARN
103 :
104 0 : OsPath pathname = ah_get_log_dir()/"crashlog.txt";
105 0 : FILE* f = sys_OpenFile(pathname, "w");
106 0 : if(!f)
107 : {
108 0 : state = FAILED; // must come before DEBUG_DISPLAY_ERROR
109 0 : DEBUG_DISPLAY_ERROR(L"Unable to open crashlog.txt for writing (please ensure the log directory is writable)");
110 0 : return ERR::FAIL; // NOWARN (the above text is more helpful than a generic error code)
111 : }
112 :
113 0 : fputwc(0xFEFF, f); // BOM
114 0 : fwprintf(f, L"%ls\n", text);
115 0 : fwprintf(f, L"\n\n====================================\n\n");
116 :
117 : // allow user to bundle whatever information they want
118 0 : ah_bundle_logs(f);
119 :
120 0 : fclose(f);
121 0 : state = IDLE;
122 0 : return INFO::OK;
123 0 : }
124 :
125 :
126 : //-----------------------------------------------------------------------------
127 : // error message
128 : //-----------------------------------------------------------------------------
129 :
130 :
131 : // a stream with printf-style varargs and the possibility of
132 : // writing directly to the output buffer.
133 : class PrintfWriter
134 : {
135 : public:
136 0 : PrintfWriter(wchar_t* buf, size_t maxChars)
137 0 : : m_pos(buf), m_charsLeft(maxChars)
138 : {
139 : }
140 :
141 0 : bool operator()(const wchar_t* fmt, ...) WPRINTF_ARGS(2)
142 : {
143 0 : va_list ap;
144 0 : va_start(ap, fmt);
145 0 : const int len = vswprintf(m_pos, m_charsLeft, fmt, ap);
146 0 : va_end(ap);
147 0 : if(len < 0)
148 : return false;
149 0 : m_pos += len;
150 0 : m_charsLeft -= len;
151 0 : return true;
152 : }
153 :
154 0 : wchar_t* Position() const
155 : {
156 0 : return m_pos;
157 : }
158 :
159 0 : size_t CharsLeft() const
160 : {
161 0 : return m_charsLeft;
162 : }
163 :
164 0 : void CountAddedChars()
165 : {
166 0 : const size_t len = wcslen(m_pos);
167 0 : m_pos += len;
168 0 : m_charsLeft -= len;
169 0 : }
170 :
171 : private:
172 : wchar_t* m_pos;
173 : size_t m_charsLeft;
174 : };
175 :
176 :
177 : // split out of debug_DisplayError because it's used by the self-test.
178 0 : const wchar_t* debug_BuildErrorMessage(
179 : const wchar_t* description,
180 : const wchar_t* filename, int line, const char* func,
181 : void* context, const wchar_t* lastFuncToSkip)
182 : {
183 : // retrieve errno (might be relevant) before doing anything else
184 : // that might overwrite it.
185 0 : wchar_t description_buf[100] = L"?";
186 0 : wchar_t os_error[100] = L"?";
187 0 : Status errno_equiv = StatusFromErrno(); // NOWARN
188 0 : if(errno_equiv != ERR::FAIL) // meaningful translation
189 0 : StatusDescription(errno_equiv, description_buf, ARRAY_SIZE(description_buf));
190 0 : sys_StatusDescription(0, os_error, ARRAY_SIZE(os_error));
191 :
192 0 : PrintfWriter writer(g_MessageBuffer, MESSAGE_SIZE);
193 :
194 : // header
195 0 : if(!writer(
196 : L"%ls\r\n"
197 : L"Location: %ls:%d (%hs)\r\n"
198 : L"\r\n"
199 : L"Call stack:\r\n"
200 : L"\r\n",
201 : description, filename, line, func
202 : ))
203 : {
204 0 : fail:
205 0 : return L"(error while formatting error message)";
206 : }
207 :
208 : // append stack trace
209 0 : Status ret = debug_DumpStack(writer.Position(), writer.CharsLeft(), context, lastFuncToSkip);
210 0 : if(ret == ERR::REENTERED)
211 : {
212 0 : if(!writer(
213 : L"While generating an error report, we encountered a second "
214 : L"problem. Please be sure to report both this and the subsequent "
215 : L"error messages."
216 : ))
217 0 : goto fail;
218 : }
219 0 : else if(ret != INFO::OK)
220 : {
221 0 : wchar_t error_buf[100] = {'?'};
222 0 : if(!writer(
223 : L"(error while dumping stack: %ls)",
224 : StatusDescription(ret, error_buf, ARRAY_SIZE(error_buf))
225 : ))
226 0 : goto fail;
227 : }
228 : else // success
229 : {
230 0 : writer.CountAddedChars();
231 : }
232 :
233 : // append errno
234 0 : if(!writer(
235 : L"\r\n"
236 : L"errno = %d (%ls)\r\n"
237 : L"OS error = %ls\r\n",
238 0 : errno, description_buf, os_error
239 : ))
240 0 : goto fail;
241 :
242 : return g_MessageBuffer;
243 : }
244 :
245 :
246 : //-----------------------------------------------------------------------------
247 : // display error messages
248 : //-----------------------------------------------------------------------------
249 :
250 : // translates and displays the given strings in a dialog.
251 : // this is typically only used when debug_DisplayError has failed or
252 : // is unavailable because that function is much more capable.
253 : // implemented via sys_display_msg; see documentation there.
254 0 : void debug_DisplayMessage(const wchar_t* caption, const wchar_t* msg)
255 : {
256 0 : sys_display_msg(caption, msg);
257 0 : }
258 :
259 :
260 : // when an error has come up and user clicks Exit, we don't want any further
261 : // errors (e.g. caused by atexit handlers) to come up, possibly causing an
262 : // infinite loop. hiding errors isn't good, but we assume that whoever clicked
263 : // exit really doesn't want to see any more messages.
264 : static std::atomic<bool> isExiting{ false };
265 :
266 : // this logic is applicable to any type of error. special cases such as
267 : // suppressing certain expected WARN_ERRs are done there.
268 0 : static bool ShouldSuppressError(std::atomic<bool>* suppress)
269 : {
270 0 : if(isExiting)
271 : return true;
272 :
273 0 : if(!suppress)
274 : return false;
275 :
276 0 : if(*suppress)
277 : return true;
278 :
279 : return false;
280 : }
281 :
282 0 : static ErrorReactionInternal CallDisplayError(const wchar_t* text, size_t flags)
283 : {
284 : // first try app hook implementation
285 0 : ErrorReactionInternal er = ah_display_error(text, flags);
286 : // .. it's only a stub: default to normal implementation
287 0 : if(er == ERI_NOT_IMPLEMENTED)
288 0 : er = sys_display_error(text, flags);
289 :
290 0 : return er;
291 : }
292 :
293 0 : static ErrorReaction PerformErrorReaction(ErrorReactionInternal er, size_t flags, std::atomic<bool>* suppress)
294 : {
295 0 : const bool shouldHandleBreak = (flags & DE_MANUAL_BREAK) == 0;
296 :
297 0 : switch(er)
298 : {
299 : case ERI_CONTINUE:
300 : return ER_CONTINUE;
301 :
302 0 : case ERI_BREAK:
303 : // handle "break" request unless the caller wants to (doing so here
304 : // instead of within the dlgproc yields a correct call stack)
305 0 : if(shouldHandleBreak)
306 : {
307 0 : debug_break();
308 0 : return ER_CONTINUE;
309 : }
310 : else
311 : return ER_BREAK;
312 :
313 0 : case ERI_SUPPRESS:
314 0 : {
315 0 : bool initialSuppress{ false };
316 0 : (void)suppress->compare_exchange_strong(initialSuppress, true);
317 0 : return ER_CONTINUE;
318 : }
319 0 : case ERI_EXIT:
320 0 : isExiting = true; // see declaration
321 :
322 0 : exit(EXIT_FAILURE);
323 :
324 0 : case ERI_NOT_IMPLEMENTED:
325 0 : default:
326 0 : debug_break(); // not expected to be reached
327 0 : return ER_CONTINUE;
328 : }
329 : }
330 :
331 0 : ErrorReaction debug_DisplayError(const wchar_t* description,
332 : size_t flags, void* context, const wchar_t* lastFuncToSkip,
333 : const wchar_t* pathname, int line, const char* func,
334 : std::atomic<bool>* suppress)
335 : {
336 : // "suppressing" this error means doing nothing and returning ER_CONTINUE.
337 0 : if(ShouldSuppressError(suppress))
338 : return ER_CONTINUE;
339 :
340 : // fix up params
341 : // .. caller supports a suppress flag; set the corresponding flag so that
342 : // the error display implementation enables the Suppress option.
343 0 : if(suppress)
344 0 : flags |= DE_ALLOW_SUPPRESS;
345 :
346 0 : if(flags & DE_NO_DEBUG_INFO)
347 : {
348 : // in non-debug-info mode, simply display the given description
349 : // and then return immediately
350 0 : ErrorReactionInternal er = CallDisplayError(description, flags);
351 0 : return PerformErrorReaction(er, flags, suppress);
352 : }
353 :
354 : // .. deal with incomplete file/line info
355 0 : if(!pathname || pathname[0] == '\0')
356 0 : pathname = L"unknown";
357 0 : if(line <= 0)
358 : line = 0;
359 0 : if(!func || func[0] == '\0')
360 0 : func = "?";
361 : // .. _FILE__ evaluates to the full path (albeit without drive letter)
362 : // which is rather long. we only display the base name for clarity.
363 0 : const wchar_t* filename = path_name_only(pathname);
364 :
365 : // display in output window; double-click will navigate to error location.
366 0 : const wchar_t* text = debug_BuildErrorMessage(description, filename, line, func, context, lastFuncToSkip);
367 :
368 0 : (void)debug_WriteCrashlog(text);
369 0 : ErrorReactionInternal er = CallDisplayError(text, flags);
370 :
371 : // TODO: use utf8 conversion without internal allocations.
372 0 : debug_printf("%s(%d): %s\n", utf8_from_wstring(filename).c_str(), line, utf8_from_wstring(description).c_str());
373 :
374 : // note: debug_break-ing here to make sure the app doesn't continue
375 : // running is no longer necessary. debug_DisplayError now determines our
376 : // window handle and is modal.
377 :
378 0 : return PerformErrorReaction(er, flags, suppress);
379 : }
380 :
381 :
382 : // is errorToSkip valid? (also guarantees mutual exclusion)
383 : enum SkipStatus
384 : {
385 : INVALID, VALID, BUSY
386 : };
387 : static std::atomic<SkipStatus> skipStatus{ INVALID };
388 : static Status errorToSkip;
389 : static size_t numSkipped;
390 :
391 9 : void debug_SkipErrors(Status err)
392 : {
393 9 : SkipStatus expected{ INVALID };
394 9 : if(skipStatus.compare_exchange_strong(expected, BUSY))
395 : {
396 9 : errorToSkip = err;
397 9 : numSkipped = 0;
398 9 : skipStatus = VALID; // linearization point
399 : }
400 : else
401 0 : DEBUG_WARN_ERR(ERR::REENTERED);
402 9 : }
403 :
404 9 : size_t debug_StopSkippingErrors()
405 : {
406 9 : SkipStatus expected{ VALID };
407 9 : if(skipStatus.compare_exchange_strong(expected, BUSY))
408 : {
409 9 : const size_t ret = numSkipped;
410 9 : skipStatus = INVALID; // linearization point
411 9 : return ret;
412 : }
413 : else
414 : {
415 0 : DEBUG_WARN_ERR(ERR::REENTERED);
416 0 : return 0;
417 : }
418 : }
419 :
420 29 : static bool ShouldSkipError(Status err)
421 : {
422 29 : SkipStatus expected{ VALID };
423 29 : if(skipStatus.compare_exchange_strong(expected, BUSY))
424 : {
425 29 : numSkipped++;
426 29 : const bool ret = (err == errorToSkip);
427 29 : skipStatus = VALID;
428 29 : return ret;
429 : }
430 : return false;
431 : }
432 :
433 29 : ErrorReaction debug_OnError(Status err, std::atomic<bool>* suppress, const wchar_t* file, int line, const char* func)
434 : {
435 29 : CACHE_ALIGNED(std::uint8_t) context[DEBUG_CONTEXT_SIZE];
436 29 : (void)debug_CaptureContext(context);
437 :
438 29 : if(ShouldSkipError(err))
439 : return ER_CONTINUE;
440 :
441 0 : const wchar_t* lastFuncToSkip = L"debug_OnError";
442 0 : wchar_t buf[400];
443 0 : wchar_t err_buf[200]; StatusDescription(err, err_buf, ARRAY_SIZE(err_buf));
444 0 : swprintf_s(buf, ARRAY_SIZE(buf), L"Function call failed: return value was %lld (%ls)", (long long)err, err_buf);
445 0 : return debug_DisplayError(buf, DE_MANUAL_BREAK, context, lastFuncToSkip, file,line,func, suppress);
446 : }
447 :
448 0 : ErrorReaction debug_OnAssertionFailure(const wchar_t* expr, std::atomic<bool>* suppress, const wchar_t* file, int line, const char* func)
449 : {
450 0 : CACHE_ALIGNED(std::uint8_t) context[DEBUG_CONTEXT_SIZE];
451 0 : (void)debug_CaptureContext(context);
452 :
453 0 : const wchar_t* lastFuncToSkip = L"debug_OnAssertionFailure";
454 0 : wchar_t buf[400];
455 0 : swprintf_s(buf, ARRAY_SIZE(buf), L"Assertion failed: \"%ls\"", expr);
456 0 : return debug_DisplayError(buf, DE_MANUAL_BREAK, context, lastFuncToSkip, file,line,func, suppress);
457 : }
|