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