annotate win64-msvc/include/kj/exception.h @ 64:eccd51b72864

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