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