Pyrogenesis HEAD
Pyrogenesis, a RTS Engine
status.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 * error handling system: defines status codes, translates them to/from
25 * other schemes (e.g. errno), associates them with descriptive text,
26 * simplifies propagating errors / checking if functions failed.
27 */
28
29/**
30
31Error handling system
32
33
34Why Error Codes?
35----------------
36
37To convey information about what failed, the alternatives are unique
38integral codes and direct pointers to descriptive text. Both occupy the
39same amount of space, but codes are easier to internationalize.
40
41
42Method of Propagating Errors
43----------------------------
44
45When a low-level function has failed, this must be conveyed to the
46higher-level application logic across several functions on the call stack.
47There are two alternatives:
481) check at each call site whether a function failed;
49 if so, return to the caller.
502) throw an exception.
51
52We will discuss the advantages and disadvantages of exceptions,
53which are the opposites of call site checking.
54- performance: they shouldn't be used in time-critical code.
55- predictability: exceptions can come up almost anywhere,
56 so it is hard to say what execution path will be taken.
57- interoperability: not compatible with other languages.
58+ readability: cleans up code by separating application logic and
59 error handling. however, this is also a disadvantage because it
60 may be difficult to see at a glance if a piece of code does
61 error checking at all.
62+ visibility: errors are more likely to be seen than relying on
63 callers to check return codes; less reliant on discipline.
64
65Both have their place. Our recommendation is to throw error code
66exceptions when checking call sites and propagating errors becomes tedious.
67However, inter-module boundaries should always return error codes for
68interoperability with other languages.
69
70
71Simplifying Call-Site Checking
72------------------------------
73
74As mentioned above, this approach requires discipline. We provide
75"enforcer" macros to simplify this task by propagating errors to
76the calling function.
77
78Consider the following example:
79 Status status = doWork();
80 if(status != INFO::OK)
81 return status;
82This can be replaced by:
83 RETURN_STATUS_IF_ERR(doWork());
84
85This provides a visible sign that the code handles errors but
86reduces clutter.
87
88
89When to warn the user?
90----------------------
91
92When a function fails, there are 2 places we can raise a warning:
93as soon as the error condition is known, or higher on the call stack.
94
95We prefer the former because it is easier to ensure that all
96possible return paths have been covered: search for all "return ERR::*"
97or "return StatusFrom*" that are not followed by a "// NOWARN" comment.
98The latter approach also risks multiple warnings along the
99call stack for the same error.
100
101Note the special case of "validator" functions that e.g. verify the
102state of an object: we now discuss pros/cons of just returning errors
103without warning, and having their callers take care of that.
104+ they typically have many return paths (-> increased code size)
105- this is balanced by validators that have many call sites.
106- we want all return statements wrapped for consistency and
107 easily checking if any were forgotten
108- adding // NOWARN to each validator return statement would be tedious.
109- there is no advantage to checking at the call site; the call stack
110 indicates which caller of the validator failed anyway.
111Validator functions should therefore also use WARN_RETURN.
112
113
114Numbering Scheme
115----------------
116
117Each module header defines its own error codes to avoid a full rebuild
118whenever a new code is added.
119
120Error codes start at -100000 (warnings are positive, but the
121corresponding negative value should not be used to avoid confusion).
122This scheme avoids collisions with all other known error codes.
123
124Each header gets 100 possible values; the tens value may be
125used to denote groups within that header.
126
127The subsystem is denoted by the ten-thousands digit:
1280 general
1291 file
1302 res (resource management)
1313 sysdep (system-dependent)
1324 win (Windows-specific)
133
134To summarize: +/-1SHHCC (S=subsystem, HH=header, CC=code number)
135
13610 general
137 00CC misc
138 03CC path
139 04CC debug
140 05CC debug_stl
141 06CC secure_crt
142 07CC wchar
143
14411 file
145 01CC vfs
146 03CC file
147 04CC archive
148
14912 res
150 00CC h_mgr
151 01CC tex
152
15313 sysdep
154 00CC cpu
155 01CC os_cpu
156
15714 win
158 00CC whrt
159**/
160
161#ifndef INCLUDED_STATUS
162#define INCLUDED_STATUS
163
164#include "lib/code_annotation.h"
165
166#include <cstddef>
167#include <system_error>
168
169// an integral type allows defining error codes in separate headers,
170// but is not as type-safe as an enum. use Lint's 'strong type' checking
171// to catch errors such as Status Func() { return 1; }.
172// this must be std::int64_t because some functions may multiplex Status with
173// file offsets/sizes in their return value.
174typedef std::int64_t Status;
175
176// associates a status code with a description [and errno_equivalent].
177struct StatusDefinition // POD
178{
180
181 // typically a string literal; must remain valid until end of program.
182 const wchar_t* description;
183
184 // omit initializer (or initialize to 0) if there is no errno equivalent.
186};
187
188// retrieving description and errno_equivalent requires going through all
189// StatusDefinition instances. we avoid dynamic memory allocation (which
190// is problematic because status codes may be needed before _cinit) by
191// organizing them into a linked list, with nodes residing in static storage.
192// since modules may introduce many status codes, they are stored in an
193// array, aka "bucket", which includes a link to the next bucket.
194// initialized via STATUS_ADD_DEFINITIONS; opaque.
196{
200};
201
202/**
203 * (called via STATUS_ADD_DEFINITIONS)
204 *
205 * @param bucket is being added; its definitions and numDefinitions must
206 * already be initialized.
207 * @return previous bucket in list, suitable for initializing bucket->next.
208 *
209 * (this function must be callable as a static initializer; initializing
210 * next avoids the need for a separate dummy variable)
211 **/
213
214/**
215 * add a module's array of StatusDefinition to the list.
216 * typically invoked at file scope.
217 * @param definitions name (identifier) of the array
218 **/
219#define STATUS_ADD_DEFINITIONS(definitions) static StatusDefinitionBucket definitions##_bucket = { definitions, ARRAY_SIZE(definitions), StatusAddDefinitions(&definitions##_bucket) }
220
221
222/**
223 * generate textual description of a Status.
224 *
225 * @param buf destination buffer (allows generating strings with
226 * the code's numerical value if no definition is found)
227 * @param max_chars size of buffer [characters]
228 * @return buf (allows using this function in expressions)
229 **/
230wchar_t* StatusDescription(Status status, wchar_t* buf, size_t max_chars);
231
232/**
233 * @return the errno equivalent of a Status.
234 *
235 * used in wposix - underlying functions return Status but must be
236 * translated to errno at e.g. the mmap interface level. higher-level code
237 * that calls mmap will in turn convert back to Status.
238 **/
239extern int ErrnoFromStatus(Status status);
240
241/**
242 * @return Status equivalent of errno, or ERR::FAIL if there's no equivalent.
243 *
244 * NB: reset errno to 0 before calling POSIX functions to avoid confusion
245 * with previous errors.
246 **/
247extern Status StatusFromErrno();
248
249/**
250 * @return Status equivalent of error_code, or ERR::FAIL if there's no equivalent.
251 */
252extern Status StatusFromSystemError(std::error_code& ec);
253
254// note: other conversion routines (e.g. to/from Win32) are implemented in
255// the corresponding modules to keep this header portable.
256
257
258//-----------------------------------------------------------------------------
259// propagation macros
260
261// warn and return a status. use when an error is first detected to
262// begin propagating it to callers.
263#define WARN_RETURN(status)\
264 do\
265 {\
266 DEBUG_WARN_ERR(status);\
267 return status;\
268 }\
269 while(0)
270
271// warn if expression is negative, i.e. an error.
272// (this macro is more convenient than ENSURE)
273#define WARN_IF_ERR(expression)\
274 do\
275 {\
276 const Status status_ = (expression);\
277 if(status_ < 0)\
278 DEBUG_WARN_ERR(status_);\
279 }\
280 while(0)
281
282// return expression if it is negative, i.e. pass on errors to
283// the caller. use when failures are common/expected.
284#define RETURN_STATUS_IF_ERR(expression)\
285 do\
286 {\
287 const Status status_ = (expression);\
288 if(status_ < 0)\
289 return status_;\
290 }\
291 while(0)
292
293// warn and return expression if it is negative.
294// use if a function doesn't raise warnings when it returns errors.
295#define WARN_RETURN_STATUS_IF_ERR(expression)\
296 do\
297 {\
298 const Status status_ = (expression);\
299 if(status_ < 0)\
300 {\
301 DEBUG_WARN_ERR(status_);\
302 return status_;\
303 }\
304 }\
305 while(0)
306
307// warn and throw a status. use when an error is first detected to
308// begin propagating it to callers.
309#define WARN_THROW(status)\
310 do\
311 {\
312 DEBUG_WARN_ERR(status);\
313 throw status;\
314 }\
315 while(0)
316
317// throw expression if it is negative. use to propagate
318// expected errors from constructors.
319#define THROW_STATUS_IF_ERR(expression)\
320 do\
321 {\
322 const Status status_ = (expression);\
323 if(status_ < 0)\
324 throw status_;\
325 }\
326 while(0)
327
328// warn and throw expression if it is negative. use to propagate
329// errors from constructors.
330#define WARN_THROW_STATUS_IF_ERR(expression)\
331 do\
332 {\
333 const Status status_ = (expression);\
334 if(status_ < 0)\
335 {\
336 DEBUG_WARN_ERR(status_);\
337 throw status_;\
338 }\
339 }\
340 while(0)
341
342// if expression (typically the invocation of a callback) evaluates to:
343// - INFO::OK, do nothing;
344// - INFO::ALL_COMPLETE, return INFO::OK;
345// - anything else, return that.
346#define RETURN_STATUS_FROM_CALLBACK(expression)\
347 do\
348 {\
349 const Status status_ = (expression);\
350 if(status_ == INFO::ALL_COMPLETE)\
351 return INFO::OK;\
352 else if(status_ != INFO::OK)\
353 return status_;\
354 }\
355 while(0)
356
357// return 0 if expression is negative. use in functions that return pointers.
358#define RETURN_0_IF_ERR(expression)\
359 do\
360 {\
361 const Status status_ = (expression);\
362 if(status_ < 0)\
363 return 0;\
364 }\
365 while(0)
366
367// warn if expression is false, i.e. zero.
368#define WARN_IF_FALSE(expression)\
369 do\
370 {\
371 if(!(expression))\
372 debug_warn(L"FYI: WARN_IF_FALSE reports that a function failed. Feel free to ignore or suppress this warning.");\
373 }\
374 while(0)
375
376// warn and return 0 if expression is false, i.e. zero.
377#define WARN_RETURN_0_IF_FALSE(expression)\
378 do\
379 {\
380 if(!(expression))\
381 {\
382 debug_warn(L"FYI: WARN_RETURN_0_IF_FALSE reports that a function failed. Feel free to ignore or suppress this warning.");\
383 return 0;\
384 }\
385 }\
386 while(0)
387
388
389//-----------------------------------------------------------------------------
390// shared status code definitions
391
392namespace INFO {
393
394 const Status OK = 0;
395
396 // note: these values are > 100 to allow multiplexing them with
397 // coroutine return values, which return completion percentage.
398
399 // notify caller that nothing was done.
400 const Status SKIPPED = +100001;
401
402 // function is incapable of doing the requested task with the given inputs.
403 // this implies SKIPPED, but also conveys a bit more information.
404 const Status CANNOT_HANDLE = +100002;
405
406 // function is meant to be called repeatedly, and now indicates that
407 // all jobs are complete.
408 const Status ALL_COMPLETE = +100003;
409
410} // namespace INFO
411
412namespace ERR {
413
414 const Status FAIL = -1; // unknown failure
415
416 // general
417 const Status LOGIC = -100010;
418 const Status EXCEPTION = -100011;
419 const Status TIMED_OUT = -100012;
420 const Status REENTERED = -100013;
421 const Status CORRUPTED = -100014;
422 const Status ABORTED = -100015;
423
424 // invalid values (usually function arguments)
425 const Status INVALID_ALIGNMENT = -100020;
426 const Status INVALID_OFFSET = -100021;
427 const Status INVALID_HANDLE = -100022;
428 const Status INVALID_POINTER = -100023;
429 const Status INVALID_SIZE = -100024;
430 const Status INVALID_FLAG = -100025;
431 const Status INVALID_PARAM = -100026;
432 const Status INVALID_VERSION = -100027;
433
434 // system limitations
435 const Status AGAIN = -100030;
436 const Status LIMIT = -100031;
437 const Status NOT_SUPPORTED = -100032;
438 const Status NO_MEM = -100033;
439
440 // these are for cases where we just want a distinct value to display and
441 // a symbolic name + string would be overkill (e.g. the various
442 // test cases in a validate() call). they are shared between multiple
443 // functions; when something fails, the stack trace will show in which
444 // one it was => these errors are unambiguous.
445 // there are 3 tiers - 1..9 are used in most functions, 11..19 are
446 // used in a function that calls another validator and 21..29 are
447 // for for functions that call 2 other validators (this avoids
448 // ambiguity as to which error actually happened where)
449 const Status _1 = -100101;
450 const Status _2 = -100102;
451 const Status _3 = -100103;
452 const Status _4 = -100104;
453 const Status _5 = -100105;
454 const Status _6 = -100106;
455 const Status _7 = -100107;
456 const Status _8 = -100108;
457 const Status _9 = -100109;
458 const Status _11 = -100111;
459 const Status _12 = -100112;
460 const Status _13 = -100113;
461 const Status _14 = -100114;
462 const Status _15 = -100115;
463 const Status _16 = -100116;
464 const Status _17 = -100117;
465 const Status _18 = -100118;
466 const Status _19 = -100119;
467 const Status _21 = -100121;
468 const Status _22 = -100122;
469 const Status _23 = -100123;
470 const Status _24 = -100124;
471 const Status _25 = -100125;
472 const Status _26 = -100126;
473 const Status _27 = -100127;
474 const Status _28 = -100128;
475 const Status _29 = -100129;
476
477} // namespace ERR
478
479#endif // #ifndef INCLUDED_STATUS
Definition: debug.h:340
const Status INVALID_VERSION
Definition: status.h:432
const Status _21
Definition: status.h:467
const Status INVALID_SIZE
Definition: status.h:429
const Status _7
Definition: status.h:455
const Status ABORTED
Definition: status.h:422
const Status _27
Definition: status.h:473
const Status _11
Definition: status.h:458
const Status _16
Definition: status.h:463
const Status _19
Definition: status.h:466
const Status LOGIC
Definition: status.h:417
const Status CORRUPTED
Definition: status.h:421
const Status FAIL
Definition: status.h:414
const Status INVALID_FLAG
Definition: status.h:430
const Status _29
Definition: status.h:475
const Status _26
Definition: status.h:472
const Status _13
Definition: status.h:460
const Status INVALID_HANDLE
Definition: status.h:427
const Status _12
Definition: status.h:459
const Status _6
Definition: status.h:454
const Status _15
Definition: status.h:462
const Status NO_MEM
Definition: status.h:438
const Status TIMED_OUT
Definition: status.h:419
const Status _23
Definition: status.h:469
const Status REENTERED
Definition: status.h:420
const Status INVALID_PARAM
Definition: status.h:431
const Status NOT_SUPPORTED
Definition: status.h:437
const Status _17
Definition: status.h:464
const Status _18
Definition: status.h:465
const Status _2
Definition: status.h:450
const Status _4
Definition: status.h:452
const Status _24
Definition: status.h:470
const Status _25
Definition: status.h:471
const Status INVALID_ALIGNMENT
Definition: status.h:425
const Status _8
Definition: status.h:456
const Status _22
Definition: status.h:468
const Status INVALID_OFFSET
Definition: status.h:426
const Status INVALID_POINTER
Definition: status.h:428
const Status _28
Definition: status.h:474
const Status _9
Definition: status.h:457
const Status _14
Definition: status.h:461
const Status _1
Definition: status.h:449
const Status LIMIT
Definition: status.h:436
const Status EXCEPTION
Definition: status.h:418
const Status AGAIN
Definition: status.h:435
const Status _3
Definition: status.h:451
const Status _5
Definition: status.h:453
Definition: debug.h:356
const Status CANNOT_HANDLE
Definition: status.h:404
const Status SKIPPED
Definition: status.h:400
const Status ALL_COMPLETE
Definition: status.h:408
const Status OK
Definition: status.h:394
int ErrnoFromStatus(Status status)
Definition: status.cpp:92
StatusDefinitionBucket * StatusAddDefinitions(StatusDefinitionBucket *bucket)
(called via STATUS_ADD_DEFINITIONS)
Definition: status.cpp:39
wchar_t * StatusDescription(Status status, wchar_t *buf, size_t max_chars)
generate textual description of a Status.
Definition: status.cpp:78
std::int64_t Status
Error handling system.
Definition: status.h:174
Status StatusFromErrno()
Definition: status.cpp:114
Status StatusFromSystemError(std::error_code &ec)
Definition: status.cpp:103
Definition: status.h:196
size_t numDefinitions
Definition: status.h:198
const StatusDefinition * definitions
Definition: status.h:197
StatusDefinitionBucket * next
Definition: status.h:199
Definition: status.h:178
int errno_equivalent
Definition: status.h:185
Status status
Definition: status.h:179
const wchar_t * description
Definition: status.h:182