Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_manager.cc
blobd02466ce2db8cef7215e5095b80a1bc8e7b6ee0d
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/frame_host/render_frame_host_manager.h"
7 #include <algorithm>
8 #include <utility>
10 #include "base/command_line.h"
11 #include "base/logging.h"
12 #include "base/stl_util.h"
13 #include "base/trace_event/trace_event.h"
14 #include "content/browser/child_process_security_policy_impl.h"
15 #include "content/browser/devtools/render_frame_devtools_agent_host.h"
16 #include "content/browser/frame_host/cross_site_transferring_request.h"
17 #include "content/browser/frame_host/debug_urls.h"
18 #include "content/browser/frame_host/frame_navigation_entry.h"
19 #include "content/browser/frame_host/interstitial_page_impl.h"
20 #include "content/browser/frame_host/navigation_controller_impl.h"
21 #include "content/browser/frame_host/navigation_entry_impl.h"
22 #include "content/browser/frame_host/navigation_request.h"
23 #include "content/browser/frame_host/navigator.h"
24 #include "content/browser/frame_host/render_frame_host_factory.h"
25 #include "content/browser/frame_host/render_frame_host_impl.h"
26 #include "content/browser/frame_host/render_frame_proxy_host.h"
27 #include "content/browser/renderer_host/render_process_host_impl.h"
28 #include "content/browser/renderer_host/render_view_host_factory.h"
29 #include "content/browser/renderer_host/render_view_host_impl.h"
30 #include "content/browser/site_instance_impl.h"
31 #include "content/browser/webui/web_ui_controller_factory_registry.h"
32 #include "content/browser/webui/web_ui_impl.h"
33 #include "content/common/frame_messages.h"
34 #include "content/common/view_messages.h"
35 #include "content/public/browser/content_browser_client.h"
36 #include "content/public/browser/render_process_host_observer.h"
37 #include "content/public/browser/render_widget_host_iterator.h"
38 #include "content/public/browser/render_widget_host_view.h"
39 #include "content/public/browser/user_metrics.h"
40 #include "content/public/browser/web_ui_controller.h"
41 #include "content/public/common/content_switches.h"
42 #include "content/public/common/referrer.h"
43 #include "content/public/common/url_constants.h"
45 namespace content {
47 // A helper class to hold all frame proxies and register as a
48 // RenderProcessHostObserver for them.
49 class RenderFrameHostManager::RenderFrameProxyHostMap
50 : public RenderProcessHostObserver {
51 public:
52 using MapType = base::hash_map<int32, RenderFrameProxyHost*>;
54 RenderFrameProxyHostMap(RenderFrameHostManager* manager);
55 ~RenderFrameProxyHostMap() override;
57 // Read-only access to the underlying map of site instance ID to
58 // RenderFrameProxyHosts.
59 MapType::const_iterator begin() const { return map_.begin(); }
60 MapType::const_iterator end() const { return map_.end(); }
61 bool empty() const { return map_.empty(); }
63 // Returns the proxy with the specified ID, or nullptr if there is no such
64 // one.
65 RenderFrameProxyHost* Get(int32 id);
67 // Adds the specified proxy with the specified ID. It is an error (and fatal)
68 // to add more than one proxy with the specified ID.
69 void Add(int32 id, scoped_ptr<RenderFrameProxyHost> proxy);
71 // Removes the proxy with the specified site instance ID.
72 void Remove(int32 id);
74 // Removes all proxies.
75 void Clear();
77 // RenderProcessHostObserver implementation.
78 void RenderProcessWillExit(RenderProcessHost* host) override;
79 void RenderProcessExited(RenderProcessHost* host,
80 base::TerminationStatus status,
81 int exit_code) override;
83 private:
84 RenderFrameHostManager* manager_;
85 MapType map_;
88 RenderFrameHostManager::RenderFrameProxyHostMap::RenderFrameProxyHostMap(
89 RenderFrameHostManager* manager)
90 : manager_(manager) {}
92 RenderFrameHostManager::RenderFrameProxyHostMap::~RenderFrameProxyHostMap() {
93 Clear();
96 RenderFrameProxyHost* RenderFrameHostManager::RenderFrameProxyHostMap::Get(
97 int32 id) {
98 auto it = map_.find(id);
99 if (it != map_.end())
100 return it->second;
101 return nullptr;
104 void RenderFrameHostManager::RenderFrameProxyHostMap::Add(
105 int32 id,
106 scoped_ptr<RenderFrameProxyHost> proxy) {
107 CHECK_EQ(0u, map_.count(id)) << "Inserting a duplicate item.";
109 // If this is the first proxy that has this process host, observe the
110 // process host.
111 RenderProcessHost* host = proxy->GetProcess();
112 size_t count =
113 std::count_if(begin(), end(), [host](MapType::value_type item) {
114 return item.second->GetProcess() == host;
116 if (count == 0)
117 host->AddObserver(this);
119 map_[id] = proxy.release();
122 void RenderFrameHostManager::RenderFrameProxyHostMap::Remove(int32 id) {
123 auto it = map_.find(id);
124 if (it == map_.end())
125 return;
127 // If this is the last proxy that has this process host, stop observing the
128 // process host.
129 RenderProcessHost* host = it->second->GetProcess();
130 size_t count =
131 std::count_if(begin(), end(), [host](MapType::value_type item) {
132 return item.second->GetProcess() == host;
134 if (count == 1)
135 host->RemoveObserver(this);
137 delete it->second;
138 map_.erase(it);
141 void RenderFrameHostManager::RenderFrameProxyHostMap::Clear() {
142 std::set<RenderProcessHost*> hosts;
143 for (const auto& pair : map_)
144 hosts.insert(pair.second->GetProcess());
145 for (auto host : hosts)
146 host->RemoveObserver(this);
148 STLDeleteValues(&map_);
151 void RenderFrameHostManager::RenderFrameProxyHostMap::RenderProcessWillExit(
152 RenderProcessHost* host) {
153 manager_->RendererProcessClosing(host);
156 void RenderFrameHostManager::RenderFrameProxyHostMap::RenderProcessExited(
157 RenderProcessHost* host,
158 base::TerminationStatus status,
159 int exit_code) {
160 manager_->RendererProcessClosing(host);
163 // static
164 bool RenderFrameHostManager::ClearRFHsPendingShutdown(FrameTreeNode* node) {
165 node->render_manager()->pending_delete_hosts_.clear();
166 return true;
169 // static
170 bool RenderFrameHostManager::IsSwappedOutStateForbidden() {
171 return base::CommandLine::ForCurrentProcess()->HasSwitch(
172 switches::kSitePerProcess);
175 RenderFrameHostManager::RenderFrameHostManager(
176 FrameTreeNode* frame_tree_node,
177 RenderFrameHostDelegate* render_frame_delegate,
178 RenderViewHostDelegate* render_view_delegate,
179 RenderWidgetHostDelegate* render_widget_delegate,
180 Delegate* delegate)
181 : frame_tree_node_(frame_tree_node),
182 delegate_(delegate),
183 render_frame_delegate_(render_frame_delegate),
184 render_view_delegate_(render_view_delegate),
185 render_widget_delegate_(render_widget_delegate),
186 proxy_hosts_(new RenderFrameProxyHostMap(this)),
187 interstitial_page_(nullptr),
188 should_reuse_web_ui_(false),
189 weak_factory_(this) {
190 DCHECK(frame_tree_node_);
193 RenderFrameHostManager::~RenderFrameHostManager() {
194 if (pending_render_frame_host_) {
195 scoped_ptr<RenderFrameHostImpl> relic = UnsetPendingRenderFrameHost();
196 ShutdownProxiesIfLastActiveFrameInSiteInstance(relic.get());
199 if (speculative_render_frame_host_) {
200 scoped_ptr<RenderFrameHostImpl> relic = UnsetSpeculativeRenderFrameHost();
201 ShutdownProxiesIfLastActiveFrameInSiteInstance(relic.get());
204 ShutdownProxiesIfLastActiveFrameInSiteInstance(render_frame_host_.get());
206 // Delete any RenderFrameProxyHosts and swapped out RenderFrameHosts.
207 // It is important to delete those prior to deleting the current
208 // RenderFrameHost, since the CrossProcessFrameConnector (owned by
209 // RenderFrameProxyHost) points to the RenderWidgetHostView associated with
210 // the current RenderFrameHost and uses it during its destructor.
211 ResetProxyHosts();
213 // Release the WebUI prior to resetting the current RenderFrameHost, as the
214 // WebUI accesses the RenderFrameHost during cleanup.
215 web_ui_.reset();
217 // We should always have a current RenderFrameHost except in some tests.
218 SetRenderFrameHost(scoped_ptr<RenderFrameHostImpl>());
221 void RenderFrameHostManager::Init(BrowserContext* browser_context,
222 SiteInstance* site_instance,
223 int view_routing_id,
224 int frame_routing_id) {
225 // Create a RenderViewHost and RenderFrameHost, once we have an instance. It
226 // is important to immediately give this SiteInstance to a RenderViewHost so
227 // that the SiteInstance is ref counted.
228 if (!site_instance)
229 site_instance = SiteInstance::Create(browser_context);
231 int flags = delegate_->IsHidden() ? CREATE_RF_HIDDEN : 0;
232 SetRenderFrameHost(CreateRenderFrameHost(site_instance, view_routing_id,
233 frame_routing_id, flags));
235 // Notify the delegate of the creation of the current RenderFrameHost.
236 // Do this only for subframes, as the main frame case is taken care of by
237 // WebContentsImpl::Init.
238 if (!frame_tree_node_->IsMainFrame()) {
239 delegate_->NotifySwappedFromRenderManager(
240 nullptr, render_frame_host_.get(), false);
244 RenderViewHostImpl* RenderFrameHostManager::current_host() const {
245 if (!render_frame_host_)
246 return nullptr;
247 return render_frame_host_->render_view_host();
250 RenderViewHostImpl* RenderFrameHostManager::pending_render_view_host() const {
251 if (!pending_render_frame_host_)
252 return nullptr;
253 return pending_render_frame_host_->render_view_host();
256 RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const {
257 if (interstitial_page_)
258 return interstitial_page_->GetView();
259 if (render_frame_host_)
260 return render_frame_host_->GetView();
261 return nullptr;
264 bool RenderFrameHostManager::ForInnerDelegate() {
265 // TODO(lazyboy): Subframes inside inner WebContents needs to be tested and
266 // we have to make sure that IsMainFrame() check below is appropriate. See
267 // http://crbug.com/500957.
268 return frame_tree_node_->IsMainFrame() &&
269 delegate_->GetOuterDelegateFrameTreeNodeID() !=
270 FrameTreeNode::kFrameTreeNodeInvalidID;
273 RenderWidgetHostImpl*
274 RenderFrameHostManager::GetOuterRenderWidgetHostForKeyboardInput() {
275 if (!ForInnerDelegate())
276 return nullptr;
278 FrameTreeNode* outer_contents_frame_tree_node =
279 FrameTreeNode::GloballyFindByID(
280 delegate_->GetOuterDelegateFrameTreeNodeID());
281 return outer_contents_frame_tree_node->parent()
282 ->current_frame_host()
283 ->render_view_host();
286 RenderFrameProxyHost* RenderFrameHostManager::GetProxyToParent() {
287 if (frame_tree_node_->IsMainFrame())
288 return nullptr;
290 return proxy_hosts_->Get(frame_tree_node_->parent()
291 ->render_manager()
292 ->current_frame_host()
293 ->GetSiteInstance()
294 ->GetId());
297 RenderFrameProxyHost* RenderFrameHostManager::GetProxyToOuterDelegate() {
298 int outer_contents_frame_tree_node_id =
299 delegate_->GetOuterDelegateFrameTreeNodeID();
300 FrameTreeNode* outer_contents_frame_tree_node =
301 FrameTreeNode::GloballyFindByID(outer_contents_frame_tree_node_id);
302 if (!outer_contents_frame_tree_node ||
303 !outer_contents_frame_tree_node->parent()) {
304 return nullptr;
307 return GetRenderFrameProxyHost(outer_contents_frame_tree_node->parent()
308 ->current_frame_host()
309 ->GetSiteInstance());
312 void RenderFrameHostManager::RemoveOuterDelegateFrame() {
313 FrameTreeNode* outer_delegate_frame_tree_node =
314 FrameTreeNode::GloballyFindByID(
315 delegate_->GetOuterDelegateFrameTreeNodeID());
316 DCHECK(outer_delegate_frame_tree_node->parent());
317 outer_delegate_frame_tree_node->frame_tree()->RemoveFrame(
318 outer_delegate_frame_tree_node);
321 void RenderFrameHostManager::SetPendingWebUI(const GURL& url, int bindings) {
322 pending_web_ui_ = CreateWebUI(url, bindings);
323 pending_and_current_web_ui_.reset();
326 scoped_ptr<WebUIImpl> RenderFrameHostManager::CreateWebUI(const GURL& url,
327 int bindings) {
328 scoped_ptr<WebUIImpl> new_web_ui(delegate_->CreateWebUIForRenderManager(url));
330 // If we have assigned (zero or more) bindings to this NavigationEntry in the
331 // past, make sure we're not granting it different bindings than it had
332 // before. If so, note it and don't give it any bindings, to avoid a
333 // potential privilege escalation.
334 if (new_web_ui && bindings != NavigationEntryImpl::kInvalidBindings &&
335 new_web_ui->GetBindings() != bindings) {
336 RecordAction(base::UserMetricsAction("ProcessSwapBindingsMismatch_RVHM"));
337 return nullptr;
339 return new_web_ui.Pass();
342 RenderFrameHostImpl* RenderFrameHostManager::Navigate(
343 const GURL& dest_url,
344 const FrameNavigationEntry& frame_entry,
345 const NavigationEntryImpl& entry) {
346 TRACE_EVENT1("navigation", "RenderFrameHostManager:Navigate",
347 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
348 // Create a pending RenderFrameHost to use for the navigation.
349 RenderFrameHostImpl* dest_render_frame_host = UpdateStateForNavigate(
350 dest_url,
351 // TODO(creis): Move source_site_instance to FNE.
352 entry.source_site_instance(), frame_entry.site_instance(),
353 entry.GetTransitionType(),
354 entry.restore_type() != NavigationEntryImpl::RESTORE_NONE,
355 entry.IsViewSourceMode(), entry.transferred_global_request_id(),
356 entry.bindings());
357 if (!dest_render_frame_host)
358 return nullptr; // We weren't able to create a pending render frame host.
360 // If the current render_frame_host_ isn't live, we should create it so
361 // that we don't show a sad tab while the dest_render_frame_host fetches
362 // its first page. (Bug 1145340)
363 if (dest_render_frame_host != render_frame_host_ &&
364 !render_frame_host_->IsRenderFrameLive()) {
365 // Note: we don't call InitRenderView here because we are navigating away
366 // soon anyway, and we don't have the NavigationEntry for this host.
367 delegate_->CreateRenderViewForRenderManager(
368 render_frame_host_->render_view_host(), MSG_ROUTING_NONE,
369 MSG_ROUTING_NONE, frame_tree_node_->current_replication_state(),
370 frame_tree_node_->IsMainFrame());
373 // If the renderer crashed, then try to create a new one to satisfy this
374 // navigation request.
375 if (!dest_render_frame_host->IsRenderFrameLive()) {
376 // Instruct the destination render frame host to set up a Mojo connection
377 // with the new render frame if necessary. Note that this call needs to
378 // occur before initializing the RenderView; the flow of creating the
379 // RenderView can cause browser-side code to execute that expects the this
380 // RFH's ServiceRegistry to be initialized (e.g., if the site is a WebUI
381 // site that is handled via Mojo, then Mojo WebUI code in //chrome will
382 // add a service to this RFH's ServiceRegistry).
383 dest_render_frame_host->SetUpMojoIfNeeded();
385 // Recreate the opener chain.
386 CreateOpenerProxiesIfNeeded(dest_render_frame_host->GetSiteInstance());
387 if (!InitRenderView(dest_render_frame_host->render_view_host(),
388 MSG_ROUTING_NONE,
389 frame_tree_node_->IsMainFrame()))
390 return nullptr;
392 // Now that we've created a new renderer, be sure to hide it if it isn't
393 // our primary one. Otherwise, we might crash if we try to call Show()
394 // on it later.
395 if (dest_render_frame_host != render_frame_host_) {
396 if (dest_render_frame_host->GetView())
397 dest_render_frame_host->GetView()->Hide();
398 } else {
399 // TODO(nasko): This is a very ugly hack. The Chrome extensions process
400 // manager still uses NotificationService and expects to see a
401 // RenderViewHost changed notification after WebContents and
402 // RenderFrameHostManager are completely initialized. This should be
403 // removed once the process manager moves away from NotificationService.
404 // See https://crbug.com/462682.
405 delegate_->NotifyMainFrameSwappedFromRenderManager(
406 nullptr, render_frame_host_->render_view_host());
410 // If entry includes the request ID of a request that is being transferred,
411 // the destination render frame will take ownership, so release ownership of
412 // the request.
413 if (cross_site_transferring_request_.get() &&
414 cross_site_transferring_request_->request_id() ==
415 entry.transferred_global_request_id()) {
416 cross_site_transferring_request_->ReleaseRequest();
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 // Sanity check that the params are for the correct frame and process.
564 // These should match the RenderFrameHost that made the request.
565 // If it started as a cross-process navigation via OpenURL, this is the
566 // pending one. If it wasn't cross-process until the transfer, this is the
567 // current one.
568 int render_frame_id = pending_render_frame_host_ ?
569 pending_render_frame_host_->GetRoutingID() :
570 render_frame_host_->GetRoutingID();
571 DCHECK_EQ(render_frame_id, pending_render_frame_host->GetRoutingID());
572 int process_id = pending_render_frame_host_ ?
573 pending_render_frame_host_->GetProcess()->GetID() :
574 render_frame_host_->GetProcess()->GetID();
575 DCHECK_EQ(process_id, global_request_id.child_id);
577 // Treat the last URL in the chain as the destination and the remainder as
578 // the redirect chain.
579 CHECK(transfer_url_chain.size());
580 GURL transfer_url = transfer_url_chain.back();
581 std::vector<GURL> rest_of_chain = transfer_url_chain;
582 rest_of_chain.pop_back();
584 // We don't know whether the original request had |user_action| set to true.
585 // However, since we force the navigation to be in the current tab, it
586 // doesn't matter.
587 pending_render_frame_host->frame_tree_node()->navigator()->RequestTransferURL(
588 pending_render_frame_host, transfer_url, nullptr, rest_of_chain, referrer,
589 page_transition, CURRENT_TAB, global_request_id,
590 should_replace_current_entry, true);
592 // The transferring request was only needed during the RequestTransferURL
593 // call, so it is safe to clear at this point.
594 cross_site_transferring_request_.reset();
597 void RenderFrameHostManager::DidNavigateFrame(
598 RenderFrameHostImpl* render_frame_host,
599 bool was_caused_by_user_gesture) {
600 CommitPendingIfNecessary(render_frame_host, was_caused_by_user_gesture);
602 // Make sure any dynamic changes to this frame's sandbox flags that were made
603 // prior to navigation take effect.
604 CommitPendingSandboxFlags();
607 void RenderFrameHostManager::CommitPendingIfNecessary(
608 RenderFrameHostImpl* render_frame_host,
609 bool was_caused_by_user_gesture) {
610 if (!pending_render_frame_host_ && !speculative_render_frame_host_) {
611 DCHECK_IMPLIES(should_reuse_web_ui_, web_ui_);
613 // We should only hear this from our current renderer.
614 DCHECK_EQ(render_frame_host_, render_frame_host);
616 // Even when there is no pending RVH, there may be a pending Web UI.
617 if (pending_web_ui() || speculative_web_ui_)
618 CommitPending();
619 return;
622 if (render_frame_host == pending_render_frame_host_ ||
623 render_frame_host == speculative_render_frame_host_) {
624 // The pending cross-process navigation completed, so show the renderer.
625 CommitPending();
626 } else if (render_frame_host == render_frame_host_) {
627 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
628 switches::kEnableBrowserSideNavigation)) {
629 CleanUpNavigation();
630 } else {
631 if (was_caused_by_user_gesture) {
632 // A navigation in the original page has taken place. Cancel the
633 // pending one. Only do it for user gesture originated navigations to
634 // prevent page doing any shenanigans to prevent user from navigating.
635 // See https://code.google.com/p/chromium/issues/detail?id=75195
636 CancelPending();
639 } else {
640 // No one else should be sending us DidNavigate in this state.
641 DCHECK(false);
645 void RenderFrameHostManager::DidDisownOpener(
646 RenderFrameHost* render_frame_host) {
647 // Notify all RenderFrameHosts but the one that notified us. This is necessary
648 // in case a process swap has occurred while the message was in flight.
649 for (const auto& pair : *proxy_hosts_) {
650 DCHECK_NE(pair.second->GetSiteInstance(),
651 current_frame_host()->GetSiteInstance());
652 pair.second->DisownOpener();
655 if (render_frame_host_.get() != render_frame_host)
656 render_frame_host_->DisownOpener();
658 if (pending_render_frame_host_ &&
659 pending_render_frame_host_.get() != render_frame_host) {
660 pending_render_frame_host_->DisownOpener();
664 void RenderFrameHostManager::CommitPendingSandboxFlags() {
665 // Return early if there were no pending sandbox flags updates.
666 if (!frame_tree_node_->CommitPendingSandboxFlags())
667 return;
669 // Sandbox flags updates can only happen when the frame has a parent.
670 CHECK(frame_tree_node_->parent());
672 // Notify all of the frame's proxies about updated sandbox flags, excluding
673 // the parent process since it already knows the latest flags.
674 SiteInstance* parent_site_instance =
675 frame_tree_node_->parent()->current_frame_host()->GetSiteInstance();
676 for (const auto& pair : *proxy_hosts_) {
677 if (pair.second->GetSiteInstance() != parent_site_instance) {
678 pair.second->Send(new FrameMsg_DidUpdateSandboxFlags(
679 pair.second->GetRoutingID(),
680 frame_tree_node_->current_replication_state().sandbox_flags));
685 void RenderFrameHostManager::RendererProcessClosing(
686 RenderProcessHost* render_process_host) {
687 // Remove any swapped out RVHs from this process, so that we don't try to
688 // swap them back in while the process is exiting. Start by finding them,
689 // since there could be more than one.
690 std::list<int> ids_to_remove;
691 // Do not remove proxies in the dead process that still have active frame
692 // count though, we just reset them to be uninitialized.
693 std::list<int> ids_to_keep;
694 for (const auto& pair : *proxy_hosts_) {
695 RenderFrameProxyHost* proxy = pair.second;
696 if (proxy->GetProcess() != render_process_host)
697 continue;
699 if (static_cast<SiteInstanceImpl*>(proxy->GetSiteInstance())
700 ->active_frame_count() >= 1U) {
701 ids_to_keep.push_back(pair.first);
702 } else {
703 ids_to_remove.push_back(pair.first);
707 // Now delete them.
708 while (!ids_to_remove.empty()) {
709 proxy_hosts_->Remove(ids_to_remove.back());
710 ids_to_remove.pop_back();
713 while (!ids_to_keep.empty()) {
714 frame_tree_node_->frame_tree()->ForEach(
715 base::Bind(
716 &RenderFrameHostManager::ResetProxiesInSiteInstance,
717 ids_to_keep.back()));
718 ids_to_keep.pop_back();
722 void RenderFrameHostManager::SwapOutOldFrame(
723 scoped_ptr<RenderFrameHostImpl> old_render_frame_host) {
724 TRACE_EVENT1("navigation", "RenderFrameHostManager::SwapOutOldFrame",
725 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
727 // Tell the renderer to suppress any further modal dialogs so that we can swap
728 // it out. This must be done before canceling any current dialog, in case
729 // there is a loop creating additional dialogs.
730 // TODO(creis): Handle modal dialogs in subframe processes.
731 old_render_frame_host->render_view_host()->SuppressDialogsUntilSwapOut();
733 // Now close any modal dialogs that would prevent us from swapping out. This
734 // must be done separately from SwapOut, so that the PageGroupLoadDeferrer is
735 // no longer on the stack when we send the SwapOut message.
736 delegate_->CancelModalDialogsForRenderManager();
738 // If the old RFH is not live, just return as there is no further work to do.
739 // It will be deleted and there will be no proxy created.
740 int32 old_site_instance_id =
741 old_render_frame_host->GetSiteInstance()->GetId();
742 if (!old_render_frame_host->IsRenderFrameLive()) {
743 ShutdownProxiesIfLastActiveFrameInSiteInstance(old_render_frame_host.get());
744 return;
747 // If there are no active frames besides this one, we can delete the old
748 // RenderFrameHost once it runs its unload handler, without replacing it with
749 // a proxy.
750 size_t active_frame_count =
751 old_render_frame_host->GetSiteInstance()->active_frame_count();
752 if (active_frame_count <= 1) {
753 // Clear out any proxies from this SiteInstance, in case this was the
754 // last one keeping other proxies alive.
755 ShutdownProxiesIfLastActiveFrameInSiteInstance(old_render_frame_host.get());
757 // Tell the old RenderFrameHost to swap out, with no proxy to replace it.
758 old_render_frame_host->SwapOut(nullptr, true);
759 MoveToPendingDeleteHosts(old_render_frame_host.Pass());
760 return;
763 // Otherwise there are active views and we need a proxy for the old RFH.
764 // (There should not be one yet.)
765 RenderFrameProxyHost* proxy = new RenderFrameProxyHost(
766 old_render_frame_host->GetSiteInstance(),
767 old_render_frame_host->render_view_host(), frame_tree_node_);
768 proxy_hosts_->Add(old_site_instance_id, make_scoped_ptr(proxy));
770 // Tell the old RenderFrameHost to swap out and be replaced by the proxy.
771 old_render_frame_host->SwapOut(proxy, true);
773 // SwapOut creates a RenderFrameProxy, so set the proxy to be initialized.
774 proxy->set_render_frame_proxy_created(true);
776 if (RenderFrameHostManager::IsSwappedOutStateForbidden()) {
777 // In --site-per-process, frames delete their RFH rather than storing it
778 // in the proxy. Schedule it for deletion once the SwapOutACK comes in.
779 // TODO(creis): This will be the default when we remove swappedout://.
780 MoveToPendingDeleteHosts(old_render_frame_host.Pass());
781 } else {
782 // We shouldn't get here for subframes, since we only swap subframes when
783 // --site-per-process is used.
784 DCHECK(frame_tree_node_->IsMainFrame());
786 // The old RenderFrameHost will stay alive inside the proxy so that existing
787 // JavaScript window references to it stay valid.
788 proxy->TakeFrameHostOwnership(old_render_frame_host.Pass());
792 void RenderFrameHostManager::DiscardUnusedFrame(
793 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
794 // TODO(carlosk): this code is very similar to what can be found in
795 // SwapOutOldFrame and we should see that these are unified at some point.
797 // If the SiteInstance for the pending RFH is being used by others don't
798 // delete the RFH. Just swap it out and it can be reused at a later point.
799 // In --site-per-process, RenderFrameHosts are not kept around and are
800 // deleted when not used, replaced by RenderFrameProxyHosts.
801 SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance();
802 if (site_instance->HasSite() && site_instance->active_frame_count() > 1) {
803 // Any currently suspended navigations are no longer needed.
804 render_frame_host->CancelSuspendedNavigations();
806 RenderFrameProxyHost* proxy = new RenderFrameProxyHost(
807 site_instance, render_frame_host->render_view_host(), frame_tree_node_);
808 proxy_hosts_->Add(site_instance->GetId(), make_scoped_ptr(proxy));
810 // Check if the RenderFrameHost is already swapped out, to avoid swapping it
811 // out again.
812 if (!render_frame_host->is_swapped_out())
813 render_frame_host->SwapOut(proxy, false);
815 if (!RenderFrameHostManager::IsSwappedOutStateForbidden()) {
816 DCHECK(frame_tree_node_->IsMainFrame());
817 proxy->TakeFrameHostOwnership(render_frame_host.Pass());
821 if (render_frame_host) {
822 // We won't be coming back, so delete this one.
823 ShutdownProxiesIfLastActiveFrameInSiteInstance(render_frame_host.get());
824 render_frame_host.reset();
828 void RenderFrameHostManager::MoveToPendingDeleteHosts(
829 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
830 // |render_frame_host| will be deleted when its SwapOut ACK is received, or
831 // when the timer times out, or when the RFHM itself is deleted (whichever
832 // comes first).
833 pending_delete_hosts_.push_back(
834 linked_ptr<RenderFrameHostImpl>(render_frame_host.release()));
837 bool RenderFrameHostManager::IsPendingDeletion(
838 RenderFrameHostImpl* render_frame_host) {
839 for (const auto& rfh : pending_delete_hosts_) {
840 if (rfh == render_frame_host)
841 return true;
843 return false;
846 bool RenderFrameHostManager::DeleteFromPendingList(
847 RenderFrameHostImpl* render_frame_host) {
848 for (RFHPendingDeleteList::iterator iter = pending_delete_hosts_.begin();
849 iter != pending_delete_hosts_.end();
850 iter++) {
851 if (*iter == render_frame_host) {
852 pending_delete_hosts_.erase(iter);
853 return true;
856 return false;
859 void RenderFrameHostManager::ResetProxyHosts() {
860 proxy_hosts_->Clear();
863 // PlzNavigate
864 void RenderFrameHostManager::DidCreateNavigationRequest(
865 const NavigationRequest& request) {
866 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
867 switches::kEnableBrowserSideNavigation));
868 // Clean up any state in case there's an ongoing navigation.
869 // TODO(carlosk): remove this cleanup here once we properly cancel ongoing
870 // navigations.
871 CleanUpNavigation();
873 RenderFrameHostImpl* dest_rfh = GetFrameHostForNavigation(request);
874 DCHECK(dest_rfh);
877 // PlzNavigate
878 RenderFrameHostImpl* RenderFrameHostManager::GetFrameHostForNavigation(
879 const NavigationRequest& request) {
880 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
881 switches::kEnableBrowserSideNavigation));
883 SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance();
885 SiteInstance* candidate_site_instance =
886 speculative_render_frame_host_
887 ? speculative_render_frame_host_->GetSiteInstance()
888 : nullptr;
890 scoped_refptr<SiteInstance> dest_site_instance = GetSiteInstanceForNavigation(
891 request.common_params().url, request.source_site_instance(),
892 request.dest_site_instance(), candidate_site_instance,
893 request.common_params().transition,
894 request.restore_type() != NavigationEntryImpl::RESTORE_NONE,
895 request.is_view_source());
897 // The appropriate RenderFrameHost to commit the navigation.
898 RenderFrameHostImpl* navigation_rfh = nullptr;
900 // Renderer-initiated main frame navigations that may require a SiteInstance
901 // swap are sent to the browser via the OpenURL IPC and are afterwards treated
902 // as browser-initiated navigations. NavigationRequests marked as
903 // renderer-initiated are created by receiving a BeginNavigation IPC, and will
904 // then proceed in the same renderer that sent the IPC due to the condition
905 // below.
906 // Subframe navigations will use the current renderer, unless
907 // --site-per-process is enabled.
908 // TODO(carlosk): Have renderer-initated main frame navigations swap processes
909 // if needed when it no longer breaks OAuth popups (see
910 // https://crbug.com/440266).
911 bool site_per_process = base::CommandLine::ForCurrentProcess()->HasSwitch(
912 switches::kSitePerProcess);
913 bool is_main_frame = frame_tree_node_->IsMainFrame();
914 if (current_site_instance == dest_site_instance.get() ||
915 (!request.browser_initiated() && is_main_frame) ||
916 (!is_main_frame && !site_per_process)) {
917 // Reuse the current RFH if its SiteInstance matches the the navigation's
918 // or if this is a subframe navigation. We only swap RFHs for subframes when
919 // --site-per-process is enabled.
920 CleanUpNavigation();
921 navigation_rfh = render_frame_host_.get();
923 // As SiteInstances are the same, check if the WebUI should be reused.
924 const NavigationEntry* current_navigation_entry =
925 delegate_->GetLastCommittedNavigationEntryForRenderManager();
926 should_reuse_web_ui_ = ShouldReuseWebUI(current_navigation_entry,
927 request.common_params().url);
928 if (!should_reuse_web_ui_) {
929 speculative_web_ui_ = CreateWebUI(request.common_params().url,
930 request.bindings());
931 // Make sure the current RenderViewHost has the right bindings.
932 if (speculative_web_ui() &&
933 !render_frame_host_->GetProcess()->IsForGuestsOnly()) {
934 render_frame_host_->render_view_host()->AllowBindings(
935 speculative_web_ui()->GetBindings());
938 } else {
939 // If the SiteInstance for the final URL doesn't match the one from the
940 // speculatively created RenderFrameHost, create a new RenderFrameHost using
941 // this new SiteInstance.
942 if (!speculative_render_frame_host_ ||
943 speculative_render_frame_host_->GetSiteInstance() !=
944 dest_site_instance.get()) {
945 CleanUpNavigation();
946 bool success = CreateSpeculativeRenderFrameHost(
947 request.common_params().url, current_site_instance,
948 dest_site_instance.get(), request.bindings());
949 DCHECK(success);
951 DCHECK(speculative_render_frame_host_);
952 navigation_rfh = speculative_render_frame_host_.get();
954 // Check if our current RFH is live.
955 if (!render_frame_host_->IsRenderFrameLive()) {
956 // The current RFH is not live. There's no reason to sit around with a
957 // sad tab or a newly created RFH while we wait for the navigation to
958 // complete. Just switch to the speculative RFH now and go back to normal.
959 // (Note that we don't care about on{before}unload handlers if the current
960 // RFH isn't live.)
961 CommitPending();
964 DCHECK(navigation_rfh &&
965 (navigation_rfh == render_frame_host_.get() ||
966 navigation_rfh == speculative_render_frame_host_.get()));
968 // If the RenderFrame that needs to navigate is not live (its process was just
969 // created or has crashed), initialize it.
970 if (!navigation_rfh->IsRenderFrameLive()) {
971 // Recreate the opener chain.
972 CreateOpenerProxiesIfNeeded(navigation_rfh->GetSiteInstance());
973 if (!InitRenderView(navigation_rfh->render_view_host(), MSG_ROUTING_NONE,
974 frame_tree_node_->IsMainFrame())) {
975 return nullptr;
978 if (navigation_rfh == render_frame_host_) {
979 // TODO(nasko): This is a very ugly hack. The Chrome extensions process
980 // manager still uses NotificationService and expects to see a
981 // RenderViewHost changed notification after WebContents and
982 // RenderFrameHostManager are completely initialized. This should be
983 // removed once the process manager moves away from NotificationService.
984 // See https://crbug.com/462682.
985 delegate_->NotifyMainFrameSwappedFromRenderManager(
986 nullptr, render_frame_host_->render_view_host());
990 return navigation_rfh;
993 // PlzNavigate
994 void RenderFrameHostManager::CleanUpNavigation() {
995 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
996 switches::kEnableBrowserSideNavigation));
997 speculative_web_ui_.reset();
998 should_reuse_web_ui_ = false;
999 if (speculative_render_frame_host_)
1000 DiscardUnusedFrame(UnsetSpeculativeRenderFrameHost());
1003 // PlzNavigate
1004 scoped_ptr<RenderFrameHostImpl>
1005 RenderFrameHostManager::UnsetSpeculativeRenderFrameHost() {
1006 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1007 switches::kEnableBrowserSideNavigation));
1008 speculative_render_frame_host_->GetProcess()->RemovePendingView();
1009 return speculative_render_frame_host_.Pass();
1012 void RenderFrameHostManager::OnDidStartLoading() {
1013 for (const auto& pair : *proxy_hosts_) {
1014 pair.second->Send(
1015 new FrameMsg_DidStartLoading(pair.second->GetRoutingID()));
1019 void RenderFrameHostManager::OnDidStopLoading() {
1020 for (const auto& pair : *proxy_hosts_) {
1021 pair.second->Send(new FrameMsg_DidStopLoading(pair.second->GetRoutingID()));
1025 void RenderFrameHostManager::OnDidUpdateName(const std::string& name) {
1026 // The window.name message may be sent outside of --site-per-process when
1027 // report_frame_name_changes renderer preference is set (used by
1028 // WebView). Don't send the update to proxies in those cases.
1029 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1030 switches::kSitePerProcess))
1031 return;
1033 for (const auto& pair : *proxy_hosts_) {
1034 pair.second->Send(
1035 new FrameMsg_DidUpdateName(pair.second->GetRoutingID(), name));
1039 void RenderFrameHostManager::OnDidUpdateOrigin(const url::Origin& origin) {
1040 if (!IsSwappedOutStateForbidden())
1041 return;
1043 for (const auto& pair : *proxy_hosts_) {
1044 pair.second->Send(
1045 new FrameMsg_DidUpdateOrigin(pair.second->GetRoutingID(), origin));
1049 RenderFrameHostManager::SiteInstanceDescriptor::SiteInstanceDescriptor(
1050 BrowserContext* browser_context,
1051 GURL dest_url,
1052 bool related_to_current)
1053 : existing_site_instance(nullptr),
1054 new_is_related_to_current(related_to_current) {
1055 new_site_url = SiteInstance::GetSiteForURL(browser_context, dest_url);
1058 // static
1059 bool RenderFrameHostManager::ClearProxiesInSiteInstance(
1060 int32 site_instance_id,
1061 FrameTreeNode* node) {
1062 RenderFrameProxyHost* proxy =
1063 node->render_manager()->proxy_hosts_->Get(site_instance_id);
1064 if (proxy) {
1065 // Delete the proxy. If it is for a main frame (and thus the RFH is stored
1066 // in the proxy) and it was still pending swap out, move the RFH to the
1067 // pending deletion list first.
1068 if (node->IsMainFrame() &&
1069 proxy->render_frame_host() &&
1070 proxy->render_frame_host()->rfh_state() ==
1071 RenderFrameHostImpl::STATE_PENDING_SWAP_OUT) {
1072 DCHECK(!RenderFrameHostManager::IsSwappedOutStateForbidden());
1073 scoped_ptr<RenderFrameHostImpl> swapped_out_rfh =
1074 proxy->PassFrameHostOwnership();
1075 node->render_manager()->MoveToPendingDeleteHosts(swapped_out_rfh.Pass());
1077 node->render_manager()->proxy_hosts_->Remove(site_instance_id);
1080 return true;
1083 // static.
1084 bool RenderFrameHostManager::ResetProxiesInSiteInstance(int32 site_instance_id,
1085 FrameTreeNode* node) {
1086 RenderFrameProxyHost* proxy =
1087 node->render_manager()->proxy_hosts_->Get(site_instance_id);
1088 if (proxy)
1089 proxy->set_render_frame_proxy_created(false);
1091 return true;
1094 bool RenderFrameHostManager::ShouldTransitionCrossSite() {
1095 // True for --site-per-process, which overrides both kSingleProcess and
1096 // kProcessPerTab.
1097 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1098 switches::kSitePerProcess))
1099 return true;
1101 // False in the single-process mode, as it makes RVHs to accumulate
1102 // in swapped_out_hosts_.
1103 // True if we are using process-per-site-instance (default) or
1104 // process-per-site (kProcessPerSite).
1105 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
1106 switches::kSingleProcess) &&
1107 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1108 switches::kProcessPerTab);
1111 bool RenderFrameHostManager::ShouldSwapBrowsingInstancesForNavigation(
1112 const GURL& current_effective_url,
1113 bool current_is_view_source_mode,
1114 SiteInstance* new_site_instance,
1115 const GURL& new_effective_url,
1116 bool new_is_view_source_mode) const {
1117 // If new_entry already has a SiteInstance, assume it is correct. We only
1118 // need to force a swap if it is in a different BrowsingInstance.
1119 if (new_site_instance) {
1120 return !new_site_instance->IsRelatedSiteInstance(
1121 render_frame_host_->GetSiteInstance());
1124 // Check for reasons to swap processes even if we are in a process model that
1125 // doesn't usually swap (e.g., process-per-tab). Any time we return true,
1126 // the new_entry will be rendered in a new SiteInstance AND BrowsingInstance.
1127 BrowserContext* browser_context =
1128 delegate_->GetControllerForRenderManager().GetBrowserContext();
1130 // Don't force a new BrowsingInstance for debug URLs that are handled in the
1131 // renderer process, like javascript: or chrome://crash.
1132 if (IsRendererDebugURL(new_effective_url))
1133 return false;
1135 // For security, we should transition between processes when one is a Web UI
1136 // page and one isn't.
1137 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1138 render_frame_host_->GetProcess()->GetID()) ||
1139 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1140 browser_context, current_effective_url)) {
1141 // If so, force a swap if destination is not an acceptable URL for Web UI.
1142 // Here, data URLs are never allowed.
1143 if (!WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
1144 browser_context, new_effective_url)) {
1145 return true;
1147 } else {
1148 // Force a swap if it's a Web UI URL.
1149 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1150 browser_context, new_effective_url)) {
1151 return true;
1155 // Check with the content client as well. Important to pass
1156 // current_effective_url here, which uses the SiteInstance's site if there is
1157 // no current_entry.
1158 if (GetContentClient()->browser()->ShouldSwapBrowsingInstancesForNavigation(
1159 render_frame_host_->GetSiteInstance(),
1160 current_effective_url, new_effective_url)) {
1161 return true;
1164 // We can't switch a RenderView between view source and non-view source mode
1165 // without screwing up the session history sometimes (when navigating between
1166 // "view-source:http://foo.com/" and "http://foo.com/", Blink doesn't treat
1167 // it as a new navigation). So require a BrowsingInstance switch.
1168 if (current_is_view_source_mode != new_is_view_source_mode)
1169 return true;
1171 return false;
1174 bool RenderFrameHostManager::ShouldReuseWebUI(
1175 const NavigationEntry* current_entry,
1176 const GURL& new_url) const {
1177 NavigationControllerImpl& controller =
1178 delegate_->GetControllerForRenderManager();
1179 return current_entry && web_ui_ &&
1180 (WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
1181 controller.GetBrowserContext(), current_entry->GetURL()) ==
1182 WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
1183 controller.GetBrowserContext(), new_url));
1186 SiteInstance* RenderFrameHostManager::GetSiteInstanceForNavigation(
1187 const GURL& dest_url,
1188 SiteInstance* source_instance,
1189 SiteInstance* dest_instance,
1190 SiteInstance* candidate_instance,
1191 ui::PageTransition transition,
1192 bool dest_is_restore,
1193 bool dest_is_view_source_mode) {
1194 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1196 // We do not currently swap processes for navigations in webview tag guests.
1197 if (current_instance->GetSiteURL().SchemeIs(kGuestScheme))
1198 return current_instance;
1200 // Determine if we need a new BrowsingInstance for this entry. If true, this
1201 // implies that it will get a new SiteInstance (and likely process), and that
1202 // other tabs in the current BrowsingInstance will be unable to script it.
1203 // This is used for cases that require a process swap even in the
1204 // process-per-tab model, such as WebUI pages.
1205 // TODO(clamy): Remove the dependency on the current entry.
1206 const NavigationEntry* current_entry =
1207 delegate_->GetLastCommittedNavigationEntryForRenderManager();
1208 BrowserContext* browser_context =
1209 delegate_->GetControllerForRenderManager().GetBrowserContext();
1210 const GURL& current_effective_url = current_entry ?
1211 SiteInstanceImpl::GetEffectiveURL(browser_context,
1212 current_entry->GetURL()) :
1213 render_frame_host_->GetSiteInstance()->GetSiteURL();
1214 bool current_is_view_source_mode = current_entry ?
1215 current_entry->IsViewSourceMode() : dest_is_view_source_mode;
1216 bool force_swap = ShouldSwapBrowsingInstancesForNavigation(
1217 current_effective_url,
1218 current_is_view_source_mode,
1219 dest_instance,
1220 SiteInstanceImpl::GetEffectiveURL(browser_context, dest_url),
1221 dest_is_view_source_mode);
1222 SiteInstanceDescriptor new_instance_descriptor =
1223 SiteInstanceDescriptor(current_instance);
1224 if (ShouldTransitionCrossSite() || force_swap) {
1225 new_instance_descriptor = DetermineSiteInstanceForURL(
1226 dest_url, source_instance, current_instance, dest_instance, transition,
1227 dest_is_restore, dest_is_view_source_mode, force_swap);
1230 SiteInstance* new_instance =
1231 ConvertToSiteInstance(new_instance_descriptor, candidate_instance);
1233 // If |force_swap| is true, we must use a different SiteInstance than the
1234 // current one. If we didn't, we would have two RenderFrameHosts in the same
1235 // SiteInstance and the same frame, resulting in page_id conflicts for their
1236 // NavigationEntries.
1237 if (force_swap)
1238 CHECK_NE(new_instance, current_instance);
1239 return new_instance;
1242 RenderFrameHostManager::SiteInstanceDescriptor
1243 RenderFrameHostManager::DetermineSiteInstanceForURL(
1244 const GURL& dest_url,
1245 SiteInstance* source_instance,
1246 SiteInstance* current_instance,
1247 SiteInstance* dest_instance,
1248 ui::PageTransition transition,
1249 bool dest_is_restore,
1250 bool dest_is_view_source_mode,
1251 bool force_browsing_instance_swap) {
1252 SiteInstanceImpl* current_instance_impl =
1253 static_cast<SiteInstanceImpl*>(current_instance);
1254 NavigationControllerImpl& controller =
1255 delegate_->GetControllerForRenderManager();
1256 BrowserContext* browser_context = controller.GetBrowserContext();
1258 // If the entry has an instance already we should use it.
1259 if (dest_instance) {
1260 // If we are forcing a swap, this should be in a different BrowsingInstance.
1261 if (force_browsing_instance_swap) {
1262 CHECK(!dest_instance->IsRelatedSiteInstance(
1263 render_frame_host_->GetSiteInstance()));
1265 return SiteInstanceDescriptor(dest_instance);
1268 // If a swap is required, we need to force the SiteInstance AND
1269 // BrowsingInstance to be different ones, using CreateForURL.
1270 if (force_browsing_instance_swap)
1271 return SiteInstanceDescriptor(browser_context, dest_url, false);
1273 // (UGLY) HEURISTIC, process-per-site only:
1275 // If this navigation is generated, then it probably corresponds to a search
1276 // query. Given that search results typically lead to users navigating to
1277 // other sites, we don't really want to use the search engine hostname to
1278 // determine the site instance for this navigation.
1280 // NOTE: This can be removed once we have a way to transition between
1281 // RenderViews in response to a link click.
1283 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1284 switches::kProcessPerSite) &&
1285 ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_GENERATED)) {
1286 return SiteInstanceDescriptor(current_instance_impl);
1289 // If we haven't used our SiteInstance (and thus RVH) yet, then we can use it
1290 // for this entry. We won't commit the SiteInstance to this site until the
1291 // navigation commits (in DidNavigate), unless the navigation entry was
1292 // restored or it's a Web UI as described below.
1293 if (!current_instance_impl->HasSite()) {
1294 // If we've already created a SiteInstance for our destination, we don't
1295 // want to use this unused SiteInstance; use the existing one. (We don't
1296 // do this check if the current_instance has a site, because for now, we
1297 // want to compare against the current URL and not the SiteInstance's site.
1298 // In this case, there is no current URL, so comparing against the site is
1299 // ok. See additional comments below.)
1301 // Also, if the URL should use process-per-site mode and there is an
1302 // existing process for the site, we should use it. We can call
1303 // GetRelatedSiteInstance() for this, which will eagerly set the site and
1304 // thus use the correct process.
1305 bool use_process_per_site =
1306 RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) &&
1307 RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url);
1308 if (current_instance_impl->HasRelatedSiteInstance(dest_url) ||
1309 use_process_per_site) {
1310 return SiteInstanceDescriptor(browser_context, dest_url, true);
1313 // For extensions, Web UI URLs (such as the new tab page), and apps we do
1314 // not want to use the |current_instance_impl| if it has no site, since it
1315 // will have a RenderProcessHost of PRIV_NORMAL. Create a new SiteInstance
1316 // for this URL instead (with the correct process type).
1317 if (current_instance_impl->HasWrongProcessForURL(dest_url))
1318 return SiteInstanceDescriptor(browser_context, dest_url, true);
1320 // View-source URLs must use a new SiteInstance and BrowsingInstance.
1321 // TODO(nasko): This is the same condition as later in the function. This
1322 // should be taken into account when refactoring this method as part of
1323 // http://crbug.com/123007.
1324 if (dest_is_view_source_mode)
1325 return SiteInstanceDescriptor(browser_context, dest_url, false);
1327 // If we are navigating from a blank SiteInstance to a WebUI, make sure we
1328 // create a new SiteInstance.
1329 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1330 browser_context, dest_url)) {
1331 return SiteInstanceDescriptor(browser_context, dest_url, false);
1334 // Normally the "site" on the SiteInstance is set lazily when the load
1335 // actually commits. This is to support better process sharing in case
1336 // the site redirects to some other site: we want to use the destination
1337 // site in the site instance.
1339 // In the case of session restore, as it loads all the pages immediately
1340 // we need to set the site first, otherwise after a restore none of the
1341 // pages would share renderers in process-per-site.
1343 // The embedder can request some urls never to be assigned to SiteInstance
1344 // through the ShouldAssignSiteForURL() content client method, so that
1345 // renderers created for particular chrome urls (e.g. the chrome-native://
1346 // scheme) can be reused for subsequent navigations in the same WebContents.
1347 // See http://crbug.com/386542.
1348 if (dest_is_restore &&
1349 GetContentClient()->browser()->ShouldAssignSiteForURL(dest_url)) {
1350 current_instance_impl->SetSite(dest_url);
1353 return SiteInstanceDescriptor(current_instance_impl);
1356 // Otherwise, only create a new SiteInstance for a cross-process navigation.
1358 // TODO(creis): Once we intercept links and script-based navigations, we
1359 // will be able to enforce that all entries in a SiteInstance actually have
1360 // the same site, and it will be safe to compare the URL against the
1361 // SiteInstance's site, as follows:
1362 // const GURL& current_url = current_instance_impl->site();
1363 // For now, though, we're in a hybrid model where you only switch
1364 // SiteInstances if you type in a cross-site URL. This means we have to
1365 // compare the entry's URL to the last committed entry's URL.
1366 NavigationEntry* current_entry = controller.GetLastCommittedEntry();
1367 if (interstitial_page_) {
1368 // The interstitial is currently the last committed entry, but we want to
1369 // compare against the last non-interstitial entry.
1370 current_entry = controller.GetEntryAtOffset(-1);
1373 // View-source URLs must use a new SiteInstance and BrowsingInstance.
1374 // We don't need a swap when going from view-source to a debug URL like
1375 // chrome://crash, however.
1376 // TODO(creis): Refactor this method so this duplicated code isn't needed.
1377 // See http://crbug.com/123007.
1378 if (current_entry &&
1379 current_entry->IsViewSourceMode() != dest_is_view_source_mode &&
1380 !IsRendererDebugURL(dest_url)) {
1381 return SiteInstanceDescriptor(browser_context, dest_url, false);
1384 // Use the source SiteInstance in case of data URLs or about:blank pages,
1385 // because the content is then controlled and/or scriptable by the source
1386 // SiteInstance.
1387 GURL about_blank(url::kAboutBlankURL);
1388 if (source_instance &&
1389 (dest_url == about_blank || dest_url.scheme() == url::kDataScheme)) {
1390 return SiteInstanceDescriptor(source_instance);
1393 // Use the current SiteInstance for same site navigations, as long as the
1394 // process type is correct. (The URL may have been installed as an app since
1395 // the last time we visited it.)
1396 const GURL& current_url =
1397 GetCurrentURLForSiteInstance(current_instance_impl, current_entry);
1398 if (SiteInstance::IsSameWebSite(browser_context, current_url, dest_url) &&
1399 !current_instance_impl->HasWrongProcessForURL(dest_url)) {
1400 return SiteInstanceDescriptor(current_instance_impl);
1403 // Start the new renderer in a new SiteInstance, but in the current
1404 // BrowsingInstance. It is important to immediately give this new
1405 // SiteInstance to a RenderViewHost (if it is different than our current
1406 // SiteInstance), so that it is ref counted. This will happen in
1407 // CreateRenderView.
1408 return SiteInstanceDescriptor(browser_context, dest_url, true);
1411 SiteInstance* RenderFrameHostManager::ConvertToSiteInstance(
1412 const SiteInstanceDescriptor& descriptor,
1413 SiteInstance* candidate_instance) {
1414 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1416 // Note: If the |candidate_instance| matches the descriptor, it will already
1417 // be set to |descriptor.existing_site_instance|.
1418 if (descriptor.existing_site_instance)
1419 return descriptor.existing_site_instance;
1421 // Note: If the |candidate_instance| matches the descriptor,
1422 // GetRelatedSiteInstance will return it.
1423 if (descriptor.new_is_related_to_current)
1424 return current_instance->GetRelatedSiteInstance(descriptor.new_site_url);
1426 // At this point we know an unrelated site instance must be returned. First
1427 // check if the candidate matches.
1428 if (candidate_instance &&
1429 !current_instance->IsRelatedSiteInstance(candidate_instance) &&
1430 candidate_instance->GetSiteURL() == descriptor.new_site_url) {
1431 return candidate_instance;
1434 // Otherwise return a newly created one.
1435 return SiteInstance::CreateForURL(
1436 delegate_->GetControllerForRenderManager().GetBrowserContext(),
1437 descriptor.new_site_url);
1440 const GURL& RenderFrameHostManager::GetCurrentURLForSiteInstance(
1441 SiteInstance* current_instance, NavigationEntry* current_entry) {
1442 // If this is a subframe that is potentially out of process from its parent,
1443 // don't consider using current_entry's url for SiteInstance selection, since
1444 // current_entry's url is for the main frame and may be in a different site
1445 // than this frame.
1446 // TODO(creis): Remove this when we can check the FrameNavigationEntry's url.
1447 // See http://crbug.com/369654
1448 if (!frame_tree_node_->IsMainFrame() &&
1449 base::CommandLine::ForCurrentProcess()->HasSwitch(
1450 switches::kSitePerProcess))
1451 return frame_tree_node_->current_url();
1453 // If there is no last non-interstitial entry (and current_instance already
1454 // has a site), then we must have been opened from another tab. We want
1455 // to compare against the URL of the page that opened us, but we can't
1456 // get to it directly. The best we can do is check against the site of
1457 // the SiteInstance. This will be correct when we intercept links and
1458 // script-based navigations, but for now, it could place some pages in a
1459 // new process unnecessarily. We should only hit this case if a page tries
1460 // to open a new tab to an interstitial-inducing URL, and then navigates
1461 // the page to a different same-site URL. (This seems very unlikely in
1462 // practice.)
1463 if (current_entry)
1464 return current_entry->GetURL();
1465 return current_instance->GetSiteURL();
1468 void RenderFrameHostManager::CreatePendingRenderFrameHost(
1469 SiteInstance* old_instance,
1470 SiteInstance* new_instance,
1471 bool is_main_frame) {
1472 int create_render_frame_flags = 0;
1473 if (is_main_frame)
1474 create_render_frame_flags |= CREATE_RF_FOR_MAIN_FRAME_NAVIGATION;
1476 if (delegate_->IsHidden())
1477 create_render_frame_flags |= CREATE_RF_HIDDEN;
1479 if (pending_render_frame_host_)
1480 CancelPending();
1482 // The process for the new SiteInstance may (if we're sharing a process with
1483 // another host that already initialized it) or may not (we have our own
1484 // process or the existing process crashed) have been initialized. Calling
1485 // Init multiple times will be ignored, so this is safe.
1486 if (!new_instance->GetProcess()->Init())
1487 return;
1489 CreateProxiesForNewRenderFrameHost(old_instance, new_instance,
1490 &create_render_frame_flags);
1492 // Create a non-swapped-out RFH with the given opener.
1493 pending_render_frame_host_ = CreateRenderFrame(
1494 new_instance, pending_web_ui(), create_render_frame_flags, nullptr);
1497 void RenderFrameHostManager::CreateProxiesForNewRenderFrameHost(
1498 SiteInstance* old_instance,
1499 SiteInstance* new_instance,
1500 int* create_render_frame_flags) {
1501 // Only create opener proxies if they are in the same BrowsingInstance.
1502 if (new_instance->IsRelatedSiteInstance(old_instance))
1503 CreateOpenerProxiesIfNeeded(new_instance);
1504 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1505 switches::kSitePerProcess)) {
1506 // Ensure that the frame tree has RenderFrameProxyHosts for the new
1507 // SiteInstance in all nodes except the current one. We do this for all
1508 // frames in the tree, whether they are in the same BrowsingInstance or not.
1509 // We will still check whether two frames are in the same BrowsingInstance
1510 // before we allow them to interact (e.g., postMessage).
1511 frame_tree_node_->frame_tree()->CreateProxiesForSiteInstance(
1512 frame_tree_node_, new_instance);
1513 // RenderFrames in different processes from their parent RenderFrames
1514 // in the frame tree require RenderWidgets for rendering and processing
1515 // input events.
1516 if (frame_tree_node_->parent() &&
1517 frame_tree_node_->parent()->current_frame_host()->GetSiteInstance() !=
1518 new_instance)
1519 *create_render_frame_flags |= CREATE_RF_NEEDS_RENDER_WIDGET_HOST;
1523 void RenderFrameHostManager::CreateProxiesForNewNamedFrame() {
1524 // TODO(alexmos): use SiteIsolationPolicy::AreCrossProcessFramesPossible once
1525 // https://codereview.chromium.org/1208143002/ lands.
1526 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1527 switches::kSitePerProcess))
1528 return;
1530 DCHECK(!frame_tree_node_->frame_name().empty());
1532 // If this is a top-level frame, create proxies for this node in the
1533 // SiteInstances of its opener's ancestors, which are allowed to discover
1534 // this frame by name (see https://crbug.com/511474 and part 4 of
1535 // https://html.spec.whatwg.org/#the-rules-for-choosing-a-browsing-context-
1536 // given-a-browsing-context-name).
1537 FrameTreeNode* opener = frame_tree_node_->opener();
1538 if (!opener || !frame_tree_node_->IsMainFrame())
1539 return;
1540 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1542 // Start from opener's parent. There's no need to create a proxy in the
1543 // opener's SiteInstance, since new windows are always first opened in the
1544 // same SiteInstance as their opener, and if the new window navigates
1545 // cross-site, that proxy would be created as part of swapping out.
1546 for (FrameTreeNode* ancestor = opener->parent(); ancestor;
1547 ancestor = ancestor->parent()) {
1548 RenderFrameHostImpl* ancestor_rfh = ancestor->current_frame_host();
1549 if (ancestor_rfh->GetSiteInstance() != current_instance)
1550 CreateRenderFrameProxy(ancestor_rfh->GetSiteInstance());
1554 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::CreateRenderFrameHost(
1555 SiteInstance* site_instance,
1556 int view_routing_id,
1557 int frame_routing_id,
1558 int flags) {
1559 if (frame_routing_id == MSG_ROUTING_NONE)
1560 frame_routing_id = site_instance->GetProcess()->GetNextRoutingID();
1562 bool swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
1563 bool hidden = !!(flags & CREATE_RF_HIDDEN);
1565 // Create a RVH for main frames, or find the existing one for subframes.
1566 FrameTree* frame_tree = frame_tree_node_->frame_tree();
1567 RenderViewHostImpl* render_view_host = nullptr;
1568 if (frame_tree_node_->IsMainFrame()) {
1569 render_view_host = frame_tree->CreateRenderViewHost(
1570 site_instance, view_routing_id, frame_routing_id, swapped_out, hidden);
1571 } else {
1572 render_view_host = frame_tree->GetRenderViewHost(site_instance);
1574 CHECK(render_view_host);
1577 // TODO(creis): Pass hidden to RFH.
1578 scoped_ptr<RenderFrameHostImpl> render_frame_host = make_scoped_ptr(
1579 RenderFrameHostFactory::Create(
1580 site_instance, render_view_host, render_frame_delegate_,
1581 render_widget_delegate_, frame_tree, frame_tree_node_,
1582 frame_routing_id, flags).release());
1583 return render_frame_host.Pass();
1586 // PlzNavigate
1587 bool RenderFrameHostManager::CreateSpeculativeRenderFrameHost(
1588 const GURL& url,
1589 SiteInstance* old_instance,
1590 SiteInstance* new_instance,
1591 int bindings) {
1592 CHECK(new_instance);
1593 CHECK_NE(old_instance, new_instance);
1594 CHECK(!should_reuse_web_ui_);
1596 // Note: |speculative_web_ui_| must be initialized before starting the
1597 // |speculative_render_frame_host_| creation steps otherwise the WebUI
1598 // won't be properly initialized.
1599 speculative_web_ui_ = CreateWebUI(url, bindings);
1601 // The process for the new SiteInstance may (if we're sharing a process with
1602 // another host that already initialized it) or may not (we have our own
1603 // process or the existing process crashed) have been initialized. Calling
1604 // Init multiple times will be ignored, so this is safe.
1605 if (!new_instance->GetProcess()->Init())
1606 return false;
1608 int create_render_frame_flags = 0;
1609 CreateProxiesForNewRenderFrameHost(old_instance, new_instance,
1610 &create_render_frame_flags);
1612 if (frame_tree_node_->IsMainFrame())
1613 create_render_frame_flags |= CREATE_RF_FOR_MAIN_FRAME_NAVIGATION;
1614 if (delegate_->IsHidden())
1615 create_render_frame_flags |= CREATE_RF_HIDDEN;
1616 speculative_render_frame_host_ =
1617 CreateRenderFrame(new_instance, speculative_web_ui_.get(),
1618 create_render_frame_flags, nullptr);
1620 if (!speculative_render_frame_host_) {
1621 speculative_web_ui_.reset();
1622 return false;
1624 return true;
1627 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::CreateRenderFrame(
1628 SiteInstance* instance,
1629 WebUIImpl* web_ui,
1630 int flags,
1631 int* view_routing_id_ptr) {
1632 bool swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
1633 bool swapped_out_forbidden = IsSwappedOutStateForbidden();
1634 bool is_site_per_process = base::CommandLine::ForCurrentProcess()->HasSwitch(
1635 switches::kSitePerProcess);
1637 CHECK(instance);
1638 CHECK_IMPLIES(swapped_out_forbidden, !swapped_out);
1639 CHECK_IMPLIES(!is_site_per_process, frame_tree_node_->IsMainFrame());
1641 // Swapped out views should always be hidden.
1642 DCHECK_IMPLIES(swapped_out, (flags & CREATE_RF_HIDDEN));
1644 scoped_ptr<RenderFrameHostImpl> new_render_frame_host;
1645 bool success = true;
1646 if (view_routing_id_ptr)
1647 *view_routing_id_ptr = MSG_ROUTING_NONE;
1649 // We are creating a pending, speculative or swapped out RFH here. We should
1650 // never create it in the same SiteInstance as our current RFH.
1651 CHECK_NE(render_frame_host_->GetSiteInstance(), instance);
1653 // Check if we've already created an RFH for this SiteInstance. If so, try
1654 // to re-use the existing one, which has already been initialized. We'll
1655 // remove it from the list of proxy hosts below if it will be active.
1656 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1657 if (proxy && proxy->render_frame_host()) {
1658 CHECK(!swapped_out_forbidden);
1659 if (view_routing_id_ptr)
1660 *view_routing_id_ptr = proxy->GetRenderViewHost()->GetRoutingID();
1661 // Delete the existing RenderFrameProxyHost, but reuse the RenderFrameHost.
1662 // Prevent the process from exiting while we're trying to use it.
1663 if (!swapped_out) {
1664 new_render_frame_host = proxy->PassFrameHostOwnership();
1665 new_render_frame_host->GetProcess()->AddPendingView();
1667 proxy_hosts_->Remove(instance->GetId());
1668 // NB |proxy| is deleted at this point.
1670 } else {
1671 // Create a new RenderFrameHost if we don't find an existing one.
1672 new_render_frame_host = CreateRenderFrameHost(instance, MSG_ROUTING_NONE,
1673 MSG_ROUTING_NONE, flags);
1674 RenderViewHostImpl* render_view_host =
1675 new_render_frame_host->render_view_host();
1676 int proxy_routing_id = MSG_ROUTING_NONE;
1678 // Prevent the process from exiting while we're trying to navigate in it.
1679 // Otherwise, if the new RFH is swapped out already, store it.
1680 if (!swapped_out) {
1681 new_render_frame_host->GetProcess()->AddPendingView();
1682 } else {
1683 proxy = new RenderFrameProxyHost(
1684 new_render_frame_host->GetSiteInstance(),
1685 new_render_frame_host->render_view_host(), frame_tree_node_);
1686 proxy_hosts_->Add(instance->GetId(), make_scoped_ptr(proxy));
1687 proxy_routing_id = proxy->GetRoutingID();
1688 proxy->TakeFrameHostOwnership(new_render_frame_host.Pass());
1691 success = InitRenderView(render_view_host, proxy_routing_id,
1692 !!(flags & CREATE_RF_FOR_MAIN_FRAME_NAVIGATION));
1693 if (success) {
1694 // Remember that InitRenderView also created the RenderFrameProxy.
1695 if (swapped_out)
1696 proxy->set_render_frame_proxy_created(true);
1697 if (frame_tree_node_->IsMainFrame()) {
1698 // Don't show the main frame's view until we get a DidNavigate from it.
1699 // Only the RenderViewHost for the top-level RenderFrameHost has a
1700 // RenderWidgetHostView; RenderWidgetHosts for out-of-process iframes
1701 // will be created later and hidden.
1702 if (render_view_host->GetView())
1703 render_view_host->GetView()->Hide();
1705 // RenderViewHost for |instance| might exist prior to calling
1706 // CreateRenderFrame. In such a case, InitRenderView will not create the
1707 // RenderFrame in the renderer process and it needs to be done
1708 // explicitly.
1709 if (swapped_out_forbidden) {
1710 // Init the RFH, so a RenderFrame is created in the renderer.
1711 DCHECK(new_render_frame_host);
1712 success = InitRenderFrame(new_render_frame_host.get());
1716 if (success) {
1717 if (view_routing_id_ptr)
1718 *view_routing_id_ptr = render_view_host->GetRoutingID();
1722 // When a new RenderView is created by the renderer process, the new
1723 // WebContents gets a RenderViewHost in the SiteInstance of its opener
1724 // WebContents. If not used in the first navigation, this RVH is swapped out
1725 // and is not granted bindings, so we may need to grant them when swapping it
1726 // in.
1727 if (web_ui && !new_render_frame_host->GetProcess()->IsForGuestsOnly()) {
1728 int required_bindings = web_ui->GetBindings();
1729 RenderViewHost* render_view_host =
1730 new_render_frame_host->render_view_host();
1731 if ((render_view_host->GetEnabledBindings() & required_bindings) !=
1732 required_bindings) {
1733 render_view_host->AllowBindings(required_bindings);
1737 // Returns the new RFH if it isn't swapped out.
1738 if (success && !swapped_out) {
1739 DCHECK(new_render_frame_host->GetSiteInstance() == instance);
1740 return new_render_frame_host.Pass();
1742 return nullptr;
1745 int RenderFrameHostManager::CreateRenderFrameProxy(SiteInstance* instance) {
1746 // A RenderFrameProxyHost should never be created in the same SiteInstance as
1747 // the current RFH.
1748 CHECK(instance);
1749 CHECK_NE(instance, render_frame_host_->GetSiteInstance());
1751 RenderViewHostImpl* render_view_host = nullptr;
1753 // Ensure a RenderViewHost exists for |instance|, as it creates the page
1754 // level structure in Blink.
1755 if (RenderFrameHostManager::IsSwappedOutStateForbidden()) {
1756 render_view_host =
1757 frame_tree_node_->frame_tree()->GetRenderViewHost(instance);
1758 if (!render_view_host) {
1759 CHECK(frame_tree_node_->IsMainFrame());
1760 render_view_host = frame_tree_node_->frame_tree()->CreateRenderViewHost(
1761 instance, MSG_ROUTING_NONE, MSG_ROUTING_NONE, true, true);
1765 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1766 if (proxy && proxy->is_render_frame_proxy_live())
1767 return proxy->GetRoutingID();
1769 if (!proxy) {
1770 proxy =
1771 new RenderFrameProxyHost(instance, render_view_host, frame_tree_node_);
1772 proxy_hosts_->Add(instance->GetId(), make_scoped_ptr(proxy));
1775 if (RenderFrameHostManager::IsSwappedOutStateForbidden() &&
1776 frame_tree_node_->IsMainFrame()) {
1777 InitRenderView(render_view_host, proxy->GetRoutingID(), true);
1778 proxy->set_render_frame_proxy_created(true);
1779 } else {
1780 proxy->InitRenderFrameProxy();
1783 return proxy->GetRoutingID();
1786 void RenderFrameHostManager::CreateProxiesForChildFrame(FrameTreeNode* child) {
1787 for (const auto& pair : *proxy_hosts_) {
1788 child->render_manager()->CreateRenderFrameProxy(
1789 pair.second->GetSiteInstance());
1793 void RenderFrameHostManager::EnsureRenderViewInitialized(
1794 RenderViewHostImpl* render_view_host,
1795 SiteInstance* instance) {
1796 DCHECK(frame_tree_node_->IsMainFrame());
1798 if (render_view_host->IsRenderViewLive())
1799 return;
1801 // Recreate the opener chain.
1802 CreateOpenerProxiesIfNeeded(instance);
1804 // If the proxy in |instance| doesn't exist, this RenderView is not swapped
1805 // out and shouldn't be reinitialized here.
1806 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1807 if (!proxy)
1808 return;
1810 InitRenderView(render_view_host, proxy->GetRoutingID(), false);
1811 proxy->set_render_frame_proxy_created(true);
1814 void RenderFrameHostManager::CreateOuterDelegateProxy(
1815 SiteInstance* outer_contents_site_instance,
1816 RenderFrameHostImpl* render_frame_host) {
1817 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1818 switches::kSitePerProcess));
1819 RenderFrameProxyHost* proxy = new RenderFrameProxyHost(
1820 outer_contents_site_instance, nullptr, frame_tree_node_);
1821 proxy_hosts_->Add(outer_contents_site_instance->GetId(),
1822 make_scoped_ptr(proxy));
1824 // Swap the outer WebContents's frame with the proxy to inner WebContents.
1826 // We are in the outer WebContents, and its FrameTree would never see
1827 // a load start for any of its inner WebContents. Eventually, that also makes
1828 // the FrameTree never see the matching load stop. Therefore, we always pass
1829 // false to |is_loading| below.
1830 // TODO(lazyboy): This |is_loading| behavior might not be what we want,
1831 // investigate and fix.
1832 render_frame_host->Send(new FrameMsg_SwapOut(
1833 render_frame_host->GetRoutingID(), proxy->GetRoutingID(),
1834 false /* is_loading */, FrameReplicationState()));
1835 proxy->set_render_frame_proxy_created(true);
1838 void RenderFrameHostManager::SetRWHViewForInnerContents(
1839 RenderWidgetHostView* child_rwhv) {
1840 DCHECK(ForInnerDelegate());
1841 GetProxyToOuterDelegate()->SetChildRWHView(child_rwhv);
1844 bool RenderFrameHostManager::InitRenderView(
1845 RenderViewHostImpl* render_view_host,
1846 int proxy_routing_id,
1847 bool for_main_frame_navigation) {
1848 // Ensure the renderer process is initialized before creating the
1849 // RenderView.
1850 if (!render_view_host->GetProcess()->Init())
1851 return false;
1853 // We may have initialized this RenderViewHost for another RenderFrameHost.
1854 if (render_view_host->IsRenderViewLive())
1855 return true;
1857 // If the ongoing navigation is to a WebUI and the RenderView is not in a
1858 // guest process, tell the RenderViewHost about any bindings it will need
1859 // enabled.
1860 WebUIImpl* dest_web_ui = nullptr;
1861 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1862 switches::kEnableBrowserSideNavigation)) {
1863 dest_web_ui =
1864 should_reuse_web_ui_ ? web_ui_.get() : speculative_web_ui_.get();
1865 } else {
1866 dest_web_ui = pending_web_ui();
1868 if (dest_web_ui && !render_view_host->GetProcess()->IsForGuestsOnly()) {
1869 render_view_host->AllowBindings(dest_web_ui->GetBindings());
1870 } else {
1871 // Ensure that we don't create an unprivileged RenderView in a WebUI-enabled
1872 // process unless it's swapped out.
1873 if (render_view_host->is_active()) {
1874 CHECK(!ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1875 render_view_host->GetProcess()->GetID()));
1879 int opener_frame_routing_id =
1880 GetOpenerRoutingID(render_view_host->GetSiteInstance());
1882 return delegate_->CreateRenderViewForRenderManager(
1883 render_view_host, opener_frame_routing_id, proxy_routing_id,
1884 frame_tree_node_->current_replication_state(), for_main_frame_navigation);
1887 bool RenderFrameHostManager::InitRenderFrame(
1888 RenderFrameHostImpl* render_frame_host) {
1889 if (render_frame_host->IsRenderFrameLive())
1890 return true;
1892 int parent_routing_id = MSG_ROUTING_NONE;
1893 int previous_sibling_routing_id = MSG_ROUTING_NONE;
1894 int proxy_routing_id = MSG_ROUTING_NONE;
1896 if (frame_tree_node_->parent()) {
1897 parent_routing_id = frame_tree_node_->parent()->render_manager()->
1898 GetRoutingIdForSiteInstance(render_frame_host->GetSiteInstance());
1899 CHECK_NE(parent_routing_id, MSG_ROUTING_NONE);
1902 // At this point, all RenderFrameProxies for sibling frames have already been
1903 // created, including any proxies that come after this frame. To preserve
1904 // correct order for indexed window access (e.g., window.frames[1]), pass the
1905 // previous sibling frame so that this frame is correctly inserted into the
1906 // frame tree on the renderer side.
1907 FrameTreeNode* previous_sibling = frame_tree_node_->PreviousSibling();
1908 if (previous_sibling) {
1909 previous_sibling_routing_id =
1910 previous_sibling->render_manager()->GetRoutingIdForSiteInstance(
1911 render_frame_host->GetSiteInstance());
1912 CHECK_NE(previous_sibling_routing_id, MSG_ROUTING_NONE);
1915 // Check whether there is an existing proxy for this frame in this
1916 // SiteInstance. If there is, the new RenderFrame needs to be able to find
1917 // the proxy it is replacing, so that it can fully initialize itself.
1918 // NOTE: This is the only time that a RenderFrameProxyHost can be in the same
1919 // SiteInstance as its RenderFrameHost. This is only the case until the
1920 // RenderFrameHost commits, at which point it will replace and delete the
1921 // RenderFrameProxyHost.
1922 RenderFrameProxyHost* existing_proxy =
1923 GetRenderFrameProxyHost(render_frame_host->GetSiteInstance());
1924 if (existing_proxy) {
1925 proxy_routing_id = existing_proxy->GetRoutingID();
1926 CHECK_NE(proxy_routing_id, MSG_ROUTING_NONE);
1927 if (!existing_proxy->is_render_frame_proxy_live())
1928 existing_proxy->InitRenderFrameProxy();
1930 return delegate_->CreateRenderFrameForRenderManager(
1931 render_frame_host, parent_routing_id, previous_sibling_routing_id,
1932 proxy_routing_id);
1935 int RenderFrameHostManager::GetRoutingIdForSiteInstance(
1936 SiteInstance* site_instance) {
1937 if (render_frame_host_->GetSiteInstance() == site_instance)
1938 return render_frame_host_->GetRoutingID();
1940 // If there is a matching pending RFH, only return it if swapped out is
1941 // allowed, since otherwise there should be a proxy that should be used
1942 // instead.
1943 if (pending_render_frame_host_ &&
1944 pending_render_frame_host_->GetSiteInstance() == site_instance &&
1945 !RenderFrameHostManager::IsSwappedOutStateForbidden())
1946 return pending_render_frame_host_->GetRoutingID();
1948 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(site_instance);
1949 if (proxy)
1950 return proxy->GetRoutingID();
1952 return MSG_ROUTING_NONE;
1955 void RenderFrameHostManager::CommitPending() {
1956 TRACE_EVENT1("navigation", "RenderFrameHostManager::CommitPending",
1957 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
1958 bool browser_side_navigation =
1959 base::CommandLine::ForCurrentProcess()->HasSwitch(
1960 switches::kEnableBrowserSideNavigation);
1962 // First check whether we're going to want to focus the location bar after
1963 // this commit. We do this now because the navigation hasn't formally
1964 // committed yet, so if we've already cleared |pending_web_ui_| the call chain
1965 // this triggers won't be able to figure out what's going on.
1966 bool will_focus_location_bar = delegate_->FocusLocationBarByDefault();
1968 // Next commit the Web UI, if any. Either replace |web_ui_| with
1969 // |pending_web_ui_|, or clear |web_ui_| if there is no pending WebUI, or
1970 // leave |web_ui_| as is if reusing it.
1971 DCHECK(!(pending_web_ui_ && pending_and_current_web_ui_));
1972 if (pending_web_ui_ || speculative_web_ui_) {
1973 DCHECK(!should_reuse_web_ui_);
1974 web_ui_.reset(browser_side_navigation ? speculative_web_ui_.release()
1975 : pending_web_ui_.release());
1976 } else if (pending_and_current_web_ui_ || should_reuse_web_ui_) {
1977 if (browser_side_navigation) {
1978 DCHECK(web_ui_);
1979 should_reuse_web_ui_ = false;
1980 } else {
1981 DCHECK_EQ(pending_and_current_web_ui_.get(), web_ui_.get());
1982 pending_and_current_web_ui_.reset();
1984 } else {
1985 web_ui_.reset();
1987 DCHECK(!speculative_web_ui_);
1988 DCHECK(!should_reuse_web_ui_);
1990 // It's possible for the pending_render_frame_host_ to be nullptr when we
1991 // aren't crossing process boundaries. If so, we just needed to handle the Web
1992 // UI committing above and we're done.
1993 if (!pending_render_frame_host_ && !speculative_render_frame_host_) {
1994 if (will_focus_location_bar)
1995 delegate_->SetFocusToLocationBar(false);
1996 return;
1999 // Remember if the page was focused so we can focus the new renderer in
2000 // that case.
2001 bool focus_render_view = !will_focus_location_bar &&
2002 render_frame_host_->GetView() &&
2003 render_frame_host_->GetView()->HasFocus();
2005 bool is_main_frame = frame_tree_node_->IsMainFrame();
2007 // Swap in the pending or speculative frame and make it active. Also ensure
2008 // the FrameTree stays in sync.
2009 scoped_ptr<RenderFrameHostImpl> old_render_frame_host;
2010 if (!browser_side_navigation) {
2011 DCHECK(!speculative_render_frame_host_);
2012 old_render_frame_host =
2013 SetRenderFrameHost(pending_render_frame_host_.Pass());
2014 } else {
2015 // PlzNavigate
2016 DCHECK(speculative_render_frame_host_);
2017 old_render_frame_host =
2018 SetRenderFrameHost(speculative_render_frame_host_.Pass());
2021 // Remove the children of the old frame from the tree.
2022 frame_tree_node_->ResetForNewProcess();
2024 // The process will no longer try to exit, so we can decrement the count.
2025 render_frame_host_->GetProcess()->RemovePendingView();
2027 // Show the new view (or a sad tab) if necessary.
2028 bool new_rfh_has_view = !!render_frame_host_->GetView();
2029 if (!delegate_->IsHidden() && new_rfh_has_view) {
2030 // In most cases, we need to show the new view.
2031 render_frame_host_->GetView()->Show();
2033 if (!new_rfh_has_view) {
2034 // If the view is gone, then this RenderViewHost died while it was hidden.
2035 // We ignored the RenderProcessGone call at the time, so we should send it
2036 // now to make sure the sad tab shows up, etc.
2037 DCHECK(!render_frame_host_->IsRenderFrameLive());
2038 DCHECK(!render_frame_host_->render_view_host()->IsRenderViewLive());
2039 delegate_->RenderProcessGoneFromRenderManager(
2040 render_frame_host_->render_view_host());
2043 // For top-level frames, also hide the old RenderViewHost's view.
2044 // TODO(creis): As long as show/hide are on RVH, we don't want to hide on
2045 // subframe navigations or we will interfere with the top-level frame.
2046 if (is_main_frame && old_render_frame_host->render_view_host()->GetView())
2047 old_render_frame_host->render_view_host()->GetView()->Hide();
2049 // Make sure the size is up to date. (Fix for bug 1079768.)
2050 delegate_->UpdateRenderViewSizeForRenderManager();
2052 if (will_focus_location_bar) {
2053 delegate_->SetFocusToLocationBar(false);
2054 } else if (focus_render_view && render_frame_host_->GetView()) {
2055 render_frame_host_->GetView()->Focus();
2058 // Notify that we've swapped RenderFrameHosts. We do this before shutting down
2059 // the RFH so that we can clean up RendererResources related to the RFH first.
2060 delegate_->NotifySwappedFromRenderManager(
2061 old_render_frame_host.get(), render_frame_host_.get(), is_main_frame);
2063 // The RenderViewHost keeps track of the main RenderFrameHost routing id.
2064 // If this is committing a main frame navigation, update it and set the
2065 // routing id in the RenderViewHost associated with the old RenderFrameHost
2066 // to MSG_ROUTING_NONE.
2067 if (is_main_frame && RenderFrameHostManager::IsSwappedOutStateForbidden()) {
2068 render_frame_host_->render_view_host()->set_main_frame_routing_id(
2069 render_frame_host_->routing_id());
2070 old_render_frame_host->render_view_host()->set_main_frame_routing_id(
2071 MSG_ROUTING_NONE);
2074 // Swap out the old frame now that the new one is visible.
2075 // This will swap it out and then put it on the proxy list (if there are other
2076 // active views in its SiteInstance) or schedule it for deletion when the swap
2077 // out ack arrives (or immediately if the process isn't live).
2078 // In the --site-per-process case, old subframe RFHs are not kept alive inside
2079 // the proxy.
2080 SwapOutOldFrame(old_render_frame_host.Pass());
2082 if (RenderFrameHostManager::IsSwappedOutStateForbidden()) {
2083 // Since the new RenderFrameHost is now committed, there must be no proxies
2084 // for its SiteInstance. Delete any existing ones.
2085 proxy_hosts_->Remove(render_frame_host_->GetSiteInstance()->GetId());
2088 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2089 switches::kSitePerProcess)) {
2090 // If this is a subframe, it should have a CrossProcessFrameConnector
2091 // created already. Use it to link the new RFH's view to the proxy that
2092 // belongs to the parent frame's SiteInstance. If this navigation causes
2093 // an out-of-process frame to return to the same process as its parent, the
2094 // proxy would have been removed from proxy_hosts_ above.
2095 // Note: We do this after swapping out the old RFH because that may create
2096 // the proxy we're looking for.
2097 RenderFrameProxyHost* proxy_to_parent = GetProxyToParent();
2098 if (proxy_to_parent)
2099 proxy_to_parent->SetChildRWHView(render_frame_host_->GetView());
2102 // After all is done, there must never be a proxy in the list which has the
2103 // same SiteInstance as the current RenderFrameHost.
2104 CHECK(!proxy_hosts_->Get(render_frame_host_->GetSiteInstance()->GetId()));
2107 void RenderFrameHostManager::ShutdownProxiesIfLastActiveFrameInSiteInstance(
2108 RenderFrameHostImpl* render_frame_host) {
2109 if (!render_frame_host)
2110 return;
2111 if (!RenderFrameHostImpl::IsRFHStateActive(render_frame_host->rfh_state()))
2112 return;
2113 if (render_frame_host->GetSiteInstance()->active_frame_count() > 1U)
2114 return;
2116 // After |render_frame_host| goes away, there will be no active frames left in
2117 // its SiteInstance, so we can delete all proxies created in that SiteInstance
2118 // on behalf of frames anywhere in the BrowsingInstance.
2119 int32 site_instance_id = render_frame_host->GetSiteInstance()->GetId();
2121 // First remove any proxies for this SiteInstance from our own list.
2122 ClearProxiesInSiteInstance(site_instance_id, frame_tree_node_);
2124 // Use the safe RenderWidgetHost iterator for now to find all RenderViewHosts
2125 // in the SiteInstance, then tell their respective FrameTrees to remove all
2126 // RenderFrameProxyHosts corresponding to them.
2127 // TODO(creis): Replace this with a RenderFrameHostIterator that protects
2128 // against use-after-frees if a later element is deleted before getting to it.
2129 scoped_ptr<RenderWidgetHostIterator> widgets(
2130 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
2131 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2132 if (!widget->IsRenderView())
2133 continue;
2134 RenderViewHostImpl* rvh =
2135 static_cast<RenderViewHostImpl*>(RenderViewHost::From(widget));
2136 if (site_instance_id == rvh->GetSiteInstance()->GetId()) {
2137 // This deletes all RenderFrameHosts using the |rvh|, which then causes
2138 // |rvh| to Shutdown.
2139 FrameTree* tree = rvh->GetDelegate()->GetFrameTree();
2140 tree->ForEach(base::Bind(
2141 &RenderFrameHostManager::ClearProxiesInSiteInstance,
2142 site_instance_id));
2147 RenderFrameHostImpl* RenderFrameHostManager::UpdateStateForNavigate(
2148 const GURL& dest_url,
2149 SiteInstance* source_instance,
2150 SiteInstance* dest_instance,
2151 ui::PageTransition transition,
2152 bool dest_is_restore,
2153 bool dest_is_view_source_mode,
2154 const GlobalRequestID& transferred_request_id,
2155 int bindings) {
2156 // Don't swap for subframes unless we are in --site-per-process. We can get
2157 // here in tests for subframes (e.g., NavigateFrameToURL).
2158 if (!frame_tree_node_->IsMainFrame() &&
2159 !base::CommandLine::ForCurrentProcess()->HasSwitch(
2160 switches::kSitePerProcess))
2161 return render_frame_host_.get();
2163 // If we are currently navigating cross-process, we want to get back to normal
2164 // and then navigate as usual.
2165 if (pending_render_frame_host_)
2166 CancelPending();
2168 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
2169 scoped_refptr<SiteInstance> new_instance = GetSiteInstanceForNavigation(
2170 dest_url, source_instance, dest_instance, nullptr, transition,
2171 dest_is_restore, dest_is_view_source_mode);
2173 const NavigationEntry* current_entry =
2174 delegate_->GetLastCommittedNavigationEntryForRenderManager();
2176 DCHECK(!pending_render_frame_host_);
2178 if (new_instance.get() != current_instance) {
2179 TRACE_EVENT_INSTANT2(
2180 "navigation",
2181 "RenderFrameHostManager::UpdateStateForNavigate:New SiteInstance",
2182 TRACE_EVENT_SCOPE_THREAD,
2183 "current_instance id", current_instance->GetId(),
2184 "new_instance id", new_instance->GetId());
2186 // New SiteInstance: create a pending RFH to navigate.
2188 // This will possibly create (set to nullptr) a Web UI object for the
2189 // pending page. We'll use this later to give the page special access. This
2190 // must happen before the new renderer is created below so it will get
2191 // bindings. It must also happen after the above conditional call to
2192 // CancelPending(), otherwise CancelPending may clear the pending_web_ui_
2193 // and the page will not have its bindings set appropriately.
2194 SetPendingWebUI(dest_url, bindings);
2195 CreatePendingRenderFrameHost(current_instance, new_instance.get(),
2196 frame_tree_node_->IsMainFrame());
2197 if (!pending_render_frame_host_)
2198 return nullptr;
2200 // Check if our current RFH is live before we set up a transition.
2201 if (!render_frame_host_->IsRenderFrameLive()) {
2202 // The current RFH is not live. There's no reason to sit around with a
2203 // sad tab or a newly created RFH while we wait for the pending RFH to
2204 // navigate. Just switch to the pending RFH now and go back to normal.
2205 // (Note that we don't care about on{before}unload handlers if the current
2206 // RFH isn't live.)
2207 CommitPending();
2208 return render_frame_host_.get();
2210 // Otherwise, it's safe to treat this as a pending cross-process transition.
2212 // We now have a pending RFH.
2213 DCHECK(pending_render_frame_host_);
2215 // We need to wait until the beforeunload handler has run, unless we are
2216 // transferring an existing request (in which case it has already run).
2217 // Suspend the new render view (i.e., don't let it send the cross-process
2218 // Navigate message) until we hear back from the old renderer's
2219 // beforeunload handler. If the handler returns false, we'll have to
2220 // cancel the request.
2222 DCHECK(!pending_render_frame_host_->are_navigations_suspended());
2223 bool is_transfer = transferred_request_id != GlobalRequestID();
2224 if (is_transfer) {
2225 // We don't need to stop the old renderer or run beforeunload/unload
2226 // handlers, because those have already been done.
2227 DCHECK(cross_site_transferring_request_->request_id() ==
2228 transferred_request_id);
2229 } else {
2230 // Also make sure the old render view stops, in case a load is in
2231 // progress. (We don't want to do this for transfers, since it will
2232 // interrupt the transfer with an unexpected DidStopLoading.)
2233 render_frame_host_->Send(new FrameMsg_Stop(
2234 render_frame_host_->GetRoutingID()));
2235 pending_render_frame_host_->SetNavigationsSuspended(true,
2236 base::TimeTicks());
2237 // Unless we are transferring an existing request, we should now tell the
2238 // old render view to run its beforeunload handler, since it doesn't
2239 // otherwise know that the cross-site request is happening. This will
2240 // trigger a call to OnBeforeUnloadACK with the reply.
2241 render_frame_host_->DispatchBeforeUnload(true);
2244 return pending_render_frame_host_.get();
2247 // Otherwise the same SiteInstance can be used. Navigate render_frame_host_.
2249 // It's possible to swap out the current RFH and then decide to navigate in it
2250 // anyway (e.g., a cross-process navigation that redirects back to the
2251 // original site). In that case, we have a proxy for the current RFH but
2252 // haven't deleted it yet. The new navigation will swap it back in, so we can
2253 // delete the proxy.
2254 proxy_hosts_->Remove(new_instance.get()->GetId());
2256 if (ShouldReuseWebUI(current_entry, dest_url)) {
2257 pending_web_ui_.reset();
2258 pending_and_current_web_ui_ = web_ui_->AsWeakPtr();
2259 } else {
2260 SetPendingWebUI(dest_url, bindings);
2261 // Make sure the new RenderViewHost has the right bindings.
2262 if (pending_web_ui() &&
2263 !render_frame_host_->GetProcess()->IsForGuestsOnly()) {
2264 render_frame_host_->render_view_host()->AllowBindings(
2265 pending_web_ui()->GetBindings());
2269 if (pending_web_ui() && render_frame_host_->IsRenderFrameLive()) {
2270 pending_web_ui()->GetController()->RenderViewReused(
2271 render_frame_host_->render_view_host());
2274 // The renderer can exit view source mode when any error or cancellation
2275 // happen. We must overwrite to recover the mode.
2276 if (dest_is_view_source_mode) {
2277 render_frame_host_->render_view_host()->Send(
2278 new ViewMsg_EnableViewSourceMode(
2279 render_frame_host_->render_view_host()->GetRoutingID()));
2282 return render_frame_host_.get();
2285 void RenderFrameHostManager::CancelPending() {
2286 TRACE_EVENT1("navigation", "RenderFrameHostManager::CancelPending",
2287 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
2288 DiscardUnusedFrame(UnsetPendingRenderFrameHost());
2291 scoped_ptr<RenderFrameHostImpl>
2292 RenderFrameHostManager::UnsetPendingRenderFrameHost() {
2293 scoped_ptr<RenderFrameHostImpl> pending_render_frame_host =
2294 pending_render_frame_host_.Pass();
2296 RenderFrameDevToolsAgentHost::OnCancelPendingNavigation(
2297 pending_render_frame_host.get(),
2298 render_frame_host_.get());
2300 // We no longer need to prevent the process from exiting.
2301 pending_render_frame_host->GetProcess()->RemovePendingView();
2303 pending_web_ui_.reset();
2304 pending_and_current_web_ui_.reset();
2306 return pending_render_frame_host.Pass();
2309 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::SetRenderFrameHost(
2310 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
2311 // Swap the two.
2312 scoped_ptr<RenderFrameHostImpl> old_render_frame_host =
2313 render_frame_host_.Pass();
2314 render_frame_host_ = render_frame_host.Pass();
2316 if (frame_tree_node_->IsMainFrame()) {
2317 // Update the count of top-level frames using this SiteInstance. All
2318 // subframes are in the same BrowsingInstance as the main frame, so we only
2319 // count top-level ones. This makes the value easier for consumers to
2320 // interpret.
2321 if (render_frame_host_) {
2322 render_frame_host_->GetSiteInstance()->
2323 IncrementRelatedActiveContentsCount();
2325 if (old_render_frame_host) {
2326 old_render_frame_host->GetSiteInstance()->
2327 DecrementRelatedActiveContentsCount();
2331 return old_render_frame_host.Pass();
2334 bool RenderFrameHostManager::IsRVHOnSwappedOutList(
2335 RenderViewHostImpl* rvh) const {
2336 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(
2337 rvh->GetSiteInstance());
2338 if (!proxy)
2339 return false;
2340 // If there is a proxy without RFH, it is for a subframe in the SiteInstance
2341 // of |rvh|. Subframes should be ignored in this case.
2342 if (!proxy->render_frame_host())
2343 return false;
2344 return IsOnSwappedOutList(proxy->render_frame_host());
2347 bool RenderFrameHostManager::IsOnSwappedOutList(
2348 RenderFrameHostImpl* rfh) const {
2349 if (!rfh->GetSiteInstance())
2350 return false;
2352 RenderFrameProxyHost* host =
2353 proxy_hosts_->Get(rfh->GetSiteInstance()->GetId());
2354 if (!host)
2355 return false;
2357 return host->render_frame_host() == rfh;
2360 RenderViewHostImpl* RenderFrameHostManager::GetSwappedOutRenderViewHost(
2361 SiteInstance* instance) const {
2362 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
2363 if (proxy)
2364 return proxy->GetRenderViewHost();
2365 return nullptr;
2368 RenderFrameProxyHost* RenderFrameHostManager::GetRenderFrameProxyHost(
2369 SiteInstance* instance) const {
2370 return proxy_hosts_->Get(instance->GetId());
2373 std::map<int, RenderFrameProxyHost*>
2374 RenderFrameHostManager::GetAllProxyHostsForTesting() {
2375 std::map<int, RenderFrameProxyHost*> result;
2376 result.insert(proxy_hosts_->begin(), proxy_hosts_->end());
2377 return result;
2380 void RenderFrameHostManager::CreateOpenerProxiesIfNeeded(
2381 SiteInstance* instance) {
2382 FrameTreeNode* opener = frame_tree_node_->opener();
2383 if (!opener)
2384 return;
2386 // Create proxies for the opener chain.
2387 opener->render_manager()->CreateOpenerProxies(instance);
2390 void RenderFrameHostManager::CreateOpenerProxies(SiteInstance* instance) {
2391 // If this tab has an opener, recursively create proxies for the nodes on its
2392 // frame tree.
2393 // TODO(alexmos): Once we allow frame openers to be updated (which can happen
2394 // via window.open(url, "target_frame")), this will need to be resilient to
2395 // cycles. It will also need to handle tabs that have multiple openers (e.g.,
2396 // main frame and subframe could have different openers, each of which must
2397 // be traversed).
2398 FrameTreeNode* opener = frame_tree_node_->opener();
2399 if (opener)
2400 opener->render_manager()->CreateOpenerProxies(instance);
2402 // If any of the RenderViewHosts (current, pending, or swapped out) for this
2403 // FrameTree has the same SiteInstance, then we can return early, since
2404 // proxies for other nodes in the tree should also exist (when in
2405 // site-per-process mode). An exception is if we are in
2406 // IsSwappedOutStateForbidden mode and find a pending RenderViewHost: in this
2407 // case, we should still create a proxy, which will allow communicating with
2408 // the opener until the pending RenderView commits, or if the pending
2409 // navigation is canceled.
2410 FrameTree* frame_tree = frame_tree_node_->frame_tree();
2411 RenderViewHostImpl* rvh = frame_tree->GetRenderViewHost(instance);
2412 bool need_proxy_for_pending_rvh =
2413 IsSwappedOutStateForbidden() && (rvh == pending_render_view_host());
2414 if (rvh && rvh->IsRenderViewLive() && !need_proxy_for_pending_rvh)
2415 return;
2417 if (RenderFrameHostManager::IsSwappedOutStateForbidden()) {
2418 // Ensure that all the nodes in the opener's frame tree have
2419 // RenderFrameProxyHosts for the new SiteInstance.
2420 frame_tree->CreateProxiesForSiteInstance(nullptr, instance);
2421 } else if (rvh && !rvh->IsRenderViewLive()) {
2422 EnsureRenderViewInitialized(rvh, instance);
2423 } else {
2424 // Create a swapped out RenderView in the given SiteInstance if none exists,
2425 // setting its opener to the given route_id. Since the opener can point to
2426 // a subframe, do this on the root frame of the opener's frame tree.
2427 // Return the new view's route_id.
2428 frame_tree->root()->render_manager()->
2429 CreateRenderFrame(instance, nullptr,
2430 CREATE_RF_FOR_MAIN_FRAME_NAVIGATION |
2431 CREATE_RF_SWAPPED_OUT | CREATE_RF_HIDDEN,
2432 nullptr);
2436 int RenderFrameHostManager::GetOpenerRoutingID(SiteInstance* instance) {
2437 if (!frame_tree_node_->opener())
2438 return MSG_ROUTING_NONE;
2440 return frame_tree_node_->opener()
2441 ->render_manager()
2442 ->GetRoutingIdForSiteInstance(instance);
2445 } // namespace content