Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / chrome / browser / browser_process_impl.cc
blob701fab0a53c385e64054bceb846b64cbd043d386
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/defaults.h"
33 #include "chrome/browser/devtools/remote_debugging_server.h"
34 #include "chrome/browser/download/download_request_limiter.h"
35 #include "chrome/browser/download/download_status_updater.h"
36 #include "chrome/browser/first_run/upgrade_util.h"
37 #include "chrome/browser/gpu/gl_string_manager.h"
38 #include "chrome/browser/gpu/gpu_mode_manager.h"
39 #include "chrome/browser/icon_manager.h"
40 #include "chrome/browser/idle.h"
41 #include "chrome/browser/intranet_redirect_detector.h"
42 #include "chrome/browser/io_thread.h"
43 #include "chrome/browser/lifetime/application_lifetime.h"
44 #include "chrome/browser/metrics/metrics_services_manager.h"
45 #include "chrome/browser/metrics/thread_watcher.h"
46 #include "chrome/browser/net/chrome_net_log.h"
47 #include "chrome/browser/net/crl_set_fetcher.h"
48 #include "chrome/browser/notifications/notification_ui_manager.h"
49 #include "chrome/browser/omaha_query_params/chrome_omaha_query_params_delegate.h"
50 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
51 #include "chrome/browser/plugins/plugin_finder.h"
52 #include "chrome/browser/prefs/browser_prefs.h"
53 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
54 #include "chrome/browser/prerender/prerender_tracker.h"
55 #include "chrome/browser/printing/background_printing_manager.h"
56 #include "chrome/browser/printing/print_job_manager.h"
57 #include "chrome/browser/printing/print_preview_dialog_controller.h"
58 #include "chrome/browser/profiles/profile_manager.h"
59 #include "chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h"
60 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
61 #include "chrome/browser/shell_integration.h"
62 #include "chrome/browser/status_icons/status_tray.h"
63 #include "chrome/browser/ui/apps/chrome_apps_client.h"
64 #include "chrome/browser/ui/browser_dialogs.h"
65 #include "chrome/browser/ui/browser_finder.h"
66 #include "chrome/browser/web_resource/promo_resource_service.h"
67 #include "chrome/common/chrome_constants.h"
68 #include "chrome/common/chrome_paths.h"
69 #include "chrome/common/chrome_switches.h"
70 #include "chrome/common/extensions/chrome_extensions_client.h"
71 #include "chrome/common/pref_names.h"
72 #include "chrome/common/switch_utils.h"
73 #include "chrome/common/url_constants.h"
74 #include "chrome/installer/util/google_update_constants.h"
75 #include "chrome/installer/util/google_update_settings.h"
76 #include "components/component_updater/component_updater_service.h"
77 #include "components/gcm_driver/gcm_driver.h"
78 #include "components/metrics/metrics_service.h"
79 #include "components/network_time/network_time_tracker.h"
80 #include "components/omaha_query_params/omaha_query_params.h"
81 #include "components/policy/core/common/policy_service.h"
82 #include "components/signin/core/common/profile_management_switches.h"
83 #include "components/translate/core/browser/translate_download_manager.h"
84 #include "content/public/browser/browser_thread.h"
85 #include "content/public/browser/child_process_security_policy.h"
86 #include "content/public/browser/notification_details.h"
87 #include "content/public/browser/plugin_service.h"
88 #include "content/public/browser/render_process_host.h"
89 #include "content/public/browser/resource_dispatcher_host.h"
90 #include "content/public/browser/service_worker_context.h"
91 #include "content/public/browser/storage_partition.h"
92 #include "extensions/common/constants.h"
93 #include "extensions/common/extension_l10n_util.h"
94 #include "net/socket/client_socket_pool_manager.h"
95 #include "net/url_request/url_request_context_getter.h"
96 #include "ui/base/l10n/l10n_util.h"
97 #include "ui/message_center/message_center.h"
99 #if defined(OS_WIN)
100 #include "base/win/windows_version.h"
101 #include "ui/views/focus/view_storage.h"
102 #elif defined(OS_MACOSX)
103 #include "chrome/browser/chrome_browser_main_mac.h"
104 #endif
106 #if defined(OS_ANDROID)
107 #include "components/gcm_driver/gcm_driver_android.h"
108 #else
109 #include "chrome/browser/services/gcm/gcm_desktop_utils.h"
110 #include "components/gcm_driver/gcm_client_factory.h"
111 #endif
113 #if defined(USE_AURA)
114 #include "ui/aura/env.h"
115 #endif
117 #if defined(ENABLE_CONFIGURATION_POLICY)
118 #include "components/policy/core/browser/browser_policy_connector.h"
119 #else
120 #include "components/policy/core/common/policy_service_stub.h"
121 #endif // defined(ENABLE_CONFIGURATION_POLICY)
123 #if defined(ENABLE_EXTENSIONS)
124 #include "chrome/browser/extensions/chrome_extensions_browser_client.h"
125 #include "chrome/browser/extensions/event_router_forwarder.h"
126 #include "chrome/browser/extensions/extension_renderer_state.h"
127 #include "chrome/browser/media_galleries/media_file_system_registry.h"
128 #include "components/storage_monitor/storage_monitor.h"
129 #endif
131 #if !defined(DISABLE_NACL)
132 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
133 #endif
135 #if defined(ENABLE_PLUGIN_INSTALLATION)
136 #include "chrome/browser/plugins/plugins_resource_service.h"
137 #endif
139 #if defined(ENABLE_WEBRTC)
140 #include "chrome/browser/media/webrtc_log_uploader.h"
141 #endif
143 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
144 // How often to check if the persistent instance of Chrome needs to restart
145 // to install an update.
146 static const int kUpdateCheckIntervalHours = 6;
147 #endif
149 #if defined(USE_X11) || defined(OS_WIN)
150 // How long to wait for the File thread to complete during EndSession, on Linux
151 // and Windows. We have a timeout here because we're unable to run the UI
152 // messageloop and there's some deadlock risk. Our only option is to exit
153 // anyway.
154 static const int kEndSessionTimeoutSeconds = 10;
155 #endif
157 using content::BrowserThread;
158 using content::ChildProcessSecurityPolicy;
159 using content::PluginService;
160 using content::ResourceDispatcherHost;
162 BrowserProcessImpl::BrowserProcessImpl(
163 base::SequencedTaskRunner* local_state_task_runner,
164 const CommandLine& command_line)
165 : created_watchdog_thread_(false),
166 created_browser_policy_connector_(false),
167 created_profile_manager_(false),
168 created_local_state_(false),
169 created_icon_manager_(false),
170 created_notification_ui_manager_(false),
171 created_safe_browsing_service_(false),
172 module_ref_count_(0),
173 did_start_(false),
174 download_status_updater_(new DownloadStatusUpdater),
175 local_state_task_runner_(local_state_task_runner) {
176 g_browser_process = this;
177 platform_part_.reset(new BrowserProcessPlatformPart());
179 #if defined(ENABLE_PRINTING)
180 // Must be created after the NotificationService.
181 print_job_manager_.reset(new printing::PrintJobManager);
182 #endif
184 net_log_.reset(new ChromeNetLog);
186 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
187 extensions::kExtensionScheme);
188 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
189 extensions::kExtensionResourceScheme);
190 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
191 chrome::kChromeSearchScheme);
193 #if defined(OS_MACOSX)
194 InitIdleMonitor();
195 #endif
197 #if defined(ENABLE_EXTENSIONS)
198 apps::AppsClient::Set(ChromeAppsClient::GetInstance());
200 extension_event_router_forwarder_ = new extensions::EventRouterForwarder;
201 ExtensionRendererState::GetInstance()->Init();
203 extensions::ExtensionsClient::Set(
204 extensions::ChromeExtensionsClient::GetInstance());
206 extensions_browser_client_.reset(
207 new extensions::ChromeExtensionsBrowserClient);
208 extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get());
209 #endif
211 message_center::MessageCenter::Initialize();
213 omaha_query_params::OmahaQueryParams::SetDelegate(
214 ChromeOmahaQueryParamsDelegate::GetInstance());
217 BrowserProcessImpl::~BrowserProcessImpl() {
218 tracked_objects::ThreadData::EnsureCleanupWasCalled(4);
220 g_browser_process = NULL;
223 void BrowserProcessImpl::StartTearDown() {
224 TRACE_EVENT0("shutdown", "BrowserProcessImpl::StartTearDown");
225 // We need to destroy the MetricsServicesManager, IntranetRedirectDetector,
226 // PromoResourceService, and SafeBrowsing ClientSideDetectionService (owned by
227 // the SafeBrowsingService) before the io_thread_ gets destroyed, since their
228 // destructors can call the URLFetcher destructor, which does a
229 // PostDelayedTask operation on the IO thread. (The IO thread will handle that
230 // URLFetcher operation before going away.)
231 metrics_services_manager_.reset();
232 intranet_redirect_detector_.reset();
233 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
234 if (safe_browsing_service_.get())
235 safe_browsing_service()->ShutDown();
236 #endif
238 // Need to clear the desktop notification balloons before the io_thread_ and
239 // before the profiles, since if there are any still showing we will access
240 // those things during teardown.
241 notification_ui_manager_.reset();
243 // Need to clear profiles (download managers) before the io_thread_.
245 TRACE_EVENT0("shutdown",
246 "BrowserProcessImpl::StartTearDown:ProfileManager");
247 // The desktop User Manager needs to be closed before the guest profile
248 // can be destroyed.
249 if (switches::IsNewAvatarMenu())
250 chrome::HideUserManager();
251 profile_manager_.reset();
254 #if !defined(OS_ANDROID)
255 // Debugger must be cleaned up before IO thread and NotificationService.
256 remote_debugging_server_.reset();
257 #endif
259 #if defined(ENABLE_EXTENSIONS)
260 ExtensionRendererState::GetInstance()->Shutdown();
262 media_file_system_registry_.reset();
263 // Remove the global instance of the Storage Monitor now. Otherwise the
264 // FILE thread would be gone when we try to release it in the dtor and
265 // Valgrind would report a leak on almost every single browser_test.
266 // TODO(gbillock): Make this unnecessary.
267 storage_monitor::StorageMonitor::Destroy();
268 #endif
270 message_center::MessageCenter::Shutdown();
272 #if defined(ENABLE_CONFIGURATION_POLICY)
273 // The policy providers managed by |browser_policy_connector_| need to shut
274 // down while the IO and FILE threads are still alive.
275 if (browser_policy_connector_)
276 browser_policy_connector_->Shutdown();
277 #endif
279 // The |gcm_driver_| must shut down while the IO thread is still alive.
280 if (gcm_driver_)
281 gcm_driver_->Shutdown();
283 // Stop the watchdog thread before stopping other threads.
284 watchdog_thread_.reset();
286 #if defined(USE_AURA)
287 // Delete aura after the metrics service has been deleted as it accesses
288 // monitor information.
289 aura::Env::DeleteInstance();
290 #endif
292 platform_part()->StartTearDown();
294 #if defined(ENABLE_WEBRTC)
295 // Cancel any uploads to release the system url request context references.
296 if (webrtc_log_uploader_)
297 webrtc_log_uploader_->StartShutdown();
298 #endif
300 if (local_state())
301 local_state()->CommitPendingWrite();
304 void BrowserProcessImpl::PostDestroyThreads() {
305 // With the file_thread_ flushed, we can release any icon resources.
306 icon_manager_.reset();
308 #if defined(ENABLE_WEBRTC)
309 // Must outlive the file thread.
310 webrtc_log_uploader_.reset();
311 #endif
313 // Reset associated state right after actual thread is stopped,
314 // as io_thread_.global_ cleanup happens in CleanUp on the IO
315 // thread, i.e. as the thread exits its message loop.
317 // This is important also because in various places, the
318 // IOThread object being NULL is considered synonymous with the
319 // IO thread having stopped.
320 io_thread_.reset();
323 unsigned int BrowserProcessImpl::AddRefModule() {
324 DCHECK(CalledOnValidThread());
326 // CHECK(!IsShuttingDown());
327 if (IsShuttingDown()) {
328 // Copy the stacktrace which released the final reference onto our stack so
329 // it will be available in the crash report for inspection.
330 base::debug::StackTrace callstack = release_last_reference_callstack_;
331 base::debug::Alias(&callstack);
332 CHECK(false);
335 did_start_ = true;
336 module_ref_count_++;
337 return module_ref_count_;
340 static void ShutdownServiceWorkerContext(content::StoragePartition* partition) {
341 partition->GetServiceWorkerContext()->Terminate();
344 unsigned int BrowserProcessImpl::ReleaseModule() {
345 DCHECK(CalledOnValidThread());
346 DCHECK_NE(0u, module_ref_count_);
347 module_ref_count_--;
348 if (0 == module_ref_count_) {
349 release_last_reference_callstack_ = base::debug::StackTrace();
351 // Stop service workers
352 ProfileManager* pm = profile_manager();
353 std::vector<Profile*> profiles(pm->GetLoadedProfiles());
354 for (size_t i = 0; i < profiles.size(); ++i) {
355 content::BrowserContext::ForEachStoragePartition(
356 profiles[i], base::Bind(ShutdownServiceWorkerContext));
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();
364 #endif
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();
372 #endif
374 CHECK(base::MessageLoop::current()->is_running());
376 #if defined(OS_MACOSX)
377 base::MessageLoop::current()->PostTask(
378 FROM_HERE,
379 base::Bind(ChromeBrowserMainPartsMac::DidEndMainMessageLoop));
380 #endif
381 base::MessageLoop::current()->Quit();
383 return module_ref_count_;
386 namespace {
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
391 // continuing.
392 class RundownTaskCounter :
393 public base::RefCountedThreadSafe<RundownTaskCounter> {
394 public:
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);
405 private:
406 friend class base::RefCountedThreadSafe<RundownTaskCounter>;
407 ~RundownTaskCounter() {}
409 // Decrements the counter and releases the waitable event on transition to
410 // zero.
411 void Decrement();
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.
445 Decrement();
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";
464 } // namespace
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());
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());
493 #endif
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));
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
513 // process.
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));
526 #else
527 NOTIMPLEMENTED();
528 #endif
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_)
572 CreateLocalState();
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();
594 #else
595 return NULL;
596 #endif
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();
620 #else
621 return NULL;
622 #endif
625 policy::PolicyService* BrowserProcessImpl::policy_service() {
626 #if defined(ENABLE_CONFIGURATION_POLICY)
627 return browser_policy_connector()->GetPolicyService();
628 #else
629 if (!policy_service_.get())
630 policy_service_.reset(new policy::PolicyServiceStub());
631 return policy_service_.get();
632 #endif
635 IconManager* BrowserProcessImpl::icon_manager() {
636 DCHECK(CalledOnValidThread());
637 if (!created_icon_manager_)
638 CreateIconManager();
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,
659 int port) {
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));
668 #endif
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_FULL_PRINTING)
684 DCHECK(CalledOnValidThread());
685 if (!print_preview_dialog_controller_.get())
686 CreatePrintPreviewDialogController();
687 return print_preview_dialog_controller_.get();
688 #else
689 NOTIMPLEMENTED();
690 return NULL;
691 #endif
694 printing::BackgroundPrintingManager*
695 BrowserProcessImpl::background_printing_manager() {
696 #if defined(ENABLE_FULL_PRINTING)
697 DCHECK(CalledOnValidThread());
698 if (!background_printing_manager_.get())
699 CreateBackgroundPrintingManager();
700 return background_printing_manager_.get();
701 #else
702 NOTIMPLEMENTED();
703 return NULL;
704 #endif
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());
716 return locale_;
719 void BrowserProcessImpl::SetApplicationLocale(const std::string& locale) {
720 locale_ = locale;
721 extension_l10n_util::SetProcessLocale(locale);
722 chrome::ChromeContentBrowserClient::SetApplicationLocale(locale);
723 translate::TranslateDownloadManager::GetInstance()->set_application_locale(
724 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();
736 #else
737 return NULL;
738 #endif
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();
751 #endif
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()),
757 local_state()));
759 return network_time_tracker_.get();
762 gcm::GCMDriver* BrowserProcessImpl::gcm_driver() {
763 DCHECK(CalledOnValidThread());
764 if (!gcm_driver_)
765 CreateGCMDriver();
766 return gcm_driver_.get();
769 // static
770 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple* registry) {
771 registry->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled,
772 false);
773 // This policy needs to be defined before the net subsystem is initialized,
774 // so we do it here.
775 registry->RegisterIntegerPref(prefs::kMaxConnectionsPerProxy,
776 net::kDefaultMaxSocketsPerProxyServer);
778 registry->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt, false);
780 registry->RegisterBooleanPref(prefs::kBrowserGuestModeEnabled, true);
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)
785 #if defined(OS_WIN)
786 if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
787 registry->RegisterStringPref(prefs::kRelaunchMode,
788 upgrade_util::kRelaunchModeDefault);
790 #endif
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
797 // are registered.
798 registry->RegisterStringPref(prefs::kApplicationLocale, std::string());
799 #if defined(OS_CHROMEOS)
800 registry->RegisterStringPref(prefs::kOwnerLocale, std::string());
801 registry->RegisterStringPref(prefs::kHardwareKeyboardLayout,
802 std::string());
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();
829 #else
830 NOTIMPLEMENTED();
831 return NULL;
832 #endif
835 void BrowserProcessImpl::set_background_mode_manager_for_test(
836 scoped_ptr<BackgroundModeManager> manager) {
837 background_mode_manager_ = manager.Pass();
840 StatusTray* BrowserProcessImpl::status_tray() {
841 DCHECK(CalledOnValidThread());
842 if (!status_tray_.get())
843 CreateStatusTray();
844 return status_tray_.get();
848 SafeBrowsingService* BrowserProcessImpl::safe_browsing_service() {
849 DCHECK(CalledOnValidThread());
850 if (!created_safe_browsing_service_)
851 CreateSafeBrowsingService();
852 return safe_browsing_service_.get();
855 safe_browsing::ClientSideDetectionService*
856 BrowserProcessImpl::safe_browsing_detection_service() {
857 DCHECK(CalledOnValidThread());
858 if (safe_browsing_service())
859 return safe_browsing_service()->safe_browsing_detection_service();
860 return NULL;
863 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
864 void BrowserProcessImpl::StartAutoupdateTimer() {
865 autoupdate_timer_.Start(FROM_HERE,
866 base::TimeDelta::FromHours(kUpdateCheckIntervalHours),
867 this,
868 &BrowserProcessImpl::OnAutoupdateTimer);
870 #endif
872 ChromeNetLog* BrowserProcessImpl::net_log() {
873 return net_log_.get();
876 prerender::PrerenderTracker* BrowserProcessImpl::prerender_tracker() {
877 if (!prerender_tracker_.get())
878 prerender_tracker_.reset(new prerender::PrerenderTracker);
880 return prerender_tracker_.get();
883 component_updater::ComponentUpdateService*
884 BrowserProcessImpl::component_updater() {
885 if (!component_updater_.get()) {
886 if (!BrowserThread::CurrentlyOn(BrowserThread::UI))
887 return NULL;
888 component_updater::Configurator* configurator =
889 component_updater::MakeChromeComponentUpdaterConfigurator(
890 CommandLine::ForCurrentProcess(),
891 io_thread()->system_url_request_context_getter());
892 // Creating the component updater does not do anything, components
893 // need to be registered and Start() needs to be called.
894 component_updater_.reset(ComponentUpdateServiceFactory(configurator));
896 return component_updater_.get();
899 CRLSetFetcher* BrowserProcessImpl::crl_set_fetcher() {
900 if (!crl_set_fetcher_.get())
901 crl_set_fetcher_ = new CRLSetFetcher();
902 return crl_set_fetcher_.get();
905 component_updater::PnaclComponentInstaller*
906 BrowserProcessImpl::pnacl_component_installer() {
907 #if !defined(DISABLE_NACL)
908 if (!pnacl_component_installer_.get()) {
909 pnacl_component_installer_.reset(
910 new component_updater::PnaclComponentInstaller());
912 return pnacl_component_installer_.get();
913 #else
914 return NULL;
915 #endif
918 void BrowserProcessImpl::ResourceDispatcherHostCreated() {
919 resource_dispatcher_host_delegate_.reset(
920 new ChromeResourceDispatcherHostDelegate(prerender_tracker()));
921 ResourceDispatcherHost::Get()->SetDelegate(
922 resource_dispatcher_host_delegate_.get());
924 pref_change_registrar_.Add(
925 prefs::kAllowCrossOriginAuthPrompt,
926 base::Bind(&BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy,
927 base::Unretained(this)));
928 ApplyAllowCrossOriginAuthPromptPolicy();
931 void BrowserProcessImpl::CreateWatchdogThread() {
932 DCHECK(!created_watchdog_thread_ && watchdog_thread_.get() == NULL);
933 created_watchdog_thread_ = true;
935 scoped_ptr<WatchDogThread> thread(new WatchDogThread());
936 base::Thread::Options options;
937 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
938 if (!thread->StartWithOptions(options))
939 return;
940 watchdog_thread_.swap(thread);
943 void BrowserProcessImpl::CreateProfileManager() {
944 DCHECK(!created_profile_manager_ && profile_manager_.get() == NULL);
945 created_profile_manager_ = true;
947 base::FilePath user_data_dir;
948 PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
949 profile_manager_.reset(new ProfileManager(user_data_dir));
952 void BrowserProcessImpl::CreateLocalState() {
953 DCHECK(!created_local_state_ && local_state_.get() == NULL);
954 created_local_state_ = true;
956 base::FilePath local_state_path;
957 CHECK(PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path));
958 scoped_refptr<PrefRegistrySimple> pref_registry = new PrefRegistrySimple;
960 // Register local state preferences.
961 chrome::RegisterLocalState(pref_registry.get());
963 local_state_ =
964 chrome_prefs::CreateLocalState(local_state_path,
965 local_state_task_runner_.get(),
966 policy_service(),
967 pref_registry,
968 false).Pass();
970 pref_change_registrar_.Init(local_state_.get());
972 // Initialize the notification for the default browser setting policy.
973 pref_change_registrar_.Add(
974 prefs::kDefaultBrowserSettingEnabled,
975 base::Bind(&BrowserProcessImpl::ApplyDefaultBrowserPolicy,
976 base::Unretained(this)));
978 // This preference must be kept in sync with external values; update them
979 // whenever the preference or its controlling policy changes.
980 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
981 pref_change_registrar_.Add(
982 prefs::kMetricsReportingEnabled,
983 base::Bind(&BrowserProcessImpl::ApplyMetricsReportingPolicy,
984 base::Unretained(this)));
985 #endif
987 int max_per_proxy = local_state_->GetInteger(prefs::kMaxConnectionsPerProxy);
988 net::ClientSocketPoolManager::set_max_sockets_per_proxy_server(
989 net::HttpNetworkSession::NORMAL_SOCKET_POOL,
990 std::max(std::min(max_per_proxy, 99),
991 net::ClientSocketPoolManager::max_sockets_per_group(
992 net::HttpNetworkSession::NORMAL_SOCKET_POOL)));
995 void BrowserProcessImpl::PreCreateThreads() {
996 io_thread_.reset(
997 new IOThread(local_state(), policy_service(), net_log_.get(),
998 extension_event_router_forwarder()));
1001 void BrowserProcessImpl::PreMainMessageLoopRun() {
1002 #if defined(ENABLE_CONFIGURATION_POLICY)
1003 // browser_policy_connector() is created very early because local_state()
1004 // needs policy to be initialized with the managed preference values.
1005 // However, policy fetches from the network and loading of disk caches
1006 // requires that threads are running; this Init() call lets the connector
1007 // resume its initialization now that the loops are spinning and the
1008 // system request context is available for the fetchers.
1009 browser_policy_connector()->Init(local_state(), system_request_context());
1010 #endif
1012 if (local_state_->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled))
1013 ApplyDefaultBrowserPolicy();
1015 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1016 ApplyMetricsReportingPolicy();
1017 #endif
1019 #if defined(ENABLE_PLUGINS)
1020 PluginService* plugin_service = PluginService::GetInstance();
1021 plugin_service->SetFilter(ChromePluginServiceFilter::GetInstance());
1022 plugin_service->StartWatchingPlugins();
1024 #if defined(OS_POSIX)
1025 // Also find plugins in a user-specific plugins dir,
1026 // e.g. ~/.config/chromium/Plugins.
1027 const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
1028 if (!cmd_line.HasSwitch(switches::kDisablePluginsDiscovery)) {
1029 base::FilePath user_data_dir;
1030 if (PathService::Get(chrome::DIR_USER_DATA, &user_data_dir))
1031 plugin_service->AddExtraPluginDir(user_data_dir.Append("Plugins"));
1033 #endif
1035 // Triggers initialization of the singleton instance on UI thread.
1036 PluginFinder::GetInstance()->Init();
1038 #if defined(ENABLE_PLUGIN_INSTALLATION)
1039 DCHECK(!plugins_resource_service_.get());
1040 plugins_resource_service_ = new PluginsResourceService(local_state());
1041 plugins_resource_service_->Init();
1042 #endif
1043 #endif // defined(ENABLE_PLUGINS)
1045 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1046 if (!command_line.HasSwitch(switches::kDisableWebResources)) {
1047 DCHECK(!promo_resource_service_.get());
1048 promo_resource_service_ = new PromoResourceService;
1049 promo_resource_service_->StartAfterDelay();
1052 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1053 storage_monitor::StorageMonitor::Create();
1054 #endif
1056 platform_part_->PreMainMessageLoopRun();
1059 void BrowserProcessImpl::CreateIconManager() {
1060 DCHECK(!created_icon_manager_ && icon_manager_.get() == NULL);
1061 created_icon_manager_ = true;
1062 icon_manager_.reset(new IconManager);
1065 void BrowserProcessImpl::CreateIntranetRedirectDetector() {
1066 DCHECK(intranet_redirect_detector_.get() == NULL);
1067 scoped_ptr<IntranetRedirectDetector> intranet_redirect_detector(
1068 new IntranetRedirectDetector);
1069 intranet_redirect_detector_.swap(intranet_redirect_detector);
1072 void BrowserProcessImpl::CreateNotificationUIManager() {
1073 #if defined(ENABLE_NOTIFICATIONS)
1074 DCHECK(notification_ui_manager_.get() == NULL);
1075 notification_ui_manager_.reset(NotificationUIManager::Create(local_state()));
1076 created_notification_ui_manager_ = true;
1077 #endif
1080 void BrowserProcessImpl::CreateBackgroundModeManager() {
1081 DCHECK(background_mode_manager_.get() == NULL);
1082 background_mode_manager_.reset(
1083 new BackgroundModeManager(CommandLine::ForCurrentProcess(),
1084 &profile_manager()->GetProfileInfoCache()));
1087 void BrowserProcessImpl::CreateStatusTray() {
1088 DCHECK(status_tray_.get() == NULL);
1089 status_tray_.reset(StatusTray::Create());
1092 void BrowserProcessImpl::CreatePrintPreviewDialogController() {
1093 #if defined(ENABLE_FULL_PRINTING)
1094 DCHECK(print_preview_dialog_controller_.get() == NULL);
1095 print_preview_dialog_controller_ =
1096 new printing::PrintPreviewDialogController();
1097 #else
1098 NOTIMPLEMENTED();
1099 #endif
1102 void BrowserProcessImpl::CreateBackgroundPrintingManager() {
1103 #if defined(ENABLE_FULL_PRINTING)
1104 DCHECK(background_printing_manager_.get() == NULL);
1105 background_printing_manager_.reset(new printing::BackgroundPrintingManager());
1106 #else
1107 NOTIMPLEMENTED();
1108 #endif
1111 void BrowserProcessImpl::CreateSafeBrowsingService() {
1112 DCHECK(safe_browsing_service_.get() == NULL);
1113 // Set this flag to true so that we don't retry indefinitely to
1114 // create the service class if there was an error.
1115 created_safe_browsing_service_ = true;
1116 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
1117 safe_browsing_service_ = SafeBrowsingService::CreateSafeBrowsingService();
1118 safe_browsing_service_->Initialize();
1119 #endif
1122 void BrowserProcessImpl::CreateGCMDriver() {
1123 DCHECK(!gcm_driver_);
1125 #if defined(OS_ANDROID)
1126 gcm_driver_.reset(new gcm::GCMDriverAndroid);
1127 #else
1128 base::FilePath store_path;
1129 CHECK(PathService::Get(chrome::DIR_GLOBAL_GCM_STORE, &store_path));
1130 gcm_driver_ = gcm::CreateGCMDriverDesktop(
1131 make_scoped_ptr(new gcm::GCMClientFactory),
1132 store_path,
1133 system_request_context());
1134 // Sign-in is not required for device-level GCM usage. So we just call
1135 // OnSignedIn to assume always signed-in. Note that GCM will not be started
1136 // at this point since no one has asked for it yet.
1137 // TODO(jianli): To be removed when sign-in enforcement is dropped.
1138 gcm_driver_->OnSignedIn();
1139 #endif // defined(OS_ANDROID)
1142 void BrowserProcessImpl::ApplyDefaultBrowserPolicy() {
1143 if (local_state()->GetBoolean(prefs::kDefaultBrowserSettingEnabled)) {
1144 scoped_refptr<ShellIntegration::DefaultWebClientWorker>
1145 set_browser_worker = new ShellIntegration::DefaultBrowserWorker(NULL);
1146 set_browser_worker->StartSetAsDefault();
1150 void BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy() {
1151 bool value = local_state()->GetBoolean(prefs::kAllowCrossOriginAuthPrompt);
1152 ResourceDispatcherHost::Get()->SetAllowCrossOriginAuthPrompt(value);
1155 void BrowserProcessImpl::ApplyMetricsReportingPolicy() {
1156 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1157 CHECK(BrowserThread::PostTask(
1158 BrowserThread::FILE, FROM_HERE,
1159 base::Bind(
1160 base::IgnoreResult(&GoogleUpdateSettings::SetCollectStatsConsent),
1161 local_state()->GetBoolean(prefs::kMetricsReportingEnabled))));
1162 #endif
1165 // Mac is currently not supported.
1166 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
1168 bool BrowserProcessImpl::CanAutorestartForUpdate() const {
1169 // Check if browser is in the background and if it needs to be restarted to
1170 // apply a pending update.
1171 return chrome::GetTotalBrowserCount() == 0 && chrome::WillKeepAlive() &&
1172 upgrade_util::IsUpdatePendingRestart();
1175 // Switches to add when auto-restarting Chrome.
1176 const char* const kSwitchesToAddOnAutorestart[] = {
1177 switches::kNoStartupWindow
1180 void BrowserProcessImpl::RestartBackgroundInstance() {
1181 CommandLine* old_cl = CommandLine::ForCurrentProcess();
1182 scoped_ptr<CommandLine> new_cl(new CommandLine(old_cl->GetProgram()));
1184 std::map<std::string, CommandLine::StringType> switches =
1185 old_cl->GetSwitches();
1187 switches::RemoveSwitchesForAutostart(&switches);
1189 // Append the rest of the switches (along with their values, if any)
1190 // to the new command line
1191 for (std::map<std::string, CommandLine::StringType>::const_iterator i =
1192 switches.begin(); i != switches.end(); ++i) {
1193 CommandLine::StringType switch_value = i->second;
1194 if (switch_value.length() > 0) {
1195 new_cl->AppendSwitchNative(i->first, i->second);
1196 } else {
1197 new_cl->AppendSwitch(i->first);
1201 // Ensure that our desired switches are set on the new process.
1202 for (size_t i = 0; i < arraysize(kSwitchesToAddOnAutorestart); ++i) {
1203 if (!new_cl->HasSwitch(kSwitchesToAddOnAutorestart[i]))
1204 new_cl->AppendSwitch(kSwitchesToAddOnAutorestart[i]);
1207 DLOG(WARNING) << "Shutting down current instance of the browser.";
1208 chrome::AttemptExit();
1210 // Transfer ownership to Upgrade.
1211 upgrade_util::SetNewCommandLine(new_cl.release());
1214 void BrowserProcessImpl::OnAutoupdateTimer() {
1215 if (CanAutorestartForUpdate()) {
1216 DLOG(WARNING) << "Detected update. Restarting browser.";
1217 RestartBackgroundInstance();
1221 #endif // (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)