annotate win32-mingw/include/kj/exception.h @ 150:0a1a4a299a5d

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