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 "base/sys_info.h"
40 #include "chrome/browser/chromeos/boot_times_loader.h"
41 #include "chrome/browser/chromeos/login/user_manager.h"
42 #include "chromeos/dbus/dbus_thread_manager.h"
43 #include "chromeos/dbus/session_manager_client.h"
44 #include "chromeos/dbus/update_engine_client.h"
48 #include "base/win/win_util.h"
54 // Returns true if all browsers can be closed without user interaction.
55 // This currently checks if there is pending download, or if it needs to
56 // handle unload handler.
57 bool AreAllBrowsersCloseable() {
58 chrome::BrowserIterator browser_it;
59 if (browser_it.done())
62 // If there are any downloads active, all browsers are not closeable.
63 // However, this does not block for malicious downloads.
64 if (DownloadService::NonMaliciousDownloadCountAllProfiles() > 0)
67 // Check TabsNeedBeforeUnloadFired().
68 for (; !browser_it.done(); browser_it.Next()) {
69 if (browser_it->TabsNeedBeforeUnloadFired())
75 int g_keep_alive_count = 0;
77 #if defined(OS_CHROMEOS)
78 // Whether a session manager requested to shutdown.
79 bool g_session_manager_requested_shutdown = true;
84 void MarkAsCleanShutdown() {
85 // TODO(beng): Can this use ProfileManager::GetLoadedProfiles() instead?
86 for (chrome::BrowserIterator it; !it.done(); it.Next())
87 it->profile()->SetExitType(Profile::EXIT_NORMAL);
90 void AttemptExitInternal(bool try_to_quit_application) {
91 // On Mac, the platform-specific part handles setting this.
92 #if !defined(OS_MACOSX)
93 if (try_to_quit_application)
94 browser_shutdown::SetTryingToQuit(true);
97 content::NotificationService::current()->Notify(
98 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
99 content::NotificationService::AllSources(),
100 content::NotificationService::NoDetails());
102 g_browser_process->platform_part()->AttemptExit();
105 void CloseAllBrowsersAndQuit() {
106 browser_shutdown::SetTryingToQuit(true);
110 void CloseAllBrowsers() {
111 // If there are no browsers and closing the last browser would quit the
112 // application, send the APP_TERMINATING action here. Otherwise, it will be
113 // sent by RemoveBrowser() when the last browser has closed.
114 if (browser_shutdown::ShuttingDownWithoutClosingBrowsers() ||
115 (chrome::GetTotalBrowserCount() == 0 &&
116 (browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive() ||
117 CommandLine::ForCurrentProcess()->HasSwitch(
118 switches::kDisableBatchedShutdown)))) {
119 // Tell everyone that we are shutting down.
120 browser_shutdown::SetTryingToQuit(true);
122 #if defined(ENABLE_SESSION_SERVICE)
123 // If ShuttingDownWithoutClosingBrowsers() returns true, the session
124 // services may not get a chance to shut down normally, so explicitly shut
125 // them down here to ensure they have a chance to persist their data.
126 ProfileManager::ShutdownSessionServices();
129 chrome::NotifyAndTerminate(true);
130 chrome::OnAppExiting();
134 #if defined(OS_CHROMEOS)
135 chromeos::BootTimesLoader::Get()->AddLogoutTimeMarker(
136 "StartedClosingWindows", false);
138 scoped_refptr<BrowserCloseManager> browser_close_manager =
139 new BrowserCloseManager;
140 browser_close_manager->StartClosingBrowsers();
143 void AttemptUserExit() {
144 #if defined(OS_CHROMEOS)
145 StartShutdownTracing();
146 chromeos::BootTimesLoader::Get()->AddLogoutTimeMarker("LogoutStarted", false);
147 // Write /tmp/uptime-logout-started as well.
148 const char kLogoutStarted[] = "logout-started";
149 chromeos::BootTimesLoader::Get()->RecordCurrentStats(kLogoutStarted);
151 // Login screen should show up in owner's locale.
152 PrefService* state = g_browser_process->local_state();
154 std::string owner_locale = state->GetString(prefs::kOwnerLocale);
155 if (!owner_locale.empty() &&
156 state->GetString(prefs::kApplicationLocale) != owner_locale &&
157 !state->IsManagedPreference(prefs::kApplicationLocale)) {
158 state->SetString(prefs::kApplicationLocale, owner_locale);
159 TRACE_EVENT0("shutdown", "CommitPendingWrite");
160 state->CommitPendingWrite();
163 g_session_manager_requested_shutdown = false;
164 // On ChromeOS, always terminate the browser, regardless of the result of
165 // AreAllBrowsersCloseable(). See crbug.com/123107.
166 chrome::NotifyAndTerminate(true);
168 // Reset the restart bit that might have been set in cancelled restart
170 PrefService* pref_service = g_browser_process->local_state();
171 pref_service->SetBoolean(prefs::kRestartLastSessionOnShutdown, false);
172 AttemptExitInternal(false);
176 void StartShutdownTracing() {
177 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
178 if (command_line.HasSwitch(switches::kTraceShutdown)) {
179 base::debug::CategoryFilter category_filter(
180 command_line.GetSwitchValueASCII(switches::kTraceShutdown));
181 base::debug::TraceLog::GetInstance()->SetEnabled(
183 base::debug::TraceLog::RECORD_UNTIL_FULL);
185 TRACE_EVENT0("shutdown", "StartShutdownTracing");
188 // The Android implementation is in application_lifetime_android.cc
189 #if !defined(OS_ANDROID)
190 void AttemptRestart() {
191 // TODO(beng): Can this use ProfileManager::GetLoadedProfiles instead?
192 for (chrome::BrowserIterator it; !it.done(); it.Next())
193 content::BrowserContext::SaveSessionState(it->profile());
195 PrefService* pref_service = g_browser_process->local_state();
196 pref_service->SetBoolean(prefs::kWasRestarted, true);
198 #if defined(OS_CHROMEOS)
199 // For CrOS instead of browser restart (which is not supported) perform a full
200 // sign out. Session will be only restored if user has that setting set.
201 // Same session restore behavior happens in case of full restart after update.
204 // Set the flag to restore state after the restart.
205 pref_service->SetBoolean(prefs::kRestartLastSessionOnShutdown, true);
212 // If we know that all browsers can be closed without blocking,
213 // don't notify users of crashes beyond this point.
214 // Note that MarkAsCleanShutdown() does not set UMA's exit cleanly bit
215 // so crashes during shutdown are still reported in UMA.
216 #if !defined(OS_ANDROID)
217 // Android doesn't use Browser.
218 if (AreAllBrowsersCloseable())
219 MarkAsCleanShutdown();
221 AttemptExitInternal(true);
224 #if defined(OS_CHROMEOS)
225 // A function called when SIGTERM is received.
227 // We always mark exit cleanly because SessionManager may kill
228 // chrome in 3 seconds after SIGTERM.
229 g_browser_process->EndSession();
231 // Don't block when SIGTERM is received. AreaAllBrowsersCloseable()
232 // can be false in following cases. a) power-off b) signout from
234 if (!AreAllBrowsersCloseable())
235 browser_shutdown::OnShutdownStarting(browser_shutdown::END_SESSION);
236 AttemptExitInternal(true);
240 void SessionEnding() {
241 // This is a time-limited shutdown where we need to write as much to
242 // disk as we can as soon as we can, and where we must kill the
243 // process within a hang timeout to avoid user prompts.
245 // Start watching for hang during shutdown, and crash it if takes too long.
246 // We disarm when |shutdown_watcher| object is destroyed, which is when we
247 // exit this function.
248 ShutdownWatcherHelper shutdown_watcher;
249 shutdown_watcher.Arm(base::TimeDelta::FromSeconds(90));
251 // EndSession is invoked once per frame. Only do something the first time.
252 static bool already_ended = false;
253 // We may get called in the middle of shutdown, e.g. http://crbug.com/70852
254 // In this case, do nothing.
255 if (already_ended || !content::NotificationService::current())
257 already_ended = true;
259 browser_shutdown::OnShutdownStarting(browser_shutdown::END_SESSION);
261 content::NotificationService::current()->Notify(
262 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
263 content::NotificationService::AllSources(),
264 content::NotificationService::NoDetails());
266 // Write important data first.
267 g_browser_process->EndSession();
271 // Send out notification. This is used during testing so that the test harness
272 // can properly shutdown before we exit.
273 content::NotificationService::current()->Notify(
274 chrome::NOTIFICATION_SESSION_END,
275 content::NotificationService::AllSources(),
276 content::NotificationService::NoDetails());
279 base::win::SetShouldCrashOnProcessDetach(false);
281 // This will end by terminating the process.
282 content::ImmediateShutdownAndExitProcess();
285 void StartKeepAlive() {
286 // Increment the browser process refcount as long as we're keeping the
287 // application alive.
288 if (!WillKeepAlive())
289 g_browser_process->AddRefModule();
290 ++g_keep_alive_count;
293 void EndKeepAlive() {
294 DCHECK_GT(g_keep_alive_count, 0);
295 --g_keep_alive_count;
297 DCHECK(g_browser_process);
298 // Although we should have a browser process, if there is none,
299 // there is nothing to do.
300 if (!g_browser_process) return;
302 // Allow the app to shutdown again.
303 if (!WillKeepAlive()) {
304 g_browser_process->ReleaseModule();
305 // If there are no browsers open and we aren't already shutting down,
306 // initiate a shutdown. Also skips shutdown if this is a unit test
307 // (MessageLoop::current() == null).
308 if (chrome::GetTotalBrowserCount() == 0 &&
309 !browser_shutdown::IsTryingToQuit() &&
310 base::MessageLoop::current()) {
316 bool WillKeepAlive() {
317 return g_keep_alive_count > 0;
320 void NotifyAppTerminating() {
321 static bool notified = false;
325 content::NotificationService::current()->Notify(
326 chrome::NOTIFICATION_APP_TERMINATING,
327 content::NotificationService::AllSources(),
328 content::NotificationService::NoDetails());
331 void NotifyAndTerminate(bool fast_path) {
332 #if defined(OS_CHROMEOS)
333 static bool notified = false;
334 // Return if a shutdown request has already been sent.
341 NotifyAppTerminating();
343 #if defined(OS_CHROMEOS)
344 if (base::SysInfo::IsRunningOnChromeOS()) {
345 // If we're on a ChromeOS device, reboot if an update has been applied,
346 // or else signal the session manager to log out.
347 chromeos::UpdateEngineClient* update_engine_client
348 = chromeos::DBusThreadManager::Get()->GetUpdateEngineClient();
349 if (update_engine_client->GetLastStatus().status ==
350 chromeos::UpdateEngineClient::UPDATE_STATUS_UPDATED_NEED_REBOOT) {
351 update_engine_client->RebootAfterUpdate();
352 } else if (!g_session_manager_requested_shutdown) {
353 // Don't ask SessionManager to stop session if the shutdown request comes
354 // from session manager.
355 chromeos::DBusThreadManager::Get()->GetSessionManagerClient()
359 // If running the Chrome OS build, but we're not on the device, act
360 // as if we received signal from SessionManager.
361 content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
362 base::Bind(&ExitCleanly));
367 void OnAppExiting() {
368 static bool notified = false;
372 HandleAppExitingForPlatform();
375 bool ShouldStartShutdown(Browser* browser) {
376 if (BrowserList::GetInstance(browser->host_desktop_type())->size() > 1)
378 #if defined(OS_WIN) && defined(USE_AURA)
379 // On Windows 8 the desktop and ASH environments could be active
381 // We should not start the shutdown process in the following cases:-
382 // 1. If the desktop type of the browser going away is ASH and there
383 // are browser windows open in the desktop.
384 // 2. If the desktop type of the browser going away is desktop and the ASH
385 // environment is still active.
386 if (browser->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_NATIVE)
387 return !ash::Shell::HasInstance();
388 else if (browser->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH)
389 return BrowserList::GetInstance(chrome::HOST_DESKTOP_TYPE_NATIVE)->empty();
394 } // namespace chrome