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