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 "content/browser/frame_host/render_frame_host_manager.h"
9 #include "base/command_line.h"
10 #include "base/debug/trace_event.h"
11 #include "base/logging.h"
12 #include "base/stl_util.h"
13 #include "content/browser/child_process_security_policy_impl.h"
14 #include "content/browser/devtools/render_view_devtools_agent_host.h"
15 #include "content/browser/frame_host/cross_site_transferring_request.h"
16 #include "content/browser/frame_host/debug_urls.h"
17 #include "content/browser/frame_host/interstitial_page_impl.h"
18 #include "content/browser/frame_host/navigation_controller_impl.h"
19 #include "content/browser/frame_host/navigation_entry_impl.h"
20 #include "content/browser/frame_host/navigator.h"
21 #include "content/browser/frame_host/render_frame_host_factory.h"
22 #include "content/browser/frame_host/render_frame_host_impl.h"
23 #include "content/browser/frame_host/render_frame_proxy_host.h"
24 #include "content/browser/renderer_host/render_process_host_impl.h"
25 #include "content/browser/renderer_host/render_view_host_factory.h"
26 #include "content/browser/renderer_host/render_view_host_impl.h"
27 #include "content/browser/site_instance_impl.h"
28 #include "content/browser/webui/web_ui_controller_factory_registry.h"
29 #include "content/browser/webui/web_ui_impl.h"
30 #include "content/common/frame_messages.h"
31 #include "content/common/view_messages.h"
32 #include "content/public/browser/content_browser_client.h"
33 #include "content/public/browser/notification_service.h"
34 #include "content/public/browser/notification_types.h"
35 #include "content/public/browser/render_widget_host_iterator.h"
36 #include "content/public/browser/render_widget_host_view.h"
37 #include "content/public/browser/user_metrics.h"
38 #include "content/public/browser/web_ui_controller.h"
39 #include "content/public/common/content_switches.h"
40 #include "content/public/common/referrer.h"
41 #include "content/public/common/url_constants.h"
46 bool RenderFrameHostManager::ClearRFHsPendingShutdown(FrameTreeNode* node) {
47 node->render_manager()->pending_delete_hosts_.clear();
51 RenderFrameHostManager::RenderFrameHostManager(
52 FrameTreeNode* frame_tree_node,
53 RenderFrameHostDelegate* render_frame_delegate,
54 RenderViewHostDelegate* render_view_delegate,
55 RenderWidgetHostDelegate* render_widget_delegate,
57 : frame_tree_node_(frame_tree_node),
59 cross_navigation_pending_(false),
60 render_frame_delegate_(render_frame_delegate),
61 render_view_delegate_(render_view_delegate),
62 render_widget_delegate_(render_widget_delegate),
63 interstitial_page_(NULL),
65 DCHECK(frame_tree_node_);
68 RenderFrameHostManager::~RenderFrameHostManager() {
69 if (pending_render_frame_host_)
72 // We should always have a current RenderFrameHost except in some tests.
73 SetRenderFrameHost(scoped_ptr<RenderFrameHostImpl>());
75 // Delete any swapped out RenderFrameHosts.
76 STLDeleteValues(&proxy_hosts_);
79 void RenderFrameHostManager::Init(BrowserContext* browser_context,
80 SiteInstance* site_instance,
82 int frame_routing_id) {
83 // Create a RenderViewHost and RenderFrameHost, once we have an instance. It
84 // is important to immediately give this SiteInstance to a RenderViewHost so
85 // that the SiteInstance is ref counted.
87 site_instance = SiteInstance::Create(browser_context);
89 SetRenderFrameHost(CreateRenderFrameHost(site_instance,
93 delegate_->IsHidden()));
95 // Keep track of renderer processes as they start to shut down or are
97 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSED,
98 NotificationService::AllSources());
99 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSING,
100 NotificationService::AllSources());
103 RenderViewHostImpl* RenderFrameHostManager::current_host() const {
104 if (!render_frame_host_)
106 return render_frame_host_->render_view_host();
109 RenderViewHostImpl* RenderFrameHostManager::pending_render_view_host() const {
110 if (!pending_render_frame_host_)
112 return pending_render_frame_host_->render_view_host();
115 RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const {
116 if (interstitial_page_)
117 return interstitial_page_->GetView();
118 if (!render_frame_host_)
120 return render_frame_host_->render_view_host()->GetView();
123 RenderFrameProxyHost* RenderFrameHostManager::GetProxyToParent() {
124 if (frame_tree_node_->IsMainFrame())
127 RenderFrameProxyHostMap::iterator iter =
128 proxy_hosts_.find(frame_tree_node_->parent()
130 ->current_frame_host()
133 if (iter == proxy_hosts_.end())
139 void RenderFrameHostManager::SetPendingWebUI(const GURL& url,
141 pending_web_ui_.reset(
142 delegate_->CreateWebUIForRenderManager(url));
143 pending_and_current_web_ui_.reset();
145 // If we have assigned (zero or more) bindings to this NavigationEntry in the
146 // past, make sure we're not granting it different bindings than it had
147 // before. If so, note it and don't give it any bindings, to avoid a
148 // potential privilege escalation.
149 if (pending_web_ui_.get() &&
150 bindings != NavigationEntryImpl::kInvalidBindings &&
151 pending_web_ui_->GetBindings() != bindings) {
153 base::UserMetricsAction("ProcessSwapBindingsMismatch_RVHM"));
154 pending_web_ui_.reset();
158 RenderFrameHostImpl* RenderFrameHostManager::Navigate(
159 const NavigationEntryImpl& entry) {
160 TRACE_EVENT1("navigation", "RenderFrameHostManager:Navigate",
161 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
162 // Create a pending RenderFrameHost to use for the navigation.
163 RenderFrameHostImpl* dest_render_frame_host = UpdateStateForNavigate(
165 entry.site_instance(),
166 entry.GetTransitionType(),
167 entry.restore_type() != NavigationEntryImpl::RESTORE_NONE,
168 entry.IsViewSourceMode(),
169 entry.transferred_global_request_id(),
171 if (!dest_render_frame_host)
172 return NULL; // We weren't able to create a pending render frame host.
174 // If the current render_frame_host_ isn't live, we should create it so
175 // that we don't show a sad tab while the dest_render_frame_host fetches
176 // its first page. (Bug 1145340)
177 if (dest_render_frame_host != render_frame_host_ &&
178 !render_frame_host_->IsRenderFrameLive()) {
179 // Note: we don't call InitRenderView here because we are navigating away
180 // soon anyway, and we don't have the NavigationEntry for this host.
181 delegate_->CreateRenderViewForRenderManager(
182 render_frame_host_->render_view_host(), MSG_ROUTING_NONE,
183 MSG_ROUTING_NONE, frame_tree_node_->IsMainFrame());
186 // If the renderer crashed, then try to create a new one to satisfy this
187 // navigation request.
188 if (!dest_render_frame_host->IsRenderFrameLive()) {
189 // Instruct the destination render frame host to set up a Mojo connection
190 // with the new render frame if necessary. Note that this call needs to
191 // occur before initializing the RenderView; the flow of creating the
192 // RenderView can cause browser-side code to execute that expects the this
193 // RFH's ServiceRegistry to be initialized (e.g., if the site is a WebUI
194 // site that is handled via Mojo, then Mojo WebUI code in //chrome will
195 // add a service to this RFH's ServiceRegistry).
196 dest_render_frame_host->SetUpMojoIfNeeded();
198 // Recreate the opener chain.
199 int opener_route_id = delegate_->CreateOpenerRenderViewsForRenderManager(
200 dest_render_frame_host->GetSiteInstance());
201 if (!InitRenderView(dest_render_frame_host->render_view_host(),
204 frame_tree_node_->IsMainFrame()))
207 // Now that we've created a new renderer, be sure to hide it if it isn't
208 // our primary one. Otherwise, we might crash if we try to call Show()
210 if (dest_render_frame_host != render_frame_host_ &&
211 dest_render_frame_host->render_view_host()->GetView()) {
212 dest_render_frame_host->render_view_host()->GetView()->Hide();
214 // Notify here as we won't be calling CommitPending (which does the
216 delegate_->NotifySwappedFromRenderManager(
217 NULL, render_frame_host_.get(), frame_tree_node_->IsMainFrame());
221 // If entry includes the request ID of a request that is being transferred,
222 // the destination render frame will take ownership, so release ownership of
224 if (cross_site_transferring_request_.get() &&
225 cross_site_transferring_request_->request_id() ==
226 entry.transferred_global_request_id()) {
227 cross_site_transferring_request_->ReleaseRequest();
230 return dest_render_frame_host;
233 void RenderFrameHostManager::Stop() {
234 render_frame_host_->Stop();
236 // If we are cross-navigating, we should stop the pending renderers. This
237 // will lead to a DidFailProvisionalLoad, which will properly destroy them.
238 if (cross_navigation_pending_) {
239 pending_render_frame_host_->Send(new FrameMsg_Stop(
240 pending_render_frame_host_->GetRoutingID()));
244 void RenderFrameHostManager::SetIsLoading(bool is_loading) {
245 render_frame_host_->render_view_host()->SetIsLoading(is_loading);
246 if (pending_render_frame_host_)
247 pending_render_frame_host_->render_view_host()->SetIsLoading(is_loading);
250 bool RenderFrameHostManager::ShouldCloseTabOnUnresponsiveRenderer() {
251 // If we're waiting for a close ACK, then the tab should close whether there's
252 // a navigation in progress or not. Unfortunately, we also need to check for
253 // cases that we arrive here with no navigation in progress, since there are
254 // some tab closure paths that don't set is_waiting_for_close_ack to true.
255 // TODO(creis): Clean this up in http://crbug.com/418266.
256 if (!cross_navigation_pending_ ||
257 render_frame_host_->render_view_host()->is_waiting_for_close_ack())
260 // We should always have a pending RFH when there's a cross-process navigation
261 // in progress. Sanity check this for http://crbug.com/276333.
262 CHECK(pending_render_frame_host_);
264 // Unload handlers run in the background, so we should never get an
265 // unresponsiveness warning for them.
266 CHECK(!render_frame_host_->IsWaitingForUnloadACK());
268 // If the tab becomes unresponsive during beforeunload while doing a
269 // cross-site navigation, proceed with the navigation. (This assumes that
270 // the pending RenderFrameHost is still responsive.)
271 if (render_frame_host_->is_waiting_for_beforeunload_ack()) {
272 // Haven't gotten around to starting the request, because we're still
273 // waiting for the beforeunload handler to finish. We'll pretend that it
274 // did finish, to let the navigation proceed. Note that there's a danger
275 // that the beforeunload handler will later finish and possibly return
276 // false (meaning the navigation should not proceed), but we'll ignore it
277 // in this case because it took too long.
278 if (pending_render_frame_host_->are_navigations_suspended()) {
279 pending_render_frame_host_->SetNavigationsSuspended(
280 false, base::TimeTicks::Now());
286 void RenderFrameHostManager::OnBeforeUnloadACK(
287 bool for_cross_site_transition,
289 const base::TimeTicks& proceed_time) {
290 if (for_cross_site_transition) {
291 // Ignore if we're not in a cross-site navigation.
292 if (!cross_navigation_pending_)
296 // Ok to unload the current page, so proceed with the cross-site
297 // navigation. Note that if navigations are not currently suspended, it
298 // might be because the renderer was deemed unresponsive and this call was
299 // already made by ShouldCloseTabOnUnresponsiveRenderer. In that case, it
300 // is ok to do nothing here.
301 if (pending_render_frame_host_ &&
302 pending_render_frame_host_->are_navigations_suspended()) {
303 pending_render_frame_host_->SetNavigationsSuspended(false,
307 // Current page says to cancel.
309 cross_navigation_pending_ = false;
312 // Non-cross site transition means closing the entire tab.
313 bool proceed_to_fire_unload;
314 delegate_->BeforeUnloadFiredFromRenderManager(proceed, proceed_time,
315 &proceed_to_fire_unload);
317 if (proceed_to_fire_unload) {
318 // If we're about to close the tab and there's a pending RFH, cancel it.
319 // Otherwise, if the navigation in the pending RFH completes before the
320 // close in the current RFH, we'll lose the tab close.
321 if (pending_render_frame_host_) {
323 cross_navigation_pending_ = false;
326 // This is not a cross-site navigation, the tab is being closed.
327 render_frame_host_->render_view_host()->ClosePage();
332 void RenderFrameHostManager::OnCrossSiteResponse(
333 RenderFrameHostImpl* pending_render_frame_host,
334 const GlobalRequestID& global_request_id,
335 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
336 const std::vector<GURL>& transfer_url_chain,
337 const Referrer& referrer,
338 ui::PageTransition page_transition,
339 bool should_replace_current_entry) {
340 // We should only get here for transfer navigations. Most cross-process
341 // navigations can just continue and wait to run the unload handler (by
342 // swapping out) when the new navigation commits.
343 CHECK(cross_site_transferring_request.get());
345 // A transfer should only have come from our pending or current RFH.
346 // TODO(creis): We need to handle the case that the pending RFH has changed
347 // in the mean time, while this was being posted from the IO thread. We
348 // should probably cancel the request in that case.
349 DCHECK(pending_render_frame_host == pending_render_frame_host_ ||
350 pending_render_frame_host == render_frame_host_);
352 // Store the transferring request so that we can release it if the transfer
353 // navigation matches.
354 cross_site_transferring_request_ = cross_site_transferring_request.Pass();
356 // Sanity check that the params are for the correct frame and process.
357 // These should match the RenderFrameHost that made the request.
358 // If it started as a cross-process navigation via OpenURL, this is the
359 // pending one. If it wasn't cross-process until the transfer, this is the
361 int render_frame_id = pending_render_frame_host_ ?
362 pending_render_frame_host_->GetRoutingID() :
363 render_frame_host_->GetRoutingID();
364 DCHECK_EQ(render_frame_id, pending_render_frame_host->GetRoutingID());
365 int process_id = pending_render_frame_host_ ?
366 pending_render_frame_host_->GetProcess()->GetID() :
367 render_frame_host_->GetProcess()->GetID();
368 DCHECK_EQ(process_id, global_request_id.child_id);
370 // Treat the last URL in the chain as the destination and the remainder as
371 // the redirect chain.
372 CHECK(transfer_url_chain.size());
373 GURL transfer_url = transfer_url_chain.back();
374 std::vector<GURL> rest_of_chain = transfer_url_chain;
375 rest_of_chain.pop_back();
377 // We don't know whether the original request had |user_action| set to true.
378 // However, since we force the navigation to be in the current tab, it
380 pending_render_frame_host->frame_tree_node()->navigator()->RequestTransferURL(
381 pending_render_frame_host,
388 should_replace_current_entry,
391 // The transferring request was only needed during the RequestTransferURL
392 // call, so it is safe to clear at this point.
393 cross_site_transferring_request_.reset();
396 void RenderFrameHostManager::OnDeferredAfterResponseStarted(
397 const GlobalRequestID& global_request_id,
398 RenderFrameHostImpl* pending_render_frame_host) {
399 DCHECK(!response_started_id_.get());
401 response_started_id_.reset(new GlobalRequestID(global_request_id));
404 void RenderFrameHostManager::ResumeResponseDeferredAtStart() {
405 DCHECK(response_started_id_.get());
407 RenderProcessHostImpl* process =
408 static_cast<RenderProcessHostImpl*>(render_frame_host_->GetProcess());
409 process->ResumeResponseDeferredAtStart(*response_started_id_);
411 render_frame_host_->ClearPendingTransitionRequestData();
413 response_started_id_.reset();
416 void RenderFrameHostManager::ClearNavigationTransitionData() {
417 render_frame_host_->ClearPendingTransitionRequestData();
420 void RenderFrameHostManager::DidNavigateFrame(
421 RenderFrameHostImpl* render_frame_host) {
422 if (!cross_navigation_pending_) {
423 DCHECK(!pending_render_frame_host_);
425 // We should only hear this from our current renderer.
426 DCHECK_EQ(render_frame_host_, render_frame_host);
428 // Even when there is no pending RVH, there may be a pending Web UI.
429 if (pending_web_ui())
434 if (render_frame_host == pending_render_frame_host_) {
435 // The pending cross-site navigation completed, so show the renderer.
437 cross_navigation_pending_ = false;
438 } else if (render_frame_host == render_frame_host_) {
439 // A navigation in the original page has taken place. Cancel the pending
442 cross_navigation_pending_ = false;
444 // No one else should be sending us DidNavigate in this state.
449 void RenderFrameHostManager::DidDisownOpener(
450 RenderFrameHost* render_frame_host) {
451 // Notify all RenderFrameHosts but the one that notified us. This is necessary
452 // in case a process swap has occurred while the message was in flight.
453 for (RenderFrameProxyHostMap::iterator iter = proxy_hosts_.begin();
454 iter != proxy_hosts_.end();
456 DCHECK_NE(iter->second->GetSiteInstance(),
457 current_frame_host()->GetSiteInstance());
458 iter->second->DisownOpener();
461 if (render_frame_host_.get() != render_frame_host)
462 render_frame_host_->DisownOpener();
464 if (pending_render_frame_host_ &&
465 pending_render_frame_host_.get() != render_frame_host) {
466 pending_render_frame_host_->DisownOpener();
470 void RenderFrameHostManager::RendererProcessClosing(
471 RenderProcessHost* render_process_host) {
472 // Remove any swapped out RVHs from this process, so that we don't try to
473 // swap them back in while the process is exiting. Start by finding them,
474 // since there could be more than one.
475 std::list<int> ids_to_remove;
476 for (RenderFrameProxyHostMap::iterator iter = proxy_hosts_.begin();
477 iter != proxy_hosts_.end();
479 if (iter->second->GetProcess() == render_process_host)
480 ids_to_remove.push_back(iter->first);
484 while (!ids_to_remove.empty()) {
485 delete proxy_hosts_[ids_to_remove.back()];
486 proxy_hosts_.erase(ids_to_remove.back());
487 ids_to_remove.pop_back();
491 void RenderFrameHostManager::SwapOutOldFrame(
492 scoped_ptr<RenderFrameHostImpl> old_render_frame_host) {
493 TRACE_EVENT1("navigation", "RenderFrameHostManager::SwapOutOldFrame",
494 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
496 // Tell the renderer to suppress any further modal dialogs so that we can swap
497 // it out. This must be done before canceling any current dialog, in case
498 // there is a loop creating additional dialogs.
499 // TODO(creis): Handle modal dialogs in subframe processes.
500 old_render_frame_host->render_view_host()->SuppressDialogsUntilSwapOut();
502 // Now close any modal dialogs that would prevent us from swapping out. This
503 // must be done separately from SwapOut, so that the PageGroupLoadDeferrer is
504 // no longer on the stack when we send the SwapOut message.
505 delegate_->CancelModalDialogsForRenderManager();
507 // If the old RFH is not live, just return as there is no further work to do.
508 // It will be deleted and there will be no proxy created.
509 int32 old_site_instance_id =
510 old_render_frame_host->GetSiteInstance()->GetId();
511 if (!old_render_frame_host->IsRenderFrameLive()) {
512 ShutdownRenderFrameProxyHostsInSiteInstance(old_site_instance_id);
516 // If there are no active frames besides this one, we can delete the old
517 // RenderFrameHost once it runs its unload handler, without replacing it with
519 size_t active_frame_count =
520 old_render_frame_host->GetSiteInstance()->active_frame_count();
521 if (active_frame_count <= 1) {
522 // Tell the old RenderFrameHost to swap out, with no proxy to replace it.
523 old_render_frame_host->SwapOut(NULL);
524 MoveToPendingDeleteHosts(old_render_frame_host.Pass());
526 // Also clear out any proxies from this SiteInstance, in case this was the
527 // last one keeping other proxies alive.
528 ShutdownRenderFrameProxyHostsInSiteInstance(old_site_instance_id);
533 // Otherwise there are active views and we need a proxy for the old RFH.
534 // (There should not be one yet.)
535 CHECK(!GetRenderFrameProxyHost(old_render_frame_host->GetSiteInstance()));
536 RenderFrameProxyHost* proxy = new RenderFrameProxyHost(
537 old_render_frame_host->GetSiteInstance(), frame_tree_node_);
538 CHECK(proxy_hosts_.insert(std::make_pair(old_site_instance_id, proxy)).second)
539 << "Inserting a duplicate item.";
541 // Tell the old RenderFrameHost to swap out and be replaced by the proxy.
542 old_render_frame_host->SwapOut(proxy);
544 bool is_main_frame = frame_tree_node_->IsMainFrame();
545 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess) &&
547 // In --site-per-process, subframes delete their RFH rather than storing it
548 // in the proxy. Schedule it for deletion once the SwapOutACK comes in.
549 // TODO(creis): This will be the default when we remove swappedout://.
550 MoveToPendingDeleteHosts(old_render_frame_host.Pass());
552 // We shouldn't get here for subframes, since we only swap subframes when
553 // --site-per-process is used.
554 DCHECK(is_main_frame);
556 // The old RenderFrameHost will stay alive inside the proxy so that existing
557 // JavaScript window references to it stay valid.
558 proxy->TakeFrameHostOwnership(old_render_frame_host.Pass());
562 void RenderFrameHostManager::MoveToPendingDeleteHosts(
563 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
564 // |render_frame_host| will be deleted when its SwapOut ACK is received, or
565 // when the timer times out, or when the RFHM itself is deleted (whichever
567 pending_delete_hosts_.push_back(
568 linked_ptr<RenderFrameHostImpl>(render_frame_host.release()));
571 bool RenderFrameHostManager::IsPendingDeletion(
572 RenderFrameHostImpl* render_frame_host) {
573 for (const auto& rfh : pending_delete_hosts_) {
574 if (rfh == render_frame_host)
580 bool RenderFrameHostManager::DeleteFromPendingList(
581 RenderFrameHostImpl* render_frame_host) {
582 for (RFHPendingDeleteList::iterator iter = pending_delete_hosts_.begin();
583 iter != pending_delete_hosts_.end();
585 if (*iter == render_frame_host) {
586 pending_delete_hosts_.erase(iter);
593 void RenderFrameHostManager::ResetProxyHosts() {
594 STLDeleteValues(&proxy_hosts_);
598 RenderFrameHostImpl* RenderFrameHostManager::GetFrameHostForNavigation(
600 ui::PageTransition transition) {
601 CHECK(CommandLine::ForCurrentProcess()->HasSwitch(
602 switches::kEnableBrowserSideNavigation));
603 // TODO(clamy): When we handle renderer initiated navigations, make sure not
604 // to use a different process for subframes if --site-per-process is not
607 // Pick the right RenderFrameHost to commit the navigation.
608 // TODO(clamy): Replace the default values by the right ones.
609 RenderFrameHostImpl* render_frame_host = UpdateStateForNavigate(
610 url, NULL, transition, false, false, GlobalRequestID(),
611 NavigationEntryImpl::kInvalidBindings);
613 // If the renderer that needs to navigate is not live (it was just created or
614 // it crashed), initialize it.
615 if (!render_frame_host->render_view_host()->IsRenderViewLive()) {
616 // Recreate the opener chain.
617 int opener_route_id = delegate_->CreateOpenerRenderViewsForRenderManager(
618 render_frame_host->GetSiteInstance());
619 if (!InitRenderView(render_frame_host->render_view_host(),
622 frame_tree_node_->IsMainFrame())) {
626 return render_frame_host;
629 void RenderFrameHostManager::Observe(
631 const NotificationSource& source,
632 const NotificationDetails& details) {
634 case NOTIFICATION_RENDERER_PROCESS_CLOSED:
635 case NOTIFICATION_RENDERER_PROCESS_CLOSING:
636 RendererProcessClosing(
637 Source<RenderProcessHost>(source).ptr());
646 bool RenderFrameHostManager::ClearProxiesInSiteInstance(
647 int32 site_instance_id,
648 FrameTreeNode* node) {
649 RenderFrameProxyHostMap::iterator iter =
650 node->render_manager()->proxy_hosts_.find(site_instance_id);
651 if (iter != node->render_manager()->proxy_hosts_.end()) {
652 RenderFrameProxyHost* proxy = iter->second;
653 // Delete the proxy. If it is for a main frame (and thus the RFH is stored
654 // in the proxy) and it was still pending swap out, move the RFH to the
655 // pending deletion list first.
656 if (node->IsMainFrame() &&
657 proxy->render_frame_host()->rfh_state() ==
658 RenderFrameHostImpl::STATE_PENDING_SWAP_OUT) {
659 scoped_ptr<RenderFrameHostImpl> swapped_out_rfh =
660 proxy->PassFrameHostOwnership();
661 node->render_manager()->MoveToPendingDeleteHosts(swapped_out_rfh.Pass());
664 node->render_manager()->proxy_hosts_.erase(site_instance_id);
670 bool RenderFrameHostManager::ShouldTransitionCrossSite() {
671 // False in the single-process mode, as it makes RVHs to accumulate
672 // in swapped_out_hosts_.
673 // True if we are using process-per-site-instance (default) or
674 // process-per-site (kProcessPerSite).
676 !CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess) &&
677 !CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessPerTab);
680 bool RenderFrameHostManager::ShouldSwapBrowsingInstancesForNavigation(
681 const GURL& current_effective_url,
682 bool current_is_view_source_mode,
683 SiteInstance* new_site_instance,
684 const GURL& new_effective_url,
685 bool new_is_view_source_mode) const {
686 // If new_entry already has a SiteInstance, assume it is correct. We only
687 // need to force a swap if it is in a different BrowsingInstance.
688 if (new_site_instance) {
689 return !new_site_instance->IsRelatedSiteInstance(
690 render_frame_host_->GetSiteInstance());
693 // Check for reasons to swap processes even if we are in a process model that
694 // doesn't usually swap (e.g., process-per-tab). Any time we return true,
695 // the new_entry will be rendered in a new SiteInstance AND BrowsingInstance.
696 BrowserContext* browser_context =
697 delegate_->GetControllerForRenderManager().GetBrowserContext();
699 // Don't force a new BrowsingInstance for debug URLs that are handled in the
700 // renderer process, like javascript: or chrome://crash.
701 if (IsRendererDebugURL(new_effective_url))
704 // For security, we should transition between processes when one is a Web UI
705 // page and one isn't.
706 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
707 render_frame_host_->GetProcess()->GetID()) ||
708 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
709 browser_context, current_effective_url)) {
710 // If so, force a swap if destination is not an acceptable URL for Web UI.
711 // Here, data URLs are never allowed.
712 if (!WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
713 browser_context, new_effective_url)) {
717 // Force a swap if it's a Web UI URL.
718 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
719 browser_context, new_effective_url)) {
724 // Check with the content client as well. Important to pass
725 // current_effective_url here, which uses the SiteInstance's site if there is
727 if (GetContentClient()->browser()->ShouldSwapBrowsingInstancesForNavigation(
728 render_frame_host_->GetSiteInstance(),
729 current_effective_url, new_effective_url)) {
733 // We can't switch a RenderView between view source and non-view source mode
734 // without screwing up the session history sometimes (when navigating between
735 // "view-source:http://foo.com/" and "http://foo.com/", Blink doesn't treat
736 // it as a new navigation). So require a BrowsingInstance switch.
737 if (current_is_view_source_mode != new_is_view_source_mode)
743 bool RenderFrameHostManager::ShouldReuseWebUI(
744 const NavigationEntry* current_entry,
745 const GURL& new_url) const {
746 NavigationControllerImpl& controller =
747 delegate_->GetControllerForRenderManager();
748 return current_entry && web_ui_.get() &&
749 (WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
750 controller.GetBrowserContext(), current_entry->GetURL()) ==
751 WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
752 controller.GetBrowserContext(), new_url));
755 SiteInstance* RenderFrameHostManager::GetSiteInstanceForNavigation(
756 const GURL& dest_url,
757 SiteInstance* dest_instance,
758 ui::PageTransition dest_transition,
759 bool dest_is_restore,
760 bool dest_is_view_source_mode) {
761 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
762 SiteInstance* new_instance = current_instance;
764 // We do not currently swap processes for navigations in webview tag guests.
765 if (current_instance->GetSiteURL().SchemeIs(kGuestScheme))
766 return current_instance;
768 // Determine if we need a new BrowsingInstance for this entry. If true, this
769 // implies that it will get a new SiteInstance (and likely process), and that
770 // other tabs in the current BrowsingInstance will be unable to script it.
771 // This is used for cases that require a process swap even in the
772 // process-per-tab model, such as WebUI pages.
773 // TODO(clamy): Remove the dependency on the current entry.
774 const NavigationEntry* current_entry =
775 delegate_->GetLastCommittedNavigationEntryForRenderManager();
776 BrowserContext* browser_context =
777 delegate_->GetControllerForRenderManager().GetBrowserContext();
778 const GURL& current_effective_url = current_entry ?
779 SiteInstanceImpl::GetEffectiveURL(browser_context,
780 current_entry->GetURL()) :
781 render_frame_host_->GetSiteInstance()->GetSiteURL();
782 bool current_is_view_source_mode = current_entry ?
783 current_entry->IsViewSourceMode() : dest_is_view_source_mode;
784 bool force_swap = ShouldSwapBrowsingInstancesForNavigation(
785 current_effective_url,
786 current_is_view_source_mode,
788 SiteInstanceImpl::GetEffectiveURL(browser_context, dest_url),
789 dest_is_view_source_mode);
790 if (ShouldTransitionCrossSite() || force_swap) {
791 new_instance = GetSiteInstanceForURL(
796 dest_is_view_source_mode,
801 // If force_swap is true, we must use a different SiteInstance. If we didn't,
802 // we would have two RenderFrameHosts in the same SiteInstance and the same
803 // frame, resulting in page_id conflicts for their NavigationEntries.
805 CHECK_NE(new_instance, current_instance);
809 SiteInstance* RenderFrameHostManager::GetSiteInstanceForURL(
810 const GURL& dest_url,
811 SiteInstance* dest_instance,
812 ui::PageTransition dest_transition,
813 bool dest_is_restore,
814 bool dest_is_view_source_mode,
815 SiteInstance* current_instance,
816 bool force_browsing_instance_swap) {
817 NavigationControllerImpl& controller =
818 delegate_->GetControllerForRenderManager();
819 BrowserContext* browser_context = controller.GetBrowserContext();
821 // If the entry has an instance already we should use it.
823 // If we are forcing a swap, this should be in a different BrowsingInstance.
824 if (force_browsing_instance_swap) {
825 CHECK(!dest_instance->IsRelatedSiteInstance(
826 render_frame_host_->GetSiteInstance()));
828 return dest_instance;
831 // If a swap is required, we need to force the SiteInstance AND
832 // BrowsingInstance to be different ones, using CreateForURL.
833 if (force_browsing_instance_swap)
834 return SiteInstance::CreateForURL(browser_context, dest_url);
836 // (UGLY) HEURISTIC, process-per-site only:
838 // If this navigation is generated, then it probably corresponds to a search
839 // query. Given that search results typically lead to users navigating to
840 // other sites, we don't really want to use the search engine hostname to
841 // determine the site instance for this navigation.
843 // NOTE: This can be removed once we have a way to transition between
844 // RenderViews in response to a link click.
846 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessPerSite) &&
847 ui::PageTransitionCoreTypeIs(
848 dest_transition, ui::PAGE_TRANSITION_GENERATED)) {
849 return current_instance;
852 SiteInstanceImpl* current_site_instance =
853 static_cast<SiteInstanceImpl*>(current_instance);
855 // If we haven't used our SiteInstance (and thus RVH) yet, then we can use it
856 // for this entry. We won't commit the SiteInstance to this site until the
857 // navigation commits (in DidNavigate), unless the navigation entry was
858 // restored or it's a Web UI as described below.
859 if (!current_site_instance->HasSite()) {
860 // If we've already created a SiteInstance for our destination, we don't
861 // want to use this unused SiteInstance; use the existing one. (We don't
862 // do this check if the current_instance has a site, because for now, we
863 // want to compare against the current URL and not the SiteInstance's site.
864 // In this case, there is no current URL, so comparing against the site is
865 // ok. See additional comments below.)
867 // Also, if the URL should use process-per-site mode and there is an
868 // existing process for the site, we should use it. We can call
869 // GetRelatedSiteInstance() for this, which will eagerly set the site and
870 // thus use the correct process.
871 bool use_process_per_site =
872 RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) &&
873 RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url);
874 if (current_site_instance->HasRelatedSiteInstance(dest_url) ||
875 use_process_per_site) {
876 return current_site_instance->GetRelatedSiteInstance(dest_url);
879 // For extensions, Web UI URLs (such as the new tab page), and apps we do
880 // not want to use the current_instance if it has no site, since it will
881 // have a RenderProcessHost of PRIV_NORMAL. Create a new SiteInstance for
882 // this URL instead (with the correct process type).
883 if (current_site_instance->HasWrongProcessForURL(dest_url))
884 return current_site_instance->GetRelatedSiteInstance(dest_url);
886 // View-source URLs must use a new SiteInstance and BrowsingInstance.
887 // TODO(nasko): This is the same condition as later in the function. This
888 // should be taken into account when refactoring this method as part of
889 // http://crbug.com/123007.
890 if (dest_is_view_source_mode)
891 return SiteInstance::CreateForURL(browser_context, dest_url);
893 // If we are navigating from a blank SiteInstance to a WebUI, make sure we
894 // create a new SiteInstance.
895 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
896 browser_context, dest_url)) {
897 return SiteInstance::CreateForURL(browser_context, dest_url);
900 // Normally the "site" on the SiteInstance is set lazily when the load
901 // actually commits. This is to support better process sharing in case
902 // the site redirects to some other site: we want to use the destination
903 // site in the site instance.
905 // In the case of session restore, as it loads all the pages immediately
906 // we need to set the site first, otherwise after a restore none of the
907 // pages would share renderers in process-per-site.
909 // The embedder can request some urls never to be assigned to SiteInstance
910 // through the ShouldAssignSiteForURL() content client method, so that
911 // renderers created for particular chrome urls (e.g. the chrome-native://
912 // scheme) can be reused for subsequent navigations in the same WebContents.
913 // See http://crbug.com/386542.
914 if (dest_is_restore &&
915 GetContentClient()->browser()->ShouldAssignSiteForURL(dest_url)) {
916 current_site_instance->SetSite(dest_url);
919 return current_site_instance;
922 // Otherwise, only create a new SiteInstance for a cross-site navigation.
924 // TODO(creis): Once we intercept links and script-based navigations, we
925 // will be able to enforce that all entries in a SiteInstance actually have
926 // the same site, and it will be safe to compare the URL against the
927 // SiteInstance's site, as follows:
928 // const GURL& current_url = current_instance->site();
929 // For now, though, we're in a hybrid model where you only switch
930 // SiteInstances if you type in a cross-site URL. This means we have to
931 // compare the entry's URL to the last committed entry's URL.
932 NavigationEntry* current_entry = controller.GetLastCommittedEntry();
933 if (interstitial_page_) {
934 // The interstitial is currently the last committed entry, but we want to
935 // compare against the last non-interstitial entry.
936 current_entry = controller.GetEntryAtOffset(-1);
939 // View-source URLs must use a new SiteInstance and BrowsingInstance.
940 // We don't need a swap when going from view-source to a debug URL like
941 // chrome://crash, however.
942 // TODO(creis): Refactor this method so this duplicated code isn't needed.
943 // See http://crbug.com/123007.
945 current_entry->IsViewSourceMode() != dest_is_view_source_mode &&
946 !IsRendererDebugURL(dest_url)) {
947 return SiteInstance::CreateForURL(browser_context, dest_url);
950 // Use the current SiteInstance for same site navigations, as long as the
951 // process type is correct. (The URL may have been installed as an app since
952 // the last time we visited it.)
953 const GURL& current_url =
954 GetCurrentURLForSiteInstance(current_instance, current_entry);
955 if (SiteInstance::IsSameWebSite(browser_context, current_url, dest_url) &&
956 !current_site_instance->HasWrongProcessForURL(dest_url)) {
957 return current_instance;
960 // Start the new renderer in a new SiteInstance, but in the current
961 // BrowsingInstance. It is important to immediately give this new
962 // SiteInstance to a RenderViewHost (if it is different than our current
963 // SiteInstance), so that it is ref counted. This will happen in
965 return current_instance->GetRelatedSiteInstance(dest_url);
968 const GURL& RenderFrameHostManager::GetCurrentURLForSiteInstance(
969 SiteInstance* current_instance, NavigationEntry* current_entry) {
970 // If this is a subframe that is potentially out of process from its parent,
971 // don't consider using current_entry's url for SiteInstance selection, since
972 // current_entry's url is for the main frame and may be in a different site
974 // TODO(creis): Remove this when we can check the FrameNavigationEntry's url.
975 // See http://crbug.com/369654
976 if (!frame_tree_node_->IsMainFrame() &&
977 CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess))
978 return frame_tree_node_->current_url();
980 // If there is no last non-interstitial entry (and current_instance already
981 // has a site), then we must have been opened from another tab. We want
982 // to compare against the URL of the page that opened us, but we can't
983 // get to it directly. The best we can do is check against the site of
984 // the SiteInstance. This will be correct when we intercept links and
985 // script-based navigations, but for now, it could place some pages in a
986 // new process unnecessarily. We should only hit this case if a page tries
987 // to open a new tab to an interstitial-inducing URL, and then navigates
988 // the page to a different same-site URL. (This seems very unlikely in
991 return current_entry->GetURL();
992 return current_instance->GetSiteURL();
995 void RenderFrameHostManager::CreateRenderFrameHostForNewSiteInstance(
996 SiteInstance* old_instance,
997 SiteInstance* new_instance,
998 bool is_main_frame) {
999 // Ensure that we have created RFHs for the new RFH's opener chain if
1000 // we are staying in the same BrowsingInstance. This allows the new RFH
1001 // to send cross-process script calls to its opener(s).
1002 int opener_route_id = MSG_ROUTING_NONE;
1003 if (new_instance->IsRelatedSiteInstance(old_instance)) {
1005 delegate_->CreateOpenerRenderViewsForRenderManager(new_instance);
1006 if (CommandLine::ForCurrentProcess()->HasSwitch(
1007 switches::kSitePerProcess)) {
1008 // Ensure that the frame tree has RenderFrameProxyHosts for the new
1009 // SiteInstance in all nodes except the current one.
1010 frame_tree_node_->frame_tree()->CreateProxiesForSiteInstance(
1011 frame_tree_node_, new_instance);
1015 // Create a non-swapped-out RFH with the given opener.
1016 int route_id = CreateRenderFrame(
1017 new_instance, opener_route_id, false, is_main_frame,
1018 delegate_->IsHidden());
1019 if (route_id == MSG_ROUTING_NONE) {
1020 pending_render_frame_host_.reset();
1025 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::CreateRenderFrameHost(
1026 SiteInstance* site_instance,
1027 int view_routing_id,
1028 int frame_routing_id,
1031 if (frame_routing_id == MSG_ROUTING_NONE)
1032 frame_routing_id = site_instance->GetProcess()->GetNextRoutingID();
1034 // Create a RVH for main frames, or find the existing one for subframes.
1035 FrameTree* frame_tree = frame_tree_node_->frame_tree();
1036 RenderViewHostImpl* render_view_host = NULL;
1037 if (frame_tree_node_->IsMainFrame()) {
1038 render_view_host = frame_tree->CreateRenderViewHost(
1039 site_instance, view_routing_id, frame_routing_id, swapped_out, hidden);
1041 render_view_host = frame_tree->GetRenderViewHost(site_instance);
1043 CHECK(render_view_host);
1046 // TODO(creis): Pass hidden to RFH.
1047 scoped_ptr<RenderFrameHostImpl> render_frame_host =
1048 make_scoped_ptr(RenderFrameHostFactory::Create(render_view_host,
1049 render_frame_delegate_,
1053 swapped_out).release());
1054 return render_frame_host.Pass();
1057 int RenderFrameHostManager::CreateRenderFrame(SiteInstance* instance,
1058 int opener_route_id,
1060 bool for_main_frame_navigation,
1063 DCHECK(!swapped_out || hidden); // Swapped out views should always be hidden.
1065 // TODO(nasko): Remove the following CHECK once cross-site navigation no
1066 // longer relies on swapped out RFH for the top-level frame.
1067 if (!frame_tree_node_->IsMainFrame()) {
1068 CHECK(!swapped_out);
1071 scoped_ptr<RenderFrameHostImpl> new_render_frame_host;
1072 RenderFrameHostImpl* frame_to_announce = NULL;
1073 int routing_id = MSG_ROUTING_NONE;
1075 // We are creating a pending or swapped out RFH here. We should never create
1076 // it in the same SiteInstance as our current RFH.
1077 CHECK_NE(render_frame_host_->GetSiteInstance(), instance);
1079 // Check if we've already created an RFH for this SiteInstance. If so, try
1080 // to re-use the existing one, which has already been initialized. We'll
1081 // remove it from the list of proxy hosts below if it will be active.
1082 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1084 if (proxy && proxy->render_frame_host()) {
1085 routing_id = proxy->GetRenderViewHost()->GetRoutingID();
1086 // Delete the existing RenderFrameProxyHost, but reuse the RenderFrameHost.
1087 // Prevent the process from exiting while we're trying to use it.
1089 new_render_frame_host = proxy->PassFrameHostOwnership();
1090 new_render_frame_host->GetProcess()->AddPendingView();
1092 proxy_hosts_.erase(instance->GetId());
1095 // When a new render view is created by the renderer, the new WebContents
1096 // gets a RenderViewHost in the SiteInstance of its opener WebContents.
1097 // If not used in the first navigation, this RVH is swapped out and is not
1098 // granted bindings, so we may need to grant them when swapping it in.
1099 if (pending_web_ui() &&
1100 !new_render_frame_host->GetProcess()->IsIsolatedGuest()) {
1101 int required_bindings = pending_web_ui()->GetBindings();
1102 RenderViewHost* rvh = new_render_frame_host->render_view_host();
1103 if ((rvh->GetEnabledBindings() & required_bindings) !=
1104 required_bindings) {
1105 rvh->AllowBindings(required_bindings);
1110 // Create a new RenderFrameHost if we don't find an existing one.
1111 new_render_frame_host = CreateRenderFrameHost(
1112 instance, MSG_ROUTING_NONE, MSG_ROUTING_NONE, swapped_out, hidden);
1113 RenderViewHostImpl* render_view_host =
1114 new_render_frame_host->render_view_host();
1115 int proxy_routing_id = MSG_ROUTING_NONE;
1117 // Prevent the process from exiting while we're trying to navigate in it.
1118 // Otherwise, if the new RFH is swapped out already, store it.
1120 new_render_frame_host->GetProcess()->AddPendingView();
1122 proxy = new RenderFrameProxyHost(
1123 new_render_frame_host->GetSiteInstance(), frame_tree_node_);
1124 proxy_hosts_[instance->GetId()] = proxy;
1125 proxy_routing_id = proxy->GetRoutingID();
1126 if (frame_tree_node_->IsMainFrame())
1127 proxy->TakeFrameHostOwnership(new_render_frame_host.Pass());
1130 bool success = InitRenderView(render_view_host,
1133 for_main_frame_navigation);
1135 if (frame_tree_node_->IsMainFrame()) {
1136 // Don't show the main frame's view until we get a DidNavigate from it.
1137 render_view_host->GetView()->Hide();
1138 } else if (!swapped_out) {
1139 // Init the RFH, so a RenderFrame is created in the renderer.
1140 DCHECK(new_render_frame_host.get());
1141 success = InitRenderFrame(new_render_frame_host.get());
1143 } else if (!swapped_out && pending_render_frame_host_) {
1146 routing_id = render_view_host->GetRoutingID();
1147 frame_to_announce = new_render_frame_host.get();
1150 // Use this as our new pending RFH if it isn't swapped out.
1152 pending_render_frame_host_ = new_render_frame_host.Pass();
1154 // If a brand new RFH was created, announce it to observers.
1155 if (frame_to_announce)
1156 render_frame_delegate_->RenderFrameCreated(frame_to_announce);
1161 int RenderFrameHostManager::CreateRenderFrameProxy(SiteInstance* instance) {
1162 // A RenderFrameProxyHost should never be created in the same SiteInstance as
1165 CHECK_NE(instance, render_frame_host_->GetSiteInstance());
1167 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1169 return proxy->GetRoutingID();
1171 proxy = new RenderFrameProxyHost(instance, frame_tree_node_);
1172 proxy_hosts_[instance->GetId()] = proxy;
1173 proxy->InitRenderFrameProxy();
1174 return proxy->GetRoutingID();
1177 bool RenderFrameHostManager::InitRenderView(
1178 RenderViewHostImpl* render_view_host,
1179 int opener_route_id,
1180 int proxy_routing_id,
1181 bool for_main_frame_navigation) {
1182 // We may have initialized this RenderViewHost for another RenderFrameHost.
1183 if (render_view_host->IsRenderViewLive())
1186 // If the pending navigation is to a WebUI and the RenderView is not in a
1187 // guest process, tell the RenderViewHost about any bindings it will need
1189 if (pending_web_ui() && !render_view_host->GetProcess()->IsIsolatedGuest()) {
1190 render_view_host->AllowBindings(pending_web_ui()->GetBindings());
1192 // Ensure that we don't create an unprivileged RenderView in a WebUI-enabled
1193 // process unless it's swapped out.
1194 if (render_view_host->is_active()) {
1195 CHECK(!ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1196 render_view_host->GetProcess()->GetID()));
1200 return delegate_->CreateRenderViewForRenderManager(render_view_host,
1203 for_main_frame_navigation);
1206 bool RenderFrameHostManager::InitRenderFrame(
1207 RenderFrameHostImpl* render_frame_host) {
1208 if (render_frame_host->IsRenderFrameLive())
1211 int parent_routing_id = MSG_ROUTING_NONE;
1212 int proxy_routing_id = MSG_ROUTING_NONE;
1213 if (frame_tree_node_->parent()) {
1214 parent_routing_id = frame_tree_node_->parent()->render_manager()->
1215 GetRoutingIdForSiteInstance(render_frame_host->GetSiteInstance());
1216 CHECK_NE(parent_routing_id, MSG_ROUTING_NONE);
1218 // Check whether there is an existing proxy for this frame in this
1219 // SiteInstance. If there is, the new RenderFrame needs to be able to find
1220 // the proxy it is replacing, so that it can fully initialize itself.
1221 // NOTE: This is the only time that a RenderFrameProxyHost can be in the same
1222 // SiteInstance as its RenderFrameHost. This is only the case until the
1223 // RenderFrameHost commits, at which point it will replace and delete the
1224 // RenderFrameProxyHost.
1225 RenderFrameProxyHost* existing_proxy =
1226 GetRenderFrameProxyHost(render_frame_host->GetSiteInstance());
1227 if (existing_proxy) {
1228 proxy_routing_id = existing_proxy->GetRoutingID();
1229 CHECK_NE(proxy_routing_id, MSG_ROUTING_NONE);
1231 return delegate_->CreateRenderFrameForRenderManager(render_frame_host,
1236 int RenderFrameHostManager::GetRoutingIdForSiteInstance(
1237 SiteInstance* site_instance) {
1238 if (render_frame_host_->GetSiteInstance() == site_instance)
1239 return render_frame_host_->GetRoutingID();
1241 RenderFrameProxyHostMap::iterator iter =
1242 proxy_hosts_.find(site_instance->GetId());
1243 if (iter != proxy_hosts_.end())
1244 return iter->second->GetRoutingID();
1246 return MSG_ROUTING_NONE;
1249 void RenderFrameHostManager::CommitPending() {
1250 TRACE_EVENT1("navigation", "RenderFrameHostManager::CommitPending",
1251 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
1252 // First check whether we're going to want to focus the location bar after
1253 // this commit. We do this now because the navigation hasn't formally
1254 // committed yet, so if we've already cleared |pending_web_ui_| the call chain
1255 // this triggers won't be able to figure out what's going on.
1256 bool will_focus_location_bar = delegate_->FocusLocationBarByDefault();
1258 // Next commit the Web UI, if any. Either replace |web_ui_| with
1259 // |pending_web_ui_|, or clear |web_ui_| if there is no pending WebUI, or
1260 // leave |web_ui_| as is if reusing it.
1261 DCHECK(!(pending_web_ui_.get() && pending_and_current_web_ui_.get()));
1262 if (pending_web_ui_) {
1263 web_ui_.reset(pending_web_ui_.release());
1264 } else if (!pending_and_current_web_ui_.get()) {
1267 DCHECK_EQ(pending_and_current_web_ui_.get(), web_ui_.get());
1268 pending_and_current_web_ui_.reset();
1271 // It's possible for the pending_render_frame_host_ to be NULL when we aren't
1272 // crossing process boundaries. If so, we just needed to handle the Web UI
1273 // committing above and we're done.
1274 if (!pending_render_frame_host_) {
1275 if (will_focus_location_bar)
1276 delegate_->SetFocusToLocationBar(false);
1280 // Remember if the page was focused so we can focus the new renderer in
1282 bool focus_render_view = !will_focus_location_bar &&
1283 render_frame_host_->render_view_host()->GetView() &&
1284 render_frame_host_->render_view_host()->GetView()->HasFocus();
1286 bool is_main_frame = frame_tree_node_->IsMainFrame();
1288 // Swap in the pending frame and make it active. Also ensure the FrameTree
1290 scoped_ptr<RenderFrameHostImpl> old_render_frame_host =
1291 SetRenderFrameHost(pending_render_frame_host_.Pass());
1293 render_frame_host_->render_view_host()->AttachToFrameTree();
1295 // The process will no longer try to exit, so we can decrement the count.
1296 render_frame_host_->GetProcess()->RemovePendingView();
1298 // Show the new view (or a sad tab) if necessary.
1299 bool new_rfh_has_view = !!render_frame_host_->render_view_host()->GetView();
1300 if (!delegate_->IsHidden() && new_rfh_has_view) {
1301 // In most cases, we need to show the new view.
1302 render_frame_host_->render_view_host()->GetView()->Show();
1304 if (!new_rfh_has_view) {
1305 // If the view is gone, then this RenderViewHost died while it was hidden.
1306 // We ignored the RenderProcessGone call at the time, so we should send it
1307 // now to make sure the sad tab shows up, etc.
1308 DCHECK(!render_frame_host_->IsRenderFrameLive());
1309 DCHECK(!render_frame_host_->render_view_host()->IsRenderViewLive());
1310 delegate_->RenderProcessGoneFromRenderManager(
1311 render_frame_host_->render_view_host());
1314 // For top-level frames, also hide the old RenderViewHost's view.
1315 // TODO(creis): As long as show/hide are on RVH, we don't want to hide on
1316 // subframe navigations or we will interfere with the top-level frame.
1317 if (is_main_frame && old_render_frame_host->render_view_host()->GetView())
1318 old_render_frame_host->render_view_host()->GetView()->Hide();
1320 // Make sure the size is up to date. (Fix for bug 1079768.)
1321 delegate_->UpdateRenderViewSizeForRenderManager();
1323 if (will_focus_location_bar) {
1324 delegate_->SetFocusToLocationBar(false);
1325 } else if (focus_render_view &&
1326 render_frame_host_->render_view_host()->GetView()) {
1327 render_frame_host_->render_view_host()->GetView()->Focus();
1330 // Notify that we've swapped RenderFrameHosts. We do this before shutting down
1331 // the RFH so that we can clean up RendererResources related to the RFH first.
1332 delegate_->NotifySwappedFromRenderManager(
1333 old_render_frame_host.get(), render_frame_host_.get(), is_main_frame);
1335 // Swap out the old frame now that the new one is visible.
1336 // This will swap it out and then put it on the proxy list (if there are other
1337 // active views in its SiteInstance) or schedule it for deletion when the swap
1338 // out ack arrives (or immediately if the process isn't live).
1339 // In the --site-per-process case, old subframe RHFs are not kept alive inside
1341 SwapOutOldFrame(old_render_frame_host.Pass());
1343 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess) &&
1345 // If this is a subframe, it should have a CrossProcessFrameConnector
1346 // created already. Use it to link the new RFH's view to the proxy that
1347 // belongs to the parent frame's SiteInstance.
1348 // Note: We do this after swapping out the old RFH because that may create
1349 // the proxy we're looking for.
1350 RenderFrameProxyHost* proxy_to_parent = GetProxyToParent();
1351 if (proxy_to_parent) {
1352 proxy_to_parent->SetChildRWHView(
1353 render_frame_host_->render_view_host()->GetView());
1356 // Since the new RenderFrameHost is now committed, there must be no proxies
1357 // for its SiteInstance. Delete any existing ones.
1358 RenderFrameProxyHostMap::iterator iter =
1359 proxy_hosts_.find(render_frame_host_->GetSiteInstance()->GetId());
1360 if (iter != proxy_hosts_.end()) {
1361 delete iter->second;
1362 proxy_hosts_.erase(iter);
1366 // After all is done, there must never be a proxy in the list which has the
1367 // same SiteInstance as the current RenderFrameHost.
1368 CHECK(proxy_hosts_.find(render_frame_host_->GetSiteInstance()->GetId()) ==
1369 proxy_hosts_.end());
1372 void RenderFrameHostManager::ShutdownRenderFrameProxyHostsInSiteInstance(
1373 int32 site_instance_id) {
1374 // First remove any swapped out RFH for this SiteInstance from our own list.
1375 ClearProxiesInSiteInstance(site_instance_id, frame_tree_node_);
1377 // Use the safe RenderWidgetHost iterator for now to find all RenderViewHosts
1378 // in the SiteInstance, then tell their respective FrameTrees to remove all
1379 // RenderFrameProxyHosts corresponding to them.
1380 // TODO(creis): Replace this with a RenderFrameHostIterator that protects
1381 // against use-after-frees if a later element is deleted before getting to it.
1382 scoped_ptr<RenderWidgetHostIterator> widgets(
1383 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
1384 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
1385 if (!widget->IsRenderView())
1387 RenderViewHostImpl* rvh =
1388 static_cast<RenderViewHostImpl*>(RenderViewHost::From(widget));
1389 if (site_instance_id == rvh->GetSiteInstance()->GetId()) {
1390 // This deletes all RenderFrameHosts using the |rvh|, which then causes
1391 // |rvh| to Shutdown.
1392 FrameTree* tree = rvh->GetDelegate()->GetFrameTree();
1393 tree->ForEach(base::Bind(
1394 &RenderFrameHostManager::ClearProxiesInSiteInstance,
1400 RenderFrameHostImpl* RenderFrameHostManager::UpdateStateForNavigate(
1402 SiteInstance* instance,
1403 ui::PageTransition transition,
1405 bool is_view_source_mode,
1406 const GlobalRequestID& transferred_request_id,
1408 // If we are currently navigating cross-process, we want to get back to normal
1409 // and then navigate as usual.
1410 if (cross_navigation_pending_) {
1411 if (pending_render_frame_host_)
1413 cross_navigation_pending_ = false;
1416 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1417 scoped_refptr<SiteInstance> new_instance = GetSiteInstanceForNavigation(
1418 url, instance, transition, is_restore, is_view_source_mode);
1420 const NavigationEntry* current_entry =
1421 delegate_->GetLastCommittedNavigationEntryForRenderManager();
1423 if (new_instance.get() != current_instance) {
1424 TRACE_EVENT_INSTANT2(
1426 "RenderFrameHostManager::UpdateStateForNavigate:New SiteInstance",
1427 TRACE_EVENT_SCOPE_THREAD,
1428 "current_instance id", current_instance->GetId(),
1429 "new_instance id", new_instance->GetId());
1431 // New SiteInstance: create a pending RFH to navigate.
1432 DCHECK(!cross_navigation_pending_);
1434 // This will possibly create (set to NULL) a Web UI object for the pending
1435 // page. We'll use this later to give the page special access. This must
1436 // happen before the new renderer is created below so it will get bindings.
1437 // It must also happen after the above conditional call to CancelPending(),
1438 // otherwise CancelPending may clear the pending_web_ui_ and the page will
1439 // not have its bindings set appropriately.
1440 SetPendingWebUI(url, bindings);
1441 CreateRenderFrameHostForNewSiteInstance(
1442 current_instance, new_instance.get(), frame_tree_node_->IsMainFrame());
1443 if (!pending_render_frame_host_.get()) {
1447 // Check if our current RFH is live before we set up a transition.
1448 if (!render_frame_host_->IsRenderFrameLive()) {
1449 if (!cross_navigation_pending_) {
1450 // The current RFH is not live. There's no reason to sit around with a
1451 // sad tab or a newly created RFH while we wait for the pending RFH to
1452 // navigate. Just switch to the pending RFH now and go back to non
1453 // cross-navigating (Note that we don't care about on{before}unload
1454 // handlers if the current RFH isn't live.)
1456 return render_frame_host_.get();
1459 return render_frame_host_.get();
1462 // Otherwise, it's safe to treat this as a pending cross-site transition.
1464 // We now have a pending RFH.
1465 DCHECK(!cross_navigation_pending_);
1466 cross_navigation_pending_ = true;
1468 // PlzNavigate: There is no notion of transfer navigations, and the old
1469 // renderer before unload handler has already run at that point, so return
1471 if (CommandLine::ForCurrentProcess()->HasSwitch(
1472 switches::kEnableBrowserSideNavigation)) {
1473 return pending_render_frame_host_.get();
1476 // We need to wait until the beforeunload handler has run, unless we are
1477 // transferring an existing request (in which case it has already run).
1478 // Suspend the new render view (i.e., don't let it send the cross-site
1479 // Navigate message) until we hear back from the old renderer's
1480 // beforeunload handler. If the handler returns false, we'll have to
1481 // cancel the request.
1483 DCHECK(!pending_render_frame_host_->are_navigations_suspended());
1484 bool is_transfer = transferred_request_id != GlobalRequestID();
1486 // We don't need to stop the old renderer or run beforeunload/unload
1487 // handlers, because those have already been done.
1488 DCHECK(cross_site_transferring_request_->request_id() ==
1489 transferred_request_id);
1491 // Also make sure the old render view stops, in case a load is in
1492 // progress. (We don't want to do this for transfers, since it will
1493 // interrupt the transfer with an unexpected DidStopLoading.)
1494 render_frame_host_->Send(new FrameMsg_Stop(
1495 render_frame_host_->GetRoutingID()));
1496 pending_render_frame_host_->SetNavigationsSuspended(true,
1498 // Unless we are transferring an existing request, we should now tell the
1499 // old render view to run its beforeunload handler, since it doesn't
1500 // otherwise know that the cross-site request is happening. This will
1501 // trigger a call to OnBeforeUnloadACK with the reply.
1502 render_frame_host_->DispatchBeforeUnload(true);
1505 return pending_render_frame_host_.get();
1508 // Otherwise the same SiteInstance can be used. Navigate render_frame_host_.
1509 DCHECK(!cross_navigation_pending_);
1511 // It's possible to swap out the current RFH and then decide to navigate in it
1512 // anyway (e.g., a cross-process navigation that redirects back to the
1513 // original site). In that case, we have a proxy for the current RFH but
1514 // haven't deleted it yet. The new navigation will swap it back in, so we can
1515 // delete the proxy.
1516 DeleteRenderFrameProxyHost(new_instance.get());
1518 if (ShouldReuseWebUI(current_entry, url)) {
1519 pending_web_ui_.reset();
1520 pending_and_current_web_ui_ = web_ui_->AsWeakPtr();
1522 SetPendingWebUI(url, bindings);
1523 // Make sure the new RenderViewHost has the right bindings.
1524 if (pending_web_ui() &&
1525 !render_frame_host_->GetProcess()->IsIsolatedGuest()) {
1526 render_frame_host_->render_view_host()->AllowBindings(
1527 pending_web_ui()->GetBindings());
1531 if (pending_web_ui() && render_frame_host_->IsRenderFrameLive()) {
1532 pending_web_ui()->GetController()->RenderViewReused(
1533 render_frame_host_->render_view_host());
1536 // The renderer can exit view source mode when any error or cancellation
1537 // happen. We must overwrite to recover the mode.
1538 if (is_view_source_mode) {
1539 render_frame_host_->render_view_host()->Send(
1540 new ViewMsg_EnableViewSourceMode(
1541 render_frame_host_->render_view_host()->GetRoutingID()));
1544 return render_frame_host_.get();
1547 void RenderFrameHostManager::CancelPending() {
1548 TRACE_EVENT1("navigation", "RenderFrameHostManager::CancelPending",
1549 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
1550 scoped_ptr<RenderFrameHostImpl> pending_render_frame_host =
1551 pending_render_frame_host_.Pass();
1553 RenderViewDevToolsAgentHost::OnCancelPendingNavigation(
1554 pending_render_frame_host->render_view_host(),
1555 render_frame_host_->render_view_host());
1557 // We no longer need to prevent the process from exiting.
1558 pending_render_frame_host->GetProcess()->RemovePendingView();
1560 // If the SiteInstance for the pending RFH is being used by others, don't
1561 // delete the RFH, just swap it out and it can be reused at a later point.
1562 SiteInstanceImpl* site_instance =
1563 pending_render_frame_host->GetSiteInstance();
1564 if (site_instance->active_frame_count() > 1) {
1565 // Any currently suspended navigations are no longer needed.
1566 pending_render_frame_host->CancelSuspendedNavigations();
1568 RenderFrameProxyHost* proxy =
1569 new RenderFrameProxyHost(site_instance, frame_tree_node_);
1570 proxy_hosts_[site_instance->GetId()] = proxy;
1571 pending_render_frame_host->SwapOut(proxy);
1572 if (frame_tree_node_->IsMainFrame())
1573 proxy->TakeFrameHostOwnership(pending_render_frame_host.Pass());
1575 // We won't be coming back, so delete this one.
1576 pending_render_frame_host.reset();
1579 pending_web_ui_.reset();
1580 pending_and_current_web_ui_.reset();
1583 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::SetRenderFrameHost(
1584 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
1586 scoped_ptr<RenderFrameHostImpl> old_render_frame_host =
1587 render_frame_host_.Pass();
1588 render_frame_host_ = render_frame_host.Pass();
1590 if (frame_tree_node_->IsMainFrame()) {
1591 // Update the count of top-level frames using this SiteInstance. All
1592 // subframes are in the same BrowsingInstance as the main frame, so we only
1593 // count top-level ones. This makes the value easier for consumers to
1595 if (render_frame_host_) {
1596 render_frame_host_->GetSiteInstance()->
1597 IncrementRelatedActiveContentsCount();
1599 if (old_render_frame_host) {
1600 old_render_frame_host->GetSiteInstance()->
1601 DecrementRelatedActiveContentsCount();
1605 return old_render_frame_host.Pass();
1608 bool RenderFrameHostManager::IsRVHOnSwappedOutList(
1609 RenderViewHostImpl* rvh) const {
1610 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(
1611 rvh->GetSiteInstance());
1614 // If there is a proxy without RFH, it is for a subframe in the SiteInstance
1615 // of |rvh|. Subframes should be ignored in this case.
1616 if (!proxy->render_frame_host())
1618 return IsOnSwappedOutList(proxy->render_frame_host());
1621 bool RenderFrameHostManager::IsOnSwappedOutList(
1622 RenderFrameHostImpl* rfh) const {
1623 if (!rfh->GetSiteInstance())
1626 RenderFrameProxyHostMap::const_iterator iter = proxy_hosts_.find(
1627 rfh->GetSiteInstance()->GetId());
1628 if (iter == proxy_hosts_.end())
1631 return iter->second->render_frame_host() == rfh;
1634 RenderViewHostImpl* RenderFrameHostManager::GetSwappedOutRenderViewHost(
1635 SiteInstance* instance) const {
1636 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1638 return proxy->GetRenderViewHost();
1642 RenderFrameProxyHost* RenderFrameHostManager::GetRenderFrameProxyHost(
1643 SiteInstance* instance) const {
1644 RenderFrameProxyHostMap::const_iterator iter =
1645 proxy_hosts_.find(instance->GetId());
1646 if (iter != proxy_hosts_.end())
1647 return iter->second;
1652 void RenderFrameHostManager::DeleteRenderFrameProxyHost(
1653 SiteInstance* instance) {
1654 RenderFrameProxyHostMap::iterator iter = proxy_hosts_.find(instance->GetId());
1655 if (iter != proxy_hosts_.end()) {
1656 delete iter->second;
1657 proxy_hosts_.erase(iter);
1661 } // namespace content