Fix various typos, error handling for GN auto-roller.
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_manager.cc
blob18890339a74b76ed4f2293c1bc742e6372f42fb6
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 <algorithm>
8 #include <utility>
10 #include "base/command_line.h"
11 #include "base/logging.h"
12 #include "base/stl_util.h"
13 #include "base/trace_event/trace_event.h"
14 #include "content/browser/child_process_security_policy_impl.h"
15 #include "content/browser/devtools/render_frame_devtools_agent_host.h"
16 #include "content/browser/frame_host/cross_site_transferring_request.h"
17 #include "content/browser/frame_host/debug_urls.h"
18 #include "content/browser/frame_host/frame_navigation_entry.h"
19 #include "content/browser/frame_host/interstitial_page_impl.h"
20 #include "content/browser/frame_host/navigation_controller_impl.h"
21 #include "content/browser/frame_host/navigation_entry_impl.h"
22 #include "content/browser/frame_host/navigation_request.h"
23 #include "content/browser/frame_host/navigator.h"
24 #include "content/browser/frame_host/render_frame_host_factory.h"
25 #include "content/browser/frame_host/render_frame_host_impl.h"
26 #include "content/browser/frame_host/render_frame_proxy_host.h"
27 #include "content/browser/renderer_host/render_process_host_impl.h"
28 #include "content/browser/renderer_host/render_view_host_factory.h"
29 #include "content/browser/renderer_host/render_view_host_impl.h"
30 #include "content/browser/site_instance_impl.h"
31 #include "content/browser/webui/web_ui_controller_factory_registry.h"
32 #include "content/browser/webui/web_ui_impl.h"
33 #include "content/common/frame_messages.h"
34 #include "content/common/site_isolation_policy.h"
35 #include "content/common/view_messages.h"
36 #include "content/public/browser/content_browser_client.h"
37 #include "content/public/browser/render_process_host_observer.h"
38 #include "content/public/browser/render_widget_host_iterator.h"
39 #include "content/public/browser/render_widget_host_view.h"
40 #include "content/public/browser/user_metrics.h"
41 #include "content/public/browser/web_ui_controller.h"
42 #include "content/public/common/browser_plugin_guest_mode.h"
43 #include "content/public/common/content_switches.h"
44 #include "content/public/common/referrer.h"
45 #include "content/public/common/url_constants.h"
47 namespace content {
49 // A helper class to hold all frame proxies and register as a
50 // RenderProcessHostObserver for them.
51 class RenderFrameHostManager::RenderFrameProxyHostMap
52 : public RenderProcessHostObserver {
53 public:
54 using MapType = base::hash_map<int32, RenderFrameProxyHost*>;
56 RenderFrameProxyHostMap(RenderFrameHostManager* manager);
57 ~RenderFrameProxyHostMap() override;
59 // Read-only access to the underlying map of site instance ID to
60 // RenderFrameProxyHosts.
61 MapType::const_iterator begin() const { return map_.begin(); }
62 MapType::const_iterator end() const { return map_.end(); }
63 bool empty() const { return map_.empty(); }
65 // Returns the proxy with the specified ID, or nullptr if there is no such
66 // one.
67 RenderFrameProxyHost* Get(int32 id);
69 // Adds the specified proxy with the specified ID. It is an error (and fatal)
70 // to add more than one proxy with the specified ID.
71 void Add(int32 id, scoped_ptr<RenderFrameProxyHost> proxy);
73 // Removes the proxy with the specified site instance ID.
74 void Remove(int32 id);
76 // Removes all proxies.
77 void Clear();
79 // RenderProcessHostObserver implementation.
80 void RenderProcessWillExit(RenderProcessHost* host) override;
81 void RenderProcessExited(RenderProcessHost* host,
82 base::TerminationStatus status,
83 int exit_code) override;
85 private:
86 RenderFrameHostManager* manager_;
87 MapType map_;
90 RenderFrameHostManager::RenderFrameProxyHostMap::RenderFrameProxyHostMap(
91 RenderFrameHostManager* manager)
92 : manager_(manager) {}
94 RenderFrameHostManager::RenderFrameProxyHostMap::~RenderFrameProxyHostMap() {
95 Clear();
98 RenderFrameProxyHost* RenderFrameHostManager::RenderFrameProxyHostMap::Get(
99 int32 id) {
100 auto it = map_.find(id);
101 if (it != map_.end())
102 return it->second;
103 return nullptr;
106 void RenderFrameHostManager::RenderFrameProxyHostMap::Add(
107 int32 id,
108 scoped_ptr<RenderFrameProxyHost> proxy) {
109 CHECK_EQ(0u, map_.count(id)) << "Inserting a duplicate item.";
111 // If this is the first proxy that has this process host, observe the
112 // process host.
113 RenderProcessHost* host = proxy->GetProcess();
114 size_t count =
115 std::count_if(begin(), end(), [host](MapType::value_type item) {
116 return item.second->GetProcess() == host;
118 if (count == 0)
119 host->AddObserver(this);
121 map_[id] = proxy.release();
124 void RenderFrameHostManager::RenderFrameProxyHostMap::Remove(int32 id) {
125 auto it = map_.find(id);
126 if (it == map_.end())
127 return;
129 // If this is the last proxy that has this process host, stop observing the
130 // process host.
131 RenderProcessHost* host = it->second->GetProcess();
132 size_t count =
133 std::count_if(begin(), end(), [host](MapType::value_type item) {
134 return item.second->GetProcess() == host;
136 if (count == 1)
137 host->RemoveObserver(this);
139 delete it->second;
140 map_.erase(it);
143 void RenderFrameHostManager::RenderFrameProxyHostMap::Clear() {
144 std::set<RenderProcessHost*> hosts;
145 for (const auto& pair : map_)
146 hosts.insert(pair.second->GetProcess());
147 for (auto host : hosts)
148 host->RemoveObserver(this);
150 STLDeleteValues(&map_);
153 void RenderFrameHostManager::RenderFrameProxyHostMap::RenderProcessWillExit(
154 RenderProcessHost* host) {
155 manager_->RendererProcessClosing(host);
158 void RenderFrameHostManager::RenderFrameProxyHostMap::RenderProcessExited(
159 RenderProcessHost* host,
160 base::TerminationStatus status,
161 int exit_code) {
162 manager_->RendererProcessClosing(host);
165 // static
166 bool RenderFrameHostManager::ClearRFHsPendingShutdown(FrameTreeNode* node) {
167 node->render_manager()->pending_delete_hosts_.clear();
168 return true;
171 // static
172 bool RenderFrameHostManager::IsSwappedOutStateForbidden() {
173 return SiteIsolationPolicy::AreCrossProcessFramesPossible();
176 RenderFrameHostManager::RenderFrameHostManager(
177 FrameTreeNode* frame_tree_node,
178 RenderFrameHostDelegate* render_frame_delegate,
179 RenderViewHostDelegate* render_view_delegate,
180 RenderWidgetHostDelegate* render_widget_delegate,
181 Delegate* delegate)
182 : frame_tree_node_(frame_tree_node),
183 delegate_(delegate),
184 render_frame_delegate_(render_frame_delegate),
185 render_view_delegate_(render_view_delegate),
186 render_widget_delegate_(render_widget_delegate),
187 proxy_hosts_(new RenderFrameProxyHostMap(this)),
188 interstitial_page_(nullptr),
189 should_reuse_web_ui_(false),
190 weak_factory_(this) {
191 DCHECK(frame_tree_node_);
194 RenderFrameHostManager::~RenderFrameHostManager() {
195 if (pending_render_frame_host_) {
196 scoped_ptr<RenderFrameHostImpl> relic = UnsetPendingRenderFrameHost();
197 ShutdownProxiesIfLastActiveFrameInSiteInstance(relic.get());
200 if (speculative_render_frame_host_) {
201 scoped_ptr<RenderFrameHostImpl> relic = UnsetSpeculativeRenderFrameHost();
202 ShutdownProxiesIfLastActiveFrameInSiteInstance(relic.get());
205 ShutdownProxiesIfLastActiveFrameInSiteInstance(render_frame_host_.get());
207 // Delete any RenderFrameProxyHosts and swapped out RenderFrameHosts.
208 // It is important to delete those prior to deleting the current
209 // RenderFrameHost, since the CrossProcessFrameConnector (owned by
210 // RenderFrameProxyHost) points to the RenderWidgetHostView associated with
211 // the current RenderFrameHost and uses it during its destructor.
212 ResetProxyHosts();
214 // Release the WebUI prior to resetting the current RenderFrameHost, as the
215 // WebUI accesses the RenderFrameHost during cleanup.
216 web_ui_.reset();
218 // We should always have a current RenderFrameHost except in some tests.
219 SetRenderFrameHost(scoped_ptr<RenderFrameHostImpl>());
222 void RenderFrameHostManager::Init(BrowserContext* browser_context,
223 SiteInstance* site_instance,
224 int view_routing_id,
225 int frame_routing_id) {
226 // Create a RenderViewHost and RenderFrameHost, once we have an instance. It
227 // is important to immediately give this SiteInstance to a RenderViewHost so
228 // that the SiteInstance is ref counted.
229 if (!site_instance)
230 site_instance = SiteInstance::Create(browser_context);
232 int flags = delegate_->IsHidden() ? CREATE_RF_HIDDEN : 0;
233 SetRenderFrameHost(CreateRenderFrameHost(site_instance, view_routing_id,
234 frame_routing_id, flags));
236 // Notify the delegate of the creation of the current RenderFrameHost.
237 // Do this only for subframes, as the main frame case is taken care of by
238 // WebContentsImpl::Init.
239 if (!frame_tree_node_->IsMainFrame()) {
240 delegate_->NotifySwappedFromRenderManager(
241 nullptr, render_frame_host_.get(), false);
245 RenderViewHostImpl* RenderFrameHostManager::current_host() const {
246 if (!render_frame_host_)
247 return nullptr;
248 return render_frame_host_->render_view_host();
251 RenderViewHostImpl* RenderFrameHostManager::pending_render_view_host() const {
252 if (!pending_render_frame_host_)
253 return nullptr;
254 return pending_render_frame_host_->render_view_host();
257 RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const {
258 if (interstitial_page_)
259 return interstitial_page_->GetView();
260 if (render_frame_host_)
261 return render_frame_host_->GetView();
262 return nullptr;
265 bool RenderFrameHostManager::ForInnerDelegate() {
266 // TODO(lazyboy): Subframes inside inner WebContents needs to be tested and
267 // we have to make sure that IsMainFrame() check below is appropriate. See
268 // http://crbug.com/500957.
269 return frame_tree_node_->IsMainFrame() &&
270 delegate_->GetOuterDelegateFrameTreeNodeID() !=
271 FrameTreeNode::kFrameTreeNodeInvalidID;
274 RenderWidgetHostImpl*
275 RenderFrameHostManager::GetOuterRenderWidgetHostForKeyboardInput() {
276 if (!ForInnerDelegate())
277 return nullptr;
279 FrameTreeNode* outer_contents_frame_tree_node =
280 FrameTreeNode::GloballyFindByID(
281 delegate_->GetOuterDelegateFrameTreeNodeID());
282 return outer_contents_frame_tree_node->parent()
283 ->current_frame_host()
284 ->render_view_host();
287 RenderFrameProxyHost* RenderFrameHostManager::GetProxyToParent() {
288 if (frame_tree_node_->IsMainFrame())
289 return nullptr;
291 return proxy_hosts_->Get(frame_tree_node_->parent()
292 ->render_manager()
293 ->current_frame_host()
294 ->GetSiteInstance()
295 ->GetId());
298 RenderFrameProxyHost* RenderFrameHostManager::GetProxyToOuterDelegate() {
299 int outer_contents_frame_tree_node_id =
300 delegate_->GetOuterDelegateFrameTreeNodeID();
301 FrameTreeNode* outer_contents_frame_tree_node =
302 FrameTreeNode::GloballyFindByID(outer_contents_frame_tree_node_id);
303 if (!outer_contents_frame_tree_node ||
304 !outer_contents_frame_tree_node->parent()) {
305 return nullptr;
308 return GetRenderFrameProxyHost(outer_contents_frame_tree_node->parent()
309 ->current_frame_host()
310 ->GetSiteInstance());
313 void RenderFrameHostManager::RemoveOuterDelegateFrame() {
314 FrameTreeNode* outer_delegate_frame_tree_node =
315 FrameTreeNode::GloballyFindByID(
316 delegate_->GetOuterDelegateFrameTreeNodeID());
317 DCHECK(outer_delegate_frame_tree_node->parent());
318 outer_delegate_frame_tree_node->frame_tree()->RemoveFrame(
319 outer_delegate_frame_tree_node);
322 void RenderFrameHostManager::SetPendingWebUI(const GURL& url, int bindings) {
323 pending_web_ui_ = CreateWebUI(url, bindings);
324 pending_and_current_web_ui_.reset();
327 scoped_ptr<WebUIImpl> RenderFrameHostManager::CreateWebUI(const GURL& url,
328 int bindings) {
329 scoped_ptr<WebUIImpl> new_web_ui(delegate_->CreateWebUIForRenderManager(url));
331 // If we have assigned (zero or more) bindings to this NavigationEntry in the
332 // past, make sure we're not granting it different bindings than it had
333 // before. If so, note it and don't give it any bindings, to avoid a
334 // potential privilege escalation.
335 if (new_web_ui && bindings != NavigationEntryImpl::kInvalidBindings &&
336 new_web_ui->GetBindings() != bindings) {
337 RecordAction(base::UserMetricsAction("ProcessSwapBindingsMismatch_RVHM"));
338 return nullptr;
340 return new_web_ui.Pass();
343 RenderFrameHostImpl* RenderFrameHostManager::Navigate(
344 const GURL& dest_url,
345 const FrameNavigationEntry& frame_entry,
346 const NavigationEntryImpl& entry) {
347 TRACE_EVENT1("navigation", "RenderFrameHostManager:Navigate",
348 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
349 // Create a pending RenderFrameHost to use for the navigation.
350 RenderFrameHostImpl* dest_render_frame_host = UpdateStateForNavigate(
351 dest_url,
352 // TODO(creis): Move source_site_instance to FNE.
353 entry.source_site_instance(), frame_entry.site_instance(),
354 entry.GetTransitionType(),
355 entry.restore_type() != NavigationEntryImpl::RESTORE_NONE,
356 entry.IsViewSourceMode(), entry.transferred_global_request_id(),
357 entry.bindings());
358 if (!dest_render_frame_host)
359 return nullptr; // We weren't able to create a pending render frame host.
361 // If the current render_frame_host_ isn't live, we should create it so
362 // that we don't show a sad tab while the dest_render_frame_host fetches
363 // its first page. (Bug 1145340)
364 if (dest_render_frame_host != render_frame_host_ &&
365 !render_frame_host_->IsRenderFrameLive()) {
366 // Note: we don't call InitRenderView here because we are navigating away
367 // soon anyway, and we don't have the NavigationEntry for this host.
368 delegate_->CreateRenderViewForRenderManager(
369 render_frame_host_->render_view_host(), MSG_ROUTING_NONE,
370 MSG_ROUTING_NONE, frame_tree_node_->current_replication_state(),
371 frame_tree_node_->IsMainFrame());
374 // If the renderer crashed, then try to create a new one to satisfy this
375 // navigation request.
376 if (!dest_render_frame_host->IsRenderFrameLive()) {
377 // Instruct the destination render frame host to set up a Mojo connection
378 // with the new render frame if necessary. Note that this call needs to
379 // occur before initializing the RenderView; the flow of creating the
380 // RenderView can cause browser-side code to execute that expects the this
381 // RFH's ServiceRegistry to be initialized (e.g., if the site is a WebUI
382 // site that is handled via Mojo, then Mojo WebUI code in //chrome will
383 // add a service to this RFH's ServiceRegistry).
384 dest_render_frame_host->SetUpMojoIfNeeded();
386 // Recreate the opener chain.
387 CreateOpenerProxiesIfNeeded(dest_render_frame_host->GetSiteInstance());
388 if (!InitRenderView(dest_render_frame_host->render_view_host(),
389 MSG_ROUTING_NONE,
390 frame_tree_node_->IsMainFrame()))
391 return nullptr;
393 // Now that we've created a new renderer, be sure to hide it if it isn't
394 // our primary one. Otherwise, we might crash if we try to call Show()
395 // on it later.
396 if (dest_render_frame_host != render_frame_host_) {
397 if (dest_render_frame_host->GetView())
398 dest_render_frame_host->GetView()->Hide();
399 } else {
400 // TODO(nasko): This is a very ugly hack. The Chrome extensions process
401 // manager still uses NotificationService and expects to see a
402 // RenderViewHost changed notification after WebContents and
403 // RenderFrameHostManager are completely initialized. This should be
404 // removed once the process manager moves away from NotificationService.
405 // See https://crbug.com/462682.
406 delegate_->NotifyMainFrameSwappedFromRenderManager(
407 nullptr, render_frame_host_->render_view_host());
411 // If entry includes the request ID of a request that is being transferred,
412 // the destination render frame will take ownership, so release ownership of
413 // the request.
414 if (cross_site_transferring_request_.get() &&
415 cross_site_transferring_request_->request_id() ==
416 entry.transferred_global_request_id()) {
417 cross_site_transferring_request_->ReleaseRequest();
420 return dest_render_frame_host;
423 void RenderFrameHostManager::Stop() {
424 render_frame_host_->Stop();
426 // If a cross-process navigation is happening, the pending RenderFrameHost
427 // should stop. This will lead to a DidFailProvisionalLoad, which will
428 // properly destroy it.
429 if (pending_render_frame_host_) {
430 pending_render_frame_host_->Send(new FrameMsg_Stop(
431 pending_render_frame_host_->GetRoutingID()));
434 // PlzNavigate: a loading speculative RenderFrameHost should also stop.
435 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
436 switches::kEnableBrowserSideNavigation)) {
437 if (speculative_render_frame_host_ &&
438 speculative_render_frame_host_->is_loading()) {
439 speculative_render_frame_host_->Send(
440 new FrameMsg_Stop(speculative_render_frame_host_->GetRoutingID()));
445 void RenderFrameHostManager::SetIsLoading(bool is_loading) {
446 render_frame_host_->render_view_host()->SetIsLoading(is_loading);
447 if (pending_render_frame_host_)
448 pending_render_frame_host_->render_view_host()->SetIsLoading(is_loading);
451 bool RenderFrameHostManager::ShouldCloseTabOnUnresponsiveRenderer() {
452 // If we're waiting for a close ACK, then the tab should close whether there's
453 // a navigation in progress or not. Unfortunately, we also need to check for
454 // cases that we arrive here with no navigation in progress, since there are
455 // some tab closure paths that don't set is_waiting_for_close_ack to true.
456 // TODO(creis): Clean this up in http://crbug.com/418266.
457 if (!pending_render_frame_host_ ||
458 render_frame_host_->render_view_host()->is_waiting_for_close_ack())
459 return true;
461 // We should always have a pending RFH when there's a cross-process navigation
462 // in progress. Sanity check this for http://crbug.com/276333.
463 CHECK(pending_render_frame_host_);
465 // Unload handlers run in the background, so we should never get an
466 // unresponsiveness warning for them.
467 CHECK(!render_frame_host_->IsWaitingForUnloadACK());
469 // If the tab becomes unresponsive during beforeunload while doing a
470 // cross-process navigation, proceed with the navigation. (This assumes that
471 // the pending RenderFrameHost is still responsive.)
472 if (render_frame_host_->is_waiting_for_beforeunload_ack()) {
473 // Haven't gotten around to starting the request, because we're still
474 // waiting for the beforeunload handler to finish. We'll pretend that it
475 // did finish, to let the navigation proceed. Note that there's a danger
476 // that the beforeunload handler will later finish and possibly return
477 // false (meaning the navigation should not proceed), but we'll ignore it
478 // in this case because it took too long.
479 if (pending_render_frame_host_->are_navigations_suspended()) {
480 pending_render_frame_host_->SetNavigationsSuspended(
481 false, base::TimeTicks::Now());
484 return false;
487 void RenderFrameHostManager::OnBeforeUnloadACK(
488 bool for_cross_site_transition,
489 bool proceed,
490 const base::TimeTicks& proceed_time) {
491 if (for_cross_site_transition) {
492 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
493 switches::kEnableBrowserSideNavigation));
494 // Ignore if we're not in a cross-process navigation.
495 if (!pending_render_frame_host_)
496 return;
498 if (proceed) {
499 // Ok to unload the current page, so proceed with the cross-process
500 // navigation. Note that if navigations are not currently suspended, it
501 // might be because the renderer was deemed unresponsive and this call was
502 // already made by ShouldCloseTabOnUnresponsiveRenderer. In that case, it
503 // is ok to do nothing here.
504 if (pending_render_frame_host_ &&
505 pending_render_frame_host_->are_navigations_suspended()) {
506 pending_render_frame_host_->SetNavigationsSuspended(false,
507 proceed_time);
509 } else {
510 // Current page says to cancel.
511 CancelPending();
513 } else {
514 // Non-cross-process transition means closing the entire tab.
515 bool proceed_to_fire_unload;
516 delegate_->BeforeUnloadFiredFromRenderManager(proceed, proceed_time,
517 &proceed_to_fire_unload);
519 if (proceed_to_fire_unload) {
520 // If we're about to close the tab and there's a pending RFH, cancel it.
521 // Otherwise, if the navigation in the pending RFH completes before the
522 // close in the current RFH, we'll lose the tab close.
523 if (pending_render_frame_host_) {
524 CancelPending();
527 // PlzNavigate: clean up the speculative RenderFrameHost if there is one.
528 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
529 switches::kEnableBrowserSideNavigation) &&
530 speculative_render_frame_host_) {
531 CleanUpNavigation();
534 // This is not a cross-process navigation; the tab is being closed.
535 render_frame_host_->render_view_host()->ClosePage();
540 void RenderFrameHostManager::OnCrossSiteResponse(
541 RenderFrameHostImpl* pending_render_frame_host,
542 const GlobalRequestID& global_request_id,
543 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
544 const std::vector<GURL>& transfer_url_chain,
545 const Referrer& referrer,
546 ui::PageTransition page_transition,
547 bool should_replace_current_entry) {
548 // We should only get here for transfer navigations. Most cross-process
549 // navigations can just continue and wait to run the unload handler (by
550 // swapping out) when the new navigation commits.
551 CHECK(cross_site_transferring_request);
553 // A transfer should only have come from our pending or current RFH.
554 // TODO(creis): We need to handle the case that the pending RFH has changed
555 // in the mean time, while this was being posted from the IO thread. We
556 // should probably cancel the request in that case.
557 DCHECK(pending_render_frame_host == pending_render_frame_host_ ||
558 pending_render_frame_host == render_frame_host_);
560 // Store the transferring request so that we can release it if the transfer
561 // navigation matches.
562 cross_site_transferring_request_ = cross_site_transferring_request.Pass();
564 // Sanity check that the params are for the correct frame and process.
565 // These should match the RenderFrameHost that made the request.
566 // If it started as a cross-process navigation via OpenURL, this is the
567 // pending one. If it wasn't cross-process until the transfer, this is the
568 // current one.
569 int render_frame_id = pending_render_frame_host_ ?
570 pending_render_frame_host_->GetRoutingID() :
571 render_frame_host_->GetRoutingID();
572 DCHECK_EQ(render_frame_id, pending_render_frame_host->GetRoutingID());
573 int process_id = pending_render_frame_host_ ?
574 pending_render_frame_host_->GetProcess()->GetID() :
575 render_frame_host_->GetProcess()->GetID();
576 DCHECK_EQ(process_id, global_request_id.child_id);
578 // Treat the last URL in the chain as the destination and the remainder as
579 // the redirect chain.
580 CHECK(transfer_url_chain.size());
581 GURL transfer_url = transfer_url_chain.back();
582 std::vector<GURL> rest_of_chain = transfer_url_chain;
583 rest_of_chain.pop_back();
585 // We don't know whether the original request had |user_action| set to true.
586 // However, since we force the navigation to be in the current tab, it
587 // doesn't matter.
588 pending_render_frame_host->frame_tree_node()->navigator()->RequestTransferURL(
589 pending_render_frame_host, transfer_url, nullptr, rest_of_chain, referrer,
590 page_transition, CURRENT_TAB, global_request_id,
591 should_replace_current_entry, true);
593 // The transferring request was only needed during the RequestTransferURL
594 // call, so it is safe to clear at this point.
595 cross_site_transferring_request_.reset();
598 void RenderFrameHostManager::DidNavigateFrame(
599 RenderFrameHostImpl* render_frame_host,
600 bool was_caused_by_user_gesture) {
601 CommitPendingIfNecessary(render_frame_host, was_caused_by_user_gesture);
603 // Make sure any dynamic changes to this frame's sandbox flags that were made
604 // prior to navigation take effect.
605 CommitPendingSandboxFlags();
608 void RenderFrameHostManager::CommitPendingIfNecessary(
609 RenderFrameHostImpl* render_frame_host,
610 bool was_caused_by_user_gesture) {
611 if (!pending_render_frame_host_ && !speculative_render_frame_host_) {
612 DCHECK_IMPLIES(should_reuse_web_ui_, web_ui_);
614 // We should only hear this from our current renderer.
615 DCHECK_EQ(render_frame_host_, render_frame_host);
617 // Even when there is no pending RVH, there may be a pending Web UI.
618 if (pending_web_ui() || speculative_web_ui_)
619 CommitPending();
620 return;
623 if (render_frame_host == pending_render_frame_host_ ||
624 render_frame_host == speculative_render_frame_host_) {
625 // The pending cross-process navigation completed, so show the renderer.
626 CommitPending();
627 } else if (render_frame_host == render_frame_host_) {
628 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
629 switches::kEnableBrowserSideNavigation)) {
630 CleanUpNavigation();
631 } else {
632 if (was_caused_by_user_gesture) {
633 // A navigation in the original page has taken place. Cancel the
634 // pending one. Only do it for user gesture originated navigations to
635 // prevent page doing any shenanigans to prevent user from navigating.
636 // See https://code.google.com/p/chromium/issues/detail?id=75195
637 CancelPending();
640 } else {
641 // No one else should be sending us DidNavigate in this state.
642 DCHECK(false);
646 void RenderFrameHostManager::DidDisownOpener(
647 RenderFrameHost* render_frame_host) {
648 // Notify all RenderFrameHosts but the one that notified us. This is necessary
649 // in case a process swap has occurred while the message was in flight.
650 for (const auto& pair : *proxy_hosts_) {
651 DCHECK_NE(pair.second->GetSiteInstance(),
652 current_frame_host()->GetSiteInstance());
653 pair.second->DisownOpener();
656 if (render_frame_host_.get() != render_frame_host)
657 render_frame_host_->DisownOpener();
659 if (pending_render_frame_host_ &&
660 pending_render_frame_host_.get() != render_frame_host) {
661 pending_render_frame_host_->DisownOpener();
665 void RenderFrameHostManager::CommitPendingSandboxFlags() {
666 // Return early if there were no pending sandbox flags updates.
667 if (!frame_tree_node_->CommitPendingSandboxFlags())
668 return;
670 // Sandbox flags updates can only happen when the frame has a parent.
671 CHECK(frame_tree_node_->parent());
673 // Notify all of the frame's proxies about updated sandbox flags, excluding
674 // the parent process since it already knows the latest flags.
675 SiteInstance* parent_site_instance =
676 frame_tree_node_->parent()->current_frame_host()->GetSiteInstance();
677 for (const auto& pair : *proxy_hosts_) {
678 if (pair.second->GetSiteInstance() != parent_site_instance) {
679 pair.second->Send(new FrameMsg_DidUpdateSandboxFlags(
680 pair.second->GetRoutingID(),
681 frame_tree_node_->current_replication_state().sandbox_flags));
686 void RenderFrameHostManager::RendererProcessClosing(
687 RenderProcessHost* render_process_host) {
688 // Remove any swapped out RVHs from this process, so that we don't try to
689 // swap them back in while the process is exiting. Start by finding them,
690 // since there could be more than one.
691 std::list<int> ids_to_remove;
692 // Do not remove proxies in the dead process that still have active frame
693 // count though, we just reset them to be uninitialized.
694 std::list<int> ids_to_keep;
695 for (const auto& pair : *proxy_hosts_) {
696 RenderFrameProxyHost* proxy = pair.second;
697 if (proxy->GetProcess() != render_process_host)
698 continue;
700 if (static_cast<SiteInstanceImpl*>(proxy->GetSiteInstance())
701 ->active_frame_count() >= 1U) {
702 ids_to_keep.push_back(pair.first);
703 } else {
704 ids_to_remove.push_back(pair.first);
708 // Now delete them.
709 while (!ids_to_remove.empty()) {
710 proxy_hosts_->Remove(ids_to_remove.back());
711 ids_to_remove.pop_back();
714 while (!ids_to_keep.empty()) {
715 frame_tree_node_->frame_tree()->ForEach(
716 base::Bind(
717 &RenderFrameHostManager::ResetProxiesInSiteInstance,
718 ids_to_keep.back()));
719 ids_to_keep.pop_back();
723 void RenderFrameHostManager::SwapOutOldFrame(
724 scoped_ptr<RenderFrameHostImpl> old_render_frame_host) {
725 TRACE_EVENT1("navigation", "RenderFrameHostManager::SwapOutOldFrame",
726 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
728 // Tell the renderer to suppress any further modal dialogs so that we can swap
729 // it out. This must be done before canceling any current dialog, in case
730 // there is a loop creating additional dialogs.
731 // TODO(creis): Handle modal dialogs in subframe processes.
732 old_render_frame_host->render_view_host()->SuppressDialogsUntilSwapOut();
734 // Now close any modal dialogs that would prevent us from swapping out. This
735 // must be done separately from SwapOut, so that the PageGroupLoadDeferrer is
736 // no longer on the stack when we send the SwapOut message.
737 delegate_->CancelModalDialogsForRenderManager();
739 // If the old RFH is not live, just return as there is no further work to do.
740 // It will be deleted and there will be no proxy created.
741 int32 old_site_instance_id =
742 old_render_frame_host->GetSiteInstance()->GetId();
743 if (!old_render_frame_host->IsRenderFrameLive()) {
744 ShutdownProxiesIfLastActiveFrameInSiteInstance(old_render_frame_host.get());
745 return;
748 // If there are no active frames besides this one, we can delete the old
749 // RenderFrameHost once it runs its unload handler, without replacing it with
750 // a proxy.
751 size_t active_frame_count =
752 old_render_frame_host->GetSiteInstance()->active_frame_count();
753 if (active_frame_count <= 1) {
754 // Clear out any proxies from this SiteInstance, in case this was the
755 // last one keeping other proxies alive.
756 ShutdownProxiesIfLastActiveFrameInSiteInstance(old_render_frame_host.get());
758 // Tell the old RenderFrameHost to swap out, with no proxy to replace it.
759 old_render_frame_host->SwapOut(nullptr, true);
760 MoveToPendingDeleteHosts(old_render_frame_host.Pass());
761 return;
764 // Otherwise there are active views and we need a proxy for the old RFH.
765 // (There should not be one yet.)
766 RenderFrameProxyHost* proxy = new RenderFrameProxyHost(
767 old_render_frame_host->GetSiteInstance(),
768 old_render_frame_host->render_view_host(), frame_tree_node_);
769 proxy_hosts_->Add(old_site_instance_id, make_scoped_ptr(proxy));
771 // Tell the old RenderFrameHost to swap out and be replaced by the proxy.
772 old_render_frame_host->SwapOut(proxy, true);
774 // SwapOut creates a RenderFrameProxy, so set the proxy to be initialized.
775 proxy->set_render_frame_proxy_created(true);
777 if (RenderFrameHostManager::IsSwappedOutStateForbidden()) {
778 // In --site-per-process, frames delete their RFH rather than storing it
779 // in the proxy. Schedule it for deletion once the SwapOutACK comes in.
780 // TODO(creis): This will be the default when we remove swappedout://.
781 MoveToPendingDeleteHosts(old_render_frame_host.Pass());
782 } else {
783 // We shouldn't get here for subframes, since we only swap subframes when
784 // --site-per-process is used.
785 DCHECK(frame_tree_node_->IsMainFrame());
787 // The old RenderFrameHost will stay alive inside the proxy so that existing
788 // JavaScript window references to it stay valid.
789 proxy->TakeFrameHostOwnership(old_render_frame_host.Pass());
793 void RenderFrameHostManager::DiscardUnusedFrame(
794 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
795 // TODO(carlosk): this code is very similar to what can be found in
796 // SwapOutOldFrame and we should see that these are unified at some point.
798 // If the SiteInstance for the pending RFH is being used by others don't
799 // delete the RFH. Just swap it out and it can be reused at a later point.
800 // In --site-per-process, RenderFrameHosts are not kept around and are
801 // deleted when not used, replaced by RenderFrameProxyHosts.
802 SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance();
803 if (site_instance->HasSite() && site_instance->active_frame_count() > 1) {
804 // Any currently suspended navigations are no longer needed.
805 render_frame_host->CancelSuspendedNavigations();
807 RenderFrameProxyHost* proxy = new RenderFrameProxyHost(
808 site_instance, render_frame_host->render_view_host(), frame_tree_node_);
809 proxy_hosts_->Add(site_instance->GetId(), make_scoped_ptr(proxy));
811 // Check if the RenderFrameHost is already swapped out, to avoid swapping it
812 // out again.
813 if (!render_frame_host->is_swapped_out())
814 render_frame_host->SwapOut(proxy, false);
816 if (!RenderFrameHostManager::IsSwappedOutStateForbidden()) {
817 DCHECK(frame_tree_node_->IsMainFrame());
818 proxy->TakeFrameHostOwnership(render_frame_host.Pass());
822 if (render_frame_host) {
823 // We won't be coming back, so delete this one.
824 ShutdownProxiesIfLastActiveFrameInSiteInstance(render_frame_host.get());
825 render_frame_host.reset();
829 void RenderFrameHostManager::MoveToPendingDeleteHosts(
830 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
831 // |render_frame_host| will be deleted when its SwapOut ACK is received, or
832 // when the timer times out, or when the RFHM itself is deleted (whichever
833 // comes first).
834 pending_delete_hosts_.push_back(
835 linked_ptr<RenderFrameHostImpl>(render_frame_host.release()));
838 bool RenderFrameHostManager::IsPendingDeletion(
839 RenderFrameHostImpl* render_frame_host) {
840 for (const auto& rfh : pending_delete_hosts_) {
841 if (rfh == render_frame_host)
842 return true;
844 return false;
847 bool RenderFrameHostManager::DeleteFromPendingList(
848 RenderFrameHostImpl* render_frame_host) {
849 for (RFHPendingDeleteList::iterator iter = pending_delete_hosts_.begin();
850 iter != pending_delete_hosts_.end();
851 iter++) {
852 if (*iter == render_frame_host) {
853 pending_delete_hosts_.erase(iter);
854 return true;
857 return false;
860 void RenderFrameHostManager::ResetProxyHosts() {
861 proxy_hosts_->Clear();
864 // PlzNavigate
865 void RenderFrameHostManager::DidCreateNavigationRequest(
866 const NavigationRequest& request) {
867 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
868 switches::kEnableBrowserSideNavigation));
869 // Clean up any state in case there's an ongoing navigation.
870 // TODO(carlosk): remove this cleanup here once we properly cancel ongoing
871 // navigations.
872 CleanUpNavigation();
874 RenderFrameHostImpl* dest_rfh = GetFrameHostForNavigation(request);
875 DCHECK(dest_rfh);
878 // PlzNavigate
879 RenderFrameHostImpl* RenderFrameHostManager::GetFrameHostForNavigation(
880 const NavigationRequest& request) {
881 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
882 switches::kEnableBrowserSideNavigation));
884 SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance();
886 SiteInstance* candidate_site_instance =
887 speculative_render_frame_host_
888 ? speculative_render_frame_host_->GetSiteInstance()
889 : nullptr;
891 scoped_refptr<SiteInstance> dest_site_instance = GetSiteInstanceForNavigation(
892 request.common_params().url, request.source_site_instance(),
893 request.dest_site_instance(), candidate_site_instance,
894 request.common_params().transition,
895 request.restore_type() != NavigationEntryImpl::RESTORE_NONE,
896 request.is_view_source());
898 // The appropriate RenderFrameHost to commit the navigation.
899 RenderFrameHostImpl* navigation_rfh = nullptr;
901 // Renderer-initiated main frame navigations that may require a SiteInstance
902 // swap are sent to the browser via the OpenURL IPC and are afterwards treated
903 // as browser-initiated navigations. NavigationRequests marked as
904 // renderer-initiated are created by receiving a BeginNavigation IPC, and will
905 // then proceed in the same renderer that sent the IPC due to the condition
906 // below.
907 // Subframe navigations will use the current renderer, unless
908 // --site-per-process is enabled.
909 // TODO(carlosk): Have renderer-initated main frame navigations swap processes
910 // if needed when it no longer breaks OAuth popups (see
911 // https://crbug.com/440266).
912 bool is_main_frame = frame_tree_node_->IsMainFrame();
913 if (current_site_instance == dest_site_instance.get() ||
914 (!request.browser_initiated() && is_main_frame) ||
915 (!is_main_frame && !dest_site_instance->RequiresDedicatedProcess() &&
916 !current_site_instance->RequiresDedicatedProcess())) {
917 // Reuse the current RFH if its SiteInstance matches the the navigation's
918 // or if this is a subframe navigation. We only swap RFHs for subframes when
919 // --site-per-process is enabled.
920 CleanUpNavigation();
921 navigation_rfh = render_frame_host_.get();
923 // As SiteInstances are the same, check if the WebUI should be reused.
924 const NavigationEntry* current_navigation_entry =
925 delegate_->GetLastCommittedNavigationEntryForRenderManager();
926 should_reuse_web_ui_ = ShouldReuseWebUI(current_navigation_entry,
927 request.common_params().url);
928 if (!should_reuse_web_ui_) {
929 speculative_web_ui_ = CreateWebUI(request.common_params().url,
930 request.bindings());
931 // Make sure the current RenderViewHost has the right bindings.
932 if (speculative_web_ui() &&
933 !render_frame_host_->GetProcess()->IsForGuestsOnly()) {
934 render_frame_host_->render_view_host()->AllowBindings(
935 speculative_web_ui()->GetBindings());
938 } else {
939 // If the SiteInstance for the final URL doesn't match the one from the
940 // speculatively created RenderFrameHost, create a new RenderFrameHost using
941 // this new SiteInstance.
942 if (!speculative_render_frame_host_ ||
943 speculative_render_frame_host_->GetSiteInstance() !=
944 dest_site_instance.get()) {
945 CleanUpNavigation();
946 bool success = CreateSpeculativeRenderFrameHost(
947 request.common_params().url, current_site_instance,
948 dest_site_instance.get(), request.bindings());
949 DCHECK(success);
951 DCHECK(speculative_render_frame_host_);
952 navigation_rfh = speculative_render_frame_host_.get();
954 // Check if our current RFH is live.
955 if (!render_frame_host_->IsRenderFrameLive()) {
956 // The current RFH is not live. There's no reason to sit around with a
957 // sad tab or a newly created RFH while we wait for the navigation to
958 // complete. Just switch to the speculative RFH now and go back to normal.
959 // (Note that we don't care about on{before}unload handlers if the current
960 // RFH isn't live.)
961 CommitPending();
964 DCHECK(navigation_rfh &&
965 (navigation_rfh == render_frame_host_.get() ||
966 navigation_rfh == speculative_render_frame_host_.get()));
968 // If the RenderFrame that needs to navigate is not live (its process was just
969 // created or has crashed), initialize it.
970 if (!navigation_rfh->IsRenderFrameLive()) {
971 // Recreate the opener chain.
972 CreateOpenerProxiesIfNeeded(navigation_rfh->GetSiteInstance());
973 if (!InitRenderView(navigation_rfh->render_view_host(), MSG_ROUTING_NONE,
974 frame_tree_node_->IsMainFrame())) {
975 return nullptr;
978 if (navigation_rfh == render_frame_host_) {
979 // TODO(nasko): This is a very ugly hack. The Chrome extensions process
980 // manager still uses NotificationService and expects to see a
981 // RenderViewHost changed notification after WebContents and
982 // RenderFrameHostManager are completely initialized. This should be
983 // removed once the process manager moves away from NotificationService.
984 // See https://crbug.com/462682.
985 delegate_->NotifyMainFrameSwappedFromRenderManager(
986 nullptr, render_frame_host_->render_view_host());
990 return navigation_rfh;
993 // PlzNavigate
994 void RenderFrameHostManager::CleanUpNavigation() {
995 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
996 switches::kEnableBrowserSideNavigation));
997 speculative_web_ui_.reset();
998 should_reuse_web_ui_ = false;
999 if (speculative_render_frame_host_)
1000 DiscardUnusedFrame(UnsetSpeculativeRenderFrameHost());
1003 // PlzNavigate
1004 scoped_ptr<RenderFrameHostImpl>
1005 RenderFrameHostManager::UnsetSpeculativeRenderFrameHost() {
1006 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1007 switches::kEnableBrowserSideNavigation));
1008 speculative_render_frame_host_->GetProcess()->RemovePendingView();
1009 return speculative_render_frame_host_.Pass();
1012 void RenderFrameHostManager::OnDidStartLoading() {
1013 for (const auto& pair : *proxy_hosts_) {
1014 pair.second->Send(
1015 new FrameMsg_DidStartLoading(pair.second->GetRoutingID()));
1019 void RenderFrameHostManager::OnDidStopLoading() {
1020 for (const auto& pair : *proxy_hosts_) {
1021 pair.second->Send(new FrameMsg_DidStopLoading(pair.second->GetRoutingID()));
1025 void RenderFrameHostManager::OnDidUpdateName(const std::string& name) {
1026 // The window.name message may be sent outside of --site-per-process when
1027 // report_frame_name_changes renderer preference is set (used by
1028 // WebView). Don't send the update to proxies in those cases.
1029 // TODO(nick,nasko): Should this be IsSwappedOutStateForbidden, to match
1030 // OnDidUpdateOrigin?
1031 if (!SiteIsolationPolicy::AreCrossProcessFramesPossible())
1032 return;
1034 for (const auto& pair : *proxy_hosts_) {
1035 pair.second->Send(
1036 new FrameMsg_DidUpdateName(pair.second->GetRoutingID(), name));
1040 void RenderFrameHostManager::OnDidUpdateOrigin(const url::Origin& origin) {
1041 if (!IsSwappedOutStateForbidden())
1042 return;
1044 for (const auto& pair : *proxy_hosts_) {
1045 pair.second->Send(
1046 new FrameMsg_DidUpdateOrigin(pair.second->GetRoutingID(), origin));
1050 RenderFrameHostManager::SiteInstanceDescriptor::SiteInstanceDescriptor(
1051 BrowserContext* browser_context,
1052 GURL dest_url,
1053 bool related_to_current)
1054 : existing_site_instance(nullptr),
1055 new_is_related_to_current(related_to_current) {
1056 new_site_url = SiteInstance::GetSiteForURL(browser_context, dest_url);
1059 // static
1060 bool RenderFrameHostManager::ClearProxiesInSiteInstance(
1061 int32 site_instance_id,
1062 FrameTreeNode* node) {
1063 RenderFrameProxyHost* proxy =
1064 node->render_manager()->proxy_hosts_->Get(site_instance_id);
1065 if (proxy) {
1066 // Delete the proxy. If it is for a main frame (and thus the RFH is stored
1067 // in the proxy) and it was still pending swap out, move the RFH to the
1068 // pending deletion list first.
1069 if (node->IsMainFrame() &&
1070 proxy->render_frame_host() &&
1071 proxy->render_frame_host()->rfh_state() ==
1072 RenderFrameHostImpl::STATE_PENDING_SWAP_OUT) {
1073 DCHECK(!RenderFrameHostManager::IsSwappedOutStateForbidden());
1074 scoped_ptr<RenderFrameHostImpl> swapped_out_rfh =
1075 proxy->PassFrameHostOwnership();
1076 node->render_manager()->MoveToPendingDeleteHosts(swapped_out_rfh.Pass());
1078 node->render_manager()->proxy_hosts_->Remove(site_instance_id);
1081 return true;
1084 // static.
1085 bool RenderFrameHostManager::ResetProxiesInSiteInstance(int32 site_instance_id,
1086 FrameTreeNode* node) {
1087 RenderFrameProxyHost* proxy =
1088 node->render_manager()->proxy_hosts_->Get(site_instance_id);
1089 if (proxy)
1090 proxy->set_render_frame_proxy_created(false);
1092 return true;
1095 bool RenderFrameHostManager::ShouldTransitionCrossSite() {
1096 // The logic below is weaker than "are all sites isolated" -- it asks instead,
1097 // "is any site isolated". That's appropriate here since we're just trying to
1098 // figure out if we're in any kind of site isolated mode, and in which case,
1099 // we ignore the kSingleProcess and kProcessPerTab settings.
1101 // TODO(nick): Move all handling of kSingleProcess/kProcessPerTab into
1102 // SiteIsolationPolicy so we have a consistent behavior around the interaction
1103 // of the process model flags.
1104 if (SiteIsolationPolicy::AreCrossProcessFramesPossible())
1105 return true;
1107 // False in the single-process mode, as it makes RVHs to accumulate
1108 // in swapped_out_hosts_.
1109 // True if we are using process-per-site-instance (default) or
1110 // process-per-site (kProcessPerSite).
1111 // TODO(nick): Move handling of kSingleProcess and kProcessPerTab into
1112 // SiteIsolationPolicy.
1113 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
1114 switches::kSingleProcess) &&
1115 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1116 switches::kProcessPerTab);
1119 bool RenderFrameHostManager::ShouldSwapBrowsingInstancesForNavigation(
1120 const GURL& current_effective_url,
1121 bool current_is_view_source_mode,
1122 SiteInstance* new_site_instance,
1123 const GURL& new_effective_url,
1124 bool new_is_view_source_mode) const {
1125 // If new_entry already has a SiteInstance, assume it is correct. We only
1126 // need to force a swap if it is in a different BrowsingInstance.
1127 if (new_site_instance) {
1128 return !new_site_instance->IsRelatedSiteInstance(
1129 render_frame_host_->GetSiteInstance());
1132 // Check for reasons to swap processes even if we are in a process model that
1133 // doesn't usually swap (e.g., process-per-tab). Any time we return true,
1134 // the new_entry will be rendered in a new SiteInstance AND BrowsingInstance.
1135 BrowserContext* browser_context =
1136 delegate_->GetControllerForRenderManager().GetBrowserContext();
1138 // Don't force a new BrowsingInstance for debug URLs that are handled in the
1139 // renderer process, like javascript: or chrome://crash.
1140 if (IsRendererDebugURL(new_effective_url))
1141 return false;
1143 // For security, we should transition between processes when one is a Web UI
1144 // page and one isn't.
1145 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1146 render_frame_host_->GetProcess()->GetID()) ||
1147 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1148 browser_context, current_effective_url)) {
1149 // If so, force a swap if destination is not an acceptable URL for Web UI.
1150 // Here, data URLs are never allowed.
1151 if (!WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
1152 browser_context, new_effective_url)) {
1153 return true;
1155 } else {
1156 // Force a swap if it's a Web UI URL.
1157 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1158 browser_context, new_effective_url)) {
1159 return true;
1163 // Check with the content client as well. Important to pass
1164 // current_effective_url here, which uses the SiteInstance's site if there is
1165 // no current_entry.
1166 if (GetContentClient()->browser()->ShouldSwapBrowsingInstancesForNavigation(
1167 render_frame_host_->GetSiteInstance(),
1168 current_effective_url, new_effective_url)) {
1169 return true;
1172 // We can't switch a RenderView between view source and non-view source mode
1173 // without screwing up the session history sometimes (when navigating between
1174 // "view-source:http://foo.com/" and "http://foo.com/", Blink doesn't treat
1175 // it as a new navigation). So require a BrowsingInstance switch.
1176 if (current_is_view_source_mode != new_is_view_source_mode)
1177 return true;
1179 return false;
1182 bool RenderFrameHostManager::ShouldReuseWebUI(
1183 const NavigationEntry* current_entry,
1184 const GURL& new_url) const {
1185 NavigationControllerImpl& controller =
1186 delegate_->GetControllerForRenderManager();
1187 return current_entry && web_ui_ &&
1188 (WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
1189 controller.GetBrowserContext(), current_entry->GetURL()) ==
1190 WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
1191 controller.GetBrowserContext(), new_url));
1194 SiteInstance* RenderFrameHostManager::GetSiteInstanceForNavigation(
1195 const GURL& dest_url,
1196 SiteInstance* source_instance,
1197 SiteInstance* dest_instance,
1198 SiteInstance* candidate_instance,
1199 ui::PageTransition transition,
1200 bool dest_is_restore,
1201 bool dest_is_view_source_mode) {
1202 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1204 // We do not currently swap processes for navigations in webview tag guests.
1205 if (current_instance->GetSiteURL().SchemeIs(kGuestScheme))
1206 return current_instance;
1208 // Determine if we need a new BrowsingInstance for this entry. If true, this
1209 // implies that it will get a new SiteInstance (and likely process), and that
1210 // other tabs in the current BrowsingInstance will be unable to script it.
1211 // This is used for cases that require a process swap even in the
1212 // process-per-tab model, such as WebUI pages.
1213 // TODO(clamy): Remove the dependency on the current entry.
1214 const NavigationEntry* current_entry =
1215 delegate_->GetLastCommittedNavigationEntryForRenderManager();
1216 BrowserContext* browser_context =
1217 delegate_->GetControllerForRenderManager().GetBrowserContext();
1218 const GURL& current_effective_url = current_entry ?
1219 SiteInstanceImpl::GetEffectiveURL(browser_context,
1220 current_entry->GetURL()) :
1221 render_frame_host_->GetSiteInstance()->GetSiteURL();
1222 bool current_is_view_source_mode = current_entry ?
1223 current_entry->IsViewSourceMode() : dest_is_view_source_mode;
1224 bool force_swap = ShouldSwapBrowsingInstancesForNavigation(
1225 current_effective_url,
1226 current_is_view_source_mode,
1227 dest_instance,
1228 SiteInstanceImpl::GetEffectiveURL(browser_context, dest_url),
1229 dest_is_view_source_mode);
1230 SiteInstanceDescriptor new_instance_descriptor =
1231 SiteInstanceDescriptor(current_instance);
1232 if (ShouldTransitionCrossSite() || force_swap) {
1233 new_instance_descriptor = DetermineSiteInstanceForURL(
1234 dest_url, source_instance, current_instance, dest_instance, transition,
1235 dest_is_restore, dest_is_view_source_mode, force_swap);
1238 SiteInstance* new_instance =
1239 ConvertToSiteInstance(new_instance_descriptor, candidate_instance);
1241 // If |force_swap| is true, we must use a different SiteInstance than the
1242 // current one. If we didn't, we would have two RenderFrameHosts in the same
1243 // SiteInstance and the same frame, resulting in page_id conflicts for their
1244 // NavigationEntries.
1245 if (force_swap)
1246 CHECK_NE(new_instance, current_instance);
1247 return new_instance;
1250 RenderFrameHostManager::SiteInstanceDescriptor
1251 RenderFrameHostManager::DetermineSiteInstanceForURL(
1252 const GURL& dest_url,
1253 SiteInstance* source_instance,
1254 SiteInstance* current_instance,
1255 SiteInstance* dest_instance,
1256 ui::PageTransition transition,
1257 bool dest_is_restore,
1258 bool dest_is_view_source_mode,
1259 bool force_browsing_instance_swap) {
1260 SiteInstanceImpl* current_instance_impl =
1261 static_cast<SiteInstanceImpl*>(current_instance);
1262 NavigationControllerImpl& controller =
1263 delegate_->GetControllerForRenderManager();
1264 BrowserContext* browser_context = controller.GetBrowserContext();
1266 // If the entry has an instance already we should use it.
1267 if (dest_instance) {
1268 // If we are forcing a swap, this should be in a different BrowsingInstance.
1269 if (force_browsing_instance_swap) {
1270 CHECK(!dest_instance->IsRelatedSiteInstance(
1271 render_frame_host_->GetSiteInstance()));
1273 return SiteInstanceDescriptor(dest_instance);
1276 // If a swap is required, we need to force the SiteInstance AND
1277 // BrowsingInstance to be different ones, using CreateForURL.
1278 if (force_browsing_instance_swap)
1279 return SiteInstanceDescriptor(browser_context, dest_url, false);
1281 // (UGLY) HEURISTIC, process-per-site only:
1283 // If this navigation is generated, then it probably corresponds to a search
1284 // query. Given that search results typically lead to users navigating to
1285 // other sites, we don't really want to use the search engine hostname to
1286 // determine the site instance for this navigation.
1288 // NOTE: This can be removed once we have a way to transition between
1289 // RenderViews in response to a link click.
1291 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1292 switches::kProcessPerSite) &&
1293 ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_GENERATED)) {
1294 return SiteInstanceDescriptor(current_instance_impl);
1297 // If we haven't used our SiteInstance (and thus RVH) yet, then we can use it
1298 // for this entry. We won't commit the SiteInstance to this site until the
1299 // navigation commits (in DidNavigate), unless the navigation entry was
1300 // restored or it's a Web UI as described below.
1301 if (!current_instance_impl->HasSite()) {
1302 // If we've already created a SiteInstance for our destination, we don't
1303 // want to use this unused SiteInstance; use the existing one. (We don't
1304 // do this check if the current_instance has a site, because for now, we
1305 // want to compare against the current URL and not the SiteInstance's site.
1306 // In this case, there is no current URL, so comparing against the site is
1307 // ok. See additional comments below.)
1309 // Also, if the URL should use process-per-site mode and there is an
1310 // existing process for the site, we should use it. We can call
1311 // GetRelatedSiteInstance() for this, which will eagerly set the site and
1312 // thus use the correct process.
1313 bool use_process_per_site =
1314 RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) &&
1315 RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url);
1316 if (current_instance_impl->HasRelatedSiteInstance(dest_url) ||
1317 use_process_per_site) {
1318 return SiteInstanceDescriptor(browser_context, dest_url, true);
1321 // For extensions, Web UI URLs (such as the new tab page), and apps we do
1322 // not want to use the |current_instance_impl| if it has no site, since it
1323 // will have a RenderProcessHost of PRIV_NORMAL. Create a new SiteInstance
1324 // for this URL instead (with the correct process type).
1325 if (current_instance_impl->HasWrongProcessForURL(dest_url))
1326 return SiteInstanceDescriptor(browser_context, dest_url, true);
1328 // View-source URLs must use a new SiteInstance and BrowsingInstance.
1329 // TODO(nasko): This is the same condition as later in the function. This
1330 // should be taken into account when refactoring this method as part of
1331 // http://crbug.com/123007.
1332 if (dest_is_view_source_mode)
1333 return SiteInstanceDescriptor(browser_context, dest_url, false);
1335 // If we are navigating from a blank SiteInstance to a WebUI, make sure we
1336 // create a new SiteInstance.
1337 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1338 browser_context, dest_url)) {
1339 return SiteInstanceDescriptor(browser_context, dest_url, false);
1342 // Normally the "site" on the SiteInstance is set lazily when the load
1343 // actually commits. This is to support better process sharing in case
1344 // the site redirects to some other site: we want to use the destination
1345 // site in the site instance.
1347 // In the case of session restore, as it loads all the pages immediately
1348 // we need to set the site first, otherwise after a restore none of the
1349 // pages would share renderers in process-per-site.
1351 // The embedder can request some urls never to be assigned to SiteInstance
1352 // through the ShouldAssignSiteForURL() content client method, so that
1353 // renderers created for particular chrome urls (e.g. the chrome-native://
1354 // scheme) can be reused for subsequent navigations in the same WebContents.
1355 // See http://crbug.com/386542.
1356 if (dest_is_restore &&
1357 GetContentClient()->browser()->ShouldAssignSiteForURL(dest_url)) {
1358 current_instance_impl->SetSite(dest_url);
1361 return SiteInstanceDescriptor(current_instance_impl);
1364 // Otherwise, only create a new SiteInstance for a cross-process navigation.
1366 // TODO(creis): Once we intercept links and script-based navigations, we
1367 // will be able to enforce that all entries in a SiteInstance actually have
1368 // the same site, and it will be safe to compare the URL against the
1369 // SiteInstance's site, as follows:
1370 // const GURL& current_url = current_instance_impl->site();
1371 // For now, though, we're in a hybrid model where you only switch
1372 // SiteInstances if you type in a cross-site URL. This means we have to
1373 // compare the entry's URL to the last committed entry's URL.
1374 NavigationEntry* current_entry = controller.GetLastCommittedEntry();
1375 if (interstitial_page_) {
1376 // The interstitial is currently the last committed entry, but we want to
1377 // compare against the last non-interstitial entry.
1378 current_entry = controller.GetEntryAtOffset(-1);
1381 // View-source URLs must use a new SiteInstance and BrowsingInstance.
1382 // We don't need a swap when going from view-source to a debug URL like
1383 // chrome://crash, however.
1384 // TODO(creis): Refactor this method so this duplicated code isn't needed.
1385 // See http://crbug.com/123007.
1386 if (current_entry &&
1387 current_entry->IsViewSourceMode() != dest_is_view_source_mode &&
1388 !IsRendererDebugURL(dest_url)) {
1389 return SiteInstanceDescriptor(browser_context, dest_url, false);
1392 // Use the source SiteInstance in case of data URLs or about:blank pages,
1393 // because the content is then controlled and/or scriptable by the source
1394 // SiteInstance.
1395 GURL about_blank(url::kAboutBlankURL);
1396 if (source_instance &&
1397 (dest_url == about_blank || dest_url.scheme() == url::kDataScheme)) {
1398 return SiteInstanceDescriptor(source_instance);
1401 // Use the current SiteInstance for same site navigations, as long as the
1402 // process type is correct. (The URL may have been installed as an app since
1403 // the last time we visited it.)
1404 const GURL& current_url =
1405 GetCurrentURLForSiteInstance(current_instance_impl, current_entry);
1406 if (SiteInstance::IsSameWebSite(browser_context, current_url, dest_url) &&
1407 !current_instance_impl->HasWrongProcessForURL(dest_url)) {
1408 return SiteInstanceDescriptor(current_instance_impl);
1411 // Start the new renderer in a new SiteInstance, but in the current
1412 // BrowsingInstance. It is important to immediately give this new
1413 // SiteInstance to a RenderViewHost (if it is different than our current
1414 // SiteInstance), so that it is ref counted. This will happen in
1415 // CreateRenderView.
1416 return SiteInstanceDescriptor(browser_context, dest_url, true);
1419 SiteInstance* RenderFrameHostManager::ConvertToSiteInstance(
1420 const SiteInstanceDescriptor& descriptor,
1421 SiteInstance* candidate_instance) {
1422 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1424 // Note: If the |candidate_instance| matches the descriptor, it will already
1425 // be set to |descriptor.existing_site_instance|.
1426 if (descriptor.existing_site_instance)
1427 return descriptor.existing_site_instance;
1429 // Note: If the |candidate_instance| matches the descriptor,
1430 // GetRelatedSiteInstance will return it.
1431 if (descriptor.new_is_related_to_current)
1432 return current_instance->GetRelatedSiteInstance(descriptor.new_site_url);
1434 // At this point we know an unrelated site instance must be returned. First
1435 // check if the candidate matches.
1436 if (candidate_instance &&
1437 !current_instance->IsRelatedSiteInstance(candidate_instance) &&
1438 candidate_instance->GetSiteURL() == descriptor.new_site_url) {
1439 return candidate_instance;
1442 // Otherwise return a newly created one.
1443 return SiteInstance::CreateForURL(
1444 delegate_->GetControllerForRenderManager().GetBrowserContext(),
1445 descriptor.new_site_url);
1448 const GURL& RenderFrameHostManager::GetCurrentURLForSiteInstance(
1449 SiteInstance* current_instance, NavigationEntry* current_entry) {
1450 // If this is a subframe that is potentially out of process from its parent,
1451 // don't consider using current_entry's url for SiteInstance selection, since
1452 // current_entry's url is for the main frame and may be in a different site
1453 // than this frame.
1454 // TODO(creis): Remove this when we can check the FrameNavigationEntry's url.
1455 // See http://crbug.com/369654
1456 if (!frame_tree_node_->IsMainFrame() &&
1457 SiteIsolationPolicy::AreCrossProcessFramesPossible())
1458 return frame_tree_node_->current_url();
1460 // If there is no last non-interstitial entry (and current_instance already
1461 // has a site), then we must have been opened from another tab. We want
1462 // to compare against the URL of the page that opened us, but we can't
1463 // get to it directly. The best we can do is check against the site of
1464 // the SiteInstance. This will be correct when we intercept links and
1465 // script-based navigations, but for now, it could place some pages in a
1466 // new process unnecessarily. We should only hit this case if a page tries
1467 // to open a new tab to an interstitial-inducing URL, and then navigates
1468 // the page to a different same-site URL. (This seems very unlikely in
1469 // practice.)
1470 if (current_entry)
1471 return current_entry->GetURL();
1472 return current_instance->GetSiteURL();
1475 void RenderFrameHostManager::CreatePendingRenderFrameHost(
1476 SiteInstance* old_instance,
1477 SiteInstance* new_instance,
1478 bool is_main_frame) {
1479 int create_render_frame_flags = 0;
1480 if (is_main_frame)
1481 create_render_frame_flags |= CREATE_RF_FOR_MAIN_FRAME_NAVIGATION;
1483 if (delegate_->IsHidden())
1484 create_render_frame_flags |= CREATE_RF_HIDDEN;
1486 if (pending_render_frame_host_)
1487 CancelPending();
1489 // The process for the new SiteInstance may (if we're sharing a process with
1490 // another host that already initialized it) or may not (we have our own
1491 // process or the existing process crashed) have been initialized. Calling
1492 // Init multiple times will be ignored, so this is safe.
1493 if (!new_instance->GetProcess()->Init())
1494 return;
1496 CreateProxiesForNewRenderFrameHost(old_instance, new_instance,
1497 &create_render_frame_flags);
1499 // Create a non-swapped-out RFH with the given opener.
1500 pending_render_frame_host_ = CreateRenderFrame(
1501 new_instance, pending_web_ui(), create_render_frame_flags, nullptr);
1504 void RenderFrameHostManager::CreateProxiesForNewRenderFrameHost(
1505 SiteInstance* old_instance,
1506 SiteInstance* new_instance,
1507 int* create_render_frame_flags) {
1508 // Only create opener proxies if they are in the same BrowsingInstance.
1509 if (new_instance->IsRelatedSiteInstance(old_instance))
1510 CreateOpenerProxiesIfNeeded(new_instance);
1511 if (SiteIsolationPolicy::AreCrossProcessFramesPossible()) {
1512 // Ensure that the frame tree has RenderFrameProxyHosts for the new
1513 // SiteInstance in all nodes except the current one. We do this for all
1514 // frames in the tree, whether they are in the same BrowsingInstance or not.
1515 // We will still check whether two frames are in the same BrowsingInstance
1516 // before we allow them to interact (e.g., postMessage).
1517 frame_tree_node_->frame_tree()->CreateProxiesForSiteInstance(
1518 frame_tree_node_, new_instance);
1519 // RenderFrames in different processes from their parent RenderFrames
1520 // in the frame tree require RenderWidgets for rendering and processing
1521 // input events.
1522 if (frame_tree_node_->parent() &&
1523 frame_tree_node_->parent()->current_frame_host()->GetSiteInstance() !=
1524 new_instance)
1525 *create_render_frame_flags |= CREATE_RF_NEEDS_RENDER_WIDGET_HOST;
1529 void RenderFrameHostManager::CreateProxiesForNewNamedFrame() {
1530 if (!SiteIsolationPolicy::AreCrossProcessFramesPossible())
1531 return;
1533 DCHECK(!frame_tree_node_->frame_name().empty());
1535 // If this is a top-level frame, create proxies for this node in the
1536 // SiteInstances of its opener's ancestors, which are allowed to discover
1537 // this frame by name (see https://crbug.com/511474 and part 4 of
1538 // https://html.spec.whatwg.org/#the-rules-for-choosing-a-browsing-context-
1539 // given-a-browsing-context-name).
1540 FrameTreeNode* opener = frame_tree_node_->opener();
1541 if (!opener || !frame_tree_node_->IsMainFrame())
1542 return;
1543 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1545 // Start from opener's parent. There's no need to create a proxy in the
1546 // opener's SiteInstance, since new windows are always first opened in the
1547 // same SiteInstance as their opener, and if the new window navigates
1548 // cross-site, that proxy would be created as part of swapping out.
1549 for (FrameTreeNode* ancestor = opener->parent(); ancestor;
1550 ancestor = ancestor->parent()) {
1551 RenderFrameHostImpl* ancestor_rfh = ancestor->current_frame_host();
1552 if (ancestor_rfh->GetSiteInstance() != current_instance)
1553 CreateRenderFrameProxy(ancestor_rfh->GetSiteInstance());
1557 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::CreateRenderFrameHost(
1558 SiteInstance* site_instance,
1559 int view_routing_id,
1560 int frame_routing_id,
1561 int flags) {
1562 if (frame_routing_id == MSG_ROUTING_NONE)
1563 frame_routing_id = site_instance->GetProcess()->GetNextRoutingID();
1565 bool swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
1566 bool hidden = !!(flags & CREATE_RF_HIDDEN);
1568 // Create a RVH for main frames, or find the existing one for subframes.
1569 FrameTree* frame_tree = frame_tree_node_->frame_tree();
1570 RenderViewHostImpl* render_view_host = nullptr;
1571 if (frame_tree_node_->IsMainFrame()) {
1572 render_view_host = frame_tree->CreateRenderViewHost(
1573 site_instance, view_routing_id, frame_routing_id, swapped_out, hidden);
1574 } else {
1575 render_view_host = frame_tree->GetRenderViewHost(site_instance);
1577 CHECK(render_view_host);
1580 // TODO(creis): Pass hidden to RFH.
1581 scoped_ptr<RenderFrameHostImpl> render_frame_host = make_scoped_ptr(
1582 RenderFrameHostFactory::Create(
1583 site_instance, render_view_host, render_frame_delegate_,
1584 render_widget_delegate_, frame_tree, frame_tree_node_,
1585 frame_routing_id, flags).release());
1586 return render_frame_host.Pass();
1589 // PlzNavigate
1590 bool RenderFrameHostManager::CreateSpeculativeRenderFrameHost(
1591 const GURL& url,
1592 SiteInstance* old_instance,
1593 SiteInstance* new_instance,
1594 int bindings) {
1595 CHECK(new_instance);
1596 CHECK_NE(old_instance, new_instance);
1597 CHECK(!should_reuse_web_ui_);
1599 // Note: |speculative_web_ui_| must be initialized before starting the
1600 // |speculative_render_frame_host_| creation steps otherwise the WebUI
1601 // won't be properly initialized.
1602 speculative_web_ui_ = CreateWebUI(url, bindings);
1604 // The process for the new SiteInstance may (if we're sharing a process with
1605 // another host that already initialized it) or may not (we have our own
1606 // process or the existing process crashed) have been initialized. Calling
1607 // Init multiple times will be ignored, so this is safe.
1608 if (!new_instance->GetProcess()->Init())
1609 return false;
1611 int create_render_frame_flags = 0;
1612 CreateProxiesForNewRenderFrameHost(old_instance, new_instance,
1613 &create_render_frame_flags);
1615 if (frame_tree_node_->IsMainFrame())
1616 create_render_frame_flags |= CREATE_RF_FOR_MAIN_FRAME_NAVIGATION;
1617 if (delegate_->IsHidden())
1618 create_render_frame_flags |= CREATE_RF_HIDDEN;
1619 speculative_render_frame_host_ =
1620 CreateRenderFrame(new_instance, speculative_web_ui_.get(),
1621 create_render_frame_flags, nullptr);
1623 if (!speculative_render_frame_host_) {
1624 speculative_web_ui_.reset();
1625 return false;
1627 return true;
1630 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::CreateRenderFrame(
1631 SiteInstance* instance,
1632 WebUIImpl* web_ui,
1633 int flags,
1634 int* view_routing_id_ptr) {
1635 bool swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
1636 bool swapped_out_forbidden = IsSwappedOutStateForbidden();
1638 CHECK(instance);
1639 CHECK_IMPLIES(swapped_out_forbidden, !swapped_out);
1640 CHECK_IMPLIES(!SiteIsolationPolicy::AreCrossProcessFramesPossible(),
1641 frame_tree_node_->IsMainFrame());
1643 // Swapped out views should always be hidden.
1644 DCHECK_IMPLIES(swapped_out, (flags & CREATE_RF_HIDDEN));
1646 scoped_ptr<RenderFrameHostImpl> new_render_frame_host;
1647 bool success = true;
1648 if (view_routing_id_ptr)
1649 *view_routing_id_ptr = MSG_ROUTING_NONE;
1651 // We are creating a pending, speculative or swapped out RFH here. We should
1652 // never create it in the same SiteInstance as our current RFH.
1653 CHECK_NE(render_frame_host_->GetSiteInstance(), instance);
1655 // Check if we've already created an RFH for this SiteInstance. If so, try
1656 // to re-use the existing one, which has already been initialized. We'll
1657 // remove it from the list of proxy hosts below if it will be active.
1658 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1659 if (proxy && proxy->render_frame_host()) {
1660 CHECK(!swapped_out_forbidden);
1661 if (view_routing_id_ptr)
1662 *view_routing_id_ptr = proxy->GetRenderViewHost()->GetRoutingID();
1663 // Delete the existing RenderFrameProxyHost, but reuse the RenderFrameHost.
1664 // Prevent the process from exiting while we're trying to use it.
1665 if (!swapped_out) {
1666 new_render_frame_host = proxy->PassFrameHostOwnership();
1667 new_render_frame_host->GetProcess()->AddPendingView();
1669 proxy_hosts_->Remove(instance->GetId());
1670 // NB |proxy| is deleted at this point.
1672 } else {
1673 // Create a new RenderFrameHost if we don't find an existing one.
1674 new_render_frame_host = CreateRenderFrameHost(instance, MSG_ROUTING_NONE,
1675 MSG_ROUTING_NONE, flags);
1676 RenderViewHostImpl* render_view_host =
1677 new_render_frame_host->render_view_host();
1678 int proxy_routing_id = MSG_ROUTING_NONE;
1680 // Prevent the process from exiting while we're trying to navigate in it.
1681 // Otherwise, if the new RFH is swapped out already, store it.
1682 if (!swapped_out) {
1683 new_render_frame_host->GetProcess()->AddPendingView();
1684 } else {
1685 proxy = new RenderFrameProxyHost(
1686 new_render_frame_host->GetSiteInstance(),
1687 new_render_frame_host->render_view_host(), frame_tree_node_);
1688 proxy_hosts_->Add(instance->GetId(), make_scoped_ptr(proxy));
1689 proxy_routing_id = proxy->GetRoutingID();
1690 proxy->TakeFrameHostOwnership(new_render_frame_host.Pass());
1693 success = InitRenderView(render_view_host, proxy_routing_id,
1694 !!(flags & CREATE_RF_FOR_MAIN_FRAME_NAVIGATION));
1695 if (success) {
1696 // Remember that InitRenderView also created the RenderFrameProxy.
1697 if (swapped_out)
1698 proxy->set_render_frame_proxy_created(true);
1699 if (frame_tree_node_->IsMainFrame()) {
1700 // Don't show the main frame's view until we get a DidNavigate from it.
1701 // Only the RenderViewHost for the top-level RenderFrameHost has a
1702 // RenderWidgetHostView; RenderWidgetHosts for out-of-process iframes
1703 // will be created later and hidden.
1704 if (render_view_host->GetView())
1705 render_view_host->GetView()->Hide();
1707 // RenderViewHost for |instance| might exist prior to calling
1708 // CreateRenderFrame. In such a case, InitRenderView will not create the
1709 // RenderFrame in the renderer process and it needs to be done
1710 // explicitly.
1711 if (swapped_out_forbidden) {
1712 // Init the RFH, so a RenderFrame is created in the renderer.
1713 DCHECK(new_render_frame_host);
1714 success = InitRenderFrame(new_render_frame_host.get());
1718 if (success) {
1719 if (view_routing_id_ptr)
1720 *view_routing_id_ptr = render_view_host->GetRoutingID();
1724 // When a new RenderView is created by the renderer process, the new
1725 // WebContents gets a RenderViewHost in the SiteInstance of its opener
1726 // WebContents. If not used in the first navigation, this RVH is swapped out
1727 // and is not granted bindings, so we may need to grant them when swapping it
1728 // in.
1729 if (web_ui && !new_render_frame_host->GetProcess()->IsForGuestsOnly()) {
1730 int required_bindings = web_ui->GetBindings();
1731 RenderViewHost* render_view_host =
1732 new_render_frame_host->render_view_host();
1733 if ((render_view_host->GetEnabledBindings() & required_bindings) !=
1734 required_bindings) {
1735 render_view_host->AllowBindings(required_bindings);
1739 // Returns the new RFH if it isn't swapped out.
1740 if (success && !swapped_out) {
1741 DCHECK(new_render_frame_host->GetSiteInstance() == instance);
1742 return new_render_frame_host.Pass();
1744 return nullptr;
1747 int RenderFrameHostManager::CreateRenderFrameProxy(SiteInstance* instance) {
1748 // A RenderFrameProxyHost should never be created in the same SiteInstance as
1749 // the current RFH.
1750 CHECK(instance);
1751 CHECK_NE(instance, render_frame_host_->GetSiteInstance());
1753 RenderViewHostImpl* render_view_host = nullptr;
1755 // Ensure a RenderViewHost exists for |instance|, as it creates the page
1756 // level structure in Blink.
1757 if (RenderFrameHostManager::IsSwappedOutStateForbidden()) {
1758 render_view_host =
1759 frame_tree_node_->frame_tree()->GetRenderViewHost(instance);
1760 if (!render_view_host) {
1761 CHECK(frame_tree_node_->IsMainFrame());
1762 render_view_host = frame_tree_node_->frame_tree()->CreateRenderViewHost(
1763 instance, MSG_ROUTING_NONE, MSG_ROUTING_NONE, true, true);
1767 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1768 if (proxy && proxy->is_render_frame_proxy_live())
1769 return proxy->GetRoutingID();
1771 if (!proxy) {
1772 proxy =
1773 new RenderFrameProxyHost(instance, render_view_host, frame_tree_node_);
1774 proxy_hosts_->Add(instance->GetId(), make_scoped_ptr(proxy));
1777 if (RenderFrameHostManager::IsSwappedOutStateForbidden() &&
1778 frame_tree_node_->IsMainFrame()) {
1779 InitRenderView(render_view_host, proxy->GetRoutingID(), true);
1780 proxy->set_render_frame_proxy_created(true);
1781 } else {
1782 proxy->InitRenderFrameProxy();
1785 return proxy->GetRoutingID();
1788 void RenderFrameHostManager::CreateProxiesForChildFrame(FrameTreeNode* child) {
1789 for (const auto& pair : *proxy_hosts_) {
1790 child->render_manager()->CreateRenderFrameProxy(
1791 pair.second->GetSiteInstance());
1795 void RenderFrameHostManager::EnsureRenderViewInitialized(
1796 RenderViewHostImpl* render_view_host,
1797 SiteInstance* instance) {
1798 DCHECK(frame_tree_node_->IsMainFrame());
1800 if (render_view_host->IsRenderViewLive())
1801 return;
1803 // Recreate the opener chain.
1804 CreateOpenerProxiesIfNeeded(instance);
1806 // If the proxy in |instance| doesn't exist, this RenderView is not swapped
1807 // out and shouldn't be reinitialized here.
1808 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1809 if (!proxy)
1810 return;
1812 InitRenderView(render_view_host, proxy->GetRoutingID(), false);
1813 proxy->set_render_frame_proxy_created(true);
1816 void RenderFrameHostManager::CreateOuterDelegateProxy(
1817 SiteInstance* outer_contents_site_instance,
1818 RenderFrameHostImpl* render_frame_host) {
1819 CHECK(BrowserPluginGuestMode::UseCrossProcessFramesForGuests());
1820 RenderFrameProxyHost* proxy = new RenderFrameProxyHost(
1821 outer_contents_site_instance, nullptr, frame_tree_node_);
1822 proxy_hosts_->Add(outer_contents_site_instance->GetId(),
1823 make_scoped_ptr(proxy));
1825 // Swap the outer WebContents's frame with the proxy to inner WebContents.
1827 // We are in the outer WebContents, and its FrameTree would never see
1828 // a load start for any of its inner WebContents. Eventually, that also makes
1829 // the FrameTree never see the matching load stop. Therefore, we always pass
1830 // false to |is_loading| below.
1831 // TODO(lazyboy): This |is_loading| behavior might not be what we want,
1832 // investigate and fix.
1833 render_frame_host->Send(new FrameMsg_SwapOut(
1834 render_frame_host->GetRoutingID(), proxy->GetRoutingID(),
1835 false /* is_loading */, FrameReplicationState()));
1836 proxy->set_render_frame_proxy_created(true);
1839 void RenderFrameHostManager::SetRWHViewForInnerContents(
1840 RenderWidgetHostView* child_rwhv) {
1841 DCHECK(ForInnerDelegate());
1842 GetProxyToOuterDelegate()->SetChildRWHView(child_rwhv);
1845 bool RenderFrameHostManager::InitRenderView(
1846 RenderViewHostImpl* render_view_host,
1847 int proxy_routing_id,
1848 bool for_main_frame_navigation) {
1849 // Ensure the renderer process is initialized before creating the
1850 // RenderView.
1851 if (!render_view_host->GetProcess()->Init())
1852 return false;
1854 // We may have initialized this RenderViewHost for another RenderFrameHost.
1855 if (render_view_host->IsRenderViewLive())
1856 return true;
1858 // If the ongoing navigation is to a WebUI and the RenderView is not in a
1859 // guest process, tell the RenderViewHost about any bindings it will need
1860 // enabled.
1861 WebUIImpl* dest_web_ui = nullptr;
1862 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1863 switches::kEnableBrowserSideNavigation)) {
1864 dest_web_ui =
1865 should_reuse_web_ui_ ? web_ui_.get() : speculative_web_ui_.get();
1866 } else {
1867 dest_web_ui = pending_web_ui();
1869 if (dest_web_ui && !render_view_host->GetProcess()->IsForGuestsOnly()) {
1870 render_view_host->AllowBindings(dest_web_ui->GetBindings());
1871 } else {
1872 // Ensure that we don't create an unprivileged RenderView in a WebUI-enabled
1873 // process unless it's swapped out.
1874 if (render_view_host->is_active()) {
1875 CHECK(!ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1876 render_view_host->GetProcess()->GetID()));
1880 int opener_frame_routing_id =
1881 GetOpenerRoutingID(render_view_host->GetSiteInstance());
1883 return delegate_->CreateRenderViewForRenderManager(
1884 render_view_host, opener_frame_routing_id, proxy_routing_id,
1885 frame_tree_node_->current_replication_state(), for_main_frame_navigation);
1888 bool RenderFrameHostManager::InitRenderFrame(
1889 RenderFrameHostImpl* render_frame_host) {
1890 if (render_frame_host->IsRenderFrameLive())
1891 return true;
1893 int parent_routing_id = MSG_ROUTING_NONE;
1894 int previous_sibling_routing_id = MSG_ROUTING_NONE;
1895 int proxy_routing_id = MSG_ROUTING_NONE;
1897 if (frame_tree_node_->parent()) {
1898 parent_routing_id = frame_tree_node_->parent()->render_manager()->
1899 GetRoutingIdForSiteInstance(render_frame_host->GetSiteInstance());
1900 CHECK_NE(parent_routing_id, MSG_ROUTING_NONE);
1903 // At this point, all RenderFrameProxies for sibling frames have already been
1904 // created, including any proxies that come after this frame. To preserve
1905 // correct order for indexed window access (e.g., window.frames[1]), pass the
1906 // previous sibling frame so that this frame is correctly inserted into the
1907 // frame tree on the renderer side.
1908 FrameTreeNode* previous_sibling = frame_tree_node_->PreviousSibling();
1909 if (previous_sibling) {
1910 previous_sibling_routing_id =
1911 previous_sibling->render_manager()->GetRoutingIdForSiteInstance(
1912 render_frame_host->GetSiteInstance());
1913 CHECK_NE(previous_sibling_routing_id, MSG_ROUTING_NONE);
1916 // Check whether there is an existing proxy for this frame in this
1917 // SiteInstance. If there is, the new RenderFrame needs to be able to find
1918 // the proxy it is replacing, so that it can fully initialize itself.
1919 // NOTE: This is the only time that a RenderFrameProxyHost can be in the same
1920 // SiteInstance as its RenderFrameHost. This is only the case until the
1921 // RenderFrameHost commits, at which point it will replace and delete the
1922 // RenderFrameProxyHost.
1923 RenderFrameProxyHost* existing_proxy =
1924 GetRenderFrameProxyHost(render_frame_host->GetSiteInstance());
1925 if (existing_proxy) {
1926 proxy_routing_id = existing_proxy->GetRoutingID();
1927 CHECK_NE(proxy_routing_id, MSG_ROUTING_NONE);
1928 if (!existing_proxy->is_render_frame_proxy_live())
1929 existing_proxy->InitRenderFrameProxy();
1931 return delegate_->CreateRenderFrameForRenderManager(
1932 render_frame_host, parent_routing_id, previous_sibling_routing_id,
1933 proxy_routing_id);
1936 int RenderFrameHostManager::GetRoutingIdForSiteInstance(
1937 SiteInstance* site_instance) {
1938 if (render_frame_host_->GetSiteInstance() == site_instance)
1939 return render_frame_host_->GetRoutingID();
1941 // If there is a matching pending RFH, only return it if swapped out is
1942 // allowed, since otherwise there should be a proxy that should be used
1943 // instead.
1944 if (pending_render_frame_host_ &&
1945 pending_render_frame_host_->GetSiteInstance() == site_instance &&
1946 !RenderFrameHostManager::IsSwappedOutStateForbidden())
1947 return pending_render_frame_host_->GetRoutingID();
1949 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(site_instance);
1950 if (proxy)
1951 return proxy->GetRoutingID();
1953 return MSG_ROUTING_NONE;
1956 void RenderFrameHostManager::CommitPending() {
1957 TRACE_EVENT1("navigation", "RenderFrameHostManager::CommitPending",
1958 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
1959 bool browser_side_navigation =
1960 base::CommandLine::ForCurrentProcess()->HasSwitch(
1961 switches::kEnableBrowserSideNavigation);
1963 // First check whether we're going to want to focus the location bar after
1964 // this commit. We do this now because the navigation hasn't formally
1965 // committed yet, so if we've already cleared |pending_web_ui_| the call chain
1966 // this triggers won't be able to figure out what's going on.
1967 bool will_focus_location_bar = delegate_->FocusLocationBarByDefault();
1969 // Next commit the Web UI, if any. Either replace |web_ui_| with
1970 // |pending_web_ui_|, or clear |web_ui_| if there is no pending WebUI, or
1971 // leave |web_ui_| as is if reusing it.
1972 DCHECK(!(pending_web_ui_ && pending_and_current_web_ui_));
1973 if (pending_web_ui_ || speculative_web_ui_) {
1974 DCHECK(!should_reuse_web_ui_);
1975 web_ui_.reset(browser_side_navigation ? speculative_web_ui_.release()
1976 : pending_web_ui_.release());
1977 } else if (pending_and_current_web_ui_ || should_reuse_web_ui_) {
1978 if (browser_side_navigation) {
1979 DCHECK(web_ui_);
1980 should_reuse_web_ui_ = false;
1981 } else {
1982 DCHECK_EQ(pending_and_current_web_ui_.get(), web_ui_.get());
1983 pending_and_current_web_ui_.reset();
1985 } else {
1986 web_ui_.reset();
1988 DCHECK(!speculative_web_ui_);
1989 DCHECK(!should_reuse_web_ui_);
1991 // It's possible for the pending_render_frame_host_ to be nullptr when we
1992 // aren't crossing process boundaries. If so, we just needed to handle the Web
1993 // UI committing above and we're done.
1994 if (!pending_render_frame_host_ && !speculative_render_frame_host_) {
1995 if (will_focus_location_bar)
1996 delegate_->SetFocusToLocationBar(false);
1997 return;
2000 // Remember if the page was focused so we can focus the new renderer in
2001 // that case.
2002 bool focus_render_view = !will_focus_location_bar &&
2003 render_frame_host_->GetView() &&
2004 render_frame_host_->GetView()->HasFocus();
2006 bool is_main_frame = frame_tree_node_->IsMainFrame();
2008 // Swap in the pending or speculative frame and make it active. Also ensure
2009 // the FrameTree stays in sync.
2010 scoped_ptr<RenderFrameHostImpl> old_render_frame_host;
2011 if (!browser_side_navigation) {
2012 DCHECK(!speculative_render_frame_host_);
2013 old_render_frame_host =
2014 SetRenderFrameHost(pending_render_frame_host_.Pass());
2015 } else {
2016 // PlzNavigate
2017 DCHECK(speculative_render_frame_host_);
2018 old_render_frame_host =
2019 SetRenderFrameHost(speculative_render_frame_host_.Pass());
2022 // Remove the children of the old frame from the tree.
2023 frame_tree_node_->ResetForNewProcess();
2025 // The process will no longer try to exit, so we can decrement the count.
2026 render_frame_host_->GetProcess()->RemovePendingView();
2028 // Show the new view (or a sad tab) if necessary.
2029 bool new_rfh_has_view = !!render_frame_host_->GetView();
2030 if (!delegate_->IsHidden() && new_rfh_has_view) {
2031 // In most cases, we need to show the new view.
2032 render_frame_host_->GetView()->Show();
2034 if (!new_rfh_has_view) {
2035 // If the view is gone, then this RenderViewHost died while it was hidden.
2036 // We ignored the RenderProcessGone call at the time, so we should send it
2037 // now to make sure the sad tab shows up, etc.
2038 DCHECK(!render_frame_host_->IsRenderFrameLive());
2039 DCHECK(!render_frame_host_->render_view_host()->IsRenderViewLive());
2040 delegate_->RenderProcessGoneFromRenderManager(
2041 render_frame_host_->render_view_host());
2044 // For top-level frames, also hide the old RenderViewHost's view.
2045 // TODO(creis): As long as show/hide are on RVH, we don't want to hide on
2046 // subframe navigations or we will interfere with the top-level frame.
2047 if (is_main_frame && old_render_frame_host->render_view_host()->GetView())
2048 old_render_frame_host->render_view_host()->GetView()->Hide();
2050 // Make sure the size is up to date. (Fix for bug 1079768.)
2051 delegate_->UpdateRenderViewSizeForRenderManager();
2053 if (will_focus_location_bar) {
2054 delegate_->SetFocusToLocationBar(false);
2055 } else if (focus_render_view && render_frame_host_->GetView()) {
2056 render_frame_host_->GetView()->Focus();
2059 // Notify that we've swapped RenderFrameHosts. We do this before shutting down
2060 // the RFH so that we can clean up RendererResources related to the RFH first.
2061 delegate_->NotifySwappedFromRenderManager(
2062 old_render_frame_host.get(), render_frame_host_.get(), is_main_frame);
2064 // The RenderViewHost keeps track of the main RenderFrameHost routing id.
2065 // If this is committing a main frame navigation, update it and set the
2066 // routing id in the RenderViewHost associated with the old RenderFrameHost
2067 // to MSG_ROUTING_NONE.
2068 if (is_main_frame && RenderFrameHostManager::IsSwappedOutStateForbidden()) {
2069 render_frame_host_->render_view_host()->set_main_frame_routing_id(
2070 render_frame_host_->routing_id());
2071 old_render_frame_host->render_view_host()->set_main_frame_routing_id(
2072 MSG_ROUTING_NONE);
2075 // Swap out the old frame now that the new one is visible.
2076 // This will swap it out and then put it on the proxy list (if there are other
2077 // active views in its SiteInstance) or schedule it for deletion when the swap
2078 // out ack arrives (or immediately if the process isn't live).
2079 // In the --site-per-process case, old subframe RFHs are not kept alive inside
2080 // the proxy.
2081 SwapOutOldFrame(old_render_frame_host.Pass());
2083 if (RenderFrameHostManager::IsSwappedOutStateForbidden()) {
2084 // Since the new RenderFrameHost is now committed, there must be no proxies
2085 // for its SiteInstance. Delete any existing ones.
2086 proxy_hosts_->Remove(render_frame_host_->GetSiteInstance()->GetId());
2089 // If this is a subframe, it should have a CrossProcessFrameConnector
2090 // created already. Use it to link the new RFH's view to the proxy that
2091 // belongs to the parent frame's SiteInstance. If this navigation causes
2092 // an out-of-process frame to return to the same process as its parent, the
2093 // proxy would have been removed from proxy_hosts_ above.
2094 // Note: We do this after swapping out the old RFH because that may create
2095 // the proxy we're looking for.
2096 RenderFrameProxyHost* proxy_to_parent = GetProxyToParent();
2097 if (proxy_to_parent) {
2098 CHECK(SiteIsolationPolicy::AreCrossProcessFramesPossible());
2099 proxy_to_parent->SetChildRWHView(render_frame_host_->GetView());
2102 // After all is done, there must never be a proxy in the list which has the
2103 // same SiteInstance as the current RenderFrameHost.
2104 CHECK(!proxy_hosts_->Get(render_frame_host_->GetSiteInstance()->GetId()));
2107 void RenderFrameHostManager::ShutdownProxiesIfLastActiveFrameInSiteInstance(
2108 RenderFrameHostImpl* render_frame_host) {
2109 if (!render_frame_host)
2110 return;
2111 if (!RenderFrameHostImpl::IsRFHStateActive(render_frame_host->rfh_state()))
2112 return;
2113 if (render_frame_host->GetSiteInstance()->active_frame_count() > 1U)
2114 return;
2116 // After |render_frame_host| goes away, there will be no active frames left in
2117 // its SiteInstance, so we can delete all proxies created in that SiteInstance
2118 // on behalf of frames anywhere in the BrowsingInstance.
2119 int32 site_instance_id = render_frame_host->GetSiteInstance()->GetId();
2121 // First remove any proxies for this SiteInstance from our own list.
2122 ClearProxiesInSiteInstance(site_instance_id, frame_tree_node_);
2124 // Use the safe RenderWidgetHost iterator for now to find all RenderViewHosts
2125 // in the SiteInstance, then tell their respective FrameTrees to remove all
2126 // RenderFrameProxyHosts corresponding to them.
2127 // TODO(creis): Replace this with a RenderFrameHostIterator that protects
2128 // against use-after-frees if a later element is deleted before getting to it.
2129 scoped_ptr<RenderWidgetHostIterator> widgets(
2130 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
2131 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2132 if (!widget->IsRenderView())
2133 continue;
2134 RenderViewHostImpl* rvh =
2135 static_cast<RenderViewHostImpl*>(RenderViewHost::From(widget));
2136 if (site_instance_id == rvh->GetSiteInstance()->GetId()) {
2137 // This deletes all RenderFrameHosts using the |rvh|, which then causes
2138 // |rvh| to Shutdown.
2139 FrameTree* tree = rvh->GetDelegate()->GetFrameTree();
2140 tree->ForEach(base::Bind(
2141 &RenderFrameHostManager::ClearProxiesInSiteInstance,
2142 site_instance_id));
2147 RenderFrameHostImpl* RenderFrameHostManager::UpdateStateForNavigate(
2148 const GURL& dest_url,
2149 SiteInstance* source_instance,
2150 SiteInstance* dest_instance,
2151 ui::PageTransition transition,
2152 bool dest_is_restore,
2153 bool dest_is_view_source_mode,
2154 const GlobalRequestID& transferred_request_id,
2155 int bindings) {
2156 // Don't swap for subframes unless we are in --site-per-process. We can get
2157 // here in tests for subframes (e.g., NavigateFrameToURL).
2158 if (!frame_tree_node_->IsMainFrame() &&
2159 !SiteIsolationPolicy::AreCrossProcessFramesPossible()) {
2160 return render_frame_host_.get();
2163 // If we are currently navigating cross-process, we want to get back to normal
2164 // and then navigate as usual.
2165 if (pending_render_frame_host_)
2166 CancelPending();
2168 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
2169 scoped_refptr<SiteInstance> new_instance = GetSiteInstanceForNavigation(
2170 dest_url, source_instance, dest_instance, nullptr, transition,
2171 dest_is_restore, dest_is_view_source_mode);
2173 const NavigationEntry* current_entry =
2174 delegate_->GetLastCommittedNavigationEntryForRenderManager();
2176 DCHECK(!pending_render_frame_host_);
2178 if (new_instance.get() != current_instance) {
2179 TRACE_EVENT_INSTANT2(
2180 "navigation",
2181 "RenderFrameHostManager::UpdateStateForNavigate:New SiteInstance",
2182 TRACE_EVENT_SCOPE_THREAD,
2183 "current_instance id", current_instance->GetId(),
2184 "new_instance id", new_instance->GetId());
2186 // New SiteInstance: create a pending RFH to navigate.
2188 // This will possibly create (set to nullptr) a Web UI object for the
2189 // pending page. We'll use this later to give the page special access. This
2190 // must happen before the new renderer is created below so it will get
2191 // bindings. It must also happen after the above conditional call to
2192 // CancelPending(), otherwise CancelPending may clear the pending_web_ui_
2193 // and the page will not have its bindings set appropriately.
2194 SetPendingWebUI(dest_url, bindings);
2195 CreatePendingRenderFrameHost(current_instance, new_instance.get(),
2196 frame_tree_node_->IsMainFrame());
2197 if (!pending_render_frame_host_)
2198 return nullptr;
2200 // Check if our current RFH is live before we set up a transition.
2201 if (!render_frame_host_->IsRenderFrameLive()) {
2202 // The current RFH is not live. There's no reason to sit around with a
2203 // sad tab or a newly created RFH while we wait for the pending RFH to
2204 // navigate. Just switch to the pending RFH now and go back to normal.
2205 // (Note that we don't care about on{before}unload handlers if the current
2206 // RFH isn't live.)
2207 CommitPending();
2208 return render_frame_host_.get();
2210 // Otherwise, it's safe to treat this as a pending cross-process transition.
2212 // We now have a pending RFH.
2213 DCHECK(pending_render_frame_host_);
2215 // We need to wait until the beforeunload handler has run, unless we are
2216 // transferring an existing request (in which case it has already run).
2217 // Suspend the new render view (i.e., don't let it send the cross-process
2218 // Navigate message) until we hear back from the old renderer's
2219 // beforeunload handler. If the handler returns false, we'll have to
2220 // cancel the request.
2222 DCHECK(!pending_render_frame_host_->are_navigations_suspended());
2223 bool is_transfer = transferred_request_id != GlobalRequestID();
2224 if (is_transfer) {
2225 // We don't need to stop the old renderer or run beforeunload/unload
2226 // handlers, because those have already been done.
2227 DCHECK(cross_site_transferring_request_->request_id() ==
2228 transferred_request_id);
2229 } else {
2230 // Also make sure the old render view stops, in case a load is in
2231 // progress. (We don't want to do this for transfers, since it will
2232 // interrupt the transfer with an unexpected DidStopLoading.)
2233 render_frame_host_->Send(new FrameMsg_Stop(
2234 render_frame_host_->GetRoutingID()));
2235 pending_render_frame_host_->SetNavigationsSuspended(true,
2236 base::TimeTicks());
2237 // Unless we are transferring an existing request, we should now tell the
2238 // old render view to run its beforeunload handler, since it doesn't
2239 // otherwise know that the cross-site request is happening. This will
2240 // trigger a call to OnBeforeUnloadACK with the reply.
2241 render_frame_host_->DispatchBeforeUnload(true);
2244 return pending_render_frame_host_.get();
2247 // Otherwise the same SiteInstance can be used. Navigate render_frame_host_.
2249 // It's possible to swap out the current RFH and then decide to navigate in it
2250 // anyway (e.g., a cross-process navigation that redirects back to the
2251 // original site). In that case, we have a proxy for the current RFH but
2252 // haven't deleted it yet. The new navigation will swap it back in, so we can
2253 // delete the proxy.
2254 proxy_hosts_->Remove(new_instance.get()->GetId());
2256 if (ShouldReuseWebUI(current_entry, dest_url)) {
2257 pending_web_ui_.reset();
2258 pending_and_current_web_ui_ = web_ui_->AsWeakPtr();
2259 } else {
2260 SetPendingWebUI(dest_url, bindings);
2261 // Make sure the new RenderViewHost has the right bindings.
2262 if (pending_web_ui() &&
2263 !render_frame_host_->GetProcess()->IsForGuestsOnly()) {
2264 render_frame_host_->render_view_host()->AllowBindings(
2265 pending_web_ui()->GetBindings());
2269 if (pending_web_ui() && render_frame_host_->IsRenderFrameLive()) {
2270 pending_web_ui()->GetController()->RenderViewReused(
2271 render_frame_host_->render_view_host());
2274 // The renderer can exit view source mode when any error or cancellation
2275 // happen. We must overwrite to recover the mode.
2276 if (dest_is_view_source_mode) {
2277 render_frame_host_->render_view_host()->Send(
2278 new ViewMsg_EnableViewSourceMode(
2279 render_frame_host_->render_view_host()->GetRoutingID()));
2282 return render_frame_host_.get();
2285 void RenderFrameHostManager::CancelPending() {
2286 TRACE_EVENT1("navigation", "RenderFrameHostManager::CancelPending",
2287 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
2288 DiscardUnusedFrame(UnsetPendingRenderFrameHost());
2291 scoped_ptr<RenderFrameHostImpl>
2292 RenderFrameHostManager::UnsetPendingRenderFrameHost() {
2293 scoped_ptr<RenderFrameHostImpl> pending_render_frame_host =
2294 pending_render_frame_host_.Pass();
2296 RenderFrameDevToolsAgentHost::OnCancelPendingNavigation(
2297 pending_render_frame_host.get(),
2298 render_frame_host_.get());
2300 // We no longer need to prevent the process from exiting.
2301 pending_render_frame_host->GetProcess()->RemovePendingView();
2303 pending_web_ui_.reset();
2304 pending_and_current_web_ui_.reset();
2306 return pending_render_frame_host.Pass();
2309 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::SetRenderFrameHost(
2310 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
2311 // Swap the two.
2312 scoped_ptr<RenderFrameHostImpl> old_render_frame_host =
2313 render_frame_host_.Pass();
2314 render_frame_host_ = render_frame_host.Pass();
2316 if (frame_tree_node_->IsMainFrame()) {
2317 // Update the count of top-level frames using this SiteInstance. All
2318 // subframes are in the same BrowsingInstance as the main frame, so we only
2319 // count top-level ones. This makes the value easier for consumers to
2320 // interpret.
2321 if (render_frame_host_) {
2322 render_frame_host_->GetSiteInstance()->
2323 IncrementRelatedActiveContentsCount();
2325 if (old_render_frame_host) {
2326 old_render_frame_host->GetSiteInstance()->
2327 DecrementRelatedActiveContentsCount();
2331 return old_render_frame_host.Pass();
2334 bool RenderFrameHostManager::IsRVHOnSwappedOutList(
2335 RenderViewHostImpl* rvh) const {
2336 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(
2337 rvh->GetSiteInstance());
2338 if (!proxy)
2339 return false;
2340 // If there is a proxy without RFH, it is for a subframe in the SiteInstance
2341 // of |rvh|. Subframes should be ignored in this case.
2342 if (!proxy->render_frame_host())
2343 return false;
2344 return IsOnSwappedOutList(proxy->render_frame_host());
2347 bool RenderFrameHostManager::IsOnSwappedOutList(
2348 RenderFrameHostImpl* rfh) const {
2349 if (!rfh->GetSiteInstance())
2350 return false;
2352 RenderFrameProxyHost* host =
2353 proxy_hosts_->Get(rfh->GetSiteInstance()->GetId());
2354 if (!host)
2355 return false;
2357 return host->render_frame_host() == rfh;
2360 RenderViewHostImpl* RenderFrameHostManager::GetSwappedOutRenderViewHost(
2361 SiteInstance* instance) const {
2362 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
2363 if (proxy)
2364 return proxy->GetRenderViewHost();
2365 return nullptr;
2368 RenderFrameProxyHost* RenderFrameHostManager::GetRenderFrameProxyHost(
2369 SiteInstance* instance) const {
2370 return proxy_hosts_->Get(instance->GetId());
2373 std::map<int, RenderFrameProxyHost*>
2374 RenderFrameHostManager::GetAllProxyHostsForTesting() {
2375 std::map<int, RenderFrameProxyHost*> result;
2376 result.insert(proxy_hosts_->begin(), proxy_hosts_->end());
2377 return result;
2380 void RenderFrameHostManager::CreateOpenerProxiesIfNeeded(
2381 SiteInstance* instance) {
2382 FrameTreeNode* opener = frame_tree_node_->opener();
2383 if (!opener)
2384 return;
2386 // Create proxies for the opener chain.
2387 opener->render_manager()->CreateOpenerProxies(instance);
2390 void RenderFrameHostManager::CreateOpenerProxies(SiteInstance* instance) {
2391 // If this tab has an opener, recursively create proxies for the nodes on its
2392 // frame tree.
2393 // TODO(alexmos): Once we allow frame openers to be updated (which can happen
2394 // via window.open(url, "target_frame")), this will need to be resilient to
2395 // cycles. It will also need to handle tabs that have multiple openers (e.g.,
2396 // main frame and subframe could have different openers, each of which must
2397 // be traversed).
2398 FrameTreeNode* opener = frame_tree_node_->opener();
2399 if (opener)
2400 opener->render_manager()->CreateOpenerProxies(instance);
2402 // If any of the RenderViewHosts (current, pending, or swapped out) for this
2403 // FrameTree has the same SiteInstance, then we can return early, since
2404 // proxies for other nodes in the tree should also exist (when in
2405 // site-per-process mode). An exception is if we are in
2406 // IsSwappedOutStateForbidden mode and find a pending RenderViewHost: in this
2407 // case, we should still create a proxy, which will allow communicating with
2408 // the opener until the pending RenderView commits, or if the pending
2409 // navigation is canceled.
2410 FrameTree* frame_tree = frame_tree_node_->frame_tree();
2411 RenderViewHostImpl* rvh = frame_tree->GetRenderViewHost(instance);
2412 bool need_proxy_for_pending_rvh =
2413 IsSwappedOutStateForbidden() && (rvh == pending_render_view_host());
2414 if (rvh && rvh->IsRenderViewLive() && !need_proxy_for_pending_rvh)
2415 return;
2417 if (RenderFrameHostManager::IsSwappedOutStateForbidden()) {
2418 // Ensure that all the nodes in the opener's frame tree have
2419 // RenderFrameProxyHosts for the new SiteInstance.
2420 frame_tree->CreateProxiesForSiteInstance(nullptr, instance);
2421 } else if (rvh && !rvh->IsRenderViewLive()) {
2422 EnsureRenderViewInitialized(rvh, instance);
2423 } else {
2424 // Create a swapped out RenderView in the given SiteInstance if none exists,
2425 // setting its opener to the given route_id. Since the opener can point to
2426 // a subframe, do this on the root frame of the opener's frame tree.
2427 // Return the new view's route_id.
2428 frame_tree->root()->render_manager()->
2429 CreateRenderFrame(instance, nullptr,
2430 CREATE_RF_FOR_MAIN_FRAME_NAVIGATION |
2431 CREATE_RF_SWAPPED_OUT | CREATE_RF_HIDDEN,
2432 nullptr);
2436 int RenderFrameHostManager::GetOpenerRoutingID(SiteInstance* instance) {
2437 if (!frame_tree_node_->opener())
2438 return MSG_ROUTING_NONE;
2440 return frame_tree_node_->opener()
2441 ->render_manager()
2442 ->GetRoutingIdForSiteInstance(instance);
2445 } // namespace content