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"
16 #include "base/at_exit.h"
17 #include "base/base_switches.h"
18 #include "base/bind.h"
19 #include "base/command_line.h"
20 #include "base/debug/crash_logging.h"
21 #include "base/debug/debugger.h"
22 #include "base/debug/leak_annotations.h"
23 #include "base/feature_list.h"
24 #include "base/files/file_path.h"
25 #include "base/files/file_util.h"
26 #include "base/logging.h"
27 #include "base/memory/ptr_util.h"
28 #include "base/memory/scoped_refptr.h"
29 #include "base/message_loop/message_loop_current.h"
30 #include "base/metrics/field_trial.h"
31 #include "base/metrics/histogram_macros.h"
32 #include "base/path_service.h"
33 #include "base/run_loop.h"
34 #include "base/strings/string16.h"
35 #include "base/strings/string_number_conversions.h"
36 #include "base/strings/string_piece.h"
37 #include "base/strings/sys_string_conversions.h"
38 #include "base/strings/utf_string_conversions.h"
39 #include "base/system/sys_info.h"
40 #include "base/task/thread_pool.h"
41 #include "base/threading/hang_watcher.h"
42 #include "base/threading/platform_thread.h"
43 #include "base/threading/thread_task_runner_handle.h"
44 #include "base/time/default_tick_clock.h"
45 #include "base/time/time.h"
46 #include "base/trace_event/trace_event.h"
47 #include "base/values.h"
48 #include "build/branding_buildflags.h"
49 #include "build/build_config.h"
50 #include "cc/base/switches.h"
51 #include "chrome/browser/about_flags.h"
52 #include "chrome/browser/active_use_util.h"
53 #include "chrome/browser/after_startup_task_utils.h"
54 #include "chrome/browser/browser_process.h"
55 #include "chrome/browser/browser_process_impl.h"
56 #include "chrome/browser/browser_process_platform_part.h"
57 #include "chrome/browser/chrome_browser_field_trials.h"
58 #include "chrome/browser/chrome_browser_main_extra_parts.h"
59 #include "chrome/browser/component_updater/registration.h"
60 #include "chrome/browser/defaults.h"
61 #include "chrome/browser/first_run/first_run.h"
62 #include "chrome/browser/lifetime/application_lifetime.h"
63 #include "chrome/browser/lifetime/browser_shutdown.h"
64 #include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h"
65 #include "chrome/browser/media/webrtc/webrtc_log_util.h"
66 #include "chrome/browser/metrics/chrome_feature_list_creator.h"
67 #include "chrome/browser/metrics/chrome_metrics_service_accessor.h"
68 #include "chrome/browser/metrics/expired_histograms_array.h"
69 #include "chrome/browser/metrics/renderer_uptime_tracker.h"
70 #include "chrome/browser/metrics/thread_watcher.h"
71 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
72 #include "chrome/browser/net/system_network_context_manager.h"
73 #include "chrome/browser/performance_monitor/process_monitor.h"
74 #include "chrome/browser/performance_monitor/system_monitor.h"
75 #include "chrome/browser/policy/chrome_browser_policy_connector.h"
76 #include "chrome/browser/prefs/chrome_command_line_pref_store.h"
77 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
78 #include "chrome/browser/prefs/pref_metrics_service.h"
79 #include "chrome/browser/process_singleton.h"
80 #include "chrome/browser/profiles/profile.h"
81 #include "chrome/browser/profiles/profile_attributes_entry.h"
82 #include "chrome/browser/profiles/profile_attributes_storage.h"
83 #include "chrome/browser/profiles/profile_manager.h"
84 #include "chrome/browser/profiles/profiles_state.h"
85 #include "chrome/browser/sessions/chrome_serialized_navigation_driver.h"
86 #include "chrome/browser/shell_integration.h"
87 #include "chrome/browser/startup_data.h"
88 #include "chrome/browser/tracing/background_tracing_field_trial.h"
89 #include "chrome/browser/tracing/trace_event_system_stats_monitor.h"
90 #include "chrome/browser/translate/translate_service.h"
91 #include "chrome/browser/ui/javascript_dialogs/chrome_javascript_app_modal_dialog_view_factory.h"
92 #include "chrome/browser/ui/profile_error_dialog.h"
93 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
94 #include "chrome/browser/ui/startup/startup_browser_creator.h"
95 #include "chrome/browser/ui/uma_browsing_activity_observer.h"
96 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
97 #include "chrome/common/buildflags.h"
98 #include "chrome/common/channel_info.h"
99 #include "chrome/common/chrome_constants.h"
100 #include "chrome/common/chrome_features.h"
101 #include "chrome/common/chrome_paths.h"
102 #include "chrome/common/chrome_result_codes.h"
103 #include "chrome/common/chrome_switches.h"
104 #include "chrome/common/crash_keys.h"
105 #include "chrome/common/env_vars.h"
106 #include "chrome/common/logging_chrome.h"
107 #include "chrome/common/media/media_resource_provider.h"
108 #include "chrome/common/net/net_resource_provider.h"
109 #include "chrome/common/pref_names.h"
110 #include "chrome/common/profiler/stack_sampling_configuration.h"
111 #include "chrome/common/profiler/thread_profiler.h"
112 #include "chrome/grit/generated_resources.h"
113 #include "chrome/installer/util/google_update_settings.h"
114 #include "components/device_event_log/device_event_log.h"
115 #include "components/embedder_support/switches.h"
116 #include "components/flags_ui/pref_service_flags_storage.h"
117 #include "components/google/core/common/google_util.h"
118 #include "components/language/content/browser/geo_language_provider.h"
119 #include "components/language/core/browser/pref_names.h"
120 #include "components/language/core/common/language_experiments.h"
121 #include "components/language_usage_metrics/language_usage_metrics.h"
122 #include "components/metrics/call_stack_profile_metrics_provider.h"
123 #include "components/metrics/call_stack_profile_params.h"
124 #include "components/metrics/expired_histogram_util.h"
125 #include "components/metrics/metrics_reporting_default_state.h"
126 #include "components/metrics/metrics_service.h"
127 #include "components/metrics_services_manager/metrics_services_manager.h"
128 #include "components/nacl/browser/nacl_browser.h"
129 #include "components/nacl/common/buildflags.h"
130 #include "components/offline_pages/buildflags/buildflags.h"
131 #include "components/prefs/json_pref_store.h"
132 #include "components/prefs/pref_registry_simple.h"
133 #include "components/prefs/pref_service.h"
134 #include "components/prefs/pref_value_store.h"
135 #include "components/prefs/scoped_user_pref_update.h"
136 #include "components/rappor/rappor_service_impl.h"
137 #include "components/site_isolation/site_isolation_policy.h"
138 #include "components/spellcheck/spellcheck_buildflags.h"
139 #include "components/startup_metric_utils/browser/startup_metric_utils.h"
140 #include "components/tracing/common/tracing_switches.h"
141 #include "components/translate/core/browser/translate_download_manager.h"
142 #include "components/variations/field_trial_config/field_trial_util.h"
143 #include "components/variations/pref_names.h"
144 #include "components/variations/service/variations_service.h"
145 #include "components/variations/synthetic_trials_active_group_id_provider.h"
146 #include "components/variations/variations_associated_data.h"
147 #include "components/variations/variations_crash_keys.h"
148 #include "components/variations/variations_http_header_provider.h"
149 #include "components/variations/variations_switches.h"
150 #include "components/version_info/version_info.h"
151 #include "content/public/browser/browser_context.h"
152 #include "content/public/browser/browser_task_traits.h"
153 #include "content/public/browser/browser_thread.h"
154 #include "content/public/browser/notification_observer.h"
155 #include "content/public/browser/notification_registrar.h"
156 #include "content/public/browser/notification_service.h"
157 #include "content/public/browser/notification_types.h"
158 #include "content/public/browser/site_instance.h"
159 #include "content/public/browser/system_connector.h"
160 #include "content/public/common/content_client.h"
161 #include "content/public/common/content_features.h"
162 #include "content/public/common/content_switches.h"
163 #include "content/public/common/main_function_params.h"
164 #include "content/public/common/profiling.h"
165 #include "extensions/buildflags/buildflags.h"
166 #include "media/base/localized_strings.h"
167 #include "media/media_buildflags.h"
168 #include "net/base/net_module.h"
169 #include "net/cookies/cookie_monster.h"
170 #include "net/http/http_network_layer.h"
171 #include "net/http/http_stream_factory.h"
172 #include "ppapi/buildflags/buildflags.h"
173 #include "printing/buildflags/buildflags.h"
174 #include "rlz/buildflags/buildflags.h"
175 #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h"
176 #include "third_party/blink/public/common/experiments/memory_ablation_experiment.h"
177 #include "ui/base/buildflags.h"
178 #include "ui/base/layout.h"
179 #include "ui/base/resource/resource_bundle.h"
181 #if defined(OS_ANDROID)
182 #include "chrome/browser/flags/android/chrome_feature_list.h"
183 #include "chrome/browser/metrics/thread_watcher_android.h"
184 #include "chrome/browser/ui/page_info/chrome_page_info_client.h"
185 #include "ui/base/resource/resource_bundle_android.h"
187 #include "chrome/browser/resource_coordinator/tab_activity_watcher.h"
188 #include "chrome/browser/resource_coordinator/tab_manager.h"
189 #include "chrome/browser/ui/browser.h"
190 #include "chrome/browser/ui/browser_finder.h"
191 #include "chrome/browser/upgrade_detector/upgrade_detector.h"
192 #include "chrome/browser/usb/web_usb_detector.h"
193 #include "ui/base/l10n/l10n_util.h"
194 #endif // defined(OS_ANDROID)
196 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
197 #include "chrome/browser/first_run/upgrade_util.h"
198 #include "chrome/browser/policy/chrome_browser_cloud_management_controller.h"
201 #if defined(OS_CHROMEOS)
202 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
203 #include "chrome/browser/chromeos/settings/cros_settings.h"
204 #include "chrome/browser/chromeos/settings/stats_reporting_controller.h"
205 #include "chromeos/constants/chromeos_switches.h"
206 #include "chromeos/settings/cros_settings_names.h"
207 #include "components/arc/metrics/stability_metrics_manager.h"
208 #endif // defined(OS_CHROMEOS)
210 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
211 #include "chrome/browser/first_run/upgrade_util_linux.h"
212 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
214 #if defined(OS_LINUX)
215 #include "components/crash/core/app/breakpad_linux.h"
216 #include "components/crash/core/app/crashpad.h"
219 #if defined(OS_MACOSX)
220 #include <Security/Security.h>
222 #include "base/mac/scoped_nsautorelease_pool.h"
223 #include "chrome/browser/app_controller_mac.h"
224 #include "chrome/browser/mac/keystone_glue.h"
225 #endif // defined(OS_MACOSX)
227 // TODO(port): several win-only methods have been pulled out of this, but
228 // BrowserMain() as a whole needs to be broken apart so that it's usable by
229 // other platforms. For now, it's just a stub. This is a serious work in
230 // progress and should not be taken as an indication of a real refactoring.
233 #include "base/trace_event/trace_event_etw_export_win.h"
234 #include "base/win/win_util.h"
235 #include "chrome/browser/chrome_browser_main_win.h"
236 #include "chrome/browser/first_run/upgrade_util_win.h"
237 #include "chrome/browser/notifications/win/notification_launch_id.h"
238 #include "chrome/browser/ui/network_profile_bubble.h"
239 #include "chrome/browser/ui/views/try_chrome_dialog_win/try_chrome_dialog.h"
240 #include "chrome/browser/win/browser_util.h"
241 #include "chrome/browser/win/chrome_select_file_dialog_factory.h"
242 #include "chrome/browser/win/parental_controls.h"
243 #include "chrome/install_static/install_util.h"
244 #include "ui/shell_dialogs/select_file_dialog.h"
245 #endif // defined(OS_WIN)
247 #if defined(OS_WIN) || defined(OS_MACOSX) || \
248 (defined(OS_LINUX) && !defined(OS_CHROMEOS))
249 #include "chrome/browser/metrics/desktop_session_duration/desktop_session_duration_tracker.h"
250 #include "chrome/browser/metrics/desktop_session_duration/touch_mode_stats_tracker.h"
251 #include "chrome/browser/profiles/profile_activity_metrics_recorder.h"
252 #include "ui/base/pointer/touch_ui_controller.h"
255 #if BUILDFLAG(ENABLE_BACKGROUND_MODE)
256 #include "chrome/browser/background/background_mode_manager.h"
257 #endif // BUILDFLAG(ENABLE_BACKGROUND_MODE)
259 #if BUILDFLAG(ENABLE_EXTENSIONS)
260 #include "chrome/browser/extensions/startup_helper.h"
261 #include "extensions/browser/extension_protocols.h"
262 #include "extensions/common/features/feature_provider.h"
263 #include "extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.h"
264 #endif // BUILDFLAG(ENABLE_EXTENSIONS)
266 #if BUILDFLAG(ENABLE_NACL)
267 #include "components/nacl/browser/nacl_process_host.h"
268 #endif // BUILDFLAG(ENABLE_NACL)
270 #if BUILDFLAG(ENABLE_OFFLINE_PAGES)
271 #include "chrome/browser/offline_pages/offline_page_info_handler.h"
274 #if BUILDFLAG(ENABLE_PLUGINS)
275 #include "chrome/browser/plugins/plugin_prefs.h"
278 #if BUILDFLAG(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
279 #include "printing/printed_document.h"
282 #if BUILDFLAG(ENABLE_PRINT_PREVIEW) && defined(OS_WIN)
283 #include "components/printing/browser/printer_capabilities.h"
284 #include "printing/backend/win_helper.h"
287 #if BUILDFLAG(ENABLE_PRINT_PREVIEW) && !defined(OS_CHROMEOS)
288 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
289 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
292 #if BUILDFLAG(ENABLE_RLZ)
293 #include "chrome/browser/rlz/chrome_rlz_tracker_delegate.h"
294 #include "components/rlz/rlz_tracker.h"
295 #endif // BUILDFLAG(ENABLE_RLZ)
297 #if BUILDFLAG(LACROS)
298 #include "ui/shell_dialogs/select_file_dialog_lacros.h"
301 #if defined(USE_AURA)
302 #include "ui/aura/env.h"
305 #if defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
306 #include "chrome/browser/spellchecker/spellcheck_factory.h"
307 #include "chrome/browser/spellchecker/spellcheck_service.h"
308 #include "components/spellcheck/browser/pref_names.h"
309 #include "components/spellcheck/common/spellcheck_features.h"
310 #endif // defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
314 #if !defined(OS_ANDROID)
315 // Holds the RunLoop for the non-Android MainMessageLoopRun() to Run().
316 base::RunLoop* g_run_loop = nullptr;
319 // This function provides some ways to test crash and assertion handling
320 // behavior of the program.
321 void HandleTestParameters(const base::CommandLine& command_line) {
322 // This parameter causes a null pointer crash (crash reporter trigger).
323 if (command_line.HasSwitch(switches::kBrowserCrashTest)) {
328 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
329 void AddFirstRunNewTabs(StartupBrowserCreator* browser_creator,
330 const std::vector<GURL>& new_tabs) {
331 for (auto it = new_tabs.begin(); it != new_tabs.end(); ++it) {
333 browser_creator->AddFirstRunTab(*it);
336 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
338 // Initializes the primary profile, possibly doing some user prompting to pick
339 // a fallback profile. Returns the newly created profile, or NULL if startup
340 // should not continue.
341 Profile* CreatePrimaryProfile(const content::MainFunctionParams& parameters,
342 const base::FilePath& user_data_dir,
343 const base::CommandLine& parsed_command_line) {
344 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
346 base::Time start = base::Time::Now();
348 bool set_last_used_profile = false;
350 // If the browser is launched due to activation on Windows native
351 // notification, the profile id encoded in the notification launch id should
352 // be chosen over all others.
354 std::string last_used_profile_id =
355 NotificationLaunchId::GetNotificationLaunchProfileId(parsed_command_line);
356 if (!last_used_profile_id.empty()) {
357 profiles::SetLastUsedProfile(last_used_profile_id);
358 set_last_used_profile = true;
360 #endif // defined(OS_WIN)
362 bool profile_dir_specified =
363 profiles::IsMultipleProfilesEnabled() &&
364 parsed_command_line.HasSwitch(switches::kProfileDirectory);
365 if (!set_last_used_profile && profile_dir_specified) {
366 profiles::SetLastUsedProfile(
367 parsed_command_line.GetSwitchValueASCII(switches::kProfileDirectory));
368 set_last_used_profile = true;
371 if (set_last_used_profile) {
372 // Clear kProfilesLastActive since the user only wants to launch a specific
374 ListPrefUpdate update(g_browser_process->local_state(),
375 prefs::kProfilesLastActive);
376 base::ListValue* profile_list = update.Get();
377 profile_list->Clear();
380 Profile* profile = nullptr;
381 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
382 // On ChromeOS and Android the ProfileManager will use the same path as the
383 // one we got passed. CreateInitialProfile will therefore use the correct path
385 DCHECK_EQ(user_data_dir.value(),
386 g_browser_process->profile_manager()->user_data_dir().value());
387 profile = ProfileManager::CreateInitialProfile();
389 // TODO(port): fix this. See comments near the definition of |user_data_dir|.
390 // It is better to CHECK-fail here than it is to silently exit because of
391 // missing code in the above test.
392 CHECK(profile) << "Cannot get default profile.";
395 profile = GetStartupProfile(user_data_dir, parsed_command_line);
397 if (!profile && !set_last_used_profile)
398 profile = GetFallbackStartupProfile();
401 ProfileErrorType error_type =
402 profile_dir_specified ? ProfileErrorType::CREATE_FAILURE_SPECIFIED
403 : ProfileErrorType::CREATE_FAILURE_ALL;
405 // TODO(lwchkg): What diagnostics do you want to include in the feedback
406 // report when an error occurs?
407 ShowProfileErrorDialog(error_type, IDS_COULDNT_STARTUP_PROFILE_ERROR,
408 "Error creating primary profile.");
411 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID)
413 UMA_HISTOGRAM_LONG_TIMES(
414 "Startup.CreateFirstProfile", base::Time::Now() - start);
418 #if defined(OS_MACOSX)
419 OSStatus KeychainCallback(SecKeychainEvent keychain_event,
420 SecKeychainCallbackInfo* info, void* context) {
423 #endif // defined(OS_MACOSX)
425 #if !defined(OS_ANDROID)
426 void ProcessSingletonNotificationCallbackImpl(
427 const base::CommandLine& command_line,
428 const base::FilePath& current_directory) {
429 // Drop the request if the browser process is already shutting down.
430 if (!g_browser_process || g_browser_process->IsShuttingDown())
433 g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing(
436 base::FilePath user_data_dir =
437 g_browser_process->profile_manager()->user_data_dir();
438 base::FilePath startup_profile_dir =
439 GetStartupProfilePath(user_data_dir, command_line);
441 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
442 command_line, current_directory, startup_profile_dir);
444 // Record now as the last successful chrome start.
445 if (ShouldRecordActiveUse(command_line))
446 GoogleUpdateSettings::SetLastRunTime();
449 bool ProcessSingletonNotificationCallback(
450 const base::CommandLine& command_line,
451 const base::FilePath& current_directory) {
452 // Drop the request if the browser process is already shutting down.
453 // Note that we're going to post an async task below. Even if the browser
454 // process isn't shutting down right now, it could be by the time the task
455 // starts running. So, an additional check needs to happen when it starts.
456 // But regardless of any future check, there is no reason to post the task
457 // now if we know we're already shutting down.
458 if (!g_browser_process || g_browser_process->IsShuttingDown())
461 // In order to handle this request on Windows, there is platform specific
462 // code in browser_finder.cc that requires making outbound COM calls to
463 // cross-apartment shell objects (via IVirtualDesktopManager). That is not
464 // allowed within a SendMessage handler, which this function is a part of.
465 // So, we post a task to asynchronously finish the command line processing.
466 return base::ThreadTaskRunnerHandle::Get()->PostTask(
467 FROM_HERE, base::BindOnce(&ProcessSingletonNotificationCallbackImpl,
468 command_line, current_directory));
470 #endif // !defined(OS_ANDROID)
472 class ScopedMainMessageLoopRunEvent {
474 ScopedMainMessageLoopRunEvent() {
475 TRACE_EVENT_NESTABLE_ASYNC_BEGIN0(
476 "toplevel", "ChromeBrowserMainParts::MainMessageLoopRun", this);
478 ~ScopedMainMessageLoopRunEvent() {
479 TRACE_EVENT_NESTABLE_ASYNC_END0(
480 "toplevel", "ChromeBrowserMainParts::MainMessageLoopRun", this);
486 // BrowserMainParts ------------------------------------------------------------
488 ChromeBrowserMainParts::ChromeBrowserMainParts(
489 const content::MainFunctionParams& parameters,
490 StartupData* startup_data)
491 : parameters_(parameters),
492 parsed_command_line_(parameters.command_line),
493 result_code_(service_manager::RESULT_CODE_NORMAL_EXIT),
494 should_call_pre_main_loop_start_startup_on_variations_service_(
495 !parameters.ui_task),
497 run_message_loop_(true),
498 startup_data_(startup_data) {
499 DCHECK(startup_data_);
500 // If we're running tests (ui_task is non-null).
501 if (parameters.ui_task)
502 browser_defaults::enable_help_app = false;
504 #if !defined(OS_ANDROID)
505 shutdown_watcher_ = std::make_unique<ShutdownWatcherHelper>();
506 #endif // !defined(OS_ANDROID)
509 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
510 for (int i = static_cast<int>(chrome_extra_parts_.size())-1; i >= 0; --i)
511 delete chrome_extra_parts_[i];
512 chrome_extra_parts_.clear();
515 void ChromeBrowserMainParts::SetupMetrics() {
516 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetrics");
517 metrics::MetricsService* metrics = browser_process_->metrics_service();
518 metrics->synthetic_trial_registry()->AddSyntheticTrialObserver(
519 variations::VariationsHttpHeaderProvider::GetInstance());
520 metrics->synthetic_trial_registry()->AddSyntheticTrialObserver(
521 variations::SyntheticTrialsActiveGroupIdProvider::GetInstance());
522 // Now that field trials have been created, initializes metrics recording.
523 metrics->InitializeMetricsRecordingState();
525 startup_data_->chrome_feature_list_creator()
526 ->browser_field_trials()
527 ->RegisterSyntheticTrials();
531 void ChromeBrowserMainParts::StartMetricsRecording() {
532 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
534 #if defined(OS_ANDROID)
535 // Android updates the metrics service dynamically depending on whether the
536 // application is in the foreground or not. Do not start here unless
537 // kUmaBackgroundSessions is enabled.
538 if (!base::FeatureList::IsEnabled(chrome::android::kUmaBackgroundSessions))
542 g_browser_process->metrics_service()->CheckForClonedInstall();
545 // The last live timestamp is used to assess whether a browser crash occurred
546 // due to a full system crash. Update the last live timestamp on a slow
547 // schedule to get the bast possible accuracy for the assessment.
548 g_browser_process->metrics_service()->StartUpdatingLastLiveTimestamp();
551 // Register a synthetic field trial for the sampling profiler configuration
552 // that was already chosen.
553 std::string trial_name, group_name;
554 if (StackSamplingConfiguration::Get()->GetSyntheticFieldTrial(&trial_name,
556 ChromeMetricsServiceAccessor::RegisterSyntheticFieldTrial(trial_name,
560 g_browser_process->GetMetricsServicesManager()->UpdateUploadPermissions(true);
563 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
564 // Don't record any metrics if UI was displayed before this point e.g.
565 // warning dialogs or browser was started in background mode.
566 if (startup_metric_utils::WasMainWindowStartupInterrupted())
569 bool is_first_run = false;
570 #if !defined(OS_ANDROID)
571 // On Android, first run is handled in Java code, and the C++ side of Chrome
572 // doesn't know if this is the first run. This will cause some inaccuracy in
573 // the UMA statistics, but this should be minor (first runs are rare).
574 is_first_run = first_run::IsChromeFirstRun();
575 #endif // defined(OS_ANDROID)
577 // Record collected startup metrics.
578 startup_metric_utils::RecordBrowserMainMessageLoopStart(
579 base::TimeTicks::Now(), is_first_run);
582 void ChromeBrowserMainParts::SetupOriginTrialsCommandLine(
583 PrefService* local_state) {
584 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
585 if (!command_line->HasSwitch(embedder_support::kOriginTrialPublicKey)) {
586 std::string new_public_key =
587 local_state->GetString(prefs::kOriginTrialPublicKey);
588 if (!new_public_key.empty()) {
589 command_line->AppendSwitchASCII(
590 embedder_support::kOriginTrialPublicKey,
591 local_state->GetString(prefs::kOriginTrialPublicKey));
594 if (!command_line->HasSwitch(
595 embedder_support::kOriginTrialDisabledFeatures)) {
596 const base::ListValue* override_disabled_feature_list =
597 local_state->GetList(prefs::kOriginTrialDisabledFeatures);
598 if (override_disabled_feature_list) {
599 std::vector<base::StringPiece> disabled_features;
600 base::StringPiece disabled_feature;
601 for (const auto& item : *override_disabled_feature_list) {
602 if (item.GetAsString(&disabled_feature)) {
603 disabled_features.push_back(disabled_feature);
606 if (!disabled_features.empty()) {
607 const std::string override_disabled_features =
608 base::JoinString(disabled_features, "|");
609 command_line->AppendSwitchASCII(
610 embedder_support::kOriginTrialDisabledFeatures,
611 override_disabled_features);
615 if (!command_line->HasSwitch(embedder_support::kOriginTrialDisabledTokens)) {
616 const base::ListValue* disabled_token_list =
617 local_state->GetList(prefs::kOriginTrialDisabledTokens);
618 if (disabled_token_list) {
619 std::vector<base::StringPiece> disabled_tokens;
620 base::StringPiece disabled_token;
621 for (const auto& item : *disabled_token_list) {
622 if (item.GetAsString(&disabled_token)) {
623 disabled_tokens.push_back(disabled_token);
626 if (!disabled_tokens.empty()) {
627 const std::string disabled_token_switch =
628 base::JoinString(disabled_tokens, "|");
629 command_line->AppendSwitchASCII(
630 embedder_support::kOriginTrialDisabledTokens,
631 disabled_token_switch);
637 // -----------------------------------------------------------------------------
638 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
641 #define DLLEXPORT __declspec(dllexport)
643 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
645 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded();
648 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
649 // Need an instance of AtExitManager to handle singleton creations and
650 // deletions. We need this new instance because, the old instance created
651 // in ChromeMain() got destructed when the function returned.
652 base::AtExitManager exit_manager;
653 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
657 // content::BrowserMainParts implementation ------------------------------------
659 int ChromeBrowserMainParts::PreEarlyInitialization() {
660 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
661 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
662 chrome_extra_parts_[i]->PreEarlyInitialization();
664 // Create BrowserProcess in PreEarlyInitialization() so that we can load
665 // field trials (and all it depends upon).
666 browser_process_ = std::make_unique<BrowserProcessImpl>(startup_data_);
668 bool failed_to_load_resource_bundle = false;
669 const int load_local_state_result =
670 OnLocalStateLoaded(&failed_to_load_resource_bundle);
672 // Reuses the MetricsServicesManager and GetMetricsServicesManagerClient
673 // instances created in the FeatureListCreator so they won't be created
675 auto* chrome_feature_list_creator =
676 startup_data_->chrome_feature_list_creator();
677 browser_process_->SetMetricsServices(
678 chrome_feature_list_creator->TakeMetricsServicesManager(),
679 chrome_feature_list_creator->GetMetricsServicesManagerClient());
681 if (load_local_state_result == chrome::RESULT_CODE_MISSING_DATA &&
682 failed_to_load_resource_bundle) {
683 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
684 switches::kNoErrorDialogs)) {
685 return chrome::RESULT_CODE_MISSING_DATA;
687 // Continue on and show error later (once UI has been initialized and main
688 // message loop is running).
689 return service_manager::RESULT_CODE_NORMAL_EXIT;
691 return load_local_state_result;
694 void ChromeBrowserMainParts::PostEarlyInitialization() {
695 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
696 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
697 chrome_extra_parts_[i]->PostEarlyInitialization();
700 void ChromeBrowserMainParts::ToolkitInitialized() {
701 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
702 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
703 chrome_extra_parts_[i]->ToolkitInitialized();
706 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
707 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
709 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
710 chrome_extra_parts_[i]->PreMainMessageLoopStart();
713 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
714 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
716 #if !defined(OS_ANDROID)
717 // Initialize the upgrade detector here after ChromeBrowserMainPartsChromeos
718 // has had a chance to connect the DBus services.
719 UpgradeDetector::GetInstance()->Init();
722 ThreadProfiler::SetMainThreadTaskRunner(base::ThreadTaskRunnerHandle::Get());
724 system_monitor_ = performance_monitor::SystemMonitor::Create();
726 // TODO(sebmarchand): Allow this to be created earlier if startup tracing is
728 trace_event_system_stats_monitor_ =
729 std::make_unique<tracing::TraceEventSystemStatsMonitor>();
731 // device_event_log must be initialized after the message loop. Calls to
732 // {DEVICE}_LOG prior to here will only be logged with VLOG. Some
733 // platforms (e.g. chromeos) may have already initialized this.
734 if (!device_event_log::IsInitialized())
735 device_event_log::Initialize(0 /* default max entries */);
737 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
738 chrome_extra_parts_[i]->PostMainMessageLoopStart();
741 int ChromeBrowserMainParts::PreCreateThreads() {
743 // Calls in this function should not post tasks or create threads as
744 // components used to handle those tasks are not yet available. This work
745 // should be deferred to PreMainMessageLoopRunImpl.
747 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
748 result_code_ = PreCreateThreadsImpl();
750 if (result_code_ == service_manager::RESULT_CODE_NORMAL_EXIT) {
751 // These members must be initialized before exiting this function normally.
752 #if !defined(OS_ANDROID)
753 DCHECK(browser_creator_.get());
755 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
756 DCHECK(master_prefs_.get());
759 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
760 chrome_extra_parts_[i]->PreCreateThreads();
763 // Create an instance of GpuModeManager to watch gpu mode pref change.
764 g_browser_process->gpu_mode_manager();
769 int ChromeBrowserMainParts::OnLocalStateLoaded(
770 bool* failed_to_load_resource_bundle) {
771 *failed_to_load_resource_bundle = false;
772 if (!base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir_))
773 return chrome::RESULT_CODE_MISSING_DATA;
776 if (first_run::IsChromeFirstRun()) {
778 if (GoogleUpdateSettings::GetCollectStatsConsentDefault(&stats_default)) {
779 // |stats_default| == true means that the default state of consent for the
780 // product at the time of install was to report usage statistics, meaning
782 metrics::RecordMetricsReportingDefaultState(
783 browser_process_->local_state(),
784 stats_default ? metrics::EnableMetricsDefault::OPT_OUT
785 : metrics::EnableMetricsDefault::OPT_IN);
788 #endif // defined(OS_WIN)
791 startup_data_->chrome_feature_list_creator()->actual_locale();
792 if (locale.empty()) {
793 *failed_to_load_resource_bundle = true;
794 return chrome::RESULT_CODE_MISSING_DATA;
796 browser_process_->SetApplicationLocale(locale);
798 const int apply_first_run_result = ApplyFirstRunPrefs();
799 if (apply_first_run_result != service_manager::RESULT_CODE_NORMAL_EXIT)
800 return apply_first_run_result;
802 SetupOriginTrialsCommandLine(browser_process_->local_state());
804 metrics::EnableExpiryChecker(chrome_metrics::kExpiredHistogramsHashes,
805 chrome_metrics::kNumExpiredHistograms);
807 return service_manager::RESULT_CODE_NORMAL_EXIT;
810 int ChromeBrowserMainParts::ApplyFirstRunPrefs() {
811 // Android does first run in Java instead of native.
812 // Chrome OS has its own out-of-box-experience code.
813 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
814 master_prefs_ = std::make_unique<first_run::MasterPrefs>();
816 std::unique_ptr<installer::MasterPreferences> installer_master_prefs =
817 startup_data_->chrome_feature_list_creator()->TakeMasterPrefs();
818 if (!installer_master_prefs)
819 return service_manager::RESULT_CODE_NORMAL_EXIT;
821 // On first run, we need to process the predictor preferences before the
822 // browser's profile_manager object is created, but after ResourceBundle
824 first_run::ProcessMasterPreferencesResult pmp_result =
825 first_run::ProcessMasterPreferences(user_data_dir_,
826 std::move(installer_master_prefs),
827 master_prefs_.get());
828 if (pmp_result == first_run::EULA_EXIT_NOW)
829 return chrome::RESULT_CODE_EULA_REFUSED;
831 // TODO(macourteau): refactor preferences that are copied from
832 // master_preferences into local_state, as a "local_state" section in
833 // master preferences. If possible, a generic solution would be preferred
834 // over a copy one-by-one of specific preferences. Also see related TODO
837 PrefService* local_state = g_browser_process->local_state();
838 if (!master_prefs_->suppress_default_browser_prompt_for_version.empty()) {
839 local_state->SetString(
840 prefs::kBrowserSuppressDefaultBrowserPrompt,
841 master_prefs_->suppress_default_browser_prompt_for_version);
844 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
845 return service_manager::RESULT_CODE_NORMAL_EXIT;
848 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
849 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
850 run_message_loop_ = false;
852 if (browser_process_->GetApplicationLocale().empty()) {
853 ShowMissingLocaleMessageBox();
854 return chrome::RESULT_CODE_MISSING_DATA;
857 #if !defined(OS_ANDROID)
858 chrome::MaybeShowInvalidUserDataDirWarningDialog();
859 #endif // !defined(OS_ANDROID)
861 DCHECK(!user_data_dir_.empty());
863 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
864 MediaCaptureDevicesDispatcher::GetInstance();
866 // Android's first run is done in Java instead of native.
867 #if !defined(OS_ANDROID)
868 process_singleton_.reset(new ChromeProcessSingleton(
869 user_data_dir_, base::Bind(&ProcessSingletonNotificationCallback)));
871 // Cache first run state early.
872 first_run::IsChromeFirstRun();
874 #endif // !defined(OS_ANDROID)
876 PrefService* local_state = browser_process_->local_state();
878 #if defined(OS_CHROMEOS)
879 chromeos::CrosSettings::Initialize(local_state);
880 chromeos::StatsReportingController::Initialize(local_state);
881 arc::StabilityMetricsManager::Initialize(local_state);
882 #endif // defined(OS_CHROMEOS)
887 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowserProcessImpl");
888 browser_process_->Init();
891 #if !defined(OS_ANDROID)
892 // Create the RunLoop for MainMessageLoopRun() to use, and pass a copy of
893 // its QuitClosure to the BrowserProcessImpl to call when it is time to exit.
895 g_run_loop = new base::RunLoop;
897 // These members must be initialized before returning from this function.
898 // Android doesn't use StartupBrowserCreator.
899 browser_creator_.reset(new StartupBrowserCreator);
900 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
901 chrome::UMABrowsingActivityObserver::Init();
902 #endif // !defined(OS_ANDROID)
905 // This is needed to enable ETW exporting. This is only relevant for the
906 // browser process, as other processes enable it separately.
907 base::trace_event::TraceEventETWExport::EnableETWExport();
910 // Reset the command line in the crash report details, since we may have
911 // just changed it to include experiments.
912 crash_keys::SetCrashKeysFromCommandLine(
913 *base::CommandLine::ForCurrentProcess());
915 browser_process_->browser_policy_connector()->OnResourceBundleCreated();
917 // Android does first run in Java instead of native.
918 // Chrome OS has its own out-of-box-experience code.
919 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
920 if (first_run::IsChromeFirstRun()) {
921 if (!parsed_command_line().HasSwitch(switches::kApp) &&
922 !parsed_command_line().HasSwitch(switches::kAppId) &&
923 !parsed_command_line().HasSwitch(switches::kShowAppList)) {
924 AddFirstRunNewTabs(browser_creator_.get(), master_prefs_->new_tabs);
927 #if defined(OS_MACOSX) || defined(OS_LINUX)
928 // Create directory for user-level Native Messaging manifest files. This
929 // makes it less likely that the directory will be created by third-party
930 // software with incorrect owner or permission. See crbug.com/725513 .
931 base::FilePath user_native_messaging_dir;
932 CHECK(base::PathService::Get(chrome::DIR_USER_NATIVE_MESSAGING,
933 &user_native_messaging_dir));
934 if (!base::PathExists(user_native_messaging_dir))
935 base::CreateDirectory(user_native_messaging_dir);
936 #endif // defined(OS_MACOSX) || defined(OS_LINUX)
938 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
940 #if defined(OS_LINUX) || defined(OS_OPENBSD)
941 // Set the product channel for crash reports.
942 if (!crash_reporter::IsCrashpadEnabled()) {
943 breakpad::SetChannelCrashKey(chrome::GetChannelName());
945 #endif // defined(OS_LINUX) || defined(OS_OPENBSD)
947 #if defined(OS_MACOSX)
948 // Get the Keychain API to register for distributed notifications on the main
949 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
950 // which doesn't. This ensures those notifications will get delivered
951 // properly. See issue 37766.
952 // (Note that the callback mask here is empty. I don't want to register for
953 // any callbacks, I just want to initialize the mechanism.)
954 SecKeychainAddCallback(&KeychainCallback, 0, nullptr);
955 #endif // defined(OS_MACOSX)
957 #if defined(OS_WIN) || defined(OS_MACOSX) || \
958 (defined(OS_LINUX) && !defined(OS_CHROMEOS))
959 metrics::DesktopSessionDurationTracker::Initialize();
960 ProfileActivityMetricsRecorder::Initialize();
961 TouchModeStatsTracker::Initialize(
962 metrics::DesktopSessionDurationTracker::Get(),
963 ui::TouchUiController::Get());
965 metrics::RendererUptimeTracker::Initialize();
967 // Add Site Isolation switches as dictated by policy.
968 auto* command_line = base::CommandLine::ForCurrentProcess();
969 if (local_state->GetBoolean(prefs::kSitePerProcess) &&
970 site_isolation::SiteIsolationPolicy::IsEnterprisePolicyApplicable() &&
971 !command_line->HasSwitch(switches::kSitePerProcess)) {
972 command_line->AppendSwitch(switches::kSitePerProcess);
974 // IsolateOrigins policy is taken care of through SiteIsolationPrefsObserver
975 // (constructed and owned by BrowserProcessImpl).
977 #if defined(OS_ANDROID)
978 // The admin should also be able to use these policies to force Site Isolation
979 // off (on Android; using enterprise policies to disable Site Isolation is not
980 // supported on other platforms). Note that disabling either SitePerProcess
981 // or IsolateOrigins via policy will disable both types of isolation.
982 if ((local_state->IsManagedPreference(prefs::kSitePerProcess) &&
983 !local_state->GetBoolean(prefs::kSitePerProcess)) ||
984 (local_state->IsManagedPreference(prefs::kIsolateOrigins) &&
985 local_state->GetString(prefs::kIsolateOrigins).empty())) {
986 base::CommandLine::ForCurrentProcess()->AppendSwitch(
987 switches::kDisableSiteIsolationForPolicy);
991 // ChromeOS needs ui::ResourceBundle::InitSharedInstance to be called before
993 browser_process_->PreCreateThreads(parsed_command_line());
995 // This must occur in PreCreateThreads() because it initializes global state
996 // which is then read by all threads without synchronization. It must be after
997 // browser_process_->PreCreateThreads() as that instantiates the IOThread
998 // which is used in SetupMetrics().
1001 return service_manager::RESULT_CODE_NORMAL_EXIT;
1004 void ChromeBrowserMainParts::PostCreateThreads() {
1005 // This task should be posted after the IO thread starts, and prior to the
1006 // base version of the function being invoked. It is functionally okay to post
1007 // this task in method ChromeBrowserMainParts::BrowserThreadsStarted() which
1008 // we also need to add in this class, and call this method at the very top of
1009 // BrowserMainLoop::InitializeMainThread(). PostCreateThreads is preferred to
1010 // BrowserThreadsStarted as it matches the PreCreateThreads and CreateThreads
1012 content::GetIOThreadTaskRunner({})->PostTask(
1013 FROM_HERE, base::BindOnce(&ThreadProfiler::StartOnChildThread,
1014 metrics::CallStackProfileParams::IO_THREAD));
1015 // Sampling multiple threads might cause overhead on Android and we don't want
1016 // to enable it unless the data is needed.
1017 #if !defined(OS_ANDROID)
1018 content::GetIOThreadTaskRunner({})->PostTask(
1020 base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread));
1023 tracing::SetupBackgroundTracingFieldTrial();
1025 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1026 chrome_extra_parts_[i]->PostCreateThreads();
1029 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
1030 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1032 result_code_ = PreMainMessageLoopRunImpl();
1034 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1035 chrome_extra_parts_[i]->PreMainMessageLoopRun();
1038 // PreMainMessageLoopRun calls these extra stages in the following order:
1039 // PreMainMessageLoopRunImpl()
1040 // ... initial setup, including browser_process_ setup.
1042 // ... additional setup, including CreateProfile()
1043 // PostProfileInit()
1044 // ... additional setup
1045 // PreBrowserStart()
1046 // ... browser_creator_->Start (OR parameters().ui_task->Run())
1047 // PostBrowserStart()
1049 void ChromeBrowserMainParts::PreProfileInit() {
1050 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1052 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1053 chrome_extra_parts_[i]->PreProfileInit();
1055 #if !defined(OS_ANDROID)
1056 // Ephemeral profiles may have been left behind if the browser crashed.
1057 g_browser_process->profile_manager()->CleanUpEphemeralProfiles();
1058 // Files of deleted profiles can also be left behind after a crash.
1059 g_browser_process->profile_manager()->CleanUpDeletedProfiles();
1060 #endif // !defined(OS_ANDROID)
1062 #if BUILDFLAG(ENABLE_EXTENSIONS)
1063 javascript_dialog_extensions_client::InstallClient();
1064 #endif // BUILDFLAG(ENABLE_EXTENSIONS)
1066 InstallChromeJavaScriptAppModalDialogViewFactory();
1069 void ChromeBrowserMainParts::PostProfileInit() {
1070 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1072 g_browser_process->CreateDevToolsProtocolHandler();
1073 if (parsed_command_line().HasSwitch(::switches::kAutoOpenDevToolsForTabs))
1074 g_browser_process->CreateDevToolsAutoOpener();
1076 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1077 chrome_extra_parts_[i]->PostProfileInit();
1080 void ChromeBrowserMainParts::PreBrowserStart() {
1081 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1082 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1083 chrome_extra_parts_[i]->PreBrowserStart();
1085 #if !defined(OS_ANDROID)
1086 // Start the tab manager here so that we give the most amount of time for the
1087 // other services to start up before we start adjusting the oom priority.
1088 g_browser_process->GetTabManager()->Start();
1091 // The RulesetService will make the filtering rules available to renderers
1092 // immediately after its construction, provided that the rules are already
1093 // available at no cost in an indexed format. This enables activating
1094 // subresource filtering, if needed, also for page loads on start-up.
1095 g_browser_process->subresource_filter_ruleset_service();
1098 void ChromeBrowserMainParts::PostBrowserStart() {
1099 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1100 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1101 chrome_extra_parts_[i]->PostBrowserStart();
1102 #if !defined(OS_ANDROID)
1103 // Allow ProcessSingleton to process messages.
1104 process_singleton_->Unlock();
1105 #endif // !defined(OS_ANDROID)
1106 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1107 // to reduce the impact on startup time.
1108 content::GetUIThreadTaskRunner({})->PostDelayedTask(
1110 base::BindOnce(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles),
1111 base::TimeDelta::FromMinutes(1));
1113 #if !defined(OS_ANDROID)
1114 if (base::FeatureList::IsEnabled(features::kWebUsb)) {
1115 web_usb_detector_.reset(new WebUsbDetector());
1116 content::GetUIThreadTaskRunner({base::TaskPriority::BEST_EFFORT})
1117 ->PostTask(FROM_HERE,
1118 base::BindOnce(&WebUsbDetector::Initialize,
1119 base::Unretained(web_usb_detector_.get())));
1121 if (base::FeatureList::IsEnabled(features::kTabMetricsLogging)) {
1122 // Initialize the TabActivityWatcher to begin logging tab activity events.
1123 resource_coordinator::TabActivityWatcher::GetInstance();
1127 // At this point, StartupBrowserCreator::Start has run creating initial
1128 // browser windows and tabs, but no progress has been made in loading
1129 // content as the main message loop hasn't started processing tasks yet.
1130 // We setup to observe to the initial page load here to defer running
1131 // task posted via PostAfterStartupTask until its complete.
1132 AfterStartupTaskUtils::StartMonitoringStartup();
1135 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1136 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1138 SCOPED_UMA_HISTOGRAM_LONG_TIMER("Startup.PreMainMessageLoopRunImplLongTime");
1140 // Can't be in SetupFieldTrials() because it needs a task runner.
1141 blink::MemoryAblationExperiment::MaybeStart(
1142 content::GetIOThreadTaskRunner({}));
1145 // Windows parental controls calls can be slow, so we do an early init here
1146 // that calculates this value off of the UI thread.
1147 InitializeWinParentalControls();
1150 // Now that the file thread has been started, start metrics.
1151 StartMetricsRecording();
1153 if (!base::debug::BeingDebugged()) {
1154 // Create watchdog thread after creating all other threads because it will
1155 // watch the other threads and they must be running.
1156 browser_process_->watchdog_thread();
1159 // Do any initializating in the browser process that requires all threads
1161 browser_process_->PreMainMessageLoopRun();
1163 // Record last shutdown time into a histogram.
1164 browser_shutdown::ReadLastShutdownInfo();
1167 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1168 // tasks. Those care whether the browser is already running. On Linux/Mac,
1169 // upgrade/uninstall happen separately.
1170 bool already_running = browser_util::IsBrowserAlreadyRunning();
1172 // If the command line specifies 'uninstall' then we need to work here
1173 // unless we detect another chrome browser running.
1174 if (parsed_command_line().HasSwitch(switches::kUninstall)) {
1175 return DoUninstallTasks(already_running);
1178 if (parsed_command_line().HasSwitch(switches::kHideIcons) ||
1179 parsed_command_line().HasSwitch(switches::kShowIcons)) {
1180 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1181 parsed_command_line_);
1184 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory());
1185 #elif BUILDFLAG(LACROS)
1186 ui::SelectFileDialog::SetFactory(new ui::SelectFileDialogLacros::Factory());
1187 #endif // defined(OS_WIN)
1189 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser)) {
1190 bool is_managed = g_browser_process->local_state()->IsManagedPreference(
1191 prefs::kDefaultBrowserSettingEnabled);
1192 if (is_managed && !g_browser_process->local_state()->GetBoolean(
1193 prefs::kDefaultBrowserSettingEnabled)) {
1194 return static_cast<int>(chrome::RESULT_CODE_ACTION_DISALLOWED_BY_POLICY);
1197 return shell_integration::SetAsDefaultBrowser()
1198 ? static_cast<int>(service_manager::RESULT_CODE_NORMAL_EXIT)
1199 : static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED);
1202 #if defined(USE_AURA)
1203 // Make sure aura::Env has been initialized.
1204 CHECK(aura::Env::GetInstance());
1205 #endif // defined(USE_AURA)
1207 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1208 #if !defined(OS_ANDROID)
1209 // If the command line specifies --pack-extension, attempt the pack extension
1210 // startup action and exit.
1211 if (parsed_command_line().HasSwitch(switches::kPackExtension)) {
1212 extensions::StartupHelper extension_startup_helper;
1213 if (extension_startup_helper.PackExtension(parsed_command_line()))
1214 return service_manager::RESULT_CODE_NORMAL_EXIT;
1215 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR;
1218 // When another process is running, use that process instead of starting a
1219 // new one. NotifyOtherProcess will currently give the other process up to
1220 // 20 seconds to respond. Note that this needs to be done before we attempt
1221 // to read the profile.
1222 notify_result_ = process_singleton_->NotifyOtherProcessOrCreate();
1223 UMA_HISTOGRAM_ENUMERATION("Chrome.ProcessSingleton.NotifyResult",
1225 ProcessSingleton::kNumNotifyResults);
1226 switch (notify_result_) {
1227 case ProcessSingleton::PROCESS_NONE:
1228 // No process already running, fall through to starting a new one.
1229 g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing(
1230 *base::CommandLine::ForCurrentProcess());
1233 case ProcessSingleton::PROCESS_NOTIFIED:
1234 printf("%s\n", base::SysWideToNativeMB(
1235 base::UTF16ToWide(l10n_util::GetStringUTF16(
1236 IDS_USED_EXISTING_BROWSER)))
1239 // Having a differentiated return type for testing allows for tests to
1240 // verify proper handling of some switches. When not testing, stick to
1241 // the standard Unix convention of returning zero when things went as
1243 if (parsed_command_line().HasSwitch(switches::kTestType))
1244 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED;
1245 return service_manager::RESULT_CODE_NORMAL_EXIT;
1247 case ProcessSingleton::PROFILE_IN_USE:
1248 return chrome::RESULT_CODE_PROFILE_IN_USE;
1250 case ProcessSingleton::LOCK_ERROR:
1251 LOG(ERROR) << "Failed to create a ProcessSingleton for your profile "
1252 "directory. This means that running multiple instances "
1253 "would start multiple browser processes rather than "
1254 "opening a new window in the existing process. Aborting "
1255 "now to avoid profile corruption.";
1256 return chrome::RESULT_CODE_PROFILE_IN_USE;
1259 #if BUILDFLAG(ENABLE_DOWNGRADE_PROCESSING)
1260 // Begin relaunch processing immediately if User Data migration is required
1261 // to handle a version downgrade.
1262 if (downgrade_manager_.PrepareUserDataDirectoryForCurrentVersion(
1264 return chrome::RESULT_CODE_DOWNGRADE_AND_RELAUNCH;
1266 downgrade_manager_.UpdateLastVersion(user_data_dir_);
1269 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
1270 // Initialize the chrome browser cloud management controller controller after
1271 // the browser process singleton is acquired to remove race conditions where
1272 // multiple browser processes start simultaneously. The main
1273 // initialization of browser_policy_connector is performed inside
1274 // PreMainMessageLoopRun() so that policies can be applied as soon as
1277 // Note that this protects against multiple browser process starts in
1278 // the same user data dir and not multiple starts across user data dirs.
1279 browser_process_->browser_policy_connector()
1280 ->chrome_browser_cloud_management_controller()
1281 ->Init(browser_process_->local_state(),
1282 browser_process_->system_network_context_manager()
1283 ->GetSharedURLLoaderFactory());
1285 // Wait for the chrome browser cloud management enrollment to finish.
1286 // If no enrollment is needed, this function returns immediately.
1287 // Abort the launch process if the enrollment fails.
1288 if (!browser_process_->browser_policy_connector()
1289 ->chrome_browser_cloud_management_controller()
1290 ->WaitUntilPolicyEnrollmentFinished()) {
1291 return chrome::RESULT_CODE_CLOUD_POLICY_ENROLLMENT_FAILED;
1295 // Handle special early return paths (which couldn't be processed even earlier
1296 // as they require the process singleton to be held) first.
1298 std::string try_chrome =
1299 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain);
1301 // The TryChromeDialog may be aborted by a rendezvous from another browser
1302 // process (e.g., a launch via Chrome's taskbar icon or some such). In this
1303 // case, browser startup should continue without processing the original
1304 // command line (the one with --try-chrome-again), but rather with the command
1305 // line from the other process (handled in
1306 // ProcessSingletonNotificationCallback thanks to the ProcessSingleton). This
1307 // variable is cleared in that particular case, leading to a bypass of the
1308 // StartupBrowserCreator.
1309 bool process_command_line = true;
1310 if (!try_chrome.empty()) {
1312 // Setup.exe has determined that we need to run a retention experiment
1313 // and has lauched chrome to show the experiment UI. It is guaranteed that
1314 // no other Chrome is currently running as the process singleton was
1315 // successfully grabbed above.
1317 base::StringToInt(try_chrome, &try_chrome_int);
1318 TryChromeDialog::Result answer = TryChromeDialog::Show(
1320 base::Bind(&ChromeProcessSingleton::SetModalDialogNotificationHandler,
1321 base::Unretained(process_singleton_.get())));
1323 case TryChromeDialog::NOT_NOW:
1324 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL;
1325 case TryChromeDialog::OPEN_CHROME_WELCOME:
1326 browser_creator_->set_welcome_back_page(true);
1328 case TryChromeDialog::OPEN_CHROME_DEFAULT:
1330 case TryChromeDialog::OPEN_CHROME_DEFER:
1331 process_command_line = false;
1335 // We don't support retention experiments on Mac or Linux.
1336 return service_manager::RESULT_CODE_NORMAL_EXIT;
1337 #endif // defined(OS_WIN)
1339 #endif // !defined(OS_ANDROID)
1342 // Do the tasks if chrome has been upgraded while it was last running.
1343 if (!already_running && upgrade_util::DoUpgradeTasks(parsed_command_line()))
1344 return service_manager::RESULT_CODE_NORMAL_EXIT;
1346 // Check if there is any machine level Chrome installed on the current
1347 // machine. If yes and the current Chrome process is user level, we do not
1348 // allow the user level Chrome to run. So we notify the user and uninstall
1349 // user level Chrome.
1350 // Note this check needs to happen here (after the process singleton was
1351 // obtained but before potentially creating the first run sentinel).
1352 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1353 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS;
1354 #endif // defined(OS_WIN)
1356 // Desktop construction occurs here, (required before profile creation).
1359 // This step is costly and is already measured in Startup.CreateFirstProfile
1360 // and more directly Profile.CreateAndInitializeProfile.
1361 profile_ = CreatePrimaryProfile(parameters(),
1363 parsed_command_line());
1365 return service_manager::RESULT_CODE_NORMAL_EXIT;
1367 #if defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
1368 // Create the spellcheck service. This will asynchronously retrieve the
1369 // Windows platform spellcheck dictionary language tags used to populate the
1370 // context menu for editable content.
1371 if (spellcheck::UseBrowserSpellChecker() &&
1372 profile_->GetPrefs()->GetBoolean(spellcheck::prefs::kSpellCheckEnable) &&
1373 !base::FeatureList::IsEnabled(
1374 spellcheck::kWinDelaySpellcheckServiceInit)) {
1375 SpellcheckServiceFactory::GetForContext(profile_);
1377 #endif // defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
1379 #if !defined(OS_ANDROID)
1380 // The first run sentinel must be created after the process singleton was
1381 // grabbed and no early return paths were otherwise hit above.
1382 first_run::CreateSentinelIfNeeded();
1383 #endif // !defined(OS_ANDROID)
1385 #if BUILDFLAG(ENABLE_BACKGROUND_MODE)
1386 // Autoload any profiles which are running background apps.
1387 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1388 browser_process_->profile_manager()->AutoloadProfiles();
1389 #endif // BUILDFLAG(ENABLE_BACKGROUND_MODE)
1390 // Post-profile init ---------------------------------------------------------
1392 TranslateService::Initialize();
1393 if (base::FeatureList::IsEnabled(features::kGeoLanguage) ||
1394 base::FeatureList::IsEnabled(language::kExplicitLanguageAsk) ||
1395 language::GetOverrideLanguageModel() ==
1396 language::OverrideLanguageModel::GEO) {
1397 language::GeoLanguageProvider::GetInstance()->StartUp(
1398 browser_process_->local_state());
1401 // Needs to be done before PostProfileInit, since login manager on CrOS is
1402 // called inside PostProfileInit.
1403 content::WebUIControllerFactory::RegisterFactory(
1404 ChromeWebUIControllerFactory::GetInstance());
1406 #if defined(OS_ANDROID)
1407 page_info::SetPageInfoClient(new ChromePageInfoClient());
1410 #if BUILDFLAG(ENABLE_NACL)
1411 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1412 // So make sure to create it before that.
1413 nacl::NaClBrowser::SetDelegate(std::make_unique<NaClBrowserDelegateImpl>(
1414 browser_process_->profile_manager()));
1415 #endif // BUILDFLAG(ENABLE_NACL)
1417 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1418 // (requires supporting early exit).
1421 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1422 // Execute first run specific code after the PrefService has been initialized
1423 // and preferences have been registered since some of the import code depends
1425 if (first_run::IsChromeFirstRun()) {
1426 first_run::AutoImport(profile_, master_prefs_->import_bookmarks_path);
1428 // Note: This can pop-up the first run consent dialog on Linux & Mac.
1429 first_run::DoPostImportTasks(profile_,
1430 master_prefs_->make_chrome_default_for_user);
1432 // The first run dialog is modal, and spins a RunLoop, which could receive
1433 // a SIGTERM, and call chrome::AttemptExit(). Exit cleanly in that case.
1434 if (browser_shutdown::IsTryingToQuit())
1435 return service_manager::RESULT_CODE_NORMAL_EXIT;
1437 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1440 // Sets things up so that if we crash from this point on, a dialog will
1441 // popup asking the user to restart chrome. It is done this late to avoid
1442 // testing against a bunch of special cases that are taken care early on.
1443 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1444 parsed_command_line());
1446 // Registers Chrome with the Windows Restart Manager, which will restore the
1447 // Chrome session when the computer is restarted after a system update.
1448 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1449 // but should run on startup if extended to handle crashes/hangs/patches.
1450 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1451 ChromeBrowserMainPartsWin::RegisterApplicationRestart(parsed_command_line());
1453 // Verify that the profile is not on a network share and if so prepare to show
1454 // notification to the user.
1455 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_)) {
1456 base::ThreadPool::PostTask(
1457 FROM_HERE, {base::MayBlock()},
1458 base::BindOnce(&NetworkProfileBubble::CheckNetworkProfile,
1459 profile_->GetPath()));
1461 #endif // defined(OS_WIN)
1463 #if BUILDFLAG(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1464 // Init the RLZ library. This just binds the dll and schedules a task on the
1465 // file thread to be run sometime later. If this is the first run we record
1466 // the installation event.
1468 profile_->GetPrefs()->GetInteger(prefs::kRlzPingDelaySeconds);
1469 // Negative ping delay means to send ping immediately after a first search is
1471 rlz::RLZTracker::SetRlzDelegate(
1472 base::WrapUnique(new ChromeRLZTrackerDelegate));
1473 rlz::RLZTracker::InitRlzDelayed(
1474 first_run::IsChromeFirstRun(), ping_delay < 0,
1475 base::TimeDelta::FromSeconds(abs(ping_delay)),
1476 ChromeRLZTrackerDelegate::IsGoogleDefaultSearch(profile_),
1477 ChromeRLZTrackerDelegate::IsGoogleHomepage(profile_),
1478 ChromeRLZTrackerDelegate::IsGoogleInStartpages(profile_));
1479 #endif // BUILDFLAG(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1481 // Configure modules that need access to resources.
1482 net::NetModule::SetResourceProvider(ChromeNetResourceProvider);
1483 media::SetLocalizedStringProvider(ChromeMediaLocalizedStringProvider);
1485 // In unittest mode, this will do nothing. In normal mode, this will create
1486 // the global IntranetRedirectDetector instance, which will promptly go to
1487 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1488 // to see if it should do anything else.
1490 // A simpler way of doing all this would be to have some function which could
1491 // give the time elapsed since startup, and simply have this object check that
1492 // when asked to initialize itself, but this doesn't seem to exist.
1494 // This can't be created in the BrowserProcessImpl constructor because it
1495 // needs to read prefs that get set after that runs.
1496 browser_process_->intranet_redirect_detector();
1498 #if BUILDFLAG(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1499 if (parsed_command_line().HasSwitch(switches::kDebugPrint)) {
1500 base::FilePath path =
1501 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint);
1503 printing::PrintedDocument::SetDebugDumpPath(path);
1505 #endif // BUILDFLAG(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1507 #if BUILDFLAG(ENABLE_PRINT_PREVIEW) && defined(OS_WIN)
1508 printing::SetGetDisplayNameFunction(&printing::GetUserFriendlyName);
1511 HandleTestParameters(parsed_command_line());
1512 browser_process_->metrics_service()->RecordBreakpadHasDebugger(
1513 base::debug::BeingDebugged());
1515 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1516 profile_->GetPrefs()->GetString(language::prefs::kAcceptLanguages));
1517 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1518 browser_process_->GetApplicationLocale());
1520 // On mobile, need for clean shutdown arises only when the application comes
1521 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1522 // http://crbug.com/179143
1523 #if !defined(OS_ANDROID)
1524 // Start watching for a hang.
1525 browser_process_->metrics_service()->LogNeedForCleanShutdown();
1526 #endif // !defined(OS_ANDROID)
1528 #if BUILDFLAG(ENABLE_PRINT_PREVIEW) && !defined(OS_CHROMEOS)
1529 // Create the instance of the cloud print proxy service so that it can launch
1530 // the service process if needed. This is needed because the service process
1531 // might have shutdown because an update was available.
1532 // TODO(torne): this should maybe be done with
1533 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1535 CloudPrintProxyServiceFactory::GetForProfile(profile_);
1538 // Two different types of hang detection cannot run at the same time or they
1539 // would interfere with each other.
1540 if (!base::FeatureList::IsEnabled(base::HangWatcher::kEnableHangWatcher)) {
1541 // Start watching all browser threads for responsiveness.
1542 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1545 // This has to come before the first GetInstance() call. PreBrowserStart()
1546 // seems like a reasonable place to put this, except on Android,
1547 // OfflinePageInfoHandler::Register() below calls GetInstance().
1548 // TODO(thestig): See if the Android code below can be moved to later.
1549 sessions::ContentSerializedNavigationDriver::SetInstance(
1550 ChromeSerializedNavigationDriver::GetInstance());
1552 #if defined(OS_ANDROID)
1553 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1554 #endif // defined(OS_ANDROID)
1556 #if BUILDFLAG(ENABLE_OFFLINE_PAGES)
1557 offline_pages::OfflinePageInfoHandler::Register();
1560 #if BUILDFLAG(ENABLE_NACL)
1561 content::GetIOThreadTaskRunner({})->PostTask(
1562 FROM_HERE, base::BindOnce(nacl::NaClProcessHost::EarlyStartup));
1563 #endif // BUILDFLAG(ENABLE_NACL)
1565 // Make sure initial prefs are recorded
1566 PrefMetricsService::Factory::GetForProfile(profile_);
1570 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate)) {
1571 component_updater::RegisterComponentsForUpdate(profile_->IsOffTheRecord(),
1572 profile_->GetPrefs());
1575 variations::VariationsService* variations_service =
1576 browser_process_->variations_service();
1577 if (should_call_pre_main_loop_start_startup_on_variations_service_)
1578 variations_service->PerformPreMainMessageLoopStartup();
1580 #if defined(OS_ANDROID)
1581 // Just initialize the policy prefs service here. Variations seed fetching
1582 // will be initialized when the app enters foreground mode.
1583 variations_service->set_policy_pref_service(profile_->GetPrefs());
1586 // We are in regular browser boot sequence. Open initial tabs and enter the
1587 // main message loop.
1588 std::vector<Profile*> last_opened_profiles;
1589 #if !defined(OS_CHROMEOS)
1590 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1591 // them this early as the cryptohome hasn't yet been mounted (which happens
1592 // only once we log in).
1593 last_opened_profiles =
1594 g_browser_process->profile_manager()->GetLastOpenedProfiles();
1595 #endif // defined(OS_CHROMEOS)
1597 // This step is costly and is already measured in
1598 // Startup.StartupBrowserCreator_Start.
1599 // See the comment above for an explanation of |process_command_line|.
1600 const bool started =
1601 !process_command_line ||
1602 browser_creator_->Start(parsed_command_line(), base::FilePath(), profile_,
1603 last_opened_profiles);
1605 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1606 // Initialize autoupdate timer. Timer callback costs basically nothing
1607 // when browser is not in persistent mode, so it's OK to let it ride on
1608 // the main thread. This needs to be done here because we don't want
1609 // to start the timer when Chrome is run inside a test harness.
1610 browser_process_->StartAutoupdateTimer();
1611 #endif // defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1613 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1614 // On Linux, the running exe will be updated if an upgrade becomes
1615 // available while the browser is running. We need to save the last
1616 // modified time of the exe, so we can compare to determine if there is
1617 // an upgrade while the browser is kept alive by a persistent extension.
1618 upgrade_util::SaveLastModifiedTimeOfExe();
1619 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1621 // Record now as the last successful chrome start.
1622 if (ShouldRecordActiveUse(parsed_command_line()))
1623 GoogleUpdateSettings::SetLastRunTime();
1625 #if defined(OS_MACOSX)
1626 // Call Recycle() here as late as possible, before going into the loop
1627 // because Start() will add things to it while creating the main window.
1628 if (parameters().autorelease_pool)
1629 parameters().autorelease_pool->Recycle();
1630 #endif // defined(OS_MACOSX)
1632 // Transfer ownership of the browser's lifetime to the BrowserProcess.
1633 browser_process_->SetQuitClosure(g_run_loop->QuitWhenIdleClosure());
1634 DCHECK(!run_message_loop_);
1635 run_message_loop_ = true;
1637 browser_creator_.reset();
1638 #endif // !defined(OS_ANDROID)
1642 // The ui_task can be injected by tests to replace the main message loop.
1643 // In that case we Run() it here, and set a flag to avoid running the main
1644 // message loop later, as the test will do so as needed from the |ui_task|.
1645 if (parameters().ui_task) {
1646 std::move(*parameters().ui_task).Run();
1647 delete parameters().ui_task;
1648 run_message_loop_ = false;
1651 #if BUILDFLAG(ENABLE_DOWNGRADE_PROCESSING)
1652 // Clean up old user data directory, snapshots and disk cache directory.
1653 downgrade_manager_.DeleteMovedUserDataSoon(user_data_dir_);
1656 #if defined(OS_ANDROID)
1657 // We never run the C++ main loop on Android, since the UI thread message
1658 // loop is controlled by the OS, so this is as close as we can get to
1659 // the start of the main loop.
1660 if (result_code_ <= 0) {
1661 RecordBrowserStartupTime();
1663 #endif // defined(OS_ANDROID)
1665 return result_code_;
1668 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code) {
1669 // Trace the entry and exit of this method. We don't use the TRACE_EVENT0
1670 // macro because the tracing infrastructure doesn't expect a synchronous event
1671 // around the main loop of a thread.
1672 ScopedMainMessageLoopRunEvent scoped_main_message_loop_run_event;
1673 #if defined(OS_ANDROID)
1674 // Chrome on Android does not use default MessageLoop. It has its own
1675 // Android specific MessageLoop
1679 // Set the result code set in PreMainMessageLoopRun or set above.
1680 *result_code = result_code_;
1681 if (!run_message_loop_)
1682 return true; // Don't run the default message loop.
1684 // These should be invoked as close to the start of the browser's
1685 // UI thread message loop as possible to get a stable measurement
1687 RecordBrowserStartupTime();
1689 DCHECK(base::MessageLoopCurrentForUI::IsSet());
1691 performance_monitor::ProcessMonitor::GetInstance()->StartGatherCycle();
1696 #endif // defined(OS_ANDROID)
1699 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1700 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1701 #if defined(OS_ANDROID)
1702 // Chrome on Android does not use default MessageLoop. It has its own
1703 // Android specific MessageLoop
1706 // Shutdown the UpgradeDetector here before ChromeBrowserMainPartsChromeos
1707 // disconnects DBus services in its PostDestroyThreads.
1708 UpgradeDetector::GetInstance()->Shutdown();
1710 // Start watching for jank during shutdown. It gets disarmed when
1711 // |shutdown_watcher_| object is destructed.
1712 shutdown_watcher_->Arm(base::TimeDelta::FromSeconds(300));
1714 web_usb_detector_.reset();
1716 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1717 chrome_extra_parts_[i]->PostMainMessageLoopRun();
1719 // Some tests don't set parameters.ui_task, so they started translate
1720 // language fetch that was never completed so we need to cleanup here
1721 // otherwise it will be done by the destructor in a wrong thread.
1722 TranslateService::Shutdown(!parameters().ui_task);
1724 if (notify_result_ == ProcessSingleton::PROCESS_NONE)
1725 process_singleton_->Cleanup();
1727 // Stop all tasks that might run on WatchDogThread.
1728 ThreadWatcherList::StopWatchingAll();
1730 browser_process_->metrics_service()->Stop();
1732 restart_last_session_ = browser_shutdown::ShutdownPreThreadsStop();
1733 browser_process_->StartTearDown();
1734 #endif // defined(OS_ANDROID)
1737 void ChromeBrowserMainParts::PostDestroyThreads() {
1738 #if defined(OS_ANDROID)
1739 // On Android, there is no quit/exit. So the browser's main message loop will
1743 browser_shutdown::RestartMode restart_mode =
1744 browser_shutdown::RestartMode::kNoRestart;
1746 if (restart_last_session_) {
1747 restart_mode = browser_shutdown::RestartMode::kRestartLastSession;
1749 #if BUILDFLAG(ENABLE_BACKGROUND_MODE)
1750 if (BackgroundModeManager::should_restart_in_background())
1751 restart_mode = browser_shutdown::RestartMode::kRestartInBackground;
1752 #endif // BUILDFLAG(ENABLE_BACKGROUND_MODE)
1755 browser_process_->PostDestroyThreads();
1756 // browser_shutdown takes care of deleting browser_process, so we need to
1758 ignore_result(browser_process_.release());
1760 #if BUILDFLAG(ENABLE_DOWNGRADE_PROCESSING)
1761 if (result_code_ == chrome::RESULT_CODE_DOWNGRADE_AND_RELAUNCH) {
1762 // Process a pending User Data downgrade before restarting.
1763 downgrade_manager_.ProcessDowngrade(user_data_dir_);
1765 // It's impossible for there to also be a user-driven relaunch since the
1766 // browser never fully starts in this case.
1767 DCHECK(!restart_last_session_);
1768 restart_mode = browser_shutdown::RestartMode::kRestartThisSession;
1770 #endif // BUILDFLAG(ENABLE_DOWNGRADE_PROCESSING)
1772 browser_shutdown::ShutdownPostThreadsStop(restart_mode);
1774 #if !defined(OS_CHROMEOS)
1775 master_prefs_.reset();
1776 #endif // !defined(OS_CHROMEOS)
1778 process_singleton_.reset();
1779 device_event_log::Shutdown();
1781 // We need to do this check as late as possible, but due to modularity, this
1782 // may be the last point in Chrome. This would be more effective if done at
1783 // a higher level on the stack, so that it is impossible for an early return
1784 // to bypass this code. Perhaps we need a *final* hook that is called on all
1785 // paths from content/browser/browser_main.
1786 CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
1788 #if defined(OS_CHROMEOS)
1789 arc::StabilityMetricsManager::Shutdown();
1790 chromeos::StatsReportingController::Shutdown();
1791 chromeos::CrosSettings::Shutdown();
1792 #endif // defined(OS_CHROMEOS)
1793 #endif // defined(OS_ANDROID)
1798 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts* parts) {
1799 chrome_extra_parts_.push_back(parts);
1802 #if !defined(OS_ANDROID)
1804 std::unique_ptr<base::RunLoop> ChromeBrowserMainParts::TakeRunLoopForTest() {
1805 auto run_loop = base::WrapUnique<base::RunLoop>(g_run_loop);
1806 g_run_loop = nullptr;