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