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