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