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 // When each service is created, we set a flag indicating this. At this point,
6 // the service initialization could fail or succeed. This allows us to remember
7 // if we tried to create a service, and not try creating it over and over if
8 // the creation failed.
10 #ifndef CHROME_BROWSER_BROWSER_PROCESS_IMPL_H_
11 #define CHROME_BROWSER_BROWSER_PROCESS_IMPL_H_
18 #include "base/memory/raw_ptr.h"
19 #include "base/memory/ref_counted.h"
20 #include "base/sequence_checker.h"
21 #include "base/timer/timer.h"
22 #include "build/build_config.h"
23 #include "build/chromeos_buildflags.h"
24 #include "chrome/browser/browser_process.h"
25 #include "chrome/common/buildflags.h"
26 #include "components/keep_alive_registry/keep_alive_state_observer.h"
27 #include "components/metrics_services_manager/metrics_services_manager.h"
28 #include "components/nacl/common/buildflags.h"
29 #include "components/prefs/persistent_pref_store.h"
30 #include "components/prefs/pref_change_registrar.h"
31 #include "components/services/screen_ai/buildflags/buildflags.h"
32 #include "extensions/buildflags/buildflags.h"
33 #include "media/media_buildflags.h"
34 #include "ppapi/buildflags/buildflags.h"
35 #include "printing/buildflags/buildflags.h"
36 #include "services/network/public/cpp/network_quality_tracker.h"
37 #include "services/network/public/mojom/network_service.mojom-forward.h"
39 #if !BUILDFLAG(IS_ANDROID)
40 #include "chrome/browser/upgrade_detector/build_state.h"
43 #if BUILDFLAG(IS_ANDROID)
44 #include "base/android/application_status_listener.h"
45 #include "chrome/browser/accessibility/accessibility_prefs/android/accessibility_prefs_controller.h"
46 #endif // BUILDFLAG(IS_ANDROID)
49 class ChromeMetricsServicesManagerClient;
50 class DevToolsAutoOpener;
51 class RemoteDebuggingServer;
52 class PrefRegistrySimple;
53 class SecureOriginPrefsObserver;
54 class SiteIsolationPrefsObserver;
55 class SystemNotificationHelper;
58 namespace breadcrumbs {
59 class ApplicationBreadcrumbsLogger;
60 } // namespace breadcrumbs
62 namespace embedder_support {
63 class OriginTrialsSettingsStorage;
64 } // namespace embedder_support
66 namespace extensions {
67 class ChromeExtensionsBrowserClient;
74 namespace os_crypt_async {
79 class ChromeBrowserPolicyConnector;
83 namespace webrtc_event_logging {
84 class WebRtcEventLogManager;
85 } // namespace webrtc_event_logging
88 class SodaInstallerImpl;
89 class SodaInstallerImplChromeOS;
93 class ScreenAIInstallState;
94 } // namespace screen_ai
96 // Real implementation of BrowserProcess that creates and returns the services.
97 class BrowserProcessImpl : public BrowserProcess,
98 public KeepAliveStateObserver {
100 // |startup_data| should not be null. The BrowserProcessImpl
101 // will take the PrefService owned by the creator as the Local State instead
102 // of loading the JSON file from disk.
103 explicit BrowserProcessImpl(StartupData* startup_data);
105 BrowserProcessImpl(const BrowserProcessImpl&) = delete;
106 BrowserProcessImpl& operator=(const BrowserProcessImpl&) = delete;
108 ~BrowserProcessImpl() override;
110 // Called to complete initialization.
113 #if !BUILDFLAG(IS_ANDROID)
114 // Sets a closure to be run to break out of a run loop on browser shutdown
115 // (when the KeepAlive count reaches zero).
116 // TODO(https://crbug.com/845966): This is also used on macOS for the Cocoa
117 // first run dialog so that shutdown can be initiated via a signal while the
118 // first run dialog is showing.
119 void SetQuitClosure(base::OnceClosure quit_closure);
122 #if BUILDFLAG(IS_MAC)
123 // Clears the quit closure. Shutdown will not be initiated should the
124 // KeepAlive count reach zero. This function may be called more than once.
125 // TODO(https://crbug.com/845966): Remove this once the Cocoa first run
126 // dialog no longer needs it.
127 void ClearQuitClosure();
130 // Called before the browser threads are created.
131 void PreCreateThreads();
133 // Called after the threads have been created but before the message loops
134 // starts running. Allows the browser process to do any initialization that
135 // requires all threads running.
136 void PreMainMessageLoopRun();
138 // Most cleanup is done by these functions, driven from
139 // ChromeBrowserMain based on notifications from the content
140 // framework, rather than in the destructor, so that we can
141 // interleave cleanup with threads being stopped.
142 #if !BUILDFLAG(IS_ANDROID)
143 void StartTearDown();
144 void PostDestroyThreads();
147 // Sets |metrics_services_manager_| and |metrics_services_manager_client_|
148 // which is owned by it.
149 void SetMetricsServices(
150 std::unique_ptr<metrics_services_manager::MetricsServicesManager> manager,
151 metrics_services_manager::MetricsServicesManagerClient* client);
153 // BrowserProcess implementation.
154 void EndSession() override;
155 void FlushLocalStateAndReply(base::OnceClosure reply) override;
156 metrics_services_manager::MetricsServicesManager* GetMetricsServicesManager()
158 metrics::MetricsService* metrics_service() override;
159 // TODO(qinmin): Remove this method as callers can retrieve the global
160 // instance from SystemNetworkContextManager directly.
161 SystemNetworkContextManager* system_network_context_manager() override;
162 scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory()
164 network::NetworkQualityTracker* network_quality_tracker() override;
165 embedder_support::OriginTrialsSettingsStorage*
166 GetOriginTrialsSettingsStorage() override;
167 ProfileManager* profile_manager() override;
168 PrefService* local_state() override;
169 variations::VariationsService* variations_service() override;
170 BrowserProcessPlatformPart* platform_part() override;
171 extensions::EventRouterForwarder* extension_event_router_forwarder() override;
172 NotificationUIManager* notification_ui_manager() override;
173 NotificationPlatformBridge* notification_platform_bridge() override;
174 policy::ChromeBrowserPolicyConnector* browser_policy_connector() override;
175 policy::PolicyService* policy_service() override;
176 IconManager* icon_manager() override;
177 GpuModeManager* gpu_mode_manager() override;
178 void CreateDevToolsProtocolHandler() override;
179 void CreateDevToolsAutoOpener() override;
180 bool IsShuttingDown() override;
181 printing::PrintJobManager* print_job_manager() override;
182 printing::PrintPreviewDialogController* print_preview_dialog_controller()
184 printing::BackgroundPrintingManager* background_printing_manager() override;
185 #if !BUILDFLAG(IS_ANDROID)
186 IntranetRedirectDetector* intranet_redirect_detector() override;
188 const std::string& GetApplicationLocale() override;
189 void SetApplicationLocale(const std::string& actual_locale) override;
190 DownloadStatusUpdater* download_status_updater() override;
191 DownloadRequestLimiter* download_request_limiter() override;
192 BackgroundModeManager* background_mode_manager() override;
193 #if BUILDFLAG(ENABLE_BACKGROUND_MODE)
194 void set_background_mode_manager_for_test(
195 std::unique_ptr<BackgroundModeManager> manager) override;
197 StatusTray* status_tray() override;
198 safe_browsing::SafeBrowsingService* safe_browsing_service() override;
199 subresource_filter::RulesetService* subresource_filter_ruleset_service()
202 StartupData* startup_data() override;
204 // TODO(crbug.com/1052397): Revisit the macro expression once build flag switch
205 // of lacros-chrome is complete.
206 #if BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
207 void StartAutoupdateTimer() override;
210 component_updater::ComponentUpdateService* component_updater() override;
211 MediaFileSystemRegistry* media_file_system_registry() override;
212 WebRtcLogUploader* webrtc_log_uploader() override;
213 network_time::NetworkTimeTracker* network_time_tracker() override;
214 #if !BUILDFLAG(IS_ANDROID)
215 gcm::GCMDriver* gcm_driver() override;
217 resource_coordinator::TabManager* GetTabManager() override;
218 resource_coordinator::ResourceCoordinatorParts* resource_coordinator_parts()
221 #if !BUILDFLAG(IS_ANDROID)
222 SerialPolicyAllowedPorts* serial_policy_allowed_ports() override;
223 HidSystemTrayIcon* hid_system_tray_icon() override;
224 UsbSystemTrayIcon* usb_system_tray_icon() override;
227 os_crypt_async::OSCryptAsync* os_crypt_async() override;
229 BuildState* GetBuildState() override;
231 static void RegisterPrefs(PrefRegistrySimple* registry);
234 using WebRtcEventLogManager = webrtc_event_logging::WebRtcEventLogManager;
236 // KeepAliveStateObserver implementation
237 void OnKeepAliveStateChanged(bool is_keeping_alive) override;
238 void OnKeepAliveRestartStateChanged(bool can_restart) override;
240 // Create network quality observer so that it can propagate network quality
241 // changes to the render process.
242 void CreateNetworkQualityObserver();
244 void CreateProfileManager();
245 void CreateIconManager();
246 void CreateNotificationPlatformBridge();
247 void CreateNotificationUIManager();
248 void CreatePrintPreviewDialogController();
249 void CreateBackgroundPrintingManager();
250 void CreateSafeBrowsingService();
251 void CreateSubresourceFilterRulesetService();
252 void CreateOptimizationGuideService();
253 void CreateStatusTray();
254 void CreateBackgroundModeManager();
255 void CreateGCMDriver();
256 void CreateNetworkTimeTracker();
258 void ApplyDefaultBrowserPolicy();
260 // Methods called to control our lifetime. The browser process can be "pinned"
261 // to make sure it keeps running.
265 const raw_ptr<StartupData> startup_data_;
267 // Must be destroyed after |local_state_|.
268 // Must be destroyed after |profile_manager_|.
269 std::unique_ptr<policy::ChromeBrowserPolicyConnector> const
270 browser_policy_connector_;
272 // Must be destroyed before |browser_policy_connector_|.
273 bool created_profile_manager_ = false;
274 std::unique_ptr<ProfileManager> profile_manager_;
276 const std::unique_ptr<PrefService> local_state_;
278 // |metrics_services_manager_| owns this.
279 raw_ptr<ChromeMetricsServicesManagerClient, AcrossTasksDanglingUntriaged>
280 metrics_services_manager_client_ = nullptr;
282 // Must be destroyed before |local_state_|.
283 std::unique_ptr<metrics_services_manager::MetricsServicesManager>
284 metrics_services_manager_;
286 #if BUILDFLAG(IS_ANDROID)
287 // Must be destroyed before |local_state_|.
288 std::unique_ptr<accessibility::AccessibilityPrefsController>
289 accessibility_prefs_controller_;
292 std::unique_ptr<network::NetworkQualityTracker> network_quality_tracker_;
294 // Listens to NetworkQualityTracker and sends network quality updates to the
297 network::NetworkQualityTracker::RTTAndThroughputEstimatesObserver>
298 network_quality_observer_;
300 std::unique_ptr<embedder_support::OriginTrialsSettingsStorage>
301 origin_trials_settings_storage_;
303 bool created_icon_manager_ = false;
304 std::unique_ptr<IconManager> icon_manager_;
306 std::unique_ptr<GpuModeManager> gpu_mode_manager_;
308 #if BUILDFLAG(ENABLE_EXTENSIONS)
309 std::unique_ptr<extensions::ChromeExtensionsBrowserClient>
310 extensions_browser_client_;
312 scoped_refptr<extensions::EventRouterForwarder>
313 extension_event_router_forwarder_;
315 std::unique_ptr<MediaFileSystemRegistry> media_file_system_registry_;
318 #if !BUILDFLAG(IS_ANDROID)
319 std::unique_ptr<RemoteDebuggingServer> remote_debugging_server_;
320 std::unique_ptr<DevToolsAutoOpener> devtools_auto_opener_;
323 #if BUILDFLAG(ENABLE_PRINT_PREVIEW)
324 scoped_refptr<printing::PrintPreviewDialogController>
325 print_preview_dialog_controller_;
327 std::unique_ptr<printing::BackgroundPrintingManager>
328 background_printing_manager_;
331 #if BUILDFLAG(ENABLE_CHROME_NOTIFICATIONS)
332 // Manager for desktop notification UI.
333 bool created_notification_ui_manager_ = false;
334 std::unique_ptr<NotificationUIManager> notification_ui_manager_;
337 #if !BUILDFLAG(IS_ANDROID)
338 std::unique_ptr<IntranetRedirectDetector> intranet_redirect_detector_;
341 std::unique_ptr<StatusTray> status_tray_;
343 #if BUILDFLAG(ENABLE_SYSTEM_NOTIFICATIONS)
344 bool created_notification_bridge_ = false;
347 std::unique_ptr<NotificationPlatformBridge> notification_bridge_;
349 // Use SystemNotificationHelper::GetInstance to get this instance.
350 std::unique_ptr<SystemNotificationHelper> system_notification_helper_;
352 #if BUILDFLAG(ENABLE_BACKGROUND_MODE)
353 // Must be destroyed after the profile manager, because it doesn't remove
354 // itself as a profile attributes storage observer on destruction.
355 std::unique_ptr<BackgroundModeManager> background_mode_manager_;
358 bool created_safe_browsing_service_ = false;
359 scoped_refptr<safe_browsing::SafeBrowsingService> safe_browsing_service_;
361 bool created_subresource_filter_ruleset_service_ = false;
362 std::unique_ptr<subresource_filter::RulesetService>
363 subresource_filter_ruleset_service_;
365 bool shutting_down_ = false;
367 bool tearing_down_ = false;
369 #if BUILDFLAG(ENABLE_PRINTING)
370 // Ensures that all the print jobs are finished before closing the browser.
371 std::unique_ptr<printing::PrintJobManager> print_job_manager_;
376 // Download status updates (like a changing application icon on dock/taskbar)
377 // are global per-application. DownloadStatusUpdater does no work in the ctor
378 // so we don't have to worry about lazy initialization.
379 std::unique_ptr<DownloadStatusUpdater> download_status_updater_;
381 scoped_refptr<DownloadRequestLimiter> download_request_limiter_;
383 // Ensures that the observers of plugin/print disable/enable state
384 // notifications are properly added and removed.
385 PrefChangeRegistrar pref_change_registrar_;
387 std::unique_ptr<BatteryMetrics> battery_metrics_;
389 // TODO(crbug.com/1052397): Revisit the macro expression once build flag switch
390 // of lacros-chrome is complete.
391 #if BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
392 base::RepeatingTimer autoupdate_timer_;
394 // Gets called by autoupdate timer to see if browser needs restart and can be
395 // restarted, and if that's the case, restarts the browser.
396 void OnAutoupdateTimer();
397 bool IsRunningInBackground() const;
398 void OnPendingRestartResult(bool is_update_pending_restart);
399 void RestartBackgroundInstance();
400 #endif // BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_LINUX) ||
401 // BUILDFLAG(IS_CHROMEOS_LACROS))
403 // component updater is normally not used under ChromeOS due
404 // to concerns over integrity of data shared between profiles,
405 // but some users of component updater only install per-user.
406 std::unique_ptr<component_updater::ComponentUpdateService> component_updater_;
408 #if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS)
409 // Used to create a singleton instance of SodaInstallerImpl, which can be
410 // retrieved using speech::SodaInstaller::GetInstance().
411 // SodaInstallerImpl depends on ComponentUpdateService, so define it here
412 // to ensure that SodaInstallerImpl gets destructed first.
413 std::unique_ptr<speech::SodaInstallerImpl> soda_installer_impl_;
416 #if BUILDFLAG(IS_CHROMEOS_ASH)
417 // Chrome OS has a different implementation of SodaInstaller.
418 std::unique_ptr<speech::SodaInstallerImplChromeOS> soda_installer_impl_;
421 #if BUILDFLAG(ENABLE_SCREEN_AI_SERVICE)
422 // Used to download Screen AI on demand and keep track of the library
424 std::unique_ptr<screen_ai::ScreenAIInstallState> screen_ai_download_;
427 std::unique_ptr<BrowserProcessPlatformPart> platform_part_;
429 // Lazily initialized.
430 std::unique_ptr<WebRtcLogUploader> webrtc_log_uploader_;
432 // WebRtcEventLogManager is a singleton which is instaniated before anything
433 // that needs it, and lives until ~BrowserProcessImpl(). This allows it to
434 // safely post base::Unretained(this) references to an internally owned task
435 // queue, since after ~BrowserProcessImpl(), those tasks would no longer run.
436 std::unique_ptr<WebRtcEventLogManager> webrtc_event_log_manager_;
438 std::unique_ptr<network_time::NetworkTimeTracker> network_time_tracker_;
440 std::unique_ptr<gcm::GCMDriver> gcm_driver_;
442 std::unique_ptr<resource_coordinator::ResourceCoordinatorParts>
443 resource_coordinator_parts_;
445 std::unique_ptr<SecureOriginPrefsObserver> secure_origin_prefs_observer_;
446 std::unique_ptr<SiteIsolationPrefsObserver> site_isolation_prefs_observer_;
448 #if !BUILDFLAG(IS_ANDROID)
449 // Called to signal the process' main message loop to exit.
450 base::OnceClosure quit_closure_;
452 std::unique_ptr<SerialPolicyAllowedPorts> serial_policy_allowed_ports_;
453 std::unique_ptr<HidSystemTrayIcon> hid_system_tray_icon_;
454 std::unique_ptr<UsbSystemTrayIcon> usb_system_tray_icon_;
456 BuildState build_state_;
459 #if BUILDFLAG(IS_ANDROID)
460 std::unique_ptr<base::android::ApplicationStatusListener> app_state_listener_;
463 // Observes application-wide events and logs them to breadcrumbs. Null if
464 // breadcrumbs logging is disabled.
465 std::unique_ptr<breadcrumbs::ApplicationBreadcrumbsLogger>
466 application_breadcrumbs_logger_;
468 std::unique_ptr<os_crypt_async::OSCryptAsync> os_crypt_async_;
470 SEQUENCE_CHECKER(sequence_checker_);
473 #endif // CHROME_BROWSER_BROWSER_PROCESS_IMPL_H_