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/path_service.h"
20 #include "base/prefs/json_pref_store.h"
21 #include "base/prefs/pref_registry_simple.h"
22 #include "base/prefs/pref_service.h"
23 #include "base/synchronization/waitable_event.h"
24 #include "base/threading/thread.h"
25 #include "base/threading/thread_restrictions.h"
26 #include "base/time/default_tick_clock.h"
27 #include "chrome/browser/chrome_browser_main.h"
28 #include "chrome/browser/chrome_content_browser_client.h"
29 #include "chrome/browser/chrome_notification_types.h"
30 #include "chrome/browser/component_updater/chrome_component_updater_configurator.h"
31 #include "chrome/browser/defaults.h"
32 #include "chrome/browser/devtools/remote_debugging_server.h"
33 #include "chrome/browser/download/download_request_limiter.h"
34 #include "chrome/browser/download/download_status_updater.h"
35 #include "chrome/browser/first_run/upgrade_util.h"
36 #include "chrome/browser/gpu/gl_string_manager.h"
37 #include "chrome/browser/gpu/gpu_mode_manager.h"
38 #include "chrome/browser/icon_manager.h"
39 #include "chrome/browser/idle.h"
40 #include "chrome/browser/intranet_redirect_detector.h"
41 #include "chrome/browser/io_thread.h"
42 #include "chrome/browser/lifetime/application_lifetime.h"
43 #include "chrome/browser/metrics/metrics_services_manager.h"
44 #include "chrome/browser/metrics/thread_watcher.h"
45 #include "chrome/browser/net/chrome_net_log.h"
46 #include "chrome/browser/net/crl_set_fetcher.h"
47 #include "chrome/browser/notifications/notification_ui_manager.h"
48 #include "chrome/browser/omaha_query_params/chrome_omaha_query_params_delegate.h"
49 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
50 #include "chrome/browser/plugins/plugin_finder.h"
51 #include "chrome/browser/prefs/browser_prefs.h"
52 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
53 #include "chrome/browser/prerender/prerender_tracker.h"
54 #include "chrome/browser/printing/background_printing_manager.h"
55 #include "chrome/browser/printing/print_job_manager.h"
56 #include "chrome/browser/printing/print_preview_dialog_controller.h"
57 #include "chrome/browser/profiles/profile_manager.h"
58 #include "chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h"
59 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
60 #include "chrome/browser/shell_integration.h"
61 #include "chrome/browser/status_icons/status_tray.h"
62 #include "chrome/browser/ui/browser_dialogs.h"
63 #include "chrome/browser/ui/browser_finder.h"
64 #include "chrome/browser/ui/user_manager.h"
65 #include "chrome/browser/web_resource/promo_resource_service.h"
66 #include "chrome/common/chrome_constants.h"
67 #include "chrome/common/chrome_paths.h"
68 #include "chrome/common/chrome_switches.h"
69 #include "chrome/common/extensions/chrome_extensions_client.h"
70 #include "chrome/common/pref_names.h"
71 #include "chrome/common/switch_utils.h"
72 #include "chrome/common/url_constants.h"
73 #include "chrome/installer/util/google_update_constants.h"
74 #include "chrome/installer/util/google_update_settings.h"
75 #include "components/component_updater/component_updater_service.h"
76 #include "components/gcm_driver/gcm_driver.h"
77 #include "components/metrics/metrics_service.h"
78 #include "components/network_time/network_time_tracker.h"
79 #include "components/omaha_query_params/omaha_query_params.h"
80 #include "components/policy/core/common/policy_service.h"
81 #include "components/signin/core/common/profile_management_switches.h"
82 #include "components/translate/core/browser/translate_download_manager.h"
83 #include "content/public/browser/browser_thread.h"
84 #include "content/public/browser/child_process_security_policy.h"
85 #include "content/public/browser/notification_details.h"
86 #include "content/public/browser/plugin_service.h"
87 #include "content/public/browser/render_process_host.h"
88 #include "content/public/browser/resource_dispatcher_host.h"
89 #include "content/public/browser/service_worker_context.h"
90 #include "content/public/browser/storage_partition.h"
91 #include "extensions/common/constants.h"
92 #include "net/socket/client_socket_pool_manager.h"
93 #include "net/url_request/url_request_context_getter.h"
94 #include "ui/base/l10n/l10n_util.h"
95 #include "ui/message_center/message_center.h"
98 #include "base/win/windows_version.h"
99 #include "ui/views/focus/view_storage.h"
100 #elif defined(OS_MACOSX)
101 #include "chrome/browser/chrome_browser_main_mac.h"
104 #if defined(OS_ANDROID)
105 #include "components/gcm_driver/gcm_driver_android.h"
107 #include "chrome/browser/chrome_device_client.h"
108 #include "chrome/browser/services/gcm/gcm_desktop_utils.h"
109 #include "components/gcm_driver/gcm_client_factory.h"
112 #if defined(USE_AURA)
113 #include "ui/aura/env.h"
116 #if defined(ENABLE_BACKGROUND)
117 #include "chrome/browser/background/background_mode_manager.h"
120 #if defined(ENABLE_CONFIGURATION_POLICY)
121 #include "components/policy/core/browser/browser_policy_connector.h"
123 #include "components/policy/core/common/policy_service_stub.h"
124 #endif // defined(ENABLE_CONFIGURATION_POLICY)
126 #if defined(ENABLE_EXTENSIONS)
127 #include "chrome/browser/extensions/chrome_extensions_browser_client.h"
128 #include "chrome/browser/extensions/event_router_forwarder.h"
129 #include "chrome/browser/extensions/extension_renderer_state.h"
130 #include "chrome/browser/media_galleries/media_file_system_registry.h"
131 #include "chrome/browser/ui/apps/chrome_app_window_client.h"
132 #include "components/storage_monitor/storage_monitor.h"
133 #include "extensions/common/extension_l10n_util.h"
136 #if !defined(DISABLE_NACL)
137 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
140 #if defined(ENABLE_PLUGIN_INSTALLATION)
141 #include "chrome/browser/plugins/plugins_resource_service.h"
144 #if defined(ENABLE_WEBRTC)
145 #include "chrome/browser/media/webrtc_log_uploader.h"
148 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
149 // How often to check if the persistent instance of Chrome needs to restart
150 // to install an update.
151 static const int kUpdateCheckIntervalHours = 6;
154 #if defined(USE_X11) || defined(OS_WIN)
155 // How long to wait for the File thread to complete during EndSession, on Linux
156 // and Windows. We have a timeout here because we're unable to run the UI
157 // messageloop and there's some deadlock risk. Our only option is to exit
159 static const int kEndSessionTimeoutSeconds = 10;
162 using content::BrowserThread;
163 using content::ChildProcessSecurityPolicy;
164 using content::PluginService;
165 using content::ResourceDispatcherHost;
167 BrowserProcessImpl::BrowserProcessImpl(
168 base::SequencedTaskRunner* local_state_task_runner,
169 const CommandLine& command_line)
170 : created_watchdog_thread_(false),
171 created_browser_policy_connector_(false),
172 created_profile_manager_(false),
173 created_local_state_(false),
174 created_icon_manager_(false),
175 created_notification_ui_manager_(false),
176 created_safe_browsing_service_(false),
177 module_ref_count_(0),
179 download_status_updater_(new DownloadStatusUpdater),
180 local_state_task_runner_(local_state_task_runner) {
181 g_browser_process = this;
182 platform_part_.reset(new BrowserProcessPlatformPart());
184 #if defined(ENABLE_PRINTING)
185 // Must be created after the NotificationService.
186 print_job_manager_.reset(new printing::PrintJobManager);
189 net_log_.reset(new ChromeNetLog);
191 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
192 extensions::kExtensionScheme);
193 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
194 extensions::kExtensionResourceScheme);
195 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
196 chrome::kChromeSearchScheme);
198 #if defined(OS_MACOSX)
202 #if !defined(OS_ANDROID)
203 device_client_.reset(new ChromeDeviceClient);
206 #if defined(ENABLE_EXTENSIONS)
207 #if !defined(USE_ATHENA)
208 // Athena sets its own instance during Athena's init process.
209 extensions::AppWindowClient::Set(ChromeAppWindowClient::GetInstance());
212 extension_event_router_forwarder_ = new extensions::EventRouterForwarder;
213 ExtensionRendererState::GetInstance()->Init();
215 extensions::ExtensionsClient::Set(
216 extensions::ChromeExtensionsClient::GetInstance());
218 extensions_browser_client_.reset(
219 new extensions::ChromeExtensionsBrowserClient);
220 extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get());
223 message_center::MessageCenter::Initialize();
225 omaha_query_params::OmahaQueryParams::SetDelegate(
226 ChromeOmahaQueryParamsDelegate::GetInstance());
229 BrowserProcessImpl::~BrowserProcessImpl() {
230 tracked_objects::ThreadData::EnsureCleanupWasCalled(4);
232 g_browser_process = NULL;
235 void BrowserProcessImpl::StartTearDown() {
236 TRACE_EVENT0("shutdown", "BrowserProcessImpl::StartTearDown");
237 // We need to destroy the MetricsServicesManager, IntranetRedirectDetector,
238 // PromoResourceService, and SafeBrowsing ClientSideDetectionService (owned by
239 // the SafeBrowsingService) before the io_thread_ gets destroyed, since their
240 // destructors can call the URLFetcher destructor, which does a
241 // PostDelayedTask operation on the IO thread. (The IO thread will handle that
242 // URLFetcher operation before going away.)
243 metrics_services_manager_.reset();
244 intranet_redirect_detector_.reset();
245 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
246 if (safe_browsing_service_.get())
247 safe_browsing_service()->ShutDown();
250 // Need to clear the desktop notification balloons before the io_thread_ and
251 // before the profiles, since if there are any still showing we will access
252 // those things during teardown.
253 notification_ui_manager_.reset();
255 // Need to clear profiles (download managers) before the io_thread_.
257 TRACE_EVENT0("shutdown",
258 "BrowserProcessImpl::StartTearDown:ProfileManager");
259 // The desktop User Manager needs to be closed before the guest profile
261 if (switches::IsNewAvatarMenu())
263 profile_manager_.reset();
266 #if !defined(OS_ANDROID)
267 // Debugger must be cleaned up before IO thread and NotificationService.
268 remote_debugging_server_.reset();
271 #if defined(ENABLE_EXTENSIONS)
272 ExtensionRendererState::GetInstance()->Shutdown();
274 media_file_system_registry_.reset();
275 // Remove the global instance of the Storage Monitor now. Otherwise the
276 // FILE thread would be gone when we try to release it in the dtor and
277 // Valgrind would report a leak on almost every single browser_test.
278 // TODO(gbillock): Make this unnecessary.
279 storage_monitor::StorageMonitor::Destroy();
282 message_center::MessageCenter::Shutdown();
284 #if defined(ENABLE_CONFIGURATION_POLICY)
285 // The policy providers managed by |browser_policy_connector_| need to shut
286 // down while the IO and FILE threads are still alive.
287 if (browser_policy_connector_)
288 browser_policy_connector_->Shutdown();
291 // The |gcm_driver_| must shut down while the IO thread is still alive.
293 gcm_driver_->Shutdown();
295 // Stop the watchdog thread before stopping other threads.
296 watchdog_thread_.reset();
298 #if defined(USE_AURA)
299 // Delete aura after the metrics service has been deleted as it accesses
300 // monitor information.
301 aura::Env::DeleteInstance();
304 platform_part()->StartTearDown();
306 #if defined(ENABLE_WEBRTC)
307 // Cancel any uploads to release the system url request context references.
308 if (webrtc_log_uploader_)
309 webrtc_log_uploader_->StartShutdown();
313 local_state()->CommitPendingWrite();
316 void BrowserProcessImpl::PostDestroyThreads() {
317 // With the file_thread_ flushed, we can release any icon resources.
318 icon_manager_.reset();
320 #if defined(ENABLE_WEBRTC)
321 // Must outlive the file thread.
322 webrtc_log_uploader_.reset();
325 // Reset associated state right after actual thread is stopped,
326 // as io_thread_.global_ cleanup happens in CleanUp on the IO
327 // thread, i.e. as the thread exits its message loop.
329 // This is important also because in various places, the
330 // IOThread object being NULL is considered synonymous with the
331 // IO thread having stopped.
335 unsigned int BrowserProcessImpl::AddRefModule() {
336 DCHECK(CalledOnValidThread());
338 // CHECK(!IsShuttingDown());
339 if (IsShuttingDown()) {
340 // Copy the stacktrace which released the final reference onto our stack so
341 // it will be available in the crash report for inspection.
342 base::debug::StackTrace callstack = release_last_reference_callstack_;
343 base::debug::Alias(&callstack);
349 return module_ref_count_;
352 unsigned int BrowserProcessImpl::ReleaseModule() {
353 DCHECK(CalledOnValidThread());
354 DCHECK_NE(0u, module_ref_count_);
356 if (0 == module_ref_count_) {
357 release_last_reference_callstack_ = base::debug::StackTrace();
359 #if defined(ENABLE_PRINTING)
360 // Wait for the pending print jobs to finish. Don't do this later, since
361 // this might cause a nested message loop to run, and we don't want pending
362 // tasks to run once teardown has started.
363 print_job_manager_->Shutdown();
366 #if defined(LEAK_SANITIZER)
367 // Check for memory leaks now, before we start shutting down threads. Doing
368 // this early means we won't report any shutdown-only leaks (as they have
369 // not yet happened at this point).
370 // If leaks are found, this will make the process exit immediately.
371 __lsan_do_leak_check();
374 CHECK(base::MessageLoop::current()->is_running());
376 #if defined(OS_MACOSX)
377 base::MessageLoop::current()->PostTask(
379 base::Bind(ChromeBrowserMainPartsMac::DidEndMainMessageLoop));
381 base::MessageLoop::current()->Quit();
383 return module_ref_count_;
388 // Used at the end of session to block the UI thread for completion of sentinel
389 // tasks on the set of threads used to persist profile data and local state.
390 // This is done to ensure that the data has been persisted to disk before
392 class RundownTaskCounter :
393 public base::RefCountedThreadSafe<RundownTaskCounter> {
395 RundownTaskCounter();
397 // Posts a rundown task to |task_runner|, can be invoked an arbitrary number
398 // of times before calling TimedWait.
399 void Post(base::SequencedTaskRunner* task_runner);
401 // Waits until the count is zero or |max_time| has passed.
402 // This can only be called once per instance.
403 bool TimedWait(const base::TimeDelta& max_time);
406 friend class base::RefCountedThreadSafe<RundownTaskCounter>;
407 ~RundownTaskCounter() {}
409 // Decrements the counter and releases the waitable event on transition to
413 // The count starts at one to defer the possibility of one->zero transitions
414 // until TimedWait is called.
415 base::AtomicRefCount count_;
416 base::WaitableEvent waitable_event_;
418 DISALLOW_COPY_AND_ASSIGN(RundownTaskCounter);
421 RundownTaskCounter::RundownTaskCounter()
422 : count_(1), waitable_event_(true, false) {
425 void RundownTaskCounter::Post(base::SequencedTaskRunner* task_runner) {
426 // As the count starts off at one, it should never get to zero unless
427 // TimedWait has been called.
428 DCHECK(!base::AtomicRefCountIsZero(&count_));
430 base::AtomicRefCountInc(&count_);
432 // The task must be non-nestable to guarantee that it runs after all tasks
433 // currently scheduled on |task_runner| have completed.
434 task_runner->PostNonNestableTask(FROM_HERE,
435 base::Bind(&RundownTaskCounter::Decrement, this));
438 void RundownTaskCounter::Decrement() {
439 if (!base::AtomicRefCountDec(&count_))
440 waitable_event_.Signal();
443 bool RundownTaskCounter::TimedWait(const base::TimeDelta& max_time) {
444 // Decrement the excess count from the constructor.
447 return waitable_event_.TimedWait(max_time);
450 bool ExperimentUseBrokenSynchronization() {
451 // The logoff behavior used to have a race, whereby it would perform profile
452 // IO writes on the blocking thread pool, but would sycnhronize to the FILE
453 // thread. Windows feels free to terminate any process that's hidden or
454 // destroyed all it's windows, and sometimes Chrome would be terminated
455 // with pending profile IO due to this mis-synchronization.
456 // Under the "WindowsLogoffRace" experiment group, the broken behavior is
457 // emulated, in order to allow measuring what fraction of unclean shutdowns
458 // are due to this bug.
459 const std::string group_name =
460 base::FieldTrialList::FindFullName("WindowsLogoffRace");
461 return group_name == "BrokenSynchronization";
466 void BrowserProcessImpl::EndSession() {
467 bool use_broken_synchronization = ExperimentUseBrokenSynchronization();
469 // Mark all the profiles as clean.
470 ProfileManager* pm = profile_manager();
471 std::vector<Profile*> profiles(pm->GetLoadedProfiles());
472 scoped_refptr<RundownTaskCounter> rundown_counter(new RundownTaskCounter());
473 for (size_t i = 0; i < profiles.size(); ++i) {
474 Profile* profile = profiles[i];
475 profile->SetExitType(Profile::EXIT_SESSION_ENDED);
477 if (!use_broken_synchronization)
478 rundown_counter->Post(profile->GetIOTaskRunner().get());
481 // Tell the metrics service it was cleanly shutdown.
482 metrics::MetricsService* metrics = g_browser_process->metrics_service();
483 if (metrics && local_state()) {
484 metrics->RecordStartOfSessionEnd();
485 #if !defined(OS_CHROMEOS)
486 // MetricsService lazily writes to prefs, force it to write now.
487 // On ChromeOS, chrome gets killed when hangs, so no need to
488 // commit metrics::prefs::kStabilitySessionEndCompleted change immediately.
489 local_state()->CommitPendingWrite();
491 if (!use_broken_synchronization)
492 rundown_counter->Post(local_state_task_runner_.get());
496 // http://crbug.com/125207
497 base::ThreadRestrictions::ScopedAllowWait allow_wait;
499 // We must write that the profile and metrics service shutdown cleanly,
500 // otherwise on startup we'll think we crashed. So we block until done and
501 // then proceed with normal shutdown.
503 // If you change the condition here, be sure to also change
504 // ProfileBrowserTests to match.
505 #if defined(USE_X11) || defined(OS_WIN)
506 if (use_broken_synchronization) {
507 rundown_counter->Post(
508 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE).get());
511 // Do a best-effort wait on the successful countdown of rundown tasks. Note
512 // that if we don't complete "quickly enough", Windows will terminate our
515 // On Windows, we previously posted a message to FILE and then ran a nested
516 // message loop, waiting for that message to be processed until quitting.
517 // However, doing so means that other messages will also be processed. In
518 // particular, if the GPU process host notices that the GPU has been killed
519 // during shutdown, it races exiting the nested loop with the process host
520 // blocking the message loop attempting to re-establish a connection to the
521 // GPU process synchronously. Because the system may not be allowing
522 // processes to launch, this can result in a hang. See
523 // http://crbug.com/318527.
524 rundown_counter->TimedWait(
525 base::TimeDelta::FromSeconds(kEndSessionTimeoutSeconds));
531 MetricsServicesManager* BrowserProcessImpl::GetMetricsServicesManager() {
532 DCHECK(CalledOnValidThread());
533 if (!metrics_services_manager_)
534 metrics_services_manager_.reset(new MetricsServicesManager(local_state()));
535 return metrics_services_manager_.get();
538 metrics::MetricsService* BrowserProcessImpl::metrics_service() {
539 DCHECK(CalledOnValidThread());
540 return GetMetricsServicesManager()->GetMetricsService();
543 rappor::RapporService* BrowserProcessImpl::rappor_service() {
544 DCHECK(CalledOnValidThread());
545 return GetMetricsServicesManager()->GetRapporService();
548 IOThread* BrowserProcessImpl::io_thread() {
549 DCHECK(CalledOnValidThread());
550 DCHECK(io_thread_.get());
551 return io_thread_.get();
554 WatchDogThread* BrowserProcessImpl::watchdog_thread() {
555 DCHECK(CalledOnValidThread());
556 if (!created_watchdog_thread_)
557 CreateWatchdogThread();
558 DCHECK(watchdog_thread_.get() != NULL);
559 return watchdog_thread_.get();
562 ProfileManager* BrowserProcessImpl::profile_manager() {
563 DCHECK(CalledOnValidThread());
564 if (!created_profile_manager_)
565 CreateProfileManager();
566 return profile_manager_.get();
569 PrefService* BrowserProcessImpl::local_state() {
570 DCHECK(CalledOnValidThread());
571 if (!created_local_state_)
573 return local_state_.get();
576 net::URLRequestContextGetter* BrowserProcessImpl::system_request_context() {
577 DCHECK(CalledOnValidThread());
578 return io_thread()->system_url_request_context_getter();
581 chrome_variations::VariationsService* BrowserProcessImpl::variations_service() {
582 DCHECK(CalledOnValidThread());
583 return GetMetricsServicesManager()->GetVariationsService();
586 BrowserProcessPlatformPart* BrowserProcessImpl::platform_part() {
587 return platform_part_.get();
590 extensions::EventRouterForwarder*
591 BrowserProcessImpl::extension_event_router_forwarder() {
592 #if defined(ENABLE_EXTENSIONS)
593 return extension_event_router_forwarder_.get();
599 NotificationUIManager* BrowserProcessImpl::notification_ui_manager() {
600 DCHECK(CalledOnValidThread());
601 if (!created_notification_ui_manager_)
602 CreateNotificationUIManager();
603 return notification_ui_manager_.get();
606 message_center::MessageCenter* BrowserProcessImpl::message_center() {
607 DCHECK(CalledOnValidThread());
608 return message_center::MessageCenter::Get();
611 policy::BrowserPolicyConnector* BrowserProcessImpl::browser_policy_connector() {
612 DCHECK(CalledOnValidThread());
613 #if defined(ENABLE_CONFIGURATION_POLICY)
614 if (!created_browser_policy_connector_) {
615 DCHECK(!browser_policy_connector_);
616 browser_policy_connector_ = platform_part_->CreateBrowserPolicyConnector();
617 created_browser_policy_connector_ = true;
619 return browser_policy_connector_.get();
625 policy::PolicyService* BrowserProcessImpl::policy_service() {
626 #if defined(ENABLE_CONFIGURATION_POLICY)
627 return browser_policy_connector()->GetPolicyService();
629 if (!policy_service_.get())
630 policy_service_.reset(new policy::PolicyServiceStub());
631 return policy_service_.get();
635 IconManager* BrowserProcessImpl::icon_manager() {
636 DCHECK(CalledOnValidThread());
637 if (!created_icon_manager_)
639 return icon_manager_.get();
642 GLStringManager* BrowserProcessImpl::gl_string_manager() {
643 DCHECK(CalledOnValidThread());
644 if (!gl_string_manager_.get())
645 gl_string_manager_.reset(new GLStringManager());
646 return gl_string_manager_.get();
649 GpuModeManager* BrowserProcessImpl::gpu_mode_manager() {
650 DCHECK(CalledOnValidThread());
651 if (!gpu_mode_manager_.get())
652 gpu_mode_manager_.reset(new GpuModeManager());
653 return gpu_mode_manager_.get();
656 void BrowserProcessImpl::CreateDevToolsHttpProtocolHandler(
657 chrome::HostDesktopType host_desktop_type,
658 const std::string& ip,
660 DCHECK(CalledOnValidThread());
661 #if !defined(OS_ANDROID)
662 // StartupBrowserCreator::LaunchBrowser can be run multiple times when browser
663 // is started with several profiles or existing browser process is reused.
664 if (!remote_debugging_server_.get()) {
665 remote_debugging_server_.reset(
666 new RemoteDebuggingServer(host_desktop_type, ip, port));
671 bool BrowserProcessImpl::IsShuttingDown() {
672 DCHECK(CalledOnValidThread());
673 return did_start_ && 0 == module_ref_count_;
676 printing::PrintJobManager* BrowserProcessImpl::print_job_manager() {
677 DCHECK(CalledOnValidThread());
678 return print_job_manager_.get();
681 printing::PrintPreviewDialogController*
682 BrowserProcessImpl::print_preview_dialog_controller() {
683 #if defined(ENABLE_PRINT_PREVIEW)
684 DCHECK(CalledOnValidThread());
685 if (!print_preview_dialog_controller_.get())
686 CreatePrintPreviewDialogController();
687 return print_preview_dialog_controller_.get();
694 printing::BackgroundPrintingManager*
695 BrowserProcessImpl::background_printing_manager() {
696 #if defined(ENABLE_PRINT_PREVIEW)
697 DCHECK(CalledOnValidThread());
698 if (!background_printing_manager_.get())
699 CreateBackgroundPrintingManager();
700 return background_printing_manager_.get();
707 IntranetRedirectDetector* BrowserProcessImpl::intranet_redirect_detector() {
708 DCHECK(CalledOnValidThread());
709 if (!intranet_redirect_detector_.get())
710 CreateIntranetRedirectDetector();
711 return intranet_redirect_detector_.get();
714 const std::string& BrowserProcessImpl::GetApplicationLocale() {
715 DCHECK(!locale_.empty());
719 void BrowserProcessImpl::SetApplicationLocale(const std::string& locale) {
721 #if defined(ENABLE_EXTENSIONS)
722 extension_l10n_util::SetProcessLocale(locale);
724 chrome::ChromeContentBrowserClient::SetApplicationLocale(locale);
725 translate::TranslateDownloadManager::GetInstance()->set_application_locale(
729 DownloadStatusUpdater* BrowserProcessImpl::download_status_updater() {
730 return download_status_updater_.get();
733 MediaFileSystemRegistry* BrowserProcessImpl::media_file_system_registry() {
734 #if defined(ENABLE_EXTENSIONS)
735 if (!media_file_system_registry_)
736 media_file_system_registry_.reset(new MediaFileSystemRegistry());
737 return media_file_system_registry_.get();
743 bool BrowserProcessImpl::created_local_state() const {
744 return created_local_state_;
747 #if defined(ENABLE_WEBRTC)
748 WebRtcLogUploader* BrowserProcessImpl::webrtc_log_uploader() {
749 if (!webrtc_log_uploader_.get())
750 webrtc_log_uploader_.reset(new WebRtcLogUploader());
751 return webrtc_log_uploader_.get();
755 network_time::NetworkTimeTracker* BrowserProcessImpl::network_time_tracker() {
756 if (!network_time_tracker_) {
757 network_time_tracker_.reset(new network_time::NetworkTimeTracker(
758 scoped_ptr<base::TickClock>(new base::DefaultTickClock()),
761 return network_time_tracker_.get();
764 gcm::GCMDriver* BrowserProcessImpl::gcm_driver() {
765 DCHECK(CalledOnValidThread());
768 return gcm_driver_.get();
772 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple* registry) {
773 registry->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled,
775 // This policy needs to be defined before the net subsystem is initialized,
777 registry->RegisterIntegerPref(prefs::kMaxConnectionsPerProxy,
778 net::kDefaultMaxSocketsPerProxyServer);
780 registry->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt, false);
782 #if defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
783 registry->RegisterBooleanPref(prefs::kEulaAccepted, false);
784 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
786 if (base::win::GetVersion() >= base::win::VERSION_WIN7) {
787 registry->RegisterStringPref(prefs::kRelaunchMode,
788 upgrade_util::kRelaunchModeDefault);
792 // TODO(brettw,*): this comment about ResourceBundle was here since
793 // initial commit. This comment seems unrelated, bit-rotten and
794 // a candidate for removal.
795 // Initialize ResourceBundle which handles files loaded from external
796 // sources. This has to be done before uninstall code path and before prefs
798 registry->RegisterStringPref(prefs::kApplicationLocale, std::string());
799 #if defined(OS_CHROMEOS)
800 registry->RegisterStringPref(prefs::kOwnerLocale, std::string());
801 registry->RegisterStringPref(prefs::kHardwareKeyboardLayout,
803 #endif // defined(OS_CHROMEOS)
804 #if !defined(OS_CHROMEOS)
805 registry->RegisterBooleanPref(
806 prefs::kMetricsReportingEnabled,
807 GoogleUpdateSettings::GetCollectStatsConsent());
808 #endif // !defined(OS_CHROMEOS)
810 #if defined(OS_ANDROID)
811 registry->RegisterBooleanPref(
812 prefs::kCrashReportingEnabled, false);
813 #endif // defined(OS_ANDROID)
816 DownloadRequestLimiter* BrowserProcessImpl::download_request_limiter() {
817 DCHECK(CalledOnValidThread());
818 if (!download_request_limiter_.get())
819 download_request_limiter_ = new DownloadRequestLimiter();
820 return download_request_limiter_.get();
823 BackgroundModeManager* BrowserProcessImpl::background_mode_manager() {
824 DCHECK(CalledOnValidThread());
825 #if defined(ENABLE_BACKGROUND)
826 if (!background_mode_manager_.get())
827 CreateBackgroundModeManager();
828 return background_mode_manager_.get();
835 void BrowserProcessImpl::set_background_mode_manager_for_test(
836 scoped_ptr<BackgroundModeManager> manager) {
837 #if defined(ENABLE_BACKGROUND)
838 background_mode_manager_ = manager.Pass();
842 StatusTray* BrowserProcessImpl::status_tray() {
843 DCHECK(CalledOnValidThread());
844 if (!status_tray_.get())
846 return status_tray_.get();
850 SafeBrowsingService* BrowserProcessImpl::safe_browsing_service() {
851 DCHECK(CalledOnValidThread());
852 if (!created_safe_browsing_service_)
853 CreateSafeBrowsingService();
854 return safe_browsing_service_.get();
857 safe_browsing::ClientSideDetectionService*
858 BrowserProcessImpl::safe_browsing_detection_service() {
859 DCHECK(CalledOnValidThread());
860 if (safe_browsing_service())
861 return safe_browsing_service()->safe_browsing_detection_service();
865 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
866 void BrowserProcessImpl::StartAutoupdateTimer() {
867 autoupdate_timer_.Start(FROM_HERE,
868 base::TimeDelta::FromHours(kUpdateCheckIntervalHours),
870 &BrowserProcessImpl::OnAutoupdateTimer);
874 ChromeNetLog* BrowserProcessImpl::net_log() {
875 return net_log_.get();
878 prerender::PrerenderTracker* BrowserProcessImpl::prerender_tracker() {
879 if (!prerender_tracker_.get())
880 prerender_tracker_.reset(new prerender::PrerenderTracker);
882 return prerender_tracker_.get();
885 component_updater::ComponentUpdateService*
886 BrowserProcessImpl::component_updater() {
887 if (!component_updater_.get()) {
888 if (!BrowserThread::CurrentlyOn(BrowserThread::UI))
890 component_updater::Configurator* configurator =
891 component_updater::MakeChromeComponentUpdaterConfigurator(
892 CommandLine::ForCurrentProcess(),
893 io_thread()->system_url_request_context_getter());
894 // Creating the component updater does not do anything, components
895 // need to be registered and Start() needs to be called.
896 component_updater_.reset(ComponentUpdateServiceFactory(configurator));
898 return component_updater_.get();
901 CRLSetFetcher* BrowserProcessImpl::crl_set_fetcher() {
902 if (!crl_set_fetcher_.get())
903 crl_set_fetcher_ = new CRLSetFetcher();
904 return crl_set_fetcher_.get();
907 component_updater::PnaclComponentInstaller*
908 BrowserProcessImpl::pnacl_component_installer() {
909 #if !defined(DISABLE_NACL)
910 if (!pnacl_component_installer_.get()) {
911 pnacl_component_installer_.reset(
912 new component_updater::PnaclComponentInstaller());
914 return pnacl_component_installer_.get();
920 void BrowserProcessImpl::ResourceDispatcherHostCreated() {
921 resource_dispatcher_host_delegate_.reset(
922 new ChromeResourceDispatcherHostDelegate(prerender_tracker()));
923 ResourceDispatcherHost::Get()->SetDelegate(
924 resource_dispatcher_host_delegate_.get());
926 pref_change_registrar_.Add(
927 prefs::kAllowCrossOriginAuthPrompt,
928 base::Bind(&BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy,
929 base::Unretained(this)));
930 ApplyAllowCrossOriginAuthPromptPolicy();
933 void BrowserProcessImpl::CreateWatchdogThread() {
934 DCHECK(!created_watchdog_thread_ && watchdog_thread_.get() == NULL);
935 created_watchdog_thread_ = true;
937 scoped_ptr<WatchDogThread> thread(new WatchDogThread());
938 base::Thread::Options options;
939 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
940 if (!thread->StartWithOptions(options))
942 watchdog_thread_.swap(thread);
945 void BrowserProcessImpl::CreateProfileManager() {
946 DCHECK(!created_profile_manager_ && profile_manager_.get() == NULL);
947 created_profile_manager_ = true;
949 base::FilePath user_data_dir;
950 PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
951 profile_manager_.reset(new ProfileManager(user_data_dir));
954 void BrowserProcessImpl::CreateLocalState() {
955 DCHECK(!created_local_state_ && local_state_.get() == NULL);
956 created_local_state_ = true;
958 base::FilePath local_state_path;
959 CHECK(PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path));
960 scoped_refptr<PrefRegistrySimple> pref_registry = new PrefRegistrySimple;
962 // Register local state preferences.
963 chrome::RegisterLocalState(pref_registry.get());
966 chrome_prefs::CreateLocalState(local_state_path,
967 local_state_task_runner_.get(),
972 pref_change_registrar_.Init(local_state_.get());
974 // Initialize the notification for the default browser setting policy.
975 pref_change_registrar_.Add(
976 prefs::kDefaultBrowserSettingEnabled,
977 base::Bind(&BrowserProcessImpl::ApplyDefaultBrowserPolicy,
978 base::Unretained(this)));
980 // This preference must be kept in sync with external values; update them
981 // whenever the preference or its controlling policy changes.
982 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
983 pref_change_registrar_.Add(
984 prefs::kMetricsReportingEnabled,
985 base::Bind(&BrowserProcessImpl::ApplyMetricsReportingPolicy,
986 base::Unretained(this)));
989 int max_per_proxy = local_state_->GetInteger(prefs::kMaxConnectionsPerProxy);
990 net::ClientSocketPoolManager::set_max_sockets_per_proxy_server(
991 net::HttpNetworkSession::NORMAL_SOCKET_POOL,
992 std::max(std::min(max_per_proxy, 99),
993 net::ClientSocketPoolManager::max_sockets_per_group(
994 net::HttpNetworkSession::NORMAL_SOCKET_POOL)));
997 void BrowserProcessImpl::PreCreateThreads() {
999 new IOThread(local_state(), policy_service(), net_log_.get(),
1000 extension_event_router_forwarder()));
1003 void BrowserProcessImpl::PreMainMessageLoopRun() {
1004 #if defined(ENABLE_CONFIGURATION_POLICY)
1005 // browser_policy_connector() is created very early because local_state()
1006 // needs policy to be initialized with the managed preference values.
1007 // However, policy fetches from the network and loading of disk caches
1008 // requires that threads are running; this Init() call lets the connector
1009 // resume its initialization now that the loops are spinning and the
1010 // system request context is available for the fetchers.
1011 browser_policy_connector()->Init(local_state(), system_request_context());
1014 if (local_state_->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled))
1015 ApplyDefaultBrowserPolicy();
1017 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1018 ApplyMetricsReportingPolicy();
1021 #if defined(ENABLE_PLUGINS)
1022 PluginService* plugin_service = PluginService::GetInstance();
1023 plugin_service->SetFilter(ChromePluginServiceFilter::GetInstance());
1024 plugin_service->StartWatchingPlugins();
1026 #if defined(OS_POSIX)
1027 // Also find plugins in a user-specific plugins dir,
1028 // e.g. ~/.config/chromium/Plugins.
1029 const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
1030 if (!cmd_line.HasSwitch(switches::kDisablePluginsDiscovery)) {
1031 base::FilePath user_data_dir;
1032 if (PathService::Get(chrome::DIR_USER_DATA, &user_data_dir))
1033 plugin_service->AddExtraPluginDir(user_data_dir.Append("Plugins"));
1037 // Triggers initialization of the singleton instance on UI thread.
1038 PluginFinder::GetInstance()->Init();
1040 #if defined(ENABLE_PLUGIN_INSTALLATION)
1041 DCHECK(!plugins_resource_service_.get());
1042 plugins_resource_service_ = new PluginsResourceService(local_state());
1043 plugins_resource_service_->Init();
1045 #endif // defined(ENABLE_PLUGINS)
1047 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1048 if (!command_line.HasSwitch(switches::kDisableWebResources)) {
1049 DCHECK(!promo_resource_service_.get());
1050 promo_resource_service_ = new PromoResourceService;
1051 promo_resource_service_->StartAfterDelay();
1054 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1055 storage_monitor::StorageMonitor::Create();
1058 platform_part_->PreMainMessageLoopRun();
1061 void BrowserProcessImpl::CreateIconManager() {
1062 DCHECK(!created_icon_manager_ && icon_manager_.get() == NULL);
1063 created_icon_manager_ = true;
1064 icon_manager_.reset(new IconManager);
1067 void BrowserProcessImpl::CreateIntranetRedirectDetector() {
1068 DCHECK(intranet_redirect_detector_.get() == NULL);
1069 scoped_ptr<IntranetRedirectDetector> intranet_redirect_detector(
1070 new IntranetRedirectDetector);
1071 intranet_redirect_detector_.swap(intranet_redirect_detector);
1074 void BrowserProcessImpl::CreateNotificationUIManager() {
1075 #if defined(ENABLE_NOTIFICATIONS)
1076 DCHECK(notification_ui_manager_.get() == NULL);
1077 notification_ui_manager_.reset(NotificationUIManager::Create(local_state()));
1078 created_notification_ui_manager_ = true;
1082 void BrowserProcessImpl::CreateBackgroundModeManager() {
1083 #if defined(ENABLE_BACKGROUND)
1084 DCHECK(background_mode_manager_.get() == NULL);
1085 background_mode_manager_.reset(
1086 new BackgroundModeManager(CommandLine::ForCurrentProcess(),
1087 &profile_manager()->GetProfileInfoCache()));
1091 void BrowserProcessImpl::CreateStatusTray() {
1092 DCHECK(status_tray_.get() == NULL);
1093 status_tray_.reset(StatusTray::Create());
1096 void BrowserProcessImpl::CreatePrintPreviewDialogController() {
1097 #if defined(ENABLE_PRINT_PREVIEW)
1098 DCHECK(print_preview_dialog_controller_.get() == NULL);
1099 print_preview_dialog_controller_ =
1100 new printing::PrintPreviewDialogController();
1106 void BrowserProcessImpl::CreateBackgroundPrintingManager() {
1107 #if defined(ENABLE_PRINT_PREVIEW)
1108 DCHECK(background_printing_manager_.get() == NULL);
1109 background_printing_manager_.reset(new printing::BackgroundPrintingManager());
1115 void BrowserProcessImpl::CreateSafeBrowsingService() {
1116 DCHECK(safe_browsing_service_.get() == NULL);
1117 // Set this flag to true so that we don't retry indefinitely to
1118 // create the service class if there was an error.
1119 created_safe_browsing_service_ = true;
1120 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
1121 safe_browsing_service_ = SafeBrowsingService::CreateSafeBrowsingService();
1122 safe_browsing_service_->Initialize();
1126 void BrowserProcessImpl::CreateGCMDriver() {
1127 DCHECK(!gcm_driver_);
1129 #if defined(OS_ANDROID)
1130 gcm_driver_.reset(new gcm::GCMDriverAndroid);
1132 base::FilePath store_path;
1133 CHECK(PathService::Get(chrome::DIR_GLOBAL_GCM_STORE, &store_path));
1134 gcm_driver_ = gcm::CreateGCMDriverDesktop(
1135 make_scoped_ptr(new gcm::GCMClientFactory),
1138 system_request_context());
1139 // Sign-in is not required for device-level GCM usage. So we just call
1140 // OnSignedIn to assume always signed-in. Note that GCM will not be started
1141 // at this point since no one has asked for it yet.
1142 // TODO(jianli): To be removed when sign-in enforcement is dropped.
1143 gcm_driver_->OnSignedIn();
1144 #endif // defined(OS_ANDROID)
1147 void BrowserProcessImpl::ApplyDefaultBrowserPolicy() {
1148 if (local_state()->GetBoolean(prefs::kDefaultBrowserSettingEnabled)) {
1149 scoped_refptr<ShellIntegration::DefaultWebClientWorker>
1150 set_browser_worker = new ShellIntegration::DefaultBrowserWorker(NULL);
1151 set_browser_worker->StartSetAsDefault();
1155 void BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy() {
1156 bool value = local_state()->GetBoolean(prefs::kAllowCrossOriginAuthPrompt);
1157 ResourceDispatcherHost::Get()->SetAllowCrossOriginAuthPrompt(value);
1160 void BrowserProcessImpl::ApplyMetricsReportingPolicy() {
1161 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1162 CHECK(BrowserThread::PostTask(
1163 BrowserThread::FILE, FROM_HERE,
1165 base::IgnoreResult(&GoogleUpdateSettings::SetCollectStatsConsent),
1166 local_state()->GetBoolean(prefs::kMetricsReportingEnabled))));
1170 // Mac is currently not supported.
1171 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
1173 bool BrowserProcessImpl::CanAutorestartForUpdate() const {
1174 // Check if browser is in the background and if it needs to be restarted to
1175 // apply a pending update.
1176 return chrome::GetTotalBrowserCount() == 0 && chrome::WillKeepAlive() &&
1177 upgrade_util::IsUpdatePendingRestart();
1180 // Switches to add when auto-restarting Chrome.
1181 const char* const kSwitchesToAddOnAutorestart[] = {
1182 switches::kNoStartupWindow
1185 void BrowserProcessImpl::RestartBackgroundInstance() {
1186 CommandLine* old_cl = CommandLine::ForCurrentProcess();
1187 scoped_ptr<CommandLine> new_cl(new CommandLine(old_cl->GetProgram()));
1189 std::map<std::string, CommandLine::StringType> switches =
1190 old_cl->GetSwitches();
1192 switches::RemoveSwitchesForAutostart(&switches);
1194 // Append the rest of the switches (along with their values, if any)
1195 // to the new command line
1196 for (std::map<std::string, CommandLine::StringType>::const_iterator i =
1197 switches.begin(); i != switches.end(); ++i) {
1198 CommandLine::StringType switch_value = i->second;
1199 if (switch_value.length() > 0) {
1200 new_cl->AppendSwitchNative(i->first, i->second);
1202 new_cl->AppendSwitch(i->first);
1206 // Ensure that our desired switches are set on the new process.
1207 for (size_t i = 0; i < arraysize(kSwitchesToAddOnAutorestart); ++i) {
1208 if (!new_cl->HasSwitch(kSwitchesToAddOnAutorestart[i]))
1209 new_cl->AppendSwitch(kSwitchesToAddOnAutorestart[i]);
1212 DLOG(WARNING) << "Shutting down current instance of the browser.";
1213 chrome::AttemptExit();
1215 // Transfer ownership to Upgrade.
1216 upgrade_util::SetNewCommandLine(new_cl.release());
1219 void BrowserProcessImpl::OnAutoupdateTimer() {
1220 if (CanAutorestartForUpdate()) {
1221 DLOG(WARNING) << "Detected update. Restarting browser.";
1222 RestartBackgroundInstance();
1226 #endif // (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)