cannam@147: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors cannam@147: // Licensed under the MIT License: cannam@147: // cannam@147: // Permission is hereby granted, free of charge, to any person obtaining a copy cannam@147: // of this software and associated documentation files (the "Software"), to deal cannam@147: // in the Software without restriction, including without limitation the rights cannam@147: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell cannam@147: // copies of the Software, and to permit persons to whom the Software is cannam@147: // furnished to do so, subject to the following conditions: cannam@147: // cannam@147: // The above copyright notice and this permission notice shall be included in cannam@147: // all copies or substantial portions of the Software. cannam@147: // cannam@147: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR cannam@147: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, cannam@147: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE cannam@147: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER cannam@147: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, cannam@147: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN cannam@147: // THE SOFTWARE. cannam@147: cannam@147: // This file declares convenient macros for debug logging and error handling. The macros make cannam@147: // it excessively easy to extract useful context information from code. Example: cannam@147: // cannam@147: // KJ_ASSERT(a == b, a, b, "a and b must be the same."); cannam@147: // cannam@147: // On failure, this will throw an exception whose description looks like: cannam@147: // cannam@147: // myfile.c++:43: bug in code: expected a == b; a = 14; b = 72; a and b must be the same. cannam@147: // cannam@147: // As you can see, all arguments after the first provide additional context. cannam@147: // cannam@147: // The macros available are: cannam@147: // cannam@147: // * `KJ_LOG(severity, ...)`: Just writes a log message, to stderr by default (but you can cannam@147: // intercept messages by implementing an ExceptionCallback). `severity` is `INFO`, `WARNING`, cannam@147: // `ERROR`, or `FATAL`. By default, `INFO` logs are not written, but for command-line apps the cannam@147: // user should be able to pass a flag like `--verbose` to enable them. Other log levels are cannam@147: // enabled by default. Log messages -- like exceptions -- can be intercepted by registering an cannam@147: // ExceptionCallback. cannam@147: // cannam@147: // * `KJ_DBG(...)`: Like `KJ_LOG`, but intended specifically for temporary log lines added while cannam@147: // debugging a particular problem. Calls to `KJ_DBG` should always be deleted before committing cannam@147: // code. It is suggested that you set up a pre-commit hook that checks for this. cannam@147: // cannam@147: // * `KJ_ASSERT(condition, ...)`: Throws an exception if `condition` is false, or aborts if cannam@147: // exceptions are disabled. This macro should be used to check for bugs in the surrounding code cannam@147: // and its dependencies, but NOT to check for invalid input. The macro may be followed by a cannam@147: // brace-delimited code block; if so, the block will be executed in the case where the assertion cannam@147: // fails, before throwing the exception. If control jumps out of the block (e.g. with "break", cannam@147: // "return", or "goto"), then the error is considered "recoverable" -- in this case, if cannam@147: // exceptions are disabled, execution will continue normally rather than aborting (but if cannam@147: // exceptions are enabled, an exception will still be thrown on exiting the block). A "break" cannam@147: // statement in particular will jump to the code immediately after the block (it does not break cannam@147: // any surrounding loop or switch). Example: cannam@147: // cannam@147: // KJ_ASSERT(value >= 0, "Value cannot be negative.", value) { cannam@147: // // Assertion failed. Set value to zero to "recover". cannam@147: // value = 0; cannam@147: // // Don't abort if exceptions are disabled. Continue normally. cannam@147: // // (Still throw an exception if they are enabled, though.) cannam@147: // break; cannam@147: // } cannam@147: // // When exceptions are disabled, we'll get here even if the assertion fails. cannam@147: // // Otherwise, we get here only if the assertion passes. cannam@147: // cannam@147: // * `KJ_REQUIRE(condition, ...)`: Like `KJ_ASSERT` but used to check preconditions -- e.g. to cannam@147: // validate parameters passed from a caller. A failure indicates that the caller is buggy. cannam@147: // cannam@147: // * `KJ_SYSCALL(code, ...)`: Executes `code` assuming it makes a system call. A negative result cannam@147: // is considered an error, with error code reported via `errno`. EINTR is handled by retrying. cannam@147: // Other errors are handled by throwing an exception. If you need to examine the return code, cannam@147: // assign it to a variable like so: cannam@147: // cannam@147: // int fd; cannam@147: // KJ_SYSCALL(fd = open(filename, O_RDONLY), filename); cannam@147: // cannam@147: // `KJ_SYSCALL` can be followed by a recovery block, just like `KJ_ASSERT`. cannam@147: // cannam@147: // * `KJ_NONBLOCKING_SYSCALL(code, ...)`: Like KJ_SYSCALL, but will not throw an exception on cannam@147: // EAGAIN/EWOULDBLOCK. The calling code should check the syscall's return value to see if it cannam@147: // indicates an error; in this case, it can assume the error was EAGAIN because any other error cannam@147: // would have caused an exception to be thrown. cannam@147: // cannam@147: // * `KJ_CONTEXT(...)`: Notes additional contextual information relevant to any exceptions thrown cannam@147: // from within the current scope. That is, until control exits the block in which KJ_CONTEXT() cannam@147: // is used, if any exception is generated, it will contain the given information in its context cannam@147: // chain. This is helpful because it can otherwise be very difficult to come up with error cannam@147: // messages that make sense within low-level helper code. Note that the parameters to cannam@147: // KJ_CONTEXT() are only evaluated if an exception is thrown. This implies that any variables cannam@147: // used must remain valid until the end of the scope. cannam@147: // cannam@147: // Notes: cannam@147: // * Do not write expressions with side-effects in the message content part of the macro, as the cannam@147: // message will not necessarily be evaluated. cannam@147: // * For every macro `FOO` above except `LOG`, there is also a `FAIL_FOO` macro used to report cannam@147: // failures that already happened. For the macros that check a boolean condition, `FAIL_FOO` cannam@147: // omits the first parameter and behaves like it was `false`. `FAIL_SYSCALL` and cannam@147: // `FAIL_RECOVERABLE_SYSCALL` take a string and an OS error number as the first two parameters. cannam@147: // The string should be the name of the failed system call. cannam@147: // * For every macro `FOO` above, there is a `DFOO` version (or `RECOVERABLE_DFOO`) which is only cannam@147: // executed in debug mode, i.e. when KJ_DEBUG is defined. KJ_DEBUG is defined automatically cannam@147: // by common.h when compiling without optimization (unless NDEBUG is defined), but you can also cannam@147: // define it explicitly (e.g. -DKJ_DEBUG). Generally, production builds should NOT use KJ_DEBUG cannam@147: // as it may enable expensive checks that are unlikely to fail. cannam@147: cannam@147: #ifndef KJ_DEBUG_H_ cannam@147: #define KJ_DEBUG_H_ cannam@147: cannam@147: #if defined(__GNUC__) && !KJ_HEADER_WARNINGS cannam@147: #pragma GCC system_header cannam@147: #endif cannam@147: cannam@147: #include "string.h" cannam@147: #include "exception.h" cannam@147: cannam@147: #ifdef ERROR cannam@147: // This is problematic because windows.h #defines ERROR, which we use in an enum here. cannam@147: #error "Make sure to to undefine ERROR (or just #include ) before this file" cannam@147: #endif cannam@147: cannam@147: namespace kj { cannam@147: cannam@147: #if _MSC_VER cannam@147: // MSVC does __VA_ARGS__ differently from GCC: cannam@147: // - A trailing comma before an empty __VA_ARGS__ is removed automatically, whereas GCC wants cannam@147: // you to request this behavior with "##__VA_ARGS__". cannam@147: // - If __VA_ARGS__ is passed directly as an argument to another macro, it will be treated as a cannam@147: // *single* argument rather than an argument list. This can be worked around by wrapping the cannam@147: // outer macro call in KJ_EXPAND(), which appraently forces __VA_ARGS__ to be expanded before cannam@147: // the macro is evaluated. I don't understand the C preprocessor. cannam@147: // - Using "#__VA_ARGS__" to stringify __VA_ARGS__ expands to zero tokens when __VA_ARGS__ is cannam@147: // empty, rather than expanding to an empty string literal. We can work around by concatenating cannam@147: // with an empty string literal. cannam@147: cannam@147: #define KJ_EXPAND(X) X cannam@147: cannam@147: #define KJ_LOG(severity, ...) \ cannam@147: if (!::kj::_::Debug::shouldLog(::kj::LogSeverity::severity)) {} else \ cannam@147: ::kj::_::Debug::log(__FILE__, __LINE__, ::kj::LogSeverity::severity, \ cannam@147: "" #__VA_ARGS__, __VA_ARGS__) cannam@147: cannam@147: #define KJ_DBG(...) KJ_EXPAND(KJ_LOG(DBG, __VA_ARGS__)) cannam@147: cannam@147: #define KJ_REQUIRE(cond, ...) \ cannam@147: if (KJ_LIKELY(cond)) {} else \ cannam@147: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ cannam@147: #cond, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) cannam@147: cannam@147: #define KJ_FAIL_REQUIRE(...) \ cannam@147: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ cannam@147: nullptr, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) cannam@147: cannam@147: #define KJ_SYSCALL(call, ...) \ cannam@147: if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, false)) {} else \ cannam@147: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ cannam@147: _kjSyscallResult.getErrorNumber(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) cannam@147: cannam@147: #define KJ_NONBLOCKING_SYSCALL(call, ...) \ cannam@147: if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, true)) {} else \ cannam@147: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ cannam@147: _kjSyscallResult.getErrorNumber(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) cannam@147: cannam@147: #define KJ_FAIL_SYSCALL(code, errorNumber, ...) \ cannam@147: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ cannam@147: errorNumber, code, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) cannam@147: cannam@147: #if _WIN32 cannam@147: cannam@147: #define KJ_WIN32(call, ...) \ cannam@147: if (::kj::_::Debug::isWin32Success(call)) {} else \ cannam@147: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ cannam@147: ::kj::_::Debug::getWin32Error(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) cannam@147: cannam@147: #define KJ_WINSOCK(call, ...) \ cannam@147: if ((call) != SOCKET_ERROR) {} else \ cannam@147: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ cannam@147: ::kj::_::Debug::getWin32Error(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) cannam@147: cannam@147: #define KJ_FAIL_WIN32(code, errorNumber, ...) \ cannam@147: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ cannam@147: ::kj::_::Debug::Win32Error(errorNumber), code, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) cannam@147: cannam@147: #endif cannam@147: cannam@147: #define KJ_UNIMPLEMENTED(...) \ cannam@147: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::UNIMPLEMENTED, \ cannam@147: nullptr, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal()) cannam@147: cannam@147: // TODO(msvc): MSVC mis-deduces `ContextImpl` as `ContextImpl` in some edge cannam@147: // cases, such as inside nested lambdas inside member functions. Wrapping the type in cannam@147: // `decltype(instance<...>())` helps it deduce the context function's type correctly. cannam@147: #define KJ_CONTEXT(...) \ cannam@147: auto KJ_UNIQUE_NAME(_kjContextFunc) = [&]() -> ::kj::_::Debug::Context::Value { \ cannam@147: return ::kj::_::Debug::Context::Value(__FILE__, __LINE__, \ cannam@147: ::kj::_::Debug::makeDescription("" #__VA_ARGS__, __VA_ARGS__)); \ cannam@147: }; \ cannam@147: decltype(::kj::instance<::kj::_::Debug::ContextImpl>()) \ cannam@147: KJ_UNIQUE_NAME(_kjContext)(KJ_UNIQUE_NAME(_kjContextFunc)) cannam@147: cannam@147: #define KJ_REQUIRE_NONNULL(value, ...) \ cannam@147: (*[&] { \ cannam@147: auto _kj_result = ::kj::_::readMaybe(value); \ cannam@147: if (KJ_UNLIKELY(!_kj_result)) { \ cannam@147: ::kj::_::Debug::Fault(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ cannam@147: #value " != nullptr", "" #__VA_ARGS__, __VA_ARGS__).fatal(); \ cannam@147: } \ cannam@147: return _kj_result; \ cannam@147: }()) cannam@147: cannam@147: #define KJ_EXCEPTION(type, ...) \ cannam@147: ::kj::Exception(::kj::Exception::Type::type, __FILE__, __LINE__, \ cannam@147: ::kj::_::Debug::makeDescription("" #__VA_ARGS__, __VA_ARGS__)) cannam@147: cannam@147: #else cannam@147: cannam@147: #define KJ_LOG(severity, ...) \ cannam@147: if (!::kj::_::Debug::shouldLog(::kj::LogSeverity::severity)) {} else \ cannam@147: ::kj::_::Debug::log(__FILE__, __LINE__, ::kj::LogSeverity::severity, \ cannam@147: #__VA_ARGS__, ##__VA_ARGS__) cannam@147: cannam@147: #define KJ_DBG(...) KJ_LOG(DBG, ##__VA_ARGS__) cannam@147: cannam@147: #define KJ_REQUIRE(cond, ...) \ cannam@147: if (KJ_LIKELY(cond)) {} else \ cannam@147: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ cannam@147: #cond, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) cannam@147: cannam@147: #define KJ_FAIL_REQUIRE(...) \ cannam@147: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ cannam@147: nullptr, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) cannam@147: cannam@147: #define KJ_SYSCALL(call, ...) \ cannam@147: if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, false)) {} else \ cannam@147: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ cannam@147: _kjSyscallResult.getErrorNumber(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) cannam@147: cannam@147: #define KJ_NONBLOCKING_SYSCALL(call, ...) \ cannam@147: if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, true)) {} else \ cannam@147: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ cannam@147: _kjSyscallResult.getErrorNumber(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) cannam@147: cannam@147: #define KJ_FAIL_SYSCALL(code, errorNumber, ...) \ cannam@147: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ cannam@147: errorNumber, code, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) cannam@147: cannam@147: #if _WIN32 cannam@147: cannam@147: #define KJ_WIN32(call, ...) \ cannam@147: if (::kj::_::Debug::isWin32Success(call)) {} else \ cannam@147: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ cannam@147: ::kj::_::Debug::getWin32Error(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) cannam@147: cannam@147: #define KJ_WINSOCK(call, ...) \ cannam@147: if ((call) != SOCKET_ERROR) {} else \ cannam@147: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ cannam@147: ::kj::_::Debug::getWin32Error(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) cannam@147: cannam@147: #define KJ_FAIL_WIN32(code, errorNumber, ...) \ cannam@147: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \ cannam@147: ::kj::_::Debug::Win32Error(errorNumber), code, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) cannam@147: cannam@147: #endif cannam@147: cannam@147: #define KJ_UNIMPLEMENTED(...) \ cannam@147: for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::UNIMPLEMENTED, \ cannam@147: nullptr, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal()) cannam@147: cannam@147: #define KJ_CONTEXT(...) \ cannam@147: auto KJ_UNIQUE_NAME(_kjContextFunc) = [&]() -> ::kj::_::Debug::Context::Value { \ cannam@147: return ::kj::_::Debug::Context::Value(__FILE__, __LINE__, \ cannam@147: ::kj::_::Debug::makeDescription(#__VA_ARGS__, ##__VA_ARGS__)); \ cannam@147: }; \ cannam@147: ::kj::_::Debug::ContextImpl \ cannam@147: KJ_UNIQUE_NAME(_kjContext)(KJ_UNIQUE_NAME(_kjContextFunc)) cannam@147: cannam@147: #define KJ_REQUIRE_NONNULL(value, ...) \ cannam@147: (*({ \ cannam@147: auto _kj_result = ::kj::_::readMaybe(value); \ cannam@147: if (KJ_UNLIKELY(!_kj_result)) { \ cannam@147: ::kj::_::Debug::Fault(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \ cannam@147: #value " != nullptr", #__VA_ARGS__, ##__VA_ARGS__).fatal(); \ cannam@147: } \ cannam@147: kj::mv(_kj_result); \ cannam@147: })) cannam@147: cannam@147: #define KJ_EXCEPTION(type, ...) \ cannam@147: ::kj::Exception(::kj::Exception::Type::type, __FILE__, __LINE__, \ cannam@147: ::kj::_::Debug::makeDescription(#__VA_ARGS__, ##__VA_ARGS__)) cannam@147: cannam@147: #endif cannam@147: cannam@147: #define KJ_SYSCALL_HANDLE_ERRORS(call) \ cannam@147: if (int _kjSyscallError = ::kj::_::Debug::syscallError([&](){return (call);}, false)) \ cannam@147: switch (int error = _kjSyscallError) cannam@147: // Like KJ_SYSCALL, but doesn't throw. Instead, the block after the macro is a switch block on the cannam@147: // error. Additionally, the int value `error` is defined within the block. So you can do: cannam@147: // cannam@147: // KJ_SYSCALL_HANDLE_ERRORS(foo()) { cannam@147: // case ENOENT: cannam@147: // handleNoSuchFile(); cannam@147: // break; cannam@147: // case EEXIST: cannam@147: // handleExists(); cannam@147: // break; cannam@147: // default: cannam@147: // KJ_FAIL_SYSCALL("foo()", error); cannam@147: // } else { cannam@147: // handleSuccessCase(); cannam@147: // } cannam@147: cannam@147: #define KJ_ASSERT KJ_REQUIRE cannam@147: #define KJ_FAIL_ASSERT KJ_FAIL_REQUIRE cannam@147: #define KJ_ASSERT_NONNULL KJ_REQUIRE_NONNULL cannam@147: // Use "ASSERT" in place of "REQUIRE" when the problem is local to the immediate surrounding code. cannam@147: // That is, if the assert ever fails, it indicates that the immediate surrounding code is broken. cannam@147: cannam@147: #ifdef KJ_DEBUG cannam@147: #define KJ_DLOG KJ_LOG cannam@147: #define KJ_DASSERT KJ_ASSERT cannam@147: #define KJ_DREQUIRE KJ_REQUIRE cannam@147: #else cannam@147: #define KJ_DLOG(...) do {} while (false) cannam@147: #define KJ_DASSERT(...) do {} while (false) cannam@147: #define KJ_DREQUIRE(...) do {} while (false) cannam@147: #endif cannam@147: cannam@147: namespace _ { // private cannam@147: cannam@147: class Debug { cannam@147: public: cannam@147: Debug() = delete; cannam@147: cannam@147: typedef LogSeverity Severity; // backwards-compatibility cannam@147: cannam@147: #if _WIN32 cannam@147: struct Win32Error { cannam@147: // Hack for overloading purposes. cannam@147: uint number; cannam@147: inline explicit Win32Error(uint number): number(number) {} cannam@147: }; cannam@147: #endif cannam@147: cannam@147: static inline bool shouldLog(LogSeverity severity) { return severity >= minSeverity; } cannam@147: // Returns whether messages of the given severity should be logged. cannam@147: cannam@147: static inline void setLogLevel(LogSeverity severity) { minSeverity = severity; } cannam@147: // Set the minimum message severity which will be logged. cannam@147: // cannam@147: // TODO(someday): Expose publicly. cannam@147: cannam@147: template cannam@147: static void log(const char* file, int line, LogSeverity severity, const char* macroArgs, cannam@147: Params&&... params); cannam@147: cannam@147: class Fault { cannam@147: public: cannam@147: template cannam@147: Fault(const char* file, int line, Code code, cannam@147: const char* condition, const char* macroArgs, Params&&... params); cannam@147: Fault(const char* file, int line, Exception::Type type, cannam@147: const char* condition, const char* macroArgs); cannam@147: Fault(const char* file, int line, int osErrorNumber, cannam@147: const char* condition, const char* macroArgs); cannam@147: #if _WIN32 cannam@147: Fault(const char* file, int line, Win32Error osErrorNumber, cannam@147: const char* condition, const char* macroArgs); cannam@147: #endif cannam@147: ~Fault() noexcept(false); cannam@147: cannam@147: KJ_NOINLINE KJ_NORETURN(void fatal()); cannam@147: // Throw the exception. cannam@147: cannam@147: private: cannam@147: void init(const char* file, int line, Exception::Type type, cannam@147: const char* condition, const char* macroArgs, ArrayPtr argValues); cannam@147: void init(const char* file, int line, int osErrorNumber, cannam@147: const char* condition, const char* macroArgs, ArrayPtr argValues); cannam@147: #if _WIN32 cannam@147: void init(const char* file, int line, Win32Error osErrorNumber, cannam@147: const char* condition, const char* macroArgs, ArrayPtr argValues); cannam@147: #endif cannam@147: cannam@147: Exception* exception; cannam@147: }; cannam@147: cannam@147: class SyscallResult { cannam@147: public: cannam@147: inline SyscallResult(int errorNumber): errorNumber(errorNumber) {} cannam@147: inline operator void*() { return errorNumber == 0 ? this : nullptr; } cannam@147: inline int getErrorNumber() { return errorNumber; } cannam@147: cannam@147: private: cannam@147: int errorNumber; cannam@147: }; cannam@147: cannam@147: template cannam@147: static SyscallResult syscall(Call&& call, bool nonblocking); cannam@147: template cannam@147: static int syscallError(Call&& call, bool nonblocking); cannam@147: cannam@147: #if _WIN32 cannam@147: static bool isWin32Success(int boolean); cannam@147: static bool isWin32Success(void* handle); cannam@147: static Win32Error getWin32Error(); cannam@147: #endif cannam@147: cannam@147: class Context: public ExceptionCallback { cannam@147: public: cannam@147: Context(); cannam@147: KJ_DISALLOW_COPY(Context); cannam@147: virtual ~Context() noexcept(false); cannam@147: cannam@147: struct Value { cannam@147: const char* file; cannam@147: int line; cannam@147: String description; cannam@147: cannam@147: inline Value(const char* file, int line, String&& description) cannam@147: : file(file), line(line), description(mv(description)) {} cannam@147: }; cannam@147: cannam@147: virtual Value evaluate() = 0; cannam@147: cannam@147: virtual void onRecoverableException(Exception&& exception) override; cannam@147: virtual void onFatalException(Exception&& exception) override; cannam@147: virtual void logMessage(LogSeverity severity, const char* file, int line, int contextDepth, cannam@147: String&& text) override; cannam@147: cannam@147: private: cannam@147: bool logged; cannam@147: Maybe value; cannam@147: cannam@147: Value ensureInitialized(); cannam@147: }; cannam@147: cannam@147: template cannam@147: class ContextImpl: public Context { cannam@147: public: cannam@147: inline ContextImpl(Func& func): func(func) {} cannam@147: KJ_DISALLOW_COPY(ContextImpl); cannam@147: cannam@147: Value evaluate() override { cannam@147: return func(); cannam@147: } cannam@147: private: cannam@147: Func& func; cannam@147: }; cannam@147: cannam@147: template cannam@147: static String makeDescription(const char* macroArgs, Params&&... params); cannam@147: cannam@147: private: cannam@147: static LogSeverity minSeverity; cannam@147: cannam@147: static void logInternal(const char* file, int line, LogSeverity severity, const char* macroArgs, cannam@147: ArrayPtr argValues); cannam@147: static String makeDescriptionInternal(const char* macroArgs, ArrayPtr argValues); cannam@147: cannam@147: static int getOsErrorNumber(bool nonblocking); cannam@147: // Get the error code of the last error (e.g. from errno). Returns -1 on EINTR. cannam@147: }; cannam@147: cannam@147: template cannam@147: void Debug::log(const char* file, int line, LogSeverity severity, const char* macroArgs, cannam@147: Params&&... params) { cannam@147: String argValues[sizeof...(Params)] = {str(params)...}; cannam@147: logInternal(file, line, severity, macroArgs, arrayPtr(argValues, sizeof...(Params))); cannam@147: } cannam@147: cannam@147: template <> cannam@147: inline void Debug::log<>(const char* file, int line, LogSeverity severity, const char* macroArgs) { cannam@147: logInternal(file, line, severity, macroArgs, nullptr); cannam@147: } cannam@147: cannam@147: template cannam@147: Debug::Fault::Fault(const char* file, int line, Code code, cannam@147: const char* condition, const char* macroArgs, Params&&... params) cannam@147: : exception(nullptr) { cannam@147: String argValues[sizeof...(Params)] = {str(params)...}; cannam@147: init(file, line, code, condition, macroArgs, cannam@147: arrayPtr(argValues, sizeof...(Params))); cannam@147: } cannam@147: cannam@147: inline Debug::Fault::Fault(const char* file, int line, int osErrorNumber, cannam@147: const char* condition, const char* macroArgs) cannam@147: : exception(nullptr) { cannam@147: init(file, line, osErrorNumber, condition, macroArgs, nullptr); cannam@147: } cannam@147: cannam@147: inline Debug::Fault::Fault(const char* file, int line, kj::Exception::Type type, cannam@147: const char* condition, const char* macroArgs) cannam@147: : exception(nullptr) { cannam@147: init(file, line, type, condition, macroArgs, nullptr); cannam@147: } cannam@147: cannam@147: #if _WIN32 cannam@147: inline Debug::Fault::Fault(const char* file, int line, Win32Error osErrorNumber, cannam@147: const char* condition, const char* macroArgs) cannam@147: : exception(nullptr) { cannam@147: init(file, line, osErrorNumber, condition, macroArgs, nullptr); cannam@147: } cannam@147: cannam@147: inline bool Debug::isWin32Success(int boolean) { cannam@147: return boolean; cannam@147: } cannam@147: inline bool Debug::isWin32Success(void* handle) { cannam@147: // Assume null and INVALID_HANDLE_VALUE mean failure. cannam@147: return handle != nullptr && handle != (void*)-1; cannam@147: } cannam@147: #endif cannam@147: cannam@147: template cannam@147: Debug::SyscallResult Debug::syscall(Call&& call, bool nonblocking) { cannam@147: while (call() < 0) { cannam@147: int errorNum = getOsErrorNumber(nonblocking); cannam@147: // getOsErrorNumber() returns -1 to indicate EINTR. cannam@147: // Also, if nonblocking is true, then it returns 0 on EAGAIN, which will then be treated as a cannam@147: // non-error. cannam@147: if (errorNum != -1) { cannam@147: return SyscallResult(errorNum); cannam@147: } cannam@147: } cannam@147: return SyscallResult(0); cannam@147: } cannam@147: cannam@147: template cannam@147: int Debug::syscallError(Call&& call, bool nonblocking) { cannam@147: while (call() < 0) { cannam@147: int errorNum = getOsErrorNumber(nonblocking); cannam@147: // getOsErrorNumber() returns -1 to indicate EINTR. cannam@147: // Also, if nonblocking is true, then it returns 0 on EAGAIN, which will then be treated as a cannam@147: // non-error. cannam@147: if (errorNum != -1) { cannam@147: return errorNum; cannam@147: } cannam@147: } cannam@147: return 0; cannam@147: } cannam@147: cannam@147: template cannam@147: String Debug::makeDescription(const char* macroArgs, Params&&... params) { cannam@147: String argValues[sizeof...(Params)] = {str(params)...}; cannam@147: return makeDescriptionInternal(macroArgs, arrayPtr(argValues, sizeof...(Params))); cannam@147: } cannam@147: cannam@147: template <> cannam@147: inline String Debug::makeDescription<>(const char* macroArgs) { cannam@147: return makeDescriptionInternal(macroArgs, nullptr); cannam@147: } cannam@147: cannam@147: } // namespace _ (private) cannam@147: } // namespace kj cannam@147: cannam@147: #endif // KJ_DEBUG_H_