Rename CoalescedPermissionMessage to PermissionMessage
[chromium-blink-merge.git] / chrome / browser / chrome_browser_main.cc
blob51500ea5eb9abec4995a26b2f513233dc09c4766
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/version_info/version_info.h"
130 #include "content/public/browser/browser_thread.h"
131 #include "content/public/browser/notification_observer.h"
132 #include "content/public/browser/notification_registrar.h"
133 #include "content/public/browser/notification_service.h"
134 #include "content/public/browser/notification_types.h"
135 #include "content/public/browser/power_usage_monitor.h"
136 #include "content/public/browser/site_instance.h"
137 #include "content/public/common/content_client.h"
138 #include "content/public/common/content_switches.h"
139 #include "content/public/common/main_function_params.h"
140 #include "grit/platform_locale_settings.h"
141 #include "media/audio/audio_manager.h"
142 #include "net/base/net_module.h"
143 #include "net/cookies/cookie_monster.h"
144 #include "net/http/http_network_layer.h"
145 #include "net/http/http_stream_factory.h"
146 #include "net/url_request/url_request.h"
147 #include "ui/base/l10n/l10n_util.h"
148 #include "ui/base/layout.h"
149 #include "ui/base/resource/resource_bundle.h"
150 #include "ui/strings/grit/app_locale_settings.h"
152 #if defined(OS_ANDROID)
153 #include "chrome/browser/android/dev_tools_discovery_provider_android.h"
154 #include "chrome/browser/metrics/thread_watcher_android.h"
155 #include "ui/base/resource/resource_bundle_android.h"
156 #else
157 #include "chrome/browser/devtools/chrome_devtools_discovery_provider.h"
158 #include "chrome/browser/feedback/feedback_profile_observer.h"
159 #endif // defined(OS_ANDROID)
161 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
162 #include "chrome/browser/first_run/upgrade_util_linux.h"
163 #include "chrome/browser/sxs_linux.h"
164 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
166 #if defined(OS_CHROMEOS)
167 #include "chrome/browser/chromeos/settings/cros_settings.h"
168 #include "chromeos/chromeos_switches.h"
169 #include "chromeos/settings/cros_settings_names.h"
170 #endif // defined(OS_CHROMEOS)
172 // TODO(port): several win-only methods have been pulled out of this, but
173 // BrowserMain() as a whole needs to be broken apart so that it's usable by
174 // other platforms. For now, it's just a stub. This is a serious work in
175 // progress and should not be taken as an indication of a real refactoring.
177 #if defined(OS_WIN)
178 #include "base/environment.h" // For PreRead experiment.
179 #include "base/win/windows_version.h"
180 #include "chrome/browser/browser_util_win.h"
181 #include "chrome/browser/chrome_browser_main_win.h"
182 #include "chrome/browser/chrome_select_file_dialog_factory_win.h"
183 #include "chrome/browser/component_updater/caps_installer_win.h"
184 #include "chrome/browser/component_updater/sw_reporter_installer_win.h"
185 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
186 #include "chrome/browser/first_run/upgrade_util_win.h"
187 #include "chrome/browser/ui/network_profile_bubble.h"
188 #include "chrome/installer/util/helper.h"
189 #include "chrome/installer/util/install_util.h"
190 #include "chrome/installer/util/shell_util.h"
191 #include "components/browser_watcher/exit_funnel_win.h"
192 #include "net/base/net_util.h"
193 #include "ui/base/l10n/l10n_util_win.h"
194 #include "ui/gfx/win/dpi.h"
195 #include "ui/shell_dialogs/select_file_dialog.h"
196 #endif // defined(OS_WIN)
198 #if defined(OS_MACOSX)
199 #include <Security/Security.h>
201 #include "base/mac/scoped_nsautorelease_pool.h"
202 #include "chrome/browser/mac/keystone_glue.h"
203 #endif // defined(OS_MACOSX)
205 #if !defined(OS_IOS)
206 #include "chrome/browser/ui/app_modal/chrome_javascript_native_dialog_factory.h"
207 #endif // !defined(OS_IOS)
209 #if !defined(DISABLE_NACL)
210 #include "chrome/browser/component_updater/pnacl_component_installer.h"
211 #include "components/nacl/browser/nacl_process_host.h"
212 #endif // !defined(DISABLE_NACL)
214 #if defined(ENABLE_EXTENSIONS)
215 #include "chrome/browser/extensions/startup_helper.h"
216 #include "extensions/browser/extension_protocols.h"
217 #include "extensions/common/features/feature_provider.h"
218 #include "extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.h"
219 #endif // defined(ENABLE_EXTENSIONS)
221 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
222 #include "printing/printed_document.h"
223 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
225 #if defined(ENABLE_RLZ)
226 #include "chrome/browser/rlz/chrome_rlz_tracker_delegate.h"
227 #include "components/rlz/rlz_tracker.h"
228 #endif // defined(ENABLE_RLZ)
230 #if defined(ENABLE_WEBRTC)
231 #include "chrome/browser/media/webrtc_log_util.h"
232 #endif // defined(ENABLE_WEBRTC)
234 #if defined(USE_AURA)
235 #include "ui/aura/env.h"
236 #endif // defined(USE_AURA)
238 using content::BrowserThread;
240 namespace {
242 // This function provides some ways to test crash and assertion handling
243 // behavior of the program.
244 void HandleTestParameters(const base::CommandLine& command_line) {
245 // This parameter causes a null pointer crash (crash reporter trigger).
246 if (command_line.HasSwitch(switches::kBrowserCrashTest)) {
247 int* bad_pointer = NULL;
248 *bad_pointer = 0;
252 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
253 void AddFirstRunNewTabs(StartupBrowserCreator* browser_creator,
254 const std::vector<GURL>& new_tabs) {
255 for (std::vector<GURL>::const_iterator it = new_tabs.begin();
256 it != new_tabs.end(); ++it) {
257 if (it->is_valid())
258 browser_creator->AddFirstRunTab(*it);
261 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
263 // Returns the new local state object, guaranteed non-NULL.
264 // |local_state_task_runner| must be a shutdown-blocking task runner.
265 PrefService* InitializeLocalState(
266 base::SequencedTaskRunner* local_state_task_runner,
267 const base::CommandLine& parsed_command_line) {
268 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
270 // Load local state. This includes the application locale so we know which
271 // locale dll to load. This also causes local state prefs to be registered.
272 PrefService* local_state = g_browser_process->local_state();
273 DCHECK(local_state);
275 #if defined(OS_WIN)
276 if (first_run::IsChromeFirstRun()) {
277 // During first run we read the google_update registry key to find what
278 // language the user selected when downloading the installer. This
279 // becomes our default language in the prefs.
280 // Other platforms obey the system locale.
281 base::string16 install_lang;
282 if (GoogleUpdateSettings::GetLanguage(&install_lang)) {
283 local_state->SetString(prefs::kApplicationLocale,
284 base::UTF16ToASCII(install_lang));
287 #endif // defined(OS_WIN)
289 // If the local state file for the current profile doesn't exist and the
290 // parent profile command line flag is present, then we should inherit some
291 // local state from the parent profile.
292 // Checking that the local state file for the current profile doesn't exist
293 // is the most robust way to determine whether we need to inherit or not
294 // since the parent profile command line flag can be present even when the
295 // current profile is not a new one, and in that case we do not want to
296 // inherit and reset the user's setting.
298 // TODO(mnissler): We should probably just instantiate a
299 // JSONPrefStore here instead of an entire PrefService. Once this is
300 // addressed, the call to browser_prefs::RegisterLocalState can move
301 // to chrome_prefs::CreateLocalState.
302 if (parsed_command_line.HasSwitch(switches::kParentProfile)) {
303 base::FilePath local_state_path;
304 PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path);
305 bool local_state_file_exists = base::PathExists(local_state_path);
306 if (!local_state_file_exists) {
307 base::FilePath parent_profile =
308 parsed_command_line.GetSwitchValuePath(switches::kParentProfile);
309 scoped_refptr<PrefRegistrySimple> registry = new PrefRegistrySimple();
310 scoped_ptr<PrefService> parent_local_state(
311 chrome_prefs::CreateLocalState(
312 parent_profile,
313 local_state_task_runner,
314 g_browser_process->policy_service(),
315 registry,
316 false));
317 registry->RegisterStringPref(prefs::kApplicationLocale, std::string());
318 // Right now, we only inherit the locale setting from the parent profile.
319 local_state->SetString(
320 prefs::kApplicationLocale,
321 parent_local_state->GetString(prefs::kApplicationLocale));
325 #if defined(OS_CHROMEOS)
326 if (parsed_command_line.HasSwitch(chromeos::switches::kLoginManager)) {
327 std::string owner_locale = local_state->GetString(prefs::kOwnerLocale);
328 // Ensure that we start with owner's locale.
329 if (!owner_locale.empty() &&
330 local_state->GetString(prefs::kApplicationLocale) != owner_locale &&
331 !local_state->IsManagedPreference(prefs::kApplicationLocale)) {
332 local_state->SetString(prefs::kApplicationLocale, owner_locale);
335 #endif // defined(OS_CHROMEOS)
337 return local_state;
340 // Initializes the primary profile, possibly doing some user prompting to pick
341 // a fallback profile. Returns the newly created profile, or NULL if startup
342 // should not continue.
343 Profile* CreatePrimaryProfile(const content::MainFunctionParams& parameters,
344 const base::FilePath& user_data_dir,
345 const base::CommandLine& parsed_command_line) {
346 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
347 TRACK_SCOPED_REGION(
348 "Startup", "ChromeBrowserMainParts::CreatePrimaryProfile");
350 base::Time start = base::Time::Now();
351 if (profiles::IsMultipleProfilesEnabled() &&
352 parsed_command_line.HasSwitch(switches::kProfileDirectory)) {
353 profiles::SetLastUsedProfile(
354 parsed_command_line.GetSwitchValueASCII(switches::kProfileDirectory));
355 // Clear kProfilesLastActive since the user only wants to launch a specific
356 // profile.
357 ListPrefUpdate update(g_browser_process->local_state(),
358 prefs::kProfilesLastActive);
359 base::ListValue* profile_list = update.Get();
360 profile_list->Clear();
363 Profile* profile = NULL;
364 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
365 // On ChromeOS and Android the ProfileManager will use the same path as the
366 // one we got passed. GetActiveUserProfile will therefore use the correct path
367 // automatically.
368 DCHECK_EQ(user_data_dir.value(),
369 g_browser_process->profile_manager()->user_data_dir().value());
370 profile = ProfileManager::GetActiveUserProfile();
371 #else
372 base::FilePath profile_path =
373 GetStartupProfilePath(user_data_dir, parsed_command_line);
375 // Without NewAvatarMenu, replace guest with any existing profile.
376 if (!switches::IsNewAvatarMenu() &&
377 profile_path == ProfileManager::GetGuestProfilePath()) {
378 profile_path = g_browser_process->profile_manager()->GetProfileInfoCache().
379 GetPathOfProfileAtIndex(0);
381 profile = g_browser_process->profile_manager()->GetProfile(
382 profile_path);
384 // If we're using the --new-profile-management flag and this profile is
385 // signed out, then we should show the user manager instead. By switching
386 // the active profile to the guest profile we ensure that no
387 // browser windows will be opened for the guest profile.
388 if (switches::IsNewProfileManagement() &&
389 profile &&
390 !profile->IsGuestSession()) {
391 ProfileInfoCache& cache =
392 g_browser_process->profile_manager()->GetProfileInfoCache();
393 size_t profile_index = cache.GetIndexOfProfileWithPath(profile_path);
395 if (profile_index != std::string::npos &&
396 cache.ProfileIsSigninRequiredAtIndex(profile_index)) {
397 profile = g_browser_process->profile_manager()->GetProfile(
398 ProfileManager::GetGuestProfilePath());
401 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID)
402 if (profile) {
403 UMA_HISTOGRAM_LONG_TIMES(
404 "Startup.CreateFirstProfile", base::Time::Now() - start);
405 return profile;
408 #if !defined(OS_WIN)
409 // TODO(port): fix this. See comments near the definition of
410 // user_data_dir. It is better to CHECK-fail here than it is to
411 // silently exit because of missing code in the above test.
412 CHECK(profile) << "Cannot get default profile.";
413 #endif // !defined(OS_WIN)
415 return NULL;
418 #if defined(OS_MACOSX)
419 OSStatus KeychainCallback(SecKeychainEvent keychain_event,
420 SecKeychainCallbackInfo* info, void* context) {
421 return noErr;
423 #endif // defined(OS_MACOSX)
425 void RegisterComponentsForUpdate() {
426 component_updater::ComponentUpdateService* cus =
427 g_browser_process->component_updater();
429 // Registration can be before or after cus->Start() so it is ok to post
430 // a task to the UI thread to do registration once you done the necessary
431 // file IO to know you existing component version.
432 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
433 RegisterRecoveryComponent(cus, g_browser_process->local_state());
434 RegisterPepperFlashComponent(cus);
435 RegisterSwiftShaderComponent(cus);
436 RegisterWidevineCdmComponent(cus);
437 #endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
439 #if !defined(DISABLE_NACL) && !defined(OS_ANDROID)
440 #if defined(OS_CHROMEOS)
441 // PNaCl on Chrome OS is on rootfs and there is no need to download it. But
442 // Chrome4ChromeOS on Linux doesn't contain PNaCl so enable component
443 // installer when running on Linux. See crbug.com/422121 for more details.
444 if (!base::SysInfo::IsRunningOnChromeOS())
445 #endif // defined(OS_CHROMEOS)
446 g_browser_process->pnacl_component_installer()->RegisterPnaclComponent(cus);
447 #endif // !defined(DISABLE_NACL) && !defined(OS_ANDROID)
449 // Registration of the CLD Component is a no-op unless the CLD data source has
450 // been configured to be the "Component" data source.
451 RegisterCldComponent(cus);
453 component_updater::SupervisedUserWhitelistInstaller* whitelist_installer =
454 g_browser_process->supervised_user_whitelist_installer();
455 whitelist_installer->RegisterComponents();
457 base::FilePath path;
458 if (PathService::Get(chrome::DIR_USER_DATA, &path)) {
459 #if defined(OS_ANDROID)
460 // The CRLSet component was enabled for some releases. This code attempts to
461 // delete it from the local disk of those how may have downloaded it.
462 g_browser_process->crl_set_fetcher()->DeleteFromDisk(path);
463 #elif !defined(OS_CHROMEOS)
464 // CRLSetFetcher attempts to load a CRL set from either the local disk or
465 // network.
466 // For Chrome OS this registration is delayed until user login.
467 g_browser_process->crl_set_fetcher()->StartInitialLoad(cus, path);
468 // Registration of the EV Whitelist component here is not necessary for:
469 // 1. Android: Because it currently does not have the EV indicator.
470 // 2. Chrome OS: On Chrome OS this registration is delayed until user login.
471 RegisterEVWhitelistComponent(cus, path);
472 #endif // defined(OS_ANDROID)
475 #if defined(OS_WIN)
476 #if defined(GOOGLE_CHROME_BUILD)
477 RegisterSwReporterComponent(cus);
478 #endif // defined(GOOGLE_CHROME_BUILD)
479 RegisterCAPSComponent(cus);
480 #endif // defined(OS_WIN)
483 #if !defined(OS_ANDROID)
484 bool ProcessSingletonNotificationCallback(
485 const base::CommandLine& command_line,
486 const base::FilePath& current_directory) {
487 // Drop the request if the browser process is already in shutdown path.
488 if (!g_browser_process || g_browser_process->IsShuttingDown()) {
489 #if defined(OS_WIN)
490 browser_watcher::ExitFunnel::RecordSingleEvent(
491 chrome::kBrowserExitCodesRegistryPath,
492 L"ProcessSingletonIsShuttingDown");
493 #endif // defined(OS_WIN)
495 return false;
498 if (command_line.HasSwitch(switches::kOriginalProcessStartTime)) {
499 std::string start_time_string =
500 command_line.GetSwitchValueASCII(switches::kOriginalProcessStartTime);
501 int64 remote_start_time;
502 if (base::StringToInt64(start_time_string, &remote_start_time)) {
503 base::TimeDelta elapsed =
504 base::Time::Now() - base::Time::FromInternalValue(remote_start_time);
505 if (command_line.HasSwitch(switches::kFastStart)) {
506 UMA_HISTOGRAM_LONG_TIMES(
507 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed);
508 } else {
509 UMA_HISTOGRAM_LONG_TIMES(
510 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed);
515 g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing(
516 command_line);
518 base::FilePath user_data_dir =
519 g_browser_process->profile_manager()->user_data_dir();
520 base::FilePath startup_profile_dir =
521 GetStartupProfilePath(user_data_dir, command_line);
523 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
524 command_line, current_directory, startup_profile_dir);
525 return true;
527 #endif // !defined(OS_ANDROID)
529 void LaunchDevToolsHandlerIfNeeded(const base::CommandLine& command_line) {
530 if (command_line.HasSwitch(::switches::kRemoteDebuggingPort)) {
531 std::string port_str =
532 command_line.GetSwitchValueASCII(::switches::kRemoteDebuggingPort);
533 int port;
534 if (base::StringToInt(port_str, &port) && port >= 0 && port < 65535) {
535 g_browser_process->CreateDevToolsHttpProtocolHandler(
536 chrome::HOST_DESKTOP_TYPE_NATIVE,
537 "127.0.0.1",
538 static_cast<uint16>(port));
539 } else {
540 DLOG(WARNING) << "Invalid http debugger port number " << port;
545 base::StackSamplingProfiler::SamplingParams GetStartupSamplingParams() {
546 // Sample at 10Hz for 30 seconds.
547 base::StackSamplingProfiler::SamplingParams params;
548 params.initial_delay = base::TimeDelta::FromMilliseconds(0);
549 params.bursts = 1;
550 params.samples_per_burst = 300;
551 params.sampling_interval = base::TimeDelta::FromMilliseconds(100);
552 return params;
555 } // namespace
557 namespace chrome_browser {
559 // This error message is not localized because we failed to load the
560 // localization data files.
561 #if defined(OS_WIN)
562 const char kMissingLocaleDataTitle[] = "Missing File Error";
563 #endif // defined(OS_WIN)
565 #if defined(OS_WIN)
566 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
567 const char kMissingLocaleDataMessage[] =
568 "Unable to find locale data files. Please reinstall.";
569 #endif // defined(OS_WIN)
571 } // namespace chrome_browser
573 // BrowserMainParts ------------------------------------------------------------
575 ChromeBrowserMainParts::ChromeBrowserMainParts(
576 const content::MainFunctionParams& parameters)
577 : parameters_(parameters),
578 parsed_command_line_(parameters.command_line),
579 result_code_(content::RESULT_CODE_NORMAL_EXIT),
580 startup_watcher_(new StartupTimeBomb()),
581 shutdown_watcher_(new ShutdownWatcherHelper()),
582 browser_field_trials_(parameters.command_line),
583 sampling_profiler_(
584 base::PlatformThread::CurrentId(),
585 GetStartupSamplingParams(),
586 metrics::CallStackProfileMetricsProvider::GetProfilerCallback(
587 metrics::CallStackProfileMetricsProvider::Params(
588 metrics::CallStackProfileMetricsProvider::PROCESS_STARTUP,
589 false))),
590 profile_(NULL),
591 run_message_loop_(true),
592 notify_result_(ProcessSingleton::PROCESS_NONE),
593 local_state_(NULL),
594 restart_last_session_(false) {
595 const version_info::Channel channel = chrome::GetChannel();
596 if (channel == version_info::Channel::UNKNOWN ||
597 channel == version_info::Channel::CANARY ||
598 channel == version_info::Channel::DEV) {
599 sampling_profiler_.Start();
602 // If we're running tests (ui_task is non-null).
603 if (parameters.ui_task)
604 browser_defaults::enable_help_app = false;
606 // Chrome disallows cookies by default. All code paths that want to use
607 // cookies need to go through one of Chrome's URLRequestContexts which have
608 // a ChromeNetworkDelegate attached that selectively allows cookies again.
609 net::URLRequest::SetDefaultCookiePolicyToBlock();
612 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
613 for (int i = static_cast<int>(chrome_extra_parts_.size())-1; i >= 0; --i)
614 delete chrome_extra_parts_[i];
615 chrome_extra_parts_.clear();
618 // This will be called after the command-line has been mutated by about:flags
619 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
620 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
621 // Must initialize metrics after labs have been converted into switches,
622 // but before field trials are set up (so that client ID is available for
623 // one-time randomized field trials).
625 // Initialize FieldTrialList to support FieldTrials that use one-time
626 // randomization.
627 metrics::MetricsService* metrics = browser_process_->metrics_service();
628 field_trial_list_.reset(
629 new base::FieldTrialList(metrics->CreateEntropyProvider().release()));
631 const base::CommandLine* command_line =
632 base::CommandLine::ForCurrentProcess();
633 if (command_line->HasSwitch(switches::kEnableBenchmarking) ||
634 command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking)) {
635 base::FieldTrial::EnableBenchmarking();
638 if (command_line->HasSwitch(switches::kForceFieldTrialParams)) {
639 bool result = chrome_variations::AssociateParamsFromString(
640 command_line->GetSwitchValueASCII(switches::kForceFieldTrialParams));
641 CHECK(result) << "Invalid --" << switches::kForceFieldTrialParams
642 << " list specified.";
645 // Ensure any field trials specified on the command line are initialized.
646 if (command_line->HasSwitch(switches::kForceFieldTrials)) {
647 std::set<std::string> unforceable_field_trials;
648 #if defined(OFFICIAL_BUILD)
649 unforceable_field_trials.insert("SettingsEnforcement");
650 #endif // defined(OFFICIAL_BUILD)
652 // Create field trials without activating them, so that this behaves in a
653 // consistent manner with field trials created from the server.
654 bool result = base::FieldTrialList::CreateTrialsFromString(
655 command_line->GetSwitchValueASCII(switches::kForceFieldTrials),
656 base::FieldTrialList::DONT_ACTIVATE_TRIALS,
657 unforceable_field_trials);
658 CHECK(result) << "Invalid --" << switches::kForceFieldTrials
659 << " list specified.";
662 #if defined(FIELDTRIAL_TESTING_ENABLED)
663 if (!command_line->HasSwitch(switches::kDisableFieldTrialTestingConfig) &&
664 !command_line->HasSwitch(switches::kForceFieldTrials) &&
665 !command_line->HasSwitch(switches::kVariationsServerURL))
666 chrome_variations::AssociateDefaultFieldTrialConfig();
667 #endif // defined(FIELDTRIAL_TESTING_ENABLED)
669 if (command_line->HasSwitch(switches::kForceVariationIds)) {
670 // Create default variation ids which will always be included in the
671 // X-Client-Data request header.
672 variations::VariationsHttpHeaderProvider* provider =
673 variations::VariationsHttpHeaderProvider::GetInstance();
674 bool result = provider->SetDefaultVariationIds(
675 command_line->GetSwitchValueASCII(switches::kForceVariationIds));
676 CHECK(result) << "Invalid --" << switches::kForceVariationIds
677 << " list specified.";
678 metrics->AddSyntheticTrialObserver(provider);
680 chrome_variations::VariationsService* variations_service =
681 browser_process_->variations_service();
682 if (variations_service)
683 variations_service->CreateTrialsFromSeed();
685 // This must be called after |local_state_| is initialized.
686 browser_field_trials_.SetupFieldTrials();
688 // Enable Navigation Tracing only if a trace upload url is specified.
689 if (command_line->HasSwitch(switches::kEnableNavigationTracing) &&
690 command_line->HasSwitch(switches::kTraceUploadURL)) {
691 tracing::SetupNavigationTracing();
694 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
695 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
696 // Even though base::Bind does AddRef and Release, the object will not be
697 // deleted after the Task is executed.
698 field_trial_synchronizer_ = new FieldTrialSynchronizer();
700 // Now that field trials have been created, initializes metrics recording.
701 metrics->InitializeMetricsRecordingState();
703 const version_info::Channel channel = chrome::GetChannel();
705 // TODO(dalecurtis): Remove these checks and enable for all channels once we
706 // track down the root causes of crbug.com/422522 and crbug.com/478932.
707 if (channel == version_info::Channel::UNKNOWN ||
708 channel == version_info::Channel::CANARY ||
709 channel == version_info::Channel::DEV) {
710 media::AudioManager::EnableHangMonitor();
713 // Enable profiler instrumentation depending on the channel.
714 switch (channel) {
715 case version_info::Channel::UNKNOWN:
716 case version_info::Channel::CANARY:
717 tracked_objects::ScopedTracker::Enable();
718 break;
720 case version_info::Channel::DEV:
721 case version_info::Channel::BETA:
722 case version_info::Channel::STABLE:
723 // Don't enable instrumentation.
724 break;
728 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
730 void ChromeBrowserMainParts::StartMetricsRecording() {
731 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
733 g_browser_process->metrics_service()->CheckForClonedInstall(
734 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
736 g_browser_process->GetMetricsServicesManager()->UpdateUploadPermissions(true);
739 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
740 // Don't record any metrics if UI was displayed before this point e.g.
741 // warning dialogs.
742 if (startup_metric_utils::WasNonBrowserUIDisplayed())
743 return;
745 bool is_first_run = false;
746 #if !defined(OS_ANDROID)
747 // On Android, first run is handled in Java code, and the C++ side of Chrome
748 // doesn't know if this is the first run. This will cause some inaccuracy in
749 // the UMA statistics, but this should be minor (first runs are rare).
750 is_first_run = first_run::IsChromeFirstRun();
751 #endif // defined(OS_ANDROID)
753 // Record collected startup metrics.
754 startup_metric_utils::RecordBrowserMainMessageLoopStart(base::Time::Now(),
755 is_first_run);
758 // -----------------------------------------------------------------------------
759 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
761 #if defined(OS_WIN)
762 #define DLLEXPORT __declspec(dllexport)
764 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
765 extern "C" {
766 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded();
769 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
770 // Need an instance of AtExitManager to handle singleton creations and
771 // deletions. We need this new instance because, the old instance created
772 // in ChromeMain() got destructed when the function returned.
773 base::AtExitManager exit_manager;
774 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
776 #endif
778 // content::BrowserMainParts implementation ------------------------------------
780 void ChromeBrowserMainParts::PreEarlyInitialization() {
781 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
782 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
783 chrome_extra_parts_[i]->PreEarlyInitialization();
786 void ChromeBrowserMainParts::PostEarlyInitialization() {
787 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
788 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
789 chrome_extra_parts_[i]->PostEarlyInitialization();
792 void ChromeBrowserMainParts::ToolkitInitialized() {
793 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
794 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
795 chrome_extra_parts_[i]->ToolkitInitialized();
798 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
799 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
801 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
802 chrome_extra_parts_[i]->PreMainMessageLoopStart();
805 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
806 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
808 // device_event_log must be initialized after the message loop. Calls to
809 // {DEVICE}_LOG prior to here will only be logged with VLOG. Some
810 // platforms (e.g. chromeos) may have already initialized this.
811 if (!device_event_log::IsInitialized())
812 device_event_log::Initialize(0 /* default max entries */);
814 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
815 chrome_extra_parts_[i]->PostMainMessageLoopStart();
818 int ChromeBrowserMainParts::PreCreateThreads() {
819 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
820 result_code_ = PreCreateThreadsImpl();
822 if (result_code_ == content::RESULT_CODE_NORMAL_EXIT) {
823 #if !defined(OS_ANDROID)
824 // These members must be initialized before exiting this function normally.
825 DCHECK(master_prefs_.get());
826 DCHECK(browser_creator_.get());
827 #endif // !defined(OS_ANDROID)
828 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
829 chrome_extra_parts_[i]->PreCreateThreads();
832 return result_code_;
835 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
836 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
837 run_message_loop_ = false;
838 #if !defined(OS_ANDROID)
839 chrome::MaybeShowInvalidUserDataDirWarningDialog();
840 #endif // !defined(OS_ANDROID)
841 if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir_))
842 return chrome::RESULT_CODE_MISSING_DATA;
844 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
845 MediaCaptureDevicesDispatcher::GetInstance();
847 // Android's first run is done in Java instead of native.
848 #if !defined(OS_ANDROID)
849 process_singleton_.reset(new ChromeProcessSingleton(
850 user_data_dir_, base::Bind(&ProcessSingletonNotificationCallback)));
852 // Cache first run state early.
853 first_run::IsChromeFirstRun();
854 #endif // !defined(OS_ANDROID)
856 scoped_refptr<base::SequencedTaskRunner> local_state_task_runner =
857 JsonPrefStore::GetTaskRunnerForFile(
858 base::FilePath(chrome::kLocalStorePoolName),
859 BrowserThread::GetBlockingPool());
862 TRACE_EVENT0("startup",
863 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
864 browser_process_.reset(new BrowserProcessImpl(local_state_task_runner.get(),
865 parsed_command_line()));
868 if (parsed_command_line().HasSwitch(switches::kEnableProfiling)) {
869 TRACE_EVENT0("startup",
870 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
871 // User wants to override default tracking status.
872 std::string flag =
873 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling);
874 // Default to basic profiling (no parent child support).
875 tracked_objects::ThreadData::Status status =
876 tracked_objects::ThreadData::PROFILING_ACTIVE;
877 if (flag.compare("0") != 0)
878 status = tracked_objects::ThreadData::DEACTIVATED;
879 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status);
882 local_state_ = InitializeLocalState(
883 local_state_task_runner.get(), parsed_command_line());
885 #if !defined(OS_ANDROID)
886 // These members must be initialized before returning from this function.
887 master_prefs_.reset(new first_run::MasterPrefs);
888 // Android doesn't use StartupBrowserCreator.
889 browser_creator_.reset(new StartupBrowserCreator);
890 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
891 chrome::UMABrowsingActivityObserver::Init();
892 #endif // !defined(OS_ANDROID)
894 #if !defined(OS_CHROMEOS)
895 // Convert active labs into switches. This needs to be done before
896 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
897 // affected by experiment flags (--touch-optimized-ui in particular).
898 // On ChromeOS system level flags are applied from the device settings from
899 // the session manager.
901 TRACE_EVENT0("startup",
902 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
903 about_flags::PrefServiceFlagsStorage flags_storage_(
904 g_browser_process->local_state());
905 about_flags::ConvertFlagsToSwitches(&flags_storage_,
906 base::CommandLine::ForCurrentProcess(),
907 about_flags::kAddSentinels);
909 #endif // !defined(OS_CHROMEOS)
911 local_state_->UpdateCommandLinePrefStore(
912 new CommandLinePrefStore(base::CommandLine::ForCurrentProcess()));
914 // Reset the command line in the crash report details, since we may have
915 // just changed it to include experiments.
916 crash_keys::SetSwitchesFromCommandLine(
917 base::CommandLine::ForCurrentProcess());
919 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
920 // needed when loading the MainMenu.nib and the language doesn't depend on
921 // anything since it comes from Cocoa.
922 #if defined(OS_MACOSX)
923 std::string locale =
924 parameters().ui_task ? "en-US" : l10n_util::GetLocaleOverride();
925 browser_process_->SetApplicationLocale(locale);
926 #else
927 const std::string locale =
928 local_state_->GetString(prefs::kApplicationLocale);
930 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
931 // method InitSharedInstance is ignored.
933 TRACE_EVENT_BEGIN0("startup",
934 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
935 const std::string loaded_locale =
936 ui::ResourceBundle::InitSharedInstanceWithLocale(
937 locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
938 TRACE_EVENT_END0("startup",
939 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
941 if (loaded_locale.empty() &&
942 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs)) {
943 ShowMissingLocaleMessageBox();
944 return chrome::RESULT_CODE_MISSING_DATA;
946 CHECK(!loaded_locale.empty()) << "Locale could not be found for " << locale;
947 browser_process_->SetApplicationLocale(loaded_locale);
950 TRACE_EVENT0("startup",
951 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
952 base::FilePath resources_pack_path;
953 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
954 #if defined(OS_ANDROID)
955 ui::LoadMainAndroidPackFile("assets/resources.pak", resources_pack_path);
956 #else
957 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
958 resources_pack_path, ui::SCALE_FACTOR_NONE);
959 #endif // defined(OS_ANDROID)
961 #endif // defined(OS_MACOSX)
963 // Android does first run in Java instead of native.
964 // Chrome OS has its own out-of-box-experience code.
965 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
966 // On first run, we need to process the predictor preferences before the
967 // browser's profile_manager object is created, but after ResourceBundle
968 // is initialized.
969 if (first_run::IsChromeFirstRun()) {
970 first_run::ProcessMasterPreferencesResult pmp_result =
971 first_run::ProcessMasterPreferences(user_data_dir_,
972 master_prefs_.get());
973 if (pmp_result == first_run::EULA_EXIT_NOW)
974 return chrome::RESULT_CODE_EULA_REFUSED;
976 if (!parsed_command_line().HasSwitch(switches::kApp) &&
977 !parsed_command_line().HasSwitch(switches::kAppId) &&
978 !parsed_command_line().HasSwitch(switches::kShowAppList)) {
979 AddFirstRunNewTabs(browser_creator_.get(), master_prefs_->new_tabs);
982 // TODO(macourteau): refactor preferences that are copied from
983 // master_preferences into local_state, as a "local_state" section in
984 // master preferences. If possible, a generic solution would be preferred
985 // over a copy one-by-one of specific preferences. Also see related TODO
986 // in first_run.h.
988 // Store the initial VariationsService seed in local state, if it exists
989 // in master prefs.
990 if (!master_prefs_->variations_seed.empty() ||
991 !master_prefs_->compressed_variations_seed.empty()) {
992 if (!master_prefs_->variations_seed.empty()) {
993 local_state_->SetString(chrome_variations::prefs::kVariationsSeed,
994 master_prefs_->variations_seed);
996 if (!master_prefs_->compressed_variations_seed.empty()) {
997 local_state_->SetString(
998 chrome_variations::prefs::kVariationsCompressedSeed,
999 master_prefs_->compressed_variations_seed);
1001 if (!master_prefs_->variations_seed_signature.empty()) {
1002 local_state_->SetString(
1003 chrome_variations::prefs::kVariationsSeedSignature,
1004 master_prefs_->variations_seed_signature);
1006 // Set the variation seed date to the current system time. If the user's
1007 // clock is incorrect, this may cause some field trial expiry checks to
1008 // not do the right thing until the next seed update from the server,
1009 // when this value will be updated.
1010 local_state_->SetInt64(chrome_variations::prefs::kVariationsSeedDate,
1011 base::Time::Now().ToInternalValue());
1014 if (!master_prefs_->suppress_default_browser_prompt_for_version.empty()) {
1015 local_state_->SetString(
1016 prefs::kBrowserSuppressDefaultBrowserPrompt,
1017 master_prefs_->suppress_default_browser_prompt_for_version);
1020 #if defined(OS_WIN)
1021 if (!master_prefs_->welcome_page_on_os_upgrade_enabled)
1022 local_state_->SetBoolean(prefs::kWelcomePageOnOSUpgradeEnabled, false);
1023 #endif
1025 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1027 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
1028 // Set the product channel for crash reports.
1029 base::debug::SetCrashKeyValue(crash_keys::kChannel,
1030 chrome::GetChannelString());
1031 #endif // defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
1033 // Initialize tracking synchronizer system.
1034 tracking_synchronizer_ = new metrics::TrackingSynchronizer(
1035 make_scoped_ptr(new base::DefaultTickClock()));
1037 #if defined(OS_MACOSX)
1038 // Get the Keychain API to register for distributed notifications on the main
1039 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
1040 // which doesn't. This ensures those notifications will get delivered
1041 // properly. See issue 37766.
1042 // (Note that the callback mask here is empty. I don't want to register for
1043 // any callbacks, I just want to initialize the mechanism.)
1044 SecKeychainAddCallback(&KeychainCallback, 0, NULL);
1045 #endif // defined(OS_MACOSX)
1047 #if defined(OS_CHROMEOS)
1048 // Must be done after g_browser_process is constructed, before
1049 // SetupMetricsAndFieldTrials().
1050 chromeos::CrosSettings::Initialize();
1051 #endif // defined(OS_CHROMEOS)
1053 // Now the command line has been mutated based on about:flags, we can setup
1054 // metrics and initialize field trials. The field trials are needed by
1055 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
1056 SetupMetricsAndFieldTrials();
1058 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
1059 browser_process_->PreCreateThreads();
1061 return content::RESULT_CODE_NORMAL_EXIT;
1064 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
1065 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1066 TRACK_SCOPED_REGION(
1067 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1069 result_code_ = PreMainMessageLoopRunImpl();
1071 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1072 chrome_extra_parts_[i]->PreMainMessageLoopRun();
1075 // PreMainMessageLoopRun calls these extra stages in the following order:
1076 // PreMainMessageLoopRunImpl()
1077 // ... initial setup, including browser_process_ setup.
1078 // PreProfileInit()
1079 // ... additional setup, including CreateProfile()
1080 // PostProfileInit()
1081 // ... additional setup
1082 // PreBrowserStart()
1083 // ... browser_creator_->Start (OR parameters().ui_task->Run())
1084 // PostBrowserStart()
1086 void ChromeBrowserMainParts::PreProfileInit() {
1087 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1089 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1090 chrome_extra_parts_[i]->PreProfileInit();
1092 #if !defined(OS_ANDROID)
1093 // Initialize the feedback uploader so it can setup notifications for profile
1094 // creation.
1095 feedback::FeedbackProfileObserver::Initialize();
1097 // Ephemeral profiles may have been left behind if the browser crashed.
1098 g_browser_process->profile_manager()->CleanUpEphemeralProfiles();
1099 #endif // !defined(OS_ANDROID)
1101 #if defined(ENABLE_EXTENSIONS)
1102 javascript_dialog_extensions_client::InstallClient();
1103 #endif // defined(ENABLE_EXTENSIONS)
1105 #if !defined(OS_IOS)
1106 InstallChromeJavaScriptNativeDialogFactory();
1107 #endif // !defined(OS_IOS)
1110 void ChromeBrowserMainParts::PostProfileInit() {
1111 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1113 #if defined(OS_ANDROID)
1114 DevToolsDiscoveryProviderAndroid::Install();
1115 #else
1116 ChromeDevToolsDiscoveryProvider::Install();
1117 #endif // defined(OS_ANDROID)
1119 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1120 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1121 chrome_extra_parts_[i]->PostProfileInit();
1124 void ChromeBrowserMainParts::PreBrowserStart() {
1125 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1126 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1127 chrome_extra_parts_[i]->PreBrowserStart();
1129 three_d_observer_.reset(new ThreeDAPIObserver());
1131 // Start the out-of-memory priority manager here so that we give the most
1132 // amount of time for the other services to start up before we start
1133 // adjusting the oom priority.
1135 // On CrOS, it is always enabled. On other platforms, it's behind a flag for
1136 // now.
1137 #if defined(OS_CHROMEOS)
1138 g_browser_process->GetOomPriorityManager()->Start();
1139 #elif defined(OS_WIN) || defined(OS_MACOSX)
1140 const std::string group_name =
1141 base::FieldTrialList::FindFullName("AutomaticTabDiscarding");
1142 if (parsed_command_line().HasSwitch(switches::kEnableTabDiscarding) ||
1143 base::StartsWith(group_name, "Enabled", base::CompareCase::SENSITIVE)) {
1144 g_browser_process->GetOomPriorityManager()->Start();
1146 #endif
1149 void ChromeBrowserMainParts::PostBrowserStart() {
1150 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1151 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1152 chrome_extra_parts_[i]->PostBrowserStart();
1153 #if !defined(OS_ANDROID)
1154 // Allow ProcessSingleton to process messages.
1155 process_singleton_->Unlock();
1156 #endif // !defined(OS_ANDROID)
1157 #if defined(ENABLE_WEBRTC)
1158 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1159 // to reduce the impact on startup time.
1160 BrowserThread::PostDelayedTask(
1161 BrowserThread::UI,
1162 FROM_HERE,
1163 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles),
1164 base::TimeDelta::FromMinutes(1));
1165 #endif // defined(ENABLE_WEBRTC)
1167 // At this point, StartupBrowserCreator::Start has run creating initial
1168 // browser windows and tabs, but no progress has been made in loading
1169 // content as the main message loop hasn't started processing tasks yet.
1170 // We setup to observe to the initial page load here to defer running
1171 // task posted via PostAfterStartupTask until its complete.
1172 AfterStartupTaskUtils::StartMonitoringStartup();
1175 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1176 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1177 TRACK_SCOPED_REGION(
1178 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1180 SCOPED_UMA_HISTOGRAM_LONG_TIMER("Startup.PreMainMessageLoopRunImplLongTime");
1181 const base::TimeTicks start_time_step1 = base::TimeTicks::Now();
1183 #if defined(OS_WIN)
1184 // Windows parental controls calls can be slow, so we do an early init here
1185 // that calculates this value off of the UI thread.
1186 IncognitoModePrefs::InitializePlatformParentalControls();
1187 #endif
1189 #if defined(ENABLE_EXTENSIONS)
1190 if (!variations::GetVariationParamValue(
1191 "LightSpeed", "EarlyInitStartup").empty()) {
1192 // Try to compute this early on another thread so that we don't spend time
1193 // during profile load initializing the extensions APIs.
1194 BrowserThread::PostTask(
1195 BrowserThread::FILE_USER_BLOCKING,
1196 FROM_HERE,
1197 base::Bind(
1198 base::IgnoreResult(&extensions::FeatureProvider::GetAPIFeatures)));
1200 #endif
1202 // Android updates the metrics service dynamically depending on whether the
1203 // application is in the foreground or not. Do not start here.
1204 #if !defined(OS_ANDROID)
1205 // Now that the file thread has been started, start recording.
1206 StartMetricsRecording();
1207 #endif // !defined(OS_ANDROID)
1209 if (!base::debug::BeingDebugged()) {
1210 // Create watchdog thread after creating all other threads because it will
1211 // watch the other threads and they must be running.
1212 browser_process_->watchdog_thread();
1215 // Do any initializating in the browser process that requires all threads
1216 // running.
1217 browser_process_->PreMainMessageLoopRun();
1219 // Record last shutdown time into a histogram.
1220 browser_shutdown::ReadLastShutdownInfo();
1222 #if defined(OS_WIN)
1223 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1224 // tasks. Those care whether the browser is already running. On Linux/Mac,
1225 // upgrade/uninstall happen separately.
1226 bool already_running = browser_util::IsBrowserAlreadyRunning();
1228 // If the command line specifies 'uninstall' then we need to work here
1229 // unless we detect another chrome browser running.
1230 if (parsed_command_line().HasSwitch(switches::kUninstall)) {
1231 return DoUninstallTasks(already_running);
1234 if (parsed_command_line().HasSwitch(switches::kHideIcons) ||
1235 parsed_command_line().HasSwitch(switches::kShowIcons)) {
1236 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1237 parsed_command_line_);
1240 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
1241 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
1242 #endif // defined(OS_WIN)
1244 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser)) {
1245 bool is_managed = g_browser_process->local_state()->IsManagedPreference(
1246 prefs::kDefaultBrowserSettingEnabled);
1247 if (is_managed && !g_browser_process->local_state()->GetBoolean(
1248 prefs::kDefaultBrowserSettingEnabled)) {
1249 return static_cast<int>(chrome::RESULT_CODE_ACTION_DISALLOWED_BY_POLICY);
1252 return ShellIntegration::SetAsDefaultBrowser() ?
1253 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT) :
1254 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED);
1257 #if defined(USE_AURA)
1258 // Make sure aura::Env has been initialized.
1259 CHECK(aura::Env::GetInstance());
1260 #endif // defined(USE_AURA)
1262 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1263 #if !defined(OS_ANDROID)
1264 // If the command line specifies --pack-extension, attempt the pack extension
1265 // startup action and exit.
1266 if (parsed_command_line().HasSwitch(switches::kPackExtension)) {
1267 extensions::StartupHelper extension_startup_helper;
1268 if (extension_startup_helper.PackExtension(parsed_command_line()))
1269 return content::RESULT_CODE_NORMAL_EXIT;
1270 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR;
1273 // When another process is running, use that process instead of starting a
1274 // new one. NotifyOtherProcess will currently give the other process up to
1275 // 20 seconds to respond. Note that this needs to be done before we attempt
1276 // to read the profile.
1277 notify_result_ = process_singleton_->NotifyOtherProcessOrCreate();
1278 switch (notify_result_) {
1279 case ProcessSingleton::PROCESS_NONE:
1280 // No process already running, fall through to starting a new one.
1281 break;
1283 case ProcessSingleton::PROCESS_NOTIFIED:
1284 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1285 // On POSIX systems, print a message notifying the process is running.
1286 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1287 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER))).c_str());
1288 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
1290 // Having a differentiated return type for testing allows for tests to
1291 // verify proper handling of some switches. When not testing, stick to
1292 // the standard Unix convention of returning zero when things went as
1293 // expected.
1294 if (parsed_command_line().HasSwitch(switches::kTestType))
1295 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED;
1296 return content::RESULT_CODE_NORMAL_EXIT;
1298 case ProcessSingleton::PROFILE_IN_USE:
1299 return chrome::RESULT_CODE_PROFILE_IN_USE;
1301 case ProcessSingleton::LOCK_ERROR:
1302 LOG(ERROR) << "Failed to create a ProcessSingleton for your profile "
1303 "directory. This means that running multiple instances "
1304 "would start multiple browser processes rather than "
1305 "opening a new window in the existing process. Aborting "
1306 "now to avoid profile corruption.";
1307 return chrome::RESULT_CODE_PROFILE_IN_USE;
1309 default:
1310 NOTREACHED();
1312 #endif // !defined(OS_ANDROID)
1314 // Handle special early return paths (which couldn't be processed even earlier
1315 // as they require the process singleton to be held) first.
1317 std::string try_chrome =
1318 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain);
1319 if (!try_chrome.empty()) {
1320 #if defined(OS_WIN)
1321 // Setup.exe has determined that we need to run a retention experiment
1322 // and has lauched chrome to show the experiment UI. It is guaranteed that
1323 // no other Chrome is currently running as the process singleton was
1324 // sucessfully grabbed above.
1325 int try_chrome_int;
1326 base::StringToInt(try_chrome, &try_chrome_int);
1327 TryChromeDialogView::Result answer = TryChromeDialogView::Show(
1328 try_chrome_int,
1329 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog,
1330 base::Unretained(process_singleton_.get())));
1331 if (answer == TryChromeDialogView::NOT_NOW)
1332 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL;
1333 if (answer == TryChromeDialogView::UNINSTALL_CHROME)
1334 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2;
1335 // At this point the user is willing to try chrome again.
1336 if (answer == TryChromeDialogView::TRY_CHROME_AS_DEFAULT) {
1337 // Only set in the unattended case, the interactive case is Windows 8.
1338 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1339 ShellIntegration::SET_DEFAULT_UNATTENDED)
1340 ShellIntegration::SetAsDefaultBrowser();
1342 #else
1343 // We don't support retention experiments on Mac or Linux.
1344 return content::RESULT_CODE_NORMAL_EXIT;
1345 #endif // defined(OS_WIN)
1348 #if defined(OS_WIN)
1349 // Do the tasks if chrome has been upgraded while it was last running.
1350 if (!already_running && upgrade_util::DoUpgradeTasks(parsed_command_line()))
1351 return content::RESULT_CODE_NORMAL_EXIT;
1353 // Check if there is any machine level Chrome installed on the current
1354 // machine. If yes and the current Chrome process is user level, we do not
1355 // allow the user level Chrome to run. So we notify the user and uninstall
1356 // user level Chrome.
1357 // Note this check needs to happen here (after the process singleton was
1358 // obtained but before potentially creating the first run sentinel).
1359 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1360 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS;
1361 #endif // defined(OS_WIN)
1363 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1364 if (sxs_linux::ShouldMigrateUserDataDir())
1365 return sxs_linux::MigrateUserDataDir();
1366 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1368 // Desktop construction occurs here, (required before profile creation).
1369 PreProfileInit();
1371 // Profile creation ----------------------------------------------------------
1373 metrics::MetricsService::SetExecutionPhase(
1374 metrics::MetricsService::CREATE_PROFILE,
1375 g_browser_process->local_state());
1377 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep1Time",
1378 base::TimeTicks::Now() - start_time_step1);
1380 // This step is costly and is already measured in Startup.CreateFirstProfile
1381 // and more directly Profile.CreateAndInitializeProfile.
1382 profile_ = CreatePrimaryProfile(parameters(),
1383 user_data_dir_,
1384 parsed_command_line());
1385 if (!profile_)
1386 return content::RESULT_CODE_NORMAL_EXIT;
1388 #if !defined(OS_ANDROID)
1389 const base::TimeTicks start_time_step2 = base::TimeTicks::Now();
1390 // The first run sentinel must be created after the process singleton was
1391 // grabbed and no early return paths were otherwise hit above.
1392 first_run::CreateSentinelIfNeeded();
1393 #endif // !defined(OS_ANDROID)
1395 #if defined(ENABLE_BACKGROUND)
1396 // Autoload any profiles which are running background apps.
1397 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1398 browser_process_->profile_manager()->AutoloadProfiles();
1399 #endif // defined(ENABLE_BACKGROUND)
1400 // Post-profile init ---------------------------------------------------------
1402 TranslateService::Initialize();
1404 // Needs to be done before PostProfileInit, since login manager on CrOS is
1405 // called inside PostProfileInit.
1406 content::WebUIControllerFactory::RegisterFactory(
1407 ChromeWebUIControllerFactory::GetInstance());
1409 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1410 // So make sure to create it before that.
1411 #if !defined(DISABLE_NACL)
1412 NaClBrowserDelegateImpl* delegate =
1413 new NaClBrowserDelegateImpl(browser_process_->profile_manager());
1414 nacl::NaClBrowser::SetDelegate(delegate);
1415 #endif // !defined(DISABLE_NACL)
1417 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1418 // (requires supporting early exit).
1419 PostProfileInit();
1421 // Retrieve cached GL strings from local state and use them for GPU
1422 // blacklist decisions.
1423 if (g_browser_process->gl_string_manager())
1424 g_browser_process->gl_string_manager()->Initialize();
1426 // Create an instance of GpuModeManager to watch gpu mode pref change.
1427 g_browser_process->gpu_mode_manager();
1429 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1430 // Show the First Run UI if this is the first time Chrome has been run on
1431 // this computer, or we're being compelled to do so by a command line flag.
1432 // Note that this be done _after_ the PrefService is initialized and all
1433 // preferences are registered, since some of the code that the importer
1434 // touches reads preferences.
1435 if (first_run::IsChromeFirstRun()) {
1436 first_run::AutoImport(profile_,
1437 master_prefs_->homepage_defined,
1438 master_prefs_->do_import_items,
1439 master_prefs_->dont_import_items,
1440 master_prefs_->import_bookmarks_path);
1442 // Note: this can pop the first run consent dialog on linux.
1443 first_run::DoPostImportTasks(profile_,
1444 master_prefs_->make_chrome_default_for_user);
1446 if (!master_prefs_->suppress_first_run_default_browser_prompt) {
1447 browser_creator_->set_show_main_browser_window(
1448 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_));
1449 } else {
1450 browser_creator_->set_is_default_browser_dialog_suppressed(true);
1453 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1455 #if defined(OS_WIN)
1456 // Sets things up so that if we crash from this point on, a dialog will
1457 // popup asking the user to restart chrome. It is done this late to avoid
1458 // testing against a bunch of special cases that are taken care early on.
1459 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1460 parsed_command_line());
1462 // Registers Chrome with the Windows Restart Manager, which will restore the
1463 // Chrome session when the computer is restarted after a system update.
1464 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1465 // but should run on startup if extended to handle crashes/hangs/patches.
1466 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1467 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
1468 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1469 parsed_command_line());
1472 // Verify that the profile is not on a network share and if so prepare to show
1473 // notification to the user.
1474 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_)) {
1475 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
1476 base::Bind(&NetworkProfileBubble::CheckNetworkProfile,
1477 profile_->GetPath()));
1479 #endif // defined(OS_WIN)
1481 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1482 // Init the RLZ library. This just binds the dll and schedules a task on the
1483 // file thread to be run sometime later. If this is the first run we record
1484 // the installation event.
1485 PrefService* pref_service = profile_->GetPrefs();
1486 int ping_delay = first_run::IsChromeFirstRun() ? master_prefs_->ping_delay :
1487 pref_service->GetInteger(first_run::GetPingDelayPrefName().c_str());
1488 // Negative ping delay means to send ping immediately after a first search is
1489 // recorded.
1490 rlz::RLZTracker::SetRlzDelegate(
1491 make_scoped_ptr(new ChromeRLZTrackerDelegate));
1492 rlz::RLZTracker::InitRlzDelayed(
1493 first_run::IsChromeFirstRun(), ping_delay < 0,
1494 base::TimeDelta::FromMilliseconds(abs(ping_delay)),
1495 ChromeRLZTrackerDelegate::IsGoogleDefaultSearch(profile_),
1496 ChromeRLZTrackerDelegate::IsGoogleHomepage(profile_),
1497 ChromeRLZTrackerDelegate::IsGoogleInStartpages(profile_));
1498 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1500 // Configure modules that need access to resources.
1501 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider);
1503 // In unittest mode, this will do nothing. In normal mode, this will create
1504 // the global IntranetRedirectDetector instance, which will promptly go to
1505 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1506 // to see if it should do anything else.
1508 // A simpler way of doing all this would be to have some function which could
1509 // give the time elapsed since startup, and simply have this object check that
1510 // when asked to initialize itself, but this doesn't seem to exist.
1512 // This can't be created in the BrowserProcessImpl constructor because it
1513 // needs to read prefs that get set after that runs.
1514 browser_process_->intranet_redirect_detector();
1515 GoogleSearchCounter::RegisterForNotifications();
1517 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1518 if (parsed_command_line().HasSwitch(switches::kDebugPrint)) {
1519 base::FilePath path =
1520 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint);
1521 printing::PrintedDocument::set_debug_dump_path(path);
1523 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1525 HandleTestParameters(parsed_command_line());
1526 browser_process_->metrics_service()->RecordBreakpadHasDebugger(
1527 base::debug::BeingDebugged());
1529 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1530 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1531 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1532 browser_process_->GetApplicationLocale());
1534 // Start watching for hangs during startup. We disarm this hang detector when
1535 // ThreadWatcher takes over or when browser is shutdown or when
1536 // startup_watcher_ is deleted.
1537 metrics::MetricsService::SetExecutionPhase(
1538 metrics::MetricsService::STARTUP_TIMEBOMB_ARM,
1539 g_browser_process->local_state());
1540 startup_watcher_->Arm(base::TimeDelta::FromSeconds(600));
1542 // On mobile, need for clean shutdown arises only when the application comes
1543 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1544 // http://crbug.com/179143
1545 #if !defined(OS_ANDROID)
1546 // Start watching for a hang.
1547 browser_process_->metrics_service()->LogNeedForCleanShutdown();
1548 #endif // !defined(OS_ANDROID)
1550 #if defined(ENABLE_PRINT_PREVIEW)
1551 // Create the instance of the cloud print proxy service so that it can launch
1552 // the service process if needed. This is needed because the service process
1553 // might have shutdown because an update was available.
1554 // TODO(torne): this should maybe be done with
1555 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1556 // instead?
1557 CloudPrintProxyServiceFactory::GetForProfile(profile_);
1558 #endif // defined(ENABLE_PRINT_PREVIEW)
1560 // Start watching all browser threads for responsiveness.
1561 metrics::MetricsService::SetExecutionPhase(
1562 metrics::MetricsService::THREAD_WATCHER_START,
1563 g_browser_process->local_state());
1564 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1566 #if defined(OS_ANDROID)
1567 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1568 #endif // defined(OS_ANDROID)
1570 #if !defined(DISABLE_NACL)
1571 BrowserThread::PostTask(
1572 BrowserThread::IO,
1573 FROM_HERE,
1574 base::Bind(nacl::NaClProcessHost::EarlyStartup));
1575 #endif // !defined(DISABLE_NACL)
1577 // Make sure initial prefs are recorded
1578 PrefMetricsService::Factory::GetForProfile(profile_);
1580 PreBrowserStart();
1582 // Instantiate the notification UI manager, as this triggers a perf timer
1583 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1584 // triggering the timer and call that explicitly in the approprate place.
1585 // http://crbug.com/105065.
1586 browser_process_->notification_ui_manager();
1588 // This must be called prior to RegisterComponentsForUpdate, in case the CLD
1589 // data source is based on the Component Updater.
1590 translate::BrowserCldUtils::ConfigureDefaultDataProvider();
1592 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate))
1593 RegisterComponentsForUpdate();
1595 #if defined(OS_ANDROID)
1596 chrome_variations::VariationsService* variations_service =
1597 browser_process_->variations_service();
1598 if (variations_service) {
1599 // Just initialize the policy prefs service here. Variations seed fetching
1600 // will be initialized when the app enters foreground mode.
1601 variations_service->set_policy_pref_service(profile_->GetPrefs());
1603 translate::TranslateDownloadManager::RequestLanguageList(
1604 profile_->GetPrefs());
1606 #else
1607 // Most general initialization is behind us, but opening a
1608 // tab and/or session restore and such is still to be done.
1609 base::TimeTicks browser_open_start = base::TimeTicks::Now();
1611 // We are in regular browser boot sequence. Open initial tabs and enter the
1612 // main message loop.
1613 #if defined(OS_CHROMEOS)
1614 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1615 // them this early as the cryptohome hasn't yet been mounted (which happens
1616 // only once we log in.
1617 std::vector<Profile*> last_opened_profiles;
1618 #else
1619 std::vector<Profile*> last_opened_profiles =
1620 g_browser_process->profile_manager()->GetLastOpenedProfiles();
1621 #endif // defined(OS_CHROMEOS)
1623 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep2Time",
1624 base::TimeTicks::Now() - start_time_step2);
1626 // This step is costly and is already measured in
1627 // Startup.StartupBrowserCreator_Start.
1628 bool started = browser_creator_->Start(
1629 parsed_command_line(), base::FilePath(), profile_, last_opened_profiles);
1630 const base::TimeTicks start_time_step3 = base::TimeTicks::Now();
1631 if (started) {
1632 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1633 // Initialize autoupdate timer. Timer callback costs basically nothing
1634 // when browser is not in persistent mode, so it's OK to let it ride on
1635 // the main thread. This needs to be done here because we don't want
1636 // to start the timer when Chrome is run inside a test harness.
1637 browser_process_->StartAutoupdateTimer();
1638 #endif // defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1640 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1641 // On Linux, the running exe will be updated if an upgrade becomes
1642 // available while the browser is running. We need to save the last
1643 // modified time of the exe, so we can compare to determine if there is
1644 // an upgrade while the browser is kept alive by a persistent extension.
1645 upgrade_util::SaveLastModifiedTimeOfExe();
1646 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1648 // Record now as the last successful chrome start.
1649 GoogleUpdateSettings::SetLastRunTime();
1651 #if defined(OS_MACOSX)
1652 // Call Recycle() here as late as possible, before going into the loop
1653 // because Start() will add things to it while creating the main window.
1654 if (parameters().autorelease_pool)
1655 parameters().autorelease_pool->Recycle();
1656 #endif // defined(OS_MACOSX)
1658 base::TimeDelta delay = base::TimeTicks::Now() - browser_open_start;
1659 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserOpenTabs", delay);
1661 // If we're running tests (ui_task is non-null), then we don't want to
1662 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or
1663 // RequestLanguageList
1664 if (parameters().ui_task == NULL) {
1665 // Request new variations seed information from server.
1666 chrome_variations::VariationsService* variations_service =
1667 browser_process_->variations_service();
1668 if (variations_service)
1669 variations_service->PerformPreMainMessageLoopStartup();
1671 translate::TranslateDownloadManager::RequestLanguageList(
1672 profile_->GetPrefs());
1675 run_message_loop_ = true;
1676 } else {
1677 run_message_loop_ = false;
1679 browser_creator_.reset();
1681 #if !defined(OS_LINUX) || defined(OS_CHROMEOS) // http://crbug.com/426393
1682 if (g_browser_process->metrics_service()->reporting_active())
1683 content::StartPowerUsageMonitor();
1684 #endif // !defined(OS_LINUX) || defined(OS_CHROMEOS)
1686 process_power_collector_.reset(new ProcessPowerCollector);
1687 process_power_collector_->Initialize();
1688 #endif // !defined(OS_ANDROID)
1690 PostBrowserStart();
1692 if (parameters().ui_task) {
1693 parameters().ui_task->Run();
1694 delete parameters().ui_task;
1695 run_message_loop_ = false;
1697 #if defined(OS_ANDROID)
1698 // We never run the C++ main loop on Android, since the UI thread message
1699 // loop is controlled by the OS, so this is as close as we can get to
1700 // the start of the main loop.
1701 if (result_code_ <= 0) {
1702 RecordBrowserStartupTime();
1704 #endif // defined(OS_ANDROID)
1706 #if !defined(OS_ANDROID)
1707 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep3Time",
1708 base::TimeTicks::Now() - start_time_step3);
1709 #endif // !defined(OS_ANDROID)
1711 return result_code_;
1714 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code) {
1715 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1716 #if defined(OS_ANDROID)
1717 // Chrome on Android does not use default MessageLoop. It has its own
1718 // Android specific MessageLoop
1719 NOTREACHED();
1720 return true;
1721 #else
1722 // Set the result code set in PreMainMessageLoopRun or set above.
1723 *result_code = result_code_;
1724 if (!run_message_loop_)
1725 return true; // Don't run the default message loop.
1727 // These should be invoked as close to the start of the browser's
1728 // UI thread message loop as possible to get a stable measurement
1729 // across versions.
1730 RecordBrowserStartupTime();
1732 DCHECK(base::MessageLoopForUI::IsCurrent());
1733 base::RunLoop run_loop;
1735 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1737 metrics::MetricsService::SetExecutionPhase(
1738 metrics::MetricsService::MAIN_MESSAGE_LOOP_RUN,
1739 g_browser_process->local_state());
1740 run_loop.Run();
1742 return true;
1743 #endif // defined(OS_ANDROID)
1746 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1747 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1748 #if defined(OS_ANDROID)
1749 // Chrome on Android does not use default MessageLoop. It has its own
1750 // Android specific MessageLoop
1751 NOTREACHED();
1752 #else
1753 // Start watching for jank during shutdown. It gets disarmed when
1754 // |shutdown_watcher_| object is destructed.
1755 metrics::MetricsService::SetExecutionPhase(
1756 metrics::MetricsService::SHUTDOWN_TIMEBOMB_ARM,
1757 g_browser_process->local_state());
1758 shutdown_watcher_->Arm(base::TimeDelta::FromSeconds(300));
1760 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1761 startup_watcher_->Disarm();
1763 // Remove observers attached to D-Bus clients before DbusThreadManager is
1764 // shut down.
1765 process_power_collector_.reset();
1767 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1768 chrome_extra_parts_[i]->PostMainMessageLoopRun();
1770 // Some tests don't set parameters.ui_task, so they started translate
1771 // language fetch that was never completed so we need to cleanup here
1772 // otherwise it will be done by the destructor in a wrong thread.
1773 TranslateService::Shutdown(parameters().ui_task == NULL);
1775 if (notify_result_ == ProcessSingleton::PROCESS_NONE)
1776 process_singleton_->Cleanup();
1778 // Stop all tasks that might run on WatchDogThread.
1779 ThreadWatcherList::StopWatchingAll();
1781 browser_process_->metrics_service()->Stop();
1783 restart_last_session_ = browser_shutdown::ShutdownPreThreadsStop();
1784 browser_process_->StartTearDown();
1785 #endif // defined(OS_ANDROID)
1788 void ChromeBrowserMainParts::PostDestroyThreads() {
1789 #if defined(OS_ANDROID)
1790 // On Android, there is no quit/exit. So the browser's main message loop will
1791 // not finish.
1792 NOTREACHED();
1793 #else
1794 browser_process_->PostDestroyThreads();
1795 // browser_shutdown takes care of deleting browser_process, so we need to
1796 // release it.
1797 ignore_result(browser_process_.release());
1798 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_);
1799 master_prefs_.reset();
1800 process_singleton_.reset();
1801 device_event_log::Shutdown();
1803 // We need to do this check as late as possible, but due to modularity, this
1804 // may be the last point in Chrome. This would be more effective if done at
1805 // a higher level on the stack, so that it is impossible for an early return
1806 // to bypass this code. Perhaps we need a *final* hook that is called on all
1807 // paths from content/browser/browser_main.
1808 CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
1810 #if defined(OS_CHROMEOS)
1811 chromeos::CrosSettings::Shutdown();
1812 #endif // defined(OS_CHROMEOS)
1813 #endif // defined(OS_ANDROID)
1816 // Public members:
1818 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts* parts) {
1819 chrome_extra_parts_.push_back(parts);