NaCl: Update revision in DEPS, r12770 -> r12773
[chromium-blink-merge.git] / chrome / browser / browser_shutdown.cc
blob327392f5c82b57329492b32d2ba7fd6318a01490
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"
7 #include <map>
8 #include <string>
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/threading/thread_restrictions.h"
22 #include "base/time/time.h"
23 #include "build/build_config.h"
24 #include "chrome/browser/about_flags.h"
25 #include "chrome/browser/browser_process.h"
26 #include "chrome/browser/first_run/upgrade_util.h"
27 #include "chrome/browser/jankometer.h"
28 #include "chrome/browser/lifetime/application_lifetime.h"
29 #include "chrome/browser/metrics/metrics_service.h"
30 #include "chrome/browser/profiles/profile_manager.h"
31 #include "chrome/browser/service_process/service_process_control.h"
32 #include "chrome/common/chrome_paths.h"
33 #include "chrome/common/chrome_switches.h"
34 #include "chrome/common/crash_keys.h"
35 #include "chrome/common/pref_names.h"
36 #include "chrome/common/switch_utils.h"
37 #include "content/public/browser/browser_thread.h"
38 #include "content/public/browser/render_process_host.h"
39 #include "content/public/browser/render_view_host.h"
40 #include "ui/base/resource/resource_bundle.h"
42 #if defined(OS_WIN)
43 #include "chrome/browser/browser_util_win.h"
44 #include "chrome/browser/first_run/upgrade_util_win.h"
45 #endif
47 #if defined(ENABLE_RLZ)
48 #include "chrome/browser/rlz/rlz.h"
49 #endif
51 #if defined(OS_CHROMEOS)
52 #include "chrome/browser/chromeos/boot_times_loader.h"
53 #endif
55 using base::Time;
56 using base::TimeDelta;
57 using content::BrowserThread;
59 namespace browser_shutdown {
60 namespace {
62 // Whether the browser is trying to quit (e.g., Quit chosen from menu).
63 bool g_trying_to_quit = false;
65 // Whether the browser should quit without closing browsers.
66 bool g_shutting_down_without_closing_browsers = false;
68 #if defined(OS_WIN)
69 upgrade_util::RelaunchMode g_relaunch_mode =
70 upgrade_util::RELAUNCH_MODE_DEFAULT;
71 #endif
73 Time* shutdown_started_ = NULL;
74 ShutdownType shutdown_type_ = NOT_VALID;
75 int shutdown_num_processes_;
76 int shutdown_num_processes_slow_;
78 const char kShutdownMsFile[] = "chrome_shutdown_ms.txt";
80 const char* ToShutdownTypeString(ShutdownType type) {
81 switch (type) {
82 case NOT_VALID:
83 NOTREACHED();
84 return "";
85 case WINDOW_CLOSE:
86 return "close";
87 case BROWSER_EXIT:
88 return "exit";
89 case END_SESSION:
90 return "end";
92 return "";
95 } // namespace
97 void RegisterPrefs(PrefRegistrySimple* registry) {
98 registry->RegisterIntegerPref(prefs::kShutdownType, NOT_VALID);
99 registry->RegisterIntegerPref(prefs::kShutdownNumProcesses, 0);
100 registry->RegisterIntegerPref(prefs::kShutdownNumProcessesSlow, 0);
103 ShutdownType GetShutdownType() {
104 return shutdown_type_;
107 void OnShutdownStarting(ShutdownType type) {
108 if (shutdown_type_ != NOT_VALID)
109 return;
110 base::debug::SetCrashKeyValue(crash_keys::kShutdownType,
111 ToShutdownTypeString(type));
112 #if !defined(OS_CHROMEOS)
113 // Start the shutdown tracing. Note that On ChromeOS we have started this
114 // already.
115 chrome::StartShutdownTracing();
116 #endif
118 shutdown_type_ = type;
119 // For now, we're only counting the number of renderer processes
120 // since we can't safely count the number of plugin processes from this
121 // thread, and we'd really like to avoid anything which might add further
122 // delays to shutdown time.
123 DCHECK(!shutdown_started_);
124 shutdown_started_ = new Time(Time::Now());
126 // Call FastShutdown on all of the RenderProcessHosts. This will be
127 // a no-op in some cases, so we still need to go through the normal
128 // shutdown path for the ones that didn't exit here.
129 shutdown_num_processes_ = 0;
130 shutdown_num_processes_slow_ = 0;
131 for (content::RenderProcessHost::iterator i(
132 content::RenderProcessHost::AllHostsIterator());
133 !i.IsAtEnd(); i.Advance()) {
134 ++shutdown_num_processes_;
135 if (!i.GetCurrentValue()->FastShutdownIfPossible())
136 ++shutdown_num_processes_slow_;
140 base::FilePath GetShutdownMsPath() {
141 base::FilePath shutdown_ms_file;
142 PathService::Get(chrome::DIR_USER_DATA, &shutdown_ms_file);
143 return shutdown_ms_file.AppendASCII(kShutdownMsFile);
146 bool ShutdownPreThreadsStop() {
147 #if defined(OS_CHROMEOS)
148 chromeos::BootTimesLoader::Get()->AddLogoutTimeMarker(
149 "BrowserShutdownStarted", false);
150 #endif
152 // Shutdown the IPC channel to the service processes.
153 ServiceProcessControl::GetInstance()->Disconnect();
155 // WARNING: During logoff/shutdown (WM_ENDSESSION) we may not have enough
156 // time to get here. If you have something that *must* happen on end session,
157 // consider putting it in BrowserProcessImpl::EndSession.
158 PrefService* prefs = g_browser_process->local_state();
160 MetricsService* metrics = g_browser_process->metrics_service();
161 if (metrics)
162 metrics->RecordCompletedSessionEnd();
164 if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) {
165 // Record the shutdown info so that we can put it into a histogram at next
166 // startup.
167 prefs->SetInteger(prefs::kShutdownType, shutdown_type_);
168 prefs->SetInteger(prefs::kShutdownNumProcesses, shutdown_num_processes_);
169 prefs->SetInteger(prefs::kShutdownNumProcessesSlow,
170 shutdown_num_processes_slow_);
173 // Check local state for the restart flag so we can restart the session below.
174 bool restart_last_session = false;
175 if (prefs->HasPrefPath(prefs::kRestartLastSessionOnShutdown)) {
176 restart_last_session =
177 prefs->GetBoolean(prefs::kRestartLastSessionOnShutdown);
178 prefs->ClearPref(prefs::kRestartLastSessionOnShutdown);
179 #if defined(OS_WIN)
180 if (restart_last_session) {
181 if (prefs->HasPrefPath(prefs::kRelaunchMode)) {
182 g_relaunch_mode = upgrade_util::RelaunchModeStringToEnum(
183 prefs->GetString(prefs::kRelaunchMode));
184 prefs->ClearPref(prefs::kRelaunchMode);
187 #endif
190 prefs->CommitPendingWrite();
192 #if defined(ENABLE_RLZ)
193 // Cleanup any statics created by RLZ. Must be done before NotificationService
194 // is destroyed.
195 RLZTracker::CleanupRlz();
196 #endif
198 return restart_last_session;
201 void ShutdownPostThreadsStop(bool restart_last_session) {
202 // The jank'o'meter requires that the browser process has been destroyed
203 // before calling UninstallJankometer().
204 delete g_browser_process;
205 g_browser_process = NULL;
207 // crbug.com/95079 - This needs to happen after the browser process object
208 // goes away.
209 ProfileManager::NukeDeletedProfilesFromDisk();
211 #if defined(OS_CHROMEOS)
212 chromeos::BootTimesLoader::Get()->AddLogoutTimeMarker("BrowserDeleted",
213 true);
214 #endif
216 // Uninstall Jank-O-Meter here after the IO thread is no longer running.
217 UninstallJankometer();
219 #if defined(OS_WIN)
220 if (!browser_util::IsBrowserAlreadyRunning() &&
221 shutdown_type_ != browser_shutdown::END_SESSION) {
222 upgrade_util::SwapNewChromeExeIfPresent();
224 #endif
226 if (restart_last_session) {
227 #if !defined(OS_CHROMEOS)
228 // Make sure to relaunch the browser with the original command line plus
229 // the Restore Last Session flag. Note that Chrome can be launched (ie.
230 // through ShellExecute on Windows) with a switch argument terminator at
231 // the end (double dash, as described in b/1366444) plus a URL,
232 // which prevents us from appending to the command line directly (issue
233 // 46182). We therefore use GetSwitches to copy the command line (it stops
234 // at the switch argument terminator).
235 CommandLine old_cl(*CommandLine::ForCurrentProcess());
236 scoped_ptr<CommandLine> new_cl(new CommandLine(old_cl.GetProgram()));
237 std::map<std::string, CommandLine::StringType> switches =
238 old_cl.GetSwitches();
239 // Remove the switches that shouldn't persist across restart.
240 about_flags::RemoveFlagsSwitches(&switches);
241 switches::RemoveSwitchesForAutostart(&switches);
242 // Append the old switches to the new command line.
243 for (std::map<std::string, CommandLine::StringType>::const_iterator i =
244 switches.begin(); i != switches.end(); ++i) {
245 CommandLine::StringType switch_value = i->second;
246 if (!switch_value.empty())
247 new_cl->AppendSwitchNative(i->first, i->second);
248 else
249 new_cl->AppendSwitch(i->first);
252 #if defined(OS_WIN)
253 upgrade_util::RelaunchChromeWithMode(*new_cl.get(), g_relaunch_mode);
254 #else
255 upgrade_util::RelaunchChromeBrowser(*new_cl.get());
256 #endif // defined(OS_WIN)
258 #else
259 NOTIMPLEMENTED();
260 #endif // !defined(OS_CHROMEOS)
263 if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) {
264 // Measure total shutdown time as late in the process as possible
265 // and then write it to a file to be read at startup.
266 // We can't use prefs since all services are shutdown at this point.
267 TimeDelta shutdown_delta = Time::Now() - *shutdown_started_;
268 std::string shutdown_ms =
269 base::Int64ToString(shutdown_delta.InMilliseconds());
270 int len = static_cast<int>(shutdown_ms.length()) + 1;
271 base::FilePath shutdown_ms_file = GetShutdownMsPath();
272 file_util::WriteFile(shutdown_ms_file, shutdown_ms.c_str(), len);
275 #if defined(OS_CHROMEOS)
276 chrome::NotifyAndTerminate(false);
277 #endif
280 void ReadLastShutdownFile(ShutdownType type,
281 int num_procs,
282 int num_procs_slow) {
283 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
285 base::FilePath shutdown_ms_file = GetShutdownMsPath();
286 std::string shutdown_ms_str;
287 int64 shutdown_ms = 0;
288 if (base::ReadFileToString(shutdown_ms_file, &shutdown_ms_str))
289 base::StringToInt64(shutdown_ms_str, &shutdown_ms);
290 base::DeleteFile(shutdown_ms_file, false);
292 if (type == NOT_VALID || shutdown_ms == 0 || num_procs == 0)
293 return;
295 const char* time_fmt = "Shutdown.%s.time";
296 const char* time_per_fmt = "Shutdown.%s.time_per_process";
297 std::string time;
298 std::string time_per;
299 if (type == WINDOW_CLOSE) {
300 time = base::StringPrintf(time_fmt, "window_close");
301 time_per = base::StringPrintf(time_per_fmt, "window_close");
302 } else if (type == BROWSER_EXIT) {
303 time = base::StringPrintf(time_fmt, "browser_exit");
304 time_per = base::StringPrintf(time_per_fmt, "browser_exit");
305 } else if (type == END_SESSION) {
306 time = base::StringPrintf(time_fmt, "end_session");
307 time_per = base::StringPrintf(time_per_fmt, "end_session");
308 } else {
309 NOTREACHED();
312 if (time.empty())
313 return;
315 // TODO(erikkay): change these to UMA histograms after a bit more testing.
316 UMA_HISTOGRAM_TIMES(time.c_str(),
317 TimeDelta::FromMilliseconds(shutdown_ms));
318 UMA_HISTOGRAM_TIMES(time_per.c_str(),
319 TimeDelta::FromMilliseconds(shutdown_ms / num_procs));
320 UMA_HISTOGRAM_COUNTS_100("Shutdown.renderers.total", num_procs);
321 UMA_HISTOGRAM_COUNTS_100("Shutdown.renderers.slow", num_procs_slow);
324 void ReadLastShutdownInfo() {
325 PrefService* prefs = g_browser_process->local_state();
326 ShutdownType type =
327 static_cast<ShutdownType>(prefs->GetInteger(prefs::kShutdownType));
328 int num_procs = prefs->GetInteger(prefs::kShutdownNumProcesses);
329 int num_procs_slow = prefs->GetInteger(prefs::kShutdownNumProcessesSlow);
330 // clear the prefs immediately so we don't pick them up on a future run
331 prefs->SetInteger(prefs::kShutdownType, NOT_VALID);
332 prefs->SetInteger(prefs::kShutdownNumProcesses, 0);
333 prefs->SetInteger(prefs::kShutdownNumProcessesSlow, 0);
335 // Read and delete the file on the file thread.
336 BrowserThread::PostTask(
337 BrowserThread::FILE, FROM_HERE,
338 base::Bind(&ReadLastShutdownFile, type, num_procs, num_procs_slow));
341 void SetTryingToQuit(bool quitting) {
342 g_trying_to_quit = quitting;
345 bool IsTryingToQuit() {
346 return g_trying_to_quit;
349 bool ShuttingDownWithoutClosingBrowsers() {
350 return g_shutting_down_without_closing_browsers;
353 void SetShuttingDownWithoutClosingBrowsers(bool without_close) {
354 g_shutting_down_without_closing_browsers = without_close;
357 } // namespace browser_shutdown