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 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292
/* -*- 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/. */

/*
 * JS object implementation.
 */

#include "vm/JSObject-inl.h"

#include "mozilla/ArrayUtils.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/Maybe.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/TemplateLib.h"

#include <string.h>

#include "jsapi.h"
#include "jsexn.h"
#include "jsfriendapi.h"
#include "jsnum.h"
#include "jstypes.h"
#include "jsutil.h"

#include "builtin/Array.h"
#include "builtin/BigInt.h"
#include "builtin/Eval.h"
#include "builtin/Object.h"
#include "builtin/String.h"
#include "builtin/Symbol.h"
#include "builtin/WeakSetObject.h"
#include "frontend/BytecodeCompiler.h"
#include "gc/Policy.h"
#include "jit/BaselineJIT.h"
#include "js/CharacterEncoding.h"
#include "js/MemoryMetrics.h"
#include "js/PropertyDescriptor.h"  // JS::FromPropertyDescriptor
#include "js/PropertySpec.h"        // JSPropertySpec
#include "js/Proxy.h"
#include "js/UbiNode.h"
#include "js/UniquePtr.h"
#include "js/Wrapper.h"
#include "util/Text.h"
#include "util/Windows.h"
#include "vm/ArgumentsObject.h"
#include "vm/BytecodeUtil.h"
#include "vm/DateObject.h"
#include "vm/Interpreter.h"
#include "vm/Iteration.h"
#include "vm/JSAtom.h"
#include "vm/JSContext.h"
#include "vm/JSFunction.h"
#include "vm/JSScript.h"
#include "vm/ProxyObject.h"
#include "vm/RegExpStaticsObject.h"
#include "vm/Shape.h"
#include "vm/TypedArrayObject.h"

#include "builtin/Boolean-inl.h"
#include "builtin/TypedObject-inl.h"
#include "gc/Marking-inl.h"
#include "vm/ArrayObject-inl.h"
#include "vm/BooleanObject-inl.h"
#include "vm/Caches-inl.h"
#include "vm/Compartment-inl.h"
#include "vm/Interpreter-inl.h"
#include "vm/JSAtom-inl.h"
#include "vm/JSContext-inl.h"
#include "vm/JSFunction-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/NumberObject-inl.h"
#include "vm/ObjectGroup-inl.h"
#include "vm/Realm-inl.h"
#include "vm/Shape-inl.h"
#include "vm/StringObject-inl.h"
#include "vm/TypedArrayObject-inl.h"
#include "vm/TypeInference-inl.h"

using namespace js;

void js::ReportNotObject(JSContext* cx, JSErrNum err, int spindex,
                         HandleValue v) {
  MOZ_ASSERT(!v.isObject());
  ReportValueError(cx, err, spindex, v, nullptr);
}

void js::ReportNotObject(JSContext* cx, JSErrNum err, HandleValue v) {
  ReportNotObject(cx, err, JSDVG_SEARCH_STACK, v);
}

void js::ReportNotObject(JSContext* cx, const Value& v) {
  RootedValue value(cx, v);
  ReportNotObject(cx, JSMSG_OBJECT_REQUIRED, value);
}

void js::ReportNotObjectArg(JSContext* cx, const char* nth, const char* fun,
                            HandleValue v) {
  MOZ_ASSERT(!v.isObject());

  UniqueChars bytes;
  if (const char* chars = ValueToSourceForError(cx, v, bytes)) {
    JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
                               JSMSG_OBJECT_REQUIRED_ARG, nth, fun, chars);
  }
}

JS_PUBLIC_API const char* JS::InformalValueTypeName(const Value& v) {
  switch (v.type()) {
    case ValueType::Double:
    case ValueType::Int32:
      return "number";
    case ValueType::Boolean:
      return "boolean";
    case ValueType::Undefined:
      return "undefined";
    case ValueType::Null:
      return "null";
    case ValueType::String:
      return "string";
    case ValueType::Symbol:
      return "symbol";
    case ValueType::BigInt:
      return "bigint";
    case ValueType::Object:
      return v.toObject().getClass()->name;
    case ValueType::Magic:
      return "magic";
    case ValueType::PrivateGCThing:
      break;
  }

  MOZ_CRASH("unexpected type");
}

// ES6 draft rev37 6.2.4.4 FromPropertyDescriptor
JS_PUBLIC_API bool JS::FromPropertyDescriptor(JSContext* cx,
                                              Handle<PropertyDescriptor> desc,
                                              MutableHandleValue vp) {
  AssertHeapIsIdle();
  CHECK_THREAD(cx);
  cx->check(desc);

  // Step 1.
  if (!desc.object()) {
    vp.setUndefined();
    return true;
  }

  return FromPropertyDescriptorToObject(cx, desc, vp);
}

bool js::FromPropertyDescriptorToObject(JSContext* cx,
                                        Handle<PropertyDescriptor> desc,
                                        MutableHandleValue vp) {
  // Step 2-3.
  RootedObject obj(cx, NewBuiltinClassInstance<PlainObject>(cx));
  if (!obj) {
    return false;
  }

  const JSAtomState& names = cx->names();

  // Step 4.
  if (desc.hasValue()) {
    if (!DefineDataProperty(cx, obj, names.value, desc.value())) {
      return false;
    }
  }

  // Step 5.
  RootedValue v(cx);
  if (desc.hasWritable()) {
    v.setBoolean(desc.writable());
    if (!DefineDataProperty(cx, obj, names.writable, v)) {
      return false;
    }
  }

  // Step 6.
  if (desc.hasGetterObject()) {
    if (JSObject* get = desc.getterObject()) {
      v.setObject(*get);
    } else {
      v.setUndefined();
    }
    if (!DefineDataProperty(cx, obj, names.get, v)) {
      return false;
    }
  }

  // Step 7.
  if (desc.hasSetterObject()) {
    if (JSObject* set = desc.setterObject()) {
      v.setObject(*set);
    } else {
      v.setUndefined();
    }
    if (!DefineDataProperty(cx, obj, names.set, v)) {
      return false;
    }
  }

  // Step 8.
  if (desc.hasEnumerable()) {
    v.setBoolean(desc.enumerable());
    if (!DefineDataProperty(cx, obj, names.enumerable, v)) {
      return false;
    }
  }

  // Step 9.
  if (desc.hasConfigurable()) {
    v.setBoolean(desc.configurable());
    if (!DefineDataProperty(cx, obj, names.configurable, v)) {
      return false;
    }
  }

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

bool js::GetFirstArgumentAsObject(JSContext* cx, const CallArgs& args,
                                  const char* method,
                                  MutableHandleObject objp) {
  if (!args.requireAtLeast(cx, method, 1)) {
    return false;
  }

  HandleValue v = args[0];
  if (!v.isObject()) {
    UniqueChars bytes =
        DecompileValueGenerator(cx, JSDVG_SEARCH_STACK, v, nullptr);
    if (!bytes) {
      return false;
    }
    JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
                             JSMSG_UNEXPECTED_TYPE, bytes.get(),
                             "not an object");
    return false;
  }

  objp.set(&v.toObject());
  return true;
}

static bool GetPropertyIfPresent(JSContext* cx, HandleObject obj, HandleId id,
                                 MutableHandleValue vp, bool* foundp) {
  if (!HasProperty(cx, obj, id, foundp)) {
    return false;
  }
  if (!*foundp) {
    vp.setUndefined();
    return true;
  }

  return GetProperty(cx, obj, obj, id, vp);
}

bool js::Throw(JSContext* cx, HandleId id, unsigned errorNumber,
               const char* details) {
  MOZ_ASSERT(js_ErrorFormatString[errorNumber].argCount == (details ? 2 : 1));
  MOZ_ASSERT_IF(details, JS::StringIsASCII(details));

  UniqueChars bytes =
      IdToPrintableUTF8(cx, id, IdToPrintableBehavior::IdIsPropertyKey);
  if (!bytes) {
    return false;
  }

  if (details) {
    JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, errorNumber,
                             bytes.get(), details);
  } else {
    JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, errorNumber,
                             bytes.get());
  }

  return false;
}

/*** PropertyDescriptor operations and DefineProperties *********************/

static const char js_getter_str[] = "getter";
static const char js_setter_str[] = "setter";

static Result<> CheckCallable(JSContext* cx, JSObject* obj,
                              const char* fieldName) {
  if (obj && !obj->isCallable()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_BAD_GET_SET_FIELD, fieldName);
    return cx->alreadyReportedError();
  }
  return Ok();
}

bool js::ToPropertyDescriptor(JSContext* cx, HandleValue descval,
                              bool checkAccessors,
                              MutableHandle<PropertyDescriptor> desc) {
  // step 2
  RootedObject obj(cx,
                   RequireObject(cx, JSMSG_OBJECT_REQUIRED_PROP_DESC, descval));
  if (!obj) {
    return false;
  }

  // step 3
  desc.clear();

  bool found = false;
  RootedId id(cx);
  RootedValue v(cx);
  unsigned attrs = 0;

  // step 4
  id = NameToId(cx->names().enumerable);
  if (!GetPropertyIfPresent(cx, obj, id, &v, &found)) {
    return false;
  }
  if (found) {
    if (ToBoolean(v)) {
      attrs |= JSPROP_ENUMERATE;
    }
  } else {
    attrs |= JSPROP_IGNORE_ENUMERATE;
  }

  // step 5
  id = NameToId(cx->names().configurable);
  if (!GetPropertyIfPresent(cx, obj, id, &v, &found)) {
    return false;
  }
  if (found) {
    if (!ToBoolean(v)) {
      attrs |= JSPROP_PERMANENT;
    }
  } else {
    attrs |= JSPROP_IGNORE_PERMANENT;
  }

  // step 6
  id = NameToId(cx->names().value);
  if (!GetPropertyIfPresent(cx, obj, id, &v, &found)) {
    return false;
  }
  if (found) {
    desc.value().set(v);
  } else {
    attrs |= JSPROP_IGNORE_VALUE;
  }

  // step 7
  id = NameToId(cx->names().writable);
  if (!GetPropertyIfPresent(cx, obj, id, &v, &found)) {
    return false;
  }
  if (found) {
    if (!ToBoolean(v)) {
      attrs |= JSPROP_READONLY;
    }
  } else {
    attrs |= JSPROP_IGNORE_READONLY;
  }

  // step 8
  bool hasGetOrSet;
  id = NameToId(cx->names().get);
  if (!GetPropertyIfPresent(cx, obj, id, &v, &found)) {
    return false;
  }
  hasGetOrSet = found;
  if (found) {
    if (v.isObject()) {
      if (checkAccessors) {
        JS_TRY_OR_RETURN_FALSE(cx,
                               CheckCallable(cx, &v.toObject(), js_getter_str));
      }
      desc.setGetterObject(&v.toObject());
    } else if (!v.isUndefined()) {
      JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                                JSMSG_BAD_GET_SET_FIELD, js_getter_str);
      return false;
    }
    attrs |= JSPROP_GETTER;
  }

  // step 9
  id = NameToId(cx->names().set);
  if (!GetPropertyIfPresent(cx, obj, id, &v, &found)) {
    return false;
  }
  hasGetOrSet |= found;
  if (found) {
    if (v.isObject()) {
      if (checkAccessors) {
        JS_TRY_OR_RETURN_FALSE(cx,
                               CheckCallable(cx, &v.toObject(), js_setter_str));
      }
      desc.setSetterObject(&v.toObject());
    } else if (!v.isUndefined()) {
      JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                                JSMSG_BAD_GET_SET_FIELD, js_setter_str);
      return false;
    }
    attrs |= JSPROP_SETTER;
  }

  // step 10
  if (hasGetOrSet) {
    if (!(attrs & JSPROP_IGNORE_READONLY) || !(attrs & JSPROP_IGNORE_VALUE)) {
      JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                                JSMSG_INVALID_DESCRIPTOR);
      return false;
    }

    // By convention, these bits are not used on accessor descriptors.
    attrs &= ~(JSPROP_IGNORE_READONLY | JSPROP_IGNORE_VALUE);
  }

  desc.setAttributes(attrs);
  MOZ_ASSERT_IF(attrs & JSPROP_READONLY,
                !(attrs & (JSPROP_GETTER | JSPROP_SETTER)));
  return true;
}

Result<> js::CheckPropertyDescriptorAccessors(JSContext* cx,
                                              Handle<PropertyDescriptor> desc) {
  if (desc.hasGetterObject()) {
    MOZ_TRY(CheckCallable(cx, desc.getterObject(), js_getter_str));
  }

  if (desc.hasSetterObject()) {
    MOZ_TRY(CheckCallable(cx, desc.setterObject(), js_setter_str));
  }

  return Ok();
}

void js::CompletePropertyDescriptor(MutableHandle<PropertyDescriptor> desc) {
  desc.assertValid();

  if (desc.isGenericDescriptor() || desc.isDataDescriptor()) {
    if (!desc.hasWritable()) {
      desc.attributesRef() |= JSPROP_READONLY;
    }
    desc.attributesRef() &= ~(JSPROP_IGNORE_READONLY | JSPROP_IGNORE_VALUE);
  } else {
    if (!desc.hasGetterObject()) {
      desc.setGetterObject(nullptr);
    }
    if (!desc.hasSetterObject()) {
      desc.setSetterObject(nullptr);
    }
    desc.attributesRef() |= JSPROP_GETTER | JSPROP_SETTER;
  }
  if (!desc.hasConfigurable()) {
    desc.attributesRef() |= JSPROP_PERMANENT;
  }
  desc.attributesRef() &= ~(JSPROP_IGNORE_PERMANENT | JSPROP_IGNORE_ENUMERATE);

  desc.assertComplete();
}

bool js::ReadPropertyDescriptors(
    JSContext* cx, HandleObject props, bool checkAccessors,
    MutableHandleIdVector ids, MutableHandle<PropertyDescriptorVector> descs) {
  if (!GetPropertyKeys(cx, props, JSITER_OWNONLY | JSITER_SYMBOLS, ids)) {
    return false;
  }

  RootedId id(cx);
  for (size_t i = 0, len = ids.length(); i < len; i++) {
    id = ids[i];
    Rooted<PropertyDescriptor> desc(cx);
    RootedValue v(cx);
    if (!GetProperty(cx, props, props, id, &v) ||
        !ToPropertyDescriptor(cx, v, checkAccessors, &desc) ||
        !descs.append(desc)) {
      return false;
    }
  }
  return true;
}

/*** Seal and freeze ********************************************************/

static unsigned GetSealedOrFrozenAttributes(unsigned attrs,
                                            IntegrityLevel level) {
  // Make all attributes permanent; if freezing, make data attributes
  // read-only.
  if (level == IntegrityLevel::Frozen &&
      !(attrs & (JSPROP_GETTER | JSPROP_SETTER))) {
    return JSPROP_PERMANENT | JSPROP_READONLY;
  }
  return JSPROP_PERMANENT;
}

/* ES6 draft rev 29 (6 Dec 2014) 7.3.13. */
bool js::SetIntegrityLevel(JSContext* cx, HandleObject obj,
                           IntegrityLevel level) {
  cx->check(obj);

  // Steps 3-5. (Steps 1-2 are redundant assertions.)
  if (!PreventExtensions(cx, obj)) {
    return false;
  }

  // Steps 6-9, loosely interpreted.
  if (obj->isNative() && !obj->as<NativeObject>().inDictionaryMode() &&
      !obj->is<TypedArrayObject>() && !obj->is<MappedArgumentsObject>()) {
    HandleNativeObject nobj = obj.as<NativeObject>();

    // Seal/freeze non-dictionary objects by constructing a new shape
    // hierarchy mirroring the original one, which can be shared if many
    // objects with the same structure are sealed/frozen. If we use the
    // generic path below then any non-empty object will be converted to
    // dictionary mode.
    RootedShape last(
        cx, EmptyShape::getInitialShape(
                cx, nobj->getClass(), nobj->taggedProto(),
                nobj->numFixedSlots(), nobj->lastProperty()->getObjectFlags()));
    if (!last) {
      return false;
    }

    // Get an in-order list of the shapes in this object.
    using ShapeVec = GCVector<Shape*, 8>;
    Rooted<ShapeVec> shapes(cx, ShapeVec(cx));
    for (Shape::Range<NoGC> r(nobj->lastProperty()); !r.empty(); r.popFront()) {
      if (!shapes.append(&r.front())) {
        return false;
      }
    }
    Reverse(shapes.begin(), shapes.end());

    for (Shape* shape : shapes) {
      Rooted<StackShape> child(cx, StackShape(shape));
      child.setAttrs(child.attrs() |
                     GetSealedOrFrozenAttributes(child.attrs(), level));

      if (!JSID_IS_EMPTY(child.get().propid) &&
          level == IntegrityLevel::Frozen) {
        MarkTypePropertyNonWritable(cx, nobj, child.get().propid);
      }

      last = cx->zone()->propertyTree().getChild(cx, last, child);
      if (!last) {
        return false;
      }
    }

    MOZ_ASSERT(nobj->lastProperty()->slotSpan() == last->slotSpan());
    MOZ_ALWAYS_TRUE(nobj->setLastProperty(cx, last));

    // Ordinarily ArraySetLength handles this, but we're going behind its back
    // right now, so we must do this manually.
    if (level == IntegrityLevel::Frozen && obj->is<ArrayObject>()) {
      MOZ_ASSERT(!nobj->denseElementsAreCopyOnWrite());
      obj->as<ArrayObject>().setNonWritableLength(cx);
    }
  } else {
    // Steps 6-7.
    RootedIdVector keys(cx);
    if (!GetPropertyKeys(
            cx, obj, JSITER_HIDDEN | JSITER_OWNONLY | JSITER_SYMBOLS, &keys)) {
      return false;
    }

    RootedId id(cx);
    Rooted<PropertyDescriptor> desc(cx);

    const unsigned AllowConfigure =
        JSPROP_IGNORE_ENUMERATE | JSPROP_IGNORE_READONLY | JSPROP_IGNORE_VALUE;
    const unsigned AllowConfigureAndWritable =
        AllowConfigure & ~JSPROP_IGNORE_READONLY;

    // 8.a/9.a. The two different loops are merged here.
    for (size_t i = 0; i < keys.length(); i++) {
      id = keys[i];

      if (level == IntegrityLevel::Sealed) {
        // 8.a.i.
        desc.setAttributes(AllowConfigure | JSPROP_PERMANENT);
      } else {
        // 9.a.i-ii.
        Rooted<PropertyDescriptor> currentDesc(cx);
        if (!GetOwnPropertyDescriptor(cx, obj, id, &currentDesc)) {
          return false;
        }

        // 9.a.iii.
        if (!currentDesc.object()) {
          continue;
        }

        // 9.a.iii.1-2
        if (currentDesc.isAccessorDescriptor()) {
          desc.setAttributes(AllowConfigure | JSPROP_PERMANENT);
        } else {
          desc.setAttributes(AllowConfigureAndWritable | JSPROP_PERMANENT |
                             JSPROP_READONLY);
        }
      }

      // 8.a.i-ii. / 9.a.iii.3-4
      if (!DefineProperty(cx, obj, id, desc)) {
        return false;
      }
    }
  }

  // Finally, freeze or seal the dense elements.
  if (obj->isNative()) {
    ObjectElements::FreezeOrSeal(cx, &obj->as<NativeObject>(), level);
  }

  return true;
}

static bool ResolveLazyProperties(JSContext* cx, HandleNativeObject obj) {
  const JSClass* clasp = obj->getClass();
  if (JSEnumerateOp enumerate = clasp->getEnumerate()) {
    if (!enumerate(cx, obj)) {
      return false;
    }
  }
  if (clasp->getNewEnumerate() && clasp->getResolve()) {
    RootedIdVector properties(cx);
    if (!clasp->getNewEnumerate()(cx, obj, &properties,
                                  /* enumerableOnly = */ false)) {
      return false;
    }

    RootedId id(cx);
    for (size_t i = 0; i < properties.length(); i++) {
      id = properties[i];
      bool found;
      if (!HasOwnProperty(cx, obj, id, &found)) {
        return false;
      }
    }
  }
  return true;
}

// ES6 draft rev33 (12 Feb 2015) 7.3.15
bool js::TestIntegrityLevel(JSContext* cx, HandleObject obj,
                            IntegrityLevel level, bool* result) {
  // Steps 3-6. (Steps 1-2 are redundant assertions.)
  bool status;
  if (!IsExtensible(cx, obj, &status)) {
    return false;
  }
  if (status) {
    *result = false;
    return true;
  }

  // Fast path for native objects.
  if (obj->isNative()) {
    HandleNativeObject nobj = obj.as<NativeObject>();

    // Force lazy properties to be resolved.
    if (!ResolveLazyProperties(cx, nobj)) {
      return false;
    }

    // Typed array elements are non-configurable, writable properties, so
    // if any elements are present, the typed array cannot be frozen.
    if (nobj->is<TypedArrayObject>() &&
        nobj->as<TypedArrayObject>().length() > 0 &&
        level == IntegrityLevel::Frozen) {
      *result = false;
      return true;
    }

    bool hasDenseElements = false;
    for (size_t i = 0; i < nobj->getDenseInitializedLength(); i++) {
      if (nobj->containsDenseElement(i)) {
        hasDenseElements = true;
        break;
      }
    }

    if (hasDenseElements) {
      // Unless the sealed flag is set, dense elements are configurable.
      if (!nobj->denseElementsAreSealed()) {
        *result = false;
        return true;
      }

      // Unless the frozen flag is set, dense elements are writable.
      if (level == IntegrityLevel::Frozen && !nobj->denseElementsAreFrozen()) {
        *result = false;
        return true;
      }
    }

    // Steps 7-9.
    for (Shape::Range<NoGC> r(nobj->lastProperty()); !r.empty(); r.popFront()) {
      Shape* shape = &r.front();

      // Steps 9.c.i-ii.
      if (shape->configurable() ||
          (level == IntegrityLevel::Frozen && shape->isDataDescriptor() &&
           shape->writable())) {
        *result = false;
        return true;
      }
    }
  } else {
    // Steps 7-8.
    RootedIdVector props(cx);
    if (!GetPropertyKeys(
            cx, obj, JSITER_HIDDEN | JSITER_OWNONLY | JSITER_SYMBOLS, &props)) {
      return false;
    }

    // Step 9.
    RootedId id(cx);
    Rooted<PropertyDescriptor> desc(cx);
    for (size_t i = 0, len = props.length(); i < len; i++) {
      id = props[i];

      // Steps 9.a-b.
      if (!GetOwnPropertyDescriptor(cx, obj, id, &desc)) {
        return false;
      }

      // Step 9.c.
      if (!desc.object()) {
        continue;
      }

      // Steps 9.c.i-ii.
      if (desc.configurable() || (level == IntegrityLevel::Frozen &&
                                  desc.isDataDescriptor() && desc.writable())) {
        *result = false;
        return true;
      }
    }
  }

  // Step 10.
  *result = true;
  return true;
}

/* * */

/*
 * Get the GC kind to use for scripted 'new' on the given class.
 * FIXME bug 547327: estimate the size from the allocation site.
 */
static inline gc::AllocKind NewObjectGCKind(const JSClass* clasp) {
  if (clasp == &ArrayObject::class_) {
    return gc::AllocKind::OBJECT8;
  }
  if (clasp == &JSFunction::class_) {
    return gc::AllocKind::OBJECT2;
  }
  return gc::AllocKind::OBJECT4;
}

static inline JSObject* NewObject(JSContext* cx, HandleObjectGroup group,
                                  gc::AllocKind kind, NewObjectKind newKind,
                                  uint32_t initialShapeFlags = 0) {
  const JSClass* clasp = group->clasp();

  MOZ_ASSERT(clasp != &ArrayObject::class_);
  MOZ_ASSERT_IF(clasp == &JSFunction::class_,
                kind == gc::AllocKind::FUNCTION ||
                    kind == gc::AllocKind::FUNCTION_EXTENDED);

  // For objects which can have fixed data following the object, only use
  // enough fixed slots to cover the number of reserved slots in the object,
  // regardless of the allocation kind specified.
  size_t nfixed = ClassCanHaveFixedData(clasp)
                      ? GetGCKindSlots(gc::GetGCObjectKind(clasp), clasp)
                      : GetGCKindSlots(kind, clasp);

  RootedShape shape(cx, EmptyShape::getInitialShape(cx, clasp, group->proto(),
                                                    nfixed, initialShapeFlags));
  if (!shape) {
    return nullptr;
  }

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

  JSObject* obj;
  if (clasp->isJSFunction()) {
    JS_TRY_VAR_OR_RETURN_NULL(cx, obj,
                              JSFunction::create(cx, kind, heap, shape, group));
  } else if (MOZ_LIKELY(clasp->isNative())) {
    JS_TRY_VAR_OR_RETURN_NULL(
        cx, obj, NativeObject::create(cx, kind, heap, shape, group));
  } else {
    MOZ_ASSERT(IsTypedObjectClass(clasp));
    JS_TRY_VAR_OR_RETURN_NULL(
        cx, obj, TypedObject::create(cx, kind, heap, shape, group));
  }

  if (newKind == SingletonObject) {
    RootedObject nobj(cx, obj);
    if (!JSObject::setSingleton(cx, nobj)) {
      return nullptr;
    }
    obj = nobj;
  }

  probes::CreateObject(cx, obj);
  return obj;
}

void NewObjectCache::fillProto(EntryIndex entry, const JSClass* clasp,
                               js::TaggedProto proto, gc::AllocKind kind,
                               NativeObject* obj) {
  MOZ_ASSERT_IF(proto.isObject(), !proto.toObject()->is<GlobalObject>());
  MOZ_ASSERT(obj->taggedProto() == proto);
  return fill(entry, clasp, proto.raw(), kind, obj);
}

bool js::NewObjectWithTaggedProtoIsCachable(JSContext* cx,
                                            Handle<TaggedProto> proto,
                                            NewObjectKind newKind,
                                            const JSClass* clasp) {
  return !cx->isHelperThreadContext() && proto.isObject() &&
         newKind == GenericObject && clasp->isNative() &&
         !proto.toObject()->is<GlobalObject>();
}

JSObject* js::NewObjectWithGivenTaggedProto(JSContext* cx, const JSClass* clasp,
                                            Handle<TaggedProto> proto,
                                            gc::AllocKind allocKind,
                                            NewObjectKind newKind,
                                            uint32_t initialShapeFlags) {
  if (CanChangeToBackgroundAllocKind(allocKind, clasp)) {
    allocKind = ForegroundToBackgroundAllocKind(allocKind);
  }

  bool isCachable =
      NewObjectWithTaggedProtoIsCachable(cx, proto, newKind, clasp);
  if (isCachable) {
    NewObjectCache& cache = cx->caches().newObjectCache;
    NewObjectCache::EntryIndex entry = -1;
    if (cache.lookupProto(clasp, proto.toObject(), allocKind, &entry)) {
      JSObject* obj =
          cache.newObjectFromHit(cx, entry, GetInitialHeap(newKind, clasp));
      if (obj) {
        return obj;
      }
    }
  }

  RootedObjectGroup group(
      cx, ObjectGroup::defaultNewGroup(cx, clasp, proto, nullptr));
  if (!group) {
    return nullptr;
  }

  RootedObject obj(cx,
                   NewObject(cx, group, allocKind, newKind, initialShapeFlags));
  if (!obj) {
    return nullptr;
  }

  if (isCachable && !obj->as<NativeObject>().hasDynamicSlots()) {
    NewObjectCache& cache = cx->caches().newObjectCache;
    NewObjectCache::EntryIndex entry = -1;
    cache.lookupProto(clasp, proto.toObject(), allocKind, &entry);
    cache.fillProto(entry, clasp, proto, allocKind, &obj->as<NativeObject>());
  }

  return obj;
}

static bool NewObjectIsCachable(JSContext* cx, NewObjectKind newKind,
                                const JSClass* clasp) {
  return !cx->isHelperThreadContext() && newKind == GenericObject &&
         clasp->isNative();
}

JSObject* js::NewObjectWithClassProtoCommon(JSContext* cx, const JSClass* clasp,
                                            HandleObject protoArg,
                                            gc::AllocKind allocKind,
                                            NewObjectKind newKind) {
  if (protoArg) {
    return NewObjectWithGivenTaggedProto(cx, clasp, AsTaggedProto(protoArg),
                                         allocKind, newKind);
  }

  if (CanChangeToBackgroundAllocKind(allocKind, clasp)) {
    allocKind = ForegroundToBackgroundAllocKind(allocKind);
  }

  Handle<GlobalObject*> global = cx->global();

  bool isCachable = NewObjectIsCachable(cx, newKind, clasp);
  if (isCachable) {
    NewObjectCache& cache = cx->caches().newObjectCache;
    NewObjectCache::EntryIndex entry = -1;
    if (cache.lookupGlobal(clasp, global, allocKind, &entry)) {
      gc::InitialHeap heap = GetInitialHeap(newKind, clasp);
      JSObject* obj = cache.newObjectFromHit(cx, entry, heap);
      if (obj) {
        return obj;
      }
    }
  }

  // Find the appropriate proto for clasp. Built-in classes have a cached
  // proto on cx->global(); all others get %ObjectPrototype%.
  JSProtoKey protoKey = JSCLASS_CACHED_PROTO_KEY(clasp);
  if (protoKey == JSProto_Null) {
    protoKey = JSProto_Object;
  }

  JSObject* proto = GlobalObject::getOrCreatePrototype(cx, protoKey);
  if (!proto) {
    return nullptr;
  }

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

  JSObject* obj = NewObject(cx, group, allocKind, newKind);
  if (!obj) {
    return nullptr;
  }

  if (isCachable && !obj->as<NativeObject>().hasDynamicSlots()) {
    NewObjectCache& cache = cx->caches().newObjectCache;
    NewObjectCache::EntryIndex entry = -1;
    cache.lookupGlobal(clasp, global, allocKind, &entry);
    cache.fillGlobal(entry, clasp, global, allocKind, &obj->as<NativeObject>());
  }

  return obj;
}

static bool NewObjectWithGroupIsCachable(JSContext* cx, HandleObjectGroup group,
                                         NewObjectKind newKind) {
  if (!group->proto().isObject() || newKind != GenericObject ||
      !group->clasp()->isNative() || cx->isHelperThreadContext()) {
    return false;
  }

  AutoSweepObjectGroup sweep(group);
  return !group->newScript(sweep) || group->newScript(sweep)->analyzed();
}

/*
 * Create a plain object with the specified group. This bypasses getNewGroup to
 * avoid losing creation site information for objects made by scripted 'new'.
 */
JSObject* js::NewObjectWithGroupCommon(JSContext* cx, HandleObjectGroup group,
                                       gc::AllocKind allocKind,
                                       NewObjectKind newKind) {
  MOZ_ASSERT(gc::IsObjectAllocKind(allocKind));
  if (CanChangeToBackgroundAllocKind(allocKind, group->clasp())) {
    allocKind = ForegroundToBackgroundAllocKind(allocKind);
  }

  bool isCachable = NewObjectWithGroupIsCachable(cx, group, newKind);
  if (isCachable) {
    NewObjectCache& cache = cx->caches().newObjectCache;
    NewObjectCache::EntryIndex entry = -1;
    if (cache.lookupGroup(group, allocKind, &entry)) {
      JSObject* obj =
          cache.newObjectFromHit(cx, entry, GetInitialHeap(newKind, group));
      if (obj) {
        return obj;
      }
    }
  }

  JSObject* obj = NewObject(cx, group, allocKind, newKind);
  if (!obj) {
    return nullptr;
  }

  if (isCachable && !obj->as<NativeObject>().hasDynamicSlots()) {
    NewObjectCache& cache = cx->caches().newObjectCache;
    NewObjectCache::EntryIndex entry = -1;
    cache.lookupGroup(group, allocKind, &entry);
    cache.fillGroup(entry, group, allocKind, &obj->as<NativeObject>());
  }

  return obj;
}

bool js::NewObjectScriptedCall(JSContext* cx, MutableHandleObject pobj) {
  jsbytecode* pc;
  RootedScript script(cx, cx->currentScript(&pc));
  gc::AllocKind allocKind = NewObjectGCKind(&PlainObject::class_);
  NewObjectKind newKind = GenericObject;
  if (script &&
      ObjectGroup::useSingletonForAllocationSite(script, pc, JSProto_Object)) {
    newKind = SingletonObject;
  }
  RootedObject obj(
      cx, NewBuiltinClassInstance<PlainObject>(cx, allocKind, newKind));
  if (!obj) {
    return false;
  }

  if (script) {
    /* Try to specialize the group of the object to the scripted call site. */
    if (!ObjectGroup::setAllocationSiteObjectGroup(
            cx, script, pc, obj, newKind == SingletonObject)) {
      return false;
    }
  }

  pobj.set(obj);
  return true;
}

JSObject* js::CreateThis(JSContext* cx, const JSClass* newclasp,
                         HandleObject callee) {
  RootedObject proto(cx);
  if (!GetPrototypeFromConstructor(
          cx, callee, JSCLASS_CACHED_PROTO_KEY(newclasp), &proto)) {
    return nullptr;
  }
  gc::AllocKind kind = NewObjectGCKind(newclasp);
  return NewObjectWithClassProto(cx, newclasp, proto, kind);
}

static inline JSObject* CreateThisForFunctionWithGroup(JSContext* cx,
                                                       HandleObjectGroup group,
                                                       NewObjectKind newKind) {
  TypeNewScript* maybeNewScript;
  {
    AutoSweepObjectGroup sweep(group);
    maybeNewScript = group->newScript(sweep);
  }

  if (maybeNewScript) {
    if (maybeNewScript->analyzed()) {
      // The definite properties analysis has been performed for this
      // group, so get the shape and alloc kind to use from the
      // TypeNewScript's template.
      RootedPlainObject templateObject(cx, maybeNewScript->templateObject());
      MOZ_ASSERT(templateObject->group() == group);

      RootedPlainObject res(cx,
                            CopyInitializerObject(cx, templateObject, newKind));
      if (!res) {
        return nullptr;
      }

      if (newKind == SingletonObject) {
        Rooted<TaggedProto> proto(
            cx, TaggedProto(templateObject->staticPrototype()));
        if (!JSObject::splicePrototype(cx, res, proto)) {
          return nullptr;
        }
      } else {
        res->setGroup(group);
      }
      return res;
    }

    // The initial objects registered with a TypeNewScript can't be in the
    // nursery.
    if (newKind == GenericObject) {
      newKind = TenuredObject;
    }

    // Not enough objects with this group have been created yet, so make a
    // plain object and register it with the group. Use the maximum number
    // of fixed slots, as is also required by the TypeNewScript.
    gc::AllocKind allocKind = GuessObjectGCKind(NativeObject::MAX_FIXED_SLOTS);
    PlainObject* res =
        NewObjectWithGroup<PlainObject>(cx, group, allocKind, newKind);
    if (!res) {
      return nullptr;
    }

    // Make sure group->newScript is still there.
    AutoSweepObjectGroup sweep(group);
    if (newKind != SingletonObject && group->newScript(sweep)) {
      group->newScript(sweep)->registerNewObject(res);
    }

    return res;
  }

  gc::AllocKind allocKind = NewObjectGCKind(&PlainObject::class_);

  if (newKind == SingletonObject) {
    Rooted<TaggedProto> protoRoot(cx, group->proto());
    return NewObjectWithGivenTaggedProto<PlainObject>(cx, protoRoot, allocKind,
                                                      newKind);
  }
  return NewObjectWithGroup<PlainObject>(cx, group, allocKind, newKind);
}

JSObject* js::CreateThisForFunctionWithProto(
    JSContext* cx, HandleFunction callee, HandleObject newTarget,
    HandleObject proto, NewObjectKind newKind /* = GenericObject */) {
  RootedObject res(cx);

  // Ion may call this with a cross-realm callee.
  mozilla::Maybe<AutoRealm> ar;
  if (cx->realm() != callee->realm()) {
    MOZ_ASSERT(cx->compartment() == callee->compartment());
    ar.emplace(cx, callee);
  }

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

    {
      AutoSweepObjectGroup sweep(group);
      if (group->newScript(sweep) && !group->newScript(sweep)->analyzed()) {
        bool regenerate;
        if (!group->newScript(sweep)->maybeAnalyze(cx, group, &regenerate)) {
          return nullptr;
        }
        if (regenerate) {
          // The script was analyzed successfully and may have changed
          // the new type table, so refetch the group.
          group = ObjectGroup::defaultNewGroup(cx, nullptr, TaggedProto(proto),
                                               newTarget);
          AutoSweepObjectGroup sweepNewGroup(group);
          MOZ_ASSERT(group && group->newScript(sweepNewGroup));
        }
      }
    }

    res = CreateThisForFunctionWithGroup(cx, group, newKind);
  } else {
    res = NewBuiltinClassInstance<PlainObject>(cx, newKind);
  }

  if (res) {
    MOZ_ASSERT(res->nonCCWRealm() == callee->realm());
    JSScript* script = JSFunction::getOrCreateScript(cx, callee);
    if (!script) {
      return nullptr;
    }
    jit::JitScript::MonitorThisType(cx, script, TypeSet::ObjectType(res));
  }

  return res;
}

bool js::GetPrototypeFromConstructor(JSContext* cx, HandleObject newTarget,
                                     JSProtoKey intrinsicDefaultProto,
                                     MutableHandleObject proto) {
  RootedValue protov(cx);
  if (!GetProperty(cx, newTarget, newTarget, cx->names().prototype, &protov)) {
    return false;
  }
  if (protov.isObject()) {
    proto.set(&protov.toObject());
  } else if (newTarget->is<JSFunction>() &&
             newTarget->as<JSFunction>().realm() == cx->realm()) {
    // Steps 4.a-b fetch the builtin prototype of the current realm, which we
    // represent as nullptr.
    proto.set(nullptr);
  } else if (intrinsicDefaultProto == JSProto_Null) {
    // Bug 1317416. The caller did not pass a reasonable JSProtoKey, so let the
    // caller select a prototype object. Most likely they will choose one from
    // the wrong realm.
    proto.set(nullptr);
  } else {
    // Step 4.a: Let realm be ? GetFunctionRealm(constructor);
    Realm* realm = JS::GetFunctionRealm(cx, newTarget);
    if (!realm) {
      return false;
    }

    // Step 4.b: Set proto to realm's intrinsic object named
    //           intrinsicDefaultProto.
    {
      mozilla::Maybe<AutoRealm> ar;
      if (cx->realm() != realm) {
        ar.emplace(cx, realm->maybeGlobal());
      }
      proto.set(GlobalObject::getOrCreatePrototype(cx, intrinsicDefaultProto));
    }
    if (!proto) {
      return false;
    }
    if (!cx->compartment()->wrap(cx, proto)) {
      return false;
    }
  }
  return true;
}

JSObject* js::CreateThisForFunction(JSContext* cx, HandleFunction callee,
                                    HandleObject newTarget,
                                    NewObjectKind newKind) {
  RootedObject proto(cx);
  if (!GetPrototypeFromConstructor(cx, newTarget, JSProto_Object, &proto)) {
    return nullptr;
  }

  JSObject* obj =
      CreateThisForFunctionWithProto(cx, callee, newTarget, proto, newKind);

  if (obj && newKind == SingletonObject) {
    RootedPlainObject nobj(cx, &obj->as<PlainObject>());

    /* Reshape the singleton before passing it as the 'this' value. */
    NativeObject::clear(cx, nobj);

    JSScript* calleeScript = callee->nonLazyScript();
    jit::JitScript::MonitorThisType(cx, calleeScript,
                                    TypeSet::ObjectType(nobj));

    return nobj;
  }

  return obj;
}

/* static */
bool JSObject::nonNativeSetProperty(JSContext* cx, HandleObject obj,
                                    HandleId id, HandleValue v,
                                    HandleValue receiver,
                                    ObjectOpResult& result) {
  return obj->getOpsSetProperty()(cx, obj, id, v, receiver, result);
}

/* static */
bool JSObject::nonNativeSetElement(JSContext* cx, HandleObject obj,
                                   uint32_t index, HandleValue v,
                                   HandleValue receiver,
                                   ObjectOpResult& result) {
  RootedId id(cx);
  if (!IndexToId(cx, index, &id)) {
    return false;
  }
  return nonNativeSetProperty(cx, obj, id, v, receiver, result);
}

JS_FRIEND_API bool JS_CopyPropertyFrom(JSContext* cx, HandleId id,
                                       HandleObject target, HandleObject obj,
                                       PropertyCopyBehavior copyBehavior) {
  // |target| must not be a CCW because we need to enter its realm below and
  // CCWs are not associated with a single realm.
  MOZ_ASSERT(!IsCrossCompartmentWrapper(target));

  // |obj| and |cx| are generally not same-compartment with |target| here.
  cx->check(obj, id);
  Rooted<PropertyDescriptor> desc(cx);

  if (!GetOwnPropertyDescriptor(cx, obj, id, &desc)) {
    return false;
  }
  MOZ_ASSERT(desc.object());

  // Silently skip JSGetterOp/JSSetterOp-implemented accessors.
  if (desc.getter() && !desc.hasGetterObject()) {
    return true;
  }
  if (desc.setter() && !desc.hasSetterObject()) {
    return true;
  }

  if (copyBehavior == MakeNonConfigurableIntoConfigurable) {
    // Mask off the JSPROP_PERMANENT bit.
    desc.attributesRef() &= ~JSPROP_PERMANENT;
  }

  JSAutoRealm ar(cx, target);
  cx->markId(id);
  RootedId wrappedId(cx, id);
  if (!cx->compartment()->wrap(cx, &desc)) {
    return false;
  }

  return DefineProperty(cx, target, wrappedId, desc);
}

JS_FRIEND_API bool JS_CopyPropertiesFrom(JSContext* cx, HandleObject target,
                                         HandleObject obj) {
  // Both |obj| and |target| must not be CCWs because we need to enter their
  // realms below and CCWs are not associated with a single realm.
  MOZ_ASSERT(!IsCrossCompartmentWrapper(obj));
  MOZ_ASSERT(!IsCrossCompartmentWrapper(target));

  JSAutoRealm ar(cx, obj);

  RootedIdVector props(cx);
  if (!GetPropertyKeys(cx, obj, JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS,
                       &props)) {
    return false;
  }

  for (size_t i = 0; i < props.length(); ++i) {
    if (!JS_CopyPropertyFrom(cx, props[i], target, obj)) {
      return false;
    }
  }

  return true;
}

static bool CopyProxyObject(JSContext* cx, Handle<ProxyObject*> from,
                            Handle<ProxyObject*> to) {
  MOZ_ASSERT(from->getClass() == to->getClass());

  if (from->is<WrapperObject>() &&
      (Wrapper::wrapperHandler(from)->flags() & Wrapper::CROSS_COMPARTMENT)) {
    to->setCrossCompartmentPrivate(GetProxyPrivate(from));
  } else {
    RootedValue v(cx, GetProxyPrivate(from));
    if (!cx->compartment()->wrap(cx, &v)) {
      return false;
    }
    to->setSameCompartmentPrivate(v);
  }

  MOZ_ASSERT(from->numReservedSlots() == to->numReservedSlots());

  RootedValue v(cx);
  for (size_t n = 0; n < from->numReservedSlots(); n++) {
    v = GetProxyReservedSlot(from, n);
    if (!cx->compartment()->wrap(cx, &v)) {
      return false;
    }
    SetProxyReservedSlot(to, n, v);
  }

  return true;
}

JSObject* js::CloneObject(JSContext* cx, HandleObject obj,
                          Handle<js::TaggedProto> proto) {
  if (!obj->isNative() && !obj->is<ProxyObject>()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_CANT_CLONE_OBJECT);
    return nullptr;
  }

  RootedObject clone(cx);
  if (obj->isNative()) {
    // CloneObject is used to create the target object for JSObject::swap() and
    // swap() requires its arguments are tenured, so ensure tenure allocation.
    clone = NewObjectWithGivenTaggedProto(cx, obj->getClass(), proto,
                                          NewObjectKind::TenuredObject);
    if (!clone) {
      return nullptr;
    }

    if (clone->is<JSFunction>() &&
        (obj->compartment() != clone->compartment())) {
      JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                                JSMSG_CANT_CLONE_OBJECT);
      return nullptr;
    }

    if (obj->as<NativeObject>().hasPrivate()) {
      clone->as<NativeObject>().setPrivate(
          obj->as<NativeObject>().getPrivate());
    }
  } else {
    ProxyOptions options;
    options.setClass(obj->getClass());

    auto* handler = GetProxyHandler(obj);

    // Same as above, require tenure allocation of the clone. This means for
    // proxy objects we need to reject nursery allocatable proxies.
    if (handler->canNurseryAllocate()) {
      JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                                JSMSG_CANT_CLONE_OBJECT);
      return nullptr;
    }

    clone = ProxyObject::New(cx, handler, JS::NullHandleValue, proto, options);
    if (!clone) {
      return nullptr;
    }

    if (!CopyProxyObject(cx, obj.as<ProxyObject>(), clone.as<ProxyObject>())) {
      return nullptr;
    }
  }

  return clone;
}

static bool GetScriptArrayObjectElements(
    HandleArrayObject arr, MutableHandle<GCVector<Value>> values) {
  MOZ_ASSERT(!arr->isSingleton());
  MOZ_ASSERT(!arr->isIndexed());

  size_t length = arr->length();
  if (!values.appendN(MagicValue(JS_ELEMENTS_HOLE), length)) {
    return false;
  }

  size_t initlen = arr->getDenseInitializedLength();
  for (size_t i = 0; i < initlen; i++) {
    values[i].set(arr->getDenseElement(i));
  }

  return true;
}

static bool GetScriptPlainObjectProperties(
    HandleObject obj, MutableHandle<IdValueVector> properties) {
  MOZ_ASSERT(obj->is<PlainObject>());
  PlainObject* nobj = &obj->as<PlainObject>();

  if (!properties.appendN(IdValuePair(), nobj->slotSpan())) {
    return false;
  }

  for (Shape::Range<NoGC> r(nobj->lastProperty()); !r.empty(); r.popFront()) {
    Shape& shape = r.front();
    MOZ_ASSERT(shape.isDataDescriptor());
    uint32_t slot = shape.slot();
    properties[slot].get().id = shape.propid();
    properties[slot].get().value = nobj->getSlot(slot);
  }

  for (size_t i = 0; i < nobj->getDenseInitializedLength(); i++) {
    Value v = nobj->getDenseElement(i);
    if (!v.isMagic(JS_ELEMENTS_HOLE) &&
        !properties.append(IdValuePair(INT_TO_JSID(i), v))) {
      return false;
    }
  }

  return true;
}

static bool DeepCloneValue(JSContext* cx, Value* vp, NewObjectKind newKind) {
  if (vp->isObject()) {
    RootedObject obj(cx, &vp->toObject());
    obj = DeepCloneObjectLiteral(cx, obj, newKind);
    if (!obj) {
      return false;
    }
    vp->setObject(*obj);
  } else {
    cx->markAtomValue(*vp);
  }
  return true;
}

JSObject* js::DeepCloneObjectLiteral(JSContext* cx, HandleObject obj,
                                     NewObjectKind newKind) {
  /* NB: Keep this in sync with XDRObjectLiteral. */
  MOZ_ASSERT_IF(obj->isSingleton(),
                cx->realm()->behaviors().getSingletonsAsTemplates());
  MOZ_ASSERT(obj->is<PlainObject>() || obj->is<ArrayObject>());
  MOZ_ASSERT(newKind != SingletonObject);

  if (obj->is<ArrayObject>()) {
    Rooted<GCVector<Value>> values(cx, GCVector<Value>(cx));
    if (!GetScriptArrayObjectElements(obj.as<ArrayObject>(), &values)) {
      return nullptr;
    }

    // Deep clone any elements.
    for (uint32_t i = 0; i < values.length(); ++i) {
      if (!DeepCloneValue(cx, values[i].address(), newKind)) {
        return nullptr;
      }
    }

    ObjectGroup::NewArrayKind arrayKind = ObjectGroup::NewArrayKind::Normal;
    if (obj->is<ArrayObject>() &&
        obj->as<ArrayObject>().denseElementsAreCopyOnWrite()) {
      arrayKind = ObjectGroup::NewArrayKind::CopyOnWrite;
    }

    return ObjectGroup::newArrayObject(cx, values.begin(), values.length(),
                                       newKind, arrayKind);
  }

  Rooted<IdValueVector> properties(cx, IdValueVector(cx));
  if (!GetScriptPlainObjectProperties(obj, &properties)) {
    return nullptr;
  }

  for (size_t i = 0; i < properties.length(); i++) {
    cx->markId(properties[i].get().id);
    if (!DeepCloneValue(cx, &properties[i].get().value, newKind)) {
      return nullptr;
    }
  }

  if (obj->isSingleton()) {
    newKind = SingletonObject;
  }

  return ObjectGroup::newPlainObject(cx, properties.begin(),
                                     properties.length(), newKind);
}

static bool InitializePropertiesFromCompatibleNativeObject(
    JSContext* cx, HandleNativeObject dst, HandleNativeObject src) {
  cx->check(src, dst);
  MOZ_ASSERT(src->getClass() == dst->getClass());
  MOZ_ASSERT(dst->lastProperty()->getObjectFlags() == 0);
  MOZ_ASSERT(!src->isSingleton());
  MOZ_ASSERT(src->numFixedSlots() == dst->numFixedSlots());

  if (!dst->ensureElements(cx, src->getDenseInitializedLength())) {
    return false;
  }

  uint32_t initialized = src->getDenseInitializedLength();
  for (uint32_t i = 0; i < initialized; ++i) {
    dst->setDenseInitializedLength(i + 1);
    dst->initDenseElement(i, src->getDenseElement(i));
  }

  MOZ_ASSERT(!src->hasPrivate());
  RootedShape shape(cx);
  if (src->staticPrototype() == dst->staticPrototype()) {
    shape = src->lastProperty();
  } else {
    // We need to generate a new shape for dst that has dst's proto but all
    // the property information from src.  Note that we asserted above that
    // dst's object flags are 0.
    shape = EmptyShape::getInitialShape(cx, dst->getClass(), dst->taggedProto(),
                                        dst->numFixedSlots(), 0);
    if (!shape) {
      return false;
    }

    // Get an in-order list of the shapes in the src object.
    Rooted<ShapeVector> shapes(cx, ShapeVector(cx));
    for (Shape::Range<NoGC> r(src->lastProperty()); !r.empty(); r.popFront()) {
      if (!shapes.append(&r.front())) {
        return false;
      }
    }
    Reverse(shapes.begin(), shapes.end());

    for (Shape* shapeToClone : shapes) {
      Rooted<StackShape> child(cx, StackShape(shapeToClone));
      shape = cx->zone()->propertyTree().getChild(cx, shape, child);
      if (!shape) {
        return false;
      }
    }
  }
  size_t span = shape->slotSpan();
  if (!dst->setLastProperty(cx, shape)) {
    return false;
  }
  for (size_t i = JSCLASS_RESERVED_SLOTS(src->getClass()); i < span; i++) {
    dst->setSlot(i, src->getSlot(i));
  }

  return true;
}

JS_FRIEND_API bool JS_InitializePropertiesFromCompatibleNativeObject(
    JSContext* cx, HandleObject dst, HandleObject src) {
  return InitializePropertiesFromCompatibleNativeObject(
      cx, dst.as<NativeObject>(), src.as<NativeObject>());
}

template <XDRMode mode>
XDRResult js::XDRObjectLiteral(XDRState<mode>* xdr, MutableHandleObject obj) {
  /* NB: Keep this in sync with DeepCloneObjectLiteral. */

  JSContext* cx = xdr->cx();
  cx->check(obj);

  // Distinguish between objects and array classes.
  uint32_t isArray = 0;
  {
    if (mode == XDR_ENCODE) {
      MOZ_ASSERT(obj->is<PlainObject>() || obj->is<ArrayObject>());
      isArray = obj->is<ArrayObject>() ? 1 : 0;
    }

    MOZ_TRY(xdr->codeUint32(&isArray));
  }

  RootedValue tmpValue(cx), tmpIdValue(cx);
  RootedId tmpId(cx);

  if (isArray) {
    Rooted<GCVector<Value>> values(cx, GCVector<Value>(cx));
    if (mode == XDR_ENCODE) {
      RootedArrayObject arr(cx, &obj->as<ArrayObject>());
      if (!GetScriptArrayObjectElements(arr, &values)) {
        return xdr->fail(JS::TranscodeResult_Throw);
      }
    }

    uint32_t initialized;
    if (mode == XDR_ENCODE) {
      initialized = values.length();
    }
    MOZ_TRY(xdr->codeUint32(&initialized));
    if (mode == XDR_DECODE &&
        !values.appendN(MagicValue(JS_ELEMENTS_HOLE), initialized)) {
      return xdr->fail(JS::TranscodeResult_Throw);
    }

    // Recursively copy dense elements.
    for (unsigned i = 0; i < initialized; i++) {
      MOZ_TRY(XDRScriptConst(xdr, values[i]));
    }

    uint32_t copyOnWrite;
    if (mode == XDR_ENCODE) {
      copyOnWrite = obj->is<ArrayObject>() &&
                    obj->as<ArrayObject>().denseElementsAreCopyOnWrite();
    }
    MOZ_TRY(xdr->codeUint32(&copyOnWrite));

    if (mode == XDR_DECODE) {
      ObjectGroup::NewArrayKind arrayKind =
          copyOnWrite ? ObjectGroup::NewArrayKind::CopyOnWrite
                      : ObjectGroup::NewArrayKind::Normal;
      obj.set(ObjectGroup::newArrayObject(cx, values.begin(), values.length(),
                                          TenuredObject, arrayKind));
      if (!obj) {
        return xdr->fail(JS::TranscodeResult_Throw);
      }
    }

    return Ok();
  }

  // Code the properties in the object.
  Rooted<IdValueVector> properties(cx, IdValueVector(cx));
  if (mode == XDR_ENCODE && !GetScriptPlainObjectProperties(obj, &properties)) {
    return xdr->fail(JS::TranscodeResult_Throw);
  }

  uint32_t nproperties = properties.length();
  MOZ_TRY(xdr->codeUint32(&nproperties));

  if (mode == XDR_DECODE && !properties.appendN(IdValuePair(), nproperties)) {
    return xdr->fail(JS::TranscodeResult_Throw);
  }

  for (size_t i = 0; i < nproperties; i++) {
    if (mode == XDR_ENCODE) {
      tmpIdValue = IdToValue(properties[i].get().id);
      tmpValue = properties[i].get().value;
    }

    MOZ_TRY(XDRScriptConst(xdr, &tmpIdValue));
    MOZ_TRY(XDRScriptConst(xdr, &tmpValue));

    if (mode == XDR_DECODE) {
      if (!ValueToId<CanGC>(cx, tmpIdValue, &tmpId)) {
        return xdr->fail(JS::TranscodeResult_Throw);
      }
      properties[i].get().id = tmpId;
      properties[i].get().value = tmpValue;
    }
  }

  // Code whether the object is a singleton.
  uint32_t isSingleton;
  if (mode == XDR_ENCODE) {
    isSingleton = obj->isSingleton() ? 1 : 0;
  }
  MOZ_TRY(xdr->codeUint32(&isSingleton));

  if (mode == XDR_DECODE) {
    NewObjectKind newKind = isSingleton ? SingletonObject : TenuredObject;
    obj.set(ObjectGroup::newPlainObject(cx, properties.begin(),
                                        properties.length(), newKind));
    if (!obj) {
      return xdr->fail(JS::TranscodeResult_Throw);
    }
  }

  return Ok();
}

template XDRResult js::XDRObjectLiteral(XDRState<XDR_ENCODE>* xdr,
                                        MutableHandleObject obj);

template XDRResult js::XDRObjectLiteral(XDRState<XDR_DECODE>* xdr,
                                        MutableHandleObject obj);

/* static */
bool NativeObject::fillInAfterSwap(JSContext* cx, HandleNativeObject obj,
                                   NativeObject* old, HandleValueVector values,
                                   void* priv) {
  // This object has just been swapped with some other object, and its shape
  // no longer reflects its allocated size. Correct this information and
  // fill the slots in with the specified values.
  MOZ_ASSERT(obj->slotSpan() == values.length());
  MOZ_ASSERT(!IsInsideNursery(obj));

  size_t oldSlotCount = obj->numDynamicSlots();

  // Make sure the shape's numFixedSlots() is correct.
  size_t nfixed =
      gc::GetGCKindSlots(obj->asTenured().getAllocKind(), obj->getClass());
  if (nfixed != obj->shape()->numFixedSlots()) {
    if (!NativeObject::generateOwnShape(cx, obj)) {
      return false;
    }
    obj->shape()->setNumFixedSlots(nfixed);
  }

  if (obj->hasPrivate()) {
    obj->setPrivate(priv);
  } else {
    MOZ_ASSERT(!priv);
  }

  Zone* zone = obj->zone();
  if (obj->slots_) {
    size_t size = oldSlotCount * sizeof(HeapSlot);
    zone->removeCellMemory(old, size, MemoryUse::ObjectSlots);
    js_free(obj->slots_);
    obj->slots_ = nullptr;
  }

  if (size_t ndynamic =
          dynamicSlotsCount(nfixed, values.length(), obj->getClass())) {
    obj->slots_ = cx->pod_malloc<HeapSlot>(ndynamic);
    if (!obj->slots_) {
      return false;
    }
    size_t size = ndynamic * sizeof(HeapSlot);
    zone->addCellMemory(obj, size, MemoryUse::ObjectSlots);
    Debug_SetSlotRangeToCrashOnTouch(obj->slots_, ndynamic);
  }

  obj->initSlotRange(0, values.begin(), values.length());
  return true;
}

void JSObject::fixDictionaryShapeAfterSwap() {
  // Dictionary shapes can point back to their containing objects, so after
  // swapping the guts of those objects fix the pointers up.
  if (isNative() && as<NativeObject>().inDictionaryMode()) {
    as<NativeObject>().shape()->listp = as<NativeObject>().shapePtr();
  }
}

bool js::ObjectMayBeSwapped(const JSObject* obj) {
  const JSClass* clasp = obj->getClass();

  // We want to optimize Window/globals and Gecko doesn't require transplanting
  // them (only the WindowProxy around them). A Window may be a DOMClass, so we
  // explicitly check if this is a global.
  if (clasp->isGlobal()) {
    return false;
  }

  // WindowProxy, Wrapper, DeadProxyObject, DOMProxy, and DOMClass (non-global)
  // types may be swapped. It is hard to detect DOMProxy from shell, so target
  // proxies in general.
  return clasp->isProxy() || clasp->isDOMClass();
}

static MOZ_MUST_USE bool CopyProxyValuesBeforeSwap(
    JSContext* cx, ProxyObject* proxy, MutableHandleValueVector values) {
  MOZ_ASSERT(values.empty());

  // Remove the GCPtrValues we're about to swap from the store buffer, to
  // ensure we don't trace bogus values.
  gc::StoreBuffer& sb = cx->runtime()->gc.storeBuffer();

  // Reserve space for the private slot and the reserved slots.
  if (!values.reserve(1 + proxy->numReservedSlots())) {
    return false;
  }

  js::detail::ProxyValueArray* valArray =
      js::detail::GetProxyDataLayout(proxy)->values();
  sb.unputValue(&valArray->privateSlot);
  values.infallibleAppend(valArray->privateSlot);

  for (size_t i = 0; i < proxy->numReservedSlots(); i++) {
    sb.unputValue(&valArray->reservedSlots.slots[i]);
    values.infallibleAppend(valArray->reservedSlots.slots[i]);
  }

  return true;
}

bool ProxyObject::initExternalValueArrayAfterSwap(
    JSContext* cx, const HandleValueVector values) {
  MOZ_ASSERT(getClass()->isProxy());

  size_t nreserved = numReservedSlots();

  // |values| contains the private slot and the reserved slots.
  MOZ_ASSERT(values.length() == 1 + nreserved);

  size_t nbytes = js::detail::ProxyValueArray::sizeOf(nreserved);

  auto* valArray = reinterpret_cast<js::detail::ProxyValueArray*>(
      cx->zone()->pod_malloc<uint8_t>(nbytes));
  if (!valArray) {
    return false;
  }

  valArray->privateSlot = values[0];

  for (size_t i = 0; i < nreserved; i++) {
    valArray->reservedSlots.slots[i] = values[i + 1];
  }

  // Note: we allocate external slots iff the proxy had an inline
  // ProxyValueArray, so at this point reservedSlots points into the
  // old object and we don't have to free anything.
  data.reservedSlots = &valArray->reservedSlots;
  return true;
}

/* Use this method with extreme caution. It trades the guts of two objects. */
void JSObject::swap(JSContext* cx, HandleObject a, HandleObject b) {
  // Ensure swap doesn't cause a finalizer to not be run.
  MOZ_ASSERT(IsBackgroundFinalized(a->asTenured().getAllocKind()) ==
             IsBackgroundFinalized(b->asTenured().getAllocKind()));
  MOZ_ASSERT(a->compartment() == b->compartment());

  // You must have entered the objects' compartment before calling this.
  MOZ_ASSERT(cx->compartment() == a->compartment());

  AutoEnterOOMUnsafeRegion oomUnsafe;

  if (!JSObject::getGroup(cx, a)) {
    oomUnsafe.crash("JSObject::swap");
  }
  if (!JSObject::getGroup(cx, b)) {
    oomUnsafe.crash("JSObject::swap");
  }

  // Only certain types of objects are allowed to be swapped. This allows the
  // JITs to better optimize objects that can never swap.
  MOZ_RELEASE_ASSERT(js::ObjectMayBeSwapped(a));
  MOZ_RELEASE_ASSERT(js::ObjectMayBeSwapped(b));

  /*
   * Neither object may be in the nursery, but ensure we update any embedded
   * nursery pointers in either object.
   */
  MOZ_ASSERT(!IsInsideNursery(a) && !IsInsideNursery(b));
  cx->runtime()->gc.storeBuffer().putWholeCell(a);
  cx->runtime()->gc.storeBuffer().putWholeCell(b);

  unsigned r = NotifyGCPreSwap(a, b);

  // Do the fundamental swapping of the contents of two objects.
  MOZ_ASSERT(a->compartment() == b->compartment());
  MOZ_ASSERT(a->is<JSFunction>() == b->is<JSFunction>());

  // Don't try to swap functions with different sizes.
  MOZ_ASSERT_IF(a->is<JSFunction>(),
                a->tenuredSizeOfThis() == b->tenuredSizeOfThis());

  // Watch for oddball objects that have special organizational issues and
  // can't be swapped.
  MOZ_ASSERT(!a->is<RegExpObject>() && !b->is<RegExpObject>());
  MOZ_ASSERT(!a->is<ArrayObject>() && !b->is<ArrayObject>());
  MOZ_ASSERT(!a->is<ArrayBufferObject>() && !b->is<ArrayBufferObject>());
  MOZ_ASSERT(!a->is<TypedArrayObject>() && !b->is<TypedArrayObject>());
  MOZ_ASSERT(!a->is<TypedObject>() && !b->is<TypedObject>());

  // Don't swap objects that may currently be participating in shape
  // teleporting optimizations.
  //
  // See: ReshapeForProtoMutation, ReshapeForShadowedProp
  MOZ_ASSERT_IF(a->isNative() && a->isDelegate(),
                a->taggedProto() == TaggedProto());
  MOZ_ASSERT_IF(b->isNative() && b->isDelegate(),
                b->taggedProto() == TaggedProto());

  bool aIsProxyWithInlineValues =
      a->is<ProxyObject>() && a->as<ProxyObject>().usingInlineValueArray();
  bool bIsProxyWithInlineValues =
      b->is<ProxyObject>() && b->as<ProxyObject>().usingInlineValueArray();

  // Swap element associations.
  Zone* zone = a->zone();
  zone->swapCellMemory(a, b, MemoryUse::ObjectElements);

  if (a->tenuredSizeOfThis() == b->tenuredSizeOfThis()) {
    // When both objects are the same size, just do a plain swap of their
    // contents.

    // Swap slot associations.
    zone->swapCellMemory(a, b, MemoryUse::ObjectSlots);

    size_t size = a->tenuredSizeOfThis();

    char tmp[mozilla::tl::Max<sizeof(JSFunction),
                              sizeof(JSObject_Slots16)>::value];
    MOZ_ASSERT(size <= sizeof(tmp));

    js_memcpy(tmp, a, size);
    js_memcpy(a, b, size);
    js_memcpy(b, tmp, size);

    a->fixDictionaryShapeAfterSwap();
    b->fixDictionaryShapeAfterSwap();

    if (aIsProxyWithInlineValues) {
      b->as<ProxyObject>().setInlineValueArray();
    }
    if (bIsProxyWithInlineValues) {
      a->as<ProxyObject>().setInlineValueArray();
    }
  } else {
    // Avoid GC in here to avoid confusing the tracing code with our
    // intermediate state.
    gc::AutoSuppressGC suppress(cx);

    // When the objects have different sizes, they will have different
    // numbers of fixed slots before and after the swap, so the slots for
    // native objects will need to be rearranged.
    NativeObject* na = a->isNative() ? &a->as<NativeObject>() : nullptr;
    NativeObject* nb = b->isNative() ? &b->as<NativeObject>() : nullptr;

    // Remember the original values from the objects.
    RootedValueVector avals(cx);
    void* apriv = nullptr;
    if (na) {
      apriv = na->hasPrivate() ? na->getPrivate() : nullptr;
      for (size_t i = 0; i < na->slotSpan(); i++) {
        if (!avals.append(na->getSlot(i))) {
          oomUnsafe.crash("JSObject::swap");
        }
      }
    }
    RootedValueVector bvals(cx);
    void* bpriv = nullptr;
    if (nb) {
      bpriv = nb->hasPrivate() ? nb->getPrivate() : nullptr;
      for (size_t i = 0; i < nb->slotSpan(); i++) {
        if (!bvals.append(nb->getSlot(i))) {
          oomUnsafe.crash("JSObject::swap");
        }
      }
    }

    // Do the same for proxies storing ProxyValueArray inline.
    ProxyObject* proxyA =
        a->is<ProxyObject>() ? &a->as<ProxyObject>() : nullptr;
    ProxyObject* proxyB =
        b->is<ProxyObject>() ? &b->as<ProxyObject>() : nullptr;

    if (aIsProxyWithInlineValues) {
      if (!CopyProxyValuesBeforeSwap(cx, proxyA, &avals)) {
        oomUnsafe.crash("CopyProxyValuesBeforeSwap");
      }
    }
    if (bIsProxyWithInlineValues) {
      if (!CopyProxyValuesBeforeSwap(cx, proxyB, &bvals)) {
        oomUnsafe.crash("CopyProxyValuesBeforeSwap");
      }
    }

    // Swap the main fields of the objects, whether they are native objects or
    // proxies.
    char tmp[sizeof(JSObject_Slots0)];
    js_memcpy(&tmp, a, sizeof tmp);
    js_memcpy(a, b, sizeof tmp);
    js_memcpy(b, &tmp, sizeof tmp);

    a->fixDictionaryShapeAfterSwap();
    b->fixDictionaryShapeAfterSwap();

    if (na) {
      if (!NativeObject::fillInAfterSwap(cx, b.as<NativeObject>(), na, avals,
                                         apriv)) {
        oomUnsafe.crash("fillInAfterSwap");
      }
    }
    if (nb) {
      if (!NativeObject::fillInAfterSwap(cx, a.as<NativeObject>(), nb, bvals,
                                         bpriv)) {
        oomUnsafe.crash("fillInAfterSwap");
      }
    }
    if (aIsProxyWithInlineValues) {
      if (!b->as<ProxyObject>().initExternalValueArrayAfterSwap(cx, avals)) {
        oomUnsafe.crash("initExternalValueArray");
      }
    }
    if (bIsProxyWithInlineValues) {
      if (!a->as<ProxyObject>().initExternalValueArrayAfterSwap(cx, bvals)) {
        oomUnsafe.crash("initExternalValueArray");
      }
    }
  }

  // Swapping the contents of two objects invalidates type sets which contain
  // either of the objects, so mark all such sets as unknown.
  MarkObjectGroupUnknownProperties(cx, a->group());
  MarkObjectGroupUnknownProperties(cx, b->group());

  /*
   * We need a write barrier here. If |a| was marked and |b| was not, then
   * after the swap, |b|'s guts would never be marked. The write barrier
   * solves this.
   *
   * Normally write barriers happen before the write. However, that's not
   * necessary here because nothing is being destroyed. We're just swapping.
   */
  if (zone->needsIncrementalBarrier()) {
    a->traceChildren(zone->barrierTracer());
    b->traceChildren(zone->barrierTracer());
  }

  NotifyGCPostSwap(a, b, r);
}

static NativeObject* DefineConstructorAndPrototype(
    JSContext* cx, HandleObject obj, HandleAtom atom, HandleObject protoProto,
    const JSClass* clasp, Native constructor, unsigned nargs,
    const JSPropertySpec* ps, const JSFunctionSpec* fs,
    const JSPropertySpec* static_ps, const JSFunctionSpec* static_fs,
    NativeObject** ctorp) {
  // Create the prototype object.
  RootedNativeObject proto(
      cx, GlobalObject::createBlankPrototypeInheriting(cx, clasp, protoProto));
  if (!proto) {
    return nullptr;
  }

  RootedNativeObject ctor(cx);
  if (!constructor) {
    ctor = proto;
  } else {
    ctor = NewNativeConstructor(cx, constructor, nargs, atom);
    if (!ctor) {
      return nullptr;
    }

    if (!LinkConstructorAndPrototype(cx, ctor, proto)) {
      return nullptr;
    }
  }

  if (!DefinePropertiesAndFunctions(cx, proto, ps, fs) ||
      (ctor != proto &&
       !DefinePropertiesAndFunctions(cx, ctor, static_ps, static_fs))) {
    return nullptr;
  }

  RootedId id(cx, AtomToId(atom));
  RootedValue value(cx, ObjectValue(*ctor));
  if (!DefineDataProperty(cx, obj, id, value, 0)) {
    return nullptr;
  }

  if (ctorp) {
    *ctorp = ctor;
  }
  return proto;
}

NativeObject* js::InitClass(JSContext* cx, HandleObject obj,
                            HandleObject protoProto_, const JSClass* clasp,
                            Native constructor, unsigned nargs,
                            const JSPropertySpec* ps, const JSFunctionSpec* fs,
                            const JSPropertySpec* static_ps,
                            const JSFunctionSpec* static_fs,
                            NativeObject** ctorp) {
  RootedAtom atom(cx, Atomize(cx, clasp->name, strlen(clasp->name)));
  if (!atom) {
    return nullptr;
  }

  /*
   * All instances of the class will inherit properties from the prototype
   * object we are about to create (in DefineConstructorAndPrototype), which
   * in turn will inherit from protoProto.
   *
   * If protoProto is null, default to Object.prototype.
   */
  RootedObject protoProto(cx, protoProto_);
  if (!protoProto) {
    protoProto = GlobalObject::getOrCreateObjectPrototype(cx, cx->global());
    if (!protoProto) {
      return nullptr;
    }
  }

  return DefineConstructorAndPrototype(cx, obj, atom, protoProto, clasp,
                                       constructor, nargs, ps, fs, static_ps,
                                       static_fs, ctorp);
}

void JSObject::fixupAfterMovingGC() {
  // For copy-on-write objects that don't own their elements, fix up the
  // elements pointer if it points to inline elements in the owning object.
  if (is<NativeObject>()) {
    NativeObject& obj = as<NativeObject>();
    if (obj.denseElementsAreCopyOnWrite()) {
      NativeObject* owner = obj.getElementsHeader()->ownerObject();
      // Get the new owner pointer but don't call MaybeForwarded as we
      // don't need to access the object's shape.
      if (IsForwarded(owner)) {
        owner = Forwarded(owner);
      }
      if (owner != &obj && owner->hasFixedElements()) {
        obj.elements_ = owner->getElementsHeader()->elements();
      }
      MOZ_ASSERT(!IsForwarded(obj.getElementsHeader()->ownerObject().get()));
    }
  }
}

static bool ReshapeForProtoMutation(JSContext* cx, HandleObject obj) {
  // To avoid the JIT guarding on each prototype in chain to detect prototype
  // mutation, we can instead reshape the rest of the proto chain such that a
  // guard on any of them is sufficient. To avoid excessive reshaping and
  // invalidation, we apply heuristics to decide when to apply this and when
  // to require a guard.
  //
  // Heuristics:
  //  - Always reshape singleton objects. This historically avoided
  //    de-optimizing in cases that compiler doesn't support
  //    uncacheable-proto. TODO: Revisit if this is a good idea.
  //  - Other objects instead set UNCACHEABLE_PROTO flag on shape to avoid
  //    creating too many private shape copies.
  //  - Only propegate along proto chain if we are mark DELEGATE. This avoids
  //    reshaping in normal object access cases.
  //
  // NOTE: We only handle NativeObjects and don't propegate reshapes through
  //       any non-native objects on the chain.
  //
  // See Also:
  //  - GeneratePrototypeGuards
  //  - GeneratePrototypeHoleGuards
  //  - ObjectGroup::defaultNewGroup

  RootedObject pobj(cx, obj);

  while (pobj && pobj->isNative()) {
    if (pobj->isSingleton()) {
      // If object was converted to a singleton it should have cleared
      // any UNCACHEABLE_PROTO flags.
      MOZ_ASSERT(!pobj->hasUncacheableProto());

      if (!NativeObject::reshapeForProtoMutation(cx, pobj.as<NativeObject>())) {
        return false;
      }
    } else {
      if (!JSObject::setUncacheableProto(cx, pobj)) {
        return false;
      }
    }

    if (!obj->isDelegate()) {
      break;
    }

    pobj = pobj->staticPrototype();
  }

  return true;
}

static bool SetProto(JSContext* cx, HandleObject obj,
                     Handle<js::TaggedProto> proto) {
  // Regenerate object shape (and possibly prototype shape) to invalidate JIT
  // code that is affected by a prototype mutation.
  if (!ReshapeForProtoMutation(cx, obj)) {
    return false;
  }

  if (proto.isObject()) {
    RootedObject protoObj(cx, proto.toObject());
    if (!JSObject::setDelegate(cx, protoObj)) {
      return false;
    }
  }

  if (obj->isSingleton()) {
    /*
     * Just splice the prototype, but mark the properties as unknown for
     * consistent behavior.
     */
    if (!JSObject::splicePrototype(cx, obj, proto)) {
      return false;
    }
    MarkObjectGroupUnknownProperties(cx, obj->group());
    return true;
  }

  RootedObjectGroup oldGroup(cx, obj->group());

  ObjectGroup* newGroup;
  if (oldGroup->maybeInterpretedFunction()) {
    // We're changing the group/proto of a scripted function. Create a new
    // group so we can keep track of the interpreted function for Ion
    // inlining.
    MOZ_ASSERT(obj->is<JSFunction>());
    newGroup = ObjectGroupRealm::makeGroup(cx, oldGroup->realm(),
                                           &JSFunction::class_, proto);
    if (!newGroup) {
      return false;
    }
    newGroup->setInterpretedFunction(oldGroup->maybeInterpretedFunction());
  } else {
    AutoRealm ar(cx, oldGroup);
    newGroup = ObjectGroup::defaultNewGroup(cx, obj->getClass(), proto);
    if (!newGroup) {
      return false;
    }
  }

  obj->setGroup(newGroup);

  // Add the object's property types to the new group.
  AutoSweepObjectGroup sweep(newGroup);
  if (!newGroup->unknownProperties(sweep)) {
    if (obj->isNative()) {
      AddPropertyTypesAfterProtoChange(cx, &obj->as<NativeObject>(), oldGroup);
    } else {
      MarkObjectGroupUnknownProperties(cx, newGroup);
    }
  }

  // Type sets containing this object will contain the old group but not the
  // new group of the object, so we need to treat all such type sets as
  // unknown.
  MarkObjectGroupUnknownProperties(cx, oldGroup);

  return true;
}

/* static */
bool JSObject::changeToSingleton(JSContext* cx, HandleObject obj) {
  MOZ_ASSERT(!obj->isSingleton());

  MarkObjectGroupUnknownProperties(cx, obj->group());

  ObjectGroup* group = ObjectGroup::lazySingletonGroup(
      cx, obj->group(), obj->getClass(), obj->taggedProto());
  if (!group) {
    return false;
  }

  obj->group_ = group;
  return true;
}

/**
 * Returns the original Object.prototype from the embedding-provided incumbent
 * global.
 *
 * Really, we want the incumbent global itself so we can pass it to other
 * embedding hooks which need it. Specifically, the enqueue promise hook
 * takes an incumbent global so it can set that on the PromiseCallbackJob
 * it creates.
 *
 * The reason for not just returning the global itself is that we'd need to
 * wrap it into the current compartment, and later unwrap it. Unwrapping
 * globals is tricky, though: we might accidentally unwrap through an inner
 * to its outer window and end up with the wrong global. Plain objects don't
 * have this problem, so we use the global's Object.prototype. The code using
 * it - e.g. EnqueuePromiseReactionJob - can then unwrap the object and get
 * its global without fear of unwrapping too far.
 */
bool js::GetObjectFromIncumbentGlobal(JSContext* cx, MutableHandleObject obj) {
  Rooted<GlobalObject*> globalObj(cx, cx->runtime()->getIncumbentGlobal(cx));
  if (!globalObj) {
    obj.set(nullptr);
    return true;
  }

  {
    AutoRealm ar(cx, globalObj);
    obj.set(GlobalObject::getOrCreateObjectPrototype(cx, globalObj));
    if (!obj) {
      return false;
    }
  }

  // The object might be from a different compartment, so wrap it.
  if (obj && !cx->compartment()->wrap(cx, obj)) {
    return false;
  }

  return true;
}

static bool IsStandardPrototype(JSObject* obj, JSProtoKey key) {
  Value v = obj->nonCCWGlobal().getPrototype(key);
  return v.isObject() && obj == &v.toObject();
}

JSProtoKey JS::IdentifyStandardInstance(JSObject* obj) {
  // Note: The prototype shares its JSClass with instances.
  MOZ_ASSERT(!obj->is<CrossCompartmentWrapperObject>());
  JSProtoKey key = StandardProtoKeyOrNull(obj);
  if (key != JSProto_Null && !IsStandardPrototype(obj, key)) {
    return key;
  }
  return JSProto_Null;
}

JSProtoKey JS::IdentifyStandardPrototype(JSObject* obj) {
  // Note: The prototype shares its JSClass with instances.
  MOZ_ASSERT(!obj->is<CrossCompartmentWrapperObject>());
  JSProtoKey key = StandardProtoKeyOrNull(obj);
  if (key != JSProto_Null && IsStandardPrototype(obj, key)) {
    return key;
  }
  return JSProto_Null;
}

JSProtoKey JS::IdentifyStandardInstanceOrPrototype(JSObject* obj) {
  return StandardProtoKeyOrNull(obj);
}

JSProtoKey JS::IdentifyStandardConstructor(JSObject* obj) {
  // Note that isNativeConstructor does not imply that we are a standard
  // constructor, but the converse is true (at least until we start having
  // self-hosted constructors for standard classes). This lets us avoid a costly
  // loop for many functions (which, depending on the call site, may be the
  // common case).
  if (!obj->is<JSFunction>() ||
      !(obj->as<JSFunction>().flags().isNativeConstructor())) {
    return JSProto_Null;
  }

  GlobalObject& global = obj->as<JSFunction>().global();
  for (size_t k = 0; k < JSProto_LIMIT; ++k) {
    JSProtoKey key = static_cast<JSProtoKey>(k);
    if (global.getConstructor(key) == ObjectValue(*obj)) {
      return key;
    }
  }

  return JSProto_Null;
}

bool js::LookupProperty(JSContext* cx, HandleObject obj, js::HandleId id,
                        MutableHandleObject objp,
                        MutableHandle<PropertyResult> propp) {
  if (LookupPropertyOp op = obj->getOpsLookupProperty()) {
    return op(cx, obj, id, objp, propp);
  }
  return LookupPropertyInline<CanGC>(cx, obj.as<NativeObject>(), id, objp,
                                     propp);
}

bool js::LookupName(JSContext* cx, HandlePropertyName name,
                    HandleObject envChain, MutableHandleObject objp,
                    MutableHandleObject pobjp,
                    MutableHandle<PropertyResult> propp) {
  RootedId id(cx, NameToId(name));

  for (RootedObject env(cx, envChain); env; env = env->enclosingEnvironment()) {
    if (!LookupProperty(cx, env, id, pobjp, propp)) {
      return false;
    }
    if (propp) {
      objp.set(env);
      return true;
    }
  }

  objp.set(nullptr);
  pobjp.set(nullptr);
  propp.setNotFound();
  return true;
}

bool js::LookupNameNoGC(JSContext* cx, PropertyName* name, JSObject* envChain,
                        JSObject** objp, JSObject** pobjp,
                        PropertyResult* propp) {
  AutoAssertNoPendingException nogc(cx);

  MOZ_ASSERT(!*objp && !*pobjp && !*propp);

  for (JSObject* env = envChain; env; env = env->enclosingEnvironment()) {
    if (env->getOpsLookupProperty()) {
      return false;
    }
    if (!LookupPropertyInline<NoGC>(cx, &env->as<NativeObject>(),
                                    NameToId(name), pobjp, propp)) {
      return false;
    }
    if (*propp) {
      *objp = env;
      return true;
    }
  }

  return true;
}

bool js::LookupNameWithGlobalDefault(JSContext* cx, HandlePropertyName name,
                                     HandleObject envChain,
                                     MutableHandleObject objp) {
  RootedId id(cx, NameToId(name));

  RootedObject pobj(cx);
  Rooted<PropertyResult> prop(cx);

  RootedObject env(cx, envChain);
  for (; !env->is<GlobalObject>(); env = env->enclosingEnvironment()) {
    if (!LookupProperty(cx, env, id, &pobj, &prop)) {
      return false;
    }
    if (prop) {
      break;
    }
  }

  objp.set(env);
  return true;
}

bool js::LookupNameUnqualified(JSContext* cx, HandlePropertyName name,
                               HandleObject envChain,
                               MutableHandleObject objp) {
  RootedId id(cx, NameToId(name));

  RootedObject pobj(cx);
  Rooted<PropertyResult> prop(cx);

  RootedObject env(cx, envChain);
  for (; !env->isUnqualifiedVarObj(); env = env->enclosingEnvironment()) {
    if (!LookupProperty(cx, env, id, &pobj, &prop)) {
      return false;
    }
    if (prop) {
      break;
    }
  }

  // See note above RuntimeLexicalErrorObject.
  if (pobj == env) {
    bool isTDZ = false;
    if (prop && name != cx->names().dotThis) {
      // Treat Debugger environments specially for TDZ checks, as they
      // look like non-native environments but in fact wrap native
      // environments.
      if (env->is<DebugEnvironmentProxy>()) {
        RootedValue v(cx);
        Rooted<DebugEnvironmentProxy*> envProxy(
            cx, &env->as<DebugEnvironmentProxy>());
        if (!DebugEnvironmentProxy::getMaybeSentinelValue(cx, envProxy, id,
                                                          &v)) {
          return false;
        }
        isTDZ = IsUninitializedLexical(v);
      } else {
        isTDZ = IsUninitializedLexicalSlot(env, prop);
      }
    }

    if (isTDZ) {
      env = RuntimeLexicalErrorObject::create(cx, env,
                                              JSMSG_UNINITIALIZED_LEXICAL);
      if (!env) {
        return false;
      }
    } else if (env->is<LexicalEnvironmentObject>() &&
               !prop.shape()->writable()) {
      // Assigning to a named lambda callee name is a no-op in sloppy mode.
      Rooted<LexicalEnvironmentObject*> lexicalEnv(
          cx, &env->as<LexicalEnvironmentObject>());
      if (lexicalEnv->isExtensible() ||
          lexicalEnv->scope().kind() != ScopeKind::NamedLambda) {
        MOZ_ASSERT(name != cx->names().dotThis);
        env =
            RuntimeLexicalErrorObject::create(cx, env, JSMSG_BAD_CONST_ASSIGN);
        if (!env) {
          return false;
        }
      }
    }
  }

  objp.set(env);
  return true;
}

bool js::HasOwnProperty(JSContext* cx, HandleObject obj, HandleId id,
                        bool* result) {
  if (obj->is<ProxyObject>()) {
    return Proxy::hasOwn(cx, obj, id, result);
  }

  if (GetOwnPropertyOp op = obj->getOpsGetOwnPropertyDescriptor()) {
    Rooted<PropertyDescriptor> desc(cx);
    if (!op(cx, obj, id, &desc)) {
      return false;
    }
    *result = !!desc.object();
    return true;
  }

  Rooted<PropertyResult> prop(cx);
  if (!NativeLookupOwnProperty<CanGC>(cx, obj.as<NativeObject>(), id, &prop)) {
    return false;
  }
  *result = prop.isFound();
  return true;
}

bool js::LookupPropertyPure(JSContext* cx, JSObject* obj, jsid id,
                            JSObject** objp, PropertyResult* propp) {
  bool isTypedArrayOutOfRange = false;
  do {
    if (!LookupOwnPropertyPure(cx, obj, id, propp, &isTypedArrayOutOfRange)) {
      return false;
    }

    if (*propp) {
      *objp = obj;
      return true;
    }

    if (isTypedArrayOutOfRange) {
      *objp = nullptr;
      return true;
    }

    obj = obj->staticPrototype();
  } while (obj);

  *objp = nullptr;
  propp->setNotFound();
  return true;
}

bool js::LookupOwnPropertyPure(JSContext* cx, JSObject* obj, jsid id,
                               PropertyResult* propp,
                               bool* isTypedArrayOutOfRange /* = nullptr */) {
  JS::AutoCheckCannotGC nogc;
  if (isTypedArrayOutOfRange) {
    *isTypedArrayOutOfRange = false;
  }

  if (obj->isNative()) {
    // Search for a native dense element, typed array element, or property.

    if (JSID_IS_INT(id) &&
        obj->as<NativeObject>().containsDenseElement(JSID_TO_INT(id))) {
      propp->setDenseOrTypedArrayElement();
      return true;
    }

    if (obj->is<TypedArrayObject>()) {
      uint64_t index;
      if (IsTypedArrayIndex(id, &index)) {
        if (index < obj->as<TypedArrayObject>().length()) {
          propp->setDenseOrTypedArrayElement();
        } else {
          propp->setNotFound();
          if (isTypedArrayOutOfRange) {
            *isTypedArrayOutOfRange = true;
          }
        }
        return true;
      }
    }

    if (Shape* shape = obj->as<NativeObject>().lookupPure(id)) {
      propp->setNativeProperty(shape);
      return true;
    }

    // Fail if there's a resolve hook, unless the mayResolve hook tells
    // us the resolve hook won't define a property with this id.
    if (ClassMayResolveId(cx->names(), obj->getClass(), id, obj)) {
      return false;
    }
  } else if (obj->is<TypedObject>()) {
    if (obj->as<TypedObject>().typeDescr().hasProperty(cx->names(), id)) {
      propp->setNonNativeProperty();
      return true;
    }
  } else {
    return false;
  }

  propp->setNotFound();
  return true;
}

static inline bool NativeGetPureInline(NativeObject* pobj, jsid id,
                                       PropertyResult prop, Value* vp,
                                       JSContext* cx) {
  if (prop.isDenseOrTypedArrayElement()) {
    // For simplicity we ignore the TypedArray with string index case.
    if (!JSID_IS_INT(id)) {
      return false;
    }

    return pobj->getDenseOrTypedArrayElement<NoGC>(cx, JSID_TO_INT(id), vp);
  }

  // Fail if we have a custom getter.
  Shape* shape = prop.shape();
  if (!shape->isDataProperty()) {
    return false;
  }

  *vp = pobj->getSlot(shape->slot());
  MOZ_ASSERT(!vp->isMagic());
  return true;
}

bool js::GetPropertyPure(JSContext* cx, JSObject* obj, jsid id, Value* vp) {
  JSObject* pobj;
  PropertyResult prop;
  if (!LookupPropertyPure(cx, obj, id, &pobj, &prop)) {
    return false;
  }

  if (!prop) {
    vp->setUndefined();
    return true;
  }

  return NativeGetPureInline(&pobj->as<NativeObject>(), id, prop, vp, cx);
}

bool js::GetOwnPropertyPure(JSContext* cx, JSObject* obj, jsid id, Value* vp,
                            bool* found) {
  PropertyResult prop;
  if (!LookupOwnPropertyPure(cx, obj, id, &prop)) {
    return false;
  }

  if (!prop) {
    *found = false;
    vp->setUndefined();
    return true;
  }

  *found = true;
  return NativeGetPureInline(&obj->as<NativeObject>(), id, prop, vp, cx);
}

static inline bool NativeGetGetterPureInline(PropertyResult prop,
                                             JSFunction** fp) {
  if (!prop.isDenseOrTypedArrayElement() && prop.shape()->hasGetterObject()) {
    Shape* shape = prop.shape();
    if (shape->getterObject()->is<JSFunction>()) {
      *fp = &shape->getterObject()->as<JSFunction>();
      return true;
    }
  }

  *fp = nullptr;
  return true;
}

bool js::GetGetterPure(JSContext* cx, JSObject* obj, jsid id, JSFunction** fp) {
  /* Just like GetPropertyPure, but get getter function, without invoking
   * it. */
  JSObject* pobj;
  PropertyResult prop;
  if (!LookupPropertyPure(cx, obj, id, &pobj, &prop)) {
    return false;
  }

  if (!prop) {
    *fp = nullptr;
    return true;
  }

  return prop.isNativeProperty() && NativeGetGetterPureInline(prop, fp);
}

bool js::GetOwnGetterPure(JSContext* cx, JSObject* obj, jsid id,
                          JSFunction** fp) {
  JS::AutoCheckCannotGC nogc;
  PropertyResult prop;
  if (!LookupOwnPropertyPure(cx, obj, id, &prop)) {
    return false;
  }

  if (!prop) {
    *fp = nullptr;
    return true;
  }

  return prop.isNativeProperty() && NativeGetGetterPureInline(prop, fp);
}

bool js::GetOwnNativeGetterPure(JSContext* cx, JSObject* obj, jsid id,
                                JSNative* native) {
  JS::AutoCheckCannotGC nogc;
  *native = nullptr;
  PropertyResult prop;
  if (!LookupOwnPropertyPure(cx, obj, id, &prop)) {
    return false;
  }

  if (!prop || prop.isDenseOrTypedArrayElement() ||
      !prop.shape()->hasGetterObject()) {
    return true;
  }

  JSObject* getterObj = prop.shape()->getterObject();
  if (!getterObj->is<JSFunction>()) {
    return true;
  }

  JSFunction* getter = &getterObj->as<JSFunction>();
  if (!getter->isNative()) {
    return true;
  }

  *native = getter->native();
  return true;
}

bool js::HasOwnDataPropertyPure(JSContext* cx, JSObject* obj, jsid id,
                                bool* result) {
  PropertyResult prop;
  if (!LookupOwnPropertyPure(cx, obj, id, &prop)) {
    return false;
  }

  *result = prop && !prop.isDenseOrTypedArrayElement() &&
            prop.shape()->isDataProperty();
  return true;
}

bool js::GetPrototypeIfOrdinary(JSContext* cx, HandleObject obj,
                                bool* isOrdinary, MutableHandleObject protop) {
  if (obj->is<js::ProxyObject>()) {
    return js::Proxy::getPrototypeIfOrdinary(cx, obj, isOrdinary, protop);
  }

  *isOrdinary = true;
  protop.set(obj->staticPrototype());
  return true;
}

/*** ES6 standard internal methods ******************************************/

bool js::SetPrototype(JSContext* cx, HandleObject obj, HandleObject proto,
                      JS::ObjectOpResult& result) {
  // The proxy trap subsystem fully handles prototype-setting for proxies
  // with dynamic [[Prototype]]s.
  if (obj->hasDynamicPrototype()) {
    MOZ_ASSERT(obj->is<ProxyObject>());
    return Proxy::setPrototype(cx, obj, proto, result);
  }

  /*
   * ES6 9.1.2 step 3-4 if |obj.[[Prototype]]| has SameValue as |proto| return
   * true. Since the values in question are objects, we can just compare
   * pointers.
   */
  if (proto == obj->staticPrototype()) {
    return result.succeed();
  }

  /* Disallow mutation of immutable [[Prototype]]s. */
  if (obj->staticPrototypeIsImmutable()) {
    return result.fail(JSMSG_CANT_SET_PROTO);
  }

  /*
   * Disallow mutating the [[Prototype]] on Typed Objects, per the spec.
   */
  if (obj->is<TypedObject>()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_CANT_SET_PROTO_OF,
                              "incompatible TypedObject");
    return false;
  }

  /* ES6 9.1.2 step 5 forbids changing [[Prototype]] if not [[Extensible]]. */
  bool extensible;
  if (!IsExtensible(cx, obj, &extensible)) {
    return false;
  }
  if (!extensible) {
    return result.fail(JSMSG_CANT_SET_PROTO);
  }

  // If this is a global object, resolve the Object class so that its
  // [[Prototype]] chain is always properly immutable, even in the presence
  // of lazy standard classes.
  if (obj->is<GlobalObject>()) {
    Handle<GlobalObject*> global = obj.as<GlobalObject>();
    if (!GlobalObject::ensureConstructor(cx, global, JSProto_Object)) {
      return false;
    }
  }

  /*
   * ES6 9.1.2 step 6 forbids generating cyclical prototype chains. But we
   * have to do this comparison on the observable WindowProxy, not on the
   * possibly-Window object we're setting the proto on.
   */
  RootedObject objMaybeWindowProxy(cx, ToWindowProxyIfWindow(obj));
  RootedObject obj2(cx, proto);
  while (obj2) {
    MOZ_ASSERT(!IsWindow(obj2));
    if (obj2 == objMaybeWindowProxy) {
      return result.fail(JSMSG_CANT_SET_PROTO_CYCLE);
    }

    bool isOrdinary;
    if (!GetPrototypeIfOrdinary(cx, obj2, &isOrdinary, &obj2)) {
      return false;
    }
    if (!isOrdinary) {
      break;
    }
  }

  Rooted<TaggedProto> taggedProto(cx, TaggedProto(proto));
  if (!SetProto(cx, obj, taggedProto)) {
    return false;
  }

  return result.succeed();
}

bool js::SetPrototype(JSContext* cx, HandleObject obj, HandleObject proto) {
  ObjectOpResult result;
  return SetPrototype(cx, obj, proto, result) && result.checkStrict(cx, obj);
}

bool js::PreventExtensions(JSContext* cx, HandleObject obj,
                           ObjectOpResult& result) {
  if (obj->is<ProxyObject>()) {
    return js::Proxy::preventExtensions(cx, obj, result);
  }

  if (!obj->nonProxyIsExtensible()) {
    // If the following assertion fails, there's somewhere else a missing
    // call to shrinkCapacityToInitializedLength() which needs to be found
    // and fixed.
    MOZ_ASSERT_IF(obj->isNative(),
                  obj->as<NativeObject>().getDenseInitializedLength() ==
                      obj->as<NativeObject>().getDenseCapacity());

    return result.succeed();
  }

  if (obj->isNative()) {
    // Force lazy properties to be resolved.
    if (!ResolveLazyProperties(cx, obj.as<NativeObject>())) {
      return false;
    }

    // Prepare the elements. We have to do this before we mark the object
    // non-extensible; that's fine because these changes are not observable.
    if (!ObjectElements::PreventExtensions(cx, &obj->as<NativeObject>())) {
      return false;
    }
  }

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

  return result.succeed();
}

bool js::PreventExtensions(JSContext* cx, HandleObject obj) {
  ObjectOpResult result;
  return PreventExtensions(cx, obj, result) && result.checkStrict(cx, obj);
}

bool js::GetOwnPropertyDescriptor(JSContext* cx, HandleObject obj, HandleId id,
                                  MutableHandle<PropertyDescriptor> desc) {
  if (GetOwnPropertyOp op = obj->getOpsGetOwnPropertyDescriptor()) {
    bool ok = op(cx, obj, id, desc);
    if (ok) {
      desc.assertCompleteIfFound();
    }
    return ok;
  }

  return NativeGetOwnPropertyDescriptor(cx, obj.as<NativeObject>(), id, desc);
}

bool js::DefineProperty(JSContext* cx, HandleObject obj, HandleId id,
                        Handle<PropertyDescriptor> desc) {
  ObjectOpResult result;
  return DefineProperty(cx, obj, id, desc, result) &&
         result.checkStrict(cx, obj, id);
}

bool js::DefineProperty(JSContext* cx, HandleObject obj, HandleId id,
                        Handle<PropertyDescriptor> desc,
                        ObjectOpResult& result) {
  desc.assertValid();
  if (DefinePropertyOp op = obj->getOpsDefineProperty()) {
    return op(cx, obj, id, desc, result);
  }
  return NativeDefineProperty(cx, obj.as<NativeObject>(), id, desc, result);
}

bool js::DefineAccessorProperty(JSContext* cx, HandleObject obj, HandleId id,
                                HandleObject getter, HandleObject setter,
                                unsigned attrs, ObjectOpResult& result) {
  Rooted<PropertyDescriptor> desc(cx);

  {
    GetterOp getterOp = JS_DATA_TO_FUNC_PTR(GetterOp, getter.get());
    SetterOp setterOp = JS_DATA_TO_FUNC_PTR(SetterOp, setter.get());
    desc.initFields(nullptr, UndefinedHandleValue, attrs, getterOp, setterOp);
  }

  if (DefinePropertyOp op = obj->getOpsDefineProperty()) {
    MOZ_ASSERT(!cx->isHelperThreadContext());
    return op(cx, obj, id, desc, result);
  }
  return NativeDefineProperty(cx, obj.as<NativeObject>(), id, desc, result);
}

bool js::DefineDataProperty(JSContext* cx, HandleObject obj, HandleId id,
                            HandleValue value, unsigned attrs,
                            ObjectOpResult& result) {
  Rooted<PropertyDescriptor> desc(cx);
  desc.initFields(nullptr, value, attrs, nullptr, nullptr);
  if (DefinePropertyOp op = obj->getOpsDefineProperty()) {
    MOZ_ASSERT(!cx->isHelperThreadContext());
    return op(cx, obj, id, desc, result);
  }
  return NativeDefineProperty(cx, obj.as<NativeObject>(), id, desc, result);
}

bool js::DefineDataProperty(JSContext* cx, HandleObject obj, PropertyName* name,
                            HandleValue value, unsigned attrs,
                            ObjectOpResult& result) {
  RootedId id(cx, NameToId(name));
  return DefineDataProperty(cx, obj, id, value, attrs, result);
}

bool js::DefineDataElement(JSContext* cx, HandleObject obj, uint32_t index,
                           HandleValue value, unsigned attrs,
                           ObjectOpResult& result) {
  RootedId id(cx);
  if (!IndexToId(cx, index, &id)) {
    return false;
  }
  return DefineDataProperty(cx, obj, id, value, attrs, result);
}

bool js::DefineAccessorProperty(JSContext* cx, HandleObject obj, HandleId id,
                                HandleObject getter, HandleObject setter,
                                unsigned attrs) {
  ObjectOpResult result;
  if (!DefineAccessorProperty(cx, obj, id, getter, setter, attrs, result)) {
    return false;
  }
  if (!result) {
    MOZ_ASSERT(!cx->isHelperThreadContext());
    result.reportError(cx, obj, id);
    return false;
  }
  return true;
}

bool js::DefineDataProperty(JSContext* cx, HandleObject obj, HandleId id,
                            HandleValue value, unsigned attrs) {
  ObjectOpResult result;
  if (!DefineDataProperty(cx, obj, id, value, attrs, result)) {
    return false;
  }
  if (!result) {
    MOZ_ASSERT(!cx->isHelperThreadContext());
    result.reportError(cx, obj, id);
    return false;
  }
  return true;
}

bool js::DefineDataProperty(JSContext* cx, HandleObject obj, PropertyName* name,
                            HandleValue value, unsigned attrs) {
  RootedId id(cx, NameToId(name));
  return DefineDataProperty(cx, obj, id, value, attrs);
}

bool js::DefineDataElement(JSContext* cx, HandleObject obj, uint32_t index,
                           HandleValue value, unsigned attrs) {
  RootedId id(cx);
  if (!IndexToId(cx, index, &id)) {
    return false;
  }
  return DefineDataProperty(cx, obj, id, value, attrs);
}

/*** SpiderMonkey nonstandard internal methods ******************************/

// Mark an object as having an immutable prototype
//
// NOTE: This does not correspond to the SetImmutablePrototype ECMAScript
//       method.
bool js::SetImmutablePrototype(JSContext* cx, HandleObject obj,
                               bool* succeeded) {
  if (obj->hasDynamicPrototype()) {
    MOZ_ASSERT(!cx->isHelperThreadContext());
    return Proxy::setImmutablePrototype(cx, obj, succeeded);
  }

  if (!JSObject::setFlags(cx, obj, BaseShape::IMMUTABLE_PROTOTYPE)) {
    return false;
  }
  *succeeded = true;
  return true;
}

bool js::GetPropertyDescriptor(JSContext* cx, HandleObject obj, HandleId id,
                               MutableHandle<PropertyDescriptor> desc) {
  RootedObject pobj(cx);

  for (pobj = obj; pobj;) {
    if (!GetOwnPropertyDescriptor(cx, pobj, id, desc)) {
      return false;
    }

    if (desc.object()) {
      return true;
    }

    if (!GetPrototype(cx, pobj, &pobj)) {
      return false;
    }
  }

  MOZ_ASSERT(!desc.object());
  return true;
}

/* * */

extern bool PropertySpecNameToId(JSContext* cx, JSPropertySpec::Name name,
                                 MutableHandleId id,
                                 js::PinningBehavior pin = js::DoNotPinAtom);

// If a property or method is part of an experimental feature that can be
// disabled at run-time by a preference, we keep it in the JSFunctionSpec /
// JSPropertySpec list, but omit the definition if the preference is off.
JS_FRIEND_API bool js::ShouldIgnorePropertyDefinition(JSContext* cx,
                                                      JSProtoKey key, jsid id) {
  return false;
}

static bool DefineFunctionFromSpec(JSContext* cx, HandleObject obj,
                                   const JSFunctionSpec* fs, unsigned flags,
                                   DefineAsIntrinsic intrinsic) {
  RootedId id(cx);
  if (!PropertySpecNameToId(cx, fs->name, &id)) {
    return false;
  }

  if (ShouldIgnorePropertyDefinition(cx, StandardProtoKeyOrNull(obj), id)) {
    return true;
  }

  JSFunction* fun = NewFunctionFromSpec(cx, fs, id);
  if (!fun) {
    return false;
  }

  if (intrinsic == AsIntrinsic) {
    fun->setIsIntrinsic();
  }

  RootedValue funVal(cx, ObjectValue(*fun));
  return DefineDataProperty(cx, obj, id, funVal, flags & ~JSFUN_FLAGS_MASK);
}

bool js::DefineFunctions(JSContext* cx, HandleObject obj,
                         const JSFunctionSpec* fs,
                         DefineAsIntrinsic intrinsic) {
  for (; fs->name; fs++) {
    if (!DefineFunctionFromSpec(cx, obj, fs, fs->flags, intrinsic)) {
      return false;
    }
  }
  return true;
}

/*** ToPrimitive ************************************************************/

/*
 * Gets |obj[id]|.  If that value's not callable, returns true and stores an
 * object value in *vp.  If it's callable, calls it with no arguments and |obj|
 * as |this|, returning the result in *vp.
 *
 * This is a mini-abstraction for ES6 draft rev 36 (2015 Mar 17),
 * 7.1.1, second algorithm (OrdinaryToPrimitive), steps 5.a-c.
 */
static bool MaybeCallMethod(JSContext* cx, HandleObject obj, HandleId id,
                            MutableHandleValue vp) {
  if (!GetProperty(cx, obj, obj, id, vp)) {
    return false;
  }
  if (!IsCallable(vp)) {
    vp.setObject(*obj);
    return true;
  }

  return js::Call(cx, vp, obj, vp);
}

static bool ReportCantConvert(JSContext* cx, unsigned errorNumber,
                              HandleObject obj, JSType hint) {
  const JSClass* clasp = obj->getClass();

  // Avoid recursive death when decompiling in ReportValueError.
  RootedString str(cx);
  if (hint == JSTYPE_STRING) {
    str = JS_AtomizeAndPinString(cx, clasp->name);
    if (!str) {
      return false;
    }
  } else {
    str = nullptr;
  }

  RootedValue val(cx, ObjectValue(*obj));
  ReportValueError(cx, errorNumber, JSDVG_SEARCH_STACK, val, str,
                   hint == JSTYPE_UNDEFINED
                       ? "primitive type"
                       : hint == JSTYPE_STRING ? "string" : "number");
  return false;
}

bool JS::OrdinaryToPrimitive(JSContext* cx, HandleObject obj, JSType hint,
                             MutableHandleValue vp) {
  MOZ_ASSERT(hint == JSTYPE_NUMBER || hint == JSTYPE_STRING ||
             hint == JSTYPE_UNDEFINED);

  Rooted<jsid> id(cx);

  const JSClass* clasp = obj->getClass();
  if (hint == JSTYPE_STRING) {
    id = NameToId(cx->names().toString);

    /* Optimize (new String(...)).toString(). */
    if (clasp == &StringObject::class_) {
      StringObject* nobj = &obj->as<StringObject>();
      if (HasNativeMethodPure(nobj, cx->names().toString, str_toString, cx)) {
        vp.setString(nobj->unbox());
        return true;
      }
    }

    if (!MaybeCallMethod(cx, obj, id, vp)) {
      return false;
    }
    if (vp.isPrimitive()) {
      return true;
    }

    id = NameToId(cx->names().valueOf);
    if (!MaybeCallMethod(cx, obj, id, vp)) {
      return false;
    }
    if (vp.isPrimitive()) {
      return true;
    }
  } else {
    id = NameToId(cx->names().valueOf);

    /* Optimize new String(...).valueOf(). */
    if (clasp == &StringObject::class_) {
      StringObject* nobj = &obj->as<StringObject>();
      if (HasNativeMethodPure(nobj, cx->names().valueOf, str_toString, cx)) {
        vp.setString(nobj->unbox());
        return true;
      }
    }

    /* Optimize new Number(...).valueOf(). */
    if (clasp == &NumberObject::class_) {
      NumberObject* nobj = &obj->as<NumberObject>();
      if (HasNativeMethodPure(nobj, cx->names().valueOf, num_valueOf, cx)) {
        vp.setNumber(nobj->unbox());
        return true;
      }
    }

    if (!MaybeCallMethod(cx, obj, id, vp)) {
      return false;
    }
    if (vp.isPrimitive()) {
      return true;
    }

    id = NameToId(cx->names().toString);
    if (!MaybeCallMethod(cx, obj, id, vp)) {
      return false;
    }
    if (vp.isPrimitive()) {
      return true;
    }
  }

  return ReportCantConvert(cx, JSMSG_CANT_CONVERT_TO, obj, hint);
}

bool js::ToPrimitiveSlow(JSContext* cx, JSType preferredType,
                         MutableHandleValue vp) {
  // Step numbers refer to the first algorithm listed in ES6 draft rev 36
  // (2015 Mar 17) 7.1.1 ToPrimitive.
  MOZ_ASSERT(preferredType == JSTYPE_UNDEFINED ||
             preferredType == JSTYPE_STRING || preferredType == JSTYPE_NUMBER);
  RootedObject obj(cx, &vp.toObject());

  // Steps 4-5.
  RootedValue method(cx);
  if (!GetInterestingSymbolProperty(cx, obj, cx->wellKnownSymbols().toPrimitive,
                                    &method)) {
    return false;
  }

  // Step 6.
  if (!method.isNullOrUndefined()) {
    // Step 6 of GetMethod. js::Call() below would do this check and throw a
    // TypeError anyway, but this produces a better error message.
    if (!IsCallable(method)) {
      return ReportCantConvert(cx, JSMSG_TOPRIMITIVE_NOT_CALLABLE, obj,
                               preferredType);
    }

    // Steps 1-3, 6.a-b.
    RootedValue arg0(cx, StringValue(preferredType == JSTYPE_STRING
                                         ? cx->names().string
                                         : preferredType == JSTYPE_NUMBER
                                               ? cx->names().number
                                               : cx->names().default_));

    if (!js::Call(cx, method,