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