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