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