Rename vector icon header files.
[chromium-blink-merge.git] / chrome / browser / chrome_browser_main.cc
blob42b815d2c28421d91bb3cbcfee17e00601e9881d
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/profiler/scoped_profile.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/default_tick_clock.h"
37 #include "base/time/time.h"
38 #include "base/trace_event/trace_event.h"
39 #include "base/values.h"
40 #include "build/build_config.h"
41 #include "cc/base/switches.h"
42 #include "chrome/browser/about_flags.h"
43 #include "chrome/browser/after_startup_task_utils.h"
44 #include "chrome/browser/browser_process.h"
45 #include "chrome/browser/browser_process_impl.h"
46 #include "chrome/browser/browser_process_platform_part.h"
47 #include "chrome/browser/browser_shutdown.h"
48 #include "chrome/browser/chrome_browser_main_extra_parts.h"
49 #include "chrome/browser/component_updater/cld_component_installer.h"
50 #include "chrome/browser/component_updater/ev_whitelist_component_installer.h"
51 #include "chrome/browser/component_updater/flash_component_installer.h"
52 #include "chrome/browser/component_updater/recovery_component_installer.h"
53 #include "chrome/browser/component_updater/supervised_user_whitelist_installer.h"
54 #include "chrome/browser/component_updater/swiftshader_component_installer.h"
55 #include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
56 #include "chrome/browser/defaults.h"
57 #include "chrome/browser/first_run/first_run.h"
58 #include "chrome/browser/first_run/upgrade_util.h"
59 #include "chrome/browser/google/google_search_counter.h"
60 #include "chrome/browser/gpu/gl_string_manager.h"
61 #include "chrome/browser/gpu/three_d_api_observer.h"
62 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
63 #include "chrome/browser/memory/oom_priority_manager.h"
64 #include "chrome/browser/metrics/field_trial_synchronizer.h"
65 #include "chrome/browser/metrics/metrics_services_manager.h"
66 #include "chrome/browser/metrics/thread_watcher.h"
67 #include "chrome/browser/metrics/variations/variations_service.h"
68 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
69 #include "chrome/browser/net/chrome_net_log.h"
70 #include "chrome/browser/net/crl_set_fetcher.h"
71 #include "chrome/browser/performance_monitor/performance_monitor.h"
72 #include "chrome/browser/plugins/plugin_prefs.h"
73 #include "chrome/browser/power/process_power_collector.h"
74 #include "chrome/browser/pref_service_flags_storage.h"
75 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
76 #include "chrome/browser/prefs/command_line_pref_store.h"
77 #include "chrome/browser/prefs/incognito_mode_prefs.h"
78 #include "chrome/browser/prefs/pref_metrics_service.h"
79 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
80 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
81 #include "chrome/browser/process_singleton.h"
82 #include "chrome/browser/profiles/profile.h"
83 #include "chrome/browser/profiles/profile_manager.h"
84 #include "chrome/browser/profiles/profiles_state.h"
85 #include "chrome/browser/shell_integration.h"
86 #include "chrome/browser/tracing/navigation_tracing.h"
87 #include "chrome/browser/translate/translate_service.h"
88 #include "chrome/browser/ui/app_list/app_list_service.h"
89 #include "chrome/browser/ui/browser.h"
90 #include "chrome/browser/ui/browser_finder.h"
91 #include "chrome/browser/ui/host_desktop.h"
92 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
93 #include "chrome/browser/ui/startup/default_browser_prompt.h"
94 #include "chrome/browser/ui/startup/startup_browser_creator.h"
95 #include "chrome/browser/ui/uma_browsing_activity_observer.h"
96 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
97 #include "chrome/common/channel_info.h"
98 #include "chrome/common/chrome_constants.h"
99 #include "chrome/common/chrome_paths.h"
100 #include "chrome/common/chrome_result_codes.h"
101 #include "chrome/common/chrome_switches.h"
102 #include "chrome/common/crash_keys.h"
103 #include "chrome/common/env_vars.h"
104 #include "chrome/common/logging_chrome.h"
105 #include "chrome/common/net/net_resource_provider.h"
106 #include "chrome/common/pref_names.h"
107 #include "chrome/common/profiling.h"
108 #include "chrome/common/variations/variations_util.h"
109 #include "chrome/grit/generated_resources.h"
110 #include "chrome/installer/util/google_update_settings.h"
111 #include "components/component_updater/component_updater_service.h"
112 #include "components/device_event_log/device_event_log.h"
113 #include "components/google/core/browser/google_util.h"
114 #include "components/language_usage_metrics/language_usage_metrics.h"
115 #include "components/metrics/call_stack_profile_metrics_provider.h"
116 #include "components/metrics/metrics_service.h"
117 #include "components/metrics/profiler/tracking_synchronizer.h"
118 #include "components/nacl/browser/nacl_browser.h"
119 #include "components/rappor/rappor_service.h"
120 #include "components/signin/core/common/profile_management_switches.h"
121 #include "components/startup_metric_utils/startup_metric_utils.h"
122 #include "components/tracing/tracing_switches.h"
123 #include "components/translate/content/browser/browser_cld_utils.h"
124 #include "components/translate/content/common/cld_data_source.h"
125 #include "components/translate/core/browser/translate_download_manager.h"
126 #include "components/variations/net/variations_http_header_provider.h"
127 #include "components/variations/pref_names.h"
128 #include "components/variations/variations_associated_data.h"
129 #include "components/variations/variations_switches.h"
130 #include "components/version_info/version_info.h"
131 #include "content/public/browser/browser_thread.h"
132 #include "content/public/browser/notification_observer.h"
133 #include "content/public/browser/notification_registrar.h"
134 #include "content/public/browser/notification_service.h"
135 #include "content/public/browser/notification_types.h"
136 #include "content/public/browser/power_usage_monitor.h"
137 #include "content/public/browser/site_instance.h"
138 #include "content/public/common/content_client.h"
139 #include "content/public/common/content_switches.h"
140 #include "content/public/common/main_function_params.h"
141 #include "grit/platform_locale_settings.h"
142 #include "media/audio/audio_manager.h"
143 #include "net/base/net_module.h"
144 #include "net/cookies/cookie_monster.h"
145 #include "net/http/http_network_layer.h"
146 #include "net/http/http_stream_factory.h"
147 #include "net/url_request/url_request.h"
148 #include "ui/base/l10n/l10n_util.h"
149 #include "ui/base/layout.h"
150 #include "ui/base/resource/resource_bundle.h"
151 #include "ui/strings/grit/app_locale_settings.h"
153 #if defined(OS_ANDROID)
154 #include "chrome/browser/android/dev_tools_discovery_provider_android.h"
155 #include "chrome/browser/metrics/thread_watcher_android.h"
156 #include "ui/base/resource/resource_bundle_android.h"
157 #else
158 #include "chrome/browser/devtools/chrome_devtools_discovery_provider.h"
159 #include "chrome/browser/feedback/feedback_profile_observer.h"
160 #endif // defined(OS_ANDROID)
162 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
163 #include "chrome/browser/first_run/upgrade_util_linux.h"
164 #include "chrome/browser/sxs_linux.h"
165 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
167 #if defined(OS_CHROMEOS)
168 #include "chrome/browser/chromeos/settings/cros_settings.h"
169 #include "chromeos/chromeos_switches.h"
170 #include "chromeos/settings/cros_settings_names.h"
171 #endif // defined(OS_CHROMEOS)
173 // TODO(port): several win-only methods have been pulled out of this, but
174 // BrowserMain() as a whole needs to be broken apart so that it's usable by
175 // other platforms. For now, it's just a stub. This is a serious work in
176 // progress and should not be taken as an indication of a real refactoring.
178 #if defined(OS_WIN)
179 #include "base/environment.h" // For PreRead experiment.
180 #include "base/trace_event/trace_event_etw_export_win.h"
181 #include "base/win/windows_version.h"
182 #include "chrome/browser/browser_util_win.h"
183 #include "chrome/browser/chrome_browser_main_win.h"
184 #include "chrome/browser/chrome_select_file_dialog_factory_win.h"
185 #include "chrome/browser/component_updater/caps_installer_win.h"
186 #include "chrome/browser/component_updater/sw_reporter_installer_win.h"
187 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
188 #include "chrome/browser/first_run/upgrade_util_win.h"
189 #include "chrome/browser/ui/network_profile_bubble.h"
190 #include "chrome/installer/util/helper.h"
191 #include "chrome/installer/util/install_util.h"
192 #include "chrome/installer/util/shell_util.h"
193 #include "components/browser_watcher/exit_funnel_win.h"
194 #include "net/base/net_util.h"
195 #include "ui/base/l10n/l10n_util_win.h"
196 #include "ui/gfx/win/dpi.h"
197 #include "ui/shell_dialogs/select_file_dialog.h"
198 #endif // defined(OS_WIN)
200 #if defined(OS_MACOSX)
201 #include <Security/Security.h>
203 #include "base/mac/scoped_nsautorelease_pool.h"
204 #include "chrome/browser/mac/keystone_glue.h"
205 #endif // defined(OS_MACOSX)
207 #if !defined(OS_IOS)
208 #include "chrome/browser/ui/app_modal/chrome_javascript_native_dialog_factory.h"
209 #endif // !defined(OS_IOS)
211 #if !defined(DISABLE_NACL)
212 #include "chrome/browser/component_updater/pnacl_component_installer.h"
213 #include "components/nacl/browser/nacl_process_host.h"
214 #endif // !defined(DISABLE_NACL)
216 #if defined(ENABLE_EXTENSIONS)
217 #include "chrome/browser/extensions/startup_helper.h"
218 #include "extensions/browser/extension_protocols.h"
219 #include "extensions/common/features/feature_provider.h"
220 #include "extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.h"
221 #endif // defined(ENABLE_EXTENSIONS)
223 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
224 #include "printing/printed_document.h"
225 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
227 #if defined(ENABLE_RLZ)
228 #include "chrome/browser/rlz/chrome_rlz_tracker_delegate.h"
229 #include "components/rlz/rlz_tracker.h"
230 #endif // defined(ENABLE_RLZ)
232 #if defined(ENABLE_WEBRTC)
233 #include "chrome/browser/media/webrtc_log_util.h"
234 #endif // defined(ENABLE_WEBRTC)
236 #if defined(USE_AURA)
237 #include "ui/aura/env.h"
238 #endif // defined(USE_AURA)
240 using content::BrowserThread;
242 namespace {
244 // This function provides some ways to test crash and assertion handling
245 // behavior of the program.
246 void HandleTestParameters(const base::CommandLine& command_line) {
247 // This parameter causes a null pointer crash (crash reporter trigger).
248 if (command_line.HasSwitch(switches::kBrowserCrashTest)) {
249 int* bad_pointer = NULL;
250 *bad_pointer = 0;
254 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
255 void AddFirstRunNewTabs(StartupBrowserCreator* browser_creator,
256 const std::vector<GURL>& new_tabs) {
257 for (std::vector<GURL>::const_iterator it = new_tabs.begin();
258 it != new_tabs.end(); ++it) {
259 if (it->is_valid())
260 browser_creator->AddFirstRunTab(*it);
263 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
265 // Returns the new local state object, guaranteed non-NULL.
266 // |local_state_task_runner| must be a shutdown-blocking task runner.
267 PrefService* InitializeLocalState(
268 base::SequencedTaskRunner* local_state_task_runner,
269 const base::CommandLine& parsed_command_line) {
270 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
272 // Load local state. This includes the application locale so we know which
273 // locale dll to load. This also causes local state prefs to be registered.
274 PrefService* local_state = g_browser_process->local_state();
275 DCHECK(local_state);
277 #if defined(OS_WIN)
278 if (first_run::IsChromeFirstRun()) {
279 // During first run we read the google_update registry key to find what
280 // language the user selected when downloading the installer. This
281 // becomes our default language in the prefs.
282 // Other platforms obey the system locale.
283 base::string16 install_lang;
284 if (GoogleUpdateSettings::GetLanguage(&install_lang)) {
285 local_state->SetString(prefs::kApplicationLocale,
286 base::UTF16ToASCII(install_lang));
289 #endif // defined(OS_WIN)
291 // If the local state file for the current profile doesn't exist and the
292 // parent profile command line flag is present, then we should inherit some
293 // local state from the parent profile.
294 // Checking that the local state file for the current profile doesn't exist
295 // is the most robust way to determine whether we need to inherit or not
296 // since the parent profile command line flag can be present even when the
297 // current profile is not a new one, and in that case we do not want to
298 // inherit and reset the user's setting.
300 // TODO(mnissler): We should probably just instantiate a
301 // JSONPrefStore here instead of an entire PrefService. Once this is
302 // addressed, the call to browser_prefs::RegisterLocalState can move
303 // to chrome_prefs::CreateLocalState.
304 if (parsed_command_line.HasSwitch(switches::kParentProfile)) {
305 base::FilePath local_state_path;
306 PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path);
307 bool local_state_file_exists = base::PathExists(local_state_path);
308 if (!local_state_file_exists) {
309 base::FilePath parent_profile =
310 parsed_command_line.GetSwitchValuePath(switches::kParentProfile);
311 scoped_refptr<PrefRegistrySimple> registry = new PrefRegistrySimple();
312 scoped_ptr<PrefService> parent_local_state(
313 chrome_prefs::CreateLocalState(
314 parent_profile,
315 local_state_task_runner,
316 g_browser_process->policy_service(),
317 registry,
318 false));
319 registry->RegisterStringPref(prefs::kApplicationLocale, std::string());
320 // Right now, we only inherit the locale setting from the parent profile.
321 local_state->SetString(
322 prefs::kApplicationLocale,
323 parent_local_state->GetString(prefs::kApplicationLocale));
327 #if defined(OS_CHROMEOS)
328 if (parsed_command_line.HasSwitch(chromeos::switches::kLoginManager)) {
329 std::string owner_locale = local_state->GetString(prefs::kOwnerLocale);
330 // Ensure that we start with owner's locale.
331 if (!owner_locale.empty() &&
332 local_state->GetString(prefs::kApplicationLocale) != owner_locale &&
333 !local_state->IsManagedPreference(prefs::kApplicationLocale)) {
334 local_state->SetString(prefs::kApplicationLocale, owner_locale);
337 #endif // defined(OS_CHROMEOS)
339 return local_state;
342 // Initializes the primary profile, possibly doing some user prompting to pick
343 // a fallback profile. Returns the newly created profile, or NULL if startup
344 // should not continue.
345 Profile* CreatePrimaryProfile(const content::MainFunctionParams& parameters,
346 const base::FilePath& user_data_dir,
347 const base::CommandLine& parsed_command_line) {
348 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
349 TRACK_SCOPED_REGION(
350 "Startup", "ChromeBrowserMainParts::CreatePrimaryProfile");
352 base::Time start = base::Time::Now();
353 if (profiles::IsMultipleProfilesEnabled() &&
354 parsed_command_line.HasSwitch(switches::kProfileDirectory)) {
355 profiles::SetLastUsedProfile(
356 parsed_command_line.GetSwitchValueASCII(switches::kProfileDirectory));
357 // Clear kProfilesLastActive since the user only wants to launch a specific
358 // profile.
359 ListPrefUpdate update(g_browser_process->local_state(),
360 prefs::kProfilesLastActive);
361 base::ListValue* profile_list = update.Get();
362 profile_list->Clear();
365 Profile* profile = NULL;
366 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
367 // On ChromeOS and Android the ProfileManager will use the same path as the
368 // one we got passed. GetActiveUserProfile will therefore use the correct path
369 // automatically.
370 DCHECK_EQ(user_data_dir.value(),
371 g_browser_process->profile_manager()->user_data_dir().value());
372 profile = ProfileManager::GetActiveUserProfile();
373 #else
374 base::FilePath profile_path =
375 GetStartupProfilePath(user_data_dir, parsed_command_line);
377 // Without NewAvatarMenu, replace guest with any existing profile.
378 if (!switches::IsNewAvatarMenu() &&
379 profile_path == ProfileManager::GetGuestProfilePath()) {
380 profile_path = g_browser_process->profile_manager()->GetProfileInfoCache().
381 GetPathOfProfileAtIndex(0);
383 profile = g_browser_process->profile_manager()->GetProfile(
384 profile_path);
386 // If we're using the --new-profile-management flag and this profile is
387 // signed out, then we should show the user manager instead. By switching
388 // the active profile to the guest profile we ensure that no
389 // browser windows will be opened for the guest profile.
390 if (switches::IsNewProfileManagement() &&
391 profile &&
392 !profile->IsGuestSession()) {
393 ProfileInfoCache& cache =
394 g_browser_process->profile_manager()->GetProfileInfoCache();
395 size_t profile_index = cache.GetIndexOfProfileWithPath(profile_path);
397 if (profile_index != std::string::npos &&
398 cache.ProfileIsSigninRequiredAtIndex(profile_index)) {
399 profile = g_browser_process->profile_manager()->GetProfile(
400 ProfileManager::GetGuestProfilePath());
403 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID)
404 if (profile) {
405 UMA_HISTOGRAM_LONG_TIMES(
406 "Startup.CreateFirstProfile", base::Time::Now() - start);
407 return profile;
410 #if !defined(OS_WIN)
411 // TODO(port): fix this. See comments near the definition of
412 // user_data_dir. It is better to CHECK-fail here than it is to
413 // silently exit because of missing code in the above test.
414 CHECK(profile) << "Cannot get default profile.";
415 #endif // !defined(OS_WIN)
417 return NULL;
420 #if defined(OS_MACOSX)
421 OSStatus KeychainCallback(SecKeychainEvent keychain_event,
422 SecKeychainCallbackInfo* info, void* context) {
423 return noErr;
425 #endif // defined(OS_MACOSX)
427 void RegisterComponentsForUpdate() {
428 component_updater::ComponentUpdateService* cus =
429 g_browser_process->component_updater();
431 // Registration can be before or after cus->Start() so it is ok to post
432 // a task to the UI thread to do registration once you done the necessary
433 // file IO to know you existing component version.
434 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
435 RegisterRecoveryComponent(cus, g_browser_process->local_state());
436 RegisterPepperFlashComponent(cus);
437 RegisterSwiftShaderComponent(cus);
438 RegisterWidevineCdmComponent(cus);
439 #endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
441 #if !defined(DISABLE_NACL) && !defined(OS_ANDROID)
442 #if defined(OS_CHROMEOS)
443 // PNaCl on Chrome OS is on rootfs and there is no need to download it. But
444 // Chrome4ChromeOS on Linux doesn't contain PNaCl so enable component
445 // installer when running on Linux. See crbug.com/422121 for more details.
446 if (!base::SysInfo::IsRunningOnChromeOS())
447 #endif // defined(OS_CHROMEOS)
448 g_browser_process->pnacl_component_installer()->RegisterPnaclComponent(cus);
449 #endif // !defined(DISABLE_NACL) && !defined(OS_ANDROID)
451 // Registration of the CLD Component is a no-op unless the CLD data source has
452 // been configured to be the "Component" data source.
453 RegisterCldComponent(cus);
455 component_updater::SupervisedUserWhitelistInstaller* whitelist_installer =
456 g_browser_process->supervised_user_whitelist_installer();
457 whitelist_installer->RegisterComponents();
459 base::FilePath path;
460 if (PathService::Get(chrome::DIR_USER_DATA, &path)) {
461 #if defined(OS_ANDROID)
462 // The CRLSet component was enabled for some releases. This code attempts to
463 // delete it from the local disk of those how may have downloaded it.
464 g_browser_process->crl_set_fetcher()->DeleteFromDisk(path);
465 #elif !defined(OS_CHROMEOS)
466 // CRLSetFetcher attempts to load a CRL set from either the local disk or
467 // network.
468 // For Chrome OS this registration is delayed until user login.
469 g_browser_process->crl_set_fetcher()->StartInitialLoad(cus, path);
470 // Registration of the EV Whitelist component here is not necessary for:
471 // 1. Android: Because it currently does not have the EV indicator.
472 // 2. Chrome OS: On Chrome OS this registration is delayed until user login.
473 RegisterEVWhitelistComponent(cus, path);
474 #endif // defined(OS_ANDROID)
477 #if defined(OS_WIN)
478 #if defined(GOOGLE_CHROME_BUILD)
479 RegisterSwReporterComponent(cus);
480 #endif // defined(GOOGLE_CHROME_BUILD)
481 RegisterCAPSComponent(cus);
482 #endif // defined(OS_WIN)
485 #if !defined(OS_ANDROID)
486 bool ProcessSingletonNotificationCallback(
487 const base::CommandLine& command_line,
488 const base::FilePath& current_directory) {
489 // Drop the request if the browser process is already in shutdown path.
490 if (!g_browser_process || g_browser_process->IsShuttingDown()) {
491 #if defined(OS_WIN)
492 browser_watcher::ExitFunnel::RecordSingleEvent(
493 chrome::kBrowserExitCodesRegistryPath,
494 L"ProcessSingletonIsShuttingDown");
495 #endif // defined(OS_WIN)
497 return false;
500 if (command_line.HasSwitch(switches::kOriginalProcessStartTime)) {
501 std::string start_time_string =
502 command_line.GetSwitchValueASCII(switches::kOriginalProcessStartTime);
503 int64 remote_start_time;
504 if (base::StringToInt64(start_time_string, &remote_start_time)) {
505 base::TimeDelta elapsed =
506 base::Time::Now() - base::Time::FromInternalValue(remote_start_time);
507 if (command_line.HasSwitch(switches::kFastStart)) {
508 UMA_HISTOGRAM_LONG_TIMES(
509 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed);
510 } else {
511 UMA_HISTOGRAM_LONG_TIMES(
512 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed);
517 g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing(
518 command_line);
520 base::FilePath user_data_dir =
521 g_browser_process->profile_manager()->user_data_dir();
522 base::FilePath startup_profile_dir =
523 GetStartupProfilePath(user_data_dir, command_line);
525 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
526 command_line, current_directory, startup_profile_dir);
527 return true;
529 #endif // !defined(OS_ANDROID)
531 void LaunchDevToolsHandlerIfNeeded(const base::CommandLine& command_line) {
532 if (command_line.HasSwitch(::switches::kRemoteDebuggingPort)) {
533 std::string port_str =
534 command_line.GetSwitchValueASCII(::switches::kRemoteDebuggingPort);
535 int port;
536 if (base::StringToInt(port_str, &port) && port >= 0 && port < 65535) {
537 g_browser_process->CreateDevToolsHttpProtocolHandler(
538 chrome::HOST_DESKTOP_TYPE_NATIVE,
539 "127.0.0.1",
540 static_cast<uint16>(port));
541 } else {
542 DLOG(WARNING) << "Invalid http debugger port number " << port;
547 base::StackSamplingProfiler::SamplingParams GetStartupSamplingParams() {
548 // Sample at 10Hz for 30 seconds.
549 base::StackSamplingProfiler::SamplingParams params;
550 params.initial_delay = base::TimeDelta::FromMilliseconds(0);
551 params.bursts = 1;
552 params.samples_per_burst = 300;
553 params.sampling_interval = base::TimeDelta::FromMilliseconds(100);
554 return params;
557 } // namespace
559 namespace chrome_browser {
561 // This error message is not localized because we failed to load the
562 // localization data files.
563 #if defined(OS_WIN)
564 const char kMissingLocaleDataTitle[] = "Missing File Error";
565 #endif // defined(OS_WIN)
567 #if defined(OS_WIN)
568 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
569 const char kMissingLocaleDataMessage[] =
570 "Unable to find locale data files. Please reinstall.";
571 #endif // defined(OS_WIN)
573 } // namespace chrome_browser
575 // BrowserMainParts ------------------------------------------------------------
577 ChromeBrowserMainParts::ChromeBrowserMainParts(
578 const content::MainFunctionParams& parameters)
579 : parameters_(parameters),
580 parsed_command_line_(parameters.command_line),
581 result_code_(content::RESULT_CODE_NORMAL_EXIT),
582 startup_watcher_(new StartupTimeBomb()),
583 shutdown_watcher_(new ShutdownWatcherHelper()),
584 browser_field_trials_(parameters.command_line),
585 sampling_profiler_(
586 base::PlatformThread::CurrentId(),
587 GetStartupSamplingParams(),
588 metrics::CallStackProfileMetricsProvider::GetProfilerCallback(
589 metrics::CallStackProfileMetricsProvider::Params(
590 metrics::CallStackProfileMetricsProvider::PROCESS_STARTUP,
591 false))),
592 profile_(NULL),
593 run_message_loop_(true),
594 notify_result_(ProcessSingleton::PROCESS_NONE),
595 local_state_(NULL),
596 restart_last_session_(false) {
597 const version_info::Channel channel = chrome::GetChannel();
598 if (channel == version_info::Channel::UNKNOWN ||
599 channel == version_info::Channel::CANARY ||
600 channel == version_info::Channel::DEV) {
601 sampling_profiler_.Start();
604 // If we're running tests (ui_task is non-null).
605 if (parameters.ui_task)
606 browser_defaults::enable_help_app = false;
608 // Chrome disallows cookies by default. All code paths that want to use
609 // cookies need to go through one of Chrome's URLRequestContexts which have
610 // a ChromeNetworkDelegate attached that selectively allows cookies again.
611 net::URLRequest::SetDefaultCookiePolicyToBlock();
614 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
615 for (int i = static_cast<int>(chrome_extra_parts_.size())-1; i >= 0; --i)
616 delete chrome_extra_parts_[i];
617 chrome_extra_parts_.clear();
620 // This will be called after the command-line has been mutated by about:flags
621 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
622 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
623 // Must initialize metrics after labs have been converted into switches,
624 // but before field trials are set up (so that client ID is available for
625 // one-time randomized field trials).
627 // Initialize FieldTrialList to support FieldTrials that use one-time
628 // randomization.
629 metrics::MetricsService* metrics = browser_process_->metrics_service();
630 field_trial_list_.reset(
631 new base::FieldTrialList(metrics->CreateEntropyProvider().release()));
633 const base::CommandLine* command_line =
634 base::CommandLine::ForCurrentProcess();
635 if (command_line->HasSwitch(switches::kEnableBenchmarking) ||
636 command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking)) {
637 base::FieldTrial::EnableBenchmarking();
640 if (command_line->HasSwitch(switches::kForceFieldTrialParams)) {
641 bool result = chrome_variations::AssociateParamsFromString(
642 command_line->GetSwitchValueASCII(switches::kForceFieldTrialParams));
643 CHECK(result) << "Invalid --" << switches::kForceFieldTrialParams
644 << " list specified.";
647 // Ensure any field trials specified on the command line are initialized.
648 if (command_line->HasSwitch(switches::kForceFieldTrials)) {
649 std::set<std::string> unforceable_field_trials;
650 #if defined(OFFICIAL_BUILD)
651 unforceable_field_trials.insert("SettingsEnforcement");
652 #endif // defined(OFFICIAL_BUILD)
654 // Create field trials without activating them, so that this behaves in a
655 // consistent manner with field trials created from the server.
656 bool result = base::FieldTrialList::CreateTrialsFromString(
657 command_line->GetSwitchValueASCII(switches::kForceFieldTrials),
658 base::FieldTrialList::DONT_ACTIVATE_TRIALS,
659 unforceable_field_trials);
660 CHECK(result) << "Invalid --" << switches::kForceFieldTrials
661 << " list specified.";
664 #if defined(FIELDTRIAL_TESTING_ENABLED)
665 if (!command_line->HasSwitch(switches::kDisableFieldTrialTestingConfig) &&
666 !command_line->HasSwitch(switches::kForceFieldTrials) &&
667 !command_line->HasSwitch(
668 chrome_variations::switches::kVariationsServerURL))
669 chrome_variations::AssociateDefaultFieldTrialConfig();
670 #endif // defined(FIELDTRIAL_TESTING_ENABLED)
672 if (command_line->HasSwitch(switches::kForceVariationIds)) {
673 // Create default variation ids which will always be included in the
674 // X-Client-Data request header.
675 variations::VariationsHttpHeaderProvider* provider =
676 variations::VariationsHttpHeaderProvider::GetInstance();
677 bool result = provider->SetDefaultVariationIds(
678 command_line->GetSwitchValueASCII(switches::kForceVariationIds));
679 CHECK(result) << "Invalid --" << switches::kForceVariationIds
680 << " list specified.";
681 metrics->AddSyntheticTrialObserver(provider);
683 chrome_variations::VariationsService* variations_service =
684 browser_process_->variations_service();
685 if (variations_service)
686 variations_service->CreateTrialsFromSeed();
688 // This must be called after |local_state_| is initialized.
689 browser_field_trials_.SetupFieldTrials();
691 // Enable Navigation Tracing only if a trace upload url is specified.
692 if (command_line->HasSwitch(switches::kEnableNavigationTracing) &&
693 command_line->HasSwitch(switches::kTraceUploadURL)) {
694 tracing::SetupNavigationTracing();
697 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
698 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
699 // Even though base::Bind does AddRef and Release, the object will not be
700 // deleted after the Task is executed.
701 field_trial_synchronizer_ = new FieldTrialSynchronizer();
703 // Now that field trials have been created, initializes metrics recording.
704 metrics->InitializeMetricsRecordingState();
706 const version_info::Channel channel = chrome::GetChannel();
708 // TODO(dalecurtis): Remove these checks and enable for all channels once we
709 // track down the root causes of crbug.com/422522 and crbug.com/478932.
710 if (channel == version_info::Channel::UNKNOWN ||
711 channel == version_info::Channel::CANARY ||
712 channel == version_info::Channel::DEV) {
713 media::AudioManager::EnableHangMonitor();
716 // Enable profiler instrumentation depending on the channel.
717 switch (channel) {
718 case version_info::Channel::UNKNOWN:
719 case version_info::Channel::CANARY:
720 tracked_objects::ScopedTracker::Enable();
721 break;
723 case version_info::Channel::DEV:
724 case version_info::Channel::BETA:
725 case version_info::Channel::STABLE:
726 // Don't enable instrumentation.
727 break;
731 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
733 void ChromeBrowserMainParts::StartMetricsRecording() {
734 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
736 g_browser_process->metrics_service()->CheckForClonedInstall(
737 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
739 g_browser_process->GetMetricsServicesManager()->UpdateUploadPermissions(true);
742 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
743 // Don't record any metrics if UI was displayed before this point e.g.
744 // warning dialogs.
745 if (startup_metric_utils::WasNonBrowserUIDisplayed())
746 return;
748 bool is_first_run = false;
749 #if !defined(OS_ANDROID)
750 // On Android, first run is handled in Java code, and the C++ side of Chrome
751 // doesn't know if this is the first run. This will cause some inaccuracy in
752 // the UMA statistics, but this should be minor (first runs are rare).
753 is_first_run = first_run::IsChromeFirstRun();
754 #endif // defined(OS_ANDROID)
756 // Record collected startup metrics.
757 startup_metric_utils::RecordBrowserMainMessageLoopStart(base::Time::Now(),
758 is_first_run);
761 // -----------------------------------------------------------------------------
762 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
764 #if defined(OS_WIN)
765 #define DLLEXPORT __declspec(dllexport)
767 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
768 extern "C" {
769 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded();
772 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
773 // Need an instance of AtExitManager to handle singleton creations and
774 // deletions. We need this new instance because, the old instance created
775 // in ChromeMain() got destructed when the function returned.
776 base::AtExitManager exit_manager;
777 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
779 #endif
781 // content::BrowserMainParts implementation ------------------------------------
783 void ChromeBrowserMainParts::PreEarlyInitialization() {
784 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
785 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
786 chrome_extra_parts_[i]->PreEarlyInitialization();
789 void ChromeBrowserMainParts::PostEarlyInitialization() {
790 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
791 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
792 chrome_extra_parts_[i]->PostEarlyInitialization();
795 void ChromeBrowserMainParts::ToolkitInitialized() {
796 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
797 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
798 chrome_extra_parts_[i]->ToolkitInitialized();
801 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
802 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
804 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
805 chrome_extra_parts_[i]->PreMainMessageLoopStart();
808 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
809 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
811 // device_event_log must be initialized after the message loop. Calls to
812 // {DEVICE}_LOG prior to here will only be logged with VLOG. Some
813 // platforms (e.g. chromeos) may have already initialized this.
814 if (!device_event_log::IsInitialized())
815 device_event_log::Initialize(0 /* default max entries */);
817 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
818 chrome_extra_parts_[i]->PostMainMessageLoopStart();
821 int ChromeBrowserMainParts::PreCreateThreads() {
822 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
823 result_code_ = PreCreateThreadsImpl();
825 if (result_code_ == content::RESULT_CODE_NORMAL_EXIT) {
826 #if !defined(OS_ANDROID)
827 // These members must be initialized before exiting this function normally.
828 DCHECK(master_prefs_.get());
829 DCHECK(browser_creator_.get());
830 #endif // !defined(OS_ANDROID)
831 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
832 chrome_extra_parts_[i]->PreCreateThreads();
835 return result_code_;
838 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
839 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
840 run_message_loop_ = false;
841 #if !defined(OS_ANDROID)
842 chrome::MaybeShowInvalidUserDataDirWarningDialog();
843 #endif // !defined(OS_ANDROID)
844 if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir_))
845 return chrome::RESULT_CODE_MISSING_DATA;
847 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
848 MediaCaptureDevicesDispatcher::GetInstance();
850 // Android's first run is done in Java instead of native.
851 #if !defined(OS_ANDROID)
852 process_singleton_.reset(new ChromeProcessSingleton(
853 user_data_dir_, base::Bind(&ProcessSingletonNotificationCallback)));
855 // Cache first run state early.
856 first_run::IsChromeFirstRun();
857 #endif // !defined(OS_ANDROID)
859 scoped_refptr<base::SequencedTaskRunner> local_state_task_runner =
860 JsonPrefStore::GetTaskRunnerForFile(
861 base::FilePath(chrome::kLocalStorePoolName),
862 BrowserThread::GetBlockingPool());
865 TRACE_EVENT0("startup",
866 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
867 browser_process_.reset(new BrowserProcessImpl(local_state_task_runner.get(),
868 parsed_command_line()));
871 if (parsed_command_line().HasSwitch(switches::kEnableProfiling)) {
872 TRACE_EVENT0("startup",
873 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
874 // User wants to override default tracking status.
875 std::string flag =
876 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling);
877 // Default to basic profiling (no parent child support).
878 tracked_objects::ThreadData::Status status =
879 tracked_objects::ThreadData::PROFILING_ACTIVE;
880 if (flag.compare("0") != 0)
881 status = tracked_objects::ThreadData::DEACTIVATED;
882 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status);
885 local_state_ = InitializeLocalState(
886 local_state_task_runner.get(), parsed_command_line());
888 #if !defined(OS_ANDROID)
889 // These members must be initialized before returning from this function.
890 master_prefs_.reset(new first_run::MasterPrefs);
891 // Android doesn't use StartupBrowserCreator.
892 browser_creator_.reset(new StartupBrowserCreator);
893 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
894 chrome::UMABrowsingActivityObserver::Init();
895 #endif // !defined(OS_ANDROID)
897 #if !defined(OS_CHROMEOS)
898 // Convert active labs into switches. This needs to be done before
899 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
900 // affected by experiment flags (--touch-optimized-ui in particular).
901 // On ChromeOS system level flags are applied from the device settings from
902 // the session manager.
904 TRACE_EVENT0("startup",
905 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
906 about_flags::PrefServiceFlagsStorage flags_storage_(
907 g_browser_process->local_state());
908 about_flags::ConvertFlagsToSwitches(&flags_storage_,
909 base::CommandLine::ForCurrentProcess(),
910 about_flags::kAddSentinels);
912 #endif // !defined(OS_CHROMEOS)
914 #if defined(OS_WIN)
915 // This is needed to enable ETW exporting when requested in about:flags.
916 // Normally, we enable it in ContentMainRunnerImpl::Initialize when the flag
917 // is present on the command line but flags in about:flags are converted only
918 // after this function runs. Note that this starts exporting later which
919 // affects tracing the browser startup. Also, this is only relevant for the
920 // browser process, as other processes will get all the flags on their command
921 // line regardless of the origin (command line or about:flags).
922 if (parsed_command_line().HasSwitch(switches::kTraceExportEventsToETW))
923 base::trace_event::TraceEventETWExport::EnableETWExport();
924 #endif // OS_WIN
926 local_state_->UpdateCommandLinePrefStore(
927 new CommandLinePrefStore(base::CommandLine::ForCurrentProcess()));
929 // Reset the command line in the crash report details, since we may have
930 // just changed it to include experiments.
931 crash_keys::SetSwitchesFromCommandLine(
932 base::CommandLine::ForCurrentProcess());
934 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
935 // needed when loading the MainMenu.nib and the language doesn't depend on
936 // anything since it comes from Cocoa.
937 #if defined(OS_MACOSX)
938 std::string locale =
939 parameters().ui_task ? "en-US" : l10n_util::GetLocaleOverride();
940 browser_process_->SetApplicationLocale(locale);
941 #else
942 const std::string locale =
943 local_state_->GetString(prefs::kApplicationLocale);
945 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
946 // method InitSharedInstance is ignored.
948 TRACE_EVENT_BEGIN0("startup",
949 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
950 const std::string loaded_locale =
951 ui::ResourceBundle::InitSharedInstanceWithLocale(
952 locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
953 TRACE_EVENT_END0("startup",
954 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
956 if (loaded_locale.empty() &&
957 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs)) {
958 ShowMissingLocaleMessageBox();
959 return chrome::RESULT_CODE_MISSING_DATA;
961 CHECK(!loaded_locale.empty()) << "Locale could not be found for " << locale;
962 browser_process_->SetApplicationLocale(loaded_locale);
965 TRACE_EVENT0("startup",
966 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
967 base::FilePath resources_pack_path;
968 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
969 #if defined(OS_ANDROID)
970 ui::LoadMainAndroidPackFile("assets/resources.pak", resources_pack_path);
971 #else
972 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
973 resources_pack_path, ui::SCALE_FACTOR_NONE);
974 #endif // defined(OS_ANDROID)
976 #endif // defined(OS_MACOSX)
978 // Android does first run in Java instead of native.
979 // Chrome OS has its own out-of-box-experience code.
980 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
981 // On first run, we need to process the predictor preferences before the
982 // browser's profile_manager object is created, but after ResourceBundle
983 // is initialized.
984 if (first_run::IsChromeFirstRun()) {
985 first_run::ProcessMasterPreferencesResult pmp_result =
986 first_run::ProcessMasterPreferences(user_data_dir_,
987 master_prefs_.get());
988 if (pmp_result == first_run::EULA_EXIT_NOW)
989 return chrome::RESULT_CODE_EULA_REFUSED;
991 if (!parsed_command_line().HasSwitch(switches::kApp) &&
992 !parsed_command_line().HasSwitch(switches::kAppId) &&
993 !parsed_command_line().HasSwitch(switches::kShowAppList)) {
994 AddFirstRunNewTabs(browser_creator_.get(), master_prefs_->new_tabs);
997 // TODO(macourteau): refactor preferences that are copied from
998 // master_preferences into local_state, as a "local_state" section in
999 // master preferences. If possible, a generic solution would be preferred
1000 // over a copy one-by-one of specific preferences. Also see related TODO
1001 // in first_run.h.
1003 // Store the initial VariationsService seed in local state, if it exists
1004 // in master prefs.
1005 if (!master_prefs_->variations_seed.empty() ||
1006 !master_prefs_->compressed_variations_seed.empty()) {
1007 if (!master_prefs_->variations_seed.empty()) {
1008 local_state_->SetString(chrome_variations::prefs::kVariationsSeed,
1009 master_prefs_->variations_seed);
1011 if (!master_prefs_->compressed_variations_seed.empty()) {
1012 local_state_->SetString(
1013 chrome_variations::prefs::kVariationsCompressedSeed,
1014 master_prefs_->compressed_variations_seed);
1016 if (!master_prefs_->variations_seed_signature.empty()) {
1017 local_state_->SetString(
1018 chrome_variations::prefs::kVariationsSeedSignature,
1019 master_prefs_->variations_seed_signature);
1021 // Set the variation seed date to the current system time. If the user's
1022 // clock is incorrect, this may cause some field trial expiry checks to
1023 // not do the right thing until the next seed update from the server,
1024 // when this value will be updated.
1025 local_state_->SetInt64(chrome_variations::prefs::kVariationsSeedDate,
1026 base::Time::Now().ToInternalValue());
1029 if (!master_prefs_->suppress_default_browser_prompt_for_version.empty()) {
1030 local_state_->SetString(
1031 prefs::kBrowserSuppressDefaultBrowserPrompt,
1032 master_prefs_->suppress_default_browser_prompt_for_version);
1035 #if defined(OS_WIN)
1036 if (!master_prefs_->welcome_page_on_os_upgrade_enabled)
1037 local_state_->SetBoolean(prefs::kWelcomePageOnOSUpgradeEnabled, false);
1038 #endif
1040 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1042 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
1043 // Set the product channel for crash reports.
1044 base::debug::SetCrashKeyValue(crash_keys::kChannel,
1045 chrome::GetChannelString());
1046 #endif // defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
1048 // Initialize tracking synchronizer system.
1049 tracking_synchronizer_ = new metrics::TrackingSynchronizer(
1050 make_scoped_ptr(new base::DefaultTickClock()));
1052 #if defined(OS_MACOSX)
1053 // Get the Keychain API to register for distributed notifications on the main
1054 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
1055 // which doesn't. This ensures those notifications will get delivered
1056 // properly. See issue 37766.
1057 // (Note that the callback mask here is empty. I don't want to register for
1058 // any callbacks, I just want to initialize the mechanism.)
1059 SecKeychainAddCallback(&KeychainCallback, 0, NULL);
1060 #endif // defined(OS_MACOSX)
1062 #if defined(OS_CHROMEOS)
1063 // Must be done after g_browser_process is constructed, before
1064 // SetupMetricsAndFieldTrials().
1065 chromeos::CrosSettings::Initialize();
1066 #endif // defined(OS_CHROMEOS)
1068 // Now the command line has been mutated based on about:flags, we can setup
1069 // metrics and initialize field trials. The field trials are needed by
1070 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
1071 SetupMetricsAndFieldTrials();
1073 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
1074 browser_process_->PreCreateThreads();
1076 return content::RESULT_CODE_NORMAL_EXIT;
1079 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
1080 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1081 TRACK_SCOPED_REGION(
1082 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1084 result_code_ = PreMainMessageLoopRunImpl();
1086 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1087 chrome_extra_parts_[i]->PreMainMessageLoopRun();
1090 // PreMainMessageLoopRun calls these extra stages in the following order:
1091 // PreMainMessageLoopRunImpl()
1092 // ... initial setup, including browser_process_ setup.
1093 // PreProfileInit()
1094 // ... additional setup, including CreateProfile()
1095 // PostProfileInit()
1096 // ... additional setup
1097 // PreBrowserStart()
1098 // ... browser_creator_->Start (OR parameters().ui_task->Run())
1099 // PostBrowserStart()
1101 void ChromeBrowserMainParts::PreProfileInit() {
1102 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1104 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1105 chrome_extra_parts_[i]->PreProfileInit();
1107 #if !defined(OS_ANDROID)
1108 // Initialize the feedback uploader so it can setup notifications for profile
1109 // creation.
1110 feedback::FeedbackProfileObserver::Initialize();
1112 // Ephemeral profiles may have been left behind if the browser crashed.
1113 g_browser_process->profile_manager()->CleanUpEphemeralProfiles();
1114 #endif // !defined(OS_ANDROID)
1116 #if defined(ENABLE_EXTENSIONS)
1117 javascript_dialog_extensions_client::InstallClient();
1118 #endif // defined(ENABLE_EXTENSIONS)
1120 #if !defined(OS_IOS)
1121 InstallChromeJavaScriptNativeDialogFactory();
1122 #endif // !defined(OS_IOS)
1125 void ChromeBrowserMainParts::PostProfileInit() {
1126 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1128 #if defined(OS_ANDROID)
1129 DevToolsDiscoveryProviderAndroid::Install();
1130 #else
1131 ChromeDevToolsDiscoveryProvider::Install();
1132 #endif // defined(OS_ANDROID)
1134 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1135 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1136 chrome_extra_parts_[i]->PostProfileInit();
1139 void ChromeBrowserMainParts::PreBrowserStart() {
1140 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1141 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1142 chrome_extra_parts_[i]->PreBrowserStart();
1144 three_d_observer_.reset(new ThreeDAPIObserver());
1146 // Start the out-of-memory priority manager here so that we give the most
1147 // amount of time for the other services to start up before we start
1148 // adjusting the oom priority.
1150 // On CrOS, it is always enabled. On other platforms, it's behind a flag for
1151 // now.
1152 #if defined(OS_CHROMEOS)
1153 g_browser_process->GetOomPriorityManager()->Start();
1154 #elif defined(OS_WIN) || defined(OS_MACOSX)
1155 const std::string group_name =
1156 base::FieldTrialList::FindFullName("AutomaticTabDiscarding");
1157 if (parsed_command_line().HasSwitch(switches::kEnableTabDiscarding) ||
1158 base::StartsWith(group_name, "Enabled", base::CompareCase::SENSITIVE)) {
1159 g_browser_process->GetOomPriorityManager()->Start();
1161 #endif
1164 void ChromeBrowserMainParts::PostBrowserStart() {
1165 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1166 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1167 chrome_extra_parts_[i]->PostBrowserStart();
1168 #if !defined(OS_ANDROID)
1169 // Allow ProcessSingleton to process messages.
1170 process_singleton_->Unlock();
1171 #endif // !defined(OS_ANDROID)
1172 #if defined(ENABLE_WEBRTC)
1173 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1174 // to reduce the impact on startup time.
1175 BrowserThread::PostDelayedTask(
1176 BrowserThread::UI,
1177 FROM_HERE,
1178 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles),
1179 base::TimeDelta::FromMinutes(1));
1180 #endif // defined(ENABLE_WEBRTC)
1182 // At this point, StartupBrowserCreator::Start has run creating initial
1183 // browser windows and tabs, but no progress has been made in loading
1184 // content as the main message loop hasn't started processing tasks yet.
1185 // We setup to observe to the initial page load here to defer running
1186 // task posted via PostAfterStartupTask until its complete.
1187 AfterStartupTaskUtils::StartMonitoringStartup();
1190 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1191 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1192 TRACK_SCOPED_REGION(
1193 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1195 SCOPED_UMA_HISTOGRAM_LONG_TIMER("Startup.PreMainMessageLoopRunImplLongTime");
1196 const base::TimeTicks start_time_step1 = base::TimeTicks::Now();
1198 #if defined(OS_WIN)
1199 // Windows parental controls calls can be slow, so we do an early init here
1200 // that calculates this value off of the UI thread.
1201 IncognitoModePrefs::InitializePlatformParentalControls();
1202 #endif
1204 #if defined(ENABLE_EXTENSIONS)
1205 if (!variations::GetVariationParamValue(
1206 "LightSpeed", "EarlyInitStartup").empty()) {
1207 // Try to compute this early on another thread so that we don't spend time
1208 // during profile load initializing the extensions APIs.
1209 BrowserThread::PostTask(
1210 BrowserThread::FILE_USER_BLOCKING,
1211 FROM_HERE,
1212 base::Bind(
1213 base::IgnoreResult(&extensions::FeatureProvider::GetAPIFeatures)));
1215 #endif
1217 // Android updates the metrics service dynamically depending on whether the
1218 // application is in the foreground or not. Do not start here.
1219 #if !defined(OS_ANDROID)
1220 // Now that the file thread has been started, start recording.
1221 StartMetricsRecording();
1222 #endif // !defined(OS_ANDROID)
1224 if (!base::debug::BeingDebugged()) {
1225 // Create watchdog thread after creating all other threads because it will
1226 // watch the other threads and they must be running.
1227 browser_process_->watchdog_thread();
1230 // Do any initializating in the browser process that requires all threads
1231 // running.
1232 browser_process_->PreMainMessageLoopRun();
1234 // Record last shutdown time into a histogram.
1235 browser_shutdown::ReadLastShutdownInfo();
1237 #if defined(OS_WIN)
1238 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1239 // tasks. Those care whether the browser is already running. On Linux/Mac,
1240 // upgrade/uninstall happen separately.
1241 bool already_running = browser_util::IsBrowserAlreadyRunning();
1243 // If the command line specifies 'uninstall' then we need to work here
1244 // unless we detect another chrome browser running.
1245 if (parsed_command_line().HasSwitch(switches::kUninstall)) {
1246 return DoUninstallTasks(already_running);
1249 if (parsed_command_line().HasSwitch(switches::kHideIcons) ||
1250 parsed_command_line().HasSwitch(switches::kShowIcons)) {
1251 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1252 parsed_command_line_);
1255 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
1256 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
1257 #endif // defined(OS_WIN)
1259 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser)) {
1260 bool is_managed = g_browser_process->local_state()->IsManagedPreference(
1261 prefs::kDefaultBrowserSettingEnabled);
1262 if (is_managed && !g_browser_process->local_state()->GetBoolean(
1263 prefs::kDefaultBrowserSettingEnabled)) {
1264 return static_cast<int>(chrome::RESULT_CODE_ACTION_DISALLOWED_BY_POLICY);
1267 return ShellIntegration::SetAsDefaultBrowser() ?
1268 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT) :
1269 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED);
1272 #if defined(USE_AURA)
1273 // Make sure aura::Env has been initialized.
1274 CHECK(aura::Env::GetInstance());
1275 #endif // defined(USE_AURA)
1277 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1278 #if !defined(OS_ANDROID)
1279 // If the command line specifies --pack-extension, attempt the pack extension
1280 // startup action and exit.
1281 if (parsed_command_line().HasSwitch(switches::kPackExtension)) {
1282 extensions::StartupHelper extension_startup_helper;
1283 if (extension_startup_helper.PackExtension(parsed_command_line()))
1284 return content::RESULT_CODE_NORMAL_EXIT;
1285 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR;
1288 // When another process is running, use that process instead of starting a
1289 // new one. NotifyOtherProcess will currently give the other process up to
1290 // 20 seconds to respond. Note that this needs to be done before we attempt
1291 // to read the profile.
1292 notify_result_ = process_singleton_->NotifyOtherProcessOrCreate();
1293 switch (notify_result_) {
1294 case ProcessSingleton::PROCESS_NONE:
1295 // No process already running, fall through to starting a new one.
1296 break;
1298 case ProcessSingleton::PROCESS_NOTIFIED:
1299 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1300 // On POSIX systems, print a message notifying the process is running.
1301 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1302 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER))).c_str());
1303 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
1305 // Having a differentiated return type for testing allows for tests to
1306 // verify proper handling of some switches. When not testing, stick to
1307 // the standard Unix convention of returning zero when things went as
1308 // expected.
1309 if (parsed_command_line().HasSwitch(switches::kTestType))
1310 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED;
1311 return content::RESULT_CODE_NORMAL_EXIT;
1313 case ProcessSingleton::PROFILE_IN_USE:
1314 return chrome::RESULT_CODE_PROFILE_IN_USE;
1316 case ProcessSingleton::LOCK_ERROR:
1317 LOG(ERROR) << "Failed to create a ProcessSingleton for your profile "
1318 "directory. This means that running multiple instances "
1319 "would start multiple browser processes rather than "
1320 "opening a new window in the existing process. Aborting "
1321 "now to avoid profile corruption.";
1322 return chrome::RESULT_CODE_PROFILE_IN_USE;
1324 default:
1325 NOTREACHED();
1327 #endif // !defined(OS_ANDROID)
1329 // Handle special early return paths (which couldn't be processed even earlier
1330 // as they require the process singleton to be held) first.
1332 std::string try_chrome =
1333 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain);
1334 if (!try_chrome.empty()) {
1335 #if defined(OS_WIN)
1336 // Setup.exe has determined that we need to run a retention experiment
1337 // and has lauched chrome to show the experiment UI. It is guaranteed that
1338 // no other Chrome is currently running as the process singleton was
1339 // sucessfully grabbed above.
1340 int try_chrome_int;
1341 base::StringToInt(try_chrome, &try_chrome_int);
1342 TryChromeDialogView::Result answer = TryChromeDialogView::Show(
1343 try_chrome_int,
1344 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog,
1345 base::Unretained(process_singleton_.get())));
1346 if (answer == TryChromeDialogView::NOT_NOW)
1347 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL;
1348 if (answer == TryChromeDialogView::UNINSTALL_CHROME)
1349 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2;
1350 // At this point the user is willing to try chrome again.
1351 if (answer == TryChromeDialogView::TRY_CHROME_AS_DEFAULT) {
1352 // Only set in the unattended case, the interactive case is Windows 8.
1353 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1354 ShellIntegration::SET_DEFAULT_UNATTENDED)
1355 ShellIntegration::SetAsDefaultBrowser();
1357 #else
1358 // We don't support retention experiments on Mac or Linux.
1359 return content::RESULT_CODE_NORMAL_EXIT;
1360 #endif // defined(OS_WIN)
1363 #if defined(OS_WIN)
1364 // Do the tasks if chrome has been upgraded while it was last running.
1365 if (!already_running && upgrade_util::DoUpgradeTasks(parsed_command_line()))
1366 return content::RESULT_CODE_NORMAL_EXIT;
1368 // Check if there is any machine level Chrome installed on the current
1369 // machine. If yes and the current Chrome process is user level, we do not
1370 // allow the user level Chrome to run. So we notify the user and uninstall
1371 // user level Chrome.
1372 // Note this check needs to happen here (after the process singleton was
1373 // obtained but before potentially creating the first run sentinel).
1374 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1375 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS;
1376 #endif // defined(OS_WIN)
1378 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1379 if (sxs_linux::ShouldMigrateUserDataDir())
1380 return sxs_linux::MigrateUserDataDir();
1381 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1383 // Desktop construction occurs here, (required before profile creation).
1384 PreProfileInit();
1386 // Profile creation ----------------------------------------------------------
1388 metrics::MetricsService::SetExecutionPhase(
1389 metrics::MetricsService::CREATE_PROFILE,
1390 g_browser_process->local_state());
1392 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep1Time",
1393 base::TimeTicks::Now() - start_time_step1);
1395 // This step is costly and is already measured in Startup.CreateFirstProfile
1396 // and more directly Profile.CreateAndInitializeProfile.
1397 profile_ = CreatePrimaryProfile(parameters(),
1398 user_data_dir_,
1399 parsed_command_line());
1400 if (!profile_)
1401 return content::RESULT_CODE_NORMAL_EXIT;
1403 #if !defined(OS_ANDROID)
1404 const base::TimeTicks start_time_step2 = base::TimeTicks::Now();
1405 // The first run sentinel must be created after the process singleton was
1406 // grabbed and no early return paths were otherwise hit above.
1407 first_run::CreateSentinelIfNeeded();
1408 #endif // !defined(OS_ANDROID)
1410 #if defined(ENABLE_BACKGROUND)
1411 // Autoload any profiles which are running background apps.
1412 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1413 browser_process_->profile_manager()->AutoloadProfiles();
1414 #endif // defined(ENABLE_BACKGROUND)
1415 // Post-profile init ---------------------------------------------------------
1417 TranslateService::Initialize();
1419 // Needs to be done before PostProfileInit, since login manager on CrOS is
1420 // called inside PostProfileInit.
1421 content::WebUIControllerFactory::RegisterFactory(
1422 ChromeWebUIControllerFactory::GetInstance());
1424 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1425 // So make sure to create it before that.
1426 #if !defined(DISABLE_NACL)
1427 NaClBrowserDelegateImpl* delegate =
1428 new NaClBrowserDelegateImpl(browser_process_->profile_manager());
1429 nacl::NaClBrowser::SetDelegate(delegate);
1430 #endif // !defined(DISABLE_NACL)
1432 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1433 // (requires supporting early exit).
1434 PostProfileInit();
1436 // Retrieve cached GL strings from local state and use them for GPU
1437 // blacklist decisions.
1438 if (g_browser_process->gl_string_manager())
1439 g_browser_process->gl_string_manager()->Initialize();
1441 // Create an instance of GpuModeManager to watch gpu mode pref change.
1442 g_browser_process->gpu_mode_manager();
1444 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1445 // Show the First Run UI if this is the first time Chrome has been run on
1446 // this computer, or we're being compelled to do so by a command line flag.
1447 // Note that this be done _after_ the PrefService is initialized and all
1448 // preferences are registered, since some of the code that the importer
1449 // touches reads preferences.
1450 if (first_run::IsChromeFirstRun()) {
1451 first_run::AutoImport(profile_,
1452 master_prefs_->homepage_defined,
1453 master_prefs_->do_import_items,
1454 master_prefs_->dont_import_items,
1455 master_prefs_->import_bookmarks_path);
1457 // Note: this can pop the first run consent dialog on linux.
1458 first_run::DoPostImportTasks(profile_,
1459 master_prefs_->make_chrome_default_for_user);
1461 if (!master_prefs_->suppress_first_run_default_browser_prompt) {
1462 browser_creator_->set_show_main_browser_window(
1463 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_));
1464 } else {
1465 browser_creator_->set_is_default_browser_dialog_suppressed(true);
1468 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1470 #if defined(OS_WIN)
1471 // Sets things up so that if we crash from this point on, a dialog will
1472 // popup asking the user to restart chrome. It is done this late to avoid
1473 // testing against a bunch of special cases that are taken care early on.
1474 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1475 parsed_command_line());
1477 // Registers Chrome with the Windows Restart Manager, which will restore the
1478 // Chrome session when the computer is restarted after a system update.
1479 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1480 // but should run on startup if extended to handle crashes/hangs/patches.
1481 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1482 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
1483 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1484 parsed_command_line());
1487 // Verify that the profile is not on a network share and if so prepare to show
1488 // notification to the user.
1489 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_)) {
1490 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
1491 base::Bind(&NetworkProfileBubble::CheckNetworkProfile,
1492 profile_->GetPath()));
1494 #endif // defined(OS_WIN)
1496 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1497 // Init the RLZ library. This just binds the dll and schedules a task on the
1498 // file thread to be run sometime later. If this is the first run we record
1499 // the installation event.
1500 PrefService* pref_service = profile_->GetPrefs();
1501 int ping_delay = first_run::IsChromeFirstRun() ? master_prefs_->ping_delay :
1502 pref_service->GetInteger(first_run::GetPingDelayPrefName().c_str());
1503 // Negative ping delay means to send ping immediately after a first search is
1504 // recorded.
1505 rlz::RLZTracker::SetRlzDelegate(
1506 make_scoped_ptr(new ChromeRLZTrackerDelegate));
1507 rlz::RLZTracker::InitRlzDelayed(
1508 first_run::IsChromeFirstRun(), ping_delay < 0,
1509 base::TimeDelta::FromMilliseconds(abs(ping_delay)),
1510 ChromeRLZTrackerDelegate::IsGoogleDefaultSearch(profile_),
1511 ChromeRLZTrackerDelegate::IsGoogleHomepage(profile_),
1512 ChromeRLZTrackerDelegate::IsGoogleInStartpages(profile_));
1513 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1515 // Configure modules that need access to resources.
1516 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider);
1518 // In unittest mode, this will do nothing. In normal mode, this will create
1519 // the global IntranetRedirectDetector instance, which will promptly go to
1520 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1521 // to see if it should do anything else.
1523 // A simpler way of doing all this would be to have some function which could
1524 // give the time elapsed since startup, and simply have this object check that
1525 // when asked to initialize itself, but this doesn't seem to exist.
1527 // This can't be created in the BrowserProcessImpl constructor because it
1528 // needs to read prefs that get set after that runs.
1529 browser_process_->intranet_redirect_detector();
1530 GoogleSearchCounter::RegisterForNotifications();
1532 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1533 if (parsed_command_line().HasSwitch(switches::kDebugPrint)) {
1534 base::FilePath path =
1535 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint);
1536 printing::PrintedDocument::set_debug_dump_path(path);
1538 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1540 HandleTestParameters(parsed_command_line());
1541 browser_process_->metrics_service()->RecordBreakpadHasDebugger(
1542 base::debug::BeingDebugged());
1544 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1545 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1546 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1547 browser_process_->GetApplicationLocale());
1549 // Start watching for hangs during startup. We disarm this hang detector when
1550 // ThreadWatcher takes over or when browser is shutdown or when
1551 // startup_watcher_ is deleted.
1552 metrics::MetricsService::SetExecutionPhase(
1553 metrics::MetricsService::STARTUP_TIMEBOMB_ARM,
1554 g_browser_process->local_state());
1555 startup_watcher_->Arm(base::TimeDelta::FromSeconds(600));
1557 // On mobile, need for clean shutdown arises only when the application comes
1558 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1559 // http://crbug.com/179143
1560 #if !defined(OS_ANDROID)
1561 // Start watching for a hang.
1562 browser_process_->metrics_service()->LogNeedForCleanShutdown();
1563 #endif // !defined(OS_ANDROID)
1565 #if defined(ENABLE_PRINT_PREVIEW)
1566 // Create the instance of the cloud print proxy service so that it can launch
1567 // the service process if needed. This is needed because the service process
1568 // might have shutdown because an update was available.
1569 // TODO(torne): this should maybe be done with
1570 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1571 // instead?
1572 CloudPrintProxyServiceFactory::GetForProfile(profile_);
1573 #endif // defined(ENABLE_PRINT_PREVIEW)
1575 // Start watching all browser threads for responsiveness.
1576 metrics::MetricsService::SetExecutionPhase(
1577 metrics::MetricsService::THREAD_WATCHER_START,
1578 g_browser_process->local_state());
1579 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1581 #if defined(OS_ANDROID)
1582 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1583 #endif // defined(OS_ANDROID)
1585 #if !defined(DISABLE_NACL)
1586 BrowserThread::PostTask(
1587 BrowserThread::IO,
1588 FROM_HERE,
1589 base::Bind(nacl::NaClProcessHost::EarlyStartup));
1590 #endif // !defined(DISABLE_NACL)
1592 // Make sure initial prefs are recorded
1593 PrefMetricsService::Factory::GetForProfile(profile_);
1595 PreBrowserStart();
1597 // Instantiate the notification UI manager, as this triggers a perf timer
1598 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1599 // triggering the timer and call that explicitly in the approprate place.
1600 // http://crbug.com/105065.
1601 browser_process_->notification_ui_manager();
1603 // This must be called prior to RegisterComponentsForUpdate, in case the CLD
1604 // data source is based on the Component Updater.
1605 translate::BrowserCldUtils::ConfigureDefaultDataProvider();
1607 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate))
1608 RegisterComponentsForUpdate();
1610 #if defined(OS_ANDROID)
1611 chrome_variations::VariationsService* variations_service =
1612 browser_process_->variations_service();
1613 if (variations_service) {
1614 // Just initialize the policy prefs service here. Variations seed fetching
1615 // will be initialized when the app enters foreground mode.
1616 variations_service->set_policy_pref_service(profile_->GetPrefs());
1618 translate::TranslateDownloadManager::RequestLanguageList(
1619 profile_->GetPrefs());
1621 #else
1622 // Most general initialization is behind us, but opening a
1623 // tab and/or session restore and such is still to be done.
1624 base::TimeTicks browser_open_start = base::TimeTicks::Now();
1626 // We are in regular browser boot sequence. Open initial tabs and enter the
1627 // main message loop.
1628 std::vector<Profile*> last_opened_profiles;
1629 #if !defined(OS_CHROMEOS)
1630 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1631 // them this early as the cryptohome hasn't yet been mounted (which happens
1632 // only once we log in).
1633 last_opened_profiles =
1634 g_browser_process->profile_manager()->GetLastOpenedProfiles();
1635 #endif // defined(OS_CHROMEOS)
1637 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep2Time",
1638 base::TimeTicks::Now() - start_time_step2);
1640 // This step is costly and is already measured in
1641 // Startup.StartupBrowserCreator_Start.
1642 const bool started = browser_creator_->Start(
1643 parsed_command_line(), base::FilePath(), profile_, last_opened_profiles);
1644 const base::TimeTicks start_time_step3 = base::TimeTicks::Now();
1645 if (started) {
1646 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1647 // Initialize autoupdate timer. Timer callback costs basically nothing
1648 // when browser is not in persistent mode, so it's OK to let it ride on
1649 // the main thread. This needs to be done here because we don't want
1650 // to start the timer when Chrome is run inside a test harness.
1651 browser_process_->StartAutoupdateTimer();
1652 #endif // defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1654 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1655 // On Linux, the running exe will be updated if an upgrade becomes
1656 // available while the browser is running. We need to save the last
1657 // modified time of the exe, so we can compare to determine if there is
1658 // an upgrade while the browser is kept alive by a persistent extension.
1659 upgrade_util::SaveLastModifiedTimeOfExe();
1660 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1662 // Record now as the last successful chrome start.
1663 GoogleUpdateSettings::SetLastRunTime();
1665 #if defined(OS_MACOSX)
1666 // Call Recycle() here as late as possible, before going into the loop
1667 // because Start() will add things to it while creating the main window.
1668 if (parameters().autorelease_pool)
1669 parameters().autorelease_pool->Recycle();
1670 #endif // defined(OS_MACOSX)
1672 const base::TimeDelta delta = base::TimeTicks::Now() - browser_open_start;
1673 startup_metric_utils::RecordBrowserOpenTabsDelta(delta);
1675 // If we're running tests (ui_task is non-null), then we don't want to
1676 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or
1677 // RequestLanguageList
1678 if (parameters().ui_task == NULL) {
1679 // Request new variations seed information from server.
1680 chrome_variations::VariationsService* variations_service =
1681 browser_process_->variations_service();
1682 if (variations_service)
1683 variations_service->PerformPreMainMessageLoopStartup();
1685 translate::TranslateDownloadManager::RequestLanguageList(
1686 profile_->GetPrefs());
1689 run_message_loop_ = started;
1690 browser_creator_.reset();
1692 #if !defined(OS_LINUX) || defined(OS_CHROMEOS) // http://crbug.com/426393
1693 if (g_browser_process->metrics_service()->reporting_active())
1694 content::StartPowerUsageMonitor();
1695 #endif // !defined(OS_LINUX) || defined(OS_CHROMEOS)
1697 process_power_collector_.reset(new ProcessPowerCollector);
1698 process_power_collector_->Initialize();
1699 #endif // !defined(OS_ANDROID)
1701 PostBrowserStart();
1703 if (parameters().ui_task) {
1704 parameters().ui_task->Run();
1705 delete parameters().ui_task;
1706 run_message_loop_ = false;
1708 #if defined(OS_ANDROID)
1709 // We never run the C++ main loop on Android, since the UI thread message
1710 // loop is controlled by the OS, so this is as close as we can get to
1711 // the start of the main loop.
1712 if (result_code_ <= 0) {
1713 RecordBrowserStartupTime();
1715 #endif // defined(OS_ANDROID)
1717 #if !defined(OS_ANDROID)
1718 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep3Time",
1719 base::TimeTicks::Now() - start_time_step3);
1720 #endif // !defined(OS_ANDROID)
1722 return result_code_;
1725 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code) {
1726 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1727 #if defined(OS_ANDROID)
1728 // Chrome on Android does not use default MessageLoop. It has its own
1729 // Android specific MessageLoop
1730 NOTREACHED();
1731 return true;
1732 #else
1733 // Set the result code set in PreMainMessageLoopRun or set above.
1734 *result_code = result_code_;
1735 if (!run_message_loop_)
1736 return true; // Don't run the default message loop.
1738 // These should be invoked as close to the start of the browser's
1739 // UI thread message loop as possible to get a stable measurement
1740 // across versions.
1741 RecordBrowserStartupTime();
1743 DCHECK(base::MessageLoopForUI::IsCurrent());
1744 base::RunLoop run_loop;
1746 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1748 metrics::MetricsService::SetExecutionPhase(
1749 metrics::MetricsService::MAIN_MESSAGE_LOOP_RUN,
1750 g_browser_process->local_state());
1751 run_loop.Run();
1753 return true;
1754 #endif // defined(OS_ANDROID)
1757 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1758 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1759 #if defined(OS_ANDROID)
1760 // Chrome on Android does not use default MessageLoop. It has its own
1761 // Android specific MessageLoop
1762 NOTREACHED();
1763 #else
1764 // Start watching for jank during shutdown. It gets disarmed when
1765 // |shutdown_watcher_| object is destructed.
1766 metrics::MetricsService::SetExecutionPhase(
1767 metrics::MetricsService::SHUTDOWN_TIMEBOMB_ARM,
1768 g_browser_process->local_state());
1769 shutdown_watcher_->Arm(base::TimeDelta::FromSeconds(300));
1771 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1772 startup_watcher_->Disarm();
1774 // Remove observers attached to D-Bus clients before DbusThreadManager is
1775 // shut down.
1776 process_power_collector_.reset();
1778 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1779 chrome_extra_parts_[i]->PostMainMessageLoopRun();
1781 // Some tests don't set parameters.ui_task, so they started translate
1782 // language fetch that was never completed so we need to cleanup here
1783 // otherwise it will be done by the destructor in a wrong thread.
1784 TranslateService::Shutdown(parameters().ui_task == NULL);
1786 if (notify_result_ == ProcessSingleton::PROCESS_NONE)
1787 process_singleton_->Cleanup();
1789 // Stop all tasks that might run on WatchDogThread.
1790 ThreadWatcherList::StopWatchingAll();
1792 browser_process_->metrics_service()->Stop();
1794 restart_last_session_ = browser_shutdown::ShutdownPreThreadsStop();
1795 browser_process_->StartTearDown();
1796 #endif // defined(OS_ANDROID)
1799 void ChromeBrowserMainParts::PostDestroyThreads() {
1800 #if defined(OS_ANDROID)
1801 // On Android, there is no quit/exit. So the browser's main message loop will
1802 // not finish.
1803 NOTREACHED();
1804 #else
1805 browser_process_->PostDestroyThreads();
1806 // browser_shutdown takes care of deleting browser_process, so we need to
1807 // release it.
1808 ignore_result(browser_process_.release());
1809 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_);
1810 master_prefs_.reset();
1811 process_singleton_.reset();
1812 device_event_log::Shutdown();
1814 // We need to do this check as late as possible, but due to modularity, this
1815 // may be the last point in Chrome. This would be more effective if done at
1816 // a higher level on the stack, so that it is impossible for an early return
1817 // to bypass this code. Perhaps we need a *final* hook that is called on all
1818 // paths from content/browser/browser_main.
1819 CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
1821 #if defined(OS_CHROMEOS)
1822 chromeos::CrosSettings::Shutdown();
1823 #endif // defined(OS_CHROMEOS)
1824 #endif // defined(OS_ANDROID)
1827 // Public members:
1829 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts* parts) {
1830 chrome_extra_parts_.push_back(parts);