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/background/background_mode_manager.h"
25 #include "chrome/browser/chrome_browser_main.h"
26 #include "chrome/browser/chrome_content_browser_client.h"
27 #include "chrome/browser/chrome_notification_types.h"
28 #include "chrome/browser/component_updater/component_updater_configurator.h"
29 #include "chrome/browser/component_updater/component_updater_service.h"
30 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.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/extensions/chrome_extensions_browser_client.h"
36 #include "chrome/browser/extensions/event_router_forwarder.h"
37 #include "chrome/browser/extensions/extension_renderer_state.h"
38 #include "chrome/browser/first_run/upgrade_util.h"
39 #include "chrome/browser/gpu/gl_string_manager.h"
40 #include "chrome/browser/gpu/gpu_mode_manager.h"
41 #include "chrome/browser/icon_manager.h"
42 #include "chrome/browser/idle.h"
43 #include "chrome/browser/intranet_redirect_detector.h"
44 #include "chrome/browser/io_thread.h"
45 #include "chrome/browser/lifetime/application_lifetime.h"
46 #include "chrome/browser/metrics/metrics_service.h"
47 #include "chrome/browser/metrics/thread_watcher.h"
48 #include "chrome/browser/metrics/variations/variations_service.h"
49 #include "chrome/browser/net/chrome_net_log.h"
50 #include "chrome/browser/net/crl_set_fetcher.h"
51 #include "chrome/browser/net/sdch_dictionary_fetcher.h"
52 #include "chrome/browser/notifications/notification_ui_manager.h"
53 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
54 #include "chrome/browser/plugins/plugin_finder.h"
55 #include "chrome/browser/prefs/browser_prefs.h"
56 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
57 #include "chrome/browser/prerender/prerender_tracker.h"
58 #include "chrome/browser/printing/background_printing_manager.h"
59 #include "chrome/browser/printing/print_job_manager.h"
60 #include "chrome/browser/printing/print_preview_dialog_controller.h"
61 #include "chrome/browser/profiles/profile_manager.h"
62 #include "chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h"
63 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
64 #include "chrome/browser/shell_integration.h"
65 #include "chrome/browser/status_icons/status_tray.h"
66 #include "chrome/browser/ui/browser_dialogs.h"
67 #include "chrome/browser/ui/browser_finder.h"
68 #include "chrome/browser/web_resource/promo_resource_service.h"
69 #include "chrome/common/chrome_constants.h"
70 #include "chrome/common/chrome_paths.h"
71 #include "chrome/common/chrome_switches.h"
72 #include "chrome/common/extensions/chrome_extensions_client.h"
73 #include "chrome/common/pref_names.h"
74 #include "chrome/common/switch_utils.h"
75 #include "chrome/common/url_constants.h"
76 #include "chrome/installer/util/google_update_constants.h"
77 #include "components/policy/core/common/policy_service.h"
78 #include "components/rappor/rappor_service.h"
79 #include "components/signin/core/common/profile_management_switches.h"
80 #include "components/translate/core/browser/translate_download_manager.h"
81 #include "content/public/browser/browser_thread.h"
82 #include "content/public/browser/child_process_security_policy.h"
83 #include "content/public/browser/notification_details.h"
84 #include "content/public/browser/plugin_service.h"
85 #include "content/public/browser/render_process_host.h"
86 #include "content/public/browser/resource_dispatcher_host.h"
87 #include "extensions/common/constants.h"
88 #include "extensions/common/extension_l10n_util.h"
89 #include "net/socket/client_socket_pool_manager.h"
90 #include "net/url_request/url_request_context_getter.h"
91 #include "ui/base/l10n/l10n_util.h"
92 #include "ui/message_center/message_center.h"
94 #if defined(ENABLE_CONFIGURATION_POLICY)
95 #include "components/policy/core/browser/browser_policy_connector.h"
97 #include "components/policy/core/common/policy_service_stub.h"
98 #endif // defined(ENABLE_CONFIGURATION_POLICY)
101 #include "base/win/windows_version.h"
102 #include "ui/views/focus/view_storage.h"
103 #elif defined(OS_MACOSX)
104 #include "chrome/browser/chrome_browser_main_mac.h"
107 #if defined(USE_AURA)
108 #include "ui/aura/env.h"
111 #if !defined(OS_ANDROID) && !defined(OS_IOS)
112 #include "chrome/browser/media_galleries/media_file_system_registry.h"
113 #include "components/storage_monitor/storage_monitor.h"
116 #if defined(ENABLE_PLUGIN_INSTALLATION)
117 #include "chrome/browser/plugins/plugins_resource_service.h"
120 #if defined(ENABLE_WEBRTC)
121 #include "chrome/browser/media/webrtc_log_uploader.h"
124 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
125 // How often to check if the persistent instance of Chrome needs to restart
126 // to install an update.
127 static const int kUpdateCheckIntervalHours
= 6;
130 #if defined(USE_X11) || defined(OS_WIN)
131 // How long to wait for the File thread to complete during EndSession, on Linux
132 // and Windows. We have a timeout here because we're unable to run the UI
133 // messageloop and there's some deadlock risk. Our only option is to exit
135 static const int kEndSessionTimeoutSeconds
= 10;
138 using content::BrowserThread
;
139 using content::ChildProcessSecurityPolicy
;
140 using content::PluginService
;
141 using content::ResourceDispatcherHost
;
143 BrowserProcessImpl::BrowserProcessImpl(
144 base::SequencedTaskRunner
* local_state_task_runner
,
145 const CommandLine
& command_line
)
146 : created_metrics_service_(false),
147 created_watchdog_thread_(false),
148 created_browser_policy_connector_(false),
149 created_profile_manager_(false),
150 created_local_state_(false),
151 created_icon_manager_(false),
152 created_notification_ui_manager_(false),
153 created_safe_browsing_service_(false),
154 module_ref_count_(0),
156 download_status_updater_(new DownloadStatusUpdater
),
157 local_state_task_runner_(local_state_task_runner
) {
158 g_browser_process
= this;
159 platform_part_
.reset(new BrowserProcessPlatformPart());
161 #if defined(ENABLE_PRINTING)
162 // Must be created after the NotificationService.
163 print_job_manager_
.reset(new printing::PrintJobManager
);
166 net_log_
.reset(new ChromeNetLog
);
168 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
169 extensions::kExtensionScheme
);
170 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
171 extensions::kExtensionResourceScheme
);
172 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
173 chrome::kChromeSearchScheme
);
175 #if defined(OS_MACOSX)
179 apps::AppsClient::Set(ChromeAppsClient::GetInstance());
180 extensions::ExtensionsClient::Set(
181 extensions::ChromeExtensionsClient::GetInstance());
183 extensions_browser_client_
.reset(
184 new extensions::ChromeExtensionsBrowserClient
);
185 extensions::ExtensionsBrowserClient::Set(extensions_browser_client_
.get());
187 extension_event_router_forwarder_
= new extensions::EventRouterForwarder
;
188 ExtensionRendererState::GetInstance()->Init();
190 message_center::MessageCenter::Initialize();
193 BrowserProcessImpl::~BrowserProcessImpl() {
194 tracked_objects::ThreadData::EnsureCleanupWasCalled(4);
196 g_browser_process
= NULL
;
199 void BrowserProcessImpl::StartTearDown() {
200 TRACE_EVENT0("shutdown", "BrowserProcessImpl::StartTearDown");
201 // We need to shutdown the SdchDictionaryFetcher as it regularly holds
202 // a pointer to a URLFetcher, and that URLFetcher (upon destruction) will do
203 // a PostDelayedTask onto the IO thread. This shutdown call will both discard
204 // any pending URLFetchers, and avoid creating any more.
205 BrowserThread::PostTask(BrowserThread::IO
, FROM_HERE
,
206 base::Bind(&SdchDictionaryFetcher::Shutdown
));
208 // We need to destroy the MetricsService, RapporService, VariationsService,
209 // IntranetRedirectDetector, PromoResourceService, and SafeBrowsing
210 // ClientSideDetectionService (owned by the SafeBrowsingService) before the
211 // io_thread_ gets destroyed, since their destructors can call the URLFetcher
212 // destructor, which does a PostDelayedTask operation on the IO thread. (The
213 // IO thread will handle that URLFetcher operation before going away.)
214 metrics_service_
.reset();
215 rappor_service_
.reset();
216 variations_service_
.reset();
217 intranet_redirect_detector_
.reset();
218 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
219 if (safe_browsing_service_
.get())
220 safe_browsing_service()->ShutDown();
223 // Need to clear the desktop notification balloons before the io_thread_ and
224 // before the profiles, since if there are any still showing we will access
225 // those things during teardown.
226 notification_ui_manager_
.reset();
228 // Need to clear profiles (download managers) before the io_thread_.
230 TRACE_EVENT0("shutdown",
231 "BrowserProcessImpl::StartTearDown:ProfileManager");
232 // The desktop User Manager needs to be closed before the guest profile
234 if (switches::IsNewProfileManagement())
235 chrome::HideUserManager();
236 profile_manager_
.reset();
239 #if !defined(OS_ANDROID)
240 // Debugger must be cleaned up before IO thread and NotificationService.
241 remote_debugging_server_
.reset();
244 ExtensionRendererState::GetInstance()->Shutdown();
246 #if !defined(OS_ANDROID) && !defined(OS_IOS)
247 media_file_system_registry_
.reset();
248 // Remove the global instance of the Storage Monitor now. Otherwise the
249 // FILE thread would be gone when we try to release it in the dtor and
250 // Valgrind would report a leak on almost every single browser_test.
251 // TODO(gbillock): Make this unnecessary.
252 storage_monitor::StorageMonitor::Destroy();
255 message_center::MessageCenter::Shutdown();
257 #if defined(ENABLE_CONFIGURATION_POLICY)
258 // The policy providers managed by |browser_policy_connector_| need to shut
259 // down while the IO and FILE threads are still alive.
260 if (browser_policy_connector_
)
261 browser_policy_connector_
->Shutdown();
264 // Stop the watchdog thread before stopping other threads.
265 watchdog_thread_
.reset();
267 #if defined(USE_AURA)
268 // Delete aura after the metrics service has been deleted as it accesses
269 // monitor information.
270 aura::Env::DeleteInstance();
273 platform_part()->StartTearDown();
275 #if defined(ENABLE_WEBRTC)
276 // Cancel any uploads to release the system url request context references.
277 if (webrtc_log_uploader_
)
278 webrtc_log_uploader_
->StartShutdown();
282 local_state()->CommitPendingWrite();
285 void BrowserProcessImpl::PostDestroyThreads() {
286 // With the file_thread_ flushed, we can release any icon resources.
287 icon_manager_
.reset();
289 #if defined(ENABLE_WEBRTC)
290 // Must outlive the file thread.
291 webrtc_log_uploader_
.reset();
294 // Reset associated state right after actual thread is stopped,
295 // as io_thread_.global_ cleanup happens in CleanUp on the IO
296 // thread, i.e. as the thread exits its message loop.
298 // This is important also because in various places, the
299 // IOThread object being NULL is considered synonymous with the
300 // IO thread having stopped.
304 #if defined(USE_X11) || defined(OS_WIN)
305 static void Signal(base::WaitableEvent
* event
) {
310 unsigned int BrowserProcessImpl::AddRefModule() {
311 DCHECK(CalledOnValidThread());
313 // CHECK(!IsShuttingDown());
314 if (IsShuttingDown()) {
315 // Copy the stacktrace which released the final reference onto our stack so
316 // it will be available in the crash report for inspection.
317 base::debug::StackTrace callstack
= release_last_reference_callstack_
;
318 base::debug::Alias(&callstack
);
324 return module_ref_count_
;
327 unsigned int BrowserProcessImpl::ReleaseModule() {
328 DCHECK(CalledOnValidThread());
329 DCHECK_NE(0u, module_ref_count_
);
331 if (0 == module_ref_count_
) {
332 release_last_reference_callstack_
= base::debug::StackTrace();
334 #if defined(ENABLE_PRINTING)
335 // Wait for the pending print jobs to finish. Don't do this later, since
336 // this might cause a nested message loop to run, and we don't want pending
337 // tasks to run once teardown has started.
338 print_job_manager_
->Shutdown();
341 #if defined(LEAK_SANITIZER)
342 // Check for memory leaks now, before we start shutting down threads. Doing
343 // this early means we won't report any shutdown-only leaks (as they have
344 // not yet happened at this point).
345 // If leaks are found, this will make the process exit immediately.
346 __lsan_do_leak_check();
349 CHECK(base::MessageLoop::current()->is_running());
351 #if defined(OS_MACOSX)
352 base::MessageLoop::current()->PostTask(
354 base::Bind(ChromeBrowserMainPartsMac::DidEndMainMessageLoop
));
356 base::MessageLoop::current()->Quit();
358 return module_ref_count_
;
361 void BrowserProcessImpl::EndSession() {
362 // Mark all the profiles as clean.
363 ProfileManager
* pm
= profile_manager();
364 std::vector
<Profile
*> profiles(pm
->GetLoadedProfiles());
365 for (size_t i
= 0; i
< profiles
.size(); ++i
)
366 profiles
[i
]->SetExitType(Profile::EXIT_SESSION_ENDED
);
368 // Tell the metrics service it was cleanly shutdown.
369 MetricsService
* metrics
= g_browser_process
->metrics_service();
370 if (metrics
&& local_state()) {
371 metrics
->RecordStartOfSessionEnd();
372 #if !defined(OS_CHROMEOS)
373 // MetricsService lazily writes to prefs, force it to write now.
374 // On ChromeOS, chrome gets killed when hangs, so no need to
375 // commit prefs::kStabilitySessionEndCompleted change immediately.
376 local_state()->CommitPendingWrite();
380 // http://crbug.com/125207
381 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
383 // We must write that the profile and metrics service shutdown cleanly,
384 // otherwise on startup we'll think we crashed. So we block until done and
385 // then proceed with normal shutdown.
386 #if defined(USE_X11) || defined(OS_WIN)
387 // Create a waitable event to block on file writing being complete.
389 // On Windows, we previously posted a message to FILE and then ran a nested
390 // message loop, waiting for that message to be processed until quitting.
391 // However, doing so means that other messages will also be processed. In
392 // particular, if the GPU process host notices that the GPU has been killed
393 // during shutdown, it races exiting the nested loop with the process host
394 // blocking the message loop attempting to re-establish a connection to the
395 // GPU process synchronously. Because the system may not be allowing
396 // processes to launch, this can result in a hang. See
397 // http://crbug.com/318527.
398 scoped_ptr
<base::WaitableEvent
> done_writing(
399 new base::WaitableEvent(false, false));
400 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
,
401 base::Bind(Signal
, done_writing
.get()));
402 // If all file writes haven't cleared in the timeout, leak the WaitableEvent
403 // so that there's no race to reference it in Signal().
404 if (!done_writing
->TimedWait(
405 base::TimeDelta::FromSeconds(kEndSessionTimeoutSeconds
))) {
406 ignore_result(done_writing
.release());
413 MetricsService
* BrowserProcessImpl::metrics_service() {
414 DCHECK(CalledOnValidThread());
415 if (!created_metrics_service_
)
416 CreateMetricsService();
417 return metrics_service_
.get();
420 rappor::RapporService
* BrowserProcessImpl::rappor_service() {
421 DCHECK(CalledOnValidThread());
422 if (!rappor_service_
.get())
423 rappor_service_
.reset(new rappor::RapporService());
424 return rappor_service_
.get();
427 IOThread
* BrowserProcessImpl::io_thread() {
428 DCHECK(CalledOnValidThread());
429 DCHECK(io_thread_
.get());
430 return io_thread_
.get();
433 WatchDogThread
* BrowserProcessImpl::watchdog_thread() {
434 DCHECK(CalledOnValidThread());
435 if (!created_watchdog_thread_
)
436 CreateWatchdogThread();
437 DCHECK(watchdog_thread_
.get() != NULL
);
438 return watchdog_thread_
.get();
441 ProfileManager
* BrowserProcessImpl::profile_manager() {
442 DCHECK(CalledOnValidThread());
443 if (!created_profile_manager_
)
444 CreateProfileManager();
445 return profile_manager_
.get();
448 PrefService
* BrowserProcessImpl::local_state() {
449 DCHECK(CalledOnValidThread());
450 if (!created_local_state_
)
452 return local_state_
.get();
455 net::URLRequestContextGetter
* BrowserProcessImpl::system_request_context() {
456 DCHECK(CalledOnValidThread());
457 return io_thread()->system_url_request_context_getter();
460 chrome_variations::VariationsService
* BrowserProcessImpl::variations_service() {
461 DCHECK(CalledOnValidThread());
462 if (!variations_service_
.get()) {
463 variations_service_
.reset(
464 chrome_variations::VariationsService::Create(local_state()));
466 return variations_service_
.get();
469 BrowserProcessPlatformPart
* BrowserProcessImpl::platform_part() {
470 return platform_part_
.get();
473 extensions::EventRouterForwarder
*
474 BrowserProcessImpl::extension_event_router_forwarder() {
475 return extension_event_router_forwarder_
.get();
478 NotificationUIManager
* BrowserProcessImpl::notification_ui_manager() {
479 DCHECK(CalledOnValidThread());
480 if (!created_notification_ui_manager_
)
481 CreateNotificationUIManager();
482 return notification_ui_manager_
.get();
485 message_center::MessageCenter
* BrowserProcessImpl::message_center() {
486 DCHECK(CalledOnValidThread());
487 return message_center::MessageCenter::Get();
490 policy::BrowserPolicyConnector
* BrowserProcessImpl::browser_policy_connector() {
491 DCHECK(CalledOnValidThread());
492 #if defined(ENABLE_CONFIGURATION_POLICY)
493 if (!created_browser_policy_connector_
) {
494 DCHECK(!browser_policy_connector_
);
495 browser_policy_connector_
= platform_part_
->CreateBrowserPolicyConnector();
496 created_browser_policy_connector_
= true;
498 return browser_policy_connector_
.get();
504 policy::PolicyService
* BrowserProcessImpl::policy_service() {
505 #if defined(ENABLE_CONFIGURATION_POLICY)
506 return browser_policy_connector()->GetPolicyService();
508 if (!policy_service_
.get())
509 policy_service_
.reset(new policy::PolicyServiceStub());
510 return policy_service_
.get();
514 IconManager
* BrowserProcessImpl::icon_manager() {
515 DCHECK(CalledOnValidThread());
516 if (!created_icon_manager_
)
518 return icon_manager_
.get();
521 GLStringManager
* BrowserProcessImpl::gl_string_manager() {
522 DCHECK(CalledOnValidThread());
523 if (!gl_string_manager_
.get())
524 gl_string_manager_
.reset(new GLStringManager());
525 return gl_string_manager_
.get();
528 GpuModeManager
* BrowserProcessImpl::gpu_mode_manager() {
529 DCHECK(CalledOnValidThread());
530 if (!gpu_mode_manager_
.get())
531 gpu_mode_manager_
.reset(new GpuModeManager());
532 return gpu_mode_manager_
.get();
535 void BrowserProcessImpl::CreateDevToolsHttpProtocolHandler(
536 chrome::HostDesktopType host_desktop_type
,
537 const std::string
& ip
,
539 DCHECK(CalledOnValidThread());
540 #if !defined(OS_ANDROID)
541 // StartupBrowserCreator::LaunchBrowser can be run multiple times when browser
542 // is started with several profiles or existing browser process is reused.
543 if (!remote_debugging_server_
.get()) {
544 remote_debugging_server_
.reset(
545 new RemoteDebuggingServer(host_desktop_type
, ip
, port
));
550 bool BrowserProcessImpl::IsShuttingDown() {
551 DCHECK(CalledOnValidThread());
552 return did_start_
&& 0 == module_ref_count_
;
555 printing::PrintJobManager
* BrowserProcessImpl::print_job_manager() {
556 DCHECK(CalledOnValidThread());
557 return print_job_manager_
.get();
560 printing::PrintPreviewDialogController
*
561 BrowserProcessImpl::print_preview_dialog_controller() {
562 #if defined(ENABLE_FULL_PRINTING)
563 DCHECK(CalledOnValidThread());
564 if (!print_preview_dialog_controller_
.get())
565 CreatePrintPreviewDialogController();
566 return print_preview_dialog_controller_
.get();
573 printing::BackgroundPrintingManager
*
574 BrowserProcessImpl::background_printing_manager() {
575 #if defined(ENABLE_FULL_PRINTING)
576 DCHECK(CalledOnValidThread());
577 if (!background_printing_manager_
.get())
578 CreateBackgroundPrintingManager();
579 return background_printing_manager_
.get();
586 IntranetRedirectDetector
* BrowserProcessImpl::intranet_redirect_detector() {
587 DCHECK(CalledOnValidThread());
588 if (!intranet_redirect_detector_
.get())
589 CreateIntranetRedirectDetector();
590 return intranet_redirect_detector_
.get();
593 const std::string
& BrowserProcessImpl::GetApplicationLocale() {
594 DCHECK(!locale_
.empty());
598 void BrowserProcessImpl::SetApplicationLocale(const std::string
& locale
) {
600 extension_l10n_util::SetProcessLocale(locale
);
601 chrome::ChromeContentBrowserClient::SetApplicationLocale(locale
);
602 TranslateDownloadManager::GetInstance()->set_application_locale(locale
);
605 DownloadStatusUpdater
* BrowserProcessImpl::download_status_updater() {
606 return download_status_updater_
.get();
609 MediaFileSystemRegistry
* BrowserProcessImpl::media_file_system_registry() {
610 #if defined(OS_ANDROID) || defined(OS_IOS)
613 if (!media_file_system_registry_
)
614 media_file_system_registry_
.reset(new MediaFileSystemRegistry());
615 return media_file_system_registry_
.get();
619 bool BrowserProcessImpl::created_local_state() const {
620 return created_local_state_
;
623 #if defined(ENABLE_WEBRTC)
624 WebRtcLogUploader
* BrowserProcessImpl::webrtc_log_uploader() {
625 if (!webrtc_log_uploader_
.get())
626 webrtc_log_uploader_
.reset(new WebRtcLogUploader());
627 return webrtc_log_uploader_
.get();
632 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple
* registry
) {
633 registry
->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled
,
635 // This policy needs to be defined before the net subsystem is initialized,
637 registry
->RegisterIntegerPref(prefs::kMaxConnectionsPerProxy
,
638 net::kDefaultMaxSocketsPerProxyServer
);
640 registry
->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt
, false);
642 #if defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
643 registry
->RegisterBooleanPref(prefs::kEulaAccepted
, false);
644 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
646 if (base::win::GetVersion() >= base::win::VERSION_WIN8
) {
647 registry
->RegisterStringPref(prefs::kRelaunchMode
,
648 upgrade_util::kRelaunchModeDefault
);
652 // TODO(brettw,*): this comment about ResourceBundle was here since
653 // initial commit. This comment seems unrelated, bit-rotten and
654 // a candidate for removal.
655 // Initialize ResourceBundle which handles files loaded from external
656 // sources. This has to be done before uninstall code path and before prefs
658 registry
->RegisterStringPref(prefs::kApplicationLocale
, std::string());
659 #if defined(OS_CHROMEOS)
660 registry
->RegisterStringPref(prefs::kOwnerLocale
, std::string());
661 registry
->RegisterStringPref(prefs::kHardwareKeyboardLayout
,
663 #endif // defined(OS_CHROMEOS)
664 #if !defined(OS_CHROMEOS)
665 registry
->RegisterBooleanPref(
666 prefs::kMetricsReportingEnabled
,
667 GoogleUpdateSettings::GetCollectStatsConsent());
668 #endif // !defined(OS_CHROMEOS)
670 #if defined(OS_ANDROID)
671 registry
->RegisterBooleanPref(
672 prefs::kCrashReportingEnabled
, false);
673 #endif // defined(OS_ANDROID)
676 DownloadRequestLimiter
* BrowserProcessImpl::download_request_limiter() {
677 DCHECK(CalledOnValidThread());
678 if (!download_request_limiter_
.get())
679 download_request_limiter_
= new DownloadRequestLimiter();
680 return download_request_limiter_
.get();
683 BackgroundModeManager
* BrowserProcessImpl::background_mode_manager() {
684 DCHECK(CalledOnValidThread());
685 #if defined(ENABLE_BACKGROUND)
686 if (!background_mode_manager_
.get())
687 CreateBackgroundModeManager();
688 return background_mode_manager_
.get();
695 void BrowserProcessImpl::set_background_mode_manager_for_test(
696 scoped_ptr
<BackgroundModeManager
> manager
) {
697 background_mode_manager_
= manager
.Pass();
700 StatusTray
* BrowserProcessImpl::status_tray() {
701 DCHECK(CalledOnValidThread());
702 if (!status_tray_
.get())
704 return status_tray_
.get();
708 SafeBrowsingService
* BrowserProcessImpl::safe_browsing_service() {
709 DCHECK(CalledOnValidThread());
710 if (!created_safe_browsing_service_
)
711 CreateSafeBrowsingService();
712 return safe_browsing_service_
.get();
715 safe_browsing::ClientSideDetectionService
*
716 BrowserProcessImpl::safe_browsing_detection_service() {
717 DCHECK(CalledOnValidThread());
718 if (safe_browsing_service())
719 return safe_browsing_service()->safe_browsing_detection_service();
723 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
724 void BrowserProcessImpl::StartAutoupdateTimer() {
725 autoupdate_timer_
.Start(FROM_HERE
,
726 base::TimeDelta::FromHours(kUpdateCheckIntervalHours
),
728 &BrowserProcessImpl::OnAutoupdateTimer
);
732 ChromeNetLog
* BrowserProcessImpl::net_log() {
733 return net_log_
.get();
736 prerender::PrerenderTracker
* BrowserProcessImpl::prerender_tracker() {
737 if (!prerender_tracker_
.get())
738 prerender_tracker_
.reset(new prerender::PrerenderTracker
);
740 return prerender_tracker_
.get();
743 component_updater::ComponentUpdateService
*
744 BrowserProcessImpl::component_updater() {
745 if (!component_updater_
.get()) {
746 if (!BrowserThread::CurrentlyOn(BrowserThread::UI
))
748 component_updater::ComponentUpdateService::Configurator
* configurator
=
749 component_updater::MakeChromeComponentUpdaterConfigurator(
750 CommandLine::ForCurrentProcess(),
751 io_thread()->system_url_request_context_getter());
752 // Creating the component updater does not do anything, components
753 // need to be registered and Start() needs to be called.
754 component_updater_
.reset(ComponentUpdateServiceFactory(configurator
));
756 return component_updater_
.get();
759 CRLSetFetcher
* BrowserProcessImpl::crl_set_fetcher() {
760 if (!crl_set_fetcher_
.get())
761 crl_set_fetcher_
= new CRLSetFetcher();
762 return crl_set_fetcher_
.get();
765 component_updater::PnaclComponentInstaller
*
766 BrowserProcessImpl::pnacl_component_installer() {
767 if (!pnacl_component_installer_
.get()) {
768 pnacl_component_installer_
.reset(
769 new component_updater::PnaclComponentInstaller());
771 return pnacl_component_installer_
.get();
774 void BrowserProcessImpl::ResourceDispatcherHostCreated() {
775 resource_dispatcher_host_delegate_
.reset(
776 new ChromeResourceDispatcherHostDelegate(prerender_tracker()));
777 ResourceDispatcherHost::Get()->SetDelegate(
778 resource_dispatcher_host_delegate_
.get());
780 pref_change_registrar_
.Add(
781 prefs::kAllowCrossOriginAuthPrompt
,
782 base::Bind(&BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy
,
783 base::Unretained(this)));
784 ApplyAllowCrossOriginAuthPromptPolicy();
787 void BrowserProcessImpl::CreateMetricsService() {
788 DCHECK(!created_metrics_service_
&& metrics_service_
.get() == NULL
);
789 created_metrics_service_
= true;
791 metrics_service_
.reset(new MetricsService
);
794 void BrowserProcessImpl::CreateWatchdogThread() {
795 DCHECK(!created_watchdog_thread_
&& watchdog_thread_
.get() == NULL
);
796 created_watchdog_thread_
= true;
798 scoped_ptr
<WatchDogThread
> thread(new WatchDogThread());
799 if (!thread
->Start())
801 watchdog_thread_
.swap(thread
);
804 void BrowserProcessImpl::CreateProfileManager() {
805 DCHECK(!created_profile_manager_
&& profile_manager_
.get() == NULL
);
806 created_profile_manager_
= true;
808 base::FilePath user_data_dir
;
809 PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
);
810 profile_manager_
.reset(new ProfileManager(user_data_dir
));
813 void BrowserProcessImpl::CreateLocalState() {
814 DCHECK(!created_local_state_
&& local_state_
.get() == NULL
);
815 created_local_state_
= true;
817 base::FilePath local_state_path
;
818 CHECK(PathService::Get(chrome::FILE_LOCAL_STATE
, &local_state_path
));
819 scoped_refptr
<PrefRegistrySimple
> pref_registry
= new PrefRegistrySimple
;
821 // Register local state preferences.
822 chrome::RegisterLocalState(pref_registry
.get());
825 chrome_prefs::CreateLocalState(local_state_path
,
826 local_state_task_runner_
.get(),
831 pref_change_registrar_
.Init(local_state_
.get());
833 // Initialize the notification for the default browser setting policy.
834 pref_change_registrar_
.Add(
835 prefs::kDefaultBrowserSettingEnabled
,
836 base::Bind(&BrowserProcessImpl::ApplyDefaultBrowserPolicy
,
837 base::Unretained(this)));
839 // This preference must be kept in sync with external values; update them
840 // whenever the preference or its controlling policy changes.
841 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
842 pref_change_registrar_
.Add(
843 prefs::kMetricsReportingEnabled
,
844 base::Bind(&BrowserProcessImpl::ApplyMetricsReportingPolicy
,
845 base::Unretained(this)));
848 int max_per_proxy
= local_state_
->GetInteger(prefs::kMaxConnectionsPerProxy
);
849 net::ClientSocketPoolManager::set_max_sockets_per_proxy_server(
850 net::HttpNetworkSession::NORMAL_SOCKET_POOL
,
851 std::max(std::min(max_per_proxy
, 99),
852 net::ClientSocketPoolManager::max_sockets_per_group(
853 net::HttpNetworkSession::NORMAL_SOCKET_POOL
)));
856 void BrowserProcessImpl::PreCreateThreads() {
857 io_thread_
.reset(new IOThread(local_state(), policy_service(), net_log_
.get(),
858 extension_event_router_forwarder_
.get()));
861 void BrowserProcessImpl::PreMainMessageLoopRun() {
862 #if defined(ENABLE_CONFIGURATION_POLICY)
863 // browser_policy_connector() is created very early because local_state()
864 // needs policy to be initialized with the managed preference values.
865 // However, policy fetches from the network and loading of disk caches
866 // requires that threads are running; this Init() call lets the connector
867 // resume its initialization now that the loops are spinning and the
868 // system request context is available for the fetchers.
869 browser_policy_connector()->Init(local_state(), system_request_context());
872 if (local_state_
->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled
))
873 ApplyDefaultBrowserPolicy();
875 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
876 ApplyMetricsReportingPolicy();
879 #if defined(ENABLE_PLUGINS)
880 PluginService
* plugin_service
= PluginService::GetInstance();
881 plugin_service
->SetFilter(ChromePluginServiceFilter::GetInstance());
882 plugin_service
->StartWatchingPlugins();
884 #if defined(OS_POSIX)
885 // Also find plugins in a user-specific plugins dir,
886 // e.g. ~/.config/chromium/Plugins.
887 const CommandLine
& cmd_line
= *CommandLine::ForCurrentProcess();
888 if (!cmd_line
.HasSwitch(switches::kDisablePluginsDiscovery
)) {
889 base::FilePath user_data_dir
;
890 if (PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
))
891 plugin_service
->AddExtraPluginDir(user_data_dir
.Append("Plugins"));
895 // Triggers initialization of the singleton instance on UI thread.
896 PluginFinder::GetInstance()->Init();
898 #if defined(ENABLE_PLUGIN_INSTALLATION)
899 DCHECK(!plugins_resource_service_
.get());
900 plugins_resource_service_
= new PluginsResourceService(local_state());
901 plugins_resource_service_
->Init();
903 #endif // defined(ENABLE_PLUGINS)
905 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
906 if (!command_line
.HasSwitch(switches::kDisableWebResources
)) {
907 DCHECK(!promo_resource_service_
.get());
908 promo_resource_service_
= new PromoResourceService
;
909 promo_resource_service_
->StartAfterDelay();
912 #if !defined(OS_ANDROID) && !defined(OS_IOS)
913 storage_monitor::StorageMonitor::Create();
916 platform_part_
->PreMainMessageLoopRun();
919 void BrowserProcessImpl::CreateIconManager() {
920 DCHECK(!created_icon_manager_
&& icon_manager_
.get() == NULL
);
921 created_icon_manager_
= true;
922 icon_manager_
.reset(new IconManager
);
925 void BrowserProcessImpl::CreateIntranetRedirectDetector() {
926 DCHECK(intranet_redirect_detector_
.get() == NULL
);
927 scoped_ptr
<IntranetRedirectDetector
> intranet_redirect_detector(
928 new IntranetRedirectDetector
);
929 intranet_redirect_detector_
.swap(intranet_redirect_detector
);
932 void BrowserProcessImpl::CreateNotificationUIManager() {
933 #if defined(ENABLE_NOTIFICATIONS)
934 DCHECK(notification_ui_manager_
.get() == NULL
);
935 notification_ui_manager_
.reset(NotificationUIManager::Create(local_state()));
936 created_notification_ui_manager_
= true;
940 void BrowserProcessImpl::CreateBackgroundModeManager() {
941 DCHECK(background_mode_manager_
.get() == NULL
);
942 background_mode_manager_
.reset(
943 new BackgroundModeManager(CommandLine::ForCurrentProcess(),
944 &profile_manager()->GetProfileInfoCache()));
947 void BrowserProcessImpl::CreateStatusTray() {
948 DCHECK(status_tray_
.get() == NULL
);
949 status_tray_
.reset(StatusTray::Create());
952 void BrowserProcessImpl::CreatePrintPreviewDialogController() {
953 #if defined(ENABLE_FULL_PRINTING)
954 DCHECK(print_preview_dialog_controller_
.get() == NULL
);
955 print_preview_dialog_controller_
=
956 new printing::PrintPreviewDialogController();
962 void BrowserProcessImpl::CreateBackgroundPrintingManager() {
963 #if defined(ENABLE_FULL_PRINTING)
964 DCHECK(background_printing_manager_
.get() == NULL
);
965 background_printing_manager_
.reset(new printing::BackgroundPrintingManager());
971 void BrowserProcessImpl::CreateSafeBrowsingService() {
972 DCHECK(safe_browsing_service_
.get() == NULL
);
973 // Set this flag to true so that we don't retry indefinitely to
974 // create the service class if there was an error.
975 created_safe_browsing_service_
= true;
976 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
977 safe_browsing_service_
= SafeBrowsingService::CreateSafeBrowsingService();
978 safe_browsing_service_
->Initialize();
982 void BrowserProcessImpl::ApplyDefaultBrowserPolicy() {
983 if (local_state()->GetBoolean(prefs::kDefaultBrowserSettingEnabled
)) {
984 scoped_refptr
<ShellIntegration::DefaultWebClientWorker
>
985 set_browser_worker
= new ShellIntegration::DefaultBrowserWorker(NULL
);
986 set_browser_worker
->StartSetAsDefault();
990 void BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy() {
991 bool value
= local_state()->GetBoolean(prefs::kAllowCrossOriginAuthPrompt
);
992 ResourceDispatcherHost::Get()->SetAllowCrossOriginAuthPrompt(value
);
995 void BrowserProcessImpl::ApplyMetricsReportingPolicy() {
996 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
997 CHECK(BrowserThread::PostTask(
998 BrowserThread::FILE, FROM_HERE
,
1000 base::IgnoreResult(&GoogleUpdateSettings::SetCollectStatsConsent
),
1001 local_state()->GetBoolean(prefs::kMetricsReportingEnabled
))));
1005 // Mac is currently not supported.
1006 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
1008 bool BrowserProcessImpl::CanAutorestartForUpdate() const {
1009 // Check if browser is in the background and if it needs to be restarted to
1010 // apply a pending update.
1011 return chrome::GetTotalBrowserCount() == 0 && chrome::WillKeepAlive() &&
1012 upgrade_util::IsUpdatePendingRestart();
1015 // Switches to add when auto-restarting Chrome.
1016 const char* const kSwitchesToAddOnAutorestart
[] = {
1017 switches::kNoStartupWindow
1020 void BrowserProcessImpl::RestartBackgroundInstance() {
1021 CommandLine
* old_cl
= CommandLine::ForCurrentProcess();
1022 scoped_ptr
<CommandLine
> new_cl(new CommandLine(old_cl
->GetProgram()));
1024 std::map
<std::string
, CommandLine::StringType
> switches
=
1025 old_cl
->GetSwitches();
1027 switches::RemoveSwitchesForAutostart(&switches
);
1029 // Append the rest of the switches (along with their values, if any)
1030 // to the new command line
1031 for (std::map
<std::string
, CommandLine::StringType
>::const_iterator i
=
1032 switches
.begin(); i
!= switches
.end(); ++i
) {
1033 CommandLine::StringType switch_value
= i
->second
;
1034 if (switch_value
.length() > 0) {
1035 new_cl
->AppendSwitchNative(i
->first
, i
->second
);
1037 new_cl
->AppendSwitch(i
->first
);
1041 // Ensure that our desired switches are set on the new process.
1042 for (size_t i
= 0; i
< arraysize(kSwitchesToAddOnAutorestart
); ++i
) {
1043 if (!new_cl
->HasSwitch(kSwitchesToAddOnAutorestart
[i
]))
1044 new_cl
->AppendSwitch(kSwitchesToAddOnAutorestart
[i
]);
1047 DLOG(WARNING
) << "Shutting down current instance of the browser.";
1048 chrome::AttemptExit();
1050 // Transfer ownership to Upgrade.
1051 upgrade_util::SetNewCommandLine(new_cl
.release());
1054 void BrowserProcessImpl::OnAutoupdateTimer() {
1055 if (CanAutorestartForUpdate()) {
1056 DLOG(WARNING
) << "Detected update. Restarting browser.";
1057 RestartBackgroundInstance();
1061 #endif // (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)