1 /*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #ifndef ANDROID_BASE_LOGGING_H
18 #define ANDROID_BASE_LOGGING_H
19
20 // NOTE: For Windows, you must include logging.h after windows.h to allow the
21 // following code to suppress the evil ERROR macro:
22 #ifdef _WIN32
23 // windows.h includes wingdi.h which defines an evil macro ERROR.
24 #ifdef ERROR
25 #undef ERROR
26 #endif
27 #endif
28
29 #include <functional>
30 #include <memory>
31 #include <ostream>
32
33 #include "android-base/macros.h"
34
35 namespace android {
36 namespace base {
37
38 enum LogSeverity {
39 VERBOSE,
40 DEBUG,
41 INFO,
42 WARNING,
43 ERROR,
44 FATAL,
45 };
46
47 enum LogId {
48 DEFAULT,
49 MAIN,
50 SYSTEM,
51 };
52
53 typedef std::function<void(LogId, LogSeverity, const char*, const char*,
54 unsigned int, const char*)> LogFunction;
55
56 extern void StderrLogger(LogId, LogSeverity, const char*, const char*,
57 unsigned int, const char*);
58
59 #ifdef __ANDROID__
60 // We expose this even though it is the default because a user that wants to
61 // override the default log buffer will have to construct this themselves.
62 class LogdLogger {
63 public:
64 explicit LogdLogger(LogId default_log_id = android::base::MAIN);
65
66 void operator()(LogId, LogSeverity, const char* tag, const char* file,
67 unsigned int line, const char* message);
68
69 private:
70 LogId default_log_id_;
71 };
72 #endif
73
74 // Configure logging based on ANDROID_LOG_TAGS environment variable.
75 // We need to parse a string that looks like
76 //
77 // *:v jdwp:d dalvikvm:d dalvikvm-gc:i dalvikvmi:i
78 //
79 // The tag (or '*' for the global level) comes first, followed by a colon and a
80 // letter indicating the minimum priority level we're expected to log. This can
81 // be used to reveal or conceal logs with specific tags.
82 extern void InitLogging(char* argv[], LogFunction&& logger);
83
84 // Configures logging using the default logger (logd for the device, stderr for
85 // the host).
86 extern void InitLogging(char* argv[]);
87
88 // Replace the current logger.
89 extern void SetLogger(LogFunction&& logger);
90
91 // Get the minimum severity level for logging.
92 extern LogSeverity GetMinimumLogSeverity();
93
94 class ErrnoRestorer {
95 public:
ErrnoRestorer()96 ErrnoRestorer()
97 : saved_errno_(errno) {
98 }
99
~ErrnoRestorer()100 ~ErrnoRestorer() {
101 errno = saved_errno_;
102 }
103
104 // Allow this object to be used as part of && operation.
105 operator bool() const {
106 return true;
107 }
108
109 private:
110 const int saved_errno_;
111
112 DISALLOW_COPY_AND_ASSIGN(ErrnoRestorer);
113 };
114
115 // Logs a message to logcat on Android otherwise to stderr. If the severity is
116 // FATAL it also causes an abort. For example:
117 //
118 // LOG(FATAL) << "We didn't expect to reach here";
119 #define LOG(severity) LOG_TO(DEFAULT, severity)
120
121 // Logs a message to logcat with the specified log ID on Android otherwise to
122 // stderr. If the severity is FATAL it also causes an abort.
123 // Use an if-else statement instead of just an if statement here. So if there is a
124 // else statement after LOG() macro, it won't bind to the if statement in the macro.
125 // do-while(0) statement doesn't work here. Because we need to support << operator
126 // following the macro, like "LOG(DEBUG) << xxx;".
127 #define LOG_TO(dest, severity) \
128 UNLIKELY(::android::base::severity >= ::android::base::GetMinimumLogSeverity()) && \
129 ::android::base::ErrnoRestorer() && \
130 ::android::base::LogMessage(__FILE__, __LINE__, \
131 ::android::base::dest, \
132 ::android::base::severity, -1).stream()
133
134 // A variant of LOG that also logs the current errno value. To be used when
135 // library calls fail.
136 #define PLOG(severity) PLOG_TO(DEFAULT, severity)
137
138 // Behaves like PLOG, but logs to the specified log ID.
139 #define PLOG_TO(dest, severity) \
140 UNLIKELY(::android::base::severity >= ::android::base::GetMinimumLogSeverity()) && \
141 ::android::base::ErrnoRestorer() && \
142 ::android::base::LogMessage(__FILE__, __LINE__, \
143 ::android::base::dest, \
144 ::android::base::severity, errno).stream()
145
146 // Marker that code is yet to be implemented.
147 #define UNIMPLEMENTED(level) \
148 LOG(level) << __PRETTY_FUNCTION__ << " unimplemented "
149
150 // Check whether condition x holds and LOG(FATAL) if not. The value of the
151 // expression x is only evaluated once. Extra logging can be appended using <<
152 // after. For example:
153 //
154 // CHECK(false == true) results in a log message of
155 // "Check failed: false == true".
156 #define CHECK(x) \
157 LIKELY((x)) || \
158 ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT, \
159 ::android::base::FATAL, -1).stream() \
160 << "Check failed: " #x << " "
161
162 // Helper for CHECK_xx(x,y) macros.
163 #define CHECK_OP(LHS, RHS, OP) \
164 for (auto _values = ::android::base::MakeEagerEvaluator(LHS, RHS); \
165 UNLIKELY(!(_values.lhs OP _values.rhs)); \
166 /* empty */) \
167 ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT, \
168 ::android::base::FATAL, -1).stream() \
169 << "Check failed: " << #LHS << " " << #OP << " " << #RHS \
170 << " (" #LHS "=" << _values.lhs << ", " #RHS "=" << _values.rhs << ") "
171
172 // Check whether a condition holds between x and y, LOG(FATAL) if not. The value
173 // of the expressions x and y is evaluated once. Extra logging can be appended
174 // using << after. For example:
175 //
176 // CHECK_NE(0 == 1, false) results in
177 // "Check failed: false != false (0==1=false, false=false) ".
178 #define CHECK_EQ(x, y) CHECK_OP(x, y, == )
179 #define CHECK_NE(x, y) CHECK_OP(x, y, != )
180 #define CHECK_LE(x, y) CHECK_OP(x, y, <= )
181 #define CHECK_LT(x, y) CHECK_OP(x, y, < )
182 #define CHECK_GE(x, y) CHECK_OP(x, y, >= )
183 #define CHECK_GT(x, y) CHECK_OP(x, y, > )
184
185 // Helper for CHECK_STRxx(s1,s2) macros.
186 #define CHECK_STROP(s1, s2, sense) \
187 if (LIKELY((strcmp(s1, s2) == 0) == sense)) \
188 ; \
189 else \
190 LOG(FATAL) << "Check failed: " \
191 << "\"" << s1 << "\"" \
192 << (sense ? " == " : " != ") << "\"" << s2 << "\""
193
194 // Check for string (const char*) equality between s1 and s2, LOG(FATAL) if not.
195 #define CHECK_STREQ(s1, s2) CHECK_STROP(s1, s2, true)
196 #define CHECK_STRNE(s1, s2) CHECK_STROP(s1, s2, false)
197
198 // Perform the pthread function call(args), LOG(FATAL) on error.
199 #define CHECK_PTHREAD_CALL(call, args, what) \
200 do { \
201 int rc = call args; \
202 if (rc != 0) { \
203 errno = rc; \
204 PLOG(FATAL) << #call << " failed for " << what; \
205 } \
206 } while (false)
207
208 // CHECK that can be used in a constexpr function. For example:
209 //
210 // constexpr int half(int n) {
211 // return
212 // DCHECK_CONSTEXPR(n >= 0, , 0)
213 // CHECK_CONSTEXPR((n & 1) == 0),
214 // << "Extra debugging output: n = " << n, 0)
215 // n / 2;
216 // }
217 #define CHECK_CONSTEXPR(x, out, dummy) \
218 (UNLIKELY(!(x))) \
219 ? (LOG(FATAL) << "Check failed: " << #x out, dummy) \
220 :
221
222 // DCHECKs are debug variants of CHECKs only enabled in debug builds. Generally
223 // CHECK should be used unless profiling identifies a CHECK as being in
224 // performance critical code.
225 #if defined(NDEBUG)
226 static constexpr bool kEnableDChecks = false;
227 #else
228 static constexpr bool kEnableDChecks = true;
229 #endif
230
231 #define DCHECK(x) \
232 if (::android::base::kEnableDChecks) CHECK(x)
233 #define DCHECK_EQ(x, y) \
234 if (::android::base::kEnableDChecks) CHECK_EQ(x, y)
235 #define DCHECK_NE(x, y) \
236 if (::android::base::kEnableDChecks) CHECK_NE(x, y)
237 #define DCHECK_LE(x, y) \
238 if (::android::base::kEnableDChecks) CHECK_LE(x, y)
239 #define DCHECK_LT(x, y) \
240 if (::android::base::kEnableDChecks) CHECK_LT(x, y)
241 #define DCHECK_GE(x, y) \
242 if (::android::base::kEnableDChecks) CHECK_GE(x, y)
243 #define DCHECK_GT(x, y) \
244 if (::android::base::kEnableDChecks) CHECK_GT(x, y)
245 #define DCHECK_STREQ(s1, s2) \
246 if (::android::base::kEnableDChecks) CHECK_STREQ(s1, s2)
247 #define DCHECK_STRNE(s1, s2) \
248 if (::android::base::kEnableDChecks) CHECK_STRNE(s1, s2)
249 #if defined(NDEBUG)
250 #define DCHECK_CONSTEXPR(x, out, dummy)
251 #else
252 #define DCHECK_CONSTEXPR(x, out, dummy) CHECK_CONSTEXPR(x, out, dummy)
253 #endif
254
255 // Temporary class created to evaluate the LHS and RHS, used with
256 // MakeEagerEvaluator to infer the types of LHS and RHS.
257 template <typename LHS, typename RHS>
258 struct EagerEvaluator {
EagerEvaluatorEagerEvaluator259 EagerEvaluator(LHS l, RHS r) : lhs(l), rhs(r) {
260 }
261 LHS lhs;
262 RHS rhs;
263 };
264
265 // Helper function for CHECK_xx.
266 template <typename LHS, typename RHS>
MakeEagerEvaluator(LHS lhs,RHS rhs)267 static inline EagerEvaluator<LHS, RHS> MakeEagerEvaluator(LHS lhs, RHS rhs) {
268 return EagerEvaluator<LHS, RHS>(lhs, rhs);
269 }
270
271 // Explicitly instantiate EagerEvalue for pointers so that char*s aren't treated
272 // as strings. To compare strings use CHECK_STREQ and CHECK_STRNE. We rely on
273 // signed/unsigned warnings to protect you against combinations not explicitly
274 // listed below.
275 #define EAGER_PTR_EVALUATOR(T1, T2) \
276 template <> \
277 struct EagerEvaluator<T1, T2> { \
278 EagerEvaluator(T1 l, T2 r) \
279 : lhs(reinterpret_cast<const void*>(l)), \
280 rhs(reinterpret_cast<const void*>(r)) { \
281 } \
282 const void* lhs; \
283 const void* rhs; \
284 }
285 EAGER_PTR_EVALUATOR(const char*, const char*);
286 EAGER_PTR_EVALUATOR(const char*, char*);
287 EAGER_PTR_EVALUATOR(char*, const char*);
288 EAGER_PTR_EVALUATOR(char*, char*);
289 EAGER_PTR_EVALUATOR(const unsigned char*, const unsigned char*);
290 EAGER_PTR_EVALUATOR(const unsigned char*, unsigned char*);
291 EAGER_PTR_EVALUATOR(unsigned char*, const unsigned char*);
292 EAGER_PTR_EVALUATOR(unsigned char*, unsigned char*);
293 EAGER_PTR_EVALUATOR(const signed char*, const signed char*);
294 EAGER_PTR_EVALUATOR(const signed char*, signed char*);
295 EAGER_PTR_EVALUATOR(signed char*, const signed char*);
296 EAGER_PTR_EVALUATOR(signed char*, signed char*);
297
298 // Data for the log message, not stored in LogMessage to avoid increasing the
299 // stack size.
300 class LogMessageData;
301
302 // A LogMessage is a temporarily scoped object used by LOG and the unlikely part
303 // of a CHECK. The destructor will abort if the severity is FATAL.
304 class LogMessage {
305 public:
306 LogMessage(const char* file, unsigned int line, LogId id,
307 LogSeverity severity, int error);
308
309 ~LogMessage();
310
311 // Returns the stream associated with the message, the LogMessage performs
312 // output when it goes out of scope.
313 std::ostream& stream();
314
315 // The routine that performs the actual logging.
316 static void LogLine(const char* file, unsigned int line, LogId id,
317 LogSeverity severity, const char* msg);
318
319 private:
320 const std::unique_ptr<LogMessageData> data_;
321
322 DISALLOW_COPY_AND_ASSIGN(LogMessage);
323 };
324
325 // Allows to temporarily change the minimum severity level for logging.
326 class ScopedLogSeverity {
327 public:
328 explicit ScopedLogSeverity(LogSeverity level);
329 ~ScopedLogSeverity();
330
331 private:
332 LogSeverity old_;
333 };
334
335 } // namespace base
336 } // namespace android
337
338 #endif // ANDROID_BASE_LOGGING_H
339