Bring back -fstack-protector-all on iOS.
[chromium-blink-merge.git] / base / logging.cc
blob9134b55eab27978821211ce0f3d5d1538142b92d
1 // Copyright (c) 2012 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.
5 #include "base/logging.h"
7 #if defined(OS_WIN)
8 #include <io.h>
9 #include <windows.h>
10 typedef HANDLE FileHandle;
11 typedef 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/time.h> // timespec doesn't seem to be in <time.h>
23 #else
24 #include <sys/syscall.h>
25 #endif
26 #include <time.h>
27 #endif
29 #if defined(OS_POSIX)
30 #include <errno.h>
31 #include <pthread.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #define MAX_PATH PATH_MAX
37 typedef FILE* FileHandle;
38 typedef pthread_mutex_t* MutexHandle;
39 #endif
41 #include <algorithm>
42 #include <cstring>
43 #include <ctime>
44 #include <iomanip>
45 #include <ostream>
47 #include "base/base_switches.h"
48 #include "base/command_line.h"
49 #include "base/debug/alias.h"
50 #include "base/debug/debugger.h"
51 #include "base/debug/stack_trace.h"
52 #include "base/posix/eintr_wrapper.h"
53 #include "base/strings/string_piece.h"
54 #include "base/strings/utf_string_conversions.h"
55 #include "base/synchronization/lock_impl.h"
56 #include "base/threading/platform_thread.h"
57 #include "base/vlog.h"
58 #if defined(OS_POSIX)
59 #include "base/safe_strerror_posix.h"
60 #endif
62 #if defined(OS_ANDROID)
63 #include <android/log.h>
64 #endif
66 namespace logging {
68 DcheckState g_dcheck_state = DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS;
70 void set_dcheck_state(DcheckState state) {
71 g_dcheck_state = state;
74 namespace {
76 VlogInfo* g_vlog_info = NULL;
77 VlogInfo* g_vlog_info_prev = NULL;
79 const char* const log_severity_names[LOG_NUM_SEVERITIES] = {
80 "INFO", "WARNING", "ERROR", "ERROR_REPORT", "FATAL" };
82 const char* log_severity_name(int severity)
84 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
85 return log_severity_names[severity];
86 return "UNKNOWN";
89 int min_log_level = 0;
91 LoggingDestination logging_destination = LOG_DEFAULT;
93 // For LOG_ERROR and above, always print to stderr.
94 const int kAlwaysPrintErrorLevel = LOG_ERROR;
96 // Which log file to use? This is initialized by InitLogging or
97 // will be lazily initialized to the default value when it is
98 // first needed.
99 #if defined(OS_WIN)
100 typedef std::wstring PathString;
101 #else
102 typedef std::string PathString;
103 #endif
104 PathString* log_file_name = NULL;
106 // this file is lazily opened and the handle may be NULL
107 FileHandle log_file = NULL;
109 // what should be prepended to each message?
110 bool log_process_id = false;
111 bool log_thread_id = false;
112 bool log_timestamp = true;
113 bool log_tickcount = false;
115 // Should we pop up fatal debug messages in a dialog?
116 bool show_error_dialogs = false;
118 // An assert handler override specified by the client to be called instead of
119 // the debug message dialog and process termination.
120 LogAssertHandlerFunction log_assert_handler = NULL;
121 // An report handler override specified by the client to be called instead of
122 // the debug message dialog.
123 LogReportHandlerFunction log_report_handler = NULL;
124 // A log message handler that gets notified of every log message we process.
125 LogMessageHandlerFunction log_message_handler = NULL;
127 // Helper functions to wrap platform differences.
129 int32 CurrentProcessId() {
130 #if defined(OS_WIN)
131 return GetCurrentProcessId();
132 #elif defined(OS_POSIX)
133 return getpid();
134 #endif
137 uint64 TickCount() {
138 #if defined(OS_WIN)
139 return GetTickCount();
140 #elif defined(OS_MACOSX)
141 return mach_absolute_time();
142 #elif defined(OS_NACL)
143 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
144 // So we have to use clock() for now.
145 return clock();
146 #elif defined(OS_POSIX)
147 struct timespec ts;
148 clock_gettime(CLOCK_MONOTONIC, &ts);
150 uint64 absolute_micro =
151 static_cast<int64>(ts.tv_sec) * 1000000 +
152 static_cast<int64>(ts.tv_nsec) / 1000;
154 return absolute_micro;
155 #endif
158 void DeleteFilePath(const PathString& log_name) {
159 #if defined(OS_WIN)
160 DeleteFile(log_name.c_str());
161 #elif defined (OS_NACL)
162 // Do nothing; unlink() isn't supported on NaCl.
163 #else
164 unlink(log_name.c_str());
165 #endif
168 PathString GetDefaultLogFile() {
169 #if defined(OS_WIN)
170 // On Windows we use the same path as the exe.
171 wchar_t module_name[MAX_PATH];
172 GetModuleFileName(NULL, module_name, MAX_PATH);
174 PathString log_file = module_name;
175 PathString::size_type last_backslash =
176 log_file.rfind('\\', log_file.size());
177 if (last_backslash != PathString::npos)
178 log_file.erase(last_backslash + 1);
179 log_file += L"debug.log";
180 return log_file;
181 #elif defined(OS_POSIX)
182 // On other platforms we just use the current directory.
183 return PathString("debug.log");
184 #endif
187 // This class acts as a wrapper for locking the logging files.
188 // LoggingLock::Init() should be called from the main thread before any logging
189 // is done. Then whenever logging, be sure to have a local LoggingLock
190 // instance on the stack. This will ensure that the lock is unlocked upon
191 // exiting the frame.
192 // LoggingLocks can not be nested.
193 class LoggingLock {
194 public:
195 LoggingLock() {
196 LockLogging();
199 ~LoggingLock() {
200 UnlockLogging();
203 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
204 if (initialized)
205 return;
206 lock_log_file = lock_log;
207 if (lock_log_file == LOCK_LOG_FILE) {
208 #if defined(OS_WIN)
209 if (!log_mutex) {
210 std::wstring safe_name;
211 if (new_log_file)
212 safe_name = new_log_file;
213 else
214 safe_name = GetDefaultLogFile();
215 // \ is not a legal character in mutex names so we replace \ with /
216 std::replace(safe_name.begin(), safe_name.end(), '\\', '/');
217 std::wstring t(L"Global\\");
218 t.append(safe_name);
219 log_mutex = ::CreateMutex(NULL, FALSE, t.c_str());
221 if (log_mutex == NULL) {
222 #if DEBUG
223 // Keep the error code for debugging
224 int error = GetLastError(); // NOLINT
225 base::debug::BreakDebugger();
226 #endif
227 // Return nicely without putting initialized to true.
228 return;
231 #endif
232 } else {
233 log_lock = new base::internal::LockImpl();
235 initialized = true;
238 private:
239 static void LockLogging() {
240 if (lock_log_file == LOCK_LOG_FILE) {
241 #if defined(OS_WIN)
242 ::WaitForSingleObject(log_mutex, INFINITE);
243 // WaitForSingleObject could have returned WAIT_ABANDONED. We don't
244 // abort the process here. UI tests might be crashy sometimes,
245 // and aborting the test binary only makes the problem worse.
246 // We also don't use LOG macros because that might lead to an infinite
247 // loop. For more info see http://crbug.com/18028.
248 #elif defined(OS_POSIX)
249 pthread_mutex_lock(&log_mutex);
250 #endif
251 } else {
252 // use the lock
253 log_lock->Lock();
257 static void UnlockLogging() {
258 if (lock_log_file == LOCK_LOG_FILE) {
259 #if defined(OS_WIN)
260 ReleaseMutex(log_mutex);
261 #elif defined(OS_POSIX)
262 pthread_mutex_unlock(&log_mutex);
263 #endif
264 } else {
265 log_lock->Unlock();
269 // The lock is used if log file locking is false. It helps us avoid problems
270 // with multiple threads writing to the log file at the same time. Use
271 // LockImpl directly instead of using Lock, because Lock makes logging calls.
272 static base::internal::LockImpl* log_lock;
274 // When we don't use a lock, we are using a global mutex. We need to do this
275 // because LockFileEx is not thread safe.
276 #if defined(OS_WIN)
277 static MutexHandle log_mutex;
278 #elif defined(OS_POSIX)
279 static pthread_mutex_t log_mutex;
280 #endif
282 static bool initialized;
283 static LogLockingState lock_log_file;
286 // static
287 bool LoggingLock::initialized = false;
288 // static
289 base::internal::LockImpl* LoggingLock::log_lock = NULL;
290 // static
291 LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
293 #if defined(OS_WIN)
294 // static
295 MutexHandle LoggingLock::log_mutex = NULL;
296 #elif defined(OS_POSIX)
297 pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
298 #endif
300 // Called by logging functions to ensure that debug_file is initialized
301 // and can be used for writing. Returns false if the file could not be
302 // initialized. debug_file will be NULL in this case.
303 bool InitializeLogFileHandle() {
304 if (log_file)
305 return true;
307 if (!log_file_name) {
308 // Nobody has called InitLogging to specify a debug log file, so here we
309 // initialize the log file name to a default.
310 log_file_name = new PathString(GetDefaultLogFile());
313 if ((logging_destination & LOG_TO_FILE) != 0) {
314 #if defined(OS_WIN)
315 log_file = CreateFile(log_file_name->c_str(), GENERIC_WRITE,
316 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
317 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
318 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
319 // try the current directory
320 log_file = CreateFile(L".\\debug.log", GENERIC_WRITE,
321 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
322 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
323 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
324 log_file = NULL;
325 return false;
328 SetFilePointer(log_file, 0, 0, FILE_END);
329 #elif defined(OS_POSIX)
330 log_file = fopen(log_file_name->c_str(), "a");
331 if (log_file == NULL)
332 return false;
333 #endif
336 return true;
339 void CloseFile(FileHandle log) {
340 #if defined(OS_WIN)
341 CloseHandle(log);
342 #else
343 fclose(log);
344 #endif
347 void CloseLogFileUnlocked() {
348 if (!log_file)
349 return;
351 CloseFile(log_file);
352 log_file = NULL;
355 } // namespace
357 LoggingSettings::LoggingSettings()
358 : logging_dest(LOG_DEFAULT),
359 log_file(NULL),
360 lock_log(LOCK_LOG_FILE),
361 delete_old(APPEND_TO_OLD_LOG_FILE),
362 dcheck_state(DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS) {}
364 bool BaseInitLoggingImpl(const LoggingSettings& settings) {
365 #if defined(OS_NACL)
366 // Can log only to the system debug log.
367 CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
368 #endif
369 g_dcheck_state = settings.dcheck_state;
370 CommandLine* command_line = CommandLine::ForCurrentProcess();
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 // NOTE: If g_vlog_info has already been initialized, it might be in use
376 // by another thread. Don't delete the old VLogInfo, just create a second
377 // one. We keep track of both to avoid memory leak warnings.
378 CHECK(!g_vlog_info_prev);
379 g_vlog_info_prev = g_vlog_info;
381 g_vlog_info =
382 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
383 command_line->GetSwitchValueASCII(switches::kVModule),
384 &min_log_level);
387 logging_destination = settings.logging_dest;
389 // ignore file options unless logging to file is set.
390 if ((logging_destination & LOG_TO_FILE) == 0)
391 return true;
393 LoggingLock::Init(settings.lock_log, settings.log_file);
394 LoggingLock logging_lock;
396 // Calling InitLogging twice or after some log call has already opened the
397 // default log file will re-initialize to the new options.
398 CloseLogFileUnlocked();
400 if (!log_file_name)
401 log_file_name = new PathString();
402 *log_file_name = settings.log_file;
403 if (settings.delete_old == DELETE_OLD_LOG_FILE)
404 DeleteFilePath(*log_file_name);
406 return InitializeLogFileHandle();
409 void SetMinLogLevel(int level) {
410 min_log_level = std::min(LOG_ERROR_REPORT, level);
413 int GetMinLogLevel() {
414 return min_log_level;
417 int GetVlogVerbosity() {
418 return std::max(-1, LOG_INFO - GetMinLogLevel());
421 int GetVlogLevelHelper(const char* file, size_t N) {
422 DCHECK_GT(N, 0U);
423 // Note: g_vlog_info may change on a different thread during startup
424 // (but will always be valid or NULL).
425 VlogInfo* vlog_info = g_vlog_info;
426 return vlog_info ?
427 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
428 GetVlogVerbosity();
431 void SetLogItems(bool enable_process_id, bool enable_thread_id,
432 bool enable_timestamp, bool enable_tickcount) {
433 log_process_id = enable_process_id;
434 log_thread_id = enable_thread_id;
435 log_timestamp = enable_timestamp;
436 log_tickcount = enable_tickcount;
439 void SetShowErrorDialogs(bool enable_dialogs) {
440 show_error_dialogs = enable_dialogs;
443 void SetLogAssertHandler(LogAssertHandlerFunction handler) {
444 log_assert_handler = handler;
447 void SetLogReportHandler(LogReportHandlerFunction handler) {
448 log_report_handler = handler;
451 void SetLogMessageHandler(LogMessageHandlerFunction handler) {
452 log_message_handler = handler;
455 LogMessageHandlerFunction GetLogMessageHandler() {
456 return log_message_handler;
459 // MSVC doesn't like complex extern templates and DLLs.
460 #if !defined(COMPILER_MSVC)
461 // Explicit instantiations for commonly used comparisons.
462 template std::string* MakeCheckOpString<int, int>(
463 const int&, const int&, const char* names);
464 template std::string* MakeCheckOpString<unsigned long, unsigned long>(
465 const unsigned long&, const unsigned long&, const char* names);
466 template std::string* MakeCheckOpString<unsigned long, unsigned int>(
467 const unsigned long&, const unsigned int&, const char* names);
468 template std::string* MakeCheckOpString<unsigned int, unsigned long>(
469 const unsigned int&, const unsigned long&, const char* names);
470 template std::string* MakeCheckOpString<std::string, std::string>(
471 const std::string&, const std::string&, const char* name);
472 #endif
474 // Displays a message box to the user with the error message in it.
475 // Used for fatal messages, where we close the app simultaneously.
476 // This is for developers only; we don't use this in circumstances
477 // (like release builds) where users could see it, since users don't
478 // understand these messages anyway.
479 void DisplayDebugMessageInDialog(const std::string& str) {
480 if (str.empty())
481 return;
483 if (!show_error_dialogs)
484 return;
486 #if defined(OS_WIN)
487 // For Windows programs, it's possible that the message loop is
488 // messed up on a fatal error, and creating a MessageBox will cause
489 // that message loop to be run. Instead, we try to spawn another
490 // process that displays its command line. We look for "Debug
491 // Message.exe" in the same directory as the application. If it
492 // exists, we use it, otherwise, we use a regular message box.
493 wchar_t prog_name[MAX_PATH];
494 GetModuleFileNameW(NULL, prog_name, MAX_PATH);
495 wchar_t* backslash = wcsrchr(prog_name, '\\');
496 if (backslash)
497 backslash[1] = 0;
498 wcscat_s(prog_name, MAX_PATH, L"debug_message.exe");
500 std::wstring cmdline = base::UTF8ToWide(str);
501 if (cmdline.empty())
502 return;
504 STARTUPINFO startup_info;
505 memset(&startup_info, 0, sizeof(startup_info));
506 startup_info.cb = sizeof(startup_info);
508 PROCESS_INFORMATION process_info;
509 if (CreateProcessW(prog_name, &cmdline[0], NULL, NULL, false, 0, NULL,
510 NULL, &startup_info, &process_info)) {
511 WaitForSingleObject(process_info.hProcess, INFINITE);
512 CloseHandle(process_info.hThread);
513 CloseHandle(process_info.hProcess);
514 } else {
515 // debug process broken, let's just do a message box
516 MessageBoxW(NULL, &cmdline[0], L"Fatal error",
517 MB_OK | MB_ICONHAND | MB_TOPMOST);
519 #else
520 // We intentionally don't implement a dialog on other platforms.
521 // You can just look at stderr.
522 #endif
525 #if defined(OS_WIN)
526 LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
529 LogMessage::SaveLastError::~SaveLastError() {
530 ::SetLastError(last_error_);
532 #endif // defined(OS_WIN)
534 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
535 int ctr)
536 : severity_(severity), file_(file), line_(line) {
537 Init(file, line);
540 LogMessage::LogMessage(const char* file, int line)
541 : severity_(LOG_INFO), file_(file), line_(line) {
542 Init(file, line);
545 LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
546 : severity_(severity), file_(file), line_(line) {
547 Init(file, line);
550 LogMessage::LogMessage(const char* file, int line, std::string* result)
551 : severity_(LOG_FATAL), file_(file), line_(line) {
552 Init(file, line);
553 stream_ << "Check failed: " << *result;
554 delete result;
557 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
558 std::string* result)
559 : severity_(severity), file_(file), line_(line) {
560 Init(file, line);
561 stream_ << "Check failed: " << *result;
562 delete result;
565 LogMessage::~LogMessage() {
566 #if !defined(NDEBUG) && !defined(OS_NACL)
567 if (severity_ == LOG_FATAL) {
568 // Include a stack trace on a fatal.
569 base::debug::StackTrace trace;
570 stream_ << std::endl; // Newline to separate from log message.
571 trace.OutputToStream(&stream_);
573 #endif
574 stream_ << std::endl;
575 std::string str_newline(stream_.str());
577 // Give any log message handler first dibs on the message.
578 if (log_message_handler &&
579 log_message_handler(severity_, file_, line_,
580 message_start_, str_newline)) {
581 // The handler took care of it, no further processing.
582 return;
585 if ((logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
586 #if defined(OS_WIN)
587 OutputDebugStringA(str_newline.c_str());
588 #elif defined(OS_ANDROID)
589 android_LogPriority priority =
590 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
591 switch (severity_) {
592 case LOG_INFO:
593 priority = ANDROID_LOG_INFO;
594 break;
595 case LOG_WARNING:
596 priority = ANDROID_LOG_WARN;
597 break;
598 case LOG_ERROR:
599 case LOG_ERROR_REPORT:
600 priority = ANDROID_LOG_ERROR;
601 break;
602 case LOG_FATAL:
603 priority = ANDROID_LOG_FATAL;
604 break;
606 __android_log_write(priority, "chromium", str_newline.c_str());
607 #endif
608 fprintf(stderr, "%s", str_newline.c_str());
609 fflush(stderr);
610 } else if (severity_ >= kAlwaysPrintErrorLevel) {
611 // When we're only outputting to a log file, above a certain log level, we
612 // should still output to stderr so that we can better detect and diagnose
613 // problems with unit tests, especially on the buildbots.
614 fprintf(stderr, "%s", str_newline.c_str());
615 fflush(stderr);
618 // write to log file
619 if ((logging_destination & LOG_TO_FILE) != 0) {
620 // We can have multiple threads and/or processes, so try to prevent them
621 // from clobbering each other's writes.
622 // If the client app did not call InitLogging, and the lock has not
623 // been created do it now. We do this on demand, but if two threads try
624 // to do this at the same time, there will be a race condition to create
625 // the lock. This is why InitLogging should be called from the main
626 // thread at the beginning of execution.
627 LoggingLock::Init(LOCK_LOG_FILE, NULL);
628 LoggingLock logging_lock;
629 if (InitializeLogFileHandle()) {
630 #if defined(OS_WIN)
631 SetFilePointer(log_file, 0, 0, SEEK_END);
632 DWORD num_written;
633 WriteFile(log_file,
634 static_cast<const void*>(str_newline.c_str()),
635 static_cast<DWORD>(str_newline.length()),
636 &num_written,
637 NULL);
638 #else
639 fprintf(log_file, "%s", str_newline.c_str());
640 fflush(log_file);
641 #endif
645 if (severity_ == LOG_FATAL) {
646 // Ensure the first characters of the string are on the stack so they
647 // are contained in minidumps for diagnostic purposes.
648 char str_stack[1024];
649 str_newline.copy(str_stack, arraysize(str_stack));
650 base::debug::Alias(str_stack);
652 if (log_assert_handler) {
653 // Make a copy of the string for the handler out of paranoia.
654 log_assert_handler(std::string(stream_.str()));
655 } else {
656 // Don't use the string with the newline, get a fresh version to send to
657 // the debug message process. We also don't display assertions to the
658 // user in release mode. The enduser can't do anything with this
659 // information, and displaying message boxes when the application is
660 // hosed can cause additional problems.
661 #ifndef NDEBUG
662 DisplayDebugMessageInDialog(stream_.str());
663 #endif
664 // Crash the process to generate a dump.
665 base::debug::BreakDebugger();
667 } else if (severity_ == LOG_ERROR_REPORT) {
668 // We are here only if the user runs with --enable-dcheck in release mode.
669 if (log_report_handler) {
670 log_report_handler(std::string(stream_.str()));
671 } else {
672 DisplayDebugMessageInDialog(stream_.str());
677 // writes the common header info to the stream
678 void LogMessage::Init(const char* file, int line) {
679 base::StringPiece filename(file);
680 size_t last_slash_pos = filename.find_last_of("\\/");
681 if (last_slash_pos != base::StringPiece::npos)
682 filename.remove_prefix(last_slash_pos + 1);
684 // TODO(darin): It might be nice if the columns were fixed width.
686 stream_ << '[';
687 if (log_process_id)
688 stream_ << CurrentProcessId() << ':';
689 if (log_thread_id)
690 stream_ << base::PlatformThread::CurrentId() << ':';
691 if (log_timestamp) {
692 time_t t = time(NULL);
693 struct tm local_time = {0};
694 #if _MSC_VER >= 1400
695 localtime_s(&local_time, &t);
696 #else
697 localtime_r(&t, &local_time);
698 #endif
699 struct tm* tm_time = &local_time;
700 stream_ << std::setfill('0')
701 << std::setw(2) << 1 + tm_time->tm_mon
702 << std::setw(2) << tm_time->tm_mday
703 << '/'
704 << std::setw(2) << tm_time->tm_hour
705 << std::setw(2) << tm_time->tm_min
706 << std::setw(2) << tm_time->tm_sec
707 << ':';
709 if (log_tickcount)
710 stream_ << TickCount() << ':';
711 if (severity_ >= 0)
712 stream_ << log_severity_name(severity_);
713 else
714 stream_ << "VERBOSE" << -severity_;
716 stream_ << ":" << filename << "(" << line << ")] ";
718 message_start_ = stream_.tellp();
721 #if defined(OS_WIN)
722 // This has already been defined in the header, but defining it again as DWORD
723 // ensures that the type used in the header is equivalent to DWORD. If not,
724 // the redefinition is a compile error.
725 typedef DWORD SystemErrorCode;
726 #endif
728 SystemErrorCode GetLastSystemErrorCode() {
729 #if defined(OS_WIN)
730 return ::GetLastError();
731 #elif defined(OS_POSIX)
732 return errno;
733 #else
734 #error Not implemented
735 #endif
738 #if defined(OS_WIN)
739 Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
740 int line,
741 LogSeverity severity,
742 SystemErrorCode err,
743 const char* module)
744 : err_(err),
745 module_(module),
746 log_message_(file, line, severity) {
749 Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
750 int line,
751 LogSeverity severity,
752 SystemErrorCode err)
753 : err_(err),
754 module_(NULL),
755 log_message_(file, line, severity) {
758 Win32ErrorLogMessage::~Win32ErrorLogMessage() {
759 const int error_message_buffer_size = 256;
760 char msgbuf[error_message_buffer_size];
761 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
762 HMODULE hmod;
763 if (module_) {
764 hmod = GetModuleHandleA(module_);
765 if (hmod) {
766 flags |= FORMAT_MESSAGE_FROM_HMODULE;
767 } else {
768 // This makes a nested Win32ErrorLogMessage. It will have module_ of NULL
769 // so it will not call GetModuleHandle, so recursive errors are
770 // impossible.
771 DPLOG(WARNING) << "Couldn't open module " << module_
772 << " for error message query";
774 } else {
775 hmod = NULL;
777 DWORD len = FormatMessageA(flags,
778 hmod,
779 err_,
781 msgbuf,
782 sizeof(msgbuf) / sizeof(msgbuf[0]),
783 NULL);
784 if (len) {
785 while ((len > 0) &&
786 isspace(static_cast<unsigned char>(msgbuf[len - 1]))) {
787 msgbuf[--len] = 0;
789 stream() << ": " << msgbuf;
790 } else {
791 stream() << ": Error " << GetLastError() << " while retrieving error "
792 << err_;
794 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
795 // field) and use Alias in hopes that it makes it into crash dumps.
796 DWORD last_error = err_;
797 base::debug::Alias(&last_error);
799 #elif defined(OS_POSIX)
800 ErrnoLogMessage::ErrnoLogMessage(const char* file,
801 int line,
802 LogSeverity severity,
803 SystemErrorCode err)
804 : err_(err),
805 log_message_(file, line, severity) {
808 ErrnoLogMessage::~ErrnoLogMessage() {
809 stream() << ": " << safe_strerror(err_);
811 #endif // OS_WIN
813 void CloseLogFile() {
814 LoggingLock logging_lock;
815 CloseLogFileUnlocked();
818 void RawLog(int level, const char* message) {
819 if (level >= min_log_level) {
820 size_t bytes_written = 0;
821 const size_t message_len = strlen(message);
822 int rv;
823 while (bytes_written < message_len) {
824 rv = HANDLE_EINTR(
825 write(STDERR_FILENO, message + bytes_written,
826 message_len - bytes_written));
827 if (rv < 0) {
828 // Give up, nothing we can do now.
829 break;
831 bytes_written += rv;
834 if (message_len > 0 && message[message_len - 1] != '\n') {
835 do {
836 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
837 if (rv < 0) {
838 // Give up, nothing we can do now.
839 break;
841 } while (rv != 1);
845 if (level == LOG_FATAL)
846 base::debug::BreakDebugger();
849 // This was defined at the beginning of this file.
850 #undef write
852 #if defined(OS_WIN)
853 std::wstring GetLogFileFullPath() {
854 if (log_file_name)
855 return *log_file_name;
856 return std::wstring();
858 #endif
860 } // namespace logging
862 std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) {
863 return out << base::WideToUTF8(std::wstring(wstr));