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 (b6d82b1a6b02)

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 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=8 sts=2 et sw=2 tw=80:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "vm/EnvironmentObject-inl.h"

#include "builtin/ModuleObject.h"
#include "gc/Policy.h"
#include "vm/ArgumentsObject.h"
#include "vm/AsyncFunction.h"
#include "vm/GlobalObject.h"
#include "vm/Iteration.h"
#include "vm/JSObject.h"
#include "vm/ProxyObject.h"
#include "vm/Realm.h"
#include "vm/Shape.h"
#include "vm/Xdr.h"
#include "wasm/WasmInstance.h"

#ifdef DEBUG
#  include "vm/BytecodeIterator.h"
#  include "vm/BytecodeLocation.h"
#endif

#include "gc/Marking-inl.h"
#include "vm/JSAtom-inl.h"
#include "vm/JSScript-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/Stack-inl.h"
#include "vm/TypeInference-inl.h"

#ifdef DEBUG
#  include "vm/BytecodeIterator-inl.h"
#  include "vm/BytecodeLocation-inl.h"
#endif

using namespace js;

typedef Rooted<ArgumentsObject*> RootedArgumentsObject;
typedef MutableHandle<ArgumentsObject*> MutableHandleArgumentsObject;

/*****************************************************************************/

Shape* js::EnvironmentCoordinateToEnvironmentShape(JSScript* script,
                                                   jsbytecode* pc) {
  MOZ_ASSERT(JOF_OPTYPE(JSOp(*pc)) == JOF_ENVCOORD);
  ScopeIter si(script->innermostScope(pc));
  uint32_t hops = EnvironmentCoordinate(pc).hops();
  while (true) {
    MOZ_ASSERT(!si.done());
    if (si.hasSyntacticEnvironment()) {
      if (!hops) {
        break;
      }
      hops--;
    }
    si++;
  }
  return si.environmentShape();
}

PropertyName* js::EnvironmentCoordinateNameSlow(JSScript* script,
                                                jsbytecode* pc) {
  Shape* shape = EnvironmentCoordinateToEnvironmentShape(script, pc);
  EnvironmentCoordinate ec(pc);

  Shape::Range<NoGC> r(shape);
  while (r.front().slot() != ec.slot()) {
    r.popFront();
  }
  jsid id = r.front().propidRaw();

  /* Beware nameless destructuring formal. */
  if (!JSID_IS_ATOM(id)) {
    return script->runtimeFromAnyThread()->commonNames->empty;
  }
  return JSID_TO_ATOM(id)->asPropertyName();
}

/*****************************************************************************/

CallObject* CallObject::create(JSContext* cx, HandleShape shape,
                               HandleObjectGroup group) {
  MOZ_ASSERT(!group->singleton());

  gc::AllocKind kind = gc::GetGCObjectKind(shape->numFixedSlots());
  MOZ_ASSERT(CanChangeToBackgroundAllocKind(kind, &CallObject::class_));
  kind = gc::ForegroundToBackgroundAllocKind(kind);

  gc::InitialHeap heap = GetInitialHeap(GenericObject, group);

  JSObject* obj;
  JS_TRY_VAR_OR_RETURN_NULL(cx, obj,
                            NativeObject::create(cx, kind, heap, shape, group));

  return &obj->as<CallObject>();
}

/*
 * Create a CallObject for a JSScript that is not initialized to any particular
 * callsite. This object can either be initialized (with an enclosing scope and
 * callee) or used as a template for jit compilation.
 */
CallObject* CallObject::createTemplateObject(JSContext* cx, HandleScript script,
                                             HandleObject enclosing,
                                             gc::InitialHeap heap) {
  Rooted<FunctionScope*> scope(cx, &script->bodyScope()->as<FunctionScope>());
  RootedShape shape(cx, scope->environmentShape());
  MOZ_ASSERT(shape->getObjectClass() == &class_);

  RootedObjectGroup group(
      cx, ObjectGroup::defaultNewGroup(cx, &class_, TaggedProto(nullptr)));
  if (!group) {
    return nullptr;
  }

  gc::AllocKind kind = gc::GetGCObjectKind(shape->numFixedSlots());
  MOZ_ASSERT(CanChangeToBackgroundAllocKind(kind, &class_));
  kind = gc::ForegroundToBackgroundAllocKind(kind);

  // The JITs assume the result is nursery allocated unless we collected the
  // nursery, so don't change |heap| here.

  JSObject* obj;
  JS_TRY_VAR_OR_RETURN_NULL(cx, obj,
                            NativeObject::create(cx, kind, heap, shape, group));

  CallObject* callObj = &obj->as<CallObject>();
  callObj->initEnclosingEnvironment(enclosing);

  if (scope->hasParameterExprs()) {
    // If there are parameter expressions, all parameters are lexical and
    // have TDZ.
    for (BindingIter bi(script->bodyScope()); bi; bi++) {
      BindingLocation loc = bi.location();
      if (loc.kind() == BindingLocation::Kind::Environment &&
          BindingKindIsLexical(bi.kind())) {
        callObj->initSlot(loc.slot(), MagicValue(JS_UNINITIALIZED_LEXICAL));
      }
    }
  }

  return callObj;
}

/*
 * Construct a call object for the given bindings.  If this is a call object
 * for a function invocation, callee should be the function being called.
 * Otherwise it must be a call object for eval of strict mode code, and callee
 * must be null.
 */
CallObject* CallObject::create(JSContext* cx, HandleFunction callee,
                               HandleObject enclosing) {
  RootedScript script(cx, callee->nonLazyScript());
  gc::InitialHeap heap = gc::DefaultHeap;
  CallObject* callobj =
      CallObject::createTemplateObject(cx, script, enclosing, heap);
  if (!callobj) {
    return nullptr;
  }

  callobj->initFixedSlot(CALLEE_SLOT, ObjectValue(*callee));

  return callobj;
}

CallObject* CallObject::create(JSContext* cx, AbstractFramePtr frame) {
  MOZ_ASSERT(frame.isFunctionFrame());
  cx->check(frame);

  RootedObject envChain(cx, frame.environmentChain());
  RootedFunction callee(cx, frame.callee());

  CallObject* callobj = create(cx, callee, envChain);
  if (!callobj) {
    return nullptr;
  }

  if (!frame.script()->bodyScope()->as<FunctionScope>().hasParameterExprs()) {
    // If there are no defaults, copy the aliased arguments into the call
    // object manually. If there are defaults, bytecode is generated to do
    // the copying.

    for (PositionalFormalParameterIter fi(frame.script()); fi; fi++) {
      if (!fi.closedOver()) {
        continue;
      }
      callobj->setAliasedBinding(
          cx, fi,
          frame.unaliasedFormal(fi.argumentSlot(), DONT_CHECK_ALIASING));
    }
  }

  return callobj;
}

CallObject* CallObject::createHollowForDebug(JSContext* cx,
                                             HandleFunction callee) {
  MOZ_ASSERT(!callee->needsCallObject());

  RootedScript script(cx, callee->nonLazyScript());
  Rooted<FunctionScope*> scope(cx, &script->bodyScope()->as<FunctionScope>());
  RootedShape shape(cx, FunctionScope::getEmptyEnvironmentShape(
                            cx, scope->hasParameterExprs()));
  if (!shape) {
    return nullptr;
  }
  RootedObjectGroup group(
      cx, ObjectGroup::defaultNewGroup(cx, &class_, TaggedProto(nullptr)));
  if (!group) {
    return nullptr;
  }
  Rooted<CallObject*> callobj(cx, create(cx, shape, group));
  if (!callobj) {
    return nullptr;
  }

  // This environment's enclosing link is never used: the
  // DebugEnvironmentProxy that refers to this scope carries its own
  // enclosing link, which is what Debugger uses to construct the tree of
  // Debugger.Environment objects.
  callobj->initEnclosingEnvironment(&cx->global()->lexicalEnvironment());
  callobj->initFixedSlot(CALLEE_SLOT, ObjectValue(*callee));

  RootedValue optimizedOut(cx, MagicValue(JS_OPTIMIZED_OUT));
  RootedId id(cx);
  for (Rooted<BindingIter> bi(cx, BindingIter(script)); bi; bi++) {
    id = NameToId(bi.name()->asPropertyName());
    if (!SetProperty(cx, callobj, id, optimizedOut)) {
      return nullptr;
    }
  }

  return callobj;
}

const JSClass CallObject::class_ = {
    "Call", JSCLASS_HAS_RESERVED_SLOTS(CallObject::RESERVED_SLOTS)};

/*****************************************************************************/

/* static */
VarEnvironmentObject* VarEnvironmentObject::create(JSContext* cx,
                                                   HandleShape shape,
                                                   HandleObject enclosing,
                                                   gc::InitialHeap heap) {
  MOZ_ASSERT(shape->getObjectClass() == &class_);

  RootedObjectGroup group(
      cx, ObjectGroup::defaultNewGroup(cx, &class_, TaggedProto(nullptr)));
  if (!group) {
    return nullptr;
  }

  gc::AllocKind kind = gc::GetGCObjectKind(shape->numFixedSlots());
  MOZ_ASSERT(CanChangeToBackgroundAllocKind(kind, &class_));
  kind = gc::ForegroundToBackgroundAllocKind(kind);

  {
    AutoSweepObjectGroup sweep(group);
    if (group->shouldPreTenure(sweep)) {
      heap = gc::TenuredHeap;
    }
  }

  JSObject* obj;
  JS_TRY_VAR_OR_RETURN_NULL(cx, obj,
                            NativeObject::create(cx, kind, heap, shape, group));

  VarEnvironmentObject* env = &obj->as<VarEnvironmentObject>();
  MOZ_ASSERT(!env->inDictionaryMode());
  MOZ_ASSERT(env->isDelegate());

  env->initEnclosingEnvironment(enclosing);

  return env;
}

/* static */
VarEnvironmentObject* VarEnvironmentObject::create(JSContext* cx,
                                                   HandleScope scope,
                                                   AbstractFramePtr frame) {
#ifdef DEBUG
  if (frame.isEvalFrame()) {
    MOZ_ASSERT(scope->is<EvalScope>() && scope == frame.script()->bodyScope());
    MOZ_ASSERT_IF(frame.isInterpreterFrame(),
                  cx->interpreterFrame() == frame.asInterpreterFrame());
    MOZ_ASSERT_IF(frame.isInterpreterFrame(),
                  cx->interpreterRegs().pc == frame.script()->code());
  } else {
    MOZ_ASSERT(frame.environmentChain());
    MOZ_ASSERT_IF(
        frame.callee()->needsCallObject(),
        &frame.environmentChain()->as<CallObject>().callee() == frame.callee());
  }
#endif

  RootedScript script(cx, frame.script());
  RootedObject envChain(cx, frame.environmentChain());
  RootedShape shape(cx, scope->environmentShape());
  VarEnvironmentObject* env = create(cx, shape, envChain, gc::DefaultHeap);
  if (!env) {
    return nullptr;
  }
  env->initScope(scope);
  return env;
}

/* static */
VarEnvironmentObject* VarEnvironmentObject::createHollowForDebug(
    JSContext* cx, Handle<VarScope*> scope) {
  MOZ_ASSERT(!scope->hasEnvironment());

  RootedShape shape(cx, VarScope::getEmptyEnvironmentShape(cx));
  if (!shape) {
    return nullptr;
  }

  // This environment's enclosing link is never used: the
  // DebugEnvironmentProxy that refers to this scope carries its own
  // enclosing link, which is what Debugger uses to construct the tree of
  // Debugger.Environment objects.
  RootedObject enclosingEnv(cx, &cx->global()->lexicalEnvironment());
  Rooted<VarEnvironmentObject*> env(
      cx, create(cx, shape, enclosingEnv, gc::TenuredHeap));
  if (!env) {
    return nullptr;
  }

  RootedValue optimizedOut(cx, MagicValue(JS_OPTIMIZED_OUT));
  RootedId id(cx);
  for (Rooted<BindingIter> bi(cx, BindingIter(scope)); bi; bi++) {
    id = NameToId(bi.name()->asPropertyName());
    if (!SetProperty(cx, env, id, optimizedOut)) {
      return nullptr;
    }
  }

  env->initScope(scope);
  return env;
}

const JSClass VarEnvironmentObject::class_ = {
    "Var", JSCLASS_HAS_RESERVED_SLOTS(VarEnvironmentObject::RESERVED_SLOTS)};

/*****************************************************************************/

const ObjectOps ModuleEnvironmentObject::objectOps_ = {
    ModuleEnvironmentObject::lookupProperty,
    nullptr, /* defineProperty */
    ModuleEnvironmentObject::hasProperty,
    ModuleEnvironmentObject::getProperty,
    ModuleEnvironmentObject::setProperty,
    ModuleEnvironmentObject::getOwnPropertyDescriptor,
    ModuleEnvironmentObject::deleteProperty,
    nullptr, /* getElements */
    nullptr};

const JSClassOps ModuleEnvironmentObject::classOps_ = {
    nullptr, /* addProperty */
    nullptr, /* delProperty */
    nullptr, /* enumerate */
    ModuleEnvironmentObject::newEnumerate};

const JSClass ModuleEnvironmentObject::class_ = {
    "ModuleEnvironmentObject",
    JSCLASS_HAS_RESERVED_SLOTS(ModuleEnvironmentObject::RESERVED_SLOTS),
    &ModuleEnvironmentObject::classOps_,
    JS_NULL_CLASS_SPEC,
    JS_NULL_CLASS_EXT,
    &ModuleEnvironmentObject::objectOps_};

/* static */
ModuleEnvironmentObject* ModuleEnvironmentObject::create(
    JSContext* cx, HandleModuleObject module) {
  RootedScript script(cx, module->script());
  RootedShape shape(cx,
                    script->bodyScope()->as<ModuleScope>().environmentShape());
  MOZ_ASSERT(shape->getObjectClass() == &class_);

  RootedObjectGroup group(
      cx, ObjectGroup::defaultNewGroup(cx, &class_, TaggedProto(nullptr)));
  if (!group) {
    return nullptr;
  }

  gc::AllocKind kind = gc::GetGCObjectKind(shape->numFixedSlots());
  MOZ_ASSERT(CanChangeToBackgroundAllocKind(kind, &class_));
  kind = gc::ForegroundToBackgroundAllocKind(kind);

  JSObject* obj;
  JS_TRY_VAR_OR_RETURN_NULL(
      cx, obj, NativeObject::create(cx, kind, gc::TenuredHeap, shape, group));

  RootedModuleEnvironmentObject env(cx, &obj->as<ModuleEnvironmentObject>());

  env->initReservedSlot(MODULE_SLOT, ObjectValue(*module));

  // Initialize this early so that we can manipulate the env object without
  // causing assertions.
  env->initEnclosingEnvironment(&cx->global()->lexicalEnvironment());

  // Initialize all lexical bindings and imports as uninitialized. Imports
  // get uninitialized because they have a special TDZ for cyclic imports.
  for (BindingIter bi(script); bi; bi++) {
    BindingLocation loc = bi.location();
    if (loc.kind() == BindingLocation::Kind::Environment &&
        BindingKindIsLexical(bi.kind())) {
      env->initSlot(loc.slot(), MagicValue(JS_UNINITIALIZED_LEXICAL));
    }
  }

  // It is not be possible to add or remove bindings from a module environment
  // after this point as module code is always strict.
#ifdef DEBUG
  for (Shape::Range<NoGC> r(env->lastProperty()); !r.empty(); r.popFront()) {
    MOZ_ASSERT(!r.front().configurable());
  }
  MOZ_ASSERT(env->lastProperty()->getObjectFlags() & BaseShape::NOT_EXTENSIBLE);
  MOZ_ASSERT(!env->inDictionaryMode());
#endif

  return env;
}

ModuleObject& ModuleEnvironmentObject::module() const {
  return getReservedSlot(MODULE_SLOT).toObject().as<ModuleObject>();
}

IndirectBindingMap& ModuleEnvironmentObject::importBindings() const {
  return module().importBindings();
}

bool ModuleEnvironmentObject::createImportBinding(JSContext* cx,
                                                  HandleAtom importName,
                                                  HandleModuleObject module,
                                                  HandleAtom localName) {
  RootedId importNameId(cx, AtomToId(importName));
  RootedId localNameId(cx, AtomToId(localName));
  RootedModuleEnvironmentObject env(cx, &module->initialEnvironment());
  if (!importBindings().put(cx, importNameId, env, localNameId)) {
    return false;
  }

  return true;
}

bool ModuleEnvironmentObject::hasImportBinding(HandlePropertyName name) {
  return importBindings().has(NameToId(name));
}

bool ModuleEnvironmentObject::lookupImport(jsid name,
                                           ModuleEnvironmentObject** envOut,
                                           Shape** shapeOut) {
  return importBindings().lookup(name, envOut, shapeOut);
}

void ModuleEnvironmentObject::fixEnclosingEnvironmentAfterRealmMerge(
    GlobalObject& global) {
  setEnclosingEnvironment(&global.lexicalEnvironment());
}

/* static */
bool ModuleEnvironmentObject::lookupProperty(
    JSContext* cx, HandleObject obj, HandleId id, MutableHandleObject objp,
    MutableHandle<PropertyResult> propp) {
  const IndirectBindingMap& bindings =
      obj->as<ModuleEnvironmentObject>().importBindings();
  Shape* shape;
  ModuleEnvironmentObject* env;
  if (bindings.lookup(id, &env, &shape)) {
    objp.set(env);
    propp.setNativeProperty(shape);
    return true;
  }

  RootedNativeObject target(cx, &obj->as<NativeObject>());
  if (!NativeLookupOwnProperty<CanGC>(cx, target, id, propp)) {
    return false;
  }

  objp.set(obj);
  return true;
}

/* static */
bool ModuleEnvironmentObject::hasProperty(JSContext* cx, HandleObject obj,
                                          HandleId id, bool* foundp) {
  if (obj->as<ModuleEnvironmentObject>().importBindings().has(id)) {
    *foundp = true;
    return true;
  }

  RootedNativeObject self(cx, &obj->as<NativeObject>());
  return NativeHasProperty(cx, self, id, foundp);
}

/* static */
bool ModuleEnvironmentObject::getProperty(JSContext* cx, HandleObject obj,
                                          HandleValue receiver, HandleId id,
                                          MutableHandleValue vp) {
  const IndirectBindingMap& bindings =
      obj->as<ModuleEnvironmentObject>().importBindings();
  Shape* shape;
  ModuleEnvironmentObject* env;
  if (bindings.lookup(id, &env, &shape)) {
    vp.set(env->getSlot(shape->slot()));
    return true;
  }

  RootedNativeObject self(cx, &obj->as<NativeObject>());
  return NativeGetProperty(cx, self, receiver, id, vp);
}

/* static */
bool ModuleEnvironmentObject::setProperty(JSContext* cx, HandleObject obj,
                                          HandleId id, HandleValue v,
                                          HandleValue receiver,
                                          JS::ObjectOpResult& result) {
  RootedModuleEnvironmentObject self(cx, &obj->as<ModuleEnvironmentObject>());
  if (self->importBindings().has(id)) {
    return result.failReadOnly();
  }

  return NativeSetProperty<Qualified>(cx, self, id, v, receiver, result);
}

/* static */
bool ModuleEnvironmentObject::getOwnPropertyDescriptor(
    JSContext* cx, HandleObject obj, HandleId id,
    MutableHandle<PropertyDescriptor> desc) {
  const IndirectBindingMap& bindings =
      obj->as<ModuleEnvironmentObject>().importBindings();
  Shape* shape;
  ModuleEnvironmentObject* env;
  if (bindings.lookup(id, &env, &shape)) {
    desc.setAttributes(JSPROP_ENUMERATE | JSPROP_PERMANENT);
    desc.object().set(obj);
    RootedValue value(cx, env->getSlot(shape->slot()));
    desc.setValue(value);
    desc.assertComplete();
    return true;
  }

  RootedNativeObject self(cx, &obj->as<NativeObject>());
  return NativeGetOwnPropertyDescriptor(cx, self, id, desc);
}

/* static */
bool ModuleEnvironmentObject::deleteProperty(JSContext* cx, HandleObject obj,
                                             HandleId id,
                                             ObjectOpResult& result) {
  return result.failCantDelete();
}

/* static */
bool ModuleEnvironmentObject::newEnumerate(JSContext* cx, HandleObject obj,
                                           MutableHandleIdVector properties,
                                           bool enumerableOnly) {
  RootedModuleEnvironmentObject self(cx, &obj->as<ModuleEnvironmentObject>());
  const IndirectBindingMap& bs(self->importBindings());

  MOZ_ASSERT(properties.length() == 0);
  size_t count = bs.count() + self->slotSpan() - RESERVED_SLOTS;
  if (!properties.reserve(count)) {
    ReportOutOfMemory(cx);
    return false;
  }

  bs.forEachExportedName([&](jsid name) { properties.infallibleAppend(name); });

  for (Shape::Range<NoGC> r(self->lastProperty()); !r.empty(); r.popFront()) {
    properties.infallibleAppend(r.front().propid());
  }

  MOZ_ASSERT(properties.length() == count);
  return true;
}

/*****************************************************************************/

const JSClass WasmInstanceEnvironmentObject::class_ = {
    "WasmInstance",
    JSCLASS_HAS_RESERVED_SLOTS(WasmInstanceEnvironmentObject::RESERVED_SLOTS)};

/* static */
WasmInstanceEnvironmentObject*
WasmInstanceEnvironmentObject::createHollowForDebug(
    JSContext* cx, Handle<WasmInstanceScope*> scope) {
  RootedObjectGroup group(
      cx, ObjectGroup::defaultNewGroup(cx, &class_, TaggedProto(nullptr)));
  if (!group) {
    return nullptr;
  }

  RootedShape shape(cx, scope->getEmptyEnvironmentShape(cx));
  if (!shape) {
    return nullptr;
  }

  gc::AllocKind kind = gc::GetGCObjectKind(shape->numFixedSlots());
  MOZ_ASSERT(CanChangeToBackgroundAllocKind(kind, &class_));
  kind = gc::ForegroundToBackgroundAllocKind(kind);

  JSObject* obj;
  JS_TRY_VAR_OR_RETURN_NULL(
      cx, obj, NativeObject::create(cx, kind, gc::DefaultHeap, shape, group));

  Rooted<WasmInstanceEnvironmentObject*> callobj(
      cx, &obj->as<WasmInstanceEnvironmentObject>());
  callobj->initEnclosingEnvironment(&cx->global()->lexicalEnvironment());
  callobj->initReservedSlot(SCOPE_SLOT, PrivateGCThingValue(scope));

  return callobj;
}

/*****************************************************************************/

const JSClass WasmFunctionCallObject::class_ = {
    "WasmCall",
    JSCLASS_HAS_RESERVED_SLOTS(WasmFunctionCallObject::RESERVED_SLOTS)};

/* static */
WasmFunctionCallObject* WasmFunctionCallObject::createHollowForDebug(
    JSContext* cx, HandleObject enclosing, Handle<WasmFunctionScope*> scope) {
  RootedObjectGroup group(
      cx, ObjectGroup::defaultNewGroup(cx, &class_, TaggedProto(nullptr)));
  if (!group) {
    return nullptr;
  }

  RootedShape shape(cx, scope->getEmptyEnvironmentShape(cx));
  if (!shape) {
    return nullptr;
  }

  gc::AllocKind kind = gc::GetGCObjectKind(shape->numFixedSlots());
  MOZ_ASSERT(CanChangeToBackgroundAllocKind(kind, &class_));
  kind = gc::ForegroundToBackgroundAllocKind(kind);

  JSObject* obj;
  JS_TRY_VAR_OR_RETURN_NULL(
      cx, obj, NativeObject::create(cx, kind, gc::DefaultHeap, shape, group));

  Rooted<WasmFunctionCallObject*> callobj(cx,
                                          &obj->as<WasmFunctionCallObject>());
  callobj->initEnclosingEnvironment(enclosing);
  callobj->initReservedSlot(SCOPE_SLOT, PrivateGCThingValue(scope));

  return callobj;
}

/*****************************************************************************/

WithEnvironmentObject* WithEnvironmentObject::create(JSContext* cx,
                                                     HandleObject object,
                                                     HandleObject enclosing,
                                                     Handle<WithScope*> scope) {
  Rooted<WithEnvironmentObject*> obj(cx);
  obj = NewObjectWithNullTaggedProto<WithEnvironmentObject>(
      cx, GenericObject, BaseShape::DELEGATE);
  if (!obj) {
    return nullptr;
  }

  Value thisv = GetThisValue(object);

  obj->initEnclosingEnvironment(enclosing);
  obj->initReservedSlot(OBJECT_SLOT, ObjectValue(*object));
  obj->initReservedSlot(THIS_SLOT, thisv);
  if (scope) {
    obj->initReservedSlot(SCOPE_SLOT, PrivateGCThingValue(scope));
  } else {
    obj->initReservedSlot(SCOPE_SLOT, NullValue());
  }

  return obj;
}

WithEnvironmentObject* WithEnvironmentObject::createNonSyntactic(
    JSContext* cx, HandleObject object, HandleObject enclosing) {
  return create(cx, object, enclosing, nullptr);
}

static inline bool IsUnscopableDotName(JSContext* cx, HandleId id) {
  return JSID_IS_ATOM(id, cx->names().dotThis) ||
         JSID_IS_ATOM(id, cx->names().dotGenerator);
}

/* Implements ES6 8.1.1.2.1 HasBinding steps 7-9. */
static bool CheckUnscopables(JSContext* cx, HandleObject obj, HandleId id,
                             bool* scopable) {
  RootedId unscopablesId(
      cx,
      SYMBOL_TO_JSID(cx->wellKnownSymbols().get(JS::SymbolCode::unscopables)));
  RootedValue v(cx);
  if (!GetProperty(cx, obj, obj, unscopablesId, &v)) {
    return false;
  }
  if (v.isObject()) {
    RootedObject unscopablesObj(cx, &v.toObject());
    if (!GetProperty(cx, unscopablesObj, unscopablesObj, id, &v)) {
      return false;
    }
    *scopable = !ToBoolean(v);
  } else {
    *scopable = true;
  }
  return true;
}

static bool with_LookupProperty(JSContext* cx, HandleObject obj, HandleId id,
                                MutableHandleObject objp,
                                MutableHandle<PropertyResult> propp) {
  // SpiderMonkey-specific: consider internal '.generator' and '.this' names
  // to be unscopable.
  if (IsUnscopableDotName(cx, id)) {
    objp.set(nullptr);
    propp.setNotFound();
    return true;
  }

  RootedObject actual(cx, &obj->as<WithEnvironmentObject>().object());
  if (!LookupProperty(cx, actual, id, objp, propp)) {
    return false;
  }

  if (propp) {
    bool scopable;
    if (!CheckUnscopables(cx, actual, id, &scopable)) {
      return false;
    }
    if (!scopable) {
      objp.set(nullptr);
      propp.setNotFound();
    }
  }
  return true;
}

static bool with_DefineProperty(JSContext* cx, HandleObject obj, HandleId id,
                                Handle<PropertyDescriptor> desc,
                                ObjectOpResult& result) {
  MOZ_ASSERT(!IsUnscopableDotName(cx, id));
  RootedObject actual(cx, &obj->as<WithEnvironmentObject>().object());
  return DefineProperty(cx, actual, id, desc, result);
}

static bool with_HasProperty(JSContext* cx, HandleObject obj, HandleId id,
                             bool* foundp) {
  MOZ_ASSERT(!IsUnscopableDotName(cx, id));
  RootedObject actual(cx, &obj->as<WithEnvironmentObject>().object());

  // ES 8.1.1.2.1 step 3-5.
  if (!HasProperty(cx, actual, id, foundp)) {
    return false;
  }
  if (!*foundp) {
    return true;
  }

  // Steps 7-10. (Step 6 is a no-op.)
  return CheckUnscopables(cx, actual, id, foundp);
}

static bool with_GetProperty(JSContext* cx, HandleObject obj,
                             HandleValue receiver, HandleId id,
                             MutableHandleValue vp) {
  MOZ_ASSERT(!IsUnscopableDotName(cx, id));
  RootedObject actual(cx, &obj->as<WithEnvironmentObject>().object());
  RootedValue actualReceiver(cx, receiver);
  if (receiver.isObject() && &receiver.toObject() == obj) {
    actualReceiver.setObject(*actual);
  }
  return GetProperty(cx, actual, actualReceiver, id, vp);
}

static bool with_SetProperty(JSContext* cx, HandleObject obj, HandleId id,
                             HandleValue v, HandleValue receiver,
                             ObjectOpResult& result) {
  MOZ_ASSERT(!IsUnscopableDotName(cx, id));
  RootedObject actual(cx, &obj->as<WithEnvironmentObject>().object());
  RootedValue actualReceiver(cx, receiver);
  if (receiver.isObject() && &receiver.toObject() == obj) {
    actualReceiver.setObject(*actual);
  }
  return SetProperty(cx, actual, id, v, actualReceiver, result);
}

static bool with_GetOwnPropertyDescriptor(
    JSContext* cx, HandleObject obj, HandleId id,
    MutableHandle<PropertyDescriptor> desc) {
  MOZ_ASSERT(!IsUnscopableDotName(cx, id));
  RootedObject actual(cx, &obj->as<WithEnvironmentObject>().object());
  return GetOwnPropertyDescriptor(cx, actual, id, desc);
}

static bool with_DeleteProperty(JSContext* cx, HandleObject obj, HandleId id,
                                ObjectOpResult& result) {
  MOZ_ASSERT(!IsUnscopableDotName(cx, id));
  RootedObject actual(cx, &obj->as<WithEnvironmentObject>().object());
  return DeleteProperty(cx, actual, id, result);
}

static const ObjectOps WithEnvironmentObjectOps = {
    with_LookupProperty,
    with_DefineProperty,
    with_HasProperty,
    with_GetProperty,
    with_SetProperty,
    with_GetOwnPropertyDescriptor,
    with_DeleteProperty,
    nullptr, /* getElements */
    nullptr,
};

const JSClass WithEnvironmentObject::class_ = {
    "With",
    JSCLASS_HAS_RESERVED_SLOTS(WithEnvironmentObject::RESERVED_SLOTS),
    JS_NULL_CLASS_OPS,
    JS_NULL_CLASS_SPEC,
    JS_NULL_CLASS_EXT,
    &WithEnvironmentObjectOps};

/* static */
NonSyntacticVariablesObject* NonSyntacticVariablesObject::create(
    JSContext* cx) {
  Rooted<NonSyntacticVariablesObject*> obj(
      cx, NewObjectWithNullTaggedProto<NonSyntacticVariablesObject>(
              cx, TenuredObject, BaseShape::DELEGATE));
  if (!obj) {
    return nullptr;
  }

  MOZ_ASSERT(obj->isUnqualifiedVarObj());
  if (!JSObject::setQualifiedVarObj(cx, obj)) {
    return nullptr;
  }

  obj->initEnclosingEnvironment(&cx->global()->lexicalEnvironment());
  return obj;
}

const JSClass NonSyntacticVariablesObject::class_ = {
    "NonSyntacticVariablesObject",
    JSCLASS_HAS_RESERVED_SLOTS(NonSyntacticVariablesObject::RESERVED_SLOTS)};

bool js::CreateNonSyntacticEnvironmentChain(JSContext* cx,
                                            HandleObjectVector envChain,
                                            MutableHandleObject env,
                                            MutableHandleScope scope) {
  RootedObject globalLexical(cx, &cx->global()->lexicalEnvironment());
  if (!CreateObjectsForEnvironmentChain(cx, envChain, globalLexical, env)) {
    return false;
  }

  if (!envChain.empty()) {
    scope.set(GlobalScope::createEmpty(cx, ScopeKind::NonSyntactic));
    if (!scope) {
      return false;
    }

    // The XPConnect subscript loader, which may pass in its own
    // environments to load scripts in, expects the environment chain to
    // be the holder of "var" declarations. In SpiderMonkey, such objects
    // are called "qualified varobjs", the "qualified" part meaning the
    // declaration was qualified by "var". There is only sadness.
    //
    // See JSObject::isQualifiedVarObj.
    if (!JSObject::setQualifiedVarObj(cx, env)) {
      return false;
    }

    // Also get a non-syntactic lexical environment to capture 'let' and
    // 'const' bindings. To persist lexical bindings, we have a 1-1
    // mapping with the final unwrapped environment object (the
    // environment that stores the 'var' bindings) and the lexical
    // environment.
    //
    // TODOshu: disallow the subscript loader from using non-distinguished
    // objects as dynamic scopes.
    env.set(ObjectRealm::get(env).getOrCreateNonSyntacticLexicalEnvironment(
        cx, env));
    if (!env) {
      return false;
    }
  } else {
    scope.set(&cx->global()->emptyGlobalScope());
  }

  return true;
}

/*****************************************************************************/

/* static */
LexicalEnvironmentObject* LexicalEnvironmentObject::createTemplateObject(
    JSContext* cx, HandleShape shape, HandleObject enclosing,
    gc::InitialHeap heap) {
  MOZ_ASSERT(shape->getObjectClass() == &LexicalEnvironmentObject::class_);

  RootedObjectGroup group(
      cx, ObjectGroup::defaultNewGroup(cx, &LexicalEnvironmentObject::class_,
                                       TaggedProto(nullptr)));
  if (!group) {
    return nullptr;
  }

  // The JITs assume the result is nursery allocated unless we collected the
  // nursery, so don't change |heap| here.

  gc::AllocKind allocKind = gc::GetGCObjectKind(shape->numFixedSlots());
  MOZ_ASSERT(CanChangeToBackgroundAllocKind(allocKind,
                                            &LexicalEnvironmentObject::class_));
  allocKind = ForegroundToBackgroundAllocKind(allocKind);

  JSObject* obj;
  JS_TRY_VAR_OR_RETURN_NULL(
      cx, obj, NativeObject::create(cx, allocKind, heap, shape, group));

  LexicalEnvironmentObject* env = &obj->as<LexicalEnvironmentObject>();
  MOZ_ASSERT(!env->inDictionaryMode());
  MOZ_ASSERT(env->isDelegate());

  if (enclosing) {
    env->initEnclosingEnvironment(enclosing);
  }

  return env;
}

/* static */
LexicalEnvironmentObject* LexicalEnvironmentObject::create(
    JSContext* cx, Handle<LexicalScope*> scope, HandleObject enclosing,
    gc::InitialHeap heap) {
  cx->check(enclosing);
  MOZ_ASSERT(scope->hasEnvironment());

  RootedShape shape(cx, scope->environmentShape());
  LexicalEnvironmentObject* env =
      createTemplateObject(cx, shape, enclosing, heap);
  if (!env) {
    return nullptr;
  }

  // All lexical bindings start off uninitialized for TDZ.
  uint32_t lastSlot = shape->slot();
  MOZ_ASSERT(lastSlot == env->lastProperty()->slot());
  for (uint32_t slot = JSSLOT_FREE(&class_); slot <= lastSlot; slot++) {
    env->initSlot(slot, MagicValue(JS_UNINITIALIZED_LEXICAL));
  }

  env->initScopeUnchecked(scope);
  return env;
}

/* static */
LexicalEnvironmentObject* LexicalEnvironmentObject::createForFrame(
    JSContext* cx, Handle<LexicalScope*> scope, AbstractFramePtr frame) {
  RootedObject enclosing(cx, frame.environmentChain());
  return create(cx, scope, enclosing, gc::DefaultHeap);
}

/* static */
LexicalEnvironmentObject* LexicalEnvironmentObject::createGlobal(
    JSContext* cx, Handle<GlobalObject*> global) {
  MOZ_ASSERT(global);

  RootedShape shape(cx, LexicalScope::getEmptyExtensibleEnvironmentShape(cx));
  if (!shape) {
    return nullptr;
  }

  Rooted<LexicalEnvironmentObject*> env(
      cx, LexicalEnvironmentObject::createTemplateObject(cx, shape, global,
                                                         gc::TenuredHeap));
  if (!env) {
    return nullptr;
  }

  if (!JSObject::setSingleton(cx, env)) {
    return nullptr;
  }

  env->initThisValue(global);
  return env;
}

/* static */
LexicalEnvironmentObject* LexicalEnvironmentObject::createNonSyntactic(
    JSContext* cx, HandleObject enclosing, HandleObject thisv) {
  MOZ_ASSERT(enclosing);
  MOZ_ASSERT(!IsSyntacticEnvironment(enclosing));

  RootedShape shape(cx, LexicalScope::getEmptyExtensibleEnvironmentShape(cx));
  if (!shape) {
    return nullptr;
  }

  LexicalEnvironmentObject* env =
      LexicalEnvironmentObject::createTemplateObject(cx, shape, enclosing,
                                                     gc::TenuredHeap);
  if (!env) {
    return nullptr;
  }

  env->initThisValue(thisv);

  return env;
}

/* static */
LexicalEnvironmentObject* LexicalEnvironmentObject::createHollowForDebug(
    JSContext* cx, Handle<LexicalScope*> scope) {
  MOZ_ASSERT(!scope->hasEnvironment());

  RootedShape shape(cx, LexicalScope::getEmptyExtensibleEnvironmentShape(cx));
  if (!shape) {
    return nullptr;
  }

  // This environment's enclosing link is never used: the
  // DebugEnvironmentProxy that refers to this scope carries its own
  // enclosing link, which is what Debugger uses to construct the tree of
  // Debugger.Environment objects.
  RootedObject enclosingEnv(cx, &cx->global()->lexicalEnvironment());
  Rooted<LexicalEnvironmentObject*> env(
      cx, createTemplateObject(cx, shape, enclosingEnv, gc::TenuredHeap));
  if (!env) {
    return nullptr;
  }

  RootedValue optimizedOut(cx, MagicValue(JS_OPTIMIZED_OUT));
  RootedId id(cx);
  for (Rooted<BindingIter> bi(cx, BindingIter(scope)); bi; bi++) {
    id = NameToId(bi.name()->asPropertyName());
    if (!SetProperty(cx, env, id, optimizedOut)) {
      return nullptr;
    }
  }

  if (!JSObject::setFlags(cx, env, BaseShape::NOT_EXTENSIBLE,
                          JSObject::GENERATE_SHAPE)) {
    return nullptr;
  }

  env->initScopeUnchecked(scope);
  return env;
}

/* static */
LexicalEnvironmentObject* LexicalEnvironmentObject::clone(
    JSContext* cx, Handle<LexicalEnvironmentObject*> env) {
  Rooted<LexicalScope*> scope(cx, &env->scope());
  RootedObject enclosing(cx, &env->enclosingEnvironment());
  Rooted<LexicalEnvironmentObject*> copy(
      cx, create(cx, scope, enclosing, gc::DefaultHeap));
  if (!copy) {
    return nullptr;
  }

  // We can't assert that the clone has the same shape, because it could
  // have been reshaped by ReshapeForShadowedProp.
  MOZ_ASSERT(env->slotSpan() == copy->slotSpan());
  for (uint32_t i = JSSLOT_FREE(&class_); i < copy->slotSpan(); i++) {
    copy->setSlot(i, env->getSlot(i));
  }

  return copy;
}

/* static */
LexicalEnvironmentObject* LexicalEnvironmentObject::recreate(
    JSContext* cx, Handle<LexicalEnvironmentObject*> env) {
  Rooted<LexicalScope*> scope(cx, &env->scope());
  RootedObject enclosing(cx, &env->enclosingEnvironment());
  return create(cx, scope, enclosing, gc::DefaultHeap);
}

bool LexicalEnvironmentObject::isExtensible() const {
  return NativeObject::isExtensible();
}

Value LexicalEnvironmentObject::thisValue() const {
  MOZ_ASSERT(isExtensible());
  Value v = getReservedSlot(THIS_VALUE_OR_SCOPE_SLOT);

  // Windows must never be exposed to script. setWindowProxyThisValue should
  // have set this to the WindowProxy.
  MOZ_ASSERT_IF(v.isObject(), !IsWindow(&v.toObject()));

  return v;
}

void LexicalEnvironmentObject::setWindowProxyThisValue(JSObject* obj) {
  MOZ_ASSERT(isGlobal());
  MOZ_ASSERT(IsWindowProxy(obj));
  setReservedSlot(THIS_VALUE_OR_SCOPE_SLOT, ObjectValue(*obj));
}

const JSClass LexicalEnvironmentObject::class_ = {
    "LexicalEnvironment",
    JSCLASS_HAS_RESERVED_SLOTS(LexicalEnvironmentObject::RESERVED_SLOTS),
    JS_NULL_CLASS_OPS,
    JS_NULL_CLASS_SPEC,
    JS_NULL_CLASS_EXT,
    JS_NULL_OBJECT_OPS};

/* static */
NamedLambdaObject* NamedLambdaObject::create(JSContext* cx,
                                             HandleFunction callee,
                                             HandleFunction func,
                                             HandleObject enclosing,
                                             gc::InitialHeap heap) {
  MOZ_ASSERT(callee->isNamedLambda());
  RootedScope scope(cx, callee->nonLazyScript()->maybeNamedLambdaScope());
  MOZ_ASSERT(scope && scope->environmentShape());
  MOZ_ASSERT(scope->environmentShape()->slot() == lambdaSlot());
  MOZ_ASSERT(!scope->environmentShape()->writable());

#ifdef DEBUG
  // There should be exactly one binding in the named lambda scope.
  BindingIter bi(scope);
  bi++;
  MOZ_ASSERT(bi.done());
#endif

  LexicalEnvironmentObject* obj = LexicalEnvironmentObject::create(
      cx, scope.as<LexicalScope>(), enclosing, heap);
  if (!obj) {
    return nullptr;
  }

  obj->initFixedSlot(lambdaSlot(), ObjectValue(*func));
  return static_cast<NamedLambdaObject*>(obj);
}

/* static */
NamedLambdaObject* NamedLambdaObject::createTemplateObject(
    JSContext* cx, HandleFunction callee, gc::InitialHeap heap) {
  return create(cx, callee, callee, nullptr, heap);
}

/* static */
NamedLambdaObject* NamedLambdaObject::create(JSContext* cx,
                                             AbstractFramePtr frame) {
  RootedFunction fun(cx, frame.callee());
  RootedObject enclosing(cx, frame.environmentChain());
  return create(cx, fun, fun, enclosing, gc::DefaultHeap);
}

/* static */
size_t NamedLambdaObject::lambdaSlot() {
  // Named lambda environments have exactly one name.
  return JSSLOT_FREE(&LexicalEnvironmentObject::class_);
}

/* static */
RuntimeLexicalErrorObject* RuntimeLexicalErrorObject::create(
    JSContext* cx, HandleObject enclosing, unsigned errorNumber) {
  RuntimeLexicalErrorObject* obj =
      NewObjectWithNullTaggedProto<RuntimeLexicalErrorObject>(
          cx, GenericObject, BaseShape::DELEGATE);
  if (!obj) {
    return nullptr;
  }
  obj->initEnclosingEnvironment(enclosing);
  obj->initReservedSlot(ERROR_SLOT, Int32Value(int32_t(errorNumber)));
  return obj;
}

static void ReportRuntimeLexicalErrorId(JSContext* cx, unsigned errorNumber,
                                        HandleId id) {
  if (JSID_IS_ATOM(id)) {
    RootedPropertyName name(cx, JSID_TO_ATOM(id)->asPropertyName());
    ReportRuntimeLexicalError(cx, errorNumber, name);
    return;
  }
  MOZ_CRASH(
      "RuntimeLexicalErrorObject should only be used with property names");
}

static bool lexicalError_LookupProperty(JSContext* cx, HandleObject obj,
                                        HandleId id, MutableHandleObject objp,
                                        MutableHandle<PropertyResult> propp) {
  ReportRuntimeLexicalErrorId(
      cx, obj->as<RuntimeLexicalErrorObject>().errorNumber(), id);
  return false;
}

static bool lexicalError_HasProperty(JSContext* cx, HandleObject obj,
                                     HandleId id, bool* foundp) {
  ReportRuntimeLexicalErrorId(
      cx, obj->as<RuntimeLexicalErrorObject>().errorNumber(), id);
  return false;
}

static bool lexicalError_GetProperty(JSContext* cx, HandleObject obj,
                                     HandleValue receiver, HandleId id,
                                     MutableHandleValue vp) {
  ReportRuntimeLexicalErrorId(
      cx, obj->as<RuntimeLexicalErrorObject>().errorNumber(), id);
  return false;
}

static bool lexicalError_SetProperty(JSContext* cx, HandleObject obj,
                                     HandleId id, HandleValue v,
                                     HandleValue receiver,
                                     ObjectOpResult& result) {
  ReportRuntimeLexicalErrorId(
      cx, obj->as<RuntimeLexicalErrorObject>().errorNumber(), id);
  return false;
}

static bool lexicalError_GetOwnPropertyDescriptor(
    JSContext* cx, HandleObject obj, HandleId id,
    MutableHandle<PropertyDescriptor> desc) {
  ReportRuntimeLexicalErrorId(
      cx, obj->as<RuntimeLexicalErrorObject>().errorNumber(), id);
  return false;
}

static bool lexicalError_DeleteProperty(JSContext* cx, HandleObject obj,
                                        HandleId id, ObjectOpResult& result) {
  ReportRuntimeLexicalErrorId(
      cx, obj->as<RuntimeLexicalErrorObject>().errorNumber(), id);
  return false;
}

static const ObjectOps RuntimeLexicalErrorObjectObjectOps = {
    lexicalError_LookupProperty,
    nullptr, /* defineProperty */
    lexicalError_HasProperty,
    lexicalError_GetProperty,
    lexicalError_SetProperty,
    lexicalError_GetOwnPropertyDescriptor,
    lexicalError_DeleteProperty,
    nullptr, /* getElements */
    nullptr, /* this */
};

const JSClass RuntimeLexicalErrorObject::class_ = {
    "RuntimeLexicalError",
    JSCLASS_HAS_RESERVED_SLOTS(RuntimeLexicalErrorObject::RESERVED_SLOTS),
    JS_NULL_CLASS_OPS,
    JS_NULL_CLASS_SPEC,
    JS_NULL_CLASS_EXT,
    &RuntimeLexicalErrorObjectObjectOps};

/*****************************************************************************/

EnvironmentIter::EnvironmentIter(JSContext* cx,
                                 const EnvironmentIter& ei
                                     MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)
    : si_(cx, ei.si_.get()), env_(cx, ei.env_), frame_(ei.frame_) {
  MOZ_GUARD_OBJECT_NOTIFIER_INIT;
}

EnvironmentIter::EnvironmentIter(JSContext* cx, JSObject* env,
                                 Scope* scope
                                     MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)
    : si_(cx, ScopeIter(scope)), env_(cx, env), frame_(NullFramePtr()) {
  settle();
  MOZ_GUARD_OBJECT_NOTIFIER_INIT;
}

EnvironmentIter::EnvironmentIter(JSContext* cx, AbstractFramePtr frame,
                                 jsbytecode* pc
                                     MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)
    : si_(cx, frame.script()->innermostScope(pc)),
      env_(cx, frame.environmentChain()),
      frame_(frame) {
  cx->check(frame);
  settle();
  MOZ_GUARD_OBJECT_NOTIFIER_INIT;
}

EnvironmentIter::EnvironmentIter(JSContext* cx, JSObject* env, Scope* scope,
                                 AbstractFramePtr frame
                                     MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)
    : si_(cx, ScopeIter(scope)), env_(cx, env), frame_(frame) {
  cx->check(frame);
  settle();
  MOZ_GUARD_OBJECT_NOTIFIER_INIT;
}

void EnvironmentIter::incrementScopeIter() {
  if (si_.scope()->is<GlobalScope>()) {
    // GlobalScopes may be syntactic or non-syntactic. Non-syntactic
    // GlobalScopes correspond to zero or more non-syntactic
    // EnvironmentsObjects followed by the global lexical scope, then the
    // GlobalObject or another non-EnvironmentObject object.
    if (!env_->is<EnvironmentObject>()) {
      si_++;
    }
  } else {
    si_++;
  }
}

void EnvironmentIter::settle() {
  // Check for trying to iterate a function or eval frame before the prologue
  // has created the CallObject, in which case we have to skip.
  if (frame_ && frame_.hasScript() &&
      frame_.script()->initialEnvironmentShape() &&
      !frame_.hasInitialEnvironment()) {
    // Skip until we're at the enclosing scope of the script.
    while (si_.scope() != frame_.script()->enclosingScope()) {
      if (env_->is<LexicalEnvironmentObject>() &&
          !env_->as<LexicalEnvironmentObject>().isExtensible() &&
          &env_->as<LexicalEnvironmentObject>().scope() == si_.scope()) {
        MOZ_ASSERT(si_.kind() == ScopeKind::NamedLambda ||
                   si_.kind() == ScopeKind::StrictNamedLambda);
        env_ = &env_->as<EnvironmentObject>().enclosingEnvironment();
      }
      incrementScopeIter();
    }
  }

  // Check if we have left the extent of the initial frame after we've
  // settled on a static scope.
  if (frame_ &&
      (!si_ ||
       (frame_.hasScript() &&
        si_.scope() == frame_.script()->enclosingScope()) ||
       (frame_.isWasmDebugFrame() && !si_.scope()->is<WasmFunctionScope>()))) {
    frame_ = NullFramePtr();
  }

#ifdef DEBUG
  if (si_) {
    if (hasSyntacticEnvironment()) {
      Scope* scope = si_.scope();
      if (scope->is<LexicalScope>()) {
        MOZ_ASSERT(scope == &env_->as<LexicalEnvironmentObject>().scope());
      } else if (scope->is<FunctionScope>()) {
        MOZ_ASSERT(
            scope->as<FunctionScope>().script() ==
            env_->as<CallObject>().callee().existingScriptNonDelazifying());
      } else if (scope->is<VarScope>()) {
        MOZ_ASSERT(scope == &env_->as<VarEnvironmentObject>().scope());
      } else if (scope->is<WithScope>()) {
        MOZ_ASSERT(scope == &env_->as<WithEnvironmentObject>().scope());
      } else if (scope->is<EvalScope>()) {
        MOZ_ASSERT(scope == &env_->as<VarEnvironmentObject>().scope());
      } else if (scope->is<GlobalScope>()) {
        MOZ_ASSERT(env_->is<GlobalObject>() ||
                   IsGlobalLexicalEnvironment(env_));
      }
    } else if (hasNonSyntacticEnvironmentObject()) {
      if (env_->is<LexicalEnvironmentObject>()) {
        // The global lexical environment still encloses non-syntactic
        // environment objects.
        MOZ_ASSERT(!env_->as<LexicalEnvironmentObject>().isSyntactic() ||
                   env_->as<LexicalEnvironmentObject>().isGlobal());
      } else if (env_->is<WithEnvironmentObject>()) {
        MOZ_ASSERT(!env_->as<WithEnvironmentObject>().isSyntactic());
      } else {
        MOZ_ASSERT(env_->is<NonSyntacticVariablesObject>());
      }
    }
  }
#endif
}

JSObject& EnvironmentIter::enclosingEnvironment() const {
  // As an engine invariant (maintained internally and asserted by Execute),
  // EnvironmentObjects and non-EnvironmentObjects cannot be interleaved on
  // the scope chain; every scope chain must start with zero or more
  // EnvironmentObjects and terminate with one or more
  // non-EnvironmentObjects (viz., GlobalObject).
  MOZ_ASSERT(done());
  MOZ_ASSERT(!env_->is<EnvironmentObject>());
  return *env_;
}

bool EnvironmentIter::hasNonSyntacticEnvironmentObject() const {
  // The case we're worrying about here is a NonSyntactic static scope
  // which has 0+ corresponding non-syntactic WithEnvironmentObject
  // scopes, a NonSyntacticVariablesObject, or a non-syntactic
  // LexicalEnvironmentObject.
  if (si_.kind() == ScopeKind::NonSyntactic) {
    MOZ_ASSERT_IF(env_->is<WithEnvironmentObject>(),
                  !env_->as<WithEnvironmentObject>().isSyntactic());
    return env_->is<EnvironmentObject>();
  }
  return false;
}

/* static */
HashNumber MissingEnvironmentKey::hash(MissingEnvironmentKey ek) {
  return size_t(ek.frame_.raw()) ^ size_t(ek.scope_);
}

/* static */
bool MissingEnvironmentKey::match(MissingEnvironmentKey ek1,
                                  MissingEnvironmentKey ek2) {
  return ek1.frame_ == ek2.frame_ && ek1.scope_ == ek2.scope_;
}

bool LiveEnvironmentVal::needsSweep() {
  if (scope_) {
    MOZ_ALWAYS_FALSE(IsAboutToBeFinalized(&scope_));
  }
  return false;
}

// Live EnvironmentIter values may be added to DebugEnvironments::liveEnvs, as
// LiveEnvironmentVal instances.  They need to have write barriers when they are
// added to the hash table, but no barriers when rehashing inside GC.  It's a
// nasty hack, but the important thing is that LiveEnvironmentVal and
// MissingEnvironmentKey need to alias each other.
void LiveEnvironmentVal::staticAsserts() {
  static_assert(
      sizeof(LiveEnvironmentVal) == sizeof(MissingEnvironmentKey),
      "LiveEnvironmentVal must be same size of MissingEnvironmentKey");
  static_assert(
      offsetof(LiveEnvironmentVal, scope_) ==
          offsetof(MissingEnvironmentKey, scope_),
      "LiveEnvironmentVal.scope_ must alias MissingEnvironmentKey.scope_");
}

/*****************************************************************************/

namespace {

static void ReportOptimizedOut(JSContext* cx, HandleId id) {
  if (UniqueChars printable =
          IdToPrintableUTF8(cx, id, IdToPrintableBehavior::IdIsIdentifier)) {
    JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
                             JSMSG_DEBUG_OPTIMIZED_OUT, printable.get());
  }
}

/*
 * DebugEnvironmentProxy is the handler for DebugEnvironmentProxy proxy
 * objects. Having a custom handler (rather than trying to reuse js::Wrapper)
 * gives us several important abilities:
 *  - We want to pass the EnvironmentObject as the receiver to forwarded scope
 *    property ops on aliased variables so that Call/Block/With ops do not all
 *    require a 'normalization' step.
 *  - The debug scope proxy can directly manipulate the stack frame to allow
 *    the debugger to read/write args/locals that were otherwise unaliased.
 *  - The debug scope proxy can store unaliased variables after the stack frame
 *    is popped so that they may still be read/written by the debugger.
 *  - The engine has made certain assumptions about the possible reads/writes
 *    in a scope. DebugEnvironmentProxy allows us to prevent the debugger from
 *    breaking those assumptions.
 *  - The engine makes optimizations that are observable to the debugger. The
 *    proxy can either hide these optimizations or make the situation more
 *    clear to the debugger. An example is 'arguments'.
 */
class DebugEnvironmentProxyHandler : public BaseProxyHandler {
  enum Action { SET, GET };

  enum AccessResult { ACCESS_UNALIASED, ACCESS_GENERIC, ACCESS_LOST };

  /*
   * This function handles access to unaliased locals/formals. Since they
   * are unaliased, the values of these variables are not stored in the
   * slots of the normal CallObject and LexicalEnvironmentObject
   * environments and thus must be recovered from somewhere else:
   *  + if the invocation for which the env was created is still executing,
   *    there is a JS frame live on the stack holding the values;
   *  + if the invocation for which the env was created finished executing:
   *     - and there was a DebugEnvironmentProxy associated with env, then
   *       the DebugEnvironments::onPop(Call|Lexical) handler copied out the
   *       unaliased variables. In both cases, a dense array is created in
   *       onPop(Call|Lexical) to hold the unaliased values and attached to
   *       the DebugEnvironmentProxy;
   *     - and there was not a DebugEnvironmentProxy yet associated with the
   *       scope, then the unaliased values are lost and not recoverable.
   *
   * Callers should check accessResult for non-failure results:
   *  - ACCESS_UNALIASED if the access was unaliased and completed
   *  - ACCESS_GENERIC   if the access was aliased or the property not found
   *  - ACCESS_LOST      if the value has been lost to the debugger and the
   *                     action is GET; if the action is SET, we assign to the
   *                     name of the variable on the environment object
   */
  bool handleUnaliasedAccess(JSContext* cx,
                             Handle<DebugEnvironmentProxy*> debugEnv,
                             Handle<EnvironmentObject*> env, HandleId id,
                             Action action, MutableHandleValue vp,
                             AccessResult* accessResult) const {
    MOZ_ASSERT(&debugEnv->environment() == env);
    MOZ_ASSERT_IF(action == SET, !debugEnv->isOptimizedOut());
    *accessResult = ACCESS_GENERIC;
    LiveEnvironmentVal* maybeLiveEnv =
        DebugEnvironments::hasLiveEnvironment(*env);

    // Handle unaliased formals, vars, lets, and consts at function or module
    // scope.
    if (env->is<CallObject>() || env->is<ModuleEnvironmentObject>()) {
      RootedScript script(cx);
      if (env->is<CallObject>()) {
        CallObject& callobj = env->as<CallObject>();
        RootedFunction fun(cx, &callobj.callee());
        script = JSFunction::getOrCreateScript(cx, fun);
        if (!script->ensureHasAnalyzedArgsUsage(cx)) {
          return false;
        }
      } else {
        script = env->as<ModuleEnvironmentObject>().module().maybeScript();
        if (!script) {
          *accessResult = ACCESS_LOST;
          return true;
        }
      }

      BindingIter bi(script);
      while (bi && NameToId(bi.name()->asPropertyName()) != id) {
        bi++;
      }
      if (!bi) {
        return true;
      }

      if (bi.location().kind() == BindingLocation::Kind::Import) {
        return true;
      }

      if (!bi.hasArgumentSlot()) {
        if (bi.closedOver()) {
          return true;
        }

        uint32_t i = bi.location().slot();
        if (maybeLiveEnv) {
          AbstractFramePtr frame = maybeLiveEnv->frame();
          if (action == GET) {
            vp.set(frame.unaliasedLocal(i));
          } else {
            frame.unaliasedLocal(i) = vp;
          }
        } else if (NativeObject* snapshot = debugEnv->maybeSnapshot()) {
          if (action == GET) {
            vp.set(snapshot->getDenseElement(script->numArgs() + i));
          } else {
            snapshot->setDenseElement(script->numArgs() + i, vp);
          }
        } else {
          /* The unaliased value has been lost to the debugger. */
          if (action == GET) {
            *accessResult = ACCESS_LOST;
            return true;
          }
        }
      } else {
        unsigned i = bi.argumentSlot();
        if (bi.closedOver()) {
          return true;
        }

        if (maybeLiveEnv) {
          AbstractFramePtr frame = maybeLiveEnv->frame();
          if (script->argsObjAliasesFormals() && frame.hasArgsObj()) {
            if (action == GET) {
              vp.set(frame.argsObj().arg(i));
            } else {
              frame.argsObj().setArg(i, vp);
            }
          } else {
            if (action == GET) {
              vp.set(frame.unaliasedFormal(i, DONT_CHECK_ALIASING));
            } else {
              frame.unaliasedFormal(i, DONT_CHECK_ALIASING) = vp;
            }
          }
        } else if (NativeObject* snapshot = debugEnv->maybeSnapshot()) {
          if (action == GET) {
            vp.set(snapshot->getDenseElement(i));
          } else {
            snapshot->setDenseElement(i, vp);
          }
        } else {
          /* The unaliased value has been lost to the debugger. */
          if (action == GET) {
            *accessResult = ACCESS_LOST;
            return true;
          }
        }

        if (action == SET) {
          jit::JitScript::MonitorArgType(cx, script, i, vp);
        }
      }

      // It is possible that an optimized out value flows to this
      // location due to Debugger.Frame.prototype.eval operating on a
      // live bailed-out Baseline frame. In that case, treat the access
      // as lost.
      if (vp.isMagic() && vp.whyMagic() == JS_OPTIMIZED_OUT) {
        *accessResult = ACCESS_LOST;
      } else {
        *accessResult = ACCESS_UNALIASED;
      }

      return true;
    }

    /*
     * Handle unaliased vars in functions with parameter expressions and
     * lexical bindings at block scope.
     */
    if (env->is<LexicalEnvironmentObject>() ||
        env->is<VarEnvironmentObject>()) {
      // Currently consider all global and non-syntactic top-level lexical
      // bindings to be aliased.
      if (env->is<LexicalEnvironmentObject>() &&
          env->as<LexicalEnvironmentObject>().isExtensible()) {
        MOZ_ASSERT(IsGlobalLexicalEnvironment(env) ||
                   !IsSyntacticEnvironment(env));
        return true;
      }

      // Currently all vars inside eval var environments are aliased.
      if (env->is<VarEnvironmentObject>() &&
          env->as<VarEnvironmentObject>().isForEval()) {
        return true;
      }

      RootedScope scope(cx, getEnvironmentScope(*env));
      uint32_t firstFrameSlot;
      if (env->is<LexicalEnvironmentObject>()) {
        firstFrameSlot = scope->as<LexicalScope>().firstFrameSlot();
      } else {
        firstFrameSlot = scope->as<VarScope>().firstFrameSlot();
      }

      BindingIter bi(scope);
      while (bi && NameToId(bi.name()->asPropertyName()) != id) {
        bi++;
      }
      if (!bi) {
        return true;
      }

      BindingLocation loc = bi.location();
      if (loc.kind() == BindingLocation::Kind::Environment) {
        return true;
      }

      // Named lambdas that are not closed over are lost.
      if (loc.kind() == BindingLocation::Kind::NamedLambdaCallee) {
        if (action == GET) {
          *accessResult = ACCESS_LOST;
        }
        return true;
      }

      MOZ_ASSERT(loc.kind() == BindingLocation::Kind::Frame);

      if (maybeLiveEnv) {
        AbstractFramePtr frame = maybeLiveEnv->frame();
        uint32_t local = loc.slot();
        MOZ_ASSERT(local < frame.script()->nfixed());
        if (action == GET) {
          vp.set(frame.unaliasedLocal(local));
        } else {
          frame.unaliasedLocal(local) = vp;
        }
      } else if (NativeObject* snapshot = debugEnv->maybeSnapshot()) {
        // Indices in the frame snapshot are offset by the first frame
        // slot. See DebugEnvironments::takeFrameSnapshot.
        MOZ_ASSERT(loc.slot() >= firstFrameSlot);
        uint32_t snapshotIndex = loc.slot() - firstFrameSlot;
        if (action == GET) {
          vp.set(snapshot->getDenseElement(snapshotIndex));
        } else {
          snapshot->setDenseElement(snapshotIndex, vp);
        }
      } else {
        if (action == GET) {
          // A {Lexical,Var}EnvironmentObject whose static scope
          // does not have an environment shape at all is a "hollow"
          // block object reflected for missing block scopes. Their
          // slot values are lost.
          if (!scope->hasEnvironment()) {
            *accessResult = ACCESS_LOST;
            return true;
          }

          if (!GetProperty(cx, env, env, id, vp)) {
            return false;
          }
        } else {
          if (!SetProperty(cx, env, id, vp)) {
            return false;
          }
        }
      }

      // See comment above in analogous CallObject case.
      if (vp.isMagic() && vp.whyMagic() == JS_OPTIMIZED_OUT) {
        *accessResult = ACCESS_LOST;
      } else {
        *accessResult = ACCESS_UNALIASED;
      }

      return true;
    }

    if (env->is<WasmFunctionCallObject>()) {
      if (maybeLiveEnv) {
        RootedScope scope(cx, getEnvironmentScope(*env));
        uint32_t index = 0;
        for (BindingIter bi(scope); bi; bi++) {
          if (JSID_IS_ATOM(id, bi.name())) {
            break;
          }
          MOZ_ASSERT(!bi.isLast());
          index++;
        }

        AbstractFramePtr frame = maybeLiveEnv->frame();
        MOZ_ASSERT(frame.isWasmDebugFrame());
        wasm::DebugFrame* wasmFrame = frame.asWasmDebugFrame();
        if (action == GET) {
          if (!wasmFrame->getLocal(index, vp)) {
            ReportOutOfMemory(cx);
            return false;
          }
          *accessResult = ACCESS_UNALIASED;
        } else {  // if (action == SET)
                  // TODO
        }
      } else {
        *accessResult = ACCESS_LOST;
      }
      return true;
    }

    if (env->is<WasmInstanceEnvironmentObject>()) {
      RootedScope scope(cx, getEnvironmentScope(*env));
      MOZ_ASSERT(scope->is<WasmInstanceScope>());
      uint32_t index = 0;
      for (BindingIter bi(scope); bi; bi++) {
        if (JSID_IS_ATOM(id, bi.name())) {
          break;
        }
        MOZ_ASSERT(!bi.isLast());
        index++;
      }
      Rooted<WasmInstanceScope*> instanceScope(cx,
                                               &scope->as<WasmInstanceScope>());
      wasm::Instance& instance = instanceScope->instance()->instance();

      if (action == GET) {
        if (instanceScope->memoriesStart() <= index &&
            index < instanceScope->globalsStart()) {
          MOZ_ASSERT(instanceScope->memoriesStart() + 1 ==
                     instanceScope->globalsStart());
          vp.set(ObjectValue(*instance.memory()));
        }
        if (instanceScope->globalsStart() <= index) {
          MOZ_ASSERT(index < instanceScope->namesCount());
          if (!instance.debug().getGlobal(
                  instance, index - instanceScope->globalsStart(), vp)) {
            ReportOutOfMemory(cx);
            return false;
          }
        }
        *accessResult = ACCESS_UNALIASED;
      } else {  // if (action == SET)
                // TODO
      }
      return true;
    }

    /* The rest of the internal scopes do not have unaliased vars. */
    MOZ_ASSERT(!IsSyntacticEnvironment(env) ||
               env->is<WithEnvironmentObject>());
    return true;
  }

  static bool isArguments(JSContext* cx, jsid id) {
    return id == NameToId(cx->names().arguments);
  }
  static bool isThis(JSContext* cx, jsid id) {
    return id == NameToId(cx->names().dotThis);
  }

  static bool isFunctionEnvironment(const JSObject& env) {
    return env.is<CallObject>();
  }

  static bool isNonExtensibleLexicalEnvironment(const JSObject& env) {
    return env.is<LexicalEnvironmentObject>() &&
           !env.as<LexicalEnvironmentObject>().isExtensible();
  }

  static Scope* getEnvironmentScope(const JSObject& env) {
    if (isFunctionEnvironment(env)) {
      return env.as<CallObject>().callee().nonLazyScript()->bodyScope();
    }
    if (env.is<ModuleEnvironmentObject>()) {
      JSScript* script =
          env.as<ModuleEnvironmentObject>().module().maybeScript();
      return script ? script->bodyScope() : nullptr;
    }
    if (isNonExtensibleLexicalEnvironment(env)) {
      return &env.as<LexicalEnvironmentObject>().scope();
    }
    if (env.is<VarEnvironmentObject>()) {
      return &env.as<VarEnvironmentObject>().scope();
    }
    if (env.is<WasmInstanceEnvironmentObject>()) {
      return &env.as<WasmInstanceEnvironmentObject>().scope();
    }
    if (env.is<WasmFunctionCallObject>()) {
      return &env.as<WasmFunctionCallObject>().scope();
    }
    return nullptr;
  }

  friend Scope* js::GetEnvironmentScope(const JSObject& env);

  /*
   * In theory, every non-arrow function scope contains an 'arguments'
   * bindings.  However, the engine only adds a binding if 'arguments' is
   * used in the function body. Thus, from the debugger's perspective,
   * 'arguments' may be missing from the list of bindings.
   */
  static bool isMissingArgumentsBinding(EnvironmentObject& env) {
    return isFunctionEnvironment(env) && !env.as<CallObject>()
                                              .callee()
                                              .nonLazyScript()
                                              ->argumentsHasVarBinding();
  }

  /*
   * Similar to 'arguments' above, we don't add a 'this' binding to
   * non-arrow functions if it's not used.
   */
  static bool isMissingThisBinding(EnvironmentObject& env) {
    return isFunctionEnvironmentWithThis(env) &&
           !env.as<CallObject>()
                .callee()
                .nonLazyScript()
                ->functionHasThisBinding();
  }

  /*
   * This function checks if an arguments object needs to be created when
   * the debugger requests 'arguments' for a function scope where the
   * arguments object has been optimized away (either because the binding is
   * missing altogether or because !ScriptAnalysis::needsArgsObj).
   */
  static bool isMissingArguments(JSContext* cx, jsid id,
                                 EnvironmentObject& env) {
    return isArguments(cx, id) && isFunctionEnvironment(env) &&
           !env.as<CallObject>().callee().nonLazyScript()->needsArgsObj();
  }
  static bool isMissingThis(JSContext* cx, jsid id, EnvironmentObject& env) {
    return isThis(cx, id) && isMissingThisBinding(env);
  }

  /*
   * Check if the value is the magic value JS_OPTIMIZED_ARGUMENTS. The
   * arguments analysis may have optimized out the 'arguments', and this
   * magic value could have propagated to other local slots. e.g.,
   *
   *   function f() { var a = arguments; h(); }
   *   function h() { evalInFrame(1, "a.push(0)"); }
   *
   * where evalInFrame(N, str) means to evaluate str N frames up.
   *
   * In this case we don't know we need to recover a missing arguments
   * object until after we've performed the property get.
   */
  static bool isMagicMissingArgumentsValue(EnvironmentObject& env,
                                           HandleValue v) {
    bool isMagic = v.isMagic() && v.whyMagic() == JS_OPTIMIZED_ARGUMENTS;

#ifdef DEBUG
    // The |env| object here is not limited to CallObjects but may also
    // be lexical envs in case of the following:
    //
    //   function f() { { let a = arguments; } }
    //
    // We need to check that |env|'s scope's nearest function scope has an
    // 'arguments' var binding. The environment chain is not sufficient:
    // |f| above will not have a CallObject because there are no aliased
    // body-level bindings.
    if (isMagic) {
      JSFunction* callee = nullptr;
      if (isFunctionEnvironment(env)) {
        callee = &env.as<CallObject>().callee();
      } else {
        // We will never have a WithEnvironmentObject here because no
        // binding accesses on with scopes are unaliased.
        for (ScopeIter si(getEnvironmentScope(env)); si; si++) {
          if (si.kind() == ScopeKind::Function) {
            callee = si.scope()->as<FunctionScope>().canonicalFunction();
            break;
          }
        }
      }
      MOZ_ASSERT(callee && callee->nonLazyScript()->argumentsHasVarBinding());
    }
#endif

    return isMagic;
  }

  /*
   * If the value of |this| is requested before the this-binding has been
   * initialized by JSOP_FUNCTIONTHIS, the this-binding will be |undefined|.
   * In that case, we have to call createMissingThis to initialize the
   * this-binding.
   *
   * Note that an |undefined| this-binding is perfectly valid in strict-mode
   * code, but that's fine: createMissingThis will do the right thing in that
   * case.
   */
  static bool isMaybeUninitializedThisValue(JSContext* cx, jsid id,
                                            const Value& v) {
    return isThis(cx, id) && v.isUndefined();
  }

  /*
   * Create a missing arguments object. If the function returns true but
   * argsObj is null, it means the env is dead.
   */
  static bool createMissingArguments(JSContext* cx, EnvironmentObject& env,
                                     MutableHandleArgumentsObject argsObj) {
    argsObj.set(nullptr);

    LiveEnvironmentVal* maybeEnv = DebugEnvironments::hasLiveEnvironment(env);
    if (!maybeEnv) {
      return true;
    }

    argsObj.set(ArgumentsObject::createUnexpected(cx, maybeEnv->frame()));
    return !!argsObj;
  }

  /*
   * Create a missing this Value. If the function returns true but
   * *success is false, it means the scope is dead.
   */
  static bool createMissingThis(JSContext* cx, EnvironmentObject& env,
                                MutableHandleValue thisv, bool* success) {
    *success = false;

    LiveEnvironmentVal* maybeEnv = DebugEnvironments::hasLiveEnvironment(env);
    if (!maybeEnv) {
      return true;
    }

    if (!GetFunctionThis(cx, maybeEnv->frame(), thisv)) {
      return false;
    }

    // Update the this-argument to avoid boxing primitive |this| more
    // than once.
    maybeEnv->frame().thisArgument() = thisv;
    *success = true;
    return true;
  }

 public:
  static const char family;
  static const DebugEnvironmentProxyHandler singleton;

  constexpr DebugEnvironmentProxyHandler() : BaseProxyHandler(&family) {}

  static bool isFunctionEnvironmentWithThis(const JSObject& env) {
    // All functions except arrows should have their own this binding.
    return isFunctionEnvironment(env) &&
           !env.as<CallObject>().callee().hasLexicalThis();
  }

  bool getPrototypeIfOrdinary(JSContext* cx, HandleObject proxy,
                              bool* isOrdinary,
                              MutableHandleObject protop) const override {
    MOZ_CRASH(
        "shouldn't be possible to access the prototype chain of a "
        "DebugEnvironmentProxyHandler");
  }

  bool preventExtensions(JSContext* cx, HandleObject proxy,
                         ObjectOpResult& result) const override {
    // always [[Extensible]], can't be made non-[[Extensible]], like most
    // proxies
    return result.fail(JSMSG_CANT_CHANGE_EXTENSIBILITY);
  }

  bool isExtensible(JSContext* cx, HandleObject proxy,
                    bool* extensible) const override {
    // See above.
    *extensible = true;
    return true;
  }

  bool getMissingArgumentsPropertyDescriptor(
      JSContext* cx, Handle<DebugEnvironmentProxy*> debugEnv,
      EnvironmentObject& env, MutableHandle<PropertyDescriptor> desc) const {
    RootedArgumentsObject argsObj(cx);
    if (!createMissingArguments(cx, env, &argsObj)) {
      return false;
    }

    if (!argsObj) {
      JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                                JSMSG_DEBUG_NOT_LIVE, "Debugger scope");
      return false;
    }

    desc.object().set(debugEnv);
    desc.setAttributes(JSPROP_READONLY | JSPROP_ENUMERATE | JSPROP_PERMANENT);
    desc.value().setObject(*argsObj);
    desc.setGetter(nullptr);
    desc.setSetter(nullptr);
    return true;
  }
  bool getMissingThisPropertyDescriptor(
      JSContext* cx, Handle<DebugEnvironmentProxy*> debugEnv,
      EnvironmentObject& env, MutableHandle<PropertyDescriptor> desc) const {
    RootedValue thisv(cx);
    bool success;
    if (!createMissingThis(cx, env, &thisv, &success)) {
      return false;
    }

    if (!success) {
      JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                                JSMSG_DEBUG_NOT_LIVE, "Debugger scope");
      return false;
    }

    desc.object().set(debugEnv);
    desc.setAttributes(JSPROP_READONLY | JSPROP_ENUMERATE | JSPROP_PERMANENT);
    desc.value().set(thisv);
    desc.setGetter(nullptr);
    desc.setSetter(nullptr);
    return true;
  }

  bool getOwnPropertyDescriptor(
      JSContext* cx, HandleObject proxy, HandleId id,
      MutableHandle<PropertyDescriptor> desc) const override {
    Rooted<DebugEnvironmentProxy*> debugEnv(
        cx, &proxy->as<DebugEnvironmentProxy>());
    Rooted<EnvironmentObject*> env(cx, &debugEnv->environment());

    if (isMissingArguments(cx, id, *env)) {
      return getMissingArgumentsPropertyDescriptor(cx, debugEnv, *env, desc);
    }

    if (isMissingThis(cx, id, *env)) {
      return getMissingThisPropertyDescriptor(cx, debugEnv, *env, desc);
    }

    RootedValue v(cx);
    AccessResult access;
    if (!handleUnaliasedAccess(cx, debugEnv, env, id, GET, &v, &access)) {
      return false;
    }

    switch (access) {
      case ACCESS_UNALIASED:
        if (isMagicMissingArgumentsValue(*env, v)) {
          return getMissingArgumentsPropertyDescriptor(cx, debugEnv, *env,
                                                       desc);
        }
        desc.object().set(debugEnv);
        desc.setAttributes(JSPROP_READONLY | JSPROP_ENUMERATE |
                           JSPROP_PERMANENT);
        desc.value().set(v);
        desc.setGetter(nullptr);
        desc.setSetter(nullptr);
        return true;
      case ACCESS_GENERIC:
        return JS_GetOwnPropertyDescriptorById(cx, env, id, desc);
      case ACCESS_LOST:
        ReportOptimizedOut(cx, id);
        return false;
      default:
        MOZ_CRASH("bad AccessResult");
    }
  }

  bool getMissingArguments(JSContext* cx, EnvironmentObject& env,
                           MutableHandleValue vp) const {
    RootedArgumentsObject argsObj(cx);
    if (!createMissingArguments(cx, env, &argsObj)) {
      return false;
    }

    if (!argsObj) {
      JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                                JSMSG_DEBUG_NOT_LIVE, "Debugger env");
      return false;
    }

    vp.setObject(*argsObj);
    return true;
  }

  bool getMissingThis(JSContext* cx, EnvironmentObject& env,
                      MutableHandleValue vp) const {
    RootedValue thisv(cx);
    bool success;
    if (!createMissingThis(cx, env, &thisv, &success)) {
      return false;
    }

    if (!success) {
      JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                                JSMSG_DEBUG_NOT_LIVE, "Debugger env");
      return false;
    }

    vp.set(thisv);
    return true;
  }

  bool get(JSContext* cx, HandleObject proxy, HandleValue receiver, HandleId id,
           MutableHandleValue vp) const override {
    Rooted<DebugEnvironmentProxy*> debugEnv(
        cx, &proxy->as<DebugEnvironmentProxy>());
    Rooted<EnvironmentObject*> env(
        cx, &proxy->as<DebugEnvironmentProxy>().environment());

    if (isMissingArguments(cx, id, *env)) {
      return getMissingArguments(cx, *env, vp);
    }

    if (isMissingThis(cx, id, *env)) {
      return getMissingThis(cx, *env, vp);
    }

    AccessResult access;
    if (!handleUnaliasedAccess(cx, debugEnv, env, id, GET, vp, &access)) {
      return false;
    }

    switch (access) {
      case ACCESS_UNALIASED:
        if (isMagicMissingArgumentsValue(*env, vp)) {
          return getMissingArguments(cx, *env, vp);
        }
        if (isMaybeUninitializedThisValue(cx, id, vp)) {
          return getMissingThis(cx, *env, vp);
        }
        return true;
      case ACCESS_GENERIC:
        if (!GetProperty(cx, env, env, id, vp)) {
          return false;
        }
        if (isMaybeUninitializedThisValue(cx, id, vp)) {
          return getMissingThis(cx, *env, vp);
        }
        return true;
      case ACCESS_LOST:
        ReportOptimizedOut(cx, id);
        return false;
      default:
        MOZ_CRASH("bad AccessResult");
    }
  }

  bool getMissingArgumentsMaybeSentinelValue(JSContext* cx,
                                             EnvironmentObject& env,
                                             MutableHandleValue vp) const {
    RootedArgumentsObject argsObj(cx);
    if (!createMissingArguments(cx, env, &argsObj)) {
      return false;
    }
    vp.set(argsObj ? ObjectValue(*argsObj)
                   : MagicValue(JS_OPTIMIZED_ARGUMENTS));
    return true;
  }

  bool getMissingThisMaybeSentinelValue(JSContext* cx, EnvironmentObject& env,
                                        MutableHandleValue vp) const {
    RootedValue thisv(cx);
    bool success;
    if (!createMissingThis(cx, env, &thisv, &success)) {
      return false;
    }
    vp.set(success ? thisv : MagicValue(JS_OPTIMIZED_OUT));
    return true;
  }

  /*
   * Like 'get', but returns sentinel values instead of throwing on
   * exceptional cases.
   */
  bool getMaybeSentinelValue(JSContext* cx,
                             Handle<DebugEnvironmentProxy*> debugEnv,
                             HandleId id, MutableHandleValue vp) const {
    Rooted<EnvironmentObject*> env(cx, &debugEnv->environment());

    if (isMissingArguments(cx, id, *env)) {
      return getMissingArgumentsMaybeSentinelValue(cx, *env, vp);
    }
    if (isMissingThis(cx, id, *env)) {
      return getMissingThisMaybeSentinelValue(cx, *env, vp);
    }

    AccessResult access;
    if (!handleUnaliasedAccess(cx, debugEnv, env, id, GET, vp, &access)) {
      return false;
    }

    switch (access) {
      case ACCESS_UNALIASED:
        if (isMagicMissingArgumentsValue(*env, vp)) {
          return getMissingArgumentsMaybeSentinelValue(cx, *env, vp);
        }
        if (isMaybeUninitializedThisValue(cx, id, vp)) {
          return getMissingThisMaybeSentinelValue(cx, *env, vp);
        }
        return true;
      case ACCESS_GENERIC:
        if (!GetProperty(cx, env, env, id, vp)) {
          return false;
        }
        if (isMaybeUninitializedThisValue(cx, id, vp)) {
          return getMissingThisMaybeSentinelValue(cx, *env, vp);
        }
        return true;
      case ACCESS_LOST:
        vp.setMagic(JS_OPTIMIZED_OUT);
        return true;
      default:
        MOZ_CRASH("bad AccessResult");
    }
  }

  bool set(JSContext* cx, HandleObject proxy, HandleId id, HandleValue v,
           HandleValue receiver, ObjectOpResult& result) const override {
    Rooted<DebugEnvironmentProxy*> debugEnv(
        cx, &proxy->as<DebugEnvironmentProxy>());
    Rooted<EnvironmentObject*> env(
        cx, &proxy->as<DebugEnvironmentProxy>().environment());

    if (debugEnv->isOptimizedOut()) {
      return Throw(cx, id, JSMSG_DEBUG_CANT_SET_OPT_ENV);
    }

    AccessResult access;
    RootedValue valCopy(cx, v);
    if (!handleUnaliasedAccess(cx, debugEnv, env, id, SET, &valCopy, &access)) {
      return false;
    }

    switch (access) {
      case ACCESS_UNALIASED:
        return result.succeed();
      case ACCESS_GENERIC: {
        RootedValue envVal(cx, ObjectValue(*env));
        return SetProperty(cx, env, id, v, envVal, result);
      }
      default:
        MOZ_CRASH("bad AccessResult");
    }
  }

  bool defineProperty(JSContext* cx, HandleObject proxy, HandleId id,
                      Handle<PropertyDescriptor> desc,
                      ObjectOpResult& result) const override {
    Rooted<EnvironmentObject*> env(
        cx, &proxy->as<DebugEnvironmentProxy>().environment());

    bool found;
    if (!has(cx, proxy, id, &found)) {
      return false;
    }
    if (found) {
      return Throw(cx, id, JSMSG_CANT_REDEFINE_PROP);
    }

    return JS_DefinePropertyById(cx, env, id, desc, result);
  }

  bool ownPropertyKeys(JSContext* cx, HandleObject proxy,
                       MutableHandleIdVector props) const override {
    Rooted<EnvironmentObject*> env(
        cx, &proxy->as<DebugEnvironmentProxy>().environment());

    if (isMissingArgumentsBinding(*env)) {
      if (!props.append(NameToId(cx->names().arguments))) {
        return false;
      }
    }
    if (isMissingThisBinding(*env)) {
      if (!props.append(NameToId(cx->names().dotThis))) {
        return false;
      }
    }

    // WithEnvironmentObject isn't a very good proxy.  It doesn't have a
    // JSNewEnumerateOp implementation, because if it just delegated to the
    // target object, the object would indicate that native enumeration is
    // the thing to do, but native enumeration over the WithEnvironmentObject
    // wrapper yields no properties.  So instead here we hack around the
    // issue: punch a hole through to the with object target, then manually
    // examine @@unscopables.
    RootedObject target(cx);
    bool isWith = env->is<WithEnvironmentObject>();
    if (isWith) {
      target = &env->as<WithEnvironmentObject>().object();
    } else {
      target = env;
    }
    if (!GetPropertyKeys(cx, target, JSITER_OWNONLY, props)) {
      return false;
    }

    if (isWith) {
      size_t j = 0;
      for (size_t i = 0; i < props.length(); i++) {
        bool inScope;
        if (!CheckUnscopables(cx, env, props[i], &inScope)) {
          return false;
        }
        if (inScope) {
          props[j++].set(props[i]);
        }
      }
      if (!props.resize(j)) {
        return false;
      }
    }

    /*
     * Environments with Scopes are optimized to not contain unaliased
     * variables so they must be manually appended here.
     */
    if (Scope* scope = getEnvironmentScope(*env)) {
      for (Rooted<BindingIter> bi(cx, BindingIter(scope)); bi; bi++) {
        if (!bi.closedOver() &&
            !props.append(NameToId(bi.name()->asPropertyName()))) {
          return false;
        }
      }
    }

    return true;
  }

  bool has(JSContext* cx, HandleObject proxy, HandleId id_,
           bool* bp) const override {
    RootedId id(cx, id_);
    EnvironmentObject& envObj =
        proxy->as<DebugEnvironmentProxy>().environment();

    if (isArguments(cx, id) && isFunctionEnvironment(envObj)) {
      *bp = true;
      return true;
    }

    // Be careful not to look up '.this' as a normal binding below, it will
    // assert in with_HasProperty.
    if (isThis(cx, id)) {
      *bp = isFunctionEnvironmentWithThis(envObj);
      return true;
    }

    bool found;
    RootedObject env(cx, &envObj);
    if (!JS_HasPropertyById(cx, env, id, &found)) {
      return false;
    }

    if (!found) {
      if (Scope* scope = getEnvironmentScope(*env)) {
        for (BindingIter bi(scope); bi; bi++) {
          if (!bi.closedOver() && NameToId(bi.name()->asPropertyName()) == id) {
            found = true;
            break;
          }
        }
      }
    }

    *bp = found;
    return true;
  }

  bool delete_(JSContext* cx, HandleObject proxy, HandleId id,
               ObjectOpResult& result) const override {
    return result.fail(JSMSG_CANT_DELETE);
  }
};

} /* anonymous namespace */

Scope* js::GetEnvironmentScope(const JSObject& env) {
  return DebugEnvironmentProxyHandler::getEnvironmentScope(env);
}

template <>
bool JSObject::is<js::DebugEnvironmentProxy>() const {
  return IsDerivedProxyObject(this, &DebugEnvironmentProxyHandler::singleton);
}

const char DebugEnvironmentProxyHandler::family = 0;
const DebugEnvironmentProxyHandler DebugEnvironmentProxyHandler::singleton;

/* static */
DebugEnvironmentProxy* DebugEnvironmentProxy::create(JSContext* cx,
                                                     EnvironmentObject& env,
                                                     HandleObject enclosing) {
  MOZ_ASSERT(env.realm() == cx->realm());
  MOZ_ASSERT(!enclosing->is<EnvironmentObject>());

  RootedValue priv(cx, ObjectValue(env));
  JSObject* obj = NewProxyObject(cx, &DebugEnvironmentProxyHandler::singleton,
                                 priv, nullptr /* proto */);
  if (!obj) {
    return nullptr;
  }

  DebugEnvironmentProxy* debugEnv = &obj->as<DebugEnvironmentProxy>();
  debugEnv->setReservedSlot(ENCLOSING_SLOT, ObjectValue(*enclosing));
  debugEnv->setReservedSlot(SNAPSHOT_SLOT, NullValue());

  return debugEnv;
}

EnvironmentObject& DebugEnvironmentProxy::environment() const {
  return target()->as<EnvironmentObject>();
}

JSObject& DebugEnvironmentProxy::enclosingEnvironment() const {
  return reservedSlot(ENCLOSING_SLOT).toObject();
}

ArrayObject* DebugEnvironmentProxy::maybeSnapshot() const {
  JSObject* obj = reservedSlot(SNAPSHOT_SLOT).toObjectOrNull();
  return obj ? &obj->as<ArrayObject>() : nullptr;
}

void DebugEnvironmentProxy::initSnapshot(ArrayObject& o) {
  MOZ_ASSERT(maybeSnapshot() == nullptr);
  setReservedSlot(SNAPSHOT_SLOT, ObjectValue(o));
}

bool DebugEnvironmentProxy::isForDeclarative() const {
  EnvironmentObject& e = environment();
  return e.is<CallObject>() || e.is<VarEnvironmentObject>() ||
         e.is<ModuleEnvironmentObject>() ||
         e.is<WasmInstanceEnvironmentObject>() ||
         e.is<WasmFunctionCallObject>() || e.is<LexicalEnvironmentObject>();
}

/* static */
bool DebugEnvironmentProxy::getMaybeSentinelValue(
    JSContext* cx, Handle<DebugEnvironmentProxy*> env, HandleId id,
    MutableHandleValue vp) {
  return DebugEnvironmentProxyHandler::singleton.getMaybeSentinelValue(cx, env,
                                                                       id, vp);
}

bool DebugEnvironmentProxy::isFunctionEnvironmentWithThis() {
  return DebugEnvironmentProxyHandler::isFunctionEnvironmentWithThis(
      environment());
}

bool DebugEnvironmentProxy::isOptimizedOut() const {
  EnvironmentObject& e = environment();

  if (DebugEnvironments::hasLiveEnvironment(e)) {
    return false;
  }

  if (e.is<LexicalEnvironmentObject>()) {
    return !e.as<LexicalEnvironmentObject>().isExtensible() &&
           !e.as<LexicalEnvironmentObject>().scope().hasEnvironment();
  }

  if (e.is<CallObject>()) {
    return !e.as<CallObject>().callee().needsCallObject() && !maybeSnapshot();
  }

  return false;
}

/*****************************************************************************/

DebugEnvironments::DebugEnvironments(JSContext* cx, Zone* zone)
    : zone_(zone),
      proxiedEnvs(cx),
      missingEnvs(cx->zone()),
      liveEnvs(cx->zone()) {}

DebugEnvironments::~DebugEnvironments() { MOZ_ASSERT(missingEnvs.empty()); }

void DebugEnvironments::trace(JSTracer* trc) { proxiedEnvs.trace(trc); }

void DebugEnvironments::sweep() {
  /*
   * missingEnvs points to debug envs weakly so that debug envs can be
   * released more eagerly.
   */
  for (MissingEnvironmentMap::Enum e(missingEnvs); !e.empty(); e.popFront()) {
    if (IsAboutToBeFinalized(&e.front().value())) {
      /*
       * Note that onPopCall, onPopVar, and onPopLexical rely on
       * missingEnvs to find environment objects that we synthesized for
       * the debugger's sake, and clean up the synthetic environment
       * objects' entries in liveEnvs. So if we remove an entry from
       * missingEnvs here, we must also remove the corresponding
       * liveEnvs entry.
       *
       * Since the DebugEnvironmentProxy is the only thing using its environment
       * object, and the DSO is about to be finalized, you might assume
       * that the synthetic SO is also about to be finalized too, and thus
       * the loop below will take care of things. But complex GC behavior
       * means that marks are only conservative approximations of
       * liveness; we should assume that anything could be marked.
       *
       * Thus, we must explicitly remove the entries from both liveEnvs
       * and missingEnvs here.
       */
      liveEnvs.remove(&e.front().value().unbarrieredGet()->environment());
      e.removeFront();
    } else {
      MissingEnvironmentKey key = e.front().key();
      if (IsForwarded(key.scope())) {
        key.updateScope(Forwarded(key.scope()));
        e.rekeyFront(key);
      }
    }
  }

  /*
   * Scopes can be finalized when a debugger-synthesized EnvironmentObject is
   * no longer reachable via its DebugEnvironmentProxy.
   */
  liveEnvs.sweep();
}

void DebugEnvironments::finish() { proxiedEnvs.clear(); }

#ifdef JSGC_HASH_TABLE_CHECKS
void DebugEnvironments::checkHashTablesAfterMovingGC() {
  /*
   * This is called at the end of StoreBuffer::mark() to check that our
   * postbarriers have worked and that no hashtable keys (or values) are left
   * pointing into the nursery.
   */
  proxiedEnvs.checkAfterMovingGC();
  for (MissingEnvironmentMap::Range r = missingEnvs.all(); !r.empty();
       r.popFront()) {
    CheckGCThingAfterMovingGC(r.front().key().scope());
    // Use unbarrieredGet() to prevent triggering read barrier while collecting.
    CheckGCThingAfterMovingGC(r.front().value().unbarrieredGet());
  }
  for (LiveEnvironmentMap::Range r = liveEnvs.all(); !r.empty(); r.popFront()) {
    CheckGCThingAfterMovingGC(r.front().key());
    CheckGCThingAfterMovingGC(r.front().value().scope_.get());
  }
}
#endif

/*
 * Unfortunately, GetDebugEnvironmentForFrame needs to work even outside debug
 * mode (in particular, JS_GetFrameScopeChain does not require debug mode).
 * Since DebugEnvironments::onPop* are only called in debuggee frames, this
 * means we cannot use any of the maps in DebugEnvironments. This will produce
 * debug scope chains that do not obey the debugger invariants but that is just
 * fine.
 */
static bool CanUseDebugEnvironmentMaps(JSContext* cx) {
  return cx->realm()->isDebuggee();
}

DebugEnvironments* DebugEnvironments::ensureRealmData(JSContext* cx) {
  Realm* realm = cx->realm();
  if (auto* debugEnvs = realm->debugEnvs()) {
    return debugEnvs;
  }

  auto debugEnvs = cx->make_unique<DebugEnvironments>(cx, cx->zone());
  if (!debugEnvs) {
    return nullptr;
  }

  realm->debugEnvsRef() = std::move(debugEnvs);
  return realm->debugEnvs();
}

/* static */
DebugEnvironmentProxy* DebugEnvironments::hasDebugEnvironment(
    JSContext* cx, EnvironmentObject& env) {
  DebugEnvironments* envs = env.realm()->debugEnvs();
  if (!envs) {
    return nullptr;
  }

  if (JSObject* obj = envs->proxiedEnvs.lookup(&env)) {
    MOZ_ASSERT(CanUseDebugEnvironmentMaps(cx));
    return &obj->as<DebugEnvironmentProxy>();
  }

  return nullptr;
}

/* static */
bool DebugEnvironments::addDebugEnvironment(
    JSContext* cx, Handle<EnvironmentObject*> env,
    Handle<DebugEnvironmentProxy*> debugEnv) {
  MOZ_ASSERT(cx->realm() == env->realm());
  MOZ_ASSERT(cx->realm() == debugEnv->nonCCWRealm());

  if (!CanUseDebugEnvironmentMaps(cx)) {
    return true;
  }

  DebugEnvironments* envs = ensureRealmData(cx);
  if (!envs) {
    return false;
  }

  return envs->proxiedEnvs.add(cx, env, debugEnv);
}

/* static */
DebugEnvironmentProxy* DebugEnvironments::hasDebugEnvironment(
    JSContext* cx, const EnvironmentIter& ei) {
  MOZ_ASSERT(!ei.hasSyntacticEnvironment());

  DebugEnvironments* envs = cx->realm()->debugEnvs();
  if (!envs) {
    return nullptr;
  }

  if (MissingEnvironmentMap::Ptr p =
          envs->missingEnvs.lookup(MissingEnvironmentKey(ei))) {
    MOZ_ASSERT(CanUseDebugEnvironmentMaps(cx));
    return p->value();
  }
  return nullptr;
}

/* static */
bool DebugEnvironments::addDebugEnvironment(
    JSContext* cx, const EnvironmentIter& ei,
    Handle<DebugEnvironmentProxy*> debugEnv) {
  MOZ_ASSERT(!ei.hasSyntacticEnvironment());
  MOZ_ASSERT(cx->realm() == debugEnv->nonCCWRealm());
  // Generators should always have environments.
  MOZ_ASSERT_IF(
      ei.scope().is<FunctionScope>(),
      !ei.scope().as<FunctionScope>().canonicalFunction()->isGenerator() &&
          !ei.scope().as<FunctionScope>().canonicalFunction()->isAsync());

  if (!CanUseDebugEnvironmentMaps(cx)) {
    return true;
  }

  DebugEnvironments* envs = ensureRealmData(cx);
  if (!envs) {
    return false;
  }

  MissingEnvironmentKey key(ei);
  MOZ_ASSERT(!envs->missingEnvs.has(key));
  if (!envs->missingEnvs.put(key,
                             WeakHeapPtr<DebugEnvironmentProxy*>(debugEnv))) {
    ReportOutOfMemory(cx);
    return false;
  }

  // Only add to liveEnvs if we synthesized the debug env on a live
  // frame.
  if (ei.withinInitialFrame()) {
    MOZ_ASSERT(!envs->liveEnvs.has(&debugEnv->environment()));
    if (!envs->liveEnvs.put(&debugEnv->environment(), LiveEnvironmentVal(ei))) {
      ReportOutOfMemory(cx);
      return false;
    }
  }

  return true;
}

/* static */
void DebugEnvironments::takeFrameSnapshot(
    JSContext* cx, Handle<DebugEnvironmentProxy*> debugEnv,
    AbstractFramePtr frame) {
  /*
   * When the JS stack frame is popped, the values of unaliased variables
   * are lost. If there is any debug env referring to this environment, save a
   * copy of the unaliased variables' values in an array for later debugger
   * access via DebugEnvironmentProxy::handleUnaliasedAccess.
   *
   * Note: since it is simplest for this function to be infallible, failure
   * in this code will be silently ignored. This does not break any
   * invariants since DebugEnvironmentProxy::maybeSnapshot can already be
   * nullptr.
   */

  JSScript* script = frame.script();

  // Act like no snapshot was taken if we run OOM while taking the snapshot.
  Rooted<GCVector<Value>> vec(cx, GCVector<Value>(cx));
  if (debugEnv->environment().is<CallObject>()) {
    FunctionScope* scope = &script->bodyScope()->as<FunctionScope>();
    uint32_t frameSlotCount = scope->nextFrameSlot();
    MOZ_ASSERT(frameSlotCount <= script->nfixed());

    // For simplicity, copy all frame slots from 0 to the frameSlotCount,
    // even if we don't need all of them (like in the case of a defaults
    // parameter scope having frame slots).
    uint32_t numFormals = frame.numFormalArgs();
    if (!vec.resize(numFormals + frameSlotCount)) {
      cx->recoverFromOutOfMemory();
      return;
    }
    mozilla::PodCopy(vec.begin(), frame.argv(), numFormals);
    for (uint32_t slot = 0; slot < frameSlotCount; slot++) {
      vec[slot + frame.numFormalArgs()].set(frame.unaliasedLocal(slot));
    }

    /*
     * Copy in formals that are not aliased via the scope chain
     * but are aliased via the arguments object.
     */
    if (script->analyzedArgsUsage() && script->needsArgsObj() &&
        frame.hasArgsObj()) {
      for (unsigned i = 0; i < frame.numFormalArgs(); ++i) {
        if (script->formalLivesInArgumentsObject(i)) {
          vec[i].set(frame.argsObj().arg(i));
        }
      }
    }
  } else {
    uint32_t frameSlotStart;
    uint32_t frameSlotEnd;

    if (debugEnv->environment().is<LexicalEnvironmentObject>()) {
      LexicalScope* scope =
          &debugEnv->environment().as<LexicalEnvironmentObject>().scope();
      frameSlotStart = scope->firstFrameSlot();
      frameSlotEnd = scope->nextFrameSlot();
    } else if (debugEnv->environment().is<VarEnvironmentObject>()) {
      VarEnvironmentObject* env =
          &debugEnv->environment().as<VarEnvironmentObject>();
      if (frame.isFunctionFrame()) {
        VarScope* scope = &env->scope().as<VarScope>();
        frameSlotStart = scope->firstFrameSlot();
        frameSlotEnd = scope->nextFrameSlot();
      } else {
        EvalScope* scope = &env->scope().as<EvalScope>();
        MOZ_ASSERT(scope == script->bodyScope());
        frameSlotStart = 0;
        frameSlotEnd = scope->nextFrameSlot();
      }
    } else {
      MOZ_ASSERT(&debugEnv->environment().as<ModuleEnvironmentObject>() ==
                 script->module()->environment());
      ModuleScope* scope = &script->bodyScope()->as<ModuleScope>();
      frameSlotStart = 0;
      frameSlotEnd = scope->nextFrameSlot();
    }

    uint32_t frameSlotCount = frameSlotEnd - frameSlotStart;
    MOZ_ASSERT(frameSlotCount <= script->nfixed());

    if (!vec.resize(frameSlotCount)) {
      cx->recoverFromOutOfMemory();
      return;
    }
    for (uint32_t slot = frameSlotStart; slot < frameSlotCount; slot++) {
      vec[slot - frameSlotStart].set(frame.unaliasedLocal(slot));
    }
  }

  if (vec.length() == 0) {
    return;
  }

  /*
   * Use a dense array as storage (since proxies do not have trace
   * hooks). This array must not escape into the wild.
   */
  RootedArrayObject snapshot(
      cx, NewDenseCopiedArray(cx, vec.length(), vec.begin()));
  if (!snapshot) {
    MOZ_ASSERT(cx->isThrowingOutOfMemory() || cx->isThrowingOverRecursed());
    cx->clearPendingException();
    return;
  }

  debugEnv->initSnapshot(*snapshot);
}

/* static */
void DebugEnvironments::onPopCall(JSContext* cx, AbstractFramePtr frame) {
  cx->check(frame);

  DebugEnvironments* envs = cx->realm()->debugEnvs();
  if (!envs) {
    return;
  }

  Rooted<DebugEnvironmentProxy*> debugEnv(cx, nullptr);

  FunctionScope* funScope = &frame.script()->bodyScope()->as<FunctionScope>();
  if (funScope->hasEnvironment()) {
    MOZ_ASSERT(frame.callee()->needsCallObject());

    /*
     * The frame may be observed before the prologue has created the
     * CallObject. See EnvironmentIter::settle.
     */
    if (!frame.environmentChain()->is<CallObject>()) {
      return;
    }

    if (frame.callee()->isGenerator() || frame.callee()->isAsync()) {
      return;
    }

    CallObject& callobj = frame.environmentChain()->as<CallObject>();
    envs->liveEnvs.remove(&callobj);
    if (JSObject* obj = envs->proxiedEnvs.lookup(&callobj)) {
      debugEnv = &obj->as<DebugEnvironmentProxy>();
    }
  } else {
    MissingEnvironmentKey key(frame, funScope);
    if (MissingEnvironmentMap::Ptr p = envs->missingEnvs.lookup(key)) {
      debugEnv = p->value();
      envs->liveEnvs.remove(&debugEnv->environment().as<CallObject>());
      envs->missingEnvs.remove(p);
    }
  }

  if (debugEnv) {
    DebugEnvironments::takeFrameSnapshot(cx, debugEnv, frame);
  }
}

void DebugEnvironments::onPopLexical(JSContext* cx, AbstractFramePtr frame,
                                     jsbytecode* pc) {
  cx->check(frame);

  DebugEnvironments* envs = cx->realm()->debugEnvs();
  if (!envs) {
    return;
  }

  EnvironmentIter ei(cx, frame, pc);
  onPopLexical(cx, ei);
}

template <typename Environment, typename Scope>
void DebugEnvironments::onPopGeneric(JSContext* cx, const EnvironmentIter& ei) {
  DebugEnvironments* envs = cx->realm()->debugEnvs();
  if (!envs) {
    return;
  }

  MOZ_ASSERT(ei.withinInitialFrame());
  MOZ_ASSERT(ei.scope().is<Scope>());

  Rooted<Environment*> env(cx);
  if (MissingEnvironmentMap::Ptr p =
          envs->missingEnvs.lookup(MissingEnvironmentKey(ei))) {
    env = &p->value()->environment().as<Environment>();
    envs->missingEnvs.remove(p);
  } else if (ei.hasSyntacticEnvironment()) {
    env = &ei.environment().as<Environment>();
  }

  if (env) {
    envs->liveEnvs.remove(env);

    if (JSObject* obj = envs->proxiedEnvs.lookup(env)) {
      Rooted<DebugEnvironmentProxy*> debugEnv(
          cx, &obj->as<DebugEnvironmentProxy>());
      DebugEnvironments::takeFrameSnapshot(cx, debugEnv, ei.initialFrame());
    }
  }
}

void DebugEnvironments::onPopLexical(JSContext* cx, const EnvironmentIter& ei) {
  onPopGeneric<LexicalEnvironmentObject, LexicalScope>(cx, ei);
}

void DebugEnvironments::onPopVar(JSContext* cx, AbstractFramePtr frame,
                                 jsbytecode* pc) {
  cx->check(frame);

  DebugEnvironments* envs = cx->realm()->debugEnvs();
  if (!envs) {
    return;
  }

  EnvironmentIter ei(cx, frame, pc);
  onPopVar(cx, ei);
}

void DebugEnvironments::onPopVar(JSContext* cx, const EnvironmentIter& ei) {
  if (ei.scope().is<EvalScope>()) {
    onPopGeneric<VarEnvironmentObject, EvalScope>(cx, ei);
  } else {
    onPopGeneric<VarEnvironmentObject, VarScope>(cx, ei);
  }
}

void DebugEnvironments::onPopWith(AbstractFramePtr frame) {
  Realm* realm = frame.realm();
  if (DebugEnvironments* envs = realm->debugEnvs()) {
    envs->liveEnvs.remove(
        &frame.environmentChain()->as<WithEnvironmentObject>());
  }
}

void DebugEnvironments::onPopModule(JSContext* cx, const EnvironmentIter& ei) {
  onPopGeneric<ModuleEnvironmentObject, ModuleScope>(cx, ei);
}

void DebugEnvironments::onRealmUnsetIsDebuggee(Realm* realm) {
  if (DebugEnvironments* envs = realm->debugEnvs()) {
    envs->proxiedEnvs.clear();
    envs->missingEnvs.clear();
    envs->liveEnvs.clear();
  }
}

bool DebugEnvironments::updateLiveEnvironments(JSContext* cx) {
  if (!CheckRecursionLimit(cx)) {
    return false;
  }

  /*
   * Note that we must always update the top frame's environment objects'
   * entries in liveEnvs because we can't be sure code hasn't run in that
   * frame to change the environment chain since we were last called. The
   * fp->prevUpToDate() flag indicates whether the environments of frames
   * older than fp are already included in liveEnvs. It might seem simpler
   * to have fp instead carry a flag indicating whether fp itself is
   * accurately described, but then we would need to clear that flag
   * whenever fp ran code. By storing the 'up to date' bit for fp->prev() in
   * fp, simply popping fp effectively clears the flag for us, at exactly
   * the time when execution resumes fp->prev().
   */
  for (AllFramesIter i(cx); !i.done(); ++i) {
    if (!i.hasUsableAbstractFramePtr()) {
      continue;
    }

    AbstractFramePtr frame = i.abstractFramePtr();
    if (frame.realm() != cx->realm()) {
      continue;
    }

    if (frame.isFunctionFrame()) {
      if (frame.callee()->isGenerator() || frame.callee()->isAsync()) {
        continue;
      }
    }

    if (!frame.isDebuggee()) {
      continue;
    }

    RootedObject env(cx);
    RootedScope scope(cx);
    if (!GetFrameEnvironmentAndScope(cx, frame, i.pc(), &env, &scope)) {
      return false;
    }

    for (EnvironmentIter ei(cx, env, scope, frame); ei.withinInitialFrame();
         ei++) {
      if (ei.hasSyntacticEnvironment() && !ei.scope().is<GlobalScope>()) {
        MOZ_ASSERT(ei.environment().realm() == cx->realm());
        DebugEnvironments* envs = ensureRealmData(cx);
        if (!envs) {
          return false;
        }
        if (!envs->liveEnvs.put(&ei.environment(), LiveEnvironmentVal(ei))) {
          return false;
        }
      }
    }

    if (frame.prevUpToDate()) {
      return true;
    }
    MOZ_ASSERT(frame.realm()->isDebuggee());
    frame.setPrevUpToDate();
  }

  return true;
}

LiveEnvironmentVal* DebugEnvironments::hasLiveEnvironment(
    EnvironmentObject& env) {
  DebugEnvironments* envs = env.realm()->debugEnvs();
  if (!envs) {
    return nullptr;
  }

  if (LiveEnvironmentMap::Ptr p = envs->liveEnvs.lookup(&env)) {
    return &p->value();
  }

  return nullptr;
}

/* static */
void DebugEnvironments::unsetPrevUpToDateUntil(JSContext* cx,
                                               AbstractFramePtr until) {
  // This are two exceptions where fp->prevUpToDate() is cleared without
  // popping the frame. When a frame is rematerialized or has its
  // debuggeeness toggled off->on, all frames younger than the frame must
  // have their prevUpToDate set to false. This is because unrematerialized
  // Ion frames and non-debuggee frames are skipped by updateLiveEnvironments.
  // If in the future a frame suddenly gains a usable AbstractFramePtr via
  // rematerialization or becomes a debuggee, the prevUpToDate invariant
  // will no longer hold for older frames on its stack.
  for (AllFramesIter i(cx); !i.done(); ++i) {
    if (!i.hasUsableAbstractFramePtr()) {
      continue;
    }

    AbstractFramePtr frame = i.abstractFramePtr();
    if (frame == until) {
      return;
    }

    if (frame.realm() != cx->realm()) {
      continue;
    }

    frame.unsetPrevUpToDate();
  }
}

/* static */
void DebugEnvironments::forwardLiveFrame(JSContext* cx, AbstractFramePtr from,
                                         AbstractFramePtr to) {
  DebugEnvironments* envs = cx->realm()->debugEnvs();
  if (!envs) {
    return;
  }

  for (MissingEnvironmentMap::Enum e(envs->missingEnvs); !e.empty();
       e.popFront()) {
    MissingEnvironmentKey key = e.front().key();
    if (key.frame() == from) {
      key.updateFrame(to);
      e.rekeyFront(key);
    }
  }

  for (LiveEnvironmentMap::Enum e(envs->liveEnvs); !e.empty(); e.popFront()) {
    LiveEnvironmentVal& val = e.front().value();
    if (val.frame() == from) {
      val.updateFrame(to);
    }
  }
}

/* static */
void DebugEnvironments::traceLiveFrame(JSTracer* trc, AbstractFramePtr frame) {
  for (MissingEnvironmentMap::Enum e(missingEnvs); !e.empty(); e.popFront()) {
    if (e.front().key().frame() == frame) {
      TraceEdge(trc, &e.front().value(), "debug-env-live-frame-missing-env");
    }
  }
}

/*****************************************************************************/

static JSObject* GetDebugEnvironment(JSContext* cx, const EnvironmentIter& ei);

static DebugEnvironmentProxy* GetDebugEnvironmentForEnvironmentObject(
    JSContext* cx, const EnvironmentIter& ei) {
  Rooted<EnvironmentObject*> env(cx, &ei.environment());
  if (DebugEnvironmentProxy* debugEnv =
          DebugEnvironments::hasDebugEnvironment(cx, *env)) {
    return debugEnv;
  }

  EnvironmentIter copy(cx, ei);
  RootedObject enclosingDebug(cx, GetDebugEnvironment(cx, ++copy));
  if (!enclosingDebug) {
    return nullptr;
  }

  Rooted<DebugEnvironmentProxy*> debugEnv(
      cx, DebugEnvironmentProxy::create(cx, *env, enclosingDebug));
  if (!debugEnv) {
    return nullptr;
  }

  if (!DebugEnvironments::addDebugEnvironment(cx, env, debugEnv)) {
    return nullptr;
  }

  return debugEnv;
}

static DebugEnvironmentProxy* GetDebugEnvironmentForMissing(
    JSContext* cx, const EnvironmentIter& ei) {
  MOZ_ASSERT(!ei.hasSyntacticEnvironment() &&
             (ei.scope().is<FunctionScope>() || ei.scope().is<LexicalScope>() ||
              ei.scope().is<WasmInstanceScope>() ||
              ei.scope().is<WasmFunctionScope>() || ei.scope().is<VarScope>()));

  if (DebugEnvironmentProxy* debugEnv =
          DebugEnvironments::hasDebugEnvironment(cx, ei)) {
    return debugEnv;
  }

  EnvironmentIter copy(cx, ei);
  RootedObject enclosingDebug(cx, GetDebugEnvironment(cx, ++copy));
  if (!enclosingDebug) {
    return nullptr;
  }

  /*
   * Create the missing environment object. For lexical environment objects,
   * this takes care of storing variable values after the stack frame has
   * been popped. For call objects, we only use the pretend call object to
   * access callee, bindings and to receive dynamically added
   * properties. Together, this provides the nice invariant that every
   * DebugEnvironmentProxy has a EnvironmentObject.
   *
   * Note: to preserve envChain depth invariants, these lazily-reified
   * envs must not be put on the frame's environment chain; instead, they are
   * maintained via DebugEnvironments hooks.
   */
  Rooted<DebugEnvironmentProxy*> debugEnv(cx);
  if (ei.scope().is<FunctionScope>()) {
    RootedFunction callee(cx,
                          ei.scope().as<FunctionScope>().canonicalFunction());
    // Generators should always reify their scopes.
    MOZ_ASSERT(!callee->isGenerator() && !callee->isAsync());

    JS::ExposeObjectToActiveJS(callee);
    Rooted<CallObject*> callobj(cx,
                                CallObject::createHollowForDebug(cx, callee));
    if (!callobj) {
      return nullptr;
    }

    debugEnv = DebugEnvironmentProxy::create(cx, *callobj, enclosingDebug);
  } else if (ei.scope().is<LexicalScope>()) {
    Rooted<LexicalScope*> lexicalScope(cx, &ei.scope().as<LexicalScope>());
    Rooted<LexicalEnvironmentObject*> env(
        cx, LexicalEnvironmentObject::createHollowForDebug(cx, lexicalScope));
    if (!env) {
      return nullptr;
    }

    debugEnv = DebugEnvironmentProxy::create(cx, *env, enclosingDebug);
  } else if (ei.scope().is<WasmInstanceScope>()) {
    Rooted<WasmInstanceScope*> wasmInstanceScope(
        cx, &ei.scope().as<WasmInstanceScope>());
    Rooted<WasmInstanceEnvironmentObject*> env(
        cx, WasmInstanceEnvironmentObject::createHollowForDebug(
                cx, wasmInstanceScope));
    if (!env) {
      return nullptr;
    }

    debugEnv = DebugEnvironmentProxy::create(cx, *env, enclosingDebug);
  } else if (ei.scope().is<WasmFunctionScope>()) {
    Rooted<WasmFunctionScope*> wasmFunctionScope(
        cx, &ei.scope().as<WasmFunctionScope>());
    RootedObject enclosing(
        cx, &enclosingDebug->as<DebugEnvironmentProxy>().environment());
    Rooted<WasmFunctionCallObject*> callobj(
        cx, WasmFunctionCallObject::createHollowForDebug(cx, enclosing,
                                                         wasmFunctionScope));
    if (!callobj) {
      return nullptr;
    }

    debugEnv = DebugEnvironmentProxy::create(cx, *callobj, enclosingDebug);
  } else {
    Rooted<VarScope*> varScope(cx, &ei.scope().as<VarScope>());
    Rooted<VarEnvironmentObject*> env(
        cx, VarEnvironmentObject::createHollowForDebug(cx, varScope));
    if (!env) {
      return nullptr;
    }

    debugEnv = DebugEnvironmentProxy::create(cx, *env, enclosingDebug);
  }

  if (!debugEnv) {
    return nullptr;
  }

  if (!DebugEnvironments::addDebugEnvironment(cx, ei, debugEnv)) {
    return nullptr;
  }

  return debugEnv;
}

static JSObject* GetDebugEnvironmentForNonEnvironmentObject(
    const EnvironmentIter& ei) {
  JSObject& enclosing = ei.enclosingEnvironment();
#ifdef DEBUG
  JSObject* o = &enclosing;
  while ((o = o->enclosingEnvironment())) {
    MOZ_ASSERT(!o->is<EnvironmentObject>());
  }
#endif
  return &enclosing;
}

static JSObject* GetDebugEnvironment(JSContext* cx, const EnvironmentIter& ei) {
  if (!CheckRecursionLimit(cx)) {
    return nullptr;
  }

  if (ei.done()) {
    return GetDebugEnvironmentForNonEnvironmentObject(ei);
  }

  if (ei.hasAnyEnvironmentObject()) {
    return GetDebugEnvironmentForEnvironmentObject(cx, ei);
  }

  if (ei.scope().is<FunctionScope>() || ei.scope().is<LexicalScope>() ||
      ei.scope().is<WasmInstanceScope>() ||
      ei.scope().is<WasmFunctionScope>() || ei.scope().is<VarScope>()) {
    return GetDebugEnvironmentForMissing(cx, ei);
  }

  EnvironmentIter copy(cx, ei);
  return GetDebugEnvironment(cx, ++copy);
}

JSObject* js::GetDebugEnvironmentForFunction(JSContext* cx,
                                             HandleFunction fun) {
  cx->check(fun);
  MOZ_ASSERT(CanUseDebugEnvironmentMaps(cx));
  if (!DebugEnvironments::updateLiveEnvironments(cx)) {
    return nullptr;
  }
  JSScript* script = JSFunction::getOrCreateScript(cx, fun);
  if (!script) {
    return nullptr;
  }
  EnvironmentIter ei(cx, fun->environment(), script->enclosingScope());
  return GetDebugEnvironment(cx, ei);
}

JSObject* js::GetDebugEnvironmentForFrame(JSContext* cx, AbstractFramePtr frame,
                                          jsbytecode* pc) {
  cx->check(frame);
  if (CanUseDebugEnvironmentMaps(cx) &&
      !DebugEnvironments::updateLiveEnvironments(cx)) {
    return nullptr;
  }

  RootedObject env(cx);
  RootedScope scope(cx);
  if (!GetFrameEnvironmentAndScope(cx, frame, pc, &env, &scope)) {
    return nullptr;
  }

  EnvironmentIter ei(cx, env, scope, frame);
  return GetDebugEnvironment(cx, ei);
}

JSObject* js::GetDebugEnvironmentForGlobalLexicalEnvironment(JSContext* cx) {
  EnvironmentIter ei(cx, &cx->global()->lexicalEnvironment(),
                     &cx->global()->emptyGlobalScope());
  return GetDebugEnvironment(cx, ei);
}

bool js::CreateObjectsForEnvironmentChain(JSContext* cx,
                                          HandleObjectVector chain,
                                          HandleObject terminatingEnv,
                                          MutableHandleObject envObj) {
#ifdef DEBUG
  for (size_t i = 0; i < chain.length(); ++i) {
    cx->check(chain[i]);
    MOZ_ASSERT(!chain[i]->is<GlobalObject>() &&
               !chain[i]->is<NonSyntacticVariablesObject>());
  }
#endif

  // Construct With object wrappers for the things on this environment chain
  // and use the result as the thing to scope the function to.
  Rooted<WithEnvironmentObject*> withEnv(cx);
  RootedObject enclosingEnv(cx, terminatingEnv);
  for (size_t i = chain.length(); i > 0;) {
    withEnv =
        WithEnvironmentObject::createNonSyntactic(cx, chain[--i], enclosingEnv);
    if (!withEnv) {
      return false;
    }
    enclosingEnv = withEnv;
  }

  envObj.set(enclosingEnv);
  return true;
}

JSObject& WithEnvironmentObject::object() const {
  return getReservedSlot(OBJECT_SLOT).toObject();
}

JSObject* WithEnvironmentObject::withThis() const {
  return &getReservedSlot(THIS_SLOT).toObject();
}

bool WithEnvironmentObject::isSyntactic() const {
  Value v = getReservedSlot(SCOPE_SLOT);
  MOZ_ASSERT(v.isPrivateGCThing() || v.isNull());
  return v.isPrivateGCThing();
}

WithScope& WithEnvironmentObject::scope() const {
  MOZ_ASSERT(isSyntactic());
  return *static_cast<WithScope*>(getReservedSlot(SCOPE_SLOT).toGCThing());
}

ModuleEnvironmentObject* js::GetModuleEnvironmentForScript(JSScript* script) {
  ModuleObject* module = GetModuleObjectForScript(script);
  if (!module) {
    return nullptr;
  }

  return module->environment();
}

ModuleObject* js::GetModuleObjectForScript(JSScript* script) {
  for (ScopeIter si(script); si; si++) {
    if (si.kind() == ScopeKind::Module) {
      return si.scope()->as<ModuleScope>().module();
    }
  }
  return nullptr;
}

bool js::GetThisValueForDebuggerMaybeOptimizedOut(JSContext* cx,
                                                  AbstractFramePtr frame,
                                                  jsbytecode* pc,
                                                  MutableHandleValue res) {
  RootedObject scopeChain(cx);
  RootedScope scope(cx);
  if (!GetFrameEnvironmentAndScope(cx, frame, pc, &scopeChain, &scope)) {
    return false;
  }

  for (EnvironmentIter ei(cx, scopeChain, scope, frame); ei; ei++) {
    if (ei.scope().kind() == ScopeKind::Module) {
      res.setUndefined();
      return true;
    }

    if (!ei.scope().is<FunctionScope>() ||
        ei.scope().as<FunctionScope>().canonicalFunction()->hasLexicalThis()) {
      continue;
    }

    RootedScript script(cx, ei.scope().as<FunctionScope>().script());

    // Figure out if we executed JSOP_FUNCTIONTHIS and set it.
    bool executedInitThisOp = false;
    if (script->functionHasThisBinding()) {
      for (jsbytecode* it = script->code(); it < script->codeEnd();
           it = GetNextPc(it)) {
        if (*it == JSOP_FUNCTIONTHIS) {
          // The next op after JSOP_FUNCTIONTHIS always sets it.
          executedInitThisOp = pc > GetNextPc(it);
          break;
        }
      }
    }

    if (ei.withinInitialFrame() && !executedInitThisOp) {
      // Either we're yet to initialize the this-binding
      // (JSOP_FUNCTIONTHIS), or the script does not have a this-binding
      // (because it doesn't use |this|).

      // If our this-argument is an object, or we're in strict mode,
      // the this-binding is always the same as our this-argument.
      if (frame.thisArgument().isObject() || script->strict()) {
        res.set(frame.thisArgument());
        return true;
      }

      // We didn't initialize the this-binding yet. Determine the
      // correct |this| value for this frame (box primitives if not
      // in strict mode), and assign it to the this-argument slot so
      // JSOP_FUNCTIONTHIS will use it and not box a second time.
      if (!GetFunctionThis(cx, frame, res)) {
        return false;
      }
      frame.thisArgument() = res;
      return true;
    }

    if (!script->functionHasThisBinding()) {
      res.setMagic(JS_OPTIMIZED_OUT);
      return true;
    }

    for (Rooted<BindingIter> bi(cx, BindingIter(script)); bi; bi++) {
      if (bi.name() != cx->names().dotThis) {
        continue;
      }

      BindingLocation loc = bi.location();
      if (loc.kind() == BindingLocation::Kind::Environment) {
        RootedObject callObj(cx, &ei.environment().as<CallObject>());
        return GetProperty(cx, callObj, callObj, bi.name()->asPropertyName(),
                           res);
      }

      if (loc.kind() == BindingLocation::Kind::Frame &&
          ei.withinInitialFrame()) {
        res.set(frame.unaliasedLocal(loc.slot()));
      } else {
        res.setMagic(JS_OPTIMIZED_OUT);
      }

      return true;
    }

    MOZ_CRASH("'this' binding must be found");
  }

  GetNonSyntacticGlobalThis(cx, scopeChain, res);
  return true;
}

bool js::CheckLexicalNameConflict(JSContext* cx,
                                  Handle<LexicalEnvironmentObject*> lexicalEnv,
                                  HandleObject varObj,
                                  HandlePropertyName name) {
  const char* redeclKind = nullptr;
  RootedId id(cx, NameToId(name));
  RootedShape shape(cx);
  if (varObj->is<GlobalObject>() &&
      varObj->as<GlobalObject>().realm()->isInVarNames(name)) {
    // ES 15.1.11 step 5.a
    redeclKind = "var";
  } else if ((shape = lexicalEnv->lookup(cx, name))) {
    // ES 15.1.11 step 5.b
    redeclKind = shape->writable() ? "let" : "const";
  } else if (varObj->isNative() &&
             (shape = varObj->as<NativeObject>().lookup(cx, name))) {
    // Faster path for ES 15.1.11 step 5.c-d when the shape can be found
    // without going through a resolve hook.
    if (!shape->configurable()) {
      redeclKind = "non-configurable global property";
    }
  } else {
    // ES 15.1.11 step 5.c-d
    Rooted<PropertyDescriptor> desc(cx);
    if (!GetOwnPropertyDescriptor(cx, varObj, id, &desc)) {
      return false;
    }
    if (desc.object() && desc.hasConfigurable() && !desc.configurable()) {
      redeclKind = "non-configurable global property";
    }
  }

  if (redeclKind) {
    ReportRuntimeRedeclaration(cx, name, redeclKind);
    return false;
  }

  return true;
}

bool js::CheckVarNameConflict(JSContext* cx,
                              Handle<LexicalEnvironmentObject*> lexicalEnv,
                              HandlePropertyName name) {
  if (Shape* shape = lexicalEnv->lookup(cx, name)) {
    ReportRuntimeRedeclaration(cx, name, shape->writable() ? "let" : "const");
    return false;
  }
  return true;
}

static void ReportCannotDeclareGlobalBinding(JSContext* cx,
                                             HandlePropertyName name,
                                             const char* reason) {
  if (UniqueChars printable = AtomToPrintableString(cx, name)) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_CANT_DECLARE_GLOBAL_BINDING,
                              printable.get(), reason);
  }
}

bool js::CheckCanDeclareGlobalBinding(JSContext* cx,
                                      Handle<GlobalObject*> global,
                                      HandlePropertyName name,
                                      bool isFunction) {
  RootedId id(cx, NameToId(name));
  Rooted<PropertyDescriptor> desc(cx);
  if (!GetOwnPropertyDescriptor(cx, global, id, &desc)) {
    return false;
  }

  // ES 8.1.1.4.15 CanDeclareGlobalVar
  // ES 8.1.1.4.16 CanDeclareGlobalFunction

  // Step 4.
  if (!desc.object()) {
    // 8.1.14.15 step 6.
    // 8.1.14.16 step 5.
    if (global->isExtensible()) {
      return true;
    }

    ReportCannotDeclareGlobalBinding(cx, name, "global is non-extensible");
    return false;
  }

  // Global functions have additional restrictions.
  if (isFunction) {
    // 8.1.14.16 step 6.
    if (desc.configurable()) {
      return true;
    }

    // 8.1.14.16 step 7.
    if (desc.isDataDescriptor() && desc.writable() && desc.enumerable()) {
      return true;
    }

    ReportCannotDeclareGlobalBinding(cx, name,
                                     "property must be configurable or "
                                     "both writable and enumerable");
    return false;
  }

  return true;
}

bool js::CheckGlobalDeclarationConflicts(
    JSContext* cx, HandleScript script,
    Handle<LexicalEnvironmentObject*> lexicalEnv, HandleObject varObj) {
  // Due to the extensibility of the global lexical environment, we must
  // check for redeclaring a binding.
  //
  // In the case of non-syntactic environment chains, we are checking
  // redeclarations against the non-syntactic lexical environment and the
  // variables object that the lexical environment corresponds to.
  RootedPropertyName name(cx);
  Rooted<BindingIter> bi(cx, BindingIter(script));

  // ES 15.1.11 GlobalDeclarationInstantiation

  // Step 6.
  //
  // Check 'var' declarations do not conflict with existing bindings in the
  // global lexical environment.
  for (; bi; bi++) {
    if (bi.kind() != BindingKind::Var) {
      break;
    }
    name = bi.name()->asPropertyName();
    if (!CheckVarNameConflict(cx, lexicalEnv, name)) {
      return false;
    }

    // Step 10 and 12.
    //
    // Check that global functions and vars may be declared.
    if (varObj->is<GlobalObject>()) {
      Handle<GlobalObject*> global = varObj.as<GlobalObject>();
      if (!CheckCanDeclareGlobalBinding(cx, global, name,
                                        bi.isTopLevelFunction())) {
        return false;
      }
    }
  }

  // Step 5.
  //
  // Check that lexical bindings do not conflict.
  for (; bi; bi++) {
    name = bi.name()->asPropertyName();
    if (!CheckLexicalNameConflict(cx, lexicalEnv, varObj, name)) {
      return false;
    }
  }

  return true;
}

static bool CheckVarNameConflictsInEnv(JSContext* cx, HandleScript script,
                                       HandleObject obj) {
  Rooted<LexicalEnvironmentObject*> env(cx);

  if (obj->is<LexicalEnvironmentObject>()) {
    env = &obj->as<LexicalEnvironmentObject>();
  } else if (obj->is<DebugEnvironmentProxy>() &&
             obj->as<DebugEnvironmentProxy>()
                 .environment()
                 .is<LexicalEnvironmentObject>()) {
    env = &obj->as<DebugEnvironmentProxy>()
               .environment()
               .as<LexicalEnvironmentObject>();
  } else {
    // Environment cannot contain lexical bindings.
    return true;
  }

  if (env->isSyntactic() && !env->isGlobal() &&
      env->scope().kind() == ScopeKind::SimpleCatch) {
    // Annex B.3.5 allows redeclaring simple (non-destructured) catch
    // parameters with var declarations, except when it appears in a
    // for-of. The for-of allowance is computed in
    // Parser::isVarRedeclaredInEval.
    return true;
  }

  RootedPropertyName name(cx);
  for (BindingIter bi(script); bi; bi++) {
    name = bi.name()->asPropertyName();
    if (!CheckVarNameConflict(cx, env, name)) {
      return false;
    }
  }

  return true;
}

static bool CheckEvalDeclarationConflicts(JSContext* cx, HandleScript script,
                                          HandleObject scopeChain,
                                          HandleObject varObj) {
  if (!script->bodyScope()->as<EvalScope>().hasBindings()) {
    return true;
  }

  RootedObject obj(cx, scopeChain);

  // ES 18.2.1.3.

  // Step 5.
  //
  // Check that a direct eval will not hoist 'var' bindings over lexical
  // bindings with the same name.
  while (obj != varObj) {
    if (!CheckVarNameConflictsInEnv(cx, script, obj)) {
      return false;
    }
    obj = obj->enclosingEnvironment();
  }

  // Step 8.
  //
  // Check that global functions may be declared.
  if (varObj->is<GlobalObject>()) {
    Handle<GlobalObject*> global = varObj.as<GlobalObject>();
    RootedPropertyName name(cx);
    for (Rooted<BindingIter> bi(cx, BindingIter(script)); bi; bi++) {
      name = bi.name()->asPropertyName();
      if (!CheckCanDeclareGlobalBinding(cx, global, name,
                                        bi.isTopLevelFunction())) {
        return false;
      }
    }
  }

  return true;
}

bool js::CheckGlobalOrEvalDeclarationConflicts(JSContext* cx,
                                               HandleObject envChain,
                                               HandleScript script) {
  MOZ_ASSERT(script->isGlobalCode() || script->isForEval());

  RootedObject varObj(cx, &GetVariablesObject(envChain));

  if (script->isForEval()) {
    // Strict eval and eval in parameter default expressions have their
    // own call objects.
    //
    // Non-strict eval may introduce 'var' bindings that conflict with
    // lexical bindings in an enclosing lexical scope.
    if (!script->bodyScope()->hasEnvironment()) {
      MOZ_ASSERT(
          !script->strict() &&
          (!script->enclosingScope()->is<FunctionScope>() ||
           !script->enclosingScope()->as<FunctionScope>().hasParameterExprs()));
      if (!CheckEvalDeclarationConflicts(cx, script, envChain, varObj)) {
        return false;
      }
    }
  } else {
    Rooted<LexicalEnvironmentObject*> lexicalEnv(
        cx, &NearestEnclosingExtensibleLexicalEnvironment(envChain));
    if (!CheckGlobalDeclarationConflicts(cx, script, lexicalEnv, varObj)) {
      return false;
    }
  }

  return true;
}

bool js::InitFunctionEnvironmentObjects(JSContext* cx, AbstractFramePtr frame) {
  MOZ_ASSERT(frame.isFunctionFrame());
  MOZ_ASSERT(frame.callee()->needsSomeEnvironmentObject());

  RootedFunction callee(cx, frame.callee());

  // Named lambdas may have an environment that holds itself for recursion.
  if (callee->needsNamedLambdaEnvironment()) {