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"
8 #include "base/command_line.h"
9 #include "base/logging.h"
10 #include "base/memory/scoped_ptr.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/prefs/pref_service.h"
13 #include "base/process/process.h"
14 #include "base/process/process_handle.h"
15 #include "base/trace_event/trace_event.h"
16 #include "build/build_config.h"
17 #include "chrome/browser/browser_process.h"
18 #include "chrome/browser/browser_process_platform_part.h"
19 #include "chrome/browser/browser_shutdown.h"
20 #include "chrome/browser/chrome_notification_types.h"
21 #include "chrome/browser/download/download_service.h"
22 #include "chrome/browser/lifetime/browser_close_manager.h"
23 #include "chrome/browser/metrics/thread_watcher.h"
24 #include "chrome/browser/profiles/profile.h"
25 #include "chrome/browser/profiles/profile_manager.h"
26 #include "chrome/browser/ui/browser.h"
27 #include "chrome/browser/ui/browser_finder.h"
28 #include "chrome/browser/ui/browser_iterator.h"
29 #include "chrome/browser/ui/browser_tabstrip.h"
30 #include "chrome/browser/ui/browser_window.h"
31 #include "chrome/browser/ui/tabs/tab_strip_model.h"
32 #include "chrome/browser/ui/user_manager.h"
33 #include "chrome/common/chrome_constants.h"
34 #include "chrome/common/chrome_switches.h"
35 #include "chrome/common/pref_names.h"
36 #include "content/public/browser/browser_shutdown.h"
37 #include "content/public/browser/browser_thread.h"
38 #include "content/public/browser/navigation_details.h"
39 #include "content/public/browser/notification_service.h"
41 #if defined(OS_CHROMEOS)
42 #include "base/sys_info.h"
43 #include "chrome/browser/chromeos/boot_times_recorder.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"
51 #include "components/browser_watcher/exit_funnel_win.h"
55 #include "ash/shell.h"
61 #if !defined(OS_ANDROID)
62 // Returns true if all browsers can be closed without user interaction.
63 // This currently checks if there is pending download, or if it needs to
64 // handle unload handler.
65 bool AreAllBrowsersCloseable() {
66 chrome::BrowserIterator browser_it
;
67 if (browser_it
.done())
70 // If there are any downloads active, all browsers are not closeable.
71 // However, this does not block for malicious downloads.
72 if (DownloadService::NonMaliciousDownloadCountAllProfiles() > 0)
75 // Check TabsNeedBeforeUnloadFired().
76 for (; !browser_it
.done(); browser_it
.Next()) {
77 if (browser_it
->TabsNeedBeforeUnloadFired())
82 #endif // !defined(OS_ANDROID)
84 int g_keep_alive_count
= 0;
86 #if defined(OS_CHROMEOS)
87 // Whether chrome should send stop request to a session manager.
88 bool g_send_stop_request_to_session_manager
= false;
93 void MarkAsCleanShutdown() {
94 // TODO(beng): Can this use ProfileManager::GetLoadedProfiles() instead?
95 for (chrome::BrowserIterator it
; !it
.done(); it
.Next())
96 it
->profile()->SetExitType(Profile::EXIT_NORMAL
);
99 void AttemptExitInternal(bool try_to_quit_application
) {
100 // On Mac, the platform-specific part handles setting this.
101 #if !defined(OS_MACOSX)
102 if (try_to_quit_application
)
103 browser_shutdown::SetTryingToQuit(true);
106 content::NotificationService::current()->Notify(
107 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST
,
108 content::NotificationService::AllSources(),
109 content::NotificationService::NoDetails());
111 g_browser_process
->platform_part()->AttemptExit();
114 void CloseAllBrowsersAndQuit() {
115 browser_shutdown::SetTryingToQuit(true);
119 void CloseAllBrowsers() {
120 // If there are no browsers and closing the last browser would quit the
121 // application, send the APP_TERMINATING action here. Otherwise, it will be
122 // sent by RemoveBrowser() when the last browser has closed.
123 if (chrome::GetTotalBrowserCount() == 0 &&
124 (browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive())) {
125 // Tell everyone that we are shutting down.
126 browser_shutdown::SetTryingToQuit(true);
128 #if defined(ENABLE_SESSION_SERVICE)
129 // If ShuttingDownWithoutClosingBrowsers() returns true, the session
130 // services may not get a chance to shut down normally, so explicitly shut
131 // them down here to ensure they have a chance to persist their data.
132 ProfileManager::ShutdownSessionServices();
135 chrome::NotifyAndTerminate(true);
136 chrome::OnAppExiting();
140 #if defined(OS_CHROMEOS)
141 chromeos::BootTimesRecorder::Get()->AddLogoutTimeMarker(
142 "StartedClosingWindows", false);
144 scoped_refptr
<BrowserCloseManager
> browser_close_manager
=
145 new BrowserCloseManager
;
146 browser_close_manager
->StartClosingBrowsers();
149 void AttemptUserExit() {
150 #if defined(OS_CHROMEOS)
151 StartShutdownTracing();
152 chromeos::BootTimesRecorder::Get()->AddLogoutTimeMarker("LogoutStarted",
155 PrefService
* state
= g_browser_process
->local_state();
157 chromeos::BootTimesRecorder::Get()->OnLogoutStarted(state
);
159 // Login screen should show up in owner's locale.
160 std::string owner_locale
= state
->GetString(prefs::kOwnerLocale
);
161 if (!owner_locale
.empty() &&
162 state
->GetString(prefs::kApplicationLocale
) != owner_locale
&&
163 !state
->IsManagedPreference(prefs::kApplicationLocale
)) {
164 state
->SetString(prefs::kApplicationLocale
, owner_locale
);
165 TRACE_EVENT0("shutdown", "CommitPendingWrite");
166 state
->CommitPendingWrite();
169 g_send_stop_request_to_session_manager
= true;
170 // On ChromeOS, always terminate the browser, regardless of the result of
171 // AreAllBrowsersCloseable(). See crbug.com/123107.
172 chrome::NotifyAndTerminate(true);
174 // Reset the restart bit that might have been set in cancelled restart
177 PrefService
* pref_service
= g_browser_process
->local_state();
178 pref_service
->SetBoolean(prefs::kRestartLastSessionOnShutdown
, false);
179 AttemptExitInternal(false);
183 void StartShutdownTracing() {
184 const base::CommandLine
& command_line
=
185 *base::CommandLine::ForCurrentProcess();
186 if (command_line
.HasSwitch(switches::kTraceShutdown
)) {
187 base::trace_event::CategoryFilter
category_filter(
188 command_line
.GetSwitchValueASCII(switches::kTraceShutdown
));
189 base::trace_event::TraceLog::GetInstance()->SetEnabled(
191 base::trace_event::TraceLog::RECORDING_MODE
,
192 base::trace_event::TraceOptions());
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 chromeos::BootTimesRecorder::Get()->set_restart_requested();
210 DCHECK(!g_send_stop_request_to_session_manager
);
211 // Make sure we don't send stop request to the session manager.
212 g_send_stop_request_to_session_manager
= false;
213 // Run exit process in clean stack.
214 content::BrowserThread::PostTask(content::BrowserThread::UI
, FROM_HERE
,
215 base::Bind(&ExitCleanly
));
217 // Set the flag to restore state after the restart.
218 pref_service
->SetBoolean(prefs::kRestartLastSessionOnShutdown
, true);
225 #if defined(OS_CHROMEOS)
226 // On ChromeOS, user exit and system exits are the same.
229 // If we know that all browsers can be closed without blocking,
230 // don't notify users of crashes beyond this point.
231 // Note that MarkAsCleanShutdown() does not set UMA's exit cleanly bit
232 // so crashes during shutdown are still reported in UMA.
233 #if !defined(OS_ANDROID)
234 // Android doesn't use Browser.
235 if (AreAllBrowsersCloseable())
236 MarkAsCleanShutdown();
238 AttemptExitInternal(true);
242 #if defined(OS_CHROMEOS)
243 // A function called when SIGTERM is received.
245 // We always mark exit cleanly because SessionManager may kill
246 // chrome in 3 seconds after SIGTERM.
247 g_browser_process
->EndSession();
249 // Don't block when SIGTERM is received. AreaAllBrowsersCloseable()
250 // can be false in following cases. a) power-off b) signout from
252 if (!AreAllBrowsersCloseable())
253 browser_shutdown::OnShutdownStarting(browser_shutdown::END_SESSION
);
255 browser_shutdown::OnShutdownStarting(browser_shutdown::BROWSER_EXIT
);
256 AttemptExitInternal(true);
260 void SessionEnding() {
262 browser_watcher::ExitFunnel funnel
;
264 funnel
.Init(kBrowserExitCodesRegistryPath
, base::GetCurrentProcessHandle());
265 funnel
.RecordEvent(L
"SessionEnding");
267 // This is a time-limited shutdown where we need to write as much to
268 // disk as we can as soon as we can, and where we must kill the
269 // process within a hang timeout to avoid user prompts.
271 // Start watching for hang during shutdown, and crash it if takes too long.
272 // We disarm when |shutdown_watcher| object is destroyed, which is when we
273 // exit this function.
274 ShutdownWatcherHelper shutdown_watcher
;
275 shutdown_watcher
.Arm(base::TimeDelta::FromSeconds(90));
277 // EndSession is invoked once per frame. Only do something the first time.
278 static bool already_ended
= false;
279 // We may get called in the middle of shutdown, e.g. http://crbug.com/70852
280 // In this case, do nothing.
281 if (already_ended
|| !content::NotificationService::current())
283 already_ended
= true;
285 browser_shutdown::OnShutdownStarting(browser_shutdown::END_SESSION
);
287 content::NotificationService::current()->Notify(
288 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST
,
289 content::NotificationService::AllSources(),
290 content::NotificationService::NoDetails());
293 funnel
.RecordEvent(L
"EndSession");
295 // Write important data first.
296 g_browser_process
->EndSession();
299 base::win::SetShouldCrashOnProcessDetach(false);
303 // KillProcess ought to terminate the process without further ado, so if
304 // execution gets to this point, presumably this is normal exit.
305 funnel
.RecordEvent(L
"KillProcess");
308 // On Windows 7 and later, the system will consider the process ripe for
309 // termination as soon as it hides or destroys its windows. Since any
310 // execution past that point will be non-deterministically cut short, we
311 // might as well put ourselves out of that misery deterministically.
312 base::Process::Current().Terminate(0, false);
315 void IncrementKeepAliveCount() {
316 // Increment the browser process refcount as long as we're keeping the
317 // application alive.
318 if (!WillKeepAlive())
319 g_browser_process
->AddRefModule();
320 ++g_keep_alive_count
;
323 void DecrementKeepAliveCount() {
324 DCHECK_GT(g_keep_alive_count
, 0);
325 --g_keep_alive_count
;
327 DCHECK(g_browser_process
);
328 // Although we should have a browser process, if there is none,
329 // there is nothing to do.
330 if (!g_browser_process
) return;
332 // Allow the app to shutdown again.
333 if (!WillKeepAlive()) {
334 g_browser_process
->ReleaseModule();
335 // If there are no browsers open and we aren't already shutting down,
336 // initiate a shutdown. Also skips shutdown if this is a unit test
337 // (MessageLoop::current() == null).
338 if (chrome::GetTotalBrowserCount() == 0 &&
339 !browser_shutdown::IsTryingToQuit() &&
340 base::MessageLoop::current()) {
346 bool WillKeepAlive() {
347 return g_keep_alive_count
> 0;
350 void NotifyAppTerminating() {
351 static bool notified
= false;
355 content::NotificationService::current()->Notify(
356 chrome::NOTIFICATION_APP_TERMINATING
,
357 content::NotificationService::AllSources(),
358 content::NotificationService::NoDetails());
361 void NotifyAndTerminate(bool fast_path
) {
362 #if defined(OS_CHROMEOS)
363 static bool notified
= false;
364 // Return if a shutdown request has already been sent.
371 NotifyAppTerminating();
373 #if defined(OS_CHROMEOS)
374 if (base::SysInfo::IsRunningOnChromeOS()) {
375 // If we're on a ChromeOS device, reboot if an update has been applied,
376 // or else signal the session manager to log out.
377 chromeos::UpdateEngineClient
* update_engine_client
378 = chromeos::DBusThreadManager::Get()->GetUpdateEngineClient();
379 if (update_engine_client
->GetLastStatus().status
==
380 chromeos::UpdateEngineClient::UPDATE_STATUS_UPDATED_NEED_REBOOT
) {
381 update_engine_client
->RebootAfterUpdate();
382 } else if (g_send_stop_request_to_session_manager
) {
383 // Don't ask SessionManager to stop session if the shutdown request comes
384 // from session manager.
385 chromeos::DBusThreadManager::Get()->GetSessionManagerClient()
389 if (g_send_stop_request_to_session_manager
) {
390 // If running the Chrome OS build, but we're not on the device, act
391 // as if we received signal from SessionManager.
392 content::BrowserThread::PostTask(content::BrowserThread::UI
, FROM_HERE
,
393 base::Bind(&ExitCleanly
));
399 void OnAppExiting() {
400 static bool notified
= false;
404 HandleAppExitingForPlatform();
407 bool ShouldStartShutdown(Browser
* browser
) {
408 if (BrowserList::GetInstance(browser
->host_desktop_type())->size() > 1)
411 // On Windows 8 the desktop and ASH environments could be active
413 // We should not start the shutdown process in the following cases:-
414 // 1. If the desktop type of the browser going away is ASH and there
415 // are browser windows open in the desktop.
416 // 2. If the desktop type of the browser going away is desktop and the ASH
417 // environment is still active.
418 if (browser
->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_NATIVE
)
419 return !ash::Shell::HasInstance();
420 else if (browser
->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH
)
421 return BrowserList::GetInstance(chrome::HOST_DESKTOP_TYPE_NATIVE
)->empty();
426 } // namespace chrome