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"
11 #include "base/atomic_ref_count.h"
12 #include "base/bind.h"
13 #include "base/bind_helpers.h"
14 #include "base/command_line.h"
15 #include "base/debug/alias.h"
16 #include "base/debug/leak_annotations.h"
17 #include "base/files/file_path.h"
18 #include "base/metrics/field_trial.h"
19 #include "base/metrics/histogram_macros.h"
20 #include "base/path_service.h"
21 #include "base/prefs/json_pref_store.h"
22 #include "base/prefs/pref_registry_simple.h"
23 #include "base/prefs/pref_service.h"
24 #include "base/synchronization/waitable_event.h"
25 #include "base/threading/thread.h"
26 #include "base/threading/thread_restrictions.h"
27 #include "base/time/default_tick_clock.h"
28 #include "base/trace_event/trace_event.h"
29 #include "chrome/browser/chrome_browser_main.h"
30 #include "chrome/browser/chrome_child_process_watcher.h"
31 #include "chrome/browser/chrome_content_browser_client.h"
32 #include "chrome/browser/chrome_notification_types.h"
33 #include "chrome/browser/component_updater/chrome_component_updater_configurator.h"
34 #include "chrome/browser/component_updater/supervised_user_whitelist_installer.h"
35 #include "chrome/browser/defaults.h"
36 #include "chrome/browser/devtools/remote_debugging_server.h"
37 #include "chrome/browser/download/download_request_limiter.h"
38 #include "chrome/browser/download/download_status_updater.h"
39 #include "chrome/browser/first_run/upgrade_util.h"
40 #include "chrome/browser/gpu/gl_string_manager.h"
41 #include "chrome/browser/gpu/gpu_mode_manager.h"
42 #include "chrome/browser/icon_manager.h"
43 #include "chrome/browser/intranet_redirect_detector.h"
44 #include "chrome/browser/io_thread.h"
45 #include "chrome/browser/lifetime/application_lifetime.h"
46 #include "chrome/browser/metrics/chrome_metrics_service_accessor.h"
47 #include "chrome/browser/metrics/metrics_services_manager.h"
48 #include "chrome/browser/metrics/thread_watcher.h"
49 #include "chrome/browser/net/chrome_net_log.h"
50 #include "chrome/browser/net/crl_set_fetcher.h"
51 #include "chrome/browser/notifications/notification_ui_manager.h"
52 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
53 #include "chrome/browser/plugins/plugin_finder.h"
54 #include "chrome/browser/prefs/browser_prefs.h"
55 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
56 #include "chrome/browser/printing/background_printing_manager.h"
57 #include "chrome/browser/printing/print_job_manager.h"
58 #include "chrome/browser/printing/print_preview_dialog_controller.h"
59 #include "chrome/browser/profiles/profile_manager.h"
60 #include "chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h"
61 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
62 #include "chrome/browser/shell_integration.h"
63 #include "chrome/browser/status_icons/status_tray.h"
64 #include "chrome/browser/ui/browser_dialogs.h"
65 #include "chrome/browser/ui/browser_finder.h"
66 #include "chrome/browser/ui/user_manager.h"
67 #include "chrome/browser/update_client/chrome_update_query_params_delegate.h"
68 #include "chrome/common/channel_info.h"
69 #include "chrome/common/chrome_constants.h"
70 #include "chrome/common/chrome_paths.h"
71 #include "chrome/common/chrome_switches.h"
72 #include "chrome/common/extensions/chrome_extensions_client.h"
73 #include "chrome/common/pref_names.h"
74 #include "chrome/common/switch_utils.h"
75 #include "chrome/common/url_constants.h"
76 #include "chrome/installer/util/google_update_constants.h"
77 #include "chrome/installer/util/google_update_settings.h"
78 #include "components/component_updater/component_updater_service.h"
79 #include "components/gcm_driver/gcm_driver.h"
80 #include "components/metrics/metrics_service.h"
81 #include "components/network_time/network_time_tracker.h"
82 #include "components/policy/core/common/policy_service.h"
83 #include "components/safe_json/safe_json_parser.h"
84 #include "components/signin/core/common/profile_management_switches.h"
85 #include "components/translate/core/browser/translate_download_manager.h"
86 #include "components/update_client/update_query_params.h"
87 #include "components/web_resource/promo_resource_service.h"
88 #include "components/web_resource/web_resource_pref_names.h"
89 #include "content/public/browser/browser_thread.h"
90 #include "content/public/browser/child_process_security_policy.h"
91 #include "content/public/browser/notification_details.h"
92 #include "content/public/browser/plugin_service.h"
93 #include "content/public/browser/render_process_host.h"
94 #include "content/public/browser/resource_dispatcher_host.h"
95 #include "content/public/browser/service_worker_context.h"
96 #include "content/public/browser/storage_partition.h"
97 #include "extensions/common/constants.h"
98 #include "net/socket/client_socket_pool_manager.h"
99 #include "net/url_request/url_request_context_getter.h"
100 #include "ui/base/idle/idle.h"
101 #include "ui/base/l10n/l10n_util.h"
102 #include "ui/message_center/message_center.h"
105 #include "base/win/windows_version.h"
106 #include "ui/views/focus/view_storage.h"
107 #elif defined(OS_MACOSX)
108 #include "chrome/browser/chrome_browser_main_mac.h"
111 #if !defined(OS_ANDROID)
112 #include "chrome/browser/chrome_device_client.h"
113 #include "chrome/browser/services/gcm/gcm_desktop_utils.h"
114 #include "components/gcm_driver/gcm_client_factory.h"
117 #if defined(ENABLE_BACKGROUND)
118 #include "chrome/browser/background/background_mode_manager.h"
121 #if defined(ENABLE_CONFIGURATION_POLICY)
122 #include "components/policy/core/browser/browser_policy_connector.h"
124 #include "components/policy/core/common/policy_service_stub.h"
125 #endif // defined(ENABLE_CONFIGURATION_POLICY)
127 #if defined(ENABLE_EXTENSIONS)
128 #include "chrome/browser/extensions/chrome_extensions_browser_client.h"
129 #include "chrome/browser/extensions/event_router_forwarder.h"
130 #include "chrome/browser/extensions/extension_renderer_state.h"
131 #include "chrome/browser/media_galleries/media_file_system_registry.h"
132 #include "chrome/browser/ui/apps/chrome_app_window_client.h"
133 #include "components/storage_monitor/storage_monitor.h"
134 #include "extensions/common/extension_l10n_util.h"
137 #if !defined(DISABLE_NACL)
138 #include "chrome/browser/component_updater/pnacl_component_installer.h"
141 #if defined(ENABLE_PLUGIN_INSTALLATION)
142 #include "chrome/browser/plugins/plugins_resource_service.h"
145 #if defined(ENABLE_WEBRTC)
146 #include "chrome/browser/media/webrtc_log_uploader.h"
149 #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS)
150 #include "chrome/browser/memory/oom_priority_manager.h"
153 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
154 // How often to check if the persistent instance of Chrome needs to restart
155 // to install an update.
156 static const int kUpdateCheckIntervalHours
= 6;
159 #if defined(USE_X11) || defined(OS_WIN) || defined(USE_OZONE)
160 // How long to wait for the File thread to complete during EndSession, on Linux
161 // and Windows. We have a timeout here because we're unable to run the UI
162 // messageloop and there's some deadlock risk. Our only option is to exit
164 static const int kEndSessionTimeoutSeconds
= 10;
167 using content::BrowserThread
;
168 using content::ChildProcessSecurityPolicy
;
169 using content::PluginService
;
170 using content::ResourceDispatcherHost
;
172 BrowserProcessImpl::BrowserProcessImpl(
173 base::SequencedTaskRunner
* local_state_task_runner
,
174 const base::CommandLine
& command_line
)
175 : created_watchdog_thread_(false),
176 created_browser_policy_connector_(false),
177 created_profile_manager_(false),
178 created_local_state_(false),
179 created_icon_manager_(false),
180 created_notification_ui_manager_(false),
181 created_safe_browsing_service_(false),
182 module_ref_count_(0),
184 download_status_updater_(new DownloadStatusUpdater
),
185 local_state_task_runner_(local_state_task_runner
),
186 cached_default_web_client_state_(ShellIntegration::UNKNOWN_DEFAULT
) {
187 g_browser_process
= this;
188 platform_part_
.reset(new BrowserProcessPlatformPart());
190 #if defined(ENABLE_PRINTING)
191 // Must be created after the NotificationService.
192 print_job_manager_
.reset(new printing::PrintJobManager
);
195 net_log_
.reset(new ChromeNetLog
);
197 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
198 extensions::kExtensionScheme
);
199 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
200 extensions::kExtensionResourceScheme
);
201 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
202 chrome::kChromeSearchScheme
);
204 #if defined(OS_MACOSX)
205 ui::InitIdleMonitor();
208 #if !defined(OS_ANDROID)
209 device_client_
.reset(new ChromeDeviceClient
);
212 #if defined(ENABLE_EXTENSIONS)
213 // Athena sets its own instance during Athena's init process.
214 extensions::AppWindowClient::Set(ChromeAppWindowClient::GetInstance());
216 extension_event_router_forwarder_
= new extensions::EventRouterForwarder
;
217 ExtensionRendererState::GetInstance()->Init();
219 extensions::ExtensionsClient::Set(
220 extensions::ChromeExtensionsClient::GetInstance());
222 extensions_browser_client_
.reset(
223 new extensions::ChromeExtensionsBrowserClient
);
224 extensions::ExtensionsBrowserClient::Set(extensions_browser_client_
.get());
227 message_center::MessageCenter::Initialize();
229 update_client::UpdateQueryParams::SetDelegate(
230 ChromeUpdateQueryParamsDelegate::GetInstance());
233 BrowserProcessImpl::~BrowserProcessImpl() {
234 tracked_objects::ThreadData::EnsureCleanupWasCalled(4);
236 g_browser_process
= NULL
;
239 void BrowserProcessImpl::StartTearDown() {
240 TRACE_EVENT0("shutdown", "BrowserProcessImpl::StartTearDown");
241 // We need to destroy the MetricsServicesManager, IntranetRedirectDetector,
242 // PromoResourceService, and SafeBrowsing ClientSideDetectionService (owned by
243 // the SafeBrowsingService) before the io_thread_ gets destroyed, since their
244 // destructors can call the URLFetcher destructor, which does a
245 // PostDelayedTask operation on the IO thread. (The IO thread will handle that
246 // URLFetcher operation before going away.)
247 metrics_services_manager_
.reset();
248 intranet_redirect_detector_
.reset();
249 #if defined(SAFE_BROWSING_SERVICE)
250 if (safe_browsing_service_
.get())
251 safe_browsing_service()->ShutDown();
253 #if defined(ENABLE_PLUGIN_INSTALLATION)
254 plugins_resource_service_
.reset();
257 // Need to clear the desktop notification balloons before the io_thread_ and
258 // before the profiles, since if there are any still showing we will access
259 // those things during teardown.
260 notification_ui_manager_
.reset();
262 // The SupervisedUserWhitelistInstaller observes the ProfileInfoCache, so it
263 // needs to be shut down before the ProfileManager.
264 supervised_user_whitelist_installer_
.reset();
266 #if !defined(OS_ANDROID)
267 // Debugger must be cleaned up before ProfileManager.
268 remote_debugging_server_
.reset();
271 // Need to clear profiles (download managers) before the io_thread_.
273 TRACE_EVENT0("shutdown",
274 "BrowserProcessImpl::StartTearDown:ProfileManager");
275 // The desktop User Manager needs to be closed before the guest profile
277 if (switches::IsNewAvatarMenu())
279 profile_manager_
.reset();
282 // PromoResourceService must be destroyed after the keyed services and before
284 promo_resource_service_
.reset();
286 child_process_watcher_
.reset();
288 #if defined(ENABLE_EXTENSIONS)
289 ExtensionRendererState::GetInstance()->Shutdown();
291 media_file_system_registry_
.reset();
292 // Remove the global instance of the Storage Monitor now. Otherwise the
293 // FILE thread would be gone when we try to release it in the dtor and
294 // Valgrind would report a leak on almost every single browser_test.
295 // TODO(gbillock): Make this unnecessary.
296 storage_monitor::StorageMonitor::Destroy();
299 message_center::MessageCenter::Shutdown();
301 #if defined(ENABLE_CONFIGURATION_POLICY)
302 // The policy providers managed by |browser_policy_connector_| need to shut
303 // down while the IO and FILE threads are still alive. The monitoring
304 // framework owned by |browser_policy_connector_| relies on |gcm_driver_|, so
305 // this must be shutdown before |gcm_driver_| below.
306 if (browser_policy_connector_
)
307 browser_policy_connector_
->Shutdown();
310 // The |gcm_driver_| must shut down while the IO thread is still alive.
312 gcm_driver_
->Shutdown();
314 // Stop the watchdog thread before stopping other threads.
315 watchdog_thread_
.reset();
317 platform_part()->StartTearDown();
319 #if defined(ENABLE_WEBRTC)
320 // Cancel any uploads to release the system url request context references.
321 if (webrtc_log_uploader_
)
322 webrtc_log_uploader_
->StartShutdown();
326 local_state()->CommitPendingWrite();
329 void BrowserProcessImpl::PostDestroyThreads() {
330 // With the file_thread_ flushed, we can release any icon resources.
331 icon_manager_
.reset();
333 #if defined(ENABLE_WEBRTC)
334 // Must outlive the file thread.
335 webrtc_log_uploader_
.reset();
338 // Reset associated state right after actual thread is stopped,
339 // as io_thread_.global_ cleanup happens in CleanUp on the IO
340 // thread, i.e. as the thread exits its message loop.
342 // This is important also because in various places, the
343 // IOThread object being NULL is considered synonymous with the
344 // IO thread having stopped.
348 unsigned int BrowserProcessImpl::AddRefModule() {
349 DCHECK(CalledOnValidThread());
351 // CHECK(!IsShuttingDown());
352 if (IsShuttingDown()) {
353 // Copy the stacktrace which released the final reference onto our stack so
354 // it will be available in the crash report for inspection.
355 base::debug::StackTrace callstack
= release_last_reference_callstack_
;
356 base::debug::Alias(&callstack
);
362 return module_ref_count_
;
365 unsigned int BrowserProcessImpl::ReleaseModule() {
366 DCHECK(CalledOnValidThread());
367 DCHECK_NE(0u, module_ref_count_
);
369 if (0 == module_ref_count_
) {
370 release_last_reference_callstack_
= base::debug::StackTrace();
372 #if defined(ENABLE_PRINTING)
373 // Wait for the pending print jobs to finish. Don't do this later, since
374 // this might cause a nested message loop to run, and we don't want pending
375 // tasks to run once teardown has started.
376 print_job_manager_
->Shutdown();
379 #if defined(LEAK_SANITIZER)
380 // Check for memory leaks now, before we start shutting down threads. Doing
381 // this early means we won't report any shutdown-only leaks (as they have
382 // not yet happened at this point).
383 // If leaks are found, this will make the process exit immediately.
384 __lsan_do_leak_check();
387 CHECK(base::MessageLoop::current()->is_running());
389 #if defined(OS_MACOSX)
390 base::MessageLoop::current()->PostTask(
392 base::Bind(ChromeBrowserMainPartsMac::DidEndMainMessageLoop
));
394 base::MessageLoop::current()->Quit();
396 return module_ref_count_
;
401 // Used at the end of session to block the UI thread for completion of sentinel
402 // tasks on the set of threads used to persist profile data and local state.
403 // This is done to ensure that the data has been persisted to disk before
405 class RundownTaskCounter
:
406 public base::RefCountedThreadSafe
<RundownTaskCounter
> {
408 RundownTaskCounter();
410 // Posts a rundown task to |task_runner|, can be invoked an arbitrary number
411 // of times before calling TimedWait.
412 void Post(base::SequencedTaskRunner
* task_runner
);
414 // Waits until the count is zero or |max_time| has passed.
415 // This can only be called once per instance.
416 bool TimedWait(const base::TimeDelta
& max_time
);
419 friend class base::RefCountedThreadSafe
<RundownTaskCounter
>;
420 ~RundownTaskCounter() {}
422 // Decrements the counter and releases the waitable event on transition to
426 // The count starts at one to defer the possibility of one->zero transitions
427 // until TimedWait is called.
428 base::AtomicRefCount count_
;
429 base::WaitableEvent waitable_event_
;
431 DISALLOW_COPY_AND_ASSIGN(RundownTaskCounter
);
434 RundownTaskCounter::RundownTaskCounter()
435 : count_(1), waitable_event_(true, false) {
438 void RundownTaskCounter::Post(base::SequencedTaskRunner
* task_runner
) {
439 // As the count starts off at one, it should never get to zero unless
440 // TimedWait has been called.
441 DCHECK(!base::AtomicRefCountIsZero(&count_
));
443 base::AtomicRefCountInc(&count_
);
445 // The task must be non-nestable to guarantee that it runs after all tasks
446 // currently scheduled on |task_runner| have completed.
447 task_runner
->PostNonNestableTask(FROM_HERE
,
448 base::Bind(&RundownTaskCounter::Decrement
, this));
451 void RundownTaskCounter::Decrement() {
452 if (!base::AtomicRefCountDec(&count_
))
453 waitable_event_
.Signal();
456 bool RundownTaskCounter::TimedWait(const base::TimeDelta
& max_time
) {
457 // Decrement the excess count from the constructor.
460 return waitable_event_
.TimedWait(max_time
);
465 void BrowserProcessImpl::EndSession() {
466 // Mark all the profiles as clean.
467 ProfileManager
* pm
= profile_manager();
468 std::vector
<Profile
*> profiles(pm
->GetLoadedProfiles());
469 scoped_refptr
<RundownTaskCounter
> rundown_counter(new RundownTaskCounter());
470 for (size_t i
= 0; i
< profiles
.size(); ++i
) {
471 Profile
* profile
= profiles
[i
];
472 profile
->SetExitType(Profile::EXIT_SESSION_ENDED
);
473 if (profile
->GetPrefs()) {
474 profile
->GetPrefs()->CommitPendingWrite();
475 rundown_counter
->Post(profile
->GetIOTaskRunner().get());
479 // Tell the metrics service it was cleanly shutdown.
480 metrics::MetricsService
* metrics
= g_browser_process
->metrics_service();
481 if (metrics
&& local_state()) {
482 metrics
->RecordStartOfSessionEnd();
483 #if !defined(OS_CHROMEOS)
484 // MetricsService lazily writes to prefs, force it to write now.
485 // On ChromeOS, chrome gets killed when hangs, so no need to
486 // commit metrics::prefs::kStabilitySessionEndCompleted change immediately.
487 local_state()->CommitPendingWrite();
489 rundown_counter
->Post(local_state_task_runner_
.get());
493 // http://crbug.com/125207
494 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
496 // We must write that the profile and metrics service shutdown cleanly,
497 // otherwise on startup we'll think we crashed. So we block until done and
498 // then proceed with normal shutdown.
500 // If you change the condition here, be sure to also change
501 // ProfileBrowserTests to match.
502 #if defined(USE_X11) || defined(OS_WIN) || defined(USE_OZONE)
503 // Do a best-effort wait on the successful countdown of rundown tasks. Note
504 // that if we don't complete "quickly enough", Windows will terminate our
507 // On Windows, we previously posted a message to FILE and then ran a nested
508 // message loop, waiting for that message to be processed until quitting.
509 // However, doing so means that other messages will also be processed. In
510 // particular, if the GPU process host notices that the GPU has been killed
511 // during shutdown, it races exiting the nested loop with the process host
512 // blocking the message loop attempting to re-establish a connection to the
513 // GPU process synchronously. Because the system may not be allowing
514 // processes to launch, this can result in a hang. See
515 // http://crbug.com/318527.
516 rundown_counter
->TimedWait(
517 base::TimeDelta::FromSeconds(kEndSessionTimeoutSeconds
));
523 MetricsServicesManager
* BrowserProcessImpl::GetMetricsServicesManager() {
524 DCHECK(CalledOnValidThread());
525 if (!metrics_services_manager_
)
526 metrics_services_manager_
.reset(new MetricsServicesManager(local_state()));
527 return metrics_services_manager_
.get();
530 metrics::MetricsService
* BrowserProcessImpl::metrics_service() {
531 DCHECK(CalledOnValidThread());
532 return GetMetricsServicesManager()->GetMetricsService();
535 rappor::RapporService
* BrowserProcessImpl::rappor_service() {
536 DCHECK(CalledOnValidThread());
537 return GetMetricsServicesManager()->GetRapporService();
540 IOThread
* BrowserProcessImpl::io_thread() {
541 DCHECK(CalledOnValidThread());
542 DCHECK(io_thread_
.get());
543 return io_thread_
.get();
546 WatchDogThread
* BrowserProcessImpl::watchdog_thread() {
547 DCHECK(CalledOnValidThread());
548 if (!created_watchdog_thread_
)
549 CreateWatchdogThread();
550 DCHECK(watchdog_thread_
.get() != NULL
);
551 return watchdog_thread_
.get();
554 ProfileManager
* BrowserProcessImpl::profile_manager() {
555 DCHECK(CalledOnValidThread());
556 if (!created_profile_manager_
)
557 CreateProfileManager();
558 return profile_manager_
.get();
561 PrefService
* BrowserProcessImpl::local_state() {
562 DCHECK(CalledOnValidThread());
563 if (!created_local_state_
)
565 return local_state_
.get();
568 net::URLRequestContextGetter
* BrowserProcessImpl::system_request_context() {
569 DCHECK(CalledOnValidThread());
570 return io_thread()->system_url_request_context_getter();
573 variations::VariationsService
* BrowserProcessImpl::variations_service() {
574 DCHECK(CalledOnValidThread());
575 return GetMetricsServicesManager()->GetVariationsService();
578 web_resource::PromoResourceService
*
579 BrowserProcessImpl::promo_resource_service() {
580 DCHECK(CalledOnValidThread());
581 return promo_resource_service_
.get();
584 BrowserProcessPlatformPart
* BrowserProcessImpl::platform_part() {
585 return platform_part_
.get();
588 extensions::EventRouterForwarder
*
589 BrowserProcessImpl::extension_event_router_forwarder() {
590 #if defined(ENABLE_EXTENSIONS)
591 return extension_event_router_forwarder_
.get();
597 NotificationUIManager
* BrowserProcessImpl::notification_ui_manager() {
598 DCHECK(CalledOnValidThread());
599 if (!created_notification_ui_manager_
)
600 CreateNotificationUIManager();
601 return notification_ui_manager_
.get();
604 message_center::MessageCenter
* BrowserProcessImpl::message_center() {
605 DCHECK(CalledOnValidThread());
606 return message_center::MessageCenter::Get();
609 policy::BrowserPolicyConnector
* BrowserProcessImpl::browser_policy_connector() {
610 DCHECK(CalledOnValidThread());
611 #if defined(ENABLE_CONFIGURATION_POLICY)
612 if (!created_browser_policy_connector_
) {
613 DCHECK(!browser_policy_connector_
);
614 browser_policy_connector_
= platform_part_
->CreateBrowserPolicyConnector();
615 created_browser_policy_connector_
= true;
617 return browser_policy_connector_
.get();
623 policy::PolicyService
* BrowserProcessImpl::policy_service() {
624 #if defined(ENABLE_CONFIGURATION_POLICY)
625 return browser_policy_connector()->GetPolicyService();
627 if (!policy_service_
.get())
628 policy_service_
.reset(new policy::PolicyServiceStub());
629 return policy_service_
.get();
633 IconManager
* BrowserProcessImpl::icon_manager() {
634 DCHECK(CalledOnValidThread());
635 if (!created_icon_manager_
)
637 return icon_manager_
.get();
640 GLStringManager
* BrowserProcessImpl::gl_string_manager() {
641 DCHECK(CalledOnValidThread());
642 if (!gl_string_manager_
.get())
643 gl_string_manager_
.reset(new GLStringManager());
644 return gl_string_manager_
.get();
647 GpuModeManager
* BrowserProcessImpl::gpu_mode_manager() {
648 DCHECK(CalledOnValidThread());
649 if (!gpu_mode_manager_
.get())
650 gpu_mode_manager_
.reset(new GpuModeManager());
651 return gpu_mode_manager_
.get();
654 void BrowserProcessImpl::CreateDevToolsHttpProtocolHandler(
655 chrome::HostDesktopType host_desktop_type
,
656 const std::string
& ip
,
658 DCHECK(CalledOnValidThread());
659 #if !defined(OS_ANDROID)
660 // StartupBrowserCreator::LaunchBrowser can be run multiple times when browser
661 // is started with several profiles or existing browser process is reused.
662 if (!remote_debugging_server_
.get()) {
663 remote_debugging_server_
.reset(
664 new RemoteDebuggingServer(host_desktop_type
, ip
, port
));
669 bool BrowserProcessImpl::IsShuttingDown() {
670 DCHECK(CalledOnValidThread());
671 return did_start_
&& 0 == module_ref_count_
;
674 printing::PrintJobManager
* BrowserProcessImpl::print_job_manager() {
675 DCHECK(CalledOnValidThread());
676 return print_job_manager_
.get();
679 printing::PrintPreviewDialogController
*
680 BrowserProcessImpl::print_preview_dialog_controller() {
681 #if defined(ENABLE_PRINT_PREVIEW)
682 DCHECK(CalledOnValidThread());
683 if (!print_preview_dialog_controller_
.get())
684 CreatePrintPreviewDialogController();
685 return print_preview_dialog_controller_
.get();
692 printing::BackgroundPrintingManager
*
693 BrowserProcessImpl::background_printing_manager() {
694 #if defined(ENABLE_PRINT_PREVIEW)
695 DCHECK(CalledOnValidThread());
696 if (!background_printing_manager_
.get())
697 CreateBackgroundPrintingManager();
698 return background_printing_manager_
.get();
705 IntranetRedirectDetector
* BrowserProcessImpl::intranet_redirect_detector() {
706 DCHECK(CalledOnValidThread());
707 if (!intranet_redirect_detector_
.get())
708 CreateIntranetRedirectDetector();
709 return intranet_redirect_detector_
.get();
712 const std::string
& BrowserProcessImpl::GetApplicationLocale() {
713 DCHECK(!locale_
.empty());
717 void BrowserProcessImpl::SetApplicationLocale(const std::string
& locale
) {
719 #if defined(ENABLE_EXTENSIONS)
720 extension_l10n_util::SetProcessLocale(locale
);
722 ChromeContentBrowserClient::SetApplicationLocale(locale
);
723 translate::TranslateDownloadManager::GetInstance()->set_application_locale(
727 DownloadStatusUpdater
* BrowserProcessImpl::download_status_updater() {
728 return download_status_updater_
.get();
731 MediaFileSystemRegistry
* BrowserProcessImpl::media_file_system_registry() {
732 #if defined(ENABLE_EXTENSIONS)
733 if (!media_file_system_registry_
)
734 media_file_system_registry_
.reset(new MediaFileSystemRegistry());
735 return media_file_system_registry_
.get();
741 bool BrowserProcessImpl::created_local_state() const {
742 return created_local_state_
;
745 #if defined(ENABLE_WEBRTC)
746 WebRtcLogUploader
* BrowserProcessImpl::webrtc_log_uploader() {
747 if (!webrtc_log_uploader_
.get())
748 webrtc_log_uploader_
.reset(new WebRtcLogUploader());
749 return webrtc_log_uploader_
.get();
753 network_time::NetworkTimeTracker
* BrowserProcessImpl::network_time_tracker() {
754 if (!network_time_tracker_
) {
755 network_time_tracker_
.reset(new network_time::NetworkTimeTracker(
756 scoped_ptr
<base::TickClock
>(new base::DefaultTickClock()),
759 return network_time_tracker_
.get();
762 gcm::GCMDriver
* BrowserProcessImpl::gcm_driver() {
763 DCHECK(CalledOnValidThread());
766 return gcm_driver_
.get();
769 memory::OomPriorityManager
* BrowserProcessImpl::GetOomPriorityManager() {
770 DCHECK(CalledOnValidThread());
771 #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS)
772 if (!oom_priority_manager_
.get())
773 oom_priority_manager_
.reset(new memory::OomPriorityManager());
774 return oom_priority_manager_
.get();
780 ShellIntegration::DefaultWebClientState
781 BrowserProcessImpl::CachedDefaultWebClientState() {
782 return cached_default_web_client_state_
;
786 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple
* registry
) {
787 registry
->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled
,
789 // This policy needs to be defined before the net subsystem is initialized,
791 registry
->RegisterIntegerPref(prefs::kMaxConnectionsPerProxy
,
792 net::kDefaultMaxSocketsPerProxyServer
);
794 registry
->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt
, false);
796 #if defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
797 registry
->RegisterBooleanPref(prefs::kEulaAccepted
, false);
798 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
800 if (base::win::GetVersion() >= base::win::VERSION_WIN7
) {
801 registry
->RegisterStringPref(prefs::kRelaunchMode
,
802 upgrade_util::kRelaunchModeDefault
);
806 // TODO(brettw,*): this comment about ResourceBundle was here since
807 // initial commit. This comment seems unrelated, bit-rotten and
808 // a candidate for removal.
809 // Initialize ResourceBundle which handles files loaded from external
810 // sources. This has to be done before uninstall code path and before prefs
812 registry
->RegisterStringPref(prefs::kApplicationLocale
, std::string());
813 #if defined(OS_CHROMEOS)
814 registry
->RegisterStringPref(prefs::kOwnerLocale
, std::string());
815 registry
->RegisterStringPref(prefs::kHardwareKeyboardLayout
,
817 #endif // defined(OS_CHROMEOS)
818 #if !defined(OS_CHROMEOS)
819 registry
->RegisterBooleanPref(
820 prefs::kMetricsReportingEnabled
,
821 GoogleUpdateSettings::GetCollectStatsConsent());
822 #endif // !defined(OS_CHROMEOS)
824 #if defined(OS_ANDROID)
825 registry
->RegisterBooleanPref(
826 prefs::kCrashReportingEnabled
, false);
827 #endif // defined(OS_ANDROID)
830 DownloadRequestLimiter
* BrowserProcessImpl::download_request_limiter() {
831 DCHECK(CalledOnValidThread());
832 if (!download_request_limiter_
.get())
833 download_request_limiter_
= new DownloadRequestLimiter();
834 return download_request_limiter_
.get();
837 BackgroundModeManager
* BrowserProcessImpl::background_mode_manager() {
838 DCHECK(CalledOnValidThread());
839 #if defined(ENABLE_BACKGROUND)
840 if (!background_mode_manager_
.get())
841 CreateBackgroundModeManager();
842 return background_mode_manager_
.get();
849 void BrowserProcessImpl::set_background_mode_manager_for_test(
850 scoped_ptr
<BackgroundModeManager
> manager
) {
851 #if defined(ENABLE_BACKGROUND)
852 background_mode_manager_
= manager
.Pass();
856 StatusTray
* BrowserProcessImpl::status_tray() {
857 DCHECK(CalledOnValidThread());
858 if (!status_tray_
.get())
860 return status_tray_
.get();
864 SafeBrowsingService
* BrowserProcessImpl::safe_browsing_service() {
865 DCHECK(CalledOnValidThread());
866 if (!created_safe_browsing_service_
)
867 CreateSafeBrowsingService();
868 return safe_browsing_service_
.get();
871 safe_browsing::ClientSideDetectionService
*
872 BrowserProcessImpl::safe_browsing_detection_service() {
873 DCHECK(CalledOnValidThread());
874 if (safe_browsing_service())
875 return safe_browsing_service()->safe_browsing_detection_service();
879 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
880 void BrowserProcessImpl::StartAutoupdateTimer() {
881 autoupdate_timer_
.Start(FROM_HERE
,
882 base::TimeDelta::FromHours(kUpdateCheckIntervalHours
),
884 &BrowserProcessImpl::OnAutoupdateTimer
);
888 ChromeNetLog
* BrowserProcessImpl::net_log() {
889 return net_log_
.get();
892 component_updater::ComponentUpdateService
*
893 BrowserProcessImpl::component_updater() {
894 if (!component_updater_
.get()) {
895 if (!BrowserThread::CurrentlyOn(BrowserThread::UI
))
897 scoped_refptr
<update_client::Configurator
> configurator
=
898 component_updater::MakeChromeComponentUpdaterConfigurator(
899 base::CommandLine::ForCurrentProcess(),
900 io_thread()->system_url_request_context_getter());
901 // Creating the component updater does not do anything, components
902 // need to be registered and Start() needs to be called.
903 component_updater_
.reset(component_updater::ComponentUpdateServiceFactory(
904 configurator
).release());
906 return component_updater_
.get();
909 CRLSetFetcher
* BrowserProcessImpl::crl_set_fetcher() {
910 if (!crl_set_fetcher_
)
911 crl_set_fetcher_
= new CRLSetFetcher();
912 return crl_set_fetcher_
.get();
915 component_updater::PnaclComponentInstaller
*
916 BrowserProcessImpl::pnacl_component_installer() {
917 #if !defined(DISABLE_NACL)
918 if (!pnacl_component_installer_
) {
919 pnacl_component_installer_
=
920 new component_updater::PnaclComponentInstaller();
922 return pnacl_component_installer_
.get();
928 component_updater::SupervisedUserWhitelistInstaller
*
929 BrowserProcessImpl::supervised_user_whitelist_installer() {
930 if (!supervised_user_whitelist_installer_
) {
931 supervised_user_whitelist_installer_
=
932 component_updater::SupervisedUserWhitelistInstaller::Create(
933 component_updater(), &profile_manager()->GetProfileInfoCache(),
936 return supervised_user_whitelist_installer_
.get();
939 void BrowserProcessImpl::ResourceDispatcherHostCreated() {
940 resource_dispatcher_host_delegate_
.reset(
941 new ChromeResourceDispatcherHostDelegate
);
942 ResourceDispatcherHost::Get()->SetDelegate(
943 resource_dispatcher_host_delegate_
.get());
945 pref_change_registrar_
.Add(
946 prefs::kAllowCrossOriginAuthPrompt
,
947 base::Bind(&BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy
,
948 base::Unretained(this)));
949 ApplyAllowCrossOriginAuthPromptPolicy();
952 void BrowserProcessImpl::CreateWatchdogThread() {
953 DCHECK(!created_watchdog_thread_
&& watchdog_thread_
.get() == NULL
);
954 created_watchdog_thread_
= true;
956 scoped_ptr
<WatchDogThread
> thread(new WatchDogThread());
957 base::Thread::Options options
;
958 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
959 if (!thread
->StartWithOptions(options
))
961 watchdog_thread_
.swap(thread
);
964 void BrowserProcessImpl::CreateProfileManager() {
965 DCHECK(!created_profile_manager_
&& profile_manager_
.get() == NULL
);
966 created_profile_manager_
= true;
968 base::FilePath user_data_dir
;
969 PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
);
970 profile_manager_
.reset(new ProfileManager(user_data_dir
));
973 void BrowserProcessImpl::CreateLocalState() {
974 DCHECK(!created_local_state_
&& local_state_
.get() == NULL
);
975 created_local_state_
= true;
977 base::FilePath local_state_path
;
978 CHECK(PathService::Get(chrome::FILE_LOCAL_STATE
, &local_state_path
));
979 scoped_refptr
<PrefRegistrySimple
> pref_registry
= new PrefRegistrySimple
;
981 // Register local state preferences.
982 chrome::RegisterLocalState(pref_registry
.get());
985 chrome_prefs::CreateLocalState(local_state_path
,
986 local_state_task_runner_
.get(),
991 pref_change_registrar_
.Init(local_state_
.get());
993 // Initialize the notification for the default browser setting policy.
994 pref_change_registrar_
.Add(
995 prefs::kDefaultBrowserSettingEnabled
,
996 base::Bind(&BrowserProcessImpl::ApplyDefaultBrowserPolicy
,
997 base::Unretained(this)));
999 // This preference must be kept in sync with external values; update them
1000 // whenever the preference or its controlling policy changes.
1001 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1002 pref_change_registrar_
.Add(
1003 prefs::kMetricsReportingEnabled
,
1004 base::Bind(&BrowserProcessImpl::ApplyMetricsReportingPolicy
,
1005 base::Unretained(this)));
1008 int max_per_proxy
= local_state_
->GetInteger(prefs::kMaxConnectionsPerProxy
);
1009 net::ClientSocketPoolManager::set_max_sockets_per_proxy_server(
1010 net::HttpNetworkSession::NORMAL_SOCKET_POOL
,
1011 std::max(std::min(max_per_proxy
, 99),
1012 net::ClientSocketPoolManager::max_sockets_per_group(
1013 net::HttpNetworkSession::NORMAL_SOCKET_POOL
)));
1016 void BrowserProcessImpl::PreCreateThreads() {
1018 new IOThread(local_state(), policy_service(), net_log_
.get(),
1019 extension_event_router_forwarder()));
1022 void BrowserProcessImpl::PreMainMessageLoopRun() {
1023 TRACE_EVENT0("startup", "BrowserProcessImpl::PreMainMessageLoopRun");
1024 SCOPED_UMA_HISTOGRAM_TIMER(
1025 "Startup.BrowserProcessImpl_PreMainMessageLoopRunTime");
1027 #if defined(ENABLE_CONFIGURATION_POLICY)
1028 // browser_policy_connector() is created very early because local_state()
1029 // needs policy to be initialized with the managed preference values.
1030 // However, policy fetches from the network and loading of disk caches
1031 // requires that threads are running; this Init() call lets the connector
1032 // resume its initialization now that the loops are spinning and the
1033 // system request context is available for the fetchers.
1034 browser_policy_connector()->Init(local_state(), system_request_context());
1037 if (local_state_
->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled
))
1038 ApplyDefaultBrowserPolicy();
1040 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1041 ApplyMetricsReportingPolicy();
1044 #if defined(ENABLE_PLUGINS)
1045 PluginService
* plugin_service
= PluginService::GetInstance();
1046 plugin_service
->SetFilter(ChromePluginServiceFilter::GetInstance());
1047 plugin_service
->StartWatchingPlugins();
1049 #if defined(OS_POSIX)
1050 // Also find plugins in a user-specific plugins dir,
1051 // e.g. ~/.config/chromium/Plugins.
1052 const base::CommandLine
& cmd_line
= *base::CommandLine::ForCurrentProcess();
1053 if (!cmd_line
.HasSwitch(switches::kDisablePluginsDiscovery
)) {
1054 base::FilePath user_data_dir
;
1055 if (PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
))
1056 plugin_service
->AddExtraPluginDir(user_data_dir
.Append("Plugins"));
1060 // Triggers initialization of the singleton instance on UI thread.
1061 PluginFinder::GetInstance()->Init();
1063 #if defined(ENABLE_PLUGIN_INSTALLATION)
1064 DCHECK(!plugins_resource_service_
.get());
1065 plugins_resource_service_
.reset(new PluginsResourceService(local_state()));
1066 plugins_resource_service_
->Init();
1068 #endif // defined(ENABLE_PLUGINS)
1070 const base::CommandLine
& command_line
=
1071 *base::CommandLine::ForCurrentProcess();
1072 if (!command_line
.HasSwitch(switches::kDisableWebResources
)) {
1073 DCHECK(!promo_resource_service_
.get());
1074 promo_resource_service_
.reset(new web_resource::PromoResourceService(
1075 local_state(), chrome::GetChannel(), GetApplicationLocale(),
1076 system_request_context(), switches::kDisableBackgroundNetworking
,
1077 base::Bind(safe_json::SafeJsonParser::Parse
)));
1078 promo_resource_service_
->StartAfterDelay();
1081 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1082 storage_monitor::StorageMonitor::Create();
1085 child_process_watcher_
.reset(new ChromeChildProcessWatcher());
1087 CacheDefaultWebClientState();
1089 platform_part_
->PreMainMessageLoopRun();
1092 void BrowserProcessImpl::CreateIconManager() {
1093 DCHECK(!created_icon_manager_
&& icon_manager_
.get() == NULL
);
1094 created_icon_manager_
= true;
1095 icon_manager_
.reset(new IconManager
);
1098 void BrowserProcessImpl::CreateIntranetRedirectDetector() {
1099 DCHECK(intranet_redirect_detector_
.get() == NULL
);
1100 scoped_ptr
<IntranetRedirectDetector
> intranet_redirect_detector(
1101 new IntranetRedirectDetector
);
1102 intranet_redirect_detector_
.swap(intranet_redirect_detector
);
1105 void BrowserProcessImpl::CreateNotificationUIManager() {
1106 #if defined(ENABLE_NOTIFICATIONS)
1107 DCHECK(notification_ui_manager_
.get() == NULL
);
1108 notification_ui_manager_
.reset(NotificationUIManager::Create(local_state()));
1109 created_notification_ui_manager_
= true;
1113 void BrowserProcessImpl::CreateBackgroundModeManager() {
1114 #if defined(ENABLE_BACKGROUND)
1115 DCHECK(background_mode_manager_
.get() == NULL
);
1116 background_mode_manager_
.reset(
1117 new BackgroundModeManager(*base::CommandLine::ForCurrentProcess(),
1118 &profile_manager()->GetProfileInfoCache()));
1122 void BrowserProcessImpl::CreateStatusTray() {
1123 DCHECK(status_tray_
.get() == NULL
);
1124 status_tray_
.reset(StatusTray::Create());
1127 void BrowserProcessImpl::CreatePrintPreviewDialogController() {
1128 #if defined(ENABLE_PRINT_PREVIEW)
1129 DCHECK(print_preview_dialog_controller_
.get() == NULL
);
1130 print_preview_dialog_controller_
=
1131 new printing::PrintPreviewDialogController();
1137 void BrowserProcessImpl::CreateBackgroundPrintingManager() {
1138 #if defined(ENABLE_PRINT_PREVIEW)
1139 DCHECK(background_printing_manager_
.get() == NULL
);
1140 background_printing_manager_
.reset(new printing::BackgroundPrintingManager());
1146 void BrowserProcessImpl::CreateSafeBrowsingService() {
1147 DCHECK(safe_browsing_service_
.get() == NULL
);
1148 // Set this flag to true so that we don't retry indefinitely to
1149 // create the service class if there was an error.
1150 created_safe_browsing_service_
= true;
1151 #if defined(SAFE_BROWSING_SERVICE)
1152 safe_browsing_service_
= SafeBrowsingService::CreateSafeBrowsingService();
1153 safe_browsing_service_
->Initialize();
1157 void BrowserProcessImpl::CreateGCMDriver() {
1158 DCHECK(!gcm_driver_
);
1160 #if defined(OS_ANDROID)
1161 // Android's GCMDriver currently makes the assumption that it's a singleton.
1162 // Until this gets fixed, instantiating multiple Java GCMDrivers will throw
1163 // an exception, but because they're only initialized on demand these crashes
1164 // would be very difficult to triage. See http://crbug.com/437827.
1167 base::FilePath store_path
;
1168 CHECK(PathService::Get(chrome::DIR_GLOBAL_GCM_STORE
, &store_path
));
1169 gcm_driver_
= gcm::CreateGCMDriverDesktop(
1170 make_scoped_ptr(new gcm::GCMClientFactory
),
1173 system_request_context());
1174 #endif // defined(OS_ANDROID)
1177 void BrowserProcessImpl::ApplyDefaultBrowserPolicy() {
1178 if (local_state()->GetBoolean(prefs::kDefaultBrowserSettingEnabled
)) {
1179 scoped_refptr
<ShellIntegration::DefaultWebClientWorker
>
1180 set_browser_worker
= new ShellIntegration::DefaultBrowserWorker(NULL
);
1181 set_browser_worker
->StartSetAsDefault();
1185 void BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy() {
1186 bool value
= local_state()->GetBoolean(prefs::kAllowCrossOriginAuthPrompt
);
1187 ResourceDispatcherHost::Get()->SetAllowCrossOriginAuthPrompt(value
);
1190 void BrowserProcessImpl::ApplyMetricsReportingPolicy() {
1191 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1192 CHECK(BrowserThread::PostTask(
1193 BrowserThread::FILE, FROM_HERE
,
1195 base::IgnoreResult(&GoogleUpdateSettings::SetCollectStatsConsent
),
1196 ChromeMetricsServiceAccessor::IsMetricsAndCrashReportingEnabled())));
1200 void BrowserProcessImpl::CacheDefaultWebClientState() {
1201 #if defined(OS_CHROMEOS)
1202 cached_default_web_client_state_
= ShellIntegration::IS_DEFAULT
;
1203 #elif !defined(OS_ANDROID) && !defined(OS_IOS)
1204 cached_default_web_client_state_
= ShellIntegration::GetDefaultBrowser();
1208 // Mac is currently not supported.
1209 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
1211 bool BrowserProcessImpl::CanAutorestartForUpdate() const {
1212 // Check if browser is in the background and if it needs to be restarted to
1213 // apply a pending update.
1214 return chrome::GetTotalBrowserCount() == 0 && chrome::WillKeepAlive() &&
1215 upgrade_util::IsUpdatePendingRestart();
1218 // Switches to add when auto-restarting Chrome.
1219 const char* const kSwitchesToAddOnAutorestart
[] = {
1220 switches::kNoStartupWindow
1223 void BrowserProcessImpl::RestartBackgroundInstance() {
1224 base::CommandLine
* old_cl
= base::CommandLine::ForCurrentProcess();
1225 scoped_ptr
<base::CommandLine
> new_cl(
1226 new base::CommandLine(old_cl
->GetProgram()));
1228 std::map
<std::string
, base::CommandLine::StringType
> switches
=
1229 old_cl
->GetSwitches();
1231 switches::RemoveSwitchesForAutostart(&switches
);
1233 // Append the rest of the switches (along with their values, if any)
1234 // to the new command line
1235 for (std::map
<std::string
, base::CommandLine::StringType
>::const_iterator i
=
1237 i
!= switches
.end(); ++i
) {
1238 base::CommandLine::StringType switch_value
= i
->second
;
1239 if (switch_value
.length() > 0) {
1240 new_cl
->AppendSwitchNative(i
->first
, i
->second
);
1242 new_cl
->AppendSwitch(i
->first
);
1246 // Ensure that our desired switches are set on the new process.
1247 for (size_t i
= 0; i
< arraysize(kSwitchesToAddOnAutorestart
); ++i
) {
1248 if (!new_cl
->HasSwitch(kSwitchesToAddOnAutorestart
[i
]))
1249 new_cl
->AppendSwitch(kSwitchesToAddOnAutorestart
[i
]);
1252 DLOG(WARNING
) << "Shutting down current instance of the browser.";
1253 chrome::AttemptExit();
1255 // Transfer ownership to Upgrade.
1256 upgrade_util::SetNewCommandLine(new_cl
.release());
1259 void BrowserProcessImpl::OnAutoupdateTimer() {
1260 if (CanAutorestartForUpdate()) {
1261 DLOG(WARNING
) << "Detected update. Restarting browser.";
1262 RestartBackgroundInstance();
1266 #endif // (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)