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