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/channel_info.h"
69 #include "chrome/common/chrome_constants.h"
70 #include "chrome/common/chrome_paths.h"
71 #include "chrome/common/chrome_switches.h"
72 #include "chrome/common/extensions/chrome_extensions_client.h"
73 #include "chrome/common/pref_names.h"
74 #include "chrome/common/switch_utils.h"
75 #include "chrome/common/url_constants.h"
76 #include "chrome/installer/util/google_update_constants.h"
77 #include "chrome/installer/util/google_update_settings.h"
78 #include "components/component_updater/component_updater_service.h"
79 #include "components/gcm_driver/gcm_driver.h"
80 #include "components/metrics/metrics_service.h"
81 #include "components/network_time/network_time_tracker.h"
82 #include "components/policy/core/common/policy_service.h"
83 #include "components/signin/core/common/profile_management_switches.h"
84 #include "components/translate/core/browser/translate_download_manager.h"
85 #include "components/update_client/update_query_params.h"
86 #include "components/web_resource/web_resource_pref_names.h"
87 #include "content/public/browser/browser_thread.h"
88 #include "content/public/browser/child_process_security_policy.h"
89 #include "content/public/browser/notification_details.h"
90 #include "content/public/browser/plugin_service.h"
91 #include "content/public/browser/render_process_host.h"
92 #include "content/public/browser/resource_dispatcher_host.h"
93 #include "content/public/browser/service_worker_context.h"
94 #include "content/public/browser/storage_partition.h"
95 #include "extensions/common/constants.h"
96 #include "net/socket/client_socket_pool_manager.h"
97 #include "net/url_request/url_request_context_getter.h"
98 #include "ui/base/idle/idle.h"
99 #include "ui/base/l10n/l10n_util.h"
100 #include "ui/message_center/message_center.h"
103 #include "base/win/windows_version.h"
104 #include "ui/views/focus/view_storage.h"
105 #elif defined(OS_MACOSX)
106 #include "chrome/browser/chrome_browser_main_mac.h"
109 #if !defined(OS_ANDROID)
110 #include "chrome/browser/chrome_device_client.h"
111 #include "chrome/browser/services/gcm/gcm_desktop_utils.h"
112 #include "components/gcm_driver/gcm_client_factory.h"
115 #if defined(ENABLE_BACKGROUND)
116 #include "chrome/browser/background/background_mode_manager.h"
119 #if defined(ENABLE_CONFIGURATION_POLICY)
120 #include "components/policy/core/browser/browser_policy_connector.h"
122 #include "components/policy/core/common/policy_service_stub.h"
123 #endif // defined(ENABLE_CONFIGURATION_POLICY)
125 #if defined(ENABLE_EXTENSIONS)
126 #include "chrome/browser/extensions/chrome_extensions_browser_client.h"
127 #include "chrome/browser/extensions/event_router_forwarder.h"
128 #include "chrome/browser/extensions/extension_renderer_state.h"
129 #include "chrome/browser/media_galleries/media_file_system_registry.h"
130 #include "chrome/browser/ui/apps/chrome_app_window_client.h"
131 #include "components/storage_monitor/storage_monitor.h"
132 #include "extensions/common/extension_l10n_util.h"
135 #if !defined(DISABLE_NACL)
136 #include "chrome/browser/component_updater/pnacl_component_installer.h"
139 #if defined(ENABLE_PLUGIN_INSTALLATION)
140 #include "chrome/browser/plugins/plugins_resource_service.h"
143 #if defined(ENABLE_WEBRTC)
144 #include "chrome/browser/media/webrtc_log_uploader.h"
147 #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS)
148 #include "chrome/browser/memory/oom_priority_manager.h"
151 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
152 // How often to check if the persistent instance of Chrome needs to restart
153 // to install an update.
154 static const int kUpdateCheckIntervalHours
= 6;
157 #if defined(USE_X11) || defined(OS_WIN) || defined(USE_OZONE)
158 // How long to wait for the File thread to complete during EndSession, on Linux
159 // and Windows. We have a timeout here because we're unable to run the UI
160 // messageloop and there's some deadlock risk. Our only option is to exit
162 static const int kEndSessionTimeoutSeconds
= 10;
165 using content::BrowserThread
;
166 using content::ChildProcessSecurityPolicy
;
167 using content::PluginService
;
168 using content::ResourceDispatcherHost
;
170 BrowserProcessImpl::BrowserProcessImpl(
171 base::SequencedTaskRunner
* local_state_task_runner
,
172 const base::CommandLine
& command_line
)
173 : created_watchdog_thread_(false),
174 created_browser_policy_connector_(false),
175 created_profile_manager_(false),
176 created_local_state_(false),
177 created_icon_manager_(false),
178 created_notification_ui_manager_(false),
179 created_safe_browsing_service_(false),
180 module_ref_count_(0),
182 download_status_updater_(new DownloadStatusUpdater
),
183 local_state_task_runner_(local_state_task_runner
),
184 cached_default_web_client_state_(ShellIntegration::UNKNOWN_DEFAULT
) {
185 g_browser_process
= this;
186 platform_part_
.reset(new BrowserProcessPlatformPart());
188 #if defined(ENABLE_PRINTING)
189 // Must be created after the NotificationService.
190 print_job_manager_
.reset(new printing::PrintJobManager
);
193 net_log_
.reset(new ChromeNetLog
);
195 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
196 extensions::kExtensionScheme
);
197 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
198 extensions::kExtensionResourceScheme
);
199 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
200 chrome::kChromeSearchScheme
);
202 #if defined(OS_MACOSX)
203 ui::InitIdleMonitor();
206 #if !defined(OS_ANDROID)
207 device_client_
.reset(new ChromeDeviceClient
);
210 #if defined(ENABLE_EXTENSIONS)
211 // Athena sets its own instance during Athena's init process.
212 extensions::AppWindowClient::Set(ChromeAppWindowClient::GetInstance());
214 extension_event_router_forwarder_
= new extensions::EventRouterForwarder
;
215 ExtensionRendererState::GetInstance()->Init();
217 extensions::ExtensionsClient::Set(
218 extensions::ChromeExtensionsClient::GetInstance());
220 extensions_browser_client_
.reset(
221 new extensions::ChromeExtensionsBrowserClient
);
222 extensions::ExtensionsBrowserClient::Set(extensions_browser_client_
.get());
225 message_center::MessageCenter::Initialize();
227 update_client::UpdateQueryParams::SetDelegate(
228 ChromeUpdateQueryParamsDelegate::GetInstance());
231 BrowserProcessImpl::~BrowserProcessImpl() {
232 tracked_objects::ThreadData::EnsureCleanupWasCalled(4);
234 g_browser_process
= NULL
;
237 void BrowserProcessImpl::StartTearDown() {
238 TRACE_EVENT0("shutdown", "BrowserProcessImpl::StartTearDown");
239 // We need to destroy the MetricsServicesManager, IntranetRedirectDetector,
240 // PromoResourceService, and SafeBrowsing ClientSideDetectionService (owned by
241 // the SafeBrowsingService) before the io_thread_ gets destroyed, since their
242 // destructors can call the URLFetcher destructor, which does a
243 // PostDelayedTask operation on the IO thread. (The IO thread will handle that
244 // URLFetcher operation before going away.)
245 metrics_services_manager_
.reset();
246 intranet_redirect_detector_
.reset();
247 #if defined(SAFE_BROWSING_SERVICE)
248 if (safe_browsing_service_
.get())
249 safe_browsing_service()->ShutDown();
251 #if defined(ENABLE_PLUGIN_INSTALLATION)
252 plugins_resource_service_
.reset();
255 // Need to clear the desktop notification balloons before the io_thread_ and
256 // before the profiles, since if there are any still showing we will access
257 // those things during teardown.
258 notification_ui_manager_
.reset();
260 // The SupervisedUserWhitelistInstaller observes the ProfileInfoCache, so it
261 // needs to be shut down before the ProfileManager.
262 supervised_user_whitelist_installer_
.reset();
264 #if !defined(OS_ANDROID)
265 // Debugger must be cleaned up before ProfileManager.
266 remote_debugging_server_
.reset();
269 // Need to clear profiles (download managers) before the io_thread_.
271 TRACE_EVENT0("shutdown",
272 "BrowserProcessImpl::StartTearDown:ProfileManager");
273 // The desktop User Manager needs to be closed before the guest profile
275 if (switches::IsNewAvatarMenu())
277 profile_manager_
.reset();
280 // PromoResourceService must be destroyed after the keyed services and before
282 promo_resource_service_
.reset();
284 child_process_watcher_
.reset();
286 #if defined(ENABLE_EXTENSIONS)
287 ExtensionRendererState::GetInstance()->Shutdown();
289 media_file_system_registry_
.reset();
290 // Remove the global instance of the Storage Monitor now. Otherwise the
291 // FILE thread would be gone when we try to release it in the dtor and
292 // Valgrind would report a leak on almost every single browser_test.
293 // TODO(gbillock): Make this unnecessary.
294 storage_monitor::StorageMonitor::Destroy();
297 message_center::MessageCenter::Shutdown();
299 #if defined(ENABLE_CONFIGURATION_POLICY)
300 // The policy providers managed by |browser_policy_connector_| need to shut
301 // down while the IO and FILE threads are still alive. The monitoring
302 // framework owned by |browser_policy_connector_| relies on |gcm_driver_|, so
303 // this must be shutdown before |gcm_driver_| below.
304 if (browser_policy_connector_
)
305 browser_policy_connector_
->Shutdown();
308 // The |gcm_driver_| must shut down while the IO thread is still alive.
310 gcm_driver_
->Shutdown();
312 // Stop the watchdog thread before stopping other threads.
313 watchdog_thread_
.reset();
315 platform_part()->StartTearDown();
317 #if defined(ENABLE_WEBRTC)
318 // Cancel any uploads to release the system url request context references.
319 if (webrtc_log_uploader_
)
320 webrtc_log_uploader_
->StartShutdown();
324 local_state()->CommitPendingWrite();
327 void BrowserProcessImpl::PostDestroyThreads() {
328 // With the file_thread_ flushed, we can release any icon resources.
329 icon_manager_
.reset();
331 #if defined(ENABLE_WEBRTC)
332 // Must outlive the file thread.
333 webrtc_log_uploader_
.reset();
336 // Reset associated state right after actual thread is stopped,
337 // as io_thread_.global_ cleanup happens in CleanUp on the IO
338 // thread, i.e. as the thread exits its message loop.
340 // This is important also because in various places, the
341 // IOThread object being NULL is considered synonymous with the
342 // IO thread having stopped.
346 unsigned int BrowserProcessImpl::AddRefModule() {
347 DCHECK(CalledOnValidThread());
349 // CHECK(!IsShuttingDown());
350 if (IsShuttingDown()) {
351 // Copy the stacktrace which released the final reference onto our stack so
352 // it will be available in the crash report for inspection.
353 base::debug::StackTrace callstack
= release_last_reference_callstack_
;
354 base::debug::Alias(&callstack
);
360 return module_ref_count_
;
363 unsigned int BrowserProcessImpl::ReleaseModule() {
364 DCHECK(CalledOnValidThread());
365 DCHECK_NE(0u, module_ref_count_
);
367 if (0 == module_ref_count_
) {
368 release_last_reference_callstack_
= base::debug::StackTrace();
370 #if defined(ENABLE_PRINTING)
371 // Wait for the pending print jobs to finish. Don't do this later, since
372 // this might cause a nested message loop to run, and we don't want pending
373 // tasks to run once teardown has started.
374 print_job_manager_
->Shutdown();
377 #if defined(LEAK_SANITIZER)
378 // Check for memory leaks now, before we start shutting down threads. Doing
379 // this early means we won't report any shutdown-only leaks (as they have
380 // not yet happened at this point).
381 // If leaks are found, this will make the process exit immediately.
382 __lsan_do_leak_check();
385 CHECK(base::MessageLoop::current()->is_running());
387 #if defined(OS_MACOSX)
388 base::MessageLoop::current()->PostTask(
390 base::Bind(ChromeBrowserMainPartsMac::DidEndMainMessageLoop
));
392 base::MessageLoop::current()->Quit();
394 return module_ref_count_
;
399 // Used at the end of session to block the UI thread for completion of sentinel
400 // tasks on the set of threads used to persist profile data and local state.
401 // This is done to ensure that the data has been persisted to disk before
403 class RundownTaskCounter
:
404 public base::RefCountedThreadSafe
<RundownTaskCounter
> {
406 RundownTaskCounter();
408 // Posts a rundown task to |task_runner|, can be invoked an arbitrary number
409 // of times before calling TimedWait.
410 void Post(base::SequencedTaskRunner
* task_runner
);
412 // Waits until the count is zero or |max_time| has passed.
413 // This can only be called once per instance.
414 bool TimedWait(const base::TimeDelta
& max_time
);
417 friend class base::RefCountedThreadSafe
<RundownTaskCounter
>;
418 ~RundownTaskCounter() {}
420 // Decrements the counter and releases the waitable event on transition to
424 // The count starts at one to defer the possibility of one->zero transitions
425 // until TimedWait is called.
426 base::AtomicRefCount count_
;
427 base::WaitableEvent waitable_event_
;
429 DISALLOW_COPY_AND_ASSIGN(RundownTaskCounter
);
432 RundownTaskCounter::RundownTaskCounter()
433 : count_(1), waitable_event_(true, false) {
436 void RundownTaskCounter::Post(base::SequencedTaskRunner
* task_runner
) {
437 // As the count starts off at one, it should never get to zero unless
438 // TimedWait has been called.
439 DCHECK(!base::AtomicRefCountIsZero(&count_
));
441 base::AtomicRefCountInc(&count_
);
443 // The task must be non-nestable to guarantee that it runs after all tasks
444 // currently scheduled on |task_runner| have completed.
445 task_runner
->PostNonNestableTask(FROM_HERE
,
446 base::Bind(&RundownTaskCounter::Decrement
, this));
449 void RundownTaskCounter::Decrement() {
450 if (!base::AtomicRefCountDec(&count_
))
451 waitable_event_
.Signal();
454 bool RundownTaskCounter::TimedWait(const base::TimeDelta
& max_time
) {
455 // Decrement the excess count from the constructor.
458 return waitable_event_
.TimedWait(max_time
);
463 void BrowserProcessImpl::EndSession() {
464 // Mark all the profiles as clean.
465 ProfileManager
* pm
= profile_manager();
466 std::vector
<Profile
*> profiles(pm
->GetLoadedProfiles());
467 scoped_refptr
<RundownTaskCounter
> rundown_counter(new RundownTaskCounter());
468 for (size_t i
= 0; i
< profiles
.size(); ++i
) {
469 Profile
* profile
= profiles
[i
];
470 profile
->SetExitType(Profile::EXIT_SESSION_ENDED
);
471 if (profile
->GetPrefs()) {
472 profile
->GetPrefs()->CommitPendingWrite();
473 rundown_counter
->Post(profile
->GetIOTaskRunner().get());
477 // Tell the metrics service it was cleanly shutdown.
478 metrics::MetricsService
* metrics
= g_browser_process
->metrics_service();
479 if (metrics
&& local_state()) {
480 metrics
->RecordStartOfSessionEnd();
481 #if !defined(OS_CHROMEOS)
482 // MetricsService lazily writes to prefs, force it to write now.
483 // On ChromeOS, chrome gets killed when hangs, so no need to
484 // commit metrics::prefs::kStabilitySessionEndCompleted change immediately.
485 local_state()->CommitPendingWrite();
487 rundown_counter
->Post(local_state_task_runner_
.get());
491 // http://crbug.com/125207
492 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
494 // We must write that the profile and metrics service shutdown cleanly,
495 // otherwise on startup we'll think we crashed. So we block until done and
496 // then proceed with normal shutdown.
498 // If you change the condition here, be sure to also change
499 // ProfileBrowserTests to match.
500 #if defined(USE_X11) || defined(OS_WIN) || defined(USE_OZONE)
501 // Do a best-effort wait on the successful countdown of rundown tasks. Note
502 // that if we don't complete "quickly enough", Windows will terminate our
505 // On Windows, we previously posted a message to FILE and then ran a nested
506 // message loop, waiting for that message to be processed until quitting.
507 // However, doing so means that other messages will also be processed. In
508 // particular, if the GPU process host notices that the GPU has been killed
509 // during shutdown, it races exiting the nested loop with the process host
510 // blocking the message loop attempting to re-establish a connection to the
511 // GPU process synchronously. Because the system may not be allowing
512 // processes to launch, this can result in a hang. See
513 // http://crbug.com/318527.
514 rundown_counter
->TimedWait(
515 base::TimeDelta::FromSeconds(kEndSessionTimeoutSeconds
));
521 MetricsServicesManager
* BrowserProcessImpl::GetMetricsServicesManager() {
522 DCHECK(CalledOnValidThread());
523 if (!metrics_services_manager_
)
524 metrics_services_manager_
.reset(new MetricsServicesManager(local_state()));
525 return metrics_services_manager_
.get();
528 metrics::MetricsService
* BrowserProcessImpl::metrics_service() {
529 DCHECK(CalledOnValidThread());
530 return GetMetricsServicesManager()->GetMetricsService();
533 rappor::RapporService
* BrowserProcessImpl::rappor_service() {
534 DCHECK(CalledOnValidThread());
535 return GetMetricsServicesManager()->GetRapporService();
538 IOThread
* BrowserProcessImpl::io_thread() {
539 DCHECK(CalledOnValidThread());
540 DCHECK(io_thread_
.get());
541 return io_thread_
.get();
544 WatchDogThread
* BrowserProcessImpl::watchdog_thread() {
545 DCHECK(CalledOnValidThread());
546 if (!created_watchdog_thread_
)
547 CreateWatchdogThread();
548 DCHECK(watchdog_thread_
.get() != NULL
);
549 return watchdog_thread_
.get();
552 ProfileManager
* BrowserProcessImpl::profile_manager() {
553 DCHECK(CalledOnValidThread());
554 if (!created_profile_manager_
)
555 CreateProfileManager();
556 return profile_manager_
.get();
559 PrefService
* BrowserProcessImpl::local_state() {
560 DCHECK(CalledOnValidThread());
561 if (!created_local_state_
)
563 return local_state_
.get();
566 net::URLRequestContextGetter
* BrowserProcessImpl::system_request_context() {
567 DCHECK(CalledOnValidThread());
568 return io_thread()->system_url_request_context_getter();
571 chrome_variations::VariationsService
* BrowserProcessImpl::variations_service() {
572 DCHECK(CalledOnValidThread());
573 return GetMetricsServicesManager()->GetVariationsService();
576 PromoResourceService
* BrowserProcessImpl::promo_resource_service() {
577 DCHECK(CalledOnValidThread());
578 return promo_resource_service_
.get();
581 BrowserProcessPlatformPart
* BrowserProcessImpl::platform_part() {
582 return platform_part_
.get();
585 extensions::EventRouterForwarder
*
586 BrowserProcessImpl::extension_event_router_forwarder() {
587 #if defined(ENABLE_EXTENSIONS)
588 return extension_event_router_forwarder_
.get();
594 NotificationUIManager
* BrowserProcessImpl::notification_ui_manager() {
595 DCHECK(CalledOnValidThread());
596 if (!created_notification_ui_manager_
)
597 CreateNotificationUIManager();
598 return notification_ui_manager_
.get();
601 message_center::MessageCenter
* BrowserProcessImpl::message_center() {
602 DCHECK(CalledOnValidThread());
603 return message_center::MessageCenter::Get();
606 policy::BrowserPolicyConnector
* BrowserProcessImpl::browser_policy_connector() {
607 DCHECK(CalledOnValidThread());
608 #if defined(ENABLE_CONFIGURATION_POLICY)
609 if (!created_browser_policy_connector_
) {
610 DCHECK(!browser_policy_connector_
);
611 browser_policy_connector_
= platform_part_
->CreateBrowserPolicyConnector();
612 created_browser_policy_connector_
= true;
614 return browser_policy_connector_
.get();
620 policy::PolicyService
* BrowserProcessImpl::policy_service() {
621 #if defined(ENABLE_CONFIGURATION_POLICY)
622 return browser_policy_connector()->GetPolicyService();
624 if (!policy_service_
.get())
625 policy_service_
.reset(new policy::PolicyServiceStub());
626 return policy_service_
.get();
630 IconManager
* BrowserProcessImpl::icon_manager() {
631 DCHECK(CalledOnValidThread());
632 if (!created_icon_manager_
)
634 return icon_manager_
.get();
637 GLStringManager
* BrowserProcessImpl::gl_string_manager() {
638 DCHECK(CalledOnValidThread());
639 if (!gl_string_manager_
.get())
640 gl_string_manager_
.reset(new GLStringManager());
641 return gl_string_manager_
.get();
644 GpuModeManager
* BrowserProcessImpl::gpu_mode_manager() {
645 DCHECK(CalledOnValidThread());
646 if (!gpu_mode_manager_
.get())
647 gpu_mode_manager_
.reset(new GpuModeManager());
648 return gpu_mode_manager_
.get();
651 void BrowserProcessImpl::CreateDevToolsHttpProtocolHandler(
652 chrome::HostDesktopType host_desktop_type
,
653 const std::string
& ip
,
655 DCHECK(CalledOnValidThread());
656 #if !defined(OS_ANDROID)
657 // StartupBrowserCreator::LaunchBrowser can be run multiple times when browser
658 // is started with several profiles or existing browser process is reused.
659 if (!remote_debugging_server_
.get()) {
660 remote_debugging_server_
.reset(
661 new RemoteDebuggingServer(host_desktop_type
, ip
, port
));
666 bool BrowserProcessImpl::IsShuttingDown() {
667 DCHECK(CalledOnValidThread());
668 return did_start_
&& 0 == module_ref_count_
;
671 printing::PrintJobManager
* BrowserProcessImpl::print_job_manager() {
672 DCHECK(CalledOnValidThread());
673 return print_job_manager_
.get();
676 printing::PrintPreviewDialogController
*
677 BrowserProcessImpl::print_preview_dialog_controller() {
678 #if defined(ENABLE_PRINT_PREVIEW)
679 DCHECK(CalledOnValidThread());
680 if (!print_preview_dialog_controller_
.get())
681 CreatePrintPreviewDialogController();
682 return print_preview_dialog_controller_
.get();
689 printing::BackgroundPrintingManager
*
690 BrowserProcessImpl::background_printing_manager() {
691 #if defined(ENABLE_PRINT_PREVIEW)
692 DCHECK(CalledOnValidThread());
693 if (!background_printing_manager_
.get())
694 CreateBackgroundPrintingManager();
695 return background_printing_manager_
.get();
702 IntranetRedirectDetector
* BrowserProcessImpl::intranet_redirect_detector() {
703 DCHECK(CalledOnValidThread());
704 if (!intranet_redirect_detector_
.get())
705 CreateIntranetRedirectDetector();
706 return intranet_redirect_detector_
.get();
709 const std::string
& BrowserProcessImpl::GetApplicationLocale() {
710 DCHECK(!locale_
.empty());
714 void BrowserProcessImpl::SetApplicationLocale(const std::string
& locale
) {
716 #if defined(ENABLE_EXTENSIONS)
717 extension_l10n_util::SetProcessLocale(locale
);
719 chrome::ChromeContentBrowserClient::SetApplicationLocale(locale
);
720 translate::TranslateDownloadManager::GetInstance()->set_application_locale(
724 DownloadStatusUpdater
* BrowserProcessImpl::download_status_updater() {
725 return download_status_updater_
.get();
728 MediaFileSystemRegistry
* BrowserProcessImpl::media_file_system_registry() {
729 #if defined(ENABLE_EXTENSIONS)
730 if (!media_file_system_registry_
)
731 media_file_system_registry_
.reset(new MediaFileSystemRegistry());
732 return media_file_system_registry_
.get();
738 bool BrowserProcessImpl::created_local_state() const {
739 return created_local_state_
;
742 #if defined(ENABLE_WEBRTC)
743 WebRtcLogUploader
* BrowserProcessImpl::webrtc_log_uploader() {
744 if (!webrtc_log_uploader_
.get())
745 webrtc_log_uploader_
.reset(new WebRtcLogUploader());
746 return webrtc_log_uploader_
.get();
750 network_time::NetworkTimeTracker
* BrowserProcessImpl::network_time_tracker() {
751 if (!network_time_tracker_
) {
752 network_time_tracker_
.reset(new network_time::NetworkTimeTracker(
753 scoped_ptr
<base::TickClock
>(new base::DefaultTickClock()),
756 return network_time_tracker_
.get();
759 gcm::GCMDriver
* BrowserProcessImpl::gcm_driver() {
760 DCHECK(CalledOnValidThread());
763 return gcm_driver_
.get();
766 memory::OomPriorityManager
* BrowserProcessImpl::GetOomPriorityManager() {
767 DCHECK(CalledOnValidThread());
768 #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS)
769 if (!oom_priority_manager_
.get())
770 oom_priority_manager_
.reset(new memory::OomPriorityManager());
771 return oom_priority_manager_
.get();
777 ShellIntegration::DefaultWebClientState
778 BrowserProcessImpl::CachedDefaultWebClientState() {
779 return cached_default_web_client_state_
;
783 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple
* registry
) {
784 registry
->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled
,
786 // This policy needs to be defined before the net subsystem is initialized,
788 registry
->RegisterIntegerPref(prefs::kMaxConnectionsPerProxy
,
789 net::kDefaultMaxSocketsPerProxyServer
);
791 registry
->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt
, false);
793 #if defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
794 registry
->RegisterBooleanPref(prefs::kEulaAccepted
, false);
795 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
797 if (base::win::GetVersion() >= base::win::VERSION_WIN7
) {
798 registry
->RegisterStringPref(prefs::kRelaunchMode
,
799 upgrade_util::kRelaunchModeDefault
);
803 // TODO(brettw,*): this comment about ResourceBundle was here since
804 // initial commit. This comment seems unrelated, bit-rotten and
805 // a candidate for removal.
806 // Initialize ResourceBundle which handles files loaded from external
807 // sources. This has to be done before uninstall code path and before prefs
809 registry
->RegisterStringPref(prefs::kApplicationLocale
, std::string());
810 #if defined(OS_CHROMEOS)
811 registry
->RegisterStringPref(prefs::kOwnerLocale
, std::string());
812 registry
->RegisterStringPref(prefs::kHardwareKeyboardLayout
,
814 #endif // defined(OS_CHROMEOS)
815 #if !defined(OS_CHROMEOS)
816 registry
->RegisterBooleanPref(
817 prefs::kMetricsReportingEnabled
,
818 GoogleUpdateSettings::GetCollectStatsConsent());
819 #endif // !defined(OS_CHROMEOS)
821 #if defined(OS_ANDROID)
822 registry
->RegisterBooleanPref(
823 prefs::kCrashReportingEnabled
, false);
824 #endif // defined(OS_ANDROID)
827 DownloadRequestLimiter
* BrowserProcessImpl::download_request_limiter() {
828 DCHECK(CalledOnValidThread());
829 if (!download_request_limiter_
.get())
830 download_request_limiter_
= new DownloadRequestLimiter();
831 return download_request_limiter_
.get();
834 BackgroundModeManager
* BrowserProcessImpl::background_mode_manager() {
835 DCHECK(CalledOnValidThread());
836 #if defined(ENABLE_BACKGROUND)
837 if (!background_mode_manager_
.get())
838 CreateBackgroundModeManager();
839 return background_mode_manager_
.get();
846 void BrowserProcessImpl::set_background_mode_manager_for_test(
847 scoped_ptr
<BackgroundModeManager
> manager
) {
848 #if defined(ENABLE_BACKGROUND)
849 background_mode_manager_
= manager
.Pass();
853 StatusTray
* BrowserProcessImpl::status_tray() {
854 DCHECK(CalledOnValidThread());
855 if (!status_tray_
.get())
857 return status_tray_
.get();
861 SafeBrowsingService
* BrowserProcessImpl::safe_browsing_service() {
862 DCHECK(CalledOnValidThread());
863 if (!created_safe_browsing_service_
)
864 CreateSafeBrowsingService();
865 return safe_browsing_service_
.get();
868 safe_browsing::ClientSideDetectionService
*
869 BrowserProcessImpl::safe_browsing_detection_service() {
870 DCHECK(CalledOnValidThread());
871 if (safe_browsing_service())
872 return safe_browsing_service()->safe_browsing_detection_service();
876 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
877 void BrowserProcessImpl::StartAutoupdateTimer() {
878 autoupdate_timer_
.Start(FROM_HERE
,
879 base::TimeDelta::FromHours(kUpdateCheckIntervalHours
),
881 &BrowserProcessImpl::OnAutoupdateTimer
);
885 ChromeNetLog
* BrowserProcessImpl::net_log() {
886 return net_log_
.get();
889 component_updater::ComponentUpdateService
*
890 BrowserProcessImpl::component_updater() {
891 if (!component_updater_
.get()) {
892 if (!BrowserThread::CurrentlyOn(BrowserThread::UI
))
894 scoped_refptr
<update_client::Configurator
> configurator
=
895 component_updater::MakeChromeComponentUpdaterConfigurator(
896 base::CommandLine::ForCurrentProcess(),
897 io_thread()->system_url_request_context_getter());
898 // Creating the component updater does not do anything, components
899 // need to be registered and Start() needs to be called.
900 component_updater_
.reset(component_updater::ComponentUpdateServiceFactory(
901 configurator
).release());
903 return component_updater_
.get();
906 CRLSetFetcher
* BrowserProcessImpl::crl_set_fetcher() {
907 if (!crl_set_fetcher_
)
908 crl_set_fetcher_
= new CRLSetFetcher();
909 return crl_set_fetcher_
.get();
912 component_updater::PnaclComponentInstaller
*
913 BrowserProcessImpl::pnacl_component_installer() {
914 #if !defined(DISABLE_NACL)
915 if (!pnacl_component_installer_
) {
916 pnacl_component_installer_
=
917 new component_updater::PnaclComponentInstaller();
919 return pnacl_component_installer_
.get();
925 component_updater::SupervisedUserWhitelistInstaller
*
926 BrowserProcessImpl::supervised_user_whitelist_installer() {
927 if (!supervised_user_whitelist_installer_
) {
928 supervised_user_whitelist_installer_
=
929 component_updater::SupervisedUserWhitelistInstaller::Create(
930 component_updater(), &profile_manager()->GetProfileInfoCache(),
933 return supervised_user_whitelist_installer_
.get();
936 void BrowserProcessImpl::ResourceDispatcherHostCreated() {
937 resource_dispatcher_host_delegate_
.reset(
938 new ChromeResourceDispatcherHostDelegate
);
939 ResourceDispatcherHost::Get()->SetDelegate(
940 resource_dispatcher_host_delegate_
.get());
942 pref_change_registrar_
.Add(
943 prefs::kAllowCrossOriginAuthPrompt
,
944 base::Bind(&BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy
,
945 base::Unretained(this)));
946 ApplyAllowCrossOriginAuthPromptPolicy();
949 void BrowserProcessImpl::CreateWatchdogThread() {
950 DCHECK(!created_watchdog_thread_
&& watchdog_thread_
.get() == NULL
);
951 created_watchdog_thread_
= true;
953 scoped_ptr
<WatchDogThread
> thread(new WatchDogThread());
954 base::Thread::Options options
;
955 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
956 if (!thread
->StartWithOptions(options
))
958 watchdog_thread_
.swap(thread
);
961 void BrowserProcessImpl::CreateProfileManager() {
962 DCHECK(!created_profile_manager_
&& profile_manager_
.get() == NULL
);
963 created_profile_manager_
= true;
965 base::FilePath user_data_dir
;
966 PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
);
967 profile_manager_
.reset(new ProfileManager(user_data_dir
));
970 void BrowserProcessImpl::CreateLocalState() {
971 DCHECK(!created_local_state_
&& local_state_
.get() == NULL
);
972 created_local_state_
= true;
974 base::FilePath local_state_path
;
975 CHECK(PathService::Get(chrome::FILE_LOCAL_STATE
, &local_state_path
));
976 scoped_refptr
<PrefRegistrySimple
> pref_registry
= new PrefRegistrySimple
;
978 // Register local state preferences.
979 chrome::RegisterLocalState(pref_registry
.get());
982 chrome_prefs::CreateLocalState(local_state_path
,
983 local_state_task_runner_
.get(),
988 pref_change_registrar_
.Init(local_state_
.get());
990 // Initialize the notification for the default browser setting policy.
991 pref_change_registrar_
.Add(
992 prefs::kDefaultBrowserSettingEnabled
,
993 base::Bind(&BrowserProcessImpl::ApplyDefaultBrowserPolicy
,
994 base::Unretained(this)));
996 // This preference must be kept in sync with external values; update them
997 // whenever the preference or its controlling policy changes.
998 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
999 pref_change_registrar_
.Add(
1000 prefs::kMetricsReportingEnabled
,
1001 base::Bind(&BrowserProcessImpl::ApplyMetricsReportingPolicy
,
1002 base::Unretained(this)));
1005 int max_per_proxy
= local_state_
->GetInteger(prefs::kMaxConnectionsPerProxy
);
1006 net::ClientSocketPoolManager::set_max_sockets_per_proxy_server(
1007 net::HttpNetworkSession::NORMAL_SOCKET_POOL
,
1008 std::max(std::min(max_per_proxy
, 99),
1009 net::ClientSocketPoolManager::max_sockets_per_group(
1010 net::HttpNetworkSession::NORMAL_SOCKET_POOL
)));
1013 void BrowserProcessImpl::PreCreateThreads() {
1015 new IOThread(local_state(), policy_service(), net_log_
.get(),
1016 extension_event_router_forwarder()));
1019 void BrowserProcessImpl::PreMainMessageLoopRun() {
1020 TRACE_EVENT0("startup", "BrowserProcessImpl::PreMainMessageLoopRun");
1021 SCOPED_UMA_HISTOGRAM_TIMER(
1022 "Startup.BrowserProcessImpl_PreMainMessageLoopRunTime");
1024 #if defined(ENABLE_CONFIGURATION_POLICY)
1025 // browser_policy_connector() is created very early because local_state()
1026 // needs policy to be initialized with the managed preference values.
1027 // However, policy fetches from the network and loading of disk caches
1028 // requires that threads are running; this Init() call lets the connector
1029 // resume its initialization now that the loops are spinning and the
1030 // system request context is available for the fetchers.
1031 browser_policy_connector()->Init(local_state(), system_request_context());
1034 if (local_state_
->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled
))
1035 ApplyDefaultBrowserPolicy();
1037 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1038 ApplyMetricsReportingPolicy();
1041 #if defined(ENABLE_PLUGINS)
1042 PluginService
* plugin_service
= PluginService::GetInstance();
1043 plugin_service
->SetFilter(ChromePluginServiceFilter::GetInstance());
1044 plugin_service
->StartWatchingPlugins();
1046 #if defined(OS_POSIX)
1047 // Also find plugins in a user-specific plugins dir,
1048 // e.g. ~/.config/chromium/Plugins.
1049 const base::CommandLine
& cmd_line
= *base::CommandLine::ForCurrentProcess();
1050 if (!cmd_line
.HasSwitch(switches::kDisablePluginsDiscovery
)) {
1051 base::FilePath user_data_dir
;
1052 if (PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
))
1053 plugin_service
->AddExtraPluginDir(user_data_dir
.Append("Plugins"));
1057 // Triggers initialization of the singleton instance on UI thread.
1058 PluginFinder::GetInstance()->Init();
1060 #if defined(ENABLE_PLUGIN_INSTALLATION)
1061 DCHECK(!plugins_resource_service_
.get());
1062 plugins_resource_service_
.reset(new PluginsResourceService(local_state()));
1063 plugins_resource_service_
->Init();
1065 #endif // defined(ENABLE_PLUGINS)
1067 const base::CommandLine
& command_line
=
1068 *base::CommandLine::ForCurrentProcess();
1069 if (!command_line
.HasSwitch(switches::kDisableWebResources
)) {
1070 DCHECK(!promo_resource_service_
.get());
1071 promo_resource_service_
.reset(
1072 new PromoResourceService(local_state(), chrome::GetChannel()));
1073 promo_resource_service_
->StartAfterDelay();
1076 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1077 storage_monitor::StorageMonitor::Create();
1080 child_process_watcher_
.reset(new ChromeChildProcessWatcher());
1082 CacheDefaultWebClientState();
1084 platform_part_
->PreMainMessageLoopRun();
1087 void BrowserProcessImpl::CreateIconManager() {
1088 DCHECK(!created_icon_manager_
&& icon_manager_
.get() == NULL
);
1089 created_icon_manager_
= true;
1090 icon_manager_
.reset(new IconManager
);
1093 void BrowserProcessImpl::CreateIntranetRedirectDetector() {
1094 DCHECK(intranet_redirect_detector_
.get() == NULL
);
1095 scoped_ptr
<IntranetRedirectDetector
> intranet_redirect_detector(
1096 new IntranetRedirectDetector
);
1097 intranet_redirect_detector_
.swap(intranet_redirect_detector
);
1100 void BrowserProcessImpl::CreateNotificationUIManager() {
1101 #if defined(ENABLE_NOTIFICATIONS)
1102 DCHECK(notification_ui_manager_
.get() == NULL
);
1103 notification_ui_manager_
.reset(NotificationUIManager::Create(local_state()));
1104 created_notification_ui_manager_
= true;
1108 void BrowserProcessImpl::CreateBackgroundModeManager() {
1109 #if defined(ENABLE_BACKGROUND)
1110 DCHECK(background_mode_manager_
.get() == NULL
);
1111 background_mode_manager_
.reset(
1112 new BackgroundModeManager(*base::CommandLine::ForCurrentProcess(),
1113 &profile_manager()->GetProfileInfoCache()));
1117 void BrowserProcessImpl::CreateStatusTray() {
1118 DCHECK(status_tray_
.get() == NULL
);
1119 status_tray_
.reset(StatusTray::Create());
1122 void BrowserProcessImpl::CreatePrintPreviewDialogController() {
1123 #if defined(ENABLE_PRINT_PREVIEW)
1124 DCHECK(print_preview_dialog_controller_
.get() == NULL
);
1125 print_preview_dialog_controller_
=
1126 new printing::PrintPreviewDialogController();
1132 void BrowserProcessImpl::CreateBackgroundPrintingManager() {
1133 #if defined(ENABLE_PRINT_PREVIEW)
1134 DCHECK(background_printing_manager_
.get() == NULL
);
1135 background_printing_manager_
.reset(new printing::BackgroundPrintingManager());
1141 void BrowserProcessImpl::CreateSafeBrowsingService() {
1142 DCHECK(safe_browsing_service_
.get() == NULL
);
1143 // Set this flag to true so that we don't retry indefinitely to
1144 // create the service class if there was an error.
1145 created_safe_browsing_service_
= true;
1146 #if defined(SAFE_BROWSING_SERVICE)
1147 safe_browsing_service_
= SafeBrowsingService::CreateSafeBrowsingService();
1148 safe_browsing_service_
->Initialize();
1152 void BrowserProcessImpl::CreateGCMDriver() {
1153 DCHECK(!gcm_driver_
);
1155 #if defined(OS_ANDROID)
1156 // Android's GCMDriver currently makes the assumption that it's a singleton.
1157 // Until this gets fixed, instantiating multiple Java GCMDrivers will throw
1158 // an exception, but because they're only initialized on demand these crashes
1159 // would be very difficult to triage. See http://crbug.com/437827.
1162 base::FilePath store_path
;
1163 CHECK(PathService::Get(chrome::DIR_GLOBAL_GCM_STORE
, &store_path
));
1164 gcm_driver_
= gcm::CreateGCMDriverDesktop(
1165 make_scoped_ptr(new gcm::GCMClientFactory
),
1168 system_request_context());
1169 #endif // defined(OS_ANDROID)
1172 void BrowserProcessImpl::ApplyDefaultBrowserPolicy() {
1173 if (local_state()->GetBoolean(prefs::kDefaultBrowserSettingEnabled
)) {
1174 scoped_refptr
<ShellIntegration::DefaultWebClientWorker
>
1175 set_browser_worker
= new ShellIntegration::DefaultBrowserWorker(NULL
);
1176 set_browser_worker
->StartSetAsDefault();
1180 void BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy() {
1181 bool value
= local_state()->GetBoolean(prefs::kAllowCrossOriginAuthPrompt
);
1182 ResourceDispatcherHost::Get()->SetAllowCrossOriginAuthPrompt(value
);
1185 void BrowserProcessImpl::ApplyMetricsReportingPolicy() {
1186 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1187 CHECK(BrowserThread::PostTask(
1188 BrowserThread::FILE, FROM_HERE
,
1190 base::IgnoreResult(&GoogleUpdateSettings::SetCollectStatsConsent
),
1191 local_state()->GetBoolean(prefs::kMetricsReportingEnabled
))));
1195 void BrowserProcessImpl::CacheDefaultWebClientState() {
1196 #if defined(OS_CHROMEOS)
1197 cached_default_web_client_state_
= ShellIntegration::IS_DEFAULT
;
1198 #elif !defined(OS_ANDROID) && !defined(OS_IOS)
1199 cached_default_web_client_state_
= ShellIntegration::GetDefaultBrowser();
1203 // Mac is currently not supported.
1204 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
1206 bool BrowserProcessImpl::CanAutorestartForUpdate() const {
1207 // Check if browser is in the background and if it needs to be restarted to
1208 // apply a pending update.
1209 return chrome::GetTotalBrowserCount() == 0 && chrome::WillKeepAlive() &&
1210 upgrade_util::IsUpdatePendingRestart();
1213 // Switches to add when auto-restarting Chrome.
1214 const char* const kSwitchesToAddOnAutorestart
[] = {
1215 switches::kNoStartupWindow
1218 void BrowserProcessImpl::RestartBackgroundInstance() {
1219 base::CommandLine
* old_cl
= base::CommandLine::ForCurrentProcess();
1220 scoped_ptr
<base::CommandLine
> new_cl(
1221 new base::CommandLine(old_cl
->GetProgram()));
1223 std::map
<std::string
, base::CommandLine::StringType
> switches
=
1224 old_cl
->GetSwitches();
1226 switches::RemoveSwitchesForAutostart(&switches
);
1228 // Append the rest of the switches (along with their values, if any)
1229 // to the new command line
1230 for (std::map
<std::string
, base::CommandLine::StringType
>::const_iterator i
=
1232 i
!= switches
.end(); ++i
) {
1233 base::CommandLine::StringType switch_value
= i
->second
;
1234 if (switch_value
.length() > 0) {
1235 new_cl
->AppendSwitchNative(i
->first
, i
->second
);
1237 new_cl
->AppendSwitch(i
->first
);
1241 // Ensure that our desired switches are set on the new process.
1242 for (size_t i
= 0; i
< arraysize(kSwitchesToAddOnAutorestart
); ++i
) {
1243 if (!new_cl
->HasSwitch(kSwitchesToAddOnAutorestart
[i
]))
1244 new_cl
->AppendSwitch(kSwitchesToAddOnAutorestart
[i
]);
1247 DLOG(WARNING
) << "Shutting down current instance of the browser.";
1248 chrome::AttemptExit();
1250 // Transfer ownership to Upgrade.
1251 upgrade_util::SetNewCommandLine(new_cl
.release());
1254 void BrowserProcessImpl::OnAutoupdateTimer() {
1255 if (CanAutorestartForUpdate()) {
1256 DLOG(WARNING
) << "Detected update. Restarting browser.";
1257 RestartBackgroundInstance();
1261 #endif // (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)