Add more checks to investigate SupervisedUserPrefStore crash at startup.
[chromium-blink-merge.git] / chrome / browser / chrome_browser_main.cc
blobcfd3b103a6e5876a138b6d11edaa2cd61589bbd5
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/files/file_path.h"
17 #include "base/files/file_util.h"
18 #include "base/metrics/field_trial.h"
19 #include "base/metrics/histogram_macros.h"
20 #include "base/path_service.h"
21 #include "base/prefs/json_pref_store.h"
22 #include "base/prefs/pref_registry_simple.h"
23 #include "base/prefs/pref_service.h"
24 #include "base/prefs/pref_value_store.h"
25 #include "base/prefs/scoped_user_pref_update.h"
26 #include "base/process/process_info.h"
27 #include "base/profiler/scoped_tracker.h"
28 #include "base/run_loop.h"
29 #include "base/strings/string_number_conversions.h"
30 #include "base/strings/string_piece.h"
31 #include "base/strings/string_split.h"
32 #include "base/strings/sys_string_conversions.h"
33 #include "base/strings/utf_string_conversions.h"
34 #include "base/sys_info.h"
35 #include "base/threading/platform_thread.h"
36 #include "base/time/time.h"
37 #include "base/trace_event/trace_event.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/supervised_user_whitelist_installer.h"
52 #include "chrome/browser/component_updater/swiftshader_component_installer.h"
53 #include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
54 #include "chrome/browser/defaults.h"
55 #include "chrome/browser/first_run/first_run.h"
56 #include "chrome/browser/first_run/upgrade_util.h"
57 #include "chrome/browser/google/google_search_counter.h"
58 #include "chrome/browser/gpu/gl_string_manager.h"
59 #include "chrome/browser/gpu/three_d_api_observer.h"
60 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
61 #include "chrome/browser/metrics/field_trial_synchronizer.h"
62 #include "chrome/browser/metrics/metrics_services_manager.h"
63 #include "chrome/browser/metrics/thread_watcher.h"
64 #include "chrome/browser/metrics/variations/variations_service.h"
65 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
66 #include "chrome/browser/net/chrome_net_log.h"
67 #include "chrome/browser/net/crl_set_fetcher.h"
68 #include "chrome/browser/notifications/desktop_notification_service.h"
69 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
70 #include "chrome/browser/performance_monitor/performance_monitor.h"
71 #include "chrome/browser/plugins/plugin_prefs.h"
72 #include "chrome/browser/power/process_power_collector.h"
73 #include "chrome/browser/pref_service_flags_storage.h"
74 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
75 #include "chrome/browser/prefs/command_line_pref_store.h"
76 #include "chrome/browser/prefs/pref_metrics_service.h"
77 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
78 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
79 #include "chrome/browser/process_singleton.h"
80 #include "chrome/browser/profiles/profile.h"
81 #include "chrome/browser/profiles/profile_manager.h"
82 #include "chrome/browser/profiles/profiles_state.h"
83 #include "chrome/browser/shell_integration.h"
84 #include "chrome/browser/translate/translate_service.h"
85 #include "chrome/browser/ui/app_list/app_list_service.h"
86 #include "chrome/browser/ui/browser.h"
87 #include "chrome/browser/ui/browser_finder.h"
88 #include "chrome/browser/ui/host_desktop.h"
89 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
90 #include "chrome/browser/ui/startup/default_browser_prompt.h"
91 #include "chrome/browser/ui/startup/startup_browser_creator.h"
92 #include "chrome/browser/ui/uma_browsing_activity_observer.h"
93 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
94 #include "chrome/common/chrome_constants.h"
95 #include "chrome/common/chrome_paths.h"
96 #include "chrome/common/chrome_result_codes.h"
97 #include "chrome/common/chrome_switches.h"
98 #include "chrome/common/chrome_version_info.h"
99 #include "chrome/common/crash_keys.h"
100 #include "chrome/common/env_vars.h"
101 #include "chrome/common/logging_chrome.h"
102 #include "chrome/common/net/net_resource_provider.h"
103 #include "chrome/common/pref_names.h"
104 #include "chrome/common/profiling.h"
105 #include "chrome/grit/generated_resources.h"
106 #include "chrome/installer/util/google_update_settings.h"
107 #include "components/component_updater/component_updater_service.h"
108 #include "components/device_event_log/device_event_log.h"
109 #include "components/google/core/browser/google_util.h"
110 #include "components/language_usage_metrics/language_usage_metrics.h"
111 #include "components/metrics/metrics_service.h"
112 #include "components/metrics/profiler/tracking_synchronizer.h"
113 #include "components/nacl/browser/nacl_browser.h"
114 #include "components/rappor/rappor_service.h"
115 #include "components/signin/core/common/profile_management_switches.h"
116 #include "components/startup_metric_utils/startup_metric_utils.h"
117 #include "components/translate/content/browser/browser_cld_utils.h"
118 #include "components/translate/content/common/cld_data_source.h"
119 #include "components/translate/core/browser/translate_download_manager.h"
120 #include "components/variations/net/variations_http_header_provider.h"
121 #include "content/public/browser/browser_thread.h"
122 #include "content/public/browser/notification_observer.h"
123 #include "content/public/browser/notification_registrar.h"
124 #include "content/public/browser/notification_service.h"
125 #include "content/public/browser/notification_types.h"
126 #include "content/public/browser/power_usage_monitor.h"
127 #include "content/public/browser/site_instance.h"
128 #include "content/public/common/content_client.h"
129 #include "content/public/common/content_switches.h"
130 #include "content/public/common/main_function_params.h"
131 #include "grit/platform_locale_settings.h"
132 #include "net/base/net_module.h"
133 #include "net/base/sdch_manager.h"
134 #include "net/cookies/cookie_monster.h"
135 #include "net/http/http_network_layer.h"
136 #include "net/http/http_stream_factory.h"
137 #include "net/url_request/url_request.h"
138 #include "ui/base/l10n/l10n_util.h"
139 #include "ui/base/layout.h"
140 #include "ui/base/resource/resource_bundle.h"
141 #include "ui/strings/grit/app_locale_settings.h"
143 #if defined(OS_ANDROID)
144 #include "chrome/browser/metrics/thread_watcher_android.h"
145 #else
146 #include "chrome/browser/feedback/feedback_profile_observer.h"
147 #endif
149 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
150 #include "chrome/browser/first_run/upgrade_util_linux.h"
151 #include "chrome/browser/sxs_linux.h"
152 #endif
154 #if defined(OS_CHROMEOS)
155 #include "chrome/browser/chromeos/settings/cros_settings.h"
156 #include "chromeos/chromeos_switches.h"
157 #include "chromeos/settings/cros_settings_names.h"
158 #endif
160 // TODO(port): several win-only methods have been pulled out of this, but
161 // BrowserMain() as a whole needs to be broken apart so that it's usable by
162 // other platforms. For now, it's just a stub. This is a serious work in
163 // progress and should not be taken as an indication of a real refactoring.
165 #if defined(OS_WIN)
166 #include "base/environment.h" // For PreRead experiment.
167 #include "base/win/windows_version.h"
168 #include "chrome/browser/browser_util_win.h"
169 #include "chrome/browser/chrome_browser_main_win.h"
170 #include "chrome/browser/chrome_select_file_dialog_factory_win.h"
171 #include "chrome/browser/component_updater/caps_installer_win.h"
172 #include "chrome/browser/component_updater/sw_reporter_installer_win.h"
173 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
174 #include "chrome/browser/first_run/upgrade_util_win.h"
175 #include "chrome/browser/ui/network_profile_bubble.h"
176 #include "chrome/installer/util/helper.h"
177 #include "chrome/installer/util/install_util.h"
178 #include "chrome/installer/util/shell_util.h"
179 #include "net/base/net_util.h"
180 #include "ui/base/l10n/l10n_util_win.h"
181 #include "ui/gfx/win/dpi.h"
182 #include "ui/shell_dialogs/select_file_dialog.h"
183 #endif // defined(OS_WIN)
185 #if defined(OS_MACOSX)
186 #include <Security/Security.h>
188 #include "base/mac/scoped_nsautorelease_pool.h"
189 #include "chrome/browser/mac/keystone_glue.h"
190 #endif
192 #if !defined(OS_IOS)
193 #include "chrome/browser/ui/app_modal/chrome_javascript_native_dialog_factory.h"
194 #endif
196 #if !defined(DISABLE_NACL)
197 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
198 #include "components/nacl/browser/nacl_process_host.h"
199 #endif
201 #if defined(ENABLE_EXTENSIONS)
202 #include "chrome/browser/extensions/startup_helper.h"
203 #include "extensions/browser/extension_protocols.h"
204 #include "extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.h"
205 #endif
207 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
208 #include "printing/printed_document.h"
209 #endif
211 #if defined(ENABLE_RLZ)
212 #include "chrome/browser/rlz/rlz.h"
213 #endif
215 #if defined(ENABLE_WEBRTC)
216 #include "chrome/browser/media/webrtc_log_util.h"
217 #endif
219 #if defined(USE_AURA)
220 #include "ui/aura/env.h"
221 #endif
223 using content::BrowserThread;
225 namespace {
227 // This function provides some ways to test crash and assertion handling
228 // behavior of the program.
229 void HandleTestParameters(const base::CommandLine& command_line) {
230 // This parameter causes a null pointer crash (crash reporter trigger).
231 if (command_line.HasSwitch(switches::kBrowserCrashTest)) {
232 int* bad_pointer = NULL;
233 *bad_pointer = 0;
237 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
238 void AddFirstRunNewTabs(StartupBrowserCreator* browser_creator,
239 const std::vector<GURL>& new_tabs) {
240 for (std::vector<GURL>::const_iterator it = new_tabs.begin();
241 it != new_tabs.end(); ++it) {
242 if (it->is_valid())
243 browser_creator->AddFirstRunTab(*it);
246 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
248 // Returns the new local state object, guaranteed non-NULL.
249 // |local_state_task_runner| must be a shutdown-blocking task runner.
250 PrefService* InitializeLocalState(
251 base::SequencedTaskRunner* local_state_task_runner,
252 const base::CommandLine& parsed_command_line) {
253 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
255 // Load local state. This includes the application locale so we know which
256 // locale dll to load. This also causes local state prefs to be registered.
257 PrefService* local_state = g_browser_process->local_state();
258 DCHECK(local_state);
260 #if defined(OS_WIN)
261 if (first_run::IsChromeFirstRun()) {
262 // During first run we read the google_update registry key to find what
263 // language the user selected when downloading the installer. This
264 // becomes our default language in the prefs.
265 // Other platforms obey the system locale.
266 base::string16 install_lang;
267 if (GoogleUpdateSettings::GetLanguage(&install_lang)) {
268 local_state->SetString(prefs::kApplicationLocale,
269 base::UTF16ToASCII(install_lang));
272 #endif // defined(OS_WIN)
274 // If the local state file for the current profile doesn't exist and the
275 // parent profile command line flag is present, then we should inherit some
276 // local state from the parent profile.
277 // Checking that the local state file for the current profile doesn't exist
278 // is the most robust way to determine whether we need to inherit or not
279 // since the parent profile command line flag can be present even when the
280 // current profile is not a new one, and in that case we do not want to
281 // inherit and reset the user's setting.
283 // TODO(mnissler): We should probably just instantiate a
284 // JSONPrefStore here instead of an entire PrefService. Once this is
285 // addressed, the call to browser_prefs::RegisterLocalState can move
286 // to chrome_prefs::CreateLocalState.
287 if (parsed_command_line.HasSwitch(switches::kParentProfile)) {
288 base::FilePath local_state_path;
289 PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path);
290 bool local_state_file_exists = base::PathExists(local_state_path);
291 if (!local_state_file_exists) {
292 base::FilePath parent_profile =
293 parsed_command_line.GetSwitchValuePath(switches::kParentProfile);
294 scoped_refptr<PrefRegistrySimple> registry = new PrefRegistrySimple();
295 scoped_ptr<PrefService> parent_local_state(
296 chrome_prefs::CreateLocalState(
297 parent_profile,
298 local_state_task_runner,
299 g_browser_process->policy_service(),
300 registry,
301 false));
302 registry->RegisterStringPref(prefs::kApplicationLocale, std::string());
303 // Right now, we only inherit the locale setting from the parent profile.
304 local_state->SetString(
305 prefs::kApplicationLocale,
306 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 base::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() &&
371 profile &&
372 !profile->IsGuestSession()) {
373 ProfileInfoCache& cache =
374 g_browser_process->profile_manager()->GetProfileInfoCache();
375 size_t profile_index = cache.GetIndexOfProfileWithPath(profile_path);
377 if (cache.ProfileIsSigninRequiredAtIndex(profile_index))
378 profile = g_browser_process->profile_manager()->GetProfile(
379 ProfileManager::GetGuestProfilePath());
381 #endif
382 if (profile) {
383 UMA_HISTOGRAM_LONG_TIMES(
384 "Startup.CreateFirstProfile", base::Time::Now() - start);
385 return profile;
388 #if !defined(OS_WIN)
389 // TODO(port): fix this. See comments near the definition of
390 // user_data_dir. It is better to CHECK-fail here than it is to
391 // silently exit because of missing code in the above test.
392 CHECK(profile) << "Cannot get default profile.";
393 #endif
395 return NULL;
398 #if defined(OS_MACOSX)
399 OSStatus KeychainCallback(SecKeychainEvent keychain_event,
400 SecKeychainCallbackInfo* info, void* context) {
401 return noErr;
403 #endif
405 void RegisterComponentsForUpdate() {
406 component_updater::ComponentUpdateService* cus =
407 g_browser_process->component_updater();
409 // Registration can be before or after cus->Start() so it is ok to post
410 // a task to the UI thread to do registration once you done the necessary
411 // file IO to know you existing component version.
412 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
413 RegisterRecoveryComponent(cus, g_browser_process->local_state());
414 RegisterPepperFlashComponent(cus);
415 RegisterSwiftShaderComponent(cus);
416 RegisterWidevineCdmComponent(cus);
417 #endif
419 #if !defined(DISABLE_NACL) && !defined(OS_ANDROID)
420 #if defined(OS_CHROMEOS)
421 // PNaCl on Chrome OS is on rootfs and there is no need to download it. But
422 // Chrome4ChromeOS on Linux doesn't contain PNaCl so enable component
423 // installer when running on Linux. See crbug.com/422121 for more details.
424 if (!base::SysInfo::IsRunningOnChromeOS())
425 #endif
426 g_browser_process->pnacl_component_installer()->RegisterPnaclComponent(cus);
427 #endif
429 // Registration of the CLD Component is a no-op unless the CLD data source has
430 // been configured to be the "Component" data source.
431 RegisterCldComponent(cus);
433 component_updater::SupervisedUserWhitelistInstaller* whitelist_installer =
434 g_browser_process->supervised_user_whitelist_installer();
435 whitelist_installer->RegisterComponents();
437 base::FilePath path;
438 if (PathService::Get(chrome::DIR_USER_DATA, &path)) {
439 #if defined(OS_ANDROID)
440 // The CRLSet component was enabled for some releases. This code attempts to
441 // delete it from the local disk of those how may have downloaded it.
442 g_browser_process->crl_set_fetcher()->DeleteFromDisk(path);
443 #elif !defined(OS_CHROMEOS)
444 // CRLSetFetcher attempts to load a CRL set from either the local disk or
445 // network.
446 // For Chrome OS this registration is delayed until user login.
447 g_browser_process->crl_set_fetcher()->StartInitialLoad(cus, path);
448 // Registration of the EV Whitelist component here is not necessary for:
449 // 1. Android: Because it currently does not have the EV indicator.
450 // 2. Chrome OS: On Chrome OS this registration is delayed until user login.
451 RegisterEVWhitelistComponent(cus, path);
452 #endif
455 #if defined(OS_WIN)
456 RegisterSwReporterComponent(cus, g_browser_process->local_state());
457 RegisterCAPSComponent(cus);
458 #endif
460 cus->Start();
463 #if !defined(OS_ANDROID)
464 bool ProcessSingletonNotificationCallback(
465 const base::CommandLine& command_line,
466 const base::FilePath& current_directory) {
467 // Drop the request if the browser process is already in shutdown path.
468 if (!g_browser_process || g_browser_process->IsShuttingDown())
469 return false;
471 if (command_line.HasSwitch(switches::kOriginalProcessStartTime)) {
472 std::string start_time_string =
473 command_line.GetSwitchValueASCII(switches::kOriginalProcessStartTime);
474 int64 remote_start_time;
475 if (base::StringToInt64(start_time_string, &remote_start_time)) {
476 base::TimeDelta elapsed =
477 base::Time::Now() - base::Time::FromInternalValue(remote_start_time);
478 if (command_line.HasSwitch(switches::kFastStart)) {
479 UMA_HISTOGRAM_LONG_TIMES(
480 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed);
481 } else {
482 UMA_HISTOGRAM_LONG_TIMES(
483 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed);
488 g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing(
489 command_line);
491 base::FilePath user_data_dir =
492 g_browser_process->profile_manager()->user_data_dir();
493 base::FilePath startup_profile_dir =
494 GetStartupProfilePath(user_data_dir, command_line);
496 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
497 command_line, current_directory, startup_profile_dir);
498 return true;
500 #endif // !defined(OS_ANDROID)
502 void LaunchDevToolsHandlerIfNeeded(const base::CommandLine& command_line) {
503 if (command_line.HasSwitch(::switches::kRemoteDebuggingPort)) {
504 std::string port_str =
505 command_line.GetSwitchValueASCII(::switches::kRemoteDebuggingPort);
506 int port;
507 if (base::StringToInt(port_str, &port) && port >= 0 && port < 65535) {
508 g_browser_process->CreateDevToolsHttpProtocolHandler(
509 chrome::HOST_DESKTOP_TYPE_NATIVE,
510 "127.0.0.1",
511 static_cast<uint16>(port));
512 } else {
513 DLOG(WARNING) << "Invalid http debugger port number " << port;
518 // Heap allocated class that listens for first page load, kicks off stat
519 // recording and then deletes itself.
520 class LoadCompleteListener : public content::NotificationObserver {
521 public:
522 LoadCompleteListener() {
523 registrar_.Add(this,
524 content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
525 content::NotificationService::AllSources());
527 ~LoadCompleteListener() override {}
529 // content::NotificationObserver implementation.
530 void Observe(int type,
531 const content::NotificationSource& source,
532 const content::NotificationDetails& details) override {
533 DCHECK_EQ(content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, type);
534 startup_metric_utils::OnInitialPageLoadComplete();
535 delete this;
538 private:
539 content::NotificationRegistrar registrar_;
540 DISALLOW_COPY_AND_ASSIGN(LoadCompleteListener);
543 } // namespace
545 namespace chrome_browser {
547 // This error message is not localized because we failed to load the
548 // localization data files.
549 #if defined(OS_WIN)
550 const char kMissingLocaleDataTitle[] = "Missing File Error";
551 #endif
553 #if defined(OS_WIN)
554 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
555 const char kMissingLocaleDataMessage[] =
556 "Unable to find locale data files. Please reinstall.";
557 #endif
559 } // namespace chrome_browser
561 // BrowserMainParts ------------------------------------------------------------
563 ChromeBrowserMainParts::ChromeBrowserMainParts(
564 const content::MainFunctionParams& parameters)
565 : parameters_(parameters),
566 parsed_command_line_(parameters.command_line),
567 result_code_(content::RESULT_CODE_NORMAL_EXIT),
568 startup_watcher_(new StartupTimeBomb()),
569 shutdown_watcher_(new ShutdownWatcherHelper()),
570 browser_field_trials_(parameters.command_line),
571 profile_(NULL),
572 run_message_loop_(true),
573 notify_result_(ProcessSingleton::PROCESS_NONE),
574 local_state_(NULL),
575 restart_last_session_(false) {
576 // If we're running tests (ui_task is non-null).
577 if (parameters.ui_task)
578 browser_defaults::enable_help_app = false;
580 // Chrome disallows cookies by default. All code paths that want to use
581 // cookies need to go through one of Chrome's URLRequestContexts which have
582 // a ChromeNetworkDelegate attached that selectively allows cookies again.
583 net::URLRequest::SetDefaultCookiePolicyToBlock();
586 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
587 for (int i = static_cast<int>(chrome_extra_parts_.size())-1; i >= 0; --i)
588 delete chrome_extra_parts_[i];
589 chrome_extra_parts_.clear();
592 // This will be called after the command-line has been mutated by about:flags
593 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
594 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
595 // Must initialize metrics after labs have been converted into switches,
596 // but before field trials are set up (so that client ID is available for
597 // one-time randomized field trials).
599 // Initialize FieldTrialList to support FieldTrials that use one-time
600 // randomization.
601 metrics::MetricsService* metrics = browser_process_->metrics_service();
602 field_trial_list_.reset(
603 new base::FieldTrialList(metrics->CreateEntropyProvider().release()));
605 const base::CommandLine* command_line =
606 base::CommandLine::ForCurrentProcess();
607 if (command_line->HasSwitch(switches::kEnableBenchmarking) ||
608 command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking)) {
609 base::FieldTrial::EnableBenchmarking();
612 // Ensure any field trials specified on the command line are initialized.
613 if (command_line->HasSwitch(switches::kForceFieldTrials)) {
614 std::set<std::string> unforceable_field_trials;
615 #if defined(OFFICIAL_BUILD)
616 unforceable_field_trials.insert("SettingsEnforcement");
617 #endif // defined(OFFICIAL_BUILD)
619 // Create field trials without activating them, so that this behaves in a
620 // consistent manner with field trials created from the server.
621 bool result = base::FieldTrialList::CreateTrialsFromString(
622 command_line->GetSwitchValueASCII(switches::kForceFieldTrials),
623 base::FieldTrialList::DONT_ACTIVATE_TRIALS,
624 unforceable_field_trials);
625 CHECK(result) << "Invalid --" << switches::kForceFieldTrials
626 << " list specified.";
628 if (command_line->HasSwitch(switches::kForceVariationIds)) {
629 // Create default variation ids which will always be included in the
630 // X-Client-Data request header.
631 variations::VariationsHttpHeaderProvider* provider =
632 variations::VariationsHttpHeaderProvider::GetInstance();
633 bool result = provider->SetDefaultVariationIds(
634 command_line->GetSwitchValueASCII(switches::kForceVariationIds));
635 CHECK(result) << "Invalid --" << switches::kForceVariationIds
636 << " list specified.";
637 metrics->AddSyntheticTrialObserver(provider);
639 chrome_variations::VariationsService* variations_service =
640 browser_process_->variations_service();
641 if (variations_service)
642 variations_service->CreateTrialsFromSeed();
644 // This must be called after |local_state_| is initialized.
645 browser_field_trials_.SetupFieldTrials(
646 base::Time::FromTimeT(metrics->GetInstallDate()), local_state_);
648 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
649 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
650 // Even though base::Bind does AddRef and Release, the object will not be
651 // deleted after the Task is executed.
652 field_trial_synchronizer_ = new FieldTrialSynchronizer();
654 // Now that field trials have been created, initializes metrics recording.
655 metrics->InitializeMetricsRecordingState();
657 // Enable profiler instrumentation depending on the channel.
658 switch (chrome::VersionInfo::GetChannel()) {
659 case chrome::VersionInfo::CHANNEL_UNKNOWN:
660 case chrome::VersionInfo::CHANNEL_CANARY:
661 tracked_objects::ScopedTracker::Enable();
662 break;
664 case chrome::VersionInfo::CHANNEL_DEV:
665 case chrome::VersionInfo::CHANNEL_BETA:
666 case chrome::VersionInfo::CHANNEL_STABLE:
667 // Don't enable instrumentation.
668 break;
672 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
674 void ChromeBrowserMainParts::StartMetricsRecording() {
675 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
677 g_browser_process->metrics_service()->CheckForClonedInstall(
678 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
680 g_browser_process->GetMetricsServicesManager()->UpdateUploadPermissions(true);
683 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
684 // Don't record any metrics if UI was displayed before this point e.g.
685 // warning dialogs.
686 if (startup_metric_utils::WasNonBrowserUIDisplayed())
687 return;
689 #if defined(OS_ANDROID)
690 // On Android the first run is handled in Java code, and the C++ side of
691 // Chrome doesn't know if this is the first run. This will cause some
692 // inaccuracy in the UMA statistics, but this should be minor (first runs are
693 // rare).
694 bool is_first_run = false;
695 #else
696 bool is_first_run = first_run::IsChromeFirstRun();
697 #endif
699 // CurrentProcessInfo::CreationTime() is currently only implemented on some
700 // platforms.
701 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
702 const base::Time process_creation_time =
703 base::CurrentProcessInfo::CreationTime();
705 if (!is_first_run && !process_creation_time.is_null()) {
706 base::TimeDelta delay = base::Time::Now() - process_creation_time;
707 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserMessageLoopStartTime", delay);
709 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
711 // Record collected startup metrics.
712 startup_metric_utils::OnBrowserStartupComplete(is_first_run);
714 // Deletes self.
715 new LoadCompleteListener();
718 // -----------------------------------------------------------------------------
719 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
721 #if defined(OS_WIN)
722 #define DLLEXPORT __declspec(dllexport)
724 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
725 extern "C" {
726 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded();
729 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
730 // Need an instance of AtExitManager to handle singleton creations and
731 // deletions. We need this new instance because, the old instance created
732 // in ChromeMain() got destructed when the function returned.
733 base::AtExitManager exit_manager;
734 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
736 #endif
738 // content::BrowserMainParts implementation ------------------------------------
740 void ChromeBrowserMainParts::PreEarlyInitialization() {
741 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
742 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
743 chrome_extra_parts_[i]->PreEarlyInitialization();
746 void ChromeBrowserMainParts::PostEarlyInitialization() {
747 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
748 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
749 chrome_extra_parts_[i]->PostEarlyInitialization();
752 void ChromeBrowserMainParts::ToolkitInitialized() {
753 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
754 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
755 chrome_extra_parts_[i]->ToolkitInitialized();
758 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
759 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
761 device_event_log::Initialize(0 /* default max entries */);
763 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
764 chrome_extra_parts_[i]->PreMainMessageLoopStart();
767 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
768 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
769 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
770 chrome_extra_parts_[i]->PostMainMessageLoopStart();
773 int ChromeBrowserMainParts::PreCreateThreads() {
774 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
775 result_code_ = PreCreateThreadsImpl();
777 if (result_code_ == content::RESULT_CODE_NORMAL_EXIT) {
778 #if !defined(OS_ANDROID)
779 // These members must be initialized before exiting this function normally.
780 DCHECK(master_prefs_.get());
781 DCHECK(browser_creator_.get());
782 #endif
783 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
784 chrome_extra_parts_[i]->PreCreateThreads();
787 return result_code_;
790 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
791 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
792 run_message_loop_ = false;
793 #if !defined(OS_ANDROID)
794 chrome::MaybeShowInvalidUserDataDirWarningDialog();
795 #endif
796 if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir_))
797 return chrome::RESULT_CODE_MISSING_DATA;
799 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
800 MediaCaptureDevicesDispatcher::GetInstance();
802 // Android's first run is done in Java instead of native.
803 #if !defined(OS_ANDROID)
804 process_singleton_.reset(new ChromeProcessSingleton(
805 user_data_dir_, base::Bind(&ProcessSingletonNotificationCallback)));
807 // Cache first run state early.
808 first_run::IsChromeFirstRun();
809 #endif
811 scoped_refptr<base::SequencedTaskRunner> local_state_task_runner =
812 JsonPrefStore::GetTaskRunnerForFile(
813 base::FilePath(chrome::kLocalStorePoolName),
814 BrowserThread::GetBlockingPool());
817 TRACE_EVENT0("startup",
818 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
819 browser_process_.reset(new BrowserProcessImpl(local_state_task_runner.get(),
820 parsed_command_line()));
823 if (parsed_command_line().HasSwitch(switches::kEnableProfiling)) {
824 TRACE_EVENT0("startup",
825 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
826 // User wants to override default tracking status.
827 std::string flag =
828 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling);
829 // Default to basic profiling (no parent child support).
830 tracked_objects::ThreadData::Status status =
831 tracked_objects::ThreadData::PROFILING_ACTIVE;
832 if (flag.compare("0") != 0)
833 status = tracked_objects::ThreadData::DEACTIVATED;
834 else if (flag.compare("child") != 0)
835 status = tracked_objects::ThreadData::PROFILING_CHILDREN_ACTIVE;
836 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status);
839 if (parsed_command_line().HasSwitch(switches::kProfilingOutputFile)) {
840 tracking_objects_.set_output_file_path(
841 parsed_command_line().GetSwitchValuePath(
842 switches::kProfilingOutputFile));
845 local_state_ = InitializeLocalState(
846 local_state_task_runner.get(), parsed_command_line());
848 #if !defined(OS_ANDROID)
849 // These members must be initialized before returning from this function.
850 master_prefs_.reset(new first_run::MasterPrefs);
851 // Android doesn't use StartupBrowserCreator.
852 browser_creator_.reset(new StartupBrowserCreator);
853 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
854 chrome::UMABrowsingActivityObserver::Init();
855 #endif
857 #if !defined(OS_CHROMEOS)
858 // Convert active labs into switches. This needs to be done before
859 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
860 // affected by experiment flags (--touch-optimized-ui in particular).
861 // On ChromeOS system level flags are applied from the device settings from
862 // the session manager.
864 TRACE_EVENT0("startup",
865 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
866 about_flags::PrefServiceFlagsStorage flags_storage_(
867 g_browser_process->local_state());
868 about_flags::ConvertFlagsToSwitches(&flags_storage_,
869 base::CommandLine::ForCurrentProcess(),
870 about_flags::kAddSentinels);
872 #endif
874 local_state_->UpdateCommandLinePrefStore(
875 new CommandLinePrefStore(base::CommandLine::ForCurrentProcess()));
877 // Reset the command line in the crash report details, since we may have
878 // just changed it to include experiments.
879 crash_keys::SetSwitchesFromCommandLine(
880 base::CommandLine::ForCurrentProcess());
882 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
883 // needed when loading the MainMenu.nib and the language doesn't depend on
884 // anything since it comes from Cocoa.
885 #if defined(OS_MACOSX)
886 std::string locale =
887 parameters().ui_task ? "en-US" : l10n_util::GetLocaleOverride();
888 browser_process_->SetApplicationLocale(locale);
889 #else
890 const std::string locale =
891 local_state_->GetString(prefs::kApplicationLocale);
893 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
894 // method InitSharedInstance is ignored.
896 TRACE_EVENT_BEGIN0("startup",
897 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
898 const std::string loaded_locale =
899 ui::ResourceBundle::InitSharedInstanceWithLocale(
900 locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
901 TRACE_EVENT_END0("startup",
902 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
904 if (loaded_locale.empty() &&
905 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs)) {
906 ShowMissingLocaleMessageBox();
907 return chrome::RESULT_CODE_MISSING_DATA;
909 CHECK(!loaded_locale.empty()) << "Locale could not be found for " << locale;
910 browser_process_->SetApplicationLocale(loaded_locale);
912 base::FilePath resources_pack_path;
913 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
915 TRACE_EVENT0("startup",
916 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
917 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
918 resources_pack_path, ui::SCALE_FACTOR_NONE);
920 #endif // defined(OS_MACOSX)
922 // Android does first run in Java instead of native.
923 // Chrome OS has its own out-of-box-experience code.
924 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
925 // On first run, we need to process the predictor preferences before the
926 // browser's profile_manager object is created, but after ResourceBundle
927 // is initialized.
928 if (first_run::IsChromeFirstRun()) {
929 first_run::ProcessMasterPreferencesResult pmp_result =
930 first_run::ProcessMasterPreferences(user_data_dir_,
931 master_prefs_.get());
932 if (pmp_result == first_run::EULA_EXIT_NOW)
933 return chrome::RESULT_CODE_EULA_REFUSED;
935 if (!parsed_command_line().HasSwitch(switches::kApp) &&
936 !parsed_command_line().HasSwitch(switches::kAppId) &&
937 !parsed_command_line().HasSwitch(switches::kShowAppList)) {
938 AddFirstRunNewTabs(browser_creator_.get(), master_prefs_->new_tabs);
941 // TODO(macourteau): refactor preferences that are copied from
942 // master_preferences into local_state, as a "local_state" section in
943 // master preferences. If possible, a generic solution would be preferred
944 // over a copy one-by-one of specific preferences. Also see related TODO
945 // in first_run.h.
947 // Store the initial VariationsService seed in local state, if it exists
948 // in master prefs.
949 if (!master_prefs_->variations_seed.empty() ||
950 !master_prefs_->compressed_variations_seed.empty()) {
951 if (!master_prefs_->variations_seed.empty()) {
952 local_state_->SetString(prefs::kVariationsSeed,
953 master_prefs_->variations_seed);
955 if (!master_prefs_->compressed_variations_seed.empty()) {
956 local_state_->SetString(prefs::kVariationsCompressedSeed,
957 master_prefs_->compressed_variations_seed);
959 if (!master_prefs_->variations_seed_signature.empty()) {
960 local_state_->SetString(prefs::kVariationsSeedSignature,
961 master_prefs_->variations_seed_signature);
963 // Set the variation seed date to the current system time. If the user's
964 // clock is incorrect, this may cause some field trial expiry checks to
965 // not do the right thing until the next seed update from the server,
966 // when this value will be updated.
967 local_state_->SetInt64(prefs::kVariationsSeedDate,
968 base::Time::Now().ToInternalValue());
971 if (!master_prefs_->suppress_default_browser_prompt_for_version.empty()) {
972 local_state_->SetString(
973 prefs::kBrowserSuppressDefaultBrowserPrompt,
974 master_prefs_->suppress_default_browser_prompt_for_version);
977 #endif
979 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
980 // Set the product channel for crash reports.
981 base::debug::SetCrashKeyValue(crash_keys::kChannel,
982 chrome::VersionInfo::GetVersionStringModifier());
983 #endif
985 // Initialize tracking synchronizer system.
986 tracking_synchronizer_ = new metrics::TrackingSynchronizer();
988 #if defined(OS_MACOSX)
989 // Get the Keychain API to register for distributed notifications on the main
990 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
991 // which doesn't. This ensures those notifications will get delivered
992 // properly. See issue 37766.
993 // (Note that the callback mask here is empty. I don't want to register for
994 // any callbacks, I just want to initialize the mechanism.)
995 SecKeychainAddCallback(&KeychainCallback, 0, NULL);
996 #endif
998 #if defined(OS_CHROMEOS)
999 // Must be done after g_browser_process is constructed, before
1000 // SetupMetricsAndFieldTrials().
1001 chromeos::CrosSettings::Initialize();
1002 #endif
1004 // Now the command line has been mutated based on about:flags, we can setup
1005 // metrics and initialize field trials. The field trials are needed by
1006 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
1007 SetupMetricsAndFieldTrials();
1009 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
1010 browser_process_->PreCreateThreads();
1012 return content::RESULT_CODE_NORMAL_EXIT;
1015 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
1016 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1017 result_code_ = PreMainMessageLoopRunImpl();
1019 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1020 chrome_extra_parts_[i]->PreMainMessageLoopRun();
1023 // PreMainMessageLoopRun calls these extra stages in the following order:
1024 // PreMainMessageLoopRunImpl()
1025 // ... initial setup, including browser_process_ setup.
1026 // PreProfileInit()
1027 // ... additional setup, including CreateProfile()
1028 // PostProfileInit()
1029 // ... additional setup
1030 // PreBrowserStart()
1031 // ... browser_creator_->Start (OR parameters().ui_task->Run())
1032 // PostBrowserStart()
1034 void ChromeBrowserMainParts::PreProfileInit() {
1035 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1037 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1038 chrome_extra_parts_[i]->PreProfileInit();
1040 #if !defined(OS_ANDROID)
1041 // Initialize the feedback uploader so it can setup notifications for profile
1042 // creation.
1043 feedback::FeedbackProfileObserver::Initialize();
1045 ProfileManager* profile_manager = g_browser_process->profile_manager();
1047 // First check if any ephemeral profiles are left behind because of browser
1048 // crash and schedule them for deletion and then proceed with getting the set
1049 // of profiles to open.
1050 ProfileInfoCache& profile_cache = profile_manager->GetProfileInfoCache();
1051 size_t profiles_count = profile_cache.GetNumberOfProfiles();
1052 std::vector<base::FilePath> profiles_to_delete;
1053 for (size_t i = 0; i < profiles_count; ++i) {
1054 if (profile_cache.ProfileIsEphemeralAtIndex(i))
1055 profiles_to_delete.push_back(profile_cache.GetPathOfProfileAtIndex(i));
1058 if (profiles_to_delete.size()) {
1059 for (size_t i = 0; i < profiles_to_delete.size(); ++i) {
1060 profile_manager->ScheduleProfileForDeletion(
1061 profiles_to_delete[i], ProfileManager::CreateCallback());
1063 // Clean up stale profiles immediately after browser start.
1064 BrowserThread::PostTask(
1065 BrowserThread::FILE, FROM_HERE,
1066 base::Bind(&ProfileManager::CleanUpStaleProfiles, profiles_to_delete));
1068 #endif // OS_ANDROID
1070 #if defined(ENABLE_EXTENSIONS)
1071 javascript_dialog_extensions_client::InstallClient();
1072 #endif
1074 #if !defined(OS_IOS)
1075 InstallChromeJavaScriptNativeDialogFactory();
1076 #endif
1079 void ChromeBrowserMainParts::PostProfileInit() {
1080 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1081 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1082 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1083 chrome_extra_parts_[i]->PostProfileInit();
1086 void ChromeBrowserMainParts::PreBrowserStart() {
1087 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1088 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1089 chrome_extra_parts_[i]->PreBrowserStart();
1091 three_d_observer_.reset(new ThreeDAPIObserver());
1094 void ChromeBrowserMainParts::PostBrowserStart() {
1095 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1096 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1097 chrome_extra_parts_[i]->PostBrowserStart();
1098 #if !defined(OS_ANDROID)
1099 // Allow ProcessSingleton to process messages.
1100 process_singleton_->Unlock();
1101 #endif
1102 #if defined(ENABLE_WEBRTC)
1103 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1104 // to reduce the impact on startup time.
1105 BrowserThread::PostDelayedTask(
1106 BrowserThread::UI,
1107 FROM_HERE,
1108 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles),
1109 base::TimeDelta::FromMinutes(1));
1110 #endif
1113 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1114 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1115 SCOPED_UMA_HISTOGRAM_LONG_TIMER("Startup.PreMainMessageLoopRunImplLongTime");
1116 // Android updates the metrics service dynamically depending on whether the
1117 // application is in the foreground or not. Do not start here.
1118 #if !defined(OS_ANDROID)
1119 // Now that the file thread has been started, start recording.
1120 StartMetricsRecording();
1121 #endif
1123 if (!base::debug::BeingDebugged()) {
1124 // Create watchdog thread after creating all other threads because it will
1125 // watch the other threads and they must be running.
1126 browser_process_->watchdog_thread();
1129 // Do any initializating in the browser process that requires all threads
1130 // running.
1131 browser_process_->PreMainMessageLoopRun();
1133 // Record last shutdown time into a histogram.
1134 browser_shutdown::ReadLastShutdownInfo();
1136 #if defined(OS_WIN)
1137 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1138 // tasks. Those care whether the browser is already running. On Linux/Mac,
1139 // upgrade/uninstall happen separately.
1140 bool already_running = browser_util::IsBrowserAlreadyRunning();
1142 // If the command line specifies 'uninstall' then we need to work here
1143 // unless we detect another chrome browser running.
1144 if (parsed_command_line().HasSwitch(switches::kUninstall)) {
1145 return DoUninstallTasks(already_running);
1148 if (parsed_command_line().HasSwitch(switches::kHideIcons) ||
1149 parsed_command_line().HasSwitch(switches::kShowIcons)) {
1150 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1151 parsed_command_line_);
1154 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
1155 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
1156 #endif
1158 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser)) {
1159 return ShellIntegration::SetAsDefaultBrowser() ?
1160 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT) :
1161 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED);
1164 #if defined(USE_AURA)
1165 // Make sure aura::Env has been initialized.
1166 CHECK(aura::Env::GetInstance());
1167 #endif
1169 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1170 #if !defined(OS_ANDROID)
1171 // If the command line specifies --pack-extension, attempt the pack extension
1172 // startup action and exit.
1173 if (parsed_command_line().HasSwitch(switches::kPackExtension)) {
1174 extensions::StartupHelper extension_startup_helper;
1175 if (extension_startup_helper.PackExtension(parsed_command_line()))
1176 return content::RESULT_CODE_NORMAL_EXIT;
1177 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR;
1180 // If we're being launched just to check the connector policy, we are
1181 // short-lived and don't want to be passing that switch off.
1182 bool pass_command_line = !parsed_command_line().HasSwitch(
1183 switches::kCheckCloudPrintConnectorPolicy);
1185 if (pass_command_line) {
1186 // When another process is running, use that process instead of starting a
1187 // new one. NotifyOtherProcess will currently give the other process up to
1188 // 20 seconds to respond. Note that this needs to be done before we attempt
1189 // to read the profile.
1190 notify_result_ = process_singleton_->NotifyOtherProcessOrCreate();
1191 switch (notify_result_) {
1192 case ProcessSingleton::PROCESS_NONE:
1193 // No process already running, fall through to starting a new one.
1194 break;
1196 case ProcessSingleton::PROCESS_NOTIFIED:
1197 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1198 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1199 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER))).c_str());
1200 #endif
1201 // Having a differentiated return type for testing allows for tests to
1202 // verify proper handling of some switches. When not testing, stick to
1203 // the standard Unix convention of returning zero when things went as
1204 // expected.
1205 if (parsed_command_line().HasSwitch(switches::kTestType))
1206 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED;
1207 return content::RESULT_CODE_NORMAL_EXIT;
1209 case ProcessSingleton::PROFILE_IN_USE:
1210 return chrome::RESULT_CODE_PROFILE_IN_USE;
1212 case ProcessSingleton::LOCK_ERROR:
1213 LOG(ERROR) << "Failed to create a ProcessSingleton for your profile "
1214 "directory. This means that running multiple instances "
1215 "would start multiple browser processes rather than "
1216 "opening a new window in the existing process. Aborting "
1217 "now to avoid profile corruption.";
1218 return chrome::RESULT_CODE_PROFILE_IN_USE;
1220 default:
1221 NOTREACHED();
1224 #endif // !defined(OS_ANDROID)
1226 // Handle special early return paths (which couldn't be processed even earlier
1227 // as they require the process singleton to be held) first.
1229 std::string try_chrome =
1230 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain);
1231 if (!try_chrome.empty()) {
1232 #if defined(OS_WIN)
1233 // Setup.exe has determined that we need to run a retention experiment
1234 // and has lauched chrome to show the experiment UI. It is guaranteed that
1235 // no other Chrome is currently running as the process singleton was
1236 // sucessfully grabbed above.
1237 int try_chrome_int;
1238 base::StringToInt(try_chrome, &try_chrome_int);
1239 TryChromeDialogView::Result answer = TryChromeDialogView::Show(
1240 try_chrome_int,
1241 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog,
1242 base::Unretained(process_singleton_.get())));
1243 if (answer == TryChromeDialogView::NOT_NOW)
1244 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL;
1245 if (answer == TryChromeDialogView::UNINSTALL_CHROME)
1246 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2;
1247 // At this point the user is willing to try chrome again.
1248 if (answer == TryChromeDialogView::TRY_CHROME_AS_DEFAULT) {
1249 // Only set in the unattended case, the interactive case is Windows 8.
1250 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1251 ShellIntegration::SET_DEFAULT_UNATTENDED)
1252 ShellIntegration::SetAsDefaultBrowser();
1254 #else
1255 // We don't support retention experiments on Mac or Linux.
1256 return content::RESULT_CODE_NORMAL_EXIT;
1257 #endif // defined(OS_WIN)
1260 #if defined(OS_WIN)
1261 // Do the tasks if chrome has been upgraded while it was last running.
1262 if (!already_running && upgrade_util::DoUpgradeTasks(parsed_command_line()))
1263 return content::RESULT_CODE_NORMAL_EXIT;
1265 // Check if there is any machine level Chrome installed on the current
1266 // machine. If yes and the current Chrome process is user level, we do not
1267 // allow the user level Chrome to run. So we notify the user and uninstall
1268 // user level Chrome.
1269 // Note this check needs to happen here (after the process singleton was
1270 // obtained but before potentially creating the first run sentinel).
1271 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1272 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS;
1273 #endif // defined(OS_WIN)
1275 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1276 if (sxs_linux::ShouldMigrateUserDataDir())
1277 return sxs_linux::MigrateUserDataDir();
1278 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1280 // Desktop construction occurs here, (required before profile creation).
1281 PreProfileInit();
1283 // Profile creation ----------------------------------------------------------
1285 metrics::MetricsService::SetExecutionPhase(
1286 metrics::MetricsService::CREATE_PROFILE,
1287 g_browser_process->local_state());
1288 profile_ = CreatePrimaryProfile(parameters(),
1289 user_data_dir_,
1290 parsed_command_line());
1291 if (!profile_)
1292 return content::RESULT_CODE_NORMAL_EXIT;
1294 #if !defined(OS_ANDROID)
1295 // The first run sentinel must be created after the process singleton was
1296 // grabbed and no early return paths were otherwise hit above.
1297 first_run::CreateSentinelIfNeeded();
1298 #endif // !defined(OS_ANDROID)
1300 #if defined(ENABLE_BACKGROUND)
1301 // Autoload any profiles which are running background apps.
1302 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1303 browser_process_->profile_manager()->AutoloadProfiles();
1304 #endif
1305 // Post-profile init ---------------------------------------------------------
1307 TranslateService::Initialize();
1309 // Needs to be done before PostProfileInit, since login manager on CrOS is
1310 // called inside PostProfileInit.
1311 content::WebUIControllerFactory::RegisterFactory(
1312 ChromeWebUIControllerFactory::GetInstance());
1314 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1315 // So make sure to create it before that.
1316 #if !defined(DISABLE_NACL)
1317 NaClBrowserDelegateImpl* delegate =
1318 new NaClBrowserDelegateImpl(browser_process_->profile_manager());
1319 nacl::NaClBrowser::SetDelegate(delegate);
1320 #endif
1322 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1323 // (requires supporting early exit).
1324 PostProfileInit();
1326 // Retrieve cached GL strings from local state and use them for GPU
1327 // blacklist decisions.
1328 if (g_browser_process->gl_string_manager())
1329 g_browser_process->gl_string_manager()->Initialize();
1331 // Create an instance of GpuModeManager to watch gpu mode pref change.
1332 g_browser_process->gpu_mode_manager();
1334 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1335 // Show the First Run UI if this is the first time Chrome has been run on
1336 // this computer, or we're being compelled to do so by a command line flag.
1337 // Note that this be done _after_ the PrefService is initialized and all
1338 // preferences are registered, since some of the code that the importer
1339 // touches reads preferences.
1340 if (first_run::IsChromeFirstRun()) {
1341 first_run::AutoImport(profile_,
1342 master_prefs_->homepage_defined,
1343 master_prefs_->do_import_items,
1344 master_prefs_->dont_import_items,
1345 master_prefs_->import_bookmarks_path);
1347 // Note: this can pop the first run consent dialog on linux.
1348 first_run::DoPostImportTasks(profile_,
1349 master_prefs_->make_chrome_default_for_user);
1351 if (!master_prefs_->suppress_first_run_default_browser_prompt) {
1352 browser_creator_->set_show_main_browser_window(
1353 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_));
1354 } else {
1355 browser_creator_->set_is_default_browser_dialog_suppressed(true);
1358 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1360 #if defined(OS_WIN)
1361 // Sets things up so that if we crash from this point on, a dialog will
1362 // popup asking the user to restart chrome. It is done this late to avoid
1363 // testing against a bunch of special cases that are taken care early on.
1364 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1365 parsed_command_line());
1367 // Registers Chrome with the Windows Restart Manager, which will restore the
1368 // Chrome session when the computer is restarted after a system update.
1369 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1370 // but should run on startup if extended to handle crashes/hangs/patches.
1371 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1372 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
1373 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1374 parsed_command_line());
1377 // Verify that the profile is not on a network share and if so prepare to show
1378 // notification to the user.
1379 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_)) {
1380 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
1381 base::Bind(&NetworkProfileBubble::CheckNetworkProfile,
1382 profile_->GetPath()));
1384 #endif // OS_WIN
1386 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1387 // Init the RLZ library. This just binds the dll and schedules a task on the
1388 // file thread to be run sometime later. If this is the first run we record
1389 // the installation event.
1390 PrefService* pref_service = profile_->GetPrefs();
1391 int ping_delay = first_run::IsChromeFirstRun() ? master_prefs_->ping_delay :
1392 pref_service->GetInteger(first_run::GetPingDelayPrefName().c_str());
1393 // Negative ping delay means to send ping immediately after a first search is
1394 // recorded.
1395 RLZTracker::InitRlzFromProfileDelayed(
1396 profile_, first_run::IsChromeFirstRun(), ping_delay < 0,
1397 base::TimeDelta::FromMilliseconds(abs(ping_delay)));
1398 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1400 // Configure modules that need access to resources.
1401 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider);
1403 // In unittest mode, this will do nothing. In normal mode, this will create
1404 // the global IntranetRedirectDetector instance, which will promptly go to
1405 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1406 // to see if it should do anything else.
1408 // A simpler way of doing all this would be to have some function which could
1409 // give the time elapsed since startup, and simply have this object check that
1410 // when asked to initialize itself, but this doesn't seem to exist.
1412 // This can't be created in the BrowserProcessImpl constructor because it
1413 // needs to read prefs that get set after that runs.
1414 browser_process_->intranet_redirect_detector();
1415 GoogleSearchCounter::RegisterForNotifications();
1417 // Check SDCH field trial. Default is now that everything is enabled,
1418 // so provide options for disabling HTTPS or all of SDCH.
1419 const char kSdchFieldTrialName[] = "SDCH";
1420 const char kEnabledHttpOnlyGroupName[] = "EnabledHttpOnly";
1421 const char kDisabledAllGroupName[] = "DisabledAll";
1423 // Store in a string on return to keep underlying storage for
1424 // StringPiece stable.
1425 std::string sdch_trial_group_string =
1426 base::FieldTrialList::FindFullName(kSdchFieldTrialName);
1427 base::StringPiece sdch_trial_group(sdch_trial_group_string);
1428 if (sdch_trial_group.starts_with(kEnabledHttpOnlyGroupName)) {
1429 net::SdchManager::EnableSdchSupport(true);
1430 net::SdchManager::EnableSecureSchemeSupport(false);
1431 } else if (sdch_trial_group.starts_with(kDisabledAllGroupName)) {
1432 net::SdchManager::EnableSdchSupport(false);
1435 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1436 if (parsed_command_line().HasSwitch(switches::kDebugPrint)) {
1437 base::FilePath path =
1438 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint);
1439 printing::PrintedDocument::set_debug_dump_path(path);
1441 #endif
1443 HandleTestParameters(parsed_command_line());
1444 browser_process_->metrics_service()->RecordBreakpadHasDebugger(
1445 base::debug::BeingDebugged());
1447 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1448 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1449 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1450 browser_process_->GetApplicationLocale());
1452 // Start watching for hangs during startup. We disarm this hang detector when
1453 // ThreadWatcher takes over or when browser is shutdown or when
1454 // startup_watcher_ is deleted.
1455 metrics::MetricsService::SetExecutionPhase(
1456 metrics::MetricsService::STARTUP_TIMEBOMB_ARM,
1457 g_browser_process->local_state());
1458 startup_watcher_->Arm(base::TimeDelta::FromSeconds(600));
1460 // On mobile, need for clean shutdown arises only when the application comes
1461 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1462 // http://crbug.com/179143
1463 #if !defined(OS_ANDROID)
1464 // Start watching for a hang.
1465 browser_process_->metrics_service()->LogNeedForCleanShutdown();
1466 #endif
1468 #if defined(ENABLE_PRINT_PREVIEW)
1469 // Create the instance of the cloud print proxy service so that it can launch
1470 // the service process if needed. This is needed because the service process
1471 // might have shutdown because an update was available.
1472 // TODO(torne): this should maybe be done with
1473 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1474 // instead?
1475 CloudPrintProxyServiceFactory::GetForProfile(profile_);
1476 #endif
1478 // Start watching all browser threads for responsiveness.
1479 metrics::MetricsService::SetExecutionPhase(
1480 metrics::MetricsService::THREAD_WATCHER_START,
1481 g_browser_process->local_state());
1482 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1484 #if defined(OS_ANDROID)
1485 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1486 #endif
1488 #if !defined(DISABLE_NACL)
1489 BrowserThread::PostTask(
1490 BrowserThread::IO,
1491 FROM_HERE,
1492 base::Bind(nacl::NaClProcessHost::EarlyStartup));
1493 #endif
1495 // Make sure initial prefs are recorded
1496 PrefMetricsService::Factory::GetForProfile(profile_);
1498 PreBrowserStart();
1500 // Instantiate the notification UI manager, as this triggers a perf timer
1501 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1502 // triggering the timer and call that explicitly in the approprate place.
1503 // http://crbug.com/105065.
1504 browser_process_->notification_ui_manager();
1506 // This must be called prior to RegisterComponentsForUpdate, in case the CLD
1507 // data source is based on the Component Updater.
1508 translate::BrowserCldUtils::ConfigureDefaultDataProvider();
1510 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate))
1511 RegisterComponentsForUpdate();
1513 #if defined(OS_ANDROID)
1514 chrome_variations::VariationsService* variations_service =
1515 browser_process_->variations_service();
1516 if (variations_service) {
1517 // Just initialize the policy prefs service here. Variations seed fetching
1518 // will be initialized when the app enters foreground mode.
1519 variations_service->set_policy_pref_service(profile_->GetPrefs());
1521 translate::TranslateDownloadManager::RequestLanguageList(
1522 profile_->GetPrefs());
1524 #else
1525 // Most general initialization is behind us, but opening a
1526 // tab and/or session restore and such is still to be done.
1527 base::TimeTicks browser_open_start = base::TimeTicks::Now();
1529 // We are in regular browser boot sequence. Open initial tabs and enter the
1530 // main message loop.
1531 #if defined(OS_CHROMEOS)
1532 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1533 // them this early as the cryptohome hasn't yet been mounted (which happens
1534 // only once we log in.
1535 std::vector<Profile*> last_opened_profiles;
1536 #else
1537 std::vector<Profile*> last_opened_profiles =
1538 g_browser_process->profile_manager()->GetLastOpenedProfiles();
1539 #endif
1541 if (browser_creator_->Start(parsed_command_line(), base::FilePath(),
1542 profile_, last_opened_profiles)) {
1543 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1544 // Initialize autoupdate timer. Timer callback costs basically nothing
1545 // when browser is not in persistent mode, so it's OK to let it ride on
1546 // the main thread. This needs to be done here because we don't want
1547 // to start the timer when Chrome is run inside a test harness.
1548 browser_process_->StartAutoupdateTimer();
1549 #endif
1551 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1552 // On Linux, the running exe will be updated if an upgrade becomes
1553 // available while the browser is running. We need to save the last
1554 // modified time of the exe, so we can compare to determine if there is
1555 // an upgrade while the browser is kept alive by a persistent extension.
1556 upgrade_util::SaveLastModifiedTimeOfExe();
1557 #endif
1559 // Record now as the last successful chrome start.
1560 GoogleUpdateSettings::SetLastRunTime();
1562 #if defined(OS_MACOSX)
1563 // Call Recycle() here as late as possible, before going into the loop
1564 // because Start() will add things to it while creating the main window.
1565 if (parameters().autorelease_pool)
1566 parameters().autorelease_pool->Recycle();
1567 #endif
1569 base::TimeDelta delay = base::TimeTicks::Now() - browser_open_start;
1570 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserOpenTabs", delay);
1572 // If we're running tests (ui_task is non-null), then we don't want to
1573 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or
1574 // RequestLanguageList
1575 if (parameters().ui_task == NULL) {
1576 // Request new variations seed information from server.
1577 chrome_variations::VariationsService* variations_service =
1578 browser_process_->variations_service();
1579 if (variations_service) {
1580 variations_service->StartRepeatedVariationsSeedFetch();
1582 #if defined(OS_WIN)
1583 variations_service->StartGoogleUpdateRegistrySync();
1584 #endif
1587 translate::TranslateDownloadManager::RequestLanguageList(
1588 profile_->GetPrefs());
1591 run_message_loop_ = true;
1592 } else {
1593 run_message_loop_ = false;
1595 browser_creator_.reset();
1597 #if !defined(OS_LINUX) || defined(OS_CHROMEOS) // http://crbug.com/426393
1598 if (g_browser_process->metrics_service()->reporting_active())
1599 content::StartPowerUsageMonitor();
1600 #endif
1602 process_power_collector_.reset(new ProcessPowerCollector);
1603 process_power_collector_->Initialize();
1604 #endif // !defined(OS_ANDROID)
1606 PostBrowserStart();
1608 if (parameters().ui_task) {
1609 parameters().ui_task->Run();
1610 delete parameters().ui_task;
1611 run_message_loop_ = false;
1613 #if defined(OS_ANDROID)
1614 // We never run the C++ main loop on Android, since the UI thread message
1615 // loop is controlled by the OS, so this is as close as we can get to
1616 // the start of the main loop
1617 if (result_code_ <= 0) {
1618 RecordBrowserStartupTime();
1620 #endif
1621 return result_code_;
1624 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code) {
1625 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1626 #if defined(OS_ANDROID)
1627 // Chrome on Android does not use default MessageLoop. It has its own
1628 // Android specific MessageLoop
1629 NOTREACHED();
1630 return true;
1631 #else
1632 // Set the result code set in PreMainMessageLoopRun or set above.
1633 *result_code = result_code_;
1634 if (!run_message_loop_)
1635 return true; // Don't run the default message loop.
1637 // These should be invoked as close to the start of the browser's
1638 // UI thread message loop as possible to get a stable measurement
1639 // across versions.
1640 RecordBrowserStartupTime();
1642 DCHECK(base::MessageLoopForUI::IsCurrent());
1643 base::RunLoop run_loop;
1645 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1647 metrics::MetricsService::SetExecutionPhase(
1648 metrics::MetricsService::MAIN_MESSAGE_LOOP_RUN,
1649 g_browser_process->local_state());
1650 run_loop.Run();
1652 return true;
1653 #endif
1656 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1657 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1658 #if defined(OS_ANDROID)
1659 // Chrome on Android does not use default MessageLoop. It has its own
1660 // Android specific MessageLoop
1661 NOTREACHED();
1662 #else
1664 // Start watching for jank during shutdown. It gets disarmed when
1665 // |shutdown_watcher_| object is destructed.
1666 metrics::MetricsService::SetExecutionPhase(
1667 metrics::MetricsService::SHUTDOWN_TIMEBOMB_ARM,
1668 g_browser_process->local_state());
1669 shutdown_watcher_->Arm(base::TimeDelta::FromSeconds(300));
1671 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1672 startup_watcher_->Disarm();
1674 // Remove observers attached to D-Bus clients before DbusThreadManager is
1675 // shut down.
1676 process_power_collector_.reset();
1678 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1679 chrome_extra_parts_[i]->PostMainMessageLoopRun();
1681 // Some tests don't set parameters.ui_task, so they started translate
1682 // language fetch that was never completed so we need to cleanup here
1683 // otherwise it will be done by the destructor in a wrong thread.
1684 TranslateService::Shutdown(parameters().ui_task == NULL);
1686 if (notify_result_ == ProcessSingleton::PROCESS_NONE)
1687 process_singleton_->Cleanup();
1689 // Stop all tasks that might run on WatchDogThread.
1690 ThreadWatcherList::StopWatchingAll();
1692 browser_process_->metrics_service()->Stop();
1694 restart_last_session_ = browser_shutdown::ShutdownPreThreadsStop();
1695 browser_process_->StartTearDown();
1696 #endif
1699 void ChromeBrowserMainParts::PostDestroyThreads() {
1700 #if defined(OS_ANDROID)
1701 // On Android, there is no quit/exit. So the browser's main message loop will
1702 // not finish.
1703 NOTREACHED();
1704 #else
1705 browser_process_->PostDestroyThreads();
1706 // browser_shutdown takes care of deleting browser_process, so we need to
1707 // release it.
1708 ignore_result(browser_process_.release());
1709 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_);
1710 master_prefs_.reset();
1711 process_singleton_.reset();
1712 device_event_log::Shutdown();
1714 // We need to do this check as late as possible, but due to modularity, this
1715 // may be the last point in Chrome. This would be more effective if done at
1716 // a higher level on the stack, so that it is impossible for an early return
1717 // to bypass this code. Perhaps we need a *final* hook that is called on all
1718 // paths from content/browser/browser_main.
1719 CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
1721 #if defined(OS_CHROMEOS)
1722 chromeos::CrosSettings::Shutdown();
1723 #endif
1724 #endif
1727 // Public members:
1729 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts* parts) {
1730 chrome_extra_parts_.push_back(parts);