Revert of Merge apps/pref* to extensions/browser/pref* (patchset #1 of https://codere...
[chromium-blink-merge.git] / chrome / browser / browser_process_impl.cc
blobc379704ad6f35baba5ba9319cc9a0d1650a7700b
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"
7 #include <algorithm>
8 #include <map>
9 #include <vector>
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/background/background_mode_manager.h"
28 #include "chrome/browser/chrome_browser_main.h"
29 #include "chrome/browser/chrome_content_browser_client.h"
30 #include "chrome/browser/chrome_notification_types.h"
31 #include "chrome/browser/component_updater/chrome_component_updater_configurator.h"
32 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
33 #include "chrome/browser/defaults.h"
34 #include "chrome/browser/devtools/remote_debugging_server.h"
35 #include "chrome/browser/download/download_request_limiter.h"
36 #include "chrome/browser/download/download_status_updater.h"
37 #include "chrome/browser/first_run/upgrade_util.h"
38 #include "chrome/browser/gpu/gl_string_manager.h"
39 #include "chrome/browser/gpu/gpu_mode_manager.h"
40 #include "chrome/browser/icon_manager.h"
41 #include "chrome/browser/idle.h"
42 #include "chrome/browser/intranet_redirect_detector.h"
43 #include "chrome/browser/io_thread.h"
44 #include "chrome/browser/lifetime/application_lifetime.h"
45 #include "chrome/browser/metrics/metrics_services_manager.h"
46 #include "chrome/browser/metrics/thread_watcher.h"
47 #include "chrome/browser/net/chrome_net_log.h"
48 #include "chrome/browser/net/crl_set_fetcher.h"
49 #include "chrome/browser/notifications/notification_ui_manager.h"
50 #include "chrome/browser/omaha_query_params/chrome_omaha_query_params_delegate.h"
51 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
52 #include "chrome/browser/plugins/plugin_finder.h"
53 #include "chrome/browser/prefs/browser_prefs.h"
54 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
55 #include "chrome/browser/prerender/prerender_tracker.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/apps/chrome_apps_client.h"
65 #include "chrome/browser/ui/browser_dialogs.h"
66 #include "chrome/browser/ui/browser_finder.h"
67 #include "chrome/browser/web_resource/promo_resource_service.h"
68 #include "chrome/common/chrome_constants.h"
69 #include "chrome/common/chrome_paths.h"
70 #include "chrome/common/chrome_switches.h"
71 #include "chrome/common/extensions/chrome_extensions_client.h"
72 #include "chrome/common/pref_names.h"
73 #include "chrome/common/switch_utils.h"
74 #include "chrome/common/url_constants.h"
75 #include "chrome/installer/util/google_update_constants.h"
76 #include "chrome/installer/util/google_update_settings.h"
77 #include "components/component_updater/component_updater_service.h"
78 #include "components/gcm_driver/gcm_driver.h"
79 #include "components/metrics/metrics_service.h"
80 #include "components/network_time/network_time_tracker.h"
81 #include "components/omaha_query_params/omaha_query_params.h"
82 #include "components/policy/core/common/policy_service.h"
83 #include "components/signin/core/common/profile_management_switches.h"
84 #include "components/translate/core/browser/translate_download_manager.h"
85 #include "content/public/browser/browser_thread.h"
86 #include "content/public/browser/child_process_security_policy.h"
87 #include "content/public/browser/notification_details.h"
88 #include "content/public/browser/plugin_service.h"
89 #include "content/public/browser/render_process_host.h"
90 #include "content/public/browser/resource_dispatcher_host.h"
91 #include "content/public/browser/service_worker_context.h"
92 #include "content/public/browser/storage_partition.h"
93 #include "extensions/common/constants.h"
94 #include "extensions/common/extension_l10n_util.h"
95 #include "net/socket/client_socket_pool_manager.h"
96 #include "net/url_request/url_request_context_getter.h"
97 #include "ui/base/l10n/l10n_util.h"
98 #include "ui/message_center/message_center.h"
100 #if defined(OS_WIN)
101 #include "base/win/windows_version.h"
102 #include "ui/views/focus/view_storage.h"
103 #elif defined(OS_MACOSX)
104 #include "chrome/browser/chrome_browser_main_mac.h"
105 #endif
107 #if defined(OS_ANDROID)
108 #include "components/gcm_driver/gcm_driver_android.h"
109 #else
110 #include "chrome/browser/services/gcm/gcm_desktop_utils.h"
111 #include "components/gcm_driver/gcm_client_factory.h"
112 #endif
114 #if defined(USE_AURA)
115 #include "ui/aura/env.h"
116 #endif
118 #if defined(ENABLE_CONFIGURATION_POLICY)
119 #include "components/policy/core/browser/browser_policy_connector.h"
120 #else
121 #include "components/policy/core/common/policy_service_stub.h"
122 #endif // defined(ENABLE_CONFIGURATION_POLICY)
124 #if defined(ENABLE_EXTENSIONS)
125 #include "chrome/browser/extensions/chrome_extensions_browser_client.h"
126 #include "chrome/browser/extensions/event_router_forwarder.h"
127 #include "chrome/browser/extensions/extension_renderer_state.h"
128 #include "chrome/browser/media_galleries/media_file_system_registry.h"
129 #include "components/storage_monitor/storage_monitor.h"
130 #endif
132 #if defined(ENABLE_PLUGIN_INSTALLATION)
133 #include "chrome/browser/plugins/plugins_resource_service.h"
134 #endif
136 #if defined(ENABLE_WEBRTC)
137 #include "chrome/browser/media/webrtc_log_uploader.h"
138 #endif
140 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
141 // How often to check if the persistent instance of Chrome needs to restart
142 // to install an update.
143 static const int kUpdateCheckIntervalHours = 6;
144 #endif
146 #if defined(USE_X11) || defined(OS_WIN)
147 // How long to wait for the File thread to complete during EndSession, on Linux
148 // and Windows. We have a timeout here because we're unable to run the UI
149 // messageloop and there's some deadlock risk. Our only option is to exit
150 // anyway.
151 static const int kEndSessionTimeoutSeconds = 10;
152 #endif
154 using content::BrowserThread;
155 using content::ChildProcessSecurityPolicy;
156 using content::PluginService;
157 using content::ResourceDispatcherHost;
159 BrowserProcessImpl::BrowserProcessImpl(
160 base::SequencedTaskRunner* local_state_task_runner,
161 const CommandLine& command_line)
162 : created_watchdog_thread_(false),
163 created_browser_policy_connector_(false),
164 created_profile_manager_(false),
165 created_local_state_(false),
166 created_icon_manager_(false),
167 created_notification_ui_manager_(false),
168 created_safe_browsing_service_(false),
169 module_ref_count_(0),
170 did_start_(false),
171 download_status_updater_(new DownloadStatusUpdater),
172 local_state_task_runner_(local_state_task_runner) {
173 g_browser_process = this;
174 platform_part_.reset(new BrowserProcessPlatformPart());
176 #if defined(ENABLE_PRINTING)
177 // Must be created after the NotificationService.
178 print_job_manager_.reset(new printing::PrintJobManager);
179 #endif
181 net_log_.reset(new ChromeNetLog);
183 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
184 extensions::kExtensionScheme);
185 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
186 extensions::kExtensionResourceScheme);
187 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
188 chrome::kChromeSearchScheme);
190 #if defined(OS_MACOSX)
191 InitIdleMonitor();
192 #endif
194 #if defined(ENABLE_EXTENSIONS)
195 apps::AppsClient::Set(ChromeAppsClient::GetInstance());
197 extension_event_router_forwarder_ = new extensions::EventRouterForwarder;
198 ExtensionRendererState::GetInstance()->Init();
200 extensions::ExtensionsClient::Set(
201 extensions::ChromeExtensionsClient::GetInstance());
203 extensions_browser_client_.reset(
204 new extensions::ChromeExtensionsBrowserClient);
205 extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get());
206 #endif
208 message_center::MessageCenter::Initialize();
210 omaha_query_params::OmahaQueryParams::SetDelegate(
211 ChromeOmahaQueryParamsDelegate::GetInstance());
214 BrowserProcessImpl::~BrowserProcessImpl() {
215 tracked_objects::ThreadData::EnsureCleanupWasCalled(4);
217 g_browser_process = NULL;
220 void BrowserProcessImpl::StartTearDown() {
221 TRACE_EVENT0("shutdown", "BrowserProcessImpl::StartTearDown");
222 // We need to destroy the MetricsServicesManager, IntranetRedirectDetector,
223 // PromoResourceService, and SafeBrowsing ClientSideDetectionService (owned by
224 // the SafeBrowsingService) before the io_thread_ gets destroyed, since their
225 // destructors can call the URLFetcher destructor, which does a
226 // PostDelayedTask operation on the IO thread. (The IO thread will handle that
227 // URLFetcher operation before going away.)
228 metrics_services_manager_.reset();
229 intranet_redirect_detector_.reset();
230 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
231 if (safe_browsing_service_.get())
232 safe_browsing_service()->ShutDown();
233 #endif
235 // Need to clear the desktop notification balloons before the io_thread_ and
236 // before the profiles, since if there are any still showing we will access
237 // those things during teardown.
238 notification_ui_manager_.reset();
240 // Need to clear profiles (download managers) before the io_thread_.
242 TRACE_EVENT0("shutdown",
243 "BrowserProcessImpl::StartTearDown:ProfileManager");
244 // The desktop User Manager needs to be closed before the guest profile
245 // can be destroyed.
246 if (switches::IsNewAvatarMenu())
247 chrome::HideUserManager();
248 profile_manager_.reset();
251 #if !defined(OS_ANDROID)
252 // Debugger must be cleaned up before IO thread and NotificationService.
253 remote_debugging_server_.reset();
254 #endif
256 #if defined(ENABLE_EXTENSIONS)
257 ExtensionRendererState::GetInstance()->Shutdown();
259 media_file_system_registry_.reset();
260 // Remove the global instance of the Storage Monitor now. Otherwise the
261 // FILE thread would be gone when we try to release it in the dtor and
262 // Valgrind would report a leak on almost every single browser_test.
263 // TODO(gbillock): Make this unnecessary.
264 storage_monitor::StorageMonitor::Destroy();
265 #endif
267 message_center::MessageCenter::Shutdown();
269 #if defined(ENABLE_CONFIGURATION_POLICY)
270 // The policy providers managed by |browser_policy_connector_| need to shut
271 // down while the IO and FILE threads are still alive.
272 if (browser_policy_connector_)
273 browser_policy_connector_->Shutdown();
274 #endif
276 // The |gcm_driver_| must shut down while the IO thread is still alive.
277 if (gcm_driver_)
278 gcm_driver_->Shutdown();
280 // Stop the watchdog thread before stopping other threads.
281 watchdog_thread_.reset();
283 #if defined(USE_AURA)
284 // Delete aura after the metrics service has been deleted as it accesses
285 // monitor information.
286 aura::Env::DeleteInstance();
287 #endif
289 platform_part()->StartTearDown();
291 #if defined(ENABLE_WEBRTC)
292 // Cancel any uploads to release the system url request context references.
293 if (webrtc_log_uploader_)
294 webrtc_log_uploader_->StartShutdown();
295 #endif
297 if (local_state())
298 local_state()->CommitPendingWrite();
301 void BrowserProcessImpl::PostDestroyThreads() {
302 // With the file_thread_ flushed, we can release any icon resources.
303 icon_manager_.reset();
305 #if defined(ENABLE_WEBRTC)
306 // Must outlive the file thread.
307 webrtc_log_uploader_.reset();
308 #endif
310 // Reset associated state right after actual thread is stopped,
311 // as io_thread_.global_ cleanup happens in CleanUp on the IO
312 // thread, i.e. as the thread exits its message loop.
314 // This is important also because in various places, the
315 // IOThread object being NULL is considered synonymous with the
316 // IO thread having stopped.
317 io_thread_.reset();
320 unsigned int BrowserProcessImpl::AddRefModule() {
321 DCHECK(CalledOnValidThread());
323 // CHECK(!IsShuttingDown());
324 if (IsShuttingDown()) {
325 // Copy the stacktrace which released the final reference onto our stack so
326 // it will be available in the crash report for inspection.
327 base::debug::StackTrace callstack = release_last_reference_callstack_;
328 base::debug::Alias(&callstack);
329 CHECK(false);
332 did_start_ = true;
333 module_ref_count_++;
334 return module_ref_count_;
337 static void ShutdownServiceWorkerContext(content::StoragePartition* partition) {
338 partition->GetServiceWorkerContext()->Terminate();
341 unsigned int BrowserProcessImpl::ReleaseModule() {
342 DCHECK(CalledOnValidThread());
343 DCHECK_NE(0u, module_ref_count_);
344 module_ref_count_--;
345 if (0 == module_ref_count_) {
346 release_last_reference_callstack_ = base::debug::StackTrace();
348 // Stop service workers
349 ProfileManager* pm = profile_manager();
350 std::vector<Profile*> profiles(pm->GetLoadedProfiles());
351 for (size_t i = 0; i < profiles.size(); ++i) {
352 content::BrowserContext::ForEachStoragePartition(
353 profiles[i], base::Bind(ShutdownServiceWorkerContext));
356 #if defined(ENABLE_PRINTING)
357 // Wait for the pending print jobs to finish. Don't do this later, since
358 // this might cause a nested message loop to run, and we don't want pending
359 // tasks to run once teardown has started.
360 print_job_manager_->Shutdown();
361 #endif
363 #if defined(LEAK_SANITIZER)
364 // Check for memory leaks now, before we start shutting down threads. Doing
365 // this early means we won't report any shutdown-only leaks (as they have
366 // not yet happened at this point).
367 // If leaks are found, this will make the process exit immediately.
368 __lsan_do_leak_check();
369 #endif
371 CHECK(base::MessageLoop::current()->is_running());
373 #if defined(OS_MACOSX)
374 base::MessageLoop::current()->PostTask(
375 FROM_HERE,
376 base::Bind(ChromeBrowserMainPartsMac::DidEndMainMessageLoop));
377 #endif
378 base::MessageLoop::current()->Quit();
380 return module_ref_count_;
383 namespace {
385 // Used at the end of session to block the UI thread for completion of sentinel
386 // tasks on the set of threads used to persist profile data and local state.
387 // This is done to ensure that the data has been persisted to disk before
388 // continuing.
389 class RundownTaskCounter :
390 public base::RefCountedThreadSafe<RundownTaskCounter> {
391 public:
392 RundownTaskCounter();
394 // Posts a rundown task to |task_runner|, can be invoked an arbitrary number
395 // of times before calling TimedWait.
396 void Post(base::SequencedTaskRunner* task_runner);
398 // Waits until the count is zero or |max_time| has passed.
399 // This can only be called once per instance.
400 bool TimedWait(const base::TimeDelta& max_time);
402 private:
403 friend class base::RefCountedThreadSafe<RundownTaskCounter>;
404 ~RundownTaskCounter() {}
406 // Decrements the counter and releases the waitable event on transition to
407 // zero.
408 void Decrement();
410 // The count starts at one to defer the possibility of one->zero transitions
411 // until TimedWait is called.
412 base::AtomicRefCount count_;
413 base::WaitableEvent waitable_event_;
415 DISALLOW_COPY_AND_ASSIGN(RundownTaskCounter);
418 RundownTaskCounter::RundownTaskCounter()
419 : count_(1), waitable_event_(true, false) {
422 void RundownTaskCounter::Post(base::SequencedTaskRunner* task_runner) {
423 // As the count starts off at one, it should never get to zero unless
424 // TimedWait has been called.
425 DCHECK(!base::AtomicRefCountIsZero(&count_));
427 base::AtomicRefCountInc(&count_);
429 // The task must be non-nestable to guarantee that it runs after all tasks
430 // currently scheduled on |task_runner| have completed.
431 task_runner->PostNonNestableTask(FROM_HERE,
432 base::Bind(&RundownTaskCounter::Decrement, this));
435 void RundownTaskCounter::Decrement() {
436 if (!base::AtomicRefCountDec(&count_))
437 waitable_event_.Signal();
440 bool RundownTaskCounter::TimedWait(const base::TimeDelta& max_time) {
441 // Decrement the excess count from the constructor.
442 Decrement();
444 return waitable_event_.TimedWait(max_time);
447 bool ExperimentUseBrokenSynchronization() {
448 // The logoff behavior used to have a race, whereby it would perform profile
449 // IO writes on the blocking thread pool, but would sycnhronize to the FILE
450 // thread. Windows feels free to terminate any process that's hidden or
451 // destroyed all it's windows, and sometimes Chrome would be terminated
452 // with pending profile IO due to this mis-synchronization.
453 // Under the "WindowsLogoffRace" experiment group, the broken behavior is
454 // emulated, in order to allow measuring what fraction of unclean shutdowns
455 // are due to this bug.
456 const std::string group_name =
457 base::FieldTrialList::FindFullName("WindowsLogoffRace");
458 return group_name == "BrokenSynchronization";
461 } // namespace
463 void BrowserProcessImpl::EndSession() {
464 bool use_broken_synchronization = ExperimentUseBrokenSynchronization();
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);
474 if (!use_broken_synchronization)
475 rundown_counter->Post(profile->GetIOTaskRunner());
478 // Tell the metrics service it was cleanly shutdown.
479 MetricsService* metrics = g_browser_process->metrics_service();
480 if (metrics && local_state()) {
481 metrics->RecordStartOfSessionEnd();
482 #if !defined(OS_CHROMEOS)
483 // MetricsService lazily writes to prefs, force it to write now.
484 // On ChromeOS, chrome gets killed when hangs, so no need to
485 // commit metrics::prefs::kStabilitySessionEndCompleted change immediately.
486 local_state()->CommitPendingWrite();
488 if (!use_broken_synchronization)
489 rundown_counter->Post(local_state_task_runner_);
490 #endif
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)
503 if (use_broken_synchronization) {
504 rundown_counter->Post(
505 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
508 // Do a best-effort wait on the successful countdown of rundown tasks. Note
509 // that if we don't complete "quickly enough", Windows will terminate our
510 // process.
512 // On Windows, we previously posted a message to FILE and then ran a nested
513 // message loop, waiting for that message to be processed until quitting.
514 // However, doing so means that other messages will also be processed. In
515 // particular, if the GPU process host notices that the GPU has been killed
516 // during shutdown, it races exiting the nested loop with the process host
517 // blocking the message loop attempting to re-establish a connection to the
518 // GPU process synchronously. Because the system may not be allowing
519 // processes to launch, this can result in a hang. See
520 // http://crbug.com/318527.
521 rundown_counter->TimedWait(
522 base::TimeDelta::FromSeconds(kEndSessionTimeoutSeconds));
523 #else
524 NOTIMPLEMENTED();
525 #endif
528 MetricsServicesManager* BrowserProcessImpl::GetMetricsServicesManager() {
529 DCHECK(CalledOnValidThread());
530 if (!metrics_services_manager_)
531 metrics_services_manager_.reset(new MetricsServicesManager(local_state()));
532 return metrics_services_manager_.get();
535 MetricsService* BrowserProcessImpl::metrics_service() {
536 DCHECK(CalledOnValidThread());
537 return GetMetricsServicesManager()->GetMetricsService();
540 rappor::RapporService* BrowserProcessImpl::rappor_service() {
541 DCHECK(CalledOnValidThread());
542 return GetMetricsServicesManager()->GetRapporService();
545 IOThread* BrowserProcessImpl::io_thread() {
546 DCHECK(CalledOnValidThread());
547 DCHECK(io_thread_.get());
548 return io_thread_.get();
551 WatchDogThread* BrowserProcessImpl::watchdog_thread() {
552 DCHECK(CalledOnValidThread());
553 if (!created_watchdog_thread_)
554 CreateWatchdogThread();
555 DCHECK(watchdog_thread_.get() != NULL);
556 return watchdog_thread_.get();
559 ProfileManager* BrowserProcessImpl::profile_manager() {
560 DCHECK(CalledOnValidThread());
561 if (!created_profile_manager_)
562 CreateProfileManager();
563 return profile_manager_.get();
566 PrefService* BrowserProcessImpl::local_state() {
567 DCHECK(CalledOnValidThread());
568 if (!created_local_state_)
569 CreateLocalState();
570 return local_state_.get();
573 net::URLRequestContextGetter* BrowserProcessImpl::system_request_context() {
574 DCHECK(CalledOnValidThread());
575 return io_thread()->system_url_request_context_getter();
578 chrome_variations::VariationsService* BrowserProcessImpl::variations_service() {
579 DCHECK(CalledOnValidThread());
580 return GetMetricsServicesManager()->GetVariationsService();
583 BrowserProcessPlatformPart* BrowserProcessImpl::platform_part() {
584 return platform_part_.get();
587 extensions::EventRouterForwarder*
588 BrowserProcessImpl::extension_event_router_forwarder() {
589 #if defined(ENABLE_EXTENSIONS)
590 return extension_event_router_forwarder_.get();
591 #else
592 return NULL;
593 #endif
596 NotificationUIManager* BrowserProcessImpl::notification_ui_manager() {
597 DCHECK(CalledOnValidThread());
598 if (!created_notification_ui_manager_)
599 CreateNotificationUIManager();
600 return notification_ui_manager_.get();
603 message_center::MessageCenter* BrowserProcessImpl::message_center() {
604 DCHECK(CalledOnValidThread());
605 return message_center::MessageCenter::Get();
608 policy::BrowserPolicyConnector* BrowserProcessImpl::browser_policy_connector() {
609 DCHECK(CalledOnValidThread());
610 #if defined(ENABLE_CONFIGURATION_POLICY)
611 if (!created_browser_policy_connector_) {
612 DCHECK(!browser_policy_connector_);
613 browser_policy_connector_ = platform_part_->CreateBrowserPolicyConnector();
614 created_browser_policy_connector_ = true;
616 return browser_policy_connector_.get();
617 #else
618 return NULL;
619 #endif
622 policy::PolicyService* BrowserProcessImpl::policy_service() {
623 #if defined(ENABLE_CONFIGURATION_POLICY)
624 return browser_policy_connector()->GetPolicyService();
625 #else
626 if (!policy_service_.get())
627 policy_service_.reset(new policy::PolicyServiceStub());
628 return policy_service_.get();
629 #endif
632 IconManager* BrowserProcessImpl::icon_manager() {
633 DCHECK(CalledOnValidThread());
634 if (!created_icon_manager_)
635 CreateIconManager();
636 return icon_manager_.get();
639 GLStringManager* BrowserProcessImpl::gl_string_manager() {
640 DCHECK(CalledOnValidThread());
641 if (!gl_string_manager_.get())
642 gl_string_manager_.reset(new GLStringManager());
643 return gl_string_manager_.get();
646 GpuModeManager* BrowserProcessImpl::gpu_mode_manager() {
647 DCHECK(CalledOnValidThread());
648 if (!gpu_mode_manager_.get())
649 gpu_mode_manager_.reset(new GpuModeManager());
650 return gpu_mode_manager_.get();
653 void BrowserProcessImpl::CreateDevToolsHttpProtocolHandler(
654 chrome::HostDesktopType host_desktop_type,
655 const std::string& ip,
656 int port) {
657 DCHECK(CalledOnValidThread());
658 #if !defined(OS_ANDROID)
659 // StartupBrowserCreator::LaunchBrowser can be run multiple times when browser
660 // is started with several profiles or existing browser process is reused.
661 if (!remote_debugging_server_.get()) {
662 remote_debugging_server_.reset(
663 new RemoteDebuggingServer(host_desktop_type, ip, port));
665 #endif
668 bool BrowserProcessImpl::IsShuttingDown() {
669 DCHECK(CalledOnValidThread());
670 return did_start_ && 0 == module_ref_count_;
673 printing::PrintJobManager* BrowserProcessImpl::print_job_manager() {
674 DCHECK(CalledOnValidThread());
675 return print_job_manager_.get();
678 printing::PrintPreviewDialogController*
679 BrowserProcessImpl::print_preview_dialog_controller() {
680 #if defined(ENABLE_FULL_PRINTING)
681 DCHECK(CalledOnValidThread());
682 if (!print_preview_dialog_controller_.get())
683 CreatePrintPreviewDialogController();
684 return print_preview_dialog_controller_.get();
685 #else
686 NOTIMPLEMENTED();
687 return NULL;
688 #endif
691 printing::BackgroundPrintingManager*
692 BrowserProcessImpl::background_printing_manager() {
693 #if defined(ENABLE_FULL_PRINTING)
694 DCHECK(CalledOnValidThread());
695 if (!background_printing_manager_.get())
696 CreateBackgroundPrintingManager();
697 return background_printing_manager_.get();
698 #else
699 NOTIMPLEMENTED();
700 return NULL;
701 #endif
704 IntranetRedirectDetector* BrowserProcessImpl::intranet_redirect_detector() {
705 DCHECK(CalledOnValidThread());
706 if (!intranet_redirect_detector_.get())
707 CreateIntranetRedirectDetector();
708 return intranet_redirect_detector_.get();
711 const std::string& BrowserProcessImpl::GetApplicationLocale() {
712 DCHECK(!locale_.empty());
713 return locale_;
716 void BrowserProcessImpl::SetApplicationLocale(const std::string& locale) {
717 locale_ = locale;
718 extension_l10n_util::SetProcessLocale(locale);
719 chrome::ChromeContentBrowserClient::SetApplicationLocale(locale);
720 translate::TranslateDownloadManager::GetInstance()->set_application_locale(
721 locale);
724 DownloadStatusUpdater* BrowserProcessImpl::download_status_updater() {
725 return download_status_updater_.get();
728 MediaFileSystemRegistry* BrowserProcessImpl::media_file_system_registry() {
729 #if defined(ENABLE_EXTENSIONS)
730 if (!media_file_system_registry_)
731 media_file_system_registry_.reset(new MediaFileSystemRegistry());
732 return media_file_system_registry_.get();
733 #else
734 return NULL;
735 #endif
738 bool BrowserProcessImpl::created_local_state() const {
739 return created_local_state_;
742 #if defined(ENABLE_WEBRTC)
743 WebRtcLogUploader* BrowserProcessImpl::webrtc_log_uploader() {
744 if (!webrtc_log_uploader_.get())
745 webrtc_log_uploader_.reset(new WebRtcLogUploader());
746 return webrtc_log_uploader_.get();
748 #endif
750 network_time::NetworkTimeTracker* BrowserProcessImpl::network_time_tracker() {
751 if (!network_time_tracker_) {
752 network_time_tracker_.reset(new network_time::NetworkTimeTracker(
753 scoped_ptr<base::TickClock>(new base::DefaultTickClock()),
754 local_state()));
756 return network_time_tracker_.get();
759 gcm::GCMDriver* BrowserProcessImpl::gcm_driver() {
760 DCHECK(CalledOnValidThread());
761 if (!gcm_driver_)
762 CreateGCMDriver();
763 return gcm_driver_.get();
766 // static
767 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple* registry) {
768 registry->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled,
769 false);
770 // This policy needs to be defined before the net subsystem is initialized,
771 // so we do it here.
772 registry->RegisterIntegerPref(prefs::kMaxConnectionsPerProxy,
773 net::kDefaultMaxSocketsPerProxyServer);
775 registry->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt, false);
777 registry->RegisterBooleanPref(prefs::kBrowserGuestModeEnabled, true);
779 #if defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
780 registry->RegisterBooleanPref(prefs::kEulaAccepted, false);
781 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
782 #if defined(OS_WIN)
783 if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
784 registry->RegisterStringPref(prefs::kRelaunchMode,
785 upgrade_util::kRelaunchModeDefault);
787 #endif
789 // TODO(brettw,*): this comment about ResourceBundle was here since
790 // initial commit. This comment seems unrelated, bit-rotten and
791 // a candidate for removal.
792 // Initialize ResourceBundle which handles files loaded from external
793 // sources. This has to be done before uninstall code path and before prefs
794 // are registered.
795 registry->RegisterStringPref(prefs::kApplicationLocale, std::string());
796 #if defined(OS_CHROMEOS)
797 registry->RegisterStringPref(prefs::kOwnerLocale, std::string());
798 registry->RegisterStringPref(prefs::kHardwareKeyboardLayout,
799 std::string());
800 #endif // defined(OS_CHROMEOS)
801 #if !defined(OS_CHROMEOS)
802 registry->RegisterBooleanPref(
803 prefs::kMetricsReportingEnabled,
804 GoogleUpdateSettings::GetCollectStatsConsent());
805 #endif // !defined(OS_CHROMEOS)
807 #if defined(OS_ANDROID)
808 registry->RegisterBooleanPref(
809 prefs::kCrashReportingEnabled, false);
810 #endif // defined(OS_ANDROID)
813 DownloadRequestLimiter* BrowserProcessImpl::download_request_limiter() {
814 DCHECK(CalledOnValidThread());
815 if (!download_request_limiter_.get())
816 download_request_limiter_ = new DownloadRequestLimiter();
817 return download_request_limiter_.get();
820 BackgroundModeManager* BrowserProcessImpl::background_mode_manager() {
821 DCHECK(CalledOnValidThread());
822 #if defined(ENABLE_BACKGROUND)
823 if (!background_mode_manager_.get())
824 CreateBackgroundModeManager();
825 return background_mode_manager_.get();
826 #else
827 NOTIMPLEMENTED();
828 return NULL;
829 #endif
832 void BrowserProcessImpl::set_background_mode_manager_for_test(
833 scoped_ptr<BackgroundModeManager> manager) {
834 background_mode_manager_ = manager.Pass();
837 StatusTray* BrowserProcessImpl::status_tray() {
838 DCHECK(CalledOnValidThread());
839 if (!status_tray_.get())
840 CreateStatusTray();
841 return status_tray_.get();
845 SafeBrowsingService* BrowserProcessImpl::safe_browsing_service() {
846 DCHECK(CalledOnValidThread());
847 if (!created_safe_browsing_service_)
848 CreateSafeBrowsingService();
849 return safe_browsing_service_.get();
852 safe_browsing::ClientSideDetectionService*
853 BrowserProcessImpl::safe_browsing_detection_service() {
854 DCHECK(CalledOnValidThread());
855 if (safe_browsing_service())
856 return safe_browsing_service()->safe_browsing_detection_service();
857 return NULL;
860 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
861 void BrowserProcessImpl::StartAutoupdateTimer() {
862 autoupdate_timer_.Start(FROM_HERE,
863 base::TimeDelta::FromHours(kUpdateCheckIntervalHours),
864 this,
865 &BrowserProcessImpl::OnAutoupdateTimer);
867 #endif
869 ChromeNetLog* BrowserProcessImpl::net_log() {
870 return net_log_.get();
873 prerender::PrerenderTracker* BrowserProcessImpl::prerender_tracker() {
874 if (!prerender_tracker_.get())
875 prerender_tracker_.reset(new prerender::PrerenderTracker);
877 return prerender_tracker_.get();
880 component_updater::ComponentUpdateService*
881 BrowserProcessImpl::component_updater() {
882 if (!component_updater_.get()) {
883 if (!BrowserThread::CurrentlyOn(BrowserThread::UI))
884 return NULL;
885 component_updater::Configurator* configurator =
886 component_updater::MakeChromeComponentUpdaterConfigurator(
887 CommandLine::ForCurrentProcess(),
888 io_thread()->system_url_request_context_getter());
889 // Creating the component updater does not do anything, components
890 // need to be registered and Start() needs to be called.
891 component_updater_.reset(ComponentUpdateServiceFactory(configurator));
893 return component_updater_.get();
896 CRLSetFetcher* BrowserProcessImpl::crl_set_fetcher() {
897 if (!crl_set_fetcher_.get())
898 crl_set_fetcher_ = new CRLSetFetcher();
899 return crl_set_fetcher_.get();
902 component_updater::PnaclComponentInstaller*
903 BrowserProcessImpl::pnacl_component_installer() {
904 if (!pnacl_component_installer_.get()) {
905 pnacl_component_installer_.reset(
906 new component_updater::PnaclComponentInstaller());
908 return pnacl_component_installer_.get();
911 void BrowserProcessImpl::ResourceDispatcherHostCreated() {
912 resource_dispatcher_host_delegate_.reset(
913 new ChromeResourceDispatcherHostDelegate(prerender_tracker()));
914 ResourceDispatcherHost::Get()->SetDelegate(
915 resource_dispatcher_host_delegate_.get());
917 pref_change_registrar_.Add(
918 prefs::kAllowCrossOriginAuthPrompt,
919 base::Bind(&BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy,
920 base::Unretained(this)));
921 ApplyAllowCrossOriginAuthPromptPolicy();
924 void BrowserProcessImpl::CreateWatchdogThread() {
925 DCHECK(!created_watchdog_thread_ && watchdog_thread_.get() == NULL);
926 created_watchdog_thread_ = true;
928 scoped_ptr<WatchDogThread> thread(new WatchDogThread());
929 base::Thread::Options options;
930 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
931 if (!thread->StartWithOptions(options))
932 return;
933 watchdog_thread_.swap(thread);
936 void BrowserProcessImpl::CreateProfileManager() {
937 DCHECK(!created_profile_manager_ && profile_manager_.get() == NULL);
938 created_profile_manager_ = true;
940 base::FilePath user_data_dir;
941 PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
942 profile_manager_.reset(new ProfileManager(user_data_dir));
945 void BrowserProcessImpl::CreateLocalState() {
946 DCHECK(!created_local_state_ && local_state_.get() == NULL);
947 created_local_state_ = true;
949 base::FilePath local_state_path;
950 CHECK(PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path));
951 scoped_refptr<PrefRegistrySimple> pref_registry = new PrefRegistrySimple;
953 // Register local state preferences.
954 chrome::RegisterLocalState(pref_registry.get());
956 local_state_ =
957 chrome_prefs::CreateLocalState(local_state_path,
958 local_state_task_runner_.get(),
959 policy_service(),
960 pref_registry,
961 false).Pass();
963 pref_change_registrar_.Init(local_state_.get());
965 // Initialize the notification for the default browser setting policy.
966 pref_change_registrar_.Add(
967 prefs::kDefaultBrowserSettingEnabled,
968 base::Bind(&BrowserProcessImpl::ApplyDefaultBrowserPolicy,
969 base::Unretained(this)));
971 // This preference must be kept in sync with external values; update them
972 // whenever the preference or its controlling policy changes.
973 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
974 pref_change_registrar_.Add(
975 prefs::kMetricsReportingEnabled,
976 base::Bind(&BrowserProcessImpl::ApplyMetricsReportingPolicy,
977 base::Unretained(this)));
978 #endif
980 int max_per_proxy = local_state_->GetInteger(prefs::kMaxConnectionsPerProxy);
981 net::ClientSocketPoolManager::set_max_sockets_per_proxy_server(
982 net::HttpNetworkSession::NORMAL_SOCKET_POOL,
983 std::max(std::min(max_per_proxy, 99),
984 net::ClientSocketPoolManager::max_sockets_per_group(
985 net::HttpNetworkSession::NORMAL_SOCKET_POOL)));
988 void BrowserProcessImpl::PreCreateThreads() {
989 io_thread_.reset(
990 new IOThread(local_state(), policy_service(), net_log_.get(),
991 extension_event_router_forwarder()));
994 void BrowserProcessImpl::PreMainMessageLoopRun() {
995 #if defined(ENABLE_CONFIGURATION_POLICY)
996 // browser_policy_connector() is created very early because local_state()
997 // needs policy to be initialized with the managed preference values.
998 // However, policy fetches from the network and loading of disk caches
999 // requires that threads are running; this Init() call lets the connector
1000 // resume its initialization now that the loops are spinning and the
1001 // system request context is available for the fetchers.
1002 browser_policy_connector()->Init(local_state(), system_request_context());
1003 #endif
1005 if (local_state_->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled))
1006 ApplyDefaultBrowserPolicy();
1008 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1009 ApplyMetricsReportingPolicy();
1010 #endif
1012 #if defined(ENABLE_PLUGINS)
1013 PluginService* plugin_service = PluginService::GetInstance();
1014 plugin_service->SetFilter(ChromePluginServiceFilter::GetInstance());
1015 plugin_service->StartWatchingPlugins();
1017 #if defined(OS_POSIX)
1018 // Also find plugins in a user-specific plugins dir,
1019 // e.g. ~/.config/chromium/Plugins.
1020 const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
1021 if (!cmd_line.HasSwitch(switches::kDisablePluginsDiscovery)) {
1022 base::FilePath user_data_dir;
1023 if (PathService::Get(chrome::DIR_USER_DATA, &user_data_dir))
1024 plugin_service->AddExtraPluginDir(user_data_dir.Append("Plugins"));
1026 #endif
1028 // Triggers initialization of the singleton instance on UI thread.
1029 PluginFinder::GetInstance()->Init();
1031 #if defined(ENABLE_PLUGIN_INSTALLATION)
1032 DCHECK(!plugins_resource_service_.get());
1033 plugins_resource_service_ = new PluginsResourceService(local_state());
1034 plugins_resource_service_->Init();
1035 #endif
1036 #endif // defined(ENABLE_PLUGINS)
1038 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1039 if (!command_line.HasSwitch(switches::kDisableWebResources)) {
1040 DCHECK(!promo_resource_service_.get());
1041 promo_resource_service_ = new PromoResourceService;
1042 promo_resource_service_->StartAfterDelay();
1045 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1046 storage_monitor::StorageMonitor::Create();
1047 #endif
1049 platform_part_->PreMainMessageLoopRun();
1052 void BrowserProcessImpl::CreateIconManager() {
1053 DCHECK(!created_icon_manager_ && icon_manager_.get() == NULL);
1054 created_icon_manager_ = true;
1055 icon_manager_.reset(new IconManager);
1058 void BrowserProcessImpl::CreateIntranetRedirectDetector() {
1059 DCHECK(intranet_redirect_detector_.get() == NULL);
1060 scoped_ptr<IntranetRedirectDetector> intranet_redirect_detector(
1061 new IntranetRedirectDetector);
1062 intranet_redirect_detector_.swap(intranet_redirect_detector);
1065 void BrowserProcessImpl::CreateNotificationUIManager() {
1066 #if defined(ENABLE_NOTIFICATIONS)
1067 DCHECK(notification_ui_manager_.get() == NULL);
1068 notification_ui_manager_.reset(NotificationUIManager::Create(local_state()));
1069 created_notification_ui_manager_ = true;
1070 #endif
1073 void BrowserProcessImpl::CreateBackgroundModeManager() {
1074 DCHECK(background_mode_manager_.get() == NULL);
1075 background_mode_manager_.reset(
1076 new BackgroundModeManager(CommandLine::ForCurrentProcess(),
1077 &profile_manager()->GetProfileInfoCache()));
1080 void BrowserProcessImpl::CreateStatusTray() {
1081 DCHECK(status_tray_.get() == NULL);
1082 status_tray_.reset(StatusTray::Create());
1085 void BrowserProcessImpl::CreatePrintPreviewDialogController() {
1086 #if defined(ENABLE_FULL_PRINTING)
1087 DCHECK(print_preview_dialog_controller_.get() == NULL);
1088 print_preview_dialog_controller_ =
1089 new printing::PrintPreviewDialogController();
1090 #else
1091 NOTIMPLEMENTED();
1092 #endif
1095 void BrowserProcessImpl::CreateBackgroundPrintingManager() {
1096 #if defined(ENABLE_FULL_PRINTING)
1097 DCHECK(background_printing_manager_.get() == NULL);
1098 background_printing_manager_.reset(new printing::BackgroundPrintingManager());
1099 #else
1100 NOTIMPLEMENTED();
1101 #endif
1104 void BrowserProcessImpl::CreateSafeBrowsingService() {
1105 DCHECK(safe_browsing_service_.get() == NULL);
1106 // Set this flag to true so that we don't retry indefinitely to
1107 // create the service class if there was an error.
1108 created_safe_browsing_service_ = true;
1109 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
1110 safe_browsing_service_ = SafeBrowsingService::CreateSafeBrowsingService();
1111 safe_browsing_service_->Initialize();
1112 #endif
1115 void BrowserProcessImpl::CreateGCMDriver() {
1116 DCHECK(!gcm_driver_);
1118 #if defined(OS_ANDROID)
1119 gcm_driver_.reset(new gcm::GCMDriverAndroid);
1120 #else
1121 base::FilePath store_path;
1122 CHECK(PathService::Get(chrome::DIR_GLOBAL_GCM_STORE, &store_path));
1123 gcm_driver_ = gcm::CreateGCMDriverDesktop(
1124 make_scoped_ptr(new gcm::GCMClientFactory),
1125 store_path,
1126 system_request_context());
1127 // Sign-in is not required for device-level GCM usage. So we just call
1128 // OnSignedIn to assume always signed-in. Note that GCM will not be started
1129 // at this point since no one has asked for it yet.
1130 // TODO(jianli): To be removed when sign-in enforcement is dropped.
1131 gcm_driver_->OnSignedIn();
1132 #endif // defined(OS_ANDROID)
1135 void BrowserProcessImpl::ApplyDefaultBrowserPolicy() {
1136 if (local_state()->GetBoolean(prefs::kDefaultBrowserSettingEnabled)) {
1137 scoped_refptr<ShellIntegration::DefaultWebClientWorker>
1138 set_browser_worker = new ShellIntegration::DefaultBrowserWorker(NULL);
1139 set_browser_worker->StartSetAsDefault();
1143 void BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy() {
1144 bool value = local_state()->GetBoolean(prefs::kAllowCrossOriginAuthPrompt);
1145 ResourceDispatcherHost::Get()->SetAllowCrossOriginAuthPrompt(value);
1148 void BrowserProcessImpl::ApplyMetricsReportingPolicy() {
1149 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1150 CHECK(BrowserThread::PostTask(
1151 BrowserThread::FILE, FROM_HERE,
1152 base::Bind(
1153 base::IgnoreResult(&GoogleUpdateSettings::SetCollectStatsConsent),
1154 local_state()->GetBoolean(prefs::kMetricsReportingEnabled))));
1155 #endif
1158 // Mac is currently not supported.
1159 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
1161 bool BrowserProcessImpl::CanAutorestartForUpdate() const {
1162 // Check if browser is in the background and if it needs to be restarted to
1163 // apply a pending update.
1164 return chrome::GetTotalBrowserCount() == 0 && chrome::WillKeepAlive() &&
1165 upgrade_util::IsUpdatePendingRestart();
1168 // Switches to add when auto-restarting Chrome.
1169 const char* const kSwitchesToAddOnAutorestart[] = {
1170 switches::kNoStartupWindow
1173 void BrowserProcessImpl::RestartBackgroundInstance() {
1174 CommandLine* old_cl = CommandLine::ForCurrentProcess();
1175 scoped_ptr<CommandLine> new_cl(new CommandLine(old_cl->GetProgram()));
1177 std::map<std::string, CommandLine::StringType> switches =
1178 old_cl->GetSwitches();
1180 switches::RemoveSwitchesForAutostart(&switches);
1182 // Append the rest of the switches (along with their values, if any)
1183 // to the new command line
1184 for (std::map<std::string, CommandLine::StringType>::const_iterator i =
1185 switches.begin(); i != switches.end(); ++i) {
1186 CommandLine::StringType switch_value = i->second;
1187 if (switch_value.length() > 0) {
1188 new_cl->AppendSwitchNative(i->first, i->second);
1189 } else {
1190 new_cl->AppendSwitch(i->first);
1194 // Ensure that our desired switches are set on the new process.
1195 for (size_t i = 0; i < arraysize(kSwitchesToAddOnAutorestart); ++i) {
1196 if (!new_cl->HasSwitch(kSwitchesToAddOnAutorestart[i]))
1197 new_cl->AppendSwitch(kSwitchesToAddOnAutorestart[i]);
1200 DLOG(WARNING) << "Shutting down current instance of the browser.";
1201 chrome::AttemptExit();
1203 // Transfer ownership to Upgrade.
1204 upgrade_util::SetNewCommandLine(new_cl.release());
1207 void BrowserProcessImpl::OnAutoupdateTimer() {
1208 if (CanAutorestartForUpdate()) {
1209 DLOG(WARNING) << "Detected update. Restarting browser.";
1210 RestartBackgroundInstance();
1214 #endif // (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)