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 // This header also provides assertions:
     47 //
     48 //   CHECK(must_be_true);
     49 //   CHECK_EQ(a, b) << z_is_interesting_too;
     50 
     51 // NOTE: For Windows, you must include logging.h after windows.h to allow the
     52 // following code to suppress the evil ERROR macro:
     53 #ifdef _WIN32
     54 // windows.h includes wingdi.h which defines an evil macro ERROR.
     55 #ifdef ERROR
     56 #undef ERROR
     57 #endif
     58 #endif
     59 
     60 #include <functional>
     61 #include <memory>
     62 #include <ostream>
     63 
     64 #include "android-base/macros.h"
     65 
     66 namespace android {
     67 namespace base {
     68 
     69 enum LogSeverity {
     70   VERBOSE,
     71   DEBUG,
     72   INFO,
     73   WARNING,
     74   ERROR,
     75   FATAL_WITHOUT_ABORT,
     76   FATAL,
     77 };
     78 
     79 enum LogId {
     80   DEFAULT,
     81   MAIN,
     82   SYSTEM,
     83 };
     84 
     85 using LogFunction = std::function<void(LogId, LogSeverity, const char*, const char*,
     86                                        unsigned int, const char*)>;
     87 using AbortFunction = std::function<void(const char*)>;
     88 
     89 void KernelLogger(LogId, LogSeverity, const char*, const char*, unsigned int, const char*);
     90 void StderrLogger(LogId, LogSeverity, const char*, const char*, unsigned int, const char*);
     91 
     92 void DefaultAborter(const char* abort_message);
     93 
     94 #ifdef __ANDROID__
     95 // We expose this even though it is the default because a user that wants to
     96 // override the default log buffer will have to construct this themselves.
     97 class LogdLogger {
     98  public:
     99   explicit LogdLogger(LogId default_log_id = android::base::MAIN);
    100 
    101   void operator()(LogId, LogSeverity, const char* tag, const char* file,
    102                   unsigned int line, const char* message);
    103 
    104  private:
    105   LogId default_log_id_;
    106 };
    107 #endif
    108 
    109 // Configure logging based on ANDROID_LOG_TAGS environment variable.
    110 // We need to parse a string that looks like
    111 //
    112 //      *:v jdwp:d dalvikvm:d dalvikvm-gc:i dalvikvmi:i
    113 //
    114 // The tag (or '*' for the global level) comes first, followed by a colon and a
    115 // letter indicating the minimum priority level we're expected to log.  This can
    116 // be used to reveal or conceal logs with specific tags.
    117 #ifdef __ANDROID__
    118 #define INIT_LOGGING_DEFAULT_LOGGER LogdLogger()
    119 #else
    120 #define INIT_LOGGING_DEFAULT_LOGGER StderrLogger
    121 #endif
    122 void InitLogging(char* argv[],
    123                  LogFunction&& logger = INIT_LOGGING_DEFAULT_LOGGER,
    124                  AbortFunction&& aborter = DefaultAborter);
    125 #undef INIT_LOGGING_DEFAULT_LOGGER
    126 
    127 // Replace the current logger.
    128 void SetLogger(LogFunction&& logger);
    129 
    130 // Replace the current aborter.
    131 void SetAborter(AbortFunction&& aborter);
    132 
    133 class ErrnoRestorer {
    134  public:
    135   ErrnoRestorer()
    136       : saved_errno_(errno) {
    137   }
    138 
    139   ~ErrnoRestorer() {
    140     errno = saved_errno_;
    141   }
    142 
    143   // Allow this object to be used as part of && operation.
    144   operator bool() const {
    145     return true;
    146   }
    147 
    148  private:
    149   const int saved_errno_;
    150 
    151   DISALLOW_COPY_AND_ASSIGN(ErrnoRestorer);
    152 };
    153 
    154 // A helper macro that produces an expression that accepts both a qualified name and an
    155 // unqualified name for a LogSeverity, and returns a LogSeverity value.
    156 // Note: DO NOT USE DIRECTLY. This is an implementation detail.
    157 #define SEVERITY_LAMBDA(severity) ([&]() {    \
    158   using ::android::base::VERBOSE;             \
    159   using ::android::base::DEBUG;               \
    160   using ::android::base::INFO;                \
    161   using ::android::base::WARNING;             \
    162   using ::android::base::ERROR;               \
    163   using ::android::base::FATAL_WITHOUT_ABORT; \
    164   using ::android::base::FATAL;               \
    165   return (severity); }())
    166 
    167 #ifdef __clang_analyzer__
    168 // Clang's static analyzer does not see the conditional statement inside
    169 // LogMessage's destructor that will abort on FATAL severity.
    170 #define ABORT_AFTER_LOG_FATAL for (;; abort())
    171 
    172 struct LogAbortAfterFullExpr {
    173   ~LogAbortAfterFullExpr() __attribute__((noreturn)) { abort(); }
    174   explicit operator bool() const { return false; }
    175 };
    176 // Provides an expression that evaluates to the truthiness of `x`, automatically
    177 // aborting if `c` is true.
    178 #define ABORT_AFTER_LOG_EXPR_IF(c, x) (((c) && ::android::base::LogAbortAfterFullExpr()) || (x))
    179 // Note to the static analyzer that we always execute FATAL logs in practice.
    180 #define MUST_LOG_MESSAGE(severity) (SEVERITY_LAMBDA(severity) == ::android::base::FATAL)
    181 #else
    182 #define ABORT_AFTER_LOG_FATAL
    183 #define ABORT_AFTER_LOG_EXPR_IF(c, x) (x)
    184 #define MUST_LOG_MESSAGE(severity) false
    185 #endif
    186 #define ABORT_AFTER_LOG_FATAL_EXPR(x) ABORT_AFTER_LOG_EXPR_IF(true, x)
    187 
    188 // Defines whether the given severity will be logged or silently swallowed.
    189 #define WOULD_LOG(severity) \
    190   (UNLIKELY((SEVERITY_LAMBDA(severity)) >= ::android::base::GetMinimumLogSeverity()) || \
    191    MUST_LOG_MESSAGE(severity))
    192 
    193 // Get an ostream that can be used for logging at the given severity and to the default
    194 // destination.
    195 //
    196 // Notes:
    197 // 1) This will not check whether the severity is high enough. One should use WOULD_LOG to filter
    198 //    usage manually.
    199 // 2) This does not save and restore errno.
    200 #define LOG_STREAM(severity) LOG_STREAM_TO(DEFAULT, severity)
    201 
    202 // Get an ostream that can be used for logging at the given severity and to the
    203 // given destination. The same notes as for LOG_STREAM apply.
    204 #define LOG_STREAM_TO(dest, severity)                                   \
    205   ::android::base::LogMessage(__FILE__, __LINE__,                       \
    206                               ::android::base::dest,                    \
    207                               SEVERITY_LAMBDA(severity), -1).stream()
    208 
    209 // Logs a message to logcat on Android otherwise to stderr. If the severity is
    210 // FATAL it also causes an abort. For example:
    211 //
    212 //     LOG(FATAL) << "We didn't expect to reach here";
    213 #define LOG(severity) LOG_TO(DEFAULT, severity)
    214 
    215 // Checks if we want to log something, and sets up appropriate RAII objects if
    216 // so.
    217 // Note: DO NOT USE DIRECTLY. This is an implementation detail.
    218 #define LOGGING_PREAMBLE(severity)                                                         \
    219   (WOULD_LOG(severity) &&                                                                  \
    220    ABORT_AFTER_LOG_EXPR_IF((SEVERITY_LAMBDA(severity)) == ::android::base::FATAL, true) && \
    221    ::android::base::ErrnoRestorer())
    222 
    223 // Logs a message to logcat with the specified log ID on Android otherwise to
    224 // stderr. If the severity is FATAL it also causes an abort.
    225 // Use an expression here so we can support the << operator following the macro,
    226 // like "LOG(DEBUG) << xxx;".
    227 #define LOG_TO(dest, severity) LOGGING_PREAMBLE(severity) && LOG_STREAM_TO(dest, severity)
    228 
    229 // A variant of LOG that also logs the current errno value. To be used when
    230 // library calls fail.
    231 #define PLOG(severity) PLOG_TO(DEFAULT, severity)
    232 
    233 // Behaves like PLOG, but logs to the specified log ID.
    234 #define PLOG_TO(dest, severity)                                              \
    235   LOGGING_PREAMBLE(severity) &&                                              \
    236       ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::dest, \
    237                                   SEVERITY_LAMBDA(severity), errno)          \
    238           .stream()
    239 
    240 // Marker that code is yet to be implemented.
    241 #define UNIMPLEMENTED(level) \
    242   LOG(level) << __PRETTY_FUNCTION__ << " unimplemented "
    243 
    244 // Check whether condition x holds and LOG(FATAL) if not. The value of the
    245 // expression x is only evaluated once. Extra logging can be appended using <<
    246 // after. For example:
    247 //
    248 //     CHECK(false == true) results in a log message of
    249 //       "Check failed: false == true".
    250 #define CHECK(x)                                                                \
    251   LIKELY((x)) || ABORT_AFTER_LOG_FATAL_EXPR(false) ||                           \
    252       ::android::base::LogMessage(                                              \
    253           __FILE__, __LINE__, ::android::base::DEFAULT, ::android::base::FATAL, \
    254           -1).stream()                                                          \
    255           << "Check failed: " #x << " "
    256 
    257 // Helper for CHECK_xx(x,y) macros.
    258 #define CHECK_OP(LHS, RHS, OP)                                              \
    259   for (auto _values = ::android::base::MakeEagerEvaluator(LHS, RHS);        \
    260        UNLIKELY(!(_values.lhs OP _values.rhs));                             \
    261        /* empty */)                                                         \
    262   ABORT_AFTER_LOG_FATAL                                                     \
    263   ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT, \
    264                               ::android::base::FATAL, -1).stream()          \
    265       << "Check failed: " << #LHS << " " << #OP << " " << #RHS              \
    266       << " (" #LHS "=" << _values.lhs << ", " #RHS "=" << _values.rhs << ") "
    267 
    268 // Check whether a condition holds between x and y, LOG(FATAL) if not. The value
    269 // of the expressions x and y is evaluated once. Extra logging can be appended
    270 // using << after. For example:
    271 //
    272 //     CHECK_NE(0 == 1, false) results in
    273 //       "Check failed: false != false (0==1=false, false=false) ".
    274 #define CHECK_EQ(x, y) CHECK_OP(x, y, == )
    275 #define CHECK_NE(x, y) CHECK_OP(x, y, != )
    276 #define CHECK_LE(x, y) CHECK_OP(x, y, <= )
    277 #define CHECK_LT(x, y) CHECK_OP(x, y, < )
    278 #define CHECK_GE(x, y) CHECK_OP(x, y, >= )
    279 #define CHECK_GT(x, y) CHECK_OP(x, y, > )
    280 
    281 // Helper for CHECK_STRxx(s1,s2) macros.
    282 #define CHECK_STROP(s1, s2, sense)                                             \
    283   while (UNLIKELY((strcmp(s1, s2) == 0) != (sense)))                           \
    284     ABORT_AFTER_LOG_FATAL                                                      \
    285     ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT,  \
    286                                 ::android::base::FATAL, -1).stream()           \
    287         << "Check failed: " << "\"" << (s1) << "\""                            \
    288         << ((sense) ? " == " : " != ") << "\"" << (s2) << "\""
    289 
    290 // Check for string (const char*) equality between s1 and s2, LOG(FATAL) if not.
    291 #define CHECK_STREQ(s1, s2) CHECK_STROP(s1, s2, true)
    292 #define CHECK_STRNE(s1, s2) CHECK_STROP(s1, s2, false)
    293 
    294 // Perform the pthread function call(args), LOG(FATAL) on error.
    295 #define CHECK_PTHREAD_CALL(call, args, what)                           \
    296   do {                                                                 \
    297     int rc = call args;                                                \
    298     if (rc != 0) {                                                     \
    299       errno = rc;                                                      \
    300       ABORT_AFTER_LOG_FATAL                                            \
    301       PLOG(FATAL) << #call << " failed for " << (what);                \
    302     }                                                                  \
    303   } while (false)
    304 
    305 // CHECK that can be used in a constexpr function. For example:
    306 //
    307 //    constexpr int half(int n) {
    308 //      return
    309 //          DCHECK_CONSTEXPR(n >= 0, , 0)
    310 //          CHECK_CONSTEXPR((n & 1) == 0),
    311 //              << "Extra debugging output: n = " << n, 0)
    312 //          n / 2;
    313 //    }
    314 #define CHECK_CONSTEXPR(x, out, dummy)                                     \
    315   (UNLIKELY(!(x)))                                                         \
    316       ? (LOG(FATAL) << "Check failed: " << #x out, dummy) \
    317       :
    318 
    319 // DCHECKs are debug variants of CHECKs only enabled in debug builds. Generally
    320 // CHECK should be used unless profiling identifies a CHECK as being in
    321 // performance critical code.
    322 #if defined(NDEBUG) && !defined(__clang_analyzer__)
    323 static constexpr bool kEnableDChecks = false;
    324 #else
    325 static constexpr bool kEnableDChecks = true;
    326 #endif
    327 
    328 #define DCHECK(x) \
    329   if (::android::base::kEnableDChecks) CHECK(x)
    330 #define DCHECK_EQ(x, y) \
    331   if (::android::base::kEnableDChecks) CHECK_EQ(x, y)
    332 #define DCHECK_NE(x, y) \
    333   if (::android::base::kEnableDChecks) CHECK_NE(x, y)
    334 #define DCHECK_LE(x, y) \
    335   if (::android::base::kEnableDChecks) CHECK_LE(x, y)
    336 #define DCHECK_LT(x, y) \
    337   if (::android::base::kEnableDChecks) CHECK_LT(x, y)
    338 #define DCHECK_GE(x, y) \
    339   if (::android::base::kEnableDChecks) CHECK_GE(x, y)
    340 #define DCHECK_GT(x, y) \
    341   if (::android::base::kEnableDChecks) CHECK_GT(x, y)
    342 #define DCHECK_STREQ(s1, s2) \
    343   if (::android::base::kEnableDChecks) CHECK_STREQ(s1, s2)
    344 #define DCHECK_STRNE(s1, s2) \
    345   if (::android::base::kEnableDChecks) CHECK_STRNE(s1, s2)
    346 #if defined(NDEBUG) && !defined(__clang_analyzer__)
    347 #define DCHECK_CONSTEXPR(x, out, dummy)
    348 #else
    349 #define DCHECK_CONSTEXPR(x, out, dummy) CHECK_CONSTEXPR(x, out, dummy)
    350 #endif
    351 
    352 // Temporary class created to evaluate the LHS and RHS, used with
    353 // MakeEagerEvaluator to infer the types of LHS and RHS.
    354 template <typename LHS, typename RHS>
    355 struct EagerEvaluator {
    356   constexpr EagerEvaluator(LHS l, RHS r) : lhs(l), rhs(r) {
    357   }
    358   LHS lhs;
    359   RHS rhs;
    360 };
    361 
    362 // Helper function for CHECK_xx.
    363 template <typename LHS, typename RHS>
    364 constexpr EagerEvaluator<LHS, RHS> MakeEagerEvaluator(LHS lhs, RHS rhs) {
    365   return EagerEvaluator<LHS, RHS>(lhs, rhs);
    366 }
    367 
    368 // Explicitly instantiate EagerEvalue for pointers so that char*s aren't treated
    369 // as strings. To compare strings use CHECK_STREQ and CHECK_STRNE. We rely on
    370 // signed/unsigned warnings to protect you against combinations not explicitly
    371 // listed below.
    372 #define EAGER_PTR_EVALUATOR(T1, T2)               \
    373   template <>                                     \
    374   struct EagerEvaluator<T1, T2> {                 \
    375     EagerEvaluator(T1 l, T2 r)                    \
    376         : lhs(reinterpret_cast<const void*>(l)),  \
    377           rhs(reinterpret_cast<const void*>(r)) { \
    378     }                                             \
    379     const void* lhs;                              \
    380     const void* rhs;                              \
    381   }
    382 EAGER_PTR_EVALUATOR(const char*, const char*);
    383 EAGER_PTR_EVALUATOR(const char*, char*);
    384 EAGER_PTR_EVALUATOR(char*, const char*);
    385 EAGER_PTR_EVALUATOR(char*, char*);
    386 EAGER_PTR_EVALUATOR(const unsigned char*, const unsigned char*);
    387 EAGER_PTR_EVALUATOR(const unsigned char*, unsigned char*);
    388 EAGER_PTR_EVALUATOR(unsigned char*, const unsigned char*);
    389 EAGER_PTR_EVALUATOR(unsigned char*, unsigned char*);
    390 EAGER_PTR_EVALUATOR(const signed char*, const signed char*);
    391 EAGER_PTR_EVALUATOR(const signed char*, signed char*);
    392 EAGER_PTR_EVALUATOR(signed char*, const signed char*);
    393 EAGER_PTR_EVALUATOR(signed char*, signed char*);
    394 
    395 // Data for the log message, not stored in LogMessage to avoid increasing the
    396 // stack size.
    397 class LogMessageData;
    398 
    399 // A LogMessage is a temporarily scoped object used by LOG and the unlikely part
    400 // of a CHECK. The destructor will abort if the severity is FATAL.
    401 class LogMessage {
    402  public:
    403   LogMessage(const char* file, unsigned int line, LogId id,
    404              LogSeverity severity, 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, LogId id,
    414                       LogSeverity severity, 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 // Allows to temporarily change the minimum severity level for logging.
    429 class ScopedLogSeverity {
    430  public:
    431   explicit ScopedLogSeverity(LogSeverity level);
    432   ~ScopedLogSeverity();
    433 
    434  private:
    435   LogSeverity old_;
    436 };
    437 
    438 }  // namespace base
    439 }  // namespace android
    440 
    441 #endif  // ANDROID_BASE_LOGGING_H
    442