debug.h 24 KB
Newer Older
Kenton Varda's avatar
Kenton Varda committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
21

22 23 24
// This file declares convenient macros for debug logging and error handling.  The macros make
// it excessively easy to extract useful context information from code.  Example:
//
25
//     KJ_ASSERT(a == b, a, b, "a and b must be the same.");
26 27 28 29 30 31 32 33 34
//
// On failure, this will throw an exception whose description looks like:
//
//     myfile.c++:43: bug in code: expected a == b; a = 14; b = 72; a and b must be the same.
//
// As you can see, all arguments after the first provide additional context.
//
// The macros available are:
//
35 36
// * `KJ_LOG(severity, ...)`:  Just writes a log message, to stderr by default (but you can
//   intercept messages by implementing an ExceptionCallback).  `severity` is `INFO`, `WARNING`,
37 38 39 40 41 42 43 44
//   `ERROR`, or `FATAL`.  By default, `INFO` logs are not written, but for command-line apps the
//   user should be able to pass a flag like `--verbose` to enable them.  Other log levels are
//   enabled by default.  Log messages -- like exceptions -- can be intercepted by registering an
//   ExceptionCallback.
//
// * `KJ_DBG(...)`:  Like `KJ_LOG`, but intended specifically for temporary log lines added while
//   debugging a particular problem.  Calls to `KJ_DBG` should always be deleted before committing
//   code.  It is suggested that you set up a pre-commit hook that checks for this.
45
//
46 47
// * `KJ_ASSERT(condition, ...)`:  Throws an exception if `condition` is false, or aborts if
//   exceptions are disabled.  This macro should be used to check for bugs in the surrounding code
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
//   and its dependencies, but NOT to check for invalid input.  The macro may be followed by a
//   brace-delimited code block; if so, the block will be executed in the case where the assertion
//   fails, before throwing the exception.  If control jumps out of the block (e.g. with "break",
//   "return", or "goto"), then the error is considered "recoverable" -- in this case, if
//   exceptions are disabled, execution will continue normally rather than aborting (but if
//   exceptions are enabled, an exception will still be thrown on exiting the block). A "break"
//   statement in particular will jump to the code immediately after the block (it does not break
//   any surrounding loop or switch).  Example:
//
//       KJ_ASSERT(value >= 0, "Value cannot be negative.", value) {
//         // Assertion failed.  Set value to zero to "recover".
//         value = 0;
//         // Don't abort if exceptions are disabled.  Continue normally.
//         // (Still throw an exception if they are enabled, though.)
//         break;
//       }
//       // When exceptions are disabled, we'll get here even if the assertion fails.
//       // Otherwise, we get here only if the assertion passes.
66
//
67 68
// * `KJ_REQUIRE(condition, ...)`:  Like `KJ_ASSERT` but used to check preconditions -- e.g. to
//   validate parameters passed from a caller.  A failure indicates that the caller is buggy.
69
//
70 71 72 73
// * `KJ_SYSCALL(code, ...)`:  Executes `code` assuming it makes a system call.  A negative result
//   is considered an error, with error code reported via `errno`.  EINTR is handled by retrying.
//   Other errors are handled by throwing an exception.  If you need to examine the return code,
//   assign it to a variable like so:
74 75
//
//       int fd;
76 77 78
//       KJ_SYSCALL(fd = open(filename, O_RDONLY), filename);
//
//   `KJ_SYSCALL` can be followed by a recovery block, just like `KJ_ASSERT`.
79
//
80 81 82 83 84
// * `KJ_NONBLOCKING_SYSCALL(code, ...)`:  Like KJ_SYSCALL, but will not throw an exception on
//   EAGAIN/EWOULDBLOCK.  The calling code should check the syscall's return value to see if it
//   indicates an error; in this case, it can assume the error was EAGAIN because any other error
//   would have caused an exception to be thrown.
//
85 86
// * `KJ_CONTEXT(...)`:  Notes additional contextual information relevant to any exceptions thrown
//   from within the current scope.  That is, until control exits the block in which KJ_CONTEXT()
87 88
//   is used, if any exception is generated, it will contain the given information in its context
//   chain.  This is helpful because it can otherwise be very difficult to come up with error
89 90 91
//   messages that make sense within low-level helper code.  Note that the parameters to
//   KJ_CONTEXT() are only evaluated if an exception is thrown.  This implies that any variables
//   used must remain valid until the end of the scope.
92
//
93 94 95 96 97 98 99 100 101
// Notes:
// * Do not write expressions with side-effects in the message content part of the macro, as the
//   message will not necessarily be evaluated.
// * For every macro `FOO` above except `LOG`, there is also a `FAIL_FOO` macro used to report
//   failures that already happened.  For the macros that check a boolean condition, `FAIL_FOO`
//   omits the first parameter and behaves like it was `false`.  `FAIL_SYSCALL` and
//   `FAIL_RECOVERABLE_SYSCALL` take a string and an OS error number as the first two parameters.
//   The string should be the name of the failed system call.
// * For every macro `FOO` above, there is a `DFOO` version (or `RECOVERABLE_DFOO`) which is only
102 103 104 105
//   executed in debug mode, i.e. when KJ_DEBUG is defined.  KJ_DEBUG is defined automatically
//   by common.h when compiling without optimization (unless NDEBUG is defined), but you can also
//   define it explicitly (e.g. -DKJ_DEBUG).  Generally, production builds should NOT use KJ_DEBUG
//   as it may enable expensive checks that are unlikely to fail.
106

107
#pragma once
108

109 110 111 112
#if defined(__GNUC__) && !KJ_HEADER_WARNINGS
#pragma GCC system_header
#endif

Kenton Varda's avatar
Kenton Varda committed
113
#include "string.h"
114 115
#include "exception.h"

116 117 118 119 120
#ifdef ERROR
// This is problematic because windows.h #defines ERROR, which we use in an enum here.
#error "Make sure to to undefine ERROR (or just #include <kj/windows-sanity.h>) before this file"
#endif

121
namespace kj {
122

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
#if _MSC_VER
// MSVC does __VA_ARGS__ differently from GCC:
// - A trailing comma before an empty __VA_ARGS__ is removed automatically, whereas GCC wants
//   you to request this behavior with "##__VA_ARGS__".
// - If __VA_ARGS__ is passed directly as an argument to another macro, it will be treated as a
//   *single* argument rather than an argument list. This can be worked around by wrapping the
//   outer macro call in KJ_EXPAND(), which appraently forces __VA_ARGS__ to be expanded before
//   the macro is evaluated. I don't understand the C preprocessor.
// - Using "#__VA_ARGS__" to stringify __VA_ARGS__ expands to zero tokens when __VA_ARGS__ is
//   empty, rather than expanding to an empty string literal. We can work around by concatenating
//   with an empty string literal.

#define KJ_EXPAND(X) X

#define KJ_LOG(severity, ...) \
138 139
  if (!::kj::_::Debug::shouldLog(::kj::LogSeverity::severity)) {} else \
    ::kj::_::Debug::log(__FILE__, __LINE__, ::kj::LogSeverity::severity, \
140 141 142 143
                        "" #__VA_ARGS__, __VA_ARGS__)

#define KJ_DBG(...) KJ_EXPAND(KJ_LOG(DBG, __VA_ARGS__))

144
#define KJ_REQUIRE(cond, ...) \
145
  if (KJ_LIKELY(cond)) {} else \
146
    for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
147 148
                                 #cond, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())

149
#define KJ_FAIL_REQUIRE(...) \
150
  for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
151 152 153 154
                               nullptr, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())

#define KJ_SYSCALL(call, ...) \
  if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, false)) {} else \
155
    for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
156 157 158 159
             _kjSyscallResult.getErrorNumber(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())

#define KJ_NONBLOCKING_SYSCALL(call, ...) \
  if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, true)) {} else \
160
    for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
161 162 163
             _kjSyscallResult.getErrorNumber(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())

#define KJ_FAIL_SYSCALL(code, errorNumber, ...) \
164
  for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
165 166
           errorNumber, code, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())

167 168 169
#if _WIN32

#define KJ_WIN32(call, ...) \
170
  if (auto _kjWin32Result = ::kj::_::Debug::win32Call(call)) {} else \
171
    for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
172
             _kjWin32Result, #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
173 174

#define KJ_WINSOCK(call, ...) \
175
  if (auto _kjWin32Result = ::kj::_::Debug::winsockCall(call)) {} else \
176
    for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
177
             _kjWin32Result, #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
178 179 180

#define KJ_FAIL_WIN32(code, errorNumber, ...) \
  for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
181
           ::kj::_::Debug::Win32Result(errorNumber), code, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
182 183 184

#endif

185 186 187 188
#define KJ_UNIMPLEMENTED(...) \
  for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::UNIMPLEMENTED, \
                               nullptr, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())

189 190 191
// TODO(msvc):  MSVC mis-deduces `ContextImpl<decltype(func)>` as `ContextImpl<int>` in some edge
// cases, such as inside nested lambdas inside member functions. Wrapping the type in
// `decltype(instance<...>())` helps it deduce the context function's type correctly.
192 193 194
#define KJ_CONTEXT(...) \
  auto KJ_UNIQUE_NAME(_kjContextFunc) = [&]() -> ::kj::_::Debug::Context::Value { \
        return ::kj::_::Debug::Context::Value(__FILE__, __LINE__, \
195
            ::kj::_::Debug::makeDescription("" #__VA_ARGS__, __VA_ARGS__)); \
196
      }; \
197
  decltype(::kj::instance<::kj::_::Debug::ContextImpl<decltype(KJ_UNIQUE_NAME(_kjContextFunc))>>()) \
198 199
      KJ_UNIQUE_NAME(_kjContext)(KJ_UNIQUE_NAME(_kjContextFunc))

200
#define KJ_REQUIRE_NONNULL(value, ...) \
201
  (*[&] { \
202 203
    auto _kj_result = ::kj::_::readMaybe(value); \
    if (KJ_UNLIKELY(!_kj_result)) { \
Kenton Varda's avatar
Kenton Varda committed
204
      ::kj::_::Debug::Fault(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
205 206
                            #value " != nullptr", "" #__VA_ARGS__, __VA_ARGS__).fatal(); \
    } \
207 208
    return _kj_result; \
  }())
209 210 211 212

#define KJ_EXCEPTION(type, ...) \
  ::kj::Exception(::kj::Exception::Type::type, __FILE__, __LINE__, \
      ::kj::_::Debug::makeDescription("" #__VA_ARGS__, __VA_ARGS__))
213 214 215

#else

Kenton Varda's avatar
Kenton Varda committed
216
#define KJ_LOG(severity, ...) \
217 218 219
  if (!::kj::_::Debug::shouldLog(::kj::LogSeverity::severity)) {} else \
    ::kj::_::Debug::log(__FILE__, __LINE__, ::kj::LogSeverity::severity, \
                        #__VA_ARGS__, ##__VA_ARGS__)
Kenton Varda's avatar
Kenton Varda committed
220

221
#define KJ_DBG(...) KJ_LOG(DBG, ##__VA_ARGS__)
Kenton Varda's avatar
Kenton Varda committed
222

223
#define KJ_REQUIRE(cond, ...) \
224
  if (KJ_LIKELY(cond)) {} else \
225
    for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
Kenton Varda's avatar
Kenton Varda committed
226 227
                                 #cond, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())

228
#define KJ_FAIL_REQUIRE(...) \
229
  for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
Kenton Varda's avatar
Kenton Varda committed
230
                               nullptr, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
231

Kenton Varda's avatar
Kenton Varda committed
232
#define KJ_SYSCALL(call, ...) \
233
  if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, false)) {} else \
234
    for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
235 236 237 238
             _kjSyscallResult.getErrorNumber(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())

#define KJ_NONBLOCKING_SYSCALL(call, ...) \
  if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, true)) {} else \
239
    for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
Kenton Varda's avatar
Kenton Varda committed
240 241
             _kjSyscallResult.getErrorNumber(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())

242
#define KJ_FAIL_SYSCALL(code, errorNumber, ...) \
243
  for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
Kenton Varda's avatar
Kenton Varda committed
244 245
           errorNumber, code, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())

246 247 248
#if _WIN32

#define KJ_WIN32(call, ...) \
249
  if (auto _kjWin32Result = ::kj::_::Debug::win32Call(call)) {} else \
250
    for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
251 252
             _kjWin32Result, #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
// Invoke a Win32 syscall that returns either BOOL or HANDLE, and throw an exception if it fails.
253 254

#define KJ_WINSOCK(call, ...) \
255
  if (auto _kjWin32Result = ::kj::_::Debug::winsockCall(call)) {} else \
256
    for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
257 258 259 260 261
             _kjWin32Result, #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
// Like KJ_WIN32 but for winsock calls which return `int` with SOCKET_ERROR indicating failure.
//
// Unfortunately, it's impossible to distinguish these from BOOL-returning Win32 calls by type,
// since BOOL is in fact an alias for `int`. :(
262 263 264

#define KJ_FAIL_WIN32(code, errorNumber, ...) \
  for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
265
           ::kj::_::Debug::Win32Result(errorNumber), code, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
266 267 268

#endif

269 270 271 272
#define KJ_UNIMPLEMENTED(...) \
  for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::UNIMPLEMENTED, \
                               nullptr, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())

Kenton Varda's avatar
Kenton Varda committed
273
#define KJ_CONTEXT(...) \
274
  auto KJ_UNIQUE_NAME(_kjContextFunc) = [&]() -> ::kj::_::Debug::Context::Value { \
Kenton Varda's avatar
Kenton Varda committed
275
        return ::kj::_::Debug::Context::Value(__FILE__, __LINE__, \
276
            ::kj::_::Debug::makeDescription(#__VA_ARGS__, ##__VA_ARGS__)); \
Kenton Varda's avatar
Kenton Varda committed
277
      }; \
278 279
  ::kj::_::Debug::ContextImpl<decltype(KJ_UNIQUE_NAME(_kjContextFunc))> \
      KJ_UNIQUE_NAME(_kjContext)(KJ_UNIQUE_NAME(_kjContextFunc))
Kenton Varda's avatar
Kenton Varda committed
280

281
#define KJ_REQUIRE_NONNULL(value, ...) \
Kenton Varda's avatar
Kenton Varda committed
282
  (*({ \
283 284
    auto _kj_result = ::kj::_::readMaybe(value); \
    if (KJ_UNLIKELY(!_kj_result)) { \
Kenton Varda's avatar
Kenton Varda committed
285
      ::kj::_::Debug::Fault(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
286 287
                            #value " != nullptr", #__VA_ARGS__, ##__VA_ARGS__).fatal(); \
    } \
Kenton Varda's avatar
Kenton Varda committed
288
    kj::mv(_kj_result); \
Kenton Varda's avatar
Kenton Varda committed
289
  }))
290 291 292 293

#define KJ_EXCEPTION(type, ...) \
  ::kj::Exception(::kj::Exception::Type::type, __FILE__, __LINE__, \
      ::kj::_::Debug::makeDescription(#__VA_ARGS__, ##__VA_ARGS__))
294

295 296
#endif

297 298
#define KJ_SYSCALL_HANDLE_ERRORS(call) \
  if (int _kjSyscallError = ::kj::_::Debug::syscallError([&](){return (call);}, false)) \
299
    switch (int error KJ_UNUSED = _kjSyscallError)
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
// Like KJ_SYSCALL, but doesn't throw. Instead, the block after the macro is a switch block on the
// error. Additionally, the int value `error` is defined within the block. So you can do:
//
//     KJ_SYSCALL_HANDLE_ERRORS(foo()) {
//       case ENOENT:
//         handleNoSuchFile();
//         break;
//       case EEXIST:
//         handleExists();
//         break;
//       default:
//         KJ_FAIL_SYSCALL("foo()", error);
//     } else {
//       handleSuccessCase();
//     }

316 317 318 319
#if _WIN32

#define KJ_WIN32_HANDLE_ERRORS(call) \
  if (uint _kjWin32Error = ::kj::_::Debug::win32Call(call).number) \
320
    switch (uint error KJ_UNUSED = _kjWin32Error)
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
// Like KJ_WIN32, but doesn't throw. Instead, the block after the macro is a switch block on the
// error. Additionally, the int value `error` is defined within the block. So you can do:
//
//     KJ_SYSCALL_HANDLE_ERRORS(foo()) {
//       case ERROR_FILE_NOT_FOUND:
//         handleNoSuchFile();
//         break;
//       case ERROR_FILE_EXISTS:
//         handleExists();
//         break;
//       default:
//         KJ_FAIL_WIN32("foo()", error);
//     } else {
//       handleSuccessCase();
//     }

#endif

339 340 341 342 343 344
#define KJ_ASSERT KJ_REQUIRE
#define KJ_FAIL_ASSERT KJ_FAIL_REQUIRE
#define KJ_ASSERT_NONNULL KJ_REQUIRE_NONNULL
// Use "ASSERT" in place of "REQUIRE" when the problem is local to the immediate surrounding code.
// That is, if the assert ever fails, it indicates that the immediate surrounding code is broken.

345
#ifdef KJ_DEBUG
346
#define KJ_DLOG KJ_LOG
Kenton Varda's avatar
Kenton Varda committed
347 348
#define KJ_DASSERT KJ_ASSERT
#define KJ_DREQUIRE KJ_REQUIRE
349 350 351 352
#else
#define KJ_DLOG(...) do {} while (false)
#define KJ_DASSERT(...) do {} while (false)
#define KJ_DREQUIRE(...) do {} while (false)
Kenton Varda's avatar
Kenton Varda committed
353 354 355 356 357
#endif

namespace _ {  // private

class Debug {
358
public:
Kenton Varda's avatar
Kenton Varda committed
359 360
  Debug() = delete;

361
  typedef LogSeverity Severity;  // backwards-compatibility
362

363
#if _WIN32
364
  struct Win32Result {
365
    uint number;
366 367
    inline explicit Win32Result(uint number): number(number) {}
    operator bool() const { return number == 0; }
368 369 370
  };
#endif

371
  static inline bool shouldLog(LogSeverity severity) { return severity >= minSeverity; }
372 373
  // Returns whether messages of the given severity should be logged.

374
  static inline void setLogLevel(LogSeverity severity) { minSeverity = severity; }
375
  // Set the minimum message severity which will be logged.
Kenton Varda's avatar
Kenton Varda committed
376 377
  //
  // TODO(someday):  Expose publicly.
378 379

  template <typename... Params>
380
  static void log(const char* file, int line, LogSeverity severity, const char* macroArgs,
381 382
                  Params&&... params);

383 384
  class Fault {
  public:
385 386
    template <typename Code, typename... Params>
    Fault(const char* file, int line, Code code,
387
          const char* condition, const char* macroArgs, Params&&... params);
388 389
    Fault(const char* file, int line, Exception::Type type,
          const char* condition, const char* macroArgs);
390
    Fault(const char* file, int line, int osErrorNumber,
391
          const char* condition, const char* macroArgs);
392
#if _WIN32
393
    Fault(const char* file, int line, Win32Result osErrorNumber,
394 395
          const char* condition, const char* macroArgs);
#endif
396
    ~Fault() noexcept(false);
397

Kenton Varda's avatar
Kenton Varda committed
398
    KJ_NOINLINE KJ_NORETURN(void fatal());
399
    // Throw the exception.
400

401
  private:
402 403
    void init(const char* file, int line, Exception::Type type,
              const char* condition, const char* macroArgs, ArrayPtr<String> argValues);
404
    void init(const char* file, int line, int osErrorNumber,
405
              const char* condition, const char* macroArgs, ArrayPtr<String> argValues);
406
#if _WIN32
407
    void init(const char* file, int line, Win32Result osErrorNumber,
408 409
              const char* condition, const char* macroArgs, ArrayPtr<String> argValues);
#endif
410

411 412
    Exception* exception;
  };
413

414 415 416 417 418
  class SyscallResult {
  public:
    inline SyscallResult(int errorNumber): errorNumber(errorNumber) {}
    inline operator void*() { return errorNumber == 0 ? this : nullptr; }
    inline int getErrorNumber() { return errorNumber; }
419

420 421 422 423 424
  private:
    int errorNumber;
  };

  template <typename Call>
425
  static SyscallResult syscall(Call&& call, bool nonblocking);
426 427
  template <typename Call>
  static int syscallError(Call&& call, bool nonblocking);
428

429
#if _WIN32
430 431 432 433
  static Win32Result win32Call(int boolean);
  static Win32Result win32Call(void* handle);
  static Win32Result winsockCall(int result);
  static uint getWin32ErrorCode();
434 435
#endif

436 437 438
  class Context: public ExceptionCallback {
  public:
    Context();
439
    KJ_DISALLOW_COPY(Context);
440
    virtual ~Context() noexcept(false);
441 442 443 444 445 446 447 448 449 450 451

    struct Value {
      const char* file;
      int line;
      String description;

      inline Value(const char* file, int line, String&& description)
          : file(file), line(line), description(mv(description)) {}
    };

    virtual Value evaluate() = 0;
452 453 454

    virtual void onRecoverableException(Exception&& exception) override;
    virtual void onFatalException(Exception&& exception) override;
455 456
    virtual void logMessage(LogSeverity severity, const char* file, int line, int contextDepth,
                            String&& text) override;
457 458

  private:
459 460 461 462
    bool logged;
    Maybe<Value> value;

    Value ensureInitialized();
463 464 465 466 467
  };

  template <typename Func>
  class ContextImpl: public Context {
  public:
468
    inline ContextImpl(Func& func): func(func) {}
469
    KJ_DISALLOW_COPY(ContextImpl);
470

471 472
    Value evaluate() override {
      return func();
473 474
    }
  private:
475
    Func& func;
476 477 478
  };

  template <typename... Params>
479
  static String makeDescription(const char* macroArgs, Params&&... params);
480

481
private:
482
  static LogSeverity minSeverity;
483

484
  static void logInternal(const char* file, int line, LogSeverity severity, const char* macroArgs,
Kenton Varda's avatar
Kenton Varda committed
485
                          ArrayPtr<String> argValues);
486
  static String makeDescriptionInternal(const char* macroArgs, ArrayPtr<String> argValues);
487

488
  static int getOsErrorNumber(bool nonblocking);
489
  // Get the error code of the last error (e.g. from errno).  Returns -1 on EINTR.
490 491 492
};

template <typename... Params>
493
void Debug::log(const char* file, int line, LogSeverity severity, const char* macroArgs,
Kenton Varda's avatar
Kenton Varda committed
494
                Params&&... params) {
Kenton Varda's avatar
Kenton Varda committed
495
  String argValues[sizeof...(Params)] = {str(params)...};
496 497 498
  logInternal(file, line, severity, macroArgs, arrayPtr(argValues, sizeof...(Params)));
}

499
template <>
500
inline void Debug::log<>(const char* file, int line, LogSeverity severity, const char* macroArgs) {
501 502 503
  logInternal(file, line, severity, macroArgs, nullptr);
}

504 505
template <typename Code, typename... Params>
Debug::Fault::Fault(const char* file, int line, Code code,
506 507 508
                    const char* condition, const char* macroArgs, Params&&... params)
    : exception(nullptr) {
  String argValues[sizeof...(Params)] = {str(params)...};
509
  init(file, line, code, condition, macroArgs,
510
       arrayPtr(argValues, sizeof...(Params)));
511 512
}

513
inline Debug::Fault::Fault(const char* file, int line, int osErrorNumber,
514 515
                           const char* condition, const char* macroArgs)
    : exception(nullptr) {
516
  init(file, line, osErrorNumber, condition, macroArgs, nullptr);
517 518
}

519 520 521 522 523 524
inline Debug::Fault::Fault(const char* file, int line, kj::Exception::Type type,
                           const char* condition, const char* macroArgs)
    : exception(nullptr) {
  init(file, line, type, condition, macroArgs, nullptr);
}

525
#if _WIN32
526
inline Debug::Fault::Fault(const char* file, int line, Win32Result osErrorNumber,
527 528 529 530 531
                           const char* condition, const char* macroArgs)
    : exception(nullptr) {
  init(file, line, osErrorNumber, condition, macroArgs, nullptr);
}

532 533
inline Debug::Win32Result Debug::win32Call(int boolean) {
  return boolean ? Win32Result(0) : Win32Result(getWin32ErrorCode());
534
}
535
inline Debug::Win32Result Debug::win32Call(void* handle) {
536
  // Assume null and INVALID_HANDLE_VALUE mean failure.
537 538 539 540 541
  return win32Call(handle != nullptr && handle != (void*)-1);
}
inline Debug::Win32Result Debug::winsockCall(int result) {
  // Expect a return value of SOCKET_ERROR means failure.
  return win32Call(result != -1);
542 543 544
}
#endif

545
template <typename Call>
546
Debug::SyscallResult Debug::syscall(Call&& call, bool nonblocking) {
547
  while (call() < 0) {
548 549 550 551
    int errorNum = getOsErrorNumber(nonblocking);
    // getOsErrorNumber() returns -1 to indicate EINTR.
    // Also, if nonblocking is true, then it returns 0 on EAGAIN, which will then be treated as a
    // non-error.
552
    if (errorNum != -1) {
553
      return SyscallResult(errorNum);
554 555
    }
  }
556
  return SyscallResult(0);
557 558
}

559 560 561 562 563 564 565 566 567 568 569 570 571 572
template <typename Call>
int Debug::syscallError(Call&& call, bool nonblocking) {
  while (call() < 0) {
    int errorNum = getOsErrorNumber(nonblocking);
    // getOsErrorNumber() returns -1 to indicate EINTR.
    // Also, if nonblocking is true, then it returns 0 on EAGAIN, which will then be treated as a
    // non-error.
    if (errorNum != -1) {
      return errorNum;
    }
  }
  return 0;
}

573
template <typename... Params>
574
String Debug::makeDescription(const char* macroArgs, Params&&... params) {
Kenton Varda's avatar
Kenton Varda committed
575
  String argValues[sizeof...(Params)] = {str(params)...};
576
  return makeDescriptionInternal(macroArgs, arrayPtr(argValues, sizeof...(Params)));
577 578
}

579
template <>
580 581
inline String Debug::makeDescription<>(const char* macroArgs) {
  return makeDescriptionInternal(macroArgs, nullptr);
582 583
}

Kenton Varda's avatar
Kenton Varda committed
584
}  // namespace _ (private)
585
}  // namespace kj