OOPIF: Data URLs are now rendered in the renderer that initiated the navigation.
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_manager.cc
blob615bc712ec2f92ec5ca1d915be695234f8757b3e
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_controller_impl.h"
19 #include "content/browser/frame_host/navigation_entry_impl.h"
20 #include "content/browser/frame_host/navigator.h"
21 #include "content/browser/frame_host/render_frame_host_factory.h"
22 #include "content/browser/frame_host/render_frame_host_impl.h"
23 #include "content/browser/frame_host/render_frame_proxy_host.h"
24 #include "content/browser/renderer_host/render_process_host_impl.h"
25 #include "content/browser/renderer_host/render_view_host_factory.h"
26 #include "content/browser/renderer_host/render_view_host_impl.h"
27 #include "content/browser/site_instance_impl.h"
28 #include "content/browser/webui/web_ui_controller_factory_registry.h"
29 #include "content/browser/webui/web_ui_impl.h"
30 #include "content/common/frame_messages.h"
31 #include "content/common/view_messages.h"
32 #include "content/public/browser/content_browser_client.h"
33 #include "content/public/browser/notification_service.h"
34 #include "content/public/browser/notification_types.h"
35 #include "content/public/browser/render_widget_host_iterator.h"
36 #include "content/public/browser/render_widget_host_view.h"
37 #include "content/public/browser/user_metrics.h"
38 #include "content/public/browser/web_ui_controller.h"
39 #include "content/public/common/content_switches.h"
40 #include "content/public/common/referrer.h"
41 #include "content/public/common/url_constants.h"
43 namespace content {
45 // static
46 bool RenderFrameHostManager::ClearRFHsPendingShutdown(FrameTreeNode* node) {
47 node->render_manager()->pending_delete_hosts_.clear();
48 return true;
51 RenderFrameHostManager::RenderFrameHostManager(
52 FrameTreeNode* frame_tree_node,
53 RenderFrameHostDelegate* render_frame_delegate,
54 RenderViewHostDelegate* render_view_delegate,
55 RenderWidgetHostDelegate* render_widget_delegate,
56 Delegate* delegate)
57 : frame_tree_node_(frame_tree_node),
58 delegate_(delegate),
59 cross_navigation_pending_(false),
60 render_frame_delegate_(render_frame_delegate),
61 render_view_delegate_(render_view_delegate),
62 render_widget_delegate_(render_widget_delegate),
63 interstitial_page_(NULL),
64 weak_factory_(this) {
65 DCHECK(frame_tree_node_);
68 RenderFrameHostManager::~RenderFrameHostManager() {
69 if (pending_render_frame_host_)
70 UnsetPendingRenderFrameHost();
72 // We should always have a current RenderFrameHost except in some tests.
73 SetRenderFrameHost(scoped_ptr<RenderFrameHostImpl>());
75 // Delete any swapped out RenderFrameHosts.
76 STLDeleteValues(&proxy_hosts_);
79 void RenderFrameHostManager::Init(BrowserContext* browser_context,
80 SiteInstance* site_instance,
81 int view_routing_id,
82 int frame_routing_id) {
83 // Create a RenderViewHost and RenderFrameHost, once we have an instance. It
84 // is important to immediately give this SiteInstance to a RenderViewHost so
85 // that the SiteInstance is ref counted.
86 if (!site_instance)
87 site_instance = SiteInstance::Create(browser_context);
89 int flags = delegate_->IsHidden() ? CREATE_RF_HIDDEN : 0;
90 SetRenderFrameHost(CreateRenderFrameHost(site_instance, view_routing_id,
91 frame_routing_id, flags));
93 // Keep track of renderer processes as they start to shut down or are
94 // crashed/killed.
95 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSED,
96 NotificationService::AllSources());
97 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSING,
98 NotificationService::AllSources());
101 RenderViewHostImpl* RenderFrameHostManager::current_host() const {
102 if (!render_frame_host_)
103 return NULL;
104 return render_frame_host_->render_view_host();
107 RenderViewHostImpl* RenderFrameHostManager::pending_render_view_host() const {
108 if (!pending_render_frame_host_)
109 return NULL;
110 return pending_render_frame_host_->render_view_host();
113 RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const {
114 if (interstitial_page_)
115 return interstitial_page_->GetView();
116 if (!render_frame_host_)
117 return NULL;
118 return render_frame_host_->render_view_host()->GetView();
121 RenderFrameProxyHost* RenderFrameHostManager::GetProxyToParent() {
122 if (frame_tree_node_->IsMainFrame())
123 return NULL;
125 RenderFrameProxyHostMap::iterator iter =
126 proxy_hosts_.find(frame_tree_node_->parent()
127 ->render_manager()
128 ->current_frame_host()
129 ->GetSiteInstance()
130 ->GetId());
131 if (iter == proxy_hosts_.end())
132 return NULL;
134 return iter->second;
137 void RenderFrameHostManager::SetPendingWebUI(const GURL& url, int bindings) {
138 pending_web_ui_ = CreateWebUI(url, bindings);
139 pending_and_current_web_ui_.reset();
142 scoped_ptr<WebUIImpl> RenderFrameHostManager::CreateWebUI(const GURL& url,
143 int bindings) {
144 scoped_ptr<WebUIImpl> new_web_ui(delegate_->CreateWebUIForRenderManager(url));
146 // If we have assigned (zero or more) bindings to this NavigationEntry in the
147 // past, make sure we're not granting it different bindings than it had
148 // before. If so, note it and don't give it any bindings, to avoid a
149 // potential privilege escalation.
150 if (new_web_ui && bindings != NavigationEntryImpl::kInvalidBindings &&
151 new_web_ui->GetBindings() != bindings) {
152 RecordAction(base::UserMetricsAction("ProcessSwapBindingsMismatch_RVHM"));
153 return nullptr;
155 return new_web_ui.Pass();
158 RenderFrameHostImpl* RenderFrameHostManager::Navigate(
159 const NavigationEntryImpl& entry) {
160 TRACE_EVENT1("navigation", "RenderFrameHostManager:Navigate",
161 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
162 // Create a pending RenderFrameHost to use for the navigation.
163 RenderFrameHostImpl* dest_render_frame_host = UpdateStateForNavigate(
164 entry.GetURL(), entry.source_site_instance(), entry.site_instance(),
165 entry.GetTransitionType(),
166 entry.restore_type() != NavigationEntryImpl::RESTORE_NONE,
167 entry.IsViewSourceMode(), entry.transferred_global_request_id(),
168 entry.bindings());
169 if (!dest_render_frame_host)
170 return NULL; // We weren't able to create a pending render frame host.
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_->IsRenderFrameLive()) {
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());
184 // If the renderer crashed, then try to create a new one to satisfy this
185 // navigation request.
186 if (!dest_render_frame_host->IsRenderFrameLive()) {
187 // Instruct the destination render frame host to set up a Mojo connection
188 // with the new render frame if necessary. Note that this call needs to
189 // occur before initializing the RenderView; the flow of creating the
190 // RenderView can cause browser-side code to execute that expects the this
191 // RFH's ServiceRegistry to be initialized (e.g., if the site is a WebUI
192 // site that is handled via Mojo, then Mojo WebUI code in //chrome will
193 // add a service to this RFH's ServiceRegistry).
194 dest_render_frame_host->SetUpMojoIfNeeded();
196 // Recreate the opener chain.
197 int opener_route_id = delegate_->CreateOpenerRenderViewsForRenderManager(
198 dest_render_frame_host->GetSiteInstance());
199 if (!InitRenderView(dest_render_frame_host->render_view_host(),
200 opener_route_id,
201 MSG_ROUTING_NONE,
202 frame_tree_node_->IsMainFrame()))
203 return NULL;
205 // Now that we've created a new renderer, be sure to hide it if it isn't
206 // our primary one. Otherwise, we might crash if we try to call Show()
207 // on it later.
208 if (dest_render_frame_host != render_frame_host_ &&
209 dest_render_frame_host->render_view_host()->GetView()) {
210 dest_render_frame_host->render_view_host()->GetView()->Hide();
211 } else {
212 // Notify here as we won't be calling CommitPending (which does the
213 // notify).
214 delegate_->NotifySwappedFromRenderManager(
215 NULL, render_frame_host_.get(), frame_tree_node_->IsMainFrame());
219 // If entry includes the request ID of a request that is being transferred,
220 // the destination render frame will take ownership, so release ownership of
221 // the request.
222 if (cross_site_transferring_request_.get() &&
223 cross_site_transferring_request_->request_id() ==
224 entry.transferred_global_request_id()) {
225 cross_site_transferring_request_->ReleaseRequest();
228 return dest_render_frame_host;
231 void RenderFrameHostManager::Stop() {
232 render_frame_host_->Stop();
234 // If we are cross-navigating, we should stop the pending renderers. This
235 // will lead to a DidFailProvisionalLoad, which will properly destroy them.
236 if (cross_navigation_pending_) {
237 pending_render_frame_host_->Send(new FrameMsg_Stop(
238 pending_render_frame_host_->GetRoutingID()));
242 void RenderFrameHostManager::SetIsLoading(bool is_loading) {
243 render_frame_host_->render_view_host()->SetIsLoading(is_loading);
244 if (pending_render_frame_host_)
245 pending_render_frame_host_->render_view_host()->SetIsLoading(is_loading);
248 bool RenderFrameHostManager::ShouldCloseTabOnUnresponsiveRenderer() {
249 // If we're waiting for a close ACK, then the tab should close whether there's
250 // a navigation in progress or not. Unfortunately, we also need to check for
251 // cases that we arrive here with no navigation in progress, since there are
252 // some tab closure paths that don't set is_waiting_for_close_ack to true.
253 // TODO(creis): Clean this up in http://crbug.com/418266.
254 if (!cross_navigation_pending_ ||
255 render_frame_host_->render_view_host()->is_waiting_for_close_ack())
256 return true;
258 // We should always have a pending RFH when there's a cross-process navigation
259 // in progress. Sanity check this for http://crbug.com/276333.
260 CHECK(pending_render_frame_host_);
262 // Unload handlers run in the background, so we should never get an
263 // unresponsiveness warning for them.
264 CHECK(!render_frame_host_->IsWaitingForUnloadACK());
266 // If the tab becomes unresponsive during beforeunload while doing a
267 // cross-site navigation, proceed with the navigation. (This assumes that
268 // the pending RenderFrameHost is still responsive.)
269 if (render_frame_host_->is_waiting_for_beforeunload_ack()) {
270 // Haven't gotten around to starting the request, because we're still
271 // waiting for the beforeunload handler to finish. We'll pretend that it
272 // did finish, to let the navigation proceed. Note that there's a danger
273 // that the beforeunload handler will later finish and possibly return
274 // false (meaning the navigation should not proceed), but we'll ignore it
275 // in this case because it took too long.
276 if (pending_render_frame_host_->are_navigations_suspended()) {
277 pending_render_frame_host_->SetNavigationsSuspended(
278 false, base::TimeTicks::Now());
281 return false;
284 void RenderFrameHostManager::OnBeforeUnloadACK(
285 bool for_cross_site_transition,
286 bool proceed,
287 const base::TimeTicks& proceed_time) {
288 if (for_cross_site_transition) {
289 // Ignore if we're not in a cross-site navigation.
290 if (!cross_navigation_pending_)
291 return;
293 if (proceed) {
294 // Ok to unload the current page, so proceed with the cross-site
295 // navigation. Note that if navigations are not currently suspended, it
296 // might be because the renderer was deemed unresponsive and this call was
297 // already made by ShouldCloseTabOnUnresponsiveRenderer. In that case, it
298 // is ok to do nothing here.
299 if (pending_render_frame_host_ &&
300 pending_render_frame_host_->are_navigations_suspended()) {
301 pending_render_frame_host_->SetNavigationsSuspended(false,
302 proceed_time);
304 } else {
305 // Current page says to cancel.
306 CancelPending();
307 cross_navigation_pending_ = false;
309 } else {
310 // Non-cross site transition means closing the entire tab.
311 bool proceed_to_fire_unload;
312 delegate_->BeforeUnloadFiredFromRenderManager(proceed, proceed_time,
313 &proceed_to_fire_unload);
315 if (proceed_to_fire_unload) {
316 // If we're about to close the tab and there's a pending RFH, cancel it.
317 // Otherwise, if the navigation in the pending RFH completes before the
318 // close in the current RFH, we'll lose the tab close.
319 if (pending_render_frame_host_) {
320 CancelPending();
321 cross_navigation_pending_ = false;
324 // This is not a cross-site navigation, the tab is being closed.
325 render_frame_host_->render_view_host()->ClosePage();
330 void RenderFrameHostManager::OnCrossSiteResponse(
331 RenderFrameHostImpl* pending_render_frame_host,
332 const GlobalRequestID& global_request_id,
333 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
334 const std::vector<GURL>& transfer_url_chain,
335 const Referrer& referrer,
336 ui::PageTransition page_transition,
337 bool should_replace_current_entry) {
338 // We should only get here for transfer navigations. Most cross-process
339 // navigations can just continue and wait to run the unload handler (by
340 // swapping out) when the new navigation commits.
341 CHECK(cross_site_transferring_request.get());
343 // A transfer should only have come from our pending or current RFH.
344 // TODO(creis): We need to handle the case that the pending RFH has changed
345 // in the mean time, while this was being posted from the IO thread. We
346 // should probably cancel the request in that case.
347 DCHECK(pending_render_frame_host == pending_render_frame_host_ ||
348 pending_render_frame_host == render_frame_host_);
350 // Store the transferring request so that we can release it if the transfer
351 // navigation matches.
352 cross_site_transferring_request_ = cross_site_transferring_request.Pass();
354 // Sanity check that the params are for the correct frame and process.
355 // These should match the RenderFrameHost that made the request.
356 // If it started as a cross-process navigation via OpenURL, this is the
357 // pending one. If it wasn't cross-process until the transfer, this is the
358 // current one.
359 int render_frame_id = pending_render_frame_host_ ?
360 pending_render_frame_host_->GetRoutingID() :
361 render_frame_host_->GetRoutingID();
362 DCHECK_EQ(render_frame_id, pending_render_frame_host->GetRoutingID());
363 int process_id = pending_render_frame_host_ ?
364 pending_render_frame_host_->GetProcess()->GetID() :
365 render_frame_host_->GetProcess()->GetID();
366 DCHECK_EQ(process_id, global_request_id.child_id);
368 // Treat the last URL in the chain as the destination and the remainder as
369 // the redirect chain.
370 CHECK(transfer_url_chain.size());
371 GURL transfer_url = transfer_url_chain.back();
372 std::vector<GURL> rest_of_chain = transfer_url_chain;
373 rest_of_chain.pop_back();
375 // We don't know whether the original request had |user_action| set to true.
376 // However, since we force the navigation to be in the current tab, it
377 // doesn't matter.
378 pending_render_frame_host->frame_tree_node()->navigator()->RequestTransferURL(
379 pending_render_frame_host, transfer_url, nullptr, rest_of_chain, referrer,
380 page_transition, CURRENT_TAB, global_request_id,
381 should_replace_current_entry, true);
383 // The transferring request was only needed during the RequestTransferURL
384 // call, so it is safe to clear at this point.
385 cross_site_transferring_request_.reset();
388 void RenderFrameHostManager::OnDeferredAfterResponseStarted(
389 const GlobalRequestID& global_request_id,
390 RenderFrameHostImpl* pending_render_frame_host) {
391 DCHECK(!response_started_id_.get());
393 response_started_id_.reset(new GlobalRequestID(global_request_id));
396 void RenderFrameHostManager::ResumeResponseDeferredAtStart() {
397 DCHECK(response_started_id_.get());
399 RenderProcessHostImpl* process =
400 static_cast<RenderProcessHostImpl*>(render_frame_host_->GetProcess());
401 process->ResumeResponseDeferredAtStart(*response_started_id_);
403 render_frame_host_->ClearPendingTransitionRequestData();
405 response_started_id_.reset();
408 void RenderFrameHostManager::ClearNavigationTransitionData() {
409 render_frame_host_->ClearPendingTransitionRequestData();
412 void RenderFrameHostManager::DidNavigateFrame(
413 RenderFrameHostImpl* render_frame_host,
414 bool was_caused_by_user_gesture) {
415 if (!cross_navigation_pending_) {
416 DCHECK(!pending_render_frame_host_);
418 // We should only hear this from our current renderer.
419 DCHECK_EQ(render_frame_host_, render_frame_host);
421 // Even when there is no pending RVH, there may be a pending Web UI.
422 if (pending_web_ui())
423 CommitPending();
424 return;
427 if (render_frame_host == pending_render_frame_host_) {
428 // The pending cross-site navigation completed, so show the renderer.
429 CommitPending();
430 cross_navigation_pending_ = false;
431 } else if (render_frame_host == render_frame_host_) {
432 if (was_caused_by_user_gesture) {
433 // A navigation in the original page has taken place. Cancel the pending
434 // one. Only do it for user gesture originated navigations to prevent
435 // page doing any shenanigans to prevent user from navigating.
436 // See https://code.google.com/p/chromium/issues/detail?id=75195
437 CancelPending();
438 cross_navigation_pending_ = false;
440 } else {
441 // No one else should be sending us DidNavigate in this state.
442 DCHECK(false);
446 void RenderFrameHostManager::DidDisownOpener(
447 RenderFrameHost* render_frame_host) {
448 // Notify all RenderFrameHosts but the one that notified us. This is necessary
449 // in case a process swap has occurred while the message was in flight.
450 for (RenderFrameProxyHostMap::iterator iter = proxy_hosts_.begin();
451 iter != proxy_hosts_.end();
452 ++iter) {
453 DCHECK_NE(iter->second->GetSiteInstance(),
454 current_frame_host()->GetSiteInstance());
455 iter->second->DisownOpener();
458 if (render_frame_host_.get() != render_frame_host)
459 render_frame_host_->DisownOpener();
461 if (pending_render_frame_host_ &&
462 pending_render_frame_host_.get() != render_frame_host) {
463 pending_render_frame_host_->DisownOpener();
467 void RenderFrameHostManager::RendererProcessClosing(
468 RenderProcessHost* render_process_host) {
469 // Remove any swapped out RVHs from this process, so that we don't try to
470 // swap them back in while the process is exiting. Start by finding them,
471 // since there could be more than one.
472 std::list<int> ids_to_remove;
473 for (RenderFrameProxyHostMap::iterator iter = proxy_hosts_.begin();
474 iter != proxy_hosts_.end();
475 ++iter) {
476 if (iter->second->GetProcess() == render_process_host)
477 ids_to_remove.push_back(iter->first);
480 // Now delete them.
481 while (!ids_to_remove.empty()) {
482 delete proxy_hosts_[ids_to_remove.back()];
483 proxy_hosts_.erase(ids_to_remove.back());
484 ids_to_remove.pop_back();
488 void RenderFrameHostManager::SwapOutOldFrame(
489 scoped_ptr<RenderFrameHostImpl> old_render_frame_host) {
490 TRACE_EVENT1("navigation", "RenderFrameHostManager::SwapOutOldFrame",
491 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
493 // Tell the renderer to suppress any further modal dialogs so that we can swap
494 // it out. This must be done before canceling any current dialog, in case
495 // there is a loop creating additional dialogs.
496 // TODO(creis): Handle modal dialogs in subframe processes.
497 old_render_frame_host->render_view_host()->SuppressDialogsUntilSwapOut();
499 // Now close any modal dialogs that would prevent us from swapping out. This
500 // must be done separately from SwapOut, so that the PageGroupLoadDeferrer is
501 // no longer on the stack when we send the SwapOut message.
502 delegate_->CancelModalDialogsForRenderManager();
504 // If the old RFH is not live, just return as there is no further work to do.
505 // It will be deleted and there will be no proxy created.
506 int32 old_site_instance_id =
507 old_render_frame_host->GetSiteInstance()->GetId();
508 if (!old_render_frame_host->IsRenderFrameLive()) {
509 ShutdownRenderFrameProxyHostsInSiteInstance(old_site_instance_id);
510 return;
513 // If there are no active frames besides this one, we can delete the old
514 // RenderFrameHost once it runs its unload handler, without replacing it with
515 // a proxy.
516 size_t active_frame_count =
517 old_render_frame_host->GetSiteInstance()->active_frame_count();
518 if (active_frame_count <= 1) {
519 // Tell the old RenderFrameHost to swap out, with no proxy to replace it.
520 old_render_frame_host->SwapOut(NULL);
521 MoveToPendingDeleteHosts(old_render_frame_host.Pass());
523 // Also clear out any proxies from this SiteInstance, in case this was the
524 // last one keeping other proxies alive.
525 ShutdownRenderFrameProxyHostsInSiteInstance(old_site_instance_id);
527 return;
530 // Otherwise there are active views and we need a proxy for the old RFH.
531 // (There should not be one yet.)
532 CHECK(!GetRenderFrameProxyHost(old_render_frame_host->GetSiteInstance()));
533 RenderFrameProxyHost* proxy = new RenderFrameProxyHost(
534 old_render_frame_host->GetSiteInstance(), frame_tree_node_);
535 CHECK(proxy_hosts_.insert(std::make_pair(old_site_instance_id, proxy)).second)
536 << "Inserting a duplicate item.";
538 // Tell the old RenderFrameHost to swap out and be replaced by the proxy.
539 old_render_frame_host->SwapOut(proxy);
541 bool is_main_frame = frame_tree_node_->IsMainFrame();
542 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess) &&
543 !is_main_frame) {
544 // In --site-per-process, subframes delete their RFH rather than storing it
545 // in the proxy. Schedule it for deletion once the SwapOutACK comes in.
546 // TODO(creis): This will be the default when we remove swappedout://.
547 MoveToPendingDeleteHosts(old_render_frame_host.Pass());
548 } else {
549 // We shouldn't get here for subframes, since we only swap subframes when
550 // --site-per-process is used.
551 DCHECK(is_main_frame);
553 // The old RenderFrameHost will stay alive inside the proxy so that existing
554 // JavaScript window references to it stay valid.
555 proxy->TakeFrameHostOwnership(old_render_frame_host.Pass());
559 void RenderFrameHostManager::DiscardUnusedFrame(
560 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
561 // TODO(carlosk): this code is very similar to what can be found in
562 // SwapOutOldFrame and we should see that these are unified at some point.
564 // If the SiteInstance for the pending RFH is being used by others don't
565 // delete the RFH. Just swap it out and it can be reused at a later point.
566 SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance();
567 if (site_instance->HasSite() && site_instance->active_frame_count() > 1) {
568 // Any currently suspended navigations are no longer needed.
569 render_frame_host->CancelSuspendedNavigations();
571 RenderFrameProxyHost* proxy =
572 new RenderFrameProxyHost(site_instance, frame_tree_node_);
573 proxy_hosts_[site_instance->GetId()] = proxy;
574 render_frame_host->SwapOut(proxy);
575 if (frame_tree_node_->IsMainFrame())
576 proxy->TakeFrameHostOwnership(render_frame_host.Pass());
577 } else {
578 // We won't be coming back, so delete this one.
579 render_frame_host.reset();
583 void RenderFrameHostManager::MoveToPendingDeleteHosts(
584 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
585 // |render_frame_host| will be deleted when its SwapOut ACK is received, or
586 // when the timer times out, or when the RFHM itself is deleted (whichever
587 // comes first).
588 pending_delete_hosts_.push_back(
589 linked_ptr<RenderFrameHostImpl>(render_frame_host.release()));
592 bool RenderFrameHostManager::IsPendingDeletion(
593 RenderFrameHostImpl* render_frame_host) {
594 for (const auto& rfh : pending_delete_hosts_) {
595 if (rfh == render_frame_host)
596 return true;
598 return false;
601 bool RenderFrameHostManager::DeleteFromPendingList(
602 RenderFrameHostImpl* render_frame_host) {
603 for (RFHPendingDeleteList::iterator iter = pending_delete_hosts_.begin();
604 iter != pending_delete_hosts_.end();
605 iter++) {
606 if (*iter == render_frame_host) {
607 pending_delete_hosts_.erase(iter);
608 return true;
611 return false;
614 void RenderFrameHostManager::ResetProxyHosts() {
615 STLDeleteValues(&proxy_hosts_);
618 // PlzNavigate
619 RenderFrameHostImpl* RenderFrameHostManager::GetFrameHostForNavigation(
620 const GURL& url,
621 ui::PageTransition transition) {
622 CHECK(CommandLine::ForCurrentProcess()->HasSwitch(
623 switches::kEnableBrowserSideNavigation));
624 // TODO(clamy): When we handle renderer initiated navigations, make sure not
625 // to use a different process for subframes if --site-per-process is not
626 // enabled.
628 // Pick the right RenderFrameHost to commit the navigation.
629 // TODO(clamy): Replace the default values by the right ones.
630 RenderFrameHostImpl* render_frame_host = UpdateStateForNavigate(
631 url, nullptr, nullptr, transition, false, false, GlobalRequestID(),
632 NavigationEntryImpl::kInvalidBindings);
634 // If the renderer that needs to navigate is not live (it was just created or
635 // it crashed), initialize it.
636 if (!render_frame_host->render_view_host()->IsRenderViewLive()) {
637 // Recreate the opener chain.
638 int opener_route_id = delegate_->CreateOpenerRenderViewsForRenderManager(
639 render_frame_host->GetSiteInstance());
640 if (!InitRenderView(render_frame_host->render_view_host(),
641 opener_route_id,
642 MSG_ROUTING_NONE,
643 frame_tree_node_->IsMainFrame())) {
644 return nullptr;
647 return render_frame_host;
650 void RenderFrameHostManager::Observe(
651 int type,
652 const NotificationSource& source,
653 const NotificationDetails& details) {
654 switch (type) {
655 case NOTIFICATION_RENDERER_PROCESS_CLOSED:
656 case NOTIFICATION_RENDERER_PROCESS_CLOSING:
657 RendererProcessClosing(
658 Source<RenderProcessHost>(source).ptr());
659 break;
661 default:
662 NOTREACHED();
666 // static
667 bool RenderFrameHostManager::ClearProxiesInSiteInstance(
668 int32 site_instance_id,
669 FrameTreeNode* node) {
670 RenderFrameProxyHostMap::iterator iter =
671 node->render_manager()->proxy_hosts_.find(site_instance_id);
672 if (iter != node->render_manager()->proxy_hosts_.end()) {
673 RenderFrameProxyHost* proxy = iter->second;
674 // Delete the proxy. If it is for a main frame (and thus the RFH is stored
675 // in the proxy) and it was still pending swap out, move the RFH to the
676 // pending deletion list first.
677 if (node->IsMainFrame() &&
678 proxy->render_frame_host()->rfh_state() ==
679 RenderFrameHostImpl::STATE_PENDING_SWAP_OUT) {
680 scoped_ptr<RenderFrameHostImpl> swapped_out_rfh =
681 proxy->PassFrameHostOwnership();
682 node->render_manager()->MoveToPendingDeleteHosts(swapped_out_rfh.Pass());
684 delete proxy;
685 node->render_manager()->proxy_hosts_.erase(site_instance_id);
688 return true;
691 bool RenderFrameHostManager::ShouldTransitionCrossSite() {
692 // False in the single-process mode, as it makes RVHs to accumulate
693 // in swapped_out_hosts_.
694 // True if we are using process-per-site-instance (default) or
695 // process-per-site (kProcessPerSite).
696 return
697 !CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess) &&
698 !CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessPerTab);
701 bool RenderFrameHostManager::ShouldSwapBrowsingInstancesForNavigation(
702 const GURL& current_effective_url,
703 bool current_is_view_source_mode,
704 SiteInstance* new_site_instance,
705 const GURL& new_effective_url,
706 bool new_is_view_source_mode) const {
707 // If new_entry already has a SiteInstance, assume it is correct. We only
708 // need to force a swap if it is in a different BrowsingInstance.
709 if (new_site_instance) {
710 return !new_site_instance->IsRelatedSiteInstance(
711 render_frame_host_->GetSiteInstance());
714 // Check for reasons to swap processes even if we are in a process model that
715 // doesn't usually swap (e.g., process-per-tab). Any time we return true,
716 // the new_entry will be rendered in a new SiteInstance AND BrowsingInstance.
717 BrowserContext* browser_context =
718 delegate_->GetControllerForRenderManager().GetBrowserContext();
720 // Don't force a new BrowsingInstance for debug URLs that are handled in the
721 // renderer process, like javascript: or chrome://crash.
722 if (IsRendererDebugURL(new_effective_url))
723 return false;
725 // For security, we should transition between processes when one is a Web UI
726 // page and one isn't.
727 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
728 render_frame_host_->GetProcess()->GetID()) ||
729 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
730 browser_context, current_effective_url)) {
731 // If so, force a swap if destination is not an acceptable URL for Web UI.
732 // Here, data URLs are never allowed.
733 if (!WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
734 browser_context, new_effective_url)) {
735 return true;
737 } else {
738 // Force a swap if it's a Web UI URL.
739 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
740 browser_context, new_effective_url)) {
741 return true;
745 // Check with the content client as well. Important to pass
746 // current_effective_url here, which uses the SiteInstance's site if there is
747 // no current_entry.
748 if (GetContentClient()->browser()->ShouldSwapBrowsingInstancesForNavigation(
749 render_frame_host_->GetSiteInstance(),
750 current_effective_url, new_effective_url)) {
751 return true;
754 // We can't switch a RenderView between view source and non-view source mode
755 // without screwing up the session history sometimes (when navigating between
756 // "view-source:http://foo.com/" and "http://foo.com/", Blink doesn't treat
757 // it as a new navigation). So require a BrowsingInstance switch.
758 if (current_is_view_source_mode != new_is_view_source_mode)
759 return true;
761 return false;
764 bool RenderFrameHostManager::ShouldReuseWebUI(
765 const NavigationEntry* current_entry,
766 const GURL& new_url) const {
767 NavigationControllerImpl& controller =
768 delegate_->GetControllerForRenderManager();
769 return current_entry && web_ui_.get() &&
770 (WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
771 controller.GetBrowserContext(), current_entry->GetURL()) ==
772 WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
773 controller.GetBrowserContext(), new_url));
776 SiteInstance* RenderFrameHostManager::GetSiteInstanceForNavigation(
777 const GURL& dest_url,
778 SiteInstance* source_instance,
779 SiteInstance* dest_instance,
780 ui::PageTransition transition,
781 bool dest_is_restore,
782 bool dest_is_view_source_mode) {
783 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
784 SiteInstance* new_instance = current_instance;
786 // We do not currently swap processes for navigations in webview tag guests.
787 if (current_instance->GetSiteURL().SchemeIs(kGuestScheme))
788 return current_instance;
790 // Determine if we need a new BrowsingInstance for this entry. If true, this
791 // implies that it will get a new SiteInstance (and likely process), and that
792 // other tabs in the current BrowsingInstance will be unable to script it.
793 // This is used for cases that require a process swap even in the
794 // process-per-tab model, such as WebUI pages.
795 // TODO(clamy): Remove the dependency on the current entry.
796 const NavigationEntry* current_entry =
797 delegate_->GetLastCommittedNavigationEntryForRenderManager();
798 BrowserContext* browser_context =
799 delegate_->GetControllerForRenderManager().GetBrowserContext();
800 const GURL& current_effective_url = current_entry ?
801 SiteInstanceImpl::GetEffectiveURL(browser_context,
802 current_entry->GetURL()) :
803 render_frame_host_->GetSiteInstance()->GetSiteURL();
804 bool current_is_view_source_mode = current_entry ?
805 current_entry->IsViewSourceMode() : dest_is_view_source_mode;
806 bool force_swap = ShouldSwapBrowsingInstancesForNavigation(
807 current_effective_url,
808 current_is_view_source_mode,
809 dest_instance,
810 SiteInstanceImpl::GetEffectiveURL(browser_context, dest_url),
811 dest_is_view_source_mode);
812 if (ShouldTransitionCrossSite() || force_swap) {
813 new_instance = GetSiteInstanceForURL(
814 dest_url, source_instance, current_instance, dest_instance,
815 transition, dest_is_restore, dest_is_view_source_mode, force_swap);
818 // If force_swap is true, we must use a different SiteInstance. If we didn't,
819 // we would have two RenderFrameHosts in the same SiteInstance and the same
820 // frame, resulting in page_id conflicts for their NavigationEntries.
821 if (force_swap)
822 CHECK_NE(new_instance, current_instance);
823 return new_instance;
826 SiteInstance* RenderFrameHostManager::GetSiteInstanceForURL(
827 const GURL& dest_url,
828 SiteInstance* source_instance,
829 SiteInstance* current_instance,
830 SiteInstance* dest_instance,
831 ui::PageTransition transition,
832 bool dest_is_restore,
833 bool dest_is_view_source_mode,
834 bool force_browsing_instance_swap) {
835 NavigationControllerImpl& controller =
836 delegate_->GetControllerForRenderManager();
837 BrowserContext* browser_context = controller.GetBrowserContext();
839 // If the entry has an instance already we should use it.
840 if (dest_instance) {
841 // If we are forcing a swap, this should be in a different BrowsingInstance.
842 if (force_browsing_instance_swap) {
843 CHECK(!dest_instance->IsRelatedSiteInstance(
844 render_frame_host_->GetSiteInstance()));
846 return dest_instance;
849 // If a swap is required, we need to force the SiteInstance AND
850 // BrowsingInstance to be different ones, using CreateForURL.
851 if (force_browsing_instance_swap)
852 return SiteInstance::CreateForURL(browser_context, dest_url);
854 // (UGLY) HEURISTIC, process-per-site only:
856 // If this navigation is generated, then it probably corresponds to a search
857 // query. Given that search results typically lead to users navigating to
858 // other sites, we don't really want to use the search engine hostname to
859 // determine the site instance for this navigation.
861 // NOTE: This can be removed once we have a way to transition between
862 // RenderViews in response to a link click.
864 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessPerSite) &&
865 ui::PageTransitionCoreTypeIs(
866 transition, ui::PAGE_TRANSITION_GENERATED)) {
867 return current_instance;
870 SiteInstanceImpl* current_site_instance =
871 static_cast<SiteInstanceImpl*>(current_instance);
873 // If we haven't used our SiteInstance (and thus RVH) yet, then we can use it
874 // for this entry. We won't commit the SiteInstance to this site until the
875 // navigation commits (in DidNavigate), unless the navigation entry was
876 // restored or it's a Web UI as described below.
877 if (!current_site_instance->HasSite()) {
878 // If we've already created a SiteInstance for our destination, we don't
879 // want to use this unused SiteInstance; use the existing one. (We don't
880 // do this check if the current_instance has a site, because for now, we
881 // want to compare against the current URL and not the SiteInstance's site.
882 // In this case, there is no current URL, so comparing against the site is
883 // ok. See additional comments below.)
885 // Also, if the URL should use process-per-site mode and there is an
886 // existing process for the site, we should use it. We can call
887 // GetRelatedSiteInstance() for this, which will eagerly set the site and
888 // thus use the correct process.
889 bool use_process_per_site =
890 RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) &&
891 RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url);
892 if (current_site_instance->HasRelatedSiteInstance(dest_url) ||
893 use_process_per_site) {
894 return current_site_instance->GetRelatedSiteInstance(dest_url);
897 // For extensions, Web UI URLs (such as the new tab page), and apps we do
898 // not want to use the current_instance if it has no site, since it will
899 // have a RenderProcessHost of PRIV_NORMAL. Create a new SiteInstance for
900 // this URL instead (with the correct process type).
901 if (current_site_instance->HasWrongProcessForURL(dest_url))
902 return current_site_instance->GetRelatedSiteInstance(dest_url);
904 // View-source URLs must use a new SiteInstance and BrowsingInstance.
905 // TODO(nasko): This is the same condition as later in the function. This
906 // should be taken into account when refactoring this method as part of
907 // http://crbug.com/123007.
908 if (dest_is_view_source_mode)
909 return SiteInstance::CreateForURL(browser_context, dest_url);
911 // If we are navigating from a blank SiteInstance to a WebUI, make sure we
912 // create a new SiteInstance.
913 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
914 browser_context, dest_url)) {
915 return SiteInstance::CreateForURL(browser_context, dest_url);
918 // Normally the "site" on the SiteInstance is set lazily when the load
919 // actually commits. This is to support better process sharing in case
920 // the site redirects to some other site: we want to use the destination
921 // site in the site instance.
923 // In the case of session restore, as it loads all the pages immediately
924 // we need to set the site first, otherwise after a restore none of the
925 // pages would share renderers in process-per-site.
927 // The embedder can request some urls never to be assigned to SiteInstance
928 // through the ShouldAssignSiteForURL() content client method, so that
929 // renderers created for particular chrome urls (e.g. the chrome-native://
930 // scheme) can be reused for subsequent navigations in the same WebContents.
931 // See http://crbug.com/386542.
932 if (dest_is_restore &&
933 GetContentClient()->browser()->ShouldAssignSiteForURL(dest_url)) {
934 current_site_instance->SetSite(dest_url);
937 return current_site_instance;
940 // Otherwise, only create a new SiteInstance for a cross-site navigation.
942 // TODO(creis): Once we intercept links and script-based navigations, we
943 // will be able to enforce that all entries in a SiteInstance actually have
944 // the same site, and it will be safe to compare the URL against the
945 // SiteInstance's site, as follows:
946 // const GURL& current_url = current_instance->site();
947 // For now, though, we're in a hybrid model where you only switch
948 // SiteInstances if you type in a cross-site URL. This means we have to
949 // compare the entry's URL to the last committed entry's URL.
950 NavigationEntry* current_entry = controller.GetLastCommittedEntry();
951 if (interstitial_page_) {
952 // The interstitial is currently the last committed entry, but we want to
953 // compare against the last non-interstitial entry.
954 current_entry = controller.GetEntryAtOffset(-1);
957 // View-source URLs must use a new SiteInstance and BrowsingInstance.
958 // We don't need a swap when going from view-source to a debug URL like
959 // chrome://crash, however.
960 // TODO(creis): Refactor this method so this duplicated code isn't needed.
961 // See http://crbug.com/123007.
962 if (current_entry &&
963 current_entry->IsViewSourceMode() != dest_is_view_source_mode &&
964 !IsRendererDebugURL(dest_url)) {
965 return SiteInstance::CreateForURL(browser_context, dest_url);
968 // Use the source SiteInstance in case of data URLs or about:blank pages,
969 // because the content is then controlled and/or scriptable by the source
970 // SiteInstance.
971 GURL about_blank(url::kAboutBlankURL);
972 if (source_instance &&
973 (dest_url == about_blank || dest_url.scheme() == url::kDataScheme))
974 return source_instance;
976 // Use the current SiteInstance for same site navigations, as long as the
977 // process type is correct. (The URL may have been installed as an app since
978 // the last time we visited it.)
979 const GURL& current_url =
980 GetCurrentURLForSiteInstance(current_instance, current_entry);
981 if (SiteInstance::IsSameWebSite(browser_context, current_url, dest_url) &&
982 !current_site_instance->HasWrongProcessForURL(dest_url)) {
983 return current_instance;
986 // Start the new renderer in a new SiteInstance, but in the current
987 // BrowsingInstance. It is important to immediately give this new
988 // SiteInstance to a RenderViewHost (if it is different than our current
989 // SiteInstance), so that it is ref counted. This will happen in
990 // CreateRenderView.
991 return current_instance->GetRelatedSiteInstance(dest_url);
994 const GURL& RenderFrameHostManager::GetCurrentURLForSiteInstance(
995 SiteInstance* current_instance, NavigationEntry* current_entry) {
996 // If this is a subframe that is potentially out of process from its parent,
997 // don't consider using current_entry's url for SiteInstance selection, since
998 // current_entry's url is for the main frame and may be in a different site
999 // than this frame.
1000 // TODO(creis): Remove this when we can check the FrameNavigationEntry's url.
1001 // See http://crbug.com/369654
1002 if (!frame_tree_node_->IsMainFrame() &&
1003 CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess))
1004 return frame_tree_node_->current_url();
1006 // If there is no last non-interstitial entry (and current_instance already
1007 // has a site), then we must have been opened from another tab. We want
1008 // to compare against the URL of the page that opened us, but we can't
1009 // get to it directly. The best we can do is check against the site of
1010 // the SiteInstance. This will be correct when we intercept links and
1011 // script-based navigations, but for now, it could place some pages in a
1012 // new process unnecessarily. We should only hit this case if a page tries
1013 // to open a new tab to an interstitial-inducing URL, and then navigates
1014 // the page to a different same-site URL. (This seems very unlikely in
1015 // practice.)
1016 if (current_entry)
1017 return current_entry->GetURL();
1018 return current_instance->GetSiteURL();
1021 void RenderFrameHostManager::CreatePendingRenderFrameHost(
1022 SiteInstance* old_instance,
1023 SiteInstance* new_instance,
1024 bool is_main_frame) {
1025 int create_render_frame_flags = 0;
1026 if (is_main_frame)
1027 create_render_frame_flags |= CREATE_RF_FOR_MAIN_FRAME_NAVIGATION;
1029 if (delegate_->IsHidden())
1030 create_render_frame_flags |= CREATE_RF_HIDDEN;
1032 int opener_route_id =
1033 CreateOpenerRenderViewsIfNeeded(old_instance, new_instance);
1035 if (pending_render_frame_host_)
1036 CancelPending();
1038 // Create a non-swapped-out RFH with the given opener.
1039 pending_render_frame_host_ =
1040 CreateRenderFrame(new_instance, pending_web_ui(), opener_route_id,
1041 create_render_frame_flags, nullptr);
1044 int RenderFrameHostManager::CreateOpenerRenderViewsIfNeeded(
1045 SiteInstance* old_instance,
1046 SiteInstance* new_instance) {
1047 int opener_route_id = MSG_ROUTING_NONE;
1048 if (new_instance->IsRelatedSiteInstance(old_instance)) {
1049 opener_route_id =
1050 delegate_->CreateOpenerRenderViewsForRenderManager(new_instance);
1051 if (CommandLine::ForCurrentProcess()->HasSwitch(
1052 switches::kSitePerProcess)) {
1053 // Ensure that the frame tree has RenderFrameProxyHosts for the new
1054 // SiteInstance in all nodes except the current one.
1055 frame_tree_node_->frame_tree()->CreateProxiesForSiteInstance(
1056 frame_tree_node_, new_instance);
1059 return opener_route_id;
1062 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::CreateRenderFrameHost(
1063 SiteInstance* site_instance,
1064 int view_routing_id,
1065 int frame_routing_id,
1066 int flags) {
1067 if (frame_routing_id == MSG_ROUTING_NONE)
1068 frame_routing_id = site_instance->GetProcess()->GetNextRoutingID();
1070 bool swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
1071 bool hidden = !!(flags & CREATE_RF_HIDDEN);
1073 // Create a RVH for main frames, or find the existing one for subframes.
1074 FrameTree* frame_tree = frame_tree_node_->frame_tree();
1075 RenderViewHostImpl* render_view_host = NULL;
1076 if (frame_tree_node_->IsMainFrame()) {
1077 render_view_host = frame_tree->CreateRenderViewHost(
1078 site_instance, view_routing_id, frame_routing_id, swapped_out, hidden);
1079 } else {
1080 render_view_host = frame_tree->GetRenderViewHost(site_instance);
1082 CHECK(render_view_host);
1085 // TODO(creis): Pass hidden to RFH.
1086 scoped_ptr<RenderFrameHostImpl> render_frame_host =
1087 make_scoped_ptr(RenderFrameHostFactory::Create(
1088 render_view_host, render_frame_delegate_, frame_tree,
1089 frame_tree_node_, frame_routing_id, flags).release());
1090 return render_frame_host.Pass();
1093 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::CreateRenderFrame(
1094 SiteInstance* instance,
1095 WebUIImpl* web_ui,
1096 int opener_route_id,
1097 int flags,
1098 int* view_routing_id_ptr) {
1099 bool swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
1100 CHECK(instance);
1101 // Swapped out views should always be hidden.
1102 DCHECK(!swapped_out || (flags & CREATE_RF_HIDDEN));
1104 // TODO(nasko): Remove the following CHECK once cross-site navigation no
1105 // longer relies on swapped out RFH for the top-level frame.
1106 if (!frame_tree_node_->IsMainFrame()) {
1107 CHECK(!swapped_out);
1110 scoped_ptr<RenderFrameHostImpl> new_render_frame_host;
1111 bool success = true;
1112 if (view_routing_id_ptr)
1113 *view_routing_id_ptr = MSG_ROUTING_NONE;
1115 // We are creating a pending or swapped out RFH here. We should never create
1116 // it in the same SiteInstance as our current RFH.
1117 CHECK_NE(render_frame_host_->GetSiteInstance(), instance);
1119 // Check if we've already created an RFH for this SiteInstance. If so, try
1120 // to re-use the existing one, which has already been initialized. We'll
1121 // remove it from the list of proxy hosts below if it will be active.
1122 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1123 if (proxy && proxy->render_frame_host()) {
1124 if (view_routing_id_ptr)
1125 *view_routing_id_ptr = proxy->GetRenderViewHost()->GetRoutingID();
1126 // Delete the existing RenderFrameProxyHost, but reuse the RenderFrameHost.
1127 // Prevent the process from exiting while we're trying to use it.
1128 if (!swapped_out) {
1129 new_render_frame_host = proxy->PassFrameHostOwnership();
1130 new_render_frame_host->GetProcess()->AddPendingView();
1132 proxy_hosts_.erase(instance->GetId());
1133 delete proxy;
1135 // When a new render view is created by the renderer, the new WebContents
1136 // gets a RenderViewHost in the SiteInstance of its opener WebContents.
1137 // If not used in the first navigation, this RVH is swapped out and is not
1138 // granted bindings, so we may need to grant them when swapping it in.
1139 if (web_ui && !new_render_frame_host->GetProcess()->IsIsolatedGuest()) {
1140 int required_bindings = web_ui->GetBindings();
1141 RenderViewHost* render_view_host =
1142 new_render_frame_host->render_view_host();
1143 if ((render_view_host->GetEnabledBindings() & required_bindings) !=
1144 required_bindings) {
1145 render_view_host->AllowBindings(required_bindings);
1149 } else {
1150 // Create a new RenderFrameHost if we don't find an existing one.
1151 new_render_frame_host = CreateRenderFrameHost(instance, MSG_ROUTING_NONE,
1152 MSG_ROUTING_NONE, flags);
1153 RenderViewHostImpl* render_view_host =
1154 new_render_frame_host->render_view_host();
1155 int proxy_routing_id = MSG_ROUTING_NONE;
1157 // Prevent the process from exiting while we're trying to navigate in it.
1158 // Otherwise, if the new RFH is swapped out already, store it.
1159 if (!swapped_out) {
1160 new_render_frame_host->GetProcess()->AddPendingView();
1161 } else {
1162 proxy = new RenderFrameProxyHost(
1163 new_render_frame_host->GetSiteInstance(), frame_tree_node_);
1164 proxy_hosts_[instance->GetId()] = proxy;
1165 proxy_routing_id = proxy->GetRoutingID();
1166 if (frame_tree_node_->IsMainFrame())
1167 proxy->TakeFrameHostOwnership(new_render_frame_host.Pass());
1170 success =
1171 InitRenderView(render_view_host, opener_route_id, proxy_routing_id,
1172 !!(flags & CREATE_RF_FOR_MAIN_FRAME_NAVIGATION));
1173 if (success) {
1174 if (frame_tree_node_->IsMainFrame()) {
1175 // Don't show the main frame's view until we get a DidNavigate from it.
1176 render_view_host->GetView()->Hide();
1177 } else if (!swapped_out) {
1178 // Init the RFH, so a RenderFrame is created in the renderer.
1179 DCHECK(new_render_frame_host.get());
1180 success = InitRenderFrame(new_render_frame_host.get());
1182 if (success) {
1183 if (view_routing_id_ptr)
1184 *view_routing_id_ptr = render_view_host->GetRoutingID();
1185 // If a brand new RFH was created, announce it to observers.
1186 if (new_render_frame_host) {
1187 render_frame_delegate_->RenderFrameCreated(
1188 new_render_frame_host.get());
1194 // Returns the new RFH if it isn't swapped out.
1195 if (success && !swapped_out) {
1196 DCHECK(new_render_frame_host->GetSiteInstance() == instance);
1197 return new_render_frame_host.Pass();
1199 return nullptr;
1202 int RenderFrameHostManager::CreateRenderFrameProxy(SiteInstance* instance) {
1203 // A RenderFrameProxyHost should never be created in the same SiteInstance as
1204 // the current RFH.
1205 CHECK(instance);
1206 CHECK_NE(instance, render_frame_host_->GetSiteInstance());
1208 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1209 if (proxy)
1210 return proxy->GetRoutingID();
1212 proxy = new RenderFrameProxyHost(instance, frame_tree_node_);
1213 proxy_hosts_[instance->GetId()] = proxy;
1214 proxy->InitRenderFrameProxy();
1215 return proxy->GetRoutingID();
1218 bool RenderFrameHostManager::InitRenderView(
1219 RenderViewHostImpl* render_view_host,
1220 int opener_route_id,
1221 int proxy_routing_id,
1222 bool for_main_frame_navigation) {
1223 // We may have initialized this RenderViewHost for another RenderFrameHost.
1224 if (render_view_host->IsRenderViewLive())
1225 return true;
1227 // If the pending navigation is to a WebUI and the RenderView is not in a
1228 // guest process, tell the RenderViewHost about any bindings it will need
1229 // enabled.
1230 if (pending_web_ui() && !render_view_host->GetProcess()->IsIsolatedGuest()) {
1231 render_view_host->AllowBindings(pending_web_ui()->GetBindings());
1232 } else {
1233 // Ensure that we don't create an unprivileged RenderView in a WebUI-enabled
1234 // process unless it's swapped out.
1235 if (render_view_host->is_active()) {
1236 CHECK(!ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1237 render_view_host->GetProcess()->GetID()));
1241 return delegate_->CreateRenderViewForRenderManager(render_view_host,
1242 opener_route_id,
1243 proxy_routing_id,
1244 for_main_frame_navigation);
1247 bool RenderFrameHostManager::InitRenderFrame(
1248 RenderFrameHostImpl* render_frame_host) {
1249 if (render_frame_host->IsRenderFrameLive())
1250 return true;
1252 int parent_routing_id = MSG_ROUTING_NONE;
1253 int proxy_routing_id = MSG_ROUTING_NONE;
1254 if (frame_tree_node_->parent()) {
1255 parent_routing_id = frame_tree_node_->parent()->render_manager()->
1256 GetRoutingIdForSiteInstance(render_frame_host->GetSiteInstance());
1257 CHECK_NE(parent_routing_id, MSG_ROUTING_NONE);
1259 // Check whether there is an existing proxy for this frame in this
1260 // SiteInstance. If there is, the new RenderFrame needs to be able to find
1261 // the proxy it is replacing, so that it can fully initialize itself.
1262 // NOTE: This is the only time that a RenderFrameProxyHost can be in the same
1263 // SiteInstance as its RenderFrameHost. This is only the case until the
1264 // RenderFrameHost commits, at which point it will replace and delete the
1265 // RenderFrameProxyHost.
1266 RenderFrameProxyHost* existing_proxy =
1267 GetRenderFrameProxyHost(render_frame_host->GetSiteInstance());
1268 if (existing_proxy) {
1269 proxy_routing_id = existing_proxy->GetRoutingID();
1270 CHECK_NE(proxy_routing_id, MSG_ROUTING_NONE);
1272 return delegate_->CreateRenderFrameForRenderManager(render_frame_host,
1273 parent_routing_id,
1274 proxy_routing_id);
1277 int RenderFrameHostManager::GetRoutingIdForSiteInstance(
1278 SiteInstance* site_instance) {
1279 if (render_frame_host_->GetSiteInstance() == site_instance)
1280 return render_frame_host_->GetRoutingID();
1282 RenderFrameProxyHostMap::iterator iter =
1283 proxy_hosts_.find(site_instance->GetId());
1284 if (iter != proxy_hosts_.end())
1285 return iter->second->GetRoutingID();
1287 return MSG_ROUTING_NONE;
1290 void RenderFrameHostManager::CommitPending() {
1291 TRACE_EVENT1("navigation", "RenderFrameHostManager::CommitPending",
1292 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
1293 // First check whether we're going to want to focus the location bar after
1294 // this commit. We do this now because the navigation hasn't formally
1295 // committed yet, so if we've already cleared |pending_web_ui_| the call chain
1296 // this triggers won't be able to figure out what's going on.
1297 bool will_focus_location_bar = delegate_->FocusLocationBarByDefault();
1299 // Next commit the Web UI, if any. Either replace |web_ui_| with
1300 // |pending_web_ui_|, or clear |web_ui_| if there is no pending WebUI, or
1301 // leave |web_ui_| as is if reusing it.
1302 DCHECK(!(pending_web_ui_.get() && pending_and_current_web_ui_.get()));
1303 if (pending_web_ui_) {
1304 web_ui_.reset(pending_web_ui_.release());
1305 } else if (!pending_and_current_web_ui_.get()) {
1306 web_ui_.reset();
1307 } else {
1308 DCHECK_EQ(pending_and_current_web_ui_.get(), web_ui_.get());
1309 pending_and_current_web_ui_.reset();
1312 // It's possible for the pending_render_frame_host_ to be NULL when we aren't
1313 // crossing process boundaries. If so, we just needed to handle the Web UI
1314 // committing above and we're done.
1315 if (!pending_render_frame_host_) {
1316 if (will_focus_location_bar)
1317 delegate_->SetFocusToLocationBar(false);
1318 return;
1321 // Remember if the page was focused so we can focus the new renderer in
1322 // that case.
1323 bool focus_render_view = !will_focus_location_bar &&
1324 render_frame_host_->render_view_host()->GetView() &&
1325 render_frame_host_->render_view_host()->GetView()->HasFocus();
1327 bool is_main_frame = frame_tree_node_->IsMainFrame();
1329 // Swap in the pending frame and make it active. Also ensure the FrameTree
1330 // stays in sync.
1331 scoped_ptr<RenderFrameHostImpl> old_render_frame_host =
1332 SetRenderFrameHost(pending_render_frame_host_.Pass());
1333 if (is_main_frame)
1334 render_frame_host_->render_view_host()->AttachToFrameTree();
1336 // The process will no longer try to exit, so we can decrement the count.
1337 render_frame_host_->GetProcess()->RemovePendingView();
1339 // Show the new view (or a sad tab) if necessary.
1340 bool new_rfh_has_view = !!render_frame_host_->render_view_host()->GetView();
1341 if (!delegate_->IsHidden() && new_rfh_has_view) {
1342 // In most cases, we need to show the new view.
1343 render_frame_host_->render_view_host()->GetView()->Show();
1345 if (!new_rfh_has_view) {
1346 // If the view is gone, then this RenderViewHost died while it was hidden.
1347 // We ignored the RenderProcessGone call at the time, so we should send it
1348 // now to make sure the sad tab shows up, etc.
1349 DCHECK(!render_frame_host_->IsRenderFrameLive());
1350 DCHECK(!render_frame_host_->render_view_host()->IsRenderViewLive());
1351 delegate_->RenderProcessGoneFromRenderManager(
1352 render_frame_host_->render_view_host());
1355 // For top-level frames, also hide the old RenderViewHost's view.
1356 // TODO(creis): As long as show/hide are on RVH, we don't want to hide on
1357 // subframe navigations or we will interfere with the top-level frame.
1358 if (is_main_frame && old_render_frame_host->render_view_host()->GetView())
1359 old_render_frame_host->render_view_host()->GetView()->Hide();
1361 // Make sure the size is up to date. (Fix for bug 1079768.)
1362 delegate_->UpdateRenderViewSizeForRenderManager();
1364 if (will_focus_location_bar) {
1365 delegate_->SetFocusToLocationBar(false);
1366 } else if (focus_render_view &&
1367 render_frame_host_->render_view_host()->GetView()) {
1368 render_frame_host_->render_view_host()->GetView()->Focus();
1371 // Notify that we've swapped RenderFrameHosts. We do this before shutting down
1372 // the RFH so that we can clean up RendererResources related to the RFH first.
1373 delegate_->NotifySwappedFromRenderManager(
1374 old_render_frame_host.get(), render_frame_host_.get(), is_main_frame);
1376 // Swap out the old frame now that the new one is visible.
1377 // This will swap it out and then put it on the proxy list (if there are other
1378 // active views in its SiteInstance) or schedule it for deletion when the swap
1379 // out ack arrives (or immediately if the process isn't live).
1380 // In the --site-per-process case, old subframe RHFs are not kept alive inside
1381 // the proxy.
1382 SwapOutOldFrame(old_render_frame_host.Pass());
1384 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess) &&
1385 !is_main_frame) {
1386 // If this is a subframe, it should have a CrossProcessFrameConnector
1387 // created already. Use it to link the new RFH's view to the proxy that
1388 // belongs to the parent frame's SiteInstance.
1389 // Note: We do this after swapping out the old RFH because that may create
1390 // the proxy we're looking for.
1391 RenderFrameProxyHost* proxy_to_parent = GetProxyToParent();
1392 if (proxy_to_parent) {
1393 proxy_to_parent->SetChildRWHView(
1394 render_frame_host_->render_view_host()->GetView());
1397 // Since the new RenderFrameHost is now committed, there must be no proxies
1398 // for its SiteInstance. Delete any existing ones.
1399 RenderFrameProxyHostMap::iterator iter =
1400 proxy_hosts_.find(render_frame_host_->GetSiteInstance()->GetId());
1401 if (iter != proxy_hosts_.end()) {
1402 delete iter->second;
1403 proxy_hosts_.erase(iter);
1407 // After all is done, there must never be a proxy in the list which has the
1408 // same SiteInstance as the current RenderFrameHost.
1409 CHECK(proxy_hosts_.find(render_frame_host_->GetSiteInstance()->GetId()) ==
1410 proxy_hosts_.end());
1413 void RenderFrameHostManager::ShutdownRenderFrameProxyHostsInSiteInstance(
1414 int32 site_instance_id) {
1415 // First remove any swapped out RFH for this SiteInstance from our own list.
1416 ClearProxiesInSiteInstance(site_instance_id, frame_tree_node_);
1418 // Use the safe RenderWidgetHost iterator for now to find all RenderViewHosts
1419 // in the SiteInstance, then tell their respective FrameTrees to remove all
1420 // RenderFrameProxyHosts corresponding to them.
1421 // TODO(creis): Replace this with a RenderFrameHostIterator that protects
1422 // against use-after-frees if a later element is deleted before getting to it.
1423 scoped_ptr<RenderWidgetHostIterator> widgets(
1424 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
1425 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
1426 if (!widget->IsRenderView())
1427 continue;
1428 RenderViewHostImpl* rvh =
1429 static_cast<RenderViewHostImpl*>(RenderViewHost::From(widget));
1430 if (site_instance_id == rvh->GetSiteInstance()->GetId()) {
1431 // This deletes all RenderFrameHosts using the |rvh|, which then causes
1432 // |rvh| to Shutdown.
1433 FrameTree* tree = rvh->GetDelegate()->GetFrameTree();
1434 tree->ForEach(base::Bind(
1435 &RenderFrameHostManager::ClearProxiesInSiteInstance,
1436 site_instance_id));
1441 RenderFrameHostImpl* RenderFrameHostManager::UpdateStateForNavigate(
1442 const GURL& dest_url,
1443 SiteInstance* source_instance,
1444 SiteInstance* dest_instance,
1445 ui::PageTransition transition,
1446 bool dest_is_restore,
1447 bool dest_is_view_source_mode,
1448 const GlobalRequestID& transferred_request_id,
1449 int bindings) {
1450 // If we are currently navigating cross-process, we want to get back to normal
1451 // and then navigate as usual.
1452 if (cross_navigation_pending_) {
1453 if (pending_render_frame_host_)
1454 CancelPending();
1455 cross_navigation_pending_ = false;
1458 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1459 scoped_refptr<SiteInstance> new_instance = GetSiteInstanceForNavigation(
1460 dest_url, source_instance, dest_instance, transition,
1461 dest_is_restore, dest_is_view_source_mode);
1463 const NavigationEntry* current_entry =
1464 delegate_->GetLastCommittedNavigationEntryForRenderManager();
1466 if (new_instance.get() != current_instance) {
1467 TRACE_EVENT_INSTANT2(
1468 "navigation",
1469 "RenderFrameHostManager::UpdateStateForNavigate:New SiteInstance",
1470 TRACE_EVENT_SCOPE_THREAD,
1471 "current_instance id", current_instance->GetId(),
1472 "new_instance id", new_instance->GetId());
1474 // New SiteInstance: create a pending RFH to navigate.
1475 DCHECK(!cross_navigation_pending_);
1477 // This will possibly create (set to NULL) a Web UI object for the pending
1478 // page. We'll use this later to give the page special access. This must
1479 // happen before the new renderer is created below so it will get bindings.
1480 // It must also happen after the above conditional call to CancelPending(),
1481 // otherwise CancelPending may clear the pending_web_ui_ and the page will
1482 // not have its bindings set appropriately.
1483 SetPendingWebUI(dest_url, bindings);
1484 CreatePendingRenderFrameHost(current_instance, new_instance.get(),
1485 frame_tree_node_->IsMainFrame());
1486 if (!pending_render_frame_host_.get()) {
1487 return NULL;
1490 // Check if our current RFH is live before we set up a transition.
1491 if (!render_frame_host_->IsRenderFrameLive()) {
1492 if (!cross_navigation_pending_) {
1493 // The current RFH is not live. There's no reason to sit around with a
1494 // sad tab or a newly created RFH while we wait for the pending RFH to
1495 // navigate. Just switch to the pending RFH now and go back to non
1496 // cross-navigating (Note that we don't care about on{before}unload
1497 // handlers if the current RFH isn't live.)
1498 CommitPending();
1499 return render_frame_host_.get();
1500 } else {
1501 NOTREACHED();
1502 return render_frame_host_.get();
1505 // Otherwise, it's safe to treat this as a pending cross-site transition.
1507 // We now have a pending RFH.
1508 DCHECK(!cross_navigation_pending_);
1509 cross_navigation_pending_ = true;
1511 // PlzNavigate: There is no notion of transfer navigations, and the old
1512 // renderer before unload handler has already run at that point, so return
1513 // here.
1514 if (CommandLine::ForCurrentProcess()->HasSwitch(
1515 switches::kEnableBrowserSideNavigation)) {
1516 return pending_render_frame_host_.get();
1519 // We need to wait until the beforeunload handler has run, unless we are
1520 // transferring an existing request (in which case it has already run).
1521 // Suspend the new render view (i.e., don't let it send the cross-site
1522 // Navigate message) until we hear back from the old renderer's
1523 // beforeunload handler. If the handler returns false, we'll have to
1524 // cancel the request.
1526 DCHECK(!pending_render_frame_host_->are_navigations_suspended());
1527 bool is_transfer = transferred_request_id != GlobalRequestID();
1528 if (is_transfer) {
1529 // We don't need to stop the old renderer or run beforeunload/unload
1530 // handlers, because those have already been done.
1531 DCHECK(cross_site_transferring_request_->request_id() ==
1532 transferred_request_id);
1533 } else {
1534 // Also make sure the old render view stops, in case a load is in
1535 // progress. (We don't want to do this for transfers, since it will
1536 // interrupt the transfer with an unexpected DidStopLoading.)
1537 render_frame_host_->Send(new FrameMsg_Stop(
1538 render_frame_host_->GetRoutingID()));
1539 pending_render_frame_host_->SetNavigationsSuspended(true,
1540 base::TimeTicks());
1541 // Unless we are transferring an existing request, we should now tell the
1542 // old render view to run its beforeunload handler, since it doesn't
1543 // otherwise know that the cross-site request is happening. This will
1544 // trigger a call to OnBeforeUnloadACK with the reply.
1545 render_frame_host_->DispatchBeforeUnload(true);
1548 return pending_render_frame_host_.get();
1551 // Otherwise the same SiteInstance can be used. Navigate render_frame_host_.
1552 DCHECK(!cross_navigation_pending_);
1554 // It's possible to swap out the current RFH and then decide to navigate in it
1555 // anyway (e.g., a cross-process navigation that redirects back to the
1556 // original site). In that case, we have a proxy for the current RFH but
1557 // haven't deleted it yet. The new navigation will swap it back in, so we can
1558 // delete the proxy.
1559 DeleteRenderFrameProxyHost(new_instance.get());
1561 if (ShouldReuseWebUI(current_entry, dest_url)) {
1562 pending_web_ui_.reset();
1563 pending_and_current_web_ui_ = web_ui_->AsWeakPtr();
1564 } else {
1565 SetPendingWebUI(dest_url, bindings);
1566 // Make sure the new RenderViewHost has the right bindings.
1567 if (pending_web_ui() &&
1568 !render_frame_host_->GetProcess()->IsIsolatedGuest()) {
1569 render_frame_host_->render_view_host()->AllowBindings(
1570 pending_web_ui()->GetBindings());
1574 if (pending_web_ui() && render_frame_host_->IsRenderFrameLive()) {
1575 pending_web_ui()->GetController()->RenderViewReused(
1576 render_frame_host_->render_view_host());
1579 // The renderer can exit view source mode when any error or cancellation
1580 // happen. We must overwrite to recover the mode.
1581 if (dest_is_view_source_mode) {
1582 render_frame_host_->render_view_host()->Send(
1583 new ViewMsg_EnableViewSourceMode(
1584 render_frame_host_->render_view_host()->GetRoutingID()));
1587 return render_frame_host_.get();
1590 void RenderFrameHostManager::CancelPending() {
1591 TRACE_EVENT1("navigation", "RenderFrameHostManager::CancelPending",
1592 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
1593 DiscardUnusedFrame(UnsetPendingRenderFrameHost());
1596 scoped_ptr<RenderFrameHostImpl>
1597 RenderFrameHostManager::UnsetPendingRenderFrameHost() {
1598 scoped_ptr<RenderFrameHostImpl> pending_render_frame_host =
1599 pending_render_frame_host_.Pass();
1601 RenderViewDevToolsAgentHost::OnCancelPendingNavigation(
1602 pending_render_frame_host->render_view_host(),
1603 render_frame_host_->render_view_host());
1605 // We no longer need to prevent the process from exiting.
1606 pending_render_frame_host->GetProcess()->RemovePendingView();
1608 pending_web_ui_.reset();
1609 pending_and_current_web_ui_.reset();
1611 return pending_render_frame_host.Pass();
1614 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::SetRenderFrameHost(
1615 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
1616 // Swap the two.
1617 scoped_ptr<RenderFrameHostImpl> old_render_frame_host =
1618 render_frame_host_.Pass();
1619 render_frame_host_ = render_frame_host.Pass();
1621 if (frame_tree_node_->IsMainFrame()) {
1622 // Update the count of top-level frames using this SiteInstance. All
1623 // subframes are in the same BrowsingInstance as the main frame, so we only
1624 // count top-level ones. This makes the value easier for consumers to
1625 // interpret.
1626 if (render_frame_host_) {
1627 render_frame_host_->GetSiteInstance()->
1628 IncrementRelatedActiveContentsCount();
1630 if (old_render_frame_host) {
1631 old_render_frame_host->GetSiteInstance()->
1632 DecrementRelatedActiveContentsCount();
1636 return old_render_frame_host.Pass();
1639 bool RenderFrameHostManager::IsRVHOnSwappedOutList(
1640 RenderViewHostImpl* rvh) const {
1641 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(
1642 rvh->GetSiteInstance());
1643 if (!proxy)
1644 return false;
1645 // If there is a proxy without RFH, it is for a subframe in the SiteInstance
1646 // of |rvh|. Subframes should be ignored in this case.
1647 if (!proxy->render_frame_host())
1648 return false;
1649 return IsOnSwappedOutList(proxy->render_frame_host());
1652 bool RenderFrameHostManager::IsOnSwappedOutList(
1653 RenderFrameHostImpl* rfh) const {
1654 if (!rfh->GetSiteInstance())
1655 return false;
1657 RenderFrameProxyHostMap::const_iterator iter = proxy_hosts_.find(
1658 rfh->GetSiteInstance()->GetId());
1659 if (iter == proxy_hosts_.end())
1660 return false;
1662 return iter->second->render_frame_host() == rfh;
1665 RenderViewHostImpl* RenderFrameHostManager::GetSwappedOutRenderViewHost(
1666 SiteInstance* instance) const {
1667 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1668 if (proxy)
1669 return proxy->GetRenderViewHost();
1670 return NULL;
1673 RenderFrameProxyHost* RenderFrameHostManager::GetRenderFrameProxyHost(
1674 SiteInstance* instance) const {
1675 RenderFrameProxyHostMap::const_iterator iter =
1676 proxy_hosts_.find(instance->GetId());
1677 if (iter != proxy_hosts_.end())
1678 return iter->second;
1680 return NULL;
1683 void RenderFrameHostManager::DeleteRenderFrameProxyHost(
1684 SiteInstance* instance) {
1685 RenderFrameProxyHostMap::iterator iter = proxy_hosts_.find(instance->GetId());
1686 if (iter != proxy_hosts_.end()) {
1687 delete iter->second;
1688 proxy_hosts_.erase(iter);
1692 } // namespace content