logging.cc revision 1958f25718c34665d6f3fc3dcd18db91ba52ec33
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/lock_impl.h"
54#include "base/string_piece.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
67bool g_enable_dcheck = false;
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 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 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
302LockImpl* 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#ifdef ANDROID
358  // ifdef is here because we don't support parsing command line parameters
359  g_enable_dcheck = false;
360  g_vlog_info = NULL;
361#else
362  CommandLine* command_line = CommandLine::ForCurrentProcess();
363  g_enable_dcheck =
364      command_line->HasSwitch(switches::kEnableDCHECK);
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, const CheckOpString& result)
540    : severity_(LOG_FATAL), file_(file), line_(line) {
541  Init(file, line);
542  stream_ << "Check failed: " << (*result.str_);
543}
544
545LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
546                       const CheckOpString& result)
547    : severity_(severity), file_(file), line_(line) {
548  Init(file, line);
549  stream_ << "Check failed: " << (*result.str_);
550}
551
552LogMessage::LogMessage(const char* file, int line)
553    : severity_(LOG_INFO), file_(file), line_(line) {
554  Init(file, line);
555}
556
557LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
558    : severity_(severity), file_(file), line_(line) {
559  Init(file, line);
560}
561
562// writes the common header info to the stream
563void LogMessage::Init(const char* file, int line) {
564  base::StringPiece filename(file);
565  size_t last_slash_pos = filename.find_last_of("\\/");
566  if (last_slash_pos != base::StringPiece::npos)
567    filename.remove_prefix(last_slash_pos + 1);
568
569  // TODO(darin): It might be nice if the columns were fixed width.
570
571  stream_ <<  '[';
572  if (log_process_id)
573    stream_ << CurrentProcessId() << ':';
574  if (log_thread_id)
575    stream_ << CurrentThreadId() << ':';
576  if (log_timestamp) {
577    time_t t = time(NULL);
578    struct tm local_time = {0};
579#if _MSC_VER >= 1400
580    localtime_s(&local_time, &t);
581#else
582    localtime_r(&t, &local_time);
583#endif
584    struct tm* tm_time = &local_time;
585    stream_ << std::setfill('0')
586            << std::setw(2) << 1 + tm_time->tm_mon
587            << std::setw(2) << tm_time->tm_mday
588            << '/'
589            << std::setw(2) << tm_time->tm_hour
590            << std::setw(2) << tm_time->tm_min
591            << std::setw(2) << tm_time->tm_sec
592            << ':';
593  }
594  if (log_tickcount)
595    stream_ << TickCount() << ':';
596  if (severity_ >= 0)
597    stream_ << log_severity_names[severity_];
598  else
599    stream_ << "VERBOSE" << -severity_;
600
601  stream_ << ":" << filename << "(" << line << ")] ";
602
603  message_start_ = stream_.tellp();
604}
605
606LogMessage::~LogMessage() {
607#ifndef NDEBUG
608  if (severity_ == LOG_FATAL) {
609    // Include a stack trace on a fatal.
610    base::debug::StackTrace trace;
611    stream_ << std::endl;  // Newline to separate from log message.
612    trace.OutputToStream(&stream_);
613  }
614#endif
615  stream_ << std::endl;
616  std::string str_newline(stream_.str());
617
618  // Give any log message handler first dibs on the message.
619  if (log_message_handler && log_message_handler(severity_, file_, line_,
620          message_start_, str_newline)) {
621    // The handler took care of it, no further processing.
622    return;
623  }
624
625  if (logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG ||
626      logging_destination == LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG) {
627#if defined(OS_WIN)
628    OutputDebugStringA(str_newline.c_str());
629#endif
630    fprintf(stderr, "%s", str_newline.c_str());
631    fflush(stderr);
632  } else if (severity_ >= kAlwaysPrintErrorLevel) {
633    // When we're only outputting to a log file, above a certain log level, we
634    // should still output to stderr so that we can better detect and diagnose
635    // problems with unit tests, especially on the buildbots.
636    fprintf(stderr, "%s", str_newline.c_str());
637    fflush(stderr);
638  }
639
640  // We can have multiple threads and/or processes, so try to prevent them
641  // from clobbering each other's writes.
642  // If the client app did not call InitLogging, and the lock has not
643  // been created do it now. We do this on demand, but if two threads try
644  // to do this at the same time, there will be a race condition to create
645  // the lock. This is why InitLogging should be called from the main
646  // thread at the beginning of execution.
647  LoggingLock::Init(LOCK_LOG_FILE, NULL);
648  // write to log file
649  if (logging_destination != LOG_NONE &&
650      logging_destination != LOG_ONLY_TO_SYSTEM_DEBUG_LOG) {
651    LoggingLock logging_lock;
652    if (InitializeLogFileHandle()) {
653#if defined(OS_WIN)
654      SetFilePointer(log_file, 0, 0, SEEK_END);
655      DWORD num_written;
656      WriteFile(log_file,
657                static_cast<const void*>(str_newline.c_str()),
658                static_cast<DWORD>(str_newline.length()),
659                &num_written,
660                NULL);
661#else
662      fprintf(log_file, "%s", str_newline.c_str());
663      fflush(log_file);
664#endif
665    }
666  }
667
668  if (severity_ == LOG_FATAL) {
669    // display a message or break into the debugger on a fatal error
670    if (base::debug::BeingDebugged()) {
671      base::debug::BreakDebugger();
672    } else {
673      if (log_assert_handler) {
674        // make a copy of the string for the handler out of paranoia
675        log_assert_handler(std::string(stream_.str()));
676      } else {
677        // Don't use the string with the newline, get a fresh version to send to
678        // the debug message process. We also don't display assertions to the
679        // user in release mode. The enduser can't do anything with this
680        // information, and displaying message boxes when the application is
681        // hosed can cause additional problems.
682#ifndef NDEBUG
683        DisplayDebugMessageInDialog(stream_.str());
684#endif
685        // Crash the process to generate a dump.
686        base::debug::BreakDebugger();
687      }
688    }
689  } else if (severity_ == LOG_ERROR_REPORT) {
690    // We are here only if the user runs with --enable-dcheck in release mode.
691    if (log_report_handler) {
692      log_report_handler(std::string(stream_.str()));
693    } else {
694      DisplayDebugMessageInDialog(stream_.str());
695    }
696  }
697}
698
699#if defined(OS_WIN)
700// This has already been defined in the header, but defining it again as DWORD
701// ensures that the type used in the header is equivalent to DWORD. If not,
702// the redefinition is a compile error.
703typedef DWORD SystemErrorCode;
704#endif
705
706SystemErrorCode GetLastSystemErrorCode() {
707#if defined(OS_WIN)
708  return ::GetLastError();
709#elif defined(OS_POSIX)
710  return errno;
711#else
712#error Not implemented
713#endif
714}
715
716#if defined(OS_WIN)
717Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
718                                           int line,
719                                           LogSeverity severity,
720                                           SystemErrorCode err,
721                                           const char* module)
722    : err_(err),
723      module_(module),
724      log_message_(file, line, severity) {
725}
726
727Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
728                                           int line,
729                                           LogSeverity severity,
730                                           SystemErrorCode err)
731    : err_(err),
732      module_(NULL),
733      log_message_(file, line, severity) {
734}
735
736Win32ErrorLogMessage::~Win32ErrorLogMessage() {
737  const int error_message_buffer_size = 256;
738  char msgbuf[error_message_buffer_size];
739  DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
740  HMODULE hmod;
741  if (module_) {
742    hmod = GetModuleHandleA(module_);
743    if (hmod) {
744      flags |= FORMAT_MESSAGE_FROM_HMODULE;
745    } else {
746      // This makes a nested Win32ErrorLogMessage. It will have module_ of NULL
747      // so it will not call GetModuleHandle, so recursive errors are
748      // impossible.
749      DPLOG(WARNING) << "Couldn't open module " << module_
750          << " for error message query";
751    }
752  } else {
753    hmod = NULL;
754  }
755  DWORD len = FormatMessageA(flags,
756                             hmod,
757                             err_,
758                             0,
759                             msgbuf,
760                             sizeof(msgbuf) / sizeof(msgbuf[0]),
761                             NULL);
762  if (len) {
763    while ((len > 0) &&
764           isspace(static_cast<unsigned char>(msgbuf[len - 1]))) {
765      msgbuf[--len] = 0;
766    }
767    stream() << ": " << msgbuf;
768  } else {
769    stream() << ": Error " << GetLastError() << " while retrieving error "
770        << err_;
771  }
772}
773#elif defined(OS_POSIX)
774ErrnoLogMessage::ErrnoLogMessage(const char* file,
775                                 int line,
776                                 LogSeverity severity,
777                                 SystemErrorCode err)
778    : err_(err),
779      log_message_(file, line, severity) {
780}
781
782ErrnoLogMessage::~ErrnoLogMessage() {
783  stream() << ": " << safe_strerror(err_);
784}
785#endif  // OS_WIN
786
787void CloseLogFile() {
788  LoggingLock logging_lock;
789
790  if (!log_file)
791    return;
792
793  CloseFile(log_file);
794  log_file = NULL;
795}
796
797void RawLog(int level, const char* message) {
798  if (level >= min_log_level) {
799    size_t bytes_written = 0;
800    const size_t message_len = strlen(message);
801    int rv;
802    while (bytes_written < message_len) {
803      rv = HANDLE_EINTR(
804          write(STDERR_FILENO, message + bytes_written,
805                message_len - bytes_written));
806      if (rv < 0) {
807        // Give up, nothing we can do now.
808        break;
809      }
810      bytes_written += rv;
811    }
812
813    if (message_len > 0 && message[message_len - 1] != '\n') {
814      do {
815        rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
816        if (rv < 0) {
817          // Give up, nothing we can do now.
818          break;
819        }
820      } while (rv != 1);
821    }
822  }
823
824  if (level == LOG_FATAL)
825    base::debug::BreakDebugger();
826}
827
828}  // namespace logging
829
830std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) {
831  return out << WideToUTF8(std::wstring(wstr));
832}
833