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#pragma once
108
109#if defined(__GNUC__) && !KJ_HEADER_WARNINGS
110#pragma GCC system_header
111#endif
112
113#include "string.h"
114#include "exception.h"
115#include "windows-sanity.h" // work-around macro conflict with `ERROR`
116
117namespace kj {
118
119#if _MSC_VER
120// MSVC does __VA_ARGS__ differently from GCC:
121// - A trailing comma before an empty __VA_ARGS__ is removed automatically, whereas GCC wants
122// you to request this behavior with "##__VA_ARGS__".
123// - If __VA_ARGS__ is passed directly as an argument to another macro, it will be treated as a
124// *single* argument rather than an argument list. This can be worked around by wrapping the
125// outer macro call in KJ_EXPAND(), which appraently forces __VA_ARGS__ to be expanded before
126// the macro is evaluated. I don't understand the C preprocessor.
127// - Using "#__VA_ARGS__" to stringify __VA_ARGS__ expands to zero tokens when __VA_ARGS__ is
128// empty, rather than expanding to an empty string literal. We can work around by concatenating
129// with an empty string literal.
130
131#define KJ_EXPAND(X) X
132
133#define KJ_LOG(severity, ...) \
134 for (bool _kj_shouldLog = ::kj::_::Debug::shouldLog(::kj::LogSeverity::severity); \
135 _kj_shouldLog; _kj_shouldLog = false) \
136 ::kj::_::Debug::log(__FILE__, __LINE__, ::kj::LogSeverity::severity, \
137 "" #__VA_ARGS__, __VA_ARGS__)
138
139#define KJ_DBG(...) KJ_EXPAND(KJ_LOG(DBG, __VA_ARGS__))
140
141#define KJ_REQUIRE(cond, ...) \
142 if (KJ_LIKELY(cond)) {} else \
143 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
144 #cond, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
145
146#define KJ_FAIL_REQUIRE(...) \
147 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
148 nullptr, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
149
150#define KJ_SYSCALL(call, ...) \
151 if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, false)) {} else \
152 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
153 _kjSyscallResult.getErrorNumber(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
154
155#define KJ_NONBLOCKING_SYSCALL(call, ...) \
156 if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, true)) {} else \
157 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
158 _kjSyscallResult.getErrorNumber(), #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
159
160#define KJ_FAIL_SYSCALL(code, errorNumber, ...) \
161 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
162 errorNumber, code, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
163
164#if _WIN32
165
166#define KJ_WIN32(call, ...) \
167 if (auto _kjWin32Result = ::kj::_::Debug::win32Call(call)) {} else \
168 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
169 _kjWin32Result, #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
170
171#define KJ_WINSOCK(call, ...) \
172 if (auto _kjWin32Result = ::kj::_::Debug::winsockCall(call)) {} else \
173 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
174 _kjWin32Result, #call, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
175
176#define KJ_FAIL_WIN32(code, errorNumber, ...) \
177 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
178 ::kj::_::Debug::Win32Result(errorNumber), code, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
179
180#endif
181
182#define KJ_UNIMPLEMENTED(...) \
183 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::UNIMPLEMENTED, \
184 nullptr, "" #__VA_ARGS__, __VA_ARGS__);; f.fatal())
185
186// TODO(msvc): MSVC mis-deduces `ContextImpl<decltype(func)>` as `ContextImpl<int>` in some edge
187// cases, such as inside nested lambdas inside member functions. Wrapping the type in
188// `decltype(instance<...>())` helps it deduce the context function's type correctly.
189#define KJ_CONTEXT(...) \
190 auto KJ_UNIQUE_NAME(_kjContextFunc) = [&]() -> ::kj::_::Debug::Context::Value { \
191 return ::kj::_::Debug::Context::Value(__FILE__, __LINE__, \
192 ::kj::_::Debug::makeDescription("" #__VA_ARGS__, __VA_ARGS__)); \
193 }; \
194 decltype(::kj::instance<::kj::_::Debug::ContextImpl<decltype(KJ_UNIQUE_NAME(_kjContextFunc))>>()) \
195 KJ_UNIQUE_NAME(_kjContext)(KJ_UNIQUE_NAME(_kjContextFunc))
196
197#define KJ_REQUIRE_NONNULL(value, ...) \
198 (*[&] { \
199 auto _kj_result = ::kj::_::readMaybe(value); \
200 if (KJ_UNLIKELY(!_kj_result)) { \
201 ::kj::_::Debug::Fault(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
202 #value " != nullptr", "" #__VA_ARGS__, __VA_ARGS__).fatal(); \
203 } \
204 return _kj_result; \
205 }())
206
207#define KJ_EXCEPTION(type, ...) \
208 ::kj::Exception(::kj::Exception::Type::type, __FILE__, __LINE__, \
209 ::kj::_::Debug::makeDescription("" #__VA_ARGS__, __VA_ARGS__))
210
211#else
212
213#define KJ_LOG(severity, ...) \
214 for (bool _kj_shouldLog = ::kj::_::Debug::shouldLog(::kj::LogSeverity::severity); \
215 _kj_shouldLog; _kj_shouldLog = false) \
216 ::kj::_::Debug::log(__FILE__, __LINE__, ::kj::LogSeverity::severity, \
217 #__VA_ARGS__, ##__VA_ARGS__)
218
219#define KJ_DBG(...) KJ_LOG(DBG, ##__VA_ARGS__)
220
221#define KJ_REQUIRE(cond, ...) \
222 if (KJ_LIKELY(cond)) {} else \
223 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
224 #cond, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
225
226#define KJ_FAIL_REQUIRE(...) \
227 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
228 nullptr, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
229
230#define KJ_SYSCALL(call, ...) \
231 if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, false)) {} else \
232 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
233 _kjSyscallResult.getErrorNumber(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
234
235#define KJ_NONBLOCKING_SYSCALL(call, ...) \
236 if (auto _kjSyscallResult = ::kj::_::Debug::syscall([&](){return (call);}, true)) {} else \
237 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
238 _kjSyscallResult.getErrorNumber(), #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
239
240#define KJ_FAIL_SYSCALL(code, errorNumber, ...) \
241 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
242 errorNumber, code, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
243
244#if _WIN32
245
246#define KJ_WIN32(call, ...) \
247 if (auto _kjWin32Result = ::kj::_::Debug::win32Call(call)) {} else \
248 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
249 _kjWin32Result, #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
250// Invoke a Win32 syscall that returns either BOOL or HANDLE, and throw an exception if it fails.
251
252#define KJ_WINSOCK(call, ...) \
253 if (auto _kjWin32Result = ::kj::_::Debug::winsockCall(call)) {} else \
254 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
255 _kjWin32Result, #call, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
256// Like KJ_WIN32 but for winsock calls which return `int` with SOCKET_ERROR indicating failure.
257//
258// Unfortunately, it's impossible to distinguish these from BOOL-returning Win32 calls by type,
259// since BOOL is in fact an alias for `int`. :(
260
261#define KJ_FAIL_WIN32(code, errorNumber, ...) \
262 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, \
263 ::kj::_::Debug::Win32Result(errorNumber), code, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
264
265#endif
266
267#define KJ_UNIMPLEMENTED(...) \
268 for (::kj::_::Debug::Fault f(__FILE__, __LINE__, ::kj::Exception::Type::UNIMPLEMENTED, \
269 nullptr, #__VA_ARGS__, ##__VA_ARGS__);; f.fatal())
270
271#define KJ_CONTEXT(...) \
272 auto KJ_UNIQUE_NAME(_kjContextFunc) = [&]() -> ::kj::_::Debug::Context::Value { \
273 return ::kj::_::Debug::Context::Value(__FILE__, __LINE__, \
274 ::kj::_::Debug::makeDescription(#__VA_ARGS__, ##__VA_ARGS__)); \
275 }; \
276 ::kj::_::Debug::ContextImpl<decltype(KJ_UNIQUE_NAME(_kjContextFunc))> \
277 KJ_UNIQUE_NAME(_kjContext)(KJ_UNIQUE_NAME(_kjContextFunc))
278
279#define KJ_REQUIRE_NONNULL(value, ...) \
280 (*({ \
281 auto _kj_result = ::kj::_::readMaybe(value); \
282 if (KJ_UNLIKELY(!_kj_result)) { \
283 ::kj::_::Debug::Fault(__FILE__, __LINE__, ::kj::Exception::Type::FAILED, \
284 #value " != nullptr", #__VA_ARGS__, ##__VA_ARGS__).fatal(); \
285 } \
286 kj::mv(_kj_result); \
287 }))
288
289#define KJ_EXCEPTION(type, ...) \
290 ::kj::Exception(::kj::Exception::Type::type, __FILE__, __LINE__, \
291 ::kj::_::Debug::makeDescription(#__VA_ARGS__, ##__VA_ARGS__))
292
293#endif
294
295#define KJ_SYSCALL_HANDLE_ERRORS(call) \
296 if (int _kjSyscallError = ::kj::_::Debug::syscallError([&](){return (call);}, false)) \
297 switch (int error KJ_UNUSED = _kjSyscallError)
298// Like KJ_SYSCALL, but doesn't throw. Instead, the block after the macro is a switch block on the
299// error. Additionally, the int value `error` is defined within the block. So you can do:
300//
301// KJ_SYSCALL_HANDLE_ERRORS(foo()) {
302// case ENOENT:
303// handleNoSuchFile();
304// break;
305// case EEXIST:
306// handleExists();
307// break;
308// default:
309// KJ_FAIL_SYSCALL("foo()", error);
310// } else {
311// handleSuccessCase();
312// }
313
314#if _WIN32
315
316#define KJ_WIN32_HANDLE_ERRORS(call) \
317 if (uint _kjWin32Error = ::kj::_::Debug::win32Call(call).number) \
318 switch (uint error KJ_UNUSED = _kjWin32Error)
319// Like KJ_WIN32, but doesn't throw. Instead, the block after the macro is a switch block on the
320// error. Additionally, the int value `error` is defined within the block. So you can do:
321//
322// KJ_SYSCALL_HANDLE_ERRORS(foo()) {
323// case ERROR_FILE_NOT_FOUND:
324// handleNoSuchFile();
325// break;
326// case ERROR_FILE_EXISTS:
327// handleExists();
328// break;
329// default:
330// KJ_FAIL_WIN32("foo()", error);
331// } else {
332// handleSuccessCase();
333// }
334
335#endif
336
337#define KJ_ASSERT KJ_REQUIRE
338#define KJ_FAIL_ASSERT KJ_FAIL_REQUIRE
339#define KJ_ASSERT_NONNULL KJ_REQUIRE_NONNULL
340// Use "ASSERT" in place of "REQUIRE" when the problem is local to the immediate surrounding code.
341// That is, if the assert ever fails, it indicates that the immediate surrounding code is broken.
342
343#ifdef KJ_DEBUG
344#define KJ_DLOG KJ_LOG
345#define KJ_DASSERT KJ_ASSERT
346#define KJ_DREQUIRE KJ_REQUIRE
347#else
348#define KJ_DLOG(...) do {} while (false)
349#define KJ_DASSERT(...) do {} while (false)
350#define KJ_DREQUIRE(...) do {} while (false)
351#endif
352
353namespace _ { // private
354
355class Debug {
356public:
357 Debug() = delete;
358
359 typedef LogSeverity Severity; // backwards-compatibility
360
361#if _WIN32
362 struct Win32Result {
363 uint number;
364 inline explicit Win32Result(uint number): number(number) {}
365 operator bool() const { return number == 0; }
366 };
367#endif
368
369 static inline bool shouldLog(LogSeverity severity) { return severity >= minSeverity; }
370 // Returns whether messages of the given severity should be logged.
371
372 static inline void setLogLevel(LogSeverity severity) { minSeverity = severity; }
373 // Set the minimum message severity which will be logged.
374 //
375 // TODO(someday): Expose publicly.
376
377 template <typename... Params>
378 static void log(const char* file, int line, LogSeverity severity, const char* macroArgs,
379 Params&&... params);
380
381 class Fault {
382 public:
383 template <typename Code, typename... Params>
384 Fault(const char* file, int line, Code code,
385 const char* condition, const char* macroArgs, Params&&... params);
386 Fault(const char* file, int line, Exception::Type type,
387 const char* condition, const char* macroArgs);
388 Fault(const char* file, int line, int osErrorNumber,
389 const char* condition, const char* macroArgs);
390#if _WIN32
391 Fault(const char* file, int line, Win32Result osErrorNumber,
392 const char* condition, const char* macroArgs);
393#endif
394 ~Fault() noexcept(false);
395
396 KJ_NOINLINE KJ_NORETURN(void fatal());
397 // Throw the exception.
398
399 private:
400 void init(const char* file, int line, Exception::Type type,
401 const char* condition, const char* macroArgs, ArrayPtr<String> argValues);
402 void init(const char* file, int line, int osErrorNumber,
403 const char* condition, const char* macroArgs, ArrayPtr<String> argValues);
404#if _WIN32
405 void init(const char* file, int line, Win32Result osErrorNumber,
406 const char* condition, const char* macroArgs, ArrayPtr<String> argValues);
407#endif
408
409 Exception* exception;
410 };
411
412 class SyscallResult {
413 public:
414 inline SyscallResult(int errorNumber): errorNumber(errorNumber) {}
415 inline operator void*() { return errorNumber == 0 ? this : nullptr; }
416 inline int getErrorNumber() { return errorNumber; }
417
418 private:
419 int errorNumber;
420 };
421
422 template <typename Call>
423 static SyscallResult syscall(Call&& call, bool nonblocking);
424 template <typename Call>
425 static int syscallError(Call&& call, bool nonblocking);
426
427#if _WIN32
428 static Win32Result win32Call(int boolean);
429 static Win32Result win32Call(void* handle);
430 static Win32Result winsockCall(int result);
431 static uint getWin32ErrorCode();
432#endif
433
434 class Context: public ExceptionCallback {
435 public:
436 Context();
437 KJ_DISALLOW_COPY(Context);
438 virtual ~Context() noexcept(false);
439
440 struct Value {
441 const char* file;
442 int line;
443 String description;
444
445 inline Value(const char* file, int line, String&& description)
446 : file(file), line(line), description(mv(description)) {}
447 };
448
449 virtual Value evaluate() = 0;
450
451 virtual void onRecoverableException(Exception&& exception) override;
452 virtual void onFatalException(Exception&& exception) override;
453 virtual void logMessage(LogSeverity severity, const char* file, int line, int contextDepth,
454 String&& text) override;
455
456 private:
457 bool logged;
458 Maybe<Value> value;
459
460 Value ensureInitialized();
461 };
462
463 template <typename Func>
464 class ContextImpl: public Context {
465 public:
466 inline ContextImpl(Func& func): func(func) {}
467 KJ_DISALLOW_COPY(ContextImpl);
468
469 Value evaluate() override {
470 return func();
471 }
472 private:
473 Func& func;
474 };
475
476 template <typename... Params>
477 static String makeDescription(const char* macroArgs, Params&&... params);
478
479private:
480 static LogSeverity minSeverity;
481
482 static void logInternal(const char* file, int line, LogSeverity severity, const char* macroArgs,
483 ArrayPtr<String> argValues);
484 static String makeDescriptionInternal(const char* macroArgs, ArrayPtr<String> argValues);
485
486 static int getOsErrorNumber(bool nonblocking);
487 // Get the error code of the last error (e.g. from errno). Returns -1 on EINTR.
488};
489
490template <typename... Params>
491void Debug::log(const char* file, int line, LogSeverity severity, const char* macroArgs,
492 Params&&... params) {
493 String argValues[sizeof...(Params)] = {str(params)...};
494 logInternal(file, line, severity, macroArgs, arrayPtr(argValues, sizeof...(Params)));
495}
496
497template <>
498inline void Debug::log<>(const char* file, int line, LogSeverity severity, const char* macroArgs) {
499 logInternal(file, line, severity, macroArgs, nullptr);
500}
501
502template <typename Code, typename... Params>
503Debug::Fault::Fault(const char* file, int line, Code code,
504 const char* condition, const char* macroArgs, Params&&... params)
505 : exception(nullptr) {
506 String argValues[sizeof...(Params)] = {str(params)...};
507 init(file, line, code, condition, macroArgs,
508 arrayPtr(argValues, sizeof...(Params)));
509}
510
511inline Debug::Fault::Fault(const char* file, int line, int osErrorNumber,
512 const char* condition, const char* macroArgs)
513 : exception(nullptr) {
514 init(file, line, osErrorNumber, condition, macroArgs, nullptr);
515}
516
517inline Debug::Fault::Fault(const char* file, int line, kj::Exception::Type type,
518 const char* condition, const char* macroArgs)
519 : exception(nullptr) {
520 init(file, line, type, condition, macroArgs, nullptr);
521}
522
523#if _WIN32
524inline Debug::Fault::Fault(const char* file, int line, Win32Result osErrorNumber,
525 const char* condition, const char* macroArgs)
526 : exception(nullptr) {
527 init(file, line, osErrorNumber, condition, macroArgs, nullptr);
528}
529
530inline Debug::Win32Result Debug::win32Call(int boolean) {
531 return boolean ? Win32Result(0) : Win32Result(getWin32ErrorCode());
532}
533inline Debug::Win32Result Debug::win32Call(void* handle) {
534 // Assume null and INVALID_HANDLE_VALUE mean failure.
535 return win32Call(handle != nullptr && handle != (void*)-1);
536}
537inline Debug::Win32Result Debug::winsockCall(int result) {
538 // Expect a return value of SOCKET_ERROR means failure.
539 return win32Call(result != -1);
540}
541#endif
542
543template <typename Call>
544Debug::SyscallResult Debug::syscall(Call&& call, bool nonblocking) {
545 while (call() < 0) {
546 int errorNum = getOsErrorNumber(nonblocking);
547 // getOsErrorNumber() returns -1 to indicate EINTR.
548 // Also, if nonblocking is true, then it returns 0 on EAGAIN, which will then be treated as a
549 // non-error.
550 if (errorNum != -1) {
551 return SyscallResult(errorNum);
552 }
553 }
554 return SyscallResult(0);
555}
556
557template <typename Call>
558int Debug::syscallError(Call&& call, bool nonblocking) {
559 while (call() < 0) {
560 int errorNum = getOsErrorNumber(nonblocking);
561 // getOsErrorNumber() returns -1 to indicate EINTR.
562 // Also, if nonblocking is true, then it returns 0 on EAGAIN, which will then be treated as a
563 // non-error.
564 if (errorNum != -1) {
565 return errorNum;
566 }
567 }
568 return 0;
569}
570
571template <typename... Params>
572String Debug::makeDescription(const char* macroArgs, Params&&... params) {
573 String argValues[sizeof...(Params)] = {str(params)...};
574 return makeDescriptionInternal(macroArgs, arrayPtr(argValues, sizeof...(Params)));
575}
576
577template <>
578inline String Debug::makeDescription<>(const char* macroArgs) {
579 return makeDescriptionInternal(macroArgs, nullptr);
580}
581
582} // namespace _ (private)
583} // namespace kj
584