Debian Codegraph @

Xpjproject/third_party/webrtc_aec3/src/rtc_base/logging.cc

raw symbols SCIP
1 /*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #include "rtc_base/logging.h"
12
13 #include <string.h>
14
15 #if RTC_LOG_ENABLED()
16
17 #if defined(WEBRTC_WIN)
18 #include <winsock2.h>
19 #include <windows.h>
20 #if _MSC_VER < 1900
21 #define snprintf _snprintf
22 #endif
23 #undef ERROR // wingdi.h
24 #endif
25
26 #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
27 #include <CoreServices/CoreServices.h>
28 #elif defined(WEBRTC_ANDROID)
29 #include <android/log.h>
30
31 // Android has a 1024 limit on log inputs. We use 60 chars as an
32 // approx for the header/tag portion.
33 // See android/system/core/liblog/logd_write.c
34 static const int kMaxLogLineSize = 1024 - 60;
35 #endif // WEBRTC_MAC && !defined(WEBRTC_IOS) || WEBRTC_ANDROID
36
37 #include <inttypes.h>
38 #include <stdio.h>
39 #include <time.h>
40
41 #include <algorithm>
42 #include <cstdarg>
43 #include <vector>
44
45 #include "absl/base/attributes.h"
46 #include "rtc_base/checks.h"
47 #include "rtc_base/platform_thread_types.h"
48 #include "rtc_base/string_encode.h"
49 #include "rtc_base/string_utils.h"
50 #include "rtc_base/strings/string_builder.h"
51 #include "rtc_base/synchronization/mutex.h"
52 #include "rtc_base/thread_annotations.h"
53 #include "rtc_base/time_utils.h"
54
55 #if defined(WEBRTC_RACE_CHECK_MUTEX)
56 #if defined(WEBRTC_ABSL_MUTEX)
57 #error Please only define one of WEBRTC_RACE_CHECK_MUTEX and WEBRTC_ABSL_MUTEX.
58 #endif
59 #include "absl/base/const_init.h"
60 #include "absl/synchronization/mutex.h" // nogncheck
61 using LoggingMutexLock = ::absl::MutexLock;
62 #else
63 using LoggingMutexLock = ::webrtc::MutexLock;
64 #endif // if defined(WEBRTC_RACE_CHECK_MUTEX)
65
66 namespace rtc {
67 namespace {
68 // By default, release builds don't log, debug builds at info level
69 #if !defined(NDEBUG)
70 static LoggingSeverity g_min_sev = LS_INFO;
71 static LoggingSeverity g_dbg_sev = LS_INFO;
72 #else
73 static LoggingSeverity g_min_sev = LS_NONE;
74 static LoggingSeverity g_dbg_sev = LS_NONE;
75 #endif
76
77 // Return the filename portion of the string (that following the last slash).
78 const char* FilenameFromPath(const char* file) {
79 const char* end1 = ::strrchr(file, '/');
80 const char* end2 = ::strrchr(file, '\\');
81 if (!end1 && !end2)
82 return file;
83 else
84 return (end1 > end2) ? end1 + 1 : end2 + 1;
85 }
86
87 // Global lock for log subsystem, only needed to serialize access to streams_.
88 // TODO(bugs.webrtc.org/11665): this is not currently constant initialized and
89 // trivially destructible.
90 #if defined(WEBRTC_RACE_CHECK_MUTEX)
91 // When WEBRTC_RACE_CHECK_MUTEX is defined, even though WebRTC objects are
92 // invoked serially, the logging is static, invoked concurrently and hence needs
93 // protection.
94 absl::Mutex g_log_mutex_(absl::kConstInit);
95 #else
96 webrtc::Mutex g_log_mutex_;
97 #endif
98
99 } // namespace
100
101 /////////////////////////////////////////////////////////////////////////////
102 // LogMessage
103 /////////////////////////////////////////////////////////////////////////////
104
105 bool LogMessage::log_to_stderr_ = true;
106
107 // The list of logging streams currently configured.
108 // Note: we explicitly do not clean this up, because of the uncertain ordering
109 // of destructors at program exit. Let the person who sets the stream trigger
110 // cleanup by setting to null, or let it leak (safe at program exit).
111 ABSL_CONST_INIT LogSink* LogMessage::streams_ RTC_GUARDED_BY(g_log_mutex_) =
112 nullptr;
113 ABSL_CONST_INIT std::atomic<bool> LogMessage::streams_empty_ = {true};
114
115 // Boolean options default to false (0)
116 bool LogMessage::thread_, LogMessage::timestamp_;
117
118 LogMessage::LogMessage(const char* file, int line, LoggingSeverity sev)
119 : LogMessage(file, line, sev, ERRCTX_NONE, 0) {}
120
121 LogMessage::LogMessage(const char* file,
122 int line,
123 LoggingSeverity sev,
124 LogErrorContext err_ctx,
125 int err)
126 : severity_(sev) {
127 if (timestamp_) {
128 // Use SystemTimeMillis so that even if tests use fake clocks, the timestamp
129 // in log messages represents the real system time.
130 int64_t time = TimeDiff(SystemTimeMillis(), LogStartTime());
131 // Also ensure WallClockStartTime is initialized, so that it matches
132 // LogStartTime.
133 WallClockStartTime();
134 // TODO(kwiberg): Switch to absl::StrFormat, if binary size is ok.
135 char timestamp[50]; // Maximum string length of an int64_t is 20.
136 int len =
137 snprintf(timestamp, sizeof(timestamp), "[%03" PRId64 ":%03" PRId64 "]",
138 time / 1000, time % 1000);
139 RTC_DCHECK_LT(len, sizeof(timestamp));
140 print_stream_ << timestamp;
141 }
142
143 if (thread_) {
144 PlatformThreadId id = CurrentThreadId();
145 print_stream_ << "[" << id << "] ";
146 }
147
148 if (file != nullptr) {
149 #if defined(WEBRTC_ANDROID)
150 tag_ = FilenameFromPath(file);
151 print_stream_ << "(line " << line << "): ";
152 #else
153 print_stream_ << "(" << FilenameFromPath(file) << ":" << line << "): ";
154 #endif
155 }
156
157 if (err_ctx != ERRCTX_NONE) {
158 char tmp_buf[1024];
159 SimpleStringBuilder tmp(tmp_buf);
160 tmp.AppendFormat("[0x%08X]", err);
161 switch (err_ctx) {
162 case ERRCTX_ERRNO:
163 tmp << " " << strerror(err);
164 break;
165 #ifdef WEBRTC_WIN
166 case ERRCTX_HRESULT: {
167 char msgbuf[256];
168 DWORD flags =
169 FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
170 if (DWORD len = FormatMessageA(
171 flags, nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
172 msgbuf, sizeof(msgbuf) / sizeof(msgbuf[0]), nullptr)) {
173 while ((len > 0) &&
174 isspace(static_cast<unsigned char>(msgbuf[len - 1]))) {
175 msgbuf[--len] = 0;
176 }
177 tmp << " " << msgbuf;
178 }
179 break;
180 }
181 #endif // WEBRTC_WIN
182 default:
183 break;
184 }
185 extra_ = tmp.str();
186 }
187 }
188
189 #if defined(WEBRTC_ANDROID)
190 LogMessage::LogMessage(const char* file,
191 int line,
192 LoggingSeverity sev,
193 const char* tag)
194 : LogMessage(file, line, sev, ERRCTX_NONE, 0 /* err */) {
195 tag_ = tag;
196 print_stream_ << tag << ": ";
197 }
198 #endif
199
200 // DEPRECATED. Currently only used by downstream projects that use
201 // implementation details of logging.h. Work is ongoing to remove those
202 // dependencies.
203 LogMessage::LogMessage(const char* file,
204 int line,
205 LoggingSeverity sev,
206 const std::string& tag)
207 : LogMessage(file, line, sev) {
208 print_stream_ << tag << ": ";
209 }
210
211 LogMessage::~LogMessage() {
212 FinishPrintStream();
213
214 const std::string str = print_stream_.Release();
215
216 if (severity_ >= g_dbg_sev) {
217 #if defined(WEBRTC_ANDROID)
218 OutputToDebug(str, severity_, tag_);
219 #else
220 OutputToDebug(str, severity_);
221 #endif
222 }
223
224 LoggingMutexLock lock(&g_log_mutex_);
225 for (LogSink* entry = streams_; entry != nullptr; entry = entry->next_) {
226 if (severity_ >= entry->min_severity_) {
227 #if defined(WEBRTC_ANDROID)
228 entry->OnLogMessage(str, severity_, tag_);
229 #else
230 entry->OnLogMessage(str, severity_);
231 #endif
232 }
233 }
234 }
235
236 void LogMessage::AddTag(const char* tag) {
237 #ifdef WEBRTC_ANDROID
238 tag_ = tag;
239 #endif
240 }
241
242 rtc::StringBuilder& LogMessage::stream() {
243 return print_stream_;
244 }
245
246 int LogMessage::GetMinLogSeverity() {
247 return g_min_sev;
248 }
249
250 LoggingSeverity LogMessage::GetLogToDebug() {
251 return g_dbg_sev;
252 }
253 int64_t LogMessage::LogStartTime() {
254 static const int64_t g_start = SystemTimeMillis();
255 return g_start;
256 }
257
258 uint32_t LogMessage::WallClockStartTime() {
259 static const uint32_t g_start_wallclock = time(nullptr);
260 return g_start_wallclock;
261 }
262
263 void LogMessage::LogThreads(bool on) {
264 thread_ = on;
265 }
266
267 void LogMessage::LogTimestamps(bool on) {
268 timestamp_ = on;
269 }
270
271 void LogMessage::LogToDebug(LoggingSeverity min_sev) {
272 g_dbg_sev = min_sev;
273 LoggingMutexLock lock(&g_log_mutex_);
274 UpdateMinLogSeverity();
275 }
276
277 void LogMessage::SetLogToStderr(bool log_to_stderr) {
278 log_to_stderr_ = log_to_stderr;
279 }
280
281 int LogMessage::GetLogToStream(LogSink* stream) {
282 LoggingMutexLock lock(&g_log_mutex_);
283 LoggingSeverity sev = LS_NONE;
284 for (LogSink* entry = streams_; entry != nullptr; entry = entry->next_) {
285 if (stream == nullptr || stream == entry) {
286 sev = std::min(sev, entry->min_severity_);
287 }
288 }
289 return sev;
290 }
291
292 void LogMessage::AddLogToStream(LogSink* stream, LoggingSeverity min_sev) {
293 LoggingMutexLock lock(&g_log_mutex_);
294 stream->min_severity_ = min_sev;
295 stream->next_ = streams_;
296 streams_ = stream;
297 streams_empty_.store(false, std::memory_order_relaxed);
298 UpdateMinLogSeverity();
299 }
300
301 void LogMessage::RemoveLogToStream(LogSink* stream) {
302 LoggingMutexLock lock(&g_log_mutex_);
303 for (LogSink** entry = &streams_; *entry != nullptr;
304 entry = &(*entry)->next_) {
305 if (*entry == stream) {
306 *entry = (*entry)->next_;
307 break;
308 }
309 }
310 streams_empty_.store(streams_ == nullptr, std::memory_order_relaxed);
311 UpdateMinLogSeverity();
312 }
313
314 void LogMessage::ConfigureLogging(const char* params) {
315 LoggingSeverity current_level = LS_VERBOSE;
316 LoggingSeverity debug_level = GetLogToDebug();
317
318 std::vector<std::string> tokens;
319 tokenize(params, ' ', &tokens);
320
321 for (const std::string& token : tokens) {
322 if (token.empty())
323 continue;
324
325 // Logging features
326 if (token == "tstamp") {
327 LogTimestamps();
328 } else if (token == "thread") {
329 LogThreads();
330
331 // Logging levels
332 } else if (token == "verbose") {
333 current_level = LS_VERBOSE;
334 } else if (token == "info") {
335 current_level = LS_INFO;
336 } else if (token == "warning") {
337 current_level = LS_WARNING;
338 } else if (token == "error") {
339 current_level = LS_ERROR;
340 } else if (token == "none") {
341 current_level = LS_NONE;
342
343 // Logging targets
344 } else if (token == "debug") {
345 debug_level = current_level;
346 }
347 }
348
349 #if defined(WEBRTC_WIN) && !defined(WINUWP)
350 if ((LS_NONE != debug_level) && !::IsDebuggerPresent()) {
351 // First, attempt to attach to our parent's console... so if you invoke
352 // from the command line, we'll see the output there. Otherwise, create
353 // our own console window.
354 // Note: These methods fail if a console already exists, which is fine.
355 if (!AttachConsole(ATTACH_PARENT_PROCESS))
356 ::AllocConsole();
357 }
358 #endif // defined(WEBRTC_WIN) && !defined(WINUWP)
359
360 LogToDebug(debug_level);
361 }
362
363 void LogMessage::UpdateMinLogSeverity()
364 RTC_EXCLUSIVE_LOCKS_REQUIRED(g_log_mutex_) {
365 LoggingSeverity min_sev = g_dbg_sev;
366 for (LogSink* entry = streams_; entry != nullptr; entry = entry->next_) {
367 min_sev = std::min(min_sev, entry->min_severity_);
368 }
369 g_min_sev = min_sev;
370 }
371
372 #if defined(WEBRTC_ANDROID)
373 void LogMessage::OutputToDebug(const std::string& str,
374 LoggingSeverity severity,
375 const char* tag) {
376 #else
377 void LogMessage::OutputToDebug(const std::string& str,
378 LoggingSeverity severity) {
379 #endif
380 bool log_to_stderr = log_to_stderr_;
381 #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS) && defined(NDEBUG)
382 // On the Mac, all stderr output goes to the Console log and causes clutter.
383 // So in opt builds, don't log to stderr unless the user specifically sets
384 // a preference to do so.
385 CFStringRef key = CFStringCreateWithCString(
386 kCFAllocatorDefault, "logToStdErr", kCFStringEncodingUTF8);
387 CFStringRef domain = CFBundleGetIdentifier(CFBundleGetMainBundle());
388 if (key != nullptr && domain != nullptr) {
389 Boolean exists_and_is_valid;
390 Boolean should_log =
391 CFPreferencesGetAppBooleanValue(key, domain, &exists_and_is_valid);
392 // If the key doesn't exist or is invalid or is false, we will not log to
393 // stderr.
394 log_to_stderr = exists_and_is_valid && should_log;
395 }
396 if (key != nullptr) {
397 CFRelease(key);
398 }
399 #endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS) && defined(NDEBUG)
400
401 #if defined(WEBRTC_WIN)
402 // Always log to the debugger.
403 // Perhaps stderr should be controlled by a preference, as on Mac?
404 OutputDebugStringA(str.c_str());
405 if (log_to_stderr) {
406 // This handles dynamically allocated consoles, too.
407 if (HANDLE error_handle = ::GetStdHandle(STD_ERROR_HANDLE)) {
408 log_to_stderr = false;
409 DWORD written = 0;
410 ::WriteFile(error_handle, str.data(), static_cast<DWORD>(str.size()),
411 &written, 0);
412 }
413 }
414 #endif // WEBRTC_WIN
415
416 #if defined(WEBRTC_ANDROID)
417 // Android's logging facility uses severity to log messages but we
418 // need to map libjingle's severity levels to Android ones first.
419 // Also write to stderr which maybe available to executable started
420 // from the shell.
421 int prio;
422 switch (severity) {
423 case LS_VERBOSE:
424 prio = ANDROID_LOG_VERBOSE;
425 break;
426 case LS_INFO:
427 prio = ANDROID_LOG_INFO;
428 break;
429 case LS_WARNING:
430 prio = ANDROID_LOG_WARN;
431 break;
432 case LS_ERROR:
433 prio = ANDROID_LOG_ERROR;
434 break;
435 default:
436 prio = ANDROID_LOG_UNKNOWN;
437 }
438
439 int size = str.size();
440 int line = 0;
441 int idx = 0;
442 const int max_lines = size / kMaxLogLineSize + 1;
443 if (max_lines == 1) {
444 __android_log_print(prio, tag, "%.*s", size, str.c_str());
445 } else {
446 while (size > 0) {
447 const int len = std::min(size, kMaxLogLineSize);
448 // Use the size of the string in the format (str may have \0 in the
449 // middle).
450 __android_log_print(prio, tag, "[%d/%d] %.*s", line + 1, max_lines, len,
451 str.c_str() + idx);
452 idx += len;
453 size -= len;
454 ++line;
455 }
456 }
457 #endif // WEBRTC_ANDROID
458 if (log_to_stderr) {
459 fprintf(stderr, "%s", str.c_str());
460 fflush(stderr);
461 }
462 }
463
464 // static
465 bool LogMessage::IsNoop(LoggingSeverity severity) {
466 if (severity >= g_dbg_sev || severity >= g_min_sev)
467 return false;
468 return streams_empty_.load(std::memory_order_relaxed);
469 }
470
471 void LogMessage::FinishPrintStream() {
472 if (!extra_.empty())
473 print_stream_ << " : " << extra_;
474 print_stream_ << "\n";
475 }
476
477 namespace webrtc_logging_impl {
478
479 void Log(const LogArgType* fmt, ...) {
480 va_list args;
481 va_start(args, fmt);
482
483 LogMetadataErr meta;
484 const char* tag = nullptr;
485 switch (*fmt) {
486 case LogArgType::kLogMetadata: {
487 meta = {va_arg(args, LogMetadata), ERRCTX_NONE, 0};
488 break;
489 }
490 case LogArgType::kLogMetadataErr: {
491 meta = va_arg(args, LogMetadataErr);
492 break;
493 }
494 #ifdef WEBRTC_ANDROID
495 case LogArgType::kLogMetadataTag: {
496 const LogMetadataTag tag_meta = va_arg(args, LogMetadataTag);
497 meta = {{nullptr, 0, tag_meta.severity}, ERRCTX_NONE, 0};
498 tag = tag_meta.tag;
499 break;
500 }
501 #endif
502 default: {
503 RTC_NOTREACHED();
504 va_end(args);
505 return;
506 }
507 }
508
509 LogMessage log_message(meta.meta.File(), meta.meta.Line(),
510 meta.meta.Severity(), meta.err_ctx, meta.err);
511 if (tag) {
512 log_message.AddTag(tag);
513 }
514
515 for (++fmt; *fmt != LogArgType::kEnd; ++fmt) {
516 switch (*fmt) {
517 case LogArgType::kInt:
518 log_message.stream() << va_arg(args, int);
519 break;
520 case LogArgType::kLong:
521 log_message.stream() << va_arg(args, long);
522 break;
523 case LogArgType::kLongLong:
524 log_message.stream() << va_arg(args, long long);
525 break;
526 case LogArgType::kUInt:
527 log_message.stream() << va_arg(args, unsigned);
528 break;
529 case LogArgType::kULong:
530 log_message.stream() << va_arg(args, unsigned long);
531 break;
532 case LogArgType::kULongLong:
533 log_message.stream() << va_arg(args, unsigned long long);
534 break;
535 case LogArgType::kDouble:
536 log_message.stream() << va_arg(args, double);
537 break;
538 case LogArgType::kLongDouble:
539 log_message.stream() << va_arg(args, long double);
540 break;
541 case LogArgType::kCharP: {
542 const char* s = va_arg(args, const char*);
543 log_message.stream() << (s ? s : "(null)");
544 break;
545 }
546 case LogArgType::kStdString:
547 log_message.stream() << *va_arg(args, const std::string*);
548 break;
549 case LogArgType::kStringView:
550 log_message.stream() << *va_arg(args, const absl::string_view*);
551 break;
552 case LogArgType::kVoidP:
553 log_message.stream() << rtc::ToHex(
554 reinterpret_cast<uintptr_t>(va_arg(args, const void*)));
555 break;
556 default:
557 RTC_NOTREACHED();
558 va_end(args);
559 return;
560 }
561 }
562
563 va_end(args);
564 }
565
566 } // namespace webrtc_logging_impl
567 } // namespace rtc
568 #endif
569
570 namespace rtc {
571 // Inefficient default implementation, override is recommended.
572 void LogSink::OnLogMessage(const std::string& msg,
573 LoggingSeverity severity,
574 const char* tag) {
575 OnLogMessage(tag + (": " + msg), severity);
576 }
577
578 void LogSink::OnLogMessage(const std::string& msg,
579 LoggingSeverity /* severity */) {
580 OnLogMessage(msg);
581 }
582 } // namespace rtc