[M120 Migration]Fix for crash during chrome exit
[platform/framework/web/chromium-efl.git] / chrome / browser / browser_process_impl.cc
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 #include "chrome/browser/browser_process_impl.h"
6
7 #include <stddef.h>
8 #include <stdio.h>
9
10 #include <algorithm>
11 #include <map>
12 #include <utility>
13 #include <vector>
14
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"
145
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"
151 #endif
152
153 #if BUILDFLAG(IS_CHROMEOS_ASH)
154 #include "components/soda/soda_installer_impl_chromeos.h"
155 #else
156 #include "ui/message_center/message_center.h"
157 #endif
158
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"
165 #else
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"
179 #endif
180
181 #if BUILDFLAG(ENABLE_BACKGROUND_MODE)
182 #include "chrome/browser/background/background_mode_manager.h"
183 #endif
184
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"
197 #endif
198
199 #if BUILDFLAG(ENABLE_PLUGINS)
200 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
201 #include "content/public/browser/plugin_service.h"
202 #endif
203
204 #if BUILDFLAG(ENABLE_PRINT_PREVIEW)
205 #include "chrome/browser/printing/print_preview_dialog_controller.h"
206 #endif
207
208 #if BUILDFLAG(ENABLE_SESSION_SERVICE)
209 #include "chrome/browser/sessions/exit_type_service.h"
210 #endif
211
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"
216 #endif
217
218 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
219 #include "chrome/browser/error_reporting/chrome_js_error_report_processor.h"  // nogncheck
220 #endif
221
222 #if BUILDFLAG(ENABLE_CHROME_NOTIFICATIONS)
223 #include "chrome/browser/notifications/notification_ui_manager.h"
224 #endif
225
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"
235 #endif
236
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;
241 #endif
242
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
247 // anyway.
248 static constexpr base::TimeDelta kEndSessionTimeout = base::Seconds(10);
249 #endif
250
251 using content::BrowserThread;
252 using content::ChildProcessSecurityPolicy;
253
254 BrowserProcessImpl::BrowserProcessImpl(StartupData* startup_data)
255     : startup_data_(startup_data),
256       browser_policy_connector_(startup_data->chrome_feature_list_creator()
257                                     ->TakeChromeBrowserPolicyConnector()),
258       local_state_(
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;
263
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());
267
268   DCHECK(browser_policy_connector_);
269   DCHECK(local_state_);
270   DCHECK(startup_data);
271   // Most work should be done in Init().
272 }
273
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();
280   }
281
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
285   // created).
286   GetMetricsServicesManager();
287   DCHECK(metrics_services_manager_client_);
288   metrics_services_manager_client_->OnCrosSettingsCreated();
289 #endif
290
291   download_status_updater_ = std::make_unique<DownloadStatusUpdater>();
292
293 #if BUILDFLAG(ENABLE_PRINTING)
294   // Must be created after the NotificationService.
295   print_job_manager_ = std::make_unique<printing::PrintJobManager>();
296 #endif
297
298   ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
299       chrome::kChromeSearchScheme);
300
301 #if BUILDFLAG(IS_MAC)
302   ui::InitIdleMonitor();
303 #endif
304
305 #if BUILDFLAG(ENABLE_EXTENSIONS)
306   extensions::AppWindowClient::Set(ChromeAppWindowClient::GetInstance());
307
308   extension_event_router_forwarder_ =
309       base::MakeRefCounted<extensions::EventRouterForwarder>();
310
311   EnsureExtensionsClientInitialized(
312       controlled_frame::CreateAvailabilityCheckMap());
313
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());
319
320 #if BUILDFLAG(IS_CHROMEOS)
321   extensions_browser_client_->AddAPIProvider(
322       std::make_unique<
323           chromeos::ChromeOSTelemetryExtensionsBrowserAPIProvider>());
324 #endif  // BUILDFLAG(IS_CHROMEOS)
325
326 #endif  // BUILDFLAG(ENABLE_EXTENSIONS)
327
328 #if BUILDFLAG(ENABLE_CHROME_NOTIFICATIONS)
329   message_center::MessageCenter::Initialize();
330   // Set the system notification source display name ("Google Chrome" or
331   // "Chromium").
332   if (message_center::MessageCenter::Get()) {
333     message_center::MessageCenter::Get()->SetSystemNotificationAppName(
334         l10n_util::GetStringUTF16(IDS_PRODUCT_NAME));
335   }
336 #endif
337
338   system_notification_helper_ = std::make_unique<SystemNotificationHelper>();
339
340   update_client::UpdateQueryParams::SetDelegate(
341       ChromeUpdateQueryParamsDelegate::GetInstance());
342
343   // Make sure permissions client has been set.
344   ChromePermissionsClient::GetInstance();
345
346   // Make sure media session client has been set.
347   ChromeMediaSessionClient::GetInstance();
348
349   // Make sure webapps client has been set.
350   webapps::ChromeWebappsClient::GetInstance();
351
352 #if !BUILDFLAG(IS_ANDROID)
353   KeepAliveRegistry::GetInstance()->SetIsShuttingDown(false);
354   KeepAliveRegistry::GetInstance()->AddObserver(this);
355 #endif  // !BUILDFLAG(IS_ANDROID)
356
357   MigrateObsoleteLocalStatePrefs(local_state());
358   pref_change_registrar_.Init(local_state());
359
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)));
365
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));
370
371   DCHECK(!webrtc_event_log_manager_);
372   webrtc_event_log_manager_ = WebRtcEventLogManager::CreateSingletonInstance();
373
374 #if BUILDFLAG(IS_MAC)
375   system_media_permissions::LogSystemMediaPermissionsStartupStats();
376 #endif
377
378 #if BUILDFLAG(IS_ANDROID)
379   webauthn::WebAuthnClientAndroid::SetClient(
380       std::make_unique<ChromeWebAuthnClientAndroid>());
381   accessibility_prefs_controller_ =
382       std::make_unique<accessibility::AccessibilityPrefsController>(
383           local_state());
384 #endif
385
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>();
390 #else
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)
395 }
396
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);
403 }
404 #endif
405
406 #if BUILDFLAG(IS_MAC)
407 void BrowserProcessImpl::ClearQuitClosure() {
408   quit_closure_.Reset();
409 }
410 #endif
411
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);
417 #endif
418
419 #if !BUILDFLAG(IS_ANDROID)
420   KeepAliveRegistry::GetInstance()->RemoveObserver(this);
421 #endif
422
423   g_browser_process = nullptr;
424 }
425
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());
433
434 #if BUILDFLAG(IS_ANDROID)
435   accessibility_prefs_controller_.reset();
436 #endif
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();
442
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();
451 #endif
452
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
456   // non-ChromeOS.
457   hid_system_tray_icon_.reset();
458   usb_system_tray_icon_.reset();
459 #endif
460
461   system_notification_helper_.reset();
462
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();
468 #endif
469
470   // Debugger must be cleaned up before ProfileManager.
471   remote_debugging_server_.reset();
472   devtools_auto_opener_.reset();
473
474   battery_metrics_.reset();
475
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();
480 #endif
481
482   // Need to clear profiles (download managers) before the IO thread.
483   {
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
488     // can be destroyed.
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-
494     // free).
495     profile_manager_.reset();
496   }
497
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();
507 #endif
508
509 #if BUILDFLAG(ENABLE_CHROME_NOTIFICATIONS)
510   if (message_center::MessageCenter::Get())
511     message_center::MessageCenter::Shutdown();
512 #endif
513
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();
519
520   // The |gcm_driver_| must shut down while the IO thread is still alive.
521   if (gcm_driver_)
522     gcm_driver_->Shutdown();
523
524   platform_part()->StartTearDown();
525
526   // Cancel any uploads to release the system url request context references.
527   if (webrtc_log_uploader_)
528     webrtc_log_uploader_->Shutdown();
529
530   sessions::SessionIdGenerator::GetInstance()->Shutdown();
531
532   // Resetting the status tray will result in calls to
533   // |g_browser_process->local_state()|. See crbug.com/1187418
534   status_tray_.reset();
535
536   local_state_->CommitPendingWrite();
537
538   // This expects to be destroyed before the task scheduler is torn down.
539   SystemNetworkContextManager::DeleteInstance();
540
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
543   // down.
544   application_breadcrumbs_logger_.reset();
545 }
546
547 void BrowserProcessImpl::PostDestroyThreads() {
548   // With the file_thread_ flushed, we can release any icon resources.
549   icon_manager_.reset();
550
551   // Must outlive the worker threads.
552   webrtc_log_uploader_.reset();
553 }
554 #endif  // !BUILDFLAG(IS_ANDROID)
555
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);
562 }
563
564 namespace {
565
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
569 // continuing.
570 class RundownTaskCounter :
571     public base::RefCountedThreadSafe<RundownTaskCounter> {
572  public:
573   RundownTaskCounter();
574
575   RundownTaskCounter(const RundownTaskCounter&) = delete;
576   RundownTaskCounter& operator=(const RundownTaskCounter&) = delete;
577
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
581   // out.
582   base::OnceClosure GetRundownClosure();
583
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);
587
588  private:
589   friend class base::RefCountedThreadSafe<RundownTaskCounter>;
590   ~RundownTaskCounter() {}
591
592   // Decrements the counter and releases the waitable event on transition to
593   // zero.
594   void Decrement();
595
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_;
600 };
601
602 RundownTaskCounter::RundownTaskCounter() = default;
603
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());
608
609   count_.Increment();
610
611   return base::BindOnce(&RundownTaskCounter::Decrement, this);
612 }
613
614 void RundownTaskCounter::Decrement() {
615   if (!count_.Decrement())
616     waitable_event_.Signal();
617 }
618
619 void RundownTaskCounter::TimedWait(base::TimeDelta timeout) {
620   // Decrement the excess count from the constructor.
621   Decrement();
622
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);
628 }
629
630 #if !BUILDFLAG(IS_ANDROID)
631 void RequestProxyResolvingSocketFactoryOnUIThread(
632     mojo::PendingReceiver<network::mojom::ProxyResolvingSocketFactory>
633         receiver) {
634   network::mojom::NetworkContext* network_context =
635       g_browser_process->system_network_context_manager()->GetContext();
636   network_context->CreateProxyResolvingSocketFactory(std::move(receiver));
637 }
638
639 void RequestProxyResolvingSocketFactory(
640     mojo::PendingReceiver<network::mojom::ProxyResolvingSocketFactory>
641         receiver) {
642   content::GetUIThreadTaskRunner({})->PostTask(
643       FROM_HERE, base::BindOnce(&RequestProxyResolvingSocketFactoryOnUIThread,
644                                 std::move(receiver)));
645 }
646 #endif
647
648 }  // namespace
649
650 void BrowserProcessImpl::FlushLocalStateAndReply(base::OnceClosure reply) {
651   local_state_->CommitPendingWrite(std::move(reply));
652 }
653
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);
665 #endif
666     if (profile->GetPrefs()) {
667       profile->GetPrefs()->CommitPendingWrite(
668           base::OnceClosure(), rundown_counter->GetRundownClosure());
669     }
670   }
671
672   // Tell the metrics service it was cleanly shutdown.
673   metrics::MetricsService* metrics = g_browser_process->metrics_service();
674   if (metrics) {
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.
679     //
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());
684 #endif
685   }
686
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;
691
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.
695   //
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
701   // process.
702   //
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);
713 #else
714   NOTIMPLEMENTED();
715 #endif
716 }
717
718 metrics_services_manager::MetricsServicesManager*
719 BrowserProcessImpl::GetMetricsServicesManager() {
720   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
721   if (!metrics_services_manager_) {
722     auto client =
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>(
727             std::move(client));
728   }
729   return metrics_services_manager_.get();
730 }
731
732 metrics::MetricsService* BrowserProcessImpl::metrics_service() {
733   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
734   return GetMetricsServicesManager()->GetMetricsService();
735 }
736
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>();
743   }
744   return origin_trials_settings_storage_.get();
745 }
746
747 SystemNetworkContextManager*
748 BrowserProcessImpl::system_network_context_manager() {
749   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
750   DCHECK(SystemNetworkContextManager::GetInstance());
751   return SystemNetworkContextManager::GetInstance();
752 }
753
754 scoped_refptr<network::SharedURLLoaderFactory>
755 BrowserProcessImpl::shared_url_loader_factory() {
756   return system_network_context_manager()->GetSharedURLLoaderFactory();
757 }
758
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));
764   }
765   return network_quality_tracker_.get();
766 }
767
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();
773 }
774
775 PrefService* BrowserProcessImpl::local_state() {
776   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
777   return local_state_.get();
778 }
779
780 variations::VariationsService* BrowserProcessImpl::variations_service() {
781   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
782   return GetMetricsServicesManager()->GetVariationsService();
783 }
784
785 BrowserProcessPlatformPart* BrowserProcessImpl::platform_part() {
786   return platform_part_.get();
787 }
788
789 extensions::EventRouterForwarder*
790 BrowserProcessImpl::extension_event_router_forwarder() {
791 #if BUILDFLAG(ENABLE_EXTENSIONS)
792   return extension_event_router_forwarder_.get();
793 #else
794   return NULL;
795 #endif
796 }
797
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();
804 #else
805   return nullptr;
806 #endif
807 }
808
809 NotificationPlatformBridge* BrowserProcessImpl::notification_platform_bridge() {
810 #if BUILDFLAG(ENABLE_SYSTEM_NOTIFICATIONS)
811   if (!created_notification_bridge_)
812     CreateNotificationPlatformBridge();
813   return notification_bridge_.get();
814 #else
815   return nullptr;
816 #endif
817 }
818
819 policy::ChromeBrowserPolicyConnector*
820 BrowserProcessImpl::browser_policy_connector() {
821   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
822   return browser_policy_connector_.get();
823 }
824
825 policy::PolicyService* BrowserProcessImpl::policy_service() {
826   return browser_policy_connector()->GetPolicyService();
827 }
828
829 IconManager* BrowserProcessImpl::icon_manager() {
830   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
831   if (!created_icon_manager_)
832     CreateIconManager();
833   return icon_manager_.get();
834 }
835
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();
841 }
842
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",
853             stderr);
854       fflush(stderr);
855       return;
856     }
857     remote_debugging_server_ = std::make_unique<RemoteDebuggingServer>();
858   }
859 #endif
860 }
861
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>();
869 #endif
870 }
871
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_;
878 }
879
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();
884 #else
885   NOTREACHED();
886   return nullptr;
887 #endif
888 }
889
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();
897 #else
898   NOTIMPLEMENTED();
899   return NULL;
900 #endif
901 }
902
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();
910 #else
911   NOTIMPLEMENTED();
912   return NULL;
913 #endif
914 }
915
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>();
921
922   return intranet_redirect_detector_.get();
923 }
924 #endif
925
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_);
930 #endif
931   DCHECK(!locale_.empty());
932   return locale_;
933 }
934
935 void BrowserProcessImpl::SetApplicationLocale(
936     const std::string& actual_locale) {
937   // NOTE: this is called before any threads have been created in non-test
938   // environments.
939   locale_ = actual_locale;
940   ChromeContentBrowserClient::SetApplicationLocale(actual_locale);
941   translate::TranslateDownloadManager::GetInstance()->set_application_locale(
942       actual_locale);
943 }
944
945 DownloadStatusUpdater* BrowserProcessImpl::download_status_updater() {
946   return download_status_updater_.get();
947 }
948
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();
954 #else
955   return NULL;
956 #endif
957 }
958
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();
963 }
964
965 network_time::NetworkTimeTracker* BrowserProcessImpl::network_time_tracker() {
966   CreateNetworkTimeTracker();
967   return network_time_tracker_.get();
968 }
969
970 #if !BUILDFLAG(IS_ANDROID)
971 gcm::GCMDriver* BrowserProcessImpl::gcm_driver() {
972   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
973   if (!gcm_driver_)
974     CreateGCMDriver();
975   return gcm_driver_.get();
976 }
977 #endif
978
979 resource_coordinator::TabManager* BrowserProcessImpl::GetTabManager() {
980   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
981   return resource_coordinator_parts()->tab_manager();
982 }
983
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>();
990   }
991   return resource_coordinator_parts_.get();
992 }
993
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());
1000   }
1001   return serial_policy_allowed_ports_.get();
1002 }
1003
1004 HidSystemTrayIcon* BrowserProcessImpl::hid_system_tray_icon() {
1005   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1006   return hid_system_tray_icon_.get();
1007 }
1008
1009 UsbSystemTrayIcon* BrowserProcessImpl::usb_system_tray_icon() {
1010   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1011   return usb_system_tray_icon_.get();
1012 }
1013 #endif
1014
1015 os_crypt_async::OSCryptAsync* BrowserProcessImpl::os_crypt_async() {
1016   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1017   return os_crypt_async_.get();
1018 }
1019
1020 BuildState* BrowserProcessImpl::GetBuildState() {
1021 #if !BUILDFLAG(IS_ANDROID)
1022   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1023   return &build_state_;
1024 #else
1025   NOTIMPLEMENTED();
1026   return nullptr;
1027 #endif
1028 }
1029
1030 // static
1031 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple* registry) {
1032   registry->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled,
1033                                 false);
1034
1035   registry->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt, false);
1036
1037 #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_ANDROID)
1038   registry->RegisterBooleanPref(prefs::kEulaAccepted, false);
1039 #endif  // BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_ANDROID)
1040
1041   registry->RegisterStringPref(language::prefs::kApplicationLocale,
1042                                std::string());
1043 #if BUILDFLAG(IS_CHROMEOS_ASH)
1044   registry->RegisterStringPref(prefs::kOwnerLocale, std::string());
1045   registry->RegisterStringPref(prefs::kHardwareKeyboardLayout,
1046                                std::string());
1047 #endif  // BUILDFLAG(IS_CHROMEOS_ASH)
1048
1049   registry->RegisterBooleanPref(metrics::prefs::kMetricsReportingEnabled,
1050                                 GoogleUpdateSettings::GetCollectStatsConsent());
1051   registry->RegisterBooleanPref(prefs::kDevToolsRemoteDebuggingAllowed, true);
1052 }
1053
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>();
1058   }
1059   return download_request_limiter_.get();
1060 }
1061
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();
1068 #else
1069   return nullptr;
1070 #endif
1071 }
1072
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);
1077 }
1078 #endif
1079
1080 StatusTray* BrowserProcessImpl::status_tray() {
1081   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1082   if (!status_tray_)
1083     CreateStatusTray();
1084   return status_tray_.get();
1085 }
1086
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();
1093 }
1094
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();
1101 }
1102
1103 StartupData* BrowserProcessImpl::startup_data() {
1104   return startup_data_;
1105 }
1106
1107 // TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is
1108 // complete.
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);
1113 }
1114 #endif
1115
1116 component_updater::ComponentUpdateService*
1117 BrowserProcessImpl::component_updater() {
1118   if (component_updater_)
1119     return component_updater_.get();
1120
1121   if (!BrowserThread::CurrentlyOn(BrowserThread::UI))
1122     return nullptr;
1123
1124   std::unique_ptr<component_updater::UpdateScheduler> scheduler =
1125       std::make_unique<component_updater::TimerUpdateScheduler>();
1126
1127   std::string brand;
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);
1134
1135   return component_updater_.get();
1136 }
1137
1138 void BrowserProcessImpl::OnKeepAliveStateChanged(bool is_keeping_alive) {
1139   if (is_keeping_alive)
1140     Pin();
1141   else
1142     Unpin();
1143 }
1144
1145 void BrowserProcessImpl::CreateNetworkQualityObserver() {
1146   DCHECK(!network_quality_observer_);
1147   network_quality_observer_ =
1148       content::CreateNetworkQualityObserver(network_quality_tracker());
1149   DCHECK(network_quality_observer_);
1150 }
1151
1152 void BrowserProcessImpl::OnKeepAliveRestartStateChanged(bool can_restart) {}
1153
1154 void BrowserProcessImpl::CreateProfileManager() {
1155   DCHECK(!created_profile_manager_ && !profile_manager_);
1156   created_profile_manager_ = true;
1157
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);
1161 }
1162
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);
1169 #endif
1170
1171   battery_metrics_ = std::make_unique<BatteryMetrics>();
1172
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);
1179       }));
1180   content::OnBrowserVisibilityChanged(
1181       base::android::ApplicationStatusListener::HasVisibleActivities());
1182 #endif  // BUILDFLAG(IS_ANDROID)
1183
1184   secure_origin_prefs_observer_ =
1185       std::make_unique<SecureOriginPrefsObserver>(local_state());
1186   site_isolation_prefs_observer_ =
1187       std::make_unique<SiteIsolationPrefsObserver>(local_state());
1188
1189   // Create SystemNetworkContextManager without a NetworkService if it has not
1190   // been requested yet.
1191   if (!SystemNetworkContextManager::HasInstance())
1192     SystemNetworkContextManager::CreateInstance(local_state());
1193 }
1194
1195 void BrowserProcessImpl::PreMainMessageLoopRun() {
1196   TRACE_EVENT0("startup", "BrowserProcessImpl::PreMainMessageLoopRun");
1197   SCOPED_UMA_HISTOGRAM_TIMER(
1198       "Startup.BrowserProcessImpl_PreMainMessageLoopRunTime");
1199
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(
1207       local_state(),
1208       system_network_context_manager()->GetSharedURLLoaderFactory());
1209
1210   if (local_state_->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled))
1211     ApplyDefaultBrowserPolicy();
1212
1213   ApplyMetricsReportingPolicy();
1214
1215 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
1216 #if defined(EWK_BRINGUP) && !BUILDFLAG(IS_TIZEN)  // FIXME: m108 bringup
1217   ChromeJsErrorReportProcessor::Create();
1218 #endif
1219 #endif
1220
1221 #if BUILDFLAG(ENABLE_PLUGINS)
1222   content::PluginService::GetInstance()->SetFilter(
1223       ChromePluginServiceFilter::GetInstance());
1224 #endif  // BUILDFLAG(ENABLE_PLUGINS)
1225
1226 #if !BUILDFLAG(IS_ANDROID)
1227   storage_monitor::StorageMonitor::Create();
1228 #endif
1229
1230   platform_part_->PreMainMessageLoopRun();
1231
1232   CreateNetworkTimeTracker();
1233
1234   CreateNetworkQualityObserver();
1235
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());
1240 #endif
1241
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)
1246
1247 #if BUILDFLAG(IS_CHROMEOS_ASH)
1248   soda_installer_impl_ = std::make_unique<speech::SodaInstallerImplChromeOS>();
1249 #endif  // BUILDFLAG(IS_CHROMEOS_ASH)
1250
1251 #if BUILDFLAG(ENABLE_SCREEN_AI_SERVICE)
1252   screen_ai_download_ = screen_ai::ScreenAIInstallState::Create();
1253 #endif
1254
1255   base::FilePath user_data_dir;
1256   bool result = base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
1257   DCHECK(result);
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();
1262
1263     application_breadcrumbs_logger_ =
1264         std::make_unique<breadcrumbs::ApplicationBreadcrumbsLogger>(
1265             user_data_dir, base::BindRepeating([] {
1266               return ChromeMetricsServiceAccessor::
1267                   IsMetricsAndCrashReportingEnabled();
1268             }));
1269   } else {
1270     breadcrumbs::DeleteBreadcrumbFiles(user_data_dir);
1271   }
1272
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
1276   // is added.
1277   os_crypt_async_ = std::make_unique<os_crypt_async::OSCryptAsync>(
1278       std::vector<
1279           std::pair<size_t, std::unique_ptr<os_crypt_async::KeyProvider>>>());
1280
1281   // Trigger async initialization of OSCrypt key providers.
1282   std::ignore = os_crypt_async_->GetInstance(base::DoNothing());
1283 }
1284
1285 void BrowserProcessImpl::CreateIconManager() {
1286   DCHECK(!created_icon_manager_ && !icon_manager_);
1287   created_icon_manager_ = true;
1288   icon_manager_ = std::make_unique<IconManager>();
1289 }
1290
1291 void BrowserProcessImpl::CreateNotificationPlatformBridge() {
1292 #if BUILDFLAG(ENABLE_SYSTEM_NOTIFICATIONS)
1293   DCHECK(!notification_bridge_);
1294   notification_bridge_ = NotificationPlatformBridge::Create();
1295   created_notification_bridge_ = true;
1296 #endif
1297 }
1298
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_;
1304 #endif
1305 }
1306
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());
1313 #endif
1314 }
1315
1316 void BrowserProcessImpl::CreateStatusTray() {
1317   DCHECK(!status_tray_);
1318   status_tray_ = StatusTray::Create();
1319 }
1320
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>();
1326 #else
1327   NOTIMPLEMENTED();
1328 #endif
1329 }
1330
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>();
1336 #else
1337   NOTIMPLEMENTED();
1338 #endif
1339 }
1340
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;
1346
1347   // The factory can be overridden in tests.
1348   if (!safe_browsing::SafeBrowsingServiceInterface::HasFactory()) {
1349     safe_browsing::SafeBrowsingServiceInterface::RegisterFactory(
1350         safe_browsing::GetSafeBrowsingServiceFactory());
1351   }
1352
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();
1359 }
1360
1361 void BrowserProcessImpl::CreateSubresourceFilterRulesetService() {
1362   DCHECK(!subresource_filter_ruleset_service_);
1363   created_subresource_filter_ruleset_service_ = true;
1364
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);
1369 }
1370
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_);
1378
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}));
1385
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);
1394 }
1395 #endif  // !BUILDFLAG(IS_ANDROID)
1396
1397 void BrowserProcessImpl::CreateNetworkTimeTracker() {
1398   if (network_time_tracker_) {
1399     return;
1400   }
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());
1405 }
1406
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());
1419   }
1420 }
1421
1422 void BrowserProcessImpl::Pin() {
1423   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1424   CHECK(!IsShuttingDown());
1425 }
1426
1427 void BrowserProcessImpl::Unpin() {
1428   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1429
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.
1435   if (!quit_closure_)
1436     return;
1437 #endif
1438
1439   DCHECK(!shutting_down_);
1440   shutting_down_ = true;
1441
1442 #if !BUILDFLAG(IS_ANDROID)
1443   KeepAliveRegistry::GetInstance()->SetIsShuttingDown();
1444 #endif  // !BUILDFLAG(IS_ANDROID)
1445
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();
1451 #endif
1452
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();
1459 #endif
1460
1461   CHECK(base::RunLoop::IsRunningOnCurrentThread());
1462
1463 #if BUILDFLAG(IS_MAC)
1464   base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
1465       FROM_HERE,
1466       base::BindOnce(ChromeBrowserMainPartsMac::DidEndMainMessageLoop));
1467 #endif
1468
1469 #if !BUILDFLAG(IS_ANDROID)
1470   std::move(quit_closure_).Run();
1471
1472   chrome::ShutdownIfNeeded();
1473
1474   // TODO(crbug.com/967603): remove when root cause is found.
1475   CHECK_EQ(BrowserList::GetInstance()->size(), 0u);
1476 #endif  // !BUILDFLAG(IS_ANDROID)
1477 }
1478
1479 // Mac is currently not supported.
1480 // TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is
1481 // complete.
1482 #if BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
1483
1484 bool BrowserProcessImpl::IsRunningInBackground() const {
1485   // Check if browser is in the background.
1486   return chrome::GetTotalBrowserCount() == 0 &&
1487          KeepAliveRegistry::GetInstance()->IsKeepingAlive();
1488 }
1489
1490 void BrowserProcessImpl::RestartBackgroundInstance() {
1491   base::CommandLine* old_cl = base::CommandLine::ForCurrentProcess();
1492   auto new_cl = std::make_unique<base::CommandLine>(old_cl->GetProgram());
1493
1494   base::CommandLine::SwitchMap switches = old_cl->GetSwitches();
1495   switches::RemoveSwitchesForAutostart(&switches);
1496
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);
1504     else
1505       new_cl->AppendSwitchNative(switch_name, switch_value);
1506   }
1507
1508   // Switches to add when auto-restarting Chrome.
1509   static constexpr const char* kSwitchesToAddOnAutorestart[] = {
1510       switches::kNoStartupWindow};
1511
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);
1516   }
1517
1518 #if BUILDFLAG(IS_WIN)
1519   new_cl->AppendArg(switches::kPrefetchArgumentBrowserBackground);
1520 #endif  // BUILDFLAG(IS_WIN)
1521
1522   DLOG(WARNING) << "Shutting down current instance of the browser.";
1523   chrome::AttemptExit();
1524
1525   upgrade_util::SetNewCommandLine(std::move(new_cl));
1526 }
1527
1528 void BrowserProcessImpl::OnAutoupdateTimer() {
1529   if (IsRunningInBackground()) {
1530     // upgrade_util::IsUpdatePendingRestart touches the disk, so do it on a
1531     // suitable thread.
1532     base::ThreadPool::PostTaskAndReplyWithResult(
1533         FROM_HERE,
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)));
1539   }
1540 }
1541
1542 void BrowserProcessImpl::OnPendingRestartResult(
1543     bool is_update_pending_restart) {
1544   // Make sure that the browser is still in the background after returning from
1545   // the check.
1546   if (is_update_pending_restart && IsRunningInBackground()) {
1547     DLOG(WARNING) << "Detected update.  Restarting browser.";
1548     RestartBackgroundInstance();
1549   }
1550 }
1551 #endif  // BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_LINUX) ||
1552         // BUILDFLAG(IS_CHROMEOS_LACROS))