comparison osx/include/kj/debug.h @ 49:3ab5a40c4e3b

Add Capnp and KJ builds for OSX
author Chris Cannam <cannam@all-day-breakfast.com>
date Tue, 25 Oct 2016 14:48:23 +0100
parents
children 0994c39f1e94
comparison
equal deleted inserted replaced
48:9530b331f8c1 49:3ab5a40c4e3b
1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
2 // Licensed under the MIT License:
3 //
4 // Permission is hereby granted, free of charge, to any person obtaining a copy
5 // of this software and associated documentation files (the "Software"), to deal
6 // in the Software without restriction, including without limitation the rights
7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 // copies of the Software, and to permit persons to whom the Software is
9 // furnished to do so, subject to the following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included in
12 // all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 // THE SOFTWARE.
21
22 // This file declares convenient macros for debug logging and error handling. The macros make
23 // it excessively easy to extract useful context information from code. Example:
24 //
25 // KJ_ASSERT(a == b, a, b, "a and b must be the same.");
26 //
27 // On failure, this will throw an exception whose description looks like:
28 //
29 // myfile.c++:43: bug in code: expected a == b; a = 14; b = 72; a and b must be the same.
30 //
31 // As you can see, all arguments after the first provide additional context.
32 //
33 // The macros available are:
34 //
35 // * `KJ_LOG(severity, ...)`: Just writes a log message, to stderr by default (but you can
36 // intercept messages by implementing an ExceptionCallback). `severity` is `INFO`, `WARNING`,
37 // `ERROR`, or `FATAL`. By default, `INFO` logs are not written, but for command-line apps the
38 // user should be able to pass a flag like `--verbose` to enable them. Other log levels are
39 // enabled by default. Log messages -- like exceptions -- can be intercepted by registering an
40 // ExceptionCallback.
41 //
42 // * `KJ_DBG(...)`: Like `KJ_LOG`, but intended specifically for temporary log lines added while
43 // debugging a particular problem. Calls to `KJ_DBG` should always be deleted before committing
44 // code. It is suggested that you set up a pre-commit hook that checks for this.
45 //
46 // * `KJ_ASSERT(condition, ...)`: Throws an exception if `condition` is false, or aborts if
47 // exceptions are disabled. This macro should be used to check for bugs in the surrounding code
48 // and its dependencies, but NOT to check for invalid input. The macro may be followed by a
49 // brace-delimited code block; if so, the block will be executed in the case where the assertion
50 // fails, before throwing the exception. If control jumps out of the block (e.g. with "break",
51 // "return", or "goto"), then the error is considered "recoverable" -- in this case, if
52 // exceptions are disabled, execution will continue normally rather than aborting (but if
53 // exceptions are enabled, an exception will still be thrown on exiting the block). A "break"
54 // statement in particular will jump to the code immediately after the block (it does not break
55 // any surrounding loop or switch). Example:
56 //
57 // KJ_ASSERT(value >= 0, "Value cannot be negative.", value) {
58 // // Assertion failed. Set value to zero to "recover".
59 // value = 0;
60 // // Don't abort if exceptions are disabled. Continue normally.
61 // // (Still throw an exception if they are enabled, though.)
62 // break;
63 // }
64 // // When exceptions are disabled, we'll get here even if the assertion fails.
65 // // Otherwise, we get here only if the assertion passes.
66 //
67 // * `KJ_REQUIRE(condition, ...)`: Like `KJ_ASSERT` but used to check preconditions -- e.g. to
68 // validate parameters passed from a caller. A failure indicates that the caller is buggy.
69 //
70 // * `KJ_SYSCALL(code, ...)`: Executes `code` assuming it makes a system call. A negative result
71 // is considered an error, with error code reported via `errno`. EINTR is handled by retrying.
72 // Other errors are handled by throwing an exception. If you need to examine the return code,
73 // assign it to a variable like so:
74 //
75 // int fd;
76 // KJ_SYSCALL(fd = open(filename, O_RDONLY), filename);
77 //
78 // `KJ_SYSCALL` can be followed by a recovery block, just like `KJ_ASSERT`.
79 //
80 // * `KJ_NONBLOCKING_SYSCALL(code, ...)`: Like KJ_SYSCALL, but will not throw an exception on
81 // EAGAIN/EWOULDBLOCK. The calling code should check the syscall's return value to see if it
82 // indicates an error; in this case, it can assume the error was EAGAIN because any other error
83 // would have caused an exception to be thrown.
84 //
85 // * `KJ_CONTEXT(...)`: Notes additional contextual information relevant to any exceptions thrown
86 // from within the current scope. That is, until control exits the block in which KJ_CONTEXT()
87 // is used, if any exception is generated, it will contain the given information in its context
88 // chain. This is helpful because it can otherwise be very difficult to come up with error
89 // messages that make sense within low-level helper code. Note that the parameters to
90 // KJ_CONTEXT() are only evaluated if an exception is thrown. This implies that any variables
91 // used must remain valid until the end of the scope.
92 //
93 // Notes:
94 // * Do not write expressions with side-effects in the message content part of the macro, as the
95 // message will not necessarily be evaluated.
96 // * For every macro `FOO` above except `LOG`, there is also a `FAIL_FOO` macro used to report
97 // failures that already happened. For the macros that check a boolean condition, `FAIL_FOO`
98 // omits the first parameter and behaves like it was `false`. `FAIL_SYSCALL` and
99 // `FAIL_RECOVERABLE_SYSCALL` take a string and an OS error number as the first two parameters.
100 // The string should be the name of the failed system call.
101 // * For every macro `FOO` above, there is a `DFOO` version (or `RECOVERABLE_DFOO`) which is only
102 // executed in debug mode, i.e. when KJ_DEBUG is defined. KJ_DEBUG is defined automatically
103 // by common.h when compiling without optimization (unless NDEBUG is defined), but you can also
104 // define it explicitly (e.g. -DKJ_DEBUG). Generally, production builds should NOT use KJ_DEBUG
105 // as it may enable expensive checks that are unlikely to fail.
106
107 #ifndef KJ_DEBUG_H_
108 #define KJ_DEBUG_H_
109
110 #if defined(__GNUC__) && !KJ_HEADER_WARNINGS
111 #pragma GCC system_header
112 #endif
113
114 #include "string.h"
115 #include "exception.h"
116
117 #ifdef ERROR
118 // This is problematic because windows.h #defines ERROR, which we use in an enum here.
119 #error "Make sure to to undefine ERROR (or just #include <kj/windows-sanity.h>) before this file"
120 #endif
121
122 namespace kj {
123
124 #if _MSC_VER
125 // MSVC does __VA_ARGS__ differently from GCC:
126 // - A trailing comma before an empty __VA_ARGS__ is removed automatically, whereas GCC wants
127 // you to request this behavior with "##__VA_ARGS__".
128 // - If __VA_ARGS__ is passed directly as an argument to another macro, it will be treated as a
129 // *single* argument rather than an argument list. This can be worked around by wrapping the
130 // outer macro call in KJ_EXPAND(), which appraently forces __VA_ARGS__ to be expanded before
131 // the macro is evaluated. I don't understand the C preprocessor.
132 // - Using "#__VA_ARGS__" to stringify __VA_ARGS__ expands to zero tokens when __VA_ARGS__ is
133 // empty, rather than expanding to an empty string literal. We can work around by concatenating
134 // with an empty string literal.
135
136 #define KJ_EXPAND(X) X
137
138 #define KJ_LOG(severity, ...) \
139 if (!::kj::_::Debug::shouldLog(::kj::LogSeverity::severity)) {} else \
140 ::kj::_::Debug::log(__FILE__, __LINE__, ::kj::LogSeverity::severity, \
141 "" #__VA_ARGS__, __VA_ARGS__)
142
143 #define KJ_DBG(...) KJ_EXPAND(KJ_LOG(DBG, __VA_ARGS__))
144
145 #define KJ_REQUIRE(cond, ...) \
146 if (KJ_LIKELY(cond)) {} else \
147 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
148 #cond, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
149
150 #define KJ_FAIL_REQUIRE(...) \
151 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
152 nullptr, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
153
154 #define KJ_SYSCALL(call, ...) \
155 if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, false)) {} else \
156 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
157 _kjSyscallResult.getErrorNumber(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
158
159 #define KJ_NONBLOCKING_SYSCALL(call, ...) \
160 if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, true)) {} else \
161 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
162 _kjSyscallResult.getErrorNumber(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
163
164 #define KJ_FAIL_SYSCALL(code, errorNumber, ...) \
165 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
166 errorNumber, code, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
167
168 #define KJ_UNIMPLEMENTED(...) \
169 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::UNIMPLEMENTED, \
170 nullptr, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
171
172 #define KJ_CONTEXT(...) \
173 auto KJ_UNIQUE_NAME(_kjContextFunc) = [&]() -> ::kj::_::Debug::Context::Value { \
174 return ::kj::_::Debug::Context::Value(__FILE__, __LINE__, \
175 ::kj::_::Debug::makeDescription("" #__VA_ARGS__, __VA_ARGS__)); \
176 }; \
177 ::kj::_::Debug::ContextImpl<decltype(KJ_UNIQUE_NAME(_kjContextFunc))> \
178 KJ_UNIQUE_NAME(_kjContext)(KJ_UNIQUE_NAME(_kjContextFunc))
179
180 #define KJ_REQUIRE_NONNULL(value, ...) \
181 (*[&] { \
182 auto _kj_result = ::kj::_::readMaybe(value); \
183 if (KJ_UNLIKELY(!_kj_result)) { \
184 ::kj::_::Debug::Fault(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
185 #value " != nullptr", "" #__VA_ARGS__, __VA_ARGS__).fatal(); \
186 } \
187 return _kj_result; \
188 }())
189
190 #define KJ_EXCEPTION(type, ...) \
191 ::kj::Exception(::kj::Exception::Type::type, __FILE__, __LINE__, \
192 ::kj::_::Debug::makeDescription("" #__VA_ARGS__, __VA_ARGS__))
193
194 #else
195
196 #define KJ_LOG(severity, ...) \
197 if (!::kj::_::Debug::shouldLog(::kj::LogSeverity::severity)) {} else \
198 ::kj::_::Debug::log(__FILE__, __LINE__, ::kj::LogSeverity::severity, \
199 #__VA_ARGS__, ##__VA_ARGS__)
200
201 #define KJ_DBG(...) KJ_LOG(DBG, ##__VA_ARGS__)
202
203 #define KJ_REQUIRE(cond, ...) \
204 if (KJ_LIKELY(cond)) {} else \
205 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
206 #cond, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
207
208 #define KJ_FAIL_REQUIRE(...) \
209 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
210 nullptr, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
211
212 #define KJ_SYSCALL(call, ...) \
213 if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, false)) {} else \
214 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
215 _kjSyscallResult.getErrorNumber(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
216
217 #define KJ_NONBLOCKING_SYSCALL(call, ...) \
218 if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, true)) {} else \
219 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
220 _kjSyscallResult.getErrorNumber(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
221
222 #define KJ_FAIL_SYSCALL(code, errorNumber, ...) \
223 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
224 errorNumber, code, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
225
226 #define KJ_UNIMPLEMENTED(...) \
227 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::UNIMPLEMENTED, \
228 nullptr, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
229
230 #define KJ_CONTEXT(...) \
231 auto KJ_UNIQUE_NAME(_kjContextFunc) = [&]() -> ::kj::_::Debug::Context::Value { \
232 return ::kj::_::Debug::Context::Value(__FILE__, __LINE__, \
233 ::kj::_::Debug::makeDescription(#__VA_ARGS__, ##__VA_ARGS__)); \
234 }; \
235 ::kj::_::Debug::ContextImpl<decltype(KJ_UNIQUE_NAME(_kjContextFunc))> \
236 KJ_UNIQUE_NAME(_kjContext)(KJ_UNIQUE_NAME(_kjContextFunc))
237
238 #define KJ_REQUIRE_NONNULL(value, ...) \
239 (*({ \
240 auto _kj_result = ::kj::_::readMaybe(value); \
241 if (KJ_UNLIKELY(!_kj_result)) { \
242 ::kj::_::Debug::Fault(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
243 #value " != nullptr", #__VA_ARGS__, ##__VA_ARGS__).fatal(); \
244 } \
245 kj::mv(_kj_result); \
246 }))
247
248 #define KJ_EXCEPTION(type, ...) \
249 ::kj::Exception(::kj::Exception::Type::type, __FILE__, __LINE__, \
250 ::kj::_::Debug::makeDescription(#__VA_ARGS__, ##__VA_ARGS__))
251
252 #endif
253
254 #define KJ_ASSERT KJ_REQUIRE
255 #define KJ_FAIL_ASSERT KJ_FAIL_REQUIRE
256 #define KJ_ASSERT_NONNULL KJ_REQUIRE_NONNULL
257 // Use "ASSERT" in place of "REQUIRE" when the problem is local to the immediate surrounding code.
258 // That is, if the assert ever fails, it indicates that the immediate surrounding code is broken.
259
260 #ifdef KJ_DEBUG
261 #define KJ_DLOG KJ_LOG
262 #define KJ_DASSERT KJ_ASSERT
263 #define KJ_DREQUIRE KJ_REQUIRE
264 #else
265 #define KJ_DLOG(...) do {} while (false)
266 #define KJ_DASSERT(...) do {} while (false)
267 #define KJ_DREQUIRE(...) do {} while (false)
268 #endif
269
270 namespace _ { // private
271
272 class Debug {
273 public:
274 Debug() = delete;
275
276 typedef LogSeverity Severity; // backwards-compatibility
277
278 static inline bool shouldLog(LogSeverity severity) { return severity >= minSeverity; }
279 // Returns whether messages of the given severity should be logged.
280
281 static inline void setLogLevel(LogSeverity severity) { minSeverity = severity; }
282 // Set the minimum message severity which will be logged.
283 //
284 // TODO(someday): Expose publicly.
285
286 template <typename... Params>
287 static void log(const char* file, int line, LogSeverity severity, const char* macroArgs,
288 Params&&... params);
289
290 class Fault {
291 public:
292 template <typename... Params>
293 Fault(const char* file, int line, Exception::Type type,
294 const char* condition, const char* macroArgs, Params&&... params);
295 template <typename... Params>
296 Fault(const char* file, int line, int osErrorNumber,
297 const char* condition, const char* macroArgs, Params&&... params);
298 Fault(const char* file, int line, Exception::Type type,
299 const char* condition, const char* macroArgs);
300 Fault(const char* file, int line, int osErrorNumber,
301 const char* condition, const char* macroArgs);
302 ~Fault() noexcept(false);
303
304 KJ_NOINLINE KJ_NORETURN(void fatal());
305 // Throw the exception.
306
307 private:
308 void init(const char* file, int line, Exception::Type type,
309 const char* condition, const char* macroArgs, ArrayPtr<String> argValues);
310 void init(const char* file, int line, int osErrorNumber,
311 const char* condition, const char* macroArgs, ArrayPtr<String> argValues);
312
313 Exception* exception;
314 };
315
316 class SyscallResult {
317 public:
318 inline SyscallResult(int errorNumber): errorNumber(errorNumber) {}
319 inline operator void*() { return errorNumber == 0 ? this : nullptr; }
320 inline int getErrorNumber() { return errorNumber; }
321
322 private:
323 int errorNumber;
324 };
325
326 template <typename Call>
327 static SyscallResult syscall(Call&& call, bool nonblocking);
328
329 class Context: public ExceptionCallback {
330 public:
331 Context();
332 KJ_DISALLOW_COPY(Context);
333 virtual ~Context() noexcept(false);
334
335 struct Value {
336 const char* file;
337 int line;
338 String description;
339
340 inline Value(const char* file, int line, String&& description)
341 : file(file), line(line), description(mv(description)) {}
342 };
343
344 virtual Value evaluate() = 0;
345
346 virtual void onRecoverableException(Exception&& exception) override;
347 virtual void onFatalException(Exception&& exception) override;
348 virtual void logMessage(LogSeverity severity, const char* file, int line, int contextDepth,
349 String&& text) override;
350
351 private:
352 bool logged;
353 Maybe<Value> value;
354
355 Value ensureInitialized();
356 };
357
358 template <typename Func>
359 class ContextImpl: public Context {
360 public:
361 inline ContextImpl(Func& func): func(func) {}
362 KJ_DISALLOW_COPY(ContextImpl);
363
364 Value evaluate() override {
365 return func();
366 }
367 private:
368 Func& func;
369 };
370
371 template <typename... Params>
372 static String makeDescription(const char* macroArgs, Params&&... params);
373
374 private:
375 static LogSeverity minSeverity;
376
377 static void logInternal(const char* file, int line, LogSeverity severity, const char* macroArgs,
378 ArrayPtr<String> argValues);
379 static String makeDescriptionInternal(const char* macroArgs, ArrayPtr<String> argValues);
380
381 static int getOsErrorNumber(bool nonblocking);
382 // Get the error code of the last error (e.g. from errno). Returns -1 on EINTR.
383 };
384
385 template <typename... Params>
386 void Debug::log(const char* file, int line, LogSeverity severity, const char* macroArgs,
387 Params&&... params) {
388 String argValues[sizeof...(Params)] = {str(params)...};
389 logInternal(file, line, severity, macroArgs, arrayPtr(argValues, sizeof...(Params)));
390 }
391
392 template <>
393 inline void Debug::log<>(const char* file, int line, LogSeverity severity, const char* macroArgs) {
394 logInternal(file, line, severity, macroArgs, nullptr);
395 }
396
397 template <typename... Params>
398 Debug::Fault::Fault(const char* file, int line, Exception::Type type,
399 const char* condition, const char* macroArgs, Params&&... params)
400 : exception(nullptr) {
401 String argValues[sizeof...(Params)] = {str(params)...};
402 init(file, line, type, condition, macroArgs,
403 arrayPtr(argValues, sizeof...(Params)));
404 }
405
406 template <typename... Params>
407 Debug::Fault::Fault(const char* file, int line, int osErrorNumber,
408 const char* condition, const char* macroArgs, Params&&... params)
409 : exception(nullptr) {
410 String argValues[sizeof...(Params)] = {str(params)...};
411 init(file, line, osErrorNumber, condition, macroArgs,
412 arrayPtr(argValues, sizeof...(Params)));
413 }
414
415 inline Debug::Fault::Fault(const char* file, int line, int osErrorNumber,
416 const char* condition, const char* macroArgs)
417 : exception(nullptr) {
418 init(file, line, osErrorNumber, condition, macroArgs, nullptr);
419 }
420
421 inline Debug::Fault::Fault(const char* file, int line, kj::Exception::Type type,
422 const char* condition, const char* macroArgs)
423 : exception(nullptr) {
424 init(file, line, type, condition, macroArgs, nullptr);
425 }
426
427 template <typename Call>
428 Debug::SyscallResult Debug::syscall(Call&& call, bool nonblocking) {
429 while (call() < 0) {
430 int errorNum = getOsErrorNumber(nonblocking);
431 // getOsErrorNumber() returns -1 to indicate EINTR.
432 // Also, if nonblocking is true, then it returns 0 on EAGAIN, which will then be treated as a
433 // non-error.
434 if (errorNum != -1) {
435 return SyscallResult(errorNum);
436 }
437 }
438 return SyscallResult(0);
439 }
440
441 template <typename... Params>
442 String Debug::makeDescription(const char* macroArgs, Params&&... params) {
443 String argValues[sizeof...(Params)] = {str(params)...};
444 return makeDescriptionInternal(macroArgs, arrayPtr(argValues, sizeof...(Params)));
445 }
446
447 template <>
448 inline String Debug::makeDescription<>(const char* macroArgs) {
449 return makeDescriptionInternal(macroArgs, nullptr);
450 }
451
452 } // namespace _ (private)
453 } // namespace kj
454
455 #endif // KJ_DEBUG_H_