Only grant permissions to new extensions from sync if they have the expected version
[chromium-blink-merge.git] / chrome / browser / browser_shutdown.cc
bloba3669a620849d7fcd3b986f67dd25556e819ac3c
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/files/file_path.h"
13 #include "base/files/file_util.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/profiles/profile_metrics.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"
37 #if defined(OS_WIN)
38 #include "chrome/browser/browser_util_win.h"
39 #include "chrome/browser/first_run/upgrade_util_win.h"
40 #endif
42 #if defined(ENABLE_RLZ)
43 #include "components/rlz/rlz_tracker.h"
44 #endif
46 #if defined(OS_CHROMEOS)
47 #include "chrome/browser/chromeos/boot_times_recorder.h"
48 #endif
50 #if defined(ENABLE_PRINT_PREVIEW)
51 #include "chrome/browser/service_process/service_process_control.h"
52 #endif
54 using base::Time;
55 using base::TimeDelta;
56 using content::BrowserThread;
58 namespace browser_shutdown {
59 namespace {
61 // Whether the browser is trying to quit (e.g., Quit chosen from menu).
62 bool g_trying_to_quit = false;
64 #if defined(OS_WIN)
65 upgrade_util::RelaunchMode g_relaunch_mode =
66 upgrade_util::RELAUNCH_MODE_DEFAULT;
67 #endif
69 Time* g_shutdown_started = nullptr;
70 ShutdownType g_shutdown_type = NOT_VALID;
71 int g_shutdown_num_processes;
72 int g_shutdown_num_processes_slow;
74 const char kShutdownMsFile[] = "chrome_shutdown_ms.txt";
76 const char* ToShutdownTypeString(ShutdownType type) {
77 switch (type) {
78 case NOT_VALID:
79 NOTREACHED();
80 return "";
81 case WINDOW_CLOSE:
82 return "close";
83 case BROWSER_EXIT:
84 return "exit";
85 case END_SESSION:
86 return "end";
88 return "";
91 } // namespace
93 void RegisterPrefs(PrefRegistrySimple* registry) {
94 registry->RegisterIntegerPref(prefs::kShutdownType, NOT_VALID);
95 registry->RegisterIntegerPref(prefs::kShutdownNumProcesses, 0);
96 registry->RegisterIntegerPref(prefs::kShutdownNumProcessesSlow, 0);
99 ShutdownType GetShutdownType() {
100 return g_shutdown_type;
103 void OnShutdownStarting(ShutdownType type) {
104 if (g_shutdown_type != NOT_VALID)
105 return;
106 base::debug::SetCrashKeyValue(crash_keys::kShutdownType,
107 ToShutdownTypeString(type));
108 #if !defined(OS_CHROMEOS)
109 // Start the shutdown tracing. Note that On ChromeOS this has already been
110 // called in AttemptUserExit().
111 chrome::StartShutdownTracing();
112 #endif
114 g_shutdown_type = type;
115 // For now, we're only counting the number of renderer processes
116 // since we can't safely count the number of plugin processes from this
117 // thread, and we'd really like to avoid anything which might add further
118 // delays to shutdown time.
119 DCHECK(!g_shutdown_started);
120 g_shutdown_started = new Time(Time::Now());
122 // Call FastShutdown on all of the RenderProcessHosts. This will be
123 // a no-op in some cases, so we still need to go through the normal
124 // shutdown path for the ones that didn't exit here.
125 g_shutdown_num_processes = 0;
126 g_shutdown_num_processes_slow = 0;
127 for (content::RenderProcessHost::iterator i(
128 content::RenderProcessHost::AllHostsIterator());
129 !i.IsAtEnd(); i.Advance()) {
130 ++g_shutdown_num_processes;
131 if (!i.GetCurrentValue()->FastShutdownIfPossible())
132 ++g_shutdown_num_processes_slow;
136 base::FilePath GetShutdownMsPath() {
137 base::FilePath shutdown_ms_file;
138 PathService::Get(chrome::DIR_USER_DATA, &shutdown_ms_file);
139 return shutdown_ms_file.AppendASCII(kShutdownMsFile);
142 bool ShutdownPreThreadsStop() {
143 #if defined(OS_CHROMEOS)
144 chromeos::BootTimesRecorder::Get()->AddLogoutTimeMarker(
145 "BrowserShutdownStarted", false);
146 #endif
147 #if defined(ENABLE_PRINT_PREVIEW)
148 // Shutdown the IPC channel to the service processes.
149 ServiceProcessControl::GetInstance()->Disconnect();
150 #endif // ENABLE_PRINT_PREVIEW
152 // WARNING: During logoff/shutdown (WM_ENDSESSION) we may not have enough
153 // time to get here. If you have something that *must* happen on end session,
154 // consider putting it in BrowserProcessImpl::EndSession.
155 PrefService* prefs = g_browser_process->local_state();
157 // Log the amount of times the user switched profiles during this session.
158 ProfileMetrics::LogNumberOfProfileSwitches();
160 metrics::MetricsService* metrics = g_browser_process->metrics_service();
161 if (metrics)
162 metrics->RecordCompletedSessionEnd();
164 if (g_shutdown_type > NOT_VALID && g_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, g_shutdown_type);
168 prefs->SetInteger(prefs::kShutdownNumProcesses, g_shutdown_num_processes);
169 prefs->SetInteger(prefs::kShutdownNumProcessesSlow,
170 g_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 rlz::RLZTracker::CleanupRlz();
196 #endif
198 return restart_last_session;
201 void ShutdownPostThreadsStop(bool restart_last_session) {
202 delete g_browser_process;
203 g_browser_process = NULL;
205 // crbug.com/95079 - This needs to happen after the browser process object
206 // goes away.
207 ProfileManager::NukeDeletedProfilesFromDisk();
209 #if defined(OS_CHROMEOS)
210 chromeos::BootTimesRecorder::Get()->AddLogoutTimeMarker("BrowserDeleted",
211 true);
212 #endif
214 #if defined(OS_WIN)
215 if (!browser_util::IsBrowserAlreadyRunning() &&
216 g_shutdown_type != browser_shutdown::END_SESSION) {
217 upgrade_util::SwapNewChromeExeIfPresent();
219 #endif
221 if (restart_last_session) {
222 #if !defined(OS_CHROMEOS)
223 // Make sure to relaunch the browser with the original command line plus
224 // the Restore Last Session flag. Note that Chrome can be launched (ie.
225 // through ShellExecute on Windows) with a switch argument terminator at
226 // the end (double dash, as described in b/1366444) plus a URL,
227 // which prevents us from appending to the command line directly (issue
228 // 46182). We therefore use GetSwitches to copy the command line (it stops
229 // at the switch argument terminator).
230 base::CommandLine old_cl(*base::CommandLine::ForCurrentProcess());
231 scoped_ptr<base::CommandLine> new_cl(
232 new base::CommandLine(old_cl.GetProgram()));
233 std::map<std::string, base::CommandLine::StringType> switches =
234 old_cl.GetSwitches();
235 // Remove the switches that shouldn't persist across restart.
236 about_flags::RemoveFlagsSwitches(&switches);
237 switches::RemoveSwitchesForAutostart(&switches);
238 // Append the old switches to the new command line.
239 for (const auto& it : switches) {
240 const base::CommandLine::StringType& switch_value = it.second;
241 if (!switch_value.empty())
242 new_cl->AppendSwitchNative(it.first, it.second);
243 else
244 new_cl->AppendSwitch(it.first);
247 #if defined(OS_WIN)
248 upgrade_util::RelaunchChromeWithMode(*new_cl.get(), g_relaunch_mode);
249 #else
250 upgrade_util::RelaunchChromeBrowser(*new_cl.get());
251 #endif // defined(OS_WIN)
253 #else
254 NOTIMPLEMENTED();
255 #endif // !defined(OS_CHROMEOS)
258 if (g_shutdown_type > NOT_VALID && g_shutdown_num_processes > 0) {
259 // Measure total shutdown time as late in the process as possible
260 // and then write it to a file to be read at startup.
261 // We can't use prefs since all services are shutdown at this point.
262 TimeDelta shutdown_delta = Time::Now() - *g_shutdown_started;
263 std::string shutdown_ms =
264 base::Int64ToString(shutdown_delta.InMilliseconds());
265 int len = static_cast<int>(shutdown_ms.length()) + 1;
266 base::FilePath shutdown_ms_file = GetShutdownMsPath();
267 base::WriteFile(shutdown_ms_file, shutdown_ms.c_str(), len);
270 #if defined(OS_CHROMEOS)
271 chrome::NotifyAndTerminate(false);
272 #endif
275 void ReadLastShutdownFile(ShutdownType type,
276 int num_procs,
277 int num_procs_slow) {
278 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
280 base::FilePath shutdown_ms_file = GetShutdownMsPath();
281 std::string shutdown_ms_str;
282 int64_t shutdown_ms = 0;
283 if (base::ReadFileToString(shutdown_ms_file, &shutdown_ms_str))
284 base::StringToInt64(shutdown_ms_str, &shutdown_ms);
285 base::DeleteFile(shutdown_ms_file, false);
287 if (type == NOT_VALID || shutdown_ms == 0 || num_procs == 0)
288 return;
290 const char time_fmt[] = "Shutdown.%s.time";
291 const char time_per_fmt[] = "Shutdown.%s.time_per_process";
292 std::string time;
293 std::string time_per;
294 if (type == WINDOW_CLOSE) {
295 time = base::StringPrintf(time_fmt, "window_close");
296 time_per = base::StringPrintf(time_per_fmt, "window_close");
297 } else if (type == BROWSER_EXIT) {
298 time = base::StringPrintf(time_fmt, "browser_exit");
299 time_per = base::StringPrintf(time_per_fmt, "browser_exit");
300 } else if (type == END_SESSION) {
301 time = base::StringPrintf(time_fmt, "end_session");
302 time_per = base::StringPrintf(time_per_fmt, "end_session");
303 } else {
304 NOTREACHED();
307 if (time.empty())
308 return;
310 // TODO(erikkay): change these to UMA histograms after a bit more testing.
311 UMA_HISTOGRAM_TIMES(time.c_str(), TimeDelta::FromMilliseconds(shutdown_ms));
312 UMA_HISTOGRAM_TIMES(time_per.c_str(),
313 TimeDelta::FromMilliseconds(shutdown_ms / num_procs));
314 UMA_HISTOGRAM_COUNTS_100("Shutdown.renderers.total", num_procs);
315 UMA_HISTOGRAM_COUNTS_100("Shutdown.renderers.slow", num_procs_slow);
318 void ReadLastShutdownInfo() {
319 PrefService* prefs = g_browser_process->local_state();
320 ShutdownType type =
321 static_cast<ShutdownType>(prefs->GetInteger(prefs::kShutdownType));
322 int num_procs = prefs->GetInteger(prefs::kShutdownNumProcesses);
323 int num_procs_slow = prefs->GetInteger(prefs::kShutdownNumProcessesSlow);
324 // clear the prefs immediately so we don't pick them up on a future run
325 prefs->SetInteger(prefs::kShutdownType, NOT_VALID);
326 prefs->SetInteger(prefs::kShutdownNumProcesses, 0);
327 prefs->SetInteger(prefs::kShutdownNumProcessesSlow, 0);
329 // Read and delete the file on the file thread.
330 BrowserThread::PostTask(
331 BrowserThread::FILE, FROM_HERE,
332 base::Bind(&ReadLastShutdownFile, type, num_procs, num_procs_slow));
335 void SetTryingToQuit(bool quitting) {
336 g_trying_to_quit = quitting;
339 bool IsTryingToQuit() {
340 return g_trying_to_quit;
343 } // namespace browser_shutdown