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