annotate win32-mingw/include/kj/debug.h @ 163:5cc1366da2e9

Apply patch from Tim Bunnell on PortAudio mailing list (2016-12-28, Mac 10.11 deprecation warning)
author Chris Cannam <cannam@all-day-breakfast.com>
date Wed, 30 Oct 2019 11:28:45 +0000
parents 279b18cc7785
children
rev   line source
cannam@149 1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
cannam@149 2 // Licensed under the MIT License:
cannam@149 3 //
cannam@149 4 // Permission is hereby granted, free of charge, to any person obtaining a copy
cannam@149 5 // of this software and associated documentation files (the "Software"), to deal
cannam@149 6 // in the Software without restriction, including without limitation the rights
cannam@149 7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
cannam@149 8 // copies of the Software, and to permit persons to whom the Software is
cannam@149 9 // furnished to do so, subject to the following conditions:
cannam@149 10 //
cannam@149 11 // The above copyright notice and this permission notice shall be included in
cannam@149 12 // all copies or substantial portions of the Software.
cannam@149 13 //
cannam@149 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
cannam@149 15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
cannam@149 16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
cannam@149 17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
cannam@149 18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
cannam@149 19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
cannam@149 20 // THE SOFTWARE.
cannam@149 21
cannam@149 22 // This file declares convenient macros for debug logging and error handling. The macros make
cannam@149 23 // it excessively easy to extract useful context information from code. Example:
cannam@149 24 //
cannam@149 25 // KJ_ASSERT(a == b, a, b, "a and b must be the same.");
cannam@149 26 //
cannam@149 27 // On failure, this will throw an exception whose description looks like:
cannam@149 28 //
cannam@149 29 // myfile.c++:43: bug in code: expected a == b; a = 14; b = 72; a and b must be the same.
cannam@149 30 //
cannam@149 31 // As you can see, all arguments after the first provide additional context.
cannam@149 32 //
cannam@149 33 // The macros available are:
cannam@149 34 //
cannam@149 35 // * `KJ_LOG(severity, ...)`: Just writes a log message, to stderr by default (but you can
cannam@149 36 // intercept messages by implementing an ExceptionCallback). `severity` is `INFO`, `WARNING`,
cannam@149 37 // `ERROR`, or `FATAL`. By default, `INFO` logs are not written, but for command-line apps the
cannam@149 38 // user should be able to pass a flag like `--verbose` to enable them. Other log levels are
cannam@149 39 // enabled by default. Log messages -- like exceptions -- can be intercepted by registering an
cannam@149 40 // ExceptionCallback.
cannam@149 41 //
cannam@149 42 // * `KJ_DBG(...)`: Like `KJ_LOG`, but intended specifically for temporary log lines added while
cannam@149 43 // debugging a particular problem. Calls to `KJ_DBG` should always be deleted before committing
cannam@149 44 // code. It is suggested that you set up a pre-commit hook that checks for this.
cannam@149 45 //
cannam@149 46 // * `KJ_ASSERT(condition, ...)`: Throws an exception if `condition` is false, or aborts if
cannam@149 47 // exceptions are disabled. This macro should be used to check for bugs in the surrounding code
cannam@149 48 // and its dependencies, but NOT to check for invalid input. The macro may be followed by a
cannam@149 49 // brace-delimited code block; if so, the block will be executed in the case where the assertion
cannam@149 50 // fails, before throwing the exception. If control jumps out of the block (e.g. with "break",
cannam@149 51 // "return", or "goto"), then the error is considered "recoverable" -- in this case, if
cannam@149 52 // exceptions are disabled, execution will continue normally rather than aborting (but if
cannam@149 53 // exceptions are enabled, an exception will still be thrown on exiting the block). A "break"
cannam@149 54 // statement in particular will jump to the code immediately after the block (it does not break
cannam@149 55 // any surrounding loop or switch). Example:
cannam@149 56 //
cannam@149 57 // KJ_ASSERT(value >= 0, "Value cannot be negative.", value) {
cannam@149 58 // // Assertion failed. Set value to zero to "recover".
cannam@149 59 // value = 0;
cannam@149 60 // // Don't abort if exceptions are disabled. Continue normally.
cannam@149 61 // // (Still throw an exception if they are enabled, though.)
cannam@149 62 // break;
cannam@149 63 // }
cannam@149 64 // // When exceptions are disabled, we'll get here even if the assertion fails.
cannam@149 65 // // Otherwise, we get here only if the assertion passes.
cannam@149 66 //
cannam@149 67 // * `KJ_REQUIRE(condition, ...)`: Like `KJ_ASSERT` but used to check preconditions -- e.g. to
cannam@149 68 // validate parameters passed from a caller. A failure indicates that the caller is buggy.
cannam@149 69 //
cannam@149 70 // * `KJ_SYSCALL(code, ...)`: Executes `code` assuming it makes a system call. A negative result
cannam@149 71 // is considered an error, with error code reported via `errno`. EINTR is handled by retrying.
cannam@149 72 // Other errors are handled by throwing an exception. If you need to examine the return code,
cannam@149 73 // assign it to a variable like so:
cannam@149 74 //
cannam@149 75 // int fd;
cannam@149 76 // KJ_SYSCALL(fd = open(filename, O_RDONLY), filename);
cannam@149 77 //
cannam@149 78 // `KJ_SYSCALL` can be followed by a recovery block, just like `KJ_ASSERT`.
cannam@149 79 //
cannam@149 80 // * `KJ_NONBLOCKING_SYSCALL(code, ...)`: Like KJ_SYSCALL, but will not throw an exception on
cannam@149 81 // EAGAIN/EWOULDBLOCK. The calling code should check the syscall's return value to see if it
cannam@149 82 // indicates an error; in this case, it can assume the error was EAGAIN because any other error
cannam@149 83 // would have caused an exception to be thrown.
cannam@149 84 //
cannam@149 85 // * `KJ_CONTEXT(...)`: Notes additional contextual information relevant to any exceptions thrown
cannam@149 86 // from within the current scope. That is, until control exits the block in which KJ_CONTEXT()
cannam@149 87 // is used, if any exception is generated, it will contain the given information in its context
cannam@149 88 // chain. This is helpful because it can otherwise be very difficult to come up with error
cannam@149 89 // messages that make sense within low-level helper code. Note that the parameters to
cannam@149 90 // KJ_CONTEXT() are only evaluated if an exception is thrown. This implies that any variables
cannam@149 91 // used must remain valid until the end of the scope.
cannam@149 92 //
cannam@149 93 // Notes:
cannam@149 94 // * Do not write expressions with side-effects in the message content part of the macro, as the
cannam@149 95 // message will not necessarily be evaluated.
cannam@149 96 // * For every macro `FOO` above except `LOG`, there is also a `FAIL_FOO` macro used to report
cannam@149 97 // failures that already happened. For the macros that check a boolean condition, `FAIL_FOO`
cannam@149 98 // omits the first parameter and behaves like it was `false`. `FAIL_SYSCALL` and
cannam@149 99 // `FAIL_RECOVERABLE_SYSCALL` take a string and an OS error number as the first two parameters.
cannam@149 100 // The string should be the name of the failed system call.
cannam@149 101 // * For every macro `FOO` above, there is a `DFOO` version (or `RECOVERABLE_DFOO`) which is only
cannam@149 102 // executed in debug mode, i.e. when KJ_DEBUG is defined. KJ_DEBUG is defined automatically
cannam@149 103 // by common.h when compiling without optimization (unless NDEBUG is defined), but you can also
cannam@149 104 // define it explicitly (e.g. -DKJ_DEBUG). Generally, production builds should NOT use KJ_DEBUG
cannam@149 105 // as it may enable expensive checks that are unlikely to fail.
cannam@149 106
cannam@149 107 #ifndef KJ_DEBUG_H_
cannam@149 108 #define KJ_DEBUG_H_
cannam@149 109
cannam@149 110 #if defined(__GNUC__) && !KJ_HEADER_WARNINGS
cannam@149 111 #pragma GCC system_header
cannam@149 112 #endif
cannam@149 113
cannam@149 114 #include "string.h"
cannam@149 115 #include "exception.h"
cannam@149 116
cannam@149 117 #ifdef ERROR
cannam@149 118 // This is problematic because windows.h #defines ERROR, which we use in an enum here.
cannam@149 119 #error "Make sure to to undefine ERROR (or just #include <kj/windows-sanity.h>) before this file"
cannam@149 120 #endif
cannam@149 121
cannam@149 122 namespace kj {
cannam@149 123
cannam@149 124 #if _MSC_VER
cannam@149 125 // MSVC does __VA_ARGS__ differently from GCC:
cannam@149 126 // - A trailing comma before an empty __VA_ARGS__ is removed automatically, whereas GCC wants
cannam@149 127 // you to request this behavior with "##__VA_ARGS__".
cannam@149 128 // - If __VA_ARGS__ is passed directly as an argument to another macro, it will be treated as a
cannam@149 129 // *single* argument rather than an argument list. This can be worked around by wrapping the
cannam@149 130 // outer macro call in KJ_EXPAND(), which appraently forces __VA_ARGS__ to be expanded before
cannam@149 131 // the macro is evaluated. I don't understand the C preprocessor.
cannam@149 132 // - Using "#__VA_ARGS__" to stringify __VA_ARGS__ expands to zero tokens when __VA_ARGS__ is
cannam@149 133 // empty, rather than expanding to an empty string literal. We can work around by concatenating
cannam@149 134 // with an empty string literal.
cannam@149 135
cannam@149 136 #define KJ_EXPAND(X) X
cannam@149 137
cannam@149 138 #define KJ_LOG(severity, ...) \
cannam@149 139 if (!::kj::_::Debug::shouldLog(::kj::LogSeverity::severity)) {} else \
cannam@149 140 ::kj::_::Debug::log(__FILE__, __LINE__, ::kj::LogSeverity::severity, \
cannam@149 141 "" #__VA_ARGS__, __VA_ARGS__)
cannam@149 142
cannam@149 143 #define KJ_DBG(...) KJ_EXPAND(KJ_LOG(DBG, __VA_ARGS__))
cannam@149 144
cannam@149 145 #define KJ_REQUIRE(cond, ...) \
cannam@149 146 if (KJ_LIKELY(cond)) {} else \
cannam@149 147 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
cannam@149 148 #cond, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
cannam@149 149
cannam@149 150 #define KJ_FAIL_REQUIRE(...) \
cannam@149 151 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
cannam@149 152 nullptr, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
cannam@149 153
cannam@149 154 #define KJ_SYSCALL(call, ...) \
cannam@149 155 if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, false)) {} else \
cannam@149 156 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
cannam@149 157 _kjSyscallResult.getErrorNumber(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
cannam@149 158
cannam@149 159 #define KJ_NONBLOCKING_SYSCALL(call, ...) \
cannam@149 160 if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, true)) {} else \
cannam@149 161 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
cannam@149 162 _kjSyscallResult.getErrorNumber(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
cannam@149 163
cannam@149 164 #define KJ_FAIL_SYSCALL(code, errorNumber, ...) \
cannam@149 165 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
cannam@149 166 errorNumber, code, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
cannam@149 167
cannam@149 168 #if _WIN32
cannam@149 169
cannam@149 170 #define KJ_WIN32(call, ...) \
cannam@149 171 if (::kj::_::Debug::isWin32Success(call)) {} else \
cannam@149 172 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
cannam@149 173 ::kj::_::Debug::getWin32Error(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
cannam@149 174
cannam@149 175 #define KJ_WINSOCK(call, ...) \
cannam@149 176 if ((call) != SOCKET_ERROR) {} else \
cannam@149 177 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
cannam@149 178 ::kj::_::Debug::getWin32Error(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
cannam@149 179
cannam@149 180 #define KJ_FAIL_WIN32(code, errorNumber, ...) \
cannam@149 181 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
cannam@149 182 ::kj::_::Debug::Win32Error(errorNumber), code, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
cannam@149 183
cannam@149 184 #endif
cannam@149 185
cannam@149 186 #define KJ_UNIMPLEMENTED(...) \
cannam@149 187 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::UNIMPLEMENTED, \
cannam@149 188 nullptr, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
cannam@149 189
cannam@149 190 // TODO(msvc): MSVC mis-deduces `ContextImpl<decltype(func)>` as `ContextImpl<int>` in some edge
cannam@149 191 // cases, such as inside nested lambdas inside member functions. Wrapping the type in
cannam@149 192 // `decltype(instance<...>())` helps it deduce the context function's type correctly.
cannam@149 193 #define KJ_CONTEXT(...) \
cannam@149 194 auto KJ_UNIQUE_NAME(_kjContextFunc) = [&]() -> ::kj::_::Debug::Context::Value { \
cannam@149 195 return ::kj::_::Debug::Context::Value(__FILE__, __LINE__, \
cannam@149 196 ::kj::_::Debug::makeDescription("" #__VA_ARGS__, __VA_ARGS__)); \
cannam@149 197 }; \
cannam@149 198 decltype(::kj::instance<::kj::_::Debug::ContextImpl<decltype(KJ_UNIQUE_NAME(_kjContextFunc))>>()) \
cannam@149 199 KJ_UNIQUE_NAME(_kjContext)(KJ_UNIQUE_NAME(_kjContextFunc))
cannam@149 200
cannam@149 201 #define KJ_REQUIRE_NONNULL(value, ...) \
cannam@149 202 (*[&] { \
cannam@149 203 auto _kj_result = ::kj::_::readMaybe(value); \
cannam@149 204 if (KJ_UNLIKELY(!_kj_result)) { \
cannam@149 205 ::kj::_::Debug::Fault(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
cannam@149 206 #value " != nullptr", "" #__VA_ARGS__, __VA_ARGS__).fatal(); \
cannam@149 207 } \
cannam@149 208 return _kj_result; \
cannam@149 209 }())
cannam@149 210
cannam@149 211 #define KJ_EXCEPTION(type, ...) \
cannam@149 212 ::kj::Exception(::kj::Exception::Type::type, __FILE__, __LINE__, \
cannam@149 213 ::kj::_::Debug::makeDescription("" #__VA_ARGS__, __VA_ARGS__))
cannam@149 214
cannam@149 215 #else
cannam@149 216
cannam@149 217 #define KJ_LOG(severity, ...) \
cannam@149 218 if (!::kj::_::Debug::shouldLog(::kj::LogSeverity::severity)) {} else \
cannam@149 219 ::kj::_::Debug::log(__FILE__, __LINE__, ::kj::LogSeverity::severity, \
cannam@149 220 #__VA_ARGS__, ##__VA_ARGS__)
cannam@149 221
cannam@149 222 #define KJ_DBG(...) KJ_LOG(DBG, ##__VA_ARGS__)
cannam@149 223
cannam@149 224 #define KJ_REQUIRE(cond, ...) \
cannam@149 225 if (KJ_LIKELY(cond)) {} else \
cannam@149 226 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
cannam@149 227 #cond, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
cannam@149 228
cannam@149 229 #define KJ_FAIL_REQUIRE(...) \
cannam@149 230 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
cannam@149 231 nullptr, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
cannam@149 232
cannam@149 233 #define KJ_SYSCALL(call, ...) \
cannam@149 234 if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, false)) {} else \
cannam@149 235 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
cannam@149 236 _kjSyscallResult.getErrorNumber(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
cannam@149 237
cannam@149 238 #define KJ_NONBLOCKING_SYSCALL(call, ...) \
cannam@149 239 if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, true)) {} else \
cannam@149 240 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
cannam@149 241 _kjSyscallResult.getErrorNumber(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
cannam@149 242
cannam@149 243 #define KJ_FAIL_SYSCALL(code, errorNumber, ...) \
cannam@149 244 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
cannam@149 245 errorNumber, code, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
cannam@149 246
cannam@149 247 #if _WIN32
cannam@149 248
cannam@149 249 #define KJ_WIN32(call, ...) \
cannam@149 250 if (::kj::_::Debug::isWin32Success(call)) {} else \
cannam@149 251 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
cannam@149 252 ::kj::_::Debug::getWin32Error(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
cannam@149 253
cannam@149 254 #define KJ_WINSOCK(call, ...) \
cannam@149 255 if ((call) != SOCKET_ERROR) {} else \
cannam@149 256 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
cannam@149 257 ::kj::_::Debug::getWin32Error(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
cannam@149 258
cannam@149 259 #define KJ_FAIL_WIN32(code, errorNumber, ...) \
cannam@149 260 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
cannam@149 261 ::kj::_::Debug::Win32Error(errorNumber), code, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
cannam@149 262
cannam@149 263 #endif
cannam@149 264
cannam@149 265 #define KJ_UNIMPLEMENTED(...) \
cannam@149 266 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::UNIMPLEMENTED, \
cannam@149 267 nullptr, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
cannam@149 268
cannam@149 269 #define KJ_CONTEXT(...) \
cannam@149 270 auto KJ_UNIQUE_NAME(_kjContextFunc) = [&]() -> ::kj::_::Debug::Context::Value { \
cannam@149 271 return ::kj::_::Debug::Context::Value(__FILE__, __LINE__, \
cannam@149 272 ::kj::_::Debug::makeDescription(#__VA_ARGS__, ##__VA_ARGS__)); \
cannam@149 273 }; \
cannam@149 274 ::kj::_::Debug::ContextImpl<decltype(KJ_UNIQUE_NAME(_kjContextFunc))> \
cannam@149 275 KJ_UNIQUE_NAME(_kjContext)(KJ_UNIQUE_NAME(_kjContextFunc))
cannam@149 276
cannam@149 277 #define KJ_REQUIRE_NONNULL(value, ...) \
cannam@149 278 (*({ \
cannam@149 279 auto _kj_result = ::kj::_::readMaybe(value); \
cannam@149 280 if (KJ_UNLIKELY(!_kj_result)) { \
cannam@149 281 ::kj::_::Debug::Fault(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
cannam@149 282 #value " != nullptr", #__VA_ARGS__, ##__VA_ARGS__).fatal(); \
cannam@149 283 } \
cannam@149 284 kj::mv(_kj_result); \
cannam@149 285 }))
cannam@149 286
cannam@149 287 #define KJ_EXCEPTION(type, ...) \
cannam@149 288 ::kj::Exception(::kj::Exception::Type::type, __FILE__, __LINE__, \
cannam@149 289 ::kj::_::Debug::makeDescription(#__VA_ARGS__, ##__VA_ARGS__))
cannam@149 290
cannam@149 291 #endif
cannam@149 292
cannam@149 293 #define KJ_SYSCALL_HANDLE_ERRORS(call) \
cannam@149 294 if (int _kjSyscallError = ::kj::_::Debug::syscallError([&](){return (call);}, false)) \
cannam@149 295 switch (int error = _kjSyscallError)
cannam@149 296 // Like KJ_SYSCALL, but doesn't throw. Instead, the block after the macro is a switch block on the
cannam@149 297 // error. Additionally, the int value `error` is defined within the block. So you can do:
cannam@149 298 //
cannam@149 299 // KJ_SYSCALL_HANDLE_ERRORS(foo()) {
cannam@149 300 // case ENOENT:
cannam@149 301 // handleNoSuchFile();
cannam@149 302 // break;
cannam@149 303 // case EEXIST:
cannam@149 304 // handleExists();
cannam@149 305 // break;
cannam@149 306 // default:
cannam@149 307 // KJ_FAIL_SYSCALL("foo()", error);
cannam@149 308 // } else {
cannam@149 309 // handleSuccessCase();
cannam@149 310 // }
cannam@149 311
cannam@149 312 #define KJ_ASSERT KJ_REQUIRE
cannam@149 313 #define KJ_FAIL_ASSERT KJ_FAIL_REQUIRE
cannam@149 314 #define KJ_ASSERT_NONNULL KJ_REQUIRE_NONNULL
cannam@149 315 // Use "ASSERT" in place of "REQUIRE" when the problem is local to the immediate surrounding code.
cannam@149 316 // That is, if the assert ever fails, it indicates that the immediate surrounding code is broken.
cannam@149 317
cannam@149 318 #ifdef KJ_DEBUG
cannam@149 319 #define KJ_DLOG KJ_LOG
cannam@149 320 #define KJ_DASSERT KJ_ASSERT
cannam@149 321 #define KJ_DREQUIRE KJ_REQUIRE
cannam@149 322 #else
cannam@149 323 #define KJ_DLOG(...) do {} while (false)
cannam@149 324 #define KJ_DASSERT(...) do {} while (false)
cannam@149 325 #define KJ_DREQUIRE(...) do {} while (false)
cannam@149 326 #endif
cannam@149 327
cannam@149 328 namespace _ { // private
cannam@149 329
cannam@149 330 class Debug {
cannam@149 331 public:
cannam@149 332 Debug() = delete;
cannam@149 333
cannam@149 334 typedef LogSeverity Severity; // backwards-compatibility
cannam@149 335
cannam@149 336 #if _WIN32
cannam@149 337 struct Win32Error {
cannam@149 338 // Hack for overloading purposes.
cannam@149 339 uint number;
cannam@149 340 inline explicit Win32Error(uint number): number(number) {}
cannam@149 341 };
cannam@149 342 #endif
cannam@149 343
cannam@149 344 static inline bool shouldLog(LogSeverity severity) { return severity >= minSeverity; }
cannam@149 345 // Returns whether messages of the given severity should be logged.
cannam@149 346
cannam@149 347 static inline void setLogLevel(LogSeverity severity) { minSeverity = severity; }
cannam@149 348 // Set the minimum message severity which will be logged.
cannam@149 349 //
cannam@149 350 // TODO(someday): Expose publicly.
cannam@149 351
cannam@149 352 template <typename... Params>
cannam@149 353 static void log(const char* file, int line, LogSeverity severity, const char* macroArgs,
cannam@149 354 Params&&... params);
cannam@149 355
cannam@149 356 class Fault {
cannam@149 357 public:
cannam@149 358 template <typename Code, typename... Params>
cannam@149 359 Fault(const char* file, int line, Code code,
cannam@149 360 const char* condition, const char* macroArgs, Params&&... params);
cannam@149 361 Fault(const char* file, int line, Exception::Type type,
cannam@149 362 const char* condition, const char* macroArgs);
cannam@149 363 Fault(const char* file, int line, int osErrorNumber,
cannam@149 364 const char* condition, const char* macroArgs);
cannam@149 365 #if _WIN32
cannam@149 366 Fault(const char* file, int line, Win32Error osErrorNumber,
cannam@149 367 const char* condition, const char* macroArgs);
cannam@149 368 #endif
cannam@149 369 ~Fault() noexcept(false);
cannam@149 370
cannam@149 371 KJ_NOINLINE KJ_NORETURN(void fatal());
cannam@149 372 // Throw the exception.
cannam@149 373
cannam@149 374 private:
cannam@149 375 void init(const char* file, int line, Exception::Type type,
cannam@149 376 const char* condition, const char* macroArgs, ArrayPtr<String> argValues);
cannam@149 377 void init(const char* file, int line, int osErrorNumber,
cannam@149 378 const char* condition, const char* macroArgs, ArrayPtr<String> argValues);
cannam@149 379 #if _WIN32
cannam@149 380 void init(const char* file, int line, Win32Error osErrorNumber,
cannam@149 381 const char* condition, const char* macroArgs, ArrayPtr<String> argValues);
cannam@149 382 #endif
cannam@149 383
cannam@149 384 Exception* exception;
cannam@149 385 };
cannam@149 386
cannam@149 387 class SyscallResult {
cannam@149 388 public:
cannam@149 389 inline SyscallResult(int errorNumber): errorNumber(errorNumber) {}
cannam@149 390 inline operator void*() { return errorNumber == 0 ? this : nullptr; }
cannam@149 391 inline int getErrorNumber() { return errorNumber; }
cannam@149 392
cannam@149 393 private:
cannam@149 394 int errorNumber;
cannam@149 395 };
cannam@149 396
cannam@149 397 template <typename Call>
cannam@149 398 static SyscallResult syscall(Call&& call, bool nonblocking);
cannam@149 399 template <typename Call>
cannam@149 400 static int syscallError(Call&& call, bool nonblocking);
cannam@149 401
cannam@149 402 #if _WIN32
cannam@149 403 static bool isWin32Success(int boolean);
cannam@149 404 static bool isWin32Success(void* handle);
cannam@149 405 static Win32Error getWin32Error();
cannam@149 406 #endif
cannam@149 407
cannam@149 408 class Context: public ExceptionCallback {
cannam@149 409 public:
cannam@149 410 Context();
cannam@149 411 KJ_DISALLOW_COPY(Context);
cannam@149 412 virtual ~Context() noexcept(false);
cannam@149 413
cannam@149 414 struct Value {
cannam@149 415 const char* file;
cannam@149 416 int line;
cannam@149 417 String description;
cannam@149 418
cannam@149 419 inline Value(const char* file, int line, String&& description)
cannam@149 420 : file(file), line(line), description(mv(description)) {}
cannam@149 421 };
cannam@149 422
cannam@149 423 virtual Value evaluate() = 0;
cannam@149 424
cannam@149 425 virtual void onRecoverableException(Exception&& exception) override;
cannam@149 426 virtual void onFatalException(Exception&& exception) override;
cannam@149 427 virtual void logMessage(LogSeverity severity, const char* file, int line, int contextDepth,
cannam@149 428 String&& text) override;
cannam@149 429
cannam@149 430 private:
cannam@149 431 bool logged;
cannam@149 432 Maybe<Value> value;
cannam@149 433
cannam@149 434 Value ensureInitialized();
cannam@149 435 };
cannam@149 436
cannam@149 437 template <typename Func>
cannam@149 438 class ContextImpl: public Context {
cannam@149 439 public:
cannam@149 440 inline ContextImpl(Func& func): func(func) {}
cannam@149 441 KJ_DISALLOW_COPY(ContextImpl);
cannam@149 442
cannam@149 443 Value evaluate() override {
cannam@149 444 return func();
cannam@149 445 }
cannam@149 446 private:
cannam@149 447 Func& func;
cannam@149 448 };
cannam@149 449
cannam@149 450 template <typename... Params>
cannam@149 451 static String makeDescription(const char* macroArgs, Params&&... params);
cannam@149 452
cannam@149 453 private:
cannam@149 454 static LogSeverity minSeverity;
cannam@149 455
cannam@149 456 static void logInternal(const char* file, int line, LogSeverity severity, const char* macroArgs,
cannam@149 457 ArrayPtr<String> argValues);
cannam@149 458 static String makeDescriptionInternal(const char* macroArgs, ArrayPtr<String> argValues);
cannam@149 459
cannam@149 460 static int getOsErrorNumber(bool nonblocking);
cannam@149 461 // Get the error code of the last error (e.g. from errno). Returns -1 on EINTR.
cannam@149 462 };
cannam@149 463
cannam@149 464 template <typename... Params>
cannam@149 465 void Debug::log(const char* file, int line, LogSeverity severity, const char* macroArgs,
cannam@149 466 Params&&... params) {
cannam@149 467 String argValues[sizeof...(Params)] = {str(params)...};
cannam@149 468 logInternal(file, line, severity, macroArgs, arrayPtr(argValues, sizeof...(Params)));
cannam@149 469 }
cannam@149 470
cannam@149 471 template <>
cannam@149 472 inline void Debug::log<>(const char* file, int line, LogSeverity severity, const char* macroArgs) {
cannam@149 473 logInternal(file, line, severity, macroArgs, nullptr);
cannam@149 474 }
cannam@149 475
cannam@149 476 template <typename Code, typename... Params>
cannam@149 477 Debug::Fault::Fault(const char* file, int line, Code code,
cannam@149 478 const char* condition, const char* macroArgs, Params&&... params)
cannam@149 479 : exception(nullptr) {
cannam@149 480 String argValues[sizeof...(Params)] = {str(params)...};
cannam@149 481 init(file, line, code, condition, macroArgs,
cannam@149 482 arrayPtr(argValues, sizeof...(Params)));
cannam@149 483 }
cannam@149 484
cannam@149 485 inline Debug::Fault::Fault(const char* file, int line, int osErrorNumber,
cannam@149 486 const char* condition, const char* macroArgs)
cannam@149 487 : exception(nullptr) {
cannam@149 488 init(file, line, osErrorNumber, condition, macroArgs, nullptr);
cannam@149 489 }
cannam@149 490
cannam@149 491 inline Debug::Fault::Fault(const char* file, int line, kj::Exception::Type type,
cannam@149 492 const char* condition, const char* macroArgs)
cannam@149 493 : exception(nullptr) {
cannam@149 494 init(file, line, type, condition, macroArgs, nullptr);
cannam@149 495 }
cannam@149 496
cannam@149 497 #if _WIN32
cannam@149 498 inline Debug::Fault::Fault(const char* file, int line, Win32Error osErrorNumber,
cannam@149 499 const char* condition, const char* macroArgs)
cannam@149 500 : exception(nullptr) {
cannam@149 501 init(file, line, osErrorNumber, condition, macroArgs, nullptr);
cannam@149 502 }
cannam@149 503
cannam@149 504 inline bool Debug::isWin32Success(int boolean) {
cannam@149 505 return boolean;
cannam@149 506 }
cannam@149 507 inline bool Debug::isWin32Success(void* handle) {
cannam@149 508 // Assume null and INVALID_HANDLE_VALUE mean failure.
cannam@149 509 return handle != nullptr && handle != (void*)-1;
cannam@149 510 }
cannam@149 511 #endif
cannam@149 512
cannam@149 513 template <typename Call>
cannam@149 514 Debug::SyscallResult Debug::syscall(Call&& call, bool nonblocking) {
cannam@149 515 while (call() < 0) {
cannam@149 516 int errorNum = getOsErrorNumber(nonblocking);
cannam@149 517 // getOsErrorNumber() returns -1 to indicate EINTR.
cannam@149 518 // Also, if nonblocking is true, then it returns 0 on EAGAIN, which will then be treated as a
cannam@149 519 // non-error.
cannam@149 520 if (errorNum != -1) {
cannam@149 521 return SyscallResult(errorNum);
cannam@149 522 }
cannam@149 523 }
cannam@149 524 return SyscallResult(0);
cannam@149 525 }
cannam@149 526
cannam@149 527 template <typename Call>
cannam@149 528 int Debug::syscallError(Call&& call, bool nonblocking) {
cannam@149 529 while (call() < 0) {
cannam@149 530 int errorNum = getOsErrorNumber(nonblocking);
cannam@149 531 // getOsErrorNumber() returns -1 to indicate EINTR.
cannam@149 532 // Also, if nonblocking is true, then it returns 0 on EAGAIN, which will then be treated as a
cannam@149 533 // non-error.
cannam@149 534 if (errorNum != -1) {
cannam@149 535 return errorNum;
cannam@149 536 }
cannam@149 537 }
cannam@149 538 return 0;
cannam@149 539 }
cannam@149 540
cannam@149 541 template <typename... Params>
cannam@149 542 String Debug::makeDescription(const char* macroArgs, Params&&... params) {
cannam@149 543 String argValues[sizeof...(Params)] = {str(params)...};
cannam@149 544 return makeDescriptionInternal(macroArgs, arrayPtr(argValues, sizeof...(Params)));
cannam@149 545 }
cannam@149 546
cannam@149 547 template <>
cannam@149 548 inline String Debug::makeDescription<>(const char* macroArgs) {
cannam@149 549 return makeDescriptionInternal(macroArgs, nullptr);
cannam@149 550 }
cannam@149 551
cannam@149 552 } // namespace _ (private)
cannam@149 553 } // namespace kj
cannam@149 554
cannam@149 555 #endif // KJ_DEBUG_H_