Pyrogenesis HEAD
Pyrogenesis, a RTS Engine
debug.h
Go to the documentation of this file.
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/*
24 * platform-independent debug support code.
25 */
26
27#ifndef INCLUDED_DEBUG
28#define INCLUDED_DEBUG
29
30// this module provides platform-independent debug facilities, useful for
31// diagnosing and reporting program errors.
32// - a symbol engine provides access to compiler-generated debug information and
33// can also give a stack trace including local variables;
34// - our more powerful assert() replacement gives a stack trace so
35// that the underlying problem becomes apparent;
36// - the output routines make for platform-independent logging and
37// crashlogs with "last-known activity" reporting.
38
39#include "lib/alignment.h"
40#include "lib/code_annotation.h"
41#include "lib/status.h"
42#include "lib/sysdep/compiler.h"
43
44#include <atomic>
45#include <cstddef>
46
47/**
48 * trigger a breakpoint when reached/"called".
49 * if defined as a macro, the debugger can break directly into the
50 * target function instead of one frame below it as with a conventional
51 * call-based implementation.
52 **/
53#if MSC_VERSION
54# define debug_break __debugbreak // intrinsic "function"
55#else
56extern void debug_break();
57#endif
58
59
60//-----------------------------------------------------------------------------
61// output
62//-----------------------------------------------------------------------------
63
64/**
65 * write a formatted string to the debug channel. implemented via debug_puts -
66 * see performance note there.
67 *
68 * @param fmt Format string and varargs; see printf.
69 **/
70void debug_printf(const char* fmt, ...) PRINTF_ARGS(1);
71
72
73/**
74 * translates and displays the given strings in a dialog.
75 * this is typically only used when debug_DisplayError has failed or
76 * is unavailable because that function is much more capable.
77 * implemented via sys_display_msg; see documentation there.
78 **/
79void debug_DisplayMessage(const wchar_t* caption, const wchar_t* msg);
80
81/// flags to customize debug_DisplayError behavior
83{
84 /**
85 * disallow the Continue button. used e.g. if an exception is fatal.
86 **/
88
89 /**
90 * enable the Suppress button. set automatically by debug_DisplayError if
91 * it receives a non-NULL suppress pointer. a flag is necessary because
92 * the sys_display_error interface doesn't get that pointer.
93 * rationale for automatic setting: this may prevent someone from
94 * forgetting to specify it, and disabling Suppress despite having
95 * passed a non-NULL pointer doesn't make much sense.
96 **/
98
99 /**
100 * do not trigger a breakpoint inside debug_DisplayError; caller
101 * will take care of this if ER_BREAK is returned. this is so that the
102 * debugger can jump directly into the offending function.
103 **/
105
106 /**
107 * display just the given message; do not add any information about the
108 * call stack, do not write crashlogs, etc.
109 */
112
113/**
114 * choices offered by the error dialog that are returned
115 * by debug_DisplayError.
116 **/
118{
119 /**
120 * ignore, continue as if nothing happened.
121 * note: value doesn't start at 0 because that is interpreted as a
122 * DialogBoxParam failure.
123 **/
125
126 /**
127 * trigger breakpoint, i.e. enter debugger.
128 * only returned if DE_MANUAL_BREAK was passed; otherwise,
129 * debug_DisplayError will trigger a breakpoint itself.
130 **/
133
134/**
135 * all choices offered by the error dialog. those not defined in
136 * ErrorReaction are acted upon by debug_DisplayError and
137 * never returned to callers.
138 * (this separation avoids enumerator-not-handled warnings)
139 **/
141{
144
145 /**
146 * ignore and do not report again.
147 * note: non-persistent; only applicable during this program run.
148 **/
150
151 /**
152 * exit the program immediately.
153 **/
155
156 /**
157 * special return value for the display_error app hook stub to indicate
158 * that it has done nothing and that the normal sys_display_error
159 * implementation should be called instead.
160 **/
163
164
165/**
166 * display an error dialog with a message and stack trace.
167 *
168 * @param description text to show.
169 * @param flags: see DebugDisplayErrorFlags.
170 * @param context, lastFuncToSkip: see debug_DumpStack.
171 * @param file, line, func: location of the error (typically passed as
172 * WIDEN(__FILE__), __LINE__, __func__ from a macro)
173 * @param suppress pointer to a caller-allocated flag that can be used to
174 * suppress this error. if NULL, this functionality is skipped and the
175 * "Suppress" dialog button will be disabled.
176 * note: this flag is read and written exclusively here; caller only
177 * provides the storage.
178 * @return ErrorReaction (user's choice: continue running or stop?)
179 **/
180ErrorReaction debug_DisplayError(const wchar_t* description, size_t flags, void* context, const wchar_t* lastFuncToSkip, const wchar_t* file, int line, const char* func, std::atomic<bool>* suppress);
181
182// simplified version for just displaying an error message
183#define DEBUG_DISPLAY_ERROR_IMPL(description, flags)\
184 do\
185 {\
186 CACHE_ALIGNED(std::uint8_t) context[DEBUG_CONTEXT_SIZE];\
187 (void)debug_CaptureContext(context);\
188 (void)debug_DisplayError(description, flags, context, L"debug_DisplayError", WIDEN(__FILE__), __LINE__, __func__, 0);\
189 }\
190 while(0)
191
192#define DEBUG_DISPLAY_ERROR(description) DEBUG_DISPLAY_ERROR_IMPL(description, 0)
193// disallow continue for the error.
194#define DEBUG_DISPLAY_FATAL_ERROR(description) DEBUG_DISPLAY_ERROR_IMPL(description, DE_NO_CONTINUE)
195
196/**
197 * write an error description and all logs into crashlog.txt
198 * (in unicode format).
199 *
200 * @param text description of the error (including stack trace);
201 * typically generated by debug_BuildErrorMessage.
202 *
203 * @return Status; ERR::REENTERED if reentered via recursion or
204 * multithreading (not allowed since an infinite loop may result).
205 **/
206Status debug_WriteCrashlog(const char* text);
207
208
209//-----------------------------------------------------------------------------
210// assertions
211//-----------------------------------------------------------------------------
212
213/**
214 * ensure the expression <expr> evaluates to non-zero. used to validate
215 * invariants in the program during development and thus gives a
216 * very helpful warning if something isn't going as expected.
217 * sprinkle these liberally throughout your code!
218 *
219 * to pass more information to users at runtime, you can write
220 * ENSURE(expression && "descriptive string").
221 **/
222#define ENSURE(expr)\
223 do\
224 {\
225 static std::atomic<bool> suppress__{ false };\
226 if(!(expr))\
227 {\
228 switch(debug_OnAssertionFailure(WIDEN(#expr), &suppress__, WIDEN(__FILE__), __LINE__, __func__))\
229 {\
230 case ER_CONTINUE:\
231 break;\
232 case ER_BREAK:\
233 default:\
234 debug_break();\
235 break;\
236 }\
237 }\
238 }\
239 while(0)
240
241/**
242 * same as ENSURE in debug mode, does nothing in release mode.
243 * (we don't override the `assert' macro because users may
244 * inadvertently include <assert.h> afterwards)
245 * (we do not provide an MFC-style VERIFY macro because the distinction
246 * between ENSURE and VERIFY is unclear. to always run code but only
247 * check for success in debug builds without raising unused-variable warnings,
248 * use [[maybe_unused]].)
249 **/
250#define ASSERT(expr) ENSURE(expr)
251#ifdef NDEBUG
252# undef ASSERT
253# define ASSERT(expr)
254#endif
255
256/**
257 * display the error dialog with the given text. this is less error-prone than
258 * ENSURE(0 && "text"). note that "conditional expression is constant" warnings
259 * are disabled anyway.
260 *
261 * if being able to suppress the warning is desirable (e.g. for self-tests),
262 * then use DEBUG_WARN_ERR instead.
263 **/
264#define debug_warn(expr) ENSURE(0 && (expr))
265
266/**
267 * display the error dialog with text corresponding to the given error code.
268 * used by WARN_RETURN_STATUS_IF_ERR et al., which wrap function calls and automatically
269 * raise warnings and return to the caller.
270 **/
271#define DEBUG_WARN_ERR(status)\
272 do\
273 {\
274 static std::atomic<bool> suppress__{ false };\
275 switch(debug_OnError(status, &suppress__, WIDEN(__FILE__), __LINE__, __func__))\
276 {\
277 case ER_CONTINUE:\
278 break;\
279 case ER_BREAK:\
280 default:\
281 debug_break();\
282 break;\
283 }\
284 }\
285 while(0)
286
287/**
288 * called when a ENSURE/ASSERT fails;
289 * notifies the user via debug_DisplayError.
290 *
291 * @param assert_expr the expression that failed; typically passed as
292 * \#expr in the assert macro.
293 * @param suppress see debug_DisplayError.
294 * @param file, line source file name and line number of the spot that failed
295 * @param func name of the function containing it
296 * @return ErrorReaction (user's choice: continue running or stop?)
297 **/
298ErrorReaction debug_OnAssertionFailure(const wchar_t* assert_expr, std::atomic<bool>* suppress, const wchar_t* file, int line, const char* func) ANALYZER_NORETURN;
299
300/**
301 * called when a DEBUG_WARN_ERR indicates an error occurred;
302 * notifies the user via debug_DisplayError.
303 *
304 * @param err Status value indicating the error that occurred
305 * @param suppress see debug_DisplayError.
306 * @param file, line source file name and line number of the spot that failed
307 * @param func name of the function containing it
308 * @return ErrorReaction (user's choice: continue running or stop?)
309 **/
310ErrorReaction debug_OnError(Status err, std::atomic<bool>* suppress, const wchar_t* file, int line, const char* func) ANALYZER_NORETURN;
311
312
313/**
314 * suppress (prevent from showing) the error dialog from subsequent
315 * debug_OnError for the given Status.
316 *
317 * rationale: for edge cases in some functions, warnings are raised in
318 * addition to returning an error code. self-tests deliberately trigger
319 * these cases and check for the latter but shouldn't cause the former.
320 * we therefore need to squelch them.
321 *
322 * @param err the Status to skip.
323 *
324 * note: only one concurrent skip request is allowed; call
325 * debug_StopSkippingErrors before the next debug_SkipErrors.
326 */
327void debug_SkipErrors(Status err);
328
329/**
330 * @return how many errors were skipped since the call to debug_SkipErrors()
331 **/
333
334
335//-----------------------------------------------------------------------------
336// symbol access
337//-----------------------------------------------------------------------------
338
339namespace ERR
340{
343 const Status SYM_UNRETRIEVABLE = -100402;
345 const Status SYM_INTERNAL_ERROR = -100404;
346 const Status SYM_UNSUPPORTED = -100405;
348 // this limit is to prevent infinite recursion.
349 const Status SYM_NESTING_LIMIT = -100407;
350 // this limit is to prevent large symbols (e.g. arrays or linked lists)
351 // from taking up all available output space.
353}
354
355namespace INFO
356{
357 // one of the dump_sym* functions decided not to output anything at
358 // all (e.g. for member functions in UDTs - we don't want those).
359 // therefore, skip any post-symbol formatting (e.g. ) as well.
361}
362
363
364/**
365 * Maximum number of characters (including null terminator) written to
366 * user's buffers by debug_ResolveSymbol.
367 **/
368static const size_t DEBUG_SYMBOL_CHARS = 1000;
369static const size_t DEBUG_FILE_CHARS = 100;
370
371/**
372 * read and return symbol information for the given address.
373 *
374 * NOTE: the PDB implementation is rather slow (~500 us).
375 *
376 * @param ptr_of_interest address of symbol (e.g. function, variable)
377 * @param sym_name optional out; holds at least DEBUG_SYMBOL_CHARS;
378 * receives symbol name returned via debug info.
379 * @param file optional out; holds at least DEBUG_FILE_CHARS;
380 * receives base name only (no path; see rationale in wdbg_sym) of
381 * source file containing the symbol.
382 * @param line optional out; receives source file line number of symbol.
383 *
384 * note: all of the output parameters are optional; we pass back as much
385 * information as is available and desired.
386 * @return Status; INFO::OK iff any information was successfully
387 * retrieved and stored.
388 **/
389Status debug_ResolveSymbol(void* ptr_of_interest, wchar_t* sym_name, wchar_t* file, int* line);
390
391static const size_t DEBUG_CONTEXT_SIZE = 2048; // Win32 CONTEXT is currently 1232 bytes
392
393/**
394 * @param context must point to an instance of the platform-specific type
395 * (e.g. CONTEXT) or CACHE_ALIGNED storage of DEBUG_CONTEXT_SIZE bytes.
396 **/
397Status debug_CaptureContext(void* context);
398
399
400/**
401 * write a complete stack trace (including values of local variables) into
402 * the specified buffer.
403 *
404 * @param buf Target buffer.
405 * @param maxChars Max chars of buffer (should be several thousand).
406 * @param context Platform-specific representation of execution state
407 * (e.g. Win32 CONTEXT). either specify an SEH exception's
408 * context record or use debug_CaptureContext to retrieve the current state.
409 * Rationale: intermediates such as debug_DisplayError change the
410 * context, so it should be captured as soon as possible.
411 * @param lastFuncToSkip Is used for omitting error-reporting functions like
412 * debug_OnAssertionFailure from the stack trace. It is either 0 (skip nothing) or
413 * a substring of a function's name (this allows platform-independent
414 * matching of stdcall-decorated names).
415 * Rationale: this is safer than specifying a fixed number of frames,
416 * which can be incorrect due to inlining.
417 * @return Status; ERR::REENTERED if reentered via recursion or
418 * multithreading (not allowed since static data is used).
419 **/
420Status debug_DumpStack(wchar_t* buf, size_t maxChars, void* context, const wchar_t* lastFuncToSkip);
421
422
423//-----------------------------------------------------------------------------
424// helper functions (used by implementation)
425//-----------------------------------------------------------------------------
426
427/**
428 * [system-dependent] write a string to the debug channel.
429 * this can be quite slow (~1 ms)! On Windows, it uses OutputDebugString
430 * (entails context switch), otherwise stdout+fflush (waits for IO).
431 **/
432void debug_puts(const char* text);
433
434/**
435 * return the caller of a certain function on the call stack.
436 *
437 * this function is useful for recording (partial) stack traces for
438 * memory allocation tracking, etc.
439 *
440 * @param context, lastFuncToSkip - see debug_DumpStack
441 * @return address of the caller
442 **/
443void* debug_GetCaller(void* context, const wchar_t* lastFuncToSkip);
444
445/**
446 * check if a pointer appears to be totally invalid.
447 *
448 * this check is not authoritative (the pointer may be "valid" but incorrect)
449 * but can be used to filter out obviously wrong values in a portable manner.
450 *
451 * @param p pointer
452 * @return 1 if totally bogus, otherwise 0.
453 **/
454int debug_IsPointerBogus(const void* p);
455
456/// does the given pointer appear to point to code?
457bool debug_IsCodePointer(void* p);
458
459/// does the given pointer appear to point to the stack?
460bool debug_IsStackPointer(void* p);
461
462
463/**
464 * inform the debugger of the current thread's name.
465 *
466 * (threads are easier to keep apart when they are identified by
467 * name rather than TID.)
468 **/
469void debug_SetThreadName(const char* name);
470
471/**
472 * build a string describing the given error.
473 *
474 * this is a helper function used by debug_DumpStack and is made available
475 * so that the self-test doesn't have to display the error dialog.
476 *
477 * @param description: general description of the problem.
478 * @param fn_only filename (no path) of source file that triggered the error.
479 * @param line, func: exact position of the error.
480 * @param context, lastFuncToSkip: see debug_DumpStack.
481 **/
482const wchar_t* debug_BuildErrorMessage(const wchar_t* description, const wchar_t* fn_only, int line, const char* func, void* context, const wchar_t* lastFuncToSkip);
483
484#endif // #ifndef INCLUDED_DEBUG
#define PRINTF_ARGS(fmtpos)
Definition: code_annotation.h:213
#define ANALYZER_NORETURN
mark a function as noreturn for static analyzer purposes.
Definition: code_annotation.h:76
Status debug_DumpStack(wchar_t *buf, size_t maxChars, void *context, const wchar_t *lastFuncToSkip)
write a complete stack trace (including values of local variables) into the specified buffer.
Definition: bdbg.cpp:52
const wchar_t * debug_BuildErrorMessage(const wchar_t *description, const wchar_t *fn_only, int line, const char *func, void *context, const wchar_t *lastFuncToSkip)
build a string describing the given error.
Definition: debug.cpp:178
ErrorReactionInternal
all choices offered by the error dialog.
Definition: debug.h:141
@ ERI_NOT_IMPLEMENTED
special return value for the display_error app hook stub to indicate that it has done nothing and tha...
Definition: debug.h:161
@ ERI_CONTINUE
Definition: debug.h:142
@ ERI_EXIT
exit the program immediately.
Definition: debug.h:154
@ ERI_SUPPRESS
ignore and do not report again.
Definition: debug.h:149
@ ERI_BREAK
Definition: debug.h:143
void debug_printf(const char *fmt,...) PRINTF_ARGS(1)
write a formatted string to the debug channel.
Definition: debug.cpp:71
void debug_puts(const char *text)
[system-dependent] write a string to the debug channel.
Definition: udbg.cpp:107
ErrorReaction debug_DisplayError(const wchar_t *description, size_t flags, void *context, const wchar_t *lastFuncToSkip, const wchar_t *file, int line, const char *func, std::atomic< bool > *suppress)
display an error dialog with a message and stack trace.
Definition: debug.cpp:331
size_t debug_StopSkippingErrors()
Definition: debug.cpp:404
void debug_DisplayMessage(const wchar_t *caption, const wchar_t *msg)
translates and displays the given strings in a dialog.
Definition: debug.cpp:254
ErrorReaction debug_OnError(Status err, std::atomic< bool > *suppress, const wchar_t *file, int line, const char *func) ANALYZER_NORETURN
called when a DEBUG_WARN_ERR indicates an error occurred; notifies the user via debug_DisplayError.
Definition: debug.cpp:433
static const size_t DEBUG_FILE_CHARS
Definition: debug.h:369
void debug_SkipErrors(Status err)
suppress (prevent from showing) the error dialog from subsequent debug_OnError for the given Status.
Definition: debug.cpp:391
Status debug_CaptureContext(void *context)
Definition: udbg.cpp:45
bool debug_IsStackPointer(void *p)
does the given pointer appear to point to the stack?
Definition: wdbg.cpp:77
void debug_break()
trigger a breakpoint when reached/"called".
Definition: udbg.cpp:51
void debug_SetThreadName(const char *name)
inform the debugger of the current thread's name.
Definition: bdbg.cpp:126
static const size_t DEBUG_SYMBOL_CHARS
Maximum number of characters (including null terminator) written to user's buffers by debug_ResolveSy...
Definition: debug.h:368
ErrorReaction
choices offered by the error dialog that are returned by debug_DisplayError.
Definition: debug.h:118
@ ER_CONTINUE
ignore, continue as if nothing happened.
Definition: debug.h:124
@ ER_BREAK
trigger breakpoint, i.e.
Definition: debug.h:131
static const size_t DEBUG_CONTEXT_SIZE
Definition: debug.h:391
DebugDisplayErrorFlags
flags to customize debug_DisplayError behavior
Definition: debug.h:83
@ DE_MANUAL_BREAK
do not trigger a breakpoint inside debug_DisplayError; caller will take care of this if ER_BREAK is r...
Definition: debug.h:104
@ DE_NO_CONTINUE
disallow the Continue button.
Definition: debug.h:87
@ DE_ALLOW_SUPPRESS
enable the Suppress button.
Definition: debug.h:97
@ DE_NO_DEBUG_INFO
display just the given message; do not add any information about the call stack, do not write crashlo...
Definition: debug.h:110
Status debug_WriteCrashlog(const char *text)
write an error description and all logs into crashlog.txt (in unicode format).
bool debug_IsCodePointer(void *p)
does the given pointer appear to point to code?
Definition: wdbg.cpp:62
ErrorReaction debug_OnAssertionFailure(const wchar_t *assert_expr, std::atomic< bool > *suppress, const wchar_t *file, int line, const char *func) ANALYZER_NORETURN
called when a ENSURE/ASSERT fails; notifies the user via debug_DisplayError.
Definition: debug.cpp:448
int debug_IsPointerBogus(const void *p)
check if a pointer appears to be totally invalid.
Definition: udbg.cpp:115
void * debug_GetCaller(void *context, const wchar_t *lastFuncToSkip)
return the caller of a certain function on the call stack.
Definition: bdbg.cpp:38
Status debug_ResolveSymbol(void *ptr_of_interest, wchar_t *sym_name, wchar_t *file, int *line)
read and return symbol information for the given address.
Definition: bdbg.cpp:99
Definition: debug.h:340
const Status SYM_UNRETRIEVABLE
Definition: debug.h:343
const Status SYM_UNRETRIEVABLE_STATIC
Definition: debug.h:342
const Status SYM_CHILD_NOT_FOUND
Definition: debug.h:347
const Status SYM_TYPE_INFO_UNAVAILABLE
Definition: debug.h:344
const Status SYM_NO_STACK_FRAMES_FOUND
Definition: debug.h:341
const Status SYM_NESTING_LIMIT
Definition: debug.h:349
const Status SYM_INTERNAL_ERROR
Definition: debug.h:345
const Status SYM_UNSUPPORTED
Definition: debug.h:346
const Status SYM_SINGLE_SYMBOL_LIMIT
Definition: debug.h:352
Definition: debug.h:356
const Status SYM_SUPPRESS_OUTPUT
Definition: debug.h:360
std::int64_t Status
Error handling system.
Definition: status.h:174