• 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/errno_restorer.h"
68  #include "android-base/macros.h"
69  
70  // Note: DO NOT USE DIRECTLY. Use LOG_TAG instead.
71  #ifdef _LOG_TAG_INTERNAL
72  #error "_LOG_TAG_INTERNAL must not be defined"
73  #endif
74  #ifdef LOG_TAG
75  #define _LOG_TAG_INTERNAL LOG_TAG
76  #else
77  #define _LOG_TAG_INTERNAL nullptr
78  #endif
79  
80  namespace android {
81  namespace base {
82  
83  enum LogSeverity {
84    VERBOSE,
85    DEBUG,
86    INFO,
87    WARNING,
88    ERROR,
89    FATAL_WITHOUT_ABORT,  // For loggability tests, this is considered identical to FATAL.
90    FATAL,
91  };
92  
93  enum LogId {
94    DEFAULT,
95    MAIN,
96    SYSTEM,
97    RADIO,
98    CRASH,
99  };
100  
101  using LogFunction = std::function<void(LogId, LogSeverity, const char*, const char*,
102                                         unsigned int, const char*)>;
103  using AbortFunction = std::function<void(const char*)>;
104  
105  // Loggers for use with InitLogging/SetLogger.
106  
107  // Log to the kernel log (dmesg).
108  void KernelLogger(LogId, LogSeverity, const char*, const char*, unsigned int, const char*);
109  // Log to stderr in the full logcat format (with pid/tid/time/tag details).
110  void StderrLogger(LogId, LogSeverity, const char*, const char*, unsigned int, const char*);
111  // Log just the message to stdout/stderr (without pid/tid/time/tag details).
112  // The choice of stdout versus stderr is based on the severity.
113  // Errors are also prefixed by the program name (as with err(3)/error(3)).
114  // Useful for replacing printf(3)/perror(3)/err(3)/error(3) in command-line tools.
115  void StdioLogger(LogId, LogSeverity, const char*, const char*, unsigned int, const char*);
116  
117  void DefaultAborter(const char* abort_message);
118  
119  void SetDefaultTag(const std::string& tag);
120  
121  // The LogdLogger sends chunks of up to ~4000 bytes at a time to logd.  It does not prevent other
122  // threads from writing to logd between sending each chunk, so other threads may interleave their
123  // messages.  If preventing interleaving is required, then a custom logger that takes a lock before
124  // calling this logger should be provided.
125  class LogdLogger {
126   public:
127    explicit LogdLogger(LogId default_log_id = android::base::MAIN);
128  
129    void operator()(LogId, LogSeverity, const char* tag, const char* file,
130                    unsigned int line, const char* message);
131  
132   private:
133    LogId default_log_id_;
134  };
135  
136  // Configure logging based on ANDROID_LOG_TAGS environment variable.
137  // We need to parse a string that looks like
138  //
139  //      *:v jdwp:d dalvikvm:d dalvikvm-gc:i dalvikvmi:i
140  //
141  // The tag (or '*' for the global level) comes first, followed by a colon and a
142  // letter indicating the minimum priority level we're expected to log.  This can
143  // be used to reveal or conceal logs with specific tags.
144  #ifdef __ANDROID__
145  #define INIT_LOGGING_DEFAULT_LOGGER LogdLogger()
146  #else
147  #define INIT_LOGGING_DEFAULT_LOGGER StderrLogger
148  #endif
149  void InitLogging(char* argv[],
150                   LogFunction&& logger = INIT_LOGGING_DEFAULT_LOGGER,
151                   AbortFunction&& aborter = DefaultAborter);
152  #undef INIT_LOGGING_DEFAULT_LOGGER
153  
154  // Replace the current logger.
155  void SetLogger(LogFunction&& logger);
156  
157  // Replace the current aborter.
158  void SetAborter(AbortFunction&& aborter);
159  
160  // A helper macro that produces an expression that accepts both a qualified name and an
161  // unqualified name for a LogSeverity, and returns a LogSeverity value.
162  // Note: DO NOT USE DIRECTLY. This is an implementation detail.
163  #define SEVERITY_LAMBDA(severity) ([&]() {    \
164    using ::android::base::VERBOSE;             \
165    using ::android::base::DEBUG;               \
166    using ::android::base::INFO;                \
167    using ::android::base::WARNING;             \
168    using ::android::base::ERROR;               \
169    using ::android::base::FATAL_WITHOUT_ABORT; \
170    using ::android::base::FATAL;               \
171    return (severity); }())
172  
173  #ifdef __clang_analyzer__
174  // Clang's static analyzer does not see the conditional statement inside
175  // LogMessage's destructor that will abort on FATAL severity.
176  #define ABORT_AFTER_LOG_FATAL for (;; abort())
177  
178  struct LogAbortAfterFullExpr {
~LogAbortAfterFullExprLogAbortAfterFullExpr179    ~LogAbortAfterFullExpr() __attribute__((noreturn)) { abort(); }
180    explicit operator bool() const { return false; }
181  };
182  // Provides an expression that evaluates to the truthiness of `x`, automatically
183  // aborting if `c` is true.
184  #define ABORT_AFTER_LOG_EXPR_IF(c, x) (((c) && ::android::base::LogAbortAfterFullExpr()) || (x))
185  // Note to the static analyzer that we always execute FATAL logs in practice.
186  #define MUST_LOG_MESSAGE(severity) (SEVERITY_LAMBDA(severity) == ::android::base::FATAL)
187  #else
188  #define ABORT_AFTER_LOG_FATAL
189  #define ABORT_AFTER_LOG_EXPR_IF(c, x) (x)
190  #define MUST_LOG_MESSAGE(severity) false
191  #endif
192  #define ABORT_AFTER_LOG_FATAL_EXPR(x) ABORT_AFTER_LOG_EXPR_IF(true, x)
193  
194  // Defines whether the given severity will be logged or silently swallowed.
195  #define WOULD_LOG(severity)                                                              \
196    (UNLIKELY(::android::base::ShouldLog(SEVERITY_LAMBDA(severity), _LOG_TAG_INTERNAL)) || \
197     MUST_LOG_MESSAGE(severity))
198  
199  // Get an ostream that can be used for logging at the given severity and to the default
200  // destination.
201  //
202  // Notes:
203  // 1) This will not check whether the severity is high enough. One should use WOULD_LOG to filter
204  //    usage manually.
205  // 2) This does not save and restore errno.
206  #define LOG_STREAM(severity)                                                                    \
207    ::android::base::LogMessage(__FILE__, __LINE__, SEVERITY_LAMBDA(severity), _LOG_TAG_INTERNAL, \
208                                -1)                                                               \
209        .stream()
210  
211  // Logs a message to logcat on Android otherwise to stderr. If the severity is
212  // FATAL it also causes an abort. For example:
213  //
214  //     LOG(FATAL) << "We didn't expect to reach here";
215  #define LOG(severity) LOGGING_PREAMBLE(severity) && LOG_STREAM(severity)
216  
217  // Checks if we want to log something, and sets up appropriate RAII objects if
218  // so.
219  // Note: DO NOT USE DIRECTLY. This is an implementation detail.
220  #define LOGGING_PREAMBLE(severity)                                                         \
221    (WOULD_LOG(severity) &&                                                                  \
222     ABORT_AFTER_LOG_EXPR_IF((SEVERITY_LAMBDA(severity)) == ::android::base::FATAL, true) && \
223     ::android::base::ErrnoRestorer())
224  
225  // A variant of LOG that also logs the current errno value. To be used when
226  // library calls fail.
227  #define PLOG(severity)                                                           \
228    LOGGING_PREAMBLE(severity) &&                                                  \
229        ::android::base::LogMessage(__FILE__, __LINE__, SEVERITY_LAMBDA(severity), \
230                                    _LOG_TAG_INTERNAL, errno)                      \
231            .stream()
232  
233  // Marker that code is yet to be implemented.
234  #define UNIMPLEMENTED(level) \
235    LOG(level) << __PRETTY_FUNCTION__ << " unimplemented "
236  
237  // Check whether condition x holds and LOG(FATAL) if not. The value of the
238  // expression x is only evaluated once. Extra logging can be appended using <<
239  // after. For example:
240  //
241  //     CHECK(false == true) results in a log message of
242  //       "Check failed: false == true".
243  #define CHECK(x)                                                                                 \
244    LIKELY((x)) || ABORT_AFTER_LOG_FATAL_EXPR(false) ||                                            \
245        ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::FATAL, _LOG_TAG_INTERNAL, \
246                                    -1)                                                            \
247                .stream()                                                                          \
248            << "Check failed: " #x << " "
249  
250  // clang-format off
251  // Helper for CHECK_xx(x,y) macros.
252  #define CHECK_OP(LHS, RHS, OP)                                                                   \
253    for (auto _values = ::android::base::MakeEagerEvaluator(LHS, RHS);                             \
254         UNLIKELY(!(_values.lhs OP _values.rhs));                                                  \
255         /* empty */)                                                                              \
256    ABORT_AFTER_LOG_FATAL                                                                          \
257    ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::FATAL, _LOG_TAG_INTERNAL, -1) \
258            .stream()                                                                              \
259        << "Check failed: " << #LHS << " " << #OP << " " << #RHS << " (" #LHS "=" << _values.lhs   \
260        << ", " #RHS "=" << _values.rhs << ") "
261  // clang-format on
262  
263  // Check whether a condition holds between x and y, LOG(FATAL) if not. The value
264  // of the expressions x and y is evaluated once. Extra logging can be appended
265  // using << after. For example:
266  //
267  //     CHECK_NE(0 == 1, false) results in
268  //       "Check failed: false != false (0==1=false, false=false) ".
269  #define CHECK_EQ(x, y) CHECK_OP(x, y, == )
270  #define CHECK_NE(x, y) CHECK_OP(x, y, != )
271  #define CHECK_LE(x, y) CHECK_OP(x, y, <= )
272  #define CHECK_LT(x, y) CHECK_OP(x, y, < )
273  #define CHECK_GE(x, y) CHECK_OP(x, y, >= )
274  #define CHECK_GT(x, y) CHECK_OP(x, y, > )
275  
276  // clang-format off
277  // Helper for CHECK_STRxx(s1,s2) macros.
278  #define CHECK_STROP(s1, s2, sense)                                             \
279    while (UNLIKELY((strcmp(s1, s2) == 0) != (sense)))                           \
280      ABORT_AFTER_LOG_FATAL                                                      \
281      ::android::base::LogMessage(__FILE__, __LINE__,  ::android::base::FATAL,   \
282                                   _LOG_TAG_INTERNAL, -1)                        \
283          .stream()                                                              \
284          << "Check failed: " << "\"" << (s1) << "\""                            \
285          << ((sense) ? " == " : " != ") << "\"" << (s2) << "\""
286  // clang-format on
287  
288  // Check for string (const char*) equality between s1 and s2, LOG(FATAL) if not.
289  #define CHECK_STREQ(s1, s2) CHECK_STROP(s1, s2, true)
290  #define CHECK_STRNE(s1, s2) CHECK_STROP(s1, s2, false)
291  
292  // Perform the pthread function call(args), LOG(FATAL) on error.
293  #define CHECK_PTHREAD_CALL(call, args, what)                           \
294    do {                                                                 \
295      int rc = call args;                                                \
296      if (rc != 0) {                                                     \
297        errno = rc;                                                      \
298        ABORT_AFTER_LOG_FATAL                                            \
299        PLOG(FATAL) << #call << " failed for " << (what);                \
300      }                                                                  \
301    } while (false)
302  
303  // CHECK that can be used in a constexpr function. For example:
304  //
305  //    constexpr int half(int n) {
306  //      return
307  //          DCHECK_CONSTEXPR(n >= 0, , 0)
308  //          CHECK_CONSTEXPR((n & 1) == 0),
309  //              << "Extra debugging output: n = " << n, 0)
310  //          n / 2;
311  //    }
312  #define CHECK_CONSTEXPR(x, out, dummy)                                     \
313    (UNLIKELY(!(x)))                                                         \
314        ? (LOG(FATAL) << "Check failed: " << #x out, dummy) \
315        :
316  
317  // DCHECKs are debug variants of CHECKs only enabled in debug builds. Generally
318  // CHECK should be used unless profiling identifies a CHECK as being in
319  // performance critical code.
320  #if defined(NDEBUG) && !defined(__clang_analyzer__)
321  static constexpr bool kEnableDChecks = false;
322  #else
323  static constexpr bool kEnableDChecks = true;
324  #endif
325  
326  #define DCHECK(x) \
327    if (::android::base::kEnableDChecks) CHECK(x)
328  #define DCHECK_EQ(x, y) \
329    if (::android::base::kEnableDChecks) CHECK_EQ(x, y)
330  #define DCHECK_NE(x, y) \
331    if (::android::base::kEnableDChecks) CHECK_NE(x, y)
332  #define DCHECK_LE(x, y) \
333    if (::android::base::kEnableDChecks) CHECK_LE(x, y)
334  #define DCHECK_LT(x, y) \
335    if (::android::base::kEnableDChecks) CHECK_LT(x, y)
336  #define DCHECK_GE(x, y) \
337    if (::android::base::kEnableDChecks) CHECK_GE(x, y)
338  #define DCHECK_GT(x, y) \
339    if (::android::base::kEnableDChecks) CHECK_GT(x, y)
340  #define DCHECK_STREQ(s1, s2) \
341    if (::android::base::kEnableDChecks) CHECK_STREQ(s1, s2)
342  #define DCHECK_STRNE(s1, s2) \
343    if (::android::base::kEnableDChecks) CHECK_STRNE(s1, s2)
344  #if defined(NDEBUG) && !defined(__clang_analyzer__)
345  #define DCHECK_CONSTEXPR(x, out, dummy)
346  #else
347  #define DCHECK_CONSTEXPR(x, out, dummy) CHECK_CONSTEXPR(x, out, dummy)
348  #endif
349  
350  // Temporary class created to evaluate the LHS and RHS, used with
351  // MakeEagerEvaluator to infer the types of LHS and RHS.
352  template <typename LHS, typename RHS>
353  struct EagerEvaluator {
EagerEvaluatorEagerEvaluator354    constexpr EagerEvaluator(LHS l, RHS r) : lhs(l), rhs(r) {
355    }
356    LHS lhs;
357    RHS rhs;
358  };
359  
360  // Helper function for CHECK_xx.
361  template <typename LHS, typename RHS>
MakeEagerEvaluator(LHS lhs,RHS rhs)362  constexpr EagerEvaluator<LHS, RHS> MakeEagerEvaluator(LHS lhs, RHS rhs) {
363    return EagerEvaluator<LHS, RHS>(lhs, rhs);
364  }
365  
366  // Explicitly instantiate EagerEvalue for pointers so that char*s aren't treated
367  // as strings. To compare strings use CHECK_STREQ and CHECK_STRNE. We rely on
368  // signed/unsigned warnings to protect you against combinations not explicitly
369  // listed below.
370  #define EAGER_PTR_EVALUATOR(T1, T2)               \
371    template <>                                     \
372    struct EagerEvaluator<T1, T2> {                 \
373      EagerEvaluator(T1 l, T2 r)                    \
374          : lhs(reinterpret_cast<const void*>(l)),  \
375            rhs(reinterpret_cast<const void*>(r)) { \
376      }                                             \
377      const void* lhs;                              \
378      const void* rhs;                              \
379    }
380  EAGER_PTR_EVALUATOR(const char*, const char*);
381  EAGER_PTR_EVALUATOR(const char*, char*);
382  EAGER_PTR_EVALUATOR(char*, const char*);
383  EAGER_PTR_EVALUATOR(char*, char*);
384  EAGER_PTR_EVALUATOR(const unsigned char*, const unsigned char*);
385  EAGER_PTR_EVALUATOR(const unsigned char*, unsigned char*);
386  EAGER_PTR_EVALUATOR(unsigned char*, const unsigned char*);
387  EAGER_PTR_EVALUATOR(unsigned char*, unsigned char*);
388  EAGER_PTR_EVALUATOR(const signed char*, const signed char*);
389  EAGER_PTR_EVALUATOR(const signed char*, signed char*);
390  EAGER_PTR_EVALUATOR(signed char*, const signed char*);
391  EAGER_PTR_EVALUATOR(signed char*, signed char*);
392  
393  // Data for the log message, not stored in LogMessage to avoid increasing the
394  // stack size.
395  class LogMessageData;
396  
397  // A LogMessage is a temporarily scoped object used by LOG and the unlikely part
398  // of a CHECK. The destructor will abort if the severity is FATAL.
399  class LogMessage {
400   public:
401    // LogId has been deprecated, but this constructor must exist for prebuilts.
402    LogMessage(const char* file, unsigned int line, LogId, LogSeverity severity, const char* tag,
403               int error);
404    LogMessage(const char* file, unsigned int line, LogSeverity severity, const char* tag, int error);
405  
406    ~LogMessage();
407  
408    // Returns the stream associated with the message, the LogMessage performs
409    // output when it goes out of scope.
410    std::ostream& stream();
411  
412    // The routine that performs the actual logging.
413    static void LogLine(const char* file, unsigned int line, LogSeverity severity, const char* tag,
414                        const char* msg);
415  
416   private:
417    const std::unique_ptr<LogMessageData> data_;
418  
419    DISALLOW_COPY_AND_ASSIGN(LogMessage);
420  };
421  
422  // Get the minimum severity level for logging.
423  LogSeverity GetMinimumLogSeverity();
424  
425  // Set the minimum severity level for logging, returning the old severity.
426  LogSeverity SetMinimumLogSeverity(LogSeverity new_severity);
427  
428  // Return whether or not a log message with the associated tag should be logged.
429  bool ShouldLog(LogSeverity severity, const char* tag);
430  
431  // Allows to temporarily change the minimum severity level for logging.
432  class ScopedLogSeverity {
433   public:
434    explicit ScopedLogSeverity(LogSeverity level);
435    ~ScopedLogSeverity();
436  
437   private:
438    LogSeverity old_;
439  };
440  
441  }  // namespace base
442  }  // namespace android
443  
444  namespace std {  // NOLINT(cert-dcl58-cpp)
445  
446  // Emit a warning of ostream<< with std::string*. The intention was most likely to print *string.
447  //
448  // Note: for this to work, we need to have this in a namespace.
449  // Note: using a pragma because "-Wgcc-compat" (included in "-Weverything") complains about
450  //       diagnose_if.
451  // Note: to print the pointer, use "<< static_cast<const void*>(string_pointer)" instead.
452  // Note: a not-recommended alternative is to let Clang ignore the warning by adding
453  //       -Wno-user-defined-warnings to CPPFLAGS.
454  #pragma clang diagnostic push
455  #pragma clang diagnostic ignored "-Wgcc-compat"
456  #define OSTREAM_STRING_POINTER_USAGE_WARNING \
457      __attribute__((diagnose_if(true, "Unexpected logging of string pointer", "warning")))
458  inline OSTREAM_STRING_POINTER_USAGE_WARNING
459  std::ostream& operator<<(std::ostream& stream, const std::string* string_pointer) {
460    return stream << static_cast<const void*>(string_pointer);
461  }
462  #pragma clang diagnostic pop
463  
464  }  // namespace std
465