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.v OP _values.rhs.v));                                              \
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 "="                  \
260       << ::android::base::LogNullGuard<decltype(_values.lhs.v)>::Guard(_values.lhs.v)            \
261       << ", " #RHS "="                                                                           \
262       << ::android::base::LogNullGuard<decltype(_values.rhs.v)>::Guard(_values.rhs.v)            \
263       << ") "
264 // clang-format on
265 
266 // Check whether a condition holds between x and y, LOG(FATAL) if not. The value
267 // of the expressions x and y is evaluated once. Extra logging can be appended
268 // using << after. For example:
269 //
270 //     CHECK_NE(0 == 1, false) results in
271 //       "Check failed: false != false (0==1=false, false=false) ".
272 #define CHECK_EQ(x, y) CHECK_OP(x, y, == )
273 #define CHECK_NE(x, y) CHECK_OP(x, y, != )
274 #define CHECK_LE(x, y) CHECK_OP(x, y, <= )
275 #define CHECK_LT(x, y) CHECK_OP(x, y, < )
276 #define CHECK_GE(x, y) CHECK_OP(x, y, >= )
277 #define CHECK_GT(x, y) CHECK_OP(x, y, > )
278 
279 // clang-format off
280 // Helper for CHECK_STRxx(s1,s2) macros.
281 #define CHECK_STROP(s1, s2, sense)                                             \
282   while (UNLIKELY((strcmp(s1, s2) == 0) != (sense)))                           \
283     ABORT_AFTER_LOG_FATAL                                                      \
284     ::android::base::LogMessage(__FILE__, __LINE__,  ::android::base::FATAL,   \
285                                  _LOG_TAG_INTERNAL, -1)                        \
286         .stream()                                                              \
287         << "Check failed: " << "\"" << (s1) << "\""                            \
288         << ((sense) ? " == " : " != ") << "\"" << (s2) << "\""
289 // clang-format on
290 
291 // Check for string (const char*) equality between s1 and s2, LOG(FATAL) if not.
292 #define CHECK_STREQ(s1, s2) CHECK_STROP(s1, s2, true)
293 #define CHECK_STRNE(s1, s2) CHECK_STROP(s1, s2, false)
294 
295 // Perform the pthread function call(args), LOG(FATAL) on error.
296 #define CHECK_PTHREAD_CALL(call, args, what)                           \
297   do {                                                                 \
298     int rc = call args;                                                \
299     if (rc != 0) {                                                     \
300       errno = rc;                                                      \
301       ABORT_AFTER_LOG_FATAL                                            \
302       PLOG(FATAL) << #call << " failed for " << (what);                \
303     }                                                                  \
304   } while (false)
305 
306 // DCHECKs are debug variants of CHECKs only enabled in debug builds. Generally
307 // CHECK should be used unless profiling identifies a CHECK as being in
308 // performance critical code.
309 #if defined(NDEBUG) && !defined(__clang_analyzer__)
310 static constexpr bool kEnableDChecks = false;
311 #else
312 static constexpr bool kEnableDChecks = true;
313 #endif
314 
315 #define DCHECK(x) \
316   if (::android::base::kEnableDChecks) CHECK(x)
317 #define DCHECK_EQ(x, y) \
318   if (::android::base::kEnableDChecks) CHECK_EQ(x, y)
319 #define DCHECK_NE(x, y) \
320   if (::android::base::kEnableDChecks) CHECK_NE(x, y)
321 #define DCHECK_LE(x, y) \
322   if (::android::base::kEnableDChecks) CHECK_LE(x, y)
323 #define DCHECK_LT(x, y) \
324   if (::android::base::kEnableDChecks) CHECK_LT(x, y)
325 #define DCHECK_GE(x, y) \
326   if (::android::base::kEnableDChecks) CHECK_GE(x, y)
327 #define DCHECK_GT(x, y) \
328   if (::android::base::kEnableDChecks) CHECK_GT(x, y)
329 #define DCHECK_STREQ(s1, s2) \
330   if (::android::base::kEnableDChecks) CHECK_STREQ(s1, s2)
331 #define DCHECK_STRNE(s1, s2) \
332   if (::android::base::kEnableDChecks) CHECK_STRNE(s1, s2)
333 
334 namespace log_detail {
335 
336 // Temporary storage for a single eagerly evaluated check expression operand.
337 template <typename T> struct Storage {
StorageStorage338   template <typename U> explicit constexpr Storage(U&& u) : v(std::forward<U>(u)) {}
339   explicit Storage(const Storage& t) = delete;
340   explicit Storage(Storage&& t) = delete;
341   T v;
342 };
343 
344 // Partial specialization for smart pointers to avoid copying.
345 template <typename T> struct Storage<std::unique_ptr<T>> {
346   explicit constexpr Storage(const std::unique_ptr<T>& ptr) : v(ptr.get()) {}
347   const T* v;
348 };
349 template <typename T> struct Storage<std::shared_ptr<T>> {
350   explicit constexpr Storage(const std::shared_ptr<T>& ptr) : v(ptr.get()) {}
351   const T* v;
352 };
353 
354 // Type trait that checks if a type is a (potentially const) char pointer.
355 template <typename T> struct IsCharPointer {
356   using Pointee = std::remove_cv_t<std::remove_pointer_t<T>>;
357   static constexpr bool value = std::is_pointer_v<T> &&
358       (std::is_same_v<Pointee, char> || std::is_same_v<Pointee, signed char> ||
359        std::is_same_v<Pointee, unsigned char>);
360 };
361 
362 // Counterpart to Storage that depends on both operands. This is used to prevent
363 // char pointers being treated as strings in the log output - they might point
364 // to buffers of unprintable binary data.
365 template <typename LHS, typename RHS> struct StorageTypes {
366   static constexpr bool voidptr = IsCharPointer<LHS>::value && IsCharPointer<RHS>::value;
367   using LHSType = std::conditional_t<voidptr, const void*, LHS>;
368   using RHSType = std::conditional_t<voidptr, const void*, RHS>;
369 };
370 
371 // Temporary class created to evaluate the LHS and RHS, used with
372 // MakeEagerEvaluator to infer the types of LHS and RHS.
373 template <typename LHS, typename RHS>
374 struct EagerEvaluator {
375   template <typename A, typename B> constexpr EagerEvaluator(A&& l, B&& r)
376       : lhs(std::forward<A>(l)), rhs(std::forward<B>(r)) {}
377   const Storage<typename StorageTypes<LHS, RHS>::LHSType> lhs;
378   const Storage<typename StorageTypes<LHS, RHS>::RHSType> rhs;
379 };
380 
381 }  // namespace log_detail
382 
383 // Converts std::nullptr_t and null char pointers to the string "null"
384 // when writing the failure message.
385 template <typename T> struct LogNullGuard {
386   static const T& Guard(const T& v) { return v; }
387 };
388 template <> struct LogNullGuard<std::nullptr_t> {
389   static const char* Guard(const std::nullptr_t&) { return "(null)"; }
390 };
391 template <> struct LogNullGuard<char*> {
392   static const char* Guard(const char* v) { return v ? v : "(null)"; }
393 };
394 template <> struct LogNullGuard<const char*> {
395   static const char* Guard(const char* v) { return v ? v : "(null)"; }
396 };
397 
398 // Helper function for CHECK_xx.
399 template <typename LHS, typename RHS>
400 constexpr auto MakeEagerEvaluator(LHS&& lhs, RHS&& rhs) {
401   return log_detail::EagerEvaluator<std::decay_t<LHS>, std::decay_t<RHS>>(
402       std::forward<LHS>(lhs), std::forward<RHS>(rhs));
403 }
404 
405 // Data for the log message, not stored in LogMessage to avoid increasing the
406 // stack size.
407 class LogMessageData;
408 
409 // A LogMessage is a temporarily scoped object used by LOG and the unlikely part
410 // of a CHECK. The destructor will abort if the severity is FATAL.
411 class LogMessage {
412  public:
413   // LogId has been deprecated, but this constructor must exist for prebuilts.
414   LogMessage(const char* file, unsigned int line, LogId, LogSeverity severity, const char* tag,
415              int error);
416   LogMessage(const char* file, unsigned int line, LogSeverity severity, const char* tag, int error);
417 
418   ~LogMessage();
419 
420   // Returns the stream associated with the message, the LogMessage performs
421   // output when it goes out of scope.
422   std::ostream& stream();
423 
424   // The routine that performs the actual logging.
425   static void LogLine(const char* file, unsigned int line, LogSeverity severity, const char* tag,
426                       const char* msg);
427 
428  private:
429   const std::unique_ptr<LogMessageData> data_;
430 
431   DISALLOW_COPY_AND_ASSIGN(LogMessage);
432 };
433 
434 // Get the minimum severity level for logging.
435 LogSeverity GetMinimumLogSeverity();
436 
437 // Set the minimum severity level for logging, returning the old severity.
438 LogSeverity SetMinimumLogSeverity(LogSeverity new_severity);
439 
440 // Return whether or not a log message with the associated tag should be logged.
441 bool ShouldLog(LogSeverity severity, const char* tag);
442 
443 // Allows to temporarily change the minimum severity level for logging.
444 class ScopedLogSeverity {
445  public:
446   explicit ScopedLogSeverity(LogSeverity level);
447   ~ScopedLogSeverity();
448 
449  private:
450   LogSeverity old_;
451 };
452 
453 }  // namespace base
454 }  // namespace android
455 
456 namespace std {  // NOLINT(cert-dcl58-cpp)
457 
458 // Emit a warning of ostream<< with std::string*. The intention was most likely to print *string.
459 //
460 // Note: for this to work, we need to have this in a namespace.
461 // Note: using a pragma because "-Wgcc-compat" (included in "-Weverything") complains about
462 //       diagnose_if.
463 // Note: to print the pointer, use "<< static_cast<const void*>(string_pointer)" instead.
464 // Note: a not-recommended alternative is to let Clang ignore the warning by adding
465 //       -Wno-user-defined-warnings to CPPFLAGS.
466 #pragma clang diagnostic push
467 #pragma clang diagnostic ignored "-Wgcc-compat"
468 #define OSTREAM_STRING_POINTER_USAGE_WARNING \
469     __attribute__((diagnose_if(true, "Unexpected logging of string pointer", "warning")))
470 inline OSTREAM_STRING_POINTER_USAGE_WARNING
471 std::ostream& operator<<(std::ostream& stream, const std::string* string_pointer) {
472   return stream << static_cast<const void*>(string_pointer);
473 }
474 #pragma clang diagnostic pop
475 
476 }  // namespace std
477