[M120 Migration]Fix for crash during chrome exit
[platform/framework/web/chromium-efl.git] / chrome / browser / browser_process_impl.h
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.
4
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.
9
10 #ifndef CHROME_BROWSER_BROWSER_PROCESS_IMPL_H_
11 #define CHROME_BROWSER_BROWSER_PROCESS_IMPL_H_
12
13 #include <stdint.h>
14
15 #include <memory>
16 #include <string>
17
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"
38
39 #if !BUILDFLAG(IS_ANDROID)
40 #include "chrome/browser/upgrade_detector/build_state.h"
41 #endif
42
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)
47
48 class BatteryMetrics;
49 class ChromeMetricsServicesManagerClient;
50 class DevToolsAutoOpener;
51 class RemoteDebuggingServer;
52 class PrefRegistrySimple;
53 class SecureOriginPrefsObserver;
54 class SiteIsolationPrefsObserver;
55 class SystemNotificationHelper;
56 class StartupData;
57
58 namespace breadcrumbs {
59 class ApplicationBreadcrumbsLogger;
60 }  // namespace breadcrumbs
61
62 namespace embedder_support {
63 class OriginTrialsSettingsStorage;
64 }  // namespace embedder_support
65
66 namespace extensions {
67 class ChromeExtensionsBrowserClient;
68 }
69
70 namespace gcm {
71 class GCMDriver;
72 }
73
74 namespace os_crypt_async {
75 class OSCryptAsync;
76 }
77
78 namespace policy {
79 class ChromeBrowserPolicyConnector;
80 class PolicyService;
81 }  // namespace policy
82
83 namespace webrtc_event_logging {
84 class WebRtcEventLogManager;
85 }  // namespace webrtc_event_logging
86
87 namespace speech {
88 class SodaInstallerImpl;
89 class SodaInstallerImplChromeOS;
90 }  // namespace speech
91
92 namespace screen_ai {
93 class ScreenAIInstallState;
94 }  // namespace screen_ai
95
96 // Real implementation of BrowserProcess that creates and returns the services.
97 class BrowserProcessImpl : public BrowserProcess,
98                            public KeepAliveStateObserver {
99  public:
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);
104
105   BrowserProcessImpl(const BrowserProcessImpl&) = delete;
106   BrowserProcessImpl& operator=(const BrowserProcessImpl&) = delete;
107
108   ~BrowserProcessImpl() override;
109
110   // Called to complete initialization.
111   void Init();
112
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);
120 #endif
121
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();
128 #endif
129
130   // Called before the browser threads are created.
131   void PreCreateThreads();
132
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();
137
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();
145 #endif
146
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);
152
153   // BrowserProcess implementation.
154   void EndSession() override;
155   void FlushLocalStateAndReply(base::OnceClosure reply) override;
156   metrics_services_manager::MetricsServicesManager* GetMetricsServicesManager()
157       override;
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()
163       override;
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()
183       override;
184   printing::BackgroundPrintingManager* background_printing_manager() override;
185 #if !BUILDFLAG(IS_ANDROID)
186   IntranetRedirectDetector* intranet_redirect_detector() override;
187 #endif
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;
196 #endif
197   StatusTray* status_tray() override;
198   safe_browsing::SafeBrowsingService* safe_browsing_service() override;
199   subresource_filter::RulesetService* subresource_filter_ruleset_service()
200       override;
201
202   StartupData* startup_data() override;
203
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;
208 #endif
209
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;
216 #endif
217   resource_coordinator::TabManager* GetTabManager() override;
218   resource_coordinator::ResourceCoordinatorParts* resource_coordinator_parts()
219       override;
220
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;
225 #endif
226
227   os_crypt_async::OSCryptAsync* os_crypt_async() override;
228
229   BuildState* GetBuildState() override;
230
231   static void RegisterPrefs(PrefRegistrySimple* registry);
232
233  private:
234   using WebRtcEventLogManager = webrtc_event_logging::WebRtcEventLogManager;
235
236   // KeepAliveStateObserver implementation
237   void OnKeepAliveStateChanged(bool is_keeping_alive) override;
238   void OnKeepAliveRestartStateChanged(bool can_restart) override;
239
240   // Create network quality observer so that it can propagate network quality
241   // changes to the render process.
242   void CreateNetworkQualityObserver();
243
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();
257
258   void ApplyDefaultBrowserPolicy();
259
260   // Methods called to control our lifetime. The browser process can be "pinned"
261   // to make sure it keeps running.
262   void Pin();
263   void Unpin();
264
265   const raw_ptr<StartupData> startup_data_;
266
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_;
271
272   // Must be destroyed before |browser_policy_connector_|.
273   bool created_profile_manager_ = false;
274   std::unique_ptr<ProfileManager> profile_manager_;
275
276   const std::unique_ptr<PrefService> local_state_;
277
278   // |metrics_services_manager_| owns this.
279   raw_ptr<ChromeMetricsServicesManagerClient, AcrossTasksDanglingUntriaged>
280       metrics_services_manager_client_ = nullptr;
281
282   // Must be destroyed before |local_state_|.
283   std::unique_ptr<metrics_services_manager::MetricsServicesManager>
284       metrics_services_manager_;
285
286 #if BUILDFLAG(IS_ANDROID)
287   // Must be destroyed before |local_state_|.
288   std::unique_ptr<accessibility::AccessibilityPrefsController>
289       accessibility_prefs_controller_;
290 #endif
291
292   std::unique_ptr<network::NetworkQualityTracker> network_quality_tracker_;
293
294   // Listens to NetworkQualityTracker and sends network quality updates to the
295   // renderer.
296   std::unique_ptr<
297       network::NetworkQualityTracker::RTTAndThroughputEstimatesObserver>
298       network_quality_observer_;
299
300   std::unique_ptr<embedder_support::OriginTrialsSettingsStorage>
301       origin_trials_settings_storage_;
302
303   bool created_icon_manager_ = false;
304   std::unique_ptr<IconManager> icon_manager_;
305
306   std::unique_ptr<GpuModeManager> gpu_mode_manager_;
307
308 #if BUILDFLAG(ENABLE_EXTENSIONS)
309   std::unique_ptr<extensions::ChromeExtensionsBrowserClient>
310       extensions_browser_client_;
311
312   scoped_refptr<extensions::EventRouterForwarder>
313       extension_event_router_forwarder_;
314
315   std::unique_ptr<MediaFileSystemRegistry> media_file_system_registry_;
316 #endif
317
318 #if !BUILDFLAG(IS_ANDROID)
319   std::unique_ptr<RemoteDebuggingServer> remote_debugging_server_;
320   std::unique_ptr<DevToolsAutoOpener> devtools_auto_opener_;
321 #endif
322
323 #if BUILDFLAG(ENABLE_PRINT_PREVIEW)
324   scoped_refptr<printing::PrintPreviewDialogController>
325       print_preview_dialog_controller_;
326
327   std::unique_ptr<printing::BackgroundPrintingManager>
328       background_printing_manager_;
329 #endif
330
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_;
335 #endif
336
337 #if !BUILDFLAG(IS_ANDROID)
338   std::unique_ptr<IntranetRedirectDetector> intranet_redirect_detector_;
339 #endif
340
341   std::unique_ptr<StatusTray> status_tray_;
342
343 #if BUILDFLAG(ENABLE_SYSTEM_NOTIFICATIONS)
344   bool created_notification_bridge_ = false;
345 #endif
346
347   std::unique_ptr<NotificationPlatformBridge> notification_bridge_;
348
349   // Use SystemNotificationHelper::GetInstance to get this instance.
350   std::unique_ptr<SystemNotificationHelper> system_notification_helper_;
351
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_;
356 #endif
357
358   bool created_safe_browsing_service_ = false;
359   scoped_refptr<safe_browsing::SafeBrowsingService> safe_browsing_service_;
360
361   bool created_subresource_filter_ruleset_service_ = false;
362   std::unique_ptr<subresource_filter::RulesetService>
363       subresource_filter_ruleset_service_;
364
365   bool shutting_down_ = false;
366
367   bool tearing_down_ = false;
368
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_;
372 #endif
373
374   std::string locale_;
375
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_;
380
381   scoped_refptr<DownloadRequestLimiter> download_request_limiter_;
382
383   // Ensures that the observers of plugin/print disable/enable state
384   // notifications are properly added and removed.
385   PrefChangeRegistrar pref_change_registrar_;
386
387   std::unique_ptr<BatteryMetrics> battery_metrics_;
388
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_;
393
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))
402
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_;
407
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_;
414 #endif
415
416 #if BUILDFLAG(IS_CHROMEOS_ASH)
417   // Chrome OS has a different implementation of SodaInstaller.
418   std::unique_ptr<speech::SodaInstallerImplChromeOS> soda_installer_impl_;
419 #endif
420
421 #if BUILDFLAG(ENABLE_SCREEN_AI_SERVICE)
422   // Used to download Screen AI on demand and keep track of the library
423   // availability.
424   std::unique_ptr<screen_ai::ScreenAIInstallState> screen_ai_download_;
425 #endif
426
427   std::unique_ptr<BrowserProcessPlatformPart> platform_part_;
428
429   // Lazily initialized.
430   std::unique_ptr<WebRtcLogUploader> webrtc_log_uploader_;
431
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_;
437
438   std::unique_ptr<network_time::NetworkTimeTracker> network_time_tracker_;
439
440   std::unique_ptr<gcm::GCMDriver> gcm_driver_;
441
442   std::unique_ptr<resource_coordinator::ResourceCoordinatorParts>
443       resource_coordinator_parts_;
444
445   std::unique_ptr<SecureOriginPrefsObserver> secure_origin_prefs_observer_;
446   std::unique_ptr<SiteIsolationPrefsObserver> site_isolation_prefs_observer_;
447
448 #if !BUILDFLAG(IS_ANDROID)
449   // Called to signal the process' main message loop to exit.
450   base::OnceClosure quit_closure_;
451
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_;
455
456   BuildState build_state_;
457 #endif
458
459 #if BUILDFLAG(IS_ANDROID)
460   std::unique_ptr<base::android::ApplicationStatusListener> app_state_listener_;
461 #endif
462
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_;
467
468   std::unique_ptr<os_crypt_async::OSCryptAsync> os_crypt_async_;
469
470   SEQUENCE_CHECKER(sequence_checker_);
471 };
472
473 #endif  // CHROME_BROWSER_BROWSER_PROCESS_IMPL_H_