DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (d09edbe2abfe)

VCS Links

Line Code
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
/* -*- 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/. */

/*
 * Class for managing loading of a subframe (creation of the docshell,
 * handling of loads in it, recursion-checking).
 */

#include "base/basictypes.h"

#include "prenv.h"

#include "nsDocShell.h"
#include "nsIDOMMozBrowserFrame.h"
#include "nsIDOMWindow.h"
#include "nsIContentInlines.h"
#include "nsIContentViewer.h"
#include "mozilla/dom/Document.h"
#include "nsPIDOMWindow.h"
#include "nsIWebNavigation.h"
#include "nsIWebProgress.h"
#include "nsIDocShell.h"
#include "nsIDocShellTreeOwner.h"
#include "nsDocShellLoadState.h"
#include "nsIBaseWindow.h"
#include "nsIBrowser.h"
#include "nsContentUtils.h"
#include "nsIXPConnect.h"
#include "nsUnicharUtils.h"
#include "nsIScriptGlobalObject.h"
#include "nsIScriptSecurityManager.h"
#include "nsIScrollable.h"
#include "nsFrameLoader.h"
#include "nsFrameLoaderOwner.h"
#include "nsIFrame.h"
#include "nsIScrollableFrame.h"
#include "nsSubDocumentFrame.h"
#include "nsError.h"
#include "nsISHistory.h"
#include "nsIXULWindow.h"
#include "nsIMozBrowserFrame.h"
#include "nsISHistory.h"
#include "nsIScriptError.h"
#include "nsGlobalWindow.h"
#include "nsHTMLDocument.h"
#include "nsPIWindowRoot.h"
#include "nsLayoutUtils.h"
#include "nsMappedAttributes.h"
#include "nsView.h"
#include "nsBaseWidget.h"
#include "nsQueryObject.h"
#include "ReferrerInfo.h"

#include "nsIURI.h"
#include "nsIURL.h"
#include "nsNetUtil.h"

#include "nsGkAtoms.h"
#include "nsNameSpaceManager.h"

#include "nsThreadUtils.h"

#include "nsIDOMChromeWindow.h"
#include "InProcessBrowserChildMessageManager.h"

#include "Layers.h"
#include "ClientLayerManager.h"

#include "ContentParent.h"
#include "BrowserParent.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/ExpandedPrincipal.h"
#include "mozilla/GuardObjects.h"
#include "mozilla/HTMLEditor.h"
#include "mozilla/NullPrincipal.h"
#include "mozilla/Preferences.h"
#include "mozilla/PresShell.h"
#include "mozilla/PresShellInlines.h"
#include "mozilla/Unused.h"
#include "mozilla/dom/ChromeMessageSender.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/FrameCrashedEvent.h"
#include "mozilla/dom/FrameLoaderBinding.h"
#include "mozilla/dom/MozFrameLoaderOwnerBinding.h"
#include "mozilla/dom/SessionStoreListener.h"
#include "mozilla/dom/WindowGlobalParent.h"
#include "mozilla/gfx/CrossProcessPaint.h"
#include "mozilla/jsipc/CrossProcessObjectWrappers.h"
#include "nsGenericHTMLFrameElement.h"
#include "GeckoProfiler.h"

#include "jsapi.h"
#include "mozilla/dom/HTMLIFrameElement.h"
#include "nsSandboxFlags.h"
#include "mozilla/layers/CompositorBridgeChild.h"
#include "mozilla/dom/CustomEvent.h"

#include "mozilla/dom/ipc/StructuredCloneData.h"
#include "mozilla/WebBrowserPersistLocalDocument.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/PromiseNativeHandler.h"
#include "mozilla/dom/ParentSHistory.h"
#include "mozilla/dom/ChildSHistory.h"
#include "mozilla/dom/CanonicalBrowsingContext.h"
#include "mozilla/dom/ContentChild.h"
#include "mozilla/dom/BrowserBridgeChild.h"
#include "mozilla/dom/BrowserHost.h"
#include "mozilla/dom/BrowserBridgeHost.h"

#include "mozilla/dom/HTMLBodyElement.h"

#include "mozilla/ContentPrincipal.h"

#ifdef XP_WIN
#  include "mozilla/plugins/PPluginWidgetParent.h"
#  include "../plugins/ipc/PluginWidgetParent.h"
#endif

#ifdef MOZ_XUL
#  include "nsXULPopupManager.h"
#endif

#ifdef NS_PRINTING
#  include "mozilla/embedding/printingui/PrintingParent.h"
#  include "nsIWebBrowserPrint.h"
#endif

using namespace mozilla;
using namespace mozilla::hal;
using namespace mozilla::dom;
using namespace mozilla::dom::ipc;
using namespace mozilla::layers;
using namespace mozilla::layout;
typedef ScrollableLayerGuid::ViewID ViewID;

// Bug 136580: Limit to the number of nested content frames that can have the
//             same URL. This is to stop content that is recursively loading
//             itself.  Note that "#foo" on the end of URL doesn't affect
//             whether it's considered identical, but "?foo" or ";foo" are
//             considered and compared.
// Limit this to 2, like chromium does.
#define MAX_SAME_URL_CONTENT_FRAMES 2

// Bug 8065: Limit content frame depth to some reasonable level. This
// does not count chrome frames when determining depth, nor does it
// prevent chrome recursion.  Number is fairly arbitrary, but meant to
// keep number of shells to a reasonable number on accidental recursion with a
// small (but not 1) branching factor.  With large branching factors the number
// of shells can rapidly become huge and run us out of memory.  To solve that,
// we'd need to re-institute a fixed version of bug 98158.
#define MAX_DEPTH_CONTENT_FRAMES 10

NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(nsFrameLoader, mBrowsingContext,
                                      mMessageManager, mChildMessageManager,
                                      mParentSHistory, mRemoteBrowser,
                                      mStaticCloneOf)
NS_IMPL_CYCLE_COLLECTING_ADDREF(nsFrameLoader)
NS_IMPL_CYCLE_COLLECTING_RELEASE(nsFrameLoader)

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsFrameLoader)
  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
  NS_INTERFACE_MAP_ENTRY_CONCRETE(nsFrameLoader)
  NS_INTERFACE_MAP_ENTRY(nsIMutationObserver)
  NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END

nsFrameLoader::nsFrameLoader(Element* aOwner, BrowsingContext* aBrowsingContext,
                             const nsAString& aRemoteType, bool aNetworkCreated)
    : mBrowsingContext(aBrowsingContext),
      mOwnerContent(aOwner),
      mDetachedSubdocFrame(nullptr),
      mPendingSwitchID(0),
      mChildID(0),
      mRemoteType(aRemoteType),
      mDepthTooGreat(false),
      mIsTopLevelContent(false),
      mDestroyCalled(false),
      mNeedsAsyncDestroy(false),
      mInSwap(false),
      mInShow(false),
      mHideCalled(false),
      mNetworkCreated(aNetworkCreated),
      mLoadingOriginalSrc(false),
      mRemoteBrowserShown(false),
      mIsRemoteFrame(!aRemoteType.IsEmpty()),
      mObservingOwnerContent(false),
      mTabProcessCrashFired(false) {}

nsFrameLoader::~nsFrameLoader() {
  if (mMessageManager) {
    mMessageManager->Disconnect();
  }
  MOZ_RELEASE_ASSERT(mDestroyCalled);
}

static nsAtom* TypeAttrName(Element* aOwnerContent) {
  return aOwnerContent->IsXULElement() ? nsGkAtoms::type
                                       : nsGkAtoms::mozframetype;
}

static void GetFrameName(Element* aOwnerContent, nsAString& aFrameName) {
  int32_t namespaceID = aOwnerContent->GetNameSpaceID();
  if (namespaceID == kNameSpaceID_XHTML && !aOwnerContent->IsInHTMLDocument()) {
    aOwnerContent->GetAttr(kNameSpaceID_None, nsGkAtoms::id, aFrameName);
  } else {
    aOwnerContent->GetAttr(kNameSpaceID_None, nsGkAtoms::name, aFrameName);
    // XXX if no NAME then use ID, after a transition period this will be
    // changed so that XUL only uses ID too (bug 254284).
    if (aFrameName.IsEmpty() && namespaceID == kNameSpaceID_XUL) {
      aOwnerContent->GetAttr(kNameSpaceID_None, nsGkAtoms::id, aFrameName);
    }
  }
}

// If this method returns true, the nsFrameLoader will act as a boundary, as is
// the case for <iframe mozbrowser> and <browser type="content"> elements.
//
// # Historical Notes  (10 April 2019)
//
// In the past, this boundary was defined by the "typeContent" and "typeChrome"
// nsIDocShellTreeItem types. There was only ever a single split in the tree,
// and it occurred at the boundary between these two types of docshells. When
// <iframe mozbrowser> was introduced, it was given special casing to make it
// act like a second boundary, without having to change the existing code.
//
// The about:addons page, which is loaded within a content browser, then added a
// remote <browser type="content" remote="true"> element. When remote, this
// would also act as a mechanism for creating a disjoint tree, due to the
// process keeping the embedder and embedee separate.
//
// However, when initial out-of-process iframe support was implemented, this
// codepath became a risk, as it could've caused the oop iframe remote
// WindowProxy code to be activated for the addons page. This was fixed by
// extendng the isolation logic previously reserved to <iframe mozbrowser> to
// also cover <browser> elements with the explicit `remote` property loaded in
// content.
//
// To keep these boundaries clear, and allow them to work in a cross-process
// manner, they are no longer handled by typeContent and typeChrome. Instead,
// the actual BrowsingContext tree is broken at these edges.
static bool IsTopContent(BrowsingContext* aParent, Element* aOwner) {
  nsCOMPtr<nsIMozBrowserFrame> mozbrowser = aOwner->GetAsMozBrowserFrame();

  if (aParent->IsContent()) {
    // If we're already in content, we may still want to create a new
    // BrowsingContext tree if our element is either:
    //  a) a real <iframe mozbrowser> frame, or
    //  b) a xul browser element with a `remote="true"` marker.
    return (mozbrowser && mozbrowser->GetReallyIsBrowser()) ||
           (aOwner->IsXULElement() &&
            aOwner->AttrValueIs(kNameSpaceID_None, nsGkAtoms::remote,
                                nsGkAtoms::_true, eCaseMatters));
  }

  // If we're in a chrome context, we want to start a new tree if:
  //  a) we have any mozbrowser frame (even if disabled), or
  //  b) we are an element with a `type="content"` marker.
  return (mozbrowser && mozbrowser->GetMozbrowser()) ||
         (aOwner->AttrValueIs(kNameSpaceID_None, TypeAttrName(aOwner),
                              nsGkAtoms::content, eIgnoreCase));
}

static already_AddRefed<BrowsingContext> CreateBrowsingContext(
    Element* aOwner, BrowsingContext* aOpener) {
  Document* doc = aOwner->OwnerDoc();
  // Get our parent docshell off the document of mOwnerContent
  // XXXbz this is such a total hack.... We really need to have a
  // better setup for doing this.

  // Determine our parent nsDocShell
  RefPtr<nsDocShell> parentDocShell = nsDocShell::Cast(doc->GetDocShell());

  if (NS_WARN_IF(!parentDocShell)) {
    return nullptr;
  }

  RefPtr<BrowsingContext> parentContext = parentDocShell->GetBrowsingContext();

  // Don't create a child docshell for a discarded browsing context.
  if (NS_WARN_IF(!parentContext) || parentContext->IsDiscarded()) {
    return nullptr;
  }

  // Determine the frame name for the new browsing context.
  nsAutoString frameName;
  GetFrameName(aOwner, frameName);

  if (IsTopContent(parentContext, aOwner)) {
    // Create toplevel content without a parent & as Type::Content.
    return BrowsingContext::Create(nullptr, aOpener, frameName,
                                   BrowsingContext::Type::Content);
  }

  auto type = parentContext->IsContent() ? BrowsingContext::Type::Content
                                         : BrowsingContext::Type::Chrome;

  return BrowsingContext::Create(parentContext, aOpener, frameName, type);
}

static bool InitialLoadIsRemote(Element* aOwner) {
  if (PR_GetEnv("MOZ_DISABLE_OOP_TABS") ||
      Preferences::GetBool("dom.ipc.tabs.disabled", false)) {
    return false;
  }

  // The initial load in an content process iframe should never be made remote.
  // Content process iframes always become remote due to navigation.
  if (XRE_IsContentProcess()) {
    return false;
  }

  // If we're an <iframe mozbrowser> and we don't have a "remote" attribute,
  // fall back to the default.
  nsCOMPtr<nsIMozBrowserFrame> browserFrame = do_QueryInterface(aOwner);
  bool isMozBrowserFrame = browserFrame && browserFrame->GetReallyIsBrowser();
  if (isMozBrowserFrame &&
      !aOwner->HasAttr(kNameSpaceID_None, nsGkAtoms::remote)) {
    return Preferences::GetBool("dom.ipc.browser_frames.oop_by_default", false);
  }

  // Otherwise, we're remote if we have "remote=true" and we're either a
  // browser frame or a XUL element.
  return (isMozBrowserFrame || aOwner->GetNameSpaceID() == kNameSpaceID_XUL) &&
         aOwner->AttrValueIs(kNameSpaceID_None, nsGkAtoms::remote,
                             nsGkAtoms::_true, eCaseMatters);
}

already_AddRefed<nsFrameLoader> nsFrameLoader::Create(Element* aOwner,
                                                      BrowsingContext* aOpener,
                                                      bool aNetworkCreated) {
  NS_ENSURE_TRUE(aOwner, nullptr);
  Document* doc = aOwner->OwnerDoc();

  // We never create nsFrameLoaders for elements in resource documents.
  //
  // We never create nsFrameLoaders for elements in data documents, unless the
  // document is a static document.
  // Static documents are an exception because any sub-documents need an
  // nsFrameLoader to keep the relevant docShell alive, even though the
  // nsFrameLoader isn't used to load anything (the sub-document is created by
  // the static clone process).
  //
  // We never create nsFrameLoaders for elements that are not
  // in-composed-document, unless the element belongs to a static document.
  // Static documents are an exception because this method is called at a point
  // in the static clone process before aOwner has been inserted into its
  // document.  For other types of documents this wouldn't be a problem since
  // we'd create the nsFrameLoader as necessary after aOwner is inserted into a
  // document, but the mechanisms that take care of that don't apply for static
  // documents so we need to create the nsFrameLoader now. (This isn't wasteful
  // since for a static document we know aOwner will end up in a document and
  // the nsFrameLoader will be used for its docShell.)
  //
  NS_ENSURE_TRUE(!doc->IsResourceDoc() &&
                     ((!doc->IsLoadedAsData() && aOwner->IsInComposedDoc()) ||
                      doc->IsStaticDocument()),
                 nullptr);

  RefPtr<BrowsingContext> context = CreateBrowsingContext(aOwner, aOpener);
  NS_ENSURE_TRUE(context, nullptr);

  // Determine the initial RemoteType from the load environment. An empty or
  // void remote type denotes a non-remote frame, while a named remote type
  // denotes a remote frame.
  nsAutoString remoteType(VoidString());
  if (InitialLoadIsRemote(aOwner)) {
    MOZ_ASSERT(!aOpener, "Cannot pass `aOpener` for a remote frame!");

    // If the `remoteType` attribute is specified and valid, use it. Otherwise,
    // use a default remote type.
    bool hasRemoteType =
        aOwner->GetAttr(kNameSpaceID_None, nsGkAtoms::RemoteType, remoteType);
    if (!hasRemoteType || remoteType.IsEmpty()) {
      remoteType.AssignLiteral(DEFAULT_REMOTE_TYPE);
    }
  }

  RefPtr<nsFrameLoader> fl =
      new nsFrameLoader(aOwner, context, remoteType, aNetworkCreated);
  return fl.forget();
}

/* static */
already_AddRefed<nsFrameLoader> nsFrameLoader::Recreate(
    mozilla::dom::Element* aOwner, BrowsingContext* aContext,
    const nsAString& aRemoteType, bool aNetworkCreated) {
  NS_ENSURE_TRUE(aOwner, nullptr);

#ifdef DEBUG
  // This version of Create is only called for Remoteness updates, so we can
  // assume we need a FrameLoader here and skip the check in the other Create.
  Document* doc = aOwner->OwnerDoc();
  MOZ_ASSERT(!doc->IsResourceDoc());
  MOZ_ASSERT((!doc->IsLoadedAsData() && aOwner->IsInComposedDoc()) ||
             doc->IsStaticDocument());
#endif

  RefPtr<BrowsingContext> context = aContext;
  if (!context) {
    context = CreateBrowsingContext(aOwner, /* opener */ nullptr);
  }
  NS_ENSURE_TRUE(context, nullptr);

  RefPtr<nsFrameLoader> fl =
      new nsFrameLoader(aOwner, context, aRemoteType, aNetworkCreated);
  return fl.forget();
}

void nsFrameLoader::LoadFrame(bool aOriginalSrc) {
  if (NS_WARN_IF(!mOwnerContent)) {
    return;
  }

  nsAutoString src;
  nsCOMPtr<nsIPrincipal> principal;
  nsCOMPtr<nsIContentSecurityPolicy> csp;

  bool isSrcdoc = mOwnerContent->IsHTMLElement(nsGkAtoms::iframe) &&
                  mOwnerContent->HasAttr(kNameSpaceID_None, nsGkAtoms::srcdoc);
  if (isSrcdoc) {
    src.AssignLiteral("about:srcdoc");
    principal = mOwnerContent->NodePrincipal();
    csp = mOwnerContent->GetCsp();
  } else {
    GetURL(src, getter_AddRefs(principal), getter_AddRefs(csp));

    src.Trim(" \t\n\r");

    if (src.IsEmpty()) {
      // If the frame is a XUL element and has the attribute 'nodefaultsrc=true'
      // then we will not use 'about:blank' as fallback but return early without
      // starting a load if no 'src' attribute is given (or it's empty).
      if (mOwnerContent->IsXULElement() &&
          mOwnerContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::nodefaultsrc,
                                     nsGkAtoms::_true, eCaseMatters)) {
        return;
      }
      src.AssignLiteral("about:blank");
      principal = mOwnerContent->NodePrincipal();
      csp = mOwnerContent->GetCsp();
    }
  }

  Document* doc = mOwnerContent->OwnerDoc();
  if (doc->IsStaticDocument()) {
    return;
  }

  if (doc->IsLoadedAsInteractiveData()) {
    // XBL bindings doc shouldn't load sub-documents.
    return;
  }

  nsIURI* base_uri = mOwnerContent->GetBaseURI();
  auto encoding = doc->GetDocumentCharacterSet();

  nsCOMPtr<nsIURI> uri;
  nsresult rv = NS_NewURI(getter_AddRefs(uri), src, encoding, base_uri);

  // If the URI was malformed, try to recover by loading about:blank.
  if (rv == NS_ERROR_MALFORMED_URI) {
    rv = NS_NewURI(getter_AddRefs(uri), NS_LITERAL_STRING("about:blank"),
                   encoding, base_uri);
  }

  if (NS_SUCCEEDED(rv)) {
    rv = LoadURI(uri, principal, csp, aOriginalSrc);
  }

  if (NS_FAILED(rv)) {
    FireErrorEvent();
  }
}

void nsFrameLoader::FireErrorEvent() {
  if (!mOwnerContent) {
    return;
  }
  RefPtr<AsyncEventDispatcher> loadBlockingAsyncDispatcher =
      new LoadBlockingAsyncEventDispatcher(
          mOwnerContent, NS_LITERAL_STRING("error"), CanBubble::eNo,
          ChromeOnlyDispatch::eNo);
  loadBlockingAsyncDispatcher->PostDOMEvent();
}

nsresult nsFrameLoader::LoadURI(nsIURI* aURI,
                                nsIPrincipal* aTriggeringPrincipal,
                                nsIContentSecurityPolicy* aCsp,
                                bool aOriginalSrc) {
  if (!aURI) return NS_ERROR_INVALID_POINTER;
  NS_ENSURE_STATE(!mDestroyCalled && mOwnerContent);
  MOZ_ASSERT(
      aTriggeringPrincipal,
      "Must have an explicit triggeringPrincipal to nsFrameLoader::LoadURI.");

  mLoadingOriginalSrc = aOriginalSrc;

  nsCOMPtr<Document> doc = mOwnerContent->OwnerDoc();

  nsresult rv;
  rv = CheckURILoad(aURI, aTriggeringPrincipal);
  NS_ENSURE_SUCCESS(rv, rv);

  mURIToLoad = aURI;
  mTriggeringPrincipal = aTriggeringPrincipal;
  mCsp = aCsp;
  rv = doc->InitializeFrameLoader(this);
  if (NS_FAILED(rv)) {
    mURIToLoad = nullptr;
    mTriggeringPrincipal = nullptr;
    mCsp = nullptr;
  }
  return rv;
}

void nsFrameLoader::ResumeLoad(uint64_t aPendingSwitchID) {
  Document* doc = mOwnerContent->OwnerDoc();
  if (doc->IsStaticDocument() || doc->IsLoadedAsInteractiveData()) {
    // Static & XBL bindings doc shouldn't load sub-documents.
    return;
  }

  if (NS_WARN_IF(mDestroyCalled || !mOwnerContent)) {
    FireErrorEvent();
    return;
  }

  mLoadingOriginalSrc = false;
  mURIToLoad = nullptr;
  mPendingSwitchID = aPendingSwitchID;
  mTriggeringPrincipal = mOwnerContent->NodePrincipal();
  mCsp = mOwnerContent->GetCsp();

  nsresult rv = doc->InitializeFrameLoader(this);
  if (NS_FAILED(rv)) {
    mPendingSwitchID = 0;
    mTriggeringPrincipal = nullptr;
    mCsp = nullptr;

    FireErrorEvent();
  }
}

nsresult nsFrameLoader::ReallyStartLoading() {
  nsresult rv = ReallyStartLoadingInternal();
  if (NS_FAILED(rv)) {
    FireErrorEvent();
  }

  return rv;
}

nsresult nsFrameLoader::ReallyStartLoadingInternal() {
  NS_ENSURE_STATE((mURIToLoad || mPendingSwitchID) && mOwnerContent &&
                  mOwnerContent->IsInComposedDoc());

  AUTO_PROFILER_LABEL("nsFrameLoader::ReallyStartLoadingInternal", OTHER);

  if (IsRemoteFrame()) {
    if (!EnsureRemoteBrowser()) {
      NS_WARNING("Couldn't create child process for iframe.");
      return NS_ERROR_FAILURE;
    }

    if (mPendingSwitchID) {
      mRemoteBrowser->ResumeLoad(mPendingSwitchID);
      mPendingSwitchID = 0;
    } else {
      mRemoteBrowser->LoadURL(mURIToLoad);
    }

    if (!mRemoteBrowserShown) {
      // This can fail if it's too early to show the frame, we will retry later.
      Unused << ShowRemoteFrame(ScreenIntSize(0, 0));
    }

    return NS_OK;
  }

  if (GetDocShell()) {
    // If we already have a docshell, ensure that the docshell's storage access
    // flag is cleared.
    GetDocShell()->MaybeClearStorageAccessFlag();
  }

  nsresult rv = MaybeCreateDocShell();
  if (NS_FAILED(rv)) {
    return rv;
  }
  MOZ_ASSERT(GetDocShell(),
             "MaybeCreateDocShell succeeded with a null docShell");

  // If we have a pending switch, just resume our load.
  if (mPendingSwitchID) {
    bool tmpState = mNeedsAsyncDestroy;
    mNeedsAsyncDestroy = true;
    rv = GetDocShell()->ResumeRedirectedLoad(mPendingSwitchID, -1);
    mNeedsAsyncDestroy = tmpState;
    mPendingSwitchID = 0;
    return rv;
  }

  // Just to be safe, recheck uri.
  rv = CheckURILoad(mURIToLoad, mTriggeringPrincipal);
  NS_ENSURE_SUCCESS(rv, rv);

  RefPtr<nsDocShellLoadState> loadState = new nsDocShellLoadState(mURIToLoad);

  loadState->SetOriginalFrameSrc(mLoadingOriginalSrc);
  mLoadingOriginalSrc = false;

  // If this frame is sandboxed with respect to origin we will set it up with
  // a null principal later in nsDocShell::DoURILoad.
  // We do it there to correctly sandbox content that was loaded into
  // the frame via other methods than the src attribute.
  // We'll use our principal, not that of the document loaded inside us.  This
  // is very important; needed to prevent XSS attacks on documents loaded in
  // subframes!
  if (mTriggeringPrincipal) {
    loadState->SetTriggeringPrincipal(mTriggeringPrincipal);
  } else {
    loadState->SetTriggeringPrincipal(mOwnerContent->NodePrincipal());
  }

  // If we have an explicit CSP, we set it. If not, we only query it from
  // the document in case there was no explicit triggeringPrincipal.
  // Otherwise it's possible that the original triggeringPrincipal did not
  // have a CSP which causes the CSP on the Principal and explicit CSP
  // to be out of sync.
  if (mCsp) {
    loadState->SetCsp(mCsp);
  } else if (!mTriggeringPrincipal) {
    nsCOMPtr<nsIContentSecurityPolicy> csp = mOwnerContent->GetCsp();
    loadState->SetCsp(csp);
  }

  nsAutoString srcdoc;
  bool isSrcdoc =
      mOwnerContent->IsHTMLElement(nsGkAtoms::iframe) &&
      mOwnerContent->GetAttr(kNameSpaceID_None, nsGkAtoms::srcdoc, srcdoc);

  if (isSrcdoc) {
    loadState->SetSrcdocData(srcdoc);
    loadState->SetBaseURI(mOwnerContent->GetBaseURI());
  }

  nsCOMPtr<nsIReferrerInfo> referrerInfo = new ReferrerInfo();
  referrerInfo->InitWithNode(mOwnerContent);
  loadState->SetReferrerInfo(referrerInfo);

  // Default flags:
  int32_t flags = nsIWebNavigation::LOAD_FLAGS_NONE;

  // Flags for browser frame:
  if (OwnerIsMozBrowserFrame()) {
    flags = nsIWebNavigation::LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP |
            nsIWebNavigation::LOAD_FLAGS_DISALLOW_INHERIT_PRINCIPAL;
  }

  loadState->SetIsFromProcessingFrameAttributes();

  // Kick off the load...
  bool tmpState = mNeedsAsyncDestroy;
  mNeedsAsyncDestroy = true;
  loadState->SetLoadFlags(flags);
  loadState->SetFirstParty(false);
  rv = GetDocShell()->LoadURI(loadState);
  mNeedsAsyncDestroy = tmpState;
  mURIToLoad = nullptr;
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}

nsresult nsFrameLoader::CheckURILoad(nsIURI* aURI,
                                     nsIPrincipal* aTriggeringPrincipal) {
  // Check for security.  The fun part is trying to figure out what principals
  // to use.  The way I figure it, if we're doing a LoadFrame() accidentally
  // (eg someone created a frame/iframe node, we're being parsed, XUL iframes
  // are being reframed, etc.) then we definitely want to use the node
  // principal of mOwnerContent for security checks.  If, on the other hand,
  // someone's setting the src on our owner content, or created it via script,
  // or whatever, then they can clearly access it... and we should still use
  // the principal of mOwnerContent.  I don't think that leads to privilege
  // escalation, and it's reasonably guaranteed to not lead to XSS issues
  // (since caller can already access mOwnerContent in this case).  So just use
  // the principal of mOwnerContent no matter what.  If script wants to run
  // things with its own permissions, which differ from those of mOwnerContent
  // (which means the script is privileged in some way) it should set
  // window.location instead.
  nsIScriptSecurityManager* secMan = nsContentUtils::GetSecurityManager();

  // Get our principal
  nsIPrincipal* principal =
      (aTriggeringPrincipal ? aTriggeringPrincipal
                            : mOwnerContent->NodePrincipal());

  // Check if we are allowed to load absURL
  nsresult rv = secMan->CheckLoadURIWithPrincipal(
      principal, aURI, nsIScriptSecurityManager::STANDARD);
  if (NS_FAILED(rv)) {
    return rv;  // We're not
  }

  // Bail out if this is an infinite recursion scenario
  if (IsRemoteFrame()) {
    return NS_OK;
  }
  return CheckForRecursiveLoad(aURI);
}

nsDocShell* nsFrameLoader::GetDocShell(ErrorResult& aRv) {
  if (IsRemoteFrame()) {
    return nullptr;
  }

  // If we have an owner, make sure we have a docshell and return
  // that. If not, we're most likely in the middle of being torn down,
  // then we just return null.
  if (mOwnerContent) {
    nsresult rv = MaybeCreateDocShell();
    if (NS_FAILED(rv)) {
      aRv.Throw(rv);
      return nullptr;
    }
    MOZ_ASSERT(GetDocShell(),
               "MaybeCreateDocShell succeeded, but null docShell");
  }

  return GetDocShell();
}

static void SetTreeOwnerAndChromeEventHandlerOnDocshellTree(
    nsIDocShellTreeItem* aItem, nsIDocShellTreeOwner* aOwner,
    EventTarget* aHandler) {
  MOZ_ASSERT(aItem, "Must have item");

  aItem->SetTreeOwner(aOwner);

  int32_t childCount = 0;
  aItem->GetInProcessChildCount(&childCount);
  for (int32_t i = 0; i < childCount; ++i) {
    nsCOMPtr<nsIDocShellTreeItem> item;
    aItem->GetInProcessChildAt(i, getter_AddRefs(item));
    if (aHandler) {
      nsCOMPtr<nsIDocShell> shell(do_QueryInterface(item));
      shell->SetChromeEventHandler(aHandler);
    }
    SetTreeOwnerAndChromeEventHandlerOnDocshellTree(item, aOwner, aHandler);
  }
}

#if defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
static bool CheckDocShellType(mozilla::dom::Element* aOwnerContent,
                              nsIDocShellTreeItem* aDocShell, nsAtom* aAtom) {
  bool isContent = aOwnerContent->AttrValueIs(kNameSpaceID_None, aAtom,
                                              nsGkAtoms::content, eIgnoreCase);

  if (!isContent) {
    nsCOMPtr<nsIMozBrowserFrame> mozbrowser =
        aOwnerContent->GetAsMozBrowserFrame();
    if (mozbrowser) {
      mozbrowser->GetMozbrowser(&isContent);
    }
  }

  if (isContent) {
    return aDocShell->ItemType() == nsIDocShellTreeItem::typeContent;
  }

  nsCOMPtr<nsIDocShellTreeItem> parent;
  aDocShell->GetInProcessParent(getter_AddRefs(parent));

  return parent && parent->ItemType() == aDocShell->ItemType();
}
#endif  // defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)

/**
 * Hook up a given TreeItem to its tree owner. aItem's type must have already
 * been set, and it should already be part of the DocShellTree.
 * @param aItem the treeitem we're working with
 * @param aTreeOwner the relevant treeowner; might be null
 */
void nsFrameLoader::AddTreeItemToTreeOwner(nsIDocShellTreeItem* aItem,
                                           nsIDocShellTreeOwner* aOwner) {
  MOZ_ASSERT(aItem, "Must have docshell treeitem");
  MOZ_ASSERT(mOwnerContent, "Must have owning content");

  MOZ_DIAGNOSTIC_ASSERT(
      CheckDocShellType(mOwnerContent, aItem, TypeAttrName(mOwnerContent)),
      "Correct ItemType should be set when creating BrowsingContext");

  if (mIsTopLevelContent) {
    bool is_primary = mOwnerContent->AttrValueIs(
        kNameSpaceID_None, nsGkAtoms::primary, nsGkAtoms::_true, eIgnoreCase);
    if (aOwner) {
      mOwnerContent->AddMutationObserver(this);
      mObservingOwnerContent = true;
      aOwner->ContentShellAdded(aItem, is_primary);
    }
  }
}

static bool AllDescendantsOfType(nsIDocShellTreeItem* aParentItem,
                                 int32_t aType) {
  int32_t childCount = 0;
  aParentItem->GetInProcessChildCount(&childCount);

  for (int32_t i = 0; i < childCount; ++i) {
    nsCOMPtr<nsIDocShellTreeItem> kid;
    aParentItem->GetInProcessChildAt(i, getter_AddRefs(kid));

    if (kid->ItemType() != aType || !AllDescendantsOfType(kid, aType)) {
      return false;
    }
  }

  return true;
}

/**
 * A class that automatically sets mInShow to false when it goes
 * out of scope.
 */
class MOZ_RAII AutoResetInShow {
 private:
  nsFrameLoader* mFrameLoader;
  MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
 public:
  explicit AutoResetInShow(
      nsFrameLoader* aFrameLoader MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
      : mFrameLoader(aFrameLoader) {
    MOZ_GUARD_OBJECT_NOTIFIER_INIT;
  }
  ~AutoResetInShow() { mFrameLoader->mInShow = false; }
};

static bool ParentWindowIsActive(Document* aDoc) {
  nsCOMPtr<nsPIWindowRoot> root = nsContentUtils::GetWindowRoot(aDoc);
  if (root) {
    nsPIDOMWindowOuter* rootWin = root->GetWindow();
    return rootWin && rootWin->IsActive();
  }
  return false;
}

void nsFrameLoader::MaybeShowFrame() {
  nsIFrame* frame = GetPrimaryFrameOfOwningContent();
  if (frame) {
    nsSubDocumentFrame* subDocFrame = do_QueryFrame(frame);
    if (subDocFrame) {
      subDocFrame->MaybeShowViewer();
    }
  }
}

bool nsFrameLoader::Show(int32_t marginWidth, int32_t marginHeight,
                         int32_t scrollbarPrefX, int32_t scrollbarPrefY,
                         nsSubDocumentFrame* frame) {
  if (mInShow) {
    return false;
  }
  // Reset mInShow if we exit early.
  AutoResetInShow resetInShow(this);
  mInShow = true;

  ScreenIntSize size = frame->GetSubdocumentSize();
  if (IsRemoteFrame()) {
    return ShowRemoteFrame(size, frame);
  }

  nsresult rv = MaybeCreateDocShell();
  if (NS_FAILED(rv)) {
    return false;
  }
  MOZ_ASSERT(GetDocShell(), "MaybeCreateDocShell succeeded, but null docShell");
  if (!GetDocShell()) {
    return false;
  }

  GetDocShell()->SetMarginWidth(marginWidth);
  GetDocShell()->SetMarginHeight(marginHeight);

  GetDocShell()->SetDefaultScrollbarPreferences(
      nsIScrollable::ScrollOrientation_X, scrollbarPrefX);
  GetDocShell()->SetDefaultScrollbarPreferences(
      nsIScrollable::ScrollOrientation_Y, scrollbarPrefY);

  if (PresShell* presShell = GetDocShell()->GetPresShell()) {
    // Ensure root scroll frame is reflowed in case scroll preferences or
    // margins have changed
    nsIFrame* rootScrollFrame = presShell->GetRootScrollFrame();
    if (rootScrollFrame) {
      presShell->FrameNeedsReflow(rootScrollFrame, IntrinsicDirty::Resize,
                                  NS_FRAME_IS_DIRTY);
    }
    return true;
  }

  nsView* view = frame->EnsureInnerView();
  if (!view) return false;

  RefPtr<nsDocShell> baseWindow = GetDocShell();
  baseWindow->InitWindow(nullptr, view->GetWidget(), 0, 0, size.width,
                         size.height);
  // This is kinda whacky, this "Create()" call doesn't really
  // create anything, one starts to wonder why this was named
  // "Create"...
  baseWindow->Create();
  baseWindow->SetVisibility(true);
  NS_ENSURE_TRUE(GetDocShell(), false);

  // Trigger editor re-initialization if midas is turned on in the
  // sub-document. This shouldn't be necessary, but given the way our
  // editor works, it is. See
  // https://bugzilla.mozilla.org/show_bug.cgi?id=284245
  if (RefPtr<PresShell> presShell = GetDocShell()->GetPresShell()) {
    Document* doc = presShell->GetDocument();
    nsHTMLDocument* htmlDoc =
        doc && doc->IsHTMLOrXHTML() ? doc->AsHTMLDocument() : nullptr;

    if (htmlDoc) {
      nsAutoString designMode;
      htmlDoc->GetDesignMode(designMode);

      if (designMode.EqualsLiteral("on")) {
        // Hold on to the editor object to let the document reattach to the
        // same editor object, instead of creating a new one.
        RefPtr<HTMLEditor> htmlEditor = GetDocShell()->GetHTMLEditor();
        Unused << htmlEditor;
        htmlDoc->SetDesignMode(NS_LITERAL_STRING("off"), Nothing(),
                               IgnoreErrors());

        htmlDoc->SetDesignMode(NS_LITERAL_STRING("on"), Nothing(),
                               IgnoreErrors());
      } else {
        // Re-initialize the presentation for contenteditable documents
        bool editable = false, hasEditingSession = false;
        GetDocShell()->GetEditable(&editable);
        GetDocShell()->GetHasEditingSession(&hasEditingSession);
        RefPtr<HTMLEditor> htmlEditor = GetDocShell()->GetHTMLEditor();
        if (editable && hasEditingSession && htmlEditor) {
          htmlEditor->PostCreate();
        }
      }
    }
  }

  mInShow = false;
  if (mHideCalled) {
    mHideCalled = false;
    Hide();
    return false;
  }
  return true;
}

void nsFrameLoader::MarginsChanged(uint32_t aMarginWidth,
                                   uint32_t aMarginHeight) {
  // We assume that the margins are always zero for remote frames.
  if (IsRemoteFrame()) {
    return;
  }

  // If there's no docshell, we're probably not up and running yet.
  // nsFrameLoader::Show() will take care of setting the right
  // margins.
  if (!GetDocShell()) {
    return;
  }

  // Set the margins
  GetDocShell()->SetMarginWidth(aMarginWidth);
  GetDocShell()->SetMarginHeight(aMarginHeight);

  // There's a cached property declaration block
  // that needs to be updated
  if (Document* doc = GetDocShell()->GetDocument()) {
    for (nsINode* cur = doc; cur; cur = cur->GetNextNode()) {
      if (cur->IsHTMLElement(nsGkAtoms::body)) {
        static_cast<HTMLBodyElement*>(cur)->ClearMappedServoStyle();
      }
    }
  }

  // Trigger a restyle if there's a prescontext
  // FIXME: This could do something much less expensive.
  if (nsPresContext* presContext = GetDocShell()->GetPresContext()) {
    // rebuild, because now the same nsMappedAttributes* will produce
    // a different style
    presContext->RebuildAllStyleData(nsChangeHint(0),
                                     RestyleHint::RestyleSubtree());
  }
}

bool nsFrameLoader::ShowRemoteFrame(const ScreenIntSize& size,
                                    nsSubDocumentFrame* aFrame) {
  AUTO_PROFILER_LABEL("nsFrameLoader::ShowRemoteFrame", OTHER);
  NS_ASSERTION(IsRemoteFrame(),
               "ShowRemote only makes sense on remote frames.");

  if (!EnsureRemoteBrowser()) {
    NS_ERROR("Couldn't create child process.");
    return false;
  }

  // FIXME/bug 589337: Show()/Hide() is pretty expensive for
  // cross-process layers; need to figure out what behavior we really
  // want here.  For now, hack.
  if (!mRemoteBrowserShown) {
    if (!mOwnerContent || !mOwnerContent->GetComposedDoc()) {
      return false;
    }

    // We never want to host remote frameloaders in simple popups, like menus.
    nsIWidget* widget = nsContentUtils::WidgetForContent(mOwnerContent);
    if (!widget || static_cast<nsBaseWidget*>(widget)->IsSmallPopup()) {
      return false;
    }

    if (RefPtr<BrowserBridgeChild> browserBridgeChild =
            GetBrowserBridgeChild()) {
      nsCOMPtr<nsISupports> container =
          mOwnerContent->OwnerDoc()->GetContainer();
      nsCOMPtr<nsIBaseWindow> baseWindow = do_QueryInterface(container);
      nsCOMPtr<nsIWidget> mainWidget;
      baseWindow->GetMainWidget(getter_AddRefs(mainWidget));
      nsSizeMode sizeMode =
          mainWidget ? mainWidget->SizeMode() : nsSizeMode_Normal;

      Unused << browserBridgeChild->SendShow(
          size, ParentWindowIsActive(mOwnerContent->OwnerDoc()), sizeMode);
      mRemoteBrowserShown = true;
      return true;
    }

    if (!mRemoteBrowser->Show(
            size, ParentWindowIsActive(mOwnerContent->OwnerDoc()))) {
      return false;
    }
    mRemoteBrowserShown = true;

    nsCOMPtr<nsIObserverService> os = services::GetObserverService();
    if (os) {
      os->NotifyObservers(ToSupports(this), "remote-browser-shown", nullptr);
    }
  } else {
    nsIntRect dimensions;
    NS_ENSURE_SUCCESS(GetWindowDimensions(dimensions), false);

    // Don't show remote iframe if we are waiting for the completion of reflow.
    if (!aFrame || !(aFrame->GetStateBits() & NS_FRAME_FIRST_REFLOW)) {
      mRemoteBrowser->UpdateDimensions(dimensions, size);
    }
  }

  return true;
}

void nsFrameLoader::Hide() {
  if (mHideCalled) {
    return;
  }
  if (mInShow) {
    mHideCalled = true;
    return;
  }

  if (!GetDocShell()) {
    return;
  }

  GetDocShell()->MaybeClearStorageAccessFlag();

  nsCOMPtr<nsIContentViewer> contentViewer;
  GetDocShell()->GetContentViewer(getter_AddRefs(contentViewer));
  if (contentViewer) contentViewer->SetSticky(false);

  RefPtr<nsDocShell> baseWin = GetDocShell();
  baseWin->SetVisibility(false);
  baseWin->SetParentWidget(nullptr);
}

void nsFrameLoader::ForceLayoutIfNecessary() {
  nsIFrame* frame = GetPrimaryFrameOfOwningContent();
  if (!frame) {
    return;
  }

  nsPresContext* presContext = frame->PresContext();
  if (!presContext) {
    return;
  }

  // Only force the layout flush if the frameloader hasn't ever been
  // run through layout.
  if (frame->GetStateBits() & NS_FRAME_FIRST_REFLOW) {
    if (RefPtr<PresShell> presShell = presContext->GetPresShell()) {
      presShell->FlushPendingNotifications(FlushType::Layout);
    }
  }
}

nsresult nsFrameLoader::SwapWithOtherRemoteLoader(
    nsFrameLoader* aOther, nsFrameLoaderOwner* aThisOwner,
    nsFrameLoaderOwner* aOtherOwner) {
  MOZ_ASSERT(NS_IsMainThread());

#ifdef DEBUG
  RefPtr<nsFrameLoader> first = aThisOwner->GetFrameLoader();
  RefPtr<nsFrameLoader> second = aOtherOwner->GetFrameLoader();
  MOZ_ASSERT(first == this, "aThisOwner must own this");
  MOZ_ASSERT(second == aOther, "aOtherOwner must own aOther");
#endif

  Element* ourContent = mOwnerContent;
  Element* otherContent = aOther->mOwnerContent;

  if (!ourContent || !otherContent) {
    // Can't handle this
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  // Make sure there are no same-origin issues
  bool equal;
  nsresult rv = ourContent->NodePrincipal()->Equals(
      otherContent->NodePrincipal(), &equal);
  if (NS_FAILED(rv) || !equal) {
    // Security problems loom.  Just bail on it all
    return NS_ERROR_DOM_SECURITY_ERR;
  }

  Document* ourDoc = ourContent->GetComposedDoc();
  Document* otherDoc = otherContent->GetComposedDoc();
  if (!ourDoc || !otherDoc) {
    // Again, how odd, given that we had docshells
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  PresShell* ourPresShell = ourDoc->GetPresShell();
  PresShell* otherPresShell = otherDoc->GetPresShell();
  if (!ourPresShell || !otherPresShell) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  auto* browserParent = GetBrowserParent();
  auto* otherBrowserParent = aOther->GetBrowserParent();

  if (!browserParent || !otherBrowserParent) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  // When we swap docShells, maybe we have to deal with a new page created just
  // for this operation. In this case, the browser code should already have set
  // the correct userContextId attribute value in the owning element, but our
  // docShell, that has been created way before) doesn't know that that
  // happened.
  // This is the reason why now we must retrieve the correct value from the
  // usercontextid attribute before comparing our originAttributes with the
  // other one.
  OriginAttributes ourOriginAttributes = browserParent->OriginAttributesRef();
  rv = PopulateUserContextIdFromAttribute(ourOriginAttributes);
  NS_ENSURE_SUCCESS(rv, rv);

  OriginAttributes otherOriginAttributes =
      otherBrowserParent->OriginAttributesRef();
  rv = aOther->PopulateUserContextIdFromAttribute(otherOriginAttributes);
  NS_ENSURE_SUCCESS(rv, rv);

  if (ourOriginAttributes != otherOriginAttributes) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  bool ourHasHistory =
      mIsTopLevelContent && ourContent->IsXULElement(nsGkAtoms::browser) &&
      !ourContent->HasAttr(kNameSpaceID_None, nsGkAtoms::disablehistory);
  bool otherHasHistory =
      aOther->mIsTopLevelContent &&
      otherContent->IsXULElement(nsGkAtoms::browser) &&
      !otherContent->HasAttr(kNameSpaceID_None, nsGkAtoms::disablehistory);
  if (ourHasHistory != otherHasHistory) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  if (mInSwap || aOther->mInSwap) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }
  mInSwap = aOther->mInSwap = true;

  nsIFrame* ourFrame = ourContent->GetPrimaryFrame();
  nsIFrame* otherFrame = otherContent->GetPrimaryFrame();
  if (!ourFrame || !otherFrame) {
    mInSwap = aOther->mInSwap = false;
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  nsSubDocumentFrame* ourFrameFrame = do_QueryFrame(ourFrame);
  if (!ourFrameFrame) {
    mInSwap = aOther->mInSwap = false;
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  rv = ourFrameFrame->BeginSwapDocShells(otherFrame);
  if (NS_FAILED(rv)) {
    mInSwap = aOther->mInSwap = false;
    return rv;
  }

  nsCOMPtr<nsIBrowserDOMWindow> otherBrowserDOMWindow =
      otherBrowserParent->GetBrowserDOMWindow();
  nsCOMPtr<nsIBrowserDOMWindow> browserDOMWindow =
      browserParent->GetBrowserDOMWindow();

  if (!!otherBrowserDOMWindow != !!browserDOMWindow) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  // Destroy browser frame scripts for content leaving a frame with browser API
  if (OwnerIsMozBrowserFrame() && !aOther->OwnerIsMozBrowserFrame()) {
    DestroyBrowserFrameScripts();
  }
  if (!OwnerIsMozBrowserFrame() && aOther->OwnerIsMozBrowserFrame()) {
    aOther->DestroyBrowserFrameScripts();
  }

  otherBrowserParent->SetBrowserDOMWindow(browserDOMWindow);
  browserParent->SetBrowserDOMWindow(otherBrowserDOMWindow);

#ifdef XP_WIN
  // Native plugin windows used by this remote content need to be reparented.
  if (nsPIDOMWindowOuter* newWin = ourDoc->GetWindow()) {
    RefPtr<nsIWidget> newParent =
        nsGlobalWindowOuter::Cast(newWin)->GetMainWidget();
    const ManagedContainer<mozilla::plugins::PPluginWidgetParent>& plugins =
        otherBrowserParent->ManagedPPluginWidgetParent();
    for (auto iter = plugins.ConstIter(); !iter.Done(); iter.Next()) {
      static_cast<mozilla::plugins::PluginWidgetParent*>(iter.Get()->GetKey())
          ->SetParent(newParent);
    }
  }
#endif  // XP_WIN

  MaybeUpdatePrimaryBrowserParent(eBrowserParentRemoved);
  aOther->MaybeUpdatePrimaryBrowserParent(eBrowserParentRemoved);

  SetOwnerContent(otherContent);
  aOther->SetOwnerContent(ourContent);

  browserParent->SetOwnerElement(otherContent);
  otherBrowserParent->SetOwnerElement(ourContent);

  // Update window activation state for the swapped owner content.
  Unused << browserParent->SendParentActivated(
      ParentWindowIsActive(otherContent->OwnerDoc()));
  Unused << otherBrowserParent->SendParentActivated(
      ParentWindowIsActive(ourContent->OwnerDoc()));

  MaybeUpdatePrimaryBrowserParent(eBrowserParentChanged);
  aOther->MaybeUpdatePrimaryBrowserParent(eBrowserParentChanged);

  RefPtr<nsFrameMessageManager> ourMessageManager = mMessageManager;
  RefPtr<nsFrameMessageManager> otherMessageManager = aOther->mMessageManager;
  // Swap and setup things in parent message managers.
  if (ourMessageManager) {
    ourMessageManager->SetCallback(aOther);
  }
  if (otherMessageManager) {
    otherMessageManager->SetCallback(this);
  }
  mMessageManager.swap(aOther->mMessageManager);

  // Perform the actual swap of the internal refptrs. We keep a strong reference
  // to ourselves to make sure we don't die while we overwrite our reference to
  // ourself.
  RefPtr<nsFrameLoader> kungFuDeathGrip(this);
  aThisOwner->SetFrameLoader(aOther);
  aOtherOwner->SetFrameLoader(kungFuDeathGrip);

  ourFrameFrame->EndSwapDocShells(otherFrame);

  ourPresShell->BackingScaleFactorChanged();
  otherPresShell->BackingScaleFactorChanged();

  // Initialize browser API if needed now that owner content has changed.
  InitializeBrowserAPI();
  aOther->InitializeBrowserAPI();

  mInSwap = aOther->mInSwap = false;

  // Send an updated tab context since owner content type may have changed.
  MutableTabContext ourContext;
  rv = GetNewTabContext(&ourContext);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }
  MutableTabContext otherContext;
  rv = aOther->GetNewTabContext(&otherContext);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  Unused << browserParent->SendSwappedWithOtherRemoteLoader(
      ourContext.AsIPCTabContext());
  Unused << otherBrowserParent->SendSwappedWithOtherRemoteLoader(
      otherContext.AsIPCTabContext());
  return NS_OK;
}

class MOZ_RAII AutoResetInFrameSwap final {
 public:
  AutoResetInFrameSwap(
      nsFrameLoader* aThisFrameLoader, nsFrameLoader* aOtherFrameLoader,
      nsDocShell* aThisDocShell, nsDocShell* aOtherDocShell,
      EventTarget* aThisEventTarget,
      EventTarget* aOtherEventTarget MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
      : mThisFrameLoader(aThisFrameLoader),
        mOtherFrameLoader(aOtherFrameLoader),
        mThisDocShell(aThisDocShell),
        mOtherDocShell(aOtherDocShell),
        mThisEventTarget(aThisEventTarget),
        mOtherEventTarget(aOtherEventTarget) {
    MOZ_GUARD_OBJECT_NOTIFIER_INIT;

    mThisFrameLoader->mInSwap = true;
    mOtherFrameLoader->mInSwap = true;
    mThisDocShell->SetInFrameSwap(true);
    mOtherDocShell->SetInFrameSwap(true);

    // Fire pageshow events on still-loading pages, and then fire pagehide
    // events.  Note that we do NOT fire these in the normal way, but just fire
    // them on the chrome event handlers.
    nsContentUtils::FirePageShowEvent(mThisDocShell, mThisEventTarget, false);
    nsContentUtils::FirePageShowEvent(mOtherDocShell, mOtherEventTarget, false);
    nsContentUtils::FirePageHideEvent(mThisDocShell, mThisEventTarget);
    nsContentUtils::FirePageHideEvent(mOtherDocShell, mOtherEventTarget);
  }

  ~AutoResetInFrameSwap() {
    nsContentUtils::FirePageShowEvent(mThisDocShell, mThisEventTarget, true);
    nsContentUtils::FirePageShowEvent(mOtherDocShell, mOtherEventTarget, true);

    mThisFrameLoader->mInSwap = false;
    mOtherFrameLoader->mInSwap = false;
    mThisDocShell->SetInFrameSwap(false);
    mOtherDocShell->SetInFrameSwap(false);
  }

 private:
  RefPtr<nsFrameLoader> mThisFrameLoader;
  RefPtr<nsFrameLoader> mOtherFrameLoader;
  RefPtr<nsDocShell> mThisDocShell;
  RefPtr<nsDocShell> mOtherDocShell;
  nsCOMPtr<EventTarget> mThisEventTarget;
  nsCOMPtr<EventTarget> mOtherEventTarget;
  MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
};

nsresult nsFrameLoader::SwapWithOtherLoader(nsFrameLoader* aOther,
                                            nsFrameLoaderOwner* aThisOwner,
                                            nsFrameLoaderOwner* aOtherOwner) {
#ifdef DEBUG
  RefPtr<nsFrameLoader> first = aThisOwner->GetFrameLoader();
  RefPtr<nsFrameLoader> second = aOtherOwner->GetFrameLoader();
  MOZ_ASSERT(first == this, "aThisOwner must own this");
  MOZ_ASSERT(second == aOther, "aOtherOwner must own aOther");
#endif

  NS_ENSURE_STATE(!mInShow && !aOther->mInShow);

  if (IsRemoteFrame() != aOther->IsRemoteFrame()) {
    NS_WARNING(
        "Swapping remote and non-remote frames is not currently supported");
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  Element* ourContent = mOwnerContent;
  Element* otherContent = aOther->mOwnerContent;

  if (!ourContent || !otherContent) {
    // Can't handle this
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  bool ourHasSrcdoc = ourContent->IsHTMLElement(nsGkAtoms::iframe) &&
                      ourContent->HasAttr(kNameSpaceID_None, nsGkAtoms::srcdoc);
  bool otherHasSrcdoc =
      otherContent->IsHTMLElement(nsGkAtoms::iframe) &&
      otherContent->HasAttr(kNameSpaceID_None, nsGkAtoms::srcdoc);
  if (ourHasSrcdoc || otherHasSrcdoc) {
    // Ignore this case entirely for now, since we support XUL <-> HTML swapping
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  bool ourFullscreenAllowed =
      ourContent->IsXULElement() ||
      (OwnerIsMozBrowserFrame() &&
       (ourContent->HasAttr(kNameSpaceID_None, nsGkAtoms::allowfullscreen) ||
        ourContent->HasAttr(kNameSpaceID_None, nsGkAtoms::mozallowfullscreen)));
  bool otherFullscreenAllowed =
      otherContent->IsXULElement() ||
      (aOther->OwnerIsMozBrowserFrame() &&
       (otherContent->HasAttr(kNameSpaceID_None, nsGkAtoms::allowfullscreen) ||
        otherContent->HasAttr(kNameSpaceID_None,
                              nsGkAtoms::mozallowfullscreen)));
  if (ourFullscreenAllowed != otherFullscreenAllowed) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  bool ourPaymentRequestAllowed =
      ourContent->HasAttr(kNameSpaceID_None, nsGkAtoms::allowpaymentrequest);
  bool otherPaymentRequestAllowed =
      otherContent->HasAttr(kNameSpaceID_None, nsGkAtoms::allowpaymentrequest);
  if (ourPaymentRequestAllowed != otherPaymentRequestAllowed) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  // Divert to a separate path for the remaining steps in the remote case
  if (IsRemoteFrame()) {
    MOZ_ASSERT(aOther->IsRemoteFrame());
    return SwapWithOtherRemoteLoader(aOther, aThisOwner, aOtherOwner);
  }

  // Make sure there are no same-origin issues
  bool equal;
  nsresult rv = ourContent->NodePrincipal()->Equals(
      otherContent->NodePrincipal(), &equal);
  if (NS_FAILED(rv) || !equal) {
    // Security problems loom.  Just bail on it all
    return NS_ERROR_DOM_SECURITY_ERR;
  }

  RefPtr<nsDocShell> ourDocshell =
      static_cast<nsDocShell*>(GetExistingDocShell());
  RefPtr<nsDocShell> otherDocshell =
      static_cast<nsDocShell*>(aOther->GetExistingDocShell());
  if (!ourDocshell || !otherDocshell) {
    // How odd
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  // To avoid having to mess with session history, avoid swapping
  // frameloaders that don't correspond to root same-type docshells,
  // unless both roots have session history disabled.
  nsCOMPtr<nsIDocShellTreeItem> ourRootTreeItem, otherRootTreeItem;
  ourDocshell->GetInProcessSameTypeRootTreeItem(
      getter_AddRefs(ourRootTreeItem));
  otherDocshell->GetInProcessSameTypeRootTreeItem(
      getter_AddRefs(otherRootTreeItem));
  nsCOMPtr<nsIWebNavigation> ourRootWebnav = do_QueryInterface(ourRootTreeItem);
  nsCOMPtr<nsIWebNavigation> otherRootWebnav =
      do_QueryInterface(otherRootTreeItem);

  if (!ourRootWebnav || !otherRootWebnav) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  RefPtr<ChildSHistory> ourHistory = ourRootWebnav->GetSessionHistory();
  RefPtr<ChildSHistory> otherHistory = otherRootWebnav->GetSessionHistory();

  if ((ourRootTreeItem != ourDocshell || otherRootTreeItem != otherDocshell) &&
      (ourHistory || otherHistory)) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  // Also make sure that the two docshells are the same type. Otherwise
  // swapping is certainly not safe. If this needs to be changed then
  // the code below needs to be audited as it assumes identical types.
  int32_t ourType = ourDocshell->ItemType();
  int32_t otherType = otherDocshell->ItemType();
  if (ourType != otherType) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  // One more twist here.  Setting up the right treeowners in a heterogeneous
  // tree is a bit of a pain.  So make sure that if ourType is not
  // nsIDocShellTreeItem::typeContent then all of our descendants are the same
  // type as us.
  if (ourType != nsIDocShellTreeItem::typeContent &&
      (!AllDescendantsOfType(ourDocshell, ourType) ||
       !AllDescendantsOfType(otherDocshell, otherType))) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  // Save off the tree owners, frame elements, chrome event handlers, and
  // docshell and document parents before doing anything else.
  nsCOMPtr<nsIDocShellTreeOwner> ourOwner, otherOwner;
  ourDocshell->GetTreeOwner(getter_AddRefs(ourOwner));
  otherDocshell->GetTreeOwner(getter_AddRefs(otherOwner));
  // Note: it's OK to have null treeowners.

  nsCOMPtr<nsIDocShellTreeItem> ourParentItem, otherParentItem;
  ourDocshell->GetInProcessParent(getter_AddRefs(ourParentItem));
  otherDocshell->GetInProcessParent(getter_AddRefs(otherParentItem));
  if (!ourParentItem || !otherParentItem) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  // Make sure our parents are the same type too
  int32_t ourParentType = ourParentItem->ItemType();
  int32_t otherParentType = otherParentItem->ItemType();
  if (ourParentType != otherParentType) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  nsCOMPtr<nsPIDOMWindowOuter> ourWindow = ourDocshell->GetWindow();
  nsCOMPtr<nsPIDOMWindowOuter> otherWindow = otherDocshell->GetWindow();

  nsCOMPtr<Element> ourFrameElement = ourWindow->GetFrameElementInternal();
  nsCOMPtr<Element> otherFrameElement = otherWindow->GetFrameElementInternal();

  nsCOMPtr<EventTarget> ourChromeEventHandler =
      ourWindow->GetChromeEventHandler();
  nsCOMPtr<EventTarget> otherChromeEventHandler =
      otherWindow->GetChromeEventHandler();

  nsCOMPtr<EventTarget> ourEventTarget = ourWindow->GetParentTarget();
  nsCOMPtr<EventTarget> otherEventTarget = otherWindow->GetParentTarget();

  NS_ASSERTION(SameCOMIdentity(ourFrameElement, ourContent) &&
                   SameCOMIdentity(otherFrameElement, otherContent) &&
                   SameCOMIdentity(ourChromeEventHandler, ourContent) &&
                   SameCOMIdentity(otherChromeEventHandler, otherContent),
               "How did that happen, exactly?");

  nsCOMPtr<Document> ourChildDocument = ourWindow->GetExtantDoc();
  nsCOMPtr<Document> otherChildDocument = otherWindow->GetExtantDoc();
  if (!ourChildDocument || !otherChildDocument) {
    // This shouldn't be happening
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  nsCOMPtr<Document> ourParentDocument =
      ourChildDocument->GetInProcessParentDocument();
  nsCOMPtr<Document> otherParentDocument =
      otherChildDocument->GetInProcessParentDocument();

  // Make sure to swap docshells between the two frames.
  Document* ourDoc = ourContent->GetComposedDoc();
  Document* otherDoc = otherContent->GetComposedDoc();
  if (!ourDoc || !otherDoc) {
    // Again, how odd, given that we had docshells
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  NS_ASSERTION(ourDoc == ourParentDocument, "Unexpected parent document");
  NS_ASSERTION(otherDoc == otherParentDocument, "Unexpected parent document");

  PresShell* ourPresShell = ourDoc->GetPresShell();
  PresShell* otherPresShell = otherDoc->GetPresShell();
  if (!ourPresShell || !otherPresShell) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  // When we swap docShells, maybe we have to deal with a new page created just
  // for this operation. In this case, the browser code should already have set
  // the correct userContextId attribute value in the owning element, but our
  // docShell, that has been created way before) doesn't know that that
  // happened.
  // This is the reason why now we must retrieve the correct value from the
  // usercontextid attribute before comparing our originAttributes with the
  // other one.
  OriginAttributes ourOriginAttributes = ourDocshell->GetOriginAttributes();
  rv = PopulateUserContextIdFromAttribute(ourOriginAttributes);
  NS_ENSURE_SUCCESS(rv, rv);

  OriginAttributes otherOriginAttributes = otherDocshell->GetOriginAttributes();
  rv = aOther->PopulateUserContextIdFromAttribute(otherOriginAttributes);
  NS_ENSURE_SUCCESS(rv, rv);

  if (ourOriginAttributes != otherOriginAttributes) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  if (mInSwap || aOther->mInSwap) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }
  AutoResetInFrameSwap autoFrameSwap(this, aOther, ourDocshell, otherDocshell,
                                     ourEventTarget, otherEventTarget);

  nsIFrame* ourFrame = ourContent->GetPrimaryFrame();
  nsIFrame* otherFrame = otherContent->GetPrimaryFrame();
  if (!ourFrame || !otherFrame) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  nsSubDocumentFrame* ourFrameFrame = do_QueryFrame(ourFrame);
  if (!ourFrameFrame) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  // OK.  First begin to swap the docshells in the two nsIFrames
  rv = ourFrameFrame->BeginSwapDocShells(otherFrame);
  if (NS_FAILED(rv)) {
    return rv;
  }

  // Destroy browser frame scripts for content leaving a frame with browser API
  if (OwnerIsMozBrowserFrame() && !aOther->OwnerIsMozBrowserFrame()) {
    DestroyBrowserFrameScripts();
  }
  if (!OwnerIsMozBrowserFrame() && aOther->OwnerIsMozBrowserFrame()) {
    aOther->DestroyBrowserFrameScripts();
  }

  // Now move the docshells to the right docshell trees.  Note that this
  // resets their treeowners to null.
  ourParentItem->RemoveChild(ourDocshell);
  otherParentItem->RemoveChild(otherDocshell);
  if (ourType == nsIDocShellTreeItem::typeContent) {
    ourOwner->ContentShellRemoved(ourDocshell);
    otherOwner->ContentShellRemoved(otherDocshell);
  }

  ourParentItem->AddChild(otherDocshell);
  otherParentItem->AddChild(ourDocshell);

  // Restore the correct chrome event handlers.
  ourDocshell->SetChromeEventHandler(otherChromeEventHandler);
  otherDocshell->SetChromeEventHandler(ourChromeEventHandler);
  // Restore the correct treeowners
  // (and also chrome event handlers for content frames only).
  SetTreeOwnerAndChromeEventHandlerOnDocshellTree(
      ourDocshell, otherOwner,
      ourType == nsIDocShellTreeItem::typeContent
          ? otherChromeEventHandler.get()
          : nullptr);
  SetTreeOwnerAndChromeEventHandlerOnDocshellTree(
      otherDocshell, ourOwner,
      ourType == nsIDocShellTreeItem::typeContent ? ourChromeEventHandler.get()
                                                  : nullptr);

  // Switch the owner content before we start calling AddTreeItemToTreeOwner.
  // Note that we rely on this to deal with setting mObservingOwnerContent to
  // false and calling RemoveMutationObserver as needed.
  SetOwnerContent(otherContent);
  aOther->SetOwnerContent(ourContent);

  AddTreeItemToTreeOwner(ourDocshell, otherOwner);
  aOther->AddTreeItemToTreeOwner(otherDocshell, ourOwner);

  // SetSubDocumentFor nulls out parent documents on the old child doc if a
  // new non-null document is passed in, so just go ahead and remove both
  // kids before reinserting in the parent subdoc maps, to avoid
  // complications.
  ourParentDocument->SetSubDocumentFor(ourContent, nullptr);
  otherParentDocument->SetSubDocumentFor(otherContent, nullptr);
  ourParentDocument->SetSubDocumentFor(ourContent, otherChildDocument);
  otherParentDocument->SetSubDocumentFor(otherContent, ourChildDocument);

  ourWindow->SetFrameElementInternal(otherFrameElement);
  otherWindow->SetFrameElementInternal(ourFrameElement);

  RefPtr<nsFrameMessageManager> ourMessageManager = mMessageManager;
  RefPtr<nsFrameMessageManager> otherMessageManager = aOther->mMessageManager;
  // Swap pointers in child message managers.
  if (mChildMessageManager) {
    InProcessBrowserChildMessageManager* browserChild = mChildMessageManager;
    browserChild->SetOwner(otherContent);
    browserChild->SetChromeMessageManager(otherMessageManager);
  }
  if (aOther->mChildMessageManager) {
    InProcessBrowserChildMessageManager* otherBrowserChild =
        aOther->mChildMessageManager;
    otherBrowserChild->SetOwner(ourContent);
    otherBrowserChild->SetChromeMessageManager(ourMessageManager);
  }
  // Swap and setup things in parent message managers.
  if (mMessageManager) {
    mMessageManager->SetCallback(aOther);
  }
  if (aOther->mMessageManager) {
    aOther->mMessageManager->SetCallback(this);
  }
  mMessageManager.swap(aOther->mMessageManager);

  // Perform the actual swap of the internal refptrs. We keep a strong reference
  // to ourselves to make sure we don't die while we overwrite our reference to
  // ourself.
  RefPtr<nsFrameLoader> kungFuDeathGrip(this);
  aThisOwner->SetFrameLoader(aOther);
  aOtherOwner->SetFrameLoader(kungFuDeathGrip);

  // Drop any cached content viewers in the two session histories.
  if (ourHistory) {
    ourHistory->EvictLocalContentViewers();
  }
  if (otherHistory) {
    otherHistory->EvictLocalContentViewers();
  }

  NS_ASSERTION(ourFrame == ourContent->GetPrimaryFrame() &&
                   otherFrame == otherContent->GetPrimaryFrame(),
               "changed primary frame");

  ourFrameFrame->EndSwapDocShells(otherFrame);

  // If the content being swapped came from windows on two screens with
  // incompatible backing resolution (e.g. dragging a tab between windows on
  // hi-dpi and low-dpi screens), it will have style data that is based on
  // the wrong appUnitsPerDevPixel value. So we tell the PresShells that their
  // backing scale factor may have changed. (Bug 822266)
  ourPresShell->BackingScaleFactorChanged();
  otherPresShell->BackingScaleFactorChanged();

  // Initialize browser API if needed now that owner content has changed
  InitializeBrowserAPI();
  aOther->InitializeBrowserAPI();

  return NS_OK;
}

void nsFrameLoader::Destroy() { StartDestroy(); }

class nsFrameLoaderDestroyRunnable : public Runnable {
  enum DestroyPhase {
    // See the implementation of Run for an explanation of these phases.
    eDestroyDocShell,
    eWaitForUnloadMessage,
    eDestroyComplete
  };

  RefPtr<nsFrameLoader> mFrameLoader;
  DestroyPhase mPhase;

 public:
  explicit nsFrameLoaderDestroyRunnable(nsFrameLoader* aFrameLoader)
      : mozilla::Runnable("nsFrameLoaderDestroyRunnable"),
        mFrameLoader(aFrameLoader),
        mPhase(eDestroyDocShell) {}

  NS_IMETHOD Run() override;
};

void nsFrameLoader::StartDestroy() {
  // nsFrameLoader::StartDestroy is called just before the frameloader is
  // detached from the <browser> element. Destruction continues in phases via
  // the nsFrameLoaderDestroyRunnable.

  if (mDestroyCalled) {
    return;
  }
  mDestroyCalled = true;

  // request a tabStateFlush before tab is closed
  RequestTabStateFlush(/*flushId*/ 0, /*isFinal*/ true);

  // After this point, we return an error when trying to send a message using
  // the message manager on the frame.
  if (mMessageManager) {
    mMessageManager->Close();
  }

  // Retain references to the <browser> element and the frameloader in case we
  // receive any messages from the message manager on the frame. These
  // references are dropped in DestroyComplete.
  if (mChildMessageManager || mRemoteBrowser) {
    mOwnerContentStrong = mOwnerContent;
    if (auto* browserParent = GetBrowserParent()) {
      browserParent->CacheFrameLoader(this);
    }
    if (mChildMessageManager) {
      mChildMessageManager->CacheFrameLoader(this);
    }
  }

  // If the BrowserParent has installed any event listeners on the window, this
  // is its last chance to remove them while we're still in the document.
  if (auto* browserParent = GetBrowserParent()) {
    browserParent->RemoveWindowListeners();
  }

  nsCOMPtr<Document> doc;
  bool dynamicSubframeRemoval = false;
  if (mOwnerContent) {
    doc = mOwnerContent->OwnerDoc();
    dynamicSubframeRemoval = !mIsTopLevelContent && !doc->InUnlinkOrDeletion();
    doc->SetSubDocumentFor(mOwnerContent, nullptr);
    MaybeUpdatePrimaryBrowserParent(eBrowserParentRemoved);
    SetOwnerContent(nullptr);
  }

  // Seems like this is a dynamic frame removal.
  if (dynamicSubframeRemoval) {
    if (GetDocShell()) {
      GetDocShell()->RemoveFromSessionHistory();
    }
  }

  // Let the tree owner know we're gone.
  if (mIsTopLevelContent) {
    if (GetDocShell()) {
      nsCOMPtr<nsIDocShellTreeItem> parentItem;
      GetDocShell()->GetInProcessParent(getter_AddRefs(parentItem));
      nsCOMPtr<nsIDocShellTreeOwner> owner = do_GetInterface(parentItem);
      if (owner) {
        owner->ContentShellRemoved(GetDocShell());
      }
    }
  }

  // Let our window know that we are gone
  if (GetDocShell()) {
    nsCOMPtr<nsPIDOMWindowOuter> win_private(GetDocShell()->GetWindow());
    if (win_private) {
      win_private->SetFrameElementInternal(nullptr);
    }
  }

  nsCOMPtr<nsIRunnable> destroyRunnable =
      new nsFrameLoaderDestroyRunnable(this);
  if (mNeedsAsyncDestroy || !doc ||
      NS_FAILED(doc->FinalizeFrameLoader(this, destroyRunnable))) {
    NS_DispatchToCurrentThread(destroyRunnable);
  }
}

nsresult nsFrameLoaderDestroyRunnable::Run() {
  switch (mPhase) {
    case eDestroyDocShell:
      mFrameLoader->DestroyDocShell();

      // In the out-of-process case, BrowserParent will eventually call
      // DestroyComplete once it receives a __delete__ message from the child.
      // In the in-process case, we dispatch a series of runnables to ensure
      // that DestroyComplete gets called at the right time. The frame loader is
      // kept alive by mFrameLoader during this time.
      if (mFrameLoader->mChildMessageManager) {
        // When the docshell is destroyed, NotifyWindowIDDestroyed is called to
        // asynchronously notify {outer,inner}-window-destroyed via a runnable.
        // We don't want DestroyComplete to run until after those runnables have
        // run. Since we're enqueueing ourselves after the window-destroyed
        // runnables are enqueued, we're guaranteed to run after.
        mPhase = eWaitForUnloadMessage;
        NS_DispatchToCurrentThread(this);
      }
      break;

    case eWaitForUnloadMessage:
      // The *-window-destroyed observers have finished running at this
      // point. However, it's possible that a *-window-destroyed observer might
      // have sent a message using the message manager. These messages might not
      // have been processed yet. So we enqueue ourselves again to ensure that
      // DestroyComplete runs after all messages sent by *-window-destroyed
      // observers have been processed.
      mPhase = eDestroyComplete;
      NS_DispatchToCurrentThread(this);
      break;

    case eDestroyComplete:
      // Now that all messages sent by unload listeners and window destroyed
      // observers have been processed, we disconnect the message manager and
      // finish destruction.
      mFrameLoader->DestroyComplete();
      break;
  }

  return NS_OK;
}

void nsFrameLoader::DestroyDocShell() {
  // This code runs after the frameloader has been detached from the <browser>
  // element. We postpone this work because we may not be allowed to run
  // script at that time.

  // Ask the BrowserChild to fire the frame script "unload" event, destroy its
  // docshell, and finally destroy the PBrowser actor. This eventually leads to
  // nsFrameLoader::DestroyComplete being called.
  if (mRemoteBrowser) {
    mRemoteBrowser->DestroyStart();
  }

  // Fire the "unload" event if we're in-process.
  if (mChildMessageManager) {
    mChildMessageManager->FireUnloadEvent();
  }

  if (mSessionStoreListener) {
    mSessionStoreListener->RemoveListeners();
    mSessionStoreListener = nullptr;
  }

  // Destroy the docshell.
  if (GetDocShell()) {
    GetDocShell()->Destroy();
  }

  mBrowsingContext = nullptr;

  if (mChildMessageManager) {
    // Stop handling events in the in-process frame script.
    mChildMessageManager->DisconnectEventListeners();
  }
}

void nsFrameLoader::DestroyComplete() {
  // We get here, as part of StartDestroy, after the docshell has been destroyed
  // and all message manager messages sent during docshell destruction have been
  // dispatched.  We also get here if the child process crashes. In the latter
  // case, StartDestroy might not have been called.

  // Drop the strong references created in StartDestroy.
  if (mChildMessageManager || mRemoteBrowser) {
    mOwnerContentStrong = nullptr;
    if (auto* browserParent = GetBrowserParent()) {
      browserParent->CacheFrameLoader(nullptr);
    }
    if (mChildMessageManager) {
      mChildMessageManager->CacheFrameLoader(nullptr);
    }
  }

  // Call BrowserParent::Destroy if we haven't already (in case of a crash).
  if (mRemoteBrowser) {
    mRemoteBrowser->DestroyComplete();
    mRemoteBrowser = nullptr;
  }

  if (mMessageManager) {
    mMessageManager->Disconnect();
  }

  if (mChildMessageManager) {
    mChildMessageManager->Disconnect();
  }

  mMessageManager = nullptr;
  mChildMessageManager = nullptr;
}

void nsFrameLoader::SetOwnerContent(Element* aContent) {
  if (mObservingOwnerContent) {
    mObservingOwnerContent = false;
    mOwnerContent->RemoveMutationObserver(this);
  }
  mOwnerContent = aContent;

  if (RefPtr<BrowsingContext> browsingContext = GetBrowsingContext()) {
    browsingContext->SetEmbedderElement(mOwnerContent);
  }

  AutoJSAPI jsapi;
  jsapi.Init();

  JS::RootedObject wrapper(jsapi.cx(), GetWrapper());
  if (wrapper) {
    JSAutoRealm ar(jsapi.cx(), wrapper);
    IgnoredErrorResult rv;
    UpdateReflectorGlobal(jsapi.cx(), wrapper, rv);
    Unused << NS_WARN_IF(rv.Failed());
  }
}

bool nsFrameLoader::OwnerIsMozBrowserFrame() {
  nsCOMPtr<nsIMozBrowserFrame> browserFrame = do_QueryInterface(mOwnerContent);
  return browserFrame ? browserFrame->GetReallyIsBrowser() : false;
}

nsresult nsFrameLoader::MaybeCreateDocShell() {
  if (GetDocShell()) {
    return NS_OK;
  }
  if (IsRemoteFrame()) {
    return NS_OK;
  }
  NS_ENSURE_STATE(!mDestroyCalled);

  // Get our parent docshell off the document of mOwnerContent
  // XXXbz this is such a total hack.... We really need to have a
  // better setup for doing this.
  Document* doc = mOwnerContent->OwnerDoc();

  MOZ_RELEASE_ASSERT(!doc->IsResourceDoc(), "We shouldn't even exist");

  // Check if the document still has a window since it is possible for an
  // iframe to be inserted and cause the creation of the docshell in a
  // partially unloaded document (see Bug 1305237 comment 127).
  if (!doc->IsStaticDocument() &&
      (!doc->GetWindow() || !mOwnerContent->IsInComposedDoc())) {
    return NS_ERROR_UNEXPECTED;
  }

  if (!doc->IsActive()) {
    // Don't allow subframe loads in non-active documents.
    // (See bug 610571 comment 5.)
    return NS_ERROR_NOT_AVAILABLE;
  }

  RefPtr<nsDocShell> parentDocShell = nsDocShell::Cast(doc->GetDocShell());
  if (NS_WARN_IF(!parentDocShell)) {
    return NS_ERROR_UNEXPECTED;
  }

  // nsDocShell::Create will attach itself to the passed browsing
  // context inside of nsDocShell::Create
  RefPtr<nsDocShell> docShell = nsDocShell::Create(mBrowsingContext);
  NS_ENSURE_TRUE(docShell, NS_ERROR_FAILURE);

  mBrowsingContext->SetEmbedderElement(mOwnerContent);

  mIsTopLevelContent =
      mBrowsingContext->IsContent() && !mBrowsingContext->GetParent();
  if (!mNetworkCreated && !mIsTopLevelContent) {
    docShell->SetCreatedDynamically(true);
  }

  if (mIsTopLevelContent) {
    // Manually add ourselves to our parent's docshell, as BrowsingContext won't
    // have done this for us.
    //
    // XXX(nika): Consider removing the DocShellTree in the future, for
    // consistency between local and remote frames..
    parentDocShell->AddChild(docShell);
  }

  // Now that we are part of the DocShellTree, attach our DocShell to our
  // parent's TreeOwner.
  nsCOMPtr<nsIDocShellTreeOwner> parentTreeOwner;
  parentDocShell->GetTreeOwner(getter_AddRefs(parentTreeOwner));
  AddTreeItemToTreeOwner(docShell, parentTreeOwner);

  // Make sure all nsDocShells have links back to the content element in the
  // nearest enclosing chrome shell.
  RefPtr<EventTarget> chromeEventHandler;
  bool parentIsContent = parentDocShell->GetBrowsingContext()->IsContent();
  if (parentIsContent) {
    // Our parent shell is a content shell. Get the chrome event handler from it
    // and use that for our shell as well.
    parentDocShell->GetChromeEventHandler(getter_AddRefs(chromeEventHandler));
  } else {
    // Our parent shell is a chrome shell. It is therefore our nearest enclosing
    // chrome shell.
    chromeEventHandler = mOwnerContent;
  }

  docShell->SetChromeEventHandler(chromeEventHandler);

  // This is nasty, this code (the docShell->GetWindow() below)
  // *must* come *after* the above call to
  // docShell->SetChromeEventHandler() for the global window to get
  // the right chrome event handler.

  // Tell the window about the frame that hosts it.
  nsCOMPtr<nsPIDOMWindowOuter> newWindow = docShell->GetWindow();
  if (NS_WARN_IF(!newWindow)) {
    // Do not call Destroy() here. See bug 472312.
    NS_WARNING("Something wrong when creating the docshell for a frameloader!");
    return NS_ERROR_FAILURE;
  }

  newWindow->SetFrameElementInternal(mOwnerContent);

  // Allow scripts to close the docshell if specified.
  if (mOwnerContent->IsXULElement(nsGkAtoms::browser) &&
      mOwnerContent->AttrValueIs(kNameSpaceID_None,
                                 nsGkAtoms::allowscriptstoclose,
                                 nsGkAtoms::_true, eCaseMatters)) {
    nsGlobalWindowOuter::Cast(newWindow)->AllowScriptsToClose();
  }

  // This is kinda whacky, this call doesn't really create anything,
  // but it must be called to make sure things are properly
  // initialized.
  if (NS_FAILED(docShell->Create())) {
    // Do not call Destroy() here. See bug 472312.
    NS_WARNING("Something wrong when creating the docshell for a frameloader!");
    return NS_ERROR_FAILURE;
  }

  // If we are an in-process browser, we want to set up our session history. We
  // do this by creating both the child SHistory (which is in the nsDocShell),
  // and creating the corresponding in-process ParentSHistory.
  if (mIsTopLevelContent && mOwnerContent->IsXULElement(nsGkAtoms::browser) &&
      !mOwnerContent->HasAttr(kNameSpaceID_None, nsGkAtoms::disablehistory)) {
    // XXX(nika): Set this up more explicitly?
    nsresult rv = docShell->InitSessionHistory();
    NS_ENSURE_SUCCESS(rv, rv);
    mParentSHistory = new ParentSHistory(this);
  }

  OriginAttributes attrs;
  if (parentDocShell->ItemType() == docShell->ItemType()) {
    attrs = parentDocShell->GetOriginAttributes();
  }

  // Inherit origin attributes from parent document if
  // 1. It's in a content docshell.
  // 2. its nodePrincipal is not a SystemPrincipal.
  // 3. It's not a mozbrowser frame.
  //
  // For example, firstPartyDomain is computed from top-level document, it
  // doesn't exist in the top-level docshell.
  if (parentIsContent &&
      !nsContentUtils::IsSystemPrincipal(doc->NodePrincipal()) &&
      !OwnerIsMozBrowserFrame()) {
    OriginAttributes oa = doc->NodePrincipal()->OriginAttributesRef();

    // Assert on the firstPartyDomain from top-level docshell should be empty
    MOZ_ASSERT_IF(mIsTopLevelContent, attrs.mFirstPartyDomain.IsEmpty());

    // So far we want to make sure Inherit doesn't override any other origin
    // attribute than firstPartyDomain.
    MOZ_ASSERT(
        attrs.mUserContextId == oa.mUserContextId,
        "docshell and document should have the same userContextId attribute.");
    MOZ_ASSERT(attrs.mPrivateBrowsingId == oa.mPrivateBrowsingId,
               "docshell and document should have the same privateBrowsingId "
               "attribute.");

    attrs = oa;
  }

  if (OwnerIsMozBrowserFrame()) {
    docShell->SetFrameType(nsIDocShell::FRAME_TYPE_BROWSER);
  } else {
    nsCOMPtr<nsIDocShellTreeItem> parentCheck;
    docShell->GetInProcessSameTypeParent(getter_AddRefs(parentCheck));
    if (!!parentCheck) {
      docShell->SetIsFrame();
    }
  }

  // Apply sandbox flags even if our owner is not an iframe, as this copies
  // flags from our owning content's owning document.
  // Note: ApplySandboxFlags should be called after docShell->SetFrameType
  // because we need to get the correct presentation URL in ApplySandboxFlags.
  uint32_t sandboxFlags = 0;
  HTMLIFrameElement* iframe = HTMLIFrameElement::FromNode(mOwnerContent);
  if (iframe) {
    sandboxFlags = iframe->GetSandboxFlags();
  }
  ApplySandboxFlags(sandboxFlags);

  // Grab the userContextId from owner
  nsresult rv = PopulateUserContextIdFromAttribute(attrs);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  bool isPrivate = false;
  rv = parentDocShell->GetUsePrivateBrowsing(&isPrivate);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }
  attrs.SyncAttributesWithPrivateBrowsing(isPrivate);

  if (OwnerIsMozBrowserFrame()) {
    // For inproc frames, set the docshell properties.
    nsAutoString name;
    if (mOwnerContent->GetAttr(kNameSpaceID_None, nsGkAtoms::name, name)) {
      docShell->SetName(name);
    }
    docShell->SetFullscreenAllowed(
        mOwnerContent->HasAttr(kNameSpaceID_None, nsGkAtoms::allowfullscreen) ||
        mOwnerContent->HasAttr(kNameSpaceID_None,
                               nsGkAtoms::mozallowfullscreen));
    bool isPrivate = mOwnerContent->HasAttr(kNameSpaceID_None,
                                            nsGkAtoms::mozprivatebrowsing);
    if (isPrivate) {
      if (docShell->GetHasLoadedNonBlankURI()) {
        nsContentUtils::ReportToConsoleNonLocalized(
            NS_LITERAL_STRING("We should not switch to Private Browsing after "
                              "loading a document."),
            nsIScriptError::warningFlag,
            NS_LITERAL_CSTRING("mozprivatebrowsing"), nullptr);
      } else {
        // This handles the case where a frames private browsing is set by
        // chrome flags and not inherited by its parent.
        attrs.SyncAttributesWithPrivateBrowsing(isPrivate);
      }
    }
  }

  docShell->SetOriginAttributes(attrs);

  // Typically there will be a window, however for some cases such as printing
  // the document is cloned with a docshell that has no window.  We check
  // that the window exists to ensure we don't try to gather ancestors for
  // those cases.
  nsCOMPtr<nsPIDOMWindowOuter> win = doc->GetWindow();
  if (!docShell->GetIsMozBrowser() &&
      parentDocShell->ItemType() == docShell->ItemType() &&
      !doc->IsStaticDocument() && win) {
    // Propagate through the ancestor principals.
    nsTArray<nsCOMPtr<nsIPrincipal>> ancestorPrincipals;
    // Make a copy, so we can modify it.
    ancestorPrincipals = doc->AncestorPrincipals();
    ancestorPrincipals.InsertElementAt(0, doc->NodePrincipal());
    docShell->SetAncestorPrincipals(std::move(ancestorPrincipals));

    // Repeat for outer window IDs.
    nsTArray<uint64_t> ancestorOuterWindowIDs;
    ancestorOuterWindowIDs = doc->AncestorOuterWindowIDs();
    ancestorOuterWindowIDs.InsertElementAt(0, win->WindowID());
    docShell->SetAncestorOuterWindowIDs(std::move(ancestorOuterWindowIDs));
  }

  ReallyLoadFrameScripts();
  InitializeBrowserAPI();

  nsCOMPtr<nsIObserverService> os = services::GetObserverService();
  if (os) {
    os->NotifyObservers(ToSupports(this), "inprocess-browser-shown", nullptr);
  }

  return NS_OK;
}

void nsFrameLoader::GetURL(nsString& aURI, nsIPrincipal** aTriggeringPrincipal,
                           nsIContentSecurityPolicy** aCsp) {
  aURI.Truncate();
  // Within this function we default to using the NodePrincipal as the
  // triggeringPrincipal and the CSP of the document.
  // Expanded Principals however override the CSP of the document, hence
  // if frame->GetSrcTriggeringPrincipal() returns a valid principal, we
  // have to query the CSP from that Principal.
  nsCOMPtr<nsIPrincipal> triggeringPrincipal = mOwnerContent->NodePrincipal();
  nsCOMPtr<nsIContentSecurityPolicy> csp = mOwnerContent->GetCsp();

  if (mOwnerContent->IsHTMLElement(nsGkAtoms::object)) {
    mOwnerContent->GetAttr(kNameSpaceID_None, nsGkAtoms::data, aURI);
  } else {
    mOwnerContent->GetAttr(kNameSpaceID_None, nsGkAtoms::src, aURI);
    if (RefPtr<nsGenericHTMLFrameElement> frame =
            do_QueryObject(mOwnerContent)) {
      nsCOMPtr<nsIPrincipal> srcPrincipal = frame->GetSrcTriggeringPrincipal();
      if (srcPrincipal) {
        triggeringPrincipal = srcPrincipal;
        nsCOMPtr<nsIExpandedPrincipal> ep =
            do_QueryInterface(triggeringPrincipal);
        if (ep) {
          csp = ep->GetCsp();
        }
      }
    }
  }
  triggeringPrincipal.forget(aTriggeringPrincipal);
  csp.forget(aCsp);
}

nsresult nsFrameLoader::CheckForRecursiveLoad(nsIURI* aURI) {
  nsresult rv;

  MOZ_ASSERT(!IsRemoteFrame(),
             "Shouldn't call CheckForRecursiveLoad on remote frames.");

  mDepthTooGreat = false;
  rv = MaybeCreateDocShell();
  if (NS_FAILED(rv)) {
    return rv;
  }
  MOZ_ASSERT(GetDocShell(), "MaybeCreateDocShell succeeded, but null docShell");
  if (!GetDocShell()) {
    return NS_ERROR_FAILURE;
  }

  // Check that we're still in the docshell tree.
  nsCOMPtr<nsIDocShellTreeOwner> treeOwner;
  GetDocShell()->GetTreeOwner(getter_AddRefs(treeOwner));
  NS_WARNING_ASSERTION(treeOwner,
                       "Trying to load a new url to a docshell without owner!");
  NS_ENSURE_STATE(treeOwner);

  if (GetDocShell()->ItemType() != nsIDocShellTreeItem::typeContent) {
    // No need to do recursion-protection here XXXbz why not??  Do we really
    // trust people not to screw up with non-content docshells?
    return NS_OK;
  }

  // Bug 8065: Don't exceed some maximum depth in content frames
  // (MAX_DEPTH_CONTENT_FRAMES)
  nsCOMPtr<nsIDocShellTreeItem> parentAsItem;
  GetDocShell()->GetInProcessSameTypeParent(getter_AddRefs(parentAsItem));
  int32_t depth = 0;
  while (parentAsItem) {
    ++depth;

    if (depth >= MAX_DEPTH_CONTENT_FRAMES) {
      mDepthTooGreat = true;
      NS_WARNING("Too many nested content frames so giving up");

      return NS_ERROR_UNEXPECTED;  // Too deep, give up!  (silently?)
    }

    nsCOMPtr<nsIDocShellTreeItem> temp;
    temp.swap(parentAsItem);
    temp->GetInProcessSameTypeParent(getter_AddRefs(parentAsItem));
  }

  // Bug 136580: Check for recursive frame loading excluding about:srcdoc URIs.
  // srcdoc URIs require their contents to be specified inline, so it isn't
  // possible for undesirable recursion to occur without the aid of a
  // non-srcdoc URI,  which this method will block normally.
  // Besides, URI is not enough to guarantee uniqueness of srcdoc documents.
  nsAutoCString buffer;
  rv = aURI->GetScheme(buffer);
  if (NS_SUCCEEDED(rv) && buffer.EqualsLiteral("about")) {
    rv = aURI->GetPathQueryRef(buffer);
    if (NS_SUCCEEDED(rv) && buffer.EqualsLiteral("srcdoc")) {
      // Duplicates allowed up to depth limits
      return NS_OK;
    }
  }
  int32_t matchCount = 0;
  GetDocShell()->GetInProcessSameTypeParent(getter_AddRefs(parentAsItem));
  while (parentAsItem) {
    // Check the parent URI with the URI we're loading
    nsCOMPtr<nsIWebNavigation> parentAsNav(do_QueryInterface(parentAsItem));
    if (parentAsNav) {
      // Does the URI match the one we're about to load?
      nsCOMPtr<nsIURI> parentURI;
      parentAsNav->GetCurrentURI(getter_AddRefs(parentURI));
      if (parentURI) {
        // Bug 98158/193011: We need to ignore data after the #
        bool equal;
        rv = aURI->EqualsExceptRef(parentURI, &equal);
        NS_ENSURE_SUCCESS(rv, rv);

        if (equal) {
          matchCount++;
          if (matchCount >= MAX_SAME_URL_CONTENT_FRAMES) {
            NS_WARNING(
                "Too many nested content frames have the same url (recursion?) "
                "so giving up");
            return NS_ERROR_UNEXPECTED;
          }
        }
      }
    }
    nsCOMPtr<nsIDocShellTreeItem> temp;
    temp.swap(parentAsItem);
    temp->GetInProcessSameTypeParent(getter_AddRefs(parentAsItem));
  }

  return NS_OK;
}

nsresult nsFrameLoader::GetWindowDimensions(nsIntRect& aRect) {
  // Need to get outer window position here
  Document* doc = mOwnerContent->GetComposedDoc();
  if (!doc) {
    return NS_ERROR_FAILURE;
  }

  MOZ_RELEASE_ASSERT(!doc->IsResourceDoc(), "We shouldn't even exist");

  nsCOMPtr<nsPIDOMWindowOuter> win = doc->GetWindow();
  if (!win) {
    return NS_ERROR_FAILURE;
  }

  nsCOMPtr<nsIDocShellTreeItem> parentAsItem(win->GetDocShell());
  if (!parentAsItem) {
    return NS_ERROR_FAILURE;
  }

  nsCOMPtr<nsIDocShellTreeOwner> parentOwner;
  if (NS_FAILED(parentAsItem->GetTreeOwner(getter_AddRefs(parentOwner))) ||
      !parentOwner) {
    return NS_ERROR_FAILURE;
  }

  nsCOMPtr<nsIBaseWindow> treeOwnerAsWin(do_GetInterface(parentOwner));
  treeOwnerAsWin->GetPosition(&aRect.x, &aRect.y);
  treeOwnerAsWin->GetSize(&aRect.width, &aRect.height);
  return NS_OK;
}

nsresult nsFrameLoader::UpdatePositionAndSize(nsSubDocumentFrame* aIFrame) {
  if (IsRemoteFrame()) {
    if (mRemoteBrowser) {
      ScreenIntSize size = aIFrame->GetSubdocumentSize();
      // If we were not able to show remote frame before, we should probably
      // retry now to send correct showInfo.
      if (!mRemoteBrowserShown) {
        ShowRemoteFrame(size, aIFrame);
      }
      nsIntRect dimensions;
      NS_ENSURE_SUCCESS(GetWindowDimensions(dimensions), NS_ERROR_FAILURE);
      mLazySize = size;
      mRemoteBrowser->UpdateDimensions(dimensions, size);
    }
    return NS_OK;
  }
  UpdateBaseWindowPositionAndSize(aIFrame);
  return NS_OK;
}

void nsFrameLoader::SendIsUnderHiddenEmbedderElement(
    bool aIsUnderHiddenEmbedderElement) {
  MOZ_ASSERT(IsRemoteFrame());

  if (auto* browserBridgeChild = GetBrowserBridgeChild()) {
    browserBridgeChild->SetIsUnderHiddenEmbedderElement(
        aIsUnderHiddenEmbedderElement);
  }
}

void nsFrameLoader::UpdateBaseWindowPositionAndSize(
    nsSubDocumentFrame* aIFrame) {
  nsCOMPtr<nsIBaseWindow> baseWindow = GetDocShell(IgnoreErrors());

  // resize the sub document
  if (baseWindow) {
    int32_t x = 0;
    int32_t y = 0;

    AutoWeakFrame weakFrame(aIFrame);

    baseWindow->GetPosition(&x, &y);

    if (!weakFrame.IsAlive()) {
      // GetPosition() killed us
      return;
    }

    ScreenIntSize size = aIFrame->GetSubdocumentSize();
    mLazySize = size;

    baseWindow->SetPositionAndSize(x, y, size.width, size.height,
                                   nsIBaseWindow::eDelayResize);
  }
}

uint32_t nsFrameLoader::LazyWidth() const {
  uint32_t lazyWidth = mLazySize.width;

  nsIFrame* frame = GetPrimaryFrameOfOwningContent();
  if (frame) {
    lazyWidth = frame->PresContext()->DevPixelsToIntCSSPixels(lazyWidth);
  }

  return lazyWidth;
}

uint32_t nsFrameLoader::LazyHeight() const {
  uint32_t lazyHeight = mLazySize.height;

  nsIFrame* frame = GetPrimaryFrameOfOwningContent();
  if (frame) {
    lazyHeight = frame->PresContext()->DevPixelsToIntCSSPixels(lazyHeight);
  }

  return lazyHeight;
}

static Tuple<ContentParent*, BrowserParent*> GetContentParent(
    Element* aBrowser) {
  using ReturnTuple = Tuple<ContentParent*, BrowserParent*>;

  nsCOMPtr<nsIBrowser> browser = aBrowser ? aBrowser->AsBrowser() : nullptr;
  if (!browser) {
    return ReturnTuple(nullptr, nullptr);
  }

  RefPtr<nsFrameLoader> otherLoader;
  browser->GetSameProcessAsFrameLoader(getter_AddRefs(otherLoader));
  if (!otherLoader) {
    return ReturnTuple(nullptr, nullptr);
  }

  BrowserParent* browserParent = BrowserParent::GetFrom(otherLoader);
  if (browserParent && browserParent->Manager()) {
    return MakeTuple(browserParent->Manager(), browserParent);
  }

  return ReturnTuple(nullptr, nullptr);
}

bool nsFrameLoader::EnsureRemoteBrowser() {
  MOZ_ASSERT(IsRemoteFrame());
  return mRemoteBrowser || TryRemoteBrowser();
}

bool nsFrameLoader::TryRemoteBrowserInternal() {
  NS_ASSERTION(!mRemoteBrowser,
               "TryRemoteBrowser called with a remote browser already?");

  if (!mOwnerContent) {
    return false;
  }

  // XXXsmaug Per spec (2014/08/21) frameloader should not work in case the
  //         element isn't in document, only in shadow dom, but that will change
  //         https://www.w3.org/Bugs/Public/show_bug.cgi?id=26365#c0
  Document* doc = mOwnerContent->GetComposedDoc();
  if (!doc) {
    return false;
  }

  MOZ_RELEASE_ASSERT(!doc->IsResourceDoc(), "We shouldn't even exist");

  if (!doc->IsActive()) {
    // Don't allow subframe loads in non-active documents.
    // (See bug 610571 comment 5.)
    return false;
  }

  nsCOMPtr<nsPIDOMWindowOuter> parentWin = doc->GetWindow();
  if (!parentWin) {
    return false;
  }

  nsCOMPtr<nsIDocShell> parentDocShell = parentWin->GetDocShell();
  if (!parentDocShell) {
    return false;
  }

  RefPtr<ContentParent> openerContentParent;
  RefPtr<BrowserParent> sameTabGroupAs;
  if (auto* host = BrowserHost::GetFrom(parentDocShell->GetOpener())) {
    openerContentParent = host->GetContentParent();
  }

  // <iframe mozbrowser> gets to skip these checks.
  // iframes for JS plugins also get to skip these checks. We control the URL
  // that gets loaded, but the load is triggered from the document containing
  // the plugin.
  // out of process iframes also get to skip this check.
  if (!OwnerIsMozBrowserFrame() && !XRE_IsContentProcess()) {
    if (parentDocShell->ItemType() != nsIDocShellTreeItem::typeChrome) {
      // Allow two exceptions to this rule :
      // - about:addon so it can load remote extension options pages
      // - DevTools webext panels if DevTools is loaded in a content frame
      //
      // Note that the new frame's message manager will not be a child of the
      // chrome window message manager, and, the values of window.top and
      // window.parent will be different than they would be for a non-remote
      // frame.
      nsIURI* parentURI = parentWin->GetDocumentURI();
      if (!parentURI) {
        return false;
      }

      nsAutoCString specIgnoringRef;
      if (NS_FAILED(parentURI->GetSpecIgnoringRef(specIgnoringRef))) {
        return false;
      }

      if (!(specIgnoringRef.EqualsLiteral("about:addons") ||
            specIgnoringRef.EqualsLiteral(
                "chrome://mozapps/content/extensions/aboutaddons.html") ||
            specIgnoringRef.EqualsLiteral(
                "chrome://browser/content/webext-panels.xul"))) {
        return false;
      }
    }

    if (!mOwnerContent->IsXULElement()) {
      return false;
    }

    if (!mOwnerContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
                                    nsGkAtoms::content, eIgnoreCase)) {
      return false;
    }

    // Try to get the related content parent from our browser element.
    Tie(openerContentParent, sameTabGroupAs) = GetContentParent(mOwnerContent);
    // If we have an opener, it may be in the same process as our new child, and
    // therefore needs to be in the same tab group. The long term solution to
    // this problem is to get rid of TabGroups entirely. In the short term, the
    // following hack deals with the specific problem that when a window has an
    // opener, it asserts that its BrowserChild is bound to the same tab group
    // as its opener. There are likely other mismatches that it does not handle,
    // but those will all be fixed by the removal of TabGroups.
    if (RefPtr<BrowsingContext> openerBC = mBrowsingContext->GetOpener()) {
      sameTabGroupAs = openerBC->Canonical()->GetCurrentWindowGlobal()->GetBrowserParent();
    }
  }

  uint32_t chromeFlags = 0;
  nsCOMPtr<nsIDocShellTreeOwner> parentOwner;
  if (NS_FAILED(parentDocShell->GetTreeOwner(getter_AddRefs(parentOwner))) ||
      !parentOwner) {
    return false;
  }
  nsCOMPtr<nsIXULWindow> window(do_GetInterface(parentOwner));
  if (window && NS_FAILED(window->GetChromeFlags(&chromeFlags))) {
    return false;
  }

  AUTO_PROFILER_LABEL("nsFrameLoader::TryRemoteBrowser:Create", OTHER);

  MutableTabContext context;
  nsresult rv = GetNewTabContext(&context);
  NS_ENSURE_SUCCESS(rv, false);

  uint64_t nextRemoteTabId = 0;
  if (mOwnerContent) {
    nsAutoString nextBrowserParentIdAttr;
    mOwnerContent->GetAttr(kNameSpaceID_None, nsGkAtoms::nextRemoteTabId,
                           nextBrowserParentIdAttr);
    nextRemoteTabId = strtoull(
        NS_ConvertUTF16toUTF8(nextBrowserParentIdAttr).get(), nullptr, 10);

    // We may be in a window that was just opened, so try the
    // nsIBrowserDOMWindow API as a backup.
    if (!nextRemoteTabId && window) {
      Unused << window->GetNextRemoteTabId(&nextRemoteTabId);
    }
  }

  nsCOMPtr<Element> ownerElement = mOwnerContent;

  // If we're in a content process, create a BrowserBridgeChild actor.
  if (XRE_IsContentProcess()) {
    mBrowsingContext->SetEmbedderElement(mOwnerContent);

    mRemoteBrowser = ContentChild::CreateBrowser(this, context, mRemoteType,
                                                 mBrowsingContext);
    return !!mRemoteBrowser;
  }

  mRemoteBrowser = ContentParent::CreateBrowser(
      context, ownerElement, mRemoteType, mBrowsingContext, openerContentParent,
      sameTabGroupAs, nextRemoteTabId);
  if (!mRemoteBrowser) {
    return false;
  }

  // Grab the reference to the actor
  RefPtr<BrowserParent> browserParent = GetBrowserParent();

  // We no longer need the remoteType attribute on the frame element.
  // The remoteType can be queried by asking the message manager instead.
  ownerElement->UnsetAttr(kNameSpaceID_None, nsGkAtoms::RemoteType, false);

  // Now that browserParent is set, we can initialize graphics
  browserParent->InitRendering();

  MaybeUpdatePrimaryBrowserParent(eBrowserParentChanged);

  mChildID = browserParent->Manager()->ChildID();

  nsCOMPtr<nsIDocShellTreeItem> rootItem;
  parentDocShell->GetInProcessRootTreeItem(getter_AddRefs(rootItem));
  nsCOMPtr<nsPIDOMWindowOuter> rootWin = rootItem->GetWindow();
  nsCOMPtr<nsIDOMChromeWindow> rootChromeWin = do_QueryInterface(rootWin);

  if (rootChromeWin) {
    nsCOMPtr<nsIBrowserDOMWindow> browserDOMWin;
    rootChromeWin->GetBrowserDOMWindow(getter_AddRefs(browserDOMWin));
    browserParent->SetBrowserDOMWindow(browserDOMWin);
  }

  // Set up a parent SHistory
  if (XRE_IsParentProcess()) {
    // XXX(nika): Once we get out of process iframes we won't want to
    // unconditionally set this up. What do we do for iframes in a chrome loaded
    // document for example?
    mParentSHistory = new ParentSHistory(this);
  }

  // For xul:browsers, update some settings based on attributes:
  if (mOwnerContent->IsXULElement()) {
    // Send down the name of the browser through browserParent if it is set.
    nsAutoString frameName;
    mOwnerContent->GetAttr(kNameSpaceID_None, nsGkAtoms::name, frameName);
    if (nsContentUtils::IsOverridingWindowName(frameName)) {
      Unused << browserParent->SendSetWindowName(frameName);
    }
    // Allow scripts to close the window if the browser specified so:
    if (mOwnerContent->AttrValueIs(kNameSpaceID_None,
                                   nsGkAtoms::allowscriptstoclose,
                                   nsGkAtoms::_true, eCaseMatters)) {
      Unused << browserParent->SendAllowScriptsToClose();
    }
  }

  ReallyLoadFrameScripts();
  InitializeBrowserAPI();

  return true;
}

bool nsFrameLoader::TryRemoteBrowser() {
  // Try to create the internal remote browser.
  if (TryRemoteBrowserInternal()) {
    return true;
  }

  // Check if we should report a browser-crashed error because the browser
  // failed to start.
  if (XRE_IsParentProcess() && mOwnerContent && mOwnerContent->IsXULElement()) {
    MaybeNotifyCrashed(nullptr, nullptr);
  }

  return false;
}

bool nsFrameLoader::IsRemoteFrame() {
  if (mIsRemoteFrame) {
    MOZ_ASSERT(!GetDocShell(), "Found a remote frame with a DocShell");
    return true;
  }
  return false;
}

RemoteBrowser* nsFrameLoader::GetRemoteBrowser() const {
  return mRemoteBrowser;
}

BrowserParent* nsFrameLoader::GetBrowserParent() const {
  if (!mRemoteBrowser) {
    return nullptr;
  }
  RefPtr<BrowserHost> browserHost = mRemoteBrowser->AsBrowserHost();
  if (!browserHost) {
    return nullptr;
  }
  return browserHost->GetActor();
}

BrowserBridgeChild* nsFrameLoader::GetBrowserBridgeChild() const {
  if (!mRemoteBrowser) {
    return nullptr;
  }
  RefPtr<BrowserBridgeHost> browserBridgeHost =
      mRemoteBrowser->AsBrowserBridgeHost();
  if (!browserBridgeHost) {
    return nullptr;
  }
  return browserBridgeHost->GetActor();
}

mozilla::layers::LayersId nsFrameLoader::GetLayersId() const {
  MOZ_ASSERT(mIsRemoteFrame);
  return mRemoteBrowser->GetLayersId();
}

void nsFrameLoader::ActivateRemoteFrame(ErrorResult& aRv) {
  auto* browserParent = GetBrowserParent();
  if (!browserParent) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return;
  }

  browserParent->Activate();
}

void nsFrameLoader::DeactivateRemoteFrame(ErrorResult& aRv) {
  auto* browserParent = GetBrowserParent();
  if (!browserParent) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return;
  }

  browserParent->Deactivate(false);
}

void nsFrameLoader::SendCrossProcessMouseEvent(const nsAString& aType, float aX,
                                               float aY, int32_t aButton,
                                               int32_t aClickCount,
                                               int32_t aModifiers,
                                               bool aIgnoreRootScrollFrame,
                                               ErrorResult& aRv) {
  auto* browserParent = GetBrowserParent();
  if (!browserParent) {
    aRv.Throw(NS_ERROR_FAILURE);
    return;
  }

  browserParent->SendMouseEvent(aType, aX, aY, aButton, aClickCount, aModifiers,
                                aIgnoreRootScrollFrame);
}

void nsFrameLoader::ActivateFrameEvent(const nsAString& aType, bool aCapture,
                                       ErrorResult& aRv) {
  auto* browserParent = GetBrowserParent();
  if (!browserParent) {
    aRv.Throw(NS_ERROR_FAILURE);
    return;
  }

  bool ok = browserParent->SendActivateFrameEvent(nsString(aType), aCapture);
  if (!ok) {
    aRv.Throw(NS_ERROR_NOT_AVAILABLE);
  }
}

nsresult nsFrameLoader::CreateStaticClone(nsFrameLoader* aDest) {
  if (NS_WARN_IF(IsRemoteFrame())) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  // Ensure that the embedder element is set correctly.
  aDest->mBrowsingContext->SetEmbedderElement(aDest->mOwnerContent);
  aDest->mStaticCloneOf = this;
  return NS_OK;
}

nsresult nsFrameLoader::FinishStaticClone() {
  // After cloning is complete, discard the reference to the original
  // nsFrameLoader, as it is no longer needed.
  auto exitGuard = MakeScopeExit([&] { mStaticCloneOf = nullptr; });

  if (NS_WARN_IF(!mStaticCloneOf || IsDead())) {
    return NS_ERROR_UNEXPECTED;
  }

  MaybeCreateDocShell();
  NS_ENSURE_STATE(GetDocShell());

  nsCOMPtr<Document> kungFuDeathGrip = GetDocShell()->GetDocument();
  Unused << kungFuDeathGrip;

  nsCOMPtr<nsIContentViewer> viewer;
  GetDocShell()->GetContentViewer(getter_AddRefs(viewer));
  NS_ENSURE_STATE(viewer);

  nsIDocShell* origDocShell = mStaticCloneOf->GetDocShell(IgnoreErrors());
  NS_ENSURE_STATE(origDocShell);

  nsCOMPtr<Document> doc = origDocShell->GetDocument();
  NS_ENSURE_STATE(doc);

  nsCOMPtr<Document> clonedDoc = doc->CreateStaticClone(GetDocShell());

  viewer->SetDocument(clonedDoc);
  return NS_OK;
}

bool nsFrameLoader::DoLoadMessageManagerScript(const nsAString& aURL,
                                               bool aRunInGlobalScope) {
  if (auto* browserParent = GetBrowserParent()) {
    return browserParent->SendLoadRemoteScript(nsString(aURL),
                                               aRunInGlobalScope);
  }
  RefPtr<InProcessBrowserChildMessageManager> browserChild =
      GetBrowserChildMessageManager();
  if (browserChild) {
    browserChild->LoadFrameScript(aURL, aRunInGlobalScope);
  }
  return true;
}

class nsAsyncMessageToChild : public nsSameProcessAsyncMessageBase,
                              public Runnable {
 public:
  nsAsyncMessageToChild(JS::RootingContext* aRootingCx,
                        JS::Handle<JSObject*> aCpows,
                        nsFrameLoader* aFrameLoader)
      : nsSameProcessAsyncMessageBase(aRootingCx, aCpows),
        mozilla::Runnable("nsAsyncMessageToChild"),
        mFrameLoader(aFrameLoader) {}

  NS_IMETHOD Run() override {
    InProcessBrowserChildMessageManager* browserChild =
        mFrameLoader->mChildMessageManager;
    // Since bug 1126089, messages can arrive even when the docShell is
    // destroyed. Here we make sure that those messages are not delivered.
    if (browserChild && browserChild->GetInnerManager() &&
        mFrameLoader->GetExistingDocShell()) {
      JS::Rooted<JSObject*> kungFuDeathGrip(dom::RootingCx(),
                                            browserChild->GetWrapper());
      ReceiveMessage(static_cast<EventTarget*>(browserChild), mFrameLoader,
                     browserChild->GetInnerManager());
    }
    return NS_OK;
  }
  RefPtr<nsFrameLoader> mFrameLoader;
};

nsresult nsFrameLoader::DoSendAsyncMessage(JSContext* aCx,
                                           const nsAString& aMessage,
                                           StructuredCloneData& aData,
                                           JS::Handle<JSObject*> aCpows,
                                           nsIPrincipal* aPrincipal) {
  auto* browserParent = GetBrowserParent();
  if (browserParent) {
    ClonedMessageData data;
    ContentParent* cp = browserParent->Manager();
    if (!BuildClonedMessageDataForParent(cp, aData, data)) {
      MOZ_CRASH();
      return NS_ERROR_DOM_DATA_CLONE_ERR;
    }
    nsTArray<mozilla::jsipc::CpowEntry> cpows;
    jsipc::CPOWManager* mgr = cp->GetCPOWManager();
    if (aCpows && (!mgr || !mgr->Wrap(aCx, aCpows, &cpows))) {
      return NS_ERROR_UNEXPECTED;
    }
    if (browserParent->SendAsyncMessage(nsString(aMessage), cpows,
                                        IPC::Principal(aPrincipal), data)) {
      return NS_OK;
    } else {
      return NS_ERROR_UNEXPECTED;
    }
  }

  if (mChildMessageManager) {
    JS::RootingContext* rcx = JS::RootingContext::get(aCx);
    RefPtr<nsAsyncMessageToChild> ev =
        new nsAsyncMessageToChild(rcx, aCpows, this);
    nsresult rv = ev->Init(aMessage, aData, aPrincipal);
    if (NS_FAILED(rv)) {
      return rv;
    }
    rv = NS_DispatchToCurrentThread(ev);
    if (NS_FAILED(rv)) {
      return rv;
    }
    return rv;
  }

  // We don't have any targets to send our asynchronous message to.
  return NS_ERROR_UNEXPECTED;
}

already_AddRefed<MessageSender> nsFrameLoader::GetMessageManager() {
  EnsureMessageManager();
  return do_AddRef(mMessageManager);
}

nsresult nsFrameLoader::EnsureMessageManager() {
  NS_ENSURE_STATE(mOwnerContent);

  if (mMessageManager) {
    return NS_OK;
  }

  if (!mIsTopLevelContent && !OwnerIsMozBrowserFrame() && !IsRemoteFrame() &&
      !(mOwnerContent->IsXULElement() &&
        mOwnerContent->AttrValueIs(kNameSpaceID_None,
                                   nsGkAtoms::forcemessagemanager,
                                   nsGkAtoms::_true, eCaseMatters))) {
    return NS_OK;
  }

  RefPtr<nsGlobalWindowOuter> window =
      nsGlobalWindowOuter::Cast(GetOwnerDoc()->GetWindow());
  RefPtr<ChromeMessageBroadcaster> parentManager;

  if (window && window->IsChromeWindow()) {
    nsAutoString messagemanagergroup;
    if (mOwnerContent->IsXULElement() &&
        mOwnerContent->GetAttr(kNameSpaceID_None,
                               nsGkAtoms::messagemanagergroup,
                               messagemanagergroup)) {
      parentManager = window->GetGroupMessageManager(messagemanagergroup);
    }

    if (!parentManager) {
      parentManager = window->GetMessageManager();
    }
  } else {
    parentManager = nsFrameMessageManager::GetGlobalMessageManager();
  }

  mMessageManager = new ChromeMessageSender(parentManager);
  if (!IsRemoteFrame()) {
    nsresult rv = MaybeCreateDocShell();
    if (NS_FAILED(rv)) {
      return rv;
    }
    MOZ_ASSERT(GetDocShell(),
               "MaybeCreateDocShell succeeded, but null docShell");
    if (!GetDocShell()) {
      return NS_ERROR_FAILURE;
    }
    mChildMessageManager = InProcessBrowserChildMessageManager::Create(
        GetDocShell(), mOwnerContent, mMessageManager);
    NS_ENSURE_TRUE(mChildMessageManager, NS_ERROR_UNEXPECTED);

#if !defined(MOZ_WIDGET_ANDROID) && !defined(MOZ_THUNDERBIRD) && !defined(MOZ_SUITE)
    // Set up a TabListener for sessionStore
    if (XRE_IsParentProcess()) {
      mSessionStoreListener = new TabListener(GetDocShell(), mOwnerContent);
      rv = mSessionStoreListener->Init();
      NS_ENSURE_SUCCESS(rv, rv);
    }
#endif
  }
  return NS_OK;
}

nsresult nsFrameLoader::ReallyLoadFrameScripts() {
  nsresult rv = EnsureMessageManager();
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }
  if (mMessageManager) {
    mMessageManager->InitWithCallback(this);
  }
  return NS_OK;
}

already_AddRefed<Element> nsFrameLoader::GetOwnerElement() {
  return do_AddRef(mOwnerContent);
}

void nsFrameLoader::InitializeFromBrowserParent(BrowserParent* aBrowserParent) {
  MOZ_ASSERT(!mRemoteBrowser);
  mIsRemoteFrame = true;
  mRemoteBrowser = new BrowserHost(aBrowserParent);
  mChildID = aBrowserParent ? aBrowserParent->Manager()->ChildID() : 0;
  MaybeUpdatePrimaryBrowserParent(eBrowserParentChanged);
  ReallyLoadFrameScripts();
  InitializeBrowserAPI();
  aBrowserParent->InitRendering();
  ShowRemoteFrame(ScreenIntSize(0, 0));
}

void nsFrameLoader::SetDetachedSubdocFrame(nsIFrame* aDetachedFrame,
                                           Document* aContainerDoc) {
  mDetachedSubdocFrame = aDetachedFrame;
  mContainerDocWhileDetached = aContainerDoc;
}

nsIFrame* nsFrameLoader::GetDetachedSubdocFrame(
    Document** aContainerDoc) const {
  NS_IF_ADDREF(*aContainerDoc = mContainerDocWhileDetached);
  return mDetachedSubdocFrame.GetFrame();
}

void nsFrameLoader::ApplySandboxFlags(uint32_t sandboxFlags) {
  if (GetDocShell()) {
    uint32_t parentSandboxFlags = mOwnerContent->OwnerDoc()->GetSandboxFlags();

    // The child can only add restrictions, never remove them.
    sandboxFlags |= parentSandboxFlags;

    // If this frame is a receiving browsing context, we should add
    // sandboxed auxiliary navigation flag to sandboxFlags. See
    // https://w3c.github.io/presentation-api/#creating-a-receiving-browsing-context
    nsAutoString presentationURL;
    nsContentUtils::GetPresentationURL(GetDocShell(), presentationURL);
    if (!presentationURL.IsEmpty()) {
      sandboxFlags |= SANDBOXED_AUXILIARY_NAVIGATION;
    }
    GetDocShell()->SetSandboxFlags(sandboxFlags);
  }
}

/* virtual */
void nsFrameLoader::AttributeChanged(mozilla::dom::Element* aElement,
                                     int32_t aNameSpaceID, nsAtom* aAttribute,
                                     int32_t aModType,
                                     const nsAttrValue* aOldValue) {
  MOZ_ASSERT(mObservingOwnerContent);

  if (aElement != mOwnerContent) {
    return;
  }

  if (aNameSpaceID != kNameSpaceID_None ||
      (aAttribute != TypeAttrName(aElement) &&
       aAttribute != nsGkAtoms::primary)) {
    return;
  }

  // Note: This logic duplicates a lot of logic in
  // MaybeCreateDocshell.  We should fix that.

  // Notify our enclosing chrome that our type has changed.  We only do this
  // if our parent is chrome, since in all other cases we're random content
  // subframes and the treeowner shouldn't worry about us.
  if (!GetDocShell()) {
    MaybeUpdatePrimaryBrowserParent(eBrowserParentChanged);
    return;
  }

  nsCOMPtr<nsIDocShellTreeItem> parentItem;
  GetDocShell()->GetInProcessParent(getter_AddRefs(parentItem));
  if (!parentItem) {
    return;
  }

  if (parentItem->ItemType() != nsIDocShellTreeItem::typeChrome) {
    return;
  }

  nsCOMPtr<nsIDocShellTreeOwner> parentTreeOwner;
  parentItem->GetTreeOwner(getter_AddRefs(parentTreeOwner));
  if (!parentTreeOwner) {
    return;
  }

  bool is_primary = aElement->AttrValueIs(kNameSpaceID_None, nsGkAtoms::primary,
                                          nsGkAtoms::_true, eIgnoreCase);

#ifdef MOZ_XUL
  // when a content panel is no longer primary, hide any open popups it may have
  if (!is_primary) {
    nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
    if (pm) {
      pm->HidePopupsInDocShell(GetDocShell());
    }
  }
#endif

  parentTreeOwner->ContentShellRemoved(GetDocShell());
  if (aElement->AttrValueIs(kNameSpaceID_None, TypeAttrName(aElement),
                            nsGkAtoms::content, eIgnoreCase)) {
    parentTreeOwner->ContentShellAdded(GetDocShell(), is_primary);
  }
}

/**
 * Send the RequestNotifyAfterRemotePaint message to the current Tab.
 */
void nsFrameLoader::RequestNotifyAfterRemotePaint() {
  // If remote browsing (e10s), handle this with the BrowserParent.
  if (auto* browserParent = GetBrowserParent()) {
    Unused << browserParent->SendRequestNotifyAfterRemotePaint();
  }
}

void nsFrameLoader::RequestUpdatePosition(ErrorResult& aRv) {
  if (auto* browserParent = GetBrowserParent()) {
    nsresult rv = browserParent->UpdatePosition();

    if (NS_FAILED(rv)) {
      aRv.Throw(rv);
    }
  }
}

bool nsFrameLoader::RequestTabStateFlush(uint32_t aFlushId, bool aIsFinal) {
  if (mSessionStoreListener) {
    mSessionStoreListener->ForceFlushFromParent(aFlushId, aIsFinal);
    // No async ipc call is involved in parent only case
    return false;
  }

  // If remote browsing (e10s), handle this with the BrowserParent.
  if (auto* browserParent = GetBrowserParent()) {
    Unused << browserParent->SendFlushTabState(aFlushId, aIsFinal);
    return true;
  }

  return false;
}

void nsFrameLoader::RequestEpochUpdate(uint32_t aEpoch) {
  if (mSessionStoreListener) {
    mSessionStoreListener->SetEpoch(aEpoch);
    return;
  }

  // If remote browsing (e10s), handle this with the BrowserParent.
  if (auto* browserParent = GetBrowserParent()) {
    Unused << browserParent->SendUpdateEpoch(aEpoch);
  }
}

void nsFrameLoader::Print(uint64_t aOuterWindowID,
                          nsIPrintSettings* aPrintSettings,
                          nsIWebProgressListener* aProgressListener,
                          ErrorResult& aRv) {
#if defined(NS_PRINTING)
  if (auto* browserParent = GetBrowserParent()) {
    RefPtr<embedding::PrintingParent> printingParent =
        browserParent->Manager()->GetPrintingParent();

    embedding::PrintData printData;
    nsresult rv = printingParent->SerializeAndEnsureRemotePrintJob(
        aPrintSettings, aProgressListener, nullptr, &printData);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      aRv.Throw(rv);
      return;
    }

    bool success = browserParent->SendPrint(aOuterWindowID, printData);
    if (!success) {
      aRv.Throw(NS_ERROR_FAILURE);
    }
    return;
  }

  nsGlobalWindowOuter* outerWindow =
      nsGlobalWindowOuter::GetOuterWindowWithId(aOuterWindowID);
  if (NS_WARN_IF(!outerWindow)) {
    aRv.Throw(NS_ERROR_FAILURE);
    return;
  }

  nsCOMPtr<nsIWebBrowserPrint> webBrowserPrint =
      do_GetInterface(ToSupports(outerWindow));
  if (NS_WARN_IF(!webBrowserPrint)) {
    aRv.Throw(NS_ERROR_FAILURE);
    return;
  }

  nsresult rv = webBrowserPrint->Print(aPrintSettings, aProgressListener);
  if (NS_FAILED(rv)) {
    aRv.Throw(rv);
    return;
  }
#endif
}

already_AddRefed<nsIRemoteTab> nsFrameLoader::GetRemoteTab() {
  if (!mRemoteBrowser) {
    return nullptr;
  }
  if (auto* browserHost = mRemoteBrowser->AsBrowserHost()) {
    return do_AddRef(browserHost);
  }
  return nullptr;
}

already_AddRefed<nsILoadContext> nsFrameLoader::LoadContext() {
  nsCOMPtr<nsILoadContext> loadContext;
  if (IsRemoteFrame() && EnsureRemoteBrowser()) {
    loadContext = mRemoteBrowser->GetLoadContext();
  } else {
    loadContext = do_GetInterface(ToSupports(GetDocShell(IgnoreErrors())));
  }
  return loadContext.forget();
}

already_AddRefed<BrowsingContext> nsFrameLoader::GetBrowsingContext() {
  RefPtr<BrowsingContext> browsingContext;
  if (IsRemoteFrame() && EnsureRemoteBrowser()) {
    browsingContext = mRemoteBrowser->GetBrowsingContext();
  } else if (GetDocShell(IgnoreErrors())) {
    browsingContext = GetDocShell()->GetBrowsingContext();
  }
  return browsingContext.forget();
}

void nsFrameLoader::InitializeBrowserAPI() {
  if (!OwnerIsMozBrowserFrame()) {
    return;
  }
  if (!IsRemoteFrame()) {
    nsresult rv = EnsureMessageManager();
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return;
    }
    if (mMessageManager) {
      mMessageManager->LoadFrameScript(
          NS_LITERAL_STRING("chrome://global/content/BrowserElementChild.js"),
          /* allowDelayedLoad = */ true,
          /* aRunInGlobalScope */ true, IgnoreErrors());
    }
  }
  nsCOMPtr<nsIMozBrowserFrame> browserFrame = do_QueryInterface(mOwnerContent);
  if (browserFrame) {
    browserFrame->InitializeBrowserAPI();
  }
}

void nsFrameLoader::DestroyBrowserFrameScripts() {
  if (!OwnerIsMozBrowserFrame()) {
    return;
  }
  nsCOMPtr<nsIMozBrowserFrame> browserFrame = do_QueryInterface(mOwnerContent);
  if (browserFrame) {
    browserFrame->DestroyBrowserFrameScripts();
  }
}

void nsFrameLoader::StartPersistence(
    uint64_t aOuterWindowID, nsIWebBrowserPersistDocumentReceiver* aRecv,
    ErrorResult& aRv) {
  MOZ_ASSERT(aRecv);

  if (auto* browserParent = GetBrowserParent()) {
    browserParent->StartPersistence(aOuterWindowID, aRecv, aRv);
    return;
  }

  nsCOMPtr<Document> rootDoc =
      GetDocShell() ? GetDocShell()->GetDocument() : nullptr;
  nsCOMPtr<Document> foundDoc;
  if (aOuterWindowID) {
    foundDoc = nsContentUtils::GetSubdocumentWithOuterWindowId(rootDoc,
                                                               aOuterWindowID);
  } else {
    foundDoc = rootDoc;
  }

  if (!foundDoc) {
    aRecv->OnError(NS_ERROR_NO_CONTENT);
  } else {
    nsCOMPtr<nsIWebBrowserPersistDocument> pdoc =
        new mozilla::WebBrowserPersistLocalDocument(foundDoc);
    aRecv->OnDocumentReady(pdoc);
  }
}

void nsFrameLoader::MaybeUpdatePrimaryBrowserParent(
    BrowserParentChange aChange) {
  if (!mOwnerContent || !mRemoteBrowser) {
    return;
  }

  RefPtr<BrowserHost> browserHost = mRemoteBrowser->AsBrowserHost();
  if (!browserHost) {
    return;
  }

  nsCOMPtr<nsIDocShell> docShell = mOwnerContent->OwnerDoc()->GetDocShell();
  if (!docShell) {
    return;
  }

  int32_t parentType = docShell->ItemType();
  if (parentType != nsIDocShellTreeItem::typeChrome) {
    return;
  }

  nsCOMPtr<nsIDocShellTreeOwner> parentTreeOwner;
  docShell->GetTreeOwner(getter_AddRefs(parentTreeOwner));
  if (!parentTreeOwner) {
    return;
  }

  if (!mObservingOwnerContent) {
    mOwnerContent->AddMutationObserver(this);
    mObservingOwnerContent = true;
  }

  parentTreeOwner->RemoteTabRemoved(browserHost);
  if (aChange == eBrowserParentChanged) {
    bool isPrimary = mOwnerContent->AttrValueIs(
        kNameSpaceID_None, nsGkAtoms::primary, nsGkAtoms::_true, eIgnoreCase);
    parentTreeOwner->RemoteTabAdded(browserHost, isPrimary);
  }
}

nsresult nsFrameLoader::GetNewTabContext(MutableTabContext* aTabContext,
                                         nsIURI* aURI) {
  OriginAttributes attrs;
  nsresult rv;

  // set the userContextId on the attrs before we pass them into
  // the tab context
  rv = PopulateUserContextIdFromAttribute(attrs);
  NS_ENSURE_SUCCESS(rv, rv);

  nsAutoString presentationURLStr;
  mOwnerContent->GetAttr(kNameSpaceID_None, nsGkAtoms::mozpresentation,
                         presentationURLStr);

  nsCOMPtr<nsIDocShell> docShell = mOwnerContent->OwnerDoc()->GetDocShell();
  nsCOMPtr<nsILoadContext> parentContext = do_QueryInterface(docShell);
  NS_ENSURE_STATE(parentContext);

  bool isPrivate = parentContext->UsePrivateBrowsing();
  attrs.SyncAttributesWithPrivateBrowsing(isPrivate);

  UIStateChangeType showFocusRings = UIStateChangeType_NoChange;
  uint64_t chromeOuterWindowID = 0;

  Document* doc = mOwnerContent->OwnerDoc();
  if (doc) {
    nsCOMPtr<nsPIWindowRoot> root = nsContentUtils::GetWindowRoot(doc);
    if (root) {
      showFocusRings = root->ShowFocusRings() ? UIStateChangeType_Set
                                              : UIStateChangeType_Clear;

      nsPIDOMWindowOuter* outerWin = root->GetWindow();
      if (outerWin) {
        chromeOuterWindowID = outerWin->WindowID();
      }
    }
  }

  uint32_t maxTouchPoints = BrowserParent::GetMaxTouchPoints(mOwnerContent);

  bool tabContextUpdated = aTabContext->SetTabContext(
      OwnerIsMozBrowserFrame(), chromeOuterWindowID, showFocusRings, attrs,
      presentationURLStr, maxTouchPoints);
  NS_ENSURE_STATE(tabContextUpdated);

  return NS_OK;
}

nsresult nsFrameLoader::PopulateUserContextIdFromAttribute(
    OriginAttributes& aAttr) {
  if (aAttr.mUserContextId ==
      nsIScriptSecurityManager::DEFAULT_USER_CONTEXT_ID) {
    // Grab the userContextId from owner if XUL or mozbrowser frame
    nsAutoString userContextIdStr;
    int32_t namespaceID = mOwnerContent->GetNameSpaceID();
    if ((namespaceID == kNameSpaceID_XUL || OwnerIsMozBrowserFrame()) &&
        mOwnerContent->GetAttr(kNameSpaceID_None, nsGkAtoms::usercontextid,
                               userContextIdStr) &&
        !userContextIdStr.IsEmpty()) {
      nsresult rv;
      aAttr.mUserContextId = userContextIdStr.ToInteger(&rv);
      NS_ENSURE_SUCCESS(rv, rv);
    }
  }

  return NS_OK;
}

ProcessMessageManager* nsFrameLoader::GetProcessMessageManager() const {
  if (auto* browserParent = GetBrowserParent()) {
    return browserParent->Manager()->GetMessageManager();
  }
  return nullptr;
};

JSObject* nsFrameLoader::WrapObject(JSContext* cx,
                                    JS::Handle<JSObject*> aGivenProto) {
  JS::RootedObject result(cx);
  FrameLoader_Binding::Wrap(cx, this, this, aGivenProto, &result);
  return result;
}

void nsFrameLoader::SkipBrowsingContextDetach() {
  if (IsRemoteFrame()) {
    // OOP Browser - Go directly over Browser Parent
    if (auto* browserParent = GetBrowserParent()) {
      RefPtr<BrowsingContext> bc(GetBrowsingContext());
      // We're going to be synchronously changing the owner of the
      // BrowsingContext in the parent process while the current owner may still
      // have in-flight requests which only the owner is allowed to make. Those
      // requests will typically trigger assertions if they come from a child
      // other than the owner.
      //
      // To work around this, we record the previous owner at the start of the
      // process switch, and clear it when we've received a reply from the
      // child, treating ownership mismatches as warnings in the interim.
      //
      // In the future, this sort of issue will probably need to be handled
      // using ownership epochs, which should be more both flexible and
      // resilient. For the moment, though, the surrounding process switch code
      // is enough in flux that we're better off with a workable interim
      // solution.
      bc->Canonical()->SetInFlightProcessId(
          browserParent->Manager()->ChildID());
      browserParent->SendSkipBrowsingContextDetach(
          [bc](bool aSuccess) { bc->Canonical()->SetInFlightProcessId(0); },
          [bc](mozilla::ipc::ResponseRejectReason aReason) {
            bc->Canonical()->SetInFlightProcessId(0);
          });
    }
    // OOP IFrame - Through Browser Bridge Parent, set on browser child
    else if (auto* browserBridgeChild = GetBrowserBridgeChild()) {
      Unused << browserBridgeChild->SendSkipBrowsingContextDetach();
    }
    return;
  }

  // In process
  RefPtr<nsDocShell> docshell = GetDocShell();
  MOZ_ASSERT(docshell);
  docshell->SkipBrowsingContextDetach();
}

void nsFrameLoader::MaybeNotifyCrashed(BrowsingContext* aBrowsingContext,
                                       mozilla::ipc::MessageChannel* aChannel) {
  if (mTabProcessCrashFired) {
    return;
  }

  if (mBrowsingContext == aBrowsingContext) {
    mTabProcessCrashFired = true;
  }

  // Fire the crashed observer notification.
  nsCOMPtr<nsIObserverService> os = services::GetObserverService();
  if (!os) {
    return;
  }
  os->NotifyObservers(ToSupports(this), "oop-frameloader-crashed", nullptr);

  // Check our owner element still references us. If it's moved, on, events
  // don't need to be fired.
  RefPtr<nsFrameLoaderOwner> owner = do_QueryObject(mOwnerContent);
  if (!owner) {
    return;
  }

  RefPtr<nsFrameLoader> currentFrameLoader = owner->GetFrameLoader();
  if (currentFrameLoader != this) {
    return;
  }

  // Fire the actual crashed event.
  nsString eventName;
  if (aChannel && !aChannel->DoBuildIDsMatch()) {
    eventName = NS_LITERAL_STRING("oop-browser-buildid-mismatch");
  } else {
    eventName = NS_LITERAL_STRING("oop-browser-crashed");
  }

  FrameCrashedEventInit init;
  init.mBubbles = true;
  init.mCancelable = true;
  if (aBrowsingContext) {
    init.mBrowsingContextId = aBrowsingContext->Id();
    init.mIsTopFrame = !aBrowsingContext->GetParent();
  }

  RefPtr<FrameCrashedEvent> event = FrameCrashedEvent::Constructor(
      mOwnerContent->OwnerDoc(), eventName, init);
  event->SetTrusted(true);
  EventDispatcher::DispatchDOMEvent(mOwnerContent, nullptr, event, nullptr,
                                    nullptr);
}