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 a session manager requested to shutdown.
83 bool g_session_manager_requested_shutdown
= true;
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_session_manager_requested_shutdown
= false;
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 // For CrOS instead of browser restart (which is not supported) perform a full
209 // sign out. Session will be only restored if user has that setting set.
210 // Same session restore behavior happens in case of full restart after update.
213 // Set the flag to restore state after the restart.
214 pref_service
->SetBoolean(prefs::kRestartLastSessionOnShutdown
, true);
221 // If we know that all browsers can be closed without blocking,
222 // don't notify users of crashes beyond this point.
223 // Note that MarkAsCleanShutdown() does not set UMA's exit cleanly bit
224 // so crashes during shutdown are still reported in UMA.
225 #if !defined(OS_ANDROID)
226 // Android doesn't use Browser.
227 if (AreAllBrowsersCloseable())
228 MarkAsCleanShutdown();
230 AttemptExitInternal(true);
233 #if defined(OS_CHROMEOS)
234 // A function called when SIGTERM is received.
236 // We always mark exit cleanly because SessionManager may kill
237 // chrome in 3 seconds after SIGTERM.
238 g_browser_process
->EndSession();
240 // Don't block when SIGTERM is received. AreaAllBrowsersCloseable()
241 // can be false in following cases. a) power-off b) signout from
243 if (!AreAllBrowsersCloseable())
244 browser_shutdown::OnShutdownStarting(browser_shutdown::END_SESSION
);
246 browser_shutdown::OnShutdownStarting(browser_shutdown::BROWSER_EXIT
);
247 AttemptExitInternal(true);
251 void SessionEnding() {
252 // This is a time-limited shutdown where we need to write as much to
253 // disk as we can as soon as we can, and where we must kill the
254 // process within a hang timeout to avoid user prompts.
256 // Start watching for hang during shutdown, and crash it if takes too long.
257 // We disarm when |shutdown_watcher| object is destroyed, which is when we
258 // exit this function.
259 ShutdownWatcherHelper shutdown_watcher
;
260 shutdown_watcher
.Arm(base::TimeDelta::FromSeconds(90));
262 // EndSession is invoked once per frame. Only do something the first time.
263 static bool already_ended
= false;
264 // We may get called in the middle of shutdown, e.g. http://crbug.com/70852
265 // In this case, do nothing.
266 if (already_ended
|| !content::NotificationService::current())
268 already_ended
= true;
270 browser_shutdown::OnShutdownStarting(browser_shutdown::END_SESSION
);
272 content::NotificationService::current()->Notify(
273 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST
,
274 content::NotificationService::AllSources(),
275 content::NotificationService::NoDetails());
277 // Write important data first.
278 g_browser_process
->EndSession();
282 // Send out notification. This is used during testing so that the test harness
283 // can properly shutdown before we exit.
284 content::NotificationService::current()->Notify(
285 chrome::NOTIFICATION_SESSION_END
,
286 content::NotificationService::AllSources(),
287 content::NotificationService::NoDetails());
290 base::win::SetShouldCrashOnProcessDetach(false);
292 // This will end by terminating the process.
293 content::ImmediateShutdownAndExitProcess();
296 void StartKeepAlive() {
297 // Increment the browser process refcount as long as we're keeping the
298 // application alive.
299 if (!WillKeepAlive())
300 g_browser_process
->AddRefModule();
301 ++g_keep_alive_count
;
304 void EndKeepAlive() {
305 DCHECK_GT(g_keep_alive_count
, 0);
306 --g_keep_alive_count
;
308 DCHECK(g_browser_process
);
309 // Although we should have a browser process, if there is none,
310 // there is nothing to do.
311 if (!g_browser_process
) return;
313 // Allow the app to shutdown again.
314 if (!WillKeepAlive()) {
315 g_browser_process
->ReleaseModule();
316 // If there are no browsers open and we aren't already shutting down,
317 // initiate a shutdown. Also skips shutdown if this is a unit test
318 // (MessageLoop::current() == null).
319 if (chrome::GetTotalBrowserCount() == 0 &&
320 !browser_shutdown::IsTryingToQuit() &&
321 base::MessageLoop::current()) {
327 bool WillKeepAlive() {
328 return g_keep_alive_count
> 0;
331 void NotifyAppTerminating() {
332 static bool notified
= false;
336 content::NotificationService::current()->Notify(
337 chrome::NOTIFICATION_APP_TERMINATING
,
338 content::NotificationService::AllSources(),
339 content::NotificationService::NoDetails());
342 void NotifyAndTerminate(bool fast_path
) {
343 #if defined(OS_CHROMEOS)
344 static bool notified
= false;
345 // Return if a shutdown request has already been sent.
352 NotifyAppTerminating();
354 #if defined(OS_CHROMEOS)
355 if (base::SysInfo::IsRunningOnChromeOS()) {
356 // If we're on a ChromeOS device, reboot if an update has been applied,
357 // or else signal the session manager to log out.
358 chromeos::UpdateEngineClient
* update_engine_client
359 = chromeos::DBusThreadManager::Get()->GetUpdateEngineClient();
360 if (update_engine_client
->GetLastStatus().status
==
361 chromeos::UpdateEngineClient::UPDATE_STATUS_UPDATED_NEED_REBOOT
) {
362 update_engine_client
->RebootAfterUpdate();
363 } else if (!g_session_manager_requested_shutdown
) {
364 // Don't ask SessionManager to stop session if the shutdown request comes
365 // from session manager.
366 chromeos::DBusThreadManager::Get()->GetSessionManagerClient()
370 // If running the Chrome OS build, but we're not on the device, act
371 // as if we received signal from SessionManager.
372 content::BrowserThread::PostTask(content::BrowserThread::UI
, FROM_HERE
,
373 base::Bind(&ExitCleanly
));
378 void OnAppExiting() {
379 static bool notified
= false;
383 HandleAppExitingForPlatform();
386 bool ShouldStartShutdown(Browser
* browser
) {
387 if (BrowserList::GetInstance(browser
->host_desktop_type())->size() > 1)
389 #if defined(OS_WIN) && defined(USE_AURA)
390 // On Windows 8 the desktop and ASH environments could be active
392 // We should not start the shutdown process in the following cases:-
393 // 1. If the desktop type of the browser going away is ASH and there
394 // are browser windows open in the desktop.
395 // 2. If the desktop type of the browser going away is desktop and the ASH
396 // environment is still active.
397 if (browser
->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_NATIVE
)
398 return !ash::Shell::HasInstance();
399 else if (browser
->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH
)
400 return BrowserList::GetInstance(chrome::HOST_DESKTOP_TYPE_NATIVE
)->empty();
405 } // namespace chrome