Move StartsWith[ASCII] to base namespace.
[chromium-blink-merge.git] / chrome / browser / chrome_browser_main.cc
blob462a2755262be0271d2f2161658ae910a610cd2b
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/chrome_browser_main.h"
7 #include <set>
8 #include <string>
9 #include <vector>
11 #include "base/at_exit.h"
12 #include "base/bind.h"
13 #include "base/command_line.h"
14 #include "base/debug/crash_logging.h"
15 #include "base/debug/debugger.h"
16 #include "base/files/file_path.h"
17 #include "base/files/file_util.h"
18 #include "base/metrics/field_trial.h"
19 #include "base/metrics/histogram_macros.h"
20 #include "base/path_service.h"
21 #include "base/prefs/json_pref_store.h"
22 #include "base/prefs/pref_registry_simple.h"
23 #include "base/prefs/pref_service.h"
24 #include "base/prefs/pref_value_store.h"
25 #include "base/prefs/scoped_user_pref_update.h"
26 #include "base/process/process_info.h"
27 #include "base/profiler/scoped_profile.h"
28 #include "base/profiler/scoped_tracker.h"
29 #include "base/run_loop.h"
30 #include "base/strings/string_number_conversions.h"
31 #include "base/strings/string_piece.h"
32 #include "base/strings/string_split.h"
33 #include "base/strings/sys_string_conversions.h"
34 #include "base/strings/utf_string_conversions.h"
35 #include "base/sys_info.h"
36 #include "base/threading/platform_thread.h"
37 #include "base/time/default_tick_clock.h"
38 #include "base/time/time.h"
39 #include "base/trace_event/trace_event.h"
40 #include "base/values.h"
41 #include "build/build_config.h"
42 #include "cc/base/switches.h"
43 #include "chrome/browser/about_flags.h"
44 #include "chrome/browser/after_startup_task_utils.h"
45 #include "chrome/browser/browser_process.h"
46 #include "chrome/browser/browser_process_impl.h"
47 #include "chrome/browser/browser_process_platform_part.h"
48 #include "chrome/browser/browser_shutdown.h"
49 #include "chrome/browser/chrome_browser_main_extra_parts.h"
50 #include "chrome/browser/component_updater/cld_component_installer.h"
51 #include "chrome/browser/component_updater/ev_whitelist_component_installer.h"
52 #include "chrome/browser/component_updater/flash_component_installer.h"
53 #include "chrome/browser/component_updater/recovery_component_installer.h"
54 #include "chrome/browser/component_updater/supervised_user_whitelist_installer.h"
55 #include "chrome/browser/component_updater/swiftshader_component_installer.h"
56 #include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
57 #include "chrome/browser/defaults.h"
58 #include "chrome/browser/first_run/first_run.h"
59 #include "chrome/browser/first_run/upgrade_util.h"
60 #include "chrome/browser/google/google_search_counter.h"
61 #include "chrome/browser/gpu/gl_string_manager.h"
62 #include "chrome/browser/gpu/three_d_api_observer.h"
63 #include "chrome/browser/media/media_capture_devices_dispatcher.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/notifications/desktop_notification_service.h"
72 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
73 #include "chrome/browser/performance_monitor/performance_monitor.h"
74 #include "chrome/browser/plugins/plugin_prefs.h"
75 #include "chrome/browser/power/process_power_collector.h"
76 #include "chrome/browser/pref_service_flags_storage.h"
77 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
78 #include "chrome/browser/prefs/command_line_pref_store.h"
79 #include "chrome/browser/prefs/incognito_mode_prefs.h"
80 #include "chrome/browser/prefs/pref_metrics_service.h"
81 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
82 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
83 #include "chrome/browser/process_singleton.h"
84 #include "chrome/browser/profiles/profile.h"
85 #include "chrome/browser/profiles/profile_manager.h"
86 #include "chrome/browser/profiles/profiles_state.h"
87 #include "chrome/browser/shell_integration.h"
88 #include "chrome/browser/translate/translate_service.h"
89 #include "chrome/browser/ui/app_list/app_list_service.h"
90 #include "chrome/browser/ui/browser.h"
91 #include "chrome/browser/ui/browser_finder.h"
92 #include "chrome/browser/ui/host_desktop.h"
93 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
94 #include "chrome/browser/ui/startup/default_browser_prompt.h"
95 #include "chrome/browser/ui/startup/startup_browser_creator.h"
96 #include "chrome/browser/ui/uma_browsing_activity_observer.h"
97 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.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/chrome_version_info.h"
103 #include "chrome/common/crash_keys.h"
104 #include "chrome/common/env_vars.h"
105 #include "chrome/common/logging_chrome.h"
106 #include "chrome/common/net/net_resource_provider.h"
107 #include "chrome/common/pref_names.h"
108 #include "chrome/common/profiling.h"
109 #include "chrome/common/variations/variations_util.h"
110 #include "chrome/grit/generated_resources.h"
111 #include "chrome/installer/util/google_update_settings.h"
112 #include "components/component_updater/component_updater_service.h"
113 #include "components/device_event_log/device_event_log.h"
114 #include "components/google/core/browser/google_util.h"
115 #include "components/language_usage_metrics/language_usage_metrics.h"
116 #include "components/metrics/call_stack_profile_metrics_provider.h"
117 #include "components/metrics/metrics_service.h"
118 #include "components/metrics/profiler/tracking_synchronizer.h"
119 #include "components/nacl/browser/nacl_browser.h"
120 #include "components/rappor/rappor_service.h"
121 #include "components/signin/core/common/profile_management_switches.h"
122 #include "components/startup_metric_utils/startup_metric_utils.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/variations_associated_data.h"
128 #include "content/public/browser/browser_thread.h"
129 #include "content/public/browser/notification_observer.h"
130 #include "content/public/browser/notification_registrar.h"
131 #include "content/public/browser/notification_service.h"
132 #include "content/public/browser/notification_types.h"
133 #include "content/public/browser/power_usage_monitor.h"
134 #include "content/public/browser/site_instance.h"
135 #include "content/public/common/content_client.h"
136 #include "content/public/common/content_switches.h"
137 #include "content/public/common/main_function_params.h"
138 #include "grit/platform_locale_settings.h"
139 #include "media/audio/audio_manager.h"
140 #include "net/base/net_module.h"
141 #include "net/cookies/cookie_monster.h"
142 #include "net/http/http_network_layer.h"
143 #include "net/http/http_stream_factory.h"
144 #include "net/url_request/url_request.h"
145 #include "ui/base/l10n/l10n_util.h"
146 #include "ui/base/layout.h"
147 #include "ui/base/resource/resource_bundle.h"
148 #include "ui/strings/grit/app_locale_settings.h"
150 #if defined(OS_ANDROID)
151 #include "chrome/browser/android/dev_tools_discovery_provider_android.h"
152 #include "chrome/browser/metrics/thread_watcher_android.h"
153 #else
154 #include "chrome/browser/devtools/chrome_devtools_discovery_provider.h"
155 #include "chrome/browser/feedback/feedback_profile_observer.h"
156 #endif // defined(OS_ANDROID)
158 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
159 #include "chrome/browser/first_run/upgrade_util_linux.h"
160 #include "chrome/browser/sxs_linux.h"
161 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
163 #if defined(OS_CHROMEOS)
164 #include "chrome/browser/chromeos/settings/cros_settings.h"
165 #include "chromeos/chromeos_switches.h"
166 #include "chromeos/settings/cros_settings_names.h"
167 #endif // defined(OS_CHROMEOS)
169 // TODO(port): several win-only methods have been pulled out of this, but
170 // BrowserMain() as a whole needs to be broken apart so that it's usable by
171 // other platforms. For now, it's just a stub. This is a serious work in
172 // progress and should not be taken as an indication of a real refactoring.
174 #if defined(OS_WIN)
175 #include "base/environment.h" // For PreRead experiment.
176 #include "base/win/windows_version.h"
177 #include "chrome/browser/browser_util_win.h"
178 #include "chrome/browser/chrome_browser_main_win.h"
179 #include "chrome/browser/chrome_select_file_dialog_factory_win.h"
180 #include "chrome/browser/component_updater/caps_installer_win.h"
181 #include "chrome/browser/component_updater/sw_reporter_installer_win.h"
182 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
183 #include "chrome/browser/first_run/upgrade_util_win.h"
184 #include "chrome/browser/ui/network_profile_bubble.h"
185 #include "chrome/installer/util/helper.h"
186 #include "chrome/installer/util/install_util.h"
187 #include "chrome/installer/util/shell_util.h"
188 #include "components/browser_watcher/exit_funnel_win.h"
189 #include "net/base/net_util.h"
190 #include "ui/base/l10n/l10n_util_win.h"
191 #include "ui/gfx/win/dpi.h"
192 #include "ui/shell_dialogs/select_file_dialog.h"
193 #endif // defined(OS_WIN)
195 #if defined(OS_MACOSX)
196 #include <Security/Security.h>
198 #include "base/mac/scoped_nsautorelease_pool.h"
199 #include "chrome/browser/mac/keystone_glue.h"
200 #endif // defined(OS_MACOSX)
202 #if !defined(OS_IOS)
203 #include "chrome/browser/ui/app_modal/chrome_javascript_native_dialog_factory.h"
204 #endif // !defined(OS_IOS)
206 #if !defined(DISABLE_NACL)
207 #include "chrome/browser/component_updater/pnacl_component_installer.h"
208 #include "components/nacl/browser/nacl_process_host.h"
209 #endif // !defined(DISABLE_NACL)
211 #if defined(ENABLE_EXTENSIONS)
212 #include "chrome/browser/extensions/startup_helper.h"
213 #include "extensions/browser/extension_protocols.h"
214 #include "extensions/common/features/feature_provider.h"
215 #include "extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.h"
216 #endif // defined(ENABLE_EXTENSIONS)
218 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
219 #include "printing/printed_document.h"
220 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
222 #if defined(ENABLE_RLZ)
223 #include "chrome/browser/rlz/rlz.h"
224 #endif // defined(ENABLE_RLZ)
226 #if defined(ENABLE_WEBRTC)
227 #include "chrome/browser/media/webrtc_log_util.h"
228 #endif // defined(ENABLE_WEBRTC)
230 #if defined(USE_AURA)
231 #include "ui/aura/env.h"
232 #endif // defined(USE_AURA)
234 using content::BrowserThread;
236 namespace {
238 // This function provides some ways to test crash and assertion handling
239 // behavior of the program.
240 void HandleTestParameters(const base::CommandLine& command_line) {
241 // This parameter causes a null pointer crash (crash reporter trigger).
242 if (command_line.HasSwitch(switches::kBrowserCrashTest)) {
243 int* bad_pointer = NULL;
244 *bad_pointer = 0;
248 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
249 void AddFirstRunNewTabs(StartupBrowserCreator* browser_creator,
250 const std::vector<GURL>& new_tabs) {
251 for (std::vector<GURL>::const_iterator it = new_tabs.begin();
252 it != new_tabs.end(); ++it) {
253 if (it->is_valid())
254 browser_creator->AddFirstRunTab(*it);
257 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
259 // Returns the new local state object, guaranteed non-NULL.
260 // |local_state_task_runner| must be a shutdown-blocking task runner.
261 PrefService* InitializeLocalState(
262 base::SequencedTaskRunner* local_state_task_runner,
263 const base::CommandLine& parsed_command_line) {
264 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
266 // Load local state. This includes the application locale so we know which
267 // locale dll to load. This also causes local state prefs to be registered.
268 PrefService* local_state = g_browser_process->local_state();
269 DCHECK(local_state);
271 #if defined(OS_WIN)
272 if (first_run::IsChromeFirstRun()) {
273 // During first run we read the google_update registry key to find what
274 // language the user selected when downloading the installer. This
275 // becomes our default language in the prefs.
276 // Other platforms obey the system locale.
277 base::string16 install_lang;
278 if (GoogleUpdateSettings::GetLanguage(&install_lang)) {
279 local_state->SetString(prefs::kApplicationLocale,
280 base::UTF16ToASCII(install_lang));
283 #endif // defined(OS_WIN)
285 // If the local state file for the current profile doesn't exist and the
286 // parent profile command line flag is present, then we should inherit some
287 // local state from the parent profile.
288 // Checking that the local state file for the current profile doesn't exist
289 // is the most robust way to determine whether we need to inherit or not
290 // since the parent profile command line flag can be present even when the
291 // current profile is not a new one, and in that case we do not want to
292 // inherit and reset the user's setting.
294 // TODO(mnissler): We should probably just instantiate a
295 // JSONPrefStore here instead of an entire PrefService. Once this is
296 // addressed, the call to browser_prefs::RegisterLocalState can move
297 // to chrome_prefs::CreateLocalState.
298 if (parsed_command_line.HasSwitch(switches::kParentProfile)) {
299 base::FilePath local_state_path;
300 PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path);
301 bool local_state_file_exists = base::PathExists(local_state_path);
302 if (!local_state_file_exists) {
303 base::FilePath parent_profile =
304 parsed_command_line.GetSwitchValuePath(switches::kParentProfile);
305 scoped_refptr<PrefRegistrySimple> registry = new PrefRegistrySimple();
306 scoped_ptr<PrefService> parent_local_state(
307 chrome_prefs::CreateLocalState(
308 parent_profile,
309 local_state_task_runner,
310 g_browser_process->policy_service(),
311 registry,
312 false));
313 registry->RegisterStringPref(prefs::kApplicationLocale, std::string());
314 // Right now, we only inherit the locale setting from the parent profile.
315 local_state->SetString(
316 prefs::kApplicationLocale,
317 parent_local_state->GetString(prefs::kApplicationLocale));
321 #if defined(OS_CHROMEOS)
322 if (parsed_command_line.HasSwitch(chromeos::switches::kLoginManager)) {
323 std::string owner_locale = local_state->GetString(prefs::kOwnerLocale);
324 // Ensure that we start with owner's locale.
325 if (!owner_locale.empty() &&
326 local_state->GetString(prefs::kApplicationLocale) != owner_locale &&
327 !local_state->IsManagedPreference(prefs::kApplicationLocale)) {
328 local_state->SetString(prefs::kApplicationLocale, owner_locale);
331 #endif // defined(OS_CHROMEOS)
333 return local_state;
336 // Initializes the primary profile, possibly doing some user prompting to pick
337 // a fallback profile. Returns the newly created profile, or NULL if startup
338 // should not continue.
339 Profile* CreatePrimaryProfile(const content::MainFunctionParams& parameters,
340 const base::FilePath& user_data_dir,
341 const base::CommandLine& parsed_command_line) {
342 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
343 TRACK_SCOPED_REGION(
344 "Startup", "ChromeBrowserMainParts::CreatePrimaryProfile");
346 base::Time start = base::Time::Now();
347 if (profiles::IsMultipleProfilesEnabled() &&
348 parsed_command_line.HasSwitch(switches::kProfileDirectory)) {
349 profiles::SetLastUsedProfile(
350 parsed_command_line.GetSwitchValueASCII(switches::kProfileDirectory));
351 // Clear kProfilesLastActive since the user only wants to launch a specific
352 // profile.
353 ListPrefUpdate update(g_browser_process->local_state(),
354 prefs::kProfilesLastActive);
355 base::ListValue* profile_list = update.Get();
356 profile_list->Clear();
359 Profile* profile = NULL;
360 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
361 // On ChromeOS and Android the ProfileManager will use the same path as the
362 // one we got passed. GetActiveUserProfile will therefore use the correct path
363 // automatically.
364 DCHECK_EQ(user_data_dir.value(),
365 g_browser_process->profile_manager()->user_data_dir().value());
366 profile = ProfileManager::GetActiveUserProfile();
367 #else
368 base::FilePath profile_path =
369 GetStartupProfilePath(user_data_dir, parsed_command_line);
371 // Without NewAvatarMenu, replace guest with any existing profile.
372 if (!switches::IsNewAvatarMenu() &&
373 profile_path == ProfileManager::GetGuestProfilePath()) {
374 profile_path = g_browser_process->profile_manager()->GetProfileInfoCache().
375 GetPathOfProfileAtIndex(0);
377 profile = g_browser_process->profile_manager()->GetProfile(
378 profile_path);
380 // If we're using the --new-profile-management flag and this profile is
381 // signed out, then we should show the user manager instead. By switching
382 // the active profile to the guest profile we ensure that no
383 // browser windows will be opened for the guest profile.
384 if (switches::IsNewProfileManagement() &&
385 profile &&
386 !profile->IsGuestSession()) {
387 ProfileInfoCache& cache =
388 g_browser_process->profile_manager()->GetProfileInfoCache();
389 size_t profile_index = cache.GetIndexOfProfileWithPath(profile_path);
391 if (profile_index != std::string::npos &&
392 cache.ProfileIsSigninRequiredAtIndex(profile_index)) {
393 profile = g_browser_process->profile_manager()->GetProfile(
394 ProfileManager::GetGuestProfilePath());
397 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID)
398 if (profile) {
399 UMA_HISTOGRAM_LONG_TIMES(
400 "Startup.CreateFirstProfile", base::Time::Now() - start);
401 return profile;
404 #if !defined(OS_WIN)
405 // TODO(port): fix this. See comments near the definition of
406 // user_data_dir. It is better to CHECK-fail here than it is to
407 // silently exit because of missing code in the above test.
408 CHECK(profile) << "Cannot get default profile.";
409 #endif // !defined(OS_WIN)
411 return NULL;
414 #if defined(OS_MACOSX)
415 OSStatus KeychainCallback(SecKeychainEvent keychain_event,
416 SecKeychainCallbackInfo* info, void* context) {
417 return noErr;
419 #endif // defined(OS_MACOSX)
421 void RegisterComponentsForUpdate() {
422 component_updater::ComponentUpdateService* cus =
423 g_browser_process->component_updater();
425 // Registration can be before or after cus->Start() so it is ok to post
426 // a task to the UI thread to do registration once you done the necessary
427 // file IO to know you existing component version.
428 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
429 RegisterRecoveryComponent(cus, g_browser_process->local_state());
430 RegisterPepperFlashComponent(cus);
431 RegisterSwiftShaderComponent(cus);
432 RegisterWidevineCdmComponent(cus);
433 #endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
435 #if !defined(DISABLE_NACL) && !defined(OS_ANDROID)
436 #if defined(OS_CHROMEOS)
437 // PNaCl on Chrome OS is on rootfs and there is no need to download it. But
438 // Chrome4ChromeOS on Linux doesn't contain PNaCl so enable component
439 // installer when running on Linux. See crbug.com/422121 for more details.
440 if (!base::SysInfo::IsRunningOnChromeOS())
441 #endif // defined(OS_CHROMEOS)
442 g_browser_process->pnacl_component_installer()->RegisterPnaclComponent(cus);
443 #endif // !defined(DISABLE_NACL) && !defined(OS_ANDROID)
445 // Registration of the CLD Component is a no-op unless the CLD data source has
446 // been configured to be the "Component" data source.
447 RegisterCldComponent(cus);
449 component_updater::SupervisedUserWhitelistInstaller* whitelist_installer =
450 g_browser_process->supervised_user_whitelist_installer();
451 whitelist_installer->RegisterComponents();
453 base::FilePath path;
454 if (PathService::Get(chrome::DIR_USER_DATA, &path)) {
455 #if defined(OS_ANDROID)
456 // The CRLSet component was enabled for some releases. This code attempts to
457 // delete it from the local disk of those how may have downloaded it.
458 g_browser_process->crl_set_fetcher()->DeleteFromDisk(path);
459 #elif !defined(OS_CHROMEOS)
460 // CRLSetFetcher attempts to load a CRL set from either the local disk or
461 // network.
462 // For Chrome OS this registration is delayed until user login.
463 g_browser_process->crl_set_fetcher()->StartInitialLoad(cus, path);
464 // Registration of the EV Whitelist component here is not necessary for:
465 // 1. Android: Because it currently does not have the EV indicator.
466 // 2. Chrome OS: On Chrome OS this registration is delayed until user login.
467 RegisterEVWhitelistComponent(cus, path);
468 #endif // defined(OS_ANDROID)
471 #if defined(OS_WIN)
472 RegisterSwReporterComponent(cus, g_browser_process->local_state());
473 RegisterCAPSComponent(cus);
474 #endif // defined(OS_WIN)
477 #if !defined(OS_ANDROID)
478 bool ProcessSingletonNotificationCallback(
479 const base::CommandLine& command_line,
480 const base::FilePath& current_directory) {
481 // Drop the request if the browser process is already in shutdown path.
482 if (!g_browser_process || g_browser_process->IsShuttingDown()) {
483 #if defined(OS_WIN)
484 browser_watcher::ExitFunnel::RecordSingleEvent(
485 chrome::kBrowserExitCodesRegistryPath,
486 L"ProcessSingletonIsShuttingDown");
487 #endif // defined(OS_WIN)
489 return false;
492 if (command_line.HasSwitch(switches::kOriginalProcessStartTime)) {
493 std::string start_time_string =
494 command_line.GetSwitchValueASCII(switches::kOriginalProcessStartTime);
495 int64 remote_start_time;
496 if (base::StringToInt64(start_time_string, &remote_start_time)) {
497 base::TimeDelta elapsed =
498 base::Time::Now() - base::Time::FromInternalValue(remote_start_time);
499 if (command_line.HasSwitch(switches::kFastStart)) {
500 UMA_HISTOGRAM_LONG_TIMES(
501 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed);
502 } else {
503 UMA_HISTOGRAM_LONG_TIMES(
504 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed);
509 g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing(
510 command_line);
512 base::FilePath user_data_dir =
513 g_browser_process->profile_manager()->user_data_dir();
514 base::FilePath startup_profile_dir =
515 GetStartupProfilePath(user_data_dir, command_line);
517 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
518 command_line, current_directory, startup_profile_dir);
519 return true;
521 #endif // !defined(OS_ANDROID)
523 void LaunchDevToolsHandlerIfNeeded(const base::CommandLine& command_line) {
524 if (command_line.HasSwitch(::switches::kRemoteDebuggingPort)) {
525 std::string port_str =
526 command_line.GetSwitchValueASCII(::switches::kRemoteDebuggingPort);
527 int port;
528 if (base::StringToInt(port_str, &port) && port >= 0 && port < 65535) {
529 g_browser_process->CreateDevToolsHttpProtocolHandler(
530 chrome::HOST_DESKTOP_TYPE_NATIVE,
531 "127.0.0.1",
532 static_cast<uint16>(port));
533 } else {
534 DLOG(WARNING) << "Invalid http debugger port number " << port;
539 } // namespace
541 namespace chrome_browser {
543 // This error message is not localized because we failed to load the
544 // localization data files.
545 #if defined(OS_WIN)
546 const char kMissingLocaleDataTitle[] = "Missing File Error";
547 #endif // defined(OS_WIN)
549 #if defined(OS_WIN)
550 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
551 const char kMissingLocaleDataMessage[] =
552 "Unable to find locale data files. Please reinstall.";
553 #endif // defined(OS_WIN)
555 } // namespace chrome_browser
557 // BrowserMainParts ------------------------------------------------------------
559 ChromeBrowserMainParts::ChromeBrowserMainParts(
560 const content::MainFunctionParams& parameters)
561 : parameters_(parameters),
562 parsed_command_line_(parameters.command_line),
563 result_code_(content::RESULT_CODE_NORMAL_EXIT),
564 startup_watcher_(new StartupTimeBomb()),
565 shutdown_watcher_(new ShutdownWatcherHelper()),
566 browser_field_trials_(parameters.command_line),
567 profile_(NULL),
568 run_message_loop_(true),
569 notify_result_(ProcessSingleton::PROCESS_NONE),
570 local_state_(NULL),
571 restart_last_session_(false) {
572 // If we're running tests (ui_task is non-null).
573 if (parameters.ui_task)
574 browser_defaults::enable_help_app = false;
576 // Chrome disallows cookies by default. All code paths that want to use
577 // cookies need to go through one of Chrome's URLRequestContexts which have
578 // a ChromeNetworkDelegate attached that selectively allows cookies again.
579 net::URLRequest::SetDefaultCookiePolicyToBlock();
582 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
583 for (int i = static_cast<int>(chrome_extra_parts_.size())-1; i >= 0; --i)
584 delete chrome_extra_parts_[i];
585 chrome_extra_parts_.clear();
588 // This will be called after the command-line has been mutated by about:flags
589 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
590 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
591 // Must initialize metrics after labs have been converted into switches,
592 // but before field trials are set up (so that client ID is available for
593 // one-time randomized field trials).
595 // Initialize FieldTrialList to support FieldTrials that use one-time
596 // randomization.
597 metrics::MetricsService* metrics = browser_process_->metrics_service();
598 field_trial_list_.reset(
599 new base::FieldTrialList(metrics->CreateEntropyProvider().release()));
601 const base::CommandLine* command_line =
602 base::CommandLine::ForCurrentProcess();
603 if (command_line->HasSwitch(switches::kEnableBenchmarking) ||
604 command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking)) {
605 base::FieldTrial::EnableBenchmarking();
608 if (command_line->HasSwitch(switches::kForceFieldTrialParams)) {
609 bool result = chrome_variations::AssociateParamsFromString(
610 command_line->GetSwitchValueASCII(switches::kForceFieldTrialParams));
611 CHECK(result) << "Invalid --" << switches::kForceFieldTrialParams
612 << " list specified.";
615 // Ensure any field trials specified on the command line are initialized.
616 if (command_line->HasSwitch(switches::kForceFieldTrials)) {
617 std::set<std::string> unforceable_field_trials;
618 #if defined(OFFICIAL_BUILD)
619 unforceable_field_trials.insert("SettingsEnforcement");
620 #endif // defined(OFFICIAL_BUILD)
622 // Create field trials without activating them, so that this behaves in a
623 // consistent manner with field trials created from the server.
624 bool result = base::FieldTrialList::CreateTrialsFromString(
625 command_line->GetSwitchValueASCII(switches::kForceFieldTrials),
626 base::FieldTrialList::DONT_ACTIVATE_TRIALS,
627 unforceable_field_trials);
628 CHECK(result) << "Invalid --" << switches::kForceFieldTrials
629 << " list specified.";
631 if (command_line->HasSwitch(switches::kForceVariationIds)) {
632 // Create default variation ids which will always be included in the
633 // X-Client-Data request header.
634 variations::VariationsHttpHeaderProvider* provider =
635 variations::VariationsHttpHeaderProvider::GetInstance();
636 bool result = provider->SetDefaultVariationIds(
637 command_line->GetSwitchValueASCII(switches::kForceVariationIds));
638 CHECK(result) << "Invalid --" << switches::kForceVariationIds
639 << " list specified.";
640 metrics->AddSyntheticTrialObserver(provider);
642 chrome_variations::VariationsService* variations_service =
643 browser_process_->variations_service();
644 if (variations_service)
645 variations_service->CreateTrialsFromSeed();
647 // This must be called after |local_state_| is initialized.
648 browser_field_trials_.SetupFieldTrials();
650 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
651 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
652 // Even though base::Bind does AddRef and Release, the object will not be
653 // deleted after the Task is executed.
654 field_trial_synchronizer_ = new FieldTrialSynchronizer();
656 // Now that field trials have been created, initializes metrics recording.
657 metrics->InitializeMetricsRecordingState();
659 const chrome::VersionInfo::Channel channel =
660 chrome::VersionInfo::GetChannel();
662 // TODO(dalecurtis): Remove these checks and enable for all channels once we
663 // track down the root causes of crbug.com/422522 and crbug.com/478932.
664 if (channel == chrome::VersionInfo::CHANNEL_UNKNOWN ||
665 channel == chrome::VersionInfo::CHANNEL_CANARY ||
666 channel == chrome::VersionInfo::CHANNEL_DEV) {
667 media::AudioManager::EnableHangMonitor();
670 // Enable profiler instrumentation depending on the channel.
671 switch (channel) {
672 case chrome::VersionInfo::CHANNEL_UNKNOWN:
673 case chrome::VersionInfo::CHANNEL_CANARY:
674 tracked_objects::ScopedTracker::Enable();
675 break;
677 case chrome::VersionInfo::CHANNEL_DEV:
678 case chrome::VersionInfo::CHANNEL_BETA:
679 case chrome::VersionInfo::CHANNEL_STABLE:
680 // Don't enable instrumentation.
681 break;
685 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
687 void ChromeBrowserMainParts::StartMetricsRecording() {
688 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
690 g_browser_process->metrics_service()->CheckForClonedInstall(
691 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
693 g_browser_process->GetMetricsServicesManager()->UpdateUploadPermissions(true);
696 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
697 // Don't record any metrics if UI was displayed before this point e.g.
698 // warning dialogs.
699 if (startup_metric_utils::WasNonBrowserUIDisplayed())
700 return;
702 #if defined(OS_ANDROID)
703 // On Android the first run is handled in Java code, and the C++ side of
704 // Chrome doesn't know if this is the first run. This will cause some
705 // inaccuracy in the UMA statistics, but this should be minor (first runs are
706 // rare).
707 bool is_first_run = false;
708 #else
709 bool is_first_run = first_run::IsChromeFirstRun();
710 #endif // defined(OS_ANDROID)
712 // CurrentProcessInfo::CreationTime() is currently only implemented on some
713 // platforms.
714 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
715 const base::Time process_creation_time =
716 base::CurrentProcessInfo::CreationTime();
718 if (!is_first_run && !process_creation_time.is_null()) {
719 base::TimeDelta delay = base::Time::Now() - process_creation_time;
720 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserMessageLoopStartTime", delay);
722 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
724 // Record collected startup metrics.
725 startup_metric_utils::OnBrowserStartupComplete(is_first_run);
728 // -----------------------------------------------------------------------------
729 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
731 #if defined(OS_WIN)
732 #define DLLEXPORT __declspec(dllexport)
734 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
735 extern "C" {
736 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded();
739 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
740 // Need an instance of AtExitManager to handle singleton creations and
741 // deletions. We need this new instance because, the old instance created
742 // in ChromeMain() got destructed when the function returned.
743 base::AtExitManager exit_manager;
744 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
746 #endif
748 // content::BrowserMainParts implementation ------------------------------------
750 void ChromeBrowserMainParts::PreEarlyInitialization() {
751 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
752 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
753 chrome_extra_parts_[i]->PreEarlyInitialization();
756 void ChromeBrowserMainParts::PostEarlyInitialization() {
757 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
758 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
759 chrome_extra_parts_[i]->PostEarlyInitialization();
762 void ChromeBrowserMainParts::ToolkitInitialized() {
763 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
764 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
765 chrome_extra_parts_[i]->ToolkitInitialized();
768 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
769 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
771 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
772 chrome_extra_parts_[i]->PreMainMessageLoopStart();
775 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
776 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
778 // device_event_log must be initialized after the message loop. Calls to
779 // {DEVICE}_LOG prior to here will only be logged with VLOG. Some
780 // platforms (e.g. chromeos) may have already initialized this.
781 if (!device_event_log::IsInitialized())
782 device_event_log::Initialize(0 /* default max entries */);
784 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
785 chrome_extra_parts_[i]->PostMainMessageLoopStart();
788 int ChromeBrowserMainParts::PreCreateThreads() {
789 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
790 result_code_ = PreCreateThreadsImpl();
792 if (result_code_ == content::RESULT_CODE_NORMAL_EXIT) {
793 #if !defined(OS_ANDROID)
794 // These members must be initialized before exiting this function normally.
795 DCHECK(master_prefs_.get());
796 DCHECK(browser_creator_.get());
797 #endif // !defined(OS_ANDROID)
798 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
799 chrome_extra_parts_[i]->PreCreateThreads();
802 return result_code_;
805 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
806 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
807 run_message_loop_ = false;
808 #if !defined(OS_ANDROID)
809 chrome::MaybeShowInvalidUserDataDirWarningDialog();
810 #endif // !defined(OS_ANDROID)
811 if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir_))
812 return chrome::RESULT_CODE_MISSING_DATA;
814 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
815 MediaCaptureDevicesDispatcher::GetInstance();
817 // Android's first run is done in Java instead of native.
818 #if !defined(OS_ANDROID)
819 process_singleton_.reset(new ChromeProcessSingleton(
820 user_data_dir_, base::Bind(&ProcessSingletonNotificationCallback)));
822 // Cache first run state early.
823 first_run::IsChromeFirstRun();
824 #endif // !defined(OS_ANDROID)
826 scoped_refptr<base::SequencedTaskRunner> local_state_task_runner =
827 JsonPrefStore::GetTaskRunnerForFile(
828 base::FilePath(chrome::kLocalStorePoolName),
829 BrowserThread::GetBlockingPool());
832 TRACE_EVENT0("startup",
833 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
834 browser_process_.reset(new BrowserProcessImpl(local_state_task_runner.get(),
835 parsed_command_line()));
838 if (parsed_command_line().HasSwitch(switches::kEnableProfiling)) {
839 TRACE_EVENT0("startup",
840 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
841 // User wants to override default tracking status.
842 std::string flag =
843 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling);
844 // Default to basic profiling (no parent child support).
845 tracked_objects::ThreadData::Status status =
846 tracked_objects::ThreadData::PROFILING_ACTIVE;
847 if (flag.compare("0") != 0)
848 status = tracked_objects::ThreadData::DEACTIVATED;
849 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status);
852 local_state_ = InitializeLocalState(
853 local_state_task_runner.get(), parsed_command_line());
855 #if !defined(OS_ANDROID)
856 // These members must be initialized before returning from this function.
857 master_prefs_.reset(new first_run::MasterPrefs);
858 // Android doesn't use StartupBrowserCreator.
859 browser_creator_.reset(new StartupBrowserCreator);
860 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
861 chrome::UMABrowsingActivityObserver::Init();
862 #endif // !defined(OS_ANDROID)
864 #if !defined(OS_CHROMEOS)
865 // Convert active labs into switches. This needs to be done before
866 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
867 // affected by experiment flags (--touch-optimized-ui in particular).
868 // On ChromeOS system level flags are applied from the device settings from
869 // the session manager.
871 TRACE_EVENT0("startup",
872 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
873 about_flags::PrefServiceFlagsStorage flags_storage_(
874 g_browser_process->local_state());
875 about_flags::ConvertFlagsToSwitches(&flags_storage_,
876 base::CommandLine::ForCurrentProcess(),
877 about_flags::kAddSentinels);
879 #endif // !defined(OS_CHROMEOS)
881 local_state_->UpdateCommandLinePrefStore(
882 new CommandLinePrefStore(base::CommandLine::ForCurrentProcess()));
884 // Reset the command line in the crash report details, since we may have
885 // just changed it to include experiments.
886 crash_keys::SetSwitchesFromCommandLine(
887 base::CommandLine::ForCurrentProcess());
889 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
890 // needed when loading the MainMenu.nib and the language doesn't depend on
891 // anything since it comes from Cocoa.
892 #if defined(OS_MACOSX)
893 std::string locale =
894 parameters().ui_task ? "en-US" : l10n_util::GetLocaleOverride();
895 browser_process_->SetApplicationLocale(locale);
896 #else
897 const std::string locale =
898 local_state_->GetString(prefs::kApplicationLocale);
900 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
901 // method InitSharedInstance is ignored.
903 TRACE_EVENT_BEGIN0("startup",
904 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
905 const std::string loaded_locale =
906 ui::ResourceBundle::InitSharedInstanceWithLocale(
907 locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
908 TRACE_EVENT_END0("startup",
909 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
911 if (loaded_locale.empty() &&
912 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs)) {
913 ShowMissingLocaleMessageBox();
914 return chrome::RESULT_CODE_MISSING_DATA;
916 CHECK(!loaded_locale.empty()) << "Locale could not be found for " << locale;
917 browser_process_->SetApplicationLocale(loaded_locale);
919 base::FilePath resources_pack_path;
920 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
922 TRACE_EVENT0("startup",
923 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
924 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
925 resources_pack_path, ui::SCALE_FACTOR_NONE);
927 #endif // defined(OS_MACOSX)
929 // Android does first run in Java instead of native.
930 // Chrome OS has its own out-of-box-experience code.
931 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
932 // On first run, we need to process the predictor preferences before the
933 // browser's profile_manager object is created, but after ResourceBundle
934 // is initialized.
935 if (first_run::IsChromeFirstRun()) {
936 first_run::ProcessMasterPreferencesResult pmp_result =
937 first_run::ProcessMasterPreferences(user_data_dir_,
938 master_prefs_.get());
939 if (pmp_result == first_run::EULA_EXIT_NOW)
940 return chrome::RESULT_CODE_EULA_REFUSED;
942 if (!parsed_command_line().HasSwitch(switches::kApp) &&
943 !parsed_command_line().HasSwitch(switches::kAppId) &&
944 !parsed_command_line().HasSwitch(switches::kShowAppList)) {
945 AddFirstRunNewTabs(browser_creator_.get(), master_prefs_->new_tabs);
948 // TODO(macourteau): refactor preferences that are copied from
949 // master_preferences into local_state, as a "local_state" section in
950 // master preferences. If possible, a generic solution would be preferred
951 // over a copy one-by-one of specific preferences. Also see related TODO
952 // in first_run.h.
954 // Store the initial VariationsService seed in local state, if it exists
955 // in master prefs.
956 if (!master_prefs_->variations_seed.empty() ||
957 !master_prefs_->compressed_variations_seed.empty()) {
958 if (!master_prefs_->variations_seed.empty()) {
959 local_state_->SetString(prefs::kVariationsSeed,
960 master_prefs_->variations_seed);
962 if (!master_prefs_->compressed_variations_seed.empty()) {
963 local_state_->SetString(prefs::kVariationsCompressedSeed,
964 master_prefs_->compressed_variations_seed);
966 if (!master_prefs_->variations_seed_signature.empty()) {
967 local_state_->SetString(prefs::kVariationsSeedSignature,
968 master_prefs_->variations_seed_signature);
970 // Set the variation seed date to the current system time. If the user's
971 // clock is incorrect, this may cause some field trial expiry checks to
972 // not do the right thing until the next seed update from the server,
973 // when this value will be updated.
974 local_state_->SetInt64(prefs::kVariationsSeedDate,
975 base::Time::Now().ToInternalValue());
978 if (!master_prefs_->suppress_default_browser_prompt_for_version.empty()) {
979 local_state_->SetString(
980 prefs::kBrowserSuppressDefaultBrowserPrompt,
981 master_prefs_->suppress_default_browser_prompt_for_version);
984 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
986 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
987 // Set the product channel for crash reports.
988 base::debug::SetCrashKeyValue(crash_keys::kChannel,
989 chrome::VersionInfo::GetVersionStringModifier());
990 #endif // defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
992 // Initialize tracking synchronizer system.
993 tracking_synchronizer_ = new metrics::TrackingSynchronizer(
994 make_scoped_ptr(new base::DefaultTickClock()));
996 #if defined(OS_MACOSX)
997 // Get the Keychain API to register for distributed notifications on the main
998 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
999 // which doesn't. This ensures those notifications will get delivered
1000 // properly. See issue 37766.
1001 // (Note that the callback mask here is empty. I don't want to register for
1002 // any callbacks, I just want to initialize the mechanism.)
1003 SecKeychainAddCallback(&KeychainCallback, 0, NULL);
1004 #endif // defined(OS_MACOSX)
1006 #if defined(OS_CHROMEOS)
1007 // Must be done after g_browser_process is constructed, before
1008 // SetupMetricsAndFieldTrials().
1009 chromeos::CrosSettings::Initialize();
1010 #endif // defined(OS_CHROMEOS)
1012 // Now the command line has been mutated based on about:flags, we can setup
1013 // metrics and initialize field trials. The field trials are needed by
1014 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
1015 SetupMetricsAndFieldTrials();
1017 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
1018 browser_process_->PreCreateThreads();
1020 return content::RESULT_CODE_NORMAL_EXIT;
1023 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
1024 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1025 TRACK_SCOPED_REGION(
1026 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1028 result_code_ = PreMainMessageLoopRunImpl();
1030 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1031 chrome_extra_parts_[i]->PreMainMessageLoopRun();
1034 // PreMainMessageLoopRun calls these extra stages in the following order:
1035 // PreMainMessageLoopRunImpl()
1036 // ... initial setup, including browser_process_ setup.
1037 // PreProfileInit()
1038 // ... additional setup, including CreateProfile()
1039 // PostProfileInit()
1040 // ... additional setup
1041 // PreBrowserStart()
1042 // ... browser_creator_->Start (OR parameters().ui_task->Run())
1043 // PostBrowserStart()
1045 void ChromeBrowserMainParts::PreProfileInit() {
1046 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1048 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1049 chrome_extra_parts_[i]->PreProfileInit();
1051 #if !defined(OS_ANDROID)
1052 // Initialize the feedback uploader so it can setup notifications for profile
1053 // creation.
1054 feedback::FeedbackProfileObserver::Initialize();
1056 // Ephemeral profiles may have been left behind if the browser crashed.
1057 g_browser_process->profile_manager()->CleanUpEphemeralProfiles();
1058 #endif // !defined(OS_ANDROID)
1060 #if defined(ENABLE_EXTENSIONS)
1061 javascript_dialog_extensions_client::InstallClient();
1062 #endif // defined(ENABLE_EXTENSIONS)
1064 #if !defined(OS_IOS)
1065 InstallChromeJavaScriptNativeDialogFactory();
1066 #endif // !defined(OS_IOS)
1069 void ChromeBrowserMainParts::PostProfileInit() {
1070 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1072 #if defined(OS_ANDROID)
1073 DevToolsDiscoveryProviderAndroid::Install();
1074 #else
1075 ChromeDevToolsDiscoveryProvider::Install();
1076 #endif // defined(OS_ANDROID)
1078 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1079 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1080 chrome_extra_parts_[i]->PostProfileInit();
1083 void ChromeBrowserMainParts::PreBrowserStart() {
1084 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1085 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1086 chrome_extra_parts_[i]->PreBrowserStart();
1088 three_d_observer_.reset(new ThreeDAPIObserver());
1091 void ChromeBrowserMainParts::PostBrowserStart() {
1092 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1093 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1094 chrome_extra_parts_[i]->PostBrowserStart();
1095 #if !defined(OS_ANDROID)
1096 // Allow ProcessSingleton to process messages.
1097 process_singleton_->Unlock();
1098 #endif // !defined(OS_ANDROID)
1099 #if defined(ENABLE_WEBRTC)
1100 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1101 // to reduce the impact on startup time.
1102 BrowserThread::PostDelayedTask(
1103 BrowserThread::UI,
1104 FROM_HERE,
1105 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles),
1106 base::TimeDelta::FromMinutes(1));
1107 #endif // defined(ENABLE_WEBRTC)
1109 // At this point, StartupBrowserCreator::Start has run creating initial
1110 // browser windows and tabs, but no progress has been made in loading
1111 // content as the main message loop hasn't started processing tasks yet.
1112 // We setup to observe to the initial page load here to defer running
1113 // task posted via PostAfterStartupTask until its complete.
1114 AfterStartupTaskUtils::StartMonitoringStartup();
1117 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1118 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1119 TRACK_SCOPED_REGION(
1120 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1122 SCOPED_UMA_HISTOGRAM_LONG_TIMER("Startup.PreMainMessageLoopRunImplLongTime");
1123 const base::TimeTicks start_time_step1 = base::TimeTicks::Now();
1125 #if defined(OS_WIN)
1126 // Windows parental controls calls can be slow, so we do an early init here
1127 // that calculates this value off of the UI thread.
1128 IncognitoModePrefs::InitializePlatformParentalControls();
1129 #endif
1131 #if defined(ENABLE_EXTENSIONS)
1132 if (!variations::GetVariationParamValue(
1133 "LightSpeed", "EarlyInitStartup").empty()) {
1134 // Try to compute this early on another thread so that we don't spend time
1135 // during profile load initializing the extensions APIs.
1136 BrowserThread::PostTask(
1137 BrowserThread::FILE_USER_BLOCKING,
1138 FROM_HERE,
1139 base::Bind(
1140 base::IgnoreResult(&extensions::FeatureProvider::GetAPIFeatures)));
1142 #endif
1144 // Android updates the metrics service dynamically depending on whether the
1145 // application is in the foreground or not. Do not start here.
1146 #if !defined(OS_ANDROID)
1147 // Now that the file thread has been started, start recording.
1148 StartMetricsRecording();
1149 #endif // !defined(OS_ANDROID)
1151 if (!base::debug::BeingDebugged()) {
1152 // Create watchdog thread after creating all other threads because it will
1153 // watch the other threads and they must be running.
1154 browser_process_->watchdog_thread();
1157 // Do any initializating in the browser process that requires all threads
1158 // running.
1159 browser_process_->PreMainMessageLoopRun();
1161 // Record last shutdown time into a histogram.
1162 browser_shutdown::ReadLastShutdownInfo();
1164 #if defined(OS_WIN)
1165 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1166 // tasks. Those care whether the browser is already running. On Linux/Mac,
1167 // upgrade/uninstall happen separately.
1168 bool already_running = browser_util::IsBrowserAlreadyRunning();
1170 // If the command line specifies 'uninstall' then we need to work here
1171 // unless we detect another chrome browser running.
1172 if (parsed_command_line().HasSwitch(switches::kUninstall)) {
1173 return DoUninstallTasks(already_running);
1176 if (parsed_command_line().HasSwitch(switches::kHideIcons) ||
1177 parsed_command_line().HasSwitch(switches::kShowIcons)) {
1178 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1179 parsed_command_line_);
1182 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
1183 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
1184 #endif // defined(OS_WIN)
1186 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser)) {
1187 bool is_managed = g_browser_process->local_state()->IsManagedPreference(
1188 prefs::kDefaultBrowserSettingEnabled);
1189 if (is_managed && !g_browser_process->local_state()->GetBoolean(
1190 prefs::kDefaultBrowserSettingEnabled)) {
1191 return static_cast<int>(chrome::RESULT_CODE_ACTION_DISALLOWED_BY_POLICY);
1194 return ShellIntegration::SetAsDefaultBrowser() ?
1195 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT) :
1196 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED);
1199 #if defined(USE_AURA)
1200 // Make sure aura::Env has been initialized.
1201 CHECK(aura::Env::GetInstance());
1202 #endif // defined(USE_AURA)
1204 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1205 #if !defined(OS_ANDROID)
1206 // If the command line specifies --pack-extension, attempt the pack extension
1207 // startup action and exit.
1208 if (parsed_command_line().HasSwitch(switches::kPackExtension)) {
1209 extensions::StartupHelper extension_startup_helper;
1210 if (extension_startup_helper.PackExtension(parsed_command_line()))
1211 return content::RESULT_CODE_NORMAL_EXIT;
1212 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR;
1215 // When another process is running, use that process instead of starting a
1216 // new one. NotifyOtherProcess will currently give the other process up to
1217 // 20 seconds to respond. Note that this needs to be done before we attempt
1218 // to read the profile.
1219 notify_result_ = process_singleton_->NotifyOtherProcessOrCreate();
1220 switch (notify_result_) {
1221 case ProcessSingleton::PROCESS_NONE:
1222 // No process already running, fall through to starting a new one.
1223 break;
1225 case ProcessSingleton::PROCESS_NOTIFIED:
1226 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1227 // On POSIX systems, print a message notifying the process is running.
1228 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1229 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER))).c_str());
1230 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
1232 // Having a differentiated return type for testing allows for tests to
1233 // verify proper handling of some switches. When not testing, stick to
1234 // the standard Unix convention of returning zero when things went as
1235 // expected.
1236 if (parsed_command_line().HasSwitch(switches::kTestType))
1237 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED;
1238 return content::RESULT_CODE_NORMAL_EXIT;
1240 case ProcessSingleton::PROFILE_IN_USE:
1241 return chrome::RESULT_CODE_PROFILE_IN_USE;
1243 case ProcessSingleton::LOCK_ERROR:
1244 LOG(ERROR) << "Failed to create a ProcessSingleton for your profile "
1245 "directory. This means that running multiple instances "
1246 "would start multiple browser processes rather than "
1247 "opening a new window in the existing process. Aborting "
1248 "now to avoid profile corruption.";
1249 return chrome::RESULT_CODE_PROFILE_IN_USE;
1251 default:
1252 NOTREACHED();
1254 #endif // !defined(OS_ANDROID)
1256 // Handle special early return paths (which couldn't be processed even earlier
1257 // as they require the process singleton to be held) first.
1259 std::string try_chrome =
1260 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain);
1261 if (!try_chrome.empty()) {
1262 #if defined(OS_WIN)
1263 // Setup.exe has determined that we need to run a retention experiment
1264 // and has lauched chrome to show the experiment UI. It is guaranteed that
1265 // no other Chrome is currently running as the process singleton was
1266 // sucessfully grabbed above.
1267 int try_chrome_int;
1268 base::StringToInt(try_chrome, &try_chrome_int);
1269 TryChromeDialogView::Result answer = TryChromeDialogView::Show(
1270 try_chrome_int,
1271 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog,
1272 base::Unretained(process_singleton_.get())));
1273 if (answer == TryChromeDialogView::NOT_NOW)
1274 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL;
1275 if (answer == TryChromeDialogView::UNINSTALL_CHROME)
1276 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2;
1277 // At this point the user is willing to try chrome again.
1278 if (answer == TryChromeDialogView::TRY_CHROME_AS_DEFAULT) {
1279 // Only set in the unattended case, the interactive case is Windows 8.
1280 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1281 ShellIntegration::SET_DEFAULT_UNATTENDED)
1282 ShellIntegration::SetAsDefaultBrowser();
1284 #else
1285 // We don't support retention experiments on Mac or Linux.
1286 return content::RESULT_CODE_NORMAL_EXIT;
1287 #endif // defined(OS_WIN)
1290 #if defined(OS_WIN)
1291 // Do the tasks if chrome has been upgraded while it was last running.
1292 if (!already_running && upgrade_util::DoUpgradeTasks(parsed_command_line()))
1293 return content::RESULT_CODE_NORMAL_EXIT;
1295 // Check if there is any machine level Chrome installed on the current
1296 // machine. If yes and the current Chrome process is user level, we do not
1297 // allow the user level Chrome to run. So we notify the user and uninstall
1298 // user level Chrome.
1299 // Note this check needs to happen here (after the process singleton was
1300 // obtained but before potentially creating the first run sentinel).
1301 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1302 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS;
1303 #endif // defined(OS_WIN)
1305 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1306 if (sxs_linux::ShouldMigrateUserDataDir())
1307 return sxs_linux::MigrateUserDataDir();
1308 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1310 // Desktop construction occurs here, (required before profile creation).
1311 PreProfileInit();
1313 // Profile creation ----------------------------------------------------------
1315 metrics::MetricsService::SetExecutionPhase(
1316 metrics::MetricsService::CREATE_PROFILE,
1317 g_browser_process->local_state());
1319 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep1Time",
1320 base::TimeTicks::Now() - start_time_step1);
1322 // This step is costly and is already measured in Startup.CreateFirstProfile
1323 // and more directly Profile.CreateAndInitializeProfile.
1324 profile_ = CreatePrimaryProfile(parameters(),
1325 user_data_dir_,
1326 parsed_command_line());
1327 if (!profile_)
1328 return content::RESULT_CODE_NORMAL_EXIT;
1330 #if !defined(OS_ANDROID)
1331 const base::TimeTicks start_time_step2 = base::TimeTicks::Now();
1332 // The first run sentinel must be created after the process singleton was
1333 // grabbed and no early return paths were otherwise hit above.
1334 first_run::CreateSentinelIfNeeded();
1335 #endif // !defined(OS_ANDROID)
1337 #if defined(ENABLE_BACKGROUND)
1338 // Autoload any profiles which are running background apps.
1339 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1340 browser_process_->profile_manager()->AutoloadProfiles();
1341 #endif // defined(ENABLE_BACKGROUND)
1342 // Post-profile init ---------------------------------------------------------
1344 TranslateService::Initialize();
1346 // Needs to be done before PostProfileInit, since login manager on CrOS is
1347 // called inside PostProfileInit.
1348 content::WebUIControllerFactory::RegisterFactory(
1349 ChromeWebUIControllerFactory::GetInstance());
1351 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1352 // So make sure to create it before that.
1353 #if !defined(DISABLE_NACL)
1354 NaClBrowserDelegateImpl* delegate =
1355 new NaClBrowserDelegateImpl(browser_process_->profile_manager());
1356 nacl::NaClBrowser::SetDelegate(delegate);
1357 #endif // !defined(DISABLE_NACL)
1359 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1360 // (requires supporting early exit).
1361 PostProfileInit();
1363 // Retrieve cached GL strings from local state and use them for GPU
1364 // blacklist decisions.
1365 if (g_browser_process->gl_string_manager())
1366 g_browser_process->gl_string_manager()->Initialize();
1368 // Create an instance of GpuModeManager to watch gpu mode pref change.
1369 g_browser_process->gpu_mode_manager();
1371 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1372 // Show the First Run UI if this is the first time Chrome has been run on
1373 // this computer, or we're being compelled to do so by a command line flag.
1374 // Note that this be done _after_ the PrefService is initialized and all
1375 // preferences are registered, since some of the code that the importer
1376 // touches reads preferences.
1377 if (first_run::IsChromeFirstRun()) {
1378 first_run::AutoImport(profile_,
1379 master_prefs_->homepage_defined,
1380 master_prefs_->do_import_items,
1381 master_prefs_->dont_import_items,
1382 master_prefs_->import_bookmarks_path);
1384 // Note: this can pop the first run consent dialog on linux.
1385 first_run::DoPostImportTasks(profile_,
1386 master_prefs_->make_chrome_default_for_user);
1388 if (!master_prefs_->suppress_first_run_default_browser_prompt) {
1389 browser_creator_->set_show_main_browser_window(
1390 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_));
1391 } else {
1392 browser_creator_->set_is_default_browser_dialog_suppressed(true);
1395 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1397 #if defined(OS_WIN)
1398 // Sets things up so that if we crash from this point on, a dialog will
1399 // popup asking the user to restart chrome. It is done this late to avoid
1400 // testing against a bunch of special cases that are taken care early on.
1401 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1402 parsed_command_line());
1404 // Registers Chrome with the Windows Restart Manager, which will restore the
1405 // Chrome session when the computer is restarted after a system update.
1406 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1407 // but should run on startup if extended to handle crashes/hangs/patches.
1408 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1409 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
1410 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1411 parsed_command_line());
1414 // Verify that the profile is not on a network share and if so prepare to show
1415 // notification to the user.
1416 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_)) {
1417 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
1418 base::Bind(&NetworkProfileBubble::CheckNetworkProfile,
1419 profile_->GetPath()));
1421 #endif // defined(OS_WIN)
1423 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1424 // Init the RLZ library. This just binds the dll and schedules a task on the
1425 // file thread to be run sometime later. If this is the first run we record
1426 // the installation event.
1427 PrefService* pref_service = profile_->GetPrefs();
1428 int ping_delay = first_run::IsChromeFirstRun() ? master_prefs_->ping_delay :
1429 pref_service->GetInteger(first_run::GetPingDelayPrefName().c_str());
1430 // Negative ping delay means to send ping immediately after a first search is
1431 // recorded.
1432 RLZTracker::InitRlzFromProfileDelayed(
1433 profile_, first_run::IsChromeFirstRun(), ping_delay < 0,
1434 base::TimeDelta::FromMilliseconds(abs(ping_delay)));
1435 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1437 // Configure modules that need access to resources.
1438 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider);
1440 // In unittest mode, this will do nothing. In normal mode, this will create
1441 // the global IntranetRedirectDetector instance, which will promptly go to
1442 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1443 // to see if it should do anything else.
1445 // A simpler way of doing all this would be to have some function which could
1446 // give the time elapsed since startup, and simply have this object check that
1447 // when asked to initialize itself, but this doesn't seem to exist.
1449 // This can't be created in the BrowserProcessImpl constructor because it
1450 // needs to read prefs that get set after that runs.
1451 browser_process_->intranet_redirect_detector();
1452 GoogleSearchCounter::RegisterForNotifications();
1454 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1455 if (parsed_command_line().HasSwitch(switches::kDebugPrint)) {
1456 base::FilePath path =
1457 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint);
1458 printing::PrintedDocument::set_debug_dump_path(path);
1460 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1462 HandleTestParameters(parsed_command_line());
1463 browser_process_->metrics_service()->RecordBreakpadHasDebugger(
1464 base::debug::BeingDebugged());
1466 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1467 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1468 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1469 browser_process_->GetApplicationLocale());
1471 // Start watching for hangs during startup. We disarm this hang detector when
1472 // ThreadWatcher takes over or when browser is shutdown or when
1473 // startup_watcher_ is deleted.
1474 metrics::MetricsService::SetExecutionPhase(
1475 metrics::MetricsService::STARTUP_TIMEBOMB_ARM,
1476 g_browser_process->local_state());
1477 startup_watcher_->Arm(base::TimeDelta::FromSeconds(600));
1479 // On mobile, need for clean shutdown arises only when the application comes
1480 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1481 // http://crbug.com/179143
1482 #if !defined(OS_ANDROID)
1483 // Start watching for a hang.
1484 browser_process_->metrics_service()->LogNeedForCleanShutdown();
1485 #endif // !defined(OS_ANDROID)
1487 #if defined(ENABLE_PRINT_PREVIEW)
1488 // Create the instance of the cloud print proxy service so that it can launch
1489 // the service process if needed. This is needed because the service process
1490 // might have shutdown because an update was available.
1491 // TODO(torne): this should maybe be done with
1492 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1493 // instead?
1494 CloudPrintProxyServiceFactory::GetForProfile(profile_);
1495 #endif // defined(ENABLE_PRINT_PREVIEW)
1497 // Start watching all browser threads for responsiveness.
1498 metrics::MetricsService::SetExecutionPhase(
1499 metrics::MetricsService::THREAD_WATCHER_START,
1500 g_browser_process->local_state());
1501 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1503 #if defined(OS_ANDROID)
1504 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1505 #endif // defined(OS_ANDROID)
1507 #if !defined(DISABLE_NACL)
1508 BrowserThread::PostTask(
1509 BrowserThread::IO,
1510 FROM_HERE,
1511 base::Bind(nacl::NaClProcessHost::EarlyStartup));
1512 #endif // !defined(DISABLE_NACL)
1514 // Make sure initial prefs are recorded
1515 PrefMetricsService::Factory::GetForProfile(profile_);
1517 PreBrowserStart();
1519 // Instantiate the notification UI manager, as this triggers a perf timer
1520 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1521 // triggering the timer and call that explicitly in the approprate place.
1522 // http://crbug.com/105065.
1523 browser_process_->notification_ui_manager();
1525 // This must be called prior to RegisterComponentsForUpdate, in case the CLD
1526 // data source is based on the Component Updater.
1527 translate::BrowserCldUtils::ConfigureDefaultDataProvider();
1529 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate))
1530 RegisterComponentsForUpdate();
1532 #if defined(OS_ANDROID)
1533 chrome_variations::VariationsService* variations_service =
1534 browser_process_->variations_service();
1535 if (variations_service) {
1536 // Just initialize the policy prefs service here. Variations seed fetching
1537 // will be initialized when the app enters foreground mode.
1538 variations_service->set_policy_pref_service(profile_->GetPrefs());
1540 translate::TranslateDownloadManager::RequestLanguageList(
1541 profile_->GetPrefs());
1543 #else
1544 // Most general initialization is behind us, but opening a
1545 // tab and/or session restore and such is still to be done.
1546 base::TimeTicks browser_open_start = base::TimeTicks::Now();
1548 // We are in regular browser boot sequence. Open initial tabs and enter the
1549 // main message loop.
1550 #if defined(OS_CHROMEOS)
1551 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1552 // them this early as the cryptohome hasn't yet been mounted (which happens
1553 // only once we log in.
1554 std::vector<Profile*> last_opened_profiles;
1555 #else
1556 std::vector<Profile*> last_opened_profiles =
1557 g_browser_process->profile_manager()->GetLastOpenedProfiles();
1558 #endif // defined(OS_CHROMEOS)
1560 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep2Time",
1561 base::TimeTicks::Now() - start_time_step2);
1563 // This step is costly and is already measured in
1564 // Startup.StartupBrowserCreator_Start.
1565 bool started = browser_creator_->Start(
1566 parsed_command_line(), base::FilePath(), profile_, last_opened_profiles);
1567 const base::TimeTicks start_time_step3 = base::TimeTicks::Now();
1568 if (started) {
1569 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1570 // Initialize autoupdate timer. Timer callback costs basically nothing
1571 // when browser is not in persistent mode, so it's OK to let it ride on
1572 // the main thread. This needs to be done here because we don't want
1573 // to start the timer when Chrome is run inside a test harness.
1574 browser_process_->StartAutoupdateTimer();
1575 #endif // defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1577 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1578 // On Linux, the running exe will be updated if an upgrade becomes
1579 // available while the browser is running. We need to save the last
1580 // modified time of the exe, so we can compare to determine if there is
1581 // an upgrade while the browser is kept alive by a persistent extension.
1582 upgrade_util::SaveLastModifiedTimeOfExe();
1583 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1585 // Record now as the last successful chrome start.
1586 GoogleUpdateSettings::SetLastRunTime();
1588 #if defined(OS_MACOSX)
1589 // Call Recycle() here as late as possible, before going into the loop
1590 // because Start() will add things to it while creating the main window.
1591 if (parameters().autorelease_pool)
1592 parameters().autorelease_pool->Recycle();
1593 #endif // defined(OS_MACOSX)
1595 base::TimeDelta delay = base::TimeTicks::Now() - browser_open_start;
1596 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserOpenTabs", delay);
1598 // If we're running tests (ui_task is non-null), then we don't want to
1599 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or
1600 // RequestLanguageList
1601 if (parameters().ui_task == NULL) {
1602 // Request new variations seed information from server.
1603 chrome_variations::VariationsService* variations_service =
1604 browser_process_->variations_service();
1605 if (variations_service) {
1606 variations_service->StartRepeatedVariationsSeedFetch();
1608 #if defined(OS_WIN)
1609 variations_service->StartGoogleUpdateRegistrySync();
1610 #endif // defined(OS_WIN)
1613 translate::TranslateDownloadManager::RequestLanguageList(
1614 profile_->GetPrefs());
1617 run_message_loop_ = true;
1618 } else {
1619 run_message_loop_ = false;
1621 browser_creator_.reset();
1623 #if !defined(OS_LINUX) || defined(OS_CHROMEOS) // http://crbug.com/426393
1624 if (g_browser_process->metrics_service()->reporting_active())
1625 content::StartPowerUsageMonitor();
1626 #endif // !defined(OS_LINUX) || defined(OS_CHROMEOS)
1628 process_power_collector_.reset(new ProcessPowerCollector);
1629 process_power_collector_->Initialize();
1630 #endif // !defined(OS_ANDROID)
1632 PostBrowserStart();
1634 if (parameters().ui_task) {
1635 parameters().ui_task->Run();
1636 delete parameters().ui_task;
1637 run_message_loop_ = false;
1639 #if defined(OS_ANDROID)
1640 // We never run the C++ main loop on Android, since the UI thread message
1641 // loop is controlled by the OS, so this is as close as we can get to
1642 // the start of the main loop.
1643 if (result_code_ <= 0) {
1644 RecordBrowserStartupTime();
1646 #endif // defined(OS_ANDROID)
1648 #if !defined(OS_ANDROID)
1649 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep3Time",
1650 base::TimeTicks::Now() - start_time_step3);
1651 #endif // !defined(OS_ANDROID)
1653 return result_code_;
1656 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code) {
1657 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1658 #if defined(OS_ANDROID)
1659 // Chrome on Android does not use default MessageLoop. It has its own
1660 // Android specific MessageLoop
1661 NOTREACHED();
1662 return true;
1663 #else
1664 // Set the result code set in PreMainMessageLoopRun or set above.
1665 *result_code = result_code_;
1666 if (!run_message_loop_)
1667 return true; // Don't run the default message loop.
1669 // These should be invoked as close to the start of the browser's
1670 // UI thread message loop as possible to get a stable measurement
1671 // across versions.
1672 RecordBrowserStartupTime();
1674 DCHECK(base::MessageLoopForUI::IsCurrent());
1675 base::RunLoop run_loop;
1677 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1679 metrics::MetricsService::SetExecutionPhase(
1680 metrics::MetricsService::MAIN_MESSAGE_LOOP_RUN,
1681 g_browser_process->local_state());
1682 run_loop.Run();
1684 return true;
1685 #endif // defined(OS_ANDROID)
1688 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1689 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1690 #if defined(OS_ANDROID)
1691 // Chrome on Android does not use default MessageLoop. It has its own
1692 // Android specific MessageLoop
1693 NOTREACHED();
1694 #else
1696 // Start watching for jank during shutdown. It gets disarmed when
1697 // |shutdown_watcher_| object is destructed.
1698 metrics::MetricsService::SetExecutionPhase(
1699 metrics::MetricsService::SHUTDOWN_TIMEBOMB_ARM,
1700 g_browser_process->local_state());
1701 shutdown_watcher_->Arm(base::TimeDelta::FromSeconds(300));
1703 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1704 startup_watcher_->Disarm();
1706 // Remove observers attached to D-Bus clients before DbusThreadManager is
1707 // shut down.
1708 process_power_collector_.reset();
1710 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1711 chrome_extra_parts_[i]->PostMainMessageLoopRun();
1713 // Some tests don't set parameters.ui_task, so they started translate
1714 // language fetch that was never completed so we need to cleanup here
1715 // otherwise it will be done by the destructor in a wrong thread.
1716 TranslateService::Shutdown(parameters().ui_task == NULL);
1718 if (notify_result_ == ProcessSingleton::PROCESS_NONE)
1719 process_singleton_->Cleanup();
1721 // Stop all tasks that might run on WatchDogThread.
1722 ThreadWatcherList::StopWatchingAll();
1724 browser_process_->metrics_service()->Stop();
1726 restart_last_session_ = browser_shutdown::ShutdownPreThreadsStop();
1727 browser_process_->StartTearDown();
1728 #endif // defined(OS_ANDROID)
1731 void ChromeBrowserMainParts::PostDestroyThreads() {
1732 #if defined(OS_ANDROID)
1733 // On Android, there is no quit/exit. So the browser's main message loop will
1734 // not finish.
1735 NOTREACHED();
1736 #else
1737 browser_process_->PostDestroyThreads();
1738 // browser_shutdown takes care of deleting browser_process, so we need to
1739 // release it.
1740 ignore_result(browser_process_.release());
1741 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_);
1742 master_prefs_.reset();
1743 process_singleton_.reset();
1744 device_event_log::Shutdown();
1746 // We need to do this check as late as possible, but due to modularity, this
1747 // may be the last point in Chrome. This would be more effective if done at
1748 // a higher level on the stack, so that it is impossible for an early return
1749 // to bypass this code. Perhaps we need a *final* hook that is called on all
1750 // paths from content/browser/browser_main.
1751 CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
1753 #if defined(OS_CHROMEOS)
1754 chromeos::CrosSettings::Shutdown();
1755 #endif // defined(OS_CHROMEOS)
1756 #endif // defined(OS_ANDROID)
1759 // Public members:
1761 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts* parts) {
1762 chrome_extra_parts_.push_back(parts);