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/browser_shutdown.h"
10 #include "base/bind.h"
11 #include "base/command_line.h"
12 #include "base/file_util.h"
13 #include "base/files/file_path.h"
14 #include "base/metrics/histogram.h"
15 #include "base/path_service.h"
16 #include "base/prefs/pref_registry_simple.h"
17 #include "base/prefs/pref_service.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/threading/thread.h"
21 #include "base/time/time.h"
22 #include "chrome/browser/about_flags.h"
23 #include "chrome/browser/browser_process.h"
24 #include "chrome/browser/first_run/upgrade_util.h"
25 #include "chrome/browser/lifetime/application_lifetime.h"
26 #include "chrome/browser/profiles/profile_manager.h"
27 #include "chrome/browser/service_process/service_process_control.h"
28 #include "chrome/common/chrome_paths.h"
29 #include "chrome/common/chrome_switches.h"
30 #include "chrome/common/crash_keys.h"
31 #include "chrome/common/pref_names.h"
32 #include "chrome/common/switch_utils.h"
33 #include "components/metrics/metrics_service.h"
34 #include "content/public/browser/browser_thread.h"
35 #include "content/public/browser/render_process_host.h"
38 #include "chrome/browser/browser_util_win.h"
39 #include "chrome/browser/first_run/upgrade_util_win.h"
42 #if defined(ENABLE_RLZ)
43 #include "chrome/browser/rlz/rlz.h"
46 #if defined(OS_CHROMEOS)
47 #include "chrome/browser/chromeos/boot_times_loader.h"
51 using base::TimeDelta
;
52 using content::BrowserThread
;
54 namespace browser_shutdown
{
57 // Whether the browser is trying to quit (e.g., Quit chosen from menu).
58 bool g_trying_to_quit
= false;
61 upgrade_util::RelaunchMode g_relaunch_mode
=
62 upgrade_util::RELAUNCH_MODE_DEFAULT
;
65 Time
* shutdown_started_
= NULL
;
66 ShutdownType shutdown_type_
= NOT_VALID
;
67 int shutdown_num_processes_
;
68 int shutdown_num_processes_slow_
;
70 const char kShutdownMsFile
[] = "chrome_shutdown_ms.txt";
72 const char* ToShutdownTypeString(ShutdownType type
) {
89 void RegisterPrefs(PrefRegistrySimple
* registry
) {
90 registry
->RegisterIntegerPref(prefs::kShutdownType
, NOT_VALID
);
91 registry
->RegisterIntegerPref(prefs::kShutdownNumProcesses
, 0);
92 registry
->RegisterIntegerPref(prefs::kShutdownNumProcessesSlow
, 0);
95 ShutdownType
GetShutdownType() {
96 return shutdown_type_
;
99 void OnShutdownStarting(ShutdownType type
) {
100 if (shutdown_type_
!= NOT_VALID
)
102 base::debug::SetCrashKeyValue(crash_keys::kShutdownType
,
103 ToShutdownTypeString(type
));
104 #if !defined(OS_CHROMEOS)
105 // Start the shutdown tracing. Note that On ChromeOS we have started this
107 chrome::StartShutdownTracing();
110 shutdown_type_
= type
;
111 // For now, we're only counting the number of renderer processes
112 // since we can't safely count the number of plugin processes from this
113 // thread, and we'd really like to avoid anything which might add further
114 // delays to shutdown time.
115 DCHECK(!shutdown_started_
);
116 shutdown_started_
= new Time(Time::Now());
118 // Call FastShutdown on all of the RenderProcessHosts. This will be
119 // a no-op in some cases, so we still need to go through the normal
120 // shutdown path for the ones that didn't exit here.
121 shutdown_num_processes_
= 0;
122 shutdown_num_processes_slow_
= 0;
123 for (content::RenderProcessHost::iterator
i(
124 content::RenderProcessHost::AllHostsIterator());
125 !i
.IsAtEnd(); i
.Advance()) {
126 ++shutdown_num_processes_
;
127 if (!i
.GetCurrentValue()->FastShutdownIfPossible())
128 ++shutdown_num_processes_slow_
;
132 base::FilePath
GetShutdownMsPath() {
133 base::FilePath shutdown_ms_file
;
134 PathService::Get(chrome::DIR_USER_DATA
, &shutdown_ms_file
);
135 return shutdown_ms_file
.AppendASCII(kShutdownMsFile
);
138 bool ShutdownPreThreadsStop() {
139 #if defined(OS_CHROMEOS)
140 chromeos::BootTimesLoader::Get()->AddLogoutTimeMarker(
141 "BrowserShutdownStarted", false);
144 // Shutdown the IPC channel to the service processes.
145 ServiceProcessControl::GetInstance()->Disconnect();
147 // WARNING: During logoff/shutdown (WM_ENDSESSION) we may not have enough
148 // time to get here. If you have something that *must* happen on end session,
149 // consider putting it in BrowserProcessImpl::EndSession.
150 PrefService
* prefs
= g_browser_process
->local_state();
152 MetricsService
* metrics
= g_browser_process
->metrics_service();
154 metrics
->RecordCompletedSessionEnd();
156 if (shutdown_type_
> NOT_VALID
&& shutdown_num_processes_
> 0) {
157 // Record the shutdown info so that we can put it into a histogram at next
159 prefs
->SetInteger(prefs::kShutdownType
, shutdown_type_
);
160 prefs
->SetInteger(prefs::kShutdownNumProcesses
, shutdown_num_processes_
);
161 prefs
->SetInteger(prefs::kShutdownNumProcessesSlow
,
162 shutdown_num_processes_slow_
);
165 // Check local state for the restart flag so we can restart the session below.
166 bool restart_last_session
= false;
167 if (prefs
->HasPrefPath(prefs::kRestartLastSessionOnShutdown
)) {
168 restart_last_session
=
169 prefs
->GetBoolean(prefs::kRestartLastSessionOnShutdown
);
170 prefs
->ClearPref(prefs::kRestartLastSessionOnShutdown
);
172 if (restart_last_session
) {
173 if (prefs
->HasPrefPath(prefs::kRelaunchMode
)) {
174 g_relaunch_mode
= upgrade_util::RelaunchModeStringToEnum(
175 prefs
->GetString(prefs::kRelaunchMode
));
176 prefs
->ClearPref(prefs::kRelaunchMode
);
182 prefs
->CommitPendingWrite();
184 #if defined(ENABLE_RLZ)
185 // Cleanup any statics created by RLZ. Must be done before NotificationService
187 RLZTracker::CleanupRlz();
190 return restart_last_session
;
193 void ShutdownPostThreadsStop(bool restart_last_session
) {
194 delete g_browser_process
;
195 g_browser_process
= NULL
;
197 // crbug.com/95079 - This needs to happen after the browser process object
199 ProfileManager::NukeDeletedProfilesFromDisk();
201 #if defined(OS_CHROMEOS)
202 chromeos::BootTimesLoader::Get()->AddLogoutTimeMarker("BrowserDeleted",
207 if (!browser_util::IsBrowserAlreadyRunning() &&
208 shutdown_type_
!= browser_shutdown::END_SESSION
) {
209 upgrade_util::SwapNewChromeExeIfPresent();
213 if (restart_last_session
) {
214 #if !defined(OS_CHROMEOS)
215 // Make sure to relaunch the browser with the original command line plus
216 // the Restore Last Session flag. Note that Chrome can be launched (ie.
217 // through ShellExecute on Windows) with a switch argument terminator at
218 // the end (double dash, as described in b/1366444) plus a URL,
219 // which prevents us from appending to the command line directly (issue
220 // 46182). We therefore use GetSwitches to copy the command line (it stops
221 // at the switch argument terminator).
222 CommandLine
old_cl(*CommandLine::ForCurrentProcess());
223 scoped_ptr
<CommandLine
> new_cl(new CommandLine(old_cl
.GetProgram()));
224 std::map
<std::string
, CommandLine::StringType
> switches
=
225 old_cl
.GetSwitches();
226 // Remove the switches that shouldn't persist across restart.
227 about_flags::RemoveFlagsSwitches(&switches
);
228 switches::RemoveSwitchesForAutostart(&switches
);
229 // Append the old switches to the new command line.
230 for (std::map
<std::string
, CommandLine::StringType
>::const_iterator i
=
231 switches
.begin(); i
!= switches
.end(); ++i
) {
232 CommandLine::StringType switch_value
= i
->second
;
233 if (!switch_value
.empty())
234 new_cl
->AppendSwitchNative(i
->first
, i
->second
);
236 new_cl
->AppendSwitch(i
->first
);
240 upgrade_util::RelaunchChromeWithMode(*new_cl
.get(), g_relaunch_mode
);
242 upgrade_util::RelaunchChromeBrowser(*new_cl
.get());
243 #endif // defined(OS_WIN)
247 #endif // !defined(OS_CHROMEOS)
250 if (shutdown_type_
> NOT_VALID
&& shutdown_num_processes_
> 0) {
251 // Measure total shutdown time as late in the process as possible
252 // and then write it to a file to be read at startup.
253 // We can't use prefs since all services are shutdown at this point.
254 TimeDelta shutdown_delta
= Time::Now() - *shutdown_started_
;
255 std::string shutdown_ms
=
256 base::Int64ToString(shutdown_delta
.InMilliseconds());
257 int len
= static_cast<int>(shutdown_ms
.length()) + 1;
258 base::FilePath shutdown_ms_file
= GetShutdownMsPath();
259 base::WriteFile(shutdown_ms_file
, shutdown_ms
.c_str(), len
);
262 #if defined(OS_CHROMEOS)
263 chrome::NotifyAndTerminate(false);
267 void ReadLastShutdownFile(ShutdownType type
,
269 int num_procs_slow
) {
270 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
272 base::FilePath shutdown_ms_file
= GetShutdownMsPath();
273 std::string shutdown_ms_str
;
274 int64 shutdown_ms
= 0;
275 if (base::ReadFileToString(shutdown_ms_file
, &shutdown_ms_str
))
276 base::StringToInt64(shutdown_ms_str
, &shutdown_ms
);
277 base::DeleteFile(shutdown_ms_file
, false);
279 if (type
== NOT_VALID
|| shutdown_ms
== 0 || num_procs
== 0)
282 const char* time_fmt
= "Shutdown.%s.time";
283 const char* time_per_fmt
= "Shutdown.%s.time_per_process";
285 std::string time_per
;
286 if (type
== WINDOW_CLOSE
) {
287 time
= base::StringPrintf(time_fmt
, "window_close");
288 time_per
= base::StringPrintf(time_per_fmt
, "window_close");
289 } else if (type
== BROWSER_EXIT
) {
290 time
= base::StringPrintf(time_fmt
, "browser_exit");
291 time_per
= base::StringPrintf(time_per_fmt
, "browser_exit");
292 } else if (type
== END_SESSION
) {
293 time
= base::StringPrintf(time_fmt
, "end_session");
294 time_per
= base::StringPrintf(time_per_fmt
, "end_session");
302 // TODO(erikkay): change these to UMA histograms after a bit more testing.
303 UMA_HISTOGRAM_TIMES(time
.c_str(),
304 TimeDelta::FromMilliseconds(shutdown_ms
));
305 UMA_HISTOGRAM_TIMES(time_per
.c_str(),
306 TimeDelta::FromMilliseconds(shutdown_ms
/ num_procs
));
307 UMA_HISTOGRAM_COUNTS_100("Shutdown.renderers.total", num_procs
);
308 UMA_HISTOGRAM_COUNTS_100("Shutdown.renderers.slow", num_procs_slow
);
311 void ReadLastShutdownInfo() {
312 PrefService
* prefs
= g_browser_process
->local_state();
314 static_cast<ShutdownType
>(prefs
->GetInteger(prefs::kShutdownType
));
315 int num_procs
= prefs
->GetInteger(prefs::kShutdownNumProcesses
);
316 int num_procs_slow
= prefs
->GetInteger(prefs::kShutdownNumProcessesSlow
);
317 // clear the prefs immediately so we don't pick them up on a future run
318 prefs
->SetInteger(prefs::kShutdownType
, NOT_VALID
);
319 prefs
->SetInteger(prefs::kShutdownNumProcesses
, 0);
320 prefs
->SetInteger(prefs::kShutdownNumProcessesSlow
, 0);
322 // Read and delete the file on the file thread.
323 BrowserThread::PostTask(
324 BrowserThread::FILE, FROM_HERE
,
325 base::Bind(&ReadLastShutdownFile
, type
, num_procs
, num_procs_slow
));
328 void SetTryingToQuit(bool quitting
) {
329 g_trying_to_quit
= quitting
;
332 bool IsTryingToQuit() {
333 return g_trying_to_quit
;
336 } // namespace browser_shutdown