debug.h 13.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// Copyright (c) 2013, Kenton Varda <temporal@gmail.com>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

24 25 26
// 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:
//
27
//     KJ_ASSERT(a == b, a, b, "a and b must be the same.");
28 29 30 31 32 33 34 35 36
//
// 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:
//
37 38
// * `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`,
39 40 41 42 43 44 45 46
//   `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.
47
//
48 49
// * `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
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
//   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.
68
//
69 70
// * `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.
71
//
72 73 74 75
// * `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:
76 77
//
//       int fd;
78 79 80
//       KJ_SYSCALL(fd = open(filename, O_RDONLY), filename);
//
//   `KJ_SYSCALL` can be followed by a recovery block, just like `KJ_ASSERT`.
81
//
82 83
// * `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()
84 85
//   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
86 87 88
//   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.
89
//
90 91 92 93 94 95 96 97 98 99 100
// 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
//   executed in debug mode.  When `NDEBUG` is defined, these macros expand to nothing.

101 102
#ifndef KJ_DEBUG_H_
#define KJ_DEBUG_H_
103

Kenton Varda's avatar
Kenton Varda committed
104
#include "string.h"
105 106
#include "exception.h"

107
namespace kj {
108

Kenton Varda's avatar
Kenton Varda committed
109 110 111 112 113
#define KJ_LOG(severity, ...) \
  if (!::kj::_::Debug::shouldLog(::kj::_::Debug::Severity::severity)) {} else \
    ::kj::_::Debug::log(__FILE__, __LINE__, ::kj::_::Debug::Severity::severity, \
                        #__VA_ARGS__, __VA_ARGS__)

114
#define KJ_DBG(...) KJ_LOG(DBG, ##__VA_ARGS__)
Kenton Varda's avatar
Kenton Varda committed
115 116

#define _kJ_FAULT(nature, cond, ...) \
117
  if (KJ_LIKELY(cond)) {} else \
Kenton Varda's avatar
Kenton Varda committed
118 119 120 121 122 123
    for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Nature::nature, 0, \
                                 #cond, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())

#define _kJ_FAIL_FAULT(nature, ...) \
  for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Nature::nature, 0, \
                               nullptr, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
124

Kenton Varda's avatar
Kenton Varda committed
125 126 127 128 129 130 131 132 133 134 135 136
#define KJ_ASSERT(...) _kJ_FAULT(LOCAL_BUG, ##__VA_ARGS__)
#define KJ_REQUIRE(...) _kJ_FAULT(PRECONDITION, ##__VA_ARGS__)

#define KJ_FAIL_ASSERT(...) _kJ_FAIL_FAULT(LOCAL_BUG, ##__VA_ARGS__)
#define KJ_FAIL_REQUIRE(...) _kJ_FAIL_FAULT(PRECONDITION, ##__VA_ARGS__)

#define KJ_SYSCALL(call, ...) \
  if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);})) {} else \
    for (::kj::_::Debug::Fault f( \
             __FILE__, __LINE__, ::kj::Exception::Nature::OS_ERROR, \
             _kjSyscallResult.getErrorNumber(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())

137
#define KJ_FAIL_SYSCALL(code, errorNumber, ...) \
Kenton Varda's avatar
Kenton Varda committed
138 139 140 141 142
  for (::kj::_::Debug::Fault f( \
           __FILE__, __LINE__, ::kj::Exception::Nature::OS_ERROR, \
           errorNumber, code, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())

#define KJ_CONTEXT(...) \
143
  auto KJ_UNIQUE_NAME(_kjContextFunc) = [&]() -> ::kj::_::Debug::Context::Value { \
Kenton Varda's avatar
Kenton Varda committed
144 145 146
        return ::kj::_::Debug::Context::Value(__FILE__, __LINE__, \
            ::kj::_::Debug::makeContextDescription(#__VA_ARGS__, ##__VA_ARGS__)); \
      }; \
147 148
  ::kj::_::Debug::ContextImpl<decltype(KJ_UNIQUE_NAME(_kjContextFunc))> \
      KJ_UNIQUE_NAME(_kjContext)(KJ_UNIQUE_NAME(_kjContextFunc))
Kenton Varda's avatar
Kenton Varda committed
149

150
#define _kJ_NONNULL(nature, value, ...) \
Kenton Varda's avatar
Kenton Varda committed
151
  (*({ \
152 153 154 155 156
    auto result = ::kj::_::readMaybe(value); \
    if (KJ_UNLIKELY(!result)) { \
      ::kj::_::Debug::Fault(__FILE__, __LINE__, ::kj::Exception::Nature::nature, 0, \
                            #value " != nullptr", #__VA_ARGS__, ##__VA_ARGS__).fatal(); \
    } \
Kenton Varda's avatar
Kenton Varda committed
157 158
    result; \
  }))
159 160 161
#define KJ_ASSERT_NONNULL(value, ...) _kJ_NONNULL(LOCAL_BUG, value, ##__VA_ARGS__)
#define KJ_REQUIRE_NONNULL(value, ...) _kJ_NONNULL(PRECONDITION, value, ##__VA_ARGS__)

162
#ifdef KJ_DEBUG
Kenton Varda's avatar
Kenton Varda committed
163 164 165
#define KJ_DLOG LOG
#define KJ_DASSERT KJ_ASSERT
#define KJ_DREQUIRE KJ_REQUIRE
166 167 168 169
#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
170 171 172 173 174
#endif

namespace _ {  // private

class Debug {
175
public:
Kenton Varda's avatar
Kenton Varda committed
176 177
  Debug() = delete;

178
  enum class Severity {
179 180 181
    INFO,      // Information describing what the code is up to, which users may request to see
               // with a flag like `--verbose`.  Does not indicate a problem.  Not printed by
               // default; you must call setLogLevel(INFO) to enable.
182 183
    WARNING,   // A problem was detected but execution can continue with correct output.
    ERROR,     // Something is wrong, but execution can continue with garbage output.
184
    FATAL,     // Something went wrong, and execution cannot continue.
185
    DBG        // Temporary debug logging.  See KJ_DBG.
186 187 188 189 190

    // Make sure to update the stringifier if you add a new severity level.
  };

  static inline bool shouldLog(Severity severity) { return severity >= minSeverity; }
191 192
  // Returns whether messages of the given severity should be logged.

193
  static inline void setLogLevel(Severity severity) { minSeverity = severity; }
194
  // Set the minimum message severity which will be logged.
Kenton Varda's avatar
Kenton Varda committed
195 196
  //
  // TODO(someday):  Expose publicly.
197 198

  template <typename... Params>
Kenton Varda's avatar
Kenton Varda committed
199
  static void log(const char* file, int line, Severity severity, const char* macroArgs,
200 201
                  Params&&... params);

202 203 204 205 206 207
  class Fault {
  public:
    template <typename... Params>
    Fault(const char* file, int line, Exception::Nature nature, int errorNumber,
          const char* condition, const char* macroArgs, Params&&... params);
    ~Fault() noexcept(false);
208

209 210
    void fatal() KJ_NORETURN;
    // Throw the exception.
211

212 213 214
  private:
    void init(const char* file, int line, Exception::Nature nature, int errorNumber,
              const char* condition, const char* macroArgs, ArrayPtr<String> argValues);
215

216 217
    Exception* exception;
  };
218

219 220 221 222 223
  class SyscallResult {
  public:
    inline SyscallResult(int errorNumber): errorNumber(errorNumber) {}
    inline operator void*() { return errorNumber == 0 ? this : nullptr; }
    inline int getErrorNumber() { return errorNumber; }
224

225 226 227 228 229 230
  private:
    int errorNumber;
  };

  template <typename Call>
  static SyscallResult syscall(Call&& call);
231

232 233 234
  class Context: public ExceptionCallback {
  public:
    Context();
235
    KJ_DISALLOW_COPY(Context);
236
    virtual ~Context() noexcept(false);
237 238 239 240 241 242 243 244 245 246 247

    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;
248 249 250

    virtual void onRecoverableException(Exception&& exception) override;
    virtual void onFatalException(Exception&& exception) override;
251
    virtual void logMessage(const char* file, int line, int contextDepth, String&& text) override;
252 253

  private:
254 255 256 257
    bool logged;
    Maybe<Value> value;

    Value ensureInitialized();
258 259 260 261 262
  };

  template <typename Func>
  class ContextImpl: public Context {
  public:
263
    inline ContextImpl(Func& func): func(func) {}
264
    KJ_DISALLOW_COPY(ContextImpl);
265

266 267
    Value evaluate() override {
      return func();
268 269
    }
  private:
270
    Func& func;
271 272 273
  };

  template <typename... Params>
274
  static String makeContextDescription(const char* macroArgs, Params&&... params);
275

276 277 278
private:
  static Severity minSeverity;

Kenton Varda's avatar
Kenton Varda committed
279
  static void logInternal(const char* file, int line, Severity severity, const char* macroArgs,
Kenton Varda's avatar
Kenton Varda committed
280
                          ArrayPtr<String> argValues);
281
  static String makeContextDescriptionInternal(const char* macroArgs, ArrayPtr<String> argValues);
282 283 284

  static int getOsErrorNumber();
  // Get the error code of the last error (e.g. from errno).  Returns -1 on EINTR.
285 286
};

Kenton Varda's avatar
Kenton Varda committed
287
ArrayPtr<const char> KJ_STRINGIFY(Debug::Severity severity);
288 289

template <typename... Params>
Kenton Varda's avatar
Kenton Varda committed
290 291
void Debug::log(const char* file, int line, Severity severity, const char* macroArgs,
                Params&&... params) {
Kenton Varda's avatar
Kenton Varda committed
292
  String argValues[sizeof...(Params)] = {str(params)...};
293 294 295 296
  logInternal(file, line, severity, macroArgs, arrayPtr(argValues, sizeof...(Params)));
}

template <typename... Params>
Kenton Varda's avatar
Kenton Varda committed
297 298
Debug::Fault::Fault(const char* file, int line, Exception::Nature nature, int errorNumber,
                    const char* condition, const char* macroArgs, Params&&... params)
299
    : exception(nullptr) {
Kenton Varda's avatar
Kenton Varda committed
300
  String argValues[sizeof...(Params)] = {str(params)...};
301 302
  init(file, line, nature, errorNumber, condition, macroArgs,
       arrayPtr(argValues, sizeof...(Params)));
303 304
}

305
template <typename Call>
Kenton Varda's avatar
Kenton Varda committed
306
Debug::SyscallResult Debug::syscall(Call&& call) {
307
  while (call() < 0) {
308 309 310
    int errorNum = getOsErrorNumber();
    // getOsErrorNumber() returns -1 to indicate EINTR
    if (errorNum != -1) {
311
      return SyscallResult(errorNum);
312 313
    }
  }
314
  return SyscallResult(0);
315 316
}

317
template <typename... Params>
Kenton Varda's avatar
Kenton Varda committed
318
String Debug::makeContextDescription(const char* macroArgs, Params&&... params) {
Kenton Varda's avatar
Kenton Varda committed
319
  String argValues[sizeof...(Params)] = {str(params)...};
320
  return makeContextDescriptionInternal(macroArgs, arrayPtr(argValues, sizeof...(Params)));
321 322
}

Kenton Varda's avatar
Kenton Varda committed
323
}  // namespace _ (private)
324
}  // namespace kj
325

326
#endif  // KJ_DEBUG_H_