Adding instrumentation to locate the source of jankiness
[chromium-blink-merge.git] / chrome / browser / lifetime / application_lifetime.cc
blob5f57bd60f4fe4f0fb0702640899436005c021a72
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 "chrome/browser/lifetime/application_lifetime.h"
7 #include "ash/shell.h"
8 #include "base/bind.h"
9 #include "base/command_line.h"
10 #include "base/debug/trace_event.h"
11 #include "base/logging.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/metrics/field_trial.h"
15 #include "base/prefs/pref_service.h"
16 #include "base/process/kill.h"
17 #include "base/process/process_handle.h"
18 #include "build/build_config.h"
19 #include "chrome/browser/browser_process.h"
20 #include "chrome/browser/browser_process_platform_part.h"
21 #include "chrome/browser/browser_shutdown.h"
22 #include "chrome/browser/chrome_notification_types.h"
23 #include "chrome/browser/download/download_service.h"
24 #include "chrome/browser/lifetime/browser_close_manager.h"
25 #include "chrome/browser/metrics/thread_watcher.h"
26 #include "chrome/browser/profiles/profile.h"
27 #include "chrome/browser/profiles/profile_manager.h"
28 #include "chrome/browser/ui/browser.h"
29 #include "chrome/browser/ui/browser_finder.h"
30 #include "chrome/browser/ui/browser_iterator.h"
31 #include "chrome/browser/ui/browser_tabstrip.h"
32 #include "chrome/browser/ui/browser_window.h"
33 #include "chrome/browser/ui/tabs/tab_strip_model.h"
34 #include "chrome/browser/ui/user_manager.h"
35 #include "chrome/common/chrome_switches.h"
36 #include "chrome/common/pref_names.h"
37 #include "content/public/browser/browser_shutdown.h"
38 #include "content/public/browser/browser_thread.h"
39 #include "content/public/browser/navigation_details.h"
40 #include "content/public/browser/notification_service.h"
42 #if defined(OS_CHROMEOS)
43 #include "base/sys_info.h"
44 #include "chrome/browser/chromeos/boot_times_loader.h"
45 #include "chromeos/dbus/dbus_thread_manager.h"
46 #include "chromeos/dbus/session_manager_client.h"
47 #include "chromeos/dbus/update_engine_client.h"
48 #endif
50 #if defined(OS_WIN)
51 #include "base/win/win_util.h"
52 #endif
54 namespace chrome {
55 namespace {
57 #if !defined(OS_ANDROID)
58 // Returns true if all browsers can be closed without user interaction.
59 // This currently checks if there is pending download, or if it needs to
60 // handle unload handler.
61 bool AreAllBrowsersCloseable() {
62 chrome::BrowserIterator browser_it;
63 if (browser_it.done())
64 return true;
66 // If there are any downloads active, all browsers are not closeable.
67 // However, this does not block for malicious downloads.
68 if (DownloadService::NonMaliciousDownloadCountAllProfiles() > 0)
69 return false;
71 // Check TabsNeedBeforeUnloadFired().
72 for (; !browser_it.done(); browser_it.Next()) {
73 if (browser_it->TabsNeedBeforeUnloadFired())
74 return false;
76 return true;
78 #endif // !defined(OS_ANDROID)
80 int g_keep_alive_count = 0;
82 #if defined(OS_CHROMEOS)
83 // Whether chrome should send stop request to a session manager.
84 bool g_send_stop_request_to_session_manager = false;
85 #endif
87 } // namespace
89 void MarkAsCleanShutdown() {
90 // TODO(beng): Can this use ProfileManager::GetLoadedProfiles() instead?
91 for (chrome::BrowserIterator it; !it.done(); it.Next())
92 it->profile()->SetExitType(Profile::EXIT_NORMAL);
95 void AttemptExitInternal(bool try_to_quit_application) {
96 // On Mac, the platform-specific part handles setting this.
97 #if !defined(OS_MACOSX)
98 if (try_to_quit_application)
99 browser_shutdown::SetTryingToQuit(true);
100 #endif
102 content::NotificationService::current()->Notify(
103 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
104 content::NotificationService::AllSources(),
105 content::NotificationService::NoDetails());
107 g_browser_process->platform_part()->AttemptExit();
110 void CloseAllBrowsersAndQuit() {
111 browser_shutdown::SetTryingToQuit(true);
112 CloseAllBrowsers();
115 void CloseAllBrowsers() {
116 // If there are no browsers and closing the last browser would quit the
117 // application, send the APP_TERMINATING action here. Otherwise, it will be
118 // sent by RemoveBrowser() when the last browser has closed.
119 if (chrome::GetTotalBrowserCount() == 0 &&
120 (browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive())) {
121 // Tell everyone that we are shutting down.
122 browser_shutdown::SetTryingToQuit(true);
124 #if defined(ENABLE_SESSION_SERVICE)
125 // If ShuttingDownWithoutClosingBrowsers() returns true, the session
126 // services may not get a chance to shut down normally, so explicitly shut
127 // them down here to ensure they have a chance to persist their data.
128 ProfileManager::ShutdownSessionServices();
129 #endif
131 chrome::NotifyAndTerminate(true);
132 chrome::OnAppExiting();
133 return;
136 #if defined(OS_CHROMEOS)
137 chromeos::BootTimesLoader::Get()->AddLogoutTimeMarker(
138 "StartedClosingWindows", false);
139 #endif
140 scoped_refptr<BrowserCloseManager> browser_close_manager =
141 new BrowserCloseManager;
142 browser_close_manager->StartClosingBrowsers();
145 void AttemptUserExit() {
146 #if defined(OS_CHROMEOS)
147 StartShutdownTracing();
148 chromeos::BootTimesLoader::Get()->AddLogoutTimeMarker("LogoutStarted", false);
150 PrefService* state = g_browser_process->local_state();
151 if (state) {
152 chromeos::BootTimesLoader::Get()->OnLogoutStarted(state);
154 // Login screen should show up in owner's locale.
155 std::string owner_locale = state->GetString(prefs::kOwnerLocale);
156 if (!owner_locale.empty() &&
157 state->GetString(prefs::kApplicationLocale) != owner_locale &&
158 !state->IsManagedPreference(prefs::kApplicationLocale)) {
159 state->SetString(prefs::kApplicationLocale, owner_locale);
160 TRACE_EVENT0("shutdown", "CommitPendingWrite");
161 state->CommitPendingWrite();
164 g_send_stop_request_to_session_manager = true;
165 // On ChromeOS, always terminate the browser, regardless of the result of
166 // AreAllBrowsersCloseable(). See crbug.com/123107.
167 chrome::NotifyAndTerminate(true);
168 #else
169 // Reset the restart bit that might have been set in cancelled restart
170 // request.
171 UserManager::Hide();
172 PrefService* pref_service = g_browser_process->local_state();
173 pref_service->SetBoolean(prefs::kRestartLastSessionOnShutdown, false);
174 AttemptExitInternal(false);
175 #endif
178 void StartShutdownTracing() {
179 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
180 if (command_line.HasSwitch(switches::kTraceShutdown)) {
181 base::debug::CategoryFilter category_filter(
182 command_line.GetSwitchValueASCII(switches::kTraceShutdown));
183 base::debug::TraceLog::GetInstance()->SetEnabled(
184 category_filter,
185 base::debug::TraceLog::RECORDING_MODE,
186 base::debug::TraceOptions());
188 TRACE_EVENT0("shutdown", "StartShutdownTracing");
191 // The Android implementation is in application_lifetime_android.cc
192 #if !defined(OS_ANDROID)
193 void AttemptRestart() {
194 // TODO(beng): Can this use ProfileManager::GetLoadedProfiles instead?
195 for (chrome::BrowserIterator it; !it.done(); it.Next())
196 content::BrowserContext::SaveSessionState(it->profile());
198 PrefService* pref_service = g_browser_process->local_state();
199 pref_service->SetBoolean(prefs::kWasRestarted, true);
201 #if defined(OS_CHROMEOS)
202 chromeos::BootTimesLoader::Get()->set_restart_requested();
204 DCHECK(!g_send_stop_request_to_session_manager);
205 // Make sure we don't send stop request to the session manager.
206 g_send_stop_request_to_session_manager = false;
207 // Run exit process in clean stack.
208 content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
209 base::Bind(&ExitCleanly));
210 #else
211 // Set the flag to restore state after the restart.
212 pref_service->SetBoolean(prefs::kRestartLastSessionOnShutdown, true);
213 AttemptExit();
214 #endif
216 #endif
218 void AttemptExit() {
219 #if defined(OS_CHROMEOS)
220 // On ChromeOS, user exit and system exits are the same.
221 AttemptUserExit();
222 #else
223 // If we know that all browsers can be closed without blocking,
224 // don't notify users of crashes beyond this point.
225 // Note that MarkAsCleanShutdown() does not set UMA's exit cleanly bit
226 // so crashes during shutdown are still reported in UMA.
227 #if !defined(OS_ANDROID)
228 // Android doesn't use Browser.
229 if (AreAllBrowsersCloseable())
230 MarkAsCleanShutdown();
231 #endif
232 AttemptExitInternal(true);
233 #endif
236 #if defined(OS_CHROMEOS)
237 // A function called when SIGTERM is received.
238 void ExitCleanly() {
239 // We always mark exit cleanly because SessionManager may kill
240 // chrome in 3 seconds after SIGTERM.
241 g_browser_process->EndSession();
243 // Don't block when SIGTERM is received. AreaAllBrowsersCloseable()
244 // can be false in following cases. a) power-off b) signout from
245 // screen locker.
246 if (!AreAllBrowsersCloseable())
247 browser_shutdown::OnShutdownStarting(browser_shutdown::END_SESSION);
248 else
249 browser_shutdown::OnShutdownStarting(browser_shutdown::BROWSER_EXIT);
250 AttemptExitInternal(true);
252 #endif
254 namespace {
256 bool ExperimentUseBrokenSynchronization() {
257 const std::string group_name =
258 base::FieldTrialList::FindFullName("WindowsLogoffRace");
259 return group_name == "BrokenSynchronization";
262 } // namespace
264 void SessionEnding() {
265 // This is a time-limited shutdown where we need to write as much to
266 // disk as we can as soon as we can, and where we must kill the
267 // process within a hang timeout to avoid user prompts.
269 // Start watching for hang during shutdown, and crash it if takes too long.
270 // We disarm when |shutdown_watcher| object is destroyed, which is when we
271 // exit this function.
272 ShutdownWatcherHelper shutdown_watcher;
273 shutdown_watcher.Arm(base::TimeDelta::FromSeconds(90));
275 // EndSession is invoked once per frame. Only do something the first time.
276 static bool already_ended = false;
277 // We may get called in the middle of shutdown, e.g. http://crbug.com/70852
278 // In this case, do nothing.
279 if (already_ended || !content::NotificationService::current())
280 return;
281 already_ended = true;
283 browser_shutdown::OnShutdownStarting(browser_shutdown::END_SESSION);
285 content::NotificationService::current()->Notify(
286 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
287 content::NotificationService::AllSources(),
288 content::NotificationService::NoDetails());
290 // Write important data first.
291 g_browser_process->EndSession();
293 #if defined(OS_WIN)
294 base::win::SetShouldCrashOnProcessDetach(false);
295 #endif
297 if (ExperimentUseBrokenSynchronization()) {
298 CloseAllBrowsers();
300 // Send out notification. This is used during testing so that the test
301 // harness can properly shutdown before we exit.
302 content::NotificationService::current()->Notify(
303 chrome::NOTIFICATION_SESSION_END,
304 content::NotificationService::AllSources(),
305 content::NotificationService::NoDetails());
307 // This will end by terminating the process.
308 content::ImmediateShutdownAndExitProcess();
309 } else {
310 // On Windows 7 and later, the system will consider the process ripe for
311 // termination as soon as it hides or destroys its windows. Since any
312 // execution past that point will be non-deterministically cut short, we
313 // might as well put ourselves out of that misery deterministically.
314 base::KillProcess(base::GetCurrentProcessHandle(), 0, false);
318 void IncrementKeepAliveCount() {
319 // Increment the browser process refcount as long as we're keeping the
320 // application alive.
321 if (!WillKeepAlive())
322 g_browser_process->AddRefModule();
323 ++g_keep_alive_count;
326 void DecrementKeepAliveCount() {
327 DCHECK_GT(g_keep_alive_count, 0);
328 --g_keep_alive_count;
330 DCHECK(g_browser_process);
331 // Although we should have a browser process, if there is none,
332 // there is nothing to do.
333 if (!g_browser_process) return;
335 // Allow the app to shutdown again.
336 if (!WillKeepAlive()) {
337 g_browser_process->ReleaseModule();
338 // If there are no browsers open and we aren't already shutting down,
339 // initiate a shutdown. Also skips shutdown if this is a unit test
340 // (MessageLoop::current() == null).
341 if (chrome::GetTotalBrowserCount() == 0 &&
342 !browser_shutdown::IsTryingToQuit() &&
343 base::MessageLoop::current()) {
344 CloseAllBrowsers();
349 bool WillKeepAlive() {
350 return g_keep_alive_count > 0;
353 void NotifyAppTerminating() {
354 static bool notified = false;
355 if (notified)
356 return;
357 notified = true;
358 content::NotificationService::current()->Notify(
359 chrome::NOTIFICATION_APP_TERMINATING,
360 content::NotificationService::AllSources(),
361 content::NotificationService::NoDetails());
364 void NotifyAndTerminate(bool fast_path) {
365 #if defined(OS_CHROMEOS)
366 static bool notified = false;
367 // Return if a shutdown request has already been sent.
368 if (notified)
369 return;
370 notified = true;
371 #endif
373 if (fast_path)
374 NotifyAppTerminating();
376 #if defined(OS_CHROMEOS)
377 if (base::SysInfo::IsRunningOnChromeOS()) {
378 // If we're on a ChromeOS device, reboot if an update has been applied,
379 // or else signal the session manager to log out.
380 chromeos::UpdateEngineClient* update_engine_client
381 = chromeos::DBusThreadManager::Get()->GetUpdateEngineClient();
382 if (update_engine_client->GetLastStatus().status ==
383 chromeos::UpdateEngineClient::UPDATE_STATUS_UPDATED_NEED_REBOOT) {
384 update_engine_client->RebootAfterUpdate();
385 } else if (g_send_stop_request_to_session_manager) {
386 // Don't ask SessionManager to stop session if the shutdown request comes
387 // from session manager.
388 chromeos::DBusThreadManager::Get()->GetSessionManagerClient()
389 ->StopSession();
391 } else {
392 if (g_send_stop_request_to_session_manager) {
393 // If running the Chrome OS build, but we're not on the device, act
394 // as if we received signal from SessionManager.
395 content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
396 base::Bind(&ExitCleanly));
399 #endif
402 void OnAppExiting() {
403 static bool notified = false;
404 if (notified)
405 return;
406 notified = true;
407 HandleAppExitingForPlatform();
410 bool ShouldStartShutdown(Browser* browser) {
411 if (BrowserList::GetInstance(browser->host_desktop_type())->size() > 1)
412 return false;
413 #if defined(OS_WIN)
414 // On Windows 8 the desktop and ASH environments could be active
415 // at the same time.
416 // We should not start the shutdown process in the following cases:-
417 // 1. If the desktop type of the browser going away is ASH and there
418 // are browser windows open in the desktop.
419 // 2. If the desktop type of the browser going away is desktop and the ASH
420 // environment is still active.
421 if (browser->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_NATIVE)
422 return !ash::Shell::HasInstance();
423 else if (browser->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH)
424 return BrowserList::GetInstance(chrome::HOST_DESKTOP_TYPE_NATIVE)->empty();
425 #endif
426 return true;
429 } // namespace chrome