Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_manager.cc
blob5e1e3afc2defdc7053748e49a07b2cacb0b70555
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/frame_host/render_frame_host_manager.h"
7 #include <utility>
9 #include "base/command_line.h"
10 #include "base/debug/trace_event.h"
11 #include "base/logging.h"
12 #include "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_before_commit_info.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/navigation_request.h"
22 #include "content/browser/frame_host/navigation_request_info.h"
23 #include "content/browser/frame_host/navigator.h"
24 #include "content/browser/frame_host/render_frame_host_factory.h"
25 #include "content/browser/frame_host/render_frame_host_impl.h"
26 #include "content/browser/frame_host/render_frame_proxy_host.h"
27 #include "content/browser/renderer_host/render_process_host_impl.h"
28 #include "content/browser/renderer_host/render_view_host_factory.h"
29 #include "content/browser/renderer_host/render_view_host_impl.h"
30 #include "content/browser/site_instance_impl.h"
31 #include "content/browser/webui/web_ui_controller_factory_registry.h"
32 #include "content/browser/webui/web_ui_impl.h"
33 #include "content/common/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/referrer.h"
43 #include "content/public/common/url_constants.h"
44 #include "net/base/load_flags.h"
46 namespace content {
48 namespace {
50 // PlzNavigate
51 // Simulates a renderer response to a navigation request when there is no live
52 // renderer.
53 FrameHostMsg_BeginNavigation_Params BeginNavigationFromNavigate(
54 const FrameMsg_Navigate_Params& navigate_params) {
55 FrameHostMsg_BeginNavigation_Params begin_navigation_params;
56 begin_navigation_params.method = navigate_params.is_post ? "POST" : "GET";
57 begin_navigation_params.url = navigate_params.url;
58 begin_navigation_params.referrer =
59 Referrer(navigate_params.referrer.url, navigate_params.referrer.policy);
61 // TODO(clamy): This should be modified to take into account caching policy
62 // requirements (eg for POST reloads).
63 begin_navigation_params.load_flags = net::LOAD_NORMAL;
65 // TODO(clamy): Post data from the browser should be put in the request body.
67 begin_navigation_params.has_user_gesture = false;
68 begin_navigation_params.transition_type = navigate_params.transition;
69 begin_navigation_params.should_replace_current_entry =
70 navigate_params.should_replace_current_entry;
71 begin_navigation_params.allow_download =
72 navigate_params.allow_download;
73 return begin_navigation_params;
76 } // namespace
78 bool RenderFrameHostManager::ClearRFHsPendingShutdown(FrameTreeNode* node) {
79 node->render_manager()->pending_delete_hosts_.clear();
80 return true;
83 RenderFrameHostManager::RenderFrameHostManager(
84 FrameTreeNode* frame_tree_node,
85 RenderFrameHostDelegate* render_frame_delegate,
86 RenderViewHostDelegate* render_view_delegate,
87 RenderWidgetHostDelegate* render_widget_delegate,
88 Delegate* delegate)
89 : frame_tree_node_(frame_tree_node),
90 delegate_(delegate),
91 cross_navigation_pending_(false),
92 render_frame_delegate_(render_frame_delegate),
93 render_view_delegate_(render_view_delegate),
94 render_widget_delegate_(render_widget_delegate),
95 interstitial_page_(NULL),
96 weak_factory_(this) {
97 DCHECK(frame_tree_node_);
100 RenderFrameHostManager::~RenderFrameHostManager() {
101 if (pending_render_frame_host_)
102 CancelPending();
104 // We should always have a current RenderFrameHost except in some tests.
105 SetRenderFrameHost(scoped_ptr<RenderFrameHostImpl>());
107 // Delete any swapped out RenderFrameHosts.
108 STLDeleteValues(&proxy_hosts_);
111 void RenderFrameHostManager::Init(BrowserContext* browser_context,
112 SiteInstance* site_instance,
113 int view_routing_id,
114 int frame_routing_id) {
115 // Create a RenderViewHost and RenderFrameHost, once we have an instance. It
116 // is important to immediately give this SiteInstance to a RenderViewHost so
117 // that the SiteInstance is ref counted.
118 if (!site_instance)
119 site_instance = SiteInstance::Create(browser_context);
121 SetRenderFrameHost(CreateRenderFrameHost(site_instance,
122 view_routing_id,
123 frame_routing_id,
124 false,
125 delegate_->IsHidden()));
127 // Keep track of renderer processes as they start to shut down or are
128 // crashed/killed.
129 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSED,
130 NotificationService::AllSources());
131 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSING,
132 NotificationService::AllSources());
135 RenderViewHostImpl* RenderFrameHostManager::current_host() const {
136 if (!render_frame_host_)
137 return NULL;
138 return render_frame_host_->render_view_host();
141 RenderViewHostImpl* RenderFrameHostManager::pending_render_view_host() const {
142 if (!pending_render_frame_host_)
143 return NULL;
144 return pending_render_frame_host_->render_view_host();
147 RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const {
148 if (interstitial_page_)
149 return interstitial_page_->GetView();
150 if (!render_frame_host_)
151 return NULL;
152 return render_frame_host_->render_view_host()->GetView();
155 RenderFrameProxyHost* RenderFrameHostManager::GetProxyToParent() {
156 if (frame_tree_node_->IsMainFrame())
157 return NULL;
159 RenderFrameProxyHostMap::iterator iter =
160 proxy_hosts_.find(frame_tree_node_->parent()
161 ->render_manager()
162 ->current_frame_host()
163 ->GetSiteInstance()
164 ->GetId());
165 if (iter == proxy_hosts_.end())
166 return NULL;
168 return iter->second;
171 void RenderFrameHostManager::SetPendingWebUI(const NavigationEntryImpl& entry) {
172 pending_web_ui_.reset(
173 delegate_->CreateWebUIForRenderManager(entry.GetURL()));
174 pending_and_current_web_ui_.reset();
176 // If we have assigned (zero or more) bindings to this NavigationEntry in the
177 // past, make sure we're not granting it different bindings than it had
178 // before. If so, note it and don't give it any bindings, to avoid a
179 // potential privilege escalation.
180 if (pending_web_ui_.get() &&
181 entry.bindings() != NavigationEntryImpl::kInvalidBindings &&
182 pending_web_ui_->GetBindings() != entry.bindings()) {
183 RecordAction(
184 base::UserMetricsAction("ProcessSwapBindingsMismatch_RVHM"));
185 pending_web_ui_.reset();
189 RenderFrameHostImpl* RenderFrameHostManager::Navigate(
190 const NavigationEntryImpl& entry) {
191 TRACE_EVENT0("browser", "RenderFrameHostManager:Navigate");
192 // Create a pending RenderFrameHost to use for the navigation.
193 RenderFrameHostImpl* dest_render_frame_host = UpdateStateForNavigate(entry);
194 if (!dest_render_frame_host)
195 return NULL; // We weren't able to create a pending render frame host.
197 // If the current render_frame_host_ isn't live, we should create it so
198 // that we don't show a sad tab while the dest_render_frame_host fetches
199 // its first page. (Bug 1145340)
200 if (dest_render_frame_host != render_frame_host_ &&
201 !render_frame_host_->render_view_host()->IsRenderViewLive()) {
202 // Note: we don't call InitRenderView here because we are navigating away
203 // soon anyway, and we don't have the NavigationEntry for this host.
204 delegate_->CreateRenderViewForRenderManager(
205 render_frame_host_->render_view_host(), MSG_ROUTING_NONE,
206 MSG_ROUTING_NONE, frame_tree_node_->IsMainFrame());
209 // If the renderer crashed, then try to create a new one to satisfy this
210 // navigation request.
211 if (!dest_render_frame_host->render_view_host()->IsRenderViewLive()) {
212 // Recreate the opener chain.
213 int opener_route_id = delegate_->CreateOpenerRenderViewsForRenderManager(
214 dest_render_frame_host->GetSiteInstance());
215 if (!InitRenderView(dest_render_frame_host->render_view_host(),
216 opener_route_id,
217 MSG_ROUTING_NONE,
218 frame_tree_node_->IsMainFrame()))
219 return NULL;
221 // Now that we've created a new renderer, be sure to hide it if it isn't
222 // our primary one. Otherwise, we might crash if we try to call Show()
223 // on it later.
224 if (dest_render_frame_host != render_frame_host_ &&
225 dest_render_frame_host->render_view_host()->GetView()) {
226 dest_render_frame_host->render_view_host()->GetView()->Hide();
227 } else {
228 // Notify here as we won't be calling CommitPending (which does the
229 // notify).
230 delegate_->NotifySwappedFromRenderManager(
231 NULL, render_frame_host_.get(), frame_tree_node_->IsMainFrame());
235 // If entry includes the request ID of a request that is being transferred,
236 // the destination render frame will take ownership, so release ownership of
237 // the request.
238 if (cross_site_transferring_request_.get() &&
239 cross_site_transferring_request_->request_id() ==
240 entry.transferred_global_request_id()) {
241 cross_site_transferring_request_->ReleaseRequest();
244 return dest_render_frame_host;
247 void RenderFrameHostManager::Stop() {
248 render_frame_host_->render_view_host()->Stop();
250 // If we are cross-navigating, we should stop the pending renderers. This
251 // will lead to a DidFailProvisionalLoad, which will properly destroy them.
252 if (cross_navigation_pending_) {
253 pending_render_frame_host_->render_view_host()->Send(new ViewMsg_Stop(
254 pending_render_frame_host_->render_view_host()->GetRoutingID()));
258 void RenderFrameHostManager::SetIsLoading(bool is_loading) {
259 render_frame_host_->render_view_host()->SetIsLoading(is_loading);
260 if (pending_render_frame_host_)
261 pending_render_frame_host_->render_view_host()->SetIsLoading(is_loading);
264 bool RenderFrameHostManager::ShouldCloseTabOnUnresponsiveRenderer() {
265 if (!cross_navigation_pending_)
266 return true;
268 // We should always have a pending RFH when there's a cross-process navigation
269 // in progress. Sanity check this for http://crbug.com/276333.
270 CHECK(pending_render_frame_host_);
272 // If the tab becomes unresponsive during {before}unload while doing a
273 // cross-site navigation, proceed with the navigation. (This assumes that
274 // the pending RenderFrameHost is still responsive.)
275 if (render_frame_host_->render_view_host()->IsWaitingForUnloadACK()) {
276 // The request has been started and paused while we're waiting for the
277 // unload handler to finish. We'll pretend that it did. The pending
278 // renderer will then be swapped in as part of the usual DidNavigate logic.
279 // (If the unload handler later finishes, this call will be ignored because
280 // the pending_nav_params_ state will already be cleaned up.)
281 current_host()->OnSwappedOut(true);
282 } else if (render_frame_host_->render_view_host()->
283 is_waiting_for_beforeunload_ack()) {
284 // Haven't gotten around to starting the request, because we're still
285 // waiting for the beforeunload handler to finish. We'll pretend that it
286 // did finish, to let the navigation proceed. Note that there's a danger
287 // that the beforeunload handler will later finish and possibly return
288 // false (meaning the navigation should not proceed), but we'll ignore it
289 // in this case because it took too long.
290 if (pending_render_frame_host_->are_navigations_suspended()) {
291 pending_render_frame_host_->SetNavigationsSuspended(
292 false, base::TimeTicks::Now());
295 return false;
298 void RenderFrameHostManager::OnBeforeUnloadACK(
299 bool for_cross_site_transition,
300 bool proceed,
301 const base::TimeTicks& proceed_time) {
302 if (for_cross_site_transition) {
303 // Ignore if we're not in a cross-site navigation.
304 if (!cross_navigation_pending_)
305 return;
307 if (proceed) {
308 // Ok to unload the current page, so proceed with the cross-site
309 // navigation. Note that if navigations are not currently suspended, it
310 // might be because the renderer was deemed unresponsive and this call was
311 // already made by ShouldCloseTabOnUnresponsiveRenderer. In that case, it
312 // is ok to do nothing here.
313 if (pending_render_frame_host_ &&
314 pending_render_frame_host_->are_navigations_suspended()) {
315 pending_render_frame_host_->SetNavigationsSuspended(false,
316 proceed_time);
318 } else {
319 // Current page says to cancel.
320 CancelPending();
321 cross_navigation_pending_ = false;
323 } else {
324 // Non-cross site transition means closing the entire tab.
325 bool proceed_to_fire_unload;
326 delegate_->BeforeUnloadFiredFromRenderManager(proceed, proceed_time,
327 &proceed_to_fire_unload);
329 if (proceed_to_fire_unload) {
330 // If we're about to close the tab and there's a pending RFH, cancel it.
331 // Otherwise, if the navigation in the pending RFH completes before the
332 // close in the current RFH, we'll lose the tab close.
333 if (pending_render_frame_host_) {
334 CancelPending();
335 cross_navigation_pending_ = false;
338 // This is not a cross-site navigation, the tab is being closed.
339 render_frame_host_->render_view_host()->ClosePage();
344 void RenderFrameHostManager::OnCrossSiteResponse(
345 RenderFrameHostImpl* pending_render_frame_host,
346 const GlobalRequestID& global_request_id,
347 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
348 const std::vector<GURL>& transfer_url_chain,
349 const Referrer& referrer,
350 PageTransition page_transition,
351 bool should_replace_current_entry) {
352 // We should only get here for transfer navigations. Most cross-process
353 // navigations can just continue and wait to run the unload handler (by
354 // swapping out) when the new navigation commits.
355 CHECK(cross_site_transferring_request.get());
357 // A transfer should only have come from our pending or current RFH.
358 // TODO(creis): We need to handle the case that the pending RFH has changed
359 // in the mean time, while this was being posted from the IO thread. We
360 // should probably cancel the request in that case.
361 DCHECK(pending_render_frame_host == pending_render_frame_host_ ||
362 pending_render_frame_host == render_frame_host_);
364 // Store the transferring request so that we can release it if the transfer
365 // navigation matches.
366 cross_site_transferring_request_ = cross_site_transferring_request.Pass();
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_render_frame_host->GetRoutingID());
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, global_request_id.child_id);
382 // Treat the last URL in the chain as the destination and the remainder as
383 // the redirect chain.
384 CHECK(transfer_url_chain.size());
385 GURL transfer_url = transfer_url_chain.back();
386 std::vector<GURL> rest_of_chain = transfer_url_chain;
387 rest_of_chain.pop_back();
389 // We don't know whether the original request had |user_action| set to true.
390 // However, since we force the navigation to be in the current tab, it
391 // doesn't matter.
392 pending_render_frame_host->frame_tree_node()->navigator()->RequestTransferURL(
393 pending_render_frame_host,
394 transfer_url,
395 rest_of_chain,
396 referrer,
397 page_transition,
398 CURRENT_TAB,
399 global_request_id,
400 should_replace_current_entry,
401 true);
403 // The transferring request was only needed during the RequestTransferURL
404 // call, so it is safe to clear at this point.
405 cross_site_transferring_request_.reset();
408 void RenderFrameHostManager::OnDeferredAfterResponseStarted(
409 const GlobalRequestID& global_request_id,
410 RenderFrameHostImpl* pending_render_frame_host) {
411 DCHECK(!response_started_id_.get());
413 response_started_id_.reset(new GlobalRequestID(global_request_id));
416 void RenderFrameHostManager::ResumeResponseDeferredAtStart() {
417 DCHECK(response_started_id_.get());
419 RenderProcessHostImpl* process =
420 static_cast<RenderProcessHostImpl*>(render_frame_host_->GetProcess());
421 process->ResumeResponseDeferredAtStart(*response_started_id_);
423 render_frame_host_->ClearPendingTransitionRequestData();
425 response_started_id_.reset();
428 void RenderFrameHostManager::DidNavigateFrame(
429 RenderFrameHostImpl* render_frame_host) {
430 if (!cross_navigation_pending_) {
431 DCHECK(!pending_render_frame_host_);
433 // We should only hear this from our current renderer.
434 DCHECK_EQ(render_frame_host_, render_frame_host);
436 // Even when there is no pending RVH, there may be a pending Web UI.
437 if (pending_web_ui())
438 CommitPending();
439 return;
442 if (render_frame_host == pending_render_frame_host_) {
443 // The pending cross-site navigation completed, so show the renderer.
444 CommitPending();
445 cross_navigation_pending_ = false;
446 } else if (render_frame_host == render_frame_host_) {
447 // A navigation in the original page has taken place. Cancel the pending
448 // one.
449 CancelPending();
450 cross_navigation_pending_ = false;
451 } else {
452 // No one else should be sending us DidNavigate in this state.
453 DCHECK(false);
457 void RenderFrameHostManager::DidDisownOpener(
458 RenderFrameHost* render_frame_host) {
459 // Notify all RenderFrameHosts but the one that notified us. This is necessary
460 // in case a process swap has occurred while the message was in flight.
461 for (RenderFrameProxyHostMap::iterator iter = proxy_hosts_.begin();
462 iter != proxy_hosts_.end();
463 ++iter) {
464 DCHECK_NE(iter->second->GetSiteInstance(),
465 current_frame_host()->GetSiteInstance());
466 iter->second->DisownOpener();
469 if (render_frame_host_.get() != render_frame_host)
470 render_frame_host_->DisownOpener();
472 if (pending_render_frame_host_ &&
473 pending_render_frame_host_.get() != render_frame_host) {
474 pending_render_frame_host_->DisownOpener();
478 void RenderFrameHostManager::RendererProcessClosing(
479 RenderProcessHost* render_process_host) {
480 // Remove any swapped out RVHs from this process, so that we don't try to
481 // swap them back in while the process is exiting. Start by finding them,
482 // since there could be more than one.
483 std::list<int> ids_to_remove;
484 for (RenderFrameProxyHostMap::iterator iter = proxy_hosts_.begin();
485 iter != proxy_hosts_.end();
486 ++iter) {
487 if (iter->second->GetProcess() == render_process_host)
488 ids_to_remove.push_back(iter->first);
491 // Now delete them.
492 while (!ids_to_remove.empty()) {
493 delete proxy_hosts_[ids_to_remove.back()];
494 proxy_hosts_.erase(ids_to_remove.back());
495 ids_to_remove.pop_back();
499 void RenderFrameHostManager::SwapOutOldPage(
500 RenderFrameHostImpl* old_render_frame_host) {
501 // Should only see this while we have a pending renderer.
502 CHECK(cross_navigation_pending_);
504 // Tell the renderer to suppress any further modal dialogs so that we can swap
505 // it out. This must be done before canceling any current dialog, in case
506 // there is a loop creating additional dialogs.
507 // TODO(creis): Handle modal dialogs in subframe processes.
508 old_render_frame_host->render_view_host()->SuppressDialogsUntilSwapOut();
510 // Now close any modal dialogs that would prevent us from swapping out. This
511 // must be done separately from SwapOut, so that the PageGroupLoadDeferrer is
512 // no longer on the stack when we send the SwapOut message.
513 delegate_->CancelModalDialogsForRenderManager();
515 // Create the RenderFrameProxyHost that will replace the
516 // RenderFrameHost which is swapping out. If one exists, ensure it is deleted
517 // from the map and not leaked.
518 DeleteRenderFrameProxyHost(old_render_frame_host->GetSiteInstance());
520 RenderFrameProxyHost* proxy = new RenderFrameProxyHost(
521 old_render_frame_host->GetSiteInstance(), frame_tree_node_);
522 std::pair<RenderFrameProxyHostMap::iterator, bool> result =
523 proxy_hosts_.insert(std::make_pair(
524 old_render_frame_host->GetSiteInstance()->GetId(), proxy));
525 CHECK(result.second) << "Inserting a duplicate item.";
527 // Tell the old frame it is being swapped out. This will fire the unload
528 // handler in the background (without firing the beforeunload handler a second
529 // time). This is done right after we commit the new RenderFrameHost.
530 old_render_frame_host->SwapOut(proxy);
533 void RenderFrameHostManager::ClearPendingShutdownRFHForSiteInstance(
534 int32 site_instance_id,
535 RenderFrameHostImpl* rfh) {
536 RFHPendingDeleteMap::iterator iter =
537 pending_delete_hosts_.find(site_instance_id);
538 if (iter != pending_delete_hosts_.end() && iter->second.get() == rfh)
539 pending_delete_hosts_.erase(site_instance_id);
542 void RenderFrameHostManager::ResetProxyHosts() {
543 STLDeleteValues(&proxy_hosts_);
546 // PlzNavigate
547 bool RenderFrameHostManager::RequestNavigation(
548 const NavigationEntryImpl& entry,
549 const FrameMsg_Navigate_Params& navigate_params) {
550 CHECK(CommandLine::ForCurrentProcess()->HasSwitch(
551 switches::kEnableBrowserSideNavigation));
552 // TODO(clamy): replace RenderViewHost::IsRenderViewLive by
553 // RenderFrameHost::IsLive.
554 if (render_frame_host_->render_view_host()->IsRenderViewLive())
555 // TODO(clamy): send a RequestNavigation IPC.
556 return true;
558 // The navigation request is sent directly to the IO thread.
559 OnBeginNavigation(BeginNavigationFromNavigate(navigate_params));
560 return true;
563 // PlzNavigate
564 void RenderFrameHostManager::OnBeginNavigation(
565 const FrameHostMsg_BeginNavigation_Params& params) {
566 CHECK(CommandLine::ForCurrentProcess()->HasSwitch(
567 switches::kEnableBrowserSideNavigation));
568 // TODO(clamy): Check if navigations are blocked and if so, return
569 // immediately.
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 // TODO(clamy): Check if the current RFH should be initialized (in case it has
580 // crashed) not to display a sad tab while navigating.
581 // TODO(clamy): Spawn a speculative renderer process if we do not have one to
582 // use for the navigation.
583 navigation_request_.reset(new NavigationRequest(
584 info, frame_tree_node_->frame_tree_node_id()));
585 navigation_request_->BeginNavigation(params.request_body);
588 // PlzNavigate
589 void RenderFrameHostManager::CommitNavigation(
590 const NavigationBeforeCommitInfo& info) {
591 CHECK(CommandLine::ForCurrentProcess()->HasSwitch(
592 switches::kEnableBrowserSideNavigation));
593 // Pick the right RenderFrameHost to commit the navigation.
594 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
595 // TODO(clamy): Replace the default values by the right ones. This may require
596 // some storing in RequestNavigation.
597 SiteInstance* new_instance = GetSiteInstanceForNavigation(
598 info.navigation_url,
599 NULL,
600 navigation_request_->info().navigation_params.transition_type,
601 false,
602 false);
603 DCHECK(!pending_render_frame_host_.get());
605 // TODO(clamy): Update how pending WebUI objects are handled.
606 if (current_instance != new_instance) {
607 CreateRenderFrameHostForNewSiteInstance(
608 current_instance, new_instance, frame_tree_node_->IsMainFrame());
609 DCHECK(pending_render_frame_host_.get());
610 // TODO(clamy): Wait until the navigation has committed before swapping
611 // renderers.
612 scoped_ptr<RenderFrameHostImpl> old_render_frame_host =
613 SetRenderFrameHost(pending_render_frame_host_.Pass());
614 if (frame_tree_node_->IsMainFrame())
615 render_frame_host_->render_view_host()->AttachToFrameTree();
618 frame_tree_node_->navigator()->CommitNavigation(
619 render_frame_host_.get(), info);
622 void RenderFrameHostManager::Observe(
623 int type,
624 const NotificationSource& source,
625 const NotificationDetails& details) {
626 switch (type) {
627 case NOTIFICATION_RENDERER_PROCESS_CLOSED:
628 case NOTIFICATION_RENDERER_PROCESS_CLOSING:
629 RendererProcessClosing(
630 Source<RenderProcessHost>(source).ptr());
631 break;
633 default:
634 NOTREACHED();
638 bool RenderFrameHostManager::ClearProxiesInSiteInstance(
639 int32 site_instance_id,
640 FrameTreeNode* node) {
641 RenderFrameProxyHostMap::iterator iter =
642 node->render_manager()->proxy_hosts_.find(site_instance_id);
643 if (iter != node->render_manager()->proxy_hosts_.end()) {
644 RenderFrameProxyHost* proxy = iter->second;
645 // If the RVH is pending swap out, it needs to switch state to
646 // pending shutdown. Otherwise it is deleted.
647 if (proxy->GetRenderViewHost()->rvh_state() ==
648 RenderViewHostImpl::STATE_PENDING_SWAP_OUT) {
649 scoped_ptr<RenderFrameHostImpl> swapped_out_rfh =
650 proxy->PassFrameHostOwnership();
652 swapped_out_rfh->SetPendingShutdown(base::Bind(
653 &RenderFrameHostManager::ClearPendingShutdownRFHForSiteInstance,
654 node->render_manager()->weak_factory_.GetWeakPtr(),
655 site_instance_id,
656 swapped_out_rfh.get()));
657 RFHPendingDeleteMap::iterator pending_delete_iter =
658 node->render_manager()->pending_delete_hosts_.find(site_instance_id);
659 if (pending_delete_iter ==
660 node->render_manager()->pending_delete_hosts_.end() ||
661 pending_delete_iter->second.get() != swapped_out_rfh) {
662 node->render_manager()->pending_delete_hosts_[site_instance_id] =
663 linked_ptr<RenderFrameHostImpl>(swapped_out_rfh.release());
666 delete proxy;
667 node->render_manager()->proxy_hosts_.erase(site_instance_id);
670 return true;
673 bool RenderFrameHostManager::ShouldTransitionCrossSite() {
674 // False in the single-process mode, as it makes RVHs to accumulate
675 // in swapped_out_hosts_.
676 // True if we are using process-per-site-instance (default) or
677 // process-per-site (kProcessPerSite).
678 return
679 !CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess) &&
680 !CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessPerTab);
683 bool RenderFrameHostManager::ShouldSwapBrowsingInstancesForNavigation(
684 const GURL& current_effective_url,
685 bool current_is_view_source_mode,
686 SiteInstance* new_site_instance,
687 const GURL& new_effective_url,
688 bool new_is_view_source_mode) const {
689 // If new_entry already has a SiteInstance, assume it is correct. We only
690 // need to force a swap if it is in a different BrowsingInstance.
691 if (new_site_instance) {
692 return !new_site_instance->IsRelatedSiteInstance(
693 render_frame_host_->GetSiteInstance());
696 // Check for reasons to swap processes even if we are in a process model that
697 // doesn't usually swap (e.g., process-per-tab). Any time we return true,
698 // the new_entry will be rendered in a new SiteInstance AND BrowsingInstance.
699 BrowserContext* browser_context =
700 delegate_->GetControllerForRenderManager().GetBrowserContext();
702 // Don't force a new BrowsingInstance for debug URLs that are handled in the
703 // renderer process, like javascript: or chrome://crash.
704 if (IsRendererDebugURL(new_effective_url))
705 return false;
707 // For security, we should transition between processes when one is a Web UI
708 // page and one isn't.
709 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
710 browser_context, current_effective_url)) {
711 // If so, force a swap if destination is not an acceptable URL for Web UI.
712 // Here, data URLs are never allowed.
713 if (!WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
714 browser_context, new_effective_url)) {
715 return true;
717 } else {
718 // Force a swap if it's a Web UI URL.
719 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
720 browser_context, new_effective_url)) {
721 return true;
725 // Check with the content client as well. Important to pass
726 // current_effective_url here, which uses the SiteInstance's site if there is
727 // no current_entry.
728 if (GetContentClient()->browser()->ShouldSwapBrowsingInstancesForNavigation(
729 render_frame_host_->GetSiteInstance(),
730 current_effective_url, new_effective_url)) {
731 return true;
734 // We can't switch a RenderView between view source and non-view source mode
735 // without screwing up the session history sometimes (when navigating between
736 // "view-source:http://foo.com/" and "http://foo.com/", Blink doesn't treat
737 // it as a new navigation). So require a BrowsingInstance switch.
738 if (current_is_view_source_mode != new_is_view_source_mode)
739 return true;
741 return false;
744 bool RenderFrameHostManager::ShouldReuseWebUI(
745 const NavigationEntry* current_entry,
746 const NavigationEntryImpl* new_entry) const {
747 NavigationControllerImpl& controller =
748 delegate_->GetControllerForRenderManager();
749 return current_entry && web_ui_.get() &&
750 (WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
751 controller.GetBrowserContext(), current_entry->GetURL()) ==
752 WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
753 controller.GetBrowserContext(), new_entry->GetURL()));
756 SiteInstance* RenderFrameHostManager::GetSiteInstanceForNavigation(
757 const GURL& dest_url,
758 SiteInstance* dest_instance,
759 PageTransition dest_transition,
760 bool dest_is_restore,
761 bool dest_is_view_source_mode) {
762 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
763 SiteInstance* new_instance = current_instance;
765 // We do not currently swap processes for navigations in webview tag guests.
766 bool is_guest_scheme = current_instance->GetSiteURL().SchemeIs(kGuestScheme);
768 // Determine if we need a new BrowsingInstance for this entry. If true, this
769 // implies that it will get a new SiteInstance (and likely process), and that
770 // other tabs in the current BrowsingInstance will be unable to script it.
771 // This is used for cases that require a process swap even in the
772 // process-per-tab model, such as WebUI pages.
773 // TODO(clamy): Remove the dependency on the current entry.
774 const NavigationEntry* current_entry =
775 delegate_->GetLastCommittedNavigationEntryForRenderManager();
776 BrowserContext* browser_context =
777 delegate_->GetControllerForRenderManager().GetBrowserContext();
778 const GURL& current_effective_url = current_entry ?
779 SiteInstanceImpl::GetEffectiveURL(browser_context,
780 current_entry->GetURL()) :
781 render_frame_host_->GetSiteInstance()->GetSiteURL();
782 bool current_is_view_source_mode = current_entry ?
783 current_entry->IsViewSourceMode() : dest_is_view_source_mode;
784 bool force_swap = !is_guest_scheme &&
785 ShouldSwapBrowsingInstancesForNavigation(
786 current_effective_url,
787 current_is_view_source_mode,
788 dest_instance,
789 SiteInstanceImpl::GetEffectiveURL(browser_context, dest_url),
790 dest_is_view_source_mode);
791 if (!is_guest_scheme && (ShouldTransitionCrossSite() || force_swap)) {
792 new_instance = GetSiteInstanceForURL(
793 dest_url,
794 dest_instance,
795 dest_transition,
796 dest_is_restore,
797 dest_is_view_source_mode,
798 current_instance,
799 force_swap);
802 // If force_swap is true, we must use a different SiteInstance. If we didn't,
803 // we would have two RenderFrameHosts in the same SiteInstance and the same
804 // frame, resulting in page_id conflicts for their NavigationEntries.
805 if (force_swap)
806 CHECK_NE(new_instance, current_instance);
807 return new_instance;
810 SiteInstance* RenderFrameHostManager::GetSiteInstanceForURL(
811 const GURL& dest_url,
812 SiteInstance* dest_instance,
813 PageTransition dest_transition,
814 bool dest_is_restore,
815 bool dest_is_view_source_mode,
816 SiteInstance* current_instance,
817 bool force_browsing_instance_swap) {
818 NavigationControllerImpl& controller =
819 delegate_->GetControllerForRenderManager();
820 BrowserContext* browser_context = controller.GetBrowserContext();
822 // If the entry has an instance already we should use it.
823 if (dest_instance) {
824 // If we are forcing a swap, this should be in a different BrowsingInstance.
825 if (force_browsing_instance_swap) {
826 CHECK(!dest_instance->IsRelatedSiteInstance(
827 render_frame_host_->GetSiteInstance()));
829 return dest_instance;
832 // If a swap is required, we need to force the SiteInstance AND
833 // BrowsingInstance to be different ones, using CreateForURL.
834 if (force_browsing_instance_swap)
835 return SiteInstance::CreateForURL(browser_context, dest_url);
837 // (UGLY) HEURISTIC, process-per-site only:
839 // If this navigation is generated, then it probably corresponds to a search
840 // query. Given that search results typically lead to users navigating to
841 // other sites, we don't really want to use the search engine hostname to
842 // determine the site instance for this navigation.
844 // NOTE: This can be removed once we have a way to transition between
845 // RenderViews in response to a link click.
847 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessPerSite) &&
848 PageTransitionCoreTypeIs(dest_transition, PAGE_TRANSITION_GENERATED)) {
849 return current_instance;
852 SiteInstanceImpl* current_site_instance =
853 static_cast<SiteInstanceImpl*>(current_instance);
855 // If we haven't used our SiteInstance (and thus RVH) yet, then we can use it
856 // for this entry. We won't commit the SiteInstance to this site until the
857 // navigation commits (in DidNavigate), unless the navigation entry was
858 // restored or it's a Web UI as described below.
859 if (!current_site_instance->HasSite()) {
860 // If we've already created a SiteInstance for our destination, we don't
861 // want to use this unused SiteInstance; use the existing one. (We don't
862 // do this check if the current_instance has a site, because for now, we
863 // want to compare against the current URL and not the SiteInstance's site.
864 // In this case, there is no current URL, so comparing against the site is
865 // ok. See additional comments below.)
867 // Also, if the URL should use process-per-site mode and there is an
868 // existing process for the site, we should use it. We can call
869 // GetRelatedSiteInstance() for this, which will eagerly set the site and
870 // thus use the correct process.
871 bool use_process_per_site =
872 RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) &&
873 RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url);
874 if (current_site_instance->HasRelatedSiteInstance(dest_url) ||
875 use_process_per_site) {
876 return current_site_instance->GetRelatedSiteInstance(dest_url);
879 // For extensions, Web UI URLs (such as the new tab page), and apps we do
880 // not want to use the current_instance if it has no site, since it will
881 // have a RenderProcessHost of PRIV_NORMAL. Create a new SiteInstance for
882 // this URL instead (with the correct process type).
883 if (current_site_instance->HasWrongProcessForURL(dest_url))
884 return current_site_instance->GetRelatedSiteInstance(dest_url);
886 // View-source URLs must use a new SiteInstance and BrowsingInstance.
887 // TODO(nasko): This is the same condition as later in the function. This
888 // should be taken into account when refactoring this method as part of
889 // http://crbug.com/123007.
890 if (dest_is_view_source_mode)
891 return SiteInstance::CreateForURL(browser_context, dest_url);
893 // If we are navigating from a blank SiteInstance to a WebUI, make sure we
894 // create a new SiteInstance.
895 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
896 browser_context, dest_url)) {
897 return SiteInstance::CreateForURL(browser_context, dest_url);
900 // Normally the "site" on the SiteInstance is set lazily when the load
901 // actually commits. This is to support better process sharing in case
902 // the site redirects to some other site: we want to use the destination
903 // site in the site instance.
905 // In the case of session restore, as it loads all the pages immediately
906 // we need to set the site first, otherwise after a restore none of the
907 // pages would share renderers in process-per-site.
909 // The embedder can request some urls never to be assigned to SiteInstance
910 // through the ShouldAssignSiteForURL() content client method, so that
911 // renderers created for particular chrome urls (e.g. the chrome-native://
912 // scheme) can be reused for subsequent navigations in the same WebContents.
913 // See http://crbug.com/386542.
914 if (dest_is_restore &&
915 GetContentClient()->browser()->ShouldAssignSiteForURL(dest_url)) {
916 current_site_instance->SetSite(dest_url);
919 return current_site_instance;
922 // Otherwise, only create a new SiteInstance for a cross-site navigation.
924 // TODO(creis): Once we intercept links and script-based navigations, we
925 // will be able to enforce that all entries in a SiteInstance actually have
926 // the same site, and it will be safe to compare the URL against the
927 // SiteInstance's site, as follows:
928 // const GURL& current_url = current_instance->site();
929 // For now, though, we're in a hybrid model where you only switch
930 // SiteInstances if you type in a cross-site URL. This means we have to
931 // compare the entry's URL to the last committed entry's URL.
932 NavigationEntry* current_entry = controller.GetLastCommittedEntry();
933 if (interstitial_page_) {
934 // The interstitial is currently the last committed entry, but we want to
935 // compare against the last non-interstitial entry.
936 current_entry = controller.GetEntryAtOffset(-1);
938 // If there is no last non-interstitial entry (and current_instance already
939 // has a site), then we must have been opened from another tab. We want
940 // to compare against the URL of the page that opened us, but we can't
941 // get to it directly. The best we can do is check against the site of
942 // the SiteInstance. This will be correct when we intercept links and
943 // script-based navigations, but for now, it could place some pages in a
944 // new process unnecessarily. We should only hit this case if a page tries
945 // to open a new tab to an interstitial-inducing URL, and then navigates
946 // the page to a different same-site URL. (This seems very unlikely in
947 // practice.)
948 const GURL& current_url = (current_entry) ? current_entry->GetURL() :
949 current_instance->GetSiteURL();
951 // View-source URLs must use a new SiteInstance and BrowsingInstance.
952 // We don't need a swap when going from view-source to a debug URL like
953 // chrome://crash, however.
954 // TODO(creis): Refactor this method so this duplicated code isn't needed.
955 // See http://crbug.com/123007.
956 if (current_entry &&
957 current_entry->IsViewSourceMode() != dest_is_view_source_mode &&
958 !IsRendererDebugURL(dest_url)) {
959 return SiteInstance::CreateForURL(browser_context, dest_url);
962 // Use the current SiteInstance for same site navigations, as long as the
963 // process type is correct. (The URL may have been installed as an app since
964 // the last time we visited it.)
965 if (SiteInstance::IsSameWebSite(browser_context, current_url, dest_url) &&
966 !current_site_instance->HasWrongProcessForURL(dest_url)) {
967 return current_instance;
970 // Start the new renderer in a new SiteInstance, but in the current
971 // BrowsingInstance. It is important to immediately give this new
972 // SiteInstance to a RenderViewHost (if it is different than our current
973 // SiteInstance), so that it is ref counted. This will happen in
974 // CreateRenderView.
975 return current_instance->GetRelatedSiteInstance(dest_url);
978 void RenderFrameHostManager::CreateRenderFrameHostForNewSiteInstance(
979 SiteInstance* old_instance,
980 SiteInstance* new_instance,
981 bool is_main_frame) {
982 // Ensure that we have created RFHs for the new RFH's opener chain if
983 // we are staying in the same BrowsingInstance. This allows the new RFH
984 // to send cross-process script calls to its opener(s).
985 int opener_route_id = MSG_ROUTING_NONE;
986 if (new_instance->IsRelatedSiteInstance(old_instance)) {
987 opener_route_id =
988 delegate_->CreateOpenerRenderViewsForRenderManager(new_instance);
989 if (CommandLine::ForCurrentProcess()->HasSwitch(
990 switches::kSitePerProcess)) {
991 // Ensure that the frame tree has RenderFrameProxyHosts for the new
992 // SiteInstance in all nodes except the current one.
993 frame_tree_node_->frame_tree()->CreateProxiesForSiteInstance(
994 frame_tree_node_, new_instance);
998 // Create a non-swapped-out RFH with the given opener.
999 int route_id = CreateRenderFrame(
1000 new_instance, opener_route_id, false, is_main_frame,
1001 delegate_->IsHidden());
1002 if (route_id == MSG_ROUTING_NONE) {
1003 pending_render_frame_host_.reset();
1004 return;
1008 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::CreateRenderFrameHost(
1009 SiteInstance* site_instance,
1010 int view_routing_id,
1011 int frame_routing_id,
1012 bool swapped_out,
1013 bool hidden) {
1014 if (frame_routing_id == MSG_ROUTING_NONE)
1015 frame_routing_id = site_instance->GetProcess()->GetNextRoutingID();
1017 // Create a RVH for main frames, or find the existing one for subframes.
1018 FrameTree* frame_tree = frame_tree_node_->frame_tree();
1019 RenderViewHostImpl* render_view_host = NULL;
1020 if (frame_tree_node_->IsMainFrame()) {
1021 render_view_host = frame_tree->CreateRenderViewHost(
1022 site_instance, view_routing_id, frame_routing_id, swapped_out, hidden);
1023 } else {
1024 render_view_host = frame_tree->GetRenderViewHost(site_instance);
1026 CHECK(render_view_host);
1029 // TODO(creis): Pass hidden to RFH.
1030 scoped_ptr<RenderFrameHostImpl> render_frame_host =
1031 make_scoped_ptr(RenderFrameHostFactory::Create(render_view_host,
1032 render_frame_delegate_,
1033 frame_tree,
1034 frame_tree_node_,
1035 frame_routing_id,
1036 swapped_out).release());
1037 return render_frame_host.Pass();
1040 int RenderFrameHostManager::CreateRenderFrame(SiteInstance* instance,
1041 int opener_route_id,
1042 bool swapped_out,
1043 bool for_main_frame_navigation,
1044 bool hidden) {
1045 CHECK(instance);
1046 DCHECK(!swapped_out || hidden); // Swapped out views should always be hidden.
1048 // TODO(nasko): Remove the following CHECK once cross-site navigation no
1049 // longer relies on swapped out RFH for the top-level frame.
1050 if (!frame_tree_node_->IsMainFrame()) {
1051 CHECK(!swapped_out);
1054 scoped_ptr<RenderFrameHostImpl> new_render_frame_host;
1055 RenderFrameHostImpl* frame_to_announce = NULL;
1056 int routing_id = MSG_ROUTING_NONE;
1058 // We are creating a pending or swapped out RFH here. We should never create
1059 // it in the same SiteInstance as our current RFH.
1060 CHECK_NE(render_frame_host_->GetSiteInstance(), instance);
1062 // Check if we've already created an RFH for this SiteInstance. If so, try
1063 // to re-use the existing one, which has already been initialized. We'll
1064 // remove it from the list of proxy hosts below if it will be active.
1065 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1067 if (proxy) {
1068 routing_id = proxy->GetRenderViewHost()->GetRoutingID();
1069 // Delete the existing RenderFrameProxyHost, but reuse the RenderFrameHost.
1070 // Prevent the process from exiting while we're trying to use it.
1071 if (!swapped_out) {
1072 new_render_frame_host = proxy->PassFrameHostOwnership();
1073 new_render_frame_host->GetProcess()->AddPendingView();
1075 proxy_hosts_.erase(instance->GetId());
1076 delete proxy;
1078 // When a new render view is created by the renderer, the new WebContents
1079 // gets a RenderViewHost in the SiteInstance of its opener WebContents.
1080 // If not used in the first navigation, this RVH is swapped out and is not
1081 // granted bindings, so we may need to grant them when swapping it in.
1082 if (pending_web_ui() &&
1083 !new_render_frame_host->GetProcess()->IsIsolatedGuest()) {
1084 int required_bindings = pending_web_ui()->GetBindings();
1085 RenderViewHost* rvh = new_render_frame_host->render_view_host();
1086 if ((rvh->GetEnabledBindings() & required_bindings) !=
1087 required_bindings) {
1088 rvh->AllowBindings(required_bindings);
1092 } else {
1093 // Create a new RenderFrameHost if we don't find an existing one.
1094 new_render_frame_host = CreateRenderFrameHost(
1095 instance, MSG_ROUTING_NONE, MSG_ROUTING_NONE, swapped_out, hidden);
1096 RenderViewHostImpl* render_view_host =
1097 new_render_frame_host->render_view_host();
1098 int proxy_routing_id = MSG_ROUTING_NONE;
1100 // Prevent the process from exiting while we're trying to navigate in it.
1101 // Otherwise, if the new RFH is swapped out already, store it.
1102 if (!swapped_out) {
1103 new_render_frame_host->GetProcess()->AddPendingView();
1104 } else {
1105 proxy = new RenderFrameProxyHost(
1106 new_render_frame_host->GetSiteInstance(), frame_tree_node_);
1107 proxy_hosts_[instance->GetId()] = proxy;
1108 proxy->TakeFrameHostOwnership(new_render_frame_host.Pass());
1109 proxy_routing_id = proxy->GetRoutingID();
1112 bool success = InitRenderView(render_view_host,
1113 opener_route_id,
1114 proxy_routing_id,
1115 for_main_frame_navigation);
1116 if (success) {
1117 if (frame_tree_node_->IsMainFrame()) {
1118 // Don't show the main frame's view until we get a DidNavigate from it.
1119 render_view_host->GetView()->Hide();
1120 } else if (!swapped_out) {
1121 // Init the RFH, so a RenderFrame is created in the renderer.
1122 DCHECK(new_render_frame_host.get());
1123 success = InitRenderFrame(new_render_frame_host.get());
1125 if (swapped_out) {
1126 proxy_hosts_[instance->GetId()]->InitRenderFrameProxy();
1128 } else if (!swapped_out && pending_render_frame_host_) {
1129 CancelPending();
1131 routing_id = render_view_host->GetRoutingID();
1132 frame_to_announce = new_render_frame_host.get();
1135 // Use this as our new pending RFH if it isn't swapped out.
1136 if (!swapped_out)
1137 pending_render_frame_host_ = new_render_frame_host.Pass();
1139 // If a brand new RFH was created, announce it to observers.
1140 if (frame_to_announce)
1141 render_frame_delegate_->RenderFrameCreated(frame_to_announce);
1143 return routing_id;
1146 int RenderFrameHostManager::CreateRenderFrameProxy(SiteInstance* instance) {
1147 // A RenderFrameProxyHost should never be created in the same SiteInstance as
1148 // the current RFH.
1149 CHECK(instance);
1150 CHECK_NE(instance, render_frame_host_->GetSiteInstance());
1152 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1153 if (proxy)
1154 return proxy->GetRoutingID();
1156 proxy = new RenderFrameProxyHost(instance, frame_tree_node_);
1157 proxy_hosts_[instance->GetId()] = proxy;
1158 proxy->InitRenderFrameProxy();
1159 return proxy->GetRoutingID();
1162 bool RenderFrameHostManager::InitRenderView(RenderViewHost* render_view_host,
1163 int opener_route_id,
1164 int proxy_routing_id,
1165 bool for_main_frame_navigation) {
1166 // We may have initialized this RenderViewHost for another RenderFrameHost.
1167 if (render_view_host->IsRenderViewLive())
1168 return true;
1170 // If the pending navigation is to a WebUI and the RenderView is not in a
1171 // guest process, tell the RenderViewHost about any bindings it will need
1172 // enabled.
1173 if (pending_web_ui() && !render_view_host->GetProcess()->IsIsolatedGuest()) {
1174 render_view_host->AllowBindings(pending_web_ui()->GetBindings());
1175 } else {
1176 // Ensure that we don't create an unprivileged RenderView in a WebUI-enabled
1177 // process unless it's swapped out.
1178 RenderViewHostImpl* rvh_impl =
1179 static_cast<RenderViewHostImpl*>(render_view_host);
1180 if (!rvh_impl->IsSwappedOut()) {
1181 CHECK(!ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1182 render_view_host->GetProcess()->GetID()));
1186 return delegate_->CreateRenderViewForRenderManager(
1187 render_view_host,
1188 opener_route_id,
1189 proxy_routing_id,
1190 for_main_frame_navigation);
1193 bool RenderFrameHostManager::InitRenderFrame(
1194 RenderFrameHost* render_frame_host) {
1195 RenderFrameHostImpl* rfh =
1196 static_cast<RenderFrameHostImpl*>(render_frame_host);
1197 if (rfh->IsRenderFrameLive())
1198 return true;
1200 int parent_routing_id = MSG_ROUTING_NONE;
1201 if (frame_tree_node_->parent()) {
1202 parent_routing_id = frame_tree_node_->parent()->render_manager()->
1203 GetRoutingIdForSiteInstance(render_frame_host->GetSiteInstance());
1204 CHECK_NE(parent_routing_id, MSG_ROUTING_NONE);
1206 return delegate_->CreateRenderFrameForRenderManager(render_frame_host,
1207 parent_routing_id);
1210 int RenderFrameHostManager::GetRoutingIdForSiteInstance(
1211 SiteInstance* site_instance) {
1212 if (render_frame_host_->GetSiteInstance() == site_instance)
1213 return render_frame_host_->GetRoutingID();
1215 RenderFrameProxyHostMap::iterator iter =
1216 proxy_hosts_.find(site_instance->GetId());
1217 if (iter != proxy_hosts_.end())
1218 return iter->second->GetRoutingID();
1220 return MSG_ROUTING_NONE;
1223 void RenderFrameHostManager::CommitPending() {
1224 // First check whether we're going to want to focus the location bar after
1225 // this commit. We do this now because the navigation hasn't formally
1226 // committed yet, so if we've already cleared |pending_web_ui_| the call chain
1227 // this triggers won't be able to figure out what's going on.
1228 bool will_focus_location_bar = delegate_->FocusLocationBarByDefault();
1230 // Next commit the Web UI, if any. Either replace |web_ui_| with
1231 // |pending_web_ui_|, or clear |web_ui_| if there is no pending WebUI, or
1232 // leave |web_ui_| as is if reusing it.
1233 DCHECK(!(pending_web_ui_.get() && pending_and_current_web_ui_.get()));
1234 if (pending_web_ui_) {
1235 web_ui_.reset(pending_web_ui_.release());
1236 } else if (!pending_and_current_web_ui_.get()) {
1237 web_ui_.reset();
1238 } else {
1239 DCHECK_EQ(pending_and_current_web_ui_.get(), web_ui_.get());
1240 pending_and_current_web_ui_.reset();
1243 // It's possible for the pending_render_frame_host_ to be NULL when we aren't
1244 // crossing process boundaries. If so, we just needed to handle the Web UI
1245 // committing above and we're done.
1246 if (!pending_render_frame_host_) {
1247 if (will_focus_location_bar)
1248 delegate_->SetFocusToLocationBar(false);
1249 return;
1252 // Remember if the page was focused so we can focus the new renderer in
1253 // that case.
1254 bool focus_render_view = !will_focus_location_bar &&
1255 render_frame_host_->render_view_host()->GetView() &&
1256 render_frame_host_->render_view_host()->GetView()->HasFocus();
1258 // TODO(creis): As long as show/hide are on RVH, we don't want to do them for
1259 // subframe navigations or they'll interfere with the top-level page.
1260 bool is_main_frame = frame_tree_node_->IsMainFrame();
1262 // Swap in the pending frame and make it active. Also ensure the FrameTree
1263 // stays in sync.
1264 scoped_ptr<RenderFrameHostImpl> old_render_frame_host =
1265 SetRenderFrameHost(pending_render_frame_host_.Pass());
1266 if (is_main_frame)
1267 render_frame_host_->render_view_host()->AttachToFrameTree();
1269 // The process will no longer try to exit, so we can decrement the count.
1270 render_frame_host_->GetProcess()->RemovePendingView();
1272 // If the view is gone, then this RenderViewHost died while it was hidden.
1273 // We ignored the RenderProcessGone call at the time, so we should send it now
1274 // to make sure the sad tab shows up, etc.
1275 if (!render_frame_host_->render_view_host()->GetView()) {
1276 delegate_->RenderProcessGoneFromRenderManager(
1277 render_frame_host_->render_view_host());
1278 } else if (!delegate_->IsHidden()) {
1279 render_frame_host_->render_view_host()->GetView()->Show();
1282 // If the old frame is live, swap it out now that the new frame is visible.
1283 int32 old_site_instance_id =
1284 old_render_frame_host->GetSiteInstance()->GetId();
1285 if (old_render_frame_host->render_view_host()->IsRenderViewLive()) {
1286 SwapOutOldPage(old_render_frame_host.get());
1288 // Schedule the old frame to shut down after it swaps out, if there are no
1289 // other active views in its SiteInstance.
1290 if (!static_cast<SiteInstanceImpl*>(
1291 old_render_frame_host->GetSiteInstance())->active_view_count()) {
1292 old_render_frame_host->render_view_host()->SetPendingShutdown(base::Bind(
1293 &RenderFrameHostManager::ClearPendingShutdownRFHForSiteInstance,
1294 weak_factory_.GetWeakPtr(),
1295 old_site_instance_id,
1296 old_render_frame_host.get()));
1300 // For top-level frames, also hide the old RenderViewHost's view.
1301 if (is_main_frame && old_render_frame_host->render_view_host()->GetView())
1302 old_render_frame_host->render_view_host()->GetView()->Hide();
1304 // Make sure the size is up to date. (Fix for bug 1079768.)
1305 delegate_->UpdateRenderViewSizeForRenderManager();
1307 if (will_focus_location_bar) {
1308 delegate_->SetFocusToLocationBar(false);
1309 } else if (focus_render_view &&
1310 render_frame_host_->render_view_host()->GetView()) {
1311 render_frame_host_->render_view_host()->GetView()->Focus();
1314 // Notify that we've swapped RenderFrameHosts. We do this before shutting down
1315 // the RFH so that we can clean up RendererResources related to the RFH first.
1316 delegate_->NotifySwappedFromRenderManager(
1317 old_render_frame_host.get(), render_frame_host_.get(), is_main_frame);
1319 // If the old RFH is not live, just return as there is no further work to do.
1320 if (!old_render_frame_host->render_view_host()->IsRenderViewLive())
1321 return;
1323 // If the old RFH is live, we are swapping it out and should keep track of
1324 // it in case we navigate back to it, or it is waiting for the unload event
1325 // to execute in the background.
1326 // TODO(creis): Swap out the subframe in --site-per-process.
1327 if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess)) {
1328 DCHECK(old_render_frame_host->is_swapped_out() ||
1329 !RenderViewHostImpl::IsRVHStateActive(
1330 old_render_frame_host->render_view_host()->rvh_state()));
1333 // If the RenderViewHost backing the RenderFrameHost is pending shutdown,
1334 // the RenderFrameHost should be put in the map of RenderFrameHosts pending
1335 // shutdown. Otherwise, it is stored in the map of proxy hosts.
1336 if (old_render_frame_host->render_view_host()->rvh_state() ==
1337 RenderViewHostImpl::STATE_PENDING_SHUTDOWN) {
1338 // The proxy for this RenderFrameHost is created when sending the
1339 // SwapOut message, so check if it already exists and delete it.
1340 RenderFrameProxyHostMap::iterator iter =
1341 proxy_hosts_.find(old_site_instance_id);
1342 if (iter != proxy_hosts_.end()) {
1343 delete iter->second;
1344 proxy_hosts_.erase(iter);
1346 RFHPendingDeleteMap::iterator pending_delete_iter =
1347 pending_delete_hosts_.find(old_site_instance_id);
1348 if (pending_delete_iter == pending_delete_hosts_.end() ||
1349 pending_delete_iter->second.get() != old_render_frame_host) {
1350 pending_delete_hosts_[old_site_instance_id] =
1351 linked_ptr<RenderFrameHostImpl>(old_render_frame_host.release());
1353 } else {
1354 CHECK(proxy_hosts_.find(render_frame_host_->GetSiteInstance()->GetId()) ==
1355 proxy_hosts_.end());
1357 // Capture the active view count on the old RFH SiteInstance, since the
1358 // ownership might be passed into the proxy and the pointer will be
1359 // invalid.
1360 int active_view_count =
1361 static_cast<SiteInstanceImpl*>(old_render_frame_host->GetSiteInstance())
1362 ->active_view_count();
1364 if (is_main_frame) {
1365 RenderFrameProxyHostMap::iterator iter =
1366 proxy_hosts_.find(old_site_instance_id);
1367 CHECK(iter != proxy_hosts_.end());
1368 iter->second->TakeFrameHostOwnership(old_render_frame_host.Pass());
1371 // If there are no active views in this SiteInstance, it means that
1372 // this RFH was the last active one in the SiteInstance. Now that we
1373 // know that all RFHs are swapped out, we can delete all the RFPHs and
1374 // RVHs in this SiteInstance.
1375 if (!active_view_count) {
1376 ShutdownRenderFrameProxyHostsInSiteInstance(old_site_instance_id);
1377 } else {
1378 // If this is a subframe, it should have a CrossProcessFrameConnector
1379 // created already and we just need to link it to the proper view in the
1380 // new process.
1381 if (!is_main_frame) {
1382 RenderFrameProxyHost* proxy = GetProxyToParent();
1383 if (proxy) {
1384 proxy->SetChildRWHView(
1385 render_frame_host_->render_view_host()->GetView());
1392 void RenderFrameHostManager::ShutdownRenderFrameProxyHostsInSiteInstance(
1393 int32 site_instance_id) {
1394 // First remove any swapped out RFH for this SiteInstance from our own list.
1395 ClearProxiesInSiteInstance(site_instance_id, frame_tree_node_);
1397 // Use the safe RenderWidgetHost iterator for now to find all RenderViewHosts
1398 // in the SiteInstance, then tell their respective FrameTrees to remove all
1399 // RenderFrameProxyHosts corresponding to them.
1400 // TODO(creis): Replace this with a RenderFrameHostIterator that protects
1401 // against use-after-frees if a later element is deleted before getting to it.
1402 scoped_ptr<RenderWidgetHostIterator> widgets(
1403 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
1404 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
1405 if (!widget->IsRenderView())
1406 continue;
1407 RenderViewHostImpl* rvh =
1408 static_cast<RenderViewHostImpl*>(RenderViewHost::From(widget));
1409 if (site_instance_id == rvh->GetSiteInstance()->GetId()) {
1410 // This deletes all RenderFrameHosts using the |rvh|, which then causes
1411 // |rvh| to Shutdown.
1412 FrameTree* tree = rvh->GetDelegate()->GetFrameTree();
1413 tree->ForEach(base::Bind(
1414 &RenderFrameHostManager::ClearProxiesInSiteInstance,
1415 site_instance_id));
1420 RenderFrameHostImpl* RenderFrameHostManager::UpdateStateForNavigate(
1421 const NavigationEntryImpl& entry) {
1422 // If we are currently navigating cross-process, we want to get back to normal
1423 // and then navigate as usual.
1424 if (cross_navigation_pending_) {
1425 if (pending_render_frame_host_)
1426 CancelPending();
1427 cross_navigation_pending_ = false;
1430 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1431 scoped_refptr<SiteInstance> new_instance =
1432 GetSiteInstanceForNavigation(
1433 entry.GetURL(),
1434 entry.site_instance(),
1435 entry.GetTransitionType(),
1436 entry.restore_type() != NavigationEntryImpl::RESTORE_NONE,
1437 entry.IsViewSourceMode());
1439 const NavigationEntry* current_entry =
1440 delegate_->GetLastCommittedNavigationEntryForRenderManager();
1442 if (new_instance.get() != current_instance) {
1443 // New SiteInstance: create a pending RFH to navigate.
1444 DCHECK(!cross_navigation_pending_);
1446 // This will possibly create (set to NULL) a Web UI object for the pending
1447 // page. We'll use this later to give the page special access. This must
1448 // happen before the new renderer is created below so it will get bindings.
1449 // It must also happen after the above conditional call to CancelPending(),
1450 // otherwise CancelPending may clear the pending_web_ui_ and the page will
1451 // not have its bindings set appropriately.
1452 SetPendingWebUI(entry);
1453 CreateRenderFrameHostForNewSiteInstance(
1454 current_instance, new_instance.get(), frame_tree_node_->IsMainFrame());
1455 if (!pending_render_frame_host_.get()) {
1456 return NULL;
1459 // Check if our current RFH is live before we set up a transition.
1460 if (!render_frame_host_->render_view_host()->IsRenderViewLive()) {
1461 if (!cross_navigation_pending_) {
1462 // The current RFH is not live. There's no reason to sit around with a
1463 // sad tab or a newly created RFH while we wait for the pending RFH to
1464 // navigate. Just switch to the pending RFH now and go back to non
1465 // cross-navigating (Note that we don't care about on{before}unload
1466 // handlers if the current RFH isn't live.)
1467 CommitPending();
1468 return render_frame_host_.get();
1469 } else {
1470 NOTREACHED();
1471 return render_frame_host_.get();
1474 // Otherwise, it's safe to treat this as a pending cross-site transition.
1476 // We need to wait until the beforeunload handler has run, unless we are
1477 // transferring an existing request (in which case it has already run).
1478 // Suspend the new render view (i.e., don't let it send the cross-site
1479 // Navigate message) until we hear back from the old renderer's
1480 // beforeunload handler. If the handler returns false, we'll have to
1481 // cancel the request.
1482 DCHECK(!pending_render_frame_host_->are_navigations_suspended());
1483 bool is_transfer =
1484 entry.transferred_global_request_id() != GlobalRequestID();
1485 if (is_transfer) {
1486 // We don't need to stop the old renderer or run beforeunload/unload
1487 // handlers, because those have already been done.
1488 DCHECK(cross_site_transferring_request_->request_id() ==
1489 entry.transferred_global_request_id());
1490 } else {
1491 // Also make sure the old render view stops, in case a load is in
1492 // progress. (We don't want to do this for transfers, since it will
1493 // interrupt the transfer with an unexpected DidStopLoading.)
1494 render_frame_host_->render_view_host()->Send(new ViewMsg_Stop(
1495 render_frame_host_->render_view_host()->GetRoutingID()));
1497 pending_render_frame_host_->SetNavigationsSuspended(true,
1498 base::TimeTicks());
1501 // We now have a pending RFH.
1502 DCHECK(!cross_navigation_pending_);
1503 cross_navigation_pending_ = true;
1505 // Unless we are transferring an existing request, we should now
1506 // tell the old render view to run its beforeunload handler, since it
1507 // doesn't otherwise know that the cross-site request is happening. This
1508 // will trigger a call to OnBeforeUnloadACK with the reply.
1509 if (!is_transfer)
1510 render_frame_host_->DispatchBeforeUnload(true);
1512 return pending_render_frame_host_.get();
1515 // Otherwise the same SiteInstance can be used. Navigate render_frame_host_.
1516 DCHECK(!cross_navigation_pending_);
1518 // It's possible to swap out the current RFH and then decide to navigate in it
1519 // anyway (e.g., a cross-process navigation that redirects back to the
1520 // original site). In that case, we have a proxy for the current RFH but
1521 // haven't deleted it yet. The new navigation will swap it back in, so we can
1522 // delete the proxy.
1523 DeleteRenderFrameProxyHost(new_instance.get());
1525 if (ShouldReuseWebUI(current_entry, &entry)) {
1526 pending_web_ui_.reset();
1527 pending_and_current_web_ui_ = web_ui_->AsWeakPtr();
1528 } else {
1529 SetPendingWebUI(entry);
1531 // Make sure the new RenderViewHost has the right bindings.
1532 if (pending_web_ui() &&
1533 !render_frame_host_->GetProcess()->IsIsolatedGuest()) {
1534 render_frame_host_->render_view_host()->AllowBindings(
1535 pending_web_ui()->GetBindings());
1539 if (pending_web_ui() &&
1540 render_frame_host_->render_view_host()->IsRenderViewLive()) {
1541 pending_web_ui()->GetController()->RenderViewReused(
1542 render_frame_host_->render_view_host());
1545 // The renderer can exit view source mode when any error or cancellation
1546 // happen. We must overwrite to recover the mode.
1547 if (entry.IsViewSourceMode()) {
1548 render_frame_host_->render_view_host()->Send(
1549 new ViewMsg_EnableViewSourceMode(
1550 render_frame_host_->render_view_host()->GetRoutingID()));
1553 return render_frame_host_.get();
1556 void RenderFrameHostManager::CancelPending() {
1557 scoped_ptr<RenderFrameHostImpl> pending_render_frame_host =
1558 pending_render_frame_host_.Pass();
1560 RenderViewDevToolsAgentHost::OnCancelPendingNavigation(
1561 pending_render_frame_host->render_view_host(),
1562 render_frame_host_->render_view_host());
1564 // We no longer need to prevent the process from exiting.
1565 pending_render_frame_host->GetProcess()->RemovePendingView();
1567 // If the SiteInstance for the pending RFH is being used by others, don't
1568 // delete the RFH, just swap it out and it can be reused at a later point.
1569 SiteInstanceImpl* site_instance = static_cast<SiteInstanceImpl*>(
1570 pending_render_frame_host->GetSiteInstance());
1571 if (site_instance->active_view_count() > 1) {
1572 // Any currently suspended navigations are no longer needed.
1573 pending_render_frame_host->CancelSuspendedNavigations();
1575 RenderFrameProxyHost* proxy =
1576 new RenderFrameProxyHost(site_instance, frame_tree_node_);
1577 proxy_hosts_[site_instance->GetId()] = proxy;
1578 pending_render_frame_host->SwapOut(proxy);
1579 if (frame_tree_node_->IsMainFrame())
1580 proxy->TakeFrameHostOwnership(pending_render_frame_host.Pass());
1581 } else {
1582 // We won't be coming back, so delete this one.
1583 pending_render_frame_host.reset();
1586 pending_web_ui_.reset();
1587 pending_and_current_web_ui_.reset();
1590 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::SetRenderFrameHost(
1591 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
1592 // Swap the two.
1593 scoped_ptr<RenderFrameHostImpl> old_render_frame_host =
1594 render_frame_host_.Pass();
1595 render_frame_host_ = render_frame_host.Pass();
1597 if (frame_tree_node_->IsMainFrame()) {
1598 // Update the count of top-level frames using this SiteInstance. All
1599 // subframes are in the same BrowsingInstance as the main frame, so we only
1600 // count top-level ones. This makes the value easier for consumers to
1601 // interpret.
1602 if (render_frame_host_) {
1603 static_cast<SiteInstanceImpl*>(render_frame_host_->GetSiteInstance())->
1604 IncrementRelatedActiveContentsCount();
1606 if (old_render_frame_host) {
1607 static_cast<SiteInstanceImpl*>(old_render_frame_host->GetSiteInstance())->
1608 DecrementRelatedActiveContentsCount();
1612 return old_render_frame_host.Pass();
1615 bool RenderFrameHostManager::IsRVHOnSwappedOutList(
1616 RenderViewHostImpl* rvh) const {
1617 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(
1618 rvh->GetSiteInstance());
1619 if (!proxy)
1620 return false;
1621 // If there is a proxy without RFH, it is for a subframe in the SiteInstance
1622 // of |rvh|. Subframes should be ignored in this case.
1623 if (!proxy->render_frame_host())
1624 return false;
1625 return IsOnSwappedOutList(proxy->render_frame_host());
1628 bool RenderFrameHostManager::IsOnSwappedOutList(
1629 RenderFrameHostImpl* rfh) const {
1630 if (!rfh->GetSiteInstance())
1631 return false;
1633 RenderFrameProxyHostMap::const_iterator iter = proxy_hosts_.find(
1634 rfh->GetSiteInstance()->GetId());
1635 if (iter == proxy_hosts_.end())
1636 return false;
1638 return iter->second->render_frame_host() == rfh;
1641 RenderViewHostImpl* RenderFrameHostManager::GetSwappedOutRenderViewHost(
1642 SiteInstance* instance) const {
1643 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1644 if (proxy)
1645 return proxy->GetRenderViewHost();
1646 return NULL;
1649 RenderFrameProxyHost* RenderFrameHostManager::GetRenderFrameProxyHost(
1650 SiteInstance* instance) const {
1651 RenderFrameProxyHostMap::const_iterator iter =
1652 proxy_hosts_.find(instance->GetId());
1653 if (iter != proxy_hosts_.end())
1654 return iter->second;
1656 return NULL;
1659 void RenderFrameHostManager::DeleteRenderFrameProxyHost(
1660 SiteInstance* instance) {
1661 RenderFrameProxyHostMap::iterator iter = proxy_hosts_.find(instance->GetId());
1662 if (iter != proxy_hosts_.end()) {
1663 delete iter->second;
1664 proxy_hosts_.erase(iter);
1668 } // namespace content