logging.cc revision 4a5e2dc747d50c653511c68ccb2cfbfb740bd5a7
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 // The macros in logging.h should already avoid creating LogMessages 612 // when this holds, but it's possible that users create LogMessages 613 // directly (e.g., using LOG_STREAM() directly). 614 if (severity_ < min_log_level) 615 return; 616 617#ifndef NDEBUG 618 if (severity_ == LOG_FATAL) { 619 // Include a stack trace on a fatal. 620 base::debug::StackTrace trace; 621 stream_ << std::endl; // Newline to separate from log message. 622 trace.OutputToStream(&stream_); 623 } 624#endif 625 stream_ << std::endl; 626 std::string str_newline(stream_.str()); 627 628 // Give any log message handler first dibs on the message. 629 if (log_message_handler && log_message_handler(severity_, file_, line_, 630 message_start_, str_newline)) { 631 // The handler took care of it, no further processing. 632 return; 633 } 634 635 if (logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG || 636 logging_destination == LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG) { 637#if defined(OS_WIN) 638 OutputDebugStringA(str_newline.c_str()); 639#endif 640 fprintf(stderr, "%s", str_newline.c_str()); 641 fflush(stderr); 642 } else if (severity_ >= kAlwaysPrintErrorLevel) { 643 // When we're only outputting to a log file, above a certain log level, we 644 // should still output to stderr so that we can better detect and diagnose 645 // problems with unit tests, especially on the buildbots. 646 fprintf(stderr, "%s", str_newline.c_str()); 647 fflush(stderr); 648 } 649 650 // We can have multiple threads and/or processes, so try to prevent them 651 // from clobbering each other's writes. 652 // If the client app did not call InitLogging, and the lock has not 653 // been created do it now. We do this on demand, but if two threads try 654 // to do this at the same time, there will be a race condition to create 655 // the lock. This is why InitLogging should be called from the main 656 // thread at the beginning of execution. 657 LoggingLock::Init(LOCK_LOG_FILE, NULL); 658 // write to log file 659 if (logging_destination != LOG_NONE && 660 logging_destination != LOG_ONLY_TO_SYSTEM_DEBUG_LOG) { 661 LoggingLock logging_lock; 662 if (InitializeLogFileHandle()) { 663#if defined(OS_WIN) 664 SetFilePointer(log_file, 0, 0, SEEK_END); 665 DWORD num_written; 666 WriteFile(log_file, 667 static_cast<const void*>(str_newline.c_str()), 668 static_cast<DWORD>(str_newline.length()), 669 &num_written, 670 NULL); 671#else 672 fprintf(log_file, "%s", str_newline.c_str()); 673 fflush(log_file); 674#endif 675 } 676 } 677 678 if (severity_ == LOG_FATAL) { 679 // display a message or break into the debugger on a fatal error 680 if (base::debug::BeingDebugged()) { 681 base::debug::BreakDebugger(); 682 } else { 683 if (log_assert_handler) { 684 // make a copy of the string for the handler out of paranoia 685 log_assert_handler(std::string(stream_.str())); 686 } else { 687 // Don't use the string with the newline, get a fresh version to send to 688 // the debug message process. We also don't display assertions to the 689 // user in release mode. The enduser can't do anything with this 690 // information, and displaying message boxes when the application is 691 // hosed can cause additional problems. 692#ifndef NDEBUG 693 DisplayDebugMessageInDialog(stream_.str()); 694#endif 695 // Crash the process to generate a dump. 696 base::debug::BreakDebugger(); 697 } 698 } 699 } else if (severity_ == LOG_ERROR_REPORT) { 700 // We are here only if the user runs with --enable-dcheck in release mode. 701 if (log_report_handler) { 702 log_report_handler(std::string(stream_.str())); 703 } else { 704 DisplayDebugMessageInDialog(stream_.str()); 705 } 706 } 707} 708 709#if defined(OS_WIN) 710// This has already been defined in the header, but defining it again as DWORD 711// ensures that the type used in the header is equivalent to DWORD. If not, 712// the redefinition is a compile error. 713typedef DWORD SystemErrorCode; 714#endif 715 716SystemErrorCode GetLastSystemErrorCode() { 717#if defined(OS_WIN) 718 return ::GetLastError(); 719#elif defined(OS_POSIX) 720 return errno; 721#else 722#error Not implemented 723#endif 724} 725 726#if defined(OS_WIN) 727Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file, 728 int line, 729 LogSeverity severity, 730 SystemErrorCode err, 731 const char* module) 732 : err_(err), 733 module_(module), 734 log_message_(file, line, severity) { 735} 736 737Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file, 738 int line, 739 LogSeverity severity, 740 SystemErrorCode err) 741 : err_(err), 742 module_(NULL), 743 log_message_(file, line, severity) { 744} 745 746Win32ErrorLogMessage::~Win32ErrorLogMessage() { 747 const int error_message_buffer_size = 256; 748 char msgbuf[error_message_buffer_size]; 749 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; 750 HMODULE hmod; 751 if (module_) { 752 hmod = GetModuleHandleA(module_); 753 if (hmod) { 754 flags |= FORMAT_MESSAGE_FROM_HMODULE; 755 } else { 756 // This makes a nested Win32ErrorLogMessage. It will have module_ of NULL 757 // so it will not call GetModuleHandle, so recursive errors are 758 // impossible. 759 DPLOG(WARNING) << "Couldn't open module " << module_ 760 << " for error message query"; 761 } 762 } else { 763 hmod = NULL; 764 } 765 DWORD len = FormatMessageA(flags, 766 hmod, 767 err_, 768 0, 769 msgbuf, 770 sizeof(msgbuf) / sizeof(msgbuf[0]), 771 NULL); 772 if (len) { 773 while ((len > 0) && 774 isspace(static_cast<unsigned char>(msgbuf[len - 1]))) { 775 msgbuf[--len] = 0; 776 } 777 stream() << ": " << msgbuf; 778 } else { 779 stream() << ": Error " << GetLastError() << " while retrieving error " 780 << err_; 781 } 782} 783#elif defined(OS_POSIX) 784ErrnoLogMessage::ErrnoLogMessage(const char* file, 785 int line, 786 LogSeverity severity, 787 SystemErrorCode err) 788 : err_(err), 789 log_message_(file, line, severity) { 790} 791 792ErrnoLogMessage::~ErrnoLogMessage() { 793 stream() << ": " << safe_strerror(err_); 794} 795#endif // OS_WIN 796 797void CloseLogFile() { 798 LoggingLock logging_lock; 799 800 if (!log_file) 801 return; 802 803 CloseFile(log_file); 804 log_file = NULL; 805} 806 807void RawLog(int level, const char* message) { 808 if (level >= min_log_level) { 809 size_t bytes_written = 0; 810 const size_t message_len = strlen(message); 811 int rv; 812 while (bytes_written < message_len) { 813 rv = HANDLE_EINTR( 814 write(STDERR_FILENO, message + bytes_written, 815 message_len - bytes_written)); 816 if (rv < 0) { 817 // Give up, nothing we can do now. 818 break; 819 } 820 bytes_written += rv; 821 } 822 823 if (message_len > 0 && message[message_len - 1] != '\n') { 824 do { 825 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1)); 826 if (rv < 0) { 827 // Give up, nothing we can do now. 828 break; 829 } 830 } while (rv != 1); 831 } 832 } 833 834 if (level == LOG_FATAL) 835 base::debug::BreakDebugger(); 836} 837 838} // namespace logging 839 840std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) { 841 return out << WideToUTF8(std::wstring(wstr)); 842} 843