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 // Notes: 216 // 1) This will not check whether the severity is high enough. One should use WOULD_LOG to filter 217 // usage manually. 218 // 2) This does not save and restore errno. 219 #define LOG_STREAM(severity) \ 220 ::android::base::LogMessage(__FILE__, __LINE__, SEVERITY_LAMBDA(severity), _LOG_TAG_INTERNAL, \ 221 -1) \ 222 .stream() 223 224 // Logs a message to logcat on Android otherwise to stderr. If the severity is 225 // FATAL it also causes an abort. For example: 226 // 227 // LOG(FATAL) << "We didn't expect to reach here"; 228 #define LOG(severity) LOGGING_PREAMBLE(severity) && LOG_STREAM(severity) 229 230 // Checks if we want to log something, and sets up appropriate RAII objects if 231 // so. 232 // Note: DO NOT USE DIRECTLY. This is an implementation detail. 233 #define LOGGING_PREAMBLE(severity) \ 234 (WOULD_LOG(severity) && \ 235 ABORT_AFTER_LOG_EXPR_IF((SEVERITY_LAMBDA(severity)) == ::android::base::FATAL, true) && \ 236 ::android::base::ErrnoRestorer()) 237 238 // A variant of LOG that also logs the current errno value. To be used when 239 // library calls fail. 240 #define PLOG(severity) \ 241 LOGGING_PREAMBLE(severity) && \ 242 ::android::base::LogMessage(__FILE__, __LINE__, SEVERITY_LAMBDA(severity), \ 243 _LOG_TAG_INTERNAL, errno) \ 244 .stream() 245 246 // Marker that code is yet to be implemented. 247 #define UNIMPLEMENTED(level) \ 248 LOG(level) << __PRETTY_FUNCTION__ << " unimplemented " 249 250 // Check whether condition x holds and LOG(FATAL) if not. The value of the 251 // expression x is only evaluated once. Extra logging can be appended using << 252 // after. For example: 253 // 254 // CHECK(false == true) results in a log message of 255 // "Check failed: false == true". 256 #define CHECK(x) \ 257 LIKELY((x)) || ABORT_AFTER_LOG_FATAL_EXPR(false) || \ 258 ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::FATAL, _LOG_TAG_INTERNAL, \ 259 -1) \ 260 .stream() \ 261 << "Check failed: " #x << " " 262 263 // clang-format off 264 // Helper for CHECK_xx(x,y) macros. 265 #define CHECK_OP(LHS, RHS, OP) \ 266 for (auto _values = ::android::base::MakeEagerEvaluator(LHS, RHS); \ 267 UNLIKELY(!(_values.lhs.v OP _values.rhs.v)); \ 268 /* empty */) \ 269 ABORT_AFTER_LOG_FATAL \ 270 ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::FATAL, _LOG_TAG_INTERNAL, -1) \ 271 .stream() \ 272 << "Check failed: " << #LHS << " " << #OP << " " << #RHS << " (" #LHS "=" \ 273 << ::android::base::LogNullGuard<decltype(_values.lhs.v)>::Guard(_values.lhs.v) \ 274 << ", " #RHS "=" \ 275 << ::android::base::LogNullGuard<decltype(_values.rhs.v)>::Guard(_values.rhs.v) \ 276 << ") " 277 // clang-format on 278 279 // Check whether a condition holds between x and y, LOG(FATAL) if not. The value 280 // of the expressions x and y is evaluated once. Extra logging can be appended 281 // using << after. For example: 282 // 283 // CHECK_NE(0 == 1, false) results in 284 // "Check failed: false != false (0==1=false, false=false) ". 285 #define CHECK_EQ(x, y) CHECK_OP(x, y, == ) 286 #define CHECK_NE(x, y) CHECK_OP(x, y, != ) 287 #define CHECK_LE(x, y) CHECK_OP(x, y, <= ) 288 #define CHECK_LT(x, y) CHECK_OP(x, y, < ) 289 #define CHECK_GE(x, y) CHECK_OP(x, y, >= ) 290 #define CHECK_GT(x, y) CHECK_OP(x, y, > ) 291 292 // clang-format off 293 // Helper for CHECK_STRxx(s1,s2) macros. 294 #define CHECK_STROP(s1, s2, sense) \ 295 while (UNLIKELY((strcmp(s1, s2) == 0) != (sense))) \ 296 ABORT_AFTER_LOG_FATAL \ 297 ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::FATAL, \ 298 _LOG_TAG_INTERNAL, -1) \ 299 .stream() \ 300 << "Check failed: " << "\"" << (s1) << "\"" \ 301 << ((sense) ? " == " : " != ") << "\"" << (s2) << "\"" 302 // clang-format on 303 304 // Check for string (const char*) equality between s1 and s2, LOG(FATAL) if not. 305 #define CHECK_STREQ(s1, s2) CHECK_STROP(s1, s2, true) 306 #define CHECK_STRNE(s1, s2) CHECK_STROP(s1, s2, false) 307 308 // Perform the pthread function call(args), LOG(FATAL) on error. 309 #define CHECK_PTHREAD_CALL(call, args, what) \ 310 do { \ 311 int rc = call args; \ 312 if (rc != 0) { \ 313 errno = rc; \ 314 ABORT_AFTER_LOG_FATAL \ 315 PLOG(FATAL) << #call << " failed for " << (what); \ 316 } \ 317 } while (false) 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 347 namespace log_detail { 348 349 // Temporary storage for a single eagerly evaluated check expression operand. 350 template <typename T> struct Storage { StorageStorage351 template <typename U> explicit constexpr Storage(U&& u) : v(std::forward<U>(u)) {} 352 explicit Storage(const Storage& t) = delete; 353 explicit Storage(Storage&& t) = delete; 354 T v; 355 }; 356 357 // Partial specialization for smart pointers to avoid copying. 358 template <typename T> struct Storage<std::unique_ptr<T>> { 359 explicit constexpr Storage(const std::unique_ptr<T>& ptr) : v(ptr.get()) {} 360 const T* v; 361 }; 362 template <typename T> struct Storage<std::shared_ptr<T>> { 363 explicit constexpr Storage(const std::shared_ptr<T>& ptr) : v(ptr.get()) {} 364 const T* v; 365 }; 366 367 // Type trait that checks if a type is a (potentially const) char pointer. 368 template <typename T> struct IsCharPointer { 369 using Pointee = std::remove_cv_t<std::remove_pointer_t<T>>; 370 static constexpr bool value = std::is_pointer_v<T> && 371 (std::is_same_v<Pointee, char> || std::is_same_v<Pointee, signed char> || 372 std::is_same_v<Pointee, unsigned char>); 373 }; 374 375 // Counterpart to Storage that depends on both operands. This is used to prevent 376 // char pointers being treated as strings in the log output - they might point 377 // to buffers of unprintable binary data. 378 template <typename LHS, typename RHS> struct StorageTypes { 379 static constexpr bool voidptr = IsCharPointer<LHS>::value && IsCharPointer<RHS>::value; 380 using LHSType = std::conditional_t<voidptr, const void*, LHS>; 381 using RHSType = std::conditional_t<voidptr, const void*, RHS>; 382 }; 383 384 // Temporary class created to evaluate the LHS and RHS, used with 385 // MakeEagerEvaluator to infer the types of LHS and RHS. 386 template <typename LHS, typename RHS> 387 struct EagerEvaluator { 388 template <typename A, typename B> constexpr EagerEvaluator(A&& l, B&& r) 389 : lhs(std::forward<A>(l)), rhs(std::forward<B>(r)) {} 390 const Storage<typename StorageTypes<LHS, RHS>::LHSType> lhs; 391 const Storage<typename StorageTypes<LHS, RHS>::RHSType> rhs; 392 }; 393 394 } // namespace log_detail 395 396 // Converts std::nullptr_t and null char pointers to the string "null" 397 // when writing the failure message. 398 template <typename T> struct LogNullGuard { 399 static const T& Guard(const T& v) { return v; } 400 }; 401 template <> struct LogNullGuard<std::nullptr_t> { 402 static const char* Guard(const std::nullptr_t&) { return "(null)"; } 403 }; 404 template <> struct LogNullGuard<char*> { 405 static const char* Guard(const char* v) { return v ? v : "(null)"; } 406 }; 407 template <> struct LogNullGuard<const char*> { 408 static const char* Guard(const char* v) { return v ? v : "(null)"; } 409 }; 410 411 // Helper function for CHECK_xx. 412 template <typename LHS, typename RHS> 413 constexpr auto MakeEagerEvaluator(LHS&& lhs, RHS&& rhs) { 414 return log_detail::EagerEvaluator<std::decay_t<LHS>, std::decay_t<RHS>>( 415 std::forward<LHS>(lhs), std::forward<RHS>(rhs)); 416 } 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 // LogId has been deprecated, but this constructor must exist for prebuilts. 427 LogMessage(const char* file, unsigned int line, LogId, LogSeverity severity, const char* tag, 428 int error); 429 LogMessage(const char* file, unsigned int line, LogSeverity severity, const char* tag, int error); 430 431 ~LogMessage(); 432 433 // Returns the stream associated with the message, the LogMessage performs 434 // output when it goes out of scope. 435 std::ostream& stream(); 436 437 // The routine that performs the actual logging. 438 static void LogLine(const char* file, unsigned int line, LogSeverity severity, const char* tag, 439 const char* msg); 440 441 private: 442 const std::unique_ptr<LogMessageData> data_; 443 444 DISALLOW_COPY_AND_ASSIGN(LogMessage); 445 }; 446 447 // Get the minimum severity level for logging. 448 LogSeverity GetMinimumLogSeverity(); 449 450 // Set the minimum severity level for logging, returning the old severity. 451 LogSeverity SetMinimumLogSeverity(LogSeverity new_severity); 452 453 // Return whether or not a log message with the associated tag should be logged. 454 bool ShouldLog(LogSeverity severity, const char* tag); 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 { // NOLINT(cert-dcl58-cpp) 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: using a pragma because "-Wgcc-compat" (included in "-Weverything") complains about 475 // diagnose_if. 476 // Note: to print the pointer, use "<< static_cast<const void*>(string_pointer)" instead. 477 // Note: a not-recommended alternative is to let Clang ignore the warning by adding 478 // -Wno-user-defined-warnings to CPPFLAGS. 479 #pragma clang diagnostic push 480 #pragma clang diagnostic ignored "-Wgcc-compat" 481 #define OSTREAM_STRING_POINTER_USAGE_WARNING \ 482 __attribute__((diagnose_if(true, "Unexpected logging of string pointer", "warning"))) 483 inline OSTREAM_STRING_POINTER_USAGE_WARNING 484 std::ostream& operator<<(std::ostream& stream, const std::string* string_pointer) { 485 return stream << static_cast<const void*>(string_pointer); 486 } 487 #pragma clang diagnostic pop 488 489 } // namespace std 490