1 /*
2  *  Copyright 2006 The WebRTC Project Authors. All rights reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #ifndef RTC_BASE_CHECKS_H_
12 #define RTC_BASE_CHECKS_H_
13 
14 // If you for some reson need to know if DCHECKs are on, test the value of
15 // RTC_DCHECK_IS_ON. (Test its value, not if it's defined; it'll always be
16 // defined, to either a true or a false value.)
17 #if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)
18 #define RTC_DCHECK_IS_ON 1
19 #else
20 #define RTC_DCHECK_IS_ON 0
21 #endif
22 
23 // Annotate a function that will not return control flow to the caller.
24 #if defined(_MSC_VER)
25 #define RTC_NORETURN __declspec(noreturn)
26 #elif defined(__GNUC__)
27 #define RTC_NORETURN __attribute__((__noreturn__))
28 #else
29 #define RTC_NORETURN
30 #endif
31 
32 #ifdef __cplusplus
33 extern "C" {
34 #endif
35 RTC_NORETURN void rtc_FatalMessage(const char* file, int line, const char* msg);
36 #ifdef __cplusplus
37 }  // extern "C"
38 #endif
39 
40 #ifdef RTC_DISABLE_CHECK_MSG
41 #define RTC_CHECK_MSG_ENABLED 0
42 #else
43 #define RTC_CHECK_MSG_ENABLED 1
44 #endif
45 
46 #if RTC_CHECK_MSG_ENABLED
47 #define RTC_CHECK_EVAL_MESSAGE(message) message
48 #else
49 #define RTC_CHECK_EVAL_MESSAGE(message) ""
50 #endif
51 
52 #ifdef __cplusplus
53 // C++ version.
54 
55 #include <string>
56 
57 #include "absl/meta/type_traits.h"
58 #include "absl/strings/string_view.h"
59 #include "rtc_base/numerics/safe_compare.h"
60 #include "rtc_base/system/inline.h"
61 #include "rtc_base/system/rtc_export.h"
62 
63 // The macros here print a message to stderr and abort under various
64 // conditions. All will accept additional stream messages. For example:
65 // RTC_DCHECK_EQ(foo, bar) << "I'm printed when foo != bar.";
66 //
67 // - RTC_CHECK(x) is an assertion that x is always true, and that if it isn't,
68 //   it's better to terminate the process than to continue. During development,
69 //   the reason that it's better to terminate might simply be that the error
70 //   handling code isn't in place yet; in production, the reason might be that
71 //   the author of the code truly believes that x will always be true, but that
72 //   they recognizes that if they are wrong, abrupt and unpleasant process
73 //   termination is still better than carrying on with the assumption violated.
74 //
75 //   RTC_CHECK always evaluates its argument, so it's OK for x to have side
76 //   effects.
77 //
78 // - RTC_DCHECK(x) is the same as RTC_CHECK(x)---an assertion that x is always
79 //   true---except that x will only be evaluated in debug builds; in production
80 //   builds, x is simply assumed to be true. This is useful if evaluating x is
81 //   expensive and the expected cost of failing to detect the violated
82 //   assumption is acceptable. You should not handle cases where a production
83 //   build fails to spot a violated condition, even those that would result in
84 //   crashes. If the code needs to cope with the error, make it cope, but don't
85 //   call RTC_DCHECK; if the condition really can't occur, but you'd sleep
86 //   better at night knowing that the process will suicide instead of carrying
87 //   on in case you were wrong, use RTC_CHECK instead of RTC_DCHECK.
88 //
89 //   RTC_DCHECK only evaluates its argument in debug builds, so if x has visible
90 //   side effects, you need to write e.g.
91 //     bool w = x; RTC_DCHECK(w);
92 //
93 // - RTC_CHECK_EQ, _NE, _GT, ..., and RTC_DCHECK_EQ, _NE, _GT, ... are
94 //   specialized variants of RTC_CHECK and RTC_DCHECK that print prettier
95 //   messages if the condition doesn't hold. Prefer them to raw RTC_CHECK and
96 //   RTC_DCHECK.
97 //
98 // - RTC_FATAL() aborts unconditionally.
99 
100 namespace rtc {
101 namespace webrtc_checks_impl {
102 enum class CheckArgType : int8_t {
103   kEnd = 0,
104   kInt,
105   kLong,
106   kLongLong,
107   kUInt,
108   kULong,
109   kULongLong,
110   kDouble,
111   kLongDouble,
112   kCharP,
113   kStdString,
114   kStringView,
115   kVoidP,
116 
117   // kCheckOp doesn't represent an argument type. Instead, it is sent as the
118   // first argument from RTC_CHECK_OP to make FatalLog use the next two
119   // arguments to build the special CHECK_OP error message
120   // (the "a == b (1 vs. 2)" bit).
121   kCheckOp,
122 };
123 
124 #if RTC_CHECK_MSG_ENABLED
125 RTC_NORETURN RTC_EXPORT void FatalLog(const char* file,
126                                       int line,
127                                       const char* message,
128                                       const CheckArgType* fmt,
129                                       ...);
130 #else
131 RTC_NORETURN RTC_EXPORT void FatalLog(const char* file, int line);
132 #endif
133 
134 // Wrapper for log arguments. Only ever make values of this type with the
135 // MakeVal() functions.
136 template <CheckArgType N, typename T>
137 struct Val {
TypeVal138   static constexpr CheckArgType Type() { return N; }
GetValVal139   T GetVal() const { return val; }
140   T val;
141 };
142 
143 // Case for when we need to construct a temp string and then print that.
144 // (We can't use Val<CheckArgType::kStdString, const std::string*>
145 // because we need somewhere to store the temp string.)
146 struct ToStringVal {
TypeToStringVal147   static constexpr CheckArgType Type() { return CheckArgType::kStdString; }
GetValToStringVal148   const std::string* GetVal() const { return &val; }
149   std::string val;
150 };
151 
MakeVal(int x)152 inline Val<CheckArgType::kInt, int> MakeVal(int x) {
153   return {x};
154 }
MakeVal(long x)155 inline Val<CheckArgType::kLong, long> MakeVal(long x) {
156   return {x};
157 }
MakeVal(long long x)158 inline Val<CheckArgType::kLongLong, long long> MakeVal(long long x) {
159   return {x};
160 }
MakeVal(unsigned int x)161 inline Val<CheckArgType::kUInt, unsigned int> MakeVal(unsigned int x) {
162   return {x};
163 }
MakeVal(unsigned long x)164 inline Val<CheckArgType::kULong, unsigned long> MakeVal(unsigned long x) {
165   return {x};
166 }
MakeVal(unsigned long long x)167 inline Val<CheckArgType::kULongLong, unsigned long long> MakeVal(
168     unsigned long long x) {
169   return {x};
170 }
171 
MakeVal(double x)172 inline Val<CheckArgType::kDouble, double> MakeVal(double x) {
173   return {x};
174 }
MakeVal(long double x)175 inline Val<CheckArgType::kLongDouble, long double> MakeVal(long double x) {
176   return {x};
177 }
178 
MakeVal(const char * x)179 inline Val<CheckArgType::kCharP, const char*> MakeVal(const char* x) {
180   return {x};
181 }
MakeVal(const std::string & x)182 inline Val<CheckArgType::kStdString, const std::string*> MakeVal(
183     const std::string& x) {
184   return {&x};
185 }
MakeVal(const absl::string_view & x)186 inline Val<CheckArgType::kStringView, const absl::string_view*> MakeVal(
187     const absl::string_view& x) {
188   return {&x};
189 }
190 
MakeVal(const void * x)191 inline Val<CheckArgType::kVoidP, const void*> MakeVal(const void* x) {
192   return {x};
193 }
194 
195 // The enum class types are not implicitly convertible to arithmetic types.
196 template <typename T,
197           absl::enable_if_t<std::is_enum<T>::value &&
198                             !std::is_arithmetic<T>::value>* = nullptr>
decltype(MakeVal (std::declval<absl::underlying_type_t<T>> ()))199 inline decltype(MakeVal(std::declval<absl::underlying_type_t<T>>())) MakeVal(
200     T x) {
201   return {static_cast<absl::underlying_type_t<T>>(x)};
202 }
203 
204 template <typename T, decltype(ToLogString(std::declval<T>()))* = nullptr>
MakeVal(const T & x)205 ToStringVal MakeVal(const T& x) {
206   return {ToLogString(x)};
207 }
208 
209 // Ephemeral type that represents the result of the logging << operator.
210 template <typename... Ts>
211 class LogStreamer;
212 
213 // Base case: Before the first << argument.
214 template <>
215 class LogStreamer<> final {
216  public:
217   template <typename U,
218             typename V = decltype(MakeVal(std::declval<U>())),
219             absl::enable_if_t<std::is_arithmetic<U>::value ||
220                               std::is_enum<U>::value>* = nullptr>
221   RTC_FORCE_INLINE LogStreamer<V> operator<<(U arg) const {
222     return LogStreamer<V>(MakeVal(arg), this);
223   }
224 
225   template <typename U,
226             typename V = decltype(MakeVal(std::declval<U>())),
227             absl::enable_if_t<!std::is_arithmetic<U>::value &&
228                               !std::is_enum<U>::value>* = nullptr>
229   RTC_FORCE_INLINE LogStreamer<V> operator<<(const U& arg) const {
230     return LogStreamer<V>(MakeVal(arg), this);
231   }
232 
233 #if RTC_CHECK_MSG_ENABLED
234   template <typename... Us>
Call(const char * file,const int line,const char * message,const Us &...args)235   RTC_NORETURN RTC_FORCE_INLINE static void Call(const char* file,
236                                                  const int line,
237                                                  const char* message,
238                                                  const Us&... args) {
239     static constexpr CheckArgType t[] = {Us::Type()..., CheckArgType::kEnd};
240     FatalLog(file, line, message, t, args.GetVal()...);
241   }
242 
243   template <typename... Us>
CallCheckOp(const char * file,const int line,const char * message,const Us &...args)244   RTC_NORETURN RTC_FORCE_INLINE static void CallCheckOp(const char* file,
245                                                         const int line,
246                                                         const char* message,
247                                                         const Us&... args) {
248     static constexpr CheckArgType t[] = {CheckArgType::kCheckOp, Us::Type()...,
249                                          CheckArgType::kEnd};
250     FatalLog(file, line, message, t, args.GetVal()...);
251   }
252 #else
253   template <typename... Us>
Call(const char * file,const int line)254   RTC_NORETURN RTC_FORCE_INLINE static void Call(const char* file,
255                                                  const int line) {
256     FatalLog(file, line);
257   }
258 #endif
259 };
260 
261 // Inductive case: We've already seen at least one << argument. The most recent
262 // one had type `T`, and the earlier ones had types `Ts`.
263 template <typename T, typename... Ts>
264 class LogStreamer<T, Ts...> final {
265  public:
LogStreamer(T arg,const LogStreamer<Ts...> * prior)266   RTC_FORCE_INLINE LogStreamer(T arg, const LogStreamer<Ts...>* prior)
267       : arg_(arg), prior_(prior) {}
268 
269   template <typename U,
270             typename V = decltype(MakeVal(std::declval<U>())),
271             absl::enable_if_t<std::is_arithmetic<U>::value ||
272                               std::is_enum<U>::value>* = nullptr>
273   RTC_FORCE_INLINE LogStreamer<V, T, Ts...> operator<<(U arg) const {
274     return LogStreamer<V, T, Ts...>(MakeVal(arg), this);
275   }
276 
277   template <typename U,
278             typename V = decltype(MakeVal(std::declval<U>())),
279             absl::enable_if_t<!std::is_arithmetic<U>::value &&
280                               !std::is_enum<U>::value>* = nullptr>
281   RTC_FORCE_INLINE LogStreamer<V, T, Ts...> operator<<(const U& arg) const {
282     return LogStreamer<V, T, Ts...>(MakeVal(arg), this);
283   }
284 
285 #if RTC_CHECK_MSG_ENABLED
286   template <typename... Us>
Call(const char * file,const int line,const char * message,const Us &...args)287   RTC_NORETURN RTC_FORCE_INLINE void Call(const char* file,
288                                           const int line,
289                                           const char* message,
290                                           const Us&... args) const {
291     prior_->Call(file, line, message, arg_, args...);
292   }
293 
294   template <typename... Us>
CallCheckOp(const char * file,const int line,const char * message,const Us &...args)295   RTC_NORETURN RTC_FORCE_INLINE void CallCheckOp(const char* file,
296                                                  const int line,
297                                                  const char* message,
298                                                  const Us&... args) const {
299     prior_->CallCheckOp(file, line, message, arg_, args...);
300   }
301 #else
302   template <typename... Us>
Call(const char * file,const int line)303   RTC_NORETURN RTC_FORCE_INLINE void Call(const char* file,
304                                           const int line) const {
305     prior_->Call(file, line);
306   }
307 #endif
308 
309  private:
310   // The most recent argument.
311   T arg_;
312 
313   // Earlier arguments.
314   const LogStreamer<Ts...>* prior_;
315 };
316 
317 template <bool isCheckOp>
318 class FatalLogCall final {
319  public:
FatalLogCall(const char * file,int line,const char * message)320   FatalLogCall(const char* file, int line, const char* message)
321       : file_(file), line_(line), message_(message) {}
322 
323   // This can be any binary operator with precedence lower than <<.
324   template <typename... Ts>
325   RTC_NORETURN RTC_FORCE_INLINE void operator&(
326       const LogStreamer<Ts...>& streamer) {
327 #if RTC_CHECK_MSG_ENABLED
328     isCheckOp ? streamer.CallCheckOp(file_, line_, message_)
329               : streamer.Call(file_, line_, message_);
330 #else
331     streamer.Call(file_, line_);
332 #endif
333   }
334 
335  private:
336   const char* file_;
337   int line_;
338   const char* message_;
339 };
340 
341 #if RTC_DCHECK_IS_ON
342 
343 // Be helpful, and include file and line in the RTC_CHECK_NOTREACHED error
344 // message.
345 #define RTC_UNREACHABLE_FILE_AND_LINE_CALL_ARGS __FILE__, __LINE__
346 RTC_NORETURN RTC_EXPORT void UnreachableCodeReached(const char* file, int line);
347 
348 #else
349 
350 // Be mindful of binary size, and don't include file and line in the
351 // RTC_CHECK_NOTREACHED error message.
352 #define RTC_UNREACHABLE_FILE_AND_LINE_CALL_ARGS
353 RTC_NORETURN RTC_EXPORT void UnreachableCodeReached();
354 
355 #endif
356 
357 }  // namespace webrtc_checks_impl
358 
359 // The actual stream used isn't important. We reference |ignored| in the code
360 // but don't evaluate it; this is to avoid "unused variable" warnings (we do so
361 // in a particularly convoluted way with an extra ?: because that appears to be
362 // the simplest construct that keeps Visual Studio from complaining about
363 // condition being unused).
364 #define RTC_EAT_STREAM_PARAMETERS(ignored)                          \
365   (true ? true : ((void)(ignored), true))                           \
366       ? static_cast<void>(0)                                        \
367       : ::rtc::webrtc_checks_impl::FatalLogCall<false>("", 0, "") & \
368             ::rtc::webrtc_checks_impl::LogStreamer<>()
369 
370 // Call RTC_EAT_STREAM_PARAMETERS with an argument that fails to compile if
371 // values of the same types as |a| and |b| can't be compared with the given
372 // operation, and that would evaluate |a| and |b| if evaluated.
373 #define RTC_EAT_STREAM_PARAMETERS_OP(op, a, b) \
374   RTC_EAT_STREAM_PARAMETERS(((void)::rtc::Safe##op(a, b)))
375 
376 // RTC_CHECK dies with a fatal error if condition is not true. It is *not*
377 // controlled by NDEBUG or anything else, so the check will be executed
378 // regardless of compilation mode.
379 //
380 // We make sure RTC_CHECK et al. always evaluates |condition|, as
381 // doing RTC_CHECK(FunctionWithSideEffect()) is a common idiom.
382 //
383 // RTC_CHECK_OP is a helper macro for binary operators.
384 // Don't use this macro directly in your code, use RTC_CHECK_EQ et al below.
385 #if RTC_CHECK_MSG_ENABLED
386 #define RTC_CHECK(condition)                                    \
387   (condition) ? static_cast<void>(0)                            \
388               : ::rtc::webrtc_checks_impl::FatalLogCall<false>( \
389                     __FILE__, __LINE__, #condition) &           \
390                     ::rtc::webrtc_checks_impl::LogStreamer<>()
391 
392 #define RTC_CHECK_OP(name, op, val1, val2)                 \
393   ::rtc::Safe##name((val1), (val2))                        \
394       ? static_cast<void>(0)                               \
395       : ::rtc::webrtc_checks_impl::FatalLogCall<true>(     \
396             __FILE__, __LINE__, #val1 " " #op " " #val2) & \
397             ::rtc::webrtc_checks_impl::LogStreamer<>() << (val1) << (val2)
398 #else
399 #define RTC_CHECK(condition)                                                  \
400   (condition)                                                                 \
401       ? static_cast<void>(0)                                                  \
402       : true ? ::rtc::webrtc_checks_impl::FatalLogCall<false>(__FILE__,       \
403                                                               __LINE__, "") & \
404                    ::rtc::webrtc_checks_impl::LogStreamer<>()                 \
405              : ::rtc::webrtc_checks_impl::FatalLogCall<false>("", 0, "") &    \
406                    ::rtc::webrtc_checks_impl::LogStreamer<>()
407 
408 #define RTC_CHECK_OP(name, op, val1, val2)                                   \
409   ::rtc::Safe##name((val1), (val2))                                          \
410       ? static_cast<void>(0)                                                 \
411       : true ? ::rtc::webrtc_checks_impl::FatalLogCall<true>(__FILE__,       \
412                                                              __LINE__, "") & \
413                    ::rtc::webrtc_checks_impl::LogStreamer<>()                \
414              : ::rtc::webrtc_checks_impl::FatalLogCall<false>("", 0, "") &   \
415                    ::rtc::webrtc_checks_impl::LogStreamer<>()
416 #endif
417 
418 #define RTC_CHECK_EQ(val1, val2) RTC_CHECK_OP(Eq, ==, val1, val2)
419 #define RTC_CHECK_NE(val1, val2) RTC_CHECK_OP(Ne, !=, val1, val2)
420 #define RTC_CHECK_LE(val1, val2) RTC_CHECK_OP(Le, <=, val1, val2)
421 #define RTC_CHECK_LT(val1, val2) RTC_CHECK_OP(Lt, <, val1, val2)
422 #define RTC_CHECK_GE(val1, val2) RTC_CHECK_OP(Ge, >=, val1, val2)
423 #define RTC_CHECK_GT(val1, val2) RTC_CHECK_OP(Gt, >, val1, val2)
424 
425 // The RTC_DCHECK macro is equivalent to RTC_CHECK except that it only generates
426 // code in debug builds. It does reference the condition parameter in all cases,
427 // though, so callers won't risk getting warnings about unused variables.
428 #if RTC_DCHECK_IS_ON
429 #define RTC_DCHECK(condition) RTC_CHECK(condition)
430 #define RTC_DCHECK_EQ(v1, v2) RTC_CHECK_EQ(v1, v2)
431 #define RTC_DCHECK_NE(v1, v2) RTC_CHECK_NE(v1, v2)
432 #define RTC_DCHECK_LE(v1, v2) RTC_CHECK_LE(v1, v2)
433 #define RTC_DCHECK_LT(v1, v2) RTC_CHECK_LT(v1, v2)
434 #define RTC_DCHECK_GE(v1, v2) RTC_CHECK_GE(v1, v2)
435 #define RTC_DCHECK_GT(v1, v2) RTC_CHECK_GT(v1, v2)
436 #else
437 #define RTC_DCHECK(condition) RTC_EAT_STREAM_PARAMETERS(condition)
438 #define RTC_DCHECK_EQ(v1, v2) RTC_EAT_STREAM_PARAMETERS_OP(Eq, v1, v2)
439 #define RTC_DCHECK_NE(v1, v2) RTC_EAT_STREAM_PARAMETERS_OP(Ne, v1, v2)
440 #define RTC_DCHECK_LE(v1, v2) RTC_EAT_STREAM_PARAMETERS_OP(Le, v1, v2)
441 #define RTC_DCHECK_LT(v1, v2) RTC_EAT_STREAM_PARAMETERS_OP(Lt, v1, v2)
442 #define RTC_DCHECK_GE(v1, v2) RTC_EAT_STREAM_PARAMETERS_OP(Ge, v1, v2)
443 #define RTC_DCHECK_GT(v1, v2) RTC_EAT_STREAM_PARAMETERS_OP(Gt, v1, v2)
444 #endif
445 
446 #define RTC_UNREACHABLE_CODE_HIT false
447 #define RTC_NOTREACHED() RTC_DCHECK(RTC_UNREACHABLE_CODE_HIT)
448 
449 // Kills the process with an error message. Never returns. Use when you wish to
450 // assert that a point in the code is never reached.
451 #define RTC_CHECK_NOTREACHED()                         \
452   do {                                                 \
453     ::rtc::webrtc_checks_impl::UnreachableCodeReached( \
454         RTC_UNREACHABLE_FILE_AND_LINE_CALL_ARGS);      \
455   } while (0)
456 
457 #define RTC_FATAL()                                                  \
458   ::rtc::webrtc_checks_impl::FatalLogCall<false>(__FILE__, __LINE__, \
459                                                  "FATAL()") &        \
460       ::rtc::webrtc_checks_impl::LogStreamer<>()
461 
462 // Performs the integer division a/b and returns the result. CHECKs that the
463 // remainder is zero.
464 template <typename T>
CheckedDivExact(T a,T b)465 inline T CheckedDivExact(T a, T b) {
466   RTC_CHECK_EQ(a % b, 0) << a << " is not evenly divisible by " << b;
467   return a / b;
468 }
469 
470 }  // namespace rtc
471 
472 #else  // __cplusplus not defined
473 // C version. Lacks many features compared to the C++ version, but usage
474 // guidelines are the same.
475 
476 #define RTC_CHECK(condition)                                                 \
477   do {                                                                       \
478     if (!(condition)) {                                                      \
479       rtc_FatalMessage(__FILE__, __LINE__,                                   \
480                        RTC_CHECK_EVAL_MESSAGE("CHECK failed: " #condition)); \
481     }                                                                        \
482   } while (0)
483 
484 #define RTC_CHECK_EQ(a, b) RTC_CHECK((a) == (b))
485 #define RTC_CHECK_NE(a, b) RTC_CHECK((a) != (b))
486 #define RTC_CHECK_LE(a, b) RTC_CHECK((a) <= (b))
487 #define RTC_CHECK_LT(a, b) RTC_CHECK((a) < (b))
488 #define RTC_CHECK_GE(a, b) RTC_CHECK((a) >= (b))
489 #define RTC_CHECK_GT(a, b) RTC_CHECK((a) > (b))
490 
491 #define RTC_DCHECK(condition)                                                 \
492   do {                                                                        \
493     if (RTC_DCHECK_IS_ON && !(condition)) {                                   \
494       rtc_FatalMessage(__FILE__, __LINE__,                                    \
495                        RTC_CHECK_EVAL_MESSAGE("DCHECK failed: " #condition)); \
496     }                                                                         \
497   } while (0)
498 
499 #define RTC_DCHECK_EQ(a, b) RTC_DCHECK((a) == (b))
500 #define RTC_DCHECK_NE(a, b) RTC_DCHECK((a) != (b))
501 #define RTC_DCHECK_LE(a, b) RTC_DCHECK((a) <= (b))
502 #define RTC_DCHECK_LT(a, b) RTC_DCHECK((a) < (b))
503 #define RTC_DCHECK_GE(a, b) RTC_DCHECK((a) >= (b))
504 #define RTC_DCHECK_GT(a, b) RTC_DCHECK((a) > (b))
505 
506 #endif  // __cplusplus
507 
508 #endif  // RTC_BASE_CHECKS_H_
509