1 // Copyright 2012 The Chromium Authors
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/browser_process_impl.h"
15 #include "base/atomic_ref_count.h"
16 #include "base/command_line.h"
17 #include "base/debug/leak_annotations.h"
18 #include "base/files/file_path.h"
19 #include "base/functional/bind.h"
20 #include "base/functional/callback.h"
21 #include "base/functional/callback_helpers.h"
22 #include "base/location.h"
23 #include "base/memory/ptr_util.h"
24 #include "base/metrics/histogram_macros.h"
25 #include "base/notreached.h"
26 #include "base/path_service.h"
27 #include "base/run_loop.h"
28 #include "base/synchronization/waitable_event.h"
29 #include "base/task/sequenced_task_runner.h"
30 #include "base/task/single_thread_task_runner.h"
31 #include "base/task/task_traits.h"
32 #include "base/task/thread_pool.h"
33 #include "base/threading/thread.h"
34 #include "base/threading/thread_restrictions.h"
35 #include "base/time/default_clock.h"
36 #include "base/time/default_tick_clock.h"
37 #include "base/trace_event/trace_event.h"
38 #include "build/build_config.h"
39 #include "build/chromeos_buildflags.h"
40 #include "chrome/browser/accessibility/soda_installer_impl.h"
41 #include "chrome/browser/battery/battery_metrics.h"
42 #include "chrome/browser/browser_process_platform_part.h"
43 #include "chrome/browser/chrome_browser_main.h"
44 #include "chrome/browser/chrome_content_browser_client.h"
45 #include "chrome/browser/component_updater/chrome_component_updater_configurator.h"
46 #include "chrome/browser/defaults.h"
47 #include "chrome/browser/devtools/remote_debugging_server.h"
48 #include "chrome/browser/download/download_request_limiter.h"
49 #include "chrome/browser/download/download_status_updater.h"
50 #include "chrome/browser/google/google_brand.h"
51 #include "chrome/browser/gpu/gpu_mode_manager.h"
52 #include "chrome/browser/icon_manager.h"
53 #include "chrome/browser/lifetime/application_lifetime.h"
54 #include "chrome/browser/lifetime/browser_shutdown.h"
55 #include "chrome/browser/lifetime/switch_utils.h"
56 #include "chrome/browser/media/chrome_media_session_client.h"
57 #include "chrome/browser/media/webrtc/webrtc_event_log_manager.h"
58 #include "chrome/browser/media/webrtc/webrtc_log_uploader.h"
59 #include "chrome/browser/metrics/chrome_feature_list_creator.h"
60 #include "chrome/browser/metrics/chrome_metrics_service_accessor.h"
61 #include "chrome/browser/metrics/chrome_metrics_services_manager_client.h"
62 #include "chrome/browser/metrics/metrics_reporting_state.h"
63 #include "chrome/browser/net/system_network_context_manager.h"
64 #include "chrome/browser/notifications/notification_platform_bridge.h"
65 #include "chrome/browser/notifications/system_notification_helper.h"
66 #include "chrome/browser/permissions/chrome_permissions_client.h"
67 #include "chrome/browser/policy/chrome_browser_policy_connector.h"
68 #include "chrome/browser/prefs/browser_prefs.h"
69 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
70 #include "chrome/browser/printing/background_printing_manager.h"
71 #include "chrome/browser/printing/print_job_manager.h"
72 #include "chrome/browser/profiles/profile_manager.h"
73 #include "chrome/browser/resource_coordinator/resource_coordinator_parts.h"
74 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
75 #include "chrome/browser/shell_integration.h"
76 #include "chrome/browser/site_isolation/prefs_observer.h"
77 #include "chrome/browser/ssl/secure_origin_prefs_observer.h"
78 #include "chrome/browser/startup_data.h"
79 #include "chrome/browser/status_icons/status_tray.h"
80 #include "chrome/browser/ui/browser_dialogs.h"
81 #include "chrome/browser/update_client/chrome_update_query_params_delegate.h"
82 #include "chrome/browser/webapps/chrome_webapps_client.h"
83 #include "chrome/common/buildflags.h"
84 #include "chrome/common/channel_info.h"
85 #include "chrome/common/chrome_constants.h"
86 #include "chrome/common/chrome_features.h"
87 #include "chrome/common/chrome_paths.h"
88 #include "chrome/common/chrome_switches.h"
89 #include "chrome/common/pref_names.h"
90 #include "chrome/common/url_constants.h"
91 #include "chrome/grit/branded_strings.h"
92 #include "chrome/installer/util/google_update_settings.h"
93 #include "components/breadcrumbs/core/application_breadcrumbs_logger.h"
94 #include "components/breadcrumbs/core/breadcrumb_persistent_storage_util.h"
95 #include "components/breadcrumbs/core/breadcrumbs_status.h"
96 #include "components/breadcrumbs/core/crash_reporter_breadcrumb_observer.h"
97 #include "components/component_updater/component_updater_service.h"
98 #include "components/component_updater/timer_update_scheduler.h"
99 #include "components/crash/core/common/crash_key.h"
100 #include "components/embedder_support/origin_trials/origin_trials_settings_storage.h"
101 #include "components/gcm_driver/gcm_driver.h"
102 #include "components/language/core/browser/pref_names.h"
103 #include "components/metrics/metrics_pref_names.h"
104 #include "components/metrics/metrics_service.h"
105 #include "components/metrics_services_manager/metrics_services_manager.h"
106 #include "components/metrics_services_manager/metrics_services_manager_client.h"
107 #include "components/network_time/network_time_tracker.h"
108 #include "components/os_crypt/async/browser/os_crypt_async.h"
109 #include "components/permissions/permissions_client.h"
110 #include "components/policy/core/common/policy_service.h"
111 #include "components/prefs/json_pref_store.h"
112 #include "components/prefs/pref_registry_simple.h"
113 #include "components/prefs/pref_service.h"
114 #include "components/safe_browsing/content/browser/safe_browsing_service_interface.h"
115 #include "components/sessions/core/session_id_generator.h"
116 #include "components/subresource_filter/content/browser/ruleset_service.h"
117 #include "components/translate/core/browser/translate_download_manager.h"
118 #include "components/ukm/ukm_service.h"
119 #include "components/update_client/update_query_params.h"
120 #include "components/variations/service/variations_service.h"
121 #include "components/web_resource/web_resource_pref_names.h"
122 #include "content/public/browser/browser_task_traits.h"
123 #include "content/public/browser/browser_thread.h"
124 #include "content/public/browser/child_process_security_policy.h"
125 #include "content/public/browser/network_quality_observer_factory.h"
126 #include "content/public/browser/network_service_instance.h"
127 #include "content/public/browser/network_service_util.h"
128 #include "content/public/browser/process_visibility_util.h"
129 #include "content/public/browser/render_process_host.h"
130 #include "content/public/browser/service_worker_context.h"
131 #include "content/public/browser/storage_partition.h"
132 #include "content/public/common/content_switches.h"
133 #include "extensions/buildflags/buildflags.h"
134 #include "extensions/common/constants.h"
135 #include "media/media_buildflags.h"
136 #include "mojo/public/cpp/bindings/pending_receiver.h"
137 #include "net/log/net_log.h"
138 #include "ppapi/buildflags/buildflags.h"
139 #include "printing/buildflags/buildflags.h"
140 #include "services/network/public/cpp/features.h"
141 #include "services/network/public/cpp/network_switches.h"
142 #include "ui/base/idle/idle.h"
143 #include "ui/base/l10n/l10n_util.h"
144 #include "ui/base/ui_base_features.h"
146 #if BUILDFLAG(IS_WIN)
147 #include "base/win/windows_version.h"
148 #elif BUILDFLAG(IS_MAC)
149 #include "chrome/browser/chrome_browser_main_mac.h"
150 #include "chrome/browser/media/webrtc/system_media_capture_permissions_stats_mac.h"
153 #if BUILDFLAG(IS_CHROMEOS_ASH)
154 #include "components/soda/soda_installer_impl_chromeos.h"
156 #include "ui/message_center/message_center.h"
159 #if BUILDFLAG(IS_ANDROID)
160 #include "chrome/browser/accessibility/accessibility_prefs/android/accessibility_prefs_controller.h"
161 #include "chrome/browser/flags/android/chrome_feature_list.h"
162 #include "chrome/browser/ssl/chrome_security_state_client.h"
163 #include "chrome/browser/webauthn/android/chrome_webauthn_client_android.h"
164 #include "components/webauthn/android/webauthn_client_android.h"
166 #include "chrome/browser/devtools/devtools_auto_opener.h"
167 #include "chrome/browser/gcm/gcm_product_util.h"
168 #include "chrome/browser/hid/hid_system_tray_icon.h"
169 #include "chrome/browser/intranet_redirect_detector.h"
170 #include "chrome/browser/lifetime/application_lifetime_desktop.h"
171 #include "chrome/browser/resource_coordinator/tab_manager.h"
172 #include "chrome/browser/serial/serial_policy_allowed_ports.h"
173 #include "chrome/browser/ui/browser_finder.h"
174 #include "chrome/browser/ui/browser_list.h"
175 #include "chrome/browser/usb/usb_system_tray_icon.h"
176 #include "components/gcm_driver/gcm_client_factory.h"
177 #include "components/gcm_driver/gcm_desktop_utils.h"
178 #include "components/keep_alive_registry/keep_alive_registry.h"
181 #if BUILDFLAG(ENABLE_BACKGROUND_MODE)
182 #include "chrome/browser/background/background_mode_manager.h"
185 #if BUILDFLAG(ENABLE_EXTENSIONS)
186 #include "chrome/browser/apps/platform_apps/chrome_apps_browser_api_provider.h"
187 #include "chrome/browser/extensions/chrome_extensions_browser_client.h"
188 #include "chrome/browser/extensions/event_router_forwarder.h"
189 #include "chrome/browser/media_galleries/media_file_system_registry.h"
190 #include "chrome/browser/ui/apps/chrome_app_window_client.h"
191 #include "chrome/common/controlled_frame/controlled_frame.h"
192 #include "chrome/common/extensions/chrome_extensions_client.h"
193 #include "chrome/common/initialize_extensions_client.h"
194 #include "components/storage_monitor/storage_monitor.h"
195 #include "extensions/common/context_data.h"
196 #include "extensions/common/extension_l10n_util.h"
199 #if BUILDFLAG(ENABLE_PLUGINS)
200 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
201 #include "content/public/browser/plugin_service.h"
204 #if BUILDFLAG(ENABLE_PRINT_PREVIEW)
205 #include "chrome/browser/printing/print_preview_dialog_controller.h"
208 #if BUILDFLAG(ENABLE_SESSION_SERVICE)
209 #include "chrome/browser/sessions/exit_type_service.h"
212 #if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH)
213 #include "chrome/browser/first_run/upgrade_util.h"
214 #include "chrome/browser/ui/profiles/profile_picker.h"
215 #include "components/enterprise/browser/controller/chrome_browser_cloud_management_controller.h"
218 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
219 #include "chrome/browser/error_reporting/chrome_js_error_report_processor.h" // nogncheck
222 #if BUILDFLAG(ENABLE_CHROME_NOTIFICATIONS)
223 #include "chrome/browser/notifications/notification_ui_manager.h"
226 #if BUILDFLAG(IS_CHROMEOS)
227 #include "chrome/browser/chromeos/extensions/telemetry/chromeos_telemetry_extensions_browser_api_provider.h"
228 #include "chrome/browser/hid/hid_pinned_notification.h"
229 #include "chrome/browser/screen_ai/screen_ai_downloader_chromeos.h"
230 #include "chrome/browser/usb/usb_pinned_notification.h"
231 #elif !BUILDFLAG(IS_ANDROID)
232 #include "chrome/browser/hid/hid_status_icon.h"
233 #include "chrome/browser/screen_ai/screen_ai_downloader_non_chromeos.h"
234 #include "chrome/browser/usb/usb_status_icon.h"
237 #if BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
238 // How often to check if the persistent instance of Chrome needs to restart
239 // to install an update.
240 static const int kUpdateCheckIntervalHours = 6;
243 #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_OZONE)
244 // How long to wait for the File thread to complete during EndSession, on Linux
245 // and Windows. We have a timeout here because we're unable to run the UI
246 // messageloop and there's some deadlock risk. Our only option is to exit
248 static constexpr base::TimeDelta kEndSessionTimeout = base::Seconds(10);
251 using content::BrowserThread;
252 using content::ChildProcessSecurityPolicy;
254 BrowserProcessImpl::BrowserProcessImpl(StartupData* startup_data)
255 : startup_data_(startup_data),
256 browser_policy_connector_(startup_data->chrome_feature_list_creator()
257 ->TakeChromeBrowserPolicyConnector()),
259 startup_data->chrome_feature_list_creator()->TakePrefService()),
260 platform_part_(std::make_unique<BrowserProcessPlatformPart>()) {
261 CHECK(!g_browser_process);
262 g_browser_process = this;
264 // Initialize the SessionIdGenerator instance, providing a PrefService to
265 // ensure the persistent storage of current max SessionId.
266 sessions::SessionIdGenerator::GetInstance()->Init(local_state_.get());
268 DCHECK(browser_policy_connector_);
269 DCHECK(local_state_);
270 DCHECK(startup_data);
271 // Most work should be done in Init().
274 void BrowserProcessImpl::Init() {
275 if (content::IsOutOfProcessNetworkService()) {
276 // Initialize NetLog source IDs to use an alternate starting value for
277 // the browser process. This needs to be done early in process startup
278 // before any NetLogSource objects might get created.
279 net::NetLog::Get()->InitializeSourceIdPartition();
282 #if BUILDFLAG(IS_CHROMEOS_ASH)
283 // Forces creation of |metrics_services_manager_client_| if necessary
284 // (typically this call is a no-op as MetricsServicesManager has already been
286 GetMetricsServicesManager();
287 DCHECK(metrics_services_manager_client_);
288 metrics_services_manager_client_->OnCrosSettingsCreated();
291 download_status_updater_ = std::make_unique<DownloadStatusUpdater>();
293 #if BUILDFLAG(ENABLE_PRINTING)
294 // Must be created after the NotificationService.
295 print_job_manager_ = std::make_unique<printing::PrintJobManager>();
298 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
299 chrome::kChromeSearchScheme);
301 #if BUILDFLAG(IS_MAC)
302 ui::InitIdleMonitor();
305 #if BUILDFLAG(ENABLE_EXTENSIONS)
306 extensions::AppWindowClient::Set(ChromeAppWindowClient::GetInstance());
308 extension_event_router_forwarder_ =
309 base::MakeRefCounted<extensions::EventRouterForwarder>();
311 EnsureExtensionsClientInitialized(
312 controlled_frame::CreateAvailabilityCheckMap());
314 extensions_browser_client_ =
315 std::make_unique<extensions::ChromeExtensionsBrowserClient>();
316 extensions_browser_client_->AddAPIProvider(
317 std::make_unique<chrome_apps::ChromeAppsBrowserAPIProvider>());
318 extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get());
320 #if BUILDFLAG(IS_CHROMEOS)
321 extensions_browser_client_->AddAPIProvider(
323 chromeos::ChromeOSTelemetryExtensionsBrowserAPIProvider>());
324 #endif // BUILDFLAG(IS_CHROMEOS)
326 #endif // BUILDFLAG(ENABLE_EXTENSIONS)
328 #if BUILDFLAG(ENABLE_CHROME_NOTIFICATIONS)
329 message_center::MessageCenter::Initialize();
330 // Set the system notification source display name ("Google Chrome" or
332 if (message_center::MessageCenter::Get()) {
333 message_center::MessageCenter::Get()->SetSystemNotificationAppName(
334 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME));
338 system_notification_helper_ = std::make_unique<SystemNotificationHelper>();
340 update_client::UpdateQueryParams::SetDelegate(
341 ChromeUpdateQueryParamsDelegate::GetInstance());
343 // Make sure permissions client has been set.
344 ChromePermissionsClient::GetInstance();
346 // Make sure media session client has been set.
347 ChromeMediaSessionClient::GetInstance();
349 // Make sure webapps client has been set.
350 webapps::ChromeWebappsClient::GetInstance();
352 #if !BUILDFLAG(IS_ANDROID)
353 KeepAliveRegistry::GetInstance()->SetIsShuttingDown(false);
354 KeepAliveRegistry::GetInstance()->AddObserver(this);
355 #endif // !BUILDFLAG(IS_ANDROID)
357 MigrateObsoleteLocalStatePrefs(local_state());
358 pref_change_registrar_.Init(local_state());
360 // Initialize the notification for the default browser setting policy.
361 pref_change_registrar_.Add(
362 prefs::kDefaultBrowserSettingEnabled,
363 base::BindRepeating(&BrowserProcessImpl::ApplyDefaultBrowserPolicy,
364 base::Unretained(this)));
366 // This preference must be kept in sync with external values; update them
367 // whenever the preference or its controlling policy changes.
368 pref_change_registrar_.Add(metrics::prefs::kMetricsReportingEnabled,
369 base::BindRepeating(&ApplyMetricsReportingPolicy));
371 DCHECK(!webrtc_event_log_manager_);
372 webrtc_event_log_manager_ = WebRtcEventLogManager::CreateSingletonInstance();
374 #if BUILDFLAG(IS_MAC)
375 system_media_permissions::LogSystemMediaPermissionsStartupStats();
378 #if BUILDFLAG(IS_ANDROID)
379 webauthn::WebAuthnClientAndroid::SetClient(
380 std::make_unique<ChromeWebAuthnClientAndroid>());
381 accessibility_prefs_controller_ =
382 std::make_unique<accessibility::AccessibilityPrefsController>(
386 #if !BUILDFLAG(IS_ANDROID)
387 #if BUILDFLAG(IS_CHROMEOS)
388 hid_system_tray_icon_ = std::make_unique<HidPinnedNotification>();
389 usb_system_tray_icon_ = std::make_unique<UsbPinnedNotification>();
391 hid_system_tray_icon_ = std::make_unique<HidStatusIcon>();
392 usb_system_tray_icon_ = std::make_unique<UsbStatusIcon>();
393 #endif // BUILDFLAG(IS_CHROMEOS)
394 #endif // !BUILDFLAG(IS_ANDROID)
397 #if !BUILDFLAG(IS_ANDROID)
398 void BrowserProcessImpl::SetQuitClosure(base::OnceClosure quit_closure) {
399 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
400 DCHECK(quit_closure);
401 DCHECK(!quit_closure_);
402 quit_closure_ = std::move(quit_closure);
406 #if BUILDFLAG(IS_MAC)
407 void BrowserProcessImpl::ClearQuitClosure() {
408 quit_closure_.Reset();
412 BrowserProcessImpl::~BrowserProcessImpl() {
413 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
414 #if BUILDFLAG(ENABLE_EXTENSIONS)
415 extensions::ExtensionsBrowserClient::Set(nullptr);
416 extensions::AppWindowClient::Set(nullptr);
419 #if !BUILDFLAG(IS_ANDROID)
420 KeepAliveRegistry::GetInstance()->RemoveObserver(this);
423 g_browser_process = nullptr;
426 #if !BUILDFLAG(IS_ANDROID)
427 void BrowserProcessImpl::StartTearDown() {
428 TRACE_EVENT0("shutdown", "BrowserProcessImpl::StartTearDown");
429 // TODO(crbug.com/560486): Fix the tests that make the check of
430 // |tearing_down_| necessary in IsShuttingDown().
431 tearing_down_ = true;
432 DCHECK(IsShuttingDown());
434 #if BUILDFLAG(IS_ANDROID)
435 accessibility_prefs_controller_.reset();
437 metrics_services_manager_.reset();
438 intranet_redirect_detector_.reset();
439 if (safe_browsing_service_.get())
440 safe_browsing_service()->ShutDown();
441 network_time_tracker_.reset();
443 #if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH)
444 // Initial cleanup for ChromeBrowserCloudManagement, shutdown components that
445 // depend on profile and notification system. For example, ProfileManager
446 // observer and KeyServices observer need to be removed before profiles.
447 auto* cloud_management_controller =
448 browser_policy_connector_->chrome_browser_cloud_management_controller();
449 if (cloud_management_controller)
450 cloud_management_controller->ShutDown();
453 #if !BUILDFLAG(IS_ANDROID)
454 // |hid_system_tray_icon_| and |usb_system_tray_icon_| must be destroyed
455 // before |system_notification_helper_| for ChromeOS and |status_tray_| for
457 hid_system_tray_icon_.reset();
458 usb_system_tray_icon_.reset();
461 system_notification_helper_.reset();
463 #if BUILDFLAG(ENABLE_CHROME_NOTIFICATIONS)
464 // Need to clear the desktop notification balloons before the IO thread and
465 // before the profiles, since if there are any still showing we will access
466 // those things during teardown.
467 notification_ui_manager_.reset();
470 // Debugger must be cleaned up before ProfileManager.
471 remote_debugging_server_.reset();
472 devtools_auto_opener_.reset();
474 battery_metrics_.reset();
476 #if BUILDFLAG(ENABLE_EXTENSIONS)
477 // The Extensions Browser Client needs to teardown some members while the
478 // profile manager is still alive.
479 extensions_browser_client_->StartTearDown();
482 // Need to clear profiles (download managers) before the IO thread.
484 TRACE_EVENT0("shutdown",
485 "BrowserProcessImpl::StartTearDown:ProfileManager");
486 #if !BUILDFLAG(IS_CHROMEOS_ASH)
487 // The desktop profile picker needs to be closed before the guest profile
489 ProfilePicker::Hide();
490 #endif // !BUILDFLAG(IS_CHROMEOS_ASH)
491 // `profile_manager_` must be destroyed before `background_mode_manager_`,
492 // because the background mode manager does not stop observing profile
493 // changes at destruction (notifying the observers would cause a use-after-
495 profile_manager_.reset();
498 #if BUILDFLAG(ENABLE_EXTENSIONS)
499 // The `media_file_system_registry_` cannot be reset until the
500 // `profile_manager_` has been.
501 media_file_system_registry_.reset();
502 // Remove the global instance of the Storage Monitor now. Otherwise the
503 // FILE thread would be gone when we try to release it in the dtor and
504 // Valgrind would report a leak on almost every single browser_test.
505 // TODO(gbillock): Make this unnecessary.
506 storage_monitor::StorageMonitor::Destroy();
509 #if BUILDFLAG(ENABLE_CHROME_NOTIFICATIONS)
510 if (message_center::MessageCenter::Get())
511 message_center::MessageCenter::Shutdown();
514 // The policy providers managed by |browser_policy_connector_| need to shut
515 // down while the IO and FILE threads are still alive. The monitoring
516 // framework owned by |browser_policy_connector_| relies on |gcm_driver_|, so
517 // this must be shutdown before |gcm_driver_| below.
518 browser_policy_connector_->Shutdown();
520 // The |gcm_driver_| must shut down while the IO thread is still alive.
522 gcm_driver_->Shutdown();
524 platform_part()->StartTearDown();
526 // Cancel any uploads to release the system url request context references.
527 if (webrtc_log_uploader_)
528 webrtc_log_uploader_->Shutdown();
530 sessions::SessionIdGenerator::GetInstance()->Shutdown();
532 // Resetting the status tray will result in calls to
533 // |g_browser_process->local_state()|. See crbug.com/1187418
534 status_tray_.reset();
536 local_state_->CommitPendingWrite();
538 // This expects to be destroyed before the task scheduler is torn down.
539 SystemNetworkContextManager::DeleteInstance();
541 // The ApplicationBreadcrumbsLogger logs a shutdown event via a task when it
542 // is destroyed, so it should be destroyed before the task scheduler is torn
544 application_breadcrumbs_logger_.reset();
547 void BrowserProcessImpl::PostDestroyThreads() {
548 // With the file_thread_ flushed, we can release any icon resources.
549 icon_manager_.reset();
551 // Must outlive the worker threads.
552 webrtc_log_uploader_.reset();
554 #endif // !BUILDFLAG(IS_ANDROID)
556 void BrowserProcessImpl::SetMetricsServices(
557 std::unique_ptr<metrics_services_manager::MetricsServicesManager> manager,
558 metrics_services_manager::MetricsServicesManagerClient* client) {
559 metrics_services_manager_ = std::move(manager);
560 metrics_services_manager_client_ =
561 static_cast<ChromeMetricsServicesManagerClient*>(client);
566 // Used at the end of session to block the UI thread for completion of sentinel
567 // tasks on the set of threads used to persist profile data and local state.
568 // This is done to ensure that the data has been persisted to disk before
570 class RundownTaskCounter :
571 public base::RefCountedThreadSafe<RundownTaskCounter> {
573 RundownTaskCounter();
575 RundownTaskCounter(const RundownTaskCounter&) = delete;
576 RundownTaskCounter& operator=(const RundownTaskCounter&) = delete;
578 // Increments |count_| and returns a closure bound to Decrement(). All
579 // closures returned by this RundownTaskCounter's GetRundownClosure() method
580 // must be invoked for TimedWait() to complete its wait without timing
582 base::OnceClosure GetRundownClosure();
584 // Waits until the count is zero or |timeout| expires.
585 // This can only be called once per instance.
586 void TimedWait(base::TimeDelta timeout);
589 friend class base::RefCountedThreadSafe<RundownTaskCounter>;
590 ~RundownTaskCounter() {}
592 // Decrements the counter and releases the waitable event on transition to
596 // The count starts at one to defer the possibility of one->zero transitions
597 // until TimedWait is called.
598 base::AtomicRefCount count_{1};
599 base::WaitableEvent waitable_event_;
602 RundownTaskCounter::RundownTaskCounter() = default;
604 base::OnceClosure RundownTaskCounter::GetRundownClosure() {
605 // As the count starts off at one, it should never get to zero unless
606 // TimedWait has been called.
607 DCHECK(!count_.IsZero());
611 return base::BindOnce(&RundownTaskCounter::Decrement, this);
614 void RundownTaskCounter::Decrement() {
615 if (!count_.Decrement())
616 waitable_event_.Signal();
619 void RundownTaskCounter::TimedWait(base::TimeDelta timeout) {
620 // Decrement the excess count from the constructor.
623 // RundownTaskCounter::TimedWait() could return
624 // |waitable_event_.TimedWait()|'s result if any user ever cared about whether
625 // it returned per success or timeout. Currently no user of this API cares and
626 // as such this return value is ignored.
627 waitable_event_.TimedWait(timeout);
630 #if !BUILDFLAG(IS_ANDROID)
631 void RequestProxyResolvingSocketFactoryOnUIThread(
632 mojo::PendingReceiver<network::mojom::ProxyResolvingSocketFactory>
634 network::mojom::NetworkContext* network_context =
635 g_browser_process->system_network_context_manager()->GetContext();
636 network_context->CreateProxyResolvingSocketFactory(std::move(receiver));
639 void RequestProxyResolvingSocketFactory(
640 mojo::PendingReceiver<network::mojom::ProxyResolvingSocketFactory>
642 content::GetUIThreadTaskRunner({})->PostTask(
643 FROM_HERE, base::BindOnce(&RequestProxyResolvingSocketFactoryOnUIThread,
644 std::move(receiver)));
650 void BrowserProcessImpl::FlushLocalStateAndReply(base::OnceClosure reply) {
651 local_state_->CommitPendingWrite(std::move(reply));
654 void BrowserProcessImpl::EndSession() {
655 // Mark all the profiles as clean.
656 ProfileManager* pm = profile_manager();
657 scoped_refptr<RundownTaskCounter> rundown_counter =
658 base::MakeRefCounted<RundownTaskCounter>();
659 for (Profile* profile : pm->GetLoadedProfiles()) {
660 #if BUILDFLAG(ENABLE_SESSION_SERVICE)
661 ExitTypeService* exit_type_service =
662 ExitTypeService::GetInstanceForProfile(profile);
663 if (exit_type_service)
664 exit_type_service->SetCurrentSessionExitType(ExitType::kForcedShutdown);
666 if (profile->GetPrefs()) {
667 profile->GetPrefs()->CommitPendingWrite(
668 base::OnceClosure(), rundown_counter->GetRundownClosure());
672 // Tell the metrics service it was cleanly shutdown.
673 metrics::MetricsService* metrics = g_browser_process->metrics_service();
675 metrics->LogCleanShutdown();
676 #if !BUILDFLAG(IS_CHROMEOS_ASH)
677 // The MetricsService may update Local State prefs in memory without
678 // writing the updated prefs to disk, so schedule a Local State write now.
680 // Do not schedule a write on ChromeOS because writing to disk multiple
681 // times during shutdown was causing shutdown problems. See crbug/302578.
682 local_state_->CommitPendingWrite(base::OnceClosure(),
683 rundown_counter->GetRundownClosure());
687 // This wait is legitimate and necessary on Windows, since the process will
688 // be terminated soon.
689 // http://crbug.com/125207
690 base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_wait;
692 // We must write that the profile and metrics service shutdown cleanly,
693 // otherwise on startup we'll think we crashed. So we block until done and
694 // then proceed with normal shutdown.
696 // If you change the condition here, be sure to also change
697 // ProfileBrowserTests to match.
698 #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_OZONE)
699 // Do a best-effort wait on the successful countdown of rundown tasks. Note
700 // that if we don't complete "quickly enough", Windows will terminate our
703 // On Windows, we previously posted a message to FILE and then ran a nested
704 // message loop, waiting for that message to be processed until quitting.
705 // However, doing so means that other messages will also be processed. In
706 // particular, if the GPU process host notices that the GPU has been killed
707 // during shutdown, it races exiting the nested loop with the process host
708 // blocking the message loop attempting to re-establish a connection to the
709 // GPU process synchronously. Because the system may not be allowing
710 // processes to launch, this can result in a hang. See
711 // http://crbug.com/318527.
712 rundown_counter->TimedWait(kEndSessionTimeout);
718 metrics_services_manager::MetricsServicesManager*
719 BrowserProcessImpl::GetMetricsServicesManager() {
720 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
721 if (!metrics_services_manager_) {
723 std::make_unique<ChromeMetricsServicesManagerClient>(local_state());
724 metrics_services_manager_client_ = client.get();
725 metrics_services_manager_ =
726 std::make_unique<metrics_services_manager::MetricsServicesManager>(
729 return metrics_services_manager_.get();
732 metrics::MetricsService* BrowserProcessImpl::metrics_service() {
733 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
734 return GetMetricsServicesManager()->GetMetricsService();
737 embedder_support::OriginTrialsSettingsStorage*
738 BrowserProcessImpl::GetOriginTrialsSettingsStorage() {
739 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
740 if (!origin_trials_settings_storage_) {
741 origin_trials_settings_storage_ =
742 std::make_unique<embedder_support::OriginTrialsSettingsStorage>();
744 return origin_trials_settings_storage_.get();
747 SystemNetworkContextManager*
748 BrowserProcessImpl::system_network_context_manager() {
749 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
750 DCHECK(SystemNetworkContextManager::GetInstance());
751 return SystemNetworkContextManager::GetInstance();
754 scoped_refptr<network::SharedURLLoaderFactory>
755 BrowserProcessImpl::shared_url_loader_factory() {
756 return system_network_context_manager()->GetSharedURLLoaderFactory();
759 network::NetworkQualityTracker* BrowserProcessImpl::network_quality_tracker() {
760 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
761 if (!network_quality_tracker_) {
762 network_quality_tracker_ = std::make_unique<network::NetworkQualityTracker>(
763 base::BindRepeating(&content::GetNetworkService));
765 return network_quality_tracker_.get();
768 ProfileManager* BrowserProcessImpl::profile_manager() {
769 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
770 if (!created_profile_manager_)
771 CreateProfileManager();
772 return profile_manager_.get();
775 PrefService* BrowserProcessImpl::local_state() {
776 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
777 return local_state_.get();
780 variations::VariationsService* BrowserProcessImpl::variations_service() {
781 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
782 return GetMetricsServicesManager()->GetVariationsService();
785 BrowserProcessPlatformPart* BrowserProcessImpl::platform_part() {
786 return platform_part_.get();
789 extensions::EventRouterForwarder*
790 BrowserProcessImpl::extension_event_router_forwarder() {
791 #if BUILDFLAG(ENABLE_EXTENSIONS)
792 return extension_event_router_forwarder_.get();
798 NotificationUIManager* BrowserProcessImpl::notification_ui_manager() {
799 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
800 #if BUILDFLAG(ENABLE_CHROME_NOTIFICATIONS)
801 if (!created_notification_ui_manager_)
802 CreateNotificationUIManager();
803 return notification_ui_manager_.get();
809 NotificationPlatformBridge* BrowserProcessImpl::notification_platform_bridge() {
810 #if BUILDFLAG(ENABLE_SYSTEM_NOTIFICATIONS)
811 if (!created_notification_bridge_)
812 CreateNotificationPlatformBridge();
813 return notification_bridge_.get();
819 policy::ChromeBrowserPolicyConnector*
820 BrowserProcessImpl::browser_policy_connector() {
821 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
822 return browser_policy_connector_.get();
825 policy::PolicyService* BrowserProcessImpl::policy_service() {
826 return browser_policy_connector()->GetPolicyService();
829 IconManager* BrowserProcessImpl::icon_manager() {
830 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
831 if (!created_icon_manager_)
833 return icon_manager_.get();
836 GpuModeManager* BrowserProcessImpl::gpu_mode_manager() {
837 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
838 if (!gpu_mode_manager_)
839 gpu_mode_manager_ = std::make_unique<GpuModeManager>();
840 return gpu_mode_manager_.get();
843 void BrowserProcessImpl::CreateDevToolsProtocolHandler() {
844 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
845 #if !BUILDFLAG(IS_ANDROID)
846 // StartupBrowserCreator::LaunchBrowser can be run multiple times when browser
847 // is started with several profiles or existing browser process is reused.
848 if (!remote_debugging_server_) {
849 if (!local_state_->GetBoolean(prefs::kDevToolsRemoteDebuggingAllowed)) {
850 // Follow content/browser/devtools/devtools_http_handler.cc that reports
851 // its remote debugging port on stderr for symmetry.
852 fputs("\nDevTools remote debugging is disallowed by the system admin.\n",
857 remote_debugging_server_ = std::make_unique<RemoteDebuggingServer>();
862 void BrowserProcessImpl::CreateDevToolsAutoOpener() {
863 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
864 #if !BUILDFLAG(IS_ANDROID)
865 // StartupBrowserCreator::LaunchBrowser can be run multiple times when browser
866 // is started with several profiles or existing browser process is reused.
867 if (!devtools_auto_opener_)
868 devtools_auto_opener_ = std::make_unique<DevToolsAutoOpener>();
872 bool BrowserProcessImpl::IsShuttingDown() {
873 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
874 // TODO (crbug.com/560486): Fix the tests that make the check of
875 // |tearing_down_| necessary here.
876 // TODO (crbug/1155597): Maybe use browser_shutdown::HasShutdownStarted here.
877 return shutting_down_ || tearing_down_;
880 printing::PrintJobManager* BrowserProcessImpl::print_job_manager() {
881 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
882 #if BUILDFLAG(ENABLE_PRINTING)
883 return print_job_manager_.get();
890 printing::PrintPreviewDialogController*
891 BrowserProcessImpl::print_preview_dialog_controller() {
892 #if BUILDFLAG(ENABLE_PRINT_PREVIEW)
893 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
894 if (!print_preview_dialog_controller_.get())
895 CreatePrintPreviewDialogController();
896 return print_preview_dialog_controller_.get();
903 printing::BackgroundPrintingManager*
904 BrowserProcessImpl::background_printing_manager() {
905 #if BUILDFLAG(ENABLE_PRINT_PREVIEW)
906 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
907 if (!background_printing_manager_)
908 CreateBackgroundPrintingManager();
909 return background_printing_manager_.get();
916 #if !BUILDFLAG(IS_ANDROID)
917 IntranetRedirectDetector* BrowserProcessImpl::intranet_redirect_detector() {
918 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
919 if (!intranet_redirect_detector_)
920 intranet_redirect_detector_ = std::make_unique<IntranetRedirectDetector>();
922 return intranet_redirect_detector_.get();
926 const std::string& BrowserProcessImpl::GetApplicationLocale() {
927 #if !BUILDFLAG(IS_CHROMEOS_ASH)
928 // TODO(crbug.com/1033644): Remove #if.
929 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
931 DCHECK(!locale_.empty());
935 void BrowserProcessImpl::SetApplicationLocale(
936 const std::string& actual_locale) {
937 // NOTE: this is called before any threads have been created in non-test
939 locale_ = actual_locale;
940 ChromeContentBrowserClient::SetApplicationLocale(actual_locale);
941 translate::TranslateDownloadManager::GetInstance()->set_application_locale(
945 DownloadStatusUpdater* BrowserProcessImpl::download_status_updater() {
946 return download_status_updater_.get();
949 MediaFileSystemRegistry* BrowserProcessImpl::media_file_system_registry() {
950 #if BUILDFLAG(ENABLE_EXTENSIONS)
951 if (!media_file_system_registry_)
952 media_file_system_registry_ = std::make_unique<MediaFileSystemRegistry>();
953 return media_file_system_registry_.get();
959 WebRtcLogUploader* BrowserProcessImpl::webrtc_log_uploader() {
960 if (!webrtc_log_uploader_)
961 webrtc_log_uploader_ = std::make_unique<WebRtcLogUploader>();
962 return webrtc_log_uploader_.get();
965 network_time::NetworkTimeTracker* BrowserProcessImpl::network_time_tracker() {
966 CreateNetworkTimeTracker();
967 return network_time_tracker_.get();
970 #if !BUILDFLAG(IS_ANDROID)
971 gcm::GCMDriver* BrowserProcessImpl::gcm_driver() {
972 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
975 return gcm_driver_.get();
979 resource_coordinator::TabManager* BrowserProcessImpl::GetTabManager() {
980 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
981 return resource_coordinator_parts()->tab_manager();
984 resource_coordinator::ResourceCoordinatorParts*
985 BrowserProcessImpl::resource_coordinator_parts() {
986 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
987 if (!resource_coordinator_parts_) {
988 resource_coordinator_parts_ =
989 std::make_unique<resource_coordinator::ResourceCoordinatorParts>();
991 return resource_coordinator_parts_.get();
994 #if !BUILDFLAG(IS_ANDROID)
995 SerialPolicyAllowedPorts* BrowserProcessImpl::serial_policy_allowed_ports() {
996 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
997 if (!serial_policy_allowed_ports_) {
998 serial_policy_allowed_ports_ =
999 std::make_unique<SerialPolicyAllowedPorts>(local_state());
1001 return serial_policy_allowed_ports_.get();
1004 HidSystemTrayIcon* BrowserProcessImpl::hid_system_tray_icon() {
1005 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1006 return hid_system_tray_icon_.get();
1009 UsbSystemTrayIcon* BrowserProcessImpl::usb_system_tray_icon() {
1010 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1011 return usb_system_tray_icon_.get();
1015 os_crypt_async::OSCryptAsync* BrowserProcessImpl::os_crypt_async() {
1016 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1017 return os_crypt_async_.get();
1020 BuildState* BrowserProcessImpl::GetBuildState() {
1021 #if !BUILDFLAG(IS_ANDROID)
1022 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1023 return &build_state_;
1031 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple* registry) {
1032 registry->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled,
1035 registry->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt, false);
1037 #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_ANDROID)
1038 registry->RegisterBooleanPref(prefs::kEulaAccepted, false);
1039 #endif // BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_ANDROID)
1041 registry->RegisterStringPref(language::prefs::kApplicationLocale,
1043 #if BUILDFLAG(IS_CHROMEOS_ASH)
1044 registry->RegisterStringPref(prefs::kOwnerLocale, std::string());
1045 registry->RegisterStringPref(prefs::kHardwareKeyboardLayout,
1047 #endif // BUILDFLAG(IS_CHROMEOS_ASH)
1049 registry->RegisterBooleanPref(metrics::prefs::kMetricsReportingEnabled,
1050 GoogleUpdateSettings::GetCollectStatsConsent());
1051 registry->RegisterBooleanPref(prefs::kDevToolsRemoteDebuggingAllowed, true);
1054 DownloadRequestLimiter* BrowserProcessImpl::download_request_limiter() {
1055 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1056 if (!download_request_limiter_.get()) {
1057 download_request_limiter_ = base::MakeRefCounted<DownloadRequestLimiter>();
1059 return download_request_limiter_.get();
1062 BackgroundModeManager* BrowserProcessImpl::background_mode_manager() {
1063 #if BUILDFLAG(ENABLE_BACKGROUND_MODE)
1064 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1065 if (!background_mode_manager_)
1066 CreateBackgroundModeManager();
1067 return background_mode_manager_.get();
1073 #if BUILDFLAG(ENABLE_BACKGROUND_MODE)
1074 void BrowserProcessImpl::set_background_mode_manager_for_test(
1075 std::unique_ptr<BackgroundModeManager> manager) {
1076 background_mode_manager_ = std::move(manager);
1080 StatusTray* BrowserProcessImpl::status_tray() {
1081 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1084 return status_tray_.get();
1087 safe_browsing::SafeBrowsingService*
1088 BrowserProcessImpl::safe_browsing_service() {
1089 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1090 if (!created_safe_browsing_service_)
1091 CreateSafeBrowsingService();
1092 return safe_browsing_service_.get();
1095 subresource_filter::RulesetService*
1096 BrowserProcessImpl::subresource_filter_ruleset_service() {
1097 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1098 if (!created_subresource_filter_ruleset_service_)
1099 CreateSubresourceFilterRulesetService();
1100 return subresource_filter_ruleset_service_.get();
1103 StartupData* BrowserProcessImpl::startup_data() {
1104 return startup_data_;
1107 // TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is
1109 #if BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
1110 void BrowserProcessImpl::StartAutoupdateTimer() {
1111 autoupdate_timer_.Start(FROM_HERE, base::Hours(kUpdateCheckIntervalHours),
1112 this, &BrowserProcessImpl::OnAutoupdateTimer);
1116 component_updater::ComponentUpdateService*
1117 BrowserProcessImpl::component_updater() {
1118 if (component_updater_)
1119 return component_updater_.get();
1121 if (!BrowserThread::CurrentlyOn(BrowserThread::UI))
1124 std::unique_ptr<component_updater::UpdateScheduler> scheduler =
1125 std::make_unique<component_updater::TimerUpdateScheduler>();
1128 google_brand::GetBrand(&brand);
1129 component_updater_ = component_updater::ComponentUpdateServiceFactory(
1130 component_updater::MakeChromeComponentUpdaterConfigurator(
1131 base::CommandLine::ForCurrentProcess(),
1132 g_browser_process->local_state()),
1133 std::move(scheduler), brand);
1135 return component_updater_.get();
1138 void BrowserProcessImpl::OnKeepAliveStateChanged(bool is_keeping_alive) {
1139 if (is_keeping_alive)
1145 void BrowserProcessImpl::CreateNetworkQualityObserver() {
1146 DCHECK(!network_quality_observer_);
1147 network_quality_observer_ =
1148 content::CreateNetworkQualityObserver(network_quality_tracker());
1149 DCHECK(network_quality_observer_);
1152 void BrowserProcessImpl::OnKeepAliveRestartStateChanged(bool can_restart) {}
1154 void BrowserProcessImpl::CreateProfileManager() {
1155 DCHECK(!created_profile_manager_ && !profile_manager_);
1156 created_profile_manager_ = true;
1158 base::FilePath user_data_dir;
1159 base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
1160 profile_manager_ = std::make_unique<ProfileManager>(user_data_dir);
1163 void BrowserProcessImpl::PreCreateThreads() {
1164 #if BUILDFLAG(ENABLE_EXTENSIONS)
1165 // chrome-extension:// URLs are safe to request anywhere, but may only
1166 // commit (including in iframes) in extension processes.
1167 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeIsolatedScheme(
1168 extensions::kExtensionScheme, true);
1171 battery_metrics_ = std::make_unique<BatteryMetrics>();
1173 #if BUILDFLAG(IS_ANDROID)
1174 app_state_listener_ = base::android::ApplicationStatusListener::New(
1175 base::BindRepeating([](base::android::ApplicationState state) {
1176 content::OnBrowserVisibilityChanged(
1177 state == base::android::APPLICATION_STATE_HAS_RUNNING_ACTIVITIES ||
1178 state == base::android::APPLICATION_STATE_HAS_PAUSED_ACTIVITIES);
1180 content::OnBrowserVisibilityChanged(
1181 base::android::ApplicationStatusListener::HasVisibleActivities());
1182 #endif // BUILDFLAG(IS_ANDROID)
1184 secure_origin_prefs_observer_ =
1185 std::make_unique<SecureOriginPrefsObserver>(local_state());
1186 site_isolation_prefs_observer_ =
1187 std::make_unique<SiteIsolationPrefsObserver>(local_state());
1189 // Create SystemNetworkContextManager without a NetworkService if it has not
1190 // been requested yet.
1191 if (!SystemNetworkContextManager::HasInstance())
1192 SystemNetworkContextManager::CreateInstance(local_state());
1195 void BrowserProcessImpl::PreMainMessageLoopRun() {
1196 TRACE_EVENT0("startup", "BrowserProcessImpl::PreMainMessageLoopRun");
1197 SCOPED_UMA_HISTOGRAM_TIMER(
1198 "Startup.BrowserProcessImpl_PreMainMessageLoopRunTime");
1200 // browser_policy_connector() is created very early because local_state()
1201 // needs policy to be initialized with the managed preference values.
1202 // However, policy fetches from the network and loading of disk caches
1203 // requires that threads are running; this Init() call lets the connector
1204 // resume its initialization now that the loops are spinning and the
1205 // system request context is available for the fetchers.
1206 browser_policy_connector()->Init(
1208 system_network_context_manager()->GetSharedURLLoaderFactory());
1210 if (local_state_->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled))
1211 ApplyDefaultBrowserPolicy();
1213 ApplyMetricsReportingPolicy();
1215 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
1216 #if defined(EWK_BRINGUP) && !BUILDFLAG(IS_TIZEN) // FIXME: m108 bringup
1217 ChromeJsErrorReportProcessor::Create();
1221 #if BUILDFLAG(ENABLE_PLUGINS)
1222 content::PluginService::GetInstance()->SetFilter(
1223 ChromePluginServiceFilter::GetInstance());
1224 #endif // BUILDFLAG(ENABLE_PLUGINS)
1226 #if !BUILDFLAG(IS_ANDROID)
1227 storage_monitor::StorageMonitor::Create();
1230 platform_part_->PreMainMessageLoopRun();
1232 CreateNetworkTimeTracker();
1234 CreateNetworkQualityObserver();
1236 #if BUILDFLAG(IS_ANDROID)
1237 // This needs to be here so that SecurityStateClient is non-null when
1238 // SecurityStateModel code is called.
1239 security_state::SetSecurityStateClient(new ChromeSecurityStateClient());
1242 // Create the global SodaInstaller instance.
1243 #if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS)
1244 soda_installer_impl_ = std::make_unique<speech::SodaInstallerImpl>();
1245 #endif // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS)
1247 #if BUILDFLAG(IS_CHROMEOS_ASH)
1248 soda_installer_impl_ = std::make_unique<speech::SodaInstallerImplChromeOS>();
1249 #endif // BUILDFLAG(IS_CHROMEOS_ASH)
1251 #if BUILDFLAG(ENABLE_SCREEN_AI_SERVICE)
1252 screen_ai_download_ = screen_ai::ScreenAIInstallState::Create();
1255 base::FilePath user_data_dir;
1256 bool result = base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
1258 if (breadcrumbs::IsEnabled()) {
1259 // Start crash reporter listening for breadcrumb events. Collected
1260 // breadcrumbs will be attached to crash reports.
1261 breadcrumbs::CrashReporterBreadcrumbObserver::GetInstance();
1263 application_breadcrumbs_logger_ =
1264 std::make_unique<breadcrumbs::ApplicationBreadcrumbsLogger>(
1265 user_data_dir, base::BindRepeating([] {
1266 return ChromeMetricsServiceAccessor::
1267 IsMetricsAndCrashReportingEnabled();
1270 breadcrumbs::DeleteBreadcrumbFiles(user_data_dir);
1273 // For now, initialize OSCryptAsync with no providers. This delegates all
1274 // encryption operations to OSCrypt.
1275 // TODO(crbug.com/1373092): Add providers behind features, as support for them
1277 os_crypt_async_ = std::make_unique<os_crypt_async::OSCryptAsync>(
1279 std::pair<size_t, std::unique_ptr<os_crypt_async::KeyProvider>>>());
1281 // Trigger async initialization of OSCrypt key providers.
1282 std::ignore = os_crypt_async_->GetInstance(base::DoNothing());
1285 void BrowserProcessImpl::CreateIconManager() {
1286 DCHECK(!created_icon_manager_ && !icon_manager_);
1287 created_icon_manager_ = true;
1288 icon_manager_ = std::make_unique<IconManager>();
1291 void BrowserProcessImpl::CreateNotificationPlatformBridge() {
1292 #if BUILDFLAG(ENABLE_SYSTEM_NOTIFICATIONS)
1293 DCHECK(!notification_bridge_);
1294 notification_bridge_ = NotificationPlatformBridge::Create();
1295 created_notification_bridge_ = true;
1299 void BrowserProcessImpl::CreateNotificationUIManager() {
1300 #if BUILDFLAG(ENABLE_CHROME_NOTIFICATIONS)
1301 DCHECK(!notification_ui_manager_);
1302 notification_ui_manager_ = NotificationUIManager::Create();
1303 created_notification_ui_manager_ = !!notification_ui_manager_;
1307 void BrowserProcessImpl::CreateBackgroundModeManager() {
1308 #if BUILDFLAG(ENABLE_BACKGROUND_MODE)
1309 DCHECK(!background_mode_manager_);
1310 background_mode_manager_ = std::make_unique<BackgroundModeManager>(
1311 *base::CommandLine::ForCurrentProcess(),
1312 &profile_manager()->GetProfileAttributesStorage());
1316 void BrowserProcessImpl::CreateStatusTray() {
1317 DCHECK(!status_tray_);
1318 status_tray_ = StatusTray::Create();
1321 void BrowserProcessImpl::CreatePrintPreviewDialogController() {
1322 #if BUILDFLAG(ENABLE_PRINT_PREVIEW)
1323 DCHECK(!print_preview_dialog_controller_);
1324 print_preview_dialog_controller_ =
1325 base::MakeRefCounted<printing::PrintPreviewDialogController>();
1331 void BrowserProcessImpl::CreateBackgroundPrintingManager() {
1332 #if BUILDFLAG(ENABLE_PRINT_PREVIEW)
1333 DCHECK(!background_printing_manager_);
1334 background_printing_manager_ =
1335 std::make_unique<printing::BackgroundPrintingManager>();
1341 void BrowserProcessImpl::CreateSafeBrowsingService() {
1342 DCHECK(!safe_browsing_service_);
1343 // Set this flag to true so that we don't retry indefinitely to
1344 // create the service class if there was an error.
1345 created_safe_browsing_service_ = true;
1347 // The factory can be overridden in tests.
1348 if (!safe_browsing::SafeBrowsingServiceInterface::HasFactory()) {
1349 safe_browsing::SafeBrowsingServiceInterface::RegisterFactory(
1350 safe_browsing::GetSafeBrowsingServiceFactory());
1353 // TODO(crbug/925153): Port consumers of the |safe_browsing_service_| to use
1354 // the interface in components/safe_browsing, and remove this cast.
1355 safe_browsing_service_ = static_cast<safe_browsing::SafeBrowsingService*>(
1356 safe_browsing::SafeBrowsingServiceInterface::CreateSafeBrowsingService());
1357 if (safe_browsing_service_)
1358 safe_browsing_service_->Initialize();
1361 void BrowserProcessImpl::CreateSubresourceFilterRulesetService() {
1362 DCHECK(!subresource_filter_ruleset_service_);
1363 created_subresource_filter_ruleset_service_ = true;
1365 base::FilePath user_data_dir;
1366 base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
1367 subresource_filter_ruleset_service_ =
1368 subresource_filter::RulesetService::Create(local_state(), user_data_dir);
1371 #if !BUILDFLAG(IS_ANDROID)
1372 // Android's GCMDriver currently makes the assumption that it's a singleton.
1373 // Until this gets fixed, instantiating multiple Java GCMDrivers will throw an
1374 // exception, but because they're only initialized on demand these crashes
1375 // would be very difficult to triage. See http://crbug.com/437827.
1376 void BrowserProcessImpl::CreateGCMDriver() {
1377 DCHECK(!gcm_driver_);
1379 base::FilePath store_path;
1380 CHECK(base::PathService::Get(chrome::DIR_GLOBAL_GCM_STORE, &store_path));
1381 scoped_refptr<base::SequencedTaskRunner> blocking_task_runner(
1382 base::ThreadPool::CreateSequencedTaskRunner(
1383 {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
1384 base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}));
1386 gcm_driver_ = gcm::CreateGCMDriverDesktop(
1387 base::WrapUnique(new gcm::GCMClientFactory), local_state(), store_path,
1388 base::BindRepeating(&RequestProxyResolvingSocketFactory),
1389 system_network_context_manager()->GetSharedURLLoaderFactory(),
1390 content::GetNetworkConnectionTracker(), chrome::GetChannel(),
1391 gcm::GetProductCategoryForSubtypes(local_state()),
1392 content::GetUIThreadTaskRunner({}), content::GetIOThreadTaskRunner({}),
1393 blocking_task_runner);
1395 #endif // !BUILDFLAG(IS_ANDROID)
1397 void BrowserProcessImpl::CreateNetworkTimeTracker() {
1398 if (network_time_tracker_) {
1401 network_time_tracker_ = std::make_unique<network_time::NetworkTimeTracker>(
1402 base::WrapUnique(new base::DefaultClock()),
1403 base::WrapUnique(new base::DefaultTickClock()), local_state(),
1404 system_network_context_manager()->GetSharedURLLoaderFactory());
1407 void BrowserProcessImpl::ApplyDefaultBrowserPolicy() {
1408 if (local_state()->GetBoolean(prefs::kDefaultBrowserSettingEnabled)) {
1409 // The worker pointer is reference counted. While it is running, the
1410 // message loops of the FILE and UI thread will hold references to it
1411 // and it will be automatically freed once all its tasks have finished.
1412 auto set_browser_worker =
1413 base::MakeRefCounted<shell_integration::DefaultBrowserWorker>();
1414 // The user interaction must always be disabled when applying the default
1415 // browser policy since it is done at each browser startup and the result
1416 // of the interaction cannot be forced.
1417 set_browser_worker->set_interactive_permitted(false);
1418 set_browser_worker->StartSetAsDefault(base::NullCallback());
1422 void BrowserProcessImpl::Pin() {
1423 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1424 CHECK(!IsShuttingDown());
1427 void BrowserProcessImpl::Unpin() {
1428 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1430 #if !BUILDFLAG(IS_ANDROID)
1431 // The quit closure is set by ChromeBrowserMainParts to transfer ownership of
1432 // the browser's lifetime to the BrowserProcess. Any KeepAlives registered and
1433 // unregistered prior to setting the quit closure are ignored. Only once the
1434 // quit closure is set should unpinning start process shutdown.
1439 DCHECK(!shutting_down_);
1440 shutting_down_ = true;
1442 #if !BUILDFLAG(IS_ANDROID)
1443 KeepAliveRegistry::GetInstance()->SetIsShuttingDown();
1444 #endif // !BUILDFLAG(IS_ANDROID)
1446 #if BUILDFLAG(ENABLE_PRINTING)
1447 // Wait for the pending print jobs to finish. Don't do this later, since
1448 // this might cause a nested run loop to run, and we don't want pending
1449 // tasks to run once teardown has started.
1450 print_job_manager_->Shutdown();
1453 #if defined(LEAK_SANITIZER)
1454 // Check for memory leaks now, before we start shutting down threads. Doing
1455 // this early means we won't report any shutdown-only leaks (as they have
1456 // not yet happened at this point).
1457 // If leaks are found, this will make the process exit immediately.
1458 __lsan_do_leak_check();
1461 CHECK(base::RunLoop::IsRunningOnCurrentThread());
1463 #if BUILDFLAG(IS_MAC)
1464 base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
1466 base::BindOnce(ChromeBrowserMainPartsMac::DidEndMainMessageLoop));
1469 #if !BUILDFLAG(IS_ANDROID)
1470 std::move(quit_closure_).Run();
1472 chrome::ShutdownIfNeeded();
1474 // TODO(crbug.com/967603): remove when root cause is found.
1475 CHECK_EQ(BrowserList::GetInstance()->size(), 0u);
1476 #endif // !BUILDFLAG(IS_ANDROID)
1479 // Mac is currently not supported.
1480 // TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is
1482 #if BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
1484 bool BrowserProcessImpl::IsRunningInBackground() const {
1485 // Check if browser is in the background.
1486 return chrome::GetTotalBrowserCount() == 0 &&
1487 KeepAliveRegistry::GetInstance()->IsKeepingAlive();
1490 void BrowserProcessImpl::RestartBackgroundInstance() {
1491 base::CommandLine* old_cl = base::CommandLine::ForCurrentProcess();
1492 auto new_cl = std::make_unique<base::CommandLine>(old_cl->GetProgram());
1494 base::CommandLine::SwitchMap switches = old_cl->GetSwitches();
1495 switches::RemoveSwitchesForAutostart(&switches);
1497 // Append the rest of the switches (along with their values, if any)
1498 // to the new command line
1499 for (const auto& it : switches) {
1500 const auto& switch_name = it.first;
1501 const auto& switch_value = it.second;
1502 if (switch_value.empty())
1503 new_cl->AppendSwitch(switch_name);
1505 new_cl->AppendSwitchNative(switch_name, switch_value);
1508 // Switches to add when auto-restarting Chrome.
1509 static constexpr const char* kSwitchesToAddOnAutorestart[] = {
1510 switches::kNoStartupWindow};
1512 // Ensure that our desired switches are set on the new process.
1513 for (const char* switch_to_add : kSwitchesToAddOnAutorestart) {
1514 if (!new_cl->HasSwitch(switch_to_add))
1515 new_cl->AppendSwitch(switch_to_add);
1518 #if BUILDFLAG(IS_WIN)
1519 new_cl->AppendArg(switches::kPrefetchArgumentBrowserBackground);
1520 #endif // BUILDFLAG(IS_WIN)
1522 DLOG(WARNING) << "Shutting down current instance of the browser.";
1523 chrome::AttemptExit();
1525 upgrade_util::SetNewCommandLine(std::move(new_cl));
1528 void BrowserProcessImpl::OnAutoupdateTimer() {
1529 if (IsRunningInBackground()) {
1530 // upgrade_util::IsUpdatePendingRestart touches the disk, so do it on a
1532 base::ThreadPool::PostTaskAndReplyWithResult(
1534 {base::TaskPriority::BEST_EFFORT,
1535 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN, base::MayBlock()},
1536 base::BindOnce(&upgrade_util::IsUpdatePendingRestart),
1537 base::BindOnce(&BrowserProcessImpl::OnPendingRestartResult,
1538 base::Unretained(this)));
1542 void BrowserProcessImpl::OnPendingRestartResult(
1543 bool is_update_pending_restart) {
1544 // Make sure that the browser is still in the background after returning from
1546 if (is_update_pending_restart && IsRunningInBackground()) {
1547 DLOG(WARNING) << "Detected update. Restarting browser.";
1548 RestartBackgroundInstance();
1551 #endif // BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_LINUX) ||
1552 // BUILDFLAG(IS_CHROMEOS_LACROS))