annotate win64-msvc/include/kj/exception.h @ 166:cbd6d7e562c7

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