annotate osx/include/kj/exception.h @ 83:ae30d91d2ffe

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