1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/logging.h"
6 
7 #include <limits.h>
8 #include <stdint.h>
9 
10 #include "base/macros.h"
11 #include "build/build_config.h"
12 
13 #if defined(OS_WIN)
14 #include <io.h>
15 #include <windows.h>
16 typedef HANDLE FileHandle;
17 typedef HANDLE MutexHandle;
18 // Windows warns on using write().  It prefers _write().
19 #define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
20 // Windows doesn't define STDERR_FILENO.  Define it here.
21 #define STDERR_FILENO 2
22 
23 #elif defined(OS_MACOSX)
24 // In MacOS 10.12 and iOS 10.0 and later ASL (Apple System Log) was deprecated
25 // in favor of OS_LOG (Unified Logging).
26 #include <AvailabilityMacros.h>
27 #if defined(OS_IOS)
28 #if !defined(__IPHONE_10_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
29 #define USE_ASL
30 #endif
31 #else  // !defined(OS_IOS)
32 #if !defined(MAC_OS_X_VERSION_10_12) || \
33     MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12
34 #define USE_ASL
35 #endif
36 #endif  // defined(OS_IOS)
37 
38 #if defined(USE_ASL)
39 #include <asl.h>
40 #else
41 #include <os/log.h>
42 #endif
43 
44 #include <CoreFoundation/CoreFoundation.h>
45 #include <mach/mach.h>
46 #include <mach/mach_time.h>
47 #include <mach-o/dyld.h>
48 
49 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
50 #if defined(OS_NACL)
51 #include <sys/time.h>  // timespec doesn't seem to be in <time.h>
52 #endif
53 #include <time.h>
54 #endif
55 
56 #if defined(OS_FUCHSIA)
57 #include <zircon/process.h>
58 #include <zircon/syscalls.h>
59 #endif
60 
61 #if defined(OS_ANDROID)
62 #include <android/log.h>
63 #endif
64 
65 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
66 #include <errno.h>
67 #include <paths.h>
68 #include <pthread.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #include <string.h>
72 #include <sys/stat.h>
73 #include <unistd.h>
74 #define MAX_PATH PATH_MAX
75 typedef FILE* FileHandle;
76 typedef pthread_mutex_t* MutexHandle;
77 #endif
78 
79 #include <algorithm>
80 #include <cstring>
81 #include <ctime>
82 #include <iomanip>
83 #include <ostream>
84 #include <string>
85 #include <utility>
86 
87 #include "base/base_switches.h"
88 #include "base/callback.h"
89 #include "base/command_line.h"
90 #include "base/containers/stack.h"
91 #include "base/debug/activity_tracker.h"
92 #include "base/debug/alias.h"
93 #include "base/debug/debugger.h"
94 #include "base/debug/stack_trace.h"
95 #include "base/lazy_instance.h"
96 #include "base/posix/eintr_wrapper.h"
97 #include "base/strings/string_piece.h"
98 #include "base/strings/string_util.h"
99 #include "base/strings/stringprintf.h"
100 #include "base/strings/sys_string_conversions.h"
101 #include "base/strings/utf_string_conversions.h"
102 #include "base/synchronization/lock_impl.h"
103 #include "base/threading/platform_thread.h"
104 #include "base/vlog.h"
105 
106 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
107 #include "base/posix/safe_strerror.h"
108 #endif
109 
110 namespace logging {
111 
112 namespace {
113 
114 VlogInfo* g_vlog_info = nullptr;
115 VlogInfo* g_vlog_info_prev = nullptr;
116 
117 const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
118 static_assert(LOG_NUM_SEVERITIES == arraysize(log_severity_names),
119               "Incorrect number of log_severity_names");
120 
log_severity_name(int severity)121 const char* log_severity_name(int severity) {
122   if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
123     return log_severity_names[severity];
124   return "UNKNOWN";
125 }
126 
127 int g_min_log_level = 0;
128 
129 LoggingDestination g_logging_destination = LOG_DEFAULT;
130 
131 // For LOG_ERROR and above, always print to stderr.
132 const int kAlwaysPrintErrorLevel = LOG_ERROR;
133 
134 // Which log file to use? This is initialized by InitLogging or
135 // will be lazily initialized to the default value when it is
136 // first needed.
137 #if defined(OS_WIN)
138 typedef std::wstring PathString;
139 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
140 typedef std::string PathString;
141 #endif
142 PathString* g_log_file_name = nullptr;
143 
144 // This file is lazily opened and the handle may be nullptr
145 FileHandle g_log_file = nullptr;
146 
147 // What should be prepended to each message?
148 bool g_log_process_id = false;
149 bool g_log_thread_id = false;
150 bool g_log_timestamp = true;
151 bool g_log_tickcount = false;
152 
153 // Should we pop up fatal debug messages in a dialog?
154 bool show_error_dialogs = false;
155 
156 // An assert handler override specified by the client to be called instead of
157 // the debug message dialog and process termination. Assert handlers are stored
158 // in stack to allow overriding and restoring.
159 base::LazyInstance<base::stack<LogAssertHandlerFunction>>::Leaky
160     log_assert_handler_stack = LAZY_INSTANCE_INITIALIZER;
161 
162 // A log message handler that gets notified of every log message we process.
163 LogMessageHandlerFunction log_message_handler = nullptr;
164 
165 // Helper functions to wrap platform differences.
166 
CurrentProcessId()167 int32_t CurrentProcessId() {
168 #if defined(OS_WIN)
169   return GetCurrentProcessId();
170 #elif defined(OS_FUCHSIA)
171   zx_info_handle_basic_t basic = {};
172   zx_object_get_info(zx_process_self(), ZX_INFO_HANDLE_BASIC, &basic,
173                      sizeof(basic), nullptr, nullptr);
174   return basic.koid;
175 #elif defined(OS_POSIX)
176   return getpid();
177 #endif
178 }
179 
TickCount()180 uint64_t TickCount() {
181 #if defined(OS_WIN)
182   return GetTickCount();
183 #elif defined(OS_FUCHSIA)
184   return zx_clock_get(ZX_CLOCK_MONOTONIC) /
185          static_cast<zx_time_t>(base::Time::kNanosecondsPerMicrosecond);
186 #elif defined(OS_MACOSX)
187   return mach_absolute_time();
188 #elif defined(OS_NACL)
189   // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
190   // So we have to use clock() for now.
191   return clock();
192 #elif defined(OS_POSIX)
193   struct timespec ts;
194   clock_gettime(CLOCK_MONOTONIC, &ts);
195 
196   uint64_t absolute_micro = static_cast<int64_t>(ts.tv_sec) * 1000000 +
197                             static_cast<int64_t>(ts.tv_nsec) / 1000;
198 
199   return absolute_micro;
200 #endif
201 }
202 
DeleteFilePath(const PathString & log_name)203 void DeleteFilePath(const PathString& log_name) {
204 #if defined(OS_WIN)
205   DeleteFile(log_name.c_str());
206 #elif defined(OS_NACL)
207   // Do nothing; unlink() isn't supported on NaCl.
208 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
209   unlink(log_name.c_str());
210 #else
211 #error Unsupported platform
212 #endif
213 }
214 
GetDefaultLogFile()215 PathString GetDefaultLogFile() {
216 #if defined(OS_WIN)
217   // On Windows we use the same path as the exe.
218   wchar_t module_name[MAX_PATH];
219   GetModuleFileName(nullptr, module_name, MAX_PATH);
220 
221   PathString log_name = module_name;
222   PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
223   if (last_backslash != PathString::npos)
224     log_name.erase(last_backslash + 1);
225   log_name += L"debug.log";
226   return log_name;
227 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
228   // On other platforms we just use the current directory.
229   return PathString("debug.log");
230 #endif
231 }
232 
233 // We don't need locks on Windows for atomically appending to files. The OS
234 // provides this functionality.
235 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
236 // This class acts as a wrapper for locking the logging files.
237 // LoggingLock::Init() should be called from the main thread before any logging
238 // is done. Then whenever logging, be sure to have a local LoggingLock
239 // instance on the stack. This will ensure that the lock is unlocked upon
240 // exiting the frame.
241 // LoggingLocks can not be nested.
242 class LoggingLock {
243  public:
LoggingLock()244   LoggingLock() {
245     LockLogging();
246   }
247 
~LoggingLock()248   ~LoggingLock() {
249     UnlockLogging();
250   }
251 
Init(LogLockingState lock_log,const PathChar * new_log_file)252   static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
253     if (initialized)
254       return;
255     lock_log_file = lock_log;
256 
257     if (lock_log_file != LOCK_LOG_FILE)
258       log_lock = new base::internal::LockImpl();
259 
260     initialized = true;
261   }
262 
263  private:
LockLogging()264   static void LockLogging() {
265     if (lock_log_file == LOCK_LOG_FILE) {
266       pthread_mutex_lock(&log_mutex);
267     } else {
268       // use the lock
269       log_lock->Lock();
270     }
271   }
272 
UnlockLogging()273   static void UnlockLogging() {
274     if (lock_log_file == LOCK_LOG_FILE) {
275       pthread_mutex_unlock(&log_mutex);
276     } else {
277       log_lock->Unlock();
278     }
279   }
280 
281   // The lock is used if log file locking is false. It helps us avoid problems
282   // with multiple threads writing to the log file at the same time.  Use
283   // LockImpl directly instead of using Lock, because Lock makes logging calls.
284   static base::internal::LockImpl* log_lock;
285 
286   // When we don't use a lock, we are using a global mutex. We need to do this
287   // because LockFileEx is not thread safe.
288   static pthread_mutex_t log_mutex;
289 
290   static bool initialized;
291   static LogLockingState lock_log_file;
292 };
293 
294 // static
295 bool LoggingLock::initialized = false;
296 // static
297 base::internal::LockImpl* LoggingLock::log_lock = nullptr;
298 // static
299 LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
300 
301 pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
302 
303 #endif  // OS_POSIX || OS_FUCHSIA
304 
305 // Called by logging functions to ensure that |g_log_file| is initialized
306 // and can be used for writing. Returns false if the file could not be
307 // initialized. |g_log_file| will be nullptr in this case.
InitializeLogFileHandle()308 bool InitializeLogFileHandle() {
309   if (g_log_file)
310     return true;
311 
312   if (!g_log_file_name) {
313     // Nobody has called InitLogging to specify a debug log file, so here we
314     // initialize the log file name to a default.
315     g_log_file_name = new PathString(GetDefaultLogFile());
316   }
317 
318   if ((g_logging_destination & LOG_TO_FILE) != 0) {
319 #if defined(OS_WIN)
320     // The FILE_APPEND_DATA access mask ensures that the file is atomically
321     // appended to across accesses from multiple threads.
322     // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
323     // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
324     g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
325                             FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
326                             OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
327     if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
328       // We are intentionally not using FilePath or FileUtil here to reduce the
329       // dependencies of the logging implementation. For e.g. FilePath and
330       // FileUtil depend on shell32 and user32.dll. This is not acceptable for
331       // some consumers of base logging like chrome_elf, etc.
332       // Please don't change the code below to use FilePath.
333       // try the current directory
334       wchar_t system_buffer[MAX_PATH];
335       system_buffer[0] = 0;
336       DWORD len = ::GetCurrentDirectory(arraysize(system_buffer),
337                                         system_buffer);
338       if (len == 0 || len > arraysize(system_buffer))
339         return false;
340 
341       *g_log_file_name = system_buffer;
342       // Append a trailing backslash if needed.
343       if (g_log_file_name->back() != L'\\')
344         *g_log_file_name += L"\\";
345       *g_log_file_name += L"debug.log";
346 
347       g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
348                               FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
349                               OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
350       if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
351         g_log_file = nullptr;
352         return false;
353       }
354     }
355 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
356     g_log_file = fopen(g_log_file_name->c_str(), "a");
357     if (g_log_file == nullptr)
358       return false;
359 #else
360 #error Unsupported platform
361 #endif
362   }
363 
364   return true;
365 }
366 
CloseFile(FileHandle log)367 void CloseFile(FileHandle log) {
368 #if defined(OS_WIN)
369   CloseHandle(log);
370 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
371   fclose(log);
372 #else
373 #error Unsupported platform
374 #endif
375 }
376 
CloseLogFileUnlocked()377 void CloseLogFileUnlocked() {
378   if (!g_log_file)
379     return;
380 
381   CloseFile(g_log_file);
382   g_log_file = nullptr;
383 }
384 
385 }  // namespace
386 
387 #if DCHECK_IS_CONFIGURABLE
388 // In DCHECK-enabled Chrome builds, allow the meaning of LOG_DCHECK to be
389 // determined at run-time. We default it to INFO, to avoid it triggering
390 // crashes before the run-time has explicitly chosen the behaviour.
391 BASE_EXPORT logging::LogSeverity LOG_DCHECK = LOG_INFO;
392 #endif  // DCHECK_IS_CONFIGURABLE
393 
394 // This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
395 // an object of the correct type on the LHS of the unused part of the ternary
396 // operator.
397 std::ostream* g_swallow_stream;
398 
LoggingSettings()399 LoggingSettings::LoggingSettings()
400     : logging_dest(LOG_DEFAULT),
401       log_file(nullptr),
402       lock_log(LOCK_LOG_FILE),
403       delete_old(APPEND_TO_OLD_LOG_FILE) {}
404 
BaseInitLoggingImpl(const LoggingSettings & settings)405 bool BaseInitLoggingImpl(const LoggingSettings& settings) {
406 #if defined(OS_NACL)
407   // Can log only to the system debug log.
408   CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
409 #endif
410   if (base::CommandLine::InitializedForCurrentProcess()) {
411     base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
412     // Don't bother initializing |g_vlog_info| unless we use one of the
413     // vlog switches.
414     if (command_line->HasSwitch(switches::kV) ||
415         command_line->HasSwitch(switches::kVModule)) {
416       // NOTE: If |g_vlog_info| has already been initialized, it might be in use
417       // by another thread. Don't delete the old VLogInfo, just create a second
418       // one. We keep track of both to avoid memory leak warnings.
419       CHECK(!g_vlog_info_prev);
420       g_vlog_info_prev = g_vlog_info;
421 
422       g_vlog_info =
423           new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
424                        command_line->GetSwitchValueASCII(switches::kVModule),
425                        &g_min_log_level);
426     }
427   }
428 
429   g_logging_destination = settings.logging_dest;
430 
431   // ignore file options unless logging to file is set.
432   if ((g_logging_destination & LOG_TO_FILE) == 0)
433     return true;
434 
435 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
436   LoggingLock::Init(settings.lock_log, settings.log_file);
437   LoggingLock logging_lock;
438 #endif
439 
440   // Calling InitLogging twice or after some log call has already opened the
441   // default log file will re-initialize to the new options.
442   CloseLogFileUnlocked();
443 
444   if (!g_log_file_name)
445     g_log_file_name = new PathString();
446   *g_log_file_name = settings.log_file;
447   if (settings.delete_old == DELETE_OLD_LOG_FILE)
448     DeleteFilePath(*g_log_file_name);
449 
450   return InitializeLogFileHandle();
451 }
452 
SetMinLogLevel(int level)453 void SetMinLogLevel(int level) {
454   g_min_log_level = std::min(LOG_FATAL, level);
455 }
456 
GetMinLogLevel()457 int GetMinLogLevel() {
458   return g_min_log_level;
459 }
460 
ShouldCreateLogMessage(int severity)461 bool ShouldCreateLogMessage(int severity) {
462   if (severity < g_min_log_level)
463     return false;
464 
465   // Return true here unless we know ~LogMessage won't do anything. Note that
466   // ~LogMessage writes to stderr if severity_ >= kAlwaysPrintErrorLevel, even
467   // when g_logging_destination is LOG_NONE.
468   return g_logging_destination != LOG_NONE || log_message_handler ||
469          severity >= kAlwaysPrintErrorLevel;
470 }
471 
GetVlogVerbosity()472 int GetVlogVerbosity() {
473   return std::max(-1, LOG_INFO - GetMinLogLevel());
474 }
475 
GetVlogLevelHelper(const char * file,size_t N)476 int GetVlogLevelHelper(const char* file, size_t N) {
477   DCHECK_GT(N, 0U);
478   // Note: |g_vlog_info| may change on a different thread during startup
479   // (but will always be valid or nullptr).
480   VlogInfo* vlog_info = g_vlog_info;
481   return vlog_info ?
482       vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
483       GetVlogVerbosity();
484 }
485 
SetLogItems(bool enable_process_id,bool enable_thread_id,bool enable_timestamp,bool enable_tickcount)486 void SetLogItems(bool enable_process_id, bool enable_thread_id,
487                  bool enable_timestamp, bool enable_tickcount) {
488   g_log_process_id = enable_process_id;
489   g_log_thread_id = enable_thread_id;
490   g_log_timestamp = enable_timestamp;
491   g_log_tickcount = enable_tickcount;
492 }
493 
SetShowErrorDialogs(bool enable_dialogs)494 void SetShowErrorDialogs(bool enable_dialogs) {
495   show_error_dialogs = enable_dialogs;
496 }
497 
ScopedLogAssertHandler(LogAssertHandlerFunction handler)498 ScopedLogAssertHandler::ScopedLogAssertHandler(
499     LogAssertHandlerFunction handler) {
500   log_assert_handler_stack.Get().push(std::move(handler));
501 }
502 
~ScopedLogAssertHandler()503 ScopedLogAssertHandler::~ScopedLogAssertHandler() {
504   log_assert_handler_stack.Get().pop();
505 }
506 
SetLogMessageHandler(LogMessageHandlerFunction handler)507 void SetLogMessageHandler(LogMessageHandlerFunction handler) {
508   log_message_handler = handler;
509 }
510 
GetLogMessageHandler()511 LogMessageHandlerFunction GetLogMessageHandler() {
512   return log_message_handler;
513 }
514 
515 // Explicit instantiations for commonly used comparisons.
516 template std::string* MakeCheckOpString<int, int>(
517     const int&, const int&, const char* names);
518 template std::string* MakeCheckOpString<unsigned long, unsigned long>(
519     const unsigned long&, const unsigned long&, const char* names);
520 template std::string* MakeCheckOpString<unsigned long, unsigned int>(
521     const unsigned long&, const unsigned int&, const char* names);
522 template std::string* MakeCheckOpString<unsigned int, unsigned long>(
523     const unsigned int&, const unsigned long&, const char* names);
524 template std::string* MakeCheckOpString<std::string, std::string>(
525     const std::string&, const std::string&, const char* name);
526 
MakeCheckOpValueString(std::ostream * os,std::nullptr_t p)527 void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p) {
528   (*os) << "nullptr";
529 }
530 
531 #if !defined(NDEBUG)
532 // Displays a message box to the user with the error message in it.
533 // Used for fatal messages, where we close the app simultaneously.
534 // This is for developers only; we don't use this in circumstances
535 // (like release builds) where users could see it, since users don't
536 // understand these messages anyway.
DisplayDebugMessageInDialog(const std::string & str)537 void DisplayDebugMessageInDialog(const std::string& str) {
538   if (str.empty())
539     return;
540 
541   if (!show_error_dialogs)
542     return;
543 
544 #if defined(OS_WIN)
545   // We intentionally don't implement a dialog on other platforms.
546   // You can just look at stderr.
547   MessageBoxW(nullptr, base::UTF8ToUTF16(str).c_str(), L"Fatal error",
548               MB_OK | MB_ICONHAND | MB_TOPMOST);
549 #endif  // defined(OS_WIN)
550 }
551 #endif  // !defined(NDEBUG)
552 
553 #if defined(OS_WIN)
SaveLastError()554 LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
555 }
556 
~SaveLastError()557 LogMessage::SaveLastError::~SaveLastError() {
558   ::SetLastError(last_error_);
559 }
560 #endif  // defined(OS_WIN)
561 
LogMessage(const char * file,int line,LogSeverity severity)562 LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
563     : severity_(severity), file_(file), line_(line) {
564   Init(file, line);
565 }
566 
LogMessage(const char * file,int line,const char * condition)567 LogMessage::LogMessage(const char* file, int line, const char* condition)
568     : severity_(LOG_FATAL), file_(file), line_(line) {
569   Init(file, line);
570   stream_ << "Check failed: " << condition << ". ";
571 }
572 
LogMessage(const char * file,int line,std::string * result)573 LogMessage::LogMessage(const char* file, int line, std::string* result)
574     : severity_(LOG_FATAL), file_(file), line_(line) {
575   Init(file, line);
576   stream_ << "Check failed: " << *result;
577   delete result;
578 }
579 
LogMessage(const char * file,int line,LogSeverity severity,std::string * result)580 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
581                        std::string* result)
582     : severity_(severity), file_(file), line_(line) {
583   Init(file, line);
584   stream_ << "Check failed: " << *result;
585   delete result;
586 }
587 
~LogMessage()588 LogMessage::~LogMessage() {
589   size_t stack_start = stream_.tellp();
590 #if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__) && \
591     !defined(OS_AIX)
592   if (severity_ == LOG_FATAL && !base::debug::BeingDebugged()) {
593     // Include a stack trace on a fatal, unless a debugger is attached.
594     base::debug::StackTrace trace;
595     stream_ << std::endl;  // Newline to separate from log message.
596     trace.OutputToStream(&stream_);
597   }
598 #endif
599   stream_ << std::endl;
600   std::string str_newline(stream_.str());
601 
602   // Give any log message handler first dibs on the message.
603   if (log_message_handler &&
604       log_message_handler(severity_, file_, line_,
605                           message_start_, str_newline)) {
606     // The handler took care of it, no further processing.
607     return;
608   }
609 
610   if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
611 #if defined(OS_WIN)
612     OutputDebugStringA(str_newline.c_str());
613 #elif defined(OS_MACOSX)
614     // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
615     // stderr. If stderr is /dev/null, also log via ASL (Apple System Log) or
616     // its successor OS_LOG. If there's something weird about stderr, assume
617     // that log messages are going nowhere and log via ASL/OS_LOG too.
618     // Messages logged via ASL/OS_LOG show up in Console.app.
619     //
620     // Programs started by launchd, as UI applications normally are, have had
621     // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
622     // a pipe to launchd, which logged what it received (see log_redirect_fd in
623     // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
624     //
625     // Another alternative would be to determine whether stderr is a pipe to
626     // launchd and avoid logging via ASL only in that case. See 10.7.5
627     // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
628     // both stderr and ASL/OS_LOG even in tests, where it's undesirable to log
629     // to the system log at all.
630     //
631     // Note that the ASL client by default discards messages whose levels are
632     // below ASL_LEVEL_NOTICE. It's possible to change that with
633     // asl_set_filter(), but this is pointless because syslogd normally applies
634     // the same filter.
635     const bool log_to_system = []() {
636       struct stat stderr_stat;
637       if (fstat(fileno(stderr), &stderr_stat) == -1) {
638         return true;
639       }
640       if (!S_ISCHR(stderr_stat.st_mode)) {
641         return false;
642       }
643 
644       struct stat dev_null_stat;
645       if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
646         return true;
647       }
648 
649       return !S_ISCHR(dev_null_stat.st_mode) ||
650              stderr_stat.st_rdev == dev_null_stat.st_rdev;
651     }();
652 
653     if (log_to_system) {
654       // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
655       // CF-1153.18/CFUtilities.c __CFLogCString().
656       CFBundleRef main_bundle = CFBundleGetMainBundle();
657       CFStringRef main_bundle_id_cf =
658           main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
659       std::string main_bundle_id =
660           main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
661                             : std::string("");
662 #if defined(USE_ASL)
663       // The facility is set to the main bundle ID if available. Otherwise,
664       // "com.apple.console" is used.
665       const class ASLClient {
666        public:
667         explicit ASLClient(const std::string& facility)
668             : client_(asl_open(nullptr, facility.c_str(), ASL_OPT_NO_DELAY)) {}
669         ~ASLClient() { asl_close(client_); }
670 
671         aslclient get() const { return client_; }
672 
673        private:
674         aslclient client_;
675         DISALLOW_COPY_AND_ASSIGN(ASLClient);
676       } asl_client(main_bundle_id.empty() ? main_bundle_id
677                                           : "com.apple.console");
678 
679       const class ASLMessage {
680        public:
681         ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
682         ~ASLMessage() { asl_free(message_); }
683 
684         aslmsg get() const { return message_; }
685 
686        private:
687         aslmsg message_;
688         DISALLOW_COPY_AND_ASSIGN(ASLMessage);
689       } asl_message;
690 
691       // By default, messages are only readable by the admin group. Explicitly
692       // make them readable by the user generating the messages.
693       char euid_string[12];
694       snprintf(euid_string, arraysize(euid_string), "%d", geteuid());
695       asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
696 
697       // Map Chrome log severities to ASL log levels.
698       const char* const asl_level_string = [](LogSeverity severity) {
699         // ASL_LEVEL_* are ints, but ASL needs equivalent strings. This
700         // non-obvious two-step macro trick achieves what's needed.
701         // https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
702 #define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
703 #define ASL_LEVEL_STR_X(level) #level
704         switch (severity) {
705           case LOG_INFO:
706             return ASL_LEVEL_STR(ASL_LEVEL_INFO);
707           case LOG_WARNING:
708             return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
709           case LOG_ERROR:
710             return ASL_LEVEL_STR(ASL_LEVEL_ERR);
711           case LOG_FATAL:
712             return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
713           default:
714             return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
715                                 : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
716         }
717 #undef ASL_LEVEL_STR
718 #undef ASL_LEVEL_STR_X
719       }(severity_);
720       asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
721 
722       asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
723 
724       asl_send(asl_client.get(), asl_message.get());
725 #else   // !defined(USE_ASL)
726       const class OSLog {
727        public:
728         explicit OSLog(const char* subsystem)
729             : os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
730                                 : OS_LOG_DEFAULT) {}
731         ~OSLog() {
732           if (os_log_ != OS_LOG_DEFAULT) {
733             os_release(os_log_);
734           }
735         }
736         os_log_t get() const { return os_log_; }
737 
738        private:
739         os_log_t os_log_;
740         DISALLOW_COPY_AND_ASSIGN(OSLog);
741       } log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str());
742       const os_log_type_t os_log_type = [](LogSeverity severity) {
743         switch (severity) {
744           case LOG_INFO:
745             return OS_LOG_TYPE_INFO;
746           case LOG_WARNING:
747             return OS_LOG_TYPE_DEFAULT;
748           case LOG_ERROR:
749             return OS_LOG_TYPE_ERROR;
750           case LOG_FATAL:
751             return OS_LOG_TYPE_FAULT;
752           default:
753             return severity < 0 ? OS_LOG_TYPE_DEBUG : OS_LOG_TYPE_DEFAULT;
754         }
755       }(severity_);
756       os_log_with_type(log.get(), os_log_type, "%{public}s",
757                        str_newline.c_str());
758 #endif  // defined(USE_ASL)
759     }
760 #elif defined(OS_ANDROID)
761     android_LogPriority priority =
762         (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
763     switch (severity_) {
764       case LOG_INFO:
765         priority = ANDROID_LOG_INFO;
766         break;
767       case LOG_WARNING:
768         priority = ANDROID_LOG_WARN;
769         break;
770       case LOG_ERROR:
771         priority = ANDROID_LOG_ERROR;
772         break;
773       case LOG_FATAL:
774         priority = ANDROID_LOG_FATAL;
775         break;
776     }
777 #if 0 // This is for building Chromium browser on Android.
778     __android_log_write(priority, "chromium", str_newline.c_str());
779 #else
780     __android_log_write(
781         priority,
782         base::CommandLine::InitializedForCurrentProcess() ?
783             base::CommandLine::ForCurrentProcess()->
784                 GetProgram().BaseName().value().c_str() : nullptr,
785         str_newline.c_str());
786 #endif  // 0
787 #endif  // defined(OS_ANDROID)
788     ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
789     fflush(stderr);
790   } else if (severity_ >= kAlwaysPrintErrorLevel) {
791     // When we're only outputting to a log file, above a certain log level, we
792     // should still output to stderr so that we can better detect and diagnose
793     // problems with unit tests, especially on the buildbots.
794     ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
795     fflush(stderr);
796   }
797 
798   // write to log file
799   if ((g_logging_destination & LOG_TO_FILE) != 0) {
800     // We can have multiple threads and/or processes, so try to prevent them
801     // from clobbering each other's writes.
802     // If the client app did not call InitLogging, and the lock has not
803     // been created do it now. We do this on demand, but if two threads try
804     // to do this at the same time, there will be a race condition to create
805     // the lock. This is why InitLogging should be called from the main
806     // thread at the beginning of execution.
807 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
808     LoggingLock::Init(LOCK_LOG_FILE, nullptr);
809     LoggingLock logging_lock;
810 #endif
811     if (InitializeLogFileHandle()) {
812 #if defined(OS_WIN)
813       DWORD num_written;
814       WriteFile(g_log_file,
815                 static_cast<const void*>(str_newline.c_str()),
816                 static_cast<DWORD>(str_newline.length()),
817                 &num_written,
818                 nullptr);
819 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
820       ignore_result(fwrite(
821           str_newline.data(), str_newline.size(), 1, g_log_file));
822       fflush(g_log_file);
823 #else
824 #error Unsupported platform
825 #endif
826     }
827   }
828 
829   if (severity_ == LOG_FATAL) {
830     // Write the log message to the global activity tracker, if running.
831     base::debug::GlobalActivityTracker* tracker =
832         base::debug::GlobalActivityTracker::Get();
833     if (tracker)
834       tracker->RecordLogMessage(str_newline);
835 
836     // Ensure the first characters of the string are on the stack so they
837     // are contained in minidumps for diagnostic purposes.
838     DEBUG_ALIAS_FOR_CSTR(str_stack, str_newline.c_str(), 1024);
839 
840     if (log_assert_handler_stack.IsCreated() &&
841         !log_assert_handler_stack.Get().empty()) {
842       LogAssertHandlerFunction log_assert_handler =
843           log_assert_handler_stack.Get().top();
844 
845       if (log_assert_handler) {
846         log_assert_handler.Run(
847             file_, line_,
848             base::StringPiece(str_newline.c_str() + message_start_,
849                               stack_start - message_start_),
850             base::StringPiece(str_newline.c_str() + stack_start));
851       }
852     } else {
853       // Don't use the string with the newline, get a fresh version to send to
854       // the debug message process. We also don't display assertions to the
855       // user in release mode. The enduser can't do anything with this
856       // information, and displaying message boxes when the application is
857       // hosed can cause additional problems.
858 #ifndef NDEBUG
859       if (!base::debug::BeingDebugged()) {
860         // Displaying a dialog is unnecessary when debugging and can complicate
861         // debugging.
862         DisplayDebugMessageInDialog(stream_.str());
863       }
864 #endif
865       // Crash the process to generate a dump.
866       base::debug::BreakDebugger();
867     }
868   }
869 }
870 
871 // writes the common header info to the stream
Init(const char * file,int line)872 void LogMessage::Init(const char* file, int line) {
873   base::StringPiece filename(file);
874   size_t last_slash_pos = filename.find_last_of("\\/");
875   if (last_slash_pos != base::StringPiece::npos)
876     filename.remove_prefix(last_slash_pos + 1);
877 
878   // TODO(darin): It might be nice if the columns were fixed width.
879 
880   stream_ <<  '[';
881   if (g_log_process_id)
882     stream_ << CurrentProcessId() << ':';
883   if (g_log_thread_id)
884     stream_ << base::PlatformThread::CurrentId() << ':';
885   if (g_log_timestamp) {
886 #if defined(OS_WIN)
887     SYSTEMTIME local_time;
888     GetLocalTime(&local_time);
889     stream_ << std::setfill('0')
890             << std::setw(2) << local_time.wMonth
891             << std::setw(2) << local_time.wDay
892             << '/'
893             << std::setw(2) << local_time.wHour
894             << std::setw(2) << local_time.wMinute
895             << std::setw(2) << local_time.wSecond
896             << '.'
897             << std::setw(3)
898             << local_time.wMilliseconds
899             << ':';
900 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
901     timeval tv;
902     gettimeofday(&tv, nullptr);
903     time_t t = tv.tv_sec;
904     struct tm local_time;
905     localtime_r(&t, &local_time);
906     struct tm* tm_time = &local_time;
907     stream_ << std::setfill('0')
908             << std::setw(2) << 1 + tm_time->tm_mon
909             << std::setw(2) << tm_time->tm_mday
910             << '/'
911             << std::setw(2) << tm_time->tm_hour
912             << std::setw(2) << tm_time->tm_min
913             << std::setw(2) << tm_time->tm_sec
914             << '.'
915             << std::setw(6) << tv.tv_usec
916             << ':';
917 #else
918 #error Unsupported platform
919 #endif
920   }
921   if (g_log_tickcount)
922     stream_ << TickCount() << ':';
923   if (severity_ >= 0)
924     stream_ << log_severity_name(severity_);
925   else
926     stream_ << "VERBOSE" << -severity_;
927 
928   stream_ << ":" << filename << "(" << line << ")] ";
929 
930   message_start_ = stream_.str().length();
931 }
932 
933 #if defined(OS_WIN)
934 // This has already been defined in the header, but defining it again as DWORD
935 // ensures that the type used in the header is equivalent to DWORD. If not,
936 // the redefinition is a compile error.
937 typedef DWORD SystemErrorCode;
938 #endif
939 
GetLastSystemErrorCode()940 SystemErrorCode GetLastSystemErrorCode() {
941 #if defined(OS_WIN)
942   return ::GetLastError();
943 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
944   return errno;
945 #endif
946 }
947 
SystemErrorCodeToString(SystemErrorCode error_code)948 BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
949 #if defined(OS_WIN)
950   const int kErrorMessageBufferSize = 256;
951   char msgbuf[kErrorMessageBufferSize];
952   DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
953   DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
954                              arraysize(msgbuf), nullptr);
955   if (len) {
956     // Messages returned by system end with line breaks.
957     return base::CollapseWhitespaceASCII(msgbuf, true) +
958            base::StringPrintf(" (0x%lX)", error_code);
959   }
960   return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)",
961                             GetLastError(), error_code);
962 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
963   return base::safe_strerror(error_code) +
964          base::StringPrintf(" (%d)", error_code);
965 #endif  // defined(OS_WIN)
966 }
967 
968 
969 #if defined(OS_WIN)
Win32ErrorLogMessage(const char * file,int line,LogSeverity severity,SystemErrorCode err)970 Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
971                                            int line,
972                                            LogSeverity severity,
973                                            SystemErrorCode err)
974     : err_(err),
975       log_message_(file, line, severity) {
976 }
977 
~Win32ErrorLogMessage()978 Win32ErrorLogMessage::~Win32ErrorLogMessage() {
979   stream() << ": " << SystemErrorCodeToString(err_);
980   // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
981   // field) and use Alias in hopes that it makes it into crash dumps.
982   DWORD last_error = err_;
983   base::debug::Alias(&last_error);
984 }
985 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
ErrnoLogMessage(const char * file,int line,LogSeverity severity,SystemErrorCode err)986 ErrnoLogMessage::ErrnoLogMessage(const char* file,
987                                  int line,
988                                  LogSeverity severity,
989                                  SystemErrorCode err)
990     : err_(err),
991       log_message_(file, line, severity) {
992 }
993 
~ErrnoLogMessage()994 ErrnoLogMessage::~ErrnoLogMessage() {
995   stream() << ": " << SystemErrorCodeToString(err_);
996   // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
997   // field) and use Alias in hopes that it makes it into crash dumps.
998   int last_error = err_;
999   base::debug::Alias(&last_error);
1000 }
1001 #endif  // defined(OS_WIN)
1002 
CloseLogFile()1003 void CloseLogFile() {
1004 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
1005   LoggingLock logging_lock;
1006 #endif
1007   CloseLogFileUnlocked();
1008 }
1009 
RawLog(int level,const char * message)1010 void RawLog(int level, const char* message) {
1011   if (level >= g_min_log_level && message) {
1012     size_t bytes_written = 0;
1013     const size_t message_len = strlen(message);
1014     int rv;
1015     while (bytes_written < message_len) {
1016       rv = HANDLE_EINTR(
1017           write(STDERR_FILENO, message + bytes_written,
1018                 message_len - bytes_written));
1019       if (rv < 0) {
1020         // Give up, nothing we can do now.
1021         break;
1022       }
1023       bytes_written += rv;
1024     }
1025 
1026     if (message_len > 0 && message[message_len - 1] != '\n') {
1027       do {
1028         rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
1029         if (rv < 0) {
1030           // Give up, nothing we can do now.
1031           break;
1032         }
1033       } while (rv != 1);
1034     }
1035   }
1036 
1037   if (level == LOG_FATAL)
1038     base::debug::BreakDebugger();
1039 }
1040 
1041 // This was defined at the beginning of this file.
1042 #undef write
1043 
1044 #if defined(OS_WIN)
IsLoggingToFileEnabled()1045 bool IsLoggingToFileEnabled() {
1046   return g_logging_destination & LOG_TO_FILE;
1047 }
1048 
GetLogFileFullPath()1049 std::wstring GetLogFileFullPath() {
1050   if (g_log_file_name)
1051     return *g_log_file_name;
1052   return std::wstring();
1053 }
1054 #endif
1055 
LogErrorNotReached(const char * file,int line)1056 BASE_EXPORT void LogErrorNotReached(const char* file, int line) {
1057   LogMessage(file, line, LOG_ERROR).stream()
1058       << "NOTREACHED() hit.";
1059 }
1060 
1061 }  // namespace logging
1062 
operator <<(std::ostream & out,const wchar_t * wstr)1063 std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
1064   return out << (wstr ? base::WideToUTF8(wstr) : std::string());
1065 }
1066