annotate win64-msvc/include/kj/exception.h @ 47:d93140aac40b

Current Capnp libs and headers from git
author Chris Cannam
date Thu, 20 Oct 2016 18:15:38 +0100
parents
children 0f2d93caa50c
rev   line source
Chris@47 1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
Chris@47 2 // Licensed under the MIT License:
Chris@47 3 //
Chris@47 4 // Permission is hereby granted, free of charge, to any person obtaining a copy
Chris@47 5 // of this software and associated documentation files (the "Software"), to deal
Chris@47 6 // in the Software without restriction, including without limitation the rights
Chris@47 7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
Chris@47 8 // copies of the Software, and to permit persons to whom the Software is
Chris@47 9 // furnished to do so, subject to the following conditions:
Chris@47 10 //
Chris@47 11 // The above copyright notice and this permission notice shall be included in
Chris@47 12 // all copies or substantial portions of the Software.
Chris@47 13 //
Chris@47 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
Chris@47 15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
Chris@47 16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
Chris@47 17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
Chris@47 18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
Chris@47 19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
Chris@47 20 // THE SOFTWARE.
Chris@47 21
Chris@47 22 #ifndef KJ_EXCEPTION_H_
Chris@47 23 #define KJ_EXCEPTION_H_
Chris@47 24
Chris@47 25 #if defined(__GNUC__) && !KJ_HEADER_WARNINGS
Chris@47 26 #pragma GCC system_header
Chris@47 27 #endif
Chris@47 28
Chris@47 29 #include "memory.h"
Chris@47 30 #include "array.h"
Chris@47 31 #include "string.h"
Chris@47 32
Chris@47 33 namespace kj {
Chris@47 34
Chris@47 35 class ExceptionImpl;
Chris@47 36
Chris@47 37 class Exception {
Chris@47 38 // Exception thrown in case of fatal errors.
Chris@47 39 //
Chris@47 40 // Actually, a subclass of this which also implements std::exception will be thrown, but we hide
Chris@47 41 // that fact from the interface to avoid #including <exception>.
Chris@47 42
Chris@47 43 public:
Chris@47 44 enum class Type {
Chris@47 45 // What kind of failure?
Chris@47 46
Chris@47 47 FAILED = 0,
Chris@47 48 // Something went wrong. This is the usual error type. KJ_ASSERT and KJ_REQUIRE throw this
Chris@47 49 // error type.
Chris@47 50
Chris@47 51 OVERLOADED = 1,
Chris@47 52 // The call failed because of a temporary lack of resources. This could be space resources
Chris@47 53 // (out of memory, out of disk space) or time resources (request queue overflow, operation
Chris@47 54 // timed out).
Chris@47 55 //
Chris@47 56 // The operation might work if tried again, but it should NOT be repeated immediately as this
Chris@47 57 // may simply exacerbate the problem.
Chris@47 58
Chris@47 59 DISCONNECTED = 2,
Chris@47 60 // The call required communication over a connection that has been lost. The callee will need
Chris@47 61 // to re-establish connections and try again.
Chris@47 62
Chris@47 63 UNIMPLEMENTED = 3
Chris@47 64 // The requested method is not implemented. The caller may wish to revert to a fallback
Chris@47 65 // approach based on other methods.
Chris@47 66
Chris@47 67 // IF YOU ADD A NEW VALUE:
Chris@47 68 // - Update the stringifier.
Chris@47 69 // - Update Cap'n Proto's RPC protocol's Exception.Type enum.
Chris@47 70 };
Chris@47 71
Chris@47 72 Exception(Type type, const char* file, int line, String description = nullptr) noexcept;
Chris@47 73 Exception(Type type, String file, int line, String description = nullptr) noexcept;
Chris@47 74 Exception(const Exception& other) noexcept;
Chris@47 75 Exception(Exception&& other) = default;
Chris@47 76 ~Exception() noexcept;
Chris@47 77
Chris@47 78 const char* getFile() const { return file; }
Chris@47 79 int getLine() const { return line; }
Chris@47 80 Type getType() const { return type; }
Chris@47 81 StringPtr getDescription() const { return description; }
Chris@47 82 ArrayPtr<void* const> getStackTrace() const { return arrayPtr(trace, traceCount); }
Chris@47 83
Chris@47 84 struct Context {
Chris@47 85 // Describes a bit about what was going on when the exception was thrown.
Chris@47 86
Chris@47 87 const char* file;
Chris@47 88 int line;
Chris@47 89 String description;
Chris@47 90 Maybe<Own<Context>> next;
Chris@47 91
Chris@47 92 Context(const char* file, int line, String&& description, Maybe<Own<Context>>&& next)
Chris@47 93 : file(file), line(line), description(mv(description)), next(mv(next)) {}
Chris@47 94 Context(const Context& other) noexcept;
Chris@47 95 };
Chris@47 96
Chris@47 97 inline Maybe<const Context&> getContext() const {
Chris@47 98 KJ_IF_MAYBE(c, context) {
Chris@47 99 return **c;
Chris@47 100 } else {
Chris@47 101 return nullptr;
Chris@47 102 }
Chris@47 103 }
Chris@47 104
Chris@47 105 void wrapContext(const char* file, int line, String&& description);
Chris@47 106 // Wraps the context in a new node. This becomes the head node returned by getContext() -- it
Chris@47 107 // is expected that contexts will be added in reverse order as the exception passes up the
Chris@47 108 // callback stack.
Chris@47 109
Chris@47 110 KJ_NOINLINE void extendTrace(uint ignoreCount);
Chris@47 111 // Append the current stack trace to the exception's trace, ignoring the first `ignoreCount`
Chris@47 112 // frames (see `getStackTrace()` for discussion of `ignoreCount`).
Chris@47 113
Chris@47 114 KJ_NOINLINE void truncateCommonTrace();
Chris@47 115 // Remove the part of the stack trace which the exception shares with the caller of this method.
Chris@47 116 // This is used by the async library to remove the async infrastructure from the stack trace
Chris@47 117 // before replacing it with the async trace.
Chris@47 118
Chris@47 119 void addTrace(void* ptr);
Chris@47 120 // Append the given pointer to the backtrace, if it is not already full. This is used by the
Chris@47 121 // async library to trace through the promise chain that led to the exception.
Chris@47 122
Chris@47 123 private:
Chris@47 124 String ownFile;
Chris@47 125 const char* file;
Chris@47 126 int line;
Chris@47 127 Type type;
Chris@47 128 String description;
Chris@47 129 Maybe<Own<Context>> context;
Chris@47 130 void* trace[32];
Chris@47 131 uint traceCount;
Chris@47 132
Chris@47 133 friend class ExceptionImpl;
Chris@47 134 };
Chris@47 135
Chris@47 136 StringPtr KJ_STRINGIFY(Exception::Type type);
Chris@47 137 String KJ_STRINGIFY(const Exception& e);
Chris@47 138
Chris@47 139 // =======================================================================================
Chris@47 140
Chris@47 141 enum class LogSeverity {
Chris@47 142 INFO, // Information describing what the code is up to, which users may request to see
Chris@47 143 // with a flag like `--verbose`. Does not indicate a problem. Not printed by
Chris@47 144 // default; you must call setLogLevel(INFO) to enable.
Chris@47 145 WARNING, // A problem was detected but execution can continue with correct output.
Chris@47 146 ERROR, // Something is wrong, but execution can continue with garbage output.
Chris@47 147 FATAL, // Something went wrong, and execution cannot continue.
Chris@47 148 DBG // Temporary debug logging. See KJ_DBG.
Chris@47 149
Chris@47 150 // Make sure to update the stringifier if you add a new severity level.
Chris@47 151 };
Chris@47 152
Chris@47 153 StringPtr KJ_STRINGIFY(LogSeverity severity);
Chris@47 154
Chris@47 155 class ExceptionCallback {
Chris@47 156 // If you don't like C++ exceptions, you may implement and register an ExceptionCallback in order
Chris@47 157 // to perform your own exception handling. For example, a reasonable thing to do is to have
Chris@47 158 // onRecoverableException() set a flag indicating that an error occurred, and then check for that
Chris@47 159 // flag just before writing to storage and/or returning results to the user. If the flag is set,
Chris@47 160 // discard whatever you have and return an error instead.
Chris@47 161 //
Chris@47 162 // ExceptionCallbacks must always be allocated on the stack. When an exception is thrown, the
Chris@47 163 // newest ExceptionCallback on the calling thread's stack is called. The default implementation
Chris@47 164 // of each method calls the next-oldest ExceptionCallback for that thread. Thus the callbacks
Chris@47 165 // behave a lot like try/catch blocks, except that they are called before any stack unwinding
Chris@47 166 // occurs.
Chris@47 167
Chris@47 168 public:
Chris@47 169 ExceptionCallback();
Chris@47 170 KJ_DISALLOW_COPY(ExceptionCallback);
Chris@47 171 virtual ~ExceptionCallback() noexcept(false);
Chris@47 172
Chris@47 173 virtual void onRecoverableException(Exception&& exception);
Chris@47 174 // Called when an exception has been raised, but the calling code has the ability to continue by
Chris@47 175 // producing garbage output. This method _should_ throw the exception, but is allowed to simply
Chris@47 176 // return if garbage output is acceptable.
Chris@47 177 //
Chris@47 178 // The global default implementation throws an exception unless the library was compiled with
Chris@47 179 // -fno-exceptions, in which case it logs an error and returns.
Chris@47 180
Chris@47 181 virtual void onFatalException(Exception&& exception);
Chris@47 182 // Called when an exception has been raised and the calling code cannot continue. If this method
Chris@47 183 // returns normally, abort() will be called. The method must throw the exception to avoid
Chris@47 184 // aborting.
Chris@47 185 //
Chris@47 186 // The global default implementation throws an exception unless the library was compiled with
Chris@47 187 // -fno-exceptions, in which case it logs an error and returns.
Chris@47 188
Chris@47 189 virtual void logMessage(LogSeverity severity, const char* file, int line, int contextDepth,
Chris@47 190 String&& text);
Chris@47 191 // Called when something wants to log some debug text. `contextDepth` indicates how many levels
Chris@47 192 // of context the message passed through; it may make sense to indent the message accordingly.
Chris@47 193 //
Chris@47 194 // The global default implementation writes the text to stderr.
Chris@47 195
Chris@47 196 protected:
Chris@47 197 ExceptionCallback& next;
Chris@47 198
Chris@47 199 private:
Chris@47 200 ExceptionCallback(ExceptionCallback& next);
Chris@47 201
Chris@47 202 class RootExceptionCallback;
Chris@47 203 friend ExceptionCallback& getExceptionCallback();
Chris@47 204 };
Chris@47 205
Chris@47 206 ExceptionCallback& getExceptionCallback();
Chris@47 207 // Returns the current exception callback.
Chris@47 208
Chris@47 209 KJ_NOINLINE KJ_NORETURN(void throwFatalException(kj::Exception&& exception, uint ignoreCount = 0));
Chris@47 210 // Invoke the exception callback to throw the given fatal exception. If the exception callback
Chris@47 211 // returns, abort.
Chris@47 212
Chris@47 213 KJ_NOINLINE void throwRecoverableException(kj::Exception&& exception, uint ignoreCount = 0);
Chris@47 214 // Invoke the exception callback to throw the given recoverable exception. If the exception
Chris@47 215 // callback returns, return normally.
Chris@47 216
Chris@47 217 // =======================================================================================
Chris@47 218
Chris@47 219 namespace _ { class Runnable; }
Chris@47 220
Chris@47 221 template <typename Func>
Chris@47 222 Maybe<Exception> runCatchingExceptions(Func&& func) noexcept;
Chris@47 223 // Executes the given function (usually, a lambda returning nothing) catching any exceptions that
Chris@47 224 // are thrown. Returns the Exception if there was one, or null if the operation completed normally.
Chris@47 225 // Non-KJ exceptions will be wrapped.
Chris@47 226 //
Chris@47 227 // If exception are disabled (e.g. with -fno-exceptions), this will still detect whether any
Chris@47 228 // recoverable exceptions occurred while running the function and will return those.
Chris@47 229
Chris@47 230 class UnwindDetector {
Chris@47 231 // Utility for detecting when a destructor is called due to unwind. Useful for:
Chris@47 232 // - Avoiding throwing exceptions in this case, which would terminate the program.
Chris@47 233 // - Detecting whether to commit or roll back a transaction.
Chris@47 234 //
Chris@47 235 // To use this class, either inherit privately from it or declare it as a member. The detector
Chris@47 236 // works by comparing the exception state against that when the constructor was called, so for
Chris@47 237 // an object that was actually constructed during exception unwind, it will behave as if no
Chris@47 238 // unwind is taking place. This is usually the desired behavior.
Chris@47 239
Chris@47 240 public:
Chris@47 241 UnwindDetector();
Chris@47 242
Chris@47 243 bool isUnwinding() const;
Chris@47 244 // Returns true if the current thread is in a stack unwind that it wasn't in at the time the
Chris@47 245 // object was constructed.
Chris@47 246
Chris@47 247 template <typename Func>
Chris@47 248 void catchExceptionsIfUnwinding(Func&& func) const;
Chris@47 249 // Runs the given function (e.g., a lambda). If isUnwinding() is true, any exceptions are
Chris@47 250 // caught and treated as secondary faults, meaning they are considered to be side-effects of the
Chris@47 251 // exception that is unwinding the stack. Otherwise, exceptions are passed through normally.
Chris@47 252
Chris@47 253 private:
Chris@47 254 uint uncaughtCount;
Chris@47 255
Chris@47 256 void catchExceptionsAsSecondaryFaults(_::Runnable& runnable) const;
Chris@47 257 };
Chris@47 258
Chris@47 259 namespace _ { // private
Chris@47 260
Chris@47 261 class Runnable {
Chris@47 262 public:
Chris@47 263 virtual void run() = 0;
Chris@47 264 };
Chris@47 265
Chris@47 266 template <typename Func>
Chris@47 267 class RunnableImpl: public Runnable {
Chris@47 268 public:
Chris@47 269 RunnableImpl(Func&& func): func(kj::mv(func)) {}
Chris@47 270 void run() override {
Chris@47 271 func();
Chris@47 272 }
Chris@47 273 private:
Chris@47 274 Func func;
Chris@47 275 };
Chris@47 276
Chris@47 277 Maybe<Exception> runCatchingExceptions(Runnable& runnable) noexcept;
Chris@47 278
Chris@47 279 } // namespace _ (private)
Chris@47 280
Chris@47 281 template <typename Func>
Chris@47 282 Maybe<Exception> runCatchingExceptions(Func&& func) noexcept {
Chris@47 283 _::RunnableImpl<Decay<Func>> runnable(kj::fwd<Func>(func));
Chris@47 284 return _::runCatchingExceptions(runnable);
Chris@47 285 }
Chris@47 286
Chris@47 287 template <typename Func>
Chris@47 288 void UnwindDetector::catchExceptionsIfUnwinding(Func&& func) const {
Chris@47 289 if (isUnwinding()) {
Chris@47 290 _::RunnableImpl<Decay<Func>> runnable(kj::fwd<Func>(func));
Chris@47 291 catchExceptionsAsSecondaryFaults(runnable);
Chris@47 292 } else {
Chris@47 293 func();
Chris@47 294 }
Chris@47 295 }
Chris@47 296
Chris@47 297 #define KJ_ON_SCOPE_SUCCESS(code) \
Chris@47 298 ::kj::UnwindDetector KJ_UNIQUE_NAME(_kjUnwindDetector); \
Chris@47 299 KJ_DEFER(if (!KJ_UNIQUE_NAME(_kjUnwindDetector).isUnwinding()) { code; })
Chris@47 300 // Runs `code` if the current scope is exited normally (not due to an exception).
Chris@47 301
Chris@47 302 #define KJ_ON_SCOPE_FAILURE(code) \
Chris@47 303 ::kj::UnwindDetector KJ_UNIQUE_NAME(_kjUnwindDetector); \
Chris@47 304 KJ_DEFER(if (KJ_UNIQUE_NAME(_kjUnwindDetector).isUnwinding()) { code; })
Chris@47 305 // Runs `code` if the current scope is exited due to an exception.
Chris@47 306
Chris@47 307 // =======================================================================================
Chris@47 308
Chris@47 309 KJ_NOINLINE ArrayPtr<void* const> getStackTrace(ArrayPtr<void*> space, uint ignoreCount);
Chris@47 310 // Attempt to get the current stack trace, returning a list of pointers to instructions. The
Chris@47 311 // returned array is a slice of `space`. Provide a larger `space` to get a deeper stack trace.
Chris@47 312 // If the platform doesn't support stack traces, returns an empty array.
Chris@47 313 //
Chris@47 314 // `ignoreCount` items will be truncated from the front of the trace. This is useful for chopping
Chris@47 315 // off a prefix of the trace that is uninteresting to the developer because it's just locations
Chris@47 316 // inside the debug infrastructure that is requesting the trace. Be careful to mark functions as
Chris@47 317 // KJ_NOINLINE if you intend to count them in `ignoreCount`. Note that, unfortunately, the
Chris@47 318 // ignored entries will still waste space in the `space` array (and the returned array's `begin()`
Chris@47 319 // is never exactly equal to `space.begin()` due to this effect, even if `ignoreCount` is zero
Chris@47 320 // since `getStackTrace()` needs to ignore its own internal frames).
Chris@47 321
Chris@47 322 String stringifyStackTrace(ArrayPtr<void* const>);
Chris@47 323 // Convert the stack trace to a string with file names and line numbers. This may involve executing
Chris@47 324 // suprocesses.
Chris@47 325
Chris@47 326 void printStackTraceOnCrash();
Chris@47 327 // Registers signal handlers on common "crash" signals like SIGSEGV that will (attempt to) print
Chris@47 328 // a stack trace. You should call this as early as possible on program startup. Programs using
Chris@47 329 // KJ_MAIN get this automatically.
Chris@47 330
Chris@47 331 kj::StringPtr trimSourceFilename(kj::StringPtr filename);
Chris@47 332 // Given a source code file name, trim off noisy prefixes like "src/" or
Chris@47 333 // "/ekam-provider/canonical/".
Chris@47 334
Chris@47 335 } // namespace kj
Chris@47 336
Chris@47 337 #endif // KJ_EXCEPTION_H_