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/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/command_line.h"
14 #include "base/debug/alias.h"
15 #include "base/debug/leak_annotations.h"
16 #include "base/path_service.h"
17 #include "base/prefs/json_pref_store.h"
18 #include "base/prefs/pref_registry_simple.h"
19 #include "base/prefs/pref_service.h"
20 #include "base/synchronization/waitable_event.h"
21 #include "base/threading/thread.h"
22 #include "base/threading/thread_restrictions.h"
23 #include "chrome/browser/apps/chrome_apps_client.h"
24 #include "chrome/browser/automation/automation_provider_list.h"
25 #include "chrome/browser/background/background_mode_manager.h"
26 #include "chrome/browser/chrome_browser_main.h"
27 #include "chrome/browser/chrome_content_browser_client.h"
28 #include "chrome/browser/chrome_notification_types.h"
29 #include "chrome/browser/component_updater/component_updater_configurator.h"
30 #include "chrome/browser/component_updater/component_updater_service.h"
31 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
32 #include "chrome/browser/defaults.h"
33 #include "chrome/browser/devtools/remote_debugging_server.h"
34 #include "chrome/browser/download/download_request_limiter.h"
35 #include "chrome/browser/download/download_status_updater.h"
36 #include "chrome/browser/extensions/chrome_extensions_browser_client.h"
37 #include "chrome/browser/extensions/event_router_forwarder.h"
38 #include "chrome/browser/extensions/extension_renderer_state.h"
39 #include "chrome/browser/first_run/upgrade_util.h"
40 #include "chrome/browser/gpu/gl_string_manager.h"
41 #include "chrome/browser/gpu/gpu_mode_manager.h"
42 #include "chrome/browser/icon_manager.h"
43 #include "chrome/browser/idle.h"
44 #include "chrome/browser/intranet_redirect_detector.h"
45 #include "chrome/browser/io_thread.h"
46 #include "chrome/browser/lifetime/application_lifetime.h"
47 #include "chrome/browser/metrics/metrics_service.h"
48 #include "chrome/browser/metrics/thread_watcher.h"
49 #include "chrome/browser/metrics/variations/variations_service.h"
50 #include "chrome/browser/net/chrome_net_log.h"
51 #include "chrome/browser/net/crl_set_fetcher.h"
52 #include "chrome/browser/net/sdch_dictionary_fetcher.h"
53 #include "chrome/browser/notifications/notification_ui_manager.h"
54 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
55 #include "chrome/browser/plugins/plugin_finder.h"
56 #include "chrome/browser/prefs/browser_prefs.h"
57 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
58 #include "chrome/browser/prerender/prerender_tracker.h"
59 #include "chrome/browser/printing/background_printing_manager.h"
60 #include "chrome/browser/printing/print_job_manager.h"
61 #include "chrome/browser/printing/print_preview_dialog_controller.h"
62 #include "chrome/browser/profiles/profile_manager.h"
63 #include "chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h"
64 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
65 #include "chrome/browser/shell_integration.h"
66 #include "chrome/browser/status_icons/status_tray.h"
67 #include "chrome/browser/storage_monitor/storage_monitor.h"
68 #include "chrome/browser/thumbnails/render_widget_snapshot_taker.h"
69 #include "chrome/browser/ui/bookmarks/bookmark_prompt_controller.h"
70 #include "chrome/browser/ui/browser_dialogs.h"
71 #include "chrome/browser/ui/browser_finder.h"
72 #include "chrome/browser/web_resource/promo_resource_service.h"
73 #include "chrome/common/chrome_constants.h"
74 #include "chrome/common/chrome_paths.h"
75 #include "chrome/common/chrome_switches.h"
76 #include "chrome/common/extensions/chrome_extensions_client.h"
77 #include "chrome/common/extensions/extension_l10n_util.h"
78 #include "chrome/common/pref_names.h"
79 #include "chrome/common/profile_management_switches.h"
80 #include "chrome/common/switch_utils.h"
81 #include "chrome/common/url_constants.h"
82 #include "chrome/installer/util/google_update_constants.h"
83 #include "components/policy/core/common/policy_service.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 "extensions/common/constants.h"
91 #include "net/socket/client_socket_pool_manager.h"
92 #include "net/url_request/url_request_context_getter.h"
93 #include "ui/base/l10n/l10n_util.h"
94 #include "ui/message_center/message_center.h"
96 #if defined(ENABLE_CONFIGURATION_POLICY)
97 #include "chrome/browser/policy/browser_policy_connector.h"
99 #include "components/policy/core/common/policy_service_stub.h"
100 #endif // defined(ENABLE_CONFIGURATION_POLICY)
103 #include "base/win/windows_version.h"
104 #include "ui/views/focus/view_storage.h"
105 #elif defined(OS_MACOSX)
106 #include "chrome/browser/chrome_browser_main_mac.h"
109 #if defined(USE_AURA)
110 #include "ui/aura/env.h"
113 #if !defined(OS_ANDROID) && !defined(OS_IOS)
114 #include "chrome/browser/media_galleries/media_file_system_registry.h"
117 #if defined(ENABLE_PLUGIN_INSTALLATION)
118 #include "chrome/browser/plugins/plugins_resource_service.h"
121 #if defined(ENABLE_WEBRTC)
122 #include "chrome/browser/media/webrtc_log_uploader.h"
125 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
126 // How often to check if the persistent instance of Chrome needs to restart
127 // to install an update.
128 static const int kUpdateCheckIntervalHours
= 6;
132 // Attest to the fact that the call to the file thread to save preferences has
133 // run, and it is safe to terminate. This avoids the potential of some other
134 // task prematurely terminating our waiting message loop by posting a
136 static bool g_end_session_file_thread_has_completed
= false;
140 // How long to wait for the File thread to complete during EndSession, on
141 // Linux. We have a timeout here because we're unable to run the UI messageloop
142 // and there's some deadlock risk. Our only option is to exit anyway.
143 static const int kEndSessionTimeoutSeconds
= 10;
146 using content::BrowserThread
;
147 using content::ChildProcessSecurityPolicy
;
148 using content::PluginService
;
149 using content::ResourceDispatcherHost
;
151 BrowserProcessImpl::BrowserProcessImpl(
152 base::SequencedTaskRunner
* local_state_task_runner
,
153 const CommandLine
& command_line
)
154 : created_metrics_service_(false),
155 created_watchdog_thread_(false),
156 created_browser_policy_connector_(false),
157 created_profile_manager_(false),
158 created_local_state_(false),
159 created_icon_manager_(false),
160 created_notification_ui_manager_(false),
161 created_safe_browsing_service_(false),
162 module_ref_count_(0),
164 checked_for_new_frames_(false),
165 using_new_frames_(false),
166 render_widget_snapshot_taker_(new RenderWidgetSnapshotTaker
),
167 download_status_updater_(new DownloadStatusUpdater
),
168 local_state_task_runner_(local_state_task_runner
) {
169 g_browser_process
= this;
170 platform_part_
.reset(new BrowserProcessPlatformPart());
172 #if defined(ENABLE_PRINTING)
173 // Must be created after the NotificationService.
174 print_job_manager_
.reset(new printing::PrintJobManager
);
177 net_log_
.reset(new ChromeNetLog
);
179 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
180 extensions::kExtensionScheme
);
181 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
182 extensions::kExtensionResourceScheme
);
183 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
184 chrome::kChromeSearchScheme
);
186 #if defined(OS_MACOSX)
190 apps::AppsClient::Set(ChromeAppsClient::GetInstance());
191 extensions::ExtensionsClient::Set(
192 extensions::ChromeExtensionsClient::GetInstance());
194 extensions_browser_client_
.reset(
195 new extensions::ChromeExtensionsBrowserClient
);
196 extensions::ExtensionsBrowserClient::Set(extensions_browser_client_
.get());
198 extension_event_router_forwarder_
= new extensions::EventRouterForwarder
;
199 ExtensionRendererState::GetInstance()->Init();
201 message_center::MessageCenter::Initialize();
204 BrowserProcessImpl::~BrowserProcessImpl() {
205 tracked_objects::ThreadData::EnsureCleanupWasCalled(4);
207 g_browser_process
= NULL
;
210 void BrowserProcessImpl::StartTearDown() {
211 TRACE_EVENT0("shutdown", "BrowserProcessImpl::StartTearDown");
212 #if defined(ENABLE_AUTOMATION)
213 // Delete the AutomationProviderList before NotificationService,
214 // since it may try to unregister notifications
215 // Both NotificationService and AutomationProvider are singleton instances in
216 // the BrowserProcess. Since AutomationProvider may have some active
217 // notification observers, it is essential that it gets destroyed before the
218 // NotificationService. NotificationService won't be destroyed until after
219 // this destructor is run.
220 automation_provider_list_
.reset();
223 // We need to shutdown the SdchDictionaryFetcher as it regularly holds
224 // a pointer to a URLFetcher, and that URLFetcher (upon destruction) will do
225 // a PostDelayedTask onto the IO thread. This shutdown call will both discard
226 // any pending URLFetchers, and avoid creating any more.
227 BrowserThread::PostTask(BrowserThread::IO
, FROM_HERE
,
228 base::Bind(&SdchDictionaryFetcher::Shutdown
));
230 // We need to destroy the MetricsService, VariationsService,
231 // IntranetRedirectDetector, PromoResourceService, and SafeBrowsing
232 // ClientSideDetectionService (owned by the SafeBrowsingService) before the
233 // io_thread_ gets destroyed, since their destructors can call the URLFetcher
234 // destructor, which does a PostDelayedTask operation on the IO thread. (The
235 // IO thread will handle that URLFetcher operation before going away.)
236 metrics_service_
.reset();
237 variations_service_
.reset();
238 intranet_redirect_detector_
.reset();
239 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
240 if (safe_browsing_service_
.get())
241 safe_browsing_service()->ShutDown();
244 // Need to clear the desktop notification balloons before the io_thread_ and
245 // before the profiles, since if there are any still showing we will access
246 // those things during teardown.
247 notification_ui_manager_
.reset();
249 // Need to clear profiles (download managers) before the io_thread_.
251 TRACE_EVENT0("shutdown",
252 "BrowserProcessImpl::StartTearDown:ProfileManager");
253 // The desktop User Manager needs to be closed before the guest profile
255 if (switches::IsNewProfileManagement())
256 chrome::HideUserManager();
257 profile_manager_
.reset();
260 #if !defined(OS_ANDROID)
261 // Debugger must be cleaned up before IO thread and NotificationService.
262 remote_debugging_server_
.reset();
265 ExtensionRendererState::GetInstance()->Shutdown();
267 #if !defined(OS_ANDROID) && !defined(OS_IOS)
268 media_file_system_registry_
.reset();
269 // Delete |storage_monitor_| now. Otherwise the FILE thread would be gone
270 // when we try to release it in the dtor and Valgrind would report a
271 // leak on almost every single browser_test.
272 // TODO(gbillock): Make this unnecessary.
273 storage_monitor_
.reset();
276 message_center::MessageCenter::Shutdown();
278 #if defined(ENABLE_CONFIGURATION_POLICY)
279 // The policy providers managed by |browser_policy_connector_| need to shut
280 // down while the IO and FILE threads are still alive.
281 if (browser_policy_connector_
)
282 browser_policy_connector_
->Shutdown();
285 // Stop the watchdog thread before stopping other threads.
286 watchdog_thread_
.reset();
288 #if defined(USE_AURA)
289 // Delete aura after the metrics service has been deleted as it accesses
290 // monitor information.
291 aura::Env::DeleteInstance();
294 platform_part()->StartTearDown();
296 #if defined(ENABLE_WEBRTC)
297 webrtc_log_uploader_
.reset();
301 local_state()->CommitPendingWrite();
304 void BrowserProcessImpl::PostDestroyThreads() {
305 // With the file_thread_ flushed, we can release any icon resources.
306 icon_manager_
.reset();
308 // Reset associated state right after actual thread is stopped,
309 // as io_thread_.global_ cleanup happens in CleanUp on the IO
310 // thread, i.e. as the thread exits its message loop.
312 // This is important also because in various places, the
313 // IOThread object being NULL is considered synonymous with the
314 // IO thread having stopped.
319 // Send a QuitTask to the given MessageLoop when the (file) thread has processed
320 // our (other) recent requests (to save preferences).
321 // Change the boolean so that the receiving thread will know that we did indeed
322 // send the QuitTask that terminated the message loop.
323 static void PostQuit(base::MessageLoop
* message_loop
) {
324 g_end_session_file_thread_has_completed
= true;
325 message_loop
->PostTask(FROM_HERE
, base::MessageLoop::QuitClosure());
327 #elif defined(USE_X11)
328 static void Signal(base::WaitableEvent
* event
) {
333 unsigned int BrowserProcessImpl::AddRefModule() {
334 DCHECK(CalledOnValidThread());
336 // CHECK(!IsShuttingDown());
337 if (IsShuttingDown()) {
338 // Copy the stacktrace which released the final reference onto our stack so
339 // it will be available in the crash report for inspection.
340 base::debug::StackTrace callstack
= release_last_reference_callstack_
;
341 base::debug::Alias(&callstack
);
347 return module_ref_count_
;
350 unsigned int BrowserProcessImpl::ReleaseModule() {
351 DCHECK(CalledOnValidThread());
352 DCHECK_NE(0u, module_ref_count_
);
354 if (0 == module_ref_count_
) {
355 release_last_reference_callstack_
= base::debug::StackTrace();
357 #if defined(ENABLE_PRINTING)
358 // Wait for the pending print jobs to finish. Don't do this later, since
359 // this might cause a nested message loop to run, and we don't want pending
360 // tasks to run once teardown has started.
361 print_job_manager_
->Shutdown();
364 #if defined(LEAK_SANITIZER)
365 // Check for memory leaks now, before we start shutting down threads. Doing
366 // this early means we won't report any shutdown-only leaks (as they have
367 // not yet happened at this point).
368 // If leaks are found, this will make the process exit immediately.
369 __lsan_do_leak_check();
372 CHECK(base::MessageLoop::current()->is_running());
374 #if defined(OS_MACOSX)
375 base::MessageLoop::current()->PostTask(
377 base::Bind(ChromeBrowserMainPartsMac::DidEndMainMessageLoop
));
379 base::MessageLoop::current()->Quit();
381 return module_ref_count_
;
384 void BrowserProcessImpl::EndSession() {
385 // Mark all the profiles as clean.
386 ProfileManager
* pm
= profile_manager();
387 std::vector
<Profile
*> profiles(pm
->GetLoadedProfiles());
388 for (size_t i
= 0; i
< profiles
.size(); ++i
)
389 profiles
[i
]->SetExitType(Profile::EXIT_SESSION_ENDED
);
391 // Tell the metrics service it was cleanly shutdown.
392 MetricsService
* metrics
= g_browser_process
->metrics_service();
393 if (metrics
&& local_state()) {
394 metrics
->RecordStartOfSessionEnd();
395 #if !defined(OS_CHROMEOS)
396 // MetricsService lazily writes to prefs, force it to write now.
397 // On ChromeOS, chrome gets killed when hangs, so no need to
398 // commit prefs::kStabilitySessionEndCompleted change immediately.
399 local_state()->CommitPendingWrite();
403 // http://crbug.com/125207
404 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
406 // We must write that the profile and metrics service shutdown cleanly,
407 // otherwise on startup we'll think we crashed. So we block until done and
408 // then proceed with normal shutdown.
410 // Can't run a local loop on linux. Instead create a waitable event.
411 scoped_ptr
<base::WaitableEvent
> done_writing(
412 new base::WaitableEvent(false, false));
413 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
,
414 base::Bind(Signal
, done_writing
.get()));
415 // If all file writes haven't cleared in the timeout, leak the WaitableEvent
416 // so that there's no race to reference it in Signal().
417 if (!done_writing
->TimedWait(
418 base::TimeDelta::FromSeconds(kEndSessionTimeoutSeconds
))) {
419 ignore_result(done_writing
.release());
422 #elif defined(OS_WIN)
423 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
,
424 base::Bind(PostQuit
, base::MessageLoop::current()));
425 int quits_received
= 0;
427 base::MessageLoop::current()->Run();
429 } while (!g_end_session_file_thread_has_completed
);
430 // If we did get extra quits, then we should re-post them to the message loop.
431 while (--quits_received
> 0) {
432 base::MessageLoop::current()->PostTask(FROM_HERE
,
433 base::MessageLoop::QuitClosure());
440 MetricsService
* BrowserProcessImpl::metrics_service() {
441 DCHECK(CalledOnValidThread());
442 if (!created_metrics_service_
)
443 CreateMetricsService();
444 return metrics_service_
.get();
447 IOThread
* BrowserProcessImpl::io_thread() {
448 DCHECK(CalledOnValidThread());
449 DCHECK(io_thread_
.get());
450 return io_thread_
.get();
453 WatchDogThread
* BrowserProcessImpl::watchdog_thread() {
454 DCHECK(CalledOnValidThread());
455 if (!created_watchdog_thread_
)
456 CreateWatchdogThread();
457 DCHECK(watchdog_thread_
.get() != NULL
);
458 return watchdog_thread_
.get();
461 ProfileManager
* BrowserProcessImpl::profile_manager() {
462 DCHECK(CalledOnValidThread());
463 if (!created_profile_manager_
)
464 CreateProfileManager();
465 return profile_manager_
.get();
468 PrefService
* BrowserProcessImpl::local_state() {
469 DCHECK(CalledOnValidThread());
470 if (!created_local_state_
)
472 return local_state_
.get();
475 net::URLRequestContextGetter
* BrowserProcessImpl::system_request_context() {
476 DCHECK(CalledOnValidThread());
477 return io_thread()->system_url_request_context_getter();
480 chrome_variations::VariationsService
* BrowserProcessImpl::variations_service() {
481 DCHECK(CalledOnValidThread());
482 if (!variations_service_
.get()) {
483 variations_service_
.reset(
484 chrome_variations::VariationsService::Create(local_state()));
486 return variations_service_
.get();
489 BrowserProcessPlatformPart
* BrowserProcessImpl::platform_part() {
490 return platform_part_
.get();
493 extensions::EventRouterForwarder
*
494 BrowserProcessImpl::extension_event_router_forwarder() {
495 return extension_event_router_forwarder_
.get();
498 NotificationUIManager
* BrowserProcessImpl::notification_ui_manager() {
499 DCHECK(CalledOnValidThread());
500 if (!created_notification_ui_manager_
)
501 CreateNotificationUIManager();
502 return notification_ui_manager_
.get();
505 message_center::MessageCenter
* BrowserProcessImpl::message_center() {
506 DCHECK(CalledOnValidThread());
507 return message_center::MessageCenter::Get();
510 policy::BrowserPolicyConnector
* BrowserProcessImpl::browser_policy_connector() {
511 DCHECK(CalledOnValidThread());
512 #if defined(ENABLE_CONFIGURATION_POLICY)
513 if (!created_browser_policy_connector_
) {
514 DCHECK(!browser_policy_connector_
);
515 browser_policy_connector_
.reset(new policy::BrowserPolicyConnector());
516 created_browser_policy_connector_
= true;
518 return browser_policy_connector_
.get();
524 policy::PolicyService
* BrowserProcessImpl::policy_service() {
525 #if defined(ENABLE_CONFIGURATION_POLICY)
526 return browser_policy_connector()->GetPolicyService();
528 if (!policy_service_
.get())
529 policy_service_
.reset(new policy::PolicyServiceStub());
530 return policy_service_
.get();
534 IconManager
* BrowserProcessImpl::icon_manager() {
535 DCHECK(CalledOnValidThread());
536 if (!created_icon_manager_
)
538 return icon_manager_
.get();
541 GLStringManager
* BrowserProcessImpl::gl_string_manager() {
542 DCHECK(CalledOnValidThread());
543 if (!gl_string_manager_
.get())
544 gl_string_manager_
.reset(new GLStringManager());
545 return gl_string_manager_
.get();
548 GpuModeManager
* BrowserProcessImpl::gpu_mode_manager() {
549 DCHECK(CalledOnValidThread());
550 if (!gpu_mode_manager_
.get())
551 gpu_mode_manager_
.reset(new GpuModeManager());
552 return gpu_mode_manager_
.get();
555 RenderWidgetSnapshotTaker
* BrowserProcessImpl::GetRenderWidgetSnapshotTaker() {
556 return render_widget_snapshot_taker_
.get();
559 AutomationProviderList
* BrowserProcessImpl::GetAutomationProviderList() {
560 DCHECK(CalledOnValidThread());
561 #if defined(ENABLE_AUTOMATION)
562 if (automation_provider_list_
.get() == NULL
)
563 automation_provider_list_
.reset(new AutomationProviderList());
564 return automation_provider_list_
.get();
570 void BrowserProcessImpl::CreateDevToolsHttpProtocolHandler(
571 chrome::HostDesktopType host_desktop_type
,
572 const std::string
& ip
,
574 const std::string
& frontend_url
) {
575 DCHECK(CalledOnValidThread());
576 #if !defined(OS_ANDROID)
577 // StartupBrowserCreator::LaunchBrowser can be run multiple times when browser
578 // is started with several profiles or existing browser process is reused.
579 if (!remote_debugging_server_
.get()) {
580 remote_debugging_server_
.reset(
581 new RemoteDebuggingServer(host_desktop_type
, ip
, port
,
587 bool BrowserProcessImpl::IsShuttingDown() {
588 DCHECK(CalledOnValidThread());
589 return did_start_
&& 0 == module_ref_count_
;
592 printing::PrintJobManager
* BrowserProcessImpl::print_job_manager() {
593 DCHECK(CalledOnValidThread());
594 return print_job_manager_
.get();
597 printing::PrintPreviewDialogController
*
598 BrowserProcessImpl::print_preview_dialog_controller() {
599 #if defined(ENABLE_FULL_PRINTING)
600 DCHECK(CalledOnValidThread());
601 if (!print_preview_dialog_controller_
.get())
602 CreatePrintPreviewDialogController();
603 return print_preview_dialog_controller_
.get();
610 printing::BackgroundPrintingManager
*
611 BrowserProcessImpl::background_printing_manager() {
612 #if defined(ENABLE_FULL_PRINTING)
613 DCHECK(CalledOnValidThread());
614 if (!background_printing_manager_
.get())
615 CreateBackgroundPrintingManager();
616 return background_printing_manager_
.get();
623 IntranetRedirectDetector
* BrowserProcessImpl::intranet_redirect_detector() {
624 DCHECK(CalledOnValidThread());
625 if (!intranet_redirect_detector_
.get())
626 CreateIntranetRedirectDetector();
627 return intranet_redirect_detector_
.get();
630 const std::string
& BrowserProcessImpl::GetApplicationLocale() {
631 DCHECK(!locale_
.empty());
635 void BrowserProcessImpl::SetApplicationLocale(const std::string
& locale
) {
637 extension_l10n_util::SetProcessLocale(locale
);
638 chrome::ChromeContentBrowserClient::SetApplicationLocale(locale
);
641 DownloadStatusUpdater
* BrowserProcessImpl::download_status_updater() {
642 return download_status_updater_
.get();
645 BookmarkPromptController
* BrowserProcessImpl::bookmark_prompt_controller() {
646 #if defined(OS_ANDROID)
649 return bookmark_prompt_controller_
.get();
653 StorageMonitor
* BrowserProcessImpl::storage_monitor() {
654 #if defined(OS_ANDROID) || defined(OS_IOS)
657 return storage_monitor_
.get();
661 void BrowserProcessImpl::set_storage_monitor_for_test(
662 scoped_ptr
<StorageMonitor
> monitor
) {
663 #if !defined(OS_ANDROID) && !defined(OS_IOS)
664 storage_monitor_
= monitor
.Pass();
668 MediaFileSystemRegistry
* BrowserProcessImpl::media_file_system_registry() {
669 #if defined(OS_ANDROID) || defined(OS_IOS)
672 if (!media_file_system_registry_
)
673 media_file_system_registry_
.reset(new MediaFileSystemRegistry());
674 return media_file_system_registry_
.get();
678 bool BrowserProcessImpl::created_local_state() const {
679 return created_local_state_
;
682 #if defined(ENABLE_WEBRTC)
683 WebRtcLogUploader
* BrowserProcessImpl::webrtc_log_uploader() {
684 if (!webrtc_log_uploader_
.get())
685 webrtc_log_uploader_
.reset(new WebRtcLogUploader());
686 return webrtc_log_uploader_
.get();
691 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple
* registry
) {
692 registry
->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled
,
694 // This policy needs to be defined before the net subsystem is initialized,
696 registry
->RegisterIntegerPref(prefs::kMaxConnectionsPerProxy
,
697 net::kDefaultMaxSocketsPerProxyServer
);
699 registry
->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt
, false);
701 #if defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
702 registry
->RegisterBooleanPref(prefs::kEulaAccepted
, false);
703 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
705 if (base::win::GetVersion() >= base::win::VERSION_WIN8
) {
706 registry
->RegisterStringPref(prefs::kRelaunchMode
,
707 upgrade_util::kRelaunchModeDefault
);
711 // TODO(brettw,*): this comment about ResourceBundle was here since
712 // initial commit. This comment seems unrelated, bit-rotten and
713 // a candidate for removal.
714 // Initialize ResourceBundle which handles files loaded from external
715 // sources. This has to be done before uninstall code path and before prefs
717 registry
->RegisterStringPref(prefs::kApplicationLocale
, std::string());
718 #if defined(OS_CHROMEOS)
719 registry
->RegisterStringPref(prefs::kOwnerLocale
, std::string());
720 registry
->RegisterStringPref(prefs::kHardwareKeyboardLayout
,
722 #endif // defined(OS_CHROMEOS)
723 #if !defined(OS_CHROMEOS)
724 registry
->RegisterBooleanPref(
725 prefs::kMetricsReportingEnabled
,
726 GoogleUpdateSettings::GetCollectStatsConsent());
727 #endif // !defined(OS_CHROMEOS)
729 #if defined(OS_ANDROID)
730 registry
->RegisterBooleanPref(
731 prefs::kCrashReportingEnabled
, false);
732 #endif // defined(OS_ANDROID)
735 DownloadRequestLimiter
* BrowserProcessImpl::download_request_limiter() {
736 DCHECK(CalledOnValidThread());
737 if (!download_request_limiter_
.get())
738 download_request_limiter_
= new DownloadRequestLimiter();
739 return download_request_limiter_
.get();
742 BackgroundModeManager
* BrowserProcessImpl::background_mode_manager() {
743 DCHECK(CalledOnValidThread());
744 #if defined(ENABLE_BACKGROUND)
745 if (!background_mode_manager_
.get())
746 CreateBackgroundModeManager();
747 return background_mode_manager_
.get();
754 void BrowserProcessImpl::set_background_mode_manager_for_test(
755 scoped_ptr
<BackgroundModeManager
> manager
) {
756 background_mode_manager_
= manager
.Pass();
759 StatusTray
* BrowserProcessImpl::status_tray() {
760 DCHECK(CalledOnValidThread());
761 if (!status_tray_
.get())
763 return status_tray_
.get();
767 SafeBrowsingService
* BrowserProcessImpl::safe_browsing_service() {
768 DCHECK(CalledOnValidThread());
769 if (!created_safe_browsing_service_
)
770 CreateSafeBrowsingService();
771 return safe_browsing_service_
.get();
774 safe_browsing::ClientSideDetectionService
*
775 BrowserProcessImpl::safe_browsing_detection_service() {
776 DCHECK(CalledOnValidThread());
777 if (safe_browsing_service())
778 return safe_browsing_service()->safe_browsing_detection_service();
782 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
783 void BrowserProcessImpl::StartAutoupdateTimer() {
784 autoupdate_timer_
.Start(FROM_HERE
,
785 base::TimeDelta::FromHours(kUpdateCheckIntervalHours
),
787 &BrowserProcessImpl::OnAutoupdateTimer
);
791 ChromeNetLog
* BrowserProcessImpl::net_log() {
792 return net_log_
.get();
795 prerender::PrerenderTracker
* BrowserProcessImpl::prerender_tracker() {
796 if (!prerender_tracker_
.get())
797 prerender_tracker_
.reset(new prerender::PrerenderTracker
);
799 return prerender_tracker_
.get();
802 component_updater::ComponentUpdateService
*
803 BrowserProcessImpl::component_updater() {
804 if (!component_updater_
.get()) {
805 if (!BrowserThread::CurrentlyOn(BrowserThread::UI
))
807 component_updater::ComponentUpdateService::Configurator
* configurator
=
808 component_updater::MakeChromeComponentUpdaterConfigurator(
809 CommandLine::ForCurrentProcess(),
810 io_thread()->system_url_request_context_getter());
811 // Creating the component updater does not do anything, components
812 // need to be registered and Start() needs to be called.
813 component_updater_
.reset(ComponentUpdateServiceFactory(configurator
));
815 return component_updater_
.get();
818 CRLSetFetcher
* BrowserProcessImpl::crl_set_fetcher() {
819 if (!crl_set_fetcher_
.get())
820 crl_set_fetcher_
= new CRLSetFetcher();
821 return crl_set_fetcher_
.get();
824 component_updater::PnaclComponentInstaller
*
825 BrowserProcessImpl::pnacl_component_installer() {
826 if (!pnacl_component_installer_
.get()) {
827 pnacl_component_installer_
.reset(
828 new component_updater::PnaclComponentInstaller());
830 return pnacl_component_installer_
.get();
833 void BrowserProcessImpl::ResourceDispatcherHostCreated() {
834 resource_dispatcher_host_delegate_
.reset(
835 new ChromeResourceDispatcherHostDelegate(prerender_tracker()));
836 ResourceDispatcherHost::Get()->SetDelegate(
837 resource_dispatcher_host_delegate_
.get());
839 pref_change_registrar_
.Add(
840 prefs::kAllowCrossOriginAuthPrompt
,
841 base::Bind(&BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy
,
842 base::Unretained(this)));
843 ApplyAllowCrossOriginAuthPromptPolicy();
846 void BrowserProcessImpl::CreateMetricsService() {
847 DCHECK(!created_metrics_service_
&& metrics_service_
.get() == NULL
);
848 created_metrics_service_
= true;
850 metrics_service_
.reset(new MetricsService
);
853 void BrowserProcessImpl::CreateWatchdogThread() {
854 DCHECK(!created_watchdog_thread_
&& watchdog_thread_
.get() == NULL
);
855 created_watchdog_thread_
= true;
857 scoped_ptr
<WatchDogThread
> thread(new WatchDogThread());
858 if (!thread
->Start())
860 watchdog_thread_
.swap(thread
);
863 void BrowserProcessImpl::CreateProfileManager() {
864 DCHECK(!created_profile_manager_
&& profile_manager_
.get() == NULL
);
865 created_profile_manager_
= true;
867 base::FilePath user_data_dir
;
868 PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
);
869 profile_manager_
.reset(new ProfileManager(user_data_dir
));
872 void BrowserProcessImpl::CreateLocalState() {
873 DCHECK(!created_local_state_
&& local_state_
.get() == NULL
);
874 created_local_state_
= true;
876 base::FilePath local_state_path
;
877 CHECK(PathService::Get(chrome::FILE_LOCAL_STATE
, &local_state_path
));
878 scoped_refptr
<PrefRegistrySimple
> pref_registry
= new PrefRegistrySimple
;
880 // Register local state preferences.
881 chrome::RegisterLocalState(pref_registry
.get());
884 chrome_prefs::CreateLocalState(local_state_path
,
885 local_state_task_runner_
.get(),
890 pref_change_registrar_
.Init(local_state_
.get());
892 // Initialize the notification for the default browser setting policy.
893 pref_change_registrar_
.Add(
894 prefs::kDefaultBrowserSettingEnabled
,
895 base::Bind(&BrowserProcessImpl::ApplyDefaultBrowserPolicy
,
896 base::Unretained(this)));
898 // This preference must be kept in sync with external values; update them
899 // whenever the preference or its controlling policy changes.
900 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
901 pref_change_registrar_
.Add(
902 prefs::kMetricsReportingEnabled
,
903 base::Bind(&BrowserProcessImpl::ApplyMetricsReportingPolicy
,
904 base::Unretained(this)));
907 int max_per_proxy
= local_state_
->GetInteger(prefs::kMaxConnectionsPerProxy
);
908 net::ClientSocketPoolManager::set_max_sockets_per_proxy_server(
909 net::HttpNetworkSession::NORMAL_SOCKET_POOL
,
910 std::max(std::min(max_per_proxy
, 99),
911 net::ClientSocketPoolManager::max_sockets_per_group(
912 net::HttpNetworkSession::NORMAL_SOCKET_POOL
)));
915 void BrowserProcessImpl::PreCreateThreads() {
916 io_thread_
.reset(new IOThread(local_state(), policy_service(), net_log_
.get(),
917 extension_event_router_forwarder_
.get()));
920 void BrowserProcessImpl::PreMainMessageLoopRun() {
921 #if defined(ENABLE_CONFIGURATION_POLICY)
922 // browser_policy_connector() is created very early because local_state()
923 // needs policy to be initialized with the managed preference values.
924 // However, policy fetches from the network and loading of disk caches
925 // requires that threads are running; this Init() call lets the connector
926 // resume its initialization now that the loops are spinning and the
927 // system request context is available for the fetchers.
928 browser_policy_connector()->Init(local_state(), system_request_context());
931 if (local_state_
->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled
))
932 ApplyDefaultBrowserPolicy();
934 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
935 ApplyMetricsReportingPolicy();
938 #if defined(ENABLE_PLUGINS)
939 PluginService
* plugin_service
= PluginService::GetInstance();
940 plugin_service
->SetFilter(ChromePluginServiceFilter::GetInstance());
941 plugin_service
->StartWatchingPlugins();
943 #if defined(OS_POSIX)
944 // Also find plugins in a user-specific plugins dir,
945 // e.g. ~/.config/chromium/Plugins.
946 const CommandLine
& cmd_line
= *CommandLine::ForCurrentProcess();
947 if (!cmd_line
.HasSwitch(switches::kDisablePluginsDiscovery
)) {
948 base::FilePath user_data_dir
;
949 if (PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
))
950 plugin_service
->AddExtraPluginDir(user_data_dir
.Append("Plugins"));
954 // Triggers initialization of the singleton instance on UI thread.
955 PluginFinder::GetInstance()->Init();
957 #if defined(ENABLE_PLUGIN_INSTALLATION)
958 DCHECK(!plugins_resource_service_
.get());
959 plugins_resource_service_
= new PluginsResourceService(local_state());
960 plugins_resource_service_
->Init();
962 #endif // defined(ENABLE_PLUGINS)
964 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
965 if (!command_line
.HasSwitch(switches::kDisableWebResources
)) {
966 DCHECK(!promo_resource_service_
.get());
967 promo_resource_service_
= new PromoResourceService
;
968 promo_resource_service_
->StartAfterDelay();
971 #if !defined(OS_ANDROID)
972 if (browser_defaults::bookmarks_enabled
&&
973 BookmarkPromptController::IsEnabled()) {
974 bookmark_prompt_controller_
.reset(new BookmarkPromptController());
978 #if !defined(OS_ANDROID) && !defined(OS_IOS)
979 storage_monitor_
.reset(StorageMonitor::Create());
982 platform_part_
->PreMainMessageLoopRun();
985 void BrowserProcessImpl::CreateIconManager() {
986 DCHECK(!created_icon_manager_
&& icon_manager_
.get() == NULL
);
987 created_icon_manager_
= true;
988 icon_manager_
.reset(new IconManager
);
991 void BrowserProcessImpl::CreateIntranetRedirectDetector() {
992 DCHECK(intranet_redirect_detector_
.get() == NULL
);
993 scoped_ptr
<IntranetRedirectDetector
> intranet_redirect_detector(
994 new IntranetRedirectDetector
);
995 intranet_redirect_detector_
.swap(intranet_redirect_detector
);
998 void BrowserProcessImpl::CreateNotificationUIManager() {
999 #if defined(ENABLE_NOTIFICATIONS)
1000 DCHECK(notification_ui_manager_
.get() == NULL
);
1001 notification_ui_manager_
.reset(NotificationUIManager::Create(local_state()));
1002 created_notification_ui_manager_
= true;
1006 void BrowserProcessImpl::CreateBackgroundModeManager() {
1007 DCHECK(background_mode_manager_
.get() == NULL
);
1008 background_mode_manager_
.reset(
1009 new BackgroundModeManager(CommandLine::ForCurrentProcess(),
1010 &profile_manager()->GetProfileInfoCache()));
1013 void BrowserProcessImpl::CreateStatusTray() {
1014 DCHECK(status_tray_
.get() == NULL
);
1015 status_tray_
.reset(StatusTray::Create());
1018 void BrowserProcessImpl::CreatePrintPreviewDialogController() {
1019 #if defined(ENABLE_FULL_PRINTING)
1020 DCHECK(print_preview_dialog_controller_
.get() == NULL
);
1021 print_preview_dialog_controller_
=
1022 new printing::PrintPreviewDialogController();
1028 void BrowserProcessImpl::CreateBackgroundPrintingManager() {
1029 #if defined(ENABLE_FULL_PRINTING)
1030 DCHECK(background_printing_manager_
.get() == NULL
);
1031 background_printing_manager_
.reset(new printing::BackgroundPrintingManager());
1037 void BrowserProcessImpl::CreateSafeBrowsingService() {
1038 DCHECK(safe_browsing_service_
.get() == NULL
);
1039 // Set this flag to true so that we don't retry indefinitely to
1040 // create the service class if there was an error.
1041 created_safe_browsing_service_
= true;
1042 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
1043 safe_browsing_service_
= SafeBrowsingService::CreateSafeBrowsingService();
1044 safe_browsing_service_
->Initialize();
1048 void BrowserProcessImpl::ApplyDefaultBrowserPolicy() {
1049 if (local_state()->GetBoolean(prefs::kDefaultBrowserSettingEnabled
)) {
1050 scoped_refptr
<ShellIntegration::DefaultWebClientWorker
>
1051 set_browser_worker
= new ShellIntegration::DefaultBrowserWorker(NULL
);
1052 set_browser_worker
->StartSetAsDefault();
1056 void BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy() {
1057 bool value
= local_state()->GetBoolean(prefs::kAllowCrossOriginAuthPrompt
);
1058 ResourceDispatcherHost::Get()->SetAllowCrossOriginAuthPrompt(value
);
1061 void BrowserProcessImpl::ApplyMetricsReportingPolicy() {
1062 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1063 CHECK(BrowserThread::PostTask(
1064 BrowserThread::FILE, FROM_HERE
,
1066 base::IgnoreResult(&GoogleUpdateSettings::SetCollectStatsConsent
),
1067 local_state()->GetBoolean(prefs::kMetricsReportingEnabled
))));
1071 // Mac is currently not supported.
1072 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
1074 bool BrowserProcessImpl::CanAutorestartForUpdate() const {
1075 // Check if browser is in the background and if it needs to be restarted to
1076 // apply a pending update.
1077 return chrome::GetTotalBrowserCount() == 0 && chrome::WillKeepAlive() &&
1078 upgrade_util::IsUpdatePendingRestart();
1081 // Switches to add when auto-restarting Chrome.
1082 const char* const kSwitchesToAddOnAutorestart
[] = {
1083 switches::kNoStartupWindow
1086 void BrowserProcessImpl::RestartBackgroundInstance() {
1087 CommandLine
* old_cl
= CommandLine::ForCurrentProcess();
1088 scoped_ptr
<CommandLine
> new_cl(new CommandLine(old_cl
->GetProgram()));
1090 std::map
<std::string
, CommandLine::StringType
> switches
=
1091 old_cl
->GetSwitches();
1093 switches::RemoveSwitchesForAutostart(&switches
);
1095 // Append the rest of the switches (along with their values, if any)
1096 // to the new command line
1097 for (std::map
<std::string
, CommandLine::StringType
>::const_iterator i
=
1098 switches
.begin(); i
!= switches
.end(); ++i
) {
1099 CommandLine::StringType switch_value
= i
->second
;
1100 if (switch_value
.length() > 0) {
1101 new_cl
->AppendSwitchNative(i
->first
, i
->second
);
1103 new_cl
->AppendSwitch(i
->first
);
1107 // Ensure that our desired switches are set on the new process.
1108 for (size_t i
= 0; i
< arraysize(kSwitchesToAddOnAutorestart
); ++i
) {
1109 if (!new_cl
->HasSwitch(kSwitchesToAddOnAutorestart
[i
]))
1110 new_cl
->AppendSwitch(kSwitchesToAddOnAutorestart
[i
]);
1113 DLOG(WARNING
) << "Shutting down current instance of the browser.";
1114 chrome::AttemptExit();
1116 // Transfer ownership to Upgrade.
1117 upgrade_util::SetNewCommandLine(new_cl
.release());
1120 void BrowserProcessImpl::OnAutoupdateTimer() {
1121 if (CanAutorestartForUpdate()) {
1122 DLOG(WARNING
) << "Detected update. Restarting browser.";
1123 RestartBackgroundInstance();
1127 #endif // (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)