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