Add a FrameHostMsg_BeginNavigation IPC
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_manager_unittest.cc
blob7ac3f3727e65ee9b7c8b1bea9d9d35da835e5bd5
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 "base/files/file_path.h"
6 #include "base/strings/utf_string_conversions.h"
7 #include "content/browser/frame_host/cross_site_transferring_request.h"
8 #include "content/browser/frame_host/navigation_controller_impl.h"
9 #include "content/browser/frame_host/navigation_entry_impl.h"
10 #include "content/browser/frame_host/navigation_request.h"
11 #include "content/browser/frame_host/navigator.h"
12 #include "content/browser/frame_host/render_frame_host_manager.h"
13 #include "content/browser/site_instance_impl.h"
14 #include "content/browser/webui/web_ui_controller_factory_registry.h"
15 #include "content/common/view_messages.h"
16 #include "content/public/browser/notification_details.h"
17 #include "content/public/browser/notification_service.h"
18 #include "content/public/browser/notification_source.h"
19 #include "content/public/browser/notification_types.h"
20 #include "content/public/browser/render_process_host.h"
21 #include "content/public/browser/render_widget_host_iterator.h"
22 #include "content/public/browser/web_contents_delegate.h"
23 #include "content/public/browser/web_contents_observer.h"
24 #include "content/public/browser/web_ui_controller.h"
25 #include "content/public/common/bindings_policy.h"
26 #include "content/public/common/javascript_message_type.h"
27 #include "content/public/common/page_transition_types.h"
28 #include "content/public/common/url_constants.h"
29 #include "content/public/common/url_utils.h"
30 #include "content/public/test/mock_render_process_host.h"
31 #include "content/public/test/test_notification_tracker.h"
32 #include "content/test/test_content_browser_client.h"
33 #include "content/test/test_content_client.h"
34 #include "content/test/test_render_view_host.h"
35 #include "content/test/test_web_contents.h"
36 #include "testing/gtest/include/gtest/gtest.h"
38 namespace content {
39 namespace {
41 class RenderFrameHostManagerTestWebUIControllerFactory
42 : public WebUIControllerFactory {
43 public:
44 RenderFrameHostManagerTestWebUIControllerFactory()
45 : should_create_webui_(false) {
47 virtual ~RenderFrameHostManagerTestWebUIControllerFactory() {}
49 void set_should_create_webui(bool should_create_webui) {
50 should_create_webui_ = should_create_webui;
53 // WebUIFactory implementation.
54 virtual WebUIController* CreateWebUIControllerForURL(
55 WebUI* web_ui, const GURL& url) const OVERRIDE {
56 if (!(should_create_webui_ && HasWebUIScheme(url)))
57 return NULL;
58 return new WebUIController(web_ui);
61 virtual WebUI::TypeID GetWebUIType(BrowserContext* browser_context,
62 const GURL& url) const OVERRIDE {
63 return WebUI::kNoWebUI;
66 virtual bool UseWebUIForURL(BrowserContext* browser_context,
67 const GURL& url) const OVERRIDE {
68 return HasWebUIScheme(url);
71 virtual bool UseWebUIBindingsForURL(BrowserContext* browser_context,
72 const GURL& url) const OVERRIDE {
73 return HasWebUIScheme(url);
76 private:
77 bool should_create_webui_;
79 DISALLOW_COPY_AND_ASSIGN(RenderFrameHostManagerTestWebUIControllerFactory);
82 class BeforeUnloadFiredWebContentsDelegate : public WebContentsDelegate {
83 public:
84 BeforeUnloadFiredWebContentsDelegate() {}
85 virtual ~BeforeUnloadFiredWebContentsDelegate() {}
87 virtual void BeforeUnloadFired(WebContents* web_contents,
88 bool proceed,
89 bool* proceed_to_fire_unload) OVERRIDE {
90 *proceed_to_fire_unload = proceed;
93 private:
94 DISALLOW_COPY_AND_ASSIGN(BeforeUnloadFiredWebContentsDelegate);
97 // This observer keeps track of the last deleted RenderViewHost to avoid
98 // accessing it and causing use-after-free condition.
99 class RenderViewHostDeletedObserver : public WebContentsObserver {
100 public:
101 RenderViewHostDeletedObserver(RenderViewHost* rvh)
102 : WebContentsObserver(WebContents::FromRenderViewHost(rvh)),
103 process_id_(rvh->GetProcess()->GetID()),
104 routing_id_(rvh->GetRoutingID()),
105 deleted_(false) {
108 virtual void RenderViewDeleted(RenderViewHost* render_view_host) OVERRIDE {
109 if (render_view_host->GetProcess()->GetID() == process_id_ &&
110 render_view_host->GetRoutingID() == routing_id_) {
111 deleted_ = true;
115 bool deleted() {
116 return deleted_;
119 private:
120 int process_id_;
121 int routing_id_;
122 bool deleted_;
124 DISALLOW_COPY_AND_ASSIGN(RenderViewHostDeletedObserver);
127 // This observer keeps track of the last deleted RenderFrameHost to avoid
128 // accessing it and causing use-after-free condition.
129 class RenderFrameHostDeletedObserver : public WebContentsObserver {
130 public:
131 RenderFrameHostDeletedObserver(RenderFrameHost* rfh)
132 : WebContentsObserver(WebContents::FromRenderFrameHost(rfh)),
133 process_id_(rfh->GetProcess()->GetID()),
134 routing_id_(rfh->GetRoutingID()),
135 deleted_(false) {
138 virtual void RenderFrameDeleted(RenderFrameHost* render_frame_host) OVERRIDE {
139 if (render_frame_host->GetProcess()->GetID() == process_id_ &&
140 render_frame_host->GetRoutingID() == routing_id_) {
141 deleted_ = true;
145 bool deleted() {
146 return deleted_;
149 private:
150 int process_id_;
151 int routing_id_;
152 bool deleted_;
154 DISALLOW_COPY_AND_ASSIGN(RenderFrameHostDeletedObserver);
158 // This observer is used to check whether IPC messages are being filtered for
159 // swapped out RenderFrameHost objects. It observes the plugin crash and favicon
160 // update events, which the FilterMessagesWhileSwappedOut test simulates being
161 // sent. The test is successful if the event is not observed.
162 // See http://crbug.com/351815
163 class PluginFaviconMessageObserver : public WebContentsObserver {
164 public:
165 PluginFaviconMessageObserver(WebContents* web_contents)
166 : WebContentsObserver(web_contents),
167 plugin_crashed_(false),
168 favicon_received_(false) { }
170 virtual void PluginCrashed(const base::FilePath& plugin_path,
171 base::ProcessId plugin_pid) OVERRIDE {
172 plugin_crashed_ = true;
175 virtual void DidUpdateFaviconURL(
176 const std::vector<FaviconURL>& candidates) OVERRIDE {
177 favicon_received_ = true;
180 bool plugin_crashed() {
181 return plugin_crashed_;
184 bool favicon_received() {
185 return favicon_received_;
188 private:
189 bool plugin_crashed_;
190 bool favicon_received_;
192 DISALLOW_COPY_AND_ASSIGN(PluginFaviconMessageObserver);
195 // Ensures that RenderFrameDeleted and RenderFrameCreated are called in a
196 // consistent manner.
197 class FrameLifetimeConsistencyChecker : public WebContentsObserver {
198 public:
199 explicit FrameLifetimeConsistencyChecker(WebContentsImpl* web_contents)
200 : WebContentsObserver(web_contents) {
201 RenderViewCreated(web_contents->GetRenderViewHost());
202 RenderFrameCreated(web_contents->GetMainFrame());
205 virtual void RenderFrameCreated(RenderFrameHost* render_frame_host) OVERRIDE {
206 std::pair<int, int> routing_pair =
207 std::make_pair(render_frame_host->GetProcess()->GetID(),
208 render_frame_host->GetRoutingID());
209 bool was_live_already = !live_routes_.insert(routing_pair).second;
210 bool was_used_before = deleted_routes_.count(routing_pair) != 0;
212 if (was_live_already) {
213 FAIL() << "RenderFrameCreated called more than once for routing pair: "
214 << Format(render_frame_host);
215 } else if (was_used_before) {
216 FAIL() << "RenderFrameCreated called for routing pair "
217 << Format(render_frame_host) << " that was previously deleted.";
221 virtual void RenderFrameDeleted(RenderFrameHost* render_frame_host) OVERRIDE {
222 std::pair<int, int> routing_pair =
223 std::make_pair(render_frame_host->GetProcess()->GetID(),
224 render_frame_host->GetRoutingID());
225 bool was_live = live_routes_.erase(routing_pair);
226 bool was_dead_already = !deleted_routes_.insert(routing_pair).second;
228 if (was_dead_already) {
229 FAIL() << "RenderFrameDeleted called more than once for routing pair "
230 << Format(render_frame_host);
231 } else if (!was_live) {
232 FAIL() << "RenderFrameDeleted called for routing pair "
233 << Format(render_frame_host)
234 << " for which RenderFrameCreated was never called";
238 private:
239 std::string Format(RenderFrameHost* render_frame_host) {
240 return base::StringPrintf(
241 "(%d, %d -> %s )",
242 render_frame_host->GetProcess()->GetID(),
243 render_frame_host->GetRoutingID(),
244 render_frame_host->GetSiteInstance()->GetSiteURL().spec().c_str());
246 std::set<std::pair<int, int> > live_routes_;
247 std::set<std::pair<int, int> > deleted_routes_;
250 } // namespace
252 class RenderFrameHostManagerTest
253 : public RenderViewHostImplTestHarness {
254 public:
255 virtual void SetUp() OVERRIDE {
256 RenderViewHostImplTestHarness::SetUp();
257 WebUIControllerFactory::RegisterFactory(&factory_);
258 lifetime_checker_.reset(new FrameLifetimeConsistencyChecker(contents()));
261 virtual void TearDown() OVERRIDE {
262 lifetime_checker_.reset();
263 RenderViewHostImplTestHarness::TearDown();
264 WebUIControllerFactory::UnregisterFactoryForTesting(&factory_);
267 void set_should_create_webui(bool should_create_webui) {
268 factory_.set_should_create_webui(should_create_webui);
271 void StartCrossSiteTransition(TestWebContents* contents) {
272 std::vector<GURL> url_chain;
273 contents->GetRenderManagerForTesting()->OnCrossSiteResponse(
274 contents->GetRenderManagerForTesting()->pending_frame_host(),
275 GlobalRequestID(0, 0), scoped_ptr<CrossSiteTransferringRequest>(),
276 url_chain, Referrer(), PAGE_TRANSITION_TYPED, false);
277 EXPECT_TRUE(contents->cross_navigation_pending());
278 RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>(
279 contents->GetRenderViewHost());
280 EXPECT_EQ(RenderViewHostImpl::STATE_WAITING_FOR_UNLOAD_ACK,
281 rvh->rvh_state());
284 void NavigateActiveAndCommit(const GURL& url) {
285 // Note: we navigate the active RenderViewHost because previous navigations
286 // won't have committed yet, so NavigateAndCommit does the wrong thing
287 // for us.
288 controller().LoadURL(url, Referrer(), PAGE_TRANSITION_LINK, std::string());
289 TestRenderViewHost* old_rvh = test_rvh();
291 // Simulate the BeforeUnload_ACK that is received from the current renderer
292 // for a cross-site navigation.
293 if (old_rvh != active_rvh()) {
294 old_rvh->SendBeforeUnloadACK(true);
295 EXPECT_EQ(RenderViewHostImpl::STATE_DEFAULT, old_rvh->rvh_state());
298 // Commit the navigation with a new page ID.
299 int32 max_page_id = contents()->GetMaxPageIDForSiteInstance(
300 active_rvh()->GetSiteInstance());
302 // Simulate the response coming from the pending renderer.
303 if (old_rvh != active_rvh())
304 StartCrossSiteTransition(contents());
306 // Simulate the SwapOut_ACK that fires if you commit a cross-site
307 // navigation.
308 if (old_rvh != active_rvh()) {
309 old_rvh->OnSwappedOut(false);
310 EXPECT_EQ(RenderViewHostImpl::STATE_WAITING_FOR_COMMIT,
311 old_rvh->rvh_state());
314 // Use an observer to avoid accessing a deleted renderer later on when the
315 // state is being checked.
316 RenderViewHostDeletedObserver rvh_observer(old_rvh);
317 active_test_rvh()->SendNavigate(max_page_id + 1, url);
319 if (old_rvh != active_rvh() && !rvh_observer.deleted())
320 EXPECT_TRUE(old_rvh->IsSwappedOut());
323 bool ShouldSwapProcesses(RenderFrameHostManager* manager,
324 const NavigationEntryImpl* current_entry,
325 const NavigationEntryImpl* new_entry) const {
326 return manager->ShouldSwapBrowsingInstancesForNavigation(current_entry,
327 new_entry);
330 // Creates a test RenderViewHost that's swapped out.
331 TestRenderViewHost* CreateSwappedOutRenderViewHost() {
332 const GURL kChromeURL("chrome://foo");
333 const GURL kDestUrl("http://www.google.com/");
335 // Navigate our first tab to a chrome url and then to the destination.
336 NavigateActiveAndCommit(kChromeURL);
337 TestRenderViewHost* ntp_rvh = static_cast<TestRenderViewHost*>(
338 contents()->GetRenderManagerForTesting()->current_host());
340 // Navigate to a cross-site URL.
341 contents()->GetController().LoadURL(
342 kDestUrl, Referrer(), PAGE_TRANSITION_LINK, std::string());
343 EXPECT_TRUE(contents()->cross_navigation_pending());
345 // Manually increase the number of active views in the
346 // SiteInstance that ntp_rvh belongs to, to prevent it from being
347 // destroyed when it gets swapped out.
348 static_cast<SiteInstanceImpl*>(ntp_rvh->GetSiteInstance())->
349 increment_active_view_count();
351 TestRenderViewHost* dest_rvh = static_cast<TestRenderViewHost*>(
352 contents()->GetRenderManagerForTesting()->pending_render_view_host());
353 CHECK(dest_rvh);
354 EXPECT_NE(ntp_rvh, dest_rvh);
356 // BeforeUnload finishes.
357 ntp_rvh->SendBeforeUnloadACK(true);
359 dest_rvh->SendNavigate(101, kDestUrl);
360 ntp_rvh->OnSwappedOut(false);
362 EXPECT_TRUE(ntp_rvh->IsSwappedOut());
363 return ntp_rvh;
366 NavigationRequest* NavigationRequestForRenderFrameManager(
367 RenderFrameHostManager* manager) const {
368 return manager->navigation_request_for_testing();
371 private:
372 RenderFrameHostManagerTestWebUIControllerFactory factory_;
373 scoped_ptr<FrameLifetimeConsistencyChecker> lifetime_checker_;
376 // Tests that when you navigate from a chrome:// url to another page, and
377 // then do that same thing in another tab, that the two resulting pages have
378 // different SiteInstances, BrowsingInstances, and RenderProcessHosts. This is
379 // a regression test for bug 9364.
380 TEST_F(RenderFrameHostManagerTest, NewTabPageProcesses) {
381 set_should_create_webui(true);
382 const GURL kChromeUrl("chrome://foo");
383 const GURL kDestUrl("http://www.google.com/");
385 // Navigate our first tab to the chrome url and then to the destination,
386 // ensuring we grant bindings to the chrome URL.
387 NavigateActiveAndCommit(kChromeUrl);
388 EXPECT_TRUE(active_rvh()->GetEnabledBindings() & BINDINGS_POLICY_WEB_UI);
389 NavigateActiveAndCommit(kDestUrl);
391 // Make a second tab.
392 scoped_ptr<TestWebContents> contents2(
393 TestWebContents::Create(browser_context(), NULL));
395 // Load the two URLs in the second tab. Note that the first navigation creates
396 // a RVH that's not pending (since there is no cross-site transition), so
397 // we use the committed one.
398 contents2->GetController().LoadURL(
399 kChromeUrl, Referrer(), PAGE_TRANSITION_LINK, std::string());
400 TestRenderViewHost* ntp_rvh2 = static_cast<TestRenderViewHost*>(
401 contents2->GetRenderManagerForTesting()->current_host());
402 EXPECT_FALSE(contents2->cross_navigation_pending());
403 ntp_rvh2->SendNavigate(100, kChromeUrl);
405 // The second one is the opposite, creating a cross-site transition and
406 // requiring a beforeunload ack.
407 contents2->GetController().LoadURL(
408 kDestUrl, Referrer(), PAGE_TRANSITION_LINK, std::string());
409 EXPECT_TRUE(contents2->cross_navigation_pending());
410 TestRenderViewHost* dest_rvh2 = static_cast<TestRenderViewHost*>(
411 contents2->GetRenderManagerForTesting()->pending_render_view_host());
412 ASSERT_TRUE(dest_rvh2);
414 ntp_rvh2->SendBeforeUnloadACK(true);
415 StartCrossSiteTransition(contents2.get());
416 dest_rvh2->SendNavigate(101, kDestUrl);
418 // The two RVH's should be different in every way.
419 EXPECT_NE(active_rvh()->GetProcess(), dest_rvh2->GetProcess());
420 EXPECT_NE(active_rvh()->GetSiteInstance(), dest_rvh2->GetSiteInstance());
421 EXPECT_FALSE(active_rvh()->GetSiteInstance()->IsRelatedSiteInstance(
422 dest_rvh2->GetSiteInstance()));
424 // Navigate both to the new tab page, and verify that they share a
425 // RenderProcessHost (not a SiteInstance).
426 NavigateActiveAndCommit(kChromeUrl);
428 contents2->GetController().LoadURL(
429 kChromeUrl, Referrer(), PAGE_TRANSITION_LINK, std::string());
430 dest_rvh2->SendBeforeUnloadACK(true);
431 StartCrossSiteTransition(contents2.get());
432 static_cast<TestRenderViewHost*>(contents2->GetRenderManagerForTesting()->
433 pending_render_view_host())->SendNavigate(102, kChromeUrl);
435 EXPECT_NE(active_rvh()->GetSiteInstance(),
436 contents2->GetRenderViewHost()->GetSiteInstance());
437 EXPECT_EQ(active_rvh()->GetSiteInstance()->GetProcess(),
438 contents2->GetRenderViewHost()->GetSiteInstance()->GetProcess());
441 // Ensure that the browser ignores most IPC messages that arrive from a
442 // RenderViewHost that has been swapped out. We do not want to take
443 // action on requests from a non-active renderer. The main exception is
444 // for synchronous messages, which cannot be ignored without leaving the
445 // renderer in a stuck state. See http://crbug.com/93427.
446 TEST_F(RenderFrameHostManagerTest, FilterMessagesWhileSwappedOut) {
447 const GURL kChromeURL("chrome://foo");
448 const GURL kDestUrl("http://www.google.com/");
449 std::vector<FaviconURL> icons;
451 // Navigate our first tab to a chrome url and then to the destination.
452 NavigateActiveAndCommit(kChromeURL);
453 TestRenderViewHost* ntp_rvh = static_cast<TestRenderViewHost*>(
454 contents()->GetRenderManagerForTesting()->current_host());
456 // Send an update favicon message and make sure it works.
457 const base::string16 ntp_title = base::ASCIIToUTF16("NTP Title");
459 PluginFaviconMessageObserver observer(contents());
460 EXPECT_TRUE(ntp_rvh->OnMessageReceived(
461 ViewHostMsg_UpdateFaviconURL(
462 rvh()->GetRoutingID(), icons)));
463 EXPECT_TRUE(observer.favicon_received());
465 // Create one more view in the same SiteInstance where ntp_rvh
466 // exists so that it doesn't get deleted on navigation to another
467 // site.
468 static_cast<SiteInstanceImpl*>(ntp_rvh->GetSiteInstance())->
469 increment_active_view_count();
472 // Navigate to a cross-site URL.
473 NavigateActiveAndCommit(kDestUrl);
474 TestRenderViewHost* dest_rvh = static_cast<TestRenderViewHost*>(
475 contents()->GetRenderViewHost());
476 ASSERT_TRUE(dest_rvh);
477 EXPECT_NE(ntp_rvh, dest_rvh);
479 // The new RVH should be able to update its favicon.
480 const base::string16 dest_title = base::ASCIIToUTF16("Google");
482 PluginFaviconMessageObserver observer(contents());
483 EXPECT_TRUE(
484 dest_rvh->OnMessageReceived(
485 ViewHostMsg_UpdateFaviconURL(rvh()->GetRoutingID(), icons)));
486 EXPECT_TRUE(observer.favicon_received());
489 // The old renderer, being slow, now updates the favicon. It should be
490 // filtered out and not take effect.
491 EXPECT_TRUE(ntp_rvh->IsSwappedOut());
493 PluginFaviconMessageObserver observer(contents());
494 EXPECT_TRUE(
495 ntp_rvh->OnMessageReceived(
496 ViewHostMsg_UpdateFaviconURL(rvh()->GetRoutingID(), icons)));
497 EXPECT_FALSE(observer.favicon_received());
500 // The same logic should apply to RenderFrameHosts as well and routing through
501 // swapped out RFH shouldn't be allowed. Use a PluginCrashObserver to check
502 // if the IPC message is allowed through or not.
504 PluginFaviconMessageObserver observer(contents());
505 // TODO(nasko): Check that the RFH is in swapped out when the state moves
506 // from RVH to RFH.
507 EXPECT_TRUE(ntp_rvh->main_render_frame_host()->OnMessageReceived(
508 FrameHostMsg_PluginCrashed(
509 main_rfh()->GetRoutingID(), base::FilePath(), 0)));
510 EXPECT_FALSE(observer.plugin_crashed());
513 // We cannot filter out synchronous IPC messages, because the renderer would
514 // be left waiting for a reply. We pick RunBeforeUnloadConfirm as an example
515 // that can run easily within a unit test, and that needs to receive a reply
516 // without showing an actual dialog.
517 MockRenderProcessHost* ntp_process_host =
518 static_cast<MockRenderProcessHost*>(ntp_rvh->GetProcess());
519 ntp_process_host->sink().ClearMessages();
520 RenderFrameHost* ntp_rfh = ntp_rvh->GetMainFrame();
521 const base::string16 msg = base::ASCIIToUTF16("Message");
522 bool result = false;
523 base::string16 unused;
524 FrameHostMsg_RunBeforeUnloadConfirm before_unload_msg(
525 ntp_rfh->GetRoutingID(), kChromeURL, msg, false, &result, &unused);
526 // Enable pumping for check in BrowserMessageFilter::CheckCanDispatchOnUI.
527 before_unload_msg.EnableMessagePumping();
528 EXPECT_TRUE(ntp_rfh->OnMessageReceived(before_unload_msg));
529 EXPECT_TRUE(ntp_process_host->sink().GetUniqueMessageMatching(IPC_REPLY_ID));
531 // Also test RunJavaScriptMessage.
532 ntp_process_host->sink().ClearMessages();
533 FrameHostMsg_RunJavaScriptMessage js_msg(
534 ntp_rfh->GetRoutingID(), msg, msg, kChromeURL,
535 JAVASCRIPT_MESSAGE_TYPE_CONFIRM, &result, &unused);
536 js_msg.EnableMessagePumping();
537 EXPECT_TRUE(ntp_rfh->OnMessageReceived(js_msg));
538 EXPECT_TRUE(ntp_process_host->sink().GetUniqueMessageMatching(IPC_REPLY_ID));
541 TEST_F(RenderFrameHostManagerTest, WhiteListSwapCompositorFrame) {
542 TestRenderViewHost* swapped_out_rvh = CreateSwappedOutRenderViewHost();
543 TestRenderWidgetHostView* swapped_out_rwhv =
544 static_cast<TestRenderWidgetHostView*>(swapped_out_rvh->GetView());
545 EXPECT_FALSE(swapped_out_rwhv->did_swap_compositor_frame());
547 MockRenderProcessHost* process_host =
548 static_cast<MockRenderProcessHost*>(swapped_out_rvh->GetProcess());
549 process_host->sink().ClearMessages();
551 cc::CompositorFrame frame;
552 ViewHostMsg_SwapCompositorFrame msg(rvh()->GetRoutingID(), 0, frame);
554 EXPECT_TRUE(swapped_out_rvh->OnMessageReceived(msg));
555 EXPECT_TRUE(swapped_out_rwhv->did_swap_compositor_frame());
558 // Test if RenderViewHost::GetRenderWidgetHosts() only returns active
559 // widgets.
560 TEST_F(RenderFrameHostManagerTest, GetRenderWidgetHostsReturnsActiveViews) {
561 TestRenderViewHost* swapped_out_rvh = CreateSwappedOutRenderViewHost();
562 EXPECT_TRUE(swapped_out_rvh->IsSwappedOut());
564 scoped_ptr<RenderWidgetHostIterator> widgets(
565 RenderWidgetHost::GetRenderWidgetHosts());
566 // We know that there is the only one active widget. Another view is
567 // now swapped out, so the swapped out view is not included in the
568 // list.
569 RenderWidgetHost* widget = widgets->GetNextHost();
570 EXPECT_FALSE(widgets->GetNextHost());
571 RenderViewHost* rvh = RenderViewHost::From(widget);
572 EXPECT_EQ(RenderViewHostImpl::STATE_DEFAULT,
573 static_cast<RenderViewHostImpl*>(rvh)->rvh_state());
576 // Test if RenderViewHost::GetRenderWidgetHosts() returns a subset of
577 // RenderViewHostImpl::GetAllRenderWidgetHosts().
578 // RenderViewHost::GetRenderWidgetHosts() returns only active widgets, but
579 // RenderViewHostImpl::GetAllRenderWidgetHosts() returns everything
580 // including swapped out ones.
581 TEST_F(RenderFrameHostManagerTest,
582 GetRenderWidgetHostsWithinGetAllRenderWidgetHosts) {
583 TestRenderViewHost* swapped_out_rvh = CreateSwappedOutRenderViewHost();
584 EXPECT_TRUE(swapped_out_rvh->IsSwappedOut());
586 scoped_ptr<RenderWidgetHostIterator> widgets(
587 RenderWidgetHost::GetRenderWidgetHosts());
589 while (RenderWidgetHost* w = widgets->GetNextHost()) {
590 bool found = false;
591 scoped_ptr<RenderWidgetHostIterator> all_widgets(
592 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
593 while (RenderWidgetHost* widget = all_widgets->GetNextHost()) {
594 if (w == widget) {
595 found = true;
596 break;
599 EXPECT_TRUE(found);
603 // Test if SiteInstanceImpl::active_view_count() is correctly updated
604 // as views in a SiteInstance get swapped out and in.
605 TEST_F(RenderFrameHostManagerTest, ActiveViewCountWhileSwappingInandOut) {
606 const GURL kUrl1("http://www.google.com/");
607 const GURL kUrl2("http://www.chromium.org/");
609 // Navigate to an initial URL.
610 contents()->NavigateAndCommit(kUrl1);
611 TestRenderViewHost* rvh1 = test_rvh();
613 SiteInstanceImpl* instance1 =
614 static_cast<SiteInstanceImpl*>(rvh1->GetSiteInstance());
615 EXPECT_EQ(instance1->active_view_count(), 1U);
617 // Create 2 new tabs and simulate them being the opener chain for the main
618 // tab. They should be in the same SiteInstance.
619 scoped_ptr<TestWebContents> opener1(
620 TestWebContents::Create(browser_context(), instance1));
621 contents()->SetOpener(opener1.get());
623 scoped_ptr<TestWebContents> opener2(
624 TestWebContents::Create(browser_context(), instance1));
625 opener1->SetOpener(opener2.get());
627 EXPECT_EQ(instance1->active_view_count(), 3U);
629 // Navigate to a cross-site URL (different SiteInstance but same
630 // BrowsingInstance).
631 contents()->NavigateAndCommit(kUrl2);
632 TestRenderViewHost* rvh2 = test_rvh();
633 SiteInstanceImpl* instance2 =
634 static_cast<SiteInstanceImpl*>(rvh2->GetSiteInstance());
636 // rvh2 is on chromium.org which is different from google.com on
637 // which other tabs are.
638 EXPECT_EQ(instance2->active_view_count(), 1U);
640 // There are two active views on google.com now.
641 EXPECT_EQ(instance1->active_view_count(), 2U);
643 // Navigate to the original origin (google.com).
644 contents()->NavigateAndCommit(kUrl1);
646 EXPECT_EQ(instance1->active_view_count(), 3U);
649 // This deletes a WebContents when the given RVH is deleted. This is
650 // only for testing whether deleting an RVH does not cause any UaF in
651 // other parts of the system. For now, this class is only used for the
652 // next test cases to detect the bug mentioned at
653 // http://crbug.com/259859.
654 class RenderViewHostDestroyer : public WebContentsObserver {
655 public:
656 RenderViewHostDestroyer(RenderViewHost* render_view_host,
657 WebContents* web_contents)
658 : WebContentsObserver(WebContents::FromRenderViewHost(render_view_host)),
659 render_view_host_(render_view_host),
660 web_contents_(web_contents) {}
662 virtual void RenderViewDeleted(
663 RenderViewHost* render_view_host) OVERRIDE {
664 if (render_view_host == render_view_host_)
665 delete web_contents_;
668 private:
669 RenderViewHost* render_view_host_;
670 WebContents* web_contents_;
672 DISALLOW_COPY_AND_ASSIGN(RenderViewHostDestroyer);
675 // Test if ShutdownRenderViewHostsInSiteInstance() does not touch any
676 // RenderWidget that has been freed while deleting a RenderViewHost in
677 // a previous iteration. This is a regression test for
678 // http://crbug.com/259859.
679 TEST_F(RenderFrameHostManagerTest,
680 DetectUseAfterFreeInShutdownRenderViewHostsInSiteInstance) {
681 const GURL kChromeURL("chrome://newtab");
682 const GURL kUrl1("http://www.google.com");
683 const GURL kUrl2("http://www.chromium.org");
685 // Navigate our first tab to a chrome url and then to the destination.
686 NavigateActiveAndCommit(kChromeURL);
687 TestRenderViewHost* ntp_rvh = static_cast<TestRenderViewHost*>(
688 contents()->GetRenderManagerForTesting()->current_host());
690 // Create one more tab and navigate to kUrl1. web_contents is not
691 // wrapped as scoped_ptr since it intentionally deleted by destroyer
692 // below as part of this test.
693 TestWebContents* web_contents =
694 TestWebContents::Create(browser_context(), ntp_rvh->GetSiteInstance());
695 web_contents->NavigateAndCommit(kUrl1);
696 RenderViewHostDestroyer destroyer(ntp_rvh, web_contents);
698 // This causes the first tab to navigate to kUrl2, which destroys
699 // the ntp_rvh in ShutdownRenderViewHostsInSiteInstance(). When
700 // ntp_rvh is destroyed, it also destroys the RVHs in web_contents
701 // too. This can test whether
702 // SiteInstanceImpl::ShutdownRenderViewHostsInSiteInstance() can
703 // touch any object freed in this way or not while iterating through
704 // all widgets.
705 contents()->NavigateAndCommit(kUrl2);
708 // When there is an error with the specified page, renderer exits view-source
709 // mode. See WebFrameImpl::DidFail(). We check by this test that
710 // EnableViewSourceMode message is sent on every navigation regardless
711 // RenderView is being newly created or reused.
712 TEST_F(RenderFrameHostManagerTest, AlwaysSendEnableViewSourceMode) {
713 const GURL kChromeUrl("chrome://foo");
714 const GURL kUrl("view-source:http://foo");
716 // We have to navigate to some page at first since without this, the first
717 // navigation will reuse the SiteInstance created by Init(), and the second
718 // one will create a new SiteInstance. Because current_instance and
719 // new_instance will be different, a new RenderViewHost will be created for
720 // the second navigation. We have to avoid this in order to exercise the
721 // target code patch.
722 NavigateActiveAndCommit(kChromeUrl);
724 // Navigate.
725 controller().LoadURL(
726 kUrl, Referrer(), PAGE_TRANSITION_TYPED, std::string());
727 // Simulate response from RenderFrame for DispatchBeforeUnload.
728 base::TimeTicks now = base::TimeTicks::Now();
729 main_test_rfh()->OnMessageReceived(FrameHostMsg_BeforeUnload_ACK(
730 main_test_rfh()->GetRoutingID(), true, now, now));
731 ASSERT_TRUE(pending_rvh()); // New pending RenderViewHost will be created.
732 RenderViewHost* last_rvh = pending_rvh();
733 int32 new_id = contents()->GetMaxPageIDForSiteInstance(
734 active_rvh()->GetSiteInstance()) + 1;
735 pending_test_rvh()->SendNavigate(new_id, kUrl);
736 EXPECT_EQ(controller().GetLastCommittedEntryIndex(), 1);
737 ASSERT_TRUE(controller().GetLastCommittedEntry());
738 EXPECT_TRUE(kUrl == controller().GetLastCommittedEntry()->GetURL());
739 EXPECT_FALSE(controller().GetPendingEntry());
740 // Because we're using TestWebContents and TestRenderViewHost in this
741 // unittest, no one calls WebContentsImpl::RenderViewCreated(). So, we see no
742 // EnableViewSourceMode message, here.
744 // Clear queued messages before load.
745 process()->sink().ClearMessages();
746 // Navigate, again.
747 controller().LoadURL(
748 kUrl, Referrer(), PAGE_TRANSITION_TYPED, std::string());
749 // The same RenderViewHost should be reused.
750 EXPECT_FALSE(pending_rvh());
751 EXPECT_TRUE(last_rvh == rvh());
752 test_rvh()->SendNavigate(new_id, kUrl); // The same page_id returned.
753 EXPECT_EQ(controller().GetLastCommittedEntryIndex(), 1);
754 EXPECT_FALSE(controller().GetPendingEntry());
755 // New message should be sent out to make sure to enter view-source mode.
756 EXPECT_TRUE(process()->sink().GetUniqueMessageMatching(
757 ViewMsg_EnableViewSourceMode::ID));
760 // Tests the Init function by checking the initial RenderViewHost.
761 TEST_F(RenderFrameHostManagerTest, Init) {
762 // Using TestBrowserContext.
763 SiteInstanceImpl* instance =
764 static_cast<SiteInstanceImpl*>(SiteInstance::Create(browser_context()));
765 EXPECT_FALSE(instance->HasSite());
767 scoped_ptr<TestWebContents> web_contents(
768 TestWebContents::Create(browser_context(), instance));
770 RenderFrameHostManager* manager = web_contents->GetRenderManagerForTesting();
771 RenderViewHostImpl* rvh = manager->current_host();
772 RenderFrameHostImpl* rfh = manager->current_frame_host();
773 ASSERT_TRUE(rvh);
774 ASSERT_TRUE(rfh);
775 EXPECT_EQ(rvh, rfh->render_view_host());
776 EXPECT_EQ(instance, rvh->GetSiteInstance());
777 EXPECT_EQ(web_contents.get(), rvh->GetDelegate());
778 EXPECT_EQ(web_contents.get(), rfh->delegate());
779 EXPECT_TRUE(manager->GetRenderWidgetHostView());
780 EXPECT_FALSE(manager->pending_render_view_host());
783 // Tests the Navigate function. We navigate three sites consecutively and check
784 // how the pending/committed RenderViewHost are modified.
785 TEST_F(RenderFrameHostManagerTest, Navigate) {
786 TestNotificationTracker notifications;
788 SiteInstance* instance = SiteInstance::Create(browser_context());
790 scoped_ptr<TestWebContents> web_contents(
791 TestWebContents::Create(browser_context(), instance));
792 notifications.ListenFor(NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
793 Source<WebContents>(web_contents.get()));
795 RenderFrameHostManager* manager = web_contents->GetRenderManagerForTesting();
796 RenderFrameHostImpl* host;
798 // 1) The first navigation. --------------------------
799 const GURL kUrl1("http://www.google.com/");
800 NavigationEntryImpl entry1(
801 NULL /* instance */, -1 /* page_id */, kUrl1, Referrer(),
802 base::string16() /* title */, PAGE_TRANSITION_TYPED,
803 false /* is_renderer_init */);
804 host = manager->Navigate(entry1);
806 // The RenderFrameHost created in Init will be reused.
807 EXPECT_TRUE(host == manager->current_frame_host());
808 EXPECT_FALSE(manager->pending_frame_host());
810 // Commit.
811 manager->DidNavigateFrame(host);
812 // Commit to SiteInstance should be delayed until RenderView commit.
813 EXPECT_TRUE(host == manager->current_frame_host());
814 ASSERT_TRUE(host);
815 EXPECT_FALSE(static_cast<SiteInstanceImpl*>(host->GetSiteInstance())->
816 HasSite());
817 static_cast<SiteInstanceImpl*>(host->GetSiteInstance())->SetSite(kUrl1);
819 // 2) Navigate to next site. -------------------------
820 const GURL kUrl2("http://www.google.com/foo");
821 NavigationEntryImpl entry2(
822 NULL /* instance */, -1 /* page_id */, kUrl2,
823 Referrer(kUrl1, blink::WebReferrerPolicyDefault),
824 base::string16() /* title */, PAGE_TRANSITION_LINK,
825 true /* is_renderer_init */);
826 host = manager->Navigate(entry2);
828 // The RenderFrameHost created in Init will be reused.
829 EXPECT_TRUE(host == manager->current_frame_host());
830 EXPECT_FALSE(manager->pending_frame_host());
832 // Commit.
833 manager->DidNavigateFrame(host);
834 EXPECT_TRUE(host == manager->current_frame_host());
835 ASSERT_TRUE(host);
836 EXPECT_TRUE(static_cast<SiteInstanceImpl*>(host->GetSiteInstance())->
837 HasSite());
839 // 3) Cross-site navigate to next site. --------------
840 const GURL kUrl3("http://webkit.org/");
841 NavigationEntryImpl entry3(
842 NULL /* instance */, -1 /* page_id */, kUrl3,
843 Referrer(kUrl2, blink::WebReferrerPolicyDefault),
844 base::string16() /* title */, PAGE_TRANSITION_LINK,
845 false /* is_renderer_init */);
846 host = manager->Navigate(entry3);
848 // A new RenderFrameHost should be created.
849 EXPECT_TRUE(manager->pending_frame_host());
850 ASSERT_EQ(host, manager->pending_frame_host());
852 notifications.Reset();
854 // Commit.
855 manager->DidNavigateFrame(manager->pending_frame_host());
856 EXPECT_TRUE(host == manager->current_frame_host());
857 ASSERT_TRUE(host);
858 EXPECT_TRUE(static_cast<SiteInstanceImpl*>(host->GetSiteInstance())->
859 HasSite());
860 // Check the pending RenderFrameHost has been committed.
861 EXPECT_FALSE(manager->pending_frame_host());
863 // We should observe a notification.
864 EXPECT_TRUE(
865 notifications.Check1AndReset(NOTIFICATION_RENDER_VIEW_HOST_CHANGED));
868 // Tests the Navigate function. In this unit test we verify that the Navigate
869 // function can handle a new navigation event before the previous navigation
870 // has been committed. This is also a regression test for
871 // http://crbug.com/104600.
872 TEST_F(RenderFrameHostManagerTest, NavigateWithEarlyReNavigation) {
873 TestNotificationTracker notifications;
875 SiteInstance* instance = SiteInstance::Create(browser_context());
877 scoped_ptr<TestWebContents> web_contents(
878 TestWebContents::Create(browser_context(), instance));
879 notifications.ListenFor(NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
880 Source<WebContents>(web_contents.get()));
882 RenderFrameHostManager* manager = web_contents->GetRenderManagerForTesting();
884 // 1) The first navigation. --------------------------
885 const GURL kUrl1("http://www.google.com/");
886 NavigationEntryImpl entry1(NULL /* instance */, -1 /* page_id */, kUrl1,
887 Referrer(), base::string16() /* title */,
888 PAGE_TRANSITION_TYPED,
889 false /* is_renderer_init */);
890 RenderFrameHostImpl* host = manager->Navigate(entry1);
892 // The RenderFrameHost created in Init will be reused.
893 EXPECT_TRUE(host == manager->current_frame_host());
894 EXPECT_FALSE(manager->pending_frame_host());
896 // We should observe a notification.
897 EXPECT_TRUE(
898 notifications.Check1AndReset(NOTIFICATION_RENDER_VIEW_HOST_CHANGED));
899 notifications.Reset();
901 // Commit.
902 manager->DidNavigateFrame(host);
904 // Commit to SiteInstance should be delayed until RenderView commit.
905 EXPECT_TRUE(host == manager->current_frame_host());
906 ASSERT_TRUE(host);
907 EXPECT_FALSE(static_cast<SiteInstanceImpl*>(host->GetSiteInstance())->
908 HasSite());
909 static_cast<SiteInstanceImpl*>(host->GetSiteInstance())->SetSite(kUrl1);
911 // 2) Cross-site navigate to next site. -------------------------
912 const GURL kUrl2("http://www.example.com");
913 NavigationEntryImpl entry2(
914 NULL /* instance */, -1 /* page_id */, kUrl2, Referrer(),
915 base::string16() /* title */, PAGE_TRANSITION_TYPED,
916 false /* is_renderer_init */);
917 RenderFrameHostImpl* host2 = manager->Navigate(entry2);
918 int host2_process_id = host2->GetProcess()->GetID();
920 // A new RenderFrameHost should be created.
921 EXPECT_TRUE(manager->pending_frame_host());
922 ASSERT_EQ(host2, manager->pending_frame_host());
923 EXPECT_NE(host2, host);
925 // Check that the navigation is still suspended because the old RVH
926 // is not swapped out, yet.
927 EXPECT_TRUE(host2->render_view_host()->are_navigations_suspended());
928 MockRenderProcessHost* test_process_host2 =
929 static_cast<MockRenderProcessHost*>(host2->GetProcess());
930 test_process_host2->sink().ClearMessages();
931 host2->render_view_host()->NavigateToURL(kUrl2);
932 EXPECT_FALSE(test_process_host2->sink().GetUniqueMessageMatching(
933 FrameMsg_Navigate::ID));
935 // Allow closing the current Render View (precondition for swapping out
936 // the RVH): Simulate response from RenderFrame for FrameMsg_BeforeUnload sent
937 // by DispatchBeforeUnload.
938 TestRenderViewHost* test_host =
939 static_cast<TestRenderViewHost*>(host->render_view_host());
940 MockRenderProcessHost* test_process_host =
941 static_cast<MockRenderProcessHost*>(test_host->GetProcess());
942 EXPECT_TRUE(test_process_host->sink().GetUniqueMessageMatching(
943 FrameMsg_BeforeUnload::ID));
944 test_host->SendBeforeUnloadACK(true);
946 // CrossSiteResourceHandler::StartCrossSiteTransition triggers a
947 // call of RenderFrameHostManager::SwapOutOldPage before
948 // RenderFrameHostManager::DidNavigateFrame is called.
949 // The RVH is swapped out after receiving the unload ack.
950 manager->SwapOutOldPage();
951 EXPECT_TRUE(test_process_host->sink().GetUniqueMessageMatching(
952 FrameMsg_SwapOut::ID));
953 test_host->OnSwappedOut(false);
955 EXPECT_EQ(host, manager->current_frame_host());
956 EXPECT_FALSE(manager->current_frame_host()->is_swapped_out());
957 EXPECT_EQ(host2, manager->pending_frame_host());
958 // There should be still no navigation messages being sent.
959 EXPECT_FALSE(test_process_host2->sink().GetUniqueMessageMatching(
960 FrameMsg_Navigate::ID));
962 // 3) Cross-site navigate to next site before 2) has committed. --------------
963 const GURL kUrl3("http://webkit.org/");
964 NavigationEntryImpl entry3(NULL /* instance */, -1 /* page_id */, kUrl3,
965 Referrer(), base::string16() /* title */,
966 PAGE_TRANSITION_TYPED,
967 false /* is_renderer_init */);
968 test_process_host->sink().ClearMessages();
969 RenderFrameHostImpl* host3 = manager->Navigate(entry3);
971 // A new RenderFrameHost should be created. host2 is now deleted.
972 EXPECT_TRUE(manager->pending_frame_host());
973 ASSERT_EQ(host3, manager->pending_frame_host());
974 EXPECT_NE(host3, host);
975 EXPECT_NE(host3->GetProcess()->GetID(), host2_process_id);
977 // Navigations in the new RVH should be suspended.
978 EXPECT_TRUE(static_cast<RenderViewHostImpl*>(
979 host3->render_view_host())->are_navigations_suspended());
980 EXPECT_EQ(host, manager->current_frame_host());
981 EXPECT_FALSE(manager->current_frame_host()->is_swapped_out());
983 // Simulate a response to the second beforeunload request.
984 EXPECT_TRUE(test_process_host->sink().GetUniqueMessageMatching(
985 FrameMsg_BeforeUnload::ID));
986 test_host->SendBeforeUnloadACK(true);
988 // CrossSiteResourceHandler::StartCrossSiteTransition triggers a
989 // call of RenderFrameHostManager::SwapOutOldPage before
990 // RenderFrameHostManager::DidNavigateFrame is called. Since the previous
991 // navigation has already caused the renderer to start swapping out, there
992 // will be no more SwapOut messages being sent.
993 manager->SwapOutOldPage();
994 EXPECT_FALSE(test_process_host->sink().GetUniqueMessageMatching(
995 FrameMsg_SwapOut::ID));
996 test_host->OnSwappedOut(false);
998 // Commit.
999 manager->DidNavigateFrame(host3);
1000 EXPECT_TRUE(host3 == manager->current_frame_host());
1001 ASSERT_TRUE(host3);
1002 EXPECT_TRUE(static_cast<SiteInstanceImpl*>(host3->GetSiteInstance())->
1003 HasSite());
1004 // Check the pending RenderFrameHost has been committed.
1005 EXPECT_FALSE(manager->pending_frame_host());
1007 // We should observe a notification.
1008 EXPECT_TRUE(
1009 notifications.Check1AndReset(NOTIFICATION_RENDER_VIEW_HOST_CHANGED));
1012 // Test that navigation is not blocked when we make new navigation before
1013 // previous one has been committed. This is also a regression test for
1014 // http://crbug.com/104600.
1015 TEST_F(RenderFrameHostManagerTest, NewCrossNavigationBetweenSwapOutAndCommit) {
1016 const GURL kUrl1("http://www.google.com/");
1017 const GURL kUrl2("http://www.chromium.org/");
1018 const GURL kUrl3("http://www.youtube.com/");
1020 contents()->NavigateAndCommit(kUrl1);
1021 TestRenderViewHost* rvh1 = test_rvh();
1023 // Keep active_view_count nonzero so that no swapped out views in
1024 // this SiteInstance get forcefully deleted.
1025 static_cast<SiteInstanceImpl*>(rvh1->GetSiteInstance())->
1026 increment_active_view_count();
1028 // Navigate but don't commit.
1029 contents()->GetController().LoadURL(
1030 kUrl2, Referrer(), PAGE_TRANSITION_LINK, std::string());
1031 EXPECT_TRUE(rvh1->is_waiting_for_beforeunload_ack());
1032 contents()->ProceedWithCrossSiteNavigation();
1033 EXPECT_FALSE(rvh1->is_waiting_for_beforeunload_ack());
1034 StartCrossSiteTransition(contents());
1035 EXPECT_TRUE(rvh1->IsWaitingForUnloadACK());
1037 rvh1->OnSwappedOut(false);
1038 EXPECT_EQ(RenderViewHostImpl::STATE_WAITING_FOR_COMMIT, rvh1->rvh_state());
1040 TestRenderViewHost* rvh2 = pending_test_rvh();
1041 EXPECT_TRUE(rvh2);
1042 static_cast<SiteInstanceImpl*>(rvh2->GetSiteInstance())->
1043 increment_active_view_count();
1045 contents()->GetController().LoadURL(
1046 kUrl3, Referrer(), PAGE_TRANSITION_LINK, std::string());
1047 // Pending rvh2 is already deleted.
1048 contents()->ProceedWithCrossSiteNavigation();
1050 TestRenderViewHost* rvh3 = pending_test_rvh();
1051 EXPECT_TRUE(rvh3);
1052 // Navigation should be already unblocked by rvh1.
1053 EXPECT_FALSE(rvh3->are_navigations_suspended());
1056 // Tests WebUI creation.
1057 TEST_F(RenderFrameHostManagerTest, WebUI) {
1058 set_should_create_webui(true);
1059 SiteInstance* instance = SiteInstance::Create(browser_context());
1061 scoped_ptr<TestWebContents> web_contents(
1062 TestWebContents::Create(browser_context(), instance));
1063 RenderFrameHostManager* manager = web_contents->GetRenderManagerForTesting();
1065 EXPECT_FALSE(manager->current_host()->IsRenderViewLive());
1067 const GURL kUrl("chrome://foo");
1068 NavigationEntryImpl entry(NULL /* instance */, -1 /* page_id */, kUrl,
1069 Referrer(), base::string16() /* title */,
1070 PAGE_TRANSITION_TYPED,
1071 false /* is_renderer_init */);
1072 RenderFrameHostImpl* host = manager->Navigate(entry);
1074 // We commit the pending RenderFrameHost immediately because the previous
1075 // RenderFrameHost was not live. We test a case where it is live in
1076 // WebUIInNewTab.
1077 EXPECT_TRUE(host);
1078 EXPECT_EQ(host, manager->current_frame_host());
1079 EXPECT_FALSE(manager->pending_frame_host());
1081 // It's important that the site instance get set on the Web UI page as soon
1082 // as the navigation starts, rather than lazily after it commits, so we don't
1083 // try to re-use the SiteInstance/process for non Web UI things that may
1084 // get loaded in between.
1085 EXPECT_TRUE(static_cast<SiteInstanceImpl*>(host->GetSiteInstance())->
1086 HasSite());
1087 EXPECT_EQ(kUrl, host->GetSiteInstance()->GetSiteURL());
1089 // The Web UI is committed immediately because the RenderViewHost has not been
1090 // used yet. UpdateStateForNavigate() took the short cut path.
1091 EXPECT_FALSE(manager->pending_web_ui());
1092 EXPECT_TRUE(manager->web_ui());
1094 // Commit.
1095 manager->DidNavigateFrame(host);
1096 EXPECT_TRUE(
1097 host->render_view_host()->GetEnabledBindings() & BINDINGS_POLICY_WEB_UI);
1100 // Tests that we can open a WebUI link in a new tab from a WebUI page and still
1101 // grant the correct bindings. http://crbug.com/189101.
1102 TEST_F(RenderFrameHostManagerTest, WebUIInNewTab) {
1103 set_should_create_webui(true);
1104 SiteInstance* blank_instance = SiteInstance::Create(browser_context());
1106 // Create a blank tab.
1107 scoped_ptr<TestWebContents> web_contents1(
1108 TestWebContents::Create(browser_context(), blank_instance));
1109 RenderFrameHostManager* manager1 =
1110 web_contents1->GetRenderManagerForTesting();
1111 // Test the case that new RVH is considered live.
1112 manager1->current_host()->CreateRenderView(
1113 base::string16(), -1, MSG_ROUTING_NONE, -1, false);
1115 // Navigate to a WebUI page.
1116 const GURL kUrl1("chrome://foo");
1117 NavigationEntryImpl entry1(NULL /* instance */, -1 /* page_id */, kUrl1,
1118 Referrer(), base::string16() /* title */,
1119 PAGE_TRANSITION_TYPED,
1120 false /* is_renderer_init */);
1121 RenderFrameHostImpl* host1 = manager1->Navigate(entry1);
1123 // We should have a pending navigation to the WebUI RenderViewHost.
1124 // It should already have bindings.
1125 EXPECT_EQ(host1, manager1->pending_frame_host());
1126 EXPECT_NE(host1, manager1->current_frame_host());
1127 EXPECT_TRUE(
1128 host1->render_view_host()->GetEnabledBindings() & BINDINGS_POLICY_WEB_UI);
1130 // Commit and ensure we still have bindings.
1131 manager1->DidNavigateFrame(host1);
1132 SiteInstance* webui_instance = host1->GetSiteInstance();
1133 EXPECT_EQ(host1, manager1->current_frame_host());
1134 EXPECT_TRUE(
1135 host1->render_view_host()->GetEnabledBindings() & BINDINGS_POLICY_WEB_UI);
1137 // Now simulate clicking a link that opens in a new tab.
1138 scoped_ptr<TestWebContents> web_contents2(
1139 TestWebContents::Create(browser_context(), webui_instance));
1140 RenderFrameHostManager* manager2 =
1141 web_contents2->GetRenderManagerForTesting();
1142 // Make sure the new RVH is considered live. This is usually done in
1143 // RenderWidgetHost::Init when opening a new tab from a link.
1144 manager2->current_host()->CreateRenderView(
1145 base::string16(), -1, MSG_ROUTING_NONE, -1, false);
1147 const GURL kUrl2("chrome://foo/bar");
1148 NavigationEntryImpl entry2(NULL /* instance */, -1 /* page_id */, kUrl2,
1149 Referrer(), base::string16() /* title */,
1150 PAGE_TRANSITION_LINK,
1151 true /* is_renderer_init */);
1152 RenderFrameHostImpl* host2 = manager2->Navigate(entry2);
1154 // No cross-process transition happens because we are already in the right
1155 // SiteInstance. We should grant bindings immediately.
1156 EXPECT_EQ(host2, manager2->current_frame_host());
1157 EXPECT_TRUE(
1158 host2->render_view_host()->GetEnabledBindings() & BINDINGS_POLICY_WEB_UI);
1160 manager2->DidNavigateFrame(host2);
1163 // Tests that we don't end up in an inconsistent state if a page does a back and
1164 // then reload. http://crbug.com/51680
1165 TEST_F(RenderFrameHostManagerTest, PageDoesBackAndReload) {
1166 const GURL kUrl1("http://www.google.com/");
1167 const GURL kUrl2("http://www.evil-site.com/");
1169 // Navigate to a safe site, then an evil site.
1170 // This will switch RenderViewHosts. We cannot assert that the first and
1171 // second RVHs are different, though, because the first one may be promptly
1172 // deleted.
1173 contents()->NavigateAndCommit(kUrl1);
1174 contents()->NavigateAndCommit(kUrl2);
1175 RenderViewHost* evil_rvh = contents()->GetRenderViewHost();
1177 // Now let's simulate the evil page calling history.back().
1178 contents()->OnGoToEntryAtOffset(-1);
1179 // We should have a new pending RVH.
1180 // Note that in this case, the navigation has not committed, so evil_rvh will
1181 // not be deleted yet.
1182 EXPECT_NE(evil_rvh, contents()->GetRenderManagerForTesting()->
1183 pending_render_view_host());
1185 // Before that RVH has committed, the evil page reloads itself.
1186 FrameHostMsg_DidCommitProvisionalLoad_Params params;
1187 params.page_id = 1;
1188 params.url = kUrl2;
1189 params.transition = PAGE_TRANSITION_CLIENT_REDIRECT;
1190 params.should_update_history = false;
1191 params.gesture = NavigationGestureAuto;
1192 params.was_within_same_page = false;
1193 params.is_post = false;
1194 params.page_state = PageState::CreateFromURL(kUrl2);
1196 RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>(evil_rvh);
1197 RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(
1198 rvh->GetProcess()->GetID(), rvh->main_frame_routing_id());
1199 contents()->GetFrameTree()->root()->navigator()->DidNavigate(rfh, params);
1201 // That should have cancelled the pending RVH, and the evil RVH should be the
1202 // current one.
1203 EXPECT_TRUE(contents()->GetRenderManagerForTesting()->
1204 pending_render_view_host() == NULL);
1205 EXPECT_EQ(evil_rvh, contents()->GetRenderManagerForTesting()->current_host());
1207 // Also we should not have a pending navigation entry.
1208 EXPECT_TRUE(contents()->GetController().GetPendingEntry() == NULL);
1209 NavigationEntry* entry = contents()->GetController().GetVisibleEntry();
1210 ASSERT_TRUE(entry != NULL);
1211 EXPECT_EQ(kUrl2, entry->GetURL());
1214 // Ensure that we can go back and forward even if a SwapOut ACK isn't received.
1215 // See http://crbug.com/93427.
1216 TEST_F(RenderFrameHostManagerTest, NavigateAfterMissingSwapOutACK) {
1217 const GURL kUrl1("http://www.google.com/");
1218 const GURL kUrl2("http://www.chromium.org/");
1220 // Navigate to two pages.
1221 contents()->NavigateAndCommit(kUrl1);
1222 TestRenderViewHost* rvh1 = test_rvh();
1224 // Keep active_view_count nonzero so that no swapped out views in
1225 // this SiteInstance get forcefully deleted.
1226 static_cast<SiteInstanceImpl*>(rvh1->GetSiteInstance())->
1227 increment_active_view_count();
1229 contents()->NavigateAndCommit(kUrl2);
1230 TestRenderViewHost* rvh2 = test_rvh();
1231 static_cast<SiteInstanceImpl*>(rvh2->GetSiteInstance())->
1232 increment_active_view_count();
1234 // Now go back, but suppose the SwapOut_ACK isn't received. This shouldn't
1235 // happen, but we have seen it when going back quickly across many entries
1236 // (http://crbug.com/93427).
1237 contents()->GetController().GoBack();
1238 EXPECT_TRUE(rvh2->is_waiting_for_beforeunload_ack());
1239 contents()->ProceedWithCrossSiteNavigation();
1240 EXPECT_FALSE(rvh2->is_waiting_for_beforeunload_ack());
1241 StartCrossSiteTransition(contents());
1242 EXPECT_TRUE(rvh2->IsWaitingForUnloadACK());
1244 // The back navigation commits.
1245 const NavigationEntry* entry1 = contents()->GetController().GetPendingEntry();
1246 rvh1->SendNavigate(entry1->GetPageID(), entry1->GetURL());
1247 EXPECT_EQ(RenderViewHostImpl::STATE_PENDING_SWAP_OUT, rvh2->rvh_state());
1249 // We should be able to navigate forward.
1250 contents()->GetController().GoForward();
1251 contents()->ProceedWithCrossSiteNavigation();
1252 StartCrossSiteTransition(contents());
1253 const NavigationEntry* entry2 = contents()->GetController().GetPendingEntry();
1254 rvh2->SendNavigate(entry2->GetPageID(), entry2->GetURL());
1255 EXPECT_EQ(rvh2, rvh());
1256 EXPECT_EQ(RenderViewHostImpl::STATE_DEFAULT, rvh2->rvh_state());
1257 EXPECT_EQ(RenderViewHostImpl::STATE_PENDING_SWAP_OUT, rvh1->rvh_state());
1258 rvh1->OnSwappedOut(false);
1259 EXPECT_TRUE(rvh1->IsSwappedOut());
1262 // Test that we create swapped out RVHs for the opener chain when navigating an
1263 // opened tab cross-process. This allows us to support certain cross-process
1264 // JavaScript calls (http://crbug.com/99202).
1265 TEST_F(RenderFrameHostManagerTest, CreateSwappedOutOpenerRVHs) {
1266 const GURL kUrl1("http://www.google.com/");
1267 const GURL kUrl2("http://www.chromium.org/");
1268 const GURL kChromeUrl("chrome://foo");
1270 // Navigate to an initial URL.
1271 contents()->NavigateAndCommit(kUrl1);
1272 RenderFrameHostManager* manager = contents()->GetRenderManagerForTesting();
1273 TestRenderViewHost* rvh1 = test_rvh();
1275 // Create 2 new tabs and simulate them being the opener chain for the main
1276 // tab. They should be in the same SiteInstance.
1277 scoped_ptr<TestWebContents> opener1(
1278 TestWebContents::Create(browser_context(), rvh1->GetSiteInstance()));
1279 RenderFrameHostManager* opener1_manager =
1280 opener1->GetRenderManagerForTesting();
1281 contents()->SetOpener(opener1.get());
1283 scoped_ptr<TestWebContents> opener2(
1284 TestWebContents::Create(browser_context(), rvh1->GetSiteInstance()));
1285 RenderFrameHostManager* opener2_manager =
1286 opener2->GetRenderManagerForTesting();
1287 opener1->SetOpener(opener2.get());
1289 // Navigate to a cross-site URL (different SiteInstance but same
1290 // BrowsingInstance).
1291 contents()->NavigateAndCommit(kUrl2);
1292 TestRenderViewHost* rvh2 = test_rvh();
1293 EXPECT_NE(rvh1->GetSiteInstance(), rvh2->GetSiteInstance());
1294 EXPECT_TRUE(rvh1->GetSiteInstance()->IsRelatedSiteInstance(
1295 rvh2->GetSiteInstance()));
1297 // Ensure rvh1 is placed on swapped out list of the current tab.
1298 EXPECT_TRUE(manager->IsRVHOnSwappedOutList(rvh1));
1299 EXPECT_EQ(rvh1,
1300 manager->GetSwappedOutRenderViewHost(rvh1->GetSiteInstance()));
1302 // Ensure a swapped out RVH is created in the first opener tab.
1303 TestRenderViewHost* opener1_rvh = static_cast<TestRenderViewHost*>(
1304 opener1_manager->GetSwappedOutRenderViewHost(rvh2->GetSiteInstance()));
1305 EXPECT_TRUE(opener1_manager->IsRVHOnSwappedOutList(opener1_rvh));
1306 EXPECT_TRUE(opener1_rvh->IsSwappedOut());
1308 // Ensure a swapped out RVH is created in the second opener tab.
1309 TestRenderViewHost* opener2_rvh = static_cast<TestRenderViewHost*>(
1310 opener2_manager->GetSwappedOutRenderViewHost(rvh2->GetSiteInstance()));
1311 EXPECT_TRUE(opener2_manager->IsRVHOnSwappedOutList(opener2_rvh));
1312 EXPECT_TRUE(opener2_rvh->IsSwappedOut());
1314 // Navigate to a cross-BrowsingInstance URL.
1315 contents()->NavigateAndCommit(kChromeUrl);
1316 TestRenderViewHost* rvh3 = test_rvh();
1317 EXPECT_NE(rvh1->GetSiteInstance(), rvh3->GetSiteInstance());
1318 EXPECT_FALSE(rvh1->GetSiteInstance()->IsRelatedSiteInstance(
1319 rvh3->GetSiteInstance()));
1321 // No scripting is allowed across BrowsingInstances, so we should not create
1322 // swapped out RVHs for the opener chain in this case.
1323 EXPECT_FALSE(opener1_manager->GetSwappedOutRenderViewHost(
1324 rvh3->GetSiteInstance()));
1325 EXPECT_FALSE(opener2_manager->GetSwappedOutRenderViewHost(
1326 rvh3->GetSiteInstance()));
1329 // Test that we clean up swapped out RenderViewHosts when a process hosting
1330 // those associated RenderViews crashes. http://crbug.com/258993
1331 TEST_F(RenderFrameHostManagerTest, CleanUpSwappedOutRVHOnProcessCrash) {
1332 const GURL kUrl1("http://www.google.com/");
1333 const GURL kUrl2("http://www.chromium.org/");
1335 // Navigate to an initial URL.
1336 contents()->NavigateAndCommit(kUrl1);
1337 TestRenderViewHost* rvh1 = test_rvh();
1339 // Create a new tab as an opener for the main tab.
1340 scoped_ptr<TestWebContents> opener1(
1341 TestWebContents::Create(browser_context(), rvh1->GetSiteInstance()));
1342 RenderFrameHostManager* opener1_manager =
1343 opener1->GetRenderManagerForTesting();
1344 contents()->SetOpener(opener1.get());
1346 // Make sure the new opener RVH is considered live.
1347 opener1_manager->current_host()->CreateRenderView(
1348 base::string16(), -1, MSG_ROUTING_NONE, -1, false);
1350 // Use a cross-process navigation in the opener to swap out the old RVH.
1351 EXPECT_FALSE(opener1_manager->GetSwappedOutRenderViewHost(
1352 rvh1->GetSiteInstance()));
1353 opener1->NavigateAndCommit(kUrl2);
1354 EXPECT_TRUE(opener1_manager->GetSwappedOutRenderViewHost(
1355 rvh1->GetSiteInstance()));
1357 // Fake a process crash.
1358 RenderProcessHost::RendererClosedDetails details(
1359 rvh1->GetProcess()->GetHandle(),
1360 base::TERMINATION_STATUS_PROCESS_CRASHED,
1362 NotificationService::current()->Notify(
1363 NOTIFICATION_RENDERER_PROCESS_CLOSED,
1364 Source<RenderProcessHost>(rvh1->GetProcess()),
1365 Details<RenderProcessHost::RendererClosedDetails>(&details));
1366 rvh1->set_render_view_created(false);
1368 // Ensure that the swapped out RenderViewHost has been deleted.
1369 EXPECT_FALSE(opener1_manager->GetSwappedOutRenderViewHost(
1370 rvh1->GetSiteInstance()));
1372 // Reload the initial tab. This should recreate the opener's swapped out RVH
1373 // in the original SiteInstance.
1374 contents()->GetController().Reload(true);
1375 EXPECT_EQ(opener1_manager->GetSwappedOutRenderViewHost(
1376 rvh1->GetSiteInstance())->GetRoutingID(),
1377 test_rvh()->opener_route_id());
1380 // Test that RenderViewHosts created for WebUI navigations are properly
1381 // granted WebUI bindings even if an unprivileged swapped out RenderViewHost
1382 // is in the same process (http://crbug.com/79918).
1383 TEST_F(RenderFrameHostManagerTest, EnableWebUIWithSwappedOutOpener) {
1384 set_should_create_webui(true);
1385 const GURL kSettingsUrl("chrome://chrome/settings");
1386 const GURL kPluginUrl("chrome://plugins");
1388 // Navigate to an initial WebUI URL.
1389 contents()->NavigateAndCommit(kSettingsUrl);
1391 // Ensure the RVH has WebUI bindings.
1392 TestRenderViewHost* rvh1 = test_rvh();
1393 EXPECT_TRUE(rvh1->GetEnabledBindings() & BINDINGS_POLICY_WEB_UI);
1395 // Create a new tab and simulate it being the opener for the main
1396 // tab. It should be in the same SiteInstance.
1397 scoped_ptr<TestWebContents> opener1(
1398 TestWebContents::Create(browser_context(), rvh1->GetSiteInstance()));
1399 RenderFrameHostManager* opener1_manager =
1400 opener1->GetRenderManagerForTesting();
1401 contents()->SetOpener(opener1.get());
1403 // Navigate to a different WebUI URL (different SiteInstance, same
1404 // BrowsingInstance).
1405 contents()->NavigateAndCommit(kPluginUrl);
1406 TestRenderViewHost* rvh2 = test_rvh();
1407 EXPECT_NE(rvh1->GetSiteInstance(), rvh2->GetSiteInstance());
1408 EXPECT_TRUE(rvh1->GetSiteInstance()->IsRelatedSiteInstance(
1409 rvh2->GetSiteInstance()));
1411 // Ensure a swapped out RVH is created in the first opener tab.
1412 TestRenderViewHost* opener1_rvh = static_cast<TestRenderViewHost*>(
1413 opener1_manager->GetSwappedOutRenderViewHost(rvh2->GetSiteInstance()));
1414 EXPECT_TRUE(opener1_manager->IsRVHOnSwappedOutList(opener1_rvh));
1415 EXPECT_TRUE(opener1_rvh->IsSwappedOut());
1417 // Ensure the new RVH has WebUI bindings.
1418 EXPECT_TRUE(rvh2->GetEnabledBindings() & BINDINGS_POLICY_WEB_UI);
1421 // Test that we reuse the same guest SiteInstance if we navigate across sites.
1422 TEST_F(RenderFrameHostManagerTest, NoSwapOnGuestNavigations) {
1423 TestNotificationTracker notifications;
1425 GURL guest_url(std::string(kGuestScheme).append("://abc123"));
1426 SiteInstance* instance =
1427 SiteInstance::CreateForURL(browser_context(), guest_url);
1428 scoped_ptr<TestWebContents> web_contents(
1429 TestWebContents::Create(browser_context(), instance));
1431 RenderFrameHostManager* manager = web_contents->GetRenderManagerForTesting();
1433 RenderFrameHostImpl* host;
1435 // 1) The first navigation. --------------------------
1436 const GURL kUrl1("http://www.google.com/");
1437 NavigationEntryImpl entry1(
1438 NULL /* instance */, -1 /* page_id */, kUrl1, Referrer(),
1439 base::string16() /* title */, PAGE_TRANSITION_TYPED,
1440 false /* is_renderer_init */);
1441 host = manager->Navigate(entry1);
1443 // The RenderFrameHost created in Init will be reused.
1444 EXPECT_TRUE(host == manager->current_frame_host());
1445 EXPECT_FALSE(manager->pending_frame_host());
1446 EXPECT_EQ(manager->current_frame_host()->GetSiteInstance(), instance);
1448 // Commit.
1449 manager->DidNavigateFrame(host);
1450 // Commit to SiteInstance should be delayed until RenderView commit.
1451 EXPECT_EQ(host, manager->current_frame_host());
1452 ASSERT_TRUE(host);
1453 EXPECT_TRUE(static_cast<SiteInstanceImpl*>(host->GetSiteInstance())->
1454 HasSite());
1456 // 2) Navigate to a different domain. -------------------------
1457 // Guests stay in the same process on navigation.
1458 const GURL kUrl2("http://www.chromium.org");
1459 NavigationEntryImpl entry2(
1460 NULL /* instance */, -1 /* page_id */, kUrl2,
1461 Referrer(kUrl1, blink::WebReferrerPolicyDefault),
1462 base::string16() /* title */, PAGE_TRANSITION_LINK,
1463 true /* is_renderer_init */);
1464 host = manager->Navigate(entry2);
1466 // The RenderFrameHost created in Init will be reused.
1467 EXPECT_EQ(host, manager->current_frame_host());
1468 EXPECT_FALSE(manager->pending_frame_host());
1470 // Commit.
1471 manager->DidNavigateFrame(host);
1472 EXPECT_EQ(host, manager->current_frame_host());
1473 ASSERT_TRUE(host);
1474 EXPECT_EQ(static_cast<SiteInstanceImpl*>(host->GetSiteInstance()),
1475 instance);
1478 // Test that we cancel a pending RVH if we close the tab while it's pending.
1479 // http://crbug.com/294697.
1480 TEST_F(RenderFrameHostManagerTest, NavigateWithEarlyClose) {
1481 TestNotificationTracker notifications;
1483 SiteInstance* instance = SiteInstance::Create(browser_context());
1485 BeforeUnloadFiredWebContentsDelegate delegate;
1486 scoped_ptr<TestWebContents> web_contents(
1487 TestWebContents::Create(browser_context(), instance));
1488 web_contents->SetDelegate(&delegate);
1489 notifications.ListenFor(NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
1490 Source<WebContents>(web_contents.get()));
1492 RenderFrameHostManager* manager = web_contents->GetRenderManagerForTesting();
1494 // 1) The first navigation. --------------------------
1495 const GURL kUrl1("http://www.google.com/");
1496 NavigationEntryImpl entry1(NULL /* instance */, -1 /* page_id */, kUrl1,
1497 Referrer(), base::string16() /* title */,
1498 PAGE_TRANSITION_TYPED,
1499 false /* is_renderer_init */);
1500 RenderFrameHostImpl* host = manager->Navigate(entry1);
1502 // The RenderFrameHost created in Init will be reused.
1503 EXPECT_EQ(host, manager->current_frame_host());
1504 EXPECT_FALSE(manager->pending_frame_host());
1506 // We should observe a notification.
1507 EXPECT_TRUE(
1508 notifications.Check1AndReset(NOTIFICATION_RENDER_VIEW_HOST_CHANGED));
1509 notifications.Reset();
1511 // Commit.
1512 manager->DidNavigateFrame(host);
1514 // Commit to SiteInstance should be delayed until RenderFrame commits.
1515 EXPECT_EQ(host, manager->current_frame_host());
1516 EXPECT_FALSE(static_cast<SiteInstanceImpl*>(host->GetSiteInstance())->
1517 HasSite());
1518 static_cast<SiteInstanceImpl*>(host->GetSiteInstance())->SetSite(kUrl1);
1520 // 2) Cross-site navigate to next site. -------------------------
1521 const GURL kUrl2("http://www.example.com");
1522 NavigationEntryImpl entry2(
1523 NULL /* instance */, -1 /* page_id */, kUrl2, Referrer(),
1524 base::string16() /* title */, PAGE_TRANSITION_TYPED,
1525 false /* is_renderer_init */);
1526 RenderFrameHostImpl* host2 = manager->Navigate(entry2);
1528 // A new RenderFrameHost should be created.
1529 ASSERT_EQ(host2, manager->pending_frame_host());
1530 EXPECT_NE(host2, host);
1532 EXPECT_EQ(host, manager->current_frame_host());
1533 EXPECT_FALSE(manager->current_frame_host()->is_swapped_out());
1534 EXPECT_EQ(host2, manager->pending_frame_host());
1536 // 3) Close the tab. -------------------------
1537 notifications.ListenFor(NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1538 Source<RenderWidgetHost>(host2->render_view_host()));
1539 manager->OnBeforeUnloadACK(false, true, base::TimeTicks());
1541 EXPECT_TRUE(
1542 notifications.Check1AndReset(NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED));
1543 EXPECT_FALSE(manager->pending_frame_host());
1544 EXPECT_EQ(host, manager->current_frame_host());
1547 // Tests that the RenderViewHost is properly deleted when the SwapOutACK is
1548 // received before the new page commits.
1549 TEST_F(RenderFrameHostManagerTest,
1550 SwapOutACKBeforeNewPageCommitsLeadsToDeletion) {
1551 const GURL kUrl1("http://www.google.com/");
1552 const GURL kUrl2("http://www.chromium.org/");
1554 // Navigate to the first page.
1555 contents()->NavigateAndCommit(kUrl1);
1556 TestRenderViewHost* rvh1 = test_rvh();
1557 RenderViewHostDeletedObserver rvh_deleted_observer(rvh1);
1558 EXPECT_EQ(RenderViewHostImpl::STATE_DEFAULT, rvh1->rvh_state());
1560 // Navigate to new site, simulating onbeforeunload approval.
1561 controller().LoadURL(kUrl2, Referrer(), PAGE_TRANSITION_LINK, std::string());
1562 base::TimeTicks now = base::TimeTicks::Now();
1563 main_test_rfh()->OnMessageReceived(
1564 FrameHostMsg_BeforeUnload_ACK(0, true, now, now));
1565 EXPECT_TRUE(contents()->cross_navigation_pending());
1566 TestRenderViewHost* rvh2 =
1567 static_cast<TestRenderViewHost*>(contents()->GetPendingRenderViewHost());
1569 // Simulate rvh2's response, which leads to an unload request being sent to
1570 // rvh1.
1571 std::vector<GURL> url_chain;
1572 url_chain.push_back(GURL());
1573 contents()->GetRenderManagerForTesting()->OnCrossSiteResponse(
1574 contents()->GetRenderManagerForTesting()->pending_frame_host(),
1575 GlobalRequestID(0, 0), scoped_ptr<CrossSiteTransferringRequest>(),
1576 url_chain, Referrer(), PAGE_TRANSITION_TYPED, false);
1577 EXPECT_TRUE(contents()->cross_navigation_pending());
1578 EXPECT_EQ(RenderViewHostImpl::STATE_WAITING_FOR_UNLOAD_ACK,
1579 rvh1->rvh_state());
1581 // Simulate the swap out ack.
1582 rvh1->OnSwappedOut(false);
1583 EXPECT_EQ(RenderViewHostImpl::STATE_WAITING_FOR_COMMIT, rvh1->rvh_state());
1585 // The new page commits.
1586 contents()->TestDidNavigate(rvh2, 1, kUrl2, PAGE_TRANSITION_TYPED);
1587 EXPECT_FALSE(contents()->cross_navigation_pending());
1588 EXPECT_EQ(rvh2, rvh());
1589 EXPECT_TRUE(contents()->GetPendingRenderViewHost() == NULL);
1590 EXPECT_EQ(RenderViewHostImpl::STATE_DEFAULT, rvh2->rvh_state());
1592 // rvh1 should have been deleted.
1593 EXPECT_TRUE(rvh_deleted_observer.deleted());
1594 rvh1 = NULL;
1597 // Tests that the RenderViewHost is properly swapped out when the SwapOutACK is
1598 // received before the new page commits.
1599 TEST_F(RenderFrameHostManagerTest,
1600 SwapOutACKBeforeNewPageCommitsLeadsToSwapOut) {
1601 const GURL kUrl1("http://www.google.com/");
1602 const GURL kUrl2("http://www.chromium.org/");
1604 // Navigate to the first page.
1605 contents()->NavigateAndCommit(kUrl1);
1606 TestRenderViewHost* rvh1 = test_rvh();
1607 RenderViewHostDeletedObserver rvh_deleted_observer(rvh1);
1608 EXPECT_EQ(RenderViewHostImpl::STATE_DEFAULT, rvh1->rvh_state());
1610 // Increment the number of active views in SiteInstanceImpl so that rvh2 is
1611 // not deleted on swap out.
1612 static_cast<SiteInstanceImpl*>(
1613 rvh1->GetSiteInstance())->increment_active_view_count();
1615 // Navigate to new site, simulating onbeforeunload approval.
1616 controller().LoadURL(kUrl2, Referrer(), PAGE_TRANSITION_LINK, std::string());
1617 base::TimeTicks now = base::TimeTicks::Now();
1618 main_test_rfh()->OnMessageReceived(
1619 FrameHostMsg_BeforeUnload_ACK(0, true, now, now));
1620 EXPECT_TRUE(contents()->cross_navigation_pending());
1621 TestRenderViewHost* rvh2 =
1622 static_cast<TestRenderViewHost*>(contents()->GetPendingRenderViewHost());
1624 // Simulate rvh2's response, which leads to an unload request being sent to
1625 // rvh1.
1626 std::vector<GURL> url_chain;
1627 url_chain.push_back(GURL());
1628 contents()->GetRenderManagerForTesting()->OnCrossSiteResponse(
1629 contents()->GetRenderManagerForTesting()->pending_frame_host(),
1630 GlobalRequestID(0, 0), scoped_ptr<CrossSiteTransferringRequest>(),
1631 url_chain, Referrer(), PAGE_TRANSITION_TYPED, false);
1632 EXPECT_TRUE(contents()->cross_navigation_pending());
1633 EXPECT_EQ(RenderViewHostImpl::STATE_WAITING_FOR_UNLOAD_ACK,
1634 rvh1->rvh_state());
1636 // Simulate the swap out ack.
1637 rvh1->OnSwappedOut(false);
1638 EXPECT_EQ(RenderViewHostImpl::STATE_WAITING_FOR_COMMIT, rvh1->rvh_state());
1640 // The new page commits.
1641 contents()->TestDidNavigate(rvh2, 1, kUrl2, PAGE_TRANSITION_TYPED);
1642 EXPECT_FALSE(contents()->cross_navigation_pending());
1643 EXPECT_EQ(rvh2, rvh());
1644 EXPECT_TRUE(contents()->GetPendingRenderViewHost() == NULL);
1645 EXPECT_EQ(RenderViewHostImpl::STATE_DEFAULT, rvh2->rvh_state());
1647 // rvh1 should be swapped out.
1648 EXPECT_FALSE(rvh_deleted_observer.deleted());
1649 EXPECT_TRUE(rvh1->IsSwappedOut());
1652 // Tests that the RenderViewHost is properly deleted when the new
1653 // page commits before the swap out ack is received.
1654 TEST_F(RenderFrameHostManagerTest,
1655 NewPageCommitsBeforeSwapOutACKLeadsToDeletion) {
1656 const GURL kUrl1("http://www.google.com/");
1657 const GURL kUrl2("http://www.chromium.org/");
1659 // Navigate to the first page.
1660 contents()->NavigateAndCommit(kUrl1);
1661 TestRenderViewHost* rvh1 = test_rvh();
1662 RenderViewHostDeletedObserver rvh_deleted_observer(rvh1);
1663 EXPECT_EQ(RenderViewHostImpl::STATE_DEFAULT, rvh1->rvh_state());
1665 // Navigate to new site, simulating onbeforeunload approval.
1666 controller().LoadURL(kUrl2, Referrer(), PAGE_TRANSITION_LINK, std::string());
1667 base::TimeTicks now = base::TimeTicks::Now();
1668 main_test_rfh()->OnMessageReceived(
1669 FrameHostMsg_BeforeUnload_ACK(0, true, now, now));
1670 EXPECT_TRUE(contents()->cross_navigation_pending());
1671 TestRenderViewHost* rvh2 =
1672 static_cast<TestRenderViewHost*>(contents()->GetPendingRenderViewHost());
1674 // Simulate rvh2's response, which leads to an unload request being sent to
1675 // rvh1.
1676 std::vector<GURL> url_chain;
1677 url_chain.push_back(GURL());
1678 contents()->GetRenderManagerForTesting()->OnCrossSiteResponse(
1679 contents()->GetRenderManagerForTesting()->pending_frame_host(),
1680 GlobalRequestID(0, 0), scoped_ptr<CrossSiteTransferringRequest>(),
1681 url_chain, Referrer(), PAGE_TRANSITION_TYPED, false);
1682 EXPECT_TRUE(contents()->cross_navigation_pending());
1683 EXPECT_EQ(RenderViewHostImpl::STATE_WAITING_FOR_UNLOAD_ACK,
1684 rvh1->rvh_state());
1686 // The new page commits.
1687 contents()->TestDidNavigate(rvh2, 1, kUrl2, PAGE_TRANSITION_TYPED);
1688 EXPECT_FALSE(contents()->cross_navigation_pending());
1689 EXPECT_EQ(rvh2, rvh());
1690 EXPECT_TRUE(contents()->GetPendingRenderViewHost() == NULL);
1691 EXPECT_EQ(RenderViewHostImpl::STATE_DEFAULT, rvh2->rvh_state());
1692 EXPECT_EQ(RenderViewHostImpl::STATE_PENDING_SHUTDOWN, rvh1->rvh_state());
1694 // Simulate the swap out ack.
1695 rvh1->OnSwappedOut(false);
1697 // rvh1 should have been deleted.
1698 EXPECT_TRUE(rvh_deleted_observer.deleted());
1699 rvh1 = NULL;
1702 // Tests that the RenderViewHost is properly swapped out when the new page
1703 // commits before the swap out ack is received.
1704 TEST_F(RenderFrameHostManagerTest,
1705 NewPageCommitsBeforeSwapOutACKLeadsToSwapOut) {
1706 const GURL kUrl1("http://www.google.com/");
1707 const GURL kUrl2("http://www.chromium.org/");
1709 // Navigate to the first page.
1710 contents()->NavigateAndCommit(kUrl1);
1711 TestRenderViewHost* rvh1 = test_rvh();
1712 RenderViewHostDeletedObserver rvh_deleted_observer(rvh1);
1713 EXPECT_EQ(RenderViewHostImpl::STATE_DEFAULT, rvh1->rvh_state());
1715 // Increment the number of active views in SiteInstanceImpl so that rvh1 is
1716 // not deleted on swap out.
1717 static_cast<SiteInstanceImpl*>(
1718 rvh1->GetSiteInstance())->increment_active_view_count();
1720 // Navigate to new site, simulating onbeforeunload approval.
1721 controller().LoadURL(kUrl2, Referrer(), PAGE_TRANSITION_LINK, std::string());
1722 base::TimeTicks now = base::TimeTicks::Now();
1723 main_test_rfh()->OnMessageReceived(
1724 FrameHostMsg_BeforeUnload_ACK(0, true, now, now));
1725 EXPECT_TRUE(contents()->cross_navigation_pending());
1726 TestRenderViewHost* rvh2 =
1727 static_cast<TestRenderViewHost*>(contents()->GetPendingRenderViewHost());
1729 // Simulate rvh2's response, which leads to an unload request being sent to
1730 // rvh1.
1731 std::vector<GURL> url_chain;
1732 url_chain.push_back(GURL());
1733 contents()->GetRenderManagerForTesting()->OnCrossSiteResponse(
1734 contents()->GetRenderManagerForTesting()->pending_frame_host(),
1735 GlobalRequestID(0, 0), scoped_ptr<CrossSiteTransferringRequest>(),
1736 url_chain, Referrer(), PAGE_TRANSITION_TYPED, false);
1737 EXPECT_TRUE(contents()->cross_navigation_pending());
1738 EXPECT_EQ(RenderViewHostImpl::STATE_WAITING_FOR_UNLOAD_ACK,
1739 rvh1->rvh_state());
1741 // The new page commits.
1742 contents()->TestDidNavigate(rvh2, 1, kUrl2, PAGE_TRANSITION_TYPED);
1743 EXPECT_FALSE(contents()->cross_navigation_pending());
1744 EXPECT_EQ(rvh2, rvh());
1745 EXPECT_TRUE(contents()->GetPendingRenderViewHost() == NULL);
1746 EXPECT_EQ(RenderViewHostImpl::STATE_DEFAULT, rvh2->rvh_state());
1747 EXPECT_EQ(RenderViewHostImpl::STATE_PENDING_SWAP_OUT, rvh1->rvh_state());
1749 // Simulate the swap out ack.
1750 rvh1->OnSwappedOut(false);
1752 // rvh1 should be swapped out.
1753 EXPECT_FALSE(rvh_deleted_observer.deleted());
1754 EXPECT_TRUE(rvh1->IsSwappedOut());
1757 // Test that the RenderViewHost is properly swapped out if a navigation in the
1758 // new renderer commits before sending the SwapOut message to the old renderer.
1759 // This simulates a cross-site navigation to a synchronously committing URL
1760 // (e.g., a data URL) and ensures it works properly.
1761 TEST_F(RenderFrameHostManagerTest,
1762 CommitNewNavigationBeforeSendingSwapOut) {
1763 const GURL kUrl1("http://www.google.com/");
1764 const GURL kUrl2("http://www.chromium.org/");
1766 // Navigate to the first page.
1767 contents()->NavigateAndCommit(kUrl1);
1768 TestRenderViewHost* rvh1 = test_rvh();
1769 RenderViewHostDeletedObserver rvh_deleted_observer(rvh1);
1770 EXPECT_EQ(RenderViewHostImpl::STATE_DEFAULT, rvh1->rvh_state());
1772 // Increment the number of active views in SiteInstanceImpl so that rvh1 is
1773 // not deleted on swap out.
1774 static_cast<SiteInstanceImpl*>(
1775 rvh1->GetSiteInstance())->increment_active_view_count();
1777 // Navigate to new site, simulating onbeforeunload approval.
1778 controller().LoadURL(kUrl2, Referrer(), PAGE_TRANSITION_LINK, std::string());
1779 base::TimeTicks now = base::TimeTicks::Now();
1780 main_test_rfh()->OnMessageReceived(
1781 FrameHostMsg_BeforeUnload_ACK(0, true, now, now));
1782 EXPECT_TRUE(contents()->cross_navigation_pending());
1783 TestRenderViewHost* rvh2 =
1784 static_cast<TestRenderViewHost*>(contents()->GetPendingRenderViewHost());
1786 // The new page commits.
1787 contents()->TestDidNavigate(rvh2, 1, kUrl2, PAGE_TRANSITION_TYPED);
1788 EXPECT_FALSE(contents()->cross_navigation_pending());
1789 EXPECT_EQ(rvh2, rvh());
1790 EXPECT_TRUE(contents()->GetPendingRenderViewHost() == NULL);
1791 EXPECT_EQ(RenderViewHostImpl::STATE_DEFAULT, rvh2->rvh_state());
1792 EXPECT_EQ(RenderViewHostImpl::STATE_PENDING_SWAP_OUT, rvh1->rvh_state());
1794 // Simulate the swap out ack.
1795 rvh1->OnSwappedOut(false);
1797 // rvh1 should be swapped out.
1798 EXPECT_FALSE(rvh_deleted_observer.deleted());
1799 EXPECT_TRUE(rvh1->IsSwappedOut());
1802 // Test that a RenderFrameHost is properly deleted or swapped out when a
1803 // cross-site navigation is cancelled.
1804 TEST_F(RenderFrameHostManagerTest,
1805 CancelPendingProperlyDeletesOrSwaps) {
1806 const GURL kUrl1("http://www.google.com/");
1807 const GURL kUrl2("http://www.chromium.org/");
1808 RenderFrameHostImpl* pending_rfh = NULL;
1809 base::TimeTicks now = base::TimeTicks::Now();
1811 // Navigate to the first page.
1812 contents()->NavigateAndCommit(kUrl1);
1813 TestRenderViewHost* rvh1 = test_rvh();
1814 EXPECT_EQ(RenderViewHostImpl::STATE_DEFAULT, rvh1->rvh_state());
1816 // Navigate to a new site, starting a cross-site navigation.
1817 controller().LoadURL(kUrl2, Referrer(), PAGE_TRANSITION_LINK, std::string());
1819 pending_rfh = contents()->GetFrameTree()->root()->render_manager()
1820 ->pending_frame_host();
1821 RenderFrameHostDeletedObserver rvh_deleted_observer(pending_rfh);
1823 // Cancel the navigation by simulating a declined beforeunload dialog.
1824 main_test_rfh()->OnMessageReceived(
1825 FrameHostMsg_BeforeUnload_ACK(0, false, now, now));
1826 EXPECT_FALSE(contents()->cross_navigation_pending());
1828 // Since the pending RFH is the only one for the new SiteInstance, it should
1829 // be deleted.
1830 EXPECT_TRUE(rvh_deleted_observer.deleted());
1833 // Start another cross-site navigation.
1834 controller().LoadURL(kUrl2, Referrer(), PAGE_TRANSITION_LINK, std::string());
1836 pending_rfh = contents()->GetFrameTree()->root()->render_manager()
1837 ->pending_frame_host();
1838 RenderFrameHostDeletedObserver rvh_deleted_observer(pending_rfh);
1840 // Increment the number of active views in the new SiteInstance, which will
1841 // cause the pending RFH to be swapped out instead of deleted.
1842 static_cast<SiteInstanceImpl*>(
1843 pending_rfh->GetSiteInstance())->increment_active_view_count();
1845 main_test_rfh()->OnMessageReceived(
1846 FrameHostMsg_BeforeUnload_ACK(0, false, now, now));
1847 EXPECT_FALSE(contents()->cross_navigation_pending());
1848 EXPECT_FALSE(rvh_deleted_observer.deleted());
1852 // Browser-side navigation: Test that a proper NavigationRequest is created by
1853 // BeginNavigation.
1854 TEST_F(RenderFrameHostManagerTest, BrowserSideNavigationBeginNavigation) {
1855 const GURL kUrl1("http://www.google.com/");
1856 const GURL kUrl2("http://www.chromium.org/");
1857 const GURL kUrl3("http://www.gmail.com/");
1859 // Navigate to the first page.
1860 contents()->NavigateAndCommit(kUrl1);
1861 TestRenderViewHost* rvh1 = test_rvh();
1862 EXPECT_EQ(RenderViewHostImpl::STATE_DEFAULT, rvh1->rvh_state());
1864 // Add a subframe.
1865 TestRenderFrameHost* subframe_rfh = static_cast<TestRenderFrameHost*>(
1866 contents()->GetFrameTree()->AddFrame(
1867 contents()->GetFrameTree()->root(), 14, "Child"));
1869 // Simulate a BeginNavigation IPC on the subframe.
1870 subframe_rfh->SendBeginNavigationWithURL(kUrl2);
1871 NavigationRequest* subframe_request =
1872 NavigationRequestForRenderFrameManager(
1873 subframe_rfh->frame_tree_node()->render_manager());
1874 ASSERT_TRUE(subframe_request);
1875 EXPECT_EQ(kUrl2, subframe_request->info_for_testing().navigation_params.url);
1876 // First party for cookies url should be that of the main frame.
1877 EXPECT_EQ(
1878 kUrl1, subframe_request->info_for_testing().first_party_for_cookies);
1879 EXPECT_FALSE(subframe_request->info_for_testing().is_main_frame);
1880 EXPECT_TRUE(subframe_request->info_for_testing().parent_is_main_frame);
1882 // Simulate a BeginNavigation IPC on the main frame.
1883 main_test_rfh()->SendBeginNavigationWithURL(kUrl3);
1884 NavigationRequest* main_request =
1885 NavigationRequestForRenderFrameManager(
1886 main_test_rfh()->frame_tree_node()->render_manager());
1887 ASSERT_TRUE(main_request);
1888 EXPECT_EQ(kUrl3, main_request->info_for_testing().navigation_params.url);
1889 EXPECT_EQ(kUrl3, main_request->info_for_testing().first_party_for_cookies);
1890 EXPECT_TRUE(main_request->info_for_testing().is_main_frame);
1891 EXPECT_FALSE(main_request->info_for_testing().parent_is_main_frame);
1894 } // namespace content