Remove PlatformFile from profile_browsertest
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_manager.cc
blobb9c5be36a75c1c6896c7a7e1ebe7793720f0eceb
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/debug/trace_event.h"
11 #include "base/logging.h"
12 #include "content/browser/child_process_security_policy_impl.h"
13 #include "content/browser/devtools/render_view_devtools_agent_host.h"
14 #include "content/browser/frame_host/cross_process_frame_connector.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/navigator.h"
21 #include "content/browser/frame_host/render_frame_host_factory.h"
22 #include "content/browser/frame_host/render_frame_host_impl.h"
23 #include "content/browser/renderer_host/render_process_host_impl.h"
24 #include "content/browser/renderer_host/render_view_host_factory.h"
25 #include "content/browser/renderer_host/render_view_host_impl.h"
26 #include "content/browser/site_instance_impl.h"
27 #include "content/browser/webui/web_ui_controller_factory_registry.h"
28 #include "content/browser/webui/web_ui_impl.h"
29 #include "content/common/view_messages.h"
30 #include "content/port/browser/render_widget_host_view_port.h"
31 #include "content/public/browser/content_browser_client.h"
32 #include "content/public/browser/notification_service.h"
33 #include "content/public/browser/notification_types.h"
34 #include "content/public/browser/render_widget_host_iterator.h"
35 #include "content/public/browser/user_metrics.h"
36 #include "content/public/browser/web_ui_controller.h"
37 #include "content/public/common/content_switches.h"
38 #include "content/public/common/url_constants.h"
40 namespace content {
42 RenderFrameHostManager::PendingNavigationParams::PendingNavigationParams(
43 const GlobalRequestID& global_request_id,
44 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
45 const std::vector<GURL>& transfer_url_chain,
46 Referrer referrer,
47 PageTransition page_transition,
48 int render_frame_id,
49 bool should_replace_current_entry)
50 : global_request_id(global_request_id),
51 cross_site_transferring_request(cross_site_transferring_request.Pass()),
52 transfer_url_chain(transfer_url_chain),
53 referrer(referrer),
54 page_transition(page_transition),
55 render_frame_id(render_frame_id),
56 should_replace_current_entry(should_replace_current_entry) {
59 RenderFrameHostManager::PendingNavigationParams::~PendingNavigationParams() {}
61 bool RenderFrameHostManager::ClearRFHsPendingShutdown(FrameTreeNode* node) {
62 node->render_manager()->pending_delete_hosts_.clear();
63 return true;
66 RenderFrameHostManager::RenderFrameHostManager(
67 FrameTreeNode* frame_tree_node,
68 RenderFrameHostDelegate* render_frame_delegate,
69 RenderViewHostDelegate* render_view_delegate,
70 RenderWidgetHostDelegate* render_widget_delegate,
71 Delegate* delegate)
72 : frame_tree_node_(frame_tree_node),
73 delegate_(delegate),
74 cross_navigation_pending_(false),
75 render_frame_delegate_(render_frame_delegate),
76 render_view_delegate_(render_view_delegate),
77 render_widget_delegate_(render_widget_delegate),
78 interstitial_page_(NULL),
79 cross_process_frame_connector_(NULL),
80 weak_factory_(this) {}
82 RenderFrameHostManager::~RenderFrameHostManager() {
83 if (pending_render_frame_host_)
84 CancelPending();
86 if (cross_process_frame_connector_)
87 delete cross_process_frame_connector_;
89 // We should always have a current RenderFrameHost except in some tests.
90 render_frame_host_.reset();
92 // TODO(creis): Now that we aren't using Shutdown, make RenderFrameHostMap
93 // use scoped_ptrs.
94 // Delete any swapped out RenderFrameHosts.
95 for (RenderFrameHostMap::iterator iter = swapped_out_hosts_.begin();
96 iter != swapped_out_hosts_.end();
97 ++iter) {
98 delete iter->second;
102 void RenderFrameHostManager::Init(BrowserContext* browser_context,
103 SiteInstance* site_instance,
104 int view_routing_id,
105 int frame_routing_id) {
106 // Create a RenderViewHost and RenderFrameHost, once we have an instance. It
107 // is important to immediately give this SiteInstance to a RenderViewHost so
108 // that the SiteInstance is ref counted.
109 if (!site_instance)
110 site_instance = SiteInstance::Create(browser_context);
112 render_frame_host_ = make_scoped_ptr(
113 CreateRenderFrameHost(site_instance, view_routing_id, frame_routing_id,
114 false, delegate_->IsHidden()));
116 // Keep track of renderer processes as they start to shut down or are
117 // crashed/killed.
118 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSED,
119 NotificationService::AllSources());
120 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSING,
121 NotificationService::AllSources());
124 RenderViewHostImpl* RenderFrameHostManager::current_host() const {
125 if (!render_frame_host_)
126 return NULL;
127 return render_frame_host_->render_view_host();
130 RenderViewHostImpl* RenderFrameHostManager::pending_render_view_host() const {
131 if (!pending_render_frame_host_)
132 return NULL;
133 return pending_render_frame_host_->render_view_host();
136 RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const {
137 if (interstitial_page_)
138 return interstitial_page_->GetView();
139 if (!render_frame_host_)
140 return NULL;
141 return render_frame_host_->render_view_host()->GetView();
144 void RenderFrameHostManager::SetPendingWebUI(const NavigationEntryImpl& entry) {
145 pending_web_ui_.reset(
146 delegate_->CreateWebUIForRenderManager(entry.GetURL()));
147 pending_and_current_web_ui_.reset();
149 // If we have assigned (zero or more) bindings to this NavigationEntry in the
150 // past, make sure we're not granting it different bindings than it had
151 // before. If so, note it and don't give it any bindings, to avoid a
152 // potential privilege escalation.
153 if (pending_web_ui_.get() &&
154 entry.bindings() != NavigationEntryImpl::kInvalidBindings &&
155 pending_web_ui_->GetBindings() != entry.bindings()) {
156 RecordAction(
157 base::UserMetricsAction("ProcessSwapBindingsMismatch_RVHM"));
158 pending_web_ui_.reset();
162 RenderFrameHostImpl* RenderFrameHostManager::Navigate(
163 const NavigationEntryImpl& entry) {
164 TRACE_EVENT0("browser", "RenderFrameHostManager:Navigate");
165 // Create a pending RenderFrameHost to use for the navigation.
166 RenderFrameHostImpl* dest_render_frame_host =
167 UpdateRendererStateForNavigate(entry);
168 if (!dest_render_frame_host)
169 return NULL; // We weren't able to create a pending render frame host.
171 // If the current render_frame_host_ isn't live, we should create it so
172 // that we don't show a sad tab while the dest_render_frame_host fetches
173 // its first page. (Bug 1145340)
174 if (dest_render_frame_host != render_frame_host_ &&
175 !render_frame_host_->render_view_host()->IsRenderViewLive()) {
176 // Note: we don't call InitRenderView here because we are navigating away
177 // soon anyway, and we don't have the NavigationEntry for this host.
178 delegate_->CreateRenderViewForRenderManager(
179 render_frame_host_->render_view_host(), MSG_ROUTING_NONE, NULL);
182 // If the renderer crashed, then try to create a new one to satisfy this
183 // navigation request.
184 if (!dest_render_frame_host->render_view_host()->IsRenderViewLive()) {
185 // Recreate the opener chain.
186 int opener_route_id = delegate_->CreateOpenerRenderViewsForRenderManager(
187 dest_render_frame_host->GetSiteInstance());
188 if (!InitRenderView(dest_render_frame_host->render_view_host(),
189 opener_route_id))
190 return NULL;
192 // Now that we've created a new renderer, be sure to hide it if it isn't
193 // our primary one. Otherwise, we might crash if we try to call Show()
194 // on it later.
195 if (dest_render_frame_host != render_frame_host_ &&
196 dest_render_frame_host->render_view_host()->GetView()) {
197 dest_render_frame_host->render_view_host()->GetView()->Hide();
198 } else if (frame_tree_node_->IsMainFrame()) {
199 // This is our primary renderer, notify here as we won't be calling
200 // CommitPending (which does the notify). We only do this for top-level
201 // frames.
202 delegate_->NotifySwappedFromRenderManager(
203 NULL, render_frame_host_->render_view_host());
207 // If entry includes the request ID of a request that is being transferred,
208 // the destination render frame will take ownership, so release ownership of
209 // the request.
210 if (pending_nav_params_ &&
211 pending_nav_params_->global_request_id ==
212 entry.transferred_global_request_id()) {
213 pending_nav_params_->cross_site_transferring_request->ReleaseRequest();
216 return dest_render_frame_host;
219 void RenderFrameHostManager::Stop() {
220 render_frame_host_->render_view_host()->Stop();
222 // If we are cross-navigating, we should stop the pending renderers. This
223 // will lead to a DidFailProvisionalLoad, which will properly destroy them.
224 if (cross_navigation_pending_) {
225 pending_render_frame_host_->render_view_host()->Send(new ViewMsg_Stop(
226 pending_render_frame_host_->render_view_host()->GetRoutingID()));
230 void RenderFrameHostManager::SetIsLoading(bool is_loading) {
231 render_frame_host_->render_view_host()->SetIsLoading(is_loading);
232 if (pending_render_frame_host_)
233 pending_render_frame_host_->render_view_host()->SetIsLoading(is_loading);
236 bool RenderFrameHostManager::ShouldCloseTabOnUnresponsiveRenderer() {
237 if (!cross_navigation_pending_)
238 return true;
240 // We should always have a pending RFH when there's a cross-process navigation
241 // in progress. Sanity check this for http://crbug.com/276333.
242 CHECK(pending_render_frame_host_);
244 // If the tab becomes unresponsive during {before}unload while doing a
245 // cross-site navigation, proceed with the navigation. (This assumes that
246 // the pending RenderFrameHost is still responsive.)
247 if (render_frame_host_->render_view_host()->IsWaitingForUnloadACK()) {
248 // The request has been started and paused while we're waiting for the
249 // unload handler to finish. We'll pretend that it did. The pending
250 // renderer will then be swapped in as part of the usual DidNavigate logic.
251 // (If the unload handler later finishes, this call will be ignored because
252 // the pending_nav_params_ state will already be cleaned up.)
253 current_host()->OnSwappedOut(true);
254 } else if (render_frame_host_->render_view_host()->
255 is_waiting_for_beforeunload_ack()) {
256 // Haven't gotten around to starting the request, because we're still
257 // waiting for the beforeunload handler to finish. We'll pretend that it
258 // did finish, to let the navigation proceed. Note that there's a danger
259 // that the beforeunload handler will later finish and possibly return
260 // false (meaning the navigation should not proceed), but we'll ignore it
261 // in this case because it took too long.
262 if (pending_render_frame_host_->render_view_host()->
263 are_navigations_suspended()) {
264 pending_render_frame_host_->render_view_host()->SetNavigationsSuspended(
265 false, base::TimeTicks::Now());
268 return false;
271 void RenderFrameHostManager::OnBeforeUnloadACK(
272 bool for_cross_site_transition,
273 bool proceed,
274 const base::TimeTicks& proceed_time) {
275 if (for_cross_site_transition) {
276 // Ignore if we're not in a cross-site navigation.
277 if (!cross_navigation_pending_)
278 return;
280 if (proceed) {
281 // Ok to unload the current page, so proceed with the cross-site
282 // navigation. Note that if navigations are not currently suspended, it
283 // might be because the renderer was deemed unresponsive and this call was
284 // already made by ShouldCloseTabOnUnresponsiveRenderer. In that case, it
285 // is ok to do nothing here.
286 if (pending_render_frame_host_ &&
287 pending_render_frame_host_->render_view_host()->
288 are_navigations_suspended()) {
289 pending_render_frame_host_->render_view_host()->
290 SetNavigationsSuspended(false, proceed_time);
292 } else {
293 // Current page says to cancel.
294 CancelPending();
295 cross_navigation_pending_ = false;
297 } else {
298 // Non-cross site transition means closing the entire tab.
299 bool proceed_to_fire_unload;
300 delegate_->BeforeUnloadFiredFromRenderManager(proceed, proceed_time,
301 &proceed_to_fire_unload);
303 if (proceed_to_fire_unload) {
304 // If we're about to close the tab and there's a pending RFH, cancel it.
305 // Otherwise, if the navigation in the pending RFH completes before the
306 // close in the current RFH, we'll lose the tab close.
307 if (pending_render_frame_host_) {
308 CancelPending();
309 cross_navigation_pending_ = false;
312 // This is not a cross-site navigation, the tab is being closed.
313 render_frame_host_->render_view_host()->ClosePage();
318 void RenderFrameHostManager::OnCrossSiteResponse(
319 RenderFrameHostImpl* pending_render_frame_host,
320 const GlobalRequestID& global_request_id,
321 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
322 const std::vector<GURL>& transfer_url_chain,
323 const Referrer& referrer,
324 PageTransition page_transition,
325 bool should_replace_current_entry) {
326 // This should be called either when the pending RFH is ready to commit or
327 // when we realize that the current RFH's request requires a transfer.
328 DCHECK(pending_render_frame_host == pending_render_frame_host_ ||
329 pending_render_frame_host == render_frame_host_);
331 // TODO(creis): Eventually we will want to check all navigation responses
332 // here, but currently we pass information for a transfer if
333 // ShouldSwapProcessesForRedirect returned true in the network stack.
334 // In that case, we should set up a transfer after the unload handler runs.
335 // If |cross_site_transferring_request| is NULL, we will just run the unload
336 // handler and resume.
337 pending_nav_params_.reset(new PendingNavigationParams(
338 global_request_id, cross_site_transferring_request.Pass(),
339 transfer_url_chain, referrer, page_transition,
340 pending_render_frame_host->GetRoutingID(),
341 should_replace_current_entry));
343 // Run the unload handler of the current page.
344 SwapOutOldPage();
347 void RenderFrameHostManager::SwappedOut(
348 RenderFrameHostImpl* render_frame_host) {
349 // Make sure this is from our current RFH, and that we have a pending
350 // navigation from OnCrossSiteResponse. (There may be no pending navigation
351 // for data URLs that don't make network requests, for example.) If not,
352 // just return early and ignore.
353 if (render_frame_host != render_frame_host_ || !pending_nav_params_.get()) {
354 pending_nav_params_.reset();
355 return;
358 // Now that the unload handler has run, we need to either initiate the
359 // pending transfer (if there is one) or resume the paused response (if not).
360 // TODO(creis): The blank swapped out page is visible during this time, but
361 // we can shorten this by delivering the response directly, rather than
362 // forcing an identical request to be made.
363 if (pending_nav_params_->cross_site_transferring_request) {
364 // Sanity check that the params are for the correct frame and process.
365 // These should match the RenderFrameHost that made the request.
366 // If it started as a cross-process navigation via OpenURL, this is the
367 // pending one. If it wasn't cross-process until the transfer, this is the
368 // current one.
369 int render_frame_id = pending_render_frame_host_ ?
370 pending_render_frame_host_->GetRoutingID() :
371 render_frame_host_->GetRoutingID();
372 DCHECK_EQ(render_frame_id, pending_nav_params_->render_frame_id);
373 int process_id = pending_render_frame_host_ ?
374 pending_render_frame_host_->GetProcess()->GetID() :
375 render_frame_host_->GetProcess()->GetID();
376 DCHECK_EQ(process_id, pending_nav_params_->global_request_id.child_id);
378 // Treat the last URL in the chain as the destination and the remainder as
379 // the redirect chain.
380 CHECK(pending_nav_params_->transfer_url_chain.size());
381 GURL transfer_url = pending_nav_params_->transfer_url_chain.back();
382 pending_nav_params_->transfer_url_chain.pop_back();
384 // We don't know whether the original request had |user_action| set to true.
385 // However, since we force the navigation to be in the current tab, it
386 // doesn't matter.
387 render_frame_host->frame_tree_node()->navigator()->RequestTransferURL(
388 render_frame_host,
389 transfer_url,
390 pending_nav_params_->transfer_url_chain,
391 pending_nav_params_->referrer,
392 pending_nav_params_->page_transition,
393 CURRENT_TAB,
394 pending_nav_params_->global_request_id,
395 pending_nav_params_->should_replace_current_entry,
396 true);
397 } else if (pending_render_frame_host_) {
398 RenderProcessHostImpl* pending_process =
399 static_cast<RenderProcessHostImpl*>(
400 pending_render_frame_host_->GetProcess());
401 pending_process->ResumeDeferredNavigation(
402 pending_nav_params_->global_request_id);
404 pending_nav_params_.reset();
407 void RenderFrameHostManager::DidNavigateFrame(
408 RenderFrameHostImpl* render_frame_host) {
409 if (!cross_navigation_pending_) {
410 DCHECK(!pending_render_frame_host_);
412 // We should only hear this from our current renderer.
413 DCHECK_EQ(render_frame_host_, render_frame_host);
415 // Even when there is no pending RVH, there may be a pending Web UI.
416 if (pending_web_ui())
417 CommitPending();
418 return;
421 if (render_frame_host == pending_render_frame_host_) {
422 // The pending cross-site navigation completed, so show the renderer.
423 // If it committed without sending network requests (e.g., data URLs),
424 // then we still need to swap out the old RFH first and run its unload
425 // handler, only if it hasn't happened yet. OK for that to happen in the
426 // background.
427 if (pending_render_frame_host_->render_view_host()->
428 HasPendingCrossSiteRequest() &&
429 pending_render_frame_host_->render_view_host()->rvh_state() ==
430 RenderViewHostImpl::STATE_DEFAULT) {
431 SwapOutOldPage();
434 CommitPending();
435 cross_navigation_pending_ = false;
436 } else if (render_frame_host == render_frame_host_) {
437 // A navigation in the original page has taken place. Cancel the pending
438 // one.
439 CancelPending();
440 cross_navigation_pending_ = false;
441 } else {
442 // No one else should be sending us DidNavigate in this state.
443 DCHECK(false);
447 // TODO(creis): Take in RenderFrameHost instead, since frames can have openers.
448 void RenderFrameHostManager::DidDisownOpener(RenderViewHost* render_view_host) {
449 // Notify all swapped out hosts, including the pending RVH.
450 for (RenderFrameHostMap::iterator iter = swapped_out_hosts_.begin();
451 iter != swapped_out_hosts_.end();
452 ++iter) {
453 DCHECK_NE(iter->second->GetSiteInstance(),
454 current_frame_host()->GetSiteInstance());
455 iter->second->render_view_host()->DisownOpener();
459 void RenderFrameHostManager::RendererProcessClosing(
460 RenderProcessHost* render_process_host) {
461 // Remove any swapped out RVHs from this process, so that we don't try to
462 // swap them back in while the process is exiting. Start by finding them,
463 // since there could be more than one.
464 std::list<int> ids_to_remove;
465 for (RenderFrameHostMap::iterator iter = swapped_out_hosts_.begin();
466 iter != swapped_out_hosts_.end();
467 ++iter) {
468 if (iter->second->GetProcess() == render_process_host)
469 ids_to_remove.push_back(iter->first);
472 // Now delete them.
473 while (!ids_to_remove.empty()) {
474 delete swapped_out_hosts_[ids_to_remove.back()];
475 swapped_out_hosts_.erase(ids_to_remove.back());
476 ids_to_remove.pop_back();
480 void RenderFrameHostManager::SwapOutOldPage() {
481 // Should only see this while we have a pending renderer or transfer.
482 CHECK(cross_navigation_pending_ || pending_nav_params_.get());
484 // Tell the renderer to suppress any further modal dialogs so that we can swap
485 // it out. This must be done before canceling any current dialog, in case
486 // there is a loop creating additional dialogs.
487 // TODO(creis): Handle modal dialogs in subframe processes.
488 render_frame_host_->render_view_host()->SuppressDialogsUntilSwapOut();
490 // Now close any modal dialogs that would prevent us from swapping out. This
491 // must be done separately from SwapOut, so that the PageGroupLoadDeferrer is
492 // no longer on the stack when we send the SwapOut message.
493 delegate_->CancelModalDialogsForRenderManager();
495 if (!frame_tree_node_->IsMainFrame()) {
496 // The RenderFrameHost being swapped out becomes the proxy for this
497 // frame in its parent's process. CrossProcessFrameConnector
498 // initialization only needs to happen on an initial cross-process
499 // navigation, when the RenderFrame leaves the same process as its parent.
500 // The same CrossProcessFrameConnector is used for subsequent cross-
501 // process navigations, but it will be destroyed if the Frame is
502 // navigated back to the same site instance as its parent.
503 // TODO(kenrb): This will change when RenderFrameProxyHost is created.
504 if (!cross_process_frame_connector_) {
505 cross_process_frame_connector_ =
506 new CrossProcessFrameConnector(render_frame_host_.get());
510 // Tell the old frame it is being swapped out. This will fire the unload
511 // handler in the background (without firing the beforeunload handler a second
512 // time). When the navigation completes, we will send a message to the
513 // ResourceDispatcherHost, allowing the pending RVH's response to resume.
514 render_frame_host_->SwapOut();
516 // ResourceDispatcherHost has told us to run the onunload handler, which
517 // means it is not a download or unsafe page, and we are going to perform the
518 // navigation. Thus, we no longer need to remember that the RenderFrameHost
519 // is part of a pending cross-site request.
520 if (pending_render_frame_host_) {
521 pending_render_frame_host_->render_view_host()->
522 SetHasPendingCrossSiteRequest(false);
526 void RenderFrameHostManager::ClearPendingShutdownRFHForSiteInstance(
527 int32 site_instance_id,
528 RenderFrameHostImpl* rfh) {
529 RFHPendingDeleteMap::iterator iter =
530 pending_delete_hosts_.find(site_instance_id);
531 if (iter != pending_delete_hosts_.end() && iter->second.get() == rfh)
532 pending_delete_hosts_.erase(site_instance_id);
535 void RenderFrameHostManager::Observe(
536 int type,
537 const NotificationSource& source,
538 const NotificationDetails& details) {
539 switch (type) {
540 case NOTIFICATION_RENDERER_PROCESS_CLOSED:
541 case NOTIFICATION_RENDERER_PROCESS_CLOSING:
542 RendererProcessClosing(
543 Source<RenderProcessHost>(source).ptr());
544 break;
546 default:
547 NOTREACHED();
551 bool RenderFrameHostManager::ClearSwappedOutRFHsInSiteInstance(
552 int32 site_instance_id,
553 FrameTreeNode* node) {
554 RenderFrameHostMap::iterator iter =
555 node->render_manager()->swapped_out_hosts_.find(site_instance_id);
556 if (iter != node->render_manager()->swapped_out_hosts_.end()) {
557 RenderFrameHostImpl* swapped_out_rfh = iter->second;
558 // If the RVH is pending swap out, it needs to switch state to
559 // pending shutdown. Otherwise it is deleted.
560 if (swapped_out_rfh->render_view_host()->rvh_state() ==
561 RenderViewHostImpl::STATE_PENDING_SWAP_OUT) {
562 swapped_out_rfh->SetPendingShutdown(base::Bind(
563 &RenderFrameHostManager::ClearPendingShutdownRFHForSiteInstance,
564 node->render_manager()->weak_factory_.GetWeakPtr(),
565 site_instance_id,
566 swapped_out_rfh));
567 RFHPendingDeleteMap::iterator pending_delete_iter =
568 node->render_manager()->pending_delete_hosts_.find(site_instance_id);
569 if (pending_delete_iter ==
570 node->render_manager()->pending_delete_hosts_.end() ||
571 pending_delete_iter->second.get() != iter->second) {
572 node->render_manager()->pending_delete_hosts_[site_instance_id] =
573 linked_ptr<RenderFrameHostImpl>(swapped_out_rfh);
575 } else {
576 delete swapped_out_rfh;
578 node->render_manager()->swapped_out_hosts_.erase(site_instance_id);
581 return true;
584 bool RenderFrameHostManager::ShouldTransitionCrossSite() {
585 // False in the single-process mode, as it makes RVHs to accumulate
586 // in swapped_out_hosts_.
587 // True if we are using process-per-site-instance (default) or
588 // process-per-site (kProcessPerSite).
589 return
590 !CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess) &&
591 !CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessPerTab);
594 bool RenderFrameHostManager::ShouldSwapBrowsingInstancesForNavigation(
595 const NavigationEntry* current_entry,
596 const NavigationEntryImpl* new_entry) const {
597 DCHECK(new_entry);
599 // If new_entry already has a SiteInstance, assume it is correct. We only
600 // need to force a swap if it is in a different BrowsingInstance.
601 if (new_entry->site_instance()) {
602 return !new_entry->site_instance()->IsRelatedSiteInstance(
603 render_frame_host_->GetSiteInstance());
606 // Check for reasons to swap processes even if we are in a process model that
607 // doesn't usually swap (e.g., process-per-tab). Any time we return true,
608 // the new_entry will be rendered in a new SiteInstance AND BrowsingInstance.
610 // We use the effective URL here, since that's what is used in the
611 // SiteInstance's site and when we later call IsSameWebSite. If there is no
612 // current_entry, check the current SiteInstance's site, which might already
613 // be committed to a Web UI URL (such as the NTP).
614 BrowserContext* browser_context =
615 delegate_->GetControllerForRenderManager().GetBrowserContext();
616 const GURL& current_url = (current_entry) ?
617 SiteInstanceImpl::GetEffectiveURL(browser_context,
618 current_entry->GetURL()) :
619 render_frame_host_->GetSiteInstance()->GetSiteURL();
620 const GURL& new_url = SiteInstanceImpl::GetEffectiveURL(browser_context,
621 new_entry->GetURL());
623 // Don't force a new BrowsingInstance for debug URLs that are handled in the
624 // renderer process, like javascript: or chrome://crash.
625 if (IsRendererDebugURL(new_url))
626 return false;
628 // For security, we should transition between processes when one is a Web UI
629 // page and one isn't.
630 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
631 browser_context, current_url)) {
632 // If so, force a swap if destination is not an acceptable URL for Web UI.
633 // Here, data URLs are never allowed.
634 if (!WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
635 browser_context, new_url)) {
636 return true;
638 } else {
639 // Force a swap if it's a Web UI URL.
640 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
641 browser_context, new_url)) {
642 return true;
646 // Check with the content client as well. Important to pass current_url here,
647 // which uses the SiteInstance's site if there is no current_entry.
648 if (GetContentClient()->browser()->ShouldSwapBrowsingInstancesForNavigation(
649 render_frame_host_->GetSiteInstance(),
650 current_url, new_url)) {
651 return true;
654 // We can't switch a RenderView between view source and non-view source mode
655 // without screwing up the session history sometimes (when navigating between
656 // "view-source:http://foo.com/" and "http://foo.com/", Blink doesn't treat
657 // it as a new navigation). So require a BrowsingInstance switch.
658 if (current_entry &&
659 current_entry->IsViewSourceMode() != new_entry->IsViewSourceMode())
660 return true;
662 return false;
665 bool RenderFrameHostManager::ShouldReuseWebUI(
666 const NavigationEntry* current_entry,
667 const NavigationEntryImpl* new_entry) const {
668 NavigationControllerImpl& controller =
669 delegate_->GetControllerForRenderManager();
670 return current_entry && web_ui_.get() &&
671 (WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
672 controller.GetBrowserContext(), current_entry->GetURL()) ==
673 WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
674 controller.GetBrowserContext(), new_entry->GetURL()));
677 SiteInstance* RenderFrameHostManager::GetSiteInstanceForEntry(
678 const NavigationEntryImpl& entry,
679 SiteInstance* current_instance,
680 bool force_browsing_instance_swap) {
681 // Determine which SiteInstance to use for navigating to |entry|.
682 const GURL& dest_url = entry.GetURL();
683 NavigationControllerImpl& controller =
684 delegate_->GetControllerForRenderManager();
685 BrowserContext* browser_context = controller.GetBrowserContext();
687 // If the entry has an instance already we should use it.
688 if (entry.site_instance()) {
689 // If we are forcing a swap, this should be in a different BrowsingInstance.
690 if (force_browsing_instance_swap) {
691 CHECK(!entry.site_instance()->IsRelatedSiteInstance(
692 render_frame_host_->GetSiteInstance()));
694 return entry.site_instance();
697 // If a swap is required, we need to force the SiteInstance AND
698 // BrowsingInstance to be different ones, using CreateForURL.
699 if (force_browsing_instance_swap)
700 return SiteInstance::CreateForURL(browser_context, dest_url);
702 // (UGLY) HEURISTIC, process-per-site only:
704 // If this navigation is generated, then it probably corresponds to a search
705 // query. Given that search results typically lead to users navigating to
706 // other sites, we don't really want to use the search engine hostname to
707 // determine the site instance for this navigation.
709 // NOTE: This can be removed once we have a way to transition between
710 // RenderViews in response to a link click.
712 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessPerSite) &&
713 PageTransitionCoreTypeIs(entry.GetTransitionType(),
714 PAGE_TRANSITION_GENERATED)) {
715 return current_instance;
718 SiteInstanceImpl* current_site_instance =
719 static_cast<SiteInstanceImpl*>(current_instance);
721 // If we haven't used our SiteInstance (and thus RVH) yet, then we can use it
722 // for this entry. We won't commit the SiteInstance to this site until the
723 // navigation commits (in DidNavigate), unless the navigation entry was
724 // restored or it's a Web UI as described below.
725 if (!current_site_instance->HasSite()) {
726 // If we've already created a SiteInstance for our destination, we don't
727 // want to use this unused SiteInstance; use the existing one. (We don't
728 // do this check if the current_instance has a site, because for now, we
729 // want to compare against the current URL and not the SiteInstance's site.
730 // In this case, there is no current URL, so comparing against the site is
731 // ok. See additional comments below.)
733 // Also, if the URL should use process-per-site mode and there is an
734 // existing process for the site, we should use it. We can call
735 // GetRelatedSiteInstance() for this, which will eagerly set the site and
736 // thus use the correct process.
737 bool use_process_per_site =
738 RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) &&
739 RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url);
740 if (current_site_instance->HasRelatedSiteInstance(dest_url) ||
741 use_process_per_site) {
742 return current_site_instance->GetRelatedSiteInstance(dest_url);
745 // For extensions, Web UI URLs (such as the new tab page), and apps we do
746 // not want to use the current_instance if it has no site, since it will
747 // have a RenderProcessHost of PRIV_NORMAL. Create a new SiteInstance for
748 // this URL instead (with the correct process type).
749 if (current_site_instance->HasWrongProcessForURL(dest_url))
750 return current_site_instance->GetRelatedSiteInstance(dest_url);
752 // View-source URLs must use a new SiteInstance and BrowsingInstance.
753 // TODO(nasko): This is the same condition as later in the function. This
754 // should be taken into account when refactoring this method as part of
755 // http://crbug.com/123007.
756 if (entry.IsViewSourceMode())
757 return SiteInstance::CreateForURL(browser_context, dest_url);
759 // If we are navigating from a blank SiteInstance to a WebUI, make sure we
760 // create a new SiteInstance.
761 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
762 browser_context, dest_url)) {
763 return SiteInstance::CreateForURL(browser_context, dest_url);
766 // Normally the "site" on the SiteInstance is set lazily when the load
767 // actually commits. This is to support better process sharing in case
768 // the site redirects to some other site: we want to use the destination
769 // site in the site instance.
771 // In the case of session restore, as it loads all the pages immediately
772 // we need to set the site first, otherwise after a restore none of the
773 // pages would share renderers in process-per-site.
774 if (entry.restore_type() != NavigationEntryImpl::RESTORE_NONE)
775 current_site_instance->SetSite(dest_url);
777 return current_site_instance;
780 // Otherwise, only create a new SiteInstance for a cross-site navigation.
782 // TODO(creis): Once we intercept links and script-based navigations, we
783 // will be able to enforce that all entries in a SiteInstance actually have
784 // the same site, and it will be safe to compare the URL against the
785 // SiteInstance's site, as follows:
786 // const GURL& current_url = current_instance->site();
787 // For now, though, we're in a hybrid model where you only switch
788 // SiteInstances if you type in a cross-site URL. This means we have to
789 // compare the entry's URL to the last committed entry's URL.
790 NavigationEntry* current_entry = controller.GetLastCommittedEntry();
791 if (interstitial_page_) {
792 // The interstitial is currently the last committed entry, but we want to
793 // compare against the last non-interstitial entry.
794 current_entry = controller.GetEntryAtOffset(-1);
796 // If there is no last non-interstitial entry (and current_instance already
797 // has a site), then we must have been opened from another tab. We want
798 // to compare against the URL of the page that opened us, but we can't
799 // get to it directly. The best we can do is check against the site of
800 // the SiteInstance. This will be correct when we intercept links and
801 // script-based navigations, but for now, it could place some pages in a
802 // new process unnecessarily. We should only hit this case if a page tries
803 // to open a new tab to an interstitial-inducing URL, and then navigates
804 // the page to a different same-site URL. (This seems very unlikely in
805 // practice.)
806 const GURL& current_url = (current_entry) ? current_entry->GetURL() :
807 current_instance->GetSiteURL();
809 // View-source URLs must use a new SiteInstance and BrowsingInstance.
810 // We don't need a swap when going from view-source to a debug URL like
811 // chrome://crash, however.
812 // TODO(creis): Refactor this method so this duplicated code isn't needed.
813 // See http://crbug.com/123007.
814 if (current_entry &&
815 current_entry->IsViewSourceMode() != entry.IsViewSourceMode() &&
816 !IsRendererDebugURL(dest_url)) {
817 return SiteInstance::CreateForURL(browser_context, dest_url);
820 // Use the current SiteInstance for same site navigations, as long as the
821 // process type is correct. (The URL may have been installed as an app since
822 // the last time we visited it.)
823 if (SiteInstance::IsSameWebSite(browser_context, current_url, dest_url) &&
824 !current_site_instance->HasWrongProcessForURL(dest_url)) {
825 return current_instance;
828 // Start the new renderer in a new SiteInstance, but in the current
829 // BrowsingInstance. It is important to immediately give this new
830 // SiteInstance to a RenderViewHost (if it is different than our current
831 // SiteInstance), so that it is ref counted. This will happen in
832 // CreateRenderView.
833 return current_instance->GetRelatedSiteInstance(dest_url);
836 RenderFrameHostImpl* RenderFrameHostManager::CreateRenderFrameHost(
837 SiteInstance* site_instance,
838 int view_routing_id,
839 int frame_routing_id,
840 bool swapped_out,
841 bool hidden) {
842 if (frame_routing_id == MSG_ROUTING_NONE)
843 frame_routing_id = site_instance->GetProcess()->GetNextRoutingID();
845 // Create a RVH for main frames, or find the existing one for subframes.
846 FrameTree* frame_tree = frame_tree_node_->frame_tree();
847 RenderViewHostImpl* render_view_host = NULL;
848 if (frame_tree_node_->IsMainFrame()) {
849 render_view_host = frame_tree->CreateRenderViewHostForMainFrame(
850 site_instance, view_routing_id, frame_routing_id, swapped_out, hidden);
851 } else {
852 render_view_host = frame_tree->GetRenderViewHostForSubFrame(site_instance);
854 // If we haven't found a RVH for a subframe RFH, it's because we currently
855 // do not create top-level RFHs for pending subframe navigations. Create
856 // the RVH here for now.
857 // TODO(creis): Mirror the frame tree so this check isn't necessary.
858 if (!render_view_host) {
859 render_view_host = frame_tree->CreateRenderViewHostForMainFrame(
860 site_instance, view_routing_id, frame_routing_id, swapped_out,
861 hidden);
865 // TODO(creis): Make render_frame_host a scoped_ptr.
866 // TODO(creis): Pass hidden to RFH.
867 RenderFrameHostImpl* render_frame_host =
868 RenderFrameHostFactory::Create(render_view_host,
869 render_frame_delegate_,
870 frame_tree,
871 frame_tree_node_,
872 frame_routing_id,
873 swapped_out).release();
874 return render_frame_host;
877 int RenderFrameHostManager::CreateRenderFrame(
878 SiteInstance* instance,
879 int opener_route_id,
880 bool swapped_out,
881 bool hidden) {
882 CHECK(instance);
883 DCHECK(!swapped_out || hidden); // Swapped out views should always be hidden.
885 // We are creating a pending or swapped out RFH here. We should never create
886 // it in the same SiteInstance as our current RFH.
887 CHECK_NE(render_frame_host_->GetSiteInstance(), instance);
889 // Check if we've already created an RFH for this SiteInstance. If so, try
890 // to re-use the existing one, which has already been initialized. We'll
891 // remove it from the list of swapped out hosts if it commits.
892 RenderFrameHostImpl* new_render_frame_host =
893 GetSwappedOutRenderFrameHost(instance);
895 FrameTreeNode* parent_node = NULL;
896 if (frame_tree_node_)
897 parent_node = frame_tree_node_->parent();
899 if (new_render_frame_host) {
900 // Prevent the process from exiting while we're trying to use it.
901 if (!swapped_out) {
902 new_render_frame_host->GetProcess()->AddPendingView();
903 } else {
904 // Detect if this is a cross-process child frame that is navigating
905 // back to the same SiteInstance as its parent.
906 if (parent_node && cross_process_frame_connector_ &&
907 render_frame_host_->GetSiteInstance() == parent_node->
908 render_manager()->current_frame_host()->GetSiteInstance()) {
909 delete cross_process_frame_connector_;
910 cross_process_frame_connector_ = NULL;
913 } else {
914 // Create a new RenderFrameHost if we don't find an existing one.
915 // TODO(creis): Make new_render_frame_host a scoped_ptr.
916 new_render_frame_host = CreateRenderFrameHost(instance, MSG_ROUTING_NONE,
917 MSG_ROUTING_NONE, swapped_out,
918 hidden);
920 // If the new RFH is swapped out already, store it. Otherwise prevent the
921 // process from exiting while we're trying to navigate in it.
922 if (swapped_out) {
923 swapped_out_hosts_[instance->GetId()] = new_render_frame_host;
924 } else {
925 new_render_frame_host->GetProcess()->AddPendingView();
928 RenderViewHostImpl* render_view_host =
929 new_render_frame_host->render_view_host();
930 bool success = InitRenderView(render_view_host, opener_route_id);
931 if (success && frame_tree_node_->IsMainFrame()) {
932 // Don't show the main frame's view until we get a DidNavigate from it.
933 render_view_host->GetView()->Hide();
934 } else if (!swapped_out && pending_render_frame_host_) {
935 CancelPending();
939 // Use this as our new pending RFH if it isn't swapped out.
940 if (!swapped_out)
941 pending_render_frame_host_.reset(new_render_frame_host);
943 return new_render_frame_host->render_view_host()->GetRoutingID();
946 bool RenderFrameHostManager::InitRenderView(RenderViewHost* render_view_host,
947 int opener_route_id) {
948 // We may have initialized this RenderViewHost for another RenderFrameHost.
949 if (render_view_host->IsRenderViewLive())
950 return true;
952 // If the pending navigation is to a WebUI and the RenderView is not in a
953 // guest process, tell the RenderViewHost about any bindings it will need
954 // enabled.
955 if (pending_web_ui() && !render_view_host->GetProcess()->IsGuest()) {
956 render_view_host->AllowBindings(pending_web_ui()->GetBindings());
957 } else {
958 // Ensure that we don't create an unprivileged RenderView in a WebUI-enabled
959 // process unless it's swapped out.
960 RenderViewHostImpl* rvh_impl =
961 static_cast<RenderViewHostImpl*>(render_view_host);
962 if (!rvh_impl->IsSwappedOut()) {
963 CHECK(!ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
964 render_view_host->GetProcess()->GetID()));
968 return delegate_->CreateRenderViewForRenderManager(
969 render_view_host, opener_route_id, cross_process_frame_connector_);
972 void RenderFrameHostManager::CommitPending() {
973 // First check whether we're going to want to focus the location bar after
974 // this commit. We do this now because the navigation hasn't formally
975 // committed yet, so if we've already cleared |pending_web_ui_| the call chain
976 // this triggers won't be able to figure out what's going on.
977 bool will_focus_location_bar = delegate_->FocusLocationBarByDefault();
979 // We expect SwapOutOldPage to have canceled any modal dialogs and told the
980 // renderer to suppress any further dialogs until it is swapped out. However,
981 // crash reports indicate that it's still possible for modal dialogs to exist
982 // at this point, which poses a risk if we delete their RenderViewHost below.
983 // Cancel them again to be safe. http://crbug.com/324320.
984 delegate_->CancelModalDialogsForRenderManager();
986 // Next commit the Web UI, if any. Either replace |web_ui_| with
987 // |pending_web_ui_|, or clear |web_ui_| if there is no pending WebUI, or
988 // leave |web_ui_| as is if reusing it.
989 DCHECK(!(pending_web_ui_.get() && pending_and_current_web_ui_.get()));
990 if (pending_web_ui_) {
991 web_ui_.reset(pending_web_ui_.release());
992 } else if (!pending_and_current_web_ui_.get()) {
993 web_ui_.reset();
994 } else {
995 DCHECK_EQ(pending_and_current_web_ui_.get(), web_ui_.get());
996 pending_and_current_web_ui_.reset();
999 // It's possible for the pending_render_frame_host_ to be NULL when we aren't
1000 // crossing process boundaries. If so, we just needed to handle the Web UI
1001 // committing above and we're done.
1002 if (!pending_render_frame_host_) {
1003 if (will_focus_location_bar)
1004 delegate_->SetFocusToLocationBar(false);
1005 return;
1008 // Remember if the page was focused so we can focus the new renderer in
1009 // that case.
1010 bool focus_render_view = !will_focus_location_bar &&
1011 render_frame_host_->render_view_host()->GetView() &&
1012 render_frame_host_->render_view_host()->GetView()->HasFocus();
1014 // TODO(creis): As long as show/hide are on RVH, we don't want to do them for
1015 // subframe navigations or they'll interfere with the top-level page.
1016 bool is_main_frame = frame_tree_node_->IsMainFrame();
1018 // Swap in the pending frame and make it active. Also ensure the FrameTree
1019 // stays in sync.
1020 RenderFrameHostImpl* old_render_frame_host = render_frame_host_.release();
1021 render_frame_host_ = pending_render_frame_host_.Pass();
1022 if (is_main_frame)
1023 render_frame_host_->render_view_host()->AttachToFrameTree();
1025 // The process will no longer try to exit, so we can decrement the count.
1026 render_frame_host_->GetProcess()->RemovePendingView();
1028 // If the view is gone, then this RenderViewHost died while it was hidden.
1029 // We ignored the RenderProcessGone call at the time, so we should send it now
1030 // to make sure the sad tab shows up, etc.
1031 if (!render_frame_host_->render_view_host()->GetView()) {
1032 delegate_->RenderProcessGoneFromRenderManager(
1033 render_frame_host_->render_view_host());
1034 } else if (!delegate_->IsHidden()) {
1035 render_frame_host_->render_view_host()->GetView()->Show();
1038 // If the old view is live and top-level, hide it now that the new one is
1039 // visible.
1040 int32 old_site_instance_id =
1041 old_render_frame_host->GetSiteInstance()->GetId();
1042 if (old_render_frame_host->render_view_host()->GetView()) {
1043 if (is_main_frame) {
1044 old_render_frame_host->render_view_host()->GetView()->Hide();
1045 old_render_frame_host->render_view_host()->WasSwappedOut(base::Bind(
1046 &RenderFrameHostManager::ClearPendingShutdownRFHForSiteInstance,
1047 weak_factory_.GetWeakPtr(),
1048 old_site_instance_id,
1049 old_render_frame_host));
1050 } else {
1051 // TODO(creis): We'll need to set this back to false if we navigate back.
1052 old_render_frame_host->set_swapped_out(true);
1056 // Make sure the size is up to date. (Fix for bug 1079768.)
1057 delegate_->UpdateRenderViewSizeForRenderManager();
1059 if (will_focus_location_bar) {
1060 delegate_->SetFocusToLocationBar(false);
1061 } else if (focus_render_view &&
1062 render_frame_host_->render_view_host()->GetView()) {
1063 RenderWidgetHostViewPort::FromRWHV(
1064 render_frame_host_->render_view_host()->GetView())->Focus();
1067 // Notify that we've swapped RenderFrameHosts. We do this before shutting down
1068 // the RFH so that we can clean up RendererResources related to the RFH first.
1069 // TODO(creis): Only do this on top-level RFHs for now, and later update it to
1070 // pass the RFHs.
1071 if (is_main_frame) {
1072 delegate_->NotifySwappedFromRenderManager(
1073 old_render_frame_host->render_view_host(),
1074 render_frame_host_->render_view_host());
1077 // If the pending frame was on the swapped out list, we can remove it.
1078 swapped_out_hosts_.erase(render_frame_host_->GetSiteInstance()->GetId());
1080 if (old_render_frame_host->render_view_host()->IsRenderViewLive()) {
1081 // If the old RFH is live, we are swapping it out and should keep track of
1082 // it in case we navigate back to it, or it is waiting for the unload event
1083 // to execute in the background.
1084 // TODO(creis): Swap out the subframe in --site-per-process.
1085 if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess))
1086 DCHECK(old_render_frame_host->is_swapped_out() ||
1087 !RenderViewHostImpl::IsRVHStateActive(
1088 old_render_frame_host->render_view_host()->rvh_state()));
1089 // Temp fix for http://crbug.com/90867 until we do a better cleanup to make
1090 // sure we don't get different rvh instances for the same site instance
1091 // in the same rvhmgr.
1092 // TODO(creis): Clean this up.
1093 RenderFrameHostMap::iterator iter =
1094 swapped_out_hosts_.find(old_site_instance_id);
1095 if (iter != swapped_out_hosts_.end() &&
1096 iter->second != old_render_frame_host) {
1097 // Delete the RFH that will be replaced in the map to avoid a leak.
1098 delete iter->second;
1100 // If the RenderViewHost backing the RenderFrameHost is pending shutdown,
1101 // the RenderFrameHost should be put in the map of RenderFrameHosts pending
1102 // shutdown. Otherwise, it is stored in the map of swapped out
1103 // RenderFrameHosts.
1104 if (old_render_frame_host->render_view_host()->rvh_state() ==
1105 RenderViewHostImpl::STATE_PENDING_SHUTDOWN) {
1106 swapped_out_hosts_.erase(old_site_instance_id);
1107 RFHPendingDeleteMap::iterator pending_delete_iter =
1108 pending_delete_hosts_.find(old_site_instance_id);
1109 if (pending_delete_iter == pending_delete_hosts_.end() ||
1110 pending_delete_iter->second.get() != old_render_frame_host) {
1111 pending_delete_hosts_[old_site_instance_id] =
1112 linked_ptr<RenderFrameHostImpl>(old_render_frame_host);
1114 } else {
1115 swapped_out_hosts_[old_site_instance_id] = old_render_frame_host;
1118 // If there are no active views in this SiteInstance, it means that
1119 // this RFH was the last active one in the SiteInstance. Now that we
1120 // know that all RFHs are swapped out, we can delete all the RFHs and RVHs
1121 // in this SiteInstance. We do this after ensuring the RFH is on the
1122 // swapped out list to simplify the deletion.
1123 if (!static_cast<SiteInstanceImpl*>(
1124 old_render_frame_host->GetSiteInstance())->active_view_count()) {
1125 ShutdownRenderFrameHostsInSiteInstance(old_site_instance_id);
1126 // This is deleted while cleaning up the SiteInstance's views.
1127 old_render_frame_host = NULL;
1129 } else {
1130 delete old_render_frame_host;
1134 void RenderFrameHostManager::ShutdownRenderFrameHostsInSiteInstance(
1135 int32 site_instance_id) {
1136 // First remove any swapped out RFH for this SiteInstance from our own list.
1137 ClearSwappedOutRFHsInSiteInstance(site_instance_id, frame_tree_node_);
1139 // Use the safe RenderWidgetHost iterator for now to find all RenderViewHosts
1140 // in the SiteInstance, then tell their respective FrameTrees to remove all
1141 // swapped out RenderFrameHosts corresponding to them.
1142 // TODO(creis): Replace this with a RenderFrameHostIterator that protects
1143 // against use-after-frees if a later element is deleted before getting to it.
1144 scoped_ptr<RenderWidgetHostIterator> widgets(
1145 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
1146 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
1147 if (!widget->IsRenderView())
1148 continue;
1149 RenderViewHostImpl* rvh =
1150 static_cast<RenderViewHostImpl*>(RenderViewHost::From(widget));
1151 if (site_instance_id == rvh->GetSiteInstance()->GetId()) {
1152 // This deletes all RenderFrameHosts using the |rvh|, which then causes
1153 // |rvh| to Shutdown.
1154 FrameTree* tree = rvh->GetDelegate()->GetFrameTree();
1155 tree->ForEach(base::Bind(
1156 &RenderFrameHostManager::ClearSwappedOutRFHsInSiteInstance,
1157 site_instance_id));
1162 RenderFrameHostImpl* RenderFrameHostManager::UpdateRendererStateForNavigate(
1163 const NavigationEntryImpl& entry) {
1164 // If we are currently navigating cross-process, we want to get back to normal
1165 // and then navigate as usual.
1166 if (cross_navigation_pending_) {
1167 if (pending_render_frame_host_)
1168 CancelPending();
1169 cross_navigation_pending_ = false;
1172 // render_frame_host_'s SiteInstance and new_instance will not be deleted
1173 // before the end of this method, so we don't have to worry about their ref
1174 // counts dropping to zero.
1175 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1176 SiteInstance* new_instance = current_instance;
1178 // We do not currently swap processes for navigations in webview tag guests.
1179 bool is_guest_scheme = current_instance->GetSiteURL().SchemeIs(kGuestScheme);
1181 // Determine if we need a new BrowsingInstance for this entry. If true, this
1182 // implies that it will get a new SiteInstance (and likely process), and that
1183 // other tabs in the current BrowsingInstance will be unable to script it.
1184 // This is used for cases that require a process swap even in the
1185 // process-per-tab model, such as WebUI pages.
1186 const NavigationEntry* current_entry =
1187 delegate_->GetLastCommittedNavigationEntryForRenderManager();
1188 bool force_swap = !is_guest_scheme &&
1189 ShouldSwapBrowsingInstancesForNavigation(current_entry, &entry);
1190 if (!is_guest_scheme && (ShouldTransitionCrossSite() || force_swap))
1191 new_instance = GetSiteInstanceForEntry(entry, current_instance, force_swap);
1193 // If force_swap is true, we must use a different SiteInstance. If we didn't,
1194 // we would have two RenderFrameHosts in the same SiteInstance and the same
1195 // frame, resulting in page_id conflicts for their NavigationEntries.
1196 if (force_swap)
1197 CHECK_NE(new_instance, current_instance);
1199 if (new_instance != current_instance) {
1200 // New SiteInstance: create a pending RFH to navigate.
1201 DCHECK(!cross_navigation_pending_);
1203 // This will possibly create (set to NULL) a Web UI object for the pending
1204 // page. We'll use this later to give the page special access. This must
1205 // happen before the new renderer is created below so it will get bindings.
1206 // It must also happen after the above conditional call to CancelPending(),
1207 // otherwise CancelPending may clear the pending_web_ui_ and the page will
1208 // not have its bindings set appropriately.
1209 SetPendingWebUI(entry);
1211 // Ensure that we have created RFHs for the new RFH's opener chain if
1212 // we are staying in the same BrowsingInstance. This allows the pending RFH
1213 // to send cross-process script calls to its opener(s).
1214 int opener_route_id = MSG_ROUTING_NONE;
1215 if (new_instance->IsRelatedSiteInstance(current_instance)) {
1216 opener_route_id =
1217 delegate_->CreateOpenerRenderViewsForRenderManager(new_instance);
1220 // Create a non-swapped-out pending RFH with the given opener and navigate
1221 // it.
1222 int route_id = CreateRenderFrame(new_instance, opener_route_id, false,
1223 delegate_->IsHidden());
1224 if (route_id == MSG_ROUTING_NONE)
1225 return NULL;
1227 // Check if our current RFH is live before we set up a transition.
1228 if (!render_frame_host_->render_view_host()->IsRenderViewLive()) {
1229 if (!cross_navigation_pending_) {
1230 // The current RFH is not live. There's no reason to sit around with a
1231 // sad tab or a newly created RFH while we wait for the pending RFH to
1232 // navigate. Just switch to the pending RFH now and go back to non
1233 // cross-navigating (Note that we don't care about on{before}unload
1234 // handlers if the current RFH isn't live.)
1235 CommitPending();
1236 return render_frame_host_.get();
1237 } else {
1238 NOTREACHED();
1239 return render_frame_host_.get();
1242 // Otherwise, it's safe to treat this as a pending cross-site transition.
1244 // We need to wait until the beforeunload handler has run, unless we are
1245 // transferring an existing request (in which case it has already run).
1246 // Suspend the new render view (i.e., don't let it send the cross-site
1247 // Navigate message) until we hear back from the old renderer's
1248 // beforeunload handler. If the handler returns false, we'll have to
1249 // cancel the request.
1250 DCHECK(!pending_render_frame_host_->render_view_host()->
1251 are_navigations_suspended());
1252 bool is_transfer =
1253 entry.transferred_global_request_id() != GlobalRequestID();
1254 if (is_transfer) {
1255 // We don't need to stop the old renderer or run beforeunload/unload
1256 // handlers, because those have already been done.
1257 DCHECK(pending_nav_params_->global_request_id ==
1258 entry.transferred_global_request_id());
1259 } else {
1260 // Also make sure the old render view stops, in case a load is in
1261 // progress. (We don't want to do this for transfers, since it will
1262 // interrupt the transfer with an unexpected DidStopLoading.)
1263 render_frame_host_->render_view_host()->Send(new ViewMsg_Stop(
1264 render_frame_host_->render_view_host()->GetRoutingID()));
1266 pending_render_frame_host_->render_view_host()->SetNavigationsSuspended(
1267 true, base::TimeTicks());
1269 // Tell the CrossSiteRequestManager that this RVH has a pending cross-site
1270 // request, so that ResourceDispatcherHost will know to tell us to run the
1271 // old page's unload handler before it sends the response.
1272 // TODO(creis): This needs to be on the RFH.
1273 pending_render_frame_host_->render_view_host()->
1274 SetHasPendingCrossSiteRequest(true);
1277 // We now have a pending RFH.
1278 DCHECK(!cross_navigation_pending_);
1279 cross_navigation_pending_ = true;
1281 // Unless we are transferring an existing request, we should now
1282 // tell the old render view to run its beforeunload handler, since it
1283 // doesn't otherwise know that the cross-site request is happening. This
1284 // will trigger a call to OnBeforeUnloadACK with the reply.
1285 if (!is_transfer)
1286 render_frame_host_->DispatchBeforeUnload(true);
1288 return pending_render_frame_host_.get();
1291 // Otherwise the same SiteInstance can be used. Navigate render_frame_host_.
1292 DCHECK(!cross_navigation_pending_);
1293 if (ShouldReuseWebUI(current_entry, &entry)) {
1294 pending_web_ui_.reset();
1295 pending_and_current_web_ui_ = web_ui_->AsWeakPtr();
1296 } else {
1297 SetPendingWebUI(entry);
1299 // Make sure the new RenderViewHost has the right bindings.
1300 if (pending_web_ui() && !render_frame_host_->GetProcess()->IsGuest()) {
1301 render_frame_host_->render_view_host()->AllowBindings(
1302 pending_web_ui()->GetBindings());
1306 if (pending_web_ui() &&
1307 render_frame_host_->render_view_host()->IsRenderViewLive()) {
1308 pending_web_ui()->GetController()->RenderViewReused(
1309 render_frame_host_->render_view_host());
1312 // The renderer can exit view source mode when any error or cancellation
1313 // happen. We must overwrite to recover the mode.
1314 if (entry.IsViewSourceMode()) {
1315 render_frame_host_->render_view_host()->Send(
1316 new ViewMsg_EnableViewSourceMode(
1317 render_frame_host_->render_view_host()->GetRoutingID()));
1320 return render_frame_host_.get();
1323 void RenderFrameHostManager::CancelPending() {
1324 RenderFrameHostImpl* pending_render_frame_host =
1325 pending_render_frame_host_.release();
1327 RenderViewDevToolsAgentHost::OnCancelPendingNavigation(
1328 pending_render_frame_host->render_view_host(),
1329 render_frame_host_->render_view_host());
1331 // We no longer need to prevent the process from exiting.
1332 pending_render_frame_host->GetProcess()->RemovePendingView();
1334 // The pending RFH may already be on the swapped out list if we started to
1335 // swap it back in and then canceled. If so, make sure it gets swapped out
1336 // again. If it's not on the swapped out list (e.g., aborting a pending
1337 // load), then it's safe to shut down.
1338 if (IsOnSwappedOutList(pending_render_frame_host)) {
1339 // Any currently suspended navigations are no longer needed.
1340 pending_render_frame_host->render_view_host()->CancelSuspendedNavigations();
1342 pending_render_frame_host->SwapOut();
1343 } else {
1344 // We won't be coming back, so shut this one down.
1345 delete pending_render_frame_host;
1348 pending_web_ui_.reset();
1349 pending_and_current_web_ui_.reset();
1352 void RenderFrameHostManager::RenderViewDeleted(RenderViewHost* rvh) {
1353 // We are doing this in order to work around and to track a crasher
1354 // (http://crbug.com/23411) where it seems that pending_render_frame_host_ is
1355 // deleted (not sure from where) but not NULLed.
1356 if (pending_render_frame_host_ &&
1357 rvh == pending_render_frame_host_->render_view_host()) {
1358 // If you hit this NOTREACHED, please report it in the following bug
1359 // http://crbug.com/23411 Make sure to include what you were doing when it
1360 // happened (navigating to a new page, closing a tab...) and if you can
1361 // reproduce.
1362 NOTREACHED();
1363 pending_render_frame_host_.reset();
1366 // Make sure deleted RVHs are not kept in the swapped out list while we are
1367 // still alive. (If render_frame_host_ is null, we're already being deleted.)
1368 if (!render_frame_host_)
1369 return;
1371 // We can't look it up by SiteInstance ID, which may no longer be valid.
1372 for (RenderFrameHostMap::iterator iter = swapped_out_hosts_.begin();
1373 iter != swapped_out_hosts_.end();
1374 ++iter) {
1375 if (iter->second->render_view_host() == rvh) {
1376 swapped_out_hosts_.erase(iter);
1377 break;
1382 bool RenderFrameHostManager::IsRVHOnSwappedOutList(
1383 RenderViewHostImpl* rvh) const {
1384 RenderFrameHostImpl* render_frame_host = GetSwappedOutRenderFrameHost(
1385 rvh->GetSiteInstance());
1386 if (!render_frame_host)
1387 return false;
1388 return IsOnSwappedOutList(render_frame_host);
1391 bool RenderFrameHostManager::IsOnSwappedOutList(
1392 RenderFrameHostImpl* rfh) const {
1393 if (!rfh->GetSiteInstance())
1394 return false;
1396 RenderFrameHostMap::const_iterator iter = swapped_out_hosts_.find(
1397 rfh->GetSiteInstance()->GetId());
1398 if (iter == swapped_out_hosts_.end())
1399 return false;
1401 return iter->second == rfh;
1404 RenderViewHostImpl* RenderFrameHostManager::GetSwappedOutRenderViewHost(
1405 SiteInstance* instance) const {
1406 RenderFrameHostImpl* render_frame_host =
1407 GetSwappedOutRenderFrameHost(instance);
1408 if (render_frame_host)
1409 return render_frame_host->render_view_host();
1410 return NULL;
1413 RenderFrameHostImpl* RenderFrameHostManager::GetSwappedOutRenderFrameHost(
1414 SiteInstance* instance) const {
1415 RenderFrameHostMap::const_iterator iter =
1416 swapped_out_hosts_.find(instance->GetId());
1417 if (iter != swapped_out_hosts_.end())
1418 return iter->second;
1420 return NULL;
1423 } // namespace content