logging.h 18.8 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef V8_BASE_LOGGING_H_
#define V8_BASE_LOGGING_H_

8 9 10
#include <cstring>
#include <sstream>
#include <string>
11

12
#include "src/base/base-export.h"
13
#include "src/base/build_config.h"
jfb's avatar
jfb committed
14
#include "src/base/compiler-specific.h"
15
#include "src/base/immediate-crash.h"
16
#include "src/base/template-utils.h"
17

18 19 20
V8_BASE_EXPORT V8_NOINLINE void V8_Dcheck(const char* file, int line,
                                          const char* message);

21
#ifdef DEBUG
22 23 24 25
// In debug, include file, line, and full error message for all
// FATAL() calls.
[[noreturn]] PRINTF_FORMAT(3, 4) V8_BASE_EXPORT V8_NOINLINE
    void V8_Fatal(const char* file, int line, const char* format, ...);
26
#define FATAL(...) V8_Fatal(__FILE__, __LINE__, __VA_ARGS__)
27

28 29 30 31
#else
[[noreturn]] PRINTF_FORMAT(1, 2) V8_BASE_EXPORT V8_NOINLINE
    void V8_Fatal(const char* format, ...);
#if !defined(OFFICIAL_BUILD)
32 33 34
// In non-official release, include full error message, but drop file & line
// numbers. It saves binary size to drop the |file| & |line| as opposed to just
// passing in "", 0 for them.
35
#define FATAL(...) V8_Fatal(__VA_ARGS__)
36
#else
37 38
// FATAL(msg) -> IMMEDIATE_CRASH()
// FATAL(msg, ...) -> V8_Fatal(msg, ...)
39
#define FATAL_HELPER(_7, _6, _5, _4, _3, _2, _1, _0, ...) _0
40
#define FATAL_DISCARD_ARG(arg) IMMEDIATE_CRASH()
41 42
#define FATAL(...)                                                            \
  FATAL_HELPER(__VA_ARGS__, V8_Fatal, V8_Fatal, V8_Fatal, V8_Fatal, V8_Fatal, \
43
               V8_Fatal, FATAL_DISCARD_ARG)                                   \
44
  (__VA_ARGS__)
45 46
#endif  // !defined(OFFICIAL_BUILD)
#endif  // DEBUG
47

48 49
#define UNIMPLEMENTED() FATAL("unimplemented code")
#define UNREACHABLE() FATAL("unreachable code")
50

51 52
namespace v8 {
namespace base {
53

54 55
class CheckMessageStream : public std::ostringstream {};

56 57 58
// Overwrite the default function that prints a stack trace.
V8_BASE_EXPORT void SetPrintStackTrace(void (*print_stack_trace_)());

59 60 61 62
// Override the default function that handles DCHECKs.
V8_BASE_EXPORT void SetDcheckFunction(void (*dcheck_Function)(const char*, int,
                                                              const char*));

63 64 65 66 67 68 69 70
// In official builds, assume all check failures can be debugged given just the
// stack trace.
#if !defined(DEBUG) && defined(OFFICIAL_BUILD)
#define CHECK_FAILED_HANDLER(message) FATAL("ignored")
#else
#define CHECK_FAILED_HANDLER(message) FATAL("Check failed: %s.", message)
#endif

71 72 73 74 75 76
// CHECK dies with a fatal error if condition is not true.  It is *not*
// controlled by DEBUG, so the check will be executed regardless of
// compilation mode.
//
// We make sure CHECK et al. always evaluates their arguments, as
// doing CHECK(FunctionWithSideEffect()) is a common idiom.
77 78 79
#define CHECK_WITH_MSG(condition, message) \
  do {                                     \
    if (V8_UNLIKELY(!(condition))) {       \
80
      CHECK_FAILED_HANDLER(message);       \
81
    }                                      \
82
  } while (false)
83
#define CHECK(condition) CHECK_WITH_MSG(condition, #condition)
84

85
#ifdef DEBUG
86

87 88 89 90 91
#define DCHECK_WITH_MSG(condition, message)   \
  do {                                        \
    if (V8_UNLIKELY(!(condition))) {          \
      V8_Dcheck(__FILE__, __LINE__, message); \
    }                                         \
92
  } while (false)
93 94
#define DCHECK(condition) DCHECK_WITH_MSG(condition, #condition)

95 96
// Helper macro for binary operators.
// Don't use this macro directly in your code, use CHECK_EQ et al below.
97 98 99 100 101 102
#define CHECK_OP(name, op, lhs, rhs)                                      \
  do {                                                                    \
    if (std::string* _msg = ::v8::base::Check##name##Impl<                \
            typename ::v8::base::pass_value_or_ref<decltype(lhs)>::type,  \
            typename ::v8::base::pass_value_or_ref<decltype(rhs)>::type>( \
            (lhs), (rhs), #lhs " " #op " " #rhs)) {                       \
103
      FATAL("Check failed: %s.", _msg->c_str());                          \
104 105
      delete _msg;                                                        \
    }                                                                     \
106
  } while (false)
107

108 109 110 111 112 113 114 115 116
#define DCHECK_OP(name, op, lhs, rhs)                                     \
  do {                                                                    \
    if (std::string* _msg = ::v8::base::Check##name##Impl<                \
            typename ::v8::base::pass_value_or_ref<decltype(lhs)>::type,  \
            typename ::v8::base::pass_value_or_ref<decltype(rhs)>::type>( \
            (lhs), (rhs), #lhs " " #op " " #rhs)) {                       \
      V8_Dcheck(__FILE__, __LINE__, _msg->c_str());                       \
      delete _msg;                                                        \
    }                                                                     \
117
  } while (false)
118

119
#else
120

121 122
// Make all CHECK functions discard their log strings to reduce code
// bloat for official release builds.
123

124 125 126 127 128 129 130
#define CHECK_OP(name, op, lhs, rhs)                                         \
  do {                                                                       \
    bool _cmp = ::v8::base::Cmp##name##Impl<                                 \
        typename ::v8::base::pass_value_or_ref<decltype(lhs)>::type,         \
        typename ::v8::base::pass_value_or_ref<decltype(rhs)>::type>((lhs),  \
                                                                     (rhs)); \
    CHECK_WITH_MSG(_cmp, #lhs " " #op " " #rhs);                             \
131
  } while (false)
132

133 134
#define DCHECK_WITH_MSG(condition, msg) void(0);

135
#endif
136

137 138 139
namespace detail {
template <typename... Ts>
std::string PrintToString(Ts&&... ts) {
140
  CheckMessageStream oss;
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
  int unused_results[]{((oss << std::forward<Ts>(ts)), 0)...};
  (void)unused_results;  // Avoid "unused variable" warning.
  return oss.str();
}

template <typename T>
auto GetUnderlyingEnumTypeForPrinting(T val) {
  using underlying_t = typename std::underlying_type<T>::type;
  // For single-byte enums, return a 16-bit integer to avoid printing the value
  // as a character.
  using int_t = typename std::conditional_t<
      sizeof(underlying_t) != 1, underlying_t,
      std::conditional_t<std::is_signed<underlying_t>::value, int16_t,
                         uint16_t> >;
  return static_cast<int_t>(static_cast<underlying_t>(val));
}
}  // namespace detail

159 160
// Define PrintCheckOperand<T> for each T which defines operator<< for ostream.
template <typename T>
161 162
typename std::enable_if<
    !std::is_function<typename std::remove_pointer<T>::type>::value &&
163 164
        !std::is_enum<T>::value &&
        has_output_operator<T, CheckMessageStream>::value,
165 166
    std::string>::type
PrintCheckOperand(T val) {
167
  return detail::PrintToString(std::forward<T>(val));
168 169
}

170 171 172 173 174 175 176
// Provide an overload for functions and function pointers. Function pointers
// don't implicitly convert to void* but do implicitly convert to bool, so
// without this function pointers are always printed as 1 or 0. (MSVC isn't
// standards-conforming here and converts function pointers to regular
// pointers, so this is a no-op for MSVC.)
template <typename T>
typename std::enable_if<
177 178 179 180
    std::is_function<typename std::remove_pointer<T>::type>::value,
    std::string>::type
PrintCheckOperand(T val) {
  return PrintCheckOperand(reinterpret_cast<const void*>(val));
181 182
}

183 184
// Define PrintCheckOperand<T> for enums with an output operator.
template <typename T>
185 186
typename std::enable_if<std::is_enum<T>::value &&
                            has_output_operator<T, CheckMessageStream>::value,
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
                        std::string>::type
PrintCheckOperand(T val) {
  std::string val_str = detail::PrintToString(val);
  std::string int_str =
      detail::PrintToString(detail::GetUnderlyingEnumTypeForPrinting(val));
  // Printing the original enum might have printed a single non-printable
  // character. Ignore it in that case. Also ignore if it printed the same as
  // the integral representation.
  // TODO(clemensb): Can we somehow statically find out if the output operator
  // is the default one, printing the integral value?
  if ((val_str.length() == 1 && !std::isprint(val_str[0])) ||
      val_str == int_str) {
    return int_str;
  }
  return detail::PrintToString(val_str, " (", int_str, ")");
}

// Define PrintCheckOperand<T> for enums without an output operator.
205
template <typename T>
206 207 208
typename std::enable_if<std::is_enum<T>::value &&
                            !has_output_operator<T, CheckMessageStream>::value,
                        std::string>::type
209
PrintCheckOperand(T val) {
210
  return detail::PrintToString(detail::GetUnderlyingEnumTypeForPrinting(val));
211 212 213 214
}

// Define default PrintCheckOperand<T> for non-printable types.
template <typename T>
215
typename std::enable_if<!has_output_operator<T, CheckMessageStream>::value &&
216 217 218 219
                            !std::is_enum<T>::value,
                        std::string>::type
PrintCheckOperand(T val) {
  return "<unprintable>";
220 221
}

222
// Define specializations for character types, defined in logging.cc.
223 224 225 226 227 228 229
#define DEFINE_PRINT_CHECK_OPERAND_CHAR(type)                       \
  template <>                                                       \
  V8_BASE_EXPORT std::string PrintCheckOperand<type>(type ch);      \
  template <>                                                       \
  V8_BASE_EXPORT std::string PrintCheckOperand<type*>(type * cstr); \
  template <>                                                       \
  V8_BASE_EXPORT std::string PrintCheckOperand<const type*>(const type* cstr);
230 231 232 233 234 235

DEFINE_PRINT_CHECK_OPERAND_CHAR(char)
DEFINE_PRINT_CHECK_OPERAND_CHAR(signed char)
DEFINE_PRINT_CHECK_OPERAND_CHAR(unsigned char)
#undef DEFINE_PRINT_CHECK_OPERAND_CHAR

236 237 238 239 240
// Build the error message string.  This is separate from the "Impl"
// function template because it is not performance critical and so can
// be out of line, while the "Impl" code should be inline. Caller
// takes ownership of the returned string.
template <typename Lhs, typename Rhs>
241
V8_NOINLINE std::string* MakeCheckOpString(Lhs lhs, Rhs rhs, char const* msg) {
242 243
  std::string lhs_str = PrintCheckOperand<Lhs>(lhs);
  std::string rhs_str = PrintCheckOperand<Rhs>(rhs);
244
  CheckMessageStream ss;
245 246 247 248 249 250 251 252
  ss << msg;
  constexpr size_t kMaxInlineLength = 50;
  if (lhs_str.size() <= kMaxInlineLength &&
      rhs_str.size() <= kMaxInlineLength) {
    ss << " (" << lhs_str << " vs. " << rhs_str << ")";
  } else {
    ss << "\n   " << lhs_str << "\n vs.\n   " << rhs_str << "\n";
  }
253
  return new std::string(ss.str());
254 255
}

256 257
// Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated
// in logging.cc.
258
#define EXPLICIT_CHECK_OP_INSTANTIATION(type)                                \
259
  extern template V8_BASE_EXPORT std::string* MakeCheckOpString<type, type>( \
260
      type, type, char const*);                                              \
261
  extern template V8_BASE_EXPORT std::string PrintCheckOperand<type>(type);
262 263 264 265 266 267 268 269 270

EXPLICIT_CHECK_OP_INSTANTIATION(int)
EXPLICIT_CHECK_OP_INSTANTIATION(long)       // NOLINT(runtime/int)
EXPLICIT_CHECK_OP_INSTANTIATION(long long)  // NOLINT(runtime/int)
EXPLICIT_CHECK_OP_INSTANTIATION(unsigned int)
EXPLICIT_CHECK_OP_INSTANTIATION(unsigned long)       // NOLINT(runtime/int)
EXPLICIT_CHECK_OP_INSTANTIATION(unsigned long long)  // NOLINT(runtime/int)
EXPLICIT_CHECK_OP_INSTANTIATION(void const*)
#undef EXPLICIT_CHECK_OP_INSTANTIATION
271

272
// comparison_underlying_type provides the underlying integral type of an enum,
273 274
// or std::decay<T>::type if T is not an enum. Booleans are converted to
// "unsigned int", to allow "unsigned int == bool" comparisons.
275 276 277 278 279 280 281 282 283
template <typename T>
struct comparison_underlying_type {
  // std::underlying_type must only be used with enum types, thus use this
  // {Dummy} type if the given type is not an enum.
  enum Dummy {};
  using decay = typename std::decay<T>::type;
  static constexpr bool is_enum = std::is_enum<decay>::value;
  using underlying = typename std::underlying_type<
      typename std::conditional<is_enum, decay, Dummy>::type>::type;
284 285 286 287 288
  using type_or_bool =
      typename std::conditional<is_enum, underlying, decay>::type;
  using type =
      typename std::conditional<std::is_same<type_or_bool, bool>::value,
                                unsigned int, type_or_bool>::type;
289
};
290 291 292
// Cast a value to its underlying type
#define MAKE_UNDERLYING(Type, value) \
  static_cast<typename comparison_underlying_type<Type>::type>(value)
293

294 295 296 297
// is_signed_vs_unsigned::value is true if both types are integral, Lhs is
// signed, and Rhs is unsigned. False in all other cases.
template <typename Lhs, typename Rhs>
struct is_signed_vs_unsigned {
298 299 300 301 302 303
  using lhs_underlying = typename comparison_underlying_type<Lhs>::type;
  using rhs_underlying = typename comparison_underlying_type<Rhs>::type;
  static constexpr bool value = std::is_integral<lhs_underlying>::value &&
                                std::is_integral<rhs_underlying>::value &&
                                std::is_signed<lhs_underlying>::value &&
                                std::is_unsigned<rhs_underlying>::value;
304 305 306 307 308 309 310 311
};
// Same thing, other way around: Lhs is unsigned, Rhs signed.
template <typename Lhs, typename Rhs>
struct is_unsigned_vs_signed : public is_signed_vs_unsigned<Rhs, Lhs> {};

// Specialize the compare functions for signed vs. unsigned comparisons.
// std::enable_if ensures that this template is only instantiable if both Lhs
// and Rhs are integral types, and their signedness does not match.
312 313 314
#define MAKE_UNSIGNED(Type, value)         \
  static_cast<typename std::make_unsigned< \
      typename comparison_underlying_type<Type>::type>::type>(value)
315 316 317 318 319 320
#define DEFINE_SIGNED_MISMATCH_COMP(CHECK, NAME, IMPL)            \
  template <typename Lhs, typename Rhs>                           \
  V8_INLINE constexpr                                             \
      typename std::enable_if<CHECK<Lhs, Rhs>::value, bool>::type \
          Cmp##NAME##Impl(Lhs lhs, Rhs rhs) {                     \
    return IMPL;                                                  \
321 322
  }
DEFINE_SIGNED_MISMATCH_COMP(is_signed_vs_unsigned, EQ,
323 324
                            lhs >= 0 && MAKE_UNSIGNED(Lhs, lhs) ==
                                            MAKE_UNDERLYING(Rhs, rhs))
325
DEFINE_SIGNED_MISMATCH_COMP(is_signed_vs_unsigned, LT,
326 327
                            lhs < 0 || MAKE_UNSIGNED(Lhs, lhs) <
                                           MAKE_UNDERLYING(Rhs, rhs))
328
DEFINE_SIGNED_MISMATCH_COMP(is_signed_vs_unsigned, LE,
329 330
                            lhs <= 0 || MAKE_UNSIGNED(Lhs, lhs) <=
                                            MAKE_UNDERLYING(Rhs, rhs))
331 332 333 334 335 336 337 338 339 340 341 342
DEFINE_SIGNED_MISMATCH_COMP(is_signed_vs_unsigned, NE, !CmpEQImpl(lhs, rhs))
DEFINE_SIGNED_MISMATCH_COMP(is_signed_vs_unsigned, GT, !CmpLEImpl(lhs, rhs))
DEFINE_SIGNED_MISMATCH_COMP(is_signed_vs_unsigned, GE, !CmpLTImpl(lhs, rhs))
DEFINE_SIGNED_MISMATCH_COMP(is_unsigned_vs_signed, EQ, CmpEQImpl(rhs, lhs))
DEFINE_SIGNED_MISMATCH_COMP(is_unsigned_vs_signed, NE, CmpNEImpl(rhs, lhs))
DEFINE_SIGNED_MISMATCH_COMP(is_unsigned_vs_signed, LT, CmpGTImpl(rhs, lhs))
DEFINE_SIGNED_MISMATCH_COMP(is_unsigned_vs_signed, LE, CmpGEImpl(rhs, lhs))
DEFINE_SIGNED_MISMATCH_COMP(is_unsigned_vs_signed, GT, CmpLTImpl(rhs, lhs))
DEFINE_SIGNED_MISMATCH_COMP(is_unsigned_vs_signed, GE, CmpLEImpl(rhs, lhs))
#undef MAKE_UNSIGNED
#undef DEFINE_SIGNED_MISMATCH_COMP

343 344
// Helper functions for CHECK_OP macro.
// The (float, float) and (double, double) instantiations are explicitly
345 346 347 348 349
// externalized to ensure proper 32/64-bit comparisons on x86.
// The Cmp##NAME##Impl function is only instantiable if one of the two types is
// not integral or their signedness matches (i.e. whenever no specialization is
// required, see above). Otherwise it is disabled by the enable_if construct,
// and the compiler will pick a specialization from above.
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
#define DEFINE_CHECK_OP_IMPL(NAME, op)                                        \
  template <typename Lhs, typename Rhs>                                       \
  V8_INLINE constexpr                                                         \
      typename std::enable_if<!is_signed_vs_unsigned<Lhs, Rhs>::value &&      \
                                  !is_unsigned_vs_signed<Lhs, Rhs>::value,    \
                              bool>::type Cmp##NAME##Impl(Lhs lhs, Rhs rhs) { \
    return lhs op rhs;                                                        \
  }                                                                           \
  template <typename Lhs, typename Rhs>                                       \
  V8_INLINE constexpr std::string* Check##NAME##Impl(Lhs lhs, Rhs rhs,        \
                                                     char const* msg) {       \
    using LhsPassT = typename pass_value_or_ref<Lhs>::type;                   \
    using RhsPassT = typename pass_value_or_ref<Rhs>::type;                   \
    bool cmp = Cmp##NAME##Impl<LhsPassT, RhsPassT>(lhs, rhs);                 \
    return V8_LIKELY(cmp)                                                     \
               ? nullptr                                                      \
               : MakeCheckOpString<LhsPassT, RhsPassT>(lhs, rhs, msg);        \
  }
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
DEFINE_CHECK_OP_IMPL(EQ, ==)
DEFINE_CHECK_OP_IMPL(NE, !=)
DEFINE_CHECK_OP_IMPL(LE, <=)
DEFINE_CHECK_OP_IMPL(LT, < )
DEFINE_CHECK_OP_IMPL(GE, >=)
DEFINE_CHECK_OP_IMPL(GT, > )
#undef DEFINE_CHECK_OP_IMPL

#define CHECK_EQ(lhs, rhs) CHECK_OP(EQ, ==, lhs, rhs)
#define CHECK_NE(lhs, rhs) CHECK_OP(NE, !=, lhs, rhs)
#define CHECK_LE(lhs, rhs) CHECK_OP(LE, <=, lhs, rhs)
#define CHECK_LT(lhs, rhs) CHECK_OP(LT, <, lhs, rhs)
#define CHECK_GE(lhs, rhs) CHECK_OP(GE, >=, lhs, rhs)
#define CHECK_GT(lhs, rhs) CHECK_OP(GT, >, lhs, rhs)
#define CHECK_NULL(val) CHECK((val) == nullptr)
#define CHECK_NOT_NULL(val) CHECK((val) != nullptr)
384 385
#define CHECK_IMPLIES(lhs, rhs) \
  CHECK_WITH_MSG(!(lhs) || (rhs), #lhs " implies " #rhs)
386

387 388
}  // namespace base
}  // namespace v8
389 390


391
// The DCHECK macro is equivalent to CHECK except that it only
392 393
// generates code in debug builds.
#ifdef DEBUG
394 395 396 397 398 399 400 401 402 403
#define DCHECK_EQ(lhs, rhs) DCHECK_OP(EQ, ==, lhs, rhs)
#define DCHECK_NE(lhs, rhs) DCHECK_OP(NE, !=, lhs, rhs)
#define DCHECK_GT(lhs, rhs) DCHECK_OP(GT, >, lhs, rhs)
#define DCHECK_GE(lhs, rhs) DCHECK_OP(GE, >=, lhs, rhs)
#define DCHECK_LT(lhs, rhs) DCHECK_OP(LT, <, lhs, rhs)
#define DCHECK_LE(lhs, rhs) DCHECK_OP(LE, <=, lhs, rhs)
#define DCHECK_NULL(val) DCHECK((val) == nullptr)
#define DCHECK_NOT_NULL(val) DCHECK((val) != nullptr)
#define DCHECK_IMPLIES(lhs, rhs) \
  DCHECK_WITH_MSG(!(lhs) || (rhs), #lhs " implies " #rhs)
404
#else
405 406 407
#define DCHECK(condition)      ((void) 0)
#define DCHECK_EQ(v1, v2)      ((void) 0)
#define DCHECK_NE(v1, v2)      ((void) 0)
mlippautz's avatar
mlippautz committed
408
#define DCHECK_GT(v1, v2)      ((void) 0)
409 410 411
#define DCHECK_GE(v1, v2)      ((void) 0)
#define DCHECK_LT(v1, v2)      ((void) 0)
#define DCHECK_LE(v1, v2)      ((void) 0)
412 413 414
#define DCHECK_NULL(val)       ((void) 0)
#define DCHECK_NOT_NULL(val)   ((void) 0)
#define DCHECK_IMPLIES(v1, v2) ((void) 0)
415 416 417
#endif

#endif  // V8_BASE_LOGGING_H_