android-webview: Remove legacy crash handler (### Version)
[chromium-blink-merge.git] / chrome / browser / chrome_browser_main.cc
blob2b77ec8caea9a21a138f3d20fc5c73c5cf922b2f
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 // Heap allocated class that listens for first page load, kicks off stat
540 // recording and then deletes itself.
541 class LoadCompleteListener : public content::NotificationObserver {
542 public:
543 LoadCompleteListener() {
544 registrar_.Add(this,
545 content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
546 content::NotificationService::AllSources());
548 ~LoadCompleteListener() override {}
550 // content::NotificationObserver implementation.
551 void Observe(int type,
552 const content::NotificationSource& source,
553 const content::NotificationDetails& details) override {
554 DCHECK_EQ(content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, type);
555 startup_metric_utils::OnInitialPageLoadComplete();
556 delete this;
559 private:
560 content::NotificationRegistrar registrar_;
561 DISALLOW_COPY_AND_ASSIGN(LoadCompleteListener);
564 } // namespace
566 namespace chrome_browser {
568 // This error message is not localized because we failed to load the
569 // localization data files.
570 #if defined(OS_WIN)
571 const char kMissingLocaleDataTitle[] = "Missing File Error";
572 #endif // defined(OS_WIN)
574 #if defined(OS_WIN)
575 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
576 const char kMissingLocaleDataMessage[] =
577 "Unable to find locale data files. Please reinstall.";
578 #endif // defined(OS_WIN)
580 } // namespace chrome_browser
582 // BrowserMainParts ------------------------------------------------------------
584 ChromeBrowserMainParts::ChromeBrowserMainParts(
585 const content::MainFunctionParams& parameters)
586 : parameters_(parameters),
587 parsed_command_line_(parameters.command_line),
588 result_code_(content::RESULT_CODE_NORMAL_EXIT),
589 startup_watcher_(new StartupTimeBomb()),
590 shutdown_watcher_(new ShutdownWatcherHelper()),
591 browser_field_trials_(parameters.command_line),
592 profile_(NULL),
593 run_message_loop_(true),
594 notify_result_(ProcessSingleton::PROCESS_NONE),
595 local_state_(NULL),
596 restart_last_session_(false) {
597 // If we're running tests (ui_task is non-null).
598 if (parameters.ui_task)
599 browser_defaults::enable_help_app = false;
601 // Chrome disallows cookies by default. All code paths that want to use
602 // cookies need to go through one of Chrome's URLRequestContexts which have
603 // a ChromeNetworkDelegate attached that selectively allows cookies again.
604 net::URLRequest::SetDefaultCookiePolicyToBlock();
607 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
608 for (int i = static_cast<int>(chrome_extra_parts_.size())-1; i >= 0; --i)
609 delete chrome_extra_parts_[i];
610 chrome_extra_parts_.clear();
613 // This will be called after the command-line has been mutated by about:flags
614 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
615 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
616 // Must initialize metrics after labs have been converted into switches,
617 // but before field trials are set up (so that client ID is available for
618 // one-time randomized field trials).
620 // Initialize FieldTrialList to support FieldTrials that use one-time
621 // randomization.
622 metrics::MetricsService* metrics = browser_process_->metrics_service();
623 field_trial_list_.reset(
624 new base::FieldTrialList(metrics->CreateEntropyProvider().release()));
626 const base::CommandLine* command_line =
627 base::CommandLine::ForCurrentProcess();
628 if (command_line->HasSwitch(switches::kEnableBenchmarking) ||
629 command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking)) {
630 base::FieldTrial::EnableBenchmarking();
633 if (command_line->HasSwitch(switches::kForceFieldTrialParams)) {
634 bool result = chrome_variations::AssociateParamsFromString(
635 command_line->GetSwitchValueASCII(switches::kForceFieldTrialParams));
636 CHECK(result) << "Invalid --" << switches::kForceFieldTrialParams
637 << " list specified.";
640 // Ensure any field trials specified on the command line are initialized.
641 if (command_line->HasSwitch(switches::kForceFieldTrials)) {
642 std::set<std::string> unforceable_field_trials;
643 #if defined(OFFICIAL_BUILD)
644 unforceable_field_trials.insert("SettingsEnforcement");
645 #endif // defined(OFFICIAL_BUILD)
647 // Create field trials without activating them, so that this behaves in a
648 // consistent manner with field trials created from the server.
649 bool result = base::FieldTrialList::CreateTrialsFromString(
650 command_line->GetSwitchValueASCII(switches::kForceFieldTrials),
651 base::FieldTrialList::DONT_ACTIVATE_TRIALS,
652 unforceable_field_trials);
653 CHECK(result) << "Invalid --" << switches::kForceFieldTrials
654 << " list specified.";
656 if (command_line->HasSwitch(switches::kForceVariationIds)) {
657 // Create default variation ids which will always be included in the
658 // X-Client-Data request header.
659 variations::VariationsHttpHeaderProvider* provider =
660 variations::VariationsHttpHeaderProvider::GetInstance();
661 bool result = provider->SetDefaultVariationIds(
662 command_line->GetSwitchValueASCII(switches::kForceVariationIds));
663 CHECK(result) << "Invalid --" << switches::kForceVariationIds
664 << " list specified.";
665 metrics->AddSyntheticTrialObserver(provider);
667 chrome_variations::VariationsService* variations_service =
668 browser_process_->variations_service();
669 if (variations_service)
670 variations_service->CreateTrialsFromSeed();
672 // This must be called after |local_state_| is initialized.
673 browser_field_trials_.SetupFieldTrials();
675 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
676 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
677 // Even though base::Bind does AddRef and Release, the object will not be
678 // deleted after the Task is executed.
679 field_trial_synchronizer_ = new FieldTrialSynchronizer();
681 // Now that field trials have been created, initializes metrics recording.
682 metrics->InitializeMetricsRecordingState();
684 const chrome::VersionInfo::Channel channel =
685 chrome::VersionInfo::GetChannel();
687 // TODO(dalecurtis): Remove these checks and enable for all channels once we
688 // track down the root causes of crbug.com/422522 and crbug.com/478932.
689 if (channel == chrome::VersionInfo::CHANNEL_UNKNOWN ||
690 channel == chrome::VersionInfo::CHANNEL_CANARY ||
691 channel == chrome::VersionInfo::CHANNEL_DEV) {
692 media::AudioManager::EnableHangMonitor();
695 // Enable profiler instrumentation depending on the channel.
696 switch (channel) {
697 case chrome::VersionInfo::CHANNEL_UNKNOWN:
698 case chrome::VersionInfo::CHANNEL_CANARY:
699 tracked_objects::ScopedTracker::Enable();
700 break;
702 case chrome::VersionInfo::CHANNEL_DEV:
703 case chrome::VersionInfo::CHANNEL_BETA:
704 case chrome::VersionInfo::CHANNEL_STABLE:
705 // Don't enable instrumentation.
706 break;
710 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
712 void ChromeBrowserMainParts::StartMetricsRecording() {
713 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
715 g_browser_process->metrics_service()->CheckForClonedInstall(
716 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
718 g_browser_process->GetMetricsServicesManager()->UpdateUploadPermissions(true);
721 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
722 // Don't record any metrics if UI was displayed before this point e.g.
723 // warning dialogs.
724 if (startup_metric_utils::WasNonBrowserUIDisplayed())
725 return;
727 #if defined(OS_ANDROID)
728 // On Android the first run is handled in Java code, and the C++ side of
729 // Chrome doesn't know if this is the first run. This will cause some
730 // inaccuracy in the UMA statistics, but this should be minor (first runs are
731 // rare).
732 bool is_first_run = false;
733 #else
734 bool is_first_run = first_run::IsChromeFirstRun();
735 #endif // defined(OS_ANDROID)
737 // CurrentProcessInfo::CreationTime() is currently only implemented on some
738 // platforms.
739 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
740 const base::Time process_creation_time =
741 base::CurrentProcessInfo::CreationTime();
743 if (!is_first_run && !process_creation_time.is_null()) {
744 base::TimeDelta delay = base::Time::Now() - process_creation_time;
745 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserMessageLoopStartTime", delay);
747 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
749 // Record collected startup metrics.
750 startup_metric_utils::OnBrowserStartupComplete(is_first_run);
752 // Deletes self.
753 new LoadCompleteListener();
756 // -----------------------------------------------------------------------------
757 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
759 #if defined(OS_WIN)
760 #define DLLEXPORT __declspec(dllexport)
762 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
763 extern "C" {
764 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded();
767 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
768 // Need an instance of AtExitManager to handle singleton creations and
769 // deletions. We need this new instance because, the old instance created
770 // in ChromeMain() got destructed when the function returned.
771 base::AtExitManager exit_manager;
772 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
774 #endif
776 // content::BrowserMainParts implementation ------------------------------------
778 void ChromeBrowserMainParts::PreEarlyInitialization() {
779 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
780 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
781 chrome_extra_parts_[i]->PreEarlyInitialization();
784 void ChromeBrowserMainParts::PostEarlyInitialization() {
785 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
786 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
787 chrome_extra_parts_[i]->PostEarlyInitialization();
790 void ChromeBrowserMainParts::ToolkitInitialized() {
791 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
792 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
793 chrome_extra_parts_[i]->ToolkitInitialized();
796 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
797 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
799 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
800 chrome_extra_parts_[i]->PreMainMessageLoopStart();
803 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
804 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
806 // device_event_log must be initialized after the message loop. Calls to
807 // {DEVICE}_LOG prior to here will only be logged with VLOG. Some
808 // platforms (e.g. chromeos) may have already initialized this.
809 if (!device_event_log::IsInitialized())
810 device_event_log::Initialize(0 /* default max entries */);
812 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
813 chrome_extra_parts_[i]->PostMainMessageLoopStart();
816 int ChromeBrowserMainParts::PreCreateThreads() {
817 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
818 result_code_ = PreCreateThreadsImpl();
820 if (result_code_ == content::RESULT_CODE_NORMAL_EXIT) {
821 #if !defined(OS_ANDROID)
822 // These members must be initialized before exiting this function normally.
823 DCHECK(master_prefs_.get());
824 DCHECK(browser_creator_.get());
825 #endif // !defined(OS_ANDROID)
826 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
827 chrome_extra_parts_[i]->PreCreateThreads();
830 return result_code_;
833 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
834 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
835 run_message_loop_ = false;
836 #if !defined(OS_ANDROID)
837 chrome::MaybeShowInvalidUserDataDirWarningDialog();
838 #endif // !defined(OS_ANDROID)
839 if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir_))
840 return chrome::RESULT_CODE_MISSING_DATA;
842 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
843 MediaCaptureDevicesDispatcher::GetInstance();
845 // Android's first run is done in Java instead of native.
846 #if !defined(OS_ANDROID)
847 process_singleton_.reset(new ChromeProcessSingleton(
848 user_data_dir_, base::Bind(&ProcessSingletonNotificationCallback)));
850 // Cache first run state early.
851 first_run::IsChromeFirstRun();
852 #endif // !defined(OS_ANDROID)
854 scoped_refptr<base::SequencedTaskRunner> local_state_task_runner =
855 JsonPrefStore::GetTaskRunnerForFile(
856 base::FilePath(chrome::kLocalStorePoolName),
857 BrowserThread::GetBlockingPool());
860 TRACE_EVENT0("startup",
861 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
862 browser_process_.reset(new BrowserProcessImpl(local_state_task_runner.get(),
863 parsed_command_line()));
866 if (parsed_command_line().HasSwitch(switches::kEnableProfiling)) {
867 TRACE_EVENT0("startup",
868 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
869 // User wants to override default tracking status.
870 std::string flag =
871 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling);
872 // Default to basic profiling (no parent child support).
873 tracked_objects::ThreadData::Status status =
874 tracked_objects::ThreadData::PROFILING_ACTIVE;
875 if (flag.compare("0") != 0)
876 status = tracked_objects::ThreadData::DEACTIVATED;
877 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status);
880 local_state_ = InitializeLocalState(
881 local_state_task_runner.get(), parsed_command_line());
883 #if !defined(OS_ANDROID)
884 // These members must be initialized before returning from this function.
885 master_prefs_.reset(new first_run::MasterPrefs);
886 // Android doesn't use StartupBrowserCreator.
887 browser_creator_.reset(new StartupBrowserCreator);
888 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
889 chrome::UMABrowsingActivityObserver::Init();
890 #endif // !defined(OS_ANDROID)
892 #if !defined(OS_CHROMEOS)
893 // Convert active labs into switches. This needs to be done before
894 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
895 // affected by experiment flags (--touch-optimized-ui in particular).
896 // On ChromeOS system level flags are applied from the device settings from
897 // the session manager.
899 TRACE_EVENT0("startup",
900 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
901 about_flags::PrefServiceFlagsStorage flags_storage_(
902 g_browser_process->local_state());
903 about_flags::ConvertFlagsToSwitches(&flags_storage_,
904 base::CommandLine::ForCurrentProcess(),
905 about_flags::kAddSentinels);
907 #endif // !defined(OS_CHROMEOS)
909 local_state_->UpdateCommandLinePrefStore(
910 new CommandLinePrefStore(base::CommandLine::ForCurrentProcess()));
912 // Reset the command line in the crash report details, since we may have
913 // just changed it to include experiments.
914 crash_keys::SetSwitchesFromCommandLine(
915 base::CommandLine::ForCurrentProcess());
917 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
918 // needed when loading the MainMenu.nib and the language doesn't depend on
919 // anything since it comes from Cocoa.
920 #if defined(OS_MACOSX)
921 std::string locale =
922 parameters().ui_task ? "en-US" : l10n_util::GetLocaleOverride();
923 browser_process_->SetApplicationLocale(locale);
924 #else
925 const std::string locale =
926 local_state_->GetString(prefs::kApplicationLocale);
928 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
929 // method InitSharedInstance is ignored.
931 TRACE_EVENT_BEGIN0("startup",
932 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
933 const std::string loaded_locale =
934 ui::ResourceBundle::InitSharedInstanceWithLocale(
935 locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
936 TRACE_EVENT_END0("startup",
937 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
939 if (loaded_locale.empty() &&
940 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs)) {
941 ShowMissingLocaleMessageBox();
942 return chrome::RESULT_CODE_MISSING_DATA;
944 CHECK(!loaded_locale.empty()) << "Locale could not be found for " << locale;
945 browser_process_->SetApplicationLocale(loaded_locale);
947 base::FilePath resources_pack_path;
948 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
950 TRACE_EVENT0("startup",
951 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
952 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
953 resources_pack_path, ui::SCALE_FACTOR_NONE);
955 #endif // defined(OS_MACOSX)
957 // Android does first run in Java instead of native.
958 // Chrome OS has its own out-of-box-experience code.
959 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
960 // On first run, we need to process the predictor preferences before the
961 // browser's profile_manager object is created, but after ResourceBundle
962 // is initialized.
963 if (first_run::IsChromeFirstRun()) {
964 first_run::ProcessMasterPreferencesResult pmp_result =
965 first_run::ProcessMasterPreferences(user_data_dir_,
966 master_prefs_.get());
967 if (pmp_result == first_run::EULA_EXIT_NOW)
968 return chrome::RESULT_CODE_EULA_REFUSED;
970 if (!parsed_command_line().HasSwitch(switches::kApp) &&
971 !parsed_command_line().HasSwitch(switches::kAppId) &&
972 !parsed_command_line().HasSwitch(switches::kShowAppList)) {
973 AddFirstRunNewTabs(browser_creator_.get(), master_prefs_->new_tabs);
976 // TODO(macourteau): refactor preferences that are copied from
977 // master_preferences into local_state, as a "local_state" section in
978 // master preferences. If possible, a generic solution would be preferred
979 // over a copy one-by-one of specific preferences. Also see related TODO
980 // in first_run.h.
982 // Store the initial VariationsService seed in local state, if it exists
983 // in master prefs.
984 if (!master_prefs_->variations_seed.empty() ||
985 !master_prefs_->compressed_variations_seed.empty()) {
986 if (!master_prefs_->variations_seed.empty()) {
987 local_state_->SetString(prefs::kVariationsSeed,
988 master_prefs_->variations_seed);
990 if (!master_prefs_->compressed_variations_seed.empty()) {
991 local_state_->SetString(prefs::kVariationsCompressedSeed,
992 master_prefs_->compressed_variations_seed);
994 if (!master_prefs_->variations_seed_signature.empty()) {
995 local_state_->SetString(prefs::kVariationsSeedSignature,
996 master_prefs_->variations_seed_signature);
998 // Set the variation seed date to the current system time. If the user's
999 // clock is incorrect, this may cause some field trial expiry checks to
1000 // not do the right thing until the next seed update from the server,
1001 // when this value will be updated.
1002 local_state_->SetInt64(prefs::kVariationsSeedDate,
1003 base::Time::Now().ToInternalValue());
1006 if (!master_prefs_->suppress_default_browser_prompt_for_version.empty()) {
1007 local_state_->SetString(
1008 prefs::kBrowserSuppressDefaultBrowserPrompt,
1009 master_prefs_->suppress_default_browser_prompt_for_version);
1012 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1014 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
1015 // Set the product channel for crash reports.
1016 base::debug::SetCrashKeyValue(crash_keys::kChannel,
1017 chrome::VersionInfo::GetVersionStringModifier());
1018 #endif // defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
1020 // Initialize tracking synchronizer system.
1021 tracking_synchronizer_ = new metrics::TrackingSynchronizer(
1022 make_scoped_ptr(new base::DefaultTickClock()));
1024 #if defined(OS_MACOSX)
1025 // Get the Keychain API to register for distributed notifications on the main
1026 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
1027 // which doesn't. This ensures those notifications will get delivered
1028 // properly. See issue 37766.
1029 // (Note that the callback mask here is empty. I don't want to register for
1030 // any callbacks, I just want to initialize the mechanism.)
1031 SecKeychainAddCallback(&KeychainCallback, 0, NULL);
1032 #endif // defined(OS_MACOSX)
1034 #if defined(OS_CHROMEOS)
1035 // Must be done after g_browser_process is constructed, before
1036 // SetupMetricsAndFieldTrials().
1037 chromeos::CrosSettings::Initialize();
1038 #endif // defined(OS_CHROMEOS)
1040 // Now the command line has been mutated based on about:flags, we can setup
1041 // metrics and initialize field trials. The field trials are needed by
1042 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
1043 SetupMetricsAndFieldTrials();
1045 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
1046 browser_process_->PreCreateThreads();
1048 return content::RESULT_CODE_NORMAL_EXIT;
1051 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
1052 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1053 TRACK_SCOPED_REGION(
1054 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1056 result_code_ = PreMainMessageLoopRunImpl();
1058 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1059 chrome_extra_parts_[i]->PreMainMessageLoopRun();
1062 // PreMainMessageLoopRun calls these extra stages in the following order:
1063 // PreMainMessageLoopRunImpl()
1064 // ... initial setup, including browser_process_ setup.
1065 // PreProfileInit()
1066 // ... additional setup, including CreateProfile()
1067 // PostProfileInit()
1068 // ... additional setup
1069 // PreBrowserStart()
1070 // ... browser_creator_->Start (OR parameters().ui_task->Run())
1071 // PostBrowserStart()
1073 void ChromeBrowserMainParts::PreProfileInit() {
1074 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1076 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1077 chrome_extra_parts_[i]->PreProfileInit();
1079 #if !defined(OS_ANDROID)
1080 // Initialize the feedback uploader so it can setup notifications for profile
1081 // creation.
1082 feedback::FeedbackProfileObserver::Initialize();
1084 // Ephemeral profiles may have been left behind if the browser crashed.
1085 g_browser_process->profile_manager()->CleanUpEphemeralProfiles();
1086 #endif // !defined(OS_ANDROID)
1088 #if defined(ENABLE_EXTENSIONS)
1089 javascript_dialog_extensions_client::InstallClient();
1090 #endif // defined(ENABLE_EXTENSIONS)
1092 #if !defined(OS_IOS)
1093 InstallChromeJavaScriptNativeDialogFactory();
1094 #endif // !defined(OS_IOS)
1097 void ChromeBrowserMainParts::PostProfileInit() {
1098 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1100 #if defined(OS_ANDROID)
1101 DevToolsDiscoveryProviderAndroid::Install();
1102 #else
1103 ChromeDevToolsDiscoveryProvider::Install();
1104 #endif // defined(OS_ANDROID)
1106 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1107 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1108 chrome_extra_parts_[i]->PostProfileInit();
1111 void ChromeBrowserMainParts::PreBrowserStart() {
1112 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1113 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1114 chrome_extra_parts_[i]->PreBrowserStart();
1116 three_d_observer_.reset(new ThreeDAPIObserver());
1119 void ChromeBrowserMainParts::PostBrowserStart() {
1120 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1121 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1122 chrome_extra_parts_[i]->PostBrowserStart();
1123 #if !defined(OS_ANDROID)
1124 // Allow ProcessSingleton to process messages.
1125 process_singleton_->Unlock();
1126 #endif // !defined(OS_ANDROID)
1127 #if defined(ENABLE_WEBRTC)
1128 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1129 // to reduce the impact on startup time.
1130 BrowserThread::PostDelayedTask(
1131 BrowserThread::UI,
1132 FROM_HERE,
1133 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles),
1134 base::TimeDelta::FromMinutes(1));
1135 #endif // defined(ENABLE_WEBRTC)
1137 // At this point, StartupBrowserCreator::Start has run creating initial
1138 // browser windows and tabs, but no progress has been made in loading
1139 // content as the main message loop hasn't started processing tasks yet.
1140 // We setup to observe to the initial page load here to defer running
1141 // task posted via PostAfterStartupTask until its complete.
1142 AfterStartupTaskUtils::StartMonitoringStartup();
1145 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1146 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1147 TRACK_SCOPED_REGION(
1148 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1150 SCOPED_UMA_HISTOGRAM_LONG_TIMER("Startup.PreMainMessageLoopRunImplLongTime");
1151 const base::TimeTicks start_time_step1 = base::TimeTicks::Now();
1153 #if defined(OS_WIN)
1154 // Windows parental controls calls can be slow, so we do an early init here
1155 // that calculates this value off of the UI thread.
1156 IncognitoModePrefs::InitializePlatformParentalControls();
1157 #endif
1159 #if defined(ENABLE_EXTENSIONS)
1160 if (!variations::GetVariationParamValue(
1161 "LightSpeed", "EarlyInitStartup").empty()) {
1162 // Try to compute this early on another thread so that we don't spend time
1163 // during profile load initializing the extensions APIs.
1164 BrowserThread::PostTask(
1165 BrowserThread::FILE_USER_BLOCKING,
1166 FROM_HERE,
1167 base::Bind(
1168 base::IgnoreResult(&extensions::FeatureProvider::GetAPIFeatures)));
1170 #endif
1172 // Android updates the metrics service dynamically depending on whether the
1173 // application is in the foreground or not. Do not start here.
1174 #if !defined(OS_ANDROID)
1175 // Now that the file thread has been started, start recording.
1176 StartMetricsRecording();
1177 #endif // !defined(OS_ANDROID)
1179 if (!base::debug::BeingDebugged()) {
1180 // Create watchdog thread after creating all other threads because it will
1181 // watch the other threads and they must be running.
1182 browser_process_->watchdog_thread();
1185 // Do any initializating in the browser process that requires all threads
1186 // running.
1187 browser_process_->PreMainMessageLoopRun();
1189 // Record last shutdown time into a histogram.
1190 browser_shutdown::ReadLastShutdownInfo();
1192 #if defined(OS_WIN)
1193 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1194 // tasks. Those care whether the browser is already running. On Linux/Mac,
1195 // upgrade/uninstall happen separately.
1196 bool already_running = browser_util::IsBrowserAlreadyRunning();
1198 // If the command line specifies 'uninstall' then we need to work here
1199 // unless we detect another chrome browser running.
1200 if (parsed_command_line().HasSwitch(switches::kUninstall)) {
1201 return DoUninstallTasks(already_running);
1204 if (parsed_command_line().HasSwitch(switches::kHideIcons) ||
1205 parsed_command_line().HasSwitch(switches::kShowIcons)) {
1206 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1207 parsed_command_line_);
1210 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
1211 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
1212 #endif // defined(OS_WIN)
1214 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser)) {
1215 bool is_managed = g_browser_process->local_state()->IsManagedPreference(
1216 prefs::kDefaultBrowserSettingEnabled);
1217 if (is_managed && !g_browser_process->local_state()->GetBoolean(
1218 prefs::kDefaultBrowserSettingEnabled)) {
1219 return static_cast<int>(chrome::RESULT_CODE_ACTION_DISALLOWED_BY_POLICY);
1222 return ShellIntegration::SetAsDefaultBrowser() ?
1223 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT) :
1224 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED);
1227 #if defined(USE_AURA)
1228 // Make sure aura::Env has been initialized.
1229 CHECK(aura::Env::GetInstance());
1230 #endif // defined(USE_AURA)
1232 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1233 #if !defined(OS_ANDROID)
1234 // If the command line specifies --pack-extension, attempt the pack extension
1235 // startup action and exit.
1236 if (parsed_command_line().HasSwitch(switches::kPackExtension)) {
1237 extensions::StartupHelper extension_startup_helper;
1238 if (extension_startup_helper.PackExtension(parsed_command_line()))
1239 return content::RESULT_CODE_NORMAL_EXIT;
1240 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR;
1243 // When another process is running, use that process instead of starting a
1244 // new one. NotifyOtherProcess will currently give the other process up to
1245 // 20 seconds to respond. Note that this needs to be done before we attempt
1246 // to read the profile.
1247 notify_result_ = process_singleton_->NotifyOtherProcessOrCreate();
1248 switch (notify_result_) {
1249 case ProcessSingleton::PROCESS_NONE:
1250 // No process already running, fall through to starting a new one.
1251 break;
1253 case ProcessSingleton::PROCESS_NOTIFIED:
1254 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1255 // On POSIX systems, print a message notifying the process is running.
1256 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1257 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER))).c_str());
1258 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
1260 // Having a differentiated return type for testing allows for tests to
1261 // verify proper handling of some switches. When not testing, stick to
1262 // the standard Unix convention of returning zero when things went as
1263 // expected.
1264 if (parsed_command_line().HasSwitch(switches::kTestType))
1265 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED;
1266 return content::RESULT_CODE_NORMAL_EXIT;
1268 case ProcessSingleton::PROFILE_IN_USE:
1269 return chrome::RESULT_CODE_PROFILE_IN_USE;
1271 case ProcessSingleton::LOCK_ERROR:
1272 LOG(ERROR) << "Failed to create a ProcessSingleton for your profile "
1273 "directory. This means that running multiple instances "
1274 "would start multiple browser processes rather than "
1275 "opening a new window in the existing process. Aborting "
1276 "now to avoid profile corruption.";
1277 return chrome::RESULT_CODE_PROFILE_IN_USE;
1279 default:
1280 NOTREACHED();
1282 #endif // !defined(OS_ANDROID)
1284 // Handle special early return paths (which couldn't be processed even earlier
1285 // as they require the process singleton to be held) first.
1287 std::string try_chrome =
1288 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain);
1289 if (!try_chrome.empty()) {
1290 #if defined(OS_WIN)
1291 // Setup.exe has determined that we need to run a retention experiment
1292 // and has lauched chrome to show the experiment UI. It is guaranteed that
1293 // no other Chrome is currently running as the process singleton was
1294 // sucessfully grabbed above.
1295 int try_chrome_int;
1296 base::StringToInt(try_chrome, &try_chrome_int);
1297 TryChromeDialogView::Result answer = TryChromeDialogView::Show(
1298 try_chrome_int,
1299 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog,
1300 base::Unretained(process_singleton_.get())));
1301 if (answer == TryChromeDialogView::NOT_NOW)
1302 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL;
1303 if (answer == TryChromeDialogView::UNINSTALL_CHROME)
1304 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2;
1305 // At this point the user is willing to try chrome again.
1306 if (answer == TryChromeDialogView::TRY_CHROME_AS_DEFAULT) {
1307 // Only set in the unattended case, the interactive case is Windows 8.
1308 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1309 ShellIntegration::SET_DEFAULT_UNATTENDED)
1310 ShellIntegration::SetAsDefaultBrowser();
1312 #else
1313 // We don't support retention experiments on Mac or Linux.
1314 return content::RESULT_CODE_NORMAL_EXIT;
1315 #endif // defined(OS_WIN)
1318 #if defined(OS_WIN)
1319 // Do the tasks if chrome has been upgraded while it was last running.
1320 if (!already_running && upgrade_util::DoUpgradeTasks(parsed_command_line()))
1321 return content::RESULT_CODE_NORMAL_EXIT;
1323 // Check if there is any machine level Chrome installed on the current
1324 // machine. If yes and the current Chrome process is user level, we do not
1325 // allow the user level Chrome to run. So we notify the user and uninstall
1326 // user level Chrome.
1327 // Note this check needs to happen here (after the process singleton was
1328 // obtained but before potentially creating the first run sentinel).
1329 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1330 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS;
1331 #endif // defined(OS_WIN)
1333 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1334 if (sxs_linux::ShouldMigrateUserDataDir())
1335 return sxs_linux::MigrateUserDataDir();
1336 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1338 // Desktop construction occurs here, (required before profile creation).
1339 PreProfileInit();
1341 // Profile creation ----------------------------------------------------------
1343 metrics::MetricsService::SetExecutionPhase(
1344 metrics::MetricsService::CREATE_PROFILE,
1345 g_browser_process->local_state());
1347 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep1Time",
1348 base::TimeTicks::Now() - start_time_step1);
1350 // This step is costly and is already measured in Startup.CreateFirstProfile
1351 // and more directly Profile.CreateAndInitializeProfile.
1352 profile_ = CreatePrimaryProfile(parameters(),
1353 user_data_dir_,
1354 parsed_command_line());
1355 if (!profile_)
1356 return content::RESULT_CODE_NORMAL_EXIT;
1358 #if !defined(OS_ANDROID)
1359 const base::TimeTicks start_time_step2 = base::TimeTicks::Now();
1360 // The first run sentinel must be created after the process singleton was
1361 // grabbed and no early return paths were otherwise hit above.
1362 first_run::CreateSentinelIfNeeded();
1363 #endif // !defined(OS_ANDROID)
1365 #if defined(ENABLE_BACKGROUND)
1366 // Autoload any profiles which are running background apps.
1367 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1368 browser_process_->profile_manager()->AutoloadProfiles();
1369 #endif // defined(ENABLE_BACKGROUND)
1370 // Post-profile init ---------------------------------------------------------
1372 TranslateService::Initialize();
1374 // Needs to be done before PostProfileInit, since login manager on CrOS is
1375 // called inside PostProfileInit.
1376 content::WebUIControllerFactory::RegisterFactory(
1377 ChromeWebUIControllerFactory::GetInstance());
1379 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1380 // So make sure to create it before that.
1381 #if !defined(DISABLE_NACL)
1382 NaClBrowserDelegateImpl* delegate =
1383 new NaClBrowserDelegateImpl(browser_process_->profile_manager());
1384 nacl::NaClBrowser::SetDelegate(delegate);
1385 #endif // !defined(DISABLE_NACL)
1387 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1388 // (requires supporting early exit).
1389 PostProfileInit();
1391 // Retrieve cached GL strings from local state and use them for GPU
1392 // blacklist decisions.
1393 if (g_browser_process->gl_string_manager())
1394 g_browser_process->gl_string_manager()->Initialize();
1396 // Create an instance of GpuModeManager to watch gpu mode pref change.
1397 g_browser_process->gpu_mode_manager();
1399 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1400 // Show the First Run UI if this is the first time Chrome has been run on
1401 // this computer, or we're being compelled to do so by a command line flag.
1402 // Note that this be done _after_ the PrefService is initialized and all
1403 // preferences are registered, since some of the code that the importer
1404 // touches reads preferences.
1405 if (first_run::IsChromeFirstRun()) {
1406 first_run::AutoImport(profile_,
1407 master_prefs_->homepage_defined,
1408 master_prefs_->do_import_items,
1409 master_prefs_->dont_import_items,
1410 master_prefs_->import_bookmarks_path);
1412 // Note: this can pop the first run consent dialog on linux.
1413 first_run::DoPostImportTasks(profile_,
1414 master_prefs_->make_chrome_default_for_user);
1416 if (!master_prefs_->suppress_first_run_default_browser_prompt) {
1417 browser_creator_->set_show_main_browser_window(
1418 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_));
1419 } else {
1420 browser_creator_->set_is_default_browser_dialog_suppressed(true);
1423 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1425 #if defined(OS_WIN)
1426 // Sets things up so that if we crash from this point on, a dialog will
1427 // popup asking the user to restart chrome. It is done this late to avoid
1428 // testing against a bunch of special cases that are taken care early on.
1429 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1430 parsed_command_line());
1432 // Registers Chrome with the Windows Restart Manager, which will restore the
1433 // Chrome session when the computer is restarted after a system update.
1434 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1435 // but should run on startup if extended to handle crashes/hangs/patches.
1436 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1437 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
1438 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1439 parsed_command_line());
1442 // Verify that the profile is not on a network share and if so prepare to show
1443 // notification to the user.
1444 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_)) {
1445 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
1446 base::Bind(&NetworkProfileBubble::CheckNetworkProfile,
1447 profile_->GetPath()));
1449 #endif // defined(OS_WIN)
1451 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1452 // Init the RLZ library. This just binds the dll and schedules a task on the
1453 // file thread to be run sometime later. If this is the first run we record
1454 // the installation event.
1455 PrefService* pref_service = profile_->GetPrefs();
1456 int ping_delay = first_run::IsChromeFirstRun() ? master_prefs_->ping_delay :
1457 pref_service->GetInteger(first_run::GetPingDelayPrefName().c_str());
1458 // Negative ping delay means to send ping immediately after a first search is
1459 // recorded.
1460 RLZTracker::InitRlzFromProfileDelayed(
1461 profile_, first_run::IsChromeFirstRun(), ping_delay < 0,
1462 base::TimeDelta::FromMilliseconds(abs(ping_delay)));
1463 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1465 // Configure modules that need access to resources.
1466 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider);
1468 // In unittest mode, this will do nothing. In normal mode, this will create
1469 // the global IntranetRedirectDetector instance, which will promptly go to
1470 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1471 // to see if it should do anything else.
1473 // A simpler way of doing all this would be to have some function which could
1474 // give the time elapsed since startup, and simply have this object check that
1475 // when asked to initialize itself, but this doesn't seem to exist.
1477 // This can't be created in the BrowserProcessImpl constructor because it
1478 // needs to read prefs that get set after that runs.
1479 browser_process_->intranet_redirect_detector();
1480 GoogleSearchCounter::RegisterForNotifications();
1482 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1483 if (parsed_command_line().HasSwitch(switches::kDebugPrint)) {
1484 base::FilePath path =
1485 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint);
1486 printing::PrintedDocument::set_debug_dump_path(path);
1488 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1490 HandleTestParameters(parsed_command_line());
1491 browser_process_->metrics_service()->RecordBreakpadHasDebugger(
1492 base::debug::BeingDebugged());
1494 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1495 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1496 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1497 browser_process_->GetApplicationLocale());
1499 // Start watching for hangs during startup. We disarm this hang detector when
1500 // ThreadWatcher takes over or when browser is shutdown or when
1501 // startup_watcher_ is deleted.
1502 metrics::MetricsService::SetExecutionPhase(
1503 metrics::MetricsService::STARTUP_TIMEBOMB_ARM,
1504 g_browser_process->local_state());
1505 startup_watcher_->Arm(base::TimeDelta::FromSeconds(600));
1507 // On mobile, need for clean shutdown arises only when the application comes
1508 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1509 // http://crbug.com/179143
1510 #if !defined(OS_ANDROID)
1511 // Start watching for a hang.
1512 browser_process_->metrics_service()->LogNeedForCleanShutdown();
1513 #endif // !defined(OS_ANDROID)
1515 #if defined(ENABLE_PRINT_PREVIEW)
1516 // Create the instance of the cloud print proxy service so that it can launch
1517 // the service process if needed. This is needed because the service process
1518 // might have shutdown because an update was available.
1519 // TODO(torne): this should maybe be done with
1520 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1521 // instead?
1522 CloudPrintProxyServiceFactory::GetForProfile(profile_);
1523 #endif // defined(ENABLE_PRINT_PREVIEW)
1525 // Start watching all browser threads for responsiveness.
1526 metrics::MetricsService::SetExecutionPhase(
1527 metrics::MetricsService::THREAD_WATCHER_START,
1528 g_browser_process->local_state());
1529 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1531 #if defined(OS_ANDROID)
1532 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1533 #endif // defined(OS_ANDROID)
1535 #if !defined(DISABLE_NACL)
1536 BrowserThread::PostTask(
1537 BrowserThread::IO,
1538 FROM_HERE,
1539 base::Bind(nacl::NaClProcessHost::EarlyStartup));
1540 #endif // !defined(DISABLE_NACL)
1542 // Make sure initial prefs are recorded
1543 PrefMetricsService::Factory::GetForProfile(profile_);
1545 PreBrowserStart();
1547 // Instantiate the notification UI manager, as this triggers a perf timer
1548 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1549 // triggering the timer and call that explicitly in the approprate place.
1550 // http://crbug.com/105065.
1551 browser_process_->notification_ui_manager();
1553 // This must be called prior to RegisterComponentsForUpdate, in case the CLD
1554 // data source is based on the Component Updater.
1555 translate::BrowserCldUtils::ConfigureDefaultDataProvider();
1557 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate))
1558 RegisterComponentsForUpdate();
1560 #if defined(OS_ANDROID)
1561 chrome_variations::VariationsService* variations_service =
1562 browser_process_->variations_service();
1563 if (variations_service) {
1564 // Just initialize the policy prefs service here. Variations seed fetching
1565 // will be initialized when the app enters foreground mode.
1566 variations_service->set_policy_pref_service(profile_->GetPrefs());
1568 translate::TranslateDownloadManager::RequestLanguageList(
1569 profile_->GetPrefs());
1571 #else
1572 // Most general initialization is behind us, but opening a
1573 // tab and/or session restore and such is still to be done.
1574 base::TimeTicks browser_open_start = base::TimeTicks::Now();
1576 // We are in regular browser boot sequence. Open initial tabs and enter the
1577 // main message loop.
1578 #if defined(OS_CHROMEOS)
1579 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1580 // them this early as the cryptohome hasn't yet been mounted (which happens
1581 // only once we log in.
1582 std::vector<Profile*> last_opened_profiles;
1583 #else
1584 std::vector<Profile*> last_opened_profiles =
1585 g_browser_process->profile_manager()->GetLastOpenedProfiles();
1586 #endif // defined(OS_CHROMEOS)
1588 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep2Time",
1589 base::TimeTicks::Now() - start_time_step2);
1591 // This step is costly and is already measured in
1592 // Startup.StartupBrowserCreator_Start.
1593 bool started = browser_creator_->Start(
1594 parsed_command_line(), base::FilePath(), profile_, last_opened_profiles);
1595 const base::TimeTicks start_time_step3 = base::TimeTicks::Now();
1596 if (started) {
1597 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1598 // Initialize autoupdate timer. Timer callback costs basically nothing
1599 // when browser is not in persistent mode, so it's OK to let it ride on
1600 // the main thread. This needs to be done here because we don't want
1601 // to start the timer when Chrome is run inside a test harness.
1602 browser_process_->StartAutoupdateTimer();
1603 #endif // defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1605 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1606 // On Linux, the running exe will be updated if an upgrade becomes
1607 // available while the browser is running. We need to save the last
1608 // modified time of the exe, so we can compare to determine if there is
1609 // an upgrade while the browser is kept alive by a persistent extension.
1610 upgrade_util::SaveLastModifiedTimeOfExe();
1611 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1613 // Record now as the last successful chrome start.
1614 GoogleUpdateSettings::SetLastRunTime();
1616 #if defined(OS_MACOSX)
1617 // Call Recycle() here as late as possible, before going into the loop
1618 // because Start() will add things to it while creating the main window.
1619 if (parameters().autorelease_pool)
1620 parameters().autorelease_pool->Recycle();
1621 #endif // defined(OS_MACOSX)
1623 base::TimeDelta delay = base::TimeTicks::Now() - browser_open_start;
1624 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserOpenTabs", delay);
1626 // If we're running tests (ui_task is non-null), then we don't want to
1627 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or
1628 // RequestLanguageList
1629 if (parameters().ui_task == NULL) {
1630 // Request new variations seed information from server.
1631 chrome_variations::VariationsService* variations_service =
1632 browser_process_->variations_service();
1633 if (variations_service) {
1634 variations_service->StartRepeatedVariationsSeedFetch();
1636 #if defined(OS_WIN)
1637 variations_service->StartGoogleUpdateRegistrySync();
1638 #endif // defined(OS_WIN)
1641 translate::TranslateDownloadManager::RequestLanguageList(
1642 profile_->GetPrefs());
1645 run_message_loop_ = true;
1646 } else {
1647 run_message_loop_ = false;
1649 browser_creator_.reset();
1651 #if !defined(OS_LINUX) || defined(OS_CHROMEOS) // http://crbug.com/426393
1652 if (g_browser_process->metrics_service()->reporting_active())
1653 content::StartPowerUsageMonitor();
1654 #endif // !defined(OS_LINUX) || defined(OS_CHROMEOS)
1656 process_power_collector_.reset(new ProcessPowerCollector);
1657 process_power_collector_->Initialize();
1658 #endif // !defined(OS_ANDROID)
1660 PostBrowserStart();
1662 if (parameters().ui_task) {
1663 parameters().ui_task->Run();
1664 delete parameters().ui_task;
1665 run_message_loop_ = false;
1667 #if defined(OS_ANDROID)
1668 // We never run the C++ main loop on Android, since the UI thread message
1669 // loop is controlled by the OS, so this is as close as we can get to
1670 // the start of the main loop.
1671 if (result_code_ <= 0) {
1672 RecordBrowserStartupTime();
1674 #endif // defined(OS_ANDROID)
1676 #if !defined(OS_ANDROID)
1677 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep3Time",
1678 base::TimeTicks::Now() - start_time_step3);
1679 #endif // !defined(OS_ANDROID)
1681 return result_code_;
1684 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code) {
1685 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1686 #if defined(OS_ANDROID)
1687 // Chrome on Android does not use default MessageLoop. It has its own
1688 // Android specific MessageLoop
1689 NOTREACHED();
1690 return true;
1691 #else
1692 // Set the result code set in PreMainMessageLoopRun or set above.
1693 *result_code = result_code_;
1694 if (!run_message_loop_)
1695 return true; // Don't run the default message loop.
1697 // These should be invoked as close to the start of the browser's
1698 // UI thread message loop as possible to get a stable measurement
1699 // across versions.
1700 RecordBrowserStartupTime();
1702 DCHECK(base::MessageLoopForUI::IsCurrent());
1703 base::RunLoop run_loop;
1705 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1707 metrics::MetricsService::SetExecutionPhase(
1708 metrics::MetricsService::MAIN_MESSAGE_LOOP_RUN,
1709 g_browser_process->local_state());
1710 run_loop.Run();
1712 return true;
1713 #endif // defined(OS_ANDROID)
1716 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1717 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1718 #if defined(OS_ANDROID)
1719 // Chrome on Android does not use default MessageLoop. It has its own
1720 // Android specific MessageLoop
1721 NOTREACHED();
1722 #else
1724 // Start watching for jank during shutdown. It gets disarmed when
1725 // |shutdown_watcher_| object is destructed.
1726 metrics::MetricsService::SetExecutionPhase(
1727 metrics::MetricsService::SHUTDOWN_TIMEBOMB_ARM,
1728 g_browser_process->local_state());
1729 shutdown_watcher_->Arm(base::TimeDelta::FromSeconds(300));
1731 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1732 startup_watcher_->Disarm();
1734 // Remove observers attached to D-Bus clients before DbusThreadManager is
1735 // shut down.
1736 process_power_collector_.reset();
1738 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1739 chrome_extra_parts_[i]->PostMainMessageLoopRun();
1741 // Some tests don't set parameters.ui_task, so they started translate
1742 // language fetch that was never completed so we need to cleanup here
1743 // otherwise it will be done by the destructor in a wrong thread.
1744 TranslateService::Shutdown(parameters().ui_task == NULL);
1746 if (notify_result_ == ProcessSingleton::PROCESS_NONE)
1747 process_singleton_->Cleanup();
1749 // Stop all tasks that might run on WatchDogThread.
1750 ThreadWatcherList::StopWatchingAll();
1752 browser_process_->metrics_service()->Stop();
1754 restart_last_session_ = browser_shutdown::ShutdownPreThreadsStop();
1755 browser_process_->StartTearDown();
1756 #endif // defined(OS_ANDROID)
1759 void ChromeBrowserMainParts::PostDestroyThreads() {
1760 #if defined(OS_ANDROID)
1761 // On Android, there is no quit/exit. So the browser's main message loop will
1762 // not finish.
1763 NOTREACHED();
1764 #else
1765 browser_process_->PostDestroyThreads();
1766 // browser_shutdown takes care of deleting browser_process, so we need to
1767 // release it.
1768 ignore_result(browser_process_.release());
1769 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_);
1770 master_prefs_.reset();
1771 process_singleton_.reset();
1772 device_event_log::Shutdown();
1774 // We need to do this check as late as possible, but due to modularity, this
1775 // may be the last point in Chrome. This would be more effective if done at
1776 // a higher level on the stack, so that it is impossible for an early return
1777 // to bypass this code. Perhaps we need a *final* hook that is called on all
1778 // paths from content/browser/browser_main.
1779 CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
1781 #if defined(OS_CHROMEOS)
1782 chromeos::CrosSettings::Shutdown();
1783 #endif // defined(OS_CHROMEOS)
1784 #endif // defined(OS_ANDROID)
1787 // Public members:
1789 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts* parts) {
1790 chrome_extra_parts_.push_back(parts);