ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / extensions / browser / process_manager.cc
blob5ba41c449d570e37691d1637f2ed81abe86b135f
1 // Copyright 2013 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 "extensions/browser/process_manager.h"
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/lazy_instance.h"
10 #include "base/logging.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/metrics/histogram_macros.h"
13 #include "base/stl_util.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "base/time/time.h"
16 #include "content/public/browser/browser_context.h"
17 #include "content/public/browser/browser_thread.h"
18 #include "content/public/browser/devtools_agent_host.h"
19 #include "content/public/browser/notification_service.h"
20 #include "content/public/browser/render_frame_host.h"
21 #include "content/public/browser/render_process_host.h"
22 #include "content/public/browser/render_view_host.h"
23 #include "content/public/browser/site_instance.h"
24 #include "content/public/browser/web_contents.h"
25 #include "content/public/browser/web_contents_delegate.h"
26 #include "content/public/browser/web_contents_observer.h"
27 #include "content/public/browser/web_contents_user_data.h"
28 #include "content/public/common/renderer_preferences.h"
29 #include "content/public/common/url_constants.h"
30 #include "extensions/browser/extension_host.h"
31 #include "extensions/browser/extension_registry.h"
32 #include "extensions/browser/extension_system.h"
33 #include "extensions/browser/extensions_browser_client.h"
34 #include "extensions/browser/notification_types.h"
35 #include "extensions/browser/process_manager_delegate.h"
36 #include "extensions/browser/process_manager_factory.h"
37 #include "extensions/browser/process_manager_observer.h"
38 #include "extensions/browser/view_type_utils.h"
39 #include "extensions/common/constants.h"
40 #include "extensions/common/extension.h"
41 #include "extensions/common/extension_messages.h"
42 #include "extensions/common/manifest_handlers/background_info.h"
43 #include "extensions/common/manifest_handlers/incognito_info.h"
44 #include "extensions/common/one_shot_event.h"
46 using content::BrowserContext;
47 using content::RenderViewHost;
48 using content::SiteInstance;
49 using content::WebContents;
51 namespace extensions {
52 class RenderViewHostDestructionObserver;
54 DEFINE_WEB_CONTENTS_USER_DATA_KEY(
55 extensions::RenderViewHostDestructionObserver);
57 namespace extensions {
59 namespace {
61 // The time to delay between an extension becoming idle and
62 // sending a ShouldSuspend message.
63 // Note: Must be sufficiently larger (e.g. 2x) than
64 // kKeepaliveThrottleIntervalInSeconds in ppapi/proxy/plugin_globals.
65 unsigned g_event_page_idle_time_msec = 10000;
67 // The time to delay between sending a ShouldSuspend message and
68 // sending a Suspend message.
69 unsigned g_event_page_suspending_time_msec = 5000;
71 std::string GetExtensionID(RenderViewHost* render_view_host) {
72 // This works for both apps and extensions because the site has been
73 // normalized to the extension URL for hosted apps.
74 content::SiteInstance* site_instance = render_view_host->GetSiteInstance();
75 if (!site_instance)
76 return std::string();
78 const GURL& site_url = site_instance->GetSiteURL();
80 if (!site_url.SchemeIs(kExtensionScheme) &&
81 !site_url.SchemeIs(content::kGuestScheme))
82 return std::string();
84 return site_url.host();
87 std::string GetExtensionIDFromFrame(
88 content::RenderFrameHost* render_frame_host) {
89 // This works for both apps and extensions because the site has been
90 // normalized to the extension URL for apps.
91 if (!render_frame_host->GetSiteInstance())
92 return std::string();
94 return render_frame_host->GetSiteInstance()->GetSiteURL().host();
97 bool IsFrameInExtensionHost(ExtensionHost* extension_host,
98 content::RenderFrameHost* render_frame_host) {
99 return WebContents::FromRenderFrameHost(render_frame_host) ==
100 extension_host->host_contents();
103 void OnRenderViewHostUnregistered(BrowserContext* context,
104 RenderViewHost* render_view_host) {
105 content::NotificationService::current()->Notify(
106 extensions::NOTIFICATION_EXTENSION_VIEW_UNREGISTERED,
107 content::Source<BrowserContext>(context),
108 content::Details<RenderViewHost>(render_view_host));
111 // Incognito profiles use this process manager. It is mostly a shim that decides
112 // whether to fall back on the original profile's ProcessManager based
113 // on whether a given extension uses "split" or "spanning" incognito behavior.
114 class IncognitoProcessManager : public ProcessManager {
115 public:
116 IncognitoProcessManager(BrowserContext* incognito_context,
117 BrowserContext* original_context,
118 ExtensionRegistry* extension_registry);
119 ~IncognitoProcessManager() override {}
120 bool CreateBackgroundHost(const Extension* extension,
121 const GURL& url) override;
122 scoped_refptr<SiteInstance> GetSiteInstanceForURL(const GURL& url) override;
124 private:
125 DISALLOW_COPY_AND_ASSIGN(IncognitoProcessManager);
128 static void CreateBackgroundHostForExtensionLoad(
129 ProcessManager* manager, const Extension* extension) {
130 DVLOG(1) << "CreateBackgroundHostForExtensionLoad";
131 if (BackgroundInfo::HasPersistentBackgroundPage(extension))
132 manager->CreateBackgroundHost(extension,
133 BackgroundInfo::GetBackgroundURL(extension));
136 } // namespace
138 class RenderViewHostDestructionObserver
139 : public content::WebContentsObserver,
140 public content::WebContentsUserData<RenderViewHostDestructionObserver> {
141 public:
142 ~RenderViewHostDestructionObserver() override {}
144 private:
145 explicit RenderViewHostDestructionObserver(WebContents* web_contents)
146 : WebContentsObserver(web_contents) {
147 BrowserContext* context = web_contents->GetBrowserContext();
148 process_manager_ = ProcessManager::Get(context);
151 friend class content::WebContentsUserData<RenderViewHostDestructionObserver>;
153 // content::WebContentsObserver overrides.
154 void RenderViewDeleted(RenderViewHost* render_view_host) override {
155 process_manager_->UnregisterRenderViewHost(render_view_host);
158 ProcessManager* process_manager_;
160 DISALLOW_COPY_AND_ASSIGN(RenderViewHostDestructionObserver);
163 struct ProcessManager::BackgroundPageData {
164 // The count of things keeping the lazy background page alive.
165 int lazy_keepalive_count;
167 // Tracks if an impulse event has occured since the last polling check.
168 bool keepalive_impulse;
169 bool previous_keepalive_impulse;
171 // True if the page responded to the ShouldSuspend message and is currently
172 // dispatching the suspend event. During this time any events that arrive will
173 // cancel the suspend process and an onSuspendCanceled event will be
174 // dispatched to the page.
175 bool is_closing;
177 // Stores the value of the incremented
178 // ProcessManager::last_background_close_sequence_id_ whenever the extension
179 // is active. A copy of the ID is also passed in the callbacks and IPC
180 // messages leading up to CloseLazyBackgroundPageNow. The process is aborted
181 // if the IDs ever differ due to new activity.
182 uint64 close_sequence_id;
184 // Keeps track of when this page was last suspended. Used for perf metrics.
185 linked_ptr<base::ElapsedTimer> since_suspended;
187 BackgroundPageData()
188 : lazy_keepalive_count(0),
189 keepalive_impulse(false),
190 previous_keepalive_impulse(false),
191 is_closing(false),
192 close_sequence_id(0) {}
195 // Data of a RenderViewHost associated with an extension.
196 struct ProcessManager::ExtensionRenderViewData {
197 // The type of the view.
198 extensions::ViewType view_type;
200 // Whether the view is keeping the lazy background page alive or not.
201 bool has_keepalive;
203 ExtensionRenderViewData()
204 : view_type(VIEW_TYPE_INVALID), has_keepalive(false) {}
206 // Returns whether the view can keep the lazy background page alive or not.
207 bool CanKeepalive() const {
208 switch (view_type) {
209 case VIEW_TYPE_APP_WINDOW:
210 case VIEW_TYPE_BACKGROUND_CONTENTS:
211 case VIEW_TYPE_EXTENSION_DIALOG:
212 case VIEW_TYPE_EXTENSION_POPUP:
213 case VIEW_TYPE_LAUNCHER_PAGE:
214 case VIEW_TYPE_PANEL:
215 case VIEW_TYPE_TAB_CONTENTS:
216 case VIEW_TYPE_VIRTUAL_KEYBOARD:
217 return true;
219 case VIEW_TYPE_INVALID:
220 case VIEW_TYPE_EXTENSION_BACKGROUND_PAGE:
221 return false;
223 NOTREACHED();
224 return false;
229 // ProcessManager
232 // static
233 ProcessManager* ProcessManager::Get(BrowserContext* context) {
234 return ProcessManagerFactory::GetForBrowserContext(context);
237 // static
238 ProcessManager* ProcessManager::Create(BrowserContext* context) {
239 ExtensionRegistry* extension_registry = ExtensionRegistry::Get(context);
240 ExtensionsBrowserClient* client = ExtensionsBrowserClient::Get();
241 if (client->IsGuestSession(context)) {
242 // In the guest session, there is a single off-the-record context. Unlike
243 // a regular incognito mode, background pages of extensions must be
244 // created regardless of whether extensions use "spanning" or "split"
245 // incognito behavior.
246 BrowserContext* original_context = client->GetOriginalContext(context);
247 return new ProcessManager(context, original_context, extension_registry);
250 if (context->IsOffTheRecord()) {
251 BrowserContext* original_context = client->GetOriginalContext(context);
252 return new IncognitoProcessManager(
253 context, original_context, extension_registry);
256 return new ProcessManager(context, context, extension_registry);
259 // static
260 ProcessManager* ProcessManager::CreateForTesting(
261 BrowserContext* context,
262 ExtensionRegistry* extension_registry) {
263 DCHECK(!context->IsOffTheRecord());
264 return new ProcessManager(context, context, extension_registry);
267 // static
268 ProcessManager* ProcessManager::CreateIncognitoForTesting(
269 BrowserContext* incognito_context,
270 BrowserContext* original_context,
271 ExtensionRegistry* extension_registry) {
272 DCHECK(incognito_context->IsOffTheRecord());
273 DCHECK(!original_context->IsOffTheRecord());
274 return new IncognitoProcessManager(incognito_context,
275 original_context,
276 extension_registry);
279 ProcessManager::ProcessManager(BrowserContext* context,
280 BrowserContext* original_context,
281 ExtensionRegistry* extension_registry)
282 : site_instance_(SiteInstance::Create(context)),
283 extension_registry_(extension_registry),
284 startup_background_hosts_created_(false),
285 devtools_callback_(base::Bind(&ProcessManager::OnDevToolsStateChanged,
286 base::Unretained(this))),
287 last_background_close_sequence_id_(0),
288 weak_ptr_factory_(this) {
289 // ExtensionRegistry is shared between incognito and regular contexts.
290 DCHECK_EQ(original_context, extension_registry_->browser_context());
291 extension_registry_->AddObserver(this);
292 registrar_.Add(this,
293 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
294 content::Source<BrowserContext>(original_context));
295 registrar_.Add(this,
296 extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED,
297 content::Source<BrowserContext>(context));
298 registrar_.Add(this,
299 extensions::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE,
300 content::Source<BrowserContext>(context));
301 registrar_.Add(this, content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
302 content::NotificationService::AllSources());
303 registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_CONNECTED,
304 content::NotificationService::AllSources());
306 content::DevToolsAgentHost::AddAgentStateCallback(devtools_callback_);
308 OnKeepaliveImpulseCheck();
311 ProcessManager::~ProcessManager() {
312 extension_registry_->RemoveObserver(this);
313 CloseBackgroundHosts();
314 DCHECK(background_hosts_.empty());
315 content::DevToolsAgentHost::RemoveAgentStateCallback(devtools_callback_);
318 const ProcessManager::ViewSet ProcessManager::GetAllViews() const {
319 ViewSet result;
320 for (ExtensionRenderViews::const_iterator iter =
321 all_extension_views_.begin();
322 iter != all_extension_views_.end(); ++iter) {
323 result.insert(iter->first);
325 return result;
328 void ProcessManager::AddObserver(ProcessManagerObserver* observer) {
329 observer_list_.AddObserver(observer);
332 void ProcessManager::RemoveObserver(ProcessManagerObserver* observer) {
333 observer_list_.RemoveObserver(observer);
336 bool ProcessManager::CreateBackgroundHost(const Extension* extension,
337 const GURL& url) {
338 // Hosted apps are taken care of from BackgroundContentsService. Ignore them
339 // here.
340 if (extension->is_hosted_app())
341 return false;
343 // Don't create hosts if the embedder doesn't allow it.
344 ProcessManagerDelegate* delegate =
345 ExtensionsBrowserClient::Get()->GetProcessManagerDelegate();
346 if (delegate && !delegate->IsBackgroundPageAllowed(GetBrowserContext()))
347 return false;
349 // Don't create multiple background hosts for an extension.
350 if (GetBackgroundHostForExtension(extension->id()))
351 return true; // TODO(kalman): return false here? It might break things...
353 ExtensionHost* host =
354 new ExtensionHost(extension, GetSiteInstanceForURL(url).get(), url,
355 VIEW_TYPE_EXTENSION_BACKGROUND_PAGE);
356 host->CreateRenderViewSoon();
357 OnBackgroundHostCreated(host);
358 return true;
361 ExtensionHost* ProcessManager::GetBackgroundHostForExtension(
362 const std::string& extension_id) {
363 for (ExtensionHostSet::iterator iter = background_hosts_.begin();
364 iter != background_hosts_.end(); ++iter) {
365 ExtensionHost* host = *iter;
366 if (host->extension_id() == extension_id)
367 return host;
369 return NULL;
372 std::set<RenderViewHost*> ProcessManager::GetRenderViewHostsForExtension(
373 const std::string& extension_id) {
374 std::set<RenderViewHost*> result;
376 scoped_refptr<SiteInstance> site_instance(GetSiteInstanceForURL(
377 Extension::GetBaseURLFromExtensionId(extension_id)));
378 if (!site_instance.get())
379 return result;
381 // Gather up all the views for that site.
382 for (ExtensionRenderViews::iterator view = all_extension_views_.begin();
383 view != all_extension_views_.end(); ++view) {
384 if (view->first->GetSiteInstance() == site_instance)
385 result.insert(view->first);
388 return result;
391 const Extension* ProcessManager::GetExtensionForRenderViewHost(
392 RenderViewHost* render_view_host) {
393 if (!render_view_host->GetSiteInstance())
394 return NULL;
396 return extension_registry_->enabled_extensions().GetByID(
397 GetExtensionID(render_view_host));
400 void ProcessManager::AcquireLazyKeepaliveCountForView(
401 content::RenderViewHost* render_view_host) {
402 auto it = all_extension_views_.find(render_view_host);
403 if (it == all_extension_views_.end())
404 return;
406 ExtensionRenderViewData* data = &it->second;
407 if (data->CanKeepalive() && !data->has_keepalive) {
408 const Extension* extension =
409 GetExtensionForRenderViewHost(render_view_host);
410 if (extension) {
411 IncrementLazyKeepaliveCount(extension);
412 data->has_keepalive = true;
417 void ProcessManager::ReleaseLazyKeepaliveCountForView(
418 content::RenderViewHost* render_view_host) {
419 auto it = all_extension_views_.find(render_view_host);
420 if (it == all_extension_views_.end())
421 return;
423 ExtensionRenderViewData* data = &it->second;
424 if (data->CanKeepalive() && data->has_keepalive) {
425 const Extension* extension =
426 GetExtensionForRenderViewHost(render_view_host);
427 if (extension) {
428 DecrementLazyKeepaliveCount(extension);
429 data->has_keepalive = false;
434 void ProcessManager::UnregisterRenderViewHost(
435 RenderViewHost* render_view_host) {
436 ExtensionRenderViews::iterator view =
437 all_extension_views_.find(render_view_host);
438 if (view == all_extension_views_.end())
439 return;
441 OnRenderViewHostUnregistered(GetBrowserContext(), render_view_host);
443 // Keepalive count, balanced in RegisterRenderViewHost.
444 ReleaseLazyKeepaliveCountForView(render_view_host);
445 all_extension_views_.erase(view);
448 bool ProcessManager::RegisterRenderViewHost(RenderViewHost* render_view_host) {
449 const Extension* extension = GetExtensionForRenderViewHost(
450 render_view_host);
451 if (!extension)
452 return false;
454 WebContents* web_contents = WebContents::FromRenderViewHost(render_view_host);
455 ExtensionRenderViewData* data = &all_extension_views_[render_view_host];
456 data->view_type = GetViewType(web_contents);
458 // Keep the lazy background page alive as long as any non-background-page
459 // extension views are visible. Keepalive count balanced in
460 // UnregisterRenderViewHost.
461 AcquireLazyKeepaliveCountForView(render_view_host);
462 return true;
465 scoped_refptr<SiteInstance> ProcessManager::GetSiteInstanceForURL(
466 const GURL& url) {
467 return make_scoped_refptr(site_instance_->GetRelatedSiteInstance(url));
470 bool ProcessManager::IsBackgroundHostClosing(const std::string& extension_id) {
471 ExtensionHost* host = GetBackgroundHostForExtension(extension_id);
472 return (host && background_page_data_[extension_id].is_closing);
475 int ProcessManager::GetLazyKeepaliveCount(const Extension* extension) {
476 if (!BackgroundInfo::HasLazyBackgroundPage(extension))
477 return 0;
479 return background_page_data_[extension->id()].lazy_keepalive_count;
482 void ProcessManager::IncrementLazyKeepaliveCount(const Extension* extension) {
483 if (!BackgroundInfo::HasLazyBackgroundPage(extension))
484 return;
486 int& count = background_page_data_[extension->id()].lazy_keepalive_count;
487 if (++count == 1)
488 OnLazyBackgroundPageActive(extension->id());
491 void ProcessManager::DecrementLazyKeepaliveCount(const Extension* extension) {
492 if (!BackgroundInfo::HasLazyBackgroundPage(extension))
493 return;
494 DecrementLazyKeepaliveCount(extension->id());
497 void ProcessManager::DecrementLazyKeepaliveCount(
498 const std::string& extension_id) {
499 int& count = background_page_data_[extension_id].lazy_keepalive_count;
500 DCHECK(count > 0 ||
501 !extension_registry_->enabled_extensions().Contains(extension_id));
503 // If we reach a zero keepalive count when the lazy background page is about
504 // to be closed, incrementing close_sequence_id will cancel the close
505 // sequence and cause the background page to linger. So check is_closing
506 // before initiating another close sequence.
507 if (--count == 0 && !background_page_data_[extension_id].is_closing) {
508 background_page_data_[extension_id].close_sequence_id =
509 ++last_background_close_sequence_id_;
510 base::MessageLoop::current()->PostDelayedTask(
511 FROM_HERE,
512 base::Bind(&ProcessManager::OnLazyBackgroundPageIdle,
513 weak_ptr_factory_.GetWeakPtr(),
514 extension_id,
515 last_background_close_sequence_id_),
516 base::TimeDelta::FromMilliseconds(g_event_page_idle_time_msec));
520 // This implementation layers on top of the keepalive count. An impulse sets
521 // a per extension flag. On a regular interval that flag is checked. Changes
522 // from the flag not being set to set cause an IncrementLazyKeepaliveCount.
523 void ProcessManager::KeepaliveImpulse(const Extension* extension) {
524 if (!BackgroundInfo::HasLazyBackgroundPage(extension))
525 return;
527 BackgroundPageData& bd = background_page_data_[extension->id()];
529 if (!bd.keepalive_impulse) {
530 bd.keepalive_impulse = true;
531 if (!bd.previous_keepalive_impulse) {
532 IncrementLazyKeepaliveCount(extension);
536 if (!keepalive_impulse_callback_for_testing_.is_null()) {
537 ImpulseCallbackForTesting callback_may_clear_callbacks_reentrantly =
538 keepalive_impulse_callback_for_testing_;
539 callback_may_clear_callbacks_reentrantly.Run(extension->id());
543 // static
544 void ProcessManager::OnKeepaliveFromPlugin(int render_process_id,
545 int render_frame_id,
546 const std::string& extension_id) {
547 content::RenderFrameHost* render_frame_host =
548 content::RenderFrameHost::FromID(render_process_id, render_frame_id);
549 if (!render_frame_host)
550 return;
552 content::SiteInstance* site_instance = render_frame_host->GetSiteInstance();
553 if (!site_instance)
554 return;
556 BrowserContext* browser_context = site_instance->GetBrowserContext();
557 const Extension* extension =
558 ExtensionRegistry::Get(browser_context)->enabled_extensions().GetByID(
559 extension_id);
560 if (!extension)
561 return;
563 ProcessManager::Get(browser_context)->KeepaliveImpulse(extension);
566 // DecrementLazyKeepaliveCount is called when no calls to KeepaliveImpulse
567 // have been made for at least g_event_page_idle_time_msec. In the best case an
568 // impulse was made just before being cleared, and the decrement will occur
569 // g_event_page_idle_time_msec later, causing a 2 * g_event_page_idle_time_msec
570 // total time for extension to be shut down based on impulses. Worst case is
571 // an impulse just after a clear, adding one check cycle and resulting in 3x
572 // total time.
573 void ProcessManager::OnKeepaliveImpulseCheck() {
574 for (BackgroundPageDataMap::iterator i = background_page_data_.begin();
575 i != background_page_data_.end();
576 ++i) {
577 if (i->second.previous_keepalive_impulse && !i->second.keepalive_impulse) {
578 DecrementLazyKeepaliveCount(i->first);
579 if (!keepalive_impulse_decrement_callback_for_testing_.is_null()) {
580 ImpulseCallbackForTesting callback_may_clear_callbacks_reentrantly =
581 keepalive_impulse_decrement_callback_for_testing_;
582 callback_may_clear_callbacks_reentrantly.Run(i->first);
586 i->second.previous_keepalive_impulse = i->second.keepalive_impulse;
587 i->second.keepalive_impulse = false;
590 // OnKeepaliveImpulseCheck() is always called in constructor, but in unit
591 // tests there will be no message loop. In that event don't schedule tasks.
592 if (base::MessageLoop::current()) {
593 base::MessageLoop::current()->PostDelayedTask(
594 FROM_HERE,
595 base::Bind(&ProcessManager::OnKeepaliveImpulseCheck,
596 weak_ptr_factory_.GetWeakPtr()),
597 base::TimeDelta::FromMilliseconds(g_event_page_idle_time_msec));
601 void ProcessManager::OnLazyBackgroundPageIdle(const std::string& extension_id,
602 uint64 sequence_id) {
603 ExtensionHost* host = GetBackgroundHostForExtension(extension_id);
604 if (host && !background_page_data_[extension_id].is_closing &&
605 sequence_id == background_page_data_[extension_id].close_sequence_id) {
606 // Tell the renderer we are about to close. This is a simple ping that the
607 // renderer will respond to. The purpose is to control sequencing: if the
608 // extension remains idle until the renderer responds with an ACK, then we
609 // know that the extension process is ready to shut down. If our
610 // close_sequence_id has already changed, then we would ignore the
611 // ShouldSuspendAck, so we don't send the ping.
612 host->render_view_host()->Send(new ExtensionMsg_ShouldSuspend(
613 extension_id, sequence_id));
617 void ProcessManager::OnLazyBackgroundPageActive(
618 const std::string& extension_id) {
619 if (!background_page_data_[extension_id].is_closing) {
620 // Cancel the current close sequence by changing the close_sequence_id,
621 // which causes us to ignore the next ShouldSuspendAck.
622 background_page_data_[extension_id].close_sequence_id =
623 ++last_background_close_sequence_id_;
627 void ProcessManager::OnShouldSuspendAck(const std::string& extension_id,
628 uint64 sequence_id) {
629 ExtensionHost* host = GetBackgroundHostForExtension(extension_id);
630 if (host &&
631 sequence_id == background_page_data_[extension_id].close_sequence_id) {
632 host->render_view_host()->Send(new ExtensionMsg_Suspend(extension_id));
636 void ProcessManager::OnSuspendAck(const std::string& extension_id) {
637 background_page_data_[extension_id].is_closing = true;
638 uint64 sequence_id = background_page_data_[extension_id].close_sequence_id;
639 base::MessageLoop::current()->PostDelayedTask(
640 FROM_HERE,
641 base::Bind(&ProcessManager::CloseLazyBackgroundPageNow,
642 weak_ptr_factory_.GetWeakPtr(),
643 extension_id,
644 sequence_id),
645 base::TimeDelta::FromMilliseconds(g_event_page_suspending_time_msec));
648 void ProcessManager::CloseLazyBackgroundPageNow(const std::string& extension_id,
649 uint64 sequence_id) {
650 ExtensionHost* host = GetBackgroundHostForExtension(extension_id);
651 if (host &&
652 sequence_id == background_page_data_[extension_id].close_sequence_id) {
653 // Close remaining views.
654 std::vector<RenderViewHost*> views_to_close;
655 for (const auto& view : all_extension_views_) {
656 if (view.second.CanKeepalive() &&
657 GetExtensionID(view.first) == extension_id) {
658 DCHECK(!view.second.has_keepalive);
659 views_to_close.push_back(view.first);
662 for (auto view : views_to_close) {
663 view->ClosePage();
664 // RenderViewHost::ClosePage() may result in calling
665 // UnregisterRenderViewHost() asynchronously and may cause race conditions
666 // when the background page is reloaded.
667 // To avoid this, unregister the view now.
668 UnregisterRenderViewHost(view);
671 ExtensionHost* host = GetBackgroundHostForExtension(extension_id);
672 if (host)
673 CloseBackgroundHost(host);
677 void ProcessManager::OnNetworkRequestStarted(
678 content::RenderFrameHost* render_frame_host,
679 uint64 request_id) {
680 ExtensionHost* host = GetBackgroundHostForExtension(
681 GetExtensionIDFromFrame(render_frame_host));
682 if (host && IsFrameInExtensionHost(host, render_frame_host)) {
683 IncrementLazyKeepaliveCount(host->extension());
684 host->OnNetworkRequestStarted(request_id);
688 void ProcessManager::OnNetworkRequestDone(
689 content::RenderFrameHost* render_frame_host,
690 uint64 request_id) {
691 ExtensionHost* host = GetBackgroundHostForExtension(
692 GetExtensionIDFromFrame(render_frame_host));
693 if (host && IsFrameInExtensionHost(host, render_frame_host)) {
694 host->OnNetworkRequestDone(request_id);
695 DecrementLazyKeepaliveCount(host->extension());
699 void ProcessManager::CancelSuspend(const Extension* extension) {
700 bool& is_closing = background_page_data_[extension->id()].is_closing;
701 ExtensionHost* host = GetBackgroundHostForExtension(extension->id());
702 if (host && is_closing) {
703 is_closing = false;
704 host->render_view_host()->Send(
705 new ExtensionMsg_CancelSuspend(extension->id()));
706 // This increment / decrement is to simulate an instantaneous event. This
707 // has the effect of invalidating close_sequence_id, preventing any in
708 // progress closes from completing and starting a new close process if
709 // necessary.
710 IncrementLazyKeepaliveCount(extension);
711 DecrementLazyKeepaliveCount(extension);
715 void ProcessManager::CloseBackgroundHosts() {
716 STLDeleteElements(&background_hosts_);
719 content::BrowserContext* ProcessManager::GetBrowserContext() const {
720 return site_instance_->GetBrowserContext();
723 void ProcessManager::SetKeepaliveImpulseCallbackForTesting(
724 const ImpulseCallbackForTesting& callback) {
725 keepalive_impulse_callback_for_testing_ = callback;
728 void ProcessManager::SetKeepaliveImpulseDecrementCallbackForTesting(
729 const ImpulseCallbackForTesting& callback) {
730 keepalive_impulse_decrement_callback_for_testing_ = callback;
733 // static
734 void ProcessManager::SetEventPageIdleTimeForTesting(unsigned idle_time_msec) {
735 CHECK_GT(idle_time_msec, 0u); // OnKeepaliveImpulseCheck requires non zero.
736 g_event_page_idle_time_msec = idle_time_msec;
739 // static
740 void ProcessManager::SetEventPageSuspendingTimeForTesting(
741 unsigned suspending_time_msec) {
742 g_event_page_suspending_time_msec = suspending_time_msec;
745 void ProcessManager::Observe(int type,
746 const content::NotificationSource& source,
747 const content::NotificationDetails& details) {
748 TRACE_EVENT0("browser,startup", "ProcessManager::Observe");
749 switch (type) {
750 case extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED: {
751 // TODO(jamescook): Convert this to use ExtensionSystem::ready() instead
752 // of a notification.
753 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.ProcessManagerStartupHostsTime");
754 MaybeCreateStartupBackgroundHosts();
755 break;
758 case extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED: {
759 ExtensionHost* host = content::Details<ExtensionHost>(details).ptr();
760 if (background_hosts_.erase(host)) {
761 ClearBackgroundPageData(host->extension()->id());
762 background_page_data_[host->extension()->id()].since_suspended.reset(
763 new base::ElapsedTimer());
765 break;
768 case extensions::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE: {
769 ExtensionHost* host = content::Details<ExtensionHost>(details).ptr();
770 if (host->extension_host_type() == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE) {
771 CloseBackgroundHost(host);
773 break;
776 case content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED: {
777 // We get this notification both for new WebContents and when one
778 // has its RenderViewHost replaced (e.g. when a user does a cross-site
779 // navigation away from an extension URL). For the replaced case, we must
780 // unregister the old RVH so it doesn't count as an active view that would
781 // keep the event page alive.
782 WebContents* contents = content::Source<WebContents>(source).ptr();
783 if (contents->GetBrowserContext() != GetBrowserContext())
784 break;
786 typedef std::pair<RenderViewHost*, RenderViewHost*> RVHPair;
787 RVHPair* switched_details = content::Details<RVHPair>(details).ptr();
788 if (switched_details->first)
789 UnregisterRenderViewHost(switched_details->first);
791 // The above will unregister a RVH when it gets swapped out with a new
792 // one. However we need to watch the WebContents to know when a RVH is
793 // deleted because the WebContents has gone away.
794 if (RegisterRenderViewHost(switched_details->second)) {
795 RenderViewHostDestructionObserver::CreateForWebContents(contents);
797 break;
800 case content::NOTIFICATION_WEB_CONTENTS_CONNECTED: {
801 WebContents* contents = content::Source<WebContents>(source).ptr();
802 if (contents->GetBrowserContext() != GetBrowserContext())
803 break;
804 const Extension* extension = GetExtensionForRenderViewHost(
805 contents->GetRenderViewHost());
806 if (!extension)
807 return;
809 // RegisterRenderViewHost is called too early (before the process is
810 // available), so we need to wait until now to notify.
811 content::NotificationService::current()->Notify(
812 extensions::NOTIFICATION_EXTENSION_VIEW_REGISTERED,
813 content::Source<BrowserContext>(GetBrowserContext()),
814 content::Details<RenderViewHost>(contents->GetRenderViewHost()));
815 break;
818 default:
819 NOTREACHED();
823 void ProcessManager::OnExtensionLoaded(BrowserContext* browser_context,
824 const Extension* extension) {
825 if (ExtensionSystem::Get(browser_context)->ready().is_signaled()) {
826 // The extension system is ready, so create the background host.
827 CreateBackgroundHostForExtensionLoad(this, extension);
831 void ProcessManager::OnExtensionUnloaded(
832 BrowserContext* browser_context,
833 const Extension* extension,
834 UnloadedExtensionInfo::Reason reason) {
835 ExtensionHost* host = GetBackgroundHostForExtension(extension->id());
836 if (host != NULL)
837 CloseBackgroundHost(host);
838 UnregisterExtension(extension->id());
841 void ProcessManager::OnDevToolsStateChanged(
842 content::DevToolsAgentHost* agent_host,
843 bool attached) {
844 WebContents* web_contents = agent_host->GetWebContents();
845 // Ignore unrelated notifications.
846 if (!web_contents || web_contents->GetBrowserContext() != GetBrowserContext())
847 return;
848 if (GetViewType(web_contents) != VIEW_TYPE_EXTENSION_BACKGROUND_PAGE)
849 return;
850 const Extension* extension =
851 GetExtensionForRenderViewHost(web_contents->GetRenderViewHost());
852 if (!extension)
853 return;
854 if (attached) {
855 // Keep the lazy background page alive while it's being inspected.
856 CancelSuspend(extension);
857 IncrementLazyKeepaliveCount(extension);
858 } else {
859 DecrementLazyKeepaliveCount(extension);
863 void ProcessManager::MaybeCreateStartupBackgroundHosts() {
864 if (startup_background_hosts_created_)
865 return;
867 // The embedder might disallow background pages entirely.
868 ProcessManagerDelegate* delegate =
869 ExtensionsBrowserClient::Get()->GetProcessManagerDelegate();
870 if (delegate && !delegate->IsBackgroundPageAllowed(GetBrowserContext()))
871 return;
873 // The embedder might want to defer background page loading. For example,
874 // Chrome defers background page loading when it is launched to show the app
875 // list, then triggers a load later when a browser window opens.
876 if (delegate &&
877 delegate->DeferCreatingStartupBackgroundHosts(GetBrowserContext()))
878 return;
880 CreateStartupBackgroundHosts();
881 startup_background_hosts_created_ = true;
883 // Background pages should only be loaded once. To prevent any further loads
884 // occurring, we remove the notification listeners.
885 BrowserContext* original_context =
886 ExtensionsBrowserClient::Get()->GetOriginalContext(GetBrowserContext());
887 if (registrar_.IsRegistered(
888 this,
889 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
890 content::Source<BrowserContext>(original_context))) {
891 registrar_.Remove(this,
892 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
893 content::Source<BrowserContext>(original_context));
897 void ProcessManager::CreateStartupBackgroundHosts() {
898 DCHECK(!startup_background_hosts_created_);
899 const ExtensionSet& enabled_extensions =
900 extension_registry_->enabled_extensions();
901 for (ExtensionSet::const_iterator extension = enabled_extensions.begin();
902 extension != enabled_extensions.end();
903 ++extension) {
904 CreateBackgroundHostForExtensionLoad(this, extension->get());
906 FOR_EACH_OBSERVER(ProcessManagerObserver,
907 observer_list_,
908 OnBackgroundHostStartup(extension->get()));
912 void ProcessManager::OnBackgroundHostCreated(ExtensionHost* host) {
913 DCHECK_EQ(GetBrowserContext(), host->browser_context());
914 background_hosts_.insert(host);
916 if (BackgroundInfo::HasLazyBackgroundPage(host->extension())) {
917 linked_ptr<base::ElapsedTimer> since_suspended(
918 background_page_data_[host->extension()->id()].
919 since_suspended.release());
920 if (since_suspended.get()) {
921 UMA_HISTOGRAM_LONG_TIMES("Extensions.EventPageIdleTime",
922 since_suspended->Elapsed());
925 FOR_EACH_OBSERVER(ProcessManagerObserver, observer_list_,
926 OnBackgroundHostCreated(host));
929 void ProcessManager::CloseBackgroundHost(ExtensionHost* host) {
930 ExtensionId extension_id = host->extension_id();
931 CHECK(host->extension_host_type() ==
932 VIEW_TYPE_EXTENSION_BACKGROUND_PAGE);
933 delete host;
934 // |host| should deregister itself from our structures.
935 CHECK(background_hosts_.find(host) == background_hosts_.end());
937 FOR_EACH_OBSERVER(ProcessManagerObserver,
938 observer_list_,
939 OnBackgroundHostClose(extension_id));
942 void ProcessManager::UnregisterExtension(const std::string& extension_id) {
943 // The lazy_keepalive_count may be greater than zero at this point because
944 // RenderViewHosts are still alive. During extension reloading, they will
945 // decrement the lazy_keepalive_count to negative for the new extension
946 // instance when they are destroyed. Since we are erasing the background page
947 // data for the unloaded extension, unregister the RenderViewHosts too.
948 BrowserContext* context = GetBrowserContext();
949 for (ExtensionRenderViews::iterator it = all_extension_views_.begin();
950 it != all_extension_views_.end(); ) {
951 if (GetExtensionID(it->first) == extension_id) {
952 OnRenderViewHostUnregistered(context, it->first);
953 all_extension_views_.erase(it++);
954 } else {
955 ++it;
959 background_page_data_.erase(extension_id);
962 void ProcessManager::ClearBackgroundPageData(const std::string& extension_id) {
963 background_page_data_.erase(extension_id);
965 // Re-register all RenderViews for this extension. We do this to restore
966 // the lazy_keepalive_count (if any) to properly reflect the number of open
967 // views.
968 for (ExtensionRenderViews::const_iterator it = all_extension_views_.begin();
969 it != all_extension_views_.end(); ++it) {
970 RenderViewHost* view = it->first;
971 const ExtensionRenderViewData& data = it->second;
972 // Do not increment the count when |has_keepalive| is false
973 // (i.e. ReleaseLazyKeepaliveCountForView() was called).
974 if (GetExtensionID(view) == extension_id && data.has_keepalive) {
975 const Extension* extension = GetExtensionForRenderViewHost(view);
976 if (extension)
977 IncrementLazyKeepaliveCount(extension);
983 // IncognitoProcessManager
986 IncognitoProcessManager::IncognitoProcessManager(
987 BrowserContext* incognito_context,
988 BrowserContext* original_context,
989 ExtensionRegistry* extension_registry)
990 : ProcessManager(incognito_context, original_context, extension_registry) {
991 DCHECK(incognito_context->IsOffTheRecord());
993 // The original profile will have its own ProcessManager to
994 // load the background pages of the spanning extensions. This process
995 // manager need only worry about the split mode extensions, which is handled
996 // in the NOTIFICATION_BROWSER_WINDOW_READY notification handler.
997 registrar_.Remove(this,
998 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
999 content::Source<BrowserContext>(original_context));
1002 bool IncognitoProcessManager::CreateBackgroundHost(const Extension* extension,
1003 const GURL& url) {
1004 if (IncognitoInfo::IsSplitMode(extension)) {
1005 if (ExtensionsBrowserClient::Get()->IsExtensionIncognitoEnabled(
1006 extension->id(), GetBrowserContext()))
1007 return ProcessManager::CreateBackgroundHost(extension, url);
1008 } else {
1009 // Do nothing. If an extension is spanning, then its original-profile
1010 // background page is shared with incognito, so we don't create another.
1012 return false;
1015 scoped_refptr<SiteInstance> IncognitoProcessManager::GetSiteInstanceForURL(
1016 const GURL& url) {
1017 const Extension* extension =
1018 extension_registry_->enabled_extensions().GetExtensionOrAppByURL(url);
1019 if (extension && !IncognitoInfo::IsSplitMode(extension)) {
1020 BrowserContext* original_context =
1021 ExtensionsBrowserClient::Get()->GetOriginalContext(GetBrowserContext());
1022 return ProcessManager::Get(original_context)->GetSiteInstanceForURL(url);
1025 return ProcessManager::GetSiteInstanceForURL(url);
1028 } // namespace extensions