1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/browser_process_impl.h"
11 #include "base/atomic_ref_count.h"
12 #include "base/bind.h"
13 #include "base/bind_helpers.h"
14 #include "base/command_line.h"
15 #include "base/debug/alias.h"
16 #include "base/debug/leak_annotations.h"
17 #include "base/files/file_path.h"
18 #include "base/metrics/field_trial.h"
19 #include "base/path_service.h"
20 #include "base/prefs/json_pref_store.h"
21 #include "base/prefs/pref_registry_simple.h"
22 #include "base/prefs/pref_service.h"
23 #include "base/synchronization/waitable_event.h"
24 #include "base/threading/thread.h"
25 #include "base/threading/thread_restrictions.h"
26 #include "base/time/default_tick_clock.h"
27 #include "chrome/browser/chrome_browser_main.h"
28 #include "chrome/browser/chrome_content_browser_client.h"
29 #include "chrome/browser/chrome_notification_types.h"
30 #include "chrome/browser/component_updater/chrome_component_updater_configurator.h"
31 #include "chrome/browser/defaults.h"
32 #include "chrome/browser/devtools/remote_debugging_server.h"
33 #include "chrome/browser/download/download_request_limiter.h"
34 #include "chrome/browser/download/download_status_updater.h"
35 #include "chrome/browser/first_run/upgrade_util.h"
36 #include "chrome/browser/gpu/gl_string_manager.h"
37 #include "chrome/browser/gpu/gpu_mode_manager.h"
38 #include "chrome/browser/icon_manager.h"
39 #include "chrome/browser/idle.h"
40 #include "chrome/browser/intranet_redirect_detector.h"
41 #include "chrome/browser/io_thread.h"
42 #include "chrome/browser/lifetime/application_lifetime.h"
43 #include "chrome/browser/metrics/metrics_services_manager.h"
44 #include "chrome/browser/metrics/thread_watcher.h"
45 #include "chrome/browser/net/chrome_net_log.h"
46 #include "chrome/browser/net/crl_set_fetcher.h"
47 #include "chrome/browser/notifications/notification_ui_manager.h"
48 #include "chrome/browser/omaha_client/chrome_omaha_query_params_delegate.h"
49 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
50 #include "chrome/browser/plugins/plugin_finder.h"
51 #include "chrome/browser/prefs/browser_prefs.h"
52 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
53 #include "chrome/browser/prerender/prerender_tracker.h"
54 #include "chrome/browser/printing/background_printing_manager.h"
55 #include "chrome/browser/printing/print_job_manager.h"
56 #include "chrome/browser/printing/print_preview_dialog_controller.h"
57 #include "chrome/browser/profiles/profile_manager.h"
58 #include "chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h"
59 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
60 #include "chrome/browser/shell_integration.h"
61 #include "chrome/browser/status_icons/status_tray.h"
62 #include "chrome/browser/ui/browser_dialogs.h"
63 #include "chrome/browser/ui/browser_finder.h"
64 #include "chrome/browser/ui/user_manager.h"
65 #include "chrome/browser/web_resource/promo_resource_service.h"
66 #include "chrome/common/chrome_constants.h"
67 #include "chrome/common/chrome_paths.h"
68 #include "chrome/common/chrome_switches.h"
69 #include "chrome/common/extensions/chrome_extensions_client.h"
70 #include "chrome/common/pref_names.h"
71 #include "chrome/common/switch_utils.h"
72 #include "chrome/common/url_constants.h"
73 #include "chrome/installer/util/google_update_constants.h"
74 #include "chrome/installer/util/google_update_settings.h"
75 #include "components/component_updater/component_updater_service.h"
76 #include "components/gcm_driver/gcm_driver.h"
77 #include "components/metrics/metrics_service.h"
78 #include "components/network_time/network_time_tracker.h"
79 #include "components/omaha_client/omaha_query_params.h"
80 #include "components/policy/core/common/policy_service.h"
81 #include "components/signin/core/common/profile_management_switches.h"
82 #include "components/translate/core/browser/translate_download_manager.h"
83 #include "components/web_resource/web_resource_pref_names.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 "net/socket/client_socket_pool_manager.h"
94 #include "net/url_request/url_request_context_getter.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 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)
201 #if !defined(OS_ANDROID)
202 device_client_
.reset(new ChromeDeviceClient
);
205 #if defined(ENABLE_EXTENSIONS)
206 #if !defined(USE_ATHENA)
207 // Athena sets its own instance during Athena's init process.
208 extensions::AppWindowClient::Set(ChromeAppWindowClient::GetInstance());
211 extension_event_router_forwarder_
= new extensions::EventRouterForwarder
;
212 ExtensionRendererState::GetInstance()->Init();
214 extensions::ExtensionsClient::Set(
215 extensions::ChromeExtensionsClient::GetInstance());
217 extensions_browser_client_
.reset(
218 new extensions::ChromeExtensionsBrowserClient
);
219 extensions::ExtensionsBrowserClient::Set(extensions_browser_client_
.get());
222 message_center::MessageCenter::Initialize();
224 omaha_client::OmahaQueryParams::SetDelegate(
225 ChromeOmahaQueryParamsDelegate::GetInstance());
228 BrowserProcessImpl::~BrowserProcessImpl() {
229 tracked_objects::ThreadData::EnsureCleanupWasCalled(4);
231 g_browser_process
= NULL
;
234 void BrowserProcessImpl::StartTearDown() {
235 TRACE_EVENT0("shutdown", "BrowserProcessImpl::StartTearDown");
236 // We need to destroy the MetricsServicesManager, IntranetRedirectDetector,
237 // PromoResourceService, and SafeBrowsing ClientSideDetectionService (owned by
238 // the SafeBrowsingService) before the io_thread_ gets destroyed, since their
239 // destructors can call the URLFetcher destructor, which does a
240 // PostDelayedTask operation on the IO thread. (The IO thread will handle that
241 // URLFetcher operation before going away.)
242 metrics_services_manager_
.reset();
243 intranet_redirect_detector_
.reset();
244 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
245 if (safe_browsing_service_
.get())
246 safe_browsing_service()->ShutDown();
249 // Need to clear the desktop notification balloons before the io_thread_ and
250 // before the profiles, since if there are any still showing we will access
251 // those things during teardown.
252 notification_ui_manager_
.reset();
254 // Need to clear profiles (download managers) before the io_thread_.
256 TRACE_EVENT0("shutdown",
257 "BrowserProcessImpl::StartTearDown:ProfileManager");
258 // The desktop User Manager needs to be closed before the guest profile
260 if (switches::IsNewAvatarMenu())
262 profile_manager_
.reset();
265 #if !defined(OS_ANDROID)
266 // Debugger must be cleaned up before IO thread and NotificationService.
267 remote_debugging_server_
.reset();
270 #if defined(ENABLE_EXTENSIONS)
271 ExtensionRendererState::GetInstance()->Shutdown();
273 media_file_system_registry_
.reset();
274 // Remove the global instance of the Storage Monitor now. Otherwise the
275 // FILE thread would be gone when we try to release it in the dtor and
276 // Valgrind would report a leak on almost every single browser_test.
277 // TODO(gbillock): Make this unnecessary.
278 storage_monitor::StorageMonitor::Destroy();
281 message_center::MessageCenter::Shutdown();
283 #if defined(ENABLE_CONFIGURATION_POLICY)
284 // The policy providers managed by |browser_policy_connector_| need to shut
285 // down while the IO and FILE threads are still alive.
286 if (browser_policy_connector_
)
287 browser_policy_connector_
->Shutdown();
290 // The |gcm_driver_| must shut down while the IO thread is still alive.
292 gcm_driver_
->Shutdown();
294 // Stop the watchdog thread before stopping other threads.
295 watchdog_thread_
.reset();
297 #if defined(USE_AURA)
298 // Delete aura after the metrics service has been deleted as it accesses
299 // monitor information.
300 aura::Env::DeleteInstance();
303 platform_part()->StartTearDown();
305 #if defined(ENABLE_WEBRTC)
306 // Cancel any uploads to release the system url request context references.
307 if (webrtc_log_uploader_
)
308 webrtc_log_uploader_
->StartShutdown();
312 local_state()->CommitPendingWrite();
315 void BrowserProcessImpl::PostDestroyThreads() {
316 // With the file_thread_ flushed, we can release any icon resources.
317 icon_manager_
.reset();
319 #if defined(ENABLE_WEBRTC)
320 // Must outlive the file thread.
321 webrtc_log_uploader_
.reset();
324 // Reset associated state right after actual thread is stopped,
325 // as io_thread_.global_ cleanup happens in CleanUp on the IO
326 // thread, i.e. as the thread exits its message loop.
328 // This is important also because in various places, the
329 // IOThread object being NULL is considered synonymous with the
330 // IO thread having stopped.
334 unsigned int BrowserProcessImpl::AddRefModule() {
335 DCHECK(CalledOnValidThread());
337 // CHECK(!IsShuttingDown());
338 if (IsShuttingDown()) {
339 // Copy the stacktrace which released the final reference onto our stack so
340 // it will be available in the crash report for inspection.
341 base::debug::StackTrace callstack
= release_last_reference_callstack_
;
342 base::debug::Alias(&callstack
);
348 return module_ref_count_
;
351 unsigned int BrowserProcessImpl::ReleaseModule() {
352 DCHECK(CalledOnValidThread());
353 DCHECK_NE(0u, module_ref_count_
);
355 if (0 == module_ref_count_
) {
356 release_last_reference_callstack_
= base::debug::StackTrace();
358 #if defined(ENABLE_PRINTING)
359 // Wait for the pending print jobs to finish. Don't do this later, since
360 // this might cause a nested message loop to run, and we don't want pending
361 // tasks to run once teardown has started.
362 print_job_manager_
->Shutdown();
365 #if defined(LEAK_SANITIZER)
366 // Check for memory leaks now, before we start shutting down threads. Doing
367 // this early means we won't report any shutdown-only leaks (as they have
368 // not yet happened at this point).
369 // If leaks are found, this will make the process exit immediately.
370 __lsan_do_leak_check();
373 CHECK(base::MessageLoop::current()->is_running());
375 #if defined(OS_MACOSX)
376 base::MessageLoop::current()->PostTask(
378 base::Bind(ChromeBrowserMainPartsMac::DidEndMainMessageLoop
));
380 base::MessageLoop::current()->Quit();
382 return module_ref_count_
;
387 // Used at the end of session to block the UI thread for completion of sentinel
388 // tasks on the set of threads used to persist profile data and local state.
389 // This is done to ensure that the data has been persisted to disk before
391 class RundownTaskCounter
:
392 public base::RefCountedThreadSafe
<RundownTaskCounter
> {
394 RundownTaskCounter();
396 // Posts a rundown task to |task_runner|, can be invoked an arbitrary number
397 // of times before calling TimedWait.
398 void Post(base::SequencedTaskRunner
* task_runner
);
400 // Waits until the count is zero or |max_time| has passed.
401 // This can only be called once per instance.
402 bool TimedWait(const base::TimeDelta
& max_time
);
405 friend class base::RefCountedThreadSafe
<RundownTaskCounter
>;
406 ~RundownTaskCounter() {}
408 // Decrements the counter and releases the waitable event on transition to
412 // The count starts at one to defer the possibility of one->zero transitions
413 // until TimedWait is called.
414 base::AtomicRefCount count_
;
415 base::WaitableEvent waitable_event_
;
417 DISALLOW_COPY_AND_ASSIGN(RundownTaskCounter
);
420 RundownTaskCounter::RundownTaskCounter()
421 : count_(1), waitable_event_(true, false) {
424 void RundownTaskCounter::Post(base::SequencedTaskRunner
* task_runner
) {
425 // As the count starts off at one, it should never get to zero unless
426 // TimedWait has been called.
427 DCHECK(!base::AtomicRefCountIsZero(&count_
));
429 base::AtomicRefCountInc(&count_
);
431 // The task must be non-nestable to guarantee that it runs after all tasks
432 // currently scheduled on |task_runner| have completed.
433 task_runner
->PostNonNestableTask(FROM_HERE
,
434 base::Bind(&RundownTaskCounter::Decrement
, this));
437 void RundownTaskCounter::Decrement() {
438 if (!base::AtomicRefCountDec(&count_
))
439 waitable_event_
.Signal();
442 bool RundownTaskCounter::TimedWait(const base::TimeDelta
& max_time
) {
443 // Decrement the excess count from the constructor.
446 return waitable_event_
.TimedWait(max_time
);
451 void BrowserProcessImpl::EndSession() {
452 // Mark all the profiles as clean.
453 ProfileManager
* pm
= profile_manager();
454 std::vector
<Profile
*> profiles(pm
->GetLoadedProfiles());
455 scoped_refptr
<RundownTaskCounter
> rundown_counter(new RundownTaskCounter());
456 for (size_t i
= 0; i
< profiles
.size(); ++i
) {
457 Profile
* profile
= profiles
[i
];
458 profile
->SetExitType(Profile::EXIT_SESSION_ENDED
);
460 rundown_counter
->Post(profile
->GetIOTaskRunner().get());
463 // Tell the metrics service it was cleanly shutdown.
464 metrics::MetricsService
* metrics
= g_browser_process
->metrics_service();
465 if (metrics
&& local_state()) {
466 metrics
->RecordStartOfSessionEnd();
467 #if !defined(OS_CHROMEOS)
468 // MetricsService lazily writes to prefs, force it to write now.
469 // On ChromeOS, chrome gets killed when hangs, so no need to
470 // commit metrics::prefs::kStabilitySessionEndCompleted change immediately.
471 local_state()->CommitPendingWrite();
473 rundown_counter
->Post(local_state_task_runner_
.get());
477 // http://crbug.com/125207
478 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
480 // We must write that the profile and metrics service shutdown cleanly,
481 // otherwise on startup we'll think we crashed. So we block until done and
482 // then proceed with normal shutdown.
484 // If you change the condition here, be sure to also change
485 // ProfileBrowserTests to match.
486 #if defined(USE_X11) || defined(OS_WIN)
487 // Do a best-effort wait on the successful countdown of rundown tasks. Note
488 // that if we don't complete "quickly enough", Windows will terminate our
491 // On Windows, we previously posted a message to FILE and then ran a nested
492 // message loop, waiting for that message to be processed until quitting.
493 // However, doing so means that other messages will also be processed. In
494 // particular, if the GPU process host notices that the GPU has been killed
495 // during shutdown, it races exiting the nested loop with the process host
496 // blocking the message loop attempting to re-establish a connection to the
497 // GPU process synchronously. Because the system may not be allowing
498 // processes to launch, this can result in a hang. See
499 // http://crbug.com/318527.
500 rundown_counter
->TimedWait(
501 base::TimeDelta::FromSeconds(kEndSessionTimeoutSeconds
));
507 MetricsServicesManager
* BrowserProcessImpl::GetMetricsServicesManager() {
508 DCHECK(CalledOnValidThread());
509 if (!metrics_services_manager_
)
510 metrics_services_manager_
.reset(new MetricsServicesManager(local_state()));
511 return metrics_services_manager_
.get();
514 metrics::MetricsService
* BrowserProcessImpl::metrics_service() {
515 DCHECK(CalledOnValidThread());
516 return GetMetricsServicesManager()->GetMetricsService();
519 rappor::RapporService
* BrowserProcessImpl::rappor_service() {
520 DCHECK(CalledOnValidThread());
521 return GetMetricsServicesManager()->GetRapporService();
524 IOThread
* BrowserProcessImpl::io_thread() {
525 DCHECK(CalledOnValidThread());
526 DCHECK(io_thread_
.get());
527 return io_thread_
.get();
530 WatchDogThread
* BrowserProcessImpl::watchdog_thread() {
531 DCHECK(CalledOnValidThread());
532 if (!created_watchdog_thread_
)
533 CreateWatchdogThread();
534 DCHECK(watchdog_thread_
.get() != NULL
);
535 return watchdog_thread_
.get();
538 ProfileManager
* BrowserProcessImpl::profile_manager() {
539 DCHECK(CalledOnValidThread());
540 if (!created_profile_manager_
)
541 CreateProfileManager();
542 return profile_manager_
.get();
545 PrefService
* BrowserProcessImpl::local_state() {
546 DCHECK(CalledOnValidThread());
547 if (!created_local_state_
)
549 return local_state_
.get();
552 net::URLRequestContextGetter
* BrowserProcessImpl::system_request_context() {
553 DCHECK(CalledOnValidThread());
554 return io_thread()->system_url_request_context_getter();
557 chrome_variations::VariationsService
* BrowserProcessImpl::variations_service() {
558 DCHECK(CalledOnValidThread());
559 return GetMetricsServicesManager()->GetVariationsService();
562 BrowserProcessPlatformPart
* BrowserProcessImpl::platform_part() {
563 return platform_part_
.get();
566 extensions::EventRouterForwarder
*
567 BrowserProcessImpl::extension_event_router_forwarder() {
568 #if defined(ENABLE_EXTENSIONS)
569 return extension_event_router_forwarder_
.get();
575 NotificationUIManager
* BrowserProcessImpl::notification_ui_manager() {
576 DCHECK(CalledOnValidThread());
577 if (!created_notification_ui_manager_
)
578 CreateNotificationUIManager();
579 return notification_ui_manager_
.get();
582 message_center::MessageCenter
* BrowserProcessImpl::message_center() {
583 DCHECK(CalledOnValidThread());
584 return message_center::MessageCenter::Get();
587 policy::BrowserPolicyConnector
* BrowserProcessImpl::browser_policy_connector() {
588 DCHECK(CalledOnValidThread());
589 #if defined(ENABLE_CONFIGURATION_POLICY)
590 if (!created_browser_policy_connector_
) {
591 DCHECK(!browser_policy_connector_
);
592 browser_policy_connector_
= platform_part_
->CreateBrowserPolicyConnector();
593 created_browser_policy_connector_
= true;
595 return browser_policy_connector_
.get();
601 policy::PolicyService
* BrowserProcessImpl::policy_service() {
602 #if defined(ENABLE_CONFIGURATION_POLICY)
603 return browser_policy_connector()->GetPolicyService();
605 if (!policy_service_
.get())
606 policy_service_
.reset(new policy::PolicyServiceStub());
607 return policy_service_
.get();
611 IconManager
* BrowserProcessImpl::icon_manager() {
612 DCHECK(CalledOnValidThread());
613 if (!created_icon_manager_
)
615 return icon_manager_
.get();
618 GLStringManager
* BrowserProcessImpl::gl_string_manager() {
619 DCHECK(CalledOnValidThread());
620 if (!gl_string_manager_
.get())
621 gl_string_manager_
.reset(new GLStringManager());
622 return gl_string_manager_
.get();
625 GpuModeManager
* BrowserProcessImpl::gpu_mode_manager() {
626 DCHECK(CalledOnValidThread());
627 if (!gpu_mode_manager_
.get())
628 gpu_mode_manager_
.reset(new GpuModeManager());
629 return gpu_mode_manager_
.get();
632 void BrowserProcessImpl::CreateDevToolsHttpProtocolHandler(
633 chrome::HostDesktopType host_desktop_type
,
634 const std::string
& ip
,
636 DCHECK(CalledOnValidThread());
637 #if !defined(OS_ANDROID)
638 // StartupBrowserCreator::LaunchBrowser can be run multiple times when browser
639 // is started with several profiles or existing browser process is reused.
640 if (!remote_debugging_server_
.get()) {
641 remote_debugging_server_
.reset(
642 new RemoteDebuggingServer(host_desktop_type
, ip
, port
));
647 bool BrowserProcessImpl::IsShuttingDown() {
648 DCHECK(CalledOnValidThread());
649 return did_start_
&& 0 == module_ref_count_
;
652 printing::PrintJobManager
* BrowserProcessImpl::print_job_manager() {
653 DCHECK(CalledOnValidThread());
654 return print_job_manager_
.get();
657 printing::PrintPreviewDialogController
*
658 BrowserProcessImpl::print_preview_dialog_controller() {
659 #if defined(ENABLE_PRINT_PREVIEW)
660 DCHECK(CalledOnValidThread());
661 if (!print_preview_dialog_controller_
.get())
662 CreatePrintPreviewDialogController();
663 return print_preview_dialog_controller_
.get();
670 printing::BackgroundPrintingManager
*
671 BrowserProcessImpl::background_printing_manager() {
672 #if defined(ENABLE_PRINT_PREVIEW)
673 DCHECK(CalledOnValidThread());
674 if (!background_printing_manager_
.get())
675 CreateBackgroundPrintingManager();
676 return background_printing_manager_
.get();
683 IntranetRedirectDetector
* BrowserProcessImpl::intranet_redirect_detector() {
684 DCHECK(CalledOnValidThread());
685 if (!intranet_redirect_detector_
.get())
686 CreateIntranetRedirectDetector();
687 return intranet_redirect_detector_
.get();
690 const std::string
& BrowserProcessImpl::GetApplicationLocale() {
691 DCHECK(!locale_
.empty());
695 void BrowserProcessImpl::SetApplicationLocale(const std::string
& locale
) {
697 #if defined(ENABLE_EXTENSIONS)
698 extension_l10n_util::SetProcessLocale(locale
);
700 chrome::ChromeContentBrowserClient::SetApplicationLocale(locale
);
701 translate::TranslateDownloadManager::GetInstance()->set_application_locale(
705 DownloadStatusUpdater
* BrowserProcessImpl::download_status_updater() {
706 return download_status_updater_
.get();
709 MediaFileSystemRegistry
* BrowserProcessImpl::media_file_system_registry() {
710 #if defined(ENABLE_EXTENSIONS)
711 if (!media_file_system_registry_
)
712 media_file_system_registry_
.reset(new MediaFileSystemRegistry());
713 return media_file_system_registry_
.get();
719 bool BrowserProcessImpl::created_local_state() const {
720 return created_local_state_
;
723 #if defined(ENABLE_WEBRTC)
724 WebRtcLogUploader
* BrowserProcessImpl::webrtc_log_uploader() {
725 if (!webrtc_log_uploader_
.get())
726 webrtc_log_uploader_
.reset(new WebRtcLogUploader());
727 return webrtc_log_uploader_
.get();
731 network_time::NetworkTimeTracker
* BrowserProcessImpl::network_time_tracker() {
732 if (!network_time_tracker_
) {
733 network_time_tracker_
.reset(new network_time::NetworkTimeTracker(
734 scoped_ptr
<base::TickClock
>(new base::DefaultTickClock()),
737 return network_time_tracker_
.get();
740 gcm::GCMDriver
* BrowserProcessImpl::gcm_driver() {
741 DCHECK(CalledOnValidThread());
744 return gcm_driver_
.get();
748 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple
* registry
) {
749 registry
->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled
,
751 // This policy needs to be defined before the net subsystem is initialized,
753 registry
->RegisterIntegerPref(prefs::kMaxConnectionsPerProxy
,
754 net::kDefaultMaxSocketsPerProxyServer
);
756 registry
->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt
, false);
758 #if defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
759 registry
->RegisterBooleanPref(prefs::kEulaAccepted
, false);
760 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
762 if (base::win::GetVersion() >= base::win::VERSION_WIN7
) {
763 registry
->RegisterStringPref(prefs::kRelaunchMode
,
764 upgrade_util::kRelaunchModeDefault
);
768 // TODO(brettw,*): this comment about ResourceBundle was here since
769 // initial commit. This comment seems unrelated, bit-rotten and
770 // a candidate for removal.
771 // Initialize ResourceBundle which handles files loaded from external
772 // sources. This has to be done before uninstall code path and before prefs
774 registry
->RegisterStringPref(prefs::kApplicationLocale
, std::string());
775 #if defined(OS_CHROMEOS)
776 registry
->RegisterStringPref(prefs::kOwnerLocale
, std::string());
777 registry
->RegisterStringPref(prefs::kHardwareKeyboardLayout
,
779 #endif // defined(OS_CHROMEOS)
780 #if !defined(OS_CHROMEOS)
781 registry
->RegisterBooleanPref(
782 prefs::kMetricsReportingEnabled
,
783 GoogleUpdateSettings::GetCollectStatsConsent());
784 #endif // !defined(OS_CHROMEOS)
786 #if defined(OS_ANDROID)
787 registry
->RegisterBooleanPref(
788 prefs::kCrashReportingEnabled
, false);
789 #endif // defined(OS_ANDROID)
792 DownloadRequestLimiter
* BrowserProcessImpl::download_request_limiter() {
793 DCHECK(CalledOnValidThread());
794 if (!download_request_limiter_
.get())
795 download_request_limiter_
= new DownloadRequestLimiter();
796 return download_request_limiter_
.get();
799 BackgroundModeManager
* BrowserProcessImpl::background_mode_manager() {
800 DCHECK(CalledOnValidThread());
801 #if defined(ENABLE_BACKGROUND)
802 if (!background_mode_manager_
.get())
803 CreateBackgroundModeManager();
804 return background_mode_manager_
.get();
811 void BrowserProcessImpl::set_background_mode_manager_for_test(
812 scoped_ptr
<BackgroundModeManager
> manager
) {
813 #if defined(ENABLE_BACKGROUND)
814 background_mode_manager_
= manager
.Pass();
818 StatusTray
* BrowserProcessImpl::status_tray() {
819 DCHECK(CalledOnValidThread());
820 if (!status_tray_
.get())
822 return status_tray_
.get();
826 SafeBrowsingService
* BrowserProcessImpl::safe_browsing_service() {
827 DCHECK(CalledOnValidThread());
828 if (!created_safe_browsing_service_
)
829 CreateSafeBrowsingService();
830 return safe_browsing_service_
.get();
833 safe_browsing::ClientSideDetectionService
*
834 BrowserProcessImpl::safe_browsing_detection_service() {
835 DCHECK(CalledOnValidThread());
836 if (safe_browsing_service())
837 return safe_browsing_service()->safe_browsing_detection_service();
841 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
842 void BrowserProcessImpl::StartAutoupdateTimer() {
843 autoupdate_timer_
.Start(FROM_HERE
,
844 base::TimeDelta::FromHours(kUpdateCheckIntervalHours
),
846 &BrowserProcessImpl::OnAutoupdateTimer
);
850 ChromeNetLog
* BrowserProcessImpl::net_log() {
851 return net_log_
.get();
854 prerender::PrerenderTracker
* BrowserProcessImpl::prerender_tracker() {
855 if (!prerender_tracker_
.get())
856 prerender_tracker_
.reset(new prerender::PrerenderTracker
);
858 return prerender_tracker_
.get();
861 component_updater::ComponentUpdateService
*
862 BrowserProcessImpl::component_updater() {
863 if (!component_updater_
.get()) {
864 if (!BrowserThread::CurrentlyOn(BrowserThread::UI
))
866 component_updater::Configurator
* configurator
=
867 component_updater::MakeChromeComponentUpdaterConfigurator(
868 CommandLine::ForCurrentProcess(),
869 io_thread()->system_url_request_context_getter());
870 // Creating the component updater does not do anything, components
871 // need to be registered and Start() needs to be called.
872 component_updater_
.reset(ComponentUpdateServiceFactory(configurator
));
874 return component_updater_
.get();
877 CRLSetFetcher
* BrowserProcessImpl::crl_set_fetcher() {
878 if (!crl_set_fetcher_
.get())
879 crl_set_fetcher_
= new CRLSetFetcher();
880 return crl_set_fetcher_
.get();
883 component_updater::PnaclComponentInstaller
*
884 BrowserProcessImpl::pnacl_component_installer() {
885 #if !defined(DISABLE_NACL)
886 if (!pnacl_component_installer_
.get()) {
887 pnacl_component_installer_
.reset(
888 new component_updater::PnaclComponentInstaller());
890 return pnacl_component_installer_
.get();
896 void BrowserProcessImpl::ResourceDispatcherHostCreated() {
897 resource_dispatcher_host_delegate_
.reset(
898 new ChromeResourceDispatcherHostDelegate(prerender_tracker()));
899 ResourceDispatcherHost::Get()->SetDelegate(
900 resource_dispatcher_host_delegate_
.get());
902 pref_change_registrar_
.Add(
903 prefs::kAllowCrossOriginAuthPrompt
,
904 base::Bind(&BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy
,
905 base::Unretained(this)));
906 ApplyAllowCrossOriginAuthPromptPolicy();
909 void BrowserProcessImpl::CreateWatchdogThread() {
910 DCHECK(!created_watchdog_thread_
&& watchdog_thread_
.get() == NULL
);
911 created_watchdog_thread_
= true;
913 scoped_ptr
<WatchDogThread
> thread(new WatchDogThread());
914 base::Thread::Options options
;
915 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
916 if (!thread
->StartWithOptions(options
))
918 watchdog_thread_
.swap(thread
);
921 void BrowserProcessImpl::CreateProfileManager() {
922 DCHECK(!created_profile_manager_
&& profile_manager_
.get() == NULL
);
923 created_profile_manager_
= true;
925 base::FilePath user_data_dir
;
926 PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
);
927 profile_manager_
.reset(new ProfileManager(user_data_dir
));
930 void BrowserProcessImpl::CreateLocalState() {
931 DCHECK(!created_local_state_
&& local_state_
.get() == NULL
);
932 created_local_state_
= true;
934 base::FilePath local_state_path
;
935 CHECK(PathService::Get(chrome::FILE_LOCAL_STATE
, &local_state_path
));
936 scoped_refptr
<PrefRegistrySimple
> pref_registry
= new PrefRegistrySimple
;
938 // Register local state preferences.
939 chrome::RegisterLocalState(pref_registry
.get());
942 chrome_prefs::CreateLocalState(local_state_path
,
943 local_state_task_runner_
.get(),
948 pref_change_registrar_
.Init(local_state_
.get());
950 // Initialize the notification for the default browser setting policy.
951 pref_change_registrar_
.Add(
952 prefs::kDefaultBrowserSettingEnabled
,
953 base::Bind(&BrowserProcessImpl::ApplyDefaultBrowserPolicy
,
954 base::Unretained(this)));
956 // This preference must be kept in sync with external values; update them
957 // whenever the preference or its controlling policy changes.
958 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
959 pref_change_registrar_
.Add(
960 prefs::kMetricsReportingEnabled
,
961 base::Bind(&BrowserProcessImpl::ApplyMetricsReportingPolicy
,
962 base::Unretained(this)));
965 int max_per_proxy
= local_state_
->GetInteger(prefs::kMaxConnectionsPerProxy
);
966 net::ClientSocketPoolManager::set_max_sockets_per_proxy_server(
967 net::HttpNetworkSession::NORMAL_SOCKET_POOL
,
968 std::max(std::min(max_per_proxy
, 99),
969 net::ClientSocketPoolManager::max_sockets_per_group(
970 net::HttpNetworkSession::NORMAL_SOCKET_POOL
)));
973 void BrowserProcessImpl::PreCreateThreads() {
975 new IOThread(local_state(), policy_service(), net_log_
.get(),
976 extension_event_router_forwarder()));
979 void BrowserProcessImpl::PreMainMessageLoopRun() {
980 #if defined(ENABLE_CONFIGURATION_POLICY)
981 // browser_policy_connector() is created very early because local_state()
982 // needs policy to be initialized with the managed preference values.
983 // However, policy fetches from the network and loading of disk caches
984 // requires that threads are running; this Init() call lets the connector
985 // resume its initialization now that the loops are spinning and the
986 // system request context is available for the fetchers.
987 browser_policy_connector()->Init(local_state(), system_request_context());
990 if (local_state_
->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled
))
991 ApplyDefaultBrowserPolicy();
993 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
994 ApplyMetricsReportingPolicy();
997 #if defined(ENABLE_PLUGINS)
998 PluginService
* plugin_service
= PluginService::GetInstance();
999 plugin_service
->SetFilter(ChromePluginServiceFilter::GetInstance());
1000 plugin_service
->StartWatchingPlugins();
1002 #if defined(OS_POSIX)
1003 // Also find plugins in a user-specific plugins dir,
1004 // e.g. ~/.config/chromium/Plugins.
1005 const CommandLine
& cmd_line
= *CommandLine::ForCurrentProcess();
1006 if (!cmd_line
.HasSwitch(switches::kDisablePluginsDiscovery
)) {
1007 base::FilePath user_data_dir
;
1008 if (PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
))
1009 plugin_service
->AddExtraPluginDir(user_data_dir
.Append("Plugins"));
1013 // Triggers initialization of the singleton instance on UI thread.
1014 PluginFinder::GetInstance()->Init();
1016 #if defined(ENABLE_PLUGIN_INSTALLATION)
1017 DCHECK(!plugins_resource_service_
.get());
1018 plugins_resource_service_
= new PluginsResourceService(local_state());
1019 plugins_resource_service_
->Init();
1021 #endif // defined(ENABLE_PLUGINS)
1023 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
1024 if (!command_line
.HasSwitch(switches::kDisableWebResources
)) {
1025 DCHECK(!promo_resource_service_
.get());
1026 promo_resource_service_
= new PromoResourceService
;
1027 promo_resource_service_
->StartAfterDelay();
1030 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1031 storage_monitor::StorageMonitor::Create();
1034 platform_part_
->PreMainMessageLoopRun();
1037 void BrowserProcessImpl::CreateIconManager() {
1038 DCHECK(!created_icon_manager_
&& icon_manager_
.get() == NULL
);
1039 created_icon_manager_
= true;
1040 icon_manager_
.reset(new IconManager
);
1043 void BrowserProcessImpl::CreateIntranetRedirectDetector() {
1044 DCHECK(intranet_redirect_detector_
.get() == NULL
);
1045 scoped_ptr
<IntranetRedirectDetector
> intranet_redirect_detector(
1046 new IntranetRedirectDetector
);
1047 intranet_redirect_detector_
.swap(intranet_redirect_detector
);
1050 void BrowserProcessImpl::CreateNotificationUIManager() {
1051 #if defined(ENABLE_NOTIFICATIONS)
1052 DCHECK(notification_ui_manager_
.get() == NULL
);
1053 notification_ui_manager_
.reset(NotificationUIManager::Create(local_state()));
1054 created_notification_ui_manager_
= true;
1058 void BrowserProcessImpl::CreateBackgroundModeManager() {
1059 #if defined(ENABLE_BACKGROUND)
1060 DCHECK(background_mode_manager_
.get() == NULL
);
1061 background_mode_manager_
.reset(
1062 new BackgroundModeManager(CommandLine::ForCurrentProcess(),
1063 &profile_manager()->GetProfileInfoCache()));
1067 void BrowserProcessImpl::CreateStatusTray() {
1068 DCHECK(status_tray_
.get() == NULL
);
1069 status_tray_
.reset(StatusTray::Create());
1072 void BrowserProcessImpl::CreatePrintPreviewDialogController() {
1073 #if defined(ENABLE_PRINT_PREVIEW)
1074 DCHECK(print_preview_dialog_controller_
.get() == NULL
);
1075 print_preview_dialog_controller_
=
1076 new printing::PrintPreviewDialogController();
1082 void BrowserProcessImpl::CreateBackgroundPrintingManager() {
1083 #if defined(ENABLE_PRINT_PREVIEW)
1084 DCHECK(background_printing_manager_
.get() == NULL
);
1085 background_printing_manager_
.reset(new printing::BackgroundPrintingManager());
1091 void BrowserProcessImpl::CreateSafeBrowsingService() {
1092 DCHECK(safe_browsing_service_
.get() == NULL
);
1093 // Set this flag to true so that we don't retry indefinitely to
1094 // create the service class if there was an error.
1095 created_safe_browsing_service_
= true;
1096 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
1097 safe_browsing_service_
= SafeBrowsingService::CreateSafeBrowsingService();
1098 safe_browsing_service_
->Initialize();
1102 void BrowserProcessImpl::CreateGCMDriver() {
1103 DCHECK(!gcm_driver_
);
1105 #if defined(OS_ANDROID)
1106 // Android's GCMDriver currently makes the assumption that it's a singleton.
1107 // Until this gets fixed, instantiating multiple Java GCMDrivers will throw
1108 // an exception, but because they're only initialized on demand these crashes
1109 // would be very difficult to triage. See http://crbug.com/437827.
1112 base::FilePath store_path
;
1113 CHECK(PathService::Get(chrome::DIR_GLOBAL_GCM_STORE
, &store_path
));
1114 gcm_driver_
= gcm::CreateGCMDriverDesktop(
1115 make_scoped_ptr(new gcm::GCMClientFactory
),
1118 system_request_context());
1119 // Sign-in is not required for device-level GCM usage. So we just call
1120 // OnSignedIn to assume always signed-in. Note that GCM will not be started
1121 // at this point since no one has asked for it yet.
1122 // TODO(jianli): To be removed when sign-in enforcement is dropped.
1123 gcm_driver_
->OnSignedIn();
1124 #endif // defined(OS_ANDROID)
1127 void BrowserProcessImpl::ApplyDefaultBrowserPolicy() {
1128 if (local_state()->GetBoolean(prefs::kDefaultBrowserSettingEnabled
)) {
1129 scoped_refptr
<ShellIntegration::DefaultWebClientWorker
>
1130 set_browser_worker
= new ShellIntegration::DefaultBrowserWorker(NULL
);
1131 set_browser_worker
->StartSetAsDefault();
1135 void BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy() {
1136 bool value
= local_state()->GetBoolean(prefs::kAllowCrossOriginAuthPrompt
);
1137 ResourceDispatcherHost::Get()->SetAllowCrossOriginAuthPrompt(value
);
1140 void BrowserProcessImpl::ApplyMetricsReportingPolicy() {
1141 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1142 CHECK(BrowserThread::PostTask(
1143 BrowserThread::FILE, FROM_HERE
,
1145 base::IgnoreResult(&GoogleUpdateSettings::SetCollectStatsConsent
),
1146 local_state()->GetBoolean(prefs::kMetricsReportingEnabled
))));
1150 // Mac is currently not supported.
1151 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
1153 bool BrowserProcessImpl::CanAutorestartForUpdate() const {
1154 // Check if browser is in the background and if it needs to be restarted to
1155 // apply a pending update.
1156 return chrome::GetTotalBrowserCount() == 0 && chrome::WillKeepAlive() &&
1157 upgrade_util::IsUpdatePendingRestart();
1160 // Switches to add when auto-restarting Chrome.
1161 const char* const kSwitchesToAddOnAutorestart
[] = {
1162 switches::kNoStartupWindow
1165 void BrowserProcessImpl::RestartBackgroundInstance() {
1166 CommandLine
* old_cl
= CommandLine::ForCurrentProcess();
1167 scoped_ptr
<CommandLine
> new_cl(new CommandLine(old_cl
->GetProgram()));
1169 std::map
<std::string
, CommandLine::StringType
> switches
=
1170 old_cl
->GetSwitches();
1172 switches::RemoveSwitchesForAutostart(&switches
);
1174 // Append the rest of the switches (along with their values, if any)
1175 // to the new command line
1176 for (std::map
<std::string
, CommandLine::StringType
>::const_iterator i
=
1177 switches
.begin(); i
!= switches
.end(); ++i
) {
1178 CommandLine::StringType switch_value
= i
->second
;
1179 if (switch_value
.length() > 0) {
1180 new_cl
->AppendSwitchNative(i
->first
, i
->second
);
1182 new_cl
->AppendSwitch(i
->first
);
1186 // Ensure that our desired switches are set on the new process.
1187 for (size_t i
= 0; i
< arraysize(kSwitchesToAddOnAutorestart
); ++i
) {
1188 if (!new_cl
->HasSwitch(kSwitchesToAddOnAutorestart
[i
]))
1189 new_cl
->AppendSwitch(kSwitchesToAddOnAutorestart
[i
]);
1192 DLOG(WARNING
) << "Shutting down current instance of the browser.";
1193 chrome::AttemptExit();
1195 // Transfer ownership to Upgrade.
1196 upgrade_util::SetNewCommandLine(new_cl
.release());
1199 void BrowserProcessImpl::OnAutoupdateTimer() {
1200 if (CanAutorestartForUpdate()) {
1201 DLOG(WARNING
) << "Detected update. Restarting browser.";
1202 RestartBackgroundInstance();
1206 #endif // (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)