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
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/dom/CanonicalBrowsingContext.h"
#include "ContentAnalysis.h"
#include "ErrorList.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/Components.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/EventForwards.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/dom/BrowserParent.h"
#include "mozilla/dom/BrowsingContextBinding.h"
#include "mozilla/dom/BrowsingContextGroup.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/EventTarget.h"
#include "mozilla/dom/Navigation.h"
#include "mozilla/dom/NavigationUtils.h"
#include "mozilla/dom/PBrowserParent.h"
#include "mozilla/dom/PBackgroundSessionStorageCache.h"
#include "mozilla/dom/PWindowGlobalParent.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/Promise-inl.h"
#include "mozilla/dom/WindowGlobalParent.h"
#include "mozilla/dom/ContentProcessManager.h"
#include "mozilla/dom/MediaController.h"
#include "mozilla/dom/MediaControlService.h"
#include "mozilla/dom/ContentPlaybackController.h"
#include "mozilla/dom/SessionStorageManager.h"
#include "mozilla/ipc/ProtocolUtils.h"
#include "mozilla/layers/CompositorBridgeChild.h"
#ifdef NS_PRINTING
# include "mozilla/layout/RemotePrintJobParent.h"
#endif
#include "mozilla/net/DocumentLoadListener.h"
#include "mozilla/NullPrincipal.h"
#include "mozilla/StaticPrefs_browser.h"
#include "mozilla/StaticPrefs_docshell.h"
#include "mozilla/StaticPrefs_fission.h"
#include "mozilla/StaticPrefs_security.h"
#include "mozilla/glean/DomMetrics.h"
#include "nsILayoutHistoryState.h"
#include "nsIParentalControlsService.h"
#include "nsIPrintSettings.h"
#include "nsIPrintSettingsService.h"
#include "nsISupports.h"
#include "nsIWebNavigation.h"
#include "nsDocShell.h"
#include "nsFrameLoader.h"
#include "nsFrameLoaderOwner.h"
#include "nsGlobalWindowOuter.h"
#include "nsIContentAnalysis.h"
#include "nsIWebBrowserChrome.h"
#include "nsIXULRuntime.h"
#include "nsNetUtil.h"
#include "nsSHistory.h"
#include "nsSecureBrowserUI.h"
#include "nsQueryObject.h"
#include "nsBrowserStatusFilter.h"
#include "nsIBrowser.h"
#include "nsTHashSet.h"
#include "nsISessionStoreFunctions.h"
#include "nsIXPConnect.h"
#include "nsImportModule.h"
#include "UnitTransforms.h"
using namespace mozilla::ipc;
extern mozilla::LazyLogModule gAutoplayPermissionLog;
extern mozilla::LazyLogModule gNavigationAPILog;
extern mozilla::LazyLogModule gSHLog;
extern mozilla::LazyLogModule gSHIPBFCacheLog;
#define AUTOPLAY_LOG(msg, ...) \
MOZ_LOG(gAutoplayPermissionLog, LogLevel::Debug, (msg, ##__VA_ARGS__))
static mozilla::LazyLogModule sPBContext("PBContext");
// Global count of canonical browsing contexts with the private attribute set
static uint32_t gNumberOfPrivateContexts = 0;
static void IncreasePrivateCount() {
gNumberOfPrivateContexts++;
MOZ_LOG(sPBContext, mozilla::LogLevel::Debug,
("%s: Private browsing context count %d -> %d", __func__,
gNumberOfPrivateContexts - 1, gNumberOfPrivateContexts));
if (gNumberOfPrivateContexts > 1) {
return;
}
static bool sHasSeenPrivateContext = false;
if (!sHasSeenPrivateContext) {
sHasSeenPrivateContext = true;
mozilla::glean::dom_parentprocess::private_window_used.Set(true);
}
}
static void DecreasePrivateCount() {
MOZ_ASSERT(gNumberOfPrivateContexts > 0);
gNumberOfPrivateContexts--;
MOZ_LOG(sPBContext, mozilla::LogLevel::Debug,
("%s: Private browsing context count %d -> %d", __func__,
gNumberOfPrivateContexts + 1, gNumberOfPrivateContexts));
if (!gNumberOfPrivateContexts &&
!mozilla::StaticPrefs::browser_privatebrowsing_autostart()) {
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
if (observerService) {
MOZ_LOG(sPBContext, mozilla::LogLevel::Debug,
("%s: last-pb-context-exited fired", __func__));
observerService->NotifyObservers(nullptr, "last-pb-context-exited",
nullptr);
}
}
}
namespace mozilla::dom {
extern mozilla::LazyLogModule gUserInteractionPRLog;
#define USER_ACTIVATION_LOG(msg, ...) \
MOZ_LOG(gUserInteractionPRLog, LogLevel::Debug, (msg, ##__VA_ARGS__))
CanonicalBrowsingContext::CanonicalBrowsingContext(WindowContext* aParentWindow,
BrowsingContextGroup* aGroup,
uint64_t aBrowsingContextId,
uint64_t aOwnerProcessId,
uint64_t aEmbedderProcessId,
BrowsingContext::Type aType,
FieldValues&& aInit)
: BrowsingContext(aParentWindow, aGroup, aBrowsingContextId, aType,
std::move(aInit)),
mProcessId(aOwnerProcessId),
mEmbedderProcessId(aEmbedderProcessId),
mPermanentKey(JS::NullValue()) {
// You are only ever allowed to create CanonicalBrowsingContexts in the
// parent process.
MOZ_RELEASE_ASSERT(XRE_IsParentProcess());
// The initial URI in a BrowsingContext is always "about:blank".
MOZ_ALWAYS_SUCCEEDS(
NS_NewURI(getter_AddRefs(mCurrentRemoteURI), "about:blank"));
mozilla::HoldJSObjects(this);
}
CanonicalBrowsingContext::~CanonicalBrowsingContext() {
mPermanentKey.setNull();
mozilla::DropJSObjects(this);
if (mSessionHistory) {
mSessionHistory->SetBrowsingContext(nullptr);
}
mActiveEntryList = nullptr;
}
/* static */
already_AddRefed<CanonicalBrowsingContext> CanonicalBrowsingContext::Get(
uint64_t aId) {
MOZ_RELEASE_ASSERT(XRE_IsParentProcess());
return BrowsingContext::Get(aId).downcast<CanonicalBrowsingContext>();
}
/* static */
CanonicalBrowsingContext* CanonicalBrowsingContext::Cast(
BrowsingContext* aContext) {
MOZ_RELEASE_ASSERT(XRE_IsParentProcess());
return static_cast<CanonicalBrowsingContext*>(aContext);
}
/* static */
const CanonicalBrowsingContext* CanonicalBrowsingContext::Cast(
const BrowsingContext* aContext) {
MOZ_RELEASE_ASSERT(XRE_IsParentProcess());
return static_cast<const CanonicalBrowsingContext*>(aContext);
}
already_AddRefed<CanonicalBrowsingContext> CanonicalBrowsingContext::Cast(
already_AddRefed<BrowsingContext>&& aContext) {
MOZ_RELEASE_ASSERT(XRE_IsParentProcess());
return aContext.downcast<CanonicalBrowsingContext>();
}
ContentParent* CanonicalBrowsingContext::GetContentParent() const {
if (mProcessId == 0) {
return nullptr;
}
ContentProcessManager* cpm = ContentProcessManager::GetSingleton();
if (!cpm) {
return nullptr;
}
return cpm->GetContentProcessById(ContentParentId(mProcessId));
}
void CanonicalBrowsingContext::GetCurrentRemoteType(nsACString& aRemoteType,
ErrorResult& aRv) const {
// If we're in the parent process, dump out the void string.
if (mProcessId == 0) {
aRemoteType = NOT_REMOTE_TYPE;
return;
}
ContentParent* cp = GetContentParent();
if (!cp) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return;
}
aRemoteType = cp->GetRemoteType();
}
void CanonicalBrowsingContext::SetOwnerProcessId(uint64_t aProcessId) {
MOZ_LOG(GetLog(), LogLevel::Debug,
("SetOwnerProcessId for 0x%08" PRIx64 " (0x%08" PRIx64
" -> 0x%08" PRIx64 ")",
Id(), mProcessId, aProcessId));
mProcessId = aProcessId;
}
nsISecureBrowserUI* CanonicalBrowsingContext::GetSecureBrowserUI() {
if (!IsTop()) {
return nullptr;
}
if (!mSecureBrowserUI) {
mSecureBrowserUI = new nsSecureBrowserUI(this);
}
return mSecureBrowserUI;
}
void CanonicalBrowsingContext::ReplacedBy(
CanonicalBrowsingContext* aNewContext,
const NavigationIsolationOptions& aRemotenessOptions) {
MOZ_ASSERT(!aNewContext->mWebProgress);
MOZ_ASSERT(!aNewContext->mSessionHistory);
MOZ_ASSERT(IsTop() && aNewContext->IsTop());
mIsReplaced = true;
aNewContext->mIsReplaced = false;
if (mStatusFilter) {
mStatusFilter->RemoveProgressListener(mDocShellProgressBridge);
mStatusFilter = nullptr;
}
mWebProgress->ContextReplaced(aNewContext);
aNewContext->mWebProgress = std::move(mWebProgress);
// Use the Transaction for the fields which need to be updated whether or not
// the new context has been attached before.
// SetWithoutSyncing can be used if context hasn't been attached.
Transaction txn;
txn.SetBrowserId(GetBrowserId());
txn.SetIsAppTab(GetIsAppTab());
txn.SetIsCaptivePortalTab(GetIsCaptivePortalTab());
txn.SetHasSiblings(GetHasSiblings());
txn.SetTopLevelCreatedByWebContent(GetTopLevelCreatedByWebContent());
txn.SetHistoryID(GetHistoryID());
txn.SetExplicitActive(GetExplicitActive());
txn.SetEmbedderColorSchemes(GetEmbedderColorSchemes());
txn.SetHasRestoreData(GetHasRestoreData());
txn.SetShouldDelayMediaFromStart(GetShouldDelayMediaFromStart());
txn.SetForceOffline(GetForceOffline());
txn.SetTopInnerSizeForRFP(GetTopInnerSizeForRFP());
txn.SetIPAddressSpace(GetIPAddressSpace());
txn.SetParentalControlsEnabled(GetParentalControlsEnabled());
if (!GetLanguageOverride().IsEmpty()) {
// Reapply language override to update the corresponding realm.
txn.SetLanguageOverride(GetLanguageOverride());
}
if (!GetTimezoneOverride().IsEmpty()) {
// Reapply timezone override to update the corresponding realm.
txn.SetTimezoneOverride(GetTimezoneOverride());
}
// Propagate some settings on BrowsingContext replacement so they're not lost
// on bfcached navigations. These are important for GeckoView (see bug
// 1781936).
txn.SetAllowJavascript(GetAllowJavascript());
txn.SetForceEnableTrackingProtection(GetForceEnableTrackingProtection());
txn.SetUserAgentOverride(GetUserAgentOverride());
txn.SetSuspendMediaWhenInactive(GetSuspendMediaWhenInactive());
txn.SetDisplayMode(GetDisplayMode());
txn.SetForceDesktopViewport(GetForceDesktopViewport());
txn.SetIsUnderHiddenEmbedderElement(GetIsUnderHiddenEmbedderElement());
// When using site-specific zoom, we let the frontend manage the zoom level
// of BFCache'd contexts. Overriding those zoom levels can cause weirdness
// like bug 1846141. We always copy to new contexts to avoid bug 1914149.
if (!aNewContext->EverAttached() ||
!StaticPrefs::browser_zoom_siteSpecific()) {
txn.SetFullZoom(GetFullZoom());
txn.SetTextZoom(GetTextZoom());
}
// Propagate the default load flags so that the TRR mode flags are forwarded
// to the new browsing context. See bug 1828643.
txn.SetDefaultLoadFlags(GetDefaultLoadFlags());
// As this is a different BrowsingContext, set InitialSandboxFlags to the
// current flags in the new context so that they also apply to any initial
// about:blank documents created in it.
txn.SetSandboxFlags(GetSandboxFlags());
txn.SetInitialSandboxFlags(GetSandboxFlags());
txn.SetTargetTopLevelLinkClicksToBlankInternal(
TargetTopLevelLinkClicksToBlank());
if (aNewContext->EverAttached()) {
MOZ_ALWAYS_SUCCEEDS(txn.Commit(aNewContext));
} else {
txn.CommitWithoutSyncing(aNewContext);
}
aNewContext->mRestoreState = mRestoreState.forget();
Transaction selfTxn;
selfTxn.SetHasRestoreData(false);
selfTxn.SetExplicitActive(ExplicitActiveStatus::Inactive);
MOZ_ALWAYS_SUCCEEDS(selfTxn.Commit(this));
// XXXBFCache name handling is still a bit broken in Fission in general,
// at least in case name should be cleared.
if (aRemotenessOptions.mTryUseBFCache) {
MOZ_ASSERT(!aNewContext->EverAttached());
aNewContext->mFields.SetWithoutSyncing<IDX_Name>(GetName());
// We don't copy over HasLoadedNonInitialDocument here, we'll actually end
// up loading a new initial document at this point, before the real load.
// The real load will then end up setting HasLoadedNonInitialDocument to
// true.
}
if (mSessionHistory) {
mSessionHistory->SetBrowsingContext(aNewContext);
// At this point we will be creating a new ChildSHistory in the child.
// That means that the child's epoch will be reset, so it makes sense to
// reset the epoch in the parent too.
mSessionHistory->SetEpoch(0, Nothing());
mSessionHistory.swap(aNewContext->mSessionHistory);
RefPtr<ChildSHistory> childSHistory = ForgetChildSHistory();
aNewContext->SetChildSHistory(childSHistory);
}
BackgroundSessionStorageManager::PropagateManager(Id(), aNewContext->Id());
// Transfer the ownership of the priority active status from the old context
// to the new context.
aNewContext->mPriorityActive = mPriorityActive;
mPriorityActive = false;
MOZ_ASSERT(aNewContext->mLoadingEntries.IsEmpty());
mLoadingEntries.SwapElements(aNewContext->mLoadingEntries);
MOZ_ASSERT(!aNewContext->mActiveEntry);
mActiveEntry.swap(aNewContext->mActiveEntry);
if (Navigation::IsAPIEnabled()) {
MOZ_ASSERT(!aNewContext->mActiveEntryList);
aNewContext->mActiveEntryList = std::move(mActiveEntryList);
}
aNewContext->mPermanentKey = mPermanentKey;
mPermanentKey.setNull();
}
void CanonicalBrowsingContext::UpdateSecurityState() {
if (mSecureBrowserUI) {
mSecureBrowserUI->RecomputeSecurityFlags();
}
}
void CanonicalBrowsingContext::GetWindowGlobals(
nsTArray<RefPtr<WindowGlobalParent>>& aWindows) {
aWindows.SetCapacity(GetWindowContexts().Length());
for (auto& window : GetWindowContexts()) {
aWindows.AppendElement(static_cast<WindowGlobalParent*>(window.get()));
}
}
WindowGlobalParent* CanonicalBrowsingContext::GetCurrentWindowGlobal() const {
return static_cast<WindowGlobalParent*>(GetCurrentWindowContext());
}
WindowGlobalParent* CanonicalBrowsingContext::GetParentWindowContext() {
return static_cast<WindowGlobalParent*>(
BrowsingContext::GetParentWindowContext());
}
WindowGlobalParent* CanonicalBrowsingContext::GetTopWindowContext() {
return static_cast<WindowGlobalParent*>(
BrowsingContext::GetTopWindowContext());
}
already_AddRefed<nsIWidget>
CanonicalBrowsingContext::GetParentProcessWidgetContaining() {
// If our document is loaded in-process, such as chrome documents, get the
// widget directly from our outer window. Otherwise, try to get the widget
// from the toplevel content's browser's element.
nsCOMPtr<nsIWidget> widget;
if (nsGlobalWindowOuter* window = nsGlobalWindowOuter::Cast(GetDOMWindow())) {
widget = window->GetNearestWidget();
} else if (Element* topEmbedder = Top()->GetEmbedderElement()) {
widget = nsContentUtils::WidgetForContent(topEmbedder);
if (!widget) {
widget = nsContentUtils::WidgetForDocument(topEmbedder->OwnerDoc());
}
}
if (widget) {
widget = widget->GetTopLevelWidget();
}
return widget.forget();
}
already_AddRefed<nsIBrowserDOMWindow>
CanonicalBrowsingContext::GetBrowserDOMWindow() {
RefPtr<CanonicalBrowsingContext> chromeTop = TopCrossChromeBoundary();
nsGlobalWindowOuter* topWin;
if ((topWin = nsGlobalWindowOuter::Cast(chromeTop->GetDOMWindow())) &&
topWin->IsChromeWindow()) {
return do_AddRef(topWin->GetBrowserDOMWindow());
}
return nullptr;
}
already_AddRefed<WindowGlobalParent>
CanonicalBrowsingContext::GetEmbedderWindowGlobal() const {
uint64_t windowId = GetEmbedderInnerWindowId();
if (windowId == 0) {
return nullptr;
}
return WindowGlobalParent::GetByInnerWindowId(windowId);
}
CanonicalBrowsingContext*
CanonicalBrowsingContext::GetParentCrossChromeBoundary() {
if (GetParent()) {
return Cast(GetParent());
}
if (auto* embedder = GetEmbedderElement()) {
return Cast(embedder->OwnerDoc()->GetBrowsingContext());
}
return nullptr;
}
CanonicalBrowsingContext* CanonicalBrowsingContext::TopCrossChromeBoundary() {
CanonicalBrowsingContext* bc = this;
while (auto* parent = bc->GetParentCrossChromeBoundary()) {
bc = parent;
}
return bc;
}
Nullable<WindowProxyHolder> CanonicalBrowsingContext::GetTopChromeWindow() {
RefPtr<CanonicalBrowsingContext> bc = TopCrossChromeBoundary();
if (bc->IsChrome()) {
return WindowProxyHolder(bc.forget());
}
return nullptr;
}
nsISHistory* CanonicalBrowsingContext::GetSessionHistory() {
if (!IsTop()) {
return Cast(Top())->GetSessionHistory();
}
// Check GetChildSessionHistory() to make sure that this BrowsingContext has
// session history enabled.
if (!mSessionHistory && GetChildSessionHistory()) {
mSessionHistory = new nsSHistory(this);
}
return mSessionHistory;
}
SessionHistoryEntry* CanonicalBrowsingContext::GetActiveSessionHistoryEntry() {
return mActiveEntry;
}
void CanonicalBrowsingContext::SetActiveSessionHistoryEntryFromBFCache(
SessionHistoryEntry* aEntry) {
mActiveEntry = aEntry;
auto* activeEntries = GetActiveEntries();
if (Navigation::IsAPIEnabled() && activeEntries) {
if (StaticPrefs::dom_navigation_api_strict_enabled()) {
MOZ_DIAGNOSTIC_ASSERT(!aEntry || activeEntries->contains(aEntry));
MOZ_DIAGNOSTIC_ASSERT(aEntry || activeEntries->isEmpty());
} else {
MOZ_ASSERT(!aEntry || activeEntries->contains(aEntry));
MOZ_ASSERT(aEntry || activeEntries->isEmpty());
}
}
}
bool CanonicalBrowsingContext::HasHistoryEntry(nsISHEntry* aEntry) {
// XXX Should we check also loading entries?
return aEntry && mActiveEntry == aEntry;
}
void CanonicalBrowsingContext::SwapHistoryEntries(nsISHEntry* aOldEntry,
nsISHEntry* aNewEntry) {
// XXX Should we check also loading entries?
if (mActiveEntry != aOldEntry) {
return;
}
nsCOMPtr<SessionHistoryEntry> newEntry = do_QueryInterface(aNewEntry);
auto* activeEntries = GetActiveEntries();
MOZ_LOG(gSHLog, LogLevel::Verbose,
("Swapping History Entries: mActiveEntry=%p, aNewEntry=%p. "
"Is in list? mActiveEntry %s, aNewEntry %s. "
"Is aNewEntry in current mActiveEntryList? %s.",
mActiveEntry.get(), aNewEntry,
mActiveEntry && mActiveEntry->isInList() ? "yes" : "no",
newEntry && newEntry->isInList() ? "yes" : "no",
activeEntries->contains(newEntry) ? "yes" : "no"));
if (!newEntry) {
activeEntries->clear();
mActiveEntry = nullptr;
return;
}
if (Navigation::IsAPIEnabled() && mActiveEntry->isInList()) {
RefPtr beforeOldEntry = mActiveEntry->removeAndGetPrevious();
if (beforeOldEntry != newEntry) {
if (newEntry->isInList()) {
newEntry->setNext(mActiveEntry);
newEntry->remove();
}
if (beforeOldEntry) {
beforeOldEntry->setNext(newEntry);
} else {
activeEntries->insertFront(newEntry);
}
} else {
newEntry->setPrevious(mActiveEntry);
}
}
mActiveEntry = newEntry.forget();
}
void CanonicalBrowsingContext::AddLoadingSessionHistoryEntry(
uint64_t aLoadId, SessionHistoryEntry* aEntry) {
(void)SetHistoryID(aEntry->DocshellID());
mLoadingEntries.AppendElement(LoadingSessionHistoryEntry{aLoadId, aEntry});
}
void CanonicalBrowsingContext::GetLoadingSessionHistoryInfoFromParent(
Maybe<LoadingSessionHistoryInfo>& aLoadingInfo) {
nsISHistory* shistory = GetSessionHistory();
if (!shistory || !GetParent()) {
return;
}
SessionHistoryEntry* parentSHE =
GetParent()->Canonical()->GetActiveSessionHistoryEntry();
if (parentSHE) {
int32_t index = -1;
for (BrowsingContext* sibling : GetParent()->Children()) {
++index;
if (sibling == this) {
nsCOMPtr<nsISHEntry> shEntry;
parentSHE->GetChildSHEntryIfHasNoDynamicallyAddedChild(
index, getter_AddRefs(shEntry));
nsCOMPtr<SessionHistoryEntry> she = do_QueryInterface(shEntry);
if (she) {
aLoadingInfo.emplace(she);
mLoadingEntries.AppendElement(LoadingSessionHistoryEntry{
aLoadingInfo.value().mLoadId, she.get()});
(void)SetHistoryID(she->DocshellID());
}
break;
}
}
}
}
UniquePtr<LoadingSessionHistoryInfo>
CanonicalBrowsingContext::CreateLoadingSessionHistoryEntryForLoad(
nsDocShellLoadState* aLoadState, SessionHistoryEntry* existingEntry,
nsIChannel* aChannel) {
RefPtr<SessionHistoryEntry> entry;
const LoadingSessionHistoryInfo* existingLoadingInfo =
aLoadState->GetLoadingSessionHistoryInfo();
MOZ_ASSERT_IF(!existingLoadingInfo, !existingEntry);
if (existingLoadingInfo) {
if (existingEntry) {
entry = existingEntry;
} else {
MOZ_ASSERT(!existingLoadingInfo->mLoadIsFromSessionHistory);
SessionHistoryEntry::LoadingEntry* loadingEntry =
SessionHistoryEntry::GetByLoadId(existingLoadingInfo->mLoadId);
MOZ_LOG(gSHLog, LogLevel::Verbose,
("SHEntry::GetByLoadId(%" PRIu64 ") -> %p",
existingLoadingInfo->mLoadId, entry.get()));
if (!loadingEntry) {
return nullptr;
}
entry = loadingEntry->mEntry;
}
// If the entry was updated, update also the LoadingSessionHistoryInfo.
UniquePtr<LoadingSessionHistoryInfo> lshi =
MakeUnique<LoadingSessionHistoryInfo>(entry, existingLoadingInfo);
aLoadState->SetLoadingSessionHistoryInfo(std::move(lshi));
existingLoadingInfo = aLoadState->GetLoadingSessionHistoryInfo();
(void)SetHistoryEntryCount(entry->BCHistoryLength());
} else if (aLoadState->LoadType() == LOAD_REFRESH &&
!ShouldAddEntryForRefresh(aLoadState->URI(),
aLoadState->PostDataStream()) &&
mActiveEntry) {
entry = mActiveEntry;
} else {
entry = new SessionHistoryEntry(aLoadState, aChannel);
if (IsTop() &&
!nsDocShell::ShouldAddToSessionHistory(aLoadState->URI(), aChannel)) {
entry->SetTransient();
}
if (!IsTop() && (mActiveEntry || !mLoadingEntries.IsEmpty())) {
entry->SetIsSubFrame(true);
}
entry->SetDocshellID(GetHistoryID());
entry->SetIsDynamicallyAdded(CreatedDynamically());
entry->SetForInitialLoad(true);
}
MOZ_DIAGNOSTIC_ASSERT(entry);
if (aLoadState->GetNavigationType() == NavigationType::Replace) {
MaybeReuseNavigationKeyFromActiveEntry(entry);
}
UniquePtr<LoadingSessionHistoryInfo> loadingInfo;
if (existingLoadingInfo) {
loadingInfo = MakeUnique<LoadingSessionHistoryInfo>(*existingLoadingInfo);
} else {
loadingInfo = MakeUnique<LoadingSessionHistoryInfo>(entry);
mLoadingEntries.AppendElement(
LoadingSessionHistoryEntry{loadingInfo->mLoadId, entry});
}
// When adding a new entry we need to make sure that the navigation object
// gets it's entries list initialized to the contiguous entries ending in the
// new entry.
if (Navigation::IsAPIEnabled()) {
bool sessionHistoryLoad =
existingLoadingInfo && existingLoadingInfo->mLoadIsFromSessionHistory;
if (sessionHistoryLoad && !mActiveEntry) {
auto* activeEntries = GetActiveEntries();
if (activeEntries && activeEntries->isEmpty()) {
nsSHistory* shistory = static_cast<nsSHistory*>(GetSessionHistory());
shistory->ReconstructContiguousEntryListFrom(entry);
}
}
MOZ_LOG_FMT(gNavigationAPILog, LogLevel::Debug,
"Determining navigation type from loadType={}",
aLoadState->LoadType());
Maybe<NavigationType> navigationType =
NavigationUtils::NavigationTypeFromLoadType(aLoadState->LoadType());
if (!navigationType) {
MOZ_LOG_FMT(gNavigationAPILog, LogLevel::Debug,
"Failed to determine navigation type");
return loadingInfo;
}
loadingInfo->mTriggeringEntry =
mActiveEntry ? Some(mActiveEntry->Info()) : Nothing();
MOZ_LOG_FMT(gNavigationAPILog, LogLevel::Verbose,
"Triggering entry was {}.",
fmt::ptr(loadingInfo->mTriggeringEntry
.map([](auto& entry) { return &entry; })
.valueOr(nullptr)));
if (!existingLoadingInfo ||
!existingLoadingInfo->mTriggeringNavigationType) {
loadingInfo->mTriggeringNavigationType = navigationType;
}
MOZ_LOG_FMT(gNavigationAPILog, LogLevel::Verbose,
"Triggering navigation type was {}.", *navigationType);
GetContiguousEntriesForLoad(*loadingInfo, entry);
if (MOZ_LOG_TEST(gNavigationAPILog, LogLevel::Debug)) {
int32_t index = 0;
MOZ_LOG_FMT(gNavigationAPILog, LogLevel::Debug,
"Preparing contiguous for {} ({}load))",
entry->Info().GetURI()->GetSpecOrDefault(),
sessionHistoryLoad ? "history " : "");
for (const auto& entry : loadingInfo->mContiguousEntries) {
MOZ_LOG_FMT(gNavigationAPILog, LogLevel::Debug,
"{}+- {} SHI {} {}\n URL = {}",
(mActiveEntry && entry == mActiveEntry->Info()) ? ">" : " ",
index++, entry.NavigationKey().ToString().get(),
entry.NavigationId().ToString().get(),
entry.GetURI()->GetSpecOrDefault());
}
}
[[maybe_unused]] auto pred = [&](auto& entry) {
return entry.NavigationKey() == loadingInfo->mInfo.NavigationKey();
};
if (StaticPrefs::dom_navigation_api_strict_enabled()) {
// https://bugzil.la/1989045
MOZ_DIAGNOSTIC_ASSERT(
mozilla::AnyOf(loadingInfo->mContiguousEntries.begin(),
loadingInfo->mContiguousEntries.end(), pred),
"The target entry now needs to be a part of the contiguous list of "
"entries.");
} else {
MOZ_ASSERT(
mozilla::AnyOf(loadingInfo->mContiguousEntries.begin(),
loadingInfo->mContiguousEntries.end(), pred),
"The target entry now needs to be a part of the contiguous list of "
"entries.");
}
}
MOZ_ASSERT(SessionHistoryEntry::GetByLoadId(loadingInfo->mLoadId)->mEntry ==
entry);
return loadingInfo;
}
UniquePtr<LoadingSessionHistoryInfo>
CanonicalBrowsingContext::ReplaceLoadingSessionHistoryEntryForLoad(
LoadingSessionHistoryInfo* aInfo, nsIChannel* aNewChannel) {
MOZ_ASSERT(aInfo);
MOZ_ASSERT(aNewChannel);
SessionHistoryInfo newInfo =
SessionHistoryInfo(aNewChannel, aInfo->mInfo.LoadType(),
aInfo->mInfo.GetPartitionedPrincipalToInherit(),
aInfo->mInfo.GetPolicyContainer());
for (size_t i = 0; i < mLoadingEntries.Length(); ++i) {
if (mLoadingEntries[i].mLoadId == aInfo->mLoadId) {
RefPtr<SessionHistoryEntry> loadingEntry = mLoadingEntries[i].mEntry;
loadingEntry->SetInfo(&newInfo);
if (IsTop()) {
// Only top level pages care about Get/SetTransient.
nsCOMPtr<nsIURI> uri;
aNewChannel->GetURI(getter_AddRefs(uri));
if (!nsDocShell::ShouldAddToSessionHistory(uri, aNewChannel)) {
loadingEntry->SetTransient();
}
} else {
loadingEntry->SetIsSubFrame(aInfo->mInfo.IsSubFrame());
}
loadingEntry->SetDocshellID(GetHistoryID());
loadingEntry->SetIsDynamicallyAdded(CreatedDynamically());
if (aInfo->mTriggeringNavigationType &&
*aInfo->mTriggeringNavigationType == NavigationType::Replace) {
MaybeReuseNavigationKeyFromActiveEntry(loadingEntry);
}
auto result = MakeUnique<LoadingSessionHistoryInfo>(loadingEntry, aInfo);
MOZ_LOG_FMT(
gNavigationAPILog, LogLevel::Debug,
"CanonicalBrowsingContext::ReplaceLoadingSessionHistoryEntryForLoad: "
"Recreating the contiguous entries list after redirected navigation "
"to {}.",
ToMaybeRef(result->mInfo.GetURI())
.map(std::mem_fn(&nsIURI::GetSpecOrDefault))
.valueOr("(null URI)."_ns));
GetContiguousEntriesForLoad(*result, loadingEntry);
return result;
}
}
return nullptr;
}
void CanonicalBrowsingContext::GetContiguousEntriesForLoad(
LoadingSessionHistoryInfo& aLoadingInfo,
const RefPtr<SessionHistoryEntry>& aEntry) {
nsCOMPtr<nsIURI> uri =
mActiveEntry ? mActiveEntry->GetURIOrInheritedForAboutBlank() : nullptr;
nsCOMPtr<nsIURI> targetURI = aEntry->GetURIOrInheritedForAboutBlank();
bool sameOrigin =
NS_SUCCEEDED(nsContentUtils::GetSecurityManager()->CheckSameOriginURI(
targetURI, uri, false, false));
if (aEntry->isInList() ||
(mActiveEntry && mActiveEntry->isInList() && sameOrigin)) {
MOZ_DIAGNOSTIC_ASSERT(aLoadingInfo.mTriggeringNavigationType);
NavigationType navigationType =
aLoadingInfo.mTriggeringNavigationType.valueOr(NavigationType::Push);
nsSHistory::WalkContiguousEntriesInOrder(
aEntry->isInList() ? aEntry : mActiveEntry,
[activeEntry = mActiveEntry, entries = &aLoadingInfo.mContiguousEntries,
navigationType](auto* aEntry) {
nsCOMPtr<SessionHistoryEntry> entry = do_QueryObject(aEntry);
MOZ_ASSERT(entry);
if (navigationType == NavigationType::Replace &&
entry == activeEntry) {
// In the case of a replace navigation, we end up dropping the
// active entry and all following entries.
return false;
}
entries->AppendElement(entry->Info());
// In the case of a push navigation, we end up keeping the
// current active entry but drop all following entries.
return !(navigationType == NavigationType::Push &&
entry == activeEntry);
});
}
if (!aLoadingInfo.mLoadIsFromSessionHistory || !sameOrigin) {
aLoadingInfo.mContiguousEntries.AppendElement(aEntry->Info());
}
}
void CanonicalBrowsingContext::MaybeReuseNavigationKeyFromActiveEntry(
SessionHistoryEntry* aEntry) {
MOZ_ASSERT(aEntry);
// https://html.spec.whatwg.org/#finalize-a-cross-document-navigation
// 9. If entryToReplace is null, then: ...
// Otherwise: ...
// 4. If historyEntry's document state's origin is same origin with
// entryToReplace's document state's origin, then set
// historyEntry's navigation API key to entryToReplace's
// navigation API key.
if (!mActiveEntry) {
return;
}
nsCOMPtr<nsIURI> uri = mActiveEntry->GetURIOrInheritedForAboutBlank();
nsCOMPtr<nsIURI> targetURI = aEntry->GetURIOrInheritedForAboutBlank();
bool sameOrigin =
NS_SUCCEEDED(nsContentUtils::GetSecurityManager()->CheckSameOriginURI(
targetURI, uri, false, false));
if (!sameOrigin) {
return;
}
aEntry->SetNavigationKey(mActiveEntry->Info().NavigationKey());
}
using PrintPromise = CanonicalBrowsingContext::PrintPromise;
#ifdef NS_PRINTING
// Clients must call StaticCloneForPrintingCreated or
// NoStaticCloneForPrintingWillBeCreated before the underlying promise can
// resolve.
class PrintListenerAdapter final : public nsIWebProgressListener {
public:
explicit PrintListenerAdapter(PrintPromise::Private* aPromise)
: mPromise(aPromise) {}
NS_DECL_ISUPPORTS
// NS_DECL_NSIWEBPROGRESSLISTENER
NS_IMETHOD OnStateChange(nsIWebProgress* aWebProgress, nsIRequest* aRequest,
uint32_t aStateFlags, nsresult aStatus) override {
MOZ_ASSERT(NS_IsMainThread());
if (aStateFlags & nsIWebProgressListener::STATE_STOP &&
aStateFlags & nsIWebProgressListener::STATE_IS_DOCUMENT && mPromise) {
mPrintJobFinished = true;
if (mHaveSetBrowsingContext) {
mPromise->Resolve(mClonedStaticBrowsingContext, __func__);
mPromise = nullptr;
}
}
return NS_OK;
}
NS_IMETHOD OnStatusChange(nsIWebProgress* aWebProgress, nsIRequest* aRequest,
nsresult aStatus,
const char16_t* aMessage) override {
if (aStatus != NS_OK && mPromise) {
mPromise->Reject(aStatus, __func__);
mPromise = nullptr;
}
return NS_OK;
}
NS_IMETHOD OnProgressChange(nsIWebProgress* aWebProgress,
nsIRequest* aRequest, int32_t aCurSelfProgress,
int32_t aMaxSelfProgress,
int32_t aCurTotalProgress,
int32_t aMaxTotalProgress) override {
return NS_OK;
}
NS_IMETHOD OnLocationChange(nsIWebProgress* aWebProgress,
nsIRequest* aRequest, nsIURI* aLocation,
uint32_t aFlags) override {
return NS_OK;
}
NS_IMETHOD OnSecurityChange(nsIWebProgress* aWebProgress,
nsIRequest* aRequest, uint32_t aState) override {
return NS_OK;
}
NS_IMETHOD OnContentBlockingEvent(nsIWebProgress* aWebProgress,
nsIRequest* aRequest,
uint32_t aEvent) override {
return NS_OK;
}
void StaticCloneForPrintingCreated(
MaybeDiscardedBrowsingContext&& aClonedStaticBrowsingContext) {
MOZ_ASSERT(NS_IsMainThread());
mClonedStaticBrowsingContext = std::move(aClonedStaticBrowsingContext);
mHaveSetBrowsingContext = true;
if (mPrintJobFinished && mPromise) {
mPromise->Resolve(mClonedStaticBrowsingContext, __func__);
mPromise = nullptr;
}
}
void NoStaticCloneForPrintingWillBeCreated() {
StaticCloneForPrintingCreated(nullptr);
}
private:
~PrintListenerAdapter() = default;
RefPtr<PrintPromise::Private> mPromise;
MaybeDiscardedBrowsingContext mClonedStaticBrowsingContext = nullptr;
bool mHaveSetBrowsingContext = false;
bool mPrintJobFinished = false;
};
NS_IMPL_ISUPPORTS(PrintListenerAdapter, nsIWebProgressListener)
#endif
already_AddRefed<Promise> CanonicalBrowsingContext::PrintJS(
nsIPrintSettings* aPrintSettings, ErrorResult& aRv) {
RefPtr<Promise> promise = Promise::Create(GetIncumbentGlobal(), aRv);
if (NS_WARN_IF(aRv.Failed())) {
return promise.forget();
}
Print(aPrintSettings)
->Then(
GetCurrentSerialEventTarget(), __func__,
[promise](MaybeDiscardedBrowsingContext) {
promise->MaybeResolveWithUndefined();
},
[promise](nsresult aResult) { promise->MaybeReject(aResult); });
return promise.forget();
}
RefPtr<PrintPromise> CanonicalBrowsingContext::Print(
nsIPrintSettings* aPrintSettings) {
#ifndef NS_PRINTING
return PrintPromise::CreateAndReject(NS_ERROR_NOT_AVAILABLE, __func__);
#else
// Content analysis is not supported on non-Windows platforms.
# if defined(XP_WIN)
bool needContentAnalysis = false;
nsCOMPtr<nsIContentAnalysis> contentAnalysis =
mozilla::components::nsIContentAnalysis::Service();
(void)NS_WARN_IF(!contentAnalysis);
if (contentAnalysis) {
nsresult rv = contentAnalysis->GetIsActive(&needContentAnalysis);
(void)NS_WARN_IF(NS_FAILED(rv));
}
if (needContentAnalysis) {
auto done = MakeRefPtr<PrintPromise::Private>(__func__);
contentanalysis::ContentAnalysis::PrintToPDFToDetermineIfPrintAllowed(
this, aPrintSettings)
->Then(
GetCurrentSerialEventTarget(), __func__,
[done, aPrintSettings = RefPtr{aPrintSettings},
self = RefPtr{this}](
contentanalysis::ContentAnalysis::PrintAllowedResult aResponse)
MOZ_CAN_RUN_SCRIPT_BOUNDARY_LAMBDA mutable {
if (aResponse.mAllowed) {
self->PrintWithNoContentAnalysis(
aPrintSettings, false,
aResponse.mCachedStaticDocumentBrowsingContext)
->ChainTo(done.forget(), __func__);
} else {
// Since we are not doing the second print in this case,
// release the clone that is no longer needed.
self->ReleaseClonedPrint(
aResponse.mCachedStaticDocumentBrowsingContext);
done->Reject(NS_ERROR_CONTENT_BLOCKED, __func__);
}
},
[done, self = RefPtr{this}](
contentanalysis::ContentAnalysis::PrintAllowedError
aErrorResponse) MOZ_CAN_RUN_SCRIPT_BOUNDARY_LAMBDA {
// Since we are not doing the second print in this case, release
// the clone that is no longer needed.
self->ReleaseClonedPrint(
aErrorResponse.mCachedStaticDocumentBrowsingContext);
done->Reject(aErrorResponse.mError, __func__);
});
return done;
}
# endif
return PrintWithNoContentAnalysis(aPrintSettings, false, nullptr);
#endif
}
void CanonicalBrowsingContext::ReleaseClonedPrint(
const MaybeDiscardedBrowsingContext& aClonedStaticBrowsingContext) {
#ifdef NS_PRINTING
auto* browserParent = GetBrowserParent();
if (NS_WARN_IF(!browserParent)) {
return;
}
(void)browserParent->SendDestroyPrintClone(aClonedStaticBrowsingContext);
#endif
}
RefPtr<PrintPromise> CanonicalBrowsingContext::PrintWithNoContentAnalysis(
nsIPrintSettings* aPrintSettings, bool aForceStaticDocument,
const MaybeDiscardedBrowsingContext& aCachedStaticDocument) {
#ifndef NS_PRINTING
return PrintPromise::CreateAndReject(NS_ERROR_NOT_AVAILABLE, __func__);
#else
auto promise = MakeRefPtr<PrintPromise::Private>(__func__);
auto listener = MakeRefPtr<PrintListenerAdapter>(promise);
if (IsInProcess()) {
RefPtr<nsGlobalWindowOuter> outerWindow =
nsGlobalWindowOuter::Cast(GetDOMWindow());
if (NS_WARN_IF(!outerWindow)) {
promise->Reject(NS_ERROR_FAILURE, __func__);
return promise;
}
ErrorResult rv;
listener->NoStaticCloneForPrintingWillBeCreated();
outerWindow->Print(aPrintSettings,
/* aRemotePrintJob = */ nullptr, listener,
/* aDocShellToCloneInto = */ nullptr,
nsGlobalWindowOuter::IsPreview::No,
nsGlobalWindowOuter::IsForWindowDotPrint::No,
/* aPrintPreviewCallback = */ nullptr,
/* aCachedBrowsingContext = */ nullptr, rv);
if (rv.Failed()) {
promise->Reject(rv.StealNSResult(), __func__);
}
return promise;
}
auto* browserParent = GetBrowserParent();
if (NS_WARN_IF(!browserParent)) {
promise->Reject(NS_ERROR_FAILURE, __func__);
return promise;
}
nsCOMPtr<nsIPrintSettingsService> printSettingsSvc =
do_GetService("@mozilla.org/gfx/printsettings-service;1");
if (NS_WARN_IF(!printSettingsSvc)) {
promise->Reject(NS_ERROR_FAILURE, __func__);
return promise;
}
nsresult rv;
nsCOMPtr<nsIPrintSettings> printSettings = aPrintSettings;
if (!printSettings) {
rv =
printSettingsSvc->CreateNewPrintSettings(getter_AddRefs(printSettings));
if (NS_WARN_IF(NS_FAILED(rv))) {
promise->Reject(rv, __func__);
return promise;
}
}
embedding::PrintData printData;
rv = printSettingsSvc->SerializeToPrintData(printSettings, &printData);
if (NS_WARN_IF(NS_FAILED(rv))) {
promise->Reject(rv, __func__);
return promise;
}
layout::RemotePrintJobParent* remotePrintJob =
new layout::RemotePrintJobParent(printSettings);
printData.remotePrintJob() =
browserParent->Manager()->SendPRemotePrintJobConstructor(remotePrintJob);
remotePrintJob->RegisterListener(listener);
if (!aCachedStaticDocument.IsNullOrDiscarded()) {
// There is no cloned static browsing context that
// SendPrintClonedPage() will return, so indicate this
// so listener can resolve its promise.
listener->NoStaticCloneForPrintingWillBeCreated();
if (NS_WARN_IF(!browserParent->SendPrintClonedPage(
this, printData, aCachedStaticDocument))) {
promise->Reject(NS_ERROR_FAILURE, __func__);
}
} else {
RefPtr<PBrowserParent::PrintPromise> printPromise =
browserParent->SendPrint(this, printData, aForceStaticDocument);
printPromise->Then(
GetMainThreadSerialEventTarget(), __func__,
[listener](MaybeDiscardedBrowsingContext cachedStaticDocument) {
// promise will get resolved by the listener
listener->StaticCloneForPrintingCreated(
std::move(cachedStaticDocument));
},
[promise](ResponseRejectReason reason) {
NS_WARNING("SendPrint() failed");
promise->Reject(NS_ERROR_FAILURE, __func__);
});
}
return promise.forget();
#endif
}
void CanonicalBrowsingContext::CallOnTopDescendants(
const FunctionRef<CallState(CanonicalBrowsingContext*)>& aCallback,
TopDescendantKind aKind) {
// Calling with All on something other than a chrome root is unlikely to be
// what you want, so lacking a use-case for it, we assert against it for now.
MOZ_ASSERT_IF(aKind == TopDescendantKind::All,
IsChrome() && !GetParentCrossChromeBoundary());
// Similarly, calling with {NonNested,All} on a non-top bc is unlikely to be
// what you want.
MOZ_ASSERT_IF(aKind != TopDescendantKind::ChildrenOnly, IsTop());
if (!IsInProcess()) {
// We rely on top levels having to be embedded in the parent process, so
// we can only have top level descendants if embedded here...
return;
}
const auto* ourTop = Top();
AutoTArray<RefPtr<BrowsingContextGroup>, 32> groups;
BrowsingContextGroup::GetAllGroups(groups);
for (auto& browsingContextGroup : groups) {
for (auto& topLevel : browsingContextGroup->Toplevels()) {
if (topLevel == ourTop) {
// A nested toplevel can't be a descendant of our same toplevel.
continue;
}
// Walk up the CanonicalBrowsingContext tree, looking for a match.
const bool topLevelIsRelevant = [&] {
auto* current = topLevel->Canonical();
while (auto* parent = current->GetParentCrossChromeBoundary()) {
if (parent == this) {
return true;
}
// If we've reached aKind's stop condition, break out early.
if (aKind == TopDescendantKind::ChildrenOnly ||
(aKind == TopDescendantKind::NonNested && parent->IsTop())) {
return false;
}
current = parent;
}
return false;
}();
if (!topLevelIsRelevant) {
continue;
}
if (aCallback(topLevel->Canonical()) == CallState::Stop) {
return;
}
}
}
}
void CanonicalBrowsingContext::SessionHistoryCommit(
uint64_t aLoadId, const nsID& aChangeID, uint32_t aLoadType,
bool aCloneEntryChildren, bool aChannelExpired, uint32_t aCacheKey) {
MOZ_LOG(gSHLog, LogLevel::Verbose,
("CanonicalBrowsingContext::SessionHistoryCommit %p %" PRIu64, this,
aLoadId));
MOZ_ASSERT(aLoadId != UINT64_MAX,
"Must not send special about:blank loadinfo to parent.");
for (size_t i = 0; i < mLoadingEntries.Length(); ++i) {
if (mLoadingEntries[i].mLoadId == aLoadId) {
nsSHistory* shistory = static_cast<nsSHistory*>(GetSessionHistory());
if (!shistory) {
SessionHistoryEntry::RemoveLoadId(aLoadId);
mLoadingEntries.RemoveElementAt(i);
return;
}
RefPtr<SessionHistoryEntry> newActiveEntry = mLoadingEntries[i].mEntry;
if (aCacheKey != 0) {
newActiveEntry->SetCacheKey(aCacheKey);
}
if (aChannelExpired) {
newActiveEntry->SharedInfo()->mExpired = true;
}
bool loadFromSessionHistory = !newActiveEntry->ForInitialLoad();
newActiveEntry->SetForInitialLoad(false);
SessionHistoryEntry::RemoveLoadId(aLoadId);
mLoadingEntries.RemoveElementAt(i);
int32_t indexOfHistoryLoad = -1;
if (loadFromSessionHistory) {
nsCOMPtr<nsISHEntry> root = nsSHistory::GetRootSHEntry(newActiveEntry);
indexOfHistoryLoad = shistory->GetIndexOfEntry(root);
if (indexOfHistoryLoad < 0) {
// Entry has been removed from the session history.
return;
}
}
CallerWillNotifyHistoryIndexAndLengthChanges caller(shistory);
// If there is a name in the new entry, clear the name of all contiguous
// entries. This is for https://html.spec.whatwg.org/#history-traversal
// Step 4.4.2.
nsAutoString nameOfNewEntry;
newActiveEntry->GetName(nameOfNewEntry);
if (!nameOfNewEntry.IsEmpty()) {
nsSHistory::WalkContiguousEntries(
newActiveEntry,
[](nsISHEntry* aEntry) { aEntry->SetName(EmptyString()); });
}
auto* activeEntries = GetActiveEntries();
MOZ_LOG(gSHLog, LogLevel::Verbose,
("SessionHistoryCommit called with mActiveEntry=%p, "
"newActiveEntry=%p, "
"active entry list does%s contain the active entry.",
mActiveEntry.get(), newActiveEntry.get(),
activeEntries->contains(mActiveEntry) ? "" : "n't"));
bool addEntry = ShouldUpdateSessionHistory(aLoadType);
if (IsTop()) {
if (mActiveEntry && !mActiveEntry->GetFrameLoader()) {
bool sharesDocument = true;
mActiveEntry->SharesDocumentWith(newActiveEntry, &sharesDocument);
if (!sharesDocument) {
// If the old page won't be in the bfcache,
// clear the dynamic entries.
RemoveDynEntriesFromActiveSessionHistoryEntry();
}
}
if (LOAD_TYPE_HAS_FLAGS(aLoadType,
nsIWebNavigation::LOAD_FLAGS_REPLACE_HISTORY)) {
// Replace the current entry with the new entry.
int32_t index = shistory->GetTargetIndexForHistoryOperation();
// If we're trying to replace an inexistant shistory entry then we
// should append instead.
addEntry = index < 0;
MOZ_LOG_FMT(gSHLog, LogLevel::Verbose,
"IsTop: Replacing history with addEntry={}", addEntry);
if (!addEntry) {
shistory->ReplaceEntry(index, newActiveEntry);
if (Navigation::IsAPIEnabled() && mActiveEntry &&
mActiveEntry->isInList() && !newActiveEntry->isInList()) {
mActiveEntry->setNext(newActiveEntry);
mActiveEntry->remove();
}
}
if (Navigation::IsAPIEnabled() && !newActiveEntry->isInList()) {
activeEntries->insertBack(newActiveEntry);
}
mActiveEntry = newActiveEntry;
} else if (LOAD_TYPE_HAS_FLAGS(
aLoadType, nsIWebNavigation::LOAD_FLAGS_IS_REFRESH) &&
!ShouldAddEntryForRefresh(newActiveEntry) && mActiveEntry) {
MOZ_LOG_FMT(gSHLog, LogLevel::Verbose,
"IsTop: Refresh without adding entry");
addEntry = false;
mActiveEntry->ReplaceWith(*newActiveEntry);
} else if (!loadFromSessionHistory && mActiveEntry) {
MOZ_LOG_FMT(gSHLog, LogLevel::Verbose, "IsTop: Adding new entry");
if (Navigation::IsAPIEnabled() && mActiveEntry->isInList()) {
RefPtr entry = mActiveEntry->getNext();
while (entry) {
entry = entry->removeAndGetNext();
}
// TODO(avandolder): Can this check ever actually be false?
if (!newActiveEntry->isInList()) {
activeEntries->insertBack(newActiveEntry);
}
}
mActiveEntry = newActiveEntry;
} else if (!mActiveEntry) {
MOZ_LOG_FMT(gSHLog, LogLevel::Verbose,
"IsTop: No active entry, adding new entry");
if (Navigation::IsAPIEnabled() && !newActiveEntry->isInList()) {
activeEntries->insertBack(newActiveEntry);
}
mActiveEntry = newActiveEntry;
} else {
MOZ_LOG_FMT(gSHLog, LogLevel::Verbose,
"IsTop: Loading from session history");
mActiveEntry = newActiveEntry;
if (Navigation::IsAPIEnabled() && !mActiveEntry->isInList()) {
activeEntries->insertBack(mActiveEntry);
}
}
if (loadFromSessionHistory) {
// XXX Synchronize browsing context tree and session history tree?
shistory->InternalSetRequestedIndex(indexOfHistoryLoad);
shistory->UpdateIndex();
if (IsTop()) {
mActiveEntry->SetWireframe(Nothing());
}
} else if (addEntry) {
shistory->AddEntry(mActiveEntry);
shistory->InternalSetRequestedIndex(-1);
}
} else {
// FIXME The old implementations adds it to the parent's mLSHE if there
// is one, need to figure out if that makes sense here (peterv
// doesn't think it would).
if (loadFromSessionHistory) {
if (mActiveEntry) {
// mActiveEntry is null if we're loading iframes from session
// history while also parent page is loading from session history.
// In that case there isn't anything to sync.
mActiveEntry->SyncTreesForSubframeNavigation(newActiveEntry, Top(),
this);
}
MOZ_LOG_FMT(gSHLog, LogLevel::Verbose,
"NotTop: Loading from session history");
mActiveEntry = newActiveEntry;
if (Navigation::IsAPIEnabled() && !mActiveEntry->isInList()) {
shistory->ReconstructContiguousEntryListFrom(mActiveEntry);
}
shistory->InternalSetRequestedIndex(indexOfHistoryLoad);
// FIXME UpdateIndex() here may update index too early (but even the
// old implementation seems to have similar issues).
shistory->UpdateIndex();
} else if (addEntry) {
if (mActiveEntry) {
if (LOAD_TYPE_HAS_FLAGS(
aLoadType, nsIWebNavigation::LOAD_FLAGS_REPLACE_HISTORY) ||
(LOAD_TYPE_HAS_FLAGS(aLoadType,
nsIWebNavigation::LOAD_FLAGS_IS_REFRESH) &&
!ShouldAddEntryForRefresh(newActiveEntry))) {
// FIXME We need to make sure that when we create the info we
// make a copy of the shared state.
mActiveEntry->ReplaceWith(*newActiveEntry);
MOZ_LOG_FMT(gSHLog, LogLevel::Verbose,
"NotTop: replace current active entry");
} else {
// AddNestedSHEntry does update the index of the session
// history!
MOZ_LOG_FMT(gSHLog, LogLevel::Verbose,
"NotTop: Adding entry with an active entry");
shistory->AddNestedSHEntry(mActiveEntry, newActiveEntry, Top(),
aCloneEntryChildren);
if (Navigation::IsAPIEnabled()) {
if (!mActiveEntry->isInList()) {
activeEntries->insertBack(mActiveEntry);
}
mActiveEntry->setNext(newActiveEntry);
}
mActiveEntry = newActiveEntry;
}
} else {
SessionHistoryEntry* parentEntry = GetParent()->mActiveEntry;
// XXX What should happen if parent doesn't have mActiveEntry?
// Or can that even happen ever?
if (parentEntry) {
MOZ_LOG_FMT(gSHLog, LogLevel::Verbose,
"NotTop: Adding entry without an active entry");
mActiveEntry = newActiveEntry;
if (Navigation::IsAPIEnabled() && !mActiveEntry->isInList()) {
activeEntries->insertBack(mActiveEntry);
}
// FIXME Using IsInProcess for aUseRemoteSubframes isn't quite
// right, but aUseRemoteSubframes should be going away.
parentEntry->AddChild(
mActiveEntry,
CreatedDynamically() ? -1 : GetParent()->IndexOf(this),
IsInProcess());
}
}
shistory->InternalSetRequestedIndex(-1);
}
}
ResetSHEntryHasUserInteractionCache();
HistoryCommitIndexAndLength(aChangeID, caller);
shistory->LogHistory();
return;
}
// XXX Should the loading entries before [i] be removed?
}
// FIXME Should we throw an error if we don't find an entry for
// aSessionHistoryEntryId?
}
already_AddRefed<nsDocShellLoadState> CanonicalBrowsingContext::CreateLoadInfo(
SessionHistoryEntry* aEntry, NavigationType aNavigationType) {
const SessionHistoryInfo& info = aEntry->Info();
RefPtr<nsDocShellLoadState> loadState(new nsDocShellLoadState(info.GetURI()));
info.FillLoadInfo(*loadState);
UniquePtr<LoadingSessionHistoryInfo> loadingInfo;
loadingInfo = MakeUnique<LoadingSessionHistoryInfo>(aEntry);
loadingInfo->mTriggeringNavigationType = Some(aNavigationType);
mLoadingEntries.AppendElement(
LoadingSessionHistoryEntry{loadingInfo->mLoadId, aEntry});
loadState->SetLoadingSessionHistoryInfo(std::move(loadingInfo));
return loadState.forget();
}
void CanonicalBrowsingContext::NotifyOnHistoryReload(
bool aForceReload, bool& aCanReload,
Maybe<NotNull<RefPtr<nsDocShellLoadState>>>& aLoadState,
Maybe<bool>& aReloadActiveEntry) {
MOZ_DIAGNOSTIC_ASSERT(!aLoadState);
aCanReload = true;
nsISHistory* shistory = GetSessionHistory();
NS_ENSURE_TRUE_VOID(shistory);
shistory->NotifyOnHistoryReload(&aCanReload);
if (!aCanReload) {
return;
}
if (mActiveEntry) {
aLoadState.emplace(WrapMovingNotNull(
RefPtr{CreateLoadInfo(mActiveEntry, NavigationType::Reload)}));
aReloadActiveEntry.emplace(true);
if (aForceReload) {
shistory->RemoveFrameEntries(mActiveEntry);
}
} else if (!mLoadingEntries.IsEmpty()) {
const LoadingSessionHistoryEntry& loadingEntry =
mLoadingEntries.LastElement();
uint64_t loadId = loadingEntry.mLoadId;
aLoadState.emplace(WrapMovingNotNull(
RefPtr{CreateLoadInfo(loadingEntry.mEntry, NavigationType::Reload)}));
aReloadActiveEntry.emplace(false);
if (aForceReload) {
SessionHistoryEntry::LoadingEntry* entry =
SessionHistoryEntry::GetByLoadId(loadId);
if (entry) {
shistory->RemoveFrameEntries(entry->mEntry);
}
}
}
if (aLoadState) {
// Use 0 as the offset, since aLoadState will be be used for reload.
aLoadState.ref()->SetLoadIsFromSessionHistory(0,
aReloadActiveEntry.value());
}
// If we don't have an active entry and we don't have a loading entry then
// the nsDocShell will create a load state based on its document.
}
void CanonicalBrowsingContext::SetActiveSessionHistoryEntry(
const Maybe<nsPoint>& aPreviousScrollPos, SessionHistoryInfo* aInfo,
uint32_t aLoadType, uint32_t aUpdatedCacheKey, const nsID& aChangeID) {
nsISHistory* shistory = GetSessionHistory();
if (!shistory) {
return;
}
CallerWillNotifyHistoryIndexAndLengthChanges caller(shistory);
RefPtr<SessionHistoryEntry> oldActiveEntry = mActiveEntry;
if (aPreviousScrollPos.isSome() && oldActiveEntry) {
oldActiveEntry->SetScrollPosition(aPreviousScrollPos.ref().x,
aPreviousScrollPos.ref().y);
}
mActiveEntry = new SessionHistoryEntry(aInfo);
mActiveEntry->SetDocshellID(GetHistoryID());
mActiveEntry->AdoptBFCacheEntry(oldActiveEntry);
if (aUpdatedCacheKey != 0) {
mActiveEntry->SharedInfo()->mCacheKey = aUpdatedCacheKey;
}
if (IsTop()) {
Maybe<int32_t> previousEntryIndex, loadedEntryIndex;
shistory->AddToRootSessionHistory(true, oldActiveEntry, this, mActiveEntry,
aLoadType, &previousEntryIndex,
&loadedEntryIndex);
} else {
if (oldActiveEntry) {
shistory->AddNestedSHEntry(oldActiveEntry, mActiveEntry, Top(), true);
} else if (GetParent() && GetParent()->mActiveEntry) {
GetParent()->mActiveEntry->AddChild(
mActiveEntry, CreatedDynamically() ? -1 : GetParent()->IndexOf(this),
UseRemoteSubframes());
}
}
auto* activeEntries = GetActiveEntries();
MOZ_LOG(
gSHLog, LogLevel::Verbose,
("SetActiveSessionHistoryEntry called with oldActiveEntry=%p, "
"mActiveEntry=%p, active entry list does%s contain the active entry. ",
oldActiveEntry.get(), mActiveEntry.get(),
activeEntries->contains(mActiveEntry) ? "" : "n't"));
if (Navigation::IsAPIEnabled() &&
(!oldActiveEntry || oldActiveEntry->isInList())) {
RefPtr toRemove =
oldActiveEntry ? oldActiveEntry->getNext() : activeEntries->getFirst();
while (toRemove) {
toRemove = toRemove->removeAndGetNext();
}
activeEntries->insertBack(mActiveEntry);
}
ResetSHEntryHasUserInteractionCache();
shistory->InternalSetRequestedIndex(-1);
// FIXME Need to do the equivalent of EvictDocumentViewersOrReplaceEntry.
HistoryCommitIndexAndLength(aChangeID, caller);
static_cast<nsSHistory*>(shistory)->LogHistory();
}
void CanonicalBrowsingContext::ReplaceActiveSessionHistoryEntry(
SessionHistoryInfo* aInfo) {
if (!mActiveEntry) {
return;
}
// aInfo comes from the entry stored in the current document's docshell, whose
// interaction state does not get updated. So we instead propagate state from
// the previous canonical entry. See bug 1917369.
const bool hasUserInteraction = mActiveEntry->GetHasUserInteraction();
mActiveEntry->SetInfo(aInfo);
mActiveEntry->SetHasUserInteraction(hasUserInteraction);
// Notify children of the update
nsSHistory* shistory = static_cast<nsSHistory*>(GetSessionHistory());
if (shistory) {
shistory->NotifyOnHistoryReplaceEntry();
}
ResetSHEntryHasUserInteractionCache();
if (IsTop()) {
mActiveEntry->SetWireframe(Nothing());
}
MOZ_LOG(gSHLog, LogLevel::Verbose,
("Replacing active session history entry"));
if (Navigation::IsAPIEnabled() && mActiveEntry->isInList()) {
RefPtr toRemove = mActiveEntry->getNext();
while (toRemove) {
toRemove = toRemove->removeAndGetNext();
}
}
// FIXME Need to do the equivalent of EvictDocumentViewersOrReplaceEntry.
}
void CanonicalBrowsingContext::RemoveDynEntriesFromActiveSessionHistoryEntry() {
nsISHistory* shistory = GetSessionHistory();
// In theory shistory can be null here if the method is called right after
// CanonicalBrowsingContext::ReplacedBy call.
NS_ENSURE_TRUE_VOID(shistory);
nsCOMPtr<nsISHEntry> root = nsSHistory::GetRootSHEntry(mActiveEntry);
shistory->RemoveDynEntries(shistory->GetIndexOfEntry(root), mActiveEntry);
}
void CanonicalBrowsingContext::RemoveFromSessionHistory(const nsID& aChangeID) {
nsSHistory* shistory = static_cast<nsSHistory*>(GetSessionHistory());
if (shistory) {
CallerWillNotifyHistoryIndexAndLengthChanges caller(shistory);
nsCOMPtr<nsISHEntry> root = nsSHistory::GetRootSHEntry(mActiveEntry);
bool didRemove;
AutoTArray<nsID, 16> ids({GetHistoryID()});
shistory->RemoveEntries(ids, shistory->GetIndexOfEntry(root), &didRemove);
if (didRemove) {
RefPtr<BrowsingContext> rootBC = shistory->GetBrowsingContext();
if (rootBC) {
if (!rootBC->IsInProcess()) {
if (ContentParent* cp = rootBC->Canonical()->GetContentParent()) {
(void)cp->SendDispatchLocationChangeEvent(rootBC);
}
} else if (rootBC->GetDocShell()) {
rootBC->GetDocShell()->DispatchLocationChangeEvent();
}
}
}
HistoryCommitIndexAndLength(aChangeID, caller);
}
}
// https://html.spec.whatwg.org/#apply-the-history-step
// This might not seem to be #apply-the-history-step, but it is in fact exactly
// what it is.
Maybe<int32_t> CanonicalBrowsingContext::HistoryGo(
int32_t aOffset, uint64_t aHistoryEpoch, bool aRequireUserInteraction,
bool aUserActivation, bool aCheckForCancelation,
Maybe<ContentParentId> aContentId,
std::function<void(nsresult)>&& aResolver) {
if (aRequireUserInteraction && aOffset != -1 && aOffset != 1) {
NS_ERROR(
"aRequireUserInteraction may only be used with an offset of -1 or 1");
return Nothing();
}
nsSHistory* shistory = static_cast<nsSHistory*>(GetSessionHistory());
if (!shistory) {
return Nothing();
}
CheckedInt<int32_t> index = shistory->GetTargetIndexForHistoryOperation();
MOZ_LOG(gSHLog, LogLevel::Debug,
("HistoryGo(%d->%d) epoch %" PRIu64 "/id %" PRIu64, aOffset,
(index + aOffset).value(), aHistoryEpoch,
(uint64_t)(aContentId.isSome() ? aContentId.value() : 0)));
while (true) {
index += aOffset;
if (!index.isValid()) {
MOZ_LOG(gSHLog, LogLevel::Debug, ("Invalid index"));
return Nothing();
}
// Check for user interaction if desired, except for the first and last
// history entries. We compare with >= to account for the case where
// aOffset >= length.
if (!StaticPrefs::browser_navigation_requireUserInteraction() ||
!aRequireUserInteraction || index.value() >= shistory->Length() - 1 ||
index.value() <= 0) {
break;
}
if (shistory->HasUserInteractionAtIndex(index.value())) {
break;
}
}
// Implement aborting additional history navigations from within the same
// event spin of the content process.
uint64_t epoch;
bool sameEpoch = false;
Maybe<ContentParentId> id;
shistory->GetEpoch(epoch, id);
if (aContentId == id && epoch >= aHistoryEpoch) {
sameEpoch = true;
MOZ_LOG(gSHLog, LogLevel::Debug, ("Same epoch/id"));
}
// Don't update the epoch until we know if the target index is valid
// GoToIndex checks that index is >= 0 and < length.
nsTArray<nsSHistory::LoadEntryResult> loadResults;
const int32_t oldRequestedIndex = shistory->GetRequestedIndex();
nsresult rv = shistory->GotoIndex(this, index.value(), loadResults, sameEpoch,
aOffset == 0, aUserActivation);
if (NS_FAILED(rv)) {
MOZ_LOG(gSHLog, LogLevel::Debug,
("Dropping HistoryGo - bad index or same epoch (not in same doc)"));
return Nothing();
}
for (auto& loadResult : loadResults) {
if (nsresult result = loadResult.mBrowsingContext->CheckSandboxFlags(
loadResult.mLoadState);
NS_FAILED(result)) {
aResolver(result);
MOZ_LOG(gSHLog, LogLevel::Debug,
("Dropping HistoryGo - sandbox check failed"));
shistory->InternalSetRequestedIndex(oldRequestedIndex);
return Nothing();
}
}
if (epoch < aHistoryEpoch || aContentId != id) {
MOZ_LOG(gSHLog, LogLevel::Debug, ("Set epoch"));
shistory->SetEpoch(aHistoryEpoch, aContentId);
}
int32_t requestedIndex = shistory->GetRequestedIndex();
RefPtr traversable = Top();
nsSHistory::LoadURIs(loadResults, aCheckForCancelation, aResolver,
traversable);
return Some(requestedIndex);
}
// https://html.spec.whatwg.org/#performing-a-navigation-api-traversal
// Sub-steps for step 12
void CanonicalBrowsingContext::NavigationTraverse(
const nsID& aKey, uint64_t aHistoryEpoch, bool aUserActivation,
bool aCheckForCancelation, Maybe<ContentParentId> aContentId,
std::function<void(nsresult)>&& aResolver) {
MOZ_LOG_FMT(gNavigationAPILog, LogLevel::Debug, "Traverse navigation to {}",
aKey.ToString().get());
nsSHistory* shistory = static_cast<nsSHistory*>(GetSessionHistory());
if (!shistory) {
return aResolver(NS_ERROR_DOM_INVALID_STATE_ERR);
}
RefPtr<SessionHistoryEntry> targetEntry;
// 12.1 Let navigableSHEs be the result of getting session history entries
// given navigable.
nsSHistory::WalkContiguousEntriesInOrder(
mActiveEntry, [&targetEntry, aKey](auto* aEntry) {
auto* entry = static_cast<SessionHistoryEntry*>(aEntry);
if (entry->Info().NavigationKey() == aKey) {
targetEntry = entry;
return false;
}
return true;
});
// Step 12.2
if (!targetEntry) {
return aResolver(NS_ERROR_DOM_INVALID_STATE_ERR);
}
// Step 12.3
if (targetEntry == mActiveEntry) {
return aResolver(NS_OK);
}
nsCOMPtr targetRoot = nsSHistory::GetRootSHEntry(targetEntry);
nsCOMPtr activeRoot = nsSHistory::GetRootSHEntry(mActiveEntry);
if (!targetRoot || !activeRoot) {
return aResolver(NS_ERROR_DOM_INVALID_STATE_ERR);
}
int32_t targetIndex = shistory->GetIndexOfEntry(targetRoot);
int32_t activeIndex = shistory->GetIndexOfEntry(activeRoot);
if (targetIndex == -1 || activeIndex == -1) {
return aResolver(NS_ERROR_DOM_INVALID_STATE_ERR);
}
int32_t offset = targetIndex - activeIndex;
int32_t requestedIndex = shistory->GetTargetIndexForHistoryOperation();
// Step 12.3
if (requestedIndex == targetIndex) {
return aResolver(NS_OK);
}
// Reset the requested index since this is not a relative traversal, and the
// offset is overriding any currently ongoing history traversals.
shistory->InternalSetRequestedIndex(-1);
HistoryGo(offset, aHistoryEpoch, false, aUserActivation, aCheckForCancelation,
aContentId, std::move(aResolver));
}
JSObject* CanonicalBrowsingContext::WrapObject(
JSContext* aCx, JS::Handle<JSObject*> aGivenProto) {
return CanonicalBrowsingContext_Binding::Wrap(aCx, this, aGivenProto);
}
void CanonicalBrowsingContext::DispatchWheelZoomChange(bool aIncrease) {
Element* element = Top()->GetEmbedderElement();
if (!element) {
return;
}
auto event = aIncrease ? u"DoZoomEnlargeBy10"_ns : u"DoZoomReduceBy10"_ns;
auto dispatcher = MakeRefPtr<AsyncEventDispatcher>(
element, event, CanBubble::eYes, ChromeOnlyDispatch::eYes);
dispatcher->PostDOMEvent();
}
void CanonicalBrowsingContext::CanonicalDiscard() {
if (mTabMediaController) {
mTabMediaController->Shutdown();
mTabMediaController = nullptr;
}
if (mCurrentLoad) {
mCurrentLoad->Cancel(NS_BINDING_ABORTED,
"CanonicalBrowsingContext::CanonicalDiscard"_ns);
}
if (mWebProgress) {
RefPtr<BrowsingContextWebProgress> progress = mWebProgress;
progress->ContextDiscarded();
}
if (IsTop()) {
BackgroundSessionStorageManager::RemoveManager(Id());
}
CancelSessionStoreUpdate();
if (UsePrivateBrowsing() && EverAttached() && IsContent()) {
DecreasePrivateCount();
}
}
void CanonicalBrowsingContext::CanonicalAttach() {
if (UsePrivateBrowsing() && IsContent()) {
IncreasePrivateCount();
}
}
void CanonicalBrowsingContext::AddPendingDiscard() {
MOZ_ASSERT(!mFullyDiscarded);
mPendingDiscards++;
}
void CanonicalBrowsingContext::RemovePendingDiscard() {
mPendingDiscards--;
if (!mPendingDiscards) {
mFullyDiscarded = true;
auto listeners = std::move(mFullyDiscardedListeners);
for (const auto& listener : listeners) {
listener(Id());
}
}
}
void CanonicalBrowsingContext::AddFinalDiscardListener(
std::function<void(uint64_t)>&& aListener) {
if (mFullyDiscarded) {
aListener(Id());
return;
}
mFullyDiscardedListeners.AppendElement(std::move(aListener));
}
void CanonicalBrowsingContext::SetForceAppWindowActive(bool aForceActive,
ErrorResult& aRv) {
MOZ_DIAGNOSTIC_ASSERT(IsChrome());
MOZ_DIAGNOSTIC_ASSERT(IsTop());
if (!IsChrome() || !IsTop()) {
return aRv.ThrowNotAllowedError(
"You shouldn't need to force this BrowsingContext to be active, use "
".isActive instead");
}
if (mForceAppWindowActive == aForceActive) {
return;
}
mForceAppWindowActive = aForceActive;
RecomputeAppWindowVisibility();
}
void CanonicalBrowsingContext::RecomputeAppWindowVisibility() {
MOZ_RELEASE_ASSERT(IsChrome());
MOZ_RELEASE_ASSERT(IsTop());
const bool wasAlreadyActive = IsActive();
nsCOMPtr<nsIWidget> widget;
if (auto* docShell = GetDocShell()) {
widget = nsDocShell::Cast(docShell)->GetMainWidget();
}
(void)NS_WARN_IF(!widget);
const bool isNowActive =
ForceAppWindowActive() || (widget && !widget->IsFullyOccluded() &&
widget->SizeMode() != nsSizeMode_Minimized);
if (isNowActive == wasAlreadyActive) {
return;
}
SetIsActiveInternal(isNowActive, IgnoreErrors());
if (widget) {
// Pause if we are not active, resume if we are active.
widget->PauseOrResumeCompositor(!isNowActive);
}
}
void CanonicalBrowsingContext::AdjustPrivateBrowsingCount(
bool aPrivateBrowsing) {
if (IsDiscarded() || !EverAttached() || IsChrome()) {
return;
}
MOZ_DIAGNOSTIC_ASSERT(aPrivateBrowsing == UsePrivateBrowsing());
if (aPrivateBrowsing) {
IncreasePrivateCount();
} else {
DecreasePrivateCount();
}
}
void CanonicalBrowsingContext::NotifyStartDelayedAutoplayMedia() {
WindowContext* windowContext = GetCurrentWindowContext();
if (!windowContext) {
return;
}
// As this function would only be called when user click the play icon on the
// tab bar. That's clear user intent to play, so gesture activate the window
// context so that the block-autoplay logic allows the media to autoplay.
windowContext->NotifyUserGestureActivation();
AUTOPLAY_LOG("NotifyStartDelayedAutoplayMedia for chrome bc 0x%08" PRIx64,
Id());
StartDelayedAutoplayMediaComponents();
// Notfiy all content browsing contexts which are related with the canonical
// browsing content tree to start delayed autoplay media.
Group()->EachParent([&](ContentParent* aParent) {
(void)aParent->SendStartDelayedAutoplayMediaComponents(this);
});
}
void CanonicalBrowsingContext::NotifyMediaMutedChanged(bool aMuted,
ErrorResult& aRv) {
MOZ_ASSERT(!GetParent(),
"Notify media mute change on non top-level context!");
SetMuted(aMuted, aRv);
}
uint32_t CanonicalBrowsingContext::CountSiteOrigins(
GlobalObject& aGlobal,
const Sequence<OwningNonNull<BrowsingContext>>& aRoots) {
nsTHashSet<nsCString> uniqueSiteOrigins;
for (const auto& root : aRoots) {
root->PreOrderWalk([&](BrowsingContext* aContext) {
WindowGlobalParent* windowGlobalParent =
aContext->Canonical()->GetCurrentWindowGlobal();
if (windowGlobalParent) {
nsIPrincipal* documentPrincipal =
windowGlobalParent->DocumentPrincipal();
bool isContentPrincipal = documentPrincipal->GetIsContentPrincipal();
if (isContentPrincipal) {
nsCString siteOrigin;
documentPrincipal->GetSiteOrigin(siteOrigin);
uniqueSiteOrigins.Insert(siteOrigin);
}
}
});
}
return uniqueSiteOrigins.Count();
}
/* static */
bool CanonicalBrowsingContext::IsPrivateBrowsingActive() {
return gNumberOfPrivateContexts > 0;
}
void CanonicalBrowsingContext::UpdateMediaControlAction(
const MediaControlAction& aAction) {
if (IsDiscarded()) {
return;
}
ContentMediaControlKeyHandler::HandleMediaControlAction(this, aAction);
Group()->EachParent([&](ContentParent* aParent) {
(void)aParent->SendUpdateMediaControlAction(this, aAction);
});
}
void CanonicalBrowsingContext::LoadURI(nsIURI* aURI,
const LoadURIOptions& aOptions,
ErrorResult& aError) {
RefPtr<nsDocShellLoadState> loadState;
nsresult rv = nsDocShellLoadState::CreateFromLoadURIOptions(
this, aURI, aOptions, getter_AddRefs(loadState));
MOZ_ASSERT(rv != NS_ERROR_MALFORMED_URI);
if (NS_FAILED(rv)) {
aError.Throw(rv);
return;
}
// Set the captive portal tab flag on the browsing context if requested
if (loadState->GetIsCaptivePortalTab()) {
(void)SetIsCaptivePortalTab(true);
}
LoadURI(loadState, true);
}
void CanonicalBrowsingContext::FixupAndLoadURIString(
const nsAString& aURI, const LoadURIOptions& aOptions,
ErrorResult& aError) {
RefPtr<nsDocShellLoadState> loadState;
nsresult rv = nsDocShellLoadState::CreateFromLoadURIOptions(
this, aURI, aOptions, getter_AddRefs(loadState));
if (rv == NS_ERROR_MALFORMED_URI) {
DisplayLoadError(aURI);
return;
}
if (NS_FAILED(rv)) {
aError.Throw(rv);
return;
}
// Set the captive portal tab flag on the browsing context if requested
if (loadState->GetIsCaptivePortalTab()) {
(void)SetIsCaptivePortalTab(true);
}
LoadURI(loadState, true);
}
void CanonicalBrowsingContext::GoBack(
const Optional<int32_t>& aCancelContentJSEpoch,
bool aRequireUserInteraction, bool aUserActivation) {
if (IsDiscarded()) {
return;
}
// Stop any known network loads if necessary.
if (mCurrentLoad) {
mCurrentLoad->Cancel(NS_BINDING_CANCELLED_OLD_LOAD, ""_ns);
}
if (RefPtr<nsDocShell> docShell = nsDocShell::Cast(GetDocShell())) {
if (aCancelContentJSEpoch.WasPassed()) {
docShell->SetCancelContentJSEpoch(aCancelContentJSEpoch.Value());
}
docShell->GoBack(aRequireUserInteraction, aUserActivation);
} else if (ContentParent* cp = GetContentParent()) {
Maybe<int32_t> cancelContentJSEpoch;
if (aCancelContentJSEpoch.WasPassed()) {
cancelContentJSEpoch = Some(aCancelContentJSEpoch.Value());
}
(void)cp->SendGoBack(this, cancelContentJSEpoch, aRequireUserInteraction,
aUserActivation);
}
}
void CanonicalBrowsingContext::GoForward(
const Optional<int32_t>& aCancelContentJSEpoch,
bool aRequireUserInteraction, bool aUserActivation) {
if (IsDiscarded()) {
return;
}
// Stop any known network loads if necessary.
if (mCurrentLoad) {
mCurrentLoad->Cancel(NS_BINDING_CANCELLED_OLD_LOAD, ""_ns);
}
if (RefPtr<nsDocShell> docShell = nsDocShell::Cast(GetDocShell())) {
if (aCancelContentJSEpoch.WasPassed()) {
docShell->SetCancelContentJSEpoch(aCancelContentJSEpoch.Value());
}
docShell->GoForward(aRequireUserInteraction, aUserActivation);
} else if (ContentParent* cp = GetContentParent()) {
Maybe<int32_t> cancelContentJSEpoch;
if (aCancelContentJSEpoch.WasPassed()) {
cancelContentJSEpoch.emplace(aCancelContentJSEpoch.Value());
}
(void)cp->SendGoForward(this, cancelContentJSEpoch, aRequireUserInteraction,
aUserActivation);
}
}
void CanonicalBrowsingContext::GoToIndex(
int32_t aIndex, const Optional<int32_t>& aCancelContentJSEpoch,
bool aUserActivation) {
if (IsDiscarded()) {
return;
}
// Stop any known network loads if necessary.
if (mCurrentLoad) {
mCurrentLoad->Cancel(NS_BINDING_CANCELLED_OLD_LOAD, ""_ns);
}
if (RefPtr<nsDocShell> docShell = nsDocShell::Cast(GetDocShell())) {
if (aCancelContentJSEpoch.WasPassed()) {
docShell->SetCancelContentJSEpoch(aCancelContentJSEpoch.Value());
}
docShell->GotoIndex(aIndex, aUserActivation);
} else if (ContentParent* cp = GetContentParent()) {
Maybe<int32_t> cancelContentJSEpoch;
if (aCancelContentJSEpoch.WasPassed()) {
cancelContentJSEpoch.emplace(aCancelContentJSEpoch.Value());
}
(void)cp->SendGoToIndex(this, aIndex, cancelContentJSEpoch,
aUserActivation);
}
}
void CanonicalBrowsingContext::Reload(uint32_t aReloadFlags) {
if (IsDiscarded()) {
return;
}
// Stop any known network loads if necessary.
if (mCurrentLoad) {
mCurrentLoad->Cancel(NS_BINDING_CANCELLED_OLD_LOAD, ""_ns);
}
if (RefPtr<nsDocShell> docShell = nsDocShell::Cast(GetDocShell())) {
docShell->Reload(aReloadFlags);
} else if (ContentParent* cp = GetContentParent()) {
(void)cp->SendReload(this, aReloadFlags);
}
}
void CanonicalBrowsingContext::Stop(uint32_t aStopFlags) {
if (IsDiscarded()) {
return;
}
// Stop any known network loads if necessary.
if (mCurrentLoad && (aStopFlags & nsIWebNavigation::STOP_NETWORK)) {
mCurrentLoad->Cancel(NS_BINDING_ABORTED,
"CanonicalBrowsingContext::Stop"_ns);
}
// Ask the docshell to stop to handle loads that haven't
// yet reached here, as well as non-network activity.
if (auto* docShell = nsDocShell::Cast(GetDocShell())) {
docShell->Stop(aStopFlags);
} else if (ContentParent* cp = GetContentParent()) {
(void)cp->SendStopLoad(this, aStopFlags);
}
}
void CanonicalBrowsingContext::PendingRemotenessChange::ProcessLaunched() {
if (!mPromise) {
return;
}
if (mContentParentKeepAlive) {
// If our new content process is still unloading from a previous process
// switch, wait for that unload to complete before continuing.
auto found = mTarget->FindUnloadingHost(mContentParentKeepAlive->ChildID());
if (found != mTarget->mUnloadingHosts.end()) {
found->mCallbacks.AppendElement(
[self = RefPtr{this}]()
MOZ_CAN_RUN_SCRIPT_BOUNDARY_LAMBDA { self->ProcessReady(); });
return;
}
}
ProcessReady();
}
void CanonicalBrowsingContext::PendingRemotenessChange::ProcessReady() {
if (!mPromise) {
return;
}
MOZ_ASSERT(!mProcessReady);
mProcessReady = true;
MaybeFinish();
}
void CanonicalBrowsingContext::PendingRemotenessChange::MaybeFinish() {
if (!mPromise) {
return;
}
if (!mProcessReady || mWaitingForPrepareToChange) {
return;
}
// If this BrowsingContext is embedded within the parent process, perform the
// process switch directly.
nsresult rv = mTarget->IsTopContent() ? FinishTopContent() : FinishSubframe();
if (NS_FAILED(rv)) {
NS_WARNING("Error finishing PendingRemotenessChange!");
Cancel(rv);
} else {
Clear();
}
}
// Logic for finishing a toplevel process change embedded within the parent
// process. Due to frontend integration the logic differs substantially from
// subframe process switches, and is handled separately.
nsresult CanonicalBrowsingContext::PendingRemotenessChange::FinishTopContent() {
MOZ_DIAGNOSTIC_ASSERT(mTarget->IsTop(),
"We shouldn't be trying to change the remoteness of "
"non-remote iframes");
// Abort if our ContentParent died while process switching.
if (mContentParentKeepAlive &&
NS_WARN_IF(mContentParentKeepAlive->IsShuttingDown())) {
return NS_ERROR_FAILURE;
}
// While process switching, we need to check if any of our ancestors are
// discarded or no longer current, in which case the process switch needs to
// be aborted.
RefPtr<CanonicalBrowsingContext> target(mTarget);
if (target->IsDiscarded() || !target->AncestorsAreCurrent()) {
return NS_ERROR_FAILURE;
}
Element* browserElement = target->GetEmbedderElement();
if (!browserElement) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIBrowser> browser = browserElement->AsBrowser();
if (!browser) {
return NS_ERROR_FAILURE;
}
RefPtr<nsFrameLoaderOwner> frameLoaderOwner = do_QueryObject(browserElement);
MOZ_RELEASE_ASSERT(frameLoaderOwner,
"embedder browser must be nsFrameLoaderOwner");
// If we're process switching a browsing context in private browsing
// mode we might decrease the private browsing count to '0', which
// would make us fire "last-pb-context-exited" and drop the private
// session. To prevent that we artificially increment the number of
// private browsing contexts with '1' until the process switch is done.
bool usePrivateBrowsing = mTarget->UsePrivateBrowsing();
if (usePrivateBrowsing) {
IncreasePrivateCount();
}
auto restorePrivateCount = MakeScopeExit([usePrivateBrowsing]() {
if (usePrivateBrowsing) {
DecreasePrivateCount();
}
});
// Tell frontend code that this browser element is about to change process.
nsresult rv = browser->BeforeChangeRemoteness();
if (NS_FAILED(rv)) {
return rv;
}
// Some frontend code checks the value of the `remote` attribute on the
// browser to determine if it is remote, so update the value.
browserElement->SetAttr(kNameSpaceID_None, nsGkAtoms::remote,
mContentParentKeepAlive ? u"true"_ns : u"false"_ns,
/* notify */ true);
// The process has been created, hand off to nsFrameLoaderOwner to finish
// the process switch.
ErrorResult error;
RefPtr keepAlive = mContentParentKeepAlive.get();
RefPtr specificGroup = mSpecificGroup;
frameLoaderOwner->ChangeRemotenessToProcess(keepAlive, mOptions,
specificGroup, error);
if (error.Failed()) {
return error.StealNSResult();
}
// Tell frontend the load is done.
bool loadResumed = false;
rv = browser->FinishChangeRemoteness(mPendingSwitchId, &loadResumed);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
// We did it! The process switch is complete.
RefPtr<nsFrameLoader> frameLoader = frameLoaderOwner->GetFrameLoader();
RefPtr<BrowserParent> newBrowser = frameLoader->GetBrowserParent();
if (!newBrowser) {
if (mContentParentKeepAlive) {
// Failed to create the BrowserParent somehow! Abort the process switch
// attempt.
return NS_ERROR_UNEXPECTED;
}
if (!loadResumed) {
RefPtr<nsDocShell> newDocShell = frameLoader->GetDocShell(error);
if (error.Failed()) {
return error.StealNSResult();
}
rv = newDocShell->ResumeRedirectedLoad(mPendingSwitchId,
/* aHistoryIndex */ -1);
if (NS_FAILED(rv)) {
return rv;
}
}
} else if (!loadResumed) {
newBrowser->ResumeLoad(mPendingSwitchId);
}
mPromise->Resolve(
std::pair{newBrowser,
RefPtr{frameLoader->GetBrowsingContext()->Canonical()}},
__func__);
return NS_OK;
}
nsresult CanonicalBrowsingContext::PendingRemotenessChange::FinishSubframe() {
MOZ_DIAGNOSTIC_ASSERT(!mOptions.mReplaceBrowsingContext,
"Cannot replace BC for subframe");
MOZ_DIAGNOSTIC_ASSERT(!mTarget->IsTop());
// While process switching, we need to check if any of our ancestors are
// discarded or no longer current, in which case the process switch needs to
// be aborted.
RefPtr<CanonicalBrowsingContext> target(mTarget);
if (target->IsDiscarded() || !target->AncestorsAreCurrent()) {
return NS_ERROR_FAILURE;
}
if (NS_WARN_IF(!mContentParentKeepAlive)) {
return NS_ERROR_FAILURE;
}
RefPtr<WindowGlobalParent> embedderWindow = target->GetParentWindowContext();
if (NS_WARN_IF(!embedderWindow) || NS_WARN_IF(!embedderWindow->CanSend())) {
return NS_ERROR_FAILURE;
}
RefPtr<BrowserParent> embedderBrowser = embedderWindow->GetBrowserParent();
if (NS_WARN_IF(!embedderBrowser)) {
return NS_ERROR_FAILURE;
}
// If we're creating a new remote browser, and the host process is already
// dead, abort the process switch.
if (mContentParentKeepAlive != embedderBrowser->Manager() &&
NS_WARN_IF(mContentParentKeepAlive->IsShuttingDown())) {
return NS_ERROR_FAILURE;
}
RefPtr<BrowserParent> oldBrowser = target->GetBrowserParent();
target->SetCurrentBrowserParent(nullptr);
// If we were in a remote frame, trigger unloading of the remote window. The
// previous BrowserParent is registered in `mUnloadingHosts` and will only be
// cleared when the BrowserParent is fully destroyed.
bool wasRemote = oldBrowser && oldBrowser->GetBrowsingContext() == target;
if (wasRemote) {
MOZ_DIAGNOSTIC_ASSERT(oldBrowser != embedderBrowser);
MOZ_DIAGNOSTIC_ASSERT(oldBrowser->IsDestroyed() ||
oldBrowser->GetBrowserBridgeParent());
// `oldBrowser` will clear the `UnloadingHost` status once the actor has
// been destroyed.
if (oldBrowser->CanSend()) {
target->StartUnloadingHost(oldBrowser->Manager()->ChildID());
(void)oldBrowser->SendWillChangeProcess();
oldBrowser->Destroy();
}
}
// Update which process is considered the current owner
target->SetOwnerProcessId(mContentParentKeepAlive->ChildID());
// If we're switching from remote to local, we don't need to create a
// BrowserBridge, and can instead perform the switch directly.
if (mContentParentKeepAlive == embedderBrowser->Manager()) {
MOZ_DIAGNOSTIC_ASSERT(
mPendingSwitchId,
"We always have a PendingSwitchId, except for print-preview loads, "
"which will never perform a process-switch to being in-process with "
"their embedder");
MOZ_DIAGNOSTIC_ASSERT(wasRemote,
"Attempt to process-switch from local to local?");
target->SetCurrentBrowserParent(embedderBrowser);
(void)embedderWindow->SendMakeFrameLocal(target, mPendingSwitchId);
mPromise->Resolve(std::pair{embedderBrowser, target}, __func__);
return NS_OK;
}
// The BrowsingContext will be remote, either as an already-remote frame
// changing processes, or as a local frame becoming remote. Construct a new
// BrowserBridgeParent to host the remote content.
target->SetCurrentBrowserParent(nullptr);
MOZ_DIAGNOSTIC_ASSERT(target->UseRemoteTabs() && target->UseRemoteSubframes(),
"Not supported without fission");
uint32_t chromeFlags = nsIWebBrowserChrome::CHROME_REMOTE_WINDOW |
nsIWebBrowserChrome::CHROME_FISSION_WINDOW;
if (target->UsePrivateBrowsing()) {
chromeFlags |= nsIWebBrowserChrome::CHROME_PRIVATE_WINDOW;
}
nsCOMPtr<nsIPrincipal> initialPrincipal =
NullPrincipal::Create(target->OriginAttributesRef());
WindowGlobalInit windowInit =
WindowGlobalActor::AboutBlankInitializer(target, initialPrincipal);
// Create and initialize our new BrowserBridgeParent.
TabId tabId(nsContentUtils::GenerateTabId());
RefPtr<BrowserBridgeParent> bridge = new BrowserBridgeParent();
nsresult rv =
bridge->InitWithProcess(embedderBrowser, mContentParentKeepAlive.get(),
windowInit, chromeFlags, tabId);
if (NS_WARN_IF(NS_FAILED(rv))) {
// If we've already destroyed our previous document, make a best-effort
// attempt to recover from this failure and show the crashed tab UI. We only
// do this in the previously-remote case, as previously in-process frames
// will have their navigation cancelled, and will remain visible.
if (wasRemote) {
target->ShowSubframeCrashedUI(oldBrowser->GetBrowserBridgeParent());
}
return rv;
}
// Tell the embedder process a remoteness change is in-process. When this is
// acknowledged, reset the in-flight ID if it used to be an in-process load.
RefPtr<BrowserParent> newBrowser = bridge->GetBrowserParent();
{
// If we weren't remote, mark our embedder window browser as unloading until
// our embedder process has acked our MakeFrameRemote message.
Maybe<uint64_t> clearChildID;
if (!wasRemote) {
clearChildID = Some(embedderBrowser->Manager()->ChildID());
target->StartUnloadingHost(*clearChildID);
}
auto callback = [target, clearChildID](auto&&) {
if (clearChildID) {
target->ClearUnloadingHost(*clearChildID);
}
};
ManagedEndpoint<PBrowserBridgeChild> endpoint =
embedderBrowser->OpenPBrowserBridgeEndpoint(bridge);
MOZ_DIAGNOSTIC_ASSERT(endpoint.IsValid());
embedderWindow->SendMakeFrameRemote(target, std::move(endpoint), tabId,
newBrowser->GetLayersId(), callback,
callback);
}
// Resume the pending load in our new process.
if (mPendingSwitchId) {
newBrowser->ResumeLoad(mPendingSwitchId);
}
// We did it! The process switch is complete.
mPromise->Resolve(std::pair{newBrowser, target}, __func__);
return NS_OK;
}
void CanonicalBrowsingContext::PendingRemotenessChange::Cancel(nsresult aRv) {
if (!mPromise) {
return;
}
mPromise->Reject(aRv, __func__);
Clear();
}
void CanonicalBrowsingContext::PendingRemotenessChange::Clear() {
// Make sure we don't die while we're doing cleanup.
RefPtr<PendingRemotenessChange> kungFuDeathGrip(this);
if (mTarget) {
MOZ_DIAGNOSTIC_ASSERT(mTarget->mPendingRemotenessChange == this);
mTarget->mPendingRemotenessChange = nullptr;
}
// When this PendingRemotenessChange was created, it was given a
// `mContentParentKeepAlive`.
mContentParentKeepAlive = nullptr;
// If we were given a specific group, stop keeping that group alive manually.
if (mSpecificGroup) {
mSpecificGroup->RemoveKeepAlive();
mSpecificGroup = nullptr;
}
mPromise = nullptr;
mTarget = nullptr;
}
CanonicalBrowsingContext::PendingRemotenessChange::PendingRemotenessChange(
CanonicalBrowsingContext* aTarget, RemotenessPromise::Private* aPromise,
uint64_t aPendingSwitchId, const NavigationIsolationOptions& aOptions)
: mTarget(aTarget),
mPromise(aPromise),
mPendingSwitchId(aPendingSwitchId),
mOptions(aOptions) {}
CanonicalBrowsingContext::PendingRemotenessChange::~PendingRemotenessChange() {
MOZ_ASSERT(
!mPromise && !mTarget && !mContentParentKeepAlive && !mSpecificGroup,
"should've already been Cancel() or Complete()-ed");
}
BrowserParent* CanonicalBrowsingContext::GetBrowserParent() const {
return mCurrentBrowserParent;
}
void CanonicalBrowsingContext::SetCurrentBrowserParent(
BrowserParent* aBrowserParent) {
MOZ_DIAGNOSTIC_ASSERT(!mCurrentBrowserParent || !aBrowserParent,
"BrowsingContext already has a current BrowserParent!");
MOZ_DIAGNOSTIC_ASSERT_IF(aBrowserParent, aBrowserParent->CanSend());
MOZ_DIAGNOSTIC_ASSERT_IF(aBrowserParent,
aBrowserParent->Manager()->ChildID() == mProcessId);
// BrowserParent must either be directly for this BrowsingContext, or the
// manager out our embedder WindowGlobal.
MOZ_DIAGNOSTIC_ASSERT_IF(
aBrowserParent && aBrowserParent->GetBrowsingContext() != this,
GetParentWindowContext() &&
GetParentWindowContext()->Manager() == aBrowserParent);
if (aBrowserParent && IsTopContent() && !ManuallyManagesActiveness()) {
aBrowserParent->SetRenderLayers(IsActive());
}
mCurrentBrowserParent = aBrowserParent;
}
bool CanonicalBrowsingContext::ManuallyManagesActiveness() const {
auto* el = GetEmbedderElement();
return el && el->IsXULElement() && el->HasAttr(nsGkAtoms::manualactiveness);
}
RefPtr<CanonicalBrowsingContext::RemotenessPromise>
CanonicalBrowsingContext::ChangeRemoteness(
const NavigationIsolationOptions& aOptions, uint64_t aPendingSwitchId) {
MOZ_DIAGNOSTIC_ASSERT(IsContent(),
"cannot change the process of chrome contexts");
MOZ_DIAGNOSTIC_ASSERT(
IsTop() == IsEmbeddedInProcess(0),
"toplevel content must be embedded in the parent process");
MOZ_DIAGNOSTIC_ASSERT(!aOptions.mReplaceBrowsingContext || IsTop(),
"Cannot replace BrowsingContext for subframes");
MOZ_DIAGNOSTIC_ASSERT(
aOptions.mSpecificGroupId == 0 || aOptions.mReplaceBrowsingContext,
"Cannot specify group ID unless replacing BC");
MOZ_DIAGNOSTIC_ASSERT(aPendingSwitchId || !IsTop(),
"Should always have aPendingSwitchId for top-level "
"frames");
if (!AncestorsAreCurrent()) {
NS_WARNING("An ancestor context is no longer current");
return RemotenessPromise::CreateAndReject(NS_ERROR_FAILURE, __func__);
}
// Ensure our embedder hasn't been destroyed or asked to shutdown already.
RefPtr<WindowGlobalParent> embedderWindowGlobal = GetEmbedderWindowGlobal();
if (!embedderWindowGlobal) {
NS_WARNING("Non-embedded BrowsingContext");
return RemotenessPromise::CreateAndReject(NS_ERROR_UNEXPECTED, __func__);
}
if (!embedderWindowGlobal->CanSend()) {
NS_WARNING("Embedder already been destroyed.");
return RemotenessPromise::CreateAndReject(NS_ERROR_NOT_AVAILABLE, __func__);
}
RefPtr<BrowserParent> embedderBrowser =
embedderWindowGlobal->GetBrowserParent();
if (embedderBrowser && embedderBrowser->Manager()->IsShuttingDown()) {
NS_WARNING("Embedder already asked to shutdown.");
return RemotenessPromise::CreateAndReject(NS_ERROR_NOT_AVAILABLE, __func__);
}
if (aOptions.mRemoteType.IsEmpty() && (!IsTop() || !GetEmbedderElement())) {
NS_WARNING("Cannot load non-remote subframes");
return RemotenessPromise::CreateAndReject(NS_ERROR_FAILURE, __func__);
}
// Cancel ongoing remoteness changes.
if (mPendingRemotenessChange) {
mPendingRemotenessChange->Cancel(NS_ERROR_ABORT);
MOZ_DIAGNOSTIC_ASSERT(!mPendingRemotenessChange, "Should have cleared");
}
auto promise = MakeRefPtr<RemotenessPromise::Private>(__func__);
promise->UseDirectTaskDispatch(__func__);
RefPtr<PendingRemotenessChange> change =
new PendingRemotenessChange(this, promise, aPendingSwitchId, aOptions);
mPendingRemotenessChange = change;
// If we're replacing BrowsingContext, determine which BrowsingContextGroup
// we'll switch into, taking into account load options.
if (aOptions.mReplaceBrowsingContext) {
change->mSpecificGroup =
aOptions.mSpecificGroupId
? BrowsingContextGroup::GetOrCreate(aOptions.mSpecificGroupId)
: BrowsingContextGroup::Create(aOptions.mShouldCrossOriginIsolate);
change->mSpecificGroup->AddKeepAlive();
}
// Call `prepareToChangeRemoteness` in parallel with starting a new process
// for <browser> loads.
if (IsTop() && GetEmbedderElement()) {
nsCOMPtr<nsIBrowser> browser = GetEmbedderElement()->AsBrowser();
if (!browser) {
change->Cancel(NS_ERROR_FAILURE);
return promise.forget();
}
RefPtr<Promise> blocker;
nsresult rv = browser->PrepareToChangeRemoteness(getter_AddRefs(blocker));
if (NS_FAILED(rv)) {
change->Cancel(rv);
return promise.forget();
}
// Mark prepareToChange as unresolved, and wait for it to become resolved.
if (blocker && blocker->State() != Promise::PromiseState::Resolved) {
change->mWaitingForPrepareToChange = true;
blocker->AddCallbacksWithCycleCollectedArgs(
[change](JSContext*, JS::Handle<JS::Value>, ErrorResult&)
MOZ_CAN_RUN_SCRIPT_BOUNDARY_LAMBDA {
change->mWaitingForPrepareToChange = false;
change->MaybeFinish();
},
[change](JSContext*, JS::Handle<JS::Value> aValue, ErrorResult&) {
change->Cancel(
Promise::TryExtractNSResultFromRejectionValue(aValue));
});
}
}
// Switching a subframe to be local within it's embedding process.
if (embedderBrowser &&
aOptions.mRemoteType == embedderBrowser->Manager()->GetRemoteType()) {
MOZ_DIAGNOSTIC_ASSERT(
aPendingSwitchId,
"We always have a PendingSwitchId, except for print-preview loads, "
"which will never perform a process-switch to being in-process with "
"their embedder");
MOZ_DIAGNOSTIC_ASSERT(!aOptions.mReplaceBrowsingContext);
MOZ_DIAGNOSTIC_ASSERT(!aOptions.mRemoteType.IsEmpty());
MOZ_DIAGNOSTIC_ASSERT(!change->mWaitingForPrepareToChange);
MOZ_DIAGNOSTIC_ASSERT(!change->mSpecificGroup);
// Switching to local, so we don't need to create a new process, and will
// instead use our embedder process.
change->mContentParentKeepAlive =
embedderBrowser->Manager()->AddKeepAlive(BrowserId());
change->ProcessLaunched();
return promise.forget();
}
// Switching to the parent process.
if (aOptions.mRemoteType.IsEmpty()) {
change->ProcessLaunched();
return promise.forget();
}
// If we're aiming to end up in a new process of the same type as our old
// process, and then putting our previous document in the BFCache, try to stay
// in the same process to avoid creating new processes unnecessarily.
RefPtr<ContentParent> existingProcess = GetContentParent();
if (existingProcess && !existingProcess->IsShuttingDown() &&
aOptions.mReplaceBrowsingContext &&
aOptions.mRemoteType == existingProcess->GetRemoteType()) {
change->mContentParentKeepAlive =
existingProcess->AddKeepAlive(BrowserId());
change->ProcessLaunched();
return promise.forget();
}
// Try to predict which BrowsingContextGroup will be used for the final load
// in this BrowsingContext. This has to be accurate if switching into an
// existing group, as it will control what pool of processes will be used
// for process selection.
//
// It's _technically_ OK to provide a group here if we're actually going to
// switch into a brand new group, though it's sub-optimal, as it can
// restrict the set of processes we're using.
BrowsingContextGroup* finalGroup =
aOptions.mReplaceBrowsingContext ? change->mSpecificGroup.get() : Group();
bool preferUsed =
StaticPrefs::browser_tabs_remote_subframesPreferUsed() && !IsTop();
change->mContentParentKeepAlive =
ContentParent::GetNewOrUsedLaunchingBrowserProcess(
/* aRemoteType = */ aOptions.mRemoteType,
/* aGroup = */ finalGroup,
/* aPriority = */ hal::PROCESS_PRIORITY_FOREGROUND,
/* aPreferUsed = */ preferUsed,
/* aBrowserId */ BrowserId());
if (!change->mContentParentKeepAlive) {
change->Cancel(NS_ERROR_FAILURE);
return promise.forget();
}
if (change->mContentParentKeepAlive->IsLaunching()) {
change->mContentParentKeepAlive
->WaitForLaunchAsync(/* aPriority */ hal::PROCESS_PRIORITY_FOREGROUND,
/* aBrowserId */ BrowserId())
->Then(
GetMainThreadSerialEventTarget(), __func__,
[change](UniqueContentParentKeepAlive&&)
MOZ_CAN_RUN_SCRIPT_BOUNDARY_LAMBDA {
change->ProcessLaunched();
},
[change]() { change->Cancel(NS_ERROR_FAILURE); });
} else {
change->ProcessLaunched();
}
return promise.forget();
}
void CanonicalBrowsingContext::MaybeSetPermanentKey(Element* aEmbedder) {
MOZ_DIAGNOSTIC_ASSERT(IsTop());
if (aEmbedder) {
if (nsCOMPtr<nsIBrowser> browser = aEmbedder->AsBrowser()) {
JS::Rooted<JS::Value> key(RootingCx());
if (NS_SUCCEEDED(browser->GetPermanentKey(&key)) && key.isObject()) {
mPermanentKey = key;
}
}
}
}
MediaController* CanonicalBrowsingContext::GetMediaController() {
// We would only create one media controller per tab, so accessing the
// controller via the top-level browsing context.
if (GetParent()) {
return Cast(Top())->GetMediaController();
}
MOZ_ASSERT(!GetParent(),
"Must access the controller from the top-level browsing context!");
// Only content browsing context can create media controller, we won't create
// controller for chrome document, such as the browser UI.
if (!mTabMediaController && !IsDiscarded() && IsContent()) {
mTabMediaController = new MediaController(Id());
}
return mTabMediaController;
}
bool CanonicalBrowsingContext::HasCreatedMediaController() const {
return !!mTabMediaController;
}
bool CanonicalBrowsingContext::SupportsLoadingInParent(
nsDocShellLoadState* aLoadState, uint64_t* aOuterWindowId) {
// We currently don't support initiating loads in the parent when they are
// watched by devtools. This is because devtools tracks loads using content
// process notifications, which happens after the load is initiated in this
// case. Devtools clears all prior requests when it detects a new navigation,
// so it drops the main document load that happened here.
if (WatchedByDevTools()) {
return false;
}
// Session-history-in-parent implementation relies currently on getting a
// round trip through a child process.
if (aLoadState->LoadIsFromSessionHistory()) {
return false;
}
// DocumentChannel currently only supports connecting channels into the
// content process, so we can only support schemes that will always be loaded
// there for now. Restrict to just http(s) for simplicity.
if (!net::SchemeIsHttpOrHttps(aLoadState->URI())) {
return false;
}
if (WindowGlobalParent* global = GetCurrentWindowGlobal()) {
nsCOMPtr<nsIURI> currentURI = global->GetDocumentURI();
if (currentURI) {
nsCOMPtr<nsIURI> uri = aLoadState->URI();
bool newURIHasRef = false;
uri->GetHasRef(&newURIHasRef);
bool equalsExceptRef = false;
uri->EqualsExceptRef(currentURI, &equalsExceptRef);
if (equalsExceptRef && newURIHasRef) {
// This navigation is same-doc WRT the current one, we should pass it
// down to the docshell to be handled.
return false;
}
}
// If unloading the current document will cause a beforeunload listener to
// run, then we need to start the load in that process after we fire the
// event.
if (PreOrderWalkFlag([&](BrowsingContext* aBC) {
WindowContext* wc = aBC->GetCurrentWindowContext();
if (wc && wc->NeedsBeforeUnload()) {
// We can stop as soon as we know at least one beforeunload listener
// exists.
return WalkFlag::Stop;
}
return WalkFlag::Next;
}) == WalkFlag::Stop) {
return false;
}
*aOuterWindowId = global->OuterWindowId();
}
return true;
}
bool CanonicalBrowsingContext::AttemptSpeculativeLoadInParent(
nsDocShellLoadState* aLoadState) {
// We currently only support starting loads directly from the
// CanonicalBrowsingContext for top-level BCs.
// We currently only support starting loads directly from the
// CanonicalBrowsingContext for top-level BCs.
if (!IsTopContent() || !GetContentParent()) {
return false;
}
uint64_t outerWindowId = 0;
if (!SupportsLoadingInParent(aLoadState, &outerWindowId)) {
return false;
}
// If we successfully open the DocumentChannel, then it'll register
// itself using aLoadIdentifier and be kept alive until it completes
// loading.
return net::DocumentLoadListener::SpeculativeLoadInParent(this, aLoadState);
}
bool CanonicalBrowsingContext::StartDocumentLoad(
net::DocumentLoadListener* aLoad) {
mCurrentLoad = aLoad;
if (NS_FAILED(SetCurrentLoadIdentifier(Some(aLoad->GetLoadIdentifier())))) {
mCurrentLoad = nullptr;
return false;
}
return true;
}
void CanonicalBrowsingContext::EndDocumentLoad(bool aContinueNavigating) {
mCurrentLoad = nullptr;
if (!aContinueNavigating) {
// Resetting the current load identifier on a discarded context
// has no effect when a document load has finished.
(void)SetCurrentLoadIdentifier(Nothing());
}
}
already_AddRefed<nsIURI> CanonicalBrowsingContext::GetCurrentURI() const {
nsCOMPtr<nsIURI> currentURI;
if (nsIDocShell* docShell = GetDocShell()) {
MOZ_ALWAYS_SUCCEEDS(
nsDocShell::Cast(docShell)->GetCurrentURI(getter_AddRefs(currentURI)));
} else {
currentURI = mCurrentRemoteURI;
}
return currentURI.forget();
}
void CanonicalBrowsingContext::SetCurrentRemoteURI(nsIURI* aCurrentRemoteURI) {
MOZ_ASSERT(!GetDocShell());
mCurrentRemoteURI = aCurrentRemoteURI;
}
void CanonicalBrowsingContext::ResetSHEntryHasUserInteractionCache() {
WindowContext* topWc = GetTopWindowContext();
if (topWc && !topWc->IsDiscarded()) {
MOZ_ALWAYS_SUCCEEDS(topWc->SetSHEntryHasUserInteraction(false));
}
}
void CanonicalBrowsingContext::HistoryCommitIndexAndLength() {
nsID changeID = {};
CallerWillNotifyHistoryIndexAndLengthChanges caller(nullptr);
HistoryCommitIndexAndLength(changeID, caller);
}
void CanonicalBrowsingContext::HistoryCommitIndexAndLength(
const nsID& aChangeID,
const CallerWillNotifyHistoryIndexAndLengthChanges& aProofOfCaller) {
if (!IsTop()) {
Cast(Top())->HistoryCommitIndexAndLength(aChangeID, aProofOfCaller);
return;
}
nsISHistory* shistory = GetSessionHistory();
if (!shistory) {
return;
}
int32_t index = 0;
shistory->GetIndex(&index);
int32_t length = shistory->GetCount();
GetChildSessionHistory()->SetIndexAndLength(index, length, aChangeID);
shistory->EvictOutOfRangeDocumentViewers(index);
Group()->EachParent([&](ContentParent* aParent) {
(void)aParent->SendHistoryCommitIndexAndLength(this, index, length,
aChangeID);
});
}
void CanonicalBrowsingContext::SynchronizeLayoutHistoryState() {
if (mActiveEntry) {
if (IsInProcess()) {
nsIDocShell* docShell = GetDocShell();
if (docShell) {
docShell->PersistLayoutHistoryState();
nsCOMPtr<nsILayoutHistoryState> state;
docShell->GetLayoutHistoryState(getter_AddRefs(state));
if (state) {
mActiveEntry->SetLayoutHistoryState(state);
}
}
} else if (ContentParent* cp = GetContentParent()) {
cp->SendGetLayoutHistoryState(this)->Then(
GetCurrentSerialEventTarget(), __func__,
[activeEntry = mActiveEntry](
const std::tuple<RefPtr<nsILayoutHistoryState>, Maybe<Wireframe>>&
aResult) {
if (std::get<0>(aResult)) {
activeEntry->SetLayoutHistoryState(std::get<0>(aResult));
}
if (std::get<1>(aResult)) {
activeEntry->SetWireframe(std::get<1>(aResult));
}
},
[]() {});
}
}
}
void CanonicalBrowsingContext::SynchronizeNavigationAPIState(
nsIStructuredCloneContainer* aState) {
if (mActiveEntry) {
mActiveEntry->SetNavigationAPIState(aState);
}
}
void CanonicalBrowsingContext::ResetScalingZoom() {
// This currently only ever gets called in the parent process, and we
// pass the message on to the WindowGlobalChild for the rootmost browsing
// context.
if (WindowGlobalParent* topWindow = GetTopWindowContext()) {
(void)topWindow->SendResetScalingZoom();
}
}
void CanonicalBrowsingContext::SetRestoreData(SessionStoreRestoreData* aData,
ErrorResult& aError) {
MOZ_DIAGNOSTIC_ASSERT(aData);
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(GetParentObject());
RefPtr<Promise> promise = Promise::Create(global, aError);
if (aError.Failed()) {
return;
}
if (NS_WARN_IF(NS_FAILED(SetHasRestoreData(true)))) {
aError.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
return;
}
mRestoreState = new RestoreState();
mRestoreState->mData = aData;
mRestoreState->mPromise = promise;
}
already_AddRefed<Promise> CanonicalBrowsingContext::GetRestorePromise() {
if (mRestoreState) {
return do_AddRef(mRestoreState->mPromise);
}
return nullptr;
}
void CanonicalBrowsingContext::ClearRestoreState() {
if (IsDiscarded()) {
return;
}
if (!mRestoreState) {
MOZ_DIAGNOSTIC_ASSERT(!GetHasRestoreData());
return;
}
if (mRestoreState->mPromise) {
mRestoreState->mPromise->MaybeRejectWithUndefined();
}
mRestoreState = nullptr;
MOZ_ALWAYS_SUCCEEDS(SetHasRestoreData(false));
}
void CanonicalBrowsingContext::RequestRestoreTabContent(
WindowGlobalParent* aWindow) {
MOZ_DIAGNOSTIC_ASSERT(IsTop());
if (IsDiscarded() || !mRestoreState || !mRestoreState->mData) {
return;
}
CanonicalBrowsingContext* context = aWindow->GetBrowsingContext();
MOZ_DIAGNOSTIC_ASSERT(!context->IsDiscarded());
RefPtr<SessionStoreRestoreData> data =
mRestoreState->mData->FindDataForChild(context);
if (context->IsTop()) {
MOZ_DIAGNOSTIC_ASSERT(context == this);
// We need to wait until the appropriate load event has fired before we
// can "complete" the restore process, so if we're holding an empty data
// object, just resolve the promise immediately.
if (mRestoreState->mData->IsEmpty()) {
MOZ_DIAGNOSTIC_ASSERT(!data || data->IsEmpty());
mRestoreState->Resolve();
ClearRestoreState();
return;
}
// Since we're following load event order, we'll only arrive here for a
// toplevel context after we've already sent down data for all child frames,
// so it's safe to clear this reference now. The completion callback below
// relies on the mData field being null to determine if all requests have
// been sent out.
mRestoreState->ClearData();
MOZ_ALWAYS_SUCCEEDS(SetHasRestoreData(false));
}
if (data && !data->IsEmpty()) {
auto onTabRestoreComplete = [self = RefPtr{this},
state = RefPtr{mRestoreState}](auto) {
state->mResolves++;
if (!state->mData && state->mRequests == state->mResolves) {
state->Resolve();
if (state == self->mRestoreState) {
self->ClearRestoreState();
}
}
};
mRestoreState->mRequests++;
if (data->CanRestoreInto(aWindow->GetDocumentURI())) {
if (!aWindow->IsInProcess()) {
aWindow->SendRestoreTabContent(WrapNotNull(data.get()),
onTabRestoreComplete,
onTabRestoreComplete);
return;
}
data->RestoreInto(context);
}
// This must be called both when we're doing an in-process restore, and when
// we didn't do a restore at all due to a URL mismatch.
onTabRestoreComplete(true);
}
}
void CanonicalBrowsingContext::RestoreState::Resolve() {
MOZ_DIAGNOSTIC_ASSERT(mPromise);
mPromise->MaybeResolveWithUndefined();
mPromise = nullptr;
}
nsresult CanonicalBrowsingContext::WriteSessionStorageToSessionStore(
const nsTArray<SSCacheCopy>& aSesssionStorage, uint32_t aEpoch) {
nsCOMPtr<nsISessionStoreFunctions> sessionStoreFuncs =
do_GetService("@mozilla.org/toolkit/sessionstore-functions;1");
if (!sessionStoreFuncs) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIXPConnectWrappedJS> wrapped =
do_QueryInterface(sessionStoreFuncs);
AutoJSAPI jsapi;
if (!jsapi.Init(wrapped->GetJSObjectGlobal())) {
return NS_ERROR_FAILURE;
}
JS::Rooted<JS::Value> key(jsapi.cx(), Top()->PermanentKey());
Record<nsCString, Record<nsString, nsString>> storage;
JS::Rooted<JS::Value> update(jsapi.cx());
if (!aSesssionStorage.IsEmpty()) {
SessionStoreUtils::ConstructSessionStorageValues(this, aSesssionStorage,
storage);
if (!ToJSValue(jsapi.cx(), storage, &update)) {
return NS_ERROR_FAILURE;
}
} else {
update.setNull();
}
return sessionStoreFuncs->UpdateSessionStoreForStorage(
Top()->GetEmbedderElement(), this, key, aEpoch, update);
}
void CanonicalBrowsingContext::UpdateSessionStoreSessionStorage(
const std::function<void()>& aDone) {
using DataPromise = BackgroundSessionStorageManager::DataPromise;
BackgroundSessionStorageManager::GetData(
this, StaticPrefs::browser_sessionstore_dom_storage_limit(),
/* aClearSessionStoreTimer = */ true)
->Then(GetCurrentSerialEventTarget(), __func__,
[self = RefPtr{this}, aDone, epoch = GetSessionStoreEpoch()](
const DataPromise::ResolveOrRejectValue& valueList) {
if (valueList.IsResolve()) {
self->WriteSessionStorageToSessionStore(
valueList.ResolveValue(), epoch);
}
aDone();
});
}
/* static */
void CanonicalBrowsingContext::UpdateSessionStoreForStorage(
uint64_t aBrowsingContextId) {
RefPtr<CanonicalBrowsingContext> browsingContext = Get(aBrowsingContextId);
if (!browsingContext) {
return;
}
browsingContext->UpdateSessionStoreSessionStorage([]() {});
}
void CanonicalBrowsingContext::MaybeScheduleSessionStoreUpdate() {
if (!SessionStorePlatformCollection()) {
return;
}
if (!IsTop()) {
Top()->MaybeScheduleSessionStoreUpdate();
return;
}
if (IsInBFCache()) {
return;
}
if (mSessionStoreSessionStorageUpdateTimer) {
return;
}
if (!StaticPrefs::browser_sessionstore_debug_no_auto_updates()) {
auto result = NS_NewTimerWithFuncCallback(
[](nsITimer*, void* aClosure) {
auto* context = static_cast<CanonicalBrowsingContext*>(aClosure);
context->UpdateSessionStoreSessionStorage([]() {});
},
this, StaticPrefs::browser_sessionstore_interval(),
nsITimer::TYPE_ONE_SHOT,
"CanonicalBrowsingContext::MaybeScheduleSessionStoreUpdate"_ns);
if (result.isErr()) {
return;
}
mSessionStoreSessionStorageUpdateTimer = result.unwrap();
}
}
void CanonicalBrowsingContext::CancelSessionStoreUpdate() {
if (mSessionStoreSessionStorageUpdateTimer) {
mSessionStoreSessionStorageUpdateTimer->Cancel();
mSessionStoreSessionStorageUpdateTimer = nullptr;
}
}
void CanonicalBrowsingContext::SetContainerFeaturePolicy(
Maybe<FeaturePolicyInfo>&& aContainerFeaturePolicyInfo) {
mContainerFeaturePolicyInfo = std::move(aContainerFeaturePolicyInfo);
}
already_AddRefed<CanonicalBrowsingContext>
CanonicalBrowsingContext::GetCrossGroupOpener() const {
return Get(mCrossGroupOpenerId);
}
void CanonicalBrowsingContext::SetCrossGroupOpenerId(uint64_t aOpenerId) {
MOZ_DIAGNOSTIC_ASSERT(IsTopContent());
MOZ_DIAGNOSTIC_ASSERT(mCrossGroupOpenerId == 0,
"Can only set CrossGroupOpenerId once");
mCrossGroupOpenerId = aOpenerId;
}
void CanonicalBrowsingContext::SetCrossGroupOpener(
CanonicalBrowsingContext* aCrossGroupOpener, ErrorResult& aRv) {
if (!IsTopContent()) {
aRv.ThrowNotAllowedError(
"Can only set crossGroupOpener on toplevel content");
return;
}
if (mCrossGroupOpenerId != 0) {
aRv.ThrowNotAllowedError("Can only set crossGroupOpener once");
return;
}
if (!aCrossGroupOpener) {
aRv.ThrowNotAllowedError("Can't set crossGroupOpener to null");
return;
}
SetCrossGroupOpenerId(aCrossGroupOpener->Id());
}
auto CanonicalBrowsingContext::FindUnloadingHost(uint64_t aChildID)
-> nsTArray<UnloadingHost>::iterator {
return std::find_if(
mUnloadingHosts.begin(), mUnloadingHosts.end(),
[&](const auto& host) { return host.mChildID == aChildID; });
}
void CanonicalBrowsingContext::ClearUnloadingHost(uint64_t aChildID) {
// Notify any callbacks which were waiting for the host to finish unloading
// that it has.
auto found = FindUnloadingHost(aChildID);
if (found != mUnloadingHosts.end()) {
auto callbacks = std::move(found->mCallbacks);
mUnloadingHosts.RemoveElementAt(found);
for (const auto& callback : callbacks) {
callback();
}
}
}
void CanonicalBrowsingContext::StartUnloadingHost(uint64_t aChildID) {
MOZ_DIAGNOSTIC_ASSERT(FindUnloadingHost(aChildID) == mUnloadingHosts.end());
mUnloadingHosts.AppendElement(UnloadingHost{aChildID, {}});
}
void CanonicalBrowsingContext::BrowserParentDestroyed(
BrowserParent* aBrowserParent, bool aAbnormalShutdown) {
ClearUnloadingHost(aBrowserParent->Manager()->ChildID());
// Handling specific to when the current BrowserParent has been destroyed.
if (mCurrentBrowserParent == aBrowserParent) {
mCurrentBrowserParent = nullptr;
// If this BrowserParent is for a subframe, attempt to recover from a
// subframe crash by rendering the subframe crashed page in the embedding
// content.
if (aAbnormalShutdown) {
ShowSubframeCrashedUI(aBrowserParent->GetBrowserBridgeParent());
}
}
}
void CanonicalBrowsingContext::ShowSubframeCrashedUI(
BrowserBridgeParent* aBridge) {
if (!aBridge || IsDiscarded() || !aBridge->CanSend()) {
return;
}
MOZ_DIAGNOSTIC_ASSERT(!aBridge->GetBrowsingContext() ||
aBridge->GetBrowsingContext() == this);
// There is no longer a current inner window within this
// BrowsingContext, update the `CurrentInnerWindowId` field to reflect
// this.
MOZ_ALWAYS_SUCCEEDS(SetCurrentInnerWindowId(0));
// The owning process will now be the embedder to render the subframe
// crashed page, switch ownership back over.
SetOwnerProcessId(aBridge->Manager()->Manager()->ChildID());
SetCurrentBrowserParent(aBridge->Manager());
(void)aBridge->SendSubFrameCrashed();
}
static void LogBFCacheBlockingForDoc(BrowsingContext* aBrowsingContext,
uint32_t aBFCacheCombo, bool aIsSubDoc) {
if (aIsSubDoc) {
nsAutoCString uri("[no uri]");
nsCOMPtr<nsIURI> currentURI =
aBrowsingContext->Canonical()->GetCurrentURI();
if (currentURI) {
uri = currentURI->GetSpecOrDefault();
}
MOZ_LOG(gSHIPBFCacheLog, LogLevel::Debug,
(" ** Blocked for document %s", uri.get()));
}
if (aBFCacheCombo & BFCacheStatus::EVENT_HANDLING_SUPPRESSED) {
MOZ_LOG(gSHIPBFCacheLog, LogLevel::Debug,
(" * event handling suppression"));
}
if (aBFCacheCombo & BFCacheStatus::SUSPENDED) {
MOZ_LOG(gSHIPBFCacheLog, LogLevel::Debug, (" * suspended Window"));
}
if (aBFCacheCombo & BFCacheStatus::UNLOAD_LISTENER) {
MOZ_LOG(gSHIPBFCacheLog, LogLevel::Debug, (" * unload listener"));
}
if (aBFCacheCombo & BFCacheStatus::REQUEST) {
MOZ_LOG(gSHIPBFCacheLog, LogLevel::Debug, (" * requests in the loadgroup"));
}
if (aBFCacheCombo & BFCacheStatus::ACTIVE_GET_USER_MEDIA) {
MOZ_LOG(gSHIPBFCacheLog, LogLevel::Debug, (" * GetUserMedia"));
}
if (aBFCacheCombo & BFCacheStatus::ACTIVE_PEER_CONNECTION) {
MOZ_LOG(gSHIPBFCacheLog, LogLevel::Debug, (" * PeerConnection"));
}
if (aBFCacheCombo & BFCacheStatus::CONTAINS_EME_CONTENT) {
MOZ_LOG(gSHIPBFCacheLog, LogLevel::Debug, (" * EME content"));
}
if (aBFCacheCombo & BFCacheStatus::CONTAINS_MSE_CONTENT) {
MOZ_LOG(gSHIPBFCacheLog, LogLevel::Debug, (" * MSE use"));
}
if (aBFCacheCombo & BFCacheStatus::HAS_ACTIVE_SPEECH_SYNTHESIS) {
MOZ_LOG(gSHIPBFCacheLog, LogLevel::Debug, (" * Speech use"));
}
if (aBFCacheCombo & BFCacheStatus::HAS_USED_VR) {
MOZ_LOG(gSHIPBFCacheLog, LogLevel::Debug, (" * used VR"));
}
if (aBFCacheCombo & BFCacheStatus::BEFOREUNLOAD_LISTENER) {
MOZ_LOG(gSHIPBFCacheLog, LogLevel::Debug, (" * beforeunload listener"));
}
if (aBFCacheCombo & BFCacheStatus::ACTIVE_LOCK) {
MOZ_LOG(gSHIPBFCacheLog, LogLevel::Debug, (" * has active Web Locks"));
}
if (aBFCacheCombo & BFCacheStatus::PAGE_LOADING) {
MOZ_LOG(gSHIPBFCacheLog, LogLevel::Debug, (" * has page loading"));
}
}
bool CanonicalBrowsingContext::AllowedInBFCache(
const Maybe<uint64_t>& aChannelId, nsIURI* aNewURI) {
if (MOZ_UNLIKELY(MOZ_LOG_TEST(gSHIPBFCacheLog, LogLevel::Debug))) {
nsAutoCString uri("[no uri]");
nsCOMPtr<nsIURI> currentURI = GetCurrentURI();
if (currentURI) {
uri = currentURI->GetSpecOrDefault();
}
MOZ_LOG(gSHIPBFCacheLog, LogLevel::Debug, ("Checking %s", uri.get()));
}
if (IsInProcess()) {
return false;
}
uint32_t bfcacheCombo = 0;
if (mRestoreState) {
bfcacheCombo |= BFCacheStatus::RESTORING;
MOZ_LOG(gSHIPBFCacheLog, LogLevel::Debug, (" * during session restore"));
}
if (Group()->Toplevels().Length() > 1) {
bfcacheCombo |= BFCacheStatus::NOT_ONLY_TOPLEVEL_IN_BCG;
MOZ_LOG(gSHIPBFCacheLog, LogLevel::Debug,
(" * auxiliary BrowsingContexts"));
}
// There are not a lot of about:* pages that are allowed to load in
// subframes, so it's OK to allow those few about:* pages enter BFCache.
MOZ_ASSERT(IsTop(), "Trying to put a non top level BC into BFCache");
WindowGlobalParent* wgp = GetCurrentWindowGlobal();
if (wgp && wgp->GetDocumentURI()) {
nsCOMPtr<nsIURI> currentURI = wgp->GetDocumentURI();
// Exempt about:* pages from bfcache, with the exception of about:blank
if (currentURI->SchemeIs("about") &&
!NS_IsAboutBlankAllowQueryAndFragment(currentURI)) {
bfcacheCombo |= BFCacheStatus::ABOUT_PAGE;
MOZ_LOG(gSHIPBFCacheLog, LogLevel::Debug, (" * about:* page"));
}
if (aNewURI) {
bool equalUri = false;
aNewURI->Equals(currentURI, &equalUri);
if (equalUri) {
// When loading the same uri, disable bfcache so that
// nsDocShell::OnNewURI transforms the load to LOAD_NORMAL_REPLACE.
return false;
}
}
}
// For telemetry we're collecting all the flags for all the BCs hanging
// from this top-level BC.
PreOrderWalk([&](BrowsingContext* aBrowsingContext) {
WindowGlobalParent* wgp =
aBrowsingContext->Canonical()->GetCurrentWindowGlobal();
uint32_t subDocBFCacheCombo = wgp ? wgp->GetBFCacheStatus() : 0;
if (wgp) {
const Maybe<uint64_t>& singleChannelId = wgp->GetSingleChannelId();
if (singleChannelId.isSome()) {
if (singleChannelId.value() == 0 || aChannelId.isNothing() ||
singleChannelId.value() != aChannelId.value()) {
subDocBFCacheCombo |= BFCacheStatus::REQUEST;
}
}
}
if (MOZ_UNLIKELY(MOZ_LOG_TEST(gSHIPBFCacheLog, LogLevel::Debug))) {
LogBFCacheBlockingForDoc(aBrowsingContext, subDocBFCacheCombo,
aBrowsingContext != this);
}
bfcacheCombo |= subDocBFCacheCombo;
});
nsDocShell::ReportBFCacheComboTelemetry(bfcacheCombo);
if (MOZ_UNLIKELY(MOZ_LOG_TEST(gSHIPBFCacheLog, LogLevel::Debug))) {
nsAutoCString uri("[no uri]");
nsCOMPtr<nsIURI> currentURI = GetCurrentURI();
if (currentURI) {
uri = currentURI->GetSpecOrDefault();
}
MOZ_LOG(gSHIPBFCacheLog, LogLevel::Debug,
(" +> %s %s be blocked from going into the BFCache", uri.get(),
bfcacheCombo == 0 ? "shouldn't" : "should"));
}
if (StaticPrefs::docshell_shistory_bfcache_allow_unload_listeners()) {
bfcacheCombo &= ~BFCacheStatus::UNLOAD_LISTENER;
}
return bfcacheCombo == 0;
}
struct ClearSiteWalkHistoryData {
nsIPrincipal* mPrincipal = nullptr;
bool mShouldClear = false;
};
// static
nsresult CanonicalBrowsingContext::ContainsSameOriginBfcacheEntry(
nsISHEntry* aEntry, mozilla::dom::BrowsingContext* aBC, int32_t aChildIndex,
void* aData) {
if (!aEntry) {
return NS_OK;
}
nsCOMPtr<nsIPrincipal> entryPrincipal;
nsresult rv =
aEntry->GetPartitionedPrincipalToInherit(getter_AddRefs(entryPrincipal));
if (NS_FAILED(rv) || !entryPrincipal) {
return NS_OK;
}
ClearSiteWalkHistoryData* data =
static_cast<ClearSiteWalkHistoryData*>(aData);
if (data->mPrincipal->OriginAttributesRef() ==
entryPrincipal->OriginAttributesRef()) {
nsCOMPtr<nsIURI> entryURI = aEntry->GetURI();
if (data->mPrincipal->IsSameOrigin(entryURI)) {
data->mShouldClear = true;
} else {
nsSHistory::WalkHistoryEntries(aEntry, aBC,
ContainsSameOriginBfcacheEntry, aData);
}
}
return NS_OK;
}
// static
nsresult CanonicalBrowsingContext::ClearBfcacheByPrincipal(
nsIPrincipal* aPrincipal) {
NS_ENSURE_ARG_POINTER(aPrincipal);
MOZ_DIAGNOSTIC_ASSERT(XRE_IsParentProcess());
// Allow disabling the feature if unexpected regressions occur
if (!StaticPrefs::privacy_clearSiteDataHeader_cache_bfcache_enabled()) {
return NS_OK;
}
// Iter through all open tabs by going through all top-level browsing
// contexts.
AutoTArray<RefPtr<BrowsingContextGroup>, 32> groups;
BrowsingContextGroup::GetAllGroups(groups);
for (auto& browsingContextGroup : groups) {
for (auto& topLevel : browsingContextGroup->Toplevels()) {
if (topLevel->IsDiscarded()) {
continue;
}
auto* bc = topLevel->Canonical();
nsSHistory* sh = static_cast<nsSHistory*>(bc->GetSessionHistory());
if (!sh) {
continue;
}
AutoTArray<nsCOMPtr<nsISHEntry>, 4> entriesToDelete;
// We only need to traverse all top-level history items due to bfcache
// only caching top level sites and partitioning origins. If an iframe has
// the same origin, we only want to clear it, if the top level has the
// same origin.
for (nsCOMPtr<nsISHEntry>& entry : sh->Entries()) {
// Determine whether this history entry matches the origin, or contains
// an iframe with that origin
ClearSiteWalkHistoryData data;
data.mPrincipal = aPrincipal;
CanonicalBrowsingContext::ContainsSameOriginBfcacheEntry(entry, nullptr,
0, &data);
if (data.mShouldClear) {
entriesToDelete.AppendElement(entry);
}
}
for (nsCOMPtr<nsISHEntry>& entry : entriesToDelete) {
sh->EvictDocumentViewerForEntry(entry);
}
}
}
return NS_OK;
}
void CanonicalBrowsingContext::SetIsActive(bool aIsActive, ErrorResult& aRv) {
#ifdef DEBUG
if (MOZ_UNLIKELY(!ManuallyManagesActiveness())) {
xpc_DumpJSStack(true, true, false);
MOZ_ASSERT_UNREACHABLE(
"Trying to manually manage activeness of a browsing context that isn't "
"manually managed (see manualactiveness attribute)");
}
#endif
SetIsActiveInternal(aIsActive, aRv);
}
void CanonicalBrowsingContext::SetTouchEventsOverride(
dom::TouchEventsOverride aOverride, ErrorResult& aRv) {
SetTouchEventsOverrideInternal(aOverride, aRv);
}
void CanonicalBrowsingContext::SetTargetTopLevelLinkClicksToBlank(
bool aTargetTopLevelLinkClicksToBlank, ErrorResult& aRv) {
SetTargetTopLevelLinkClicksToBlankInternal(aTargetTopLevelLinkClicksToBlank,
aRv);
}
void CanonicalBrowsingContext::AddPageAwakeRequest() {
MOZ_ASSERT(IsTop());
auto count = GetPageAwakeRequestCount();
MOZ_ASSERT(count < UINT32_MAX);
(void)SetPageAwakeRequestCount(++count);
}
void CanonicalBrowsingContext::RemovePageAwakeRequest() {
MOZ_ASSERT(IsTop());
auto count = GetPageAwakeRequestCount();
MOZ_ASSERT(count > 0);
(void)SetPageAwakeRequestCount(--count);
}
void CanonicalBrowsingContext::CloneDocumentTreeInto(
CanonicalBrowsingContext* aSource, const nsACString& aRemoteType,
embedding::PrintData&& aPrintData) {
NavigationIsolationOptions options;
options.mRemoteType = aRemoteType;
mClonePromise =
ChangeRemoteness(options, /* aPendingSwitchId = */ 0)
->Then(
GetMainThreadSerialEventTarget(), __func__,
[source = MaybeDiscardedBrowsingContext{aSource},
data = std::move(aPrintData)](
const std::pair<RefPtr<BrowserParent>,
RefPtr<CanonicalBrowsingContext>>& aResult)
-> RefPtr<GenericNonExclusivePromise> {
const auto& [browserParent, browsingContext] = aResult;
RefPtr<BrowserBridgeParent> bridge =
browserParent->GetBrowserBridgeParent();
return browserParent
->SendCloneDocumentTreeIntoSelf(source, data)
->Then(
GetMainThreadSerialEventTarget(), __func__,
[bridge](
BrowserParent::CloneDocumentTreeIntoSelfPromise::
ResolveOrRejectValue&& aValue) {
// We're cloning a remote iframe, so we created a
// BrowserBridge which makes us register an OOP load
// (see Document::OOPChildLoadStarted), even though
// this isn't a real load. We call
// SendMaybeFireEmbedderLoadEvents here so that we do
// register the end of the load (see
// Document::OOPChildLoadDone).
if (bridge) {
(void)bridge->SendMaybeFireEmbedderLoadEvents(
EmbedderElementEventType::NoEvent);
}
if (aValue.IsResolve() && aValue.ResolveValue()) {
return GenericNonExclusivePromise::CreateAndResolve(
true, __func__);
}
return GenericNonExclusivePromise::CreateAndReject(
NS_ERROR_FAILURE, __func__);
});
},
[](nsresult aRv) -> RefPtr<GenericNonExclusivePromise> {
NS_WARNING(
nsPrintfCString("Remote clone failed: %x\n", unsigned(aRv))
.get());
return GenericNonExclusivePromise::CreateAndReject(
NS_ERROR_FAILURE, __func__);
});
mClonePromise->Then(
GetMainThreadSerialEventTarget(), __func__,
[self = RefPtr{this}]() { self->mClonePromise = nullptr; });
}
bool CanonicalBrowsingContext::StartApzAutoscroll(float aAnchorX,
float aAnchorY,
nsViewID aScrollId,
uint32_t aPresShellId) {
nsCOMPtr<nsIWidget> widget;
mozilla::layers::LayersId layersId{0};
if (IsInProcess()) {
nsCOMPtr<nsPIDOMWindowOuter> outer = GetDOMWindow();
if (!outer) {
return false;
}
widget = widget::WidgetUtils::DOMWindowToWidget(outer);
if (widget) {
layersId = widget->GetRootLayerTreeId();
}
} else {
RefPtr<BrowserParent> parent = GetBrowserParent();
if (!parent) {
return false;
}
widget = parent->GetWidget();
layersId = parent->GetLayersId();
}
if (!widget || !widget->AsyncPanZoomEnabled()) {
return false;
}
// The anchor coordinates that are passed in are relative to the origin of the
// screen, but we are sending them to APZ which only knows about coordinates
// relative to the widget, so convert them accordingly.
const LayoutDeviceIntPoint anchor =
RoundedToInt(LayoutDevicePoint(aAnchorX, aAnchorY)) -
widget->WidgetToScreenOffset();
mozilla::layers::ScrollableLayerGuid guid(layersId, aPresShellId, aScrollId);
return widget->StartAsyncAutoscroll(
ViewAs<ScreenPixel>(
anchor, PixelCastJustification::LayoutDeviceIsScreenForBounds),
guid);
}
void CanonicalBrowsingContext::StopApzAutoscroll(nsViewID aScrollId,
uint32_t aPresShellId) {
nsCOMPtr<nsIWidget> widget;
mozilla::layers::LayersId layersId{0};
if (IsInProcess()) {
nsCOMPtr<nsPIDOMWindowOuter> outer = GetDOMWindow();
if (!outer) {
return;
}
widget = widget::WidgetUtils::DOMWindowToWidget(outer);
if (widget) {
layersId = widget->GetRootLayerTreeId();
}
} else {
RefPtr<BrowserParent> parent = GetBrowserParent();
if (!parent) {
return;
}
widget = parent->GetWidget();
layersId = parent->GetLayersId();
}
if (!widget || !widget->AsyncPanZoomEnabled()) {
return;
}
mozilla::layers::ScrollableLayerGuid guid(layersId, aPresShellId, aScrollId);
widget->StopAsyncAutoscroll(guid);
}
already_AddRefed<nsISHEntry>
CanonicalBrowsingContext::GetMostRecentLoadingSessionHistoryEntry() {
if (mLoadingEntries.IsEmpty()) {
return nullptr;
}
RefPtr<SessionHistoryEntry> entry = mLoadingEntries.LastElement().mEntry;
return entry.forget();
}
already_AddRefed<BounceTrackingState>
CanonicalBrowsingContext::GetBounceTrackingState() {
if (!mWebProgress) {
return nullptr;
}
return mWebProgress->GetBounceTrackingState();
}
bool CanonicalBrowsingContext::CanOpenModalPicker() {
if (!mozilla::StaticPrefs::browser_disable_pickers_background_tabs()) {
return true;
}
// Alway allows to open picker from chrome.
if (IsChrome()) {
return true;
}
if (!IsActive()) {
return false;
}
mozilla::dom::Element* topFrameElement = GetTopFrameElement();
if (!mozilla::StaticPrefs::
browser_disable_pickers_in_hidden_extension_pages() &&
Windowless()) {
WindowGlobalParent* wgp = GetCurrentWindowGlobal();
if (wgp && BasePrincipal::Cast(wgp->DocumentPrincipal())->AddonPolicy()) {
// This may be a HiddenExtensionPage, e.g. an extension background page.
return true;
}
}
RefPtr<Document> chromeDoc = TopCrossChromeBoundary()->GetExtantDocument();
if (!chromeDoc || !chromeDoc->HasFocus(mozilla::IgnoreErrors())) {
return false;
}
// Only allow web content to open a picker when it has focus. For example, if
// the focus is on the URL bar, web content cannot open a picker, even if it
// is the foreground tab.
// topFrameElement may be a <browser> embedded in another <browser>. In that
// case, verify that the full chain of <browser> elements has focus.
while (topFrameElement) {
RefPtr<Document> doc = topFrameElement->OwnerDoc();
if (doc->GetActiveElement() != topFrameElement) {
return false;
}
topFrameElement = doc->GetBrowsingContext()->GetTopFrameElement();
// Eventually topFrameElement == nullptr, implying that we have reached the
// top browser window (and chromeDoc == doc).
}
return true;
}
bool CanonicalBrowsingContext::ShouldEnforceParentalControls() {
if (StaticPrefs::security_restrict_to_adults_always()) {
return true;
}
if (StaticPrefs::security_restrict_to_adults_respect_platform()) {
bool enabled;
nsCOMPtr<nsIParentalControlsService> pcs =
do_CreateInstance("@mozilla.org/parental-controls-service;1");
nsresult rv = pcs->GetParentalControlsEnabled(&enabled);
if (NS_FAILED(rv)) {
return false;
}
return enabled;
}
return false;
}
void CanonicalBrowsingContext::MaybeReconstructActiveEntryList() {
MOZ_ASSERT(IsTop());
if (!Navigation::IsAPIEnabled()) {
return;
}
auto* shistory = static_cast<nsSHistory*>(GetSessionHistory());
if (mActiveEntry && !shistory->ContainsEntry(mActiveEntry)) {
shistory->ReconstructContiguousEntryList();
}
}
EntryList* CanonicalBrowsingContext::GetActiveEntries() {
if (!mActiveEntryList) {
auto* shistory = static_cast<nsSHistory*>(GetSessionHistory());
if (shistory) {
mActiveEntryList = shistory->EntryListFor(GetHistoryID());
}
}
return mActiveEntryList;
}
already_AddRefed<net::DocumentLoadListener>
CanonicalBrowsingContext::GetCurrentLoad() {
return do_AddRef(this->mCurrentLoad);
}
NS_IMPL_CYCLE_COLLECTION_CLASS(CanonicalBrowsingContext)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(CanonicalBrowsingContext,
BrowsingContext)
tmp->mActiveEntryList = nullptr;
tmp->mPermanentKey.setNull();
if (tmp->mSessionHistory) {
tmp->mSessionHistory->SetBrowsingContext(nullptr);
}
NS_IMPL_CYCLE_COLLECTION_UNLINK(mSessionHistory, mCurrentBrowserParent,
mWebProgress,
mSessionStoreSessionStorageUpdateTimer)
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(CanonicalBrowsingContext,
BrowsingContext)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSessionHistory, mCurrentBrowserParent,
mWebProgress,
mSessionStoreSessionStorageUpdateTimer)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN_INHERITED(CanonicalBrowsingContext,
BrowsingContext)
NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mPermanentKey)
NS_IMPL_CYCLE_COLLECTION_TRACE_END
NS_IMPL_ADDREF_INHERITED(CanonicalBrowsingContext, BrowsingContext)
NS_IMPL_RELEASE_INHERITED(CanonicalBrowsingContext, BrowsingContext)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(CanonicalBrowsingContext)
NS_INTERFACE_MAP_END_INHERITING(BrowsingContext)
} // namespace mozilla::dom
|