logging.cc revision 72a454cd3513ac24fbdd0e0cb9ad70b86a99b801
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<<<<<<< HEAD
357                         OldFileDeletionState delete_old) {
358#ifdef ANDROID
359  // ifdef is here because we don't support parsing command line parameters
360  g_enable_dcheck = false;
361  g_vlog_info = NULL;
362#else
363=======
364                         OldFileDeletionState delete_old,
365                         DcheckState dcheck_state) {
366>>>>>>> chromium.org at r11.0.672.0
367  CommandLine* command_line = CommandLine::ForCurrentProcess();
368  g_dcheck_state = dcheck_state;
369  delete g_vlog_info;
370  g_vlog_info = NULL;
371  // Don't bother initializing g_vlog_info unless we use one of the
372  // vlog switches.
373  if (command_line->HasSwitch(switches::kV) ||
374      command_line->HasSwitch(switches::kVModule)) {
375    g_vlog_info =
376        new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
377                     command_line->GetSwitchValueASCII(switches::kVModule),
378                     &min_log_level);
379  }
380#endif
381
382  LoggingLock::Init(lock_log, new_log_file);
383
384  LoggingLock logging_lock;
385
386  if (log_file) {
387    // calling InitLogging twice or after some log call has already opened the
388    // default log file will re-initialize to the new options
389    CloseFile(log_file);
390    log_file = NULL;
391  }
392
393  logging_destination = logging_dest;
394
395  // ignore file options if logging is disabled or only to system
396  if (logging_destination == LOG_NONE ||
397      logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG)
398    return true;
399
400  if (!log_file_name)
401    log_file_name = new PathString();
402  *log_file_name = new_log_file;
403  if (delete_old == DELETE_OLD_LOG_FILE)
404    DeleteFilePath(*log_file_name);
405
406  return InitializeLogFileHandle();
407}
408
409void SetMinLogLevel(int level) {
410  min_log_level = std::min(LOG_ERROR_REPORT, level);
411}
412
413int GetMinLogLevel() {
414  return min_log_level;
415}
416
417int GetVlogVerbosity() {
418  return std::max(-1, LOG_INFO - GetMinLogLevel());
419}
420
421int GetVlogLevelHelper(const char* file, size_t N) {
422  DCHECK_GT(N, 0U);
423  return g_vlog_info ?
424      g_vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
425      GetVlogVerbosity();
426}
427
428void SetLogItems(bool enable_process_id, bool enable_thread_id,
429                 bool enable_timestamp, bool enable_tickcount) {
430  log_process_id = enable_process_id;
431  log_thread_id = enable_thread_id;
432  log_timestamp = enable_timestamp;
433  log_tickcount = enable_tickcount;
434}
435
436void SetShowErrorDialogs(bool enable_dialogs) {
437  show_error_dialogs = enable_dialogs;
438}
439
440void SetLogAssertHandler(LogAssertHandlerFunction handler) {
441  log_assert_handler = handler;
442}
443
444void SetLogReportHandler(LogReportHandlerFunction handler) {
445  log_report_handler = handler;
446}
447
448void SetLogMessageHandler(LogMessageHandlerFunction handler) {
449  log_message_handler = handler;
450}
451
452LogMessageHandlerFunction GetLogMessageHandler() {
453  return log_message_handler;
454}
455
456// MSVC doesn't like complex extern templates and DLLs.
457#if !defined(COMPILER_MSVC)
458// Explicit instantiations for commonly used comparisons.
459template std::string* MakeCheckOpString<int, int>(
460    const int&, const int&, const char* names);
461template std::string* MakeCheckOpString<unsigned long, unsigned long>(
462    const unsigned long&, const unsigned long&, const char* names);
463template std::string* MakeCheckOpString<unsigned long, unsigned int>(
464    const unsigned long&, const unsigned int&, const char* names);
465template std::string* MakeCheckOpString<unsigned int, unsigned long>(
466    const unsigned int&, const unsigned long&, const char* names);
467template std::string* MakeCheckOpString<std::string, std::string>(
468    const std::string&, const std::string&, const char* name);
469#endif
470
471// Displays a message box to the user with the error message in it.
472// Used for fatal messages, where we close the app simultaneously.
473// This is for developers only; we don't use this in circumstances
474// (like release builds) where users could see it, since users don't
475// understand these messages anyway.
476void DisplayDebugMessageInDialog(const std::string& str) {
477  if (str.empty())
478    return;
479
480  if (!show_error_dialogs)
481    return;
482
483#if defined(OS_WIN)
484  // For Windows programs, it's possible that the message loop is
485  // messed up on a fatal error, and creating a MessageBox will cause
486  // that message loop to be run. Instead, we try to spawn another
487  // process that displays its command line. We look for "Debug
488  // Message.exe" in the same directory as the application. If it
489  // exists, we use it, otherwise, we use a regular message box.
490  wchar_t prog_name[MAX_PATH];
491  GetModuleFileNameW(NULL, prog_name, MAX_PATH);
492  wchar_t* backslash = wcsrchr(prog_name, '\\');
493  if (backslash)
494    backslash[1] = 0;
495  wcscat_s(prog_name, MAX_PATH, L"debug_message.exe");
496
497  std::wstring cmdline = UTF8ToWide(str);
498  if (cmdline.empty())
499    return;
500
501  STARTUPINFO startup_info;
502  memset(&startup_info, 0, sizeof(startup_info));
503  startup_info.cb = sizeof(startup_info);
504
505  PROCESS_INFORMATION process_info;
506  if (CreateProcessW(prog_name, &cmdline[0], NULL, NULL, false, 0, NULL,
507                     NULL, &startup_info, &process_info)) {
508    WaitForSingleObject(process_info.hProcess, INFINITE);
509    CloseHandle(process_info.hThread);
510    CloseHandle(process_info.hProcess);
511  } else {
512    // debug process broken, let's just do a message box
513    MessageBoxW(NULL, &cmdline[0], L"Fatal error",
514                MB_OK | MB_ICONHAND | MB_TOPMOST);
515  }
516#elif defined(OS_MACOSX)
517  base::mac::ScopedCFTypeRef<CFStringRef> message(
518      base::SysUTF8ToCFStringRef(str));
519  CFUserNotificationDisplayNotice(0, kCFUserNotificationStopAlertLevel,
520                                  NULL, NULL, NULL, CFSTR("Fatal Error"),
521                                  message, NULL);
522#else
523  // We intentionally don't implement a dialog on other platforms.
524  // You can just look at stderr.
525#endif
526}
527
528#if defined(OS_WIN)
529LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
530}
531
532LogMessage::SaveLastError::~SaveLastError() {
533  ::SetLastError(last_error_);
534}
535#endif  // defined(OS_WIN)
536
537LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
538                       int ctr)
539    : severity_(severity), file_(file), line_(line) {
540  Init(file, line);
541}
542
543LogMessage::LogMessage(const char* file, int line)
544    : severity_(LOG_INFO), file_(file), line_(line) {
545  Init(file, line);
546}
547
548LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
549    : severity_(severity), file_(file), line_(line) {
550  Init(file, line);
551}
552
553LogMessage::LogMessage(const char* file, int line, std::string* result)
554    : severity_(LOG_FATAL), file_(file), line_(line) {
555  Init(file, line);
556  stream_ << "Check failed: " << *result;
557  delete result;
558}
559
560LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
561                       std::string* result)
562    : severity_(severity), file_(file), line_(line) {
563  Init(file, line);
564  stream_ << "Check failed: " << *result;
565  delete result;
566}
567
568LogMessage::~LogMessage() {
569#ifndef NDEBUG
570  if (severity_ == LOG_FATAL) {
571    // Include a stack trace on a fatal.
572    base::debug::StackTrace trace;
573    stream_ << std::endl;  // Newline to separate from log message.
574    trace.OutputToStream(&stream_);
575  }
576#endif
577  stream_ << std::endl;
578  std::string str_newline(stream_.str());
579
580  // Give any log message handler first dibs on the message.
581  if (log_message_handler && log_message_handler(severity_, file_, line_,
582          message_start_, str_newline)) {
583    // The handler took care of it, no further processing.
584    return;
585  }
586
587  if (logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG ||
588      logging_destination == LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG) {
589#if defined(OS_WIN)
590    OutputDebugStringA(str_newline.c_str());
591#endif
592    fprintf(stderr, "%s", str_newline.c_str());
593    fflush(stderr);
594  } else if (severity_ >= kAlwaysPrintErrorLevel) {
595    // When we're only outputting to a log file, above a certain log level, we
596    // should still output to stderr so that we can better detect and diagnose
597    // problems with unit tests, especially on the buildbots.
598    fprintf(stderr, "%s", str_newline.c_str());
599    fflush(stderr);
600  }
601
602  // We can have multiple threads and/or processes, so try to prevent them
603  // from clobbering each other's writes.
604  // If the client app did not call InitLogging, and the lock has not
605  // been created do it now. We do this on demand, but if two threads try
606  // to do this at the same time, there will be a race condition to create
607  // the lock. This is why InitLogging should be called from the main
608  // thread at the beginning of execution.
609  LoggingLock::Init(LOCK_LOG_FILE, NULL);
610  // write to log file
611  if (logging_destination != LOG_NONE &&
612      logging_destination != LOG_ONLY_TO_SYSTEM_DEBUG_LOG) {
613    LoggingLock logging_lock;
614    if (InitializeLogFileHandle()) {
615#if defined(OS_WIN)
616      SetFilePointer(log_file, 0, 0, SEEK_END);
617      DWORD num_written;
618      WriteFile(log_file,
619                static_cast<const void*>(str_newline.c_str()),
620                static_cast<DWORD>(str_newline.length()),
621                &num_written,
622                NULL);
623#else
624      fprintf(log_file, "%s", str_newline.c_str());
625      fflush(log_file);
626#endif
627    }
628  }
629
630  if (severity_ == LOG_FATAL) {
631    // display a message or break into the debugger on a fatal error
632    if (base::debug::BeingDebugged()) {
633      base::debug::BreakDebugger();
634    } else {
635      if (log_assert_handler) {
636        // make a copy of the string for the handler out of paranoia
637        log_assert_handler(std::string(stream_.str()));
638      } else {
639        // Don't use the string with the newline, get a fresh version to send to
640        // the debug message process. We also don't display assertions to the
641        // user in release mode. The enduser can't do anything with this
642        // information, and displaying message boxes when the application is
643        // hosed can cause additional problems.
644#ifndef NDEBUG
645        DisplayDebugMessageInDialog(stream_.str());
646#endif
647        // Crash the process to generate a dump.
648        base::debug::BreakDebugger();
649      }
650    }
651  } else if (severity_ == LOG_ERROR_REPORT) {
652    // We are here only if the user runs with --enable-dcheck in release mode.
653    if (log_report_handler) {
654      log_report_handler(std::string(stream_.str()));
655    } else {
656      DisplayDebugMessageInDialog(stream_.str());
657    }
658  }
659}
660
661// writes the common header info to the stream
662void LogMessage::Init(const char* file, int line) {
663  base::StringPiece filename(file);
664  size_t last_slash_pos = filename.find_last_of("\\/");
665  if (last_slash_pos != base::StringPiece::npos)
666    filename.remove_prefix(last_slash_pos + 1);
667
668  // TODO(darin): It might be nice if the columns were fixed width.
669
670  stream_ <<  '[';
671  if (log_process_id)
672    stream_ << CurrentProcessId() << ':';
673  if (log_thread_id)
674    stream_ << CurrentThreadId() << ':';
675  if (log_timestamp) {
676    time_t t = time(NULL);
677    struct tm local_time = {0};
678#if _MSC_VER >= 1400
679    localtime_s(&local_time, &t);
680#else
681    localtime_r(&t, &local_time);
682#endif
683    struct tm* tm_time = &local_time;
684    stream_ << std::setfill('0')
685            << std::setw(2) << 1 + tm_time->tm_mon
686            << std::setw(2) << tm_time->tm_mday
687            << '/'
688            << std::setw(2) << tm_time->tm_hour
689            << std::setw(2) << tm_time->tm_min
690            << std::setw(2) << tm_time->tm_sec
691            << ':';
692  }
693  if (log_tickcount)
694    stream_ << TickCount() << ':';
695  if (severity_ >= 0)
696    stream_ << log_severity_names[severity_];
697  else
698    stream_ << "VERBOSE" << -severity_;
699
700  stream_ << ":" << filename << "(" << line << ")] ";
701
702  message_start_ = stream_.tellp();
703}
704
705#if defined(OS_WIN)
706// This has already been defined in the header, but defining it again as DWORD
707// ensures that the type used in the header is equivalent to DWORD. If not,
708// the redefinition is a compile error.
709typedef DWORD SystemErrorCode;
710#endif
711
712SystemErrorCode GetLastSystemErrorCode() {
713#if defined(OS_WIN)
714  return ::GetLastError();
715#elif defined(OS_POSIX)
716  return errno;
717#else
718#error Not implemented
719#endif
720}
721
722#if defined(OS_WIN)
723Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
724                                           int line,
725                                           LogSeverity severity,
726                                           SystemErrorCode err,
727                                           const char* module)
728    : err_(err),
729      module_(module),
730      log_message_(file, line, severity) {
731}
732
733Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
734                                           int line,
735                                           LogSeverity severity,
736                                           SystemErrorCode err)
737    : err_(err),
738      module_(NULL),
739      log_message_(file, line, severity) {
740}
741
742Win32ErrorLogMessage::~Win32ErrorLogMessage() {
743  const int error_message_buffer_size = 256;
744  char msgbuf[error_message_buffer_size];
745  DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
746  HMODULE hmod;
747  if (module_) {
748    hmod = GetModuleHandleA(module_);
749    if (hmod) {
750      flags |= FORMAT_MESSAGE_FROM_HMODULE;
751    } else {
752      // This makes a nested Win32ErrorLogMessage. It will have module_ of NULL
753      // so it will not call GetModuleHandle, so recursive errors are
754      // impossible.
755      DPLOG(WARNING) << "Couldn't open module " << module_
756          << " for error message query";
757    }
758  } else {
759    hmod = NULL;
760  }
761  DWORD len = FormatMessageA(flags,
762                             hmod,
763                             err_,
764                             0,
765                             msgbuf,
766                             sizeof(msgbuf) / sizeof(msgbuf[0]),
767                             NULL);
768  if (len) {
769    while ((len > 0) &&
770           isspace(static_cast<unsigned char>(msgbuf[len - 1]))) {
771      msgbuf[--len] = 0;
772    }
773    stream() << ": " << msgbuf;
774  } else {
775    stream() << ": Error " << GetLastError() << " while retrieving error "
776        << err_;
777  }
778}
779#elif defined(OS_POSIX)
780ErrnoLogMessage::ErrnoLogMessage(const char* file,
781                                 int line,
782                                 LogSeverity severity,
783                                 SystemErrorCode err)
784    : err_(err),
785      log_message_(file, line, severity) {
786}
787
788ErrnoLogMessage::~ErrnoLogMessage() {
789  stream() << ": " << safe_strerror(err_);
790}
791#endif  // OS_WIN
792
793void CloseLogFile() {
794  LoggingLock logging_lock;
795
796  if (!log_file)
797    return;
798
799  CloseFile(log_file);
800  log_file = NULL;
801}
802
803void RawLog(int level, const char* message) {
804  if (level >= min_log_level) {
805    size_t bytes_written = 0;
806    const size_t message_len = strlen(message);
807    int rv;
808    while (bytes_written < message_len) {
809      rv = HANDLE_EINTR(
810          write(STDERR_FILENO, message + bytes_written,
811                message_len - bytes_written));
812      if (rv < 0) {
813        // Give up, nothing we can do now.
814        break;
815      }
816      bytes_written += rv;
817    }
818
819    if (message_len > 0 && message[message_len - 1] != '\n') {
820      do {
821        rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
822        if (rv < 0) {
823          // Give up, nothing we can do now.
824          break;
825        }
826      } while (rv != 1);
827    }
828  }
829
830  if (level == LOG_FATAL)
831    base::debug::BreakDebugger();
832}
833
834}  // namespace logging
835
836std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) {
837  return out << WideToUTF8(std::wstring(wstr));
838}
839