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"
9 #include "base/command_line.h"
10 #include "base/debug/trace_event.h"
11 #include "base/logging.h"
12 #include "base/stl_util.h"
13 #include "content/browser/child_process_security_policy_impl.h"
14 #include "content/browser/devtools/render_view_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/navigation_request_info.h"
22 #include "content/browser/frame_host/navigator.h"
23 #include "content/browser/frame_host/render_frame_host_factory.h"
24 #include "content/browser/frame_host/render_frame_host_impl.h"
25 #include "content/browser/frame_host/render_frame_proxy_host.h"
26 #include "content/browser/renderer_host/render_process_host_impl.h"
27 #include "content/browser/renderer_host/render_view_host_factory.h"
28 #include "content/browser/renderer_host/render_view_host_impl.h"
29 #include "content/browser/site_instance_impl.h"
30 #include "content/browser/webui/web_ui_controller_factory_registry.h"
31 #include "content/browser/webui/web_ui_impl.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/url_constants.h"
45 RenderFrameHostManager::PendingNavigationParams::PendingNavigationParams(
46 const GlobalRequestID& global_request_id,
47 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
48 const std::vector<GURL>& transfer_url_chain,
50 PageTransition page_transition,
52 bool should_replace_current_entry)
53 : global_request_id(global_request_id),
54 cross_site_transferring_request(cross_site_transferring_request.Pass()),
55 transfer_url_chain(transfer_url_chain),
57 page_transition(page_transition),
58 render_frame_id(render_frame_id),
59 should_replace_current_entry(should_replace_current_entry) {
62 RenderFrameHostManager::PendingNavigationParams::~PendingNavigationParams() {}
64 bool RenderFrameHostManager::ClearRFHsPendingShutdown(FrameTreeNode* node) {
65 node->render_manager()->pending_delete_hosts_.clear();
69 RenderFrameHostManager::RenderFrameHostManager(
70 FrameTreeNode* frame_tree_node,
71 RenderFrameHostDelegate* render_frame_delegate,
72 RenderViewHostDelegate* render_view_delegate,
73 RenderWidgetHostDelegate* render_widget_delegate,
75 : frame_tree_node_(frame_tree_node),
77 cross_navigation_pending_(false),
78 render_frame_delegate_(render_frame_delegate),
79 render_view_delegate_(render_view_delegate),
80 render_widget_delegate_(render_widget_delegate),
81 interstitial_page_(NULL),
83 DCHECK(frame_tree_node_);
86 RenderFrameHostManager::~RenderFrameHostManager() {
87 if (pending_render_frame_host_)
90 // We should always have a current RenderFrameHost except in some tests.
91 SetRenderFrameHost(scoped_ptr<RenderFrameHostImpl>());
93 // Delete any swapped out RenderFrameHosts.
94 STLDeleteValues(&proxy_hosts_);
97 void RenderFrameHostManager::Init(BrowserContext* browser_context,
98 SiteInstance* site_instance,
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.
105 site_instance = SiteInstance::Create(browser_context);
107 SetRenderFrameHost(CreateRenderFrameHost(site_instance,
111 delegate_->IsHidden()));
113 // Keep track of renderer processes as they start to shut down or are
115 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSED,
116 NotificationService::AllSources());
117 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSING,
118 NotificationService::AllSources());
121 RenderViewHostImpl* RenderFrameHostManager::current_host() const {
122 if (!render_frame_host_)
124 return render_frame_host_->render_view_host();
127 RenderViewHostImpl* RenderFrameHostManager::pending_render_view_host() const {
128 if (!pending_render_frame_host_)
130 return pending_render_frame_host_->render_view_host();
133 RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const {
134 if (interstitial_page_)
135 return interstitial_page_->GetView();
136 if (!render_frame_host_)
138 return render_frame_host_->render_view_host()->GetView();
141 RenderFrameProxyHost* RenderFrameHostManager::GetProxyToParent() {
142 if (frame_tree_node_->IsMainFrame())
145 RenderFrameProxyHostMap::iterator iter =
146 proxy_hosts_.find(frame_tree_node_->parent()
148 ->current_frame_host()
151 if (iter == proxy_hosts_.end())
157 void RenderFrameHostManager::SetPendingWebUI(const NavigationEntryImpl& entry) {
158 pending_web_ui_.reset(
159 delegate_->CreateWebUIForRenderManager(entry.GetURL()));
160 pending_and_current_web_ui_.reset();
162 // If we have assigned (zero or more) bindings to this NavigationEntry in the
163 // past, make sure we're not granting it different bindings than it had
164 // before. If so, note it and don't give it any bindings, to avoid a
165 // potential privilege escalation.
166 if (pending_web_ui_.get() &&
167 entry.bindings() != NavigationEntryImpl::kInvalidBindings &&
168 pending_web_ui_->GetBindings() != entry.bindings()) {
170 base::UserMetricsAction("ProcessSwapBindingsMismatch_RVHM"));
171 pending_web_ui_.reset();
175 RenderFrameHostImpl* RenderFrameHostManager::Navigate(
176 const NavigationEntryImpl& entry) {
177 TRACE_EVENT0("browser", "RenderFrameHostManager:Navigate");
178 // Create a pending RenderFrameHost to use for the navigation.
179 RenderFrameHostImpl* dest_render_frame_host = UpdateStateForNavigate(entry);
180 if (!dest_render_frame_host)
181 return NULL; // We weren't able to create a pending render frame host.
183 // If the current render_frame_host_ isn't live, we should create it so
184 // that we don't show a sad tab while the dest_render_frame_host fetches
185 // its first page. (Bug 1145340)
186 if (dest_render_frame_host != render_frame_host_ &&
187 !render_frame_host_->render_view_host()->IsRenderViewLive()) {
188 // Note: we don't call InitRenderView here because we are navigating away
189 // soon anyway, and we don't have the NavigationEntry for this host.
190 delegate_->CreateRenderViewForRenderManager(
191 render_frame_host_->render_view_host(), MSG_ROUTING_NONE,
192 MSG_ROUTING_NONE, frame_tree_node_->IsMainFrame());
195 // If the renderer crashed, then try to create a new one to satisfy this
196 // navigation request.
197 if (!dest_render_frame_host->render_view_host()->IsRenderViewLive()) {
198 // Recreate the opener chain.
199 int opener_route_id = delegate_->CreateOpenerRenderViewsForRenderManager(
200 dest_render_frame_host->GetSiteInstance());
201 if (!InitRenderView(dest_render_frame_host->render_view_host(),
204 frame_tree_node_->IsMainFrame()))
207 // Now that we've created a new renderer, be sure to hide it if it isn't
208 // our primary one. Otherwise, we might crash if we try to call Show()
210 if (dest_render_frame_host != render_frame_host_ &&
211 dest_render_frame_host->render_view_host()->GetView()) {
212 dest_render_frame_host->render_view_host()->GetView()->Hide();
214 // Notify here as we won't be calling CommitPending (which does the
216 delegate_->NotifySwappedFromRenderManager(
217 NULL, render_frame_host_.get(), frame_tree_node_->IsMainFrame());
221 // If entry includes the request ID of a request that is being transferred,
222 // the destination render frame will take ownership, so release ownership of
224 if (pending_nav_params_ &&
225 pending_nav_params_->global_request_id ==
226 entry.transferred_global_request_id()) {
227 pending_nav_params_->cross_site_transferring_request->ReleaseRequest();
230 return dest_render_frame_host;
233 void RenderFrameHostManager::Stop() {
234 render_frame_host_->render_view_host()->Stop();
236 // If we are cross-navigating, we should stop the pending renderers. This
237 // will lead to a DidFailProvisionalLoad, which will properly destroy them.
238 if (cross_navigation_pending_) {
239 pending_render_frame_host_->render_view_host()->Send(new ViewMsg_Stop(
240 pending_render_frame_host_->render_view_host()->GetRoutingID()));
244 void RenderFrameHostManager::SetIsLoading(bool is_loading) {
245 render_frame_host_->render_view_host()->SetIsLoading(is_loading);
246 if (pending_render_frame_host_)
247 pending_render_frame_host_->render_view_host()->SetIsLoading(is_loading);
250 bool RenderFrameHostManager::ShouldCloseTabOnUnresponsiveRenderer() {
251 if (!cross_navigation_pending_)
254 // We should always have a pending RFH when there's a cross-process navigation
255 // in progress. Sanity check this for http://crbug.com/276333.
256 CHECK(pending_render_frame_host_);
258 // If the tab becomes unresponsive during {before}unload while doing a
259 // cross-site navigation, proceed with the navigation. (This assumes that
260 // the pending RenderFrameHost is still responsive.)
261 if (render_frame_host_->render_view_host()->IsWaitingForUnloadACK()) {
262 // The request has been started and paused while we're waiting for the
263 // unload handler to finish. We'll pretend that it did. The pending
264 // renderer will then be swapped in as part of the usual DidNavigate logic.
265 // (If the unload handler later finishes, this call will be ignored because
266 // the pending_nav_params_ state will already be cleaned up.)
267 current_host()->OnSwappedOut(true);
268 } else if (render_frame_host_->render_view_host()->
269 is_waiting_for_beforeunload_ack()) {
270 // Haven't gotten around to starting the request, because we're still
271 // waiting for the beforeunload handler to finish. We'll pretend that it
272 // did finish, to let the navigation proceed. Note that there's a danger
273 // that the beforeunload handler will later finish and possibly return
274 // false (meaning the navigation should not proceed), but we'll ignore it
275 // in this case because it took too long.
276 if (pending_render_frame_host_->are_navigations_suspended()) {
277 pending_render_frame_host_->SetNavigationsSuspended(
278 false, base::TimeTicks::Now());
284 void RenderFrameHostManager::OnBeforeUnloadACK(
285 bool for_cross_site_transition,
287 const base::TimeTicks& proceed_time) {
288 if (for_cross_site_transition) {
289 // Ignore if we're not in a cross-site navigation.
290 if (!cross_navigation_pending_)
294 // Ok to unload the current page, so proceed with the cross-site
295 // navigation. Note that if navigations are not currently suspended, it
296 // might be because the renderer was deemed unresponsive and this call was
297 // already made by ShouldCloseTabOnUnresponsiveRenderer. In that case, it
298 // is ok to do nothing here.
299 if (pending_render_frame_host_ &&
300 pending_render_frame_host_->are_navigations_suspended()) {
301 pending_render_frame_host_->SetNavigationsSuspended(false,
305 // Current page says to cancel.
307 cross_navigation_pending_ = false;
310 // Non-cross site transition means closing the entire tab.
311 bool proceed_to_fire_unload;
312 delegate_->BeforeUnloadFiredFromRenderManager(proceed, proceed_time,
313 &proceed_to_fire_unload);
315 if (proceed_to_fire_unload) {
316 // If we're about to close the tab and there's a pending RFH, cancel it.
317 // Otherwise, if the navigation in the pending RFH completes before the
318 // close in the current RFH, we'll lose the tab close.
319 if (pending_render_frame_host_) {
321 cross_navigation_pending_ = false;
324 // This is not a cross-site navigation, the tab is being closed.
325 render_frame_host_->render_view_host()->ClosePage();
330 void RenderFrameHostManager::OnCrossSiteResponse(
331 RenderFrameHostImpl* pending_render_frame_host,
332 const GlobalRequestID& global_request_id,
333 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
334 const std::vector<GURL>& transfer_url_chain,
335 const Referrer& referrer,
336 PageTransition page_transition,
337 bool should_replace_current_entry) {
338 // This should be called either when the pending RFH is ready to commit or
339 // when we realize that the current RFH's request requires a transfer.
340 DCHECK(pending_render_frame_host == pending_render_frame_host_ ||
341 pending_render_frame_host == render_frame_host_);
343 // TODO(creis): Eventually we will want to check all navigation responses
344 // here, but currently we pass information for a transfer if
345 // ShouldSwapProcessesForRedirect returned true in the network stack.
346 // In that case, we should set up a transfer after the unload handler runs.
347 // If |cross_site_transferring_request| is NULL, we will just run the unload
348 // handler and resume.
349 pending_nav_params_.reset(new PendingNavigationParams(
350 global_request_id, cross_site_transferring_request.Pass(),
351 transfer_url_chain, referrer, page_transition,
352 pending_render_frame_host->GetRoutingID(),
353 should_replace_current_entry));
355 // Run the unload handler of the current page.
359 void RenderFrameHostManager::OnDeferredAfterResponseStarted(
360 const GlobalRequestID& global_request_id,
361 RenderFrameHostImpl* pending_render_frame_host) {
362 DCHECK(!response_started_id_.get());
364 response_started_id_.reset(new GlobalRequestID(global_request_id));
367 void RenderFrameHostManager::ResumeResponseDeferredAtStart() {
368 DCHECK(response_started_id_.get());
370 RenderProcessHostImpl* process =
371 static_cast<RenderProcessHostImpl*>(render_frame_host_->GetProcess());
372 process->ResumeResponseDeferredAtStart(*response_started_id_);
374 render_frame_host_->ClearPendingTransitionRequestData();
376 response_started_id_.reset();
379 void RenderFrameHostManager::SwappedOut(
380 RenderFrameHostImpl* render_frame_host) {
381 // Make sure this is from our current RFH, and that we have a pending
382 // navigation from OnCrossSiteResponse. (There may be no pending navigation
383 // for data URLs that don't make network requests, for example.) If not,
384 // just return early and ignore.
385 if (render_frame_host != render_frame_host_ || !pending_nav_params_.get()) {
386 pending_nav_params_.reset();
390 // Now that the unload handler has run, we need to either initiate the
391 // pending transfer (if there is one) or resume the paused response (if not).
392 // TODO(creis): The blank swapped out page is visible during this time, but
393 // we can shorten this by delivering the response directly, rather than
394 // forcing an identical request to be made.
395 if (pending_nav_params_->cross_site_transferring_request) {
396 // Sanity check that the params are for the correct frame and process.
397 // These should match the RenderFrameHost that made the request.
398 // If it started as a cross-process navigation via OpenURL, this is the
399 // pending one. If it wasn't cross-process until the transfer, this is the
401 int render_frame_id = pending_render_frame_host_ ?
402 pending_render_frame_host_->GetRoutingID() :
403 render_frame_host_->GetRoutingID();
404 DCHECK_EQ(render_frame_id, pending_nav_params_->render_frame_id);
405 int process_id = pending_render_frame_host_ ?
406 pending_render_frame_host_->GetProcess()->GetID() :
407 render_frame_host_->GetProcess()->GetID();
408 DCHECK_EQ(process_id, pending_nav_params_->global_request_id.child_id);
410 // Treat the last URL in the chain as the destination and the remainder as
411 // the redirect chain.
412 CHECK(pending_nav_params_->transfer_url_chain.size());
413 GURL transfer_url = pending_nav_params_->transfer_url_chain.back();
414 pending_nav_params_->transfer_url_chain.pop_back();
416 // We don't know whether the original request had |user_action| set to true.
417 // However, since we force the navigation to be in the current tab, it
419 render_frame_host->frame_tree_node()->navigator()->RequestTransferURL(
422 pending_nav_params_->transfer_url_chain,
423 pending_nav_params_->referrer,
424 pending_nav_params_->page_transition,
426 pending_nav_params_->global_request_id,
427 pending_nav_params_->should_replace_current_entry,
429 } else if (pending_render_frame_host_) {
430 RenderProcessHostImpl* pending_process =
431 static_cast<RenderProcessHostImpl*>(
432 pending_render_frame_host_->GetProcess());
433 pending_process->ResumeDeferredNavigation(
434 pending_nav_params_->global_request_id);
436 pending_nav_params_.reset();
439 void RenderFrameHostManager::DidNavigateFrame(
440 RenderFrameHostImpl* render_frame_host) {
441 if (!cross_navigation_pending_) {
442 DCHECK(!pending_render_frame_host_);
444 // We should only hear this from our current renderer.
445 DCHECK_EQ(render_frame_host_, render_frame_host);
447 // Even when there is no pending RVH, there may be a pending Web UI.
448 if (pending_web_ui())
453 if (render_frame_host == pending_render_frame_host_) {
454 // The pending cross-site navigation completed, so show the renderer.
455 // If it committed without sending network requests (e.g., data URLs),
456 // then we still need to swap out the old RFH first and run its unload
457 // handler, only if it hasn't happened yet. OK for that to happen in the
459 if (pending_render_frame_host_->HasPendingCrossSiteRequest() &&
460 pending_render_frame_host_->render_view_host()->rvh_state() ==
461 RenderViewHostImpl::STATE_DEFAULT) {
466 cross_navigation_pending_ = false;
467 } else if (render_frame_host == render_frame_host_) {
468 // A navigation in the original page has taken place. Cancel the pending
471 cross_navigation_pending_ = false;
473 // No one else should be sending us DidNavigate in this state.
478 // TODO(creis): Take in RenderFrameHost instead, since frames can have openers.
479 void RenderFrameHostManager::DidDisownOpener(RenderViewHost* render_view_host) {
480 // Notify all swapped out hosts, including the pending RVH.
481 for (RenderFrameProxyHostMap::iterator iter = proxy_hosts_.begin();
482 iter != proxy_hosts_.end();
484 DCHECK_NE(iter->second->GetSiteInstance(),
485 current_frame_host()->GetSiteInstance());
486 iter->second->GetRenderViewHost()->DisownOpener();
490 void RenderFrameHostManager::RendererProcessClosing(
491 RenderProcessHost* render_process_host) {
492 // Remove any swapped out RVHs from this process, so that we don't try to
493 // swap them back in while the process is exiting. Start by finding them,
494 // since there could be more than one.
495 std::list<int> ids_to_remove;
496 for (RenderFrameProxyHostMap::iterator iter = proxy_hosts_.begin();
497 iter != proxy_hosts_.end();
499 if (iter->second->GetProcess() == render_process_host)
500 ids_to_remove.push_back(iter->first);
504 while (!ids_to_remove.empty()) {
505 delete proxy_hosts_[ids_to_remove.back()];
506 proxy_hosts_.erase(ids_to_remove.back());
507 ids_to_remove.pop_back();
511 void RenderFrameHostManager::SwapOutOldPage() {
512 // Should only see this while we have a pending renderer or transfer.
513 CHECK(cross_navigation_pending_ || pending_nav_params_.get());
515 // Tell the renderer to suppress any further modal dialogs so that we can swap
516 // it out. This must be done before canceling any current dialog, in case
517 // there is a loop creating additional dialogs.
518 // TODO(creis): Handle modal dialogs in subframe processes.
519 render_frame_host_->render_view_host()->SuppressDialogsUntilSwapOut();
521 // Now close any modal dialogs that would prevent us from swapping out. This
522 // must be done separately from SwapOut, so that the PageGroupLoadDeferrer is
523 // no longer on the stack when we send the SwapOut message.
524 delegate_->CancelModalDialogsForRenderManager();
526 // Create the RenderFrameProxyHost that will replace the
527 // RenderFrameHost which is swapping out. If one exists, ensure it is deleted
528 // from the map and not leaked.
529 DeleteRenderFrameProxyHost(render_frame_host_->GetSiteInstance());
531 RenderFrameProxyHost* proxy = new RenderFrameProxyHost(
532 render_frame_host_->GetSiteInstance(), frame_tree_node_);
533 std::pair<RenderFrameProxyHostMap::iterator, bool> result =
534 proxy_hosts_.insert(std::make_pair(
535 render_frame_host_->GetSiteInstance()->GetId(), proxy));
536 CHECK(result.second) << "Inserting a duplicate item.";
538 // Tell the old frame it is being swapped out. This will fire the unload
539 // handler in the background (without firing the beforeunload handler a second
540 // time). When the navigation completes, we will send a message to the
541 // ResourceDispatcherHost, allowing the pending RVH's response to resume.
542 render_frame_host_->SwapOut(proxy);
544 // ResourceDispatcherHost has told us to run the onunload handler, which
545 // means it is not a download or unsafe page, and we are going to perform the
546 // navigation. Thus, we no longer need to remember that the RenderFrameHost
547 // is part of a pending cross-site request.
548 if (pending_render_frame_host_) {
549 pending_render_frame_host_->SetHasPendingCrossSiteRequest(false);
553 void RenderFrameHostManager::ClearPendingShutdownRFHForSiteInstance(
554 int32 site_instance_id,
555 RenderFrameHostImpl* rfh) {
556 RFHPendingDeleteMap::iterator iter =
557 pending_delete_hosts_.find(site_instance_id);
558 if (iter != pending_delete_hosts_.end() && iter->second.get() == rfh)
559 pending_delete_hosts_.erase(site_instance_id);
562 void RenderFrameHostManager::ResetProxyHosts() {
563 STLDeleteValues(&proxy_hosts_);
566 void RenderFrameHostManager::OnBeginNavigation(
567 const FrameHostMsg_BeginNavigation_Params& params) {
568 // TODO(clamy): Check if navigations are blocked and if so, return
570 NavigationRequestInfo info(params);
572 info.first_party_for_cookies = frame_tree_node_->IsMainFrame() ?
573 params.url : frame_tree_node_->frame_tree()->root()->current_url();
574 info.is_main_frame = frame_tree_node_->IsMainFrame();
575 info.parent_is_main_frame = !frame_tree_node_->parent() ?
576 false : frame_tree_node_->parent()->IsMainFrame();
577 info.is_showing = GetRenderWidgetHostView()->IsShowing();
579 navigation_request_.reset(
580 new NavigationRequest(info, frame_tree_node_->frame_tree_node_id()));
581 navigation_request_->BeginNavigation(params.request_body);
582 // TODO(clamy): If we have no live RenderFrameHost to handle the request (eg
583 // cross-site navigation) spawn one speculatively here and keep track of it.
586 void RenderFrameHostManager::Observe(
588 const NotificationSource& source,
589 const NotificationDetails& details) {
591 case NOTIFICATION_RENDERER_PROCESS_CLOSED:
592 case NOTIFICATION_RENDERER_PROCESS_CLOSING:
593 RendererProcessClosing(
594 Source<RenderProcessHost>(source).ptr());
602 bool RenderFrameHostManager::ClearProxiesInSiteInstance(
603 int32 site_instance_id,
604 FrameTreeNode* node) {
605 RenderFrameProxyHostMap::iterator iter =
606 node->render_manager()->proxy_hosts_.find(site_instance_id);
607 if (iter != node->render_manager()->proxy_hosts_.end()) {
608 RenderFrameProxyHost* proxy = iter->second;
609 // If the RVH is pending swap out, it needs to switch state to
610 // pending shutdown. Otherwise it is deleted.
611 if (proxy->GetRenderViewHost()->rvh_state() ==
612 RenderViewHostImpl::STATE_PENDING_SWAP_OUT) {
613 scoped_ptr<RenderFrameHostImpl> swapped_out_rfh =
614 proxy->PassFrameHostOwnership();
616 swapped_out_rfh->SetPendingShutdown(base::Bind(
617 &RenderFrameHostManager::ClearPendingShutdownRFHForSiteInstance,
618 node->render_manager()->weak_factory_.GetWeakPtr(),
620 swapped_out_rfh.get()));
621 RFHPendingDeleteMap::iterator pending_delete_iter =
622 node->render_manager()->pending_delete_hosts_.find(site_instance_id);
623 if (pending_delete_iter ==
624 node->render_manager()->pending_delete_hosts_.end() ||
625 pending_delete_iter->second.get() != swapped_out_rfh) {
626 node->render_manager()->pending_delete_hosts_[site_instance_id] =
627 linked_ptr<RenderFrameHostImpl>(swapped_out_rfh.release());
631 node->render_manager()->proxy_hosts_.erase(site_instance_id);
637 bool RenderFrameHostManager::ShouldTransitionCrossSite() {
638 // False in the single-process mode, as it makes RVHs to accumulate
639 // in swapped_out_hosts_.
640 // True if we are using process-per-site-instance (default) or
641 // process-per-site (kProcessPerSite).
643 !CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess) &&
644 !CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessPerTab);
647 bool RenderFrameHostManager::ShouldSwapBrowsingInstancesForNavigation(
648 const GURL& current_effective_url,
649 bool current_is_view_source_mode,
650 SiteInstance* new_site_instance,
651 const GURL& new_effective_url,
652 bool new_is_view_source_mode) const {
653 // If new_entry already has a SiteInstance, assume it is correct. We only
654 // need to force a swap if it is in a different BrowsingInstance.
655 if (new_site_instance) {
656 return !new_site_instance->IsRelatedSiteInstance(
657 render_frame_host_->GetSiteInstance());
660 // Check for reasons to swap processes even if we are in a process model that
661 // doesn't usually swap (e.g., process-per-tab). Any time we return true,
662 // the new_entry will be rendered in a new SiteInstance AND BrowsingInstance.
663 BrowserContext* browser_context =
664 delegate_->GetControllerForRenderManager().GetBrowserContext();
666 // Don't force a new BrowsingInstance for debug URLs that are handled in the
667 // renderer process, like javascript: or chrome://crash.
668 if (IsRendererDebugURL(new_effective_url))
671 // For security, we should transition between processes when one is a Web UI
672 // page and one isn't.
673 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
674 browser_context, current_effective_url)) {
675 // If so, force a swap if destination is not an acceptable URL for Web UI.
676 // Here, data URLs are never allowed.
677 if (!WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
678 browser_context, new_effective_url)) {
682 // Force a swap if it's a Web UI URL.
683 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
684 browser_context, new_effective_url)) {
689 // Check with the content client as well. Important to pass
690 // current_effective_url here, which uses the SiteInstance's site if there is
692 if (GetContentClient()->browser()->ShouldSwapBrowsingInstancesForNavigation(
693 render_frame_host_->GetSiteInstance(),
694 current_effective_url, new_effective_url)) {
698 // We can't switch a RenderView between view source and non-view source mode
699 // without screwing up the session history sometimes (when navigating between
700 // "view-source:http://foo.com/" and "http://foo.com/", Blink doesn't treat
701 // it as a new navigation). So require a BrowsingInstance switch.
702 if (current_is_view_source_mode != new_is_view_source_mode)
708 bool RenderFrameHostManager::ShouldReuseWebUI(
709 const NavigationEntry* current_entry,
710 const NavigationEntryImpl* new_entry) const {
711 NavigationControllerImpl& controller =
712 delegate_->GetControllerForRenderManager();
713 return current_entry && web_ui_.get() &&
714 (WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
715 controller.GetBrowserContext(), current_entry->GetURL()) ==
716 WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
717 controller.GetBrowserContext(), new_entry->GetURL()));
720 SiteInstance* RenderFrameHostManager::GetSiteInstanceForURL(
721 const GURL& dest_url,
722 SiteInstance* dest_instance,
723 PageTransition dest_transition,
724 bool dest_is_restore,
725 bool dest_is_view_source_mode,
726 SiteInstance* current_instance,
727 bool force_browsing_instance_swap) {
728 NavigationControllerImpl& controller =
729 delegate_->GetControllerForRenderManager();
730 BrowserContext* browser_context = controller.GetBrowserContext();
732 // If the entry has an instance already we should use it.
734 // If we are forcing a swap, this should be in a different BrowsingInstance.
735 if (force_browsing_instance_swap) {
736 CHECK(!dest_instance->IsRelatedSiteInstance(
737 render_frame_host_->GetSiteInstance()));
739 return dest_instance;
742 // If a swap is required, we need to force the SiteInstance AND
743 // BrowsingInstance to be different ones, using CreateForURL.
744 if (force_browsing_instance_swap)
745 return SiteInstance::CreateForURL(browser_context, dest_url);
747 // (UGLY) HEURISTIC, process-per-site only:
749 // If this navigation is generated, then it probably corresponds to a search
750 // query. Given that search results typically lead to users navigating to
751 // other sites, we don't really want to use the search engine hostname to
752 // determine the site instance for this navigation.
754 // NOTE: This can be removed once we have a way to transition between
755 // RenderViews in response to a link click.
757 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessPerSite) &&
758 PageTransitionCoreTypeIs(dest_transition, PAGE_TRANSITION_GENERATED)) {
759 return current_instance;
762 SiteInstanceImpl* current_site_instance =
763 static_cast<SiteInstanceImpl*>(current_instance);
765 // If we haven't used our SiteInstance (and thus RVH) yet, then we can use it
766 // for this entry. We won't commit the SiteInstance to this site until the
767 // navigation commits (in DidNavigate), unless the navigation entry was
768 // restored or it's a Web UI as described below.
769 if (!current_site_instance->HasSite()) {
770 // If we've already created a SiteInstance for our destination, we don't
771 // want to use this unused SiteInstance; use the existing one. (We don't
772 // do this check if the current_instance has a site, because for now, we
773 // want to compare against the current URL and not the SiteInstance's site.
774 // In this case, there is no current URL, so comparing against the site is
775 // ok. See additional comments below.)
777 // Also, if the URL should use process-per-site mode and there is an
778 // existing process for the site, we should use it. We can call
779 // GetRelatedSiteInstance() for this, which will eagerly set the site and
780 // thus use the correct process.
781 bool use_process_per_site =
782 RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) &&
783 RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url);
784 if (current_site_instance->HasRelatedSiteInstance(dest_url) ||
785 use_process_per_site) {
786 return current_site_instance->GetRelatedSiteInstance(dest_url);
789 // For extensions, Web UI URLs (such as the new tab page), and apps we do
790 // not want to use the current_instance if it has no site, since it will
791 // have a RenderProcessHost of PRIV_NORMAL. Create a new SiteInstance for
792 // this URL instead (with the correct process type).
793 if (current_site_instance->HasWrongProcessForURL(dest_url))
794 return current_site_instance->GetRelatedSiteInstance(dest_url);
796 // View-source URLs must use a new SiteInstance and BrowsingInstance.
797 // TODO(nasko): This is the same condition as later in the function. This
798 // should be taken into account when refactoring this method as part of
799 // http://crbug.com/123007.
800 if (dest_is_view_source_mode)
801 return SiteInstance::CreateForURL(browser_context, dest_url);
803 // If we are navigating from a blank SiteInstance to a WebUI, make sure we
804 // create a new SiteInstance.
805 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
806 browser_context, dest_url)) {
807 return SiteInstance::CreateForURL(browser_context, dest_url);
810 // Normally the "site" on the SiteInstance is set lazily when the load
811 // actually commits. This is to support better process sharing in case
812 // the site redirects to some other site: we want to use the destination
813 // site in the site instance.
815 // In the case of session restore, as it loads all the pages immediately
816 // we need to set the site first, otherwise after a restore none of the
817 // pages would share renderers in process-per-site.
819 // The embedder can request some urls never to be assigned to SiteInstance
820 // through the ShouldAssignSiteForURL() content client method, so that
821 // renderers created for particular chrome urls (e.g. the chrome-native://
822 // scheme) can be reused for subsequent navigations in the same WebContents.
823 // See http://crbug.com/386542.
824 if (dest_is_restore &&
825 GetContentClient()->browser()->ShouldAssignSiteForURL(dest_url)) {
826 current_site_instance->SetSite(dest_url);
829 return current_site_instance;
832 // Otherwise, only create a new SiteInstance for a cross-site navigation.
834 // TODO(creis): Once we intercept links and script-based navigations, we
835 // will be able to enforce that all entries in a SiteInstance actually have
836 // the same site, and it will be safe to compare the URL against the
837 // SiteInstance's site, as follows:
838 // const GURL& current_url = current_instance->site();
839 // For now, though, we're in a hybrid model where you only switch
840 // SiteInstances if you type in a cross-site URL. This means we have to
841 // compare the entry's URL to the last committed entry's URL.
842 NavigationEntry* current_entry = controller.GetLastCommittedEntry();
843 if (interstitial_page_) {
844 // The interstitial is currently the last committed entry, but we want to
845 // compare against the last non-interstitial entry.
846 current_entry = controller.GetEntryAtOffset(-1);
848 // If there is no last non-interstitial entry (and current_instance already
849 // has a site), then we must have been opened from another tab. We want
850 // to compare against the URL of the page that opened us, but we can't
851 // get to it directly. The best we can do is check against the site of
852 // the SiteInstance. This will be correct when we intercept links and
853 // script-based navigations, but for now, it could place some pages in a
854 // new process unnecessarily. We should only hit this case if a page tries
855 // to open a new tab to an interstitial-inducing URL, and then navigates
856 // the page to a different same-site URL. (This seems very unlikely in
858 const GURL& current_url = (current_entry) ? current_entry->GetURL() :
859 current_instance->GetSiteURL();
861 // View-source URLs must use a new SiteInstance and BrowsingInstance.
862 // We don't need a swap when going from view-source to a debug URL like
863 // chrome://crash, however.
864 // TODO(creis): Refactor this method so this duplicated code isn't needed.
865 // See http://crbug.com/123007.
867 current_entry->IsViewSourceMode() != dest_is_view_source_mode &&
868 !IsRendererDebugURL(dest_url)) {
869 return SiteInstance::CreateForURL(browser_context, dest_url);
872 // Use the current SiteInstance for same site navigations, as long as the
873 // process type is correct. (The URL may have been installed as an app since
874 // the last time we visited it.)
875 if (SiteInstance::IsSameWebSite(browser_context, current_url, dest_url) &&
876 !current_site_instance->HasWrongProcessForURL(dest_url)) {
877 return current_instance;
880 // Start the new renderer in a new SiteInstance, but in the current
881 // BrowsingInstance. It is important to immediately give this new
882 // SiteInstance to a RenderViewHost (if it is different than our current
883 // SiteInstance), so that it is ref counted. This will happen in
885 return current_instance->GetRelatedSiteInstance(dest_url);
888 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::CreateRenderFrameHost(
889 SiteInstance* site_instance,
891 int frame_routing_id,
894 if (frame_routing_id == MSG_ROUTING_NONE)
895 frame_routing_id = site_instance->GetProcess()->GetNextRoutingID();
897 // Create a RVH for main frames, or find the existing one for subframes.
898 FrameTree* frame_tree = frame_tree_node_->frame_tree();
899 RenderViewHostImpl* render_view_host = NULL;
900 if (frame_tree_node_->IsMainFrame()) {
901 render_view_host = frame_tree->CreateRenderViewHost(
902 site_instance, view_routing_id, frame_routing_id, swapped_out, hidden);
904 render_view_host = frame_tree->GetRenderViewHost(site_instance);
906 CHECK(render_view_host);
909 // TODO(creis): Pass hidden to RFH.
910 scoped_ptr<RenderFrameHostImpl> render_frame_host =
911 make_scoped_ptr(RenderFrameHostFactory::Create(render_view_host,
912 render_frame_delegate_,
916 swapped_out).release());
917 return render_frame_host.Pass();
920 int RenderFrameHostManager::CreateRenderFrame(SiteInstance* instance,
923 bool for_main_frame_navigation,
926 DCHECK(!swapped_out || hidden); // Swapped out views should always be hidden.
928 // TODO(nasko): Remove the following CHECK once cross-site navigation no
929 // longer relies on swapped out RFH for the top-level frame.
930 if (!frame_tree_node_->IsMainFrame()) {
934 scoped_ptr<RenderFrameHostImpl> new_render_frame_host;
935 RenderFrameHostImpl* frame_to_announce = NULL;
936 int routing_id = MSG_ROUTING_NONE;
938 // We are creating a pending or swapped out RFH here. We should never create
939 // it in the same SiteInstance as our current RFH.
940 CHECK_NE(render_frame_host_->GetSiteInstance(), instance);
942 // Check if we've already created an RFH for this SiteInstance. If so, try
943 // to re-use the existing one, which has already been initialized. We'll
944 // remove it from the list of swapped out hosts if it commits.
945 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
948 routing_id = proxy->GetRenderViewHost()->GetRoutingID();
949 // Delete the existing RenderFrameProxyHost, but reuse the RenderFrameHost.
950 // Prevent the process from exiting while we're trying to use it.
952 new_render_frame_host = proxy->PassFrameHostOwnership();
953 new_render_frame_host->GetProcess()->AddPendingView();
955 proxy_hosts_.erase(instance->GetId());
958 // When a new render view is created by the renderer, the new WebContents
959 // gets a RenderViewHost in the SiteInstance of its opener WebContents.
960 // If not used in the first navigation, this RVH is swapped out and is not
961 // granted bindings, so we may need to grant them when swapping it in.
962 if (pending_web_ui() &&
963 !new_render_frame_host->GetProcess()->IsIsolatedGuest()) {
964 int required_bindings = pending_web_ui()->GetBindings();
965 RenderViewHost* rvh = new_render_frame_host->render_view_host();
966 if ((rvh->GetEnabledBindings() & required_bindings) !=
968 rvh->AllowBindings(required_bindings);
973 // Create a new RenderFrameHost if we don't find an existing one.
974 new_render_frame_host = CreateRenderFrameHost(
975 instance, MSG_ROUTING_NONE, MSG_ROUTING_NONE, swapped_out, hidden);
976 RenderViewHostImpl* render_view_host =
977 new_render_frame_host->render_view_host();
978 int proxy_routing_id = MSG_ROUTING_NONE;
980 // Prevent the process from exiting while we're trying to navigate in it.
981 // Otherwise, if the new RFH is swapped out already, store it.
983 new_render_frame_host->GetProcess()->AddPendingView();
985 proxy = new RenderFrameProxyHost(
986 new_render_frame_host->GetSiteInstance(), frame_tree_node_);
987 proxy_hosts_[instance->GetId()] = proxy;
988 proxy->TakeFrameHostOwnership(new_render_frame_host.Pass());
989 proxy_routing_id = proxy->GetRoutingID();
992 bool success = InitRenderView(render_view_host,
995 for_main_frame_navigation);
997 if (frame_tree_node_->IsMainFrame()) {
998 // Don't show the main frame's view until we get a DidNavigate from it.
999 render_view_host->GetView()->Hide();
1000 } else if (!swapped_out) {
1001 // Init the RFH, so a RenderFrame is created in the renderer.
1002 DCHECK(new_render_frame_host.get());
1003 success = InitRenderFrame(new_render_frame_host.get());
1006 proxy_hosts_[instance->GetId()]->InitRenderFrameProxy();
1008 } else if (!swapped_out && pending_render_frame_host_) {
1011 routing_id = render_view_host->GetRoutingID();
1012 frame_to_announce = new_render_frame_host.get();
1015 // Use this as our new pending RFH if it isn't swapped out.
1017 pending_render_frame_host_ = new_render_frame_host.Pass();
1019 // If a brand new RFH was created, announce it to observers.
1020 if (frame_to_announce)
1021 render_frame_delegate_->RenderFrameCreated(frame_to_announce);
1026 int RenderFrameHostManager::CreateRenderFrameProxy(SiteInstance* instance) {
1027 // A RenderFrameProxyHost should never be created in the same SiteInstance as
1030 CHECK_NE(instance, render_frame_host_->GetSiteInstance());
1032 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1034 return proxy->GetRoutingID();
1036 proxy = new RenderFrameProxyHost(instance, frame_tree_node_);
1037 proxy_hosts_[instance->GetId()] = proxy;
1038 proxy->InitRenderFrameProxy();
1039 return proxy->GetRoutingID();
1042 bool RenderFrameHostManager::InitRenderView(RenderViewHost* render_view_host,
1043 int opener_route_id,
1044 int proxy_routing_id,
1045 bool for_main_frame_navigation) {
1046 // We may have initialized this RenderViewHost for another RenderFrameHost.
1047 if (render_view_host->IsRenderViewLive())
1050 // If the pending navigation is to a WebUI and the RenderView is not in a
1051 // guest process, tell the RenderViewHost about any bindings it will need
1053 if (pending_web_ui() && !render_view_host->GetProcess()->IsIsolatedGuest()) {
1054 render_view_host->AllowBindings(pending_web_ui()->GetBindings());
1056 // Ensure that we don't create an unprivileged RenderView in a WebUI-enabled
1057 // process unless it's swapped out.
1058 RenderViewHostImpl* rvh_impl =
1059 static_cast<RenderViewHostImpl*>(render_view_host);
1060 if (!rvh_impl->IsSwappedOut()) {
1061 CHECK(!ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1062 render_view_host->GetProcess()->GetID()));
1066 return delegate_->CreateRenderViewForRenderManager(
1070 for_main_frame_navigation);
1073 bool RenderFrameHostManager::InitRenderFrame(
1074 RenderFrameHost* render_frame_host) {
1075 RenderFrameHostImpl* rfh =
1076 static_cast<RenderFrameHostImpl*>(render_frame_host);
1077 if (rfh->IsRenderFrameLive())
1080 int parent_routing_id = MSG_ROUTING_NONE;
1081 if (frame_tree_node_->parent()) {
1082 parent_routing_id = frame_tree_node_->parent()->render_manager()->
1083 GetRoutingIdForSiteInstance(render_frame_host->GetSiteInstance());
1084 CHECK_NE(parent_routing_id, MSG_ROUTING_NONE);
1086 return delegate_->CreateRenderFrameForRenderManager(render_frame_host,
1090 int RenderFrameHostManager::GetRoutingIdForSiteInstance(
1091 SiteInstance* site_instance) {
1092 if (render_frame_host_->GetSiteInstance() == site_instance)
1093 return render_frame_host_->GetRoutingID();
1095 RenderFrameProxyHostMap::iterator iter =
1096 proxy_hosts_.find(site_instance->GetId());
1097 if (iter != proxy_hosts_.end())
1098 return iter->second->GetRoutingID();
1100 return MSG_ROUTING_NONE;
1103 void RenderFrameHostManager::CommitPending() {
1104 // First check whether we're going to want to focus the location bar after
1105 // this commit. We do this now because the navigation hasn't formally
1106 // committed yet, so if we've already cleared |pending_web_ui_| the call chain
1107 // this triggers won't be able to figure out what's going on.
1108 bool will_focus_location_bar = delegate_->FocusLocationBarByDefault();
1110 // We expect SwapOutOldPage to have canceled any modal dialogs and told the
1111 // renderer to suppress any further dialogs until it is swapped out. However,
1112 // crash reports indicate that it's still possible for modal dialogs to exist
1113 // at this point, which poses a risk if we delete their RenderViewHost below.
1114 // Cancel them again to be safe. http://crbug.com/324320.
1115 delegate_->CancelModalDialogsForRenderManager();
1117 // Next commit the Web UI, if any. Either replace |web_ui_| with
1118 // |pending_web_ui_|, or clear |web_ui_| if there is no pending WebUI, or
1119 // leave |web_ui_| as is if reusing it.
1120 DCHECK(!(pending_web_ui_.get() && pending_and_current_web_ui_.get()));
1121 if (pending_web_ui_) {
1122 web_ui_.reset(pending_web_ui_.release());
1123 } else if (!pending_and_current_web_ui_.get()) {
1126 DCHECK_EQ(pending_and_current_web_ui_.get(), web_ui_.get());
1127 pending_and_current_web_ui_.reset();
1130 // It's possible for the pending_render_frame_host_ to be NULL when we aren't
1131 // crossing process boundaries. If so, we just needed to handle the Web UI
1132 // committing above and we're done.
1133 if (!pending_render_frame_host_) {
1134 if (will_focus_location_bar)
1135 delegate_->SetFocusToLocationBar(false);
1139 // Remember if the page was focused so we can focus the new renderer in
1141 bool focus_render_view = !will_focus_location_bar &&
1142 render_frame_host_->render_view_host()->GetView() &&
1143 render_frame_host_->render_view_host()->GetView()->HasFocus();
1145 // TODO(creis): As long as show/hide are on RVH, we don't want to do them for
1146 // subframe navigations or they'll interfere with the top-level page.
1147 bool is_main_frame = frame_tree_node_->IsMainFrame();
1149 // Swap in the pending frame and make it active. Also ensure the FrameTree
1151 scoped_ptr<RenderFrameHostImpl> old_render_frame_host =
1152 SetRenderFrameHost(pending_render_frame_host_.Pass());
1154 render_frame_host_->render_view_host()->AttachToFrameTree();
1156 // The process will no longer try to exit, so we can decrement the count.
1157 render_frame_host_->GetProcess()->RemovePendingView();
1159 // If the view is gone, then this RenderViewHost died while it was hidden.
1160 // We ignored the RenderProcessGone call at the time, so we should send it now
1161 // to make sure the sad tab shows up, etc.
1162 if (!render_frame_host_->render_view_host()->GetView()) {
1163 delegate_->RenderProcessGoneFromRenderManager(
1164 render_frame_host_->render_view_host());
1165 } else if (!delegate_->IsHidden()) {
1166 render_frame_host_->render_view_host()->GetView()->Show();
1169 // If the old view is live and top-level, hide it now that the new one is
1171 int32 old_site_instance_id =
1172 old_render_frame_host->GetSiteInstance()->GetId();
1173 if (old_render_frame_host->render_view_host()->GetView()) {
1174 if (is_main_frame) {
1175 old_render_frame_host->render_view_host()->GetView()->Hide();
1176 old_render_frame_host->render_view_host()->WasSwappedOut(base::Bind(
1177 &RenderFrameHostManager::ClearPendingShutdownRFHForSiteInstance,
1178 weak_factory_.GetWeakPtr(),
1179 old_site_instance_id,
1180 old_render_frame_host.get()));
1182 // TODO(creis): We'll need to set this back to false if we navigate back.
1183 old_render_frame_host->set_swapped_out(true);
1187 // Make sure the size is up to date. (Fix for bug 1079768.)
1188 delegate_->UpdateRenderViewSizeForRenderManager();
1190 if (will_focus_location_bar) {
1191 delegate_->SetFocusToLocationBar(false);
1192 } else if (focus_render_view &&
1193 render_frame_host_->render_view_host()->GetView()) {
1194 render_frame_host_->render_view_host()->GetView()->Focus();
1197 // Notify that we've swapped RenderFrameHosts. We do this before shutting down
1198 // the RFH so that we can clean up RendererResources related to the RFH first.
1199 delegate_->NotifySwappedFromRenderManager(
1200 old_render_frame_host.get(), render_frame_host_.get(), is_main_frame);
1202 // If the old RFH is not live, just return as there is no work to do.
1203 if (!old_render_frame_host->render_view_host()->IsRenderViewLive()) {
1207 // If the old RFH is live, we are swapping it out and should keep track of
1208 // it in case we navigate back to it, or it is waiting for the unload event
1209 // to execute in the background.
1210 // TODO(creis): Swap out the subframe in --site-per-process.
1211 if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess))
1212 DCHECK(old_render_frame_host->is_swapped_out() ||
1213 !RenderViewHostImpl::IsRVHStateActive(
1214 old_render_frame_host->render_view_host()->rvh_state()));
1216 // If the RenderViewHost backing the RenderFrameHost is pending shutdown,
1217 // the RenderFrameHost should be put in the map of RenderFrameHosts pending
1218 // shutdown. Otherwise, it is stored in the map of proxy hosts.
1219 if (old_render_frame_host->render_view_host()->rvh_state() ==
1220 RenderViewHostImpl::STATE_PENDING_SHUTDOWN) {
1221 // The proxy for this RenderFrameHost is created when sending the
1222 // SwapOut message, so check if it already exists and delete it.
1223 RenderFrameProxyHostMap::iterator iter =
1224 proxy_hosts_.find(old_site_instance_id);
1225 if (iter != proxy_hosts_.end()) {
1226 delete iter->second;
1227 proxy_hosts_.erase(iter);
1229 RFHPendingDeleteMap::iterator pending_delete_iter =
1230 pending_delete_hosts_.find(old_site_instance_id);
1231 if (pending_delete_iter == pending_delete_hosts_.end() ||
1232 pending_delete_iter->second.get() != old_render_frame_host) {
1233 pending_delete_hosts_[old_site_instance_id] =
1234 linked_ptr<RenderFrameHostImpl>(old_render_frame_host.release());
1237 CHECK(proxy_hosts_.find(render_frame_host_->GetSiteInstance()->GetId()) ==
1238 proxy_hosts_.end());
1240 // Capture the active view count on the old RFH SiteInstance, since the
1241 // ownership might be passed into the proxy and the pointer will be
1243 int active_view_count =
1244 static_cast<SiteInstanceImpl*>(old_render_frame_host->GetSiteInstance())
1245 ->active_view_count();
1247 if (is_main_frame) {
1248 RenderFrameProxyHostMap::iterator iter =
1249 proxy_hosts_.find(old_site_instance_id);
1250 CHECK(iter != proxy_hosts_.end());
1251 iter->second->TakeFrameHostOwnership(old_render_frame_host.Pass());
1254 // If there are no active views in this SiteInstance, it means that
1255 // this RFH was the last active one in the SiteInstance. Now that we
1256 // know that all RFHs are swapped out, we can delete all the RFPHs and
1257 // RVHs in this SiteInstance.
1258 if (!active_view_count) {
1259 ShutdownRenderFrameProxyHostsInSiteInstance(old_site_instance_id);
1261 // If this is a subframe, it should have a CrossProcessFrameConnector
1262 // created already and we just need to link it to the proper view in the
1264 if (!is_main_frame) {
1265 RenderFrameProxyHost* proxy = GetProxyToParent();
1267 proxy->SetChildRWHView(
1268 render_frame_host_->render_view_host()->GetView());
1275 void RenderFrameHostManager::ShutdownRenderFrameProxyHostsInSiteInstance(
1276 int32 site_instance_id) {
1277 // First remove any swapped out RFH for this SiteInstance from our own list.
1278 ClearProxiesInSiteInstance(site_instance_id, frame_tree_node_);
1280 // Use the safe RenderWidgetHost iterator for now to find all RenderViewHosts
1281 // in the SiteInstance, then tell their respective FrameTrees to remove all
1282 // RenderFrameProxyHosts corresponding to them.
1283 // TODO(creis): Replace this with a RenderFrameHostIterator that protects
1284 // against use-after-frees if a later element is deleted before getting to it.
1285 scoped_ptr<RenderWidgetHostIterator> widgets(
1286 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
1287 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
1288 if (!widget->IsRenderView())
1290 RenderViewHostImpl* rvh =
1291 static_cast<RenderViewHostImpl*>(RenderViewHost::From(widget));
1292 if (site_instance_id == rvh->GetSiteInstance()->GetId()) {
1293 // This deletes all RenderFrameHosts using the |rvh|, which then causes
1294 // |rvh| to Shutdown.
1295 FrameTree* tree = rvh->GetDelegate()->GetFrameTree();
1296 tree->ForEach(base::Bind(
1297 &RenderFrameHostManager::ClearProxiesInSiteInstance,
1303 RenderFrameHostImpl* RenderFrameHostManager::UpdateStateForNavigate(
1304 const NavigationEntryImpl& entry) {
1305 // If we are currently navigating cross-process, we want to get back to normal
1306 // and then navigate as usual.
1307 if (cross_navigation_pending_) {
1308 if (pending_render_frame_host_)
1310 cross_navigation_pending_ = false;
1313 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1314 scoped_refptr<SiteInstance> new_instance = current_instance;
1316 // We do not currently swap processes for navigations in webview tag guests.
1317 bool is_guest_scheme = current_instance->GetSiteURL().SchemeIs(kGuestScheme);
1319 // Determine if we need a new BrowsingInstance for this entry. If true, this
1320 // implies that it will get a new SiteInstance (and likely process), and that
1321 // other tabs in the current BrowsingInstance will be unable to script it.
1322 // This is used for cases that require a process swap even in the
1323 // process-per-tab model, such as WebUI pages.
1324 const NavigationEntry* current_entry =
1325 delegate_->GetLastCommittedNavigationEntryForRenderManager();
1326 BrowserContext* browser_context =
1327 delegate_->GetControllerForRenderManager().GetBrowserContext();
1328 const GURL& current_effective_url = current_entry ?
1329 SiteInstanceImpl::GetEffectiveURL(browser_context,
1330 current_entry->GetURL()) :
1331 render_frame_host_->GetSiteInstance()->GetSiteURL();
1332 bool current_is_view_source_mode = current_entry ?
1333 current_entry->IsViewSourceMode() : entry.IsViewSourceMode();
1334 bool force_swap = !is_guest_scheme &&
1335 ShouldSwapBrowsingInstancesForNavigation(
1336 current_effective_url,
1337 current_is_view_source_mode,
1338 entry.site_instance(),
1339 SiteInstanceImpl::GetEffectiveURL(browser_context, entry.GetURL()),
1340 entry.IsViewSourceMode());
1341 if (!is_guest_scheme && (ShouldTransitionCrossSite() || force_swap)) {
1342 new_instance = GetSiteInstanceForURL(
1344 entry.site_instance(),
1345 entry.GetTransitionType(),
1346 entry.restore_type() != NavigationEntryImpl::RESTORE_NONE,
1347 entry.IsViewSourceMode(),
1352 // If force_swap is true, we must use a different SiteInstance. If we didn't,
1353 // we would have two RenderFrameHosts in the same SiteInstance and the same
1354 // frame, resulting in page_id conflicts for their NavigationEntries.
1356 CHECK_NE(new_instance, current_instance);
1358 if (new_instance != current_instance) {
1359 // New SiteInstance: create a pending RFH to navigate.
1360 DCHECK(!cross_navigation_pending_);
1362 // This will possibly create (set to NULL) a Web UI object for the pending
1363 // page. We'll use this later to give the page special access. This must
1364 // happen before the new renderer is created below so it will get bindings.
1365 // It must also happen after the above conditional call to CancelPending(),
1366 // otherwise CancelPending may clear the pending_web_ui_ and the page will
1367 // not have its bindings set appropriately.
1368 SetPendingWebUI(entry);
1370 // Ensure that we have created RFHs for the new RFH's opener chain if
1371 // we are staying in the same BrowsingInstance. This allows the pending RFH
1372 // to send cross-process script calls to its opener(s).
1373 int opener_route_id = MSG_ROUTING_NONE;
1374 if (new_instance->IsRelatedSiteInstance(current_instance)) {
1376 delegate_->CreateOpenerRenderViewsForRenderManager(new_instance);
1378 if (CommandLine::ForCurrentProcess()->HasSwitch(
1379 switches::kSitePerProcess)) {
1380 // Ensure that the frame tree has RenderFrameProxyHosts for the new
1381 // SiteInstance in all nodes except the current one.
1382 frame_tree_node_->frame_tree()->CreateProxiesForSiteInstance(
1383 frame_tree_node_, new_instance);
1387 // Create a non-swapped-out pending RFH with the given opener and navigate
1389 int route_id = CreateRenderFrame(new_instance,
1392 frame_tree_node_->IsMainFrame(),
1393 delegate_->IsHidden());
1394 if (route_id == MSG_ROUTING_NONE)
1397 // Check if our current RFH is live before we set up a transition.
1398 if (!render_frame_host_->render_view_host()->IsRenderViewLive()) {
1399 if (!cross_navigation_pending_) {
1400 // The current RFH is not live. There's no reason to sit around with a
1401 // sad tab or a newly created RFH while we wait for the pending RFH to
1402 // navigate. Just switch to the pending RFH now and go back to non
1403 // cross-navigating (Note that we don't care about on{before}unload
1404 // handlers if the current RFH isn't live.)
1406 return render_frame_host_.get();
1409 return render_frame_host_.get();
1412 // Otherwise, it's safe to treat this as a pending cross-site transition.
1414 // We need to wait until the beforeunload handler has run, unless we are
1415 // transferring an existing request (in which case it has already run).
1416 // Suspend the new render view (i.e., don't let it send the cross-site
1417 // Navigate message) until we hear back from the old renderer's
1418 // beforeunload handler. If the handler returns false, we'll have to
1419 // cancel the request.
1420 DCHECK(!pending_render_frame_host_->are_navigations_suspended());
1422 entry.transferred_global_request_id() != GlobalRequestID();
1424 // We don't need to stop the old renderer or run beforeunload/unload
1425 // handlers, because those have already been done.
1426 DCHECK(pending_nav_params_->global_request_id ==
1427 entry.transferred_global_request_id());
1429 // Also make sure the old render view stops, in case a load is in
1430 // progress. (We don't want to do this for transfers, since it will
1431 // interrupt the transfer with an unexpected DidStopLoading.)
1432 render_frame_host_->render_view_host()->Send(new ViewMsg_Stop(
1433 render_frame_host_->render_view_host()->GetRoutingID()));
1435 pending_render_frame_host_->SetNavigationsSuspended(true,
1438 // Tell the CrossSiteRequestManager that this RFH has a pending cross-site
1439 // request, so that ResourceDispatcherHost will know to tell us to run the
1440 // old page's unload handler before it sends the response.
1441 pending_render_frame_host_->SetHasPendingCrossSiteRequest(true);
1444 // We now have a pending RFH.
1445 DCHECK(!cross_navigation_pending_);
1446 cross_navigation_pending_ = true;
1448 // Unless we are transferring an existing request, we should now
1449 // tell the old render view to run its beforeunload handler, since it
1450 // doesn't otherwise know that the cross-site request is happening. This
1451 // will trigger a call to OnBeforeUnloadACK with the reply.
1453 render_frame_host_->DispatchBeforeUnload(true);
1455 return pending_render_frame_host_.get();
1458 // Otherwise the same SiteInstance can be used. Navigate render_frame_host_.
1459 DCHECK(!cross_navigation_pending_);
1461 // It's possible to swap out the current RFH and then decide to navigate in it
1462 // anyway (e.g., a cross-process navigation that redirects back to the
1463 // original site). In that case, we have a proxy for the current RFH but
1464 // haven't deleted it yet. The new navigation will swap it back in, so we can
1465 // delete the proxy.
1466 DeleteRenderFrameProxyHost(new_instance);
1468 if (ShouldReuseWebUI(current_entry, &entry)) {
1469 pending_web_ui_.reset();
1470 pending_and_current_web_ui_ = web_ui_->AsWeakPtr();
1472 SetPendingWebUI(entry);
1474 // Make sure the new RenderViewHost has the right bindings.
1475 if (pending_web_ui() &&
1476 !render_frame_host_->GetProcess()->IsIsolatedGuest()) {
1477 render_frame_host_->render_view_host()->AllowBindings(
1478 pending_web_ui()->GetBindings());
1482 if (pending_web_ui() &&
1483 render_frame_host_->render_view_host()->IsRenderViewLive()) {
1484 pending_web_ui()->GetController()->RenderViewReused(
1485 render_frame_host_->render_view_host());
1488 // The renderer can exit view source mode when any error or cancellation
1489 // happen. We must overwrite to recover the mode.
1490 if (entry.IsViewSourceMode()) {
1491 render_frame_host_->render_view_host()->Send(
1492 new ViewMsg_EnableViewSourceMode(
1493 render_frame_host_->render_view_host()->GetRoutingID()));
1496 return render_frame_host_.get();
1499 void RenderFrameHostManager::CancelPending() {
1500 scoped_ptr<RenderFrameHostImpl> pending_render_frame_host =
1501 pending_render_frame_host_.Pass();
1503 RenderViewDevToolsAgentHost::OnCancelPendingNavigation(
1504 pending_render_frame_host->render_view_host(),
1505 render_frame_host_->render_view_host());
1507 // We no longer need to prevent the process from exiting.
1508 pending_render_frame_host->GetProcess()->RemovePendingView();
1510 // If the SiteInstance for the pending RFH is being used by others, don't
1511 // delete the RFH, just swap it out and it can be reused at a later point.
1512 SiteInstanceImpl* site_instance = static_cast<SiteInstanceImpl*>(
1513 pending_render_frame_host->GetSiteInstance());
1514 if (site_instance->active_view_count() > 1) {
1515 // Any currently suspended navigations are no longer needed.
1516 pending_render_frame_host->CancelSuspendedNavigations();
1518 RenderFrameProxyHost* proxy =
1519 new RenderFrameProxyHost(site_instance, frame_tree_node_);
1520 proxy_hosts_[site_instance->GetId()] = proxy;
1521 pending_render_frame_host->SwapOut(proxy);
1522 if (frame_tree_node_->IsMainFrame())
1523 proxy->TakeFrameHostOwnership(pending_render_frame_host.Pass());
1525 // We won't be coming back, so delete this one.
1526 pending_render_frame_host.reset();
1529 pending_web_ui_.reset();
1530 pending_and_current_web_ui_.reset();
1533 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::SetRenderFrameHost(
1534 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
1536 scoped_ptr<RenderFrameHostImpl> old_render_frame_host =
1537 render_frame_host_.Pass();
1538 render_frame_host_ = render_frame_host.Pass();
1540 if (frame_tree_node_->IsMainFrame()) {
1541 // Update the count of top-level frames using this SiteInstance. All
1542 // subframes are in the same BrowsingInstance as the main frame, so we only
1543 // count top-level ones. This makes the value easier for consumers to
1545 if (render_frame_host_) {
1546 static_cast<SiteInstanceImpl*>(render_frame_host_->GetSiteInstance())->
1547 IncrementRelatedActiveContentsCount();
1549 if (old_render_frame_host) {
1550 static_cast<SiteInstanceImpl*>(old_render_frame_host->GetSiteInstance())->
1551 DecrementRelatedActiveContentsCount();
1555 return old_render_frame_host.Pass();
1558 bool RenderFrameHostManager::IsRVHOnSwappedOutList(
1559 RenderViewHostImpl* rvh) const {
1560 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(
1561 rvh->GetSiteInstance());
1564 // If there is a proxy without RFH, it is for a subframe in the SiteInstance
1565 // of |rvh|. Subframes should be ignored in this case.
1566 if (!proxy->render_frame_host())
1568 return IsOnSwappedOutList(proxy->render_frame_host());
1571 bool RenderFrameHostManager::IsOnSwappedOutList(
1572 RenderFrameHostImpl* rfh) const {
1573 if (!rfh->GetSiteInstance())
1576 RenderFrameProxyHostMap::const_iterator iter = proxy_hosts_.find(
1577 rfh->GetSiteInstance()->GetId());
1578 if (iter == proxy_hosts_.end())
1581 return iter->second->render_frame_host() == rfh;
1584 RenderViewHostImpl* RenderFrameHostManager::GetSwappedOutRenderViewHost(
1585 SiteInstance* instance) const {
1586 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1588 return proxy->GetRenderViewHost();
1592 RenderFrameProxyHost* RenderFrameHostManager::GetRenderFrameProxyHost(
1593 SiteInstance* instance) const {
1594 RenderFrameProxyHostMap::const_iterator iter =
1595 proxy_hosts_.find(instance->GetId());
1596 if (iter != proxy_hosts_.end())
1597 return iter->second;
1602 void RenderFrameHostManager::DeleteRenderFrameProxyHost(
1603 SiteInstance* instance) {
1604 RenderFrameProxyHostMap::iterator iter = proxy_hosts_.find(instance->GetId());
1605 if (iter != proxy_hosts_.end()) {
1606 delete iter->second;
1607 proxy_hosts_.erase(iter);
1611 } // namespace content