1
    2
    3
    4
    5
    6
    7
    8
    9
   10
   11
   12
   13
   14
   15
   16
   17
   18
   19
   20
   21
   22
   23
   24
   25
   26
   27
   28
   29
   30
   31
   32
   33
   34
   35
   36
   37
   38
   39
   40
   41
   42
   43
   44
   45
   46
   47
   48
   49
   50
   51
   52
   53
   54
   55
   56
   57
   58
   59
   60
   61
   62
   63
   64
   65
   66
   67
   68
   69
   70
   71
   72
   73
   74
   75
   76
   77
   78
   79
   80
   81
   82
   83
   84
   85
   86
   87
   88
   89
   90
   91
   92
   93
   94
   95
   96
   97
   98
   99
  100
  101
  102
  103
  104
  105
  106
  107
  108
  109
  110
  111
  112
  113
  114
  115
  116
  117
  118
  119
  120
  121
  122
  123
  124
  125
  126
  127
  128
  129
  130
  131
  132
  133
  134
  135
  136
  137
  138
  139
  140
  141
  142
  143
  144
  145
  146
  147
  148
  149
  150
  151
  152
  153
  154
  155
  156
  157
  158
  159
  160
  161
  162
  163
  164
  165
  166
  167
  168
  169
  170
  171
  172
  173
  174
  175
  176
  177
  178
  179
  180
  181
  182
  183
  184
  185
  186
  187
  188
  189
  190
  191
  192
  193
  194
  195
  196
  197
  198
  199
  200
  201
  202
  203
  204
  205
  206
  207
  208
  209
  210
  211
  212
  213
  214
  215
  216
  217
  218
  219
  220
  221
  222
  223
  224
  225
  226
  227
  228
  229
  230
  231
  232
  233
  234
  235
  236
  237
  238
  239
  240
  241
  242
  243
  244
  245
  246
  247
  248
  249
  250
  251
  252
  253
  254
  255
  256
  257
  258
  259
  260
  261
  262
  263
  264
  265
  266
  267
  268
  269
  270
  271
  272
  273
  274
  275
  276
  277
  278
  279
  280
  281
  282
  283
  284
  285
  286
  287
  288
  289
  290
  291
  292
  293
  294
  295
  296
  297
  298
  299
  300
  301
  302
  303
  304
  305
  306
  307
  308
  309
  310
  311
  312
  313
  314
  315
  316
  317
  318
  319
  320
  321
  322
  323
  324
  325
  326
  327
  328
  329
  330
  331
  332
  333
  334
  335
  336
  337
  338
  339
  340
  341
  342
  343
  344
  345
  346
  347
  348
  349
  350
  351
  352
  353
  354
  355
  356
  357
  358
  359
  360
  361
  362
  363
  364
  365
  366
  367
  368
  369
  370
  371
  372
  373
  374
  375
  376
  377
  378
  379
  380
  381
  382
  383
  384
  385
  386
  387
  388
  389
  390
  391
  392
  393
  394
  395
  396
  397
  398
  399
  400
  401
  402
  403
  404
  405
  406
  407
  408
  409
  410
  411
  412
  413
  414
  415
  416
  417
  418
  419
  420
  421
  422
  423
  424
  425
  426
  427
  428
  429
  430
  431
  432
  433
  434
  435
  436
  437
  438
  439
  440
  441
  442
  443
  444
  445
  446
  447
  448
  449
  450
  451
  452
  453
  454
  455
  456
  457
  458
  459
  460
  461
  462
  463
  464
  465
  466
  467
  468
  469
  470
  471
  472
  473
  474
  475
  476
  477
  478
  479
  480
  481
  482
  483
  484
  485
  486
  487
  488
  489
  490
  491
  492
  493
  494
  495
  496
  497
  498
  499
  500
  501
  502
  503
  504
  505
  506
  507
  508
  509
  510
  511
  512
  513
  514
  515
  516
  517
  518
  519
  520
  521
  522
  523
  524
  525
  526
  527
  528
  529
  530
  531
  532
  533
  534
  535
  536
  537
  538
  539
  540
  541
  542
  543
  544
  545
  546
  547
  548
  549
  550
  551
  552
  553
  554
  555
  556
  557
  558
  559
  560
  561
  562
  563
  564
  565
  566
  567
  568
  569
  570
  571
  572
  573
  574
  575
  576
  577
  578
  579
  580
  581
  582
  583
  584
  585
  586
  587
  588
  589
  590
  591
  592
  593
  594
  595
  596
  597
  598
  599
  600
  601
  602
  603
  604
  605
  606
  607
  608
  609
  610
  611
  612
  613
  614
  615
  616
  617
  618
  619
  620
  621
  622
  623
  624
  625
  626
  627
  628
  629
  630
  631
  632
  633
  634
  635
  636
  637
  638
  639
  640
  641
  642
  643
  644
  645
  646
  647
  648
  649
  650
  651
  652
  653
  654
  655
  656
  657
  658
  659
  660
  661
  662
  663
  664
  665
  666
  667
  668
  669
  670
  671
  672
  673
  674
  675
  676
  677
  678
  679
  680
  681
  682
  683
  684
  685
  686
  687
  688
  689
  690
  691
  692
  693
  694
  695
  696
  697
  698
  699
  700
  701
  702
  703
  704
  705
  706
  707
  708
  709
  710
  711
  712
  713
  714
  715
  716
  717
  718
  719
  720
  721
  722
  723
  724
  725
  726
  727
  728
  729
  730
  731
  732
  733
  734
  735
  736
  737
  738
  739
  740
  741
  742
  743
  744
  745
  746
  747
  748
  749
  750
  751
  752
  753
  754
  755
  756
  757
  758
  759
  760
  761
  762
  763
  764
  765
  766
  767
  768
  769
  770
  771
  772
  773
  774
  775
  776
  777
  778
  779
  780
  781
  782
  783
  784
  785
  786
  787
  788
  789
  790
  791
  792
  793
  794
  795
  796
  797
  798
  799
  800
  801
  802
  803
  804
  805
  806
  807
  808
  809
  810
  811
  812
  813
  814
  815
  816
  817
  818
  819
  820
  821
  822
  823
  824
  825
  826
  827
  828
  829
  830
  831
  832
  833
  834
  835
  836
  837
  838
  839
  840
  841
  842
  843
  844
  845
  846
  847
  848
  849
  850
  851
  852
  853
  854
  855
  856
  857
  858
  859
  860
  861
  862
  863
  864
  865
  866
  867
  868
  869
  870
  871
  872
  873
  874
  875
  876
  877
  878
  879
  880
  881
  882
  883
  884
  885
  886
  887
  888
  889
  890
  891
  892
  893
  894
  895
  896
  897
  898
  899
  900
  901
  902
  903
  904
  905
  906
  907
  908
  909
  910
  911
  912
  913
  914
  915
  916
  917
  918
  919
  920
  921
  922
  923
  924
  925
  926
  927
  928
  929
  930
  931
  932
  933
  934
  935
  936
  937
  938
  939
  940
  941
  942
  943
  944
  945
  946
  947
  948
  949
  950
  951
  952
  953
  954
  955
  956
  957
  958
  959
  960
  961
  962
  963
  964
  965
  966
  967
  968
  969
  970
  971
  972
  973
  974
  975
  976
  977
  978
  979
  980
  981
  982
  983
  984
  985
  986
  987
  988
  989
  990
  991
  992
  993
  994
  995
  996
  997
  998
  999
 1000
 1001
 1002
 1003
 1004
 1005
 1006
 1007
 1008
 1009
 1010
 1011
 1012
 1013
 1014
 1015
 1016
 1017
 1018
 1019
 1020
 1021
 1022
 1023
 1024
 1025
 1026
 1027
 1028
 1029
 1030
 1031
 1032
 1033
 1034
 1035
 1036
 1037
 1038
 1039
 1040
 1041
 1042
 1043
 1044
 1045
 1046
 1047
 1048
 1049
 1050
 1051
 1052
 1053
 1054
 1055
 1056
 1057
 1058
 1059
 1060
 1061
 1062
 1063
 1064
 1065
 1066
 1067
 1068
 1069
 1070
 1071
 1072
 1073
 1074
 1075
 1076
 1077
 1078
 1079
 1080
 1081
 1082
 1083
 1084
 1085
 1086
 1087
 1088
 1089
 1090
 1091
 1092
 1093
 1094
 1095
 1096
 1097
 1098
 1099
 1100
 1101
 1102
 1103
 1104
 1105
 1106
 1107
 1108
 1109
 1110
 1111
 1112
 1113
 1114
 1115
 1116
 1117
 1118
 1119
 1120
 1121
 1122
 1123
 1124
 1125
 1126
 1127
 1128
 1129
 1130
 1131
 1132
 1133
 1134
 1135
 1136
 1137
 1138
 1139
 1140
 1141
 1142
 1143
 1144
 1145
 1146
 1147
 1148
 1149
 1150
 1151
 1152
 1153
 1154
 1155
 1156
 1157
 1158
 1159
 1160
 1161
 1162
 1163
 1164
 1165
 1166
 1167
 1168
 1169
 1170
 1171
 1172
 1173
 1174
 1175
 1176
 1177
 1178
 1179
 1180
 1181
 1182
 1183
 1184
 1185
 1186
 1187
 1188
 1189
 1190
 1191
 1192
 1193
 1194
 1195
 1196
 1197
 1198
 1199
 1200
 1201
 1202
 1203
 1204
 1205
 1206
 1207
 1208
 1209
 1210
 1211
 1212
 1213
 1214
 1215
 1216
 1217
 1218
 1219
 1220
 1221
 1222
 1223
 1224
 1225
 1226
 1227
 1228
 1229
 1230
 1231
 1232
 1233
 1234
 1235
 1236
 1237
 1238
 1239
 1240
 1241
 1242
 1243
 1244
 1245
 1246
 1247
 1248
 1249
 1250
 1251
 1252
 1253
 1254
 1255
 1256
 1257
 1258
 1259
 1260
 1261
 1262
 1263
 1264
 1265
 1266
 1267
 1268
 1269
 1270
 1271
 1272
 1273
 1274
 1275
 1276
 1277
 1278
 1279
 1280
 1281
 1282
 1283
 1284
 1285
 1286
 1287
 1288
 1289
 1290
 1291
 1292
 1293
 1294
 1295
 1296
 1297
 1298
 1299
 1300
 1301
 1302
 1303
 1304
 1305
 1306
 1307
 1308
 1309
 1310
 1311
 1312
 1313
 1314
 1315
 1316
 1317
 1318
 1319
 1320
 1321
 1322
 1323
 1324
 1325
 1326
 1327
 1328
 1329
 1330
 1331
 1332
 1333
 1334
 1335
 1336
 1337
 1338
 1339
 1340
 1341
 1342
 1343
 1344
 1345
 1346
 1347
 1348
 1349
 1350
 1351
 1352
 1353
 1354
 1355
 1356
 1357
 1358
 1359
 1360
 1361
 1362
 1363
 1364
 1365
 1366
 1367
 1368
 1369
 1370
 1371
 1372
 1373
 1374
 1375
 1376
 1377
 1378
 1379
 1380
 1381
 1382
 1383
 1384
 1385
 1386
 1387
 1388
 1389
 1390
 1391
 1392
 1393
 1394
 1395
 1396
 1397
 1398
 1399
 1400
 1401
 1402
 1403
 1404
 1405
 1406
 1407
 1408
 1409
 1410
 1411
 1412
 1413
 1414
 1415
 1416
 1417
 1418
 1419
 1420
 1421
 1422
 1423
 1424
 1425
 1426
 1427
 1428
 1429
 1430
 1431
 1432
 1433
 1434
 1435
 1436
 1437
 1438
 1439
 1440
 1441
 1442
 1443
 1444
 1445
 1446
 1447
 1448
 1449
 1450
 1451
 1452
 1453
 1454
 1455
 1456
 1457
 1458
 1459
 1460
 1461
 1462
 1463
 1464
 1465
 1466
 1467
 1468
 1469
 1470
 1471
 1472
 1473
 1474
 1475
 1476
 1477
 1478
 1479
 1480
 1481
 1482
 1483
 1484
 1485
 1486
 1487
 1488
 1489
 1490
 1491
 1492
 1493
 1494
 1495
 1496
 1497
 1498
 1499
 1500
 1501
 1502
 1503
 1504
 1505
 1506
 1507
 1508
 1509
 1510
 1511
 1512
 1513
 1514
 1515
 1516
 1517
 1518
 1519
 1520
 1521
 1522
 1523
 1524
 1525
 1526
 1527
 1528
 1529
 1530
 1531
 1532
 1533
 1534
 1535
 1536
 1537
 1538
 1539
 1540
 1541
 1542
 1543
 1544
 1545
 1546
 1547
 1548
 1549
 1550
 1551
 1552
 1553
 1554
 1555
 1556
 1557
 1558
 1559
 1560
 1561
 1562
 1563
 1564
 1565
 1566
 1567
 1568
 1569
 1570
 1571
 1572
 1573
 1574
 1575
 1576
 1577
 1578
 1579
 1580
 1581
 1582
 1583
 1584
 1585
 1586
 1587
 1588
 1589
 1590
 1591
 1592
 1593
 1594
 1595
 1596
 1597
 1598
 1599
 1600
 1601
 1602
 1603
 1604
 1605
 1606
 1607
 1608
 1609
 1610
 1611
 1612
 1613
 1614
 1615
 1616
 1617
 1618
 1619
 1620
 1621
 1622
 1623
 1624
 1625
 1626
 1627
 1628
 1629
 1630
 1631
 1632
 1633
 1634
 1635
 1636
 1637
 1638
 1639
 1640
 1641
 1642
 1643
 1644
 1645
 1646
 1647
 1648
 1649
 1650
 1651
 1652
 1653
 1654
 1655
 1656
 1657
 1658
 1659
 1660
 1661
 1662
 1663
 1664
 1665
 1666
 1667
 1668
 1669
 1670
 1671
 1672
 1673
 1674
 1675
 1676
 1677
 1678
 1679
 1680
 1681
 1682
 1683
 1684
 1685
 1686
 1687
 1688
 1689
 1690
 1691
 1692
 1693
 1694
 1695
 1696
 1697
 1698
 1699
 1700
 1701
 1702
 1703
 1704
 1705
 1706
 1707
 1708
 1709
 1710
 1711
 1712
 1713
 1714
 1715
 1716
 1717
 1718
 1719
 1720
 1721
 1722
 1723
 1724
 1725
 1726
 1727
 1728
 1729
 1730
 1731
 1732
 1733
 1734
 1735
 1736
 1737
 1738
 1739
 1740
 1741
 1742
 1743
 1744
 1745
 1746
 1747
 1748
 1749
 1750
 1751
 1752
 1753
 1754
 1755
 1756
 1757
 1758
 1759
 1760
 1761
 1762
 1763
 1764
 1765
 1766
 1767
 1768
 1769
 1770
 1771
 1772
 1773
 1774
 1775
 1776
 1777
 1778
 1779
 1780
 1781
 1782
 1783
 1784
 1785
 1786
 1787
 1788
 1789
 1790
 1791
 1792
 1793
 1794
 1795
 1796
 1797
 1798
 1799
 1800
 1801
 1802
 1803
 1804
 1805
 1806
 1807
 1808
 1809
 1810
 1811
 1812
 1813
 1814
 1815
 1816
 1817
 1818
 1819
 1820
 1821
 1822
 1823
 1824
 1825
 1826
 1827
 1828
 1829
 1830
 1831
 1832
 1833
 1834
 1835
 1836
 1837
 1838
 1839
 1840
 1841
 1842
 1843
 1844
 1845
 1846
 1847
 1848
 1849
 1850
 1851
 1852
 1853
 1854
 1855
 1856
 1857
 1858
 1859
 1860
 1861
 1862
 1863
 1864
 1865
 1866
 1867
 1868
 1869
 1870
 1871
 1872
 1873
 1874
 1875
 1876
 1877
 1878
 1879
 1880
 1881
 1882
 1883
 1884
 1885
 1886
 1887
 1888
 1889
 1890
 1891
 1892
 1893
 1894
 1895
 1896
 1897
 1898
 1899
 1900
 1901
 1902
 1903
 1904
 1905
 1906
 1907
 1908
 1909
 1910
 1911
 1912
 1913
 1914
 1915
 1916
 1917
 1918
 1919
 1920
 1921
 1922
 1923
 1924
 1925
 1926
 1927
 1928
 1929
 1930
 1931
 1932
 1933
 1934
 1935
 1936
 1937
 1938
 1939
 1940
 1941
 1942
 1943
 1944
 1945
 1946
 1947
 1948
 1949
 1950
 1951
 1952
 1953
 1954
 1955
 1956
 1957
 1958
 1959
 1960
 1961
 1962
 1963
 1964
 1965
 1966
 1967
 1968
 1969
 1970
 1971
 1972
 1973
 1974
 1975
 1976
 1977
 1978
 1979
 1980
 1981
 1982
 1983
 1984
 1985
 1986
 1987
 1988
 1989
 1990
 1991
 1992
 1993
 1994
 1995
 1996
 1997
 1998
 1999
 2000
 2001
 2002
 2003
 2004
 2005
 2006
 2007
 2008
 2009
 2010
 2011
 2012
 2013
 2014
 2015
 2016
 2017
 2018
 2019
 2020
 2021
 2022
 2023
 2024
 2025
 2026
 2027
 2028
 2029
 2030
 2031
 2032
 2033
 2034
 2035
 2036
 2037
 2038
 2039
 2040
 2041
 2042
 2043
 2044
 2045
 2046
 2047
 2048
 2049
 2050
 2051
 2052
 2053
 2054
 2055
 2056
 2057
 2058
 2059
 2060
 2061
 2062
 2063
 2064
 2065
 2066
 2067
 2068
 2069
 2070
 2071
 2072
 2073
 2074
 2075
 2076
 2077
 2078
 2079
 2080
 2081
 2082
 2083
 2084
 2085
 2086
 2087
 2088
 2089
 2090
 2091
 2092
 2093
 2094
 2095
 2096
 2097
 2098
 2099
 2100
 2101
 2102
 2103
 2104
 2105
 2106
 2107
 2108
 2109
 2110
 2111
 2112
 2113
 2114
 2115
 2116
 2117
 2118
 2119
 2120
 2121
 2122
 2123
 2124
 2125
 2126
 2127
 2128
 2129
 2130
 2131
 2132
 2133
 2134
 2135
 2136
 2137
 2138
 2139
 2140
 2141
 2142
 2143
 2144
 2145
 2146
 2147
 2148
 2149
 2150
 2151
 2152
 2153
 2154
 2155
 2156
 2157
 2158
 2159
 2160
 2161
 2162
 2163
 2164
 2165
 2166
 2167
 2168
 2169
 2170
 2171
 2172
 2173
 2174
 2175
 2176
 2177
 2178
 2179
 2180
 2181
 2182
 2183
 2184
 2185
 2186
 2187
 2188
 2189
 2190
 2191
 2192
 2193
 2194
 2195
 2196
 2197
 2198
 2199
 2200
 2201
 2202
 2203
 2204
 2205
 2206
 2207
 2208
 2209
 2210
 2211
 2212
 2213
 2214
 2215
 2216
 2217
 2218
 2219
 2220
 2221
 2222
 2223
 2224
 2225
 2226
 2227
 2228
 2229
 2230
 2231
 2232
 2233
 2234
 2235
 2236
 2237
 2238
 2239
 2240
 2241
 2242
 2243
 2244
 2245
 2246
 2247
 2248
 2249
 2250
 2251
 2252
 2253
 2254
 2255
 2256
 2257
 2258
 2259
 2260
 2261
 2262
 2263
 2264
 2265
 2266
 2267
 2268
 2269
 2270
 2271
 2272
 2273
 2274
 2275
 2276
 2277
 2278
 2279
 2280
 2281
 2282
 2283
 2284
 2285
 2286
 2287
 2288
 2289
 2290
 2291
 2292
 2293
 2294
 2295
 2296
 2297
 2298
 2299
 2300
 2301
 2302
 2303
 2304
 2305
 2306
 2307
 2308
 2309
 2310
 2311
 2312
 2313
 2314
 2315
 2316
 2317
 2318
 2319
 2320
 2321
 2322
 2323
 2324
 2325
 2326
 2327
 2328
 2329
 2330
 2331
 2332
 2333
 2334
 2335
 2336
 2337
 2338
 2339
 2340
 2341
 2342
 2343
 2344
 2345
 2346
 2347
 2348
 2349
 2350
 2351
 2352
 2353
 2354
 2355
 2356
 2357
 2358
 2359
 2360
 2361
 2362
 2363
 2364
 2365
 2366
 2367
 2368
 2369
 2370
 2371
 2372
 2373
 2374
 2375
 2376
 2377
 2378
 2379
 2380
 2381
 2382
 2383
 2384
 2385
 2386
 2387
 2388
 2389
 2390
 2391
 2392
 2393
 2394
 2395
 2396
 2397
 2398
 2399
 2400
 2401
 2402
 2403
 2404
 2405
 2406
 2407
 2408
 2409
 2410
 2411
 2412
 2413
 2414
 2415
 2416
 2417
 2418
 2419
 2420
 2421
 2422
 2423
 2424
 2425
 2426
 2427
 2428
 2429
 2430
 2431
 2432
 2433
 2434
 2435
 2436
 2437
 2438
 2439
 2440
 2441
 2442
 2443
 2444
 2445
 2446
 2447
 2448
 2449
 2450
 2451
 2452
 2453
 2454
 2455
 2456
 2457
 2458
 2459
 2460
 2461
 2462
 2463
 2464
 2465
 2466
 2467
 2468
 2469
 2470
 2471
 2472
 2473
 2474
 2475
 2476
 2477
 2478
 2479
 2480
 2481
 2482
 2483
 2484
 2485
 2486
 2487
 2488
 2489
 2490
 2491
 2492
 2493
 2494
 2495
 2496
 2497
 2498
 2499
 2500
 2501
 2502
 2503
 2504
 2505
 2506
 2507
 2508
 2509
 2510
 2511
 2512
 2513
 2514
 2515
 2516
 2517
 2518
 2519
 2520
 2521
 2522
 2523
 2524
 2525
 2526
 2527
 2528
 2529
 2530
 2531
 2532
 2533
 2534
 2535
 2536
 2537
 2538
 2539
 2540
 2541
 2542
 2543
 2544
 2545
 2546
 2547
 2548
 2549
 2550
 2551
 2552
 2553
 2554
 2555
 2556
 2557
 2558
 2559
 2560
 2561
 2562
 2563
 2564
 2565
 2566
 2567
 2568
 2569
 2570
 2571
 2572
 2573
 2574
 2575
 2576
 2577
 2578
 2579
 2580
 2581
 2582
 2583
 2584
 2585
 2586
 2587
 2588
 2589
 2590
 2591
 2592
 2593
 2594
 2595
 2596
 2597
 2598
 2599
 2600
 2601
 2602
 2603
 2604
 2605
 2606
 2607
 2608
 2609
 2610
 2611
 2612
 2613
 2614
 2615
 2616
 2617
 2618
 2619
 2620
 2621
 2622
 2623
 2624
 2625
 2626
 2627
 2628
 2629
 2630
 2631
 2632
 2633
 2634
 2635
 2636
 2637
 2638
 2639
 2640
 2641
 2642
 2643
 2644
 2645
 2646
 2647
 2648
 2649
 2650
 2651
 2652
 2653
 2654
 2655
 2656
 2657
 2658
 2659
 2660
 2661
 2662
 2663
 2664
 2665
 2666
 2667
 2668
 2669
 2670
 2671
 2672
 2673
 2674
 2675
 2676
 2677
 2678
 2679
 2680
 2681
 2682
 2683
 2684
 2685
 2686
 2687
 2688
 2689
 2690
 2691
 2692
 2693
 2694
 2695
 2696
 2697
 2698
 2699
 2700
 2701
 2702
 2703
 2704
 2705
 2706
 2707
 2708
 2709
 2710
 2711
 2712
 2713
 2714
 2715
 2716
 2717
 2718
 2719
 2720
 2721
 2722
 2723
 2724
 2725
 2726
 2727
 2728
 2729
 2730
 2731
 2732
 2733
 2734
 2735
 2736
 2737
 2738
 2739
 2740
 2741
 2742
 2743
 2744
 2745
 2746
 2747
 2748
 2749
 2750
 2751
 2752
 2753
 2754
 2755
 2756
 2757
 2758
 2759
 2760
 2761
 2762
 2763
 2764
 2765
 2766
 2767
 2768
 2769
 2770
 2771
 2772
 2773
 2774
 2775
 2776
 2777
 2778
 2779
 2780
 2781
 2782
 2783
 2784
 2785
 2786
 2787
 2788
 2789
 2790
 2791
 2792
 2793
 2794
 2795
 2796
 2797
 2798
 2799
 2800
 2801
 2802
 2803
 2804
 2805
 2806
 2807
 2808
 2809
 2810
 2811
 2812
 2813
 2814
 2815
 2816
 2817
 2818
 2819
 2820
 2821
 2822
 2823
 2824
 2825
 2826
 2827
 2828
 2829
 2830
 2831
 2832
 2833
 2834
 2835
 2836
 2837
 2838
 2839
 2840
 2841
 2842
 2843
 2844
 2845
 2846
 2847
 2848
 2849
 2850
 2851
 2852
 2853
 2854
 2855
 2856
 2857
 2858
 2859
 2860
 2861
 2862
 2863
 2864
 2865
 2866
 2867
 2868
 2869
 2870
 2871
 2872
 2873
 2874
 2875
 2876
 2877
 2878
 2879
 2880
 2881
 2882
 2883
 2884
 2885
 2886
 2887
 2888
 2889
 2890
 2891
 2892
 2893
 2894
 2895
 2896
 2897
 2898
 2899
 2900
 2901
 2902
 2903
 2904
 2905
 2906
 2907
 2908
 2909
 2910
 2911
 2912
 2913
 2914
 2915
 2916
 2917
 2918
 2919
 2920
 2921
 2922
 2923
 2924
 2925
 2926
 2927
 2928
 2929
 2930
 2931
 2932
 2933
 2934
 2935
 2936
 2937
 2938
 2939
 2940
 2941
 2942
 2943
 2944
 2945
 2946
 2947
 2948
 2949
 2950
 2951
 2952
 2953
 2954
 2955
 2956
 2957
 2958
 2959
 2960
 2961
 2962
 2963
 2964
 2965
 2966
 2967
 2968
 2969
 2970
 2971
 2972
 2973
 2974
 2975
 2976
 2977
 2978
 2979
 2980
 2981
 2982
 2983
 2984
 2985
 2986
 2987
 2988
 2989
 2990
 2991
 2992
 2993
 2994
 2995
 2996
 2997
 2998
 2999
 3000
 3001
 3002
 3003
 3004
 3005
 3006
 3007
 3008
 3009
 3010
 3011
 3012
 3013
 3014
 3015
 3016
 3017
 3018
 3019
 3020
 3021
 3022
 3023
 3024
 3025
 3026
 3027
 3028
 3029
 3030
 3031
 3032
 3033
 3034
 3035
 3036
 3037
 3038
 3039
 3040
 3041
 3042
 3043
 3044
 3045
 3046
 3047
 3048
 3049
 3050
 3051
 3052
 3053
 3054
 3055
 3056
 3057
 3058
 3059
 3060
 3061
 3062
 3063
 3064
 3065
 3066
 3067
 3068
 3069
 3070
 3071
 3072
 3073
 3074
 3075
 3076
 3077
 3078
 3079
 3080
 3081
 3082
 3083
 3084
 3085
 3086
 3087
 3088
 3089
 3090
 3091
 3092
 3093
 3094
 3095
 3096
 3097
 3098
 3099
 3100
 3101
 3102
 3103
 3104
 3105
 3106
 3107
 3108
 3109
 3110
 3111
 3112
 3113
 3114
 3115
 3116
 3117
 3118
 3119
 3120
 3121
 3122
 3123
 3124
 3125
 3126
 3127
 3128
 3129
 3130
 3131
 3132
 3133
 3134
 3135
 3136
 3137
 3138
 3139
 3140
 3141
 3142
 3143
 3144
 3145
 3146
 3147
 3148
 3149
 3150
 3151
 3152
 3153
 3154
 3155
 3156
 3157
 3158
 3159
 3160
 3161
 3162
 3163
 3164
 3165
 3166
 3167
 3168
 3169
 3170
 3171
 3172
 3173
 3174
 3175
 3176
 3177
 3178
 3179
 3180
 3181
 3182
 3183
 3184
 3185
 3186
 3187
 3188
 3189
 3190
 3191
 3192
 3193
 3194
 3195
 3196
 3197
 3198
 3199
 3200
 3201
 3202
 3203
 3204
 3205
 3206
 3207
 3208
 3209
 3210
 3211
 3212
 3213
 3214
 3215
 3216
 3217
 3218
 3219
 3220
 3221
 3222
 3223
 3224
 3225
 3226
 3227
 3228
 3229
 3230
 3231
 3232
 3233
 3234
 3235
 3236
 3237
 3238
 3239
 3240
 3241
 3242
 3243
 3244
 3245
 3246
 3247
 3248
 3249
 3250
 3251
 3252
 3253
 3254
 3255
 3256
 3257
 3258
 3259
 3260
 3261
 3262
 3263
 3264
 3265
 3266
 3267
 3268
 3269
 3270
 3271
 3272
 3273
 3274
 3275
 3276
 3277
 3278
 3279
 3280
 3281
 3282
 3283
 3284
 3285
 3286
 3287
 3288
 3289
 3290
 3291
 3292
 3293
 3294
 3295
 3296
 3297
 3298
 3299
 3300
 3301
 3302
 3303
 3304
 3305
 3306
 3307
 3308
 3309
 3310
 3311
 3312
 3313
 3314
 3315
 3316
 3317
 3318
 3319
 3320
 3321
 3322
 3323
 3324
 3325
 3326
 3327
 3328
 3329
 3330
 3331
 3332
 3333
 3334
 3335
 3336
 3337
 3338
 3339
 3340
 3341
 3342
 3343
 3344
 3345
 3346
 3347
 3348
 3349
 3350
 3351
 3352
 3353
 3354
 3355
 3356
 3357
 3358
 3359
 3360
 3361
 3362
 3363
 3364
 3365
 3366
 3367
 3368
 3369
 3370
 3371
 3372
 3373
 3374
 3375
 3376
 3377
 3378
 3379
 3380
 3381
 3382
 3383
 3384
 3385
 3386
 3387
 3388
 3389
 3390
 3391
 3392
 3393
 3394
 3395
 3396
 3397
 3398
 3399
 3400
 3401
 3402
 3403
 3404
 3405
 3406
 3407
 3408
 3409
 3410
 3411
 3412
 3413
 3414
 3415
 3416
 3417
 3418
 3419
 3420
 3421
 3422
 3423
 3424
 3425
 3426
 3427
 3428
 3429
 3430
 3431
 3432
 3433
 3434
 3435
 3436
 3437
 3438
 3439
 3440
 3441
 3442
 3443
 3444
 3445
 3446
 3447
 3448
 3449
 3450
 3451
 3452
 3453
 3454
 3455
 3456
 3457
 3458
 3459
 3460
 3461
 3462
 3463
 3464
 3465
 3466
 3467
 3468
 3469
 3470
 3471
 3472
 3473
 3474
 3475
 3476
 3477
 3478
 3479
 3480
 3481
 3482
 3483
 3484
 3485
 3486
 3487
 3488
 3489
 3490
 3491
 3492
 3493
 3494
 3495
 3496
 3497
 3498
 3499
 3500
 3501
 3502
 3503
 3504
 3505
 3506
 3507
 3508
 3509
 3510
 3511
 3512
 3513
 3514
 3515
 3516
 3517
 3518
 3519
 3520
 3521
 3522
 3523
 3524
 3525
 3526
 3527
 3528
 3529
 3530
 3531
 3532
 3533
 3534
 3535
 3536
 3537
 3538
 3539
 3540
 3541
 3542
 3543
 3544
 3545
 3546
 3547
 3548
 3549
 3550
 3551
 3552
 3553
 3554
 3555
 3556
 3557
 3558
 3559
 3560
 3561
 3562
 3563
 3564
 3565
 3566
 3567
 3568
 3569
 3570
 3571
 3572
 3573
 3574
 3575
 3576
 3577
 3578
 3579
 3580
 3581
 3582
 3583
 3584
 3585
 3586
 3587
 3588
 3589
 3590
 3591
 3592
 3593
 3594
 3595
 3596
 3597
 3598
 3599
 3600
 3601
 3602
 3603
 3604
 3605
 3606
 3607
 3608
 3609
 3610
 3611
 3612
 3613
 3614
 3615
 3616
 3617
 3618
 3619
 3620
 3621
 3622
 3623
 3624
 3625
 3626
 3627
 3628
 3629
 3630
 3631
 3632
 3633
 3634
 3635
 3636
 3637
 3638
 3639
 3640
 3641
 3642
 3643
 3644
 3645
 3646
 3647
 3648
 3649
 3650
 3651
 3652
 3653
 3654
 3655
 3656
 3657
 3658
 3659
 3660
 3661
 3662
 3663
 3664
 3665
 3666
 3667
 3668
 3669
 3670
 3671
 3672
 3673
 3674
 3675
 3676
 3677
 3678
 3679
 3680
 3681
 3682
 3683
 3684
 3685
 3686
 3687
 3688
 3689
 3690
 3691
 3692
 3693
 3694
 3695
 3696
 3697
 3698
 3699
 3700
 3701
 3702
 3703
 3704
 3705
 3706
 3707
 3708
 3709
 3710
 3711
 3712
 3713
 3714
 3715
 3716
 3717
 3718
 3719
 3720
 3721
 3722
 3723
 3724
 3725
 3726
 3727
 3728
 3729
 3730
 3731
 3732
 3733
 3734
 3735
 3736
 3737
 3738
 3739
 3740
 3741
 3742
 3743
 3744
 3745
 3746
 3747
 3748
 3749
 3750
 3751
 3752
 3753
 3754
 3755
 3756
 3757
 3758
 3759
 3760
 3761
 3762
 3763
 3764
 3765
 3766
 3767
 3768
 3769
 3770
 3771
 3772
 3773
 3774
 3775
 3776
 3777
 3778
 3779
 3780
 3781
 3782
 3783
 3784
 3785
 3786
 3787
 3788
 3789
 3790
 3791
 3792
 3793
 3794
 3795
 3796
 3797
 3798
 3799
 3800
 3801
 3802
 3803
 3804
 3805
 3806
 3807
 3808
 3809
 3810
 3811
 3812
 3813
 3814
 3815
 3816
 3817
 3818
 3819
 3820
 3821
 3822
 3823
 3824
 3825
 3826
 3827
 3828
 3829
 3830
 3831
 3832
 3833
 3834
 3835
 3836
 3837
 3838
 3839
 3840
 3841
 3842
 3843
 3844
 3845
 3846
 3847
 3848
 3849
 3850
 3851
 3852
 3853
 3854
 3855
 3856
 3857
 3858
 3859
 3860
 3861
 3862
 3863
 3864
 3865
 3866
 3867
 3868
 3869
 3870
 3871
 3872
 3873
 3874
 3875
 3876
 3877
 3878
 3879
 3880
 3881
 3882
 3883
 3884
 3885
 3886
 3887
 3888
 3889
 3890
 3891
 3892
 3893
 3894
 3895
 3896
 3897
 3898
 3899
 3900
 3901
 3902
 3903
 3904
 3905
 3906
 3907
 3908
 3909
 3910
 3911
 3912
 3913
 3914
 3915
 3916
 3917
 3918
 3919
 3920
 3921
 3922
 3923
 3924
 3925
 3926
 3927
 3928
 3929
 3930
 3931
 3932
 3933
 3934
 3935
 3936
 3937
 3938
 3939
 3940
 3941
 3942
 3943
 3944
 3945
 3946
 3947
 3948
 3949
 3950
 3951
 3952
 3953
 3954
 3955
 3956
 3957
 3958
 3959
 3960
 3961
 3962
 3963
 3964
 3965
 3966
 3967
 3968
 3969
 3970
 3971
 3972
 3973
 3974
 3975
 3976
 3977
 3978
 3979
 3980
 3981
 3982
 3983
 3984
 3985
 3986
 3987
 3988
 3989
 3990
 3991
 3992
 3993
 3994
 3995
 3996
 3997
 3998
 3999
 4000
 4001
 4002
 4003
 4004
 4005
 4006
 4007
 4008
 4009
 4010
 4011
 4012
 4013
 4014
 4015
 4016
 4017
 4018
 4019
 4020
 4021
 4022
 4023
 4024
 4025
 4026
 4027
 4028
 4029
 4030
 4031
 4032
 4033
 4034
 4035
 4036
 4037
 4038
 4039
 4040
 4041
 4042
 4043
 4044
 4045
 4046
 4047
 4048
 4049
 4050
 4051
 4052
 4053
 4054
 4055
 4056
 4057
 4058
 4059
 4060
 4061
 4062
 4063
 4064
 4065
 4066
 4067
 4068
 4069
 4070
 4071
 4072
 4073
 4074
 4075
 4076
 4077
 4078
 4079
 4080
 4081
 4082
 4083
 4084
 4085
 4086
 4087
 4088
 4089
 4090
 4091
 4092
 4093
 4094
 4095
 4096
 4097
 4098
 4099
 4100
 4101
 4102
 4103
 4104
 4105
 4106
 4107
 4108
 4109
 4110
 4111
 4112
 4113
 4114
 4115
 4116
 4117
 4118
 4119
 4120
 4121
 4122
 4123
 4124
 4125
 4126
 4127
 4128
 4129
 4130
 4131
 4132
 4133
 4134
 4135
 4136
 4137
 4138
 4139
 4140
 4141
 4142
 4143
 4144
 4145
 4146
 4147
 4148
 4149
 4150
 4151
 4152
 4153
 4154
 4155
 4156
 4157
 4158
 4159
 4160
 4161
 4162
 4163
 4164
 4165
 4166
 4167
 4168
 4169
 4170
 4171
 4172
 4173
 4174
 4175
 4176
 4177
 4178
 4179
 4180
 4181
 4182
 4183
 4184
 4185
 4186
 4187
 4188
 4189
 4190
 4191
 4192
 4193
 4194
 4195
 4196
 4197
 4198
 4199
 4200
 4201
 4202
 4203
 4204
 4205
 4206
 4207
 4208
 4209
 4210
 4211
 4212
 4213
 4214
 4215
 4216
 4217
 4218
 4219
 4220
 4221
 4222
 4223
 4224
 4225
 4226
 4227
 4228
 4229
 4230
 4231
 4232
 4233
 4234
 4235
 4236
 4237
 4238
 4239
 4240
 4241
 4242
 4243
 4244
 4245
 4246
 4247
 4248
 4249
 4250
 4251
 4252
 4253
 4254
 4255
 4256
 4257
 4258
 4259
 4260
 4261
 4262
 4263
 4264
 4265
 4266
 4267
 4268
 4269
 4270
 4271
 4272
 4273
 4274
 4275
 4276
 4277
 4278
 4279
 4280
 4281
 4282
 4283
 4284
 4285
 4286
 4287
 4288
 4289
 4290
 4291
 4292
 4293
 4294
 4295
 4296
 4297
 4298
 4299
 4300
 4301
 4302
 4303
 4304
 4305
 4306
 4307
 4308
 4309
 4310
 4311
 4312
 4313
 4314
 4315
 4316
 4317
 4318
 4319
 4320
 4321
 4322
 4323
 4324
 4325
 4326
 4327
 4328
 4329
 4330
 4331
 4332
 4333
 4334
 4335
 4336
 4337
 4338
 4339
 4340
 4341
 4342
 4343
 4344
 4345
 4346
 4347
 4348
 4349
 4350
 4351
 4352
 4353
 4354
 4355
 4356
 4357
 4358
 4359
 4360
 4361
 4362
 4363
 4364
 4365
 4366
 4367
 4368
 4369
 4370
 4371
 4372
 4373
 4374
 4375
 4376
 4377
 4378
 4379
 4380
 4381
 4382
 4383
 4384
 4385
 4386
 4387
 4388
 4389
 4390
 4391
 4392
 4393
 4394
 4395
 4396
 4397
 4398
 4399
 4400
 4401
 4402
 4403
 4404
 4405
 4406
 4407
 4408
 4409
 4410
 4411
 4412
 4413
 4414
 4415
 4416
 4417
 4418
 4419
 4420
 4421
 4422
 4423
 4424
 4425
 4426
 4427
 4428
 4429
 4430
 4431
 4432
 4433
 4434
 4435
 4436
 4437
 4438
 4439
 4440
 4441
 4442
 4443
 4444
 4445
 4446
 4447
 4448
 4449
 4450
 4451
 4452
 4453
 4454
 4455
 4456
 4457
 4458
 4459
 4460
 4461
 4462
 4463
 4464
 4465
 4466
 4467
 4468
 4469
 4470
 4471
 4472
 4473
 4474
 4475
 4476
 4477
 4478
 4479
 4480
 4481
 4482
 4483
 4484
 4485
 4486
 4487
 4488
 4489
 4490
 4491
 4492
 4493
 4494
 4495
 4496
 4497
 4498
 4499
 4500
 4501
 4502
 4503
 4504
 4505
 4506
 4507
 4508
 4509
 4510
 4511
 4512
 4513
 4514
 4515
 4516
 4517
 4518
 4519
 4520
 4521
 4522
 4523
 4524
 4525
 4526
 4527
 4528
 4529
 4530
 4531
 4532
 4533
 4534
 4535
 4536
 4537
 4538
 4539
 4540
 4541
 4542
 4543
 4544
 4545
 4546
 4547
 4548
 4549
 4550
 4551
 4552
 4553
 4554
 4555
 4556
 4557
 4558
 4559
 4560
 4561
 4562
 4563
 4564
 4565
 4566
 4567
 4568
 4569
 4570
 4571
 4572
 4573
 4574
 4575
 4576
 4577
 4578
 4579
 4580
 4581
 4582
 4583
 4584
 4585
 4586
 4587
 4588
 4589
 4590
 4591
 4592
 4593
 4594
 4595
 4596
 4597
 4598
 4599
 4600
 4601
 4602
 4603
 4604
 4605
 4606
 4607
 4608
 4609
 4610
 4611
 4612
 4613
 4614
 4615
 4616
 4617
 4618
 4619
 4620
 4621
 4622
 4623
 4624
 4625
 4626
 4627
 4628
 4629
 4630
 4631
 4632
 4633
 4634
 4635
 4636
 4637
 4638
 4639
 4640
 4641
 4642
 4643
 4644
 4645
 4646
 4647
 4648
 4649
 4650
 4651
 4652
 4653
 4654
 4655
 4656
 4657
 4658
 4659
 4660
 4661
 4662
 4663
 4664
 4665
 4666
 4667
 4668
 4669
 4670
 4671
 4672
 4673
 4674
 4675
 4676
 4677
 4678
 4679
 4680
 4681
 4682
 4683
 4684
 4685
 4686
 4687
 4688
 4689
 4690
 4691
 4692
 4693
 4694
 4695
 4696
 4697
 4698
 4699
 4700
 4701
 4702
 4703
 4704
 4705
 4706
 4707
 4708
 4709
 4710
 4711
 4712
 4713
 4714
 4715
 4716
 4717
 4718
 4719
 4720
 4721
 4722
 4723
 4724
 4725
 4726
 4727
 4728
 4729
 4730
 4731
 4732
 4733
 4734
 4735
 4736
 4737
 4738
 4739
 4740
 4741
 4742
 4743
 4744
 4745
 4746
 4747
 4748
 4749
 4750
 4751
 4752
 4753
 4754
 4755
 4756
 4757
 4758
 4759
 4760
 4761
 4762
 4763
 4764
 4765
 4766
 4767
 4768
 4769
 4770
 4771
 4772
 4773
 4774
 4775
 4776
 4777
 4778
 4779
 4780
 4781
 4782
 4783
 4784
 4785
 4786
 4787
 4788
 4789
 4790
 4791
 4792
 4793
 4794
 4795
 4796
 4797
 4798
 4799
 4800
 4801
 4802
 4803
 4804
 4805
 4806
 4807
 4808
 4809
 4810
 4811
 4812
 4813
 4814
 4815
 4816
 4817
 4818
 4819
 4820
 4821
 4822
 4823
 4824
 4825
 4826
 4827
 4828
 4829
 4830
 4831
 4832
 4833
 4834
 4835
 4836
 4837
 4838
 4839
 4840
 4841
 4842
 4843
 4844
 4845
 4846
 4847
 4848
 4849
 4850
 4851
 4852
 4853
 4854
 4855
 4856
 4857
 4858
 4859
 4860
 4861
 4862
 4863
 4864
 4865
 4866
 4867
 4868
 4869
 4870
 4871
 4872
 4873
 4874
 4875
 4876
 4877
 4878
 4879
 4880
 4881
 4882
 4883
 4884
 4885
 4886
 4887
 4888
 4889
 4890
 4891
 4892
 4893
 4894
 4895
 4896
 4897
 4898
 4899
 4900
 4901
 4902
 4903
 4904
 4905
 4906
 4907
 4908
 4909
 4910
 4911
 4912
 4913
 4914
 4915
 4916
 4917
 4918
 4919
 4920
 4921
 4922
 4923
 4924
 4925
 4926
 4927
 4928
 4929
 4930
 4931
 4932
 4933
 4934
 4935
 4936
 4937
 4938
 4939
 4940
 4941
 4942
 4943
 4944
 4945
 4946
 4947
 4948
 4949
 4950
 4951
 4952
 4953
 4954
 4955
 4956
 4957
 4958
 4959
 4960
 4961
 4962
 4963
 4964
 4965
 4966
 4967
 4968
 4969
 4970
 4971
 4972
 4973
 4974
 4975
 4976
 4977
 4978
 4979
 4980
 4981
 4982
 4983
 4984
 4985
 4986
 4987
 4988
 4989
 4990
 4991
 4992
 4993
 4994
 4995
 4996
 4997
 4998
 4999
 5000
 5001
 5002
 5003
 5004
 5005
 5006
 5007
 5008
 5009
 5010
 5011
 5012
 5013
 5014
 5015
 5016
 5017
 5018
 5019
 5020
 5021
 5022
 5023
 5024
 5025
 5026
 5027
 5028
 5029
 5030
 5031
 5032
 5033
 5034
 5035
 5036
 5037
 5038
 5039
 5040
 5041
 5042
 5043
 5044
 5045
 5046
 5047
 5048
 5049
 5050
 5051
 5052
 5053
 5054
 5055
 5056
 5057
 5058
 5059
 5060
 5061
 5062
 5063
 5064
 5065
 5066
 5067
 5068
 5069
 5070
 5071
 5072
 5073
 5074
 5075
 5076
 5077
 5078
 5079
 5080
 5081
 5082
 5083
 5084
 5085
 5086
 5087
 5088
 5089
 5090
 5091
 5092
 5093
 5094
 5095
 5096
 5097
 5098
 5099
 5100
 5101
 5102
 5103
 5104
 5105
 5106
 5107
 5108
 5109
 5110
 5111
 5112
 5113
 5114
 5115
 5116
 5117
 5118
 5119
 5120
 5121
 5122
 5123
 5124
 5125
 5126
 5127
 5128
 5129
 5130
 5131
 5132
 5133
 5134
 5135
 5136
 5137
 5138
 5139
 5140
 5141
 5142
 5143
 5144
 5145
 5146
 5147
 5148
 5149
 5150
 5151
 5152
 5153
 5154
 5155
 5156
 5157
 5158
 5159
 5160
 5161
 5162
 5163
 5164
 5165
 5166
 5167
 5168
 5169
 5170
 5171
 5172
 5173
 5174
 5175
 5176
 5177
 5178
 5179
 5180
 5181
 5182
 5183
 5184
 5185
 5186
 5187
 5188
 5189
 5190
 5191
 5192
 5193
 5194
 5195
 5196
 5197
 5198
 5199
 5200
 5201
 5202
 5203
 5204
 5205
 5206
 5207
 5208
 5209
 5210
 5211
 5212
 5213
 5214
 5215
 5216
 5217
 5218
 5219
 5220
 5221
 5222
 5223
 5224
 5225
 5226
 5227
 5228
 5229
 5230
 5231
 5232
 5233
 5234
 5235
 5236
 5237
 5238
 5239
 5240
 5241
 5242
 5243
 5244
 5245
 5246
 5247
 5248
 5249
 5250
 5251
 5252
 5253
 5254
 5255
 5256
 5257
 5258
 5259
 5260
 5261
 5262
 5263
 5264
 5265
 5266
 5267
 5268
 5269
 5270
 5271
 5272
 5273
 5274
 5275
 5276
 5277
 5278
 5279
 5280
 5281
 5282
 5283
 5284
 5285
 5286
 5287
 5288
 5289
 5290
 5291
 5292
 5293
 5294
 5295
 5296
 5297
 5298
 5299
 5300
 5301
 5302
 5303
 5304
 5305
 5306
 5307
 5308
 5309
 5310
 5311
 5312
 5313
 5314
 5315
 5316
 5317
 5318
 5319
 5320
 5321
 5322
 5323
 5324
 5325
 5326
 5327
 5328
 5329
 5330
 5331
 5332
 5333
 5334
 5335
 5336
 5337
 5338
 5339
 5340
 5341
 5342
 5343
 5344
 5345
 5346
 5347
 5348
 5349
 5350
 5351
 5352
 5353
 5354
 5355
 5356
 5357
 5358
 5359
 5360
 5361
 5362
 5363
 5364
 5365
 5366
 5367
 5368
 5369
 5370
 5371
 5372
 5373
 5374
 5375
 5376
 5377
 5378
 5379
 5380
 5381
 5382
 5383
 5384
 5385
 5386
 5387
 5388
 5389
 5390
 5391
 5392
 5393
 5394
 5395
 5396
 5397
 5398
 5399
 5400
 5401
 5402
 5403
 5404
 5405
 5406
 5407
 5408
 5409
 5410
 5411
 5412
 5413
 5414
 5415
 5416
 5417
 5418
 5419
 5420
 5421
 5422
 5423
 5424
 5425
 5426
 5427
 5428
 5429
 5430
 5431
 5432
 5433
 5434
 5435
 5436
 5437
 5438
 5439
 5440
 5441
 5442
 5443
 5444
 5445
 5446
 5447
 5448
 5449
 5450
 5451
 5452
 5453
 5454
 5455
 5456
 5457
 5458
 5459
 5460
 5461
 5462
 5463
 5464
 5465
 5466
 5467
 5468
 5469
 5470
 5471
 5472
 5473
 5474
 5475
 5476
 5477
 5478
 5479
 5480
 5481
 5482
 5483
 5484
 5485
 5486
 5487
 5488
 5489
 5490
 5491
 5492
 5493
 5494
 5495
 5496
 5497
 5498
 5499
 5500
 5501
 5502
 5503
 5504
 5505
 5506
 5507
 5508
 5509
 5510
 5511
 5512
 5513
 5514
 5515
 5516
 5517
 5518
 5519
 5520
 5521
 5522
 5523
 5524
 5525
 5526
 5527
 5528
 5529
 5530
 5531
 5532
 5533
 5534
 5535
 5536
 5537
 5538
 5539
 5540
 5541
 5542
 5543
 5544
 5545
 5546
 5547
 5548
 5549
 5550
 5551
 5552
 5553
 5554
 5555
 5556
 5557
 5558
 5559
 5560
 5561
 5562
 5563
 5564
 5565
 5566
 5567
 5568
 5569
 5570
 5571
 5572
 5573
 5574
 5575
 5576
 5577
 5578
 5579
 5580
 5581
 5582
 5583
 5584
 5585
 5586
 5587
 5588
 5589
 5590
 5591
 5592
 5593
 5594
 5595
 5596
 5597
 5598
 5599
 5600
 5601
 5602
 5603
 5604
 5605
 5606
 5607
 5608
 5609
 5610
 5611
 5612
 5613
 5614
 5615
 5616
 5617
 5618
 5619
 5620
 5621
 5622
 5623
 5624
 5625
 5626
 5627
 5628
 5629
 5630
 5631
 5632
 5633
 5634
 5635
 5636
 5637
 5638
 5639
 5640
 5641
 5642
 5643
 5644
 5645
 5646
 5647
 5648
 5649
 5650
 5651
 5652
 5653
 5654
 5655
 5656
 5657
 5658
 5659
 5660
 5661
 5662
 5663
 5664
 5665
 5666
 5667
 5668
 5669
 5670
 5671
 5672
 5673
 5674
 5675
 5676
 5677
 5678
 5679
 5680
 5681
 5682
 5683
 5684
 5685
 5686
 5687
 5688
 5689
 5690
 5691
 5692
 5693
 5694
 5695
 5696
 5697
 5698
 5699
 5700
 5701
 5702
 5703
 5704
 5705
 5706
 5707
 5708
 5709
 5710
 5711
 5712
 5713
 5714
 5715
 5716
 5717
 5718
 5719
 5720
 5721
 5722
 5723
 5724
 5725
 5726
 5727
 5728
 5729
 5730
 5731
 5732
 5733
 5734
 5735
 5736
 5737
 5738
 5739
 5740
 5741
 5742
 5743
 5744
 5745
 5746
 5747
 5748
 5749
 5750
 5751
 5752
 5753
 5754
 5755
 5756
 5757
 5758
 5759
 5760
 5761
 5762
 5763
 5764
 5765
 5766
 5767
 5768
 5769
 5770
 5771
 5772
 5773
 5774
 5775
 5776
 5777
 5778
 5779
 5780
 5781
 5782
 5783
 5784
 5785
 5786
 5787
 5788
 5789
 5790
 5791
 5792
 5793
 5794
 5795
 5796
 5797
 5798
 5799
 5800
 5801
 5802
 5803
 5804
 5805
 5806
 5807
 5808
 5809
 5810
 5811
 5812
 5813
 5814
 5815
 5816
 5817
 5818
 5819
 5820
 5821
 5822
 5823
 5824
 5825
 5826
 5827
 5828
 5829
 5830
 5831
 5832
 5833
 5834
 5835
 5836
 5837
 5838
 5839
 5840
 5841
 5842
 5843
 5844
 5845
 5846
 5847
 5848
 5849
 5850
 5851
 5852
 5853
 5854
 5855
 5856
 5857
 5858
 5859
 5860
 5861
 5862
 5863
 5864
 5865
 5866
 5867
 5868
 5869
 5870
 5871
 5872
 5873
 5874
 5875
 5876
 5877
 5878
 5879
 5880
 5881
 5882
 5883
 5884
 5885
 5886
 5887
 5888
 5889
 5890
 5891
 5892
 5893
 5894
 5895
 5896
 5897
 5898
 5899
 5900
 5901
 5902
 5903
 5904
 5905
 5906
 5907
 5908
 5909
 5910
 5911
 5912
 5913
 5914
 5915
 5916
 5917
 5918
 5919
 5920
 5921
 5922
 5923
 5924
 5925
 5926
 5927
 5928
 5929
 5930
 5931
 5932
 5933
 5934
 5935
 5936
 5937
 5938
 5939
 5940
 5941
 5942
 5943
 5944
 5945
 5946
 5947
 5948
 5949
 5950
 5951
 5952
 5953
 5954
 5955
 5956
 5957
 5958
 5959
 5960
 5961
 5962
 5963
 5964
 5965
 5966
 5967
 5968
 5969
 5970
 5971
 5972
 5973
 5974
 5975
 5976
 5977
 5978
 5979
 5980
 5981
 5982
 5983
 5984
 5985
 5986
 5987
 5988
 5989
 5990
 5991
 5992
 5993
 5994
 5995
 5996
 5997
 5998
 5999
 6000
 6001
 6002
 6003
 6004
 6005
 6006
 6007
 6008
 6009
 6010
 6011
 6012
 6013
 6014
 6015
 6016
 6017
 6018
 6019
 6020
 6021
 6022
 6023
 6024
 6025
 6026
 6027
 6028
 6029
 6030
 6031
 6032
 6033
 6034
 6035
 6036
 6037
 6038
 6039
 6040
 6041
 6042
 6043
 6044
 6045
 6046
 6047
 6048
 6049
 6050
 6051
 6052
 6053
 6054
 6055
 6056
 6057
 6058
 6059
 6060
 6061
 6062
 6063
 6064
 6065
 6066
 6067
 6068
 6069
 6070
 6071
 6072
 6073
 6074
 6075
 6076
 6077
 6078
 6079
 6080
 6081
 6082
 6083
 6084
 6085
 6086
 6087
 6088
 6089
 6090
 6091
 6092
 6093
 6094
 6095
 6096
 6097
 6098
 6099
 6100
 6101
 6102
 6103
 6104
 6105
 6106
 6107
 6108
 6109
 6110
 6111
 6112
 6113
 6114
 6115
 6116
 6117
 6118
 6119
 6120
 6121
 6122
 6123
 6124
 6125
 6126
 6127
 6128
 6129
 6130
 6131
 6132
 6133
 6134
 6135
 6136
 6137
 6138
 6139
 6140
 6141
 6142
 6143
 6144
 6145
 6146
 6147
 6148
 6149
 6150
 6151
 6152
 6153
 6154
 6155
 6156
 6157
 6158
 6159
 6160
 6161
 6162
 6163
 6164
 6165
 6166
 6167
 6168
 6169
 6170
 6171
 6172
 6173
 6174
 6175
 6176
 6177
 6178
 6179
 6180
 6181
 6182
 6183
 6184
 6185
 6186
 6187
 6188
 6189
 6190
 6191
 6192
 6193
 6194
 6195
 6196
 6197
 6198
 6199
 6200
 6201
 6202
 6203
 6204
 6205
 6206
 6207
 6208
 6209
 6210
 6211
 6212
 6213
 6214
 6215
 6216
 6217
 6218
 6219
 6220
 6221
 6222
 6223
 6224
 6225
 6226
 6227
 6228
 6229
 6230
 6231
 6232
 6233
 6234
 6235
 6236
 6237
 6238
 6239
 6240
 6241
 6242
 6243
 6244
 6245
 6246
 6247
 6248
 6249
 6250
 6251
 6252
 6253
 6254
 6255
 6256
 6257
 6258
 6259
 6260
 6261
 6262
 6263
 6264
 6265
 6266
 6267
 6268
 6269
 6270
 6271
 6272
 6273
 6274
 6275
 6276
 6277
 6278
 6279
 6280
 6281
 6282
 6283
 6284
 6285
 6286
 6287
 6288
 6289
 6290
 6291
 6292
 6293
 6294
 6295
 6296
 6297
 6298
 6299
 6300
 6301
 6302
 6303
 6304
 6305
 6306
 6307
 6308
 6309
 6310
 6311
 6312
 6313
 6314
 6315
 6316
 6317
 6318
 6319
 6320
 6321
 6322
 6323
 6324
 6325
 6326
 6327
 6328
 6329
 6330
 6331
 6332
 6333
 6334
 6335
 6336
 6337
 6338
 6339
 6340
 6341
 6342
 6343
 6344
 6345
 6346
 6347
 6348
 6349
 6350
 6351
 6352
 6353
 6354
 6355
 6356
 6357
 6358
 6359
 6360
 6361
 6362
 6363
 6364
 6365
 6366
 6367
 6368
 6369
 6370
 6371
 6372
 6373
 6374
 6375
 6376
 6377
 6378
 6379
 6380
 6381
 6382
 6383
 6384
 6385
 6386
 6387
 6388
 6389
 6390
 6391
 6392
 6393
 6394
 6395
 6396
 6397
 6398
 6399
 6400
 6401
 6402
 6403
 6404
 6405
 6406
 6407
 6408
 6409
 6410
 6411
 6412
 6413
 6414
 6415
 6416
 6417
 6418
 6419
 6420
 6421
 6422
 6423
 6424
 6425
 6426
 6427
 6428
 6429
 6430
 6431
 6432
 6433
 6434
 6435
 6436
 6437
 6438
 6439
 6440
 6441
 6442
 6443
 6444
 6445
 6446
 6447
 6448
 6449
 6450
 6451
 6452
 6453
 6454
 6455
 6456
 6457
 6458
 6459
 6460
 6461
 6462
 6463
 6464
 6465
 6466
 6467
 6468
 6469
 6470
 6471
 6472
 6473
 6474
 6475
 6476
 6477
 6478
 6479
 6480
 6481
 6482
 6483
 6484
 6485
 6486
 6487
 6488
 6489
 6490
 6491
 6492
 6493
 6494
 6495
 6496
 6497
 6498
 6499
 6500
 6501
 6502
 6503
 6504
 6505
 6506
 6507
 6508
 6509
 6510
 6511
 6512
 6513
 6514
 6515
 6516
 6517
 6518
 6519
 6520
 6521
 6522
 6523
 6524
 6525
 6526
 6527
 6528
 6529
 6530
 6531
 6532
 6533
 6534
 6535
 6536
 6537
 6538
 6539
 6540
 6541
 6542
 6543
 6544
 6545
 6546
 6547
 6548
 6549
 6550
 6551
 6552
 6553
 6554
 6555
 6556
 6557
 6558
 6559
 6560
 6561
 6562
 6563
 6564
 6565
 6566
 6567
 6568
 6569
 6570
 6571
 6572
 6573
 6574
 6575
 6576
 6577
 6578
 6579
 6580
 6581
 6582
 6583
 6584
 6585
 6586
 6587
 6588
 6589
 6590
 6591
 6592
 6593
 6594
 6595
 6596
 6597
 6598
 6599
 6600
 6601
 6602
 6603
 6604
 6605
 6606
 6607
 6608
 6609
 6610
 6611
 6612
 6613
 6614
 6615
 6616
 6617
 6618
 6619
 6620
 6621
 6622
 6623
 6624
 6625
 6626
 6627
 6628
 6629
 6630
 6631
 6632
 6633
 6634
 6635
 6636
 6637
 6638
 6639
 6640
 6641
 6642
 6643
 6644
 6645
 6646
 6647
 6648
 6649
 6650
 6651
 6652
 6653
 6654
 6655
 6656
 6657
 6658
 6659
 6660
 6661
 6662
 6663
 6664
 6665
 6666
 6667
 6668
 6669
 6670
 6671
 6672
 6673
 6674
 6675
 6676
 6677
 6678
 6679
 6680
 6681
 6682
 6683
 6684
 6685
 6686
 6687
 6688
 6689
 6690
 6691
 6692
 6693
 6694
 6695
 6696
 6697
 6698
 6699
 6700
 6701
 6702
 6703
 6704
 6705
 6706
 6707
 6708
 6709
 6710
 6711
 6712
 6713
 6714
 6715
 6716
 6717
 6718
 6719
 6720
 6721
 6722
 6723
 6724
 6725
 6726
 6727
 6728
 6729
 6730
 6731
 6732
 6733
 6734
 6735
 6736
 6737
 6738
 6739
 6740
 6741
 6742
 6743
 6744
 6745
 6746
 6747
 6748
 6749
 6750
 6751
 6752
 6753
 6754
 6755
 6756
 6757
 6758
 6759
 6760
 6761
 6762
 6763
 6764
 6765
 6766
 6767
 6768
 6769
 6770
 6771
 6772
 6773
 6774
 6775
 6776
 6777
 6778
 6779
 6780
 6781
 6782
 6783
 6784
 6785
 6786
 6787
 6788
 6789
 6790
 6791
 6792
 6793
 6794
 6795
 6796
 6797
 6798
 6799
 6800
 6801
 6802
 6803
 6804
 6805
 6806
 6807
 6808
 6809
 6810
 6811
 6812
 6813
 6814
 6815
 6816
 6817
 6818
 6819
 6820
 6821
 6822
 6823
 6824
 6825
 6826
 6827
 6828
 6829
 6830
 6831
 6832
 6833
 6834
 6835
 6836
 6837
 6838
 6839
 6840
 6841
 6842
 6843
 6844
 6845
 6846
 6847
 6848
 6849
 6850
 6851
 6852
 6853
 6854
 6855
 6856
 6857
 6858
 6859
 6860
 6861
 6862
 6863
 6864
 6865
 6866
 6867
 6868
 6869
 6870
 6871

content / browser / renderer_host / render_frame_host_manager_browsertest.cc [blame]

// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/renderer_host/render_frame_host_manager_browsertest.h"

#include <stddef.h>
#include <stdint.h>

#include <functional>
#include <memory>
#include <set>

#include "base/cfi_buildflags.h"
#include "base/command_line.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/json/json_reader.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/synchronization/lock.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/bind.h"
#include "base/thread_annotations.h"
#include "base/time/time.h"
#include "base/values.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/process_lock.h"
#include "content/browser/renderer_host/frame_tree_node.h"
#include "content/browser/renderer_host/navigation_entry_restore_context_impl.h"
#include "content/browser/renderer_host/navigation_request.h"
#include "content/browser/renderer_host/render_frame_host_impl.h"
#include "content/browser/renderer_host/render_frame_proxy_host.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/renderer_host/spare_render_process_host_manager_impl.h"
#include "content/browser/site_info.h"
#include "content/browser/site_instance_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/browser/webui/web_ui_controller_factory_registry.h"
#include "content/browser/webui/web_ui_impl.h"
#include "content/common/content_constants_internal.h"
#include "content/common/content_navigation_policy.h"
#include "content/common/features.h"
#include "content/public/browser/browser_child_process_host.h"
#include "content/public/browser/child_process_launcher_utils.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/site_isolation_policy.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "content/public/common/bindings_policy.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/isolated_world_ids.h"
#include "content/public/common/url_constants.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/commit_message_delayer.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_content_browser_client.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/navigation_handle_observer.h"
#include "content/public/test/test_frame_navigation_observer.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_navigation_throttle.h"
#include "content/public/test/test_navigation_throttle_inserter.h"
#include "content/public/test/test_utils.h"
#include "content/public/test/url_loader_interceptor.h"
#include "content/shell/browser/shell.h"
#include "content/test/content_browser_test_utils_internal.h"
#include "content/test/render_document_feature.h"
#include "content/test/storage_partition_test_helpers.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/controllable_http_response.h"
#include "net/test/embedded_test_server/default_handlers.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/request_handler_util.h"
#include "net/test/url_request/url_request_failed_job.h"
#include "testing/gmock/include/gmock/gmock-matchers.h"
#include "third_party/blink/public/common/chrome_debug_urls.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/web_preferences/web_preferences.h"

using base::ASCIIToUTF16;

namespace content {

namespace {

// Helper function that return true in cases where the current process model
// will return the same SiteInstance for a cross-process navigation.
bool ExpectSameSiteInstance() {
  return AreDefaultSiteInstancesEnabled() &&
         !CanCrossSiteNavigationsProactivelySwapBrowsingInstances();
}

class TestWebUIMessageHandler : public WebUIMessageHandler {
 public:
  using WebUIMessageHandler::AllowJavascript;
  using WebUIMessageHandler::IsJavascriptAllowed;

 protected:
  void RegisterMessages() override {}
};

// This class implements waiting for RenderFrameHost destruction. It relies on
// the fact that RenderFrameDeleted event is fired when RenderFrameHost is
// destroyed.
// Note: RenderFrameDeleted is also fired when the process associated with the
// RenderFrameHost crashes, so this cannot be used in cases where process dying
// is expected.
class RenderFrameHostDestructionObserver : public WebContentsObserver {
 public:
  explicit RenderFrameHostDestructionObserver(RenderFrameHost* rfh)
      : WebContentsObserver(WebContents::FromRenderFrameHost(rfh)),
        message_loop_runner_(new MessageLoopRunner),
        deleted_(false),
        render_frame_host_(rfh) {}
  ~RenderFrameHostDestructionObserver() override = default;

  bool deleted() const { return deleted_; }

  void Wait() {
    if (deleted_)
      return;

    message_loop_runner_->Run();
  }

  // WebContentsObserver implementation:
  void RenderFrameDeleted(RenderFrameHost* rfh) override {
    if (rfh == render_frame_host_) {
      CHECK(!deleted_);
      deleted_ = true;
    }

    if (deleted_ && message_loop_runner_->loop_running()) {
      base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
          FROM_HERE, message_loop_runner_->QuitClosure());
    }
  }

 private:
  scoped_refptr<MessageLoopRunner> message_loop_runner_;
  bool deleted_;
  raw_ptr<RenderFrameHost, AcrossTasksDanglingUntriaged> render_frame_host_;
};

// A NavigationThrottle implementation that blocks all outgoing navigation
// requests for a specific WebContents. It is used to block navigations to
// WebUI URLs in tests.
class RequestBlockingNavigationThrottle : public NavigationThrottle {
 public:
  explicit RequestBlockingNavigationThrottle(NavigationHandle* handle)
      : NavigationThrottle(handle) {}

  RequestBlockingNavigationThrottle(const RequestBlockingNavigationThrottle&) =
      delete;
  RequestBlockingNavigationThrottle& operator=(
      const RequestBlockingNavigationThrottle&) = delete;

  static std::unique_ptr<NavigationThrottle> Create(NavigationHandle* handle) {
    return std::make_unique<RequestBlockingNavigationThrottle>(handle);
  }

 private:
  ThrottleCheckResult WillStartRequest() override {
    return NavigationThrottle::BLOCK_REQUEST;
  }

  const char* GetNameForLogging() override {
    return "RequestBlockingNavigationThrottle";
  }
};

// Helper function for error page navigations that makes sure that the last
// committed origin on |node| is an opaque origin with a precursor that matches
// |url|'s origin.
// Returns true if the frame has an opaque origin with the expected precursor
// information. Otherwise returns false.
bool IsOriginOpaqueAndCompatibleWithURL(FrameTreeNode* node, const GURL& url) {
  url::Origin frame_origin =
      node->current_frame_host()->GetLastCommittedOrigin();

  if (!frame_origin.opaque()) {
    LOG(ERROR) << "Frame origin was not opaque. " << frame_origin;
    return false;
  }

  const GURL url_origin = url.DeprecatedGetOriginAsURL();
  const GURL precursor_origin =
      frame_origin.GetTupleOrPrecursorTupleIfOpaque().GetURL();
  if (url_origin != precursor_origin) {
    LOG(ERROR) << "url_origin '" << url_origin << "' !=  precursor_origin '"
               << precursor_origin << "'";
    return false;
  }
  return true;
}

bool IsMainFrameOriginOpaqueAndCompatibleWithURL(Shell* shell,
                                                 const GURL& url) {
  return IsOriginOpaqueAndCompatibleWithURL(
      static_cast<WebContentsImpl*>(shell->web_contents())
          ->GetPrimaryFrameTree()
          .root(),
      url);
}

bool HasErrorPageSiteInfo(SiteInstance* site_instance) {
  auto* site_instance_impl = static_cast<SiteInstanceImpl*>(site_instance);
  return site_instance_impl->GetSiteInfo().is_error_page();
}

bool HasErrorPageProcessLock(SiteInstance* site_instance) {
  return site_instance->GetProcess()->GetProcessLock().is_error_page();
}

}  // anonymous namespace

RenderFrameHostManagerTest::RenderFrameHostManagerTest() : foo_com_("foo.com") {
  replace_host_.SetHostStr(foo_com_);
  InitAndEnableRenderDocumentFeature(&feature_list_, GetParam());
}

RenderFrameHostManagerTest::~RenderFrameHostManagerTest() = default;

void RenderFrameHostManagerTest::SetUpOnMainThread() {
  // Support multiple sites on the test server.
  host_resolver()->AddRule("*", "127.0.0.1");
}

void RenderFrameHostManagerTest::DisableBackForwardCache(
    BackForwardCacheImpl::DisableForTestingReason reason) const {
  return static_cast<WebContentsImpl*>(shell()->web_contents())
      ->GetController()
      .GetBackForwardCache()
      .DisableForTesting(reason);
}

void RenderFrameHostManagerTest::StartServer() {
  ASSERT_TRUE(embedded_test_server()->Start());

  foo_host_port_ = embedded_test_server()->host_port_pair();
  foo_host_port_.set_host(foo_com_);
}

void RenderFrameHostManagerTest::StartEmbeddedServer() {
  SetupCrossSiteRedirector(embedded_test_server());
  ASSERT_TRUE(embedded_test_server()->Start());
}

std::unique_ptr<content::URLLoaderInterceptor>
RenderFrameHostManagerTest::SetupRequestFailForURL(const GURL& url) {
  return URLLoaderInterceptor::SetupRequestFailForURL(url,
                                                      net::ERR_DNS_TIMED_OUT);
}

// Returns a URL on foo.com with the given path.
GURL RenderFrameHostManagerTest::GetCrossSiteURL(const std::string& path) {
  GURL cross_site_url(embedded_test_server()->GetURL(path));
  return cross_site_url.ReplaceComponents(replace_host_);
}

void RenderFrameHostManagerTest::NavigateToPageWithLinks(Shell* shell) {
  EXPECT_TRUE(NavigateToURL(
      shell, embedded_test_server()->GetURL("/click-noreferrer-links.html")));

  // Rewrite selected links on the page to be actual cross-site (bar.com)
  // URLs. This does not use the /cross-site/ redirector, since that creates
  // links that initially look same-site.
  std::string script = "setOriginForLinks('http://bar.com:" +
                       embedded_test_server()->base_url().port() + "/');";
  EXPECT_TRUE(ExecJs(shell, script));
}

// Web pages should not have script access to the unloaded page.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest, NoScriptAccessAfterUnload) {
  StartEmbeddedServer();

  // Load a page with links that open in a new window.
  NavigateToPageWithLinks(shell());

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance.get() != nullptr);

  // Open a same-site link in a new window.
  ShellAddedObserver new_shell_observer;
  EXPECT_EQ(true, EvalJs(shell(), "clickSameSiteTargetedLink();"));
  Shell* new_shell = new_shell_observer.GetShell();

  // Wait for the navigation in the new window to finish, if it hasn't.
  EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));
  EXPECT_EQ("/navigate_opener.html",
            new_shell->web_contents()->GetLastCommittedURL().path());

  // Should have the same SiteInstance.
  EXPECT_EQ(orig_site_instance, new_shell->web_contents()->GetSiteInstance());

  // We should have access to the opened window's location.
  EXPECT_EQ(true, EvalJs(shell(), "testScriptAccessToWindow();"));

  // Now navigate the new window to a different site.
  EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(
      new_shell, embedded_test_server()->GetURL("foo.com", "/title1.html")));
  scoped_refptr<SiteInstance> new_site_instance(
      new_shell->web_contents()->GetSiteInstance());
  if (AreDefaultSiteInstancesEnabled()) {
    EXPECT_EQ(orig_site_instance, new_site_instance);
  } else {
    EXPECT_NE(orig_site_instance, new_site_instance);
  }

  // We should no longer have script access to the opened window's location.
  EXPECT_EQ(false, EvalJs(shell(), "testScriptAccessToWindow();"));

  // We now navigate the window to an about:blank page.
  TestNavigationObserver navigation_observer(new_shell->web_contents());
  EXPECT_EQ(true, EvalJs(shell(), "clickBlankTargetedLink();"));

  // Wait for the navigation in the new window to finish.
  navigation_observer.Wait();

  GURL blank_url(url::kAboutBlankURL);
  EXPECT_EQ(blank_url, new_shell->web_contents()->GetLastCommittedURL());
  EXPECT_EQ(orig_site_instance, new_shell->web_contents()->GetSiteInstance());

  // We should have access to the opened window's location.
  EXPECT_EQ(true, EvalJs(shell(), "testScriptAccessToWindow();"));
}

// Test for crbug.com/24447.  Following a cross-site link with rel=noreferrer
// and target=_blank should create a new SiteInstance.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       SwapProcessWithRelNoreferrerAndTargetBlank) {
  StartEmbeddedServer();

  NavigateToPageWithLinks(shell());

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance.get() != nullptr);

  // Test clicking a rel=noreferrer + target=blank link.
  ShellAddedObserver new_shell_observer;
  EXPECT_EQ(true, EvalJs(shell(), "clickNoRefTargetBlankLink();"));

  // Wait for the window to open.
  Shell* new_shell = new_shell_observer.GetShell();

  EXPECT_EQ("/title2.html", new_shell->web_contents()->GetVisibleURL().path());

  // Check that `window.opener` is not set.
  EXPECT_EQ(true, EvalJs(new_shell, "window.opener == null;"));

  // Wait for the cross-site transition in the new tab to finish.
  EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));

  // Should have a new SiteInstance.
  scoped_refptr<SiteInstance> noref_blank_site_instance(
      new_shell->web_contents()->GetSiteInstance());
  EXPECT_NE(orig_site_instance, noref_blank_site_instance);
  EXPECT_FALSE(noref_blank_site_instance->IsRelatedSiteInstance(
      orig_site_instance.get()));
}

// Same as above, but for 'noopener'
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       SwapProcessWithRelNoopenerAndTargetBlank) {
  StartEmbeddedServer();

  NavigateToPageWithLinks(shell());

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance.get() != nullptr);

  // Test clicking a rel=noreferrer + target=blank link.
  ShellAddedObserver new_shell_observer;
  EXPECT_EQ(true, EvalJs(shell(), "clickNoOpenerTargetBlankLink();"));

  // Wait for the window to open.
  Shell* new_shell = new_shell_observer.GetShell();

  EXPECT_EQ("/title2.html", new_shell->web_contents()->GetVisibleURL().path());

  // Check that `window.opener` is not set.
  EXPECT_EQ(true, EvalJs(new_shell, "window.opener == null;"));

  // Wait for the cross-site transition in the new tab to finish.
  EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));

  // Check that the referrer is set correctly.
  std::string expected_referrer =
      embedded_test_server()->GetURL("/").DeprecatedGetOriginAsURL().spec();
  EXPECT_EQ(true, EvalJs(new_shell,
                         "document.referrer == '" + expected_referrer + "';"));

  // Should have a new SiteInstance.
  scoped_refptr<SiteInstance> noopener_blank_site_instance(
      new_shell->web_contents()->GetSiteInstance());
  EXPECT_NE(orig_site_instance, noopener_blank_site_instance);
  EXPECT_FALSE(noopener_blank_site_instance->IsRelatedSiteInstance(
      orig_site_instance.get()));
}

// 'noopener' also works from 'window.open'
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       SwapProcessWithWindowOpenAndNoopener) {
  StartEmbeddedServer();

  NavigateToPageWithLinks(shell());

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance.get());

  // Test opening a window with the 'noopener' feature.
  ShellAddedObserver new_shell_observer;
  // We should not get a reference to the opened window.
  EXPECT_EQ(
      false,
      EvalJs(
          shell(),
          "openWindowWithTargetAndFeatures('/title2.html', '', 'noopener');"));

  // Wait for the window to open.
  Shell* new_shell = new_shell_observer.GetShell();

  // Wait for the cross-site transition in the new tab to finish.
  EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));

  EXPECT_EQ("/title2.html",
            new_shell->web_contents()->GetLastCommittedURL().path());

  // Check that `window.opener` is not set.
  EXPECT_EQ(true, EvalJs(new_shell, "window.opener == null;"));

  // Check that the referrer is set correctly.
  std::string expected_referrer =
      embedded_test_server()->GetURL("/click-noreferrer-links.html").spec();
  EXPECT_EQ(true, EvalJs(new_shell,
                         "document.referrer == '" + expected_referrer + "';"));

  // Should have a new SiteInstance.
  scoped_refptr<SiteInstance> noopener_blank_site_instance(
      new_shell->web_contents()->GetSiteInstance());
  EXPECT_NE(orig_site_instance, noopener_blank_site_instance);
  EXPECT_FALSE(noopener_blank_site_instance->IsRelatedSiteInstance(
      orig_site_instance.get()));
}

// As of crbug.com/69267, we create a new BrowsingInstance (and SiteInstance)
// for rel=noreferrer links in new windows, even to same site pages and named
// targets.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       SwapProcessWithSameSiteRelNoreferrer) {
  StartEmbeddedServer();

  // Load a page with links that open in a new window.
  NavigateToPageWithLinks(shell());

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance.get() != nullptr);

  // Test clicking a same-site rel=noreferrer + target=foo link.
  ShellAddedObserver new_shell_observer;
  EXPECT_EQ(true, EvalJs(shell(), "clickSameSiteNoRefTargetedLink();"));

  // Wait for the window to open.
  Shell* new_shell = new_shell_observer.GetShell();

  // Opens in new window.
  EXPECT_EQ("/title2.html", new_shell->web_contents()->GetVisibleURL().path());

  // Check that `window.opener` is not set.
  EXPECT_EQ(true, EvalJs(new_shell, "window.opener == null;"));

  // Wait for the cross-site transition in the new tab to finish.
  EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));

  // Should have a new SiteInstance (in a new BrowsingInstance).
  scoped_refptr<SiteInstance> noref_blank_site_instance(
      new_shell->web_contents()->GetSiteInstance());
  EXPECT_NE(orig_site_instance, noref_blank_site_instance);
  EXPECT_FALSE(noref_blank_site_instance->IsRelatedSiteInstance(
      orig_site_instance.get()));
}

// Same as above, but for 'noopener'
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       SwapProcessWithSameSiteRelNoopener) {
  StartEmbeddedServer();

  // Load a page with links that open in a new window.
  NavigateToPageWithLinks(shell());

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance.get() != nullptr);

  // Test clicking a same-site rel=noopener + target=foo link.
  ShellAddedObserver new_shell_observer;
  EXPECT_EQ(true, EvalJs(shell(), "clickSameSiteNoOpenerTargetedLink();"));

  // Wait for the window to open.
  Shell* new_shell = new_shell_observer.GetShell();

  // Opens in new window.
  EXPECT_EQ("/title2.html", new_shell->web_contents()->GetVisibleURL().path());

  // Check that `window.opener` is not set.
  EXPECT_EQ(true, EvalJs(new_shell, "window.opener == null;"));

  // Wait for the cross-site transition in the new tab to finish.
  EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));

  // Should have a new SiteInstance (in a new BrowsingInstance).
  scoped_refptr<SiteInstance> noref_blank_site_instance(
      new_shell->web_contents()->GetSiteInstance());
  EXPECT_NE(orig_site_instance, noref_blank_site_instance);
  EXPECT_FALSE(noref_blank_site_instance->IsRelatedSiteInstance(
      orig_site_instance.get()));
}

// Test for crbug.com/24447.  Following a cross-site link with just
// target=_blank should not create a new SiteInstance, unless we
// are running in --site-per-process mode.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       DontSwapProcessWithOnlyTargetBlank) {
  StartEmbeddedServer();

  // Load a page with links that open in a new window.
  NavigateToPageWithLinks(shell());

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance.get() != nullptr);

  // Test clicking a target=blank link.
  ShellAddedObserver new_shell_observer;
  EXPECT_EQ(true, EvalJs(shell(), "clickTargetBlankLink();"));

  // Wait for the window to open.
  Shell* new_shell = new_shell_observer.GetShell();

  // Wait for the cross-site transition in the new tab to finish.
  EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));
  EXPECT_EQ("/title2.html",
            new_shell->web_contents()->GetLastCommittedURL().path());

  // Should have the same SiteInstance unless we're in site-per-process mode.
  scoped_refptr<SiteInstance> blank_site_instance(
      new_shell->web_contents()->GetSiteInstance());
  if (AreDefaultSiteInstancesEnabled())
    EXPECT_EQ(orig_site_instance, blank_site_instance);
  else
    EXPECT_NE(orig_site_instance, blank_site_instance);
}

// Test for crbug.com/24447.  Following a cross-site link with rel=noreferrer
// and no target=_blank should not create a new SiteInstance.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       DontSwapProcessWithOnlyRelNoreferrer) {
  StartEmbeddedServer();

  // Load a page with links that open in a new window.
  NavigateToPageWithLinks(shell());

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance.get() != nullptr);

  // Test clicking a rel=noreferrer link.
  EXPECT_EQ(true, EvalJs(shell(), "clickNoRefLink();"));

  // Wait for the cross-site transition in the current tab to finish.
  EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));

  // Opens in same window.
  EXPECT_EQ(1u, Shell::windows().size());
  EXPECT_EQ("/title2.html",
            shell()->web_contents()->GetLastCommittedURL().path());

  scoped_refptr<SiteInstance> noref_site_instance(
      shell()->web_contents()->GetSiteInstance());
  if (ExpectSameSiteInstance()) {
    EXPECT_EQ(orig_site_instance, noref_site_instance);
  } else {
    EXPECT_NE(orig_site_instance, noref_site_instance);
  }
}

// Same as above, but for 'noopener'
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       DontSwapProcessWithOnlyRelNoOpener) {
  StartEmbeddedServer();

  // Load a page with links that open in a new window.
  NavigateToPageWithLinks(shell());

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance.get() != nullptr);

  // Test clicking a rel=noreferrer link.
  EXPECT_EQ(true, EvalJs(shell(), "clickNoRefLink();"));

  // Wait for the cross-site transition in the current tab to finish.
  EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));

  // Opens in same window.
  EXPECT_EQ(1u, Shell::windows().size());
  EXPECT_EQ("/title2.html",
            shell()->web_contents()->GetLastCommittedURL().path());

  scoped_refptr<SiteInstance> noref_site_instance(
      shell()->web_contents()->GetSiteInstance());
  if (ExpectSameSiteInstance()) {
    EXPECT_EQ(orig_site_instance, noref_site_instance);
  } else {
    EXPECT_NE(orig_site_instance, noref_site_instance);
  }
}

// Test for crbug.com/116192.  Targeted links should still work after the
// named target window has swapped processes.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       AllowTargetedNavigationsAfterSwap) {
  StartEmbeddedServer();

  // Ensure that the first and second page are isolated from each other (even on
  // Android, where site-per-process is not the default).
  IsolateOriginsForTesting(embedded_test_server(), shell()->web_contents(),
                           {"foo.com"});

  // Load a page with links that open in a new window.
  NavigateToPageWithLinks(shell());

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance.get() != nullptr);

  // Test clicking a target=foo link.
  ShellAddedObserver new_shell_observer;
  EXPECT_EQ(true, EvalJs(shell(), "clickSameSiteTargetedLink()"));
  Shell* new_shell = new_shell_observer.GetShell();

  // Wait for the navigation in the new tab to finish, if it hasn't.
  EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));
  EXPECT_EQ("/navigate_opener.html",
            new_shell->web_contents()->GetLastCommittedURL().path());

  // Should have the same SiteInstance.
  scoped_refptr<SiteInstance> blank_site_instance(
      new_shell->web_contents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, blank_site_instance);

  // Now navigate the new tab to a different site.
  GURL cross_site_url(
      embedded_test_server()->GetURL("foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, cross_site_url));
  scoped_refptr<SiteInstance> new_site_instance(
      new_shell->web_contents()->GetSiteInstance());
  EXPECT_NE(orig_site_instance, new_site_instance);

  // Clicking the original link in the first tab should cause us to swap back.
  {
    TestNavigationObserver navigation_observer(new_shell->web_contents());
    EXPECT_EQ(true, EvalJs(shell(), "clickSameSiteTargetedLink()"));
    navigation_observer.Wait();
  }

  // Should have swapped back and shown the new window again.
  scoped_refptr<SiteInstance> revisit_site_instance(
      new_shell->web_contents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, revisit_site_instance);

  // If it navigates away to another process, the original window should
  // still be able to close it (using a cross-process close message).
  EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, cross_site_url));
  EXPECT_EQ(new_site_instance.get(),
            new_shell->web_contents()->GetSiteInstance());
  WebContentsDestroyedWatcher close_watcher(new_shell->web_contents());
  EXPECT_EQ(true, EvalJs(shell(), "testCloseWindow()"));
  close_watcher.Wait();
}

// Test that setting the opener to null in a window affects cross-process
// navigations, including those to existing entries.  http://crbug.com/156669.
// This test crashes under ThreadSanitizer, http://crbug.com/356758.
#if defined(THREAD_SANITIZER)
#define MAYBE_DisownOpener DISABLED_DisownOpener
#else
#define MAYBE_DisownOpener DisownOpener
#endif
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest, MAYBE_DisownOpener) {
  StartEmbeddedServer();

  if (IsIsolatedOriginRequiredToGuaranteeDedicatedProcess()) {
    // Isolate "foo.com" so we are guaranteed to get a non-default
    // SiteInstance for navigations to this origin.
    IsolateOriginsForTesting(embedded_test_server(), shell()->web_contents(),
                             {"foo.com"});
  }

  // Load a page with links that open in a new window.
  NavigateToPageWithLinks(shell());

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance.get() != nullptr);

  // Test clicking a target=_blank link.
  ShellAddedObserver new_shell_observer;
  EXPECT_EQ(true, EvalJs(shell(), "clickSameSiteTargetBlankLink();"));
  Shell* new_shell = new_shell_observer.GetShell();
  EXPECT_TRUE(new_shell->web_contents()->HasOpener());

  // Wait for the navigation in the new tab to finish, if it hasn't.
  EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));
  EXPECT_EQ("/title2.html",
            new_shell->web_contents()->GetLastCommittedURL().path());

  // Should have the same SiteInstance.
  scoped_refptr<SiteInstance> blank_site_instance(
      new_shell->web_contents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, blank_site_instance);

  // Now navigate the new tab to a different site.
  GURL cross_site_url(
      embedded_test_server()->GetURL("foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, cross_site_url));
  scoped_refptr<SiteInstance> new_site_instance(
      new_shell->web_contents()->GetSiteInstance());
  EXPECT_NE(orig_site_instance, new_site_instance);
  EXPECT_TRUE(new_shell->web_contents()->HasOpener());

  // Now disown the opener.
  EXPECT_TRUE(ExecJs(new_shell, "window.opener = null;"));
  EXPECT_FALSE(new_shell->web_contents()->HasOpener());

  // Go back and ensure the opener is still null.
  {
    TestNavigationObserver back_nav_load_observer(new_shell->web_contents());
    new_shell->web_contents()->GetController().GoBack();
    back_nav_load_observer.Wait();
  }
  EXPECT_EQ(true, EvalJs(new_shell, "window.opener == null;"));
  EXPECT_FALSE(new_shell->web_contents()->HasOpener());

  // Now navigate forward again (creating a new process) and check opener.
  EXPECT_TRUE(NavigateToURL(new_shell, cross_site_url));
  EXPECT_EQ(true, EvalJs(new_shell, "window.opener == null;"));
  EXPECT_FALSE(new_shell->web_contents()->HasOpener());
}

// Test that subframes can disown their openers.  http://crbug.com/225528.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest, DisownSubframeOpener) {
  const GURL frame_url("data:text/html,<iframe name=\"foo\"></iframe>");
  EXPECT_TRUE(NavigateToURL(shell(), frame_url));

  // Give the frame an opener using window.open.
  EXPECT_TRUE(ExecJs(shell(), "window.open('about:blank','foo');"));

  // Check that the browser process updates the subframe's opener.
  FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
                            ->GetPrimaryFrameTree()
                            .root();
  EXPECT_EQ(root, root->child_at(0)->opener());
  EXPECT_EQ(
      nullptr,
      root->child_at(0)->first_live_main_frame_in_original_opener_chain());

  // Now disown the frame's opener.  Shouldn't crash.
  EXPECT_TRUE(ExecJs(shell(), "window.frames[0].opener = null;"));

  // Check that the subframe's opener in the browser process is disowned.
  EXPECT_EQ(nullptr, root->child_at(0)->opener());
  EXPECT_EQ(
      nullptr,
      root->child_at(0)->first_live_main_frame_in_original_opener_chain());
}

// Check that window.name is preserved for top frames when they navigate
// cross-process.  See https://crbug.com/504164.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       PreserveTopFrameWindowNameOnCrossProcessNavigations) {
  StartEmbeddedServer();
  if (IsIsolatedOriginRequiredToGuaranteeDedicatedProcess()) {
    // Isolate "foo.com" so we are guaranteed it is placed in a different
    // process.
    IsolateOriginsForTesting(embedded_test_server(), shell()->web_contents(),
                             {"foo.com"});
  }

  GURL main_url(embedded_test_server()->GetURL("/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), main_url));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance.get() != nullptr);

  // Open a popup using window.open with a 'foo' window.name.
  Shell* new_shell = OpenPopup(shell(), GURL(url::kAboutBlankURL), "foo");
  EXPECT_TRUE(new_shell);

  // The window.name for the new popup should be "foo".
  EXPECT_EQ("foo", EvalJs(new_shell, "window.name;"));

  // Now navigate the new tab to a different site.
  GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title2.html"));
  EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, foo_url));
  scoped_refptr<SiteInstance> new_site_instance(
      new_shell->web_contents()->GetSiteInstance());
  EXPECT_NE(orig_site_instance->GetProcess(), new_site_instance->GetProcess());

  // window.name should still be "foo".
  EXPECT_EQ("foo", EvalJs(new_shell, "window.name;"));

  // Open another popup from the 'foo' popup and navigate it cross-site.
  Shell* new_shell2 = OpenPopup(new_shell, GURL(url::kAboutBlankURL), "bar");
  EXPECT_TRUE(new_shell2);
  GURL bar_url(embedded_test_server()->GetURL("bar.com", "/title3.html"));
  EXPECT_TRUE(NavigateToURLFromRenderer(new_shell2, bar_url));

  // Check that the new popup's window.opener has name "foo", which verifies
  // that new swapped-out RenderViews also propagate window.name.  This has to
  // be done via window.open, since window.name isn't readable cross-origin.
  EXPECT_EQ(true,
            EvalJs(new_shell2, "window.opener === window.open('','foo');"));
}

// Test for crbug.com/99202.  PostMessage calls should still work after
// navigating the source and target windows to different sites.
// Specifically:
// 1) Create 3 windows (opener, "foo", and _blank) and send "foo" cross-process.
// 2) Fail to post a message from "foo" to opener with the wrong target origin.
// 3) Post a message from "foo" to opener, which replies back to "foo".
// 4) Post a message from _blank to "foo".
// 5) Post a message from "foo" to a subframe of opener, which replies back.
// 6) Post a message from _blank to a subframe of "foo".
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       SupportCrossProcessPostMessage) {
  StartEmbeddedServer();
  if (IsIsolatedOriginRequiredToGuaranteeDedicatedProcess()) {
    // Isolate "foo.com" so we are guaranteed it is placed in a different
    // process.
    IsolateOriginsForTesting(embedded_test_server(), shell()->web_contents(),
                             {"foo.com"});
  }

  // Load a page with links that open in a new window.
  NavigateToPageWithLinks(shell());

  // Get the original SiteInstance and RVHM for later comparison.
  WebContents* opener_contents = shell()->web_contents();
  scoped_refptr<SiteInstance> orig_site_instance(
      opener_contents->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance.get() != nullptr);
  RenderFrameHostManager* opener_manager =
      static_cast<WebContentsImpl*>(opener_contents)
          ->GetPrimaryFrameTree()
          .root()
          ->render_manager();

  // 1) Open two more windows, one named.  These initially have openers but no
  // reference to each other.  We will later post a message between them.

  // First, a named target=foo window.
  ShellAddedObserver new_shell_observer;
  EXPECT_EQ(true, EvalJs(opener_contents, "clickSameSiteTargetedLink();"));
  Shell* new_shell = new_shell_observer.GetShell();

  // Wait for the navigation in the new window to finish, if it hasn't, then
  // send it to post_message.html on a different site.
  WebContents* foo_contents = new_shell->web_contents();
  EXPECT_TRUE(WaitForLoadStop(foo_contents));
  EXPECT_EQ("/navigate_opener.html",
            foo_contents->GetLastCommittedURL().path());
  EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(
      new_shell,
      embedded_test_server()->GetURL("foo.com", "/post_message.html")));
  scoped_refptr<SiteInstance> foo_site_instance(
      foo_contents->GetSiteInstance());
  EXPECT_NE(orig_site_instance, foo_site_instance);
  EXPECT_NE(static_cast<SiteInstanceImpl*>(orig_site_instance.get())->group(),
            static_cast<SiteInstanceImpl*>(foo_site_instance.get())->group());

  // Second, a target=_blank window.
  ShellAddedObserver new_shell_observer2;
  EXPECT_EQ(true, EvalJs(shell(), "clickSameSiteTargetBlankLink();"));

  // Wait for the navigation in the new window to finish, if it hasn't, then
  // send it to post_message.html on the original site.
  Shell* new_shell2 = new_shell_observer2.GetShell();
  WebContents* new_contents = new_shell2->web_contents();
  EXPECT_TRUE(WaitForLoadStop(new_contents));
  EXPECT_EQ("/title2.html", new_contents->GetLastCommittedURL().path());
  EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(
      new_shell2, embedded_test_server()->GetURL("/post_message.html")));
  EXPECT_EQ(orig_site_instance.get(), new_contents->GetSiteInstance());
  RenderFrameHostManager* new_manager =
      static_cast<WebContentsImpl*>(new_contents)
          ->GetPrimaryFrameTree()
          .root()
          ->render_manager();

  // We now have three windows.  The opener should have a RenderFrameProxyHost
  // for the new SiteInstanceGroup, but the _blank window should not.
  EXPECT_EQ(3u, Shell::windows().size());
  EXPECT_TRUE(opener_manager->current_frame_host()
                  ->browsing_context_state()
                  ->GetRenderFrameProxyHost(
                      static_cast<SiteInstanceImpl*>(foo_site_instance.get())
                          ->group()));
  EXPECT_FALSE(new_manager->current_frame_host()
                   ->browsing_context_state()
                   ->GetRenderFrameProxyHost(
                       static_cast<SiteInstanceImpl*>(foo_site_instance.get())
                           ->group()));

  // 2) Fail to post a message from the foo window to the opener if the target
  // origin is wrong.  We won't see an error, but we can check for the right
  // number of received messages below.
  EXPECT_EQ(true,
            EvalJs(foo_contents, "postToOpener('msg', 'http://google.com');"));
  ASSERT_FALSE(opener_manager->current_frame_host()
                   ->browsing_context_state()
                   ->GetRenderFrameProxyHost(
                       static_cast<SiteInstanceImpl*>(orig_site_instance.get())
                           ->group()));

  // 3) Post a message from the foo window to the opener.  The opener will
  // reply, causing the foo window to update its own title.
  std::u16string expected_title = u"msg";
  TitleWatcher title_watcher(foo_contents, expected_title);
  EXPECT_EQ(true, EvalJs(foo_contents, "postToOpener('msg','*');"));
  ASSERT_FALSE(opener_manager->current_frame_host()
                   ->browsing_context_state()
                   ->GetRenderFrameProxyHost(
                       static_cast<SiteInstanceImpl*>(orig_site_instance.get())
                           ->group()));
  ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle());

  // We should have received only 1 message in the opener and "foo" tabs,
  // and updated the title.
  EXPECT_EQ(1, EvalJs(opener_contents, "window.receivedMessages;"));
  EXPECT_EQ(1, EvalJs(foo_contents, "window.receivedMessages;"));
  EXPECT_EQ(u"msg", foo_contents->GetTitle());

  // 4) Now post a message from the _blank window to the foo window.  The
  // foo window will update its title and will not reply.
  expected_title = u"msg2";
  TitleWatcher title_watcher2(foo_contents, expected_title);
  EXPECT_EQ(true, EvalJs(new_contents, "postToFoo('msg2');"));
  ASSERT_EQ(expected_title, title_watcher2.WaitAndGetTitle());

  // This postMessage should have created a RenderFrameProxyHost for the new
  // SiteInstanceGroup in the target=_blank window.
  EXPECT_TRUE(new_manager->current_frame_host()
                  ->browsing_context_state()
                  ->GetRenderFrameProxyHost(
                      static_cast<SiteInstanceImpl*>(foo_site_instance.get())
                          ->group()));

  // TODO(nasko): Test subframe targeting of postMessage once
  // http://crbug.com/153701 is fixed.
}

// Test for crbug.com/278336. MessagePorts should work cross-process. Messages
// which contain Transferables that need to be forwarded between processes via
// RenderFrameProxy::willCheckAndDispatchMessageEvent should work.
// Specifically:
// 1) Create 2 windows (opener and "foo") and send "foo" cross-process.
// 2) Post a message containing a message port from opener to "foo".
// 3) Post a message from "foo" back to opener via the passed message port.
// The test will be enabled when the feature implementation lands.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       SupportCrossProcessPostMessageWithMessagePort) {
  StartEmbeddedServer();
  if (IsIsolatedOriginRequiredToGuaranteeDedicatedProcess()) {
    // Isolate "foo.com" so we are guaranteed it is placed in a different
    // process.
    IsolateOriginsForTesting(embedded_test_server(), shell()->web_contents(),
                             {"foo.com"});
  }

  // Load a page with links that open in a new window.
  NavigateToPageWithLinks(shell());

  // Get the original SiteInstance and RVHM for later comparison.
  WebContents* opener_contents = shell()->web_contents();
  scoped_refptr<SiteInstance> orig_site_instance(
      opener_contents->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance.get() != nullptr);
  RenderFrameHostManager* opener_manager =
      static_cast<WebContentsImpl*>(opener_contents)
          ->GetPrimaryFrameTree()
          .root()
          ->render_manager();

  // 1) Open a named target=foo window. We will later post a message between the
  // opener and the new window.
  ShellAddedObserver new_shell_observer;
  EXPECT_EQ(true, EvalJs(opener_contents, "clickSameSiteTargetedLink();"));
  Shell* new_shell = new_shell_observer.GetShell();

  // Wait for the navigation in the new window to finish, if it hasn't, then
  // send it to post_message.html on a different site.
  WebContents* foo_contents = new_shell->web_contents();
  EXPECT_TRUE(WaitForLoadStop(foo_contents));
  EXPECT_EQ("/navigate_opener.html",
            foo_contents->GetLastCommittedURL().path());
  EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(
      new_shell,
      embedded_test_server()->GetURL("foo.com", "/post_message.html")));
  scoped_refptr<SiteInstance> foo_site_instance(
      foo_contents->GetSiteInstance());
  EXPECT_NE(orig_site_instance, foo_site_instance);

  // We now have two windows. The opener should have a RenderFrameProxyHost
  // for the new SiteInstanceGroup.
  EXPECT_EQ(2u, Shell::windows().size());
  EXPECT_TRUE(opener_manager->current_frame_host()
                  ->browsing_context_state()
                  ->GetRenderFrameProxyHost(
                      static_cast<SiteInstanceImpl*>(foo_site_instance.get())
                          ->group()));

  // 2) Post a message containing a MessagePort from opener to the the foo
  // window. The foo window will reply via the passed port, causing the opener
  // to update its own title.
  std::u16string expected_title = u"msg-back-via-port";
  TitleWatcher title_observer(opener_contents, expected_title);
  EXPECT_EQ(true, EvalJs(opener_contents, "postWithPortToFoo();"));
  ASSERT_FALSE(opener_manager->current_frame_host()
                   ->browsing_context_state()
                   ->GetRenderFrameProxyHost(
                       static_cast<SiteInstanceImpl*>(orig_site_instance.get())
                           ->group()));
  ASSERT_EQ(expected_title, title_observer.WaitAndGetTitle());

  // Check message counts.
  EXPECT_EQ(1, EvalJs(opener_contents, "window.receivedMessagesViaPort;"));
  EXPECT_EQ(1, EvalJs(foo_contents, "window.receivedMessages;"));
  EXPECT_EQ(1, EvalJs(foo_contents, "window.receivedMessagesWithPort;"));
  EXPECT_EQ(u"msg-with-port", foo_contents->GetTitle());
  EXPECT_EQ(u"msg-back-via-port", opener_contents->GetTitle());
}

// Test for crbug.com/116192.  Navigations to a window's opener should
// still work after a process swap.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       AllowTargetedNavigationsInOpenerAfterSwap) {
  StartEmbeddedServer();

  if (IsIsolatedOriginRequiredToGuaranteeDedicatedProcess()) {
    // Isolate "foo.com" so we are guaranteed to get a non-default
    // SiteInstance for navigations to this origin.
    IsolateOriginsForTesting(embedded_test_server(), shell()->web_contents(),
                             {"foo.com"});
  }

  // Load a page with links that open in a new window.
  NavigateToPageWithLinks(shell());

  // Get the original tab and SiteInstance for later comparison.
  WebContents* orig_contents = shell()->web_contents();
  scoped_refptr<SiteInstance> orig_site_instance(
      orig_contents->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance.get() != nullptr);

  // Test clicking a target=foo link.
  ShellAddedObserver new_shell_observer;
  EXPECT_EQ(true, EvalJs(orig_contents, "clickSameSiteTargetedLink();"));
  Shell* new_shell = new_shell_observer.GetShell();

  // Wait for the navigation in the new window to finish, if it hasn't.
  EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));
  EXPECT_EQ("/navigate_opener.html",
            new_shell->web_contents()->GetLastCommittedURL().path());

  // Should have the same SiteInstance.
  scoped_refptr<SiteInstance> blank_site_instance(
      new_shell->web_contents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, blank_site_instance);

  // Now navigate the original (opener) tab to a different site.
  EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(
      shell(), embedded_test_server()->GetURL("foo.com", "/title1.html")));
  scoped_refptr<SiteInstance> new_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_NE(orig_site_instance, new_site_instance);

  // The opened tab should be able to navigate the opener back to its process.
  TestNavigationObserver navigation_observer(orig_contents);
  EXPECT_EQ(true, EvalJs(new_shell, "navigateOpener();"));
  navigation_observer.Wait();

  // Should have swapped back into this process.
  scoped_refptr<SiteInstance> revisit_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, revisit_site_instance);
}

// Test that subframes do not crash when sending a postMessage to the top frame
// from an unload handler while the top frame is being replaced as part of
// navigating cross-process.  https://crbug.com/475651.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       PostMessageFromSubframeUnloadHandler) {
  StartEmbeddedServer();

  GURL frame_url(embedded_test_server()->GetURL("/post_message.html"));
  GURL main_url("data:text/html,<iframe name='foo' src='" + frame_url.spec() +
                "'></iframe>");
  EXPECT_TRUE(NavigateToURL(shell(), main_url));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_NE(nullptr, orig_site_instance.get());

  // It is safe to obtain the root frame tree node here, as it doesn't change.
  FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
                            ->GetPrimaryFrameTree()
                            .root();
  ASSERT_EQ(1U, root->child_count());
  EXPECT_EQ(frame_url, root->child_at(0)->current_url());

  // Register an unload handler that sends a postMessage to the top frame.
  EXPECT_TRUE(ExecJs(root->child_at(0), "registerUnload();"));

  // Navigate the top frame cross-site.  This will cause the top frame to be
  // unloaded, and the original renderer process should then terminate since
  // it's not rendering any other frames.
  RenderProcessHostWatcher exit_observer(
      root->current_frame_host()->GetProcess(),
      RenderProcessHostWatcher::WATCH_FOR_HOST_DESTRUCTION);
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("foo.com", "/title1.html")));
  scoped_refptr<SiteInstance> new_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_NE(orig_site_instance, new_site_instance);

  // Ensure that the original renderer process exited cleanly without crashing.
  exit_observer.Wait();
  EXPECT_TRUE(exit_observer.did_exit_normally());
}

// Test that opening a new window in the same SiteInstance and then navigating
// both windows to a different SiteInstance allows the first process to exit.
// See http://crbug.com/126333.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       ProcessExitWithSwappedOutViews) {
  StartEmbeddedServer();
  if (IsIsolatedOriginRequiredToGuaranteeDedicatedProcess()) {
    // Isolate "foo.com" so we are guaranteed to get a non-default
    // SiteInstance for navigations to this origin.
    IsolateOriginsForTesting(embedded_test_server(), shell()->web_contents(),
                             {"foo.com"});
  }

  // Load a page with links that open in a new window.
  NavigateToPageWithLinks(shell());

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance.get() != nullptr);

  // Test clicking a target=foo link.
  ShellAddedObserver new_shell_observer;
  EXPECT_EQ(true, EvalJs(shell(), "clickSameSiteTargetedLink();"));
  Shell* new_shell = new_shell_observer.GetShell();

  // Wait for the navigation in the new window to finish, if it hasn't.
  EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));
  EXPECT_EQ("/navigate_opener.html",
            new_shell->web_contents()->GetLastCommittedURL().path());

  // Should have the same SiteInstance.
  scoped_refptr<SiteInstance> opened_site_instance(
      new_shell->web_contents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, opened_site_instance);

  // Now navigate the opened window to a different site.
  GURL cross_site_url(
      embedded_test_server()->GetURL("foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, cross_site_url));
  scoped_refptr<SiteInstance> new_site_instance(
      new_shell->web_contents()->GetSiteInstance());
  EXPECT_NE(orig_site_instance, new_site_instance);

  // The original process should still be alive, since it is still used in the
  // first window.
  RenderProcessHost* orig_process = orig_site_instance->GetProcess();
  EXPECT_TRUE(orig_process->IsInitializedAndNotDead());

  // Navigate the first window to a different site as well.  The original
  // process should exit, since all of its active frames are gone.
  RenderProcessHostWatcher exit_observer(
      orig_process, RenderProcessHostWatcher::WATCH_FOR_HOST_DESTRUCTION);
  EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(shell(), cross_site_url));
  exit_observer.Wait();
  scoped_refptr<SiteInstance> new_site_instance2(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_EQ(new_site_instance, new_site_instance2);
}

// Test for crbug.com/76666.  A cross-site navigation that fails with a 204
// error should not make us ignore future renderer-initiated navigations.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest, ClickLinkAfter204Error) {
  StartServer();

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance.get() != nullptr);

  // Load a cross-site page that fails with a 204 error.
  EXPECT_TRUE(
      NavigateToURLAndExpectNoCommit(shell(), GetCrossSiteURL("/nocontent")));

  // We should still be looking at the normal page.  Because we started from a
  // blank new tab, the typed URL will still be visible until the user clears it
  // manually.  The last committed URL will be the previous page.
  scoped_refptr<SiteInstance> post_nav_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, post_nav_site_instance);
  EXPECT_EQ("/nocontent", shell()->web_contents()->GetVisibleURL().path());
  NavigationEntry* current_entry =
      shell()->web_contents()->GetController().GetLastCommittedEntry();
  EXPECT_TRUE(!current_entry || current_entry->IsInitialEntry());

  // Renderer-initiated navigations should work.
  std::u16string expected_title = u"Title Of Awesomeness";
  TitleWatcher title_watcher(shell()->web_contents(), expected_title);
  GURL url = embedded_test_server()->GetURL("/title2.html");
  EXPECT_TRUE(ExecJs(
      shell(), base::StringPrintf("location.href = '%s'", url.spec().c_str())));
  ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle());

  // Opens in same tab.
  EXPECT_EQ(1u, Shell::windows().size());
  EXPECT_EQ("/title2.html",
            shell()->web_contents()->GetLastCommittedURL().path());

  // Should have the same SiteInstance.
  scoped_refptr<SiteInstance> new_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, new_site_instance);
}

// A collection of tests to prevent URL spoofs when showing pending URLs above
// initial empty documents, ensuring that the URL reverts to about:blank if the
// document is accessed. See https://crbug.com/9682.
class RenderFrameHostManagerSpoofingTest : public RenderFrameHostManagerTest {
 public:
  void SetUpInProcessBrowserTestFixture() override {
    base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();

    base::CommandLine new_command_line(command_line->GetProgram());
    base::CommandLine::SwitchMap switches = command_line->GetSwitches();

    // Injecting the DOM automation controller causes false positives, since it
    // triggers the DidAccessInitialDocument() callback by mutating the global
    // object.
    switches.erase(switches::kDomAutomationController);

    for (const auto& it : switches)
      new_command_line.AppendSwitchNative(it.first, it.second);

    *command_line = new_command_line;
  }

 protected:
  // Custom ExecuteScript() helper that doesn't depend on DOM automation
  // controller. This is used to guarantee the script has completed execution,
  // but the spoofing tests synchronize execution using window title changes.
  void ExecuteScript(const ToRenderFrameHost& adapter, const char* script) {
    adapter.render_frame_host()->ExecuteJavaScriptForTests(
        base::UTF8ToUTF16(script), base::NullCallback(),
        ISOLATED_WORLD_ID_GLOBAL);
  }
};

// Helper to wait until a WebContent's NavigationController has a visible entry
// that is not the initial NavigationEntry.
class VisibleEntryWaiter : public WebContentsObserver {
 public:
  explicit VisibleEntryWaiter(WebContents* web_contents)
      : WebContentsObserver(web_contents) {}

  void Wait() {
    if (auto* entry = web_contents()->GetController().GetVisibleEntry()) {
      if (entry && !entry->IsInitialEntry())
        return;
    }
    run_loop_.Run();
  }

  // WebContentsObserver overrides:
  void DidStartNavigation(NavigationHandle* navigation_handle) override {
    run_loop_.Quit();
  }

 private:
  base::RunLoop run_loop_;
};

// Sanity test that a newly opened window shows the pending URL if the initial
// empty document is not modified. This is intentionally structured as similarly
// as possible to the subsequent ShowLoadingURLUntil*Spoof tests: it performs
// the same operations as the subsequent tests except DOM modification. This
// should help catch instances where the subsequent tests incorrectly pass due
// to a side effect of the test infrastructure.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerSpoofingTest,
                       ShowLoadingURLIfNotModified) {
  ASSERT_TRUE(embedded_test_server()->Start());

  // Load a page that can open a URL that won't commit in a new window.
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("/click-nocontent-link.html")));
  WebContents* orig_contents = shell()->web_contents();

  // Click a /nocontent link that opens in a new window but never commits.
  ShellAddedObserver new_shell_observer;
  ExecuteScript(orig_contents, "clickNoContentTargetedLink();");

  // Wait for the window to open.
  Shell* new_shell = new_shell_observer.GetShell();
  WebContents* contents = new_shell->web_contents();

  // Make sure the new window has started the provisional load, so the
  // associated navigation controller will have a visible entry.
  {
    VisibleEntryWaiter waiter(contents);
    waiter.Wait();
  }

  // Ensure the destination URL is visible, because it is considered the
  // initial navigation.
  EXPECT_TRUE(contents->GetController().IsInitialNavigation());
  EXPECT_EQ("/nocontent",
            contents->GetController().GetVisibleEntry()->GetURL().path());

  // Now get another reference to the window object, but don't otherwise access
  // it. This is to ensure that DidAccessInitialDocument() notifications are not
  // incorrectly generated when nothing is modified.
  std::u16string expected_title = u"Modified Title";
  TitleWatcher title_watcher(orig_contents, expected_title);
  ExecuteScript(orig_contents, "getNewWindowReference();");
  ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle());

  // The destination URL should still be visible, since nothing was modified.
  EXPECT_TRUE(contents->GetController().IsInitialNavigation());
  EXPECT_EQ("/nocontent",
            contents->GetController().GetVisibleEntry()->GetURL().path());
}

// Test for crbug.com/9682.  We should show the URL for a pending renderer-
// initiated navigation in a new tab, until the content of the initial
// about:blank page is modified by another window.  At that point, we should
// revert to showing about:blank to prevent a URL spoof.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerSpoofingTest,
                       ShowLoadingURLUntilSpoof) {
  ASSERT_TRUE(embedded_test_server()->Start());

  // Load a page that can open a URL that won't commit in a new window.
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("/click-nocontent-link.html")));
  WebContents* orig_contents = shell()->web_contents();

  // Change the link to be cross-site.
  GURL target_url = embedded_test_server()->GetURL("foo.com", "/nocontent");
  ExecuteScript(
      orig_contents,
      base::StringPrintf(
          "document.getElementById('nocontent_targeted_link').href = '%s';",
          target_url.spec().c_str())
          .c_str());

  // Click a /nocontent link that opens in a new window but never commits.
  ShellAddedObserver new_shell_observer;
  ExecuteScript(orig_contents, "clickNoContentTargetedLink();");

  // Wait for the window to open.
  Shell* new_shell = new_shell_observer.GetShell();
  WebContents* contents = new_shell->web_contents();

  // Make sure the new window has started the navigation, so the associated
  // navigation controller will have a visible entry.
  {
    VisibleEntryWaiter waiter(contents);
    waiter.Wait();
  }

  // Ensure the destination URL is visible, because it is considered the
  // initial navigation.
  EXPECT_TRUE(contents->GetController().IsInitialNavigation());
  EXPECT_EQ(target_url, contents->GetController().GetVisibleEntry()->GetURL());

  // Now modify the contents of the new window from the opener.  This will also
  // modify the title of the document to give us something to listen for.
  std::u16string expected_title = u"Modified Title";
  TitleWatcher title_watcher(orig_contents, expected_title);
  ExecuteScript(orig_contents, "modifyNewWindow();");
  ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle());

  // At this point, we should no longer be showing the destination URL.
  // The visible entry should be the initial entry (or null), resulting in
  // about:blank in the address bar.
  NavigationEntry* visible_entry =
      new_shell->web_contents()->GetController().GetLastCommittedEntry();
  EXPECT_TRUE(!visible_entry || visible_entry->IsInitialEntry());
}

// Same as ShowLoadingURLUntilSpoof, but reloads the new popup before modifying
// it, to test https://crbug.com/847718.  The reload should not cause the
// visible entry to stick around after the modification, even though it is
// triggered in the browser process.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerSpoofingTest,
                       ShowLoadingURLUntilSpoofAfterReload) {
  ASSERT_TRUE(embedded_test_server()->Start());

  // Load a page that can open a URL that won't commit in a new window.
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("/click-nocontent-link.html")));
  WebContents* orig_contents = shell()->web_contents();

  // Change the link to be cross-site.
  GURL target_url = embedded_test_server()->GetURL("foo.com", "/nocontent");
  ExecuteScript(
      orig_contents,
      base::StringPrintf(
          "document.getElementById('nocontent_targeted_link').href = '%s';",
          target_url.spec().c_str())
          .c_str());

  // Click a /nocontent link that opens in a new window but never commits.
  ShellAddedObserver new_shell_observer;
  ExecuteScript(orig_contents, "clickNoContentTargetedLink();");

  // Wait for the window to open.
  Shell* new_shell = new_shell_observer.GetShell();
  WebContents* contents = new_shell->web_contents();

  // Make sure the new window has started the navigation, so the associated
  // navigation controller will have a visible entry.
  {
    VisibleEntryWaiter waiter(contents);
    waiter.Wait();
  }

  // Ensure the destination URL is visible, because it is considered the
  // initial navigation.
  EXPECT_TRUE(contents->GetController().IsInitialNavigation());
  EXPECT_EQ(target_url, contents->GetController().GetVisibleEntry()->GetURL());

  // Reload the popup before modifying it.  See https://crbug.com/847718.
  contents->GetController().Reload(ReloadType::NORMAL, false);

  // Now modify the contents of the new window from the opener.  This will also
  // modify the title of the document to give us something to listen for.
  std::u16string expected_title = u"Modified Title";
  TitleWatcher title_watcher(orig_contents, expected_title);
  ExecuteScript(orig_contents, "modifyNewWindow();");
  ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle());

  // At this point, we should no longer be showing the destination URL.
  // The visible entry should be the initial entry (or null), resulting in
  // about:blank in the address bar.
  NavigationEntry* visible_entry =
      new_shell->web_contents()->GetController().GetLastCommittedEntry();
  EXPECT_TRUE(!visible_entry || visible_entry->IsInitialEntry());
}

// Similar but using document.open(): once a Document is opened, subsequent
// document.write() calls can insert arbitrary content into the target Document.
// Since this could result in URL spoofing, the pending URL should no longer be
// shown in the omnibox.
//
// Note: document.write() implicitly invokes document.open() if the Document has
// not already been opened, so there's no need to test document.write()
// separately.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerSpoofingTest,
                       ShowLoadingURLUntilDocumentOpenSpoof) {
  ASSERT_TRUE(embedded_test_server()->Start());

  // Load a page that can open a URL that won't commit in a new window.
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("/click-nocontent-link.html")));
  WebContents* orig_contents = shell()->web_contents();

  // Click a /nocontent link that opens in a new window but never commits.
  ShellAddedObserver new_shell_observer;
  ExecuteScript(orig_contents, "clickNoContentTargetedLink();");

  // Wait for the window to open.
  Shell* new_shell = new_shell_observer.GetShell();
  WebContents* contents = new_shell->web_contents();

  // Make sure the new window has started the provisional load, so the
  // associated navigation controller will have a visible entry.
  {
    VisibleEntryWaiter waiter(contents);
    waiter.Wait();
  }

  // Ensure the destination URL is visible, because it is considered the
  // initial navigation.
  EXPECT_TRUE(contents->GetController().IsInitialNavigation());
  EXPECT_EQ("/nocontent",
            contents->GetController().GetVisibleEntry()->GetURL().path());

  // Now modify the contents of the new window from the opener.  This will also
  // modify the title of the document to give us something to listen for.
  std::u16string expected_title = u"Modified Title";
  TitleWatcher title_watcher(orig_contents, expected_title);
  ExecuteScript(orig_contents, "modifyNewWindowWithDocumentOpen();");
  ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle());

  // At this point, we should no longer be showing the destination URL.
  // The visible entry should be the initial entry (or null), resulting in
  // about:blank in the address bar.
  NavigationEntry* visible_entry =
      new_shell->web_contents()->GetController().GetLastCommittedEntry();
  EXPECT_TRUE(!visible_entry || visible_entry->IsInitialEntry());
}

IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       WasDiscardedWhenNavigationInterruptsReload) {
  EXPECT_TRUE(embedded_test_server()->Start());
  GURL discarded_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), discarded_url));
  // Discard the page.
  shell()->web_contents()->SetWasDiscarded(true);
  // Reload the discarded page, but pretend that it's slow to commit.
  TestNavigationManager first_reload(shell()->web_contents(), discarded_url);
  shell()->web_contents()->GetController().LoadOriginalRequestURL();
  EXPECT_TRUE(first_reload.WaitForRequestStart());
  // Before the response is received, simulate user navigating to another URL.
  GURL second_url(embedded_test_server()->GetURL("b.com", "/title1.html"));
  TestNavigationManager second_navigation(shell()->web_contents(), second_url);
  shell()->LoadURL(second_url);
  ASSERT_TRUE(second_navigation.WaitForNavigationFinished());
  const char kDiscardedStateJS[] = "window.document.wasDiscarded;";
  EXPECT_EQ(false, content::EvalJs(shell(), kDiscardedStateJS));
}

// Ensures that a pending navigation's URL  is no longer visible after the
// speculative RFH is discarded due to a concurrent renderer-initiated
// navigation.  See https://crbug.com/760342.
// TODO(crbug.com/41448629): Disabled due to flaky timeouts.
IN_PROC_BROWSER_TEST_P(
    RenderFrameHostManagerTest,
    DISABLED_ResetVisibleURLOnCrossProcessNavigationInterrupted) {
  const std::string kVictimPath = "/victim.html";
  const std::string kAttackPath = "/attack.html";
  net::test_server::ControllableHttpResponse victim_response(
      embedded_test_server(), kVictimPath);
  net::test_server::ControllableHttpResponse attack_response(
      embedded_test_server(), kAttackPath);
  EXPECT_TRUE(embedded_test_server()->Start());

  const GURL kVictimURL = embedded_test_server()->GetURL("a.com", kVictimPath);
  const GURL kAttackURL = embedded_test_server()->GetURL("b.com", kAttackPath);

  // First navigate to the attacker page. This page will be cross-site compared
  // to the next navigations we will attempt.
  const GURL kAttackInitialURL =
      embedded_test_server()->GetURL("b.com", "/title1.html");
  EXPECT_TRUE(NavigateToURL(shell(), kAttackInitialURL));
  EXPECT_EQ(kAttackInitialURL, shell()->web_contents()->GetVisibleURL());

  // Now, start a browser-initiated cross-site navigation to a new page that
  // will hang at ready to commit stage.
  TestNavigationManager victim_navigation(shell()->web_contents(), kVictimURL);
  shell()->LoadURL(kVictimURL);
  EXPECT_TRUE(victim_navigation.WaitForRequestStart());
  victim_navigation.ResumeNavigation();

  victim_response.WaitForRequest();
  victim_response.Send(
      "HTTP/1.1 200 OK\r\n"
      "Content-Type: text/html; charset=utf-8\r\n"
      "\r\n");
  EXPECT_TRUE(victim_navigation.WaitForResponse());
  victim_navigation.ResumeNavigation();

  // The navigation is ready to commit: it has been handed to the speculative
  // RenderFrameHost for commit.
  RenderFrameHostImpl* speculative_rfh =
      static_cast<WebContentsImpl*>(shell()->web_contents())
          ->GetPrimaryFrameTree()
          .root()
          ->render_manager()
          ->speculative_frame_host();
  CHECK(speculative_rfh);
  EXPECT_TRUE(speculative_rfh->is_loading());

  // Since we have a browser-initiated pending navigation, the navigation URL is
  // showing in the address bar.
  EXPECT_EQ(kVictimURL, shell()->web_contents()->GetVisibleURL());

  // The attacker page requests a navigation to a new document while the
  // browser-initiated navigation hasn't committed yet.
  TestNavigationManager attack_navigation(shell()->web_contents(), kAttackURL);
  EXPECT_TRUE(ExecJs(shell()->web_contents(),
                     "location.href = \"" + kAttackURL.spec() + "\";",
                     EXECUTE_SCRIPT_NO_USER_GESTURE));
  EXPECT_TRUE(attack_navigation.WaitForRequestStart());

  // This deletes the speculative RenderFrameHost that was supposed to commit
  // the browser-initiated navigation.
  speculative_rfh = static_cast<WebContentsImpl*>(shell()->web_contents())
                        ->GetPrimaryFrameTree()
                        .root()
                        ->render_manager()
                        ->speculative_frame_host();
  EXPECT_FALSE(speculative_rfh);

  // The URL of the browser-initiated navigation should no longer be shown in
  // the address bar since the RenderFrameHost that was supposed to commit it
  // has been discarded. Instead, we should be showing the URL of the current
  // page as we do not show the URL of pending navigations when they are
  // renderer-initiated.
  EXPECT_NE(kVictimURL, shell()->web_contents()->GetVisibleURL());
  EXPECT_EQ(kAttackInitialURL, shell()->web_contents()->GetVisibleURL());

  // The attacker navigation results in a 204.
  attack_navigation.ResumeNavigation();
  attack_response.WaitForRequest();
  attack_response.Send(
      "HTTP/1.1 204 OK\r\n"
      "Connection: close\r\n"
      "\r\n");
  ASSERT_TRUE(attack_navigation.WaitForNavigationFinished());
  speculative_rfh = static_cast<WebContentsImpl*>(shell()->web_contents())
                        ->GetPrimaryFrameTree()
                        .root()
                        ->render_manager()
                        ->speculative_frame_host();
  EXPECT_FALSE(speculative_rfh);

  // We are still showing the URL of the current page.
  EXPECT_EQ(kAttackInitialURL, shell()->web_contents()->GetVisibleURL());
}

// Ensures that deleting a speculative RenderFrameHost trying to commit a
// navigation to the pending NavigationEntry will not crash if it happens
// because a new navigation to the same pending NavigationEntry started. This is
// a regression test for crbug.com/796135.
IN_PROC_BROWSER_TEST_P(
    RenderFrameHostManagerTest,
    DeleteSpeculativeRFHPendingCommitOfPendingEntryOnInterrupted1) {
  if (!AreAllSitesIsolatedForTesting()) {
    GTEST_SKIP() << "This test requires speculative RenderFrameHosts, so skip "
                    "it when site isolation is turned off";
  }

  const std::string kOriginalPath = "/original.html";
  const std::string kFirstRedirectPath = "/redirect1.html";
  const std::string kSecondRedirectPath = "/reidrect2.html";
  net::test_server::ControllableHttpResponse original_response1(
      embedded_test_server(), kOriginalPath);
  net::test_server::ControllableHttpResponse original_response2(
      embedded_test_server(), kOriginalPath);
  net::test_server::ControllableHttpResponse original_response3(
      embedded_test_server(), kOriginalPath);
  net::test_server::ControllableHttpResponse first_redirect_response(
      embedded_test_server(), kFirstRedirectPath);
  net::test_server::ControllableHttpResponse second_redirect_response(
      embedded_test_server(), kSecondRedirectPath);
  EXPECT_TRUE(embedded_test_server()->Start());

  const GURL kOriginalURL =
      embedded_test_server()->GetURL("a.com", kOriginalPath);
  const GURL kFirstRedirectURL =
      embedded_test_server()->GetURL("b.com", kFirstRedirectPath);
  const GURL kSecondRedirectURL =
      embedded_test_server()->GetURL("c.com", kSecondRedirectPath);

  // First navigate to the initial URL. This page will have a cross-site
  // redirect.
  shell()->LoadURL(kOriginalURL);
  original_response1.WaitForRequest();
  original_response1.Send(
      "HTTP/1.1 302 FOUND\r\n"
      "Location: " +
      kFirstRedirectURL.spec() +
      "\r\n"
      "\r\n");
  original_response1.Done();
  first_redirect_response.WaitForRequest();
  first_redirect_response.Send(
      "HTTP/1.1 200 OK\r\n"
      "Content-Type: text/html; charset=utf-8\r\n"
      "\r\n");
  first_redirect_response.Send(
      "<html>"
      "<body></body>"
      "</html>");
  first_redirect_response.Done();
  EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
  EXPECT_EQ(kFirstRedirectURL, shell()->web_contents()->GetLastCommittedURL());

  // Now reload the original request, but redirect to yet another site.
  TestNavigationManager first_reload(shell()->web_contents(), kOriginalURL);
  shell()->web_contents()->GetController().LoadOriginalRequestURL();
  EXPECT_TRUE(first_reload.WaitForRequestStart());
  first_reload.ResumeNavigation();

  original_response2.WaitForRequest();
  original_response2.Send(
      "HTTP/1.1 302 FOUND\r\n"
      "Location: " +
      kSecondRedirectURL.spec() +
      "\r\n"
      "\r\n");
  original_response2.Done();
  EXPECT_TRUE(first_reload.WaitForRequestRedirected());
  first_reload.ResumeNavigation();
  second_redirect_response.WaitForRequest();
  second_redirect_response.Send(
      "HTTP/1.1 200 OK\r\n"
      "Content-Type: text/html; charset=utf-8\r\n"
      "\r\n");
  EXPECT_TRUE(first_reload.WaitForResponse());

  FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
                            ->GetPrimaryFrameTree()
                            .root();
  RenderFrameHostImplWrapper first_speculative_rfh(
      root->render_manager()->speculative_frame_host());
  EXPECT_TRUE(first_speculative_rfh.get());

  // The user requests a new reload while the previous reload hasn't committed
  // yet. This second reload starts immediately after pausing the commit of the
  // first reload. It might delete the speculative RenderFrameHost that was
  // supposed to commit the first reload. This should not crash.
  TestNavigationManager second_reload(shell()->web_contents(), kOriginalURL);
  CommitNavigationPauser commit_pauser(first_speculative_rfh.get());
  first_reload.ResumeNavigation();
  commit_pauser.WaitForCommitAndPause();
  shell()->web_contents()->GetController().LoadOriginalRequestURL();
  EXPECT_TRUE(second_reload.WaitForRequestStart());

  RenderFrameHostImplWrapper second_speculative_rfh(
      root->render_manager()->speculative_frame_host());

  EXPECT_TRUE(second_speculative_rfh.get());
  if (ShouldQueueNavigationsWhenPendingCommitRFHExists()) {
    // When navigation queueing is enabled, the first speculative RFH is still
    // kept around as it is pending commit.
    EXPECT_TRUE(first_speculative_rfh.get());
    EXPECT_EQ(first_speculative_rfh.get(), second_speculative_rfh.get());
  } else {
    // Otherwise, the first speculative RFH will be deleted and replaced by a
    // new speculative RFH.
    EXPECT_FALSE(first_speculative_rfh.get());
  }

  // The second reload results in a 204.
  second_reload.ResumeNavigation();
  original_response3.WaitForRequest();
  original_response3.Send(
      "HTTP/1.1 204 OK\r\n"
      "Connection: close\r\n"
      "\r\n");
  ASSERT_TRUE(second_reload.WaitForNavigationFinished());

  if (ShouldQueueNavigationsWhenPendingCommitRFHExists()) {
    // If navigation queuing is enabled, the first reload's speculative RFH
    // will be kept.
    EXPECT_TRUE(root->render_manager()->speculative_frame_host());
  } else {
    // If navigation queueing is turned off, the second reload will delete the
    // first reload's speculative RFH, and we end up with no speculative RFH
    // after the second reload commits.
    EXPECT_FALSE(root->render_manager()->speculative_frame_host());
  }
}

#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) || \
    BUILDFLAG(IS_MAC)
#define MAYBE_DeleteSpeculativeRFHPendingCommitOfPendingEntryOnInterrupted2 \
  DISABLED_DeleteSpeculativeRFHPendingCommitOfPendingEntryOnInterrupted2
#else
#define MAYBE_DeleteSpeculativeRFHPendingCommitOfPendingEntryOnInterrupted2 \
  DeleteSpeculativeRFHPendingCommitOfPendingEntryOnInterrupted2
#endif
// Ensures that deleting a speculative RenderFrameHost trying to commit a
// navigation to the pending NavigationEntry will not crash if it happens
// because a new navigation to the same pending NavigationEntry started.  This
// is a variant of the previous test, where we destroy the speculative
// RenderFrameHost to create another speculative RenderFrameHost. This is a
// regression test for crbug.com/796135.
IN_PROC_BROWSER_TEST_P(
    RenderFrameHostManagerTest,
    MAYBE_DeleteSpeculativeRFHPendingCommitOfPendingEntryOnInterrupted2) {
  if (ShouldQueueNavigationsWhenPendingCommitRFHExists()) {
    // When navigation queueing is enabled, starting a new navigation won't
    // delete an existing pending commit RFH, so this test can't run as
    // intended.
    return;
  }
  const std::string kOriginalPath = "/original.html";
  const std::string kRedirectPath = "/redirect.html";
  net::test_server::ControllableHttpResponse original_response1(
      embedded_test_server(), kOriginalPath);
  net::test_server::ControllableHttpResponse original_response2(
      embedded_test_server(), kOriginalPath);
  net::test_server::ControllableHttpResponse redirect_response(
      embedded_test_server(), kRedirectPath);
  EXPECT_TRUE(embedded_test_server()->Start());

  const GURL kOriginalURL =
      embedded_test_server()->GetURL("a.com", kOriginalPath);
  const GURL kRedirectURL =
      embedded_test_server()->GetURL("b.com", kRedirectPath);
  const GURL kCrossSiteURL =
      embedded_test_server()->GetURL("c.com", "/title1.html");

  IsolationContext isolation_context(
      shell()->web_contents()->GetBrowserContext());
  const auto kOriginalSiteInfo =
      SiteInfo::CreateForTesting(isolation_context, kOriginalURL);
  const auto kRedirectSiteInfo =
      SiteInfo::CreateForTesting(isolation_context, kRedirectURL);

  // First navigate to the initial URL.
  shell()->LoadURL(kOriginalURL);
  original_response1.WaitForRequest();
  original_response1.Send(
      "HTTP/1.1 200 OK\r\n"
      "Content-Type: text/html; charset=utf-8\r\n"
      "Cache-Control: no-cache, no-store, must-revalidate\r\n"
      "Pragma: no-cache\r\n"
      "\r\n");
  original_response1.Send(
      "<html>"
      "<body></body>"
      "</html>");
  original_response1.Done();
  EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
  EXPECT_EQ(kOriginalURL, shell()->web_contents()->GetLastCommittedURL());

  // Navigate cross-site.
  EXPECT_TRUE(NavigateToURL(shell(), kCrossSiteURL));

  // Now go back to the original request, which will do a cross-site redirect.
  TestNavigationManager first_back(shell()->web_contents(), kOriginalURL);
  shell()->GoBackOrForward(-1);
  EXPECT_TRUE(first_back.WaitForRequestStart());
  first_back.ResumeNavigation();

  original_response2.WaitForRequest();
  original_response2.Send(
      "HTTP/1.1 302 FOUND\r\n"
      "Location: " +
      kRedirectURL.spec() +
      "\r\n"
      "\r\n");
  original_response2.Done();
  redirect_response.WaitForRequest();
  redirect_response.Send(
      "HTTP/1.1 200 OK\r\n"
      "Content-Type: text/html; charset=utf-8\r\n"
      "\r\n");
  EXPECT_TRUE(first_back.WaitForResponse());
  first_back.ResumeNavigation();

  // The navigation is ready to commit: it has been handed to the speculative
  // RenderFrameHost for commit.
  RenderFrameHostImpl* speculative_rfh =
      static_cast<WebContentsImpl*>(shell()->web_contents())
          ->GetPrimaryFrameTree()
          .root()
          ->render_manager()
          ->speculative_frame_host();
  CHECK(speculative_rfh);
  EXPECT_TRUE(speculative_rfh->is_loading());
  if (AreAllSitesIsolatedForTesting()) {
    EXPECT_EQ(kRedirectSiteInfo,
              speculative_rfh->GetSiteInstance()->GetSiteInfo());
  } else if (AreDefaultSiteInstancesEnabled()) {
    EXPECT_TRUE(speculative_rfh->GetSiteInstance()->IsDefaultSiteInstance());
  } else {
    EXPECT_EQ(kOriginalSiteInfo,
              speculative_rfh->GetSiteInstance()->GetSiteInfo());
  }
  auto site_instance_id = speculative_rfh->GetSiteInstance()->GetId();

  // The user starts a navigation towards the redirected URL, for which we have
  // a speculative RenderFrameHost. This shouldn't delete the speculative
  // RenderFrameHost.
  TestNavigationManager navigation_to_redirect(shell()->web_contents(),
                                               kRedirectURL);
  shell()->LoadURL(kRedirectURL);
  EXPECT_TRUE(navigation_to_redirect.WaitForRequestStart());
  speculative_rfh = static_cast<WebContentsImpl*>(shell()->web_contents())
                        ->GetPrimaryFrameTree()
                        .root()
                        ->render_manager()
                        ->speculative_frame_host();
  CHECK(speculative_rfh);
  if (AreDefaultSiteInstancesEnabled()) {
    EXPECT_TRUE(speculative_rfh->GetSiteInstance()->IsDefaultSiteInstance());
  } else {
    EXPECT_EQ(kRedirectSiteInfo,
              speculative_rfh->GetSiteInstance()->GetSiteInfo());
    if (AreAllSitesIsolatedForTesting())
      EXPECT_EQ(site_instance_id, speculative_rfh->GetSiteInstance()->GetId());
  }

  // The user requests to go back again while the previous back hasn't committed
  // yet. This should delete the speculative RenderFrameHost trying to commit
  // the back, and re-create a new speculative RenderFrameHost. This shouldn't
  // crash.
  TestNavigationManager second_back(shell()->web_contents(), kOriginalURL);
  shell()->GoBackOrForward(-1);
  EXPECT_TRUE(second_back.WaitForRequestStart());
  speculative_rfh = static_cast<WebContentsImpl*>(shell()->web_contents())
                        ->GetPrimaryFrameTree()
                        .root()
                        ->render_manager()
                        ->speculative_frame_host();
  CHECK(speculative_rfh);
  if (AreDefaultSiteInstancesEnabled()) {
    EXPECT_TRUE(speculative_rfh->GetSiteInstance()->IsDefaultSiteInstance());
  } else {
    EXPECT_EQ(kOriginalSiteInfo,
              speculative_rfh->GetSiteInstance()->GetSiteInfo());
  }
  if (AreAllSitesIsolatedForTesting())
    EXPECT_NE(site_instance_id, speculative_rfh->GetSiteInstance()->GetId());
}

// Test for crbug.com/9682.  We should not show the URL for a pending renderer-
// initiated navigation in a new tab if it is not the initial navigation.  In
// this case, the renderer will not notify us of a modification, so we cannot
// show the pending URL without allowing a spoof.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       DontShowLoadingURLIfNotInitialNav) {
  ASSERT_TRUE(embedded_test_server()->Start());

  // Load a page that can open a URL that won't commit in a new window.
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("/click-nocontent-link.html")));
  WebContents* orig_contents = shell()->web_contents();

  // Click a /nocontent link that opens in a new window but never commits.
  // By using an onclick handler that first creates the window, the slow
  // navigation is not considered an initial navigation.
  ShellAddedObserver new_shell_observer;
  EXPECT_EQ(true,
            EvalJs(orig_contents, "clickNoContentScriptedTargetedLink();"));

  // Wait for the window to open.
  Shell* new_shell = new_shell_observer.GetShell();

  // Ensure the destination URL is not visible, because it is not the initial
  // navigation.
  WebContents* contents = new_shell->web_contents();
  EXPECT_FALSE(contents->GetController().IsInitialNavigation());
  // The visible entry should be the entry for the synchronously committed
  // about:blank, resulting in about:blank in the address bar.
  EXPECT_EQ(GURL(url::kAboutBlankURL),
            contents->GetController().GetVisibleEntry()->GetURL());
}

// Crashes under ThreadSanitizer, http://crbug.com/356758.
#if defined(THREAD_SANITIZER)
#define MAYBE_BackForwardNotStale DISABLED_BackForwardNotStale
#else
#define MAYBE_BackForwardNotStale BackForwardNotStale
#endif
// Test for http://crbug.com/93427.  Ensure that cross-site navigations
// do not cause back/forward navigations to be considered stale by the
// renderer.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest, MAYBE_BackForwardNotStale) {
  StartEmbeddedServer();
  EXPECT_TRUE(
      NavigateToURL(shell(), embedded_test_server()->GetURL("/empty.html")));

  // Visit a page on first site.
  EXPECT_TRUE(
      NavigateToURL(shell(), embedded_test_server()->GetURL("/title1.html")));

  // Visit three pages on second site.
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("foo.com", "/title1.html")));
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("foo.com", "/title2.html")));
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("foo.com", "/title3.html")));

  // History is now [blank, A1, B1, B2, *B3].
  WebContents* contents = shell()->web_contents();
  EXPECT_EQ(5, contents->GetController().GetEntryCount());

  // Open another window in same process to keep this process alive.
  Shell* new_shell = CreateBrowser();
  EXPECT_TRUE(NavigateToURL(
      new_shell, embedded_test_server()->GetURL("foo.com", "/title1.html")));

  // Go back three times to first site.
  {
    TestNavigationObserver back_nav_load_observer(shell()->web_contents());
    shell()->web_contents()->GetController().GoBack();
    back_nav_load_observer.Wait();
  }
  {
    TestNavigationObserver back_nav_load_observer(shell()->web_contents());
    shell()->web_contents()->GetController().GoBack();
    back_nav_load_observer.Wait();
  }
  {
    TestNavigationObserver back_nav_load_observer(shell()->web_contents());
    shell()->web_contents()->GetController().GoBack();
    back_nav_load_observer.Wait();
  }

  // Now go forward twice to B2.  Shouldn't be left spinning.
  {
    TestNavigationObserver forward_nav_load_observer(shell()->web_contents());
    shell()->web_contents()->GetController().GoForward();
    forward_nav_load_observer.Wait();
  }
  {
    TestNavigationObserver forward_nav_load_observer(shell()->web_contents());
    shell()->web_contents()->GetController().GoForward();
    forward_nav_load_observer.Wait();
  }

  // Go back twice to first site.
  {
    TestNavigationObserver back_nav_load_observer(shell()->web_contents());
    shell()->web_contents()->GetController().GoBack();
    back_nav_load_observer.Wait();
  }
  {
    TestNavigationObserver back_nav_load_observer(shell()->web_contents());
    shell()->web_contents()->GetController().GoBack();
    back_nav_load_observer.Wait();
  }

  // Now go forward directly to B3.  Shouldn't be left spinning.
  {
    TestNavigationObserver forward_nav_load_observer(shell()->web_contents());
    shell()->web_contents()->GetController().GoToIndex(4);
    forward_nav_load_observer.Wait();
  }
}

// This class ensures that all the given RenderViewHosts have properly been
// shutdown.
class RenderViewHostDestructionObserver : public WebContentsObserver {
 public:
  explicit RenderViewHostDestructionObserver(WebContents* web_contents)
      : WebContentsObserver(web_contents) {}
  ~RenderViewHostDestructionObserver() override = default;
  void EnsureRVHGetsDestructed(RenderViewHost* rvh) {
    watched_render_view_hosts_.insert(rvh);
  }
  size_t GetNumberOfWatchedRenderViewHosts() const {
    return watched_render_view_hosts_.size();
  }

 private:
  // WebContentsObserver implementation:
  void RenderViewDeleted(RenderViewHost* rvh) override {
    watched_render_view_hosts_.erase(rvh);
  }

  std::set<raw_ptr<RenderViewHost, SetExperimental>> watched_render_view_hosts_;
};

// Crashes under ThreadSanitizer, http://crbug.com/356758.
#if defined(THREAD_SANITIZER)
#define MAYBE_LeakingRenderViewHosts DISABLED_LeakingRenderViewHosts
#else
#define MAYBE_LeakingRenderViewHosts LeakingRenderViewHosts
#endif
// Test for crbug.com/90867. Make sure we don't leak render view hosts since
// they may cause crashes or memory corruptions when trying to call dead
// delegate_. This test also verifies crbug.com/117420 and crbug.com/143255 to
// ensure that a separate SiteInstance is created when navigating to view-source
// URLs, regardless of current URL.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       MAYBE_LeakingRenderViewHosts) {
  StartEmbeddedServer();

  // Observe the created render_view_host's to make sure they will not leak.
  RenderViewHostDestructionObserver rvh_observers(shell()->web_contents());

  GURL navigated_url(embedded_test_server()->GetURL("/title2.html"));
  GURL view_source_url(kViewSourceScheme + std::string(":") +
                       navigated_url.spec());

  // Let's ensure that when we start with a blank window, navigating away to a
  // view-source URL, we create a new SiteInstance.
  RenderViewHost* blank_rvh =
      shell()->web_contents()->GetPrimaryMainFrame()->GetRenderViewHost();
  SiteInstance* blank_site_instance =
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), GURL());
  EXPECT_EQ(blank_site_instance->GetSiteURL(), GURL());
  rvh_observers.EnsureRVHGetsDestructed(blank_rvh);

  // Now navigate to the view-source URL and ensure we got a different
  // SiteInstance and RenderViewHost.
  EXPECT_TRUE(NavigateToURL(shell(), view_source_url));
  EXPECT_NE(
      blank_rvh,
      shell()->web_contents()->GetPrimaryMainFrame()->GetRenderViewHost());
  EXPECT_NE(blank_site_instance,
            shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());
  rvh_observers.EnsureRVHGetsDestructed(
      shell()->web_contents()->GetPrimaryMainFrame()->GetRenderViewHost());

  // Load a random page and then navigate to view-source: of it.
  // This used to cause two RVH instances for the same SiteInstance, which
  // was a problem.  This is no longer the case.
  EXPECT_TRUE(NavigateToURL(shell(), navigated_url));
  SiteInstance* site_instance1 =
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  rvh_observers.EnsureRVHGetsDestructed(
      shell()->web_contents()->GetPrimaryMainFrame()->GetRenderViewHost());

  EXPECT_TRUE(NavigateToURL(shell(), view_source_url));
  rvh_observers.EnsureRVHGetsDestructed(
      shell()->web_contents()->GetPrimaryMainFrame()->GetRenderViewHost());
  SiteInstance* site_instance2 =
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();

  // Ensure that view-source navigations force a new SiteInstance.
  EXPECT_NE(site_instance1, site_instance2);

  // Now navigate to a different instance so that we swap out again.
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("foo.com", "/title2.html")));
  rvh_observers.EnsureRVHGetsDestructed(
      shell()->web_contents()->GetPrimaryMainFrame()->GetRenderViewHost());

  // This used to leak a render view host.
  shell()->Close();

  RunAllPendingInMessageLoop();  // Needed on ChromeOS.

  EXPECT_EQ(0U, rvh_observers.GetNumberOfWatchedRenderViewHosts());
}

// Test for crbug.com/143155.  Frame tree updates during unload should not
// interrupt the intended navigation.
// Specifically:
// 1) Open 2 tabs in an HTTP SiteInstance, with a subframe in the opener.
// 2) Send the second tab to a different foo.com SiteInstance.
//    This created an opener proxy for the first tab in the foo process.
// 3) Navigate the first tab to the foo.com SiteInstance, and have the first
//    tab's unload handler remove its frame.
// In older versions of Chrome, this caused an update to the frame tree that
// resulted in showing an internal page rather than the real page.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       DontPreemptNavigationWithFrameTreeUpdate) {
  StartEmbeddedServer();

  if (IsIsolatedOriginRequiredToGuaranteeDedicatedProcess()) {
    // Isolate "foo.com" so we are guaranteed to get a non-default
    // SiteInstance for navigations to this origin.
    IsolateOriginsForTesting(embedded_test_server(), shell()->web_contents(),
                             {"foo.com"});
  }

  // 1. Load a page that deletes its iframe during unload.
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("/remove_frame_on_unload.html")));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      shell()->web_contents()->GetSiteInstance());

  // Open a same-site page in a new window.
  ShellAddedObserver new_shell_observer;
  EXPECT_EQ(true, EvalJs(shell(), "openWindow();"));
  Shell* new_shell = new_shell_observer.GetShell();

  // Wait for the navigation in the new window to finish, if it hasn't.
  EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));
  EXPECT_EQ("/title1.html",
            new_shell->web_contents()->GetLastCommittedURL().path());

  // Should have the same SiteInstance.
  EXPECT_EQ(orig_site_instance.get(),
            new_shell->web_contents()->GetSiteInstance());

  // 2. Send the second tab to a different process.
  GURL cross_site_url(
      embedded_test_server()->GetURL("foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, cross_site_url));
  scoped_refptr<SiteInstance> new_site_instance(
      new_shell->web_contents()->GetSiteInstance());
  EXPECT_NE(orig_site_instance, new_site_instance);

  // 3. Send the first tab to the second tab's process.
  EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(shell(), cross_site_url));

  // Make sure it ends up at the right page.
  EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
  EXPECT_EQ(cross_site_url, shell()->web_contents()->GetLastCommittedURL());
  EXPECT_EQ(new_site_instance, shell()->web_contents()->GetSiteInstance());
}

// Ensure that renderer-side debug URLs do not cause a process swap, since they
// are meant to run in the current page.  We had a bug where we expected a
// BrowsingInstance swap to occur on pages like view-source and extensions,
// which broke chrome://crash and javascript: URLs.
// See http://crbug.com/335503.
// The test fails on Mac OSX with ASAN.
// See http://crbug.com/699062.
#if BUILDFLAG(IS_MAC) && defined(THREAD_SANITIZER)
#define MAYBE_RendererDebugURLsDontSwap DISABLED_RendererDebugURLsDontSwap
#else
#define MAYBE_RendererDebugURLsDontSwap RendererDebugURLsDontSwap
#endif
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       MAYBE_RendererDebugURLsDontSwap) {
  StartEmbeddedServer();

  GURL original_url(embedded_test_server()->GetURL("/title2.html"));
  GURL view_source_url(kViewSourceScheme + std::string(":") +
                       original_url.spec());

  EXPECT_TRUE(NavigateToURL(shell(), view_source_url));

  // Check that javascript: URLs work.
  std::u16string expected_title = u"msg";
  TitleWatcher title_watcher(shell()->web_contents(), expected_title);
  shell()->LoadURL(GURL("javascript:document.title='msg'"));
  ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle());

  scoped_refptr<SiteInstance> orig_site_instance(
      shell()->web_contents()->GetSiteInstance());
  // Crash the renderer of the view-source page.
  RenderProcessHostWatcher crash_observer(
      shell()->web_contents(),
      RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
  EXPECT_TRUE(
      NavigateToURLAndExpectNoCommit(shell(), GURL(blink::kChromeUICrashURL)));
  crash_observer.Wait();

  // We should not change SiteInstance and BrowsingInstance on navigations to
  // RendererDebug URLs.
  auto* new_site_instance = shell()->web_contents()->GetSiteInstance();
  EXPECT_EQ(orig_site_instance, new_site_instance);
  EXPECT_TRUE(orig_site_instance->IsRelatedSiteInstance(new_site_instance));
}

// Ensure that renderer-side debug URLs don't take effect on crashed renderers.
// Otherwise, we might try to load an unprivileged about:blank page into a
// WebUI-enabled RenderProcessHost, failing a safety check in InitRenderView.
// See http://crbug.com/334214.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       IgnoreRendererDebugURLsWhenCrashed) {
  // Visit a WebUI page with bindings.
  GURL webui_url = GURL(std::string(kChromeUIScheme) + "://" +
                        std::string(kChromeUIGpuHost));
  EXPECT_TRUE(NavigateToURL(shell(), webui_url));
  EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID()));

  // Crash the renderer of the WebUI page.
  RenderProcessHostWatcher crash_observer(
      shell()->web_contents(),
      RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
  EXPECT_TRUE(
      NavigateToURLAndExpectNoCommit(shell(), GURL(blink::kChromeUICrashURL)));
  crash_observer.Wait();

  // Load the crash URL again but don't wait for any action.  If it is not
  // ignored this time, we will fail the WebUI CHECK in InitRenderView.
  shell()->LoadURL(GURL(blink::kChromeUICrashURL));

  // Ensure that such URLs can still work as the initial navigation of a tab.
  // We postpone the initial navigation of the tab using an empty GURL, so that
  // we can add a watcher for crashes.
  Shell* shell2 =
      Shell::CreateNewWindow(shell()->web_contents()->GetBrowserContext(),
                             GURL(), nullptr, gfx::Size());
  RenderProcessHostWatcher crash_observer2(
      shell2->web_contents(), RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
  EXPECT_TRUE(
      NavigateToURLAndExpectNoCommit(shell2, GURL(blink::kChromeUIKillURL)));
  crash_observer2.Wait();
}

class RFHMProcessPerTabTest : public RenderFrameHostManagerTest {
 public:
  RFHMProcessPerTabTest() = default;

  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(switches::kProcessPerTab);
  }
};

// Test that we still swap processes for BrowsingInstance changes even in
// --process-per-tab mode.  See http://crbug.com/343017.
// Disabled on Android: http://crbug.com/345873.
// Crashes under ThreadSanitizer, http://crbug.com/356758.
#if BUILDFLAG(IS_ANDROID) || defined(THREAD_SANITIZER)
#define MAYBE_BackFromWebUI DISABLED_BackFromWebUI
#else
#define MAYBE_BackFromWebUI BackFromWebUI
#endif
IN_PROC_BROWSER_TEST_P(RFHMProcessPerTabTest, MAYBE_BackFromWebUI) {
  StartEmbeddedServer();
  GURL original_url(embedded_test_server()->GetURL("/title2.html"));
  EXPECT_TRUE(NavigateToURL(shell(), original_url));

  // Visit a WebUI page with bindings.
  GURL webui_url(GURL(std::string(kChromeUIScheme) + "://" +
                      std::string(kChromeUIGpuHost)));
  EXPECT_TRUE(NavigateToURL(shell(), webui_url));
  EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID()));

  // Go back and ensure we have no WebUI bindings.
  TestNavigationObserver back_nav_load_observer(shell()->web_contents());
  shell()->web_contents()->GetController().GoBack();
  back_nav_load_observer.Wait();
  EXPECT_EQ(original_url, shell()->web_contents()->GetLastCommittedURL());
  EXPECT_FALSE(ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID()));
}

// crbug.com/424526
// The test loads a WebUI page in process-per-tab mode, then navigates to a
// blank page and then to a regular page. The bug reproduces if blank page is
// visited in between WebUI and regular page.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       ForceSwapAfterWebUIBindings) {
  base::CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kProcessPerTab);
  StartEmbeddedServer();

  const GURL web_ui_url(std::string(kChromeUIScheme) + "://" +
                        std::string(kChromeUIGpuHost));
  EXPECT_TRUE(NavigateToURL(shell(), web_ui_url));
  EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID()));

  // Capture the SiteInstance before navigating to about:blank to ensure
  // it doesn't change.
  scoped_refptr<SiteInstance> orig_site_instance(
      shell()->web_contents()->GetSiteInstance());

  EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL)));
  EXPECT_NE(orig_site_instance, shell()->web_contents()->GetSiteInstance());

  GURL regular_page_url(embedded_test_server()->GetURL("/title2.html"));
  EXPECT_TRUE(NavigateToURL(shell(), regular_page_url));
  EXPECT_FALSE(ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID()));
}

// crbug.com/615274
// This test ensures that after an RFH is unloaded, the associated WebUI
// instance is no longer allowed to send JavaScript messages. This is necessary
// because WebUI currently (and unusually) always sends JavaScript messages to
// the current main frame, rather than the RFH that owns the WebUI.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       WebUIJavascriptDisallowedAfterUnload) {
  StartEmbeddedServer();

  const GURL web_ui_url(std::string(kChromeUIScheme) + "://" +
                        std::string(kChromeUIGpuHost));
  EXPECT_TRUE(NavigateToURL(shell(), web_ui_url));

  RenderFrameHostImpl* rfh =
      static_cast<WebContentsImpl*>(shell()->web_contents())
          ->GetPrimaryMainFrame();

  // Set up a slow unload handler to force the RFH to linger in the unloaded
  // but not-yet-deleted state.
  EXPECT_TRUE(ExecJs(rfh, "window.onunload=function(e){ while(1); };\n"));

  WebUIImpl* web_ui = rfh->web_ui();

  EXPECT_TRUE(web_ui->CanCallJavascript());
  auto handler_owner = std::make_unique<TestWebUIMessageHandler>();
  TestWebUIMessageHandler* handler = handler_owner.get();

  web_ui->AddMessageHandler(std::move(handler_owner));
  EXPECT_FALSE(handler->IsJavascriptAllowed());

  handler->AllowJavascript();
  EXPECT_TRUE(handler->IsJavascriptAllowed());

  rfh->DisableUnloadTimerForTesting();
  RenderFrameHostDestructionObserver rfh_observer(rfh);

  // Navigate, but wait for commit, not the actual load to finish.
  SiteInstanceImpl* web_ui_site_instance = rfh->GetSiteInstance();
  FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
                            ->GetPrimaryFrameTree()
                            .root();
  TestFrameNavigationObserver commit_observer(root);
  shell()->LoadURL(GURL(url::kAboutBlankURL));
  commit_observer.WaitForCommit();
  EXPECT_NE(web_ui_site_instance, shell()->web_contents()->GetSiteInstance());
  EXPECT_TRUE(root->current_frame_host()
                  ->browsing_context_state()
                  ->GetRenderFrameProxyHost(web_ui_site_instance->group()));

  // The previous RFH should still be pending deletion, as we wait for either
  // the mojo::AgentSchedulingGroupHost::DidUnloadRenderFrame or a timeout.
  ASSERT_TRUE(rfh->IsRenderFrameLive());
  ASSERT_TRUE(rfh->IsPendingDeletion());

  // We specifically want verify behavior between unload and RFH destruction.
  ASSERT_FALSE(rfh_observer.deleted());

  EXPECT_FALSE(handler->IsJavascriptAllowed());
}

// Test for http://crbug.com/703303.  Ensures that the renderer process does not
// try to select files whose paths cannot be converted to WebStrings.  This
// check is done in the renderer because it is hard to predict which paths will
// turn into empty WebStrings, and the behavior varies by platform.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest, DontSelectInvalidFiles) {
  StartServer();
  base::RunLoop run_loop;

  // Use a file path with an invalid encoding, such that it can't be converted
  // to a WebString (on all platforms but Windows).
  base::FilePath file;
  EXPECT_TRUE(base::PathService::Get(base::DIR_TEMP, &file));
  file = file.Append(FILE_PATH_LITERAL("foo\337bar"));

  // Navigate and try to get page to reference this file in its PageState.
  GURL url1(embedded_test_server()->GetURL("/file_input.html"));
  EXPECT_TRUE(NavigateToURL(shell(), url1));
  int process_id =
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
  std::unique_ptr<FileChooserDelegate> delegate(
      new FileChooserDelegate(file, run_loop.QuitClosure()));
  shell()->web_contents()->SetDelegate(delegate.get());
  EXPECT_TRUE(ExecJs(shell(), "document.getElementById('fileinput').click();"));
  run_loop.Run();

  // The browser process grants access to the file whether or not the renderer
  // process realizes that it can't use it.  This is ok, since the user actually
  // did select the file from the chooser.
  EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
      process_id, file));

  // Disable the unload timer so we wait for the UpdateState message.
  static_cast<WebContentsImpl*>(shell()->web_contents())
      ->GetPrimaryMainFrame()
      ->DisableUnloadTimerForTesting();

  // Navigate to a different process and wait for the old process to exit.
  RenderProcessHostWatcher exit_observer(
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess(),
      RenderProcessHostWatcher::WATCH_FOR_HOST_DESTRUCTION);

  // With BackForwardCache, old process won't get deleted on navigation as it is
  // still in use by the bfcached document, disable back-forward cache to ensure
  // that the process gets deleted.
  DisableBackForwardCache(BackForwardCacheImpl::TEST_REQUIRES_NO_CACHING);

  EXPECT_TRUE(NavigateToURL(shell(), GetCrossSiteURL("/title1.html")));
  exit_observer.Wait();
  EXPECT_FALSE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(),
      file));

  // The renderer process should not have been killed.  This is the important
  // part of the test.  If this fails, then we didn't get a PageState to check
  // below, so use an assert (since the test can't meaningfully proceed).
  ASSERT_TRUE(exit_observer.did_exit_normally());

  // Ensure that the file did not end up in the PageState of the previous entry,
  // except on Windows where the path is valid and WebString can handle it.
  NavigationEntry* prev_entry =
      shell()->web_contents()->GetController().GetEntryAtIndex(0);
  EXPECT_EQ(url1, prev_entry->GetURL());
  const std::vector<base::FilePath>& files =
      prev_entry->GetPageState().GetReferencedFiles();
#if BUILDFLAG(IS_WIN)
  EXPECT_EQ(1U, files.size());
#else
  EXPECT_EQ(0U, files.size());
#endif
}

// Test for http://crbug.com/262948.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       RestoreFileAccessForHistoryNavigation) {
  StartServer();
  base::RunLoop run_loop;
  base::FilePath file;
  EXPECT_TRUE(base::PathService::Get(base::DIR_TEMP, &file));
  file = file.AppendASCII("bar");

  WebContentsImpl* wc = static_cast<WebContentsImpl*>(shell()->web_contents());

  // Navigate to url and get it to reference a file in its PageState.
  GURL url1(embedded_test_server()->GetURL("/file_input.html"));
  EXPECT_TRUE(NavigateToURL(shell(), url1));
  int process_id = wc->GetPrimaryMainFrame()->GetProcess()->GetID();
  std::unique_ptr<FileChooserDelegate> delegate(
      new FileChooserDelegate(file, run_loop.QuitClosure()));
  wc->SetDelegate(delegate.get());
  EXPECT_TRUE(ExecJs(shell(), "document.getElementById('fileinput').click();"));
  run_loop.Run();
  EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
      process_id, file));

  // Disable the unload timer so we wait for the UpdateState message.
  wc->GetPrimaryMainFrame()->DisableUnloadTimerForTesting();

  // Navigate to a different process without access to the file, and wait for
  // the old process to exit.
  RenderProcessHostWatcher exit_observer(
      wc->GetPrimaryMainFrame()->GetProcess(),
      RenderProcessHostWatcher::WATCH_FOR_HOST_DESTRUCTION);

  // With BackForwardCache, old process won't get deleted on navigation as it is
  // still in use by the bfcached document, disable back-forward cache to ensure
  // that the process gets deleted.
  DisableBackForwardCache(BackForwardCacheImpl::TEST_REQUIRES_NO_CACHING);

  EXPECT_TRUE(NavigateToURL(shell(), GetCrossSiteURL("/title1.html")));
  exit_observer.Wait();
  EXPECT_FALSE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
      wc->GetPrimaryMainFrame()->GetProcess()->GetID(), file));

  // Ensure that the file ended up in the PageState of the previous entry.
  NavigationEntry* prev_entry = wc->GetController().GetEntryAtIndex(0);
  EXPECT_EQ(url1, prev_entry->GetURL());
  const std::vector<base::FilePath>& files =
      prev_entry->GetPageState().GetReferencedFiles();
  ASSERT_EQ(1U, files.size());
  EXPECT_EQ(file, files.at(0));

  // Go back, ending up in a different RenderProcessHost than before.
  TestNavigationObserver back_nav_load_observer(wc);
  wc->GetController().GoBack();
  back_nav_load_observer.Wait();
  EXPECT_NE(process_id, wc->GetPrimaryMainFrame()->GetProcess()->GetID());

  // Ensure that the file access still exists in the new process ID.
  EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
      wc->GetPrimaryMainFrame()->GetProcess()->GetID(), file));

  // Navigate to a same site page to trigger a PageState update and ensure the
  // renderer is not killed.
  EXPECT_TRUE(
      NavigateToURL(shell(), embedded_test_server()->GetURL("/title2.html")));
}

// Same as RenderFrameHostManagerTest.RestoreFileAccessForHistoryNavigation, but
// replace the cross-origin navigation by a crash, followed by a reload.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       RestoreFileAccessForHistoryNavigationAfterCrash) {
  StartServer();
  base::RunLoop run_loop;
  base::FilePath file;
  EXPECT_TRUE(base::PathService::Get(base::DIR_TEMP, &file));
  file = file.AppendASCII("bar");

  WebContentsImpl* wc = static_cast<WebContentsImpl*>(shell()->web_contents());

  // Navigate to url and get it to reference a file in its PageState.
  GURL url1(embedded_test_server()->GetURL("/file_input.html"));
  EXPECT_TRUE(NavigateToURL(shell(), url1));
  int process_id = wc->GetPrimaryMainFrame()->GetProcess()->GetID();
  std::unique_ptr<FileChooserDelegate> delegate(
      new FileChooserDelegate(file, run_loop.QuitClosure()));
  wc->SetDelegate(delegate.get());
  EXPECT_FALSE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
      process_id, file));
  EXPECT_TRUE(ExecJs(shell(), "document.getElementById('fileinput').click();"));
  run_loop.Run();
  EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
      process_id, file));

  // The PageState hasn't been updated yet. It requires a navigation.
  {
    NavigationEntry* prev_entry = wc->GetController().GetEntryAtIndex(0);
    EXPECT_EQ(url1, prev_entry->GetURL());
    const std::vector<base::FilePath>& files =
        prev_entry->GetPageState().GetReferencedFiles();
    ASSERT_EQ(0U, files.size());
  }

  // Same-document navigation
  EXPECT_TRUE(ExecJs(shell(), "history.pushState({},'title','#foo')"));

  // The PageState has been updated, it now contains the file.
  {
    NavigationEntry* prev_entry = wc->GetController().GetEntryAtIndex(0);
    EXPECT_EQ(url1, prev_entry->GetURL());
    const std::vector<base::FilePath>& files =
        prev_entry->GetPageState().GetReferencedFiles();
    ASSERT_EQ(1U, files.size());
    EXPECT_EQ(file, files.at(0));
  }

  // Crash.
  {
    RenderProcessHost* process = wc->GetPrimaryMainFrame()->GetProcess();
    RenderProcessHostWatcher crash_observer(
        process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
    process->Shutdown(0);
    crash_observer.Wait();
  }

  // The renderer process is still allowed to read the file, even if it is
  // crashed.
  EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
      wc->GetPrimaryMainFrame()->GetProcess()->GetID(), file));

  // Reload
  wc->GetController().Reload(ReloadType::NORMAL, false);
  EXPECT_TRUE(WaitForLoadStop(wc));

  // After recovering from the crash, the renderer process is allowed to read
  // the file.
  EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
      wc->GetPrimaryMainFrame()->GetProcess()->GetID(), file));

  // Same-document history back navigation.
  {
    TestNavigationObserver back_nav_load_observer(wc);
    wc->GetController().GoBack();
    back_nav_load_observer.Wait();
  }

  // Ensure that the file access still exists in the new process ID.
  EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
      wc->GetPrimaryMainFrame()->GetProcess()->GetID(), file));

  // Navigate to a same site page to trigger a PageState update and ensure the
  // renderer is not killed.
  EXPECT_TRUE(
      NavigateToURL(shell(), embedded_test_server()->GetURL("/title2.html")));
}

// Test for http://crbug.com/441966.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       RestoreSubframeFileAccessForHistoryNavigation) {
  StartServer();
  base::RunLoop run_loop;
  base::FilePath file;
  EXPECT_TRUE(base::PathService::Get(base::DIR_TEMP, &file));
  file = file.AppendASCII("bar");

  // Navigate to url and get it to reference a file in its PageState.
  GURL url1(embedded_test_server()->GetURL("/file_input_subframe.html"));
  EXPECT_TRUE(NavigateToURL(shell(), url1));
  WebContentsImpl* wc = static_cast<WebContentsImpl*>(shell()->web_contents());
  FrameTreeNode* root = wc->GetPrimaryFrameTree().root();
  int process_id =
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
  std::unique_ptr<FileChooserDelegate> delegate(
      new FileChooserDelegate(file, run_loop.QuitClosure()));
  shell()->web_contents()->SetDelegate(delegate.get());
  EXPECT_TRUE(ExecJs(root->child_at(0),
                     "document.getElementById('fileinput').click();"));
  run_loop.Run();
  EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
      process_id, file));

  // Disable the unload timer so we wait for the UpdateState message.
  root->current_frame_host()->DisableUnloadTimerForTesting();

  // Do an in-page navigation in the child to make sure we hear a PageState with
  // the chosen file before the subframe's FrameTreeNode is deleted.  In
  // practice, we'll get the PageState 1 second after the file is chosen.
  // TODO(creis): Remove this in-page navigation once we keep track of
  // FrameTreeNodes that are pending deletion.  See https://crbug.com/609963.
  {
    TestNavigationObserver nav_observer(shell()->web_contents());
    std::string script = "location.href='#foo';";
    EXPECT_TRUE(ExecJs(root->child_at(0), script));
    nav_observer.Wait();
  }

  // Navigate to a different process without access to the file, and wait for
  // the old process to exit.
  RenderProcessHostWatcher exit_observer(
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess(),
      RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);

  // With BackForwardCache, old process won't get deleted on navigation as it is
  // still in use by the bfcached document, disable back-forward cache to ensure
  // that the process gets deleted.
  DisableBackForwardCache(BackForwardCacheImpl::TEST_REQUIRES_NO_CACHING);

  EXPECT_TRUE(NavigateToURL(shell(), GetCrossSiteURL("/title1.html")));
  exit_observer.Wait();
  EXPECT_FALSE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(),
      file));

  // Ensure that the file ended up in the PageState of the previous entry.
  NavigationEntry* prev_entry =
      shell()->web_contents()->GetController().GetEntryAtIndex(0);
  EXPECT_EQ(url1, prev_entry->GetURL());
  const std::vector<base::FilePath>& files =
      prev_entry->GetPageState().GetReferencedFiles();
  ASSERT_EQ(1U, files.size());
  EXPECT_EQ(file, files.at(0));

  // Go back, ending up in a different RenderProcessHost than before.
  TestNavigationObserver back_nav_load_observer(shell()->web_contents());
  shell()->web_contents()->GetController().GoToIndex(0);
  back_nav_load_observer.Wait();
  EXPECT_NE(
      process_id,
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID());

  // Ensure that the file access still exists in the new process ID.
  EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(),
      file));

  // Do another in-page navigation in the child to make sure we hear a PageState
  // with the chosen file.
  // TODO(creis): Remove this in-page navigation once we keep track of
  // FrameTreeNodes that are pending deletion.  See https://crbug.com/609963.
  {
    TestNavigationObserver nav_observer(shell()->web_contents());
    std::string script = "location.href='#foo';";
    EXPECT_TRUE(ExecJs(root->child_at(0), script));
    nav_observer.Wait();
  }

  // Also try cloning the tab by creating a new NavigationEntry with the same
  // PageState.  This exercises a different path, by combining the frame
  // specific PageStates into a full-tree PageState and converting back.  There
  // was a bug where this caused us to lose the list of referenced files.  See
  // https://crbug.com/620261.
  std::unique_ptr<NavigationEntryImpl> cloned_entry =
      NavigationEntryImpl::FromNavigationEntry(
          NavigationController::CreateNavigationEntry(
              url1, Referrer(), /* initiator_origin= */ std::nullopt,
              /* initiator_base_url= */ std::nullopt,
              ui::PAGE_TRANSITION_RELOAD, false, std::string(),
              shell()->web_contents()->GetBrowserContext(),
              nullptr /* blob_url_loader_factory */));
  prev_entry = shell()->web_contents()->GetController().GetEntryAtIndex(0);

  NavigationEntryRestoreContextImpl context;
  cloned_entry->SetPageState(prev_entry->GetPageState(), &context);
  const std::vector<base::FilePath>& cloned_files =
      cloned_entry->GetPageState().GetReferencedFiles();
  ASSERT_EQ(1U, cloned_files.size());
  EXPECT_EQ(file, cloned_files.at(0));

  std::vector<std::unique_ptr<NavigationEntry>> entries;
  entries.push_back(std::move(cloned_entry));
  Shell* new_shell =
      Shell::CreateNewWindow(shell()->web_contents()->GetBrowserContext(),
                             GURL(), nullptr, gfx::Size());
  FrameTreeNode* new_root =
      static_cast<WebContentsImpl*>(new_shell->web_contents())
          ->GetPrimaryFrameTree()
          .root();
  NavigationControllerImpl& new_controller =
      static_cast<NavigationControllerImpl&>(
          new_shell->web_contents()->GetController());
  new_controller.Restore(entries.size() - 1, RestoreType::kRestored, &entries);
  ASSERT_EQ(0u, entries.size());
  {
    TestNavigationObserver restore_observer(new_shell->web_contents());
    new_controller.LoadIfNecessary();
    restore_observer.Wait();
  }
  ASSERT_EQ(1U, new_root->child_count());
  EXPECT_EQ(url1, new_root->current_url());

  // Ensure that the file access exists in the new process ID.
  EXPECT_TRUE(ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile(
      new_root->current_frame_host()->GetProcess()->GetID(), file));

  // Also, extract the file from the renderer process to ensure that the
  // response made it over successfully and the proper filename is set.
  EXPECT_EQ("bar",
            EvalJs(new_root->child_at(0),
                   "document.getElementById('fileinput').files[0].name;"));

  // Navigate to a same site page to trigger a PageState update and ensure the
  // renderer is not killed.
  EXPECT_TRUE(
      NavigateToURL(new_shell, embedded_test_server()->GetURL("/title2.html")));
}

// Ensures that no RenderFrameHost/RenderViewHost objects are leaked when
// doing a simple cross-process navigation.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       CleanupOnCrossProcessNavigation) {
  StartEmbeddedServer();

  // Do an initial navigation and capture objects we expect to be cleaned up
  // on cross-process navigation.
  GURL start_url = embedded_test_server()->GetURL("/title1.html");
  EXPECT_TRUE(NavigateToURL(shell(), start_url));

  FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
                            ->GetPrimaryFrameTree()
                            .root();
  auto orig_site_instance_id =
      root->current_frame_host()->GetSiteInstance()->GetId();
  int initial_process_id =
      root->current_frame_host()->GetSiteInstance()->GetProcess()->GetID();
  int initial_rfh_id = root->current_frame_host()->GetRoutingID();
  int initial_rvh_id =
      root->current_frame_host()->render_view_host()->GetRoutingID();

  // Navigate cross-process and ensure that cleanup is performed as expected.
  GURL cross_site_url =
      embedded_test_server()->GetURL("foo.com", "/title2.html");
  RenderFrameHostDestructionObserver rfh_observer(root->current_frame_host());

  // The old RenderFrameHost might have entered the BackForwardCache. Disable
  // back-forward cache to ensure that the RenderFrameHost gets deleted.
  DisableBackForwardCache(BackForwardCacheImpl::TEST_REQUIRES_NO_CACHING);

  EXPECT_TRUE(NavigateToURL(shell(), cross_site_url));
  rfh_observer.Wait();

  EXPECT_NE(orig_site_instance_id,
            root->current_frame_host()->GetSiteInstance()->GetId());
  EXPECT_FALSE(RenderFrameHost::FromID(initial_process_id, initial_rfh_id));
  EXPECT_FALSE(RenderViewHost::FromID(initial_process_id, initial_rvh_id));
}

// Ensure that the opener chain proxies and RVHs are properly reinitialized if
// a tab crashes and reloads.  See https://crbug.com/505090.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       ReinitializeOpenerChainAfterCrashAndReload) {
  StartEmbeddedServer();

  if (IsIsolatedOriginRequiredToGuaranteeDedicatedProcess()) {
    // Isolate "foo.com" so we are guaranteed to get a non-default
    // SiteInstance for navigations to this origin.
    IsolateOriginsForTesting(embedded_test_server(), shell()->web_contents(),
                             {"foo.com"});
  }

  GURL main_url = embedded_test_server()->GetURL("/title1.html");
  EXPECT_TRUE(NavigateToURL(shell(), main_url));

  FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
                            ->GetPrimaryFrameTree()
                            .root();

  scoped_refptr<SiteInstance> orig_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance);

  // Open a popup and navigate it cross-site.
  Shell* new_shell = OpenPopup(shell(), GURL(url::kAboutBlankURL), "foo");
  EXPECT_TRUE(new_shell);
  FrameTreeNode* popup_root =
      static_cast<WebContentsImpl*>(new_shell->web_contents())
          ->GetPrimaryFrameTree()
          .root();

  GURL cross_site_url =
      embedded_test_server()->GetURL("foo.com", "/title2.html");
  EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(new_shell, cross_site_url));

  scoped_refptr<SiteInstance> foo_site_instance(
      new_shell->web_contents()->GetSiteInstance());
  EXPECT_NE(foo_site_instance, orig_site_instance);

  // Kill the popup's process.
  RenderProcessHost* popup_process =
      popup_root->current_frame_host()->GetProcess();
  RenderProcessHostWatcher crash_observer(
      popup_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
  popup_process->Shutdown(0);
  crash_observer.Wait();
  EXPECT_FALSE(popup_root->current_frame_host()->IsRenderFrameLive());
  EXPECT_FALSE(
      popup_root->current_frame_host()->render_view_host()->IsRenderViewLive());

  // The proxy and RVH for the opener page in the foo.com SiteInstanceGroup
  // should not be live.
  RenderFrameHostManager* opener_manager = root->render_manager();
  RenderFrameProxyHost* opener_rfph =
      opener_manager->current_frame_host()
          ->browsing_context_state()
          ->GetRenderFrameProxyHost(
              static_cast<SiteInstanceImpl*>(foo_site_instance.get())->group());
  EXPECT_TRUE(opener_rfph);
  EXPECT_FALSE(opener_rfph->is_render_frame_proxy_live());
  RenderViewHostImpl* opener_rvh = opener_rfph->GetRenderViewHost();
  EXPECT_TRUE(opener_rvh);
  EXPECT_FALSE(opener_rvh->IsRenderViewLive());

  // Re-navigate the popup to the same URL and check that this recreates the
  // opener's RVH and proxy in the foo.com SiteInstanceGroup.
  EXPECT_TRUE(NavigateToURL(new_shell, cross_site_url));
  EXPECT_TRUE(opener_rvh->IsRenderViewLive());
  EXPECT_TRUE(opener_rfph->is_render_frame_proxy_live());
}

// Test that when a frame's opener is updated via window.open, the browser
// process and the frame's proxies in other processes find out about the new
// opener.  Open two popups in different processes, set one popup's opener to
// the other popup, and ensure that the opener is updated in all processes.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest, UpdateOpener) {
  StartEmbeddedServer();
  if (IsIsolatedOriginRequiredToGuaranteeDedicatedProcess()) {
    // Isolate "foo.com" so we are guaranteed it is placed in a different
    // process.
    IsolateOriginsForTesting(embedded_test_server(), shell()->web_contents(),
                             {"foo.com"});
  }

  GURL main_url = embedded_test_server()->GetURL("/post_message.html");
  EXPECT_TRUE(NavigateToURL(shell(), main_url));

  // It is safe to obtain the root frame tree node here, as it doesn't change.
  FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
                            ->GetPrimaryFrameTree()
                            .root();

  scoped_refptr<SiteInstance> orig_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance);

  // Open a cross-site popup named "foo" and a same-site popup named "bar".
  Shell* foo_shell = OpenPopup(shell(), GURL(url::kAboutBlankURL), "foo");
  EXPECT_TRUE(foo_shell);
  GURL foo_url(embedded_test_server()->GetURL("foo.com", "/post_message.html"));
  EXPECT_TRUE(NavigateToURLInSameBrowsingInstance(foo_shell, foo_url));

  GURL bar_url(embedded_test_server()->GetURL(
      "/frame_tree/page_with_post_message_frames.html"));
  Shell* bar_shell = OpenPopup(shell(), bar_url, "bar");
  EXPECT_TRUE(bar_shell);

  EXPECT_NE(shell()->web_contents()->GetSiteInstance()->GetProcess(),
            foo_shell->web_contents()->GetSiteInstance()->GetProcess());
  EXPECT_EQ(shell()->web_contents()->GetSiteInstance()->GetProcess(),
            bar_shell->web_contents()->GetSiteInstance()->GetProcess());

  // Initially, both popups' openers should point to main window.
  FrameTreeNode* foo_root =
      static_cast<WebContentsImpl*>(foo_shell->web_contents())
          ->GetPrimaryFrameTree()
          .root();
  FrameTreeNode* bar_root =
      static_cast<WebContentsImpl*>(bar_shell->web_contents())
          ->GetPrimaryFrameTree()
          .root();
  EXPECT_EQ(root, foo_root->opener());
  EXPECT_EQ(root, foo_root->first_live_main_frame_in_original_opener_chain());
  EXPECT_EQ(root, bar_root->opener());
  EXPECT_EQ(root, bar_root->first_live_main_frame_in_original_opener_chain());

  // From the bar process, use window.open to update foo's opener to point to
  // bar. This is allowed since bar is same-origin with foo's opener.  Use
  // window.open with an empty URL, which should return a reference to the
  // target frame without navigating it.
  EXPECT_EQ(true, EvalJs(bar_shell, "!!window.open('','foo');"));
  EXPECT_FALSE(foo_shell->web_contents()->IsLoading());
  EXPECT_EQ(foo_url, foo_root->current_url());

  // Check that updated opener propagated to the browser process.
  EXPECT_EQ(bar_root, foo_root->opener());
  EXPECT_EQ(root, foo_root->first_live_main_frame_in_original_opener_chain());

  // Check that foo's opener was updated in foo's process. Send a postMessage
  // to the opener and check that the right window (bar_shell) receives it.
  std::u16string expected_title = u"opener-msg";
  TitleWatcher title_watcher(bar_shell->web_contents(), expected_title);
  EXPECT_EQ(true, EvalJs(foo_shell, "postToOpener('opener-msg', '*');"));
  EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());

  // Check that a non-null assignment to the opener doesn't change the opener
  // in the browser process.
  EXPECT_TRUE(ExecJs(foo_shell, "window.opener = window;"));
  EXPECT_EQ(bar_root, foo_root->opener());
  EXPECT_EQ(root, foo_root->first_live_main_frame_in_original_opener_chain());
}

// Tests that when a popup is opened, which is then navigated cross-process and
// back, it can be still accessed through the original window reference in
// JavaScript. See https://crbug.com/537657
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       PopupKeepsWindowReferenceCrossProcesAndBack) {
  StartEmbeddedServer();

  // Load a page with links that open in a new window.
  NavigateToPageWithLinks(shell());

  // Click a target=foo link to open a popup.
  ShellAddedObserver new_shell_observer;
  EXPECT_EQ(true, EvalJs(shell(), "clickSameSiteTargetedLink();"));
  Shell* new_shell = new_shell_observer.GetShell();
  EXPECT_TRUE(new_shell->web_contents()->HasOpener());

  // Wait for the navigation in the popup to finish, if it hasn't.
  EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));
  EXPECT_EQ("/navigate_opener.html",
            new_shell->web_contents()->GetLastCommittedURL().path());

  // Capture the window reference, so we can check that accessing its location
  // works after navigating cross-process and back.
  GURL expected_url = new_shell->web_contents()->GetLastCommittedURL();
  EXPECT_TRUE(ExecJs(shell(), "saveWindowReference();"));

  // Now navigate the popup to a different site and then go back.
  EXPECT_TRUE(NavigateToURL(
      new_shell, embedded_test_server()->GetURL("foo.com", "/title1.html")));
  TestNavigationObserver back_nav_load_observer(new_shell->web_contents());
  new_shell->web_contents()->GetController().GoBack();
  back_nav_load_observer.Wait();

  // Check that the location.href window attribute is accessible and is correct.
  EXPECT_EQ(expected_url.spec(),
            EvalJs(shell(), "getLastOpenedWindowLocation();"));
}

// Tests that going back to the same SiteInstance as a pending RenderFrameHost
// doesn't create a duplicate RenderFrameProxyHost. For example:
// 1. Navigate to a page on the opener site - a.com
// 2. Navigate to a page on site b.com
// 3. Start a navigation to another page on a.com, but commit is delayed.
// 4. Go back.
// See https://crbug.com/541619.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       PopupPendingAndBackToSameSiteInstance) {
  StartEmbeddedServer();
  GURL main_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
  GURL popup_url(embedded_test_server()->GetURL("a.com", "/title2.html"));
  EXPECT_TRUE(NavigateToURL(shell(), main_url));

  // Open a popup to navigate.
  Shell* new_shell = OpenPopup(shell(), popup_url, "foo");
  EXPECT_EQ(shell()->web_contents()->GetSiteInstance(),
            new_shell->web_contents()->GetSiteInstance());

  // Navigate the popup to a different site.
  EXPECT_TRUE(NavigateToURL(
      new_shell, embedded_test_server()->GetURL("b.com", "/title2.html")));

  // Navigate again to the original site, but to a page that will take a while
  // to commit.
  GURL same_site_url(embedded_test_server()->GetURL("a.com", "/title3.html"));
  TestNavigationManager stalled_navigation(new_shell->web_contents(),
                                           same_site_url);
  new_shell->LoadURL(same_site_url);
  EXPECT_TRUE(stalled_navigation.WaitForRequestStart());

  // Going back in history should work and the test should not crash.
  TestNavigationObserver back_nav_load_observer(new_shell->web_contents());
  new_shell->web_contents()->GetController().GoBack();
  back_nav_load_observer.Wait();
}

// Tests that navigating cross-process and reusing an existing RenderViewHost
// (whose process has been killed/crashed) recreates properly the
// `blink::WebView` and `blink::RemoteFrame` on the renderer side. See
// https://crbug.com/544271
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       RenderViewInitAfterProcessKill) {
  StartEmbeddedServer();
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("a.com", "/title1.html")));

  // Open a popup to navigate.
  Shell* new_shell = OpenPopup(
      shell(), embedded_test_server()->GetURL("a.com", "/title2.html"), "foo");
  FrameTreeNode* popup_root =
      static_cast<WebContentsImpl*>(new_shell->web_contents())
          ->GetPrimaryFrameTree()
          .root();
  EXPECT_EQ(shell()->web_contents()->GetSiteInstance(),
            new_shell->web_contents()->GetSiteInstance());

  // Navigate the popup to a different site.
  EXPECT_TRUE(NavigateToURL(
      new_shell, embedded_test_server()->GetURL("b.com", "/title2.html")));
  EXPECT_NE(shell()->web_contents()->GetSiteInstance(),
            new_shell->web_contents()->GetSiteInstance());

  // Kill the process hosting the popup.
  RenderProcessHost* process = popup_root->current_frame_host()->GetProcess();
  RenderProcessHostWatcher crash_observer(
      process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
  process->Shutdown(0);
  crash_observer.Wait();
  EXPECT_FALSE(popup_root->current_frame_host()->IsRenderFrameLive());
  EXPECT_FALSE(
      popup_root->current_frame_host()->render_view_host()->IsRenderViewLive());

  // Navigate the main tab to the site of the popup. This will cause the
  // `blink::WebView` for b.com in the main tab to be recreated. If the issue
  // is not fixed, this will result in process crash and failing test.
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("b.com", "/title3.html")));
}

// Ensure that we don't crash the renderer in CreateRenderView if a proxy goes
// away between unload and the next navigation.  See https://crbug.com/581912.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       CreateRenderViewAfterProcessKillAndClosedProxy) {
  StartEmbeddedServer();
  FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
                            ->GetPrimaryFrameTree()
                            .root();

  // Give an initial page an unload handler that never completes.
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("a.com", "/title1.html")));
  EXPECT_TRUE(ExecJs(root, "window.onunload=function(e){ while(1); };\n"));

  // Open a popup in the same process.
  Shell* new_shell = OpenPopup(shell(), GURL(url::kAboutBlankURL), "foo");
  FrameTreeNode* popup_root =
      static_cast<WebContentsImpl*>(new_shell->web_contents())
          ->GetPrimaryFrameTree()
          .root();
  EXPECT_EQ(shell()->web_contents()->GetSiteInstance(),
            new_shell->web_contents()->GetSiteInstance());

  // Navigate the first tab to a different site, and only wait for commit, not
  // load stop.
  RenderFrameHostImpl* rfh_a = root->current_frame_host();
  rfh_a->DisableUnloadTimerForTesting();
  scoped_refptr<SiteInstanceImpl> site_instance_a = rfh_a->GetSiteInstance();
  TestFrameNavigationObserver commit_observer(root);
  shell()->LoadURL(embedded_test_server()->GetURL("b.com", "/title2.html"));
  commit_observer.WaitForCommit();
  EXPECT_NE(shell()->web_contents()->GetSiteInstance(),
            new_shell->web_contents()->GetSiteInstance());
  EXPECT_TRUE(root->current_frame_host()
                  ->browsing_context_state()
                  ->GetRenderFrameProxyHost(site_instance_a->group()));

  // The previous RFH should still be pending deletion, as we wait for either
  // the mojo::AgentSchedulingGroupHost::DidUnloadRenderFrame or a timeout.
  ASSERT_TRUE(rfh_a->IsRenderFrameLive());
  ASSERT_TRUE(rfh_a->IsPendingDeletion());

  // The corresponding RVH should still be referenced by the proxy and the old
  // frame.
  RenderViewHostImpl* rvh_a = rfh_a->render_view_host();
  EXPECT_FALSE(rvh_a->HasOneRef());
  EXPECT_TRUE(rvh_a->HasAtLeastOneRef());

  // Kill the old process.
  RenderProcessHost* process = rfh_a->GetProcess();
  RenderProcessHostWatcher crash_observer(
      process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
  process->Shutdown(0);
  crash_observer.Wait();
  EXPECT_FALSE(popup_root->current_frame_host()->IsRenderFrameLive());
  // |rfh_a| is now deleted, thanks to the bug fix.

  // With |rfh_a| gone, the RVH should only be referenced by the (dead) proxy.
  EXPECT_TRUE(rvh_a->HasOneRef());
  EXPECT_TRUE(root->current_frame_host()
                  ->browsing_context_state()
                  ->GetRenderFrameProxyHost(site_instance_a->group()));
  EXPECT_FALSE(root->current_frame_host()
                   ->browsing_context_state()
                   ->GetRenderFrameProxyHost(site_instance_a->group())
                   ->is_render_frame_proxy_live());

  // Close the popup so there is no proxy for a.com in the original tab.
  new_shell->Close();

  // Verify that there are no proxies, meaning there's no proxy for a.com. At
  // this point, |site_instance_group_a| has been freed, so searching the proxy
  // host map using it isn't an option.
  EXPECT_EQ(nullptr, site_instance_a->group());
  EXPECT_EQ(0u, root->current_frame_host()
                    ->browsing_context_state()
                    ->proxy_hosts()
                    .size());

  // This should delete the RVH as well. Check this by verifying that there's
  // only one RVH in the frame tree, and it's for the current SiteInstanceGroup,
  // not |site_instance_group_a|.
  EXPECT_TRUE(root->frame_tree().GetRenderViewHost(
      root->current_frame_host()->GetSiteInstance()->group()));
  EXPECT_EQ(1u, root->frame_tree().render_view_host_map_.size());

  // Go back in the main frame from b.com to a.com. In https://crbug.com/581912,
  // the browser process would crash here because there was no main frame
  // routing ID or proxy in RVHI::CreateRenderView.
  {
    TestNavigationObserver back_nav_load_observer(shell()->web_contents());
    shell()->web_contents()->GetController().GoBack();
    back_nav_load_observer.Wait();
  }
}

// Ensure that we don't crash in RenderViewImpl::Init if a proxy is created
// after unload and before navigation.  See https://crbug.com/544755.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       RenderViewInitAfterNewProxyAndProcessKill) {
  StartEmbeddedServer();
  FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
                            ->GetPrimaryFrameTree()
                            .root();

  // Give an initial page a pagehide handler that never completes.
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("a.com", "/title1.html")));
  EXPECT_TRUE(ExecJs(root, "window.onpagehide=function(e){ while(1); };\n"));

  // With BackForwardCache, swapped out RenderFrameHost won't have a
  // replacement proxy as the document is stored in cache.
  DisableBackForwardCache(BackForwardCacheImpl::TEST_REQUIRES_NO_CACHING);

  // Navigate the tab to a different site, and only wait for commit, not load
  // stop.
  RenderFrameHostImpl* rfh_a = root->current_frame_host();
  rfh_a->DisableUnloadTimerForTesting();
  SiteInstanceImpl* site_instance_a = rfh_a->GetSiteInstance();
  TestFrameNavigationObserver commit_observer(root);
  shell()->LoadURL(embedded_test_server()->GetURL("b.com", "/title2.html"));
  commit_observer.WaitForCommit();
  EXPECT_NE(site_instance_a, shell()->web_contents()->GetSiteInstance());

  // The previous RFH should still be pending deletion, as we wait for either
  // the unload ACK or a timeout.
  ASSERT_TRUE(rfh_a->IsRenderFrameLive());
  ASSERT_TRUE(rfh_a->IsPendingDeletion());

  // When the previous RFH was unloaded, it should have still gotten a
  // replacement proxy even though it's the last active frame in the process.
  EXPECT_TRUE(root->current_frame_host()
                  ->browsing_context_state()
                  ->GetRenderFrameProxyHost(site_instance_a->group()));

  // Open a popup in the new B process.
  Shell* new_shell = OpenPopup(shell(), GURL(url::kAboutBlankURL), "foo");
  EXPECT_EQ(shell()->web_contents()->GetSiteInstance(),
            new_shell->web_contents()->GetSiteInstance());

  // Navigate the popup to the original site, but don't wait for commit (which
  // won't happen).  This should reuse the proxy in the original tab, which at
  // this point exists alongside the RFH pending deletion.
  new_shell->LoadURL(embedded_test_server()->GetURL("a.com", "/title2.html"));
  EXPECT_TRUE(root->current_frame_host()
                  ->browsing_context_state()
                  ->GetRenderFrameProxyHost(site_instance_a->group()));

  // Kill the old process.
  RenderProcessHost* process = rfh_a->GetProcess();
  RenderProcessHostWatcher crash_observer(
      process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
  process->Shutdown(0);
  crash_observer.Wait();
  // |rfh_a| is now deleted, thanks to the bug fix.

  // Go back in the main frame from b.com to a.com.
  {
    TestNavigationObserver back_nav_load_observer(shell()->web_contents());
    shell()->web_contents()->GetController().GoBack();
    back_nav_load_observer.Wait();
  }

  // In https://crbug.com/581912, the renderer process would crash here because
  // there was a frame, view, and proxy (and is_swapped_out was true).
  EXPECT_EQ(site_instance_a, root->current_frame_host()->GetSiteInstance());
  EXPECT_TRUE(root->current_frame_host()->IsRenderFrameLive());
  EXPECT_TRUE(
      new_shell->web_contents()->GetPrimaryMainFrame()->IsRenderFrameLive());
}

// Ensure that we use the same pending RenderFrameHost if a second navigation to
// its site occurs before it commits.  Otherwise the renderer process will have
// two competing pending RenderFrames that both try to swap with the same
// RenderFrameProxy.  See https://crbug.com/545900.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       ConsecutiveNavigationsToSite) {
  StartEmbeddedServer();
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("a.com", "/title1.html")));

  // Open a popup and navigate it to b.com to keep the b.com process alive.
  Shell* new_shell = OpenPopup(shell(), GURL(url::kAboutBlankURL), "popup");
  EXPECT_TRUE(NavigateToURL(
      new_shell, embedded_test_server()->GetURL("b.com", "/title3.html")));

  // Start a cross-site navigation to the same site but don't commit.
  GURL cross_site_url(embedded_test_server()->GetURL("b.com", "/title1.html"));
  TestNavigationManager stalled_navigation(shell()->web_contents(),
                                           cross_site_url);
  shell()->LoadURL(cross_site_url);
  EXPECT_TRUE(stalled_navigation.WaitForResponse());

  WebContentsImpl* web_contents =
      static_cast<WebContentsImpl*>(shell()->web_contents());
  RenderFrameHostImpl* next_rfh = web_contents->GetPrimaryFrameTree()
                                      .root()
                                      ->render_manager()
                                      ->speculative_frame_host();
  ASSERT_TRUE(next_rfh);

  // Navigate to the same new site and verify that we commit in the same RFH.
  GURL cross_site_url2(embedded_test_server()->GetURL("b.com", "/title2.html"));
  TestNavigationObserver navigation_observer(web_contents, 1);
  shell()->LoadURL(cross_site_url2);
  EXPECT_EQ(next_rfh, web_contents->GetPrimaryFrameTree()
                          .root()
                          ->render_manager()
                          ->speculative_frame_host());
  navigation_observer.Wait();
  EXPECT_EQ(cross_site_url2, web_contents->GetLastCommittedURL());
  EXPECT_EQ(next_rfh, web_contents->GetPrimaryMainFrame());
  EXPECT_FALSE(web_contents->GetPrimaryFrameTree()
                   .root()
                   ->render_manager()
                   ->speculative_frame_host());
}

// Check that if a sandboxed subframe opens a cross-process popup such that the
// popup's opener won't be set, the popup still inherits the subframe's sandbox
// flags.  This matters for rel=noopener and rel=noreferrer links, as well as
// for some situations in non-site-per-process mode where the popup would
// normally maintain the opener, but loses it due to being placed in a new
// process and not creating subframe proxies.  The latter might happen when
// opening the default search provider site.  See https://crbug.com/576204.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       CrossProcessPopupInheritsSandboxFlagsWithNoOpener) {
  StartEmbeddedServer();
  FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
                            ->GetPrimaryFrameTree()
                            .root();

  GURL main_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), main_url));

  // Add a sandboxed about:blank iframe.
  {
    std::string script =
        "var frame = document.createElement('iframe');\n"
        "frame.sandbox = 'allow-scripts allow-popups';\n"
        "document.body.appendChild(frame);\n";
    EXPECT_TRUE(ExecJs(shell(), script));
  }

  // Navigate iframe to a page with target=_blank links, and rewrite the links
  // to point to valid cross-site URLs.
  GURL frame_url(
      embedded_test_server()->GetURL("a.com", "/click-noreferrer-links.html"));
  EXPECT_TRUE(NavigateToURLFromRenderer(root->child_at(0), frame_url));
  std::string script = "setOriginForLinks('http://b.com:" +
                       embedded_test_server()->base_url().port() + "/');";
  EXPECT_TRUE(ExecJs(root->child_at(0), script));

  // Helper to click on the 'rel=noreferrer target=_blank' and 'rel=noopener
  // target=_blank' links.  Checks that these links open a popup that ends up
  // in a new SiteInstance even without site-per-process and then verifies that
  // the popup is still sandboxed.
  auto click_link_and_verify_popup = [this,
                                      root](std::string link_opening_script) {
    ShellAddedObserver new_shell_observer;
    EXPECT_EQ(true, EvalJs(root->child_at(0), link_opening_script));

    Shell* new_shell = new_shell_observer.GetShell();
    EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));
    EXPECT_NE(new_shell->web_contents()->GetSiteInstance(),
              shell()->web_contents()->GetSiteInstance());

    // Check that the popup is sandboxed by checking its self.origin, which
    // should be unique.
    EXPECT_EQ("null", EvalJs(new_shell, "self.origin"));
  };

  click_link_and_verify_popup("clickNoOpenerTargetBlankLink()");
  click_link_and_verify_popup("clickNoRefTargetBlankLink()");
}

// When two frames are same-origin but cross-process, they should behave as if
// they are not same-origin and should not crash.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       SameOriginFramesInDifferentProcesses) {
  StartEmbeddedServer();

  // Load a page with links that open in a new window.
  EXPECT_TRUE(NavigateToURL(
      shell(),
      embedded_test_server()->GetURL("a.com", "/click-noreferrer-links.html")));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      shell()->web_contents()->GetSiteInstance());
  EXPECT_NE(nullptr, orig_site_instance.get());

  // Test clicking a target=foo link.
  ShellAddedObserver new_shell_observer;
  EXPECT_EQ(true, EvalJs(shell(),
                         "const result = clickSameSiteTargetedLink();"
                         "saveWindowReference();"
                         "result;"));
  Shell* new_shell = new_shell_observer.GetShell();

  // Wait for the navigation in the new tab to finish, if it hasn't.
  EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));
  EXPECT_EQ("/navigate_opener.html",
            new_shell->web_contents()->GetLastCommittedURL().path());

  // Do a cross-site navigation that winds up same-site. The same-site
  // navigation to a.com will commit in a different process than the original
  // a.com window.
  EXPECT_TRUE(NavigateToURL(
      new_shell,
      embedded_test_server()->GetURL("b.com", "/cross-site/a.com/title1.html"),
      /* expected_commit_url */
      embedded_test_server()->GetURL("a.com", "/title1.html")));
  // The SiteInstance for the navigation is determined after the redirect.
  // So both windows will actually be in the same process.
  EXPECT_EQ(shell()->web_contents()->GetSiteInstance(),
            new_shell->web_contents()->GetSiteInstance());

  std::string result = EvalJs(shell(),
                              "(function() {\n"
                              "  try {\n"
                              "    return getLastOpenedWindowLocation();\n"
                              "  } catch (e) {\n"
                              "    return e.toString();\n"
                              "  }\n"
                              "})()")
                           .ExtractString();
  EXPECT_THAT(result, ::testing::MatchesRegex("http://a.com:\\d+/title1.html"));
}

// Test coverage for attempts to open subframe links in new windows, to prevent
// incorrect invariant checks.  See https://crbug.com/605055.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest, CtrlClickSubframeLink) {
  StartEmbeddedServer();

  // Load a page with a subframe link.
  EXPECT_TRUE(NavigateToURL(shell(), embedded_test_server()->GetURL(
                                         "/ctrl-click-subframe-link.html")));

  // Simulate a ctrl click on the link.  This won't actually create a new Shell
  // because Shell::OpenURLFromTab only supports CURRENT_TAB, but it's enough to
  // trigger the crash from https://crbug.com/605055.
  EXPECT_TRUE(
      ExecJs(shell(), "window.domAutomationController.send(ctrlClickLink());"));
}

// Ensure that we don't update the wrong NavigationEntry's title after an
// ignored commit during a cross-process navigation.
// See https://crbug.com/577449.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       UnloadPushStateOnCrossProcessNavigation) {
  // TODO(sreejakshetty): Replace 'unload' with 'pagehide' and reenable this
  // test for BackForwardCache.
  DisableBackForwardCache(content::BackForwardCache::TEST_USES_UNLOAD_EVENT);

  StartEmbeddedServer();
  WebContentsImpl* web_contents =
      static_cast<WebContentsImpl*>(shell()->web_contents());
  FrameTreeNode* root = web_contents->GetPrimaryFrameTree().root();

  // Give an initial page an unload handler that does a pushState, which will be
  // ignored by the browser process.  It then does a title update which is
  // meant for a NavigationEntry that will never be created.
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("a.com", "/title2.html")));
  EXPECT_TRUE(ExecJs(root,
                     "window.onunload=function(e){"
                     "history.pushState({}, 'foo', 'foo');"
                     "document.title='foo'; };\n"));
  std::u16string title = web_contents->GetTitle();
  NavigationEntryImpl* entry = web_contents->GetController().GetEntryAtIndex(0);

  // Navigate the first tab to a different site and wait for the old process to
  // complete its unload handler and exit.
  RenderFrameHostImpl* rfh_a = root->current_frame_host();
  rfh_a->DisableUnloadTimerForTesting();
  RenderProcessHostWatcher exit_observer(
      rfh_a->GetProcess(), RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
  TestNavigationObserver commit_observer(web_contents);
  shell()->LoadURL(embedded_test_server()->GetURL("b.com", "/title1.html"));
  commit_observer.Wait();
  exit_observer.Wait();

  // Ensure the entry's title hasn't changed after the ignored commit.
  EXPECT_EQ(title, entry->GetTitle());
}

// Ensure that document hosted on file: URL can successfully execute pushState
// with arbitrary origin, when universal access setting is enabled.
// TODO(nasko): The test is disabled on Mac, since universal access from file
// scheme behaves differently.  See also https://crbug.com/981018.
#if BUILDFLAG(IS_MAC)
#define MAYBE_EnsureUniversalAccessFromFileSchemeSucceeds \
  DISABLED_EnsureUniversalAccessFromFileSchemeSucceeds
#else
#define MAYBE_EnsureUniversalAccessFromFileSchemeSucceeds \
  EnsureUniversalAccessFromFileSchemeSucceeds
#endif
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       MAYBE_EnsureUniversalAccessFromFileSchemeSucceeds) {
  StartEmbeddedServer();
  WebContentsImpl* web_contents =
      static_cast<WebContentsImpl*>(shell()->web_contents());
  FrameTreeNode* root = web_contents->GetPrimaryFrameTree().root();

  auto prefs = web_contents->GetOrCreateWebPreferences();
  prefs.allow_universal_access_from_file_urls = true;
  web_contents->SetWebPreferences(prefs);

  GURL file_url = GetTestUrl("", "title1.html");
  ASSERT_TRUE(file_url.SchemeIsFile());
  ASSERT_TRUE(NavigateToURL(shell(), file_url));
  EXPECT_EQ(1, web_contents->GetController().GetEntryCount());
  EXPECT_TRUE(
      ExecJs(root, "history.pushState({}, '', 'https://chromium.org');"));
  ASSERT_TRUE(web_contents->GetPrimaryMainFrame()->IsRenderFrameLive());
  EXPECT_EQ(2, web_contents->GetController().GetEntryCount());

  // At this point, we should still consider the current origin to be file://,
  // so that subsequent web or file URLs would still be legal for same-document
  // navigations.  See https://crbug.com/553418.
  const url::Origin file_origin = url::Origin::Create(file_url);
  EXPECT_TRUE(file_origin.IsSameOriginWith(
      web_contents->GetPrimaryMainFrame()->GetLastCommittedOrigin()));
  EXPECT_TRUE(ExecJs(root, "history.pushState({}, '', 'https://foo.com');"));
  ASSERT_TRUE(web_contents->GetPrimaryMainFrame()->IsRenderFrameLive());
  EXPECT_EQ(3, web_contents->GetController().GetEntryCount());
  EXPECT_TRUE(
      ExecJs(root, JsReplace("history.pushState({}, '', $1);", file_url)));
  ASSERT_TRUE(web_contents->GetPrimaryMainFrame()->IsRenderFrameLive());
  EXPECT_EQ(4, web_contents->GetController().GetEntryCount());

  // Illegal schemes would not normally be allowed to commit by CanCommitURL,
  // but they are granted an exception if allow_universal_access_from_file_urls
  // is in use.
  GURL illegal_url("google:com");
  EXPECT_TRUE(ExecJs(
      root, JsReplace("history.replaceState({}, '', $1);", illegal_url)));
  ASSERT_TRUE(web_contents->GetPrimaryMainFrame()->IsRenderFrameLive());
  EXPECT_EQ(4, web_contents->GetController().GetEntryCount());

  // Illegal schemes should also work for document.open on same-origin frames,
  // where the initiator's URL is inherited (in the renderer process).
  std::string create_frame_and_open_script =
      "var new_iframe = document.createElement('iframe');"
      "document.documentElement.appendChild(new_iframe);"
      "new_iframe.contentDocument.open();";
  EXPECT_TRUE(ExecJs(shell(), create_frame_and_open_script));
  EXPECT_EQ(
      illegal_url,
      root->child_at(0)->current_frame_host()->last_document_url_in_renderer());
  // Ensure the renderer process has not crashed.
  ASSERT_TRUE(ExecJs(shell(), "true"));
  ASSERT_TRUE(root->child_at(0)->current_frame_host()->IsRenderFrameLive());

  // Now disable universal access, while still allowing file URLs to access each
  // other. This generally turns off the exemption from commit-time security
  // checks, while still allowing document.open to work in file:// origins.
  prefs.allow_universal_access_from_file_urls = false;
  prefs.allow_file_access_from_file_urls = true;
  web_contents->SetWebPreferences(prefs);

  // Calling document.open on another iframe should remember that the process
  // already had an exemption for file:// origins and continue to work.
  // See https://crbug.com/326250356#comment26.
  EXPECT_TRUE(ExecJs(shell(), create_frame_and_open_script));
  EXPECT_EQ(
      illegal_url,
      root->child_at(1)->current_frame_host()->last_document_url_in_renderer());
  // Ensure the renderer process has not crashed.
  ASSERT_TRUE(ExecJs(shell(), "true"));
  ASSERT_TRUE(root->child_at(1)->current_frame_host()->IsRenderFrameLive());
}

// Ensure that navigating back from a sad tab to an existing process works
// correctly. See https://crbug.com/591984.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       NavigateBackToExistingProcessFromSadTab) {
  StartEmbeddedServer();
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("a.com", "/title1.html")));

  // Open a popup and navigate it to b.com.
  Shell* popup = OpenPopup(
      shell(), embedded_test_server()->GetURL("a.com", "/title2.html"), "foo");
  EXPECT_TRUE(NavigateToURL(
      popup, embedded_test_server()->GetURL("b.com", "/title3.html")));

  // Kill the b.com process.
  RenderProcessHost* b_process =
      popup->web_contents()->GetPrimaryMainFrame()->GetProcess();
  RenderProcessHostWatcher crash_observer(
      b_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
  b_process->Shutdown(0);
  crash_observer.Wait();

  // The popup should now be showing the sad tab.  Main tab should not be.
  EXPECT_NE(base::TERMINATION_STATUS_STILL_RUNNING,
            popup->web_contents()->GetCrashedStatus());
  EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING,
            shell()->web_contents()->GetCrashedStatus());

  // Go back in the popup from b.com to a.com/title2.html.
  TestNavigationObserver back_observer(popup->web_contents());
  popup->web_contents()->GetController().GoBack();
  back_observer.Wait();

  // In the bug, after the back navigation the popup was still showing
  // the sad tab.  Ensure this is not the case.
  EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING,
            popup->web_contents()->GetCrashedStatus());
  EXPECT_TRUE(
      popup->web_contents()->GetPrimaryMainFrame()->IsRenderFrameLive());
  EXPECT_EQ(popup->web_contents()->GetPrimaryMainFrame()->GetSiteInstance(),
            shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());
}

// Verify that GetLastCommittedOrigin() is correct for the full lifetime of a
// RenderFrameHost, including when it's pending, current, and pending deletion.
// This is checked both for main frames and subframes.
// See https://crbug.com/590035.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest, LastCommittedOrigin) {
  StartEmbeddedServer();

  // Disable the back-forward cache so that documents are always deleted when
  // navigating.
  DisableBackForwardCache(BackForwardCacheImpl::TEST_REQUIRES_NO_CACHING);

  GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), url_a));

  WebContentsImpl* web_contents =
      static_cast<WebContentsImpl*>(shell()->web_contents());
  FrameTreeNode* root = web_contents->GetPrimaryFrameTree().root();
  RenderFrameHostImpl* rfh_a = root->current_frame_host();
  rfh_a->DisableUnloadTimerForTesting();

  EXPECT_EQ(url::Origin::Create(url_a), rfh_a->GetLastCommittedOrigin());
  EXPECT_EQ(rfh_a, web_contents->GetPrimaryMainFrame());

  // Start a navigation to a b.com URL, and don't wait for commit.
  GURL url_b(embedded_test_server()->GetURL("b.com", "/title2.html"));
  TestNavigationManager navigation_manager(web_contents, url_b);
  RenderFrameDeletedObserver deleted_observer(rfh_a);
  shell()->LoadURL(url_b);
  navigation_manager.WaitForSpeculativeRenderFrameHostCreation();

  // The speculative RFH shouln't have a last committed origin (the default
  // value is a unique origin). The current RFH shouldn't change its last
  // committed origin before commit.
  RenderFrameHostImpl* rfh_b = root->render_manager()->speculative_frame_host();
  EXPECT_EQ("null", rfh_b->GetLastCommittedOrigin().Serialize());
  EXPECT_EQ(url::Origin::Create(url_a), rfh_a->GetLastCommittedOrigin());

  // Verify that the last committed origin is set for the b.com RHF once it
  // commits.
  ASSERT_TRUE(navigation_manager.WaitForNavigationFinished());
  EXPECT_EQ(url::Origin::Create(url_b), rfh_b->GetLastCommittedOrigin());
  EXPECT_EQ(rfh_b, web_contents->GetPrimaryMainFrame());

  // The old RFH should now be pending deletion.  Verify it still has correct
  // last committed origin.
  EXPECT_EQ(url::Origin::Create(url_a), rfh_a->GetLastCommittedOrigin());
  EXPECT_TRUE(rfh_a->IsPendingDeletion());

  // Wait for |rfh_a| to be deleted and double-check |rfh_b|'s origin.
  deleted_observer.WaitUntilDeleted();
  EXPECT_EQ(url::Origin::Create(url_b), rfh_b->GetLastCommittedOrigin());

  // Navigate to a same-origin page with an about:blank iframe.  The iframe
  // should also have a b.com origin.
  GURL url_b_with_frame(embedded_test_server()->GetURL(
      "b.com", "/navigation_controller/page_with_iframe.html"));
  EXPECT_TRUE(NavigateToURL(shell(), url_b_with_frame));
  if (ShouldCreateNewHostForAllFrames()) {
    // If main-frame RenderDocument is enabled, the navigation will result in a
    // new RFH.
    EXPECT_NE(rfh_b, web_contents->GetPrimaryMainFrame());
    rfh_b = web_contents->GetPrimaryMainFrame();
  } else {
    EXPECT_EQ(rfh_b, web_contents->GetPrimaryMainFrame());
  }
  EXPECT_EQ(url::Origin::Create(url_b), rfh_b->GetLastCommittedOrigin());
  FrameTreeNode* child = root->child_at(0);
  RenderFrameHostImpl* child_rfh_b = root->child_at(0)->current_frame_host();
  child_rfh_b->DisableUnloadTimerForTesting();
  EXPECT_EQ(url::Origin::Create(url_b), child_rfh_b->GetLastCommittedOrigin());

  // Navigate subframe to c.com.  Wait for commit but not full load, and then
  // verify the subframe's origin.
  GURL url_c(embedded_test_server()->GetURL("c.com", "/title3.html"));
  {
    TestFrameNavigationObserver child_commit_observer(root->child_at(0));
    EXPECT_TRUE(ExecJs(child, "location.href = '" + url_c.spec() + "';"));
    child_commit_observer.WaitForCommit();
  }
  EXPECT_EQ(url::Origin::Create(url_c),
            child->current_frame_host()->GetLastCommittedOrigin());

  // With OOPIFs, this navigation used a cross-process transfer.  Ensure that
  // the iframe's old RFH still has correct origin, even though it's pending
  // deletion.
  if (AreAllSitesIsolatedForTesting()) {
    EXPECT_TRUE(child_rfh_b->IsPendingDeletion());
    EXPECT_NE(child_rfh_b, child->current_frame_host());
    EXPECT_EQ(url::Origin::Create(url_b),
              child_rfh_b->GetLastCommittedOrigin());
  }
}

// Ensure that loading a page with cross-site coreferencing iframes does not
// cause an infinite number of nested iframes to be created.
// See https://crbug.com/650332.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest, CoReferencingFrames) {
  // Load a page with a cross-site coreferencing iframe. "Coreferencing" here
  // refers to two separate pages that contain subframes with URLs to each
  // other.
  StartEmbeddedServer();
  GURL url_1(
      embedded_test_server()->GetURL("a.com", "/coreferencingframe_1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), url_1));

  WebContentsImpl* web_contents =
      static_cast<WebContentsImpl*>(shell()->web_contents());

  FrameTreeNode* root = web_contents->GetPrimaryFrameTree().root();

  // The FrameTree contains two successful instances of each site plus an
  // unsuccessfully-navigated third instance of B with a blank URL.  When not in
  // strict SiteInstance mode, the FrameTreeVisualizer depicts all nodes as
  // referencing Site A because iframes are identified with their root site.
  if (AreStrictSiteInstancesEnabled()) {
    EXPECT_EQ(
        " Site A ------------ proxies for B\n"
        "   +--Site B ------- proxies for A\n"
        "        +--Site A -- proxies for B\n"
        "             +--Site B -- proxies for A\n"
        "                  +--Site B -- proxies for A\n"
        "Where A = http://a.com/\n"
        "      B = http://b.com/",
        DepictFrameTree(*root));
  } else {
    const GURL kExpectedSiteURL = AreDefaultSiteInstancesEnabled()
                                      ? SiteInstanceImpl::GetDefaultSiteURL()
                                      : GURL("http://a.com/");
    EXPECT_EQ(std::string(" Site A\n"
                          "   +--Site A\n"
                          "        +--Site A\n"
                          "             +--Site A\n"
                          "                  +--Site A\n"
                          "Where A = ") +
                  kExpectedSiteURL.spec(),
              DepictFrameTree(*root));
  }
  FrameTreeNode* bottom_child =
      root->child_at(0)->child_at(0)->child_at(0)->child_at(0);
  EXPECT_TRUE(bottom_child->current_url().is_empty());
  EXPECT_TRUE(bottom_child->is_on_initial_empty_document());
}

// Ensures that nested subframes with the same URL but different fragments can
// only be nested once.  See https://crbug.com/650332.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       SelfReferencingFragmentFrames) {
  StartEmbeddedServer();
  GURL url(
      embedded_test_server()->GetURL("a.com", "/page_with_iframe.html#123"));
  EXPECT_TRUE(NavigateToURL(shell(), url));

  WebContentsImpl* web_contents =
      static_cast<WebContentsImpl*>(shell()->web_contents());

  FrameTreeNode* root = web_contents->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);

  // ExecJs is used here and once more below because it is important to
  // use renderer-initiated navigations since browser-initiated navigations are
  // bypassed in the self-referencing navigation check.
  TestFrameNavigationObserver observer1(child);
  EXPECT_TRUE(ExecJs(child, "location.href = '" + url.spec() + "456" + "';"));
  observer1.Wait();

  FrameTreeNode* grandchild = child->child_at(0);
  GURL expected_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
  EXPECT_EQ(expected_url, grandchild->current_url());

  // This navigation should be blocked.
  GURL blocked_url(embedded_test_server()->GetURL(
      "a.com", "/page_with_iframe.html#123456789"));
  TestNavigationManager manager(web_contents, blocked_url);
  EXPECT_TRUE(
      ExecJs(grandchild, "location.href = '" + blocked_url.spec() + "';"));
  // Wait for WillStartRequest and verify that the request is aborted before
  // starting it.
  EXPECT_FALSE(manager.WaitForRequestStart());
  EXPECT_TRUE(WaitForLoadStop(web_contents));

  // The FrameTree contains two successful instances of the url plus an
  // unsuccessfully-navigated third instance with a blank URL.
  const GURL kExpectedSiteURL = AreDefaultSiteInstancesEnabled()
                                    ? SiteInstanceImpl::GetDefaultSiteURL()
                                    : GURL("http://a.com/");
  EXPECT_EQ(std::string(" Site A\n"
                        "   +--Site A\n"
                        "        +--Site A\n"
                        "Where A = ") +
                kExpectedSiteURL.spec(),
            DepictFrameTree(*root));

  // The URL of the grandchild has not changed.
  EXPECT_EQ(expected_url, grandchild->current_url());
}

// Ensure that loading a page with a meta refresh iframe does not cause an
// infinite number of nested iframes to be created.  This test loads a page with
// an about:blank iframe where the page injects html containing a meta refresh
// into the iframe.  This test then checks that this does not cause infinite
// nested iframes to be created.  See https://crbug.com/527367.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       SelfReferencingMetaRefreshFrames) {
  // Load a page with a blank iframe.
  StartEmbeddedServer();
  GURL url(embedded_test_server()->GetURL(
      "a.com", "/page_with_meta_refresh_frame.html"));
  NavigateToURLBlockUntilNavigationsComplete(shell(), url, 3);

  WebContentsImpl* web_contents =
      static_cast<WebContentsImpl*>(shell()->web_contents());

  FrameTreeNode* root = web_contents->GetPrimaryFrameTree().root();

  // The third navigation should fail and be cancelled, leaving a FrameTree with
  // a height of 2.
  const GURL kExpectedSiteURL = AreDefaultSiteInstancesEnabled()
                                    ? SiteInstanceImpl::GetDefaultSiteURL()
                                    : GURL("http://a.com/");
  // The FrameTreeVisualizer test ensure that the childmost frame is not loaded.
  EXPECT_EQ(std::string(" Site A\n"
                        "   +--Site A\n"
                        "        +--Site A\n"
                        "Where A = ") +
                kExpectedSiteURL.spec(),
            DepictFrameTree(*root));

  EXPECT_EQ(GURL(url::kAboutBlankURL),
            root->child_at(0)->child_at(0)->current_url());

  // The frame is no longer on the initial empty document.
  EXPECT_FALSE(root->child_at(0)->child_at(0)->is_on_initial_empty_document());
}

// Ensure that navigating a subframe to the same URL as its parent twice in a
// row is not blocked by the self-reference check.
// See https://crbug.com/650332.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       SelfReferencingSameURLRenavigation) {
  StartEmbeddedServer();
  GURL first_url(
      embedded_test_server()->GetURL("a.com", "/page_with_iframe.html"));
  GURL second_url(first_url.spec() + "#123");
  EXPECT_TRUE(NavigateToURL(shell(), first_url));

  WebContentsImpl* web_contents =
      static_cast<WebContentsImpl*>(shell()->web_contents());

  FrameTreeNode* root = web_contents->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);

  TestFrameNavigationObserver observer1(child);
  EXPECT_TRUE(ExecJs(child, "location.href = '" + second_url.spec() + "';"));
  observer1.Wait();

  EXPECT_EQ(child->current_url(), second_url);

  TestFrameNavigationObserver observer2(child);
  // This navigation shouldn't be blocked. Blocking should only occur when more
  // than one ancestor has the same URL (excluding fragments), and the
  // navigating frame's current URL shouldn't count toward that.
  EXPECT_TRUE(ExecJs(child, "location.href = '" + first_url.spec() + "';"));
  observer2.Wait();

  EXPECT_EQ(child->current_url(), first_url);
}

// Ensures that POST requests bypass self-referential URL checks. See
// https://crbug.com/710008.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       SelfReferencingFramesWithPOST) {
  StartEmbeddedServer();
  GURL url(embedded_test_server()->GetURL("a.com", "/page_with_iframe.html"));
  EXPECT_TRUE(NavigateToURL(shell(), url));

  WebContentsImpl* web_contents =
      static_cast<WebContentsImpl*>(shell()->web_contents());

  FrameTreeNode* root = web_contents->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);

  GURL child_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
  EXPECT_EQ(url, root->current_url());
  EXPECT_EQ(child_url, child->current_url());

  // Navigate the child frame to the same URL as parent via POST.
  std::string script =
      "var f = document.createElement('form');\n"
      "f.method = 'POST';\n"
      "f.action = '/page_with_iframe.html';\n"
      "document.body.appendChild(f);\n"
      "f.submit();";
  {
    TestFrameNavigationObserver observer(child);
    EXPECT_TRUE(ExecJs(child, script));
    observer.Wait();
  }

  FrameTreeNode* grandchild = child->child_at(0);
  EXPECT_EQ(url, child->current_url());
  EXPECT_EQ(child_url, grandchild->current_url());

  // Now navigate the grandchild to the same URL as its two ancestors. This
  // should be allowed since it uses POST; it was blocked prior to
  // fixing https://crbug.com/710008.
  {
    TestFrameNavigationObserver observer(grandchild);
    EXPECT_TRUE(ExecJs(grandchild, script));
    observer.Wait();
  }

  EXPECT_EQ(url, grandchild->current_url());
  ASSERT_EQ(1U, grandchild->child_count());
  EXPECT_EQ(child_url, grandchild->child_at(0)->current_url());
}

// Ensures that we don't reset a speculative RFH if a JavaScript URL is loaded
// while there's an ongoing cross-process navigation. See
// https://crbug.com/793432.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       JavaScriptLoadDoesntResetSpeculativeRFH) {
  EXPECT_TRUE(embedded_test_server()->Start());

  GURL site1 = embedded_test_server()->GetURL("a.com", "/title1.html");
  GURL site2 = embedded_test_server()->GetURL("b.com", "/title2.html");

  EXPECT_TRUE(NavigateToURL(shell(), site1));

  TestNavigationManager cross_site_navigation(shell()->web_contents(), site2);
  shell()->LoadURL(site2);
  cross_site_navigation.WaitForSpeculativeRenderFrameHostCreation();

  RenderFrameHostImpl* speculative_rfh =
      static_cast<WebContentsImpl*>(shell()->web_contents())
          ->GetPrimaryFrameTree()
          .root()
          ->render_manager()
          ->speculative_frame_host();
  CHECK(speculative_rfh);
  shell()->web_contents()->GetController().LoadURL(
      GURL("javascript:(0)"), Referrer(), ui::PAGE_TRANSITION_TYPED,
      std::string());

  ASSERT_TRUE(cross_site_navigation.WaitForNavigationFinished());
  // No crash means everything worked!
}

// Test that unrelated browsing contexts cannot find each other's windows,
// even when they end up using the same renderer process (e.g. because of
// hitting a process limit).  See also https://crbug.com/718489.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       ProcessReuseVsBrowsingInstance) {
  // Set max renderers to 1 to force reusing a renderer process between two
  // unrelated tabs.
  RenderProcessHost::SetMaxRendererProcessCount(1);

  // Navigate 2 tabs to a web page (regular web pages can share renderers
  // among themselves without any restrictions, unlike extensions, apps, etc.).
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url1(embedded_test_server()->GetURL("/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), url1));
  RenderFrameHost* tab1 = shell()->web_contents()->GetPrimaryMainFrame();
  EXPECT_EQ(url1, tab1->GetLastCommittedURL());
  GURL url2(embedded_test_server()->GetURL("/title2.html"));
  Shell* shell2 = Shell::CreateNewWindow(
      shell()->web_contents()->GetBrowserContext(), url2, nullptr, gfx::Size());
  EXPECT_TRUE(NavigateToURL(shell2, url2));
  RenderFrameHost* tab2 = shell2->web_contents()->GetPrimaryMainFrame();
  EXPECT_EQ(url2, tab2->GetLastCommittedURL());

  // Sanity-check test setup: 2 frames share a renderer process, but are not in
  // a related browsing instance.
  if (!AreAllSitesIsolatedForTesting())
    EXPECT_EQ(tab1->GetProcess(), tab2->GetProcess());
  EXPECT_FALSE(
      tab1->GetSiteInstance()->IsRelatedSiteInstance(tab2->GetSiteInstance()));

  // Name the 2 frames.
  EXPECT_TRUE(ExecJs(tab1, "window.name = 'tab1';"));
  EXPECT_TRUE(ExecJs(tab2, "window.name = 'tab2';"));

  // Verify that |tab1| cannot find named frames belonging to |tab2| (i.e. that
  // window.open will end up creating a new tab rather than returning the old
  // |tab2| tab).
  WebContentsAddedObserver new_contents_observer;
  EXPECT_EQ(url::kAboutBlankURL, EvalJs(tab1,
                                        "var w = window.open('', 'tab2');\n"
                                        "w.location.href;"));
  EXPECT_TRUE(new_contents_observer.GetWebContents());
}

// Verify that cross-site main frame navigations will swap BrowsingInstances
// for certain browser-initiated navigations, such as user typing the URL into
// the address bar.  This helps avoid unneeded process sharing and should
// happen even if the current frame has an opener.  See
// https://crbug.com/803367.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       BrowserInitiatedNavigationsSwapBrowsingInstance) {
  ASSERT_TRUE(embedded_test_server()->Start());

  // Start with a page on a.com.
  GURL a_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), a_url));
  scoped_refptr<SiteInstance> a_site_instance(
      shell()->web_contents()->GetSiteInstance());

  // Open a popup for b.com. This should stay in the current BrowsingInstance.
  GURL b_url(embedded_test_server()->GetURL("b.com", "/title1.html"));
  Shell* popup = OpenPopup(shell(), b_url, "foo");
  EXPECT_TRUE(WaitForLoadStop(popup->web_contents()));
  scoped_refptr<SiteInstance> b_site_instance(
      popup->web_contents()->GetSiteInstance());
  EXPECT_TRUE(a_site_instance->IsRelatedSiteInstance(b_site_instance.get()));

  // 1. Same-site browser-initiated navigations shouldn't swap BrowsingInstances
  //    or SiteInstances.
  EXPECT_TRUE(NavigateToURL(
      popup, embedded_test_server()->GetURL("b.com", "/title2.html")));
  EXPECT_EQ(b_site_instance, popup->web_contents()->GetSiteInstance());

  // 2. A cross-site browser-initiated navigation should swap BrowsingInstances,
  //    despite having an opener in the same site as the destination URL.
  EXPECT_TRUE(NavigateToURL(
      popup, embedded_test_server()->GetURL("a.com", "/title3.html")));
  EXPECT_NE(b_site_instance, popup->web_contents()->GetSiteInstance());
  EXPECT_NE(a_site_instance, popup->web_contents()->GetSiteInstance());
  EXPECT_FALSE(a_site_instance->IsRelatedSiteInstance(
      popup->web_contents()->GetSiteInstance()));
  EXPECT_FALSE(b_site_instance->IsRelatedSiteInstance(
      popup->web_contents()->GetSiteInstance()));

  auto transitions_forcing_browsing_instance_swap = {
      ui::PAGE_TRANSITION_AUTO_BOOKMARK, /* user clicking on a bookmark */
      ui::PAGE_TRANSITION_GENERATED,     /* search query */
      ui::PAGE_TRANSITION_KEYWORD, /* search within a site from address bar */
      ui::PAGE_TRANSITION_TYPED,   /* user typing URL into address bar */
  };
  auto transitions_not_forcing_browsing_instance_swap = {
      ui::PAGE_TRANSITION_LINK, /* user clicked on a link in the document */
      ui::PAGE_TRANSITION_AUTO_TOPLEVEL,
      ui::PAGE_TRANSITION_FORM_SUBMIT,
      ui::PAGE_TRANSITION_KEYWORD_GENERATED,
      ui::PAGE_TRANSITION_RELOAD,
  };
  int current_site = 0;
  scoped_refptr<SiteInstance> curr_instance(
      popup->web_contents()->GetSiteInstance());

  // 3. Perform several cross-site browser-initiated navigations in the popup
  //    that do not force a BrowsingInstance swap.
  //
  // When ProactivelySwapBrowsingInstance is disabled, the BrowsingInstance
  // isn't swapped, even if it could be.
  //
  // When ProactivelySwapBrowsingInstance is enabled, the BrowsingInstance is
  // now swapped. It can be swapped, because (2) caused the popup to live in a
  // different BrowsingInstance. The window and the popup are no longer related.
  for (auto transition : transitions_not_forcing_browsing_instance_swap) {
    GURL cross_site_url(embedded_test_server()->GetURL(
        base::StringPrintf("site%d.com", current_site++), "/title1.html"));
    SCOPED_TRACE(base::StringPrintf(
        "... wrong BrowsingInstance for '%s' transition to %s",
        ui::PageTransitionGetCoreTransitionString(transition),
        cross_site_url.spec().c_str()));

    TestNavigationObserver observer(popup->web_contents());
    NavigationController::LoadURLParams params(cross_site_url);
    params.transition_type = transition;
    popup->web_contents()->GetController().LoadURLWithParams(params);
    observer.Wait();

    if (CanCrossSiteNavigationsProactivelySwapBrowsingInstances()) {
      EXPECT_FALSE(curr_instance->IsRelatedSiteInstance(
          popup->web_contents()->GetSiteInstance()));
    } else {
      EXPECT_TRUE(curr_instance->IsRelatedSiteInstance(
          popup->web_contents()->GetSiteInstance()));
    }
  }

  // 4. Perform several cross-site browser-initiated navigations in the popup,
  //    all using page transitions that force BrowsingInstance swaps:
  for (auto transition : transitions_forcing_browsing_instance_swap) {
    GURL cross_site_url(embedded_test_server()->GetURL(
        base::StringPrintf("site%d.com", current_site++), "/title1.html"));
    scoped_refptr<SiteInstance> prev_instance(
        popup->web_contents()->GetSiteInstance());
    SCOPED_TRACE(base::StringPrintf(
        "... expected BrowsingInstance swap for '%s' transition to %s",
        ui::PageTransitionGetCoreTransitionString(transition),
        cross_site_url.spec().c_str()));

    TestNavigationObserver observer(popup->web_contents());
    NavigationController::LoadURLParams params(cross_site_url);
    params.transition_type = transition;
    popup->web_contents()->GetController().LoadURLWithParams(params);
    observer.Wait();

    // This should swap BrowsingInstances.
    scoped_refptr<SiteInstance> updated_curr_instance(
        popup->web_contents()->GetSiteInstance());
    EXPECT_NE(a_site_instance, updated_curr_instance);
    EXPECT_FALSE(
        a_site_instance->IsRelatedSiteInstance(updated_curr_instance.get()));
    EXPECT_NE(prev_instance, updated_curr_instance);
    EXPECT_FALSE(
        prev_instance->IsRelatedSiteInstance(updated_curr_instance.get()));
  }
}

// Verifies that a renderer-initiated navigation from a site in the default
// StoragePartition to one that ContentBrowserClient places in a non-default
// StoragePartition will swap to a new BrowsingInstance.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       NavigationToDifferentPartitionSwapsBrowsingInstance) {
  ASSERT_TRUE(embedded_test_server()->Start());

  // Set up a ContentBrowserClient that maps b.com to a non-default partition.
  CustomStoragePartitionBrowserClient modified_client(GURL("http://b.com/"));

  // Load a page on a.com and verify that it uses the default partition.
  GURL a_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), a_url));
  RenderFrameHostImpl* rfh =
      static_cast<WebContentsImpl*>(shell()->web_contents())
          ->GetPrimaryMainFrame();
  SiteInstanceImpl* a_site_instance = rfh->GetSiteInstance();
  EXPECT_TRUE(
      a_site_instance->GetSiteInfo().storage_partition_config().is_default());

  // Make sure proactive BrowserInstance swapping doesn't interfere.
  rfh->DisableProactiveBrowsingInstanceSwapForTesting();

  // Do a renderer-initiated navigation to a page on b.com and verify that we
  // swapped BrowsingInstances.
  GURL b_url(embedded_test_server()->GetURL("b.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURLFromRenderer(shell(), b_url));
  rfh = static_cast<WebContentsImpl*>(shell()->web_contents())
            ->GetPrimaryMainFrame();
  SiteInstanceImpl* b_site_instance = rfh->GetSiteInstance();
  EXPECT_FALSE(
      b_site_instance->GetSiteInfo().storage_partition_config().is_default());
  EXPECT_FALSE(a_site_instance->IsRelatedSiteInstance(b_site_instance));
}

// Verifies that iframes inherit their StoragePartition, even if
// ContentBrowserClient would normally place the iframe's URL in a dedicated
// StoragePartition.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       SubframeInheritsStoragePartition) {
  ASSERT_TRUE(embedded_test_server()->Start());

  // Set up a ContentBrowserClient that maps b.com to a non-default partition.
  CustomStoragePartitionBrowserClient modified_client(GURL("http://b.com/"));

  // Load a page on b.com to verify that it uses the correct partition.
  GURL b_url(embedded_test_server()->GetURL("b.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), b_url));
  RenderFrameHostImpl* rfh =
      static_cast<WebContentsImpl*>(shell()->web_contents())
          ->GetPrimaryMainFrame();
  EXPECT_FALSE(rfh->GetSiteInstance()
                   ->GetSiteInfo()
                   .storage_partition_config()
                   .is_default());

  // Load a page on a.com that iframes a b.com page.
  GURL a_url(embedded_test_server()->GetURL(
      "a.com", "/cross_site_iframe_factory.html?a(b)"));
  EXPECT_TRUE(NavigateToURL(shell(), a_url));
  rfh = static_cast<WebContentsImpl*>(shell()->web_contents())
            ->GetPrimaryMainFrame();
  SiteInstanceImpl* a_site_instance = rfh->GetSiteInstance();
  if (AreDefaultSiteInstancesEnabled()) {
    EXPECT_TRUE(a_site_instance->IsDefaultSiteInstance());
  } else {
    EXPECT_EQ("http://a.com/", a_site_instance->GetSiteURL());
  }
  EXPECT_TRUE(
      a_site_instance->GetSiteInfo().storage_partition_config().is_default());

  // Verify that the iframe uses the default StoragePartition.
  EXPECT_EQ(1UL, rfh->child_count());
  SiteInstanceImpl* b_site_instance = static_cast<SiteInstanceImpl*>(
      rfh->child_at(0)->current_frame_host()->GetSiteInstance());
  if (AreDefaultSiteInstancesEnabled()) {
    EXPECT_TRUE(b_site_instance->IsDefaultSiteInstance());
  } else {
    EXPECT_EQ("http://b.com/", b_site_instance->GetSiteURL());
  }
  EXPECT_TRUE(
      b_site_instance->GetSiteInfo().storage_partition_config().is_default());
}

// Ensure that these two browser-initiated navigations:
//   foo.com -> about:blank -> foo.com
// stay in the same SiteInstance.  This isn't technically required for
// correctness, but some tests (e.g., testEnsureHotFromScratch from
// telemetry_unittests) currently depend on this behavior.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       NavigateToAndFromAboutBlank) {
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));
  scoped_refptr<SiteInstance> site_instance(
      shell()->web_contents()->GetSiteInstance());

  // Navigate to about:blank from address bar.  This stays in the foo.com
  // SiteInstance, unless we do a proactive BrowsingInstance swap due to
  // back/forward cache.
  EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL)));
  if (IsBackForwardCacheEnabled()) {
    site_instance = shell()->web_contents()->GetSiteInstance();
  } else {
    EXPECT_EQ(site_instance, shell()->web_contents()->GetSiteInstance());
  }

  // Perform a browser-initiated navigation to foo.com.  This should also stay
  // in the original foo.com SiteInstance and BrowsingInstance.
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));
  EXPECT_EQ(site_instance, shell()->web_contents()->GetSiteInstance());
}

// Check that with the following sequence of navigations:
//   foo.com -(1)-> bar.com -(2)-> about:blank -(3)-> foo.com
// where (1) is renderer-initiated and (2)+(3) are browser-initiated, the last
// navigation goes back to the first SiteInstance without --site-per-process,
// and to a new SiteInstance and BrowsingInstance with --site-per-process.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       NavigateToFooThenBarThenAboutBlankThenFoo) {
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));
  scoped_refptr<SiteInstance> site_instance(
      shell()->web_contents()->GetSiteInstance());

  // Do a renderer-initiated navigation to bar.com, then navigate to
  // about:blank from address bar, then back to foo.com.
  GURL bar_url(embedded_test_server()->GetURL("bar.com", "/title1.html"));

  EXPECT_TRUE(NavigateToURLFromRenderer(shell(), bar_url));
  EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL)));
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));

  // This should again go back to the original foo.com SiteInstance without
  // --site-per-process, as in that case both the bar.com and
  // about:blank navigation will stay in the foo.com SiteInstance, and the
  // final navigation to foo.com will be considered same-site with the current
  // SiteInstance.
  //
  // With --site-per-process, bar.com should get its own SiteInstance, the
  // about:blank navigation will stay in it, and thus the final foo.com
  // navigation should be considered cross-site from the current SiteInstance.
  // Since this is a browser-initiated, cross-site navigation, it will swap
  // BrowsingInstances, and create a new foo.com SiteInstance, distinct from
  // the initial one.
  if (ExpectSameSiteInstance()) {
    EXPECT_EQ(site_instance, shell()->web_contents()->GetSiteInstance());
  } else {
    EXPECT_NE(site_instance, shell()->web_contents()->GetSiteInstance());
    EXPECT_FALSE(site_instance->IsRelatedSiteInstance(
        shell()->web_contents()->GetSiteInstance()));
    EXPECT_EQ(site_instance->GetSiteURL(),
              shell()->web_contents()->GetSiteInstance()->GetSiteURL());
  }
}

// Test to verify that navigations in the main frame, which result in an error
// page, properly commit the error page in its own dedicated process.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       ErrorPageNavigationInMainFrame) {
  // This test is only valid if error page isolation is enabled.
  if (!SiteIsolationPolicy::IsErrorPageIsolationEnabled(true))
    return;

  StartEmbeddedServer();
  GURL url(embedded_test_server()->GetURL("/title1.html"));
  GURL error_url(embedded_test_server()->GetURL("/empty.html"));
  std::unique_ptr<URLLoaderInterceptor> url_interceptor =
      SetupRequestFailForURL(error_url);
  // Start with a successful navigation to a document.
  EXPECT_TRUE(NavigateToURL(shell(), url));
  scoped_refptr<SiteInstance> success_site_instance =
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();

  // Browser-initiated navigation to an error page should result in changing the
  // SiteInstance and process.
  {
    NavigationHandleObserver observer(shell()->web_contents(), error_url);
    EXPECT_FALSE(NavigateToURL(shell(), error_url));
    EXPECT_TRUE(observer.is_error());
    EXPECT_EQ(net::ERR_DNS_TIMED_OUT, observer.net_error_code());

    scoped_refptr<SiteInstance> error_site_instance =
        shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
    EXPECT_NE(success_site_instance, error_site_instance);
    if (CanSameSiteMainFrameNavigationsChangeSiteInstances()) {
      // When ProactivelySwapBrowsingInstance is enabled on same-site
      // navigations, the navigation above will result in a new
      // BrowsingInstance.
      EXPECT_FALSE(success_site_instance->IsRelatedSiteInstance(
          error_site_instance.get()));
    } else {
      EXPECT_TRUE(success_site_instance->IsRelatedSiteInstance(
          error_site_instance.get()));
    }
    EXPECT_NE(success_site_instance->GetProcess()->GetID(),
              error_site_instance->GetProcess()->GetID());
    EXPECT_TRUE(HasErrorPageSiteInfo(error_site_instance.get()));

    // Verify that the error page process is locked to origin
    EXPECT_TRUE(HasErrorPageProcessLock(error_site_instance.get()));
    EXPECT_TRUE(
        IsMainFrameOriginOpaqueAndCompatibleWithURL(shell(), error_url));
  }

  // Navigate successfully again to a document, then perform a
  // renderer-initiated navigation and verify it behaves the same way.
  EXPECT_TRUE(NavigateToURL(shell(), url));
  success_site_instance =
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  EXPECT_FALSE(HasErrorPageProcessLock(success_site_instance.get()));

  {
    NavigationHandleObserver observer(shell()->web_contents(), error_url);
    TestFrameNavigationObserver frame_observer(shell()->web_contents());
    EXPECT_TRUE(ExecJs(shell()->web_contents(),
                       "location.href = '" + error_url.spec() + "';"));
    frame_observer.Wait();
    EXPECT_TRUE(observer.is_error());
    EXPECT_EQ(net::ERR_DNS_TIMED_OUT, observer.net_error_code());

    scoped_refptr<SiteInstance> error_site_instance =
        shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
    EXPECT_NE(success_site_instance, error_site_instance);
    if (CanSameSiteMainFrameNavigationsChangeSiteInstances()) {
      // When ProactivelySwapBrowsingInstance is enabled on same-site
      // navigations, the navigation above will result in a new
      // BrowsingInstance.
      EXPECT_FALSE(success_site_instance->IsRelatedSiteInstance(
          error_site_instance.get()));
    } else {
      EXPECT_TRUE(success_site_instance->IsRelatedSiteInstance(
          error_site_instance.get()));
    }
    EXPECT_NE(success_site_instance->GetProcess()->GetID(),
              error_site_instance->GetProcess()->GetID());
    EXPECT_TRUE(HasErrorPageSiteInfo(error_site_instance.get()));

    // Verify that the error page process is locked to origin
    EXPECT_TRUE(HasErrorPageProcessLock(error_site_instance.get()));
  }
}

// Test to verify that navigations in subframes, which result in an error
// page, commit the error page in the same process and not in the dedicated
// error page process.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       ErrorPageNavigationInChildFrame) {
  StartEmbeddedServer();
  GURL url(embedded_test_server()->GetURL("/page_with_iframe.html"));
  GURL error_url(embedded_test_server()->GetURL("/empty.html"));
  std::unique_ptr<URLLoaderInterceptor> url_interceptor =
      SetupRequestFailForURL(error_url);

  // Start with a successful navigation to a document.
  EXPECT_TRUE(NavigateToURL(shell(), url));

  WebContentsImpl* web_contents =
      static_cast<WebContentsImpl*>(shell()->web_contents());

  FrameTreeNode* root = web_contents->GetPrimaryFrameTree().root();
  FrameTreeNode* child = root->child_at(0);

  scoped_refptr<SiteInstance> success_site_instance =
      child->current_frame_host()->GetSiteInstance();

  NavigationHandleObserver observer(web_contents, error_url);
  TestFrameNavigationObserver frame_observer(child);
  EXPECT_TRUE(ExecJs(child, "location.href = '" + error_url.spec() + "';"));
  frame_observer.Wait();

  EXPECT_TRUE(observer.is_error());
  EXPECT_EQ(net::ERR_DNS_TIMED_OUT, observer.net_error_code());

  scoped_refptr<SiteInstance> error_site_instance =
      child->current_frame_host()->GetSiteInstance();
  EXPECT_TRUE(IsExpectedSubframeErrorTransition(success_site_instance.get(),
                                                error_site_instance.get()));
  EXPECT_TRUE(IsOriginOpaqueAndCompatibleWithURL(child, error_url));
}

// Test to verify that navigations in new window, which result in an error
// page, commit the error page in the dedicated error page process and not in
// the one for the destination site.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       ErrorPageNavigationInNewWindow) {
  // This test is only valid if error page isolation is enabled.
  if (!SiteIsolationPolicy::IsErrorPageIsolationEnabled(true))
    return;

  StartEmbeddedServer();
  GURL error_url(embedded_test_server()->GetURL("/empty.html"));
  std::unique_ptr<URLLoaderInterceptor> url_interceptor =
      SetupRequestFailForURL(error_url);

  // Start with a successful navigation to a document.
  EXPECT_TRUE(
      NavigateToURL(shell(), embedded_test_server()->GetURL("/title1.html")));

  FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
                            ->GetPrimaryFrameTree()
                            .root();
  scoped_refptr<SiteInstance> main_site_instance =
      root->current_frame_host()->GetSiteInstance();

  Shell* new_shell = OpenPopup(shell(), error_url, "foo");
  EXPECT_TRUE(new_shell);

  scoped_refptr<SiteInstance> error_site_instance =
      new_shell->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  EXPECT_NE(main_site_instance, error_site_instance);
  EXPECT_TRUE(HasErrorPageSiteInfo(error_site_instance.get()));

  // Verify that the error page process is locked to origin
  EXPECT_TRUE(HasErrorPageProcessLock(error_site_instance.get()));
  EXPECT_TRUE(
      IsMainFrameOriginOpaqueAndCompatibleWithURL(new_shell, error_url));
}

// Test to verify that windows that are not part of the same
// BrowsingInstance end up using the same error page process, even though
// their SiteInstances are not related.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       ErrorPageNavigationInUnrelatedWindows) {
  // This test is only valid if error page isolation is enabled.
  if (!SiteIsolationPolicy::IsErrorPageIsolationEnabled(true))
    return;

  StartEmbeddedServer();
  GURL error_url(embedded_test_server()->GetURL("/empty.html"));
  std::unique_ptr<URLLoaderInterceptor> url_interceptor =
      SetupRequestFailForURL(error_url);

  // Navigate the main window to an error page and verify.
  {
    NavigationHandleObserver observer(shell()->web_contents(), error_url);
    EXPECT_FALSE(NavigateToURL(shell(), error_url));
    scoped_refptr<SiteInstance> error_site_instance =
        shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
    EXPECT_TRUE(observer.is_error());
    EXPECT_EQ(net::ERR_DNS_TIMED_OUT, observer.net_error_code());
    EXPECT_TRUE(HasErrorPageSiteInfo(error_site_instance.get()));
    EXPECT_TRUE(
        IsMainFrameOriginOpaqueAndCompatibleWithURL(shell(), error_url));
  }

  // Creat a new, unrelated, window, navigate it to an error page and
  // verify.
  Shell* new_shell = CreateBrowser();
  {
    NavigationHandleObserver observer(new_shell->web_contents(), error_url);
    EXPECT_FALSE(NavigateToURL(new_shell, error_url));
    scoped_refptr<SiteInstance> error_site_instance =
        new_shell->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
    EXPECT_TRUE(observer.is_error());
    EXPECT_EQ(net::ERR_DNS_TIMED_OUT, observer.net_error_code());
    EXPECT_TRUE(HasErrorPageSiteInfo(error_site_instance.get()));
    EXPECT_TRUE(
        IsMainFrameOriginOpaqueAndCompatibleWithURL(new_shell, error_url));
  }

  // Verify the two SiteInstanes are not related, but they end up using the
  // same underlying RenderProcessHost.
  EXPECT_FALSE(
      shell()->web_contents()->GetSiteInstance()->IsRelatedSiteInstance(
          new_shell->web_contents()->GetSiteInstance()));
  EXPECT_EQ(shell()->web_contents()->GetSiteInstance()->GetProcess(),
            new_shell->web_contents()->GetSiteInstance()->GetProcess());

  // Verify that the process is locked to origin
  EXPECT_TRUE(
      HasErrorPageProcessLock(shell()->web_contents()->GetSiteInstance()));
}

// Test to verify that reloading an error page once the error condition has
// cleared up is successful and does not create a new navigation entry.
// See https://crbug.com/840485.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest, ErrorPageNavigationReload) {
  // This test is only valid if error page isolation is enabled.
  if (!SiteIsolationPolicy::IsErrorPageIsolationEnabled(true))
    return;

  StartEmbeddedServer();
  GURL start_url(embedded_test_server()->GetURL("/title1.html"));
  GURL error_url(embedded_test_server()->GetURL("/empty.html"));
  GURL end_url(embedded_test_server()->GetURL("/title2.html"));
  NavigationControllerImpl& nav_controller =
      static_cast<NavigationControllerImpl&>(
          shell()->web_contents()->GetController());

  // Build session history with three entries, where the middle one will be
  // tested for successful and failed reloads. This allows checking whether
  // reload accidentally clears the forward session history if it is
  // incorrectly classified.
  EXPECT_TRUE(NavigateToURL(shell(), start_url));
  EXPECT_TRUE(NavigateToURL(shell(), error_url));
  EXPECT_TRUE(NavigateToURL(shell(), end_url));
  {
    TestNavigationObserver back_observer(shell()->web_contents());
    shell()->web_contents()->GetController().GoBack();
    back_observer.Wait();
    EXPECT_TRUE(back_observer.last_navigation_succeeded());
  }
  EXPECT_EQ(3, nav_controller.GetEntryCount());
  EXPECT_EQ(1, nav_controller.GetLastCommittedEntryIndex());
  EXPECT_EQ(error_url, shell()->web_contents()->GetLastCommittedURL());

  scoped_refptr<SiteInstance> success_site_instance =
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  url::Origin expected_origin =
      shell()->web_contents()->GetPrimaryMainFrame()->GetLastCommittedOrigin();

  EXPECT_EQ(url::Origin::Create(error_url), expected_origin);

  // Install an interceptor which will cause network failure for |error_url|,
  // reload the existing entry and verify.
  std::unique_ptr<URLLoaderInterceptor> url_interceptor =
      SetupRequestFailForURL(error_url);
  {
    TestNavigationObserverInternal reload_observer(shell()->web_contents());
    shell()->web_contents()->GetController().Reload(ReloadType::NORMAL, false);
    reload_observer.Wait();
    EXPECT_FALSE(reload_observer.last_navigation_succeeded());
    // TODO(nasko): Investigate making a failing reload of a successful
    // navigation be classified as NEW_ENTRY instead, since with error page
    // isolation it involves a SiteInstance swap.
    EXPECT_EQ(NavigationType::NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY,
              reload_observer.last_navigation_type());
  }
  EXPECT_EQ(3, nav_controller.GetEntryCount());
  EXPECT_EQ(1, nav_controller.GetLastCommittedEntryIndex());
  int process_id =
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
  EXPECT_TRUE(HasErrorPageProcessLock(
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance()));
  EXPECT_TRUE(IsMainFrameOriginOpaqueAndCompatibleWithURL(shell(), error_url));

  // Reload while it will still fail to ensure it stays in the same process.
  {
    TestNavigationObserverInternal reload_observer(shell()->web_contents());
    shell()->web_contents()->GetController().Reload(ReloadType::NORMAL, false);
    reload_observer.Wait();
    EXPECT_FALSE(reload_observer.last_navigation_succeeded());
    EXPECT_EQ(NavigationType::NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY,
              reload_observer.last_navigation_type());
  }
  EXPECT_EQ(
      process_id,
      shell()->web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID());
  EXPECT_TRUE(IsMainFrameOriginOpaqueAndCompatibleWithURL(shell(), error_url));

  // Reload the error page after clearing the error condition, such that the
  // navigation is successful and verify that no new entry was added to
  // session history and forward history is not pruned.
  url_interceptor.reset();
  {
    TestNavigationObserverInternal reload_observer(shell()->web_contents());
    shell()->web_contents()->GetController().Reload(ReloadType::NORMAL, false);
    reload_observer.Wait();
    EXPECT_TRUE(reload_observer.last_navigation_succeeded());
    // The successful reload should be classified as a NEW_ENTRY navigation
    // with replacement, since it needs to stay at the same entry in session
    // history, but needs a new entry because of the change in SiteInstance.
    EXPECT_EQ(NavigationType::NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY,
              reload_observer.last_navigation_type());
  }
  EXPECT_EQ(3, nav_controller.GetEntryCount());
  EXPECT_EQ(1, nav_controller.GetLastCommittedEntryIndex());
  EXPECT_FALSE(HasErrorPageSiteInfo(
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance()));
  EXPECT_FALSE(HasErrorPageProcessLock(
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance()));
  EXPECT_EQ(
      expected_origin,
      shell()->web_contents()->GetPrimaryMainFrame()->GetLastCommittedOrigin());

  // Test the same scenario as above, but this time initiated by the
  // renderer process.
  url_interceptor = SetupRequestFailForURL(error_url);
  {
    TestNavigationObserverInternal reload_observer(shell()->web_contents());
    shell()->web_contents()->GetController().Reload(ReloadType::NORMAL, false);
    reload_observer.Wait();
    EXPECT_FALSE(reload_observer.last_navigation_succeeded());
    // TODO(nasko): Investigate making a failing reload of a successful
    // navigation be classified as NEW_ENTRY instead, since with error page
    // isolation it involves a SiteInstance swap.
    EXPECT_EQ(NavigationType::NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY,
              reload_observer.last_navigation_type());
  }
  EXPECT_EQ(3, nav_controller.GetEntryCount());
  EXPECT_EQ(1, nav_controller.GetLastCommittedEntryIndex());
  EXPECT_TRUE(HasErrorPageSiteInfo(
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance()));
  EXPECT_TRUE(HasErrorPageProcessLock(
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance()));
  EXPECT_TRUE(IsMainFrameOriginOpaqueAndCompatibleWithURL(shell(), error_url));

  url_interceptor.reset();
  {
    TestNavigationObserverInternal reload_observer(shell()->web_contents());
    EXPECT_TRUE(ExecJs(shell(), "location.reload();"));
    reload_observer.Wait();
    EXPECT_TRUE(reload_observer.last_navigation_succeeded());
    // TODO(nasko): Investigate making renderer initiated reloads that change
    // SiteInstance be classified as NEW_ENTRY as well.
    EXPECT_EQ(NavigationType::NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY,
              reload_observer.last_navigation_type());
  }
  EXPECT_EQ(3, nav_controller.GetEntryCount());
  EXPECT_EQ(1, nav_controller.GetLastCommittedEntryIndex());
  EXPECT_FALSE(HasErrorPageSiteInfo(
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance()));
  EXPECT_FALSE(HasErrorPageProcessLock(
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance()));
  EXPECT_EQ(
      expected_origin,
      shell()->web_contents()->GetPrimaryMainFrame()->GetLastCommittedOrigin());
}

// Version of ErrorPageNavigationReload test that targets a subframe (because
// subframes are currently [~2019Q1] not subject to error page isolation).
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       ErrorPageNavigationReload_InSubframe_NetworkError) {
  StartEmbeddedServer();

  // Isolating a.com helps more robustly exercise platforms without strict
  // site isolation - we want to ensure that enforcing |initiator_origin| in
  // BeginNavigation is compatible with process locks, even when only one of
  // the frames requires isolation.
  IsolateOriginsForTesting(embedded_test_server(), shell()->web_contents(),
                           {"b.com"});

  // Start on a page with a main frame and a subframe.
  GURL page_url(embedded_test_server()->GetURL(
      "a.com", "/cross_site_iframe_factory.html?a(b)"));
  GURL test_url(embedded_test_server()->GetURL("b.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), page_url));
  NavigationControllerImpl& nav_controller =
      static_cast<NavigationControllerImpl&>(
          shell()->web_contents()->GetController());
  // We start at 3, because IsolateOriginsForTesting is sneeking in extra two
  // navigations.
  EXPECT_EQ(3, nav_controller.GetEntryCount());

  // Grab child's site URL.
  FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
                            ->GetPrimaryFrameTree()
                            .root();
  FrameTreeNode* child = root->child_at(0);
  GURL child_site_url =
      child->current_frame_host()->GetSiteInstance()->GetSiteURL();

  // Navigate the subframe to a URL that is cross-site from the main frame.
  {
    TestNavigationObserver nav_observer(shell()->web_contents());
    ASSERT_TRUE(ExecJs(child, JsReplace("window.location = $1", test_url)));
    nav_observer.Wait();

    EXPECT_TRUE(nav_observer.last_navigation_succeeded());
    EXPECT_EQ(4, nav_controller.GetEntryCount());
    EXPECT_EQ(test_url, child->current_frame_host()->GetLastCommittedURL());
    EXPECT_EQ(url::Origin::Create(test_url),
              child->current_frame_host()->GetLastCommittedOrigin());
    EXPECT_EQ(child_site_url,
              child->current_frame_host()->GetSiteInstance()->GetSiteURL());
  }

  // Reload the subframe while the network is down.
  {
    scoped_refptr<SiteInstance> success_site_instance =
        child->current_frame_host()->GetSiteInstance();
    std::unique_ptr<URLLoaderInterceptor> url_interceptor =
        SetupRequestFailForURL(test_url);
    TestNavigationObserver nav_observer(shell()->web_contents());
    ASSERT_TRUE(ExecJs(child, "window.location.reload()"));
    nav_observer.Wait();

    EXPECT_FALSE(nav_observer.last_navigation_succeeded());
    EXPECT_EQ(4, nav_controller.GetEntryCount());
    EXPECT_EQ(test_url, child->current_frame_host()->GetLastCommittedURL());

    // Error pages should commit in an opaque origin.
    EXPECT_TRUE(IsOriginOpaqueAndCompatibleWithURL(child, test_url));

    EXPECT_TRUE(IsExpectedSubframeErrorTransition(
        success_site_instance.get(),
        child->current_frame_host()->GetSiteInstance()));
  }

  // Reload the subframe after the network is restored.
  {
    TestNavigationObserver nav_observer(shell()->web_contents());
    // Note that some error pages actually do embed a button that will do an
    // equivalent of the renderer-initiated reload that is triggered below.
    ASSERT_TRUE(ExecJs(child, "window.location.reload()"));
    nav_observer.Wait();

    EXPECT_TRUE(nav_observer.last_navigation_succeeded());
    EXPECT_EQ(4, nav_controller.GetEntryCount());
    EXPECT_EQ(test_url, child->current_frame_host()->GetLastCommittedURL());
    EXPECT_EQ(url::Origin::Create(test_url),
              child->current_frame_host()->GetLastCommittedOrigin());
    EXPECT_EQ(child_site_url,
              child->current_frame_host()->GetSiteInstance()->GetSiteURL());
  }
}

// Version of ErrorPageNavigationReload test that targets a subframe (because
// subframes are currently [~2019Q1] not subject to error page isolation).
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       ErrorPageNavigationReload_InSubframe_BlockedByClient) {
  StartEmbeddedServer();

  // Isolating a.com and b.com helps more robustly exercise platforms without
  // strict site isolation - we want to ensure that enforcing |initiator_origin|
  // in BeginNavigation is compatible with process locks, even when only some of
  // the frames requires isolation.
  IsolateOriginsForTesting(embedded_test_server(), shell()->web_contents(),
                           std::vector<std::string>{"a.com", "b.com"});

  // Start on a page with a same-site main frame and a subframe.
  GURL page_url(embedded_test_server()->GetURL(
      "a.com", "/cross_site_iframe_factory.html?a(b,b)"));
  GURL test_url(embedded_test_server()->GetURL("c.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), page_url));
  NavigationControllerImpl& nav_controller =
      static_cast<NavigationControllerImpl&>(
          shell()->web_contents()->GetController());
  // We start at 3, because IsolateOriginsForTesting calls are sneeking in extra
  // two navigations.
  EXPECT_EQ(3, nav_controller.GetEntryCount());

  // Grab child's site URL.
  FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
                            ->GetPrimaryFrameTree()
                            .root();
  FrameTreeNode* child1 = root->child_at(0);
  FrameTreeNode* child2 = root->child_at(1);
  GURL a_site_url = root->current_frame_host()->GetSiteInstance()->GetSiteURL();
  EXPECT_EQ("a.com", a_site_url.host());
  GURL b_site_url =
      child2->current_frame_host()->GetSiteInstance()->GetSiteURL();
  EXPECT_EQ("b.com", b_site_url.host());

  // Navigate the subframe to a cross-site URL, while blocking the request with
  // ERR_BLOCKED_BY_CLIENT.
  {
    // Name the first child, so it can be found and navigated by the other child
    // in the next test step below.
    ASSERT_TRUE(ExecJs(child1, "window.name = 'child1';"));

    // Have |child2| initiate navigation of |child1| - the navigation should
    // result in ERR_BLOCKED_BY_CLIENT (because of the throttle created below).
    content::TestNavigationThrottleInserter throttle_inserter(
        shell()->web_contents(),
        base::BindRepeating(&RequestBlockingNavigationThrottle::Create));
    const char kScriptTemplate[] = R"(
        var child1 = window.open('', 'child1');
        child1.location = $1;
    )";
    scoped_refptr<SiteInstance> initial_site_instance =
        child2->current_frame_host()->GetSiteInstance();
    TestNavigationObserver nav_observer(shell()->web_contents());
    ASSERT_TRUE(ExecJs(child2, JsReplace(kScriptTemplate, test_url)));
    nav_observer.Wait();
    EXPECT_FALSE(nav_observer.last_navigation_succeeded());
    EXPECT_EQ(4, nav_controller.GetEntryCount());
    EXPECT_EQ(test_url, child1->current_frame_host()->GetLastCommittedURL());

    // Error pages should commit in an opaque origin.
    EXPECT_TRUE(IsOriginOpaqueAndCompatibleWithURL(child1, test_url));

    // net::ERR_BLOCKED_BY_CLIENT errors in subframes should commit in the
    // the correct process based on whether isolation is enabled or not.
    EXPECT_TRUE(IsExpectedSubframeErrorTransition(
        initial_site_instance.get(),
        child1->current_frame_host()->GetSiteInstance()));
  }

  // Reload the subframe when no longer blocking the navigation.
  {
    TestNavigationObserver nav_observer(shell()->web_contents());
    // Note that some error pages actually do embed a button that will do an
    // equivalent of the renderer-initiated reload that is triggered below.
    ASSERT_TRUE(ExecJs(child1, "window.location.reload()"));
    nav_observer.Wait();

    EXPECT_TRUE(nav_observer.last_navigation_succeeded());
    EXPECT_EQ(4, nav_controller.GetEntryCount());
    EXPECT_EQ(test_url, child1->current_frame_host()->GetLastCommittedURL());
    EXPECT_EQ(url::Origin::Create(test_url),
              child1->current_frame_host()->GetLastCommittedOrigin());

    SiteInstanceImpl* child1_site_instance =
        child1->current_frame_host()->GetSiteInstance();

    GURL c_site_url = child1_site_instance->GetSiteURL();
    if (AreDefaultSiteInstancesEnabled()) {
      EXPECT_TRUE(child1_site_instance->IsDefaultSiteInstance());
    } else {
      EXPECT_EQ("c.com", c_site_url.host());
      EXPECT_EQ(test_url.host(), c_site_url.host());
    }
    EXPECT_NE(a_site_url, c_site_url);
    EXPECT_NE(b_site_url, c_site_url);
  }
}

// Make sure that reload works properly if it redirects to a different site than
// the initial navigation.  The initial purpose of this test was to make sure
// the corresponding unit test matches the actual product code behavior
// (e.g. see NavigationControllerTest.Reload_GeneratesNewPage).
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       ReloadRedirectsToDifferentCrossSitePage) {
  // Set-up http server handlers for |start_url|.
  //
  // |response1| is only required to make sure that |response2| doesn't kick-in
  // and intercept the http request until step 4.  Note that step 3 won't hit
  // the http server and therefore doesn't require handling here.
  auto response1 = std::make_unique<net::test_server::ControllableHttpResponse>(
      embedded_test_server(), "/title1.html");
  auto response2 = std::make_unique<net::test_server::ControllableHttpResponse>(
      embedded_test_server(), "/title1.html");

  // Start the server after all the required handlers have been already
  // registered.
  StartEmbeddedServer();
  NavigationControllerImpl& nav_controller =
      static_cast<NavigationControllerImpl&>(
          shell()->web_contents()->GetController());

  // URLs used in the test:
  // - Step1: Navigate to |start_url|
  // - Step2: Navigate to |second_url|
  // - Step3: Go back (to |start_url|)
  // - Step4: Reload (redirects to a different destination - |redirect_url|).
  GURL start_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
  GURL second_url(embedded_test_server()->GetURL("foo.com", "/title3.html"));
  GURL redirect_url(embedded_test_server()->GetURL("bar.com", "/title2.html"));

  // Test Step 1: Simple navigation that won't redirect and will just
  // successfully commit http://foo.com/title1.html.
  {
    // Navigate...
    TestNavigationObserver nav_observer(shell()->web_contents());
    shell()->LoadURL(start_url);
    response1->WaitForRequest();
    response1->Send(net::HTTP_OK, "text/html; charset=utf-8", "<p>Blah</p>");
    response1->Done();
    nav_observer.Wait();

    // Verify...
    EXPECT_TRUE(nav_observer.last_navigation_succeeded());
    EXPECT_EQ(1, nav_controller.GetEntryCount());
    EXPECT_EQ(0, nav_controller.GetLastCommittedEntryIndex());
    EXPECT_EQ(start_url, nav_controller.GetLastCommittedEntry()->GetURL());
  }

  // Test Step 2: Simple navigation that won't redirect and will just
  // successfully commit http://foo.com/title3.html.
  {
    // Navigate...
    EXPECT_TRUE(NavigateToURL(shell(), second_url));

    // Verify...
    EXPECT_EQ(2, nav_controller.GetEntryCount());
    EXPECT_EQ(1, nav_controller.GetLastCommittedEntryIndex());
    EXPECT_EQ(second_url, nav_controller.GetLastCommittedEntry()->GetURL());
  }

  // Test Step 3: Go back (to |start_url|).
  {
    // Navigate...
    TestNavigationObserver nav_observer(shell()->web_contents());
    nav_controller.GoBack();
    nav_observer.Wait();

    // Verify...
    EXPECT_TRUE(nav_observer.last_navigation_succeeded());
    EXPECT_EQ(2, nav_controller.GetEntryCount());
    EXPECT_EQ(0, nav_controller.GetLastCommittedEntryIndex());
    EXPECT_EQ(start_url, nav_controller.GetLastCommittedEntry()->GetURL());
  }

  // Test Step 4: Reload that will redirect to http://bar.com/title2.html (which
  // is a different, cross-site location compared to what the initial navigation
  // committed).
  {
    // Navigate...
    TestNavigationObserverInternal reload_observer(shell()->web_contents());
    shell()->web_contents()->GetController().Reload(ReloadType::NORMAL, false);
    response2->WaitForRequest();
    response2->Send("HTTP/1.1 302 Moved Temporarily\n");
    response2->Send("Location: " + redirect_url.spec());
    response2->Done();
    reload_observer.Wait();

    // Verify that reload 1) replaced the current entry (rather than creating a
    // new entry) and 2) the tail of the history (e.g. the |second_url|
    // navigation) was preserved rather than truncated.
    EXPECT_TRUE(reload_observer.last_navigation_succeeded());
    EXPECT_EQ(2, nav_controller.GetEntryCount());
    EXPECT_EQ(0, nav_controller.GetLastCommittedEntryIndex());
    EXPECT_EQ(redirect_url, nav_controller.GetLastCommittedEntry()->GetURL());
    EXPECT_EQ(second_url, nav_controller.GetEntryAtIndex(1)->GetURL());
    if (AreAllSitesIsolatedForTesting()) {
      // The successful reload should be classified as a NEW_ENTRY navigation
      // with replacement, since it needs to stay at the same entry in session
      // history, but needs a new entry because of the change in SiteInstance.
      // (the same as expectations in the ErrorPageNavigationReload test above).
      EXPECT_EQ(NavigationType::NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY,
                reload_observer.last_navigation_type());
    } else {
      EXPECT_EQ(NavigationType::NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY,
                reload_observer.last_navigation_type());
    }
  }
}

// Test to verify that navigating away from an error page results in correct
// change in SiteInstance.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       ErrorPageNavigationAfterError) {
  // This test is only valid if error page isolation is enabled.
  if (!SiteIsolationPolicy::IsErrorPageIsolationEnabled(true))
    return;

  StartEmbeddedServer();
  GURL url(embedded_test_server()->GetURL("/title1.html"));
  GURL error_url(embedded_test_server()->GetURL("/empty.html"));
  std::unique_ptr<URLLoaderInterceptor> url_interceptor =
      SetupRequestFailForURL(error_url);
  NavigationControllerImpl& nav_controller =
      static_cast<NavigationControllerImpl&>(
          shell()->web_contents()->GetController());

  // Start with a successful navigation to a document.
  EXPECT_TRUE(NavigateToURL(shell(), url));
  scoped_refptr<SiteInstance> success_site_instance =
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  EXPECT_EQ(1, nav_controller.GetEntryCount());

  // Navigate to an url resulting in an error page.
  EXPECT_FALSE(NavigateToURL(shell(), error_url));
  EXPECT_TRUE(HasErrorPageSiteInfo(
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance()));
  EXPECT_TRUE(HasErrorPageProcessLock(
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance()));
  EXPECT_EQ(2, nav_controller.GetEntryCount());
  EXPECT_TRUE(IsMainFrameOriginOpaqueAndCompatibleWithURL(shell(), error_url));

  // Navigate again to the initial successful document, expecting a new
  // navigation and new SiteInstance. A new SiteInstance is expected here
  // because we are doing a cross-site navigation from an error page
  // to a site for |url|. This triggers the creation of a new BrowsingInstance
  // and therefore a new SiteInstance.
  EXPECT_TRUE(NavigateToURL(shell(), url));
  EXPECT_FALSE(HasErrorPageSiteInfo(
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance()));
  if (AreDefaultSiteInstancesEnabled()) {
    // Verify that we get the default SiteInstance because the original URL does
    // not require a dedicated process.
    EXPECT_TRUE(
        static_cast<SiteInstanceImpl*>(
            shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance())
            ->IsDefaultSiteInstance());
  }
  EXPECT_EQ(success_site_instance->GetSiteURL(), shell()
                                                     ->web_contents()
                                                     ->GetPrimaryMainFrame()
                                                     ->GetSiteInstance()
                                                     ->GetSiteURL());
  EXPECT_NE(success_site_instance,
            shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());

  EXPECT_EQ(3, nav_controller.GetEntryCount());

  // Repeat again using a renderer-initiated navigation for the successful one.
  EXPECT_FALSE(NavigateToURL(shell(), error_url));
  EXPECT_TRUE(HasErrorPageSiteInfo(
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance()));
  EXPECT_TRUE(HasErrorPageProcessLock(
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance()));
  EXPECT_EQ(4, nav_controller.GetEntryCount());
  {
    TestNavigationObserver observer(shell()->web_contents());
    EXPECT_TRUE(ExecJs(shell(), "location.href = '" + url.spec() + "';"));
    observer.Wait();
    EXPECT_TRUE(observer.last_navigation_succeeded());
  }
  EXPECT_EQ(5, nav_controller.GetEntryCount());
  EXPECT_FALSE(HasErrorPageSiteInfo(
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance()));
}

// Test to verify that when an error page is hit and its process is terminated,
// a successful reload correctly commits in a different process.
// See https://crbug.com/866549.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       ErrorPageNavigationReloadWithTerminatedProcess) {
  // This test is only valid if error page isolation is enabled.
  if (!SiteIsolationPolicy::IsErrorPageIsolationEnabled(true))
    return;

  StartEmbeddedServer();
  GURL url(embedded_test_server()->GetURL("/title1.html"));
  GURL error_url(embedded_test_server()->GetURL("/empty.html"));
  std::unique_ptr<URLLoaderInterceptor> url_interceptor =
      SetupRequestFailForURL(error_url);
  WebContents* web_contents = shell()->web_contents();
  NavigationControllerImpl& nav_controller =
      static_cast<NavigationControllerImpl&>(web_contents->GetController());

  // Start with a successful navigation to a document.
  EXPECT_TRUE(NavigateToURL(shell(), url));
  scoped_refptr<SiteInstance> success_site_instance =
      web_contents->GetPrimaryMainFrame()->GetSiteInstance();
  EXPECT_EQ(1, nav_controller.GetEntryCount());

  // Navigate to an url resulting in an error page.
  EXPECT_FALSE(NavigateToURL(shell(), error_url));
  EXPECT_TRUE(HasErrorPageSiteInfo(
      web_contents->GetPrimaryMainFrame()->GetSiteInstance()));
  EXPECT_TRUE(HasErrorPageProcessLock(
      web_contents->GetPrimaryMainFrame()->GetSiteInstance()));
  EXPECT_EQ(2, nav_controller.GetEntryCount());
  EXPECT_TRUE(IsMainFrameOriginOpaqueAndCompatibleWithURL(shell(), error_url));

  // Terminate the renderer process.
  {
    RenderProcessHostWatcher termination_observer(
        web_contents->GetPrimaryMainFrame()->GetProcess(),
        RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
    web_contents->GetPrimaryMainFrame()->GetProcess()->Shutdown(0);
    termination_observer.Wait();
  }

  // Clear the interceptor so the navigation will succeed on reload.
  url_interceptor.reset();

  // Reload the URL and execute a Javascript statement to verify that the
  // renderer process is still around and responsive.
  TestNavigationObserver reload_observer(shell()->web_contents());
  nav_controller.Reload(ReloadType::NORMAL, false);
  reload_observer.Wait();
  EXPECT_TRUE(reload_observer.last_navigation_succeeded());

  EXPECT_EQ(error_url.spec(), EvalJs(shell(), "location.href;"));
}

// Test to verify that navigation to existing history entry, which results in
// an error page, is correctly placed in the error page SiteInstance.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       ErrorPageNavigationHistoryNavigationFailure) {
  // This test is only valid if error page isolation is enabled.
  if (!SiteIsolationPolicy::IsErrorPageIsolationEnabled(true))
    return;

  StartEmbeddedServer();

  // Perform successful navigations to two URLs to establish session history.
  GURL url1(embedded_test_server()->GetURL("a.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), url1));

  GURL url2(embedded_test_server()->GetURL("b.com", "/title2.html"));
  EXPECT_TRUE(NavigateToURL(shell(), url2));

  WebContents* web_contents = shell()->web_contents();
  NavigationControllerImpl& nav_controller =
      static_cast<NavigationControllerImpl&>(web_contents->GetController());

  // There should be two NavigationEntries.
  EXPECT_EQ(2, nav_controller.GetEntryCount());

  // Ensure that previous document won't be restored from the BackForwardCache,
  // to force a network fetch, which would result in a network error.
  DisableBackForwardCache(BackForwardCacheImpl::TEST_REQUIRES_NO_CACHING);

  // Create an interceptor to cause navigations to url1 to fail and go back
  // in session history.
  std::unique_ptr<URLLoaderInterceptor> url_interceptor =
      SetupRequestFailForURL(url1);
  TestNavigationObserver back_observer(web_contents);
  nav_controller.GoBack();
  back_observer.Wait();
  EXPECT_FALSE(back_observer.last_navigation_succeeded());
  EXPECT_EQ(2, nav_controller.GetEntryCount());
  EXPECT_EQ(0, nav_controller.GetLastCommittedEntryIndex());

  EXPECT_TRUE(HasErrorPageSiteInfo(
      web_contents->GetPrimaryMainFrame()->GetSiteInstance()));
  EXPECT_TRUE(HasErrorPageProcessLock(
      web_contents->GetPrimaryMainFrame()->GetSiteInstance()));
  EXPECT_TRUE(IsMainFrameOriginOpaqueAndCompatibleWithURL(shell(), url1));
}

// Test to verify that a successful navigation to existing history entry,
// which initially resulted in an error page, is correctly placed in a
// SiteInstance different than the error page one.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       ErrorPageNavigationHistoryNavigationSuccess) {
  // This test is only valid if error page isolation is enabled.
  if (!SiteIsolationPolicy::IsErrorPageIsolationEnabled(true))
    return;

  StartEmbeddedServer();
  WebContents* web_contents = shell()->web_contents();

  // Start with a successful navigation.
  GURL url1(embedded_test_server()->GetURL("a.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), url1));

  // Navigate to URL that results in an error page and verify its SiteInstance.
  GURL url2(embedded_test_server()->GetURL("b.com", "/title2.html"));
  std::unique_ptr<URLLoaderInterceptor> url_interceptor =
      SetupRequestFailForURL(url2);

  EXPECT_FALSE(NavigateToURL(shell(), url2));
  EXPECT_TRUE(HasErrorPageSiteInfo(
      web_contents->GetPrimaryMainFrame()->GetSiteInstance()));
  EXPECT_TRUE(HasErrorPageProcessLock(
      web_contents->GetPrimaryMainFrame()->GetSiteInstance()));
  EXPECT_TRUE(IsMainFrameOriginOpaqueAndCompatibleWithURL(shell(), url2));

  // There should be two NavigationEntries.
  NavigationControllerImpl& nav_controller =
      static_cast<NavigationControllerImpl&>(web_contents->GetController());
  EXPECT_EQ(2, nav_controller.GetEntryCount());

  // Navigate once more to create another session history entry.
  GURL url3(embedded_test_server()->GetURL("c.com", "/title3.html"));
  EXPECT_TRUE(NavigateToURL(shell(), url3));
  EXPECT_EQ(3, nav_controller.GetEntryCount());

  // Navigate back, this time remove the interceptor so the navigation will
  // succeed.
  url_interceptor.reset();
  TestNavigationObserver back_observer(web_contents);
  nav_controller.GoBack();
  back_observer.Wait();
  EXPECT_TRUE(back_observer.last_navigation_succeeded());
  EXPECT_EQ(3, nav_controller.GetEntryCount());
  EXPECT_EQ(1, nav_controller.GetLastCommittedEntryIndex());

  EXPECT_FALSE(HasErrorPageSiteInfo(
      web_contents->GetPrimaryMainFrame()->GetSiteInstance()));
  EXPECT_FALSE(HasErrorPageProcessLock(
      web_contents->GetPrimaryMainFrame()->GetSiteInstance()));
}

// Test to verify that navigations to WebUI URL which results in an error
// commits properly in the error page process and does not give it WebUI
// bindings.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       ErrorPageNavigationToWebUIResourceWithError) {
  // This test is only valid if error page isolation is enabled.
  if (!SiteIsolationPolicy::IsErrorPageIsolationEnabled(true))
    return;

  GURL webui_url = GetWebUIURL(kChromeUIGpuHost);
  GURL error_url(webui_url.Resolve("/foo"));

  // Navigate to the main WebUI URL and ensure it is successful.
  EXPECT_TRUE(NavigateToURL(shell(), webui_url));

  // Ensure that the subsequent navigation is blocked, resulting in an
  // error.
  TestNavigationThrottleInserter throttle_inserter(
      shell()->web_contents(),
      base::BindRepeating(&RequestBlockingNavigationThrottle::Create));

  // Navigate to a WebUI URL and verify the resulting error page process does
  // not get WebUI bindings.
  NavigationHandleObserver observer(shell()->web_contents(), error_url);
  EXPECT_FALSE(NavigateToURL(shell(), error_url));
  scoped_refptr<SiteInstance> error_site_instance =
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  EXPECT_TRUE(observer.is_error());
  EXPECT_TRUE(HasErrorPageSiteInfo(error_site_instance.get()));
  EXPECT_TRUE(HasErrorPageProcessLock(error_site_instance.get()));
  EXPECT_FALSE(ChildProcessSecurityPolicy::GetInstance()->HasWebUIBindings(
      error_site_instance->GetProcess()->GetID()));
  EXPECT_TRUE(IsMainFrameOriginOpaqueAndCompatibleWithURL(shell(), error_url));
}

// If a WebUI page leads to an error page and is then reloaded successfully from
// its NavigationEntry, ensure that WebUI bindings are granted and that we don't
// crash. See https://crbug.com/1046159.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       ReloadWebUIErrorPageToValidWebUI) {
  // This test is only valid if error page isolation is enabled.
  if (!SiteIsolationPolicy::IsErrorPageIsolationEnabled(true))
    return;

  GURL webui_url = GetWebUIURL(kChromeUIGpuHost);

  // Temporarily insert throttles that will block all navigations, leading to
  // error pages instead.
  {
    TestNavigationThrottleInserter throttle_inserter(
        shell()->web_contents(),
        base::BindRepeating(&RequestBlockingNavigationThrottle::Create));

    // Navigate to a WebUI URL and verify the resulting error page process does
    // not get WebUI bindings.
    NavigationHandleObserver observer(shell()->web_contents(), webui_url);
    EXPECT_FALSE(NavigateToURL(shell(), webui_url));
    EXPECT_TRUE(observer.is_error());
    scoped_refptr<SiteInstance> error_site_instance =
        shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
    EXPECT_TRUE(HasErrorPageSiteInfo(error_site_instance.get()));
    EXPECT_FALSE(ChildProcessSecurityPolicy::GetInstance()->HasWebUIBindings(
        error_site_instance->GetProcess()->GetID()));
  }

  // Once the throttles are no longer inserted into each navigation, reloading
  // the NavigationEntry should succeed and grant WebUI bindings.
  {
    TestNavigationObserver reload_observer(shell()->web_contents());
    shell()->web_contents()->GetController().Reload(ReloadType::NORMAL, false);
    reload_observer.Wait();
    EXPECT_TRUE(reload_observer.last_navigation_succeeded());
  }
  scoped_refptr<SiteInstance> webui_site_instance =
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  EXPECT_EQ(webui_url, webui_site_instance->GetSiteURL());
  EXPECT_TRUE(ChildProcessSecurityPolicy::GetInstance()->HasWebUIBindings(
      webui_site_instance->GetProcess()->GetID()));

  // A second reload should work without crashing the browser process.
  {
    TestNavigationObserver reload_observer(shell()->web_contents());
    shell()->web_contents()->GetController().Reload(ReloadType::NORMAL, false);
    reload_observer.Wait();
    EXPECT_TRUE(reload_observer.last_navigation_succeeded());
  }
}
// A custom ContentBrowserClient that simulates GetEffectiveURL() translation
// for all URLs that are in the same page (including URL with refs).
class PageEffectiveURLContentBrowserClient
    : public ContentBrowserTestContentBrowserClient {
 public:
  PageEffectiveURLContentBrowserClient(const GURL& url_to_modify,
                                       const GURL& url_to_return)
      : url_to_modify_(url_to_modify), url_to_return_(url_to_return) {}

  PageEffectiveURLContentBrowserClient(
      const PageEffectiveURLContentBrowserClient&) = delete;
  PageEffectiveURLContentBrowserClient& operator=(
      const PageEffectiveURLContentBrowserClient&) = delete;

  ~PageEffectiveURLContentBrowserClient() override = default;

 private:
  GURL GetEffectiveURL(BrowserContext* browser_context,
                       const GURL& url) override {
    if (url.EqualsIgnoringRef(url_to_modify_))
      return url_to_return_;
    return url;
  }

  GURL url_to_modify_;
  GURL url_to_return_;
};

// Ensure that same-document navigations for URLs with effective URLs don't
// incorrectly swap BrowsingInstance. See crbug.com/1073540.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       NavigationToSameDocumentWithEffectiveURL) {
  StartEmbeddedServer();
  const GURL page_url(embedded_test_server()->GetURL("/title1.html"));
  const GURL anchor_in_page_url(
      embedded_test_server()->GetURL("/title1.html#bar"));
  const GURL effective_url("http://foo.com");
  auto* web_contents = static_cast<WebContentsImpl*>(shell()->web_contents());
  // The effective URL for |page_url| and |anchor_in_page_url| will be
  // |effective_url|.
  PageEffectiveURLContentBrowserClient modified_client(page_url, effective_url);

  // Make a navigation to |page_url|.
  EXPECT_TRUE(NavigateToURL(shell(), page_url));
  EXPECT_EQ(web_contents->GetLastCommittedURL(), page_url);
  scoped_refptr<SiteInstance> orig_site_instance =
      web_contents->GetPrimaryMainFrame()->GetSiteInstance();

  // Navigate to #bar in the same document.
  EXPECT_TRUE(NavigateToURL(shell(), anchor_in_page_url));
  EXPECT_EQ(web_contents->GetLastCommittedURL(), anchor_in_page_url);
  // We should reuse the same SiteInstance.
  EXPECT_EQ(orig_site_instance,
            web_contents->GetPrimaryMainFrame()->GetSiteInstance());
}

// A test ContentBrowserClient implementation which enforces
// BrowsingInstance swap on every navigation. It is used to verify that
// reloading of an error page to an URL that requires BrowsingInstance swap
// works correctly.
class BrowsingInstanceSwapContentBrowserClient
    : public ContentBrowserTestContentBrowserClient {
 public:
  BrowsingInstanceSwapContentBrowserClient() = default;

  BrowsingInstanceSwapContentBrowserClient(
      const BrowsingInstanceSwapContentBrowserClient&) = delete;
  BrowsingInstanceSwapContentBrowserClient& operator=(
      const BrowsingInstanceSwapContentBrowserClient&) = delete;

  bool ShouldIsolateErrorPage(bool in_main_frame) override {
    return in_main_frame;
  }

  bool ShouldSwapBrowsingInstancesForNavigation(
      content::SiteInstance* site_instance,
      const GURL& current_effective_url,
      const GURL& destination_effective_url) override {
    return true;
  }
};

// Test to verify that reloading of an error page which resulted from a
// navigation to an URL which requires a BrowsingInstance swap, correcly
// reloads in the same SiteInstance for the error page.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       ErrorPageNavigationReloadBrowsingInstanceSwap) {
  StartEmbeddedServer();
  GURL url(embedded_test_server()->GetURL("a.com", "/title1.html"));
  GURL error_url(embedded_test_server()->GetURL("b.com", "/empty.html"));
  std::unique_ptr<URLLoaderInterceptor> url_interceptor =
      SetupRequestFailForURL(error_url);
  NavigationControllerImpl& nav_controller =
      static_cast<NavigationControllerImpl&>(
          shell()->web_contents()->GetController());

  // Start with a successful navigation to a document and verify there is
  // only one entry in session history.
  EXPECT_TRUE(NavigateToURL(shell(), url));
  scoped_refptr<SiteInstance> success_site_instance =
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  EXPECT_EQ(1, nav_controller.GetEntryCount());

  // Navigate to an url resulting in an error page and ensure a new entry
  // was added to session history.
  EXPECT_FALSE(NavigateToURL(shell(), error_url));
  EXPECT_EQ(2, nav_controller.GetEntryCount());

  scoped_refptr<SiteInstance> initial_instance =
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance();
  EXPECT_TRUE(HasErrorPageSiteInfo(initial_instance.get()));
  EXPECT_TRUE(IsMainFrameOriginOpaqueAndCompatibleWithURL(shell(), error_url));
  if (CanCrossSiteNavigationsProactivelySwapBrowsingInstances()) {
    EXPECT_FALSE(
        success_site_instance->IsRelatedSiteInstance(initial_instance.get()));
  } else {
    EXPECT_TRUE(
        success_site_instance->IsRelatedSiteInstance(initial_instance.get()));
  }

  // Reload of the error page that still results in an error should stay in
  // the same SiteInstance. Ensure this works for both browser-initiated
  // reloads and renderer-initiated ones.
  {
    TestNavigationObserver reload_observer(shell()->web_contents());
    shell()->web_contents()->GetController().Reload(ReloadType::NORMAL, false);
    reload_observer.Wait();
    EXPECT_FALSE(reload_observer.last_navigation_succeeded());
    EXPECT_EQ(2, nav_controller.GetEntryCount());
    EXPECT_EQ(
        initial_instance,
        shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());
    EXPECT_TRUE(
        IsMainFrameOriginOpaqueAndCompatibleWithURL(shell(), error_url));
  }
  {
    TestNavigationObserver reload_observer(shell()->web_contents());
    EXPECT_TRUE(ExecJs(shell(), "location.reload();"));
    reload_observer.Wait();
    EXPECT_FALSE(reload_observer.last_navigation_succeeded());
    EXPECT_EQ(2, nav_controller.GetEntryCount());
    EXPECT_EQ(
        initial_instance,
        shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());
    EXPECT_TRUE(
        IsMainFrameOriginOpaqueAndCompatibleWithURL(shell(), error_url));
  }

  // Install a client forcing every navigation to swap BrowsingInstances.
  BrowsingInstanceSwapContentBrowserClient content_browser_client;

  // Allow the navigation to succeed and ensure it swapped to a non-related
  // SiteInstance.
  url_interceptor.reset();
  {
    TestNavigationObserver reload_observer(shell()->web_contents());
    EXPECT_TRUE(ExecJs(shell(), "location.reload();"));
    reload_observer.Wait();
    EXPECT_TRUE(reload_observer.last_navigation_succeeded());
    EXPECT_EQ(2, nav_controller.GetEntryCount());
    EXPECT_FALSE(initial_instance->IsRelatedSiteInstance(
        shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance()));
    EXPECT_FALSE(success_site_instance->IsRelatedSiteInstance(
        shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance()));
  }
}

// Helper class to simplify testing of unload handlers.  It allows waiting for
// particular HTTP requests to be made to the embedded_test_server(); the tests
// use this to wait for termination pings (e.g., navigator.sendBeacon()) made
// from unload handlers.
class RenderFrameHostManagerUnloadBrowserTest
    : public RenderFrameHostManagerTest {
 public:
  RenderFrameHostManagerUnloadBrowserTest() = default;

  RenderFrameHostManagerUnloadBrowserTest(
      const RenderFrameHostManagerUnloadBrowserTest&) = delete;
  RenderFrameHostManagerUnloadBrowserTest& operator=(
      const RenderFrameHostManagerUnloadBrowserTest&) = delete;

  // Starts monitoring requests made to the embedded_test_server() looking for
  // one made to |url|.  To be used together with WaitForMonitoredRequest().
  void StartMonitoringRequestsFor(const GURL& url) {
    base::AutoLock lock(lock_);
    request_url_ = url;
    saw_request_url_ = false;
  }

  // Waits for a request to a URL set earlier via StartMonitoringRequestsFor().
  // Returns right away if that request was already made.
  void WaitForMonitoredRequest() {
    base::AutoLock lock(lock_);
    if (saw_request_url_)
      return;

    run_loop_ = std::make_unique<base::RunLoop>();
    {
      base::RunLoop* run_loop = run_loop_.get();
      base::AutoUnlock unlock(lock_);
      run_loop->Run();
    }
    run_loop_.reset();
  }

  // Returns the body of the monitored request if it was a POST.
  const std::string& GetRequestContent() {
    base::AutoLock lock(lock_);
    return request_content_;
  }

  blink::mojom::SuddenTerminationDisablerType DisablerTypeForEvent(
      const std::string& event_name) {
    if (event_name == "unload")
      return blink::mojom::SuddenTerminationDisablerType::kUnloadHandler;
    if (event_name == "beforeunload")
      return blink::mojom::SuddenTerminationDisablerType::kBeforeUnloadHandler;
    if (event_name == "pagehide")
      return blink::mojom::SuddenTerminationDisablerType::kPageHideHandler;
    if (event_name == "visibilitychange")
      return blink::mojom::SuddenTerminationDisablerType::
          kVisibilityChangeHandler;
    NOTREACHED_IN_MIGRATION();
    return blink::mojom::SuddenTerminationDisablerType::kUnloadHandler;
  }

  // Returns the list of event targets that the given `event_name` should be
  // registered on.
  // Since the `visibilitychange` event is fired at the document and it
  // may bubble up to the window, we should test the cases where the event
  // listener is registered on both the document and the window.
  std::vector<std::string> EventTargetsForEvent(const std::string& event_name) {
    if (event_name == "unload" || event_name == "beforeunload" ||
        event_name == "pagehide") {
      return {"window"};
    }
    if (event_name == "visibilitychange") {
      return {"window", "document"};
    }
    NOTREACHED_IN_MIGRATION();
    return {};
  }

  // Adds an unload event handler (can be for the unload, pagehide, or
  // visibilitychange event) to |rfh| and verifies that the unload state
  // bookkeeping on |rfh| is updated properly.
  void AddUnloadEventHandler(RenderFrameHostImpl* rfh,
                             const std::string& event_name,
                             const std::string& event_target,
                             const std::string& script) {
    EXPECT_THAT(event_name,
                testing::AnyOf(testing::Eq("unload"), testing::Eq("pagehide"),
                               testing::Eq("visibilitychange")));
    EXPECT_FALSE(rfh->GetSuddenTerminationDisablerState(
        DisablerTypeForEvent(event_name)));
    EXPECT_FALSE(rfh->has_unload_handlers());
    EXPECT_TRUE(ExecJs(
        rfh, base::StringPrintf("%s.addEventListener('%s', (e) => { %s });",
                                event_target.c_str(), event_name.c_str(),
                                script.c_str())));
    EXPECT_TRUE(rfh->GetSuddenTerminationDisablerState(
        DisablerTypeForEvent(event_name)));
    EXPECT_TRUE(rfh->has_unload_handlers());
  }

  // Extend the timeout for keeping the subframe process alive for unload
  // processing to prevent any test flakiness.  This is the time that the ping
  // request will have to make it from the renderer to the test server.
  void ExtendSubframeUnloadTimeoutForTerminationPing(RenderFrameHostImpl* rfh) {
    rfh->SetSubframeUnloadTimeoutForTesting(base::Seconds(30));
  }

  void SetUpCommandLine(base::CommandLine* command_line) override {
    RenderFrameHostManagerTest::SetUpCommandLine(command_line);
    feature_list_.InitAndDisableFeature(blink::features::kDeprecateUnload);
  }

 protected:
  void SetUpOnMainThread() override {
    // Request interceptor needs to be installed before the test server is
    // started.
    embedded_test_server()->RegisterRequestMonitor(base::BindRepeating(
        &RenderFrameHostManagerUnloadBrowserTest::MonitorResourceRequest,
        base::Unretained(this)));

    RenderFrameHostManagerTest::SetUpOnMainThread();
  }

 private:
  void MonitorResourceRequest(const net::test_server::HttpRequest& request) {
    // |request.GetURL()| gives us the URL after it's already resolved to
    // 127.0.0.1, so reconstruct the requested host via the Host header (which
    // includes host+port).
    GURL requested_url = request.GetURL();
    auto it = request.headers.find("Host");
    if (it != request.headers.end())
      requested_url = GURL("http://" + it->second + request.relative_url);

    base::AutoLock lock(lock_);
    if (!saw_request_url_ && request_url_ == requested_url) {
      saw_request_url_ = true;
      request_content_ = request.content;
      if (run_loop_)
        run_loop_->Quit();
    }
  }

  base::Lock lock_;
  GURL request_url_ GUARDED_BY(lock_);
  std::string request_content_ GUARDED_BY(lock_);
  bool saw_request_url_ GUARDED_BY(lock_) = false;
  std::unique_ptr<base::RunLoop> run_loop_ GUARDED_BY(lock_);
  base::test::ScopedFeatureList feature_list_;
};

// Ensure that after a main frame with a cross-site iframe is itself navigated
// cross-site, the unload event handlers (for unload, pagehide, or
// visibilitychange events) in the iframe can use navigator.sendBeacon() to do a
// termination ping.  See https://crbug.com/852204, where this was broken with
// site isolation if the iframe was in its own process.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerUnloadBrowserTest,
                       SubframeTerminationPing_SendBeacon) {
  StartEmbeddedServer();
  // See BackForwardCache::DisableForTestingReason for explanation.
  DisableBackForwardCache(BackForwardCacheImpl::TEST_USES_UNLOAD_EVENT);
  const std::string unload_event_names[] = {"unload", "pagehide",
                                            "visibilitychange"};
  GURL main_url(embedded_test_server()->GetURL(
      "a.com", "/cross_site_iframe_factory.html?a(b)"));
  GURL ping_url(embedded_test_server()->GetURL("b.com", "/empty.html"));
  GURL c_url(embedded_test_server()->GetURL("c.com", "/title1.html"));

  for (const std::string& unload_event_name : unload_event_names) {
    for (const std::string& unload_event_target :
         EventTargetsForEvent(unload_event_name)) {
      EXPECT_TRUE(NavigateToURL(shell(), main_url));
      FrameTreeNode* root =
          static_cast<WebContentsImpl*>(shell()->web_contents())
              ->GetPrimaryFrameTree()
              .root();
      RenderFrameHostImpl* child_rfh = root->child_at(0)->current_frame_host();
      // Add a subframe unload handler to do a termination ping via sendBeacon.
      AddUnloadEventHandler(
          child_rfh, unload_event_name, unload_event_target,
          base::StringPrintf("navigator.sendBeacon('%s', 'ping');",
                             ping_url.spec().c_str()));
      ExtendSubframeUnloadTimeoutForTerminationPing(child_rfh);

      // Navigate the main frame to c.com and wait for the ping.
      StartMonitoringRequestsFor(ping_url);
      EXPECT_TRUE(NavigateToURL(shell(), c_url));
      // Test succeeds if this doesn't time out while waiting for |ping_url|.
      WaitForMonitoredRequest();
      EXPECT_EQ("ping", GetRequestContent());
    }
  }
}

// Ensure that after a main frame with a cross-site iframe is itself navigated
// cross-site, the pagehide handler in the iframe can use an image load to do a
// termination ping. See https://crbug.com/852204, where this was broken with
// site isolation if the iframe was in its own process.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerUnloadBrowserTest,
                       SubframeTerminationPing_Image) {
  StartEmbeddedServer();
  // See BackForwardCache::DisableForTestingReason for explanation.
  DisableBackForwardCache(BackForwardCacheImpl::TEST_REQUIRES_NO_CACHING);

  GURL main_url(embedded_test_server()->GetURL(
      "a.com", "/cross_site_iframe_factory.html?a(b)"));
  EXPECT_TRUE(NavigateToURL(shell(), main_url));
  FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
                            ->GetPrimaryFrameTree()
                            .root();
  RenderFrameHostImpl* child_rfh = root->child_at(0)->current_frame_host();

  // Add a subframe pagehide handler to do a termination ping by loading an
  // image.
  GURL ping_url(embedded_test_server()->GetURL("b.com", "/blank.jpg"));
  AddUnloadEventHandler(
      child_rfh, "pagehide", "window",
      base::StringPrintf("var img = document.createElement('img');"
                         "img.src = '%s';"
                         "document.body.appendChild(img);",
                         ping_url.spec().c_str()));
  ExtendSubframeUnloadTimeoutForTerminationPing(child_rfh);

  // Navigate the main frame to c.com and wait for the ping.
  StartMonitoringRequestsFor(ping_url);
  GURL c_url(embedded_test_server()->GetURL("c.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), c_url));
  // Test succeeds if this doesn't time out while waiting for |ping_url|.
  WaitForMonitoredRequest();
}

// Ensure that when closing a window containing a page with a cross-site
// iframe, the iframe still runs its pagehide handler and can do a sendBeacon
// termination ping.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerUnloadBrowserTest,
                       SubframeTerminationPingWhenWindowCloses) {
  StartEmbeddedServer();
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("a.com", "/title1.html")));
  FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
                            ->GetPrimaryFrameTree()
                            .root();

  // Open a popup window with a page containing a cross-site iframe.
  GURL popup_url(embedded_test_server()->GetURL(
      "b.com", "/cross_site_iframe_factory.html?b(c)"));
  Shell* popup = OpenPopup(root, popup_url, "popup");
  WebContentsImpl* popup_contents =
      static_cast<WebContentsImpl*>(popup->web_contents());
  EXPECT_TRUE(WaitForLoadStop(popup_contents));
  EXPECT_EQ(popup_url, popup_contents->GetLastCommittedURL());

  FrameTreeNode* popup_root = popup_contents->GetPrimaryFrameTree().root();
  RenderFrameHostImpl* child_rfh =
      popup_root->child_at(0)->current_frame_host();

  // In the popup, add a subframe pagehide handler to do a termination ping via
  // sendBeacon.
  GURL ping_url(embedded_test_server()->GetURL("c.com", "/empty.html"));
  AddUnloadEventHandler(
      child_rfh, "pagehide", "window",
      base::StringPrintf("navigator.sendBeacon('%s', 'ping');",
                         ping_url.spec().c_str()));
  ExtendSubframeUnloadTimeoutForTerminationPing(child_rfh);

  // Close the popup and wait for the ping.
  StartMonitoringRequestsFor(ping_url);
  popup->Close();
  // Test succeeds if this doesn't time out while waiting for |ping_url|.
  WaitForMonitoredRequest();
  EXPECT_EQ("ping", GetRequestContent());
}

// Ensure that after a main frame with a cross-site iframe is navigated
// cross-site, and the iframe had a pagehide handler which never finishes,
// the iframe's process eventually exits.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerUnloadBrowserTest,
                       SubframeProcessGoesAwayAfterUnloadTimeout) {
  StartEmbeddedServer();
  // See BackForwardCache::DisableForTestingReason for explanation.
  DisableBackForwardCache(BackForwardCacheImpl::TEST_REQUIRES_NO_CACHING);

  GURL main_url(embedded_test_server()->GetURL(
      "a.com", "/cross_site_iframe_factory.html?a(b)"));
  EXPECT_TRUE(NavigateToURL(shell(), main_url));
  FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
                            ->GetPrimaryFrameTree()
                            .root();
  RenderFrameHostImpl* child_rfh = root->child_at(0)->current_frame_host();

  // Add a pagehide handler which never finishes to b.com subframe.
  AddUnloadEventHandler(child_rfh, "pagehide", "window", "while(1);");

  // Navigate the main frame to c.com and wait for the subframe process to
  // shut down.  This should happen when the subframe unload timeout happens,
  // roughly in one second.  Note that depending on whether site isolation is
  // enabled, the subframe process may or may not be the same as the old main
  // frame process, but it should shut down regardless.
  GURL c_url(embedded_test_server()->GetURL("c.com", "/title1.html"));
  RenderProcessHostWatcher process_exit_observer(
      child_rfh->GetProcess(),
      RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
  EXPECT_TRUE(NavigateToURL(shell(), c_url));
  process_exit_observer.Wait();
}

// Verify that when an OOPIF with a pagehide handler navigates cross-process,
// its pagehide handler is able to send a postMessage to the parent frame.
// See https://crbug.com/857274.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerUnloadBrowserTest,
                       PostMessageToParentWhenSubframeNavigates) {
  StartEmbeddedServer();
  GURL main_url(embedded_test_server()->GetURL(
      "a.com", "/cross_site_iframe_factory.html?a(b)"));
  EXPECT_TRUE(NavigateToURL(shell(), main_url));
  FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
                            ->GetPrimaryFrameTree()
                            .root();
  FrameTreeNode* child = root->child_at(0);

  // Add an onmessage listener in the main frame.
  EXPECT_TRUE(ExecJs(root, R"(
    function waitForMessage() {
      return new Promise(resolve => {
        window.addEventListener('message', function(e) {
            resolve(e.data);
        });
      });
    })"));

  // Add a pagehide handler in the child frame to send a postMessage to the
  // parent frame.
  AddUnloadEventHandler(child->current_frame_host(), "pagehide", "window",
                        "parent.postMessage('foo', '*')");
  child->current_frame_host()->DisableUnloadTimerForTesting();

  // Navigate the subframe cross-site to c.com and wait for the message.
  GURL c_url(embedded_test_server()->GetURL("c.com", "/title1.html"));
  EXPECT_EQ("foo",
            EvalJs(root, base::StringPrintf(
                             "var p = waitForMessage();"
                             "document.querySelector('iframe').src = '%s';"
                             "p;",
                             c_url.spec().c_str())));

  // Now repeat the test with a remote-to-local navigation that brings the
  // subframe back to a.com.
  AddUnloadEventHandler(child->current_frame_host(), "pagehide", "window",
                        "parent.postMessage('bar', '*')");
  child->current_frame_host()->DisableUnloadTimerForTesting();
  GURL a_url(embedded_test_server()->GetURL("a.com", "/title2.html"));
  EXPECT_EQ("bar",
            EvalJs(root, base::StringPrintf(
                             "var p = waitForMessage();"
                             "document.querySelector('iframe').src = '%s';"
                             "p;",
                             a_url.spec().c_str())));
}

// Ensure that when a pending delete RenderFrameHost's process dies, the
// current RenderFrameHost does not lose its child frames.  See
// https://crbug.com/867274.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerUnloadBrowserTest,
                       PendingDeleteRFHProcessShutdownDoesNotRemoveSubframes) {
  StartEmbeddedServer();
  GURL first_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), first_url));
  FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
                            ->GetPrimaryFrameTree()
                            .root();
  RenderFrameHostImpl* rfh = root->current_frame_host();

  // Set up a pagehide handler which never finishes to force |rfh| to stay
  // around in pending delete state and never receive the
  // mojo::AgentSchedulingGroupHost::DidUnloadRenderFrame.
  EXPECT_TRUE(ExecJs(rfh, "window.onpagehide = function(e) { while(1); };\n"));
  rfh->DisableUnloadTimerForTesting();

  // Navigate to another page with two subframes.
  RenderFrameDeletedObserver rfh_observer(rfh);

  // Ensure that current document won't enter the BackForwardCache, so that it
  // properly execute its unload handler. So, we disable back-forward cache for
  // this test.
  DisableBackForwardCache(BackForwardCacheImpl::TEST_USES_UNLOAD_EVENT);

  GURL second_url(embedded_test_server()->GetURL(
      "b.com", "/cross_site_iframe_factory.html?b(c,b)"));
  EXPECT_TRUE(NavigateToURL(shell(), second_url));

  // At this point, |rfh| should still be live and pending deletion.
  EXPECT_FALSE(rfh_observer.deleted());
  EXPECT_TRUE(rfh->IsPendingDeletion());
  EXPECT_TRUE(rfh->IsRenderFrameLive());

  // Meanwhile, the new page should have two subframes.
  EXPECT_EQ(2U, root->child_count());

  // Kill the pending delete RFH's process.
  RenderProcessHostWatcher crash_observer(
      rfh->GetProcess(), RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
  rfh->GetProcess()->Shutdown(0);
  crash_observer.Wait();

  // The process kill should simulate a
  // mojo::AgentSchedulingGroupHost::DidUnloadRenderFrame and trigger
  // destruction of the pending delete RFH.
  rfh_observer.WaitUntilDeleted();

  // Ensure that the process kill didn't incorrectly remove subframes from the
  // new page.
  ASSERT_EQ(2U, root->child_count());
  EXPECT_TRUE(root->child_at(0)->current_frame_host()->IsRenderFrameLive());
  EXPECT_TRUE(root->child_at(1)->current_frame_host()->IsRenderFrameLive());
}

// RenderFrameHost should have correct sudden termination disabler
// state after the event listeners are registered and removed.
// Regression test for crbug.com/1341417.
IN_PROC_BROWSER_TEST_P(
    RenderFrameHostManagerUnloadBrowserTest,
    AddAndRemoveEventListenersAffectingSuddenTerminationDisablerState) {
  StartEmbeddedServer();
  const std::string sudden_termination_disabler_event_names[] = {
      "unload", "beforeunload", "pagehide", "visibilitychange"};

  // Initialize the RenderFrameHost.
  GURL first_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
  EXPECT_TRUE(NavigateToURL(shell(), first_url));
  FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
                            ->GetPrimaryFrameTree()
                            .root();
  RenderFrameHostImpl* rfh = root->current_frame_host();

  // Register a callback function so we can remove the event listener later.
  EXPECT_TRUE(ExecJs(rfh, "var callback = (e) => {};\n"));

  for (const std::string& event_name :
       sudden_termination_disabler_event_names) {
    for (const std::string& event_target : EventTargetsForEvent(event_name)) {
      // The sudden termination disabler state is initially set to false.
      EXPECT_FALSE(rfh->GetSuddenTerminationDisablerState(
          DisablerTypeForEvent(event_name)));
      // Now add an event listener for the event_name.
      EXPECT_TRUE(ExecJs(
          rfh, base::StringPrintf("%s.addEventListener('%s', callback);",
                                  event_target.c_str(), event_name.c_str())));
      // The sudden termination disabler state should be true now.
      EXPECT_TRUE(rfh->GetSuddenTerminationDisablerState(
          DisablerTypeForEvent(event_name)));
      // Remove the registered event listener.
      EXPECT_TRUE(ExecJs(
          rfh, base::StringPrintf("%s.removeEventListener('%s', callback);",
                                  event_target.c_str(), event_name.c_str())));
      // The sudden termination disabler state should be false now.
      EXPECT_FALSE(rfh->GetSuddenTerminationDisablerState(
          DisablerTypeForEvent(event_name)));

      // Add the event listener back for the event_name.
      EXPECT_TRUE(ExecJs(
          rfh, base::StringPrintf("%s.addEventListener('%s', callback);",
                                  event_target.c_str(), event_name.c_str())));
      // The sudden termination disabler state should be true again.
      EXPECT_TRUE(rfh->GetSuddenTerminationDisablerState(
          DisablerTypeForEvent(event_name)));
      // Calling `document.open()` should trigger `RemoveAllEventListeners()`
      // in both the document DOM node and the DOM window.
      EXPECT_TRUE(ExecJs(rfh, "document.open();"));
      // The sudden termination disabler state should be false now.
      EXPECT_FALSE(rfh->GetSuddenTerminationDisablerState(
          DisablerTypeForEvent(event_name)));
    }
  }
}

namespace {

// A helper to post a recurring check that a renderer process is foregrounded.
// The recurring check uses WeakPtr semantic and will die when this class goes
// out of scope.
class AssertForegroundHelper {
 public:
  AssertForegroundHelper() = default;

  AssertForegroundHelper(const AssertForegroundHelper&) = delete;
  AssertForegroundHelper& operator=(const AssertForegroundHelper&) = delete;

#if BUILDFLAG(IS_APPLE)
  // Asserts that |renderer_process| isn't backgrounded and reposts self to
  // check again shortly. |renderer_process| must outlive this
  // AssertForegroundHelper instance.
  void AssertForegroundAndRepost(const base::Process& renderer_process) {
    ASSERT_EQ(renderer_process.GetPriority(
                  BrowserChildProcessHost::GetPortProvider()),
              base::Process::Priority::kUserBlocking);
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(&AssertForegroundHelper::AssertForegroundAndRepost,
                       weak_ptr_factory_.GetWeakPtr(),
                       std::cref(renderer_process)),
        base::Milliseconds(1));
  }
#else   // BUILDFLAG(IS_APPLE)
  // Same as above without the Mac specific base::PortProvider.
  void AssertForegroundAndRepost(const base::Process& renderer_process) {
    ASSERT_NE(renderer_process.GetPriority(),
              base::Process::Priority::kBestEffort);
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(&AssertForegroundHelper::AssertForegroundAndRepost,
                       weak_ptr_factory_.GetWeakPtr(),
                       std::cref(renderer_process)),
        base::Milliseconds(1));
  }
#endif  // BUILDFLAG(IS_APPLE)

 private:
  base::WeakPtrFactory<AssertForegroundHelper> weak_ptr_factory_{this};
};

}  // namespace

// This is a regression test for https://crbug.com/560446. It ensures the
// newly launched process for cross-process navigation in the foreground
// WebContents isn't backgrounded prior to the navigation committing and a
// "visible" widget being added to the process. This test discards the spare
// RenderProcessHost if present, to ensure that it is not used in the
// cross-process navigation.
// TODO(crbug.com/40760155): Flaky on Mac.
#if BUILDFLAG(IS_APPLE)
#define MAYBE_ForegroundNavigationIsNeverBackgroundedWithoutSpareProcess \
  DISABLED_ForegroundNavigationIsNeverBackgroundedWithoutSpareProcess
#else
#define MAYBE_ForegroundNavigationIsNeverBackgroundedWithoutSpareProcess \
  ForegroundNavigationIsNeverBackgroundedWithoutSpareProcess
#endif
IN_PROC_BROWSER_TEST_P(
    RenderFrameHostManagerTest,
    MAYBE_ForegroundNavigationIsNeverBackgroundedWithoutSpareProcess) {
  StartEmbeddedServer();
  WebContentsImpl* web_contents =
      static_cast<WebContentsImpl*>(shell()->web_contents());

  // Start off navigating to a.com and capture the process used to commit.
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("a.com", "/title1.html")));
  RenderProcessHost* start_rph =
      web_contents->GetPrimaryMainFrame()->GetProcess();

  // Discard the spare RenderProcessHost to ensure a new RenderProcessHost
  // is created and has the right prioritization.
  auto& spare_manager = SpareRenderProcessHostManagerImpl::Get();
  spare_manager.CleanupSparesForTesting();
  EXPECT_TRUE(spare_manager.GetSpares().empty());

  // Start a navigation to b.com to ensure a cross-process navigation is
  // in progress and ensure the process for the speculative host is different.
  GURL url(embedded_test_server()->GetURL("b.com", "/title2.html"));
  content::TestNavigationManager navigation_manager(web_contents, url);

  shell()->LoadURL(url);
  navigation_manager.WaitForSpeculativeRenderFrameHostCreation();
  RenderProcessHost* speculative_rph = web_contents->GetPrimaryFrameTree()
                                           .root()
                                           ->render_manager()
                                           ->speculative_frame_host()
                                           ->GetProcess();
  EXPECT_NE(start_rph, speculative_rph);
  EXPECT_FALSE(speculative_rph->IsReady());

#if !BUILDFLAG(IS_ANDROID)
  // TODO(gab, nasko): On Android IsProcessBackgrounded is currently giving
  // incorrect value at this stage of the process lifetime. This should be
  // fixed in follow up cleanup work. See https://crbug.com/560446.
  EXPECT_NE(speculative_rph->GetPriority(),
            base::Process::Priority::kBestEffort);
#endif

  // Wait for the underlying OS process to have launched and be ready to
  // receive IPCs.
  RenderProcessHostWatcher process_observer(
      speculative_rph, RenderProcessHostWatcher::WATCH_FOR_PROCESS_READY);
  process_observer.Wait();

  // Kick off an infinite check against self that the process used for
  // navigation is never backgrounded. The WaitForNavigationFinished will wait
  // inside a RunLoop() and hence perform this check regularly throughout the
  // navigation.
  const base::Process& process = speculative_rph->GetProcess();
  EXPECT_TRUE(process.IsValid());
  AssertForegroundHelper assert_foreground_helper;
  assert_foreground_helper.AssertForegroundAndRepost(process);

  // The process should be foreground priority before commit because it is
  // pending, and foreground after commit because it has a visible widget.
  ASSERT_TRUE(navigation_manager.WaitForNavigationFinished());
  EXPECT_NE(start_rph, web_contents->GetPrimaryMainFrame()->GetProcess());
  EXPECT_EQ(speculative_rph, web_contents->GetPrimaryMainFrame()->GetProcess());
}

// Similar to the test above, but verifies the spare RenderProcessHost uses the
// right priority.
IN_PROC_BROWSER_TEST_P(
    RenderFrameHostManagerTest,
    ForegroundNavigationIsNeverBackgroundedWithSpareProcess) {
  // This test applies only when spare RenderProcessHost is enabled and in use.
  if (!RenderProcessHostImpl::IsSpareProcessKeptAtAllTimes())
    return;

  StartEmbeddedServer();
  WebContentsImpl* web_contents =
      static_cast<WebContentsImpl*>(shell()->web_contents());

  // Start off navigating to a.com and capture the process used to commit.
  SpareRenderProcessHostStartedObserver spare_started_observer;
  EXPECT_TRUE(NavigateToURL(
      shell(), embedded_test_server()->GetURL("a.com", "/title1.html")));
  // The AndroidWarmUpSpareRendererWithTimeout feature will create a spare
  // renderer after the navigation finishes or with a delay so we need to
  // explicitly wait.
  if (base::FeatureList::IsEnabled(
          features::kAndroidWarmUpSpareRendererWithTimeout)) {
    spare_started_observer.WaitForSpareRenderProcessStarted();
  }
  RenderProcessHost* start_rph =
      web_contents->GetPrimaryMainFrame()->GetProcess();

  // At this time, there should be a spare RenderProcesHost. Capture it for
  // testing expectations later.
  auto& spare_manager = SpareRenderProcessHostManagerImpl::Get();
  ASSERT_EQ(spare_manager.GetSpares().size(), 1u);
  RenderProcessHost* spare_rph = spare_manager.GetSpares()[0];
  EXPECT_EQ(spare_rph->GetPriority(), base::Process::Priority::kBestEffort);

  // Start a navigation to b.com to ensure a cross-process navigation is
  // in progress and ensure the process for the speculative host is
  // different, but matches the spare RenderProcessHost.
  GURL url(embedded_test_server()->GetURL("b.com", "/title2.html"));
  content::TestNavigationManager navigation_manager(web_contents, url);

  shell()->LoadURL(url);
  navigation_manager.WaitForSpeculativeRenderFrameHostCreation();
  RenderProcessHost* speculative_rph = web_contents->GetPrimaryFrameTree()
                                           .root()
                                           ->render_manager()
                                           ->speculative_frame_host()
                                           ->GetProcess();
  EXPECT_NE(start_rph, speculative_rph);

  // In this test case, the spare RenderProcessHost will be used, so verify it
  // and ensure it is ready.
  EXPECT_EQ(spare_rph, speculative_rph);

  // If LoadUrl finished before the task to call
  // RenderProcessHostImpl::OnChannelConnected is run, wait for the task to be
  // run.
  if (!spare_rph->IsReady()) {
    RenderProcessHostWatcher ready_waiter(
        spare_rph, RenderProcessHostWatcher::WATCH_FOR_PROCESS_READY);
    ready_waiter.Wait();
  }
  EXPECT_TRUE(spare_rph->IsReady());

  // The creation of the speculative RenderFrameHost should change the
  // RenderProcessHost's copy of the priority of the spare process from
  // background to foreground.
  EXPECT_NE(spare_rph->GetPriority(), base::Process::Priority::kBestEffort);

  // The OS process itself is updated on the process launcher thread, so it
  // cannot be observed immediately here. Perform a thread hop to and back to
  // allow for the priority change to occur before using the
  // AssertForegroundHelper object to check the OS process priority.
  {
    base::RunLoop run_loop;
    GetProcessLauncherTaskRunner()->PostTaskAndReply(
        FROM_HERE, base::DoNothing(), run_loop.QuitWhenIdleClosure());
    run_loop.Run();
  }

  // Kick off an infinite check against self that the process used for
  // navigation is never backgrounded. The WaitForNavigationFinished will wait
  // inside a RunLoop() and hence perform this check regularly throughout the
  // navigation.
  const base::Process& process = spare_rph->GetProcess();
  EXPECT_TRUE(process.IsValid());
  AssertForegroundHelper assert_foreground_helper;
  assert_foreground_helper.AssertForegroundAndRepost(process);

  // The process should be foreground priority before commit because it is
  // pending, and foreground after commit because it has a visible widget.
  ASSERT_TRUE(navigation_manager.WaitForNavigationFinished());
  EXPECT_NE(start_rph, web_contents->GetPrimaryMainFrame()->GetProcess());
  EXPECT_EQ(speculative_rph, web_contents->GetPrimaryMainFrame()->GetProcess());
}

// When ProactivelySwapBrowsingInstance is enabled, the browser switch to a new
// BrowsingInstance on cross-site HTTP(S) main frame navigations, when there are
// no other windows in the BrowsingInstance.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       ProactivelySwapBrowsingInstance) {
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL a_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
  GURL b_url(embedded_test_server()->GetURL("b.com", "/title1.html"));

  WebContentsImpl* web_contents =
      static_cast<WebContentsImpl*>(shell()->web_contents());

  // Navigate to A.
  EXPECT_TRUE(NavigateToURL(shell(), a_url));
  scoped_refptr<SiteInstance> a_site_instance =
      web_contents->GetPrimaryMainFrame()->GetSiteInstance();

  // Navigate to B. The navigation is document initiated. It swaps
  // BrowsingInstance only if  ProactivelySwapBrowsingInstance is enabled.
  EXPECT_TRUE(NavigateToURLFromRenderer(shell(), b_url));
  EXPECT_TRUE(WaitForLoadStop(web_contents));
  scoped_refptr<SiteInstance> b_site_instance =
      web_contents->GetPrimaryMainFrame()->GetSiteInstance();

  if (CanCrossSiteNavigationsProactivelySwapBrowsingInstances())
    EXPECT_FALSE(a_site_instance->IsRelatedSiteInstance(b_site_instance.get()));
  else
    EXPECT_TRUE(a_site_instance->IsRelatedSiteInstance(b_site_instance.get()));
}

// Tests specific to the "default process" mode (which creates strict
// SiteInstances that can share a default process per BrowsingInstance).
class RenderFrameHostManagerDefaultProcessTest
    : public RenderFrameHostManagerTest {
 public:
  RenderFrameHostManagerDefaultProcessTest() {
    feature_list_.InitAndEnableFeature(
        features::kProcessSharingWithStrictSiteInstances);
  }

  RenderFrameHostManagerDefaultProcessTest(
      const RenderFrameHostManagerDefaultProcessTest&) = delete;
  RenderFrameHostManagerDefaultProcessTest& operator=(
      const RenderFrameHostManagerDefaultProcessTest&) = delete;

  ~RenderFrameHostManagerDefaultProcessTest() override = default;

  void SetUpCommandLine(base::CommandLine* command_line) override {
    RenderFrameHostManagerTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kDisableSiteIsolation);

    if (AreAllSitesIsolatedForTesting()) {
      LOG(WARNING) << "This test should be run without strict site isolation. "
                   << "It does nothing when --site-per-process is specified.";
    }
  }

 private:
  base::test::ScopedFeatureList feature_list_;
};

// Ensure that the default process can be used for URLs that don't assign a site
// to the SiteInstance, when Site Isolation is not enabled.
// 1. Visit foo.com.
// 2. Start to navigate to a siteless URL.
// 3. When the commit is pending, start a navigation to bar.com in a popup.
// (Using a popup avoids a crash when replacting the speculative RFH, per
// https://crbug.com/838348.)
// All navigations should use the default process, and we should not crash.
// See https://crbug.com/977956.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerDefaultProcessTest,
                       NavigationRacesWithSitelessCommitInDefaultProcess) {
  // This test is designed to run without strict site isolation.
  if (AreAllSitesIsolatedForTesting())
    return;

  ASSERT_TRUE(embedded_test_server()->Start());
  WebContentsImpl* web_contents =
      static_cast<WebContentsImpl*>(shell()->web_contents());
  GURL foo_url(embedded_test_server()->GetURL("foo.com", "/title1.html"));
  GURL bar_url(embedded_test_server()->GetURL("bar.com", "/title1.html"));

  // Step 1: Visit foo.com in the default process.
  EXPECT_TRUE(NavigateToURL(shell(), foo_url));
  RenderProcessHost* original_process =
      web_contents->GetPrimaryMainFrame()->GetProcess();
  EXPECT_EQ(original_process, web_contents->GetPrimaryMainFrame()
                                  ->GetSiteInstance()
                                  ->GetSiteInstanceGroupProcessIfAvailable());
  // This test expect a cross-site navigation to be same BrowsingInstance. With
  // ProactivelySwapBrowsingInstance, it won't be the case. Opening a popup
  // prevent the BrowsingInstance to change.
  if (CanCrossSiteNavigationsProactivelySwapBrowsingInstances()) {
    GURL popup_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
    EXPECT_TRUE(OpenPopup(web_contents->GetPrimaryMainFrame(), popup_url, ""));
  }

  // Set up a URL for which ShouldAssignSiteForURL will return false.  The
  // corresponding SiteInstance's site will be left unassigned, and its process
  // won't be locked.  This requires adding the URL's scheme as an empty
  // document scheme.
  url::ScopedSchemeRegistryForTests scheme_registry;
  url::AddEmptyDocumentScheme("siteless");
  GURL siteless_url("siteless://test");
  EXPECT_FALSE(SiteInstance::ShouldAssignSiteForURL(siteless_url));

  // Set up the work to be done after the renderer is asked to commit
  // |siteless_url|, but before the corresponding DidCommitProvisionalLoad IPC
  // is processed.  This will start a navigation to |bar_url| in a popup and
  // wait for its response.  We use a popup to avoid trampling the speculative
  // RFH while it is committing (per https://crbug.com/838348).
  auto did_commit_callback =
      base::BindLambdaForTesting([&](RenderFrameHost* rfh) {
        Shell* new_shell = OpenPopup(shell(), GURL(url::kAboutBlankURL), "foo");
        EXPECT_TRUE(new_shell);

        // Step 3: Navigate to bar.com in the same BrowsingInstance, while the
        // commit to siteless_url is pending.  This used to crash because it
        // picked the default process, but IsSuitableHost said it was not ok due
        // to the pending siteless URL commit (in https://crbug.com/977956).
        TestNavigationManager bar_manager(new_shell->web_contents(), bar_url);
        EXPECT_TRUE(
            ExecJs(new_shell, base::StringPrintf("location.href = '%s'",
                                                 bar_url.spec().c_str())));

        // Wait for response.  This will cause |bar_manager| to spin up a
        // nested message loop while we're blocked in the current message loop
        // (within DidCommitNavigationInterceptor).  Thus, it's important to
        // allow nestable tasks in |bar_manager|'s message loop, so that it can
        // process the response before we unblock the
        // DidCommitNavigationInterceptor's message loop and finish processing
        // the commit.
        bar_manager.AllowNestableTasks();
        EXPECT_TRUE(bar_manager.WaitForResponse());

        bar_manager.ResumeNavigation();

        // After returning here, the commit for |siteless_url| will be
        // processed.
      });

  // Step 2: Visit siteless_url in the same BrowsingInstance, but wait before
  // the commit IPC is processed.  (See did_commit_callback above for step 3.)
  CommitMessageDelayer commit_delayer(web_contents,
                                      siteless_url /* deferred_url */,
                                      std::move(did_commit_callback));
  EXPECT_TRUE(ExecJs(shell(), base::StringPrintf("location.href = '%s'",
                                                 siteless_url.spec().c_str())));

  // Wait for the DidCommit IPC for |siteless_url|, and before processing it,
  // trigger a navigation to |foo_url| and wait for its response.
  commit_delayer.Wait();

  EXPECT_EQ(original_process,
            web_contents->GetPrimaryMainFrame()->GetProcess());
}

// 1. Navigate to A1(B2, B3(B4), C5)
// 2. Crash process B
// 3. Reload B2, creating RFH B6.
//
// Along the way, check the RenderFrameProxies.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       CrashFrameReloadAndCheckProxy) {
  // This test explicitly requires multiple processes to be used. It won't mean
  // anything without SiteIsolation.
  if (!AreAllSitesIsolatedForTesting())
    return;

  // 1. Navigate to A1(B2, B3(B4), C5).
  StartEmbeddedServer();
  GURL url(embedded_test_server()->GetURL(
      "a.com", "/cross_site_iframe_factory.html?a(b,b(b),c)"));
  EXPECT_TRUE(NavigateToURL(shell(), url));

  WebContentsImpl* web_contents =
      static_cast<WebContentsImpl*>(shell()->web_contents());
  RenderFrameHostImpl* a1 = web_contents->GetPrimaryMainFrame();
  RenderFrameHostImpl* b2 = a1->child_at(0)->current_frame_host();
  RenderFrameHostImpl* b3 = a1->child_at(1)->current_frame_host();
  RenderFrameHostImpl* b4 = b3->child_at(0)->current_frame_host();
  RenderFrameHostImpl* c5 = a1->child_at(2)->current_frame_host();

  RenderFrameDeletedObserver delete_a1(a1);
  RenderFrameDeletedObserver delete_b2(b2);
  RenderFrameDeletedObserver delete_b3(b3);
  RenderFrameDeletedObserver delete_b4(b4);
  RenderFrameDeletedObserver delete_c5(c5);

  GURL b2_url = b2->GetLastCommittedURL();
  int b2_routing_id = b2->GetRoutingID();

  auto proxy_count = [](RenderFrameHostImpl* rfh) {
    return rfh->browsing_context_state()->GetProxyCount();
  };

  // There are 3 processes, so every frame has 2 frame proxies.
  EXPECT_EQ(2u, proxy_count(a1));
  EXPECT_EQ(2u, proxy_count(b2));
  EXPECT_EQ(2u, proxy_count(b3));
  EXPECT_EQ(2u, proxy_count(b4));
  EXPECT_EQ(2u, proxy_count(c5));

  auto is_proxy_live = [](RenderFrameHostImpl* rfh,
                          scoped_refptr<SiteInstanceImpl> site_instance) {
    return rfh->browsing_context_state()
        ->GetRenderFrameProxyHost(site_instance->group())
        ->is_render_frame_proxy_live();
  };

  // Store SiteInstance for later comparison.
  scoped_refptr<SiteInstanceImpl> a_site_instance(a1->GetSiteInstance());
  scoped_refptr<SiteInstanceImpl> b_site_instance(b2->GetSiteInstance());
  scoped_refptr<SiteInstanceImpl> c_site_instance(c5->GetSiteInstance());

  // Check that each of the site instances are in a different group, so proxies
  // exist for the others.
  EXPECT_NE(a_site_instance->group(), b_site_instance->group());
  EXPECT_NE(a_site_instance->group(), c_site_instance->group());
  EXPECT_NE(b_site_instance->group(), c_site_instance->group());

  // Check the state of the proxies before the crash:
  EXPECT_TRUE(is_proxy_live(a1, b_site_instance));
  EXPECT_TRUE(is_proxy_live(a1, c_site_instance));
  EXPECT_TRUE(is_proxy_live(b2, a_site_instance));
  EXPECT_TRUE(is_proxy_live(b2, c_site_instance));
  EXPECT_TRUE(is_proxy_live(b3, a_site_instance));
  EXPECT_TRUE(is_proxy_live(b3, c_site_instance));
  EXPECT_TRUE(is_proxy_live(c5, a_site_instance));
  EXPECT_TRUE(is_proxy_live(c5, b_site_instance));

  // 2. Crash process B.
  RenderProcessHost* process = b2->GetProcess();
  RenderProcessHostWatcher crash_observer(
      process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
  process->Shutdown(0);
  crash_observer.Wait();

  // Only B4 is deleted. B2 and B3 are still there in a "crashed" state.
  delete_b4.WaitUntilDeleted();

  // B2, B3, B4 RenderFrame are gone.
  EXPECT_FALSE(delete_a1.deleted());
  EXPECT_TRUE(delete_b2.deleted());
  EXPECT_TRUE(delete_b3.deleted());
  EXPECT_TRUE(delete_b4.deleted());
  EXPECT_FALSE(delete_c5.deleted());

  // B2 and B3 RenderFrameHost are still there, but B4 is definitely gone.
  ASSERT_EQ(3u, a1->child_count());
  EXPECT_EQ(b2, a1->child_at(0)->current_frame_host());
  EXPECT_EQ(b3, a1->child_at(1)->current_frame_host());
  ASSERT_EQ(0u, b3->child_count());

  EXPECT_FALSE(a1->must_be_replaced());
  EXPECT_TRUE(b2->must_be_replaced());
  EXPECT_TRUE(b3->must_be_replaced());
  EXPECT_FALSE(c5->must_be_replaced());

  EXPECT_EQ(2u, proxy_count(a1));
  EXPECT_EQ(2u, proxy_count(b2));
  EXPECT_EQ(2u, proxy_count(b3));
  EXPECT_EQ(2u, proxy_count(c5));

  // Check the state of the proxies after the crash:
  EXPECT_FALSE(is_proxy_live(a1, b_site_instance));
  EXPECT_TRUE(is_proxy_live(a1, c_site_instance));
  EXPECT_TRUE(is_proxy_live(b2, a_site_instance));
  EXPECT_TRUE(is_proxy_live(b2, c_site_instance));
  EXPECT_TRUE(is_proxy_live(b3, a_site_instance));
  EXPECT_TRUE(is_proxy_live(b3, c_site_instance));
  EXPECT_TRUE(is_proxy_live(c5, a_site_instance));
  EXPECT_FALSE(is_proxy_live(c5, b_site_instance));

  // 3. Reload B2, B6 is created.
  NavigateFrameToURL(b2->frame_tree_node(), b2_url);

  // B2 has been replaced
  EXPECT_NE(b2_routing_id,
            a1->child_at(0)->current_frame_host()->GetRoutingID());
  // B3 hasn't been replaced.
  EXPECT_EQ(b3, a1->child_at(1)->current_frame_host());
  RenderFrameHostImpl* b6 = a1->child_at(0)->current_frame_host();
  EXPECT_TRUE(b3->must_be_replaced());
  EXPECT_FALSE(b6->must_be_replaced());

  EXPECT_EQ(a_site_instance, a1->GetSiteInstance());
  EXPECT_EQ(b_site_instance, b6->GetSiteInstance());
  EXPECT_EQ(c_site_instance, c5->GetSiteInstance());

  EXPECT_EQ(2u, proxy_count(a1));
  EXPECT_EQ(2u, proxy_count(b6));
  EXPECT_EQ(2u, proxy_count(b3));
  EXPECT_EQ(2u, proxy_count(c5));

  // Check the state of the proxies after the reload.
  EXPECT_TRUE(is_proxy_live(a1, b_site_instance));
  EXPECT_TRUE(is_proxy_live(a1, c_site_instance));
  EXPECT_TRUE(is_proxy_live(b6, a_site_instance));
  EXPECT_TRUE(is_proxy_live(b6, c_site_instance));
  EXPECT_TRUE(is_proxy_live(b3, a_site_instance));
  EXPECT_TRUE(is_proxy_live(b3, c_site_instance));
  EXPECT_TRUE(is_proxy_live(c5, a_site_instance));
  EXPECT_TRUE(is_proxy_live(c5, b_site_instance));
}

// With just the right initial navigations using RendererDebugURLs, creating a
// new RenderFrameHost can fail. https://crbug.com/1006814
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       NavigateFromRevivedRendererDebugURL) {
  StartEmbeddedServer();
  // This matches IsRendererDebugURL.
  GURL debug_url("javascript:'hello'");
  // Just needs to be any URL that would navigate successfully.
  GURL other_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
  WebContentsImpl* web_contents =
      static_cast<WebContentsImpl*>(shell()->web_contents());

  // Go to the debug URL. This is a synchronous navigation.
  shell()->LoadURL(debug_url);
  ASSERT_EQ("hello", EvalJs(shell(), "document.body.innerText"));

  // Crash the renderer.
  FrameTreeNode* root = web_contents->GetPrimaryFrameTree().root();
  RenderFrameHostImpl* rfh = root->current_frame_host();
  RenderProcessHost* process = rfh->GetProcess();
  RenderProcessHostWatcher crash_observer(
      process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
  process->Shutdown(0);
  crash_observer.Wait();

  // Load the URL again. This will cause the RenderWidgetHost to be revived,
  // pointing to a RenderWidget in a new process.
  shell()->LoadURL(debug_url);
  ASSERT_EQ("hello", EvalJs(shell(), "document.body.innerText"));
  RenderProcessHost* new_process = root->current_frame_host()->GetProcess();

  // Now try load another URL. It should cope smoothly with the fact that the
  // RenderWidgetHost is already revived.
  ASSERT_TRUE(NavigateToURL(web_contents, other_url));

  // In https://crbug.com/1006814 with site-isolation disabled when creating new
  // hosts for crashed frames, the process does not change. We check that here
  // to make sure that we actually recreated the bug. With site-isolation
  // enabled, the process should change.
  if (!AreAllSitesIsolatedForTesting()) {
    ASSERT_EQ(new_process, root->current_frame_host()->GetProcess());
  } else {
    ASSERT_NE(new_process, root->current_frame_host()->GetProcess());
  }
}

// Helper class to run tests without site isolation.
class RenderFrameHostManagerNoSiteIsolationTest
    : public RenderFrameHostManagerTest {
 public:
  RenderFrameHostManagerNoSiteIsolationTest() = default;

  RenderFrameHostManagerNoSiteIsolationTest(
      const RenderFrameHostManagerNoSiteIsolationTest&) = delete;
  RenderFrameHostManagerNoSiteIsolationTest& operator=(
      const RenderFrameHostManagerNoSiteIsolationTest&) = delete;

  ~RenderFrameHostManagerNoSiteIsolationTest() override = default;

  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(switches::kDisableSiteIsolation);
  }
};

// Ensure that when a process that allows any site gets reused by new
// BrowsingInstances, ChildProcessSecurityPolicy gets notified about those new
// BrowsingInstances.  Failure to do so will lead to a crash at commit time due
// to mismatched process locks.  See https://crbug.com/1141877.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerNoSiteIsolationTest,
                       IncludeIsolationContextInProcessThatAllowsAnySite) {
  StartEmbeddedServer();
  // Ensure we have one renderer process that's reused for everything.
  RenderProcessHost::SetMaxRendererProcessCount(1);

  // The test starts out with an initial window with a blank SiteInstance.
  // Create a new window in a new BrowsingInstance and another blank
  // SiteInstance.
  Shell* shell2 =
      Shell::CreateNewWindow(shell()->web_contents()->GetBrowserContext(),
                             GURL(), nullptr, gfx::Size());
  SiteInstanceImpl* old_instance = static_cast<SiteInstanceImpl*>(
      shell()->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());
  SiteInstanceImpl* new_instance = static_cast<SiteInstanceImpl*>(
      shell2->web_contents()->GetPrimaryMainFrame()->GetSiteInstance());
  EXPECT_FALSE(old_instance->IsRelatedSiteInstance(new_instance));

  // At this point, neither SiteInstance should have a site assigned.
  EXPECT_FALSE(old_instance->HasSite());
  EXPECT_FALSE(new_instance->HasSite());

  // Both should use the same process.
  EXPECT_EQ(old_instance->GetProcess(), new_instance->GetProcess());

  // Make sure the BrowsingInstanceId is cleaned up immediately.
  ChildProcessSecurityPolicyImpl::GetInstance()
      ->SetBrowsingInstanceCleanupDelayForTesting(0);

  // Close the test's initial window.  This should destroy the initial
  // BrowsingInstance and remove it from ChildProcessSecurityPolicy.
  shell()->Close();

  // Navigate to a web URL in the second window.  This shouldn't crash.
  GURL url(embedded_test_server()->GetURL("a.com", "/title1.html"));
  ASSERT_TRUE(NavigateToURL(shell2->web_contents(), url));
}

// With RenderDocument for subframes, removing a frame while it is executing
// its own unload handler caused a crash. https://crbug.com/1148793
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       RemoveSubframeInPageHide_SameSite) {
  // TODO(crbug.com/40731502): Remove this early return. This doesn't
  // work for RenderDocumentLevel::kNonLocalRootSubframe or greater because
  // cancelling the navigation when detaching the subtree tries to restore the
  // replaced `blink::RemoteFrame` (which doesn't exist in the same-site
  // RenderDocument case because the replaced object wasn't a
  // `blink::RemoteFrame`, but instead a RenderFrame).
  if (ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
          /*is_main_frame=*/false, /*is_local_root=*/false)) {
    return;
  }
  AssertCanRemoveSubframeInPageHide(/*same_site=*/true);
}

// See RemoveSubframeInUnload_SameSite
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       RemoveSubframeInPageHide_CrossSite) {
  // TODO(crbug.com/40731502): Remove this early return.
  if (ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
          /*is_main_frame=*/false, /*is_local_root=*/false) &&
      !AreAllSitesIsolatedForTesting()) {
    return;
  }
  AssertCanRemoveSubframeInPageHide(/*same_site=*/false);
}

// This test demonstrates a similar issue to the previous two tests, but
// triggers it in a slightly different way. The previous two tests navigate a
// subframe and rely on some variant of RenderDocument being enabled to trigger
// the crash. If the navigation commits in a new RenderFrameHostImpl, the
// renderer does not correctly handle the case where running the unload handler
// while swapping in the new frame detaches the navigated frame.
//
// However, this bug actually precedes RenderDocument, as detaching a document
// for navigation at swap time must also detach the subtree. Given a frame tree
// A1(B(A2)) and a navigation from B->A3, committing A3 will unload B. However,
// unloading B will also detach A2, and A2's unload handler can detach B since
// it can script A1 and remove the frame owner element synchronously.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerUnloadBrowserTest, NestedUnload) {
  // These tests require site isolation to trigger the (formerly problematic)
  // delayed detach of the remote frame when swapping in the new local frame.
  if (!AreAllSitesIsolatedForTesting())
    return;

  SetupCrossSiteRedirector(embedded_test_server());
  StartEmbeddedServer();
  EXPECT_TRUE(NavigateToURL(shell(), embedded_test_server()->GetURL(
                                         "a.com", "/nested-unload-0.html")));

  WebContentsImpl* web_contents =
      static_cast<WebContentsImpl*>(shell()->web_contents());

  EXPECT_EQ(
      " Site A ------------ proxies for B\n"
      "   +--Site B ------- proxies for A\n"
      "        +--Site A -- proxies for B\n"
      "Where A = http://a.com/\n"
      "      B = http://b.com/",
      FrameTreeVisualizer().DepictFrameTree(
          web_contents->GetPrimaryFrameTree().root()));

  // Navigate the subframe, triggering unload.
  FrameTreeNode* subframe = web_contents->GetPrimaryMainFrame()->child_at(0);
  RenderFrameDeletedObserver observer(
      subframe->render_manager()->current_frame_host());

  GURL other_url(embedded_test_server()->GetURL("a.com", "/title1.html"));
  // The navigation will remove the frame that was navigating. Various Navigate
  // helpers run into problems with this because there is no successful commit
  // nor is there a DidStopLoading (because the destination frame should not
  // load at all). So instead we start the Navigation and just wait for the
  // deletion.
  ASSERT_TRUE(ExecJs(subframe, JsReplace("location = $1", other_url)));
  observer.WaitUntilDeleted();

  // The subframe has been removed.
  EXPECT_EQ(0UL, web_contents->GetPrimaryMainFrame()->child_count());
  // TODO(crbug.com/40142480): Remove this. Without this, the crash in
  // the renderer in https://crbug.com/1148793 is usually not caught.
  ASSERT_TRUE(ExecJs(shell(), ""));
}

// See RemoveSubframeInPageHide_SameSite
void RenderFrameHostManagerTest::AssertCanRemoveSubframeInPageHide(
    bool same_site) {
  StartEmbeddedServer();

  // Create a page with a subframe.
  GURL frame_url(embedded_test_server()->GetURL(
      "a.com", "/cross_site_iframe_factory.html?a(a)"));
  ASSERT_TRUE(NavigateToURL(shell(), frame_url));

  // Set up the subframe's pagehide handler to remove the subframe.
  ASSERT_TRUE(ExecJs(shell(), R"(
    const subframe = document.getElementById("child-0");
    subframe.contentWindow.onpagehide = () => {
      subframe.remove();
    }
  )"));

  // Navigate the subframe, triggering pagehide.
  WebContentsImpl* web_contents =
      static_cast<WebContentsImpl*>(shell()->web_contents());

  FrameTreeNode* subframe = web_contents->GetPrimaryMainFrame()->child_at(0);
  RenderFrameDeletedObserver observer(
      subframe->render_manager()->current_frame_host());

  GURL other_url(embedded_test_server()->GetURL(same_site ? "a.com" : "b.com",
                                                "/title1.html"));
  // The navigation will remove the frame that was navigating. Various Navigate
  // helpers run into problems with this because there is no successful commit
  // nor is there a DidStopLoading (because the destination frame should not
  // load at all). So instead we start the Navigation and just wait for the
  // deletion.
  ASSERT_TRUE(ExecJs(subframe, JsReplace("location = $1", other_url)));
  observer.WaitUntilDeleted();

  // The subframe has been removed.
  EXPECT_EQ(0UL, web_contents->GetPrimaryMainFrame()->child_count());
  // TODO(crbug.com/40142480): Remove this. Without this, the crash in
  // the renderer in https://crbug.com/1148793 is usually not caught.
  ASSERT_TRUE(ExecJs(shell(), ""));
}

// From https://crbug.com/1169844. Verify that crashing a cross-site subframe
// and navigating it to a new site does not cause the browser to crash.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerTest,
                       NavigateCrossSiteSubframeAfterCrash) {
  StartEmbeddedServer();
  // Ensure that all 3 pages are isolated from each other (even on
  // Android, where site-per-process is not the default).
  IsolateOriginsForTesting(embedded_test_server(), shell()->web_contents(),
                           {"a.com", "b.com", "c.com"});

  // Create a page with a subframe and navigate it cross-site.
  GURL url(embedded_test_server()->GetURL(
      "a.com", "/cross_site_iframe_factory.html?a(b)"));
  ASSERT_TRUE(NavigateToURL(shell(), url));

  // Crash the subframe.
  WebContentsImpl* web_contents =
      static_cast<WebContentsImpl*>(shell()->web_contents());
  FrameTreeNode* subframe = web_contents->GetPrimaryMainFrame()->child_at(0);
  RenderFrameHostImpl* rfh = subframe->current_frame_host();
  RenderProcessHost* process = rfh->GetProcess();
  {
    RenderProcessHostWatcher crash_observer(
        process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
    process->Shutdown(0);
    crash_observer.Wait();
  }
  ASSERT_FALSE(rfh->IsRenderFrameLive());
  subframe = web_contents->GetPrimaryMainFrame()->child_at(0);

  // Navigate the subframe cross-site.
  GURL url_c(embedded_test_server()->GetURL("c.com", "/title1.html"));
  ASSERT_TRUE(NavigateFrameToURL(subframe, url_c));
  ASSERT_TRUE(subframe->current_frame_host()->IsRenderFrameLive());
}

// From https://crbug.com/1503038.
// The RuntimeFeatureStateDocumentData should be re-created when the main frame
// recovers from a crash.
IN_PROC_BROWSER_TEST_P(
    RenderFrameHostManagerTest,
    RuntimeFeatureStateDocumentDataShouldBeRecreatedAfterCrash) {
  StartEmbeddedServer();

  GURL url(embedded_test_server()->GetURL("a.com", "/empty.html"));

  ASSERT_TRUE(NavigateToURL(shell(), url));

  // Crash the frame.
  WebContentsImpl* web_contents =
      static_cast<WebContentsImpl*>(shell()->web_contents());
  RenderFrameHostImpl* rfh = web_contents->GetPrimaryMainFrame();
  RenderProcessHost* process = rfh->GetProcess();
  {
    RenderProcessHostWatcher crash_observer(
        process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
    process->Shutdown(0);
    crash_observer.Wait();
  }
  ASSERT_FALSE(rfh->IsRenderFrameLive());

  auto* root = web_contents->GetPrimaryFrameTree().root();
  RenderFrameHostManager* manager = root->render_manager();

  manager->InitializeMainRenderFrameForImmediateUse();

  // Add a new iframe. As part of this iframe's creation
  // RenderFrameHostImpl::SetOriginDependentStateOfNewFrame() will be called
  // which will attempt to copy the parent frame's
  // RuntimeFeatureStateDocumentData.
  std::string script =
      "var new_iframe = document.createElement('iframe');"
      "document.documentElement.appendChild(new_iframe);";

  // If the parent's RuntimeFeatureStateDocumentData exists then this will
  // succeed, otherwise we'll hit a CHECK.
  EXPECT_TRUE(ExecJs(shell(), script));
}

// Tests that enable clearing window.name on cross-site
// cross-BrowsingInstance navigations.
class RenderFrameHostManagerClearWindowNameTest
    : public RenderFrameHostManagerTest {
 public:
  RenderFrameHostManagerClearWindowNameTest() {
    feature_list_.InitAndEnableFeature(
        features::kClearCrossSiteCrossBrowsingContextGroupWindowName);
  }
  ~RenderFrameHostManagerClearWindowNameTest() override = default;

 private:
  base::test::ScopedFeatureList feature_list_;
};

// Verify that cross-site main frame navigation that swaps BrowsingInstances
// clears window.name.
IN_PROC_BROWSER_TEST_P(RenderFrameHostManagerClearWindowNameTest,
                       ClearWindowNameCrossSite) {
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
  GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html"));
  GURL url_c(embedded_test_server()->GetURL("c.com", "/title1.html"));
  WebContentsImpl* web_contents =
      static_cast<WebContentsImpl*>(shell()->web_contents());

  // Navigate to a.com/title1.html.
  EXPECT_TRUE(NavigateToURL(shell(), url_a));
  // Set window.name.
  EXPECT_TRUE(content::ExecJs(web_contents, "window.name='foo'"));
  auto* frame_a = web_contents->GetPrimaryMainFrame();
  EXPECT_EQ("foo", frame_a->GetFrameName());

  scoped_refptr<SiteInstance> site_instance_a = frame_a->GetSiteInstance();

  // Renderer-initiated navigate to b.com/title2.html.
  EXPECT_TRUE(NavigateToURLFromRenderer(shell(), url_b));
  auto* frame_b = web_contents->GetPrimaryMainFrame();
  scoped_refptr<SiteInstance> site_instance_b = frame_b->GetSiteInstance();

  // Whether renderer-initiated top-level cross-site navigates swap
  // BrowsingInstances is based on whether ProactivelySwapBrowsingInstances or
  // BackForwardCache is enabled.
  if (CanCrossSiteNavigationsProactivelySwapBrowsingInstances()) {
    EXPECT_FALSE(site_instance_a->IsRelatedSiteInstance(site_instance_b.get()));
    // The BrowsingInstance got swapped, window.name is cleared.
    EXPECT_EQ("", frame_b->GetFrameName());
  } else {
    EXPECT_TRUE(site_instance_a->IsRelatedSiteInstance(site_instance_b.get()));
    // Window.name is not cleared.
    EXPECT_EQ("foo", frame_b->GetFrameName());
  }

  // Navigate to c.com/title1.html. The navigation is cross-site, top-level and
  // swaps BrowsingInstances, thus should clear window.name.
  EXPECT_TRUE(NavigateToURL(shell(), url_c));
  auto* frame_c = web_contents->GetPrimaryMainFrame();
  // Check that b.com/title1.html and c.com/title1.html are in different
  // BrowsingInstances.
  scoped_refptr<SiteInstance> site_instance_c = frame_c->GetSiteInstance();
  EXPECT_FALSE(site_instance_b->IsRelatedSiteInstance(site_instance_c.get()));
  // Window.name should be cleared.
  EXPECT_EQ("", frame_c->GetFrameName());
}

INSTANTIATE_TEST_SUITE_P(All,
                         RenderFrameHostManagerTest,
                         testing::ValuesIn(RenderDocumentFeatureLevelValues()));
INSTANTIATE_TEST_SUITE_P(All,
                         RenderFrameHostManagerUnloadBrowserTest,
                         testing::ValuesIn(RenderDocumentFeatureLevelValues()));
INSTANTIATE_TEST_SUITE_P(All,
                         RenderFrameHostManagerSpoofingTest,
                         testing::ValuesIn(RenderDocumentFeatureLevelValues()));
INSTANTIATE_TEST_SUITE_P(All,
                         RFHMProcessPerTabTest,
                         testing::ValuesIn(RenderDocumentFeatureLevelValues()));
INSTANTIATE_TEST_SUITE_P(All,
                         RenderFrameHostManagerDefaultProcessTest,
                         testing::ValuesIn(RenderDocumentFeatureLevelValues()));
INSTANTIATE_TEST_SUITE_P(All,
                         RenderFrameHostManagerNoSiteIsolationTest,
                         testing::ValuesIn(RenderDocumentFeatureLevelValues()));
INSTANTIATE_TEST_SUITE_P(All,
                         RenderFrameHostManagerClearWindowNameTest,
                         testing::ValuesIn(RenderDocumentFeatureLevelValues()));
}  // namespace content