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"
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/prefs/pref_service.h"
15 #include "build/build_config.h"
16 #include "chrome/browser/browser_process.h"
17 #include "chrome/browser/browser_process_platform_part.h"
18 #include "chrome/browser/browser_shutdown.h"
19 #include "chrome/browser/chrome_notification_types.h"
20 #include "chrome/browser/download/download_service.h"
21 #include "chrome/browser/lifetime/browser_close_manager.h"
22 #include "chrome/browser/metrics/thread_watcher.h"
23 #include "chrome/browser/profiles/profile.h"
24 #include "chrome/browser/profiles/profile_manager.h"
25 #include "chrome/browser/ui/browser.h"
26 #include "chrome/browser/ui/browser_finder.h"
27 #include "chrome/browser/ui/browser_iterator.h"
28 #include "chrome/browser/ui/browser_tabstrip.h"
29 #include "chrome/browser/ui/browser_window.h"
30 #include "chrome/browser/ui/tabs/tab_strip_model.h"
31 #include "chrome/common/chrome_switches.h"
32 #include "chrome/common/pref_names.h"
33 #include "content/public/browser/browser_shutdown.h"
34 #include "content/public/browser/browser_thread.h"
35 #include "content/public/browser/navigation_details.h"
36 #include "content/public/browser/notification_service.h"
38 #if defined(OS_CHROMEOS)
39 #include "ash/multi_profile_uma.h"
40 #include "ash/session_state_delegate.h"
41 #include "base/sys_info.h"
42 #include "chrome/browser/chromeos/boot_times_loader.h"
43 #include "chrome/browser/chromeos/login/user_manager.h"
44 #include "chromeos/dbus/dbus_thread_manager.h"
45 #include "chromeos/dbus/session_manager_client.h"
46 #include "chromeos/dbus/update_engine_client.h"
50 #include "base/win/win_util.h"
56 #if !defined(OS_ANDROID)
57 // Returns true if all browsers can be closed without user interaction.
58 // This currently checks if there is pending download, or if it needs to
59 // handle unload handler.
60 bool AreAllBrowsersCloseable() {
61 chrome::BrowserIterator browser_it;
62 if (browser_it.done())
65 // If there are any downloads active, all browsers are not closeable.
66 // However, this does not block for malicious downloads.
67 if (DownloadService::NonMaliciousDownloadCountAllProfiles() > 0)
70 // Check TabsNeedBeforeUnloadFired().
71 for (; !browser_it.done(); browser_it.Next()) {
72 if (browser_it->TabsNeedBeforeUnloadFired())
77 #endif // !defined(OS_ANDROID)
79 int g_keep_alive_count = 0;
81 #if defined(OS_CHROMEOS)
82 // Whether chrome should send stop request to a session manager.
83 bool g_send_stop_request_to_session_manager = false;
88 void MarkAsCleanShutdown() {
89 // TODO(beng): Can this use ProfileManager::GetLoadedProfiles() instead?
90 for (chrome::BrowserIterator it; !it.done(); it.Next())
91 it->profile()->SetExitType(Profile::EXIT_NORMAL);
94 void AttemptExitInternal(bool try_to_quit_application) {
95 // On Mac, the platform-specific part handles setting this.
96 #if !defined(OS_MACOSX)
97 if (try_to_quit_application)
98 browser_shutdown::SetTryingToQuit(true);
101 content::NotificationService::current()->Notify(
102 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
103 content::NotificationService::AllSources(),
104 content::NotificationService::NoDetails());
106 g_browser_process->platform_part()->AttemptExit();
109 void CloseAllBrowsersAndQuit() {
110 browser_shutdown::SetTryingToQuit(true);
114 void CloseAllBrowsers() {
115 // If there are no browsers and closing the last browser would quit the
116 // application, send the APP_TERMINATING action here. Otherwise, it will be
117 // sent by RemoveBrowser() when the last browser has closed.
118 if (browser_shutdown::ShuttingDownWithoutClosingBrowsers() ||
119 (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();
131 chrome::NotifyAndTerminate(true);
132 chrome::OnAppExiting();
136 #if defined(OS_CHROMEOS)
137 chromeos::BootTimesLoader::Get()->AddLogoutTimeMarker(
138 "StartedClosingWindows", false);
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);
149 // Write /tmp/uptime-logout-started as well.
150 const char kLogoutStarted[] = "logout-started";
151 chromeos::BootTimesLoader::Get()->RecordCurrentStats(kLogoutStarted);
153 // Since we are shutting down now we should record how many users have joined
154 // the session since session start.
155 ash::MultiProfileUMA::RecordUserCount(
156 ash::Shell::GetInstance()->session_state_delegate()->
157 NumberOfLoggedInUsers());
159 // Login screen should show up in owner's locale.
160 PrefService* state = g_browser_process->local_state();
162 std::string owner_locale = state->GetString(prefs::kOwnerLocale);
163 if (!owner_locale.empty() &&
164 state->GetString(prefs::kApplicationLocale) != owner_locale &&
165 !state->IsManagedPreference(prefs::kApplicationLocale)) {
166 state->SetString(prefs::kApplicationLocale, owner_locale);
167 TRACE_EVENT0("shutdown", "CommitPendingWrite");
168 state->CommitPendingWrite();
171 g_send_stop_request_to_session_manager = true;
172 // On ChromeOS, always terminate the browser, regardless of the result of
173 // AreAllBrowsersCloseable(). See crbug.com/123107.
174 chrome::NotifyAndTerminate(true);
176 // Reset the restart bit that might have been set in cancelled restart
178 PrefService* pref_service = g_browser_process->local_state();
179 pref_service->SetBoolean(prefs::kRestartLastSessionOnShutdown, false);
180 AttemptExitInternal(false);
184 void StartShutdownTracing() {
185 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
186 if (command_line.HasSwitch(switches::kTraceShutdown)) {
187 base::debug::CategoryFilter category_filter(
188 command_line.GetSwitchValueASCII(switches::kTraceShutdown));
189 base::debug::TraceLog::GetInstance()->SetEnabled(
191 base::debug::TraceLog::RECORDING_MODE,
192 base::debug::TraceLog::RECORD_UNTIL_FULL);
194 TRACE_EVENT0("shutdown", "StartShutdownTracing");
197 // The Android implementation is in application_lifetime_android.cc
198 #if !defined(OS_ANDROID)
199 void AttemptRestart() {
200 // TODO(beng): Can this use ProfileManager::GetLoadedProfiles instead?
201 for (chrome::BrowserIterator it; !it.done(); it.Next())
202 content::BrowserContext::SaveSessionState(it->profile());
204 PrefService* pref_service = g_browser_process->local_state();
205 pref_service->SetBoolean(prefs::kWasRestarted, true);
207 #if defined(OS_CHROMEOS)
208 DCHECK(!g_send_stop_request_to_session_manager);
209 // Make sure we don't send stop request to the session manager.
210 g_send_stop_request_to_session_manager = false;
211 // Run exit process in clean stack.
212 content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
213 base::Bind(&ExitCleanly));
215 // Set the flag to restore state after the restart.
216 pref_service->SetBoolean(prefs::kRestartLastSessionOnShutdown, true);
223 #if defined(OS_CHROMEOS)
224 // On ChromeOS, user exit and system exits are the same.
227 // If we know that all browsers can be closed without blocking,
228 // don't notify users of crashes beyond this point.
229 // Note that MarkAsCleanShutdown() does not set UMA's exit cleanly bit
230 // so crashes during shutdown are still reported in UMA.
231 #if !defined(OS_ANDROID)
232 // Android doesn't use Browser.
233 if (AreAllBrowsersCloseable())
234 MarkAsCleanShutdown();
236 AttemptExitInternal(true);
240 #if defined(OS_CHROMEOS)
241 // A function called when SIGTERM is received.
243 // We always mark exit cleanly because SessionManager may kill
244 // chrome in 3 seconds after SIGTERM.
245 g_browser_process->EndSession();
247 // Don't block when SIGTERM is received. AreaAllBrowsersCloseable()
248 // can be false in following cases. a) power-off b) signout from
250 if (!AreAllBrowsersCloseable())
251 browser_shutdown::OnShutdownStarting(browser_shutdown::END_SESSION);
253 browser_shutdown::OnShutdownStarting(browser_shutdown::BROWSER_EXIT);
254 AttemptExitInternal(true);
258 void SessionEnding() {
259 // This is a time-limited shutdown where we need to write as much to
260 // disk as we can as soon as we can, and where we must kill the
261 // process within a hang timeout to avoid user prompts.
263 // Start watching for hang during shutdown, and crash it if takes too long.
264 // We disarm when |shutdown_watcher| object is destroyed, which is when we
265 // exit this function.
266 ShutdownWatcherHelper shutdown_watcher;
267 shutdown_watcher.Arm(base::TimeDelta::FromSeconds(90));
269 // EndSession is invoked once per frame. Only do something the first time.
270 static bool already_ended = false;
271 // We may get called in the middle of shutdown, e.g. http://crbug.com/70852
272 // In this case, do nothing.
273 if (already_ended || !content::NotificationService::current())
275 already_ended = true;
277 browser_shutdown::OnShutdownStarting(browser_shutdown::END_SESSION);
279 content::NotificationService::current()->Notify(
280 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
281 content::NotificationService::AllSources(),
282 content::NotificationService::NoDetails());
284 // Write important data first.
285 g_browser_process->EndSession();
289 // Send out notification. This is used during testing so that the test harness
290 // can properly shutdown before we exit.
291 content::NotificationService::current()->Notify(
292 chrome::NOTIFICATION_SESSION_END,
293 content::NotificationService::AllSources(),
294 content::NotificationService::NoDetails());
297 base::win::SetShouldCrashOnProcessDetach(false);
299 // This will end by terminating the process.
300 content::ImmediateShutdownAndExitProcess();
303 void StartKeepAlive() {
304 // Increment the browser process refcount as long as we're keeping the
305 // application alive.
306 if (!WillKeepAlive())
307 g_browser_process->AddRefModule();
308 ++g_keep_alive_count;
311 void EndKeepAlive() {
312 DCHECK_GT(g_keep_alive_count, 0);
313 --g_keep_alive_count;
315 DCHECK(g_browser_process);
316 // Although we should have a browser process, if there is none,
317 // there is nothing to do.
318 if (!g_browser_process) return;
320 // Allow the app to shutdown again.
321 if (!WillKeepAlive()) {
322 g_browser_process->ReleaseModule();
323 // If there are no browsers open and we aren't already shutting down,
324 // initiate a shutdown. Also skips shutdown if this is a unit test
325 // (MessageLoop::current() == null).
326 if (chrome::GetTotalBrowserCount() == 0 &&
327 !browser_shutdown::IsTryingToQuit() &&
328 base::MessageLoop::current()) {
334 bool WillKeepAlive() {
335 return g_keep_alive_count > 0;
338 void NotifyAppTerminating() {
339 static bool notified = false;
343 content::NotificationService::current()->Notify(
344 chrome::NOTIFICATION_APP_TERMINATING,
345 content::NotificationService::AllSources(),
346 content::NotificationService::NoDetails());
349 void NotifyAndTerminate(bool fast_path) {
350 #if defined(OS_CHROMEOS)
351 static bool notified = false;
352 // Return if a shutdown request has already been sent.
359 NotifyAppTerminating();
361 #if defined(OS_CHROMEOS)
362 if (base::SysInfo::IsRunningOnChromeOS()) {
363 // If we're on a ChromeOS device, reboot if an update has been applied,
364 // or else signal the session manager to log out.
365 chromeos::UpdateEngineClient* update_engine_client
366 = chromeos::DBusThreadManager::Get()->GetUpdateEngineClient();
367 if (update_engine_client->GetLastStatus().status ==
368 chromeos::UpdateEngineClient::UPDATE_STATUS_UPDATED_NEED_REBOOT) {
369 update_engine_client->RebootAfterUpdate();
370 } else if (g_send_stop_request_to_session_manager) {
371 // Don't ask SessionManager to stop session if the shutdown request comes
372 // from session manager.
373 chromeos::DBusThreadManager::Get()->GetSessionManagerClient()
377 if (g_send_stop_request_to_session_manager) {
378 // If running the Chrome OS build, but we're not on the device, act
379 // as if we received signal from SessionManager.
380 content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
381 base::Bind(&ExitCleanly));
387 void OnAppExiting() {
388 static bool notified = false;
392 HandleAppExitingForPlatform();
395 bool ShouldStartShutdown(Browser* browser) {
396 if (BrowserList::GetInstance(browser->host_desktop_type())->size() > 1)
399 // On Windows 8 the desktop and ASH environments could be active
401 // We should not start the shutdown process in the following cases:-
402 // 1. If the desktop type of the browser going away is ASH and there
403 // are browser windows open in the desktop.
404 // 2. If the desktop type of the browser going away is desktop and the ASH
405 // environment is still active.
406 if (browser->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_NATIVE)
407 return !ash::Shell::HasInstance();
408 else if (browser->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH)
409 return BrowserList::GetInstance(chrome::HOST_DESKTOP_TYPE_NATIVE)->empty();
414 } // namespace chrome