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