1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/browser_process_impl.h"
11 #include "base/atomic_ref_count.h"
12 #include "base/bind.h"
13 #include "base/bind_helpers.h"
14 #include "base/command_line.h"
15 #include "base/debug/alias.h"
16 #include "base/debug/leak_annotations.h"
17 #include "base/files/file_path.h"
18 #include "base/metrics/field_trial.h"
19 #include "base/path_service.h"
20 #include "base/prefs/json_pref_store.h"
21 #include "base/prefs/pref_registry_simple.h"
22 #include "base/prefs/pref_service.h"
23 #include "base/synchronization/waitable_event.h"
24 #include "base/threading/thread.h"
25 #include "base/threading/thread_restrictions.h"
26 #include "base/time/default_tick_clock.h"
27 #include "chrome/browser/chrome_browser_main.h"
28 #include "chrome/browser/chrome_content_browser_client.h"
29 #include "chrome/browser/chrome_notification_types.h"
30 #include "chrome/browser/component_updater/chrome_component_updater_configurator.h"
31 #include "chrome/browser/defaults.h"
32 #include "chrome/browser/devtools/remote_debugging_server.h"
33 #include "chrome/browser/download/download_request_limiter.h"
34 #include "chrome/browser/download/download_status_updater.h"
35 #include "chrome/browser/first_run/upgrade_util.h"
36 #include "chrome/browser/gpu/gl_string_manager.h"
37 #include "chrome/browser/gpu/gpu_mode_manager.h"
38 #include "chrome/browser/icon_manager.h"
39 #include "chrome/browser/intranet_redirect_detector.h"
40 #include "chrome/browser/io_thread.h"
41 #include "chrome/browser/lifetime/application_lifetime.h"
42 #include "chrome/browser/metrics/metrics_services_manager.h"
43 #include "chrome/browser/metrics/thread_watcher.h"
44 #include "chrome/browser/net/chrome_net_log.h"
45 #include "chrome/browser/net/crl_set_fetcher.h"
46 #include "chrome/browser/notifications/notification_ui_manager.h"
47 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
48 #include "chrome/browser/plugins/plugin_finder.h"
49 #include "chrome/browser/prefs/browser_prefs.h"
50 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
51 #include "chrome/browser/prerender/prerender_tracker.h"
52 #include "chrome/browser/printing/background_printing_manager.h"
53 #include "chrome/browser/printing/print_job_manager.h"
54 #include "chrome/browser/printing/print_preview_dialog_controller.h"
55 #include "chrome/browser/profiles/profile_manager.h"
56 #include "chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h"
57 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
58 #include "chrome/browser/shell_integration.h"
59 #include "chrome/browser/status_icons/status_tray.h"
60 #include "chrome/browser/ui/browser_dialogs.h"
61 #include "chrome/browser/ui/browser_finder.h"
62 #include "chrome/browser/ui/user_manager.h"
63 #include "chrome/browser/update_client/chrome_update_query_params_delegate.h"
64 #include "chrome/browser/web_resource/promo_resource_service.h"
65 #include "chrome/common/chrome_constants.h"
66 #include "chrome/common/chrome_paths.h"
67 #include "chrome/common/chrome_switches.h"
68 #include "chrome/common/extensions/chrome_extensions_client.h"
69 #include "chrome/common/pref_names.h"
70 #include "chrome/common/switch_utils.h"
71 #include "chrome/common/url_constants.h"
72 #include "chrome/installer/util/google_update_constants.h"
73 #include "chrome/installer/util/google_update_settings.h"
74 #include "components/component_updater/component_updater_service.h"
75 #include "components/gcm_driver/gcm_driver.h"
76 #include "components/metrics/metrics_service.h"
77 #include "components/network_time/network_time_tracker.h"
78 #include "components/policy/core/common/policy_service.h"
79 #include "components/signin/core/common/profile_management_switches.h"
80 #include "components/translate/core/browser/translate_download_manager.h"
81 #include "components/update_client/update_query_params.h"
82 #include "components/web_resource/web_resource_pref_names.h"
83 #include "content/public/browser/browser_thread.h"
84 #include "content/public/browser/child_process_security_policy.h"
85 #include "content/public/browser/notification_details.h"
86 #include "content/public/browser/plugin_service.h"
87 #include "content/public/browser/render_process_host.h"
88 #include "content/public/browser/resource_dispatcher_host.h"
89 #include "content/public/browser/service_worker_context.h"
90 #include "content/public/browser/storage_partition.h"
91 #include "extensions/common/constants.h"
92 #include "net/socket/client_socket_pool_manager.h"
93 #include "net/url_request/url_request_context_getter.h"
94 #include "ui/base/idle/idle.h"
95 #include "ui/base/l10n/l10n_util.h"
96 #include "ui/message_center/message_center.h"
99 #include "base/win/windows_version.h"
100 #include "ui/views/focus/view_storage.h"
101 #elif defined(OS_MACOSX)
102 #include "chrome/browser/chrome_browser_main_mac.h"
105 #if !defined(OS_ANDROID)
106 #include "chrome/browser/chrome_device_client.h"
107 #include "chrome/browser/services/gcm/gcm_desktop_utils.h"
108 #include "components/gcm_driver/gcm_client_factory.h"
111 #if defined(USE_AURA)
112 #include "ui/aura/env.h"
115 #if defined(ENABLE_BACKGROUND)
116 #include "chrome/browser/background/background_mode_manager.h"
119 #if defined(ENABLE_CONFIGURATION_POLICY)
120 #include "components/policy/core/browser/browser_policy_connector.h"
122 #include "components/policy/core/common/policy_service_stub.h"
123 #endif // defined(ENABLE_CONFIGURATION_POLICY)
125 #if defined(ENABLE_EXTENSIONS)
126 #include "chrome/browser/extensions/chrome_extensions_browser_client.h"
127 #include "chrome/browser/extensions/event_router_forwarder.h"
128 #include "chrome/browser/extensions/extension_renderer_state.h"
129 #include "chrome/browser/media_galleries/media_file_system_registry.h"
130 #include "chrome/browser/ui/apps/chrome_app_window_client.h"
131 #include "components/storage_monitor/storage_monitor.h"
132 #include "extensions/common/extension_l10n_util.h"
135 #if !defined(DISABLE_NACL)
136 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
139 #if defined(ENABLE_PLUGIN_INSTALLATION)
140 #include "chrome/browser/plugins/plugins_resource_service.h"
143 #if defined(ENABLE_WEBRTC)
144 #include "chrome/browser/media/webrtc_log_uploader.h"
147 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
148 // How often to check if the persistent instance of Chrome needs to restart
149 // to install an update.
150 static const int kUpdateCheckIntervalHours
= 6;
153 #if defined(USE_X11) || defined(OS_WIN)
154 // How long to wait for the File thread to complete during EndSession, on Linux
155 // and Windows. We have a timeout here because we're unable to run the UI
156 // messageloop and there's some deadlock risk. Our only option is to exit
158 static const int kEndSessionTimeoutSeconds
= 10;
161 using content::BrowserThread
;
162 using content::ChildProcessSecurityPolicy
;
163 using content::PluginService
;
164 using content::ResourceDispatcherHost
;
166 BrowserProcessImpl::BrowserProcessImpl(
167 base::SequencedTaskRunner
* local_state_task_runner
,
168 const base::CommandLine
& command_line
)
169 : created_watchdog_thread_(false),
170 created_browser_policy_connector_(false),
171 created_profile_manager_(false),
172 created_local_state_(false),
173 created_icon_manager_(false),
174 created_notification_ui_manager_(false),
175 created_safe_browsing_service_(false),
176 module_ref_count_(0),
178 download_status_updater_(new DownloadStatusUpdater
),
179 local_state_task_runner_(local_state_task_runner
) {
180 g_browser_process
= this;
181 platform_part_
.reset(new BrowserProcessPlatformPart());
183 #if defined(ENABLE_PRINTING)
184 // Must be created after the NotificationService.
185 print_job_manager_
.reset(new printing::PrintJobManager
);
188 net_log_
.reset(new ChromeNetLog
);
190 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
191 extensions::kExtensionScheme
);
192 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
193 extensions::kExtensionResourceScheme
);
194 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
195 chrome::kChromeSearchScheme
);
197 #if defined(OS_MACOSX)
198 ui::InitIdleMonitor();
201 #if !defined(OS_ANDROID)
202 device_client_
.reset(new ChromeDeviceClient
);
205 #if defined(ENABLE_EXTENSIONS)
206 // Athena sets its own instance during Athena's init process.
207 extensions::AppWindowClient::Set(ChromeAppWindowClient::GetInstance());
209 extension_event_router_forwarder_
= new extensions::EventRouterForwarder
;
210 ExtensionRendererState::GetInstance()->Init();
212 extensions::ExtensionsClient::Set(
213 extensions::ChromeExtensionsClient::GetInstance());
215 extensions_browser_client_
.reset(
216 new extensions::ChromeExtensionsBrowserClient
);
217 extensions::ExtensionsBrowserClient::Set(extensions_browser_client_
.get());
220 message_center::MessageCenter::Initialize();
222 update_client::UpdateQueryParams::SetDelegate(
223 ChromeUpdateQueryParamsDelegate::GetInstance());
226 BrowserProcessImpl::~BrowserProcessImpl() {
227 tracked_objects::ThreadData::EnsureCleanupWasCalled(4);
229 g_browser_process
= NULL
;
232 void BrowserProcessImpl::StartTearDown() {
233 TRACE_EVENT0("shutdown", "BrowserProcessImpl::StartTearDown");
234 // We need to destroy the MetricsServicesManager, IntranetRedirectDetector,
235 // PromoResourceService, and SafeBrowsing ClientSideDetectionService (owned by
236 // the SafeBrowsingService) before the io_thread_ gets destroyed, since their
237 // destructors can call the URLFetcher destructor, which does a
238 // PostDelayedTask operation on the IO thread. (The IO thread will handle that
239 // URLFetcher operation before going away.)
240 metrics_services_manager_
.reset();
241 intranet_redirect_detector_
.reset();
242 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
243 if (safe_browsing_service_
.get())
244 safe_browsing_service()->ShutDown();
247 // Need to clear the desktop notification balloons before the io_thread_ and
248 // before the profiles, since if there are any still showing we will access
249 // those things during teardown.
250 notification_ui_manager_
.reset();
252 // Need to clear profiles (download managers) before the io_thread_.
254 TRACE_EVENT0("shutdown",
255 "BrowserProcessImpl::StartTearDown:ProfileManager");
256 // The desktop User Manager needs to be closed before the guest profile
258 if (switches::IsNewAvatarMenu())
260 profile_manager_
.reset();
263 #if !defined(OS_ANDROID)
264 // Debugger must be cleaned up before IO thread and NotificationService.
265 remote_debugging_server_
.reset();
268 #if defined(ENABLE_EXTENSIONS)
269 ExtensionRendererState::GetInstance()->Shutdown();
271 media_file_system_registry_
.reset();
272 // Remove the global instance of the Storage Monitor now. Otherwise the
273 // FILE thread would be gone when we try to release it in the dtor and
274 // Valgrind would report a leak on almost every single browser_test.
275 // TODO(gbillock): Make this unnecessary.
276 storage_monitor::StorageMonitor::Destroy();
279 message_center::MessageCenter::Shutdown();
281 #if defined(ENABLE_CONFIGURATION_POLICY)
282 // The policy providers managed by |browser_policy_connector_| need to shut
283 // down while the IO and FILE threads are still alive.
284 if (browser_policy_connector_
)
285 browser_policy_connector_
->Shutdown();
288 // The |gcm_driver_| must shut down while the IO thread is still alive.
290 gcm_driver_
->Shutdown();
292 // Stop the watchdog thread before stopping other threads.
293 watchdog_thread_
.reset();
295 #if defined(USE_AURA)
296 // Delete aura after the metrics service has been deleted as it accesses
297 // monitor information.
298 aura::Env::DeleteInstance();
301 platform_part()->StartTearDown();
303 #if defined(ENABLE_WEBRTC)
304 // Cancel any uploads to release the system url request context references.
305 if (webrtc_log_uploader_
)
306 webrtc_log_uploader_
->StartShutdown();
310 local_state()->CommitPendingWrite();
313 void BrowserProcessImpl::PostDestroyThreads() {
314 // With the file_thread_ flushed, we can release any icon resources.
315 icon_manager_
.reset();
317 #if defined(ENABLE_WEBRTC)
318 // Must outlive the file thread.
319 webrtc_log_uploader_
.reset();
322 // Reset associated state right after actual thread is stopped,
323 // as io_thread_.global_ cleanup happens in CleanUp on the IO
324 // thread, i.e. as the thread exits its message loop.
326 // This is important also because in various places, the
327 // IOThread object being NULL is considered synonymous with the
328 // IO thread having stopped.
332 unsigned int BrowserProcessImpl::AddRefModule() {
333 DCHECK(CalledOnValidThread());
335 // CHECK(!IsShuttingDown());
336 if (IsShuttingDown()) {
337 // Copy the stacktrace which released the final reference onto our stack so
338 // it will be available in the crash report for inspection.
339 base::debug::StackTrace callstack
= release_last_reference_callstack_
;
340 base::debug::Alias(&callstack
);
346 return module_ref_count_
;
349 unsigned int BrowserProcessImpl::ReleaseModule() {
350 DCHECK(CalledOnValidThread());
351 DCHECK_NE(0u, module_ref_count_
);
353 if (0 == module_ref_count_
) {
354 release_last_reference_callstack_
= base::debug::StackTrace();
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();
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();
371 CHECK(base::MessageLoop::current()->is_running());
373 #if defined(OS_MACOSX)
374 base::MessageLoop::current()->PostTask(
376 base::Bind(ChromeBrowserMainPartsMac::DidEndMainMessageLoop
));
378 base::MessageLoop::current()->Quit();
380 return module_ref_count_
;
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
389 class RundownTaskCounter
:
390 public base::RefCountedThreadSafe
<RundownTaskCounter
> {
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
);
403 friend class base::RefCountedThreadSafe
<RundownTaskCounter
>;
404 ~RundownTaskCounter() {}
406 // Decrements the counter and releases the waitable event on transition to
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.
444 return waitable_event_
.TimedWait(max_time
);
449 void BrowserProcessImpl::EndSession() {
450 // Mark all the profiles as clean.
451 ProfileManager
* pm
= profile_manager();
452 std::vector
<Profile
*> profiles(pm
->GetLoadedProfiles());
453 scoped_refptr
<RundownTaskCounter
> rundown_counter(new RundownTaskCounter());
454 for (size_t i
= 0; i
< profiles
.size(); ++i
) {
455 Profile
* profile
= profiles
[i
];
456 profile
->SetExitType(Profile::EXIT_SESSION_ENDED
);
458 rundown_counter
->Post(profile
->GetIOTaskRunner().get());
461 // Tell the metrics service it was cleanly shutdown.
462 metrics::MetricsService
* metrics
= g_browser_process
->metrics_service();
463 if (metrics
&& local_state()) {
464 metrics
->RecordStartOfSessionEnd();
465 #if !defined(OS_CHROMEOS)
466 // MetricsService lazily writes to prefs, force it to write now.
467 // On ChromeOS, chrome gets killed when hangs, so no need to
468 // commit metrics::prefs::kStabilitySessionEndCompleted change immediately.
469 local_state()->CommitPendingWrite();
471 rundown_counter
->Post(local_state_task_runner_
.get());
475 // http://crbug.com/125207
476 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
478 // We must write that the profile and metrics service shutdown cleanly,
479 // otherwise on startup we'll think we crashed. So we block until done and
480 // then proceed with normal shutdown.
482 // If you change the condition here, be sure to also change
483 // ProfileBrowserTests to match.
484 #if defined(USE_X11) || defined(OS_WIN)
485 // Do a best-effort wait on the successful countdown of rundown tasks. Note
486 // that if we don't complete "quickly enough", Windows will terminate our
489 // On Windows, we previously posted a message to FILE and then ran a nested
490 // message loop, waiting for that message to be processed until quitting.
491 // However, doing so means that other messages will also be processed. In
492 // particular, if the GPU process host notices that the GPU has been killed
493 // during shutdown, it races exiting the nested loop with the process host
494 // blocking the message loop attempting to re-establish a connection to the
495 // GPU process synchronously. Because the system may not be allowing
496 // processes to launch, this can result in a hang. See
497 // http://crbug.com/318527.
498 rundown_counter
->TimedWait(
499 base::TimeDelta::FromSeconds(kEndSessionTimeoutSeconds
));
505 MetricsServicesManager
* BrowserProcessImpl::GetMetricsServicesManager() {
506 DCHECK(CalledOnValidThread());
507 if (!metrics_services_manager_
)
508 metrics_services_manager_
.reset(new MetricsServicesManager(local_state()));
509 return metrics_services_manager_
.get();
512 metrics::MetricsService
* BrowserProcessImpl::metrics_service() {
513 DCHECK(CalledOnValidThread());
514 return GetMetricsServicesManager()->GetMetricsService();
517 rappor::RapporService
* BrowserProcessImpl::rappor_service() {
518 DCHECK(CalledOnValidThread());
519 return GetMetricsServicesManager()->GetRapporService();
522 IOThread
* BrowserProcessImpl::io_thread() {
523 DCHECK(CalledOnValidThread());
524 DCHECK(io_thread_
.get());
525 return io_thread_
.get();
528 WatchDogThread
* BrowserProcessImpl::watchdog_thread() {
529 DCHECK(CalledOnValidThread());
530 if (!created_watchdog_thread_
)
531 CreateWatchdogThread();
532 DCHECK(watchdog_thread_
.get() != NULL
);
533 return watchdog_thread_
.get();
536 ProfileManager
* BrowserProcessImpl::profile_manager() {
537 DCHECK(CalledOnValidThread());
538 if (!created_profile_manager_
)
539 CreateProfileManager();
540 return profile_manager_
.get();
543 PrefService
* BrowserProcessImpl::local_state() {
544 DCHECK(CalledOnValidThread());
545 if (!created_local_state_
)
547 return local_state_
.get();
550 net::URLRequestContextGetter
* BrowserProcessImpl::system_request_context() {
551 DCHECK(CalledOnValidThread());
552 return io_thread()->system_url_request_context_getter();
555 chrome_variations::VariationsService
* BrowserProcessImpl::variations_service() {
556 DCHECK(CalledOnValidThread());
557 return GetMetricsServicesManager()->GetVariationsService();
560 BrowserProcessPlatformPart
* BrowserProcessImpl::platform_part() {
561 return platform_part_
.get();
564 extensions::EventRouterForwarder
*
565 BrowserProcessImpl::extension_event_router_forwarder() {
566 #if defined(ENABLE_EXTENSIONS)
567 return extension_event_router_forwarder_
.get();
573 NotificationUIManager
* BrowserProcessImpl::notification_ui_manager() {
574 DCHECK(CalledOnValidThread());
575 if (!created_notification_ui_manager_
)
576 CreateNotificationUIManager();
577 return notification_ui_manager_
.get();
580 message_center::MessageCenter
* BrowserProcessImpl::message_center() {
581 DCHECK(CalledOnValidThread());
582 return message_center::MessageCenter::Get();
585 policy::BrowserPolicyConnector
* BrowserProcessImpl::browser_policy_connector() {
586 DCHECK(CalledOnValidThread());
587 #if defined(ENABLE_CONFIGURATION_POLICY)
588 if (!created_browser_policy_connector_
) {
589 DCHECK(!browser_policy_connector_
);
590 browser_policy_connector_
= platform_part_
->CreateBrowserPolicyConnector();
591 created_browser_policy_connector_
= true;
593 return browser_policy_connector_
.get();
599 policy::PolicyService
* BrowserProcessImpl::policy_service() {
600 #if defined(ENABLE_CONFIGURATION_POLICY)
601 return browser_policy_connector()->GetPolicyService();
603 if (!policy_service_
.get())
604 policy_service_
.reset(new policy::PolicyServiceStub());
605 return policy_service_
.get();
609 IconManager
* BrowserProcessImpl::icon_manager() {
610 DCHECK(CalledOnValidThread());
611 if (!created_icon_manager_
)
613 return icon_manager_
.get();
616 GLStringManager
* BrowserProcessImpl::gl_string_manager() {
617 DCHECK(CalledOnValidThread());
618 if (!gl_string_manager_
.get())
619 gl_string_manager_
.reset(new GLStringManager());
620 return gl_string_manager_
.get();
623 GpuModeManager
* BrowserProcessImpl::gpu_mode_manager() {
624 DCHECK(CalledOnValidThread());
625 if (!gpu_mode_manager_
.get())
626 gpu_mode_manager_
.reset(new GpuModeManager());
627 return gpu_mode_manager_
.get();
630 void BrowserProcessImpl::CreateDevToolsHttpProtocolHandler(
631 chrome::HostDesktopType host_desktop_type
,
632 const std::string
& ip
,
634 DCHECK(CalledOnValidThread());
635 #if !defined(OS_ANDROID)
636 // StartupBrowserCreator::LaunchBrowser can be run multiple times when browser
637 // is started with several profiles or existing browser process is reused.
638 if (!remote_debugging_server_
.get()) {
639 remote_debugging_server_
.reset(
640 new RemoteDebuggingServer(host_desktop_type
, ip
, port
));
645 bool BrowserProcessImpl::IsShuttingDown() {
646 DCHECK(CalledOnValidThread());
647 return did_start_
&& 0 == module_ref_count_
;
650 printing::PrintJobManager
* BrowserProcessImpl::print_job_manager() {
651 DCHECK(CalledOnValidThread());
652 return print_job_manager_
.get();
655 printing::PrintPreviewDialogController
*
656 BrowserProcessImpl::print_preview_dialog_controller() {
657 #if defined(ENABLE_PRINT_PREVIEW)
658 DCHECK(CalledOnValidThread());
659 if (!print_preview_dialog_controller_
.get())
660 CreatePrintPreviewDialogController();
661 return print_preview_dialog_controller_
.get();
668 printing::BackgroundPrintingManager
*
669 BrowserProcessImpl::background_printing_manager() {
670 #if defined(ENABLE_PRINT_PREVIEW)
671 DCHECK(CalledOnValidThread());
672 if (!background_printing_manager_
.get())
673 CreateBackgroundPrintingManager();
674 return background_printing_manager_
.get();
681 IntranetRedirectDetector
* BrowserProcessImpl::intranet_redirect_detector() {
682 DCHECK(CalledOnValidThread());
683 if (!intranet_redirect_detector_
.get())
684 CreateIntranetRedirectDetector();
685 return intranet_redirect_detector_
.get();
688 const std::string
& BrowserProcessImpl::GetApplicationLocale() {
689 DCHECK(!locale_
.empty());
693 void BrowserProcessImpl::SetApplicationLocale(const std::string
& locale
) {
695 #if defined(ENABLE_EXTENSIONS)
696 extension_l10n_util::SetProcessLocale(locale
);
698 chrome::ChromeContentBrowserClient::SetApplicationLocale(locale
);
699 translate::TranslateDownloadManager::GetInstance()->set_application_locale(
703 DownloadStatusUpdater
* BrowserProcessImpl::download_status_updater() {
704 return download_status_updater_
.get();
707 MediaFileSystemRegistry
* BrowserProcessImpl::media_file_system_registry() {
708 #if defined(ENABLE_EXTENSIONS)
709 if (!media_file_system_registry_
)
710 media_file_system_registry_
.reset(new MediaFileSystemRegistry());
711 return media_file_system_registry_
.get();
717 bool BrowserProcessImpl::created_local_state() const {
718 return created_local_state_
;
721 #if defined(ENABLE_WEBRTC)
722 WebRtcLogUploader
* BrowserProcessImpl::webrtc_log_uploader() {
723 if (!webrtc_log_uploader_
.get())
724 webrtc_log_uploader_
.reset(new WebRtcLogUploader());
725 return webrtc_log_uploader_
.get();
729 network_time::NetworkTimeTracker
* BrowserProcessImpl::network_time_tracker() {
730 if (!network_time_tracker_
) {
731 network_time_tracker_
.reset(new network_time::NetworkTimeTracker(
732 scoped_ptr
<base::TickClock
>(new base::DefaultTickClock()),
735 return network_time_tracker_
.get();
738 gcm::GCMDriver
* BrowserProcessImpl::gcm_driver() {
739 DCHECK(CalledOnValidThread());
742 return gcm_driver_
.get();
746 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple
* registry
) {
747 registry
->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled
,
749 // This policy needs to be defined before the net subsystem is initialized,
751 registry
->RegisterIntegerPref(prefs::kMaxConnectionsPerProxy
,
752 net::kDefaultMaxSocketsPerProxyServer
);
754 registry
->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt
, false);
756 #if defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
757 registry
->RegisterBooleanPref(prefs::kEulaAccepted
, false);
758 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
760 if (base::win::GetVersion() >= base::win::VERSION_WIN7
) {
761 registry
->RegisterStringPref(prefs::kRelaunchMode
,
762 upgrade_util::kRelaunchModeDefault
);
766 // TODO(brettw,*): this comment about ResourceBundle was here since
767 // initial commit. This comment seems unrelated, bit-rotten and
768 // a candidate for removal.
769 // Initialize ResourceBundle which handles files loaded from external
770 // sources. This has to be done before uninstall code path and before prefs
772 registry
->RegisterStringPref(prefs::kApplicationLocale
, std::string());
773 #if defined(OS_CHROMEOS)
774 registry
->RegisterStringPref(prefs::kOwnerLocale
, std::string());
775 registry
->RegisterStringPref(prefs::kHardwareKeyboardLayout
,
777 #endif // defined(OS_CHROMEOS)
778 #if !defined(OS_CHROMEOS)
779 registry
->RegisterBooleanPref(
780 prefs::kMetricsReportingEnabled
,
781 GoogleUpdateSettings::GetCollectStatsConsent());
782 #endif // !defined(OS_CHROMEOS)
784 #if defined(OS_ANDROID)
785 registry
->RegisterBooleanPref(
786 prefs::kCrashReportingEnabled
, false);
787 #endif // defined(OS_ANDROID)
790 DownloadRequestLimiter
* BrowserProcessImpl::download_request_limiter() {
791 DCHECK(CalledOnValidThread());
792 if (!download_request_limiter_
.get())
793 download_request_limiter_
= new DownloadRequestLimiter();
794 return download_request_limiter_
.get();
797 BackgroundModeManager
* BrowserProcessImpl::background_mode_manager() {
798 DCHECK(CalledOnValidThread());
799 #if defined(ENABLE_BACKGROUND)
800 if (!background_mode_manager_
.get())
801 CreateBackgroundModeManager();
802 return background_mode_manager_
.get();
809 void BrowserProcessImpl::set_background_mode_manager_for_test(
810 scoped_ptr
<BackgroundModeManager
> manager
) {
811 #if defined(ENABLE_BACKGROUND)
812 background_mode_manager_
= manager
.Pass();
816 StatusTray
* BrowserProcessImpl::status_tray() {
817 DCHECK(CalledOnValidThread());
818 if (!status_tray_
.get())
820 return status_tray_
.get();
824 SafeBrowsingService
* BrowserProcessImpl::safe_browsing_service() {
825 DCHECK(CalledOnValidThread());
826 if (!created_safe_browsing_service_
)
827 CreateSafeBrowsingService();
828 return safe_browsing_service_
.get();
831 safe_browsing::ClientSideDetectionService
*
832 BrowserProcessImpl::safe_browsing_detection_service() {
833 DCHECK(CalledOnValidThread());
834 if (safe_browsing_service())
835 return safe_browsing_service()->safe_browsing_detection_service();
839 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
840 void BrowserProcessImpl::StartAutoupdateTimer() {
841 autoupdate_timer_
.Start(FROM_HERE
,
842 base::TimeDelta::FromHours(kUpdateCheckIntervalHours
),
844 &BrowserProcessImpl::OnAutoupdateTimer
);
848 ChromeNetLog
* BrowserProcessImpl::net_log() {
849 return net_log_
.get();
852 prerender::PrerenderTracker
* BrowserProcessImpl::prerender_tracker() {
853 if (!prerender_tracker_
.get())
854 prerender_tracker_
.reset(new prerender::PrerenderTracker
);
856 return prerender_tracker_
.get();
859 component_updater::ComponentUpdateService
*
860 BrowserProcessImpl::component_updater() {
861 if (!component_updater_
.get()) {
862 if (!BrowserThread::CurrentlyOn(BrowserThread::UI
))
864 component_updater::Configurator
* configurator
=
865 component_updater::MakeChromeComponentUpdaterConfigurator(
866 base::CommandLine::ForCurrentProcess(),
867 io_thread()->system_url_request_context_getter());
868 // Creating the component updater does not do anything, components
869 // need to be registered and Start() needs to be called.
870 component_updater_
.reset(ComponentUpdateServiceFactory(configurator
));
872 return component_updater_
.get();
875 CRLSetFetcher
* BrowserProcessImpl::crl_set_fetcher() {
876 if (!crl_set_fetcher_
.get())
877 crl_set_fetcher_
= new CRLSetFetcher();
878 return crl_set_fetcher_
.get();
881 component_updater::PnaclComponentInstaller
*
882 BrowserProcessImpl::pnacl_component_installer() {
883 #if !defined(DISABLE_NACL)
884 if (!pnacl_component_installer_
.get()) {
885 pnacl_component_installer_
.reset(
886 new component_updater::PnaclComponentInstaller());
888 return pnacl_component_installer_
.get();
894 void BrowserProcessImpl::ResourceDispatcherHostCreated() {
895 resource_dispatcher_host_delegate_
.reset(
896 new ChromeResourceDispatcherHostDelegate(prerender_tracker()));
897 ResourceDispatcherHost::Get()->SetDelegate(
898 resource_dispatcher_host_delegate_
.get());
900 pref_change_registrar_
.Add(
901 prefs::kAllowCrossOriginAuthPrompt
,
902 base::Bind(&BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy
,
903 base::Unretained(this)));
904 ApplyAllowCrossOriginAuthPromptPolicy();
907 void BrowserProcessImpl::CreateWatchdogThread() {
908 DCHECK(!created_watchdog_thread_
&& watchdog_thread_
.get() == NULL
);
909 created_watchdog_thread_
= true;
911 scoped_ptr
<WatchDogThread
> thread(new WatchDogThread());
912 base::Thread::Options options
;
913 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
914 if (!thread
->StartWithOptions(options
))
916 watchdog_thread_
.swap(thread
);
919 void BrowserProcessImpl::CreateProfileManager() {
920 DCHECK(!created_profile_manager_
&& profile_manager_
.get() == NULL
);
921 created_profile_manager_
= true;
923 base::FilePath user_data_dir
;
924 PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
);
925 profile_manager_
.reset(new ProfileManager(user_data_dir
));
928 void BrowserProcessImpl::CreateLocalState() {
929 DCHECK(!created_local_state_
&& local_state_
.get() == NULL
);
930 created_local_state_
= true;
932 base::FilePath local_state_path
;
933 CHECK(PathService::Get(chrome::FILE_LOCAL_STATE
, &local_state_path
));
934 scoped_refptr
<PrefRegistrySimple
> pref_registry
= new PrefRegistrySimple
;
936 // Register local state preferences.
937 chrome::RegisterLocalState(pref_registry
.get());
940 chrome_prefs::CreateLocalState(local_state_path
,
941 local_state_task_runner_
.get(),
946 pref_change_registrar_
.Init(local_state_
.get());
948 // Initialize the notification for the default browser setting policy.
949 pref_change_registrar_
.Add(
950 prefs::kDefaultBrowserSettingEnabled
,
951 base::Bind(&BrowserProcessImpl::ApplyDefaultBrowserPolicy
,
952 base::Unretained(this)));
954 // This preference must be kept in sync with external values; update them
955 // whenever the preference or its controlling policy changes.
956 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
957 pref_change_registrar_
.Add(
958 prefs::kMetricsReportingEnabled
,
959 base::Bind(&BrowserProcessImpl::ApplyMetricsReportingPolicy
,
960 base::Unretained(this)));
963 int max_per_proxy
= local_state_
->GetInteger(prefs::kMaxConnectionsPerProxy
);
964 net::ClientSocketPoolManager::set_max_sockets_per_proxy_server(
965 net::HttpNetworkSession::NORMAL_SOCKET_POOL
,
966 std::max(std::min(max_per_proxy
, 99),
967 net::ClientSocketPoolManager::max_sockets_per_group(
968 net::HttpNetworkSession::NORMAL_SOCKET_POOL
)));
971 void BrowserProcessImpl::PreCreateThreads() {
973 new IOThread(local_state(), policy_service(), net_log_
.get(),
974 extension_event_router_forwarder()));
977 void BrowserProcessImpl::PreMainMessageLoopRun() {
978 #if defined(ENABLE_CONFIGURATION_POLICY)
979 // browser_policy_connector() is created very early because local_state()
980 // needs policy to be initialized with the managed preference values.
981 // However, policy fetches from the network and loading of disk caches
982 // requires that threads are running; this Init() call lets the connector
983 // resume its initialization now that the loops are spinning and the
984 // system request context is available for the fetchers.
985 browser_policy_connector()->Init(local_state(), system_request_context());
988 if (local_state_
->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled
))
989 ApplyDefaultBrowserPolicy();
991 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
992 ApplyMetricsReportingPolicy();
995 #if defined(ENABLE_PLUGINS)
996 PluginService
* plugin_service
= PluginService::GetInstance();
997 plugin_service
->SetFilter(ChromePluginServiceFilter::GetInstance());
998 plugin_service
->StartWatchingPlugins();
1000 #if defined(OS_POSIX)
1001 // Also find plugins in a user-specific plugins dir,
1002 // e.g. ~/.config/chromium/Plugins.
1003 const base::CommandLine
& cmd_line
= *base::CommandLine::ForCurrentProcess();
1004 if (!cmd_line
.HasSwitch(switches::kDisablePluginsDiscovery
)) {
1005 base::FilePath user_data_dir
;
1006 if (PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
))
1007 plugin_service
->AddExtraPluginDir(user_data_dir
.Append("Plugins"));
1011 // Triggers initialization of the singleton instance on UI thread.
1012 PluginFinder::GetInstance()->Init();
1014 #if defined(ENABLE_PLUGIN_INSTALLATION)
1015 DCHECK(!plugins_resource_service_
.get());
1016 plugins_resource_service_
= new PluginsResourceService(local_state());
1017 plugins_resource_service_
->Init();
1019 #endif // defined(ENABLE_PLUGINS)
1021 const base::CommandLine
& command_line
=
1022 *base::CommandLine::ForCurrentProcess();
1023 if (!command_line
.HasSwitch(switches::kDisableWebResources
)) {
1024 DCHECK(!promo_resource_service_
.get());
1025 promo_resource_service_
= new PromoResourceService
;
1026 promo_resource_service_
->StartAfterDelay();
1029 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1030 storage_monitor::StorageMonitor::Create();
1033 platform_part_
->PreMainMessageLoopRun();
1036 void BrowserProcessImpl::CreateIconManager() {
1037 DCHECK(!created_icon_manager_
&& icon_manager_
.get() == NULL
);
1038 created_icon_manager_
= true;
1039 icon_manager_
.reset(new IconManager
);
1042 void BrowserProcessImpl::CreateIntranetRedirectDetector() {
1043 DCHECK(intranet_redirect_detector_
.get() == NULL
);
1044 scoped_ptr
<IntranetRedirectDetector
> intranet_redirect_detector(
1045 new IntranetRedirectDetector
);
1046 intranet_redirect_detector_
.swap(intranet_redirect_detector
);
1049 void BrowserProcessImpl::CreateNotificationUIManager() {
1050 #if defined(ENABLE_NOTIFICATIONS)
1051 DCHECK(notification_ui_manager_
.get() == NULL
);
1052 notification_ui_manager_
.reset(NotificationUIManager::Create(local_state()));
1053 created_notification_ui_manager_
= true;
1057 void BrowserProcessImpl::CreateBackgroundModeManager() {
1058 #if defined(ENABLE_BACKGROUND)
1059 DCHECK(background_mode_manager_
.get() == NULL
);
1060 background_mode_manager_
.reset(
1061 new BackgroundModeManager(*base::CommandLine::ForCurrentProcess(),
1062 &profile_manager()->GetProfileInfoCache()));
1066 void BrowserProcessImpl::CreateStatusTray() {
1067 DCHECK(status_tray_
.get() == NULL
);
1068 status_tray_
.reset(StatusTray::Create());
1071 void BrowserProcessImpl::CreatePrintPreviewDialogController() {
1072 #if defined(ENABLE_PRINT_PREVIEW)
1073 DCHECK(print_preview_dialog_controller_
.get() == NULL
);
1074 print_preview_dialog_controller_
=
1075 new printing::PrintPreviewDialogController();
1081 void BrowserProcessImpl::CreateBackgroundPrintingManager() {
1082 #if defined(ENABLE_PRINT_PREVIEW)
1083 DCHECK(background_printing_manager_
.get() == NULL
);
1084 background_printing_manager_
.reset(new printing::BackgroundPrintingManager());
1090 void BrowserProcessImpl::CreateSafeBrowsingService() {
1091 DCHECK(safe_browsing_service_
.get() == NULL
);
1092 // Set this flag to true so that we don't retry indefinitely to
1093 // create the service class if there was an error.
1094 created_safe_browsing_service_
= true;
1095 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
1096 safe_browsing_service_
= SafeBrowsingService::CreateSafeBrowsingService();
1097 safe_browsing_service_
->Initialize();
1101 void BrowserProcessImpl::CreateGCMDriver() {
1102 DCHECK(!gcm_driver_
);
1104 #if defined(OS_ANDROID)
1105 // Android's GCMDriver currently makes the assumption that it's a singleton.
1106 // Until this gets fixed, instantiating multiple Java GCMDrivers will throw
1107 // an exception, but because they're only initialized on demand these crashes
1108 // would be very difficult to triage. See http://crbug.com/437827.
1111 base::FilePath store_path
;
1112 CHECK(PathService::Get(chrome::DIR_GLOBAL_GCM_STORE
, &store_path
));
1113 gcm_driver_
= gcm::CreateGCMDriverDesktop(
1114 make_scoped_ptr(new gcm::GCMClientFactory
),
1117 system_request_context());
1118 #endif // defined(OS_ANDROID)
1121 void BrowserProcessImpl::ApplyDefaultBrowserPolicy() {
1122 if (local_state()->GetBoolean(prefs::kDefaultBrowserSettingEnabled
)) {
1123 scoped_refptr
<ShellIntegration::DefaultWebClientWorker
>
1124 set_browser_worker
= new ShellIntegration::DefaultBrowserWorker(NULL
);
1125 set_browser_worker
->StartSetAsDefault();
1129 void BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy() {
1130 bool value
= local_state()->GetBoolean(prefs::kAllowCrossOriginAuthPrompt
);
1131 ResourceDispatcherHost::Get()->SetAllowCrossOriginAuthPrompt(value
);
1134 void BrowserProcessImpl::ApplyMetricsReportingPolicy() {
1135 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1136 CHECK(BrowserThread::PostTask(
1137 BrowserThread::FILE, FROM_HERE
,
1139 base::IgnoreResult(&GoogleUpdateSettings::SetCollectStatsConsent
),
1140 local_state()->GetBoolean(prefs::kMetricsReportingEnabled
))));
1144 // Mac is currently not supported.
1145 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
1147 bool BrowserProcessImpl::CanAutorestartForUpdate() const {
1148 // Check if browser is in the background and if it needs to be restarted to
1149 // apply a pending update.
1150 return chrome::GetTotalBrowserCount() == 0 && chrome::WillKeepAlive() &&
1151 upgrade_util::IsUpdatePendingRestart();
1154 // Switches to add when auto-restarting Chrome.
1155 const char* const kSwitchesToAddOnAutorestart
[] = {
1156 switches::kNoStartupWindow
1159 void BrowserProcessImpl::RestartBackgroundInstance() {
1160 base::CommandLine
* old_cl
= base::CommandLine::ForCurrentProcess();
1161 scoped_ptr
<base::CommandLine
> new_cl(
1162 new base::CommandLine(old_cl
->GetProgram()));
1164 std::map
<std::string
, base::CommandLine::StringType
> switches
=
1165 old_cl
->GetSwitches();
1167 switches::RemoveSwitchesForAutostart(&switches
);
1169 // Append the rest of the switches (along with their values, if any)
1170 // to the new command line
1171 for (std::map
<std::string
, base::CommandLine::StringType
>::const_iterator i
=
1173 i
!= switches
.end(); ++i
) {
1174 base::CommandLine::StringType switch_value
= i
->second
;
1175 if (switch_value
.length() > 0) {
1176 new_cl
->AppendSwitchNative(i
->first
, i
->second
);
1178 new_cl
->AppendSwitch(i
->first
);
1182 // Ensure that our desired switches are set on the new process.
1183 for (size_t i
= 0; i
< arraysize(kSwitchesToAddOnAutorestart
); ++i
) {
1184 if (!new_cl
->HasSwitch(kSwitchesToAddOnAutorestart
[i
]))
1185 new_cl
->AppendSwitch(kSwitchesToAddOnAutorestart
[i
]);
1188 DLOG(WARNING
) << "Shutting down current instance of the browser.";
1189 chrome::AttemptExit();
1191 // Transfer ownership to Upgrade.
1192 upgrade_util::SetNewCommandLine(new_cl
.release());
1195 void BrowserProcessImpl::OnAutoupdateTimer() {
1196 if (CanAutorestartForUpdate()) {
1197 DLOG(WARNING
) << "Detected update. Restarting browser.";
1198 RestartBackgroundInstance();
1202 #endif // (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)