DevTools: cut host and port from webSocketDebuggerUrl in addition to ws:// prefix
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_manager.cc
blobcd85433714fe8f693e255ef4be2f90db85e957f3
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/frame_navigation_entry.h"
18 #include "content/browser/frame_host/interstitial_page_impl.h"
19 #include "content/browser/frame_host/navigation_controller_impl.h"
20 #include "content/browser/frame_host/navigation_entry_impl.h"
21 #include "content/browser/frame_host/navigation_request.h"
22 #include "content/browser/frame_host/navigator.h"
23 #include "content/browser/frame_host/render_frame_host_factory.h"
24 #include "content/browser/frame_host/render_frame_host_impl.h"
25 #include "content/browser/frame_host/render_frame_proxy_host.h"
26 #include "content/browser/renderer_host/render_process_host_impl.h"
27 #include "content/browser/renderer_host/render_view_host_factory.h"
28 #include "content/browser/renderer_host/render_view_host_impl.h"
29 #include "content/browser/site_instance_impl.h"
30 #include "content/browser/webui/web_ui_controller_factory_registry.h"
31 #include "content/browser/webui/web_ui_impl.h"
32 #include "content/common/frame_messages.h"
33 #include "content/common/view_messages.h"
34 #include "content/public/browser/content_browser_client.h"
35 #include "content/public/browser/notification_service.h"
36 #include "content/public/browser/notification_types.h"
37 #include "content/public/browser/render_widget_host_iterator.h"
38 #include "content/public/browser/render_widget_host_view.h"
39 #include "content/public/browser/user_metrics.h"
40 #include "content/public/browser/web_ui_controller.h"
41 #include "content/public/common/content_switches.h"
42 #include "content/public/common/referrer.h"
43 #include "content/public/common/url_constants.h"
45 namespace content {
47 // static
48 bool RenderFrameHostManager::ClearRFHsPendingShutdown(FrameTreeNode* node) {
49 node->render_manager()->pending_delete_hosts_.clear();
50 return true;
53 // static
54 bool RenderFrameHostManager::IsSwappedOutStateForbidden() {
55 return base::CommandLine::ForCurrentProcess()->HasSwitch(
56 switches::kSitePerProcess);
59 RenderFrameHostManager::RenderFrameHostManager(
60 FrameTreeNode* frame_tree_node,
61 RenderFrameHostDelegate* render_frame_delegate,
62 RenderViewHostDelegate* render_view_delegate,
63 RenderWidgetHostDelegate* render_widget_delegate,
64 Delegate* delegate)
65 : frame_tree_node_(frame_tree_node),
66 delegate_(delegate),
67 render_frame_delegate_(render_frame_delegate),
68 render_view_delegate_(render_view_delegate),
69 render_widget_delegate_(render_widget_delegate),
70 interstitial_page_(nullptr),
71 should_reuse_web_ui_(false),
72 weak_factory_(this) {
73 DCHECK(frame_tree_node_);
76 RenderFrameHostManager::~RenderFrameHostManager() {
77 if (pending_render_frame_host_) {
78 scoped_ptr<RenderFrameHostImpl> relic = UnsetPendingRenderFrameHost();
79 ShutdownProxiesIfLastActiveFrameInSiteInstance(relic.get());
82 if (speculative_render_frame_host_) {
83 scoped_ptr<RenderFrameHostImpl> relic = UnsetSpeculativeRenderFrameHost();
84 ShutdownProxiesIfLastActiveFrameInSiteInstance(relic.get());
87 ShutdownProxiesIfLastActiveFrameInSiteInstance(render_frame_host_.get());
89 // Delete any RenderFrameProxyHosts and swapped out RenderFrameHosts.
90 // It is important to delete those prior to deleting the current
91 // RenderFrameHost, since the CrossProcessFrameConnector (owned by
92 // RenderFrameProxyHost) points to the RenderWidgetHostView associated with
93 // the current RenderFrameHost and uses it during its destructor.
94 STLDeleteValues(&proxy_hosts_);
96 // Release the WebUI prior to resetting the current RenderFrameHost, as the
97 // WebUI accesses the RenderFrameHost during cleanup.
98 web_ui_.reset();
100 // We should always have a current RenderFrameHost except in some tests.
101 SetRenderFrameHost(scoped_ptr<RenderFrameHostImpl>());
104 void RenderFrameHostManager::Init(BrowserContext* browser_context,
105 SiteInstance* site_instance,
106 int view_routing_id,
107 int frame_routing_id) {
108 // Create a RenderViewHost and RenderFrameHost, once we have an instance. It
109 // is important to immediately give this SiteInstance to a RenderViewHost so
110 // that the SiteInstance is ref counted.
111 if (!site_instance)
112 site_instance = SiteInstance::Create(browser_context);
114 int flags = delegate_->IsHidden() ? CREATE_RF_HIDDEN : 0;
115 SetRenderFrameHost(CreateRenderFrameHost(site_instance, view_routing_id,
116 frame_routing_id, flags));
118 // Notify the delegate of the creation of the current RenderFrameHost.
119 // Do this only for subframes, as the main frame case is taken care of by
120 // WebContentsImpl::Init.
121 if (!frame_tree_node_->IsMainFrame()) {
122 delegate_->NotifySwappedFromRenderManager(
123 nullptr, render_frame_host_.get(), false);
126 // Keep track of renderer processes as they start to shut down or are
127 // crashed/killed.
128 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSED,
129 NotificationService::AllSources());
130 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSING,
131 NotificationService::AllSources());
134 RenderViewHostImpl* RenderFrameHostManager::current_host() const {
135 if (!render_frame_host_)
136 return NULL;
137 return render_frame_host_->render_view_host();
140 RenderViewHostImpl* RenderFrameHostManager::pending_render_view_host() const {
141 if (!pending_render_frame_host_)
142 return NULL;
143 return pending_render_frame_host_->render_view_host();
146 RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const {
147 if (interstitial_page_)
148 return interstitial_page_->GetView();
149 if (render_frame_host_)
150 return render_frame_host_->GetView();
151 return nullptr;
154 bool RenderFrameHostManager::ForInnerDelegate() {
155 // TODO(lazyboy): Subframes inside inner WebContents needs to be tested and
156 // we have to make sure that IsMainFrame() check below is appropriate. See
157 // http://crbug.com/500957.
158 return frame_tree_node_->IsMainFrame() &&
159 delegate_->GetOuterDelegateFrameTreeNodeID() !=
160 FrameTreeNode::kFrameTreeNodeInvalidID;
163 RenderWidgetHostImpl*
164 RenderFrameHostManager::GetOuterRenderWidgetHostForKeyboardInput() {
165 if (!ForInnerDelegate())
166 return nullptr;
168 FrameTreeNode* outer_contents_frame_tree_node =
169 FrameTreeNode::GloballyFindByID(
170 delegate_->GetOuterDelegateFrameTreeNodeID());
171 return outer_contents_frame_tree_node->parent()
172 ->current_frame_host()
173 ->render_view_host();
176 RenderFrameProxyHost* RenderFrameHostManager::GetProxyToParent() {
177 if (frame_tree_node_->IsMainFrame())
178 return NULL;
180 RenderFrameProxyHostMap::iterator iter =
181 proxy_hosts_.find(frame_tree_node_->parent()
182 ->render_manager()
183 ->current_frame_host()
184 ->GetSiteInstance()
185 ->GetId());
186 if (iter == proxy_hosts_.end())
187 return NULL;
189 return iter->second;
192 RenderFrameProxyHost* RenderFrameHostManager::GetProxyToOuterDelegate() {
193 int outer_contents_frame_tree_node_id =
194 delegate_->GetOuterDelegateFrameTreeNodeID();
195 FrameTreeNode* outer_contents_frame_tree_node =
196 FrameTreeNode::GloballyFindByID(outer_contents_frame_tree_node_id);
197 if (!outer_contents_frame_tree_node ||
198 !outer_contents_frame_tree_node->parent()) {
199 return nullptr;
202 return GetRenderFrameProxyHost(outer_contents_frame_tree_node->parent()
203 ->current_frame_host()
204 ->GetSiteInstance());
207 void RenderFrameHostManager::RemoveOuterDelegateFrame() {
208 FrameTreeNode* outer_delegate_frame_tree_node =
209 FrameTreeNode::GloballyFindByID(
210 delegate_->GetOuterDelegateFrameTreeNodeID());
211 DCHECK(outer_delegate_frame_tree_node->parent());
212 outer_delegate_frame_tree_node->frame_tree()->RemoveFrame(
213 outer_delegate_frame_tree_node);
216 void RenderFrameHostManager::SetPendingWebUI(const GURL& url, int bindings) {
217 pending_web_ui_ = CreateWebUI(url, bindings);
218 pending_and_current_web_ui_.reset();
221 scoped_ptr<WebUIImpl> RenderFrameHostManager::CreateWebUI(const GURL& url,
222 int bindings) {
223 scoped_ptr<WebUIImpl> new_web_ui(delegate_->CreateWebUIForRenderManager(url));
225 // If we have assigned (zero or more) bindings to this NavigationEntry in the
226 // past, make sure we're not granting it different bindings than it had
227 // before. If so, note it and don't give it any bindings, to avoid a
228 // potential privilege escalation.
229 if (new_web_ui && bindings != NavigationEntryImpl::kInvalidBindings &&
230 new_web_ui->GetBindings() != bindings) {
231 RecordAction(base::UserMetricsAction("ProcessSwapBindingsMismatch_RVHM"));
232 return nullptr;
234 return new_web_ui.Pass();
237 RenderFrameHostImpl* RenderFrameHostManager::Navigate(
238 const FrameNavigationEntry& frame_entry,
239 const NavigationEntryImpl& entry) {
240 TRACE_EVENT1("navigation", "RenderFrameHostManager:Navigate",
241 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
242 // Create a pending RenderFrameHost to use for the navigation.
243 RenderFrameHostImpl* dest_render_frame_host = UpdateStateForNavigate(
244 frame_entry.url(),
245 // TODO(creis): Move source_site_instance to FNE.
246 entry.source_site_instance(), frame_entry.site_instance(),
247 entry.GetTransitionType(),
248 entry.restore_type() != NavigationEntryImpl::RESTORE_NONE,
249 entry.IsViewSourceMode(), entry.transferred_global_request_id(),
250 entry.bindings());
251 if (!dest_render_frame_host)
252 return NULL; // We weren't able to create a pending render frame host.
254 // If the current render_frame_host_ isn't live, we should create it so
255 // that we don't show a sad tab while the dest_render_frame_host fetches
256 // its first page. (Bug 1145340)
257 if (dest_render_frame_host != render_frame_host_ &&
258 !render_frame_host_->IsRenderFrameLive()) {
259 // Note: we don't call InitRenderView here because we are navigating away
260 // soon anyway, and we don't have the NavigationEntry for this host.
261 delegate_->CreateRenderViewForRenderManager(
262 render_frame_host_->render_view_host(), MSG_ROUTING_NONE,
263 MSG_ROUTING_NONE, frame_tree_node_->current_replication_state(),
264 frame_tree_node_->IsMainFrame());
267 // If the renderer crashed, then try to create a new one to satisfy this
268 // navigation request.
269 if (!dest_render_frame_host->IsRenderFrameLive()) {
270 // Instruct the destination render frame host to set up a Mojo connection
271 // with the new render frame if necessary. Note that this call needs to
272 // occur before initializing the RenderView; the flow of creating the
273 // RenderView can cause browser-side code to execute that expects the this
274 // RFH's ServiceRegistry to be initialized (e.g., if the site is a WebUI
275 // site that is handled via Mojo, then Mojo WebUI code in //chrome will
276 // add a service to this RFH's ServiceRegistry).
277 dest_render_frame_host->SetUpMojoIfNeeded();
279 // Recreate the opener chain.
280 int opener_route_id =
281 CreateOpenerProxiesIfNeeded(dest_render_frame_host->GetSiteInstance());
282 if (!InitRenderView(dest_render_frame_host->render_view_host(),
283 opener_route_id,
284 MSG_ROUTING_NONE,
285 frame_tree_node_->IsMainFrame()))
286 return NULL;
288 // Now that we've created a new renderer, be sure to hide it if it isn't
289 // our primary one. Otherwise, we might crash if we try to call Show()
290 // on it later.
291 if (dest_render_frame_host != render_frame_host_) {
292 if (dest_render_frame_host->GetView())
293 dest_render_frame_host->GetView()->Hide();
294 } else {
295 // TODO(nasko): This is a very ugly hack. The Chrome extensions process
296 // manager still uses NotificationService and expects to see a
297 // RenderViewHost changed notification after WebContents and
298 // RenderFrameHostManager are completely initialized. This should be
299 // removed once the process manager moves away from NotificationService.
300 // See https://crbug.com/462682.
301 delegate_->NotifyMainFrameSwappedFromRenderManager(
302 nullptr, render_frame_host_->render_view_host());
306 // If entry includes the request ID of a request that is being transferred,
307 // the destination render frame will take ownership, so release ownership of
308 // the request.
309 if (cross_site_transferring_request_.get() &&
310 cross_site_transferring_request_->request_id() ==
311 entry.transferred_global_request_id()) {
312 cross_site_transferring_request_->ReleaseRequest();
315 return dest_render_frame_host;
318 void RenderFrameHostManager::Stop() {
319 render_frame_host_->Stop();
321 // If we are navigating cross-process, we should stop the pending renderers.
322 // This will lead to a DidFailProvisionalLoad, which will properly destroy
323 // them.
324 if (pending_render_frame_host_) {
325 pending_render_frame_host_->Send(new FrameMsg_Stop(
326 pending_render_frame_host_->GetRoutingID()));
330 void RenderFrameHostManager::SetIsLoading(bool is_loading) {
331 render_frame_host_->render_view_host()->SetIsLoading(is_loading);
332 if (pending_render_frame_host_)
333 pending_render_frame_host_->render_view_host()->SetIsLoading(is_loading);
336 bool RenderFrameHostManager::ShouldCloseTabOnUnresponsiveRenderer() {
337 // If we're waiting for a close ACK, then the tab should close whether there's
338 // a navigation in progress or not. Unfortunately, we also need to check for
339 // cases that we arrive here with no navigation in progress, since there are
340 // some tab closure paths that don't set is_waiting_for_close_ack to true.
341 // TODO(creis): Clean this up in http://crbug.com/418266.
342 if (!pending_render_frame_host_ ||
343 render_frame_host_->render_view_host()->is_waiting_for_close_ack())
344 return true;
346 // We should always have a pending RFH when there's a cross-process navigation
347 // in progress. Sanity check this for http://crbug.com/276333.
348 CHECK(pending_render_frame_host_);
350 // Unload handlers run in the background, so we should never get an
351 // unresponsiveness warning for them.
352 CHECK(!render_frame_host_->IsWaitingForUnloadACK());
354 // If the tab becomes unresponsive during beforeunload while doing a
355 // cross-process navigation, proceed with the navigation. (This assumes that
356 // the pending RenderFrameHost is still responsive.)
357 if (render_frame_host_->is_waiting_for_beforeunload_ack()) {
358 // Haven't gotten around to starting the request, because we're still
359 // waiting for the beforeunload handler to finish. We'll pretend that it
360 // did finish, to let the navigation proceed. Note that there's a danger
361 // that the beforeunload handler will later finish and possibly return
362 // false (meaning the navigation should not proceed), but we'll ignore it
363 // in this case because it took too long.
364 if (pending_render_frame_host_->are_navigations_suspended()) {
365 pending_render_frame_host_->SetNavigationsSuspended(
366 false, base::TimeTicks::Now());
369 return false;
372 void RenderFrameHostManager::OnBeforeUnloadACK(
373 bool for_cross_site_transition,
374 bool proceed,
375 const base::TimeTicks& proceed_time) {
376 if (for_cross_site_transition) {
377 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
378 switches::kEnableBrowserSideNavigation));
379 // Ignore if we're not in a cross-process navigation.
380 if (!pending_render_frame_host_)
381 return;
383 if (proceed) {
384 // Ok to unload the current page, so proceed with the cross-process
385 // navigation. Note that if navigations are not currently suspended, it
386 // might be because the renderer was deemed unresponsive and this call was
387 // already made by ShouldCloseTabOnUnresponsiveRenderer. In that case, it
388 // is ok to do nothing here.
389 if (pending_render_frame_host_ &&
390 pending_render_frame_host_->are_navigations_suspended()) {
391 pending_render_frame_host_->SetNavigationsSuspended(false,
392 proceed_time);
394 } else {
395 // Current page says to cancel.
396 CancelPending();
398 } else {
399 // Non-cross-process transition means closing the entire tab.
400 bool proceed_to_fire_unload;
401 delegate_->BeforeUnloadFiredFromRenderManager(proceed, proceed_time,
402 &proceed_to_fire_unload);
404 if (proceed_to_fire_unload) {
405 // If we're about to close the tab and there's a pending RFH, cancel it.
406 // Otherwise, if the navigation in the pending RFH completes before the
407 // close in the current RFH, we'll lose the tab close.
408 if (pending_render_frame_host_) {
409 CancelPending();
412 // PlzNavigate: clean up the speculative RenderFrameHost if there is one.
413 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
414 switches::kEnableBrowserSideNavigation) &&
415 speculative_render_frame_host_) {
416 CleanUpNavigation();
419 // This is not a cross-process navigation; the tab is being closed.
420 render_frame_host_->render_view_host()->ClosePage();
425 void RenderFrameHostManager::OnCrossSiteResponse(
426 RenderFrameHostImpl* pending_render_frame_host,
427 const GlobalRequestID& global_request_id,
428 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
429 const std::vector<GURL>& transfer_url_chain,
430 const Referrer& referrer,
431 ui::PageTransition page_transition,
432 bool should_replace_current_entry) {
433 // We should only get here for transfer navigations. Most cross-process
434 // navigations can just continue and wait to run the unload handler (by
435 // swapping out) when the new navigation commits.
436 CHECK(cross_site_transferring_request);
438 // A transfer should only have come from our pending or current RFH.
439 // TODO(creis): We need to handle the case that the pending RFH has changed
440 // in the mean time, while this was being posted from the IO thread. We
441 // should probably cancel the request in that case.
442 DCHECK(pending_render_frame_host == pending_render_frame_host_ ||
443 pending_render_frame_host == render_frame_host_);
445 // Store the transferring request so that we can release it if the transfer
446 // navigation matches.
447 cross_site_transferring_request_ = cross_site_transferring_request.Pass();
449 // Sanity check that the params are for the correct frame and process.
450 // These should match the RenderFrameHost that made the request.
451 // If it started as a cross-process navigation via OpenURL, this is the
452 // pending one. If it wasn't cross-process until the transfer, this is the
453 // current one.
454 int render_frame_id = pending_render_frame_host_ ?
455 pending_render_frame_host_->GetRoutingID() :
456 render_frame_host_->GetRoutingID();
457 DCHECK_EQ(render_frame_id, pending_render_frame_host->GetRoutingID());
458 int process_id = pending_render_frame_host_ ?
459 pending_render_frame_host_->GetProcess()->GetID() :
460 render_frame_host_->GetProcess()->GetID();
461 DCHECK_EQ(process_id, global_request_id.child_id);
463 // Treat the last URL in the chain as the destination and the remainder as
464 // the redirect chain.
465 CHECK(transfer_url_chain.size());
466 GURL transfer_url = transfer_url_chain.back();
467 std::vector<GURL> rest_of_chain = transfer_url_chain;
468 rest_of_chain.pop_back();
470 // We don't know whether the original request had |user_action| set to true.
471 // However, since we force the navigation to be in the current tab, it
472 // doesn't matter.
473 pending_render_frame_host->frame_tree_node()->navigator()->RequestTransferURL(
474 pending_render_frame_host, transfer_url, nullptr, rest_of_chain, referrer,
475 page_transition, CURRENT_TAB, global_request_id,
476 should_replace_current_entry, true);
478 // The transferring request was only needed during the RequestTransferURL
479 // call, so it is safe to clear at this point.
480 cross_site_transferring_request_.reset();
483 void RenderFrameHostManager::DidNavigateFrame(
484 RenderFrameHostImpl* render_frame_host,
485 bool was_caused_by_user_gesture) {
486 CommitPendingIfNecessary(render_frame_host, was_caused_by_user_gesture);
488 // Make sure any dynamic changes to this frame's sandbox flags that were made
489 // prior to navigation take effect.
490 CommitPendingSandboxFlags();
493 void RenderFrameHostManager::CommitPendingIfNecessary(
494 RenderFrameHostImpl* render_frame_host,
495 bool was_caused_by_user_gesture) {
496 if (!pending_render_frame_host_ && !speculative_render_frame_host_) {
497 DCHECK_IMPLIES(should_reuse_web_ui_, web_ui_);
499 // We should only hear this from our current renderer.
500 DCHECK_EQ(render_frame_host_, render_frame_host);
502 // Even when there is no pending RVH, there may be a pending Web UI.
503 if (pending_web_ui() || speculative_web_ui_)
504 CommitPending();
505 return;
508 if (render_frame_host == pending_render_frame_host_ ||
509 render_frame_host == speculative_render_frame_host_) {
510 // The pending cross-process navigation completed, so show the renderer.
511 CommitPending();
512 } else if (render_frame_host == render_frame_host_) {
513 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
514 switches::kEnableBrowserSideNavigation)) {
515 CleanUpNavigation();
516 } else {
517 if (was_caused_by_user_gesture) {
518 // A navigation in the original page has taken place. Cancel the
519 // pending one. Only do it for user gesture originated navigations to
520 // prevent page doing any shenanigans to prevent user from navigating.
521 // See https://code.google.com/p/chromium/issues/detail?id=75195
522 CancelPending();
525 } else {
526 // No one else should be sending us DidNavigate in this state.
527 DCHECK(false);
531 void RenderFrameHostManager::DidDisownOpener(
532 RenderFrameHost* render_frame_host) {
533 // Notify all RenderFrameHosts but the one that notified us. This is necessary
534 // in case a process swap has occurred while the message was in flight.
535 for (RenderFrameProxyHostMap::iterator iter = proxy_hosts_.begin();
536 iter != proxy_hosts_.end();
537 ++iter) {
538 DCHECK_NE(iter->second->GetSiteInstance(),
539 current_frame_host()->GetSiteInstance());
540 iter->second->DisownOpener();
543 if (render_frame_host_.get() != render_frame_host)
544 render_frame_host_->DisownOpener();
546 if (pending_render_frame_host_ &&
547 pending_render_frame_host_.get() != render_frame_host) {
548 pending_render_frame_host_->DisownOpener();
552 void RenderFrameHostManager::CommitPendingSandboxFlags() {
553 // Return early if there were no pending sandbox flags updates.
554 if (!frame_tree_node_->CommitPendingSandboxFlags())
555 return;
557 // Sandbox flags updates can only happen when the frame has a parent.
558 CHECK(frame_tree_node_->parent());
560 // Notify all of the frame's proxies about updated sandbox flags, excluding
561 // the parent process since it already knows the latest flags.
562 SiteInstance* parent_site_instance =
563 frame_tree_node_->parent()->current_frame_host()->GetSiteInstance();
564 for (const auto& pair : proxy_hosts_) {
565 if (pair.second->GetSiteInstance() != parent_site_instance) {
566 pair.second->Send(new FrameMsg_DidUpdateSandboxFlags(
567 pair.second->GetRoutingID(),
568 frame_tree_node_->current_replication_state().sandbox_flags));
573 void RenderFrameHostManager::RendererProcessClosing(
574 RenderProcessHost* render_process_host) {
575 // Remove any swapped out RVHs from this process, so that we don't try to
576 // swap them back in while the process is exiting. Start by finding them,
577 // since there could be more than one.
578 std::list<int> ids_to_remove;
579 // Do not remove proxies in the dead process that still have active frame
580 // count though, we just reset them to be uninitialized.
581 std::list<int> ids_to_keep;
582 for (RenderFrameProxyHostMap::iterator iter = proxy_hosts_.begin();
583 iter != proxy_hosts_.end();
584 ++iter) {
585 RenderFrameProxyHost* proxy = iter->second;
586 if (proxy->GetProcess() != render_process_host)
587 continue;
589 if (static_cast<SiteInstanceImpl*>(proxy->GetSiteInstance())
590 ->active_frame_count() >= 1U) {
591 ids_to_keep.push_back(iter->first);
592 } else {
593 ids_to_remove.push_back(iter->first);
597 // Now delete them.
598 while (!ids_to_remove.empty()) {
599 delete proxy_hosts_[ids_to_remove.back()];
600 proxy_hosts_.erase(ids_to_remove.back());
601 ids_to_remove.pop_back();
604 while (!ids_to_keep.empty()) {
605 frame_tree_node_->frame_tree()->ForEach(
606 base::Bind(
607 &RenderFrameHostManager::ResetProxiesInSiteInstance,
608 ids_to_keep.back()));
609 ids_to_keep.pop_back();
613 void RenderFrameHostManager::SwapOutOldFrame(
614 scoped_ptr<RenderFrameHostImpl> old_render_frame_host) {
615 TRACE_EVENT1("navigation", "RenderFrameHostManager::SwapOutOldFrame",
616 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
618 // Tell the renderer to suppress any further modal dialogs so that we can swap
619 // it out. This must be done before canceling any current dialog, in case
620 // there is a loop creating additional dialogs.
621 // TODO(creis): Handle modal dialogs in subframe processes.
622 old_render_frame_host->render_view_host()->SuppressDialogsUntilSwapOut();
624 // Now close any modal dialogs that would prevent us from swapping out. This
625 // must be done separately from SwapOut, so that the PageGroupLoadDeferrer is
626 // no longer on the stack when we send the SwapOut message.
627 delegate_->CancelModalDialogsForRenderManager();
629 // If the old RFH is not live, just return as there is no further work to do.
630 // It will be deleted and there will be no proxy created.
631 int32 old_site_instance_id =
632 old_render_frame_host->GetSiteInstance()->GetId();
633 if (!old_render_frame_host->IsRenderFrameLive()) {
634 ShutdownProxiesIfLastActiveFrameInSiteInstance(old_render_frame_host.get());
635 return;
638 // If there are no active frames besides this one, we can delete the old
639 // RenderFrameHost once it runs its unload handler, without replacing it with
640 // a proxy.
641 size_t active_frame_count =
642 old_render_frame_host->GetSiteInstance()->active_frame_count();
643 if (active_frame_count <= 1) {
644 // Clear out any proxies from this SiteInstance, in case this was the
645 // last one keeping other proxies alive.
646 ShutdownProxiesIfLastActiveFrameInSiteInstance(old_render_frame_host.get());
648 // Tell the old RenderFrameHost to swap out, with no proxy to replace it.
649 old_render_frame_host->SwapOut(NULL, true);
650 MoveToPendingDeleteHosts(old_render_frame_host.Pass());
651 return;
654 // Otherwise there are active views and we need a proxy for the old RFH.
655 // (There should not be one yet.)
656 CHECK(!GetRenderFrameProxyHost(old_render_frame_host->GetSiteInstance()));
657 RenderFrameProxyHost* proxy = new RenderFrameProxyHost(
658 old_render_frame_host->GetSiteInstance(),
659 old_render_frame_host->render_view_host(), frame_tree_node_);
660 CHECK(proxy_hosts_.insert(std::make_pair(old_site_instance_id, proxy)).second)
661 << "Inserting a duplicate item.";
663 // Tell the old RenderFrameHost to swap out and be replaced by the proxy.
664 old_render_frame_host->SwapOut(proxy, true);
666 // SwapOut creates a RenderFrameProxy, so set the proxy to be initialized.
667 proxy->set_render_frame_proxy_created(true);
669 if (RenderFrameHostManager::IsSwappedOutStateForbidden()) {
670 // In --site-per-process, frames delete their RFH rather than storing it
671 // in the proxy. Schedule it for deletion once the SwapOutACK comes in.
672 // TODO(creis): This will be the default when we remove swappedout://.
673 MoveToPendingDeleteHosts(old_render_frame_host.Pass());
674 } else {
675 // We shouldn't get here for subframes, since we only swap subframes when
676 // --site-per-process is used.
677 DCHECK(frame_tree_node_->IsMainFrame());
679 // The old RenderFrameHost will stay alive inside the proxy so that existing
680 // JavaScript window references to it stay valid.
681 proxy->TakeFrameHostOwnership(old_render_frame_host.Pass());
685 void RenderFrameHostManager::DiscardUnusedFrame(
686 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
687 // TODO(carlosk): this code is very similar to what can be found in
688 // SwapOutOldFrame and we should see that these are unified at some point.
690 // If the SiteInstance for the pending RFH is being used by others don't
691 // delete the RFH. Just swap it out and it can be reused at a later point.
692 // In --site-per-process, RenderFrameHosts are not kept around and are
693 // deleted when not used, replaced by RenderFrameProxyHosts.
694 SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance();
695 if (site_instance->HasSite() && site_instance->active_frame_count() > 1) {
696 // Any currently suspended navigations are no longer needed.
697 render_frame_host->CancelSuspendedNavigations();
699 CHECK(!GetRenderFrameProxyHost(site_instance));
700 RenderFrameProxyHost* proxy = new RenderFrameProxyHost(
701 site_instance, render_frame_host->render_view_host(), frame_tree_node_);
702 proxy_hosts_[site_instance->GetId()] = proxy;
704 // Check if the RenderFrameHost is already swapped out, to avoid swapping it
705 // out again.
706 if (!render_frame_host->is_swapped_out())
707 render_frame_host->SwapOut(proxy, false);
709 if (!RenderFrameHostManager::IsSwappedOutStateForbidden()) {
710 DCHECK(frame_tree_node_->IsMainFrame());
711 proxy->TakeFrameHostOwnership(render_frame_host.Pass());
715 if (render_frame_host) {
716 // We won't be coming back, so delete this one.
717 ShutdownProxiesIfLastActiveFrameInSiteInstance(render_frame_host.get());
718 render_frame_host.reset();
722 void RenderFrameHostManager::MoveToPendingDeleteHosts(
723 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
724 // |render_frame_host| will be deleted when its SwapOut ACK is received, or
725 // when the timer times out, or when the RFHM itself is deleted (whichever
726 // comes first).
727 pending_delete_hosts_.push_back(
728 linked_ptr<RenderFrameHostImpl>(render_frame_host.release()));
731 bool RenderFrameHostManager::IsPendingDeletion(
732 RenderFrameHostImpl* render_frame_host) {
733 for (const auto& rfh : pending_delete_hosts_) {
734 if (rfh == render_frame_host)
735 return true;
737 return false;
740 bool RenderFrameHostManager::DeleteFromPendingList(
741 RenderFrameHostImpl* render_frame_host) {
742 for (RFHPendingDeleteList::iterator iter = pending_delete_hosts_.begin();
743 iter != pending_delete_hosts_.end();
744 iter++) {
745 if (*iter == render_frame_host) {
746 pending_delete_hosts_.erase(iter);
747 return true;
750 return false;
753 void RenderFrameHostManager::ResetProxyHosts() {
754 STLDeleteValues(&proxy_hosts_);
757 // PlzNavigate
758 void RenderFrameHostManager::DidCreateNavigationRequest(
759 const NavigationRequest& request) {
760 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
761 switches::kEnableBrowserSideNavigation));
762 // Clean up any state in case there's an ongoing navigation.
763 // TODO(carlosk): remove this cleanup here once we properly cancel ongoing
764 // navigations.
765 CleanUpNavigation();
767 RenderFrameHostImpl* dest_rfh = GetFrameHostForNavigation(request);
768 DCHECK(dest_rfh);
771 // PlzNavigate
772 RenderFrameHostImpl* RenderFrameHostManager::GetFrameHostForNavigation(
773 const NavigationRequest& request) {
774 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
775 switches::kEnableBrowserSideNavigation));
777 SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance();
779 SiteInstance* candidate_site_instance =
780 speculative_render_frame_host_
781 ? speculative_render_frame_host_->GetSiteInstance()
782 : nullptr;
784 scoped_refptr<SiteInstance> dest_site_instance = GetSiteInstanceForNavigation(
785 request.common_params().url, request.source_site_instance(),
786 request.dest_site_instance(), candidate_site_instance,
787 request.common_params().transition,
788 request.restore_type() != NavigationEntryImpl::RESTORE_NONE,
789 request.is_view_source());
791 // The appropriate RenderFrameHost to commit the navigation.
792 RenderFrameHostImpl* navigation_rfh = nullptr;
794 // Renderer-initiated main frame navigations that may require a SiteInstance
795 // swap are sent to the browser via the OpenURL IPC and are afterwards treated
796 // as browser-initiated navigations. NavigationRequests marked as
797 // renderer-initiated are created by receiving a BeginNavigation IPC, and will
798 // then proceed in the same renderer that sent the IPC due to the condition
799 // below.
800 // Subframe navigations will use the current renderer, unless
801 // --site-per-process is enabled.
802 // TODO(carlosk): Have renderer-initated main frame navigations swap processes
803 // if needed when it no longer breaks OAuth popups (see
804 // https://crbug.com/440266).
805 bool site_per_process = base::CommandLine::ForCurrentProcess()->HasSwitch(
806 switches::kSitePerProcess);
807 bool is_main_frame = frame_tree_node_->IsMainFrame();
808 if (current_site_instance == dest_site_instance.get() ||
809 (!request.browser_initiated() && is_main_frame) ||
810 (!is_main_frame && !site_per_process)) {
811 // Reuse the current RFH if its SiteInstance matches the the navigation's
812 // or if this is a subframe navigation. We only swap RFHs for subframes when
813 // --site-per-process is enabled.
814 CleanUpNavigation();
815 navigation_rfh = render_frame_host_.get();
817 // As SiteInstances are the same, check if the WebUI should be reused.
818 const NavigationEntry* current_navigation_entry =
819 delegate_->GetLastCommittedNavigationEntryForRenderManager();
820 should_reuse_web_ui_ = ShouldReuseWebUI(current_navigation_entry,
821 request.common_params().url);
822 if (!should_reuse_web_ui_) {
823 speculative_web_ui_ = CreateWebUI(request.common_params().url,
824 request.bindings());
825 // Make sure the current RenderViewHost has the right bindings.
826 if (speculative_web_ui() &&
827 !render_frame_host_->GetProcess()->IsForGuestsOnly()) {
828 render_frame_host_->render_view_host()->AllowBindings(
829 speculative_web_ui()->GetBindings());
832 } else {
833 // If the SiteInstance for the final URL doesn't match the one from the
834 // speculatively created RenderFrameHost, create a new RenderFrameHost using
835 // this new SiteInstance.
836 if (!speculative_render_frame_host_ ||
837 speculative_render_frame_host_->GetSiteInstance() !=
838 dest_site_instance.get()) {
839 CleanUpNavigation();
840 bool success = CreateSpeculativeRenderFrameHost(
841 request.common_params().url, current_site_instance,
842 dest_site_instance.get(), request.bindings());
843 DCHECK(success);
845 DCHECK(speculative_render_frame_host_);
846 navigation_rfh = speculative_render_frame_host_.get();
848 // Check if our current RFH is live.
849 if (!render_frame_host_->IsRenderFrameLive()) {
850 // The current RFH is not live. There's no reason to sit around with a
851 // sad tab or a newly created RFH while we wait for the navigation to
852 // complete. Just switch to the speculative RFH now and go back to normal.
853 // (Note that we don't care about on{before}unload handlers if the current
854 // RFH isn't live.)
855 CommitPending();
858 DCHECK(navigation_rfh &&
859 (navigation_rfh == render_frame_host_.get() ||
860 navigation_rfh == speculative_render_frame_host_.get()));
862 // If the RenderFrame that needs to navigate is not live (its process was just
863 // created or has crashed), initialize it.
864 if (!navigation_rfh->IsRenderFrameLive()) {
865 // Recreate the opener chain.
866 int opener_route_id =
867 CreateOpenerProxiesIfNeeded(navigation_rfh->GetSiteInstance());
868 if (!InitRenderView(navigation_rfh->render_view_host(), opener_route_id,
869 MSG_ROUTING_NONE, frame_tree_node_->IsMainFrame())) {
870 return nullptr;
873 if (navigation_rfh == render_frame_host_) {
874 // TODO(nasko): This is a very ugly hack. The Chrome extensions process
875 // manager still uses NotificationService and expects to see a
876 // RenderViewHost changed notification after WebContents and
877 // RenderFrameHostManager are completely initialized. This should be
878 // removed once the process manager moves away from NotificationService.
879 // See https://crbug.com/462682.
880 delegate_->NotifyMainFrameSwappedFromRenderManager(
881 nullptr, render_frame_host_->render_view_host());
885 return navigation_rfh;
888 // PlzNavigate
889 void RenderFrameHostManager::CleanUpNavigation() {
890 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
891 switches::kEnableBrowserSideNavigation));
892 speculative_web_ui_.reset();
893 should_reuse_web_ui_ = false;
894 if (speculative_render_frame_host_)
895 DiscardUnusedFrame(UnsetSpeculativeRenderFrameHost());
898 // PlzNavigate
899 scoped_ptr<RenderFrameHostImpl>
900 RenderFrameHostManager::UnsetSpeculativeRenderFrameHost() {
901 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
902 switches::kEnableBrowserSideNavigation));
903 speculative_render_frame_host_->GetProcess()->RemovePendingView();
904 return speculative_render_frame_host_.Pass();
907 void RenderFrameHostManager::OnDidStartLoading() {
908 for (const auto& pair : proxy_hosts_) {
909 pair.second->Send(
910 new FrameMsg_DidStartLoading(pair.second->GetRoutingID()));
914 void RenderFrameHostManager::OnDidStopLoading() {
915 for (const auto& pair : proxy_hosts_) {
916 pair.second->Send(new FrameMsg_DidStopLoading(pair.second->GetRoutingID()));
920 void RenderFrameHostManager::OnDidUpdateName(const std::string& name) {
921 // The window.name message may be sent outside of --site-per-process when
922 // report_frame_name_changes renderer preference is set (used by
923 // WebView). Don't send the update to proxies in those cases.
924 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
925 switches::kSitePerProcess))
926 return;
928 for (const auto& pair : proxy_hosts_) {
929 pair.second->Send(
930 new FrameMsg_DidUpdateName(pair.second->GetRoutingID(), name));
934 void RenderFrameHostManager::OnDidUpdateOrigin(const url::Origin& origin) {
935 if (!IsSwappedOutStateForbidden())
936 return;
938 for (const auto& pair : proxy_hosts_) {
939 pair.second->Send(
940 new FrameMsg_DidUpdateOrigin(pair.second->GetRoutingID(), origin));
944 void RenderFrameHostManager::Observe(
945 int type,
946 const NotificationSource& source,
947 const NotificationDetails& details) {
948 switch (type) {
949 case NOTIFICATION_RENDERER_PROCESS_CLOSED:
950 case NOTIFICATION_RENDERER_PROCESS_CLOSING:
951 RendererProcessClosing(
952 Source<RenderProcessHost>(source).ptr());
953 break;
955 default:
956 NOTREACHED();
960 RenderFrameHostManager::SiteInstanceDescriptor::SiteInstanceDescriptor(
961 BrowserContext* browser_context,
962 GURL dest_url,
963 bool related_to_current)
964 : existing_site_instance(nullptr),
965 new_is_related_to_current(related_to_current) {
966 new_site_url = SiteInstance::GetSiteForURL(browser_context, dest_url);
969 // static
970 bool RenderFrameHostManager::ClearProxiesInSiteInstance(
971 int32 site_instance_id,
972 FrameTreeNode* node) {
973 RenderFrameProxyHostMap::iterator iter =
974 node->render_manager()->proxy_hosts_.find(site_instance_id);
975 if (iter != node->render_manager()->proxy_hosts_.end()) {
976 RenderFrameProxyHost* proxy = iter->second;
977 // Delete the proxy. If it is for a main frame (and thus the RFH is stored
978 // in the proxy) and it was still pending swap out, move the RFH to the
979 // pending deletion list first.
980 if (node->IsMainFrame() &&
981 proxy->render_frame_host() &&
982 proxy->render_frame_host()->rfh_state() ==
983 RenderFrameHostImpl::STATE_PENDING_SWAP_OUT) {
984 DCHECK(!RenderFrameHostManager::IsSwappedOutStateForbidden());
985 scoped_ptr<RenderFrameHostImpl> swapped_out_rfh =
986 proxy->PassFrameHostOwnership();
987 node->render_manager()->MoveToPendingDeleteHosts(swapped_out_rfh.Pass());
989 delete proxy;
990 node->render_manager()->proxy_hosts_.erase(site_instance_id);
993 return true;
996 // static.
997 bool RenderFrameHostManager::ResetProxiesInSiteInstance(int32 site_instance_id,
998 FrameTreeNode* node) {
999 RenderFrameProxyHostMap::iterator iter =
1000 node->render_manager()->proxy_hosts_.find(site_instance_id);
1001 if (iter != node->render_manager()->proxy_hosts_.end())
1002 iter->second->set_render_frame_proxy_created(false);
1004 return true;
1007 bool RenderFrameHostManager::ShouldTransitionCrossSite() {
1008 // True for --site-per-process, which overrides both kSingleProcess and
1009 // kProcessPerTab.
1010 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1011 switches::kSitePerProcess))
1012 return true;
1014 // False in the single-process mode, as it makes RVHs to accumulate
1015 // in swapped_out_hosts_.
1016 // True if we are using process-per-site-instance (default) or
1017 // process-per-site (kProcessPerSite).
1018 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
1019 switches::kSingleProcess) &&
1020 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1021 switches::kProcessPerTab);
1024 bool RenderFrameHostManager::ShouldSwapBrowsingInstancesForNavigation(
1025 const GURL& current_effective_url,
1026 bool current_is_view_source_mode,
1027 SiteInstance* new_site_instance,
1028 const GURL& new_effective_url,
1029 bool new_is_view_source_mode) const {
1030 // If new_entry already has a SiteInstance, assume it is correct. We only
1031 // need to force a swap if it is in a different BrowsingInstance.
1032 if (new_site_instance) {
1033 return !new_site_instance->IsRelatedSiteInstance(
1034 render_frame_host_->GetSiteInstance());
1037 // Check for reasons to swap processes even if we are in a process model that
1038 // doesn't usually swap (e.g., process-per-tab). Any time we return true,
1039 // the new_entry will be rendered in a new SiteInstance AND BrowsingInstance.
1040 BrowserContext* browser_context =
1041 delegate_->GetControllerForRenderManager().GetBrowserContext();
1043 // Don't force a new BrowsingInstance for debug URLs that are handled in the
1044 // renderer process, like javascript: or chrome://crash.
1045 if (IsRendererDebugURL(new_effective_url))
1046 return false;
1048 // For security, we should transition between processes when one is a Web UI
1049 // page and one isn't.
1050 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1051 render_frame_host_->GetProcess()->GetID()) ||
1052 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1053 browser_context, current_effective_url)) {
1054 // If so, force a swap if destination is not an acceptable URL for Web UI.
1055 // Here, data URLs are never allowed.
1056 if (!WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
1057 browser_context, new_effective_url)) {
1058 return true;
1060 } else {
1061 // Force a swap if it's a Web UI URL.
1062 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1063 browser_context, new_effective_url)) {
1064 return true;
1068 // Check with the content client as well. Important to pass
1069 // current_effective_url here, which uses the SiteInstance's site if there is
1070 // no current_entry.
1071 if (GetContentClient()->browser()->ShouldSwapBrowsingInstancesForNavigation(
1072 render_frame_host_->GetSiteInstance(),
1073 current_effective_url, new_effective_url)) {
1074 return true;
1077 // We can't switch a RenderView between view source and non-view source mode
1078 // without screwing up the session history sometimes (when navigating between
1079 // "view-source:http://foo.com/" and "http://foo.com/", Blink doesn't treat
1080 // it as a new navigation). So require a BrowsingInstance switch.
1081 if (current_is_view_source_mode != new_is_view_source_mode)
1082 return true;
1084 return false;
1087 bool RenderFrameHostManager::ShouldReuseWebUI(
1088 const NavigationEntry* current_entry,
1089 const GURL& new_url) const {
1090 NavigationControllerImpl& controller =
1091 delegate_->GetControllerForRenderManager();
1092 return current_entry && web_ui_ &&
1093 (WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
1094 controller.GetBrowserContext(), current_entry->GetURL()) ==
1095 WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
1096 controller.GetBrowserContext(), new_url));
1099 SiteInstance* RenderFrameHostManager::GetSiteInstanceForNavigation(
1100 const GURL& dest_url,
1101 SiteInstance* source_instance,
1102 SiteInstance* dest_instance,
1103 SiteInstance* candidate_instance,
1104 ui::PageTransition transition,
1105 bool dest_is_restore,
1106 bool dest_is_view_source_mode) {
1107 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1109 // We do not currently swap processes for navigations in webview tag guests.
1110 if (current_instance->GetSiteURL().SchemeIs(kGuestScheme))
1111 return current_instance;
1113 // Determine if we need a new BrowsingInstance for this entry. If true, this
1114 // implies that it will get a new SiteInstance (and likely process), and that
1115 // other tabs in the current BrowsingInstance will be unable to script it.
1116 // This is used for cases that require a process swap even in the
1117 // process-per-tab model, such as WebUI pages.
1118 // TODO(clamy): Remove the dependency on the current entry.
1119 const NavigationEntry* current_entry =
1120 delegate_->GetLastCommittedNavigationEntryForRenderManager();
1121 BrowserContext* browser_context =
1122 delegate_->GetControllerForRenderManager().GetBrowserContext();
1123 const GURL& current_effective_url = current_entry ?
1124 SiteInstanceImpl::GetEffectiveURL(browser_context,
1125 current_entry->GetURL()) :
1126 render_frame_host_->GetSiteInstance()->GetSiteURL();
1127 bool current_is_view_source_mode = current_entry ?
1128 current_entry->IsViewSourceMode() : dest_is_view_source_mode;
1129 bool force_swap = ShouldSwapBrowsingInstancesForNavigation(
1130 current_effective_url,
1131 current_is_view_source_mode,
1132 dest_instance,
1133 SiteInstanceImpl::GetEffectiveURL(browser_context, dest_url),
1134 dest_is_view_source_mode);
1135 SiteInstanceDescriptor new_instance_descriptor =
1136 SiteInstanceDescriptor(current_instance);
1137 if (ShouldTransitionCrossSite() || force_swap) {
1138 new_instance_descriptor = DetermineSiteInstanceForURL(
1139 dest_url, source_instance, current_instance, dest_instance, transition,
1140 dest_is_restore, dest_is_view_source_mode, force_swap);
1143 SiteInstance* new_instance =
1144 ConvertToSiteInstance(new_instance_descriptor, candidate_instance);
1146 // If |force_swap| is true, we must use a different SiteInstance than the
1147 // current one. If we didn't, we would have two RenderFrameHosts in the same
1148 // SiteInstance and the same frame, resulting in page_id conflicts for their
1149 // NavigationEntries.
1150 if (force_swap)
1151 CHECK_NE(new_instance, current_instance);
1152 return new_instance;
1155 RenderFrameHostManager::SiteInstanceDescriptor
1156 RenderFrameHostManager::DetermineSiteInstanceForURL(
1157 const GURL& dest_url,
1158 SiteInstance* source_instance,
1159 SiteInstance* current_instance,
1160 SiteInstance* dest_instance,
1161 ui::PageTransition transition,
1162 bool dest_is_restore,
1163 bool dest_is_view_source_mode,
1164 bool force_browsing_instance_swap) {
1165 SiteInstanceImpl* current_instance_impl =
1166 static_cast<SiteInstanceImpl*>(current_instance);
1167 NavigationControllerImpl& controller =
1168 delegate_->GetControllerForRenderManager();
1169 BrowserContext* browser_context = controller.GetBrowserContext();
1171 // If the entry has an instance already we should use it.
1172 if (dest_instance) {
1173 // If we are forcing a swap, this should be in a different BrowsingInstance.
1174 if (force_browsing_instance_swap) {
1175 CHECK(!dest_instance->IsRelatedSiteInstance(
1176 render_frame_host_->GetSiteInstance()));
1178 return SiteInstanceDescriptor(dest_instance);
1181 // If a swap is required, we need to force the SiteInstance AND
1182 // BrowsingInstance to be different ones, using CreateForURL.
1183 if (force_browsing_instance_swap)
1184 return SiteInstanceDescriptor(browser_context, dest_url, false);
1186 // (UGLY) HEURISTIC, process-per-site only:
1188 // If this navigation is generated, then it probably corresponds to a search
1189 // query. Given that search results typically lead to users navigating to
1190 // other sites, we don't really want to use the search engine hostname to
1191 // determine the site instance for this navigation.
1193 // NOTE: This can be removed once we have a way to transition between
1194 // RenderViews in response to a link click.
1196 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1197 switches::kProcessPerSite) &&
1198 ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_GENERATED)) {
1199 return SiteInstanceDescriptor(current_instance_impl);
1202 // If we haven't used our SiteInstance (and thus RVH) yet, then we can use it
1203 // for this entry. We won't commit the SiteInstance to this site until the
1204 // navigation commits (in DidNavigate), unless the navigation entry was
1205 // restored or it's a Web UI as described below.
1206 if (!current_instance_impl->HasSite()) {
1207 // If we've already created a SiteInstance for our destination, we don't
1208 // want to use this unused SiteInstance; use the existing one. (We don't
1209 // do this check if the current_instance has a site, because for now, we
1210 // want to compare against the current URL and not the SiteInstance's site.
1211 // In this case, there is no current URL, so comparing against the site is
1212 // ok. See additional comments below.)
1214 // Also, if the URL should use process-per-site mode and there is an
1215 // existing process for the site, we should use it. We can call
1216 // GetRelatedSiteInstance() for this, which will eagerly set the site and
1217 // thus use the correct process.
1218 bool use_process_per_site =
1219 RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) &&
1220 RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url);
1221 if (current_instance_impl->HasRelatedSiteInstance(dest_url) ||
1222 use_process_per_site) {
1223 return SiteInstanceDescriptor(browser_context, dest_url, true);
1226 // For extensions, Web UI URLs (such as the new tab page), and apps we do
1227 // not want to use the |current_instance_impl| if it has no site, since it
1228 // will have a RenderProcessHost of PRIV_NORMAL. Create a new SiteInstance
1229 // for this URL instead (with the correct process type).
1230 if (current_instance_impl->HasWrongProcessForURL(dest_url))
1231 return SiteInstanceDescriptor(browser_context, dest_url, true);
1233 // View-source URLs must use a new SiteInstance and BrowsingInstance.
1234 // TODO(nasko): This is the same condition as later in the function. This
1235 // should be taken into account when refactoring this method as part of
1236 // http://crbug.com/123007.
1237 if (dest_is_view_source_mode)
1238 return SiteInstanceDescriptor(browser_context, dest_url, false);
1240 // If we are navigating from a blank SiteInstance to a WebUI, make sure we
1241 // create a new SiteInstance.
1242 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1243 browser_context, dest_url)) {
1244 return SiteInstanceDescriptor(browser_context, dest_url, false);
1247 // Normally the "site" on the SiteInstance is set lazily when the load
1248 // actually commits. This is to support better process sharing in case
1249 // the site redirects to some other site: we want to use the destination
1250 // site in the site instance.
1252 // In the case of session restore, as it loads all the pages immediately
1253 // we need to set the site first, otherwise after a restore none of the
1254 // pages would share renderers in process-per-site.
1256 // The embedder can request some urls never to be assigned to SiteInstance
1257 // through the ShouldAssignSiteForURL() content client method, so that
1258 // renderers created for particular chrome urls (e.g. the chrome-native://
1259 // scheme) can be reused for subsequent navigations in the same WebContents.
1260 // See http://crbug.com/386542.
1261 if (dest_is_restore &&
1262 GetContentClient()->browser()->ShouldAssignSiteForURL(dest_url)) {
1263 current_instance_impl->SetSite(dest_url);
1266 return SiteInstanceDescriptor(current_instance_impl);
1269 // Otherwise, only create a new SiteInstance for a cross-process navigation.
1271 // TODO(creis): Once we intercept links and script-based navigations, we
1272 // will be able to enforce that all entries in a SiteInstance actually have
1273 // the same site, and it will be safe to compare the URL against the
1274 // SiteInstance's site, as follows:
1275 // const GURL& current_url = current_instance_impl->site();
1276 // For now, though, we're in a hybrid model where you only switch
1277 // SiteInstances if you type in a cross-site URL. This means we have to
1278 // compare the entry's URL to the last committed entry's URL.
1279 NavigationEntry* current_entry = controller.GetLastCommittedEntry();
1280 if (interstitial_page_) {
1281 // The interstitial is currently the last committed entry, but we want to
1282 // compare against the last non-interstitial entry.
1283 current_entry = controller.GetEntryAtOffset(-1);
1286 // View-source URLs must use a new SiteInstance and BrowsingInstance.
1287 // We don't need a swap when going from view-source to a debug URL like
1288 // chrome://crash, however.
1289 // TODO(creis): Refactor this method so this duplicated code isn't needed.
1290 // See http://crbug.com/123007.
1291 if (current_entry &&
1292 current_entry->IsViewSourceMode() != dest_is_view_source_mode &&
1293 !IsRendererDebugURL(dest_url)) {
1294 return SiteInstanceDescriptor(browser_context, dest_url, false);
1297 // Use the source SiteInstance in case of data URLs or about:blank pages,
1298 // because the content is then controlled and/or scriptable by the source
1299 // SiteInstance.
1300 GURL about_blank(url::kAboutBlankURL);
1301 if (source_instance &&
1302 (dest_url == about_blank || dest_url.scheme() == url::kDataScheme)) {
1303 return SiteInstanceDescriptor(source_instance);
1306 // Use the current SiteInstance for same site navigations, as long as the
1307 // process type is correct. (The URL may have been installed as an app since
1308 // the last time we visited it.)
1309 const GURL& current_url =
1310 GetCurrentURLForSiteInstance(current_instance_impl, current_entry);
1311 if (SiteInstance::IsSameWebSite(browser_context, current_url, dest_url) &&
1312 !current_instance_impl->HasWrongProcessForURL(dest_url)) {
1313 return SiteInstanceDescriptor(current_instance_impl);
1316 // Start the new renderer in a new SiteInstance, but in the current
1317 // BrowsingInstance. It is important to immediately give this new
1318 // SiteInstance to a RenderViewHost (if it is different than our current
1319 // SiteInstance), so that it is ref counted. This will happen in
1320 // CreateRenderView.
1321 return SiteInstanceDescriptor(browser_context, dest_url, true);
1324 SiteInstance* RenderFrameHostManager::ConvertToSiteInstance(
1325 const SiteInstanceDescriptor& descriptor,
1326 SiteInstance* candidate_instance) {
1327 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1329 // Note: If the |candidate_instance| matches the descriptor, it will already
1330 // be set to |descriptor.existing_site_instance|.
1331 if (descriptor.existing_site_instance)
1332 return descriptor.existing_site_instance;
1334 // Note: If the |candidate_instance| matches the descriptor,
1335 // GetRelatedSiteInstance will return it.
1336 if (descriptor.new_is_related_to_current)
1337 return current_instance->GetRelatedSiteInstance(descriptor.new_site_url);
1339 // At this point we know an unrelated site instance must be returned. First
1340 // check if the candidate matches.
1341 if (candidate_instance &&
1342 !current_instance->IsRelatedSiteInstance(candidate_instance) &&
1343 candidate_instance->GetSiteURL() == descriptor.new_site_url) {
1344 return candidate_instance;
1347 // Otherwise return a newly created one.
1348 return SiteInstance::CreateForURL(
1349 delegate_->GetControllerForRenderManager().GetBrowserContext(),
1350 descriptor.new_site_url);
1353 const GURL& RenderFrameHostManager::GetCurrentURLForSiteInstance(
1354 SiteInstance* current_instance, NavigationEntry* current_entry) {
1355 // If this is a subframe that is potentially out of process from its parent,
1356 // don't consider using current_entry's url for SiteInstance selection, since
1357 // current_entry's url is for the main frame and may be in a different site
1358 // than this frame.
1359 // TODO(creis): Remove this when we can check the FrameNavigationEntry's url.
1360 // See http://crbug.com/369654
1361 if (!frame_tree_node_->IsMainFrame() &&
1362 base::CommandLine::ForCurrentProcess()->HasSwitch(
1363 switches::kSitePerProcess))
1364 return frame_tree_node_->current_url();
1366 // If there is no last non-interstitial entry (and current_instance already
1367 // has a site), then we must have been opened from another tab. We want
1368 // to compare against the URL of the page that opened us, but we can't
1369 // get to it directly. The best we can do is check against the site of
1370 // the SiteInstance. This will be correct when we intercept links and
1371 // script-based navigations, but for now, it could place some pages in a
1372 // new process unnecessarily. We should only hit this case if a page tries
1373 // to open a new tab to an interstitial-inducing URL, and then navigates
1374 // the page to a different same-site URL. (This seems very unlikely in
1375 // practice.)
1376 if (current_entry)
1377 return current_entry->GetURL();
1378 return current_instance->GetSiteURL();
1381 void RenderFrameHostManager::CreatePendingRenderFrameHost(
1382 SiteInstance* old_instance,
1383 SiteInstance* new_instance,
1384 bool is_main_frame) {
1385 int create_render_frame_flags = 0;
1386 if (is_main_frame)
1387 create_render_frame_flags |= CREATE_RF_FOR_MAIN_FRAME_NAVIGATION;
1389 if (delegate_->IsHidden())
1390 create_render_frame_flags |= CREATE_RF_HIDDEN;
1392 if (pending_render_frame_host_)
1393 CancelPending();
1395 // The process for the new SiteInstance may (if we're sharing a process with
1396 // another host that already initialized it) or may not (we have our own
1397 // process or the existing process crashed) have been initialized. Calling
1398 // Init multiple times will be ignored, so this is safe.
1399 if (!new_instance->GetProcess()->Init())
1400 return;
1402 int opener_route_id = CreateProxiesForNewRenderFrameHost(
1403 old_instance, new_instance, &create_render_frame_flags);
1405 // Create a non-swapped-out RFH with the given opener.
1406 pending_render_frame_host_ =
1407 CreateRenderFrame(new_instance, pending_web_ui(), opener_route_id,
1408 create_render_frame_flags, nullptr);
1411 int RenderFrameHostManager::CreateProxiesForNewRenderFrameHost(
1412 SiteInstance* old_instance,
1413 SiteInstance* new_instance,
1414 int* create_render_frame_flags) {
1415 int opener_route_id = MSG_ROUTING_NONE;
1416 // Only create opener proxies if they are in the same BrowsingInstance.
1417 if (new_instance->IsRelatedSiteInstance(old_instance))
1418 opener_route_id = CreateOpenerProxiesIfNeeded(new_instance);
1419 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1420 switches::kSitePerProcess)) {
1421 // Ensure that the frame tree has RenderFrameProxyHosts for the new
1422 // SiteInstance in all nodes except the current one. We do this for all
1423 // frames in the tree, whether they are in the same BrowsingInstance or not.
1424 // We will still check whether two frames are in the same BrowsingInstance
1425 // before we allow them to interact (e.g., postMessage).
1426 frame_tree_node_->frame_tree()->CreateProxiesForSiteInstance(
1427 frame_tree_node_, new_instance);
1428 // RenderFrames in different processes from their parent RenderFrames
1429 // in the frame tree require RenderWidgets for rendering and processing
1430 // input events.
1431 if (frame_tree_node_->parent() &&
1432 frame_tree_node_->parent()->current_frame_host()->GetSiteInstance() !=
1433 new_instance)
1434 *create_render_frame_flags |= CREATE_RF_NEEDS_RENDER_WIDGET_HOST;
1436 return opener_route_id;
1439 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::CreateRenderFrameHost(
1440 SiteInstance* site_instance,
1441 int view_routing_id,
1442 int frame_routing_id,
1443 int flags) {
1444 if (frame_routing_id == MSG_ROUTING_NONE)
1445 frame_routing_id = site_instance->GetProcess()->GetNextRoutingID();
1447 bool swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
1448 bool hidden = !!(flags & CREATE_RF_HIDDEN);
1450 // Create a RVH for main frames, or find the existing one for subframes.
1451 FrameTree* frame_tree = frame_tree_node_->frame_tree();
1452 RenderViewHostImpl* render_view_host = nullptr;
1453 if (frame_tree_node_->IsMainFrame()) {
1454 render_view_host = frame_tree->CreateRenderViewHost(
1455 site_instance, view_routing_id, frame_routing_id, swapped_out, hidden);
1456 } else {
1457 render_view_host = frame_tree->GetRenderViewHost(site_instance);
1459 CHECK(render_view_host);
1462 // TODO(creis): Pass hidden to RFH.
1463 scoped_ptr<RenderFrameHostImpl> render_frame_host = make_scoped_ptr(
1464 RenderFrameHostFactory::Create(
1465 site_instance, render_view_host, render_frame_delegate_,
1466 render_widget_delegate_, frame_tree, frame_tree_node_,
1467 frame_routing_id, flags).release());
1468 return render_frame_host.Pass();
1471 // PlzNavigate
1472 bool RenderFrameHostManager::CreateSpeculativeRenderFrameHost(
1473 const GURL& url,
1474 SiteInstance* old_instance,
1475 SiteInstance* new_instance,
1476 int bindings) {
1477 CHECK(new_instance);
1478 CHECK_NE(old_instance, new_instance);
1479 CHECK(!should_reuse_web_ui_);
1481 // Note: |speculative_web_ui_| must be initialized before starting the
1482 // |speculative_render_frame_host_| creation steps otherwise the WebUI
1483 // won't be properly initialized.
1484 speculative_web_ui_ = CreateWebUI(url, bindings);
1486 // The process for the new SiteInstance may (if we're sharing a process with
1487 // another host that already initialized it) or may not (we have our own
1488 // process or the existing process crashed) have been initialized. Calling
1489 // Init multiple times will be ignored, so this is safe.
1490 if (!new_instance->GetProcess()->Init())
1491 return false;
1493 int create_render_frame_flags = 0;
1494 int opener_route_id = CreateProxiesForNewRenderFrameHost(
1495 old_instance, new_instance, &create_render_frame_flags);
1497 if (frame_tree_node_->IsMainFrame())
1498 create_render_frame_flags |= CREATE_RF_FOR_MAIN_FRAME_NAVIGATION;
1499 if (delegate_->IsHidden())
1500 create_render_frame_flags |= CREATE_RF_HIDDEN;
1501 speculative_render_frame_host_ =
1502 CreateRenderFrame(new_instance, speculative_web_ui_.get(),
1503 opener_route_id, create_render_frame_flags, nullptr);
1505 if (!speculative_render_frame_host_) {
1506 speculative_web_ui_.reset();
1507 return false;
1509 return true;
1512 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::CreateRenderFrame(
1513 SiteInstance* instance,
1514 WebUIImpl* web_ui,
1515 int opener_route_id,
1516 int flags,
1517 int* view_routing_id_ptr) {
1518 bool swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
1519 bool swapped_out_forbidden = IsSwappedOutStateForbidden();
1520 bool is_site_per_process = base::CommandLine::ForCurrentProcess()->HasSwitch(
1521 switches::kSitePerProcess);
1523 CHECK(instance);
1524 CHECK_IMPLIES(swapped_out_forbidden, !swapped_out);
1525 CHECK_IMPLIES(!is_site_per_process, frame_tree_node_->IsMainFrame());
1527 // Swapped out views should always be hidden.
1528 DCHECK_IMPLIES(swapped_out, (flags & CREATE_RF_HIDDEN));
1530 scoped_ptr<RenderFrameHostImpl> new_render_frame_host;
1531 bool success = true;
1532 if (view_routing_id_ptr)
1533 *view_routing_id_ptr = MSG_ROUTING_NONE;
1535 // We are creating a pending, speculative or swapped out RFH here. We should
1536 // never create it in the same SiteInstance as our current RFH.
1537 CHECK_NE(render_frame_host_->GetSiteInstance(), instance);
1539 // Check if we've already created an RFH for this SiteInstance. If so, try
1540 // to re-use the existing one, which has already been initialized. We'll
1541 // remove it from the list of proxy hosts below if it will be active.
1542 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1543 if (proxy && proxy->render_frame_host()) {
1544 CHECK(!swapped_out_forbidden);
1545 if (view_routing_id_ptr)
1546 *view_routing_id_ptr = proxy->GetRenderViewHost()->GetRoutingID();
1547 // Delete the existing RenderFrameProxyHost, but reuse the RenderFrameHost.
1548 // Prevent the process from exiting while we're trying to use it.
1549 if (!swapped_out) {
1550 new_render_frame_host = proxy->PassFrameHostOwnership();
1551 new_render_frame_host->GetProcess()->AddPendingView();
1553 proxy_hosts_.erase(instance->GetId());
1554 delete proxy;
1556 } else {
1557 // Create a new RenderFrameHost if we don't find an existing one.
1558 new_render_frame_host = CreateRenderFrameHost(instance, MSG_ROUTING_NONE,
1559 MSG_ROUTING_NONE, flags);
1560 RenderViewHostImpl* render_view_host =
1561 new_render_frame_host->render_view_host();
1562 int proxy_routing_id = MSG_ROUTING_NONE;
1564 // Prevent the process from exiting while we're trying to navigate in it.
1565 // Otherwise, if the new RFH is swapped out already, store it.
1566 if (!swapped_out) {
1567 new_render_frame_host->GetProcess()->AddPendingView();
1568 } else {
1569 proxy = new RenderFrameProxyHost(
1570 new_render_frame_host->GetSiteInstance(),
1571 new_render_frame_host->render_view_host(), frame_tree_node_);
1572 proxy_hosts_[instance->GetId()] = proxy;
1573 proxy_routing_id = proxy->GetRoutingID();
1574 proxy->TakeFrameHostOwnership(new_render_frame_host.Pass());
1577 success =
1578 InitRenderView(render_view_host, opener_route_id, proxy_routing_id,
1579 !!(flags & CREATE_RF_FOR_MAIN_FRAME_NAVIGATION));
1580 if (success) {
1581 // Remember that InitRenderView also created the RenderFrameProxy.
1582 if (swapped_out)
1583 proxy->set_render_frame_proxy_created(true);
1584 if (frame_tree_node_->IsMainFrame()) {
1585 // Don't show the main frame's view until we get a DidNavigate from it.
1586 // Only the RenderViewHost for the top-level RenderFrameHost has a
1587 // RenderWidgetHostView; RenderWidgetHosts for out-of-process iframes
1588 // will be created later and hidden.
1589 if (render_view_host->GetView())
1590 render_view_host->GetView()->Hide();
1592 // RenderViewHost for |instance| might exist prior to calling
1593 // CreateRenderFrame. In such a case, InitRenderView will not create the
1594 // RenderFrame in the renderer process and it needs to be done
1595 // explicitly.
1596 if (swapped_out_forbidden) {
1597 // Init the RFH, so a RenderFrame is created in the renderer.
1598 DCHECK(new_render_frame_host);
1599 success = InitRenderFrame(new_render_frame_host.get());
1603 if (success) {
1604 if (view_routing_id_ptr)
1605 *view_routing_id_ptr = render_view_host->GetRoutingID();
1609 // When a new RenderView is created by the renderer process, the new
1610 // WebContents gets a RenderViewHost in the SiteInstance of its opener
1611 // WebContents. If not used in the first navigation, this RVH is swapped out
1612 // and is not granted bindings, so we may need to grant them when swapping it
1613 // in.
1614 if (web_ui && !new_render_frame_host->GetProcess()->IsForGuestsOnly()) {
1615 int required_bindings = web_ui->GetBindings();
1616 RenderViewHost* render_view_host =
1617 new_render_frame_host->render_view_host();
1618 if ((render_view_host->GetEnabledBindings() & required_bindings) !=
1619 required_bindings) {
1620 render_view_host->AllowBindings(required_bindings);
1624 // Returns the new RFH if it isn't swapped out.
1625 if (success && !swapped_out) {
1626 DCHECK(new_render_frame_host->GetSiteInstance() == instance);
1627 return new_render_frame_host.Pass();
1629 return nullptr;
1632 int RenderFrameHostManager::CreateRenderFrameProxy(SiteInstance* instance) {
1633 // A RenderFrameProxyHost should never be created in the same SiteInstance as
1634 // the current RFH.
1635 CHECK(instance);
1636 CHECK_NE(instance, render_frame_host_->GetSiteInstance());
1638 RenderViewHostImpl* render_view_host = nullptr;
1640 // Ensure a RenderViewHost exists for |instance|, as it creates the page
1641 // level structure in Blink.
1642 if (RenderFrameHostManager::IsSwappedOutStateForbidden()) {
1643 render_view_host =
1644 frame_tree_node_->frame_tree()->GetRenderViewHost(instance);
1645 if (!render_view_host) {
1646 CHECK(frame_tree_node_->IsMainFrame());
1647 render_view_host = frame_tree_node_->frame_tree()->CreateRenderViewHost(
1648 instance, MSG_ROUTING_NONE, MSG_ROUTING_NONE, true, true);
1652 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1653 if (proxy && proxy->is_render_frame_proxy_live())
1654 return proxy->GetRoutingID();
1656 if (!proxy) {
1657 proxy = new RenderFrameProxyHost(
1658 instance, render_view_host, frame_tree_node_);
1659 proxy_hosts_[instance->GetId()] = proxy;
1662 if (RenderFrameHostManager::IsSwappedOutStateForbidden() &&
1663 frame_tree_node_->IsMainFrame()) {
1664 InitRenderView(
1665 render_view_host, MSG_ROUTING_NONE, proxy->GetRoutingID(), true);
1666 proxy->set_render_frame_proxy_created(true);
1667 } else {
1668 proxy->InitRenderFrameProxy();
1671 return proxy->GetRoutingID();
1674 void RenderFrameHostManager::CreateProxiesForChildFrame(FrameTreeNode* child) {
1675 for (const auto& pair : proxy_hosts_) {
1676 child->render_manager()->CreateRenderFrameProxy(
1677 pair.second->GetSiteInstance());
1681 void RenderFrameHostManager::EnsureRenderViewInitialized(
1682 RenderViewHostImpl* render_view_host,
1683 SiteInstance* instance) {
1684 DCHECK(frame_tree_node_->IsMainFrame());
1686 if (render_view_host->IsRenderViewLive())
1687 return;
1689 // Recreate the opener chain.
1690 int opener_route_id = CreateOpenerProxiesIfNeeded(instance);
1692 // If the proxy in |instance| doesn't exist, this RenderView is not swapped
1693 // out and shouldn't be reinitialized here.
1694 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1695 if (!proxy)
1696 return;
1698 InitRenderView(render_view_host, opener_route_id, proxy->GetRoutingID(),
1699 false);
1700 proxy->set_render_frame_proxy_created(true);
1703 void RenderFrameHostManager::CreateOuterDelegateProxy(
1704 SiteInstance* outer_contents_site_instance,
1705 RenderFrameHostImpl* render_frame_host) {
1706 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1707 switches::kSitePerProcess));
1708 RenderFrameProxyHost* proxy = new RenderFrameProxyHost(
1709 outer_contents_site_instance, nullptr, frame_tree_node_);
1710 proxy_hosts_[outer_contents_site_instance->GetId()] = proxy;
1712 // Swap the outer WebContents's frame with the proxy to inner WebContents.
1714 // We are in the outer WebContents, and its FrameTree would never see
1715 // a load start for any of its inner WebContents. Eventually, that also makes
1716 // the FrameTree never see the matching load stop. Therefore, we always pass
1717 // false to |is_loading| below.
1718 // TODO(lazyboy): This |is_loading| behavior might not be what we want,
1719 // investigate and fix.
1720 render_frame_host->Send(new FrameMsg_SwapOut(
1721 render_frame_host->GetRoutingID(), proxy->GetRoutingID(),
1722 false /* is_loading */, FrameReplicationState()));
1723 proxy->set_render_frame_proxy_created(true);
1726 void RenderFrameHostManager::SetRWHViewForInnerContents(
1727 RenderWidgetHostView* child_rwhv) {
1728 DCHECK(ForInnerDelegate());
1729 GetProxyToOuterDelegate()->SetChildRWHView(child_rwhv);
1732 bool RenderFrameHostManager::InitRenderView(
1733 RenderViewHostImpl* render_view_host,
1734 int opener_route_id,
1735 int proxy_routing_id,
1736 bool for_main_frame_navigation) {
1737 // Ensure the renderer process is initialized before creating the
1738 // RenderView.
1739 if (!render_view_host->GetProcess()->Init())
1740 return false;
1742 // We may have initialized this RenderViewHost for another RenderFrameHost.
1743 if (render_view_host->IsRenderViewLive())
1744 return true;
1746 // If the ongoing navigation is to a WebUI and the RenderView is not in a
1747 // guest process, tell the RenderViewHost about any bindings it will need
1748 // enabled.
1749 WebUIImpl* dest_web_ui = nullptr;
1750 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1751 switches::kEnableBrowserSideNavigation)) {
1752 dest_web_ui =
1753 should_reuse_web_ui_ ? web_ui_.get() : speculative_web_ui_.get();
1754 } else {
1755 dest_web_ui = pending_web_ui();
1757 if (dest_web_ui && !render_view_host->GetProcess()->IsForGuestsOnly()) {
1758 render_view_host->AllowBindings(dest_web_ui->GetBindings());
1759 } else {
1760 // Ensure that we don't create an unprivileged RenderView in a WebUI-enabled
1761 // process unless it's swapped out.
1762 if (render_view_host->is_active()) {
1763 CHECK(!ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1764 render_view_host->GetProcess()->GetID()));
1768 return delegate_->CreateRenderViewForRenderManager(
1769 render_view_host,
1770 opener_route_id,
1771 proxy_routing_id,
1772 frame_tree_node_->current_replication_state(),
1773 for_main_frame_navigation);
1776 bool RenderFrameHostManager::InitRenderFrame(
1777 RenderFrameHostImpl* render_frame_host) {
1778 if (render_frame_host->IsRenderFrameLive())
1779 return true;
1781 int parent_routing_id = MSG_ROUTING_NONE;
1782 int previous_sibling_routing_id = MSG_ROUTING_NONE;
1783 int proxy_routing_id = MSG_ROUTING_NONE;
1785 if (frame_tree_node_->parent()) {
1786 parent_routing_id = frame_tree_node_->parent()->render_manager()->
1787 GetRoutingIdForSiteInstance(render_frame_host->GetSiteInstance());
1788 CHECK_NE(parent_routing_id, MSG_ROUTING_NONE);
1791 // At this point, all RenderFrameProxies for sibling frames have already been
1792 // created, including any proxies that come after this frame. To preserve
1793 // correct order for indexed window access (e.g., window.frames[1]), pass the
1794 // previous sibling frame so that this frame is correctly inserted into the
1795 // frame tree on the renderer side.
1796 FrameTreeNode* previous_sibling = frame_tree_node_->PreviousSibling();
1797 if (previous_sibling) {
1798 previous_sibling_routing_id =
1799 previous_sibling->render_manager()->GetRoutingIdForSiteInstance(
1800 render_frame_host->GetSiteInstance());
1801 CHECK_NE(previous_sibling_routing_id, MSG_ROUTING_NONE);
1804 // Check whether there is an existing proxy for this frame in this
1805 // SiteInstance. If there is, the new RenderFrame needs to be able to find
1806 // the proxy it is replacing, so that it can fully initialize itself.
1807 // NOTE: This is the only time that a RenderFrameProxyHost can be in the same
1808 // SiteInstance as its RenderFrameHost. This is only the case until the
1809 // RenderFrameHost commits, at which point it will replace and delete the
1810 // RenderFrameProxyHost.
1811 RenderFrameProxyHost* existing_proxy =
1812 GetRenderFrameProxyHost(render_frame_host->GetSiteInstance());
1813 if (existing_proxy) {
1814 proxy_routing_id = existing_proxy->GetRoutingID();
1815 CHECK_NE(proxy_routing_id, MSG_ROUTING_NONE);
1816 if (!existing_proxy->is_render_frame_proxy_live())
1817 existing_proxy->InitRenderFrameProxy();
1819 return delegate_->CreateRenderFrameForRenderManager(
1820 render_frame_host, parent_routing_id, previous_sibling_routing_id,
1821 proxy_routing_id);
1824 int RenderFrameHostManager::GetRoutingIdForSiteInstance(
1825 SiteInstance* site_instance) {
1826 if (render_frame_host_->GetSiteInstance() == site_instance)
1827 return render_frame_host_->GetRoutingID();
1829 RenderFrameProxyHostMap::iterator iter =
1830 proxy_hosts_.find(site_instance->GetId());
1831 if (iter != proxy_hosts_.end())
1832 return iter->second->GetRoutingID();
1834 return MSG_ROUTING_NONE;
1837 void RenderFrameHostManager::CommitPending() {
1838 TRACE_EVENT1("navigation", "RenderFrameHostManager::CommitPending",
1839 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
1840 bool browser_side_navigation =
1841 base::CommandLine::ForCurrentProcess()->HasSwitch(
1842 switches::kEnableBrowserSideNavigation);
1844 // First check whether we're going to want to focus the location bar after
1845 // this commit. We do this now because the navigation hasn't formally
1846 // committed yet, so if we've already cleared |pending_web_ui_| the call chain
1847 // this triggers won't be able to figure out what's going on.
1848 bool will_focus_location_bar = delegate_->FocusLocationBarByDefault();
1850 // Next commit the Web UI, if any. Either replace |web_ui_| with
1851 // |pending_web_ui_|, or clear |web_ui_| if there is no pending WebUI, or
1852 // leave |web_ui_| as is if reusing it.
1853 DCHECK(!(pending_web_ui_ && pending_and_current_web_ui_));
1854 if (pending_web_ui_ || speculative_web_ui_) {
1855 DCHECK(!should_reuse_web_ui_);
1856 web_ui_.reset(browser_side_navigation ? speculative_web_ui_.release()
1857 : pending_web_ui_.release());
1858 } else if (pending_and_current_web_ui_ || should_reuse_web_ui_) {
1859 if (browser_side_navigation) {
1860 DCHECK(web_ui_);
1861 should_reuse_web_ui_ = false;
1862 } else {
1863 DCHECK_EQ(pending_and_current_web_ui_.get(), web_ui_.get());
1864 pending_and_current_web_ui_.reset();
1866 } else {
1867 web_ui_.reset();
1869 DCHECK(!speculative_web_ui_);
1870 DCHECK(!should_reuse_web_ui_);
1872 // It's possible for the pending_render_frame_host_ to be nullptr when we
1873 // aren't crossing process boundaries. If so, we just needed to handle the Web
1874 // UI committing above and we're done.
1875 if (!pending_render_frame_host_ && !speculative_render_frame_host_) {
1876 if (will_focus_location_bar)
1877 delegate_->SetFocusToLocationBar(false);
1878 return;
1881 // Remember if the page was focused so we can focus the new renderer in
1882 // that case.
1883 bool focus_render_view = !will_focus_location_bar &&
1884 render_frame_host_->GetView() &&
1885 render_frame_host_->GetView()->HasFocus();
1887 bool is_main_frame = frame_tree_node_->IsMainFrame();
1889 // Swap in the pending or speculative frame and make it active. Also ensure
1890 // the FrameTree stays in sync.
1891 scoped_ptr<RenderFrameHostImpl> old_render_frame_host;
1892 if (!browser_side_navigation) {
1893 DCHECK(!speculative_render_frame_host_);
1894 old_render_frame_host =
1895 SetRenderFrameHost(pending_render_frame_host_.Pass());
1896 } else {
1897 // PlzNavigate
1898 DCHECK(speculative_render_frame_host_);
1899 old_render_frame_host =
1900 SetRenderFrameHost(speculative_render_frame_host_.Pass());
1903 // Remove the children of the old frame from the tree.
1904 frame_tree_node_->ResetForNewProcess();
1906 // The process will no longer try to exit, so we can decrement the count.
1907 render_frame_host_->GetProcess()->RemovePendingView();
1909 // Show the new view (or a sad tab) if necessary.
1910 bool new_rfh_has_view = !!render_frame_host_->GetView();
1911 if (!delegate_->IsHidden() && new_rfh_has_view) {
1912 // In most cases, we need to show the new view.
1913 render_frame_host_->GetView()->Show();
1915 if (!new_rfh_has_view) {
1916 // If the view is gone, then this RenderViewHost died while it was hidden.
1917 // We ignored the RenderProcessGone call at the time, so we should send it
1918 // now to make sure the sad tab shows up, etc.
1919 DCHECK(!render_frame_host_->IsRenderFrameLive());
1920 DCHECK(!render_frame_host_->render_view_host()->IsRenderViewLive());
1921 delegate_->RenderProcessGoneFromRenderManager(
1922 render_frame_host_->render_view_host());
1925 // For top-level frames, also hide the old RenderViewHost's view.
1926 // TODO(creis): As long as show/hide are on RVH, we don't want to hide on
1927 // subframe navigations or we will interfere with the top-level frame.
1928 if (is_main_frame && old_render_frame_host->render_view_host()->GetView())
1929 old_render_frame_host->render_view_host()->GetView()->Hide();
1931 // Make sure the size is up to date. (Fix for bug 1079768.)
1932 delegate_->UpdateRenderViewSizeForRenderManager();
1934 if (will_focus_location_bar) {
1935 delegate_->SetFocusToLocationBar(false);
1936 } else if (focus_render_view && render_frame_host_->GetView()) {
1937 render_frame_host_->GetView()->Focus();
1940 // Notify that we've swapped RenderFrameHosts. We do this before shutting down
1941 // the RFH so that we can clean up RendererResources related to the RFH first.
1942 delegate_->NotifySwappedFromRenderManager(
1943 old_render_frame_host.get(), render_frame_host_.get(), is_main_frame);
1945 // The RenderViewHost keeps track of the main RenderFrameHost routing id.
1946 // If this is committing a main frame navigation, update it and set the
1947 // routing id in the RenderViewHost associated with the old RenderFrameHost
1948 // to MSG_ROUTING_NONE.
1949 if (is_main_frame && RenderFrameHostManager::IsSwappedOutStateForbidden()) {
1950 render_frame_host_->render_view_host()->set_main_frame_routing_id(
1951 render_frame_host_->routing_id());
1952 old_render_frame_host->render_view_host()->set_main_frame_routing_id(
1953 MSG_ROUTING_NONE);
1956 // Swap out the old frame now that the new one is visible.
1957 // This will swap it out and then put it on the proxy list (if there are other
1958 // active views in its SiteInstance) or schedule it for deletion when the swap
1959 // out ack arrives (or immediately if the process isn't live).
1960 // In the --site-per-process case, old subframe RFHs are not kept alive inside
1961 // the proxy.
1962 SwapOutOldFrame(old_render_frame_host.Pass());
1964 if (RenderFrameHostManager::IsSwappedOutStateForbidden()) {
1965 // Since the new RenderFrameHost is now committed, there must be no proxies
1966 // for its SiteInstance. Delete any existing ones.
1967 RenderFrameProxyHostMap::iterator iter =
1968 proxy_hosts_.find(render_frame_host_->GetSiteInstance()->GetId());
1969 if (iter != proxy_hosts_.end()) {
1970 delete iter->second;
1971 proxy_hosts_.erase(iter);
1975 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1976 switches::kSitePerProcess)) {
1977 // If this is a subframe, it should have a CrossProcessFrameConnector
1978 // created already. Use it to link the new RFH's view to the proxy that
1979 // belongs to the parent frame's SiteInstance. If this navigation causes
1980 // an out-of-process frame to return to the same process as its parent, the
1981 // proxy would have been removed from proxy_hosts_ above.
1982 // Note: We do this after swapping out the old RFH because that may create
1983 // the proxy we're looking for.
1984 RenderFrameProxyHost* proxy_to_parent = GetProxyToParent();
1985 if (proxy_to_parent)
1986 proxy_to_parent->SetChildRWHView(render_frame_host_->GetView());
1989 // After all is done, there must never be a proxy in the list which has the
1990 // same SiteInstance as the current RenderFrameHost.
1991 CHECK(proxy_hosts_.find(render_frame_host_->GetSiteInstance()->GetId()) ==
1992 proxy_hosts_.end());
1995 void RenderFrameHostManager::ShutdownProxiesIfLastActiveFrameInSiteInstance(
1996 RenderFrameHostImpl* render_frame_host) {
1997 if (!render_frame_host)
1998 return;
1999 if (!RenderFrameHostImpl::IsRFHStateActive(render_frame_host->rfh_state()))
2000 return;
2001 if (render_frame_host->GetSiteInstance()->active_frame_count() > 1U)
2002 return;
2004 // After |render_frame_host| goes away, there will be no active frames left in
2005 // its SiteInstance, so we can delete all proxies created in that SiteInstance
2006 // on behalf of frames anywhere in the BrowsingInstance.
2007 int32 site_instance_id = render_frame_host->GetSiteInstance()->GetId();
2009 // First remove any proxies for this SiteInstance from our own list.
2010 ClearProxiesInSiteInstance(site_instance_id, frame_tree_node_);
2012 // Use the safe RenderWidgetHost iterator for now to find all RenderViewHosts
2013 // in the SiteInstance, then tell their respective FrameTrees to remove all
2014 // RenderFrameProxyHosts corresponding to them.
2015 // TODO(creis): Replace this with a RenderFrameHostIterator that protects
2016 // against use-after-frees if a later element is deleted before getting to it.
2017 scoped_ptr<RenderWidgetHostIterator> widgets(
2018 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
2019 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2020 if (!widget->IsRenderView())
2021 continue;
2022 RenderViewHostImpl* rvh =
2023 static_cast<RenderViewHostImpl*>(RenderViewHost::From(widget));
2024 if (site_instance_id == rvh->GetSiteInstance()->GetId()) {
2025 // This deletes all RenderFrameHosts using the |rvh|, which then causes
2026 // |rvh| to Shutdown.
2027 FrameTree* tree = rvh->GetDelegate()->GetFrameTree();
2028 tree->ForEach(base::Bind(
2029 &RenderFrameHostManager::ClearProxiesInSiteInstance,
2030 site_instance_id));
2035 RenderFrameHostImpl* RenderFrameHostManager::UpdateStateForNavigate(
2036 const GURL& dest_url,
2037 SiteInstance* source_instance,
2038 SiteInstance* dest_instance,
2039 ui::PageTransition transition,
2040 bool dest_is_restore,
2041 bool dest_is_view_source_mode,
2042 const GlobalRequestID& transferred_request_id,
2043 int bindings) {
2044 // Don't swap for subframes unless we are in --site-per-process. We can get
2045 // here in tests for subframes (e.g., NavigateFrameToURL).
2046 if (!frame_tree_node_->IsMainFrame() &&
2047 !base::CommandLine::ForCurrentProcess()->HasSwitch(
2048 switches::kSitePerProcess))
2049 return render_frame_host_.get();
2051 // If we are currently navigating cross-process, we want to get back to normal
2052 // and then navigate as usual.
2053 if (pending_render_frame_host_)
2054 CancelPending();
2056 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
2057 scoped_refptr<SiteInstance> new_instance = GetSiteInstanceForNavigation(
2058 dest_url, source_instance, dest_instance, nullptr, transition,
2059 dest_is_restore, dest_is_view_source_mode);
2061 const NavigationEntry* current_entry =
2062 delegate_->GetLastCommittedNavigationEntryForRenderManager();
2064 DCHECK(!pending_render_frame_host_);
2066 if (new_instance.get() != current_instance) {
2067 TRACE_EVENT_INSTANT2(
2068 "navigation",
2069 "RenderFrameHostManager::UpdateStateForNavigate:New SiteInstance",
2070 TRACE_EVENT_SCOPE_THREAD,
2071 "current_instance id", current_instance->GetId(),
2072 "new_instance id", new_instance->GetId());
2074 // New SiteInstance: create a pending RFH to navigate.
2076 // This will possibly create (set to nullptr) a Web UI object for the
2077 // pending page. We'll use this later to give the page special access. This
2078 // must happen before the new renderer is created below so it will get
2079 // bindings. It must also happen after the above conditional call to
2080 // CancelPending(), otherwise CancelPending may clear the pending_web_ui_
2081 // and the page will not have its bindings set appropriately.
2082 SetPendingWebUI(dest_url, bindings);
2083 CreatePendingRenderFrameHost(current_instance, new_instance.get(),
2084 frame_tree_node_->IsMainFrame());
2085 if (!pending_render_frame_host_)
2086 return nullptr;
2088 // Check if our current RFH is live before we set up a transition.
2089 if (!render_frame_host_->IsRenderFrameLive()) {
2090 // The current RFH is not live. There's no reason to sit around with a
2091 // sad tab or a newly created RFH while we wait for the pending RFH to
2092 // navigate. Just switch to the pending RFH now and go back to normal.
2093 // (Note that we don't care about on{before}unload handlers if the current
2094 // RFH isn't live.)
2095 CommitPending();
2096 return render_frame_host_.get();
2098 // Otherwise, it's safe to treat this as a pending cross-process transition.
2100 // We now have a pending RFH.
2101 DCHECK(pending_render_frame_host_);
2103 // We need to wait until the beforeunload handler has run, unless we are
2104 // transferring an existing request (in which case it has already run).
2105 // Suspend the new render view (i.e., don't let it send the cross-process
2106 // Navigate message) until we hear back from the old renderer's
2107 // beforeunload handler. If the handler returns false, we'll have to
2108 // cancel the request.
2110 DCHECK(!pending_render_frame_host_->are_navigations_suspended());
2111 bool is_transfer = transferred_request_id != GlobalRequestID();
2112 if (is_transfer) {
2113 // We don't need to stop the old renderer or run beforeunload/unload
2114 // handlers, because those have already been done.
2115 DCHECK(cross_site_transferring_request_->request_id() ==
2116 transferred_request_id);
2117 } else {
2118 // Also make sure the old render view stops, in case a load is in
2119 // progress. (We don't want to do this for transfers, since it will
2120 // interrupt the transfer with an unexpected DidStopLoading.)
2121 render_frame_host_->Send(new FrameMsg_Stop(
2122 render_frame_host_->GetRoutingID()));
2123 pending_render_frame_host_->SetNavigationsSuspended(true,
2124 base::TimeTicks());
2125 // Unless we are transferring an existing request, we should now tell the
2126 // old render view to run its beforeunload handler, since it doesn't
2127 // otherwise know that the cross-site request is happening. This will
2128 // trigger a call to OnBeforeUnloadACK with the reply.
2129 render_frame_host_->DispatchBeforeUnload(true);
2132 return pending_render_frame_host_.get();
2135 // Otherwise the same SiteInstance can be used. Navigate render_frame_host_.
2137 // It's possible to swap out the current RFH and then decide to navigate in it
2138 // anyway (e.g., a cross-process navigation that redirects back to the
2139 // original site). In that case, we have a proxy for the current RFH but
2140 // haven't deleted it yet. The new navigation will swap it back in, so we can
2141 // delete the proxy.
2142 DeleteRenderFrameProxyHost(new_instance.get());
2144 if (ShouldReuseWebUI(current_entry, dest_url)) {
2145 pending_web_ui_.reset();
2146 pending_and_current_web_ui_ = web_ui_->AsWeakPtr();
2147 } else {
2148 SetPendingWebUI(dest_url, bindings);
2149 // Make sure the new RenderViewHost has the right bindings.
2150 if (pending_web_ui() &&
2151 !render_frame_host_->GetProcess()->IsForGuestsOnly()) {
2152 render_frame_host_->render_view_host()->AllowBindings(
2153 pending_web_ui()->GetBindings());
2157 if (pending_web_ui() && render_frame_host_->IsRenderFrameLive()) {
2158 pending_web_ui()->GetController()->RenderViewReused(
2159 render_frame_host_->render_view_host());
2162 // The renderer can exit view source mode when any error or cancellation
2163 // happen. We must overwrite to recover the mode.
2164 if (dest_is_view_source_mode) {
2165 render_frame_host_->render_view_host()->Send(
2166 new ViewMsg_EnableViewSourceMode(
2167 render_frame_host_->render_view_host()->GetRoutingID()));
2170 return render_frame_host_.get();
2173 void RenderFrameHostManager::CancelPending() {
2174 TRACE_EVENT1("navigation", "RenderFrameHostManager::CancelPending",
2175 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
2176 DiscardUnusedFrame(UnsetPendingRenderFrameHost());
2179 scoped_ptr<RenderFrameHostImpl>
2180 RenderFrameHostManager::UnsetPendingRenderFrameHost() {
2181 scoped_ptr<RenderFrameHostImpl> pending_render_frame_host =
2182 pending_render_frame_host_.Pass();
2184 RenderFrameDevToolsAgentHost::OnCancelPendingNavigation(
2185 pending_render_frame_host.get(),
2186 render_frame_host_.get());
2188 // We no longer need to prevent the process from exiting.
2189 pending_render_frame_host->GetProcess()->RemovePendingView();
2191 pending_web_ui_.reset();
2192 pending_and_current_web_ui_.reset();
2194 return pending_render_frame_host.Pass();
2197 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::SetRenderFrameHost(
2198 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
2199 // Swap the two.
2200 scoped_ptr<RenderFrameHostImpl> old_render_frame_host =
2201 render_frame_host_.Pass();
2202 render_frame_host_ = render_frame_host.Pass();
2204 if (frame_tree_node_->IsMainFrame()) {
2205 // Update the count of top-level frames using this SiteInstance. All
2206 // subframes are in the same BrowsingInstance as the main frame, so we only
2207 // count top-level ones. This makes the value easier for consumers to
2208 // interpret.
2209 if (render_frame_host_) {
2210 render_frame_host_->GetSiteInstance()->
2211 IncrementRelatedActiveContentsCount();
2213 if (old_render_frame_host) {
2214 old_render_frame_host->GetSiteInstance()->
2215 DecrementRelatedActiveContentsCount();
2219 return old_render_frame_host.Pass();
2222 bool RenderFrameHostManager::IsRVHOnSwappedOutList(
2223 RenderViewHostImpl* rvh) const {
2224 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(
2225 rvh->GetSiteInstance());
2226 if (!proxy)
2227 return false;
2228 // If there is a proxy without RFH, it is for a subframe in the SiteInstance
2229 // of |rvh|. Subframes should be ignored in this case.
2230 if (!proxy->render_frame_host())
2231 return false;
2232 return IsOnSwappedOutList(proxy->render_frame_host());
2235 bool RenderFrameHostManager::IsOnSwappedOutList(
2236 RenderFrameHostImpl* rfh) const {
2237 if (!rfh->GetSiteInstance())
2238 return false;
2240 RenderFrameProxyHostMap::const_iterator iter = proxy_hosts_.find(
2241 rfh->GetSiteInstance()->GetId());
2242 if (iter == proxy_hosts_.end())
2243 return false;
2245 return iter->second->render_frame_host() == rfh;
2248 RenderViewHostImpl* RenderFrameHostManager::GetSwappedOutRenderViewHost(
2249 SiteInstance* instance) const {
2250 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
2251 if (proxy)
2252 return proxy->GetRenderViewHost();
2253 return NULL;
2256 RenderFrameProxyHost* RenderFrameHostManager::GetRenderFrameProxyHost(
2257 SiteInstance* instance) const {
2258 RenderFrameProxyHostMap::const_iterator iter =
2259 proxy_hosts_.find(instance->GetId());
2260 if (iter != proxy_hosts_.end())
2261 return iter->second;
2263 return NULL;
2266 void RenderFrameHostManager::DeleteRenderFrameProxyHost(
2267 SiteInstance* instance) {
2268 RenderFrameProxyHostMap::iterator iter = proxy_hosts_.find(instance->GetId());
2269 if (iter != proxy_hosts_.end()) {
2270 delete iter->second;
2271 proxy_hosts_.erase(iter);
2275 int RenderFrameHostManager::CreateOpenerProxiesIfNeeded(
2276 SiteInstance* instance) {
2277 FrameTreeNode* opener = frame_tree_node_->opener();
2278 if (!opener)
2279 return MSG_ROUTING_NONE;
2281 // Create proxies for the opener chain.
2282 return opener->render_manager()->CreateOpenerProxies(instance);
2285 int RenderFrameHostManager::CreateOpenerProxies(SiteInstance* instance) {
2286 int opener_route_id = MSG_ROUTING_NONE;
2288 // If this tab has an opener, recursively create proxies for the nodes on its
2289 // frame tree.
2290 // TODO(alexmos): Once we allow frame openers to be updated (which can happen
2291 // via window.open(url, "target_frame")), this will need to be resilient to
2292 // cycles. It will also need to handle tabs that have multiple openers (e.g.,
2293 // main frame and subframe could have different openers, each of which must
2294 // be traversed).
2295 FrameTreeNode* opener = frame_tree_node_->opener();
2296 if (opener)
2297 opener_route_id = opener->render_manager()->CreateOpenerProxies(instance);
2299 // If any of the RenderViews (current, pending, or swapped out) for this
2300 // FrameTree has the same SiteInstance, use it. If such a RenderView exists,
2301 // that implies that proxies for all nodes in the tree should also exist
2302 // (when in site-per-process mode), so it is safe to exit early.
2303 FrameTree* frame_tree = frame_tree_node_->frame_tree();
2304 RenderViewHostImpl* rvh = frame_tree->GetRenderViewHost(instance);
2305 if (rvh && rvh->IsRenderViewLive())
2306 return rvh->GetRoutingID();
2308 int render_view_routing_id = MSG_ROUTING_NONE;
2309 if (RenderFrameHostManager::IsSwappedOutStateForbidden()) {
2310 // Ensure that all the nodes in the opener's frame tree have
2311 // RenderFrameProxyHosts for the new SiteInstance.
2312 frame_tree->CreateProxiesForSiteInstance(nullptr, instance);
2313 rvh = frame_tree->GetRenderViewHost(instance);
2314 render_view_routing_id = rvh->GetRoutingID();
2315 } else if (rvh && !rvh->IsRenderViewLive()) {
2316 EnsureRenderViewInitialized(rvh, instance);
2317 render_view_routing_id = rvh->GetRoutingID();
2318 } else {
2319 // Create a swapped out RenderView in the given SiteInstance if none exists,
2320 // setting its opener to the given route_id. Since the opener can point to
2321 // a subframe, do this on the root frame of the opener's frame tree.
2322 // Return the new view's route_id.
2323 frame_tree->root()->render_manager()->
2324 CreateRenderFrame(instance, nullptr, opener_route_id,
2325 CREATE_RF_FOR_MAIN_FRAME_NAVIGATION |
2326 CREATE_RF_SWAPPED_OUT | CREATE_RF_HIDDEN,
2327 &render_view_routing_id);
2329 return render_view_routing_id;
2332 } // namespace content