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_query_params/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/apps/chrome_app_window_client.h"
63 #include "chrome/browser/ui/browser_dialogs.h"
64 #include "chrome/browser/ui/browser_finder.h"
65 #include "chrome/browser/ui/user_manager.h"
66 #include "chrome/browser/web_resource/promo_resource_service.h"
67 #include "chrome/common/chrome_constants.h"
68 #include "chrome/common/chrome_paths.h"
69 #include "chrome/common/chrome_switches.h"
70 #include "chrome/common/extensions/chrome_extensions_client.h"
71 #include "chrome/common/pref_names.h"
72 #include "chrome/common/switch_utils.h"
73 #include "chrome/common/url_constants.h"
74 #include "chrome/installer/util/google_update_constants.h"
75 #include "chrome/installer/util/google_update_settings.h"
76 #include "components/component_updater/component_updater_service.h"
77 #include "components/gcm_driver/gcm_driver.h"
78 #include "components/metrics/metrics_service.h"
79 #include "components/network_time/network_time_tracker.h"
80 #include "components/omaha_query_params/omaha_query_params.h"
81 #include "components/policy/core/common/policy_service.h"
82 #include "components/signin/core/common/profile_management_switches.h"
83 #include "components/translate/core/browser/translate_download_manager.h"
84 #include "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 "components/gcm_driver/gcm_driver_android.h"
108 #include "chrome/browser/chrome_device_client.h"
109 #include "chrome/browser/services/gcm/gcm_desktop_utils.h"
110 #include "components/gcm_driver/gcm_client_factory.h"
113 #if defined(USE_AURA)
114 #include "ui/aura/env.h"
117 #if defined(ENABLE_BACKGROUND)
118 #include "chrome/browser/background/background_mode_manager.h"
121 #if defined(ENABLE_CONFIGURATION_POLICY)
122 #include "components/policy/core/browser/browser_policy_connector.h"
124 #include "components/policy/core/common/policy_service_stub.h"
125 #endif // defined(ENABLE_CONFIGURATION_POLICY)
127 #if defined(ENABLE_EXTENSIONS)
128 #include "chrome/browser/extensions/chrome_extensions_browser_client.h"
129 #include "chrome/browser/extensions/event_router_forwarder.h"
130 #include "chrome/browser/extensions/extension_renderer_state.h"
131 #include "chrome/browser/media_galleries/media_file_system_registry.h"
132 #include "components/storage_monitor/storage_monitor.h"
133 #include "extensions/common/extension_l10n_util.h"
136 #if !defined(DISABLE_NACL)
137 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
140 #if defined(ENABLE_PLUGIN_INSTALLATION)
141 #include "chrome/browser/plugins/plugins_resource_service.h"
144 #if defined(ENABLE_WEBRTC)
145 #include "chrome/browser/media/webrtc_log_uploader.h"
148 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
149 // How often to check if the persistent instance of Chrome needs to restart
150 // to install an update.
151 static const int kUpdateCheckIntervalHours
= 6;
154 #if defined(USE_X11) || defined(OS_WIN)
155 // How long to wait for the File thread to complete during EndSession, on Linux
156 // and Windows. We have a timeout here because we're unable to run the UI
157 // messageloop and there's some deadlock risk. Our only option is to exit
159 static const int kEndSessionTimeoutSeconds
= 10;
162 using content::BrowserThread
;
163 using content::ChildProcessSecurityPolicy
;
164 using content::PluginService
;
165 using content::ResourceDispatcherHost
;
167 BrowserProcessImpl::BrowserProcessImpl(
168 base::SequencedTaskRunner
* local_state_task_runner
,
169 const CommandLine
& command_line
)
170 : created_watchdog_thread_(false),
171 created_browser_policy_connector_(false),
172 created_profile_manager_(false),
173 created_local_state_(false),
174 created_icon_manager_(false),
175 created_notification_ui_manager_(false),
176 created_safe_browsing_service_(false),
177 module_ref_count_(0),
179 download_status_updater_(new DownloadStatusUpdater
),
180 local_state_task_runner_(local_state_task_runner
) {
181 g_browser_process
= this;
182 platform_part_
.reset(new BrowserProcessPlatformPart());
184 #if defined(ENABLE_PRINTING)
185 // Must be created after the NotificationService.
186 print_job_manager_
.reset(new printing::PrintJobManager
);
189 net_log_
.reset(new ChromeNetLog
);
191 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
192 extensions::kExtensionScheme
);
193 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
194 extensions::kExtensionResourceScheme
);
195 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
196 chrome::kChromeSearchScheme
);
198 #if defined(OS_MACOSX)
202 #if !defined(OS_ANDROID)
203 device_client_
.reset(new ChromeDeviceClient
);
206 #if defined(ENABLE_EXTENSIONS)
207 #if !defined(USE_ATHENA)
208 // Athena sets its own instance during Athena's init process.
209 extensions::AppWindowClient::Set(ChromeAppWindowClient::GetInstance());
212 extension_event_router_forwarder_
= new extensions::EventRouterForwarder
;
213 ExtensionRendererState::GetInstance()->Init();
215 extensions::ExtensionsClient::Set(
216 extensions::ChromeExtensionsClient::GetInstance());
218 extensions_browser_client_
.reset(
219 new extensions::ChromeExtensionsBrowserClient
);
220 extensions::ExtensionsBrowserClient::Set(extensions_browser_client_
.get());
223 message_center::MessageCenter::Initialize();
225 omaha_query_params::OmahaQueryParams::SetDelegate(
226 ChromeOmahaQueryParamsDelegate::GetInstance());
229 BrowserProcessImpl::~BrowserProcessImpl() {
230 tracked_objects::ThreadData::EnsureCleanupWasCalled(4);
232 g_browser_process
= NULL
;
235 void BrowserProcessImpl::StartTearDown() {
236 TRACE_EVENT0("shutdown", "BrowserProcessImpl::StartTearDown");
237 // We need to destroy the MetricsServicesManager, IntranetRedirectDetector,
238 // PromoResourceService, and SafeBrowsing ClientSideDetectionService (owned by
239 // the SafeBrowsingService) before the io_thread_ gets destroyed, since their
240 // destructors can call the URLFetcher destructor, which does a
241 // PostDelayedTask operation on the IO thread. (The IO thread will handle that
242 // URLFetcher operation before going away.)
243 metrics_services_manager_
.reset();
244 intranet_redirect_detector_
.reset();
245 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
246 if (safe_browsing_service_
.get())
247 safe_browsing_service()->ShutDown();
250 // Need to clear the desktop notification balloons before the io_thread_ and
251 // before the profiles, since if there are any still showing we will access
252 // those things during teardown.
253 notification_ui_manager_
.reset();
255 // Need to clear profiles (download managers) before the io_thread_.
257 TRACE_EVENT0("shutdown",
258 "BrowserProcessImpl::StartTearDown:ProfileManager");
259 // The desktop User Manager needs to be closed before the guest profile
261 if (switches::IsNewAvatarMenu())
263 profile_manager_
.reset();
266 #if !defined(OS_ANDROID)
267 // Debugger must be cleaned up before IO thread and NotificationService.
268 remote_debugging_server_
.reset();
271 #if defined(ENABLE_EXTENSIONS)
272 ExtensionRendererState::GetInstance()->Shutdown();
274 media_file_system_registry_
.reset();
275 // Remove the global instance of the Storage Monitor now. Otherwise the
276 // FILE thread would be gone when we try to release it in the dtor and
277 // Valgrind would report a leak on almost every single browser_test.
278 // TODO(gbillock): Make this unnecessary.
279 storage_monitor::StorageMonitor::Destroy();
282 message_center::MessageCenter::Shutdown();
284 #if defined(ENABLE_CONFIGURATION_POLICY)
285 // The policy providers managed by |browser_policy_connector_| need to shut
286 // down while the IO and FILE threads are still alive.
287 if (browser_policy_connector_
)
288 browser_policy_connector_
->Shutdown();
291 // The |gcm_driver_| must shut down while the IO thread is still alive.
293 gcm_driver_
->Shutdown();
295 // Stop the watchdog thread before stopping other threads.
296 watchdog_thread_
.reset();
298 #if defined(USE_AURA)
299 // Delete aura after the metrics service has been deleted as it accesses
300 // monitor information.
301 aura::Env::DeleteInstance();
304 platform_part()->StartTearDown();
306 #if defined(ENABLE_WEBRTC)
307 // Cancel any uploads to release the system url request context references.
308 if (webrtc_log_uploader_
)
309 webrtc_log_uploader_
->StartShutdown();
313 local_state()->CommitPendingWrite();
316 void BrowserProcessImpl::PostDestroyThreads() {
317 // With the file_thread_ flushed, we can release any icon resources.
318 icon_manager_
.reset();
320 #if defined(ENABLE_WEBRTC)
321 // Must outlive the file thread.
322 webrtc_log_uploader_
.reset();
325 // Reset associated state right after actual thread is stopped,
326 // as io_thread_.global_ cleanup happens in CleanUp on the IO
327 // thread, i.e. as the thread exits its message loop.
329 // This is important also because in various places, the
330 // IOThread object being NULL is considered synonymous with the
331 // IO thread having stopped.
335 unsigned int BrowserProcessImpl::AddRefModule() {
336 DCHECK(CalledOnValidThread());
338 // CHECK(!IsShuttingDown());
339 if (IsShuttingDown()) {
340 // Copy the stacktrace which released the final reference onto our stack so
341 // it will be available in the crash report for inspection.
342 base::debug::StackTrace callstack
= release_last_reference_callstack_
;
343 base::debug::Alias(&callstack
);
349 return module_ref_count_
;
352 static void ShutdownServiceWorkerContext(content::StoragePartition
* partition
) {
353 partition
->GetServiceWorkerContext()->Terminate();
356 unsigned int BrowserProcessImpl::ReleaseModule() {
357 DCHECK(CalledOnValidThread());
358 DCHECK_NE(0u, module_ref_count_
);
360 if (0 == module_ref_count_
) {
361 release_last_reference_callstack_
= base::debug::StackTrace();
363 // Stop service workers
364 ProfileManager
* pm
= profile_manager();
365 std::vector
<Profile
*> profiles(pm
->GetLoadedProfiles());
366 for (size_t i
= 0; i
< profiles
.size(); ++i
) {
367 content::BrowserContext::ForEachStoragePartition(
368 profiles
[i
], base::Bind(ShutdownServiceWorkerContext
));
371 #if defined(ENABLE_PRINTING)
372 // Wait for the pending print jobs to finish. Don't do this later, since
373 // this might cause a nested message loop to run, and we don't want pending
374 // tasks to run once teardown has started.
375 print_job_manager_
->Shutdown();
378 #if defined(LEAK_SANITIZER)
379 // Check for memory leaks now, before we start shutting down threads. Doing
380 // this early means we won't report any shutdown-only leaks (as they have
381 // not yet happened at this point).
382 // If leaks are found, this will make the process exit immediately.
383 __lsan_do_leak_check();
386 CHECK(base::MessageLoop::current()->is_running());
388 #if defined(OS_MACOSX)
389 base::MessageLoop::current()->PostTask(
391 base::Bind(ChromeBrowserMainPartsMac::DidEndMainMessageLoop
));
393 base::MessageLoop::current()->Quit();
395 return module_ref_count_
;
400 // Used at the end of session to block the UI thread for completion of sentinel
401 // tasks on the set of threads used to persist profile data and local state.
402 // This is done to ensure that the data has been persisted to disk before
404 class RundownTaskCounter
:
405 public base::RefCountedThreadSafe
<RundownTaskCounter
> {
407 RundownTaskCounter();
409 // Posts a rundown task to |task_runner|, can be invoked an arbitrary number
410 // of times before calling TimedWait.
411 void Post(base::SequencedTaskRunner
* task_runner
);
413 // Waits until the count is zero or |max_time| has passed.
414 // This can only be called once per instance.
415 bool TimedWait(const base::TimeDelta
& max_time
);
418 friend class base::RefCountedThreadSafe
<RundownTaskCounter
>;
419 ~RundownTaskCounter() {}
421 // Decrements the counter and releases the waitable event on transition to
425 // The count starts at one to defer the possibility of one->zero transitions
426 // until TimedWait is called.
427 base::AtomicRefCount count_
;
428 base::WaitableEvent waitable_event_
;
430 DISALLOW_COPY_AND_ASSIGN(RundownTaskCounter
);
433 RundownTaskCounter::RundownTaskCounter()
434 : count_(1), waitable_event_(true, false) {
437 void RundownTaskCounter::Post(base::SequencedTaskRunner
* task_runner
) {
438 // As the count starts off at one, it should never get to zero unless
439 // TimedWait has been called.
440 DCHECK(!base::AtomicRefCountIsZero(&count_
));
442 base::AtomicRefCountInc(&count_
);
444 // The task must be non-nestable to guarantee that it runs after all tasks
445 // currently scheduled on |task_runner| have completed.
446 task_runner
->PostNonNestableTask(FROM_HERE
,
447 base::Bind(&RundownTaskCounter::Decrement
, this));
450 void RundownTaskCounter::Decrement() {
451 if (!base::AtomicRefCountDec(&count_
))
452 waitable_event_
.Signal();
455 bool RundownTaskCounter::TimedWait(const base::TimeDelta
& max_time
) {
456 // Decrement the excess count from the constructor.
459 return waitable_event_
.TimedWait(max_time
);
462 bool ExperimentUseBrokenSynchronization() {
463 // The logoff behavior used to have a race, whereby it would perform profile
464 // IO writes on the blocking thread pool, but would sycnhronize to the FILE
465 // thread. Windows feels free to terminate any process that's hidden or
466 // destroyed all it's windows, and sometimes Chrome would be terminated
467 // with pending profile IO due to this mis-synchronization.
468 // Under the "WindowsLogoffRace" experiment group, the broken behavior is
469 // emulated, in order to allow measuring what fraction of unclean shutdowns
470 // are due to this bug.
471 const std::string group_name
=
472 base::FieldTrialList::FindFullName("WindowsLogoffRace");
473 return group_name
== "BrokenSynchronization";
478 void BrowserProcessImpl::EndSession() {
479 bool use_broken_synchronization
= ExperimentUseBrokenSynchronization();
481 // Mark all the profiles as clean.
482 ProfileManager
* pm
= profile_manager();
483 std::vector
<Profile
*> profiles(pm
->GetLoadedProfiles());
484 scoped_refptr
<RundownTaskCounter
> rundown_counter(new RundownTaskCounter());
485 for (size_t i
= 0; i
< profiles
.size(); ++i
) {
486 Profile
* profile
= profiles
[i
];
487 profile
->SetExitType(Profile::EXIT_SESSION_ENDED
);
489 if (!use_broken_synchronization
)
490 rundown_counter
->Post(profile
->GetIOTaskRunner().get());
493 // Tell the metrics service it was cleanly shutdown.
494 metrics::MetricsService
* metrics
= g_browser_process
->metrics_service();
495 if (metrics
&& local_state()) {
496 metrics
->RecordStartOfSessionEnd();
497 #if !defined(OS_CHROMEOS)
498 // MetricsService lazily writes to prefs, force it to write now.
499 // On ChromeOS, chrome gets killed when hangs, so no need to
500 // commit metrics::prefs::kStabilitySessionEndCompleted change immediately.
501 local_state()->CommitPendingWrite();
503 if (!use_broken_synchronization
)
504 rundown_counter
->Post(local_state_task_runner_
.get());
508 // http://crbug.com/125207
509 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
511 // We must write that the profile and metrics service shutdown cleanly,
512 // otherwise on startup we'll think we crashed. So we block until done and
513 // then proceed with normal shutdown.
515 // If you change the condition here, be sure to also change
516 // ProfileBrowserTests to match.
517 #if defined(USE_X11) || defined(OS_WIN)
518 if (use_broken_synchronization
) {
519 rundown_counter
->Post(
520 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE).get());
523 // Do a best-effort wait on the successful countdown of rundown tasks. Note
524 // that if we don't complete "quickly enough", Windows will terminate our
527 // On Windows, we previously posted a message to FILE and then ran a nested
528 // message loop, waiting for that message to be processed until quitting.
529 // However, doing so means that other messages will also be processed. In
530 // particular, if the GPU process host notices that the GPU has been killed
531 // during shutdown, it races exiting the nested loop with the process host
532 // blocking the message loop attempting to re-establish a connection to the
533 // GPU process synchronously. Because the system may not be allowing
534 // processes to launch, this can result in a hang. See
535 // http://crbug.com/318527.
536 rundown_counter
->TimedWait(
537 base::TimeDelta::FromSeconds(kEndSessionTimeoutSeconds
));
543 MetricsServicesManager
* BrowserProcessImpl::GetMetricsServicesManager() {
544 DCHECK(CalledOnValidThread());
545 if (!metrics_services_manager_
)
546 metrics_services_manager_
.reset(new MetricsServicesManager(local_state()));
547 return metrics_services_manager_
.get();
550 metrics::MetricsService
* BrowserProcessImpl::metrics_service() {
551 DCHECK(CalledOnValidThread());
552 return GetMetricsServicesManager()->GetMetricsService();
555 rappor::RapporService
* BrowserProcessImpl::rappor_service() {
556 DCHECK(CalledOnValidThread());
557 return GetMetricsServicesManager()->GetRapporService();
560 IOThread
* BrowserProcessImpl::io_thread() {
561 DCHECK(CalledOnValidThread());
562 DCHECK(io_thread_
.get());
563 return io_thread_
.get();
566 WatchDogThread
* BrowserProcessImpl::watchdog_thread() {
567 DCHECK(CalledOnValidThread());
568 if (!created_watchdog_thread_
)
569 CreateWatchdogThread();
570 DCHECK(watchdog_thread_
.get() != NULL
);
571 return watchdog_thread_
.get();
574 ProfileManager
* BrowserProcessImpl::profile_manager() {
575 DCHECK(CalledOnValidThread());
576 if (!created_profile_manager_
)
577 CreateProfileManager();
578 return profile_manager_
.get();
581 PrefService
* BrowserProcessImpl::local_state() {
582 DCHECK(CalledOnValidThread());
583 if (!created_local_state_
)
585 return local_state_
.get();
588 net::URLRequestContextGetter
* BrowserProcessImpl::system_request_context() {
589 DCHECK(CalledOnValidThread());
590 return io_thread()->system_url_request_context_getter();
593 chrome_variations::VariationsService
* BrowserProcessImpl::variations_service() {
594 DCHECK(CalledOnValidThread());
595 return GetMetricsServicesManager()->GetVariationsService();
598 BrowserProcessPlatformPart
* BrowserProcessImpl::platform_part() {
599 return platform_part_
.get();
602 extensions::EventRouterForwarder
*
603 BrowserProcessImpl::extension_event_router_forwarder() {
604 #if defined(ENABLE_EXTENSIONS)
605 return extension_event_router_forwarder_
.get();
611 NotificationUIManager
* BrowserProcessImpl::notification_ui_manager() {
612 DCHECK(CalledOnValidThread());
613 if (!created_notification_ui_manager_
)
614 CreateNotificationUIManager();
615 return notification_ui_manager_
.get();
618 message_center::MessageCenter
* BrowserProcessImpl::message_center() {
619 DCHECK(CalledOnValidThread());
620 return message_center::MessageCenter::Get();
623 policy::BrowserPolicyConnector
* BrowserProcessImpl::browser_policy_connector() {
624 DCHECK(CalledOnValidThread());
625 #if defined(ENABLE_CONFIGURATION_POLICY)
626 if (!created_browser_policy_connector_
) {
627 DCHECK(!browser_policy_connector_
);
628 browser_policy_connector_
= platform_part_
->CreateBrowserPolicyConnector();
629 created_browser_policy_connector_
= true;
631 return browser_policy_connector_
.get();
637 policy::PolicyService
* BrowserProcessImpl::policy_service() {
638 #if defined(ENABLE_CONFIGURATION_POLICY)
639 return browser_policy_connector()->GetPolicyService();
641 if (!policy_service_
.get())
642 policy_service_
.reset(new policy::PolicyServiceStub());
643 return policy_service_
.get();
647 IconManager
* BrowserProcessImpl::icon_manager() {
648 DCHECK(CalledOnValidThread());
649 if (!created_icon_manager_
)
651 return icon_manager_
.get();
654 GLStringManager
* BrowserProcessImpl::gl_string_manager() {
655 DCHECK(CalledOnValidThread());
656 if (!gl_string_manager_
.get())
657 gl_string_manager_
.reset(new GLStringManager());
658 return gl_string_manager_
.get();
661 GpuModeManager
* BrowserProcessImpl::gpu_mode_manager() {
662 DCHECK(CalledOnValidThread());
663 if (!gpu_mode_manager_
.get())
664 gpu_mode_manager_
.reset(new GpuModeManager());
665 return gpu_mode_manager_
.get();
668 void BrowserProcessImpl::CreateDevToolsHttpProtocolHandler(
669 chrome::HostDesktopType host_desktop_type
,
670 const std::string
& ip
,
672 DCHECK(CalledOnValidThread());
673 #if !defined(OS_ANDROID)
674 // StartupBrowserCreator::LaunchBrowser can be run multiple times when browser
675 // is started with several profiles or existing browser process is reused.
676 if (!remote_debugging_server_
.get()) {
677 remote_debugging_server_
.reset(
678 new RemoteDebuggingServer(host_desktop_type
, ip
, port
));
683 bool BrowserProcessImpl::IsShuttingDown() {
684 DCHECK(CalledOnValidThread());
685 return did_start_
&& 0 == module_ref_count_
;
688 printing::PrintJobManager
* BrowserProcessImpl::print_job_manager() {
689 DCHECK(CalledOnValidThread());
690 return print_job_manager_
.get();
693 printing::PrintPreviewDialogController
*
694 BrowserProcessImpl::print_preview_dialog_controller() {
695 #if defined(ENABLE_FULL_PRINTING)
696 DCHECK(CalledOnValidThread());
697 if (!print_preview_dialog_controller_
.get())
698 CreatePrintPreviewDialogController();
699 return print_preview_dialog_controller_
.get();
706 printing::BackgroundPrintingManager
*
707 BrowserProcessImpl::background_printing_manager() {
708 #if defined(ENABLE_FULL_PRINTING)
709 DCHECK(CalledOnValidThread());
710 if (!background_printing_manager_
.get())
711 CreateBackgroundPrintingManager();
712 return background_printing_manager_
.get();
719 IntranetRedirectDetector
* BrowserProcessImpl::intranet_redirect_detector() {
720 DCHECK(CalledOnValidThread());
721 if (!intranet_redirect_detector_
.get())
722 CreateIntranetRedirectDetector();
723 return intranet_redirect_detector_
.get();
726 const std::string
& BrowserProcessImpl::GetApplicationLocale() {
727 DCHECK(!locale_
.empty());
731 void BrowserProcessImpl::SetApplicationLocale(const std::string
& locale
) {
733 #if defined(ENABLE_EXTENSIONS)
734 extension_l10n_util::SetProcessLocale(locale
);
736 chrome::ChromeContentBrowserClient::SetApplicationLocale(locale
);
737 translate::TranslateDownloadManager::GetInstance()->set_application_locale(
741 DownloadStatusUpdater
* BrowserProcessImpl::download_status_updater() {
742 return download_status_updater_
.get();
745 MediaFileSystemRegistry
* BrowserProcessImpl::media_file_system_registry() {
746 #if defined(ENABLE_EXTENSIONS)
747 if (!media_file_system_registry_
)
748 media_file_system_registry_
.reset(new MediaFileSystemRegistry());
749 return media_file_system_registry_
.get();
755 bool BrowserProcessImpl::created_local_state() const {
756 return created_local_state_
;
759 #if defined(ENABLE_WEBRTC)
760 WebRtcLogUploader
* BrowserProcessImpl::webrtc_log_uploader() {
761 if (!webrtc_log_uploader_
.get())
762 webrtc_log_uploader_
.reset(new WebRtcLogUploader());
763 return webrtc_log_uploader_
.get();
767 network_time::NetworkTimeTracker
* BrowserProcessImpl::network_time_tracker() {
768 if (!network_time_tracker_
) {
769 network_time_tracker_
.reset(new network_time::NetworkTimeTracker(
770 scoped_ptr
<base::TickClock
>(new base::DefaultTickClock()),
773 return network_time_tracker_
.get();
776 gcm::GCMDriver
* BrowserProcessImpl::gcm_driver() {
777 DCHECK(CalledOnValidThread());
780 return gcm_driver_
.get();
784 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple
* registry
) {
785 registry
->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled
,
787 // This policy needs to be defined before the net subsystem is initialized,
789 registry
->RegisterIntegerPref(prefs::kMaxConnectionsPerProxy
,
790 net::kDefaultMaxSocketsPerProxyServer
);
792 registry
->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt
, false);
794 #if defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
795 registry
->RegisterBooleanPref(prefs::kEulaAccepted
, false);
796 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
798 if (base::win::GetVersion() >= base::win::VERSION_WIN7
) {
799 registry
->RegisterStringPref(prefs::kRelaunchMode
,
800 upgrade_util::kRelaunchModeDefault
);
804 // TODO(brettw,*): this comment about ResourceBundle was here since
805 // initial commit. This comment seems unrelated, bit-rotten and
806 // a candidate for removal.
807 // Initialize ResourceBundle which handles files loaded from external
808 // sources. This has to be done before uninstall code path and before prefs
810 registry
->RegisterStringPref(prefs::kApplicationLocale
, std::string());
811 #if defined(OS_CHROMEOS)
812 registry
->RegisterStringPref(prefs::kOwnerLocale
, std::string());
813 registry
->RegisterStringPref(prefs::kHardwareKeyboardLayout
,
815 #endif // defined(OS_CHROMEOS)
816 #if !defined(OS_CHROMEOS)
817 registry
->RegisterBooleanPref(
818 prefs::kMetricsReportingEnabled
,
819 GoogleUpdateSettings::GetCollectStatsConsent());
820 #endif // !defined(OS_CHROMEOS)
822 #if defined(OS_ANDROID)
823 registry
->RegisterBooleanPref(
824 prefs::kCrashReportingEnabled
, false);
825 #endif // defined(OS_ANDROID)
828 DownloadRequestLimiter
* BrowserProcessImpl::download_request_limiter() {
829 DCHECK(CalledOnValidThread());
830 if (!download_request_limiter_
.get())
831 download_request_limiter_
= new DownloadRequestLimiter();
832 return download_request_limiter_
.get();
835 BackgroundModeManager
* BrowserProcessImpl::background_mode_manager() {
836 DCHECK(CalledOnValidThread());
837 #if defined(ENABLE_BACKGROUND)
838 if (!background_mode_manager_
.get())
839 CreateBackgroundModeManager();
840 return background_mode_manager_
.get();
847 void BrowserProcessImpl::set_background_mode_manager_for_test(
848 scoped_ptr
<BackgroundModeManager
> manager
) {
849 #if defined(ENABLE_BACKGROUND)
850 background_mode_manager_
= manager
.Pass();
854 StatusTray
* BrowserProcessImpl::status_tray() {
855 DCHECK(CalledOnValidThread());
856 if (!status_tray_
.get())
858 return status_tray_
.get();
862 SafeBrowsingService
* BrowserProcessImpl::safe_browsing_service() {
863 DCHECK(CalledOnValidThread());
864 if (!created_safe_browsing_service_
)
865 CreateSafeBrowsingService();
866 return safe_browsing_service_
.get();
869 safe_browsing::ClientSideDetectionService
*
870 BrowserProcessImpl::safe_browsing_detection_service() {
871 DCHECK(CalledOnValidThread());
872 if (safe_browsing_service())
873 return safe_browsing_service()->safe_browsing_detection_service();
877 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
878 void BrowserProcessImpl::StartAutoupdateTimer() {
879 autoupdate_timer_
.Start(FROM_HERE
,
880 base::TimeDelta::FromHours(kUpdateCheckIntervalHours
),
882 &BrowserProcessImpl::OnAutoupdateTimer
);
886 ChromeNetLog
* BrowserProcessImpl::net_log() {
887 return net_log_
.get();
890 prerender::PrerenderTracker
* BrowserProcessImpl::prerender_tracker() {
891 if (!prerender_tracker_
.get())
892 prerender_tracker_
.reset(new prerender::PrerenderTracker
);
894 return prerender_tracker_
.get();
897 component_updater::ComponentUpdateService
*
898 BrowserProcessImpl::component_updater() {
899 if (!component_updater_
.get()) {
900 if (!BrowserThread::CurrentlyOn(BrowserThread::UI
))
902 component_updater::Configurator
* configurator
=
903 component_updater::MakeChromeComponentUpdaterConfigurator(
904 CommandLine::ForCurrentProcess(),
905 io_thread()->system_url_request_context_getter());
906 // Creating the component updater does not do anything, components
907 // need to be registered and Start() needs to be called.
908 component_updater_
.reset(ComponentUpdateServiceFactory(configurator
));
910 return component_updater_
.get();
913 CRLSetFetcher
* BrowserProcessImpl::crl_set_fetcher() {
914 if (!crl_set_fetcher_
.get())
915 crl_set_fetcher_
= new CRLSetFetcher();
916 return crl_set_fetcher_
.get();
919 component_updater::PnaclComponentInstaller
*
920 BrowserProcessImpl::pnacl_component_installer() {
921 #if !defined(DISABLE_NACL)
922 if (!pnacl_component_installer_
.get()) {
923 pnacl_component_installer_
.reset(
924 new component_updater::PnaclComponentInstaller());
926 return pnacl_component_installer_
.get();
932 void BrowserProcessImpl::ResourceDispatcherHostCreated() {
933 resource_dispatcher_host_delegate_
.reset(
934 new ChromeResourceDispatcherHostDelegate(prerender_tracker()));
935 ResourceDispatcherHost::Get()->SetDelegate(
936 resource_dispatcher_host_delegate_
.get());
938 pref_change_registrar_
.Add(
939 prefs::kAllowCrossOriginAuthPrompt
,
940 base::Bind(&BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy
,
941 base::Unretained(this)));
942 ApplyAllowCrossOriginAuthPromptPolicy();
945 void BrowserProcessImpl::CreateWatchdogThread() {
946 DCHECK(!created_watchdog_thread_
&& watchdog_thread_
.get() == NULL
);
947 created_watchdog_thread_
= true;
949 scoped_ptr
<WatchDogThread
> thread(new WatchDogThread());
950 base::Thread::Options options
;
951 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
952 if (!thread
->StartWithOptions(options
))
954 watchdog_thread_
.swap(thread
);
957 void BrowserProcessImpl::CreateProfileManager() {
958 DCHECK(!created_profile_manager_
&& profile_manager_
.get() == NULL
);
959 created_profile_manager_
= true;
961 base::FilePath user_data_dir
;
962 PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
);
963 profile_manager_
.reset(new ProfileManager(user_data_dir
));
966 void BrowserProcessImpl::CreateLocalState() {
967 DCHECK(!created_local_state_
&& local_state_
.get() == NULL
);
968 created_local_state_
= true;
970 base::FilePath local_state_path
;
971 CHECK(PathService::Get(chrome::FILE_LOCAL_STATE
, &local_state_path
));
972 scoped_refptr
<PrefRegistrySimple
> pref_registry
= new PrefRegistrySimple
;
974 // Register local state preferences.
975 chrome::RegisterLocalState(pref_registry
.get());
978 chrome_prefs::CreateLocalState(local_state_path
,
979 local_state_task_runner_
.get(),
984 pref_change_registrar_
.Init(local_state_
.get());
986 // Initialize the notification for the default browser setting policy.
987 pref_change_registrar_
.Add(
988 prefs::kDefaultBrowserSettingEnabled
,
989 base::Bind(&BrowserProcessImpl::ApplyDefaultBrowserPolicy
,
990 base::Unretained(this)));
992 // This preference must be kept in sync with external values; update them
993 // whenever the preference or its controlling policy changes.
994 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
995 pref_change_registrar_
.Add(
996 prefs::kMetricsReportingEnabled
,
997 base::Bind(&BrowserProcessImpl::ApplyMetricsReportingPolicy
,
998 base::Unretained(this)));
1001 int max_per_proxy
= local_state_
->GetInteger(prefs::kMaxConnectionsPerProxy
);
1002 net::ClientSocketPoolManager::set_max_sockets_per_proxy_server(
1003 net::HttpNetworkSession::NORMAL_SOCKET_POOL
,
1004 std::max(std::min(max_per_proxy
, 99),
1005 net::ClientSocketPoolManager::max_sockets_per_group(
1006 net::HttpNetworkSession::NORMAL_SOCKET_POOL
)));
1009 void BrowserProcessImpl::PreCreateThreads() {
1011 new IOThread(local_state(), policy_service(), net_log_
.get(),
1012 extension_event_router_forwarder()));
1015 void BrowserProcessImpl::PreMainMessageLoopRun() {
1016 #if defined(ENABLE_CONFIGURATION_POLICY)
1017 // browser_policy_connector() is created very early because local_state()
1018 // needs policy to be initialized with the managed preference values.
1019 // However, policy fetches from the network and loading of disk caches
1020 // requires that threads are running; this Init() call lets the connector
1021 // resume its initialization now that the loops are spinning and the
1022 // system request context is available for the fetchers.
1023 browser_policy_connector()->Init(local_state(), system_request_context());
1026 if (local_state_
->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled
))
1027 ApplyDefaultBrowserPolicy();
1029 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1030 ApplyMetricsReportingPolicy();
1033 #if defined(ENABLE_PLUGINS)
1034 PluginService
* plugin_service
= PluginService::GetInstance();
1035 plugin_service
->SetFilter(ChromePluginServiceFilter::GetInstance());
1036 plugin_service
->StartWatchingPlugins();
1038 #if defined(OS_POSIX)
1039 // Also find plugins in a user-specific plugins dir,
1040 // e.g. ~/.config/chromium/Plugins.
1041 const CommandLine
& cmd_line
= *CommandLine::ForCurrentProcess();
1042 if (!cmd_line
.HasSwitch(switches::kDisablePluginsDiscovery
)) {
1043 base::FilePath user_data_dir
;
1044 if (PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
))
1045 plugin_service
->AddExtraPluginDir(user_data_dir
.Append("Plugins"));
1049 // Triggers initialization of the singleton instance on UI thread.
1050 PluginFinder::GetInstance()->Init();
1052 #if defined(ENABLE_PLUGIN_INSTALLATION)
1053 DCHECK(!plugins_resource_service_
.get());
1054 plugins_resource_service_
= new PluginsResourceService(local_state());
1055 plugins_resource_service_
->Init();
1057 #endif // defined(ENABLE_PLUGINS)
1059 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
1060 if (!command_line
.HasSwitch(switches::kDisableWebResources
)) {
1061 DCHECK(!promo_resource_service_
.get());
1062 promo_resource_service_
= new PromoResourceService
;
1063 promo_resource_service_
->StartAfterDelay();
1066 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1067 storage_monitor::StorageMonitor::Create();
1070 platform_part_
->PreMainMessageLoopRun();
1073 void BrowserProcessImpl::CreateIconManager() {
1074 DCHECK(!created_icon_manager_
&& icon_manager_
.get() == NULL
);
1075 created_icon_manager_
= true;
1076 icon_manager_
.reset(new IconManager
);
1079 void BrowserProcessImpl::CreateIntranetRedirectDetector() {
1080 DCHECK(intranet_redirect_detector_
.get() == NULL
);
1081 scoped_ptr
<IntranetRedirectDetector
> intranet_redirect_detector(
1082 new IntranetRedirectDetector
);
1083 intranet_redirect_detector_
.swap(intranet_redirect_detector
);
1086 void BrowserProcessImpl::CreateNotificationUIManager() {
1087 #if defined(ENABLE_NOTIFICATIONS)
1088 DCHECK(notification_ui_manager_
.get() == NULL
);
1089 notification_ui_manager_
.reset(NotificationUIManager::Create(local_state()));
1090 created_notification_ui_manager_
= true;
1094 void BrowserProcessImpl::CreateBackgroundModeManager() {
1095 #if defined(ENABLE_BACKGROUND)
1096 DCHECK(background_mode_manager_
.get() == NULL
);
1097 background_mode_manager_
.reset(
1098 new BackgroundModeManager(CommandLine::ForCurrentProcess(),
1099 &profile_manager()->GetProfileInfoCache()));
1103 void BrowserProcessImpl::CreateStatusTray() {
1104 DCHECK(status_tray_
.get() == NULL
);
1105 status_tray_
.reset(StatusTray::Create());
1108 void BrowserProcessImpl::CreatePrintPreviewDialogController() {
1109 #if defined(ENABLE_FULL_PRINTING)
1110 DCHECK(print_preview_dialog_controller_
.get() == NULL
);
1111 print_preview_dialog_controller_
=
1112 new printing::PrintPreviewDialogController();
1118 void BrowserProcessImpl::CreateBackgroundPrintingManager() {
1119 #if defined(ENABLE_FULL_PRINTING)
1120 DCHECK(background_printing_manager_
.get() == NULL
);
1121 background_printing_manager_
.reset(new printing::BackgroundPrintingManager());
1127 void BrowserProcessImpl::CreateSafeBrowsingService() {
1128 DCHECK(safe_browsing_service_
.get() == NULL
);
1129 // Set this flag to true so that we don't retry indefinitely to
1130 // create the service class if there was an error.
1131 created_safe_browsing_service_
= true;
1132 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
1133 safe_browsing_service_
= SafeBrowsingService::CreateSafeBrowsingService();
1134 safe_browsing_service_
->Initialize();
1138 void BrowserProcessImpl::CreateGCMDriver() {
1139 DCHECK(!gcm_driver_
);
1141 #if defined(OS_ANDROID)
1142 gcm_driver_
.reset(new gcm::GCMDriverAndroid
);
1144 base::FilePath store_path
;
1145 CHECK(PathService::Get(chrome::DIR_GLOBAL_GCM_STORE
, &store_path
));
1146 gcm_driver_
= gcm::CreateGCMDriverDesktop(
1147 make_scoped_ptr(new gcm::GCMClientFactory
),
1150 system_request_context());
1151 // Sign-in is not required for device-level GCM usage. So we just call
1152 // OnSignedIn to assume always signed-in. Note that GCM will not be started
1153 // at this point since no one has asked for it yet.
1154 // TODO(jianli): To be removed when sign-in enforcement is dropped.
1155 gcm_driver_
->OnSignedIn();
1156 #endif // defined(OS_ANDROID)
1159 void BrowserProcessImpl::ApplyDefaultBrowserPolicy() {
1160 if (local_state()->GetBoolean(prefs::kDefaultBrowserSettingEnabled
)) {
1161 scoped_refptr
<ShellIntegration::DefaultWebClientWorker
>
1162 set_browser_worker
= new ShellIntegration::DefaultBrowserWorker(NULL
);
1163 set_browser_worker
->StartSetAsDefault();
1167 void BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy() {
1168 bool value
= local_state()->GetBoolean(prefs::kAllowCrossOriginAuthPrompt
);
1169 ResourceDispatcherHost::Get()->SetAllowCrossOriginAuthPrompt(value
);
1172 void BrowserProcessImpl::ApplyMetricsReportingPolicy() {
1173 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1174 CHECK(BrowserThread::PostTask(
1175 BrowserThread::FILE, FROM_HERE
,
1177 base::IgnoreResult(&GoogleUpdateSettings::SetCollectStatsConsent
),
1178 local_state()->GetBoolean(prefs::kMetricsReportingEnabled
))));
1182 // Mac is currently not supported.
1183 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
1185 bool BrowserProcessImpl::CanAutorestartForUpdate() const {
1186 // Check if browser is in the background and if it needs to be restarted to
1187 // apply a pending update.
1188 return chrome::GetTotalBrowserCount() == 0 && chrome::WillKeepAlive() &&
1189 upgrade_util::IsUpdatePendingRestart();
1192 // Switches to add when auto-restarting Chrome.
1193 const char* const kSwitchesToAddOnAutorestart
[] = {
1194 switches::kNoStartupWindow
1197 void BrowserProcessImpl::RestartBackgroundInstance() {
1198 CommandLine
* old_cl
= CommandLine::ForCurrentProcess();
1199 scoped_ptr
<CommandLine
> new_cl(new CommandLine(old_cl
->GetProgram()));
1201 std::map
<std::string
, CommandLine::StringType
> switches
=
1202 old_cl
->GetSwitches();
1204 switches::RemoveSwitchesForAutostart(&switches
);
1206 // Append the rest of the switches (along with their values, if any)
1207 // to the new command line
1208 for (std::map
<std::string
, CommandLine::StringType
>::const_iterator i
=
1209 switches
.begin(); i
!= switches
.end(); ++i
) {
1210 CommandLine::StringType switch_value
= i
->second
;
1211 if (switch_value
.length() > 0) {
1212 new_cl
->AppendSwitchNative(i
->first
, i
->second
);
1214 new_cl
->AppendSwitch(i
->first
);
1218 // Ensure that our desired switches are set on the new process.
1219 for (size_t i
= 0; i
< arraysize(kSwitchesToAddOnAutorestart
); ++i
) {
1220 if (!new_cl
->HasSwitch(kSwitchesToAddOnAutorestart
[i
]))
1221 new_cl
->AppendSwitch(kSwitchesToAddOnAutorestart
[i
]);
1224 DLOG(WARNING
) << "Shutting down current instance of the browser.";
1225 chrome::AttemptExit();
1227 // Transfer ownership to Upgrade.
1228 upgrade_util::SetNewCommandLine(new_cl
.release());
1231 void BrowserProcessImpl::OnAutoupdateTimer() {
1232 if (CanAutorestartForUpdate()) {
1233 DLOG(WARNING
) << "Detected update. Restarting browser.";
1234 RestartBackgroundInstance();
1238 #endif // (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)