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