annotate win32-mingw/include/kj/exception.h @ 50:37d53a7e8262

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