Roll src/third_party/WebKit 8b42d1d:744641d (svn 186770:186771)
[chromium-blink-merge.git] / chrome / browser / chrome_browser_main.cc
blob3f83021f5a3332aec15e72c0b9ea14fe8ece6097
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/chrome_browser_main.h"
7 #include <set>
8 #include <string>
9 #include <vector>
11 #include "base/at_exit.h"
12 #include "base/bind.h"
13 #include "base/command_line.h"
14 #include "base/debug/crash_logging.h"
15 #include "base/debug/debugger.h"
16 #include "base/debug/trace_event.h"
17 #include "base/files/file_path.h"
18 #include "base/files/file_util.h"
19 #include "base/metrics/field_trial.h"
20 #include "base/metrics/histogram.h"
21 #include "base/path_service.h"
22 #include "base/prefs/json_pref_store.h"
23 #include "base/prefs/pref_registry_simple.h"
24 #include "base/prefs/pref_service.h"
25 #include "base/prefs/pref_value_store.h"
26 #include "base/prefs/scoped_user_pref_update.h"
27 #include "base/process/process_info.h"
28 #include "base/profiler/scoped_tracker.h"
29 #include "base/run_loop.h"
30 #include "base/strings/string_number_conversions.h"
31 #include "base/strings/string_piece.h"
32 #include "base/strings/string_split.h"
33 #include "base/strings/sys_string_conversions.h"
34 #include "base/strings/utf_string_conversions.h"
35 #include "base/sys_info.h"
36 #include "base/threading/platform_thread.h"
37 #include "base/time/time.h"
38 #include "base/values.h"
39 #include "build/build_config.h"
40 #include "cc/base/switches.h"
41 #include "chrome/browser/about_flags.h"
42 #include "chrome/browser/browser_process.h"
43 #include "chrome/browser/browser_process_impl.h"
44 #include "chrome/browser/browser_process_platform_part.h"
45 #include "chrome/browser/browser_shutdown.h"
46 #include "chrome/browser/chrome_browser_main_extra_parts.h"
47 #include "chrome/browser/component_updater/cld_component_installer.h"
48 #include "chrome/browser/component_updater/ev_whitelist_component_installer.h"
49 #include "chrome/browser/component_updater/flash_component_installer.h"
50 #include "chrome/browser/component_updater/recovery_component_installer.h"
51 #include "chrome/browser/component_updater/swiftshader_component_installer.h"
52 #include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
53 #include "chrome/browser/defaults.h"
54 #include "chrome/browser/first_run/first_run.h"
55 #include "chrome/browser/first_run/upgrade_util.h"
56 #include "chrome/browser/google/google_search_counter.h"
57 #include "chrome/browser/gpu/gl_string_manager.h"
58 #include "chrome/browser/gpu/three_d_api_observer.h"
59 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
60 #include "chrome/browser/metrics/field_trial_synchronizer.h"
61 #include "chrome/browser/metrics/thread_watcher.h"
62 #include "chrome/browser/metrics/variations/variations_service.h"
63 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
64 #include "chrome/browser/net/chrome_net_log.h"
65 #include "chrome/browser/net/crl_set_fetcher.h"
66 #include "chrome/browser/notifications/desktop_notification_service.h"
67 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
68 #include "chrome/browser/performance_monitor/performance_monitor.h"
69 #include "chrome/browser/plugins/plugin_prefs.h"
70 #include "chrome/browser/power/process_power_collector.h"
71 #include "chrome/browser/pref_service_flags_storage.h"
72 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
73 #include "chrome/browser/prefs/command_line_pref_store.h"
74 #include "chrome/browser/prefs/pref_metrics_service.h"
75 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
76 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
77 #include "chrome/browser/process_singleton.h"
78 #include "chrome/browser/profiles/profile.h"
79 #include "chrome/browser/profiles/profile_manager.h"
80 #include "chrome/browser/profiles/profiles_state.h"
81 #include "chrome/browser/shell_integration.h"
82 #include "chrome/browser/translate/translate_service.h"
83 #include "chrome/browser/ui/app_list/app_list_service.h"
84 #include "chrome/browser/ui/browser.h"
85 #include "chrome/browser/ui/browser_finder.h"
86 #include "chrome/browser/ui/host_desktop.h"
87 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
88 #include "chrome/browser/ui/startup/default_browser_prompt.h"
89 #include "chrome/browser/ui/startup/startup_browser_creator.h"
90 #include "chrome/browser/ui/uma_browsing_activity_observer.h"
91 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
92 #include "chrome/common/chrome_constants.h"
93 #include "chrome/common/chrome_paths.h"
94 #include "chrome/common/chrome_result_codes.h"
95 #include "chrome/common/chrome_switches.h"
96 #include "chrome/common/chrome_version_info.h"
97 #include "chrome/common/crash_keys.h"
98 #include "chrome/common/env_vars.h"
99 #include "chrome/common/logging_chrome.h"
100 #include "chrome/common/net/net_resource_provider.h"
101 #include "chrome/common/pref_names.h"
102 #include "chrome/common/profiling.h"
103 #include "chrome/grit/generated_resources.h"
104 #include "chrome/installer/util/google_update_settings.h"
105 #include "components/component_updater/component_updater_service.h"
106 #include "components/google/core/browser/google_util.h"
107 #include "components/language_usage_metrics/language_usage_metrics.h"
108 #include "components/metrics/metrics_service.h"
109 #include "components/metrics/profiler/tracking_synchronizer.h"
110 #include "components/nacl/browser/nacl_browser.h"
111 #include "components/rappor/rappor_service.h"
112 #include "components/signin/core/common/profile_management_switches.h"
113 #include "components/startup_metric_utils/startup_metric_utils.h"
114 #include "components/translate/content/browser/browser_cld_utils.h"
115 #include "components/translate/content/common/cld_data_source.h"
116 #include "components/translate/core/browser/translate_download_manager.h"
117 #include "components/variations/net/variations_http_header_provider.h"
118 #include "content/public/browser/browser_thread.h"
119 #include "content/public/browser/notification_observer.h"
120 #include "content/public/browser/notification_registrar.h"
121 #include "content/public/browser/notification_service.h"
122 #include "content/public/browser/notification_types.h"
123 #include "content/public/browser/power_usage_monitor.h"
124 #include "content/public/browser/site_instance.h"
125 #include "content/public/common/content_client.h"
126 #include "content/public/common/content_switches.h"
127 #include "content/public/common/main_function_params.h"
128 #include "grit/platform_locale_settings.h"
129 #include "net/base/net_module.h"
130 #include "net/base/sdch_manager.h"
131 #include "net/cookies/cookie_monster.h"
132 #include "net/http/http_network_layer.h"
133 #include "net/http/http_stream_factory.h"
134 #include "net/url_request/url_request.h"
135 #include "ui/base/l10n/l10n_util.h"
136 #include "ui/base/layout.h"
137 #include "ui/base/resource/resource_bundle.h"
138 #include "ui/strings/grit/app_locale_settings.h"
140 #if defined(OS_ANDROID)
141 #include "chrome/browser/metrics/thread_watcher_android.h"
142 #else
143 #include "chrome/browser/feedback/feedback_profile_observer.h"
144 #endif
146 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
147 #include "chrome/browser/first_run/upgrade_util_linux.h"
148 #include "chrome/browser/sxs_linux.h"
149 #endif
151 #if defined(OS_CHROMEOS)
152 #include "chrome/browser/chromeos/settings/cros_settings.h"
153 #include "chromeos/chromeos_switches.h"
154 #include "chromeos/settings/cros_settings_names.h"
155 #endif
157 // TODO(port): several win-only methods have been pulled out of this, but
158 // BrowserMain() as a whole needs to be broken apart so that it's usable by
159 // other platforms. For now, it's just a stub. This is a serious work in
160 // progress and should not be taken as an indication of a real refactoring.
162 #if defined(OS_WIN)
163 #include "base/environment.h" // For PreRead experiment.
164 #include "base/win/windows_version.h"
165 #include "chrome/browser/browser_util_win.h"
166 #include "chrome/browser/chrome_browser_main_win.h"
167 #include "chrome/browser/chrome_select_file_dialog_factory_win.h"
168 #include "chrome/browser/component_updater/sw_reporter_installer_win.h"
169 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
170 #include "chrome/browser/first_run/upgrade_util_win.h"
171 #include "chrome/browser/ui/network_profile_bubble.h"
172 #include "chrome/installer/util/helper.h"
173 #include "chrome/installer/util/install_util.h"
174 #include "chrome/installer/util/shell_util.h"
175 #include "net/base/net_util.h"
176 #include "ui/base/l10n/l10n_util_win.h"
177 #include "ui/gfx/win/dpi.h"
178 #include "ui/shell_dialogs/select_file_dialog.h"
179 #endif // defined(OS_WIN)
181 #if defined(OS_MACOSX)
182 #include <Security/Security.h>
184 #include "base/mac/scoped_nsautorelease_pool.h"
185 #include "chrome/browser/mac/keystone_glue.h"
186 #endif
188 #if !defined(OS_IOS)
189 #include "chrome/browser/ui/app_modal/chrome_javascript_native_dialog_factory.h"
190 #endif
192 #if !defined(DISABLE_NACL)
193 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
194 #include "components/nacl/browser/nacl_process_host.h"
195 #endif
197 #if defined(ENABLE_EXTENSIONS)
198 #include "chrome/browser/extensions/startup_helper.h"
199 #include "extensions/browser/extension_protocols.h"
200 #include "extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.h"
201 #endif
203 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
204 #include "printing/printed_document.h"
205 #endif
207 #if defined(ENABLE_RLZ)
208 #include "chrome/browser/rlz/rlz.h"
209 #endif
211 #if defined(ENABLE_WEBRTC)
212 #include "chrome/browser/media/webrtc_log_util.h"
213 #endif
215 #if defined(USE_AURA)
216 #include "ui/aura/env.h"
217 #endif
219 using content::BrowserThread;
221 namespace {
223 // This function provides some ways to test crash and assertion handling
224 // behavior of the program.
225 void HandleTestParameters(const CommandLine& command_line) {
226 // This parameter causes an assertion.
227 if (command_line.HasSwitch(switches::kBrowserAssertTest)) {
228 DCHECK(false);
231 // This parameter causes a null pointer crash (crash reporter trigger).
232 if (command_line.HasSwitch(switches::kBrowserCrashTest)) {
233 int* bad_pointer = NULL;
234 *bad_pointer = 0;
238 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
239 void AddFirstRunNewTabs(StartupBrowserCreator* browser_creator,
240 const std::vector<GURL>& new_tabs) {
241 for (std::vector<GURL>::const_iterator it = new_tabs.begin();
242 it != new_tabs.end(); ++it) {
243 if (it->is_valid())
244 browser_creator->AddFirstRunTab(*it);
247 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
249 // Returns the new local state object, guaranteed non-NULL.
250 // |local_state_task_runner| must be a shutdown-blocking task runner.
251 PrefService* InitializeLocalState(
252 base::SequencedTaskRunner* local_state_task_runner,
253 const CommandLine& parsed_command_line) {
254 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
255 base::FilePath local_state_path;
256 PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path);
257 bool local_state_file_exists = base::PathExists(local_state_path);
259 // Load local state. This includes the application locale so we know which
260 // locale dll to load. This also causes local state prefs to be registered.
261 PrefService* local_state = g_browser_process->local_state();
262 DCHECK(local_state);
264 #if defined(OS_WIN)
265 if (first_run::IsChromeFirstRun()) {
266 // During first run we read the google_update registry key to find what
267 // language the user selected when downloading the installer. This
268 // becomes our default language in the prefs.
269 // Other platforms obey the system locale.
270 base::string16 install_lang;
271 if (GoogleUpdateSettings::GetLanguage(&install_lang)) {
272 local_state->SetString(prefs::kApplicationLocale,
273 base::UTF16ToASCII(install_lang));
276 #endif // defined(OS_WIN)
278 // If the local state file for the current profile doesn't exist and the
279 // parent profile command line flag is present, then we should inherit some
280 // local state from the parent profile.
281 // Checking that the local state file for the current profile doesn't exist
282 // is the most robust way to determine whether we need to inherit or not
283 // since the parent profile command line flag can be present even when the
284 // current profile is not a new one, and in that case we do not want to
285 // inherit and reset the user's setting.
287 // TODO(mnissler): We should probably just instantiate a
288 // JSONPrefStore here instead of an entire PrefService. Once this is
289 // addressed, the call to browser_prefs::RegisterLocalState can move
290 // to chrome_prefs::CreateLocalState.
291 if (!local_state_file_exists &&
292 parsed_command_line.HasSwitch(switches::kParentProfile)) {
293 base::FilePath parent_profile =
294 parsed_command_line.GetSwitchValuePath(switches::kParentProfile);
295 scoped_refptr<PrefRegistrySimple> registry = new PrefRegistrySimple();
296 scoped_ptr<PrefService> parent_local_state(
297 chrome_prefs::CreateLocalState(
298 parent_profile,
299 local_state_task_runner,
300 g_browser_process->policy_service(),
301 registry,
302 false));
303 registry->RegisterStringPref(prefs::kApplicationLocale, std::string());
304 // Right now, we only inherit the locale setting from the parent profile.
305 local_state->SetString(
306 prefs::kApplicationLocale,
307 parent_local_state->GetString(prefs::kApplicationLocale));
310 #if defined(OS_CHROMEOS)
311 if (parsed_command_line.HasSwitch(chromeos::switches::kLoginManager)) {
312 std::string owner_locale = local_state->GetString(prefs::kOwnerLocale);
313 // Ensure that we start with owner's locale.
314 if (!owner_locale.empty() &&
315 local_state->GetString(prefs::kApplicationLocale) != owner_locale &&
316 !local_state->IsManagedPreference(prefs::kApplicationLocale)) {
317 local_state->SetString(prefs::kApplicationLocale, owner_locale);
320 #endif
322 return local_state;
325 // Initializes the primary profile, possibly doing some user prompting to pick
326 // a fallback profile. Returns the newly created profile, or NULL if startup
327 // should not continue.
328 Profile* CreatePrimaryProfile(const content::MainFunctionParams& parameters,
329 const base::FilePath& user_data_dir,
330 const CommandLine& parsed_command_line) {
331 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
332 base::Time start = base::Time::Now();
333 if (profiles::IsMultipleProfilesEnabled() &&
334 parsed_command_line.HasSwitch(switches::kProfileDirectory)) {
335 g_browser_process->local_state()->SetString(prefs::kProfileLastUsed,
336 parsed_command_line.GetSwitchValueASCII(switches::kProfileDirectory));
337 // Clear kProfilesLastActive since the user only wants to launch a specific
338 // profile.
339 ListPrefUpdate update(g_browser_process->local_state(),
340 prefs::kProfilesLastActive);
341 base::ListValue* profile_list = update.Get();
342 profile_list->Clear();
345 Profile* profile = NULL;
346 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
347 // On ChromeOS and Android the ProfileManager will use the same path as the
348 // one we got passed. GetActiveUserProfile will therefore use the correct path
349 // automatically.
350 DCHECK_EQ(user_data_dir.value(),
351 g_browser_process->profile_manager()->user_data_dir().value());
352 profile = ProfileManager::GetActiveUserProfile();
353 #else
354 base::FilePath profile_path =
355 GetStartupProfilePath(user_data_dir, parsed_command_line);
357 // Without NewAvatarMenu, replace guest with any existing profile.
358 if (!switches::IsNewAvatarMenu() &&
359 profile_path == ProfileManager::GetGuestProfilePath()) {
360 profile_path = g_browser_process->profile_manager()->GetProfileInfoCache().
361 GetPathOfProfileAtIndex(0);
363 profile = g_browser_process->profile_manager()->GetProfile(
364 profile_path);
366 // If we're using the --new-profile-management flag and this profile is
367 // signed out, then we should show the user manager instead. By switching
368 // the active profile to the guest profile we ensure that no
369 // browser windows will be opened for the guest profile.
370 if (switches::IsNewProfileManagement() && !profile->IsGuestSession()) {
371 ProfileInfoCache& cache =
372 g_browser_process->profile_manager()->GetProfileInfoCache();
373 size_t profile_index = cache.GetIndexOfProfileWithPath(profile_path);
375 if (cache.ProfileIsSigninRequiredAtIndex(profile_index))
376 profile = g_browser_process->profile_manager()->GetProfile(
377 ProfileManager::GetGuestProfilePath());
379 #endif
380 if (profile) {
381 UMA_HISTOGRAM_LONG_TIMES(
382 "Startup.CreateFirstProfile", base::Time::Now() - start);
383 return profile;
386 #if !defined(OS_WIN)
387 // TODO(port): fix this. See comments near the definition of
388 // user_data_dir. It is better to CHECK-fail here than it is to
389 // silently exit because of missing code in the above test.
390 CHECK(profile) << "Cannot get default profile.";
391 #endif
393 return NULL;
396 #if defined(OS_MACOSX)
397 OSStatus KeychainCallback(SecKeychainEvent keychain_event,
398 SecKeychainCallbackInfo* info, void* context) {
399 return noErr;
401 #endif
403 void RegisterComponentsForUpdate() {
404 component_updater::ComponentUpdateService* cus =
405 g_browser_process->component_updater();
407 // Registration can be before or after cus->Start() so it is ok to post
408 // a task to the UI thread to do registration once you done the necessary
409 // file IO to know you existing component version.
410 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
411 RegisterRecoveryComponent(cus, g_browser_process->local_state());
412 RegisterPepperFlashComponent(cus);
413 RegisterSwiftShaderComponent(cus);
414 RegisterWidevineCdmComponent(cus);
415 #endif
417 #if !defined(DISABLE_NACL) && !defined(OS_ANDROID)
418 #if defined(OS_CHROMEOS)
419 // PNaCl on Chrome OS is on rootfs and there is no need to download it. But
420 // Chrome4ChromeOS on Linux doesn't contain PNaCl so enable component
421 // installer when ruining on Linux. See crbug.com/422121 for more details.
422 if (!base::SysInfo::IsRunningOnChromeOS())
423 #endif
424 g_browser_process->pnacl_component_installer()->RegisterPnaclComponent(cus);
425 #endif
427 // Registration of the CLD Component is a no-op unless the CLD data source has
428 // been configured to be the "Component" data source.
429 RegisterCldComponent(cus);
431 base::FilePath path;
432 if (PathService::Get(chrome::DIR_USER_DATA, &path)) {
433 #if defined(OS_ANDROID)
434 // The CRLSet component was enabled for some releases. This code attempts to
435 // delete it from the local disk of those how may have downloaded it.
436 g_browser_process->crl_set_fetcher()->DeleteFromDisk(path);
437 #elif !defined(OS_CHROMEOS)
438 // CRLSetFetcher attempts to load a CRL set from either the local disk or
439 // network.
440 // For Chrome OS this registration is delayed until user login.
441 g_browser_process->crl_set_fetcher()->StartInitialLoad(cus, path);
442 // Registration of the EV Whitelist component here is not necessary for:
443 // 1. Android: Because it currently does not have the EV indicator.
444 // 2. Chrome OS: On Chrome OS this registration is delayed until user login.
445 RegisterEVWhitelistComponent(cus, path);
446 #endif
449 #if defined(OS_WIN)
450 RegisterSwReporterComponent(cus, g_browser_process->local_state());
451 #endif
453 cus->Start();
456 #if !defined(OS_ANDROID)
457 bool ProcessSingletonNotificationCallback(
458 const CommandLine& command_line,
459 const base::FilePath& current_directory) {
460 // Drop the request if the browser process is already in shutdown path.
461 if (!g_browser_process || g_browser_process->IsShuttingDown())
462 return false;
464 if (command_line.HasSwitch(switches::kOriginalProcessStartTime)) {
465 std::string start_time_string =
466 command_line.GetSwitchValueASCII(switches::kOriginalProcessStartTime);
467 int64 remote_start_time;
468 if (base::StringToInt64(start_time_string, &remote_start_time)) {
469 base::TimeDelta elapsed =
470 base::Time::Now() - base::Time::FromInternalValue(remote_start_time);
471 if (command_line.HasSwitch(switches::kFastStart)) {
472 UMA_HISTOGRAM_LONG_TIMES(
473 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed);
474 } else {
475 UMA_HISTOGRAM_LONG_TIMES(
476 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed);
481 g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing(
482 command_line);
484 base::FilePath user_data_dir =
485 g_browser_process->profile_manager()->user_data_dir();
486 base::FilePath startup_profile_dir =
487 GetStartupProfilePath(user_data_dir, command_line);
489 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
490 command_line, current_directory, startup_profile_dir);
491 return true;
493 #endif // !defined(OS_ANDROID)
495 void LaunchDevToolsHandlerIfNeeded(const CommandLine& command_line) {
496 if (command_line.HasSwitch(::switches::kRemoteDebuggingPort)) {
497 std::string port_str =
498 command_line.GetSwitchValueASCII(::switches::kRemoteDebuggingPort);
499 int port;
500 if (base::StringToInt(port_str, &port) && port >= 0 && port < 65535) {
501 g_browser_process->CreateDevToolsHttpProtocolHandler(
502 chrome::HOST_DESKTOP_TYPE_NATIVE,
503 "127.0.0.1",
504 static_cast<uint16>(port));
505 } else {
506 DLOG(WARNING) << "Invalid http debugger port number " << port;
511 // Heap allocated class that listens for first page load, kicks off stat
512 // recording and then deletes itself.
513 class LoadCompleteListener : public content::NotificationObserver {
514 public:
515 LoadCompleteListener() {
516 registrar_.Add(this,
517 content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
518 content::NotificationService::AllSources());
520 ~LoadCompleteListener() override {}
522 // content::NotificationObserver implementation.
523 void Observe(int type,
524 const content::NotificationSource& source,
525 const content::NotificationDetails& details) override {
526 DCHECK_EQ(content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, type);
527 startup_metric_utils::OnInitialPageLoadComplete();
528 delete this;
531 private:
532 content::NotificationRegistrar registrar_;
533 DISALLOW_COPY_AND_ASSIGN(LoadCompleteListener);
536 } // namespace
538 namespace chrome_browser {
540 // This error message is not localized because we failed to load the
541 // localization data files.
542 #if defined(OS_WIN)
543 const char kMissingLocaleDataTitle[] = "Missing File Error";
544 #endif
546 #if defined(OS_WIN)
547 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
548 const char kMissingLocaleDataMessage[] =
549 "Unable to find locale data files. Please reinstall.";
550 #endif
552 } // namespace chrome_browser
554 // BrowserMainParts ------------------------------------------------------------
556 // static
557 bool ChromeBrowserMainParts::disable_enforcing_cookie_policies_for_tests_ =
558 false;
560 ChromeBrowserMainParts::ChromeBrowserMainParts(
561 const content::MainFunctionParams& parameters)
562 : parameters_(parameters),
563 parsed_command_line_(parameters.command_line),
564 result_code_(content::RESULT_CODE_NORMAL_EXIT),
565 startup_watcher_(new StartupTimeBomb()),
566 shutdown_watcher_(new ShutdownWatcherHelper()),
567 browser_field_trials_(parameters.command_line),
568 profile_(NULL),
569 run_message_loop_(true),
570 notify_result_(ProcessSingleton::PROCESS_NONE),
571 local_state_(NULL),
572 restart_last_session_(false) {
573 // If we're running tests (ui_task is non-null).
574 if (parameters.ui_task)
575 browser_defaults::enable_help_app = false;
577 // Chrome disallows cookies by default. All code paths that want to use
578 // cookies need to go through one of Chrome's URLRequestContexts which have
579 // a ChromeNetworkDelegate attached that selectively allows cookies again.
580 if (!disable_enforcing_cookie_policies_for_tests_)
581 net::URLRequest::SetDefaultCookiePolicyToBlock();
584 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
585 for (int i = static_cast<int>(chrome_extra_parts_.size())-1; i >= 0; --i)
586 delete chrome_extra_parts_[i];
587 chrome_extra_parts_.clear();
590 // This will be called after the command-line has been mutated by about:flags
591 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
592 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
593 // Must initialize metrics after labs have been converted into switches,
594 // but before field trials are set up (so that client ID is available for
595 // one-time randomized field trials).
597 // Initialize FieldTrialList to support FieldTrials that use one-time
598 // randomization.
599 metrics::MetricsService* metrics = browser_process_->metrics_service();
600 field_trial_list_.reset(
601 new base::FieldTrialList(metrics->CreateEntropyProvider().release()));
603 const CommandLine* command_line = CommandLine::ForCurrentProcess();
604 if (command_line->HasSwitch(switches::kEnableBenchmarking) ||
605 command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking)) {
606 base::FieldTrial::EnableBenchmarking();
609 // Ensure any field trials specified on the command line are initialized.
610 if (command_line->HasSwitch(switches::kForceFieldTrials)) {
611 std::set<std::string> unforceable_field_trials;
612 #if defined(OFFICIAL_BUILD)
613 unforceable_field_trials.insert("SettingsEnforcement");
614 #endif // defined(OFFICIAL_BUILD)
616 // Create field trials without activating them, so that this behaves in a
617 // consistent manner with field trials created from the server.
618 bool result = base::FieldTrialList::CreateTrialsFromString(
619 command_line->GetSwitchValueASCII(switches::kForceFieldTrials),
620 base::FieldTrialList::DONT_ACTIVATE_TRIALS,
621 unforceable_field_trials);
622 CHECK(result) << "Invalid --" << switches::kForceFieldTrials
623 << " list specified.";
625 if (command_line->HasSwitch(switches::kForceVariationIds)) {
626 // Create default variation ids which will always be included in the
627 // X-Client-Data request header.
628 variations::VariationsHttpHeaderProvider* provider =
629 variations::VariationsHttpHeaderProvider::GetInstance();
630 bool result = provider->SetDefaultVariationIds(
631 command_line->GetSwitchValueASCII(switches::kForceVariationIds));
632 CHECK(result) << "Invalid --" << switches::kForceVariationIds
633 << " list specified.";
634 metrics->AddSyntheticTrialObserver(provider);
636 chrome_variations::VariationsService* variations_service =
637 browser_process_->variations_service();
638 if (variations_service)
639 variations_service->CreateTrialsFromSeed();
641 // This must be called after |local_state_| is initialized.
642 browser_field_trials_.SetupFieldTrials(
643 base::Time::FromTimeT(metrics->GetInstallDate()), local_state_);
645 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
646 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
647 // Even though base::Bind does AddRef and Release, the object will not be
648 // deleted after the Task is executed.
649 field_trial_synchronizer_ = new FieldTrialSynchronizer();
651 // Now that field trials have been created, initializes metrics recording.
652 metrics->InitializeMetricsRecordingState();
654 // Enable profiler instrumentation depending on the channel.
655 switch (chrome::VersionInfo::GetChannel()) {
656 case chrome::VersionInfo::CHANNEL_UNKNOWN:
657 case chrome::VersionInfo::CHANNEL_CANARY:
658 tracked_objects::ScopedTracker::Enable();
659 break;
661 case chrome::VersionInfo::CHANNEL_DEV:
662 case chrome::VersionInfo::CHANNEL_BETA:
663 case chrome::VersionInfo::CHANNEL_STABLE:
664 // Don't enable instrumentation.
665 break;
669 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
671 void ChromeBrowserMainParts::StartMetricsRecording() {
672 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
673 metrics::MetricsService* metrics = g_browser_process->metrics_service();
675 const bool only_do_metrics_recording =
676 parsed_command_line_.HasSwitch(switches::kMetricsRecordingOnly) ||
677 parsed_command_line_.HasSwitch(switches::kEnableBenchmarking);
678 if (only_do_metrics_recording) {
679 // If we're testing then we don't care what the user preference is, we turn
680 // on recording, but not reporting, otherwise tests fail.
681 metrics->StartRecordingForTests();
682 return;
685 metrics->CheckForClonedInstall(
686 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
687 const bool metrics_enabled = metrics->StartIfMetricsReportingEnabled();
688 // TODO(asvitkine): Since this function is not run on Android, RAPPOR is
689 // currently disabled there. http://crbug.com/370041
690 browser_process_->rappor_service()->Start(
691 browser_process_->system_request_context(),
692 metrics_enabled);
695 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
696 // Don't record any metrics if UI was displayed before this point e.g.
697 // warning dialogs.
698 if (startup_metric_utils::WasNonBrowserUIDisplayed())
699 return;
701 #if defined(OS_ANDROID)
702 // On Android the first run is handled in Java code, and the C++ side of
703 // Chrome doesn't know if this is the first run. This will cause some
704 // inaccuracy in the UMA statistics, but this should be minor (first runs are
705 // rare).
706 bool is_first_run = false;
707 #else
708 bool is_first_run = first_run::IsChromeFirstRun();
709 #endif
711 // CurrentProcessInfo::CreationTime() is currently only implemented on some
712 // platforms.
713 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
714 const base::Time process_creation_time =
715 base::CurrentProcessInfo::CreationTime();
717 if (!is_first_run && !process_creation_time.is_null()) {
718 base::TimeDelta delay = base::Time::Now() - process_creation_time;
719 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserMessageLoopStartTime", delay);
721 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
723 // Record collected startup metrics.
724 startup_metric_utils::OnBrowserStartupComplete(is_first_run);
726 // Deletes self.
727 new LoadCompleteListener();
730 // -----------------------------------------------------------------------------
731 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
733 #if defined(OS_WIN)
734 #define DLLEXPORT __declspec(dllexport)
736 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
737 extern "C" {
738 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded();
741 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
742 // Need an instance of AtExitManager to handle singleton creations and
743 // deletions. We need this new instance because, the old instance created
744 // in ChromeMain() got destructed when the function returned.
745 base::AtExitManager exit_manager;
746 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
748 #endif
750 // content::BrowserMainParts implementation ------------------------------------
752 void ChromeBrowserMainParts::PreEarlyInitialization() {
753 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
754 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
755 chrome_extra_parts_[i]->PreEarlyInitialization();
758 void ChromeBrowserMainParts::PostEarlyInitialization() {
759 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
760 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
761 chrome_extra_parts_[i]->PostEarlyInitialization();
764 void ChromeBrowserMainParts::ToolkitInitialized() {
765 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
766 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
767 chrome_extra_parts_[i]->ToolkitInitialized();
770 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
771 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
772 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
773 chrome_extra_parts_[i]->PreMainMessageLoopStart();
776 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
777 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
778 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
779 chrome_extra_parts_[i]->PostMainMessageLoopStart();
782 int ChromeBrowserMainParts::PreCreateThreads() {
783 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
784 result_code_ = PreCreateThreadsImpl();
786 if (result_code_ == content::RESULT_CODE_NORMAL_EXIT) {
787 #if !defined(OS_ANDROID)
788 // These members must be initialized before exiting this function normally.
789 DCHECK(master_prefs_.get());
790 DCHECK(browser_creator_.get());
791 #endif
792 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
793 chrome_extra_parts_[i]->PreCreateThreads();
796 return result_code_;
799 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
800 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
801 run_message_loop_ = false;
802 #if !defined(OS_ANDROID)
803 chrome::MaybeShowInvalidUserDataDirWarningDialog();
804 #endif
805 if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir_))
806 return chrome::RESULT_CODE_MISSING_DATA;
808 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
809 MediaCaptureDevicesDispatcher::GetInstance();
811 // Android's first run is done in Java instead of native.
812 #if !defined(OS_ANDROID)
813 process_singleton_.reset(new ChromeProcessSingleton(
814 user_data_dir_, base::Bind(&ProcessSingletonNotificationCallback)));
816 // Cache first run state early.
817 first_run::IsChromeFirstRun();
818 #endif
820 scoped_refptr<base::SequencedTaskRunner> local_state_task_runner =
821 JsonPrefStore::GetTaskRunnerForFile(
822 base::FilePath(chrome::kLocalStorePoolName),
823 BrowserThread::GetBlockingPool());
826 TRACE_EVENT0("startup",
827 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
828 browser_process_.reset(new BrowserProcessImpl(local_state_task_runner.get(),
829 parsed_command_line()));
832 if (parsed_command_line().HasSwitch(switches::kEnableProfiling)) {
833 TRACE_EVENT0("startup",
834 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
835 // User wants to override default tracking status.
836 std::string flag =
837 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling);
838 // Default to basic profiling (no parent child support).
839 tracked_objects::ThreadData::Status status =
840 tracked_objects::ThreadData::PROFILING_ACTIVE;
841 if (flag.compare("0") != 0)
842 status = tracked_objects::ThreadData::DEACTIVATED;
843 else if (flag.compare("child") != 0)
844 status = tracked_objects::ThreadData::PROFILING_CHILDREN_ACTIVE;
845 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status);
848 if (parsed_command_line().HasSwitch(switches::kProfilingOutputFile)) {
849 tracking_objects_.set_output_file_path(
850 parsed_command_line().GetSwitchValuePath(
851 switches::kProfilingOutputFile));
854 local_state_ = InitializeLocalState(
855 local_state_task_runner.get(), parsed_command_line());
857 #if !defined(OS_ANDROID)
858 // These members must be initialized before returning from this function.
859 master_prefs_.reset(new first_run::MasterPrefs);
860 // Android doesn't use StartupBrowserCreator.
861 browser_creator_.reset(new StartupBrowserCreator);
862 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
863 chrome::UMABrowsingActivityObserver::Init();
864 #endif
866 #if !defined(OS_CHROMEOS)
867 // Convert active labs into switches. This needs to be done before
868 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
869 // affected by experiment flags (--touch-optimized-ui in particular).
870 // On ChromeOS system level flags are applied from the device settings from
871 // the session manager.
873 TRACE_EVENT0("startup",
874 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
875 about_flags::PrefServiceFlagsStorage flags_storage_(
876 g_browser_process->local_state());
877 about_flags::ConvertFlagsToSwitches(&flags_storage_,
878 CommandLine::ForCurrentProcess(),
879 about_flags::kAddSentinels);
881 #endif
883 local_state_->UpdateCommandLinePrefStore(
884 new CommandLinePrefStore(CommandLine::ForCurrentProcess()));
886 // Reset the command line in the crash report details, since we may have
887 // just changed it to include experiments.
888 crash_keys::SetSwitchesFromCommandLine(CommandLine::ForCurrentProcess());
890 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
891 // needed when loading the MainMenu.nib and the language doesn't depend on
892 // anything since it comes from Cocoa.
893 #if defined(OS_MACOSX)
894 std::string locale =
895 parameters().ui_task ? "en-US" : l10n_util::GetLocaleOverride();
896 browser_process_->SetApplicationLocale(locale);
897 #else
898 const std::string locale =
899 local_state_->GetString(prefs::kApplicationLocale);
901 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
902 // method InitSharedInstance is ignored.
904 TRACE_EVENT_BEGIN0("startup",
905 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
906 const std::string loaded_locale =
907 ui::ResourceBundle::InitSharedInstanceWithLocale(
908 locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
909 TRACE_EVENT_END0("startup",
910 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
912 if (loaded_locale.empty() &&
913 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs)) {
914 ShowMissingLocaleMessageBox();
915 return chrome::RESULT_CODE_MISSING_DATA;
917 CHECK(!loaded_locale.empty()) << "Locale could not be found for " << locale;
918 browser_process_->SetApplicationLocale(loaded_locale);
920 base::FilePath resources_pack_path;
921 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
923 TRACE_EVENT0("startup",
924 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
925 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
926 resources_pack_path, ui::SCALE_FACTOR_NONE);
928 #endif // defined(OS_MACOSX)
930 // Android does first run in Java instead of native.
931 // Chrome OS has its own out-of-box-experience code.
932 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
933 // On first run, we need to process the predictor preferences before the
934 // browser's profile_manager object is created, but after ResourceBundle
935 // is initialized.
936 if (first_run::IsChromeFirstRun()) {
937 first_run::ProcessMasterPreferencesResult pmp_result =
938 first_run::ProcessMasterPreferences(user_data_dir_,
939 master_prefs_.get());
940 if (pmp_result == first_run::EULA_EXIT_NOW)
941 return chrome::RESULT_CODE_EULA_REFUSED;
943 if (!parsed_command_line().HasSwitch(switches::kApp) &&
944 !parsed_command_line().HasSwitch(switches::kAppId) &&
945 !parsed_command_line().HasSwitch(switches::kShowAppList)) {
946 AddFirstRunNewTabs(browser_creator_.get(), master_prefs_->new_tabs);
949 // TODO(macourteau): refactor preferences that are copied from
950 // master_preferences into local_state, as a "local_state" section in
951 // master preferences. If possible, a generic solution would be preferred
952 // over a copy one-by-one of specific preferences. Also see related TODO
953 // in first_run.h.
955 // Store the initial VariationsService seed in local state, if it exists
956 // in master prefs.
957 if (!master_prefs_->variations_seed.empty()) {
958 local_state_->SetString(prefs::kVariationsSeed,
959 master_prefs_->variations_seed);
960 if (!master_prefs_->variations_seed_signature.empty()) {
961 local_state_->SetString(prefs::kVariationsSeedSignature,
962 master_prefs_->variations_seed_signature);
964 // Set the variation seed date to the current system time. If the user's
965 // clock is incorrect, this may cause some field trial expiry checks to
966 // not do the right thing until the next seed update from the server,
967 // when this value will be updated.
968 local_state_->SetInt64(prefs::kVariationsSeedDate,
969 base::Time::Now().ToInternalValue());
972 if (!master_prefs_->suppress_default_browser_prompt_for_version.empty()) {
973 local_state_->SetString(
974 prefs::kBrowserSuppressDefaultBrowserPrompt,
975 master_prefs_->suppress_default_browser_prompt_for_version);
978 AppListService::Get(chrome::HOST_DESKTOP_TYPE_NATIVE)->HandleFirstRun();
980 #endif
982 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
983 // Set the product channel for crash reports.
984 base::debug::SetCrashKeyValue(crash_keys::kChannel,
985 chrome::VersionInfo::GetVersionStringModifier());
986 #endif
988 // Initialize tracking synchronizer system.
989 tracking_synchronizer_ = new metrics::TrackingSynchronizer();
991 #if defined(OS_MACOSX)
992 // Get the Keychain API to register for distributed notifications on the main
993 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
994 // which doesn't. This ensures those notifications will get delivered
995 // properly. See issue 37766.
996 // (Note that the callback mask here is empty. I don't want to register for
997 // any callbacks, I just want to initialize the mechanism.)
998 SecKeychainAddCallback(&KeychainCallback, 0, NULL);
999 #endif
1001 #if defined(OS_CHROMEOS)
1002 // Must be done after g_browser_process is constructed, before
1003 // SetupMetricsAndFieldTrials().
1004 chromeos::CrosSettings::Initialize();
1005 #endif
1007 // Now the command line has been mutated based on about:flags, we can setup
1008 // metrics and initialize field trials. The field trials are needed by
1009 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
1010 SetupMetricsAndFieldTrials();
1012 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
1013 browser_process_->PreCreateThreads();
1015 return content::RESULT_CODE_NORMAL_EXIT;
1018 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
1019 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1020 result_code_ = PreMainMessageLoopRunImpl();
1022 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1023 chrome_extra_parts_[i]->PreMainMessageLoopRun();
1026 // PreMainMessageLoopRun calls these extra stages in the following order:
1027 // PreMainMessageLoopRunImpl()
1028 // ... initial setup, including browser_process_ setup.
1029 // PreProfileInit()
1030 // ... additional setup, including CreateProfile()
1031 // PostProfileInit()
1032 // ... additional setup
1033 // PreBrowserStart()
1034 // ... browser_creator_->Start (OR parameters().ui_task->Run())
1035 // PostBrowserStart()
1037 void ChromeBrowserMainParts::PreProfileInit() {
1038 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1040 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1041 chrome_extra_parts_[i]->PreProfileInit();
1043 #if !defined(OS_ANDROID)
1044 // Initialize the feedback uploader so it can setup notifications for profile
1045 // creation.
1046 feedback::FeedbackProfileObserver::Initialize();
1048 ProfileManager* profile_manager = g_browser_process->profile_manager();
1050 // First check if any ephemeral profiles are left behind because of browser
1051 // crash and schedule them for deletion and then proceed with getting the set
1052 // of profiles to open.
1053 ProfileInfoCache& profile_cache = profile_manager->GetProfileInfoCache();
1054 size_t profiles_count = profile_cache.GetNumberOfProfiles();
1055 std::vector<base::FilePath> profiles_to_delete;
1056 for (size_t i = 0; i < profiles_count; ++i) {
1057 if (profile_cache.ProfileIsEphemeralAtIndex(i))
1058 profiles_to_delete.push_back(profile_cache.GetPathOfProfileAtIndex(i));
1061 if (profiles_to_delete.size()) {
1062 for (size_t i = 0; i < profiles_to_delete.size(); ++i) {
1063 profile_manager->ScheduleProfileForDeletion(
1064 profiles_to_delete[i], ProfileManager::CreateCallback());
1066 // Clean up stale profiles immediately after browser start.
1067 BrowserThread::PostTask(
1068 BrowserThread::FILE, FROM_HERE,
1069 base::Bind(&ProfileManager::CleanUpStaleProfiles, profiles_to_delete));
1071 #endif // OS_ANDROID
1073 #if defined(ENABLE_EXTENSIONS)
1074 javascript_dialog_extensions_client::InstallClient();
1075 #endif
1077 #if !defined(OS_IOS)
1078 InstallChromeJavaScriptNativeDialogFactory();
1079 #endif
1082 void ChromeBrowserMainParts::PostProfileInit() {
1083 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1084 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1085 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1086 chrome_extra_parts_[i]->PostProfileInit();
1089 void ChromeBrowserMainParts::PreBrowserStart() {
1090 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1091 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1092 chrome_extra_parts_[i]->PreBrowserStart();
1094 three_d_observer_.reset(new ThreeDAPIObserver());
1097 void ChromeBrowserMainParts::PostBrowserStart() {
1098 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1099 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1100 chrome_extra_parts_[i]->PostBrowserStart();
1101 #if !defined(OS_ANDROID)
1102 // Allow ProcessSingleton to process messages.
1103 process_singleton_->Unlock();
1104 #endif
1105 #if defined(ENABLE_WEBRTC)
1106 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1107 // to reduce the impact on startup time.
1108 BrowserThread::PostDelayedTask(
1109 BrowserThread::UI,
1110 FROM_HERE,
1111 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles),
1112 base::TimeDelta::FromMinutes(1));
1113 #endif
1116 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1117 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1118 // Android updates the metrics service dynamically depending on whether the
1119 // application is in the foreground or not. Do not start here.
1120 #if !defined(OS_ANDROID)
1121 // Now that the file thread has been started, start recording.
1122 StartMetricsRecording();
1123 #endif
1125 if (!base::debug::BeingDebugged()) {
1126 // Create watchdog thread after creating all other threads because it will
1127 // watch the other threads and they must be running.
1128 browser_process_->watchdog_thread();
1131 // Do any initializating in the browser process that requires all threads
1132 // running.
1133 browser_process_->PreMainMessageLoopRun();
1135 // Record last shutdown time into a histogram.
1136 browser_shutdown::ReadLastShutdownInfo();
1138 #if defined(OS_WIN)
1139 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1140 // tasks. Those care whether the browser is already running. On Linux/Mac,
1141 // upgrade/uninstall happen separately.
1142 bool already_running = browser_util::IsBrowserAlreadyRunning();
1144 // If the command line specifies 'uninstall' then we need to work here
1145 // unless we detect another chrome browser running.
1146 if (parsed_command_line().HasSwitch(switches::kUninstall)) {
1147 return DoUninstallTasks(already_running);
1150 if (parsed_command_line().HasSwitch(switches::kHideIcons) ||
1151 parsed_command_line().HasSwitch(switches::kShowIcons)) {
1152 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1153 parsed_command_line_);
1156 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
1157 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
1158 #endif
1160 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser)) {
1161 return ShellIntegration::SetAsDefaultBrowser() ?
1162 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT) :
1163 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED);
1166 #if defined(USE_AURA)
1167 // Make sure aura::Env has been initialized.
1168 CHECK(aura::Env::GetInstance());
1169 #endif
1171 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1172 #if !defined(OS_ANDROID)
1173 // If the command line specifies --pack-extension, attempt the pack extension
1174 // startup action and exit.
1175 if (parsed_command_line().HasSwitch(switches::kPackExtension)) {
1176 extensions::StartupHelper extension_startup_helper;
1177 if (extension_startup_helper.PackExtension(parsed_command_line()))
1178 return content::RESULT_CODE_NORMAL_EXIT;
1179 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR;
1182 // If we're being launched just to check the connector policy, we are
1183 // short-lived and don't want to be passing that switch off.
1184 bool pass_command_line = !parsed_command_line().HasSwitch(
1185 switches::kCheckCloudPrintConnectorPolicy);
1187 if (pass_command_line) {
1188 // When another process is running, use that process instead of starting a
1189 // new one. NotifyOtherProcess will currently give the other process up to
1190 // 20 seconds to respond. Note that this needs to be done before we attempt
1191 // to read the profile.
1192 notify_result_ = process_singleton_->NotifyOtherProcessOrCreate();
1193 switch (notify_result_) {
1194 case ProcessSingleton::PROCESS_NONE:
1195 // No process already running, fall through to starting a new one.
1196 break;
1198 case ProcessSingleton::PROCESS_NOTIFIED:
1199 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1200 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1201 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER))).c_str());
1202 #endif
1203 // Having a differentiated return type for testing allows for tests to
1204 // verify proper handling of some switches. When not testing, stick to
1205 // the standard Unix convention of returning zero when things went as
1206 // expected.
1207 if (parsed_command_line().HasSwitch(switches::kTestType))
1208 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED;
1209 return content::RESULT_CODE_NORMAL_EXIT;
1211 case ProcessSingleton::PROFILE_IN_USE:
1212 return chrome::RESULT_CODE_PROFILE_IN_USE;
1214 case ProcessSingleton::LOCK_ERROR:
1215 LOG(ERROR) << "Failed to create a ProcessSingleton for your profile "
1216 "directory. This means that running multiple instances "
1217 "would start multiple browser processes rather than "
1218 "opening a new window in the existing process. Aborting "
1219 "now to avoid profile corruption.";
1220 return chrome::RESULT_CODE_PROFILE_IN_USE;
1222 default:
1223 NOTREACHED();
1226 #endif // !defined(OS_ANDROID)
1228 // Handle special early return paths (which couldn't be processed even earlier
1229 // as they require the process singleton to be held) first.
1231 std::string try_chrome =
1232 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain);
1233 if (!try_chrome.empty()) {
1234 #if defined(OS_WIN)
1235 // Setup.exe has determined that we need to run a retention experiment
1236 // and has lauched chrome to show the experiment UI. It is guaranteed that
1237 // no other Chrome is currently running as the process singleton was
1238 // sucessfully grabbed above.
1239 int try_chrome_int;
1240 base::StringToInt(try_chrome, &try_chrome_int);
1241 TryChromeDialogView::Result answer = TryChromeDialogView::Show(
1242 try_chrome_int,
1243 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog,
1244 base::Unretained(process_singleton_.get())));
1245 if (answer == TryChromeDialogView::NOT_NOW)
1246 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL;
1247 if (answer == TryChromeDialogView::UNINSTALL_CHROME)
1248 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2;
1249 // At this point the user is willing to try chrome again.
1250 if (answer == TryChromeDialogView::TRY_CHROME_AS_DEFAULT) {
1251 // Only set in the unattended case, the interactive case is Windows 8.
1252 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1253 ShellIntegration::SET_DEFAULT_UNATTENDED)
1254 ShellIntegration::SetAsDefaultBrowser();
1256 #else
1257 // We don't support retention experiments on Mac or Linux.
1258 return content::RESULT_CODE_NORMAL_EXIT;
1259 #endif // defined(OS_WIN)
1262 #if defined(OS_WIN)
1263 // Do the tasks if chrome has been upgraded while it was last running.
1264 if (!already_running && upgrade_util::DoUpgradeTasks(parsed_command_line()))
1265 return content::RESULT_CODE_NORMAL_EXIT;
1267 // Check if there is any machine level Chrome installed on the current
1268 // machine. If yes and the current Chrome process is user level, we do not
1269 // allow the user level Chrome to run. So we notify the user and uninstall
1270 // user level Chrome.
1271 // Note this check needs to happen here (after the process singleton was
1272 // obtained but before potentially creating the first run sentinel).
1273 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1274 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS;
1275 #endif // defined(OS_WIN)
1277 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1278 if (sxs_linux::ShouldMigrateUserDataDir())
1279 return sxs_linux::MigrateUserDataDir();
1280 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1282 // Desktop construction occurs here, (required before profile creation).
1283 PreProfileInit();
1285 // Profile creation ----------------------------------------------------------
1287 metrics::MetricsService::SetExecutionPhase(
1288 metrics::MetricsService::CREATE_PROFILE,
1289 g_browser_process->local_state());
1290 profile_ = CreatePrimaryProfile(parameters(),
1291 user_data_dir_,
1292 parsed_command_line());
1293 if (!profile_)
1294 return content::RESULT_CODE_NORMAL_EXIT;
1296 #if !defined(OS_ANDROID)
1297 // The first run sentinel must be created after the process singleton was
1298 // grabbed and no early return paths were otherwise hit above.
1299 first_run::CreateSentinelIfNeeded();
1300 #endif // !defined(OS_ANDROID)
1302 #if defined(ENABLE_BACKGROUND)
1303 // Autoload any profiles which are running background apps.
1304 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1305 browser_process_->profile_manager()->AutoloadProfiles();
1306 #endif
1307 // Post-profile init ---------------------------------------------------------
1309 TranslateService::Initialize();
1311 // Needs to be done before PostProfileInit, since login manager on CrOS is
1312 // called inside PostProfileInit.
1313 content::WebUIControllerFactory::RegisterFactory(
1314 ChromeWebUIControllerFactory::GetInstance());
1316 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1317 // So make sure to create it before that.
1318 #if !defined(DISABLE_NACL)
1319 NaClBrowserDelegateImpl* delegate =
1320 new NaClBrowserDelegateImpl(browser_process_->profile_manager());
1321 nacl::NaClBrowser::SetDelegate(delegate);
1322 #endif
1324 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1325 // (requires supporting early exit).
1326 PostProfileInit();
1328 // Retrieve cached GL strings from local state and use them for GPU
1329 // blacklist decisions.
1330 if (g_browser_process->gl_string_manager())
1331 g_browser_process->gl_string_manager()->Initialize();
1333 // Create an instance of GpuModeManager to watch gpu mode pref change.
1334 g_browser_process->gpu_mode_manager();
1336 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1337 // Show the First Run UI if this is the first time Chrome has been run on
1338 // this computer, or we're being compelled to do so by a command line flag.
1339 // Note that this be done _after_ the PrefService is initialized and all
1340 // preferences are registered, since some of the code that the importer
1341 // touches reads preferences.
1342 if (first_run::IsChromeFirstRun()) {
1343 first_run::AutoImport(profile_,
1344 master_prefs_->homepage_defined,
1345 master_prefs_->do_import_items,
1346 master_prefs_->dont_import_items,
1347 master_prefs_->import_bookmarks_path);
1349 // Note: this can pop the first run consent dialog on linux.
1350 first_run::DoPostImportTasks(profile_,
1351 master_prefs_->make_chrome_default_for_user);
1353 if (!master_prefs_->suppress_first_run_default_browser_prompt) {
1354 browser_creator_->set_show_main_browser_window(
1355 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_));
1356 } else {
1357 browser_creator_->set_is_default_browser_dialog_suppressed(true);
1360 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1362 #if defined(OS_WIN)
1363 // Sets things up so that if we crash from this point on, a dialog will
1364 // popup asking the user to restart chrome. It is done this late to avoid
1365 // testing against a bunch of special cases that are taken care early on.
1366 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1367 parsed_command_line());
1369 // Registers Chrome with the Windows Restart Manager, which will restore the
1370 // Chrome session when the computer is restarted after a system update.
1371 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1372 // but should run on startup if extended to handle crashes/hangs/patches.
1373 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1374 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
1375 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1376 parsed_command_line());
1379 // Verify that the profile is not on a network share and if so prepare to show
1380 // notification to the user.
1381 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_)) {
1382 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
1383 base::Bind(&NetworkProfileBubble::CheckNetworkProfile,
1384 profile_->GetPath()));
1386 #endif // OS_WIN
1388 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1389 // Init the RLZ library. This just binds the dll and schedules a task on the
1390 // file thread to be run sometime later. If this is the first run we record
1391 // the installation event.
1392 PrefService* pref_service = profile_->GetPrefs();
1393 int ping_delay = first_run::IsChromeFirstRun() ? master_prefs_->ping_delay :
1394 pref_service->GetInteger(first_run::GetPingDelayPrefName().c_str());
1395 // Negative ping delay means to send ping immediately after a first search is
1396 // recorded.
1397 RLZTracker::InitRlzFromProfileDelayed(
1398 profile_, first_run::IsChromeFirstRun(), ping_delay < 0,
1399 base::TimeDelta::FromMilliseconds(abs(ping_delay)));
1400 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1402 // Configure modules that need access to resources.
1403 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider);
1405 // In unittest mode, this will do nothing. In normal mode, this will create
1406 // the global IntranetRedirectDetector instance, which will promptly go to
1407 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1408 // to see if it should do anything else.
1410 // A simpler way of doing all this would be to have some function which could
1411 // give the time elapsed since startup, and simply have this object check that
1412 // when asked to initialize itself, but this doesn't seem to exist.
1414 // This can't be created in the BrowserProcessImpl constructor because it
1415 // needs to read prefs that get set after that runs.
1416 browser_process_->intranet_redirect_detector();
1417 GoogleSearchCounter::RegisterForNotifications();
1419 // Check SDCH field trial. Default is now that everything is enabled,
1420 // so provide options for disabling HTTPS or all of SDCH.
1421 const char kSdchFieldTrialName[] = "SDCH";
1422 const char kEnabledHttpOnlyGroupName[] = "EnabledHttpOnly";
1423 const char kDisabledAllGroupName[] = "DisabledAll";
1425 // Store in a string on return to keep underlying storage for
1426 // StringPiece stable.
1427 std::string sdch_trial_group_string =
1428 base::FieldTrialList::FindFullName(kSdchFieldTrialName);
1429 base::StringPiece sdch_trial_group(sdch_trial_group_string);
1430 if (sdch_trial_group.starts_with(kEnabledHttpOnlyGroupName)) {
1431 net::SdchManager::EnableSdchSupport(true);
1432 net::SdchManager::EnableSecureSchemeSupport(false);
1433 } else if (sdch_trial_group.starts_with(kDisabledAllGroupName)) {
1434 net::SdchManager::EnableSdchSupport(false);
1437 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1438 if (parsed_command_line().HasSwitch(switches::kDebugPrint)) {
1439 base::FilePath path =
1440 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint);
1441 printing::PrintedDocument::set_debug_dump_path(path);
1443 #endif
1445 HandleTestParameters(parsed_command_line());
1446 browser_process_->metrics_service()->RecordBreakpadHasDebugger(
1447 base::debug::BeingDebugged());
1449 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1450 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1451 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1452 browser_process_->GetApplicationLocale());
1454 // Start watching for hangs during startup. We disarm this hang detector when
1455 // ThreadWatcher takes over or when browser is shutdown or when
1456 // startup_watcher_ is deleted.
1457 metrics::MetricsService::SetExecutionPhase(
1458 metrics::MetricsService::STARTUP_TIMEBOMB_ARM,
1459 g_browser_process->local_state());
1460 startup_watcher_->Arm(base::TimeDelta::FromSeconds(600));
1462 // On mobile, need for clean shutdown arises only when the application comes
1463 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1464 // http://crbug.com/179143
1465 #if !defined(OS_ANDROID)
1466 // Start watching for a hang.
1467 browser_process_->metrics_service()->LogNeedForCleanShutdown();
1468 #endif
1470 #if defined(ENABLE_PRINT_PREVIEW)
1471 // Create the instance of the cloud print proxy service so that it can launch
1472 // the service process if needed. This is needed because the service process
1473 // might have shutdown because an update was available.
1474 // TODO(torne): this should maybe be done with
1475 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1476 // instead?
1477 CloudPrintProxyServiceFactory::GetForProfile(profile_);
1478 #endif
1480 // Start watching all browser threads for responsiveness.
1481 metrics::MetricsService::SetExecutionPhase(
1482 metrics::MetricsService::THREAD_WATCHER_START,
1483 g_browser_process->local_state());
1484 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1486 #if defined(OS_ANDROID)
1487 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1488 #endif
1490 #if !defined(DISABLE_NACL)
1491 BrowserThread::PostTask(
1492 BrowserThread::IO,
1493 FROM_HERE,
1494 base::Bind(nacl::NaClProcessHost::EarlyStartup));
1495 #endif
1497 // Make sure initial prefs are recorded
1498 PrefMetricsService::Factory::GetForProfile(profile_);
1500 PreBrowserStart();
1502 // Instantiate the notification UI manager, as this triggers a perf timer
1503 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1504 // triggering the timer and call that explicitly in the approprate place.
1505 // http://crbug.com/105065.
1506 browser_process_->notification_ui_manager();
1508 // This must be called prior to RegisterComponentsForUpdate, in case the CLD
1509 // data source is based on the Component Updater.
1510 translate::BrowserCldUtils::ConfigureDefaultDataProvider();
1512 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate))
1513 RegisterComponentsForUpdate();
1515 #if defined(OS_ANDROID)
1516 chrome_variations::VariationsService* variations_service =
1517 browser_process_->variations_service();
1518 if (variations_service) {
1519 variations_service->set_policy_pref_service(profile_->GetPrefs());
1520 variations_service->StartRepeatedVariationsSeedFetch();
1522 translate::TranslateDownloadManager::RequestLanguageList(
1523 profile_->GetPrefs());
1525 #else
1526 // Most general initialization is behind us, but opening a
1527 // tab and/or session restore and such is still to be done.
1528 base::TimeTicks browser_open_start = base::TimeTicks::Now();
1530 // We are in regular browser boot sequence. Open initial tabs and enter the
1531 // main message loop.
1532 int result_code;
1533 #if defined(OS_CHROMEOS)
1534 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1535 // them this early as the cryptohome hasn't yet been mounted (which happens
1536 // only once we log in.
1537 std::vector<Profile*> last_opened_profiles;
1538 #else
1539 std::vector<Profile*> last_opened_profiles =
1540 g_browser_process->profile_manager()->GetLastOpenedProfiles();
1541 #endif
1543 if (browser_creator_->Start(parsed_command_line(), base::FilePath(),
1544 profile_, last_opened_profiles, &result_code)) {
1545 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1546 // Initialize autoupdate timer. Timer callback costs basically nothing
1547 // when browser is not in persistent mode, so it's OK to let it ride on
1548 // the main thread. This needs to be done here because we don't want
1549 // to start the timer when Chrome is run inside a test harness.
1550 browser_process_->StartAutoupdateTimer();
1551 #endif
1553 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1554 // On Linux, the running exe will be updated if an upgrade becomes
1555 // available while the browser is running. We need to save the last
1556 // modified time of the exe, so we can compare to determine if there is
1557 // an upgrade while the browser is kept alive by a persistent extension.
1558 upgrade_util::SaveLastModifiedTimeOfExe();
1559 #endif
1561 // Record now as the last successful chrome start.
1562 GoogleUpdateSettings::SetLastRunTime();
1564 #if defined(OS_MACOSX)
1565 // Call Recycle() here as late as possible, before going into the loop
1566 // because Start() will add things to it while creating the main window.
1567 if (parameters().autorelease_pool)
1568 parameters().autorelease_pool->Recycle();
1569 #endif
1571 base::TimeDelta delay = base::TimeTicks::Now() - browser_open_start;
1572 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserOpenTabs", delay);
1574 // If we're running tests (ui_task is non-null), then we don't want to
1575 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or
1576 // RequestLanguageList
1577 if (parameters().ui_task == NULL) {
1578 // Request new variations seed information from server.
1579 chrome_variations::VariationsService* variations_service =
1580 browser_process_->variations_service();
1581 if (variations_service) {
1582 variations_service->StartRepeatedVariationsSeedFetch();
1584 #if defined(OS_WIN)
1585 variations_service->StartGoogleUpdateRegistrySync();
1586 #endif
1589 translate::TranslateDownloadManager::RequestLanguageList(
1590 profile_->GetPrefs());
1593 run_message_loop_ = true;
1594 } else {
1595 run_message_loop_ = false;
1597 browser_creator_.reset();
1599 #if !defined(OS_LINUX) || defined(OS_CHROMEOS) // http://crbug.com/426393
1600 if (g_browser_process->metrics_service()->reporting_active())
1601 content::StartPowerUsageMonitor();
1602 #endif
1604 process_power_collector_.reset(new ProcessPowerCollector);
1605 process_power_collector_->Initialize();
1606 #endif // !defined(OS_ANDROID)
1608 PostBrowserStart();
1610 if (parameters().ui_task) {
1611 parameters().ui_task->Run();
1612 delete parameters().ui_task;
1613 run_message_loop_ = false;
1615 #if defined(OS_ANDROID)
1616 // We never run the C++ main loop on Android, since the UI thread message
1617 // loop is controlled by the OS, so this is as close as we can get to
1618 // the start of the main loop
1619 if (result_code_ <= 0) {
1620 RecordBrowserStartupTime();
1622 #endif
1623 return result_code_;
1626 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code) {
1627 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1628 #if defined(OS_ANDROID)
1629 // Chrome on Android does not use default MessageLoop. It has its own
1630 // Android specific MessageLoop
1631 NOTREACHED();
1632 return true;
1633 #else
1634 // Set the result code set in PreMainMessageLoopRun or set above.
1635 *result_code = result_code_;
1636 if (!run_message_loop_)
1637 return true; // Don't run the default message loop.
1639 // These should be invoked as close to the start of the browser's
1640 // UI thread message loop as possible to get a stable measurement
1641 // across versions.
1642 RecordBrowserStartupTime();
1644 DCHECK(base::MessageLoopForUI::IsCurrent());
1645 base::RunLoop run_loop;
1647 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1649 metrics::MetricsService::SetExecutionPhase(
1650 metrics::MetricsService::MAIN_MESSAGE_LOOP_RUN,
1651 g_browser_process->local_state());
1652 run_loop.Run();
1654 return true;
1655 #endif
1658 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1659 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1660 #if defined(OS_ANDROID)
1661 // Chrome on Android does not use default MessageLoop. It has its own
1662 // Android specific MessageLoop
1663 NOTREACHED();
1664 #else
1666 // Start watching for jank during shutdown. It gets disarmed when
1667 // |shutdown_watcher_| object is destructed.
1668 metrics::MetricsService::SetExecutionPhase(
1669 metrics::MetricsService::SHUTDOWN_TIMEBOMB_ARM,
1670 g_browser_process->local_state());
1671 shutdown_watcher_->Arm(base::TimeDelta::FromSeconds(300));
1673 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1674 startup_watcher_->Disarm();
1676 // Remove observers attached to D-Bus clients before DbusThreadManager is
1677 // shut down.
1678 process_power_collector_.reset();
1680 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1681 chrome_extra_parts_[i]->PostMainMessageLoopRun();
1683 // Some tests don't set parameters.ui_task, so they started translate
1684 // language fetch that was never completed so we need to cleanup here
1685 // otherwise it will be done by the destructor in a wrong thread.
1686 TranslateService::Shutdown(parameters().ui_task == NULL);
1688 if (notify_result_ == ProcessSingleton::PROCESS_NONE)
1689 process_singleton_->Cleanup();
1691 // Stop all tasks that might run on WatchDogThread.
1692 ThreadWatcherList::StopWatchingAll();
1694 browser_process_->metrics_service()->Stop();
1696 restart_last_session_ = browser_shutdown::ShutdownPreThreadsStop();
1697 browser_process_->StartTearDown();
1698 #endif
1701 void ChromeBrowserMainParts::PostDestroyThreads() {
1702 #if defined(OS_ANDROID)
1703 // On Android, there is no quit/exit. So the browser's main message loop will
1704 // not finish.
1705 NOTREACHED();
1706 #else
1707 browser_process_->PostDestroyThreads();
1708 // browser_shutdown takes care of deleting browser_process, so we need to
1709 // release it.
1710 ignore_result(browser_process_.release());
1711 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_);
1712 master_prefs_.reset();
1713 process_singleton_.reset();
1715 // We need to do this check as late as possible, but due to modularity, this
1716 // may be the last point in Chrome. This would be more effective if done at
1717 // a higher level on the stack, so that it is impossible for an early return
1718 // to bypass this code. Perhaps we need a *final* hook that is called on all
1719 // paths from content/browser/browser_main.
1720 CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
1722 #if defined(OS_CHROMEOS)
1723 chromeos::CrosSettings::Shutdown();
1724 #endif
1725 #endif
1728 // Public members:
1730 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts* parts) {
1731 chrome_extra_parts_.push_back(parts);