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