Pass FrameTreeNode (not RenderFrameHost) to NavigateToEntry.
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_manager.cc
blob0cd3b53b3c42c4eed16da2eba5360ecbc65d8a34
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"
7 #include <utility>
9 #include "base/command_line.h"
10 #include "base/logging.h"
11 #include "base/stl_util.h"
12 #include "base/trace_event/trace_event.h"
13 #include "content/browser/child_process_security_policy_impl.h"
14 #include "content/browser/devtools/render_frame_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/navigation_request.h"
21 #include "content/browser/frame_host/navigator.h"
22 #include "content/browser/frame_host/render_frame_host_factory.h"
23 #include "content/browser/frame_host/render_frame_host_impl.h"
24 #include "content/browser/frame_host/render_frame_proxy_host.h"
25 #include "content/browser/renderer_host/render_process_host_impl.h"
26 #include "content/browser/renderer_host/render_view_host_factory.h"
27 #include "content/browser/renderer_host/render_view_host_impl.h"
28 #include "content/browser/site_instance_impl.h"
29 #include "content/browser/webui/web_ui_controller_factory_registry.h"
30 #include "content/browser/webui/web_ui_impl.h"
31 #include "content/common/frame_messages.h"
32 #include "content/common/view_messages.h"
33 #include "content/public/browser/content_browser_client.h"
34 #include "content/public/browser/notification_service.h"
35 #include "content/public/browser/notification_types.h"
36 #include "content/public/browser/render_widget_host_iterator.h"
37 #include "content/public/browser/render_widget_host_view.h"
38 #include "content/public/browser/user_metrics.h"
39 #include "content/public/browser/web_ui_controller.h"
40 #include "content/public/common/content_switches.h"
41 #include "content/public/common/referrer.h"
42 #include "content/public/common/url_constants.h"
44 namespace content {
46 // static
47 bool RenderFrameHostManager::ClearRFHsPendingShutdown(FrameTreeNode* node) {
48 node->render_manager()->pending_delete_hosts_.clear();
49 return true;
52 RenderFrameHostManager::RenderFrameHostManager(
53 FrameTreeNode* frame_tree_node,
54 RenderFrameHostDelegate* render_frame_delegate,
55 RenderViewHostDelegate* render_view_delegate,
56 RenderWidgetHostDelegate* render_widget_delegate,
57 Delegate* delegate)
58 : frame_tree_node_(frame_tree_node),
59 delegate_(delegate),
60 cross_navigation_pending_(false),
61 render_frame_delegate_(render_frame_delegate),
62 render_view_delegate_(render_view_delegate),
63 render_widget_delegate_(render_widget_delegate),
64 interstitial_page_(nullptr),
65 should_reuse_web_ui_(false),
66 weak_factory_(this) {
67 DCHECK(frame_tree_node_);
70 RenderFrameHostManager::~RenderFrameHostManager() {
71 if (pending_render_frame_host_)
72 UnsetPendingRenderFrameHost();
74 if (speculative_render_frame_host_)
75 UnsetSpeculativeRenderFrameHost();
77 if (render_frame_host_ &&
78 render_frame_host_->GetSiteInstance()->active_frame_count() <= 1U) {
79 ShutdownRenderFrameProxyHostsInSiteInstance(
80 render_frame_host_->GetSiteInstance()->GetId());
83 // Delete any RenderFrameProxyHosts and swapped out RenderFrameHosts.
84 // It is important to delete those prior to deleting the current
85 // RenderFrameHost, since the CrossProcessFrameConnector (owned by
86 // RenderFrameProxyHost) points to the RenderWidgetHostView associated with
87 // the current RenderFrameHost and uses it during its destructor.
88 STLDeleteValues(&proxy_hosts_);
90 // We should always have a current RenderFrameHost except in some tests.
91 SetRenderFrameHost(scoped_ptr<RenderFrameHostImpl>());
94 void RenderFrameHostManager::Init(BrowserContext* browser_context,
95 SiteInstance* site_instance,
96 int view_routing_id,
97 int frame_routing_id) {
98 // Create a RenderViewHost and RenderFrameHost, once we have an instance. It
99 // is important to immediately give this SiteInstance to a RenderViewHost so
100 // that the SiteInstance is ref counted.
101 if (!site_instance)
102 site_instance = SiteInstance::Create(browser_context);
104 int flags = delegate_->IsHidden() ? CREATE_RF_HIDDEN : 0;
105 SetRenderFrameHost(CreateRenderFrameHost(site_instance, view_routing_id,
106 frame_routing_id, flags));
108 // Keep track of renderer processes as they start to shut down or are
109 // crashed/killed.
110 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSED,
111 NotificationService::AllSources());
112 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSING,
113 NotificationService::AllSources());
116 RenderViewHostImpl* RenderFrameHostManager::current_host() const {
117 if (!render_frame_host_)
118 return NULL;
119 return render_frame_host_->render_view_host();
122 RenderViewHostImpl* RenderFrameHostManager::pending_render_view_host() const {
123 if (!pending_render_frame_host_)
124 return NULL;
125 return pending_render_frame_host_->render_view_host();
128 RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const {
129 if (interstitial_page_)
130 return interstitial_page_->GetView();
131 if (render_frame_host_)
132 return render_frame_host_->GetView();
133 return nullptr;
136 RenderFrameProxyHost* RenderFrameHostManager::GetProxyToParent() {
137 if (frame_tree_node_->IsMainFrame())
138 return NULL;
140 RenderFrameProxyHostMap::iterator iter =
141 proxy_hosts_.find(frame_tree_node_->parent()
142 ->render_manager()
143 ->current_frame_host()
144 ->GetSiteInstance()
145 ->GetId());
146 if (iter == proxy_hosts_.end())
147 return NULL;
149 return iter->second;
152 void RenderFrameHostManager::SetPendingWebUI(const GURL& url, int bindings) {
153 pending_web_ui_ = CreateWebUI(url, bindings);
154 pending_and_current_web_ui_.reset();
157 scoped_ptr<WebUIImpl> RenderFrameHostManager::CreateWebUI(const GURL& url,
158 int bindings) {
159 scoped_ptr<WebUIImpl> new_web_ui(delegate_->CreateWebUIForRenderManager(url));
161 // If we have assigned (zero or more) bindings to this NavigationEntry in the
162 // past, make sure we're not granting it different bindings than it had
163 // before. If so, note it and don't give it any bindings, to avoid a
164 // potential privilege escalation.
165 if (new_web_ui && bindings != NavigationEntryImpl::kInvalidBindings &&
166 new_web_ui->GetBindings() != bindings) {
167 RecordAction(base::UserMetricsAction("ProcessSwapBindingsMismatch_RVHM"));
168 return nullptr;
170 return new_web_ui.Pass();
173 RenderFrameHostImpl* RenderFrameHostManager::Navigate(
174 const NavigationEntryImpl& entry) {
175 TRACE_EVENT1("navigation", "RenderFrameHostManager:Navigate",
176 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
177 // Create a pending RenderFrameHost to use for the navigation.
178 RenderFrameHostImpl* dest_render_frame_host = UpdateStateForNavigate(
179 entry.GetURL(), entry.source_site_instance(), entry.site_instance(),
180 entry.GetTransitionType(),
181 entry.restore_type() != NavigationEntryImpl::RESTORE_NONE,
182 entry.IsViewSourceMode(), entry.transferred_global_request_id(),
183 entry.bindings());
184 if (!dest_render_frame_host)
185 return NULL; // We weren't able to create a pending render frame host.
187 // If the current render_frame_host_ isn't live, we should create it so
188 // that we don't show a sad tab while the dest_render_frame_host fetches
189 // its first page. (Bug 1145340)
190 if (dest_render_frame_host != render_frame_host_ &&
191 !render_frame_host_->IsRenderFrameLive()) {
192 // Note: we don't call InitRenderView here because we are navigating away
193 // soon anyway, and we don't have the NavigationEntry for this host.
194 delegate_->CreateRenderViewForRenderManager(
195 render_frame_host_->render_view_host(), MSG_ROUTING_NONE,
196 MSG_ROUTING_NONE, frame_tree_node_->IsMainFrame());
199 // If the renderer crashed, then try to create a new one to satisfy this
200 // navigation request.
201 if (!dest_render_frame_host->IsRenderFrameLive()) {
202 // Instruct the destination render frame host to set up a Mojo connection
203 // with the new render frame if necessary. Note that this call needs to
204 // occur before initializing the RenderView; the flow of creating the
205 // RenderView can cause browser-side code to execute that expects the this
206 // RFH's ServiceRegistry to be initialized (e.g., if the site is a WebUI
207 // site that is handled via Mojo, then Mojo WebUI code in //chrome will
208 // add a service to this RFH's ServiceRegistry).
209 dest_render_frame_host->SetUpMojoIfNeeded();
211 // Recreate the opener chain.
212 int opener_route_id = delegate_->CreateOpenerRenderViewsForRenderManager(
213 dest_render_frame_host->GetSiteInstance());
214 if (!InitRenderView(dest_render_frame_host->render_view_host(),
215 opener_route_id,
216 MSG_ROUTING_NONE,
217 frame_tree_node_->IsMainFrame()))
218 return NULL;
220 // Now that we've created a new renderer, be sure to hide it if it isn't
221 // our primary one. Otherwise, we might crash if we try to call Show()
222 // on it later.
223 if (dest_render_frame_host != render_frame_host_ &&
224 dest_render_frame_host->GetView()) {
225 dest_render_frame_host->GetView()->Hide();
226 } else {
227 // Notify here as we won't be calling CommitPending (which does the
228 // notify).
229 delegate_->NotifySwappedFromRenderManager(
230 NULL, render_frame_host_.get(), frame_tree_node_->IsMainFrame());
234 // If entry includes the request ID of a request that is being transferred,
235 // the destination render frame will take ownership, so release ownership of
236 // the request.
237 if (cross_site_transferring_request_.get() &&
238 cross_site_transferring_request_->request_id() ==
239 entry.transferred_global_request_id()) {
240 cross_site_transferring_request_->ReleaseRequest();
243 return dest_render_frame_host;
246 void RenderFrameHostManager::Stop() {
247 render_frame_host_->Stop();
249 // If we are cross-navigating, we should stop the pending renderers. This
250 // will lead to a DidFailProvisionalLoad, which will properly destroy them.
251 if (cross_navigation_pending_) {
252 pending_render_frame_host_->Send(new FrameMsg_Stop(
253 pending_render_frame_host_->GetRoutingID()));
257 void RenderFrameHostManager::SetIsLoading(bool is_loading) {
258 render_frame_host_->render_view_host()->SetIsLoading(is_loading);
259 if (pending_render_frame_host_)
260 pending_render_frame_host_->render_view_host()->SetIsLoading(is_loading);
263 bool RenderFrameHostManager::ShouldCloseTabOnUnresponsiveRenderer() {
264 // If we're waiting for a close ACK, then the tab should close whether there's
265 // a navigation in progress or not. Unfortunately, we also need to check for
266 // cases that we arrive here with no navigation in progress, since there are
267 // some tab closure paths that don't set is_waiting_for_close_ack to true.
268 // TODO(creis): Clean this up in http://crbug.com/418266.
269 if (!cross_navigation_pending_ ||
270 render_frame_host_->render_view_host()->is_waiting_for_close_ack())
271 return true;
273 // We should always have a pending RFH when there's a cross-process navigation
274 // in progress. Sanity check this for http://crbug.com/276333.
275 CHECK(pending_render_frame_host_);
277 // Unload handlers run in the background, so we should never get an
278 // unresponsiveness warning for them.
279 CHECK(!render_frame_host_->IsWaitingForUnloadACK());
281 // If the tab becomes unresponsive during beforeunload while doing a
282 // cross-site navigation, proceed with the navigation. (This assumes that
283 // the pending RenderFrameHost is still responsive.)
284 if (render_frame_host_->IsWaitingForBeforeUnloadACK()) {
285 // Haven't gotten around to starting the request, because we're still
286 // waiting for the beforeunload handler to finish. We'll pretend that it
287 // did finish, to let the navigation proceed. Note that there's a danger
288 // that the beforeunload handler will later finish and possibly return
289 // false (meaning the navigation should not proceed), but we'll ignore it
290 // in this case because it took too long.
291 if (pending_render_frame_host_->are_navigations_suspended()) {
292 pending_render_frame_host_->SetNavigationsSuspended(
293 false, base::TimeTicks::Now());
296 return false;
299 void RenderFrameHostManager::OnBeforeUnloadACK(
300 bool for_cross_site_transition,
301 bool proceed,
302 const base::TimeTicks& proceed_time) {
303 if (for_cross_site_transition) {
304 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
305 switches::kEnableBrowserSideNavigation));
306 // Ignore if we're not in a cross-site navigation.
307 if (!cross_navigation_pending_)
308 return;
310 if (proceed) {
311 // Ok to unload the current page, so proceed with the cross-site
312 // navigation. Note that if navigations are not currently suspended, it
313 // might be because the renderer was deemed unresponsive and this call was
314 // already made by ShouldCloseTabOnUnresponsiveRenderer. In that case, it
315 // is ok to do nothing here.
316 if (pending_render_frame_host_ &&
317 pending_render_frame_host_->are_navigations_suspended()) {
318 pending_render_frame_host_->SetNavigationsSuspended(false,
319 proceed_time);
321 } else {
322 // Current page says to cancel.
323 CancelPending();
324 cross_navigation_pending_ = false;
326 } else {
327 // Non-cross site transition means closing the entire tab.
328 bool proceed_to_fire_unload;
329 delegate_->BeforeUnloadFiredFromRenderManager(proceed, proceed_time,
330 &proceed_to_fire_unload);
332 if (proceed_to_fire_unload) {
333 // If we're about to close the tab and there's a pending RFH, cancel it.
334 // Otherwise, if the navigation in the pending RFH completes before the
335 // close in the current RFH, we'll lose the tab close.
336 if (pending_render_frame_host_) {
337 CancelPending();
338 cross_navigation_pending_ = false;
341 // This is not a cross-site navigation, the tab is being closed.
342 render_frame_host_->render_view_host()->ClosePage();
347 void RenderFrameHostManager::OnCrossSiteResponse(
348 RenderFrameHostImpl* pending_render_frame_host,
349 const GlobalRequestID& global_request_id,
350 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
351 const std::vector<GURL>& transfer_url_chain,
352 const Referrer& referrer,
353 ui::PageTransition page_transition,
354 bool should_replace_current_entry) {
355 // We should only get here for transfer navigations. Most cross-process
356 // navigations can just continue and wait to run the unload handler (by
357 // swapping out) when the new navigation commits.
358 CHECK(cross_site_transferring_request.get());
360 // A transfer should only have come from our pending or current RFH.
361 // TODO(creis): We need to handle the case that the pending RFH has changed
362 // in the mean time, while this was being posted from the IO thread. We
363 // should probably cancel the request in that case.
364 DCHECK(pending_render_frame_host == pending_render_frame_host_ ||
365 pending_render_frame_host == render_frame_host_);
367 // Store the transferring request so that we can release it if the transfer
368 // navigation matches.
369 cross_site_transferring_request_ = cross_site_transferring_request.Pass();
371 // Sanity check that the params are for the correct frame and process.
372 // These should match the RenderFrameHost that made the request.
373 // If it started as a cross-process navigation via OpenURL, this is the
374 // pending one. If it wasn't cross-process until the transfer, this is the
375 // current one.
376 int render_frame_id = pending_render_frame_host_ ?
377 pending_render_frame_host_->GetRoutingID() :
378 render_frame_host_->GetRoutingID();
379 DCHECK_EQ(render_frame_id, pending_render_frame_host->GetRoutingID());
380 int process_id = pending_render_frame_host_ ?
381 pending_render_frame_host_->GetProcess()->GetID() :
382 render_frame_host_->GetProcess()->GetID();
383 DCHECK_EQ(process_id, global_request_id.child_id);
385 // Treat the last URL in the chain as the destination and the remainder as
386 // the redirect chain.
387 CHECK(transfer_url_chain.size());
388 GURL transfer_url = transfer_url_chain.back();
389 std::vector<GURL> rest_of_chain = transfer_url_chain;
390 rest_of_chain.pop_back();
392 // We don't know whether the original request had |user_action| set to true.
393 // However, since we force the navigation to be in the current tab, it
394 // doesn't matter.
395 pending_render_frame_host->frame_tree_node()->navigator()->RequestTransferURL(
396 pending_render_frame_host, transfer_url, nullptr, rest_of_chain, referrer,
397 page_transition, CURRENT_TAB, global_request_id,
398 should_replace_current_entry, true);
400 // The transferring request was only needed during the RequestTransferURL
401 // call, so it is safe to clear at this point.
402 cross_site_transferring_request_.reset();
405 void RenderFrameHostManager::OnDeferredAfterResponseStarted(
406 const GlobalRequestID& global_request_id,
407 RenderFrameHostImpl* pending_render_frame_host) {
408 DCHECK(!response_started_id_.get());
410 response_started_id_.reset(new GlobalRequestID(global_request_id));
413 void RenderFrameHostManager::ResumeResponseDeferredAtStart() {
414 DCHECK(response_started_id_.get());
416 RenderProcessHostImpl* process =
417 static_cast<RenderProcessHostImpl*>(render_frame_host_->GetProcess());
418 process->ResumeResponseDeferredAtStart(*response_started_id_);
420 render_frame_host_->ClearPendingTransitionRequestData();
422 response_started_id_.reset();
425 void RenderFrameHostManager::ClearNavigationTransitionData() {
426 render_frame_host_->ClearPendingTransitionRequestData();
429 void RenderFrameHostManager::DidNavigateFrame(
430 RenderFrameHostImpl* render_frame_host,
431 bool was_caused_by_user_gesture) {
432 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
433 switches::kEnableBrowserSideNavigation)) {
434 if (render_frame_host == speculative_render_frame_host_.get()) {
435 CommitPending();
436 } else if (render_frame_host == render_frame_host_.get()) {
437 // TODO(carlosk): this code doesn't properly handle in-page navigation or
438 // interwoven navigation requests.
439 DCHECK(!speculative_render_frame_host_);
440 } else {
441 // No one else should be sending us a DidNavigate in this state.
442 DCHECK(false);
444 DCHECK(!speculative_render_frame_host_);
445 return;
448 if (!cross_navigation_pending_) {
449 DCHECK(!pending_render_frame_host_);
451 // We should only hear this from our current renderer.
452 DCHECK_EQ(render_frame_host_, render_frame_host);
454 // Even when there is no pending RVH, there may be a pending Web UI.
455 if (pending_web_ui())
456 CommitPending();
457 return;
460 if (render_frame_host == pending_render_frame_host_) {
461 // The pending cross-site navigation completed, so show the renderer.
462 CommitPending();
463 } else if (render_frame_host == render_frame_host_) {
464 if (was_caused_by_user_gesture) {
465 // A navigation in the original page has taken place. Cancel the pending
466 // one. Only do it for user gesture originated navigations to prevent
467 // page doing any shenanigans to prevent user from navigating.
468 // See https://code.google.com/p/chromium/issues/detail?id=75195
469 CancelPending();
470 cross_navigation_pending_ = false;
472 } else {
473 // No one else should be sending us DidNavigate in this state.
474 DCHECK(false);
478 void RenderFrameHostManager::DidDisownOpener(
479 RenderFrameHost* render_frame_host) {
480 // Notify all RenderFrameHosts but the one that notified us. This is necessary
481 // in case a process swap has occurred while the message was in flight.
482 for (RenderFrameProxyHostMap::iterator iter = proxy_hosts_.begin();
483 iter != proxy_hosts_.end();
484 ++iter) {
485 DCHECK_NE(iter->second->GetSiteInstance(),
486 current_frame_host()->GetSiteInstance());
487 iter->second->DisownOpener();
490 if (render_frame_host_.get() != render_frame_host)
491 render_frame_host_->DisownOpener();
493 if (pending_render_frame_host_ &&
494 pending_render_frame_host_.get() != render_frame_host) {
495 pending_render_frame_host_->DisownOpener();
499 void RenderFrameHostManager::RendererProcessClosing(
500 RenderProcessHost* render_process_host) {
501 // Remove any swapped out RVHs from this process, so that we don't try to
502 // swap them back in while the process is exiting. Start by finding them,
503 // since there could be more than one.
504 std::list<int> ids_to_remove;
505 // Do not remove proxies in the dead process that still have active frame
506 // count though, we just reset them to be uninitialized.
507 std::list<int> ids_to_keep;
508 for (RenderFrameProxyHostMap::iterator iter = proxy_hosts_.begin();
509 iter != proxy_hosts_.end();
510 ++iter) {
511 RenderFrameProxyHost* proxy = iter->second;
512 if (proxy->GetProcess() != render_process_host)
513 continue;
515 if (static_cast<SiteInstanceImpl*>(proxy->GetSiteInstance())
516 ->active_frame_count() >= 1U) {
517 ids_to_keep.push_back(iter->first);
518 } else {
519 ids_to_remove.push_back(iter->first);
523 // Now delete them.
524 while (!ids_to_remove.empty()) {
525 delete proxy_hosts_[ids_to_remove.back()];
526 proxy_hosts_.erase(ids_to_remove.back());
527 ids_to_remove.pop_back();
530 while (!ids_to_keep.empty()) {
531 frame_tree_node_->frame_tree()->ForEach(
532 base::Bind(
533 &RenderFrameHostManager::ResetProxiesInSiteInstance,
534 ids_to_keep.back()));
535 ids_to_keep.pop_back();
539 void RenderFrameHostManager::SwapOutOldFrame(
540 scoped_ptr<RenderFrameHostImpl> old_render_frame_host) {
541 TRACE_EVENT1("navigation", "RenderFrameHostManager::SwapOutOldFrame",
542 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
544 // Tell the renderer to suppress any further modal dialogs so that we can swap
545 // it out. This must be done before canceling any current dialog, in case
546 // there is a loop creating additional dialogs.
547 // TODO(creis): Handle modal dialogs in subframe processes.
548 old_render_frame_host->render_view_host()->SuppressDialogsUntilSwapOut();
550 // Now close any modal dialogs that would prevent us from swapping out. This
551 // must be done separately from SwapOut, so that the PageGroupLoadDeferrer is
552 // no longer on the stack when we send the SwapOut message.
553 delegate_->CancelModalDialogsForRenderManager();
555 // If the old RFH is not live, just return as there is no further work to do.
556 // It will be deleted and there will be no proxy created.
557 int32 old_site_instance_id =
558 old_render_frame_host->GetSiteInstance()->GetId();
559 if (!old_render_frame_host->IsRenderFrameLive()) {
560 ShutdownRenderFrameProxyHostsInSiteInstance(old_site_instance_id);
561 return;
564 // If there are no active frames besides this one, we can delete the old
565 // RenderFrameHost once it runs its unload handler, without replacing it with
566 // a proxy.
567 size_t active_frame_count =
568 old_render_frame_host->GetSiteInstance()->active_frame_count();
569 if (active_frame_count <= 1) {
570 // Tell the old RenderFrameHost to swap out, with no proxy to replace it.
571 old_render_frame_host->SwapOut(NULL, true);
572 MoveToPendingDeleteHosts(old_render_frame_host.Pass());
574 // Also clear out any proxies from this SiteInstance, in case this was the
575 // last one keeping other proxies alive.
576 ShutdownRenderFrameProxyHostsInSiteInstance(old_site_instance_id);
578 return;
581 // Otherwise there are active views and we need a proxy for the old RFH.
582 // (There should not be one yet.)
583 CHECK(!GetRenderFrameProxyHost(old_render_frame_host->GetSiteInstance()));
584 RenderFrameProxyHost* proxy = new RenderFrameProxyHost(
585 old_render_frame_host->GetSiteInstance(), frame_tree_node_);
586 CHECK(proxy_hosts_.insert(std::make_pair(old_site_instance_id, proxy)).second)
587 << "Inserting a duplicate item.";
589 // Tell the old RenderFrameHost to swap out and be replaced by the proxy.
590 old_render_frame_host->SwapOut(proxy, true);
592 // SwapOut creates a RenderFrameProxy, so set the proxy to be initialized.
593 proxy->set_render_frame_proxy_created(true);
595 bool is_main_frame = frame_tree_node_->IsMainFrame();
596 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
597 switches::kSitePerProcess) &&
598 !is_main_frame) {
599 // In --site-per-process, subframes delete their RFH rather than storing it
600 // in the proxy. Schedule it for deletion once the SwapOutACK comes in.
601 // TODO(creis): This will be the default when we remove swappedout://.
602 MoveToPendingDeleteHosts(old_render_frame_host.Pass());
603 } else {
604 // We shouldn't get here for subframes, since we only swap subframes when
605 // --site-per-process is used.
606 DCHECK(is_main_frame);
608 // The old RenderFrameHost will stay alive inside the proxy so that existing
609 // JavaScript window references to it stay valid.
610 proxy->TakeFrameHostOwnership(old_render_frame_host.Pass());
614 void RenderFrameHostManager::DiscardUnusedFrame(
615 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
616 // TODO(carlosk): this code is very similar to what can be found in
617 // SwapOutOldFrame and we should see that these are unified at some point.
619 // If the SiteInstance for the pending RFH is being used by others don't
620 // delete the RFH. Just swap it out and it can be reused at a later point.
621 SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance();
622 if (site_instance->HasSite() && site_instance->active_frame_count() > 1) {
623 // Any currently suspended navigations are no longer needed.
624 render_frame_host->CancelSuspendedNavigations();
626 RenderFrameProxyHost* proxy =
627 new RenderFrameProxyHost(site_instance, frame_tree_node_);
628 proxy_hosts_[site_instance->GetId()] = proxy;
630 // Check if the RenderFrameHost is already swapped out, to avoid swapping it
631 // out again.
632 if (!render_frame_host->is_swapped_out())
633 render_frame_host->SwapOut(proxy, false);
635 if (frame_tree_node_->IsMainFrame())
636 proxy->TakeFrameHostOwnership(render_frame_host.Pass());
637 } else {
638 // We won't be coming back, so delete this one.
639 render_frame_host.reset();
643 void RenderFrameHostManager::MoveToPendingDeleteHosts(
644 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
645 // |render_frame_host| will be deleted when its SwapOut ACK is received, or
646 // when the timer times out, or when the RFHM itself is deleted (whichever
647 // comes first).
648 pending_delete_hosts_.push_back(
649 linked_ptr<RenderFrameHostImpl>(render_frame_host.release()));
652 bool RenderFrameHostManager::IsPendingDeletion(
653 RenderFrameHostImpl* render_frame_host) {
654 for (const auto& rfh : pending_delete_hosts_) {
655 if (rfh == render_frame_host)
656 return true;
658 return false;
661 bool RenderFrameHostManager::DeleteFromPendingList(
662 RenderFrameHostImpl* render_frame_host) {
663 for (RFHPendingDeleteList::iterator iter = pending_delete_hosts_.begin();
664 iter != pending_delete_hosts_.end();
665 iter++) {
666 if (*iter == render_frame_host) {
667 pending_delete_hosts_.erase(iter);
668 return true;
671 return false;
674 void RenderFrameHostManager::ResetProxyHosts() {
675 STLDeleteValues(&proxy_hosts_);
678 // PlzNavigate
679 void RenderFrameHostManager::BeginNavigation(const NavigationRequest& request) {
680 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
681 switches::kEnableBrowserSideNavigation));
682 // Clean up any state in case there's an ongoing navigation.
683 // TODO(carlosk): remove this cleanup here once we properly cancel ongoing
684 // navigations.
685 CleanUpNavigation();
687 RenderFrameHostImpl* dest_rfh = GetFrameHostForNavigation(request);
688 DCHECK(dest_rfh);
691 // PlzNavigate
692 RenderFrameHostImpl* RenderFrameHostManager::GetFrameHostForNavigation(
693 const NavigationRequest& request) {
694 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
695 switches::kEnableBrowserSideNavigation));
697 SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance();
699 scoped_refptr<SiteInstance> dest_site_instance = GetSiteInstanceForNavigation(
700 request.common_params().url, request.source_site_instance(),
701 request.dest_site_instance(), request.common_params().transition,
702 request.restore_type() != NavigationEntryImpl::RESTORE_NONE,
703 request.is_view_source());
704 // The appropriate RenderFrameHost to commit the navigation.
705 RenderFrameHostImpl* navigation_rfh = nullptr;
707 // TODO(carlosk): do not swap processes for renderer initiated navigations
708 // (see crbug.com/440266).
709 if (current_site_instance == dest_site_instance.get() ||
710 (!frame_tree_node_->IsMainFrame() &&
711 !base::CommandLine::ForCurrentProcess()->HasSwitch(
712 switches::kSitePerProcess))) {
713 // Reuse the current RFH if its SiteInstance matches the the navigation's
714 // or if this is a subframe navigation. We only swap RFHs for subframes when
715 // --site-per-process is enabled.
716 CleanUpNavigation();
717 navigation_rfh = render_frame_host_.get();
719 // As SiteInstances are the same, check if the WebUI should be reused.
720 const NavigationEntry* current_navigation_entry =
721 delegate_->GetLastCommittedNavigationEntryForRenderManager();
722 bool should_reuse_web_ui_ = ShouldReuseWebUI(current_navigation_entry,
723 request.common_params().url);
724 if (!should_reuse_web_ui_) {
725 speculative_web_ui_ = CreateWebUI(request.common_params().url,
726 request.bindings());
727 // Make sure the current RenderViewHost has the right bindings.
728 if (speculative_web_ui() &&
729 !render_frame_host_->GetProcess()->IsIsolatedGuest()) {
730 render_frame_host_->render_view_host()->AllowBindings(
731 speculative_web_ui()->GetBindings());
734 } else {
735 // If the SiteInstance for the final URL doesn't match the one from the
736 // speculatively created RenderFrameHost, create a new RenderFrameHost using
737 // this new SiteInstance.
738 if (!speculative_render_frame_host_ ||
739 speculative_render_frame_host_->GetSiteInstance() !=
740 dest_site_instance.get()) {
741 CleanUpNavigation();
742 bool success = CreateSpeculativeRenderFrameHost(
743 request.common_params().url, current_site_instance,
744 dest_site_instance.get(), request.bindings());
745 DCHECK(success);
747 DCHECK(speculative_render_frame_host_);
748 navigation_rfh = speculative_render_frame_host_.get();
750 // Check if our current RFH is live.
751 if (!render_frame_host_->IsRenderFrameLive()) {
752 // The current RFH is not live. There's no reason to sit around with a
753 // sad tab or a newly created RFH while we wait for the navigation to
754 // complete. Just switch to the speculative RFH now and go back to non
755 // cross-navigating (Note that we don't care about on{before}unload
756 // handlers if the current RFH isn't live.)
757 CommitPending();
760 DCHECK(navigation_rfh &&
761 (navigation_rfh == render_frame_host_.get() ||
762 navigation_rfh == speculative_render_frame_host_.get()));
764 // If the RenderFrame that needs to navigate is not live (its process was just
765 // created or has crashed), initialize it.
766 if (!navigation_rfh->IsRenderFrameLive()) {
767 // Recreate the opener chain.
768 int opener_route_id = delegate_->CreateOpenerRenderViewsForRenderManager(
769 navigation_rfh->GetSiteInstance());
770 if (!InitRenderView(navigation_rfh->render_view_host(), opener_route_id,
771 MSG_ROUTING_NONE, frame_tree_node_->IsMainFrame())) {
772 return nullptr;
776 cross_navigation_pending_ = navigation_rfh != render_frame_host_.get();
777 return navigation_rfh;
780 // PlzNavigate
781 void RenderFrameHostManager::CleanUpNavigation() {
782 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
783 switches::kEnableBrowserSideNavigation));
784 speculative_web_ui_.reset();
785 should_reuse_web_ui_ = false;
786 if (speculative_render_frame_host_)
787 DiscardUnusedFrame(UnsetSpeculativeRenderFrameHost());
790 // PlzNavigate
791 scoped_ptr<RenderFrameHostImpl>
792 RenderFrameHostManager::UnsetSpeculativeRenderFrameHost() {
793 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
794 switches::kEnableBrowserSideNavigation));
795 speculative_render_frame_host_->GetProcess()->RemovePendingView();
796 return speculative_render_frame_host_.Pass();
799 void RenderFrameHostManager::OnDidStartLoading() {
800 for (const auto& pair : proxy_hosts_) {
801 pair.second->Send(
802 new FrameMsg_DidStartLoading(pair.second->GetRoutingID()));
806 void RenderFrameHostManager::OnDidStopLoading() {
807 for (const auto& pair : proxy_hosts_) {
808 pair.second->Send(new FrameMsg_DidStopLoading(pair.second->GetRoutingID()));
812 void RenderFrameHostManager::Observe(
813 int type,
814 const NotificationSource& source,
815 const NotificationDetails& details) {
816 switch (type) {
817 case NOTIFICATION_RENDERER_PROCESS_CLOSED:
818 case NOTIFICATION_RENDERER_PROCESS_CLOSING:
819 RendererProcessClosing(
820 Source<RenderProcessHost>(source).ptr());
821 break;
823 default:
824 NOTREACHED();
828 // static
829 bool RenderFrameHostManager::ClearProxiesInSiteInstance(
830 int32 site_instance_id,
831 FrameTreeNode* node) {
832 RenderFrameProxyHostMap::iterator iter =
833 node->render_manager()->proxy_hosts_.find(site_instance_id);
834 if (iter != node->render_manager()->proxy_hosts_.end()) {
835 RenderFrameProxyHost* proxy = iter->second;
836 // Delete the proxy. If it is for a main frame (and thus the RFH is stored
837 // in the proxy) and it was still pending swap out, move the RFH to the
838 // pending deletion list first.
839 if (node->IsMainFrame() &&
840 proxy->render_frame_host()->rfh_state() ==
841 RenderFrameHostImpl::STATE_PENDING_SWAP_OUT) {
842 scoped_ptr<RenderFrameHostImpl> swapped_out_rfh =
843 proxy->PassFrameHostOwnership();
844 node->render_manager()->MoveToPendingDeleteHosts(swapped_out_rfh.Pass());
846 delete proxy;
847 node->render_manager()->proxy_hosts_.erase(site_instance_id);
850 return true;
853 // static.
854 bool RenderFrameHostManager::ResetProxiesInSiteInstance(int32 site_instance_id,
855 FrameTreeNode* node) {
856 RenderFrameProxyHostMap::iterator iter =
857 node->render_manager()->proxy_hosts_.find(site_instance_id);
858 if (iter != node->render_manager()->proxy_hosts_.end())
859 iter->second->set_render_frame_proxy_created(false);
861 return true;
864 bool RenderFrameHostManager::ShouldTransitionCrossSite() {
865 // True for --site-per-process, which overrides both kSingleProcess and
866 // kProcessPerTab.
867 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
868 switches::kSitePerProcess))
869 return true;
871 // False in the single-process mode, as it makes RVHs to accumulate
872 // in swapped_out_hosts_.
873 // True if we are using process-per-site-instance (default) or
874 // process-per-site (kProcessPerSite).
875 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
876 switches::kSingleProcess) &&
877 !base::CommandLine::ForCurrentProcess()->HasSwitch(
878 switches::kProcessPerTab);
881 bool RenderFrameHostManager::ShouldSwapBrowsingInstancesForNavigation(
882 const GURL& current_effective_url,
883 bool current_is_view_source_mode,
884 SiteInstance* new_site_instance,
885 const GURL& new_effective_url,
886 bool new_is_view_source_mode) const {
887 // If new_entry already has a SiteInstance, assume it is correct. We only
888 // need to force a swap if it is in a different BrowsingInstance.
889 if (new_site_instance) {
890 return !new_site_instance->IsRelatedSiteInstance(
891 render_frame_host_->GetSiteInstance());
894 // Check for reasons to swap processes even if we are in a process model that
895 // doesn't usually swap (e.g., process-per-tab). Any time we return true,
896 // the new_entry will be rendered in a new SiteInstance AND BrowsingInstance.
897 BrowserContext* browser_context =
898 delegate_->GetControllerForRenderManager().GetBrowserContext();
900 // Don't force a new BrowsingInstance for debug URLs that are handled in the
901 // renderer process, like javascript: or chrome://crash.
902 if (IsRendererDebugURL(new_effective_url))
903 return false;
905 // For security, we should transition between processes when one is a Web UI
906 // page and one isn't.
907 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
908 render_frame_host_->GetProcess()->GetID()) ||
909 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
910 browser_context, current_effective_url)) {
911 // If so, force a swap if destination is not an acceptable URL for Web UI.
912 // Here, data URLs are never allowed.
913 if (!WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
914 browser_context, new_effective_url)) {
915 return true;
917 } else {
918 // Force a swap if it's a Web UI URL.
919 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
920 browser_context, new_effective_url)) {
921 return true;
925 // Check with the content client as well. Important to pass
926 // current_effective_url here, which uses the SiteInstance's site if there is
927 // no current_entry.
928 if (GetContentClient()->browser()->ShouldSwapBrowsingInstancesForNavigation(
929 render_frame_host_->GetSiteInstance(),
930 current_effective_url, new_effective_url)) {
931 return true;
934 // We can't switch a RenderView between view source and non-view source mode
935 // without screwing up the session history sometimes (when navigating between
936 // "view-source:http://foo.com/" and "http://foo.com/", Blink doesn't treat
937 // it as a new navigation). So require a BrowsingInstance switch.
938 if (current_is_view_source_mode != new_is_view_source_mode)
939 return true;
941 return false;
944 bool RenderFrameHostManager::ShouldReuseWebUI(
945 const NavigationEntry* current_entry,
946 const GURL& new_url) const {
947 NavigationControllerImpl& controller =
948 delegate_->GetControllerForRenderManager();
949 return current_entry && web_ui_.get() &&
950 (WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
951 controller.GetBrowserContext(), current_entry->GetURL()) ==
952 WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
953 controller.GetBrowserContext(), new_url));
956 SiteInstance* RenderFrameHostManager::GetSiteInstanceForNavigation(
957 const GURL& dest_url,
958 SiteInstance* source_instance,
959 SiteInstance* dest_instance,
960 ui::PageTransition transition,
961 bool dest_is_restore,
962 bool dest_is_view_source_mode) {
963 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
964 SiteInstance* new_instance = current_instance;
966 // We do not currently swap processes for navigations in webview tag guests.
967 if (current_instance->GetSiteURL().SchemeIs(kGuestScheme))
968 return current_instance;
970 // Determine if we need a new BrowsingInstance for this entry. If true, this
971 // implies that it will get a new SiteInstance (and likely process), and that
972 // other tabs in the current BrowsingInstance will be unable to script it.
973 // This is used for cases that require a process swap even in the
974 // process-per-tab model, such as WebUI pages.
975 // TODO(clamy): Remove the dependency on the current entry.
976 const NavigationEntry* current_entry =
977 delegate_->GetLastCommittedNavigationEntryForRenderManager();
978 BrowserContext* browser_context =
979 delegate_->GetControllerForRenderManager().GetBrowserContext();
980 const GURL& current_effective_url = current_entry ?
981 SiteInstanceImpl::GetEffectiveURL(browser_context,
982 current_entry->GetURL()) :
983 render_frame_host_->GetSiteInstance()->GetSiteURL();
984 bool current_is_view_source_mode = current_entry ?
985 current_entry->IsViewSourceMode() : dest_is_view_source_mode;
986 bool force_swap = ShouldSwapBrowsingInstancesForNavigation(
987 current_effective_url,
988 current_is_view_source_mode,
989 dest_instance,
990 SiteInstanceImpl::GetEffectiveURL(browser_context, dest_url),
991 dest_is_view_source_mode);
992 if (ShouldTransitionCrossSite() || force_swap) {
993 new_instance = GetSiteInstanceForURL(
994 dest_url, source_instance, current_instance, dest_instance,
995 transition, dest_is_restore, dest_is_view_source_mode, force_swap);
998 // If force_swap is true, we must use a different SiteInstance. If we didn't,
999 // we would have two RenderFrameHosts in the same SiteInstance and the same
1000 // frame, resulting in page_id conflicts for their NavigationEntries.
1001 if (force_swap)
1002 CHECK_NE(new_instance, current_instance);
1003 return new_instance;
1006 SiteInstance* RenderFrameHostManager::GetSiteInstanceForURL(
1007 const GURL& dest_url,
1008 SiteInstance* source_instance,
1009 SiteInstance* current_instance,
1010 SiteInstance* dest_instance,
1011 ui::PageTransition transition,
1012 bool dest_is_restore,
1013 bool dest_is_view_source_mode,
1014 bool force_browsing_instance_swap) {
1015 NavigationControllerImpl& controller =
1016 delegate_->GetControllerForRenderManager();
1017 BrowserContext* browser_context = controller.GetBrowserContext();
1019 // If the entry has an instance already we should use it.
1020 if (dest_instance) {
1021 // If we are forcing a swap, this should be in a different BrowsingInstance.
1022 if (force_browsing_instance_swap) {
1023 CHECK(!dest_instance->IsRelatedSiteInstance(
1024 render_frame_host_->GetSiteInstance()));
1026 return dest_instance;
1029 // If a swap is required, we need to force the SiteInstance AND
1030 // BrowsingInstance to be different ones, using CreateForURL.
1031 if (force_browsing_instance_swap)
1032 return SiteInstance::CreateForURL(browser_context, dest_url);
1034 // (UGLY) HEURISTIC, process-per-site only:
1036 // If this navigation is generated, then it probably corresponds to a search
1037 // query. Given that search results typically lead to users navigating to
1038 // other sites, we don't really want to use the search engine hostname to
1039 // determine the site instance for this navigation.
1041 // NOTE: This can be removed once we have a way to transition between
1042 // RenderViews in response to a link click.
1044 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1045 switches::kProcessPerSite) &&
1046 ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_GENERATED)) {
1047 return current_instance;
1050 SiteInstanceImpl* current_site_instance =
1051 static_cast<SiteInstanceImpl*>(current_instance);
1053 // If we haven't used our SiteInstance (and thus RVH) yet, then we can use it
1054 // for this entry. We won't commit the SiteInstance to this site until the
1055 // navigation commits (in DidNavigate), unless the navigation entry was
1056 // restored or it's a Web UI as described below.
1057 if (!current_site_instance->HasSite()) {
1058 // If we've already created a SiteInstance for our destination, we don't
1059 // want to use this unused SiteInstance; use the existing one. (We don't
1060 // do this check if the current_instance has a site, because for now, we
1061 // want to compare against the current URL and not the SiteInstance's site.
1062 // In this case, there is no current URL, so comparing against the site is
1063 // ok. See additional comments below.)
1065 // Also, if the URL should use process-per-site mode and there is an
1066 // existing process for the site, we should use it. We can call
1067 // GetRelatedSiteInstance() for this, which will eagerly set the site and
1068 // thus use the correct process.
1069 bool use_process_per_site =
1070 RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) &&
1071 RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url);
1072 if (current_site_instance->HasRelatedSiteInstance(dest_url) ||
1073 use_process_per_site) {
1074 return current_site_instance->GetRelatedSiteInstance(dest_url);
1077 // For extensions, Web UI URLs (such as the new tab page), and apps we do
1078 // not want to use the current_instance if it has no site, since it will
1079 // have a RenderProcessHost of PRIV_NORMAL. Create a new SiteInstance for
1080 // this URL instead (with the correct process type).
1081 if (current_site_instance->HasWrongProcessForURL(dest_url))
1082 return current_site_instance->GetRelatedSiteInstance(dest_url);
1084 // View-source URLs must use a new SiteInstance and BrowsingInstance.
1085 // TODO(nasko): This is the same condition as later in the function. This
1086 // should be taken into account when refactoring this method as part of
1087 // http://crbug.com/123007.
1088 if (dest_is_view_source_mode)
1089 return SiteInstance::CreateForURL(browser_context, dest_url);
1091 // If we are navigating from a blank SiteInstance to a WebUI, make sure we
1092 // create a new SiteInstance.
1093 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1094 browser_context, dest_url)) {
1095 return SiteInstance::CreateForURL(browser_context, dest_url);
1098 // Normally the "site" on the SiteInstance is set lazily when the load
1099 // actually commits. This is to support better process sharing in case
1100 // the site redirects to some other site: we want to use the destination
1101 // site in the site instance.
1103 // In the case of session restore, as it loads all the pages immediately
1104 // we need to set the site first, otherwise after a restore none of the
1105 // pages would share renderers in process-per-site.
1107 // The embedder can request some urls never to be assigned to SiteInstance
1108 // through the ShouldAssignSiteForURL() content client method, so that
1109 // renderers created for particular chrome urls (e.g. the chrome-native://
1110 // scheme) can be reused for subsequent navigations in the same WebContents.
1111 // See http://crbug.com/386542.
1112 if (dest_is_restore &&
1113 GetContentClient()->browser()->ShouldAssignSiteForURL(dest_url)) {
1114 current_site_instance->SetSite(dest_url);
1117 return current_site_instance;
1120 // Otherwise, only create a new SiteInstance for a cross-site navigation.
1122 // TODO(creis): Once we intercept links and script-based navigations, we
1123 // will be able to enforce that all entries in a SiteInstance actually have
1124 // the same site, and it will be safe to compare the URL against the
1125 // SiteInstance's site, as follows:
1126 // const GURL& current_url = current_instance->site();
1127 // For now, though, we're in a hybrid model where you only switch
1128 // SiteInstances if you type in a cross-site URL. This means we have to
1129 // compare the entry's URL to the last committed entry's URL.
1130 NavigationEntry* current_entry = controller.GetLastCommittedEntry();
1131 if (interstitial_page_) {
1132 // The interstitial is currently the last committed entry, but we want to
1133 // compare against the last non-interstitial entry.
1134 current_entry = controller.GetEntryAtOffset(-1);
1137 // View-source URLs must use a new SiteInstance and BrowsingInstance.
1138 // We don't need a swap when going from view-source to a debug URL like
1139 // chrome://crash, however.
1140 // TODO(creis): Refactor this method so this duplicated code isn't needed.
1141 // See http://crbug.com/123007.
1142 if (current_entry &&
1143 current_entry->IsViewSourceMode() != dest_is_view_source_mode &&
1144 !IsRendererDebugURL(dest_url)) {
1145 return SiteInstance::CreateForURL(browser_context, dest_url);
1148 // Use the source SiteInstance in case of data URLs or about:blank pages,
1149 // because the content is then controlled and/or scriptable by the source
1150 // SiteInstance.
1151 GURL about_blank(url::kAboutBlankURL);
1152 if (source_instance &&
1153 (dest_url == about_blank || dest_url.scheme() == url::kDataScheme))
1154 return source_instance;
1156 // Use the current SiteInstance for same site navigations, as long as the
1157 // process type is correct. (The URL may have been installed as an app since
1158 // the last time we visited it.)
1159 const GURL& current_url =
1160 GetCurrentURLForSiteInstance(current_instance, current_entry);
1161 if (SiteInstance::IsSameWebSite(browser_context, current_url, dest_url) &&
1162 !current_site_instance->HasWrongProcessForURL(dest_url)) {
1163 return current_instance;
1166 // Start the new renderer in a new SiteInstance, but in the current
1167 // BrowsingInstance. It is important to immediately give this new
1168 // SiteInstance to a RenderViewHost (if it is different than our current
1169 // SiteInstance), so that it is ref counted. This will happen in
1170 // CreateRenderView.
1171 return current_instance->GetRelatedSiteInstance(dest_url);
1174 const GURL& RenderFrameHostManager::GetCurrentURLForSiteInstance(
1175 SiteInstance* current_instance, NavigationEntry* current_entry) {
1176 // If this is a subframe that is potentially out of process from its parent,
1177 // don't consider using current_entry's url for SiteInstance selection, since
1178 // current_entry's url is for the main frame and may be in a different site
1179 // than this frame.
1180 // TODO(creis): Remove this when we can check the FrameNavigationEntry's url.
1181 // See http://crbug.com/369654
1182 if (!frame_tree_node_->IsMainFrame() &&
1183 base::CommandLine::ForCurrentProcess()->HasSwitch(
1184 switches::kSitePerProcess))
1185 return frame_tree_node_->current_url();
1187 // If there is no last non-interstitial entry (and current_instance already
1188 // has a site), then we must have been opened from another tab. We want
1189 // to compare against the URL of the page that opened us, but we can't
1190 // get to it directly. The best we can do is check against the site of
1191 // the SiteInstance. This will be correct when we intercept links and
1192 // script-based navigations, but for now, it could place some pages in a
1193 // new process unnecessarily. We should only hit this case if a page tries
1194 // to open a new tab to an interstitial-inducing URL, and then navigates
1195 // the page to a different same-site URL. (This seems very unlikely in
1196 // practice.)
1197 if (current_entry)
1198 return current_entry->GetURL();
1199 return current_instance->GetSiteURL();
1202 void RenderFrameHostManager::CreatePendingRenderFrameHost(
1203 SiteInstance* old_instance,
1204 SiteInstance* new_instance,
1205 bool is_main_frame) {
1206 int create_render_frame_flags = 0;
1207 if (is_main_frame)
1208 create_render_frame_flags |= CREATE_RF_FOR_MAIN_FRAME_NAVIGATION;
1210 if (delegate_->IsHidden())
1211 create_render_frame_flags |= CREATE_RF_HIDDEN;
1213 int opener_route_id = CreateOpenerRenderViewsIfNeeded(
1214 old_instance, new_instance, &create_render_frame_flags);
1216 if (pending_render_frame_host_)
1217 CancelPending();
1219 // Create a non-swapped-out RFH with the given opener.
1220 pending_render_frame_host_ =
1221 CreateRenderFrame(new_instance, pending_web_ui(), opener_route_id,
1222 create_render_frame_flags, nullptr);
1225 int RenderFrameHostManager::CreateOpenerRenderViewsIfNeeded(
1226 SiteInstance* old_instance,
1227 SiteInstance* new_instance,
1228 int* create_render_frame_flags) {
1229 int opener_route_id = MSG_ROUTING_NONE;
1230 if (new_instance->IsRelatedSiteInstance(old_instance)) {
1231 opener_route_id =
1232 delegate_->CreateOpenerRenderViewsForRenderManager(new_instance);
1233 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1234 switches::kSitePerProcess)) {
1235 // Ensure that the frame tree has RenderFrameProxyHosts for the new
1236 // SiteInstance in all nodes except the current one.
1237 frame_tree_node_->frame_tree()->CreateProxiesForSiteInstance(
1238 frame_tree_node_, new_instance);
1239 // RenderFrames in different processes from their parent RenderFrames
1240 // in the frame tree require RenderWidgets for rendering and processing
1241 // input events.
1242 if (frame_tree_node_->parent() &&
1243 frame_tree_node_->parent()->current_frame_host()->GetSiteInstance() !=
1244 new_instance)
1245 *create_render_frame_flags |= CREATE_RF_NEEDS_RENDER_WIDGET_HOST;
1248 return opener_route_id;
1251 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::CreateRenderFrameHost(
1252 SiteInstance* site_instance,
1253 int view_routing_id,
1254 int frame_routing_id,
1255 int flags) {
1256 if (frame_routing_id == MSG_ROUTING_NONE)
1257 frame_routing_id = site_instance->GetProcess()->GetNextRoutingID();
1259 bool swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
1260 bool hidden = !!(flags & CREATE_RF_HIDDEN);
1262 // Create a RVH for main frames, or find the existing one for subframes.
1263 FrameTree* frame_tree = frame_tree_node_->frame_tree();
1264 RenderViewHostImpl* render_view_host = nullptr;
1265 if (frame_tree_node_->IsMainFrame()) {
1266 render_view_host = frame_tree->CreateRenderViewHost(
1267 site_instance, view_routing_id, frame_routing_id, swapped_out, hidden);
1268 } else {
1269 render_view_host = frame_tree->GetRenderViewHost(site_instance);
1271 CHECK(render_view_host);
1274 // TODO(creis): Pass hidden to RFH.
1275 scoped_ptr<RenderFrameHostImpl> render_frame_host = make_scoped_ptr(
1276 RenderFrameHostFactory::Create(
1277 site_instance, render_view_host, render_frame_delegate_,
1278 render_widget_delegate_, frame_tree, frame_tree_node_,
1279 frame_routing_id, flags).release());
1280 return render_frame_host.Pass();
1283 // PlzNavigate
1284 bool RenderFrameHostManager::CreateSpeculativeRenderFrameHost(
1285 const GURL& url,
1286 SiteInstance* old_instance,
1287 SiteInstance* new_instance,
1288 int bindings) {
1289 CHECK(new_instance);
1290 CHECK_NE(old_instance, new_instance);
1291 CHECK(!should_reuse_web_ui_);
1293 // Note: |speculative_web_ui_| must be initialized before starting the
1294 // |speculative_render_frame_host_| creation steps otherwise the WebUI
1295 // won't be properly initialized.
1296 speculative_web_ui_ = CreateWebUI(url, bindings);
1298 int create_render_frame_flags = 0;
1299 int opener_route_id =
1300 CreateOpenerRenderViewsIfNeeded(old_instance, new_instance,
1301 &create_render_frame_flags);
1303 if (frame_tree_node_->IsMainFrame())
1304 create_render_frame_flags |= CREATE_RF_FOR_MAIN_FRAME_NAVIGATION;
1305 if (delegate_->IsHidden())
1306 create_render_frame_flags |= CREATE_RF_HIDDEN;
1307 speculative_render_frame_host_ =
1308 CreateRenderFrame(new_instance, speculative_web_ui_.get(),
1309 opener_route_id, create_render_frame_flags, nullptr);
1311 if (!speculative_render_frame_host_) {
1312 speculative_web_ui_.reset();
1313 return false;
1315 return true;
1318 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::CreateRenderFrame(
1319 SiteInstance* instance,
1320 WebUIImpl* web_ui,
1321 int opener_route_id,
1322 int flags,
1323 int* view_routing_id_ptr) {
1324 bool swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
1325 CHECK(instance);
1326 // Swapped out views should always be hidden.
1327 DCHECK(!swapped_out || (flags & CREATE_RF_HIDDEN));
1329 // TODO(nasko): Remove the following CHECK once cross-site navigation no
1330 // longer relies on swapped out RFH for the top-level frame.
1331 if (!frame_tree_node_->IsMainFrame())
1332 CHECK(!swapped_out);
1334 scoped_ptr<RenderFrameHostImpl> new_render_frame_host;
1335 bool success = true;
1336 if (view_routing_id_ptr)
1337 *view_routing_id_ptr = MSG_ROUTING_NONE;
1339 // We are creating a pending, speculative or swapped out RFH here. We should
1340 // never create it in the same SiteInstance as our current RFH.
1341 CHECK_NE(render_frame_host_->GetSiteInstance(), instance);
1343 // Check if we've already created an RFH for this SiteInstance. If so, try
1344 // to re-use the existing one, which has already been initialized. We'll
1345 // remove it from the list of proxy hosts below if it will be active.
1346 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1347 if (proxy && proxy->render_frame_host()) {
1348 if (view_routing_id_ptr)
1349 *view_routing_id_ptr = proxy->GetRenderViewHost()->GetRoutingID();
1350 // Delete the existing RenderFrameProxyHost, but reuse the RenderFrameHost.
1351 // Prevent the process from exiting while we're trying to use it.
1352 if (!swapped_out) {
1353 new_render_frame_host = proxy->PassFrameHostOwnership();
1354 new_render_frame_host->GetProcess()->AddPendingView();
1356 proxy_hosts_.erase(instance->GetId());
1357 delete proxy;
1359 // When a new render view is created by the renderer, the new WebContents
1360 // gets a RenderViewHost in the SiteInstance of its opener WebContents.
1361 // If not used in the first navigation, this RVH is swapped out and is not
1362 // granted bindings, so we may need to grant them when swapping it in.
1363 if (web_ui && !new_render_frame_host->GetProcess()->IsIsolatedGuest()) {
1364 int required_bindings = web_ui->GetBindings();
1365 RenderViewHost* render_view_host =
1366 new_render_frame_host->render_view_host();
1367 if ((render_view_host->GetEnabledBindings() & required_bindings) !=
1368 required_bindings) {
1369 render_view_host->AllowBindings(required_bindings);
1373 } else {
1374 // Create a new RenderFrameHost if we don't find an existing one.
1375 new_render_frame_host = CreateRenderFrameHost(instance, MSG_ROUTING_NONE,
1376 MSG_ROUTING_NONE, flags);
1377 RenderViewHostImpl* render_view_host =
1378 new_render_frame_host->render_view_host();
1379 int proxy_routing_id = MSG_ROUTING_NONE;
1381 // Prevent the process from exiting while we're trying to navigate in it.
1382 // Otherwise, if the new RFH is swapped out already, store it.
1383 if (!swapped_out) {
1384 new_render_frame_host->GetProcess()->AddPendingView();
1385 } else {
1386 proxy = new RenderFrameProxyHost(
1387 new_render_frame_host->GetSiteInstance(), frame_tree_node_);
1388 proxy_hosts_[instance->GetId()] = proxy;
1389 proxy_routing_id = proxy->GetRoutingID();
1390 proxy->TakeFrameHostOwnership(new_render_frame_host.Pass());
1393 success =
1394 InitRenderView(render_view_host, opener_route_id, proxy_routing_id,
1395 !!(flags & CREATE_RF_FOR_MAIN_FRAME_NAVIGATION));
1396 if (success) {
1397 if (frame_tree_node_->IsMainFrame()) {
1398 // Don't show the main frame's view until we get a DidNavigate from it.
1399 // Only the RenderViewHost for the top-level RenderFrameHost has a
1400 // RenderWidgetHostView; RenderWidgetHosts for out-of-process iframes
1401 // will be created later and hidden.
1402 if (render_view_host->GetView())
1403 render_view_host->GetView()->Hide();
1404 } else if (!swapped_out) {
1405 // Init the RFH, so a RenderFrame is created in the renderer.
1406 DCHECK(new_render_frame_host.get());
1407 success = InitRenderFrame(new_render_frame_host.get());
1411 if (success) {
1412 if (view_routing_id_ptr)
1413 *view_routing_id_ptr = render_view_host->GetRoutingID();
1415 // A brand new RenderFrame was created by one of the Init calls above.
1416 // Announce it to observers.
1417 if (swapped_out)
1418 render_frame_delegate_->RenderFrameCreated(proxy->render_frame_host());
1419 else
1420 render_frame_delegate_->RenderFrameCreated(new_render_frame_host.get());
1424 // Returns the new RFH if it isn't swapped out.
1425 if (success && !swapped_out) {
1426 DCHECK(new_render_frame_host->GetSiteInstance() == instance);
1427 return new_render_frame_host.Pass();
1429 return nullptr;
1432 int RenderFrameHostManager::CreateRenderFrameProxy(SiteInstance* instance) {
1433 // A RenderFrameProxyHost should never be created in the same SiteInstance as
1434 // the current RFH.
1435 CHECK(instance);
1436 CHECK_NE(instance, render_frame_host_->GetSiteInstance());
1438 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1439 if (proxy)
1440 return proxy->GetRoutingID();
1442 proxy = new RenderFrameProxyHost(instance, frame_tree_node_);
1443 proxy_hosts_[instance->GetId()] = proxy;
1444 proxy->InitRenderFrameProxy();
1445 return proxy->GetRoutingID();
1448 void RenderFrameHostManager::EnsureRenderViewInitialized(
1449 FrameTreeNode* source,
1450 RenderViewHostImpl* render_view_host,
1451 SiteInstance* instance) {
1452 DCHECK(frame_tree_node_->IsMainFrame());
1454 if (render_view_host->IsRenderViewLive())
1455 return;
1457 // Recreate the opener chain.
1458 int opener_route_id =
1459 delegate_->CreateOpenerRenderViewsForRenderManager(instance);
1460 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1461 InitRenderView(render_view_host, opener_route_id, proxy->GetRoutingID(),
1462 source->IsMainFrame());
1465 bool RenderFrameHostManager::InitRenderView(
1466 RenderViewHostImpl* render_view_host,
1467 int opener_route_id,
1468 int proxy_routing_id,
1469 bool for_main_frame_navigation) {
1470 // We may have initialized this RenderViewHost for another RenderFrameHost.
1471 if (render_view_host->IsRenderViewLive())
1472 return true;
1474 // If the ongoing navigation is to a WebUI and the RenderView is not in a
1475 // guest process, tell the RenderViewHost about any bindings it will need
1476 // enabled.
1477 WebUIImpl* dest_web_ui = nullptr;
1478 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1479 switches::kEnableBrowserSideNavigation)) {
1480 dest_web_ui =
1481 should_reuse_web_ui_ ? web_ui_.get() : speculative_web_ui_.get();
1482 } else {
1483 dest_web_ui = pending_web_ui();
1485 if (dest_web_ui && !render_view_host->GetProcess()->IsIsolatedGuest()) {
1486 render_view_host->AllowBindings(dest_web_ui->GetBindings());
1487 } else {
1488 // Ensure that we don't create an unprivileged RenderView in a WebUI-enabled
1489 // process unless it's swapped out.
1490 if (render_view_host->is_active()) {
1491 CHECK(!ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1492 render_view_host->GetProcess()->GetID()));
1496 return delegate_->CreateRenderViewForRenderManager(render_view_host,
1497 opener_route_id,
1498 proxy_routing_id,
1499 for_main_frame_navigation);
1502 bool RenderFrameHostManager::InitRenderFrame(
1503 RenderFrameHostImpl* render_frame_host) {
1504 if (render_frame_host->IsRenderFrameLive())
1505 return true;
1507 int parent_routing_id = MSG_ROUTING_NONE;
1508 int proxy_routing_id = MSG_ROUTING_NONE;
1509 if (frame_tree_node_->parent()) {
1510 parent_routing_id = frame_tree_node_->parent()->render_manager()->
1511 GetRoutingIdForSiteInstance(render_frame_host->GetSiteInstance());
1512 CHECK_NE(parent_routing_id, MSG_ROUTING_NONE);
1514 // Check whether there is an existing proxy for this frame in this
1515 // SiteInstance. If there is, the new RenderFrame needs to be able to find
1516 // the proxy it is replacing, so that it can fully initialize itself.
1517 // NOTE: This is the only time that a RenderFrameProxyHost can be in the same
1518 // SiteInstance as its RenderFrameHost. This is only the case until the
1519 // RenderFrameHost commits, at which point it will replace and delete the
1520 // RenderFrameProxyHost.
1521 RenderFrameProxyHost* existing_proxy =
1522 GetRenderFrameProxyHost(render_frame_host->GetSiteInstance());
1523 if (existing_proxy) {
1524 proxy_routing_id = existing_proxy->GetRoutingID();
1525 CHECK_NE(proxy_routing_id, MSG_ROUTING_NONE);
1526 if (!existing_proxy->is_render_frame_proxy_live())
1527 existing_proxy->InitRenderFrameProxy();
1529 return delegate_->CreateRenderFrameForRenderManager(render_frame_host,
1530 parent_routing_id,
1531 proxy_routing_id);
1534 int RenderFrameHostManager::GetRoutingIdForSiteInstance(
1535 SiteInstance* site_instance) {
1536 if (render_frame_host_->GetSiteInstance() == site_instance)
1537 return render_frame_host_->GetRoutingID();
1539 RenderFrameProxyHostMap::iterator iter =
1540 proxy_hosts_.find(site_instance->GetId());
1541 if (iter != proxy_hosts_.end())
1542 return iter->second->GetRoutingID();
1544 return MSG_ROUTING_NONE;
1547 void RenderFrameHostManager::CommitPending() {
1548 TRACE_EVENT1("navigation", "RenderFrameHostManager::CommitPending",
1549 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
1550 bool browser_side_navigation =
1551 base::CommandLine::ForCurrentProcess()->HasSwitch(
1552 switches::kEnableBrowserSideNavigation);
1553 // First check whether we're going to want to focus the location bar after
1554 // this commit. We do this now because the navigation hasn't formally
1555 // committed yet, so if we've already cleared |pending_web_ui_| the call chain
1556 // this triggers won't be able to figure out what's going on.
1557 bool will_focus_location_bar = delegate_->FocusLocationBarByDefault();
1559 if (!browser_side_navigation) {
1560 DCHECK(!speculative_web_ui_);
1561 // Next commit the Web UI, if any. Either replace |web_ui_| with
1562 // |pending_web_ui_|, or clear |web_ui_| if there is no pending WebUI, or
1563 // leave |web_ui_| as is if reusing it.
1564 DCHECK(!(pending_web_ui_.get() && pending_and_current_web_ui_.get()));
1565 if (pending_web_ui_) {
1566 web_ui_.reset(pending_web_ui_.release());
1567 } else if (!pending_and_current_web_ui_.get()) {
1568 web_ui_.reset();
1569 } else {
1570 DCHECK_EQ(pending_and_current_web_ui_.get(), web_ui_.get());
1571 pending_and_current_web_ui_.reset();
1573 } else {
1574 // PlzNavigate
1575 if (!should_reuse_web_ui_)
1576 web_ui_.reset(speculative_web_ui_.release());
1577 DCHECK(!speculative_web_ui_);
1580 // It's possible for the pending_render_frame_host_ to be nullptr when we
1581 // aren't crossing process boundaries. If so, we just needed to handle the Web
1582 // UI committing above and we're done.
1583 if (!pending_render_frame_host_ && !speculative_render_frame_host_) {
1584 if (will_focus_location_bar)
1585 delegate_->SetFocusToLocationBar(false);
1586 return;
1589 // Remember if the page was focused so we can focus the new renderer in
1590 // that case.
1591 bool focus_render_view = !will_focus_location_bar &&
1592 render_frame_host_->GetView() &&
1593 render_frame_host_->GetView()->HasFocus();
1595 bool is_main_frame = frame_tree_node_->IsMainFrame();
1597 // Swap in the pending or speculative frame and make it active. Also ensure
1598 // the FrameTree stays in sync.
1599 scoped_ptr<RenderFrameHostImpl> old_render_frame_host;
1600 if (!browser_side_navigation) {
1601 DCHECK(!speculative_render_frame_host_);
1602 old_render_frame_host =
1603 SetRenderFrameHost(pending_render_frame_host_.Pass());
1604 } else {
1605 // PlzNavigate
1606 DCHECK(speculative_render_frame_host_);
1607 old_render_frame_host =
1608 SetRenderFrameHost(speculative_render_frame_host_.Pass());
1610 cross_navigation_pending_ = false;
1612 if (is_main_frame)
1613 render_frame_host_->render_view_host()->AttachToFrameTree();
1615 // The process will no longer try to exit, so we can decrement the count.
1616 render_frame_host_->GetProcess()->RemovePendingView();
1618 // Show the new view (or a sad tab) if necessary.
1619 bool new_rfh_has_view = !!render_frame_host_->GetView();
1620 if (!delegate_->IsHidden() && new_rfh_has_view) {
1621 // In most cases, we need to show the new view.
1622 render_frame_host_->GetView()->Show();
1624 if (!new_rfh_has_view) {
1625 // If the view is gone, then this RenderViewHost died while it was hidden.
1626 // We ignored the RenderProcessGone call at the time, so we should send it
1627 // now to make sure the sad tab shows up, etc.
1628 DCHECK(!render_frame_host_->IsRenderFrameLive());
1629 DCHECK(!render_frame_host_->render_view_host()->IsRenderViewLive());
1630 delegate_->RenderProcessGoneFromRenderManager(
1631 render_frame_host_->render_view_host());
1634 // For top-level frames, also hide the old RenderViewHost's view.
1635 // TODO(creis): As long as show/hide are on RVH, we don't want to hide on
1636 // subframe navigations or we will interfere with the top-level frame.
1637 if (is_main_frame && old_render_frame_host->render_view_host()->GetView())
1638 old_render_frame_host->render_view_host()->GetView()->Hide();
1640 // Make sure the size is up to date. (Fix for bug 1079768.)
1641 delegate_->UpdateRenderViewSizeForRenderManager();
1643 if (will_focus_location_bar) {
1644 delegate_->SetFocusToLocationBar(false);
1645 } else if (focus_render_view && render_frame_host_->GetView()) {
1646 render_frame_host_->GetView()->Focus();
1649 // Notify that we've swapped RenderFrameHosts. We do this before shutting down
1650 // the RFH so that we can clean up RendererResources related to the RFH first.
1651 delegate_->NotifySwappedFromRenderManager(
1652 old_render_frame_host.get(), render_frame_host_.get(), is_main_frame);
1654 // Swap out the old frame now that the new one is visible.
1655 // This will swap it out and then put it on the proxy list (if there are other
1656 // active views in its SiteInstance) or schedule it for deletion when the swap
1657 // out ack arrives (or immediately if the process isn't live).
1658 // In the --site-per-process case, old subframe RHFs are not kept alive inside
1659 // the proxy.
1660 SwapOutOldFrame(old_render_frame_host.Pass());
1662 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1663 switches::kSitePerProcess) &&
1664 !is_main_frame) {
1665 // If this is a subframe, it should have a CrossProcessFrameConnector
1666 // created already. Use it to link the new RFH's view to the proxy that
1667 // belongs to the parent frame's SiteInstance.
1668 // Note: We do this after swapping out the old RFH because that may create
1669 // the proxy we're looking for.
1670 RenderFrameProxyHost* proxy_to_parent = GetProxyToParent();
1671 if (proxy_to_parent) {
1672 proxy_to_parent->SetChildRWHView(render_frame_host_->GetView());
1675 // Since the new RenderFrameHost is now committed, there must be no proxies
1676 // for its SiteInstance. Delete any existing ones.
1677 RenderFrameProxyHostMap::iterator iter =
1678 proxy_hosts_.find(render_frame_host_->GetSiteInstance()->GetId());
1679 if (iter != proxy_hosts_.end()) {
1680 delete iter->second;
1681 proxy_hosts_.erase(iter);
1685 // After all is done, there must never be a proxy in the list which has the
1686 // same SiteInstance as the current RenderFrameHost.
1687 CHECK(proxy_hosts_.find(render_frame_host_->GetSiteInstance()->GetId()) ==
1688 proxy_hosts_.end());
1691 void RenderFrameHostManager::ShutdownRenderFrameProxyHostsInSiteInstance(
1692 int32 site_instance_id) {
1693 // First remove any swapped out RFH for this SiteInstance from our own list.
1694 ClearProxiesInSiteInstance(site_instance_id, frame_tree_node_);
1696 // Use the safe RenderWidgetHost iterator for now to find all RenderViewHosts
1697 // in the SiteInstance, then tell their respective FrameTrees to remove all
1698 // RenderFrameProxyHosts corresponding to them.
1699 // TODO(creis): Replace this with a RenderFrameHostIterator that protects
1700 // against use-after-frees if a later element is deleted before getting to it.
1701 scoped_ptr<RenderWidgetHostIterator> widgets(
1702 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
1703 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
1704 if (!widget->IsRenderView())
1705 continue;
1706 RenderViewHostImpl* rvh =
1707 static_cast<RenderViewHostImpl*>(RenderViewHost::From(widget));
1708 if (site_instance_id == rvh->GetSiteInstance()->GetId()) {
1709 // This deletes all RenderFrameHosts using the |rvh|, which then causes
1710 // |rvh| to Shutdown.
1711 FrameTree* tree = rvh->GetDelegate()->GetFrameTree();
1712 tree->ForEach(base::Bind(
1713 &RenderFrameHostManager::ClearProxiesInSiteInstance,
1714 site_instance_id));
1719 RenderFrameHostImpl* RenderFrameHostManager::UpdateStateForNavigate(
1720 const GURL& dest_url,
1721 SiteInstance* source_instance,
1722 SiteInstance* dest_instance,
1723 ui::PageTransition transition,
1724 bool dest_is_restore,
1725 bool dest_is_view_source_mode,
1726 const GlobalRequestID& transferred_request_id,
1727 int bindings) {
1728 // If we are currently navigating cross-process, we want to get back to normal
1729 // and then navigate as usual.
1730 if (cross_navigation_pending_) {
1731 if (pending_render_frame_host_)
1732 CancelPending();
1733 cross_navigation_pending_ = false;
1736 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1737 scoped_refptr<SiteInstance> new_instance = GetSiteInstanceForNavigation(
1738 dest_url, source_instance, dest_instance, transition,
1739 dest_is_restore, dest_is_view_source_mode);
1741 const NavigationEntry* current_entry =
1742 delegate_->GetLastCommittedNavigationEntryForRenderManager();
1744 DCHECK(!cross_navigation_pending_);
1746 if (new_instance.get() != current_instance) {
1747 TRACE_EVENT_INSTANT2(
1748 "navigation",
1749 "RenderFrameHostManager::UpdateStateForNavigate:New SiteInstance",
1750 TRACE_EVENT_SCOPE_THREAD,
1751 "current_instance id", current_instance->GetId(),
1752 "new_instance id", new_instance->GetId());
1754 // New SiteInstance: create a pending RFH to navigate.
1756 // This will possibly create (set to nullptr) a Web UI object for the
1757 // pending page. We'll use this later to give the page special access. This
1758 // must happen before the new renderer is created below so it will get
1759 // bindings. It must also happen after the above conditional call to
1760 // CancelPending(), otherwise CancelPending may clear the pending_web_ui_
1761 // and the page will not have its bindings set appropriately.
1762 SetPendingWebUI(dest_url, bindings);
1763 CreatePendingRenderFrameHost(current_instance, new_instance.get(),
1764 frame_tree_node_->IsMainFrame());
1765 if (!pending_render_frame_host_.get()) {
1766 return nullptr;
1769 // Check if our current RFH is live before we set up a transition.
1770 if (!render_frame_host_->IsRenderFrameLive()) {
1771 if (!cross_navigation_pending_) {
1772 // The current RFH is not live. There's no reason to sit around with a
1773 // sad tab or a newly created RFH while we wait for the pending RFH to
1774 // navigate. Just switch to the pending RFH now and go back to non
1775 // cross-navigating (Note that we don't care about on{before}unload
1776 // handlers if the current RFH isn't live.)
1777 CommitPending();
1778 return render_frame_host_.get();
1779 } else {
1780 NOTREACHED();
1781 return render_frame_host_.get();
1784 // Otherwise, it's safe to treat this as a pending cross-site transition.
1786 // We now have a pending RFH.
1787 DCHECK(!cross_navigation_pending_);
1788 cross_navigation_pending_ = true;
1790 // We need to wait until the beforeunload handler has run, unless we are
1791 // transferring an existing request (in which case it has already run).
1792 // Suspend the new render view (i.e., don't let it send the cross-site
1793 // Navigate message) until we hear back from the old renderer's
1794 // beforeunload handler. If the handler returns false, we'll have to
1795 // cancel the request.
1797 DCHECK(!pending_render_frame_host_->are_navigations_suspended());
1798 bool is_transfer = transferred_request_id != GlobalRequestID();
1799 if (is_transfer) {
1800 // We don't need to stop the old renderer or run beforeunload/unload
1801 // handlers, because those have already been done.
1802 DCHECK(cross_site_transferring_request_->request_id() ==
1803 transferred_request_id);
1804 } else {
1805 // Also make sure the old render view stops, in case a load is in
1806 // progress. (We don't want to do this for transfers, since it will
1807 // interrupt the transfer with an unexpected DidStopLoading.)
1808 render_frame_host_->Send(new FrameMsg_Stop(
1809 render_frame_host_->GetRoutingID()));
1810 pending_render_frame_host_->SetNavigationsSuspended(true,
1811 base::TimeTicks());
1812 // Unless we are transferring an existing request, we should now tell the
1813 // old render view to run its beforeunload handler, since it doesn't
1814 // otherwise know that the cross-site request is happening. This will
1815 // trigger a call to OnBeforeUnloadACK with the reply.
1816 render_frame_host_->DispatchBeforeUnload(true);
1819 return pending_render_frame_host_.get();
1822 // Otherwise the same SiteInstance can be used. Navigate render_frame_host_.
1824 // It's possible to swap out the current RFH and then decide to navigate in it
1825 // anyway (e.g., a cross-process navigation that redirects back to the
1826 // original site). In that case, we have a proxy for the current RFH but
1827 // haven't deleted it yet. The new navigation will swap it back in, so we can
1828 // delete the proxy.
1829 DeleteRenderFrameProxyHost(new_instance.get());
1831 if (ShouldReuseWebUI(current_entry, dest_url)) {
1832 pending_web_ui_.reset();
1833 pending_and_current_web_ui_ = web_ui_->AsWeakPtr();
1834 } else {
1835 SetPendingWebUI(dest_url, bindings);
1836 // Make sure the new RenderViewHost has the right bindings.
1837 if (pending_web_ui() &&
1838 !render_frame_host_->GetProcess()->IsIsolatedGuest()) {
1839 render_frame_host_->render_view_host()->AllowBindings(
1840 pending_web_ui()->GetBindings());
1844 if (pending_web_ui() && render_frame_host_->IsRenderFrameLive()) {
1845 pending_web_ui()->GetController()->RenderViewReused(
1846 render_frame_host_->render_view_host());
1849 // The renderer can exit view source mode when any error or cancellation
1850 // happen. We must overwrite to recover the mode.
1851 if (dest_is_view_source_mode) {
1852 render_frame_host_->render_view_host()->Send(
1853 new ViewMsg_EnableViewSourceMode(
1854 render_frame_host_->render_view_host()->GetRoutingID()));
1857 return render_frame_host_.get();
1860 void RenderFrameHostManager::CancelPending() {
1861 TRACE_EVENT1("navigation", "RenderFrameHostManager::CancelPending",
1862 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
1863 DiscardUnusedFrame(UnsetPendingRenderFrameHost());
1866 scoped_ptr<RenderFrameHostImpl>
1867 RenderFrameHostManager::UnsetPendingRenderFrameHost() {
1868 scoped_ptr<RenderFrameHostImpl> pending_render_frame_host =
1869 pending_render_frame_host_.Pass();
1871 RenderFrameDevToolsAgentHost::OnCancelPendingNavigation(
1872 pending_render_frame_host.get(),
1873 render_frame_host_.get());
1875 // We no longer need to prevent the process from exiting.
1876 pending_render_frame_host->GetProcess()->RemovePendingView();
1878 pending_web_ui_.reset();
1879 pending_and_current_web_ui_.reset();
1881 return pending_render_frame_host.Pass();
1884 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::SetRenderFrameHost(
1885 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
1886 // Swap the two.
1887 scoped_ptr<RenderFrameHostImpl> old_render_frame_host =
1888 render_frame_host_.Pass();
1889 render_frame_host_ = render_frame_host.Pass();
1891 if (frame_tree_node_->IsMainFrame()) {
1892 // Update the count of top-level frames using this SiteInstance. All
1893 // subframes are in the same BrowsingInstance as the main frame, so we only
1894 // count top-level ones. This makes the value easier for consumers to
1895 // interpret.
1896 if (render_frame_host_) {
1897 render_frame_host_->GetSiteInstance()->
1898 IncrementRelatedActiveContentsCount();
1900 if (old_render_frame_host) {
1901 old_render_frame_host->GetSiteInstance()->
1902 DecrementRelatedActiveContentsCount();
1906 return old_render_frame_host.Pass();
1909 bool RenderFrameHostManager::IsRVHOnSwappedOutList(
1910 RenderViewHostImpl* rvh) const {
1911 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(
1912 rvh->GetSiteInstance());
1913 if (!proxy)
1914 return false;
1915 // If there is a proxy without RFH, it is for a subframe in the SiteInstance
1916 // of |rvh|. Subframes should be ignored in this case.
1917 if (!proxy->render_frame_host())
1918 return false;
1919 return IsOnSwappedOutList(proxy->render_frame_host());
1922 bool RenderFrameHostManager::IsOnSwappedOutList(
1923 RenderFrameHostImpl* rfh) const {
1924 if (!rfh->GetSiteInstance())
1925 return false;
1927 RenderFrameProxyHostMap::const_iterator iter = proxy_hosts_.find(
1928 rfh->GetSiteInstance()->GetId());
1929 if (iter == proxy_hosts_.end())
1930 return false;
1932 return iter->second->render_frame_host() == rfh;
1935 RenderViewHostImpl* RenderFrameHostManager::GetSwappedOutRenderViewHost(
1936 SiteInstance* instance) const {
1937 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1938 if (proxy)
1939 return proxy->GetRenderViewHost();
1940 return NULL;
1943 RenderFrameProxyHost* RenderFrameHostManager::GetRenderFrameProxyHost(
1944 SiteInstance* instance) const {
1945 RenderFrameProxyHostMap::const_iterator iter =
1946 proxy_hosts_.find(instance->GetId());
1947 if (iter != proxy_hosts_.end())
1948 return iter->second;
1950 return NULL;
1953 void RenderFrameHostManager::DeleteRenderFrameProxyHost(
1954 SiteInstance* instance) {
1955 RenderFrameProxyHostMap::iterator iter = proxy_hosts_.find(instance->GetId());
1956 if (iter != proxy_hosts_.end()) {
1957 delete iter->second;
1958 proxy_hosts_.erase(iter);
1962 } // namespace content