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