[M85 Dev][EFL] Fix errors to generate ninja files
[platform/framework/web/chromium-efl.git] / chrome / browser / browser_process_impl.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "chrome/browser/browser_process_impl.h"
6
7 #include <stddef.h>
8
9 #include <algorithm>
10 #include <map>
11 #include <utility>
12 #include <vector>
13
14 #include "base/atomic_ref_count.h"
15 #include "base/bind.h"
16 #include "base/bind_helpers.h"
17 #include "base/command_line.h"
18 #include "base/debug/leak_annotations.h"
19 #include "base/files/file_path.h"
20 #include "base/location.h"
21 #include "base/macros.h"
22 #include "base/memory/ptr_util.h"
23 #include "base/metrics/histogram_macros.h"
24 #include "base/path_service.h"
25 #include "base/run_loop.h"
26 #include "base/single_thread_task_runner.h"
27 #include "base/synchronization/waitable_event.h"
28 #include "base/task/task_traits.h"
29 #include "base/task/thread_pool.h"
30 #include "base/threading/thread.h"
31 #include "base/threading/thread_restrictions.h"
32 #include "base/threading/thread_task_runner_handle.h"
33 #include "base/time/default_clock.h"
34 #include "base/time/default_tick_clock.h"
35 #include "base/trace_event/trace_event.h"
36 #include "build/build_config.h"
37 #include "chrome/browser/battery/battery_metrics.h"
38 #include "chrome/browser/browser_process_platform_part.h"
39 #include "chrome/browser/chrome_browser_main.h"
40 #include "chrome/browser/chrome_content_browser_client.h"
41 #include "chrome/browser/chrome_notification_types.h"
42 #include "chrome/browser/component_updater/chrome_component_updater_configurator.h"
43 #include "chrome/browser/defaults.h"
44 #include "chrome/browser/devtools/devtools_auto_opener.h"
45 #include "chrome/browser/devtools/remote_debugging_server.h"
46 #include "chrome/browser/download/download_request_limiter.h"
47 #include "chrome/browser/download/download_status_updater.h"
48 #include "chrome/browser/gpu/gpu_mode_manager.h"
49 #include "chrome/browser/icon_manager.h"
50 #include "chrome/browser/intranet_redirect_detector.h"
51 #include "chrome/browser/lifetime/application_lifetime.h"
52 #include "chrome/browser/lifetime/browser_shutdown.h"
53 #include "chrome/browser/lifetime/switch_utils.h"
54 #include "chrome/browser/media/webrtc/webrtc_event_log_manager.h"
55 #include "chrome/browser/media/webrtc/webrtc_log_uploader.h"
56 #include "chrome/browser/metrics/chrome_feature_list_creator.h"
57 #include "chrome/browser/metrics/chrome_metrics_services_manager_client.h"
58 #include "chrome/browser/metrics/metrics_reporting_state.h"
59 #include "chrome/browser/metrics/thread_watcher.h"
60 #include "chrome/browser/net/system_network_context_manager.h"
61 #include "chrome/browser/notifications/notification_platform_bridge.h"
62 #include "chrome/browser/notifications/system_notification_helper.h"
63 #include "chrome/browser/permissions/chrome_permissions_client.h"
64 #include "chrome/browser/policy/chrome_browser_policy_connector.h"
65 #include "chrome/browser/prefs/browser_prefs.h"
66 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
67 #include "chrome/browser/printing/background_printing_manager.h"
68 #include "chrome/browser/printing/print_job_manager.h"
69 #include "chrome/browser/printing/print_preview_dialog_controller.h"
70 #include "chrome/browser/profiles/profile_manager.h"
71 #include "chrome/browser/resource_coordinator/resource_coordinator_parts.h"
72 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
73 #include "chrome/browser/shell_integration.h"
74 #include "chrome/browser/site_isolation/prefs_observer.h"
75 #include "chrome/browser/ssl/secure_origin_prefs_observer.h"
76 #include "chrome/browser/startup_data.h"
77 #include "chrome/browser/status_icons/status_tray.h"
78 #include "chrome/browser/ui/browser_dialogs.h"
79 #include "chrome/browser/ui/browser_list.h"
80 #include "chrome/browser/update_client/chrome_update_query_params_delegate.h"
81 #include "chrome/common/buildflags.h"
82 #include "chrome/common/channel_info.h"
83 #include "chrome/common/chrome_constants.h"
84 #include "chrome/common/chrome_features.h"
85 #include "chrome/common/chrome_paths.h"
86 #include "chrome/common/chrome_switches.h"
87 #include "chrome/common/extensions/chrome_extensions_client.h"
88 #include "chrome/common/pref_names.h"
89 #include "chrome/common/url_constants.h"
90 #include "chrome/grit/chromium_strings.h"
91 #include "chrome/installer/util/google_update_settings.h"
92 #include "components/component_updater/component_updater_service.h"
93 #include "components/component_updater/timer_update_scheduler.h"
94 #include "components/crash/core/common/crash_key.h"
95 #include "components/federated_learning/floc_blocklist_service.h"
96 #include "components/federated_learning/floc_constants.h"
97 #include "components/gcm_driver/gcm_driver.h"
98 #include "components/language/core/browser/pref_names.h"
99 #include "components/metrics/metrics_pref_names.h"
100 #include "components/metrics/metrics_service.h"
101 #include "components/metrics_services_manager/metrics_services_manager.h"
102 #include "components/metrics_services_manager/metrics_services_manager_client.h"
103 #include "components/network_time/network_time_tracker.h"
104 #include "components/optimization_guide/optimization_guide_features.h"
105 #include "components/optimization_guide/optimization_guide_service.h"
106 #include "components/permissions/permissions_client.h"
107 #include "components/policy/core/common/policy_service.h"
108 #include "components/prefs/json_pref_store.h"
109 #include "components/prefs/pref_registry_simple.h"
110 #include "components/prefs/pref_service.h"
111 #include "components/rappor/public/rappor_utils.h"
112 #include "components/rappor/rappor_service_impl.h"
113 #include "components/safe_browsing/core/safe_browsing_service_interface.h"
114 #include "components/sessions/core/session_id_generator.h"
115 #include "components/subresource_filter/content/browser/ruleset_service.h"
116 #include "components/subresource_filter/core/browser/subresource_filter_constants.h"
117 #include "components/subresource_filter/core/browser/subresource_filter_features.h"
118 #include "components/translate/core/browser/translate_download_manager.h"
119 #include "components/ukm/ukm_service.h"
120 #include "components/update_client/update_query_params.h"
121 #include "components/variations/service/variations_service.h"
122 #include "components/web_resource/web_resource_pref_names.h"
123 #include "content/public/browser/browser_task_traits.h"
124 #include "content/public/browser/browser_thread.h"
125 #include "content/public/browser/child_process_security_policy.h"
126 #include "content/public/browser/network_quality_observer_factory.h"
127 #include "content/public/browser/network_service_instance.h"
128 #include "content/public/browser/notification_details.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_features.h"
133 #include "content/public/common/content_switches.h"
134 #include "content/public/common/network_service_util.h"
135 #include "extensions/buildflags/buildflags.h"
136 #include "extensions/common/constants.h"
137 #include "media/media_buildflags.h"
138 #include "mojo/public/cpp/bindings/pending_receiver.h"
139 #include "net/log/net_log.h"
140 #include "ppapi/buildflags/buildflags.h"
141 #include "printing/buildflags/buildflags.h"
142 #include "services/network/public/cpp/features.h"
143 #include "services/network/public/cpp/network_switches.h"
144 #include "ui/base/idle/idle.h"
145 #include "ui/base/l10n/l10n_util.h"
146 #include "ui/base/ui_base_features.h"
147
148 #if defined(OS_WIN)
149 #include "base/win/windows_version.h"
150 #elif defined(OS_MACOSX)
151 #include "chrome/browser/chrome_browser_main_mac.h"
152 #include "chrome/browser/media/webrtc/system_media_capture_permissions_stats_mac.h"
153 #endif
154
155 #if !defined(OS_CHROMEOS)
156 #include "ui/message_center/message_center.h"
157 #endif
158
159 #if defined(OS_ANDROID)
160 #include "chrome/browser/android/component_updater/background_task_update_scheduler.h"
161 #include "chrome/browser/flags/android/chrome_feature_list.h"
162 #include "chrome/browser/ssl/chrome_security_state_client.h"
163 #else
164 #include "chrome/browser/gcm/gcm_product_util.h"
165 #include "chrome/browser/resource_coordinator/tab_manager.h"
166 #include "chrome/browser/ui/browser_finder.h"
167 #include "components/gcm_driver/gcm_client_factory.h"
168 #include "components/gcm_driver/gcm_desktop_utils.h"
169 #include "components/keep_alive_registry/keep_alive_registry.h"
170 #endif
171
172 #if BUILDFLAG(ENABLE_BACKGROUND_MODE)
173 #include "chrome/browser/background/background_mode_manager.h"
174 #endif
175
176 #if BUILDFLAG(ENABLE_EXTENSIONS)
177 #include "chrome/browser/apps/platform_apps/chrome_apps_browser_api_provider.h"
178 #include "chrome/browser/extensions/chrome_extensions_browser_client.h"
179 #include "chrome/browser/extensions/event_router_forwarder.h"
180 #include "chrome/browser/media_galleries/media_file_system_registry.h"
181 #include "chrome/browser/ui/apps/chrome_app_window_client.h"
182 #include "chrome/common/initialize_extensions_client.h"
183 #include "components/storage_monitor/storage_monitor.h"
184 #include "extensions/common/extension_l10n_util.h"
185 #endif
186
187 #if BUILDFLAG(ENABLE_PLUGINS)
188 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
189 #include "chrome/browser/plugins/plugin_finder.h"
190 #include "chrome/browser/plugins/plugins_resource_service.h"
191 #include "content/public/browser/plugin_service.h"
192 #endif
193
194 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
195 #include "chrome/browser/first_run/upgrade_util.h"
196 #include "chrome/browser/notifications/notification_ui_manager.h"
197 #include "chrome/browser/policy/chrome_browser_cloud_management_controller.h"
198 #include "chrome/browser/ui/user_manager.h"
199 #endif
200
201 #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
202 #include "chrome/browser/component_updater/supervised_user_whitelist_installer.h"
203 #endif
204
205 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
206 // How often to check if the persistent instance of Chrome needs to restart
207 // to install an update.
208 static const int kUpdateCheckIntervalHours = 6;
209 #endif
210
211 #if defined(USE_X11) || defined(OS_WIN) || defined(USE_OZONE)
212 // How long to wait for the File thread to complete during EndSession, on Linux
213 // and Windows. We have a timeout here because we're unable to run the UI
214 // messageloop and there's some deadlock risk. Our only option is to exit
215 // anyway.
216 static constexpr base::TimeDelta kEndSessionTimeout =
217     base::TimeDelta::FromSeconds(10);
218 #endif
219
220 using content::BrowserThread;
221 using content::ChildProcessSecurityPolicy;
222
223 rappor::RapporService* GetBrowserRapporService() {
224   if (g_browser_process != nullptr)
225     return g_browser_process->rappor_service();
226   return nullptr;
227 }
228
229 BrowserProcessImpl::BrowserProcessImpl(StartupData* startup_data) {
230   g_browser_process = this;
231
232   DCHECK(startup_data);
233   startup_data_ = startup_data;
234
235   chrome_feature_list_creator_ = startup_data->chrome_feature_list_creator();
236   browser_policy_connector_ =
237       chrome_feature_list_creator_->TakeChromeBrowserPolicyConnector();
238   created_browser_policy_connector_ = true;
239
240   platform_part_ = std::make_unique<BrowserProcessPlatformPart>();
241   // Most work should be done in Init().
242 }
243
244 void BrowserProcessImpl::Init() {
245   if (content::IsOutOfProcessNetworkService()) {
246     // Initialize NetLog source IDs to use an alternate starting value for
247     // the browser process. This needs to be done early in process startup
248     // before any NetLogSource objects might get created.
249     net::NetLog::Get()->InitializeSourceIdPartition();
250   }
251
252 #if defined(OS_CHROMEOS)
253   // Forces creation of |metrics_services_manager_client_| if necessary
254   // (typically this call is a no-op as MetricsServicesManager has already been
255   // created).
256   GetMetricsServicesManager();
257   DCHECK(metrics_services_manager_client_);
258   metrics_services_manager_client_->OnCrosSettingsCreated();
259 #endif
260
261   download_status_updater_ = std::make_unique<DownloadStatusUpdater>();
262
263   rappor::SetDefaultServiceAccessor(&GetBrowserRapporService);
264
265 #if BUILDFLAG(ENABLE_PRINTING)
266   // Must be created after the NotificationService.
267   print_job_manager_ = std::make_unique<printing::PrintJobManager>();
268 #endif
269
270   ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
271       chrome::kChromeSearchScheme);
272
273 #if defined(OS_MACOSX)
274   ui::InitIdleMonitor();
275 #endif
276
277 #if BUILDFLAG(ENABLE_EXTENSIONS)
278   extensions::AppWindowClient::Set(ChromeAppWindowClient::GetInstance());
279
280   extension_event_router_forwarder_ =
281       base::MakeRefCounted<extensions::EventRouterForwarder>();
282
283   EnsureExtensionsClientInitialized();
284
285   extensions_browser_client_ =
286       std::make_unique<extensions::ChromeExtensionsBrowserClient>();
287   extensions_browser_client_->AddAPIProvider(
288       std::make_unique<chrome_apps::ChromeAppsBrowserAPIProvider>());
289   extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get());
290 #endif
291
292 #if !defined(OS_CHROMEOS)
293   message_center::MessageCenter::Initialize();
294   // Set the system notification source display name ("Google Chrome" or
295   // "Chromium").
296   if (message_center::MessageCenter::Get()) {
297     message_center::MessageCenter::Get()->SetSystemNotificationAppName(
298         l10n_util::GetStringUTF16(IDS_PRODUCT_NAME));
299   }
300 #endif
301
302   system_notification_helper_ = std::make_unique<SystemNotificationHelper>();
303
304   update_client::UpdateQueryParams::SetDelegate(
305       ChromeUpdateQueryParamsDelegate::GetInstance());
306
307   // Make sure permissions client has been set.
308   ChromePermissionsClient::GetInstance();
309
310 #if !defined(OS_ANDROID)
311   KeepAliveRegistry::GetInstance()->SetIsShuttingDown(false);
312   KeepAliveRegistry::GetInstance()->AddObserver(this);
313 #endif  // !defined(OS_ANDROID)
314
315   MigrateObsoleteLocalStatePrefs(local_state());
316   pref_change_registrar_.Init(local_state());
317
318   // Initialize the notification for the default browser setting policy.
319   pref_change_registrar_.Add(
320       prefs::kDefaultBrowserSettingEnabled,
321       base::Bind(&BrowserProcessImpl::ApplyDefaultBrowserPolicy,
322                  base::Unretained(this)));
323
324 #if !defined(OS_ANDROID)
325   // This preference must be kept in sync with external values; update them
326   // whenever the preference or its controlling policy changes.
327   pref_change_registrar_.Add(metrics::prefs::kMetricsReportingEnabled,
328                              base::Bind(&ApplyMetricsReportingPolicy));
329 #endif
330
331   DCHECK(!webrtc_event_log_manager_);
332   webrtc_event_log_manager_ = WebRtcEventLogManager::CreateSingletonInstance();
333
334 #if defined(OS_MACOSX)
335   system_media_permissions::LogSystemMediaPermissionsStartupStats();
336 #endif
337 }
338
339 #if !defined(OS_ANDROID)
340 void BrowserProcessImpl::SetQuitClosure(base::OnceClosure quit_closure) {
341   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
342   DCHECK(quit_closure);
343   DCHECK(!quit_closure_);
344   quit_closure_ = std::move(quit_closure);
345 }
346 #endif
347
348 #if defined(OS_MACOSX)
349 void BrowserProcessImpl::ClearQuitClosure() {
350   quit_closure_.Reset();
351 }
352 #endif
353
354 BrowserProcessImpl::~BrowserProcessImpl() {
355   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
356 #if BUILDFLAG(ENABLE_EXTENSIONS)
357   extensions::ExtensionsBrowserClient::Set(nullptr);
358   extensions::AppWindowClient::Set(nullptr);
359 #endif
360
361 #if !defined(OS_ANDROID)
362   KeepAliveRegistry::GetInstance()->RemoveObserver(this);
363 #endif
364
365   g_browser_process = NULL;
366 }
367
368 #if !defined(OS_ANDROID)
369 void BrowserProcessImpl::StartTearDown() {
370   TRACE_EVENT0("shutdown", "BrowserProcessImpl::StartTearDown");
371   // TODO(crbug.com/560486): Fix the tests that make the check of
372   // |tearing_down_| necessary in IsShuttingDown().
373   tearing_down_ = true;
374   DCHECK(IsShuttingDown());
375
376   metrics_services_manager_.reset();
377   intranet_redirect_detector_.reset();
378   if (safe_browsing_service_.get())
379     safe_browsing_service()->ShutDown();
380   network_time_tracker_.reset();
381 #if BUILDFLAG(ENABLE_PLUGINS)
382   plugins_resource_service_.reset();
383 #endif
384
385 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
386   // Initial cleanup for ChromeBrowserCloudManagement, shutdown components that
387   // depend on profile and notification system. For example, ProfileManager
388   // observer and KeyServices observer need to be removed before profiles.
389   if (browser_policy_connector_ &&
390       browser_policy_connector_->chrome_browser_cloud_management_controller()) {
391     browser_policy_connector_->chrome_browser_cloud_management_controller()
392         ->ShutDown();
393   }
394 #endif
395
396   system_notification_helper_.reset();
397
398 #if !defined(OS_CHROMEOS)
399   // Need to clear the desktop notification balloons before the IO thread and
400   // before the profiles, since if there are any still showing we will access
401   // those things during teardown.
402   notification_ui_manager_.reset();
403 #endif
404
405 #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
406   // The SupervisedUserWhitelistInstaller observes the ProfileAttributesStorage,
407   // so it needs to be shut down before the ProfileManager.
408   supervised_user_whitelist_installer_.reset();
409 #endif
410
411   // Debugger must be cleaned up before ProfileManager.
412   remote_debugging_server_.reset();
413   devtools_auto_opener_.reset();
414
415   battery_metrics_.reset();
416
417   // Need to clear profiles (download managers) before the IO thread.
418   {
419     TRACE_EVENT0("shutdown",
420                  "BrowserProcessImpl::StartTearDown:ProfileManager");
421 #if !defined(OS_CHROMEOS)
422     // The desktop User Manager needs to be closed before the guest profile
423     // can be destroyed.
424     UserManager::Hide();
425 #endif  // !defined(OS_CHROMEOS)
426     profile_manager_.reset();
427   }
428
429 #if BUILDFLAG(ENABLE_EXTENSIONS)
430   media_file_system_registry_.reset();
431   // Remove the global instance of the Storage Monitor now. Otherwise the
432   // FILE thread would be gone when we try to release it in the dtor and
433   // Valgrind would report a leak on almost every single browser_test.
434   // TODO(gbillock): Make this unnecessary.
435   storage_monitor::StorageMonitor::Destroy();
436 #endif
437
438 #if !defined(OS_CHROMEOS)
439   if (message_center::MessageCenter::Get())
440     message_center::MessageCenter::Shutdown();
441 #endif
442
443   // The policy providers managed by |browser_policy_connector_| need to shut
444   // down while the IO and FILE threads are still alive. The monitoring
445   // framework owned by |browser_policy_connector_| relies on |gcm_driver_|, so
446   // this must be shutdown before |gcm_driver_| below.
447   if (browser_policy_connector_)
448     browser_policy_connector_->Shutdown();
449
450   // The |gcm_driver_| must shut down while the IO thread is still alive.
451   if (gcm_driver_)
452     gcm_driver_->Shutdown();
453
454   // Stop the watchdog thread before stopping other threads.
455   watchdog_thread_.reset();
456
457   platform_part()->StartTearDown();
458
459   // Cancel any uploads to release the system url request context references.
460   if (webrtc_log_uploader_)
461     webrtc_log_uploader_->Shutdown();
462
463   sessions::SessionIdGenerator::GetInstance()->Shutdown();
464
465   if (local_state_)
466     local_state_->CommitPendingWrite();
467
468   // This expects to be destroyed before the task scheduler is torn down.
469   SystemNetworkContextManager::DeleteInstance();
470 }
471
472 void BrowserProcessImpl::PostDestroyThreads() {
473   // With the file_thread_ flushed, we can release any icon resources.
474   icon_manager_.reset();
475
476   // Must outlive the worker threads.
477   webrtc_log_uploader_.reset();
478 }
479 #endif  // !defined(OS_ANDROID)
480
481 void BrowserProcessImpl::SetMetricsServices(
482     std::unique_ptr<metrics_services_manager::MetricsServicesManager> manager,
483     metrics_services_manager::MetricsServicesManagerClient* client) {
484   metrics_services_manager_ = std::move(manager);
485   metrics_services_manager_client_ =
486       static_cast<ChromeMetricsServicesManagerClient*>(client);
487 }
488
489 namespace {
490
491 // Used at the end of session to block the UI thread for completion of sentinel
492 // tasks on the set of threads used to persist profile data and local state.
493 // This is done to ensure that the data has been persisted to disk before
494 // continuing.
495 class RundownTaskCounter :
496     public base::RefCountedThreadSafe<RundownTaskCounter> {
497  public:
498   RundownTaskCounter();
499
500   // Increments |count_| and returns a closure bound to Decrement(). All
501   // closures returned by this RundownTaskCounter's GetRundownClosure() method
502   // must be invoked for TimedWait() to complete its wait without timing
503   // out.
504   base::OnceClosure GetRundownClosure();
505
506   // Waits until the count is zero or |timeout| expires.
507   // This can only be called once per instance.
508   void TimedWait(base::TimeDelta timeout);
509
510  private:
511   friend class base::RefCountedThreadSafe<RundownTaskCounter>;
512   ~RundownTaskCounter() {}
513
514   // Decrements the counter and releases the waitable event on transition to
515   // zero.
516   void Decrement();
517
518   // The count starts at one to defer the possibility of one->zero transitions
519   // until TimedWait is called.
520   base::AtomicRefCount count_{1};
521   base::WaitableEvent waitable_event_;
522
523   DISALLOW_COPY_AND_ASSIGN(RundownTaskCounter);
524 };
525
526 RundownTaskCounter::RundownTaskCounter() = default;
527
528 base::OnceClosure RundownTaskCounter::GetRundownClosure() {
529   // As the count starts off at one, it should never get to zero unless
530   // TimedWait has been called.
531   DCHECK(!count_.IsZero());
532
533   count_.Increment();
534
535   return base::BindOnce(&RundownTaskCounter::Decrement, this);
536 }
537
538 void RundownTaskCounter::Decrement() {
539   if (!count_.Decrement())
540     waitable_event_.Signal();
541 }
542
543 void RundownTaskCounter::TimedWait(base::TimeDelta timeout) {
544   // Decrement the excess count from the constructor.
545   Decrement();
546
547   // RundownTaskCounter::TimedWait() could return
548   // |waitable_event_.TimedWait()|'s result if any user ever cared about whether
549   // it returned per success or timeout. Currently no user of this API cares and
550   // as such this return value is ignored.
551   waitable_event_.TimedWait(timeout);
552 }
553
554 #if !defined(OS_ANDROID)
555 void RequestProxyResolvingSocketFactoryOnUIThread(
556     mojo::PendingReceiver<network::mojom::ProxyResolvingSocketFactory>
557         receiver) {
558   network::mojom::NetworkContext* network_context =
559       g_browser_process->system_network_context_manager()->GetContext();
560   network_context->CreateProxyResolvingSocketFactory(std::move(receiver));
561 }
562
563 void RequestProxyResolvingSocketFactory(
564     mojo::PendingReceiver<network::mojom::ProxyResolvingSocketFactory>
565         receiver) {
566   content::GetUIThreadTaskRunner({})->PostTask(
567       FROM_HERE, base::BindOnce(&RequestProxyResolvingSocketFactoryOnUIThread,
568                                 std::move(receiver)));
569 }
570 #endif
571
572 }  // namespace
573
574 void BrowserProcessImpl::FlushLocalStateAndReply(base::OnceClosure reply) {
575   if (local_state_) {
576     local_state_->CommitPendingWrite(std::move(reply));
577     return;
578   }
579   base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(reply));
580 }
581
582 void BrowserProcessImpl::EndSession() {
583   // Mark all the profiles as clean.
584   ProfileManager* pm = profile_manager();
585   std::vector<Profile*> profiles(pm->GetLoadedProfiles());
586   scoped_refptr<RundownTaskCounter> rundown_counter =
587       base::MakeRefCounted<RundownTaskCounter>();
588   for (size_t i = 0; i < profiles.size(); ++i) {
589     Profile* profile = profiles[i];
590     profile->SetExitType(Profile::EXIT_SESSION_ENDED);
591     if (profile->GetPrefs()) {
592       profile->GetPrefs()->CommitPendingWrite(
593           base::OnceClosure(), rundown_counter->GetRundownClosure());
594     }
595   }
596
597   // Tell the metrics service it was cleanly shutdown.
598   metrics::MetricsService* metrics = g_browser_process->metrics_service();
599   if (metrics && local_state_) {
600     metrics->RecordStartOfSessionEnd();
601 #if !defined(OS_CHROMEOS)
602     // MetricsService lazily writes to prefs, force it to write now.
603     // On ChromeOS, chrome gets killed when hangs, so no need to
604     // commit metrics::prefs::kStabilitySessionEndCompleted change immediately.
605     local_state_->CommitPendingWrite(base::OnceClosure(),
606                                      rundown_counter->GetRundownClosure());
607 #endif
608   }
609
610   // This wait is legitimate and necessary on Windows, since the process will
611   // be terminated soon.
612   // http://crbug.com/125207
613   base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_wait;
614
615   // We must write that the profile and metrics service shutdown cleanly,
616   // otherwise on startup we'll think we crashed. So we block until done and
617   // then proceed with normal shutdown.
618   //
619   // If you change the condition here, be sure to also change
620   // ProfileBrowserTests to match.
621 #if defined(USE_X11) || defined(OS_WIN) || defined(USE_OZONE)
622   // Do a best-effort wait on the successful countdown of rundown tasks. Note
623   // that if we don't complete "quickly enough", Windows will terminate our
624   // process.
625   //
626   // On Windows, we previously posted a message to FILE and then ran a nested
627   // message loop, waiting for that message to be processed until quitting.
628   // However, doing so means that other messages will also be processed. In
629   // particular, if the GPU process host notices that the GPU has been killed
630   // during shutdown, it races exiting the nested loop with the process host
631   // blocking the message loop attempting to re-establish a connection to the
632   // GPU process synchronously. Because the system may not be allowing
633   // processes to launch, this can result in a hang. See
634   // http://crbug.com/318527.
635   rundown_counter->TimedWait(kEndSessionTimeout);
636 #else
637   NOTIMPLEMENTED();
638 #endif
639 }
640
641 metrics_services_manager::MetricsServicesManager*
642 BrowserProcessImpl::GetMetricsServicesManager() {
643   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
644   if (!metrics_services_manager_) {
645     auto client =
646         std::make_unique<ChromeMetricsServicesManagerClient>(local_state());
647     metrics_services_manager_client_ = client.get();
648     metrics_services_manager_ =
649         std::make_unique<metrics_services_manager::MetricsServicesManager>(
650             std::move(client));
651   }
652   return metrics_services_manager_.get();
653 }
654
655 metrics::MetricsService* BrowserProcessImpl::metrics_service() {
656   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
657   return GetMetricsServicesManager()->GetMetricsService();
658 }
659
660 rappor::RapporServiceImpl* BrowserProcessImpl::rappor_service() {
661   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
662   return GetMetricsServicesManager()->GetRapporServiceImpl();
663 }
664
665 SystemNetworkContextManager*
666 BrowserProcessImpl::system_network_context_manager() {
667   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
668   DCHECK(SystemNetworkContextManager::GetInstance());
669   return SystemNetworkContextManager::GetInstance();
670 }
671
672 scoped_refptr<network::SharedURLLoaderFactory>
673 BrowserProcessImpl::shared_url_loader_factory() {
674   return system_network_context_manager()->GetSharedURLLoaderFactory();
675 }
676
677 network::NetworkQualityTracker* BrowserProcessImpl::network_quality_tracker() {
678   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
679   if (!network_quality_tracker_) {
680     network_quality_tracker_ = std::make_unique<network::NetworkQualityTracker>(
681         base::BindRepeating(&content::GetNetworkService));
682   }
683   return network_quality_tracker_.get();
684 }
685
686 WatchDogThread* BrowserProcessImpl::watchdog_thread() {
687   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
688   if (!created_watchdog_thread_)
689     CreateWatchdogThread();
690   DCHECK(watchdog_thread_.get() != NULL);
691   return watchdog_thread_.get();
692 }
693
694 ProfileManager* BrowserProcessImpl::profile_manager() {
695   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
696   if (!created_profile_manager_)
697     CreateProfileManager();
698   return profile_manager_.get();
699 }
700
701 PrefService* BrowserProcessImpl::local_state() {
702   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
703   if (!local_state_)
704     CreateLocalState();
705   return local_state_.get();
706 }
707
708 variations::VariationsService* BrowserProcessImpl::variations_service() {
709   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
710   return GetMetricsServicesManager()->GetVariationsService();
711 }
712
713 BrowserProcessPlatformPart* BrowserProcessImpl::platform_part() {
714   return platform_part_.get();
715 }
716
717 extensions::EventRouterForwarder*
718 BrowserProcessImpl::extension_event_router_forwarder() {
719 #if BUILDFLAG(ENABLE_EXTENSIONS)
720   return extension_event_router_forwarder_.get();
721 #else
722   return NULL;
723 #endif
724 }
725
726 NotificationUIManager* BrowserProcessImpl::notification_ui_manager() {
727   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
728 // TODO(miguelg) return NULL for MAC as well once native notifications
729 // are enabled by default.
730 #if defined(OS_ANDROID) || defined(OS_CHROMEOS)
731   return nullptr;
732 #else
733   if (!created_notification_ui_manager_)
734     CreateNotificationUIManager();
735   return notification_ui_manager_.get();
736 #endif
737 }
738
739 NotificationPlatformBridge* BrowserProcessImpl::notification_platform_bridge() {
740 #if BUILDFLAG(ENABLE_NATIVE_NOTIFICATIONS)
741   if (!created_notification_bridge_)
742     CreateNotificationPlatformBridge();
743   return notification_bridge_.get();
744 #else
745   return nullptr;
746 #endif
747 }
748
749 policy::ChromeBrowserPolicyConnector*
750 BrowserProcessImpl::browser_policy_connector() {
751   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
752   if (!created_browser_policy_connector_) {
753     DCHECK(!browser_policy_connector_);
754     browser_policy_connector_ = platform_part_->CreateBrowserPolicyConnector();
755     created_browser_policy_connector_ = true;
756   }
757   return browser_policy_connector_.get();
758 }
759
760 policy::PolicyService* BrowserProcessImpl::policy_service() {
761   return browser_policy_connector()->GetPolicyService();
762 }
763
764 IconManager* BrowserProcessImpl::icon_manager() {
765   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
766   if (!created_icon_manager_)
767     CreateIconManager();
768   return icon_manager_.get();
769 }
770
771 GpuModeManager* BrowserProcessImpl::gpu_mode_manager() {
772   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
773   if (!gpu_mode_manager_)
774     gpu_mode_manager_ = std::make_unique<GpuModeManager>();
775   return gpu_mode_manager_.get();
776 }
777
778 void BrowserProcessImpl::CreateDevToolsProtocolHandler() {
779   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
780 #if !defined(OS_ANDROID)
781   // StartupBrowserCreator::LaunchBrowser can be run multiple times when browser
782   // is started with several profiles or existing browser process is reused.
783   if (!remote_debugging_server_) {
784     remote_debugging_server_ = std::make_unique<RemoteDebuggingServer>();
785   }
786 #endif
787 }
788
789 void BrowserProcessImpl::CreateDevToolsAutoOpener() {
790   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
791 #if !defined(OS_ANDROID)
792   // StartupBrowserCreator::LaunchBrowser can be run multiple times when browser
793   // is started with several profiles or existing browser process is reused.
794   if (!devtools_auto_opener_)
795     devtools_auto_opener_ = std::make_unique<DevToolsAutoOpener>();
796 #endif
797 }
798
799 bool BrowserProcessImpl::IsShuttingDown() {
800   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
801   // TODO(crbug.com/560486): Fix the tests that make the check of
802   // |tearing_down_| necessary here.
803   return shutting_down_ || tearing_down_;
804 }
805
806 printing::PrintJobManager* BrowserProcessImpl::print_job_manager() {
807   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
808   return print_job_manager_.get();
809 }
810
811 printing::PrintPreviewDialogController*
812     BrowserProcessImpl::print_preview_dialog_controller() {
813 #if BUILDFLAG(ENABLE_PRINT_PREVIEW)
814   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
815   if (!print_preview_dialog_controller_.get())
816     CreatePrintPreviewDialogController();
817   return print_preview_dialog_controller_.get();
818 #else
819   NOTIMPLEMENTED();
820   return NULL;
821 #endif
822 }
823
824 printing::BackgroundPrintingManager*
825     BrowserProcessImpl::background_printing_manager() {
826 #if BUILDFLAG(ENABLE_PRINT_PREVIEW)
827   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
828   if (!background_printing_manager_)
829     CreateBackgroundPrintingManager();
830   return background_printing_manager_.get();
831 #else
832   NOTIMPLEMENTED();
833   return NULL;
834 #endif
835 }
836
837 IntranetRedirectDetector* BrowserProcessImpl::intranet_redirect_detector() {
838   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
839   if (!intranet_redirect_detector_)
840     CreateIntranetRedirectDetector();
841   return intranet_redirect_detector_.get();
842 }
843
844 const std::string& BrowserProcessImpl::GetApplicationLocale() {
845 #if !defined(OS_CHROMEOS)
846   // TODO(crbug.com/1033644): Remove #if.
847   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
848 #endif
849   DCHECK(!locale_.empty());
850   return locale_;
851 }
852
853 void BrowserProcessImpl::SetApplicationLocale(
854     const std::string& actual_locale) {
855   // NOTE: this is called before any threads have been created in non-test
856   // environments.
857   locale_ = actual_locale;
858   ChromeContentBrowserClient::SetApplicationLocale(actual_locale);
859   translate::TranslateDownloadManager::GetInstance()->set_application_locale(
860       actual_locale);
861 }
862
863 DownloadStatusUpdater* BrowserProcessImpl::download_status_updater() {
864   return download_status_updater_.get();
865 }
866
867 MediaFileSystemRegistry* BrowserProcessImpl::media_file_system_registry() {
868 #if BUILDFLAG(ENABLE_EXTENSIONS)
869   if (!media_file_system_registry_)
870     media_file_system_registry_ = std::make_unique<MediaFileSystemRegistry>();
871   return media_file_system_registry_.get();
872 #else
873   return NULL;
874 #endif
875 }
876
877 WebRtcLogUploader* BrowserProcessImpl::webrtc_log_uploader() {
878   if (!webrtc_log_uploader_)
879     webrtc_log_uploader_ = std::make_unique<WebRtcLogUploader>();
880   return webrtc_log_uploader_.get();
881 }
882
883 network_time::NetworkTimeTracker* BrowserProcessImpl::network_time_tracker() {
884   if (!network_time_tracker_) {
885     network_time_tracker_ = std::make_unique<network_time::NetworkTimeTracker>(
886         base::WrapUnique(new base::DefaultClock()),
887         base::WrapUnique(new base::DefaultTickClock()), local_state(),
888         system_network_context_manager()->GetSharedURLLoaderFactory());
889   }
890   return network_time_tracker_.get();
891 }
892
893 gcm::GCMDriver* BrowserProcessImpl::gcm_driver() {
894   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
895   if (!gcm_driver_)
896     CreateGCMDriver();
897   return gcm_driver_.get();
898 }
899
900 resource_coordinator::TabManager* BrowserProcessImpl::GetTabManager() {
901   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
902   return resource_coordinator_parts()->tab_manager();
903 }
904
905 resource_coordinator::ResourceCoordinatorParts*
906 BrowserProcessImpl::resource_coordinator_parts() {
907   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
908   if (!resource_coordinator_parts_) {
909     resource_coordinator_parts_ =
910         std::make_unique<resource_coordinator::ResourceCoordinatorParts>();
911   }
912   return resource_coordinator_parts_.get();
913 }
914
915 BuildState* BrowserProcessImpl::GetBuildState() {
916 #if !defined(OS_ANDROID)
917   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
918   return &build_state_;
919 #else
920   NOTIMPLEMENTED();
921   return nullptr;
922 #endif
923 }
924
925 // static
926 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple* registry) {
927   registry->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled,
928                                 false);
929
930   registry->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt, false);
931
932 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
933   registry->RegisterBooleanPref(prefs::kEulaAccepted, false);
934 #endif  // defined(OS_CHROMEOS) || defined(OS_ANDROID)
935
936   // TODO(brettw,*): this comment about ResourceBundle was here since
937   // initial commit.  This comment seems unrelated, bit-rotten and
938   // a candidate for removal.
939   // Initialize ResourceBundle which handles files loaded from external
940   // sources. This has to be done before uninstall code path and before prefs
941   // are registered.
942   registry->RegisterStringPref(language::prefs::kApplicationLocale,
943                                std::string());
944 #if defined(OS_CHROMEOS)
945   registry->RegisterStringPref(prefs::kOwnerLocale, std::string());
946   registry->RegisterStringPref(prefs::kHardwareKeyboardLayout,
947                                std::string());
948 #endif  // defined(OS_CHROMEOS)
949
950   registry->RegisterBooleanPref(metrics::prefs::kMetricsReportingEnabled,
951                                 GoogleUpdateSettings::GetCollectStatsConsent());
952
953 #if defined(OS_ANDROID)
954   registry->RegisterBooleanPref(
955       prefs::kCrashReportingEnabled, false);
956 #endif  // defined(OS_ANDROID)
957 }
958
959 DownloadRequestLimiter* BrowserProcessImpl::download_request_limiter() {
960   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
961   if (!download_request_limiter_.get()) {
962     download_request_limiter_ = base::MakeRefCounted<DownloadRequestLimiter>();
963   }
964   return download_request_limiter_.get();
965 }
966
967 BackgroundModeManager* BrowserProcessImpl::background_mode_manager() {
968   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
969 #if BUILDFLAG(ENABLE_BACKGROUND_MODE)
970   if (!background_mode_manager_)
971     CreateBackgroundModeManager();
972   return background_mode_manager_.get();
973 #else
974   NOTIMPLEMENTED();
975   return NULL;
976 #endif
977 }
978
979 void BrowserProcessImpl::set_background_mode_manager_for_test(
980     std::unique_ptr<BackgroundModeManager> manager) {
981 #if BUILDFLAG(ENABLE_BACKGROUND_MODE)
982   background_mode_manager_ = std::move(manager);
983 #endif
984 }
985
986 StatusTray* BrowserProcessImpl::status_tray() {
987   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
988   if (!status_tray_)
989     CreateStatusTray();
990   return status_tray_.get();
991 }
992
993 safe_browsing::SafeBrowsingService*
994 BrowserProcessImpl::safe_browsing_service() {
995   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
996   if (!created_safe_browsing_service_)
997     CreateSafeBrowsingService();
998   return safe_browsing_service_.get();
999 }
1000
1001 subresource_filter::RulesetService*
1002 BrowserProcessImpl::subresource_filter_ruleset_service() {
1003   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1004   if (!created_subresource_filter_ruleset_service_)
1005     CreateSubresourceFilterRulesetService();
1006   return subresource_filter_ruleset_service_.get();
1007 }
1008
1009 federated_learning::FlocBlocklistService*
1010 BrowserProcessImpl::floc_blocklist_service() {
1011   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1012   if (!floc_blocklist_service_)
1013     CreateFlocBlocklistService();
1014   return floc_blocklist_service_.get();
1015 }
1016
1017 optimization_guide::OptimizationGuideService*
1018 BrowserProcessImpl::optimization_guide_service() {
1019   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1020   if (!created_optimization_guide_service_)
1021     CreateOptimizationGuideService();
1022   return optimization_guide_service_.get();
1023 }
1024
1025 StartupData* BrowserProcessImpl::startup_data() {
1026   return startup_data_;
1027 }
1028
1029 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
1030 void BrowserProcessImpl::StartAutoupdateTimer() {
1031   autoupdate_timer_.Start(FROM_HERE,
1032       base::TimeDelta::FromHours(kUpdateCheckIntervalHours),
1033       this,
1034       &BrowserProcessImpl::OnAutoupdateTimer);
1035 }
1036 #endif
1037
1038 component_updater::ComponentUpdateService*
1039 BrowserProcessImpl::component_updater() {
1040   if (component_updater_)
1041     return component_updater_.get();
1042
1043   if (!BrowserThread::CurrentlyOn(BrowserThread::UI))
1044     return nullptr;
1045
1046   std::unique_ptr<component_updater::UpdateScheduler> scheduler;
1047 #if defined(OS_ANDROID)
1048   if (base::FeatureList::IsEnabled(
1049           chrome::android::kBackgroundTaskComponentUpdate) &&
1050       component_updater::BackgroundTaskUpdateScheduler::IsAvailable()) {
1051     scheduler =
1052         std::make_unique<component_updater::BackgroundTaskUpdateScheduler>();
1053   }
1054 #endif
1055   if (!scheduler)
1056     scheduler = std::make_unique<component_updater::TimerUpdateScheduler>();
1057
1058   component_updater_ = component_updater::ComponentUpdateServiceFactory(
1059       component_updater::MakeChromeComponentUpdaterConfigurator(
1060           base::CommandLine::ForCurrentProcess(),
1061           g_browser_process->local_state()),
1062       std::move(scheduler));
1063
1064   return component_updater_.get();
1065 }
1066
1067 #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
1068 component_updater::SupervisedUserWhitelistInstaller*
1069 BrowserProcessImpl::supervised_user_whitelist_installer() {
1070   if (!supervised_user_whitelist_installer_) {
1071     supervised_user_whitelist_installer_ =
1072         component_updater::SupervisedUserWhitelistInstaller::Create(
1073             component_updater(),
1074             &profile_manager()->GetProfileAttributesStorage(),
1075             local_state());
1076   }
1077   return supervised_user_whitelist_installer_.get();
1078 }
1079 #endif  // BUILDFLAG(ENABLE_SUPERVISED_USERS)
1080
1081 void BrowserProcessImpl::OnKeepAliveStateChanged(bool is_keeping_alive) {
1082   if (is_keeping_alive)
1083     Pin();
1084   else
1085     Unpin();
1086 }
1087
1088 void BrowserProcessImpl::CreateNetworkQualityObserver() {
1089   DCHECK(!network_quality_observer_);
1090   network_quality_observer_ =
1091       content::CreateNetworkQualityObserver(network_quality_tracker());
1092   DCHECK(network_quality_observer_);
1093 }
1094
1095 void BrowserProcessImpl::OnKeepAliveRestartStateChanged(bool can_restart) {}
1096
1097 void BrowserProcessImpl::CreateWatchdogThread() {
1098   DCHECK(!created_watchdog_thread_ && !watchdog_thread_);
1099   created_watchdog_thread_ = true;
1100
1101   auto thread = std::make_unique<WatchDogThread>();
1102   base::Thread::Options options;
1103   options.timer_slack = base::TIMER_SLACK_MAXIMUM;
1104   if (!thread->StartWithOptions(options))
1105     return;
1106   watchdog_thread_.swap(thread);
1107 }
1108
1109 void BrowserProcessImpl::CreateProfileManager() {
1110   DCHECK(!created_profile_manager_ && !profile_manager_);
1111   created_profile_manager_ = true;
1112
1113   base::FilePath user_data_dir;
1114   base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
1115   profile_manager_ = std::make_unique<ProfileManager>(user_data_dir);
1116 }
1117
1118 void BrowserProcessImpl::CreateLocalState() {
1119   DCHECK(!local_state_);
1120
1121   local_state_ = chrome_feature_list_creator_->TakePrefService();
1122   DCHECK(local_state_);
1123 }
1124
1125 void BrowserProcessImpl::PreCreateThreads(
1126     const base::CommandLine& command_line) {
1127 #if BUILDFLAG(ENABLE_EXTENSIONS)
1128   // chrome-extension:// URLs are safe to request anywhere, but may only
1129   // commit (including in iframes) in extension processes.
1130   ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeIsolatedScheme(
1131       extensions::kExtensionScheme, true);
1132 #endif
1133
1134   battery_metrics_ = std::make_unique<BatteryMetrics>();
1135
1136   secure_origin_prefs_observer_ =
1137       std::make_unique<SecureOriginPrefsObserver>(local_state());
1138   site_isolation_prefs_observer_ =
1139       std::make_unique<SiteIsolationPrefsObserver>(local_state());
1140
1141   // Create SystemNetworkContextManager without a NetworkService if it has not
1142   // been requested yet.
1143   if (!SystemNetworkContextManager::HasInstance())
1144     SystemNetworkContextManager::CreateInstance(local_state());
1145 }
1146
1147 void BrowserProcessImpl::PreMainMessageLoopRun() {
1148   TRACE_EVENT0("startup", "BrowserProcessImpl::PreMainMessageLoopRun");
1149   SCOPED_UMA_HISTOGRAM_TIMER(
1150       "Startup.BrowserProcessImpl_PreMainMessageLoopRunTime");
1151
1152   // browser_policy_connector() is created very early because local_state()
1153   // needs policy to be initialized with the managed preference values.
1154   // However, policy fetches from the network and loading of disk caches
1155   // requires that threads are running; this Init() call lets the connector
1156   // resume its initialization now that the loops are spinning and the
1157   // system request context is available for the fetchers.
1158   browser_policy_connector()->Init(
1159       local_state(),
1160       system_network_context_manager()->GetSharedURLLoaderFactory());
1161
1162   if (local_state_->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled))
1163     ApplyDefaultBrowserPolicy();
1164
1165 #if !defined(OS_ANDROID)
1166   ApplyMetricsReportingPolicy();
1167 #endif
1168
1169 #if BUILDFLAG(ENABLE_PLUGINS)
1170   auto* plugin_service = content::PluginService::GetInstance();
1171   plugin_service->SetFilter(ChromePluginServiceFilter::GetInstance());
1172
1173   // Triggers initialization of the singleton instance on UI thread.
1174   PluginFinder::GetInstance()->Init();
1175
1176   DCHECK(!plugins_resource_service_);
1177   plugins_resource_service_ =
1178       std::make_unique<PluginsResourceService>(local_state());
1179   plugins_resource_service_->Init();
1180 #endif  // BUILDFLAG(ENABLE_PLUGINS)
1181
1182 #if !defined(OS_ANDROID)
1183   storage_monitor::StorageMonitor::Create();
1184 #endif
1185
1186   platform_part_->PreMainMessageLoopRun();
1187
1188   if (base::FeatureList::IsEnabled(network_time::kNetworkTimeServiceQuerying)) {
1189     network_time_tracker_ = std::make_unique<network_time::NetworkTimeTracker>(
1190         base::WrapUnique(new base::DefaultClock()),
1191         base::WrapUnique(new base::DefaultTickClock()), local_state(),
1192         system_network_context_manager()->GetSharedURLLoaderFactory());
1193   }
1194
1195   CreateNetworkQualityObserver();
1196
1197 #if defined(OS_ANDROID)
1198   // This needs to be here so that SecurityStateClient is non-null when
1199   // SecurityStateModel code is called.
1200   security_state::SetSecurityStateClient(new ChromeSecurityStateClient());
1201 #endif
1202 }
1203
1204 void BrowserProcessImpl::CreateIconManager() {
1205   DCHECK(!created_icon_manager_ && !icon_manager_);
1206   created_icon_manager_ = true;
1207   icon_manager_ = std::make_unique<IconManager>();
1208 }
1209
1210 void BrowserProcessImpl::CreateIntranetRedirectDetector() {
1211   DCHECK(!intranet_redirect_detector_);
1212   intranet_redirect_detector_ = std::make_unique<IntranetRedirectDetector>();
1213 }
1214
1215 void BrowserProcessImpl::CreateNotificationPlatformBridge() {
1216 #if BUILDFLAG(ENABLE_NATIVE_NOTIFICATIONS)
1217   DCHECK(!notification_bridge_);
1218   notification_bridge_ = NotificationPlatformBridge::Create();
1219   created_notification_bridge_ = true;
1220 #endif
1221 }
1222
1223 void BrowserProcessImpl::CreateNotificationUIManager() {
1224 // Android and Chrome OS do not use the NotificationUIManager anymore.
1225 // All notification traffic is routed through NotificationPlatformBridge.
1226 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1227   DCHECK(!notification_ui_manager_);
1228   notification_ui_manager_ = NotificationUIManager::Create();
1229   created_notification_ui_manager_ = !!notification_ui_manager_;
1230 #endif
1231 }
1232
1233 void BrowserProcessImpl::CreateBackgroundModeManager() {
1234 #if BUILDFLAG(ENABLE_BACKGROUND_MODE)
1235   DCHECK(!background_mode_manager_);
1236   background_mode_manager_ = std::make_unique<BackgroundModeManager>(
1237       *base::CommandLine::ForCurrentProcess(),
1238       &profile_manager()->GetProfileAttributesStorage());
1239 #endif
1240 }
1241
1242 void BrowserProcessImpl::CreateStatusTray() {
1243   DCHECK(!status_tray_);
1244   status_tray_ = StatusTray::Create();
1245 }
1246
1247 void BrowserProcessImpl::CreatePrintPreviewDialogController() {
1248 #if BUILDFLAG(ENABLE_PRINT_PREVIEW)
1249   DCHECK(!print_preview_dialog_controller_);
1250   print_preview_dialog_controller_ =
1251       base::MakeRefCounted<printing::PrintPreviewDialogController>();
1252 #else
1253   NOTIMPLEMENTED();
1254 #endif
1255 }
1256
1257 void BrowserProcessImpl::CreateBackgroundPrintingManager() {
1258 #if BUILDFLAG(ENABLE_PRINT_PREVIEW)
1259   DCHECK(!background_printing_manager_);
1260   background_printing_manager_ =
1261       std::make_unique<printing::BackgroundPrintingManager>();
1262 #else
1263   NOTIMPLEMENTED();
1264 #endif
1265 }
1266
1267 void BrowserProcessImpl::CreateSafeBrowsingService() {
1268   DCHECK(!safe_browsing_service_);
1269   // Set this flag to true so that we don't retry indefinitely to
1270   // create the service class if there was an error.
1271   created_safe_browsing_service_ = true;
1272
1273   // The factory can be overridden in tests.
1274   if (!safe_browsing::SafeBrowsingServiceInterface::HasFactory()) {
1275     safe_browsing::SafeBrowsingServiceInterface::RegisterFactory(
1276         safe_browsing::GetSafeBrowsingServiceFactory());
1277   }
1278
1279   // TODO(crbug/925153): Port consumers of the |safe_browsing_service_| to use
1280   // the interface in components/safe_browsing, and remove this cast.
1281   safe_browsing_service_ = static_cast<safe_browsing::SafeBrowsingService*>(
1282       safe_browsing::SafeBrowsingServiceInterface::CreateSafeBrowsingService());
1283   if (safe_browsing_service_)
1284     safe_browsing_service_->Initialize();
1285 }
1286
1287 void BrowserProcessImpl::CreateSubresourceFilterRulesetService() {
1288   DCHECK(!subresource_filter_ruleset_service_);
1289   created_subresource_filter_ruleset_service_ = true;
1290
1291   if (!base::FeatureList::IsEnabled(
1292           subresource_filter::kSafeBrowsingSubresourceFilter)) {
1293     return;
1294   }
1295
1296   // Runner for tasks critical for user experience.
1297   scoped_refptr<base::SequencedTaskRunner> blocking_task_runner(
1298       base::ThreadPool::CreateSequencedTaskRunner(
1299           {base::MayBlock(), base::TaskPriority::USER_BLOCKING,
1300            base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}));
1301
1302   // Runner for tasks that do not influence user experience.
1303   scoped_refptr<base::SequencedTaskRunner> background_task_runner(
1304       base::ThreadPool::CreateSequencedTaskRunner(
1305           {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
1306            base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}));
1307
1308   base::FilePath user_data_dir;
1309   base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
1310   base::FilePath indexed_ruleset_base_dir =
1311       user_data_dir.Append(subresource_filter::kTopLevelDirectoryName)
1312           .Append(subresource_filter::kIndexedRulesetBaseDirectoryName);
1313   subresource_filter_ruleset_service_ =
1314       std::make_unique<subresource_filter::RulesetService>(
1315           local_state(), background_task_runner, indexed_ruleset_base_dir,
1316           blocking_task_runner);
1317 }
1318
1319 void BrowserProcessImpl::CreateFlocBlocklistService() {
1320   DCHECK(!floc_blocklist_service_);
1321   floc_blocklist_service_ =
1322       std::make_unique<federated_learning::FlocBlocklistService>();
1323 }
1324
1325 void BrowserProcessImpl::CreateOptimizationGuideService() {
1326   DCHECK(!created_optimization_guide_service_);
1327   DCHECK(!optimization_guide_service_);
1328   created_optimization_guide_service_ = true;
1329
1330   if (!optimization_guide::features::IsOptimizationHintsEnabled())
1331     return;
1332
1333   optimization_guide_service_ =
1334       std::make_unique<optimization_guide::OptimizationGuideService>(
1335           content::GetUIThreadTaskRunner({}));
1336 }
1337
1338 void BrowserProcessImpl::CreateGCMDriver() {
1339   DCHECK(!gcm_driver_);
1340
1341 #if defined(OS_ANDROID)
1342   // Android's GCMDriver currently makes the assumption that it's a singleton.
1343   // Until this gets fixed, instantiating multiple Java GCMDrivers will throw
1344   // an exception, but because they're only initialized on demand these crashes
1345   // would be very difficult to triage. See http://crbug.com/437827.
1346   NOTREACHED();
1347 #else
1348   base::FilePath store_path;
1349   CHECK(base::PathService::Get(chrome::DIR_GLOBAL_GCM_STORE, &store_path));
1350   scoped_refptr<base::SequencedTaskRunner> blocking_task_runner(
1351       base::ThreadPool::CreateSequencedTaskRunner(
1352           {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
1353            base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}));
1354
1355   gcm_driver_ = gcm::CreateGCMDriverDesktop(
1356       base::WrapUnique(new gcm::GCMClientFactory), local_state(), store_path,
1357       /*remove_account_mappings_with_email_key=*/false,
1358       base::BindRepeating(&RequestProxyResolvingSocketFactory),
1359       system_network_context_manager()->GetSharedURLLoaderFactory(),
1360       content::GetNetworkConnectionTracker(), chrome::GetChannel(),
1361       gcm::GetProductCategoryForSubtypes(local_state()),
1362       content::GetUIThreadTaskRunner({}), content::GetIOThreadTaskRunner({}),
1363       blocking_task_runner);
1364 #endif  // defined(OS_ANDROID)
1365 }
1366
1367 void BrowserProcessImpl::ApplyDefaultBrowserPolicy() {
1368   if (local_state()->GetBoolean(prefs::kDefaultBrowserSettingEnabled)) {
1369     // The worker pointer is reference counted. While it is running, the
1370     // message loops of the FILE and UI thread will hold references to it
1371     // and it will be automatically freed once all its tasks have finished.
1372     auto set_browser_worker =
1373         base::MakeRefCounted<shell_integration::DefaultBrowserWorker>(
1374             shell_integration::DefaultWebClientWorkerCallback());
1375     // The user interaction must always be disabled when applying the default
1376     // browser policy since it is done at each browser startup and the result
1377     // of the interaction cannot be forced.
1378     set_browser_worker->set_interactive_permitted(false);
1379     set_browser_worker->StartSetAsDefault();
1380   }
1381 }
1382
1383 void BrowserProcessImpl::Pin() {
1384   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1385   CHECK(!IsShuttingDown());
1386 }
1387
1388 void BrowserProcessImpl::Unpin() {
1389   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1390
1391 #if !defined(OS_ANDROID)
1392   // The quit closure is set by ChromeBrowserMainParts to transfer ownership of
1393   // the browser's lifetime to the BrowserProcess. Any KeepAlives registered and
1394   // unregistered prior to setting the quit closure are ignored. Only once the
1395   // quit closure is set should unpinning start process shutdown.
1396   if (!quit_closure_)
1397     return;
1398 #endif
1399
1400   DCHECK(!shutting_down_);
1401   shutting_down_ = true;
1402
1403 #if !defined(OS_ANDROID)
1404   KeepAliveRegistry::GetInstance()->SetIsShuttingDown();
1405 #endif  // !defined(OS_ANDROID)
1406
1407 #if BUILDFLAG(ENABLE_PRINTING)
1408   // Wait for the pending print jobs to finish. Don't do this later, since
1409   // this might cause a nested run loop to run, and we don't want pending
1410   // tasks to run once teardown has started.
1411   print_job_manager_->Shutdown();
1412 #endif
1413
1414 #if defined(LEAK_SANITIZER)
1415   // Check for memory leaks now, before we start shutting down threads. Doing
1416   // this early means we won't report any shutdown-only leaks (as they have
1417   // not yet happened at this point).
1418   // If leaks are found, this will make the process exit immediately.
1419   __lsan_do_leak_check();
1420 #endif
1421
1422   CHECK(base::RunLoop::IsRunningOnCurrentThread());
1423
1424 #if defined(OS_MACOSX)
1425   base::ThreadTaskRunnerHandle::Get()->PostTask(
1426       FROM_HERE,
1427       base::BindOnce(ChromeBrowserMainPartsMac::DidEndMainMessageLoop));
1428 #endif
1429
1430 #if !defined(OS_ANDROID)
1431   std::move(quit_closure_).Run();
1432
1433   chrome::ShutdownIfNeeded();
1434
1435   // TODO(crbug.com/967603): remove when root cause is found.
1436   CHECK_EQ(BrowserList::GetInstance()->size(), 0u);
1437 #endif  // !defined(OS_ANDROID)
1438 }
1439
1440 // Mac is currently not supported.
1441 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
1442
1443 bool BrowserProcessImpl::IsRunningInBackground() const {
1444   // Check if browser is in the background.
1445   return chrome::GetTotalBrowserCount() == 0 &&
1446          KeepAliveRegistry::GetInstance()->IsKeepingAlive();
1447 }
1448
1449 void BrowserProcessImpl::RestartBackgroundInstance() {
1450   base::CommandLine* old_cl = base::CommandLine::ForCurrentProcess();
1451   auto new_cl = std::make_unique<base::CommandLine>(old_cl->GetProgram());
1452
1453   base::CommandLine::SwitchMap switches = old_cl->GetSwitches();
1454   switches::RemoveSwitchesForAutostart(&switches);
1455
1456   // Append the rest of the switches (along with their values, if any)
1457   // to the new command line
1458   for (const auto& it : switches) {
1459     const auto& switch_name = it.first;
1460     const auto& switch_value = it.second;
1461     if (switch_value.empty())
1462       new_cl->AppendSwitch(switch_name);
1463     else
1464       new_cl->AppendSwitchNative(switch_name, switch_value);
1465   }
1466
1467   // Switches to add when auto-restarting Chrome.
1468   static constexpr const char* kSwitchesToAddOnAutorestart[] = {
1469       switches::kNoStartupWindow};
1470
1471   // Ensure that our desired switches are set on the new process.
1472   for (const char* switch_to_add : kSwitchesToAddOnAutorestart) {
1473     if (!new_cl->HasSwitch(switch_to_add))
1474       new_cl->AppendSwitch(switch_to_add);
1475   }
1476
1477 #if defined(OS_WIN)
1478   new_cl->AppendArg(switches::kPrefetchArgumentBrowserBackground);
1479 #endif  // defined(OS_WIN)
1480
1481   DLOG(WARNING) << "Shutting down current instance of the browser.";
1482   chrome::AttemptExit();
1483
1484   upgrade_util::SetNewCommandLine(std::move(new_cl));
1485 }
1486
1487 void BrowserProcessImpl::OnAutoupdateTimer() {
1488   if (IsRunningInBackground()) {
1489     // upgrade_util::IsUpdatePendingRestart touches the disk, so do it on a
1490     // suitable thread.
1491     base::ThreadPool::PostTaskAndReplyWithResult(
1492         FROM_HERE,
1493         {base::TaskPriority::BEST_EFFORT,
1494          base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN, base::MayBlock()},
1495         base::BindOnce(&upgrade_util::IsUpdatePendingRestart),
1496         base::BindOnce(&BrowserProcessImpl::OnPendingRestartResult,
1497                        base::Unretained(this)));
1498   }
1499 }
1500
1501 void BrowserProcessImpl::OnPendingRestartResult(
1502     bool is_update_pending_restart) {
1503   // Make sure that the browser is still in the background after returning from
1504   // the check.
1505   if (is_update_pending_restart && IsRunningInBackground()) {
1506     DLOG(WARNING) << "Detected update.  Restarting browser.";
1507     RestartBackgroundInstance();
1508   }
1509 }
1510
1511 #endif  // (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)