Add remoting and PPAPI tests to GN build
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_manager.cc
blobf9e2bf976fcbe85f71d53b78f7fbd8fe5bcf37f9
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 // Release the WebUI prior to resetting the current RenderFrameHost, as the
91 // WebUI accesses the RenderFrameHost during cleanup.
92 web_ui_.reset();
94 // We should always have a current RenderFrameHost except in some tests.
95 SetRenderFrameHost(scoped_ptr<RenderFrameHostImpl>());
98 void RenderFrameHostManager::Init(BrowserContext* browser_context,
99 SiteInstance* site_instance,
100 int view_routing_id,
101 int frame_routing_id) {
102 // Create a RenderViewHost and RenderFrameHost, once we have an instance. It
103 // is important to immediately give this SiteInstance to a RenderViewHost so
104 // that the SiteInstance is ref counted.
105 if (!site_instance)
106 site_instance = SiteInstance::Create(browser_context);
108 int flags = delegate_->IsHidden() ? CREATE_RF_HIDDEN : 0;
109 SetRenderFrameHost(CreateRenderFrameHost(site_instance, view_routing_id,
110 frame_routing_id, flags));
112 // Keep track of renderer processes as they start to shut down or are
113 // crashed/killed.
114 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSED,
115 NotificationService::AllSources());
116 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSING,
117 NotificationService::AllSources());
120 RenderViewHostImpl* RenderFrameHostManager::current_host() const {
121 if (!render_frame_host_)
122 return NULL;
123 return render_frame_host_->render_view_host();
126 RenderViewHostImpl* RenderFrameHostManager::pending_render_view_host() const {
127 if (!pending_render_frame_host_)
128 return NULL;
129 return pending_render_frame_host_->render_view_host();
132 RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const {
133 if (interstitial_page_)
134 return interstitial_page_->GetView();
135 if (render_frame_host_)
136 return render_frame_host_->GetView();
137 return nullptr;
140 RenderFrameProxyHost* RenderFrameHostManager::GetProxyToParent() {
141 if (frame_tree_node_->IsMainFrame())
142 return NULL;
144 RenderFrameProxyHostMap::iterator iter =
145 proxy_hosts_.find(frame_tree_node_->parent()
146 ->render_manager()
147 ->current_frame_host()
148 ->GetSiteInstance()
149 ->GetId());
150 if (iter == proxy_hosts_.end())
151 return NULL;
153 return iter->second;
156 void RenderFrameHostManager::SetPendingWebUI(const GURL& url, int bindings) {
157 pending_web_ui_ = CreateWebUI(url, bindings);
158 pending_and_current_web_ui_.reset();
161 scoped_ptr<WebUIImpl> RenderFrameHostManager::CreateWebUI(const GURL& url,
162 int bindings) {
163 scoped_ptr<WebUIImpl> new_web_ui(delegate_->CreateWebUIForRenderManager(url));
165 // If we have assigned (zero or more) bindings to this NavigationEntry in the
166 // past, make sure we're not granting it different bindings than it had
167 // before. If so, note it and don't give it any bindings, to avoid a
168 // potential privilege escalation.
169 if (new_web_ui && bindings != NavigationEntryImpl::kInvalidBindings &&
170 new_web_ui->GetBindings() != bindings) {
171 RecordAction(base::UserMetricsAction("ProcessSwapBindingsMismatch_RVHM"));
172 return nullptr;
174 return new_web_ui.Pass();
177 RenderFrameHostImpl* RenderFrameHostManager::Navigate(
178 const NavigationEntryImpl& entry) {
179 TRACE_EVENT1("navigation", "RenderFrameHostManager:Navigate",
180 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
181 // Create a pending RenderFrameHost to use for the navigation.
182 RenderFrameHostImpl* dest_render_frame_host = UpdateStateForNavigate(
183 entry.GetURL(), entry.source_site_instance(), entry.site_instance(),
184 entry.GetTransitionType(),
185 entry.restore_type() != NavigationEntryImpl::RESTORE_NONE,
186 entry.IsViewSourceMode(), entry.transferred_global_request_id(),
187 entry.bindings());
188 if (!dest_render_frame_host)
189 return NULL; // We weren't able to create a pending render frame host.
191 // If the current render_frame_host_ isn't live, we should create it so
192 // that we don't show a sad tab while the dest_render_frame_host fetches
193 // its first page. (Bug 1145340)
194 if (dest_render_frame_host != render_frame_host_ &&
195 !render_frame_host_->IsRenderFrameLive()) {
196 // Note: we don't call InitRenderView here because we are navigating away
197 // soon anyway, and we don't have the NavigationEntry for this host.
198 delegate_->CreateRenderViewForRenderManager(
199 render_frame_host_->render_view_host(), MSG_ROUTING_NONE,
200 MSG_ROUTING_NONE, frame_tree_node_->IsMainFrame());
203 // If the renderer crashed, then try to create a new one to satisfy this
204 // navigation request.
205 if (!dest_render_frame_host->IsRenderFrameLive()) {
206 // Instruct the destination render frame host to set up a Mojo connection
207 // with the new render frame if necessary. Note that this call needs to
208 // occur before initializing the RenderView; the flow of creating the
209 // RenderView can cause browser-side code to execute that expects the this
210 // RFH's ServiceRegistry to be initialized (e.g., if the site is a WebUI
211 // site that is handled via Mojo, then Mojo WebUI code in //chrome will
212 // add a service to this RFH's ServiceRegistry).
213 dest_render_frame_host->SetUpMojoIfNeeded();
215 // Recreate the opener chain.
216 int opener_route_id = delegate_->CreateOpenerRenderViewsForRenderManager(
217 dest_render_frame_host->GetSiteInstance());
218 if (!InitRenderView(dest_render_frame_host->render_view_host(),
219 opener_route_id,
220 MSG_ROUTING_NONE,
221 frame_tree_node_->IsMainFrame()))
222 return NULL;
224 // Now that we've created a new renderer, be sure to hide it if it isn't
225 // our primary one. Otherwise, we might crash if we try to call Show()
226 // on it later.
227 if (dest_render_frame_host != render_frame_host_ &&
228 dest_render_frame_host->GetView()) {
229 dest_render_frame_host->GetView()->Hide();
230 } else {
231 // Notify here as we won't be calling CommitPending (which does the
232 // notify).
233 delegate_->NotifySwappedFromRenderManager(
234 NULL, render_frame_host_.get(), frame_tree_node_->IsMainFrame());
238 // If entry includes the request ID of a request that is being transferred,
239 // the destination render frame will take ownership, so release ownership of
240 // the request.
241 if (cross_site_transferring_request_.get() &&
242 cross_site_transferring_request_->request_id() ==
243 entry.transferred_global_request_id()) {
244 cross_site_transferring_request_->ReleaseRequest();
247 return dest_render_frame_host;
250 void RenderFrameHostManager::Stop() {
251 render_frame_host_->Stop();
253 // If we are cross-navigating, we should stop the pending renderers. This
254 // will lead to a DidFailProvisionalLoad, which will properly destroy them.
255 if (cross_navigation_pending_) {
256 pending_render_frame_host_->Send(new FrameMsg_Stop(
257 pending_render_frame_host_->GetRoutingID()));
261 void RenderFrameHostManager::SetIsLoading(bool is_loading) {
262 render_frame_host_->render_view_host()->SetIsLoading(is_loading);
263 if (pending_render_frame_host_)
264 pending_render_frame_host_->render_view_host()->SetIsLoading(is_loading);
267 bool RenderFrameHostManager::ShouldCloseTabOnUnresponsiveRenderer() {
268 // If we're waiting for a close ACK, then the tab should close whether there's
269 // a navigation in progress or not. Unfortunately, we also need to check for
270 // cases that we arrive here with no navigation in progress, since there are
271 // some tab closure paths that don't set is_waiting_for_close_ack to true.
272 // TODO(creis): Clean this up in http://crbug.com/418266.
273 if (!cross_navigation_pending_ ||
274 render_frame_host_->render_view_host()->is_waiting_for_close_ack())
275 return true;
277 // We should always have a pending RFH when there's a cross-process navigation
278 // in progress. Sanity check this for http://crbug.com/276333.
279 CHECK(pending_render_frame_host_);
281 // Unload handlers run in the background, so we should never get an
282 // unresponsiveness warning for them.
283 CHECK(!render_frame_host_->IsWaitingForUnloadACK());
285 // If the tab becomes unresponsive during beforeunload while doing a
286 // cross-site navigation, proceed with the navigation. (This assumes that
287 // the pending RenderFrameHost is still responsive.)
288 if (render_frame_host_->IsWaitingForBeforeUnloadACK()) {
289 // Haven't gotten around to starting the request, because we're still
290 // waiting for the beforeunload handler to finish. We'll pretend that it
291 // did finish, to let the navigation proceed. Note that there's a danger
292 // that the beforeunload handler will later finish and possibly return
293 // false (meaning the navigation should not proceed), but we'll ignore it
294 // in this case because it took too long.
295 if (pending_render_frame_host_->are_navigations_suspended()) {
296 pending_render_frame_host_->SetNavigationsSuspended(
297 false, base::TimeTicks::Now());
300 return false;
303 void RenderFrameHostManager::OnBeforeUnloadACK(
304 bool for_cross_site_transition,
305 bool proceed,
306 const base::TimeTicks& proceed_time) {
307 if (for_cross_site_transition) {
308 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
309 switches::kEnableBrowserSideNavigation));
310 // Ignore if we're not in a cross-site navigation.
311 if (!cross_navigation_pending_)
312 return;
314 if (proceed) {
315 // Ok to unload the current page, so proceed with the cross-site
316 // navigation. Note that if navigations are not currently suspended, it
317 // might be because the renderer was deemed unresponsive and this call was
318 // already made by ShouldCloseTabOnUnresponsiveRenderer. In that case, it
319 // is ok to do nothing here.
320 if (pending_render_frame_host_ &&
321 pending_render_frame_host_->are_navigations_suspended()) {
322 pending_render_frame_host_->SetNavigationsSuspended(false,
323 proceed_time);
325 } else {
326 // Current page says to cancel.
327 CancelPending();
328 cross_navigation_pending_ = false;
330 } else {
331 // Non-cross site transition means closing the entire tab.
332 bool proceed_to_fire_unload;
333 delegate_->BeforeUnloadFiredFromRenderManager(proceed, proceed_time,
334 &proceed_to_fire_unload);
336 if (proceed_to_fire_unload) {
337 // If we're about to close the tab and there's a pending RFH, cancel it.
338 // Otherwise, if the navigation in the pending RFH completes before the
339 // close in the current RFH, we'll lose the tab close.
340 if (pending_render_frame_host_) {
341 CancelPending();
342 cross_navigation_pending_ = false;
345 // This is not a cross-site navigation, the tab is being closed.
346 render_frame_host_->render_view_host()->ClosePage();
351 void RenderFrameHostManager::OnCrossSiteResponse(
352 RenderFrameHostImpl* pending_render_frame_host,
353 const GlobalRequestID& global_request_id,
354 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
355 const std::vector<GURL>& transfer_url_chain,
356 const Referrer& referrer,
357 ui::PageTransition page_transition,
358 bool should_replace_current_entry) {
359 // We should only get here for transfer navigations. Most cross-process
360 // navigations can just continue and wait to run the unload handler (by
361 // swapping out) when the new navigation commits.
362 CHECK(cross_site_transferring_request.get());
364 // A transfer should only have come from our pending or current RFH.
365 // TODO(creis): We need to handle the case that the pending RFH has changed
366 // in the mean time, while this was being posted from the IO thread. We
367 // should probably cancel the request in that case.
368 DCHECK(pending_render_frame_host == pending_render_frame_host_ ||
369 pending_render_frame_host == render_frame_host_);
371 // Store the transferring request so that we can release it if the transfer
372 // navigation matches.
373 cross_site_transferring_request_ = cross_site_transferring_request.Pass();
375 // Sanity check that the params are for the correct frame and process.
376 // These should match the RenderFrameHost that made the request.
377 // If it started as a cross-process navigation via OpenURL, this is the
378 // pending one. If it wasn't cross-process until the transfer, this is the
379 // current one.
380 int render_frame_id = pending_render_frame_host_ ?
381 pending_render_frame_host_->GetRoutingID() :
382 render_frame_host_->GetRoutingID();
383 DCHECK_EQ(render_frame_id, pending_render_frame_host->GetRoutingID());
384 int process_id = pending_render_frame_host_ ?
385 pending_render_frame_host_->GetProcess()->GetID() :
386 render_frame_host_->GetProcess()->GetID();
387 DCHECK_EQ(process_id, global_request_id.child_id);
389 // Treat the last URL in the chain as the destination and the remainder as
390 // the redirect chain.
391 CHECK(transfer_url_chain.size());
392 GURL transfer_url = transfer_url_chain.back();
393 std::vector<GURL> rest_of_chain = transfer_url_chain;
394 rest_of_chain.pop_back();
396 // We don't know whether the original request had |user_action| set to true.
397 // However, since we force the navigation to be in the current tab, it
398 // doesn't matter.
399 pending_render_frame_host->frame_tree_node()->navigator()->RequestTransferURL(
400 pending_render_frame_host, transfer_url, nullptr, rest_of_chain, referrer,
401 page_transition, CURRENT_TAB, global_request_id,
402 should_replace_current_entry, true);
404 // The transferring request was only needed during the RequestTransferURL
405 // call, so it is safe to clear at this point.
406 cross_site_transferring_request_.reset();
409 void RenderFrameHostManager::OnDeferredAfterResponseStarted(
410 const GlobalRequestID& global_request_id,
411 RenderFrameHostImpl* pending_render_frame_host) {
412 DCHECK(!response_started_id_.get());
414 response_started_id_.reset(new GlobalRequestID(global_request_id));
417 void RenderFrameHostManager::ResumeResponseDeferredAtStart() {
418 DCHECK(response_started_id_.get());
420 RenderProcessHostImpl* process =
421 static_cast<RenderProcessHostImpl*>(render_frame_host_->GetProcess());
422 process->ResumeResponseDeferredAtStart(*response_started_id_);
424 render_frame_host_->ClearPendingTransitionRequestData();
426 response_started_id_.reset();
429 void RenderFrameHostManager::ClearNavigationTransitionData() {
430 render_frame_host_->ClearPendingTransitionRequestData();
433 void RenderFrameHostManager::DidNavigateFrame(
434 RenderFrameHostImpl* render_frame_host,
435 bool was_caused_by_user_gesture) {
436 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
437 switches::kEnableBrowserSideNavigation)) {
438 if (render_frame_host == speculative_render_frame_host_.get()) {
439 CommitPending();
440 } else if (render_frame_host == render_frame_host_.get()) {
441 // TODO(carlosk): this code doesn't properly handle in-page navigation or
442 // interwoven navigation requests.
443 DCHECK(!speculative_render_frame_host_);
444 } else {
445 // No one else should be sending us a DidNavigate in this state.
446 DCHECK(false);
448 DCHECK(!speculative_render_frame_host_);
449 return;
452 if (!cross_navigation_pending_) {
453 DCHECK(!pending_render_frame_host_);
455 // We should only hear this from our current renderer.
456 DCHECK_EQ(render_frame_host_, render_frame_host);
458 // Even when there is no pending RVH, there may be a pending Web UI.
459 if (pending_web_ui())
460 CommitPending();
461 return;
464 if (render_frame_host == pending_render_frame_host_) {
465 // The pending cross-site navigation completed, so show the renderer.
466 CommitPending();
467 } else if (render_frame_host == render_frame_host_) {
468 if (was_caused_by_user_gesture) {
469 // A navigation in the original page has taken place. Cancel the pending
470 // one. Only do it for user gesture originated navigations to prevent
471 // page doing any shenanigans to prevent user from navigating.
472 // See https://code.google.com/p/chromium/issues/detail?id=75195
473 CancelPending();
474 cross_navigation_pending_ = false;
476 } else {
477 // No one else should be sending us DidNavigate in this state.
478 DCHECK(false);
482 void RenderFrameHostManager::DidDisownOpener(
483 RenderFrameHost* render_frame_host) {
484 // Notify all RenderFrameHosts but the one that notified us. This is necessary
485 // in case a process swap has occurred while the message was in flight.
486 for (RenderFrameProxyHostMap::iterator iter = proxy_hosts_.begin();
487 iter != proxy_hosts_.end();
488 ++iter) {
489 DCHECK_NE(iter->second->GetSiteInstance(),
490 current_frame_host()->GetSiteInstance());
491 iter->second->DisownOpener();
494 if (render_frame_host_.get() != render_frame_host)
495 render_frame_host_->DisownOpener();
497 if (pending_render_frame_host_ &&
498 pending_render_frame_host_.get() != render_frame_host) {
499 pending_render_frame_host_->DisownOpener();
503 void RenderFrameHostManager::RendererProcessClosing(
504 RenderProcessHost* render_process_host) {
505 // Remove any swapped out RVHs from this process, so that we don't try to
506 // swap them back in while the process is exiting. Start by finding them,
507 // since there could be more than one.
508 std::list<int> ids_to_remove;
509 // Do not remove proxies in the dead process that still have active frame
510 // count though, we just reset them to be uninitialized.
511 std::list<int> ids_to_keep;
512 for (RenderFrameProxyHostMap::iterator iter = proxy_hosts_.begin();
513 iter != proxy_hosts_.end();
514 ++iter) {
515 RenderFrameProxyHost* proxy = iter->second;
516 if (proxy->GetProcess() != render_process_host)
517 continue;
519 if (static_cast<SiteInstanceImpl*>(proxy->GetSiteInstance())
520 ->active_frame_count() >= 1U) {
521 ids_to_keep.push_back(iter->first);
522 } else {
523 ids_to_remove.push_back(iter->first);
527 // Now delete them.
528 while (!ids_to_remove.empty()) {
529 delete proxy_hosts_[ids_to_remove.back()];
530 proxy_hosts_.erase(ids_to_remove.back());
531 ids_to_remove.pop_back();
534 while (!ids_to_keep.empty()) {
535 frame_tree_node_->frame_tree()->ForEach(
536 base::Bind(
537 &RenderFrameHostManager::ResetProxiesInSiteInstance,
538 ids_to_keep.back()));
539 ids_to_keep.pop_back();
543 void RenderFrameHostManager::SwapOutOldFrame(
544 scoped_ptr<RenderFrameHostImpl> old_render_frame_host) {
545 TRACE_EVENT1("navigation", "RenderFrameHostManager::SwapOutOldFrame",
546 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
548 // Tell the renderer to suppress any further modal dialogs so that we can swap
549 // it out. This must be done before canceling any current dialog, in case
550 // there is a loop creating additional dialogs.
551 // TODO(creis): Handle modal dialogs in subframe processes.
552 old_render_frame_host->render_view_host()->SuppressDialogsUntilSwapOut();
554 // Now close any modal dialogs that would prevent us from swapping out. This
555 // must be done separately from SwapOut, so that the PageGroupLoadDeferrer is
556 // no longer on the stack when we send the SwapOut message.
557 delegate_->CancelModalDialogsForRenderManager();
559 // If the old RFH is not live, just return as there is no further work to do.
560 // It will be deleted and there will be no proxy created.
561 int32 old_site_instance_id =
562 old_render_frame_host->GetSiteInstance()->GetId();
563 if (!old_render_frame_host->IsRenderFrameLive()) {
564 ShutdownRenderFrameProxyHostsInSiteInstance(old_site_instance_id);
565 return;
568 // If there are no active frames besides this one, we can delete the old
569 // RenderFrameHost once it runs its unload handler, without replacing it with
570 // a proxy.
571 size_t active_frame_count =
572 old_render_frame_host->GetSiteInstance()->active_frame_count();
573 if (active_frame_count <= 1) {
574 // Tell the old RenderFrameHost to swap out, with no proxy to replace it.
575 old_render_frame_host->SwapOut(NULL, true);
576 MoveToPendingDeleteHosts(old_render_frame_host.Pass());
578 // Also clear out any proxies from this SiteInstance, in case this was the
579 // last one keeping other proxies alive.
580 ShutdownRenderFrameProxyHostsInSiteInstance(old_site_instance_id);
582 return;
585 // Otherwise there are active views and we need a proxy for the old RFH.
586 // (There should not be one yet.)
587 CHECK(!GetRenderFrameProxyHost(old_render_frame_host->GetSiteInstance()));
588 RenderFrameProxyHost* proxy = new RenderFrameProxyHost(
589 old_render_frame_host->GetSiteInstance(), frame_tree_node_);
590 CHECK(proxy_hosts_.insert(std::make_pair(old_site_instance_id, proxy)).second)
591 << "Inserting a duplicate item.";
593 // Tell the old RenderFrameHost to swap out and be replaced by the proxy.
594 old_render_frame_host->SwapOut(proxy, true);
596 // SwapOut creates a RenderFrameProxy, so set the proxy to be initialized.
597 proxy->set_render_frame_proxy_created(true);
599 bool is_main_frame = frame_tree_node_->IsMainFrame();
600 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
601 switches::kSitePerProcess) &&
602 !is_main_frame) {
603 // In --site-per-process, subframes delete their RFH rather than storing it
604 // in the proxy. Schedule it for deletion once the SwapOutACK comes in.
605 // TODO(creis): This will be the default when we remove swappedout://.
606 MoveToPendingDeleteHosts(old_render_frame_host.Pass());
607 } else {
608 // We shouldn't get here for subframes, since we only swap subframes when
609 // --site-per-process is used.
610 DCHECK(is_main_frame);
612 // The old RenderFrameHost will stay alive inside the proxy so that existing
613 // JavaScript window references to it stay valid.
614 proxy->TakeFrameHostOwnership(old_render_frame_host.Pass());
618 void RenderFrameHostManager::DiscardUnusedFrame(
619 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
620 // TODO(carlosk): this code is very similar to what can be found in
621 // SwapOutOldFrame and we should see that these are unified at some point.
623 // If the SiteInstance for the pending RFH is being used by others don't
624 // delete the RFH. Just swap it out and it can be reused at a later point.
625 SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance();
626 if (site_instance->HasSite() && site_instance->active_frame_count() > 1) {
627 // Any currently suspended navigations are no longer needed.
628 render_frame_host->CancelSuspendedNavigations();
630 RenderFrameProxyHost* proxy =
631 new RenderFrameProxyHost(site_instance, frame_tree_node_);
632 proxy_hosts_[site_instance->GetId()] = proxy;
634 // Check if the RenderFrameHost is already swapped out, to avoid swapping it
635 // out again.
636 if (!render_frame_host->is_swapped_out())
637 render_frame_host->SwapOut(proxy, false);
639 if (frame_tree_node_->IsMainFrame())
640 proxy->TakeFrameHostOwnership(render_frame_host.Pass());
641 } else {
642 // We won't be coming back, so delete this one.
643 render_frame_host.reset();
647 void RenderFrameHostManager::MoveToPendingDeleteHosts(
648 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
649 // |render_frame_host| will be deleted when its SwapOut ACK is received, or
650 // when the timer times out, or when the RFHM itself is deleted (whichever
651 // comes first).
652 pending_delete_hosts_.push_back(
653 linked_ptr<RenderFrameHostImpl>(render_frame_host.release()));
656 bool RenderFrameHostManager::IsPendingDeletion(
657 RenderFrameHostImpl* render_frame_host) {
658 for (const auto& rfh : pending_delete_hosts_) {
659 if (rfh == render_frame_host)
660 return true;
662 return false;
665 bool RenderFrameHostManager::DeleteFromPendingList(
666 RenderFrameHostImpl* render_frame_host) {
667 for (RFHPendingDeleteList::iterator iter = pending_delete_hosts_.begin();
668 iter != pending_delete_hosts_.end();
669 iter++) {
670 if (*iter == render_frame_host) {
671 pending_delete_hosts_.erase(iter);
672 return true;
675 return false;
678 void RenderFrameHostManager::ResetProxyHosts() {
679 STLDeleteValues(&proxy_hosts_);
682 // PlzNavigate
683 void RenderFrameHostManager::BeginNavigation(const NavigationRequest& request) {
684 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
685 switches::kEnableBrowserSideNavigation));
686 // Clean up any state in case there's an ongoing navigation.
687 // TODO(carlosk): remove this cleanup here once we properly cancel ongoing
688 // navigations.
689 CleanUpNavigation();
691 RenderFrameHostImpl* dest_rfh = GetFrameHostForNavigation(request);
692 DCHECK(dest_rfh);
695 // PlzNavigate
696 RenderFrameHostImpl* RenderFrameHostManager::GetFrameHostForNavigation(
697 const NavigationRequest& request) {
698 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
699 switches::kEnableBrowserSideNavigation));
701 SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance();
703 scoped_refptr<SiteInstance> dest_site_instance = GetSiteInstanceForNavigation(
704 request.common_params().url, request.source_site_instance(),
705 request.dest_site_instance(), request.common_params().transition,
706 request.restore_type() != NavigationEntryImpl::RESTORE_NONE,
707 request.is_view_source());
708 // The appropriate RenderFrameHost to commit the navigation.
709 RenderFrameHostImpl* navigation_rfh = nullptr;
711 // TODO(carlosk): do not swap processes for renderer initiated navigations
712 // (see crbug.com/440266).
713 if (current_site_instance == dest_site_instance.get() ||
714 (!frame_tree_node_->IsMainFrame() &&
715 !base::CommandLine::ForCurrentProcess()->HasSwitch(
716 switches::kSitePerProcess))) {
717 // Reuse the current RFH if its SiteInstance matches the the navigation's
718 // or if this is a subframe navigation. We only swap RFHs for subframes when
719 // --site-per-process is enabled.
720 CleanUpNavigation();
721 navigation_rfh = render_frame_host_.get();
723 // As SiteInstances are the same, check if the WebUI should be reused.
724 const NavigationEntry* current_navigation_entry =
725 delegate_->GetLastCommittedNavigationEntryForRenderManager();
726 bool should_reuse_web_ui_ = ShouldReuseWebUI(current_navigation_entry,
727 request.common_params().url);
728 if (!should_reuse_web_ui_) {
729 speculative_web_ui_ = CreateWebUI(request.common_params().url,
730 request.bindings());
731 // Make sure the current RenderViewHost has the right bindings.
732 if (speculative_web_ui() &&
733 !render_frame_host_->GetProcess()->IsIsolatedGuest()) {
734 render_frame_host_->render_view_host()->AllowBindings(
735 speculative_web_ui()->GetBindings());
738 } else {
739 // If the SiteInstance for the final URL doesn't match the one from the
740 // speculatively created RenderFrameHost, create a new RenderFrameHost using
741 // this new SiteInstance.
742 if (!speculative_render_frame_host_ ||
743 speculative_render_frame_host_->GetSiteInstance() !=
744 dest_site_instance.get()) {
745 CleanUpNavigation();
746 bool success = CreateSpeculativeRenderFrameHost(
747 request.common_params().url, current_site_instance,
748 dest_site_instance.get(), request.bindings());
749 DCHECK(success);
751 DCHECK(speculative_render_frame_host_);
752 navigation_rfh = speculative_render_frame_host_.get();
754 // Check if our current RFH is live.
755 if (!render_frame_host_->IsRenderFrameLive()) {
756 // The current RFH is not live. There's no reason to sit around with a
757 // sad tab or a newly created RFH while we wait for the navigation to
758 // complete. Just switch to the speculative RFH now and go back to non
759 // cross-navigating (Note that we don't care about on{before}unload
760 // handlers if the current RFH isn't live.)
761 CommitPending();
764 DCHECK(navigation_rfh &&
765 (navigation_rfh == render_frame_host_.get() ||
766 navigation_rfh == speculative_render_frame_host_.get()));
768 // If the RenderFrame that needs to navigate is not live (its process was just
769 // created or has crashed), initialize it.
770 if (!navigation_rfh->IsRenderFrameLive()) {
771 // Recreate the opener chain.
772 int opener_route_id = delegate_->CreateOpenerRenderViewsForRenderManager(
773 navigation_rfh->GetSiteInstance());
774 if (!InitRenderView(navigation_rfh->render_view_host(), opener_route_id,
775 MSG_ROUTING_NONE, frame_tree_node_->IsMainFrame())) {
776 return nullptr;
780 cross_navigation_pending_ = navigation_rfh != render_frame_host_.get();
781 return navigation_rfh;
784 // PlzNavigate
785 void RenderFrameHostManager::CleanUpNavigation() {
786 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
787 switches::kEnableBrowserSideNavigation));
788 speculative_web_ui_.reset();
789 should_reuse_web_ui_ = false;
790 if (speculative_render_frame_host_)
791 DiscardUnusedFrame(UnsetSpeculativeRenderFrameHost());
794 // PlzNavigate
795 scoped_ptr<RenderFrameHostImpl>
796 RenderFrameHostManager::UnsetSpeculativeRenderFrameHost() {
797 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
798 switches::kEnableBrowserSideNavigation));
799 speculative_render_frame_host_->GetProcess()->RemovePendingView();
800 return speculative_render_frame_host_.Pass();
803 void RenderFrameHostManager::OnDidStartLoading() {
804 for (const auto& pair : proxy_hosts_) {
805 pair.second->Send(
806 new FrameMsg_DidStartLoading(pair.second->GetRoutingID()));
810 void RenderFrameHostManager::OnDidStopLoading() {
811 for (const auto& pair : proxy_hosts_) {
812 pair.second->Send(new FrameMsg_DidStopLoading(pair.second->GetRoutingID()));
816 void RenderFrameHostManager::Observe(
817 int type,
818 const NotificationSource& source,
819 const NotificationDetails& details) {
820 switch (type) {
821 case NOTIFICATION_RENDERER_PROCESS_CLOSED:
822 case NOTIFICATION_RENDERER_PROCESS_CLOSING:
823 RendererProcessClosing(
824 Source<RenderProcessHost>(source).ptr());
825 break;
827 default:
828 NOTREACHED();
832 // static
833 bool RenderFrameHostManager::ClearProxiesInSiteInstance(
834 int32 site_instance_id,
835 FrameTreeNode* node) {
836 RenderFrameProxyHostMap::iterator iter =
837 node->render_manager()->proxy_hosts_.find(site_instance_id);
838 if (iter != node->render_manager()->proxy_hosts_.end()) {
839 RenderFrameProxyHost* proxy = iter->second;
840 // Delete the proxy. If it is for a main frame (and thus the RFH is stored
841 // in the proxy) and it was still pending swap out, move the RFH to the
842 // pending deletion list first.
843 if (node->IsMainFrame() &&
844 proxy->render_frame_host()->rfh_state() ==
845 RenderFrameHostImpl::STATE_PENDING_SWAP_OUT) {
846 scoped_ptr<RenderFrameHostImpl> swapped_out_rfh =
847 proxy->PassFrameHostOwnership();
848 node->render_manager()->MoveToPendingDeleteHosts(swapped_out_rfh.Pass());
850 delete proxy;
851 node->render_manager()->proxy_hosts_.erase(site_instance_id);
854 return true;
857 // static.
858 bool RenderFrameHostManager::ResetProxiesInSiteInstance(int32 site_instance_id,
859 FrameTreeNode* node) {
860 RenderFrameProxyHostMap::iterator iter =
861 node->render_manager()->proxy_hosts_.find(site_instance_id);
862 if (iter != node->render_manager()->proxy_hosts_.end())
863 iter->second->set_render_frame_proxy_created(false);
865 return true;
868 bool RenderFrameHostManager::ShouldTransitionCrossSite() {
869 // True for --site-per-process, which overrides both kSingleProcess and
870 // kProcessPerTab.
871 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
872 switches::kSitePerProcess))
873 return true;
875 // False in the single-process mode, as it makes RVHs to accumulate
876 // in swapped_out_hosts_.
877 // True if we are using process-per-site-instance (default) or
878 // process-per-site (kProcessPerSite).
879 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
880 switches::kSingleProcess) &&
881 !base::CommandLine::ForCurrentProcess()->HasSwitch(
882 switches::kProcessPerTab);
885 bool RenderFrameHostManager::ShouldSwapBrowsingInstancesForNavigation(
886 const GURL& current_effective_url,
887 bool current_is_view_source_mode,
888 SiteInstance* new_site_instance,
889 const GURL& new_effective_url,
890 bool new_is_view_source_mode) const {
891 // If new_entry already has a SiteInstance, assume it is correct. We only
892 // need to force a swap if it is in a different BrowsingInstance.
893 if (new_site_instance) {
894 return !new_site_instance->IsRelatedSiteInstance(
895 render_frame_host_->GetSiteInstance());
898 // Check for reasons to swap processes even if we are in a process model that
899 // doesn't usually swap (e.g., process-per-tab). Any time we return true,
900 // the new_entry will be rendered in a new SiteInstance AND BrowsingInstance.
901 BrowserContext* browser_context =
902 delegate_->GetControllerForRenderManager().GetBrowserContext();
904 // Don't force a new BrowsingInstance for debug URLs that are handled in the
905 // renderer process, like javascript: or chrome://crash.
906 if (IsRendererDebugURL(new_effective_url))
907 return false;
909 // For security, we should transition between processes when one is a Web UI
910 // page and one isn't.
911 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
912 render_frame_host_->GetProcess()->GetID()) ||
913 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
914 browser_context, current_effective_url)) {
915 // If so, force a swap if destination is not an acceptable URL for Web UI.
916 // Here, data URLs are never allowed.
917 if (!WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
918 browser_context, new_effective_url)) {
919 return true;
921 } else {
922 // Force a swap if it's a Web UI URL.
923 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
924 browser_context, new_effective_url)) {
925 return true;
929 // Check with the content client as well. Important to pass
930 // current_effective_url here, which uses the SiteInstance's site if there is
931 // no current_entry.
932 if (GetContentClient()->browser()->ShouldSwapBrowsingInstancesForNavigation(
933 render_frame_host_->GetSiteInstance(),
934 current_effective_url, new_effective_url)) {
935 return true;
938 // We can't switch a RenderView between view source and non-view source mode
939 // without screwing up the session history sometimes (when navigating between
940 // "view-source:http://foo.com/" and "http://foo.com/", Blink doesn't treat
941 // it as a new navigation). So require a BrowsingInstance switch.
942 if (current_is_view_source_mode != new_is_view_source_mode)
943 return true;
945 return false;
948 bool RenderFrameHostManager::ShouldReuseWebUI(
949 const NavigationEntry* current_entry,
950 const GURL& new_url) const {
951 NavigationControllerImpl& controller =
952 delegate_->GetControllerForRenderManager();
953 return current_entry && web_ui_.get() &&
954 (WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
955 controller.GetBrowserContext(), current_entry->GetURL()) ==
956 WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
957 controller.GetBrowserContext(), new_url));
960 SiteInstance* RenderFrameHostManager::GetSiteInstanceForNavigation(
961 const GURL& dest_url,
962 SiteInstance* source_instance,
963 SiteInstance* dest_instance,
964 ui::PageTransition transition,
965 bool dest_is_restore,
966 bool dest_is_view_source_mode) {
967 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
968 SiteInstance* new_instance = current_instance;
970 // We do not currently swap processes for navigations in webview tag guests.
971 if (current_instance->GetSiteURL().SchemeIs(kGuestScheme))
972 return current_instance;
974 // Determine if we need a new BrowsingInstance for this entry. If true, this
975 // implies that it will get a new SiteInstance (and likely process), and that
976 // other tabs in the current BrowsingInstance will be unable to script it.
977 // This is used for cases that require a process swap even in the
978 // process-per-tab model, such as WebUI pages.
979 // TODO(clamy): Remove the dependency on the current entry.
980 const NavigationEntry* current_entry =
981 delegate_->GetLastCommittedNavigationEntryForRenderManager();
982 BrowserContext* browser_context =
983 delegate_->GetControllerForRenderManager().GetBrowserContext();
984 const GURL& current_effective_url = current_entry ?
985 SiteInstanceImpl::GetEffectiveURL(browser_context,
986 current_entry->GetURL()) :
987 render_frame_host_->GetSiteInstance()->GetSiteURL();
988 bool current_is_view_source_mode = current_entry ?
989 current_entry->IsViewSourceMode() : dest_is_view_source_mode;
990 bool force_swap = ShouldSwapBrowsingInstancesForNavigation(
991 current_effective_url,
992 current_is_view_source_mode,
993 dest_instance,
994 SiteInstanceImpl::GetEffectiveURL(browser_context, dest_url),
995 dest_is_view_source_mode);
996 if (ShouldTransitionCrossSite() || force_swap) {
997 new_instance = GetSiteInstanceForURL(
998 dest_url, source_instance, current_instance, dest_instance,
999 transition, dest_is_restore, dest_is_view_source_mode, force_swap);
1002 // If force_swap is true, we must use a different SiteInstance. If we didn't,
1003 // we would have two RenderFrameHosts in the same SiteInstance and the same
1004 // frame, resulting in page_id conflicts for their NavigationEntries.
1005 if (force_swap)
1006 CHECK_NE(new_instance, current_instance);
1007 return new_instance;
1010 SiteInstance* RenderFrameHostManager::GetSiteInstanceForURL(
1011 const GURL& dest_url,
1012 SiteInstance* source_instance,
1013 SiteInstance* current_instance,
1014 SiteInstance* dest_instance,
1015 ui::PageTransition transition,
1016 bool dest_is_restore,
1017 bool dest_is_view_source_mode,
1018 bool force_browsing_instance_swap) {
1019 NavigationControllerImpl& controller =
1020 delegate_->GetControllerForRenderManager();
1021 BrowserContext* browser_context = controller.GetBrowserContext();
1023 // If the entry has an instance already we should use it.
1024 if (dest_instance) {
1025 // If we are forcing a swap, this should be in a different BrowsingInstance.
1026 if (force_browsing_instance_swap) {
1027 CHECK(!dest_instance->IsRelatedSiteInstance(
1028 render_frame_host_->GetSiteInstance()));
1030 return dest_instance;
1033 // If a swap is required, we need to force the SiteInstance AND
1034 // BrowsingInstance to be different ones, using CreateForURL.
1035 if (force_browsing_instance_swap)
1036 return SiteInstance::CreateForURL(browser_context, dest_url);
1038 // (UGLY) HEURISTIC, process-per-site only:
1040 // If this navigation is generated, then it probably corresponds to a search
1041 // query. Given that search results typically lead to users navigating to
1042 // other sites, we don't really want to use the search engine hostname to
1043 // determine the site instance for this navigation.
1045 // NOTE: This can be removed once we have a way to transition between
1046 // RenderViews in response to a link click.
1048 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1049 switches::kProcessPerSite) &&
1050 ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_GENERATED)) {
1051 return current_instance;
1054 SiteInstanceImpl* current_site_instance =
1055 static_cast<SiteInstanceImpl*>(current_instance);
1057 // If we haven't used our SiteInstance (and thus RVH) yet, then we can use it
1058 // for this entry. We won't commit the SiteInstance to this site until the
1059 // navigation commits (in DidNavigate), unless the navigation entry was
1060 // restored or it's a Web UI as described below.
1061 if (!current_site_instance->HasSite()) {
1062 // If we've already created a SiteInstance for our destination, we don't
1063 // want to use this unused SiteInstance; use the existing one. (We don't
1064 // do this check if the current_instance has a site, because for now, we
1065 // want to compare against the current URL and not the SiteInstance's site.
1066 // In this case, there is no current URL, so comparing against the site is
1067 // ok. See additional comments below.)
1069 // Also, if the URL should use process-per-site mode and there is an
1070 // existing process for the site, we should use it. We can call
1071 // GetRelatedSiteInstance() for this, which will eagerly set the site and
1072 // thus use the correct process.
1073 bool use_process_per_site =
1074 RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) &&
1075 RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url);
1076 if (current_site_instance->HasRelatedSiteInstance(dest_url) ||
1077 use_process_per_site) {
1078 return current_site_instance->GetRelatedSiteInstance(dest_url);
1081 // For extensions, Web UI URLs (such as the new tab page), and apps we do
1082 // not want to use the current_instance if it has no site, since it will
1083 // have a RenderProcessHost of PRIV_NORMAL. Create a new SiteInstance for
1084 // this URL instead (with the correct process type).
1085 if (current_site_instance->HasWrongProcessForURL(dest_url))
1086 return current_site_instance->GetRelatedSiteInstance(dest_url);
1088 // View-source URLs must use a new SiteInstance and BrowsingInstance.
1089 // TODO(nasko): This is the same condition as later in the function. This
1090 // should be taken into account when refactoring this method as part of
1091 // http://crbug.com/123007.
1092 if (dest_is_view_source_mode)
1093 return SiteInstance::CreateForURL(browser_context, dest_url);
1095 // If we are navigating from a blank SiteInstance to a WebUI, make sure we
1096 // create a new SiteInstance.
1097 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1098 browser_context, dest_url)) {
1099 return SiteInstance::CreateForURL(browser_context, dest_url);
1102 // Normally the "site" on the SiteInstance is set lazily when the load
1103 // actually commits. This is to support better process sharing in case
1104 // the site redirects to some other site: we want to use the destination
1105 // site in the site instance.
1107 // In the case of session restore, as it loads all the pages immediately
1108 // we need to set the site first, otherwise after a restore none of the
1109 // pages would share renderers in process-per-site.
1111 // The embedder can request some urls never to be assigned to SiteInstance
1112 // through the ShouldAssignSiteForURL() content client method, so that
1113 // renderers created for particular chrome urls (e.g. the chrome-native://
1114 // scheme) can be reused for subsequent navigations in the same WebContents.
1115 // See http://crbug.com/386542.
1116 if (dest_is_restore &&
1117 GetContentClient()->browser()->ShouldAssignSiteForURL(dest_url)) {
1118 current_site_instance->SetSite(dest_url);
1121 return current_site_instance;
1124 // Otherwise, only create a new SiteInstance for a cross-site navigation.
1126 // TODO(creis): Once we intercept links and script-based navigations, we
1127 // will be able to enforce that all entries in a SiteInstance actually have
1128 // the same site, and it will be safe to compare the URL against the
1129 // SiteInstance's site, as follows:
1130 // const GURL& current_url = current_instance->site();
1131 // For now, though, we're in a hybrid model where you only switch
1132 // SiteInstances if you type in a cross-site URL. This means we have to
1133 // compare the entry's URL to the last committed entry's URL.
1134 NavigationEntry* current_entry = controller.GetLastCommittedEntry();
1135 if (interstitial_page_) {
1136 // The interstitial is currently the last committed entry, but we want to
1137 // compare against the last non-interstitial entry.
1138 current_entry = controller.GetEntryAtOffset(-1);
1141 // View-source URLs must use a new SiteInstance and BrowsingInstance.
1142 // We don't need a swap when going from view-source to a debug URL like
1143 // chrome://crash, however.
1144 // TODO(creis): Refactor this method so this duplicated code isn't needed.
1145 // See http://crbug.com/123007.
1146 if (current_entry &&
1147 current_entry->IsViewSourceMode() != dest_is_view_source_mode &&
1148 !IsRendererDebugURL(dest_url)) {
1149 return SiteInstance::CreateForURL(browser_context, dest_url);
1152 // Use the source SiteInstance in case of data URLs or about:blank pages,
1153 // because the content is then controlled and/or scriptable by the source
1154 // SiteInstance.
1155 GURL about_blank(url::kAboutBlankURL);
1156 if (source_instance &&
1157 (dest_url == about_blank || dest_url.scheme() == url::kDataScheme))
1158 return source_instance;
1160 // Use the current SiteInstance for same site navigations, as long as the
1161 // process type is correct. (The URL may have been installed as an app since
1162 // the last time we visited it.)
1163 const GURL& current_url =
1164 GetCurrentURLForSiteInstance(current_instance, current_entry);
1165 if (SiteInstance::IsSameWebSite(browser_context, current_url, dest_url) &&
1166 !current_site_instance->HasWrongProcessForURL(dest_url)) {
1167 return current_instance;
1170 // Start the new renderer in a new SiteInstance, but in the current
1171 // BrowsingInstance. It is important to immediately give this new
1172 // SiteInstance to a RenderViewHost (if it is different than our current
1173 // SiteInstance), so that it is ref counted. This will happen in
1174 // CreateRenderView.
1175 return current_instance->GetRelatedSiteInstance(dest_url);
1178 const GURL& RenderFrameHostManager::GetCurrentURLForSiteInstance(
1179 SiteInstance* current_instance, NavigationEntry* current_entry) {
1180 // If this is a subframe that is potentially out of process from its parent,
1181 // don't consider using current_entry's url for SiteInstance selection, since
1182 // current_entry's url is for the main frame and may be in a different site
1183 // than this frame.
1184 // TODO(creis): Remove this when we can check the FrameNavigationEntry's url.
1185 // See http://crbug.com/369654
1186 if (!frame_tree_node_->IsMainFrame() &&
1187 base::CommandLine::ForCurrentProcess()->HasSwitch(
1188 switches::kSitePerProcess))
1189 return frame_tree_node_->current_url();
1191 // If there is no last non-interstitial entry (and current_instance already
1192 // has a site), then we must have been opened from another tab. We want
1193 // to compare against the URL of the page that opened us, but we can't
1194 // get to it directly. The best we can do is check against the site of
1195 // the SiteInstance. This will be correct when we intercept links and
1196 // script-based navigations, but for now, it could place some pages in a
1197 // new process unnecessarily. We should only hit this case if a page tries
1198 // to open a new tab to an interstitial-inducing URL, and then navigates
1199 // the page to a different same-site URL. (This seems very unlikely in
1200 // practice.)
1201 if (current_entry)
1202 return current_entry->GetURL();
1203 return current_instance->GetSiteURL();
1206 void RenderFrameHostManager::CreatePendingRenderFrameHost(
1207 SiteInstance* old_instance,
1208 SiteInstance* new_instance,
1209 bool is_main_frame) {
1210 int create_render_frame_flags = 0;
1211 if (is_main_frame)
1212 create_render_frame_flags |= CREATE_RF_FOR_MAIN_FRAME_NAVIGATION;
1214 if (delegate_->IsHidden())
1215 create_render_frame_flags |= CREATE_RF_HIDDEN;
1217 int opener_route_id = CreateOpenerRenderViewsIfNeeded(
1218 old_instance, new_instance, &create_render_frame_flags);
1220 if (pending_render_frame_host_)
1221 CancelPending();
1223 // Create a non-swapped-out RFH with the given opener.
1224 pending_render_frame_host_ =
1225 CreateRenderFrame(new_instance, pending_web_ui(), opener_route_id,
1226 create_render_frame_flags, nullptr);
1229 int RenderFrameHostManager::CreateOpenerRenderViewsIfNeeded(
1230 SiteInstance* old_instance,
1231 SiteInstance* new_instance,
1232 int* create_render_frame_flags) {
1233 int opener_route_id = MSG_ROUTING_NONE;
1234 if (new_instance->IsRelatedSiteInstance(old_instance)) {
1235 opener_route_id =
1236 delegate_->CreateOpenerRenderViewsForRenderManager(new_instance);
1237 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1238 switches::kSitePerProcess)) {
1239 // Ensure that the frame tree has RenderFrameProxyHosts for the new
1240 // SiteInstance in all nodes except the current one.
1241 frame_tree_node_->frame_tree()->CreateProxiesForSiteInstance(
1242 frame_tree_node_, new_instance);
1243 // RenderFrames in different processes from their parent RenderFrames
1244 // in the frame tree require RenderWidgets for rendering and processing
1245 // input events.
1246 if (frame_tree_node_->parent() &&
1247 frame_tree_node_->parent()->current_frame_host()->GetSiteInstance() !=
1248 new_instance)
1249 *create_render_frame_flags |= CREATE_RF_NEEDS_RENDER_WIDGET_HOST;
1252 return opener_route_id;
1255 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::CreateRenderFrameHost(
1256 SiteInstance* site_instance,
1257 int view_routing_id,
1258 int frame_routing_id,
1259 int flags) {
1260 if (frame_routing_id == MSG_ROUTING_NONE)
1261 frame_routing_id = site_instance->GetProcess()->GetNextRoutingID();
1263 bool swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
1264 bool hidden = !!(flags & CREATE_RF_HIDDEN);
1266 // Create a RVH for main frames, or find the existing one for subframes.
1267 FrameTree* frame_tree = frame_tree_node_->frame_tree();
1268 RenderViewHostImpl* render_view_host = nullptr;
1269 if (frame_tree_node_->IsMainFrame()) {
1270 render_view_host = frame_tree->CreateRenderViewHost(
1271 site_instance, view_routing_id, frame_routing_id, swapped_out, hidden);
1272 } else {
1273 render_view_host = frame_tree->GetRenderViewHost(site_instance);
1275 CHECK(render_view_host);
1278 // TODO(creis): Pass hidden to RFH.
1279 scoped_ptr<RenderFrameHostImpl> render_frame_host = make_scoped_ptr(
1280 RenderFrameHostFactory::Create(
1281 site_instance, render_view_host, render_frame_delegate_,
1282 render_widget_delegate_, frame_tree, frame_tree_node_,
1283 frame_routing_id, flags).release());
1284 return render_frame_host.Pass();
1287 // PlzNavigate
1288 bool RenderFrameHostManager::CreateSpeculativeRenderFrameHost(
1289 const GURL& url,
1290 SiteInstance* old_instance,
1291 SiteInstance* new_instance,
1292 int bindings) {
1293 CHECK(new_instance);
1294 CHECK_NE(old_instance, new_instance);
1295 CHECK(!should_reuse_web_ui_);
1297 // Note: |speculative_web_ui_| must be initialized before starting the
1298 // |speculative_render_frame_host_| creation steps otherwise the WebUI
1299 // won't be properly initialized.
1300 speculative_web_ui_ = CreateWebUI(url, bindings);
1302 int create_render_frame_flags = 0;
1303 int opener_route_id =
1304 CreateOpenerRenderViewsIfNeeded(old_instance, new_instance,
1305 &create_render_frame_flags);
1307 if (frame_tree_node_->IsMainFrame())
1308 create_render_frame_flags |= CREATE_RF_FOR_MAIN_FRAME_NAVIGATION;
1309 if (delegate_->IsHidden())
1310 create_render_frame_flags |= CREATE_RF_HIDDEN;
1311 speculative_render_frame_host_ =
1312 CreateRenderFrame(new_instance, speculative_web_ui_.get(),
1313 opener_route_id, create_render_frame_flags, nullptr);
1315 if (!speculative_render_frame_host_) {
1316 speculative_web_ui_.reset();
1317 return false;
1319 return true;
1322 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::CreateRenderFrame(
1323 SiteInstance* instance,
1324 WebUIImpl* web_ui,
1325 int opener_route_id,
1326 int flags,
1327 int* view_routing_id_ptr) {
1328 bool swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
1329 CHECK(instance);
1330 // Swapped out views should always be hidden.
1331 DCHECK(!swapped_out || (flags & CREATE_RF_HIDDEN));
1333 // TODO(nasko): Remove the following CHECK once cross-site navigation no
1334 // longer relies on swapped out RFH for the top-level frame.
1335 if (!frame_tree_node_->IsMainFrame())
1336 CHECK(!swapped_out);
1338 scoped_ptr<RenderFrameHostImpl> new_render_frame_host;
1339 bool success = true;
1340 if (view_routing_id_ptr)
1341 *view_routing_id_ptr = MSG_ROUTING_NONE;
1343 // We are creating a pending, speculative or swapped out RFH here. We should
1344 // never create it in the same SiteInstance as our current RFH.
1345 CHECK_NE(render_frame_host_->GetSiteInstance(), instance);
1347 // Check if we've already created an RFH for this SiteInstance. If so, try
1348 // to re-use the existing one, which has already been initialized. We'll
1349 // remove it from the list of proxy hosts below if it will be active.
1350 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1351 if (proxy && proxy->render_frame_host()) {
1352 if (view_routing_id_ptr)
1353 *view_routing_id_ptr = proxy->GetRenderViewHost()->GetRoutingID();
1354 // Delete the existing RenderFrameProxyHost, but reuse the RenderFrameHost.
1355 // Prevent the process from exiting while we're trying to use it.
1356 if (!swapped_out) {
1357 new_render_frame_host = proxy->PassFrameHostOwnership();
1358 new_render_frame_host->GetProcess()->AddPendingView();
1360 proxy_hosts_.erase(instance->GetId());
1361 delete proxy;
1363 // When a new render view is created by the renderer, the new WebContents
1364 // gets a RenderViewHost in the SiteInstance of its opener WebContents.
1365 // If not used in the first navigation, this RVH is swapped out and is not
1366 // granted bindings, so we may need to grant them when swapping it in.
1367 if (web_ui && !new_render_frame_host->GetProcess()->IsIsolatedGuest()) {
1368 int required_bindings = web_ui->GetBindings();
1369 RenderViewHost* render_view_host =
1370 new_render_frame_host->render_view_host();
1371 if ((render_view_host->GetEnabledBindings() & required_bindings) !=
1372 required_bindings) {
1373 render_view_host->AllowBindings(required_bindings);
1377 } else {
1378 // Create a new RenderFrameHost if we don't find an existing one.
1379 new_render_frame_host = CreateRenderFrameHost(instance, MSG_ROUTING_NONE,
1380 MSG_ROUTING_NONE, flags);
1381 RenderViewHostImpl* render_view_host =
1382 new_render_frame_host->render_view_host();
1383 int proxy_routing_id = MSG_ROUTING_NONE;
1385 // Prevent the process from exiting while we're trying to navigate in it.
1386 // Otherwise, if the new RFH is swapped out already, store it.
1387 if (!swapped_out) {
1388 new_render_frame_host->GetProcess()->AddPendingView();
1389 } else {
1390 proxy = new RenderFrameProxyHost(
1391 new_render_frame_host->GetSiteInstance(), frame_tree_node_);
1392 proxy_hosts_[instance->GetId()] = proxy;
1393 proxy_routing_id = proxy->GetRoutingID();
1394 proxy->TakeFrameHostOwnership(new_render_frame_host.Pass());
1397 success =
1398 InitRenderView(render_view_host, opener_route_id, proxy_routing_id,
1399 !!(flags & CREATE_RF_FOR_MAIN_FRAME_NAVIGATION));
1400 if (success) {
1401 if (frame_tree_node_->IsMainFrame()) {
1402 // Don't show the main frame's view until we get a DidNavigate from it.
1403 // Only the RenderViewHost for the top-level RenderFrameHost has a
1404 // RenderWidgetHostView; RenderWidgetHosts for out-of-process iframes
1405 // will be created later and hidden.
1406 if (render_view_host->GetView())
1407 render_view_host->GetView()->Hide();
1408 } else if (!swapped_out) {
1409 // Init the RFH, so a RenderFrame is created in the renderer.
1410 DCHECK(new_render_frame_host.get());
1411 success = InitRenderFrame(new_render_frame_host.get());
1415 if (success) {
1416 if (view_routing_id_ptr)
1417 *view_routing_id_ptr = render_view_host->GetRoutingID();
1421 // Returns the new RFH if it isn't swapped out.
1422 if (success && !swapped_out) {
1423 DCHECK(new_render_frame_host->GetSiteInstance() == instance);
1424 return new_render_frame_host.Pass();
1426 return nullptr;
1429 int RenderFrameHostManager::CreateRenderFrameProxy(SiteInstance* instance) {
1430 // A RenderFrameProxyHost should never be created in the same SiteInstance as
1431 // the current RFH.
1432 CHECK(instance);
1433 CHECK_NE(instance, render_frame_host_->GetSiteInstance());
1435 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1436 if (proxy)
1437 return proxy->GetRoutingID();
1439 proxy = new RenderFrameProxyHost(instance, frame_tree_node_);
1440 proxy_hosts_[instance->GetId()] = proxy;
1441 proxy->InitRenderFrameProxy();
1442 return proxy->GetRoutingID();
1445 void RenderFrameHostManager::EnsureRenderViewInitialized(
1446 FrameTreeNode* source,
1447 RenderViewHostImpl* render_view_host,
1448 SiteInstance* instance) {
1449 DCHECK(frame_tree_node_->IsMainFrame());
1451 if (render_view_host->IsRenderViewLive())
1452 return;
1454 // Recreate the opener chain.
1455 int opener_route_id =
1456 delegate_->CreateOpenerRenderViewsForRenderManager(instance);
1457 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1458 InitRenderView(render_view_host, opener_route_id, proxy->GetRoutingID(),
1459 source->IsMainFrame());
1462 bool RenderFrameHostManager::InitRenderView(
1463 RenderViewHostImpl* render_view_host,
1464 int opener_route_id,
1465 int proxy_routing_id,
1466 bool for_main_frame_navigation) {
1467 // We may have initialized this RenderViewHost for another RenderFrameHost.
1468 if (render_view_host->IsRenderViewLive())
1469 return true;
1471 // If the ongoing navigation is to a WebUI and the RenderView is not in a
1472 // guest process, tell the RenderViewHost about any bindings it will need
1473 // enabled.
1474 WebUIImpl* dest_web_ui = nullptr;
1475 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1476 switches::kEnableBrowserSideNavigation)) {
1477 dest_web_ui =
1478 should_reuse_web_ui_ ? web_ui_.get() : speculative_web_ui_.get();
1479 } else {
1480 dest_web_ui = pending_web_ui();
1482 if (dest_web_ui && !render_view_host->GetProcess()->IsIsolatedGuest()) {
1483 render_view_host->AllowBindings(dest_web_ui->GetBindings());
1484 } else {
1485 // Ensure that we don't create an unprivileged RenderView in a WebUI-enabled
1486 // process unless it's swapped out.
1487 if (render_view_host->is_active()) {
1488 CHECK(!ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1489 render_view_host->GetProcess()->GetID()));
1493 return delegate_->CreateRenderViewForRenderManager(render_view_host,
1494 opener_route_id,
1495 proxy_routing_id,
1496 for_main_frame_navigation);
1499 bool RenderFrameHostManager::InitRenderFrame(
1500 RenderFrameHostImpl* render_frame_host) {
1501 if (render_frame_host->IsRenderFrameLive())
1502 return true;
1504 int parent_routing_id = MSG_ROUTING_NONE;
1505 int proxy_routing_id = MSG_ROUTING_NONE;
1506 if (frame_tree_node_->parent()) {
1507 parent_routing_id = frame_tree_node_->parent()->render_manager()->
1508 GetRoutingIdForSiteInstance(render_frame_host->GetSiteInstance());
1509 CHECK_NE(parent_routing_id, MSG_ROUTING_NONE);
1511 // Check whether there is an existing proxy for this frame in this
1512 // SiteInstance. If there is, the new RenderFrame needs to be able to find
1513 // the proxy it is replacing, so that it can fully initialize itself.
1514 // NOTE: This is the only time that a RenderFrameProxyHost can be in the same
1515 // SiteInstance as its RenderFrameHost. This is only the case until the
1516 // RenderFrameHost commits, at which point it will replace and delete the
1517 // RenderFrameProxyHost.
1518 RenderFrameProxyHost* existing_proxy =
1519 GetRenderFrameProxyHost(render_frame_host->GetSiteInstance());
1520 if (existing_proxy) {
1521 proxy_routing_id = existing_proxy->GetRoutingID();
1522 CHECK_NE(proxy_routing_id, MSG_ROUTING_NONE);
1523 if (!existing_proxy->is_render_frame_proxy_live())
1524 existing_proxy->InitRenderFrameProxy();
1526 return delegate_->CreateRenderFrameForRenderManager(render_frame_host,
1527 parent_routing_id,
1528 proxy_routing_id);
1531 int RenderFrameHostManager::GetRoutingIdForSiteInstance(
1532 SiteInstance* site_instance) {
1533 if (render_frame_host_->GetSiteInstance() == site_instance)
1534 return render_frame_host_->GetRoutingID();
1536 RenderFrameProxyHostMap::iterator iter =
1537 proxy_hosts_.find(site_instance->GetId());
1538 if (iter != proxy_hosts_.end())
1539 return iter->second->GetRoutingID();
1541 return MSG_ROUTING_NONE;
1544 void RenderFrameHostManager::CommitPending() {
1545 TRACE_EVENT1("navigation", "RenderFrameHostManager::CommitPending",
1546 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
1547 bool browser_side_navigation =
1548 base::CommandLine::ForCurrentProcess()->HasSwitch(
1549 switches::kEnableBrowserSideNavigation);
1550 // First check whether we're going to want to focus the location bar after
1551 // this commit. We do this now because the navigation hasn't formally
1552 // committed yet, so if we've already cleared |pending_web_ui_| the call chain
1553 // this triggers won't be able to figure out what's going on.
1554 bool will_focus_location_bar = delegate_->FocusLocationBarByDefault();
1556 if (!browser_side_navigation) {
1557 DCHECK(!speculative_web_ui_);
1558 // Next commit the Web UI, if any. Either replace |web_ui_| with
1559 // |pending_web_ui_|, or clear |web_ui_| if there is no pending WebUI, or
1560 // leave |web_ui_| as is if reusing it.
1561 DCHECK(!(pending_web_ui_.get() && pending_and_current_web_ui_.get()));
1562 if (pending_web_ui_) {
1563 web_ui_.reset(pending_web_ui_.release());
1564 } else if (!pending_and_current_web_ui_.get()) {
1565 web_ui_.reset();
1566 } else {
1567 DCHECK_EQ(pending_and_current_web_ui_.get(), web_ui_.get());
1568 pending_and_current_web_ui_.reset();
1570 } else {
1571 // PlzNavigate
1572 if (!should_reuse_web_ui_)
1573 web_ui_.reset(speculative_web_ui_.release());
1574 DCHECK(!speculative_web_ui_);
1577 // It's possible for the pending_render_frame_host_ to be nullptr when we
1578 // aren't crossing process boundaries. If so, we just needed to handle the Web
1579 // UI committing above and we're done.
1580 if (!pending_render_frame_host_ && !speculative_render_frame_host_) {
1581 if (will_focus_location_bar)
1582 delegate_->SetFocusToLocationBar(false);
1583 return;
1586 // Remember if the page was focused so we can focus the new renderer in
1587 // that case.
1588 bool focus_render_view = !will_focus_location_bar &&
1589 render_frame_host_->GetView() &&
1590 render_frame_host_->GetView()->HasFocus();
1592 bool is_main_frame = frame_tree_node_->IsMainFrame();
1594 // Swap in the pending or speculative frame and make it active. Also ensure
1595 // the FrameTree stays in sync.
1596 scoped_ptr<RenderFrameHostImpl> old_render_frame_host;
1597 if (!browser_side_navigation) {
1598 DCHECK(!speculative_render_frame_host_);
1599 old_render_frame_host =
1600 SetRenderFrameHost(pending_render_frame_host_.Pass());
1601 } else {
1602 // PlzNavigate
1603 DCHECK(speculative_render_frame_host_);
1604 old_render_frame_host =
1605 SetRenderFrameHost(speculative_render_frame_host_.Pass());
1607 cross_navigation_pending_ = false;
1609 if (is_main_frame)
1610 render_frame_host_->render_view_host()->AttachToFrameTree();
1612 // The process will no longer try to exit, so we can decrement the count.
1613 render_frame_host_->GetProcess()->RemovePendingView();
1615 // Show the new view (or a sad tab) if necessary.
1616 bool new_rfh_has_view = !!render_frame_host_->GetView();
1617 if (!delegate_->IsHidden() && new_rfh_has_view) {
1618 // In most cases, we need to show the new view.
1619 render_frame_host_->GetView()->Show();
1621 if (!new_rfh_has_view) {
1622 // If the view is gone, then this RenderViewHost died while it was hidden.
1623 // We ignored the RenderProcessGone call at the time, so we should send it
1624 // now to make sure the sad tab shows up, etc.
1625 DCHECK(!render_frame_host_->IsRenderFrameLive());
1626 DCHECK(!render_frame_host_->render_view_host()->IsRenderViewLive());
1627 delegate_->RenderProcessGoneFromRenderManager(
1628 render_frame_host_->render_view_host());
1631 // For top-level frames, also hide the old RenderViewHost's view.
1632 // TODO(creis): As long as show/hide are on RVH, we don't want to hide on
1633 // subframe navigations or we will interfere with the top-level frame.
1634 if (is_main_frame && old_render_frame_host->render_view_host()->GetView())
1635 old_render_frame_host->render_view_host()->GetView()->Hide();
1637 // Make sure the size is up to date. (Fix for bug 1079768.)
1638 delegate_->UpdateRenderViewSizeForRenderManager();
1640 if (will_focus_location_bar) {
1641 delegate_->SetFocusToLocationBar(false);
1642 } else if (focus_render_view && render_frame_host_->GetView()) {
1643 render_frame_host_->GetView()->Focus();
1646 // Notify that we've swapped RenderFrameHosts. We do this before shutting down
1647 // the RFH so that we can clean up RendererResources related to the RFH first.
1648 delegate_->NotifySwappedFromRenderManager(
1649 old_render_frame_host.get(), render_frame_host_.get(), is_main_frame);
1651 // Swap out the old frame now that the new one is visible.
1652 // This will swap it out and then put it on the proxy list (if there are other
1653 // active views in its SiteInstance) or schedule it for deletion when the swap
1654 // out ack arrives (or immediately if the process isn't live).
1655 // In the --site-per-process case, old subframe RHFs are not kept alive inside
1656 // the proxy.
1657 SwapOutOldFrame(old_render_frame_host.Pass());
1659 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1660 switches::kSitePerProcess) &&
1661 !is_main_frame) {
1662 // If this is a subframe, it should have a CrossProcessFrameConnector
1663 // created already. Use it to link the new RFH's view to the proxy that
1664 // belongs to the parent frame's SiteInstance.
1665 // Note: We do this after swapping out the old RFH because that may create
1666 // the proxy we're looking for.
1667 RenderFrameProxyHost* proxy_to_parent = GetProxyToParent();
1668 if (proxy_to_parent) {
1669 proxy_to_parent->SetChildRWHView(render_frame_host_->GetView());
1672 // Since the new RenderFrameHost is now committed, there must be no proxies
1673 // for its SiteInstance. Delete any existing ones.
1674 RenderFrameProxyHostMap::iterator iter =
1675 proxy_hosts_.find(render_frame_host_->GetSiteInstance()->GetId());
1676 if (iter != proxy_hosts_.end()) {
1677 delete iter->second;
1678 proxy_hosts_.erase(iter);
1682 // After all is done, there must never be a proxy in the list which has the
1683 // same SiteInstance as the current RenderFrameHost.
1684 CHECK(proxy_hosts_.find(render_frame_host_->GetSiteInstance()->GetId()) ==
1685 proxy_hosts_.end());
1688 void RenderFrameHostManager::ShutdownRenderFrameProxyHostsInSiteInstance(
1689 int32 site_instance_id) {
1690 // First remove any swapped out RFH for this SiteInstance from our own list.
1691 ClearProxiesInSiteInstance(site_instance_id, frame_tree_node_);
1693 // Use the safe RenderWidgetHost iterator for now to find all RenderViewHosts
1694 // in the SiteInstance, then tell their respective FrameTrees to remove all
1695 // RenderFrameProxyHosts corresponding to them.
1696 // TODO(creis): Replace this with a RenderFrameHostIterator that protects
1697 // against use-after-frees if a later element is deleted before getting to it.
1698 scoped_ptr<RenderWidgetHostIterator> widgets(
1699 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
1700 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
1701 if (!widget->IsRenderView())
1702 continue;
1703 RenderViewHostImpl* rvh =
1704 static_cast<RenderViewHostImpl*>(RenderViewHost::From(widget));
1705 if (site_instance_id == rvh->GetSiteInstance()->GetId()) {
1706 // This deletes all RenderFrameHosts using the |rvh|, which then causes
1707 // |rvh| to Shutdown.
1708 FrameTree* tree = rvh->GetDelegate()->GetFrameTree();
1709 tree->ForEach(base::Bind(
1710 &RenderFrameHostManager::ClearProxiesInSiteInstance,
1711 site_instance_id));
1716 RenderFrameHostImpl* RenderFrameHostManager::UpdateStateForNavigate(
1717 const GURL& dest_url,
1718 SiteInstance* source_instance,
1719 SiteInstance* dest_instance,
1720 ui::PageTransition transition,
1721 bool dest_is_restore,
1722 bool dest_is_view_source_mode,
1723 const GlobalRequestID& transferred_request_id,
1724 int bindings) {
1725 // If we are currently navigating cross-process, we want to get back to normal
1726 // and then navigate as usual.
1727 if (cross_navigation_pending_) {
1728 if (pending_render_frame_host_)
1729 CancelPending();
1730 cross_navigation_pending_ = false;
1733 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1734 scoped_refptr<SiteInstance> new_instance = GetSiteInstanceForNavigation(
1735 dest_url, source_instance, dest_instance, transition,
1736 dest_is_restore, dest_is_view_source_mode);
1738 const NavigationEntry* current_entry =
1739 delegate_->GetLastCommittedNavigationEntryForRenderManager();
1741 DCHECK(!cross_navigation_pending_);
1743 if (new_instance.get() != current_instance) {
1744 TRACE_EVENT_INSTANT2(
1745 "navigation",
1746 "RenderFrameHostManager::UpdateStateForNavigate:New SiteInstance",
1747 TRACE_EVENT_SCOPE_THREAD,
1748 "current_instance id", current_instance->GetId(),
1749 "new_instance id", new_instance->GetId());
1751 // New SiteInstance: create a pending RFH to navigate.
1753 // This will possibly create (set to nullptr) a Web UI object for the
1754 // pending page. We'll use this later to give the page special access. This
1755 // must happen before the new renderer is created below so it will get
1756 // bindings. It must also happen after the above conditional call to
1757 // CancelPending(), otherwise CancelPending may clear the pending_web_ui_
1758 // and the page will not have its bindings set appropriately.
1759 SetPendingWebUI(dest_url, bindings);
1760 CreatePendingRenderFrameHost(current_instance, new_instance.get(),
1761 frame_tree_node_->IsMainFrame());
1762 if (!pending_render_frame_host_.get()) {
1763 return nullptr;
1766 // Check if our current RFH is live before we set up a transition.
1767 if (!render_frame_host_->IsRenderFrameLive()) {
1768 if (!cross_navigation_pending_) {
1769 // The current RFH is not live. There's no reason to sit around with a
1770 // sad tab or a newly created RFH while we wait for the pending RFH to
1771 // navigate. Just switch to the pending RFH now and go back to non
1772 // cross-navigating (Note that we don't care about on{before}unload
1773 // handlers if the current RFH isn't live.)
1774 CommitPending();
1775 return render_frame_host_.get();
1776 } else {
1777 NOTREACHED();
1778 return render_frame_host_.get();
1781 // Otherwise, it's safe to treat this as a pending cross-site transition.
1783 // We now have a pending RFH.
1784 DCHECK(!cross_navigation_pending_);
1785 cross_navigation_pending_ = true;
1787 // We need to wait until the beforeunload handler has run, unless we are
1788 // transferring an existing request (in which case it has already run).
1789 // Suspend the new render view (i.e., don't let it send the cross-site
1790 // Navigate message) until we hear back from the old renderer's
1791 // beforeunload handler. If the handler returns false, we'll have to
1792 // cancel the request.
1794 DCHECK(!pending_render_frame_host_->are_navigations_suspended());
1795 bool is_transfer = transferred_request_id != GlobalRequestID();
1796 if (is_transfer) {
1797 // We don't need to stop the old renderer or run beforeunload/unload
1798 // handlers, because those have already been done.
1799 DCHECK(cross_site_transferring_request_->request_id() ==
1800 transferred_request_id);
1801 } else {
1802 // Also make sure the old render view stops, in case a load is in
1803 // progress. (We don't want to do this for transfers, since it will
1804 // interrupt the transfer with an unexpected DidStopLoading.)
1805 render_frame_host_->Send(new FrameMsg_Stop(
1806 render_frame_host_->GetRoutingID()));
1807 pending_render_frame_host_->SetNavigationsSuspended(true,
1808 base::TimeTicks());
1809 // Unless we are transferring an existing request, we should now tell the
1810 // old render view to run its beforeunload handler, since it doesn't
1811 // otherwise know that the cross-site request is happening. This will
1812 // trigger a call to OnBeforeUnloadACK with the reply.
1813 render_frame_host_->DispatchBeforeUnload(true);
1816 return pending_render_frame_host_.get();
1819 // Otherwise the same SiteInstance can be used. Navigate render_frame_host_.
1821 // It's possible to swap out the current RFH and then decide to navigate in it
1822 // anyway (e.g., a cross-process navigation that redirects back to the
1823 // original site). In that case, we have a proxy for the current RFH but
1824 // haven't deleted it yet. The new navigation will swap it back in, so we can
1825 // delete the proxy.
1826 DeleteRenderFrameProxyHost(new_instance.get());
1828 if (ShouldReuseWebUI(current_entry, dest_url)) {
1829 pending_web_ui_.reset();
1830 pending_and_current_web_ui_ = web_ui_->AsWeakPtr();
1831 } else {
1832 SetPendingWebUI(dest_url, bindings);
1833 // Make sure the new RenderViewHost has the right bindings.
1834 if (pending_web_ui() &&
1835 !render_frame_host_->GetProcess()->IsIsolatedGuest()) {
1836 render_frame_host_->render_view_host()->AllowBindings(
1837 pending_web_ui()->GetBindings());
1841 if (pending_web_ui() && render_frame_host_->IsRenderFrameLive()) {
1842 pending_web_ui()->GetController()->RenderViewReused(
1843 render_frame_host_->render_view_host());
1846 // The renderer can exit view source mode when any error or cancellation
1847 // happen. We must overwrite to recover the mode.
1848 if (dest_is_view_source_mode) {
1849 render_frame_host_->render_view_host()->Send(
1850 new ViewMsg_EnableViewSourceMode(
1851 render_frame_host_->render_view_host()->GetRoutingID()));
1854 return render_frame_host_.get();
1857 void RenderFrameHostManager::CancelPending() {
1858 TRACE_EVENT1("navigation", "RenderFrameHostManager::CancelPending",
1859 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
1860 DiscardUnusedFrame(UnsetPendingRenderFrameHost());
1863 scoped_ptr<RenderFrameHostImpl>
1864 RenderFrameHostManager::UnsetPendingRenderFrameHost() {
1865 scoped_ptr<RenderFrameHostImpl> pending_render_frame_host =
1866 pending_render_frame_host_.Pass();
1868 RenderFrameDevToolsAgentHost::OnCancelPendingNavigation(
1869 pending_render_frame_host.get(),
1870 render_frame_host_.get());
1872 // We no longer need to prevent the process from exiting.
1873 pending_render_frame_host->GetProcess()->RemovePendingView();
1875 pending_web_ui_.reset();
1876 pending_and_current_web_ui_.reset();
1878 return pending_render_frame_host.Pass();
1881 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::SetRenderFrameHost(
1882 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
1883 // Swap the two.
1884 scoped_ptr<RenderFrameHostImpl> old_render_frame_host =
1885 render_frame_host_.Pass();
1886 render_frame_host_ = render_frame_host.Pass();
1888 if (frame_tree_node_->IsMainFrame()) {
1889 // Update the count of top-level frames using this SiteInstance. All
1890 // subframes are in the same BrowsingInstance as the main frame, so we only
1891 // count top-level ones. This makes the value easier for consumers to
1892 // interpret.
1893 if (render_frame_host_) {
1894 render_frame_host_->GetSiteInstance()->
1895 IncrementRelatedActiveContentsCount();
1897 if (old_render_frame_host) {
1898 old_render_frame_host->GetSiteInstance()->
1899 DecrementRelatedActiveContentsCount();
1903 return old_render_frame_host.Pass();
1906 bool RenderFrameHostManager::IsRVHOnSwappedOutList(
1907 RenderViewHostImpl* rvh) const {
1908 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(
1909 rvh->GetSiteInstance());
1910 if (!proxy)
1911 return false;
1912 // If there is a proxy without RFH, it is for a subframe in the SiteInstance
1913 // of |rvh|. Subframes should be ignored in this case.
1914 if (!proxy->render_frame_host())
1915 return false;
1916 return IsOnSwappedOutList(proxy->render_frame_host());
1919 bool RenderFrameHostManager::IsOnSwappedOutList(
1920 RenderFrameHostImpl* rfh) const {
1921 if (!rfh->GetSiteInstance())
1922 return false;
1924 RenderFrameProxyHostMap::const_iterator iter = proxy_hosts_.find(
1925 rfh->GetSiteInstance()->GetId());
1926 if (iter == proxy_hosts_.end())
1927 return false;
1929 return iter->second->render_frame_host() == rfh;
1932 RenderViewHostImpl* RenderFrameHostManager::GetSwappedOutRenderViewHost(
1933 SiteInstance* instance) const {
1934 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1935 if (proxy)
1936 return proxy->GetRenderViewHost();
1937 return NULL;
1940 RenderFrameProxyHost* RenderFrameHostManager::GetRenderFrameProxyHost(
1941 SiteInstance* instance) const {
1942 RenderFrameProxyHostMap::const_iterator iter =
1943 proxy_hosts_.find(instance->GetId());
1944 if (iter != proxy_hosts_.end())
1945 return iter->second;
1947 return NULL;
1950 void RenderFrameHostManager::DeleteRenderFrameProxyHost(
1951 SiteInstance* instance) {
1952 RenderFrameProxyHostMap::iterator iter = proxy_hosts_.find(instance->GetId());
1953 if (iter != proxy_hosts_.end()) {
1954 delete iter->second;
1955 proxy_hosts_.erase(iter);
1959 } // namespace content