1 // Copyright 2012 The Chromium Authors
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 #ifdef BASE_CHECK_H_
8 #error "logging.h should not include check.h"
9 #endif
10
11 #include <limits.h>
12 #include <stdint.h>
13
14 #include <atomic>
15 #include <memory>
16 #include <tuple>
17 #include <vector>
18
19 #include "base/base_export.h"
20 #include "base/debug/crash_logging.h"
21 #include "base/immediate_crash.h"
22 #include "base/pending_task.h"
23 #include "base/process/process_handle.h"
24 #include "base/strings/string_piece.h"
25 #include "base/task/common/task_annotator.h"
26 #include "base/trace_event/base_tracing.h"
27 #include "build/build_config.h"
28
29 #if !BUILDFLAG(IS_NACL)
30 #include "base/auto_reset.h"
31 #include "base/debug/crash_logging.h"
32 #endif // !BUILDFLAG(IS_NACL)
33
34 #if defined(LEAK_SANITIZER) && !BUILDFLAG(IS_NACL)
35 #include "base/debug/leak_annotations.h"
36 #endif // defined(LEAK_SANITIZER) && !BUILDFLAG(IS_NACL)
37
38 #if BUILDFLAG(IS_WIN)
39 #include <io.h>
40 #include <windows.h>
41 typedef HANDLE FileHandle;
42 // Windows warns on using write(). It prefers _write().
43 #define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
44 // Windows doesn't define STDERR_FILENO. Define it here.
45 #define STDERR_FILENO 2
46
47 #elif BUILDFLAG(IS_APPLE)
48 #include <CoreFoundation/CoreFoundation.h>
49 #include <mach-o/dyld.h>
50 #include <mach/mach.h>
51 #include <mach/mach_time.h>
52 #include <os/log.h>
53
54 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
55 #if BUILDFLAG(IS_NACL)
56 #include <sys/time.h> // timespec doesn't seem to be in <time.h>
57 #endif
58 #include <time.h>
59 #endif
60
61 #if BUILDFLAG(IS_FUCHSIA)
62 #include "base/fuchsia/scoped_fx_logger.h"
63 #endif
64
65 #if BUILDFLAG(IS_ANDROID)
66 #include <android/log.h>
67 #endif
68
69 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
70 #include <errno.h>
71 #include <paths.h>
72 #include <stdio.h>
73 #include <stdlib.h>
74 #include <string.h>
75 #include <sys/stat.h>
76 #define MAX_PATH PATH_MAX
77 typedef FILE* FileHandle;
78 #endif
79
80 #include <algorithm>
81 #include <cstring>
82 #include <ctime>
83 #include <iomanip>
84 #include <ostream>
85 #include <string>
86 #include <utility>
87
88 #include "base/base_switches.h"
89 #include "base/command_line.h"
90 #include "base/containers/stack.h"
91 #include "base/debug/alias.h"
92 #include "base/debug/debugger.h"
93 #include "base/debug/stack_trace.h"
94 #include "base/debug/task_trace.h"
95 #include "base/functional/callback.h"
96 #include "base/no_destructor.h"
97 #include "base/path_service.h"
98 #include "base/posix/eintr_wrapper.h"
99 #include "base/strings/string_split.h"
100 #include "base/strings/string_util.h"
101 #include "base/strings/stringprintf.h"
102 #include "base/strings/sys_string_conversions.h"
103 #include "base/strings/utf_string_conversions.h"
104 #include "base/synchronization/lock.h"
105 #include "base/test/scoped_logging_settings.h"
106 #include "base/threading/platform_thread.h"
107 #include "base/vlog.h"
108 #include "build/chromeos_buildflags.h"
109
110 #if BUILDFLAG(IS_WIN)
111 #include "base/win/win_util.h"
112 #endif
113
114 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
115 #include "base/posix/safe_strerror.h"
116 #endif
117
118 #if BUILDFLAG(IS_CHROMEOS_ASH)
119 #include "base/files/scoped_file.h"
120 #endif
121
122 namespace logging {
123
124 namespace {
125
126 int g_min_log_level = 0;
127
128 #if BUILDFLAG(USE_RUNTIME_VLOG)
129 // NOTE: Once |g_vlog_info| has been initialized, it might be in use
130 // by another thread. Never delete the old VLogInfo, just create a second
131 // one and overwrite. We need to use leak-san annotations on this intentional
132 // leak.
133 //
134 // This can be read/written on multiple threads. In tests we don't see that
135 // causing a problem as updates tend to happen early. Atomic ensures there are
136 // no problems. To avoid some of the overhead of Atomic, we use
137 // |load(std::memory_order_acquire)| and |store(...,
138 // std::memory_order_release)| when reading or writing. This guarantees that the
139 // referenced object is available at the time the |g_vlog_info| is read and that
140 // |g_vlog_info| is updated atomically.
141 //
142 // Do not access this directly. You must use |GetVlogInfo|, |InitializeVlogInfo|
143 // and/or |ExchangeVlogInfo|.
144 std::atomic<VlogInfo*> g_vlog_info = nullptr;
145
GetVlogInfo()146 VlogInfo* GetVlogInfo() {
147 return g_vlog_info.load(std::memory_order_acquire);
148 }
149
150 // Sets g_vlog_info if it is not already set. Checking that it's not already set
151 // prevents logging initialization (which can come late in test setup) from
152 // overwriting values set via ScopedVmoduleSwitches.
InitializeVlogInfo(VlogInfo * vlog_info)153 bool InitializeVlogInfo(VlogInfo* vlog_info) {
154 VlogInfo* previous_vlog_info = nullptr;
155 return g_vlog_info.compare_exchange_strong(previous_vlog_info, vlog_info);
156 }
157
ExchangeVlogInfo(VlogInfo * vlog_info)158 VlogInfo* ExchangeVlogInfo(VlogInfo* vlog_info) {
159 return g_vlog_info.exchange(vlog_info);
160 }
161
162 // Creates a VlogInfo from the commandline if it has been initialized and if it
163 // contains relevant switches, otherwise this returns |nullptr|.
VlogInfoFromCommandLine()164 std::unique_ptr<VlogInfo> VlogInfoFromCommandLine() {
165 if (!base::CommandLine::InitializedForCurrentProcess())
166 return nullptr;
167 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
168 if (!command_line->HasSwitch(switches::kV) &&
169 !command_line->HasSwitch(switches::kVModule)) {
170 return nullptr;
171 }
172 #if defined(LEAK_SANITIZER) && !BUILDFLAG(IS_NACL)
173 // See comments on |g_vlog_info|.
174 ScopedLeakSanitizerDisabler lsan_disabler;
175 #endif // defined(LEAK_SANITIZER)
176 return std::make_unique<VlogInfo>(
177 command_line->GetSwitchValueASCII(switches::kV),
178 command_line->GetSwitchValueASCII(switches::kVModule), &g_min_log_level);
179 }
180
181 // If the commandline is initialized for the current process this will
182 // initialize g_vlog_info. If there are no VLOG switches, it will initialize it
183 // to |nullptr|.
MaybeInitializeVlogInfo()184 void MaybeInitializeVlogInfo() {
185 if (base::CommandLine::InitializedForCurrentProcess()) {
186 std::unique_ptr<VlogInfo> vlog_info = VlogInfoFromCommandLine();
187 if (vlog_info) {
188 // VlogInfoFromCommandLine is annotated with ScopedLeakSanitizerDisabler
189 // so it's allowed to leak. If the object was installed, we release it.
190 if (InitializeVlogInfo(vlog_info.get())) {
191 vlog_info.release();
192 }
193 }
194 }
195 }
196 #endif // BUILDFLAG(USE_RUNTIME_VLOG)
197
198 #if !BUILDFLAG(USE_RUNTIME_VLOG) && DCHECK_IS_ON()
199
200 // Warn developers that vlog command line settings are being ignored.
MaybeWarnVmodule()201 void MaybeWarnVmodule() {
202 if (base::CommandLine::InitializedForCurrentProcess()) {
203 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
204 if (command_line->HasSwitch(switches::kV) ||
205 command_line->HasSwitch(switches::kVModule)) {
206 LOG(WARNING)
207 << "--" << switches::kV << " and --" << switches::kVModule
208 << " are currently ignored. See comments in base/logging.h on "
209 "proper usage of USE_RUNTIME_VLOG.";
210 }
211 }
212 }
213
214 #endif // !BUILDFLAG(USE_RUNTIME_VLOG) && DCHECK_IS_ON()
215
216 const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
217 static_assert(LOGGING_NUM_SEVERITIES == std::size(log_severity_names),
218 "Incorrect number of log_severity_names");
219
log_severity_name(int severity)220 const char* log_severity_name(int severity) {
221 if (severity >= 0 && severity < LOGGING_NUM_SEVERITIES)
222 return log_severity_names[severity];
223 return "UNKNOWN";
224 }
225
226 // Specifies the process' logging sink(s), represented as a combination of
227 // LoggingDestination values joined by bitwise OR.
228 uint32_t g_logging_destination = LOG_DEFAULT;
229
230 #if BUILDFLAG(IS_CHROMEOS)
231 // Specifies the format of log header for chrome os.
232 LogFormat g_log_format = LogFormat::LOG_FORMAT_SYSLOG;
233 #endif
234
235 #if BUILDFLAG(IS_FUCHSIA)
236 // Retains system logging structures.
GetScopedFxLogger()237 base::ScopedFxLogger& GetScopedFxLogger() {
238 static base::NoDestructor<base::ScopedFxLogger> logger;
239 return *logger;
240 }
241 #endif
242
243 // For LOGGING_ERROR and above, always print to stderr.
244 const int kAlwaysPrintErrorLevel = LOGGING_ERROR;
245
246 // Which log file to use? This is initialized by InitLogging or
247 // will be lazily initialized to the default value when it is
248 // first needed.
249 using PathString = base::FilePath::StringType;
250 PathString* g_log_file_name = nullptr;
251
252 // This file is lazily opened and the handle may be nullptr
253 FileHandle g_log_file = nullptr;
254
255 // What should be prepended to each message?
256 bool g_log_process_id = false;
257 bool g_log_thread_id = false;
258 bool g_log_timestamp = true;
259 bool g_log_tickcount = false;
260 const char* g_log_prefix = nullptr;
261
262 // Should we pop up fatal debug messages in a dialog?
263 bool show_error_dialogs = false;
264
265 // An assert handler override specified by the client to be called instead of
266 // the debug message dialog and process termination. Assert handlers are stored
267 // in stack to allow overriding and restoring.
GetLogAssertHandlerStack()268 base::stack<LogAssertHandlerFunction>& GetLogAssertHandlerStack() {
269 static base::NoDestructor<base::stack<LogAssertHandlerFunction>> instance;
270 return *instance;
271 }
272
273 // A log message handler that gets notified of every log message we process.
274 LogMessageHandlerFunction g_log_message_handler = nullptr;
275
TickCount()276 uint64_t TickCount() {
277 #if BUILDFLAG(IS_WIN)
278 return GetTickCount();
279 #elif BUILDFLAG(IS_FUCHSIA)
280 return static_cast<uint64_t>(
281 zx_clock_get_monotonic() /
282 static_cast<zx_time_t>(base::Time::kNanosecondsPerMicrosecond));
283 #elif BUILDFLAG(IS_APPLE)
284 return mach_absolute_time();
285 #elif BUILDFLAG(IS_NACL)
286 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
287 // So we have to use clock() for now.
288 return clock();
289 #elif BUILDFLAG(IS_POSIX)
290 struct timespec ts;
291 clock_gettime(CLOCK_MONOTONIC, &ts);
292
293 uint64_t absolute_micro = static_cast<uint64_t>(ts.tv_sec) * 1000000 +
294 static_cast<uint64_t>(ts.tv_nsec) / 1000;
295
296 return absolute_micro;
297 #endif
298 }
299
DeleteFilePath(const PathString & log_name)300 void DeleteFilePath(const PathString& log_name) {
301 #if BUILDFLAG(IS_WIN)
302 DeleteFile(log_name.c_str());
303 #elif BUILDFLAG(IS_NACL)
304 // Do nothing; unlink() isn't supported on NaCl.
305 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
306 unlink(log_name.c_str());
307 #else
308 #error Unsupported platform
309 #endif
310 }
311
GetDefaultLogFile()312 PathString GetDefaultLogFile() {
313 #if BUILDFLAG(IS_WIN)
314 // On Windows we use the same path as the exe.
315 wchar_t module_name[MAX_PATH];
316 GetModuleFileName(nullptr, module_name, MAX_PATH);
317
318 PathString log_name = module_name;
319 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
320 if (last_backslash != PathString::npos)
321 log_name.erase(last_backslash + 1);
322 log_name += FILE_PATH_LITERAL("debug.log");
323 return log_name;
324 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
325 // On other platforms we just use the current directory.
326 return PathString("debug.log");
327 #endif
328 }
329
330 // We don't need locks on Windows for atomically appending to files. The OS
331 // provides this functionality.
332 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
333
334 // Provides a lock to synchronize appending to the log file across
335 // threads. This can be required to support NFS file systems even on OSes that
336 // provide atomic append operations in most cases. It should be noted that this
337 // lock is not not shared across processes. When using NFS filesystems
338 // protection against clobbering between different processes will be best-effort
339 // and provided by the OS. See
340 // https://man7.org/linux/man-pages/man2/open.2.html.
341 //
342 // The lock also protects initializing and closing the log file which can
343 // happen concurrently with logging on some platforms like ChromeOS that need to
344 // redirect logging by calling BaseInitLoggingImpl() twice.
GetLoggingLock()345 base::Lock& GetLoggingLock() {
346 static base::NoDestructor<base::Lock> lock;
347 return *lock;
348 }
349
350 #endif // BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
351
352 // Called by logging functions to ensure that |g_log_file| is initialized
353 // and can be used for writing. Returns false if the file could not be
354 // initialized. |g_log_file| will be nullptr in this case.
InitializeLogFileHandle()355 bool InitializeLogFileHandle() {
356 if (g_log_file)
357 return true;
358
359 if (!g_log_file_name) {
360 // Nobody has called InitLogging to specify a debug log file, so here we
361 // initialize the log file name to a default.
362 g_log_file_name = new PathString(GetDefaultLogFile());
363 }
364
365 if ((g_logging_destination & LOG_TO_FILE) == 0)
366 return true;
367
368 #if BUILDFLAG(IS_WIN)
369 // The FILE_APPEND_DATA access mask ensures that the file is atomically
370 // appended to across accesses from multiple threads.
371 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
372 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
373 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
374 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
375 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
376 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
377 // We are intentionally not using FilePath or FileUtil here to reduce the
378 // dependencies of the logging implementation. For e.g. FilePath and
379 // FileUtil depend on shell32 and user32.dll. This is not acceptable for
380 // some consumers of base logging like chrome_elf, etc.
381 // Please don't change the code below to use FilePath.
382 // try the current directory
383 wchar_t system_buffer[MAX_PATH];
384 system_buffer[0] = 0;
385 DWORD len = ::GetCurrentDirectory(std::size(system_buffer), system_buffer);
386 if (len == 0 || len > std::size(system_buffer))
387 return false;
388
389 *g_log_file_name = system_buffer;
390 // Append a trailing backslash if needed.
391 if (g_log_file_name->back() != L'\\')
392 *g_log_file_name += FILE_PATH_LITERAL("\\");
393 *g_log_file_name += FILE_PATH_LITERAL("debug.log");
394
395 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
396 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
397 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
398 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
399 g_log_file = nullptr;
400 return false;
401 }
402 }
403 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
404 g_log_file = fopen(g_log_file_name->c_str(), "a");
405 if (g_log_file == nullptr)
406 return false;
407 #else
408 #error Unsupported platform
409 #endif
410
411 return true;
412 }
413
CloseFile(FileHandle log)414 void CloseFile(FileHandle log) {
415 #if BUILDFLAG(IS_WIN)
416 CloseHandle(log);
417 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
418 fclose(log);
419 #else
420 #error Unsupported platform
421 #endif
422 }
423
CloseLogFileUnlocked()424 void CloseLogFileUnlocked() {
425 if (!g_log_file)
426 return;
427
428 CloseFile(g_log_file);
429 g_log_file = nullptr;
430
431 // If we initialized logging via an externally-provided file descriptor, we
432 // won't have a log path set and shouldn't try to reopen the log file.
433 if (!g_log_file_name)
434 g_logging_destination &= ~LOG_TO_FILE;
435 }
436
437 #if BUILDFLAG(IS_FUCHSIA)
LogSeverityToFuchsiaLogSeverity(LogSeverity severity)438 inline FuchsiaLogSeverity LogSeverityToFuchsiaLogSeverity(
439 LogSeverity severity) {
440 switch (severity) {
441 case LOGGING_INFO:
442 return FUCHSIA_LOG_INFO;
443 case LOGGING_WARNING:
444 return FUCHSIA_LOG_WARNING;
445 case LOGGING_ERROR:
446 return FUCHSIA_LOG_ERROR;
447 case LOGGING_FATAL:
448 // Don't use FX_LOG_FATAL, otherwise fx_logger_log() will abort().
449 return FUCHSIA_LOG_ERROR;
450 }
451 if (severity > -3) {
452 // LOGGING_VERBOSE levels 1 and 2.
453 return FUCHSIA_LOG_DEBUG;
454 }
455 // LOGGING_VERBOSE levels 3 and higher, or incorrect levels.
456 return FUCHSIA_LOG_TRACE;
457 }
458 #endif // BUILDFLAG(IS_FUCHSIA)
459
WriteToFd(int fd,const char * data,size_t length)460 void WriteToFd(int fd, const char* data, size_t length) {
461 size_t bytes_written = 0;
462 long rv;
463 while (bytes_written < length) {
464 rv = HANDLE_EINTR(write(fd, data + bytes_written, length - bytes_written));
465 if (rv < 0) {
466 // Give up, nothing we can do now.
467 break;
468 }
469 bytes_written += static_cast<size_t>(rv);
470 }
471 }
472
SetLogFatalCrashKey(LogMessage * log_message)473 void SetLogFatalCrashKey(LogMessage* log_message) {
474 #if !BUILDFLAG(IS_NACL)
475 // In case of an out-of-memory condition, this code could be reentered when
476 // constructing and storing the key. Using a static is not thread-safe, but if
477 // multiple threads are in the process of a fatal crash at the same time, this
478 // should work.
479 static bool guarded = false;
480 if (guarded)
481 return;
482
483 base::AutoReset<bool> guard(&guarded, true);
484
485 static auto* const crash_key = base::debug::AllocateCrashKeyString(
486 "LOG_FATAL", base::debug::CrashKeySize::Size1024);
487 base::debug::SetCrashKeyString(crash_key, log_message->BuildCrashString());
488
489 #endif // !BUILDFLAG(IS_NACL)
490 }
491
BuildCrashString(const char * file,int line,const char * message_without_prefix)492 std::string BuildCrashString(const char* file,
493 int line,
494 const char* message_without_prefix) {
495 // Only log last path component.
496 if (file) {
497 const char* slash = strrchr(file,
498 #if BUILDFLAG(IS_WIN)
499 '\\'
500 #else
501 '/'
502 #endif // BUILDFLAG(IS_WIN)
503 );
504 if (slash) {
505 file = slash + 1;
506 }
507 }
508
509 return base::StringPrintf("%s:%d: %s", file, line, message_without_prefix);
510 }
511
512 // Invokes macro to record trace event when a log message is emitted.
traceLogMessage(const char * file,int line,const std::string & message)513 void traceLogMessage(const char* file, int line, const std::string& message) {
514 TRACE_EVENT_INSTANT("log", "LogMessage", [&](perfetto::EventContext ctx) {
515 perfetto::protos::pbzero::LogMessage* log = ctx.event()->set_log_message();
516 log->set_source_location_iid(base::trace_event::InternedSourceLocation::Get(
517 &ctx, base::trace_event::TraceSourceLocation(/*function_name=*/nullptr,
518 file, line)));
519 log->set_body_iid(
520 base::trace_event::InternedLogMessage::Get(&ctx, message));
521 });
522 }
523
524 } // namespace
525
526 #if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
527 // In DCHECK-enabled Chrome builds, allow the meaning of LOGGING_DCHECK to be
528 // determined at run-time. We default it to INFO, to avoid it triggering
529 // crashes before the run-time has explicitly chosen the behaviour.
530 BASE_EXPORT logging::LogSeverity LOGGING_DCHECK = LOGGING_INFO;
531 #endif // BUILDFLAG(DCHECK_IS_CONFIGURABLE)
532
533 // This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
534 // an object of the correct type on the LHS of the unused part of the ternary
535 // operator.
536 std::ostream* g_swallow_stream;
537
BaseInitLoggingImpl(const LoggingSettings & settings)538 bool BaseInitLoggingImpl(const LoggingSettings& settings) {
539 #if BUILDFLAG(IS_NACL)
540 // Can log only to the system debug log and stderr.
541 CHECK_EQ(settings.logging_dest & ~(LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR),
542 0u);
543 #endif
544
545 #if BUILDFLAG(IS_CHROMEOS)
546 g_log_format = settings.log_format;
547 #endif
548
549 #if BUILDFLAG(USE_RUNTIME_VLOG)
550 MaybeInitializeVlogInfo();
551 #endif // BUILDFLAG(USE_RUNTIME_VLOG)
552
553 #if !BUILDFLAG(USE_RUNTIME_VLOG) && DCHECK_IS_ON()
554 MaybeWarnVmodule();
555 #endif // !BUILDFLAG(USE_RUNTIME_VLOG) && DCHECK_IS_ON()
556
557 g_logging_destination = settings.logging_dest;
558
559 #if BUILDFLAG(IS_FUCHSIA)
560 if (g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) {
561 GetScopedFxLogger() = base::ScopedFxLogger::CreateForProcess();
562 }
563 #endif
564
565 // ignore file options unless logging to file is set.
566 if ((g_logging_destination & LOG_TO_FILE) == 0)
567 return true;
568
569 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
570 base::AutoLock guard(GetLoggingLock());
571 #endif
572
573 // Calling InitLogging twice or after some log call has already opened the
574 // default log file will re-initialize to the new options.
575 CloseLogFileUnlocked();
576
577 #if BUILDFLAG(IS_CHROMEOS_ASH)
578 if (settings.log_file) {
579 DCHECK(!settings.log_file_path);
580 g_log_file = settings.log_file;
581 return true;
582 }
583 #endif
584
585 DCHECK(settings.log_file_path) << "LOG_TO_FILE set but no log_file_path!";
586
587 if (!g_log_file_name)
588 g_log_file_name = new PathString();
589 *g_log_file_name = settings.log_file_path;
590 if (settings.delete_old == DELETE_OLD_LOG_FILE)
591 DeleteFilePath(*g_log_file_name);
592
593 return InitializeLogFileHandle();
594 }
595
SetMinLogLevel(int level)596 void SetMinLogLevel(int level) {
597 g_min_log_level = std::min(LOGGING_FATAL, level);
598 }
599
GetMinLogLevel()600 int GetMinLogLevel() {
601 return g_min_log_level;
602 }
603
ShouldCreateLogMessage(int severity)604 bool ShouldCreateLogMessage(int severity) {
605 if (severity < g_min_log_level)
606 return false;
607
608 // Return true here unless we know ~LogMessage won't do anything.
609 return g_logging_destination != LOG_NONE || g_log_message_handler ||
610 severity >= kAlwaysPrintErrorLevel;
611 }
612
613 // Returns true when LOG_TO_STDERR flag is set, or |severity| is high.
614 // If |severity| is high then true will be returned when no log destinations are
615 // set, or only LOG_TO_FILE is set, since that is useful for local development
616 // and debugging.
ShouldLogToStderr(int severity)617 bool ShouldLogToStderr(int severity) {
618 if (g_logging_destination & LOG_TO_STDERR)
619 return true;
620
621 #if BUILDFLAG(IS_FUCHSIA)
622 // Fuchsia will persist data logged to stdio by a component, so do not emit
623 // logs to stderr unless explicitly configured to do so.
624 return false;
625 #else
626 if (severity >= kAlwaysPrintErrorLevel)
627 return (g_logging_destination & ~LOG_TO_FILE) == LOG_NONE;
628 return false;
629 #endif
630 }
631
GetVlogVerbosity()632 int GetVlogVerbosity() {
633 return std::max(-1, LOG_INFO - GetMinLogLevel());
634 }
635
GetVlogLevelHelper(const char * file,size_t N)636 int GetVlogLevelHelper(const char* file, size_t N) {
637 DCHECK_GT(N, 0U);
638
639 #if BUILDFLAG(USE_RUNTIME_VLOG)
640 // Note: |g_vlog_info| may change on a different thread during startup
641 // (but will always be valid or nullptr).
642 VlogInfo* vlog_info = GetVlogInfo();
643 return vlog_info ?
644 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
645 GetVlogVerbosity();
646 #else
647 return GetVlogVerbosity();
648 #endif // BUILDFLAG(USE_RUNTIME_VLOG)
649 }
650
SetLogItems(bool enable_process_id,bool enable_thread_id,bool enable_timestamp,bool enable_tickcount)651 void SetLogItems(bool enable_process_id, bool enable_thread_id,
652 bool enable_timestamp, bool enable_tickcount) {
653 g_log_process_id = enable_process_id;
654 g_log_thread_id = enable_thread_id;
655 g_log_timestamp = enable_timestamp;
656 g_log_tickcount = enable_tickcount;
657 }
658
SetLogPrefix(const char * prefix)659 void SetLogPrefix(const char* prefix) {
660 DCHECK(!prefix ||
661 base::ContainsOnlyChars(prefix, "abcdefghijklmnopqrstuvwxyz"));
662 g_log_prefix = prefix;
663 }
664
SetShowErrorDialogs(bool enable_dialogs)665 void SetShowErrorDialogs(bool enable_dialogs) {
666 show_error_dialogs = enable_dialogs;
667 }
668
ScopedLogAssertHandler(LogAssertHandlerFunction handler)669 ScopedLogAssertHandler::ScopedLogAssertHandler(
670 LogAssertHandlerFunction handler) {
671 GetLogAssertHandlerStack().push(std::move(handler));
672 }
673
~ScopedLogAssertHandler()674 ScopedLogAssertHandler::~ScopedLogAssertHandler() {
675 GetLogAssertHandlerStack().pop();
676 }
677
SetLogMessageHandler(LogMessageHandlerFunction handler)678 void SetLogMessageHandler(LogMessageHandlerFunction handler) {
679 g_log_message_handler = handler;
680 }
681
GetLogMessageHandler()682 LogMessageHandlerFunction GetLogMessageHandler() {
683 return g_log_message_handler;
684 }
685
686 #if !defined(NDEBUG)
687 // Displays a message box to the user with the error message in it.
688 // Used for fatal messages, where we close the app simultaneously.
689 // This is for developers only; we don't use this in circumstances
690 // (like release builds) where users could see it, since users don't
691 // understand these messages anyway.
DisplayDebugMessageInDialog(const std::string & str)692 void DisplayDebugMessageInDialog(const std::string& str) {
693 if (str.empty())
694 return;
695
696 if (!show_error_dialogs)
697 return;
698
699 #if BUILDFLAG(IS_WIN)
700 // We intentionally don't implement a dialog on other platforms.
701 // You can just look at stderr.
702 if (base::win::IsUser32AndGdi32Available()) {
703 MessageBoxW(nullptr, base::as_wcstr(base::UTF8ToUTF16(str)), L"Fatal error",
704 MB_OK | MB_ICONHAND | MB_TOPMOST);
705 } else {
706 OutputDebugStringW(base::as_wcstr(base::UTF8ToUTF16(str)));
707 }
708 #endif // BUILDFLAG(IS_WIN)
709 }
710 #endif // !defined(NDEBUG)
711
LogMessage(const char * file,int line,LogSeverity severity)712 LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
713 : severity_(severity), file_(file), line_(line) {
714 Init(file, line);
715 }
716
LogMessage(const char * file,int line,const char * condition)717 LogMessage::LogMessage(const char* file, int line, const char* condition)
718 : severity_(LOGGING_FATAL), file_(file), line_(line) {
719 Init(file, line);
720 stream_ << "Check failed: " << condition << ". ";
721 }
722
~LogMessage()723 LogMessage::~LogMessage() {
724 size_t stack_start = stream_.str().length();
725 #if !defined(OFFICIAL_BUILD) && !BUILDFLAG(IS_NACL) && !defined(__UCLIBC__) && \
726 !BUILDFLAG(IS_AIX)
727 if (severity_ == LOGGING_FATAL && !base::debug::BeingDebugged()) {
728 // Include a stack trace on a fatal, unless a debugger is attached.
729 base::debug::StackTrace stack_trace;
730 stream_ << std::endl; // Newline to separate from log message.
731 stack_trace.OutputToStream(&stream_);
732 base::debug::TaskTrace task_trace;
733 if (!task_trace.empty())
734 task_trace.OutputToStream(&stream_);
735
736 // Include the IPC context, if any.
737 // TODO(chrisha): Integrate with symbolization once those tools exist!
738 const auto* task = base::TaskAnnotator::CurrentTaskForThread();
739 if (task && task->ipc_hash) {
740 stream_ << "IPC message handler context: "
741 << base::StringPrintf("0x%08X", task->ipc_hash) << std::endl;
742 }
743
744 // Include the crash keys, if any.
745 base::debug::OutputCrashKeysToStream(stream_);
746 }
747 #endif
748 stream_ << std::endl;
749 std::string str_newline(stream_.str());
750 traceLogMessage(
751 file_, line_,
752 std::string(base::StringPiece(str_newline).substr(message_start_)));
753
754 if (severity_ == LOGGING_FATAL)
755 SetLogFatalCrashKey(this);
756
757 // Give any log message handler first dibs on the message.
758 if (g_log_message_handler &&
759 g_log_message_handler(severity_, file_, line_, message_start_,
760 str_newline)) {
761 // The handler took care of it, no further processing.
762 return;
763 }
764
765 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
766 #if BUILDFLAG(IS_WIN)
767 OutputDebugStringA(str_newline.c_str());
768 #elif BUILDFLAG(IS_APPLE)
769 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
770 // stderr. If stderr is /dev/null, also log via os_log. If there's something
771 // weird about stderr, assume that log messages are going nowhere and log
772 // via os_log too. Messages logged via os_log show up in Console.app.
773 //
774 // Programs started by launchd, as UI applications normally are, have had
775 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
776 // a pipe to launchd, which logged what it received (see log_redirect_fd in
777 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
778 //
779 // Another alternative would be to determine whether stderr is a pipe to
780 // launchd and avoid logging via os_log only in that case. See 10.7.5
781 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
782 // both stderr and os_log even in tests, where it's undesirable to log to
783 // the system log at all.
784 const bool log_to_system = []() {
785 struct stat stderr_stat;
786 if (fstat(fileno(stderr), &stderr_stat) == -1) {
787 return true;
788 }
789 if (!S_ISCHR(stderr_stat.st_mode)) {
790 return false;
791 }
792
793 struct stat dev_null_stat;
794 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
795 return true;
796 }
797
798 return !S_ISCHR(dev_null_stat.st_mode) ||
799 stderr_stat.st_rdev == dev_null_stat.st_rdev;
800 }();
801
802 if (log_to_system) {
803 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
804 // CF-1153.18/CFUtilities.c __CFLogCString().
805 CFBundleRef main_bundle = CFBundleGetMainBundle();
806 CFStringRef main_bundle_id_cf =
807 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
808 std::string main_bundle_id =
809 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
810 : std::string("");
811
812 const class OSLog {
813 public:
814 explicit OSLog(const char* subsystem)
815 : os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
816 : OS_LOG_DEFAULT) {}
817 OSLog(const OSLog&) = delete;
818 OSLog& operator=(const OSLog&) = delete;
819 ~OSLog() {
820 if (os_log_ != OS_LOG_DEFAULT) {
821 os_release(os_log_);
822 }
823 }
824 os_log_t get() const { return os_log_; }
825
826 private:
827 os_log_t os_log_;
828 } log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str());
829 const os_log_type_t os_log_type = [](LogSeverity severity) {
830 switch (severity) {
831 case LOGGING_INFO:
832 return OS_LOG_TYPE_INFO;
833 case LOGGING_WARNING:
834 return OS_LOG_TYPE_DEFAULT;
835 case LOGGING_ERROR:
836 return OS_LOG_TYPE_ERROR;
837 case LOGGING_FATAL:
838 return OS_LOG_TYPE_FAULT;
839 case LOGGING_VERBOSE:
840 return OS_LOG_TYPE_DEBUG;
841 default:
842 return OS_LOG_TYPE_DEFAULT;
843 }
844 }(severity_);
845 os_log_with_type(log.get(), os_log_type, "%{public}s",
846 str_newline.c_str());
847 }
848 #elif BUILDFLAG(IS_ANDROID)
849 android_LogPriority priority =
850 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
851 switch (severity_) {
852 case LOGGING_INFO:
853 priority = ANDROID_LOG_INFO;
854 break;
855 case LOGGING_WARNING:
856 priority = ANDROID_LOG_WARN;
857 break;
858 case LOGGING_ERROR:
859 priority = ANDROID_LOG_ERROR;
860 break;
861 case LOGGING_FATAL:
862 priority = ANDROID_LOG_FATAL;
863 break;
864 }
865 const char kAndroidLogTag[] = "chromium";
866 #if DCHECK_IS_ON()
867 // Split the output by new lines to prevent the Android system from
868 // truncating the log.
869 std::vector<std::string> lines = base::SplitString(
870 str_newline, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
871 // str_newline has an extra newline appended to it (at the top of this
872 // function), so skip the last split element to avoid needlessly
873 // logging an empty string.
874 lines.pop_back();
875 for (const auto& line : lines)
876 __android_log_write(priority, kAndroidLogTag, line.c_str());
877 #else
878 // The Android system may truncate the string if it's too long.
879 __android_log_write(priority, kAndroidLogTag, str_newline.c_str());
880 #endif
881 #elif BUILDFLAG(IS_FUCHSIA)
882 // LogMessage() will silently drop the message if the logger is not valid.
883 // Skip the final character of |str_newline|, since LogMessage() will add
884 // a newline.
885 const auto message = base::StringPiece(str_newline).substr(message_start_);
886 GetScopedFxLogger().LogMessage(file_, static_cast<uint32_t>(line_),
887 message.substr(0, message.size() - 1),
888 LogSeverityToFuchsiaLogSeverity(severity_));
889 #endif // BUILDFLAG(IS_FUCHSIA)
890 }
891
892 if (ShouldLogToStderr(severity_)) {
893 // Not using fwrite() here, as there are crashes on Windows when CRT calls
894 // malloc() internally, triggering an OOM crash. This likely means that the
895 // process is close to OOM, but at least get the proper error message out,
896 // and give the caller a chance to free() up some resources. For instance if
897 // the calling code is:
898 //
899 // allocate_something();
900 // if (!TryToDoSomething()) {
901 // LOG(ERROR) << "Something went wrong";
902 // free_something();
903 // }
904 WriteToFd(STDERR_FILENO, str_newline.data(), str_newline.size());
905 }
906
907 if ((g_logging_destination & LOG_TO_FILE) != 0) {
908 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
909 // If the client app did not call InitLogging() and the lock has not
910 // been created it will be done now on calling GetLoggingLock(). We do this
911 // on demand, but if two threads try to do this at the same time, there will
912 // be a race condition to create the lock. This is why InitLogging should be
913 // called from the main thread at the beginning of execution.
914 base::AutoLock guard(GetLoggingLock());
915 #endif
916 if (InitializeLogFileHandle()) {
917 #if BUILDFLAG(IS_WIN)
918 DWORD num_written;
919 WriteFile(g_log_file,
920 static_cast<const void*>(str_newline.c_str()),
921 static_cast<DWORD>(str_newline.length()),
922 &num_written,
923 nullptr);
924 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
925 std::ignore =
926 fwrite(str_newline.data(), str_newline.size(), 1, g_log_file);
927 fflush(g_log_file);
928 #else
929 #error Unsupported platform
930 #endif
931 }
932 }
933
934 if (severity_ == LOGGING_FATAL) {
935 char str_stack[1024];
936 base::strlcpy(str_stack, str_newline.data(), std::size(str_stack));
937 base::debug::Alias(&str_stack);
938
939 if (!GetLogAssertHandlerStack().empty()) {
940 LogAssertHandlerFunction log_assert_handler =
941 GetLogAssertHandlerStack().top();
942
943 if (log_assert_handler) {
944 log_assert_handler.Run(
945 file_, line_,
946 base::StringPiece(str_newline.c_str() + message_start_,
947 stack_start - message_start_),
948 base::StringPiece(str_newline.c_str() + stack_start));
949 }
950 } else {
951 // Don't use the string with the newline, get a fresh version to send to
952 // the debug message process. We also don't display assertions to the
953 // user in release mode. The enduser can't do anything with this
954 // information, and displaying message boxes when the application is
955 // hosed can cause additional problems.
956 #ifndef NDEBUG
957 if (!base::debug::BeingDebugged()) {
958 // Displaying a dialog is unnecessary when debugging and can complicate
959 // debugging.
960 DisplayDebugMessageInDialog(stream_.str());
961 }
962 #endif
963
964 // Crash the process to generate a dump.
965 base::ImmediateCrash();
966 }
967 }
968 }
969
BuildCrashString() const970 std::string LogMessage::BuildCrashString() const {
971 return logging::BuildCrashString(file(), line(),
972 str().c_str() + message_start_);
973 }
974
975 // writes the common header info to the stream
Init(const char * file,int line)976 void LogMessage::Init(const char* file, int line) {
977 base::StringPiece filename(file);
978 size_t last_slash_pos = filename.find_last_of("\\/");
979 if (last_slash_pos != base::StringPiece::npos)
980 filename.remove_prefix(last_slash_pos + 1);
981
982 #if BUILDFLAG(IS_CHROMEOS)
983 if (g_log_format == LogFormat::LOG_FORMAT_SYSLOG) {
984 InitWithSyslogPrefix(
985 filename, line, TickCount(), log_severity_name(severity_), g_log_prefix,
986 g_log_process_id, g_log_thread_id, g_log_timestamp, g_log_tickcount);
987 } else
988 #endif // BUILDFLAG(IS_CHROMEOS)
989 {
990 // TODO(darin): It might be nice if the columns were fixed width.
991 stream_ << '[';
992 if (g_log_prefix)
993 stream_ << g_log_prefix << ':';
994 if (g_log_process_id)
995 stream_ << base::GetUniqueIdForProcess() << ':';
996 if (g_log_thread_id)
997 stream_ << base::PlatformThread::CurrentId() << ':';
998 if (g_log_timestamp) {
999 #if BUILDFLAG(IS_WIN)
1000 SYSTEMTIME local_time;
1001 GetLocalTime(&local_time);
1002 stream_ << std::setfill('0')
1003 << std::setw(2) << local_time.wMonth
1004 << std::setw(2) << local_time.wDay
1005 << '/'
1006 << std::setw(2) << local_time.wHour
1007 << std::setw(2) << local_time.wMinute
1008 << std::setw(2) << local_time.wSecond
1009 << '.'
1010 << std::setw(3) << local_time.wMilliseconds
1011 << ':';
1012 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
1013 timeval tv;
1014 gettimeofday(&tv, nullptr);
1015 time_t t = tv.tv_sec;
1016 struct tm local_time;
1017 localtime_r(&t, &local_time);
1018 struct tm* tm_time = &local_time;
1019 stream_ << std::setfill('0')
1020 << std::setw(2) << 1 + tm_time->tm_mon
1021 << std::setw(2) << tm_time->tm_mday
1022 << '/'
1023 << std::setw(2) << tm_time->tm_hour
1024 << std::setw(2) << tm_time->tm_min
1025 << std::setw(2) << tm_time->tm_sec
1026 << '.'
1027 << std::setw(6) << tv.tv_usec
1028 << ':';
1029 #else
1030 #error Unsupported platform
1031 #endif
1032 }
1033 if (g_log_tickcount)
1034 stream_ << TickCount() << ':';
1035 if (severity_ >= 0) {
1036 stream_ << log_severity_name(severity_);
1037 } else {
1038 stream_ << "VERBOSE" << -severity_;
1039 }
1040 stream_ << ":" << filename << "(" << line << ")] ";
1041 }
1042 message_start_ = stream_.str().length();
1043 }
1044
1045 #if BUILDFLAG(IS_WIN)
1046 // This has already been defined in the header, but defining it again as DWORD
1047 // ensures that the type used in the header is equivalent to DWORD. If not,
1048 // the redefinition is a compile error.
1049 typedef DWORD SystemErrorCode;
1050 #endif
1051
GetLastSystemErrorCode()1052 SystemErrorCode GetLastSystemErrorCode() {
1053 #if BUILDFLAG(IS_WIN)
1054 return ::GetLastError();
1055 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
1056 return errno;
1057 #endif
1058 }
1059
SystemErrorCodeToString(SystemErrorCode error_code)1060 BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
1061 #if BUILDFLAG(IS_WIN)
1062 const int kErrorMessageBufferSize = 256;
1063 char msgbuf[kErrorMessageBufferSize];
1064 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
1065 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
1066 std::size(msgbuf), nullptr);
1067 if (len) {
1068 // Messages returned by system end with line breaks.
1069 return base::CollapseWhitespaceASCII(msgbuf, true) +
1070 base::StringPrintf(" (0x%lX)", error_code);
1071 }
1072 return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)",
1073 GetLastError(), error_code);
1074 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
1075 return base::safe_strerror(error_code) +
1076 base::StringPrintf(" (%d)", error_code);
1077 #endif // BUILDFLAG(IS_WIN)
1078 }
1079
1080 #if BUILDFLAG(IS_WIN)
Win32ErrorLogMessage(const char * file,int line,LogSeverity severity,SystemErrorCode err)1081 Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
1082 int line,
1083 LogSeverity severity,
1084 SystemErrorCode err)
1085 : LogMessage(file, line, severity), err_(err) {}
1086
~Win32ErrorLogMessage()1087 Win32ErrorLogMessage::~Win32ErrorLogMessage() {
1088 stream() << ": " << SystemErrorCodeToString(err_);
1089 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1090 // field) and use Alias in hopes that it makes it into crash dumps.
1091 DWORD last_error = err_;
1092 base::debug::Alias(&last_error);
1093 }
1094 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
ErrnoLogMessage(const char * file,int line,LogSeverity severity,SystemErrorCode err)1095 ErrnoLogMessage::ErrnoLogMessage(const char* file,
1096 int line,
1097 LogSeverity severity,
1098 SystemErrorCode err)
1099 : LogMessage(file, line, severity), err_(err) {}
1100
~ErrnoLogMessage()1101 ErrnoLogMessage::~ErrnoLogMessage() {
1102 stream() << ": " << SystemErrorCodeToString(err_);
1103 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1104 // field) and use Alias in hopes that it makes it into crash dumps.
1105 int last_error = err_;
1106 base::debug::Alias(&last_error);
1107 }
1108 #endif // BUILDFLAG(IS_WIN)
1109
CloseLogFile()1110 void CloseLogFile() {
1111 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
1112 base::AutoLock guard(GetLoggingLock());
1113 #endif
1114 CloseLogFileUnlocked();
1115 }
1116
1117 #if BUILDFLAG(IS_CHROMEOS_ASH)
DuplicateLogFILE()1118 FILE* DuplicateLogFILE() {
1119 if ((g_logging_destination & LOG_TO_FILE) == 0 || !InitializeLogFileHandle())
1120 return nullptr;
1121
1122 int log_fd = fileno(g_log_file);
1123 if (log_fd == -1)
1124 return nullptr;
1125 base::ScopedFD dup_fd(dup(log_fd));
1126 if (dup_fd == -1)
1127 return nullptr;
1128 FILE* duplicate = fdopen(dup_fd.get(), "a");
1129 if (!duplicate)
1130 return nullptr;
1131 std::ignore = dup_fd.release();
1132 return duplicate;
1133 }
1134 #endif
1135
1136 // Used for testing. Declared in test/scoped_logging_settings.h.
ScopedLoggingSettings()1137 ScopedLoggingSettings::ScopedLoggingSettings()
1138 : min_log_level_(g_min_log_level),
1139 logging_destination_(g_logging_destination),
1140 #if BUILDFLAG(IS_CHROMEOS)
1141 log_format_(g_log_format),
1142 #endif // BUILDFLAG(IS_CHROMEOS_ASH)
1143 enable_process_id_(g_log_process_id),
1144 enable_thread_id_(g_log_thread_id),
1145 enable_timestamp_(g_log_timestamp),
1146 enable_tickcount_(g_log_tickcount),
1147 log_prefix_(g_log_prefix),
1148 message_handler_(g_log_message_handler) {
1149 if (g_log_file_name)
1150 log_file_name_ = std::make_unique<PathString>(*g_log_file_name);
1151 // Duplicating |g_log_file| is complex & unnecessary for this test helpers'
1152 // use-cases, and so long as |g_log_file_name| is set, it will be re-opened
1153 // automatically anyway, when required, so just close the existing one.
1154 if (g_log_file) {
1155 CHECK(g_log_file_name) << "Un-named |log_file| is not supported.";
1156 CloseLogFileUnlocked();
1157 }
1158 }
1159
~ScopedLoggingSettings()1160 ScopedLoggingSettings::~ScopedLoggingSettings() {
1161 // Re-initialize logging via the normal path. This will clean up old file
1162 // name and handle state, including re-initializing the VLOG internal state.
1163 CHECK(InitLogging({
1164 .logging_dest = logging_destination_,
1165 .log_file_path = log_file_name_ ? log_file_name_->data() : nullptr,
1166 #if BUILDFLAG(IS_CHROMEOS)
1167 .log_format = log_format_
1168 #endif
1169 })) << "~ScopedLoggingSettings() failed to restore settings.";
1170
1171 // Restore plain data settings.
1172 SetMinLogLevel(min_log_level_);
1173 SetLogItems(enable_process_id_, enable_thread_id_, enable_timestamp_,
1174 enable_tickcount_);
1175 SetLogPrefix(log_prefix_);
1176 SetLogMessageHandler(message_handler_);
1177 }
1178
1179 #if BUILDFLAG(IS_CHROMEOS)
SetLogFormat(LogFormat log_format) const1180 void ScopedLoggingSettings::SetLogFormat(LogFormat log_format) const {
1181 g_log_format = log_format;
1182 }
1183 #endif // BUILDFLAG(IS_CHROMEOS_ASH)
1184
RawLog(int level,const char * message)1185 void RawLog(int level, const char* message) {
1186 if (level >= g_min_log_level && message) {
1187 const size_t message_len = strlen(message);
1188 WriteToFd(STDERR_FILENO, message, message_len);
1189
1190 if (message_len > 0 && message[message_len - 1] != '\n') {
1191 long rv;
1192 do {
1193 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
1194 if (rv < 0) {
1195 // Give up, nothing we can do now.
1196 break;
1197 }
1198 } while (rv != 1);
1199 }
1200 }
1201
1202 if (level == LOGGING_FATAL)
1203 base::ImmediateCrash();
1204 }
1205
1206 // This was defined at the beginning of this file.
1207 #undef write
1208
1209 #if BUILDFLAG(IS_WIN)
IsLoggingToFileEnabled()1210 bool IsLoggingToFileEnabled() {
1211 return g_logging_destination & LOG_TO_FILE;
1212 }
1213
GetLogFileFullPath()1214 std::wstring GetLogFileFullPath() {
1215 if (g_log_file_name)
1216 return *g_log_file_name;
1217 return std::wstring();
1218 }
1219 #endif
1220
1221 #if !BUILDFLAG(USE_RUNTIME_VLOG)
GetDisableAllVLogLevel()1222 int GetDisableAllVLogLevel() {
1223 return -1;
1224 }
1225 #endif // !BUILDFLAG(USE_RUNTIME_VLOG)
1226
1227 // Used for testing. Declared in test/scoped_logging_settings.h.
1228 ScopedVmoduleSwitches::ScopedVmoduleSwitches() = default;
1229 #if BUILDFLAG(USE_RUNTIME_VLOG)
CreateVlogInfoWithSwitches(const std::string & vmodule_switch)1230 VlogInfo* ScopedVmoduleSwitches::CreateVlogInfoWithSwitches(
1231 const std::string& vmodule_switch) {
1232 // Try get a VlogInfo on which to base this.
1233 // First ensure that VLOG has been initialized.
1234 MaybeInitializeVlogInfo();
1235
1236 // Getting this now and setting it later is racy, however if a
1237 // ScopedVmoduleSwitches is being used on multiple threads that requires
1238 // further coordination and avoids this race.
1239 VlogInfo* base_vlog_info = GetVlogInfo();
1240 if (!base_vlog_info) {
1241 // Base is |nullptr|, so just create it from scratch.
1242 return new VlogInfo(/*v_switch_=*/"", vmodule_switch, &g_min_log_level);
1243 }
1244 return base_vlog_info->WithSwitches(vmodule_switch);
1245 }
1246
InitWithSwitches(const std::string & vmodule_switch)1247 void ScopedVmoduleSwitches::InitWithSwitches(
1248 const std::string& vmodule_switch) {
1249 // Make sure we are only initialized once.
1250 CHECK(!scoped_vlog_info_);
1251 {
1252 #if defined(LEAK_SANITIZER) && !BUILDFLAG(IS_NACL)
1253 // See comments on |g_vlog_info|.
1254 ScopedLeakSanitizerDisabler lsan_disabler;
1255 #endif // defined(LEAK_SANITIZER)
1256 scoped_vlog_info_ = CreateVlogInfoWithSwitches(vmodule_switch);
1257 }
1258 previous_vlog_info_ = ExchangeVlogInfo(scoped_vlog_info_);
1259 }
1260
~ScopedVmoduleSwitches()1261 ScopedVmoduleSwitches::~ScopedVmoduleSwitches() {
1262 VlogInfo* replaced_vlog_info = ExchangeVlogInfo(previous_vlog_info_);
1263 // Make sure something didn't replace our scoped VlogInfo while we weren't
1264 // looking.
1265 CHECK_EQ(replaced_vlog_info, scoped_vlog_info_);
1266 }
1267 #else
InitWithSwitches(const std::string & vmodule_switch)1268 void ScopedVmoduleSwitches::InitWithSwitches(
1269 const std::string& vmodule_switch) {}
1270
1271 ScopedVmoduleSwitches::~ScopedVmoduleSwitches() = default;
1272 #endif // BUILDFLAG(USE_RUNTIME_VLOG)
1273
1274 } // namespace logging
1275
operator <<(std::ostream & out,const wchar_t * wstr)1276 std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
1277 return out << (wstr ? base::WStringPiece(wstr) : base::WStringPiece());
1278 }
1279
operator <<(std::ostream & out,const std::wstring & wstr)1280 std::ostream& std::operator<<(std::ostream& out, const std::wstring& wstr) {
1281 return out << base::WStringPiece(wstr);
1282 }
1283
operator <<(std::ostream & out,const char16_t * str16)1284 std::ostream& std::operator<<(std::ostream& out, const char16_t* str16) {
1285 return out << (str16 ? base::StringPiece16(str16) : base::StringPiece16());
1286 }
1287
operator <<(std::ostream & out,const std::u16string & str16)1288 std::ostream& std::operator<<(std::ostream& out, const std::u16string& str16) {
1289 return out << base::StringPiece16(str16);
1290 }
1291