blob: 0c4a3027340abf8777e7ad56218e02a3241b021d [file] [log] [blame]
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001// 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.
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/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
28
29#if defined(OS_POSIX)
30#include <errno.h>
31#include <pthread.h>
Torne (Richard Coles)58218062012-11-14 11:43:16 +000032#include <stdio.h>
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +010033#include <stdlib.h>
Torne (Richard Coles)58218062012-11-14 11:43:16 +000034#include <string.h>
35#include <unistd.h>
36#define MAX_PATH PATH_MAX
37typedef FILE* FileHandle;
38typedef pthread_mutex_t* MutexHandle;
39#endif
40
41#include <algorithm>
42#include <cstring>
43#include <ctime>
44#include <iomanip>
45#include <ostream>
46
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"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000052#include "base/posix/eintr_wrapper.h"
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +010053#include "base/strings/string_piece.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000054#include "base/synchronization/lock_impl.h"
55#include "base/threading/platform_thread.h"
56#include "base/utf_string_conversions.h"
57#include "base/vlog.h"
58#if defined(OS_POSIX)
59#include "base/safe_strerror_posix.h"
60#endif
61
62#if defined(OS_ANDROID)
63#include <android/log.h>
64#endif
65
66namespace logging {
67
68DcheckState g_dcheck_state = DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS;
69
70namespace {
71
72VlogInfo* g_vlog_info = NULL;
73VlogInfo* g_vlog_info_prev = NULL;
74
75const char* const log_severity_names[LOG_NUM_SEVERITIES] = {
76 "INFO", "WARNING", "ERROR", "ERROR_REPORT", "FATAL" };
77
78int min_log_level = 0;
79
80// The default set here for logging_destination will only be used if
81// InitLogging is not called. On Windows, use a file next to the exe;
82// on POSIX platforms, where it may not even be possible to locate the
83// executable on disk, use stderr.
84#if defined(OS_WIN)
85LoggingDestination logging_destination = LOG_ONLY_TO_FILE;
86#elif defined(OS_POSIX)
87LoggingDestination logging_destination = LOG_ONLY_TO_SYSTEM_DEBUG_LOG;
88#endif
89
90// For LOG_ERROR and above, always print to stderr.
91const int kAlwaysPrintErrorLevel = LOG_ERROR;
92
93// Which log file to use? This is initialized by InitLogging or
94// will be lazily initialized to the default value when it is
95// first needed.
96#if defined(OS_WIN)
97typedef std::wstring PathString;
98#else
99typedef std::string PathString;
100#endif
101PathString* log_file_name = NULL;
102
103// this file is lazily opened and the handle may be NULL
104FileHandle log_file = NULL;
105
106// what should be prepended to each message?
107bool log_process_id = false;
108bool log_thread_id = false;
109bool log_timestamp = true;
110bool log_tickcount = false;
111
112// Should we pop up fatal debug messages in a dialog?
113bool show_error_dialogs = false;
114
115// An assert handler override specified by the client to be called instead of
116// the debug message dialog and process termination.
117LogAssertHandlerFunction log_assert_handler = NULL;
118// An report handler override specified by the client to be called instead of
119// the debug message dialog.
120LogReportHandlerFunction log_report_handler = NULL;
121// A log message handler that gets notified of every log message we process.
122LogMessageHandlerFunction log_message_handler = NULL;
123
124// Helper functions to wrap platform differences.
125
126int32 CurrentProcessId() {
127#if defined(OS_WIN)
128 return GetCurrentProcessId();
129#elif defined(OS_POSIX)
130 return getpid();
131#endif
132}
133
134uint64 TickCount() {
135#if defined(OS_WIN)
136 return GetTickCount();
137#elif defined(OS_MACOSX)
138 return mach_absolute_time();
139#elif defined(OS_NACL)
140 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
141 // So we have to use clock() for now.
142 return clock();
143#elif defined(OS_POSIX)
144 struct timespec ts;
145 clock_gettime(CLOCK_MONOTONIC, &ts);
146
147 uint64 absolute_micro =
148 static_cast<int64>(ts.tv_sec) * 1000000 +
149 static_cast<int64>(ts.tv_nsec) / 1000;
150
151 return absolute_micro;
152#endif
153}
154
155void CloseFile(FileHandle log) {
156#if defined(OS_WIN)
157 CloseHandle(log);
158#else
159 fclose(log);
160#endif
161}
162
163void DeleteFilePath(const PathString& log_name) {
164#if defined(OS_WIN)
165 DeleteFile(log_name.c_str());
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100166#elif defined (OS_NACL)
167 // Do nothing; unlink() isn't supported on NaCl.
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000168#else
169 unlink(log_name.c_str());
170#endif
171}
172
173PathString GetDefaultLogFile() {
174#if defined(OS_WIN)
175 // On Windows we use the same path as the exe.
176 wchar_t module_name[MAX_PATH];
177 GetModuleFileName(NULL, module_name, MAX_PATH);
178
179 PathString log_file = module_name;
180 PathString::size_type last_backslash =
181 log_file.rfind('\\', log_file.size());
182 if (last_backslash != PathString::npos)
183 log_file.erase(last_backslash + 1);
184 log_file += L"debug.log";
185 return log_file;
186#elif defined(OS_POSIX)
187 // On other platforms we just use the current directory.
188 return PathString("debug.log");
189#endif
190}
191
192// This class acts as a wrapper for locking the logging files.
193// LoggingLock::Init() should be called from the main thread before any logging
194// is done. Then whenever logging, be sure to have a local LoggingLock
195// instance on the stack. This will ensure that the lock is unlocked upon
196// exiting the frame.
197// LoggingLocks can not be nested.
198class LoggingLock {
199 public:
200 LoggingLock() {
201 LockLogging();
202 }
203
204 ~LoggingLock() {
205 UnlockLogging();
206 }
207
208 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
209 if (initialized)
210 return;
211 lock_log_file = lock_log;
212 if (lock_log_file == LOCK_LOG_FILE) {
213#if defined(OS_WIN)
214 if (!log_mutex) {
215 std::wstring safe_name;
216 if (new_log_file)
217 safe_name = new_log_file;
218 else
219 safe_name = GetDefaultLogFile();
220 // \ is not a legal character in mutex names so we replace \ with /
221 std::replace(safe_name.begin(), safe_name.end(), '\\', '/');
222 std::wstring t(L"Global\\");
223 t.append(safe_name);
224 log_mutex = ::CreateMutex(NULL, FALSE, t.c_str());
225
226 if (log_mutex == NULL) {
227#if DEBUG
228 // Keep the error code for debugging
229 int error = GetLastError(); // NOLINT
230 base::debug::BreakDebugger();
231#endif
232 // Return nicely without putting initialized to true.
233 return;
234 }
235 }
236#endif
237 } else {
238 log_lock = new base::internal::LockImpl();
239 }
240 initialized = true;
241 }
242
243 private:
244 static void LockLogging() {
245 if (lock_log_file == LOCK_LOG_FILE) {
246#if defined(OS_WIN)
247 ::WaitForSingleObject(log_mutex, INFINITE);
248 // WaitForSingleObject could have returned WAIT_ABANDONED. We don't
249 // abort the process here. UI tests might be crashy sometimes,
250 // and aborting the test binary only makes the problem worse.
251 // We also don't use LOG macros because that might lead to an infinite
252 // loop. For more info see http://crbug.com/18028.
253#elif defined(OS_POSIX)
254 pthread_mutex_lock(&log_mutex);
255#endif
256 } else {
257 // use the lock
258 log_lock->Lock();
259 }
260 }
261
262 static void UnlockLogging() {
263 if (lock_log_file == LOCK_LOG_FILE) {
264#if defined(OS_WIN)
265 ReleaseMutex(log_mutex);
266#elif defined(OS_POSIX)
267 pthread_mutex_unlock(&log_mutex);
268#endif
269 } else {
270 log_lock->Unlock();
271 }
272 }
273
274 // The lock is used if log file locking is false. It helps us avoid problems
275 // with multiple threads writing to the log file at the same time. Use
276 // LockImpl directly instead of using Lock, because Lock makes logging calls.
277 static base::internal::LockImpl* log_lock;
278
279 // When we don't use a lock, we are using a global mutex. We need to do this
280 // because LockFileEx is not thread safe.
281#if defined(OS_WIN)
282 static MutexHandle log_mutex;
283#elif defined(OS_POSIX)
284 static pthread_mutex_t log_mutex;
285#endif
286
287 static bool initialized;
288 static LogLockingState lock_log_file;
289};
290
291// static
292bool LoggingLock::initialized = false;
293// static
294base::internal::LockImpl* LoggingLock::log_lock = NULL;
295// static
296LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
297
298#if defined(OS_WIN)
299// static
300MutexHandle LoggingLock::log_mutex = NULL;
301#elif defined(OS_POSIX)
302pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
303#endif
304
305// Called by logging functions to ensure that debug_file is initialized
306// and can be used for writing. Returns false if the file could not be
307// initialized. debug_file will be NULL in this case.
308bool InitializeLogFileHandle() {
309 if (log_file)
310 return true;
311
312 if (!log_file_name) {
313 // Nobody has called InitLogging to specify a debug log file, so here we
314 // initialize the log file name to a default.
315 log_file_name = new PathString(GetDefaultLogFile());
316 }
317
318 if (logging_destination == LOG_ONLY_TO_FILE ||
319 logging_destination == LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG) {
320#if defined(OS_WIN)
321 log_file = CreateFile(log_file_name->c_str(), GENERIC_WRITE,
322 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
323 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
324 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
325 // try the current directory
326 log_file = CreateFile(L".\\debug.log", GENERIC_WRITE,
327 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
328 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
329 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
330 log_file = NULL;
331 return false;
332 }
333 }
334 SetFilePointer(log_file, 0, 0, FILE_END);
335#elif defined(OS_POSIX)
336 log_file = fopen(log_file_name->c_str(), "a");
337 if (log_file == NULL)
338 return false;
339#endif
340 }
341
342 return true;
343}
344
345} // namespace
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) {
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100353#if defined(OS_NACL)
354 CHECK(logging_dest == LOG_NONE ||
355 logging_dest == LOG_ONLY_TO_SYSTEM_DEBUG_LOG);
356#endif
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000357 g_dcheck_state = dcheck_state;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000358 CommandLine* command_line = CommandLine::ForCurrentProcess();
359 // Don't bother initializing g_vlog_info unless we use one of the
360 // vlog switches.
361 if (command_line->HasSwitch(switches::kV) ||
362 command_line->HasSwitch(switches::kVModule)) {
363 // NOTE: If g_vlog_info has already been initialized, it might be in use
364 // by another thread. Don't delete the old VLogInfo, just create a second
365 // one. We keep track of both to avoid memory leak warnings.
366 CHECK(!g_vlog_info_prev);
367 g_vlog_info_prev = g_vlog_info;
368
369 g_vlog_info =
370 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
371 command_line->GetSwitchValueASCII(switches::kVModule),
372 &min_log_level);
373 }
374
375 LoggingLock::Init(lock_log, new_log_file);
376
377 LoggingLock logging_lock;
378
379 if (log_file) {
380 // calling InitLogging twice or after some log call has already opened the
381 // default log file will re-initialize to the new options
382 CloseFile(log_file);
383 log_file = NULL;
384 }
385
386 logging_destination = logging_dest;
387
388 // ignore file options if logging is disabled or only to system
389 if (logging_destination == LOG_NONE ||
390 logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG)
391 return true;
392
393 if (!log_file_name)
394 log_file_name = new PathString();
395 *log_file_name = new_log_file;
396 if (delete_old == DELETE_OLD_LOG_FILE)
397 DeleteFilePath(*log_file_name);
398
399 return InitializeLogFileHandle();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000400}
401
402void SetMinLogLevel(int level) {
403 min_log_level = std::min(LOG_ERROR_REPORT, level);
404}
405
406int GetMinLogLevel() {
407 return min_log_level;
408}
409
410int GetVlogVerbosity() {
411 return std::max(-1, LOG_INFO - GetMinLogLevel());
412}
413
414int GetVlogLevelHelper(const char* file, size_t N) {
415 DCHECK_GT(N, 0U);
416 // Note: g_vlog_info may change on a different thread during startup
417 // (but will always be valid or NULL).
418 VlogInfo* vlog_info = g_vlog_info;
419 return vlog_info ?
420 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
421 GetVlogVerbosity();
422}
423
424void SetLogItems(bool enable_process_id, bool enable_thread_id,
425 bool enable_timestamp, bool enable_tickcount) {
426 log_process_id = enable_process_id;
427 log_thread_id = enable_thread_id;
428 log_timestamp = enable_timestamp;
429 log_tickcount = enable_tickcount;
430}
431
432void SetShowErrorDialogs(bool enable_dialogs) {
433 show_error_dialogs = enable_dialogs;
434}
435
436void SetLogAssertHandler(LogAssertHandlerFunction handler) {
437 log_assert_handler = handler;
438}
439
440void SetLogReportHandler(LogReportHandlerFunction handler) {
441 log_report_handler = handler;
442}
443
444void SetLogMessageHandler(LogMessageHandlerFunction handler) {
445 log_message_handler = handler;
446}
447
448LogMessageHandlerFunction GetLogMessageHandler() {
449 return log_message_handler;
450}
451
452// MSVC doesn't like complex extern templates and DLLs.
453#if !defined(COMPILER_MSVC)
454// Explicit instantiations for commonly used comparisons.
455template std::string* MakeCheckOpString<int, int>(
456 const int&, const int&, const char* names);
457template std::string* MakeCheckOpString<unsigned long, unsigned long>(
458 const unsigned long&, const unsigned long&, const char* names);
459template std::string* MakeCheckOpString<unsigned long, unsigned int>(
460 const unsigned long&, const unsigned int&, const char* names);
461template std::string* MakeCheckOpString<unsigned int, unsigned long>(
462 const unsigned int&, const unsigned long&, const char* names);
463template std::string* MakeCheckOpString<std::string, std::string>(
464 const std::string&, const std::string&, const char* name);
465#endif
466
467// Displays a message box to the user with the error message in it.
468// Used for fatal messages, where we close the app simultaneously.
469// This is for developers only; we don't use this in circumstances
470// (like release builds) where users could see it, since users don't
471// understand these messages anyway.
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#else
513 // We intentionally don't implement a dialog on other platforms.
514 // You can just look at stderr.
515#endif
516}
517
518#if defined(OS_WIN)
519LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
520}
521
522LogMessage::SaveLastError::~SaveLastError() {
523 ::SetLastError(last_error_);
524}
525#endif // defined(OS_WIN)
526
527LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
528 int ctr)
529 : severity_(severity), file_(file), line_(line) {
530 Init(file, line);
531}
532
533LogMessage::LogMessage(const char* file, int line)
534 : severity_(LOG_INFO), file_(file), line_(line) {
535 Init(file, line);
536}
537
538LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
539 : severity_(severity), file_(file), line_(line) {
540 Init(file, line);
541}
542
543LogMessage::LogMessage(const char* file, int line, std::string* result)
544 : severity_(LOG_FATAL), file_(file), line_(line) {
545 Init(file, line);
546 stream_ << "Check failed: " << *result;
547 delete result;
548}
549
550LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
551 std::string* result)
552 : severity_(severity), file_(file), line_(line) {
553 Init(file, line);
554 stream_ << "Check failed: " << *result;
555 delete result;
556}
557
558LogMessage::~LogMessage() {
559 // TODO(port): enable stacktrace generation on LOG_FATAL once backtrace are
560 // working in Android.
561#if !defined(NDEBUG) && !defined(OS_ANDROID) && !defined(OS_NACL)
562 if (severity_ == LOG_FATAL) {
563 // Include a stack trace on a fatal.
564 base::debug::StackTrace trace;
565 stream_ << std::endl; // Newline to separate from log message.
566 trace.OutputToStream(&stream_);
567 }
568#endif
569 stream_ << std::endl;
570 std::string str_newline(stream_.str());
571
572 // Give any log message handler first dibs on the message.
573 if (log_message_handler && log_message_handler(severity_, file_, line_,
574 message_start_, str_newline)) {
575 // The handler took care of it, no further processing.
576 return;
577 }
578
579 if (logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG ||
580 logging_destination == LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG) {
581#if defined(OS_WIN)
582 OutputDebugStringA(str_newline.c_str());
583#elif defined(OS_ANDROID)
584 android_LogPriority priority = ANDROID_LOG_UNKNOWN;
585 switch (severity_) {
586 case LOG_INFO:
587 priority = ANDROID_LOG_INFO;
588 break;
589 case LOG_WARNING:
590 priority = ANDROID_LOG_WARN;
591 break;
592 case LOG_ERROR:
593 case LOG_ERROR_REPORT:
594 priority = ANDROID_LOG_ERROR;
595 break;
596 case LOG_FATAL:
597 priority = ANDROID_LOG_FATAL;
598 break;
599 }
600 __android_log_write(priority, "chromium", str_newline.c_str());
601#endif
602 fprintf(stderr, "%s", str_newline.c_str());
603 fflush(stderr);
604 } else if (severity_ >= kAlwaysPrintErrorLevel) {
605 // When we're only outputting to a log file, above a certain log level, we
606 // should still output to stderr so that we can better detect and diagnose
607 // problems with unit tests, especially on the buildbots.
608 fprintf(stderr, "%s", str_newline.c_str());
609 fflush(stderr);
610 }
611
612 // We can have multiple threads and/or processes, so try to prevent them
613 // from clobbering each other's writes.
614 // If the client app did not call InitLogging, and the lock has not
615 // been created do it now. We do this on demand, but if two threads try
616 // to do this at the same time, there will be a race condition to create
617 // the lock. This is why InitLogging should be called from the main
618 // thread at the beginning of execution.
619 LoggingLock::Init(LOCK_LOG_FILE, NULL);
620 // write to log file
621 if (logging_destination != LOG_NONE &&
622 logging_destination != LOG_ONLY_TO_SYSTEM_DEBUG_LOG) {
623 LoggingLock logging_lock;
624 if (InitializeLogFileHandle()) {
625#if defined(OS_WIN)
626 SetFilePointer(log_file, 0, 0, SEEK_END);
627 DWORD num_written;
628 WriteFile(log_file,
629 static_cast<const void*>(str_newline.c_str()),
630 static_cast<DWORD>(str_newline.length()),
631 &num_written,
632 NULL);
633#else
634 fprintf(log_file, "%s", str_newline.c_str());
635 fflush(log_file);
636#endif
637 }
638 }
639
640 if (severity_ == LOG_FATAL) {
641 // Ensure the first characters of the string are on the stack so they
642 // are contained in minidumps for diagnostic purposes.
643 char str_stack[1024];
644 str_newline.copy(str_stack, arraysize(str_stack));
645 base::debug::Alias(str_stack);
646
647 // display a message or break into the debugger on a fatal error
648 if (base::debug::BeingDebugged()) {
649 base::debug::BreakDebugger();
650 } else {
651 if (log_assert_handler) {
652 // make a copy of the string for the handler out of paranoia
653 log_assert_handler(std::string(stream_.str()));
654 } else {
655 // Don't use the string with the newline, get a fresh version to send to
656 // the debug message process. We also don't display assertions to the
657 // user in release mode. The enduser can't do anything with this
658 // information, and displaying message boxes when the application is
659 // hosed can cause additional problems.
660#ifndef NDEBUG
661 DisplayDebugMessageInDialog(stream_.str());
662#endif
663 // Crash the process to generate a dump.
664 base::debug::BreakDebugger();
665 }
666 }
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());
673 }
674 }
675}
676
677// writes the common header info to the stream
678void 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);
683
684 // TODO(darin): It might be nice if the columns were fixed width.
685
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 << ':';
708 }
709 if (log_tickcount)
710 stream_ << TickCount() << ':';
711 if (severity_ >= 0)
712 stream_ << log_severity_names[severity_];
713 else
714 stream_ << "VERBOSE" << -severity_;
715
716 stream_ << ":" << filename << "(" << line << ")] ";
717
718 message_start_ = stream_.tellp();
719}
720
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.
725typedef DWORD SystemErrorCode;
726#endif
727
728SystemErrorCode 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
736}
737
738#if defined(OS_WIN)
739Win32ErrorLogMessage::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) {
747}
748
749Win32ErrorLogMessage::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) {
756}
757
758Win32ErrorLogMessage::~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";
773 }
774 } else {
775 hmod = NULL;
776 }
777 DWORD len = FormatMessageA(flags,
778 hmod,
779 err_,
780 0,
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;
788 }
789 stream() << ": " << msgbuf;
790 } else {
791 stream() << ": Error " << GetLastError() << " while retrieving error "
792 << err_;
793 }
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);
798}
799#elif defined(OS_POSIX)
800ErrnoLogMessage::ErrnoLogMessage(const char* file,
801 int line,
802 LogSeverity severity,
803 SystemErrorCode err)
804 : err_(err),
805 log_message_(file, line, severity) {
806}
807
808ErrnoLogMessage::~ErrnoLogMessage() {
809 stream() << ": " << safe_strerror(err_);
810}
811#endif // OS_WIN
812
813void CloseLogFile() {
814 LoggingLock logging_lock;
815
816 if (!log_file)
817 return;
818
819 CloseFile(log_file);
820 log_file = NULL;
821}
822
823void RawLog(int level, const char* message) {
824 if (level >= min_log_level) {
825 size_t bytes_written = 0;
826 const size_t message_len = strlen(message);
827 int rv;
828 while (bytes_written < message_len) {
829 rv = HANDLE_EINTR(
830 write(STDERR_FILENO, message + bytes_written,
831 message_len - bytes_written));
832 if (rv < 0) {
833 // Give up, nothing we can do now.
834 break;
835 }
836 bytes_written += rv;
837 }
838
839 if (message_len > 0 && message[message_len - 1] != '\n') {
840 do {
841 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
842 if (rv < 0) {
843 // Give up, nothing we can do now.
844 break;
845 }
846 } while (rv != 1);
847 }
848 }
849
850 if (level == LOG_FATAL)
851 base::debug::BreakDebugger();
852}
853
854// This was defined at the beginning of this file.
855#undef write
856
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000857#if defined(OS_WIN)
858std::wstring GetLogFileFullPath() {
859 if (log_file_name)
860 return *log_file_name;
861 return std::wstring();
862}
863#endif
864
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000865} // namespace logging
866
867std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) {
868 return out << WideToUTF8(std::wstring(wstr));
869}