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.
5 #include "chrome/browser/browser_process_impl.h"
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"
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"
155 #if !defined(OS_CHROMEOS)
156 #include "ui/message_center/message_center.h"
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"
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"
172 #if BUILDFLAG(ENABLE_BACKGROUND_MODE)
173 #include "chrome/browser/background/background_mode_manager.h"
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"
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"
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"
201 #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
202 #include "chrome/browser/component_updater/supervised_user_whitelist_installer.h"
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;
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
216 static constexpr base::TimeDelta kEndSessionTimeout =
217 base::TimeDelta::FromSeconds(10);
220 using content::BrowserThread;
221 using content::ChildProcessSecurityPolicy;
223 rappor::RapporService* GetBrowserRapporService() {
224 if (g_browser_process != nullptr)
225 return g_browser_process->rappor_service();
229 BrowserProcessImpl::BrowserProcessImpl(StartupData* startup_data) {
230 g_browser_process = this;
232 DCHECK(startup_data);
233 startup_data_ = startup_data;
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;
240 platform_part_ = std::make_unique<BrowserProcessPlatformPart>();
241 // Most work should be done in Init().
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();
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
256 GetMetricsServicesManager();
257 DCHECK(metrics_services_manager_client_);
258 metrics_services_manager_client_->OnCrosSettingsCreated();
261 download_status_updater_ = std::make_unique<DownloadStatusUpdater>();
263 rappor::SetDefaultServiceAccessor(&GetBrowserRapporService);
265 #if BUILDFLAG(ENABLE_PRINTING)
266 // Must be created after the NotificationService.
267 print_job_manager_ = std::make_unique<printing::PrintJobManager>();
270 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
271 chrome::kChromeSearchScheme);
273 #if defined(OS_MACOSX)
274 ui::InitIdleMonitor();
277 #if BUILDFLAG(ENABLE_EXTENSIONS)
278 extensions::AppWindowClient::Set(ChromeAppWindowClient::GetInstance());
280 extension_event_router_forwarder_ =
281 base::MakeRefCounted<extensions::EventRouterForwarder>();
283 EnsureExtensionsClientInitialized();
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());
292 #if !defined(OS_CHROMEOS)
293 message_center::MessageCenter::Initialize();
294 // Set the system notification source display name ("Google Chrome" or
296 if (message_center::MessageCenter::Get()) {
297 message_center::MessageCenter::Get()->SetSystemNotificationAppName(
298 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME));
302 system_notification_helper_ = std::make_unique<SystemNotificationHelper>();
304 update_client::UpdateQueryParams::SetDelegate(
305 ChromeUpdateQueryParamsDelegate::GetInstance());
307 // Make sure permissions client has been set.
308 ChromePermissionsClient::GetInstance();
310 #if !defined(OS_ANDROID)
311 KeepAliveRegistry::GetInstance()->SetIsShuttingDown(false);
312 KeepAliveRegistry::GetInstance()->AddObserver(this);
313 #endif // !defined(OS_ANDROID)
315 MigrateObsoleteLocalStatePrefs(local_state());
316 pref_change_registrar_.Init(local_state());
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)));
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));
331 DCHECK(!webrtc_event_log_manager_);
332 webrtc_event_log_manager_ = WebRtcEventLogManager::CreateSingletonInstance();
334 #if defined(OS_MACOSX)
335 system_media_permissions::LogSystemMediaPermissionsStartupStats();
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);
348 #if defined(OS_MACOSX)
349 void BrowserProcessImpl::ClearQuitClosure() {
350 quit_closure_.Reset();
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);
361 #if !defined(OS_ANDROID)
362 KeepAliveRegistry::GetInstance()->RemoveObserver(this);
365 g_browser_process = NULL;
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());
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();
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()
396 system_notification_helper_.reset();
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();
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();
411 // Debugger must be cleaned up before ProfileManager.
412 remote_debugging_server_.reset();
413 devtools_auto_opener_.reset();
415 battery_metrics_.reset();
417 // Need to clear profiles (download managers) before the IO thread.
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
425 #endif // !defined(OS_CHROMEOS)
426 profile_manager_.reset();
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();
438 #if !defined(OS_CHROMEOS)
439 if (message_center::MessageCenter::Get())
440 message_center::MessageCenter::Shutdown();
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();
450 // The |gcm_driver_| must shut down while the IO thread is still alive.
452 gcm_driver_->Shutdown();
454 // Stop the watchdog thread before stopping other threads.
455 watchdog_thread_.reset();
457 platform_part()->StartTearDown();
459 // Cancel any uploads to release the system url request context references.
460 if (webrtc_log_uploader_)
461 webrtc_log_uploader_->Shutdown();
463 sessions::SessionIdGenerator::GetInstance()->Shutdown();
466 local_state_->CommitPendingWrite();
468 // This expects to be destroyed before the task scheduler is torn down.
469 SystemNetworkContextManager::DeleteInstance();
472 void BrowserProcessImpl::PostDestroyThreads() {
473 // With the file_thread_ flushed, we can release any icon resources.
474 icon_manager_.reset();
476 // Must outlive the worker threads.
477 webrtc_log_uploader_.reset();
479 #endif // !defined(OS_ANDROID)
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);
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
495 class RundownTaskCounter :
496 public base::RefCountedThreadSafe<RundownTaskCounter> {
498 RundownTaskCounter();
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
504 base::OnceClosure GetRundownClosure();
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);
511 friend class base::RefCountedThreadSafe<RundownTaskCounter>;
512 ~RundownTaskCounter() {}
514 // Decrements the counter and releases the waitable event on transition to
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_;
523 DISALLOW_COPY_AND_ASSIGN(RundownTaskCounter);
526 RundownTaskCounter::RundownTaskCounter() = default;
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());
535 return base::BindOnce(&RundownTaskCounter::Decrement, this);
538 void RundownTaskCounter::Decrement() {
539 if (!count_.Decrement())
540 waitable_event_.Signal();
543 void RundownTaskCounter::TimedWait(base::TimeDelta timeout) {
544 // Decrement the excess count from the constructor.
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);
554 #if !defined(OS_ANDROID)
555 void RequestProxyResolvingSocketFactoryOnUIThread(
556 mojo::PendingReceiver<network::mojom::ProxyResolvingSocketFactory>
558 network::mojom::NetworkContext* network_context =
559 g_browser_process->system_network_context_manager()->GetContext();
560 network_context->CreateProxyResolvingSocketFactory(std::move(receiver));
563 void RequestProxyResolvingSocketFactory(
564 mojo::PendingReceiver<network::mojom::ProxyResolvingSocketFactory>
566 content::GetUIThreadTaskRunner({})->PostTask(
567 FROM_HERE, base::BindOnce(&RequestProxyResolvingSocketFactoryOnUIThread,
568 std::move(receiver)));
574 void BrowserProcessImpl::FlushLocalStateAndReply(base::OnceClosure reply) {
576 local_state_->CommitPendingWrite(std::move(reply));
579 base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(reply));
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());
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());
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;
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.
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
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);
641 metrics_services_manager::MetricsServicesManager*
642 BrowserProcessImpl::GetMetricsServicesManager() {
643 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
644 if (!metrics_services_manager_) {
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>(
652 return metrics_services_manager_.get();
655 metrics::MetricsService* BrowserProcessImpl::metrics_service() {
656 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
657 return GetMetricsServicesManager()->GetMetricsService();
660 rappor::RapporServiceImpl* BrowserProcessImpl::rappor_service() {
661 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
662 return GetMetricsServicesManager()->GetRapporServiceImpl();
665 SystemNetworkContextManager*
666 BrowserProcessImpl::system_network_context_manager() {
667 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
668 DCHECK(SystemNetworkContextManager::GetInstance());
669 return SystemNetworkContextManager::GetInstance();
672 scoped_refptr<network::SharedURLLoaderFactory>
673 BrowserProcessImpl::shared_url_loader_factory() {
674 return system_network_context_manager()->GetSharedURLLoaderFactory();
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));
683 return network_quality_tracker_.get();
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();
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();
701 PrefService* BrowserProcessImpl::local_state() {
702 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
705 return local_state_.get();
708 variations::VariationsService* BrowserProcessImpl::variations_service() {
709 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
710 return GetMetricsServicesManager()->GetVariationsService();
713 BrowserProcessPlatformPart* BrowserProcessImpl::platform_part() {
714 return platform_part_.get();
717 extensions::EventRouterForwarder*
718 BrowserProcessImpl::extension_event_router_forwarder() {
719 #if BUILDFLAG(ENABLE_EXTENSIONS)
720 return extension_event_router_forwarder_.get();
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)
733 if (!created_notification_ui_manager_)
734 CreateNotificationUIManager();
735 return notification_ui_manager_.get();
739 NotificationPlatformBridge* BrowserProcessImpl::notification_platform_bridge() {
740 #if BUILDFLAG(ENABLE_NATIVE_NOTIFICATIONS)
741 if (!created_notification_bridge_)
742 CreateNotificationPlatformBridge();
743 return notification_bridge_.get();
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;
757 return browser_policy_connector_.get();
760 policy::PolicyService* BrowserProcessImpl::policy_service() {
761 return browser_policy_connector()->GetPolicyService();
764 IconManager* BrowserProcessImpl::icon_manager() {
765 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
766 if (!created_icon_manager_)
768 return icon_manager_.get();
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();
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>();
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>();
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_;
806 printing::PrintJobManager* BrowserProcessImpl::print_job_manager() {
807 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
808 return print_job_manager_.get();
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();
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();
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();
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_);
849 DCHECK(!locale_.empty());
853 void BrowserProcessImpl::SetApplicationLocale(
854 const std::string& actual_locale) {
855 // NOTE: this is called before any threads have been created in non-test
857 locale_ = actual_locale;
858 ChromeContentBrowserClient::SetApplicationLocale(actual_locale);
859 translate::TranslateDownloadManager::GetInstance()->set_application_locale(
863 DownloadStatusUpdater* BrowserProcessImpl::download_status_updater() {
864 return download_status_updater_.get();
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();
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();
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());
890 return network_time_tracker_.get();
893 gcm::GCMDriver* BrowserProcessImpl::gcm_driver() {
894 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
897 return gcm_driver_.get();
900 resource_coordinator::TabManager* BrowserProcessImpl::GetTabManager() {
901 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
902 return resource_coordinator_parts()->tab_manager();
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>();
912 return resource_coordinator_parts_.get();
915 BuildState* BrowserProcessImpl::GetBuildState() {
916 #if !defined(OS_ANDROID)
917 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
918 return &build_state_;
926 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple* registry) {
927 registry->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled,
930 registry->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt, false);
932 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
933 registry->RegisterBooleanPref(prefs::kEulaAccepted, false);
934 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID)
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
942 registry->RegisterStringPref(language::prefs::kApplicationLocale,
944 #if defined(OS_CHROMEOS)
945 registry->RegisterStringPref(prefs::kOwnerLocale, std::string());
946 registry->RegisterStringPref(prefs::kHardwareKeyboardLayout,
948 #endif // defined(OS_CHROMEOS)
950 registry->RegisterBooleanPref(metrics::prefs::kMetricsReportingEnabled,
951 GoogleUpdateSettings::GetCollectStatsConsent());
953 #if defined(OS_ANDROID)
954 registry->RegisterBooleanPref(
955 prefs::kCrashReportingEnabled, false);
956 #endif // defined(OS_ANDROID)
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>();
964 return download_request_limiter_.get();
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();
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);
986 StatusTray* BrowserProcessImpl::status_tray() {
987 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
990 return status_tray_.get();
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();
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();
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();
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();
1025 StartupData* BrowserProcessImpl::startup_data() {
1026 return startup_data_;
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),
1034 &BrowserProcessImpl::OnAutoupdateTimer);
1038 component_updater::ComponentUpdateService*
1039 BrowserProcessImpl::component_updater() {
1040 if (component_updater_)
1041 return component_updater_.get();
1043 if (!BrowserThread::CurrentlyOn(BrowserThread::UI))
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()) {
1052 std::make_unique<component_updater::BackgroundTaskUpdateScheduler>();
1056 scheduler = std::make_unique<component_updater::TimerUpdateScheduler>();
1058 component_updater_ = component_updater::ComponentUpdateServiceFactory(
1059 component_updater::MakeChromeComponentUpdaterConfigurator(
1060 base::CommandLine::ForCurrentProcess(),
1061 g_browser_process->local_state()),
1062 std::move(scheduler));
1064 return component_updater_.get();
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(),
1077 return supervised_user_whitelist_installer_.get();
1079 #endif // BUILDFLAG(ENABLE_SUPERVISED_USERS)
1081 void BrowserProcessImpl::OnKeepAliveStateChanged(bool is_keeping_alive) {
1082 if (is_keeping_alive)
1088 void BrowserProcessImpl::CreateNetworkQualityObserver() {
1089 DCHECK(!network_quality_observer_);
1090 network_quality_observer_ =
1091 content::CreateNetworkQualityObserver(network_quality_tracker());
1092 DCHECK(network_quality_observer_);
1095 void BrowserProcessImpl::OnKeepAliveRestartStateChanged(bool can_restart) {}
1097 void BrowserProcessImpl::CreateWatchdogThread() {
1098 DCHECK(!created_watchdog_thread_ && !watchdog_thread_);
1099 created_watchdog_thread_ = true;
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))
1106 watchdog_thread_.swap(thread);
1109 void BrowserProcessImpl::CreateProfileManager() {
1110 DCHECK(!created_profile_manager_ && !profile_manager_);
1111 created_profile_manager_ = true;
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);
1118 void BrowserProcessImpl::CreateLocalState() {
1119 DCHECK(!local_state_);
1121 local_state_ = chrome_feature_list_creator_->TakePrefService();
1122 DCHECK(local_state_);
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);
1134 battery_metrics_ = std::make_unique<BatteryMetrics>();
1136 secure_origin_prefs_observer_ =
1137 std::make_unique<SecureOriginPrefsObserver>(local_state());
1138 site_isolation_prefs_observer_ =
1139 std::make_unique<SiteIsolationPrefsObserver>(local_state());
1141 // Create SystemNetworkContextManager without a NetworkService if it has not
1142 // been requested yet.
1143 if (!SystemNetworkContextManager::HasInstance())
1144 SystemNetworkContextManager::CreateInstance(local_state());
1147 void BrowserProcessImpl::PreMainMessageLoopRun() {
1148 TRACE_EVENT0("startup", "BrowserProcessImpl::PreMainMessageLoopRun");
1149 SCOPED_UMA_HISTOGRAM_TIMER(
1150 "Startup.BrowserProcessImpl_PreMainMessageLoopRunTime");
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(
1160 system_network_context_manager()->GetSharedURLLoaderFactory());
1162 if (local_state_->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled))
1163 ApplyDefaultBrowserPolicy();
1165 #if !defined(OS_ANDROID)
1166 ApplyMetricsReportingPolicy();
1169 #if BUILDFLAG(ENABLE_PLUGINS)
1170 auto* plugin_service = content::PluginService::GetInstance();
1171 plugin_service->SetFilter(ChromePluginServiceFilter::GetInstance());
1173 // Triggers initialization of the singleton instance on UI thread.
1174 PluginFinder::GetInstance()->Init();
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)
1182 #if !defined(OS_ANDROID)
1183 storage_monitor::StorageMonitor::Create();
1186 platform_part_->PreMainMessageLoopRun();
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());
1195 CreateNetworkQualityObserver();
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());
1204 void BrowserProcessImpl::CreateIconManager() {
1205 DCHECK(!created_icon_manager_ && !icon_manager_);
1206 created_icon_manager_ = true;
1207 icon_manager_ = std::make_unique<IconManager>();
1210 void BrowserProcessImpl::CreateIntranetRedirectDetector() {
1211 DCHECK(!intranet_redirect_detector_);
1212 intranet_redirect_detector_ = std::make_unique<IntranetRedirectDetector>();
1215 void BrowserProcessImpl::CreateNotificationPlatformBridge() {
1216 #if BUILDFLAG(ENABLE_NATIVE_NOTIFICATIONS)
1217 DCHECK(!notification_bridge_);
1218 notification_bridge_ = NotificationPlatformBridge::Create();
1219 created_notification_bridge_ = true;
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_;
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());
1242 void BrowserProcessImpl::CreateStatusTray() {
1243 DCHECK(!status_tray_);
1244 status_tray_ = StatusTray::Create();
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>();
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>();
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;
1273 // The factory can be overridden in tests.
1274 if (!safe_browsing::SafeBrowsingServiceInterface::HasFactory()) {
1275 safe_browsing::SafeBrowsingServiceInterface::RegisterFactory(
1276 safe_browsing::GetSafeBrowsingServiceFactory());
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();
1287 void BrowserProcessImpl::CreateSubresourceFilterRulesetService() {
1288 DCHECK(!subresource_filter_ruleset_service_);
1289 created_subresource_filter_ruleset_service_ = true;
1291 if (!base::FeatureList::IsEnabled(
1292 subresource_filter::kSafeBrowsingSubresourceFilter)) {
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}));
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}));
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);
1319 void BrowserProcessImpl::CreateFlocBlocklistService() {
1320 DCHECK(!floc_blocklist_service_);
1321 floc_blocklist_service_ =
1322 std::make_unique<federated_learning::FlocBlocklistService>();
1325 void BrowserProcessImpl::CreateOptimizationGuideService() {
1326 DCHECK(!created_optimization_guide_service_);
1327 DCHECK(!optimization_guide_service_);
1328 created_optimization_guide_service_ = true;
1330 if (!optimization_guide::features::IsOptimizationHintsEnabled())
1333 optimization_guide_service_ =
1334 std::make_unique<optimization_guide::OptimizationGuideService>(
1335 content::GetUIThreadTaskRunner({}));
1338 void BrowserProcessImpl::CreateGCMDriver() {
1339 DCHECK(!gcm_driver_);
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.
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}));
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)
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();
1383 void BrowserProcessImpl::Pin() {
1384 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1385 CHECK(!IsShuttingDown());
1388 void BrowserProcessImpl::Unpin() {
1389 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
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.
1400 DCHECK(!shutting_down_);
1401 shutting_down_ = true;
1403 #if !defined(OS_ANDROID)
1404 KeepAliveRegistry::GetInstance()->SetIsShuttingDown();
1405 #endif // !defined(OS_ANDROID)
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();
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();
1422 CHECK(base::RunLoop::IsRunningOnCurrentThread());
1424 #if defined(OS_MACOSX)
1425 base::ThreadTaskRunnerHandle::Get()->PostTask(
1427 base::BindOnce(ChromeBrowserMainPartsMac::DidEndMainMessageLoop));
1430 #if !defined(OS_ANDROID)
1431 std::move(quit_closure_).Run();
1433 chrome::ShutdownIfNeeded();
1435 // TODO(crbug.com/967603): remove when root cause is found.
1436 CHECK_EQ(BrowserList::GetInstance()->size(), 0u);
1437 #endif // !defined(OS_ANDROID)
1440 // Mac is currently not supported.
1441 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
1443 bool BrowserProcessImpl::IsRunningInBackground() const {
1444 // Check if browser is in the background.
1445 return chrome::GetTotalBrowserCount() == 0 &&
1446 KeepAliveRegistry::GetInstance()->IsKeepingAlive();
1449 void BrowserProcessImpl::RestartBackgroundInstance() {
1450 base::CommandLine* old_cl = base::CommandLine::ForCurrentProcess();
1451 auto new_cl = std::make_unique<base::CommandLine>(old_cl->GetProgram());
1453 base::CommandLine::SwitchMap switches = old_cl->GetSwitches();
1454 switches::RemoveSwitchesForAutostart(&switches);
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);
1464 new_cl->AppendSwitchNative(switch_name, switch_value);
1467 // Switches to add when auto-restarting Chrome.
1468 static constexpr const char* kSwitchesToAddOnAutorestart[] = {
1469 switches::kNoStartupWindow};
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);
1478 new_cl->AppendArg(switches::kPrefetchArgumentBrowserBackground);
1479 #endif // defined(OS_WIN)
1481 DLOG(WARNING) << "Shutting down current instance of the browser.";
1482 chrome::AttemptExit();
1484 upgrade_util::SetNewCommandLine(std::move(new_cl));
1487 void BrowserProcessImpl::OnAutoupdateTimer() {
1488 if (IsRunningInBackground()) {
1489 // upgrade_util::IsUpdatePendingRestart touches the disk, so do it on a
1491 base::ThreadPool::PostTaskAndReplyWithResult(
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)));
1501 void BrowserProcessImpl::OnPendingRestartResult(
1502 bool is_update_pending_restart) {
1503 // Make sure that the browser is still in the background after returning from
1505 if (is_update_pending_restart && IsRunningInBackground()) {
1506 DLOG(WARNING) << "Detected update. Restarting browser.";
1507 RestartBackgroundInstance();
1511 #endif // (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)