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