Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / lifetime / application_lifetime.cc
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.
4
5 #include "chrome/browser/lifetime/application_lifetime.h"
6
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/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"
37
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"
47 #endif
48
49 #if defined(OS_WIN)
50 #include "base/win/win_util.h"
51 #endif
52
53 namespace chrome {
54 namespace {
55
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())
63     return true;
64
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)
68     return false;
69
70   // Check TabsNeedBeforeUnloadFired().
71   for (; !browser_it.done(); browser_it.Next()) {
72     if (browser_it->TabsNeedBeforeUnloadFired())
73       return false;
74   }
75   return true;
76 }
77 #endif  // !defined(OS_ANDROID)
78
79 int g_keep_alive_count = 0;
80
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;
84 #endif
85
86 }  // namespace
87
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);
92 }
93
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);
99 #endif
100
101   content::NotificationService::current()->Notify(
102       chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
103       content::NotificationService::AllSources(),
104       content::NotificationService::NoDetails());
105
106   g_browser_process->platform_part()->AttemptExit();
107 }
108
109 void CloseAllBrowsersAndQuit() {
110   browser_shutdown::SetTryingToQuit(true);
111   CloseAllBrowsers();
112 }
113
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);
123
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
130
131     chrome::NotifyAndTerminate(true);
132     chrome::OnAppExiting();
133     return;
134   }
135
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();
143 }
144
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);
152
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());
158
159   // Login screen should show up in owner's locale.
160   PrefService* state = g_browser_process->local_state();
161   if (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();
169     }
170   }
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);
175 #else
176   // Reset the restart bit that might have been set in cancelled restart
177   // request.
178   PrefService* pref_service = g_browser_process->local_state();
179   pref_service->SetBoolean(prefs::kRestartLastSessionOnShutdown, false);
180   AttemptExitInternal(false);
181 #endif
182 }
183
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(
190         category_filter,
191         base::debug::TraceLog::RECORDING_MODE,
192         base::debug::TraceLog::RECORD_UNTIL_FULL);
193   }
194   TRACE_EVENT0("shutdown", "StartShutdownTracing");
195 }
196
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());
203
204   PrefService* pref_service = g_browser_process->local_state();
205   pref_service->SetBoolean(prefs::kWasRestarted, true);
206
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));
214 #else
215   // Set the flag to restore state after the restart.
216   pref_service->SetBoolean(prefs::kRestartLastSessionOnShutdown, true);
217   AttemptExit();
218 #endif
219 }
220 #endif
221
222 void AttemptExit() {
223 #if defined(OS_CHROMEOS)
224   // On ChromeOS, user exit and system exits are the same.
225   AttemptUserExit();
226 #else
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();
235 #endif
236   AttemptExitInternal(true);
237 #endif
238 }
239
240 #if defined(OS_CHROMEOS)
241 // A function called when SIGTERM is received.
242 void ExitCleanly() {
243   // We always mark exit cleanly because SessionManager may kill
244   // chrome in 3 seconds after SIGTERM.
245   g_browser_process->EndSession();
246
247   // Don't block when SIGTERM is received. AreaAllBrowsersCloseable()
248   // can be false in following cases. a) power-off b) signout from
249   // screen locker.
250   if (!AreAllBrowsersCloseable())
251     browser_shutdown::OnShutdownStarting(browser_shutdown::END_SESSION);
252   else
253     browser_shutdown::OnShutdownStarting(browser_shutdown::BROWSER_EXIT);
254   AttemptExitInternal(true);
255 }
256 #endif
257
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.
262
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));
268
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())
274     return;
275   already_ended = true;
276
277   browser_shutdown::OnShutdownStarting(browser_shutdown::END_SESSION);
278
279   content::NotificationService::current()->Notify(
280       chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
281       content::NotificationService::AllSources(),
282       content::NotificationService::NoDetails());
283
284   // Write important data first.
285   g_browser_process->EndSession();
286
287   CloseAllBrowsers();
288
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());
295
296 #if defined(OS_WIN)
297   base::win::SetShouldCrashOnProcessDetach(false);
298 #endif
299   // This will end by terminating the process.
300   content::ImmediateShutdownAndExitProcess();
301 }
302
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;
309 }
310
311 void EndKeepAlive() {
312   DCHECK_GT(g_keep_alive_count, 0);
313   --g_keep_alive_count;
314
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;
319
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()) {
329       CloseAllBrowsers();
330     }
331   }
332 }
333
334 bool WillKeepAlive() {
335   return g_keep_alive_count > 0;
336 }
337
338 void NotifyAppTerminating() {
339   static bool notified = false;
340   if (notified)
341     return;
342   notified = true;
343   content::NotificationService::current()->Notify(
344       chrome::NOTIFICATION_APP_TERMINATING,
345       content::NotificationService::AllSources(),
346       content::NotificationService::NoDetails());
347 }
348
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.
353   if (notified)
354     return;
355   notified = true;
356 #endif
357
358   if (fast_path)
359     NotifyAppTerminating();
360
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()
374           ->StopSession();
375     }
376   } else {
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));
382     }
383   }
384 #endif
385 }
386
387 void OnAppExiting() {
388   static bool notified = false;
389   if (notified)
390     return;
391   notified = true;
392   HandleAppExitingForPlatform();
393 }
394
395 bool ShouldStartShutdown(Browser* browser) {
396   if (BrowserList::GetInstance(browser->host_desktop_type())->size() > 1)
397     return false;
398 #if defined(OS_WIN)
399   // On Windows 8 the desktop and ASH environments could be active
400   // at the same time.
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();
410 #endif
411   return true;
412 }
413
414 }  // namespace chrome