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_child_process_watcher.h"
31 #include "chrome/browser/chrome_content_browser_client.h"
32 #include "chrome/browser/chrome_notification_types.h"
33 #include "chrome/browser/component_updater/chrome_component_updater_configurator.h"
34 #include "chrome/browser/component_updater/supervised_user_whitelist_installer.h"
35 #include "chrome/browser/defaults.h"
36 #include "chrome/browser/devtools/remote_debugging_server.h"
37 #include "chrome/browser/download/download_request_limiter.h"
38 #include "chrome/browser/download/download_status_updater.h"
39 #include "chrome/browser/first_run/upgrade_util.h"
40 #include "chrome/browser/gpu/gl_string_manager.h"
41 #include "chrome/browser/gpu/gpu_mode_manager.h"
42 #include "chrome/browser/icon_manager.h"
43 #include "chrome/browser/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_services_manager.h"
47 #include "chrome/browser/metrics/thread_watcher.h"
48 #include "chrome/browser/net/chrome_net_log.h"
49 #include "chrome/browser/net/crl_set_fetcher.h"
50 #include "chrome/browser/notifications/notification_ui_manager.h"
51 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
52 #include "chrome/browser/plugins/plugin_finder.h"
53 #include "chrome/browser/prefs/browser_prefs.h"
54 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
55 #include "chrome/browser/printing/background_printing_manager.h"
56 #include "chrome/browser/printing/print_job_manager.h"
57 #include "chrome/browser/printing/print_preview_dialog_controller.h"
58 #include "chrome/browser/profiles/profile_manager.h"
59 #include "chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h"
60 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
61 #include "chrome/browser/shell_integration.h"
62 #include "chrome/browser/status_icons/status_tray.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/update_client/chrome_update_query_params_delegate.h"
67 #include "chrome/browser/web_resource/promo_resource_service.h"
68 #include "chrome/common/chrome_constants.h"
69 #include "chrome/common/chrome_paths.h"
70 #include "chrome/common/chrome_switches.h"
71 #include "chrome/common/extensions/chrome_extensions_client.h"
72 #include "chrome/common/pref_names.h"
73 #include "chrome/common/switch_utils.h"
74 #include "chrome/common/url_constants.h"
75 #include "chrome/installer/util/google_update_constants.h"
76 #include "chrome/installer/util/google_update_settings.h"
77 #include "components/component_updater/component_updater_service.h"
78 #include "components/gcm_driver/gcm_driver.h"
79 #include "components/metrics/metrics_service.h"
80 #include "components/network_time/network_time_tracker.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 "components/update_client/update_query_params.h"
85 #include "components/web_resource/web_resource_pref_names.h"
86 #include "content/public/browser/browser_thread.h"
87 #include "content/public/browser/child_process_security_policy.h"
88 #include "content/public/browser/notification_details.h"
89 #include "content/public/browser/plugin_service.h"
90 #include "content/public/browser/render_process_host.h"
91 #include "content/public/browser/resource_dispatcher_host.h"
92 #include "content/public/browser/service_worker_context.h"
93 #include "content/public/browser/storage_partition.h"
94 #include "extensions/common/constants.h"
95 #include "net/socket/client_socket_pool_manager.h"
96 #include "net/url_request/url_request_context_getter.h"
97 #include "ui/base/idle/idle.h"
98 #include "ui/base/l10n/l10n_util.h"
99 #include "ui/message_center/message_center.h"
102 #include "base/win/windows_version.h"
103 #include "ui/views/focus/view_storage.h"
104 #elif defined(OS_MACOSX)
105 #include "chrome/browser/chrome_browser_main_mac.h"
108 #if !defined(OS_ANDROID)
109 #include "chrome/browser/chrome_device_client.h"
110 #include "chrome/browser/services/gcm/gcm_desktop_utils.h"
111 #include "components/gcm_driver/gcm_client_factory.h"
114 #if defined(USE_AURA)
115 #include "ui/aura/env.h"
118 #if defined(ENABLE_BACKGROUND)
119 #include "chrome/browser/background/background_mode_manager.h"
122 #if defined(ENABLE_CONFIGURATION_POLICY)
123 #include "components/policy/core/browser/browser_policy_connector.h"
125 #include "components/policy/core/common/policy_service_stub.h"
126 #endif // defined(ENABLE_CONFIGURATION_POLICY)
128 #if defined(ENABLE_EXTENSIONS)
129 #include "chrome/browser/extensions/chrome_extensions_browser_client.h"
130 #include "chrome/browser/extensions/event_router_forwarder.h"
131 #include "chrome/browser/extensions/extension_renderer_state.h"
132 #include "chrome/browser/media_galleries/media_file_system_registry.h"
133 #include "chrome/browser/ui/apps/chrome_app_window_client.h"
134 #include "components/storage_monitor/storage_monitor.h"
135 #include "extensions/common/extension_l10n_util.h"
138 #if !defined(DISABLE_NACL)
139 #include "chrome/browser/component_updater/pnacl_component_installer.h"
142 #if defined(ENABLE_PLUGIN_INSTALLATION)
143 #include "chrome/browser/plugins/plugins_resource_service.h"
146 #if defined(ENABLE_WEBRTC)
147 #include "chrome/browser/media/webrtc_log_uploader.h"
150 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
151 // How often to check if the persistent instance of Chrome needs to restart
152 // to install an update.
153 static const int kUpdateCheckIntervalHours
= 6;
156 #if defined(USE_X11) || defined(OS_WIN) || defined(USE_OZONE)
157 // How long to wait for the File thread to complete during EndSession, on Linux
158 // and Windows. We have a timeout here because we're unable to run the UI
159 // messageloop and there's some deadlock risk. Our only option is to exit
161 static const int kEndSessionTimeoutSeconds
= 10;
164 using content::BrowserThread
;
165 using content::ChildProcessSecurityPolicy
;
166 using content::PluginService
;
167 using content::ResourceDispatcherHost
;
169 BrowserProcessImpl::BrowserProcessImpl(
170 base::SequencedTaskRunner
* local_state_task_runner
,
171 const base::CommandLine
& command_line
)
172 : created_watchdog_thread_(false),
173 created_browser_policy_connector_(false),
174 created_profile_manager_(false),
175 created_local_state_(false),
176 created_icon_manager_(false),
177 created_notification_ui_manager_(false),
178 created_safe_browsing_service_(false),
179 module_ref_count_(0),
181 download_status_updater_(new DownloadStatusUpdater
),
182 local_state_task_runner_(local_state_task_runner
) {
183 g_browser_process
= this;
184 platform_part_
.reset(new BrowserProcessPlatformPart());
186 #if defined(ENABLE_PRINTING)
187 // Must be created after the NotificationService.
188 print_job_manager_
.reset(new printing::PrintJobManager
);
191 net_log_
.reset(new ChromeNetLog
);
193 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
194 extensions::kExtensionScheme
);
195 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
196 extensions::kExtensionResourceScheme
);
197 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
198 chrome::kChromeSearchScheme
);
200 #if defined(OS_MACOSX)
201 ui::InitIdleMonitor();
204 #if !defined(OS_ANDROID)
205 device_client_
.reset(new ChromeDeviceClient
);
208 #if defined(ENABLE_EXTENSIONS)
209 // Athena sets its own instance during Athena's init process.
210 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 update_client::UpdateQueryParams::SetDelegate(
226 ChromeUpdateQueryParamsDelegate::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(SAFE_BROWSING_SERVICE)
246 if (safe_browsing_service_
.get())
247 safe_browsing_service()->ShutDown();
249 #if defined(ENABLE_PLUGIN_INSTALLATION)
250 plugins_resource_service_
.reset();
253 // Need to clear the desktop notification balloons before the io_thread_ and
254 // before the profiles, since if there are any still showing we will access
255 // those things during teardown.
256 notification_ui_manager_
.reset();
258 // The SupervisedUserWhitelistInstaller observes the ProfileInfoCache, so it
259 // needs to be shut down before the ProfileManager.
260 supervised_user_whitelist_installer_
.reset();
262 // Need to clear profiles (download managers) before the io_thread_.
264 TRACE_EVENT0("shutdown",
265 "BrowserProcessImpl::StartTearDown:ProfileManager");
266 // The desktop User Manager needs to be closed before the guest profile
268 if (switches::IsNewAvatarMenu())
270 profile_manager_
.reset();
273 // PromoResourceService must be destroyed after the keyed services and before
275 promo_resource_service_
.reset();
277 child_process_watcher_
.reset();
279 #if !defined(OS_ANDROID)
280 // Debugger must be cleaned up before IO thread and NotificationService.
281 remote_debugging_server_
.reset();
284 #if defined(ENABLE_EXTENSIONS)
285 ExtensionRendererState::GetInstance()->Shutdown();
287 media_file_system_registry_
.reset();
288 // Remove the global instance of the Storage Monitor now. Otherwise the
289 // FILE thread would be gone when we try to release it in the dtor and
290 // Valgrind would report a leak on almost every single browser_test.
291 // TODO(gbillock): Make this unnecessary.
292 storage_monitor::StorageMonitor::Destroy();
295 message_center::MessageCenter::Shutdown();
297 #if defined(ENABLE_CONFIGURATION_POLICY)
298 // The policy providers managed by |browser_policy_connector_| need to shut
299 // down while the IO and FILE threads are still alive. The monitoring
300 // framework owned by |browser_policy_connector_| relies on |gcm_driver_|, so
301 // this must be shutdown before |gcm_driver_| below.
302 if (browser_policy_connector_
)
303 browser_policy_connector_
->Shutdown();
306 // The |gcm_driver_| must shut down while the IO thread is still alive.
308 gcm_driver_
->Shutdown();
310 // Stop the watchdog thread before stopping other threads.
311 watchdog_thread_
.reset();
313 #if defined(USE_AURA)
314 // Delete aura after the metrics service has been deleted as it accesses
315 // monitor information.
316 aura::Env::DeleteInstance();
319 platform_part()->StartTearDown();
321 #if defined(ENABLE_WEBRTC)
322 // Cancel any uploads to release the system url request context references.
323 if (webrtc_log_uploader_
)
324 webrtc_log_uploader_
->StartShutdown();
328 local_state()->CommitPendingWrite();
331 void BrowserProcessImpl::PostDestroyThreads() {
332 // With the file_thread_ flushed, we can release any icon resources.
333 icon_manager_
.reset();
335 #if defined(ENABLE_WEBRTC)
336 // Must outlive the file thread.
337 webrtc_log_uploader_
.reset();
340 // Reset associated state right after actual thread is stopped,
341 // as io_thread_.global_ cleanup happens in CleanUp on the IO
342 // thread, i.e. as the thread exits its message loop.
344 // This is important also because in various places, the
345 // IOThread object being NULL is considered synonymous with the
346 // IO thread having stopped.
350 unsigned int BrowserProcessImpl::AddRefModule() {
351 DCHECK(CalledOnValidThread());
353 // CHECK(!IsShuttingDown());
354 if (IsShuttingDown()) {
355 // Copy the stacktrace which released the final reference onto our stack so
356 // it will be available in the crash report for inspection.
357 base::debug::StackTrace callstack
= release_last_reference_callstack_
;
358 base::debug::Alias(&callstack
);
364 return module_ref_count_
;
367 unsigned int BrowserProcessImpl::ReleaseModule() {
368 DCHECK(CalledOnValidThread());
369 DCHECK_NE(0u, module_ref_count_
);
371 if (0 == module_ref_count_
) {
372 release_last_reference_callstack_
= base::debug::StackTrace();
374 #if defined(ENABLE_PRINTING)
375 // Wait for the pending print jobs to finish. Don't do this later, since
376 // this might cause a nested message loop to run, and we don't want pending
377 // tasks to run once teardown has started.
378 print_job_manager_
->Shutdown();
381 #if defined(LEAK_SANITIZER)
382 // Check for memory leaks now, before we start shutting down threads. Doing
383 // this early means we won't report any shutdown-only leaks (as they have
384 // not yet happened at this point).
385 // If leaks are found, this will make the process exit immediately.
386 __lsan_do_leak_check();
389 CHECK(base::MessageLoop::current()->is_running());
391 #if defined(OS_MACOSX)
392 base::MessageLoop::current()->PostTask(
394 base::Bind(ChromeBrowserMainPartsMac::DidEndMainMessageLoop
));
396 base::MessageLoop::current()->Quit();
398 return module_ref_count_
;
403 // Used at the end of session to block the UI thread for completion of sentinel
404 // tasks on the set of threads used to persist profile data and local state.
405 // This is done to ensure that the data has been persisted to disk before
407 class RundownTaskCounter
:
408 public base::RefCountedThreadSafe
<RundownTaskCounter
> {
410 RundownTaskCounter();
412 // Posts a rundown task to |task_runner|, can be invoked an arbitrary number
413 // of times before calling TimedWait.
414 void Post(base::SequencedTaskRunner
* task_runner
);
416 // Waits until the count is zero or |max_time| has passed.
417 // This can only be called once per instance.
418 bool TimedWait(const base::TimeDelta
& max_time
);
421 friend class base::RefCountedThreadSafe
<RundownTaskCounter
>;
422 ~RundownTaskCounter() {}
424 // Decrements the counter and releases the waitable event on transition to
428 // The count starts at one to defer the possibility of one->zero transitions
429 // until TimedWait is called.
430 base::AtomicRefCount count_
;
431 base::WaitableEvent waitable_event_
;
433 DISALLOW_COPY_AND_ASSIGN(RundownTaskCounter
);
436 RundownTaskCounter::RundownTaskCounter()
437 : count_(1), waitable_event_(true, false) {
440 void RundownTaskCounter::Post(base::SequencedTaskRunner
* task_runner
) {
441 // As the count starts off at one, it should never get to zero unless
442 // TimedWait has been called.
443 DCHECK(!base::AtomicRefCountIsZero(&count_
));
445 base::AtomicRefCountInc(&count_
);
447 // The task must be non-nestable to guarantee that it runs after all tasks
448 // currently scheduled on |task_runner| have completed.
449 task_runner
->PostNonNestableTask(FROM_HERE
,
450 base::Bind(&RundownTaskCounter::Decrement
, this));
453 void RundownTaskCounter::Decrement() {
454 if (!base::AtomicRefCountDec(&count_
))
455 waitable_event_
.Signal();
458 bool RundownTaskCounter::TimedWait(const base::TimeDelta
& max_time
) {
459 // Decrement the excess count from the constructor.
462 return waitable_event_
.TimedWait(max_time
);
467 void BrowserProcessImpl::EndSession() {
468 // Mark all the profiles as clean.
469 ProfileManager
* pm
= profile_manager();
470 std::vector
<Profile
*> profiles(pm
->GetLoadedProfiles());
471 scoped_refptr
<RundownTaskCounter
> rundown_counter(new RundownTaskCounter());
472 for (size_t i
= 0; i
< profiles
.size(); ++i
) {
473 Profile
* profile
= profiles
[i
];
474 profile
->SetExitType(Profile::EXIT_SESSION_ENDED
);
475 if (profile
->GetPrefs()) {
476 profile
->GetPrefs()->CommitPendingWrite();
477 rundown_counter
->Post(profile
->GetIOTaskRunner().get());
481 // Tell the metrics service it was cleanly shutdown.
482 metrics::MetricsService
* metrics
= g_browser_process
->metrics_service();
483 if (metrics
&& local_state()) {
484 metrics
->RecordStartOfSessionEnd();
485 #if !defined(OS_CHROMEOS)
486 // MetricsService lazily writes to prefs, force it to write now.
487 // On ChromeOS, chrome gets killed when hangs, so no need to
488 // commit metrics::prefs::kStabilitySessionEndCompleted change immediately.
489 local_state()->CommitPendingWrite();
491 rundown_counter
->Post(local_state_task_runner_
.get());
495 // http://crbug.com/125207
496 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
498 // We must write that the profile and metrics service shutdown cleanly,
499 // otherwise on startup we'll think we crashed. So we block until done and
500 // then proceed with normal shutdown.
502 // If you change the condition here, be sure to also change
503 // ProfileBrowserTests to match.
504 #if defined(USE_X11) || defined(OS_WIN) || defined(USE_OZONE)
505 // Do a best-effort wait on the successful countdown of rundown tasks. Note
506 // that if we don't complete "quickly enough", Windows will terminate our
509 // On Windows, we previously posted a message to FILE and then ran a nested
510 // message loop, waiting for that message to be processed until quitting.
511 // However, doing so means that other messages will also be processed. In
512 // particular, if the GPU process host notices that the GPU has been killed
513 // during shutdown, it races exiting the nested loop with the process host
514 // blocking the message loop attempting to re-establish a connection to the
515 // GPU process synchronously. Because the system may not be allowing
516 // processes to launch, this can result in a hang. See
517 // http://crbug.com/318527.
518 rundown_counter
->TimedWait(
519 base::TimeDelta::FromSeconds(kEndSessionTimeoutSeconds
));
525 MetricsServicesManager
* BrowserProcessImpl::GetMetricsServicesManager() {
526 DCHECK(CalledOnValidThread());
527 if (!metrics_services_manager_
)
528 metrics_services_manager_
.reset(new MetricsServicesManager(local_state()));
529 return metrics_services_manager_
.get();
532 metrics::MetricsService
* BrowserProcessImpl::metrics_service() {
533 DCHECK(CalledOnValidThread());
534 return GetMetricsServicesManager()->GetMetricsService();
537 rappor::RapporService
* BrowserProcessImpl::rappor_service() {
538 DCHECK(CalledOnValidThread());
539 return GetMetricsServicesManager()->GetRapporService();
542 IOThread
* BrowserProcessImpl::io_thread() {
543 DCHECK(CalledOnValidThread());
544 DCHECK(io_thread_
.get());
545 return io_thread_
.get();
548 WatchDogThread
* BrowserProcessImpl::watchdog_thread() {
549 DCHECK(CalledOnValidThread());
550 if (!created_watchdog_thread_
)
551 CreateWatchdogThread();
552 DCHECK(watchdog_thread_
.get() != NULL
);
553 return watchdog_thread_
.get();
556 ProfileManager
* BrowserProcessImpl::profile_manager() {
557 DCHECK(CalledOnValidThread());
558 if (!created_profile_manager_
)
559 CreateProfileManager();
560 return profile_manager_
.get();
563 PrefService
* BrowserProcessImpl::local_state() {
564 DCHECK(CalledOnValidThread());
565 if (!created_local_state_
)
567 return local_state_
.get();
570 net::URLRequestContextGetter
* BrowserProcessImpl::system_request_context() {
571 DCHECK(CalledOnValidThread());
572 return io_thread()->system_url_request_context_getter();
575 chrome_variations::VariationsService
* BrowserProcessImpl::variations_service() {
576 DCHECK(CalledOnValidThread());
577 return GetMetricsServicesManager()->GetVariationsService();
580 PromoResourceService
* BrowserProcessImpl::promo_resource_service() {
581 DCHECK(CalledOnValidThread());
582 return promo_resource_service_
.get();
585 BrowserProcessPlatformPart
* BrowserProcessImpl::platform_part() {
586 return platform_part_
.get();
589 extensions::EventRouterForwarder
*
590 BrowserProcessImpl::extension_event_router_forwarder() {
591 #if defined(ENABLE_EXTENSIONS)
592 return extension_event_router_forwarder_
.get();
598 NotificationUIManager
* BrowserProcessImpl::notification_ui_manager() {
599 DCHECK(CalledOnValidThread());
600 if (!created_notification_ui_manager_
)
601 CreateNotificationUIManager();
602 return notification_ui_manager_
.get();
605 message_center::MessageCenter
* BrowserProcessImpl::message_center() {
606 DCHECK(CalledOnValidThread());
607 return message_center::MessageCenter::Get();
610 policy::BrowserPolicyConnector
* BrowserProcessImpl::browser_policy_connector() {
611 DCHECK(CalledOnValidThread());
612 #if defined(ENABLE_CONFIGURATION_POLICY)
613 if (!created_browser_policy_connector_
) {
614 DCHECK(!browser_policy_connector_
);
615 browser_policy_connector_
= platform_part_
->CreateBrowserPolicyConnector();
616 created_browser_policy_connector_
= true;
618 return browser_policy_connector_
.get();
624 policy::PolicyService
* BrowserProcessImpl::policy_service() {
625 #if defined(ENABLE_CONFIGURATION_POLICY)
626 return browser_policy_connector()->GetPolicyService();
628 if (!policy_service_
.get())
629 policy_service_
.reset(new policy::PolicyServiceStub());
630 return policy_service_
.get();
634 IconManager
* BrowserProcessImpl::icon_manager() {
635 DCHECK(CalledOnValidThread());
636 if (!created_icon_manager_
)
638 return icon_manager_
.get();
641 GLStringManager
* BrowserProcessImpl::gl_string_manager() {
642 DCHECK(CalledOnValidThread());
643 if (!gl_string_manager_
.get())
644 gl_string_manager_
.reset(new GLStringManager());
645 return gl_string_manager_
.get();
648 GpuModeManager
* BrowserProcessImpl::gpu_mode_manager() {
649 DCHECK(CalledOnValidThread());
650 if (!gpu_mode_manager_
.get())
651 gpu_mode_manager_
.reset(new GpuModeManager());
652 return gpu_mode_manager_
.get();
655 void BrowserProcessImpl::CreateDevToolsHttpProtocolHandler(
656 chrome::HostDesktopType host_desktop_type
,
657 const std::string
& ip
,
659 DCHECK(CalledOnValidThread());
660 #if !defined(OS_ANDROID)
661 // StartupBrowserCreator::LaunchBrowser can be run multiple times when browser
662 // is started with several profiles or existing browser process is reused.
663 if (!remote_debugging_server_
.get()) {
664 remote_debugging_server_
.reset(
665 new RemoteDebuggingServer(host_desktop_type
, ip
, port
));
670 bool BrowserProcessImpl::IsShuttingDown() {
671 DCHECK(CalledOnValidThread());
672 return did_start_
&& 0 == module_ref_count_
;
675 printing::PrintJobManager
* BrowserProcessImpl::print_job_manager() {
676 DCHECK(CalledOnValidThread());
677 return print_job_manager_
.get();
680 printing::PrintPreviewDialogController
*
681 BrowserProcessImpl::print_preview_dialog_controller() {
682 #if defined(ENABLE_PRINT_PREVIEW)
683 DCHECK(CalledOnValidThread());
684 if (!print_preview_dialog_controller_
.get())
685 CreatePrintPreviewDialogController();
686 return print_preview_dialog_controller_
.get();
693 printing::BackgroundPrintingManager
*
694 BrowserProcessImpl::background_printing_manager() {
695 #if defined(ENABLE_PRINT_PREVIEW)
696 DCHECK(CalledOnValidThread());
697 if (!background_printing_manager_
.get())
698 CreateBackgroundPrintingManager();
699 return background_printing_manager_
.get();
706 IntranetRedirectDetector
* BrowserProcessImpl::intranet_redirect_detector() {
707 DCHECK(CalledOnValidThread());
708 if (!intranet_redirect_detector_
.get())
709 CreateIntranetRedirectDetector();
710 return intranet_redirect_detector_
.get();
713 const std::string
& BrowserProcessImpl::GetApplicationLocale() {
714 DCHECK(!locale_
.empty());
718 void BrowserProcessImpl::SetApplicationLocale(const std::string
& locale
) {
720 #if defined(ENABLE_EXTENSIONS)
721 extension_l10n_util::SetProcessLocale(locale
);
723 chrome::ChromeContentBrowserClient::SetApplicationLocale(locale
);
724 translate::TranslateDownloadManager::GetInstance()->set_application_locale(
728 DownloadStatusUpdater
* BrowserProcessImpl::download_status_updater() {
729 return download_status_updater_
.get();
732 MediaFileSystemRegistry
* BrowserProcessImpl::media_file_system_registry() {
733 #if defined(ENABLE_EXTENSIONS)
734 if (!media_file_system_registry_
)
735 media_file_system_registry_
.reset(new MediaFileSystemRegistry());
736 return media_file_system_registry_
.get();
742 bool BrowserProcessImpl::created_local_state() const {
743 return created_local_state_
;
746 #if defined(ENABLE_WEBRTC)
747 WebRtcLogUploader
* BrowserProcessImpl::webrtc_log_uploader() {
748 if (!webrtc_log_uploader_
.get())
749 webrtc_log_uploader_
.reset(new WebRtcLogUploader());
750 return webrtc_log_uploader_
.get();
754 network_time::NetworkTimeTracker
* BrowserProcessImpl::network_time_tracker() {
755 if (!network_time_tracker_
) {
756 network_time_tracker_
.reset(new network_time::NetworkTimeTracker(
757 scoped_ptr
<base::TickClock
>(new base::DefaultTickClock()),
760 return network_time_tracker_
.get();
763 gcm::GCMDriver
* BrowserProcessImpl::gcm_driver() {
764 DCHECK(CalledOnValidThread());
767 return gcm_driver_
.get();
771 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple
* registry
) {
772 registry
->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled
,
774 // This policy needs to be defined before the net subsystem is initialized,
776 registry
->RegisterIntegerPref(prefs::kMaxConnectionsPerProxy
,
777 net::kDefaultMaxSocketsPerProxyServer
);
779 registry
->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt
, false);
781 #if defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
782 registry
->RegisterBooleanPref(prefs::kEulaAccepted
, false);
783 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
785 if (base::win::GetVersion() >= base::win::VERSION_WIN7
) {
786 registry
->RegisterStringPref(prefs::kRelaunchMode
,
787 upgrade_util::kRelaunchModeDefault
);
791 // TODO(brettw,*): this comment about ResourceBundle was here since
792 // initial commit. This comment seems unrelated, bit-rotten and
793 // a candidate for removal.
794 // Initialize ResourceBundle which handles files loaded from external
795 // sources. This has to be done before uninstall code path and before prefs
797 registry
->RegisterStringPref(prefs::kApplicationLocale
, std::string());
798 #if defined(OS_CHROMEOS)
799 registry
->RegisterStringPref(prefs::kOwnerLocale
, std::string());
800 registry
->RegisterStringPref(prefs::kHardwareKeyboardLayout
,
802 #endif // defined(OS_CHROMEOS)
803 #if !defined(OS_CHROMEOS)
804 registry
->RegisterBooleanPref(
805 prefs::kMetricsReportingEnabled
,
806 GoogleUpdateSettings::GetCollectStatsConsent());
807 #endif // !defined(OS_CHROMEOS)
809 #if defined(OS_ANDROID)
810 registry
->RegisterBooleanPref(
811 prefs::kCrashReportingEnabled
, false);
812 #endif // defined(OS_ANDROID)
815 DownloadRequestLimiter
* BrowserProcessImpl::download_request_limiter() {
816 DCHECK(CalledOnValidThread());
817 if (!download_request_limiter_
.get())
818 download_request_limiter_
= new DownloadRequestLimiter();
819 return download_request_limiter_
.get();
822 BackgroundModeManager
* BrowserProcessImpl::background_mode_manager() {
823 DCHECK(CalledOnValidThread());
824 #if defined(ENABLE_BACKGROUND)
825 if (!background_mode_manager_
.get())
826 CreateBackgroundModeManager();
827 return background_mode_manager_
.get();
834 void BrowserProcessImpl::set_background_mode_manager_for_test(
835 scoped_ptr
<BackgroundModeManager
> manager
) {
836 #if defined(ENABLE_BACKGROUND)
837 background_mode_manager_
= manager
.Pass();
841 StatusTray
* BrowserProcessImpl::status_tray() {
842 DCHECK(CalledOnValidThread());
843 if (!status_tray_
.get())
845 return status_tray_
.get();
849 SafeBrowsingService
* BrowserProcessImpl::safe_browsing_service() {
850 DCHECK(CalledOnValidThread());
851 if (!created_safe_browsing_service_
)
852 CreateSafeBrowsingService();
853 return safe_browsing_service_
.get();
856 safe_browsing::ClientSideDetectionService
*
857 BrowserProcessImpl::safe_browsing_detection_service() {
858 DCHECK(CalledOnValidThread());
859 if (safe_browsing_service())
860 return safe_browsing_service()->safe_browsing_detection_service();
864 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
865 void BrowserProcessImpl::StartAutoupdateTimer() {
866 autoupdate_timer_
.Start(FROM_HERE
,
867 base::TimeDelta::FromHours(kUpdateCheckIntervalHours
),
869 &BrowserProcessImpl::OnAutoupdateTimer
);
873 ChromeNetLog
* BrowserProcessImpl::net_log() {
874 return net_log_
.get();
877 component_updater::ComponentUpdateService
*
878 BrowserProcessImpl::component_updater() {
879 if (!component_updater_
.get()) {
880 if (!BrowserThread::CurrentlyOn(BrowserThread::UI
))
882 scoped_refptr
<update_client::Configurator
> configurator
=
883 component_updater::MakeChromeComponentUpdaterConfigurator(
884 base::CommandLine::ForCurrentProcess(),
885 io_thread()->system_url_request_context_getter());
886 // Creating the component updater does not do anything, components
887 // need to be registered and Start() needs to be called.
888 component_updater_
.reset(component_updater::ComponentUpdateServiceFactory(
889 configurator
).release());
891 return component_updater_
.get();
894 CRLSetFetcher
* BrowserProcessImpl::crl_set_fetcher() {
895 if (!crl_set_fetcher_
)
896 crl_set_fetcher_
= new CRLSetFetcher();
897 return crl_set_fetcher_
.get();
900 component_updater::PnaclComponentInstaller
*
901 BrowserProcessImpl::pnacl_component_installer() {
902 #if !defined(DISABLE_NACL)
903 if (!pnacl_component_installer_
) {
904 pnacl_component_installer_
=
905 new component_updater::PnaclComponentInstaller();
907 return pnacl_component_installer_
.get();
913 component_updater::SupervisedUserWhitelistInstaller
*
914 BrowserProcessImpl::supervised_user_whitelist_installer() {
915 if (!supervised_user_whitelist_installer_
) {
916 supervised_user_whitelist_installer_
=
917 component_updater::SupervisedUserWhitelistInstaller::Create(
918 component_updater(), &profile_manager()->GetProfileInfoCache(),
921 return supervised_user_whitelist_installer_
.get();
924 void BrowserProcessImpl::ResourceDispatcherHostCreated() {
925 resource_dispatcher_host_delegate_
.reset(
926 new ChromeResourceDispatcherHostDelegate
);
927 ResourceDispatcherHost::Get()->SetDelegate(
928 resource_dispatcher_host_delegate_
.get());
930 pref_change_registrar_
.Add(
931 prefs::kAllowCrossOriginAuthPrompt
,
932 base::Bind(&BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy
,
933 base::Unretained(this)));
934 ApplyAllowCrossOriginAuthPromptPolicy();
937 void BrowserProcessImpl::CreateWatchdogThread() {
938 DCHECK(!created_watchdog_thread_
&& watchdog_thread_
.get() == NULL
);
939 created_watchdog_thread_
= true;
941 scoped_ptr
<WatchDogThread
> thread(new WatchDogThread());
942 base::Thread::Options options
;
943 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
944 if (!thread
->StartWithOptions(options
))
946 watchdog_thread_
.swap(thread
);
949 void BrowserProcessImpl::CreateProfileManager() {
950 DCHECK(!created_profile_manager_
&& profile_manager_
.get() == NULL
);
951 created_profile_manager_
= true;
953 base::FilePath user_data_dir
;
954 PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
);
955 profile_manager_
.reset(new ProfileManager(user_data_dir
));
958 void BrowserProcessImpl::CreateLocalState() {
959 DCHECK(!created_local_state_
&& local_state_
.get() == NULL
);
960 created_local_state_
= true;
962 base::FilePath local_state_path
;
963 CHECK(PathService::Get(chrome::FILE_LOCAL_STATE
, &local_state_path
));
964 scoped_refptr
<PrefRegistrySimple
> pref_registry
= new PrefRegistrySimple
;
966 // Register local state preferences.
967 chrome::RegisterLocalState(pref_registry
.get());
970 chrome_prefs::CreateLocalState(local_state_path
,
971 local_state_task_runner_
.get(),
976 pref_change_registrar_
.Init(local_state_
.get());
978 // Initialize the notification for the default browser setting policy.
979 pref_change_registrar_
.Add(
980 prefs::kDefaultBrowserSettingEnabled
,
981 base::Bind(&BrowserProcessImpl::ApplyDefaultBrowserPolicy
,
982 base::Unretained(this)));
984 // This preference must be kept in sync with external values; update them
985 // whenever the preference or its controlling policy changes.
986 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
987 pref_change_registrar_
.Add(
988 prefs::kMetricsReportingEnabled
,
989 base::Bind(&BrowserProcessImpl::ApplyMetricsReportingPolicy
,
990 base::Unretained(this)));
993 int max_per_proxy
= local_state_
->GetInteger(prefs::kMaxConnectionsPerProxy
);
994 net::ClientSocketPoolManager::set_max_sockets_per_proxy_server(
995 net::HttpNetworkSession::NORMAL_SOCKET_POOL
,
996 std::max(std::min(max_per_proxy
, 99),
997 net::ClientSocketPoolManager::max_sockets_per_group(
998 net::HttpNetworkSession::NORMAL_SOCKET_POOL
)));
1001 void BrowserProcessImpl::PreCreateThreads() {
1003 new IOThread(local_state(), policy_service(), net_log_
.get(),
1004 extension_event_router_forwarder()));
1007 void BrowserProcessImpl::PreMainMessageLoopRun() {
1008 TRACE_EVENT0("startup", "BrowserProcessImpl::PreMainMessageLoopRun");
1009 SCOPED_UMA_HISTOGRAM_TIMER(
1010 "Startup.BrowserProcessImpl_PreMainMessageLoopRunTime");
1012 #if defined(ENABLE_CONFIGURATION_POLICY)
1013 // browser_policy_connector() is created very early because local_state()
1014 // needs policy to be initialized with the managed preference values.
1015 // However, policy fetches from the network and loading of disk caches
1016 // requires that threads are running; this Init() call lets the connector
1017 // resume its initialization now that the loops are spinning and the
1018 // system request context is available for the fetchers.
1019 browser_policy_connector()->Init(local_state(), system_request_context());
1022 if (local_state_
->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled
))
1023 ApplyDefaultBrowserPolicy();
1025 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1026 ApplyMetricsReportingPolicy();
1029 #if defined(ENABLE_PLUGINS)
1030 PluginService
* plugin_service
= PluginService::GetInstance();
1031 plugin_service
->SetFilter(ChromePluginServiceFilter::GetInstance());
1032 plugin_service
->StartWatchingPlugins();
1034 #if defined(OS_POSIX)
1035 // Also find plugins in a user-specific plugins dir,
1036 // e.g. ~/.config/chromium/Plugins.
1037 const base::CommandLine
& cmd_line
= *base::CommandLine::ForCurrentProcess();
1038 if (!cmd_line
.HasSwitch(switches::kDisablePluginsDiscovery
)) {
1039 base::FilePath user_data_dir
;
1040 if (PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
))
1041 plugin_service
->AddExtraPluginDir(user_data_dir
.Append("Plugins"));
1045 // Triggers initialization of the singleton instance on UI thread.
1046 PluginFinder::GetInstance()->Init();
1048 #if defined(ENABLE_PLUGIN_INSTALLATION)
1049 DCHECK(!plugins_resource_service_
.get());
1050 plugins_resource_service_
.reset(new PluginsResourceService(local_state()));
1051 plugins_resource_service_
->Init();
1053 #endif // defined(ENABLE_PLUGINS)
1055 const base::CommandLine
& command_line
=
1056 *base::CommandLine::ForCurrentProcess();
1057 if (!command_line
.HasSwitch(switches::kDisableWebResources
)) {
1058 DCHECK(!promo_resource_service_
.get());
1059 promo_resource_service_
.reset(new PromoResourceService
);
1060 promo_resource_service_
->StartAfterDelay();
1063 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1064 storage_monitor::StorageMonitor::Create();
1067 child_process_watcher_
.reset(new ChromeChildProcessWatcher());
1069 platform_part_
->PreMainMessageLoopRun();
1072 void BrowserProcessImpl::CreateIconManager() {
1073 DCHECK(!created_icon_manager_
&& icon_manager_
.get() == NULL
);
1074 created_icon_manager_
= true;
1075 icon_manager_
.reset(new IconManager
);
1078 void BrowserProcessImpl::CreateIntranetRedirectDetector() {
1079 DCHECK(intranet_redirect_detector_
.get() == NULL
);
1080 scoped_ptr
<IntranetRedirectDetector
> intranet_redirect_detector(
1081 new IntranetRedirectDetector
);
1082 intranet_redirect_detector_
.swap(intranet_redirect_detector
);
1085 void BrowserProcessImpl::CreateNotificationUIManager() {
1086 #if defined(ENABLE_NOTIFICATIONS)
1087 DCHECK(notification_ui_manager_
.get() == NULL
);
1088 notification_ui_manager_
.reset(NotificationUIManager::Create(local_state()));
1089 created_notification_ui_manager_
= true;
1093 void BrowserProcessImpl::CreateBackgroundModeManager() {
1094 #if defined(ENABLE_BACKGROUND)
1095 DCHECK(background_mode_manager_
.get() == NULL
);
1096 background_mode_manager_
.reset(
1097 new BackgroundModeManager(*base::CommandLine::ForCurrentProcess(),
1098 &profile_manager()->GetProfileInfoCache()));
1102 void BrowserProcessImpl::CreateStatusTray() {
1103 DCHECK(status_tray_
.get() == NULL
);
1104 status_tray_
.reset(StatusTray::Create());
1107 void BrowserProcessImpl::CreatePrintPreviewDialogController() {
1108 #if defined(ENABLE_PRINT_PREVIEW)
1109 DCHECK(print_preview_dialog_controller_
.get() == NULL
);
1110 print_preview_dialog_controller_
=
1111 new printing::PrintPreviewDialogController();
1117 void BrowserProcessImpl::CreateBackgroundPrintingManager() {
1118 #if defined(ENABLE_PRINT_PREVIEW)
1119 DCHECK(background_printing_manager_
.get() == NULL
);
1120 background_printing_manager_
.reset(new printing::BackgroundPrintingManager());
1126 void BrowserProcessImpl::CreateSafeBrowsingService() {
1127 DCHECK(safe_browsing_service_
.get() == NULL
);
1128 // Set this flag to true so that we don't retry indefinitely to
1129 // create the service class if there was an error.
1130 created_safe_browsing_service_
= true;
1131 #if defined(SAFE_BROWSING_SERVICE)
1132 safe_browsing_service_
= SafeBrowsingService::CreateSafeBrowsingService();
1133 safe_browsing_service_
->Initialize();
1137 void BrowserProcessImpl::CreateGCMDriver() {
1138 DCHECK(!gcm_driver_
);
1140 #if defined(OS_ANDROID)
1141 // Android's GCMDriver currently makes the assumption that it's a singleton.
1142 // Until this gets fixed, instantiating multiple Java GCMDrivers will throw
1143 // an exception, but because they're only initialized on demand these crashes
1144 // would be very difficult to triage. See http://crbug.com/437827.
1147 base::FilePath store_path
;
1148 CHECK(PathService::Get(chrome::DIR_GLOBAL_GCM_STORE
, &store_path
));
1149 gcm_driver_
= gcm::CreateGCMDriverDesktop(
1150 make_scoped_ptr(new gcm::GCMClientFactory
),
1153 system_request_context());
1154 #endif // defined(OS_ANDROID)
1157 void BrowserProcessImpl::ApplyDefaultBrowserPolicy() {
1158 if (local_state()->GetBoolean(prefs::kDefaultBrowserSettingEnabled
)) {
1159 scoped_refptr
<ShellIntegration::DefaultWebClientWorker
>
1160 set_browser_worker
= new ShellIntegration::DefaultBrowserWorker(NULL
);
1161 set_browser_worker
->StartSetAsDefault();
1165 void BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy() {
1166 bool value
= local_state()->GetBoolean(prefs::kAllowCrossOriginAuthPrompt
);
1167 ResourceDispatcherHost::Get()->SetAllowCrossOriginAuthPrompt(value
);
1170 void BrowserProcessImpl::ApplyMetricsReportingPolicy() {
1171 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1172 CHECK(BrowserThread::PostTask(
1173 BrowserThread::FILE, FROM_HERE
,
1175 base::IgnoreResult(&GoogleUpdateSettings::SetCollectStatsConsent
),
1176 local_state()->GetBoolean(prefs::kMetricsReportingEnabled
))));
1180 // Mac is currently not supported.
1181 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
1183 bool BrowserProcessImpl::CanAutorestartForUpdate() const {
1184 // Check if browser is in the background and if it needs to be restarted to
1185 // apply a pending update.
1186 return chrome::GetTotalBrowserCount() == 0 && chrome::WillKeepAlive() &&
1187 upgrade_util::IsUpdatePendingRestart();
1190 // Switches to add when auto-restarting Chrome.
1191 const char* const kSwitchesToAddOnAutorestart
[] = {
1192 switches::kNoStartupWindow
1195 void BrowserProcessImpl::RestartBackgroundInstance() {
1196 base::CommandLine
* old_cl
= base::CommandLine::ForCurrentProcess();
1197 scoped_ptr
<base::CommandLine
> new_cl(
1198 new base::CommandLine(old_cl
->GetProgram()));
1200 std::map
<std::string
, base::CommandLine::StringType
> switches
=
1201 old_cl
->GetSwitches();
1203 switches::RemoveSwitchesForAutostart(&switches
);
1205 // Append the rest of the switches (along with their values, if any)
1206 // to the new command line
1207 for (std::map
<std::string
, base::CommandLine::StringType
>::const_iterator i
=
1209 i
!= switches
.end(); ++i
) {
1210 base::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)