Supervised user whitelists: Cleanup
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_manager.cc
blobb1344239af60b5cd03936f098e725ae94b4e965f
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/frame_host/render_frame_host_manager.h"
7 #include <utility>
9 #include "base/command_line.h"
10 #include "base/logging.h"
11 #include "base/stl_util.h"
12 #include "base/trace_event/trace_event.h"
13 #include "content/browser/child_process_security_policy_impl.h"
14 #include "content/browser/devtools/render_frame_devtools_agent_host.h"
15 #include "content/browser/frame_host/cross_site_transferring_request.h"
16 #include "content/browser/frame_host/debug_urls.h"
17 #include "content/browser/frame_host/interstitial_page_impl.h"
18 #include "content/browser/frame_host/navigation_controller_impl.h"
19 #include "content/browser/frame_host/navigation_entry_impl.h"
20 #include "content/browser/frame_host/navigation_request.h"
21 #include "content/browser/frame_host/navigator.h"
22 #include "content/browser/frame_host/render_frame_host_factory.h"
23 #include "content/browser/frame_host/render_frame_host_impl.h"
24 #include "content/browser/frame_host/render_frame_proxy_host.h"
25 #include "content/browser/renderer_host/render_process_host_impl.h"
26 #include "content/browser/renderer_host/render_view_host_factory.h"
27 #include "content/browser/renderer_host/render_view_host_impl.h"
28 #include "content/browser/site_instance_impl.h"
29 #include "content/browser/webui/web_ui_controller_factory_registry.h"
30 #include "content/browser/webui/web_ui_impl.h"
31 #include "content/common/frame_messages.h"
32 #include "content/common/view_messages.h"
33 #include "content/public/browser/content_browser_client.h"
34 #include "content/public/browser/notification_service.h"
35 #include "content/public/browser/notification_types.h"
36 #include "content/public/browser/render_widget_host_iterator.h"
37 #include "content/public/browser/render_widget_host_view.h"
38 #include "content/public/browser/user_metrics.h"
39 #include "content/public/browser/web_ui_controller.h"
40 #include "content/public/common/content_switches.h"
41 #include "content/public/common/referrer.h"
42 #include "content/public/common/url_constants.h"
44 namespace content {
46 // static
47 bool RenderFrameHostManager::ClearRFHsPendingShutdown(FrameTreeNode* node) {
48 node->render_manager()->pending_delete_hosts_.clear();
49 return true;
52 RenderFrameHostManager::RenderFrameHostManager(
53 FrameTreeNode* frame_tree_node,
54 RenderFrameHostDelegate* render_frame_delegate,
55 RenderViewHostDelegate* render_view_delegate,
56 RenderWidgetHostDelegate* render_widget_delegate,
57 Delegate* delegate)
58 : frame_tree_node_(frame_tree_node),
59 delegate_(delegate),
60 render_frame_delegate_(render_frame_delegate),
61 render_view_delegate_(render_view_delegate),
62 render_widget_delegate_(render_widget_delegate),
63 interstitial_page_(nullptr),
64 should_reuse_web_ui_(false),
65 weak_factory_(this) {
66 DCHECK(frame_tree_node_);
69 RenderFrameHostManager::~RenderFrameHostManager() {
70 if (pending_render_frame_host_) {
71 scoped_ptr<RenderFrameHostImpl> relic = UnsetPendingRenderFrameHost();
72 ShutdownProxiesIfLastActiveFrameInSiteInstance(relic.get());
75 if (speculative_render_frame_host_) {
76 scoped_ptr<RenderFrameHostImpl> relic = UnsetSpeculativeRenderFrameHost();
77 ShutdownProxiesIfLastActiveFrameInSiteInstance(relic.get());
80 ShutdownProxiesIfLastActiveFrameInSiteInstance(render_frame_host_.get());
82 // Delete any RenderFrameProxyHosts and swapped out RenderFrameHosts.
83 // It is important to delete those prior to deleting the current
84 // RenderFrameHost, since the CrossProcessFrameConnector (owned by
85 // RenderFrameProxyHost) points to the RenderWidgetHostView associated with
86 // the current RenderFrameHost and uses it during its destructor.
87 STLDeleteValues(&proxy_hosts_);
89 // Release the WebUI prior to resetting the current RenderFrameHost, as the
90 // WebUI accesses the RenderFrameHost during cleanup.
91 web_ui_.reset();
93 // We should always have a current RenderFrameHost except in some tests.
94 SetRenderFrameHost(scoped_ptr<RenderFrameHostImpl>());
97 void RenderFrameHostManager::Init(BrowserContext* browser_context,
98 SiteInstance* site_instance,
99 int view_routing_id,
100 int frame_routing_id) {
101 // Create a RenderViewHost and RenderFrameHost, once we have an instance. It
102 // is important to immediately give this SiteInstance to a RenderViewHost so
103 // that the SiteInstance is ref counted.
104 if (!site_instance)
105 site_instance = SiteInstance::Create(browser_context);
107 int flags = delegate_->IsHidden() ? CREATE_RF_HIDDEN : 0;
108 SetRenderFrameHost(CreateRenderFrameHost(site_instance, view_routing_id,
109 frame_routing_id, flags));
111 // Notify the delegate of the creation of the current RenderFrameHost.
112 // Do this only for subframes, as the main frame case is taken care of by
113 // WebContentsImpl::Init.
114 if (!frame_tree_node_->IsMainFrame()) {
115 delegate_->NotifySwappedFromRenderManager(
116 nullptr, render_frame_host_.get(), false);
119 // Keep track of renderer processes as they start to shut down or are
120 // crashed/killed.
121 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSED,
122 NotificationService::AllSources());
123 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSING,
124 NotificationService::AllSources());
127 RenderViewHostImpl* RenderFrameHostManager::current_host() const {
128 if (!render_frame_host_)
129 return NULL;
130 return render_frame_host_->render_view_host();
133 RenderViewHostImpl* RenderFrameHostManager::pending_render_view_host() const {
134 if (!pending_render_frame_host_)
135 return NULL;
136 return pending_render_frame_host_->render_view_host();
139 RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const {
140 if (interstitial_page_)
141 return interstitial_page_->GetView();
142 if (render_frame_host_)
143 return render_frame_host_->GetView();
144 return nullptr;
147 RenderFrameProxyHost* RenderFrameHostManager::GetProxyToParent() {
148 if (frame_tree_node_->IsMainFrame())
149 return NULL;
151 RenderFrameProxyHostMap::iterator iter =
152 proxy_hosts_.find(frame_tree_node_->parent()
153 ->render_manager()
154 ->current_frame_host()
155 ->GetSiteInstance()
156 ->GetId());
157 if (iter == proxy_hosts_.end())
158 return NULL;
160 return iter->second;
163 void RenderFrameHostManager::SetPendingWebUI(const GURL& url, int bindings) {
164 pending_web_ui_ = CreateWebUI(url, bindings);
165 pending_and_current_web_ui_.reset();
168 scoped_ptr<WebUIImpl> RenderFrameHostManager::CreateWebUI(const GURL& url,
169 int bindings) {
170 scoped_ptr<WebUIImpl> new_web_ui(delegate_->CreateWebUIForRenderManager(url));
172 // If we have assigned (zero or more) bindings to this NavigationEntry in the
173 // past, make sure we're not granting it different bindings than it had
174 // before. If so, note it and don't give it any bindings, to avoid a
175 // potential privilege escalation.
176 if (new_web_ui && bindings != NavigationEntryImpl::kInvalidBindings &&
177 new_web_ui->GetBindings() != bindings) {
178 RecordAction(base::UserMetricsAction("ProcessSwapBindingsMismatch_RVHM"));
179 return nullptr;
181 return new_web_ui.Pass();
184 RenderFrameHostImpl* RenderFrameHostManager::Navigate(
185 const NavigationEntryImpl& entry) {
186 TRACE_EVENT1("navigation", "RenderFrameHostManager:Navigate",
187 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
188 // Create a pending RenderFrameHost to use for the navigation.
189 RenderFrameHostImpl* dest_render_frame_host = UpdateStateForNavigate(
190 entry.GetURL(), entry.source_site_instance(), entry.site_instance(),
191 entry.GetTransitionType(),
192 entry.restore_type() != NavigationEntryImpl::RESTORE_NONE,
193 entry.IsViewSourceMode(), entry.transferred_global_request_id(),
194 entry.bindings());
195 if (!dest_render_frame_host)
196 return NULL; // We weren't able to create a pending render frame host.
198 // If the current render_frame_host_ isn't live, we should create it so
199 // that we don't show a sad tab while the dest_render_frame_host fetches
200 // its first page. (Bug 1145340)
201 if (dest_render_frame_host != render_frame_host_ &&
202 !render_frame_host_->IsRenderFrameLive()) {
203 // Note: we don't call InitRenderView here because we are navigating away
204 // soon anyway, and we don't have the NavigationEntry for this host.
205 delegate_->CreateRenderViewForRenderManager(
206 render_frame_host_->render_view_host(), MSG_ROUTING_NONE,
207 MSG_ROUTING_NONE, frame_tree_node_->IsMainFrame());
210 // If the renderer crashed, then try to create a new one to satisfy this
211 // navigation request.
212 if (!dest_render_frame_host->IsRenderFrameLive()) {
213 // Instruct the destination render frame host to set up a Mojo connection
214 // with the new render frame if necessary. Note that this call needs to
215 // occur before initializing the RenderView; the flow of creating the
216 // RenderView can cause browser-side code to execute that expects the this
217 // RFH's ServiceRegistry to be initialized (e.g., if the site is a WebUI
218 // site that is handled via Mojo, then Mojo WebUI code in //chrome will
219 // add a service to this RFH's ServiceRegistry).
220 dest_render_frame_host->SetUpMojoIfNeeded();
222 // Recreate the opener chain.
223 int opener_route_id = delegate_->CreateOpenerRenderViewsForRenderManager(
224 dest_render_frame_host->GetSiteInstance());
225 if (!InitRenderView(dest_render_frame_host->render_view_host(),
226 opener_route_id,
227 MSG_ROUTING_NONE,
228 frame_tree_node_->IsMainFrame()))
229 return NULL;
231 // Now that we've created a new renderer, be sure to hide it if it isn't
232 // our primary one. Otherwise, we might crash if we try to call Show()
233 // on it later.
234 if (dest_render_frame_host != render_frame_host_) {
235 if (dest_render_frame_host->GetView())
236 dest_render_frame_host->GetView()->Hide();
237 } else {
238 // TODO(nasko): This is a very ugly hack. The Chrome extensions process
239 // manager still uses NotificationService and expects to see a
240 // RenderViewHost changed notification after WebContents and
241 // RenderFrameHostManager are completely initialized. This should be
242 // removed once the process manager moves away from NotificationService.
243 // See https://crbug.com/462682.
244 delegate_->NotifyMainFrameSwappedFromRenderManager(
245 nullptr, render_frame_host_->render_view_host());
249 // If entry includes the request ID of a request that is being transferred,
250 // the destination render frame will take ownership, so release ownership of
251 // the request.
252 if (cross_site_transferring_request_.get() &&
253 cross_site_transferring_request_->request_id() ==
254 entry.transferred_global_request_id()) {
255 cross_site_transferring_request_->ReleaseRequest();
258 return dest_render_frame_host;
261 void RenderFrameHostManager::Stop() {
262 render_frame_host_->Stop();
264 // If we are navigating cross-process, we should stop the pending renderers.
265 // This will lead to a DidFailProvisionalLoad, which will properly destroy
266 // them.
267 if (pending_render_frame_host_) {
268 pending_render_frame_host_->Send(new FrameMsg_Stop(
269 pending_render_frame_host_->GetRoutingID()));
273 void RenderFrameHostManager::SetIsLoading(bool is_loading) {
274 render_frame_host_->render_view_host()->SetIsLoading(is_loading);
275 if (pending_render_frame_host_)
276 pending_render_frame_host_->render_view_host()->SetIsLoading(is_loading);
279 bool RenderFrameHostManager::ShouldCloseTabOnUnresponsiveRenderer() {
280 // If we're waiting for a close ACK, then the tab should close whether there's
281 // a navigation in progress or not. Unfortunately, we also need to check for
282 // cases that we arrive here with no navigation in progress, since there are
283 // some tab closure paths that don't set is_waiting_for_close_ack to true.
284 // TODO(creis): Clean this up in http://crbug.com/418266.
285 if (!pending_render_frame_host_ ||
286 render_frame_host_->render_view_host()->is_waiting_for_close_ack())
287 return true;
289 // We should always have a pending RFH when there's a cross-process navigation
290 // in progress. Sanity check this for http://crbug.com/276333.
291 CHECK(pending_render_frame_host_);
293 // Unload handlers run in the background, so we should never get an
294 // unresponsiveness warning for them.
295 CHECK(!render_frame_host_->IsWaitingForUnloadACK());
297 // If the tab becomes unresponsive during beforeunload while doing a
298 // cross-process navigation, proceed with the navigation. (This assumes that
299 // the pending RenderFrameHost is still responsive.)
300 if (render_frame_host_->IsWaitingForBeforeUnloadACK()) {
301 // Haven't gotten around to starting the request, because we're still
302 // waiting for the beforeunload handler to finish. We'll pretend that it
303 // did finish, to let the navigation proceed. Note that there's a danger
304 // that the beforeunload handler will later finish and possibly return
305 // false (meaning the navigation should not proceed), but we'll ignore it
306 // in this case because it took too long.
307 if (pending_render_frame_host_->are_navigations_suspended()) {
308 pending_render_frame_host_->SetNavigationsSuspended(
309 false, base::TimeTicks::Now());
312 return false;
315 void RenderFrameHostManager::OnBeforeUnloadACK(
316 bool for_cross_site_transition,
317 bool proceed,
318 const base::TimeTicks& proceed_time) {
319 if (for_cross_site_transition) {
320 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
321 switches::kEnableBrowserSideNavigation));
322 // Ignore if we're not in a cross-process navigation.
323 if (!pending_render_frame_host_)
324 return;
326 if (proceed) {
327 // Ok to unload the current page, so proceed with the cross-process
328 // navigation. Note that if navigations are not currently suspended, it
329 // might be because the renderer was deemed unresponsive and this call was
330 // already made by ShouldCloseTabOnUnresponsiveRenderer. In that case, it
331 // is ok to do nothing here.
332 if (pending_render_frame_host_ &&
333 pending_render_frame_host_->are_navigations_suspended()) {
334 pending_render_frame_host_->SetNavigationsSuspended(false,
335 proceed_time);
337 } else {
338 // Current page says to cancel.
339 CancelPending();
341 } else {
342 // Non-cross-process transition means closing the entire tab.
343 bool proceed_to_fire_unload;
344 delegate_->BeforeUnloadFiredFromRenderManager(proceed, proceed_time,
345 &proceed_to_fire_unload);
347 if (proceed_to_fire_unload) {
348 // If we're about to close the tab and there's a pending RFH, cancel it.
349 // Otherwise, if the navigation in the pending RFH completes before the
350 // close in the current RFH, we'll lose the tab close.
351 if (pending_render_frame_host_) {
352 CancelPending();
355 // PlzNavigate: clean up the speculative RenderFrameHost if there is one.
356 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
357 switches::kEnableBrowserSideNavigation) &&
358 speculative_render_frame_host_) {
359 CleanUpNavigation();
362 // This is not a cross-process navigation; the tab is being closed.
363 render_frame_host_->render_view_host()->ClosePage();
368 void RenderFrameHostManager::OnCrossSiteResponse(
369 RenderFrameHostImpl* pending_render_frame_host,
370 const GlobalRequestID& global_request_id,
371 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
372 const std::vector<GURL>& transfer_url_chain,
373 const Referrer& referrer,
374 ui::PageTransition page_transition,
375 bool should_replace_current_entry) {
376 // We should only get here for transfer navigations. Most cross-process
377 // navigations can just continue and wait to run the unload handler (by
378 // swapping out) when the new navigation commits.
379 CHECK(cross_site_transferring_request);
381 // A transfer should only have come from our pending or current RFH.
382 // TODO(creis): We need to handle the case that the pending RFH has changed
383 // in the mean time, while this was being posted from the IO thread. We
384 // should probably cancel the request in that case.
385 DCHECK(pending_render_frame_host == pending_render_frame_host_ ||
386 pending_render_frame_host == render_frame_host_);
388 // Store the transferring request so that we can release it if the transfer
389 // navigation matches.
390 cross_site_transferring_request_ = cross_site_transferring_request.Pass();
392 // Sanity check that the params are for the correct frame and process.
393 // These should match the RenderFrameHost that made the request.
394 // If it started as a cross-process navigation via OpenURL, this is the
395 // pending one. If it wasn't cross-process until the transfer, this is the
396 // current one.
397 int render_frame_id = pending_render_frame_host_ ?
398 pending_render_frame_host_->GetRoutingID() :
399 render_frame_host_->GetRoutingID();
400 DCHECK_EQ(render_frame_id, pending_render_frame_host->GetRoutingID());
401 int process_id = pending_render_frame_host_ ?
402 pending_render_frame_host_->GetProcess()->GetID() :
403 render_frame_host_->GetProcess()->GetID();
404 DCHECK_EQ(process_id, global_request_id.child_id);
406 // Treat the last URL in the chain as the destination and the remainder as
407 // the redirect chain.
408 CHECK(transfer_url_chain.size());
409 GURL transfer_url = transfer_url_chain.back();
410 std::vector<GURL> rest_of_chain = transfer_url_chain;
411 rest_of_chain.pop_back();
413 // We don't know whether the original request had |user_action| set to true.
414 // However, since we force the navigation to be in the current tab, it
415 // doesn't matter.
416 pending_render_frame_host->frame_tree_node()->navigator()->RequestTransferURL(
417 pending_render_frame_host, transfer_url, nullptr, rest_of_chain, referrer,
418 page_transition, CURRENT_TAB, global_request_id,
419 should_replace_current_entry, true);
421 // The transferring request was only needed during the RequestTransferURL
422 // call, so it is safe to clear at this point.
423 cross_site_transferring_request_.reset();
426 void RenderFrameHostManager::OnDeferredAfterResponseStarted(
427 const GlobalRequestID& global_request_id,
428 RenderFrameHostImpl* pending_render_frame_host) {
429 DCHECK(!response_started_id_);
431 response_started_id_.reset(new GlobalRequestID(global_request_id));
434 void RenderFrameHostManager::ResumeResponseDeferredAtStart() {
435 DCHECK(response_started_id_);
437 RenderProcessHostImpl* process =
438 static_cast<RenderProcessHostImpl*>(render_frame_host_->GetProcess());
439 process->ResumeResponseDeferredAtStart(*response_started_id_);
441 render_frame_host_->ClearPendingTransitionRequestData();
443 response_started_id_.reset();
446 void RenderFrameHostManager::ClearNavigationTransitionData() {
447 render_frame_host_->ClearPendingTransitionRequestData();
450 void RenderFrameHostManager::DidNavigateFrame(
451 RenderFrameHostImpl* render_frame_host,
452 bool was_caused_by_user_gesture) {
453 CommitPendingIfNecessary(render_frame_host, was_caused_by_user_gesture);
455 // Make sure any dynamic changes to this frame's sandbox flags that were made
456 // prior to navigation take effect.
457 CommitPendingSandboxFlags();
460 void RenderFrameHostManager::CommitPendingIfNecessary(
461 RenderFrameHostImpl* render_frame_host,
462 bool was_caused_by_user_gesture) {
463 if (!pending_render_frame_host_ && !speculative_render_frame_host_) {
464 DCHECK_IMPLIES(should_reuse_web_ui_, web_ui_);
466 // We should only hear this from our current renderer.
467 DCHECK_EQ(render_frame_host_, render_frame_host);
469 // Even when there is no pending RVH, there may be a pending Web UI.
470 if (pending_web_ui() || speculative_web_ui_)
471 CommitPending();
472 return;
475 if (render_frame_host == pending_render_frame_host_ ||
476 render_frame_host == speculative_render_frame_host_) {
477 // The pending cross-process navigation completed, so show the renderer.
478 CommitPending();
479 } else if (render_frame_host == render_frame_host_) {
480 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
481 switches::kEnableBrowserSideNavigation)) {
482 CleanUpNavigation();
483 } else {
484 if (was_caused_by_user_gesture) {
485 // A navigation in the original page has taken place. Cancel the
486 // pending one. Only do it for user gesture originated navigations to
487 // prevent page doing any shenanigans to prevent user from navigating.
488 // See https://code.google.com/p/chromium/issues/detail?id=75195
489 CancelPending();
492 } else {
493 // No one else should be sending us DidNavigate in this state.
494 DCHECK(false);
498 void RenderFrameHostManager::DidDisownOpener(
499 RenderFrameHost* render_frame_host) {
500 // Notify all RenderFrameHosts but the one that notified us. This is necessary
501 // in case a process swap has occurred while the message was in flight.
502 for (RenderFrameProxyHostMap::iterator iter = proxy_hosts_.begin();
503 iter != proxy_hosts_.end();
504 ++iter) {
505 DCHECK_NE(iter->second->GetSiteInstance(),
506 current_frame_host()->GetSiteInstance());
507 iter->second->DisownOpener();
510 if (render_frame_host_.get() != render_frame_host)
511 render_frame_host_->DisownOpener();
513 if (pending_render_frame_host_ &&
514 pending_render_frame_host_.get() != render_frame_host) {
515 pending_render_frame_host_->DisownOpener();
519 void RenderFrameHostManager::CommitPendingSandboxFlags() {
520 // Return early if there were no pending sandbox flags updates.
521 if (!frame_tree_node_->CommitPendingSandboxFlags())
522 return;
524 // Sandbox flags updates can only happen when the frame has a parent.
525 CHECK(frame_tree_node_->parent());
527 // Notify all of the frame's proxies about updated sandbox flags, excluding
528 // the parent process since it already knows the latest flags.
529 SiteInstance* parent_site_instance =
530 frame_tree_node_->parent()->current_frame_host()->GetSiteInstance();
531 for (const auto& pair : proxy_hosts_) {
532 if (pair.second->GetSiteInstance() != parent_site_instance) {
533 pair.second->Send(new FrameMsg_DidUpdateSandboxFlags(
534 pair.second->GetRoutingID(),
535 frame_tree_node_->current_replication_state().sandbox_flags));
540 void RenderFrameHostManager::RendererProcessClosing(
541 RenderProcessHost* render_process_host) {
542 // Remove any swapped out RVHs from this process, so that we don't try to
543 // swap them back in while the process is exiting. Start by finding them,
544 // since there could be more than one.
545 std::list<int> ids_to_remove;
546 // Do not remove proxies in the dead process that still have active frame
547 // count though, we just reset them to be uninitialized.
548 std::list<int> ids_to_keep;
549 for (RenderFrameProxyHostMap::iterator iter = proxy_hosts_.begin();
550 iter != proxy_hosts_.end();
551 ++iter) {
552 RenderFrameProxyHost* proxy = iter->second;
553 if (proxy->GetProcess() != render_process_host)
554 continue;
556 if (static_cast<SiteInstanceImpl*>(proxy->GetSiteInstance())
557 ->active_frame_count() >= 1U) {
558 ids_to_keep.push_back(iter->first);
559 } else {
560 ids_to_remove.push_back(iter->first);
564 // Now delete them.
565 while (!ids_to_remove.empty()) {
566 delete proxy_hosts_[ids_to_remove.back()];
567 proxy_hosts_.erase(ids_to_remove.back());
568 ids_to_remove.pop_back();
571 while (!ids_to_keep.empty()) {
572 frame_tree_node_->frame_tree()->ForEach(
573 base::Bind(
574 &RenderFrameHostManager::ResetProxiesInSiteInstance,
575 ids_to_keep.back()));
576 ids_to_keep.pop_back();
580 void RenderFrameHostManager::SwapOutOldFrame(
581 scoped_ptr<RenderFrameHostImpl> old_render_frame_host) {
582 TRACE_EVENT1("navigation", "RenderFrameHostManager::SwapOutOldFrame",
583 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
585 // Tell the renderer to suppress any further modal dialogs so that we can swap
586 // it out. This must be done before canceling any current dialog, in case
587 // there is a loop creating additional dialogs.
588 // TODO(creis): Handle modal dialogs in subframe processes.
589 old_render_frame_host->render_view_host()->SuppressDialogsUntilSwapOut();
591 // Now close any modal dialogs that would prevent us from swapping out. This
592 // must be done separately from SwapOut, so that the PageGroupLoadDeferrer is
593 // no longer on the stack when we send the SwapOut message.
594 delegate_->CancelModalDialogsForRenderManager();
596 // If the old RFH is not live, just return as there is no further work to do.
597 // It will be deleted and there will be no proxy created.
598 int32 old_site_instance_id =
599 old_render_frame_host->GetSiteInstance()->GetId();
600 if (!old_render_frame_host->IsRenderFrameLive()) {
601 ShutdownProxiesIfLastActiveFrameInSiteInstance(old_render_frame_host.get());
602 return;
605 // If there are no active frames besides this one, we can delete the old
606 // RenderFrameHost once it runs its unload handler, without replacing it with
607 // a proxy.
608 size_t active_frame_count =
609 old_render_frame_host->GetSiteInstance()->active_frame_count();
610 if (active_frame_count <= 1) {
611 // Clear out any proxies from this SiteInstance, in case this was the
612 // last one keeping other proxies alive.
613 ShutdownProxiesIfLastActiveFrameInSiteInstance(old_render_frame_host.get());
615 // Tell the old RenderFrameHost to swap out, with no proxy to replace it.
616 old_render_frame_host->SwapOut(NULL, true);
617 MoveToPendingDeleteHosts(old_render_frame_host.Pass());
618 return;
621 // Otherwise there are active views and we need a proxy for the old RFH.
622 // (There should not be one yet.)
623 CHECK(!GetRenderFrameProxyHost(old_render_frame_host->GetSiteInstance()));
624 RenderFrameProxyHost* proxy = new RenderFrameProxyHost(
625 old_render_frame_host->GetSiteInstance(), frame_tree_node_);
626 CHECK(proxy_hosts_.insert(std::make_pair(old_site_instance_id, proxy)).second)
627 << "Inserting a duplicate item.";
629 // Tell the old RenderFrameHost to swap out and be replaced by the proxy.
630 old_render_frame_host->SwapOut(proxy, true);
632 // SwapOut creates a RenderFrameProxy, so set the proxy to be initialized.
633 proxy->set_render_frame_proxy_created(true);
635 bool is_main_frame = frame_tree_node_->IsMainFrame();
636 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
637 switches::kSitePerProcess) &&
638 !is_main_frame) {
639 // In --site-per-process, subframes delete their RFH rather than storing it
640 // in the proxy. Schedule it for deletion once the SwapOutACK comes in.
641 // TODO(creis): This will be the default when we remove swappedout://.
642 MoveToPendingDeleteHosts(old_render_frame_host.Pass());
643 } else {
644 // We shouldn't get here for subframes, since we only swap subframes when
645 // --site-per-process is used.
646 DCHECK(is_main_frame);
648 // The old RenderFrameHost will stay alive inside the proxy so that existing
649 // JavaScript window references to it stay valid.
650 proxy->TakeFrameHostOwnership(old_render_frame_host.Pass());
654 void RenderFrameHostManager::DiscardUnusedFrame(
655 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
656 // TODO(carlosk): this code is very similar to what can be found in
657 // SwapOutOldFrame and we should see that these are unified at some point.
659 // If the SiteInstance for the pending RFH is being used by others don't
660 // delete the RFH. Just swap it out and it can be reused at a later point.
661 SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance();
662 if (site_instance->HasSite() && site_instance->active_frame_count() > 1) {
663 // Any currently suspended navigations are no longer needed.
664 render_frame_host->CancelSuspendedNavigations();
666 RenderFrameProxyHost* proxy =
667 new RenderFrameProxyHost(site_instance, frame_tree_node_);
668 proxy_hosts_[site_instance->GetId()] = proxy;
670 // Check if the RenderFrameHost is already swapped out, to avoid swapping it
671 // out again.
672 if (!render_frame_host->is_swapped_out())
673 render_frame_host->SwapOut(proxy, false);
675 if (frame_tree_node_->IsMainFrame())
676 proxy->TakeFrameHostOwnership(render_frame_host.Pass());
677 } else {
678 // We won't be coming back, so delete this one.
679 ShutdownProxiesIfLastActiveFrameInSiteInstance(render_frame_host.get());
680 render_frame_host.reset();
684 void RenderFrameHostManager::MoveToPendingDeleteHosts(
685 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
686 // |render_frame_host| will be deleted when its SwapOut ACK is received, or
687 // when the timer times out, or when the RFHM itself is deleted (whichever
688 // comes first).
689 pending_delete_hosts_.push_back(
690 linked_ptr<RenderFrameHostImpl>(render_frame_host.release()));
693 bool RenderFrameHostManager::IsPendingDeletion(
694 RenderFrameHostImpl* render_frame_host) {
695 for (const auto& rfh : pending_delete_hosts_) {
696 if (rfh == render_frame_host)
697 return true;
699 return false;
702 bool RenderFrameHostManager::DeleteFromPendingList(
703 RenderFrameHostImpl* render_frame_host) {
704 for (RFHPendingDeleteList::iterator iter = pending_delete_hosts_.begin();
705 iter != pending_delete_hosts_.end();
706 iter++) {
707 if (*iter == render_frame_host) {
708 pending_delete_hosts_.erase(iter);
709 return true;
712 return false;
715 void RenderFrameHostManager::ResetProxyHosts() {
716 STLDeleteValues(&proxy_hosts_);
719 // PlzNavigate
720 void RenderFrameHostManager::BeginNavigation(const NavigationRequest& request) {
721 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
722 switches::kEnableBrowserSideNavigation));
723 // Clean up any state in case there's an ongoing navigation.
724 // TODO(carlosk): remove this cleanup here once we properly cancel ongoing
725 // navigations.
726 CleanUpNavigation();
728 RenderFrameHostImpl* dest_rfh = GetFrameHostForNavigation(request);
729 DCHECK(dest_rfh);
732 // PlzNavigate
733 RenderFrameHostImpl* RenderFrameHostManager::GetFrameHostForNavigation(
734 const NavigationRequest& request) {
735 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
736 switches::kEnableBrowserSideNavigation));
738 SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance();
740 SiteInstance* candidate_site_instance =
741 speculative_render_frame_host_
742 ? speculative_render_frame_host_->GetSiteInstance()
743 : nullptr;
745 scoped_refptr<SiteInstance> dest_site_instance = GetSiteInstanceForNavigation(
746 request.common_params().url, request.source_site_instance(),
747 request.dest_site_instance(), candidate_site_instance,
748 request.common_params().transition,
749 request.restore_type() != NavigationEntryImpl::RESTORE_NONE,
750 request.is_view_source());
752 // The appropriate RenderFrameHost to commit the navigation.
753 RenderFrameHostImpl* navigation_rfh = nullptr;
755 // Renderer-initiated navigations that may require a SiteInstance swap are
756 // sent to the browser via the OpenURL IPC and are afterwards treated as
757 // browser-initiated navigations. NavigationRequests marked as
758 // renderer-initiated are created by receiving a BeginNavigation IPC, and will
759 // then proceed in the same renderer that sent the IPC due to the condition
760 // below.
761 // TODO(carlosk): Once there is support for cross-process scripting check for
762 // non-browser-initiated navigations should be removed (see crbug.com/440266).
763 if (current_site_instance == dest_site_instance.get() ||
764 !request.browser_initiated() ||
765 (!frame_tree_node_->IsMainFrame() &&
766 !base::CommandLine::ForCurrentProcess()->HasSwitch(
767 switches::kSitePerProcess))) {
768 // Reuse the current RFH if its SiteInstance matches the the navigation's
769 // or if this is a subframe navigation. We only swap RFHs for subframes when
770 // --site-per-process is enabled.
771 CleanUpNavigation();
772 navigation_rfh = render_frame_host_.get();
774 // As SiteInstances are the same, check if the WebUI should be reused.
775 const NavigationEntry* current_navigation_entry =
776 delegate_->GetLastCommittedNavigationEntryForRenderManager();
777 should_reuse_web_ui_ = ShouldReuseWebUI(current_navigation_entry,
778 request.common_params().url);
779 if (!should_reuse_web_ui_) {
780 speculative_web_ui_ = CreateWebUI(request.common_params().url,
781 request.bindings());
782 // Make sure the current RenderViewHost has the right bindings.
783 if (speculative_web_ui() &&
784 !render_frame_host_->GetProcess()->IsIsolatedGuest()) {
785 render_frame_host_->render_view_host()->AllowBindings(
786 speculative_web_ui()->GetBindings());
789 } else {
790 // If the SiteInstance for the final URL doesn't match the one from the
791 // speculatively created RenderFrameHost, create a new RenderFrameHost using
792 // this new SiteInstance.
793 if (!speculative_render_frame_host_ ||
794 speculative_render_frame_host_->GetSiteInstance() !=
795 dest_site_instance.get()) {
796 CleanUpNavigation();
797 bool success = CreateSpeculativeRenderFrameHost(
798 request.common_params().url, current_site_instance,
799 dest_site_instance.get(), request.bindings());
800 DCHECK(success);
802 DCHECK(speculative_render_frame_host_);
803 navigation_rfh = speculative_render_frame_host_.get();
805 // Check if our current RFH is live.
806 if (!render_frame_host_->IsRenderFrameLive()) {
807 // The current RFH is not live. There's no reason to sit around with a
808 // sad tab or a newly created RFH while we wait for the navigation to
809 // complete. Just switch to the speculative RFH now and go back to normal.
810 // (Note that we don't care about on{before}unload handlers if the current
811 // RFH isn't live.)
812 CommitPending();
815 DCHECK(navigation_rfh &&
816 (navigation_rfh == render_frame_host_.get() ||
817 navigation_rfh == speculative_render_frame_host_.get()));
819 // If the RenderFrame that needs to navigate is not live (its process was just
820 // created or has crashed), initialize it.
821 if (!navigation_rfh->IsRenderFrameLive()) {
822 // Recreate the opener chain.
823 int opener_route_id = delegate_->CreateOpenerRenderViewsForRenderManager(
824 navigation_rfh->GetSiteInstance());
825 if (!InitRenderView(navigation_rfh->render_view_host(), opener_route_id,
826 MSG_ROUTING_NONE, frame_tree_node_->IsMainFrame())) {
827 return nullptr;
830 if (navigation_rfh == render_frame_host_) {
831 // TODO(nasko): This is a very ugly hack. The Chrome extensions process
832 // manager still uses NotificationService and expects to see a
833 // RenderViewHost changed notification after WebContents and
834 // RenderFrameHostManager are completely initialized. This should be
835 // removed once the process manager moves away from NotificationService.
836 // See https://crbug.com/462682.
837 delegate_->NotifyMainFrameSwappedFromRenderManager(
838 nullptr, render_frame_host_->render_view_host());
842 return navigation_rfh;
845 // PlzNavigate
846 void RenderFrameHostManager::CleanUpNavigation() {
847 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
848 switches::kEnableBrowserSideNavigation));
849 speculative_web_ui_.reset();
850 should_reuse_web_ui_ = false;
851 if (speculative_render_frame_host_)
852 DiscardUnusedFrame(UnsetSpeculativeRenderFrameHost());
855 // PlzNavigate
856 scoped_ptr<RenderFrameHostImpl>
857 RenderFrameHostManager::UnsetSpeculativeRenderFrameHost() {
858 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
859 switches::kEnableBrowserSideNavigation));
860 speculative_render_frame_host_->GetProcess()->RemovePendingView();
861 return speculative_render_frame_host_.Pass();
864 void RenderFrameHostManager::OnDidStartLoading() {
865 for (const auto& pair : proxy_hosts_) {
866 pair.second->Send(
867 new FrameMsg_DidStartLoading(pair.second->GetRoutingID()));
871 void RenderFrameHostManager::OnDidStopLoading() {
872 for (const auto& pair : proxy_hosts_) {
873 pair.second->Send(new FrameMsg_DidStopLoading(pair.second->GetRoutingID()));
877 void RenderFrameHostManager::OnDidUpdateName(const std::string& name) {
878 // The window.name message may be sent outside of --site-per-process when
879 // report_frame_name_changes renderer preference is set (used by
880 // WebView). Don't send the update to proxies in those cases.
881 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
882 switches::kSitePerProcess))
883 return;
885 for (const auto& pair : proxy_hosts_) {
886 pair.second->Send(
887 new FrameMsg_DidUpdateName(pair.second->GetRoutingID(), name));
891 void RenderFrameHostManager::Observe(
892 int type,
893 const NotificationSource& source,
894 const NotificationDetails& details) {
895 switch (type) {
896 case NOTIFICATION_RENDERER_PROCESS_CLOSED:
897 case NOTIFICATION_RENDERER_PROCESS_CLOSING:
898 RendererProcessClosing(
899 Source<RenderProcessHost>(source).ptr());
900 break;
902 default:
903 NOTREACHED();
907 RenderFrameHostManager::SiteInstanceDescriptor::SiteInstanceDescriptor(
908 BrowserContext* browser_context,
909 GURL dest_url,
910 bool related_to_current)
911 : existing_site_instance(nullptr),
912 new_is_related_to_current(related_to_current) {
913 new_site_url = SiteInstance::GetSiteForURL(browser_context, dest_url);
916 // static
917 bool RenderFrameHostManager::ClearProxiesInSiteInstance(
918 int32 site_instance_id,
919 FrameTreeNode* node) {
920 RenderFrameProxyHostMap::iterator iter =
921 node->render_manager()->proxy_hosts_.find(site_instance_id);
922 if (iter != node->render_manager()->proxy_hosts_.end()) {
923 RenderFrameProxyHost* proxy = iter->second;
924 // Delete the proxy. If it is for a main frame (and thus the RFH is stored
925 // in the proxy) and it was still pending swap out, move the RFH to the
926 // pending deletion list first.
927 if (node->IsMainFrame() &&
928 proxy->render_frame_host()->rfh_state() ==
929 RenderFrameHostImpl::STATE_PENDING_SWAP_OUT) {
930 scoped_ptr<RenderFrameHostImpl> swapped_out_rfh =
931 proxy->PassFrameHostOwnership();
932 node->render_manager()->MoveToPendingDeleteHosts(swapped_out_rfh.Pass());
934 delete proxy;
935 node->render_manager()->proxy_hosts_.erase(site_instance_id);
938 return true;
941 // static.
942 bool RenderFrameHostManager::ResetProxiesInSiteInstance(int32 site_instance_id,
943 FrameTreeNode* node) {
944 RenderFrameProxyHostMap::iterator iter =
945 node->render_manager()->proxy_hosts_.find(site_instance_id);
946 if (iter != node->render_manager()->proxy_hosts_.end())
947 iter->second->set_render_frame_proxy_created(false);
949 return true;
952 bool RenderFrameHostManager::ShouldTransitionCrossSite() {
953 // True for --site-per-process, which overrides both kSingleProcess and
954 // kProcessPerTab.
955 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
956 switches::kSitePerProcess))
957 return true;
959 // False in the single-process mode, as it makes RVHs to accumulate
960 // in swapped_out_hosts_.
961 // True if we are using process-per-site-instance (default) or
962 // process-per-site (kProcessPerSite).
963 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
964 switches::kSingleProcess) &&
965 !base::CommandLine::ForCurrentProcess()->HasSwitch(
966 switches::kProcessPerTab);
969 bool RenderFrameHostManager::ShouldSwapBrowsingInstancesForNavigation(
970 const GURL& current_effective_url,
971 bool current_is_view_source_mode,
972 SiteInstance* new_site_instance,
973 const GURL& new_effective_url,
974 bool new_is_view_source_mode) const {
975 // If new_entry already has a SiteInstance, assume it is correct. We only
976 // need to force a swap if it is in a different BrowsingInstance.
977 if (new_site_instance) {
978 return !new_site_instance->IsRelatedSiteInstance(
979 render_frame_host_->GetSiteInstance());
982 // Check for reasons to swap processes even if we are in a process model that
983 // doesn't usually swap (e.g., process-per-tab). Any time we return true,
984 // the new_entry will be rendered in a new SiteInstance AND BrowsingInstance.
985 BrowserContext* browser_context =
986 delegate_->GetControllerForRenderManager().GetBrowserContext();
988 // Don't force a new BrowsingInstance for debug URLs that are handled in the
989 // renderer process, like javascript: or chrome://crash.
990 if (IsRendererDebugURL(new_effective_url))
991 return false;
993 // For security, we should transition between processes when one is a Web UI
994 // page and one isn't.
995 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
996 render_frame_host_->GetProcess()->GetID()) ||
997 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
998 browser_context, current_effective_url)) {
999 // If so, force a swap if destination is not an acceptable URL for Web UI.
1000 // Here, data URLs are never allowed.
1001 if (!WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
1002 browser_context, new_effective_url)) {
1003 return true;
1005 } else {
1006 // Force a swap if it's a Web UI URL.
1007 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1008 browser_context, new_effective_url)) {
1009 return true;
1013 // Check with the content client as well. Important to pass
1014 // current_effective_url here, which uses the SiteInstance's site if there is
1015 // no current_entry.
1016 if (GetContentClient()->browser()->ShouldSwapBrowsingInstancesForNavigation(
1017 render_frame_host_->GetSiteInstance(),
1018 current_effective_url, new_effective_url)) {
1019 return true;
1022 // We can't switch a RenderView between view source and non-view source mode
1023 // without screwing up the session history sometimes (when navigating between
1024 // "view-source:http://foo.com/" and "http://foo.com/", Blink doesn't treat
1025 // it as a new navigation). So require a BrowsingInstance switch.
1026 if (current_is_view_source_mode != new_is_view_source_mode)
1027 return true;
1029 return false;
1032 bool RenderFrameHostManager::ShouldReuseWebUI(
1033 const NavigationEntry* current_entry,
1034 const GURL& new_url) const {
1035 NavigationControllerImpl& controller =
1036 delegate_->GetControllerForRenderManager();
1037 return current_entry && web_ui_ &&
1038 (WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
1039 controller.GetBrowserContext(), current_entry->GetURL()) ==
1040 WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
1041 controller.GetBrowserContext(), new_url));
1044 SiteInstance* RenderFrameHostManager::GetSiteInstanceForNavigation(
1045 const GURL& dest_url,
1046 SiteInstance* source_instance,
1047 SiteInstance* dest_instance,
1048 SiteInstance* candidate_instance,
1049 ui::PageTransition transition,
1050 bool dest_is_restore,
1051 bool dest_is_view_source_mode) {
1052 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1054 // We do not currently swap processes for navigations in webview tag guests.
1055 if (current_instance->GetSiteURL().SchemeIs(kGuestScheme))
1056 return current_instance;
1058 // Determine if we need a new BrowsingInstance for this entry. If true, this
1059 // implies that it will get a new SiteInstance (and likely process), and that
1060 // other tabs in the current BrowsingInstance will be unable to script it.
1061 // This is used for cases that require a process swap even in the
1062 // process-per-tab model, such as WebUI pages.
1063 // TODO(clamy): Remove the dependency on the current entry.
1064 const NavigationEntry* current_entry =
1065 delegate_->GetLastCommittedNavigationEntryForRenderManager();
1066 BrowserContext* browser_context =
1067 delegate_->GetControllerForRenderManager().GetBrowserContext();
1068 const GURL& current_effective_url = current_entry ?
1069 SiteInstanceImpl::GetEffectiveURL(browser_context,
1070 current_entry->GetURL()) :
1071 render_frame_host_->GetSiteInstance()->GetSiteURL();
1072 bool current_is_view_source_mode = current_entry ?
1073 current_entry->IsViewSourceMode() : dest_is_view_source_mode;
1074 bool force_swap = ShouldSwapBrowsingInstancesForNavigation(
1075 current_effective_url,
1076 current_is_view_source_mode,
1077 dest_instance,
1078 SiteInstanceImpl::GetEffectiveURL(browser_context, dest_url),
1079 dest_is_view_source_mode);
1080 SiteInstanceDescriptor new_instance_descriptor =
1081 SiteInstanceDescriptor(current_instance);
1082 if (ShouldTransitionCrossSite() || force_swap) {
1083 new_instance_descriptor = DetermineSiteInstanceForURL(
1084 dest_url, source_instance, current_instance, dest_instance, transition,
1085 dest_is_restore, dest_is_view_source_mode, force_swap);
1088 SiteInstance* new_instance =
1089 ConvertToSiteInstance(new_instance_descriptor, candidate_instance);
1091 // If |force_swap| is true, we must use a different SiteInstance than the
1092 // current one. If we didn't, we would have two RenderFrameHosts in the same
1093 // SiteInstance and the same frame, resulting in page_id conflicts for their
1094 // NavigationEntries.
1095 if (force_swap)
1096 CHECK_NE(new_instance, current_instance);
1097 return new_instance;
1100 RenderFrameHostManager::SiteInstanceDescriptor
1101 RenderFrameHostManager::DetermineSiteInstanceForURL(
1102 const GURL& dest_url,
1103 SiteInstance* source_instance,
1104 SiteInstance* current_instance,
1105 SiteInstance* dest_instance,
1106 ui::PageTransition transition,
1107 bool dest_is_restore,
1108 bool dest_is_view_source_mode,
1109 bool force_browsing_instance_swap) {
1110 SiteInstanceImpl* current_instance_impl =
1111 static_cast<SiteInstanceImpl*>(current_instance);
1112 NavigationControllerImpl& controller =
1113 delegate_->GetControllerForRenderManager();
1114 BrowserContext* browser_context = controller.GetBrowserContext();
1116 // If the entry has an instance already we should use it.
1117 if (dest_instance) {
1118 // If we are forcing a swap, this should be in a different BrowsingInstance.
1119 if (force_browsing_instance_swap) {
1120 CHECK(!dest_instance->IsRelatedSiteInstance(
1121 render_frame_host_->GetSiteInstance()));
1123 return SiteInstanceDescriptor(dest_instance);
1126 // If a swap is required, we need to force the SiteInstance AND
1127 // BrowsingInstance to be different ones, using CreateForURL.
1128 if (force_browsing_instance_swap)
1129 return SiteInstanceDescriptor(browser_context, dest_url, false);
1131 // (UGLY) HEURISTIC, process-per-site only:
1133 // If this navigation is generated, then it probably corresponds to a search
1134 // query. Given that search results typically lead to users navigating to
1135 // other sites, we don't really want to use the search engine hostname to
1136 // determine the site instance for this navigation.
1138 // NOTE: This can be removed once we have a way to transition between
1139 // RenderViews in response to a link click.
1141 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1142 switches::kProcessPerSite) &&
1143 ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_GENERATED)) {
1144 return SiteInstanceDescriptor(current_instance_impl);
1147 // If we haven't used our SiteInstance (and thus RVH) yet, then we can use it
1148 // for this entry. We won't commit the SiteInstance to this site until the
1149 // navigation commits (in DidNavigate), unless the navigation entry was
1150 // restored or it's a Web UI as described below.
1151 if (!current_instance_impl->HasSite()) {
1152 // If we've already created a SiteInstance for our destination, we don't
1153 // want to use this unused SiteInstance; use the existing one. (We don't
1154 // do this check if the current_instance has a site, because for now, we
1155 // want to compare against the current URL and not the SiteInstance's site.
1156 // In this case, there is no current URL, so comparing against the site is
1157 // ok. See additional comments below.)
1159 // Also, if the URL should use process-per-site mode and there is an
1160 // existing process for the site, we should use it. We can call
1161 // GetRelatedSiteInstance() for this, which will eagerly set the site and
1162 // thus use the correct process.
1163 bool use_process_per_site =
1164 RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) &&
1165 RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url);
1166 if (current_instance_impl->HasRelatedSiteInstance(dest_url) ||
1167 use_process_per_site) {
1168 return SiteInstanceDescriptor(browser_context, dest_url, true);
1171 // For extensions, Web UI URLs (such as the new tab page), and apps we do
1172 // not want to use the |current_instance_impl| if it has no site, since it
1173 // will have a RenderProcessHost of PRIV_NORMAL. Create a new SiteInstance
1174 // for this URL instead (with the correct process type).
1175 if (current_instance_impl->HasWrongProcessForURL(dest_url))
1176 return SiteInstanceDescriptor(browser_context, dest_url, true);
1178 // View-source URLs must use a new SiteInstance and BrowsingInstance.
1179 // TODO(nasko): This is the same condition as later in the function. This
1180 // should be taken into account when refactoring this method as part of
1181 // http://crbug.com/123007.
1182 if (dest_is_view_source_mode)
1183 return SiteInstanceDescriptor(browser_context, dest_url, false);
1185 // If we are navigating from a blank SiteInstance to a WebUI, make sure we
1186 // create a new SiteInstance.
1187 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1188 browser_context, dest_url)) {
1189 return SiteInstanceDescriptor(browser_context, dest_url, false);
1192 // Normally the "site" on the SiteInstance is set lazily when the load
1193 // actually commits. This is to support better process sharing in case
1194 // the site redirects to some other site: we want to use the destination
1195 // site in the site instance.
1197 // In the case of session restore, as it loads all the pages immediately
1198 // we need to set the site first, otherwise after a restore none of the
1199 // pages would share renderers in process-per-site.
1201 // The embedder can request some urls never to be assigned to SiteInstance
1202 // through the ShouldAssignSiteForURL() content client method, so that
1203 // renderers created for particular chrome urls (e.g. the chrome-native://
1204 // scheme) can be reused for subsequent navigations in the same WebContents.
1205 // See http://crbug.com/386542.
1206 if (dest_is_restore &&
1207 GetContentClient()->browser()->ShouldAssignSiteForURL(dest_url)) {
1208 current_instance_impl->SetSite(dest_url);
1211 return SiteInstanceDescriptor(current_instance_impl);
1214 // Otherwise, only create a new SiteInstance for a cross-process navigation.
1216 // TODO(creis): Once we intercept links and script-based navigations, we
1217 // will be able to enforce that all entries in a SiteInstance actually have
1218 // the same site, and it will be safe to compare the URL against the
1219 // SiteInstance's site, as follows:
1220 // const GURL& current_url = current_instance_impl->site();
1221 // For now, though, we're in a hybrid model where you only switch
1222 // SiteInstances if you type in a cross-site URL. This means we have to
1223 // compare the entry's URL to the last committed entry's URL.
1224 NavigationEntry* current_entry = controller.GetLastCommittedEntry();
1225 if (interstitial_page_) {
1226 // The interstitial is currently the last committed entry, but we want to
1227 // compare against the last non-interstitial entry.
1228 current_entry = controller.GetEntryAtOffset(-1);
1231 // View-source URLs must use a new SiteInstance and BrowsingInstance.
1232 // We don't need a swap when going from view-source to a debug URL like
1233 // chrome://crash, however.
1234 // TODO(creis): Refactor this method so this duplicated code isn't needed.
1235 // See http://crbug.com/123007.
1236 if (current_entry &&
1237 current_entry->IsViewSourceMode() != dest_is_view_source_mode &&
1238 !IsRendererDebugURL(dest_url)) {
1239 return SiteInstanceDescriptor(browser_context, dest_url, false);
1242 // Use the source SiteInstance in case of data URLs or about:blank pages,
1243 // because the content is then controlled and/or scriptable by the source
1244 // SiteInstance.
1245 GURL about_blank(url::kAboutBlankURL);
1246 if (source_instance &&
1247 (dest_url == about_blank || dest_url.scheme() == url::kDataScheme)) {
1248 return SiteInstanceDescriptor(source_instance);
1251 // Use the current SiteInstance for same site navigations, as long as the
1252 // process type is correct. (The URL may have been installed as an app since
1253 // the last time we visited it.)
1254 const GURL& current_url =
1255 GetCurrentURLForSiteInstance(current_instance_impl, current_entry);
1256 if (SiteInstance::IsSameWebSite(browser_context, current_url, dest_url) &&
1257 !current_instance_impl->HasWrongProcessForURL(dest_url)) {
1258 return SiteInstanceDescriptor(current_instance_impl);
1261 // Start the new renderer in a new SiteInstance, but in the current
1262 // BrowsingInstance. It is important to immediately give this new
1263 // SiteInstance to a RenderViewHost (if it is different than our current
1264 // SiteInstance), so that it is ref counted. This will happen in
1265 // CreateRenderView.
1266 return SiteInstanceDescriptor(browser_context, dest_url, true);
1269 SiteInstance* RenderFrameHostManager::ConvertToSiteInstance(
1270 const SiteInstanceDescriptor& descriptor,
1271 SiteInstance* candidate_instance) {
1272 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1274 // Note: If the |candidate_instance| matches the descriptor, it will already
1275 // be set to |descriptor.existing_site_instance|.
1276 if (descriptor.existing_site_instance)
1277 return descriptor.existing_site_instance;
1279 // Note: If the |candidate_instance| matches the descriptor,
1280 // GetRelatedSiteInstance will return it.
1281 if (descriptor.new_is_related_to_current)
1282 return current_instance->GetRelatedSiteInstance(descriptor.new_site_url);
1284 // At this point we know an unrelated site instance must be returned. First
1285 // check if the candidate matches.
1286 if (candidate_instance &&
1287 !current_instance->IsRelatedSiteInstance(candidate_instance) &&
1288 candidate_instance->GetSiteURL() == descriptor.new_site_url) {
1289 return candidate_instance;
1292 // Otherwise return a newly created one.
1293 return SiteInstance::CreateForURL(
1294 delegate_->GetControllerForRenderManager().GetBrowserContext(),
1295 descriptor.new_site_url);
1298 const GURL& RenderFrameHostManager::GetCurrentURLForSiteInstance(
1299 SiteInstance* current_instance, NavigationEntry* current_entry) {
1300 // If this is a subframe that is potentially out of process from its parent,
1301 // don't consider using current_entry's url for SiteInstance selection, since
1302 // current_entry's url is for the main frame and may be in a different site
1303 // than this frame.
1304 // TODO(creis): Remove this when we can check the FrameNavigationEntry's url.
1305 // See http://crbug.com/369654
1306 if (!frame_tree_node_->IsMainFrame() &&
1307 base::CommandLine::ForCurrentProcess()->HasSwitch(
1308 switches::kSitePerProcess))
1309 return frame_tree_node_->current_url();
1311 // If there is no last non-interstitial entry (and current_instance already
1312 // has a site), then we must have been opened from another tab. We want
1313 // to compare against the URL of the page that opened us, but we can't
1314 // get to it directly. The best we can do is check against the site of
1315 // the SiteInstance. This will be correct when we intercept links and
1316 // script-based navigations, but for now, it could place some pages in a
1317 // new process unnecessarily. We should only hit this case if a page tries
1318 // to open a new tab to an interstitial-inducing URL, and then navigates
1319 // the page to a different same-site URL. (This seems very unlikely in
1320 // practice.)
1321 if (current_entry)
1322 return current_entry->GetURL();
1323 return current_instance->GetSiteURL();
1326 void RenderFrameHostManager::CreatePendingRenderFrameHost(
1327 SiteInstance* old_instance,
1328 SiteInstance* new_instance,
1329 bool is_main_frame) {
1330 int create_render_frame_flags = 0;
1331 if (is_main_frame)
1332 create_render_frame_flags |= CREATE_RF_FOR_MAIN_FRAME_NAVIGATION;
1334 if (delegate_->IsHidden())
1335 create_render_frame_flags |= CREATE_RF_HIDDEN;
1337 int opener_route_id = CreateOpenerRenderViewsIfNeeded(
1338 old_instance, new_instance, &create_render_frame_flags);
1340 if (pending_render_frame_host_)
1341 CancelPending();
1343 // Create a non-swapped-out RFH with the given opener.
1344 pending_render_frame_host_ =
1345 CreateRenderFrame(new_instance, pending_web_ui(), opener_route_id,
1346 create_render_frame_flags, nullptr);
1349 int RenderFrameHostManager::CreateOpenerRenderViewsIfNeeded(
1350 SiteInstance* old_instance,
1351 SiteInstance* new_instance,
1352 int* create_render_frame_flags) {
1353 int opener_route_id = MSG_ROUTING_NONE;
1354 // Only create opener proxies if they are in the same BrowsingInstance.
1355 if (new_instance->IsRelatedSiteInstance(old_instance)) {
1356 opener_route_id =
1357 delegate_->CreateOpenerRenderViewsForRenderManager(new_instance);
1359 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1360 switches::kSitePerProcess)) {
1361 // Ensure that the frame tree has RenderFrameProxyHosts for the new
1362 // SiteInstance in all nodes except the current one. We do this for all
1363 // frames in the tree, whether they are in the same BrowsingInstance or not.
1364 // We will still check whether two frames are in the same BrowsingInstance
1365 // before we allow them to interact (e.g., postMessage).
1366 frame_tree_node_->frame_tree()->CreateProxiesForSiteInstance(
1367 frame_tree_node_, new_instance);
1368 // RenderFrames in different processes from their parent RenderFrames
1369 // in the frame tree require RenderWidgets for rendering and processing
1370 // input events.
1371 if (frame_tree_node_->parent() &&
1372 frame_tree_node_->parent()->current_frame_host()->GetSiteInstance() !=
1373 new_instance)
1374 *create_render_frame_flags |= CREATE_RF_NEEDS_RENDER_WIDGET_HOST;
1376 return opener_route_id;
1379 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::CreateRenderFrameHost(
1380 SiteInstance* site_instance,
1381 int view_routing_id,
1382 int frame_routing_id,
1383 int flags) {
1384 if (frame_routing_id == MSG_ROUTING_NONE)
1385 frame_routing_id = site_instance->GetProcess()->GetNextRoutingID();
1387 bool swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
1388 bool hidden = !!(flags & CREATE_RF_HIDDEN);
1390 // Create a RVH for main frames, or find the existing one for subframes.
1391 FrameTree* frame_tree = frame_tree_node_->frame_tree();
1392 RenderViewHostImpl* render_view_host = nullptr;
1393 if (frame_tree_node_->IsMainFrame()) {
1394 render_view_host = frame_tree->CreateRenderViewHost(
1395 site_instance, view_routing_id, frame_routing_id, swapped_out, hidden);
1396 } else {
1397 render_view_host = frame_tree->GetRenderViewHost(site_instance);
1399 CHECK(render_view_host);
1402 // TODO(creis): Pass hidden to RFH.
1403 scoped_ptr<RenderFrameHostImpl> render_frame_host = make_scoped_ptr(
1404 RenderFrameHostFactory::Create(
1405 site_instance, render_view_host, render_frame_delegate_,
1406 render_widget_delegate_, frame_tree, frame_tree_node_,
1407 frame_routing_id, flags).release());
1408 return render_frame_host.Pass();
1411 // PlzNavigate
1412 bool RenderFrameHostManager::CreateSpeculativeRenderFrameHost(
1413 const GURL& url,
1414 SiteInstance* old_instance,
1415 SiteInstance* new_instance,
1416 int bindings) {
1417 CHECK(new_instance);
1418 CHECK_NE(old_instance, new_instance);
1419 CHECK(!should_reuse_web_ui_);
1421 // Note: |speculative_web_ui_| must be initialized before starting the
1422 // |speculative_render_frame_host_| creation steps otherwise the WebUI
1423 // won't be properly initialized.
1424 speculative_web_ui_ = CreateWebUI(url, bindings);
1426 int create_render_frame_flags = 0;
1427 int opener_route_id =
1428 CreateOpenerRenderViewsIfNeeded(old_instance, new_instance,
1429 &create_render_frame_flags);
1431 if (frame_tree_node_->IsMainFrame())
1432 create_render_frame_flags |= CREATE_RF_FOR_MAIN_FRAME_NAVIGATION;
1433 if (delegate_->IsHidden())
1434 create_render_frame_flags |= CREATE_RF_HIDDEN;
1435 speculative_render_frame_host_ =
1436 CreateRenderFrame(new_instance, speculative_web_ui_.get(),
1437 opener_route_id, create_render_frame_flags, nullptr);
1439 if (!speculative_render_frame_host_) {
1440 speculative_web_ui_.reset();
1441 return false;
1443 return true;
1446 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::CreateRenderFrame(
1447 SiteInstance* instance,
1448 WebUIImpl* web_ui,
1449 int opener_route_id,
1450 int flags,
1451 int* view_routing_id_ptr) {
1452 bool swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
1453 CHECK(instance);
1454 // Swapped out views should always be hidden.
1455 DCHECK(!swapped_out || (flags & CREATE_RF_HIDDEN));
1457 // TODO(nasko): Remove the following CHECK once cross-process navigation no
1458 // longer relies on swapped out RFH for the top-level frame.
1459 if (!frame_tree_node_->IsMainFrame())
1460 CHECK(!swapped_out);
1462 scoped_ptr<RenderFrameHostImpl> new_render_frame_host;
1463 bool success = true;
1464 if (view_routing_id_ptr)
1465 *view_routing_id_ptr = MSG_ROUTING_NONE;
1467 // We are creating a pending, speculative or swapped out RFH here. We should
1468 // never create it in the same SiteInstance as our current RFH.
1469 CHECK_NE(render_frame_host_->GetSiteInstance(), instance);
1471 // Check if we've already created an RFH for this SiteInstance. If so, try
1472 // to re-use the existing one, which has already been initialized. We'll
1473 // remove it from the list of proxy hosts below if it will be active.
1474 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1475 if (proxy && proxy->render_frame_host()) {
1476 if (view_routing_id_ptr)
1477 *view_routing_id_ptr = proxy->GetRenderViewHost()->GetRoutingID();
1478 // Delete the existing RenderFrameProxyHost, but reuse the RenderFrameHost.
1479 // Prevent the process from exiting while we're trying to use it.
1480 if (!swapped_out) {
1481 new_render_frame_host = proxy->PassFrameHostOwnership();
1482 new_render_frame_host->GetProcess()->AddPendingView();
1484 proxy_hosts_.erase(instance->GetId());
1485 delete proxy;
1487 // When a new render view is created by the renderer, the new WebContents
1488 // gets a RenderViewHost in the SiteInstance of its opener WebContents.
1489 // If not used in the first navigation, this RVH is swapped out and is not
1490 // granted bindings, so we may need to grant them when swapping it in.
1491 if (web_ui && !new_render_frame_host->GetProcess()->IsIsolatedGuest()) {
1492 int required_bindings = web_ui->GetBindings();
1493 RenderViewHost* render_view_host =
1494 new_render_frame_host->render_view_host();
1495 if ((render_view_host->GetEnabledBindings() & required_bindings) !=
1496 required_bindings) {
1497 render_view_host->AllowBindings(required_bindings);
1501 } else {
1502 // Create a new RenderFrameHost if we don't find an existing one.
1503 new_render_frame_host = CreateRenderFrameHost(instance, MSG_ROUTING_NONE,
1504 MSG_ROUTING_NONE, flags);
1505 RenderViewHostImpl* render_view_host =
1506 new_render_frame_host->render_view_host();
1507 int proxy_routing_id = MSG_ROUTING_NONE;
1509 // Prevent the process from exiting while we're trying to navigate in it.
1510 // Otherwise, if the new RFH is swapped out already, store it.
1511 if (!swapped_out) {
1512 new_render_frame_host->GetProcess()->AddPendingView();
1513 } else {
1514 proxy = new RenderFrameProxyHost(
1515 new_render_frame_host->GetSiteInstance(), frame_tree_node_);
1516 proxy_hosts_[instance->GetId()] = proxy;
1517 proxy_routing_id = proxy->GetRoutingID();
1518 proxy->TakeFrameHostOwnership(new_render_frame_host.Pass());
1521 success =
1522 InitRenderView(render_view_host, opener_route_id, proxy_routing_id,
1523 !!(flags & CREATE_RF_FOR_MAIN_FRAME_NAVIGATION));
1524 if (success) {
1525 if (frame_tree_node_->IsMainFrame()) {
1526 // Don't show the main frame's view until we get a DidNavigate from it.
1527 // Only the RenderViewHost for the top-level RenderFrameHost has a
1528 // RenderWidgetHostView; RenderWidgetHosts for out-of-process iframes
1529 // will be created later and hidden.
1530 if (render_view_host->GetView())
1531 render_view_host->GetView()->Hide();
1532 } else if (!swapped_out) {
1533 // Init the RFH, so a RenderFrame is created in the renderer.
1534 DCHECK(new_render_frame_host);
1535 success = InitRenderFrame(new_render_frame_host.get());
1539 if (success) {
1540 if (view_routing_id_ptr)
1541 *view_routing_id_ptr = render_view_host->GetRoutingID();
1545 // Returns the new RFH if it isn't swapped out.
1546 if (success && !swapped_out) {
1547 DCHECK(new_render_frame_host->GetSiteInstance() == instance);
1548 return new_render_frame_host.Pass();
1550 return nullptr;
1553 int RenderFrameHostManager::CreateRenderFrameProxy(SiteInstance* instance) {
1554 // A RenderFrameProxyHost should never be created in the same SiteInstance as
1555 // the current RFH.
1556 CHECK(instance);
1557 CHECK_NE(instance, render_frame_host_->GetSiteInstance());
1559 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1560 if (proxy)
1561 return proxy->GetRoutingID();
1563 proxy = new RenderFrameProxyHost(instance, frame_tree_node_);
1564 proxy_hosts_[instance->GetId()] = proxy;
1565 proxy->InitRenderFrameProxy();
1566 return proxy->GetRoutingID();
1569 void RenderFrameHostManager::CreateProxiesForChildFrame(FrameTreeNode* child) {
1570 for (const auto& pair : proxy_hosts_) {
1571 child->render_manager()->CreateRenderFrameProxy(
1572 pair.second->GetSiteInstance());
1576 void RenderFrameHostManager::EnsureRenderViewInitialized(
1577 FrameTreeNode* source,
1578 RenderViewHostImpl* render_view_host,
1579 SiteInstance* instance) {
1580 DCHECK(frame_tree_node_->IsMainFrame());
1582 if (render_view_host->IsRenderViewLive())
1583 return;
1585 // Recreate the opener chain.
1586 int opener_route_id =
1587 delegate_->CreateOpenerRenderViewsForRenderManager(instance);
1588 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1589 InitRenderView(render_view_host, opener_route_id, proxy->GetRoutingID(),
1590 source->IsMainFrame());
1593 bool RenderFrameHostManager::InitRenderView(
1594 RenderViewHostImpl* render_view_host,
1595 int opener_route_id,
1596 int proxy_routing_id,
1597 bool for_main_frame_navigation) {
1598 // We may have initialized this RenderViewHost for another RenderFrameHost.
1599 if (render_view_host->IsRenderViewLive())
1600 return true;
1602 // If the ongoing navigation is to a WebUI and the RenderView is not in a
1603 // guest process, tell the RenderViewHost about any bindings it will need
1604 // enabled.
1605 WebUIImpl* dest_web_ui = nullptr;
1606 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1607 switches::kEnableBrowserSideNavigation)) {
1608 dest_web_ui =
1609 should_reuse_web_ui_ ? web_ui_.get() : speculative_web_ui_.get();
1610 } else {
1611 dest_web_ui = pending_web_ui();
1613 if (dest_web_ui && !render_view_host->GetProcess()->IsIsolatedGuest()) {
1614 render_view_host->AllowBindings(dest_web_ui->GetBindings());
1615 } else {
1616 // Ensure that we don't create an unprivileged RenderView in a WebUI-enabled
1617 // process unless it's swapped out.
1618 if (render_view_host->is_active()) {
1619 CHECK(!ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1620 render_view_host->GetProcess()->GetID()));
1624 return delegate_->CreateRenderViewForRenderManager(render_view_host,
1625 opener_route_id,
1626 proxy_routing_id,
1627 for_main_frame_navigation);
1630 bool RenderFrameHostManager::InitRenderFrame(
1631 RenderFrameHostImpl* render_frame_host) {
1632 if (render_frame_host->IsRenderFrameLive())
1633 return true;
1635 int parent_routing_id = MSG_ROUTING_NONE;
1636 int proxy_routing_id = MSG_ROUTING_NONE;
1637 if (frame_tree_node_->parent()) {
1638 parent_routing_id = frame_tree_node_->parent()->render_manager()->
1639 GetRoutingIdForSiteInstance(render_frame_host->GetSiteInstance());
1640 CHECK_NE(parent_routing_id, MSG_ROUTING_NONE);
1642 // Check whether there is an existing proxy for this frame in this
1643 // SiteInstance. If there is, the new RenderFrame needs to be able to find
1644 // the proxy it is replacing, so that it can fully initialize itself.
1645 // NOTE: This is the only time that a RenderFrameProxyHost can be in the same
1646 // SiteInstance as its RenderFrameHost. This is only the case until the
1647 // RenderFrameHost commits, at which point it will replace and delete the
1648 // RenderFrameProxyHost.
1649 RenderFrameProxyHost* existing_proxy =
1650 GetRenderFrameProxyHost(render_frame_host->GetSiteInstance());
1651 if (existing_proxy) {
1652 proxy_routing_id = existing_proxy->GetRoutingID();
1653 CHECK_NE(proxy_routing_id, MSG_ROUTING_NONE);
1654 if (!existing_proxy->is_render_frame_proxy_live())
1655 existing_proxy->InitRenderFrameProxy();
1657 return delegate_->CreateRenderFrameForRenderManager(render_frame_host,
1658 parent_routing_id,
1659 proxy_routing_id);
1662 int RenderFrameHostManager::GetRoutingIdForSiteInstance(
1663 SiteInstance* site_instance) {
1664 if (render_frame_host_->GetSiteInstance() == site_instance)
1665 return render_frame_host_->GetRoutingID();
1667 RenderFrameProxyHostMap::iterator iter =
1668 proxy_hosts_.find(site_instance->GetId());
1669 if (iter != proxy_hosts_.end())
1670 return iter->second->GetRoutingID();
1672 return MSG_ROUTING_NONE;
1675 void RenderFrameHostManager::CommitPending() {
1676 TRACE_EVENT1("navigation", "RenderFrameHostManager::CommitPending",
1677 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
1678 bool browser_side_navigation =
1679 base::CommandLine::ForCurrentProcess()->HasSwitch(
1680 switches::kEnableBrowserSideNavigation);
1681 // First check whether we're going to want to focus the location bar after
1682 // this commit. We do this now because the navigation hasn't formally
1683 // committed yet, so if we've already cleared |pending_web_ui_| the call chain
1684 // this triggers won't be able to figure out what's going on.
1685 bool will_focus_location_bar = delegate_->FocusLocationBarByDefault();
1687 // Next commit the Web UI, if any. Either replace |web_ui_| with
1688 // |pending_web_ui_|, or clear |web_ui_| if there is no pending WebUI, or
1689 // leave |web_ui_| as is if reusing it.
1690 DCHECK(!(pending_web_ui_ && pending_and_current_web_ui_));
1691 if (pending_web_ui_ || speculative_web_ui_) {
1692 DCHECK(!should_reuse_web_ui_);
1693 web_ui_.reset(browser_side_navigation ? speculative_web_ui_.release()
1694 : pending_web_ui_.release());
1695 } else if (pending_and_current_web_ui_ || should_reuse_web_ui_) {
1696 if (browser_side_navigation) {
1697 DCHECK(web_ui_);
1698 should_reuse_web_ui_ = false;
1699 } else {
1700 DCHECK_EQ(pending_and_current_web_ui_.get(), web_ui_.get());
1701 pending_and_current_web_ui_.reset();
1703 } else {
1704 web_ui_.reset();
1706 DCHECK(!speculative_web_ui_);
1707 DCHECK(!should_reuse_web_ui_);
1709 // It's possible for the pending_render_frame_host_ to be nullptr when we
1710 // aren't crossing process boundaries. If so, we just needed to handle the Web
1711 // UI committing above and we're done.
1712 if (!pending_render_frame_host_ && !speculative_render_frame_host_) {
1713 if (will_focus_location_bar)
1714 delegate_->SetFocusToLocationBar(false);
1715 return;
1718 // Remember if the page was focused so we can focus the new renderer in
1719 // that case.
1720 bool focus_render_view = !will_focus_location_bar &&
1721 render_frame_host_->GetView() &&
1722 render_frame_host_->GetView()->HasFocus();
1724 bool is_main_frame = frame_tree_node_->IsMainFrame();
1726 // Swap in the pending or speculative frame and make it active. Also ensure
1727 // the FrameTree stays in sync.
1728 scoped_ptr<RenderFrameHostImpl> old_render_frame_host;
1729 if (!browser_side_navigation) {
1730 DCHECK(!speculative_render_frame_host_);
1731 old_render_frame_host =
1732 SetRenderFrameHost(pending_render_frame_host_.Pass());
1733 } else {
1734 // PlzNavigate
1735 DCHECK(speculative_render_frame_host_);
1736 old_render_frame_host =
1737 SetRenderFrameHost(speculative_render_frame_host_.Pass());
1740 if (is_main_frame)
1741 render_frame_host_->render_view_host()->AttachToFrameTree();
1743 // The process will no longer try to exit, so we can decrement the count.
1744 render_frame_host_->GetProcess()->RemovePendingView();
1746 // Show the new view (or a sad tab) if necessary.
1747 bool new_rfh_has_view = !!render_frame_host_->GetView();
1748 if (!delegate_->IsHidden() && new_rfh_has_view) {
1749 // In most cases, we need to show the new view.
1750 render_frame_host_->GetView()->Show();
1752 if (!new_rfh_has_view) {
1753 // If the view is gone, then this RenderViewHost died while it was hidden.
1754 // We ignored the RenderProcessGone call at the time, so we should send it
1755 // now to make sure the sad tab shows up, etc.
1756 DCHECK(!render_frame_host_->IsRenderFrameLive());
1757 DCHECK(!render_frame_host_->render_view_host()->IsRenderViewLive());
1758 delegate_->RenderProcessGoneFromRenderManager(
1759 render_frame_host_->render_view_host());
1762 // For top-level frames, also hide the old RenderViewHost's view.
1763 // TODO(creis): As long as show/hide are on RVH, we don't want to hide on
1764 // subframe navigations or we will interfere with the top-level frame.
1765 if (is_main_frame && old_render_frame_host->render_view_host()->GetView())
1766 old_render_frame_host->render_view_host()->GetView()->Hide();
1768 // Make sure the size is up to date. (Fix for bug 1079768.)
1769 delegate_->UpdateRenderViewSizeForRenderManager();
1771 if (will_focus_location_bar) {
1772 delegate_->SetFocusToLocationBar(false);
1773 } else if (focus_render_view && render_frame_host_->GetView()) {
1774 render_frame_host_->GetView()->Focus();
1777 // Notify that we've swapped RenderFrameHosts. We do this before shutting down
1778 // the RFH so that we can clean up RendererResources related to the RFH first.
1779 delegate_->NotifySwappedFromRenderManager(
1780 old_render_frame_host.get(), render_frame_host_.get(), is_main_frame);
1782 // Swap out the old frame now that the new one is visible.
1783 // This will swap it out and then put it on the proxy list (if there are other
1784 // active views in its SiteInstance) or schedule it for deletion when the swap
1785 // out ack arrives (or immediately if the process isn't live).
1786 // In the --site-per-process case, old subframe RHFs are not kept alive inside
1787 // the proxy.
1788 SwapOutOldFrame(old_render_frame_host.Pass());
1790 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1791 switches::kSitePerProcess) &&
1792 !is_main_frame) {
1793 // Since the new RenderFrameHost is now committed, there must be no proxies
1794 // for its SiteInstance. Delete any existing ones.
1795 RenderFrameProxyHostMap::iterator iter =
1796 proxy_hosts_.find(render_frame_host_->GetSiteInstance()->GetId());
1797 if (iter != proxy_hosts_.end()) {
1798 delete iter->second;
1799 proxy_hosts_.erase(iter);
1802 // If this is a subframe, it should have a CrossProcessFrameConnector
1803 // created already. Use it to link the new RFH's view to the proxy that
1804 // belongs to the parent frame's SiteInstance. If this navigation causes
1805 // an out-of-process frame to return to the same process as its parent, the
1806 // proxy would have been removed from proxy_hosts_ above.
1807 // Note: We do this after swapping out the old RFH because that may create
1808 // the proxy we're looking for.
1809 RenderFrameProxyHost* proxy_to_parent = GetProxyToParent();
1810 if (proxy_to_parent)
1811 proxy_to_parent->SetChildRWHView(render_frame_host_->GetView());
1814 // After all is done, there must never be a proxy in the list which has the
1815 // same SiteInstance as the current RenderFrameHost.
1816 CHECK(proxy_hosts_.find(render_frame_host_->GetSiteInstance()->GetId()) ==
1817 proxy_hosts_.end());
1820 void RenderFrameHostManager::ShutdownProxiesIfLastActiveFrameInSiteInstance(
1821 RenderFrameHostImpl* render_frame_host) {
1822 if (!render_frame_host)
1823 return;
1824 if (!RenderFrameHostImpl::IsRFHStateActive(render_frame_host->rfh_state()))
1825 return;
1826 if (render_frame_host->GetSiteInstance()->active_frame_count() > 1U)
1827 return;
1829 // After |render_frame_host| goes away, there will be no active frames left in
1830 // its SiteInstance, so we can delete all proxies created in that SiteInstance
1831 // on behalf of frames anywhere in the BrowsingInstance.
1832 int32 site_instance_id = render_frame_host->GetSiteInstance()->GetId();
1834 // First remove any proxies for this SiteInstance from our own list.
1835 ClearProxiesInSiteInstance(site_instance_id, frame_tree_node_);
1837 // Use the safe RenderWidgetHost iterator for now to find all RenderViewHosts
1838 // in the SiteInstance, then tell their respective FrameTrees to remove all
1839 // RenderFrameProxyHosts corresponding to them.
1840 // TODO(creis): Replace this with a RenderFrameHostIterator that protects
1841 // against use-after-frees if a later element is deleted before getting to it.
1842 scoped_ptr<RenderWidgetHostIterator> widgets(
1843 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
1844 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
1845 if (!widget->IsRenderView())
1846 continue;
1847 RenderViewHostImpl* rvh =
1848 static_cast<RenderViewHostImpl*>(RenderViewHost::From(widget));
1849 if (site_instance_id == rvh->GetSiteInstance()->GetId()) {
1850 // This deletes all RenderFrameHosts using the |rvh|, which then causes
1851 // |rvh| to Shutdown.
1852 FrameTree* tree = rvh->GetDelegate()->GetFrameTree();
1853 tree->ForEach(base::Bind(
1854 &RenderFrameHostManager::ClearProxiesInSiteInstance,
1855 site_instance_id));
1860 RenderFrameHostImpl* RenderFrameHostManager::UpdateStateForNavigate(
1861 const GURL& dest_url,
1862 SiteInstance* source_instance,
1863 SiteInstance* dest_instance,
1864 ui::PageTransition transition,
1865 bool dest_is_restore,
1866 bool dest_is_view_source_mode,
1867 const GlobalRequestID& transferred_request_id,
1868 int bindings) {
1869 // If we are currently navigating cross-process, we want to get back to normal
1870 // and then navigate as usual.
1871 if (pending_render_frame_host_)
1872 CancelPending();
1874 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1875 scoped_refptr<SiteInstance> new_instance = GetSiteInstanceForNavigation(
1876 dest_url, source_instance, dest_instance, nullptr, transition,
1877 dest_is_restore, dest_is_view_source_mode);
1879 const NavigationEntry* current_entry =
1880 delegate_->GetLastCommittedNavigationEntryForRenderManager();
1882 DCHECK(!pending_render_frame_host_);
1884 if (new_instance.get() != current_instance) {
1885 TRACE_EVENT_INSTANT2(
1886 "navigation",
1887 "RenderFrameHostManager::UpdateStateForNavigate:New SiteInstance",
1888 TRACE_EVENT_SCOPE_THREAD,
1889 "current_instance id", current_instance->GetId(),
1890 "new_instance id", new_instance->GetId());
1892 // New SiteInstance: create a pending RFH to navigate.
1894 // This will possibly create (set to nullptr) a Web UI object for the
1895 // pending page. We'll use this later to give the page special access. This
1896 // must happen before the new renderer is created below so it will get
1897 // bindings. It must also happen after the above conditional call to
1898 // CancelPending(), otherwise CancelPending may clear the pending_web_ui_
1899 // and the page will not have its bindings set appropriately.
1900 SetPendingWebUI(dest_url, bindings);
1901 CreatePendingRenderFrameHost(current_instance, new_instance.get(),
1902 frame_tree_node_->IsMainFrame());
1903 if (!pending_render_frame_host_)
1904 return nullptr;
1906 // Check if our current RFH is live before we set up a transition.
1907 if (!render_frame_host_->IsRenderFrameLive()) {
1908 // The current RFH is not live. There's no reason to sit around with a
1909 // sad tab or a newly created RFH while we wait for the pending RFH to
1910 // navigate. Just switch to the pending RFH now and go back to normal.
1911 // (Note that we don't care about on{before}unload handlers if the current
1912 // RFH isn't live.)
1913 CommitPending();
1914 return render_frame_host_.get();
1916 // Otherwise, it's safe to treat this as a pending cross-process transition.
1918 // We now have a pending RFH.
1919 DCHECK(pending_render_frame_host_);
1921 // We need to wait until the beforeunload handler has run, unless we are
1922 // transferring an existing request (in which case it has already run).
1923 // Suspend the new render view (i.e., don't let it send the cross-process
1924 // Navigate message) until we hear back from the old renderer's
1925 // beforeunload handler. If the handler returns false, we'll have to
1926 // cancel the request.
1928 DCHECK(!pending_render_frame_host_->are_navigations_suspended());
1929 bool is_transfer = transferred_request_id != GlobalRequestID();
1930 if (is_transfer) {
1931 // We don't need to stop the old renderer or run beforeunload/unload
1932 // handlers, because those have already been done.
1933 DCHECK(cross_site_transferring_request_->request_id() ==
1934 transferred_request_id);
1935 } else {
1936 // Also make sure the old render view stops, in case a load is in
1937 // progress. (We don't want to do this for transfers, since it will
1938 // interrupt the transfer with an unexpected DidStopLoading.)
1939 render_frame_host_->Send(new FrameMsg_Stop(
1940 render_frame_host_->GetRoutingID()));
1941 pending_render_frame_host_->SetNavigationsSuspended(true,
1942 base::TimeTicks());
1943 // Unless we are transferring an existing request, we should now tell the
1944 // old render view to run its beforeunload handler, since it doesn't
1945 // otherwise know that the cross-site request is happening. This will
1946 // trigger a call to OnBeforeUnloadACK with the reply.
1947 render_frame_host_->DispatchBeforeUnload(true);
1950 return pending_render_frame_host_.get();
1953 // Otherwise the same SiteInstance can be used. Navigate render_frame_host_.
1955 // It's possible to swap out the current RFH and then decide to navigate in it
1956 // anyway (e.g., a cross-process navigation that redirects back to the
1957 // original site). In that case, we have a proxy for the current RFH but
1958 // haven't deleted it yet. The new navigation will swap it back in, so we can
1959 // delete the proxy.
1960 DeleteRenderFrameProxyHost(new_instance.get());
1962 if (ShouldReuseWebUI(current_entry, dest_url)) {
1963 pending_web_ui_.reset();
1964 pending_and_current_web_ui_ = web_ui_->AsWeakPtr();
1965 } else {
1966 SetPendingWebUI(dest_url, bindings);
1967 // Make sure the new RenderViewHost has the right bindings.
1968 if (pending_web_ui() &&
1969 !render_frame_host_->GetProcess()->IsIsolatedGuest()) {
1970 render_frame_host_->render_view_host()->AllowBindings(
1971 pending_web_ui()->GetBindings());
1975 if (pending_web_ui() && render_frame_host_->IsRenderFrameLive()) {
1976 pending_web_ui()->GetController()->RenderViewReused(
1977 render_frame_host_->render_view_host());
1980 // The renderer can exit view source mode when any error or cancellation
1981 // happen. We must overwrite to recover the mode.
1982 if (dest_is_view_source_mode) {
1983 render_frame_host_->render_view_host()->Send(
1984 new ViewMsg_EnableViewSourceMode(
1985 render_frame_host_->render_view_host()->GetRoutingID()));
1988 return render_frame_host_.get();
1991 void RenderFrameHostManager::CancelPending() {
1992 TRACE_EVENT1("navigation", "RenderFrameHostManager::CancelPending",
1993 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
1994 DiscardUnusedFrame(UnsetPendingRenderFrameHost());
1997 scoped_ptr<RenderFrameHostImpl>
1998 RenderFrameHostManager::UnsetPendingRenderFrameHost() {
1999 scoped_ptr<RenderFrameHostImpl> pending_render_frame_host =
2000 pending_render_frame_host_.Pass();
2002 RenderFrameDevToolsAgentHost::OnCancelPendingNavigation(
2003 pending_render_frame_host.get(),
2004 render_frame_host_.get());
2006 // We no longer need to prevent the process from exiting.
2007 pending_render_frame_host->GetProcess()->RemovePendingView();
2009 pending_web_ui_.reset();
2010 pending_and_current_web_ui_.reset();
2012 return pending_render_frame_host.Pass();
2015 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::SetRenderFrameHost(
2016 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
2017 // Swap the two.
2018 scoped_ptr<RenderFrameHostImpl> old_render_frame_host =
2019 render_frame_host_.Pass();
2020 render_frame_host_ = render_frame_host.Pass();
2022 if (frame_tree_node_->IsMainFrame()) {
2023 // Update the count of top-level frames using this SiteInstance. All
2024 // subframes are in the same BrowsingInstance as the main frame, so we only
2025 // count top-level ones. This makes the value easier for consumers to
2026 // interpret.
2027 if (render_frame_host_) {
2028 render_frame_host_->GetSiteInstance()->
2029 IncrementRelatedActiveContentsCount();
2031 if (old_render_frame_host) {
2032 old_render_frame_host->GetSiteInstance()->
2033 DecrementRelatedActiveContentsCount();
2037 return old_render_frame_host.Pass();
2040 bool RenderFrameHostManager::IsRVHOnSwappedOutList(
2041 RenderViewHostImpl* rvh) const {
2042 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(
2043 rvh->GetSiteInstance());
2044 if (!proxy)
2045 return false;
2046 // If there is a proxy without RFH, it is for a subframe in the SiteInstance
2047 // of |rvh|. Subframes should be ignored in this case.
2048 if (!proxy->render_frame_host())
2049 return false;
2050 return IsOnSwappedOutList(proxy->render_frame_host());
2053 bool RenderFrameHostManager::IsOnSwappedOutList(
2054 RenderFrameHostImpl* rfh) const {
2055 if (!rfh->GetSiteInstance())
2056 return false;
2058 RenderFrameProxyHostMap::const_iterator iter = proxy_hosts_.find(
2059 rfh->GetSiteInstance()->GetId());
2060 if (iter == proxy_hosts_.end())
2061 return false;
2063 return iter->second->render_frame_host() == rfh;
2066 RenderViewHostImpl* RenderFrameHostManager::GetSwappedOutRenderViewHost(
2067 SiteInstance* instance) const {
2068 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
2069 if (proxy)
2070 return proxy->GetRenderViewHost();
2071 return NULL;
2074 RenderFrameProxyHost* RenderFrameHostManager::GetRenderFrameProxyHost(
2075 SiteInstance* instance) const {
2076 RenderFrameProxyHostMap::const_iterator iter =
2077 proxy_hosts_.find(instance->GetId());
2078 if (iter != proxy_hosts_.end())
2079 return iter->second;
2081 return NULL;
2084 void RenderFrameHostManager::DeleteRenderFrameProxyHost(
2085 SiteInstance* instance) {
2086 RenderFrameProxyHostMap::iterator iter = proxy_hosts_.find(instance->GetId());
2087 if (iter != proxy_hosts_.end()) {
2088 delete iter->second;
2089 proxy_hosts_.erase(iter);
2093 } // namespace content