cannam@148: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors cannam@148: // Licensed under the MIT License: cannam@148: // cannam@148: // Permission is hereby granted, free of charge, to any person obtaining a copy cannam@148: // of this software and associated documentation files (the "Software"), to deal cannam@148: // in the Software without restriction, including without limitation the rights cannam@148: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell cannam@148: // copies of the Software, and to permit persons to whom the Software is cannam@148: // furnished to do so, subject to the following conditions: cannam@148: // cannam@148: // The above copyright notice and this permission notice shall be included in cannam@148: // all copies or substantial portions of the Software. cannam@148: // cannam@148: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR cannam@148: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, cannam@148: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE cannam@148: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER cannam@148: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, cannam@148: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN cannam@148: // THE SOFTWARE. cannam@148: cannam@148: #ifndef KJ_EXCEPTION_H_ cannam@148: #define KJ_EXCEPTION_H_ cannam@148: cannam@148: #if defined(__GNUC__) && !KJ_HEADER_WARNINGS cannam@148: #pragma GCC system_header cannam@148: #endif cannam@148: cannam@148: #include "memory.h" cannam@148: #include "array.h" cannam@148: #include "string.h" cannam@148: cannam@148: namespace kj { cannam@148: cannam@148: class ExceptionImpl; cannam@148: cannam@148: class Exception { cannam@148: // Exception thrown in case of fatal errors. cannam@148: // cannam@148: // Actually, a subclass of this which also implements std::exception will be thrown, but we hide cannam@148: // that fact from the interface to avoid #including . cannam@148: cannam@148: public: cannam@148: enum class Type { cannam@148: // What kind of failure? cannam@148: cannam@148: FAILED = 0, cannam@148: // Something went wrong. This is the usual error type. KJ_ASSERT and KJ_REQUIRE throw this cannam@148: // error type. cannam@148: cannam@148: OVERLOADED = 1, cannam@148: // The call failed because of a temporary lack of resources. This could be space resources cannam@148: // (out of memory, out of disk space) or time resources (request queue overflow, operation cannam@148: // timed out). cannam@148: // cannam@148: // The operation might work if tried again, but it should NOT be repeated immediately as this cannam@148: // may simply exacerbate the problem. cannam@148: cannam@148: DISCONNECTED = 2, cannam@148: // The call required communication over a connection that has been lost. The callee will need cannam@148: // to re-establish connections and try again. cannam@148: cannam@148: UNIMPLEMENTED = 3 cannam@148: // The requested method is not implemented. The caller may wish to revert to a fallback cannam@148: // approach based on other methods. cannam@148: cannam@148: // IF YOU ADD A NEW VALUE: cannam@148: // - Update the stringifier. cannam@148: // - Update Cap'n Proto's RPC protocol's Exception.Type enum. cannam@148: }; cannam@148: cannam@148: Exception(Type type, const char* file, int line, String description = nullptr) noexcept; cannam@148: Exception(Type type, String file, int line, String description = nullptr) noexcept; cannam@148: Exception(const Exception& other) noexcept; cannam@148: Exception(Exception&& other) = default; cannam@148: ~Exception() noexcept; cannam@148: cannam@148: const char* getFile() const { return file; } cannam@148: int getLine() const { return line; } cannam@148: Type getType() const { return type; } cannam@148: StringPtr getDescription() const { return description; } cannam@148: ArrayPtr getStackTrace() const { return arrayPtr(trace, traceCount); } cannam@148: cannam@148: struct Context { cannam@148: // Describes a bit about what was going on when the exception was thrown. cannam@148: cannam@148: const char* file; cannam@148: int line; cannam@148: String description; cannam@148: Maybe> next; cannam@148: cannam@148: Context(const char* file, int line, String&& description, Maybe>&& next) cannam@148: : file(file), line(line), description(mv(description)), next(mv(next)) {} cannam@148: Context(const Context& other) noexcept; cannam@148: }; cannam@148: cannam@148: inline Maybe getContext() const { cannam@148: KJ_IF_MAYBE(c, context) { cannam@148: return **c; cannam@148: } else { cannam@148: return nullptr; cannam@148: } cannam@148: } cannam@148: cannam@148: void wrapContext(const char* file, int line, String&& description); cannam@148: // Wraps the context in a new node. This becomes the head node returned by getContext() -- it cannam@148: // is expected that contexts will be added in reverse order as the exception passes up the cannam@148: // callback stack. cannam@148: cannam@148: KJ_NOINLINE void extendTrace(uint ignoreCount); cannam@148: // Append the current stack trace to the exception's trace, ignoring the first `ignoreCount` cannam@148: // frames (see `getStackTrace()` for discussion of `ignoreCount`). cannam@148: cannam@148: KJ_NOINLINE void truncateCommonTrace(); cannam@148: // Remove the part of the stack trace which the exception shares with the caller of this method. cannam@148: // This is used by the async library to remove the async infrastructure from the stack trace cannam@148: // before replacing it with the async trace. cannam@148: cannam@148: void addTrace(void* ptr); cannam@148: // Append the given pointer to the backtrace, if it is not already full. This is used by the cannam@148: // async library to trace through the promise chain that led to the exception. cannam@148: cannam@148: private: cannam@148: String ownFile; cannam@148: const char* file; cannam@148: int line; cannam@148: Type type; cannam@148: String description; cannam@148: Maybe> context; cannam@148: void* trace[32]; cannam@148: uint traceCount; cannam@148: cannam@148: friend class ExceptionImpl; cannam@148: }; cannam@148: cannam@148: StringPtr KJ_STRINGIFY(Exception::Type type); cannam@148: String KJ_STRINGIFY(const Exception& e); cannam@148: cannam@148: // ======================================================================================= cannam@148: cannam@148: enum class LogSeverity { cannam@148: INFO, // Information describing what the code is up to, which users may request to see cannam@148: // with a flag like `--verbose`. Does not indicate a problem. Not printed by cannam@148: // default; you must call setLogLevel(INFO) to enable. cannam@148: WARNING, // A problem was detected but execution can continue with correct output. cannam@148: ERROR, // Something is wrong, but execution can continue with garbage output. cannam@148: FATAL, // Something went wrong, and execution cannot continue. cannam@148: DBG // Temporary debug logging. See KJ_DBG. cannam@148: cannam@148: // Make sure to update the stringifier if you add a new severity level. cannam@148: }; cannam@148: cannam@148: StringPtr KJ_STRINGIFY(LogSeverity severity); cannam@148: cannam@148: class ExceptionCallback { cannam@148: // If you don't like C++ exceptions, you may implement and register an ExceptionCallback in order cannam@148: // to perform your own exception handling. For example, a reasonable thing to do is to have cannam@148: // onRecoverableException() set a flag indicating that an error occurred, and then check for that cannam@148: // flag just before writing to storage and/or returning results to the user. If the flag is set, cannam@148: // discard whatever you have and return an error instead. cannam@148: // cannam@148: // ExceptionCallbacks must always be allocated on the stack. When an exception is thrown, the cannam@148: // newest ExceptionCallback on the calling thread's stack is called. The default implementation cannam@148: // of each method calls the next-oldest ExceptionCallback for that thread. Thus the callbacks cannam@148: // behave a lot like try/catch blocks, except that they are called before any stack unwinding cannam@148: // occurs. cannam@148: cannam@148: public: cannam@148: ExceptionCallback(); cannam@148: KJ_DISALLOW_COPY(ExceptionCallback); cannam@148: virtual ~ExceptionCallback() noexcept(false); cannam@148: cannam@148: virtual void onRecoverableException(Exception&& exception); cannam@148: // Called when an exception has been raised, but the calling code has the ability to continue by cannam@148: // producing garbage output. This method _should_ throw the exception, but is allowed to simply cannam@148: // return if garbage output is acceptable. cannam@148: // cannam@148: // The global default implementation throws an exception unless the library was compiled with cannam@148: // -fno-exceptions, in which case it logs an error and returns. cannam@148: cannam@148: virtual void onFatalException(Exception&& exception); cannam@148: // Called when an exception has been raised and the calling code cannot continue. If this method cannam@148: // returns normally, abort() will be called. The method must throw the exception to avoid cannam@148: // aborting. cannam@148: // cannam@148: // The global default implementation throws an exception unless the library was compiled with cannam@148: // -fno-exceptions, in which case it logs an error and returns. cannam@148: cannam@148: virtual void logMessage(LogSeverity severity, const char* file, int line, int contextDepth, cannam@148: String&& text); cannam@148: // Called when something wants to log some debug text. `contextDepth` indicates how many levels cannam@148: // of context the message passed through; it may make sense to indent the message accordingly. cannam@148: // cannam@148: // The global default implementation writes the text to stderr. cannam@148: cannam@148: enum class StackTraceMode { cannam@148: FULL, cannam@148: // Stringifying a stack trace will attempt to determine source file and line numbers. This may cannam@148: // be expensive. For example, on Linux, this shells out to `addr2line`. cannam@148: // cannam@148: // This is the default in debug builds. cannam@148: cannam@148: ADDRESS_ONLY, cannam@148: // Stringifying a stack trace will only generate a list of code addresses. cannam@148: // cannam@148: // This is the default in release builds. cannam@148: cannam@148: NONE cannam@148: // Generating a stack trace will always return an empty array. cannam@148: // cannam@148: // This avoids ever unwinding the stack. On Windows in particular, the stack unwinding library cannam@148: // has been observed to be pretty slow, so exception-heavy code might benefit significantly cannam@148: // from this setting. (But exceptions should be rare...) cannam@148: }; cannam@148: cannam@148: virtual StackTraceMode stackTraceMode(); cannam@148: // Returns the current preferred stack trace mode. cannam@148: cannam@148: protected: cannam@148: ExceptionCallback& next; cannam@148: cannam@148: private: cannam@148: ExceptionCallback(ExceptionCallback& next); cannam@148: cannam@148: class RootExceptionCallback; cannam@148: friend ExceptionCallback& getExceptionCallback(); cannam@148: }; cannam@148: cannam@148: ExceptionCallback& getExceptionCallback(); cannam@148: // Returns the current exception callback. cannam@148: cannam@148: KJ_NOINLINE KJ_NORETURN(void throwFatalException(kj::Exception&& exception, uint ignoreCount = 0)); cannam@148: // Invoke the exception callback to throw the given fatal exception. If the exception callback cannam@148: // returns, abort. cannam@148: cannam@148: KJ_NOINLINE void throwRecoverableException(kj::Exception&& exception, uint ignoreCount = 0); cannam@148: // Invoke the exception callback to throw the given recoverable exception. If the exception cannam@148: // callback returns, return normally. cannam@148: cannam@148: // ======================================================================================= cannam@148: cannam@148: namespace _ { class Runnable; } cannam@148: cannam@148: template cannam@148: Maybe runCatchingExceptions(Func&& func) noexcept; cannam@148: // Executes the given function (usually, a lambda returning nothing) catching any exceptions that cannam@148: // are thrown. Returns the Exception if there was one, or null if the operation completed normally. cannam@148: // Non-KJ exceptions will be wrapped. cannam@148: // cannam@148: // If exception are disabled (e.g. with -fno-exceptions), this will still detect whether any cannam@148: // recoverable exceptions occurred while running the function and will return those. cannam@148: cannam@148: class UnwindDetector { cannam@148: // Utility for detecting when a destructor is called due to unwind. Useful for: cannam@148: // - Avoiding throwing exceptions in this case, which would terminate the program. cannam@148: // - Detecting whether to commit or roll back a transaction. cannam@148: // cannam@148: // To use this class, either inherit privately from it or declare it as a member. The detector cannam@148: // works by comparing the exception state against that when the constructor was called, so for cannam@148: // an object that was actually constructed during exception unwind, it will behave as if no cannam@148: // unwind is taking place. This is usually the desired behavior. cannam@148: cannam@148: public: cannam@148: UnwindDetector(); cannam@148: cannam@148: bool isUnwinding() const; cannam@148: // Returns true if the current thread is in a stack unwind that it wasn't in at the time the cannam@148: // object was constructed. cannam@148: cannam@148: template cannam@148: void catchExceptionsIfUnwinding(Func&& func) const; cannam@148: // Runs the given function (e.g., a lambda). If isUnwinding() is true, any exceptions are cannam@148: // caught and treated as secondary faults, meaning they are considered to be side-effects of the cannam@148: // exception that is unwinding the stack. Otherwise, exceptions are passed through normally. cannam@148: cannam@148: private: cannam@148: uint uncaughtCount; cannam@148: cannam@148: void catchExceptionsAsSecondaryFaults(_::Runnable& runnable) const; cannam@148: }; cannam@148: cannam@148: namespace _ { // private cannam@148: cannam@148: class Runnable { cannam@148: public: cannam@148: virtual void run() = 0; cannam@148: }; cannam@148: cannam@148: template cannam@148: class RunnableImpl: public Runnable { cannam@148: public: cannam@148: RunnableImpl(Func&& func): func(kj::mv(func)) {} cannam@148: void run() override { cannam@148: func(); cannam@148: } cannam@148: private: cannam@148: Func func; cannam@148: }; cannam@148: cannam@148: Maybe runCatchingExceptions(Runnable& runnable) noexcept; cannam@148: cannam@148: } // namespace _ (private) cannam@148: cannam@148: template cannam@148: Maybe runCatchingExceptions(Func&& func) noexcept { cannam@148: _::RunnableImpl> runnable(kj::fwd(func)); cannam@148: return _::runCatchingExceptions(runnable); cannam@148: } cannam@148: cannam@148: template cannam@148: void UnwindDetector::catchExceptionsIfUnwinding(Func&& func) const { cannam@148: if (isUnwinding()) { cannam@148: _::RunnableImpl> runnable(kj::fwd(func)); cannam@148: catchExceptionsAsSecondaryFaults(runnable); cannam@148: } else { cannam@148: func(); cannam@148: } cannam@148: } cannam@148: cannam@148: #define KJ_ON_SCOPE_SUCCESS(code) \ cannam@148: ::kj::UnwindDetector KJ_UNIQUE_NAME(_kjUnwindDetector); \ cannam@148: KJ_DEFER(if (!KJ_UNIQUE_NAME(_kjUnwindDetector).isUnwinding()) { code; }) cannam@148: // Runs `code` if the current scope is exited normally (not due to an exception). cannam@148: cannam@148: #define KJ_ON_SCOPE_FAILURE(code) \ cannam@148: ::kj::UnwindDetector KJ_UNIQUE_NAME(_kjUnwindDetector); \ cannam@148: KJ_DEFER(if (KJ_UNIQUE_NAME(_kjUnwindDetector).isUnwinding()) { code; }) cannam@148: // Runs `code` if the current scope is exited due to an exception. cannam@148: cannam@148: // ======================================================================================= cannam@148: cannam@148: KJ_NOINLINE ArrayPtr getStackTrace(ArrayPtr space, uint ignoreCount); cannam@148: // Attempt to get the current stack trace, returning a list of pointers to instructions. The cannam@148: // returned array is a slice of `space`. Provide a larger `space` to get a deeper stack trace. cannam@148: // If the platform doesn't support stack traces, returns an empty array. cannam@148: // cannam@148: // `ignoreCount` items will be truncated from the front of the trace. This is useful for chopping cannam@148: // off a prefix of the trace that is uninteresting to the developer because it's just locations cannam@148: // inside the debug infrastructure that is requesting the trace. Be careful to mark functions as cannam@148: // KJ_NOINLINE if you intend to count them in `ignoreCount`. Note that, unfortunately, the cannam@148: // ignored entries will still waste space in the `space` array (and the returned array's `begin()` cannam@148: // is never exactly equal to `space.begin()` due to this effect, even if `ignoreCount` is zero cannam@148: // since `getStackTrace()` needs to ignore its own internal frames). cannam@148: cannam@148: String stringifyStackTrace(ArrayPtr); cannam@148: // Convert the stack trace to a string with file names and line numbers. This may involve executing cannam@148: // suprocesses. cannam@148: cannam@148: String getStackTrace(); cannam@148: // Get a stack trace right now and stringify it. Useful for debugging. cannam@148: cannam@148: void printStackTraceOnCrash(); cannam@148: // Registers signal handlers on common "crash" signals like SIGSEGV that will (attempt to) print cannam@148: // a stack trace. You should call this as early as possible on program startup. Programs using cannam@148: // KJ_MAIN get this automatically. cannam@148: cannam@148: kj::StringPtr trimSourceFilename(kj::StringPtr filename); cannam@148: // Given a source code file name, trim off noisy prefixes like "src/" or cannam@148: // "/ekam-provider/canonical/". cannam@148: cannam@148: } // namespace kj cannam@148: cannam@148: #endif // KJ_EXCEPTION_H_