annotate win64-msvc/include/kj/debug.h @ 64:eccd51b72864

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