Roll src/third_party/WebKit f298044:aa8346d (svn 202628:202629)
[chromium-blink-merge.git] / chrome / browser / browser_process_impl.cc
blobab85392133582ca532a11f5611265e014b34b7a5
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"
7 #include <algorithm>
8 #include <map>
9 #include <vector>
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/chrome_metrics_service_accessor.h"
47 #include "chrome/browser/metrics/metrics_services_manager.h"
48 #include "chrome/browser/metrics/thread_watcher.h"
49 #include "chrome/browser/net/chrome_net_log_helper.h"
50 #include "chrome/browser/net/crl_set_fetcher.h"
51 #include "chrome/browser/notifications/notification_ui_manager.h"
52 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
53 #include "chrome/browser/plugins/plugin_finder.h"
54 #include "chrome/browser/prefs/browser_prefs.h"
55 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
56 #include "chrome/browser/printing/background_printing_manager.h"
57 #include "chrome/browser/printing/print_job_manager.h"
58 #include "chrome/browser/printing/print_preview_dialog_controller.h"
59 #include "chrome/browser/profiles/profile_manager.h"
60 #include "chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h"
61 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
62 #include "chrome/browser/shell_integration.h"
63 #include "chrome/browser/status_icons/status_tray.h"
64 #include "chrome/browser/ui/browser_dialogs.h"
65 #include "chrome/browser/ui/browser_finder.h"
66 #include "chrome/browser/ui/user_manager.h"
67 #include "chrome/browser/update_client/chrome_update_query_params_delegate.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/net_log/chrome_net_log.h"
82 #include "components/network_time/network_time_tracker.h"
83 #include "components/policy/core/common/policy_service.h"
84 #include "components/safe_json/safe_json_parser.h"
85 #include "components/signin/core/common/profile_management_switches.h"
86 #include "components/translate/core/browser/translate_download_manager.h"
87 #include "components/update_client/update_query_params.h"
88 #include "components/web_resource/promo_resource_service.h"
89 #include "components/web_resource/web_resource_pref_names.h"
90 #include "content/public/browser/browser_thread.h"
91 #include "content/public/browser/child_process_security_policy.h"
92 #include "content/public/browser/notification_details.h"
93 #include "content/public/browser/plugin_service.h"
94 #include "content/public/browser/render_process_host.h"
95 #include "content/public/browser/resource_dispatcher_host.h"
96 #include "content/public/browser/service_worker_context.h"
97 #include "content/public/browser/storage_partition.h"
98 #include "extensions/common/constants.h"
99 #include "net/socket/client_socket_pool_manager.h"
100 #include "net/url_request/url_request_context_getter.h"
101 #include "ui/base/idle/idle.h"
102 #include "ui/base/l10n/l10n_util.h"
103 #include "ui/message_center/message_center.h"
105 #if defined(OS_WIN)
106 #include "base/win/windows_version.h"
107 #include "ui/views/focus/view_storage.h"
108 #elif defined(OS_MACOSX)
109 #include "chrome/browser/chrome_browser_main_mac.h"
110 #endif
112 #if !defined(OS_ANDROID)
113 #include "chrome/browser/chrome_device_client.h"
114 #include "chrome/browser/services/gcm/gcm_desktop_utils.h"
115 #include "components/gcm_driver/gcm_client_factory.h"
116 #endif
118 #if defined(ENABLE_BACKGROUND)
119 #include "chrome/browser/background/background_mode_manager.h"
120 #endif
122 #if defined(ENABLE_CONFIGURATION_POLICY)
123 #include "components/policy/core/browser/browser_policy_connector.h"
124 #else
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"
136 #endif
138 #if !defined(DISABLE_NACL)
139 #include "chrome/browser/component_updater/pnacl_component_installer.h"
140 #endif
142 #if defined(ENABLE_PLUGIN_INSTALLATION)
143 #include "chrome/browser/plugins/plugins_resource_service.h"
144 #endif
146 #if defined(ENABLE_WEBRTC)
147 #include "chrome/browser/media/webrtc_log_uploader.h"
148 #endif
150 #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS)
151 #include "chrome/browser/memory/oom_priority_manager.h"
152 #endif
154 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
155 // How often to check if the persistent instance of Chrome needs to restart
156 // to install an update.
157 static const int kUpdateCheckIntervalHours = 6;
158 #endif
160 #if defined(USE_X11) || defined(OS_WIN) || defined(USE_OZONE)
161 // How long to wait for the File thread to complete during EndSession, on Linux
162 // and Windows. We have a timeout here because we're unable to run the UI
163 // messageloop and there's some deadlock risk. Our only option is to exit
164 // anyway.
165 static const int kEndSessionTimeoutSeconds = 10;
166 #endif
168 using content::BrowserThread;
169 using content::ChildProcessSecurityPolicy;
170 using content::PluginService;
171 using content::ResourceDispatcherHost;
173 BrowserProcessImpl::BrowserProcessImpl(
174 base::SequencedTaskRunner* local_state_task_runner,
175 const base::CommandLine& command_line)
176 : created_watchdog_thread_(false),
177 created_browser_policy_connector_(false),
178 created_profile_manager_(false),
179 created_local_state_(false),
180 created_icon_manager_(false),
181 created_notification_ui_manager_(false),
182 created_safe_browsing_service_(false),
183 module_ref_count_(0),
184 did_start_(false),
185 download_status_updater_(new DownloadStatusUpdater),
186 local_state_task_runner_(local_state_task_runner),
187 cached_default_web_client_state_(ShellIntegration::UNKNOWN_DEFAULT) {
188 g_browser_process = this;
189 platform_part_.reset(new BrowserProcessPlatformPart());
191 #if defined(ENABLE_PRINTING)
192 // Must be created after the NotificationService.
193 print_job_manager_.reset(new printing::PrintJobManager);
194 #endif
196 base::FilePath net_log_path;
197 if (command_line.HasSwitch(switches::kLogNetLog))
198 net_log_path = command_line.GetSwitchValuePath(switches::kLogNetLog);
199 net_log_.reset(new net_log::ChromeNetLog(
200 net_log_path, GetNetCaptureModeFromCommandLine(command_line),
201 command_line.GetCommandLineString(), chrome::GetChannelString()));
203 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
204 extensions::kExtensionScheme);
205 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
206 extensions::kExtensionResourceScheme);
207 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
208 chrome::kChromeSearchScheme);
210 #if defined(OS_MACOSX)
211 ui::InitIdleMonitor();
212 #endif
214 #if !defined(OS_ANDROID)
215 device_client_.reset(new ChromeDeviceClient);
216 #endif
218 #if defined(ENABLE_EXTENSIONS)
219 // Athena sets its own instance during Athena's init process.
220 extensions::AppWindowClient::Set(ChromeAppWindowClient::GetInstance());
222 extension_event_router_forwarder_ = new extensions::EventRouterForwarder;
223 ExtensionRendererState::GetInstance()->Init();
225 extensions::ExtensionsClient::Set(
226 extensions::ChromeExtensionsClient::GetInstance());
228 extensions_browser_client_.reset(
229 new extensions::ChromeExtensionsBrowserClient);
230 extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get());
231 #endif
233 message_center::MessageCenter::Initialize();
235 update_client::UpdateQueryParams::SetDelegate(
236 ChromeUpdateQueryParamsDelegate::GetInstance());
239 BrowserProcessImpl::~BrowserProcessImpl() {
240 tracked_objects::ThreadData::EnsureCleanupWasCalled(4);
242 g_browser_process = NULL;
245 void BrowserProcessImpl::StartTearDown() {
246 TRACE_EVENT0("shutdown", "BrowserProcessImpl::StartTearDown");
247 // We need to destroy the MetricsServicesManager, IntranetRedirectDetector,
248 // PromoResourceService, and SafeBrowsing ClientSideDetectionService (owned by
249 // the SafeBrowsingService) before the io_thread_ gets destroyed, since their
250 // destructors can call the URLFetcher destructor, which does a
251 // PostDelayedTask operation on the IO thread. (The IO thread will handle that
252 // URLFetcher operation before going away.)
253 metrics_services_manager_.reset();
254 intranet_redirect_detector_.reset();
255 #if defined(SAFE_BROWSING_SERVICE)
256 if (safe_browsing_service_.get())
257 safe_browsing_service()->ShutDown();
258 #endif
259 #if defined(ENABLE_PLUGIN_INSTALLATION)
260 plugins_resource_service_.reset();
261 #endif
263 // Need to clear the desktop notification balloons before the io_thread_ and
264 // before the profiles, since if there are any still showing we will access
265 // those things during teardown.
266 notification_ui_manager_.reset();
268 // The SupervisedUserWhitelistInstaller observes the ProfileInfoCache, so it
269 // needs to be shut down before the ProfileManager.
270 supervised_user_whitelist_installer_.reset();
272 #if !defined(OS_ANDROID)
273 // Debugger must be cleaned up before ProfileManager.
274 remote_debugging_server_.reset();
275 #endif
277 // Need to clear profiles (download managers) before the io_thread_.
279 TRACE_EVENT0("shutdown",
280 "BrowserProcessImpl::StartTearDown:ProfileManager");
281 // The desktop User Manager needs to be closed before the guest profile
282 // can be destroyed.
283 if (switches::IsNewAvatarMenu())
284 UserManager::Hide();
285 profile_manager_.reset();
288 // PromoResourceService must be destroyed after the keyed services and before
289 // the IO thread.
290 promo_resource_service_.reset();
292 child_process_watcher_.reset();
294 #if defined(ENABLE_EXTENSIONS)
295 ExtensionRendererState::GetInstance()->Shutdown();
297 media_file_system_registry_.reset();
298 // Remove the global instance of the Storage Monitor now. Otherwise the
299 // FILE thread would be gone when we try to release it in the dtor and
300 // Valgrind would report a leak on almost every single browser_test.
301 // TODO(gbillock): Make this unnecessary.
302 storage_monitor::StorageMonitor::Destroy();
303 #endif
305 message_center::MessageCenter::Shutdown();
307 #if defined(ENABLE_CONFIGURATION_POLICY)
308 // The policy providers managed by |browser_policy_connector_| need to shut
309 // down while the IO and FILE threads are still alive. The monitoring
310 // framework owned by |browser_policy_connector_| relies on |gcm_driver_|, so
311 // this must be shutdown before |gcm_driver_| below.
312 if (browser_policy_connector_)
313 browser_policy_connector_->Shutdown();
314 #endif
316 // The |gcm_driver_| must shut down while the IO thread is still alive.
317 if (gcm_driver_)
318 gcm_driver_->Shutdown();
320 // Stop the watchdog thread before stopping other threads.
321 watchdog_thread_.reset();
323 platform_part()->StartTearDown();
325 #if defined(ENABLE_WEBRTC)
326 // Cancel any uploads to release the system url request context references.
327 if (webrtc_log_uploader_)
328 webrtc_log_uploader_->StartShutdown();
329 #endif
331 if (local_state())
332 local_state()->CommitPendingWrite();
335 void BrowserProcessImpl::PostDestroyThreads() {
336 // With the file_thread_ flushed, we can release any icon resources.
337 icon_manager_.reset();
339 #if defined(ENABLE_WEBRTC)
340 // Must outlive the file thread.
341 webrtc_log_uploader_.reset();
342 #endif
344 // Reset associated state right after actual thread is stopped,
345 // as io_thread_.global_ cleanup happens in CleanUp on the IO
346 // thread, i.e. as the thread exits its message loop.
348 // This is important also because in various places, the
349 // IOThread object being NULL is considered synonymous with the
350 // IO thread having stopped.
351 io_thread_.reset();
354 unsigned int BrowserProcessImpl::AddRefModule() {
355 DCHECK(CalledOnValidThread());
357 // CHECK(!IsShuttingDown());
358 if (IsShuttingDown()) {
359 // Copy the stacktrace which released the final reference onto our stack so
360 // it will be available in the crash report for inspection.
361 base::debug::StackTrace callstack = release_last_reference_callstack_;
362 base::debug::Alias(&callstack);
363 CHECK(false);
366 did_start_ = true;
367 module_ref_count_++;
368 return module_ref_count_;
371 unsigned int BrowserProcessImpl::ReleaseModule() {
372 DCHECK(CalledOnValidThread());
373 DCHECK_NE(0u, module_ref_count_);
374 module_ref_count_--;
375 if (0 == module_ref_count_) {
376 release_last_reference_callstack_ = base::debug::StackTrace();
378 #if defined(ENABLE_PRINTING)
379 // Wait for the pending print jobs to finish. Don't do this later, since
380 // this might cause a nested message loop to run, and we don't want pending
381 // tasks to run once teardown has started.
382 print_job_manager_->Shutdown();
383 #endif
385 #if defined(LEAK_SANITIZER)
386 // Check for memory leaks now, before we start shutting down threads. Doing
387 // this early means we won't report any shutdown-only leaks (as they have
388 // not yet happened at this point).
389 // If leaks are found, this will make the process exit immediately.
390 __lsan_do_leak_check();
391 #endif
393 CHECK(base::MessageLoop::current()->is_running());
395 #if defined(OS_MACOSX)
396 base::MessageLoop::current()->PostTask(
397 FROM_HERE,
398 base::Bind(ChromeBrowserMainPartsMac::DidEndMainMessageLoop));
399 #endif
400 base::MessageLoop::current()->Quit();
402 return module_ref_count_;
405 namespace {
407 // Used at the end of session to block the UI thread for completion of sentinel
408 // tasks on the set of threads used to persist profile data and local state.
409 // This is done to ensure that the data has been persisted to disk before
410 // continuing.
411 class RundownTaskCounter :
412 public base::RefCountedThreadSafe<RundownTaskCounter> {
413 public:
414 RundownTaskCounter();
416 // Posts a rundown task to |task_runner|, can be invoked an arbitrary number
417 // of times before calling TimedWait.
418 void Post(base::SequencedTaskRunner* task_runner);
420 // Waits until the count is zero or |max_time| has passed.
421 // This can only be called once per instance.
422 bool TimedWait(const base::TimeDelta& max_time);
424 private:
425 friend class base::RefCountedThreadSafe<RundownTaskCounter>;
426 ~RundownTaskCounter() {}
428 // Decrements the counter and releases the waitable event on transition to
429 // zero.
430 void Decrement();
432 // The count starts at one to defer the possibility of one->zero transitions
433 // until TimedWait is called.
434 base::AtomicRefCount count_;
435 base::WaitableEvent waitable_event_;
437 DISALLOW_COPY_AND_ASSIGN(RundownTaskCounter);
440 RundownTaskCounter::RundownTaskCounter()
441 : count_(1), waitable_event_(true, false) {
444 void RundownTaskCounter::Post(base::SequencedTaskRunner* task_runner) {
445 // As the count starts off at one, it should never get to zero unless
446 // TimedWait has been called.
447 DCHECK(!base::AtomicRefCountIsZero(&count_));
449 base::AtomicRefCountInc(&count_);
451 // The task must be non-nestable to guarantee that it runs after all tasks
452 // currently scheduled on |task_runner| have completed.
453 task_runner->PostNonNestableTask(FROM_HERE,
454 base::Bind(&RundownTaskCounter::Decrement, this));
457 void RundownTaskCounter::Decrement() {
458 if (!base::AtomicRefCountDec(&count_))
459 waitable_event_.Signal();
462 bool RundownTaskCounter::TimedWait(const base::TimeDelta& max_time) {
463 // Decrement the excess count from the constructor.
464 Decrement();
466 return waitable_event_.TimedWait(max_time);
469 } // namespace
471 void BrowserProcessImpl::EndSession() {
472 // Mark all the profiles as clean.
473 ProfileManager* pm = profile_manager();
474 std::vector<Profile*> profiles(pm->GetLoadedProfiles());
475 scoped_refptr<RundownTaskCounter> rundown_counter(new RundownTaskCounter());
476 for (size_t i = 0; i < profiles.size(); ++i) {
477 Profile* profile = profiles[i];
478 profile->SetExitType(Profile::EXIT_SESSION_ENDED);
479 if (profile->GetPrefs()) {
480 profile->GetPrefs()->CommitPendingWrite();
481 rundown_counter->Post(profile->GetIOTaskRunner().get());
485 // Tell the metrics service it was cleanly shutdown.
486 metrics::MetricsService* metrics = g_browser_process->metrics_service();
487 if (metrics && local_state()) {
488 metrics->RecordStartOfSessionEnd();
489 #if !defined(OS_CHROMEOS)
490 // MetricsService lazily writes to prefs, force it to write now.
491 // On ChromeOS, chrome gets killed when hangs, so no need to
492 // commit metrics::prefs::kStabilitySessionEndCompleted change immediately.
493 local_state()->CommitPendingWrite();
495 rundown_counter->Post(local_state_task_runner_.get());
496 #endif
499 // http://crbug.com/125207
500 base::ThreadRestrictions::ScopedAllowWait allow_wait;
502 // We must write that the profile and metrics service shutdown cleanly,
503 // otherwise on startup we'll think we crashed. So we block until done and
504 // then proceed with normal shutdown.
506 // If you change the condition here, be sure to also change
507 // ProfileBrowserTests to match.
508 #if defined(USE_X11) || defined(OS_WIN) || defined(USE_OZONE)
509 // Do a best-effort wait on the successful countdown of rundown tasks. Note
510 // that if we don't complete "quickly enough", Windows will terminate our
511 // process.
513 // On Windows, we previously posted a message to FILE and then ran a nested
514 // message loop, waiting for that message to be processed until quitting.
515 // However, doing so means that other messages will also be processed. In
516 // particular, if the GPU process host notices that the GPU has been killed
517 // during shutdown, it races exiting the nested loop with the process host
518 // blocking the message loop attempting to re-establish a connection to the
519 // GPU process synchronously. Because the system may not be allowing
520 // processes to launch, this can result in a hang. See
521 // http://crbug.com/318527.
522 rundown_counter->TimedWait(
523 base::TimeDelta::FromSeconds(kEndSessionTimeoutSeconds));
524 #else
525 NOTIMPLEMENTED();
526 #endif
529 MetricsServicesManager* BrowserProcessImpl::GetMetricsServicesManager() {
530 DCHECK(CalledOnValidThread());
531 if (!metrics_services_manager_)
532 metrics_services_manager_.reset(new MetricsServicesManager(local_state()));
533 return metrics_services_manager_.get();
536 metrics::MetricsService* BrowserProcessImpl::metrics_service() {
537 DCHECK(CalledOnValidThread());
538 return GetMetricsServicesManager()->GetMetricsService();
541 rappor::RapporService* BrowserProcessImpl::rappor_service() {
542 DCHECK(CalledOnValidThread());
543 return GetMetricsServicesManager()->GetRapporService();
546 IOThread* BrowserProcessImpl::io_thread() {
547 DCHECK(CalledOnValidThread());
548 DCHECK(io_thread_.get());
549 return io_thread_.get();
552 WatchDogThread* BrowserProcessImpl::watchdog_thread() {
553 DCHECK(CalledOnValidThread());
554 if (!created_watchdog_thread_)
555 CreateWatchdogThread();
556 DCHECK(watchdog_thread_.get() != NULL);
557 return watchdog_thread_.get();
560 ProfileManager* BrowserProcessImpl::profile_manager() {
561 DCHECK(CalledOnValidThread());
562 if (!created_profile_manager_)
563 CreateProfileManager();
564 return profile_manager_.get();
567 PrefService* BrowserProcessImpl::local_state() {
568 DCHECK(CalledOnValidThread());
569 if (!created_local_state_)
570 CreateLocalState();
571 return local_state_.get();
574 net::URLRequestContextGetter* BrowserProcessImpl::system_request_context() {
575 DCHECK(CalledOnValidThread());
576 return io_thread()->system_url_request_context_getter();
579 variations::VariationsService* BrowserProcessImpl::variations_service() {
580 DCHECK(CalledOnValidThread());
581 return GetMetricsServicesManager()->GetVariationsService();
584 web_resource::PromoResourceService*
585 BrowserProcessImpl::promo_resource_service() {
586 DCHECK(CalledOnValidThread());
587 return promo_resource_service_.get();
590 BrowserProcessPlatformPart* BrowserProcessImpl::platform_part() {
591 return platform_part_.get();
594 extensions::EventRouterForwarder*
595 BrowserProcessImpl::extension_event_router_forwarder() {
596 #if defined(ENABLE_EXTENSIONS)
597 return extension_event_router_forwarder_.get();
598 #else
599 return NULL;
600 #endif
603 NotificationUIManager* BrowserProcessImpl::notification_ui_manager() {
604 DCHECK(CalledOnValidThread());
605 if (!created_notification_ui_manager_)
606 CreateNotificationUIManager();
607 return notification_ui_manager_.get();
610 message_center::MessageCenter* BrowserProcessImpl::message_center() {
611 DCHECK(CalledOnValidThread());
612 return message_center::MessageCenter::Get();
615 policy::BrowserPolicyConnector* BrowserProcessImpl::browser_policy_connector() {
616 DCHECK(CalledOnValidThread());
617 #if defined(ENABLE_CONFIGURATION_POLICY)
618 if (!created_browser_policy_connector_) {
619 DCHECK(!browser_policy_connector_);
620 browser_policy_connector_ = platform_part_->CreateBrowserPolicyConnector();
621 created_browser_policy_connector_ = true;
623 return browser_policy_connector_.get();
624 #else
625 return NULL;
626 #endif
629 policy::PolicyService* BrowserProcessImpl::policy_service() {
630 #if defined(ENABLE_CONFIGURATION_POLICY)
631 return browser_policy_connector()->GetPolicyService();
632 #else
633 if (!policy_service_.get())
634 policy_service_.reset(new policy::PolicyServiceStub());
635 return policy_service_.get();
636 #endif
639 IconManager* BrowserProcessImpl::icon_manager() {
640 DCHECK(CalledOnValidThread());
641 if (!created_icon_manager_)
642 CreateIconManager();
643 return icon_manager_.get();
646 GLStringManager* BrowserProcessImpl::gl_string_manager() {
647 DCHECK(CalledOnValidThread());
648 if (!gl_string_manager_.get())
649 gl_string_manager_.reset(new GLStringManager());
650 return gl_string_manager_.get();
653 GpuModeManager* BrowserProcessImpl::gpu_mode_manager() {
654 DCHECK(CalledOnValidThread());
655 if (!gpu_mode_manager_.get())
656 gpu_mode_manager_.reset(new GpuModeManager());
657 return gpu_mode_manager_.get();
660 void BrowserProcessImpl::CreateDevToolsHttpProtocolHandler(
661 chrome::HostDesktopType host_desktop_type,
662 const std::string& ip,
663 uint16 port) {
664 DCHECK(CalledOnValidThread());
665 #if !defined(OS_ANDROID)
666 // StartupBrowserCreator::LaunchBrowser can be run multiple times when browser
667 // is started with several profiles or existing browser process is reused.
668 if (!remote_debugging_server_.get()) {
669 remote_debugging_server_.reset(
670 new RemoteDebuggingServer(host_desktop_type, ip, port));
672 #endif
675 bool BrowserProcessImpl::IsShuttingDown() {
676 DCHECK(CalledOnValidThread());
677 return did_start_ && 0 == module_ref_count_;
680 printing::PrintJobManager* BrowserProcessImpl::print_job_manager() {
681 DCHECK(CalledOnValidThread());
682 return print_job_manager_.get();
685 printing::PrintPreviewDialogController*
686 BrowserProcessImpl::print_preview_dialog_controller() {
687 #if defined(ENABLE_PRINT_PREVIEW)
688 DCHECK(CalledOnValidThread());
689 if (!print_preview_dialog_controller_.get())
690 CreatePrintPreviewDialogController();
691 return print_preview_dialog_controller_.get();
692 #else
693 NOTIMPLEMENTED();
694 return NULL;
695 #endif
698 printing::BackgroundPrintingManager*
699 BrowserProcessImpl::background_printing_manager() {
700 #if defined(ENABLE_PRINT_PREVIEW)
701 DCHECK(CalledOnValidThread());
702 if (!background_printing_manager_.get())
703 CreateBackgroundPrintingManager();
704 return background_printing_manager_.get();
705 #else
706 NOTIMPLEMENTED();
707 return NULL;
708 #endif
711 IntranetRedirectDetector* BrowserProcessImpl::intranet_redirect_detector() {
712 DCHECK(CalledOnValidThread());
713 if (!intranet_redirect_detector_.get())
714 CreateIntranetRedirectDetector();
715 return intranet_redirect_detector_.get();
718 const std::string& BrowserProcessImpl::GetApplicationLocale() {
719 DCHECK(!locale_.empty());
720 return locale_;
723 void BrowserProcessImpl::SetApplicationLocale(const std::string& locale) {
724 locale_ = locale;
725 #if defined(ENABLE_EXTENSIONS)
726 extension_l10n_util::SetProcessLocale(locale);
727 #endif
728 ChromeContentBrowserClient::SetApplicationLocale(locale);
729 translate::TranslateDownloadManager::GetInstance()->set_application_locale(
730 locale);
733 DownloadStatusUpdater* BrowserProcessImpl::download_status_updater() {
734 return download_status_updater_.get();
737 MediaFileSystemRegistry* BrowserProcessImpl::media_file_system_registry() {
738 #if defined(ENABLE_EXTENSIONS)
739 if (!media_file_system_registry_)
740 media_file_system_registry_.reset(new MediaFileSystemRegistry());
741 return media_file_system_registry_.get();
742 #else
743 return NULL;
744 #endif
747 bool BrowserProcessImpl::created_local_state() const {
748 return created_local_state_;
751 #if defined(ENABLE_WEBRTC)
752 WebRtcLogUploader* BrowserProcessImpl::webrtc_log_uploader() {
753 if (!webrtc_log_uploader_.get())
754 webrtc_log_uploader_.reset(new WebRtcLogUploader());
755 return webrtc_log_uploader_.get();
757 #endif
759 network_time::NetworkTimeTracker* BrowserProcessImpl::network_time_tracker() {
760 if (!network_time_tracker_) {
761 network_time_tracker_.reset(new network_time::NetworkTimeTracker(
762 scoped_ptr<base::TickClock>(new base::DefaultTickClock()),
763 local_state()));
765 return network_time_tracker_.get();
768 gcm::GCMDriver* BrowserProcessImpl::gcm_driver() {
769 DCHECK(CalledOnValidThread());
770 if (!gcm_driver_)
771 CreateGCMDriver();
772 return gcm_driver_.get();
775 memory::OomPriorityManager* BrowserProcessImpl::GetOomPriorityManager() {
776 DCHECK(CalledOnValidThread());
777 #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS)
778 if (!oom_priority_manager_.get())
779 oom_priority_manager_.reset(new memory::OomPriorityManager());
780 return oom_priority_manager_.get();
781 #else
782 return nullptr;
783 #endif
786 ShellIntegration::DefaultWebClientState
787 BrowserProcessImpl::CachedDefaultWebClientState() {
788 return cached_default_web_client_state_;
791 // static
792 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple* registry) {
793 registry->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled,
794 false);
795 // This policy needs to be defined before the net subsystem is initialized,
796 // so we do it here.
797 registry->RegisterIntegerPref(prefs::kMaxConnectionsPerProxy,
798 net::kDefaultMaxSocketsPerProxyServer);
800 registry->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt, false);
802 #if defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
803 registry->RegisterBooleanPref(prefs::kEulaAccepted, false);
804 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
805 #if defined(OS_WIN)
806 if (base::win::GetVersion() >= base::win::VERSION_WIN7) {
807 registry->RegisterStringPref(prefs::kRelaunchMode,
808 upgrade_util::kRelaunchModeDefault);
810 #endif
812 // TODO(brettw,*): this comment about ResourceBundle was here since
813 // initial commit. This comment seems unrelated, bit-rotten and
814 // a candidate for removal.
815 // Initialize ResourceBundle which handles files loaded from external
816 // sources. This has to be done before uninstall code path and before prefs
817 // are registered.
818 registry->RegisterStringPref(prefs::kApplicationLocale, std::string());
819 #if defined(OS_CHROMEOS)
820 registry->RegisterStringPref(prefs::kOwnerLocale, std::string());
821 registry->RegisterStringPref(prefs::kHardwareKeyboardLayout,
822 std::string());
823 #endif // defined(OS_CHROMEOS)
824 #if !defined(OS_CHROMEOS)
825 registry->RegisterBooleanPref(
826 prefs::kMetricsReportingEnabled,
827 GoogleUpdateSettings::GetCollectStatsConsent());
828 #endif // !defined(OS_CHROMEOS)
830 #if defined(OS_ANDROID)
831 registry->RegisterBooleanPref(
832 prefs::kCrashReportingEnabled, false);
833 #endif // defined(OS_ANDROID)
836 DownloadRequestLimiter* BrowserProcessImpl::download_request_limiter() {
837 DCHECK(CalledOnValidThread());
838 if (!download_request_limiter_.get())
839 download_request_limiter_ = new DownloadRequestLimiter();
840 return download_request_limiter_.get();
843 BackgroundModeManager* BrowserProcessImpl::background_mode_manager() {
844 DCHECK(CalledOnValidThread());
845 #if defined(ENABLE_BACKGROUND)
846 if (!background_mode_manager_.get())
847 CreateBackgroundModeManager();
848 return background_mode_manager_.get();
849 #else
850 NOTIMPLEMENTED();
851 return NULL;
852 #endif
855 void BrowserProcessImpl::set_background_mode_manager_for_test(
856 scoped_ptr<BackgroundModeManager> manager) {
857 #if defined(ENABLE_BACKGROUND)
858 background_mode_manager_ = manager.Pass();
859 #endif
862 StatusTray* BrowserProcessImpl::status_tray() {
863 DCHECK(CalledOnValidThread());
864 if (!status_tray_.get())
865 CreateStatusTray();
866 return status_tray_.get();
870 SafeBrowsingService* BrowserProcessImpl::safe_browsing_service() {
871 DCHECK(CalledOnValidThread());
872 if (!created_safe_browsing_service_)
873 CreateSafeBrowsingService();
874 return safe_browsing_service_.get();
877 safe_browsing::ClientSideDetectionService*
878 BrowserProcessImpl::safe_browsing_detection_service() {
879 DCHECK(CalledOnValidThread());
880 if (safe_browsing_service())
881 return safe_browsing_service()->safe_browsing_detection_service();
882 return NULL;
885 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
886 void BrowserProcessImpl::StartAutoupdateTimer() {
887 autoupdate_timer_.Start(FROM_HERE,
888 base::TimeDelta::FromHours(kUpdateCheckIntervalHours),
889 this,
890 &BrowserProcessImpl::OnAutoupdateTimer);
892 #endif
894 net_log::ChromeNetLog* BrowserProcessImpl::net_log() {
895 return net_log_.get();
898 component_updater::ComponentUpdateService*
899 BrowserProcessImpl::component_updater() {
900 if (!component_updater_.get()) {
901 if (!BrowserThread::CurrentlyOn(BrowserThread::UI))
902 return NULL;
903 scoped_refptr<update_client::Configurator> configurator =
904 component_updater::MakeChromeComponentUpdaterConfigurator(
905 base::CommandLine::ForCurrentProcess(),
906 io_thread()->system_url_request_context_getter());
907 // Creating the component updater does not do anything, components
908 // need to be registered and Start() needs to be called.
909 component_updater_.reset(component_updater::ComponentUpdateServiceFactory(
910 configurator).release());
912 return component_updater_.get();
915 CRLSetFetcher* BrowserProcessImpl::crl_set_fetcher() {
916 if (!crl_set_fetcher_)
917 crl_set_fetcher_ = new CRLSetFetcher();
918 return crl_set_fetcher_.get();
921 component_updater::PnaclComponentInstaller*
922 BrowserProcessImpl::pnacl_component_installer() {
923 #if !defined(DISABLE_NACL)
924 if (!pnacl_component_installer_) {
925 pnacl_component_installer_ =
926 new component_updater::PnaclComponentInstaller();
928 return pnacl_component_installer_.get();
929 #else
930 return nullptr;
931 #endif
934 component_updater::SupervisedUserWhitelistInstaller*
935 BrowserProcessImpl::supervised_user_whitelist_installer() {
936 if (!supervised_user_whitelist_installer_) {
937 supervised_user_whitelist_installer_ =
938 component_updater::SupervisedUserWhitelistInstaller::Create(
939 component_updater(), &profile_manager()->GetProfileInfoCache(),
940 local_state());
942 return supervised_user_whitelist_installer_.get();
945 void BrowserProcessImpl::ResourceDispatcherHostCreated() {
946 resource_dispatcher_host_delegate_.reset(
947 new ChromeResourceDispatcherHostDelegate);
948 ResourceDispatcherHost::Get()->SetDelegate(
949 resource_dispatcher_host_delegate_.get());
951 pref_change_registrar_.Add(
952 prefs::kAllowCrossOriginAuthPrompt,
953 base::Bind(&BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy,
954 base::Unretained(this)));
955 ApplyAllowCrossOriginAuthPromptPolicy();
958 void BrowserProcessImpl::CreateWatchdogThread() {
959 DCHECK(!created_watchdog_thread_ && watchdog_thread_.get() == NULL);
960 created_watchdog_thread_ = true;
962 scoped_ptr<WatchDogThread> thread(new WatchDogThread());
963 base::Thread::Options options;
964 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
965 if (!thread->StartWithOptions(options))
966 return;
967 watchdog_thread_.swap(thread);
970 void BrowserProcessImpl::CreateProfileManager() {
971 DCHECK(!created_profile_manager_ && profile_manager_.get() == NULL);
972 created_profile_manager_ = true;
974 base::FilePath user_data_dir;
975 PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
976 profile_manager_.reset(new ProfileManager(user_data_dir));
979 void BrowserProcessImpl::CreateLocalState() {
980 DCHECK(!created_local_state_ && local_state_.get() == NULL);
981 created_local_state_ = true;
983 base::FilePath local_state_path;
984 CHECK(PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path));
985 scoped_refptr<PrefRegistrySimple> pref_registry = new PrefRegistrySimple;
987 // Register local state preferences.
988 chrome::RegisterLocalState(pref_registry.get());
990 local_state_ =
991 chrome_prefs::CreateLocalState(local_state_path,
992 local_state_task_runner_.get(),
993 policy_service(),
994 pref_registry,
995 false).Pass();
997 pref_change_registrar_.Init(local_state_.get());
999 // Initialize the notification for the default browser setting policy.
1000 pref_change_registrar_.Add(
1001 prefs::kDefaultBrowserSettingEnabled,
1002 base::Bind(&BrowserProcessImpl::ApplyDefaultBrowserPolicy,
1003 base::Unretained(this)));
1005 // This preference must be kept in sync with external values; update them
1006 // whenever the preference or its controlling policy changes.
1007 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1008 pref_change_registrar_.Add(
1009 prefs::kMetricsReportingEnabled,
1010 base::Bind(&BrowserProcessImpl::ApplyMetricsReportingPolicy,
1011 base::Unretained(this)));
1012 #endif
1014 int max_per_proxy = local_state_->GetInteger(prefs::kMaxConnectionsPerProxy);
1015 net::ClientSocketPoolManager::set_max_sockets_per_proxy_server(
1016 net::HttpNetworkSession::NORMAL_SOCKET_POOL,
1017 std::max(std::min(max_per_proxy, 99),
1018 net::ClientSocketPoolManager::max_sockets_per_group(
1019 net::HttpNetworkSession::NORMAL_SOCKET_POOL)));
1022 void BrowserProcessImpl::PreCreateThreads() {
1023 io_thread_.reset(
1024 new IOThread(local_state(), policy_service(), net_log_.get(),
1025 extension_event_router_forwarder()));
1028 void BrowserProcessImpl::PreMainMessageLoopRun() {
1029 TRACE_EVENT0("startup", "BrowserProcessImpl::PreMainMessageLoopRun");
1030 SCOPED_UMA_HISTOGRAM_TIMER(
1031 "Startup.BrowserProcessImpl_PreMainMessageLoopRunTime");
1033 #if defined(ENABLE_CONFIGURATION_POLICY)
1034 // browser_policy_connector() is created very early because local_state()
1035 // needs policy to be initialized with the managed preference values.
1036 // However, policy fetches from the network and loading of disk caches
1037 // requires that threads are running; this Init() call lets the connector
1038 // resume its initialization now that the loops are spinning and the
1039 // system request context is available for the fetchers.
1040 browser_policy_connector()->Init(local_state(), system_request_context());
1041 #endif
1043 if (local_state_->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled))
1044 ApplyDefaultBrowserPolicy();
1046 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1047 ApplyMetricsReportingPolicy();
1048 #endif
1050 #if defined(ENABLE_PLUGINS)
1051 PluginService* plugin_service = PluginService::GetInstance();
1052 plugin_service->SetFilter(ChromePluginServiceFilter::GetInstance());
1053 plugin_service->StartWatchingPlugins();
1055 #if defined(OS_POSIX)
1056 // Also find plugins in a user-specific plugins dir,
1057 // e.g. ~/.config/chromium/Plugins.
1058 const base::CommandLine& cmd_line = *base::CommandLine::ForCurrentProcess();
1059 if (!cmd_line.HasSwitch(switches::kDisablePluginsDiscovery)) {
1060 base::FilePath user_data_dir;
1061 if (PathService::Get(chrome::DIR_USER_DATA, &user_data_dir))
1062 plugin_service->AddExtraPluginDir(user_data_dir.Append("Plugins"));
1064 #endif
1066 // Triggers initialization of the singleton instance on UI thread.
1067 PluginFinder::GetInstance()->Init();
1069 #if defined(ENABLE_PLUGIN_INSTALLATION)
1070 DCHECK(!plugins_resource_service_.get());
1071 plugins_resource_service_.reset(new PluginsResourceService(local_state()));
1072 plugins_resource_service_->Init();
1073 #endif
1074 #endif // defined(ENABLE_PLUGINS)
1076 const base::CommandLine& command_line =
1077 *base::CommandLine::ForCurrentProcess();
1078 if (!command_line.HasSwitch(switches::kDisableWebResources)) {
1079 DCHECK(!promo_resource_service_.get());
1080 promo_resource_service_.reset(new web_resource::PromoResourceService(
1081 local_state(), chrome::GetChannel(), GetApplicationLocale(),
1082 system_request_context(), switches::kDisableBackgroundNetworking,
1083 base::Bind(safe_json::SafeJsonParser::Parse)));
1084 promo_resource_service_->StartAfterDelay();
1087 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1088 storage_monitor::StorageMonitor::Create();
1089 #endif
1091 child_process_watcher_.reset(new ChromeChildProcessWatcher());
1093 CacheDefaultWebClientState();
1095 platform_part_->PreMainMessageLoopRun();
1098 void BrowserProcessImpl::CreateIconManager() {
1099 DCHECK(!created_icon_manager_ && icon_manager_.get() == NULL);
1100 created_icon_manager_ = true;
1101 icon_manager_.reset(new IconManager);
1104 void BrowserProcessImpl::CreateIntranetRedirectDetector() {
1105 DCHECK(intranet_redirect_detector_.get() == NULL);
1106 scoped_ptr<IntranetRedirectDetector> intranet_redirect_detector(
1107 new IntranetRedirectDetector);
1108 intranet_redirect_detector_.swap(intranet_redirect_detector);
1111 void BrowserProcessImpl::CreateNotificationUIManager() {
1112 #if defined(ENABLE_NOTIFICATIONS)
1113 DCHECK(notification_ui_manager_.get() == NULL);
1114 notification_ui_manager_.reset(NotificationUIManager::Create(local_state()));
1115 created_notification_ui_manager_ = true;
1116 #endif
1119 void BrowserProcessImpl::CreateBackgroundModeManager() {
1120 #if defined(ENABLE_BACKGROUND)
1121 DCHECK(background_mode_manager_.get() == NULL);
1122 background_mode_manager_.reset(
1123 new BackgroundModeManager(*base::CommandLine::ForCurrentProcess(),
1124 &profile_manager()->GetProfileInfoCache()));
1125 #endif
1128 void BrowserProcessImpl::CreateStatusTray() {
1129 DCHECK(status_tray_.get() == NULL);
1130 status_tray_.reset(StatusTray::Create());
1133 void BrowserProcessImpl::CreatePrintPreviewDialogController() {
1134 #if defined(ENABLE_PRINT_PREVIEW)
1135 DCHECK(print_preview_dialog_controller_.get() == NULL);
1136 print_preview_dialog_controller_ =
1137 new printing::PrintPreviewDialogController();
1138 #else
1139 NOTIMPLEMENTED();
1140 #endif
1143 void BrowserProcessImpl::CreateBackgroundPrintingManager() {
1144 #if defined(ENABLE_PRINT_PREVIEW)
1145 DCHECK(background_printing_manager_.get() == NULL);
1146 background_printing_manager_.reset(new printing::BackgroundPrintingManager());
1147 #else
1148 NOTIMPLEMENTED();
1149 #endif
1152 void BrowserProcessImpl::CreateSafeBrowsingService() {
1153 DCHECK(safe_browsing_service_.get() == NULL);
1154 // Set this flag to true so that we don't retry indefinitely to
1155 // create the service class if there was an error.
1156 created_safe_browsing_service_ = true;
1157 #if defined(SAFE_BROWSING_SERVICE)
1158 safe_browsing_service_ = SafeBrowsingService::CreateSafeBrowsingService();
1159 safe_browsing_service_->Initialize();
1160 #endif
1163 void BrowserProcessImpl::CreateGCMDriver() {
1164 DCHECK(!gcm_driver_);
1166 #if defined(OS_ANDROID)
1167 // Android's GCMDriver currently makes the assumption that it's a singleton.
1168 // Until this gets fixed, instantiating multiple Java GCMDrivers will throw
1169 // an exception, but because they're only initialized on demand these crashes
1170 // would be very difficult to triage. See http://crbug.com/437827.
1171 NOTREACHED();
1172 #else
1173 base::FilePath store_path;
1174 CHECK(PathService::Get(chrome::DIR_GLOBAL_GCM_STORE, &store_path));
1175 gcm_driver_ = gcm::CreateGCMDriverDesktop(
1176 make_scoped_ptr(new gcm::GCMClientFactory),
1177 local_state(),
1178 store_path,
1179 system_request_context());
1180 #endif // defined(OS_ANDROID)
1183 void BrowserProcessImpl::ApplyDefaultBrowserPolicy() {
1184 if (local_state()->GetBoolean(prefs::kDefaultBrowserSettingEnabled)) {
1185 scoped_refptr<ShellIntegration::DefaultWebClientWorker>
1186 set_browser_worker = new ShellIntegration::DefaultBrowserWorker(NULL);
1187 set_browser_worker->StartSetAsDefault();
1191 void BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy() {
1192 bool value = local_state()->GetBoolean(prefs::kAllowCrossOriginAuthPrompt);
1193 ResourceDispatcherHost::Get()->SetAllowCrossOriginAuthPrompt(value);
1196 void BrowserProcessImpl::ApplyMetricsReportingPolicy() {
1197 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1198 CHECK(BrowserThread::PostTask(
1199 BrowserThread::FILE, FROM_HERE,
1200 base::Bind(
1201 base::IgnoreResult(&GoogleUpdateSettings::SetCollectStatsConsent),
1202 ChromeMetricsServiceAccessor::IsMetricsAndCrashReportingEnabled())));
1203 #endif
1206 void BrowserProcessImpl::CacheDefaultWebClientState() {
1207 #if defined(OS_CHROMEOS)
1208 cached_default_web_client_state_ = ShellIntegration::IS_DEFAULT;
1209 #elif !defined(OS_ANDROID) && !defined(OS_IOS)
1210 cached_default_web_client_state_ = ShellIntegration::GetDefaultBrowser();
1211 #endif
1214 // Mac is currently not supported.
1215 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
1217 bool BrowserProcessImpl::CanAutorestartForUpdate() const {
1218 // Check if browser is in the background and if it needs to be restarted to
1219 // apply a pending update.
1220 return chrome::GetTotalBrowserCount() == 0 && chrome::WillKeepAlive() &&
1221 upgrade_util::IsUpdatePendingRestart();
1224 // Switches to add when auto-restarting Chrome.
1225 const char* const kSwitchesToAddOnAutorestart[] = {
1226 switches::kNoStartupWindow
1229 void BrowserProcessImpl::RestartBackgroundInstance() {
1230 base::CommandLine* old_cl = base::CommandLine::ForCurrentProcess();
1231 scoped_ptr<base::CommandLine> new_cl(
1232 new base::CommandLine(old_cl->GetProgram()));
1234 std::map<std::string, base::CommandLine::StringType> switches =
1235 old_cl->GetSwitches();
1237 switches::RemoveSwitchesForAutostart(&switches);
1239 // Append the rest of the switches (along with their values, if any)
1240 // to the new command line
1241 for (std::map<std::string, base::CommandLine::StringType>::const_iterator i =
1242 switches.begin();
1243 i != switches.end(); ++i) {
1244 base::CommandLine::StringType switch_value = i->second;
1245 if (switch_value.length() > 0) {
1246 new_cl->AppendSwitchNative(i->first, i->second);
1247 } else {
1248 new_cl->AppendSwitch(i->first);
1252 // Ensure that our desired switches are set on the new process.
1253 for (size_t i = 0; i < arraysize(kSwitchesToAddOnAutorestart); ++i) {
1254 if (!new_cl->HasSwitch(kSwitchesToAddOnAutorestart[i]))
1255 new_cl->AppendSwitch(kSwitchesToAddOnAutorestart[i]);
1258 DLOG(WARNING) << "Shutting down current instance of the browser.";
1259 chrome::AttemptExit();
1261 // Transfer ownership to Upgrade.
1262 upgrade_util::SetNewCommandLine(new_cl.release());
1265 void BrowserProcessImpl::OnAutoupdateTimer() {
1266 if (CanAutorestartForUpdate()) {
1267 DLOG(WARNING) << "Detected update. Restarting browser.";
1268 RestartBackgroundInstance();
1272 #endif // (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)