Suppress tabs permission warning if there is already a browsingHistory warning.
[chromium-blink-merge.git] / chrome / common / logging_chrome.cc
blob93114258135c541e24bf5bbd5f03a5359c8d8da3
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 "build/build_config.h"
7 // Need to include this before most other files because it defines
8 // IPC_MESSAGE_LOG_ENABLED. We need to use it to define
9 // IPC_MESSAGE_MACROS_LOG_ENABLED so render_messages.h will generate the
10 // ViewMsgLog et al. functions.
11 #include "ipc/ipc_message.h"
13 // On Windows, the about:ipc dialog shows IPCs; on POSIX, we hook up a
14 // logger in this file. (We implement about:ipc on Mac but implement
15 // the loggers here anyway). We need to do this real early to be sure
16 // IPC_MESSAGE_MACROS_LOG_ENABLED doesn't get undefined.
17 #if defined(OS_POSIX) && defined(IPC_MESSAGE_LOG_ENABLED)
18 #define IPC_MESSAGE_MACROS_LOG_ENABLED
19 #include "content/public/common/content_ipc_logging.h"
20 #define IPC_LOG_TABLE_ADD_ENTRY(msg_id, logger) \
21 content::RegisterIPCLogger(msg_id, logger)
22 #include "chrome/common/all_messages.h"
23 #endif
25 #if defined(OS_WIN)
26 #include <windows.h>
27 #endif
29 #include <fstream>
31 #include "chrome/common/logging_chrome.h"
33 #include "base/command_line.h"
34 #include "base/compiler_specific.h"
35 #include "base/debug/debugger.h"
36 #include "base/debug/dump_without_crashing.h"
37 #include "base/environment.h"
38 #include "base/file_util.h"
39 #include "base/files/file_path.h"
40 #include "base/logging.h"
41 #include "base/path_service.h"
42 #include "base/strings/string_number_conversions.h"
43 #include "base/strings/string_util.h"
44 #include "base/strings/stringprintf.h"
45 #include "base/strings/utf_string_conversions.h"
46 #include "base/threading/thread_restrictions.h"
47 #include "base/time/time.h"
48 #include "chrome/common/chrome_constants.h"
49 #include "chrome/common/chrome_paths.h"
50 #include "chrome/common/chrome_switches.h"
51 #include "chrome/common/env_vars.h"
52 #include "ipc/ipc_logging.h"
54 #if defined(OS_CHROMEOS)
55 #include "chromeos/chromeos_switches.h"
56 #endif
58 #if defined(OS_WIN)
59 #include <initguid.h>
60 #include "base/logging_win.h"
61 #endif
63 namespace {
65 // When true, this means that error dialogs should not be shown.
66 bool dialogs_are_suppressed_ = false;
68 // This should be true for exactly the period between the end of
69 // InitChromeLogging() and the beginning of CleanupChromeLogging().
70 bool chrome_logging_initialized_ = false;
72 // Set if we called InitChromeLogging() but failed to initialize.
73 bool chrome_logging_failed_ = false;
75 // This should be true for exactly the period between the end of
76 // InitChromeLogging() and the beginning of CleanupChromeLogging().
77 bool chrome_logging_redirected_ = false;
79 #if defined(OS_WIN)
80 // {7FE69228-633E-4f06-80C1-527FEA23E3A7}
81 const GUID kChromeTraceProviderName = {
82 0x7fe69228, 0x633e, 0x4f06,
83 { 0x80, 0xc1, 0x52, 0x7f, 0xea, 0x23, 0xe3, 0xa7 } };
84 #endif
86 // Assertion handler for logging errors that occur when dialogs are
87 // silenced. To record a new error, pass the log string associated
88 // with that error in the str parameter.
89 MSVC_DISABLE_OPTIMIZE();
90 void SilentRuntimeAssertHandler(const std::string& str) {
91 base::debug::BreakDebugger();
93 void SilentRuntimeReportHandler(const std::string& str) {
95 #if defined(OS_WIN)
96 // Handler to silently dump the current process when there is an assert in
97 // chrome.
98 void DumpProcessAssertHandler(const std::string& str) {
99 base::debug::DumpWithoutCrashing();
101 #endif // OS_WIN
102 MSVC_ENABLE_OPTIMIZE();
104 // Suppresses error/assertion dialogs and enables the logging of
105 // those errors into silenced_errors_.
106 void SuppressDialogs() {
107 if (dialogs_are_suppressed_)
108 return;
110 logging::SetLogAssertHandler(SilentRuntimeAssertHandler);
111 logging::SetLogReportHandler(SilentRuntimeReportHandler);
113 #if defined(OS_WIN)
114 UINT new_flags = SEM_FAILCRITICALERRORS |
115 SEM_NOGPFAULTERRORBOX |
116 SEM_NOOPENFILEERRORBOX;
118 // Preserve existing error mode, as discussed at http://t/dmea
119 UINT existing_flags = SetErrorMode(new_flags);
120 SetErrorMode(existing_flags | new_flags);
121 #endif
123 dialogs_are_suppressed_ = true;
126 } // anonymous namespace
128 namespace logging {
130 LoggingDestination DetermineLogMode(const CommandLine& command_line) {
131 // only use OutputDebugString in debug mode
132 #ifdef NDEBUG
133 bool enable_logging = false;
134 const char *kInvertLoggingSwitch = switches::kEnableLogging;
135 const logging::LoggingDestination kDefaultLoggingMode = logging::LOG_TO_FILE;
136 #else
137 bool enable_logging = true;
138 const char *kInvertLoggingSwitch = switches::kDisableLogging;
139 const logging::LoggingDestination kDefaultLoggingMode = logging::LOG_TO_ALL;
140 #endif
142 if (command_line.HasSwitch(kInvertLoggingSwitch))
143 enable_logging = !enable_logging;
145 logging::LoggingDestination log_mode;
146 if (enable_logging) {
147 // Let --enable-logging=stderr force only stderr, particularly useful for
148 // non-debug builds where otherwise you can't get logs to stderr at all.
149 if (command_line.GetSwitchValueASCII(switches::kEnableLogging) == "stderr")
150 log_mode = logging::LOG_TO_SYSTEM_DEBUG_LOG;
151 else
152 log_mode = kDefaultLoggingMode;
153 } else {
154 log_mode = logging::LOG_NONE;
156 return log_mode;
159 #if defined(OS_CHROMEOS)
160 namespace {
161 base::FilePath SetUpSymlinkIfNeeded(const base::FilePath& symlink_path,
162 bool new_log) {
163 DCHECK(!symlink_path.empty());
165 // If not starting a new log, then just log through the existing
166 // symlink, but if the symlink doesn't exist, create it. If
167 // starting a new log, then delete the old symlink and make a new
168 // one to a fresh log file.
169 base::FilePath target_path;
170 bool symlink_exists = base::PathExists(symlink_path);
171 if (new_log || !symlink_exists) {
172 target_path = GenerateTimestampedName(symlink_path, base::Time::Now());
174 // We don't care if the unlink fails; we're going to continue anyway.
175 if (::unlink(symlink_path.value().c_str()) == -1) {
176 if (symlink_exists) // only warn if we might expect it to succeed.
177 DPLOG(WARNING) << "Unable to unlink " << symlink_path.value();
179 if (!base::CreateSymbolicLink(target_path, symlink_path)) {
180 DPLOG(ERROR) << "Unable to create symlink " << symlink_path.value()
181 << " pointing at " << target_path.value();
183 } else {
184 if (!base::ReadSymbolicLink(symlink_path, &target_path))
185 DPLOG(ERROR) << "Unable to read symlink " << symlink_path.value();
187 return target_path;
190 void RemoveSymlinkAndLog(const base::FilePath& link_path,
191 const base::FilePath& target_path) {
192 if (::unlink(link_path.value().c_str()) == -1)
193 DPLOG(WARNING) << "Unable to unlink symlink " << link_path.value();
194 if (::unlink(target_path.value().c_str()) == -1)
195 DPLOG(WARNING) << "Unable to unlink log file " << target_path.value();
198 } // anonymous namespace
200 base::FilePath GetSessionLogFile(const CommandLine& command_line) {
201 base::FilePath log_dir;
202 std::string log_dir_str;
203 scoped_ptr<base::Environment> env(base::Environment::Create());
204 if (env->GetVar(env_vars::kSessionLogDir, &log_dir_str) &&
205 !log_dir_str.empty()) {
206 log_dir = base::FilePath(log_dir_str);
207 } else if (command_line.HasSwitch(chromeos::switches::kLoginProfile)) {
208 PathService::Get(chrome::DIR_USER_DATA, &log_dir);
209 base::FilePath profile_dir;
210 std::string login_profile_value =
211 command_line.GetSwitchValueASCII(chromeos::switches::kLoginProfile);
212 if (login_profile_value == chrome::kLegacyProfileDir ||
213 login_profile_value == chrome::kTestUserProfileDir) {
214 profile_dir = base::FilePath(login_profile_value);
215 } else {
216 // We could not use g_browser_process > profile_helper() here.
217 std::string profile_dir_str = chrome::kProfileDirPrefix;
218 profile_dir_str.append(login_profile_value);
219 profile_dir = base::FilePath(profile_dir_str);
221 log_dir = log_dir.Append(profile_dir);
223 return log_dir.Append(GetLogFileName().BaseName());
226 void RedirectChromeLogging(const CommandLine& command_line) {
227 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kMultiProfiles) &&
228 chrome_logging_redirected_) {
229 // TODO(nkostylev): Support multiple active users. http://crbug.com/230345
230 LOG(ERROR) << "NOT redirecting logging for multi-profiles case.";
231 return;
234 DCHECK(!chrome_logging_redirected_) <<
235 "Attempted to redirect logging when it was already initialized.";
237 // Redirect logs to the session log directory, if set. Otherwise
238 // defaults to the profile dir.
239 base::FilePath log_path = GetSessionLogFile(command_line);
241 // Creating symlink causes us to do blocking IO on UI thread.
242 // Temporarily allow it until we fix http://crbug.com/61143
243 base::ThreadRestrictions::ScopedAllowIO allow_io;
244 // Always force a new symlink when redirecting.
245 base::FilePath target_path = SetUpSymlinkIfNeeded(log_path, true);
247 // ChromeOS always logs through the symlink, so it shouldn't be
248 // deleted if it already exists.
249 logging::LoggingSettings settings;
250 settings.logging_dest = DetermineLogMode(command_line);
251 settings.log_file = log_path.value().c_str();
252 if (!logging::InitLogging(settings)) {
253 DLOG(ERROR) << "Unable to initialize logging to " << log_path.value();
254 RemoveSymlinkAndLog(log_path, target_path);
255 } else {
256 chrome_logging_redirected_ = true;
260 #endif // OS_CHROMEOS
262 void InitChromeLogging(const CommandLine& command_line,
263 OldFileDeletionState delete_old_log_file) {
264 DCHECK(!chrome_logging_initialized_) <<
265 "Attempted to initialize logging when it was already initialized.";
267 LoggingDestination logging_dest = DetermineLogMode(command_line);
268 LogLockingState log_locking_state = LOCK_LOG_FILE;
269 base::FilePath log_path;
270 #if defined(OS_CHROMEOS)
271 base::FilePath target_path;
272 #endif
274 // Don't resolve the log path unless we need to. Otherwise we leave an open
275 // ALPC handle after sandbox lockdown on Windows.
276 if ((logging_dest & LOG_TO_FILE) != 0) {
277 log_path = GetLogFileName();
279 #if defined(OS_CHROMEOS)
280 // For BWSI (Incognito) logins, we want to put the logs in the user
281 // profile directory that is created for the temporary session instead
282 // of in the system log directory, for privacy reasons.
283 if (command_line.HasSwitch(chromeos::switches::kGuestSession))
284 log_path = GetSessionLogFile(command_line);
286 // On ChromeOS we log to the symlink. We force creation of a new
287 // symlink if we've been asked to delete the old log, since that
288 // indicates the start of a new session.
289 target_path = SetUpSymlinkIfNeeded(
290 log_path, delete_old_log_file == logging::DELETE_OLD_LOG_FILE);
292 // Because ChromeOS manages the move to a new session by redirecting
293 // the link, it shouldn't remove the old file in the logging code,
294 // since that will remove the newly created link instead.
295 delete_old_log_file = logging::APPEND_TO_OLD_LOG_FILE;
296 #endif
297 } else {
298 log_locking_state = DONT_LOCK_LOG_FILE;
301 logging::LoggingSettings settings;
302 settings.logging_dest = logging_dest;
303 settings.log_file = log_path.value().c_str();
304 settings.lock_log = log_locking_state;
305 settings.delete_old = delete_old_log_file;
306 bool success = logging::InitLogging(settings);
308 #if defined(OS_CHROMEOS)
309 if (!success) {
310 DPLOG(ERROR) << "Unable to initialize logging to " << log_path.value()
311 << " (which should be a link to " << target_path.value() << ")";
312 RemoveSymlinkAndLog(log_path, target_path);
313 chrome_logging_failed_ = true;
314 return;
316 #else
317 if (!success) {
318 DPLOG(ERROR) << "Unable to initialize logging to " << log_path.value();
319 chrome_logging_failed_ = true;
320 return;
322 #endif
324 // Default to showing error dialogs.
325 if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kNoErrorDialogs))
326 logging::SetShowErrorDialogs(true);
328 // we want process and thread IDs because we have a lot of things running
329 logging::SetLogItems(true, // enable_process_id
330 true, // enable_thread_id
331 true, // enable_timestamp
332 false); // enable_tickcount
334 // We call running in unattended mode "headless", and allow
335 // headless mode to be configured either by the Environment
336 // Variable or by the Command Line Switch. This is for
337 // automated test purposes.
338 scoped_ptr<base::Environment> env(base::Environment::Create());
339 if (env->HasVar(env_vars::kHeadless) ||
340 command_line.HasSwitch(switches::kNoErrorDialogs))
341 SuppressDialogs();
343 // Use a minimum log level if the command line asks for one,
344 // otherwise leave it at the default level (INFO).
345 if (command_line.HasSwitch(switches::kLoggingLevel)) {
346 std::string log_level = command_line.GetSwitchValueASCII(
347 switches::kLoggingLevel);
348 int level = 0;
349 if (base::StringToInt(log_level, &level) &&
350 level >= 0 && level < LOG_NUM_SEVERITIES) {
351 logging::SetMinLogLevel(level);
352 } else {
353 DLOG(WARNING) << "Bad log level: " << log_level;
357 #if defined(OS_WIN)
358 // Enable trace control and transport through event tracing for Windows.
359 logging::LogEventProvider::Initialize(kChromeTraceProviderName);
360 #endif
362 #if DCHECK_IS_ON && defined(NDEBUG) && defined(OS_WIN)
363 if (command_line.HasSwitch(switches::kSilentDumpOnDCHECK))
364 logging::SetLogReportHandler(DumpProcessAssertHandler);
365 #endif
367 chrome_logging_initialized_ = true;
370 // This is a no-op, but we'll keep it around in case
371 // we need to do more cleanup in the future.
372 void CleanupChromeLogging() {
373 if (chrome_logging_failed_)
374 return; // We failed to initiailize logging, no cleanup.
376 DCHECK(chrome_logging_initialized_) <<
377 "Attempted to clean up logging when it wasn't initialized.";
379 CloseLogFile();
381 chrome_logging_initialized_ = false;
382 chrome_logging_redirected_ = false;
385 base::FilePath GetLogFileName() {
386 std::string filename;
387 scoped_ptr<base::Environment> env(base::Environment::Create());
388 if (env->GetVar(env_vars::kLogFileName, &filename) && !filename.empty())
389 return base::FilePath::FromUTF8Unsafe(filename);
391 const base::FilePath log_filename(FILE_PATH_LITERAL("chrome_debug.log"));
392 base::FilePath log_path;
394 if (PathService::Get(chrome::DIR_LOGS, &log_path)) {
395 log_path = log_path.Append(log_filename);
396 return log_path;
397 } else {
398 // error with path service, just use some default file somewhere
399 return log_filename;
403 bool DialogsAreSuppressed() {
404 return dialogs_are_suppressed_;
407 size_t GetFatalAssertions(AssertionList* assertions) {
408 // In this function, we don't assume that assertions is non-null, so
409 // that if you just want an assertion count, you can pass in NULL.
410 if (assertions)
411 assertions->clear();
412 size_t assertion_count = 0;
414 std::ifstream log_file;
415 log_file.open(GetLogFileName().value().c_str());
416 if (!log_file.is_open())
417 return 0;
419 std::string utf8_line;
420 std::wstring wide_line;
421 while (!log_file.eof()) {
422 getline(log_file, utf8_line);
423 if (utf8_line.find(":FATAL:") != std::string::npos) {
424 wide_line = base::UTF8ToWide(utf8_line);
425 if (assertions)
426 assertions->push_back(wide_line);
427 ++assertion_count;
430 log_file.close();
432 return assertion_count;
435 base::FilePath GenerateTimestampedName(const base::FilePath& base_path,
436 base::Time timestamp) {
437 base::Time::Exploded time_deets;
438 timestamp.LocalExplode(&time_deets);
439 std::string suffix = base::StringPrintf("_%02d%02d%02d-%02d%02d%02d",
440 time_deets.year,
441 time_deets.month,
442 time_deets.day_of_month,
443 time_deets.hour,
444 time_deets.minute,
445 time_deets.second);
446 return base_path.InsertBeforeExtensionASCII(suffix);
449 } // namespace logging