Give names to all utility processes.
[chromium-blink-merge.git] / chrome / browser / chrome_browser_main.cc
blobdc203f9f5a3b19882d8bc06da28263a5d32704f1
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/cookies/cookie_monster.h"
134 #include "net/http/http_network_layer.h"
135 #include "net/http/http_stream_factory.h"
136 #include "net/url_request/url_request.h"
137 #include "ui/base/l10n/l10n_util.h"
138 #include "ui/base/layout.h"
139 #include "ui/base/resource/resource_bundle.h"
140 #include "ui/strings/grit/app_locale_settings.h"
142 #if defined(OS_ANDROID)
143 #include "chrome/browser/metrics/thread_watcher_android.h"
144 #else
145 #include "chrome/browser/feedback/feedback_profile_observer.h"
146 #endif // defined(OS_ANDROID)
148 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
149 #include "chrome/browser/first_run/upgrade_util_linux.h"
150 #include "chrome/browser/sxs_linux.h"
151 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
153 #if defined(OS_CHROMEOS)
154 #include "chrome/browser/chromeos/settings/cros_settings.h"
155 #include "chromeos/chromeos_switches.h"
156 #include "chromeos/settings/cros_settings_names.h"
157 #endif // defined(OS_CHROMEOS)
159 // TODO(port): several win-only methods have been pulled out of this, but
160 // BrowserMain() as a whole needs to be broken apart so that it's usable by
161 // other platforms. For now, it's just a stub. This is a serious work in
162 // progress and should not be taken as an indication of a real refactoring.
164 #if defined(OS_WIN)
165 #include "base/environment.h" // For PreRead experiment.
166 #include "base/win/windows_version.h"
167 #include "chrome/browser/browser_util_win.h"
168 #include "chrome/browser/chrome_browser_main_win.h"
169 #include "chrome/browser/chrome_select_file_dialog_factory_win.h"
170 #include "chrome/browser/component_updater/caps_installer_win.h"
171 #include "chrome/browser/component_updater/sw_reporter_installer_win.h"
172 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
173 #include "chrome/browser/first_run/upgrade_util_win.h"
174 #include "chrome/browser/ui/network_profile_bubble.h"
175 #include "chrome/installer/util/helper.h"
176 #include "chrome/installer/util/install_util.h"
177 #include "chrome/installer/util/shell_util.h"
178 #include "components/browser_watcher/exit_funnel_win.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 // defined(OS_MACOSX)
192 #if !defined(OS_IOS)
193 #include "chrome/browser/ui/app_modal/chrome_javascript_native_dialog_factory.h"
194 #endif // !defined(OS_IOS)
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 // !defined(DISABLE_NACL)
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 // defined(ENABLE_EXTENSIONS)
207 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
208 #include "printing/printed_document.h"
209 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
211 #if defined(ENABLE_RLZ)
212 #include "chrome/browser/rlz/rlz.h"
213 #endif // defined(ENABLE_RLZ)
215 #if defined(ENABLE_WEBRTC)
216 #include "chrome/browser/media/webrtc_log_util.h"
217 #endif // defined(ENABLE_WEBRTC)
219 #if defined(USE_AURA)
220 #include "ui/aura/env.h"
221 #endif // defined(USE_AURA)
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 // defined(OS_CHROMEOS)
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 (profile_index != std::string::npos &&
378 cache.ProfileIsSigninRequiredAtIndex(profile_index)) {
379 profile = g_browser_process->profile_manager()->GetProfile(
380 ProfileManager::GetGuestProfilePath());
383 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID)
384 if (profile) {
385 UMA_HISTOGRAM_LONG_TIMES(
386 "Startup.CreateFirstProfile", base::Time::Now() - start);
387 return profile;
390 #if !defined(OS_WIN)
391 // TODO(port): fix this. See comments near the definition of
392 // user_data_dir. It is better to CHECK-fail here than it is to
393 // silently exit because of missing code in the above test.
394 CHECK(profile) << "Cannot get default profile.";
395 #endif // !defined(OS_WIN)
397 return NULL;
400 #if defined(OS_MACOSX)
401 OSStatus KeychainCallback(SecKeychainEvent keychain_event,
402 SecKeychainCallbackInfo* info, void* context) {
403 return noErr;
405 #endif // defined(OS_MACOSX)
407 void RegisterComponentsForUpdate() {
408 component_updater::ComponentUpdateService* cus =
409 g_browser_process->component_updater();
411 // Registration can be before or after cus->Start() so it is ok to post
412 // a task to the UI thread to do registration once you done the necessary
413 // file IO to know you existing component version.
414 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
415 RegisterRecoveryComponent(cus, g_browser_process->local_state());
416 RegisterPepperFlashComponent(cus);
417 RegisterSwiftShaderComponent(cus);
418 RegisterWidevineCdmComponent(cus);
419 #endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
421 #if !defined(DISABLE_NACL) && !defined(OS_ANDROID)
422 #if defined(OS_CHROMEOS)
423 // PNaCl on Chrome OS is on rootfs and there is no need to download it. But
424 // Chrome4ChromeOS on Linux doesn't contain PNaCl so enable component
425 // installer when running on Linux. See crbug.com/422121 for more details.
426 if (!base::SysInfo::IsRunningOnChromeOS())
427 #endif // defined(OS_CHROMEOS)
428 g_browser_process->pnacl_component_installer()->RegisterPnaclComponent(cus);
429 #endif // !defined(DISABLE_NACL) && !defined(OS_ANDROID)
431 // Registration of the CLD Component is a no-op unless the CLD data source has
432 // been configured to be the "Component" data source.
433 RegisterCldComponent(cus);
435 component_updater::SupervisedUserWhitelistInstaller* whitelist_installer =
436 g_browser_process->supervised_user_whitelist_installer();
437 whitelist_installer->RegisterComponents();
439 base::FilePath path;
440 if (PathService::Get(chrome::DIR_USER_DATA, &path)) {
441 #if defined(OS_ANDROID)
442 // The CRLSet component was enabled for some releases. This code attempts to
443 // delete it from the local disk of those how may have downloaded it.
444 g_browser_process->crl_set_fetcher()->DeleteFromDisk(path);
445 #elif !defined(OS_CHROMEOS)
446 // CRLSetFetcher attempts to load a CRL set from either the local disk or
447 // network.
448 // For Chrome OS this registration is delayed until user login.
449 g_browser_process->crl_set_fetcher()->StartInitialLoad(cus, path);
450 // Registration of the EV Whitelist component here is not necessary for:
451 // 1. Android: Because it currently does not have the EV indicator.
452 // 2. Chrome OS: On Chrome OS this registration is delayed until user login.
453 RegisterEVWhitelistComponent(cus, path);
454 #endif // defined(OS_ANDROID)
457 #if defined(OS_WIN)
458 RegisterSwReporterComponent(cus, g_browser_process->local_state());
459 RegisterCAPSComponent(cus);
460 #endif // defined(OS_WIN)
462 cus->Start();
465 #if !defined(OS_ANDROID)
466 bool ProcessSingletonNotificationCallback(
467 const base::CommandLine& command_line,
468 const base::FilePath& current_directory) {
469 // Drop the request if the browser process is already in shutdown path.
470 if (!g_browser_process || g_browser_process->IsShuttingDown()) {
471 #if defined(OS_WIN)
472 browser_watcher::ExitFunnel::RecordSingleEvent(
473 chrome::kBrowserExitCodesRegistryPath,
474 L"ProcessSingletonIsShuttingDown");
475 #endif // defined(OS_WIN)
477 return false;
480 if (command_line.HasSwitch(switches::kOriginalProcessStartTime)) {
481 std::string start_time_string =
482 command_line.GetSwitchValueASCII(switches::kOriginalProcessStartTime);
483 int64 remote_start_time;
484 if (base::StringToInt64(start_time_string, &remote_start_time)) {
485 base::TimeDelta elapsed =
486 base::Time::Now() - base::Time::FromInternalValue(remote_start_time);
487 if (command_line.HasSwitch(switches::kFastStart)) {
488 UMA_HISTOGRAM_LONG_TIMES(
489 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed);
490 } else {
491 UMA_HISTOGRAM_LONG_TIMES(
492 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed);
497 g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing(
498 command_line);
500 base::FilePath user_data_dir =
501 g_browser_process->profile_manager()->user_data_dir();
502 base::FilePath startup_profile_dir =
503 GetStartupProfilePath(user_data_dir, command_line);
505 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
506 command_line, current_directory, startup_profile_dir);
507 return true;
509 #endif // !defined(OS_ANDROID)
511 void LaunchDevToolsHandlerIfNeeded(const base::CommandLine& command_line) {
512 if (command_line.HasSwitch(::switches::kRemoteDebuggingPort)) {
513 std::string port_str =
514 command_line.GetSwitchValueASCII(::switches::kRemoteDebuggingPort);
515 int port;
516 if (base::StringToInt(port_str, &port) && port >= 0 && port < 65535) {
517 g_browser_process->CreateDevToolsHttpProtocolHandler(
518 chrome::HOST_DESKTOP_TYPE_NATIVE,
519 "127.0.0.1",
520 static_cast<uint16>(port));
521 } else {
522 DLOG(WARNING) << "Invalid http debugger port number " << port;
527 // Heap allocated class that listens for first page load, kicks off stat
528 // recording and then deletes itself.
529 class LoadCompleteListener : public content::NotificationObserver {
530 public:
531 LoadCompleteListener() {
532 registrar_.Add(this,
533 content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
534 content::NotificationService::AllSources());
536 ~LoadCompleteListener() override {}
538 // content::NotificationObserver implementation.
539 void Observe(int type,
540 const content::NotificationSource& source,
541 const content::NotificationDetails& details) override {
542 DCHECK_EQ(content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, type);
543 startup_metric_utils::OnInitialPageLoadComplete();
544 delete this;
547 private:
548 content::NotificationRegistrar registrar_;
549 DISALLOW_COPY_AND_ASSIGN(LoadCompleteListener);
552 } // namespace
554 namespace chrome_browser {
556 // This error message is not localized because we failed to load the
557 // localization data files.
558 #if defined(OS_WIN)
559 const char kMissingLocaleDataTitle[] = "Missing File Error";
560 #endif // defined(OS_WIN)
562 #if defined(OS_WIN)
563 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
564 const char kMissingLocaleDataMessage[] =
565 "Unable to find locale data files. Please reinstall.";
566 #endif // defined(OS_WIN)
568 } // namespace chrome_browser
570 // BrowserMainParts ------------------------------------------------------------
572 ChromeBrowserMainParts::ChromeBrowserMainParts(
573 const content::MainFunctionParams& parameters)
574 : parameters_(parameters),
575 parsed_command_line_(parameters.command_line),
576 result_code_(content::RESULT_CODE_NORMAL_EXIT),
577 startup_watcher_(new StartupTimeBomb()),
578 shutdown_watcher_(new ShutdownWatcherHelper()),
579 browser_field_trials_(parameters.command_line),
580 profile_(NULL),
581 run_message_loop_(true),
582 notify_result_(ProcessSingleton::PROCESS_NONE),
583 local_state_(NULL),
584 restart_last_session_(false) {
585 // If we're running tests (ui_task is non-null).
586 if (parameters.ui_task)
587 browser_defaults::enable_help_app = false;
589 // Chrome disallows cookies by default. All code paths that want to use
590 // cookies need to go through one of Chrome's URLRequestContexts which have
591 // a ChromeNetworkDelegate attached that selectively allows cookies again.
592 net::URLRequest::SetDefaultCookiePolicyToBlock();
595 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
596 for (int i = static_cast<int>(chrome_extra_parts_.size())-1; i >= 0; --i)
597 delete chrome_extra_parts_[i];
598 chrome_extra_parts_.clear();
601 // This will be called after the command-line has been mutated by about:flags
602 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
603 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
604 // Must initialize metrics after labs have been converted into switches,
605 // but before field trials are set up (so that client ID is available for
606 // one-time randomized field trials).
608 // Initialize FieldTrialList to support FieldTrials that use one-time
609 // randomization.
610 metrics::MetricsService* metrics = browser_process_->metrics_service();
611 field_trial_list_.reset(
612 new base::FieldTrialList(metrics->CreateEntropyProvider().release()));
614 const base::CommandLine* command_line =
615 base::CommandLine::ForCurrentProcess();
616 if (command_line->HasSwitch(switches::kEnableBenchmarking) ||
617 command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking)) {
618 base::FieldTrial::EnableBenchmarking();
621 // Ensure any field trials specified on the command line are initialized.
622 if (command_line->HasSwitch(switches::kForceFieldTrials)) {
623 std::set<std::string> unforceable_field_trials;
624 #if defined(OFFICIAL_BUILD)
625 unforceable_field_trials.insert("SettingsEnforcement");
626 #endif // defined(OFFICIAL_BUILD)
628 // Create field trials without activating them, so that this behaves in a
629 // consistent manner with field trials created from the server.
630 bool result = base::FieldTrialList::CreateTrialsFromString(
631 command_line->GetSwitchValueASCII(switches::kForceFieldTrials),
632 base::FieldTrialList::DONT_ACTIVATE_TRIALS,
633 unforceable_field_trials);
634 CHECK(result) << "Invalid --" << switches::kForceFieldTrials
635 << " list specified.";
637 if (command_line->HasSwitch(switches::kForceVariationIds)) {
638 // Create default variation ids which will always be included in the
639 // X-Client-Data request header.
640 variations::VariationsHttpHeaderProvider* provider =
641 variations::VariationsHttpHeaderProvider::GetInstance();
642 bool result = provider->SetDefaultVariationIds(
643 command_line->GetSwitchValueASCII(switches::kForceVariationIds));
644 CHECK(result) << "Invalid --" << switches::kForceVariationIds
645 << " list specified.";
646 metrics->AddSyntheticTrialObserver(provider);
648 chrome_variations::VariationsService* variations_service =
649 browser_process_->variations_service();
650 if (variations_service)
651 variations_service->CreateTrialsFromSeed();
653 // This must be called after |local_state_| is initialized.
654 browser_field_trials_.SetupFieldTrials();
656 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
657 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
658 // Even though base::Bind does AddRef and Release, the object will not be
659 // deleted after the Task is executed.
660 field_trial_synchronizer_ = new FieldTrialSynchronizer();
662 // Now that field trials have been created, initializes metrics recording.
663 metrics->InitializeMetricsRecordingState();
665 // Enable profiler instrumentation depending on the channel.
666 switch (chrome::VersionInfo::GetChannel()) {
667 case chrome::VersionInfo::CHANNEL_UNKNOWN:
668 case chrome::VersionInfo::CHANNEL_CANARY:
669 tracked_objects::ScopedTracker::Enable();
670 break;
672 case chrome::VersionInfo::CHANNEL_DEV:
673 case chrome::VersionInfo::CHANNEL_BETA:
674 case chrome::VersionInfo::CHANNEL_STABLE:
675 // Don't enable instrumentation.
676 break;
680 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
682 void ChromeBrowserMainParts::StartMetricsRecording() {
683 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
685 g_browser_process->metrics_service()->CheckForClonedInstall(
686 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
688 g_browser_process->GetMetricsServicesManager()->UpdateUploadPermissions(true);
691 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
692 // Don't record any metrics if UI was displayed before this point e.g.
693 // warning dialogs.
694 if (startup_metric_utils::WasNonBrowserUIDisplayed())
695 return;
697 #if defined(OS_ANDROID)
698 // On Android the first run is handled in Java code, and the C++ side of
699 // Chrome doesn't know if this is the first run. This will cause some
700 // inaccuracy in the UMA statistics, but this should be minor (first runs are
701 // rare).
702 bool is_first_run = false;
703 #else
704 bool is_first_run = first_run::IsChromeFirstRun();
705 #endif // defined(OS_ANDROID)
707 // CurrentProcessInfo::CreationTime() is currently only implemented on some
708 // platforms.
709 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
710 const base::Time process_creation_time =
711 base::CurrentProcessInfo::CreationTime();
713 if (!is_first_run && !process_creation_time.is_null()) {
714 base::TimeDelta delay = base::Time::Now() - process_creation_time;
715 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserMessageLoopStartTime", delay);
717 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
719 // Record collected startup metrics.
720 startup_metric_utils::OnBrowserStartupComplete(is_first_run);
722 // Deletes self.
723 new LoadCompleteListener();
726 // -----------------------------------------------------------------------------
727 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
729 #if defined(OS_WIN)
730 #define DLLEXPORT __declspec(dllexport)
732 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
733 extern "C" {
734 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded();
737 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
738 // Need an instance of AtExitManager to handle singleton creations and
739 // deletions. We need this new instance because, the old instance created
740 // in ChromeMain() got destructed when the function returned.
741 base::AtExitManager exit_manager;
742 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
744 #endif
746 // content::BrowserMainParts implementation ------------------------------------
748 void ChromeBrowserMainParts::PreEarlyInitialization() {
749 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
750 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
751 chrome_extra_parts_[i]->PreEarlyInitialization();
754 void ChromeBrowserMainParts::PostEarlyInitialization() {
755 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
756 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
757 chrome_extra_parts_[i]->PostEarlyInitialization();
760 void ChromeBrowserMainParts::ToolkitInitialized() {
761 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
762 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
763 chrome_extra_parts_[i]->ToolkitInitialized();
766 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
767 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
769 device_event_log::Initialize(0 /* default max entries */);
771 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
772 chrome_extra_parts_[i]->PreMainMessageLoopStart();
775 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
776 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
777 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
778 chrome_extra_parts_[i]->PostMainMessageLoopStart();
781 int ChromeBrowserMainParts::PreCreateThreads() {
782 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
783 result_code_ = PreCreateThreadsImpl();
785 if (result_code_ == content::RESULT_CODE_NORMAL_EXIT) {
786 #if !defined(OS_ANDROID)
787 // These members must be initialized before exiting this function normally.
788 DCHECK(master_prefs_.get());
789 DCHECK(browser_creator_.get());
790 #endif // !defined(OS_ANDROID)
791 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
792 chrome_extra_parts_[i]->PreCreateThreads();
795 return result_code_;
798 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
799 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
800 run_message_loop_ = false;
801 #if !defined(OS_ANDROID)
802 chrome::MaybeShowInvalidUserDataDirWarningDialog();
803 #endif // !defined(OS_ANDROID)
804 if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir_))
805 return chrome::RESULT_CODE_MISSING_DATA;
807 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
808 MediaCaptureDevicesDispatcher::GetInstance();
810 // Android's first run is done in Java instead of native.
811 #if !defined(OS_ANDROID)
812 process_singleton_.reset(new ChromeProcessSingleton(
813 user_data_dir_, base::Bind(&ProcessSingletonNotificationCallback)));
815 // Cache first run state early.
816 first_run::IsChromeFirstRun();
817 #endif // !defined(OS_ANDROID)
819 scoped_refptr<base::SequencedTaskRunner> local_state_task_runner =
820 JsonPrefStore::GetTaskRunnerForFile(
821 base::FilePath(chrome::kLocalStorePoolName),
822 BrowserThread::GetBlockingPool());
825 TRACE_EVENT0("startup",
826 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
827 browser_process_.reset(new BrowserProcessImpl(local_state_task_runner.get(),
828 parsed_command_line()));
831 if (parsed_command_line().HasSwitch(switches::kEnableProfiling)) {
832 TRACE_EVENT0("startup",
833 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
834 // User wants to override default tracking status.
835 std::string flag =
836 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling);
837 // Default to basic profiling (no parent child support).
838 tracked_objects::ThreadData::Status status =
839 tracked_objects::ThreadData::PROFILING_ACTIVE;
840 if (flag.compare("0") != 0)
841 status = tracked_objects::ThreadData::DEACTIVATED;
842 else if (flag.compare("child") != 0)
843 status = tracked_objects::ThreadData::PROFILING_CHILDREN_ACTIVE;
844 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status);
847 local_state_ = InitializeLocalState(
848 local_state_task_runner.get(), parsed_command_line());
850 #if !defined(OS_ANDROID)
851 // These members must be initialized before returning from this function.
852 master_prefs_.reset(new first_run::MasterPrefs);
853 // Android doesn't use StartupBrowserCreator.
854 browser_creator_.reset(new StartupBrowserCreator);
855 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
856 chrome::UMABrowsingActivityObserver::Init();
857 #endif // !defined(OS_ANDROID)
859 #if !defined(OS_CHROMEOS)
860 // Convert active labs into switches. This needs to be done before
861 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
862 // affected by experiment flags (--touch-optimized-ui in particular).
863 // On ChromeOS system level flags are applied from the device settings from
864 // the session manager.
866 TRACE_EVENT0("startup",
867 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
868 about_flags::PrefServiceFlagsStorage flags_storage_(
869 g_browser_process->local_state());
870 about_flags::ConvertFlagsToSwitches(&flags_storage_,
871 base::CommandLine::ForCurrentProcess(),
872 about_flags::kAddSentinels);
874 #endif // !defined(OS_CHROMEOS)
876 local_state_->UpdateCommandLinePrefStore(
877 new CommandLinePrefStore(base::CommandLine::ForCurrentProcess()));
879 // Reset the command line in the crash report details, since we may have
880 // just changed it to include experiments.
881 crash_keys::SetSwitchesFromCommandLine(
882 base::CommandLine::ForCurrentProcess());
884 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
885 // needed when loading the MainMenu.nib and the language doesn't depend on
886 // anything since it comes from Cocoa.
887 #if defined(OS_MACOSX)
888 std::string locale =
889 parameters().ui_task ? "en-US" : l10n_util::GetLocaleOverride();
890 browser_process_->SetApplicationLocale(locale);
891 #else
892 const std::string locale =
893 local_state_->GetString(prefs::kApplicationLocale);
895 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
896 // method InitSharedInstance is ignored.
898 TRACE_EVENT_BEGIN0("startup",
899 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
900 const std::string loaded_locale =
901 ui::ResourceBundle::InitSharedInstanceWithLocale(
902 locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
903 TRACE_EVENT_END0("startup",
904 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
906 if (loaded_locale.empty() &&
907 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs)) {
908 ShowMissingLocaleMessageBox();
909 return chrome::RESULT_CODE_MISSING_DATA;
911 CHECK(!loaded_locale.empty()) << "Locale could not be found for " << locale;
912 browser_process_->SetApplicationLocale(loaded_locale);
914 base::FilePath resources_pack_path;
915 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
917 TRACE_EVENT0("startup",
918 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
919 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
920 resources_pack_path, ui::SCALE_FACTOR_NONE);
922 #endif // defined(OS_MACOSX)
924 // Android does first run in Java instead of native.
925 // Chrome OS has its own out-of-box-experience code.
926 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
927 // On first run, we need to process the predictor preferences before the
928 // browser's profile_manager object is created, but after ResourceBundle
929 // is initialized.
930 if (first_run::IsChromeFirstRun()) {
931 first_run::ProcessMasterPreferencesResult pmp_result =
932 first_run::ProcessMasterPreferences(user_data_dir_,
933 master_prefs_.get());
934 if (pmp_result == first_run::EULA_EXIT_NOW)
935 return chrome::RESULT_CODE_EULA_REFUSED;
937 if (!parsed_command_line().HasSwitch(switches::kApp) &&
938 !parsed_command_line().HasSwitch(switches::kAppId) &&
939 !parsed_command_line().HasSwitch(switches::kShowAppList)) {
940 AddFirstRunNewTabs(browser_creator_.get(), master_prefs_->new_tabs);
943 // TODO(macourteau): refactor preferences that are copied from
944 // master_preferences into local_state, as a "local_state" section in
945 // master preferences. If possible, a generic solution would be preferred
946 // over a copy one-by-one of specific preferences. Also see related TODO
947 // in first_run.h.
949 // Store the initial VariationsService seed in local state, if it exists
950 // in master prefs.
951 if (!master_prefs_->variations_seed.empty() ||
952 !master_prefs_->compressed_variations_seed.empty()) {
953 if (!master_prefs_->variations_seed.empty()) {
954 local_state_->SetString(prefs::kVariationsSeed,
955 master_prefs_->variations_seed);
957 if (!master_prefs_->compressed_variations_seed.empty()) {
958 local_state_->SetString(prefs::kVariationsCompressedSeed,
959 master_prefs_->compressed_variations_seed);
961 if (!master_prefs_->variations_seed_signature.empty()) {
962 local_state_->SetString(prefs::kVariationsSeedSignature,
963 master_prefs_->variations_seed_signature);
965 // Set the variation seed date to the current system time. If the user's
966 // clock is incorrect, this may cause some field trial expiry checks to
967 // not do the right thing until the next seed update from the server,
968 // when this value will be updated.
969 local_state_->SetInt64(prefs::kVariationsSeedDate,
970 base::Time::Now().ToInternalValue());
973 if (!master_prefs_->suppress_default_browser_prompt_for_version.empty()) {
974 local_state_->SetString(
975 prefs::kBrowserSuppressDefaultBrowserPrompt,
976 master_prefs_->suppress_default_browser_prompt_for_version);
979 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
981 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
982 // Set the product channel for crash reports.
983 base::debug::SetCrashKeyValue(crash_keys::kChannel,
984 chrome::VersionInfo::GetVersionStringModifier());
985 #endif // defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
987 // Initialize tracking synchronizer system.
988 tracking_synchronizer_ =
989 new metrics::TrackingSynchronizer(base::TimeTicks::Now());
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 // defined(OS_MACOSX)
1001 #if defined(OS_CHROMEOS)
1002 // Must be done after g_browser_process is constructed, before
1003 // SetupMetricsAndFieldTrials().
1004 chromeos::CrosSettings::Initialize();
1005 #endif // defined(OS_CHROMEOS)
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 // !defined(OS_ANDROID)
1073 #if defined(ENABLE_EXTENSIONS)
1074 javascript_dialog_extensions_client::InstallClient();
1075 #endif // defined(ENABLE_EXTENSIONS)
1077 #if !defined(OS_IOS)
1078 InstallChromeJavaScriptNativeDialogFactory();
1079 #endif // !defined(OS_IOS)
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 // !defined(OS_ANDROID)
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 // defined(ENABLE_WEBRTC)
1116 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1117 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1118 SCOPED_UMA_HISTOGRAM_LONG_TIMER("Startup.PreMainMessageLoopRunImplLongTime");
1119 const base::TimeTicks start_time_step1 = base::TimeTicks::Now();
1120 // Android updates the metrics service dynamically depending on whether the
1121 // application is in the foreground or not. Do not start here.
1122 #if !defined(OS_ANDROID)
1123 // Now that the file thread has been started, start recording.
1124 StartMetricsRecording();
1125 #endif // !defined(OS_ANDROID)
1127 if (!base::debug::BeingDebugged()) {
1128 // Create watchdog thread after creating all other threads because it will
1129 // watch the other threads and they must be running.
1130 browser_process_->watchdog_thread();
1133 // Do any initializating in the browser process that requires all threads
1134 // running.
1135 browser_process_->PreMainMessageLoopRun();
1137 // Record last shutdown time into a histogram.
1138 browser_shutdown::ReadLastShutdownInfo();
1140 #if defined(OS_WIN)
1141 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1142 // tasks. Those care whether the browser is already running. On Linux/Mac,
1143 // upgrade/uninstall happen separately.
1144 bool already_running = browser_util::IsBrowserAlreadyRunning();
1146 // If the command line specifies 'uninstall' then we need to work here
1147 // unless we detect another chrome browser running.
1148 if (parsed_command_line().HasSwitch(switches::kUninstall)) {
1149 return DoUninstallTasks(already_running);
1152 if (parsed_command_line().HasSwitch(switches::kHideIcons) ||
1153 parsed_command_line().HasSwitch(switches::kShowIcons)) {
1154 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1155 parsed_command_line_);
1158 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
1159 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
1160 #endif // defined(OS_WIN)
1162 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser)) {
1163 return ShellIntegration::SetAsDefaultBrowser() ?
1164 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT) :
1165 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED);
1168 #if defined(USE_AURA)
1169 // Make sure aura::Env has been initialized.
1170 CHECK(aura::Env::GetInstance());
1171 #endif // defined(USE_AURA)
1173 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1174 #if !defined(OS_ANDROID)
1175 // If the command line specifies --pack-extension, attempt the pack extension
1176 // startup action and exit.
1177 if (parsed_command_line().HasSwitch(switches::kPackExtension)) {
1178 extensions::StartupHelper extension_startup_helper;
1179 if (extension_startup_helper.PackExtension(parsed_command_line()))
1180 return content::RESULT_CODE_NORMAL_EXIT;
1181 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR;
1184 // If we're being launched just to check the connector policy, we are
1185 // short-lived and don't want to be passing that switch off.
1186 bool pass_command_line = !parsed_command_line().HasSwitch(
1187 switches::kCheckCloudPrintConnectorPolicy);
1189 if (pass_command_line) {
1190 // When another process is running, use that process instead of starting a
1191 // new one. NotifyOtherProcess will currently give the other process up to
1192 // 20 seconds to respond. Note that this needs to be done before we attempt
1193 // to read the profile.
1194 notify_result_ = process_singleton_->NotifyOtherProcessOrCreate();
1195 switch (notify_result_) {
1196 case ProcessSingleton::PROCESS_NONE:
1197 // No process already running, fall through to starting a new one.
1198 break;
1200 case ProcessSingleton::PROCESS_NOTIFIED:
1201 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1202 // On POSIX systems, print a message notifying the process is running.
1203 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1204 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER))).c_str());
1205 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
1207 // Having a differentiated return type for testing allows for tests to
1208 // verify proper handling of some switches. When not testing, stick to
1209 // the standard Unix convention of returning zero when things went as
1210 // expected.
1211 if (parsed_command_line().HasSwitch(switches::kTestType))
1212 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED;
1213 return content::RESULT_CODE_NORMAL_EXIT;
1215 case ProcessSingleton::PROFILE_IN_USE:
1216 return chrome::RESULT_CODE_PROFILE_IN_USE;
1218 case ProcessSingleton::LOCK_ERROR:
1219 LOG(ERROR) << "Failed to create a ProcessSingleton for your profile "
1220 "directory. This means that running multiple instances "
1221 "would start multiple browser processes rather than "
1222 "opening a new window in the existing process. Aborting "
1223 "now to avoid profile corruption.";
1224 return chrome::RESULT_CODE_PROFILE_IN_USE;
1226 default:
1227 NOTREACHED();
1230 #endif // !defined(OS_ANDROID)
1232 // Handle special early return paths (which couldn't be processed even earlier
1233 // as they require the process singleton to be held) first.
1235 std::string try_chrome =
1236 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain);
1237 if (!try_chrome.empty()) {
1238 #if defined(OS_WIN)
1239 // Setup.exe has determined that we need to run a retention experiment
1240 // and has lauched chrome to show the experiment UI. It is guaranteed that
1241 // no other Chrome is currently running as the process singleton was
1242 // sucessfully grabbed above.
1243 int try_chrome_int;
1244 base::StringToInt(try_chrome, &try_chrome_int);
1245 TryChromeDialogView::Result answer = TryChromeDialogView::Show(
1246 try_chrome_int,
1247 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog,
1248 base::Unretained(process_singleton_.get())));
1249 if (answer == TryChromeDialogView::NOT_NOW)
1250 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL;
1251 if (answer == TryChromeDialogView::UNINSTALL_CHROME)
1252 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2;
1253 // At this point the user is willing to try chrome again.
1254 if (answer == TryChromeDialogView::TRY_CHROME_AS_DEFAULT) {
1255 // Only set in the unattended case, the interactive case is Windows 8.
1256 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1257 ShellIntegration::SET_DEFAULT_UNATTENDED)
1258 ShellIntegration::SetAsDefaultBrowser();
1260 #else
1261 // We don't support retention experiments on Mac or Linux.
1262 return content::RESULT_CODE_NORMAL_EXIT;
1263 #endif // defined(OS_WIN)
1266 #if defined(OS_WIN)
1267 // Do the tasks if chrome has been upgraded while it was last running.
1268 if (!already_running && upgrade_util::DoUpgradeTasks(parsed_command_line()))
1269 return content::RESULT_CODE_NORMAL_EXIT;
1271 // Check if there is any machine level Chrome installed on the current
1272 // machine. If yes and the current Chrome process is user level, we do not
1273 // allow the user level Chrome to run. So we notify the user and uninstall
1274 // user level Chrome.
1275 // Note this check needs to happen here (after the process singleton was
1276 // obtained but before potentially creating the first run sentinel).
1277 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1278 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS;
1279 #endif // defined(OS_WIN)
1281 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1282 if (sxs_linux::ShouldMigrateUserDataDir())
1283 return sxs_linux::MigrateUserDataDir();
1284 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1286 // Desktop construction occurs here, (required before profile creation).
1287 PreProfileInit();
1289 // Profile creation ----------------------------------------------------------
1291 metrics::MetricsService::SetExecutionPhase(
1292 metrics::MetricsService::CREATE_PROFILE,
1293 g_browser_process->local_state());
1295 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep1Time",
1296 base::TimeTicks::Now() - start_time_step1);
1298 // This step is costly and is already measured in Startup.CreateFirstProfile
1299 // and more directly Profile.CreateAndInitializeProfile.
1300 profile_ = CreatePrimaryProfile(parameters(),
1301 user_data_dir_,
1302 parsed_command_line());
1303 if (!profile_)
1304 return content::RESULT_CODE_NORMAL_EXIT;
1306 #if !defined(OS_ANDROID)
1307 const base::TimeTicks start_time_step2 = base::TimeTicks::Now();
1308 // The first run sentinel must be created after the process singleton was
1309 // grabbed and no early return paths were otherwise hit above.
1310 first_run::CreateSentinelIfNeeded();
1311 #endif // !defined(OS_ANDROID)
1313 #if defined(ENABLE_BACKGROUND)
1314 // Autoload any profiles which are running background apps.
1315 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1316 browser_process_->profile_manager()->AutoloadProfiles();
1317 #endif // defined(ENABLE_BACKGROUND)
1318 // Post-profile init ---------------------------------------------------------
1320 TranslateService::Initialize();
1322 // Needs to be done before PostProfileInit, since login manager on CrOS is
1323 // called inside PostProfileInit.
1324 content::WebUIControllerFactory::RegisterFactory(
1325 ChromeWebUIControllerFactory::GetInstance());
1327 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1328 // So make sure to create it before that.
1329 #if !defined(DISABLE_NACL)
1330 NaClBrowserDelegateImpl* delegate =
1331 new NaClBrowserDelegateImpl(browser_process_->profile_manager());
1332 nacl::NaClBrowser::SetDelegate(delegate);
1333 #endif // !defined(DISABLE_NACL)
1335 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1336 // (requires supporting early exit).
1337 PostProfileInit();
1339 // Retrieve cached GL strings from local state and use them for GPU
1340 // blacklist decisions.
1341 if (g_browser_process->gl_string_manager())
1342 g_browser_process->gl_string_manager()->Initialize();
1344 // Create an instance of GpuModeManager to watch gpu mode pref change.
1345 g_browser_process->gpu_mode_manager();
1347 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1348 // Show the First Run UI if this is the first time Chrome has been run on
1349 // this computer, or we're being compelled to do so by a command line flag.
1350 // Note that this be done _after_ the PrefService is initialized and all
1351 // preferences are registered, since some of the code that the importer
1352 // touches reads preferences.
1353 if (first_run::IsChromeFirstRun()) {
1354 first_run::AutoImport(profile_,
1355 master_prefs_->homepage_defined,
1356 master_prefs_->do_import_items,
1357 master_prefs_->dont_import_items,
1358 master_prefs_->import_bookmarks_path);
1360 // Note: this can pop the first run consent dialog on linux.
1361 first_run::DoPostImportTasks(profile_,
1362 master_prefs_->make_chrome_default_for_user);
1364 if (!master_prefs_->suppress_first_run_default_browser_prompt) {
1365 browser_creator_->set_show_main_browser_window(
1366 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_));
1367 } else {
1368 browser_creator_->set_is_default_browser_dialog_suppressed(true);
1371 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1373 #if defined(OS_WIN)
1374 // Sets things up so that if we crash from this point on, a dialog will
1375 // popup asking the user to restart chrome. It is done this late to avoid
1376 // testing against a bunch of special cases that are taken care early on.
1377 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1378 parsed_command_line());
1380 // Registers Chrome with the Windows Restart Manager, which will restore the
1381 // Chrome session when the computer is restarted after a system update.
1382 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1383 // but should run on startup if extended to handle crashes/hangs/patches.
1384 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1385 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
1386 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1387 parsed_command_line());
1390 // Verify that the profile is not on a network share and if so prepare to show
1391 // notification to the user.
1392 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_)) {
1393 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
1394 base::Bind(&NetworkProfileBubble::CheckNetworkProfile,
1395 profile_->GetPath()));
1397 #endif // defined(OS_WIN)
1399 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1400 // Init the RLZ library. This just binds the dll and schedules a task on the
1401 // file thread to be run sometime later. If this is the first run we record
1402 // the installation event.
1403 PrefService* pref_service = profile_->GetPrefs();
1404 int ping_delay = first_run::IsChromeFirstRun() ? master_prefs_->ping_delay :
1405 pref_service->GetInteger(first_run::GetPingDelayPrefName().c_str());
1406 // Negative ping delay means to send ping immediately after a first search is
1407 // recorded.
1408 RLZTracker::InitRlzFromProfileDelayed(
1409 profile_, first_run::IsChromeFirstRun(), ping_delay < 0,
1410 base::TimeDelta::FromMilliseconds(abs(ping_delay)));
1411 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1413 // Configure modules that need access to resources.
1414 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider);
1416 // In unittest mode, this will do nothing. In normal mode, this will create
1417 // the global IntranetRedirectDetector instance, which will promptly go to
1418 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1419 // to see if it should do anything else.
1421 // A simpler way of doing all this would be to have some function which could
1422 // give the time elapsed since startup, and simply have this object check that
1423 // when asked to initialize itself, but this doesn't seem to exist.
1425 // This can't be created in the BrowserProcessImpl constructor because it
1426 // needs to read prefs that get set after that runs.
1427 browser_process_->intranet_redirect_detector();
1428 GoogleSearchCounter::RegisterForNotifications();
1430 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1431 if (parsed_command_line().HasSwitch(switches::kDebugPrint)) {
1432 base::FilePath path =
1433 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint);
1434 printing::PrintedDocument::set_debug_dump_path(path);
1436 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1438 HandleTestParameters(parsed_command_line());
1439 browser_process_->metrics_service()->RecordBreakpadHasDebugger(
1440 base::debug::BeingDebugged());
1442 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1443 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1444 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1445 browser_process_->GetApplicationLocale());
1447 // Start watching for hangs during startup. We disarm this hang detector when
1448 // ThreadWatcher takes over or when browser is shutdown or when
1449 // startup_watcher_ is deleted.
1450 metrics::MetricsService::SetExecutionPhase(
1451 metrics::MetricsService::STARTUP_TIMEBOMB_ARM,
1452 g_browser_process->local_state());
1453 startup_watcher_->Arm(base::TimeDelta::FromSeconds(600));
1455 // On mobile, need for clean shutdown arises only when the application comes
1456 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1457 // http://crbug.com/179143
1458 #if !defined(OS_ANDROID)
1459 // Start watching for a hang.
1460 browser_process_->metrics_service()->LogNeedForCleanShutdown();
1461 #endif // !defined(OS_ANDROID)
1463 #if defined(ENABLE_PRINT_PREVIEW)
1464 // Create the instance of the cloud print proxy service so that it can launch
1465 // the service process if needed. This is needed because the service process
1466 // might have shutdown because an update was available.
1467 // TODO(torne): this should maybe be done with
1468 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1469 // instead?
1470 CloudPrintProxyServiceFactory::GetForProfile(profile_);
1471 #endif // defined(ENABLE_PRINT_PREVIEW)
1473 // Start watching all browser threads for responsiveness.
1474 metrics::MetricsService::SetExecutionPhase(
1475 metrics::MetricsService::THREAD_WATCHER_START,
1476 g_browser_process->local_state());
1477 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1479 #if defined(OS_ANDROID)
1480 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1481 #endif // defined(OS_ANDROID)
1483 #if !defined(DISABLE_NACL)
1484 BrowserThread::PostTask(
1485 BrowserThread::IO,
1486 FROM_HERE,
1487 base::Bind(nacl::NaClProcessHost::EarlyStartup));
1488 #endif // !defined(DISABLE_NACL)
1490 // Make sure initial prefs are recorded
1491 PrefMetricsService::Factory::GetForProfile(profile_);
1493 PreBrowserStart();
1495 // Instantiate the notification UI manager, as this triggers a perf timer
1496 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1497 // triggering the timer and call that explicitly in the approprate place.
1498 // http://crbug.com/105065.
1499 browser_process_->notification_ui_manager();
1501 // This must be called prior to RegisterComponentsForUpdate, in case the CLD
1502 // data source is based on the Component Updater.
1503 translate::BrowserCldUtils::ConfigureDefaultDataProvider();
1505 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate))
1506 RegisterComponentsForUpdate();
1508 #if defined(OS_ANDROID)
1509 chrome_variations::VariationsService* variations_service =
1510 browser_process_->variations_service();
1511 if (variations_service) {
1512 // Just initialize the policy prefs service here. Variations seed fetching
1513 // will be initialized when the app enters foreground mode.
1514 variations_service->set_policy_pref_service(profile_->GetPrefs());
1516 translate::TranslateDownloadManager::RequestLanguageList(
1517 profile_->GetPrefs());
1519 #else
1520 // Most general initialization is behind us, but opening a
1521 // tab and/or session restore and such is still to be done.
1522 base::TimeTicks browser_open_start = base::TimeTicks::Now();
1524 // We are in regular browser boot sequence. Open initial tabs and enter the
1525 // main message loop.
1526 #if defined(OS_CHROMEOS)
1527 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1528 // them this early as the cryptohome hasn't yet been mounted (which happens
1529 // only once we log in.
1530 std::vector<Profile*> last_opened_profiles;
1531 #else
1532 std::vector<Profile*> last_opened_profiles =
1533 g_browser_process->profile_manager()->GetLastOpenedProfiles();
1534 #endif // defined(OS_CHROMEOS)
1536 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep2Time",
1537 base::TimeTicks::Now() - start_time_step2);
1539 // This step is costly and is already measured in
1540 // Startup.StartupBrowserCreator_Start.
1541 bool started = browser_creator_->Start(
1542 parsed_command_line(), base::FilePath(), profile_, last_opened_profiles);
1543 const base::TimeTicks start_time_step3 = base::TimeTicks::Now();
1544 if (started) {
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 // defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
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 // defined(OS_LINUX) && !defined(OS_CHROMEOS)
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 // defined(OS_MACOSX)
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 // defined(OS_WIN)
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 // !defined(OS_LINUX) || defined(OS_CHROMEOS)
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 // defined(OS_ANDROID)
1624 #if !defined(OS_ANDROID)
1625 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep3Time",
1626 base::TimeTicks::Now() - start_time_step3);
1627 #endif // !defined(OS_ANDROID)
1629 return result_code_;
1632 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code) {
1633 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1634 #if defined(OS_ANDROID)
1635 // Chrome on Android does not use default MessageLoop. It has its own
1636 // Android specific MessageLoop
1637 NOTREACHED();
1638 return true;
1639 #else
1640 // Set the result code set in PreMainMessageLoopRun or set above.
1641 *result_code = result_code_;
1642 if (!run_message_loop_)
1643 return true; // Don't run the default message loop.
1645 // These should be invoked as close to the start of the browser's
1646 // UI thread message loop as possible to get a stable measurement
1647 // across versions.
1648 RecordBrowserStartupTime();
1650 DCHECK(base::MessageLoopForUI::IsCurrent());
1651 base::RunLoop run_loop;
1653 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1655 metrics::MetricsService::SetExecutionPhase(
1656 metrics::MetricsService::MAIN_MESSAGE_LOOP_RUN,
1657 g_browser_process->local_state());
1658 run_loop.Run();
1660 return true;
1661 #endif // defined(OS_ANDROID)
1664 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1665 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1666 #if defined(OS_ANDROID)
1667 // Chrome on Android does not use default MessageLoop. It has its own
1668 // Android specific MessageLoop
1669 NOTREACHED();
1670 #else
1672 // Start watching for jank during shutdown. It gets disarmed when
1673 // |shutdown_watcher_| object is destructed.
1674 metrics::MetricsService::SetExecutionPhase(
1675 metrics::MetricsService::SHUTDOWN_TIMEBOMB_ARM,
1676 g_browser_process->local_state());
1677 shutdown_watcher_->Arm(base::TimeDelta::FromSeconds(300));
1679 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1680 startup_watcher_->Disarm();
1682 // Remove observers attached to D-Bus clients before DbusThreadManager is
1683 // shut down.
1684 process_power_collector_.reset();
1686 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1687 chrome_extra_parts_[i]->PostMainMessageLoopRun();
1689 // Some tests don't set parameters.ui_task, so they started translate
1690 // language fetch that was never completed so we need to cleanup here
1691 // otherwise it will be done by the destructor in a wrong thread.
1692 TranslateService::Shutdown(parameters().ui_task == NULL);
1694 if (notify_result_ == ProcessSingleton::PROCESS_NONE)
1695 process_singleton_->Cleanup();
1697 // Stop all tasks that might run on WatchDogThread.
1698 ThreadWatcherList::StopWatchingAll();
1700 browser_process_->metrics_service()->Stop();
1702 restart_last_session_ = browser_shutdown::ShutdownPreThreadsStop();
1703 browser_process_->StartTearDown();
1704 #endif // defined(OS_ANDROID)
1707 void ChromeBrowserMainParts::PostDestroyThreads() {
1708 #if defined(OS_ANDROID)
1709 // On Android, there is no quit/exit. So the browser's main message loop will
1710 // not finish.
1711 NOTREACHED();
1712 #else
1713 browser_process_->PostDestroyThreads();
1714 // browser_shutdown takes care of deleting browser_process, so we need to
1715 // release it.
1716 ignore_result(browser_process_.release());
1717 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_);
1718 master_prefs_.reset();
1719 process_singleton_.reset();
1720 device_event_log::Shutdown();
1722 // We need to do this check as late as possible, but due to modularity, this
1723 // may be the last point in Chrome. This would be more effective if done at
1724 // a higher level on the stack, so that it is impossible for an early return
1725 // to bypass this code. Perhaps we need a *final* hook that is called on all
1726 // paths from content/browser/browser_main.
1727 CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
1729 #if defined(OS_CHROMEOS)
1730 chromeos::CrosSettings::Shutdown();
1731 #endif // defined(OS_CHROMEOS)
1732 #endif // defined(OS_ANDROID)
1735 // Public members:
1737 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts* parts) {
1738 chrome_extra_parts_.push_back(parts);