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/metrics/histogram_macros.h"
20 #include "base/path_service.h"
21 #include "base/prefs/json_pref_store.h"
22 #include "base/prefs/pref_registry_simple.h"
23 #include "base/prefs/pref_service.h"
24 #include "base/synchronization/waitable_event.h"
25 #include "base/threading/thread.h"
26 #include "base/threading/thread_restrictions.h"
27 #include "base/time/default_tick_clock.h"
28 #include "base/trace_event/trace_event.h"
29 #include "chrome/browser/chrome_browser_main.h"
30 #include "chrome/browser/chrome_content_browser_client.h"
31 #include "chrome/browser/chrome_notification_types.h"
32 #include "chrome/browser/component_updater/chrome_component_updater_configurator.h"
33 #include "chrome/browser/component_updater/supervised_user_whitelist_installer.h"
34 #include "chrome/browser/defaults.h"
35 #include "chrome/browser/devtools/remote_debugging_server.h"
36 #include "chrome/browser/download/download_request_limiter.h"
37 #include "chrome/browser/download/download_status_updater.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/intranet_redirect_detector.h"
43 #include "chrome/browser/io_thread.h"
44 #include "chrome/browser/lifetime/application_lifetime.h"
45 #include "chrome/browser/metrics/metrics_services_manager.h"
46 #include "chrome/browser/metrics/thread_watcher.h"
47 #include "chrome/browser/net/chrome_net_log.h"
48 #include "chrome/browser/net/crl_set_fetcher.h"
49 #include "chrome/browser/notifications/notification_ui_manager.h"
50 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
51 #include "chrome/browser/plugins/plugin_finder.h"
52 #include "chrome/browser/prefs/browser_prefs.h"
53 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
54 #include "chrome/browser/printing/background_printing_manager.h"
55 #include "chrome/browser/printing/print_job_manager.h"
56 #include "chrome/browser/printing/print_preview_dialog_controller.h"
57 #include "chrome/browser/profiles/profile_manager.h"
58 #include "chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h"
59 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
60 #include "chrome/browser/shell_integration.h"
61 #include "chrome/browser/status_icons/status_tray.h"
62 #include "chrome/browser/ui/browser_dialogs.h"
63 #include "chrome/browser/ui/browser_finder.h"
64 #include "chrome/browser/ui/user_manager.h"
65 #include "chrome/browser/update_client/chrome_update_query_params_delegate.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/policy/core/common/policy_service.h"
81 #include "components/signin/core/common/profile_management_switches.h"
82 #include "components/translate/core/browser/translate_download_manager.h"
83 #include "components/update_client/update_query_params.h"
84 #include "components/web_resource/web_resource_pref_names.h"
85 #include "content/public/browser/browser_thread.h"
86 #include "content/public/browser/child_process_security_policy.h"
87 #include "content/public/browser/notification_details.h"
88 #include "content/public/browser/plugin_service.h"
89 #include "content/public/browser/render_process_host.h"
90 #include "content/public/browser/resource_dispatcher_host.h"
91 #include "content/public/browser/service_worker_context.h"
92 #include "content/public/browser/storage_partition.h"
93 #include "extensions/common/constants.h"
94 #include "net/socket/client_socket_pool_manager.h"
95 #include "net/url_request/url_request_context_getter.h"
96 #include "ui/base/idle/idle.h"
97 #include "ui/base/l10n/l10n_util.h"
98 #include "ui/message_center/message_center.h"
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(OS_ANDROID)
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 "chrome/browser/ui/apps/chrome_app_window_client.h"
133 #include "components/storage_monitor/storage_monitor.h"
134 #include "extensions/common/extension_l10n_util.h"
137 #if !defined(DISABLE_NACL)
138 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
141 #if defined(ENABLE_PLUGIN_INSTALLATION)
142 #include "chrome/browser/plugins/plugins_resource_service.h"
145 #if defined(ENABLE_WEBRTC)
146 #include "chrome/browser/media/webrtc_log_uploader.h"
149 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
150 // How often to check if the persistent instance of Chrome needs to restart
151 // to install an update.
152 static const int kUpdateCheckIntervalHours
= 6;
155 #if defined(USE_X11) || defined(OS_WIN)
156 // How long to wait for the File thread to complete during EndSession, on Linux
157 // and Windows. We have a timeout here because we're unable to run the UI
158 // messageloop and there's some deadlock risk. Our only option is to exit
160 static const int kEndSessionTimeoutSeconds
= 10;
163 using content::BrowserThread
;
164 using content::ChildProcessSecurityPolicy
;
165 using content::PluginService
;
166 using content::ResourceDispatcherHost
;
168 BrowserProcessImpl::BrowserProcessImpl(
169 base::SequencedTaskRunner
* local_state_task_runner
,
170 const base::CommandLine
& command_line
)
171 : created_watchdog_thread_(false),
172 created_browser_policy_connector_(false),
173 created_profile_manager_(false),
174 created_local_state_(false),
175 created_icon_manager_(false),
176 created_notification_ui_manager_(false),
177 created_safe_browsing_service_(false),
178 module_ref_count_(0),
180 download_status_updater_(new DownloadStatusUpdater
),
181 local_state_task_runner_(local_state_task_runner
) {
182 g_browser_process
= this;
183 platform_part_
.reset(new BrowserProcessPlatformPart());
185 #if defined(ENABLE_PRINTING)
186 // Must be created after the NotificationService.
187 print_job_manager_
.reset(new printing::PrintJobManager
);
190 net_log_
.reset(new ChromeNetLog
);
192 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
193 extensions::kExtensionScheme
);
194 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
195 extensions::kExtensionResourceScheme
);
196 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
197 chrome::kChromeSearchScheme
);
199 #if defined(OS_MACOSX)
200 ui::InitIdleMonitor();
203 #if !defined(OS_ANDROID)
204 device_client_
.reset(new ChromeDeviceClient
);
207 #if defined(ENABLE_EXTENSIONS)
208 // Athena sets its own instance during Athena's init process.
209 extensions::AppWindowClient::Set(ChromeAppWindowClient::GetInstance());
211 extension_event_router_forwarder_
= new extensions::EventRouterForwarder
;
212 ExtensionRendererState::GetInstance()->Init();
214 extensions::ExtensionsClient::Set(
215 extensions::ChromeExtensionsClient::GetInstance());
217 extensions_browser_client_
.reset(
218 new extensions::ChromeExtensionsBrowserClient
);
219 extensions::ExtensionsBrowserClient::Set(extensions_browser_client_
.get());
222 message_center::MessageCenter::Initialize();
224 update_client::UpdateQueryParams::SetDelegate(
225 ChromeUpdateQueryParamsDelegate::GetInstance());
228 BrowserProcessImpl::~BrowserProcessImpl() {
229 tracked_objects::ThreadData::EnsureCleanupWasCalled(4);
231 g_browser_process
= NULL
;
234 void BrowserProcessImpl::StartTearDown() {
235 TRACE_EVENT0("shutdown", "BrowserProcessImpl::StartTearDown");
236 // We need to destroy the MetricsServicesManager, IntranetRedirectDetector,
237 // PromoResourceService, and SafeBrowsing ClientSideDetectionService (owned by
238 // the SafeBrowsingService) before the io_thread_ gets destroyed, since their
239 // destructors can call the URLFetcher destructor, which does a
240 // PostDelayedTask operation on the IO thread. (The IO thread will handle that
241 // URLFetcher operation before going away.)
242 metrics_services_manager_
.reset();
243 intranet_redirect_detector_
.reset();
244 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
245 if (safe_browsing_service_
.get())
246 safe_browsing_service()->ShutDown();
248 #if defined(ENABLE_PLUGIN_INSTALLATION)
249 plugins_resource_service_
.reset();
252 // Need to clear the desktop notification balloons before the io_thread_ and
253 // before the profiles, since if there are any still showing we will access
254 // those things during teardown.
255 notification_ui_manager_
.reset();
257 // The SupervisedUserWhitelistInstaller observes the ProfileInfoCache, so it
258 // needs to be shut down before the ProfileManager.
259 supervised_user_whitelist_installer_
.reset();
261 // Need to clear profiles (download managers) before the io_thread_.
263 TRACE_EVENT0("shutdown",
264 "BrowserProcessImpl::StartTearDown:ProfileManager");
265 // The desktop User Manager needs to be closed before the guest profile
267 if (switches::IsNewAvatarMenu())
269 profile_manager_
.reset();
272 // PromoResourceService must be destroyed after the keyed services and before
274 promo_resource_service_
.reset();
276 #if !defined(OS_ANDROID)
277 // Debugger must be cleaned up before IO thread and NotificationService.
278 remote_debugging_server_
.reset();
281 #if defined(ENABLE_EXTENSIONS)
282 ExtensionRendererState::GetInstance()->Shutdown();
284 media_file_system_registry_
.reset();
285 // Remove the global instance of the Storage Monitor now. Otherwise the
286 // FILE thread would be gone when we try to release it in the dtor and
287 // Valgrind would report a leak on almost every single browser_test.
288 // TODO(gbillock): Make this unnecessary.
289 storage_monitor::StorageMonitor::Destroy();
292 message_center::MessageCenter::Shutdown();
294 #if defined(ENABLE_CONFIGURATION_POLICY)
295 // The policy providers managed by |browser_policy_connector_| need to shut
296 // down while the IO and FILE threads are still alive. The monitoring
297 // framework owned by |browser_policy_connector_| relies on |gcm_driver_|, so
298 // this must be shutdown before |gcm_driver_| below.
299 if (browser_policy_connector_
)
300 browser_policy_connector_
->Shutdown();
303 // The |gcm_driver_| must shut down while the IO thread is still alive.
305 gcm_driver_
->Shutdown();
307 // Stop the watchdog thread before stopping other threads.
308 watchdog_thread_
.reset();
310 #if defined(USE_AURA)
311 // Delete aura after the metrics service has been deleted as it accesses
312 // monitor information.
313 aura::Env::DeleteInstance();
316 platform_part()->StartTearDown();
318 #if defined(ENABLE_WEBRTC)
319 // Cancel any uploads to release the system url request context references.
320 if (webrtc_log_uploader_
)
321 webrtc_log_uploader_
->StartShutdown();
325 local_state()->CommitPendingWrite();
328 void BrowserProcessImpl::PostDestroyThreads() {
329 // With the file_thread_ flushed, we can release any icon resources.
330 icon_manager_
.reset();
332 #if defined(ENABLE_WEBRTC)
333 // Must outlive the file thread.
334 webrtc_log_uploader_
.reset();
337 // Reset associated state right after actual thread is stopped,
338 // as io_thread_.global_ cleanup happens in CleanUp on the IO
339 // thread, i.e. as the thread exits its message loop.
341 // This is important also because in various places, the
342 // IOThread object being NULL is considered synonymous with the
343 // IO thread having stopped.
347 unsigned int BrowserProcessImpl::AddRefModule() {
348 DCHECK(CalledOnValidThread());
350 // CHECK(!IsShuttingDown());
351 if (IsShuttingDown()) {
352 // Copy the stacktrace which released the final reference onto our stack so
353 // it will be available in the crash report for inspection.
354 base::debug::StackTrace callstack
= release_last_reference_callstack_
;
355 base::debug::Alias(&callstack
);
361 return module_ref_count_
;
364 unsigned int BrowserProcessImpl::ReleaseModule() {
365 DCHECK(CalledOnValidThread());
366 DCHECK_NE(0u, module_ref_count_
);
368 if (0 == module_ref_count_
) {
369 release_last_reference_callstack_
= base::debug::StackTrace();
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
);
464 void BrowserProcessImpl::EndSession() {
465 // Mark all the profiles as clean.
466 ProfileManager
* pm
= profile_manager();
467 std::vector
<Profile
*> profiles(pm
->GetLoadedProfiles());
468 scoped_refptr
<RundownTaskCounter
> rundown_counter(new RundownTaskCounter());
469 for (size_t i
= 0; i
< profiles
.size(); ++i
) {
470 Profile
* profile
= profiles
[i
];
471 profile
->SetExitType(Profile::EXIT_SESSION_ENDED
);
472 if (profile
->GetPrefs()) {
473 profile
->GetPrefs()->CommitPendingWrite();
474 rundown_counter
->Post(profile
->GetIOTaskRunner().get());
478 // Tell the metrics service it was cleanly shutdown.
479 metrics::MetricsService
* metrics
= g_browser_process
->metrics_service();
480 if (metrics
&& local_state()) {
481 metrics
->RecordStartOfSessionEnd();
482 #if !defined(OS_CHROMEOS)
483 // MetricsService lazily writes to prefs, force it to write now.
484 // On ChromeOS, chrome gets killed when hangs, so no need to
485 // commit metrics::prefs::kStabilitySessionEndCompleted change immediately.
486 local_state()->CommitPendingWrite();
488 rundown_counter
->Post(local_state_task_runner_
.get());
492 // http://crbug.com/125207
493 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
495 // We must write that the profile and metrics service shutdown cleanly,
496 // otherwise on startup we'll think we crashed. So we block until done and
497 // then proceed with normal shutdown.
499 // If you change the condition here, be sure to also change
500 // ProfileBrowserTests to match.
501 #if defined(USE_X11) || defined(OS_WIN)
502 // Do a best-effort wait on the successful countdown of rundown tasks. Note
503 // that if we don't complete "quickly enough", Windows will terminate our
506 // On Windows, we previously posted a message to FILE and then ran a nested
507 // message loop, waiting for that message to be processed until quitting.
508 // However, doing so means that other messages will also be processed. In
509 // particular, if the GPU process host notices that the GPU has been killed
510 // during shutdown, it races exiting the nested loop with the process host
511 // blocking the message loop attempting to re-establish a connection to the
512 // GPU process synchronously. Because the system may not be allowing
513 // processes to launch, this can result in a hang. See
514 // http://crbug.com/318527.
515 rundown_counter
->TimedWait(
516 base::TimeDelta::FromSeconds(kEndSessionTimeoutSeconds
));
522 MetricsServicesManager
* BrowserProcessImpl::GetMetricsServicesManager() {
523 DCHECK(CalledOnValidThread());
524 if (!metrics_services_manager_
)
525 metrics_services_manager_
.reset(new MetricsServicesManager(local_state()));
526 return metrics_services_manager_
.get();
529 metrics::MetricsService
* BrowserProcessImpl::metrics_service() {
530 DCHECK(CalledOnValidThread());
531 return GetMetricsServicesManager()->GetMetricsService();
534 rappor::RapporService
* BrowserProcessImpl::rappor_service() {
535 DCHECK(CalledOnValidThread());
536 return GetMetricsServicesManager()->GetRapporService();
539 IOThread
* BrowserProcessImpl::io_thread() {
540 DCHECK(CalledOnValidThread());
541 DCHECK(io_thread_
.get());
542 return io_thread_
.get();
545 WatchDogThread
* BrowserProcessImpl::watchdog_thread() {
546 DCHECK(CalledOnValidThread());
547 if (!created_watchdog_thread_
)
548 CreateWatchdogThread();
549 DCHECK(watchdog_thread_
.get() != NULL
);
550 return watchdog_thread_
.get();
553 ProfileManager
* BrowserProcessImpl::profile_manager() {
554 DCHECK(CalledOnValidThread());
555 if (!created_profile_manager_
)
556 CreateProfileManager();
557 return profile_manager_
.get();
560 PrefService
* BrowserProcessImpl::local_state() {
561 DCHECK(CalledOnValidThread());
562 if (!created_local_state_
)
564 return local_state_
.get();
567 net::URLRequestContextGetter
* BrowserProcessImpl::system_request_context() {
568 DCHECK(CalledOnValidThread());
569 return io_thread()->system_url_request_context_getter();
572 chrome_variations::VariationsService
* BrowserProcessImpl::variations_service() {
573 DCHECK(CalledOnValidThread());
574 return GetMetricsServicesManager()->GetVariationsService();
577 PromoResourceService
* BrowserProcessImpl::promo_resource_service() {
578 DCHECK(CalledOnValidThread());
579 return promo_resource_service_
.get();
582 BrowserProcessPlatformPart
* BrowserProcessImpl::platform_part() {
583 return platform_part_
.get();
586 extensions::EventRouterForwarder
*
587 BrowserProcessImpl::extension_event_router_forwarder() {
588 #if defined(ENABLE_EXTENSIONS)
589 return extension_event_router_forwarder_
.get();
595 NotificationUIManager
* BrowserProcessImpl::notification_ui_manager() {
596 DCHECK(CalledOnValidThread());
597 if (!created_notification_ui_manager_
)
598 CreateNotificationUIManager();
599 return notification_ui_manager_
.get();
602 message_center::MessageCenter
* BrowserProcessImpl::message_center() {
603 DCHECK(CalledOnValidThread());
604 return message_center::MessageCenter::Get();
607 policy::BrowserPolicyConnector
* BrowserProcessImpl::browser_policy_connector() {
608 DCHECK(CalledOnValidThread());
609 #if defined(ENABLE_CONFIGURATION_POLICY)
610 if (!created_browser_policy_connector_
) {
611 DCHECK(!browser_policy_connector_
);
612 browser_policy_connector_
= platform_part_
->CreateBrowserPolicyConnector();
613 created_browser_policy_connector_
= true;
615 return browser_policy_connector_
.get();
621 policy::PolicyService
* BrowserProcessImpl::policy_service() {
622 #if defined(ENABLE_CONFIGURATION_POLICY)
623 return browser_policy_connector()->GetPolicyService();
625 if (!policy_service_
.get())
626 policy_service_
.reset(new policy::PolicyServiceStub());
627 return policy_service_
.get();
631 IconManager
* BrowserProcessImpl::icon_manager() {
632 DCHECK(CalledOnValidThread());
633 if (!created_icon_manager_
)
635 return icon_manager_
.get();
638 GLStringManager
* BrowserProcessImpl::gl_string_manager() {
639 DCHECK(CalledOnValidThread());
640 if (!gl_string_manager_
.get())
641 gl_string_manager_
.reset(new GLStringManager());
642 return gl_string_manager_
.get();
645 GpuModeManager
* BrowserProcessImpl::gpu_mode_manager() {
646 DCHECK(CalledOnValidThread());
647 if (!gpu_mode_manager_
.get())
648 gpu_mode_manager_
.reset(new GpuModeManager());
649 return gpu_mode_manager_
.get();
652 void BrowserProcessImpl::CreateDevToolsHttpProtocolHandler(
653 chrome::HostDesktopType host_desktop_type
,
654 const std::string
& ip
,
656 DCHECK(CalledOnValidThread());
657 #if !defined(OS_ANDROID)
658 // StartupBrowserCreator::LaunchBrowser can be run multiple times when browser
659 // is started with several profiles or existing browser process is reused.
660 if (!remote_debugging_server_
.get()) {
661 remote_debugging_server_
.reset(
662 new RemoteDebuggingServer(host_desktop_type
, ip
, port
));
667 bool BrowserProcessImpl::IsShuttingDown() {
668 DCHECK(CalledOnValidThread());
669 return did_start_
&& 0 == module_ref_count_
;
672 printing::PrintJobManager
* BrowserProcessImpl::print_job_manager() {
673 DCHECK(CalledOnValidThread());
674 return print_job_manager_
.get();
677 printing::PrintPreviewDialogController
*
678 BrowserProcessImpl::print_preview_dialog_controller() {
679 #if defined(ENABLE_PRINT_PREVIEW)
680 DCHECK(CalledOnValidThread());
681 if (!print_preview_dialog_controller_
.get())
682 CreatePrintPreviewDialogController();
683 return print_preview_dialog_controller_
.get();
690 printing::BackgroundPrintingManager
*
691 BrowserProcessImpl::background_printing_manager() {
692 #if defined(ENABLE_PRINT_PREVIEW)
693 DCHECK(CalledOnValidThread());
694 if (!background_printing_manager_
.get())
695 CreateBackgroundPrintingManager();
696 return background_printing_manager_
.get();
703 IntranetRedirectDetector
* BrowserProcessImpl::intranet_redirect_detector() {
704 DCHECK(CalledOnValidThread());
705 if (!intranet_redirect_detector_
.get())
706 CreateIntranetRedirectDetector();
707 return intranet_redirect_detector_
.get();
710 const std::string
& BrowserProcessImpl::GetApplicationLocale() {
711 DCHECK(!locale_
.empty());
715 void BrowserProcessImpl::SetApplicationLocale(const std::string
& locale
) {
717 #if defined(ENABLE_EXTENSIONS)
718 extension_l10n_util::SetProcessLocale(locale
);
720 chrome::ChromeContentBrowserClient::SetApplicationLocale(locale
);
721 translate::TranslateDownloadManager::GetInstance()->set_application_locale(
725 DownloadStatusUpdater
* BrowserProcessImpl::download_status_updater() {
726 return download_status_updater_
.get();
729 MediaFileSystemRegistry
* BrowserProcessImpl::media_file_system_registry() {
730 #if defined(ENABLE_EXTENSIONS)
731 if (!media_file_system_registry_
)
732 media_file_system_registry_
.reset(new MediaFileSystemRegistry());
733 return media_file_system_registry_
.get();
739 bool BrowserProcessImpl::created_local_state() const {
740 return created_local_state_
;
743 #if defined(ENABLE_WEBRTC)
744 WebRtcLogUploader
* BrowserProcessImpl::webrtc_log_uploader() {
745 if (!webrtc_log_uploader_
.get())
746 webrtc_log_uploader_
.reset(new WebRtcLogUploader());
747 return webrtc_log_uploader_
.get();
751 network_time::NetworkTimeTracker
* BrowserProcessImpl::network_time_tracker() {
752 if (!network_time_tracker_
) {
753 network_time_tracker_
.reset(new network_time::NetworkTimeTracker(
754 scoped_ptr
<base::TickClock
>(new base::DefaultTickClock()),
757 return network_time_tracker_
.get();
760 gcm::GCMDriver
* BrowserProcessImpl::gcm_driver() {
761 DCHECK(CalledOnValidThread());
764 return gcm_driver_
.get();
768 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple
* registry
) {
769 registry
->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled
,
771 // This policy needs to be defined before the net subsystem is initialized,
773 registry
->RegisterIntegerPref(prefs::kMaxConnectionsPerProxy
,
774 net::kDefaultMaxSocketsPerProxyServer
);
776 registry
->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt
, false);
778 #if defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
779 registry
->RegisterBooleanPref(prefs::kEulaAccepted
, false);
780 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
782 if (base::win::GetVersion() >= base::win::VERSION_WIN7
) {
783 registry
->RegisterStringPref(prefs::kRelaunchMode
,
784 upgrade_util::kRelaunchModeDefault
);
788 // TODO(brettw,*): this comment about ResourceBundle was here since
789 // initial commit. This comment seems unrelated, bit-rotten and
790 // a candidate for removal.
791 // Initialize ResourceBundle which handles files loaded from external
792 // sources. This has to be done before uninstall code path and before prefs
794 registry
->RegisterStringPref(prefs::kApplicationLocale
, std::string());
795 #if defined(OS_CHROMEOS)
796 registry
->RegisterStringPref(prefs::kOwnerLocale
, std::string());
797 registry
->RegisterStringPref(prefs::kHardwareKeyboardLayout
,
799 #endif // defined(OS_CHROMEOS)
800 #if !defined(OS_CHROMEOS)
801 registry
->RegisterBooleanPref(
802 prefs::kMetricsReportingEnabled
,
803 GoogleUpdateSettings::GetCollectStatsConsent());
804 #endif // !defined(OS_CHROMEOS)
806 #if defined(OS_ANDROID)
807 registry
->RegisterBooleanPref(
808 prefs::kCrashReportingEnabled
, false);
809 #endif // defined(OS_ANDROID)
812 DownloadRequestLimiter
* BrowserProcessImpl::download_request_limiter() {
813 DCHECK(CalledOnValidThread());
814 if (!download_request_limiter_
.get())
815 download_request_limiter_
= new DownloadRequestLimiter();
816 return download_request_limiter_
.get();
819 BackgroundModeManager
* BrowserProcessImpl::background_mode_manager() {
820 DCHECK(CalledOnValidThread());
821 #if defined(ENABLE_BACKGROUND)
822 if (!background_mode_manager_
.get())
823 CreateBackgroundModeManager();
824 return background_mode_manager_
.get();
831 void BrowserProcessImpl::set_background_mode_manager_for_test(
832 scoped_ptr
<BackgroundModeManager
> manager
) {
833 #if defined(ENABLE_BACKGROUND)
834 background_mode_manager_
= manager
.Pass();
838 StatusTray
* BrowserProcessImpl::status_tray() {
839 DCHECK(CalledOnValidThread());
840 if (!status_tray_
.get())
842 return status_tray_
.get();
846 SafeBrowsingService
* BrowserProcessImpl::safe_browsing_service() {
847 DCHECK(CalledOnValidThread());
848 if (!created_safe_browsing_service_
)
849 CreateSafeBrowsingService();
850 return safe_browsing_service_
.get();
853 safe_browsing::ClientSideDetectionService
*
854 BrowserProcessImpl::safe_browsing_detection_service() {
855 DCHECK(CalledOnValidThread());
856 if (safe_browsing_service())
857 return safe_browsing_service()->safe_browsing_detection_service();
861 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
862 void BrowserProcessImpl::StartAutoupdateTimer() {
863 autoupdate_timer_
.Start(FROM_HERE
,
864 base::TimeDelta::FromHours(kUpdateCheckIntervalHours
),
866 &BrowserProcessImpl::OnAutoupdateTimer
);
870 ChromeNetLog
* BrowserProcessImpl::net_log() {
871 return net_log_
.get();
874 component_updater::ComponentUpdateService
*
875 BrowserProcessImpl::component_updater() {
876 if (!component_updater_
.get()) {
877 if (!BrowserThread::CurrentlyOn(BrowserThread::UI
))
879 update_client::Configurator
* configurator
=
880 component_updater::MakeChromeComponentUpdaterConfigurator(
881 base::CommandLine::ForCurrentProcess(),
882 io_thread()->system_url_request_context_getter());
883 // Creating the component updater does not do anything, components
884 // need to be registered and Start() needs to be called.
885 component_updater_
.reset(
886 component_updater::ComponentUpdateServiceFactory(configurator
));
888 return component_updater_
.get();
891 CRLSetFetcher
* BrowserProcessImpl::crl_set_fetcher() {
892 if (!crl_set_fetcher_
)
893 crl_set_fetcher_
= new CRLSetFetcher();
894 return crl_set_fetcher_
.get();
897 component_updater::PnaclComponentInstaller
*
898 BrowserProcessImpl::pnacl_component_installer() {
899 #if !defined(DISABLE_NACL)
900 if (!pnacl_component_installer_
) {
901 pnacl_component_installer_
=
902 new component_updater::PnaclComponentInstaller();
904 return pnacl_component_installer_
.get();
910 component_updater::SupervisedUserWhitelistInstaller
*
911 BrowserProcessImpl::supervised_user_whitelist_installer() {
912 if (!supervised_user_whitelist_installer_
) {
913 supervised_user_whitelist_installer_
=
914 component_updater::SupervisedUserWhitelistInstaller::Create(
915 component_updater(), &profile_manager()->GetProfileInfoCache(),
918 return supervised_user_whitelist_installer_
.get();
921 void BrowserProcessImpl::ResourceDispatcherHostCreated() {
922 resource_dispatcher_host_delegate_
.reset(
923 new ChromeResourceDispatcherHostDelegate
);
924 ResourceDispatcherHost::Get()->SetDelegate(
925 resource_dispatcher_host_delegate_
.get());
927 pref_change_registrar_
.Add(
928 prefs::kAllowCrossOriginAuthPrompt
,
929 base::Bind(&BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy
,
930 base::Unretained(this)));
931 ApplyAllowCrossOriginAuthPromptPolicy();
934 void BrowserProcessImpl::CreateWatchdogThread() {
935 DCHECK(!created_watchdog_thread_
&& watchdog_thread_
.get() == NULL
);
936 created_watchdog_thread_
= true;
938 scoped_ptr
<WatchDogThread
> thread(new WatchDogThread());
939 base::Thread::Options options
;
940 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
941 if (!thread
->StartWithOptions(options
))
943 watchdog_thread_
.swap(thread
);
946 void BrowserProcessImpl::CreateProfileManager() {
947 DCHECK(!created_profile_manager_
&& profile_manager_
.get() == NULL
);
948 created_profile_manager_
= true;
950 base::FilePath user_data_dir
;
951 PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
);
952 profile_manager_
.reset(new ProfileManager(user_data_dir
));
955 void BrowserProcessImpl::CreateLocalState() {
956 DCHECK(!created_local_state_
&& local_state_
.get() == NULL
);
957 created_local_state_
= true;
959 base::FilePath local_state_path
;
960 CHECK(PathService::Get(chrome::FILE_LOCAL_STATE
, &local_state_path
));
961 scoped_refptr
<PrefRegistrySimple
> pref_registry
= new PrefRegistrySimple
;
963 // Register local state preferences.
964 chrome::RegisterLocalState(pref_registry
.get());
967 chrome_prefs::CreateLocalState(local_state_path
,
968 local_state_task_runner_
.get(),
973 pref_change_registrar_
.Init(local_state_
.get());
975 // Initialize the notification for the default browser setting policy.
976 pref_change_registrar_
.Add(
977 prefs::kDefaultBrowserSettingEnabled
,
978 base::Bind(&BrowserProcessImpl::ApplyDefaultBrowserPolicy
,
979 base::Unretained(this)));
981 // This preference must be kept in sync with external values; update them
982 // whenever the preference or its controlling policy changes.
983 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
984 pref_change_registrar_
.Add(
985 prefs::kMetricsReportingEnabled
,
986 base::Bind(&BrowserProcessImpl::ApplyMetricsReportingPolicy
,
987 base::Unretained(this)));
990 int max_per_proxy
= local_state_
->GetInteger(prefs::kMaxConnectionsPerProxy
);
991 net::ClientSocketPoolManager::set_max_sockets_per_proxy_server(
992 net::HttpNetworkSession::NORMAL_SOCKET_POOL
,
993 std::max(std::min(max_per_proxy
, 99),
994 net::ClientSocketPoolManager::max_sockets_per_group(
995 net::HttpNetworkSession::NORMAL_SOCKET_POOL
)));
998 void BrowserProcessImpl::PreCreateThreads() {
1000 new IOThread(local_state(), policy_service(), net_log_
.get(),
1001 extension_event_router_forwarder()));
1004 void BrowserProcessImpl::PreMainMessageLoopRun() {
1005 TRACE_EVENT0("startup", "BrowserProcessImpl::PreMainMessageLoopRun");
1006 SCOPED_UMA_HISTOGRAM_TIMER(
1007 "Startup.BrowserProcessImpl_PreMainMessageLoopRunTime");
1009 #if defined(ENABLE_CONFIGURATION_POLICY)
1010 // browser_policy_connector() is created very early because local_state()
1011 // needs policy to be initialized with the managed preference values.
1012 // However, policy fetches from the network and loading of disk caches
1013 // requires that threads are running; this Init() call lets the connector
1014 // resume its initialization now that the loops are spinning and the
1015 // system request context is available for the fetchers.
1016 browser_policy_connector()->Init(local_state(), system_request_context());
1019 if (local_state_
->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled
))
1020 ApplyDefaultBrowserPolicy();
1022 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1023 ApplyMetricsReportingPolicy();
1026 #if defined(ENABLE_PLUGINS)
1027 PluginService
* plugin_service
= PluginService::GetInstance();
1028 plugin_service
->SetFilter(ChromePluginServiceFilter::GetInstance());
1029 plugin_service
->StartWatchingPlugins();
1031 #if defined(OS_POSIX)
1032 // Also find plugins in a user-specific plugins dir,
1033 // e.g. ~/.config/chromium/Plugins.
1034 const base::CommandLine
& cmd_line
= *base::CommandLine::ForCurrentProcess();
1035 if (!cmd_line
.HasSwitch(switches::kDisablePluginsDiscovery
)) {
1036 base::FilePath user_data_dir
;
1037 if (PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
))
1038 plugin_service
->AddExtraPluginDir(user_data_dir
.Append("Plugins"));
1042 // Triggers initialization of the singleton instance on UI thread.
1043 PluginFinder::GetInstance()->Init();
1045 #if defined(ENABLE_PLUGIN_INSTALLATION)
1046 DCHECK(!plugins_resource_service_
.get());
1047 plugins_resource_service_
.reset(new PluginsResourceService(local_state()));
1048 plugins_resource_service_
->Init();
1050 #endif // defined(ENABLE_PLUGINS)
1052 const base::CommandLine
& command_line
=
1053 *base::CommandLine::ForCurrentProcess();
1054 if (!command_line
.HasSwitch(switches::kDisableWebResources
)) {
1055 DCHECK(!promo_resource_service_
.get());
1056 promo_resource_service_
.reset(new PromoResourceService
);
1057 promo_resource_service_
->StartAfterDelay();
1060 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1061 storage_monitor::StorageMonitor::Create();
1064 platform_part_
->PreMainMessageLoopRun();
1067 void BrowserProcessImpl::CreateIconManager() {
1068 DCHECK(!created_icon_manager_
&& icon_manager_
.get() == NULL
);
1069 created_icon_manager_
= true;
1070 icon_manager_
.reset(new IconManager
);
1073 void BrowserProcessImpl::CreateIntranetRedirectDetector() {
1074 DCHECK(intranet_redirect_detector_
.get() == NULL
);
1075 scoped_ptr
<IntranetRedirectDetector
> intranet_redirect_detector(
1076 new IntranetRedirectDetector
);
1077 intranet_redirect_detector_
.swap(intranet_redirect_detector
);
1080 void BrowserProcessImpl::CreateNotificationUIManager() {
1081 #if defined(ENABLE_NOTIFICATIONS)
1082 DCHECK(notification_ui_manager_
.get() == NULL
);
1083 notification_ui_manager_
.reset(NotificationUIManager::Create(local_state()));
1084 created_notification_ui_manager_
= true;
1088 void BrowserProcessImpl::CreateBackgroundModeManager() {
1089 #if defined(ENABLE_BACKGROUND)
1090 DCHECK(background_mode_manager_
.get() == NULL
);
1091 background_mode_manager_
.reset(
1092 new BackgroundModeManager(*base::CommandLine::ForCurrentProcess(),
1093 &profile_manager()->GetProfileInfoCache()));
1097 void BrowserProcessImpl::CreateStatusTray() {
1098 DCHECK(status_tray_
.get() == NULL
);
1099 status_tray_
.reset(StatusTray::Create());
1102 void BrowserProcessImpl::CreatePrintPreviewDialogController() {
1103 #if defined(ENABLE_PRINT_PREVIEW)
1104 DCHECK(print_preview_dialog_controller_
.get() == NULL
);
1105 print_preview_dialog_controller_
=
1106 new printing::PrintPreviewDialogController();
1112 void BrowserProcessImpl::CreateBackgroundPrintingManager() {
1113 #if defined(ENABLE_PRINT_PREVIEW)
1114 DCHECK(background_printing_manager_
.get() == NULL
);
1115 background_printing_manager_
.reset(new printing::BackgroundPrintingManager());
1121 void BrowserProcessImpl::CreateSafeBrowsingService() {
1122 DCHECK(safe_browsing_service_
.get() == NULL
);
1123 // Set this flag to true so that we don't retry indefinitely to
1124 // create the service class if there was an error.
1125 created_safe_browsing_service_
= true;
1126 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
1127 safe_browsing_service_
= SafeBrowsingService::CreateSafeBrowsingService();
1128 safe_browsing_service_
->Initialize();
1132 void BrowserProcessImpl::CreateGCMDriver() {
1133 DCHECK(!gcm_driver_
);
1135 #if defined(OS_ANDROID)
1136 // Android's GCMDriver currently makes the assumption that it's a singleton.
1137 // Until this gets fixed, instantiating multiple Java GCMDrivers will throw
1138 // an exception, but because they're only initialized on demand these crashes
1139 // would be very difficult to triage. See http://crbug.com/437827.
1142 base::FilePath store_path
;
1143 CHECK(PathService::Get(chrome::DIR_GLOBAL_GCM_STORE
, &store_path
));
1144 gcm_driver_
= gcm::CreateGCMDriverDesktop(
1145 make_scoped_ptr(new gcm::GCMClientFactory
),
1148 system_request_context());
1149 #endif // defined(OS_ANDROID)
1152 void BrowserProcessImpl::ApplyDefaultBrowserPolicy() {
1153 if (local_state()->GetBoolean(prefs::kDefaultBrowserSettingEnabled
)) {
1154 scoped_refptr
<ShellIntegration::DefaultWebClientWorker
>
1155 set_browser_worker
= new ShellIntegration::DefaultBrowserWorker(NULL
);
1156 set_browser_worker
->StartSetAsDefault();
1160 void BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy() {
1161 bool value
= local_state()->GetBoolean(prefs::kAllowCrossOriginAuthPrompt
);
1162 ResourceDispatcherHost::Get()->SetAllowCrossOriginAuthPrompt(value
);
1165 void BrowserProcessImpl::ApplyMetricsReportingPolicy() {
1166 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1167 CHECK(BrowserThread::PostTask(
1168 BrowserThread::FILE, FROM_HERE
,
1170 base::IgnoreResult(&GoogleUpdateSettings::SetCollectStatsConsent
),
1171 local_state()->GetBoolean(prefs::kMetricsReportingEnabled
))));
1175 // Mac is currently not supported.
1176 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
1178 bool BrowserProcessImpl::CanAutorestartForUpdate() const {
1179 // Check if browser is in the background and if it needs to be restarted to
1180 // apply a pending update.
1181 return chrome::GetTotalBrowserCount() == 0 && chrome::WillKeepAlive() &&
1182 upgrade_util::IsUpdatePendingRestart();
1185 // Switches to add when auto-restarting Chrome.
1186 const char* const kSwitchesToAddOnAutorestart
[] = {
1187 switches::kNoStartupWindow
1190 void BrowserProcessImpl::RestartBackgroundInstance() {
1191 base::CommandLine
* old_cl
= base::CommandLine::ForCurrentProcess();
1192 scoped_ptr
<base::CommandLine
> new_cl(
1193 new base::CommandLine(old_cl
->GetProgram()));
1195 std::map
<std::string
, base::CommandLine::StringType
> switches
=
1196 old_cl
->GetSwitches();
1198 switches::RemoveSwitchesForAutostart(&switches
);
1200 // Append the rest of the switches (along with their values, if any)
1201 // to the new command line
1202 for (std::map
<std::string
, base::CommandLine::StringType
>::const_iterator i
=
1204 i
!= switches
.end(); ++i
) {
1205 base::CommandLine::StringType switch_value
= i
->second
;
1206 if (switch_value
.length() > 0) {
1207 new_cl
->AppendSwitchNative(i
->first
, i
->second
);
1209 new_cl
->AppendSwitch(i
->first
);
1213 // Ensure that our desired switches are set on the new process.
1214 for (size_t i
= 0; i
< arraysize(kSwitchesToAddOnAutorestart
); ++i
) {
1215 if (!new_cl
->HasSwitch(kSwitchesToAddOnAutorestart
[i
]))
1216 new_cl
->AppendSwitch(kSwitchesToAddOnAutorestart
[i
]);
1219 DLOG(WARNING
) << "Shutting down current instance of the browser.";
1220 chrome::AttemptExit();
1222 // Transfer ownership to Upgrade.
1223 upgrade_util::SetNewCommandLine(new_cl
.release());
1226 void BrowserProcessImpl::OnAutoupdateTimer() {
1227 if (CanAutorestartForUpdate()) {
1228 DLOG(WARNING
) << "Detected update. Restarting browser.";
1229 RestartBackgroundInstance();
1233 #endif // (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)