• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #pragma once
18 
19 //
20 // Google-style C++ logging.
21 //
22 
23 // This header provides a C++ stream interface to logging.
24 //
25 // To log:
26 //
27 //   LOG(INFO) << "Some text; " << some_value;
28 //
29 // Replace `INFO` with any severity from `enum LogSeverity`.
30 //
31 // To log the result of a failed function and include the string
32 // representation of `errno` at the end:
33 //
34 //   PLOG(ERROR) << "Write failed";
35 //
36 // The output will be something like `Write failed: I/O error`.
37 // Remember this as 'P' as in perror(3).
38 //
39 // To output your own types, simply implement operator<< as normal.
40 //
41 // By default, output goes to logcat on Android and stderr on the host.
42 // A process can use `SetLogger` to decide where all logging goes.
43 // Implementations are provided for logcat, stderr, and dmesg.
44 //
45 // By default, the process' name is used as the log tag.
46 // Code can choose a specific log tag by defining LOG_TAG
47 // before including this header.
48 
49 // This header also provides assertions:
50 //
51 //   CHECK(must_be_true);
52 //   CHECK_EQ(a, b) << z_is_interesting_too;
53 
54 // NOTE: For Windows, you must include logging.h after windows.h to allow the
55 // following code to suppress the evil ERROR macro:
56 #ifdef _WIN32
57 // windows.h includes wingdi.h which defines an evil macro ERROR.
58 #ifdef ERROR
59 #undef ERROR
60 #endif
61 #endif
62 
63 #include <functional>
64 #include <memory>
65 #include <ostream>
66 
67 #include "android-base/macros.h"
68 
69 // Note: DO NOT USE DIRECTLY. Use LOG_TAG instead.
70 #ifdef _LOG_TAG_INTERNAL
71 #error "_LOG_TAG_INTERNAL must not be defined"
72 #endif
73 #ifdef LOG_TAG
74 #define _LOG_TAG_INTERNAL LOG_TAG
75 #else
76 #define _LOG_TAG_INTERNAL nullptr
77 #endif
78 
79 namespace android {
80 namespace base {
81 
82 enum LogSeverity {
83   VERBOSE,
84   DEBUG,
85   INFO,
86   WARNING,
87   ERROR,
88   FATAL_WITHOUT_ABORT,
89   FATAL,
90 };
91 
92 enum LogId {
93   DEFAULT,
94   MAIN,
95   SYSTEM,
96 };
97 
98 using LogFunction = std::function<void(LogId, LogSeverity, const char*, const char*,
99                                        unsigned int, const char*)>;
100 using AbortFunction = std::function<void(const char*)>;
101 
102 // Loggers for use with InitLogging/SetLogger.
103 
104 // Log to the kernel log (dmesg).
105 void KernelLogger(LogId, LogSeverity, const char*, const char*, unsigned int, const char*);
106 // Log to stderr in the full logcat format (with pid/tid/time/tag details).
107 void StderrLogger(LogId, LogSeverity, const char*, const char*, unsigned int, const char*);
108 // Log just the message to stdout/stderr (without pid/tid/time/tag details).
109 // The choice of stdout versus stderr is based on the severity.
110 // Errors are also prefixed by the program name (as with err(3)/error(3)).
111 // Useful for replacing printf(3)/perror(3)/err(3)/error(3) in command-line tools.
112 void StdioLogger(LogId, LogSeverity, const char*, const char*, unsigned int, const char*);
113 
114 void DefaultAborter(const char* abort_message);
115 
116 std::string GetDefaultTag();
117 void SetDefaultTag(const std::string& tag);
118 
119 #ifdef __ANDROID__
120 // We expose this even though it is the default because a user that wants to
121 // override the default log buffer will have to construct this themselves.
122 class LogdLogger {
123  public:
124   explicit LogdLogger(LogId default_log_id = android::base::MAIN);
125 
126   void operator()(LogId, LogSeverity, const char* tag, const char* file,
127                   unsigned int line, const char* message);
128 
129  private:
130   LogId default_log_id_;
131 };
132 #endif
133 
134 // Configure logging based on ANDROID_LOG_TAGS environment variable.
135 // We need to parse a string that looks like
136 //
137 //      *:v jdwp:d dalvikvm:d dalvikvm-gc:i dalvikvmi:i
138 //
139 // The tag (or '*' for the global level) comes first, followed by a colon and a
140 // letter indicating the minimum priority level we're expected to log.  This can
141 // be used to reveal or conceal logs with specific tags.
142 #ifdef __ANDROID__
143 #define INIT_LOGGING_DEFAULT_LOGGER LogdLogger()
144 #else
145 #define INIT_LOGGING_DEFAULT_LOGGER StderrLogger
146 #endif
147 void InitLogging(char* argv[],
148                  LogFunction&& logger = INIT_LOGGING_DEFAULT_LOGGER,
149                  AbortFunction&& aborter = DefaultAborter);
150 #undef INIT_LOGGING_DEFAULT_LOGGER
151 
152 // Replace the current logger.
153 void SetLogger(LogFunction&& logger);
154 
155 // Replace the current aborter.
156 void SetAborter(AbortFunction&& aborter);
157 
158 class ErrnoRestorer {
159  public:
ErrnoRestorer()160   ErrnoRestorer()
161       : saved_errno_(errno) {
162   }
163 
~ErrnoRestorer()164   ~ErrnoRestorer() {
165     errno = saved_errno_;
166   }
167 
168   // Allow this object to be used as part of && operation.
169   operator bool() const {
170     return true;
171   }
172 
173  private:
174   const int saved_errno_;
175 
176   DISALLOW_COPY_AND_ASSIGN(ErrnoRestorer);
177 };
178 
179 // A helper macro that produces an expression that accepts both a qualified name and an
180 // unqualified name for a LogSeverity, and returns a LogSeverity value.
181 // Note: DO NOT USE DIRECTLY. This is an implementation detail.
182 #define SEVERITY_LAMBDA(severity) ([&]() {    \
183   using ::android::base::VERBOSE;             \
184   using ::android::base::DEBUG;               \
185   using ::android::base::INFO;                \
186   using ::android::base::WARNING;             \
187   using ::android::base::ERROR;               \
188   using ::android::base::FATAL_WITHOUT_ABORT; \
189   using ::android::base::FATAL;               \
190   return (severity); }())
191 
192 #ifdef __clang_analyzer__
193 // Clang's static analyzer does not see the conditional statement inside
194 // LogMessage's destructor that will abort on FATAL severity.
195 #define ABORT_AFTER_LOG_FATAL for (;; abort())
196 
197 struct LogAbortAfterFullExpr {
~LogAbortAfterFullExprLogAbortAfterFullExpr198   ~LogAbortAfterFullExpr() __attribute__((noreturn)) { abort(); }
199   explicit operator bool() const { return false; }
200 };
201 // Provides an expression that evaluates to the truthiness of `x`, automatically
202 // aborting if `c` is true.
203 #define ABORT_AFTER_LOG_EXPR_IF(c, x) (((c) && ::android::base::LogAbortAfterFullExpr()) || (x))
204 // Note to the static analyzer that we always execute FATAL logs in practice.
205 #define MUST_LOG_MESSAGE(severity) (SEVERITY_LAMBDA(severity) == ::android::base::FATAL)
206 #else
207 #define ABORT_AFTER_LOG_FATAL
208 #define ABORT_AFTER_LOG_EXPR_IF(c, x) (x)
209 #define MUST_LOG_MESSAGE(severity) false
210 #endif
211 #define ABORT_AFTER_LOG_FATAL_EXPR(x) ABORT_AFTER_LOG_EXPR_IF(true, x)
212 
213 // Defines whether the given severity will be logged or silently swallowed.
214 #define WOULD_LOG(severity) \
215   (UNLIKELY((SEVERITY_LAMBDA(severity)) >= ::android::base::GetMinimumLogSeverity()) || \
216    MUST_LOG_MESSAGE(severity))
217 
218 // Get an ostream that can be used for logging at the given severity and to the default
219 // destination.
220 //
221 // Notes:
222 // 1) This will not check whether the severity is high enough. One should use WOULD_LOG to filter
223 //    usage manually.
224 // 2) This does not save and restore errno.
225 #define LOG_STREAM(severity) LOG_STREAM_TO(DEFAULT, severity)
226 
227 // Get an ostream that can be used for logging at the given severity and to the
228 // given destination. The same notes as for LOG_STREAM apply.
229 #define LOG_STREAM_TO(dest, severity)                                           \
230   ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::dest,        \
231                               SEVERITY_LAMBDA(severity), _LOG_TAG_INTERNAL, -1) \
232       .stream()
233 
234 // Logs a message to logcat on Android otherwise to stderr. If the severity is
235 // FATAL it also causes an abort. For example:
236 //
237 //     LOG(FATAL) << "We didn't expect to reach here";
238 #define LOG(severity) LOG_TO(DEFAULT, severity)
239 
240 // Checks if we want to log something, and sets up appropriate RAII objects if
241 // so.
242 // Note: DO NOT USE DIRECTLY. This is an implementation detail.
243 #define LOGGING_PREAMBLE(severity)                                                         \
244   (WOULD_LOG(severity) &&                                                                  \
245    ABORT_AFTER_LOG_EXPR_IF((SEVERITY_LAMBDA(severity)) == ::android::base::FATAL, true) && \
246    ::android::base::ErrnoRestorer())
247 
248 // Logs a message to logcat with the specified log ID on Android otherwise to
249 // stderr. If the severity is FATAL it also causes an abort.
250 // Use an expression here so we can support the << operator following the macro,
251 // like "LOG(DEBUG) << xxx;".
252 #define LOG_TO(dest, severity) LOGGING_PREAMBLE(severity) && LOG_STREAM_TO(dest, severity)
253 
254 // A variant of LOG that also logs the current errno value. To be used when
255 // library calls fail.
256 #define PLOG(severity) PLOG_TO(DEFAULT, severity)
257 
258 // Behaves like PLOG, but logs to the specified log ID.
259 #define PLOG_TO(dest, severity)                                                        \
260   LOGGING_PREAMBLE(severity) &&                                                        \
261       ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::dest,           \
262                                   SEVERITY_LAMBDA(severity), _LOG_TAG_INTERNAL, errno) \
263           .stream()
264 
265 // Marker that code is yet to be implemented.
266 #define UNIMPLEMENTED(level) \
267   LOG(level) << __PRETTY_FUNCTION__ << " unimplemented "
268 
269 // Check whether condition x holds and LOG(FATAL) if not. The value of the
270 // expression x is only evaluated once. Extra logging can be appended using <<
271 // after. For example:
272 //
273 //     CHECK(false == true) results in a log message of
274 //       "Check failed: false == true".
275 #define CHECK(x)                                                                 \
276   LIKELY((x)) || ABORT_AFTER_LOG_FATAL_EXPR(false) ||                            \
277       ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT,  \
278                                   ::android::base::FATAL, _LOG_TAG_INTERNAL, -1) \
279               .stream()                                                          \
280           << "Check failed: " #x << " "
281 
282 // clang-format off
283 // Helper for CHECK_xx(x,y) macros.
284 #define CHECK_OP(LHS, RHS, OP)                                                                 \
285   for (auto _values = ::android::base::MakeEagerEvaluator(LHS, RHS);                           \
286        UNLIKELY(!(_values.lhs OP _values.rhs));                                                \
287        /* empty */)                                                                            \
288   ABORT_AFTER_LOG_FATAL                                                                        \
289   ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT,                    \
290                               ::android::base::FATAL, _LOG_TAG_INTERNAL, -1)                   \
291           .stream()                                                                            \
292       << "Check failed: " << #LHS << " " << #OP << " " << #RHS << " (" #LHS "=" << _values.lhs \
293       << ", " #RHS "=" << _values.rhs << ") "
294 // clang-format on
295 
296 // Check whether a condition holds between x and y, LOG(FATAL) if not. The value
297 // of the expressions x and y is evaluated once. Extra logging can be appended
298 // using << after. For example:
299 //
300 //     CHECK_NE(0 == 1, false) results in
301 //       "Check failed: false != false (0==1=false, false=false) ".
302 #define CHECK_EQ(x, y) CHECK_OP(x, y, == )
303 #define CHECK_NE(x, y) CHECK_OP(x, y, != )
304 #define CHECK_LE(x, y) CHECK_OP(x, y, <= )
305 #define CHECK_LT(x, y) CHECK_OP(x, y, < )
306 #define CHECK_GE(x, y) CHECK_OP(x, y, >= )
307 #define CHECK_GT(x, y) CHECK_OP(x, y, > )
308 
309 // clang-format off
310 // Helper for CHECK_STRxx(s1,s2) macros.
311 #define CHECK_STROP(s1, s2, sense)                                             \
312   while (UNLIKELY((strcmp(s1, s2) == 0) != (sense)))                           \
313     ABORT_AFTER_LOG_FATAL                                                      \
314     ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT,  \
315                                 ::android::base::FATAL, _LOG_TAG_INTERNAL, -1) \
316         .stream()                                                              \
317         << "Check failed: " << "\"" << (s1) << "\""                            \
318         << ((sense) ? " == " : " != ") << "\"" << (s2) << "\""
319 // clang-format on
320 
321 // Check for string (const char*) equality between s1 and s2, LOG(FATAL) if not.
322 #define CHECK_STREQ(s1, s2) CHECK_STROP(s1, s2, true)
323 #define CHECK_STRNE(s1, s2) CHECK_STROP(s1, s2, false)
324 
325 // Perform the pthread function call(args), LOG(FATAL) on error.
326 #define CHECK_PTHREAD_CALL(call, args, what)                           \
327   do {                                                                 \
328     int rc = call args;                                                \
329     if (rc != 0) {                                                     \
330       errno = rc;                                                      \
331       ABORT_AFTER_LOG_FATAL                                            \
332       PLOG(FATAL) << #call << " failed for " << (what);                \
333     }                                                                  \
334   } while (false)
335 
336 // CHECK that can be used in a constexpr function. For example:
337 //
338 //    constexpr int half(int n) {
339 //      return
340 //          DCHECK_CONSTEXPR(n >= 0, , 0)
341 //          CHECK_CONSTEXPR((n & 1) == 0),
342 //              << "Extra debugging output: n = " << n, 0)
343 //          n / 2;
344 //    }
345 #define CHECK_CONSTEXPR(x, out, dummy)                                     \
346   (UNLIKELY(!(x)))                                                         \
347       ? (LOG(FATAL) << "Check failed: " << #x out, dummy) \
348       :
349 
350 // DCHECKs are debug variants of CHECKs only enabled in debug builds. Generally
351 // CHECK should be used unless profiling identifies a CHECK as being in
352 // performance critical code.
353 #if defined(NDEBUG) && !defined(__clang_analyzer__)
354 static constexpr bool kEnableDChecks = false;
355 #else
356 static constexpr bool kEnableDChecks = true;
357 #endif
358 
359 #define DCHECK(x) \
360   if (::android::base::kEnableDChecks) CHECK(x)
361 #define DCHECK_EQ(x, y) \
362   if (::android::base::kEnableDChecks) CHECK_EQ(x, y)
363 #define DCHECK_NE(x, y) \
364   if (::android::base::kEnableDChecks) CHECK_NE(x, y)
365 #define DCHECK_LE(x, y) \
366   if (::android::base::kEnableDChecks) CHECK_LE(x, y)
367 #define DCHECK_LT(x, y) \
368   if (::android::base::kEnableDChecks) CHECK_LT(x, y)
369 #define DCHECK_GE(x, y) \
370   if (::android::base::kEnableDChecks) CHECK_GE(x, y)
371 #define DCHECK_GT(x, y) \
372   if (::android::base::kEnableDChecks) CHECK_GT(x, y)
373 #define DCHECK_STREQ(s1, s2) \
374   if (::android::base::kEnableDChecks) CHECK_STREQ(s1, s2)
375 #define DCHECK_STRNE(s1, s2) \
376   if (::android::base::kEnableDChecks) CHECK_STRNE(s1, s2)
377 #if defined(NDEBUG) && !defined(__clang_analyzer__)
378 #define DCHECK_CONSTEXPR(x, out, dummy)
379 #else
380 #define DCHECK_CONSTEXPR(x, out, dummy) CHECK_CONSTEXPR(x, out, dummy)
381 #endif
382 
383 // Temporary class created to evaluate the LHS and RHS, used with
384 // MakeEagerEvaluator to infer the types of LHS and RHS.
385 template <typename LHS, typename RHS>
386 struct EagerEvaluator {
EagerEvaluatorEagerEvaluator387   constexpr EagerEvaluator(LHS l, RHS r) : lhs(l), rhs(r) {
388   }
389   LHS lhs;
390   RHS rhs;
391 };
392 
393 // Helper function for CHECK_xx.
394 template <typename LHS, typename RHS>
MakeEagerEvaluator(LHS lhs,RHS rhs)395 constexpr EagerEvaluator<LHS, RHS> MakeEagerEvaluator(LHS lhs, RHS rhs) {
396   return EagerEvaluator<LHS, RHS>(lhs, rhs);
397 }
398 
399 // Explicitly instantiate EagerEvalue for pointers so that char*s aren't treated
400 // as strings. To compare strings use CHECK_STREQ and CHECK_STRNE. We rely on
401 // signed/unsigned warnings to protect you against combinations not explicitly
402 // listed below.
403 #define EAGER_PTR_EVALUATOR(T1, T2)               \
404   template <>                                     \
405   struct EagerEvaluator<T1, T2> {                 \
406     EagerEvaluator(T1 l, T2 r)                    \
407         : lhs(reinterpret_cast<const void*>(l)),  \
408           rhs(reinterpret_cast<const void*>(r)) { \
409     }                                             \
410     const void* lhs;                              \
411     const void* rhs;                              \
412   }
413 EAGER_PTR_EVALUATOR(const char*, const char*);
414 EAGER_PTR_EVALUATOR(const char*, char*);
415 EAGER_PTR_EVALUATOR(char*, const char*);
416 EAGER_PTR_EVALUATOR(char*, char*);
417 EAGER_PTR_EVALUATOR(const unsigned char*, const unsigned char*);
418 EAGER_PTR_EVALUATOR(const unsigned char*, unsigned char*);
419 EAGER_PTR_EVALUATOR(unsigned char*, const unsigned char*);
420 EAGER_PTR_EVALUATOR(unsigned char*, unsigned char*);
421 EAGER_PTR_EVALUATOR(const signed char*, const signed char*);
422 EAGER_PTR_EVALUATOR(const signed char*, signed char*);
423 EAGER_PTR_EVALUATOR(signed char*, const signed char*);
424 EAGER_PTR_EVALUATOR(signed char*, signed char*);
425 
426 // Data for the log message, not stored in LogMessage to avoid increasing the
427 // stack size.
428 class LogMessageData;
429 
430 // A LogMessage is a temporarily scoped object used by LOG and the unlikely part
431 // of a CHECK. The destructor will abort if the severity is FATAL.
432 class LogMessage {
433  public:
434   LogMessage(const char* file, unsigned int line, LogId id, LogSeverity severity, const char* tag,
435              int error);
436 
437   ~LogMessage();
438 
439   // Returns the stream associated with the message, the LogMessage performs
440   // output when it goes out of scope.
441   std::ostream& stream();
442 
443   // The routine that performs the actual logging.
444   static void LogLine(const char* file, unsigned int line, LogId id, LogSeverity severity,
445                       const char* tag, const char* msg);
446 
447  private:
448   const std::unique_ptr<LogMessageData> data_;
449 
450   DISALLOW_COPY_AND_ASSIGN(LogMessage);
451 };
452 
453 // Get the minimum severity level for logging.
454 LogSeverity GetMinimumLogSeverity();
455 
456 // Set the minimum severity level for logging, returning the old severity.
457 LogSeverity SetMinimumLogSeverity(LogSeverity new_severity);
458 
459 // Allows to temporarily change the minimum severity level for logging.
460 class ScopedLogSeverity {
461  public:
462   explicit ScopedLogSeverity(LogSeverity level);
463   ~ScopedLogSeverity();
464 
465  private:
466   LogSeverity old_;
467 };
468 
469 }  // namespace base
470 }  // namespace android
471 
472 namespace std {
473 
474 // Emit a warning of ostream<< with std::string*. The intention was most likely to print *string.
475 //
476 // Note: for this to work, we need to have this in a namespace.
477 // Note: lots of ifdef magic to make this work with Clang (platform) vs GCC (windows tools)
478 // Note: using diagnose_if(true) under Clang and nothing under GCC/mingw as there is no common
479 //       attribute support.
480 // Note: using a pragma because "-Wgcc-compat" (included in "-Weverything") complains about
481 //       diagnose_if.
482 // Note: to print the pointer, use "<< static_cast<const void*>(string_pointer)" instead.
483 // Note: a not-recommended alternative is to let Clang ignore the warning by adding
484 //       -Wno-user-defined-warnings to CPPFLAGS.
485 #pragma clang diagnostic push
486 #pragma clang diagnostic ignored "-Wgcc-compat"
487 #define OSTREAM_STRING_POINTER_USAGE_WARNING \
488     __attribute__((diagnose_if(true, "Unexpected logging of string pointer", "warning")))
489 inline std::ostream& operator<<(std::ostream& stream, const std::string* string_pointer)
490     OSTREAM_STRING_POINTER_USAGE_WARNING {
491   return stream << static_cast<const void*>(string_pointer);
492 }
493 #pragma clang diagnostic pop
494 
495 }  // namespace std
496