xref: /aosp_15_r20/system/libbase/include/android-base/logging.h (revision 8f0ba417480079999ba552f1087ae592091b9d02)
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  // Most devices filter out VERBOSE logs by default, run
31  // `adb shell setprop log.tag.<TAG> V` to see them in adb logcat.
32  //
33  // To log the result of a failed function and include the string
34  // representation of `errno` at the end:
35  //
36  //   PLOG(ERROR) << "Write failed";
37  //
38  // The output will be something like `Write failed: I/O error`.
39  // Remember this as 'P' as in perror(3).
40  //
41  // To output your own types, simply implement operator<< as normal.
42  //
43  // By default, output goes to logcat on Android and stderr on the host.
44  // A process can use `SetLogger` to decide where all logging goes.
45  // Implementations are provided for logcat, stderr, and dmesg.
46  //
47  // By default, the process' name is used as the log tag.
48  // Code can choose a specific log tag by defining LOG_TAG
49  // before including this header.
50  
51  // This header also provides assertions:
52  //
53  //   CHECK(must_be_true);
54  //   CHECK_EQ(a, b) << z_is_interesting_too;
55  
56  // NOTE: For Windows, you must include logging.h after windows.h to allow the
57  // following code to suppress the evil ERROR macro:
58  #ifdef _WIN32
59  // windows.h includes wingdi.h which defines an evil macro ERROR.
60  #ifdef ERROR
61  #undef ERROR
62  #endif
63  #endif
64  
65  #include <functional>
66  #include <memory>
67  #include <ostream>
68  
69  #include "android-base/errno_restorer.h"
70  #include "android-base/macros.h"
71  
72  // Note: DO NOT USE DIRECTLY. Use LOG_TAG instead.
73  #ifdef _LOG_TAG_INTERNAL
74  #error "_LOG_TAG_INTERNAL must not be defined"
75  #endif
76  #ifdef LOG_TAG
77  #define _LOG_TAG_INTERNAL LOG_TAG
78  #else
79  #define _LOG_TAG_INTERNAL nullptr
80  #endif
81  
82  namespace android {
83  namespace base {
84  
85  enum LogSeverity {
86    VERBOSE,
87    DEBUG,
88    INFO,
89    WARNING,
90    ERROR,
91    FATAL_WITHOUT_ABORT,  // For loggability tests, this is considered identical to FATAL.
92    FATAL,
93  };
94  
95  enum LogId {
96    DEFAULT,
97    MAIN,
98    SYSTEM,
99    RADIO,
100    CRASH,
101  };
102  
103  using LogFunction = std::function<void(LogId /*log_buffer_id*/,
104                                         LogSeverity /*severity*/,
105                                         const char* /*tag*/,
106                                         const char* /*file*/,
107                                         unsigned int /*line*/,
108                                         const char* /*message*/)>;
109  using AbortFunction = std::function<void(const char* /*abort_message*/)>;
110  
111  // Loggers for use with InitLogging/SetLogger.
112  
113  // Log to the kernel log (dmesg).
114  // Note that you'll likely need to inherit a /dev/kmsg fd from init.
115  // Add `file /dev/kmsg w` to your .rc file.
116  // You'll also need to `allow <your_domain> kmsg_device:chr_file w_file_perms;`
117  // in `system/sepolocy/private/<your_domain>.te`.
118  void KernelLogger(LogId log_buffer_id, LogSeverity severity, const char* tag, const char* file, unsigned int line, const char* message);
119  // Log to stderr in the full logcat format (with pid/tid/time/tag details).
120  void StderrLogger(LogId log_buffer_id, LogSeverity severity, const char* tag, const char* file, unsigned int line, const char* message);
121  // Log just the message to stdout/stderr (without pid/tid/time/tag details).
122  // The choice of stdout versus stderr is based on the severity.
123  // Errors are also prefixed by the program name (as with err(3)/error(3)).
124  // Useful for replacing printf(3)/perror(3)/err(3)/error(3) in command-line tools.
125  void StdioLogger(LogId log_buffer_id, LogSeverity severity, const char* tag, const char* file, unsigned int line, const char* message);
126  // Returns a log function which tees (outputs to both) log streams.
127  // For example: InitLogging(argv, TeeLogger(&StderrLogger, LogdLogger()))
128  LogFunction TeeLogger(LogFunction&& l1, LogFunction&& l2);
129  
130  void DefaultAborter(const char* abort_message);
131  
132  void SetDefaultTag(const std::string& tag);
133  
134  // The LogdLogger sends chunks of up to ~4000 bytes at a time to logd.  It does not prevent other
135  // threads from writing to logd between sending each chunk, so other threads may interleave their
136  // messages.  If preventing interleaving is required, then a custom logger that takes a lock before
137  // calling this logger should be provided.
138  class LogdLogger {
139   public:
140    explicit LogdLogger(LogId default_log_id = android::base::MAIN);
141  
142    void operator()(LogId, LogSeverity, const char* tag, const char* file,
143                    unsigned int line, const char* message);
144  
145   private:
146    LogId default_log_id_;
147  };
148  
149  // Configure logging based on ANDROID_LOG_TAGS environment variable.
150  // We need to parse a string that looks like
151  //
152  //      *:v jdwp:d dalvikvm:d dalvikvm-gc:i dalvikvmi:i
153  //
154  // The tag (or '*' for the global level) comes first, followed by a colon and a
155  // letter indicating the minimum priority level we're expected to log.  This can
156  // be used to reveal or conceal logs with specific tags.
157  #ifdef __ANDROID__
158  #define INIT_LOGGING_DEFAULT_LOGGER LogdLogger()
159  #else
160  #define INIT_LOGGING_DEFAULT_LOGGER StderrLogger
161  #endif
162  void InitLogging(char* argv[],
163                   LogFunction&& logger = INIT_LOGGING_DEFAULT_LOGGER,
164                   AbortFunction&& aborter = DefaultAborter);
165  #undef INIT_LOGGING_DEFAULT_LOGGER
166  
167  // Replace the current logger and return the old one.
168  LogFunction SetLogger(LogFunction&& logger);
169  
170  // Replace the current aborter and return the old one.
171  AbortFunction SetAborter(AbortFunction&& aborter);
172  
173  // A helper macro that produces an expression that accepts both a qualified name and an
174  // unqualified name for a LogSeverity, and returns a LogSeverity value.
175  // Note: DO NOT USE DIRECTLY. This is an implementation detail.
176  #define SEVERITY_LAMBDA(severity) ([&]() {    \
177    using ::android::base::VERBOSE;             \
178    using ::android::base::DEBUG;               \
179    using ::android::base::INFO;                \
180    using ::android::base::WARNING;             \
181    using ::android::base::ERROR;               \
182    using ::android::base::FATAL_WITHOUT_ABORT; \
183    using ::android::base::FATAL;               \
184    return (severity); }())
185  
186  #ifdef __clang_analyzer__
187  // Clang's static analyzer does not see the conditional statement inside
188  // LogMessage's destructor that will abort on FATAL severity.
189  #define ABORT_AFTER_LOG_FATAL for (;; abort())
190  
191  struct LogAbortAfterFullExpr {
~LogAbortAfterFullExprLogAbortAfterFullExpr192    ~LogAbortAfterFullExpr() __attribute__((noreturn)) { abort(); }
193    explicit operator bool() const { return false; }
194  };
195  // Provides an expression that evaluates to the truthiness of `x`, automatically
196  // aborting if `c` is true.
197  #define ABORT_AFTER_LOG_EXPR_IF(c, x) (((c) && ::android::base::LogAbortAfterFullExpr()) || (x))
198  // Note to the static analyzer that we always execute FATAL logs in practice.
199  #define MUST_LOG_MESSAGE(severity) (SEVERITY_LAMBDA(severity) == ::android::base::FATAL)
200  #else
201  #define ABORT_AFTER_LOG_FATAL
202  #define ABORT_AFTER_LOG_EXPR_IF(c, x) (x)
203  #define MUST_LOG_MESSAGE(severity) false
204  #endif
205  #define ABORT_AFTER_LOG_FATAL_EXPR(x) ABORT_AFTER_LOG_EXPR_IF(true, x)
206  
207  // Defines whether the given severity will be logged or silently swallowed.
208  #define WOULD_LOG(severity)                                                              \
209    (UNLIKELY(::android::base::ShouldLog(SEVERITY_LAMBDA(severity), _LOG_TAG_INTERNAL)) || \
210     MUST_LOG_MESSAGE(severity))
211  
212  // Get an ostream that can be used for logging at the given severity and to the default
213  // destination.
214  //
215  // Note that this does not save and restore errno.
216  #define LOG_STREAM(severity)                                                                    \
217    ::android::base::LogMessage(__FILE__, __LINE__, SEVERITY_LAMBDA(severity), _LOG_TAG_INTERNAL, \
218                                -1)                                                               \
219        .stream()
220  
221  // Logs a message to logcat on Android otherwise to stderr. If the severity is
222  // FATAL it also causes an abort. For example:
223  //
224  //     LOG(FATAL) << "We didn't expect to reach here";
225  #define LOG(severity) LOGGING_PREAMBLE(severity) && LOG_STREAM(severity)
226  
227  // Conditionally logs a message based on a specified severity level and a boolean condition.
228  // Logs to logcat on Android, or to stderr on host. See also LOG(severity) above.
229  //
230  // The message will only be logged if:
231  // 1. The provided 'cond' evaluates to true.
232  // 2. The 'severity' level is enabled for the current log tag (as determined by the logging
233  // configuration).
234  //
235  // Usage:
236  //
237  //   LOG_IF(INFO, some_condition) << "This message will be logged if 'some_condition' is true" <<
238  //       " and INFO level is enabled.";
239  //
240  // @param severity The severity level of the log message (e.g., VERBOSE, DEBUG, INFO, WARNING,
241  //      ERROR, FATAL).
242  // @param cond The boolean condition that determines whether to log the message.
243  #define LOG_IF(severity, cond) \
244    if (UNLIKELY(cond) && WOULD_LOG(severity)) LOG(severity)
245  
246  // Checks if we want to log something, and sets up appropriate RAII objects if
247  // so.
248  // Note: DO NOT USE DIRECTLY. This is an implementation detail.
249  #define LOGGING_PREAMBLE(severity)                                                         \
250    (WOULD_LOG(severity) &&                                                                  \
251     ABORT_AFTER_LOG_EXPR_IF((SEVERITY_LAMBDA(severity)) == ::android::base::FATAL, true) && \
252     ::android::base::ErrnoRestorer())
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)                                                           \
257    LOGGING_PREAMBLE(severity) &&                                                  \
258        ::android::base::LogMessage(__FILE__, __LINE__, SEVERITY_LAMBDA(severity), \
259                                    _LOG_TAG_INTERNAL, errno)                      \
260            .stream()
261  
262  // Marker that code is yet to be implemented.
263  #define UNIMPLEMENTED(level) \
264    LOG(level) << __PRETTY_FUNCTION__ << " unimplemented "
265  
266  // Check whether condition x holds and LOG(FATAL) if not. The value of the
267  // expression x is only evaluated once. Extra logging can be appended using <<
268  // after. For example:
269  //
270  //     CHECK(false == true) results in a log message of
271  //       "Check failed: false == true".
272  #define CHECK(x)                                                                                 \
273    LIKELY((x)) || ABORT_AFTER_LOG_FATAL_EXPR(false) ||                                            \
274        ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::FATAL, _LOG_TAG_INTERNAL, \
275                                    -1)                                                            \
276                .stream()                                                                          \
277            << "Check failed: " #x << " "
278  
279  // clang-format off
280  // Helper for CHECK_xx(x,y) macros.
281  #define CHECK_OP(LHS, RHS, OP)                                                                   \
282    for (auto _values = ::android::base::MakeEagerEvaluator(LHS, RHS);                             \
283         UNLIKELY(!(_values.lhs.v OP _values.rhs.v));                                              \
284         /* empty */)                                                                              \
285    ABORT_AFTER_LOG_FATAL                                                                          \
286    ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::FATAL, _LOG_TAG_INTERNAL, -1) \
287            .stream()                                                                              \
288        << "Check failed: " << #LHS << " " << #OP << " " << #RHS << " (" #LHS "="                  \
289        << ::android::base::LogNullGuard<decltype(_values.lhs.v)>::Guard(_values.lhs.v)            \
290        << ", " #RHS "="                                                                           \
291        << ::android::base::LogNullGuard<decltype(_values.rhs.v)>::Guard(_values.rhs.v)            \
292        << ") "
293  // clang-format on
294  
295  // Check whether a condition holds between x and y, LOG(FATAL) if not. The value
296  // of the expressions x and y is evaluated once. Extra logging can be appended
297  // using << after. For example:
298  //
299  //     CHECK_NE(0 == 1, false) results in
300  //       "Check failed: false != false (0==1=false, false=false) ".
301  #define CHECK_EQ(x, y) CHECK_OP(x, y, == )
302  #define CHECK_NE(x, y) CHECK_OP(x, y, != )
303  #define CHECK_LE(x, y) CHECK_OP(x, y, <= )
304  #define CHECK_LT(x, y) CHECK_OP(x, y, < )
305  #define CHECK_GE(x, y) CHECK_OP(x, y, >= )
306  #define CHECK_GT(x, y) CHECK_OP(x, y, > )
307  
308  // clang-format off
309  // Helper for CHECK_STRxx(s1,s2) macros.
310  #define CHECK_STROP(s1, s2, sense)                                             \
311    while (UNLIKELY((strcmp(s1, s2) == 0) != (sense)))                           \
312      ABORT_AFTER_LOG_FATAL                                                      \
313      ::android::base::LogMessage(__FILE__, __LINE__,  ::android::base::FATAL,   \
314                                   _LOG_TAG_INTERNAL, -1)                        \
315          .stream()                                                              \
316          << "Check failed: " << "\"" << (s1) << "\""                            \
317          << ((sense) ? " == " : " != ") << "\"" << (s2) << "\""
318  // clang-format on
319  
320  // Check for string (const char*) equality between s1 and s2, LOG(FATAL) if not.
321  #define CHECK_STREQ(s1, s2) CHECK_STROP(s1, s2, true)
322  #define CHECK_STRNE(s1, s2) CHECK_STROP(s1, s2, false)
323  
324  // Perform the pthread function call(args), LOG(FATAL) on error.
325  #define CHECK_PTHREAD_CALL(call, args, what)                           \
326    do {                                                                 \
327      int rc = call args;                                                \
328      if (rc != 0) {                                                     \
329        errno = rc;                                                      \
330        ABORT_AFTER_LOG_FATAL                                            \
331        PLOG(FATAL) << #call << " failed for " << (what);                \
332      }                                                                  \
333    } while (false)
334  
335  // DCHECKs are debug variants of CHECKs only enabled in debug builds. Generally
336  // CHECK should be used unless profiling identifies a CHECK as being in
337  // performance critical code.
338  #if defined(NDEBUG) && !defined(__clang_analyzer__)
339  static constexpr bool kEnableDChecks = false;
340  #else
341  static constexpr bool kEnableDChecks = true;
342  #endif
343  
344  #define DCHECK(x) \
345    if (::android::base::kEnableDChecks) CHECK(x)
346  #define DCHECK_EQ(x, y) \
347    if (::android::base::kEnableDChecks) CHECK_EQ(x, y)
348  #define DCHECK_NE(x, y) \
349    if (::android::base::kEnableDChecks) CHECK_NE(x, y)
350  #define DCHECK_LE(x, y) \
351    if (::android::base::kEnableDChecks) CHECK_LE(x, y)
352  #define DCHECK_LT(x, y) \
353    if (::android::base::kEnableDChecks) CHECK_LT(x, y)
354  #define DCHECK_GE(x, y) \
355    if (::android::base::kEnableDChecks) CHECK_GE(x, y)
356  #define DCHECK_GT(x, y) \
357    if (::android::base::kEnableDChecks) CHECK_GT(x, y)
358  #define DCHECK_STREQ(s1, s2) \
359    if (::android::base::kEnableDChecks) CHECK_STREQ(s1, s2)
360  #define DCHECK_STRNE(s1, s2) \
361    if (::android::base::kEnableDChecks) CHECK_STRNE(s1, s2)
362  
363  namespace log_detail {
364  
365  // Temporary storage for a single eagerly evaluated check expression operand.
366  template <typename T> struct Storage {
StorageStorage367    template <typename U> explicit constexpr Storage(U&& u) : v(std::forward<U>(u)) {}
368    explicit Storage(const Storage& t) = delete;
369    explicit Storage(Storage&& t) = delete;
370    T v;
371  };
372  
373  // Partial specialization for smart pointers to avoid copying.
374  template <typename T> struct Storage<std::unique_ptr<T>> {
375    explicit constexpr Storage(const std::unique_ptr<T>& ptr) : v(ptr.get()) {}
376    const T* v;
377  };
378  template <typename T> struct Storage<std::shared_ptr<T>> {
379    explicit constexpr Storage(const std::shared_ptr<T>& ptr) : v(ptr.get()) {}
380    const T* v;
381  };
382  
383  // Type trait that checks if a type is a (potentially const) char pointer.
384  template <typename T> struct IsCharPointer {
385    using Pointee = std::remove_cv_t<std::remove_pointer_t<T>>;
386    static constexpr bool value = std::is_pointer_v<T> &&
387        (std::is_same_v<Pointee, char> || std::is_same_v<Pointee, signed char> ||
388         std::is_same_v<Pointee, unsigned char>);
389  };
390  
391  // Counterpart to Storage that depends on both operands. This is used to prevent
392  // char pointers being treated as strings in the log output - they might point
393  // to buffers of unprintable binary data.
394  template <typename LHS, typename RHS> struct StorageTypes {
395    static constexpr bool voidptr = IsCharPointer<LHS>::value && IsCharPointer<RHS>::value;
396    using LHSType = std::conditional_t<voidptr, const void*, LHS>;
397    using RHSType = std::conditional_t<voidptr, const void*, RHS>;
398  };
399  
400  // Temporary class created to evaluate the LHS and RHS, used with
401  // MakeEagerEvaluator to infer the types of LHS and RHS.
402  template <typename LHS, typename RHS>
403  struct EagerEvaluator {
404    template <typename A, typename B> constexpr EagerEvaluator(A&& l, B&& r)
405        : lhs(std::forward<A>(l)), rhs(std::forward<B>(r)) {}
406    const Storage<typename StorageTypes<LHS, RHS>::LHSType> lhs;
407    const Storage<typename StorageTypes<LHS, RHS>::RHSType> rhs;
408  };
409  
410  }  // namespace log_detail
411  
412  // Converts std::nullptr_t and null char pointers to the string "null"
413  // when writing the failure message.
414  template <typename T> struct LogNullGuard {
415    static const T& Guard(const T& v) { return v; }
416  };
417  template <> struct LogNullGuard<std::nullptr_t> {
418    static const char* Guard(const std::nullptr_t&) { return "(null)"; }
419  };
420  template <> struct LogNullGuard<char*> {
421    static const char* Guard(const char* v) { return v ? v : "(null)"; }
422  };
423  template <> struct LogNullGuard<const char*> {
424    static const char* Guard(const char* v) { return v ? v : "(null)"; }
425  };
426  
427  // Helper function for CHECK_xx.
428  template <typename LHS, typename RHS>
429  constexpr auto MakeEagerEvaluator(LHS&& lhs, RHS&& rhs) {
430    return log_detail::EagerEvaluator<std::decay_t<LHS>, std::decay_t<RHS>>(
431        std::forward<LHS>(lhs), std::forward<RHS>(rhs));
432  }
433  
434  // Data for the log message, not stored in LogMessage to avoid increasing the
435  // stack size.
436  class LogMessageData;
437  
438  // A LogMessage is a temporarily scoped object used by LOG and the unlikely part
439  // of a CHECK. The destructor will abort if the severity is FATAL.
440  class LogMessage {
441   public:
442    // LogId has been deprecated, but this constructor must exist for prebuilts.
443    LogMessage(const char* file, unsigned int line, LogId, LogSeverity severity, const char* tag,
444               int error);
445    LogMessage(const char* file, unsigned int line, LogSeverity severity, const char* tag, int error);
446  
447    ~LogMessage();
448  
449    // Returns the stream associated with the message, the LogMessage performs
450    // output when it goes out of scope.
451    std::ostream& stream();
452  
453    // The routine that performs the actual logging.
454    static void LogLine(const char* file, unsigned int line, LogSeverity severity, const char* tag,
455                        const char* msg);
456  
457   private:
458    const std::unique_ptr<LogMessageData> data_;
459  
460    DISALLOW_COPY_AND_ASSIGN(LogMessage);
461  };
462  
463  // Get the minimum severity level for logging.
464  LogSeverity GetMinimumLogSeverity();
465  
466  // Set the minimum severity level for logging, returning the old severity.
467  LogSeverity SetMinimumLogSeverity(LogSeverity new_severity);
468  
469  // Return whether or not a log message with the associated tag should be logged.
470  bool ShouldLog(LogSeverity severity, const char* tag);
471  
472  // Allows to temporarily change the minimum severity level for logging.
473  class ScopedLogSeverity {
474   public:
475    explicit ScopedLogSeverity(LogSeverity level);
476    ~ScopedLogSeverity();
477  
478   private:
479    LogSeverity old_;
480  };
481  
482  }  // namespace base
483  }  // namespace android
484  
485  namespace std {  // NOLINT(cert-dcl58-cpp)
486  
487  // Emit a warning of ostream<< with std::string*. The intention was most likely to print *string.
488  //
489  // Note: for this to work, we need to have this in a namespace.
490  // Note: using a pragma because "-Wgcc-compat" (included in "-Weverything") complains about
491  //       diagnose_if.
492  // Note: to print the pointer, use "<< static_cast<const void*>(string_pointer)" instead.
493  // Note: a not-recommended alternative is to let Clang ignore the warning by adding
494  //       -Wno-user-defined-warnings to CPPFLAGS.
495  #pragma clang diagnostic push
496  #pragma clang diagnostic ignored "-Wgcc-compat"
497  #define OSTREAM_STRING_POINTER_USAGE_WARNING \
498      __attribute__((diagnose_if(true, "Unexpected logging of string pointer", "warning")))
499  inline OSTREAM_STRING_POINTER_USAGE_WARNING
500  std::ostream& operator<<(std::ostream& stream, const std::string* string_pointer) {
501    return stream << static_cast<const void*>(string_pointer);
502  }
503  #pragma clang diagnostic pop
504  
505  }  // namespace std
506