capnproto

FORK: Cap'n Proto serialization/RPC system - core tools and C++ library
git clone https://git.neptards.moe/neptards/capnproto.git
Log | Files | Refs | README | LICENSE

debug.h (29767B)


      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_SYSCALL(code, ...)`:  Executes `code` assuming it makes a system call.  A negative result
     71 //   is considered an error, with error code reported via `errno`.  EINTR is handled by retrying.
     72 //   Other errors are handled by throwing an exception.  If you need to examine the return code,
     73 //   assign it to a variable like so:
     74 //
     75 //       int fd;
     76 //       KJ_SYSCALL(fd = open(filename, O_RDONLY), filename);
     77 //
     78 //   `KJ_SYSCALL` can be followed by a recovery block, just like `KJ_ASSERT`.
     79 //
     80 // * `KJ_NONBLOCKING_SYSCALL(code, ...)`:  Like KJ_SYSCALL, but will not throw an exception on
     81 //   EAGAIN/EWOULDBLOCK.  The calling code should check the syscall's return value to see if it
     82 //   indicates an error; in this case, it can assume the error was EAGAIN because any other error
     83 //   would have caused an exception to be thrown.
     84 //
     85 // * `KJ_CONTEXT(...)`:  Notes additional contextual information relevant to any exceptions thrown
     86 //   from within the current scope.  That is, until control exits the block in which KJ_CONTEXT()
     87 //   is used, if any exception is generated, it will contain the given information in its context
     88 //   chain.  This is helpful because it can otherwise be very difficult to come up with error
     89 //   messages that make sense within low-level helper code.  Note that the parameters to
     90 //   KJ_CONTEXT() are only evaluated if an exception is thrown.  This implies that any variables
     91 //   used must remain valid until the end of the scope.
     92 //
     93 // Notes:
     94 // * Do not write expressions with side-effects in the message content part of the macro, as the
     95 //   message will not necessarily be evaluated.
     96 // * For every macro `FOO` above except `LOG`, there is also a `FAIL_FOO` macro used to report
     97 //   failures that already happened.  For the macros that check a boolean condition, `FAIL_FOO`
     98 //   omits the first parameter and behaves like it was `false`.  `FAIL_SYSCALL` and
     99 //   `FAIL_RECOVERABLE_SYSCALL` take a string and an OS error number as the first two parameters.
    100 //   The string should be the name of the failed system call.
    101 // * For every macro `FOO` above, there is a `DFOO` version (or `RECOVERABLE_DFOO`) which is only
    102 //   executed in debug mode, i.e. when KJ_DEBUG is defined.  KJ_DEBUG is defined automatically
    103 //   by common.h when compiling without optimization (unless NDEBUG is defined), but you can also
    104 //   define it explicitly (e.g. -DKJ_DEBUG).  Generally, production builds should NOT use KJ_DEBUG
    105 //   as it may enable expensive checks that are unlikely to fail.
    106 
    107 #pragma once
    108 
    109 #include "string.h"
    110 #include "exception.h"
    111 #include "windows-sanity.h"  // work-around macro conflict with `ERROR`
    112 
    113 KJ_BEGIN_HEADER
    114 
    115 namespace kj {
    116 
    117 #if _MSC_VER && !defined(__clang__)
    118 // MSVC does __VA_ARGS__ differently from GCC:
    119 // - A trailing comma before an empty __VA_ARGS__ is removed automatically, whereas GCC wants
    120 //   you to request this behavior with "##__VA_ARGS__".
    121 // - If __VA_ARGS__ is passed directly as an argument to another macro, it will be treated as a
    122 //   *single* argument rather than an argument list. This can be worked around by wrapping the
    123 //   outer macro call in KJ_EXPAND(), which apparently forces __VA_ARGS__ to be expanded before
    124 //   the macro is evaluated. I don't understand the C preprocessor.
    125 // - Using "#__VA_ARGS__" to stringify __VA_ARGS__ expands to zero tokens when __VA_ARGS__ is
    126 //   empty, rather than expanding to an empty string literal. We can work around by concatenating
    127 //   with an empty string literal.
    128 
    129 #define KJ_EXPAND(X) X
    130 
    131 #define KJ_LOG(severity, ...) \
    132   for (bool _kj_shouldLog = ::kj::_::Debug::shouldLog(::kj::LogSeverity::severity); \
    133        _kj_shouldLog; _kj_shouldLog = false) \
    134     ::kj::_::Debug::log(__FILE__, __LINE__, ::kj::LogSeverity::severity, \
    135                         "" #__VA_ARGS__, __VA_ARGS__)
    136 
    137 #define KJ_DBG(...) KJ_EXPAND(KJ_LOG(DBG, __VA_ARGS__))
    138 
    139 #define KJ_REQUIRE(cond, ...) \
    140   if (auto _kjCondition = ::kj::_::MAGIC_ASSERT << cond) {} else \
    141     for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
    142         #cond, "_kjCondition," #__VA_ARGS__, _kjCondition, __VA_ARGS__);; f.fatal())
    143 
    144 #define KJ_FAIL_REQUIRE(...) \
    145   for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
    146                                nullptr, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
    147 
    148 #define KJ_SYSCALL(call, ...) \
    149   if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, false)) {} else \
    150     for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
    151              _kjSyscallResult.getErrorNumber(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
    152 
    153 #define KJ_NONBLOCKING_SYSCALL(call, ...) \
    154   if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, true)) {} else \
    155     for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
    156              _kjSyscallResult.getErrorNumber(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
    157 
    158 #define KJ_FAIL_SYSCALL(code, errorNumber, ...) \
    159   for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
    160            errorNumber, code, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
    161 
    162 #if _WIN32 || __CYGWIN__
    163 
    164 #define KJ_WIN32(call, ...) \
    165   if (auto _kjWin32Result = ::kj::_::Debug::win32Call(call)) {} else \
    166     for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
    167              _kjWin32Result, #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
    168 
    169 #define KJ_WINSOCK(call, ...) \
    170   if (auto _kjWin32Result = ::kj::_::Debug::winsockCall(call)) {} else \
    171     for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
    172              _kjWin32Result, #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
    173 
    174 #define KJ_FAIL_WIN32(code, errorNumber, ...) \
    175   for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
    176            ::kj::_::Debug::Win32Result(errorNumber), code, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
    177 
    178 #endif
    179 
    180 #define KJ_UNIMPLEMENTED(...) \
    181   for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::UNIMPLEMENTED, \
    182                                nullptr, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
    183 
    184 // TODO(msvc):  MSVC mis-deduces `ContextImpl<decltype(func)>` as `ContextImpl<int>` in some edge
    185 // cases, such as inside nested lambdas inside member functions. Wrapping the type in
    186 // `decltype(instance<...>())` helps it deduce the context function's type correctly.
    187 #define KJ_CONTEXT(...) \
    188   auto KJ_UNIQUE_NAME(_kjContextFunc) = [&]() -> ::kj::_::Debug::Context::Value { \
    189         return ::kj::_::Debug::Context::Value(__FILE__, __LINE__, \
    190             ::kj::_::Debug::makeDescription("" #__VA_ARGS__, __VA_ARGS__)); \
    191       }; \
    192   decltype(::kj::instance<::kj::_::Debug::ContextImpl<decltype(KJ_UNIQUE_NAME(_kjContextFunc))>>()) \
    193       KJ_UNIQUE_NAME(_kjContext)(KJ_UNIQUE_NAME(_kjContextFunc))
    194 
    195 #define KJ_REQUIRE_NONNULL(value, ...) \
    196   (*[&] { \
    197     auto _kj_result = ::kj::_::readMaybe(value); \
    198     if (KJ_UNLIKELY(!_kj_result)) { \
    199       ::kj::_::Debug::Fault(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
    200                             #value " != nullptr", "" #__VA_ARGS__, __VA_ARGS__).fatal(); \
    201     } \
    202     return _kj_result; \
    203   }())
    204 
    205 #define KJ_EXCEPTION(type, ...) \
    206   ::kj::Exception(::kj::Exception::Type::type, __FILE__, __LINE__, \
    207       ::kj::_::Debug::makeDescription("" #__VA_ARGS__, __VA_ARGS__))
    208 
    209 #else
    210 
    211 #define KJ_LOG(severity, ...) \
    212   for (bool _kj_shouldLog = ::kj::_::Debug::shouldLog(::kj::LogSeverity::severity); \
    213        _kj_shouldLog; _kj_shouldLog = false) \
    214     ::kj::_::Debug::log(__FILE__, __LINE__, ::kj::LogSeverity::severity, \
    215                         #__VA_ARGS__, ##__VA_ARGS__)
    216 
    217 #define KJ_DBG(...) KJ_LOG(DBG, ##__VA_ARGS__)
    218 
    219 #define KJ_REQUIRE(cond, ...) \
    220   if (auto _kjCondition = ::kj::_::MAGIC_ASSERT << cond) {} else \
    221     for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
    222         #cond, "_kjCondition," #__VA_ARGS__, _kjCondition, ##__VA_ARGS__);; f.fatal())
    223 
    224 #define KJ_FAIL_REQUIRE(...) \
    225   for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
    226                                nullptr, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
    227 
    228 #define KJ_SYSCALL(call, ...) \
    229   if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, false)) {} else \
    230     for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
    231              _kjSyscallResult.getErrorNumber(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
    232 
    233 #define KJ_NONBLOCKING_SYSCALL(call, ...) \
    234   if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, true)) {} else \
    235     for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
    236              _kjSyscallResult.getErrorNumber(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
    237 
    238 #define KJ_FAIL_SYSCALL(code, errorNumber, ...) \
    239   for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
    240            errorNumber, code, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
    241 
    242 #if _WIN32 || __CYGWIN__
    243 
    244 #define KJ_WIN32(call, ...) \
    245   if (auto _kjWin32Result = ::kj::_::Debug::win32Call(call)) {} else \
    246     for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
    247              _kjWin32Result, #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
    248 // Invoke a Win32 syscall that returns either BOOL or HANDLE, and throw an exception if it fails.
    249 
    250 #define KJ_WINSOCK(call, ...) \
    251   if (auto _kjWin32Result = ::kj::_::Debug::winsockCall(call)) {} else \
    252     for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
    253              _kjWin32Result, #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
    254 // Like KJ_WIN32 but for winsock calls which return `int` with SOCKET_ERROR indicating failure.
    255 //
    256 // Unfortunately, it's impossible to distinguish these from BOOL-returning Win32 calls by type,
    257 // since BOOL is in fact an alias for `int`. :(
    258 
    259 #define KJ_FAIL_WIN32(code, errorNumber, ...) \
    260   for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
    261            ::kj::_::Debug::Win32Result(errorNumber), code, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
    262 
    263 #endif
    264 
    265 #define KJ_UNIMPLEMENTED(...) \
    266   for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::UNIMPLEMENTED, \
    267                                nullptr, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
    268 
    269 #define KJ_CONTEXT(...) \
    270   auto KJ_UNIQUE_NAME(_kjContextFunc) = [&]() -> ::kj::_::Debug::Context::Value { \
    271         return ::kj::_::Debug::Context::Value(__FILE__, __LINE__, \
    272             ::kj::_::Debug::makeDescription(#__VA_ARGS__, ##__VA_ARGS__)); \
    273       }; \
    274   ::kj::_::Debug::ContextImpl<decltype(KJ_UNIQUE_NAME(_kjContextFunc))> \
    275       KJ_UNIQUE_NAME(_kjContext)(KJ_UNIQUE_NAME(_kjContextFunc))
    276 
    277 #define KJ_REQUIRE_NONNULL(value, ...) \
    278   (*({ \
    279     auto _kj_result = ::kj::_::readMaybe(value); \
    280     if (KJ_UNLIKELY(!_kj_result)) { \
    281       ::kj::_::Debug::Fault(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
    282                             #value " != nullptr", #__VA_ARGS__, ##__VA_ARGS__).fatal(); \
    283     } \
    284     kj::mv(_kj_result); \
    285   }))
    286 
    287 #define KJ_EXCEPTION(type, ...) \
    288   ::kj::Exception(::kj::Exception::Type::type, __FILE__, __LINE__, \
    289       ::kj::_::Debug::makeDescription(#__VA_ARGS__, ##__VA_ARGS__))
    290 
    291 #endif
    292 
    293 #define KJ_SYSCALL_HANDLE_ERRORS(call) \
    294   if (int _kjSyscallError = ::kj::_::Debug::syscallError([&](){return (call);}, false)) \
    295     switch (int error KJ_UNUSED = _kjSyscallError)
    296 // Like KJ_SYSCALL, but doesn't throw. Instead, the block after the macro is a switch block on the
    297 // error. Additionally, the int value `error` is defined within the block. So you can do:
    298 //
    299 //     KJ_SYSCALL_HANDLE_ERRORS(foo()) {
    300 //       case ENOENT:
    301 //         handleNoSuchFile();
    302 //         break;
    303 //       case EEXIST:
    304 //         handleExists();
    305 //         break;
    306 //       default:
    307 //         KJ_FAIL_SYSCALL("foo()", error);
    308 //     } else {
    309 //       handleSuccessCase();
    310 //     }
    311 
    312 #if _WIN32 || __CYGWIN__
    313 
    314 #define KJ_WIN32_HANDLE_ERRORS(call) \
    315   if (uint _kjWin32Error = ::kj::_::Debug::win32Call(call).number) \
    316     switch (uint error KJ_UNUSED = _kjWin32Error)
    317 // Like KJ_WIN32, but doesn't throw. Instead, the block after the macro is a switch block on the
    318 // error. Additionally, the int value `error` is defined within the block. So you can do:
    319 //
    320 //     KJ_SYSCALL_HANDLE_ERRORS(foo()) {
    321 //       case ERROR_FILE_NOT_FOUND:
    322 //         handleNoSuchFile();
    323 //         break;
    324 //       case ERROR_FILE_EXISTS:
    325 //         handleExists();
    326 //         break;
    327 //       default:
    328 //         KJ_FAIL_WIN32("foo()", error);
    329 //     } else {
    330 //       handleSuccessCase();
    331 //     }
    332 
    333 #endif
    334 
    335 #define KJ_ASSERT KJ_REQUIRE
    336 #define KJ_FAIL_ASSERT KJ_FAIL_REQUIRE
    337 #define KJ_ASSERT_NONNULL KJ_REQUIRE_NONNULL
    338 // Use "ASSERT" in place of "REQUIRE" when the problem is local to the immediate surrounding code.
    339 // That is, if the assert ever fails, it indicates that the immediate surrounding code is broken.
    340 
    341 #ifdef KJ_DEBUG
    342 #define KJ_DLOG KJ_LOG
    343 #define KJ_DASSERT KJ_ASSERT
    344 #define KJ_DREQUIRE KJ_REQUIRE
    345 #else
    346 #define KJ_DLOG(...) do {} while (false)
    347 #define KJ_DASSERT(...) do {} while (false)
    348 #define KJ_DREQUIRE(...) do {} while (false)
    349 #endif
    350 
    351 namespace _ {  // private
    352 
    353 class Debug {
    354 public:
    355   Debug() = delete;
    356 
    357   typedef LogSeverity Severity;  // backwards-compatibility
    358 
    359 #if _WIN32 || __CYGWIN__
    360   struct Win32Result {
    361     uint number;
    362     inline explicit Win32Result(uint number): number(number) {}
    363     operator bool() const { return number == 0; }
    364   };
    365 #endif
    366 
    367   static inline bool shouldLog(LogSeverity severity) { return severity >= minSeverity; }
    368   // Returns whether messages of the given severity should be logged.
    369 
    370   static inline void setLogLevel(LogSeverity severity) { minSeverity = severity; }
    371   // Set the minimum message severity which will be logged.
    372   //
    373   // TODO(someday):  Expose publicly.
    374 
    375   template <typename... Params>
    376   static void log(const char* file, int line, LogSeverity severity, const char* macroArgs,
    377                   Params&&... params);
    378 
    379   class Fault {
    380   public:
    381     template <typename Code, typename... Params>
    382     Fault(const char* file, int line, Code code,
    383           const char* condition, const char* macroArgs, Params&&... params);
    384     Fault(const char* file, int line, Exception::Type type,
    385           const char* condition, const char* macroArgs);
    386     Fault(const char* file, int line, int osErrorNumber,
    387           const char* condition, const char* macroArgs);
    388 #if _WIN32 || __CYGWIN__
    389     Fault(const char* file, int line, Win32Result osErrorNumber,
    390           const char* condition, const char* macroArgs);
    391 #endif
    392     ~Fault() noexcept(false);
    393 
    394     KJ_NOINLINE KJ_NORETURN(void fatal());
    395     // Throw the exception.
    396 
    397   private:
    398     void init(const char* file, int line, Exception::Type type,
    399               const char* condition, const char* macroArgs, ArrayPtr<String> argValues);
    400     void init(const char* file, int line, int osErrorNumber,
    401               const char* condition, const char* macroArgs, ArrayPtr<String> argValues);
    402 #if _WIN32 || __CYGWIN__
    403     void init(const char* file, int line, Win32Result osErrorNumber,
    404               const char* condition, const char* macroArgs, ArrayPtr<String> argValues);
    405 #endif
    406 
    407     Exception* exception;
    408   };
    409 
    410   class SyscallResult {
    411   public:
    412     inline SyscallResult(int errorNumber): errorNumber(errorNumber) {}
    413     inline operator void*() { return errorNumber == 0 ? this : nullptr; }
    414     inline int getErrorNumber() { return errorNumber; }
    415 
    416   private:
    417     int errorNumber;
    418   };
    419 
    420   template <typename Call>
    421   static SyscallResult syscall(Call&& call, bool nonblocking);
    422   template <typename Call>
    423   static int syscallError(Call&& call, bool nonblocking);
    424 
    425 #if _WIN32 || __CYGWIN__
    426   static Win32Result win32Call(int boolean);
    427   static Win32Result win32Call(void* handle);
    428   static Win32Result winsockCall(int result);
    429   static uint getWin32ErrorCode();
    430 #endif
    431 
    432   class Context: public ExceptionCallback {
    433   public:
    434     Context();
    435     KJ_DISALLOW_COPY(Context);
    436     virtual ~Context() noexcept(false);
    437 
    438     struct Value {
    439       const char* file;
    440       int line;
    441       String description;
    442 
    443       inline Value(const char* file, int line, String&& description)
    444           : file(file), line(line), description(mv(description)) {}
    445     };
    446 
    447     virtual Value evaluate() = 0;
    448 
    449     virtual void onRecoverableException(Exception&& exception) override;
    450     virtual void onFatalException(Exception&& exception) override;
    451     virtual void logMessage(LogSeverity severity, const char* file, int line, int contextDepth,
    452                             String&& text) override;
    453 
    454   private:
    455     bool logged;
    456     Maybe<Value> value;
    457 
    458     Value ensureInitialized();
    459   };
    460 
    461   template <typename Func>
    462   class ContextImpl: public Context {
    463   public:
    464     inline ContextImpl(Func& func): func(func) {}
    465     KJ_DISALLOW_COPY(ContextImpl);
    466 
    467     Value evaluate() override {
    468       return func();
    469     }
    470   private:
    471     Func& func;
    472   };
    473 
    474   template <typename... Params>
    475   static String makeDescription(const char* macroArgs, Params&&... params);
    476 
    477 private:
    478   static LogSeverity minSeverity;
    479 
    480   static void logInternal(const char* file, int line, LogSeverity severity, const char* macroArgs,
    481                           ArrayPtr<String> argValues);
    482   static String makeDescriptionInternal(const char* macroArgs, ArrayPtr<String> argValues);
    483 
    484   static int getOsErrorNumber(bool nonblocking);
    485   // Get the error code of the last error (e.g. from errno).  Returns -1 on EINTR.
    486 };
    487 
    488 template <typename... Params>
    489 void Debug::log(const char* file, int line, LogSeverity severity, const char* macroArgs,
    490                 Params&&... params) {
    491   String argValues[sizeof...(Params)] = {str(params)...};
    492   logInternal(file, line, severity, macroArgs, arrayPtr(argValues, sizeof...(Params)));
    493 }
    494 
    495 template <>
    496 inline void Debug::log<>(const char* file, int line, LogSeverity severity, const char* macroArgs) {
    497   logInternal(file, line, severity, macroArgs, nullptr);
    498 }
    499 
    500 template <typename Code, typename... Params>
    501 Debug::Fault::Fault(const char* file, int line, Code code,
    502                     const char* condition, const char* macroArgs, Params&&... params)
    503     : exception(nullptr) {
    504   String argValues[sizeof...(Params)] = {str(params)...};
    505   init(file, line, code, condition, macroArgs,
    506        arrayPtr(argValues, sizeof...(Params)));
    507 }
    508 
    509 inline Debug::Fault::Fault(const char* file, int line, int osErrorNumber,
    510                            const char* condition, const char* macroArgs)
    511     : exception(nullptr) {
    512   init(file, line, osErrorNumber, condition, macroArgs, nullptr);
    513 }
    514 
    515 inline Debug::Fault::Fault(const char* file, int line, kj::Exception::Type type,
    516                            const char* condition, const char* macroArgs)
    517     : exception(nullptr) {
    518   init(file, line, type, condition, macroArgs, nullptr);
    519 }
    520 
    521 #if _WIN32 || __CYGWIN__
    522 inline Debug::Fault::Fault(const char* file, int line, Win32Result osErrorNumber,
    523                            const char* condition, const char* macroArgs)
    524     : exception(nullptr) {
    525   init(file, line, osErrorNumber, condition, macroArgs, nullptr);
    526 }
    527 
    528 inline Debug::Win32Result Debug::win32Call(int boolean) {
    529   return boolean ? Win32Result(0) : Win32Result(getWin32ErrorCode());
    530 }
    531 inline Debug::Win32Result Debug::win32Call(void* handle) {
    532   // Assume null and INVALID_HANDLE_VALUE mean failure.
    533   return win32Call(handle != nullptr && handle != (void*)-1);
    534 }
    535 inline Debug::Win32Result Debug::winsockCall(int result) {
    536   // Expect a return value of SOCKET_ERROR means failure.
    537   return win32Call(result != -1);
    538 }
    539 #endif
    540 
    541 template <typename Call>
    542 Debug::SyscallResult Debug::syscall(Call&& call, bool nonblocking) {
    543   while (call() < 0) {
    544     int errorNum = getOsErrorNumber(nonblocking);
    545     // getOsErrorNumber() returns -1 to indicate EINTR.
    546     // Also, if nonblocking is true, then it returns 0 on EAGAIN, which will then be treated as a
    547     // non-error.
    548     if (errorNum != -1) {
    549       return SyscallResult(errorNum);
    550     }
    551   }
    552   return SyscallResult(0);
    553 }
    554 
    555 template <typename Call>
    556 int Debug::syscallError(Call&& call, bool nonblocking) {
    557   while (call() < 0) {
    558     int errorNum = getOsErrorNumber(nonblocking);
    559     // getOsErrorNumber() returns -1 to indicate EINTR.
    560     // Also, if nonblocking is true, then it returns 0 on EAGAIN, which will then be treated as a
    561     // non-error.
    562     if (errorNum != -1) {
    563       return errorNum;
    564     }
    565   }
    566   return 0;
    567 }
    568 
    569 template <typename... Params>
    570 String Debug::makeDescription(const char* macroArgs, Params&&... params) {
    571   String argValues[sizeof...(Params)] = {str(params)...};
    572   return makeDescriptionInternal(macroArgs, arrayPtr(argValues, sizeof...(Params)));
    573 }
    574 
    575 template <>
    576 inline String Debug::makeDescription<>(const char* macroArgs) {
    577   return makeDescriptionInternal(macroArgs, nullptr);
    578 }
    579 
    580 // =======================================================================================
    581 // Magic Asserts!
    582 //
    583 // When KJ_ASSERT(foo == bar) fails, `foo` and `bar`'s actual values will be stringified in the
    584 // error message. How does it work? We use template magic and operator precedence. The assertion
    585 // actually evaluates something like this:
    586 //
    587 //     if (auto _kjCondition = kj::_::MAGIC_ASSERT << foo == bar)
    588 //
    589 // `<<` has operator precedence slightly above `==`, so `kj::_::MAGIC_ASSERT << foo` gets evaluated
    590 // first. This wraps `foo` in a little wrapper that captures the comparison operators and keeps
    591 // enough information around to be able to stringify the left and right sides of the comparison
    592 // independently. As always, the stringification only actually occurs if the assert fails.
    593 //
    594 // You might ask why we use operator `<<` and not e.g. operator `<=`, since operators of the same
    595 // precedence are evaluated left-to-right. The answer is that some compilers trigger all sorts of
    596 // warnings when you seem to be using a comparison as the input to another comparison. The
    597 // particular warning GCC produces is its general "-Wparentheses" warning which is broadly useful,
    598 // so we don't want to disable it. `<<` also produces some warnings, but only on Clang and the
    599 // specific warning is one we're comfortable disabling (see below). This does mean that we have to
    600 // explicitly overload `operator<<` ourselves to make sure using it in an assert still works.
    601 //
    602 // You might also ask, if we're using operator `<<` anyway, why not start it from the right, in
    603 // which case it would bind after computing any `<<` operators that were actually in the user's
    604 // code? I tried this, but it resulted in a somewhat broader warning from clang that I felt worse
    605 // about disabling (a warning about `<<` precedence not applying specifically to overloads) and
    606 // also created ambiguous overload errors in the KJ units code.
    607 
    608 #if __clang__
    609 // We intentionally overload operator << for the specific purpose of evaluating it before
    610 // evaluating comparison expressions, so stop Clang from warning about it. Unfortunately this means
    611 // eliminating a warning that would otherwise be useful for people using iostreams... sorry.
    612 #pragma GCC diagnostic ignored "-Woverloaded-shift-op-parentheses"
    613 #endif
    614 
    615 template <typename T>
    616 struct DebugExpression;
    617 
    618 template <typename T, typename = decltype(toCharSequence(instance<T&>()))>
    619 inline auto tryToCharSequence(T* value) { return kj::toCharSequence(*value); }
    620 inline StringPtr tryToCharSequence(...) { return "(can't stringify)"_kj; }
    621 // SFINAE to stringify a value if and only if it can be stringified.
    622 
    623 template <typename Left, typename Right>
    624 struct DebugComparison {
    625   Left left;
    626   Right right;
    627   StringPtr op;
    628   bool result;
    629 
    630   inline operator bool() const { return KJ_LIKELY(result); }
    631 
    632   template <typename T> inline void operator&(T&& other) = delete;
    633   template <typename T> inline void operator^(T&& other) = delete;
    634   template <typename T> inline void operator|(T&& other) = delete;
    635 };
    636 
    637 template <typename Left, typename Right>
    638 String KJ_STRINGIFY(DebugComparison<Left, Right>& cmp) {
    639   return _::concat(tryToCharSequence(&cmp.left), cmp.op, tryToCharSequence(&cmp.right));
    640 }
    641 
    642 template <typename T>
    643 struct DebugExpression {
    644   DebugExpression(T&& value): value(kj::fwd<T>(value)) {}
    645   T value;
    646 
    647   // Handle comparison operations by constructing a DebugComparison value.
    648 #define DEFINE_OPERATOR(OP) \
    649   template <typename U> \
    650   DebugComparison<T, U> operator OP(U&& other) { \
    651     bool result = value OP other; \
    652     return { kj::fwd<T>(value), kj::fwd<U>(other), " " #OP " "_kj, result }; \
    653   }
    654   DEFINE_OPERATOR(==);
    655   DEFINE_OPERATOR(!=);
    656   DEFINE_OPERATOR(<=);
    657   DEFINE_OPERATOR(>=);
    658   DEFINE_OPERATOR(< );
    659   DEFINE_OPERATOR(> );
    660 #undef DEFINE_OPERATOR
    661 
    662   // Handle binary operators that have equal or lower precedence than comparisons by performing
    663   // the operation and wrapping the result.
    664 #define DEFINE_OPERATOR(OP) \
    665   template <typename U> inline auto operator OP(U&& other) { \
    666     return DebugExpression<decltype(kj::fwd<T>(value) OP kj::fwd<U>(other))>(\
    667         kj::fwd<T>(value) OP kj::fwd<U>(other)); \
    668   }
    669   DEFINE_OPERATOR(<<);
    670   DEFINE_OPERATOR(>>);
    671   DEFINE_OPERATOR(&);
    672   DEFINE_OPERATOR(^);
    673   DEFINE_OPERATOR(|);
    674 #undef DEFINE_OPERATOR
    675 
    676   inline operator bool() {
    677     // No comparison performed, we're just asserting the expression is truthy. This also covers
    678     // the case of the logic operators && and || -- we cannot overload those because doing so would
    679     // break short-circuiting behavior.
    680     return value;
    681   }
    682 };
    683 
    684 template <typename T>
    685 StringPtr KJ_STRINGIFY(const DebugExpression<T>& exp) {
    686   // Hack: This will only ever be called in cases where the expression's truthiness was asserted
    687   //   directly, and was determined to be falsy.
    688   return "false"_kj;
    689 }
    690 
    691 struct DebugExpressionStart {
    692   template <typename T>
    693   DebugExpression<T> operator<<(T&& value) const {
    694     return DebugExpression<T>(kj::fwd<T>(value));
    695   }
    696 };
    697 static constexpr DebugExpressionStart MAGIC_ASSERT;
    698 
    699 }  // namespace _ (private)
    700 }  // namespace kj
    701 
    702 KJ_END_HEADER