ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_manager.cc
blobb9328a40b2539c35bda23a47ff0299f2e67c4949
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/logging.h"
11 #include "base/stl_util.h"
12 #include "base/trace_event/trace_event.h"
13 #include "content/browser/child_process_security_policy_impl.h"
14 #include "content/browser/devtools/render_frame_devtools_agent_host.h"
15 #include "content/browser/frame_host/cross_site_transferring_request.h"
16 #include "content/browser/frame_host/debug_urls.h"
17 #include "content/browser/frame_host/interstitial_page_impl.h"
18 #include "content/browser/frame_host/navigation_controller_impl.h"
19 #include "content/browser/frame_host/navigation_entry_impl.h"
20 #include "content/browser/frame_host/navigation_request.h"
21 #include "content/browser/frame_host/navigator.h"
22 #include "content/browser/frame_host/render_frame_host_factory.h"
23 #include "content/browser/frame_host/render_frame_host_impl.h"
24 #include "content/browser/frame_host/render_frame_proxy_host.h"
25 #include "content/browser/renderer_host/render_process_host_impl.h"
26 #include "content/browser/renderer_host/render_view_host_factory.h"
27 #include "content/browser/renderer_host/render_view_host_impl.h"
28 #include "content/browser/site_instance_impl.h"
29 #include "content/browser/webui/web_ui_controller_factory_registry.h"
30 #include "content/browser/webui/web_ui_impl.h"
31 #include "content/common/frame_messages.h"
32 #include "content/common/view_messages.h"
33 #include "content/public/browser/content_browser_client.h"
34 #include "content/public/browser/notification_service.h"
35 #include "content/public/browser/notification_types.h"
36 #include "content/public/browser/render_widget_host_iterator.h"
37 #include "content/public/browser/render_widget_host_view.h"
38 #include "content/public/browser/user_metrics.h"
39 #include "content/public/browser/web_ui_controller.h"
40 #include "content/public/common/content_switches.h"
41 #include "content/public/common/referrer.h"
42 #include "content/public/common/url_constants.h"
44 namespace content {
46 // static
47 bool RenderFrameHostManager::ClearRFHsPendingShutdown(FrameTreeNode* node) {
48 node->render_manager()->pending_delete_hosts_.clear();
49 return true;
52 RenderFrameHostManager::RenderFrameHostManager(
53 FrameTreeNode* frame_tree_node,
54 RenderFrameHostDelegate* render_frame_delegate,
55 RenderViewHostDelegate* render_view_delegate,
56 RenderWidgetHostDelegate* render_widget_delegate,
57 Delegate* delegate)
58 : frame_tree_node_(frame_tree_node),
59 delegate_(delegate),
60 cross_navigation_pending_(false),
61 render_frame_delegate_(render_frame_delegate),
62 render_view_delegate_(render_view_delegate),
63 render_widget_delegate_(render_widget_delegate),
64 interstitial_page_(nullptr),
65 should_reuse_web_ui_(false),
66 weak_factory_(this) {
67 DCHECK(frame_tree_node_);
70 RenderFrameHostManager::~RenderFrameHostManager() {
71 if (pending_render_frame_host_)
72 UnsetPendingRenderFrameHost();
74 if (speculative_render_frame_host_)
75 UnsetSpeculativeRenderFrameHost();
77 if (render_frame_host_ &&
78 render_frame_host_->GetSiteInstance()->active_frame_count() <= 1U) {
79 ShutdownRenderFrameProxyHostsInSiteInstance(
80 render_frame_host_->GetSiteInstance()->GetId());
83 // Delete any RenderFrameProxyHosts and swapped out RenderFrameHosts.
84 // It is important to delete those prior to deleting the current
85 // RenderFrameHost, since the CrossProcessFrameConnector (owned by
86 // RenderFrameProxyHost) points to the RenderWidgetHostView associated with
87 // the current RenderFrameHost and uses it during its destructor.
88 STLDeleteValues(&proxy_hosts_);
90 // Release the WebUI prior to resetting the current RenderFrameHost, as the
91 // WebUI accesses the RenderFrameHost during cleanup.
92 web_ui_.reset();
94 // We should always have a current RenderFrameHost except in some tests.
95 SetRenderFrameHost(scoped_ptr<RenderFrameHostImpl>());
98 void RenderFrameHostManager::Init(BrowserContext* browser_context,
99 SiteInstance* site_instance,
100 int view_routing_id,
101 int frame_routing_id) {
102 // Create a RenderViewHost and RenderFrameHost, once we have an instance. It
103 // is important to immediately give this SiteInstance to a RenderViewHost so
104 // that the SiteInstance is ref counted.
105 if (!site_instance)
106 site_instance = SiteInstance::Create(browser_context);
108 int flags = delegate_->IsHidden() ? CREATE_RF_HIDDEN : 0;
109 SetRenderFrameHost(CreateRenderFrameHost(site_instance, view_routing_id,
110 frame_routing_id, flags));
112 // Notify the delegate of the creation of the current RenderFrameHost.
113 // Do this only for subframes, as the main frame case is taken care of by
114 // WebContentsImpl::Init.
115 if (!frame_tree_node_->IsMainFrame()) {
116 delegate_->NotifySwappedFromRenderManager(
117 nullptr, render_frame_host_.get(), false);
120 // Keep track of renderer processes as they start to shut down or are
121 // crashed/killed.
122 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSED,
123 NotificationService::AllSources());
124 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSING,
125 NotificationService::AllSources());
128 RenderViewHostImpl* RenderFrameHostManager::current_host() const {
129 if (!render_frame_host_)
130 return NULL;
131 return render_frame_host_->render_view_host();
134 RenderViewHostImpl* RenderFrameHostManager::pending_render_view_host() const {
135 if (!pending_render_frame_host_)
136 return NULL;
137 return pending_render_frame_host_->render_view_host();
140 RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const {
141 if (interstitial_page_)
142 return interstitial_page_->GetView();
143 if (render_frame_host_)
144 return render_frame_host_->GetView();
145 return nullptr;
148 RenderFrameProxyHost* RenderFrameHostManager::GetProxyToParent() {
149 if (frame_tree_node_->IsMainFrame())
150 return NULL;
152 RenderFrameProxyHostMap::iterator iter =
153 proxy_hosts_.find(frame_tree_node_->parent()
154 ->render_manager()
155 ->current_frame_host()
156 ->GetSiteInstance()
157 ->GetId());
158 if (iter == proxy_hosts_.end())
159 return NULL;
161 return iter->second;
164 void RenderFrameHostManager::SetPendingWebUI(const GURL& url, int bindings) {
165 pending_web_ui_ = CreateWebUI(url, bindings);
166 pending_and_current_web_ui_.reset();
169 scoped_ptr<WebUIImpl> RenderFrameHostManager::CreateWebUI(const GURL& url,
170 int bindings) {
171 scoped_ptr<WebUIImpl> new_web_ui(delegate_->CreateWebUIForRenderManager(url));
173 // If we have assigned (zero or more) bindings to this NavigationEntry in the
174 // past, make sure we're not granting it different bindings than it had
175 // before. If so, note it and don't give it any bindings, to avoid a
176 // potential privilege escalation.
177 if (new_web_ui && bindings != NavigationEntryImpl::kInvalidBindings &&
178 new_web_ui->GetBindings() != bindings) {
179 RecordAction(base::UserMetricsAction("ProcessSwapBindingsMismatch_RVHM"));
180 return nullptr;
182 return new_web_ui.Pass();
185 RenderFrameHostImpl* RenderFrameHostManager::Navigate(
186 const NavigationEntryImpl& entry) {
187 TRACE_EVENT1("navigation", "RenderFrameHostManager:Navigate",
188 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
189 // Create a pending RenderFrameHost to use for the navigation.
190 RenderFrameHostImpl* dest_render_frame_host = UpdateStateForNavigate(
191 entry.GetURL(), entry.source_site_instance(), entry.site_instance(),
192 entry.GetTransitionType(),
193 entry.restore_type() != NavigationEntryImpl::RESTORE_NONE,
194 entry.IsViewSourceMode(), entry.transferred_global_request_id(),
195 entry.bindings());
196 if (!dest_render_frame_host)
197 return NULL; // We weren't able to create a pending render frame host.
199 // If the current render_frame_host_ isn't live, we should create it so
200 // that we don't show a sad tab while the dest_render_frame_host fetches
201 // its first page. (Bug 1145340)
202 if (dest_render_frame_host != render_frame_host_ &&
203 !render_frame_host_->IsRenderFrameLive()) {
204 // Note: we don't call InitRenderView here because we are navigating away
205 // soon anyway, and we don't have the NavigationEntry for this host.
206 delegate_->CreateRenderViewForRenderManager(
207 render_frame_host_->render_view_host(), MSG_ROUTING_NONE,
208 MSG_ROUTING_NONE, frame_tree_node_->IsMainFrame());
211 // If the renderer crashed, then try to create a new one to satisfy this
212 // navigation request.
213 if (!dest_render_frame_host->IsRenderFrameLive()) {
214 // Instruct the destination render frame host to set up a Mojo connection
215 // with the new render frame if necessary. Note that this call needs to
216 // occur before initializing the RenderView; the flow of creating the
217 // RenderView can cause browser-side code to execute that expects the this
218 // RFH's ServiceRegistry to be initialized (e.g., if the site is a WebUI
219 // site that is handled via Mojo, then Mojo WebUI code in //chrome will
220 // add a service to this RFH's ServiceRegistry).
221 dest_render_frame_host->SetUpMojoIfNeeded();
223 // Recreate the opener chain.
224 int opener_route_id = delegate_->CreateOpenerRenderViewsForRenderManager(
225 dest_render_frame_host->GetSiteInstance());
226 if (!InitRenderView(dest_render_frame_host->render_view_host(),
227 opener_route_id,
228 MSG_ROUTING_NONE,
229 frame_tree_node_->IsMainFrame()))
230 return NULL;
232 // Now that we've created a new renderer, be sure to hide it if it isn't
233 // our primary one. Otherwise, we might crash if we try to call Show()
234 // on it later.
235 if (dest_render_frame_host != render_frame_host_) {
236 if (dest_render_frame_host->GetView())
237 dest_render_frame_host->GetView()->Hide();
238 } else {
239 // TODO(nasko): This is a very ugly hack. The Chrome extensions process
240 // manager still uses NotificationService and expects to see a
241 // RenderViewHost changed notification after WebContents and
242 // RenderFrameHostManager are completely initialized. This should be
243 // removed once the process manager moves away from NotificationService.
244 // See https://crbug.com/462682.
245 delegate_->NotifyMainFrameSwappedFromRenderManager(
246 nullptr, render_frame_host_->render_view_host());
250 // If entry includes the request ID of a request that is being transferred,
251 // the destination render frame will take ownership, so release ownership of
252 // the request.
253 if (cross_site_transferring_request_.get() &&
254 cross_site_transferring_request_->request_id() ==
255 entry.transferred_global_request_id()) {
256 cross_site_transferring_request_->ReleaseRequest();
259 return dest_render_frame_host;
262 void RenderFrameHostManager::Stop() {
263 render_frame_host_->Stop();
265 // If we are cross-navigating, we should stop the pending renderers. This
266 // will lead to a DidFailProvisionalLoad, which will properly destroy them.
267 if (cross_navigation_pending_) {
268 pending_render_frame_host_->Send(new FrameMsg_Stop(
269 pending_render_frame_host_->GetRoutingID()));
273 void RenderFrameHostManager::SetIsLoading(bool is_loading) {
274 render_frame_host_->render_view_host()->SetIsLoading(is_loading);
275 if (pending_render_frame_host_)
276 pending_render_frame_host_->render_view_host()->SetIsLoading(is_loading);
279 bool RenderFrameHostManager::ShouldCloseTabOnUnresponsiveRenderer() {
280 // If we're waiting for a close ACK, then the tab should close whether there's
281 // a navigation in progress or not. Unfortunately, we also need to check for
282 // cases that we arrive here with no navigation in progress, since there are
283 // some tab closure paths that don't set is_waiting_for_close_ack to true.
284 // TODO(creis): Clean this up in http://crbug.com/418266.
285 if (!cross_navigation_pending_ ||
286 render_frame_host_->render_view_host()->is_waiting_for_close_ack())
287 return true;
289 // We should always have a pending RFH when there's a cross-process navigation
290 // in progress. Sanity check this for http://crbug.com/276333.
291 CHECK(pending_render_frame_host_);
293 // Unload handlers run in the background, so we should never get an
294 // unresponsiveness warning for them.
295 CHECK(!render_frame_host_->IsWaitingForUnloadACK());
297 // If the tab becomes unresponsive during beforeunload while doing a
298 // cross-site navigation, proceed with the navigation. (This assumes that
299 // the pending RenderFrameHost is still responsive.)
300 if (render_frame_host_->IsWaitingForBeforeUnloadACK()) {
301 // Haven't gotten around to starting the request, because we're still
302 // waiting for the beforeunload handler to finish. We'll pretend that it
303 // did finish, to let the navigation proceed. Note that there's a danger
304 // that the beforeunload handler will later finish and possibly return
305 // false (meaning the navigation should not proceed), but we'll ignore it
306 // in this case because it took too long.
307 if (pending_render_frame_host_->are_navigations_suspended()) {
308 pending_render_frame_host_->SetNavigationsSuspended(
309 false, base::TimeTicks::Now());
312 return false;
315 void RenderFrameHostManager::OnBeforeUnloadACK(
316 bool for_cross_site_transition,
317 bool proceed,
318 const base::TimeTicks& proceed_time) {
319 if (for_cross_site_transition) {
320 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
321 switches::kEnableBrowserSideNavigation));
322 // Ignore if we're not in a cross-site navigation.
323 if (!cross_navigation_pending_)
324 return;
326 if (proceed) {
327 // Ok to unload the current page, so proceed with the cross-site
328 // navigation. Note that if navigations are not currently suspended, it
329 // might be because the renderer was deemed unresponsive and this call was
330 // already made by ShouldCloseTabOnUnresponsiveRenderer. In that case, it
331 // is ok to do nothing here.
332 if (pending_render_frame_host_ &&
333 pending_render_frame_host_->are_navigations_suspended()) {
334 pending_render_frame_host_->SetNavigationsSuspended(false,
335 proceed_time);
337 } else {
338 // Current page says to cancel.
339 CancelPending();
340 cross_navigation_pending_ = false;
342 } else {
343 // Non-cross site transition means closing the entire tab.
344 bool proceed_to_fire_unload;
345 delegate_->BeforeUnloadFiredFromRenderManager(proceed, proceed_time,
346 &proceed_to_fire_unload);
348 if (proceed_to_fire_unload) {
349 // If we're about to close the tab and there's a pending RFH, cancel it.
350 // Otherwise, if the navigation in the pending RFH completes before the
351 // close in the current RFH, we'll lose the tab close.
352 if (pending_render_frame_host_) {
353 CancelPending();
354 cross_navigation_pending_ = false;
357 // This is not a cross-site navigation, the tab is being closed.
358 render_frame_host_->render_view_host()->ClosePage();
363 void RenderFrameHostManager::OnCrossSiteResponse(
364 RenderFrameHostImpl* pending_render_frame_host,
365 const GlobalRequestID& global_request_id,
366 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
367 const std::vector<GURL>& transfer_url_chain,
368 const Referrer& referrer,
369 ui::PageTransition page_transition,
370 bool should_replace_current_entry) {
371 // We should only get here for transfer navigations. Most cross-process
372 // navigations can just continue and wait to run the unload handler (by
373 // swapping out) when the new navigation commits.
374 CHECK(cross_site_transferring_request.get());
376 // A transfer should only have come from our pending or current RFH.
377 // TODO(creis): We need to handle the case that the pending RFH has changed
378 // in the mean time, while this was being posted from the IO thread. We
379 // should probably cancel the request in that case.
380 DCHECK(pending_render_frame_host == pending_render_frame_host_ ||
381 pending_render_frame_host == render_frame_host_);
383 // Store the transferring request so that we can release it if the transfer
384 // navigation matches.
385 cross_site_transferring_request_ = cross_site_transferring_request.Pass();
387 // Sanity check that the params are for the correct frame and process.
388 // These should match the RenderFrameHost that made the request.
389 // If it started as a cross-process navigation via OpenURL, this is the
390 // pending one. If it wasn't cross-process until the transfer, this is the
391 // current one.
392 int render_frame_id = pending_render_frame_host_ ?
393 pending_render_frame_host_->GetRoutingID() :
394 render_frame_host_->GetRoutingID();
395 DCHECK_EQ(render_frame_id, pending_render_frame_host->GetRoutingID());
396 int process_id = pending_render_frame_host_ ?
397 pending_render_frame_host_->GetProcess()->GetID() :
398 render_frame_host_->GetProcess()->GetID();
399 DCHECK_EQ(process_id, global_request_id.child_id);
401 // Treat the last URL in the chain as the destination and the remainder as
402 // the redirect chain.
403 CHECK(transfer_url_chain.size());
404 GURL transfer_url = transfer_url_chain.back();
405 std::vector<GURL> rest_of_chain = transfer_url_chain;
406 rest_of_chain.pop_back();
408 // We don't know whether the original request had |user_action| set to true.
409 // However, since we force the navigation to be in the current tab, it
410 // doesn't matter.
411 pending_render_frame_host->frame_tree_node()->navigator()->RequestTransferURL(
412 pending_render_frame_host, transfer_url, nullptr, rest_of_chain, referrer,
413 page_transition, CURRENT_TAB, global_request_id,
414 should_replace_current_entry, true);
416 // The transferring request was only needed during the RequestTransferURL
417 // call, so it is safe to clear at this point.
418 cross_site_transferring_request_.reset();
421 void RenderFrameHostManager::OnDeferredAfterResponseStarted(
422 const GlobalRequestID& global_request_id,
423 RenderFrameHostImpl* pending_render_frame_host) {
424 DCHECK(!response_started_id_.get());
426 response_started_id_.reset(new GlobalRequestID(global_request_id));
429 void RenderFrameHostManager::ResumeResponseDeferredAtStart() {
430 DCHECK(response_started_id_.get());
432 RenderProcessHostImpl* process =
433 static_cast<RenderProcessHostImpl*>(render_frame_host_->GetProcess());
434 process->ResumeResponseDeferredAtStart(*response_started_id_);
436 render_frame_host_->ClearPendingTransitionRequestData();
438 response_started_id_.reset();
441 void RenderFrameHostManager::ClearNavigationTransitionData() {
442 render_frame_host_->ClearPendingTransitionRequestData();
445 void RenderFrameHostManager::DidNavigateFrame(
446 RenderFrameHostImpl* render_frame_host,
447 bool was_caused_by_user_gesture) {
448 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
449 switches::kEnableBrowserSideNavigation)) {
450 if (render_frame_host == speculative_render_frame_host_.get()) {
451 CommitPending();
452 } else if (render_frame_host == render_frame_host_.get()) {
453 // TODO(carlosk): this code doesn't properly handle in-page navigation or
454 // interwoven navigation requests.
455 DCHECK(!speculative_render_frame_host_);
456 } else {
457 // No one else should be sending us a DidNavigate in this state.
458 DCHECK(false);
460 DCHECK(!speculative_render_frame_host_);
461 return;
464 if (!cross_navigation_pending_) {
465 DCHECK(!pending_render_frame_host_);
467 // We should only hear this from our current renderer.
468 DCHECK_EQ(render_frame_host_, render_frame_host);
470 // Even when there is no pending RVH, there may be a pending Web UI.
471 if (pending_web_ui())
472 CommitPending();
473 return;
476 if (render_frame_host == pending_render_frame_host_) {
477 // The pending cross-site navigation completed, so show the renderer.
478 CommitPending();
479 } else if (render_frame_host == render_frame_host_) {
480 if (was_caused_by_user_gesture) {
481 // A navigation in the original page has taken place. Cancel the pending
482 // one. Only do it for user gesture originated navigations to prevent
483 // page doing any shenanigans to prevent user from navigating.
484 // See https://code.google.com/p/chromium/issues/detail?id=75195
485 CancelPending();
486 cross_navigation_pending_ = false;
488 } else {
489 // No one else should be sending us DidNavigate in this state.
490 DCHECK(false);
494 void RenderFrameHostManager::DidDisownOpener(
495 RenderFrameHost* render_frame_host) {
496 // Notify all RenderFrameHosts but the one that notified us. This is necessary
497 // in case a process swap has occurred while the message was in flight.
498 for (RenderFrameProxyHostMap::iterator iter = proxy_hosts_.begin();
499 iter != proxy_hosts_.end();
500 ++iter) {
501 DCHECK_NE(iter->second->GetSiteInstance(),
502 current_frame_host()->GetSiteInstance());
503 iter->second->DisownOpener();
506 if (render_frame_host_.get() != render_frame_host)
507 render_frame_host_->DisownOpener();
509 if (pending_render_frame_host_ &&
510 pending_render_frame_host_.get() != render_frame_host) {
511 pending_render_frame_host_->DisownOpener();
515 void RenderFrameHostManager::RendererProcessClosing(
516 RenderProcessHost* render_process_host) {
517 // Remove any swapped out RVHs from this process, so that we don't try to
518 // swap them back in while the process is exiting. Start by finding them,
519 // since there could be more than one.
520 std::list<int> ids_to_remove;
521 // Do not remove proxies in the dead process that still have active frame
522 // count though, we just reset them to be uninitialized.
523 std::list<int> ids_to_keep;
524 for (RenderFrameProxyHostMap::iterator iter = proxy_hosts_.begin();
525 iter != proxy_hosts_.end();
526 ++iter) {
527 RenderFrameProxyHost* proxy = iter->second;
528 if (proxy->GetProcess() != render_process_host)
529 continue;
531 if (static_cast<SiteInstanceImpl*>(proxy->GetSiteInstance())
532 ->active_frame_count() >= 1U) {
533 ids_to_keep.push_back(iter->first);
534 } else {
535 ids_to_remove.push_back(iter->first);
539 // Now delete them.
540 while (!ids_to_remove.empty()) {
541 delete proxy_hosts_[ids_to_remove.back()];
542 proxy_hosts_.erase(ids_to_remove.back());
543 ids_to_remove.pop_back();
546 while (!ids_to_keep.empty()) {
547 frame_tree_node_->frame_tree()->ForEach(
548 base::Bind(
549 &RenderFrameHostManager::ResetProxiesInSiteInstance,
550 ids_to_keep.back()));
551 ids_to_keep.pop_back();
555 void RenderFrameHostManager::SwapOutOldFrame(
556 scoped_ptr<RenderFrameHostImpl> old_render_frame_host) {
557 TRACE_EVENT1("navigation", "RenderFrameHostManager::SwapOutOldFrame",
558 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
560 // Tell the renderer to suppress any further modal dialogs so that we can swap
561 // it out. This must be done before canceling any current dialog, in case
562 // there is a loop creating additional dialogs.
563 // TODO(creis): Handle modal dialogs in subframe processes.
564 old_render_frame_host->render_view_host()->SuppressDialogsUntilSwapOut();
566 // Now close any modal dialogs that would prevent us from swapping out. This
567 // must be done separately from SwapOut, so that the PageGroupLoadDeferrer is
568 // no longer on the stack when we send the SwapOut message.
569 delegate_->CancelModalDialogsForRenderManager();
571 // If the old RFH is not live, just return as there is no further work to do.
572 // It will be deleted and there will be no proxy created.
573 int32 old_site_instance_id =
574 old_render_frame_host->GetSiteInstance()->GetId();
575 if (!old_render_frame_host->IsRenderFrameLive()) {
576 ShutdownRenderFrameProxyHostsInSiteInstance(old_site_instance_id);
577 return;
580 // If there are no active frames besides this one, we can delete the old
581 // RenderFrameHost once it runs its unload handler, without replacing it with
582 // a proxy.
583 size_t active_frame_count =
584 old_render_frame_host->GetSiteInstance()->active_frame_count();
585 if (active_frame_count <= 1) {
586 // Tell the old RenderFrameHost to swap out, with no proxy to replace it.
587 old_render_frame_host->SwapOut(NULL, true);
588 MoveToPendingDeleteHosts(old_render_frame_host.Pass());
590 // Also clear out any proxies from this SiteInstance, in case this was the
591 // last one keeping other proxies alive.
592 ShutdownRenderFrameProxyHostsInSiteInstance(old_site_instance_id);
594 return;
597 // Otherwise there are active views and we need a proxy for the old RFH.
598 // (There should not be one yet.)
599 CHECK(!GetRenderFrameProxyHost(old_render_frame_host->GetSiteInstance()));
600 RenderFrameProxyHost* proxy = new RenderFrameProxyHost(
601 old_render_frame_host->GetSiteInstance(), frame_tree_node_);
602 CHECK(proxy_hosts_.insert(std::make_pair(old_site_instance_id, proxy)).second)
603 << "Inserting a duplicate item.";
605 // Tell the old RenderFrameHost to swap out and be replaced by the proxy.
606 old_render_frame_host->SwapOut(proxy, true);
608 // SwapOut creates a RenderFrameProxy, so set the proxy to be initialized.
609 proxy->set_render_frame_proxy_created(true);
611 bool is_main_frame = frame_tree_node_->IsMainFrame();
612 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
613 switches::kSitePerProcess) &&
614 !is_main_frame) {
615 // In --site-per-process, subframes delete their RFH rather than storing it
616 // in the proxy. Schedule it for deletion once the SwapOutACK comes in.
617 // TODO(creis): This will be the default when we remove swappedout://.
618 MoveToPendingDeleteHosts(old_render_frame_host.Pass());
619 } else {
620 // We shouldn't get here for subframes, since we only swap subframes when
621 // --site-per-process is used.
622 DCHECK(is_main_frame);
624 // The old RenderFrameHost will stay alive inside the proxy so that existing
625 // JavaScript window references to it stay valid.
626 proxy->TakeFrameHostOwnership(old_render_frame_host.Pass());
630 void RenderFrameHostManager::DiscardUnusedFrame(
631 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
632 // TODO(carlosk): this code is very similar to what can be found in
633 // SwapOutOldFrame and we should see that these are unified at some point.
635 // If the SiteInstance for the pending RFH is being used by others don't
636 // delete the RFH. Just swap it out and it can be reused at a later point.
637 SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance();
638 if (site_instance->HasSite() && site_instance->active_frame_count() > 1) {
639 // Any currently suspended navigations are no longer needed.
640 render_frame_host->CancelSuspendedNavigations();
642 RenderFrameProxyHost* proxy =
643 new RenderFrameProxyHost(site_instance, frame_tree_node_);
644 proxy_hosts_[site_instance->GetId()] = proxy;
646 // Check if the RenderFrameHost is already swapped out, to avoid swapping it
647 // out again.
648 if (!render_frame_host->is_swapped_out())
649 render_frame_host->SwapOut(proxy, false);
651 if (frame_tree_node_->IsMainFrame())
652 proxy->TakeFrameHostOwnership(render_frame_host.Pass());
653 } else {
654 // We won't be coming back, so delete this one.
655 render_frame_host.reset();
659 void RenderFrameHostManager::MoveToPendingDeleteHosts(
660 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
661 // |render_frame_host| will be deleted when its SwapOut ACK is received, or
662 // when the timer times out, or when the RFHM itself is deleted (whichever
663 // comes first).
664 pending_delete_hosts_.push_back(
665 linked_ptr<RenderFrameHostImpl>(render_frame_host.release()));
668 bool RenderFrameHostManager::IsPendingDeletion(
669 RenderFrameHostImpl* render_frame_host) {
670 for (const auto& rfh : pending_delete_hosts_) {
671 if (rfh == render_frame_host)
672 return true;
674 return false;
677 bool RenderFrameHostManager::DeleteFromPendingList(
678 RenderFrameHostImpl* render_frame_host) {
679 for (RFHPendingDeleteList::iterator iter = pending_delete_hosts_.begin();
680 iter != pending_delete_hosts_.end();
681 iter++) {
682 if (*iter == render_frame_host) {
683 pending_delete_hosts_.erase(iter);
684 return true;
687 return false;
690 void RenderFrameHostManager::ResetProxyHosts() {
691 STLDeleteValues(&proxy_hosts_);
694 // PlzNavigate
695 void RenderFrameHostManager::BeginNavigation(const NavigationRequest& request) {
696 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
697 switches::kEnableBrowserSideNavigation));
698 // Clean up any state in case there's an ongoing navigation.
699 // TODO(carlosk): remove this cleanup here once we properly cancel ongoing
700 // navigations.
701 CleanUpNavigation();
703 RenderFrameHostImpl* dest_rfh = GetFrameHostForNavigation(request);
704 DCHECK(dest_rfh);
707 // PlzNavigate
708 RenderFrameHostImpl* RenderFrameHostManager::GetFrameHostForNavigation(
709 const NavigationRequest& request) {
710 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
711 switches::kEnableBrowserSideNavigation));
713 SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance();
715 scoped_refptr<SiteInstance> dest_site_instance = GetSiteInstanceForNavigation(
716 request.common_params().url, request.source_site_instance(),
717 request.dest_site_instance(), request.common_params().transition,
718 request.restore_type() != NavigationEntryImpl::RESTORE_NONE,
719 request.is_view_source());
720 // The appropriate RenderFrameHost to commit the navigation.
721 RenderFrameHostImpl* navigation_rfh = nullptr;
723 // TODO(carlosk): do not swap processes for renderer initiated navigations
724 // (see crbug.com/440266).
725 if (current_site_instance == dest_site_instance.get() ||
726 (!frame_tree_node_->IsMainFrame() &&
727 !base::CommandLine::ForCurrentProcess()->HasSwitch(
728 switches::kSitePerProcess))) {
729 // Reuse the current RFH if its SiteInstance matches the the navigation's
730 // or if this is a subframe navigation. We only swap RFHs for subframes when
731 // --site-per-process is enabled.
732 CleanUpNavigation();
733 navigation_rfh = render_frame_host_.get();
735 // As SiteInstances are the same, check if the WebUI should be reused.
736 const NavigationEntry* current_navigation_entry =
737 delegate_->GetLastCommittedNavigationEntryForRenderManager();
738 bool should_reuse_web_ui_ = ShouldReuseWebUI(current_navigation_entry,
739 request.common_params().url);
740 if (!should_reuse_web_ui_) {
741 speculative_web_ui_ = CreateWebUI(request.common_params().url,
742 request.bindings());
743 // Make sure the current RenderViewHost has the right bindings.
744 if (speculative_web_ui() &&
745 !render_frame_host_->GetProcess()->IsIsolatedGuest()) {
746 render_frame_host_->render_view_host()->AllowBindings(
747 speculative_web_ui()->GetBindings());
750 } else {
751 // If the SiteInstance for the final URL doesn't match the one from the
752 // speculatively created RenderFrameHost, create a new RenderFrameHost using
753 // this new SiteInstance.
754 if (!speculative_render_frame_host_ ||
755 speculative_render_frame_host_->GetSiteInstance() !=
756 dest_site_instance.get()) {
757 CleanUpNavigation();
758 bool success = CreateSpeculativeRenderFrameHost(
759 request.common_params().url, current_site_instance,
760 dest_site_instance.get(), request.bindings());
761 DCHECK(success);
763 DCHECK(speculative_render_frame_host_);
764 navigation_rfh = speculative_render_frame_host_.get();
766 // Check if our current RFH is live.
767 if (!render_frame_host_->IsRenderFrameLive()) {
768 // The current RFH is not live. There's no reason to sit around with a
769 // sad tab or a newly created RFH while we wait for the navigation to
770 // complete. Just switch to the speculative RFH now and go back to non
771 // cross-navigating (Note that we don't care about on{before}unload
772 // handlers if the current RFH isn't live.)
773 CommitPending();
776 DCHECK(navigation_rfh &&
777 (navigation_rfh == render_frame_host_.get() ||
778 navigation_rfh == speculative_render_frame_host_.get()));
780 // If the RenderFrame that needs to navigate is not live (its process was just
781 // created or has crashed), initialize it.
782 if (!navigation_rfh->IsRenderFrameLive()) {
783 // Recreate the opener chain.
784 int opener_route_id = delegate_->CreateOpenerRenderViewsForRenderManager(
785 navigation_rfh->GetSiteInstance());
786 if (!InitRenderView(navigation_rfh->render_view_host(), opener_route_id,
787 MSG_ROUTING_NONE, frame_tree_node_->IsMainFrame())) {
788 return nullptr;
792 cross_navigation_pending_ = navigation_rfh != render_frame_host_.get();
793 return navigation_rfh;
796 // PlzNavigate
797 void RenderFrameHostManager::CleanUpNavigation() {
798 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
799 switches::kEnableBrowserSideNavigation));
800 speculative_web_ui_.reset();
801 should_reuse_web_ui_ = false;
802 if (speculative_render_frame_host_)
803 DiscardUnusedFrame(UnsetSpeculativeRenderFrameHost());
806 // PlzNavigate
807 scoped_ptr<RenderFrameHostImpl>
808 RenderFrameHostManager::UnsetSpeculativeRenderFrameHost() {
809 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
810 switches::kEnableBrowserSideNavigation));
811 speculative_render_frame_host_->GetProcess()->RemovePendingView();
812 return speculative_render_frame_host_.Pass();
815 void RenderFrameHostManager::OnDidStartLoading() {
816 for (const auto& pair : proxy_hosts_) {
817 pair.second->Send(
818 new FrameMsg_DidStartLoading(pair.second->GetRoutingID()));
822 void RenderFrameHostManager::OnDidStopLoading() {
823 for (const auto& pair : proxy_hosts_) {
824 pair.second->Send(new FrameMsg_DidStopLoading(pair.second->GetRoutingID()));
828 void RenderFrameHostManager::Observe(
829 int type,
830 const NotificationSource& source,
831 const NotificationDetails& details) {
832 switch (type) {
833 case NOTIFICATION_RENDERER_PROCESS_CLOSED:
834 case NOTIFICATION_RENDERER_PROCESS_CLOSING:
835 RendererProcessClosing(
836 Source<RenderProcessHost>(source).ptr());
837 break;
839 default:
840 NOTREACHED();
844 // static
845 bool RenderFrameHostManager::ClearProxiesInSiteInstance(
846 int32 site_instance_id,
847 FrameTreeNode* node) {
848 RenderFrameProxyHostMap::iterator iter =
849 node->render_manager()->proxy_hosts_.find(site_instance_id);
850 if (iter != node->render_manager()->proxy_hosts_.end()) {
851 RenderFrameProxyHost* proxy = iter->second;
852 // Delete the proxy. If it is for a main frame (and thus the RFH is stored
853 // in the proxy) and it was still pending swap out, move the RFH to the
854 // pending deletion list first.
855 if (node->IsMainFrame() &&
856 proxy->render_frame_host()->rfh_state() ==
857 RenderFrameHostImpl::STATE_PENDING_SWAP_OUT) {
858 scoped_ptr<RenderFrameHostImpl> swapped_out_rfh =
859 proxy->PassFrameHostOwnership();
860 node->render_manager()->MoveToPendingDeleteHosts(swapped_out_rfh.Pass());
862 delete proxy;
863 node->render_manager()->proxy_hosts_.erase(site_instance_id);
866 return true;
869 // static.
870 bool RenderFrameHostManager::ResetProxiesInSiteInstance(int32 site_instance_id,
871 FrameTreeNode* node) {
872 RenderFrameProxyHostMap::iterator iter =
873 node->render_manager()->proxy_hosts_.find(site_instance_id);
874 if (iter != node->render_manager()->proxy_hosts_.end())
875 iter->second->set_render_frame_proxy_created(false);
877 return true;
880 bool RenderFrameHostManager::ShouldTransitionCrossSite() {
881 // True for --site-per-process, which overrides both kSingleProcess and
882 // kProcessPerTab.
883 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
884 switches::kSitePerProcess))
885 return true;
887 // False in the single-process mode, as it makes RVHs to accumulate
888 // in swapped_out_hosts_.
889 // True if we are using process-per-site-instance (default) or
890 // process-per-site (kProcessPerSite).
891 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
892 switches::kSingleProcess) &&
893 !base::CommandLine::ForCurrentProcess()->HasSwitch(
894 switches::kProcessPerTab);
897 bool RenderFrameHostManager::ShouldSwapBrowsingInstancesForNavigation(
898 const GURL& current_effective_url,
899 bool current_is_view_source_mode,
900 SiteInstance* new_site_instance,
901 const GURL& new_effective_url,
902 bool new_is_view_source_mode) const {
903 // If new_entry already has a SiteInstance, assume it is correct. We only
904 // need to force a swap if it is in a different BrowsingInstance.
905 if (new_site_instance) {
906 return !new_site_instance->IsRelatedSiteInstance(
907 render_frame_host_->GetSiteInstance());
910 // Check for reasons to swap processes even if we are in a process model that
911 // doesn't usually swap (e.g., process-per-tab). Any time we return true,
912 // the new_entry will be rendered in a new SiteInstance AND BrowsingInstance.
913 BrowserContext* browser_context =
914 delegate_->GetControllerForRenderManager().GetBrowserContext();
916 // Don't force a new BrowsingInstance for debug URLs that are handled in the
917 // renderer process, like javascript: or chrome://crash.
918 if (IsRendererDebugURL(new_effective_url))
919 return false;
921 // For security, we should transition between processes when one is a Web UI
922 // page and one isn't.
923 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
924 render_frame_host_->GetProcess()->GetID()) ||
925 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
926 browser_context, current_effective_url)) {
927 // If so, force a swap if destination is not an acceptable URL for Web UI.
928 // Here, data URLs are never allowed.
929 if (!WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
930 browser_context, new_effective_url)) {
931 return true;
933 } else {
934 // Force a swap if it's a Web UI URL.
935 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
936 browser_context, new_effective_url)) {
937 return true;
941 // Check with the content client as well. Important to pass
942 // current_effective_url here, which uses the SiteInstance's site if there is
943 // no current_entry.
944 if (GetContentClient()->browser()->ShouldSwapBrowsingInstancesForNavigation(
945 render_frame_host_->GetSiteInstance(),
946 current_effective_url, new_effective_url)) {
947 return true;
950 // We can't switch a RenderView between view source and non-view source mode
951 // without screwing up the session history sometimes (when navigating between
952 // "view-source:http://foo.com/" and "http://foo.com/", Blink doesn't treat
953 // it as a new navigation). So require a BrowsingInstance switch.
954 if (current_is_view_source_mode != new_is_view_source_mode)
955 return true;
957 return false;
960 bool RenderFrameHostManager::ShouldReuseWebUI(
961 const NavigationEntry* current_entry,
962 const GURL& new_url) const {
963 NavigationControllerImpl& controller =
964 delegate_->GetControllerForRenderManager();
965 return current_entry && web_ui_.get() &&
966 (WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
967 controller.GetBrowserContext(), current_entry->GetURL()) ==
968 WebUIControllerFactoryRegistry::GetInstance()->GetWebUIType(
969 controller.GetBrowserContext(), new_url));
972 SiteInstance* RenderFrameHostManager::GetSiteInstanceForNavigation(
973 const GURL& dest_url,
974 SiteInstance* source_instance,
975 SiteInstance* dest_instance,
976 ui::PageTransition transition,
977 bool dest_is_restore,
978 bool dest_is_view_source_mode) {
979 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
980 SiteInstance* new_instance = current_instance;
982 // We do not currently swap processes for navigations in webview tag guests.
983 if (current_instance->GetSiteURL().SchemeIs(kGuestScheme))
984 return current_instance;
986 // Determine if we need a new BrowsingInstance for this entry. If true, this
987 // implies that it will get a new SiteInstance (and likely process), and that
988 // other tabs in the current BrowsingInstance will be unable to script it.
989 // This is used for cases that require a process swap even in the
990 // process-per-tab model, such as WebUI pages.
991 // TODO(clamy): Remove the dependency on the current entry.
992 const NavigationEntry* current_entry =
993 delegate_->GetLastCommittedNavigationEntryForRenderManager();
994 BrowserContext* browser_context =
995 delegate_->GetControllerForRenderManager().GetBrowserContext();
996 const GURL& current_effective_url = current_entry ?
997 SiteInstanceImpl::GetEffectiveURL(browser_context,
998 current_entry->GetURL()) :
999 render_frame_host_->GetSiteInstance()->GetSiteURL();
1000 bool current_is_view_source_mode = current_entry ?
1001 current_entry->IsViewSourceMode() : dest_is_view_source_mode;
1002 bool force_swap = ShouldSwapBrowsingInstancesForNavigation(
1003 current_effective_url,
1004 current_is_view_source_mode,
1005 dest_instance,
1006 SiteInstanceImpl::GetEffectiveURL(browser_context, dest_url),
1007 dest_is_view_source_mode);
1008 if (ShouldTransitionCrossSite() || force_swap) {
1009 new_instance = GetSiteInstanceForURL(
1010 dest_url, source_instance, current_instance, dest_instance,
1011 transition, dest_is_restore, dest_is_view_source_mode, force_swap);
1014 // If force_swap is true, we must use a different SiteInstance. If we didn't,
1015 // we would have two RenderFrameHosts in the same SiteInstance and the same
1016 // frame, resulting in page_id conflicts for their NavigationEntries.
1017 if (force_swap)
1018 CHECK_NE(new_instance, current_instance);
1019 return new_instance;
1022 SiteInstance* RenderFrameHostManager::GetSiteInstanceForURL(
1023 const GURL& dest_url,
1024 SiteInstance* source_instance,
1025 SiteInstance* current_instance,
1026 SiteInstance* dest_instance,
1027 ui::PageTransition transition,
1028 bool dest_is_restore,
1029 bool dest_is_view_source_mode,
1030 bool force_browsing_instance_swap) {
1031 NavigationControllerImpl& controller =
1032 delegate_->GetControllerForRenderManager();
1033 BrowserContext* browser_context = controller.GetBrowserContext();
1035 // If the entry has an instance already we should use it.
1036 if (dest_instance) {
1037 // If we are forcing a swap, this should be in a different BrowsingInstance.
1038 if (force_browsing_instance_swap) {
1039 CHECK(!dest_instance->IsRelatedSiteInstance(
1040 render_frame_host_->GetSiteInstance()));
1042 return dest_instance;
1045 // If a swap is required, we need to force the SiteInstance AND
1046 // BrowsingInstance to be different ones, using CreateForURL.
1047 if (force_browsing_instance_swap)
1048 return SiteInstance::CreateForURL(browser_context, dest_url);
1050 // (UGLY) HEURISTIC, process-per-site only:
1052 // If this navigation is generated, then it probably corresponds to a search
1053 // query. Given that search results typically lead to users navigating to
1054 // other sites, we don't really want to use the search engine hostname to
1055 // determine the site instance for this navigation.
1057 // NOTE: This can be removed once we have a way to transition between
1058 // RenderViews in response to a link click.
1060 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1061 switches::kProcessPerSite) &&
1062 ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_GENERATED)) {
1063 return current_instance;
1066 SiteInstanceImpl* current_site_instance =
1067 static_cast<SiteInstanceImpl*>(current_instance);
1069 // If we haven't used our SiteInstance (and thus RVH) yet, then we can use it
1070 // for this entry. We won't commit the SiteInstance to this site until the
1071 // navigation commits (in DidNavigate), unless the navigation entry was
1072 // restored or it's a Web UI as described below.
1073 if (!current_site_instance->HasSite()) {
1074 // If we've already created a SiteInstance for our destination, we don't
1075 // want to use this unused SiteInstance; use the existing one. (We don't
1076 // do this check if the current_instance has a site, because for now, we
1077 // want to compare against the current URL and not the SiteInstance's site.
1078 // In this case, there is no current URL, so comparing against the site is
1079 // ok. See additional comments below.)
1081 // Also, if the URL should use process-per-site mode and there is an
1082 // existing process for the site, we should use it. We can call
1083 // GetRelatedSiteInstance() for this, which will eagerly set the site and
1084 // thus use the correct process.
1085 bool use_process_per_site =
1086 RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) &&
1087 RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url);
1088 if (current_site_instance->HasRelatedSiteInstance(dest_url) ||
1089 use_process_per_site) {
1090 return current_site_instance->GetRelatedSiteInstance(dest_url);
1093 // For extensions, Web UI URLs (such as the new tab page), and apps we do
1094 // not want to use the current_instance if it has no site, since it will
1095 // have a RenderProcessHost of PRIV_NORMAL. Create a new SiteInstance for
1096 // this URL instead (with the correct process type).
1097 if (current_site_instance->HasWrongProcessForURL(dest_url))
1098 return current_site_instance->GetRelatedSiteInstance(dest_url);
1100 // View-source URLs must use a new SiteInstance and BrowsingInstance.
1101 // TODO(nasko): This is the same condition as later in the function. This
1102 // should be taken into account when refactoring this method as part of
1103 // http://crbug.com/123007.
1104 if (dest_is_view_source_mode)
1105 return SiteInstance::CreateForURL(browser_context, dest_url);
1107 // If we are navigating from a blank SiteInstance to a WebUI, make sure we
1108 // create a new SiteInstance.
1109 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1110 browser_context, dest_url)) {
1111 return SiteInstance::CreateForURL(browser_context, dest_url);
1114 // Normally the "site" on the SiteInstance is set lazily when the load
1115 // actually commits. This is to support better process sharing in case
1116 // the site redirects to some other site: we want to use the destination
1117 // site in the site instance.
1119 // In the case of session restore, as it loads all the pages immediately
1120 // we need to set the site first, otherwise after a restore none of the
1121 // pages would share renderers in process-per-site.
1123 // The embedder can request some urls never to be assigned to SiteInstance
1124 // through the ShouldAssignSiteForURL() content client method, so that
1125 // renderers created for particular chrome urls (e.g. the chrome-native://
1126 // scheme) can be reused for subsequent navigations in the same WebContents.
1127 // See http://crbug.com/386542.
1128 if (dest_is_restore &&
1129 GetContentClient()->browser()->ShouldAssignSiteForURL(dest_url)) {
1130 current_site_instance->SetSite(dest_url);
1133 return current_site_instance;
1136 // Otherwise, only create a new SiteInstance for a cross-site navigation.
1138 // TODO(creis): Once we intercept links and script-based navigations, we
1139 // will be able to enforce that all entries in a SiteInstance actually have
1140 // the same site, and it will be safe to compare the URL against the
1141 // SiteInstance's site, as follows:
1142 // const GURL& current_url = current_instance->site();
1143 // For now, though, we're in a hybrid model where you only switch
1144 // SiteInstances if you type in a cross-site URL. This means we have to
1145 // compare the entry's URL to the last committed entry's URL.
1146 NavigationEntry* current_entry = controller.GetLastCommittedEntry();
1147 if (interstitial_page_) {
1148 // The interstitial is currently the last committed entry, but we want to
1149 // compare against the last non-interstitial entry.
1150 current_entry = controller.GetEntryAtOffset(-1);
1153 // View-source URLs must use a new SiteInstance and BrowsingInstance.
1154 // We don't need a swap when going from view-source to a debug URL like
1155 // chrome://crash, however.
1156 // TODO(creis): Refactor this method so this duplicated code isn't needed.
1157 // See http://crbug.com/123007.
1158 if (current_entry &&
1159 current_entry->IsViewSourceMode() != dest_is_view_source_mode &&
1160 !IsRendererDebugURL(dest_url)) {
1161 return SiteInstance::CreateForURL(browser_context, dest_url);
1164 // Use the source SiteInstance in case of data URLs or about:blank pages,
1165 // because the content is then controlled and/or scriptable by the source
1166 // SiteInstance.
1167 GURL about_blank(url::kAboutBlankURL);
1168 if (source_instance &&
1169 (dest_url == about_blank || dest_url.scheme() == url::kDataScheme))
1170 return source_instance;
1172 // Use the current SiteInstance for same site navigations, as long as the
1173 // process type is correct. (The URL may have been installed as an app since
1174 // the last time we visited it.)
1175 const GURL& current_url =
1176 GetCurrentURLForSiteInstance(current_instance, current_entry);
1177 if (SiteInstance::IsSameWebSite(browser_context, current_url, dest_url) &&
1178 !current_site_instance->HasWrongProcessForURL(dest_url)) {
1179 return current_instance;
1182 // Start the new renderer in a new SiteInstance, but in the current
1183 // BrowsingInstance. It is important to immediately give this new
1184 // SiteInstance to a RenderViewHost (if it is different than our current
1185 // SiteInstance), so that it is ref counted. This will happen in
1186 // CreateRenderView.
1187 return current_instance->GetRelatedSiteInstance(dest_url);
1190 const GURL& RenderFrameHostManager::GetCurrentURLForSiteInstance(
1191 SiteInstance* current_instance, NavigationEntry* current_entry) {
1192 // If this is a subframe that is potentially out of process from its parent,
1193 // don't consider using current_entry's url for SiteInstance selection, since
1194 // current_entry's url is for the main frame and may be in a different site
1195 // than this frame.
1196 // TODO(creis): Remove this when we can check the FrameNavigationEntry's url.
1197 // See http://crbug.com/369654
1198 if (!frame_tree_node_->IsMainFrame() &&
1199 base::CommandLine::ForCurrentProcess()->HasSwitch(
1200 switches::kSitePerProcess))
1201 return frame_tree_node_->current_url();
1203 // If there is no last non-interstitial entry (and current_instance already
1204 // has a site), then we must have been opened from another tab. We want
1205 // to compare against the URL of the page that opened us, but we can't
1206 // get to it directly. The best we can do is check against the site of
1207 // the SiteInstance. This will be correct when we intercept links and
1208 // script-based navigations, but for now, it could place some pages in a
1209 // new process unnecessarily. We should only hit this case if a page tries
1210 // to open a new tab to an interstitial-inducing URL, and then navigates
1211 // the page to a different same-site URL. (This seems very unlikely in
1212 // practice.)
1213 if (current_entry)
1214 return current_entry->GetURL();
1215 return current_instance->GetSiteURL();
1218 void RenderFrameHostManager::CreatePendingRenderFrameHost(
1219 SiteInstance* old_instance,
1220 SiteInstance* new_instance,
1221 bool is_main_frame) {
1222 int create_render_frame_flags = 0;
1223 if (is_main_frame)
1224 create_render_frame_flags |= CREATE_RF_FOR_MAIN_FRAME_NAVIGATION;
1226 if (delegate_->IsHidden())
1227 create_render_frame_flags |= CREATE_RF_HIDDEN;
1229 int opener_route_id = CreateOpenerRenderViewsIfNeeded(
1230 old_instance, new_instance, &create_render_frame_flags);
1232 if (pending_render_frame_host_)
1233 CancelPending();
1235 // Create a non-swapped-out RFH with the given opener.
1236 pending_render_frame_host_ =
1237 CreateRenderFrame(new_instance, pending_web_ui(), opener_route_id,
1238 create_render_frame_flags, nullptr);
1241 int RenderFrameHostManager::CreateOpenerRenderViewsIfNeeded(
1242 SiteInstance* old_instance,
1243 SiteInstance* new_instance,
1244 int* create_render_frame_flags) {
1245 int opener_route_id = MSG_ROUTING_NONE;
1246 if (new_instance->IsRelatedSiteInstance(old_instance)) {
1247 opener_route_id =
1248 delegate_->CreateOpenerRenderViewsForRenderManager(new_instance);
1249 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1250 switches::kSitePerProcess)) {
1251 // Ensure that the frame tree has RenderFrameProxyHosts for the new
1252 // SiteInstance in all nodes except the current one.
1253 frame_tree_node_->frame_tree()->CreateProxiesForSiteInstance(
1254 frame_tree_node_, new_instance);
1255 // RenderFrames in different processes from their parent RenderFrames
1256 // in the frame tree require RenderWidgets for rendering and processing
1257 // input events.
1258 if (frame_tree_node_->parent() &&
1259 frame_tree_node_->parent()->current_frame_host()->GetSiteInstance() !=
1260 new_instance)
1261 *create_render_frame_flags |= CREATE_RF_NEEDS_RENDER_WIDGET_HOST;
1264 return opener_route_id;
1267 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::CreateRenderFrameHost(
1268 SiteInstance* site_instance,
1269 int view_routing_id,
1270 int frame_routing_id,
1271 int flags) {
1272 if (frame_routing_id == MSG_ROUTING_NONE)
1273 frame_routing_id = site_instance->GetProcess()->GetNextRoutingID();
1275 bool swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
1276 bool hidden = !!(flags & CREATE_RF_HIDDEN);
1278 // Create a RVH for main frames, or find the existing one for subframes.
1279 FrameTree* frame_tree = frame_tree_node_->frame_tree();
1280 RenderViewHostImpl* render_view_host = nullptr;
1281 if (frame_tree_node_->IsMainFrame()) {
1282 render_view_host = frame_tree->CreateRenderViewHost(
1283 site_instance, view_routing_id, frame_routing_id, swapped_out, hidden);
1284 } else {
1285 render_view_host = frame_tree->GetRenderViewHost(site_instance);
1287 CHECK(render_view_host);
1290 // TODO(creis): Pass hidden to RFH.
1291 scoped_ptr<RenderFrameHostImpl> render_frame_host = make_scoped_ptr(
1292 RenderFrameHostFactory::Create(
1293 site_instance, render_view_host, render_frame_delegate_,
1294 render_widget_delegate_, frame_tree, frame_tree_node_,
1295 frame_routing_id, flags).release());
1296 return render_frame_host.Pass();
1299 // PlzNavigate
1300 bool RenderFrameHostManager::CreateSpeculativeRenderFrameHost(
1301 const GURL& url,
1302 SiteInstance* old_instance,
1303 SiteInstance* new_instance,
1304 int bindings) {
1305 CHECK(new_instance);
1306 CHECK_NE(old_instance, new_instance);
1307 CHECK(!should_reuse_web_ui_);
1309 // Note: |speculative_web_ui_| must be initialized before starting the
1310 // |speculative_render_frame_host_| creation steps otherwise the WebUI
1311 // won't be properly initialized.
1312 speculative_web_ui_ = CreateWebUI(url, bindings);
1314 int create_render_frame_flags = 0;
1315 int opener_route_id =
1316 CreateOpenerRenderViewsIfNeeded(old_instance, new_instance,
1317 &create_render_frame_flags);
1319 if (frame_tree_node_->IsMainFrame())
1320 create_render_frame_flags |= CREATE_RF_FOR_MAIN_FRAME_NAVIGATION;
1321 if (delegate_->IsHidden())
1322 create_render_frame_flags |= CREATE_RF_HIDDEN;
1323 speculative_render_frame_host_ =
1324 CreateRenderFrame(new_instance, speculative_web_ui_.get(),
1325 opener_route_id, create_render_frame_flags, nullptr);
1327 if (!speculative_render_frame_host_) {
1328 speculative_web_ui_.reset();
1329 return false;
1331 return true;
1334 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::CreateRenderFrame(
1335 SiteInstance* instance,
1336 WebUIImpl* web_ui,
1337 int opener_route_id,
1338 int flags,
1339 int* view_routing_id_ptr) {
1340 bool swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
1341 CHECK(instance);
1342 // Swapped out views should always be hidden.
1343 DCHECK(!swapped_out || (flags & CREATE_RF_HIDDEN));
1345 // TODO(nasko): Remove the following CHECK once cross-site navigation no
1346 // longer relies on swapped out RFH for the top-level frame.
1347 if (!frame_tree_node_->IsMainFrame())
1348 CHECK(!swapped_out);
1350 scoped_ptr<RenderFrameHostImpl> new_render_frame_host;
1351 bool success = true;
1352 if (view_routing_id_ptr)
1353 *view_routing_id_ptr = MSG_ROUTING_NONE;
1355 // We are creating a pending, speculative or swapped out RFH here. We should
1356 // never create it in the same SiteInstance as our current RFH.
1357 CHECK_NE(render_frame_host_->GetSiteInstance(), instance);
1359 // Check if we've already created an RFH for this SiteInstance. If so, try
1360 // to re-use the existing one, which has already been initialized. We'll
1361 // remove it from the list of proxy hosts below if it will be active.
1362 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1363 if (proxy && proxy->render_frame_host()) {
1364 if (view_routing_id_ptr)
1365 *view_routing_id_ptr = proxy->GetRenderViewHost()->GetRoutingID();
1366 // Delete the existing RenderFrameProxyHost, but reuse the RenderFrameHost.
1367 // Prevent the process from exiting while we're trying to use it.
1368 if (!swapped_out) {
1369 new_render_frame_host = proxy->PassFrameHostOwnership();
1370 new_render_frame_host->GetProcess()->AddPendingView();
1372 proxy_hosts_.erase(instance->GetId());
1373 delete proxy;
1375 // When a new render view is created by the renderer, the new WebContents
1376 // gets a RenderViewHost in the SiteInstance of its opener WebContents.
1377 // If not used in the first navigation, this RVH is swapped out and is not
1378 // granted bindings, so we may need to grant them when swapping it in.
1379 if (web_ui && !new_render_frame_host->GetProcess()->IsIsolatedGuest()) {
1380 int required_bindings = web_ui->GetBindings();
1381 RenderViewHost* render_view_host =
1382 new_render_frame_host->render_view_host();
1383 if ((render_view_host->GetEnabledBindings() & required_bindings) !=
1384 required_bindings) {
1385 render_view_host->AllowBindings(required_bindings);
1389 } else {
1390 // Create a new RenderFrameHost if we don't find an existing one.
1391 new_render_frame_host = CreateRenderFrameHost(instance, MSG_ROUTING_NONE,
1392 MSG_ROUTING_NONE, flags);
1393 RenderViewHostImpl* render_view_host =
1394 new_render_frame_host->render_view_host();
1395 int proxy_routing_id = MSG_ROUTING_NONE;
1397 // Prevent the process from exiting while we're trying to navigate in it.
1398 // Otherwise, if the new RFH is swapped out already, store it.
1399 if (!swapped_out) {
1400 new_render_frame_host->GetProcess()->AddPendingView();
1401 } else {
1402 proxy = new RenderFrameProxyHost(
1403 new_render_frame_host->GetSiteInstance(), frame_tree_node_);
1404 proxy_hosts_[instance->GetId()] = proxy;
1405 proxy_routing_id = proxy->GetRoutingID();
1406 proxy->TakeFrameHostOwnership(new_render_frame_host.Pass());
1409 success =
1410 InitRenderView(render_view_host, opener_route_id, proxy_routing_id,
1411 !!(flags & CREATE_RF_FOR_MAIN_FRAME_NAVIGATION));
1412 if (success) {
1413 if (frame_tree_node_->IsMainFrame()) {
1414 // Don't show the main frame's view until we get a DidNavigate from it.
1415 // Only the RenderViewHost for the top-level RenderFrameHost has a
1416 // RenderWidgetHostView; RenderWidgetHosts for out-of-process iframes
1417 // will be created later and hidden.
1418 if (render_view_host->GetView())
1419 render_view_host->GetView()->Hide();
1420 } else if (!swapped_out) {
1421 // Init the RFH, so a RenderFrame is created in the renderer.
1422 DCHECK(new_render_frame_host.get());
1423 success = InitRenderFrame(new_render_frame_host.get());
1427 if (success) {
1428 if (view_routing_id_ptr)
1429 *view_routing_id_ptr = render_view_host->GetRoutingID();
1433 // Returns the new RFH if it isn't swapped out.
1434 if (success && !swapped_out) {
1435 DCHECK(new_render_frame_host->GetSiteInstance() == instance);
1436 return new_render_frame_host.Pass();
1438 return nullptr;
1441 int RenderFrameHostManager::CreateRenderFrameProxy(SiteInstance* instance) {
1442 // A RenderFrameProxyHost should never be created in the same SiteInstance as
1443 // the current RFH.
1444 CHECK(instance);
1445 CHECK_NE(instance, render_frame_host_->GetSiteInstance());
1447 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1448 if (proxy)
1449 return proxy->GetRoutingID();
1451 proxy = new RenderFrameProxyHost(instance, frame_tree_node_);
1452 proxy_hosts_[instance->GetId()] = proxy;
1453 proxy->InitRenderFrameProxy();
1454 return proxy->GetRoutingID();
1457 void RenderFrameHostManager::EnsureRenderViewInitialized(
1458 FrameTreeNode* source,
1459 RenderViewHostImpl* render_view_host,
1460 SiteInstance* instance) {
1461 DCHECK(frame_tree_node_->IsMainFrame());
1463 if (render_view_host->IsRenderViewLive())
1464 return;
1466 // Recreate the opener chain.
1467 int opener_route_id =
1468 delegate_->CreateOpenerRenderViewsForRenderManager(instance);
1469 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1470 InitRenderView(render_view_host, opener_route_id, proxy->GetRoutingID(),
1471 source->IsMainFrame());
1474 bool RenderFrameHostManager::InitRenderView(
1475 RenderViewHostImpl* render_view_host,
1476 int opener_route_id,
1477 int proxy_routing_id,
1478 bool for_main_frame_navigation) {
1479 // We may have initialized this RenderViewHost for another RenderFrameHost.
1480 if (render_view_host->IsRenderViewLive())
1481 return true;
1483 // If the ongoing navigation is to a WebUI and the RenderView is not in a
1484 // guest process, tell the RenderViewHost about any bindings it will need
1485 // enabled.
1486 WebUIImpl* dest_web_ui = nullptr;
1487 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1488 switches::kEnableBrowserSideNavigation)) {
1489 dest_web_ui =
1490 should_reuse_web_ui_ ? web_ui_.get() : speculative_web_ui_.get();
1491 } else {
1492 dest_web_ui = pending_web_ui();
1494 if (dest_web_ui && !render_view_host->GetProcess()->IsIsolatedGuest()) {
1495 render_view_host->AllowBindings(dest_web_ui->GetBindings());
1496 } else {
1497 // Ensure that we don't create an unprivileged RenderView in a WebUI-enabled
1498 // process unless it's swapped out.
1499 if (render_view_host->is_active()) {
1500 CHECK(!ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1501 render_view_host->GetProcess()->GetID()));
1505 return delegate_->CreateRenderViewForRenderManager(render_view_host,
1506 opener_route_id,
1507 proxy_routing_id,
1508 for_main_frame_navigation);
1511 bool RenderFrameHostManager::InitRenderFrame(
1512 RenderFrameHostImpl* render_frame_host) {
1513 if (render_frame_host->IsRenderFrameLive())
1514 return true;
1516 int parent_routing_id = MSG_ROUTING_NONE;
1517 int proxy_routing_id = MSG_ROUTING_NONE;
1518 if (frame_tree_node_->parent()) {
1519 parent_routing_id = frame_tree_node_->parent()->render_manager()->
1520 GetRoutingIdForSiteInstance(render_frame_host->GetSiteInstance());
1521 CHECK_NE(parent_routing_id, MSG_ROUTING_NONE);
1523 // Check whether there is an existing proxy for this frame in this
1524 // SiteInstance. If there is, the new RenderFrame needs to be able to find
1525 // the proxy it is replacing, so that it can fully initialize itself.
1526 // NOTE: This is the only time that a RenderFrameProxyHost can be in the same
1527 // SiteInstance as its RenderFrameHost. This is only the case until the
1528 // RenderFrameHost commits, at which point it will replace and delete the
1529 // RenderFrameProxyHost.
1530 RenderFrameProxyHost* existing_proxy =
1531 GetRenderFrameProxyHost(render_frame_host->GetSiteInstance());
1532 if (existing_proxy) {
1533 proxy_routing_id = existing_proxy->GetRoutingID();
1534 CHECK_NE(proxy_routing_id, MSG_ROUTING_NONE);
1535 if (!existing_proxy->is_render_frame_proxy_live())
1536 existing_proxy->InitRenderFrameProxy();
1538 return delegate_->CreateRenderFrameForRenderManager(render_frame_host,
1539 parent_routing_id,
1540 proxy_routing_id);
1543 int RenderFrameHostManager::GetRoutingIdForSiteInstance(
1544 SiteInstance* site_instance) {
1545 if (render_frame_host_->GetSiteInstance() == site_instance)
1546 return render_frame_host_->GetRoutingID();
1548 RenderFrameProxyHostMap::iterator iter =
1549 proxy_hosts_.find(site_instance->GetId());
1550 if (iter != proxy_hosts_.end())
1551 return iter->second->GetRoutingID();
1553 return MSG_ROUTING_NONE;
1556 void RenderFrameHostManager::CommitPending() {
1557 TRACE_EVENT1("navigation", "RenderFrameHostManager::CommitPending",
1558 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
1559 bool browser_side_navigation =
1560 base::CommandLine::ForCurrentProcess()->HasSwitch(
1561 switches::kEnableBrowserSideNavigation);
1562 // First check whether we're going to want to focus the location bar after
1563 // this commit. We do this now because the navigation hasn't formally
1564 // committed yet, so if we've already cleared |pending_web_ui_| the call chain
1565 // this triggers won't be able to figure out what's going on.
1566 bool will_focus_location_bar = delegate_->FocusLocationBarByDefault();
1568 if (!browser_side_navigation) {
1569 DCHECK(!speculative_web_ui_);
1570 // Next commit the Web UI, if any. Either replace |web_ui_| with
1571 // |pending_web_ui_|, or clear |web_ui_| if there is no pending WebUI, or
1572 // leave |web_ui_| as is if reusing it.
1573 DCHECK(!(pending_web_ui_.get() && pending_and_current_web_ui_.get()));
1574 if (pending_web_ui_) {
1575 web_ui_.reset(pending_web_ui_.release());
1576 } else if (!pending_and_current_web_ui_.get()) {
1577 web_ui_.reset();
1578 } else {
1579 DCHECK_EQ(pending_and_current_web_ui_.get(), web_ui_.get());
1580 pending_and_current_web_ui_.reset();
1582 } else {
1583 // PlzNavigate
1584 if (!should_reuse_web_ui_)
1585 web_ui_.reset(speculative_web_ui_.release());
1586 DCHECK(!speculative_web_ui_);
1589 // It's possible for the pending_render_frame_host_ to be nullptr when we
1590 // aren't crossing process boundaries. If so, we just needed to handle the Web
1591 // UI committing above and we're done.
1592 if (!pending_render_frame_host_ && !speculative_render_frame_host_) {
1593 if (will_focus_location_bar)
1594 delegate_->SetFocusToLocationBar(false);
1595 return;
1598 // Remember if the page was focused so we can focus the new renderer in
1599 // that case.
1600 bool focus_render_view = !will_focus_location_bar &&
1601 render_frame_host_->GetView() &&
1602 render_frame_host_->GetView()->HasFocus();
1604 bool is_main_frame = frame_tree_node_->IsMainFrame();
1606 // Swap in the pending or speculative frame and make it active. Also ensure
1607 // the FrameTree stays in sync.
1608 scoped_ptr<RenderFrameHostImpl> old_render_frame_host;
1609 if (!browser_side_navigation) {
1610 DCHECK(!speculative_render_frame_host_);
1611 old_render_frame_host =
1612 SetRenderFrameHost(pending_render_frame_host_.Pass());
1613 } else {
1614 // PlzNavigate
1615 DCHECK(speculative_render_frame_host_);
1616 old_render_frame_host =
1617 SetRenderFrameHost(speculative_render_frame_host_.Pass());
1619 cross_navigation_pending_ = false;
1621 if (is_main_frame)
1622 render_frame_host_->render_view_host()->AttachToFrameTree();
1624 // The process will no longer try to exit, so we can decrement the count.
1625 render_frame_host_->GetProcess()->RemovePendingView();
1627 // Show the new view (or a sad tab) if necessary.
1628 bool new_rfh_has_view = !!render_frame_host_->GetView();
1629 if (!delegate_->IsHidden() && new_rfh_has_view) {
1630 // In most cases, we need to show the new view.
1631 render_frame_host_->GetView()->Show();
1633 if (!new_rfh_has_view) {
1634 // If the view is gone, then this RenderViewHost died while it was hidden.
1635 // We ignored the RenderProcessGone call at the time, so we should send it
1636 // now to make sure the sad tab shows up, etc.
1637 DCHECK(!render_frame_host_->IsRenderFrameLive());
1638 DCHECK(!render_frame_host_->render_view_host()->IsRenderViewLive());
1639 delegate_->RenderProcessGoneFromRenderManager(
1640 render_frame_host_->render_view_host());
1643 // For top-level frames, also hide the old RenderViewHost's view.
1644 // TODO(creis): As long as show/hide are on RVH, we don't want to hide on
1645 // subframe navigations or we will interfere with the top-level frame.
1646 if (is_main_frame && old_render_frame_host->render_view_host()->GetView())
1647 old_render_frame_host->render_view_host()->GetView()->Hide();
1649 // Make sure the size is up to date. (Fix for bug 1079768.)
1650 delegate_->UpdateRenderViewSizeForRenderManager();
1652 if (will_focus_location_bar) {
1653 delegate_->SetFocusToLocationBar(false);
1654 } else if (focus_render_view && render_frame_host_->GetView()) {
1655 render_frame_host_->GetView()->Focus();
1658 // Notify that we've swapped RenderFrameHosts. We do this before shutting down
1659 // the RFH so that we can clean up RendererResources related to the RFH first.
1660 delegate_->NotifySwappedFromRenderManager(
1661 old_render_frame_host.get(), render_frame_host_.get(), is_main_frame);
1663 // Swap out the old frame now that the new one is visible.
1664 // This will swap it out and then put it on the proxy list (if there are other
1665 // active views in its SiteInstance) or schedule it for deletion when the swap
1666 // out ack arrives (or immediately if the process isn't live).
1667 // In the --site-per-process case, old subframe RHFs are not kept alive inside
1668 // the proxy.
1669 SwapOutOldFrame(old_render_frame_host.Pass());
1671 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1672 switches::kSitePerProcess) &&
1673 !is_main_frame) {
1674 // If this is a subframe, it should have a CrossProcessFrameConnector
1675 // created already. Use it to link the new RFH's view to the proxy that
1676 // belongs to the parent frame's SiteInstance.
1677 // Note: We do this after swapping out the old RFH because that may create
1678 // the proxy we're looking for.
1679 RenderFrameProxyHost* proxy_to_parent = GetProxyToParent();
1680 if (proxy_to_parent) {
1681 proxy_to_parent->SetChildRWHView(render_frame_host_->GetView());
1684 // Since the new RenderFrameHost is now committed, there must be no proxies
1685 // for its SiteInstance. Delete any existing ones.
1686 RenderFrameProxyHostMap::iterator iter =
1687 proxy_hosts_.find(render_frame_host_->GetSiteInstance()->GetId());
1688 if (iter != proxy_hosts_.end()) {
1689 delete iter->second;
1690 proxy_hosts_.erase(iter);
1694 // After all is done, there must never be a proxy in the list which has the
1695 // same SiteInstance as the current RenderFrameHost.
1696 CHECK(proxy_hosts_.find(render_frame_host_->GetSiteInstance()->GetId()) ==
1697 proxy_hosts_.end());
1700 void RenderFrameHostManager::ShutdownRenderFrameProxyHostsInSiteInstance(
1701 int32 site_instance_id) {
1702 // First remove any swapped out RFH for this SiteInstance from our own list.
1703 ClearProxiesInSiteInstance(site_instance_id, frame_tree_node_);
1705 // Use the safe RenderWidgetHost iterator for now to find all RenderViewHosts
1706 // in the SiteInstance, then tell their respective FrameTrees to remove all
1707 // RenderFrameProxyHosts corresponding to them.
1708 // TODO(creis): Replace this with a RenderFrameHostIterator that protects
1709 // against use-after-frees if a later element is deleted before getting to it.
1710 scoped_ptr<RenderWidgetHostIterator> widgets(
1711 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
1712 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
1713 if (!widget->IsRenderView())
1714 continue;
1715 RenderViewHostImpl* rvh =
1716 static_cast<RenderViewHostImpl*>(RenderViewHost::From(widget));
1717 if (site_instance_id == rvh->GetSiteInstance()->GetId()) {
1718 // This deletes all RenderFrameHosts using the |rvh|, which then causes
1719 // |rvh| to Shutdown.
1720 FrameTree* tree = rvh->GetDelegate()->GetFrameTree();
1721 tree->ForEach(base::Bind(
1722 &RenderFrameHostManager::ClearProxiesInSiteInstance,
1723 site_instance_id));
1728 RenderFrameHostImpl* RenderFrameHostManager::UpdateStateForNavigate(
1729 const GURL& dest_url,
1730 SiteInstance* source_instance,
1731 SiteInstance* dest_instance,
1732 ui::PageTransition transition,
1733 bool dest_is_restore,
1734 bool dest_is_view_source_mode,
1735 const GlobalRequestID& transferred_request_id,
1736 int bindings) {
1737 // If we are currently navigating cross-process, we want to get back to normal
1738 // and then navigate as usual.
1739 if (cross_navigation_pending_) {
1740 if (pending_render_frame_host_)
1741 CancelPending();
1742 cross_navigation_pending_ = false;
1745 SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
1746 scoped_refptr<SiteInstance> new_instance = GetSiteInstanceForNavigation(
1747 dest_url, source_instance, dest_instance, transition,
1748 dest_is_restore, dest_is_view_source_mode);
1750 const NavigationEntry* current_entry =
1751 delegate_->GetLastCommittedNavigationEntryForRenderManager();
1753 DCHECK(!cross_navigation_pending_);
1755 if (new_instance.get() != current_instance) {
1756 TRACE_EVENT_INSTANT2(
1757 "navigation",
1758 "RenderFrameHostManager::UpdateStateForNavigate:New SiteInstance",
1759 TRACE_EVENT_SCOPE_THREAD,
1760 "current_instance id", current_instance->GetId(),
1761 "new_instance id", new_instance->GetId());
1763 // New SiteInstance: create a pending RFH to navigate.
1765 // This will possibly create (set to nullptr) a Web UI object for the
1766 // pending page. We'll use this later to give the page special access. This
1767 // must happen before the new renderer is created below so it will get
1768 // bindings. It must also happen after the above conditional call to
1769 // CancelPending(), otherwise CancelPending may clear the pending_web_ui_
1770 // and the page will not have its bindings set appropriately.
1771 SetPendingWebUI(dest_url, bindings);
1772 CreatePendingRenderFrameHost(current_instance, new_instance.get(),
1773 frame_tree_node_->IsMainFrame());
1774 if (!pending_render_frame_host_.get()) {
1775 return nullptr;
1778 // Check if our current RFH is live before we set up a transition.
1779 if (!render_frame_host_->IsRenderFrameLive()) {
1780 if (!cross_navigation_pending_) {
1781 // The current RFH is not live. There's no reason to sit around with a
1782 // sad tab or a newly created RFH while we wait for the pending RFH to
1783 // navigate. Just switch to the pending RFH now and go back to non
1784 // cross-navigating (Note that we don't care about on{before}unload
1785 // handlers if the current RFH isn't live.)
1786 CommitPending();
1787 return render_frame_host_.get();
1788 } else {
1789 NOTREACHED();
1790 return render_frame_host_.get();
1793 // Otherwise, it's safe to treat this as a pending cross-site transition.
1795 // We now have a pending RFH.
1796 DCHECK(!cross_navigation_pending_);
1797 cross_navigation_pending_ = true;
1799 // We need to wait until the beforeunload handler has run, unless we are
1800 // transferring an existing request (in which case it has already run).
1801 // Suspend the new render view (i.e., don't let it send the cross-site
1802 // Navigate message) until we hear back from the old renderer's
1803 // beforeunload handler. If the handler returns false, we'll have to
1804 // cancel the request.
1806 DCHECK(!pending_render_frame_host_->are_navigations_suspended());
1807 bool is_transfer = transferred_request_id != GlobalRequestID();
1808 if (is_transfer) {
1809 // We don't need to stop the old renderer or run beforeunload/unload
1810 // handlers, because those have already been done.
1811 DCHECK(cross_site_transferring_request_->request_id() ==
1812 transferred_request_id);
1813 } else {
1814 // Also make sure the old render view stops, in case a load is in
1815 // progress. (We don't want to do this for transfers, since it will
1816 // interrupt the transfer with an unexpected DidStopLoading.)
1817 render_frame_host_->Send(new FrameMsg_Stop(
1818 render_frame_host_->GetRoutingID()));
1819 pending_render_frame_host_->SetNavigationsSuspended(true,
1820 base::TimeTicks());
1821 // Unless we are transferring an existing request, we should now tell the
1822 // old render view to run its beforeunload handler, since it doesn't
1823 // otherwise know that the cross-site request is happening. This will
1824 // trigger a call to OnBeforeUnloadACK with the reply.
1825 render_frame_host_->DispatchBeforeUnload(true);
1828 return pending_render_frame_host_.get();
1831 // Otherwise the same SiteInstance can be used. Navigate render_frame_host_.
1833 // It's possible to swap out the current RFH and then decide to navigate in it
1834 // anyway (e.g., a cross-process navigation that redirects back to the
1835 // original site). In that case, we have a proxy for the current RFH but
1836 // haven't deleted it yet. The new navigation will swap it back in, so we can
1837 // delete the proxy.
1838 DeleteRenderFrameProxyHost(new_instance.get());
1840 if (ShouldReuseWebUI(current_entry, dest_url)) {
1841 pending_web_ui_.reset();
1842 pending_and_current_web_ui_ = web_ui_->AsWeakPtr();
1843 } else {
1844 SetPendingWebUI(dest_url, bindings);
1845 // Make sure the new RenderViewHost has the right bindings.
1846 if (pending_web_ui() &&
1847 !render_frame_host_->GetProcess()->IsIsolatedGuest()) {
1848 render_frame_host_->render_view_host()->AllowBindings(
1849 pending_web_ui()->GetBindings());
1853 if (pending_web_ui() && render_frame_host_->IsRenderFrameLive()) {
1854 pending_web_ui()->GetController()->RenderViewReused(
1855 render_frame_host_->render_view_host());
1858 // The renderer can exit view source mode when any error or cancellation
1859 // happen. We must overwrite to recover the mode.
1860 if (dest_is_view_source_mode) {
1861 render_frame_host_->render_view_host()->Send(
1862 new ViewMsg_EnableViewSourceMode(
1863 render_frame_host_->render_view_host()->GetRoutingID()));
1866 return render_frame_host_.get();
1869 void RenderFrameHostManager::CancelPending() {
1870 TRACE_EVENT1("navigation", "RenderFrameHostManager::CancelPending",
1871 "FrameTreeNode id", frame_tree_node_->frame_tree_node_id());
1872 DiscardUnusedFrame(UnsetPendingRenderFrameHost());
1875 scoped_ptr<RenderFrameHostImpl>
1876 RenderFrameHostManager::UnsetPendingRenderFrameHost() {
1877 scoped_ptr<RenderFrameHostImpl> pending_render_frame_host =
1878 pending_render_frame_host_.Pass();
1880 RenderFrameDevToolsAgentHost::OnCancelPendingNavigation(
1881 pending_render_frame_host.get(),
1882 render_frame_host_.get());
1884 // We no longer need to prevent the process from exiting.
1885 pending_render_frame_host->GetProcess()->RemovePendingView();
1887 pending_web_ui_.reset();
1888 pending_and_current_web_ui_.reset();
1890 return pending_render_frame_host.Pass();
1893 scoped_ptr<RenderFrameHostImpl> RenderFrameHostManager::SetRenderFrameHost(
1894 scoped_ptr<RenderFrameHostImpl> render_frame_host) {
1895 // Swap the two.
1896 scoped_ptr<RenderFrameHostImpl> old_render_frame_host =
1897 render_frame_host_.Pass();
1898 render_frame_host_ = render_frame_host.Pass();
1900 if (frame_tree_node_->IsMainFrame()) {
1901 // Update the count of top-level frames using this SiteInstance. All
1902 // subframes are in the same BrowsingInstance as the main frame, so we only
1903 // count top-level ones. This makes the value easier for consumers to
1904 // interpret.
1905 if (render_frame_host_) {
1906 render_frame_host_->GetSiteInstance()->
1907 IncrementRelatedActiveContentsCount();
1909 if (old_render_frame_host) {
1910 old_render_frame_host->GetSiteInstance()->
1911 DecrementRelatedActiveContentsCount();
1915 return old_render_frame_host.Pass();
1918 bool RenderFrameHostManager::IsRVHOnSwappedOutList(
1919 RenderViewHostImpl* rvh) const {
1920 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(
1921 rvh->GetSiteInstance());
1922 if (!proxy)
1923 return false;
1924 // If there is a proxy without RFH, it is for a subframe in the SiteInstance
1925 // of |rvh|. Subframes should be ignored in this case.
1926 if (!proxy->render_frame_host())
1927 return false;
1928 return IsOnSwappedOutList(proxy->render_frame_host());
1931 bool RenderFrameHostManager::IsOnSwappedOutList(
1932 RenderFrameHostImpl* rfh) const {
1933 if (!rfh->GetSiteInstance())
1934 return false;
1936 RenderFrameProxyHostMap::const_iterator iter = proxy_hosts_.find(
1937 rfh->GetSiteInstance()->GetId());
1938 if (iter == proxy_hosts_.end())
1939 return false;
1941 return iter->second->render_frame_host() == rfh;
1944 RenderViewHostImpl* RenderFrameHostManager::GetSwappedOutRenderViewHost(
1945 SiteInstance* instance) const {
1946 RenderFrameProxyHost* proxy = GetRenderFrameProxyHost(instance);
1947 if (proxy)
1948 return proxy->GetRenderViewHost();
1949 return NULL;
1952 RenderFrameProxyHost* RenderFrameHostManager::GetRenderFrameProxyHost(
1953 SiteInstance* instance) const {
1954 RenderFrameProxyHostMap::const_iterator iter =
1955 proxy_hosts_.find(instance->GetId());
1956 if (iter != proxy_hosts_.end())
1957 return iter->second;
1959 return NULL;
1962 void RenderFrameHostManager::DeleteRenderFrameProxyHost(
1963 SiteInstance* instance) {
1964 RenderFrameProxyHostMap::iterator iter = proxy_hosts_.find(instance->GetId());
1965 if (iter != proxy_hosts_.end()) {
1966 delete iter->second;
1967 proxy_hosts_.erase(iter);
1971 } // namespace content