jpayne@69: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors jpayne@69: // Licensed under the MIT License: jpayne@69: // jpayne@69: // Permission is hereby granted, free of charge, to any person obtaining a copy jpayne@69: // of this software and associated documentation files (the "Software"), to deal jpayne@69: // in the Software without restriction, including without limitation the rights jpayne@69: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell jpayne@69: // copies of the Software, and to permit persons to whom the Software is jpayne@69: // furnished to do so, subject to the following conditions: jpayne@69: // jpayne@69: // The above copyright notice and this permission notice shall be included in jpayne@69: // all copies or substantial portions of the Software. jpayne@69: // jpayne@69: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR jpayne@69: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, jpayne@69: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE jpayne@69: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER jpayne@69: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, jpayne@69: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN jpayne@69: // THE SOFTWARE. jpayne@69: jpayne@69: // This file declares convenient macros for debug logging and error handling. The macros make jpayne@69: // it excessively easy to extract useful context information from code. Example: jpayne@69: // jpayne@69: // KJ_ASSERT(a == b, a, b, "a and b must be the same."); jpayne@69: // jpayne@69: // On failure, this will throw an exception whose description looks like: jpayne@69: // jpayne@69: // myfile.c++:43: bug in code: expected a == b; a = 14; b = 72; a and b must be the same. jpayne@69: // jpayne@69: // As you can see, all arguments after the first provide additional context. jpayne@69: // jpayne@69: // The macros available are: jpayne@69: // jpayne@69: // * `KJ_LOG(severity, ...)`: Just writes a log message, to stderr by default (but you can jpayne@69: // intercept messages by implementing an ExceptionCallback). `severity` is `INFO`, `WARNING`, jpayne@69: // `ERROR`, or `FATAL`. By default, `INFO` logs are not written, but for command-line apps the jpayne@69: // user should be able to pass a flag like `--verbose` to enable them. Other log levels are jpayne@69: // enabled by default. Log messages -- like exceptions -- can be intercepted by registering an jpayne@69: // ExceptionCallback. jpayne@69: // jpayne@69: // * `KJ_DBG(...)`: Like `KJ_LOG`, but intended specifically for temporary log lines added while jpayne@69: // debugging a particular problem. Calls to `KJ_DBG` should always be deleted before committing jpayne@69: // code. It is suggested that you set up a pre-commit hook that checks for this. jpayne@69: // jpayne@69: // * `KJ_ASSERT(condition, ...)`: Throws an exception if `condition` is false, or aborts if jpayne@69: // exceptions are disabled. This macro should be used to check for bugs in the surrounding code jpayne@69: // and its dependencies, but NOT to check for invalid input. The macro may be followed by a jpayne@69: // brace-delimited code block; if so, the block will be executed in the case where the assertion jpayne@69: // fails, before throwing the exception. If control jumps out of the block (e.g. with "break", jpayne@69: // "return", or "goto"), then the error is considered "recoverable" -- in this case, if jpayne@69: // exceptions are disabled, execution will continue normally rather than aborting (but if jpayne@69: // exceptions are enabled, an exception will still be thrown on exiting the block). A "break" jpayne@69: // statement in particular will jump to the code immediately after the block (it does not break jpayne@69: // any surrounding loop or switch). Example: jpayne@69: // jpayne@69: // KJ_ASSERT(value >= 0, "Value cannot be negative.", value) { jpayne@69: // // Assertion failed. Set value to zero to "recover". jpayne@69: // value = 0; jpayne@69: // // Don't abort if exceptions are disabled. Continue normally. jpayne@69: // // (Still throw an exception if they are enabled, though.) jpayne@69: // break; jpayne@69: // } jpayne@69: // // When exceptions are disabled, we'll get here even if the assertion fails. jpayne@69: // // Otherwise, we get here only if the assertion passes. jpayne@69: // jpayne@69: // * `KJ_REQUIRE(condition, ...)`: Like `KJ_ASSERT` but used to check preconditions -- e.g. to jpayne@69: // validate parameters passed from a caller. A failure indicates that the caller is buggy. jpayne@69: // jpayne@69: // * `KJ_ASSUME(condition, ...)`: Like `KJ_ASSERT`, but in release mode (if KJ_DEBUG is not jpayne@69: // defined; see below) instead warrants to the compiler that the condition can be assumed to jpayne@69: // hold, allowing it to optimize accordingly. This can result in undefined behavior, so use jpayne@69: // this macro *only* if you can prove to your satisfaction that the condition is guaranteed by jpayne@69: // surrounding code, and if the condition failing to hold would in any case result in undefined jpayne@69: // behavior in its dependencies. jpayne@69: // jpayne@69: // * `KJ_SYSCALL(code, ...)`: Executes `code` assuming it makes a system call. A negative result jpayne@69: // is considered an error, with error code reported via `errno`. EINTR is handled by retrying. jpayne@69: // Other errors are handled by throwing an exception. If you need to examine the return code, jpayne@69: // assign it to a variable like so: jpayne@69: // jpayne@69: // int fd; jpayne@69: // KJ_SYSCALL(fd = open(filename, O_RDONLY), filename); jpayne@69: // jpayne@69: // `KJ_SYSCALL` can be followed by a recovery block, just like `KJ_ASSERT`. jpayne@69: // jpayne@69: // * `KJ_NONBLOCKING_SYSCALL(code, ...)`: Like KJ_SYSCALL, but will not throw an exception on jpayne@69: // EAGAIN/EWOULDBLOCK. The calling code should check the syscall's return value to see if it jpayne@69: // indicates an error; in this case, it can assume the error was EAGAIN because any other error jpayne@69: // would have caused an exception to be thrown. jpayne@69: // jpayne@69: // * `KJ_CONTEXT(...)`: Notes additional contextual information relevant to any exceptions thrown jpayne@69: // from within the current scope. That is, until control exits the block in which KJ_CONTEXT() jpayne@69: // is used, if any exception is generated, it will contain the given information in its context jpayne@69: // chain. This is helpful because it can otherwise be very difficult to come up with error jpayne@69: // messages that make sense within low-level helper code. Note that the parameters to jpayne@69: // KJ_CONTEXT() are only evaluated if an exception is thrown. This implies that any variables jpayne@69: // used must remain valid until the end of the scope. jpayne@69: // jpayne@69: // Notes: jpayne@69: // * Do not write expressions with side-effects in the message content part of the macro, as the jpayne@69: // message will not necessarily be evaluated. jpayne@69: // * For every macro `FOO` above except `LOG`, there is also a `FAIL_FOO` macro used to report jpayne@69: // failures that already happened. For the macros that check a boolean condition, `FAIL_FOO` jpayne@69: // omits the first parameter and behaves like it was `false`. `FAIL_SYSCALL` and jpayne@69: // `FAIL_RECOVERABLE_SYSCALL` take a string and an OS error number as the first two parameters. jpayne@69: // The string should be the name of the failed system call. jpayne@69: // * For every macro `FOO` above except `ASSUME`, there is a `DFOO` version (or jpayne@69: // `RECOVERABLE_DFOO`) which is only executed in debug mode, i.e. when KJ_DEBUG is defined. jpayne@69: // KJ_DEBUG is defined automatically by common.h when compiling without optimization (unless jpayne@69: // NDEBUG is defined), but you can also define it explicitly (e.g. -DKJ_DEBUG). Generally, jpayne@69: // production builds should NOT use KJ_DEBUG as it may enable expensive checks that are unlikely jpayne@69: // to fail. jpayne@69: jpayne@69: #pragma once jpayne@69: jpayne@69: #include "string.h" jpayne@69: #include "exception.h" jpayne@69: #include "windows-sanity.h" // work-around macro conflict with `ERROR` jpayne@69: jpayne@69: KJ_BEGIN_HEADER jpayne@69: jpayne@69: namespace kj { jpayne@69: jpayne@69: #if KJ_MSVC_TRADITIONAL_CPP jpayne@69: // MSVC does __VA_ARGS__ differently from GCC: jpayne@69: // - A trailing comma before an empty __VA_ARGS__ is removed automatically, whereas GCC wants jpayne@69: // you to request this behavior with "##__VA_ARGS__". jpayne@69: // - If __VA_ARGS__ is passed directly as an argument to another macro, it will be treated as a jpayne@69: // *single* argument rather than an argument list. This can be worked around by wrapping the jpayne@69: // outer macro call in KJ_EXPAND(), which apparently forces __VA_ARGS__ to be expanded before jpayne@69: // the macro is evaluated. I don't understand the C preprocessor. jpayne@69: // - Using "#__VA_ARGS__" to stringify __VA_ARGS__ expands to zero tokens when __VA_ARGS__ is jpayne@69: // empty, rather than expanding to an empty string literal. We can work around by concatenating jpayne@69: // with an empty string literal. jpayne@69: jpayne@69: #define KJ_EXPAND(X) X jpayne@69: jpayne@69: #define KJ_LOG(severity, ...) \ jpayne@69: for (bool _kj_shouldLog = ::kj::_::Debug::shouldLog(::kj::LogSeverity::severity); \ jpayne@69: _kj_shouldLog; _kj_shouldLog = false) \ jpayne@69: ::kj::_::Debug::log(__FILE__, __LINE__, ::kj::LogSeverity::severity, \ jpayne@69: "" #__VA_ARGS__, __VA_ARGS__) jpayne@69: jpayne@69: #define KJ_DBG(...) KJ_EXPAND(KJ_LOG(DBG, __VA_ARGS__)) jpayne@69: jpayne@69: #define KJ_REQUIRE(cond, ...) \ jpayne@69: if (auto _kjCondition = ::kj::_::MAGIC_ASSERT << cond) {} else \ jpayne@69: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ jpayne@69: #cond, "_kjCondition," #__VA_ARGS__, _kjCondition, __VA_ARGS__);; f.fatal()) jpayne@69: jpayne@69: #define KJ_FAIL_REQUIRE(...) \ jpayne@69: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ jpayne@69: nullptr, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) jpayne@69: jpayne@69: #define KJ_SYSCALL(call, ...) \ jpayne@69: if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, false)) {} else \ jpayne@69: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ jpayne@69: _kjSyscallResult.getErrorNumber(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) jpayne@69: jpayne@69: #define KJ_NONBLOCKING_SYSCALL(call, ...) \ jpayne@69: if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, true)) {} else \ jpayne@69: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ jpayne@69: _kjSyscallResult.getErrorNumber(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) jpayne@69: jpayne@69: #define KJ_FAIL_SYSCALL(code, errorNumber, ...) \ jpayne@69: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ jpayne@69: errorNumber, code, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) jpayne@69: jpayne@69: #if _WIN32 || __CYGWIN__ jpayne@69: jpayne@69: #define KJ_WIN32(call, ...) \ jpayne@69: if (auto _kjWin32Result = ::kj::_::Debug::win32Call(call)) {} else \ jpayne@69: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ jpayne@69: _kjWin32Result, #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) jpayne@69: jpayne@69: #define KJ_WINSOCK(call, ...) \ jpayne@69: if (auto _kjWin32Result = ::kj::_::Debug::winsockCall(call)) {} else \ jpayne@69: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ jpayne@69: _kjWin32Result, #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) jpayne@69: jpayne@69: #define KJ_FAIL_WIN32(code, errorNumber, ...) \ jpayne@69: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ jpayne@69: ::kj::_::Debug::Win32Result(errorNumber), code, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) jpayne@69: jpayne@69: #endif jpayne@69: jpayne@69: #define KJ_UNIMPLEMENTED(...) \ jpayne@69: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::UNIMPLEMENTED, \ jpayne@69: nullptr, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) jpayne@69: jpayne@69: // TODO(msvc): MSVC mis-deduces `ContextImpl` as `ContextImpl` in some edge jpayne@69: // cases, such as inside nested lambdas inside member functions. Wrapping the type in jpayne@69: // `decltype(instance<...>())` helps it deduce the context function's type correctly. jpayne@69: #define KJ_CONTEXT(...) \ jpayne@69: auto KJ_UNIQUE_NAME(_kjContextFunc) = [&]() -> ::kj::_::Debug::Context::Value { \ jpayne@69: return ::kj::_::Debug::Context::Value(__FILE__, __LINE__, \ jpayne@69: ::kj::_::Debug::makeDescription("" #__VA_ARGS__, __VA_ARGS__)); \ jpayne@69: }; \ jpayne@69: decltype(::kj::instance<::kj::_::Debug::ContextImpl>()) \ jpayne@69: KJ_UNIQUE_NAME(_kjContext)(KJ_UNIQUE_NAME(_kjContextFunc)) jpayne@69: jpayne@69: #define KJ_REQUIRE_NONNULL(value, ...) \ jpayne@69: (*[&] { \ jpayne@69: auto _kj_result = ::kj::_::readMaybe(value); \ jpayne@69: if (KJ_UNLIKELY(!_kj_result)) { \ jpayne@69: ::kj::_::Debug::Fault(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ jpayne@69: #value " != nullptr", "" #__VA_ARGS__, __VA_ARGS__).fatal(); \ jpayne@69: } \ jpayne@69: return _kj_result; \ jpayne@69: }()) jpayne@69: jpayne@69: #define KJ_EXCEPTION(type, ...) \ jpayne@69: ::kj::Exception(::kj::Exception::Type::type, __FILE__, __LINE__, \ jpayne@69: ::kj::_::Debug::makeDescription("" #__VA_ARGS__, __VA_ARGS__)) jpayne@69: jpayne@69: #else jpayne@69: jpayne@69: #define KJ_LOG(severity, ...) \ jpayne@69: for (bool _kj_shouldLog = ::kj::_::Debug::shouldLog(::kj::LogSeverity::severity); \ jpayne@69: _kj_shouldLog; _kj_shouldLog = false) \ jpayne@69: ::kj::_::Debug::log(__FILE__, __LINE__, ::kj::LogSeverity::severity, \ jpayne@69: #__VA_ARGS__, ##__VA_ARGS__) jpayne@69: jpayne@69: #define KJ_DBG(...) KJ_LOG(DBG, ##__VA_ARGS__) jpayne@69: jpayne@69: #define KJ_REQUIRE(cond, ...) \ jpayne@69: if (auto _kjCondition = ::kj::_::MAGIC_ASSERT << cond) {} else \ jpayne@69: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ jpayne@69: #cond, "_kjCondition," #__VA_ARGS__, _kjCondition, ##__VA_ARGS__);; f.fatal()) jpayne@69: jpayne@69: #define KJ_FAIL_REQUIRE(...) \ jpayne@69: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ jpayne@69: nullptr, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) jpayne@69: jpayne@69: #define KJ_SYSCALL(call, ...) \ jpayne@69: if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, false)) {} else \ jpayne@69: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ jpayne@69: _kjSyscallResult.getErrorNumber(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) jpayne@69: jpayne@69: #define KJ_NONBLOCKING_SYSCALL(call, ...) \ jpayne@69: if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, true)) {} else \ jpayne@69: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ jpayne@69: _kjSyscallResult.getErrorNumber(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) jpayne@69: jpayne@69: #define KJ_FAIL_SYSCALL(code, errorNumber, ...) \ jpayne@69: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ jpayne@69: errorNumber, code, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) jpayne@69: jpayne@69: #if _WIN32 || __CYGWIN__ jpayne@69: jpayne@69: #define KJ_WIN32(call, ...) \ jpayne@69: if (auto _kjWin32Result = ::kj::_::Debug::win32Call(call)) {} else \ jpayne@69: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ jpayne@69: _kjWin32Result, #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) jpayne@69: // Invoke a Win32 syscall that returns either BOOL or HANDLE, and throw an exception if it fails. jpayne@69: jpayne@69: #define KJ_WINSOCK(call, ...) \ jpayne@69: if (auto _kjWin32Result = ::kj::_::Debug::winsockCall(call)) {} else \ jpayne@69: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ jpayne@69: _kjWin32Result, #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) jpayne@69: // Like KJ_WIN32 but for winsock calls which return `int` with SOCKET_ERROR indicating failure. jpayne@69: // jpayne@69: // Unfortunately, it's impossible to distinguish these from BOOL-returning Win32 calls by type, jpayne@69: // since BOOL is in fact an alias for `int`. :( jpayne@69: jpayne@69: #define KJ_FAIL_WIN32(code, errorNumber, ...) \ jpayne@69: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ jpayne@69: ::kj::_::Debug::Win32Result(errorNumber), code, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) jpayne@69: jpayne@69: #endif jpayne@69: jpayne@69: #define KJ_UNIMPLEMENTED(...) \ jpayne@69: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::UNIMPLEMENTED, \ jpayne@69: nullptr, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) jpayne@69: jpayne@69: #define KJ_CONTEXT(...) \ jpayne@69: auto KJ_UNIQUE_NAME(_kjContextFunc) = [&]() -> ::kj::_::Debug::Context::Value { \ jpayne@69: return ::kj::_::Debug::Context::Value(__FILE__, __LINE__, \ jpayne@69: ::kj::_::Debug::makeDescription(#__VA_ARGS__, ##__VA_ARGS__)); \ jpayne@69: }; \ jpayne@69: ::kj::_::Debug::ContextImpl \ jpayne@69: KJ_UNIQUE_NAME(_kjContext)(KJ_UNIQUE_NAME(_kjContextFunc)) jpayne@69: jpayne@69: #if _MSC_VER && !defined(__clang__) jpayne@69: jpayne@69: #define KJ_REQUIRE_NONNULL(value, ...) \ jpayne@69: (*([&] { \ jpayne@69: auto _kj_result = ::kj::_::readMaybe(value); \ jpayne@69: if (KJ_UNLIKELY(!_kj_result)) { \ jpayne@69: ::kj::_::Debug::Fault(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ jpayne@69: #value " != nullptr", #__VA_ARGS__, ##__VA_ARGS__).fatal(); \ jpayne@69: } \ jpayne@69: return _kj_result; \ jpayne@69: }())) jpayne@69: jpayne@69: #else jpayne@69: jpayne@69: #define KJ_REQUIRE_NONNULL(value, ...) \ jpayne@69: (*({ \ jpayne@69: auto _kj_result = ::kj::_::readMaybe(value); \ jpayne@69: if (KJ_UNLIKELY(!_kj_result)) { \ jpayne@69: ::kj::_::Debug::Fault(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ jpayne@69: #value " != nullptr", #__VA_ARGS__, ##__VA_ARGS__).fatal(); \ jpayne@69: } \ jpayne@69: kj::mv(_kj_result); \ jpayne@69: })) jpayne@69: jpayne@69: #endif jpayne@69: jpayne@69: #define KJ_EXCEPTION(type, ...) \ jpayne@69: ::kj::Exception(::kj::Exception::Type::type, __FILE__, __LINE__, \ jpayne@69: ::kj::_::Debug::makeDescription(#__VA_ARGS__, ##__VA_ARGS__)) jpayne@69: jpayne@69: #endif jpayne@69: jpayne@69: #define KJ_SYSCALL_HANDLE_ERRORS(call) \ jpayne@69: if (int _kjSyscallError = ::kj::_::Debug::syscallError([&](){return (call);}, false)) \ jpayne@69: switch (int error KJ_UNUSED = _kjSyscallError) jpayne@69: // Like KJ_SYSCALL, but doesn't throw. Instead, the block after the macro is a switch block on the jpayne@69: // error. Additionally, the int value `error` is defined within the block. So you can do: jpayne@69: // jpayne@69: // KJ_SYSCALL_HANDLE_ERRORS(foo()) { jpayne@69: // case ENOENT: jpayne@69: // handleNoSuchFile(); jpayne@69: // break; jpayne@69: // case EEXIST: jpayne@69: // handleExists(); jpayne@69: // break; jpayne@69: // default: jpayne@69: // KJ_FAIL_SYSCALL("foo()", error); jpayne@69: // } else { jpayne@69: // handleSuccessCase(); jpayne@69: // } jpayne@69: jpayne@69: #if _WIN32 || __CYGWIN__ jpayne@69: jpayne@69: #define KJ_WIN32_HANDLE_ERRORS(call) \ jpayne@69: if (uint _kjWin32Error = ::kj::_::Debug::win32Call(call).number) \ jpayne@69: switch (uint error KJ_UNUSED = _kjWin32Error) jpayne@69: // Like KJ_WIN32, but doesn't throw. Instead, the block after the macro is a switch block on the jpayne@69: // error. Additionally, the int value `error` is defined within the block. So you can do: jpayne@69: // jpayne@69: // KJ_SYSCALL_HANDLE_ERRORS(foo()) { jpayne@69: // case ERROR_FILE_NOT_FOUND: jpayne@69: // handleNoSuchFile(); jpayne@69: // break; jpayne@69: // case ERROR_FILE_EXISTS: jpayne@69: // handleExists(); jpayne@69: // break; jpayne@69: // default: jpayne@69: // KJ_FAIL_WIN32("foo()", error); jpayne@69: // } else { jpayne@69: // handleSuccessCase(); jpayne@69: // } jpayne@69: jpayne@69: #endif jpayne@69: jpayne@69: #define KJ_ASSERT KJ_REQUIRE jpayne@69: #define KJ_FAIL_ASSERT KJ_FAIL_REQUIRE jpayne@69: #define KJ_ASSERT_NONNULL KJ_REQUIRE_NONNULL jpayne@69: // Use "ASSERT" in place of "REQUIRE" when the problem is local to the immediate surrounding code. jpayne@69: // That is, if the assert ever fails, it indicates that the immediate surrounding code is broken. jpayne@69: jpayne@69: #ifdef KJ_DEBUG jpayne@69: #define KJ_DLOG KJ_LOG jpayne@69: #define KJ_DASSERT KJ_ASSERT jpayne@69: #define KJ_DREQUIRE KJ_REQUIRE jpayne@69: #define KJ_ASSUME KJ_ASSERT jpayne@69: #else jpayne@69: #define KJ_DLOG(...) do {} while (false) jpayne@69: #define KJ_DASSERT(...) do {} while (false) jpayne@69: #define KJ_DREQUIRE(...) do {} while (false) jpayne@69: #if defined(__GNUC__) jpayne@69: #define KJ_ASSUME(cond, ...) do { if (cond) {} else __builtin_unreachable(); } while (false) jpayne@69: #elif defined(__clang__) jpayne@69: #define KJ_ASSUME(cond, ...) __builtin_assume(cond) jpayne@69: #elif defined(_MSC_VER) jpayne@69: #define KJ_ASSUME(cond, ...) __assume(cond) jpayne@69: #else jpayne@69: #define KJ_ASSUME(...) do {} while (false) jpayne@69: #endif jpayne@69: jpayne@69: #endif jpayne@69: jpayne@69: namespace _ { // private jpayne@69: jpayne@69: class Debug { jpayne@69: public: jpayne@69: Debug() = delete; jpayne@69: jpayne@69: typedef LogSeverity Severity; // backwards-compatibility jpayne@69: jpayne@69: #if _WIN32 || __CYGWIN__ jpayne@69: struct Win32Result { jpayne@69: uint number; jpayne@69: inline explicit Win32Result(uint number): number(number) {} jpayne@69: operator bool() const { return number == 0; } jpayne@69: }; jpayne@69: #endif jpayne@69: jpayne@69: static inline bool shouldLog(LogSeverity severity) { return severity >= minSeverity; } jpayne@69: // Returns whether messages of the given severity should be logged. jpayne@69: jpayne@69: static inline void setLogLevel(LogSeverity severity) { minSeverity = severity; } jpayne@69: // Set the minimum message severity which will be logged. jpayne@69: // jpayne@69: // TODO(someday): Expose publicly. jpayne@69: jpayne@69: template jpayne@69: static void log(const char* file, int line, LogSeverity severity, const char* macroArgs, jpayne@69: Params&&... params); jpayne@69: jpayne@69: class Fault { jpayne@69: public: jpayne@69: template jpayne@69: Fault(const char* file, int line, Code code, jpayne@69: const char* condition, const char* macroArgs, Params&&... params); jpayne@69: Fault(const char* file, int line, Exception::Type type, jpayne@69: const char* condition, const char* macroArgs); jpayne@69: Fault(const char* file, int line, int osErrorNumber, jpayne@69: const char* condition, const char* macroArgs); jpayne@69: #if _WIN32 || __CYGWIN__ jpayne@69: Fault(const char* file, int line, Win32Result osErrorNumber, jpayne@69: const char* condition, const char* macroArgs); jpayne@69: #endif jpayne@69: ~Fault() noexcept(false); jpayne@69: jpayne@69: KJ_NOINLINE KJ_NORETURN(void fatal()); jpayne@69: // Throw the exception. jpayne@69: jpayne@69: private: jpayne@69: void init(const char* file, int line, Exception::Type type, jpayne@69: const char* condition, const char* macroArgs, ArrayPtr argValues); jpayne@69: void init(const char* file, int line, int osErrorNumber, jpayne@69: const char* condition, const char* macroArgs, ArrayPtr argValues); jpayne@69: #if _WIN32 || __CYGWIN__ jpayne@69: void init(const char* file, int line, Win32Result osErrorNumber, jpayne@69: const char* condition, const char* macroArgs, ArrayPtr argValues); jpayne@69: #endif jpayne@69: jpayne@69: Exception* exception; jpayne@69: }; jpayne@69: jpayne@69: class SyscallResult { jpayne@69: public: jpayne@69: inline SyscallResult(int errorNumber): errorNumber(errorNumber) {} jpayne@69: inline operator void*() { return errorNumber == 0 ? this : nullptr; } jpayne@69: inline int getErrorNumber() { return errorNumber; } jpayne@69: jpayne@69: private: jpayne@69: int errorNumber; jpayne@69: }; jpayne@69: jpayne@69: template jpayne@69: static SyscallResult syscall(Call&& call, bool nonblocking); jpayne@69: template jpayne@69: static int syscallError(Call&& call, bool nonblocking); jpayne@69: jpayne@69: #if _WIN32 || __CYGWIN__ jpayne@69: static Win32Result win32Call(int boolean); jpayne@69: static Win32Result win32Call(void* handle); jpayne@69: static Win32Result winsockCall(int result); jpayne@69: static uint getWin32ErrorCode(); jpayne@69: #endif jpayne@69: jpayne@69: class Context: public ExceptionCallback { jpayne@69: public: jpayne@69: Context(); jpayne@69: KJ_DISALLOW_COPY_AND_MOVE(Context); jpayne@69: virtual ~Context() noexcept(false); jpayne@69: jpayne@69: struct Value { jpayne@69: const char* file; jpayne@69: int line; jpayne@69: String description; jpayne@69: jpayne@69: inline Value(const char* file, int line, String&& description) jpayne@69: : file(file), line(line), description(mv(description)) {} jpayne@69: }; jpayne@69: jpayne@69: virtual Value evaluate() = 0; jpayne@69: jpayne@69: virtual void onRecoverableException(Exception&& exception) override; jpayne@69: virtual void onFatalException(Exception&& exception) override; jpayne@69: virtual void logMessage(LogSeverity severity, const char* file, int line, int contextDepth, jpayne@69: String&& text) override; jpayne@69: jpayne@69: private: jpayne@69: bool logged; jpayne@69: Maybe value; jpayne@69: jpayne@69: Value ensureInitialized(); jpayne@69: }; jpayne@69: jpayne@69: template jpayne@69: class ContextImpl: public Context { jpayne@69: public: jpayne@69: inline ContextImpl(Func& func): func(func) {} jpayne@69: KJ_DISALLOW_COPY_AND_MOVE(ContextImpl); jpayne@69: jpayne@69: Value evaluate() override { jpayne@69: return func(); jpayne@69: } jpayne@69: private: jpayne@69: Func& func; jpayne@69: }; jpayne@69: jpayne@69: template jpayne@69: static String makeDescription(const char* macroArgs, Params&&... params); jpayne@69: jpayne@69: private: jpayne@69: static LogSeverity minSeverity; jpayne@69: jpayne@69: static void logInternal(const char* file, int line, LogSeverity severity, const char* macroArgs, jpayne@69: ArrayPtr argValues); jpayne@69: static String makeDescriptionInternal(const char* macroArgs, ArrayPtr argValues); jpayne@69: jpayne@69: static int getOsErrorNumber(bool nonblocking); jpayne@69: // Get the error code of the last error (e.g. from errno). Returns -1 on EINTR. jpayne@69: }; jpayne@69: jpayne@69: template jpayne@69: void Debug::log(const char* file, int line, LogSeverity severity, const char* macroArgs, jpayne@69: Params&&... params) { jpayne@69: String argValues[sizeof...(Params)] = {str(params)...}; jpayne@69: logInternal(file, line, severity, macroArgs, arrayPtr(argValues, sizeof...(Params))); jpayne@69: } jpayne@69: jpayne@69: template <> jpayne@69: inline void Debug::log<>(const char* file, int line, LogSeverity severity, const char* macroArgs) { jpayne@69: logInternal(file, line, severity, macroArgs, nullptr); jpayne@69: } jpayne@69: jpayne@69: template jpayne@69: Debug::Fault::Fault(const char* file, int line, Code code, jpayne@69: const char* condition, const char* macroArgs, Params&&... params) jpayne@69: : exception(nullptr) { jpayne@69: String argValues[sizeof...(Params)] = {str(params)...}; jpayne@69: init(file, line, code, condition, macroArgs, jpayne@69: arrayPtr(argValues, sizeof...(Params))); jpayne@69: } jpayne@69: jpayne@69: inline Debug::Fault::Fault(const char* file, int line, int osErrorNumber, jpayne@69: const char* condition, const char* macroArgs) jpayne@69: : exception(nullptr) { jpayne@69: init(file, line, osErrorNumber, condition, macroArgs, nullptr); jpayne@69: } jpayne@69: jpayne@69: inline Debug::Fault::Fault(const char* file, int line, kj::Exception::Type type, jpayne@69: const char* condition, const char* macroArgs) jpayne@69: : exception(nullptr) { jpayne@69: init(file, line, type, condition, macroArgs, nullptr); jpayne@69: } jpayne@69: jpayne@69: #if _WIN32 || __CYGWIN__ jpayne@69: inline Debug::Fault::Fault(const char* file, int line, Win32Result osErrorNumber, jpayne@69: const char* condition, const char* macroArgs) jpayne@69: : exception(nullptr) { jpayne@69: init(file, line, osErrorNumber, condition, macroArgs, nullptr); jpayne@69: } jpayne@69: jpayne@69: inline Debug::Win32Result Debug::win32Call(int boolean) { jpayne@69: return boolean ? Win32Result(0) : Win32Result(getWin32ErrorCode()); jpayne@69: } jpayne@69: inline Debug::Win32Result Debug::win32Call(void* handle) { jpayne@69: // Assume null and INVALID_HANDLE_VALUE mean failure. jpayne@69: return win32Call(handle != nullptr && handle != (void*)-1); jpayne@69: } jpayne@69: inline Debug::Win32Result Debug::winsockCall(int result) { jpayne@69: // Expect a return value of SOCKET_ERROR means failure. jpayne@69: return win32Call(result != -1); jpayne@69: } jpayne@69: #endif jpayne@69: jpayne@69: template jpayne@69: Debug::SyscallResult Debug::syscall(Call&& call, bool nonblocking) { jpayne@69: while (call() < 0) { jpayne@69: int errorNum = getOsErrorNumber(nonblocking); jpayne@69: // getOsErrorNumber() returns -1 to indicate EINTR. jpayne@69: // Also, if nonblocking is true, then it returns 0 on EAGAIN, which will then be treated as a jpayne@69: // non-error. jpayne@69: if (errorNum != -1) { jpayne@69: return SyscallResult(errorNum); jpayne@69: } jpayne@69: } jpayne@69: return SyscallResult(0); jpayne@69: } jpayne@69: jpayne@69: template jpayne@69: int Debug::syscallError(Call&& call, bool nonblocking) { jpayne@69: while (call() < 0) { jpayne@69: int errorNum = getOsErrorNumber(nonblocking); jpayne@69: // getOsErrorNumber() returns -1 to indicate EINTR. jpayne@69: // Also, if nonblocking is true, then it returns 0 on EAGAIN, which will then be treated as a jpayne@69: // non-error. jpayne@69: if (errorNum != -1) { jpayne@69: return errorNum; jpayne@69: } jpayne@69: } jpayne@69: return 0; jpayne@69: } jpayne@69: jpayne@69: template jpayne@69: String Debug::makeDescription(const char* macroArgs, Params&&... params) { jpayne@69: String argValues[sizeof...(Params)] = {str(params)...}; jpayne@69: return makeDescriptionInternal(macroArgs, arrayPtr(argValues, sizeof...(Params))); jpayne@69: } jpayne@69: jpayne@69: template <> jpayne@69: inline String Debug::makeDescription<>(const char* macroArgs) { jpayne@69: return makeDescriptionInternal(macroArgs, nullptr); jpayne@69: } jpayne@69: jpayne@69: // ======================================================================================= jpayne@69: // Magic Asserts! jpayne@69: // jpayne@69: // When KJ_ASSERT(foo == bar) fails, `foo` and `bar`'s actual values will be stringified in the jpayne@69: // error message. How does it work? We use template magic and operator precedence. The assertion jpayne@69: // actually evaluates something like this: jpayne@69: // jpayne@69: // if (auto _kjCondition = kj::_::MAGIC_ASSERT << foo == bar) jpayne@69: // jpayne@69: // `<<` has operator precedence slightly above `==`, so `kj::_::MAGIC_ASSERT << foo` gets evaluated jpayne@69: // first. This wraps `foo` in a little wrapper that captures the comparison operators and keeps jpayne@69: // enough information around to be able to stringify the left and right sides of the comparison jpayne@69: // independently. As always, the stringification only actually occurs if the assert fails. jpayne@69: // jpayne@69: // You might ask why we use operator `<<` and not e.g. operator `<=`, since operators of the same jpayne@69: // precedence are evaluated left-to-right. The answer is that some compilers trigger all sorts of jpayne@69: // warnings when you seem to be using a comparison as the input to another comparison. The jpayne@69: // particular warning GCC produces is its general "-Wparentheses" warning which is broadly useful, jpayne@69: // so we don't want to disable it. `<<` also produces some warnings, but only on Clang and the jpayne@69: // specific warning is one we're comfortable disabling (see below). This does mean that we have to jpayne@69: // explicitly overload `operator<<` ourselves to make sure using it in an assert still works. jpayne@69: // jpayne@69: // You might also ask, if we're using operator `<<` anyway, why not start it from the right, in jpayne@69: // which case it would bind after computing any `<<` operators that were actually in the user's jpayne@69: // code? I tried this, but it resulted in a somewhat broader warning from clang that I felt worse jpayne@69: // about disabling (a warning about `<<` precedence not applying specifically to overloads) and jpayne@69: // also created ambiguous overload errors in the KJ units code. jpayne@69: jpayne@69: #if __clang__ jpayne@69: // We intentionally overload operator << for the specific purpose of evaluating it before jpayne@69: // evaluating comparison expressions, so stop Clang from warning about it. Unfortunately this means jpayne@69: // eliminating a warning that would otherwise be useful for people using iostreams... sorry. jpayne@69: #pragma GCC diagnostic ignored "-Woverloaded-shift-op-parentheses" jpayne@69: #endif jpayne@69: jpayne@69: template jpayne@69: struct DebugExpression; jpayne@69: jpayne@69: template ()))> jpayne@69: inline auto tryToCharSequence(T* value) { return kj::toCharSequence(*value); } jpayne@69: inline StringPtr tryToCharSequence(...) { return "(can't stringify)"_kj; } jpayne@69: // SFINAE to stringify a value if and only if it can be stringified. jpayne@69: jpayne@69: template jpayne@69: struct DebugComparison { jpayne@69: Left left; jpayne@69: Right right; jpayne@69: StringPtr op; jpayne@69: bool result; jpayne@69: jpayne@69: inline operator bool() const { return KJ_LIKELY(result); } jpayne@69: jpayne@69: template inline void operator&(T&& other) = delete; jpayne@69: template inline void operator^(T&& other) = delete; jpayne@69: template inline void operator|(T&& other) = delete; jpayne@69: }; jpayne@69: jpayne@69: template jpayne@69: String KJ_STRINGIFY(DebugComparison& cmp) { jpayne@69: return _::concat(tryToCharSequence(&cmp.left), cmp.op, tryToCharSequence(&cmp.right)); jpayne@69: } jpayne@69: jpayne@69: template jpayne@69: struct DebugExpression { jpayne@69: DebugExpression(T&& value): value(kj::fwd(value)) {} jpayne@69: T value; jpayne@69: jpayne@69: // Handle comparison operations by constructing a DebugComparison value. jpayne@69: #define DEFINE_OPERATOR(OP) \ jpayne@69: template \ jpayne@69: DebugComparison operator OP(U&& other) { \ jpayne@69: bool result = value OP other; \ jpayne@69: return { kj::fwd(value), kj::fwd(other), " " #OP " "_kj, result }; \ jpayne@69: } jpayne@69: DEFINE_OPERATOR(==); jpayne@69: DEFINE_OPERATOR(!=); jpayne@69: DEFINE_OPERATOR(<=); jpayne@69: DEFINE_OPERATOR(>=); jpayne@69: DEFINE_OPERATOR(< ); jpayne@69: DEFINE_OPERATOR(> ); jpayne@69: #undef DEFINE_OPERATOR jpayne@69: jpayne@69: // Handle binary operators that have equal or lower precedence than comparisons by performing jpayne@69: // the operation and wrapping the result. jpayne@69: #define DEFINE_OPERATOR(OP) \ jpayne@69: template inline auto operator OP(U&& other) { \ jpayne@69: return DebugExpression(value) OP kj::fwd(other))>(\ jpayne@69: kj::fwd(value) OP kj::fwd(other)); \ jpayne@69: } jpayne@69: DEFINE_OPERATOR(<<); jpayne@69: DEFINE_OPERATOR(>>); jpayne@69: DEFINE_OPERATOR(&); jpayne@69: DEFINE_OPERATOR(^); jpayne@69: DEFINE_OPERATOR(|); jpayne@69: #undef DEFINE_OPERATOR jpayne@69: jpayne@69: inline operator bool() { jpayne@69: // No comparison performed, we're just asserting the expression is truthy. This also covers jpayne@69: // the case of the logic operators && and || -- we cannot overload those because doing so would jpayne@69: // break short-circuiting behavior. jpayne@69: return value; jpayne@69: } jpayne@69: }; jpayne@69: jpayne@69: template jpayne@69: StringPtr KJ_STRINGIFY(const DebugExpression& exp) { jpayne@69: // Hack: This will only ever be called in cases where the expression's truthiness was asserted jpayne@69: // directly, and was determined to be falsy. jpayne@69: return "false"_kj; jpayne@69: } jpayne@69: jpayne@69: struct DebugExpressionStart { jpayne@69: template jpayne@69: DebugExpression operator<<(T&& value) const { jpayne@69: return DebugExpression(kj::fwd(value)); jpayne@69: } jpayne@69: }; jpayne@69: static constexpr DebugExpressionStart MAGIC_ASSERT; jpayne@69: jpayne@69: } // namespace _ (private) jpayne@69: } // namespace kj jpayne@69: jpayne@69: KJ_END_HEADER