ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / chrome / browser / browser_process_impl.cc
blob2f86717872710712e8fbce9a5e63351dc22727c5
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/metrics/histogram_macros.h"
20 #include "base/path_service.h"
21 #include "base/prefs/json_pref_store.h"
22 #include "base/prefs/pref_registry_simple.h"
23 #include "base/prefs/pref_service.h"
24 #include "base/synchronization/waitable_event.h"
25 #include "base/threading/thread.h"
26 #include "base/threading/thread_restrictions.h"
27 #include "base/time/default_tick_clock.h"
28 #include "base/trace_event/trace_event.h"
29 #include "chrome/browser/chrome_browser_main.h"
30 #include "chrome/browser/chrome_content_browser_client.h"
31 #include "chrome/browser/chrome_notification_types.h"
32 #include "chrome/browser/component_updater/chrome_component_updater_configurator.h"
33 #include "chrome/browser/component_updater/supervised_user_whitelist_installer.h"
34 #include "chrome/browser/defaults.h"
35 #include "chrome/browser/devtools/remote_debugging_server.h"
36 #include "chrome/browser/download/download_request_limiter.h"
37 #include "chrome/browser/download/download_status_updater.h"
38 #include "chrome/browser/first_run/upgrade_util.h"
39 #include "chrome/browser/gpu/gl_string_manager.h"
40 #include "chrome/browser/gpu/gpu_mode_manager.h"
41 #include "chrome/browser/icon_manager.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/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/browser_dialogs.h"
64 #include "chrome/browser/ui/browser_finder.h"
65 #include "chrome/browser/ui/user_manager.h"
66 #include "chrome/browser/update_client/chrome_update_query_params_delegate.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/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 "components/update_client/update_query_params.h"
85 #include "components/web_resource/web_resource_pref_names.h"
86 #include "content/public/browser/browser_thread.h"
87 #include "content/public/browser/child_process_security_policy.h"
88 #include "content/public/browser/notification_details.h"
89 #include "content/public/browser/plugin_service.h"
90 #include "content/public/browser/render_process_host.h"
91 #include "content/public/browser/resource_dispatcher_host.h"
92 #include "content/public/browser/service_worker_context.h"
93 #include "content/public/browser/storage_partition.h"
94 #include "extensions/common/constants.h"
95 #include "net/socket/client_socket_pool_manager.h"
96 #include "net/url_request/url_request_context_getter.h"
97 #include "ui/base/idle/idle.h"
98 #include "ui/base/l10n/l10n_util.h"
99 #include "ui/message_center/message_center.h"
101 #if defined(OS_WIN)
102 #include "base/win/windows_version.h"
103 #include "ui/views/focus/view_storage.h"
104 #elif defined(OS_MACOSX)
105 #include "chrome/browser/chrome_browser_main_mac.h"
106 #endif
108 #if !defined(OS_ANDROID)
109 #include "chrome/browser/chrome_device_client.h"
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_BACKGROUND)
119 #include "chrome/browser/background/background_mode_manager.h"
120 #endif
122 #if defined(ENABLE_CONFIGURATION_POLICY)
123 #include "components/policy/core/browser/browser_policy_connector.h"
124 #else
125 #include "components/policy/core/common/policy_service_stub.h"
126 #endif // defined(ENABLE_CONFIGURATION_POLICY)
128 #if defined(ENABLE_EXTENSIONS)
129 #include "chrome/browser/extensions/chrome_extensions_browser_client.h"
130 #include "chrome/browser/extensions/event_router_forwarder.h"
131 #include "chrome/browser/extensions/extension_renderer_state.h"
132 #include "chrome/browser/media_galleries/media_file_system_registry.h"
133 #include "chrome/browser/ui/apps/chrome_app_window_client.h"
134 #include "components/storage_monitor/storage_monitor.h"
135 #include "extensions/common/extension_l10n_util.h"
136 #endif
138 #if !defined(DISABLE_NACL)
139 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
140 #endif
142 #if defined(ENABLE_PLUGIN_INSTALLATION)
143 #include "chrome/browser/plugins/plugins_resource_service.h"
144 #endif
146 #if defined(ENABLE_WEBRTC)
147 #include "chrome/browser/media/webrtc_log_uploader.h"
148 #endif
150 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
151 // How often to check if the persistent instance of Chrome needs to restart
152 // to install an update.
153 static const int kUpdateCheckIntervalHours = 6;
154 #endif
156 #if defined(USE_X11) || defined(OS_WIN)
157 // How long to wait for the File thread to complete during EndSession, on Linux
158 // and Windows. We have a timeout here because we're unable to run the UI
159 // messageloop and there's some deadlock risk. Our only option is to exit
160 // anyway.
161 static const int kEndSessionTimeoutSeconds = 10;
162 #endif
164 using content::BrowserThread;
165 using content::ChildProcessSecurityPolicy;
166 using content::PluginService;
167 using content::ResourceDispatcherHost;
169 BrowserProcessImpl::BrowserProcessImpl(
170 base::SequencedTaskRunner* local_state_task_runner,
171 const base::CommandLine& command_line)
172 : created_watchdog_thread_(false),
173 created_browser_policy_connector_(false),
174 created_profile_manager_(false),
175 created_local_state_(false),
176 created_icon_manager_(false),
177 created_notification_ui_manager_(false),
178 created_safe_browsing_service_(false),
179 module_ref_count_(0),
180 did_start_(false),
181 download_status_updater_(new DownloadStatusUpdater),
182 local_state_task_runner_(local_state_task_runner) {
183 g_browser_process = this;
184 platform_part_.reset(new BrowserProcessPlatformPart());
186 #if defined(ENABLE_PRINTING)
187 // Must be created after the NotificationService.
188 print_job_manager_.reset(new printing::PrintJobManager);
189 #endif
191 net_log_.reset(new ChromeNetLog);
193 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
194 extensions::kExtensionScheme);
195 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
196 extensions::kExtensionResourceScheme);
197 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
198 chrome::kChromeSearchScheme);
200 #if defined(OS_MACOSX)
201 ui::InitIdleMonitor();
202 #endif
204 #if !defined(OS_ANDROID)
205 device_client_.reset(new ChromeDeviceClient);
206 #endif
208 #if defined(ENABLE_EXTENSIONS)
209 // Athena sets its own instance during Athena's init process.
210 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());
221 #endif
223 message_center::MessageCenter::Initialize();
225 update_client::UpdateQueryParams::SetDelegate(
226 ChromeUpdateQueryParamsDelegate::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();
248 #endif
249 promo_resource_service_.reset();
250 #if defined(ENABLE_PLUGIN_INSTALLATION)
251 plugins_resource_service_.reset();
252 #endif
254 // Need to clear the desktop notification balloons before the io_thread_ and
255 // before the profiles, since if there are any still showing we will access
256 // those things during teardown.
257 notification_ui_manager_.reset();
259 // The SupervisedUserWhitelistInstaller observes the ProfileInfoCache, so it
260 // needs to be shut down before the ProfileManager.
261 supervised_user_whitelist_installer_.reset();
263 // Need to clear profiles (download managers) before the io_thread_.
265 TRACE_EVENT0("shutdown",
266 "BrowserProcessImpl::StartTearDown:ProfileManager");
267 // The desktop User Manager needs to be closed before the guest profile
268 // can be destroyed.
269 if (switches::IsNewAvatarMenu())
270 UserManager::Hide();
271 profile_manager_.reset();
274 #if !defined(OS_ANDROID)
275 // Debugger must be cleaned up before IO thread and NotificationService.
276 remote_debugging_server_.reset();
277 #endif
279 #if defined(ENABLE_EXTENSIONS)
280 ExtensionRendererState::GetInstance()->Shutdown();
282 media_file_system_registry_.reset();
283 // Remove the global instance of the Storage Monitor now. Otherwise the
284 // FILE thread would be gone when we try to release it in the dtor and
285 // Valgrind would report a leak on almost every single browser_test.
286 // TODO(gbillock): Make this unnecessary.
287 storage_monitor::StorageMonitor::Destroy();
288 #endif
290 message_center::MessageCenter::Shutdown();
292 #if defined(ENABLE_CONFIGURATION_POLICY)
293 // The policy providers managed by |browser_policy_connector_| need to shut
294 // down while the IO and FILE threads are still alive. The monitoring
295 // framework owned by |browser_policy_connector_| relies on |gcm_driver_|, so
296 // this must be shutdown before |gcm_driver_| below.
297 if (browser_policy_connector_)
298 browser_policy_connector_->Shutdown();
299 #endif
301 // The |gcm_driver_| must shut down while the IO thread is still alive.
302 if (gcm_driver_)
303 gcm_driver_->Shutdown();
305 // Stop the watchdog thread before stopping other threads.
306 watchdog_thread_.reset();
308 #if defined(USE_AURA)
309 // Delete aura after the metrics service has been deleted as it accesses
310 // monitor information.
311 aura::Env::DeleteInstance();
312 #endif
314 platform_part()->StartTearDown();
316 #if defined(ENABLE_WEBRTC)
317 // Cancel any uploads to release the system url request context references.
318 if (webrtc_log_uploader_)
319 webrtc_log_uploader_->StartShutdown();
320 #endif
322 if (local_state())
323 local_state()->CommitPendingWrite();
326 void BrowserProcessImpl::PostDestroyThreads() {
327 // With the file_thread_ flushed, we can release any icon resources.
328 icon_manager_.reset();
330 #if defined(ENABLE_WEBRTC)
331 // Must outlive the file thread.
332 webrtc_log_uploader_.reset();
333 #endif
335 // Reset associated state right after actual thread is stopped,
336 // as io_thread_.global_ cleanup happens in CleanUp on the IO
337 // thread, i.e. as the thread exits its message loop.
339 // This is important also because in various places, the
340 // IOThread object being NULL is considered synonymous with the
341 // IO thread having stopped.
342 io_thread_.reset();
345 unsigned int BrowserProcessImpl::AddRefModule() {
346 DCHECK(CalledOnValidThread());
348 // CHECK(!IsShuttingDown());
349 if (IsShuttingDown()) {
350 // Copy the stacktrace which released the final reference onto our stack so
351 // it will be available in the crash report for inspection.
352 base::debug::StackTrace callstack = release_last_reference_callstack_;
353 base::debug::Alias(&callstack);
354 CHECK(false);
357 did_start_ = true;
358 module_ref_count_++;
359 return module_ref_count_;
362 unsigned int BrowserProcessImpl::ReleaseModule() {
363 DCHECK(CalledOnValidThread());
364 DCHECK_NE(0u, module_ref_count_);
365 module_ref_count_--;
366 if (0 == module_ref_count_) {
367 release_last_reference_callstack_ = base::debug::StackTrace();
369 #if defined(ENABLE_PRINTING)
370 // Wait for the pending print jobs to finish. Don't do this later, since
371 // this might cause a nested message loop to run, and we don't want pending
372 // tasks to run once teardown has started.
373 print_job_manager_->Shutdown();
374 #endif
376 #if defined(LEAK_SANITIZER)
377 // Check for memory leaks now, before we start shutting down threads. Doing
378 // this early means we won't report any shutdown-only leaks (as they have
379 // not yet happened at this point).
380 // If leaks are found, this will make the process exit immediately.
381 __lsan_do_leak_check();
382 #endif
384 CHECK(base::MessageLoop::current()->is_running());
386 #if defined(OS_MACOSX)
387 base::MessageLoop::current()->PostTask(
388 FROM_HERE,
389 base::Bind(ChromeBrowserMainPartsMac::DidEndMainMessageLoop));
390 #endif
391 base::MessageLoop::current()->Quit();
393 return module_ref_count_;
396 namespace {
398 // Used at the end of session to block the UI thread for completion of sentinel
399 // tasks on the set of threads used to persist profile data and local state.
400 // This is done to ensure that the data has been persisted to disk before
401 // continuing.
402 class RundownTaskCounter :
403 public base::RefCountedThreadSafe<RundownTaskCounter> {
404 public:
405 RundownTaskCounter();
407 // Posts a rundown task to |task_runner|, can be invoked an arbitrary number
408 // of times before calling TimedWait.
409 void Post(base::SequencedTaskRunner* task_runner);
411 // Waits until the count is zero or |max_time| has passed.
412 // This can only be called once per instance.
413 bool TimedWait(const base::TimeDelta& max_time);
415 private:
416 friend class base::RefCountedThreadSafe<RundownTaskCounter>;
417 ~RundownTaskCounter() {}
419 // Decrements the counter and releases the waitable event on transition to
420 // zero.
421 void Decrement();
423 // The count starts at one to defer the possibility of one->zero transitions
424 // until TimedWait is called.
425 base::AtomicRefCount count_;
426 base::WaitableEvent waitable_event_;
428 DISALLOW_COPY_AND_ASSIGN(RundownTaskCounter);
431 RundownTaskCounter::RundownTaskCounter()
432 : count_(1), waitable_event_(true, false) {
435 void RundownTaskCounter::Post(base::SequencedTaskRunner* task_runner) {
436 // As the count starts off at one, it should never get to zero unless
437 // TimedWait has been called.
438 DCHECK(!base::AtomicRefCountIsZero(&count_));
440 base::AtomicRefCountInc(&count_);
442 // The task must be non-nestable to guarantee that it runs after all tasks
443 // currently scheduled on |task_runner| have completed.
444 task_runner->PostNonNestableTask(FROM_HERE,
445 base::Bind(&RundownTaskCounter::Decrement, this));
448 void RundownTaskCounter::Decrement() {
449 if (!base::AtomicRefCountDec(&count_))
450 waitable_event_.Signal();
453 bool RundownTaskCounter::TimedWait(const base::TimeDelta& max_time) {
454 // Decrement the excess count from the constructor.
455 Decrement();
457 return waitable_event_.TimedWait(max_time);
460 } // namespace
462 void BrowserProcessImpl::EndSession() {
463 // Mark all the profiles as clean.
464 ProfileManager* pm = profile_manager();
465 std::vector<Profile*> profiles(pm->GetLoadedProfiles());
466 scoped_refptr<RundownTaskCounter> rundown_counter(new RundownTaskCounter());
467 for (size_t i = 0; i < profiles.size(); ++i) {
468 Profile* profile = profiles[i];
469 profile->SetExitType(Profile::EXIT_SESSION_ENDED);
471 rundown_counter->Post(profile->GetIOTaskRunner().get());
474 // Tell the metrics service it was cleanly shutdown.
475 metrics::MetricsService* metrics = g_browser_process->metrics_service();
476 if (metrics && local_state()) {
477 metrics->RecordStartOfSessionEnd();
478 #if !defined(OS_CHROMEOS)
479 // MetricsService lazily writes to prefs, force it to write now.
480 // On ChromeOS, chrome gets killed when hangs, so no need to
481 // commit metrics::prefs::kStabilitySessionEndCompleted change immediately.
482 local_state()->CommitPendingWrite();
484 rundown_counter->Post(local_state_task_runner_.get());
485 #endif
488 // http://crbug.com/125207
489 base::ThreadRestrictions::ScopedAllowWait allow_wait;
491 // We must write that the profile and metrics service shutdown cleanly,
492 // otherwise on startup we'll think we crashed. So we block until done and
493 // then proceed with normal shutdown.
495 // If you change the condition here, be sure to also change
496 // ProfileBrowserTests to match.
497 #if defined(USE_X11) || defined(OS_WIN)
498 // Do a best-effort wait on the successful countdown of rundown tasks. Note
499 // that if we don't complete "quickly enough", Windows will terminate our
500 // process.
502 // On Windows, we previously posted a message to FILE and then ran a nested
503 // message loop, waiting for that message to be processed until quitting.
504 // However, doing so means that other messages will also be processed. In
505 // particular, if the GPU process host notices that the GPU has been killed
506 // during shutdown, it races exiting the nested loop with the process host
507 // blocking the message loop attempting to re-establish a connection to the
508 // GPU process synchronously. Because the system may not be allowing
509 // processes to launch, this can result in a hang. See
510 // http://crbug.com/318527.
511 rundown_counter->TimedWait(
512 base::TimeDelta::FromSeconds(kEndSessionTimeoutSeconds));
513 #else
514 NOTIMPLEMENTED();
515 #endif
518 MetricsServicesManager* BrowserProcessImpl::GetMetricsServicesManager() {
519 DCHECK(CalledOnValidThread());
520 if (!metrics_services_manager_)
521 metrics_services_manager_.reset(new MetricsServicesManager(local_state()));
522 return metrics_services_manager_.get();
525 metrics::MetricsService* BrowserProcessImpl::metrics_service() {
526 DCHECK(CalledOnValidThread());
527 return GetMetricsServicesManager()->GetMetricsService();
530 rappor::RapporService* BrowserProcessImpl::rappor_service() {
531 DCHECK(CalledOnValidThread());
532 return GetMetricsServicesManager()->GetRapporService();
535 IOThread* BrowserProcessImpl::io_thread() {
536 DCHECK(CalledOnValidThread());
537 DCHECK(io_thread_.get());
538 return io_thread_.get();
541 WatchDogThread* BrowserProcessImpl::watchdog_thread() {
542 DCHECK(CalledOnValidThread());
543 if (!created_watchdog_thread_)
544 CreateWatchdogThread();
545 DCHECK(watchdog_thread_.get() != NULL);
546 return watchdog_thread_.get();
549 ProfileManager* BrowserProcessImpl::profile_manager() {
550 DCHECK(CalledOnValidThread());
551 if (!created_profile_manager_)
552 CreateProfileManager();
553 return profile_manager_.get();
556 PrefService* BrowserProcessImpl::local_state() {
557 DCHECK(CalledOnValidThread());
558 if (!created_local_state_)
559 CreateLocalState();
560 return local_state_.get();
563 net::URLRequestContextGetter* BrowserProcessImpl::system_request_context() {
564 DCHECK(CalledOnValidThread());
565 return io_thread()->system_url_request_context_getter();
568 chrome_variations::VariationsService* BrowserProcessImpl::variations_service() {
569 DCHECK(CalledOnValidThread());
570 return GetMetricsServicesManager()->GetVariationsService();
573 BrowserProcessPlatformPart* BrowserProcessImpl::platform_part() {
574 return platform_part_.get();
577 extensions::EventRouterForwarder*
578 BrowserProcessImpl::extension_event_router_forwarder() {
579 #if defined(ENABLE_EXTENSIONS)
580 return extension_event_router_forwarder_.get();
581 #else
582 return NULL;
583 #endif
586 NotificationUIManager* BrowserProcessImpl::notification_ui_manager() {
587 DCHECK(CalledOnValidThread());
588 if (!created_notification_ui_manager_)
589 CreateNotificationUIManager();
590 return notification_ui_manager_.get();
593 message_center::MessageCenter* BrowserProcessImpl::message_center() {
594 DCHECK(CalledOnValidThread());
595 return message_center::MessageCenter::Get();
598 policy::BrowserPolicyConnector* BrowserProcessImpl::browser_policy_connector() {
599 DCHECK(CalledOnValidThread());
600 #if defined(ENABLE_CONFIGURATION_POLICY)
601 if (!created_browser_policy_connector_) {
602 DCHECK(!browser_policy_connector_);
603 browser_policy_connector_ = platform_part_->CreateBrowserPolicyConnector();
604 created_browser_policy_connector_ = true;
606 return browser_policy_connector_.get();
607 #else
608 return NULL;
609 #endif
612 policy::PolicyService* BrowserProcessImpl::policy_service() {
613 #if defined(ENABLE_CONFIGURATION_POLICY)
614 return browser_policy_connector()->GetPolicyService();
615 #else
616 if (!policy_service_.get())
617 policy_service_.reset(new policy::PolicyServiceStub());
618 return policy_service_.get();
619 #endif
622 IconManager* BrowserProcessImpl::icon_manager() {
623 DCHECK(CalledOnValidThread());
624 if (!created_icon_manager_)
625 CreateIconManager();
626 return icon_manager_.get();
629 GLStringManager* BrowserProcessImpl::gl_string_manager() {
630 DCHECK(CalledOnValidThread());
631 if (!gl_string_manager_.get())
632 gl_string_manager_.reset(new GLStringManager());
633 return gl_string_manager_.get();
636 GpuModeManager* BrowserProcessImpl::gpu_mode_manager() {
637 DCHECK(CalledOnValidThread());
638 if (!gpu_mode_manager_.get())
639 gpu_mode_manager_.reset(new GpuModeManager());
640 return gpu_mode_manager_.get();
643 void BrowserProcessImpl::CreateDevToolsHttpProtocolHandler(
644 chrome::HostDesktopType host_desktop_type,
645 const std::string& ip,
646 uint16 port) {
647 DCHECK(CalledOnValidThread());
648 #if !defined(OS_ANDROID)
649 // StartupBrowserCreator::LaunchBrowser can be run multiple times when browser
650 // is started with several profiles or existing browser process is reused.
651 if (!remote_debugging_server_.get()) {
652 remote_debugging_server_.reset(
653 new RemoteDebuggingServer(host_desktop_type, ip, port));
655 #endif
658 bool BrowserProcessImpl::IsShuttingDown() {
659 DCHECK(CalledOnValidThread());
660 return did_start_ && 0 == module_ref_count_;
663 printing::PrintJobManager* BrowserProcessImpl::print_job_manager() {
664 DCHECK(CalledOnValidThread());
665 return print_job_manager_.get();
668 printing::PrintPreviewDialogController*
669 BrowserProcessImpl::print_preview_dialog_controller() {
670 #if defined(ENABLE_PRINT_PREVIEW)
671 DCHECK(CalledOnValidThread());
672 if (!print_preview_dialog_controller_.get())
673 CreatePrintPreviewDialogController();
674 return print_preview_dialog_controller_.get();
675 #else
676 NOTIMPLEMENTED();
677 return NULL;
678 #endif
681 printing::BackgroundPrintingManager*
682 BrowserProcessImpl::background_printing_manager() {
683 #if defined(ENABLE_PRINT_PREVIEW)
684 DCHECK(CalledOnValidThread());
685 if (!background_printing_manager_.get())
686 CreateBackgroundPrintingManager();
687 return background_printing_manager_.get();
688 #else
689 NOTIMPLEMENTED();
690 return NULL;
691 #endif
694 IntranetRedirectDetector* BrowserProcessImpl::intranet_redirect_detector() {
695 DCHECK(CalledOnValidThread());
696 if (!intranet_redirect_detector_.get())
697 CreateIntranetRedirectDetector();
698 return intranet_redirect_detector_.get();
701 const std::string& BrowserProcessImpl::GetApplicationLocale() {
702 DCHECK(!locale_.empty());
703 return locale_;
706 void BrowserProcessImpl::SetApplicationLocale(const std::string& locale) {
707 locale_ = locale;
708 #if defined(ENABLE_EXTENSIONS)
709 extension_l10n_util::SetProcessLocale(locale);
710 #endif
711 chrome::ChromeContentBrowserClient::SetApplicationLocale(locale);
712 translate::TranslateDownloadManager::GetInstance()->set_application_locale(
713 locale);
716 DownloadStatusUpdater* BrowserProcessImpl::download_status_updater() {
717 return download_status_updater_.get();
720 MediaFileSystemRegistry* BrowserProcessImpl::media_file_system_registry() {
721 #if defined(ENABLE_EXTENSIONS)
722 if (!media_file_system_registry_)
723 media_file_system_registry_.reset(new MediaFileSystemRegistry());
724 return media_file_system_registry_.get();
725 #else
726 return NULL;
727 #endif
730 bool BrowserProcessImpl::created_local_state() const {
731 return created_local_state_;
734 #if defined(ENABLE_WEBRTC)
735 WebRtcLogUploader* BrowserProcessImpl::webrtc_log_uploader() {
736 if (!webrtc_log_uploader_.get())
737 webrtc_log_uploader_.reset(new WebRtcLogUploader());
738 return webrtc_log_uploader_.get();
740 #endif
742 network_time::NetworkTimeTracker* BrowserProcessImpl::network_time_tracker() {
743 if (!network_time_tracker_) {
744 network_time_tracker_.reset(new network_time::NetworkTimeTracker(
745 scoped_ptr<base::TickClock>(new base::DefaultTickClock()),
746 local_state()));
748 return network_time_tracker_.get();
751 gcm::GCMDriver* BrowserProcessImpl::gcm_driver() {
752 DCHECK(CalledOnValidThread());
753 if (!gcm_driver_)
754 CreateGCMDriver();
755 return gcm_driver_.get();
758 // static
759 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple* registry) {
760 registry->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled,
761 false);
762 // This policy needs to be defined before the net subsystem is initialized,
763 // so we do it here.
764 registry->RegisterIntegerPref(prefs::kMaxConnectionsPerProxy,
765 net::kDefaultMaxSocketsPerProxyServer);
767 registry->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt, false);
769 #if defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
770 registry->RegisterBooleanPref(prefs::kEulaAccepted, false);
771 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
772 #if defined(OS_WIN)
773 if (base::win::GetVersion() >= base::win::VERSION_WIN7) {
774 registry->RegisterStringPref(prefs::kRelaunchMode,
775 upgrade_util::kRelaunchModeDefault);
777 #endif
779 // TODO(brettw,*): this comment about ResourceBundle was here since
780 // initial commit. This comment seems unrelated, bit-rotten and
781 // a candidate for removal.
782 // Initialize ResourceBundle which handles files loaded from external
783 // sources. This has to be done before uninstall code path and before prefs
784 // are registered.
785 registry->RegisterStringPref(prefs::kApplicationLocale, std::string());
786 #if defined(OS_CHROMEOS)
787 registry->RegisterStringPref(prefs::kOwnerLocale, std::string());
788 registry->RegisterStringPref(prefs::kHardwareKeyboardLayout,
789 std::string());
790 #endif // defined(OS_CHROMEOS)
791 #if !defined(OS_CHROMEOS)
792 registry->RegisterBooleanPref(
793 prefs::kMetricsReportingEnabled,
794 GoogleUpdateSettings::GetCollectStatsConsent());
795 #endif // !defined(OS_CHROMEOS)
797 #if defined(OS_ANDROID)
798 registry->RegisterBooleanPref(
799 prefs::kCrashReportingEnabled, false);
800 #endif // defined(OS_ANDROID)
803 DownloadRequestLimiter* BrowserProcessImpl::download_request_limiter() {
804 DCHECK(CalledOnValidThread());
805 if (!download_request_limiter_.get())
806 download_request_limiter_ = new DownloadRequestLimiter();
807 return download_request_limiter_.get();
810 BackgroundModeManager* BrowserProcessImpl::background_mode_manager() {
811 DCHECK(CalledOnValidThread());
812 #if defined(ENABLE_BACKGROUND)
813 if (!background_mode_manager_.get())
814 CreateBackgroundModeManager();
815 return background_mode_manager_.get();
816 #else
817 NOTIMPLEMENTED();
818 return NULL;
819 #endif
822 void BrowserProcessImpl::set_background_mode_manager_for_test(
823 scoped_ptr<BackgroundModeManager> manager) {
824 #if defined(ENABLE_BACKGROUND)
825 background_mode_manager_ = manager.Pass();
826 #endif
829 StatusTray* BrowserProcessImpl::status_tray() {
830 DCHECK(CalledOnValidThread());
831 if (!status_tray_.get())
832 CreateStatusTray();
833 return status_tray_.get();
837 SafeBrowsingService* BrowserProcessImpl::safe_browsing_service() {
838 DCHECK(CalledOnValidThread());
839 if (!created_safe_browsing_service_)
840 CreateSafeBrowsingService();
841 return safe_browsing_service_.get();
844 safe_browsing::ClientSideDetectionService*
845 BrowserProcessImpl::safe_browsing_detection_service() {
846 DCHECK(CalledOnValidThread());
847 if (safe_browsing_service())
848 return safe_browsing_service()->safe_browsing_detection_service();
849 return NULL;
852 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
853 void BrowserProcessImpl::StartAutoupdateTimer() {
854 autoupdate_timer_.Start(FROM_HERE,
855 base::TimeDelta::FromHours(kUpdateCheckIntervalHours),
856 this,
857 &BrowserProcessImpl::OnAutoupdateTimer);
859 #endif
861 ChromeNetLog* BrowserProcessImpl::net_log() {
862 return net_log_.get();
865 prerender::PrerenderTracker* BrowserProcessImpl::prerender_tracker() {
866 if (!prerender_tracker_.get())
867 prerender_tracker_.reset(new prerender::PrerenderTracker);
869 return prerender_tracker_.get();
872 component_updater::ComponentUpdateService*
873 BrowserProcessImpl::component_updater() {
874 if (!component_updater_.get()) {
875 if (!BrowserThread::CurrentlyOn(BrowserThread::UI))
876 return NULL;
877 update_client::Configurator* configurator =
878 component_updater::MakeChromeComponentUpdaterConfigurator(
879 base::CommandLine::ForCurrentProcess(),
880 io_thread()->system_url_request_context_getter());
881 // Creating the component updater does not do anything, components
882 // need to be registered and Start() needs to be called.
883 component_updater_.reset(
884 component_updater::ComponentUpdateServiceFactory(configurator));
886 return component_updater_.get();
889 CRLSetFetcher* BrowserProcessImpl::crl_set_fetcher() {
890 if (!crl_set_fetcher_)
891 crl_set_fetcher_ = new CRLSetFetcher();
892 return crl_set_fetcher_.get();
895 component_updater::PnaclComponentInstaller*
896 BrowserProcessImpl::pnacl_component_installer() {
897 #if !defined(DISABLE_NACL)
898 if (!pnacl_component_installer_) {
899 pnacl_component_installer_ =
900 new component_updater::PnaclComponentInstaller();
902 return pnacl_component_installer_.get();
903 #else
904 return nullptr;
905 #endif
908 component_updater::SupervisedUserWhitelistInstaller*
909 BrowserProcessImpl::supervised_user_whitelist_installer() {
910 if (!supervised_user_whitelist_installer_) {
911 supervised_user_whitelist_installer_ =
912 component_updater::SupervisedUserWhitelistInstaller::Create(
913 component_updater(), &profile_manager()->GetProfileInfoCache(),
914 local_state());
916 return supervised_user_whitelist_installer_.get();
919 void BrowserProcessImpl::ResourceDispatcherHostCreated() {
920 resource_dispatcher_host_delegate_.reset(
921 new ChromeResourceDispatcherHostDelegate(prerender_tracker()));
922 ResourceDispatcherHost::Get()->SetDelegate(
923 resource_dispatcher_host_delegate_.get());
925 pref_change_registrar_.Add(
926 prefs::kAllowCrossOriginAuthPrompt,
927 base::Bind(&BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy,
928 base::Unretained(this)));
929 ApplyAllowCrossOriginAuthPromptPolicy();
932 void BrowserProcessImpl::CreateWatchdogThread() {
933 DCHECK(!created_watchdog_thread_ && watchdog_thread_.get() == NULL);
934 created_watchdog_thread_ = true;
936 scoped_ptr<WatchDogThread> thread(new WatchDogThread());
937 base::Thread::Options options;
938 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
939 if (!thread->StartWithOptions(options))
940 return;
941 watchdog_thread_.swap(thread);
944 void BrowserProcessImpl::CreateProfileManager() {
945 DCHECK(!created_profile_manager_ && profile_manager_.get() == NULL);
946 created_profile_manager_ = true;
948 base::FilePath user_data_dir;
949 PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
950 profile_manager_.reset(new ProfileManager(user_data_dir));
953 void BrowserProcessImpl::CreateLocalState() {
954 DCHECK(!created_local_state_ && local_state_.get() == NULL);
955 created_local_state_ = true;
957 base::FilePath local_state_path;
958 CHECK(PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path));
959 scoped_refptr<PrefRegistrySimple> pref_registry = new PrefRegistrySimple;
961 // Register local state preferences.
962 chrome::RegisterLocalState(pref_registry.get());
964 local_state_ =
965 chrome_prefs::CreateLocalState(local_state_path,
966 local_state_task_runner_.get(),
967 policy_service(),
968 pref_registry,
969 false).Pass();
971 pref_change_registrar_.Init(local_state_.get());
973 // Initialize the notification for the default browser setting policy.
974 pref_change_registrar_.Add(
975 prefs::kDefaultBrowserSettingEnabled,
976 base::Bind(&BrowserProcessImpl::ApplyDefaultBrowserPolicy,
977 base::Unretained(this)));
979 // This preference must be kept in sync with external values; update them
980 // whenever the preference or its controlling policy changes.
981 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
982 pref_change_registrar_.Add(
983 prefs::kMetricsReportingEnabled,
984 base::Bind(&BrowserProcessImpl::ApplyMetricsReportingPolicy,
985 base::Unretained(this)));
986 #endif
988 int max_per_proxy = local_state_->GetInteger(prefs::kMaxConnectionsPerProxy);
989 net::ClientSocketPoolManager::set_max_sockets_per_proxy_server(
990 net::HttpNetworkSession::NORMAL_SOCKET_POOL,
991 std::max(std::min(max_per_proxy, 99),
992 net::ClientSocketPoolManager::max_sockets_per_group(
993 net::HttpNetworkSession::NORMAL_SOCKET_POOL)));
996 void BrowserProcessImpl::PreCreateThreads() {
997 io_thread_.reset(
998 new IOThread(local_state(), policy_service(), net_log_.get(),
999 extension_event_router_forwarder()));
1002 void BrowserProcessImpl::PreMainMessageLoopRun() {
1003 TRACE_EVENT0("startup", "BrowserProcessImpl::PreMainMessageLoopRun");
1004 SCOPED_UMA_HISTOGRAM_TIMER(
1005 "Startup.BrowserProcessImpl_PreMainMessageLoopRunTime");
1007 #if defined(ENABLE_CONFIGURATION_POLICY)
1008 // browser_policy_connector() is created very early because local_state()
1009 // needs policy to be initialized with the managed preference values.
1010 // However, policy fetches from the network and loading of disk caches
1011 // requires that threads are running; this Init() call lets the connector
1012 // resume its initialization now that the loops are spinning and the
1013 // system request context is available for the fetchers.
1014 browser_policy_connector()->Init(local_state(), system_request_context());
1015 #endif
1017 if (local_state_->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled))
1018 ApplyDefaultBrowserPolicy();
1020 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1021 ApplyMetricsReportingPolicy();
1022 #endif
1024 #if defined(ENABLE_PLUGINS)
1025 PluginService* plugin_service = PluginService::GetInstance();
1026 plugin_service->SetFilter(ChromePluginServiceFilter::GetInstance());
1027 plugin_service->StartWatchingPlugins();
1029 #if defined(OS_POSIX)
1030 // Also find plugins in a user-specific plugins dir,
1031 // e.g. ~/.config/chromium/Plugins.
1032 const base::CommandLine& cmd_line = *base::CommandLine::ForCurrentProcess();
1033 if (!cmd_line.HasSwitch(switches::kDisablePluginsDiscovery)) {
1034 base::FilePath user_data_dir;
1035 if (PathService::Get(chrome::DIR_USER_DATA, &user_data_dir))
1036 plugin_service->AddExtraPluginDir(user_data_dir.Append("Plugins"));
1038 #endif
1040 // Triggers initialization of the singleton instance on UI thread.
1041 PluginFinder::GetInstance()->Init();
1043 #if defined(ENABLE_PLUGIN_INSTALLATION)
1044 DCHECK(!plugins_resource_service_.get());
1045 plugins_resource_service_.reset(new PluginsResourceService(local_state()));
1046 plugins_resource_service_->Init();
1047 #endif
1048 #endif // defined(ENABLE_PLUGINS)
1050 const base::CommandLine& command_line =
1051 *base::CommandLine::ForCurrentProcess();
1052 if (!command_line.HasSwitch(switches::kDisableWebResources)) {
1053 DCHECK(!promo_resource_service_.get());
1054 promo_resource_service_.reset(new PromoResourceService);
1055 promo_resource_service_->StartAfterDelay();
1058 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1059 storage_monitor::StorageMonitor::Create();
1060 #endif
1062 platform_part_->PreMainMessageLoopRun();
1065 void BrowserProcessImpl::CreateIconManager() {
1066 DCHECK(!created_icon_manager_ && icon_manager_.get() == NULL);
1067 created_icon_manager_ = true;
1068 icon_manager_.reset(new IconManager);
1071 void BrowserProcessImpl::CreateIntranetRedirectDetector() {
1072 DCHECK(intranet_redirect_detector_.get() == NULL);
1073 scoped_ptr<IntranetRedirectDetector> intranet_redirect_detector(
1074 new IntranetRedirectDetector);
1075 intranet_redirect_detector_.swap(intranet_redirect_detector);
1078 void BrowserProcessImpl::CreateNotificationUIManager() {
1079 #if defined(ENABLE_NOTIFICATIONS)
1080 DCHECK(notification_ui_manager_.get() == NULL);
1081 notification_ui_manager_.reset(NotificationUIManager::Create(local_state()));
1082 created_notification_ui_manager_ = true;
1083 #endif
1086 void BrowserProcessImpl::CreateBackgroundModeManager() {
1087 #if defined(ENABLE_BACKGROUND)
1088 DCHECK(background_mode_manager_.get() == NULL);
1089 background_mode_manager_.reset(
1090 new BackgroundModeManager(*base::CommandLine::ForCurrentProcess(),
1091 &profile_manager()->GetProfileInfoCache()));
1092 #endif
1095 void BrowserProcessImpl::CreateStatusTray() {
1096 DCHECK(status_tray_.get() == NULL);
1097 status_tray_.reset(StatusTray::Create());
1100 void BrowserProcessImpl::CreatePrintPreviewDialogController() {
1101 #if defined(ENABLE_PRINT_PREVIEW)
1102 DCHECK(print_preview_dialog_controller_.get() == NULL);
1103 print_preview_dialog_controller_ =
1104 new printing::PrintPreviewDialogController();
1105 #else
1106 NOTIMPLEMENTED();
1107 #endif
1110 void BrowserProcessImpl::CreateBackgroundPrintingManager() {
1111 #if defined(ENABLE_PRINT_PREVIEW)
1112 DCHECK(background_printing_manager_.get() == NULL);
1113 background_printing_manager_.reset(new printing::BackgroundPrintingManager());
1114 #else
1115 NOTIMPLEMENTED();
1116 #endif
1119 void BrowserProcessImpl::CreateSafeBrowsingService() {
1120 DCHECK(safe_browsing_service_.get() == NULL);
1121 // Set this flag to true so that we don't retry indefinitely to
1122 // create the service class if there was an error.
1123 created_safe_browsing_service_ = true;
1124 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
1125 safe_browsing_service_ = SafeBrowsingService::CreateSafeBrowsingService();
1126 safe_browsing_service_->Initialize();
1127 #endif
1130 void BrowserProcessImpl::CreateGCMDriver() {
1131 DCHECK(!gcm_driver_);
1133 #if defined(OS_ANDROID)
1134 // Android's GCMDriver currently makes the assumption that it's a singleton.
1135 // Until this gets fixed, instantiating multiple Java GCMDrivers will throw
1136 // an exception, but because they're only initialized on demand these crashes
1137 // would be very difficult to triage. See http://crbug.com/437827.
1138 NOTREACHED();
1139 #else
1140 base::FilePath store_path;
1141 CHECK(PathService::Get(chrome::DIR_GLOBAL_GCM_STORE, &store_path));
1142 gcm_driver_ = gcm::CreateGCMDriverDesktop(
1143 make_scoped_ptr(new gcm::GCMClientFactory),
1144 local_state(),
1145 store_path,
1146 system_request_context());
1147 #endif // defined(OS_ANDROID)
1150 void BrowserProcessImpl::ApplyDefaultBrowserPolicy() {
1151 if (local_state()->GetBoolean(prefs::kDefaultBrowserSettingEnabled)) {
1152 scoped_refptr<ShellIntegration::DefaultWebClientWorker>
1153 set_browser_worker = new ShellIntegration::DefaultBrowserWorker(NULL);
1154 set_browser_worker->StartSetAsDefault();
1158 void BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy() {
1159 bool value = local_state()->GetBoolean(prefs::kAllowCrossOriginAuthPrompt);
1160 ResourceDispatcherHost::Get()->SetAllowCrossOriginAuthPrompt(value);
1163 void BrowserProcessImpl::ApplyMetricsReportingPolicy() {
1164 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1165 CHECK(BrowserThread::PostTask(
1166 BrowserThread::FILE, FROM_HERE,
1167 base::Bind(
1168 base::IgnoreResult(&GoogleUpdateSettings::SetCollectStatsConsent),
1169 local_state()->GetBoolean(prefs::kMetricsReportingEnabled))));
1170 #endif
1173 // Mac is currently not supported.
1174 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
1176 bool BrowserProcessImpl::CanAutorestartForUpdate() const {
1177 // Check if browser is in the background and if it needs to be restarted to
1178 // apply a pending update.
1179 return chrome::GetTotalBrowserCount() == 0 && chrome::WillKeepAlive() &&
1180 upgrade_util::IsUpdatePendingRestart();
1183 // Switches to add when auto-restarting Chrome.
1184 const char* const kSwitchesToAddOnAutorestart[] = {
1185 switches::kNoStartupWindow
1188 void BrowserProcessImpl::RestartBackgroundInstance() {
1189 base::CommandLine* old_cl = base::CommandLine::ForCurrentProcess();
1190 scoped_ptr<base::CommandLine> new_cl(
1191 new base::CommandLine(old_cl->GetProgram()));
1193 std::map<std::string, base::CommandLine::StringType> switches =
1194 old_cl->GetSwitches();
1196 switches::RemoveSwitchesForAutostart(&switches);
1198 // Append the rest of the switches (along with their values, if any)
1199 // to the new command line
1200 for (std::map<std::string, base::CommandLine::StringType>::const_iterator i =
1201 switches.begin();
1202 i != switches.end(); ++i) {
1203 base::CommandLine::StringType switch_value = i->second;
1204 if (switch_value.length() > 0) {
1205 new_cl->AppendSwitchNative(i->first, i->second);
1206 } else {
1207 new_cl->AppendSwitch(i->first);
1211 // Ensure that our desired switches are set on the new process.
1212 for (size_t i = 0; i < arraysize(kSwitchesToAddOnAutorestart); ++i) {
1213 if (!new_cl->HasSwitch(kSwitchesToAddOnAutorestart[i]))
1214 new_cl->AppendSwitch(kSwitchesToAddOnAutorestart[i]);
1217 DLOG(WARNING) << "Shutting down current instance of the browser.";
1218 chrome::AttemptExit();
1220 // Transfer ownership to Upgrade.
1221 upgrade_util::SetNewCommandLine(new_cl.release());
1224 void BrowserProcessImpl::OnAutoupdateTimer() {
1225 if (CanAutorestartForUpdate()) {
1226 DLOG(WARNING) << "Detected update. Restarting browser.";
1227 RestartBackgroundInstance();
1231 #endif // (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)