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