1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/logging.h"
6
7 #if defined(OS_WIN)
8 #include <io.h>
9 #include <windows.h>
10 typedef HANDLE FileHandle;
11 typedef HANDLE MutexHandle;
12 // Windows warns on using write(). It prefers _write().
13 #define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
14 // Windows doesn't define STDERR_FILENO. Define it here.
15 #define STDERR_FILENO 2
16 #elif defined(OS_MACOSX)
17 #include <mach/mach.h>
18 #include <mach/mach_time.h>
19 #include <mach-o/dyld.h>
20 #elif defined(OS_POSIX)
21 #if defined(OS_NACL)
22 #include <sys/time.h> // timespec doesn't seem to be in <time.h>
23 #else
24 #include <sys/syscall.h>
25 #endif
26 #include <time.h>
27 #endif
28
29 #if defined(OS_POSIX)
30 #include <errno.h>
31 #include <pthread.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #define MAX_PATH PATH_MAX
37 typedef FILE* FileHandle;
38 typedef pthread_mutex_t* MutexHandle;
39 #endif
40
41 #include <algorithm>
42 #include <cstring>
43 #include <ctime>
44 #include <iomanip>
45 #include <ostream>
46 #include <string>
47
48 #include "base/base_switches.h"
49 #include "base/command_line.h"
50 #include "base/debug/alias.h"
51 #include "base/debug/debugger.h"
52 #include "base/debug/stack_trace.h"
53 #include "base/posix/eintr_wrapper.h"
54 #include "base/strings/string_piece.h"
55 #include "base/strings/string_util.h"
56 #include "base/strings/stringprintf.h"
57 #include "base/strings/utf_string_conversions.h"
58 #include "base/synchronization/lock_impl.h"
59 #include "base/threading/platform_thread.h"
60 #include "base/vlog.h"
61 #if defined(OS_POSIX)
62 #include "base/safe_strerror_posix.h"
63 #endif
64
65 #if defined(OS_ANDROID)
66 #include <android/log.h>
67 #endif
68
69 namespace logging {
70
71 namespace {
72
73 VlogInfo* g_vlog_info = NULL;
74 VlogInfo* g_vlog_info_prev = NULL;
75
76 const char* const log_severity_names[LOG_NUM_SEVERITIES] = {
77 "INFO", "WARNING", "ERROR", "FATAL" };
78
log_severity_name(int severity)79 const char* log_severity_name(int severity)
80 {
81 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
82 return log_severity_names[severity];
83 return "UNKNOWN";
84 }
85
86 int min_log_level = 0;
87
88 LoggingDestination logging_destination = LOG_DEFAULT;
89
90 // For LOG_ERROR and above, always print to stderr.
91 const int kAlwaysPrintErrorLevel = LOG_ERROR;
92
93 // Which log file to use? This is initialized by InitLogging or
94 // will be lazily initialized to the default value when it is
95 // first needed.
96 #if defined(OS_WIN)
97 typedef std::wstring PathString;
98 #else
99 typedef std::string PathString;
100 #endif
101 PathString* log_file_name = NULL;
102
103 // this file is lazily opened and the handle may be NULL
104 FileHandle log_file = NULL;
105
106 // what should be prepended to each message?
107 bool log_process_id = false;
108 bool log_thread_id = false;
109 bool log_timestamp = true;
110 bool log_tickcount = false;
111
112 // Should we pop up fatal debug messages in a dialog?
113 bool show_error_dialogs = false;
114
115 // An assert handler override specified by the client to be called instead of
116 // the debug message dialog and process termination.
117 LogAssertHandlerFunction log_assert_handler = NULL;
118 // A log message handler that gets notified of every log message we process.
119 LogMessageHandlerFunction log_message_handler = NULL;
120
121 // Helper functions to wrap platform differences.
122
CurrentProcessId()123 int32 CurrentProcessId() {
124 #if defined(OS_WIN)
125 return GetCurrentProcessId();
126 #elif defined(OS_POSIX)
127 return getpid();
128 #endif
129 }
130
TickCount()131 uint64 TickCount() {
132 #if defined(OS_WIN)
133 return GetTickCount();
134 #elif defined(OS_MACOSX)
135 return mach_absolute_time();
136 #elif defined(OS_NACL)
137 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
138 // So we have to use clock() for now.
139 return clock();
140 #elif defined(OS_POSIX)
141 struct timespec ts;
142 clock_gettime(CLOCK_MONOTONIC, &ts);
143
144 uint64 absolute_micro =
145 static_cast<int64>(ts.tv_sec) * 1000000 +
146 static_cast<int64>(ts.tv_nsec) / 1000;
147
148 return absolute_micro;
149 #endif
150 }
151
DeleteFilePath(const PathString & log_name)152 void DeleteFilePath(const PathString& log_name) {
153 #if defined(OS_WIN)
154 DeleteFile(log_name.c_str());
155 #elif defined (OS_NACL)
156 // Do nothing; unlink() isn't supported on NaCl.
157 #else
158 unlink(log_name.c_str());
159 #endif
160 }
161
GetDefaultLogFile()162 PathString GetDefaultLogFile() {
163 #if defined(OS_WIN)
164 // On Windows we use the same path as the exe.
165 wchar_t module_name[MAX_PATH];
166 GetModuleFileName(NULL, module_name, MAX_PATH);
167
168 PathString log_file = module_name;
169 PathString::size_type last_backslash =
170 log_file.rfind('\\', log_file.size());
171 if (last_backslash != PathString::npos)
172 log_file.erase(last_backslash + 1);
173 log_file += L"debug.log";
174 return log_file;
175 #elif defined(OS_POSIX)
176 // On other platforms we just use the current directory.
177 return PathString("debug.log");
178 #endif
179 }
180
181 // This class acts as a wrapper for locking the logging files.
182 // LoggingLock::Init() should be called from the main thread before any logging
183 // is done. Then whenever logging, be sure to have a local LoggingLock
184 // instance on the stack. This will ensure that the lock is unlocked upon
185 // exiting the frame.
186 // LoggingLocks can not be nested.
187 class LoggingLock {
188 public:
LoggingLock()189 LoggingLock() {
190 LockLogging();
191 }
192
~LoggingLock()193 ~LoggingLock() {
194 UnlockLogging();
195 }
196
Init(LogLockingState lock_log,const PathChar * new_log_file)197 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
198 if (initialized)
199 return;
200 lock_log_file = lock_log;
201 if (lock_log_file == LOCK_LOG_FILE) {
202 #if defined(OS_WIN)
203 if (!log_mutex) {
204 std::wstring safe_name;
205 if (new_log_file)
206 safe_name = new_log_file;
207 else
208 safe_name = GetDefaultLogFile();
209 // \ is not a legal character in mutex names so we replace \ with /
210 std::replace(safe_name.begin(), safe_name.end(), '\\', '/');
211 std::wstring t(L"Global\\");
212 t.append(safe_name);
213 log_mutex = ::CreateMutex(NULL, FALSE, t.c_str());
214
215 if (log_mutex == NULL) {
216 #if DEBUG
217 // Keep the error code for debugging
218 int error = GetLastError(); // NOLINT
219 base::debug::BreakDebugger();
220 #endif
221 // Return nicely without putting initialized to true.
222 return;
223 }
224 }
225 #endif
226 } else {
227 log_lock = new base::internal::LockImpl();
228 }
229 initialized = true;
230 }
231
232 private:
LockLogging()233 static void LockLogging() {
234 if (lock_log_file == LOCK_LOG_FILE) {
235 #if defined(OS_WIN)
236 ::WaitForSingleObject(log_mutex, INFINITE);
237 // WaitForSingleObject could have returned WAIT_ABANDONED. We don't
238 // abort the process here. UI tests might be crashy sometimes,
239 // and aborting the test binary only makes the problem worse.
240 // We also don't use LOG macros because that might lead to an infinite
241 // loop. For more info see http://crbug.com/18028.
242 #elif defined(OS_POSIX)
243 pthread_mutex_lock(&log_mutex);
244 #endif
245 } else {
246 // use the lock
247 log_lock->Lock();
248 }
249 }
250
UnlockLogging()251 static void UnlockLogging() {
252 if (lock_log_file == LOCK_LOG_FILE) {
253 #if defined(OS_WIN)
254 ReleaseMutex(log_mutex);
255 #elif defined(OS_POSIX)
256 pthread_mutex_unlock(&log_mutex);
257 #endif
258 } else {
259 log_lock->Unlock();
260 }
261 }
262
263 // The lock is used if log file locking is false. It helps us avoid problems
264 // with multiple threads writing to the log file at the same time. Use
265 // LockImpl directly instead of using Lock, because Lock makes logging calls.
266 static base::internal::LockImpl* log_lock;
267
268 // When we don't use a lock, we are using a global mutex. We need to do this
269 // because LockFileEx is not thread safe.
270 #if defined(OS_WIN)
271 static MutexHandle log_mutex;
272 #elif defined(OS_POSIX)
273 static pthread_mutex_t log_mutex;
274 #endif
275
276 static bool initialized;
277 static LogLockingState lock_log_file;
278 };
279
280 // static
281 bool LoggingLock::initialized = false;
282 // static
283 base::internal::LockImpl* LoggingLock::log_lock = NULL;
284 // static
285 LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
286
287 #if defined(OS_WIN)
288 // static
289 MutexHandle LoggingLock::log_mutex = NULL;
290 #elif defined(OS_POSIX)
291 pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
292 #endif
293
294 // Called by logging functions to ensure that debug_file is initialized
295 // and can be used for writing. Returns false if the file could not be
296 // initialized. debug_file will be NULL in this case.
InitializeLogFileHandle()297 bool InitializeLogFileHandle() {
298 if (log_file)
299 return true;
300
301 if (!log_file_name) {
302 // Nobody has called InitLogging to specify a debug log file, so here we
303 // initialize the log file name to a default.
304 log_file_name = new PathString(GetDefaultLogFile());
305 }
306
307 if ((logging_destination & LOG_TO_FILE) != 0) {
308 #if defined(OS_WIN)
309 log_file = CreateFile(log_file_name->c_str(), GENERIC_WRITE,
310 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
311 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
312 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
313 // try the current directory
314 log_file = CreateFile(L".\\debug.log", GENERIC_WRITE,
315 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
316 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
317 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
318 log_file = NULL;
319 return false;
320 }
321 }
322 SetFilePointer(log_file, 0, 0, FILE_END);
323 #elif defined(OS_POSIX)
324 log_file = fopen(log_file_name->c_str(), "a");
325 if (log_file == NULL)
326 return false;
327 #endif
328 }
329
330 return true;
331 }
332
CloseFile(FileHandle log)333 void CloseFile(FileHandle log) {
334 #if defined(OS_WIN)
335 CloseHandle(log);
336 #else
337 fclose(log);
338 #endif
339 }
340
CloseLogFileUnlocked()341 void CloseLogFileUnlocked() {
342 if (!log_file)
343 return;
344
345 CloseFile(log_file);
346 log_file = NULL;
347 }
348
349 } // namespace
350
LoggingSettings()351 LoggingSettings::LoggingSettings()
352 : logging_dest(LOG_DEFAULT),
353 log_file(NULL),
354 lock_log(LOCK_LOG_FILE),
355 delete_old(APPEND_TO_OLD_LOG_FILE) {}
356
BaseInitLoggingImpl(const LoggingSettings & settings)357 bool BaseInitLoggingImpl(const LoggingSettings& settings) {
358 #if defined(OS_NACL)
359 // Can log only to the system debug log.
360 CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
361 #endif
362 CommandLine* command_line = CommandLine::ForCurrentProcess();
363 // Don't bother initializing g_vlog_info unless we use one of the
364 // vlog switches.
365 if (command_line->HasSwitch(switches::kV) ||
366 command_line->HasSwitch(switches::kVModule)) {
367 // NOTE: If g_vlog_info has already been initialized, it might be in use
368 // by another thread. Don't delete the old VLogInfo, just create a second
369 // one. We keep track of both to avoid memory leak warnings.
370 CHECK(!g_vlog_info_prev);
371 g_vlog_info_prev = g_vlog_info;
372
373 g_vlog_info =
374 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
375 command_line->GetSwitchValueASCII(switches::kVModule),
376 &min_log_level);
377 }
378
379 logging_destination = settings.logging_dest;
380
381 // ignore file options unless logging to file is set.
382 if ((logging_destination & LOG_TO_FILE) == 0)
383 return true;
384
385 LoggingLock::Init(settings.lock_log, settings.log_file);
386 LoggingLock logging_lock;
387
388 // Calling InitLogging twice or after some log call has already opened the
389 // default log file will re-initialize to the new options.
390 CloseLogFileUnlocked();
391
392 if (!log_file_name)
393 log_file_name = new PathString();
394 *log_file_name = settings.log_file;
395 if (settings.delete_old == DELETE_OLD_LOG_FILE)
396 DeleteFilePath(*log_file_name);
397
398 return InitializeLogFileHandle();
399 }
400
SetMinLogLevel(int level)401 void SetMinLogLevel(int level) {
402 min_log_level = std::min(LOG_FATAL, level);
403 }
404
GetMinLogLevel()405 int GetMinLogLevel() {
406 return min_log_level;
407 }
408
GetVlogVerbosity()409 int GetVlogVerbosity() {
410 return std::max(-1, LOG_INFO - GetMinLogLevel());
411 }
412
GetVlogLevelHelper(const char * file,size_t N)413 int GetVlogLevelHelper(const char* file, size_t N) {
414 DCHECK_GT(N, 0U);
415 // Note: g_vlog_info may change on a different thread during startup
416 // (but will always be valid or NULL).
417 VlogInfo* vlog_info = g_vlog_info;
418 return vlog_info ?
419 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
420 GetVlogVerbosity();
421 }
422
SetLogItems(bool enable_process_id,bool enable_thread_id,bool enable_timestamp,bool enable_tickcount)423 void SetLogItems(bool enable_process_id, bool enable_thread_id,
424 bool enable_timestamp, bool enable_tickcount) {
425 log_process_id = enable_process_id;
426 log_thread_id = enable_thread_id;
427 log_timestamp = enable_timestamp;
428 log_tickcount = enable_tickcount;
429 }
430
SetShowErrorDialogs(bool enable_dialogs)431 void SetShowErrorDialogs(bool enable_dialogs) {
432 show_error_dialogs = enable_dialogs;
433 }
434
SetLogAssertHandler(LogAssertHandlerFunction handler)435 void SetLogAssertHandler(LogAssertHandlerFunction handler) {
436 log_assert_handler = handler;
437 }
438
SetLogMessageHandler(LogMessageHandlerFunction handler)439 void SetLogMessageHandler(LogMessageHandlerFunction handler) {
440 log_message_handler = handler;
441 }
442
GetLogMessageHandler()443 LogMessageHandlerFunction GetLogMessageHandler() {
444 return log_message_handler;
445 }
446
447 // MSVC doesn't like complex extern templates and DLLs.
448 #if !defined(COMPILER_MSVC)
449 // Explicit instantiations for commonly used comparisons.
450 template std::string* MakeCheckOpString<int, int>(
451 const int&, const int&, const char* names);
452 template std::string* MakeCheckOpString<unsigned long, unsigned long>(
453 const unsigned long&, const unsigned long&, const char* names);
454 template std::string* MakeCheckOpString<unsigned long, unsigned int>(
455 const unsigned long&, const unsigned int&, const char* names);
456 template std::string* MakeCheckOpString<unsigned int, unsigned long>(
457 const unsigned int&, const unsigned long&, const char* names);
458 template std::string* MakeCheckOpString<std::string, std::string>(
459 const std::string&, const std::string&, const char* name);
460 #endif
461
462 #if !defined(NDEBUG)
463 // Displays a message box to the user with the error message in it.
464 // Used for fatal messages, where we close the app simultaneously.
465 // This is for developers only; we don't use this in circumstances
466 // (like release builds) where users could see it, since users don't
467 // understand these messages anyway.
DisplayDebugMessageInDialog(const std::string & str)468 void DisplayDebugMessageInDialog(const std::string& str) {
469 if (str.empty())
470 return;
471
472 if (!show_error_dialogs)
473 return;
474
475 #if defined(OS_WIN)
476 // For Windows programs, it's possible that the message loop is
477 // messed up on a fatal error, and creating a MessageBox will cause
478 // that message loop to be run. Instead, we try to spawn another
479 // process that displays its command line. We look for "Debug
480 // Message.exe" in the same directory as the application. If it
481 // exists, we use it, otherwise, we use a regular message box.
482 wchar_t prog_name[MAX_PATH];
483 GetModuleFileNameW(NULL, prog_name, MAX_PATH);
484 wchar_t* backslash = wcsrchr(prog_name, '\\');
485 if (backslash)
486 backslash[1] = 0;
487 wcscat_s(prog_name, MAX_PATH, L"debug_message.exe");
488
489 std::wstring cmdline = base::UTF8ToWide(str);
490 if (cmdline.empty())
491 return;
492
493 STARTUPINFO startup_info;
494 memset(&startup_info, 0, sizeof(startup_info));
495 startup_info.cb = sizeof(startup_info);
496
497 PROCESS_INFORMATION process_info;
498 if (CreateProcessW(prog_name, &cmdline[0], NULL, NULL, false, 0, NULL,
499 NULL, &startup_info, &process_info)) {
500 WaitForSingleObject(process_info.hProcess, INFINITE);
501 CloseHandle(process_info.hThread);
502 CloseHandle(process_info.hProcess);
503 } else {
504 // debug process broken, let's just do a message box
505 MessageBoxW(NULL, &cmdline[0], L"Fatal error",
506 MB_OK | MB_ICONHAND | MB_TOPMOST);
507 }
508 #else
509 // We intentionally don't implement a dialog on other platforms.
510 // You can just look at stderr.
511 #endif
512 }
513 #endif // !defined(NDEBUG)
514
515 #if defined(OS_WIN)
SaveLastError()516 LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
517 }
518
~SaveLastError()519 LogMessage::SaveLastError::~SaveLastError() {
520 ::SetLastError(last_error_);
521 }
522 #endif // defined(OS_WIN)
523
LogMessage(const char * file,int line,LogSeverity severity)524 LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
525 : severity_(severity), file_(file), line_(line) {
526 Init(file, line);
527 }
528
LogMessage(const char * file,int line,std::string * result)529 LogMessage::LogMessage(const char* file, int line, std::string* result)
530 : severity_(LOG_FATAL), file_(file), line_(line) {
531 Init(file, line);
532 stream_ << "Check failed: " << *result;
533 delete result;
534 }
535
LogMessage(const char * file,int line,LogSeverity severity,std::string * result)536 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
537 std::string* result)
538 : severity_(severity), file_(file), line_(line) {
539 Init(file, line);
540 stream_ << "Check failed: " << *result;
541 delete result;
542 }
543
~LogMessage()544 LogMessage::~LogMessage() {
545 #if !defined(NDEBUG) && !defined(OS_NACL) && !defined(__UCLIBC__)
546 if (severity_ == LOG_FATAL) {
547 // Include a stack trace on a fatal.
548 base::debug::StackTrace trace;
549 stream_ << std::endl; // Newline to separate from log message.
550 trace.OutputToStream(&stream_);
551 }
552 #endif
553 stream_ << std::endl;
554 std::string str_newline(stream_.str());
555
556 // Give any log message handler first dibs on the message.
557 if (log_message_handler &&
558 log_message_handler(severity_, file_, line_,
559 message_start_, str_newline)) {
560 // The handler took care of it, no further processing.
561 return;
562 }
563
564 if ((logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
565 #if defined(OS_WIN)
566 OutputDebugStringA(str_newline.c_str());
567 #elif defined(OS_ANDROID)
568 android_LogPriority priority =
569 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
570 switch (severity_) {
571 case LOG_INFO:
572 priority = ANDROID_LOG_INFO;
573 break;
574 case LOG_WARNING:
575 priority = ANDROID_LOG_WARN;
576 break;
577 case LOG_ERROR:
578 priority = ANDROID_LOG_ERROR;
579 break;
580 case LOG_FATAL:
581 priority = ANDROID_LOG_FATAL;
582 break;
583 }
584 __android_log_write(priority, "chromium", str_newline.c_str());
585 #endif
586 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
587 fflush(stderr);
588 } else if (severity_ >= kAlwaysPrintErrorLevel) {
589 // When we're only outputting to a log file, above a certain log level, we
590 // should still output to stderr so that we can better detect and diagnose
591 // problems with unit tests, especially on the buildbots.
592 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
593 fflush(stderr);
594 }
595
596 // write to log file
597 if ((logging_destination & LOG_TO_FILE) != 0) {
598 // We can have multiple threads and/or processes, so try to prevent them
599 // from clobbering each other's writes.
600 // If the client app did not call InitLogging, and the lock has not
601 // been created do it now. We do this on demand, but if two threads try
602 // to do this at the same time, there will be a race condition to create
603 // the lock. This is why InitLogging should be called from the main
604 // thread at the beginning of execution.
605 LoggingLock::Init(LOCK_LOG_FILE, NULL);
606 LoggingLock logging_lock;
607 if (InitializeLogFileHandle()) {
608 #if defined(OS_WIN)
609 SetFilePointer(log_file, 0, 0, SEEK_END);
610 DWORD num_written;
611 WriteFile(log_file,
612 static_cast<const void*>(str_newline.c_str()),
613 static_cast<DWORD>(str_newline.length()),
614 &num_written,
615 NULL);
616 #else
617 ignore_result(fwrite(
618 str_newline.data(), str_newline.size(), 1, log_file));
619 fflush(log_file);
620 #endif
621 }
622 }
623
624 if (severity_ == LOG_FATAL) {
625 // Ensure the first characters of the string are on the stack so they
626 // are contained in minidumps for diagnostic purposes.
627 char str_stack[1024];
628 str_newline.copy(str_stack, arraysize(str_stack));
629 base::debug::Alias(str_stack);
630
631 if (log_assert_handler) {
632 // Make a copy of the string for the handler out of paranoia.
633 log_assert_handler(std::string(stream_.str()));
634 } else {
635 // Don't use the string with the newline, get a fresh version to send to
636 // the debug message process. We also don't display assertions to the
637 // user in release mode. The enduser can't do anything with this
638 // information, and displaying message boxes when the application is
639 // hosed can cause additional problems.
640 #ifndef NDEBUG
641 DisplayDebugMessageInDialog(stream_.str());
642 #endif
643 // Crash the process to generate a dump.
644 base::debug::BreakDebugger();
645 }
646 }
647 }
648
649 // writes the common header info to the stream
Init(const char * file,int line)650 void LogMessage::Init(const char* file, int line) {
651 base::StringPiece filename(file);
652 size_t last_slash_pos = filename.find_last_of("\\/");
653 if (last_slash_pos != base::StringPiece::npos)
654 filename.remove_prefix(last_slash_pos + 1);
655
656 // TODO(darin): It might be nice if the columns were fixed width.
657
658 stream_ << '[';
659 if (log_process_id)
660 stream_ << CurrentProcessId() << ':';
661 if (log_thread_id)
662 stream_ << base::PlatformThread::CurrentId() << ':';
663 if (log_timestamp) {
664 time_t t = time(NULL);
665 struct tm local_time = {0};
666 #if _MSC_VER >= 1400
667 localtime_s(&local_time, &t);
668 #else
669 localtime_r(&t, &local_time);
670 #endif
671 struct tm* tm_time = &local_time;
672 stream_ << std::setfill('0')
673 << std::setw(2) << 1 + tm_time->tm_mon
674 << std::setw(2) << tm_time->tm_mday
675 << '/'
676 << std::setw(2) << tm_time->tm_hour
677 << std::setw(2) << tm_time->tm_min
678 << std::setw(2) << tm_time->tm_sec
679 << ':';
680 }
681 if (log_tickcount)
682 stream_ << TickCount() << ':';
683 if (severity_ >= 0)
684 stream_ << log_severity_name(severity_);
685 else
686 stream_ << "VERBOSE" << -severity_;
687
688 stream_ << ":" << filename << "(" << line << ")] ";
689
690 message_start_ = stream_.tellp();
691 }
692
693 #if defined(OS_WIN)
694 // This has already been defined in the header, but defining it again as DWORD
695 // ensures that the type used in the header is equivalent to DWORD. If not,
696 // the redefinition is a compile error.
697 typedef DWORD SystemErrorCode;
698 #endif
699
GetLastSystemErrorCode()700 SystemErrorCode GetLastSystemErrorCode() {
701 #if defined(OS_WIN)
702 return ::GetLastError();
703 #elif defined(OS_POSIX)
704 return errno;
705 #else
706 #error Not implemented
707 #endif
708 }
709
710 #if defined(OS_WIN)
SystemErrorCodeToString(SystemErrorCode error_code)711 BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
712 const int error_message_buffer_size = 256;
713 char msgbuf[error_message_buffer_size];
714 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
715 DWORD len = FormatMessageA(flags, NULL, error_code, 0, msgbuf,
716 arraysize(msgbuf), NULL);
717 if (len) {
718 // Messages returned by system end with line breaks.
719 return base::CollapseWhitespaceASCII(msgbuf, true) +
720 base::StringPrintf(" (0x%X)", error_code);
721 }
722 return base::StringPrintf("Error (0x%X) while retrieving error. (0x%X)",
723 GetLastError(), error_code);
724 }
725 #elif defined(OS_POSIX)
SystemErrorCodeToString(SystemErrorCode error_code)726 BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
727 return safe_strerror(error_code);
728 }
729 #else
730 #error Not implemented
731 #endif
732
733
734 #if defined(OS_WIN)
Win32ErrorLogMessage(const char * file,int line,LogSeverity severity,SystemErrorCode err)735 Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
736 int line,
737 LogSeverity severity,
738 SystemErrorCode err)
739 : err_(err),
740 log_message_(file, line, severity) {
741 }
742
~Win32ErrorLogMessage()743 Win32ErrorLogMessage::~Win32ErrorLogMessage() {
744 stream() << ": " << SystemErrorCodeToString(err_);
745 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
746 // field) and use Alias in hopes that it makes it into crash dumps.
747 DWORD last_error = err_;
748 base::debug::Alias(&last_error);
749 }
750 #elif defined(OS_POSIX)
ErrnoLogMessage(const char * file,int line,LogSeverity severity,SystemErrorCode err)751 ErrnoLogMessage::ErrnoLogMessage(const char* file,
752 int line,
753 LogSeverity severity,
754 SystemErrorCode err)
755 : err_(err),
756 log_message_(file, line, severity) {
757 }
758
~ErrnoLogMessage()759 ErrnoLogMessage::~ErrnoLogMessage() {
760 stream() << ": " << SystemErrorCodeToString(err_);
761 }
762 #endif // OS_WIN
763
CloseLogFile()764 void CloseLogFile() {
765 LoggingLock logging_lock;
766 CloseLogFileUnlocked();
767 }
768
RawLog(int level,const char * message)769 void RawLog(int level, const char* message) {
770 if (level >= min_log_level) {
771 size_t bytes_written = 0;
772 const size_t message_len = strlen(message);
773 int rv;
774 while (bytes_written < message_len) {
775 rv = HANDLE_EINTR(
776 write(STDERR_FILENO, message + bytes_written,
777 message_len - bytes_written));
778 if (rv < 0) {
779 // Give up, nothing we can do now.
780 break;
781 }
782 bytes_written += rv;
783 }
784
785 if (message_len > 0 && message[message_len - 1] != '\n') {
786 do {
787 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
788 if (rv < 0) {
789 // Give up, nothing we can do now.
790 break;
791 }
792 } while (rv != 1);
793 }
794 }
795
796 if (level == LOG_FATAL)
797 base::debug::BreakDebugger();
798 }
799
800 // This was defined at the beginning of this file.
801 #undef write
802
803 #if defined(OS_WIN)
GetLogFileFullPath()804 std::wstring GetLogFileFullPath() {
805 if (log_file_name)
806 return *log_file_name;
807 return std::wstring();
808 }
809 #endif
810
811 } // namespace logging
812
operator <<(std::ostream & out,const wchar_t * wstr)813 std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) {
814 return out << base::WideToUTF8(std::wstring(wstr));
815 }
816