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
|
// 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.h"
#include <stdint.h>
#include <set>
#include <string>
#include <tuple>
#include <unordered_set>
#include <utility>
#include <vector>
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/hash/hash.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/renderer_host/navigation_controller_impl.h"
#include "content/browser/renderer_host/navigation_entry_impl.h"
#include "content/browser/renderer_host/navigation_request.h"
#include "content/browser/renderer_host/navigator.h"
#include "content/browser/renderer_host/render_frame_proxy_host.h"
#include "content/browser/site_info.h"
#include "content/browser/site_instance_group.h"
#include "content/browser/site_instance_impl.h"
#include "content/browser/webui/web_ui_controller_factory_registry.h"
#include "content/common/content_navigation_policy.h"
#include "content/common/features.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_iterator.h"
#include "content/public/browser/render_widget_host_observer.h"
#include "content/public/browser/site_isolation_policy.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_ui_controller.h"
#include "content/public/common/bindings_policy.h"
#include "content/public/common/content_features.h"
#include "content/public/common/javascript_dialog_type.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/url_utils.h"
#include "content/public/test/back_forward_cache_util.h"
#include "content/public/test/fake_local_frame.h"
#include "content/public/test/fake_remote_frame.h"
#include "content/public/test/mock_render_process_host.h"
#include "content/public/test/scoped_web_ui_controller_factory_registration.h"
#include "content/public/test/test_utils.h"
#include "content/test/mock_widget_input_handler.h"
#include "content/test/navigation_simulator_impl.h"
#include "content/test/render_document_feature.h"
#include "content/test/test_content_browser_client.h"
#include "content/test/test_content_client.h"
#include "content/test/test_render_frame_host.h"
#include "content/test/test_render_view_host.h"
#include "content/test/test_render_widget_host.h"
#include "content/test/test_web_contents.h"
#include "net/base/load_flags.h"
#include "net/http/http_response_headers.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/frame/frame_policy.h"
#include "third_party/blink/public/common/tokens/tokens.h"
#include "third_party/blink/public/mojom/favicon/favicon_url.mojom.h"
#include "third_party/blink/public/mojom/frame/frame_owner_properties.mojom.h"
#include "third_party/blink/public/mojom/security_context/insecure_request_policy.mojom.h"
#include "ui/base/page_transition_types.h"
#include "url/origin.h"
#if BUILDFLAG(IS_ANDROID)
#include "content/public/browser/android/compositor.h"
#endif
namespace content {
namespace {
// VerifyPageFocusMessage from the mojo input handler.
void VerifyPageFocusMessage(TestRenderWidgetHost* twh, bool expected_focus) {
MockWidgetInputHandler::MessageVector events =
twh->GetMockWidgetInputHandler()->GetAndResetDispatchedMessages();
EXPECT_EQ(1u, events.size());
MockWidgetInputHandler::DispatchedFocusMessage* focus_message =
events.at(0)->ToFocus();
EXPECT_TRUE(focus_message);
EXPECT_EQ(expected_focus, focus_message->focused());
}
class RenderFrameHostManagerTestWebUIControllerFactory
: public WebUIControllerFactory {
public:
RenderFrameHostManagerTestWebUIControllerFactory() {}
RenderFrameHostManagerTestWebUIControllerFactory(
const RenderFrameHostManagerTestWebUIControllerFactory&) = delete;
RenderFrameHostManagerTestWebUIControllerFactory& operator=(
const RenderFrameHostManagerTestWebUIControllerFactory&) = delete;
~RenderFrameHostManagerTestWebUIControllerFactory() override {}
// WebUIFactory implementation.
std::unique_ptr<WebUIController> CreateWebUIControllerForURL(
WebUI* web_ui,
const GURL& url) override {
// If WebUI creation is enabled for the test and this is a WebUI URL,
// returns a new instance.
if (HasWebUIScheme(url))
return std::make_unique<WebUIController>(web_ui);
return nullptr;
}
WebUI::TypeID GetWebUIType(BrowserContext* browser_context,
const GURL& url) override {
// If WebUI creation is enabled for the test and this is a WebUI URL,
// returns a mock WebUI type.
if (HasWebUIScheme(url)) {
return reinterpret_cast<WebUI::TypeID>(base::FastHash(url.host()));
}
return WebUI::kNoWebUI;
}
bool UseWebUIForURL(BrowserContext* browser_context,
const GURL& url) override {
return HasWebUIScheme(url);
}
};
class BeforeUnloadFiredWebContentsDelegate : public WebContentsDelegate {
public:
BeforeUnloadFiredWebContentsDelegate() {}
BeforeUnloadFiredWebContentsDelegate(
const BeforeUnloadFiredWebContentsDelegate&) = delete;
BeforeUnloadFiredWebContentsDelegate& operator=(
const BeforeUnloadFiredWebContentsDelegate&) = delete;
~BeforeUnloadFiredWebContentsDelegate() override {}
void BeforeUnloadFired(WebContents* web_contents,
bool proceed,
bool* proceed_to_fire_unload) override {
*proceed_to_fire_unload = proceed;
}
};
class CloseWebContentsDelegate : public WebContentsDelegate {
public:
CloseWebContentsDelegate() : close_called_(false) {}
CloseWebContentsDelegate(const CloseWebContentsDelegate&) = delete;
CloseWebContentsDelegate& operator=(const CloseWebContentsDelegate&) = delete;
~CloseWebContentsDelegate() override {}
void CloseContents(WebContents* web_contents) override {
close_called_ = true;
}
bool is_closed() { return close_called_; }
private:
bool close_called_;
};
// This observer keeps track of the last deleted RenderViewHost to avoid
// accessing it and causing use-after-free condition.
class RenderViewHostDeletedObserver : public WebContentsObserver {
public:
explicit RenderViewHostDeletedObserver(RenderViewHost* rvh)
: WebContentsObserver(WebContents::FromRenderViewHost(rvh)),
process_id_(rvh->GetProcess()->GetDeprecatedID()),
routing_id_(rvh->GetRoutingID()),
deleted_(false) {}
RenderViewHostDeletedObserver(const RenderViewHostDeletedObserver&) = delete;
RenderViewHostDeletedObserver& operator=(
const RenderViewHostDeletedObserver&) = delete;
void RenderViewDeleted(RenderViewHost* render_view_host) override {
if (render_view_host->GetProcess()->GetDeprecatedID() == process_id_ &&
render_view_host->GetRoutingID() == routing_id_) {
deleted_ = true;
}
}
bool deleted() { return deleted_; }
private:
int process_id_;
int routing_id_;
bool deleted_;
};
// This observer keeps track of the last created RenderFrameHost to allow tests
// to ensure that no RenderFrameHost objects are created when not expected.
class RenderFrameHostCreatedObserver : public WebContentsObserver {
public:
explicit RenderFrameHostCreatedObserver(WebContents* web_contents)
: WebContentsObserver(web_contents), created_(false) {}
RenderFrameHostCreatedObserver(const RenderFrameHostCreatedObserver&) =
delete;
RenderFrameHostCreatedObserver& operator=(
const RenderFrameHostCreatedObserver&) = delete;
void RenderFrameCreated(RenderFrameHost* render_frame_host) override {
created_ = true;
}
bool created() { return created_; }
private:
bool created_;
};
// This observer is used to check whether IPC messages are being filtered for
// swapped out RenderFrameHost objects. It observes the plugin crash and favicon
// update events, which the FilterMessagesWhileSwappedOut test simulates being
// sent. The test is successful if the event is not observed.
// See http://crbug.com/351815
class PluginFaviconMessageObserver : public WebContentsObserver {
public:
explicit PluginFaviconMessageObserver(WebContents* web_contents)
: WebContentsObserver(web_contents),
plugin_crashed_(false),
favicon_received_(false) {}
PluginFaviconMessageObserver(const PluginFaviconMessageObserver&) = delete;
PluginFaviconMessageObserver& operator=(const PluginFaviconMessageObserver&) =
delete;
void PluginCrashed(const base::FilePath& plugin_path,
base::ProcessId plugin_pid) override {
plugin_crashed_ = true;
}
void DidUpdateFaviconURL(
RenderFrameHost* render_frame_host,
const std::vector<blink::mojom::FaviconURLPtr>& candidates) override {
favicon_received_ = true;
}
bool plugin_crashed() { return plugin_crashed_; }
bool favicon_received() { return favicon_received_; }
private:
bool plugin_crashed_;
bool favicon_received_;
};
// A shorter version for RenderFrameHostManager::DidNavigateFrame(rfh, ...).
// This provides all the arguments that aren't tested in this file.
void DidNavigateFrame(RenderFrameHostManager* rfh_manager,
RenderFrameHostImpl* rfh) {
rfh_manager->DidNavigateFrame(rfh, true /* was_caused_by_user_gesture */,
false /* is_same_document_navigation */,
false /* clear_proxies_on_commit */,
blink::FramePolicy(),
true /* allow_paint_holding */);
}
class TestDevToolsClientHost : public DevToolsAgentHostClient {
public:
TestDevToolsClientHost() = default;
TestDevToolsClientHost(const TestDevToolsClientHost&) = delete;
TestDevToolsClientHost& operator=(const TestDevToolsClientHost&) = delete;
void Close() { agent_host_->DetachClient(this); }
void AgentHostClosed(DevToolsAgentHost* agent_host) override {}
void DispatchProtocolMessage(DevToolsAgentHost* agent_host,
base::span<const uint8_t> message) override {}
void InspectAgentHost(DevToolsAgentHost* agent_host) {
agent_host_ = agent_host;
agent_host_->AttachClient(this);
}
DevToolsAgentHost* agent_host() { return agent_host_.get(); }
private:
scoped_refptr<DevToolsAgentHost> agent_host_;
};
} // namespace
// Test that the "level" feature param has the expected effect.
class RenderDocumentFeatureTest : public testing::Test {
protected:
void SetLevel(const RenderDocumentLevel level) {
InitAndEnableRenderDocumentFeature(&feature_list_,
GetRenderDocumentLevelName(level));
}
void DisableRenderDocument() {
feature_list_.InitAndDisableFeature(features::kRenderDocument);
}
private:
base::test::ScopedFeatureList feature_list_;
};
TEST_F(RenderDocumentFeatureTest, FeatureDisabled) {
DisableRenderDocument();
// Non-local-root subframe.
EXPECT_FALSE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/false, /*is_local_root=*/false));
// Local root subframe.
EXPECT_FALSE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/false, /*is_local_root=*/true));
// Main frame.
EXPECT_FALSE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/true, /*is_local_root=*/true));
// Crashed main frame.
EXPECT_TRUE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/true, /*is_local_root=*/true,
/*has_committed_any_navigation=*/true, /*must_be_replaced=*/true));
}
TEST_F(RenderDocumentFeatureTest, LevelCrashed) {
SetLevel(RenderDocumentLevel::kCrashedFrame);
// Non-local-root subframe.
EXPECT_FALSE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/false, /*is_local_root=*/false));
// Local root subframe.
EXPECT_FALSE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/false, /*is_local_root=*/true));
// Main frame.
EXPECT_FALSE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/true, /*is_local_root=*/true));
// Crashed main frame.
EXPECT_TRUE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/true, /*is_local_root=*/true,
/*has_committed_any_navigation=*/true, /*must_be_replaced=*/true));
}
TEST_F(RenderDocumentFeatureTest, LevelNonLocalRootSubframe) {
SetLevel(RenderDocumentLevel::kNonLocalRootSubframe);
// Non-local-root subframe.
EXPECT_TRUE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/false, /*is_local_root=*/false));
// Initial non-local-root subframe.
EXPECT_FALSE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/false, /*is_local_root=*/false,
/*has_committed_any_navigation=*/false));
// Crashed non-local-root subframe.
EXPECT_TRUE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/false, /*is_local_root=*/false,
/*has_committed_any_navigation=*/false, /*must_be_replaced=*/true));
EXPECT_TRUE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/false, /*is_local_root=*/false,
/*has_committed_any_navigation=*/true, /*must_be_replaced=*/true));
// Local root subframe.
EXPECT_FALSE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/false, /*is_local_root=*/true));
// Main frame.
EXPECT_FALSE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/true, /*is_local_root=*/true));
}
TEST_F(RenderDocumentFeatureTest, LevelSubframe) {
SetLevel(RenderDocumentLevel::kSubframe);
// Non-local-root subframe.
EXPECT_TRUE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/false, /*is_local_root=*/false));
// Local root subframe.
EXPECT_TRUE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/false, /*is_local_root=*/true));
// Initial local root subframe.
EXPECT_FALSE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/false, /*is_local_root=*/true,
/*has_committed_any_navigation=*/false));
// Crashed local root subframe.
EXPECT_TRUE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/false, /*is_local_root=*/true,
/*has_committed_any_navigation=*/false, /*must_be_replaced=*/true));
EXPECT_TRUE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/false, /*is_local_root=*/true,
/*has_committed_any_navigation=*/true, /*must_be_replaced=*/true));
// Main frame.
EXPECT_FALSE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/true, /*is_local_root=*/true));
}
TEST_F(RenderDocumentFeatureTest, LevelAllFrames) {
SetLevel(RenderDocumentLevel::kAllFrames);
// Non-local-root subframe.
EXPECT_TRUE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/false, /*is_local_root=*/false));
// Local root subframe.
EXPECT_TRUE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/false, /*is_local_root=*/true));
// Main frame.
EXPECT_TRUE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/true, /*is_local_root=*/true));
// Initial main frame.
EXPECT_FALSE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/true, /*is_local_root=*/true,
/*has_committed_any_navigation=*/false));
// Crashed main frame.
EXPECT_TRUE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/true, /*is_local_root=*/true,
/*has_committed_any_navigation=*/false, /*must_be_replaced=*/true));
EXPECT_TRUE(ShouldCreateNewRenderFrameHostOnSameSiteNavigation(
/*is_main_frame=*/true, /*is_local_root=*/true,
/*has_committed_any_navigation=*/true, /*must_be_replaced=*/true));
}
class RenderFrameHostManagerTest
: public RenderViewHostImplTestHarness,
public ::testing::WithParamInterface<std::string> {
public:
RenderFrameHostManagerTest() {
InitAndEnableRenderDocumentFeature(&feature_list_, GetParam());
}
void SetUp() override {
RenderViewHostImplTestHarness::SetUp();
if (IsIsolatedOriginRequiredToGuaranteeDedicatedProcess()) {
// Isolate |isolated_cross_site_url()|so it cannot share a process
// with another site.
ChildProcessSecurityPolicyImpl::GetInstance()->AddFutureIsolatedOrigins(
{url::Origin::Create(isolated_cross_site_url())},
ChildProcessSecurityPolicy::IsolatedOriginSource::TEST,
browser_context());
// Reset the WebContents so the isolated origin will be honored by
// all BrowsingInstances used in the test.
SetContents(CreateTestWebContents());
}
}
GURL isolated_cross_site_url() const {
return GURL("http://isolated-cross-site.com");
}
// Creates an inactive test RenderViewHost.
void CreateInactiveRenderViewHost() {
const GURL kChromeURL(GetWebUIURL("foo"));
const GURL kDestUrl("http://www.google.com/");
// Navigate our first tab to a chrome url and then to the destination.
NavigationSimulator::NavigateAndCommitFromBrowser(contents(), kChromeURL);
TestRenderFrameHost* ntp_rfh = contents()->GetPrimaryMainFrame();
// Navigate to a cross-site URL.
auto navigation =
NavigationSimulator::CreateBrowserInitiated(kDestUrl, contents());
navigation->ReadyToCommit();
EXPECT_TRUE(contents()->CrossProcessNavigationPending());
// Manually increase the number of active frames in the
// SiteInstanceGroup that ntp_rfh belongs to, to prevent the
// SiteInstanceGroup from being destroyed when ntp_rfh goes away.
ntp_rfh->GetSiteInstance()->group()->IncrementActiveFrameCount();
TestRenderFrameHost* dest_rfh =
contents()->GetSpeculativePrimaryMainFrame();
CHECK(dest_rfh);
EXPECT_NE(ntp_rfh, dest_rfh);
// Commit. This replaces ntp_rfh with a proxy and leaves its RVH inactive.
navigation->Commit();
}
// Returns the RenderFrameHost that should be used in the navigation to
// |entry|.
RenderFrameHostImpl* NavigateToEntry(RenderFrameHostManager* manager,
NavigationEntryImpl* entry) {
// Tests currently only navigate using main frame FrameNavigationEntries.
FrameNavigationEntry* frame_entry = entry->root_node()->frame_entry.get();
FrameTreeNode* frame_tree_node =
manager->current_frame_host()->frame_tree_node();
NavigationControllerImpl& controller = manager->current_frame_host()
->frame_tree_node()
->navigator()
.controller();
blink::mojom::NavigationType navigate_type =
entry->IsRestored() ? blink::mojom::NavigationType::RESTORE
: blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
scoped_refptr<network::ResourceRequestBody> request_body;
std::string post_content_type;
bool is_form_submission = false;
if (frame_entry->method() == "POST") {
request_body = frame_entry->GetPostData(&post_content_type);
// Might have a LF at end.
post_content_type = std::string(
base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
is_form_submission = !!request_body;
}
auto& referrer = frame_entry->referrer();
blink::mojom::CommonNavigationParamsPtr common_params =
entry->ConstructCommonNavigationParams(
*frame_entry, request_body, frame_entry->url(),
blink::mojom::Referrer::New(referrer.url, referrer.policy),
navigate_type, base::TimeTicks::Now() /* actual_navigation_start */,
base::TimeTicks::Now() /* navigation_start */,
base::TimeTicks::Now() /* input_start */);
blink::mojom::CommitNavigationParamsPtr commit_params =
entry->ConstructCommitNavigationParams(
*frame_entry, common_params->url, common_params->method,
entry->GetSubframeUniqueNames(frame_tree_node),
controller.GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
controller.GetIndexOfEntry(entry),
controller.GetLastCommittedEntryIndex(), controller.GetEntryCount(),
frame_tree_node->current_replication_state().frame_policy,
frame_tree_node->AncestorOrSelfHasCSPEE(),
blink::mojom::SystemEntropy::kNormal,
/*soft_navigation_heuristics_task_id=*/std::nullopt);
commit_params->post_content_type = post_content_type;
std::unique_ptr<NavigationRequest> navigation_request =
NavigationRequest::Create(
frame_tree_node, std::move(common_params), std::move(commit_params),
!entry->is_renderer_initiated(), false /* was_opener_suppressed */,
std::nullopt /* initiator_frame_token */,
ChildProcessHost::kInvalidUniqueID /* initiator_process_id */,
entry->extra_headers(), frame_entry, entry, is_form_submission,
nullptr /* navigation_ui_data */, std::nullopt /* impression */,
blink::mojom::NavigationInitiatorActivationAndAdStatus::
kDidNotStartWithTransientActivation,
false /* is_pdf */);
// Simulates request creation that triggers the 1st internal call to
// GetFrameHostForNavigation.
frame_tree_node->TakeNavigationRequest(std::move(navigation_request));
// And also simulates the 2nd and final call to GetFrameHostForNavigation
// that determines the final frame that will commit the navigation.
BrowsingContextGroupSwap ignored_bcg_swap_info =
BrowsingContextGroupSwap::CreateDefault();
TestRenderFrameHost* frame_host = static_cast<TestRenderFrameHost*>(
manager
->GetFrameHostForNavigation(
frame_tree_node->navigation_request(), &ignored_bcg_swap_info,
ProcessAllocationContext{ProcessAllocationSource::kTest})
.value());
CHECK(frame_host);
frame_host->SetPolicyContainerHost(
base::MakeRefCounted<PolicyContainerHost>());
return frame_host;
}
// Returns the speculative RenderFrameHost.
RenderFrameHostImpl* GetPendingFrameHost(RenderFrameHostManager* manager) {
return manager->speculative_render_frame_host_.get();
}
// Exposes RenderFrameHostManager::CollectOpenerFrameTrees for testing.
void CollectOpenerFrameTrees(
FrameTreeNode* node,
SiteInstanceGroup* site_instance_group,
std::vector<FrameTree*>* opener_frame_trees,
std::unordered_set<FrameTreeNode*>* nodes_with_back_links,
std::unordered_set<FrameTreeNode*>*
cross_browsing_context_group_openers) {
node->render_manager()->CollectOpenerFrameTrees(
site_instance_group, opener_frame_trees, nodes_with_back_links);
}
private:
RenderFrameHostManagerTestWebUIControllerFactory factory_;
ScopedWebUIControllerFactoryRegistration factory_registration_{&factory_};
base::test::ScopedFeatureList feature_list_;
};
// Tests that when you navigate from a chrome:// url to another page, and
// then do that same thing in another tab, that the two resulting pages have
// different SiteInstances, BrowsingInstances, and RenderProcessHosts. This is
// a regression test for bug 9364.
TEST_P(RenderFrameHostManagerTest, ChromeSchemeProcesses) {
const GURL kChromeUrl(GetWebUIURL("foo"));
const GURL kDestUrl("http://www.google.com/");
// Navigate our first tab to the chrome url and then to the destination,
// ensuring we grant bindings to the chrome URL.
NavigationSimulator::NavigateAndCommitFromBrowser(contents(), kChromeUrl);
EXPECT_TRUE(
main_rfh()->GetEnabledBindings().Has(BindingsPolicyValue::kWebUi));
NavigationSimulator::NavigateAndCommitFromBrowser(contents(), kDestUrl);
EXPECT_FALSE(contents()->GetSpeculativePrimaryMainFrame());
// Make a second tab.
std::unique_ptr<TestWebContents> contents2(
TestWebContents::Create(browser_context(), nullptr));
// Load the two URLs in the second tab. Note that the first navigation creates
// a RFH that's not pending (since there is no cross-site transition), so
// we use the committed one.
auto navigation1 =
NavigationSimulator::CreateBrowserInitiated(kChromeUrl, contents2.get());
navigation1->Start();
EXPECT_FALSE(contents2->CrossProcessNavigationPending());
navigation1->Commit();
// The second one is the opposite, creating a cross-site transition.
auto navigation2 =
NavigationSimulator::CreateBrowserInitiated(kDestUrl, contents2.get());
navigation2->Start();
EXPECT_TRUE(contents2->CrossProcessNavigationPending());
TestRenderFrameHost* dest_rfh2 = contents2->GetSpeculativePrimaryMainFrame();
ASSERT_TRUE(dest_rfh2);
navigation2->Commit();
// The two RFH's should be different in every way.
EXPECT_NE(contents()->GetPrimaryMainFrame()->GetProcess(),
dest_rfh2->GetProcess());
EXPECT_NE(contents()->GetPrimaryMainFrame()->GetSiteInstance(),
dest_rfh2->GetSiteInstance());
EXPECT_FALSE(dest_rfh2->GetSiteInstance()->IsRelatedSiteInstance(
contents()->GetPrimaryMainFrame()->GetSiteInstance()));
// Navigate both to a chrome://... URL, and verify that they have a separate
// RenderProcessHost and a separate SiteInstance.
NavigationSimulator::NavigateAndCommitFromBrowser(contents(), kChromeUrl);
EXPECT_FALSE(contents()->GetSpeculativePrimaryMainFrame());
NavigationSimulator::NavigateAndCommitFromBrowser(contents2.get(),
kChromeUrl);
EXPECT_NE(contents()->GetPrimaryMainFrame()->GetSiteInstance(),
contents2->GetPrimaryMainFrame()->GetSiteInstance());
EXPECT_NE(contents()->GetPrimaryMainFrame()->GetSiteInstance()->GetProcess(),
contents2->GetPrimaryMainFrame()->GetSiteInstance()->GetProcess());
}
// Ensure that the browser ignores most IPC messages that arrive from a
// RenderViewHost that has been swapped out. We do not want to take
// action on requests from a non-active renderer. The main exception is
// for synchronous messages, which cannot be ignored without leaving the
// renderer in a stuck state. See http://crbug.com/93427.
TEST_P(RenderFrameHostManagerTest, FilterMessagesWhileSwappedOut) {
const GURL kChromeURL(GetWebUIURL("foo"));
const GURL kDestUrl("http://www.google.com/");
std::vector<blink::mojom::FaviconURLPtr> icons;
// Navigate our first tab to a chrome url and then to the destination.
NavigationSimulator::NavigateAndCommitFromBrowser(contents(), kChromeURL);
TestRenderFrameHost* ntp_rfh = contents()->GetPrimaryMainFrame();
// Send an update favicon message and make sure it works.
{
PluginFaviconMessageObserver observer(contents());
ntp_rfh->UpdateFaviconURL(std::move(icons));
EXPECT_TRUE(observer.favicon_received());
}
// Create one more frame in the same SiteInstanceGroup where ntp_rfh
// exists so that it doesn't get deleted on navigation to another
// site.
ntp_rfh->GetSiteInstance()->group()->IncrementActiveFrameCount();
// Navigate to a cross-site URL (don't unload to keep |ntp_rfh| alive).
auto navigation =
NavigationSimulatorImpl::CreateBrowserInitiated(kDestUrl, contents());
navigation->set_drop_unload_ack(true);
navigation->Commit();
TestRenderFrameHost* dest_rfh = contents()->GetPrimaryMainFrame();
ASSERT_TRUE(dest_rfh);
EXPECT_NE(ntp_rfh, dest_rfh);
// The new RVH should be able to update its favicon.
{
PluginFaviconMessageObserver observer(contents());
dest_rfh->UpdateFaviconURL(std::move(icons));
EXPECT_TRUE(observer.favicon_received());
}
// The old renderer, being slow, now updates the favicon. It should be
// filtered out and not take effect.
{
PluginFaviconMessageObserver observer(contents());
ntp_rfh->UpdateFaviconURL(std::move(icons));
EXPECT_FALSE(observer.favicon_received());
}
}
// Test that the UpdateFaviconURL function is ignored if the
// renderer is in the pending deletion state. The favicon code assumes
// that it only gets UpdateFaviconURL function for the most
// recently committed navigation for each WebContentsImpl.
TEST_P(RenderFrameHostManagerTest, UpdateFaviconURLWhilePendingUnload) {
const GURL kChromeURL(GetWebUIURL("foo"));
const GURL kDestUrl("http://www.google.com/");
std::vector<blink::mojom::FaviconURLPtr> icons;
// Navigate our first tab to a chrome url and then to the destination.
NavigationSimulator::NavigateAndCommitFromBrowser(contents(), kChromeURL);
TestRenderFrameHost* ntp_rfh = contents()->GetPrimaryMainFrame();
// Send an update favicon message and make sure it works.
{
PluginFaviconMessageObserver observer(contents());
ntp_rfh->UpdateFaviconURL(std::move(icons));
EXPECT_TRUE(observer.favicon_received());
}
// Create one more frame in the same SiteInstanceGroup where |ntp_rfh| exists
// so that it doesn't get deleted on navigation to another site.
ntp_rfh->GetSiteInstance()->group()->IncrementActiveFrameCount();
// Navigate to a cross-site URL and commit the new page.
auto navigation =
NavigationSimulatorImpl::CreateBrowserInitiated(kDestUrl, contents());
navigation->set_drop_unload_ack(true);
navigation->Commit();
TestRenderFrameHost* dest_rfh = contents()->GetPrimaryMainFrame();
EXPECT_TRUE(ntp_rfh->IsPendingDeletion());
EXPECT_TRUE(dest_rfh->IsActive());
// The new RFH should be able to update its favicons.
{
PluginFaviconMessageObserver observer(contents());
dest_rfh->UpdateFaviconURL(std::move(icons));
EXPECT_TRUE(observer.favicon_received());
}
// The old renderer, being slow, now updates its favicons. The message should
// be ignored.
{
PluginFaviconMessageObserver observer(contents());
ntp_rfh->UpdateFaviconURL(std::move(icons));
EXPECT_FALSE(observer.favicon_received());
}
}
// Test if RenderViewHost::GetRenderWidgetHosts() only returns active
// widgets.
TEST_P(RenderFrameHostManagerTest, GetRenderWidgetHostsReturnsActiveViews) {
CreateInactiveRenderViewHost();
std::unique_ptr<RenderWidgetHostIterator> widgets(
RenderWidgetHost::GetRenderWidgetHosts());
// We know that there is the only one active widget. Another view is
// now inactive, so the inactive view is not included in the list.
RenderWidgetHost* widget = widgets->GetNextHost();
EXPECT_FALSE(widgets->GetNextHost());
RenderViewHost* rvh = RenderViewHost::From(widget);
EXPECT_TRUE(static_cast<RenderViewHostImpl*>(rvh)->is_active());
}
// Test if RenderViewHost::GetRenderWidgetHosts() returns a subset of
// RenderViewHostImpl::GetAllRenderWidgetHosts().
// RenderViewHost::GetRenderWidgetHosts() returns only active widgets, but
// RenderViewHostImpl::GetAllRenderWidgetHosts() returns everything
// including inactive ones.
TEST_P(RenderFrameHostManagerTest,
GetRenderWidgetHostsWithinGetAllRenderWidgetHosts) {
CreateInactiveRenderViewHost();
std::unique_ptr<RenderWidgetHostIterator> widgets(
RenderWidgetHost::GetRenderWidgetHosts());
while (RenderWidgetHost* w = widgets->GetNextHost()) {
bool found = false;
std::unique_ptr<RenderWidgetHostIterator> all_widgets(
RenderWidgetHostImpl::GetAllRenderWidgetHosts());
while (RenderWidgetHost* widget = all_widgets->GetNextHost()) {
if (w == widget) {
found = true;
break;
}
}
EXPECT_TRUE(found);
}
}
// Test if SiteInstanceImpl::active_frame_count() is correctly updated
// as frames in a SiteInstance get replaced.
TEST_P(RenderFrameHostManagerTest, ActiveFrameCountWhileSwappingInAndOut) {
const GURL kUrl1("http://www.google.com/");
const GURL kUrl2("http://www.chromium.org/");
// Navigate to an initial URL.
contents()->NavigateAndCommit(kUrl1);
TestRenderFrameHost* rfh1 = main_test_rfh();
SiteInstanceImpl* instance1 = rfh1->GetSiteInstance();
EXPECT_EQ(instance1->group()->active_frame_count(), 1U);
// Create 2 new tabs and simulate them being the opener chain for the main
// tab. They should be in the same SiteInstance.
std::unique_ptr<TestWebContents> opener1(
TestWebContents::Create(browser_context(), instance1));
contents()->SetOpener(opener1.get());
std::unique_ptr<TestWebContents> opener2(
TestWebContents::Create(browser_context(), instance1));
opener1->SetOpener(opener2.get());
EXPECT_EQ(instance1->group()->active_frame_count(), 3U);
// Navigate to a cross-site URL (different SiteInstance but same
// BrowsingInstance).
contents()->NavigateAndCommit(kUrl2);
TestRenderFrameHost* rfh2 = main_test_rfh();
SiteInstanceImpl* instance2 = rfh2->GetSiteInstance();
if (AreAllSitesIsolatedForTesting()) {
// rvh2 is on chromium.org which is different from google.com on
// which other tabs are.
EXPECT_EQ(instance2->group()->active_frame_count(), 1U);
// There are two active views on google.com now.
EXPECT_EQ(instance1->group()->active_frame_count(), 2U);
} else if (ShouldUseDefaultSiteInstanceGroup()) {
// If default SiteInstanceGroups are used, the SiteInstances should be
// different, but active frame count is per group, so the active frame count
// is the same as that of default SiteInstance.
EXPECT_EQ(instance1->group()->active_frame_count(), 3U);
EXPECT_EQ(instance1->group(), instance2->group());
EXPECT_NE(instance1, instance2);
} else {
EXPECT_TRUE(instance1->IsDefaultSiteInstance());
EXPECT_EQ(instance1->group()->active_frame_count(), 3U);
EXPECT_EQ(instance1, instance2);
}
// Navigate to the original origin (google.com).
contents()->NavigateAndCommit(kUrl1);
EXPECT_EQ(instance1->group()->active_frame_count(), 3U);
}
// This deletes a WebContents when the given RVH is deleted. This is
// only for testing whether deleting an RVH does not cause any UaF in
// other parts of the system. For now, this class is only used for the
// next test cases to detect the bug mentioned at
// http://crbug.com/259859.
class RenderViewHostDestroyer : public WebContentsObserver {
public:
RenderViewHostDestroyer(RenderViewHost* render_view_host,
std::unique_ptr<WebContents> web_contents)
: WebContentsObserver(WebContents::FromRenderViewHost(render_view_host)),
render_view_host_(render_view_host),
web_contents_(std::move(web_contents)) {}
RenderViewHostDestroyer(const RenderViewHostDestroyer&) = delete;
RenderViewHostDestroyer& operator=(const RenderViewHostDestroyer&) = delete;
void RenderViewDeleted(RenderViewHost* render_view_host) override {
if (render_view_host == render_view_host_)
web_contents_.reset();
}
private:
raw_ptr<RenderViewHost, DanglingUntriaged> render_view_host_;
std::unique_ptr<WebContents> web_contents_;
};
// Test if ShutdownRenderViewHostsInSiteInstance() does not touch any
// RenderWidget that has been freed while deleting a RenderViewHost in
// a previous iteration. This is a regression test for
// http://crbug.com/259859.
TEST_P(RenderFrameHostManagerTest,
DetectUseAfterFreeInShutdownRenderViewHostsInSiteInstance) {
const GURL kChromeURL(GetWebUIURL("newtab"));
const GURL kUrl1("http://www.google.com");
const GURL kUrl2("http://www.chromium.org");
// Navigate our first tab to a chrome url and then to the destination.
NavigationSimulator::NavigateAndCommitFromBrowser(contents(), kChromeURL);
TestRenderFrameHost* ntp_rfh = contents()->GetPrimaryMainFrame();
// Create one more tab and navigate to kUrl1. web_contents is not
// wrapped as scoped_ptr since it intentionally deleted by destroyer
// below as part of this test.
std::unique_ptr<TestWebContents> web_contents =
TestWebContents::Create(browser_context(), ntp_rfh->GetSiteInstance());
web_contents->NavigateAndCommit(kUrl1);
RenderViewHostDestroyer destroyer(ntp_rfh->GetRenderViewHost(),
std::move(web_contents));
// This causes the first tab to navigate to kUrl2, which destroys
// the ntp_rfh in ShutdownRenderViewHostsInSiteInstance(). When
// ntp_rfh is destroyed, it also destroys the RVHs in web_contents
// too. This can test whether
// SiteInstanceImpl::ShutdownRenderViewHostsInSiteInstance() can
// touch any object freed in this way or not while iterating through
// all widgets.
contents()->NavigateAndCommit(kUrl2);
}
// Stub out local frame mojo binding. Intercepts calls to EnableViewSourceMode
// and marks the message as received. This class attaches to the first
// RenderFrameHostImpl created.
class EnableViewSourceLocalFrame : public content::FakeLocalFrame,
public WebContentsObserver {
public:
explicit EnableViewSourceLocalFrame(WebContents* web_contents)
: WebContentsObserver(web_contents) {}
void ReadyToCommitNavigation(NavigationHandle* navigation_handle) override {
if (!initialized_) {
initialized_ = true;
Init(navigation_handle->GetRenderFrameHost()
->GetRemoteAssociatedInterfaces());
}
}
void EnableViewSourceMode() final { enabled_view_source_ = true; }
bool IsViewSourceModeEnabled() const { return enabled_view_source_; }
void ResetState() { enabled_view_source_ = false; }
private:
bool enabled_view_source_ = false;
bool initialized_ = false;
};
// When there is an error with the specified page, renderer exits view-source
// mode. See WebFrameImpl::DidFail(). We check by this test that
// EnableViewSourceMode message is sent on every navigation regardless
// `blink::WebView` is being newly created or reused.
TEST_P(RenderFrameHostManagerTest, AlwaysSendEnableViewSourceMode) {
const GURL kChromeUrl(GetWebUIURL("foo"));
const GURL kUrl("http://foo/");
const GURL kViewSourceUrl("view-source:http://foo/");
// We have to navigate to some page at first since without this, the first
// navigation will reuse the SiteInstance created by Init(), and the second
// one will create a new SiteInstance. Because current_instance and
// new_instance will be different, a new RenderViewHost will be created for
// the second navigation. We have to avoid this in order to exercise the
// target code path.
NavigationSimulator::NavigateAndCommitFromBrowser(contents(), kChromeUrl);
EnableViewSourceLocalFrame local_frame(contents());
// Navigate. Note that "view source" URLs are implemented by putting the RFH
// into a view-source mode and then navigating to the inner URL, so that's why
// the bare URL is what's committed and returned by the last committed entry's
// GetURL() call.
auto navigation = NavigationSimulatorImpl::CreateBrowserInitiated(
kViewSourceUrl, contents());
navigation->Start();
NavigationRequest* request =
main_test_rfh()->frame_tree_node()->navigation_request();
CHECK(request);
ASSERT_TRUE(contents()->GetSpeculativePrimaryMainFrame())
<< "Expected new pending RenderFrameHost to be created.";
RenderFrameHost* last_rfh = contents()->GetSpeculativePrimaryMainFrame();
navigation->Commit();
EXPECT_EQ(1, controller().GetLastCommittedEntryIndex());
NavigationEntry* last_committed = controller().GetLastCommittedEntry();
ASSERT_NE(nullptr, last_committed);
EXPECT_EQ(kUrl, last_committed->GetURL());
EXPECT_EQ(kViewSourceUrl, last_committed->GetVirtualURL());
EXPECT_FALSE(controller().GetPendingEntry());
// The RFH should have been put in view-source mode.
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(local_frame.IsViewSourceModeEnabled());
local_frame.ResetState();
// Navigate, again.
navigation = NavigationSimulatorImpl::CreateBrowserInitiated(kViewSourceUrl,
contents());
navigation->Start();
request = main_test_rfh()->frame_tree_node()->navigation_request();
CHECK(request);
// The same RenderFrameHost should be reused, unless RenderDocument for all
// frames is enabled, which will create a new speculative RenderFrameHost.
// In that case, view-source mode enabling will be done on the new RenderFrame
// instead. To capture that, create a new EnableViewSourceLocalFrame for the
// new RenderFrame.
EnableViewSourceLocalFrame local_frame2(contents());
navigation->ReadyToCommit();
EXPECT_EQ(ShouldCreateNewHostForAllFrames(),
!!contents()->GetSpeculativePrimaryMainFrame());
EXPECT_EQ(last_rfh, contents()->GetPrimaryMainFrame());
navigation->Commit();
EXPECT_EQ(1, controller().GetLastCommittedEntryIndex());
EXPECT_FALSE(controller().GetPendingEntry());
// New message should be sent out to make sure to enter view-source mode.
base::RunLoop().RunUntilIdle();
if (ShouldCreateNewHostForAllFrames()) {
EXPECT_TRUE(local_frame2.IsViewSourceModeEnabled());
} else {
EXPECT_TRUE(local_frame.IsViewSourceModeEnabled());
}
}
// Tests the Init function by checking the initial RenderViewHost.
TEST_P(RenderFrameHostManagerTest, Init) {
// Using TestBrowserContext.
scoped_refptr<SiteInstanceImpl> instance =
SiteInstanceImpl::Create(browser_context());
EXPECT_FALSE(instance->HasSite());
std::unique_ptr<TestWebContents> web_contents(
TestWebContents::Create(browser_context(), instance));
RenderFrameHostManager* manager =
web_contents->GetPrimaryFrameTree().root()->render_manager();
RenderFrameHostImpl* rfh = manager->current_frame_host();
RenderViewHostImpl* rvh = rfh->render_view_host();
ASSERT_TRUE(rfh);
ASSERT_TRUE(rvh);
EXPECT_EQ(instance, rfh->GetSiteInstance());
EXPECT_EQ(web_contents.get(), rvh->GetDelegate());
EXPECT_EQ(web_contents.get(), rfh->delegate());
EXPECT_TRUE(manager->GetRenderWidgetHostView());
}
// Tests the Navigate function. We navigate three sites consecutively and check
// how the pending/committed RenderViewHost are modified.
TEST_P(RenderFrameHostManagerTest, Navigate) {
std::unique_ptr<TestWebContents> web_contents(TestWebContents::Create(
browser_context(), SiteInstance::Create(browser_context())));
RenderFrameHostManager* manager =
web_contents->GetPrimaryFrameTree().root()->render_manager();
RenderFrameHostImpl* host = nullptr;
RenderViewHost* initial_render_view_host = nullptr;
// 1) The first navigation. --------------------------
const GURL kUrl1("http://www.google.com/");
NavigationEntryImpl entry1(
nullptr /* instance */, kUrl1, Referrer(),
/* initiator_origin= */ std::nullopt,
/* initiator_base_url= */ std::nullopt, std::u16string() /* title */,
ui::PAGE_TRANSITION_TYPED, false /* is_renderer_init */,
nullptr /* blob_url_loader_factory */, false /* is_initial_entry */);
host = NavigateToEntry(manager, &entry1);
// The RenderFrameHost created in Init will be reused.
EXPECT_TRUE(host == manager->current_frame_host());
EXPECT_FALSE(GetPendingFrameHost(manager));
// Commit.
DidNavigateFrame(manager, host);
// Commit to SiteInstance should be delayed until RenderFrame commit.
EXPECT_TRUE(host == manager->current_frame_host());
ASSERT_TRUE(host);
EXPECT_FALSE(host->GetSiteInstance()->HasSite());
host->GetSiteInstance()->SetSite(UrlInfo::CreateForTesting(kUrl1));
manager->GetRenderWidgetHostView()->SetBackgroundColor(SK_ColorRED);
// 2) Navigate to next site. -------------------------
const GURL kUrl2("http://www.google.com/foo");
const url::Origin kInitiatorOrigin =
url::Origin::Create(GURL("https://initiator.example.com"));
NavigationEntryImpl entry2(
nullptr /* instance */, kUrl2,
Referrer(kUrl1, network::mojom::ReferrerPolicy::kDefault),
kInitiatorOrigin, /* initiator_base_url= */ std::nullopt,
std::u16string() /* title */, ui::PAGE_TRANSITION_LINK,
true /* is_renderer_init */, nullptr /* blob_url_loader_factory */,
false /* is_initial_entry */);
host = NavigateToEntry(manager, &entry2);
initial_render_view_host = host->GetRenderViewHost();
EXPECT_TRUE(initial_render_view_host);
// The RenderFrameHost created in Init will be reused.
EXPECT_TRUE(host == manager->current_frame_host());
EXPECT_FALSE(GetPendingFrameHost(manager));
// Commit.
DidNavigateFrame(manager, host);
EXPECT_TRUE(host == manager->current_frame_host());
ASSERT_TRUE(host);
EXPECT_TRUE(host->GetSiteInstance()->HasSite());
ASSERT_TRUE(manager->GetRenderWidgetHostView()->GetBackgroundColor());
EXPECT_EQ(SK_ColorRED,
*manager->GetRenderWidgetHostView()->GetBackgroundColor());
// 3) Cross-site navigate to next site. --------------
const GURL kUrl3("http://webkit.org/");
NavigationEntryImpl entry3(
nullptr /* instance */, kUrl3,
Referrer(kUrl2, network::mojom::ReferrerPolicy::kDefault),
/* initiator_origin= */ std::nullopt,
/* initiator_base_url= */ std::nullopt, std::u16string() /* title */,
ui::PAGE_TRANSITION_LINK, false /* is_renderer_init */,
nullptr /* blob_url_loader_factory */, false /* is_initial_entry */);
host = NavigateToEntry(manager, &entry3);
// A new RenderFrameHost should be created.
EXPECT_TRUE(GetPendingFrameHost(manager));
ASSERT_EQ(host, GetPendingFrameHost(manager));
// Commit.
DidNavigateFrame(manager, GetPendingFrameHost(manager));
EXPECT_TRUE(host == manager->current_frame_host());
ASSERT_TRUE(host);
EXPECT_TRUE(host->GetSiteInstance()->HasSite());
EXPECT_NE(initial_render_view_host, host->GetRenderViewHost());
// Check the pending RenderFrameHost has been committed.
EXPECT_FALSE(GetPendingFrameHost(manager));
ASSERT_TRUE(manager->GetRenderWidgetHostView()->GetBackgroundColor());
EXPECT_EQ(SK_ColorRED,
*manager->GetRenderWidgetHostView()->GetBackgroundColor());
}
// Tests WebUI creation.
TEST_P(RenderFrameHostManagerTest, WebUI) {
scoped_refptr<SiteInstance> instance =
SiteInstance::Create(browser_context());
std::unique_ptr<TestWebContents> web_contents(
TestWebContents::Create(browser_context(), instance));
RenderFrameHostManager* manager =
web_contents->GetPrimaryFrameTree().root()->render_manager();
RenderFrameHostImpl* initial_rfh = manager->current_frame_host();
EXPECT_FALSE(initial_rfh->render_view_host()->IsRenderViewLive());
EXPECT_FALSE(manager->current_frame_host()->web_ui());
EXPECT_TRUE(initial_rfh);
const GURL kUrl(GetWebUIURL("foo"));
NavigationEntryImpl entry(
nullptr /* instance */, kUrl, Referrer(),
/* initiator_origin= */ std::nullopt,
/* initiator_base_url= */ std::nullopt, std::u16string() /* title */,
ui::PAGE_TRANSITION_TYPED, false /* is_renderer_init */,
nullptr /* blob_url_loader_factory */, false /* is_initial_entry */);
RenderFrameHostImpl* host = NavigateToEntry(manager, &entry);
// The initial non-live RenderFrameHost should be reused for the new WebUI
// navigation. We test a case where it is live in WebUIInNewTab.
EXPECT_TRUE(host);
EXPECT_EQ(initial_rfh, host);
EXPECT_EQ(host, manager->current_frame_host());
EXPECT_FALSE(GetPendingFrameHost(manager));
// It's important that the SiteInstance get set on the Web UI page as soon
// as the navigation starts, rather than lazily after it commits, so we don't
// try to re-use the SiteInstance/process for non Web UI things that may
// get loaded in between.
EXPECT_TRUE(host->GetSiteInstance()->HasSite());
EXPECT_EQ(kUrl, host->GetSiteInstance()->GetSiteURL());
// There will be a WebUI because GetFrameHostForNavigation was already called
// twice.
EXPECT_TRUE(host->web_ui());
EXPECT_TRUE(manager->current_frame_host()->web_ui());
// Commit.
DidNavigateFrame(manager, host);
EXPECT_TRUE(host->GetEnabledBindings().Has(BindingsPolicyValue::kWebUi));
}
// Tests that we can open a WebUI link in a new tab from a WebUI page and still
// grant the correct bindings. http://crbug.com/189101.
TEST_P(RenderFrameHostManagerTest, WebUIInNewTab) {
scoped_refptr<SiteInstance> blank_instance =
SiteInstance::Create(browser_context());
blank_instance->GetOrCreateProcess()->Init();
// Create a blank tab.
std::unique_ptr<TestWebContents> web_contents1(
TestWebContents::Create(browser_context(), blank_instance));
RenderFrameHostManager* manager1 =
web_contents1->GetPrimaryFrameTree().root()->render_manager();
// Test the case that new RVH is considered live.
RenderViewHostImpl* rvh1 = manager1->current_frame_host()->render_view_host();
rvh1->CreateRenderView(std::nullopt, MSG_ROUTING_NONE, false, std::nullopt);
EXPECT_TRUE(rvh1->IsRenderViewLive());
EXPECT_TRUE(manager1->current_frame_host()->IsRenderFrameLive());
// Navigate to a WebUI page.
const GURL kUrl1(GetWebUIURL("foo"));
NavigationEntryImpl entry1(
nullptr /* instance */, kUrl1, Referrer(),
/* initiator_origin= */ std::nullopt,
/* initiator_base_url= */ std::nullopt, std::u16string() /* title */,
ui::PAGE_TRANSITION_TYPED, false /* is_renderer_init */,
nullptr /* blob_url_loader_factory */, false /* is_initial_entry */);
RenderFrameHostImpl* host1 = NavigateToEntry(manager1, &entry1);
// Because we've called CreateRenderView(), the initial RenderFrameHost is
// live prior to the navigation start, but it can still be reused for the
// WebUI RenderFrameHost, since it hasn't committed any navigations and it has
// an unassigned SiteInstance and unlocked process. There should be no
// speculative RenderFrameHost.
EXPECT_FALSE(GetPendingFrameHost(manager1));
EXPECT_EQ(host1, manager1->current_frame_host());
// At this point, the initial RFH should have set the WebUI bindings. This
// should happen as part of selecting that RFH for the WebUI navigation in
// GetFrameHostForNavigation().
EXPECT_TRUE(host1->GetEnabledBindings().Has(BindingsPolicyValue::kWebUi));
// Commit and ensure we still have bindings.
DidNavigateFrame(manager1, host1);
SiteInstance* webui_instance = host1->GetSiteInstance();
EXPECT_EQ(host1, manager1->current_frame_host());
EXPECT_TRUE(host1->GetEnabledBindings().Has(BindingsPolicyValue::kWebUi));
// Now simulate clicking a link that opens in a new tab.
std::unique_ptr<TestWebContents> web_contents2(
TestWebContents::Create(browser_context(), webui_instance));
RenderFrameHostManager* manager2 =
web_contents2->GetPrimaryFrameTree().root()->render_manager();
// Make sure the new RVH is considered live. This is usually done in
// RenderWidgetHost::Init when opening a new tab from a link.
RenderViewHostImpl* rvh2 = manager2->current_frame_host()->render_view_host();
rvh2->CreateRenderView(std::nullopt, MSG_ROUTING_NONE, false, std::nullopt);
EXPECT_TRUE(rvh2->IsRenderViewLive());
const GURL kUrl2(GetWebUIURL("foo/bar"));
const url::Origin kInitiatorOrigin =
url::Origin::Create(GURL("https://initiator.example.com"));
NavigationEntryImpl entry2(
nullptr /* instance */, kUrl2, Referrer(), kInitiatorOrigin,
/* initiator_base_url= */ std::nullopt, std::u16string() /* title */,
ui::PAGE_TRANSITION_LINK, true /* is_renderer_init */,
nullptr /* blob_url_loader_factory */, false /* is_initial_entry */);
RenderFrameHostImpl* host2 = NavigateToEntry(manager2, &entry2);
// No cross-process transition happens because we are already in the right
// SiteInstance. We should grant bindings immediately.
EXPECT_EQ(host2, manager2->current_frame_host());
EXPECT_TRUE(host2->web_ui());
EXPECT_TRUE(host2->GetEnabledBindings().Has(BindingsPolicyValue::kWebUi));
DidNavigateFrame(manager2, host2);
}
// Tests that a WebUI is correctly reused between chrome:// pages.
TEST_P(RenderFrameHostManagerTest, WebUIWasReused) {
// Navigate to a WebUI page.
const GURL kUrl1(GetWebUIURL("foo"));
contents()->NavigateAndCommit(kUrl1);
WebUIImpl* web_ui = main_test_rfh()->web_ui();
EXPECT_TRUE(web_ui);
// Navigate to another WebUI page which should be same-site the same WebUI
// object is reused if the RenderFrameHost is reused.
const GURL kUrl2(GetWebUIURL("foo/bar"));
contents()->NavigateAndCommit(kUrl2);
if (ShouldCreateNewHostForAllFrames()) {
EXPECT_NE(web_ui, main_test_rfh()->web_ui());
} else {
EXPECT_EQ(web_ui, main_test_rfh()->web_ui());
}
}
// Tests that a WebUI is correctly cleaned up when navigating from a chrome://
// page to a non-chrome:// page.
TEST_P(RenderFrameHostManagerTest, WebUIWasCleared) {
// Navigate to a WebUI page.
const GURL kUrl1(GetWebUIURL("foo"));
contents()->NavigateAndCommit(kUrl1);
EXPECT_TRUE(main_test_rfh()->web_ui());
// Navigate to a non-WebUI page.
const GURL kUrl2("http://www.google.com");
contents()->NavigateAndCommit(kUrl2);
EXPECT_FALSE(main_test_rfh()->web_ui());
}
// Ensure that we can go back and forward even if a unload ACK isn't received.
// See http://crbug.com/93427.
TEST_P(RenderFrameHostManagerTest, NavigateAfterMissingUnloadACK) {
// When a page enters the BackForwardCache, the RenderFrameHost is not
// deleted. Similarly, no
// mojo::AgentSchedulingGroupHost::DidUnloadRenderFrame message is sent.
contents()->GetController().GetBackForwardCache().DisableForTesting(
BackForwardCache::TEST_REQUIRES_NO_CACHING);
const GURL kUrl1("http://www.google.com/");
const GURL kUrl2 = isolated_cross_site_url();
// Navigate to two pages.
contents()->NavigateAndCommit(kUrl1);
TestRenderFrameHost* rfh1 = main_test_rfh();
// Keep active_frame_count nonzero so that no unloaded frames in this
// SiteInstanceGroup get forcefully deleted.
rfh1->GetSiteInstance()->group()->IncrementActiveFrameCount();
contents()->NavigateAndCommit(kUrl2);
TestRenderFrameHost* rfh2 = main_test_rfh();
rfh2->GetSiteInstance()->group()->IncrementActiveFrameCount();
// Now go back, but suppose the
// mojo::AgentSchedulingGroupHost::DidUnloadRenderFrame isn't received. This
// shouldn't happen, but we have seen it when going back quickly across many
// entries (http://crbug.com/93427).
auto back_navigation1 = NavigationSimulatorImpl::CreateHistoryNavigation(
-1, contents(), false /* is_renderer_initiated */);
back_navigation1->ReadyToCommit();
EXPECT_FALSE(rfh2->is_waiting_for_beforeunload_completion());
// The back navigation commits.
back_navigation1->set_drop_unload_ack(true);
back_navigation1->Commit();
EXPECT_TRUE(rfh2->IsWaitingForUnloadACK());
EXPECT_TRUE(rfh2->IsPendingDeletion());
// We should be able to navigate forward.
NavigationSimulator::GoForward(contents());
EXPECT_TRUE(main_test_rfh()->IsActive());
}
// Test that we create `blink::RemoteFrame` objects for the opener chain when
// navigating an opened tab cross-process. This allows us to support certain
// cross-process JavaScript calls (http://crbug.com/99202).
TEST_P(RenderFrameHostManagerTest, CreateProxiesForOpeners) {
const GURL kUrl1("http://www.google.com/");
const GURL kUrl2 = isolated_cross_site_url();
const GURL kChromeUrl(GetWebUIURL("foo"));
// Navigate to an initial URL.
contents()->NavigateAndCommit(kUrl1);
RenderFrameHostManager* manager =
contents()->GetPrimaryFrameTree().root()->render_manager();
TestRenderFrameHost* rfh1 = main_test_rfh();
scoped_refptr<SiteInstanceImpl> site_instance1 = rfh1->GetSiteInstance();
RenderFrameDeletedObserver rfh1_deleted_observer(rfh1);
TestRenderViewHost* rvh1 = test_rvh();
EXPECT_EQ(!AreStrictSiteInstancesEnabled(),
site_instance1->IsDefaultSiteInstance());
// Create 2 new tabs and simulate them being the opener chain for the main
// tab. They should be in the same SiteInstance.
std::unique_ptr<TestWebContents> opener1(
TestWebContents::Create(browser_context(), site_instance1.get()));
RenderFrameHostManager* opener1_manager =
opener1->GetPrimaryFrameTree().root()->render_manager();
contents()->SetOpener(opener1.get());
std::unique_ptr<TestWebContents> opener2(
TestWebContents::Create(browser_context(), site_instance1.get()));
RenderFrameHostManager* opener2_manager =
opener2->GetPrimaryFrameTree().root()->render_manager();
opener1->SetOpener(opener2.get());
// Navigate to a cross-site URL (different SiteInstance but same
// BrowsingInstance).
contents()->NavigateAndCommit(kUrl2);
TestRenderFrameHost* rfh2 = main_test_rfh();
EXPECT_NE(site_instance1, rfh2->GetSiteInstance());
EXPECT_TRUE(site_instance1->IsRelatedSiteInstance(rfh2->GetSiteInstance()));
// Ensure rvh1 is kept with the proxy of the current tab.
EXPECT_TRUE(rfh1_deleted_observer.deleted());
EXPECT_EQ(rvh1, manager->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(site_instance1->group())
->GetRenderViewHost());
// Ensure a proxy and inactive RVH are created in the first opener tab.
RenderFrameProxyHost* rfph1 =
opener1_manager->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(rfh2->GetSiteInstance()->group());
TestRenderViewHost* opener1_rvh =
static_cast<TestRenderViewHost*>(rfph1->GetRenderViewHost());
EXPECT_FALSE(opener1_rvh->is_active());
// Ensure a proxy and inactive RVH are created in the second opener tab.
RenderFrameProxyHost* rfph2 =
opener2_manager->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(rfh2->GetSiteInstance()->group());
TestRenderViewHost* opener2_rvh =
static_cast<TestRenderViewHost*>(rfph2->GetRenderViewHost());
EXPECT_FALSE(opener2_rvh->is_active());
// Navigate to a cross-BrowsingInstance URL.
contents()->NavigateAndCommit(kChromeUrl);
TestRenderFrameHost* rfh3 = main_test_rfh();
EXPECT_NE(site_instance1, rfh3->GetSiteInstance());
EXPECT_FALSE(site_instance1->IsRelatedSiteInstance(rfh3->GetSiteInstance()));
// No scripting is allowed across BrowsingInstances, so we should not create
// proxies for the opener chain in this case.
EXPECT_FALSE(opener1_manager->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(rfh3->GetSiteInstance()->group()));
EXPECT_FALSE(opener2_manager->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(rfh3->GetSiteInstance()->group()));
}
// Test that a page can disown the opener of the WebContents.
TEST_P(RenderFrameHostManagerTest, DisownOpener) {
const GURL kUrl1("http://www.google.com/");
const GURL kUrl2 = isolated_cross_site_url();
// Navigate to an initial URL.
contents()->NavigateAndCommit(kUrl1);
TestRenderFrameHost* rfh1 = main_test_rfh();
scoped_refptr<SiteInstanceImpl> site_instance1 = rfh1->GetSiteInstance();
EXPECT_EQ(!AreStrictSiteInstancesEnabled(),
site_instance1->IsDefaultSiteInstance());
// Create a new tab and simulate having it be the opener for the main tab.
std::unique_ptr<TestWebContents> opener1(
TestWebContents::Create(browser_context(), rfh1->GetSiteInstance()));
contents()->SetOpener(opener1.get());
EXPECT_TRUE(contents()->HasOpener());
// Navigate to a cross-site URL (different SiteInstance but same
// BrowsingInstance).
contents()->NavigateAndCommit(kUrl2);
TestRenderFrameHost* rfh2 = main_test_rfh();
EXPECT_NE(site_instance1, rfh2->GetSiteInstance());
// Disown the opener from rfh2.
rfh2->SimulateDidChangeOpener(std::nullopt);
// Ensure the opener is cleared.
EXPECT_FALSE(contents()->HasOpener());
}
// Test that a page can disown a same-site opener of the WebContents.
TEST_P(RenderFrameHostManagerTest, DisownSameSiteOpener) {
const GURL kUrl1("http://www.google.com/");
// Navigate to an initial URL.
contents()->NavigateAndCommit(kUrl1);
TestRenderFrameHost* rfh1 = main_test_rfh();
// Create a new tab and simulate having it be the opener for the main tab.
std::unique_ptr<TestWebContents> opener1(
TestWebContents::Create(browser_context(), rfh1->GetSiteInstance()));
contents()->SetOpener(opener1.get());
EXPECT_TRUE(contents()->HasOpener());
// Disown the opener from rfh1.
rfh1->SimulateDidChangeOpener(std::nullopt);
// Ensure the opener is cleared even if it is in the same process.
EXPECT_FALSE(contents()->HasOpener());
}
// Test that a page can disown the opener just as a cross-process navigation is
// in progress.
TEST_P(RenderFrameHostManagerTest, DisownOpenerDuringNavigation) {
const GURL kUrl1("http://www.google.com/");
const GURL kUrl2 = isolated_cross_site_url();
// Navigate to an initial URL.
contents()->NavigateAndCommit(kUrl1);
scoped_refptr<SiteInstanceImpl> site_instance1 =
main_test_rfh()->GetSiteInstance();
EXPECT_EQ(!AreStrictSiteInstancesEnabled(),
site_instance1->IsDefaultSiteInstance());
// Create a new tab and simulate having it be the opener for the main tab.
std::unique_ptr<TestWebContents> opener1(
TestWebContents::Create(browser_context(), site_instance1.get()));
contents()->SetOpener(opener1.get());
EXPECT_TRUE(contents()->HasOpener());
// Navigate to a cross-site URL (different SiteInstance but same
// BrowsingInstance).
contents()->NavigateAndCommit(kUrl2);
TestRenderFrameHost* rfh2 = main_test_rfh();
EXPECT_NE(site_instance1, rfh2->GetSiteInstance());
// Start a back navigation.
contents()->GetController().GoBack();
contents()->GetPrimaryMainFrame()->PrepareForCommit();
// Disown the opener from rfh2.
rfh2->SimulateDidChangeOpener(std::nullopt);
// Ensure the opener is cleared.
EXPECT_FALSE(contents()->HasOpener());
// The back navigation commits.
NavigationEntry* entry1 = contents()->GetController().GetPendingEntry();
contents()->GetSpeculativePrimaryMainFrame()->SendNavigateWithTransition(
entry1->GetUniqueID(), false, entry1->GetURL(),
entry1->GetTransitionType());
// Ensure the opener is still cleared.
EXPECT_FALSE(contents()->HasOpener());
}
// Test that a page can disown the opener just after a cross-process navigation
// commits.
TEST_P(RenderFrameHostManagerTest, DisownOpenerAfterNavigation) {
const GURL kUrl1("http://www.google.com/");
const GURL kUrl2 = isolated_cross_site_url();
// Navigate to an initial URL.
contents()->NavigateAndCommit(kUrl1);
scoped_refptr<SiteInstanceImpl> site_instance1 =
main_test_rfh()->GetSiteInstance();
EXPECT_EQ(!AreStrictSiteInstancesEnabled(),
site_instance1->IsDefaultSiteInstance());
// Create a new tab and simulate having it be the opener for the main tab.
std::unique_ptr<TestWebContents> opener1(
TestWebContents::Create(browser_context(), site_instance1.get()));
contents()->SetOpener(opener1.get());
EXPECT_TRUE(contents()->HasOpener());
// Navigate to a cross-site URL (different SiteInstance but same
// BrowsingInstance).
contents()->NavigateAndCommit(kUrl2);
TestRenderFrameHost* rfh2 = main_test_rfh();
EXPECT_NE(site_instance1, rfh2->GetSiteInstance());
// Commit a back navigation before the DidChangeOpener message arrives.
contents()->GetController().GoBack();
contents()->GetPrimaryMainFrame()->PrepareForCommit();
NavigationEntry* entry1 = contents()->GetController().GetPendingEntry();
contents()->GetSpeculativePrimaryMainFrame()->SendNavigateWithTransition(
entry1->GetUniqueID(), false, entry1->GetURL(),
entry1->GetTransitionType());
// Disown the opener from rfh2.
rfh2->SimulateDidChangeOpener(std::nullopt);
EXPECT_FALSE(contents()->HasOpener());
}
// Test that we clean up RenderFrameProxyHosts when a process hosting the
// associated frames crashes. http://crbug.com/258993
TEST_P(RenderFrameHostManagerTest, CleanUpProxiesOnProcessCrash) {
const GURL kUrl1("http://www.google.com/");
const GURL kUrl2 = isolated_cross_site_url();
// Navigate to an initial URL.
contents()->NavigateAndCommit(kUrl1);
TestRenderFrameHost* rfh1 = contents()->GetPrimaryMainFrame();
// Create a new tab as an opener for the main tab.
std::unique_ptr<TestWebContents> opener1(
TestWebContents::Create(browser_context(), rfh1->GetSiteInstance()));
RenderFrameHostManager* opener1_manager =
opener1->GetPrimaryFrameTree().root()->render_manager();
contents()->SetOpener(opener1.get());
// Make sure the new opener RVH is considered live.
RenderViewHostImpl* opener_rvh =
opener1_manager->current_frame_host()->render_view_host();
opener_rvh->CreateRenderView(std::nullopt, MSG_ROUTING_NONE, false,
std::nullopt);
EXPECT_TRUE(opener_rvh->IsRenderViewLive());
EXPECT_TRUE(opener1_manager->current_frame_host()->IsRenderFrameLive());
// Use a cross-process navigation in the opener to make the old RVH inactive.
EXPECT_FALSE(opener1_manager->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(rfh1->GetSiteInstance()->group()));
opener1->NavigateAndCommit(kUrl2);
RenderFrameProxyHost* rfph1 =
opener1_manager->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(rfh1->GetSiteInstance()->group());
RenderViewHostImpl* rvh1 = rfph1->GetRenderViewHost();
EXPECT_TRUE(rvh1);
EXPECT_FALSE(rvh1->is_active());
// Fake a process crash.
rfh1->GetProcess()->SimulateCrash();
// Ensure that the RenderFrameProxyHost stays around and the RenderFrameProxy
// is deleted.
RenderFrameProxyHost* render_frame_proxy_host =
opener1_manager->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(rfh1->GetSiteInstance()->group());
EXPECT_EQ(rfph1, render_frame_proxy_host);
EXPECT_FALSE(render_frame_proxy_host->is_render_frame_proxy_live());
// Expect the RVH to exist but not be live.
EXPECT_TRUE(rfph1->GetRenderViewHost());
EXPECT_FALSE(rfph1->GetRenderViewHost()->IsRenderViewLive());
// Reload the initial tab. This should recreate the opener's RVH in the
// original SiteInstanceGroup.
contents()->GetController().Reload(ReloadType::NORMAL, true);
contents()->GetPrimaryMainFrame()->PrepareForCommit();
TestRenderFrameHost* rfh2 = contents()->GetPrimaryMainFrame();
EXPECT_TRUE(opener1_manager->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(rfh2->GetSiteInstance()->group())
->GetRenderViewHost()
->IsRenderViewLive());
EXPECT_EQ(opener1_manager->GetFrameTokenForSiteInstanceGroup(
rfh2->GetSiteInstance()->group()),
rfh2->GetRenderViewHost()->opener_frame_token());
}
// Test guest navigation behavior when navigating across sites. Since guests
// support site isolation, we should swap guest SiteInstances as usual.
TEST_P(RenderFrameHostManagerTest, GuestNavigations) {
// Create a custom StoragePartitionConfig for the guest SiteInstance. The
// resulting SiteInstance should become associated with this
// StoragePartitionConfig rather than a default one.
const StoragePartitionConfig kGuestPartitionConfig =
StoragePartitionConfig::Create(browser_context(), "someapp",
"somepartition", /*in_memory=*/false);
scoped_refptr<SiteInstance> initial_instance =
SiteInstance::CreateForGuest(browser_context(), kGuestPartitionConfig);
std::unique_ptr<TestWebContents> web_contents(
TestWebContents::Create(browser_context(), initial_instance));
EXPECT_TRUE(initial_instance->IsGuest());
EXPECT_EQ(kGuestPartitionConfig,
initial_instance->GetStoragePartitionConfig());
RenderFrameHostManager* manager =
web_contents->GetPrimaryFrameTree().root()->render_manager();
RenderFrameHostImpl* initial_host = manager->current_frame_host();
// 1) First navigation. ------------------------
// Start the first navigation, but do not commit.
const GURL kUrl1("http://www.google.com/");
NavigationEntryImpl entry1(
nullptr /* instance */, kUrl1, Referrer(),
/* initiator_origin= */ std::nullopt,
/* initiator_base_url= */ std::nullopt, std::u16string() /* title */,
ui::PAGE_TRANSITION_TYPED, false /* is_renderer_init */,
nullptr /* blob_url_loader_factory */, false /* is_initial_entry */);
RenderFrameHostImpl* host = NavigateToEntry(manager, &entry1);
// The SiteInstance of the navigating RenderFrameHost should still be a guest
// SiteInstance in the same StoragePartition.
scoped_refptr<SiteInstanceImpl> first_instance = host->GetSiteInstance();
EXPECT_EQ(first_instance->GetStoragePartitionConfig(), kGuestPartitionConfig);
EXPECT_TRUE(first_instance->IsGuest());
// We have to swap SiteInstances and RenderFrameHosts, since the initial
// SiteInstance (`instance`) has an empty site and process lock, whereas the
// navigation needs a SiteInstance with the site URL that corresponds to
// `kUrl1`. Note that there will be no speculative RenderFrameHost in that
// case, since the new RenderFrameHost will be committed right away due to
// the early commit optimization. This behavior may change if the early
// commit optimization is removed in https://crbug.com/1072817.
EXPECT_NE(first_instance, initial_instance);
EXPECT_NE(host, initial_host);
// This test may run without strict site isolation, e.g. on Android. In
// that case, the navigation will end up in a default SiteInstance.
if (AreStrictSiteInstancesEnabled()) {
EXPECT_EQ("http://google.com/",
first_instance->GetSiteInfo().site_url().spec());
} else {
EXPECT_TRUE(first_instance->IsDefaultSiteInstance());
}
EXPECT_FALSE(manager->speculative_frame_host());
EXPECT_EQ(host, manager->current_frame_host());
// Commit.
DidNavigateFrame(manager, host);
EXPECT_EQ(host, manager->current_frame_host());
ASSERT_TRUE(host);
EXPECT_TRUE(host->GetSiteInstance()->HasSite());
// 2) Second navigation. ------------------------
// Navigate to a different site. If strict site isolation is enabled, this
// will swap processes. Otherwise, the guest will stay in the same process.
const GURL kUrl2("http://www.chromium.org");
const url::Origin kInitiatorOrigin =
url::Origin::Create(GURL("https://initiator.example.com"));
NavigationEntryImpl entry2(
nullptr /* instance */, kUrl2,
Referrer(kUrl1, network::mojom::ReferrerPolicy::kDefault),
kInitiatorOrigin, /* initiator_base_url= */ std::nullopt,
std::u16string() /* title */, ui::PAGE_TRANSITION_LINK,
true /* is_renderer_init */, nullptr /* blob_url_loader_factory */,
false /* is_initial_entry */);
host = NavigateToEntry(manager, &entry2);
// The first RenderFrameHost will be reused only when there's no site
// isolation between the two sites.
if (AreStrictSiteInstancesEnabled()) {
EXPECT_NE(host, manager->current_frame_host());
EXPECT_TRUE(manager->speculative_frame_host());
} else {
EXPECT_EQ(host, manager->current_frame_host());
EXPECT_FALSE(manager->speculative_frame_host());
}
// Commit.
DidNavigateFrame(manager, host);
EXPECT_EQ(host, manager->current_frame_host());
ASSERT_TRUE(host);
EXPECT_TRUE(host->GetSiteInstance()->IsGuest());
if (AreStrictSiteInstancesEnabled()) {
EXPECT_NE(host->GetSiteInstance(), first_instance);
EXPECT_EQ("http://chromium.org/",
host->GetSiteInstance()->GetSiteInfo().site_url().spec());
} else {
EXPECT_EQ(host->GetSiteInstance(), first_instance);
}
}
namespace {
class WidgetDestructionObserver : public RenderWidgetHostObserver {
public:
explicit WidgetDestructionObserver(base::OnceClosure closure)
: closure_(std::move(closure)) {}
WidgetDestructionObserver(const WidgetDestructionObserver&) = delete;
WidgetDestructionObserver& operator=(const WidgetDestructionObserver&) =
delete;
void RenderWidgetHostDestroyed(RenderWidgetHost* widget_host) override {
std::move(closure_).Run();
}
private:
base::OnceClosure closure_;
};
} // namespace
// Test that we cancel a pending RVH if we close the tab while it's pending.
// http://crbug.com/294697.
TEST_P(RenderFrameHostManagerTest, NavigateWithEarlyClose) {
scoped_refptr<SiteInstance> instance =
SiteInstance::Create(browser_context());
BeforeUnloadFiredWebContentsDelegate delegate;
std::unique_ptr<TestWebContents> web_contents(
TestWebContents::Create(browser_context(), instance));
web_contents->SetDelegate(&delegate);
RenderFrameHostManager* manager =
web_contents->GetPrimaryFrameTree().root()->render_manager();
// 1) The first navigation. --------------------------
const GURL kUrl1("http://www.google.com/");
NavigationEntryImpl entry1(
nullptr /* instance */, kUrl1, Referrer(),
/* initiator_origin= */ std::nullopt,
/* initiator_base_url= */ std::nullopt, std::u16string() /* title */,
ui::PAGE_TRANSITION_TYPED, false /* is_renderer_init */,
nullptr /* blob_url_loader_factory */, false /* is_initial_entry */);
RenderFrameHostImpl* host = NavigateToEntry(manager, &entry1);
// The RenderFrameHost created in Init will be reused.
EXPECT_EQ(host, manager->current_frame_host());
EXPECT_FALSE(GetPendingFrameHost(manager));
// Commit.
DidNavigateFrame(manager, host);
// Commit to SiteInstance should be delayed until RenderFrame commits.
EXPECT_EQ(host, manager->current_frame_host());
EXPECT_FALSE(host->GetSiteInstance()->HasSite());
host->GetSiteInstance()->SetSite(UrlInfo::CreateForTesting(kUrl1));
// 2) Cross-site navigate to next site. -------------------------
const GURL kUrl2("http://www.example.com");
NavigationEntryImpl entry2(
nullptr /* instance */, kUrl2, Referrer(),
/* initiator_origin= */ std::nullopt,
/* initiator_base_url= */ std::nullopt, std::u16string() /* title */,
ui::PAGE_TRANSITION_TYPED, false /* is_renderer_init */,
nullptr /* blob_url_loader_factory */, false /* is_initial_entry */);
RenderFrameHostImpl* host2 = NavigateToEntry(manager, &entry2);
// A new RenderFrameHost should be created.
ASSERT_EQ(host2, GetPendingFrameHost(manager));
EXPECT_NE(host2, host);
EXPECT_EQ(host, manager->current_frame_host());
EXPECT_EQ(host2, GetPendingFrameHost(manager));
// 3) Close the tab. -------------------------
base::RunLoop run_loop;
WidgetDestructionObserver observer(run_loop.QuitClosure());
host2->render_view_host()->GetWidget()->AddObserver(&observer);
manager->BeforeUnloadCompleted(/*proceed=*/true);
run_loop.Run();
EXPECT_FALSE(GetPendingFrameHost(manager));
EXPECT_EQ(host, manager->current_frame_host());
}
TEST_P(RenderFrameHostManagerTest, CloseWithPendingWhileUnresponsive) {
const GURL kUrl1("http://www.google.com/");
const GURL kUrl2 = isolated_cross_site_url();
CloseWebContentsDelegate close_delegate;
contents()->SetDelegate(&close_delegate);
// Navigate to the first page.
contents()->NavigateAndCommit(kUrl1);
TestRenderFrameHost* rfh1 = contents()->GetPrimaryMainFrame();
// Start to close the tab, but assume it's unresponsive.
rfh1->ClosePage(RenderFrameHostImpl::ClosePageSource::kBrowser);
EXPECT_EQ(rfh1->page_close_state_,
RenderFrameHostImpl::PageCloseState::kRunningUnloadHandlers);
// Start a navigation to a new site.
controller().LoadURL(kUrl2, Referrer(), ui::PAGE_TRANSITION_LINK,
std::string());
rfh1->PrepareForCommit();
EXPECT_TRUE(contents()->CrossProcessNavigationPending());
// Simulate the unresponsiveness timer. The tab should close.
rfh1->ClosePageTimeout(RenderFrameHostImpl::ClosePageSource::kBrowser);
EXPECT_TRUE(close_delegate.is_closed());
}
TEST_P(RenderFrameHostManagerTest,
CloseWithPendingWhileUnresponsiveWithDevTools) {
const GURL kUrl1("http://www.google.com/");
const GURL kUrl2 = isolated_cross_site_url();
CloseWebContentsDelegate close_delegate;
contents()->SetDelegate(&close_delegate);
// Attach a DevTools session.
auto agent = DevToolsAgentHost::GetOrCreateFor(contents());
TestDevToolsClientHost client_host;
client_host.InspectAgentHost(agent.get());
// Test that the connection is established.
EXPECT_TRUE(agent->IsAttached());
// Navigate to the first page.
contents()->NavigateAndCommit(kUrl1);
TestRenderFrameHost* rfh1 = contents()->GetPrimaryMainFrame();
// Start to close the tab, but assume it's unresponsive.
rfh1->ClosePage(RenderFrameHostImpl::ClosePageSource::kBrowser);
EXPECT_EQ(rfh1->page_close_state_,
RenderFrameHostImpl::PageCloseState::kRunningUnloadHandlers);
// Start a navigation to a new site.
controller().LoadURL(kUrl2, Referrer(), ui::PAGE_TRANSITION_LINK,
std::string());
rfh1->PrepareForCommit();
EXPECT_TRUE(contents()->CrossProcessNavigationPending());
// Simulate the unresponsiveness timer. The tab should close.
rfh1->ClosePageTimeout(RenderFrameHostImpl::ClosePageSource::kBrowser);
EXPECT_TRUE(close_delegate.is_closed());
// Cleanup the DevTools session.
client_host.Close();
}
// Tests that the RenderFrameHost is properly deleted when the
// mojo::AgentSchedulingGroupHost::DidUnloadRenderFrame is received.
// (mojo::FrameNavigationControl::Unload and the corresponding
// mojo::AgentSchedulingGroupHost::DidUnloadRenderFrame always occur after
// commit.) Also tests that an early
// mojo::AgentSchedulingGroupHost::DidUnloadRenderFrame is properly ignored.
TEST_P(RenderFrameHostManagerTest, DeleteFrameAfterUnloadACK) {
// When a page enters the BackForwardCache, the RenderFrameHost is not
// deleted. Similarly, no
// mojo::AgentSchedulingGroupHost::DidUnloadRenderFrame message is sent.
contents()->GetController().GetBackForwardCache().DisableForTesting(
BackForwardCache::TEST_REQUIRES_NO_CACHING);
const GURL kUrl1("http://www.google.com/");
const GURL kUrl2("http://www.chromium.org/");
// Navigate to the first page.
contents()->NavigateAndCommit(kUrl1);
TestRenderFrameHost* rfh1 = contents()->GetPrimaryMainFrame();
RenderFrameDeletedObserver rfh_deleted_observer(rfh1);
EXPECT_TRUE(rfh1->IsActive());
// Navigate to new site, simulating onbeforeunload approval.
auto navigation =
NavigationSimulatorImpl::CreateBrowserInitiated(kUrl2, contents());
navigation->ReadyToCommit();
EXPECT_TRUE(contents()->CrossProcessNavigationPending());
EXPECT_TRUE(rfh1->IsActive());
TestRenderFrameHost* rfh2 = contents()->GetSpeculativePrimaryMainFrame();
// Simulate the unload ack, unexpectedly early (before commit). It should
// have no effect.
rfh1->SimulateUnloadACK();
EXPECT_TRUE(contents()->CrossProcessNavigationPending());
EXPECT_TRUE(rfh1->IsActive());
// The new page commits.
navigation->set_drop_unload_ack(true);
navigation->Commit();
EXPECT_FALSE(contents()->CrossProcessNavigationPending());
EXPECT_EQ(rfh2, contents()->GetPrimaryMainFrame());
EXPECT_TRUE(contents()->GetSpeculativePrimaryMainFrame() == nullptr);
EXPECT_TRUE(rfh2->IsActive());
EXPECT_TRUE(rfh1->IsPendingDeletion());
// Simulate the unload ack.
rfh1->SimulateUnloadACK();
// rfh1 should have been deleted.
EXPECT_TRUE(rfh_deleted_observer.deleted());
rfh1 = nullptr;
}
// Tests that the RenderFrameHost is properly unloaded when the
// mojo::AgentSchedulingGroupHost::DidUnloadRenderFrame is received.
// (mojo::FrameNavigationControl::Unload and the corresponding
// mojo::AgentSchedulingGroupHost::DidUnloadRenderFrame always occur after
// commit.)
TEST_P(RenderFrameHostManagerTest, UnloadFrameAfterUnloadACK) {
// When a page enters the BackForwardCache, the RenderFrameHost is not
// deleted. Similarly, no
// mojo::AgentSchedulingGroupHost::DidUnloadRenderFrame message is sent.
contents()->GetController().GetBackForwardCache().DisableForTesting(
BackForwardCache::TEST_REQUIRES_NO_CACHING);
const GURL kUrl1("http://www.google.com/");
const GURL kUrl2("http://www.chromium.org/");
// Navigate to the first page.
contents()->NavigateAndCommit(kUrl1);
TestRenderFrameHost* rfh1 = contents()->GetPrimaryMainFrame();
RenderFrameDeletedObserver rfh_deleted_observer(rfh1);
EXPECT_TRUE(rfh1->IsActive());
// Increment the number of active frames in SiteInstanceGroup so that rfh1 is
// not deleted on unload.
rfh1->GetSiteInstance()->group()->IncrementActiveFrameCount();
// Navigate to new site, simulating onbeforeunload approval.
auto navigation =
NavigationSimulatorImpl::CreateBrowserInitiated(kUrl2, contents());
navigation->ReadyToCommit();
EXPECT_TRUE(contents()->CrossProcessNavigationPending());
EXPECT_TRUE(rfh1->IsActive());
TestRenderFrameHost* rfh2 = contents()->GetSpeculativePrimaryMainFrame();
// The new page commits.
navigation->set_drop_unload_ack(true);
navigation->Commit();
EXPECT_FALSE(contents()->CrossProcessNavigationPending());
EXPECT_EQ(rfh2, contents()->GetPrimaryMainFrame());
EXPECT_TRUE(contents()->GetSpeculativePrimaryMainFrame() == nullptr);
EXPECT_TRUE(rfh1->IsPendingDeletion());
EXPECT_TRUE(rfh2->IsActive());
// Simulate the unload ack.
rfh1->OnUnloaded();
// rfh1 should be deleted.
EXPECT_TRUE(rfh_deleted_observer.deleted());
}
// Test that a RenderFrameHost is properly deleted if a navigation in the new
// renderer commits before sending the mojo::FrameNavigationControl::Unload
// message to the old renderer. This simulates a cross-site navigation to a
// synchronously committing URL (e.g., a data URL) and ensures it works
// properly.
TEST_P(RenderFrameHostManagerTest, CommitNewNavigationBeforeSendingUnload) {
// When a page enters the BackForwardCache, the RenderFrameHost is not
// deleted. Similarly, no
// mojo::AgentSchedulingGroupHost::DidUnloadRenderFrame message is sent.
contents()->GetController().GetBackForwardCache().DisableForTesting(
BackForwardCache::TEST_REQUIRES_NO_CACHING);
const GURL kUrl1("http://www.google.com/");
const GURL kUrl2("http://www.chromium.org/");
// Navigate to the first page.
contents()->NavigateAndCommit(kUrl1);
TestRenderFrameHost* rfh1 = contents()->GetPrimaryMainFrame();
RenderFrameDeletedObserver rfh_deleted_observer(rfh1);
EXPECT_TRUE(rfh1->IsActive());
// Increment the number of active frames in rfh1's SiteInstanceGroup so that
// the SiteInstanceGroup is not deleted on unload.
scoped_refptr<SiteInstanceGroup> site_instance_group =
rfh1->GetSiteInstance()->group();
site_instance_group->IncrementActiveFrameCount();
// Navigate to new site, simulating onbeforeunload approval.
auto navigation =
NavigationSimulatorImpl::CreateBrowserInitiated(kUrl2, contents());
navigation->ReadyToCommit();
EXPECT_TRUE(contents()->CrossProcessNavigationPending());
EXPECT_TRUE(rfh1->IsActive());
TestRenderFrameHost* rfh2 = contents()->GetSpeculativePrimaryMainFrame();
// The new page commits.
navigation->set_drop_unload_ack(true);
navigation->Commit();
EXPECT_FALSE(contents()->CrossProcessNavigationPending());
EXPECT_EQ(rfh2, contents()->GetPrimaryMainFrame());
EXPECT_TRUE(contents()->GetSpeculativePrimaryMainFrame() == nullptr);
EXPECT_TRUE(rfh1->IsPendingDeletion());
EXPECT_TRUE(rfh2->IsActive());
// Simulate the unload ack.
rfh1->OnUnloaded();
// rfh1 should be deleted.
EXPECT_TRUE(rfh_deleted_observer.deleted());
EXPECT_TRUE(contents()
->GetPrimaryFrameTree()
.root()
->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(site_instance_group.get()));
}
// Test that a RenderFrameHost is properly deleted when a cross-site navigation
// is cancelled.
TEST_P(RenderFrameHostManagerTest, CancelPendingProperlyDeletesOrSwaps) {
const GURL kUrl1("http://www.google.com/");
const GURL kUrl2 = isolated_cross_site_url();
RenderFrameHostImpl* pending_rfh = nullptr;
// Navigate to the first page.
contents()->NavigateAndCommit(kUrl1);
TestRenderFrameHost* rfh1 = main_test_rfh();
EXPECT_TRUE(rfh1->IsActive());
rfh1->SuddenTerminationDisablerChanged(
true, blink::mojom::SuddenTerminationDisablerType::kBeforeUnloadHandler);
// Navigate to a new site, starting a cross-site navigation.
controller().LoadURL(kUrl2, Referrer(), ui::PAGE_TRANSITION_LINK,
std::string());
{
pending_rfh = contents()->GetSpeculativePrimaryMainFrame();
RenderFrameDeletedObserver rfh_deleted_observer(pending_rfh);
// Cancel the navigation by simulating a declined beforeunload dialog.
contents()->GetPrimaryMainFrame()->SimulateBeforeUnloadCompleted(false);
EXPECT_FALSE(contents()->CrossProcessNavigationPending());
// Since the pending RFH is the only one for the new SiteInstance, it should
// be deleted.
EXPECT_TRUE(rfh_deleted_observer.deleted());
}
// Start another cross-site navigation.
controller().LoadURL(kUrl2, Referrer(), ui::PAGE_TRANSITION_LINK,
std::string());
{
pending_rfh = contents()->GetSpeculativePrimaryMainFrame();
RenderFrameDeletedObserver rfh_deleted_observer(pending_rfh);
// Increment the number of active frames in the new SiteInstanceGroup, which
// will cause the pending RFH to be deleted and a RenderFrameProxyHost to be
// created.
scoped_refptr<SiteInstanceGroup> site_instance_group =
pending_rfh->GetSiteInstance()->group();
site_instance_group->IncrementActiveFrameCount();
contents()->GetPrimaryMainFrame()->SimulateBeforeUnloadCompleted(false);
EXPECT_FALSE(contents()->CrossProcessNavigationPending());
EXPECT_TRUE(rfh_deleted_observer.deleted());
EXPECT_TRUE(contents()
->GetPrimaryFrameTree()
.root()
->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(site_instance_group.get()));
}
}
class RenderFrameHostManagerTestWithSiteIsolation
: public RenderFrameHostManagerTest {
public:
RenderFrameHostManagerTestWithSiteIsolation() {
IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
}
};
// Test that a pending RenderFrameHost in a non-root frame tree node is properly
// deleted when the node is detached. Motivated by http://crbug.com/441357 and
// http://crbug.com/444955.
TEST_P(RenderFrameHostManagerTestWithSiteIsolation, DetachPendingChild) {
const GURL kUrlA("http://www.google.com/");
const GURL kUrlB("http://webkit.org/");
constexpr auto kOwnerType = blink::FrameOwnerElementType::kIframe;
// Create a page with two child frames.
contents()->NavigateAndCommit(kUrlA);
contents()->GetPrimaryMainFrame()->OnCreateChildFrame(
contents()->GetPrimaryMainFrame()->GetProcess()->GetNextRoutingID(),
TestRenderFrameHost::CreateStubFrameRemote(),
TestRenderFrameHost::CreateStubBrowserInterfaceBrokerReceiver(),
TestRenderFrameHost::CreateStubPolicyContainerBindParams(),
TestRenderFrameHost::CreateStubAssociatedInterfaceProviderReceiver(),
blink::mojom::TreeScopeType::kDocument, "frame_name", "uniqueName1",
false, blink::LocalFrameToken(), base::UnguessableToken::Create(),
blink::DocumentToken(), blink::FramePolicy(),
blink::mojom::FrameOwnerProperties(), kOwnerType, ukm::kInvalidSourceId);
contents()->GetPrimaryMainFrame()->OnCreateChildFrame(
contents()->GetPrimaryMainFrame()->GetProcess()->GetNextRoutingID(),
TestRenderFrameHost::CreateStubFrameRemote(),
TestRenderFrameHost::CreateStubBrowserInterfaceBrokerReceiver(),
TestRenderFrameHost::CreateStubPolicyContainerBindParams(),
TestRenderFrameHost::CreateStubAssociatedInterfaceProviderReceiver(),
blink::mojom::TreeScopeType::kDocument, "frame_name", "uniqueName2",
false, blink::LocalFrameToken(), base::UnguessableToken::Create(),
blink::DocumentToken(), blink::FramePolicy(),
blink::mojom::FrameOwnerProperties(), kOwnerType, ukm::kInvalidSourceId);
RenderFrameHostManager* root_manager =
contents()->GetPrimaryFrameTree().root()->render_manager();
RenderFrameHostManager* iframe1 =
contents()->GetPrimaryFrameTree().root()->child_at(0)->render_manager();
RenderFrameHostManager* iframe2 =
contents()->GetPrimaryFrameTree().root()->child_at(1)->render_manager();
// 1) The first navigation.
NavigationEntryImpl entryA(
nullptr /* instance */, kUrlA, Referrer(),
/* initiator_origin= */ std::nullopt,
/* initiator_base_url= */ std::nullopt, std::u16string() /* title */,
ui::PAGE_TRANSITION_TYPED, false /* is_renderer_init */,
nullptr /* blob_url_loader_factory */, false /* is_initial_entry */);
RenderFrameHostImpl* host1 = NavigateToEntry(iframe1, &entryA);
// The RenderFrameHost created in Init will be reused.
EXPECT_TRUE(host1 == iframe1->current_frame_host());
EXPECT_FALSE(GetPendingFrameHost(iframe1));
// Commit.
DidNavigateFrame(iframe1, host1);
// Commit to SiteInstance should be delayed until RenderFrame commit.
EXPECT_TRUE(host1 == iframe1->current_frame_host());
ASSERT_TRUE(host1);
EXPECT_TRUE(host1->GetSiteInstance()->HasSite());
// 2) Cross-site navigate both frames to next site.
NavigationEntryImpl entryB(
nullptr /* instance */, kUrlB,
Referrer(kUrlA, network::mojom::ReferrerPolicy::kDefault),
/* initiator_origin= */ std::nullopt,
/* initiator_base_url= */ std::nullopt, std::u16string() /* title */,
ui::PAGE_TRANSITION_LINK, false /* is_renderer_init */,
nullptr /* blob_url_loader_factory */, false /* is_initial_entry */);
host1 = NavigateToEntry(iframe1, &entryB);
RenderFrameHostImpl* host2 = NavigateToEntry(iframe2, &entryB);
// A new, pending RenderFrameHost should be created in each FrameTreeNode.
EXPECT_TRUE(GetPendingFrameHost(iframe1));
EXPECT_TRUE(GetPendingFrameHost(iframe2));
EXPECT_EQ(host1, GetPendingFrameHost(iframe1));
EXPECT_EQ(host2, GetPendingFrameHost(iframe2));
EXPECT_EQ(GetPendingFrameHost(iframe1)->lifecycle_state(),
RenderFrameHostImpl::LifecycleStateImpl::kSpeculative);
EXPECT_EQ(GetPendingFrameHost(iframe2)->lifecycle_state(),
RenderFrameHostImpl::LifecycleStateImpl::kSpeculative);
EXPECT_NE(GetPendingFrameHost(iframe1), GetPendingFrameHost(iframe2));
EXPECT_EQ(GetPendingFrameHost(iframe1)->GetSiteInstance(),
GetPendingFrameHost(iframe2)->GetSiteInstance());
EXPECT_NE(iframe1->current_frame_host(), GetPendingFrameHost(iframe1));
EXPECT_NE(iframe2->current_frame_host(), GetPendingFrameHost(iframe2));
EXPECT_FALSE(contents()->CrossProcessNavigationPending())
<< "There should be no top-level pending navigation.";
RenderFrameDeletedObserver delete_watcher1(GetPendingFrameHost(iframe1));
RenderFrameDeletedObserver delete_watcher2(GetPendingFrameHost(iframe2));
EXPECT_FALSE(delete_watcher1.deleted());
EXPECT_FALSE(delete_watcher2.deleted());
// Keep the SiteInstance alive for testing.
scoped_refptr<SiteInstanceImpl> site_instance =
GetPendingFrameHost(iframe1)->GetSiteInstance();
EXPECT_TRUE(site_instance->HasSite());
EXPECT_NE(site_instance, contents()->GetSiteInstance());
EXPECT_EQ(2U, site_instance->group()->active_frame_count());
// Proxies should exist.
EXPECT_NE(nullptr, root_manager->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(site_instance->group()));
EXPECT_NE(nullptr, iframe1->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(site_instance->group()));
EXPECT_NE(nullptr, iframe2->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(site_instance->group()));
// Detach the first child FrameTreeNode. This should kill the pending host but
// not yet destroy proxies in |site_instance| since the other child remains.
iframe1->current_frame_host()->Detach();
iframe1 = nullptr; // Was just destroyed.
EXPECT_TRUE(delete_watcher1.deleted());
EXPECT_FALSE(delete_watcher2.deleted());
EXPECT_EQ(1U, site_instance->group()->active_frame_count());
// Proxies should still exist.
EXPECT_NE(nullptr, root_manager->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(site_instance->group()));
EXPECT_NE(nullptr, iframe2->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(site_instance->group()));
// Detach the second child FrameTreeNode. This should trigger cleanup of
// RenderFrameProxyHosts in |site_instance|.
iframe2->current_frame_host()->Detach();
iframe2 = nullptr; // Was just destroyed.
EXPECT_TRUE(delete_watcher1.deleted());
EXPECT_TRUE(delete_watcher2.deleted());
// |site_instance| should no longer have a group, which means there are no
// active frames left, or any proxies for its group.
EXPECT_FALSE(site_instance->group());
EXPECT_TRUE(site_instance->HasOneRef())
<< "This SiteInstance should be destroyable now.";
}
#if BUILDFLAG(IS_ANDROID)
// TODO(lukasza): https://crbug.com/1067432: Calling Compositor::Initialize()
// DCHECKs flakily and without such call the test below consistently fails on
// Android (DCHECKing about parent_view->GetFrameSinkId().is_valid() in
// RenderWidgetHostViewChildFrame::SetFrameConnectorDelegate).
#define MAYBE_TwoTabsCrashOneReloadsOneLeaves \
DISABLED_TwoTabsCrashOneReloadsOneLeaves
#else
#define MAYBE_TwoTabsCrashOneReloadsOneLeaves TwoTabsCrashOneReloadsOneLeaves
#endif
// Two tabs in the same process crash. The first tab is reloaded, and the second
// tab navigates away without reloading. The second tab's navigation shouldn't
// mess with the first tab's content. Motivated by http://crbug.com/473714.
TEST_P(RenderFrameHostManagerTestWithSiteIsolation,
MAYBE_TwoTabsCrashOneReloadsOneLeaves) {
#if BUILDFLAG(IS_ANDROID)
// TODO(lukasza): https://crbug.com/1067432: This call might DCHECK flakily
// about !CompositorImpl::IsInitialized()..
Compositor::Initialize();
#endif
const GURL kUrl1("http://www.google.com/");
const GURL kUrl2("http://webkit.org/");
const GURL kUrl3("http://whatwg.org/");
// |contents1| and |contents2| navigate to the same page and then crash.
TestWebContents* contents1 = contents();
std::unique_ptr<TestWebContents> contents2(
TestWebContents::Create(browser_context(), contents1->GetSiteInstance()));
contents1->NavigateAndCommit(kUrl1);
contents2->NavigateAndCommit(kUrl1);
MockRenderProcessHost* rph = contents1->GetPrimaryMainFrame()->GetProcess();
EXPECT_EQ(rph, contents2->GetPrimaryMainFrame()->GetProcess());
EXPECT_TRUE(contents1->GetPrimaryMainFrame()->GetView());
EXPECT_TRUE(contents2->GetPrimaryMainFrame()->GetView());
rph->SimulateCrash();
EXPECT_FALSE(contents1->GetPrimaryMainFrame()->IsRenderFrameLive());
EXPECT_FALSE(contents2->GetPrimaryMainFrame()->IsRenderFrameLive());
EXPECT_EQ(contents1->GetSiteInstance(), contents2->GetSiteInstance());
EXPECT_FALSE(contents1->GetPrimaryMainFrame()->GetView());
EXPECT_FALSE(contents2->GetPrimaryMainFrame()->GetView());
// Reload |contents1|.
contents1->NavigateAndCommit(kUrl1);
EXPECT_TRUE(contents1->GetPrimaryMainFrame()->IsRenderFrameLive());
EXPECT_FALSE(contents2->GetPrimaryMainFrame()->IsRenderFrameLive());
EXPECT_EQ(contents1->GetSiteInstance(), contents2->GetSiteInstance());
EXPECT_TRUE(contents1->GetPrimaryMainFrame()->GetView());
EXPECT_FALSE(contents2->GetPrimaryMainFrame()->GetView());
// |contents1| creates an out of process iframe.
contents1->GetPrimaryMainFrame()->OnCreateChildFrame(
contents1->GetPrimaryMainFrame()->GetProcess()->GetNextRoutingID(),
TestRenderFrameHost::CreateStubFrameRemote(),
TestRenderFrameHost::CreateStubBrowserInterfaceBrokerReceiver(),
TestRenderFrameHost::CreateStubPolicyContainerBindParams(),
TestRenderFrameHost::CreateStubAssociatedInterfaceProviderReceiver(),
blink::mojom::TreeScopeType::kDocument, "frame_name", "uniqueName1",
false, blink::LocalFrameToken(), base::UnguessableToken::Create(),
blink::DocumentToken(), blink::FramePolicy(),
blink::mojom::FrameOwnerProperties(),
blink::FrameOwnerElementType::kIframe, ukm::kInvalidSourceId);
RenderFrameHostManager* iframe =
contents()->GetPrimaryFrameTree().root()->child_at(0)->render_manager();
NavigationEntryImpl entry(
nullptr /* instance */, kUrl2,
Referrer(kUrl1, network::mojom::ReferrerPolicy::kDefault),
/* initiator_origin= */ std::nullopt,
/* initiator_base_url= */ std::nullopt, std::u16string() /* title */,
ui::PAGE_TRANSITION_LINK, false /* is_renderer_init */,
nullptr /* blob_url_loader_factory */, false /* is_initial_entry */);
RenderFrameHostImpl* cross_site = NavigateToEntry(iframe, &entry);
DidNavigateFrame(iframe, cross_site);
// A proxy to the iframe should now exist in the SiteInstanceGroup of the main
// frames.
EXPECT_NE(cross_site->GetSiteInstance(), contents1->GetSiteInstance());
EXPECT_NE(nullptr, iframe->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(
contents1->GetSiteInstance()->group()));
EXPECT_NE(nullptr, iframe->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(
contents2->GetSiteInstance()->group()));
// Navigate |contents2| away from the sad tab (and thus away from the
// SiteInstance of |contents1|). This should not destroy the proxies needed by
// |contents1| -- that was http://crbug.com/473714.
EXPECT_FALSE(contents2->GetPrimaryMainFrame()->IsRenderFrameLive());
contents2->NavigateAndCommit(kUrl3);
EXPECT_TRUE(contents2->GetPrimaryMainFrame()->IsRenderFrameLive());
EXPECT_NE(nullptr, iframe->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(
contents1->GetSiteInstance()->group()));
EXPECT_EQ(nullptr, iframe->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(
contents2->GetSiteInstance()->group()));
}
// Tests two WebContents from the same origin, where one is first navigated to
// a different origin. This different origin experiences a Renderer crash.
// However we then navigate that WebContents back to the old origin, which still
// has an active Renderer.
//
// This test confirms that for this return navigation that we identified that
// there is no FallbackSurface for the RenderWidgetHostView to display during
// the navigation. (https://crbug.com/1258363)
// TODO(crbug.com/375057184): Determine why this test crashes on Android and
// re-enable it.
#if BUILDFLAG(IS_ANDROID)
#define MAYBE_TwoTabsOneNavigatesAndCrashesThenNavigatesBack \
DISABLED_TwoTabsOneNavigatesAndCrashesThenNavigatesBack
#else
#define MAYBE_TwoTabsOneNavigatesAndCrashesThenNavigatesBack \
TwoTabsOneNavigatesAndCrashesThenNavigatesBack
#endif
TEST_P(RenderFrameHostManagerTestWithSiteIsolation,
MAYBE_TwoTabsOneNavigatesAndCrashesThenNavigatesBack) {
const GURL kUrl1("http://www.google.com/");
const GURL kUrl2("http://webkit.org/");
// `contents1` and `contents2` navigate to the same page.
TestWebContents* contents1 = contents();
std::unique_ptr<TestWebContents> contents2(
TestWebContents::Create(browser_context(), contents1->GetSiteInstance()));
contents1->NavigateAndCommit(kUrl1);
contents2->NavigateAndCommit(kUrl1);
MockRenderProcessHost* rph = contents1->GetPrimaryMainFrame()->GetProcess();
EXPECT_EQ(rph, contents2->GetPrimaryMainFrame()->GetProcess());
EXPECT_TRUE(contents1->GetPrimaryMainFrame()->GetView());
EXPECT_TRUE(contents2->GetPrimaryMainFrame()->GetView());
EXPECT_TRUE(contents1->GetPrimaryMainFrame()->IsRenderFrameLive());
EXPECT_TRUE(contents2->GetPrimaryMainFrame()->IsRenderFrameLive());
EXPECT_EQ(contents1->GetSiteInstance(), contents2->GetSiteInstance());
TestRenderWidgetHostView* initial_view =
static_cast<TestRenderWidgetHostView*>(
contents2->GetPrimaryMainFrame()->GetView());
// Navigate `content2` to a different page. This navigation should have a
// valid FallbackSurface for the RenderWidgetHostView to display.
contents2->NavigateAndCommit(kUrl2);
TestRenderWidgetHostView* post_nav_view =
static_cast<TestRenderWidgetHostView*>(
contents2->GetPrimaryMainFrame()->GetView());
// Since this is a different origin we should also be using a different
// RenderWidgetHostView.
EXPECT_NE(initial_view, post_nav_view);
EXPECT_FALSE(
post_nav_view->clear_fallback_surface_for_commit_pending_called());
// Since this is a cross-origin navigation, paint holding would not be
// enabled without user activation.
EXPECT_FALSE(post_nav_view->take_fallback_content_from_called());
EXPECT_TRUE(contents1->GetPrimaryMainFrame()->IsRenderFrameLive());
EXPECT_TRUE(contents2->GetPrimaryMainFrame()->IsRenderFrameLive());
EXPECT_NE(contents1->GetSiteInstance(), contents2->GetSiteInstance());
EXPECT_TRUE(contents1->GetPrimaryMainFrame()->GetView());
EXPECT_TRUE(contents2->GetPrimaryMainFrame()->GetView());
// Crash the Renderer of the tab that navigated.
MockRenderProcessHost* rph2 = contents2->GetPrimaryMainFrame()->GetProcess();
EXPECT_NE(rph, rph2);
rph2->SimulateCrash();
EXPECT_TRUE(contents1->GetPrimaryMainFrame()->IsRenderFrameLive());
EXPECT_FALSE(contents2->GetPrimaryMainFrame()->IsRenderFrameLive());
EXPECT_NE(contents1->GetSiteInstance(), contents2->GetSiteInstance());
EXPECT_TRUE(contents1->GetPrimaryMainFrame()->GetView());
EXPECT_FALSE(contents2->GetPrimaryMainFrame()->GetView());
// Navigate `contents2` back to previous host, which still has an active
// Renderer. This should notify the RenderWidgetHostView that there is no
// new FallbackSurface to take, and that it should update it's currently
// cached one.
contents2->NavigateAndCommit(kUrl1);
TestRenderWidgetHostView* return_nav_view =
static_cast<TestRenderWidgetHostView*>(
contents2->GetPrimaryMainFrame()->GetView());
// We should be reusing the original RenderWidgetHostView that `contents2`
// used before the navigation to `kUrl2`
EXPECT_EQ(initial_view, return_nav_view);
EXPECT_TRUE(
return_nav_view->clear_fallback_surface_for_commit_pending_called());
EXPECT_FALSE(return_nav_view->take_fallback_content_from_called());
return_nav_view->ClearFallbackSurfaceCalled();
EXPECT_TRUE(contents1->GetPrimaryMainFrame()->IsRenderFrameLive());
EXPECT_TRUE(contents2->GetPrimaryMainFrame()->IsRenderFrameLive());
EXPECT_EQ(contents1->GetSiteInstance(), contents2->GetSiteInstance());
EXPECT_TRUE(contents1->GetPrimaryMainFrame()->GetView());
EXPECT_TRUE(contents2->GetPrimaryMainFrame()->GetView());
// We should also be back to sharing the same RenderProcessHost.
MockRenderProcessHost* rph3 = contents2->GetPrimaryMainFrame()->GetProcess();
EXPECT_NE(rph2, rph3);
EXPECT_EQ(rph, rph3);
}
// Ensure that we don't grant WebUI bindings to a pending RenderViewHost when
// creating proxies for a non-WebUI subframe navigation. This was possible due
// to the InitRenderView call from CreateRenderFrameProxy.
// See https://crbug.com/536145.
TEST_P(RenderFrameHostManagerTestWithSiteIsolation,
DontGrantPendingWebUIToSubframe) {
// Make sure the initial process is live so that the pending WebUI navigation
// does not commit immediately. Give the page a subframe as well.
const GURL kUrl1("http://foo.com");
RenderFrameHostImpl* main_rfh = contents()->GetPrimaryMainFrame();
NavigateAndCommit(kUrl1);
EXPECT_TRUE(main_rfh->render_view_host()->IsRenderViewLive());
EXPECT_TRUE(main_rfh->IsRenderFrameLive());
main_rfh->OnCreateChildFrame(
main_rfh->GetProcess()->GetNextRoutingID(),
TestRenderFrameHost::CreateStubFrameRemote(),
TestRenderFrameHost::CreateStubBrowserInterfaceBrokerReceiver(),
TestRenderFrameHost::CreateStubPolicyContainerBindParams(),
TestRenderFrameHost::CreateStubAssociatedInterfaceProviderReceiver(),
blink::mojom::TreeScopeType::kDocument, std::string(), "uniqueName1",
false, blink::LocalFrameToken(), base::UnguessableToken::Create(),
blink::DocumentToken(), blink::FramePolicy(),
blink::mojom::FrameOwnerProperties(),
blink::FrameOwnerElementType::kIframe, ukm::kInvalidSourceId);
RenderFrameHostManager* subframe_rfhm =
contents()->GetPrimaryFrameTree().root()->child_at(0)->render_manager();
// Start a pending WebUI navigation in the main frame and verify that the
// pending RVH has bindings.
const GURL kWebUIUrl(GetWebUIURL("foo"));
NavigationEntryImpl webui_entry(
nullptr /* instance */, kWebUIUrl, Referrer(),
/* initiator_origin= */ std::nullopt,
/* initiator_base_url= */ std::nullopt, std::u16string() /* title */,
ui::PAGE_TRANSITION_TYPED, false /* is_renderer_init */,
nullptr /* blob_url_loader_factory */, false /* is_initial_entry */);
RenderFrameHostManager* main_rfhm =
contents()->GetPrimaryFrameTree().root()->render_manager();
RenderFrameHostImpl* webui_rfh = NavigateToEntry(main_rfhm, &webui_entry);
EXPECT_EQ(webui_rfh, GetPendingFrameHost(main_rfhm));
EXPECT_TRUE(webui_rfh->GetEnabledBindings().Has(BindingsPolicyValue::kWebUi));
// Before it commits, do a cross-process navigation in a subframe. This
// should not grant WebUI bindings to the subframe's RVH.
const GURL kSubframeUrl("http://bar.com");
NavigationEntryImpl subframe_entry(
nullptr /* instance */, kSubframeUrl, Referrer(),
/* initiator_origin= */ std::nullopt,
/* initiator_base_url= */ std::nullopt, std::u16string() /* title */,
ui::PAGE_TRANSITION_LINK, false /* is_renderer_init */,
nullptr /* blob_url_loader_factory */, false /* is_initial_entry */);
RenderFrameHostImpl* bar_rfh =
NavigateToEntry(subframe_rfhm, &subframe_entry);
EXPECT_FALSE(bar_rfh->GetEnabledBindings().Has(BindingsPolicyValue::kWebUi));
}
// This class intercepts RenderFrameProxyHost creations, and overrides their
// respective blink::mojom::RemoteFrame instances, so that it can watch the
// updates of opener frames.
class UpdateOpenerProxyObserver : public RenderFrameProxyHost::TestObserver {
public:
UpdateOpenerProxyObserver() {
RenderFrameProxyHost::SetObserverForTesting(this);
}
~UpdateOpenerProxyObserver() override {
RenderFrameProxyHost::SetObserverForTesting(nullptr);
}
std::optional<blink::FrameToken> OpenerFrameToken(
RenderFrameProxyHost* proxy) {
return remote_frames_[proxy]->opener_frame_token();
}
private:
class Remote : public content::FakeRemoteFrame {
public:
explicit Remote(RenderFrameProxyHost* proxy) {
Init(proxy->BindRemoteFrameReceiverForTesting());
}
void UpdateOpener(
const std::optional<blink::FrameToken>& frame_token) override {
frame_token_ = frame_token;
}
std::optional<blink::FrameToken> opener_frame_token() {
return frame_token_;
}
private:
std::optional<blink::FrameToken> frame_token_;
};
void OnRemoteFrameBound(RenderFrameProxyHost* proxy_host) override {
remote_frames_[proxy_host] = std::make_unique<Remote>(proxy_host);
}
std::map<RenderFrameProxyHost*, std::unique_ptr<Remote>> remote_frames_;
};
// Test that opener proxies are created properly with a cycle on the opener
// chain.
TEST_P(RenderFrameHostManagerTest, CreateOpenerProxiesWithCycleOnOpenerChain) {
UpdateOpenerProxyObserver proxy_observers;
const GURL kUrl1("http://www.google.com/");
const GURL kUrl2 = isolated_cross_site_url();
// Navigate to an initial URL.
contents()->NavigateAndCommit(kUrl1);
TestRenderFrameHost* rfh1 = main_test_rfh();
scoped_refptr<SiteInstanceImpl> site_instance1 = rfh1->GetSiteInstance();
EXPECT_EQ(!AreStrictSiteInstancesEnabled(),
site_instance1->IsDefaultSiteInstance());
// Create 2 new tabs and construct the opener chain as follows:
//
// tab2 <--- tab1 <---- contents()
// | ^
// +-------+
//
std::unique_ptr<TestWebContents> tab1(
TestWebContents::Create(browser_context(), site_instance1.get()));
RenderFrameHostManager* tab1_manager =
tab1->GetPrimaryFrameTree().root()->render_manager();
std::unique_ptr<TestWebContents> tab2(
TestWebContents::Create(browser_context(), site_instance1.get()));
RenderFrameHostManager* tab2_manager =
tab2->GetPrimaryFrameTree().root()->render_manager();
contents()->SetOpener(tab1.get());
tab1->SetOpener(tab2.get());
tab2->SetOpener(tab1.get());
// Navigate main window to a cross-site URL. This will call
// CreateOpenerProxies() to create proxies for the two opener tabs in the new
// SiteInstanceGroup.
contents()->NavigateAndCommit(kUrl2);
TestRenderFrameHost* rfh2 = main_test_rfh();
EXPECT_NE(site_instance1, rfh2->GetSiteInstance());
EXPECT_NE(site_instance1->group(), rfh2->GetSiteInstance()->group());
// Check that each tab now has a proxy in the new SiteInstanceGroup.
RenderFrameProxyHost* tab1_proxy =
tab1_manager->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(rfh2->GetSiteInstance()->group());
EXPECT_TRUE(tab1_proxy);
RenderFrameProxyHost* tab2_proxy =
tab2_manager->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(rfh2->GetSiteInstance()->group());
EXPECT_TRUE(tab2_proxy);
// Verify that the proxies' openers point to each other.
auto tab1_opener_frame_token =
tab1_manager->GetOpenerFrameToken(rfh2->GetSiteInstance()->group());
auto tab2_opener_frame_token =
tab2_manager->GetOpenerFrameToken(rfh2->GetSiteInstance()->group());
EXPECT_EQ(*tab1_opener_frame_token, tab2_proxy->GetFrameToken());
EXPECT_EQ(*tab2_opener_frame_token, tab1_proxy->GetFrameToken());
// Setting tab2_proxy's opener required an extra IPC message to be set, since
// the opener's frame token wasn't available when tab2_proxy was created.
// Verify that this IPC was sent and that it passed correct frame token.
base::RunLoop().RunUntilIdle();
DCHECK(proxy_observers.OpenerFrameToken(tab2_proxy) ==
tab2_manager->GetOpenerFrameToken(rfh2->GetSiteInstance()->group()));
}
// Test that opener proxies are created properly when the opener points
// to itself.
TEST_P(RenderFrameHostManagerTest, CreateOpenerProxiesWhenOpenerPointsToSelf) {
UpdateOpenerProxyObserver proxy_observers;
const GURL kUrl1("http://www.google.com/");
const GURL kUrl2 = isolated_cross_site_url();
// Navigate to an initial URL.
contents()->NavigateAndCommit(kUrl1);
TestRenderFrameHost* rfh1 = main_test_rfh();
scoped_refptr<SiteInstanceImpl> site_instance1 = rfh1->GetSiteInstance();
EXPECT_EQ(!AreStrictSiteInstancesEnabled(),
site_instance1->IsDefaultSiteInstance());
// Create an opener tab, and simulate that its opener points to itself.
std::unique_ptr<TestWebContents> opener(
TestWebContents::Create(browser_context(), site_instance1.get()));
RenderFrameHostManager* opener_manager =
opener->GetPrimaryFrameTree().root()->render_manager();
contents()->SetOpener(opener.get());
opener->SetOpener(opener.get());
// Navigate main window to a cross-site URL. This will call
// CreateOpenerProxies() to create proxies for the opener tab in the new
// SiteInstanceGroup.
contents()->NavigateAndCommit(kUrl2);
TestRenderFrameHost* rfh2 = main_test_rfh();
EXPECT_NE(site_instance1, rfh2->GetSiteInstance());
EXPECT_NE(site_instance1->group(), rfh2->GetSiteInstance()->group());
// Check that the opener now has a proxy in the new SiteInstanceGroup.
RenderFrameProxyHost* opener_proxy =
opener_manager->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(rfh2->GetSiteInstance()->group());
EXPECT_TRUE(opener_proxy);
// Verify that the proxy's opener points to itself.
auto opener_frame_token =
opener_manager->GetOpenerFrameToken(rfh2->GetSiteInstance()->group());
EXPECT_EQ(*opener_frame_token, opener_proxy->GetFrameToken());
// Setting the opener in opener_proxy required an extra IPC message, since
// the opener's frame_token wasn't available when opener_proxy was created.
// Verify that this IPC was sent and that it passed correct frame token.
base::RunLoop().RunUntilIdle();
DCHECK(proxy_observers.OpenerFrameToken(opener_proxy) ==
opener_manager->GetOpenerFrameToken(rfh2->GetSiteInstance()->group()));
}
// Build the following frame opener graph and see that it can be properly
// traversed when creating opener proxies:
//
// +-> root4 <--+ root3 <---- root2 +--- root1
// | / | ^ / \ | / \ .
// | 42 +-----|------- 22 23 <--+ 12 13
// | +------------+ | | ^
// +-------------------------------+ +-+
//
// The test starts traversing openers from root1 and expects to discover all
// four FrameTrees. Nodes 13 (with cycle to itself) and 42 (with back link to
// root3) should be put on the list of nodes that will need their frame openers
// set separately in a second pass, since their opener routing IDs won't be
// available during the first pass of CreateOpenerProxies.
TEST_P(RenderFrameHostManagerTest, TraverseComplexOpenerChain) {
contents()->NavigateAndCommit(GURL("http://tab1.com"));
FrameTree* tree1 = &contents()->GetPrimaryFrameTree();
FrameTreeNode* root1 = tree1->root();
int process_id = root1->current_frame_host()->GetProcess()->GetDeprecatedID();
constexpr auto kOwnerType = blink::FrameOwnerElementType::kIframe;
const bool is_dummy_frame_for_inner_tree = false;
tree1->AddFrame(
root1->current_frame_host(), process_id, 12,
TestRenderFrameHost::CreateStubFrameRemote(),
TestRenderFrameHost::CreateStubBrowserInterfaceBrokerReceiver(),
TestRenderFrameHost::CreateStubPolicyContainerBindParams(),
TestRenderFrameHost::CreateStubAssociatedInterfaceProviderReceiver(),
blink::mojom::TreeScopeType::kDocument, std::string(), "uniqueName0",
false, blink::LocalFrameToken(), base::UnguessableToken::Create(),
blink::DocumentToken(), blink::FramePolicy(),
blink::mojom::FrameOwnerProperties(), false, kOwnerType,
is_dummy_frame_for_inner_tree);
tree1->AddFrame(
root1->current_frame_host(), process_id, 13,
TestRenderFrameHost::CreateStubFrameRemote(),
TestRenderFrameHost::CreateStubBrowserInterfaceBrokerReceiver(),
TestRenderFrameHost::CreateStubPolicyContainerBindParams(),
TestRenderFrameHost::CreateStubAssociatedInterfaceProviderReceiver(),
blink::mojom::TreeScopeType::kDocument, std::string(), "uniqueName1",
false, blink::LocalFrameToken(), base::UnguessableToken::Create(),
blink::DocumentToken(), blink::FramePolicy(),
blink::mojom::FrameOwnerProperties(), false, kOwnerType,
is_dummy_frame_for_inner_tree);
std::unique_ptr<TestWebContents> tab2(
TestWebContents::Create(browser_context(), nullptr));
tab2->NavigateAndCommit(GURL("http://tab2.com"));
FrameTree* tree2 = &tab2->GetPrimaryFrameTree();
FrameTreeNode* root2 = tree2->root();
process_id = root2->current_frame_host()->GetProcess()->GetDeprecatedID();
tree2->AddFrame(
root2->current_frame_host(), process_id, 22,
TestRenderFrameHost::CreateStubFrameRemote(),
TestRenderFrameHost::CreateStubBrowserInterfaceBrokerReceiver(),
TestRenderFrameHost::CreateStubPolicyContainerBindParams(),
TestRenderFrameHost::CreateStubAssociatedInterfaceProviderReceiver(),
blink::mojom::TreeScopeType::kDocument, std::string(), "uniqueName2",
false, blink::LocalFrameToken(), base::UnguessableToken::Create(),
blink::DocumentToken(), blink::FramePolicy(),
blink::mojom::FrameOwnerProperties(), false, kOwnerType,
is_dummy_frame_for_inner_tree);
tree2->AddFrame(
root2->current_frame_host(), process_id, 23,
TestRenderFrameHost::CreateStubFrameRemote(),
TestRenderFrameHost::CreateStubBrowserInterfaceBrokerReceiver(),
TestRenderFrameHost::CreateStubPolicyContainerBindParams(),
TestRenderFrameHost::CreateStubAssociatedInterfaceProviderReceiver(),
blink::mojom::TreeScopeType::kDocument, std::string(), "uniqueName3",
false, blink::LocalFrameToken(), base::UnguessableToken::Create(),
blink::DocumentToken(), blink::FramePolicy(),
blink::mojom::FrameOwnerProperties(), false, kOwnerType,
is_dummy_frame_for_inner_tree);
std::unique_ptr<TestWebContents> tab3(
TestWebContents::Create(browser_context(), nullptr));
FrameTree* tree3 = &tab3->GetPrimaryFrameTree();
FrameTreeNode* root3 = tree3->root();
std::unique_ptr<TestWebContents> tab4(
TestWebContents::Create(browser_context(), nullptr));
tab4->NavigateAndCommit(GURL("http://tab4.com"));
FrameTree* tree4 = &tab4->GetPrimaryFrameTree();
FrameTreeNode* root4 = tree4->root();
process_id = root4->current_frame_host()->GetProcess()->GetDeprecatedID();
tree4->AddFrame(
root4->current_frame_host(), process_id, 42,
TestRenderFrameHost::CreateStubFrameRemote(),
TestRenderFrameHost::CreateStubBrowserInterfaceBrokerReceiver(),
TestRenderFrameHost::CreateStubPolicyContainerBindParams(),
TestRenderFrameHost::CreateStubAssociatedInterfaceProviderReceiver(),
blink::mojom::TreeScopeType::kDocument, std::string(), "uniqueName4",
false, blink::LocalFrameToken(), base::UnguessableToken::Create(),
blink::DocumentToken(), blink::FramePolicy(),
blink::mojom::FrameOwnerProperties(), false, kOwnerType,
is_dummy_frame_for_inner_tree);
root1->child_at(1)->SetOpener(root1->child_at(1));
root1->SetOpener(root2->child_at(1));
root2->SetOpener(root3);
root2->child_at(0)->SetOpener(root4);
root2->child_at(1)->SetOpener(root4);
root4->child_at(0)->SetOpener(root3);
std::vector<FrameTree*> opener_frame_trees;
std::unordered_set<FrameTreeNode*> nodes_with_back_links;
std::unordered_set<FrameTreeNode*> cross_browsing_context_group_openers;
CollectOpenerFrameTrees(root1, /*site_instance_group=*/nullptr,
&opener_frame_trees, &nodes_with_back_links,
&cross_browsing_context_group_openers);
EXPECT_EQ(4U, opener_frame_trees.size());
EXPECT_EQ(tree1, opener_frame_trees[0]);
EXPECT_EQ(tree2, opener_frame_trees[1]);
EXPECT_EQ(tree3, opener_frame_trees[2]);
EXPECT_EQ(tree4, opener_frame_trees[3]);
EXPECT_EQ(2U, nodes_with_back_links.size());
EXPECT_TRUE(nodes_with_back_links.find(root1->child_at(1)) !=
nodes_with_back_links.end());
EXPECT_TRUE(nodes_with_back_links.find(root4->child_at(0)) !=
nodes_with_back_links.end());
}
// This class intercepts RenderFrameProxyHost creations, and overrides their
// respective blink::mojom::RemoteFrame instances, so that it can watch the
// start and stop loading states.
class PageFocusProxyObserver : public RenderFrameProxyHost::TestObserver {
public:
PageFocusProxyObserver() {
RenderFrameProxyHost::SetObserverForTesting(this);
}
~PageFocusProxyObserver() override {
RenderFrameProxyHost::SetObserverForTesting(nullptr);
}
bool IsPageFocused(RenderFrameProxyHost* proxy) {
return remote_frames_[proxy]->set_page_focus();
}
private:
class Remote : public content::FakeRemoteFrame {
public:
explicit Remote(RenderFrameProxyHost* proxy) {
Init(proxy->BindRemoteFrameReceiverForTesting());
}
void SetPageFocus(bool is_focused) override {
set_page_focus_ = is_focused;
}
bool set_page_focus() { return set_page_focus_; }
private:
bool set_page_focus_ = false;
};
void OnRemoteFrameBound(RenderFrameProxyHost* proxy_host) override {
remote_frames_[proxy_host] = std::make_unique<Remote>(proxy_host);
}
std::map<RenderFrameProxyHost*, std::unique_ptr<Remote>> remote_frames_;
};
// Check that when a window is focused/blurred, the message that sets
// page-level focus updates is sent to each process involved in rendering the
// current page.
//
// TODO(alexmos): Move this test to FrameTree unit tests once NavigateToEntry
// is moved to a common place. See https://crbug.com/547275.
TEST_P(RenderFrameHostManagerTest, PageFocusPropagatesToSubframeProcesses) {
// This test only makes sense when cross-site subframes use separate
// processes.
if (!AreAllSitesIsolatedForTesting())
return;
// Start monitoring RenderFrameProxyHost.
PageFocusProxyObserver proxy_observer;
const GURL kUrlA("http://a.com/");
const GURL kUrlB("http://b.com/");
const GURL kUrlC("http://c.com/");
constexpr auto kOwnerType = blink::FrameOwnerElementType::kIframe;
// Set up a page at a.com with three subframes: two for b.com and one for
// c.com.
contents()->NavigateAndCommit(kUrlA);
main_test_rfh()->OnCreateChildFrame(
main_test_rfh()->GetProcess()->GetNextRoutingID(),
TestRenderFrameHost::CreateStubFrameRemote(),
TestRenderFrameHost::CreateStubBrowserInterfaceBrokerReceiver(),
TestRenderFrameHost::CreateStubPolicyContainerBindParams(),
TestRenderFrameHost::CreateStubAssociatedInterfaceProviderReceiver(),
blink::mojom::TreeScopeType::kDocument, "frame1", "uniqueName1", false,
blink::LocalFrameToken(), base::UnguessableToken::Create(),
blink::DocumentToken(), blink::FramePolicy(),
blink::mojom::FrameOwnerProperties(), kOwnerType, ukm::kInvalidSourceId);
main_test_rfh()->OnCreateChildFrame(
main_test_rfh()->GetProcess()->GetNextRoutingID(),
TestRenderFrameHost::CreateStubFrameRemote(),
TestRenderFrameHost::CreateStubBrowserInterfaceBrokerReceiver(),
TestRenderFrameHost::CreateStubPolicyContainerBindParams(),
TestRenderFrameHost::CreateStubAssociatedInterfaceProviderReceiver(),
blink::mojom::TreeScopeType::kDocument, "frame2", "uniqueName2", false,
blink::LocalFrameToken(), base::UnguessableToken::Create(),
blink::DocumentToken(), blink::FramePolicy(),
blink::mojom::FrameOwnerProperties(), kOwnerType, ukm::kInvalidSourceId);
main_test_rfh()->OnCreateChildFrame(
main_test_rfh()->GetProcess()->GetNextRoutingID(),
TestRenderFrameHost::CreateStubFrameRemote(),
TestRenderFrameHost::CreateStubBrowserInterfaceBrokerReceiver(),
TestRenderFrameHost::CreateStubPolicyContainerBindParams(),
TestRenderFrameHost::CreateStubAssociatedInterfaceProviderReceiver(),
blink::mojom::TreeScopeType::kDocument, "frame3", "uniqueName3", false,
blink::LocalFrameToken(), base::UnguessableToken::Create(),
blink::DocumentToken(), blink::FramePolicy(),
blink::mojom::FrameOwnerProperties(), kOwnerType, ukm::kInvalidSourceId);
FrameTreeNode* root = contents()->GetPrimaryFrameTree().root();
RenderFrameHostManager* child1 = root->child_at(0)->render_manager();
RenderFrameHostManager* child2 = root->child_at(1)->render_manager();
RenderFrameHostManager* child3 = root->child_at(2)->render_manager();
// Navigate first two subframes to B.
NavigationEntryImpl entryB(
nullptr /* instance */, kUrlB,
Referrer(kUrlA, network::mojom::ReferrerPolicy::kDefault),
/* initiator_origin= */ std::nullopt,
/* initiator_base_url= */ std::nullopt, std::u16string() /* title */,
ui::PAGE_TRANSITION_LINK, false /* is_renderer_init */,
nullptr /* blob_url_loader_factory */, false /* is_initial_entry */);
TestRenderFrameHost* host1 =
static_cast<TestRenderFrameHost*>(NavigateToEntry(child1, &entryB));
// The main frame should have proxies for B.
RenderFrameProxyHost* proxyB =
root->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(host1->GetSiteInstance()->group());
EXPECT_TRUE(proxyB);
TestRenderFrameHost* host2 =
static_cast<TestRenderFrameHost*>(NavigateToEntry(child2, &entryB));
DidNavigateFrame(child1, host1);
DidNavigateFrame(child2, host2);
// Navigate the third subframe to C.
NavigationEntryImpl entryC(
nullptr /* instance */, kUrlC,
Referrer(kUrlA, network::mojom::ReferrerPolicy::kDefault),
/* initiator_origin= */ std::nullopt,
/* initiator_base_url= */ std::nullopt, std::u16string() /* title */,
ui::PAGE_TRANSITION_LINK, false /* is_renderer_init */,
nullptr /* blob_url_loader_factory */, false /* is_initial_entry */);
TestRenderFrameHost* host3 =
static_cast<TestRenderFrameHost*>(NavigateToEntry(child3, &entryC));
// The main frame should have proxies for C.
RenderFrameProxyHost* proxyC =
root->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(host3->GetSiteInstance()->group());
EXPECT_TRUE(proxyC);
DidNavigateFrame(child3, host3);
// Make sure the first two subframes and the third subframe are placed in
// distinct processes.
EXPECT_NE(host1->GetProcess(), main_test_rfh()->GetProcess());
EXPECT_EQ(host1->GetProcess(), host2->GetProcess());
EXPECT_NE(host3->GetProcess(), main_test_rfh()->GetProcess());
EXPECT_NE(host3->GetProcess(), host1->GetProcess());
base::RunLoop().RunUntilIdle();
// Focus the main page, and verify that the focus message was sent to all
// processes. The message to A should be sent through the main frame's
// RenderViewHost, and the message to B and C should be send through proxies
// that the main frame has for B and C.
main_test_rfh()->GetProcess()->sink().ClearMessages();
host1->GetProcess()->sink().ClearMessages();
host3->GetProcess()->sink().ClearMessages();
main_test_rfh()->GetRenderWidgetHost()->Focus();
base::RunLoop().RunUntilIdle();
VerifyPageFocusMessage(main_test_rfh()->GetRenderWidgetHost(), true);
EXPECT_TRUE(proxy_observer.IsPageFocused(proxyB));
EXPECT_TRUE(proxy_observer.IsPageFocused(proxyC));
// Similarly, simulate focus loss on main page, and verify that the focus
// message was sent to all processes.
main_test_rfh()->GetProcess()->sink().ClearMessages();
host1->GetProcess()->sink().ClearMessages();
host3->GetProcess()->sink().ClearMessages();
main_test_rfh()->GetRenderWidgetHost()->Blur();
base::RunLoop().RunUntilIdle();
VerifyPageFocusMessage(main_test_rfh()->GetRenderWidgetHost(), false);
EXPECT_FALSE(proxy_observer.IsPageFocused(proxyB));
EXPECT_FALSE(proxy_observer.IsPageFocused(proxyC));
}
// Check that page-level focus state is preserved across subframe navigations.
//
// TODO(alexmos): Move this test to FrameTree unit tests once NavigateToEntry
// is moved to a common place. See https://crbug.com/547275.
TEST_P(RenderFrameHostManagerTest,
PageFocusIsPreservedAcrossSubframeNavigations) {
// This test only makes sense when cross-site subframes use separate
// processes.
if (!AreAllSitesIsolatedForTesting())
return;
// Start monitoring RenderFrameProxyHost.
PageFocusProxyObserver proxy_observer;
const GURL kUrlA("http://a.com/");
const GURL kUrlB("http://b.com/");
const GURL kUrlC("http://c.com/");
constexpr auto kOwnerType = blink::FrameOwnerElementType::kIframe;
// Set up a page at a.com with a b.com subframe.
contents()->NavigateAndCommit(kUrlA);
main_test_rfh()->OnCreateChildFrame(
main_test_rfh()->GetProcess()->GetNextRoutingID(),
TestRenderFrameHost::CreateStubFrameRemote(),
TestRenderFrameHost::CreateStubBrowserInterfaceBrokerReceiver(),
TestRenderFrameHost::CreateStubPolicyContainerBindParams(),
TestRenderFrameHost::CreateStubAssociatedInterfaceProviderReceiver(),
blink::mojom::TreeScopeType::kDocument, "frame1", "uniqueName1", false,
blink::LocalFrameToken(), base::UnguessableToken::Create(),
blink::DocumentToken(), blink::FramePolicy(),
blink::mojom::FrameOwnerProperties(), kOwnerType, ukm::kInvalidSourceId);
FrameTreeNode* root = contents()->GetPrimaryFrameTree().root();
RenderFrameHostManager* child = root->child_at(0)->render_manager();
// Navigate subframe to B.
NavigationEntryImpl entryB(
nullptr /* instance */, kUrlB,
Referrer(kUrlA, network::mojom::ReferrerPolicy::kDefault),
/* initiator_origin= */ std::nullopt,
/* initiator_base_url= */ std::nullopt, std::u16string() /* title */,
ui::PAGE_TRANSITION_LINK, false /* is_renderer_init */,
nullptr /* blob_url_loader_factory */, false /* is_initial_entry */);
TestRenderFrameHost* hostB =
static_cast<TestRenderFrameHost*>(NavigateToEntry(child, &entryB));
DidNavigateFrame(child, hostB);
// Ensure that the main page is focused.
main_test_rfh()->GetView()->Focus();
EXPECT_TRUE(main_test_rfh()->GetView()->HasFocus());
main_test_rfh()->GetRenderWidgetHost()->SetPageFocus(true);
EXPECT_TRUE(main_test_rfh()->GetRenderWidgetHost()->is_focused());
// Navigate the subframe to C.
NavigationEntryImpl entryC(
nullptr /* instance */, kUrlC,
Referrer(kUrlA, network::mojom::ReferrerPolicy::kDefault),
/* initiator_origin= */ std::nullopt,
/* initiator_base_url= */ std::nullopt, std::u16string() /* title */,
ui::PAGE_TRANSITION_LINK, false /* is_renderer_init */,
nullptr /* blob_url_loader_factory */, false /* is_initial_entry */);
TestRenderFrameHost* hostC =
static_cast<TestRenderFrameHost*>(NavigateToEntry(child, &entryC));
// The main frame should now have a proxy for C.
RenderFrameProxyHost* proxyC =
root->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(hostC->GetSiteInstance()->group());
EXPECT_TRUE(proxyC);
DidNavigateFrame(child, hostC);
base::RunLoop().RunUntilIdle();
// Since the B->C navigation happened while the current page was focused,
// page focus should propagate to the new subframe process. Check that
// process C received the proper focus message.
EXPECT_TRUE(proxy_observer.IsPageFocused(proxyC));
}
// Checks that a restore navigation to a WebUI works.
TEST_P(RenderFrameHostManagerTest, RestoreNavigationToWebUI) {
const GURL kInitUrl(GetWebUIURL("foo"));
scoped_refptr<SiteInstanceImpl> initial_instance =
SiteInstanceImpl::Create(browser_context());
initial_instance->SetSite(UrlInfo::CreateForTesting(kInitUrl));
std::unique_ptr<TestWebContents> web_contents(
TestWebContents::Create(browser_context(), initial_instance));
RenderFrameHostManager* manager =
web_contents->GetPrimaryFrameTree().root()->render_manager();
NavigationControllerImpl& controller = web_contents->GetController();
// Setup a restored entry.
std::vector<std::unique_ptr<NavigationEntry>> entries;
std::unique_ptr<NavigationEntry> new_entry =
NavigationController::CreateNavigationEntry(
kInitUrl, Referrer(), /* initiator_origin= */ std::nullopt,
/* initiator_base_url= */ std::nullopt, ui::PAGE_TRANSITION_TYPED,
false, std::string(), browser_context(),
nullptr /* blob_url_loader_factory */);
entries.push_back(std::move(new_entry));
controller.Restore(0, RestoreType::kRestored, &entries);
ASSERT_EQ(0u, entries.size());
ASSERT_EQ(1, controller.GetEntryCount());
RenderFrameHostImpl* initial_host = manager->current_frame_host();
ASSERT_TRUE(initial_host);
EXPECT_FALSE(initial_host->IsRenderFrameLive());
EXPECT_FALSE(initial_host->web_ui());
// Navigation request to an entry from a previous browsing session.
NavigationEntryImpl entry(
nullptr /* instance */, kInitUrl, Referrer(),
/* initiator_origin= */ std::nullopt,
/* initiator_base_url= */ std::nullopt, std::u16string() /* title */,
ui::PAGE_TRANSITION_RELOAD, false /* is_renderer_init */,
nullptr /* blob_url_loader_factory */, false /* is_initial_entry */);
entry.set_restore_type(RestoreType::kRestored);
NavigateToEntry(manager, &entry);
// As the initial renderer was not live, the new RenderFrameHost should be
// made immediately active at request time.
EXPECT_FALSE(GetPendingFrameHost(manager));
TestRenderFrameHost* current_host =
static_cast<TestRenderFrameHost*>(manager->current_frame_host());
ASSERT_TRUE(current_host);
EXPECT_EQ(current_host, initial_host);
EXPECT_TRUE(current_host->IsRenderFrameLive());
EXPECT_TRUE(current_host->web_ui());
// The RenderFrameHost committed.
DidNavigateFrame(manager, current_host);
EXPECT_EQ(current_host, manager->current_frame_host());
EXPECT_TRUE(current_host->web_ui());
}
// Simulates two simultaneous navigations involving one WebUI where the current
// RenderFrameHost commits.
TEST_P(RenderFrameHostManagerTest, SimultaneousNavigationWithOneWebUI1) {
if (ShouldCreateNewHostForAllFrames()) {
// This test involves starting a navigation while another navigation is
// committing, which might lead to deletion of a pending commit RFH, which
// will crash when RenderDocument is enabled. Skip the test if so.
// TODO(crbug.com/40186427): Update this test to work under
// navigation queueing, which will prevent the deletion of the pending
// commit RFH but still fails because this test waits for the new navigation
// to get to the ReadyToCommit stage before finishing the commit of the
// pending commit RFH.
return;
}
NavigationSimulator::NavigateAndCommitFromBrowser(contents(),
GetWebUIURL("foo/"));
RenderFrameHostManager* manager =
contents()->GetPrimaryFrameTree().root()->render_manager();
RenderFrameHostImpl* host1 = manager->current_frame_host();
EXPECT_TRUE(host1->IsRenderFrameLive());
WebUIImpl* web_ui = host1->web_ui();
EXPECT_TRUE(web_ui);
// Starts a reload of the WebUI page.
contents()->GetController().Reload(ReloadType::NORMAL, true);
auto reload =
NavigationSimulator::CreateFromPending(contents()->GetController());
reload->ReadyToCommit();
// It should be a same-site navigation reusing the same WebUI.
EXPECT_EQ(web_ui, host1->web_ui());
EXPECT_FALSE(GetPendingFrameHost(manager));
// Navigation request to a non-WebUI page.
const GURL kUrl("http://google.com");
auto navigation =
NavigationSimulator::CreateBrowserInitiated(kUrl, contents());
navigation->ReadyToCommit();
RenderFrameHostImpl* host2 = GetPendingFrameHost(manager);
ASSERT_TRUE(host2);
// The previous navigation should still be ongoing along with the new,
// cross-site one.
EXPECT_FALSE(host2->web_ui());
EXPECT_EQ(web_ui, host1->web_ui());
EXPECT_NE(host2, host1);
EXPECT_NE(web_ui, host2->web_ui());
// The current RenderFrameHost commits; its WebUI should still be in place.
reload->Commit();
EXPECT_EQ(host1, manager->current_frame_host());
EXPECT_EQ(web_ui, host1->web_ui());
// Because the Navigation that committed was browser-initiated, it will not
// have the user gesture bit set to true. This has the side-effect of not
// deleting the speculative RenderFrameHost at commit time.
// TODO(clamy): The speculative RenderFrameHost should be deleted at commit
// time if a browser-initiated navigation commits.
EXPECT_TRUE(GetPendingFrameHost(manager));
}
// Simulates two simultaneous navigations involving one WebUI where the new,
// cross-site RenderFrameHost commits.
TEST_P(RenderFrameHostManagerTest, SimultaneousNavigationWithOneWebUI2) {
if (ShouldCreateNewHostForAllFrames()) {
// This test involves starting a navigation while another navigation is
// committing, which might lead to deletion of a pending commit RFH, which
// will crash when RenderDocument is enabled. Skip the test if so.
// TODO(crbug.com/40186427): Update this test to work under
// navigation queueing, which will prevent the deletion of the pending
// commit RFH but still fails because this test waits for the new navigation
// to get to the ReadyToCommit stage before finishing the commit of the
// pending commit RFH.
return;
}
NavigationSimulator::NavigateAndCommitFromBrowser(contents(),
GetWebUIURL("foo/"));
RenderFrameHostManager* manager =
contents()->GetPrimaryFrameTree().root()->render_manager();
RenderFrameHostImpl* host1 = manager->current_frame_host();
EXPECT_TRUE(host1->IsRenderFrameLive());
WebUIImpl* web_ui = host1->web_ui();
EXPECT_TRUE(web_ui);
// Starts a reload of the WebUI page.
contents()->GetController().Reload(ReloadType::NORMAL, true);
auto reload =
NavigationSimulator::CreateFromPending(contents()->GetController());
reload->ReadyToCommit();
// It should be a same-site navigation reusing the same WebUI.
EXPECT_FALSE(GetPendingFrameHost(manager));
EXPECT_EQ(web_ui, host1->web_ui());
// Navigation request to a non-WebUI page.
const GURL kUrl("http://google.com");
auto navigation =
NavigationSimulator::CreateBrowserInitiated(kUrl, contents());
navigation->ReadyToCommit();
RenderFrameHostImpl* host2 = GetPendingFrameHost(manager);
ASSERT_TRUE(host2);
// The previous navigation should still be ongoing along with the new,
// cross-site one.
EXPECT_FALSE(host2->web_ui());
EXPECT_EQ(web_ui, host1->web_ui());
EXPECT_NE(host2, host1);
EXPECT_NE(web_ui, host2->web_ui());
// The new RenderFrameHost commits; there should be no active WebUI.
navigation->Commit();
EXPECT_EQ(host2, manager->current_frame_host());
EXPECT_FALSE(host2->web_ui());
EXPECT_FALSE(GetPendingFrameHost(manager));
}
// Shared code until before commit for the SimultaneousNavigationWithTwoWebUIs*
// tests, accepting a lambda to execute the commit step.
// Simulates two simultaneous navigations involving two WebUIs where the current
// RenderFrameHost commits.
TEST_P(RenderFrameHostManagerTest, SimultaneousNavigationWithTwoWebUIs1) {
if (ShouldCreateNewHostForAllFrames()) {
// This test involves starting a navigation while another navigation is
// committing, which might lead to deletion of a pending commit RFH, which
// will crash when RenderDocument is enabled. Skip the test if so.
// TODO(crbug.com/40186427): Update this test to work under
// navigation queueing, which will prevent the deletion of the pending
// commit RFH but still fails because this test waits for the new navigation
// to get to the ReadyToCommit stage before finishing the commit of the
// pending commit RFH.
return;
}
NavigationSimulator::NavigateAndCommitFromBrowser(contents(),
GetWebUIURL("foo"));
RenderFrameHostManager* manager =
contents()->GetPrimaryFrameTree().root()->render_manager();
RenderFrameHostImpl* host1 = manager->current_frame_host();
EXPECT_TRUE(host1->IsRenderFrameLive());
WebUIImpl* web_ui1 = host1->web_ui();
EXPECT_TRUE(web_ui1);
// Starts a reload of the WebUI page.
contents()->GetController().Reload(ReloadType::NORMAL, true);
auto reload =
NavigationSimulator::CreateFromPending(contents()->GetController());
reload->ReadyToCommit();
// It should be a same-site navigation reusing the same WebUI.
EXPECT_EQ(web_ui1, host1->web_ui());
EXPECT_FALSE(GetPendingFrameHost(manager));
// Navigate to another WebUI page.
const GURL kUrl(GetWebUIURL("bar"));
auto navigation =
NavigationSimulator::CreateBrowserInitiated(kUrl, contents());
navigation->ReadyToCommit();
RenderFrameHostImpl* host2 = GetPendingFrameHost(manager);
ASSERT_TRUE(host2);
// The previous navigation should still be ongoing along with the new,
// cross-site one.
EXPECT_EQ(web_ui1, host1->web_ui());
EXPECT_TRUE(manager->speculative_frame_host());
WebUIImpl* web_ui2 = manager->speculative_frame_host()->web_ui();
EXPECT_TRUE(web_ui2);
EXPECT_NE(web_ui2, web_ui1);
EXPECT_NE(host2, host1);
EXPECT_EQ(web_ui2, host2->web_ui());
// The current RenderFrameHost commits; its WebUI should still be active.
reload->Commit();
EXPECT_EQ(host1, manager->current_frame_host());
EXPECT_EQ(web_ui1, host1->web_ui());
// Because the Navigation that committed was browser-initiated, it will not
// have the user gesture bit set to true. This has the side-effect of not
// deleting the speculative RenderFrameHost at commit time.
// TODO(clamy): The speculative RenderFrameHost should be deleted at commit
// time if a browser-initiated navigation commits.
EXPECT_TRUE(manager->speculative_frame_host()->web_ui());
EXPECT_TRUE(GetPendingFrameHost(manager));
}
// Simulates two simultaneous navigations involving two WebUIs where the new,
// cross-site RenderFrameHost commits.
TEST_P(RenderFrameHostManagerTest, SimultaneousNavigationWithTwoWebUIs2) {
if (ShouldCreateNewHostForAllFrames()) {
// This test involves starting a navigation while another navigation is
// committing, which might lead to deletion of a pending commit RFH, which
// will crash when RenderDocument is enabled. Skip the test if so.
// TODO(crbug.com/40186427): Update this test to work under
// navigation queueing, which will prevent the deletion of the pending
// commit RFH but still fails because this test waits for the new navigation
// to get to the ReadyToCommit stage before finishing the commit of the
// pending commit RFH.
return;
}
NavigationSimulator::NavigateAndCommitFromBrowser(contents(),
GetWebUIURL("foo/"));
RenderFrameHostManager* manager =
contents()->GetPrimaryFrameTree().root()->render_manager();
RenderFrameHostImpl* host1 = manager->current_frame_host();
EXPECT_TRUE(host1->IsRenderFrameLive());
WebUIImpl* web_ui1 = host1->web_ui();
EXPECT_TRUE(web_ui1);
// Starts a reload of the WebUI page.
contents()->GetController().Reload(ReloadType::NORMAL, true);
auto reload =
NavigationSimulator::CreateFromPending(contents()->GetController());
reload->ReadyToCommit();
// It should be a same-site navigation reusing the same WebUI.
EXPECT_EQ(web_ui1, host1->web_ui());
EXPECT_FALSE(GetPendingFrameHost(manager));
// Navigate to another WebUI page.
const GURL kUrl(GetWebUIURL("bar/"));
auto navigation =
NavigationSimulator::CreateBrowserInitiated(kUrl, contents());
navigation->ReadyToCommit();
RenderFrameHostImpl* host2 = GetPendingFrameHost(manager);
ASSERT_TRUE(host2);
// The previous navigation should still be ongoing along with the new,
// cross-site one.
EXPECT_EQ(web_ui1, host1->web_ui());
WebUIImpl* web_ui2 = manager->speculative_frame_host()->web_ui();
EXPECT_TRUE(web_ui2);
EXPECT_NE(web_ui2, web_ui1);
EXPECT_NE(host2, host1);
EXPECT_EQ(web_ui2, host2->web_ui());
navigation->Commit();
EXPECT_EQ(host2, manager->current_frame_host());
EXPECT_EQ(web_ui2, host2->web_ui());
EXPECT_FALSE(manager->speculative_frame_host());
EXPECT_FALSE(GetPendingFrameHost(manager));
}
TEST_P(RenderFrameHostManagerTest, CanCommitOrigin) {
if (ShouldCreateNewHostForAllFrames() &&
!ShouldQueueNavigationsWhenPendingCommitRFHExists()) {
// This test involves starting multiple navigations consecutively, which
// might lead to deletion of a pending commit RFH, which will crash when
// RenderDocument is enabled. Skip the test if so, unless navigation
// queueing is enabled.
return;
}
const GURL kUrl("http://a.com/");
const GURL kUrlBar("http://a.com/bar");
NavigationSimulator::NavigateAndCommitFromBrowser(contents(), kUrl);
struct TestCase {
const char* const url;
const char* const origin;
bool mismatch;
} cases[] = {
// Positive case where the two match.
{"http://a.com/foo.html", "http://a.com", false},
// Host mismatches.
{"http://a.com/", "http://b.com", true},
{"http://b.com/", "http://a.com", true},
// Scheme mismatches.
{"file://", "http://a.com", true},
{"https://a.com/", "http://a.com", true},
// about:blank URLs inherit the origin of the context that navigated them.
{"about:blank", "http://a.com", false},
// Unique origin.
{"http://a.com", "null", false},
};
for (const auto& test_case : cases) {
auto navigation = NavigationSimulatorImpl::CreateRendererInitiated(
GURL(test_case.url), main_test_rfh());
url::Origin origin = url::Origin::Create(GURL(test_case.origin));
// Manually control what origin will be committed on the "renderer-side" in
// cases where we want to force the "renderer-side" to mismatch the correct
// origin.
if (test_case.mismatch)
navigation->set_origin(origin);
if (origin.opaque()) {
auto response_headers =
base::MakeRefCounted<net::HttpResponseHeaders>(std::string());
response_headers->SetHeader("Content-Security-Policy", "sandbox");
navigation->SetResponseHeaders(response_headers);
}
navigation->ReadyToCommit();
auto* process = static_cast<MockRenderProcessHost*>(
navigation->GetNavigationHandle()->GetRenderFrameHost()->GetProcess());
int expected_bad_msg_count = process->bad_msg_count();
if (test_case.mismatch)
expected_bad_msg_count++;
navigation->Commit();
EXPECT_EQ(expected_bad_msg_count, process->bad_msg_count())
<< " url:" << test_case.url << " origin:" << test_case.origin
<< " mismatch:" << test_case.mismatch;
}
}
// Tests that the correct intermediary and final navigation states are reached
// when navigating from a renderer that is not live to a WebUI URL.
TEST_P(RenderFrameHostManagerTest, NavigateFromDeadRendererToWebUI) {
RenderFrameHostManager* manager =
contents()->GetPrimaryFrameTree().root()->render_manager();
RenderFrameHostImpl* initial_host = manager->current_frame_host();
ASSERT_TRUE(initial_host);
EXPECT_FALSE(initial_host->IsRenderFrameLive());
// Navigation request.
const GURL kUrl(GetWebUIURL("foo"));
NavigationEntryImpl entry(
nullptr /* instance */, kUrl, Referrer(),
/* initiator_origin= */ std::nullopt,
/* initiator_base_url= */ std::nullopt, std::u16string() /* title */,
ui::PAGE_TRANSITION_TYPED, false /* is_renderer_init */,
nullptr /* blob_url_loader_factory */, false /* is_initial_entry */);
FrameNavigationEntry* frame_entry = entry.root_node()->frame_entry.get();
FrameTreeNode* frame_tree_node =
manager->current_frame_host()->frame_tree_node();
auto& referrer = frame_entry->referrer();
blink::mojom::CommonNavigationParamsPtr common_params =
entry.ConstructCommonNavigationParams(
*frame_entry, nullptr, frame_entry->url(),
blink::mojom::Referrer::New(referrer.url, referrer.policy),
blink::mojom::NavigationType::DIFFERENT_DOCUMENT,
base::TimeTicks::Now() /* actual_navigation_start */,
base::TimeTicks::Now() /* navigation_start */,
base::TimeTicks::Now() /* input_start */);
blink::mojom::CommitNavigationParamsPtr commit_params =
entry.ConstructCommitNavigationParams(
*frame_entry, common_params->url, common_params->method,
entry.GetSubframeUniqueNames(frame_tree_node),
controller().GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
static_cast<NavigationControllerImpl&>(controller())
.GetIndexOfEntry(&entry),
controller().GetLastCommittedEntryIndex(),
controller().GetEntryCount(),
frame_tree_node->current_replication_state().frame_policy,
frame_tree_node->AncestorOrSelfHasCSPEE(),
blink::mojom::SystemEntropy::kNormal,
/*soft_navigation_heuristics_task_id=*/std::nullopt);
std::unique_ptr<NavigationRequest> navigation_request =
NavigationRequest::CreateBrowserInitiated(
frame_tree_node, std::move(common_params), std::move(commit_params),
false /* was_opener_suppressed */, entry.extra_headers(), frame_entry,
&entry, false /* is_form_submission */,
nullptr /* navigation_ui_data */, std::nullopt /* impression */,
false /* is_pdf */
);
frame_tree_node->TakeNavigationRequest(std::move(navigation_request));
// The initial non-live RenderFrameHost should be reused for the WebUI
// navigation, and it should have gotten WebUI bindings by this time.
RenderFrameHostImpl* host = manager->current_frame_host();
ASSERT_TRUE(host);
EXPECT_EQ(host, initial_host);
EXPECT_TRUE(host->IsRenderFrameLive());
WebUIImpl* web_ui = host->web_ui();
EXPECT_TRUE(web_ui);
EXPECT_FALSE(GetPendingFrameHost(manager));
// Prepare to commit, update the navigating RenderFrameHost.
BrowsingContextGroupSwap ignored_bcg_swap_info =
BrowsingContextGroupSwap::CreateDefault();
EXPECT_EQ(
host,
manager
->GetFrameHostForNavigation(
frame_tree_node->navigation_request(), &ignored_bcg_swap_info,
ProcessAllocationContext{ProcessAllocationSource::kTest})
.value());
// No pending RenderFrameHost as the current one should be reused.
EXPECT_FALSE(GetPendingFrameHost(manager));
EXPECT_EQ(web_ui, host->web_ui());
// The RenderFrameHost committed.
DidNavigateFrame(manager, host);
EXPECT_EQ(host, manager->current_frame_host());
EXPECT_FALSE(GetPendingFrameHost(manager));
EXPECT_EQ(web_ui, host->web_ui());
}
// Tests that the correct intermediary and final navigation states are reached
// when navigating same-site between two WebUIs of the same type.
TEST_P(RenderFrameHostManagerTest, NavigateSameSiteBetweenWebUIs) {
NavigationSimulator::NavigateAndCommitFromBrowser(contents(),
GetWebUIURL("foo"));
RenderFrameHostManager* manager =
contents()->GetPrimaryFrameTree().root()->render_manager();
RenderFrameHostImpl* host = manager->current_frame_host();
EXPECT_TRUE(host->IsRenderFrameLive());
WebUIImpl* web_ui = host->web_ui();
EXPECT_TRUE(web_ui);
// Navigation request. No change in the returned WebUI type.
const GURL kUrl(GetWebUIURL("foo/bar"));
auto web_ui_navigation =
NavigationSimulator::CreateBrowserInitiated(kUrl, contents());
web_ui_navigation->Start();
// The current WebUI should still be in place.
EXPECT_EQ(web_ui, host->web_ui());
EXPECT_EQ(ShouldCreateNewHostForAllFrames(), !!GetPendingFrameHost(manager));
// Prepare to commit, update the navigating RenderFrameHost.
web_ui_navigation->ReadyToCommit();
EXPECT_EQ(web_ui, host->web_ui());
EXPECT_EQ(ShouldCreateNewHostForAllFrames(), !!GetPendingFrameHost(manager));
// The RenderFrameHost committed and used the same WebUI object if the
// RenderFrameHost is reused.
web_ui_navigation->Commit();
if (ShouldCreateNewHostForAllFrames()) {
EXPECT_NE(web_ui, manager->current_frame_host()->web_ui());
} else {
EXPECT_EQ(web_ui, manager->current_frame_host()->web_ui());
}
}
// Tests that the correct intermediary and final navigation states are reached
// when navigating cross-site between two different WebUI types.
TEST_P(RenderFrameHostManagerTest, NavigateCrossSiteBetweenWebUIs) {
// Cross-site navigations will always cause the change of the WebUI instance
// but for consistency sake different types will be set for each navigation.
NavigationSimulator::NavigateAndCommitFromBrowser(contents(),
GetWebUIURL("foo"));
RenderFrameHostManager* manager =
contents()->GetPrimaryFrameTree().root()->render_manager();
RenderFrameHostImpl* host = manager->current_frame_host();
EXPECT_TRUE(host->IsRenderFrameLive());
EXPECT_TRUE(host->web_ui());
// Navigate to different WebUI. This will cause the next navigation to
// "chrome://bar" to require a different WebUI than the current one,
// forcing it to be treated as cross-site.
const GURL kUrl(GetWebUIURL("bar"));
auto web_ui_navigation =
NavigationSimulator::CreateBrowserInitiated(kUrl, contents());
web_ui_navigation->Start();
// The current WebUI should still be in place and there should be a new
// active WebUI instance in the speculative RenderFrameHost.
EXPECT_TRUE(manager->current_frame_host()->web_ui());
RenderFrameHostImpl* speculative_host = GetPendingFrameHost(manager);
EXPECT_TRUE(speculative_host);
WebUIImpl* next_web_ui = speculative_host->web_ui();
EXPECT_TRUE(next_web_ui);
EXPECT_NE(next_web_ui, manager->current_frame_host()->web_ui());
// The RenderFrameHost committed.
web_ui_navigation->Commit();
EXPECT_EQ(speculative_host, manager->current_frame_host());
EXPECT_EQ(next_web_ui, manager->current_frame_host()->web_ui());
EXPECT_FALSE(GetPendingFrameHost(manager));
}
// This class intercepts RenderFrameProxyHost creations, and overrides their
// respective blink::mojom::RemoteFrame instances.
class InsecureRequestPolicyProxyObserver
: public RenderFrameProxyHost::TestObserver {
public:
InsecureRequestPolicyProxyObserver() {
RenderFrameProxyHost::SetObserverForTesting(this);
}
~InsecureRequestPolicyProxyObserver() override {
RenderFrameProxyHost::SetObserverForTesting(nullptr);
}
blink::mojom::InsecureRequestPolicy GetRequestPolicy(
RenderFrameProxyHost* proxy_host) {
return remote_frames_[proxy_host]->enforce_insecure_request_policy();
}
private:
// Stub out remote frame mojo binding. Intercepts calls to
// EnforceInsecureRequestPolicy and marks the message as received.
class RemoteFrame : public content::FakeRemoteFrame {
public:
explicit RemoteFrame(RenderFrameProxyHost* render_frame_proxy_host) {
Init(render_frame_proxy_host->BindRemoteFrameReceiverForTesting());
}
void EnforceInsecureRequestPolicy(
blink::mojom::InsecureRequestPolicy policy) override {
enforce_insecure_request_policy_ = policy;
}
blink::mojom::InsecureRequestPolicy enforce_insecure_request_policy() {
return enforce_insecure_request_policy_;
}
private:
blink::mojom::InsecureRequestPolicy enforce_insecure_request_policy_;
};
void OnRemoteFrameBound(RenderFrameProxyHost* proxy_host) override {
remote_frames_[proxy_host] = std::make_unique<RemoteFrame>(proxy_host);
}
std::map<RenderFrameProxyHost*, std::unique_ptr<RemoteFrame>> remote_frames_;
};
// Tests that frame proxies receive updates when a frame's enforcement
// of insecure request policy changes.
TEST_P(RenderFrameHostManagerTestWithSiteIsolation,
ProxiesReceiveInsecureRequestPolicy) {
const GURL kUrl1("http://www.google.test");
const GURL kUrl2("http://www.google2.test");
const GURL kUrl3("http://www.google2.test/foo");
InsecureRequestPolicyProxyObserver observer;
contents()->NavigateAndCommit(kUrl1);
// Create a child frame and navigate it cross-site.
main_test_rfh()->OnCreateChildFrame(
main_test_rfh()->GetProcess()->GetNextRoutingID(),
TestRenderFrameHost::CreateStubFrameRemote(),
TestRenderFrameHost::CreateStubBrowserInterfaceBrokerReceiver(),
TestRenderFrameHost::CreateStubPolicyContainerBindParams(),
TestRenderFrameHost::CreateStubAssociatedInterfaceProviderReceiver(),
blink::mojom::TreeScopeType::kDocument, "frame1", "uniqueName1", false,
blink::LocalFrameToken(), base::UnguessableToken::Create(),
blink::DocumentToken(), blink::FramePolicy(),
blink::mojom::FrameOwnerProperties(),
blink::FrameOwnerElementType::kIframe, ukm::kInvalidSourceId);
FrameTreeNode* root = contents()->GetPrimaryFrameTree().root();
RenderFrameHostManager* child = root->child_at(0)->render_manager();
// Navigate subframe to kUrl2.
NavigationSimulator::NavigateAndCommitFromDocument(
kUrl2, child->current_frame_host());
// Verify that parent and child are in different processes.
TestRenderFrameHost* child_host =
static_cast<TestRenderFrameHost*>(child->current_frame_host());
EXPECT_NE(child_host->GetProcess(), main_test_rfh()->GetProcess());
// Change the parent's enforcement of strict mixed content checking,
// and check that the correct IPC is sent to the child frame's
// process.
EXPECT_EQ(blink::mojom::InsecureRequestPolicy::kLeaveInsecureRequestsAlone,
root->current_replication_state().insecure_request_policy);
main_test_rfh()->DidEnforceInsecureRequestPolicy(
blink::mojom::InsecureRequestPolicy::kBlockAllMixedContent);
RenderFrameProxyHost* proxy_to_child =
root->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(child_host->GetSiteInstance()->group());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(blink::mojom::InsecureRequestPolicy::kBlockAllMixedContent,
observer.GetRequestPolicy(proxy_to_child));
EXPECT_EQ(blink::mojom::InsecureRequestPolicy::kBlockAllMixedContent,
root->current_replication_state().insecure_request_policy);
// Do the same for the child's enforcement. In general, the parent
// needs to know the status of the child's flag in case a grandchild
// is created: if A.com embeds B.com, and B.com enforces strict mixed
// content checking, and B.com adds an iframe to A.com, then the
// A.com process needs to know B.com's flag so that the grandchild
// A.com frame can inherit it.
EXPECT_EQ(
blink::mojom::InsecureRequestPolicy::kLeaveInsecureRequestsAlone,
root->child_at(0)->current_replication_state().insecure_request_policy);
child_host->DidEnforceInsecureRequestPolicy(
blink::mojom::InsecureRequestPolicy::kBlockAllMixedContent);
RenderFrameProxyHost* proxy_to_parent =
child->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(
main_test_rfh()->GetSiteInstance()->group());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(blink::mojom::InsecureRequestPolicy::kBlockAllMixedContent,
observer.GetRequestPolicy(proxy_to_parent));
EXPECT_EQ(
blink::mojom::InsecureRequestPolicy::kBlockAllMixedContent,
root->child_at(0)->current_replication_state().insecure_request_policy);
// Check that the flag for the parent's proxy to the child is reset
// when the child navigates.
main_test_rfh()->GetProcess()->sink().ClearMessages();
NavigationSimulator::NavigateAndCommitFromDocument(kUrl3, child_host);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(blink::mojom::InsecureRequestPolicy::kLeaveInsecureRequestsAlone,
observer.GetRequestPolicy(proxy_to_parent));
EXPECT_EQ(
blink::mojom::InsecureRequestPolicy::kLeaveInsecureRequestsAlone,
root->child_at(0)->current_replication_state().insecure_request_policy);
}
// This class intercepts RenderFrameProxyHost creations, and overrides their
// respective blink::mojom::RemoteFrame instances, so that it can watch the
// start and stop loading states.
class StartStopLoadingProxyObserver
: public RenderFrameProxyHost::TestObserver {
public:
StartStopLoadingProxyObserver() {
RenderFrameProxyHost::SetObserverForTesting(this);
}
~StartStopLoadingProxyObserver() override {
RenderFrameProxyHost::SetObserverForTesting(nullptr);
}
bool IsLoading(RenderFrameProxyHost* proxy) {
return remote_frames_[proxy]->is_loading();
}
private:
class Remote : public content::FakeRemoteFrame {
public:
explicit Remote(RenderFrameProxyHost* proxy) {
Init(proxy->BindRemoteFrameReceiverForTesting());
}
void DidStartLoading() override { is_loading_ = true; }
void DidStopLoading() override { is_loading_ = false; }
bool is_loading() { return is_loading_; }
private:
bool is_loading_ = false;
};
void OnRemoteFrameBound(RenderFrameProxyHost* proxy_host) override {
remote_frames_[proxy_host] = std::make_unique<Remote>(proxy_host);
}
std::map<RenderFrameProxyHost*, std::unique_ptr<Remote>> remote_frames_;
};
// Tests that new frame proxies receive an IPC to update their loading state,
// if they are created for a frame that's currently loading. See
// https://crbug.com/916137.
TEST_P(RenderFrameHostManagerTestWithSiteIsolation,
NewProxyReceivesLoadingState) {
StartStopLoadingProxyObserver proxy_observer;
const GURL kUrl1("http://www.chromium.org");
const GURL kUrl2("http://www.google.com");
const GURL kUrl3("http://foo.com");
// Navigate main frame to |kUrl1| and commit, but don't simulate
// DidStopLoading. The main frame should still be considered loading at this
// point.
auto navigation =
NavigationSimulatorImpl::CreateBrowserInitiated(kUrl1, contents());
navigation->SetKeepLoading(true);
navigation->Commit();
FrameTreeNode* root = contents()->GetPrimaryFrameTree().root();
EXPECT_TRUE(root->IsLoading());
// Create a child frame.
TestRenderFrameHost* child_host = main_test_rfh()->AppendChild("subframe");
// Navigate the child cross-site. Main frame should still be loading after
// this point.
child_host = static_cast<TestRenderFrameHost*>(
NavigationSimulator::NavigateAndCommitFromDocument(kUrl2, child_host));
EXPECT_TRUE(root->IsLoading());
// Verify that parent and child are in different processes, and that there's
// a proxy for the main frame in the child frame's process.
ASSERT_NE(child_host->GetProcess(), main_test_rfh()->GetProcess());
RenderFrameProxyHost* proxy_to_child =
root->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(child_host->GetSiteInstance()->group());
ASSERT_TRUE(proxy_to_child);
ASSERT_EQ(proxy_to_child->GetProcess(), child_host->GetProcess());
base::RunLoop().RunUntilIdle();
// Since the main frame was loading at the time the main frame proxy was
// created in child frame's process, verify that we sent a separate IPC to
// update the proxy's loading state. Note that we'll create two proxies for
// the main frame and subframe, and we're interested in the message for
// the main frame proxy.
EXPECT_TRUE(proxy_observer.IsLoading(proxy_to_child));
// Simulate load stop in the main frame.
navigation->StopLoading();
// Navigate the child to a third site.
child_host = static_cast<TestRenderFrameHost*>(
NavigationSimulator::NavigateAndCommitFromDocument(kUrl3, child_host));
proxy_to_child =
root->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(child_host->GetSiteInstance()->group());
ASSERT_TRUE(proxy_to_child);
ASSERT_EQ(proxy_to_child->GetProcess(), child_host->GetProcess());
base::RunLoop().RunUntilIdle();
// Since this time the main frame wasn't loading at the time |proxy_to_child|
// was created in the process for |kUrl3|, verify that we didn't send any
// extra IPCs to update that proxy's loading state.
EXPECT_FALSE(proxy_observer.IsLoading(proxy_to_child));
}
// Tests that a BeginNavigation IPC from a no longer active RFH in pending
// deletion state is ignored.
TEST_P(RenderFrameHostManagerTest,
BeginNavigationIgnoredWhenInPendingDeletion) {
// When a page enters the BackForwardCache, the RenderFrameHost is not
// deleted and is in BackForwardCache instead of being in pending deletion.
// Disabling to consider this scenario.
contents()->GetController().GetBackForwardCache().DisableForTesting(
BackForwardCache::TEST_REQUIRES_NO_CACHING);
const GURL kUrl1("http://www.google.com");
const GURL kUrl2("http://www.chromium.org");
const GURL kUrl3("http://foo.com");
contents()->NavigateAndCommit(kUrl1);
TestRenderFrameHost* initial_rfh = main_test_rfh();
RenderViewHostDeletedObserver delete_observer(
initial_rfh->GetRenderViewHost());
// Navigate cross-site but don't simulate the swap out ACK. The initial RFH
// should be pending delete.
auto navigation_to_kUrl2 =
NavigationSimulatorImpl::CreateBrowserInitiated(kUrl2, contents());
navigation_to_kUrl2->set_drop_unload_ack(true);
navigation_to_kUrl2->Commit();
EXPECT_NE(initial_rfh, main_test_rfh());
ASSERT_FALSE(delete_observer.deleted());
EXPECT_NE(initial_rfh->lifecycle_state(),
RenderFrameHostImpl::LifecycleStateImpl::kActive);
EXPECT_TRUE(initial_rfh->IsPendingDeletion());
// The initial RFH receives a BeginNavigation IPC. The navigation should not
// start.
auto navigation_to_kUrl3 =
NavigationSimulator::CreateRendererInitiated(kUrl3, initial_rfh);
navigation_to_kUrl3->Start();
EXPECT_FALSE(main_test_rfh()->frame_tree_node()->navigation_request());
}
// Run tests with BackForwardCache.
class RenderFrameHostManagerTestWithBackForwardCache
: public RenderFrameHostManagerTest,
public WebContentsDelegate {
public:
RenderFrameHostManagerTestWithBackForwardCache() {
scoped_feature_list_.InitWithFeaturesAndParameters(
GetDefaultEnabledBackForwardCacheFeaturesForTesting(
/*ignore_outstanding_network_request=*/false),
GetDefaultDisabledBackForwardCacheFeaturesForTesting());
}
bool IsBackForwardCacheSupported(WebContents& web_contents) override {
return true;
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
// Tests that a BeginNavigation IPC from a no longer active RFH in
// BackForwardCache is ignored. This test is a copy of
// "RenderFrameHostManagerTest.BeginNavigationIgnoredWhenInPendingDeletion" with
// BackForwardCache consideration.
TEST_P(RenderFrameHostManagerTestWithBackForwardCache,
BeginNavigationIgnoredWhenInBackForwardCache) {
const GURL kUrl1("http://www.google.com");
const GURL kUrl2("http://www.chromium.org");
const GURL kUrl3("http://foo.com");
contents()->SetDelegate(this);
contents()->NavigateAndCommit(kUrl1);
TestRenderFrameHost* initial_rfh = main_test_rfh();
RenderViewHostDeletedObserver delete_observer(
initial_rfh->GetRenderViewHost());
// Navigate cross-site but don't simulate the swap out ACK. The initial RFH
// should be in BackForwardCache.
auto navigation_to_kUrl2 =
NavigationSimulatorImpl::CreateBrowserInitiated(kUrl2, contents());
navigation_to_kUrl2->set_drop_unload_ack(true);
navigation_to_kUrl2->Commit();
EXPECT_NE(initial_rfh, main_test_rfh());
ASSERT_FALSE(delete_observer.deleted());
EXPECT_NE(initial_rfh->lifecycle_state(),
RenderFrameHostImpl::LifecycleStateImpl::kActive);
EXPECT_TRUE(initial_rfh->IsInBackForwardCache());
// The initial RFH receives a BeginNavigation IPC. The navigation should not
// start as initial RFH is not active.
auto navigation_to_kUrl3 =
NavigationSimulator::CreateRendererInitiated(kUrl3, initial_rfh);
navigation_to_kUrl3->Start();
EXPECT_FALSE(main_test_rfh()->frame_tree_node()->navigation_request());
}
// Check that after a navigation, the final SiteInstance has the correct
// original URL that was used to determine its site URL.
TEST_P(RenderFrameHostManagerTest,
SiteInstanceOriginalURLIsPreservedAfterNavigation) {
const GURL kFooUrl("https://foo.com");
const GURL kOriginalUrl("https://original.com");
const GURL kTranslatedUrl("https://translated.com");
EffectiveURLContentBrowserClient modified_client(
kOriginalUrl, kTranslatedUrl, /* requires_dedicated_process */ true);
ContentBrowserClient* regular_client =
SetBrowserClientForTesting(&modified_client);
NavigationSimulator::NavigateAndCommitFromBrowser(contents(), kFooUrl);
scoped_refptr<SiteInstanceImpl> initial_instance =
main_test_rfh()->GetSiteInstance();
SiteInfo foo_site_info = SiteInfo::CreateForTesting(
initial_instance->GetIsolationContext(), kFooUrl);
if (AreStrictSiteInstancesEnabled()) {
EXPECT_FALSE(initial_instance->IsDefaultSiteInstance());
EXPECT_EQ(kFooUrl, initial_instance->original_url());
EXPECT_EQ(foo_site_info, initial_instance->GetSiteInfo());
} else {
EXPECT_TRUE(initial_instance->IsDefaultSiteInstance());
}
// Simulate a browser-initiated navigation to an app URL, which should swap
// processes and create a new SiteInstance in a new BrowsingInstance.
// This new SiteInstance should have correct |original_url()| and a SiteInfo
// that's based on it.
NavigationSimulator::NavigateAndCommitFromBrowser(contents(), kOriginalUrl);
EXPECT_NE(initial_instance.get(), main_test_rfh()->GetSiteInstance());
EXPECT_FALSE(initial_instance->IsRelatedSiteInstance(
main_test_rfh()->GetSiteInstance()));
EXPECT_EQ(kOriginalUrl, main_test_rfh()->GetSiteInstance()->original_url());
SiteInfo expected_site_info = SiteInfo::CreateForTesting(
main_test_rfh()->GetSiteInstance()->GetIsolationContext(), kOriginalUrl);
EXPECT_EQ(expected_site_info,
main_test_rfh()->GetSiteInstance()->GetSiteInfo());
EXPECT_NE(foo_site_info, main_test_rfh()->GetSiteInstance()->GetSiteInfo());
SetBrowserClientForTesting(regular_client);
}
class AdTaggingSimulator : public WebContentsObserver {
public:
explicit AdTaggingSimulator(const std::set<GURL>& ad_urls,
WebContents* web_contents)
: WebContentsObserver(web_contents), ad_urls_(ad_urls) {}
void ReadyToCommitNavigation(NavigationHandle* navigation_handle) override {
auto it = ad_urls_.find(navigation_handle->GetURL());
navigation_handle->GetRenderFrameHost()->UpdateIsAdFrame(it !=
ad_urls_.end());
}
void SimulateOnFrameIsAd(RenderFrameHost* rfh) { rfh->UpdateIsAdFrame(true); }
private:
std::set<GURL> ad_urls_;
};
class AdStatusInterceptingRemoteFrame : public content::FakeRemoteFrame {
public:
void SetReplicatedIsAdFrame(bool is_ad_frame) override {
is_ad_frame_ = is_ad_frame;
}
// These methods reset state back to default when they are called.
bool LastAdFrame() {
bool is_ad_frame = is_ad_frame_;
is_ad_frame_ = false;
return is_ad_frame;
}
private:
bool is_ad_frame_ = false;
};
class RenderFrameHostManagerAdTaggingSignalTest
: public RenderFrameHostManagerTest,
public RenderFrameProxyHost::TestObserver {
public:
RenderFrameHostManagerAdTaggingSignalTest() {
RenderFrameProxyHost::SetObserverForTesting(this);
}
~RenderFrameHostManagerAdTaggingSignalTest() override {
RenderFrameProxyHost::SetObserverForTesting(nullptr);
}
void OnRemoteFrameBound(RenderFrameProxyHost* proxy_host) override {
auto fake_remote_frame =
std::make_unique<AdStatusInterceptingRemoteFrame>();
fake_remote_frame->Init(proxy_host->BindRemoteFrameReceiverForTesting());
// TODO(yaoxia): when a proxy host is deleted, remove the corresponding map
// entry.
proxy_map_[proxy_host] = std::move(fake_remote_frame);
if (proxy_host->frame_tree_node()
->current_replication_state()
.is_ad_frame) {
ad_frames_on_proxy_created_.insert(proxy_host);
}
}
void ExpectAdSubframeSignalForFrameProxy(RenderFrameProxyHost* proxy_host,
bool expect_is_ad_frame) {
base::RunLoop().RunUntilIdle();
auto it = proxy_map_.find(proxy_host);
EXPECT_TRUE(it != proxy_map_.end());
AdStatusInterceptingRemoteFrame* remote_frame = it->second.get();
EXPECT_EQ(expect_is_ad_frame, remote_frame->LastAdFrame());
}
void ExpectAdStatusOnFrameProxyCreated(RenderFrameProxyHost* proxy_host) {
EXPECT_TRUE(ad_frames_on_proxy_created_.find(proxy_host) !=
ad_frames_on_proxy_created_.end());
}
void AppendChildToFrame(const std::string& frame_name,
const GURL& url,
RenderFrameHost* rfh) {
RenderFrameHost* subframe_host =
RenderFrameHostTester::For(rfh)->AppendChild(frame_name);
if (url.is_valid())
NavigationSimulator::NavigateAndCommitFromDocument(url, subframe_host);
}
RenderFrameProxyHost* GetProxyHost(FrameTreeNode* proxy_node,
FrameTreeNode* proxy_to_node) {
return proxy_node->current_frame_host()
->browsing_context_state()
->GetRenderFrameProxyHost(
proxy_to_node->current_frame_host()->GetSiteInstance()->group());
}
private:
// The set of proxies that when created, the replication state of that frame
// indicates it's an ad.
std::set<raw_ptr<RenderFrameProxyHost, SetExperimental>>
ad_frames_on_proxy_created_;
std::map<RenderFrameProxyHost*,
std::unique_ptr<AdStatusInterceptingRemoteFrame>>
proxy_map_;
};
// Test that when the proxy host is created for the local child frame to be
// swapped out (which occurs before UnfreezableFrameMsg_SwapOut IPC was sent),
// the frame replication state should already have the ad status set.
TEST_P(RenderFrameHostManagerAdTaggingSignalTest,
AdStatusForLocalChildFrameToBeSwappedOut) {
if (!AreAllSitesIsolatedForTesting())
return;
const GURL kUrlA("http://a.com/");
const GURL kUrlB("http://b.com/");
std::set<GURL> ad_urls = {kUrlB};
AdTaggingSimulator ad_tagging_simulator(ad_urls, contents());
contents()->NavigateAndCommit(kUrlA);
AppendChildToFrame("name", kUrlB, web_contents()->GetPrimaryMainFrame());
FrameTreeNode* subframe_node =
contents()->GetPrimaryFrameTree().root()->child_at(0);
ExpectAdStatusOnFrameProxyCreated(
subframe_node->render_manager()->GetProxyToParent());
EXPECT_TRUE(subframe_node->current_replication_state().is_ad_frame);
}
// A page with top frame A that has subframes B and A1. A1 is an ad iframe that
// does not commit. We expect that the proxy of A1 in B's process will receive
// an ad tagging signal.
TEST_P(RenderFrameHostManagerAdTaggingSignalTest,
AdTagSignalForFrameProxyOfFrameThatDoesNotCommit) {
if (!AreAllSitesIsolatedForTesting())
return;
const GURL kUrlA("http://a.com/");
const GURL kUrlB("http://b.com/");
AdTaggingSimulator ad_tagging_simulator({}, contents());
contents()->NavigateAndCommit(kUrlA);
EXPECT_FALSE(contents()
->GetPrimaryFrameTree()
.root()
->current_replication_state()
.is_ad_frame);
AppendChildToFrame("subframe_b", kUrlB,
web_contents()->GetPrimaryMainFrame());
AppendChildToFrame("subframe_a1", GURL(),
web_contents()->GetPrimaryMainFrame());
FrameTreeNode* top_frame_node_a = contents()->GetPrimaryFrameTree().root();
FrameTreeNode* subframe_node_b = top_frame_node_a->child_at(0);
FrameTreeNode* subframe_node_a1 = top_frame_node_a->child_at(1);
ad_tagging_simulator.SimulateOnFrameIsAd(
subframe_node_a1->current_frame_host());
RenderFrameProxyHost* proxy_a1_to_b =
GetProxyHost(subframe_node_a1, subframe_node_b);
EXPECT_TRUE(subframe_node_a1->current_replication_state().is_ad_frame);
ExpectAdSubframeSignalForFrameProxy(proxy_a1_to_b, true);
}
// A page with top frame A that has subframes B and C. C is then navigated to an
// ad frame D. We expect that both the proxy of D in A's process and the proxy
// of D in B's process will receive an ad tagging signal.
TEST_P(RenderFrameHostManagerAdTaggingSignalTest,
AdTagSignalForFrameProxyOfNewFrame) {
if (!AreAllSitesIsolatedForTesting())
return;
const GURL kUrlA("http://a.com/");
const GURL kUrlB("http://b.com/");
const GURL kUrlC("http://c.com/");
const GURL kUrlD("http://d.com/");
std::set<GURL> ad_urls = {kUrlD};
AdTaggingSimulator ad_tagging_simulator(ad_urls, contents());
contents()->NavigateAndCommit(kUrlA);
EXPECT_FALSE(contents()
->GetPrimaryFrameTree()
.root()
->current_replication_state()
.is_ad_frame);
AppendChildToFrame("subframe_b", kUrlB,
web_contents()->GetPrimaryMainFrame());
AppendChildToFrame("subframe_c", kUrlC,
web_contents()->GetPrimaryMainFrame());
FrameTreeNode* top_frame_node_a = contents()->GetPrimaryFrameTree().root();
FrameTreeNode* subframe_node_b = top_frame_node_a->child_at(0);
FrameTreeNode* subframe_node_c = top_frame_node_a->child_at(1);
EXPECT_FALSE(subframe_node_b->current_replication_state().is_ad_frame);
EXPECT_FALSE(subframe_node_c->current_replication_state().is_ad_frame);
RenderFrameProxyHost* proxy_c_to_a =
GetProxyHost(subframe_node_c, top_frame_node_a);
RenderFrameProxyHost* proxy_c_to_b =
GetProxyHost(subframe_node_c, subframe_node_b);
RenderFrameProxyHost* proxy_b_to_a =
GetProxyHost(subframe_node_b, top_frame_node_a);
RenderFrameProxyHost* proxy_b_to_c =
GetProxyHost(subframe_node_b, subframe_node_c);
RenderFrameProxyHost* proxy_a_to_b =
GetProxyHost(top_frame_node_a, subframe_node_b);
RenderFrameProxyHost* proxy_a_to_c =
GetProxyHost(top_frame_node_a, subframe_node_c);
NavigationSimulator::NavigateAndCommitFromDocument(
kUrlD, subframe_node_c->current_frame_host());
EXPECT_TRUE(subframe_node_c->current_replication_state().is_ad_frame);
ExpectAdSubframeSignalForFrameProxy(proxy_c_to_a, true);
ExpectAdSubframeSignalForFrameProxy(proxy_c_to_b, true);
ExpectAdSubframeSignalForFrameProxy(proxy_b_to_a, false);
ExpectAdSubframeSignalForFrameProxy(proxy_b_to_c, false);
ExpectAdSubframeSignalForFrameProxy(proxy_a_to_b, false);
ExpectAdSubframeSignalForFrameProxy(proxy_a_to_c, false);
}
// A page with top frame A that has an ad subframe B. Frame C is then created in
// A. We expect that when the proxy host of B in C's process is created, the
// frame's replication status already has the ad bit set, which will be
// propagated to the renderer side later.
TEST_P(RenderFrameHostManagerAdTaggingSignalTest,
AdStatusForFrameProxyOfExistingFrameToNewFrame) {
if (!AreAllSitesIsolatedForTesting())
return;
const GURL kUrlA("http://a.com/");
const GURL kUrlB("http://b.com/");
const GURL kUrlC("http://c.com/");
std::set<GURL> ad_urls = {kUrlB};
AdTaggingSimulator ad_tagging_simulator(ad_urls, contents());
contents()->NavigateAndCommit(kUrlA);
AppendChildToFrame("subframe_b", kUrlB,
web_contents()->GetPrimaryMainFrame());
AppendChildToFrame("subframe_c", kUrlC,
web_contents()->GetPrimaryMainFrame());
FrameTreeNode* subframe_node_b =
contents()->GetPrimaryFrameTree().root()->child_at(0);
FrameTreeNode* subframe_node_c =
contents()->GetPrimaryFrameTree().root()->child_at(1);
RenderFrameProxyHost* proxy_b_to_c =
GetProxyHost(subframe_node_b, subframe_node_c);
ExpectAdStatusOnFrameProxyCreated(proxy_b_to_c);
}
// Test a A(B(C)) setup where B and C are ads. The creation of C will trigger
// an ad tagging signal for the proxy of C in the process of A.
TEST_P(RenderFrameHostManagerAdTaggingSignalTest, RemoteGrandchildAdTagSignal) {
if (!AreAllSitesIsolatedForTesting())
return;
const GURL kUrlA("http://a.com/");
const GURL kUrlB("http://b.com/");
const GURL kUrlC("http://c.com/");
std::set<GURL> ad_urls = {kUrlB, kUrlC};
AdTaggingSimulator ad_tagging_simulator(ad_urls, contents());
contents()->NavigateAndCommit(kUrlA);
RenderFrameHost* subframe_host =
RenderFrameHostTester::For(web_contents()->GetPrimaryMainFrame())
->AppendChild("subframe_name");
auto navigation_simulator =
NavigationSimulator::CreateRendererInitiated(kUrlB, subframe_host);
navigation_simulator->Start();
navigation_simulator->Commit();
RenderFrameHost* grandchild_host =
RenderFrameHostTester::For(
navigation_simulator->GetFinalRenderFrameHost())
->AppendChild("subframe_name");
FrameTreeNode* top_frame_node = contents()->GetPrimaryFrameTree().root();
FrameTreeNode* subframe_node = top_frame_node->child_at(0);
FrameTreeNode* grandchild_node = subframe_node->child_at(0);
RenderFrameProxyHost* proxy_to_main_frame =
GetProxyHost(grandchild_node, top_frame_node);
NavigationSimulator::NavigateAndCommitFromDocument(kUrlC, grandchild_host);
EXPECT_TRUE(subframe_node->current_replication_state().is_ad_frame);
EXPECT_TRUE(grandchild_node->current_replication_state().is_ad_frame);
ExpectAdSubframeSignalForFrameProxy(proxy_to_main_frame, true);
}
INSTANTIATE_TEST_SUITE_P(All,
RenderFrameHostManagerTest,
testing::ValuesIn(RenderDocumentFeatureLevelValues()));
INSTANTIATE_TEST_SUITE_P(All,
RenderFrameHostManagerTestWithSiteIsolation,
testing::ValuesIn(RenderDocumentFeatureLevelValues()));
INSTANTIATE_TEST_SUITE_P(All,
RenderFrameHostManagerAdTaggingSignalTest,
testing::ValuesIn(RenderDocumentFeatureLevelValues()));
INSTANTIATE_TEST_SUITE_P(All,
RenderFrameHostManagerTestWithBackForwardCache,
testing::ValuesIn(RenderDocumentFeatureLevelValues()));
} // namespace content
|