• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2022 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 // -----------------------------------------------------------------------------
16 // File: log/internal/conditions.h
17 // -----------------------------------------------------------------------------
18 //
19 // This file contains implementation of conditional log statements, like LOG_IF
20 // including all the ABSL_LOG_INTERNAL_..._CONDITION_... macros and
21 // various condition classes like LogEveryNState.
22 
23 #ifndef ABSL_LOG_INTERNAL_CONDITIONS_H_
24 #define ABSL_LOG_INTERNAL_CONDITIONS_H_
25 
26 #if defined(_WIN32) || defined(__hexagon__)
27 #include <cstdlib>
28 #else
29 #include <unistd.h>
30 #endif
31 #include <stdlib.h>
32 
33 #include <atomic>
34 #include <cstdint>
35 
36 #include "absl/base/attributes.h"
37 #include "absl/base/config.h"
38 #include "absl/log/internal/voidify.h"
39 
40 // `ABSL_LOG_INTERNAL_CONDITION` prefixes another macro that expands to a
41 // temporary `LogMessage` instantiation followed by zero or more streamed
42 // expressions.  This definition is tricky to read correctly.  It evaluates to
43 // either
44 //
45 //   (void)0;
46 //
47 // or
48 //
49 //   ::absl::log_internal::Voidify() &&
50 //       ::absl::log_internal::LogMessage(...) << "the user's message";
51 //
52 // If the condition is evaluable at compile time, as is often the case, it
53 // compiles away to just one side or the other.
54 //
55 // Although this is not used anywhere a statement (e.g. `if`) could not go,
56 // the ternary expression does a better job avoiding spurious diagnostics
57 // (dangling else, missing switch case) and preserving noreturn semantics (e.g.
58 // on `LOG(FATAL)`) without requiring braces.
59 //
60 // The `switch` ensures that this expansion is the begnning of a statement (as
61 // opposed to an expression) and prevents shenanigans like
62 // `AFunction(LOG(INFO))` and `decltype(LOG(INFO))`.  The apparently-redundant
63 // `default` case makes the condition more amenable to Clang dataflow analysis.
64 #define ABSL_LOG_INTERNAL_STATELESS_CONDITION(condition) \
65   switch (0)                                             \
66   case 0:                                                \
67   default:                                               \
68     !(condition) ? (void)0 : ::absl::log_internal::Voidify()&&
69 
70 // `ABSL_LOG_INTERNAL_STATEFUL_CONDITION` applies a condition like
71 // `ABSL_LOG_INTERNAL_CONDITION` but adds to that a series of variable
72 // declarations, including a local static object which stores the state needed
73 // to implement the stateful macros like `LOG_EVERY_N`.
74 //
75 // `for`-loops are used to declare scoped variables without braces (to permit
76 // streaming into the macro's expansion) and without the dangling-`else`
77 // problems/diagnostics that come with `if`.
78 //
79 // Two more variables are declared in separate `for`-loops:
80 //
81 // * `COUNTER` implements a streamable token whose value when streamed is the
82 //   number of times execution has passed through the macro.
83 // * A boolean flag is used to prevent any of the `for`-loops from ever actually
84 //   looping.
85 #define ABSL_LOG_INTERNAL_STATEFUL_CONDITION(condition)             \
86   for (bool absl_log_internal_stateful_condition_do_log(condition); \
87        absl_log_internal_stateful_condition_do_log;                 \
88        absl_log_internal_stateful_condition_do_log = false)         \
89   ABSL_LOG_INTERNAL_STATEFUL_CONDITION_IMPL
90 #define ABSL_LOG_INTERNAL_STATEFUL_CONDITION_IMPL(kind, ...)              \
91   for (static ::absl::log_internal::Log##kind##State                      \
92            absl_log_internal_stateful_condition_state;                    \
93        absl_log_internal_stateful_condition_do_log &&                     \
94        absl_log_internal_stateful_condition_state.ShouldLog(__VA_ARGS__); \
95        absl_log_internal_stateful_condition_do_log = false)               \
96     for (const uint32_t COUNTER ABSL_ATTRIBUTE_UNUSED =                   \
97              absl_log_internal_stateful_condition_state.counter();        \
98          absl_log_internal_stateful_condition_do_log;                     \
99          absl_log_internal_stateful_condition_do_log = false)
100 
101 // `ABSL_LOG_INTERNAL_CONDITION_*` serve to combine any conditions from the
102 // macro (e.g. `LOG_IF` or `VLOG`) with inherent conditions (e.g.
103 // `ABSL_MIN_LOG_LEVEL`) into a single boolean expression.  We could chain
104 // ternary operators instead, however some versions of Clang sometimes issue
105 // spurious diagnostics after such expressions due to a control flow analysis
106 // bug.
107 #ifdef ABSL_MIN_LOG_LEVEL
108 #define ABSL_LOG_INTERNAL_CONDITION_INFO(type, condition) \
109   ABSL_LOG_INTERNAL_##type##_CONDITION(                   \
110       (condition) && ::absl::LogSeverity::kInfo >=        \
111                          static_cast<::absl::LogSeverity>(ABSL_MIN_LOG_LEVEL))
112 #define ABSL_LOG_INTERNAL_CONDITION_WARNING(type, condition) \
113   ABSL_LOG_INTERNAL_##type##_CONDITION(                      \
114       (condition) && ::absl::LogSeverity::kWarning >=        \
115                          static_cast<::absl::LogSeverity>(ABSL_MIN_LOG_LEVEL))
116 #define ABSL_LOG_INTERNAL_CONDITION_ERROR(type, condition) \
117   ABSL_LOG_INTERNAL_##type##_CONDITION(                    \
118       (condition) && ::absl::LogSeverity::kError >=        \
119                          static_cast<::absl::LogSeverity>(ABSL_MIN_LOG_LEVEL))
120 // NOTE: Use ternary operators instead of short-circuiting to mitigate
121 // https://bugs.llvm.org/show_bug.cgi?id=51928.
122 #define ABSL_LOG_INTERNAL_CONDITION_FATAL(type, condition)                 \
123   ABSL_LOG_INTERNAL_##type##_CONDITION(                                    \
124       ((condition)                                                         \
125            ? (::absl::LogSeverity::kFatal >=                               \
126                       static_cast<::absl::LogSeverity>(ABSL_MIN_LOG_LEVEL) \
127                   ? true                                                   \
128                   : (::absl::log_internal::AbortQuietly(), false))         \
129            : false))
130 // NOTE: Use ternary operators instead of short-circuiting to mitigate
131 // https://bugs.llvm.org/show_bug.cgi?id=51928.
132 #define ABSL_LOG_INTERNAL_CONDITION_QFATAL(type, condition)                \
133   ABSL_LOG_INTERNAL_##type##_CONDITION(                                    \
134       ((condition)                                                         \
135            ? (::absl::LogSeverity::kFatal >=                               \
136                       static_cast<::absl::LogSeverity>(ABSL_MIN_LOG_LEVEL) \
137                   ? true                                                   \
138                   : (::absl::log_internal::ExitQuietly(), false))          \
139            : false))
140 
141 #define ABSL_LOG_INTERNAL_CONDITION_LEVEL(severity)                    \
142   for (int log_internal_severity_loop = 1; log_internal_severity_loop; \
143        log_internal_severity_loop = 0)                                 \
144     for (const absl::LogSeverity log_internal_severity =               \
145              ::absl::NormalizeLogSeverity(severity);                   \
146          log_internal_severity_loop; log_internal_severity_loop = 0)   \
147   ABSL_LOG_INTERNAL_CONDITION_LEVEL_IMPL
148 #define ABSL_LOG_INTERNAL_CONDITION_LEVEL_IMPL(type, condition)    \
149   ABSL_LOG_INTERNAL_##type##_CONDITION(                            \
150       (condition) &&                                               \
151       (log_internal_severity >=                                    \
152            static_cast<::absl::LogSeverity>(ABSL_MIN_LOG_LEVEL) || \
153        (log_internal_severity == ::absl::LogSeverity::kFatal &&    \
154         (::absl::log_internal::AbortQuietly(), false))))
155 #else  // ndef ABSL_MIN_LOG_LEVEL
156 #define ABSL_LOG_INTERNAL_CONDITION_INFO(type, condition) \
157   ABSL_LOG_INTERNAL_##type##_CONDITION(condition)
158 #define ABSL_LOG_INTERNAL_CONDITION_WARNING(type, condition) \
159   ABSL_LOG_INTERNAL_##type##_CONDITION(condition)
160 #define ABSL_LOG_INTERNAL_CONDITION_ERROR(type, condition) \
161   ABSL_LOG_INTERNAL_##type##_CONDITION(condition)
162 #define ABSL_LOG_INTERNAL_CONDITION_FATAL(type, condition) \
163   ABSL_LOG_INTERNAL_##type##_CONDITION(condition)
164 #define ABSL_LOG_INTERNAL_CONDITION_QFATAL(type, condition) \
165   ABSL_LOG_INTERNAL_##type##_CONDITION(condition)
166 #define ABSL_LOG_INTERNAL_CONDITION_LEVEL(severity)                    \
167   for (int log_internal_severity_loop = 1; log_internal_severity_loop; \
168        log_internal_severity_loop = 0)                                 \
169     for (const absl::LogSeverity log_internal_severity =               \
170              ::absl::NormalizeLogSeverity(severity);                   \
171          log_internal_severity_loop; log_internal_severity_loop = 0)   \
172   ABSL_LOG_INTERNAL_CONDITION_LEVEL_IMPL
173 #define ABSL_LOG_INTERNAL_CONDITION_LEVEL_IMPL(type, condition) \
174   ABSL_LOG_INTERNAL_##type##_CONDITION(condition)
175 #endif  // ndef ABSL_MIN_LOG_LEVEL
176 
177 namespace absl {
178 ABSL_NAMESPACE_BEGIN
179 namespace log_internal {
180 
181 // Stateful condition class name should be "Log" + name + "State".
182 class LogEveryNState final {
183  public:
184   bool ShouldLog(int n);
counter()185   uint32_t counter() { return counter_.load(std::memory_order_relaxed); }
186 
187  private:
188   std::atomic<uint32_t> counter_{0};
189 };
190 
191 class LogFirstNState final {
192  public:
193   bool ShouldLog(int n);
counter()194   uint32_t counter() { return counter_.load(std::memory_order_relaxed); }
195 
196  private:
197   std::atomic<uint32_t> counter_{0};
198 };
199 
200 class LogEveryPow2State final {
201  public:
202   bool ShouldLog();
counter()203   uint32_t counter() { return counter_.load(std::memory_order_relaxed); }
204 
205  private:
206   std::atomic<uint32_t> counter_{0};
207 };
208 
209 class LogEveryNSecState final {
210  public:
211   bool ShouldLog(double seconds);
counter()212   uint32_t counter() { return counter_.load(std::memory_order_relaxed); }
213 
214  private:
215   std::atomic<uint32_t> counter_{0};
216   // Cycle count according to CycleClock that we should next log at.
217   std::atomic<int64_t> next_log_time_cycles_{0};
218 };
219 
220 // Helper routines to abort the application quietly
221 
AbortQuietly()222 ABSL_ATTRIBUTE_NORETURN inline void AbortQuietly() { abort(); }
ExitQuietly()223 ABSL_ATTRIBUTE_NORETURN inline void ExitQuietly() { _exit(1); }
224 }  // namespace log_internal
225 ABSL_NAMESPACE_END
226 }  // namespace absl
227 
228 #endif  // ABSL_LOG_INTERNAL_CONDITIONS_H_
229