Mercurial > repos > rliterman > csp2
comparison CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/include/kj/debug.h @ 69:33d812a61356
planemo upload commit 2e9511a184a1ca667c7be0c6321a36dc4e3d116d
author | jpayne |
---|---|
date | Tue, 18 Mar 2025 17:55:14 -0400 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
67:0e9998148a16 | 69:33d812a61356 |
---|---|
1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors | |
2 // Licensed under the MIT License: | |
3 // | |
4 // Permission is hereby granted, free of charge, to any person obtaining a copy | |
5 // of this software and associated documentation files (the "Software"), to deal | |
6 // in the Software without restriction, including without limitation the rights | |
7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
8 // copies of the Software, and to permit persons to whom the Software is | |
9 // furnished to do so, subject to the following conditions: | |
10 // | |
11 // The above copyright notice and this permission notice shall be included in | |
12 // all copies or substantial portions of the Software. | |
13 // | |
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
20 // THE SOFTWARE. | |
21 | |
22 // This file declares convenient macros for debug logging and error handling. The macros make | |
23 // it excessively easy to extract useful context information from code. Example: | |
24 // | |
25 // KJ_ASSERT(a == b, a, b, "a and b must be the same."); | |
26 // | |
27 // On failure, this will throw an exception whose description looks like: | |
28 // | |
29 // myfile.c++:43: bug in code: expected a == b; a = 14; b = 72; a and b must be the same. | |
30 // | |
31 // As you can see, all arguments after the first provide additional context. | |
32 // | |
33 // The macros available are: | |
34 // | |
35 // * `KJ_LOG(severity, ...)`: Just writes a log message, to stderr by default (but you can | |
36 // intercept messages by implementing an ExceptionCallback). `severity` is `INFO`, `WARNING`, | |
37 // `ERROR`, or `FATAL`. By default, `INFO` logs are not written, but for command-line apps the | |
38 // user should be able to pass a flag like `--verbose` to enable them. Other log levels are | |
39 // enabled by default. Log messages -- like exceptions -- can be intercepted by registering an | |
40 // ExceptionCallback. | |
41 // | |
42 // * `KJ_DBG(...)`: Like `KJ_LOG`, but intended specifically for temporary log lines added while | |
43 // debugging a particular problem. Calls to `KJ_DBG` should always be deleted before committing | |
44 // code. It is suggested that you set up a pre-commit hook that checks for this. | |
45 // | |
46 // * `KJ_ASSERT(condition, ...)`: Throws an exception if `condition` is false, or aborts if | |
47 // exceptions are disabled. This macro should be used to check for bugs in the surrounding code | |
48 // and its dependencies, but NOT to check for invalid input. The macro may be followed by a | |
49 // brace-delimited code block; if so, the block will be executed in the case where the assertion | |
50 // fails, before throwing the exception. If control jumps out of the block (e.g. with "break", | |
51 // "return", or "goto"), then the error is considered "recoverable" -- in this case, if | |
52 // exceptions are disabled, execution will continue normally rather than aborting (but if | |
53 // exceptions are enabled, an exception will still be thrown on exiting the block). A "break" | |
54 // statement in particular will jump to the code immediately after the block (it does not break | |
55 // any surrounding loop or switch). Example: | |
56 // | |
57 // KJ_ASSERT(value >= 0, "Value cannot be negative.", value) { | |
58 // // Assertion failed. Set value to zero to "recover". | |
59 // value = 0; | |
60 // // Don't abort if exceptions are disabled. Continue normally. | |
61 // // (Still throw an exception if they are enabled, though.) | |
62 // break; | |
63 // } | |
64 // // When exceptions are disabled, we'll get here even if the assertion fails. | |
65 // // Otherwise, we get here only if the assertion passes. | |
66 // | |
67 // * `KJ_REQUIRE(condition, ...)`: Like `KJ_ASSERT` but used to check preconditions -- e.g. to | |
68 // validate parameters passed from a caller. A failure indicates that the caller is buggy. | |
69 // | |
70 // * `KJ_ASSUME(condition, ...)`: Like `KJ_ASSERT`, but in release mode (if KJ_DEBUG is not | |
71 // defined; see below) instead warrants to the compiler that the condition can be assumed to | |
72 // hold, allowing it to optimize accordingly. This can result in undefined behavior, so use | |
73 // this macro *only* if you can prove to your satisfaction that the condition is guaranteed by | |
74 // surrounding code, and if the condition failing to hold would in any case result in undefined | |
75 // behavior in its dependencies. | |
76 // | |
77 // * `KJ_SYSCALL(code, ...)`: Executes `code` assuming it makes a system call. A negative result | |
78 // is considered an error, with error code reported via `errno`. EINTR is handled by retrying. | |
79 // Other errors are handled by throwing an exception. If you need to examine the return code, | |
80 // assign it to a variable like so: | |
81 // | |
82 // int fd; | |
83 // KJ_SYSCALL(fd = open(filename, O_RDONLY), filename); | |
84 // | |
85 // `KJ_SYSCALL` can be followed by a recovery block, just like `KJ_ASSERT`. | |
86 // | |
87 // * `KJ_NONBLOCKING_SYSCALL(code, ...)`: Like KJ_SYSCALL, but will not throw an exception on | |
88 // EAGAIN/EWOULDBLOCK. The calling code should check the syscall's return value to see if it | |
89 // indicates an error; in this case, it can assume the error was EAGAIN because any other error | |
90 // would have caused an exception to be thrown. | |
91 // | |
92 // * `KJ_CONTEXT(...)`: Notes additional contextual information relevant to any exceptions thrown | |
93 // from within the current scope. That is, until control exits the block in which KJ_CONTEXT() | |
94 // is used, if any exception is generated, it will contain the given information in its context | |
95 // chain. This is helpful because it can otherwise be very difficult to come up with error | |
96 // messages that make sense within low-level helper code. Note that the parameters to | |
97 // KJ_CONTEXT() are only evaluated if an exception is thrown. This implies that any variables | |
98 // used must remain valid until the end of the scope. | |
99 // | |
100 // Notes: | |
101 // * Do not write expressions with side-effects in the message content part of the macro, as the | |
102 // message will not necessarily be evaluated. | |
103 // * For every macro `FOO` above except `LOG`, there is also a `FAIL_FOO` macro used to report | |
104 // failures that already happened. For the macros that check a boolean condition, `FAIL_FOO` | |
105 // omits the first parameter and behaves like it was `false`. `FAIL_SYSCALL` and | |
106 // `FAIL_RECOVERABLE_SYSCALL` take a string and an OS error number as the first two parameters. | |
107 // The string should be the name of the failed system call. | |
108 // * For every macro `FOO` above except `ASSUME`, there is a `DFOO` version (or | |
109 // `RECOVERABLE_DFOO`) which is only executed in debug mode, i.e. when KJ_DEBUG is defined. | |
110 // KJ_DEBUG is defined automatically by common.h when compiling without optimization (unless | |
111 // NDEBUG is defined), but you can also define it explicitly (e.g. -DKJ_DEBUG). Generally, | |
112 // production builds should NOT use KJ_DEBUG as it may enable expensive checks that are unlikely | |
113 // to fail. | |
114 | |
115 #pragma once | |
116 | |
117 #include "string.h" | |
118 #include "exception.h" | |
119 #include "windows-sanity.h" // work-around macro conflict with `ERROR` | |
120 | |
121 KJ_BEGIN_HEADER | |
122 | |
123 namespace kj { | |
124 | |
125 #if KJ_MSVC_TRADITIONAL_CPP | |
126 // MSVC does __VA_ARGS__ differently from GCC: | |
127 // - A trailing comma before an empty __VA_ARGS__ is removed automatically, whereas GCC wants | |
128 // you to request this behavior with "##__VA_ARGS__". | |
129 // - If __VA_ARGS__ is passed directly as an argument to another macro, it will be treated as a | |
130 // *single* argument rather than an argument list. This can be worked around by wrapping the | |
131 // outer macro call in KJ_EXPAND(), which apparently forces __VA_ARGS__ to be expanded before | |
132 // the macro is evaluated. I don't understand the C preprocessor. | |
133 // - Using "#__VA_ARGS__" to stringify __VA_ARGS__ expands to zero tokens when __VA_ARGS__ is | |
134 // empty, rather than expanding to an empty string literal. We can work around by concatenating | |
135 // with an empty string literal. | |
136 | |
137 #define KJ_EXPAND(X) X | |
138 | |
139 #define KJ_LOG(severity, ...) \ | |
140 for (bool _kj_shouldLog = ::kj::_::Debug::shouldLog(::kj::LogSeverity::severity); \ | |
141 _kj_shouldLog; _kj_shouldLog = false) \ | |
142 ::kj::_::Debug::log(__FILE__, __LINE__, ::kj::LogSeverity::severity, \ | |
143 "" #__VA_ARGS__, __VA_ARGS__) | |
144 | |
145 #define KJ_DBG(...) KJ_EXPAND(KJ_LOG(DBG, __VA_ARGS__)) | |
146 | |
147 #define KJ_REQUIRE(cond, ...) \ | |
148 if (auto _kjCondition = ::kj::_::MAGIC_ASSERT << cond) {} else \ | |
149 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ | |
150 #cond, "_kjCondition," #__VA_ARGS__, _kjCondition, __VA_ARGS__);; f.fatal()) | |
151 | |
152 #define KJ_FAIL_REQUIRE(...) \ | |
153 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ | |
154 nullptr, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) | |
155 | |
156 #define KJ_SYSCALL(call, ...) \ | |
157 if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, false)) {} else \ | |
158 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ | |
159 _kjSyscallResult.getErrorNumber(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) | |
160 | |
161 #define KJ_NONBLOCKING_SYSCALL(call, ...) \ | |
162 if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, true)) {} else \ | |
163 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ | |
164 _kjSyscallResult.getErrorNumber(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) | |
165 | |
166 #define KJ_FAIL_SYSCALL(code, errorNumber, ...) \ | |
167 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ | |
168 errorNumber, code, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) | |
169 | |
170 #if _WIN32 || __CYGWIN__ | |
171 | |
172 #define KJ_WIN32(call, ...) \ | |
173 if (auto _kjWin32Result = ::kj::_::Debug::win32Call(call)) {} else \ | |
174 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ | |
175 _kjWin32Result, #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) | |
176 | |
177 #define KJ_WINSOCK(call, ...) \ | |
178 if (auto _kjWin32Result = ::kj::_::Debug::winsockCall(call)) {} else \ | |
179 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ | |
180 _kjWin32Result, #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) | |
181 | |
182 #define KJ_FAIL_WIN32(code, errorNumber, ...) \ | |
183 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ | |
184 ::kj::_::Debug::Win32Result(errorNumber), code, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) | |
185 | |
186 #endif | |
187 | |
188 #define KJ_UNIMPLEMENTED(...) \ | |
189 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::UNIMPLEMENTED, \ | |
190 nullptr, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) | |
191 | |
192 // TODO(msvc): MSVC mis-deduces `ContextImpl<decltype(func)>` as `ContextImpl<int>` in some edge | |
193 // cases, such as inside nested lambdas inside member functions. Wrapping the type in | |
194 // `decltype(instance<...>())` helps it deduce the context function's type correctly. | |
195 #define KJ_CONTEXT(...) \ | |
196 auto KJ_UNIQUE_NAME(_kjContextFunc) = [&]() -> ::kj::_::Debug::Context::Value { \ | |
197 return ::kj::_::Debug::Context::Value(__FILE__, __LINE__, \ | |
198 ::kj::_::Debug::makeDescription("" #__VA_ARGS__, __VA_ARGS__)); \ | |
199 }; \ | |
200 decltype(::kj::instance<::kj::_::Debug::ContextImpl<decltype(KJ_UNIQUE_NAME(_kjContextFunc))>>()) \ | |
201 KJ_UNIQUE_NAME(_kjContext)(KJ_UNIQUE_NAME(_kjContextFunc)) | |
202 | |
203 #define KJ_REQUIRE_NONNULL(value, ...) \ | |
204 (*[&] { \ | |
205 auto _kj_result = ::kj::_::readMaybe(value); \ | |
206 if (KJ_UNLIKELY(!_kj_result)) { \ | |
207 ::kj::_::Debug::Fault(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ | |
208 #value " != nullptr", "" #__VA_ARGS__, __VA_ARGS__).fatal(); \ | |
209 } \ | |
210 return _kj_result; \ | |
211 }()) | |
212 | |
213 #define KJ_EXCEPTION(type, ...) \ | |
214 ::kj::Exception(::kj::Exception::Type::type, __FILE__, __LINE__, \ | |
215 ::kj::_::Debug::makeDescription("" #__VA_ARGS__, __VA_ARGS__)) | |
216 | |
217 #else | |
218 | |
219 #define KJ_LOG(severity, ...) \ | |
220 for (bool _kj_shouldLog = ::kj::_::Debug::shouldLog(::kj::LogSeverity::severity); \ | |
221 _kj_shouldLog; _kj_shouldLog = false) \ | |
222 ::kj::_::Debug::log(__FILE__, __LINE__, ::kj::LogSeverity::severity, \ | |
223 #__VA_ARGS__, ##__VA_ARGS__) | |
224 | |
225 #define KJ_DBG(...) KJ_LOG(DBG, ##__VA_ARGS__) | |
226 | |
227 #define KJ_REQUIRE(cond, ...) \ | |
228 if (auto _kjCondition = ::kj::_::MAGIC_ASSERT << cond) {} else \ | |
229 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ | |
230 #cond, "_kjCondition," #__VA_ARGS__, _kjCondition, ##__VA_ARGS__);; f.fatal()) | |
231 | |
232 #define KJ_FAIL_REQUIRE(...) \ | |
233 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ | |
234 nullptr, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) | |
235 | |
236 #define KJ_SYSCALL(call, ...) \ | |
237 if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, false)) {} else \ | |
238 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ | |
239 _kjSyscallResult.getErrorNumber(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) | |
240 | |
241 #define KJ_NONBLOCKING_SYSCALL(call, ...) \ | |
242 if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, true)) {} else \ | |
243 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ | |
244 _kjSyscallResult.getErrorNumber(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) | |
245 | |
246 #define KJ_FAIL_SYSCALL(code, errorNumber, ...) \ | |
247 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ | |
248 errorNumber, code, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) | |
249 | |
250 #if _WIN32 || __CYGWIN__ | |
251 | |
252 #define KJ_WIN32(call, ...) \ | |
253 if (auto _kjWin32Result = ::kj::_::Debug::win32Call(call)) {} else \ | |
254 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ | |
255 _kjWin32Result, #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) | |
256 // Invoke a Win32 syscall that returns either BOOL or HANDLE, and throw an exception if it fails. | |
257 | |
258 #define KJ_WINSOCK(call, ...) \ | |
259 if (auto _kjWin32Result = ::kj::_::Debug::winsockCall(call)) {} else \ | |
260 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ | |
261 _kjWin32Result, #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) | |
262 // Like KJ_WIN32 but for winsock calls which return `int` with SOCKET_ERROR indicating failure. | |
263 // | |
264 // Unfortunately, it's impossible to distinguish these from BOOL-returning Win32 calls by type, | |
265 // since BOOL is in fact an alias for `int`. :( | |
266 | |
267 #define KJ_FAIL_WIN32(code, errorNumber, ...) \ | |
268 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ | |
269 ::kj::_::Debug::Win32Result(errorNumber), code, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) | |
270 | |
271 #endif | |
272 | |
273 #define KJ_UNIMPLEMENTED(...) \ | |
274 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::UNIMPLEMENTED, \ | |
275 nullptr, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) | |
276 | |
277 #define KJ_CONTEXT(...) \ | |
278 auto KJ_UNIQUE_NAME(_kjContextFunc) = [&]() -> ::kj::_::Debug::Context::Value { \ | |
279 return ::kj::_::Debug::Context::Value(__FILE__, __LINE__, \ | |
280 ::kj::_::Debug::makeDescription(#__VA_ARGS__, ##__VA_ARGS__)); \ | |
281 }; \ | |
282 ::kj::_::Debug::ContextImpl<decltype(KJ_UNIQUE_NAME(_kjContextFunc))> \ | |
283 KJ_UNIQUE_NAME(_kjContext)(KJ_UNIQUE_NAME(_kjContextFunc)) | |
284 | |
285 #if _MSC_VER && !defined(__clang__) | |
286 | |
287 #define KJ_REQUIRE_NONNULL(value, ...) \ | |
288 (*([&] { \ | |
289 auto _kj_result = ::kj::_::readMaybe(value); \ | |
290 if (KJ_UNLIKELY(!_kj_result)) { \ | |
291 ::kj::_::Debug::Fault(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ | |
292 #value " != nullptr", #__VA_ARGS__, ##__VA_ARGS__).fatal(); \ | |
293 } \ | |
294 return _kj_result; \ | |
295 }())) | |
296 | |
297 #else | |
298 | |
299 #define KJ_REQUIRE_NONNULL(value, ...) \ | |
300 (*({ \ | |
301 auto _kj_result = ::kj::_::readMaybe(value); \ | |
302 if (KJ_UNLIKELY(!_kj_result)) { \ | |
303 ::kj::_::Debug::Fault(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ | |
304 #value " != nullptr", #__VA_ARGS__, ##__VA_ARGS__).fatal(); \ | |
305 } \ | |
306 kj::mv(_kj_result); \ | |
307 })) | |
308 | |
309 #endif | |
310 | |
311 #define KJ_EXCEPTION(type, ...) \ | |
312 ::kj::Exception(::kj::Exception::Type::type, __FILE__, __LINE__, \ | |
313 ::kj::_::Debug::makeDescription(#__VA_ARGS__, ##__VA_ARGS__)) | |
314 | |
315 #endif | |
316 | |
317 #define KJ_SYSCALL_HANDLE_ERRORS(call) \ | |
318 if (int _kjSyscallError = ::kj::_::Debug::syscallError([&](){return (call);}, false)) \ | |
319 switch (int error KJ_UNUSED = _kjSyscallError) | |
320 // Like KJ_SYSCALL, but doesn't throw. Instead, the block after the macro is a switch block on the | |
321 // error. Additionally, the int value `error` is defined within the block. So you can do: | |
322 // | |
323 // KJ_SYSCALL_HANDLE_ERRORS(foo()) { | |
324 // case ENOENT: | |
325 // handleNoSuchFile(); | |
326 // break; | |
327 // case EEXIST: | |
328 // handleExists(); | |
329 // break; | |
330 // default: | |
331 // KJ_FAIL_SYSCALL("foo()", error); | |
332 // } else { | |
333 // handleSuccessCase(); | |
334 // } | |
335 | |
336 #if _WIN32 || __CYGWIN__ | |
337 | |
338 #define KJ_WIN32_HANDLE_ERRORS(call) \ | |
339 if (uint _kjWin32Error = ::kj::_::Debug::win32Call(call).number) \ | |
340 switch (uint error KJ_UNUSED = _kjWin32Error) | |
341 // Like KJ_WIN32, but doesn't throw. Instead, the block after the macro is a switch block on the | |
342 // error. Additionally, the int value `error` is defined within the block. So you can do: | |
343 // | |
344 // KJ_SYSCALL_HANDLE_ERRORS(foo()) { | |
345 // case ERROR_FILE_NOT_FOUND: | |
346 // handleNoSuchFile(); | |
347 // break; | |
348 // case ERROR_FILE_EXISTS: | |
349 // handleExists(); | |
350 // break; | |
351 // default: | |
352 // KJ_FAIL_WIN32("foo()", error); | |
353 // } else { | |
354 // handleSuccessCase(); | |
355 // } | |
356 | |
357 #endif | |
358 | |
359 #define KJ_ASSERT KJ_REQUIRE | |
360 #define KJ_FAIL_ASSERT KJ_FAIL_REQUIRE | |
361 #define KJ_ASSERT_NONNULL KJ_REQUIRE_NONNULL | |
362 // Use "ASSERT" in place of "REQUIRE" when the problem is local to the immediate surrounding code. | |
363 // That is, if the assert ever fails, it indicates that the immediate surrounding code is broken. | |
364 | |
365 #ifdef KJ_DEBUG | |
366 #define KJ_DLOG KJ_LOG | |
367 #define KJ_DASSERT KJ_ASSERT | |
368 #define KJ_DREQUIRE KJ_REQUIRE | |
369 #define KJ_ASSUME KJ_ASSERT | |
370 #else | |
371 #define KJ_DLOG(...) do {} while (false) | |
372 #define KJ_DASSERT(...) do {} while (false) | |
373 #define KJ_DREQUIRE(...) do {} while (false) | |
374 #if defined(__GNUC__) | |
375 #define KJ_ASSUME(cond, ...) do { if (cond) {} else __builtin_unreachable(); } while (false) | |
376 #elif defined(__clang__) | |
377 #define KJ_ASSUME(cond, ...) __builtin_assume(cond) | |
378 #elif defined(_MSC_VER) | |
379 #define KJ_ASSUME(cond, ...) __assume(cond) | |
380 #else | |
381 #define KJ_ASSUME(...) do {} while (false) | |
382 #endif | |
383 | |
384 #endif | |
385 | |
386 namespace _ { // private | |
387 | |
388 class Debug { | |
389 public: | |
390 Debug() = delete; | |
391 | |
392 typedef LogSeverity Severity; // backwards-compatibility | |
393 | |
394 #if _WIN32 || __CYGWIN__ | |
395 struct Win32Result { | |
396 uint number; | |
397 inline explicit Win32Result(uint number): number(number) {} | |
398 operator bool() const { return number == 0; } | |
399 }; | |
400 #endif | |
401 | |
402 static inline bool shouldLog(LogSeverity severity) { return severity >= minSeverity; } | |
403 // Returns whether messages of the given severity should be logged. | |
404 | |
405 static inline void setLogLevel(LogSeverity severity) { minSeverity = severity; } | |
406 // Set the minimum message severity which will be logged. | |
407 // | |
408 // TODO(someday): Expose publicly. | |
409 | |
410 template <typename... Params> | |
411 static void log(const char* file, int line, LogSeverity severity, const char* macroArgs, | |
412 Params&&... params); | |
413 | |
414 class Fault { | |
415 public: | |
416 template <typename Code, typename... Params> | |
417 Fault(const char* file, int line, Code code, | |
418 const char* condition, const char* macroArgs, Params&&... params); | |
419 Fault(const char* file, int line, Exception::Type type, | |
420 const char* condition, const char* macroArgs); | |
421 Fault(const char* file, int line, int osErrorNumber, | |
422 const char* condition, const char* macroArgs); | |
423 #if _WIN32 || __CYGWIN__ | |
424 Fault(const char* file, int line, Win32Result osErrorNumber, | |
425 const char* condition, const char* macroArgs); | |
426 #endif | |
427 ~Fault() noexcept(false); | |
428 | |
429 KJ_NOINLINE KJ_NORETURN(void fatal()); | |
430 // Throw the exception. | |
431 | |
432 private: | |
433 void init(const char* file, int line, Exception::Type type, | |
434 const char* condition, const char* macroArgs, ArrayPtr<String> argValues); | |
435 void init(const char* file, int line, int osErrorNumber, | |
436 const char* condition, const char* macroArgs, ArrayPtr<String> argValues); | |
437 #if _WIN32 || __CYGWIN__ | |
438 void init(const char* file, int line, Win32Result osErrorNumber, | |
439 const char* condition, const char* macroArgs, ArrayPtr<String> argValues); | |
440 #endif | |
441 | |
442 Exception* exception; | |
443 }; | |
444 | |
445 class SyscallResult { | |
446 public: | |
447 inline SyscallResult(int errorNumber): errorNumber(errorNumber) {} | |
448 inline operator void*() { return errorNumber == 0 ? this : nullptr; } | |
449 inline int getErrorNumber() { return errorNumber; } | |
450 | |
451 private: | |
452 int errorNumber; | |
453 }; | |
454 | |
455 template <typename Call> | |
456 static SyscallResult syscall(Call&& call, bool nonblocking); | |
457 template <typename Call> | |
458 static int syscallError(Call&& call, bool nonblocking); | |
459 | |
460 #if _WIN32 || __CYGWIN__ | |
461 static Win32Result win32Call(int boolean); | |
462 static Win32Result win32Call(void* handle); | |
463 static Win32Result winsockCall(int result); | |
464 static uint getWin32ErrorCode(); | |
465 #endif | |
466 | |
467 class Context: public ExceptionCallback { | |
468 public: | |
469 Context(); | |
470 KJ_DISALLOW_COPY_AND_MOVE(Context); | |
471 virtual ~Context() noexcept(false); | |
472 | |
473 struct Value { | |
474 const char* file; | |
475 int line; | |
476 String description; | |
477 | |
478 inline Value(const char* file, int line, String&& description) | |
479 : file(file), line(line), description(mv(description)) {} | |
480 }; | |
481 | |
482 virtual Value evaluate() = 0; | |
483 | |
484 virtual void onRecoverableException(Exception&& exception) override; | |
485 virtual void onFatalException(Exception&& exception) override; | |
486 virtual void logMessage(LogSeverity severity, const char* file, int line, int contextDepth, | |
487 String&& text) override; | |
488 | |
489 private: | |
490 bool logged; | |
491 Maybe<Value> value; | |
492 | |
493 Value ensureInitialized(); | |
494 }; | |
495 | |
496 template <typename Func> | |
497 class ContextImpl: public Context { | |
498 public: | |
499 inline ContextImpl(Func& func): func(func) {} | |
500 KJ_DISALLOW_COPY_AND_MOVE(ContextImpl); | |
501 | |
502 Value evaluate() override { | |
503 return func(); | |
504 } | |
505 private: | |
506 Func& func; | |
507 }; | |
508 | |
509 template <typename... Params> | |
510 static String makeDescription(const char* macroArgs, Params&&... params); | |
511 | |
512 private: | |
513 static LogSeverity minSeverity; | |
514 | |
515 static void logInternal(const char* file, int line, LogSeverity severity, const char* macroArgs, | |
516 ArrayPtr<String> argValues); | |
517 static String makeDescriptionInternal(const char* macroArgs, ArrayPtr<String> argValues); | |
518 | |
519 static int getOsErrorNumber(bool nonblocking); | |
520 // Get the error code of the last error (e.g. from errno). Returns -1 on EINTR. | |
521 }; | |
522 | |
523 template <typename... Params> | |
524 void Debug::log(const char* file, int line, LogSeverity severity, const char* macroArgs, | |
525 Params&&... params) { | |
526 String argValues[sizeof...(Params)] = {str(params)...}; | |
527 logInternal(file, line, severity, macroArgs, arrayPtr(argValues, sizeof...(Params))); | |
528 } | |
529 | |
530 template <> | |
531 inline void Debug::log<>(const char* file, int line, LogSeverity severity, const char* macroArgs) { | |
532 logInternal(file, line, severity, macroArgs, nullptr); | |
533 } | |
534 | |
535 template <typename Code, typename... Params> | |
536 Debug::Fault::Fault(const char* file, int line, Code code, | |
537 const char* condition, const char* macroArgs, Params&&... params) | |
538 : exception(nullptr) { | |
539 String argValues[sizeof...(Params)] = {str(params)...}; | |
540 init(file, line, code, condition, macroArgs, | |
541 arrayPtr(argValues, sizeof...(Params))); | |
542 } | |
543 | |
544 inline Debug::Fault::Fault(const char* file, int line, int osErrorNumber, | |
545 const char* condition, const char* macroArgs) | |
546 : exception(nullptr) { | |
547 init(file, line, osErrorNumber, condition, macroArgs, nullptr); | |
548 } | |
549 | |
550 inline Debug::Fault::Fault(const char* file, int line, kj::Exception::Type type, | |
551 const char* condition, const char* macroArgs) | |
552 : exception(nullptr) { | |
553 init(file, line, type, condition, macroArgs, nullptr); | |
554 } | |
555 | |
556 #if _WIN32 || __CYGWIN__ | |
557 inline Debug::Fault::Fault(const char* file, int line, Win32Result osErrorNumber, | |
558 const char* condition, const char* macroArgs) | |
559 : exception(nullptr) { | |
560 init(file, line, osErrorNumber, condition, macroArgs, nullptr); | |
561 } | |
562 | |
563 inline Debug::Win32Result Debug::win32Call(int boolean) { | |
564 return boolean ? Win32Result(0) : Win32Result(getWin32ErrorCode()); | |
565 } | |
566 inline Debug::Win32Result Debug::win32Call(void* handle) { | |
567 // Assume null and INVALID_HANDLE_VALUE mean failure. | |
568 return win32Call(handle != nullptr && handle != (void*)-1); | |
569 } | |
570 inline Debug::Win32Result Debug::winsockCall(int result) { | |
571 // Expect a return value of SOCKET_ERROR means failure. | |
572 return win32Call(result != -1); | |
573 } | |
574 #endif | |
575 | |
576 template <typename Call> | |
577 Debug::SyscallResult Debug::syscall(Call&& call, bool nonblocking) { | |
578 while (call() < 0) { | |
579 int errorNum = getOsErrorNumber(nonblocking); | |
580 // getOsErrorNumber() returns -1 to indicate EINTR. | |
581 // Also, if nonblocking is true, then it returns 0 on EAGAIN, which will then be treated as a | |
582 // non-error. | |
583 if (errorNum != -1) { | |
584 return SyscallResult(errorNum); | |
585 } | |
586 } | |
587 return SyscallResult(0); | |
588 } | |
589 | |
590 template <typename Call> | |
591 int Debug::syscallError(Call&& call, bool nonblocking) { | |
592 while (call() < 0) { | |
593 int errorNum = getOsErrorNumber(nonblocking); | |
594 // getOsErrorNumber() returns -1 to indicate EINTR. | |
595 // Also, if nonblocking is true, then it returns 0 on EAGAIN, which will then be treated as a | |
596 // non-error. | |
597 if (errorNum != -1) { | |
598 return errorNum; | |
599 } | |
600 } | |
601 return 0; | |
602 } | |
603 | |
604 template <typename... Params> | |
605 String Debug::makeDescription(const char* macroArgs, Params&&... params) { | |
606 String argValues[sizeof...(Params)] = {str(params)...}; | |
607 return makeDescriptionInternal(macroArgs, arrayPtr(argValues, sizeof...(Params))); | |
608 } | |
609 | |
610 template <> | |
611 inline String Debug::makeDescription<>(const char* macroArgs) { | |
612 return makeDescriptionInternal(macroArgs, nullptr); | |
613 } | |
614 | |
615 // ======================================================================================= | |
616 // Magic Asserts! | |
617 // | |
618 // When KJ_ASSERT(foo == bar) fails, `foo` and `bar`'s actual values will be stringified in the | |
619 // error message. How does it work? We use template magic and operator precedence. The assertion | |
620 // actually evaluates something like this: | |
621 // | |
622 // if (auto _kjCondition = kj::_::MAGIC_ASSERT << foo == bar) | |
623 // | |
624 // `<<` has operator precedence slightly above `==`, so `kj::_::MAGIC_ASSERT << foo` gets evaluated | |
625 // first. This wraps `foo` in a little wrapper that captures the comparison operators and keeps | |
626 // enough information around to be able to stringify the left and right sides of the comparison | |
627 // independently. As always, the stringification only actually occurs if the assert fails. | |
628 // | |
629 // You might ask why we use operator `<<` and not e.g. operator `<=`, since operators of the same | |
630 // precedence are evaluated left-to-right. The answer is that some compilers trigger all sorts of | |
631 // warnings when you seem to be using a comparison as the input to another comparison. The | |
632 // particular warning GCC produces is its general "-Wparentheses" warning which is broadly useful, | |
633 // so we don't want to disable it. `<<` also produces some warnings, but only on Clang and the | |
634 // specific warning is one we're comfortable disabling (see below). This does mean that we have to | |
635 // explicitly overload `operator<<` ourselves to make sure using it in an assert still works. | |
636 // | |
637 // You might also ask, if we're using operator `<<` anyway, why not start it from the right, in | |
638 // which case it would bind after computing any `<<` operators that were actually in the user's | |
639 // code? I tried this, but it resulted in a somewhat broader warning from clang that I felt worse | |
640 // about disabling (a warning about `<<` precedence not applying specifically to overloads) and | |
641 // also created ambiguous overload errors in the KJ units code. | |
642 | |
643 #if __clang__ | |
644 // We intentionally overload operator << for the specific purpose of evaluating it before | |
645 // evaluating comparison expressions, so stop Clang from warning about it. Unfortunately this means | |
646 // eliminating a warning that would otherwise be useful for people using iostreams... sorry. | |
647 #pragma GCC diagnostic ignored "-Woverloaded-shift-op-parentheses" | |
648 #endif | |
649 | |
650 template <typename T> | |
651 struct DebugExpression; | |
652 | |
653 template <typename T, typename = decltype(toCharSequence(instance<T&>()))> | |
654 inline auto tryToCharSequence(T* value) { return kj::toCharSequence(*value); } | |
655 inline StringPtr tryToCharSequence(...) { return "(can't stringify)"_kj; } | |
656 // SFINAE to stringify a value if and only if it can be stringified. | |
657 | |
658 template <typename Left, typename Right> | |
659 struct DebugComparison { | |
660 Left left; | |
661 Right right; | |
662 StringPtr op; | |
663 bool result; | |
664 | |
665 inline operator bool() const { return KJ_LIKELY(result); } | |
666 | |
667 template <typename T> inline void operator&(T&& other) = delete; | |
668 template <typename T> inline void operator^(T&& other) = delete; | |
669 template <typename T> inline void operator|(T&& other) = delete; | |
670 }; | |
671 | |
672 template <typename Left, typename Right> | |
673 String KJ_STRINGIFY(DebugComparison<Left, Right>& cmp) { | |
674 return _::concat(tryToCharSequence(&cmp.left), cmp.op, tryToCharSequence(&cmp.right)); | |
675 } | |
676 | |
677 template <typename T> | |
678 struct DebugExpression { | |
679 DebugExpression(T&& value): value(kj::fwd<T>(value)) {} | |
680 T value; | |
681 | |
682 // Handle comparison operations by constructing a DebugComparison value. | |
683 #define DEFINE_OPERATOR(OP) \ | |
684 template <typename U> \ | |
685 DebugComparison<T, U> operator OP(U&& other) { \ | |
686 bool result = value OP other; \ | |
687 return { kj::fwd<T>(value), kj::fwd<U>(other), " " #OP " "_kj, result }; \ | |
688 } | |
689 DEFINE_OPERATOR(==); | |
690 DEFINE_OPERATOR(!=); | |
691 DEFINE_OPERATOR(<=); | |
692 DEFINE_OPERATOR(>=); | |
693 DEFINE_OPERATOR(< ); | |
694 DEFINE_OPERATOR(> ); | |
695 #undef DEFINE_OPERATOR | |
696 | |
697 // Handle binary operators that have equal or lower precedence than comparisons by performing | |
698 // the operation and wrapping the result. | |
699 #define DEFINE_OPERATOR(OP) \ | |
700 template <typename U> inline auto operator OP(U&& other) { \ | |
701 return DebugExpression<decltype(kj::fwd<T>(value) OP kj::fwd<U>(other))>(\ | |
702 kj::fwd<T>(value) OP kj::fwd<U>(other)); \ | |
703 } | |
704 DEFINE_OPERATOR(<<); | |
705 DEFINE_OPERATOR(>>); | |
706 DEFINE_OPERATOR(&); | |
707 DEFINE_OPERATOR(^); | |
708 DEFINE_OPERATOR(|); | |
709 #undef DEFINE_OPERATOR | |
710 | |
711 inline operator bool() { | |
712 // No comparison performed, we're just asserting the expression is truthy. This also covers | |
713 // the case of the logic operators && and || -- we cannot overload those because doing so would | |
714 // break short-circuiting behavior. | |
715 return value; | |
716 } | |
717 }; | |
718 | |
719 template <typename T> | |
720 StringPtr KJ_STRINGIFY(const DebugExpression<T>& exp) { | |
721 // Hack: This will only ever be called in cases where the expression's truthiness was asserted | |
722 // directly, and was determined to be falsy. | |
723 return "false"_kj; | |
724 } | |
725 | |
726 struct DebugExpressionStart { | |
727 template <typename T> | |
728 DebugExpression<T> operator<<(T&& value) const { | |
729 return DebugExpression<T>(kj::fwd<T>(value)); | |
730 } | |
731 }; | |
732 static constexpr DebugExpressionStart MAGIC_ASSERT; | |
733 | |
734 } // namespace _ (private) | |
735 } // namespace kj | |
736 | |
737 KJ_END_HEADER |