base/threading: remove ScopedTracker placed for experiments
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_manager.cc
blob50c8a599a34f0e5aab5f8bab5697b8daba1f02e1
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_handle_impl.h"
23 #include "content/browser/frame_host/navigation_request.h"
24 #include "content/browser/frame_host/navigator.h"
25 #include "content/browser/frame_host/render_frame_host_factory.h"
26 #include "content/browser/frame_host/render_frame_host_impl.h"
27 #include "content/browser/frame_host/render_frame_proxy_host.h"
28 #include "content/browser/renderer_host/render_process_host_impl.h"
29 #include "content/browser/renderer_host/render_view_host_factory.h"
30 #include "content/browser/renderer_host/render_view_host_impl.h"
31 #include "content/browser/site_instance_impl.h"
32 #include "content/browser/webui/web_ui_controller_factory_registry.h"
33 #include "content/browser/webui/web_ui_impl.h"
34 #include "content/common/frame_messages.h"
35 #include "content/common/site_isolation_policy.h"
36 #include "content/common/view_messages.h"
37 #include "content/public/browser/content_browser_client.h"
38 #include "content/public/browser/render_process_host_observer.h"
39 #include "content/public/browser/render_widget_host_iterator.h"
40 #include "content/public/browser/render_widget_host_view.h"
41 #include "content/public/browser/user_metrics.h"
42 #include "content/public/browser/web_ui_controller.h"
43 #include "content/public/common/browser_plugin_guest_mode.h"
44 #include "content/public/common/content_switches.h"
45 #include "content/public/common/referrer.h"
46 #include "content/public/common/url_constants.h"
48 namespace content {
50 // A helper class to hold all frame proxies and register as a
51 // RenderProcessHostObserver for them.
52 class RenderFrameHostManager::RenderFrameProxyHostMap
53 : public RenderProcessHostObserver {
54 public:
55 using MapType = base::hash_map<int32, RenderFrameProxyHost*>;
57 RenderFrameProxyHostMap(RenderFrameHostManager* manager);
58 ~RenderFrameProxyHostMap() override;
60 // Read-only access to the underlying map of site instance ID to
61 // RenderFrameProxyHosts.
62 MapType::const_iterator begin() const { return map_.begin(); }
63 MapType::const_iterator end() const { return map_.end(); }
64 bool empty() const { return map_.empty(); }
66 // Returns the proxy with the specified ID, or nullptr if there is no such
67 // one.
68 RenderFrameProxyHost* Get(int32 id);
70 // Adds the specified proxy with the specified ID. It is an error (and fatal)
71 // to add more than one proxy with the specified ID.
72 void Add(int32 id, scoped_ptr<RenderFrameProxyHost> proxy);
74 // Removes the proxy with the specified site instance ID.
75 void Remove(int32 id);
77 // Removes all proxies.
78 void Clear();
80 // RenderProcessHostObserver implementation.
81 void RenderProcessWillExit(RenderProcessHost* host) override;
82 void RenderProcessExited(RenderProcessHost* host,
83 base::TerminationStatus status,
84 int exit_code) override;
86 private:
87 RenderFrameHostManager* manager_;
88 MapType map_;
91 RenderFrameHostManager::RenderFrameProxyHostMap::RenderFrameProxyHostMap(
92 RenderFrameHostManager* manager)
93 : manager_(manager) {}
95 RenderFrameHostManager::RenderFrameProxyHostMap::~RenderFrameProxyHostMap() {
96 Clear();
99 RenderFrameProxyHost* RenderFrameHostManager::RenderFrameProxyHostMap::Get(
100 int32 id) {
101 auto it = map_.find(id);
102 if (it != map_.end())
103 return it->second;
104 return nullptr;
107 void RenderFrameHostManager::RenderFrameProxyHostMap::Add(
108 int32 id,
109 scoped_ptr<RenderFrameProxyHost> proxy) {
110 CHECK_EQ(0u, map_.count(id)) << "Inserting a duplicate item.";
112 // If this is the first proxy that has this process host, observe the
113 // process host.
114 RenderProcessHost* host = proxy->GetProcess();
115 size_t count =
116 std::count_if(begin(), end(), [host](MapType::value_type item) {
117 return item.second->GetProcess() == host;
119 if (count == 0)
120 host->AddObserver(this);
122 map_[id] = proxy.release();
125 void RenderFrameHostManager::RenderFrameProxyHostMap::Remove(int32 id) {
126 auto it = map_.find(id);
127 if (it == map_.end())
128 return;
130 // If this is the last proxy that has this process host, stop observing the
131 // process host.
132 RenderProcessHost* host = it->second->GetProcess();
133 size_t count =
134 std::count_if(begin(), end(), [host](MapType::value_type item) {
135 return item.second->GetProcess() == host;
137 if (count == 1)
138 host->RemoveObserver(this);
140 delete it->second;
141 map_.erase(it);
144 void RenderFrameHostManager::RenderFrameProxyHostMap::Clear() {
145 std::set<RenderProcessHost*> hosts;
146 for (const auto& pair : map_)
147 hosts.insert(pair.second->GetProcess());
148 for (auto host : hosts)
149 host->RemoveObserver(this);
151 STLDeleteValues(&map_);
154 void RenderFrameHostManager::RenderFrameProxyHostMap::RenderProcessWillExit(
155 RenderProcessHost* host) {
156 manager_->RendererProcessClosing(host);
159 void RenderFrameHostManager::RenderFrameProxyHostMap::RenderProcessExited(
160 RenderProcessHost* host,
161 base::TerminationStatus status,
162 int exit_code) {
163 manager_->RendererProcessClosing(host);
166 // static
167 bool RenderFrameHostManager::ClearRFHsPendingShutdown(FrameTreeNode* node) {
168 node->render_manager()->pending_delete_hosts_.clear();
169 return true;
172 RenderFrameHostManager::RenderFrameHostManager(
173 FrameTreeNode* frame_tree_node,
174 RenderFrameHostDelegate* render_frame_delegate,
175 RenderViewHostDelegate* render_view_delegate,
176 RenderWidgetHostDelegate* render_widget_delegate,
177 Delegate* delegate)
178 : frame_tree_node_(frame_tree_node),
179 delegate_(delegate),
180 render_frame_delegate_(render_frame_delegate),
181 render_view_delegate_(render_view_delegate),
182 render_widget_delegate_(render_widget_delegate),
183 proxy_hosts_(new RenderFrameProxyHostMap(this)),
184 interstitial_page_(nullptr),
185 should_reuse_web_ui_(false),
186 weak_factory_(this) {
187 DCHECK(frame_tree_node_);
190 RenderFrameHostManager::~RenderFrameHostManager() {
191 if (pending_render_frame_host_) {
192 scoped_ptr<RenderFrameHostImpl> relic = UnsetPendingRenderFrameHost();
193 ShutdownProxiesIfLastActiveFrameInSiteInstance(relic.get());
196 if (speculative_render_frame_host_) {
197 scoped_ptr<RenderFrameHostImpl> relic = UnsetSpeculativeRenderFrameHost();
198 ShutdownProxiesIfLastActiveFrameInSiteInstance(relic.get());
201 ShutdownProxiesIfLastActiveFrameInSiteInstance(render_frame_host_.get());
203 // Delete any RenderFrameProxyHosts and swapped out RenderFrameHosts.
204 // It is important to delete those prior to deleting the current
205 // RenderFrameHost, since the CrossProcessFrameConnector (owned by
206 // RenderFrameProxyHost) points to the RenderWidgetHostView associated with
207 // the current RenderFrameHost and uses it during its destructor.
208 ResetProxyHosts();
210 // Release the WebUI prior to resetting the current RenderFrameHost, as the
211 // WebUI accesses the RenderFrameHost during cleanup.
212 web_ui_.reset();
214 // We should always have a current RenderFrameHost except in some tests.
215 SetRenderFrameHost(scoped_ptr<RenderFrameHostImpl>());
218 void RenderFrameHostManager::Init(BrowserContext* browser_context,
219 SiteInstance* site_instance,
220 int view_routing_id,
221 int frame_routing_id) {
222 // Create a RenderViewHost and RenderFrameHost, once we have an instance. It
223 // is important to immediately give this SiteInstance to a RenderViewHost so
224 // that the SiteInstance is ref counted.
225 if (!site_instance)
226 site_instance = SiteInstance::Create(browser_context);
228 int flags = delegate_->IsHidden() ? CREATE_RF_HIDDEN : 0;
229 SetRenderFrameHost(CreateRenderFrameHost(site_instance, view_routing_id,
230 frame_routing_id, flags));
232 // Notify the delegate of the creation of the current RenderFrameHost.
233 // Do this only for subframes, as the main frame case is taken care of by
234 // WebContentsImpl::Init.
235 if (!frame_tree_node_->IsMainFrame()) {
236 delegate_->NotifySwappedFromRenderManager(
237 nullptr, render_frame_host_.get(), false);
241 RenderViewHostImpl* RenderFrameHostManager::current_host() const {
242 if (!render_frame_host_)
243 return nullptr;
244 return render_frame_host_->render_view_host();
247 RenderViewHostImpl* RenderFrameHostManager::pending_render_view_host() const {
248 if (!pending_render_frame_host_)
249 return nullptr;
250 return pending_render_frame_host_->render_view_host();
253 RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const {
254 if (interstitial_page_)
255 return interstitial_page_->GetView();
256 if (render_frame_host_)
257 return render_frame_host_->GetView();
258 return nullptr;
261 bool RenderFrameHostManager::ForInnerDelegate() {
262 return delegate_->GetOuterDelegateFrameTreeNodeID() !=
263 FrameTreeNode::kFrameTreeNodeInvalidID;
266 RenderWidgetHostImpl*
267 RenderFrameHostManager::GetOuterRenderWidgetHostForKeyboardInput() {
268 if (!ForInnerDelegate() || !frame_tree_node_->IsMainFrame())
269 return nullptr;
271 FrameTreeNode* outer_contents_frame_tree_node =
272 FrameTreeNode::GloballyFindByID(
273 delegate_->GetOuterDelegateFrameTreeNodeID());
274 return outer_contents_frame_tree_node->parent()
275 ->current_frame_host()
276 ->render_view_host();
279 RenderFrameProxyHost* RenderFrameHostManager::GetProxyToParent() {
280 if (frame_tree_node_->IsMainFrame())
281 return nullptr;
283 return proxy_hosts_->Get(frame_tree_node_->parent()
284 ->render_manager()
285 ->current_frame_host()
286 ->GetSiteInstance()
287 ->GetId());
290 RenderFrameProxyHost* RenderFrameHostManager::GetProxyToOuterDelegate() {
291 int outer_contents_frame_tree_node_id =
292 delegate_->GetOuterDelegateFrameTreeNodeID();
293 FrameTreeNode* outer_contents_frame_tree_node =
294 FrameTreeNode::GloballyFindByID(outer_contents_frame_tree_node_id);
295 if (!outer_contents_frame_tree_node ||
296 !outer_contents_frame_tree_node->parent()) {
297 return nullptr;
300 return GetRenderFrameProxyHost(outer_contents_frame_tree_node->parent()
301 ->current_frame_host()
302 ->GetSiteInstance());
305 void RenderFrameHostManager::RemoveOuterDelegateFrame() {
306 FrameTreeNode* outer_delegate_frame_tree_node =
307 FrameTreeNode::GloballyFindByID(
308 delegate_->GetOuterDelegateFrameTreeNodeID());
309 DCHECK(outer_delegate_frame_tree_node->parent());
310 outer_delegate_frame_tree_node->frame_tree()->RemoveFrame(
311 outer_delegate_frame_tree_node);
314 void RenderFrameHostManager::SetPendingWebUI(const GURL& url, int bindings) {
315 pending_web_ui_ = CreateWebUI(url, bindings);
316 pending_and_current_web_ui_.reset();
319 scoped_ptr<WebUIImpl> RenderFrameHostManager::CreateWebUI(const GURL& url,
320 int bindings) {
321 scoped_ptr<WebUIImpl> new_web_ui(delegate_->CreateWebUIForRenderManager(url));
323 // If we have assigned (zero or more) bindings to this NavigationEntry in the
324 // past, make sure we're not granting it different bindings than it had
325 // before. If so, note it and don't give it any bindings, to avoid a
326 // potential privilege escalation.
327 if (new_web_ui && bindings != NavigationEntryImpl::kInvalidBindings &&
328 new_web_ui->GetBindings() != bindings) {
329 RecordAction(base::UserMetricsAction("ProcessSwapBindingsMismatch_RVHM"));
330 return nullptr;
332 return new_web_ui.Pass();
335 RenderFrameHostImpl* RenderFrameHostManager::Navigate(
336 const GURL& dest_url,
337 const FrameNavigationEntry& frame_entry,
338 const NavigationEntryImpl& entry) {
339 TRACE_EVENT1("navigation", "RenderFrameHostManager:Navigate",
340 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
341 // Create a pending RenderFrameHost to use for the navigation.
342 RenderFrameHostImpl* dest_render_frame_host = UpdateStateForNavigate(
343 dest_url,
344 // TODO(creis): Move source_site_instance to FNE.
345 entry.source_site_instance(), frame_entry.site_instance(),
346 entry.GetTransitionType(),
347 entry.restore_type() != NavigationEntryImpl::RESTORE_NONE,
348 entry.IsViewSourceMode(), entry.transferred_global_request_id(),
349 entry.bindings());
350 if (!dest_render_frame_host)
351 return nullptr; // We weren't able to create a pending render frame host.
353 // If the current render_frame_host_ isn't live, we should create it so
354 // that we don't show a sad tab while the dest_render_frame_host fetches
355 // its first page. (Bug 1145340)
356 if (dest_render_frame_host != render_frame_host_ &&
357 !render_frame_host_->IsRenderFrameLive()) {
358 // Note: we don't call InitRenderView here because we are navigating away
359 // soon anyway, and we don't have the NavigationEntry for this host.
360 delegate_->CreateRenderViewForRenderManager(
361 render_frame_host_->render_view_host(), MSG_ROUTING_NONE,
362 MSG_ROUTING_NONE, frame_tree_node_->current_replication_state(),
363 frame_tree_node_->IsMainFrame());
366 // If the renderer crashed, then try to create a new one to satisfy this
367 // navigation request.
368 if (!dest_render_frame_host->IsRenderFrameLive()) {
369 // Instruct the destination render frame host to set up a Mojo connection
370 // with the new render frame if necessary. Note that this call needs to
371 // occur before initializing the RenderView; the flow of creating the
372 // RenderView can cause browser-side code to execute that expects the this
373 // RFH's ServiceRegistry to be initialized (e.g., if the site is a WebUI
374 // site that is handled via Mojo, then Mojo WebUI code in //chrome will
375 // add a service to this RFH's ServiceRegistry).
376 dest_render_frame_host->SetUpMojoIfNeeded();
378 // Recreate the opener chain.
379 CreateOpenerProxiesIfNeeded(dest_render_frame_host->GetSiteInstance());
380 if (!InitRenderView(dest_render_frame_host->render_view_host(),
381 MSG_ROUTING_NONE,
382 frame_tree_node_->IsMainFrame()))
383 return nullptr;
385 // Now that we've created a new renderer, be sure to hide it if it isn't
386 // our primary one. Otherwise, we might crash if we try to call Show()
387 // on it later.
388 if (dest_render_frame_host != render_frame_host_) {
389 if (dest_render_frame_host->GetView())
390 dest_render_frame_host->GetView()->Hide();
391 } else {
392 // TODO(nasko): This is a very ugly hack. The Chrome extensions process
393 // manager still uses NotificationService and expects to see a
394 // RenderViewHost changed notification after WebContents and
395 // RenderFrameHostManager are completely initialized. This should be
396 // removed once the process manager moves away from NotificationService.
397 // See https://crbug.com/462682.
398 delegate_->NotifyMainFrameSwappedFromRenderManager(
399 nullptr, render_frame_host_->render_view_host());
403 // If entry includes the request ID of a request that is being transferred,
404 // the destination render frame will take ownership, so release ownership of
405 // the request.
406 if (cross_site_transferring_request_.get() &&
407 cross_site_transferring_request_->request_id() ==
408 entry.transferred_global_request_id()) {
409 cross_site_transferring_request_->ReleaseRequest();
411 // The navigating RenderFrameHost should take ownership of the
412 // NavigationHandle that came from the transferring RenderFrameHost.
413 DCHECK(transfer_navigation_handle_);
414 dest_render_frame_host->SetNavigationHandle(
415 transfer_navigation_handle_.Pass());
417 DCHECK(!transfer_navigation_handle_);
419 return dest_render_frame_host;
422 void RenderFrameHostManager::Stop() {
423 render_frame_host_->Stop();
425 // If a cross-process navigation is happening, the pending RenderFrameHost
426 // should stop. This will lead to a DidFailProvisionalLoad, which will
427 // properly destroy it.
428 if (pending_render_frame_host_) {
429 pending_render_frame_host_->Send(new FrameMsg_Stop(
430 pending_render_frame_host_->GetRoutingID()));
433 // PlzNavigate: a loading speculative RenderFrameHost should also stop.
434 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
435 switches::kEnableBrowserSideNavigation)) {
436 if (speculative_render_frame_host_ &&
437 speculative_render_frame_host_->is_loading()) {
438 speculative_render_frame_host_->Send(
439 new FrameMsg_Stop(speculative_render_frame_host_->GetRoutingID()));
444 void RenderFrameHostManager::SetIsLoading(bool is_loading) {
445 render_frame_host_->render_view_host()->SetIsLoading(is_loading);
446 if (pending_render_frame_host_)
447 pending_render_frame_host_->render_view_host()->SetIsLoading(is_loading);
450 bool RenderFrameHostManager::ShouldCloseTabOnUnresponsiveRenderer() {
451 // If we're waiting for a close ACK, then the tab should close whether there's
452 // a navigation in progress or not. Unfortunately, we also need to check for
453 // cases that we arrive here with no navigation in progress, since there are
454 // some tab closure paths that don't set is_waiting_for_close_ack to true.
455 // TODO(creis): Clean this up in http://crbug.com/418266.
456 if (!pending_render_frame_host_ ||
457 render_frame_host_->render_view_host()->is_waiting_for_close_ack())
458 return true;
460 // We should always have a pending RFH when there's a cross-process navigation
461 // in progress. Sanity check this for http://crbug.com/276333.
462 CHECK(pending_render_frame_host_);
464 // Unload handlers run in the background, so we should never get an
465 // unresponsiveness warning for them.
466 CHECK(!render_frame_host_->IsWaitingForUnloadACK());
468 // If the tab becomes unresponsive during beforeunload while doing a
469 // cross-process navigation, proceed with the navigation. (This assumes that
470 // the pending RenderFrameHost is still responsive.)
471 if (render_frame_host_->is_waiting_for_beforeunload_ack()) {
472 // Haven't gotten around to starting the request, because we're still
473 // waiting for the beforeunload handler to finish. We'll pretend that it
474 // did finish, to let the navigation proceed. Note that there's a danger
475 // that the beforeunload handler will later finish and possibly return
476 // false (meaning the navigation should not proceed), but we'll ignore it
477 // in this case because it took too long.
478 if (pending_render_frame_host_->are_navigations_suspended()) {
479 pending_render_frame_host_->SetNavigationsSuspended(
480 false, base::TimeTicks::Now());
483 return false;
486 void RenderFrameHostManager::OnBeforeUnloadACK(
487 bool for_cross_site_transition,
488 bool proceed,
489 const base::TimeTicks& proceed_time) {
490 if (for_cross_site_transition) {
491 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
492 switches::kEnableBrowserSideNavigation));
493 // Ignore if we're not in a cross-process navigation.
494 if (!pending_render_frame_host_)
495 return;
497 if (proceed) {
498 // Ok to unload the current page, so proceed with the cross-process
499 // navigation. Note that if navigations are not currently suspended, it
500 // might be because the renderer was deemed unresponsive and this call was
501 // already made by ShouldCloseTabOnUnresponsiveRenderer. In that case, it
502 // is ok to do nothing here.
503 if (pending_render_frame_host_ &&
504 pending_render_frame_host_->are_navigations_suspended()) {
505 pending_render_frame_host_->SetNavigationsSuspended(false,
506 proceed_time);
508 } else {
509 // Current page says to cancel.
510 CancelPending();
512 } else {
513 // Non-cross-process transition means closing the entire tab.
514 bool proceed_to_fire_unload;
515 delegate_->BeforeUnloadFiredFromRenderManager(proceed, proceed_time,
516 &proceed_to_fire_unload);
518 if (proceed_to_fire_unload) {
519 // If we're about to close the tab and there's a pending RFH, cancel it.
520 // Otherwise, if the navigation in the pending RFH completes before the
521 // close in the current RFH, we'll lose the tab close.
522 if (pending_render_frame_host_) {
523 CancelPending();
526 // PlzNavigate: clean up the speculative RenderFrameHost if there is one.
527 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
528 switches::kEnableBrowserSideNavigation) &&
529 speculative_render_frame_host_) {
530 CleanUpNavigation();
533 // This is not a cross-process navigation; the tab is being closed.
534 render_frame_host_->render_view_host()->ClosePage();
539 void RenderFrameHostManager::OnCrossSiteResponse(
540 RenderFrameHostImpl* pending_render_frame_host,
541 const GlobalRequestID& global_request_id,
542 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
543 const std::vector<GURL>& transfer_url_chain,
544 const Referrer& referrer,
545 ui::PageTransition page_transition,
546 bool should_replace_current_entry) {
547 // We should only get here for transfer navigations. Most cross-process
548 // navigations can just continue and wait to run the unload handler (by
549 // swapping out) when the new navigation commits.
550 CHECK(cross_site_transferring_request);
552 // A transfer should only have come from our pending or current RFH.
553 // TODO(creis): We need to handle the case that the pending RFH has changed
554 // in the mean time, while this was being posted from the IO thread. We
555 // should probably cancel the request in that case.
556 DCHECK(pending_render_frame_host == pending_render_frame_host_ ||
557 pending_render_frame_host == render_frame_host_);
559 // Store the transferring request so that we can release it if the transfer
560 // navigation matches.
561 cross_site_transferring_request_ = cross_site_transferring_request.Pass();
563 // Store the NavigationHandle to give it to the appropriate RenderFrameHost
564 // after it started navigating.
565 transfer_navigation_handle_ =
566 pending_render_frame_host->PassNavigationHandleOwnership();
567 DCHECK(transfer_navigation_handle_);
569 // Sanity check that the params are for the correct frame and process.
570 // These should match the RenderFrameHost that made the request.
571 // If it started as a cross-process navigation via OpenURL, this is the
572 // pending one. If it wasn't cross-process until the transfer, this is
573 // the current one.
574 int render_frame_id = pending_render_frame_host_
575 ? pending_render_frame_host_->GetRoutingID()
576 : render_frame_host_->GetRoutingID();
577 DCHECK_EQ(render_frame_id, pending_render_frame_host->GetRoutingID());
578 int process_id = pending_render_frame_host_ ?
579 pending_render_frame_host_->GetProcess()->GetID() :
580 render_frame_host_->GetProcess()->GetID();
581 DCHECK_EQ(process_id, global_request_id.child_id);
583 // Treat the last URL in the chain as the destination and the remainder as
584 // the redirect chain.
585 CHECK(transfer_url_chain.size());
586 GURL transfer_url = transfer_url_chain.back();
587 std::vector<GURL> rest_of_chain = transfer_url_chain;
588 rest_of_chain.pop_back();
590 // We don't know whether the original request had |user_action| set to true.
591 // However, since we force the navigation to be in the current tab, it
592 // doesn't matter.
593 pending_render_frame_host->frame_tree_node()->navigator()->RequestTransferURL(
594 pending_render_frame_host, transfer_url, nullptr, rest_of_chain, referrer,
595 page_transition, CURRENT_TAB, global_request_id,
596 should_replace_current_entry, true);
598 // The transferring request was only needed during the RequestTransferURL
599 // call, so it is safe to clear at this point.
600 cross_site_transferring_request_.reset();
602 // If the navigation continued, the NavigationHandle should have been
603 // transfered to a RenderFrameHost. In the other cases, it should be cleared.
604 transfer_navigation_handle_.reset();
607 void RenderFrameHostManager::DidNavigateFrame(
608 RenderFrameHostImpl* render_frame_host,
609 bool was_caused_by_user_gesture) {
610 CommitPendingIfNecessary(render_frame_host, was_caused_by_user_gesture);
612 // Make sure any dynamic changes to this frame's sandbox flags that were made
613 // prior to navigation take effect.
614 CommitPendingSandboxFlags();
617 void RenderFrameHostManager::CommitPendingIfNecessary(
618 RenderFrameHostImpl* render_frame_host,
619 bool was_caused_by_user_gesture) {
620 if (!pending_render_frame_host_ && !speculative_render_frame_host_) {
621 DCHECK_IMPLIES(should_reuse_web_ui_, web_ui_);
623 // We should only hear this from our current renderer.
624 DCHECK_EQ(render_frame_host_, render_frame_host);
626 // Even when there is no pending RVH, there may be a pending Web UI.
627 if (pending_web_ui() || speculative_web_ui_)
628 CommitPending();
629 return;
632 if (render_frame_host == pending_render_frame_host_ ||
633 render_frame_host == speculative_render_frame_host_) {
634 // The pending cross-process navigation completed, so show the renderer.
635 CommitPending();
636 } else if (render_frame_host == render_frame_host_) {
637 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
638 switches::kEnableBrowserSideNavigation)) {
639 CleanUpNavigation();
640 } else {
641 if (was_caused_by_user_gesture) {
642 // A navigation in the original page has taken place. Cancel the
643 // pending one. Only do it for user gesture originated navigations to
644 // prevent page doing any shenanigans to prevent user from navigating.
645 // See https://code.google.com/p/chromium/issues/detail?id=75195
646 CancelPending();
649 } else {
650 // No one else should be sending us DidNavigate in this state.
651 DCHECK(false);
655 void RenderFrameHostManager::DidDisownOpener(
656 RenderFrameHost* render_frame_host) {
657 // Notify all RenderFrameHosts but the one that notified us. This is necessary
658 // in case a process swap has occurred while the message was in flight.
659 for (const auto& pair : *proxy_hosts_) {
660 DCHECK_NE(pair.second->GetSiteInstance(),
661 current_frame_host()->GetSiteInstance());
662 pair.second->DisownOpener();
665 if (render_frame_host_.get() != render_frame_host)
666 render_frame_host_->DisownOpener();
668 if (pending_render_frame_host_ &&
669 pending_render_frame_host_.get() != render_frame_host) {
670 pending_render_frame_host_->DisownOpener();
674 void RenderFrameHostManager::CommitPendingSandboxFlags() {
675 // Return early if there were no pending sandbox flags updates.
676 if (!frame_tree_node_->CommitPendingSandboxFlags())
677 return;
679 // Sandbox flags updates can only happen when the frame has a parent.
680 CHECK(frame_tree_node_->parent());
682 // Notify all of the frame's proxies about updated sandbox flags, excluding
683 // the parent process since it already knows the latest flags.
684 SiteInstance* parent_site_instance =
685 frame_tree_node_->parent()->current_frame_host()->GetSiteInstance();
686 for (const auto& pair : *proxy_hosts_) {
687 if (pair.second->GetSiteInstance() != parent_site_instance) {
688 pair.second->Send(new FrameMsg_DidUpdateSandboxFlags(
689 pair.second->GetRoutingID(),
690 frame_tree_node_->current_replication_state().sandbox_flags));
695 void RenderFrameHostManager::RendererProcessClosing(
696 RenderProcessHost* render_process_host) {
697 // Remove any swapped out RVHs from this process, so that we don't try to
698 // swap them back in while the process is exiting. Start by finding them,
699 // since there could be more than one.
700 std::list<int> ids_to_remove;
701 // Do not remove proxies in the dead process that still have active frame
702 // count though, we just reset them to be uninitialized.
703 std::list<int> ids_to_keep;
704 for (const auto& pair : *proxy_hosts_) {
705 RenderFrameProxyHost* proxy = pair.second;
706 if (proxy->GetProcess() != render_process_host)
707 continue;
709 if (static_cast<SiteInstanceImpl*>(proxy->GetSiteInstance())
710 ->active_frame_count() >= 1U) {
711 ids_to_keep.push_back(pair.first);
712 } else {
713 ids_to_remove.push_back(pair.first);
717 // Now delete them.
718 while (!ids_to_remove.empty()) {
719 proxy_hosts_->Remove(ids_to_remove.back());
720 ids_to_remove.pop_back();
723 while (!ids_to_keep.empty()) {
724 frame_tree_node_->frame_tree()->ForEach(
725 base::Bind(
726 &RenderFrameHostManager::ResetProxiesInSiteInstance,
727 ids_to_keep.back()));
728 ids_to_keep.pop_back();
732 void RenderFrameHostManager::SwapOutOldFrame(
733 scoped_ptr<RenderFrameHostImpl> old_render_frame_host) {
734 TRACE_EVENT1("navigation", "RenderFrameHostManager::SwapOutOldFrame",
735 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
737 // Tell the renderer to suppress any further modal dialogs so that we can swap
738 // it out. This must be done before canceling any current dialog, in case
739 // there is a loop creating additional dialogs.
740 // TODO(creis): Handle modal dialogs in subframe processes.
741 old_render_frame_host->render_view_host()->SuppressDialogsUntilSwapOut();
743 // Now close any modal dialogs that would prevent us from swapping out. This
744 // must be done separately from SwapOut, so that the PageGroupLoadDeferrer is
745 // no longer on the stack when we send the SwapOut message.
746 delegate_->CancelModalDialogsForRenderManager();
748 // If the old RFH is not live, just return as there is no further work to do.
749 // It will be deleted and there will be no proxy created.
750 int32 old_site_instance_id =
751 old_render_frame_host->GetSiteInstance()->GetId();
752 if (!old_render_frame_host->IsRenderFrameLive()) {
753 ShutdownProxiesIfLastActiveFrameInSiteInstance(old_render_frame_host.get());
754 return;
757 // If there are no active frames besides this one, we can delete the old
758 // RenderFrameHost once it runs its unload handler, without replacing it with
759 // a proxy.
760 size_t active_frame_count =
761 old_render_frame_host->GetSiteInstance()->active_frame_count();
762 if (active_frame_count <= 1) {
763 // Clear out any proxies from this SiteInstance, in case this was the
764 // last one keeping other proxies alive.
765 ShutdownProxiesIfLastActiveFrameInSiteInstance(old_render_frame_host.get());
767 // Tell the old RenderFrameHost to swap out, with no proxy to replace it.
768 old_render_frame_host->SwapOut(nullptr, true);
769 MoveToPendingDeleteHosts(old_render_frame_host.Pass());
770 return;
773 // Otherwise there are active views and we need a proxy for the old RFH.
774 // (There should not be one yet.)
775 RenderFrameProxyHost* proxy = new RenderFrameProxyHost(
776 old_render_frame_host->GetSiteInstance(),
777 old_render_frame_host->render_view_host(), frame_tree_node_);
778 proxy_hosts_->Add(old_site_instance_id, make_scoped_ptr(proxy));
780 // Tell the old RenderFrameHost to swap out and be replaced by the proxy.
781 old_render_frame_host->SwapOut(proxy, true);
783 // SwapOut creates a RenderFrameProxy, so set the proxy to be initialized.
784 proxy->set_render_frame_proxy_created(true);
786 if (SiteIsolationPolicy::IsSwappedOutStateForbidden()) {
787 // In --site-per-process, frames delete their RFH rather than storing it
788 // in the proxy. Schedule it for deletion once the SwapOutACK comes in.
789 // TODO(creis): This will be the default when we remove swappedout://.
790 MoveToPendingDeleteHosts(old_render_frame_host.Pass());
791 } else {
792 // We shouldn't get here for subframes, since we only swap subframes when
793 // --site-per-process is used.
794 DCHECK(frame_tree_node_->IsMainFrame());
796 // The old RenderFrameHost will stay alive inside the proxy so that existing
797 // JavaScript window references to it stay valid.
798 proxy->TakeFrameHostOwnership(old_render_frame_host.Pass());
802 void RenderFrameHostManager::DiscardUnusedFrame(
803 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
804 // TODO(carlosk): this code is very similar to what can be found in
805 // SwapOutOldFrame and we should see that these are unified at some point.
807 // If the SiteInstance for the pending RFH is being used by others don't
808 // delete the RFH. Just swap it out and it can be reused at a later point.
809 // In --site-per-process, RenderFrameHosts are not kept around and are
810 // deleted when not used, replaced by RenderFrameProxyHosts.
811 SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance();
812 if (site_instance->HasSite() && site_instance->active_frame_count() > 1) {
813 // Any currently suspended navigations are no longer needed.
814 render_frame_host->CancelSuspendedNavigations();
816 RenderFrameProxyHost* proxy = new RenderFrameProxyHost(
817 site_instance, render_frame_host->render_view_host(), frame_tree_node_);
818 proxy_hosts_->Add(site_instance->GetId(), make_scoped_ptr(proxy));
820 // Check if the RenderFrameHost is already swapped out, to avoid swapping it
821 // out again.
822 if (!render_frame_host->is_swapped_out())
823 render_frame_host->SwapOut(proxy, false);
825 if (!SiteIsolationPolicy::IsSwappedOutStateForbidden()) {
826 DCHECK(frame_tree_node_->IsMainFrame());
827 proxy->TakeFrameHostOwnership(render_frame_host.Pass());
831 if (render_frame_host) {
832 // We won't be coming back, so delete this one.
833 ShutdownProxiesIfLastActiveFrameInSiteInstance(render_frame_host.get());
834 render_frame_host.reset();
838 void RenderFrameHostManager::MoveToPendingDeleteHosts(
839 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
840 // |render_frame_host| will be deleted when its SwapOut ACK is received, or
841 // when the timer times out, or when the RFHM itself is deleted (whichever
842 // comes first).
843 pending_delete_hosts_.push_back(
844 linked_ptr<RenderFrameHostImpl>(render_frame_host.release()));
847 bool RenderFrameHostManager::IsPendingDeletion(
848 RenderFrameHostImpl* render_frame_host) {
849 for (const auto& rfh : pending_delete_hosts_) {
850 if (rfh == render_frame_host)
851 return true;
853 return false;
856 bool RenderFrameHostManager::DeleteFromPendingList(
857 RenderFrameHostImpl* render_frame_host) {
858 for (RFHPendingDeleteList::iterator iter = pending_delete_hosts_.begin();
859 iter != pending_delete_hosts_.end();
860 iter++) {
861 if (*iter == render_frame_host) {
862 pending_delete_hosts_.erase(iter);
863 return true;
866 return false;
869 void RenderFrameHostManager::ResetProxyHosts() {
870 proxy_hosts_->Clear();
873 // PlzNavigate
874 void RenderFrameHostManager::DidCreateNavigationRequest(
875 const NavigationRequest& request) {
876 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
877 switches::kEnableBrowserSideNavigation));
878 // Clean up any state in case there's an ongoing navigation.
879 // TODO(carlosk): remove this cleanup here once we properly cancel ongoing
880 // navigations.
881 CleanUpNavigation();
883 RenderFrameHostImpl* dest_rfh = GetFrameHostForNavigation(request);
884 DCHECK(dest_rfh);
887 // PlzNavigate
888 RenderFrameHostImpl* RenderFrameHostManager::GetFrameHostForNavigation(
889 const NavigationRequest& request) {
890 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
891 switches::kEnableBrowserSideNavigation));
893 SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance();
895 SiteInstance* candidate_site_instance =
896 speculative_render_frame_host_
897 ? speculative_render_frame_host_->GetSiteInstance()
898 : nullptr;
900 scoped_refptr<SiteInstance> dest_site_instance = GetSiteInstanceForNavigation(
901 request.common_params().url, request.source_site_instance(),
902 request.dest_site_instance(), candidate_site_instance,
903 request.common_params().transition,
904 request.restore_type() != NavigationEntryImpl::RESTORE_NONE,
905 request.is_view_source());
907 // The appropriate RenderFrameHost to commit the navigation.
908 RenderFrameHostImpl* navigation_rfh = nullptr;
910 // Renderer-initiated main frame navigations that may require a SiteInstance
911 // swap are sent to the browser via the OpenURL IPC and are afterwards treated
912 // as browser-initiated navigations. NavigationRequests marked as
913 // renderer-initiated are created by receiving a BeginNavigation IPC, and will
914 // then proceed in the same renderer that sent the IPC due to the condition
915 // below.
916 // Subframe navigations will use the current renderer, unless
917 // --site-per-process is enabled.
918 // TODO(carlosk): Have renderer-initated main frame navigations swap processes
919 // if needed when it no longer breaks OAuth popups (see
920 // https://crbug.com/440266).
921 bool is_main_frame = frame_tree_node_->IsMainFrame();
922 if (current_site_instance == dest_site_instance.get() ||
923 (!request.browser_initiated() && is_main_frame) ||
924 (!is_main_frame && !dest_site_instance->RequiresDedicatedProcess() &&
925 !current_site_instance->RequiresDedicatedProcess())) {
926 // Reuse the current RFH if its SiteInstance matches the the navigation's
927 // or if this is a subframe navigation. We only swap RFHs for subframes when
928 // --site-per-process is enabled.
929 CleanUpNavigation();
930 navigation_rfh = render_frame_host_.get();
932 // As SiteInstances are the same, check if the WebUI should be reused.
933 const NavigationEntry* current_navigation_entry =
934 delegate_->GetLastCommittedNavigationEntryForRenderManager();
935 should_reuse_web_ui_ = ShouldReuseWebUI(current_navigation_entry,
936 request.common_params().url);
937 if (!should_reuse_web_ui_) {
938 speculative_web_ui_ = CreateWebUI(request.common_params().url,
939 request.bindings());
940 // Make sure the current RenderViewHost has the right bindings.
941 if (speculative_web_ui() &&
942 !render_frame_host_->GetProcess()->IsForGuestsOnly()) {
943 render_frame_host_->render_view_host()->AllowBindings(
944 speculative_web_ui()->GetBindings());
947 } else {
948 // If the SiteInstance for the final URL doesn't match the one from the
949 // speculatively created RenderFrameHost, create a new RenderFrameHost using
950 // this new SiteInstance.
951 if (!speculative_render_frame_host_ ||
952 speculative_render_frame_host_->GetSiteInstance() !=
953 dest_site_instance.get()) {
954 CleanUpNavigation();
955 bool success = CreateSpeculativeRenderFrameHost(
956 request.common_params().url, current_site_instance,
957 dest_site_instance.get(), request.bindings());
958 DCHECK(success);
960 DCHECK(speculative_render_frame_host_);
961 navigation_rfh = speculative_render_frame_host_.get();
963 // Check if our current RFH is live.
964 if (!render_frame_host_->IsRenderFrameLive()) {
965 // The current RFH is not live. There's no reason to sit around with a
966 // sad tab or a newly created RFH while we wait for the navigation to
967 // complete. Just switch to the speculative RFH now and go back to normal.
968 // (Note that we don't care about on{before}unload handlers if the current
969 // RFH isn't live.)
970 CommitPending();
973 DCHECK(navigation_rfh &&
974 (navigation_rfh == render_frame_host_.get() ||
975 navigation_rfh == speculative_render_frame_host_.get()));
977 // If the RenderFrame that needs to navigate is not live (its process was just
978 // created or has crashed), initialize it.
979 if (!navigation_rfh->IsRenderFrameLive()) {
980 // Recreate the opener chain.
981 CreateOpenerProxiesIfNeeded(navigation_rfh->GetSiteInstance());
982 if (!InitRenderView(navigation_rfh->render_view_host(), MSG_ROUTING_NONE,
983 frame_tree_node_->IsMainFrame())) {
984 return nullptr;
987 if (navigation_rfh == render_frame_host_) {
988 // TODO(nasko): This is a very ugly hack. The Chrome extensions process
989 // manager still uses NotificationService and expects to see a
990 // RenderViewHost changed notification after WebContents and
991 // RenderFrameHostManager are completely initialized. This should be
992 // removed once the process manager moves away from NotificationService.
993 // See https://crbug.com/462682.
994 delegate_->NotifyMainFrameSwappedFromRenderManager(
995 nullptr, render_frame_host_->render_view_host());
999 return navigation_rfh;
1002 // PlzNavigate
1003 void RenderFrameHostManager::CleanUpNavigation() {
1004 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1005 switches::kEnableBrowserSideNavigation));
1006 speculative_web_ui_.reset();
1007 should_reuse_web_ui_ = false;
1008 if (speculative_render_frame_host_)
1009 DiscardUnusedFrame(UnsetSpeculativeRenderFrameHost());
1012 // PlzNavigate
1013 scoped_ptr<RenderFrameHostImpl>
1014 RenderFrameHostManager::UnsetSpeculativeRenderFrameHost() {
1015 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1016 switches::kEnableBrowserSideNavigation));
1017 speculative_render_frame_host_->GetProcess()->RemovePendingView();
1018 return speculative_render_frame_host_.Pass();
1021 void RenderFrameHostManager::OnDidStartLoading() {
1022 for (const auto& pair : *proxy_hosts_) {
1023 pair.second->Send(
1024 new FrameMsg_DidStartLoading(pair.second->GetRoutingID()));
1028 void RenderFrameHostManager::OnDidStopLoading() {
1029 for (const auto& pair : *proxy_hosts_) {
1030 pair.second->Send(new FrameMsg_DidStopLoading(pair.second->GetRoutingID()));
1034 void RenderFrameHostManager::OnDidUpdateName(const std::string& name) {
1035 // The window.name message may be sent outside of --site-per-process when
1036 // report_frame_name_changes renderer preference is set (used by
1037 // WebView). Don't send the update to proxies in those cases.
1038 // TODO(nick,nasko): Should this be IsSwappedOutStateForbidden, to match
1039 // OnDidUpdateOrigin?
1040 if (!SiteIsolationPolicy::AreCrossProcessFramesPossible())
1041 return;
1043 for (const auto& pair : *proxy_hosts_) {
1044 pair.second->Send(
1045 new FrameMsg_DidUpdateName(pair.second->GetRoutingID(), name));
1049 void RenderFrameHostManager::OnDidUpdateOrigin(const url::Origin& origin) {
1050 if (!SiteIsolationPolicy::IsSwappedOutStateForbidden())
1051 return;
1053 for (const auto& pair : *proxy_hosts_) {
1054 pair.second->Send(
1055 new FrameMsg_DidUpdateOrigin(pair.second->GetRoutingID(), origin));
1059 RenderFrameHostManager::SiteInstanceDescriptor::SiteInstanceDescriptor(
1060 BrowserContext* browser_context,
1061 GURL dest_url,
1062 bool related_to_current)
1063 : existing_site_instance(nullptr),
1064 new_is_related_to_current(related_to_current) {
1065 new_site_url = SiteInstance::GetSiteForURL(browser_context, dest_url);
1068 // static
1069 bool RenderFrameHostManager::ClearProxiesInSiteInstance(
1070 int32 site_instance_id,
1071 FrameTreeNode* node) {
1072 RenderFrameProxyHost* proxy =
1073 node->render_manager()->proxy_hosts_->Get(site_instance_id);
1074 if (proxy) {
1075 // Delete the proxy. If it is for a main frame (and thus the RFH is stored
1076 // in the proxy) and it was still pending swap out, move the RFH to the
1077 // pending deletion list first.
1078 if (node->IsMainFrame() &&
1079 proxy->render_frame_host() &&
1080 proxy->render_frame_host()->rfh_state() ==
1081 RenderFrameHostImpl::STATE_PENDING_SWAP_OUT) {
1082 DCHECK(!SiteIsolationPolicy::IsSwappedOutStateForbidden());
1083 scoped_ptr<RenderFrameHostImpl> swapped_out_rfh =
1084 proxy->PassFrameHostOwnership();
1085 node->render_manager()->MoveToPendingDeleteHosts(swapped_out_rfh.Pass());
1087 node->render_manager()->proxy_hosts_->Remove(site_instance_id);
1090 return true;
1093 // static.
1094 bool RenderFrameHostManager::ResetProxiesInSiteInstance(int32 site_instance_id,
1095 FrameTreeNode* node) {
1096 RenderFrameProxyHost* proxy =
1097 node->render_manager()->proxy_hosts_->Get(site_instance_id);
1098 if (proxy)
1099 proxy->set_render_frame_proxy_created(false);
1101 return true;
1104 bool RenderFrameHostManager::ShouldTransitionCrossSite() {
1105 // The logic below is weaker than "are all sites isolated" -- it asks instead,
1106 // "is any site isolated". That's appropriate here since we're just trying to
1107 // figure out if we're in any kind of site isolated mode, and in which case,
1108 // we ignore the kSingleProcess and kProcessPerTab settings.
1110 // TODO(nick): Move all handling of kSingleProcess/kProcessPerTab into
1111 // SiteIsolationPolicy so we have a consistent behavior around the interaction
1112 // of the process model flags.
1113 if (SiteIsolationPolicy::AreCrossProcessFramesPossible())
1114 return true;
1116 // False in the single-process mode, as it makes RVHs to accumulate
1117 // in swapped_out_hosts_.
1118 // True if we are using process-per-site-instance (default) or
1119 // process-per-site (kProcessPerSite).
1120 // TODO(nick): Move handling of kSingleProcess and kProcessPerTab into
1121 // SiteIsolationPolicy.
1122 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
1123 switches::kSingleProcess) &&
1124 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1125 switches::kProcessPerTab);
1128 bool RenderFrameHostManager::ShouldSwapBrowsingInstancesForNavigation(
1129 const GURL& current_effective_url,
1130 bool current_is_view_source_mode,
1131 SiteInstance* new_site_instance,
1132 const GURL& new_effective_url,
1133 bool new_is_view_source_mode) const {
1134 // If new_entry already has a SiteInstance, assume it is correct. We only
1135 // need to force a swap if it is in a different BrowsingInstance.
1136 if (new_site_instance) {
1137 return !new_site_instance->IsRelatedSiteInstance(
1138 render_frame_host_->GetSiteInstance());
1141 // Check for reasons to swap processes even if we are in a process model that
1142 // doesn't usually swap (e.g., process-per-tab). Any time we return true,
1143 // the new_entry will be rendered in a new SiteInstance AND BrowsingInstance.
1144 BrowserContext* browser_context =
1145 delegate_->GetControllerForRenderManager().GetBrowserContext();
1147 // Don't force a new BrowsingInstance for debug URLs that are handled in the
1148 // renderer process, like javascript: or chrome://crash.
1149 if (IsRendererDebugURL(new_effective_url))
1150 return false;
1152 // For security, we should transition between processes when one is a Web UI
1153 // page and one isn't.
1154 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1155 render_frame_host_->GetProcess()->GetID()) ||
1156 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1157 browser_context, current_effective_url)) {
1158 // If so, force a swap if destination is not an acceptable URL for Web UI.
1159 // Here, data URLs are never allowed.
1160 if (!WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
1161 browser_context, new_effective_url)) {
1162 return true;
1164 } else {
1165 // Force a swap if it's a Web UI URL.
1166 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1167 browser_context, new_effective_url)) {
1168 return true;
1172 // Check with the content client as well. Important to pass
1173 // current_effective_url here, which uses the SiteInstance's site if there is
1174 // no current_entry.
1175 if (GetContentClient()->browser()->ShouldSwapBrowsingInstancesForNavigation(
1176 render_frame_host_->GetSiteInstance(),
1177 current_effective_url, new_effective_url)) {
1178 return true;
1181 // We can't switch a RenderView between view source and non-view source mode
1182 // without screwing up the session history sometimes (when navigating between
1183 // "view-source:http://foo.com/" and "http://foo.com/", Blink doesn't treat
1184 // it as a new navigation). So require a BrowsingInstance switch.
1185 if (current_is_view_source_mode != new_is_view_source_mode)
1186 return true;
1188 return false;
1191 bool RenderFrameHostManager::ShouldReuseWebUI(
1192 const NavigationEntry* current_entry,
1193 const GURL& new_url) const {
1194 NavigationControllerImpl& controller =
1195 delegate_->GetControllerForRenderManager();
1196 return current_entry && web_ui_ &&
1197 (WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
1198 controller.GetBrowserContext(), current_entry->GetURL()) ==
1199 WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
1200 controller.GetBrowserContext(), new_url));
1203 SiteInstance* RenderFrameHostManager::GetSiteInstanceForNavigation(
1204 const GURL& dest_url,
1205 SiteInstance* source_instance,
1206 SiteInstance* dest_instance,
1207 SiteInstance* candidate_instance,
1208 ui::PageTransition transition,
1209 bool dest_is_restore,
1210 bool dest_is_view_source_mode) {
1211 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1213 // We do not currently swap processes for navigations in webview tag guests.
1214 if (current_instance->GetSiteURL().SchemeIs(kGuestScheme))
1215 return current_instance;
1217 // Determine if we need a new BrowsingInstance for this entry. If true, this
1218 // implies that it will get a new SiteInstance (and likely process), and that
1219 // other tabs in the current BrowsingInstance will be unable to script it.
1220 // This is used for cases that require a process swap even in the
1221 // process-per-tab model, such as WebUI pages.
1222 // TODO(clamy): Remove the dependency on the current entry.
1223 const NavigationEntry* current_entry =
1224 delegate_->GetLastCommittedNavigationEntryForRenderManager();
1225 BrowserContext* browser_context =
1226 delegate_->GetControllerForRenderManager().GetBrowserContext();
1227 const GURL& current_effective_url = current_entry ?
1228 SiteInstanceImpl::GetEffectiveURL(browser_context,
1229 current_entry->GetURL()) :
1230 render_frame_host_->GetSiteInstance()->GetSiteURL();
1231 bool current_is_view_source_mode = current_entry ?
1232 current_entry->IsViewSourceMode() : dest_is_view_source_mode;
1233 bool force_swap = ShouldSwapBrowsingInstancesForNavigation(
1234 current_effective_url,
1235 current_is_view_source_mode,
1236 dest_instance,
1237 SiteInstanceImpl::GetEffectiveURL(browser_context, dest_url),
1238 dest_is_view_source_mode);
1239 SiteInstanceDescriptor new_instance_descriptor =
1240 SiteInstanceDescriptor(current_instance);
1241 if (ShouldTransitionCrossSite() || force_swap) {
1242 new_instance_descriptor = DetermineSiteInstanceForURL(
1243 dest_url, source_instance, current_instance, dest_instance, transition,
1244 dest_is_restore, dest_is_view_source_mode, force_swap);
1247 SiteInstance* new_instance =
1248 ConvertToSiteInstance(new_instance_descriptor, candidate_instance);
1250 // If |force_swap| is true, we must use a different SiteInstance than the
1251 // current one. If we didn't, we would have two RenderFrameHosts in the same
1252 // SiteInstance and the same frame, resulting in page_id conflicts for their
1253 // NavigationEntries.
1254 if (force_swap)
1255 CHECK_NE(new_instance, current_instance);
1256 return new_instance;
1259 RenderFrameHostManager::SiteInstanceDescriptor
1260 RenderFrameHostManager::DetermineSiteInstanceForURL(
1261 const GURL& dest_url,
1262 SiteInstance* source_instance,
1263 SiteInstance* current_instance,
1264 SiteInstance* dest_instance,
1265 ui::PageTransition transition,
1266 bool dest_is_restore,
1267 bool dest_is_view_source_mode,
1268 bool force_browsing_instance_swap) {
1269 SiteInstanceImpl* current_instance_impl =
1270 static_cast<SiteInstanceImpl*>(current_instance);
1271 NavigationControllerImpl& controller =
1272 delegate_->GetControllerForRenderManager();
1273 BrowserContext* browser_context = controller.GetBrowserContext();
1275 // If the entry has an instance already we should use it.
1276 if (dest_instance) {
1277 // If we are forcing a swap, this should be in a different BrowsingInstance.
1278 if (force_browsing_instance_swap) {
1279 CHECK(!dest_instance->IsRelatedSiteInstance(
1280 render_frame_host_->GetSiteInstance()));
1282 return SiteInstanceDescriptor(dest_instance);
1285 // If a swap is required, we need to force the SiteInstance AND
1286 // BrowsingInstance to be different ones, using CreateForURL.
1287 if (force_browsing_instance_swap)
1288 return SiteInstanceDescriptor(browser_context, dest_url, false);
1290 // (UGLY) HEURISTIC, process-per-site only:
1292 // If this navigation is generated, then it probably corresponds to a search
1293 // query. Given that search results typically lead to users navigating to
1294 // other sites, we don't really want to use the search engine hostname to
1295 // determine the site instance for this navigation.
1297 // NOTE: This can be removed once we have a way to transition between
1298 // RenderViews in response to a link click.
1300 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1301 switches::kProcessPerSite) &&
1302 ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_GENERATED)) {
1303 return SiteInstanceDescriptor(current_instance_impl);
1306 // If we haven't used our SiteInstance (and thus RVH) yet, then we can use it
1307 // for this entry. We won't commit the SiteInstance to this site until the
1308 // navigation commits (in DidNavigate), unless the navigation entry was
1309 // restored or it's a Web UI as described below.
1310 if (!current_instance_impl->HasSite()) {
1311 // If we've already created a SiteInstance for our destination, we don't
1312 // want to use this unused SiteInstance; use the existing one. (We don't
1313 // do this check if the current_instance has a site, because for now, we
1314 // want to compare against the current URL and not the SiteInstance's site.
1315 // In this case, there is no current URL, so comparing against the site is
1316 // ok. See additional comments below.)
1318 // Also, if the URL should use process-per-site mode and there is an
1319 // existing process for the site, we should use it. We can call
1320 // GetRelatedSiteInstance() for this, which will eagerly set the site and
1321 // thus use the correct process.
1322 bool use_process_per_site =
1323 RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) &&
1324 RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url);
1325 if (current_instance_impl->HasRelatedSiteInstance(dest_url) ||
1326 use_process_per_site) {
1327 return SiteInstanceDescriptor(browser_context, dest_url, true);
1330 // For extensions, Web UI URLs (such as the new tab page), and apps we do
1331 // not want to use the |current_instance_impl| if it has no site, since it
1332 // will have a RenderProcessHost of PRIV_NORMAL. Create a new SiteInstance
1333 // for this URL instead (with the correct process type).
1334 if (current_instance_impl->HasWrongProcessForURL(dest_url))
1335 return SiteInstanceDescriptor(browser_context, dest_url, true);
1337 // View-source URLs must use a new SiteInstance and BrowsingInstance.
1338 // TODO(nasko): This is the same condition as later in the function. This
1339 // should be taken into account when refactoring this method as part of
1340 // http://crbug.com/123007.
1341 if (dest_is_view_source_mode)
1342 return SiteInstanceDescriptor(browser_context, dest_url, false);
1344 // If we are navigating from a blank SiteInstance to a WebUI, make sure we
1345 // create a new SiteInstance.
1346 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1347 browser_context, dest_url)) {
1348 return SiteInstanceDescriptor(browser_context, dest_url, false);
1351 // Normally the "site" on the SiteInstance is set lazily when the load
1352 // actually commits. This is to support better process sharing in case
1353 // the site redirects to some other site: we want to use the destination
1354 // site in the site instance.
1356 // In the case of session restore, as it loads all the pages immediately
1357 // we need to set the site first, otherwise after a restore none of the
1358 // pages would share renderers in process-per-site.
1360 // The embedder can request some urls never to be assigned to SiteInstance
1361 // through the ShouldAssignSiteForURL() content client method, so that
1362 // renderers created for particular chrome urls (e.g. the chrome-native://
1363 // scheme) can be reused for subsequent navigations in the same WebContents.
1364 // See http://crbug.com/386542.
1365 if (dest_is_restore &&
1366 GetContentClient()->browser()->ShouldAssignSiteForURL(dest_url)) {
1367 current_instance_impl->SetSite(dest_url);
1370 return SiteInstanceDescriptor(current_instance_impl);
1373 // Otherwise, only create a new SiteInstance for a cross-process navigation.
1375 // TODO(creis): Once we intercept links and script-based navigations, we
1376 // will be able to enforce that all entries in a SiteInstance actually have
1377 // the same site, and it will be safe to compare the URL against the
1378 // SiteInstance's site, as follows:
1379 // const GURL& current_url = current_instance_impl->site();
1380 // For now, though, we're in a hybrid model where you only switch
1381 // SiteInstances if you type in a cross-site URL. This means we have to
1382 // compare the entry's URL to the last committed entry's URL.
1383 NavigationEntry* current_entry = controller.GetLastCommittedEntry();
1384 if (interstitial_page_) {
1385 // The interstitial is currently the last committed entry, but we want to
1386 // compare against the last non-interstitial entry.
1387 current_entry = controller.GetEntryAtOffset(-1);
1390 // View-source URLs must use a new SiteInstance and BrowsingInstance.
1391 // We don't need a swap when going from view-source to a debug URL like
1392 // chrome://crash, however.
1393 // TODO(creis): Refactor this method so this duplicated code isn't needed.
1394 // See http://crbug.com/123007.
1395 if (current_entry &&
1396 current_entry->IsViewSourceMode() != dest_is_view_source_mode &&
1397 !IsRendererDebugURL(dest_url)) {
1398 return SiteInstanceDescriptor(browser_context, dest_url, false);
1401 // Use the source SiteInstance in case of data URLs or about:blank pages,
1402 // because the content is then controlled and/or scriptable by the source
1403 // SiteInstance.
1404 GURL about_blank(url::kAboutBlankURL);
1405 if (source_instance &&
1406 (dest_url == about_blank || dest_url.scheme() == url::kDataScheme)) {
1407 return SiteInstanceDescriptor(source_instance);
1410 // Use the current SiteInstance for same site navigations, as long as the
1411 // process type is correct. (The URL may have been installed as an app since
1412 // the last time we visited it.)
1413 const GURL& current_url =
1414 GetCurrentURLForSiteInstance(current_instance_impl, current_entry);
1415 if (SiteInstance::IsSameWebSite(browser_context, current_url, dest_url) &&
1416 !current_instance_impl->HasWrongProcessForURL(dest_url)) {
1417 return SiteInstanceDescriptor(current_instance_impl);
1420 // Start the new renderer in a new SiteInstance, but in the current
1421 // BrowsingInstance. It is important to immediately give this new
1422 // SiteInstance to a RenderViewHost (if it is different than our current
1423 // SiteInstance), so that it is ref counted. This will happen in
1424 // CreateRenderView.
1425 return SiteInstanceDescriptor(browser_context, dest_url, true);
1428 SiteInstance* RenderFrameHostManager::ConvertToSiteInstance(
1429 const SiteInstanceDescriptor& descriptor,
1430 SiteInstance* candidate_instance) {
1431 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1433 // Note: If the |candidate_instance| matches the descriptor, it will already
1434 // be set to |descriptor.existing_site_instance|.
1435 if (descriptor.existing_site_instance)
1436 return descriptor.existing_site_instance;
1438 // Note: If the |candidate_instance| matches the descriptor,
1439 // GetRelatedSiteInstance will return it.
1440 if (descriptor.new_is_related_to_current)
1441 return current_instance->GetRelatedSiteInstance(descriptor.new_site_url);
1443 // At this point we know an unrelated site instance must be returned. First
1444 // check if the candidate matches.
1445 if (candidate_instance &&
1446 !current_instance->IsRelatedSiteInstance(candidate_instance) &&
1447 candidate_instance->GetSiteURL() == descriptor.new_site_url) {
1448 return candidate_instance;
1451 // Otherwise return a newly created one.
1452 return SiteInstance::CreateForURL(
1453 delegate_->GetControllerForRenderManager().GetBrowserContext(),
1454 descriptor.new_site_url);
1457 const GURL& RenderFrameHostManager::GetCurrentURLForSiteInstance(
1458 SiteInstance* current_instance, NavigationEntry* current_entry) {
1459 // If this is a subframe that is potentially out of process from its parent,
1460 // don't consider using current_entry's url for SiteInstance selection, since
1461 // current_entry's url is for the main frame and may be in a different site
1462 // than this frame.
1463 // TODO(creis): Remove this when we can check the FrameNavigationEntry's url.
1464 // See http://crbug.com/369654
1465 if (!frame_tree_node_->IsMainFrame() &&
1466 SiteIsolationPolicy::AreCrossProcessFramesPossible())
1467 return frame_tree_node_->current_url();
1469 // If there is no last non-interstitial entry (and current_instance already
1470 // has a site), then we must have been opened from another tab. We want
1471 // to compare against the URL of the page that opened us, but we can't
1472 // get to it directly. The best we can do is check against the site of
1473 // the SiteInstance. This will be correct when we intercept links and
1474 // script-based navigations, but for now, it could place some pages in a
1475 // new process unnecessarily. We should only hit this case if a page tries
1476 // to open a new tab to an interstitial-inducing URL, and then navigates
1477 // the page to a different same-site URL. (This seems very unlikely in
1478 // practice.)
1479 if (current_entry)
1480 return current_entry->GetURL();
1481 return current_instance->GetSiteURL();
1484 void RenderFrameHostManager::CreatePendingRenderFrameHost(
1485 SiteInstance* old_instance,
1486 SiteInstance* new_instance,
1487 bool is_main_frame) {
1488 int create_render_frame_flags = 0;
1489 if (is_main_frame)
1490 create_render_frame_flags |= CREATE_RF_FOR_MAIN_FRAME_NAVIGATION;
1492 if (delegate_->IsHidden())
1493 create_render_frame_flags |= CREATE_RF_HIDDEN;
1495 if (pending_render_frame_host_)
1496 CancelPending();
1498 // The process for the new SiteInstance may (if we're sharing a process with
1499 // another host that already initialized it) or may not (we have our own
1500 // process or the existing process crashed) have been initialized. Calling
1501 // Init multiple times will be ignored, so this is safe.
1502 if (!new_instance->GetProcess()->Init())
1503 return;
1505 CreateProxiesForNewRenderFrameHost(old_instance, new_instance,
1506 &create_render_frame_flags);
1508 // Create a non-swapped-out RFH with the given opener.
1509 pending_render_frame_host_ = CreateRenderFrame(
1510 new_instance, pending_web_ui(), create_render_frame_flags, nullptr);
1513 void RenderFrameHostManager::CreateProxiesForNewRenderFrameHost(
1514 SiteInstance* old_instance,
1515 SiteInstance* new_instance,
1516 int* create_render_frame_flags) {
1517 // Only create opener proxies if they are in the same BrowsingInstance.
1518 if (new_instance->IsRelatedSiteInstance(old_instance))
1519 CreateOpenerProxiesIfNeeded(new_instance);
1520 if (SiteIsolationPolicy::AreCrossProcessFramesPossible()) {
1521 // Ensure that the frame tree has RenderFrameProxyHosts for the new
1522 // SiteInstance in all nodes except the current one. We do this for all
1523 // frames in the tree, whether they are in the same BrowsingInstance or not.
1524 // We will still check whether two frames are in the same BrowsingInstance
1525 // before we allow them to interact (e.g., postMessage).
1526 frame_tree_node_->frame_tree()->CreateProxiesForSiteInstance(
1527 frame_tree_node_, new_instance);
1528 // RenderFrames in different processes from their parent RenderFrames
1529 // in the frame tree require RenderWidgets for rendering and processing
1530 // input events.
1531 if (frame_tree_node_->parent() &&
1532 frame_tree_node_->parent()->current_frame_host()->GetSiteInstance() !=
1533 new_instance)
1534 *create_render_frame_flags |= CREATE_RF_NEEDS_RENDER_WIDGET_HOST;
1538 void RenderFrameHostManager::CreateProxiesForNewNamedFrame() {
1539 if (!SiteIsolationPolicy::AreCrossProcessFramesPossible())
1540 return;
1542 DCHECK(!frame_tree_node_->frame_name().empty());
1544 // If this is a top-level frame, create proxies for this node in the
1545 // SiteInstances of its opener's ancestors, which are allowed to discover
1546 // this frame by name (see https://crbug.com/511474 and part 4 of
1547 // https://html.spec.whatwg.org/#the-rules-for-choosing-a-browsing-context-
1548 // given-a-browsing-context-name).
1549 FrameTreeNode* opener = frame_tree_node_->opener();
1550 if (!opener || !frame_tree_node_->IsMainFrame())
1551 return;
1552 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1554 // Start from opener's parent. There's no need to create a proxy in the
1555 // opener's SiteInstance, since new windows are always first opened in the
1556 // same SiteInstance as their opener, and if the new window navigates
1557 // cross-site, that proxy would be created as part of swapping out.
1558 for (FrameTreeNode* ancestor = opener->parent(); ancestor;
1559 ancestor = ancestor->parent()) {
1560 RenderFrameHostImpl* ancestor_rfh = ancestor->current_frame_host();
1561 if (ancestor_rfh->GetSiteInstance() != current_instance)
1562 CreateRenderFrameProxy(ancestor_rfh->GetSiteInstance());
1566 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::CreateRenderFrameHost(
1567 SiteInstance* site_instance,
1568 int view_routing_id,
1569 int frame_routing_id,
1570 int flags) {
1571 if (frame_routing_id == MSG_ROUTING_NONE)
1572 frame_routing_id = site_instance->GetProcess()->GetNextRoutingID();
1574 bool swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
1575 bool hidden = !!(flags & CREATE_RF_HIDDEN);
1577 // Create a RVH for main frames, or find the existing one for subframes.
1578 FrameTree* frame_tree = frame_tree_node_->frame_tree();
1579 RenderViewHostImpl* render_view_host = nullptr;
1580 if (frame_tree_node_->IsMainFrame()) {
1581 render_view_host = frame_tree->CreateRenderViewHost(
1582 site_instance, view_routing_id, frame_routing_id, swapped_out, hidden);
1583 } else {
1584 render_view_host = frame_tree->GetRenderViewHost(site_instance);
1586 CHECK(render_view_host);
1589 // TODO(creis): Pass hidden to RFH.
1590 scoped_ptr<RenderFrameHostImpl> render_frame_host = make_scoped_ptr(
1591 RenderFrameHostFactory::Create(
1592 site_instance, render_view_host, render_frame_delegate_,
1593 render_widget_delegate_, frame_tree, frame_tree_node_,
1594 frame_routing_id, flags).release());
1595 return render_frame_host.Pass();
1598 // PlzNavigate
1599 bool RenderFrameHostManager::CreateSpeculativeRenderFrameHost(
1600 const GURL& url,
1601 SiteInstance* old_instance,
1602 SiteInstance* new_instance,
1603 int bindings) {
1604 CHECK(new_instance);
1605 CHECK_NE(old_instance, new_instance);
1606 CHECK(!should_reuse_web_ui_);
1608 // Note: |speculative_web_ui_| must be initialized before starting the
1609 // |speculative_render_frame_host_| creation steps otherwise the WebUI
1610 // won't be properly initialized.
1611 speculative_web_ui_ = CreateWebUI(url, bindings);
1613 // The process for the new SiteInstance may (if we're sharing a process with
1614 // another host that already initialized it) or may not (we have our own
1615 // process or the existing process crashed) have been initialized. Calling
1616 // Init multiple times will be ignored, so this is safe.
1617 if (!new_instance->GetProcess()->Init())
1618 return false;
1620 int create_render_frame_flags = 0;
1621 CreateProxiesForNewRenderFrameHost(old_instance, new_instance,
1622 &create_render_frame_flags);
1624 if (frame_tree_node_->IsMainFrame())
1625 create_render_frame_flags |= CREATE_RF_FOR_MAIN_FRAME_NAVIGATION;
1626 if (delegate_->IsHidden())
1627 create_render_frame_flags |= CREATE_RF_HIDDEN;
1628 speculative_render_frame_host_ =
1629 CreateRenderFrame(new_instance, speculative_web_ui_.get(),
1630 create_render_frame_flags, nullptr);
1632 if (!speculative_render_frame_host_) {
1633 speculative_web_ui_.reset();
1634 return false;
1636 return true;
1639 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::CreateRenderFrame(
1640 SiteInstance* instance,
1641 WebUIImpl* web_ui,
1642 int flags,
1643 int* view_routing_id_ptr) {
1644 bool swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
1645 bool swapped_out_forbidden =
1646 SiteIsolationPolicy::IsSwappedOutStateForbidden();
1648 CHECK(instance);
1649 CHECK_IMPLIES(swapped_out_forbidden, !swapped_out);
1650 CHECK_IMPLIES(!SiteIsolationPolicy::AreCrossProcessFramesPossible(),
1651 frame_tree_node_->IsMainFrame());
1653 // Swapped out views should always be hidden.
1654 DCHECK_IMPLIES(swapped_out, (flags & CREATE_RF_HIDDEN));
1656 scoped_ptr<RenderFrameHostImpl> new_render_frame_host;
1657 bool success = true;
1658 if (view_routing_id_ptr)
1659 *view_routing_id_ptr = MSG_ROUTING_NONE;
1661 // We are creating a pending, speculative or swapped out RFH here. We should
1662 // never create it in the same SiteInstance as our current RFH.
1663 CHECK_NE(render_frame_host_->GetSiteInstance(), instance);
1665 // Check if we've already created an RFH for this SiteInstance. If so, try
1666 // to re-use the existing one, which has already been initialized. We'll
1667 // remove it from the list of proxy hosts below if it will be active.
1668 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1669 if (proxy && proxy->render_frame_host()) {
1670 CHECK(!swapped_out_forbidden);
1671 if (view_routing_id_ptr)
1672 *view_routing_id_ptr = proxy->GetRenderViewHost()->GetRoutingID();
1673 // Delete the existing RenderFrameProxyHost, but reuse the RenderFrameHost.
1674 // Prevent the process from exiting while we're trying to use it.
1675 if (!swapped_out) {
1676 new_render_frame_host = proxy->PassFrameHostOwnership();
1677 new_render_frame_host->GetProcess()->AddPendingView();
1679 proxy_hosts_->Remove(instance->GetId());
1680 // NB |proxy| is deleted at this point.
1682 } else {
1683 // Create a new RenderFrameHost if we don't find an existing one.
1684 new_render_frame_host = CreateRenderFrameHost(instance, MSG_ROUTING_NONE,
1685 MSG_ROUTING_NONE, flags);
1686 RenderViewHostImpl* render_view_host =
1687 new_render_frame_host->render_view_host();
1688 int proxy_routing_id = MSG_ROUTING_NONE;
1690 // Prevent the process from exiting while we're trying to navigate in it.
1691 // Otherwise, if the new RFH is swapped out already, store it.
1692 if (!swapped_out) {
1693 new_render_frame_host->GetProcess()->AddPendingView();
1694 } else {
1695 proxy = new RenderFrameProxyHost(
1696 new_render_frame_host->GetSiteInstance(),
1697 new_render_frame_host->render_view_host(), frame_tree_node_);
1698 proxy_hosts_->Add(instance->GetId(), make_scoped_ptr(proxy));
1699 proxy_routing_id = proxy->GetRoutingID();
1700 proxy->TakeFrameHostOwnership(new_render_frame_host.Pass());
1703 success = InitRenderView(render_view_host, proxy_routing_id,
1704 !!(flags & CREATE_RF_FOR_MAIN_FRAME_NAVIGATION));
1705 if (success) {
1706 // Remember that InitRenderView also created the RenderFrameProxy.
1707 if (swapped_out)
1708 proxy->set_render_frame_proxy_created(true);
1709 if (frame_tree_node_->IsMainFrame()) {
1710 // Don't show the main frame's view until we get a DidNavigate from it.
1711 // Only the RenderViewHost for the top-level RenderFrameHost has a
1712 // RenderWidgetHostView; RenderWidgetHosts for out-of-process iframes
1713 // will be created later and hidden.
1714 if (render_view_host->GetView())
1715 render_view_host->GetView()->Hide();
1717 // RenderViewHost for |instance| might exist prior to calling
1718 // CreateRenderFrame. In such a case, InitRenderView will not create the
1719 // RenderFrame in the renderer process and it needs to be done
1720 // explicitly.
1721 if (swapped_out_forbidden) {
1722 // Init the RFH, so a RenderFrame is created in the renderer.
1723 DCHECK(new_render_frame_host);
1724 success = InitRenderFrame(new_render_frame_host.get());
1728 if (success) {
1729 if (view_routing_id_ptr)
1730 *view_routing_id_ptr = render_view_host->GetRoutingID();
1734 // When a new RenderView is created by the renderer process, the new
1735 // WebContents gets a RenderViewHost in the SiteInstance of its opener
1736 // WebContents. If not used in the first navigation, this RVH is swapped out
1737 // and is not granted bindings, so we may need to grant them when swapping it
1738 // in.
1739 if (web_ui && !new_render_frame_host->GetProcess()->IsForGuestsOnly()) {
1740 int required_bindings = web_ui->GetBindings();
1741 RenderViewHost* render_view_host =
1742 new_render_frame_host->render_view_host();
1743 if ((render_view_host->GetEnabledBindings() & required_bindings) !=
1744 required_bindings) {
1745 render_view_host->AllowBindings(required_bindings);
1749 // Returns the new RFH if it isn't swapped out.
1750 if (success && !swapped_out) {
1751 DCHECK(new_render_frame_host->GetSiteInstance() == instance);
1752 return new_render_frame_host.Pass();
1754 return nullptr;
1757 int RenderFrameHostManager::CreateRenderFrameProxy(SiteInstance* instance) {
1758 // A RenderFrameProxyHost should never be created in the same SiteInstance as
1759 // the current RFH.
1760 CHECK(instance);
1761 CHECK_NE(instance, render_frame_host_->GetSiteInstance());
1763 RenderViewHostImpl* render_view_host = nullptr;
1765 // Ensure a RenderViewHost exists for |instance|, as it creates the page
1766 // level structure in Blink.
1767 if (SiteIsolationPolicy::IsSwappedOutStateForbidden()) {
1768 render_view_host =
1769 frame_tree_node_->frame_tree()->GetRenderViewHost(instance);
1770 if (!render_view_host) {
1771 CHECK(frame_tree_node_->IsMainFrame());
1772 render_view_host = frame_tree_node_->frame_tree()->CreateRenderViewHost(
1773 instance, MSG_ROUTING_NONE, MSG_ROUTING_NONE, true, true);
1777 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1778 if (proxy && proxy->is_render_frame_proxy_live())
1779 return proxy->GetRoutingID();
1781 if (!proxy) {
1782 proxy =
1783 new RenderFrameProxyHost(instance, render_view_host, frame_tree_node_);
1784 proxy_hosts_->Add(instance->GetId(), make_scoped_ptr(proxy));
1787 if (SiteIsolationPolicy::IsSwappedOutStateForbidden() &&
1788 frame_tree_node_->IsMainFrame()) {
1789 InitRenderView(render_view_host, proxy->GetRoutingID(), true);
1790 proxy->set_render_frame_proxy_created(true);
1791 } else {
1792 proxy->InitRenderFrameProxy();
1795 return proxy->GetRoutingID();
1798 void RenderFrameHostManager::CreateProxiesForChildFrame(FrameTreeNode* child) {
1799 for (const auto& pair : *proxy_hosts_) {
1800 // Do not create proxies for subframes in the outer delegate's process,
1801 // since the outer delegate does not need to interact with them.
1802 if (ForInnerDelegate() && pair.second == GetProxyToOuterDelegate())
1803 continue;
1805 child->render_manager()->CreateRenderFrameProxy(
1806 pair.second->GetSiteInstance());
1810 void RenderFrameHostManager::EnsureRenderViewInitialized(
1811 RenderViewHostImpl* render_view_host,
1812 SiteInstance* instance) {
1813 DCHECK(frame_tree_node_->IsMainFrame());
1815 if (render_view_host->IsRenderViewLive())
1816 return;
1818 // Recreate the opener chain.
1819 CreateOpenerProxiesIfNeeded(instance);
1821 // If the proxy in |instance| doesn't exist, this RenderView is not swapped
1822 // out and shouldn't be reinitialized here.
1823 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1824 if (!proxy)
1825 return;
1827 InitRenderView(render_view_host, proxy->GetRoutingID(), false);
1828 proxy->set_render_frame_proxy_created(true);
1831 void RenderFrameHostManager::CreateOuterDelegateProxy(
1832 SiteInstance* outer_contents_site_instance,
1833 RenderFrameHostImpl* render_frame_host) {
1834 CHECK(BrowserPluginGuestMode::UseCrossProcessFramesForGuests());
1835 RenderFrameProxyHost* proxy = new RenderFrameProxyHost(
1836 outer_contents_site_instance, nullptr, frame_tree_node_);
1837 proxy_hosts_->Add(outer_contents_site_instance->GetId(),
1838 make_scoped_ptr(proxy));
1840 // Swap the outer WebContents's frame with the proxy to inner WebContents.
1842 // We are in the outer WebContents, and its FrameTree would never see
1843 // a load start for any of its inner WebContents. Eventually, that also makes
1844 // the FrameTree never see the matching load stop. Therefore, we always pass
1845 // false to |is_loading| below.
1846 // TODO(lazyboy): This |is_loading| behavior might not be what we want,
1847 // investigate and fix.
1848 render_frame_host->Send(new FrameMsg_SwapOut(
1849 render_frame_host->GetRoutingID(), proxy->GetRoutingID(),
1850 false /* is_loading */, FrameReplicationState()));
1851 proxy->set_render_frame_proxy_created(true);
1854 void RenderFrameHostManager::SetRWHViewForInnerContents(
1855 RenderWidgetHostView* child_rwhv) {
1856 DCHECK(ForInnerDelegate() && frame_tree_node_->IsMainFrame());
1857 GetProxyToOuterDelegate()->SetChildRWHView(child_rwhv);
1860 bool RenderFrameHostManager::InitRenderView(
1861 RenderViewHostImpl* render_view_host,
1862 int proxy_routing_id,
1863 bool for_main_frame_navigation) {
1864 // Ensure the renderer process is initialized before creating the
1865 // RenderView.
1866 if (!render_view_host->GetProcess()->Init())
1867 return false;
1869 // We may have initialized this RenderViewHost for another RenderFrameHost.
1870 if (render_view_host->IsRenderViewLive())
1871 return true;
1873 // If the ongoing navigation is to a WebUI and the RenderView is not in a
1874 // guest process, tell the RenderViewHost about any bindings it will need
1875 // enabled.
1876 WebUIImpl* dest_web_ui = nullptr;
1877 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1878 switches::kEnableBrowserSideNavigation)) {
1879 dest_web_ui =
1880 should_reuse_web_ui_ ? web_ui_.get() : speculative_web_ui_.get();
1881 } else {
1882 dest_web_ui = pending_web_ui();
1884 if (dest_web_ui && !render_view_host->GetProcess()->IsForGuestsOnly()) {
1885 render_view_host->AllowBindings(dest_web_ui->GetBindings());
1886 } else {
1887 // Ensure that we don't create an unprivileged RenderView in a WebUI-enabled
1888 // process unless it's swapped out.
1889 if (render_view_host->is_active()) {
1890 CHECK(!ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1891 render_view_host->GetProcess()->GetID()));
1895 int opener_frame_routing_id =
1896 GetOpenerRoutingID(render_view_host->GetSiteInstance());
1898 return delegate_->CreateRenderViewForRenderManager(
1899 render_view_host, opener_frame_routing_id, proxy_routing_id,
1900 frame_tree_node_->current_replication_state(), for_main_frame_navigation);
1903 bool RenderFrameHostManager::InitRenderFrame(
1904 RenderFrameHostImpl* render_frame_host) {
1905 if (render_frame_host->IsRenderFrameLive())
1906 return true;
1908 int parent_routing_id = MSG_ROUTING_NONE;
1909 int previous_sibling_routing_id = MSG_ROUTING_NONE;
1910 int proxy_routing_id = MSG_ROUTING_NONE;
1912 if (frame_tree_node_->parent()) {
1913 parent_routing_id = frame_tree_node_->parent()->render_manager()->
1914 GetRoutingIdForSiteInstance(render_frame_host->GetSiteInstance());
1915 CHECK_NE(parent_routing_id, MSG_ROUTING_NONE);
1918 // At this point, all RenderFrameProxies for sibling frames have already been
1919 // created, including any proxies that come after this frame. To preserve
1920 // correct order for indexed window access (e.g., window.frames[1]), pass the
1921 // previous sibling frame so that this frame is correctly inserted into the
1922 // frame tree on the renderer side.
1923 FrameTreeNode* previous_sibling = frame_tree_node_->PreviousSibling();
1924 if (previous_sibling) {
1925 previous_sibling_routing_id =
1926 previous_sibling->render_manager()->GetRoutingIdForSiteInstance(
1927 render_frame_host->GetSiteInstance());
1928 CHECK_NE(previous_sibling_routing_id, MSG_ROUTING_NONE);
1931 // Check whether there is an existing proxy for this frame in this
1932 // SiteInstance. If there is, the new RenderFrame needs to be able to find
1933 // the proxy it is replacing, so that it can fully initialize itself.
1934 // NOTE: This is the only time that a RenderFrameProxyHost can be in the same
1935 // SiteInstance as its RenderFrameHost. This is only the case until the
1936 // RenderFrameHost commits, at which point it will replace and delete the
1937 // RenderFrameProxyHost.
1938 RenderFrameProxyHost* existing_proxy =
1939 GetRenderFrameProxyHost(render_frame_host->GetSiteInstance());
1940 if (existing_proxy) {
1941 proxy_routing_id = existing_proxy->GetRoutingID();
1942 CHECK_NE(proxy_routing_id, MSG_ROUTING_NONE);
1943 if (!existing_proxy->is_render_frame_proxy_live())
1944 existing_proxy->InitRenderFrameProxy();
1946 return delegate_->CreateRenderFrameForRenderManager(
1947 render_frame_host, parent_routing_id, previous_sibling_routing_id,
1948 proxy_routing_id);
1951 int RenderFrameHostManager::GetRoutingIdForSiteInstance(
1952 SiteInstance* site_instance) {
1953 if (render_frame_host_->GetSiteInstance() == site_instance)
1954 return render_frame_host_->GetRoutingID();
1956 // If there is a matching pending RFH, only return it if swapped out is
1957 // allowed, since otherwise there should be a proxy that should be used
1958 // instead.
1959 if (pending_render_frame_host_ &&
1960 pending_render_frame_host_->GetSiteInstance() == site_instance &&
1961 !SiteIsolationPolicy::IsSwappedOutStateForbidden())
1962 return pending_render_frame_host_->GetRoutingID();
1964 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(site_instance);
1965 if (proxy)
1966 return proxy->GetRoutingID();
1968 return MSG_ROUTING_NONE;
1971 void RenderFrameHostManager::CommitPending() {
1972 TRACE_EVENT1("navigation", "RenderFrameHostManager::CommitPending",
1973 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
1974 bool browser_side_navigation =
1975 base::CommandLine::ForCurrentProcess()->HasSwitch(
1976 switches::kEnableBrowserSideNavigation);
1978 // First check whether we're going to want to focus the location bar after
1979 // this commit. We do this now because the navigation hasn't formally
1980 // committed yet, so if we've already cleared |pending_web_ui_| the call chain
1981 // this triggers won't be able to figure out what's going on.
1982 bool will_focus_location_bar = delegate_->FocusLocationBarByDefault();
1984 // Next commit the Web UI, if any. Either replace |web_ui_| with
1985 // |pending_web_ui_|, or clear |web_ui_| if there is no pending WebUI, or
1986 // leave |web_ui_| as is if reusing it.
1987 DCHECK(!(pending_web_ui_ && pending_and_current_web_ui_));
1988 if (pending_web_ui_ || speculative_web_ui_) {
1989 DCHECK(!should_reuse_web_ui_);
1990 web_ui_.reset(browser_side_navigation ? speculative_web_ui_.release()
1991 : pending_web_ui_.release());
1992 } else if (pending_and_current_web_ui_ || should_reuse_web_ui_) {
1993 if (browser_side_navigation) {
1994 DCHECK(web_ui_);
1995 should_reuse_web_ui_ = false;
1996 } else {
1997 DCHECK_EQ(pending_and_current_web_ui_.get(), web_ui_.get());
1998 pending_and_current_web_ui_.reset();
2000 } else {
2001 web_ui_.reset();
2003 DCHECK(!speculative_web_ui_);
2004 DCHECK(!should_reuse_web_ui_);
2006 // It's possible for the pending_render_frame_host_ to be nullptr when we
2007 // aren't crossing process boundaries. If so, we just needed to handle the Web
2008 // UI committing above and we're done.
2009 if (!pending_render_frame_host_ && !speculative_render_frame_host_) {
2010 if (will_focus_location_bar)
2011 delegate_->SetFocusToLocationBar(false);
2012 return;
2015 // Remember if the page was focused so we can focus the new renderer in
2016 // that case.
2017 bool focus_render_view = !will_focus_location_bar &&
2018 render_frame_host_->GetView() &&
2019 render_frame_host_->GetView()->HasFocus();
2021 bool is_main_frame = frame_tree_node_->IsMainFrame();
2023 // Swap in the pending or speculative frame and make it active. Also ensure
2024 // the FrameTree stays in sync.
2025 scoped_ptr<RenderFrameHostImpl> old_render_frame_host;
2026 if (!browser_side_navigation) {
2027 DCHECK(!speculative_render_frame_host_);
2028 old_render_frame_host =
2029 SetRenderFrameHost(pending_render_frame_host_.Pass());
2030 } else {
2031 // PlzNavigate
2032 DCHECK(speculative_render_frame_host_);
2033 old_render_frame_host =
2034 SetRenderFrameHost(speculative_render_frame_host_.Pass());
2037 // Remove the children of the old frame from the tree.
2038 frame_tree_node_->ResetForNewProcess();
2040 // The process will no longer try to exit, so we can decrement the count.
2041 render_frame_host_->GetProcess()->RemovePendingView();
2043 // Show the new view (or a sad tab) if necessary.
2044 bool new_rfh_has_view = !!render_frame_host_->GetView();
2045 if (!delegate_->IsHidden() && new_rfh_has_view) {
2046 // In most cases, we need to show the new view.
2047 render_frame_host_->GetView()->Show();
2049 if (!new_rfh_has_view) {
2050 // If the view is gone, then this RenderViewHost died while it was hidden.
2051 // We ignored the RenderProcessGone call at the time, so we should send it
2052 // now to make sure the sad tab shows up, etc.
2053 DCHECK(!render_frame_host_->IsRenderFrameLive());
2054 DCHECK(!render_frame_host_->render_view_host()->IsRenderViewLive());
2055 delegate_->RenderProcessGoneFromRenderManager(
2056 render_frame_host_->render_view_host());
2059 // For top-level frames, also hide the old RenderViewHost's view.
2060 // TODO(creis): As long as show/hide are on RVH, we don't want to hide on
2061 // subframe navigations or we will interfere with the top-level frame.
2062 if (is_main_frame && old_render_frame_host->render_view_host()->GetView())
2063 old_render_frame_host->render_view_host()->GetView()->Hide();
2065 // Make sure the size is up to date. (Fix for bug 1079768.)
2066 delegate_->UpdateRenderViewSizeForRenderManager();
2068 if (will_focus_location_bar) {
2069 delegate_->SetFocusToLocationBar(false);
2070 } else if (focus_render_view && render_frame_host_->GetView()) {
2071 render_frame_host_->GetView()->Focus();
2074 // Notify that we've swapped RenderFrameHosts. We do this before shutting down
2075 // the RFH so that we can clean up RendererResources related to the RFH first.
2076 delegate_->NotifySwappedFromRenderManager(
2077 old_render_frame_host.get(), render_frame_host_.get(), is_main_frame);
2079 // The RenderViewHost keeps track of the main RenderFrameHost routing id.
2080 // If this is committing a main frame navigation, update it and set the
2081 // routing id in the RenderViewHost associated with the old RenderFrameHost
2082 // to MSG_ROUTING_NONE.
2083 if (is_main_frame && SiteIsolationPolicy::IsSwappedOutStateForbidden()) {
2084 render_frame_host_->render_view_host()->set_main_frame_routing_id(
2085 render_frame_host_->routing_id());
2086 old_render_frame_host->render_view_host()->set_main_frame_routing_id(
2087 MSG_ROUTING_NONE);
2090 // Swap out the old frame now that the new one is visible.
2091 // This will swap it out and then put it on the proxy list (if there are other
2092 // active views in its SiteInstance) or schedule it for deletion when the swap
2093 // out ack arrives (or immediately if the process isn't live).
2094 // In the --site-per-process case, old subframe RFHs are not kept alive inside
2095 // the proxy.
2096 SwapOutOldFrame(old_render_frame_host.Pass());
2098 if (SiteIsolationPolicy::IsSwappedOutStateForbidden()) {
2099 // Since the new RenderFrameHost is now committed, there must be no proxies
2100 // for its SiteInstance. Delete any existing ones.
2101 proxy_hosts_->Remove(render_frame_host_->GetSiteInstance()->GetId());
2104 // If this is a subframe, it should have a CrossProcessFrameConnector
2105 // created already. Use it to link the new RFH's view to the proxy that
2106 // belongs to the parent frame's SiteInstance. If this navigation causes
2107 // an out-of-process frame to return to the same process as its parent, the
2108 // proxy would have been removed from proxy_hosts_ above.
2109 // Note: We do this after swapping out the old RFH because that may create
2110 // the proxy we're looking for.
2111 RenderFrameProxyHost* proxy_to_parent = GetProxyToParent();
2112 if (proxy_to_parent) {
2113 CHECK(SiteIsolationPolicy::AreCrossProcessFramesPossible());
2114 proxy_to_parent->SetChildRWHView(render_frame_host_->GetView());
2117 // After all is done, there must never be a proxy in the list which has the
2118 // same SiteInstance as the current RenderFrameHost.
2119 CHECK(!proxy_hosts_->Get(render_frame_host_->GetSiteInstance()->GetId()));
2122 void RenderFrameHostManager::ShutdownProxiesIfLastActiveFrameInSiteInstance(
2123 RenderFrameHostImpl* render_frame_host) {
2124 if (!render_frame_host)
2125 return;
2126 if (!RenderFrameHostImpl::IsRFHStateActive(render_frame_host->rfh_state()))
2127 return;
2128 if (render_frame_host->GetSiteInstance()->active_frame_count() > 1U)
2129 return;
2131 // After |render_frame_host| goes away, there will be no active frames left in
2132 // its SiteInstance, so we can delete all proxies created in that SiteInstance
2133 // on behalf of frames anywhere in the BrowsingInstance.
2134 int32 site_instance_id = render_frame_host->GetSiteInstance()->GetId();
2136 // First remove any proxies for this SiteInstance from our own list.
2137 ClearProxiesInSiteInstance(site_instance_id, frame_tree_node_);
2139 // Use the safe RenderWidgetHost iterator for now to find all RenderViewHosts
2140 // in the SiteInstance, then tell their respective FrameTrees to remove all
2141 // RenderFrameProxyHosts corresponding to them.
2142 // TODO(creis): Replace this with a RenderFrameHostIterator that protects
2143 // against use-after-frees if a later element is deleted before getting to it.
2144 scoped_ptr<RenderWidgetHostIterator> widgets(
2145 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
2146 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2147 if (!widget->IsRenderView())
2148 continue;
2149 RenderViewHostImpl* rvh =
2150 static_cast<RenderViewHostImpl*>(RenderViewHost::From(widget));
2151 if (site_instance_id == rvh->GetSiteInstance()->GetId()) {
2152 // This deletes all RenderFrameHosts using the |rvh|, which then causes
2153 // |rvh| to Shutdown.
2154 FrameTree* tree = rvh->GetDelegate()->GetFrameTree();
2155 tree->ForEach(base::Bind(
2156 &RenderFrameHostManager::ClearProxiesInSiteInstance,
2157 site_instance_id));
2162 RenderFrameHostImpl* RenderFrameHostManager::UpdateStateForNavigate(
2163 const GURL& dest_url,
2164 SiteInstance* source_instance,
2165 SiteInstance* dest_instance,
2166 ui::PageTransition transition,
2167 bool dest_is_restore,
2168 bool dest_is_view_source_mode,
2169 const GlobalRequestID& transferred_request_id,
2170 int bindings) {
2171 // Don't swap for subframes unless we are in --site-per-process. We can get
2172 // here in tests for subframes (e.g., NavigateFrameToURL).
2173 if (!frame_tree_node_->IsMainFrame() &&
2174 !SiteIsolationPolicy::AreCrossProcessFramesPossible()) {
2175 return render_frame_host_.get();
2178 // If we are currently navigating cross-process, we want to get back to normal
2179 // and then navigate as usual.
2180 if (pending_render_frame_host_)
2181 CancelPending();
2183 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
2184 scoped_refptr<SiteInstance> new_instance = GetSiteInstanceForNavigation(
2185 dest_url, source_instance, dest_instance, nullptr, transition,
2186 dest_is_restore, dest_is_view_source_mode);
2188 const NavigationEntry* current_entry =
2189 delegate_->GetLastCommittedNavigationEntryForRenderManager();
2191 DCHECK(!pending_render_frame_host_);
2193 if (new_instance.get() != current_instance) {
2194 TRACE_EVENT_INSTANT2(
2195 "navigation",
2196 "RenderFrameHostManager::UpdateStateForNavigate:New SiteInstance",
2197 TRACE_EVENT_SCOPE_THREAD,
2198 "current_instance id", current_instance->GetId(),
2199 "new_instance id", new_instance->GetId());
2201 // New SiteInstance: create a pending RFH to navigate.
2203 // This will possibly create (set to nullptr) a Web UI object for the
2204 // pending page. We'll use this later to give the page special access. This
2205 // must happen before the new renderer is created below so it will get
2206 // bindings. It must also happen after the above conditional call to
2207 // CancelPending(), otherwise CancelPending may clear the pending_web_ui_
2208 // and the page will not have its bindings set appropriately.
2209 SetPendingWebUI(dest_url, bindings);
2210 CreatePendingRenderFrameHost(current_instance, new_instance.get(),
2211 frame_tree_node_->IsMainFrame());
2212 if (!pending_render_frame_host_)
2213 return nullptr;
2215 // Check if our current RFH is live before we set up a transition.
2216 if (!render_frame_host_->IsRenderFrameLive()) {
2217 // The current RFH is not live. There's no reason to sit around with a
2218 // sad tab or a newly created RFH while we wait for the pending RFH to
2219 // navigate. Just switch to the pending RFH now and go back to normal.
2220 // (Note that we don't care about on{before}unload handlers if the current
2221 // RFH isn't live.)
2222 CommitPending();
2223 return render_frame_host_.get();
2225 // Otherwise, it's safe to treat this as a pending cross-process transition.
2227 // We now have a pending RFH.
2228 DCHECK(pending_render_frame_host_);
2230 // We need to wait until the beforeunload handler has run, unless we are
2231 // transferring an existing request (in which case it has already run).
2232 // Suspend the new render view (i.e., don't let it send the cross-process
2233 // Navigate message) until we hear back from the old renderer's
2234 // beforeunload handler. If the handler returns false, we'll have to
2235 // cancel the request.
2237 DCHECK(!pending_render_frame_host_->are_navigations_suspended());
2238 bool is_transfer = transferred_request_id != GlobalRequestID();
2239 if (is_transfer) {
2240 // We don't need to stop the old renderer or run beforeunload/unload
2241 // handlers, because those have already been done.
2242 DCHECK(cross_site_transferring_request_->request_id() ==
2243 transferred_request_id);
2244 } else {
2245 // Also make sure the old render view stops, in case a load is in
2246 // progress. (We don't want to do this for transfers, since it will
2247 // interrupt the transfer with an unexpected DidStopLoading.)
2248 render_frame_host_->Send(new FrameMsg_Stop(
2249 render_frame_host_->GetRoutingID()));
2250 pending_render_frame_host_->SetNavigationsSuspended(true,
2251 base::TimeTicks());
2252 // Unless we are transferring an existing request, we should now tell the
2253 // old render view to run its beforeunload handler, since it doesn't
2254 // otherwise know that the cross-site request is happening. This will
2255 // trigger a call to OnBeforeUnloadACK with the reply.
2256 render_frame_host_->DispatchBeforeUnload(true);
2259 return pending_render_frame_host_.get();
2262 // Otherwise the same SiteInstance can be used. Navigate render_frame_host_.
2264 // It's possible to swap out the current RFH and then decide to navigate in it
2265 // anyway (e.g., a cross-process navigation that redirects back to the
2266 // original site). In that case, we have a proxy for the current RFH but
2267 // haven't deleted it yet. The new navigation will swap it back in, so we can
2268 // delete the proxy.
2269 proxy_hosts_->Remove(new_instance.get()->GetId());
2271 if (ShouldReuseWebUI(current_entry, dest_url)) {
2272 pending_web_ui_.reset();
2273 pending_and_current_web_ui_ = web_ui_->AsWeakPtr();
2274 } else {
2275 SetPendingWebUI(dest_url, bindings);
2276 // Make sure the new RenderViewHost has the right bindings.
2277 if (pending_web_ui() &&
2278 !render_frame_host_->GetProcess()->IsForGuestsOnly()) {
2279 render_frame_host_->render_view_host()->AllowBindings(
2280 pending_web_ui()->GetBindings());
2284 if (pending_web_ui() && render_frame_host_->IsRenderFrameLive()) {
2285 pending_web_ui()->GetController()->RenderViewReused(
2286 render_frame_host_->render_view_host());
2289 // The renderer can exit view source mode when any error or cancellation
2290 // happen. We must overwrite to recover the mode.
2291 if (dest_is_view_source_mode) {
2292 render_frame_host_->render_view_host()->Send(
2293 new ViewMsg_EnableViewSourceMode(
2294 render_frame_host_->render_view_host()->GetRoutingID()));
2297 return render_frame_host_.get();
2300 void RenderFrameHostManager::CancelPending() {
2301 TRACE_EVENT1("navigation", "RenderFrameHostManager::CancelPending",
2302 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
2303 DiscardUnusedFrame(UnsetPendingRenderFrameHost());
2306 scoped_ptr<RenderFrameHostImpl>
2307 RenderFrameHostManager::UnsetPendingRenderFrameHost() {
2308 scoped_ptr<RenderFrameHostImpl> pending_render_frame_host =
2309 pending_render_frame_host_.Pass();
2311 RenderFrameDevToolsAgentHost::OnCancelPendingNavigation(
2312 pending_render_frame_host.get(),
2313 render_frame_host_.get());
2315 // We no longer need to prevent the process from exiting.
2316 pending_render_frame_host->GetProcess()->RemovePendingView();
2318 pending_web_ui_.reset();
2319 pending_and_current_web_ui_.reset();
2321 return pending_render_frame_host.Pass();
2324 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::SetRenderFrameHost(
2325 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
2326 // Swap the two.
2327 scoped_ptr<RenderFrameHostImpl> old_render_frame_host =
2328 render_frame_host_.Pass();
2329 render_frame_host_ = render_frame_host.Pass();
2331 if (frame_tree_node_->IsMainFrame()) {
2332 // Update the count of top-level frames using this SiteInstance. All
2333 // subframes are in the same BrowsingInstance as the main frame, so we only
2334 // count top-level ones. This makes the value easier for consumers to
2335 // interpret.
2336 if (render_frame_host_) {
2337 render_frame_host_->GetSiteInstance()->
2338 IncrementRelatedActiveContentsCount();
2340 if (old_render_frame_host) {
2341 old_render_frame_host->GetSiteInstance()->
2342 DecrementRelatedActiveContentsCount();
2346 return old_render_frame_host.Pass();
2349 bool RenderFrameHostManager::IsRVHOnSwappedOutList(
2350 RenderViewHostImpl* rvh) const {
2351 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(
2352 rvh->GetSiteInstance());
2353 if (!proxy)
2354 return false;
2355 // If there is a proxy without RFH, it is for a subframe in the SiteInstance
2356 // of |rvh|. Subframes should be ignored in this case.
2357 if (!proxy->render_frame_host())
2358 return false;
2359 return IsOnSwappedOutList(proxy->render_frame_host());
2362 bool RenderFrameHostManager::IsOnSwappedOutList(
2363 RenderFrameHostImpl* rfh) const {
2364 if (!rfh->GetSiteInstance())
2365 return false;
2367 RenderFrameProxyHost* host =
2368 proxy_hosts_->Get(rfh->GetSiteInstance()->GetId());
2369 if (!host)
2370 return false;
2372 return host->render_frame_host() == rfh;
2375 RenderViewHostImpl* RenderFrameHostManager::GetSwappedOutRenderViewHost(
2376 SiteInstance* instance) const {
2377 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
2378 if (proxy)
2379 return proxy->GetRenderViewHost();
2380 return nullptr;
2383 RenderFrameProxyHost* RenderFrameHostManager::GetRenderFrameProxyHost(
2384 SiteInstance* instance) const {
2385 return proxy_hosts_->Get(instance->GetId());
2388 std::map<int, RenderFrameProxyHost*>
2389 RenderFrameHostManager::GetAllProxyHostsForTesting() {
2390 std::map<int, RenderFrameProxyHost*> result;
2391 result.insert(proxy_hosts_->begin(), proxy_hosts_->end());
2392 return result;
2395 void RenderFrameHostManager::CreateOpenerProxiesIfNeeded(
2396 SiteInstance* instance) {
2397 FrameTreeNode* opener = frame_tree_node_->opener();
2398 if (!opener)
2399 return;
2401 // Create proxies for the opener chain.
2402 opener->render_manager()->CreateOpenerProxies(instance);
2405 void RenderFrameHostManager::CreateOpenerProxies(SiteInstance* instance) {
2406 // If this tab has an opener, recursively create proxies for the nodes on its
2407 // frame tree.
2408 // TODO(alexmos): Once we allow frame openers to be updated (which can happen
2409 // via window.open(url, "target_frame")), this will need to be resilient to
2410 // cycles. It will also need to handle tabs that have multiple openers (e.g.,
2411 // main frame and subframe could have different openers, each of which must
2412 // be traversed).
2413 FrameTreeNode* opener = frame_tree_node_->opener();
2414 if (opener)
2415 opener->render_manager()->CreateOpenerProxies(instance);
2417 // If any of the RenderViewHosts (current, pending, or swapped out) for this
2418 // FrameTree has the same SiteInstance, then we can return early, since
2419 // proxies for other nodes in the tree should also exist (when in
2420 // site-per-process mode). An exception is if we are in
2421 // IsSwappedOutStateForbidden mode and find a pending RenderViewHost: in this
2422 // case, we should still create a proxy, which will allow communicating with
2423 // the opener until the pending RenderView commits, or if the pending
2424 // navigation is canceled.
2425 FrameTree* frame_tree = frame_tree_node_->frame_tree();
2426 RenderViewHostImpl* rvh = frame_tree->GetRenderViewHost(instance);
2427 bool need_proxy_for_pending_rvh =
2428 SiteIsolationPolicy::IsSwappedOutStateForbidden() &&
2429 (rvh == pending_render_view_host());
2430 if (rvh && rvh->IsRenderViewLive() && !need_proxy_for_pending_rvh)
2431 return;
2433 if (SiteIsolationPolicy::IsSwappedOutStateForbidden()) {
2434 // Ensure that all the nodes in the opener's frame tree have
2435 // RenderFrameProxyHosts for the new SiteInstance.
2436 frame_tree->CreateProxiesForSiteInstance(nullptr, instance);
2437 } else if (rvh && !rvh->IsRenderViewLive()) {
2438 EnsureRenderViewInitialized(rvh, instance);
2439 } else {
2440 // Create a swapped out RenderView in the given SiteInstance if none exists,
2441 // setting its opener to the given route_id. Since the opener can point to
2442 // a subframe, do this on the root frame of the opener's frame tree.
2443 // Return the new view's route_id.
2444 frame_tree->root()->render_manager()->
2445 CreateRenderFrame(instance, nullptr,
2446 CREATE_RF_FOR_MAIN_FRAME_NAVIGATION |
2447 CREATE_RF_SWAPPED_OUT | CREATE_RF_HIDDEN,
2448 nullptr);
2452 int RenderFrameHostManager::GetOpenerRoutingID(SiteInstance* instance) {
2453 if (!frame_tree_node_->opener())
2454 return MSG_ROUTING_NONE;
2456 return frame_tree_node_->opener()
2457 ->render_manager()
2458 ->GetRoutingIdForSiteInstance(instance);
2461 } // namespace content