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
|
/*
* Copyright (C) 1999-2001 Harri Porten (porten@kde.org)
* Copyright (C) 2001 Peter Kelly (pmk@post.com)
* Copyright (C) 2003-2024 Apple Inc. All rights reserved.
* Copyright (C) 2007 Eric Seidel (eric@webkit.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "JSObject.h"
#include "AllocationFailureMode.h"
#include "CatchScope.h"
#include "CustomGetterSetter.h"
#include "Exception.h"
#include "GCDeferralContextInlines.h"
#include "GetterSetter.h"
#include "HeapAnalyzer.h"
#include "IndexingHeaderInlines.h"
#include "JSCInlines.h"
#include "JSCustomGetterFunction.h"
#include "JSCustomSetterFunction.h"
#include "JSFunction.h"
#include "JSImmutableButterfly.h"
#include "Lookup.h"
#include "PropertyDescriptor.h"
#include "PropertyNameArray.h"
#include "ProxyObject.h"
#include "TypeError.h"
#include "VMInlines.h"
#include "VMTrapsInlines.h"
#include <wtf/Assertions.h>
#include <wtf/text/MakeString.h>
WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN
namespace JSC {
// We keep track of the size of the last array after it was grown. We use this
// as a simple heuristic for as the value to grow the next array from size 0.
// This value is capped by the constant FIRST_VECTOR_GROW defined in
// ArrayConventions.h.
static unsigned lastArraySize = 0;
STATIC_ASSERT_IS_TRIVIALLY_DESTRUCTIBLE(JSObject);
STATIC_ASSERT_IS_TRIVIALLY_DESTRUCTIBLE(JSFinalObject);
const ASCIILiteral NonExtensibleObjectPropertyDefineError { "Attempting to define property on object that is not extensible."_s };
const ASCIILiteral ReadonlyPropertyWriteError { "Attempted to assign to readonly property."_s };
const ASCIILiteral ReadonlyPropertyChangeError { "Attempting to change value of a readonly property."_s };
const ASCIILiteral UnableToDeletePropertyError { "Unable to delete property."_s };
const ASCIILiteral UnconfigurablePropertyChangeAccessMechanismError { "Attempting to change access mechanism for an unconfigurable property."_s };
const ASCIILiteral UnconfigurablePropertyChangeConfigurabilityError { "Attempting to change configurable attribute of unconfigurable property."_s };
const ASCIILiteral UnconfigurablePropertyChangeEnumerabilityError { "Attempting to change enumerable attribute of unconfigurable property."_s };
const ASCIILiteral UnconfigurablePropertyChangeWritabilityError { "Attempting to change writable attribute of unconfigurable property."_s };
const ASCIILiteral PrototypeValueCanOnlyBeAnObjectOrNullTypeError { "Prototype value can only be an object or null"_s };
const ClassInfo JSObject::s_info = { "Object"_s, nullptr, nullptr, nullptr, CREATE_METHOD_TABLE(JSObject) };
const ClassInfo JSFinalObject::s_info = { "Object"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSFinalObject) };
template<typename Visitor>
ALWAYS_INLINE void JSObject::markAuxiliaryAndVisitOutOfLineProperties(Visitor& visitor, Butterfly* butterfly, Structure* structure, PropertyOffset maxOffset)
{
// We call this when we found everything without races.
ASSERT(structure);
if (!butterfly)
return;
if (isCopyOnWrite(structure->indexingMode())) {
visitor.append(std::bit_cast<WriteBarrier<JSCell>>(JSImmutableButterfly::fromButterfly(butterfly)));
return;
}
bool hasIndexingHeader = structure->hasIndexingHeader(this);
size_t preCapacity;
if (hasIndexingHeader)
preCapacity = butterfly->indexingHeader()->preCapacity(structure);
else
preCapacity = 0;
HeapCell* base = std::bit_cast<HeapCell*>(
butterfly->base(preCapacity, Structure::outOfLineCapacity(maxOffset)));
ASSERT(Heap::heap(base) == visitor.heap());
visitor.markAuxiliary(base);
unsigned outOfLineSize = Structure::outOfLineSize(maxOffset);
visitor.appendValuesHidden(butterfly->propertyStorage() - outOfLineSize, outOfLineSize);
}
template<typename Visitor>
ALWAYS_INLINE Structure* JSObject::visitButterfly(Visitor& visitor)
{
static const char* const raceReason = "JSObject::visitButterfly";
Structure* result = visitButterflyImpl(visitor);
if (!result)
visitor.didRace(this, raceReason);
return result;
}
template<typename Visitor>
ALWAYS_INLINE Structure* JSObject::visitButterflyImpl(Visitor& visitor)
{
Butterfly* butterfly;
Structure* structure;
PropertyOffset maxOffset;
auto visitElements = [&] (IndexingType indexingMode) {
switch (indexingMode) {
// We don't need to visit the elements for CopyOnWrite butterflies since they we marked the JSImmutableButterfly acting as out butterfly.
case ALL_WRITABLE_CONTIGUOUS_INDEXING_TYPES:
visitor.appendValuesHidden(butterfly->contiguous().data(), butterfly->publicLength());
break;
case ALL_ARRAY_STORAGE_INDEXING_TYPES:
visitor.appendValuesHidden(butterfly->arrayStorage()->m_vector, butterfly->arrayStorage()->vectorLength());
if (butterfly->arrayStorage()->m_sparseMap)
visitor.append(butterfly->arrayStorage()->m_sparseMap);
break;
default:
break;
}
};
if (visitor.mutatorIsStopped()) {
butterfly = this->butterfly();
structure = this->structure();
maxOffset = structure->maxOffset();
markAuxiliaryAndVisitOutOfLineProperties(visitor, butterfly, structure, maxOffset);
visitElements(structure->indexingMode());
return structure;
}
// We want to ensure that we only scan the butterfly if we have an exactly matched structure and an
// exactly matched size. The mutator is required to perform the following shenanigans when
// reallocating the butterfly with a concurrent collector, with all fencing necessary to ensure
// that this executes as if under sequential consistency:
//
// object->structure = nuke(object->structure)
// object->butterfly = newButterfly
// structure->m_offset = newMaxOffset
// object->structure = newStructure
//
// It's OK to skip this when reallocating the butterfly in a way that does not affect the m_offset.
// We have other protocols in place for that.
//
// Note that the m_offset can change without the structure changing, but in that case the mutator
// will still store null to the structure.
//
// The collector will ensure that it always sees a matched butterfly/structure by reading the
// structure before and after reading the butterfly. For simplicity, let's first consider the case
// where the only way to change the outOfLineCapacity is to change the structure. This works
// because the mutator performs the following steps sequentially:
//
// NukeStructure ChangeButterfly PutNewStructure
//
// Meanwhile the collector performs the following steps sequentially:
//
// ReadStructureEarly ReadButterfly ReadStructureLate
//
// The collector is allowed to do any of these three things:
//
// BEFORE: Scan the object with the structure and butterfly *before* the mutator's transition.
// AFTER: Scan the object with the structure and butterfly *after* the mutator's transition.
// IGNORE: Ignore the butterfly and call didRace to schedule us to be revisted again in the future.
//
// In other words, the collector will never see any torn structure/butterfly mix. It will
// always see the structure/butterfly before the transition or after but not in between.
//
// We can prove that this is correct by exhaustively considering all interleavings:
//
// NukeStructure ChangeButterfly PutNewStructure ReadStructureEarly ReadButterfly ReadStructureLate: AFTER, trivially.
// NukeStructure ChangeButterfly ReadStructureEarly PutNewStructure ReadButterfly ReadStructureLate: IGNORE, because nuked structure read early
// NukeStructure ChangeButterfly ReadStructureEarly ReadButterfly PutNewStructure ReadStructureLate: IGNORE, because nuked structure read early
// NukeStructure ChangeButterfly ReadStructureEarly ReadButterfly ReadStructureLate PutNewStructure: IGNORE, because nuked structure read early
// NukeStructure ReadStructureEarly ChangeButterfly PutNewStructure ReadButterfly ReadStructureLate: IGNORE, because nuked structure read early
// NukeStructure ReadStructureEarly ChangeButterfly ReadButterfly PutNewStructure ReadStructureLate: IGNORE, because nuked structure read early
// NukeStructure ReadStructureEarly ChangeButterfly ReadButterfly ReadStructureLate PutNewStructure: IGNORE, because nuked structure read early
// NukeStructure ReadStructureEarly ReadButterfly ChangeButterfly PutNewStructure ReadStructureLate: IGNORE, because nuked structure read early
// NukeStructure ReadStructureEarly ReadButterfly ChangeButterfly ReadStructureLate PutNewStructure: IGNORE, because nuked structure read early
// NukeStructure ReadStructureEarly ReadButterfly ReadStructureLate ChangeButterfly PutNewStructure: IGNORE, because nuked structure read early
// ReadStructureEarly NukeStructure ChangeButterfly PutNewStructure ReadButterfly ReadStructureLate: IGNORE, because early and late structures don't match
// ReadStructureEarly NukeStructure ChangeButterfly ReadButterfly PutNewStructure ReadStructureLate: IGNORE, because early and late structures don't match
// ReadStructureEarly NukeStructure ChangeButterfly ReadButterfly ReadStructureLate PutNewStructure: IGNORE, because nuked structure read late
// ReadStructureEarly NukeStructure ReadButterfly ChangeButterfly PutNewStructure ReadStructureLate: IGNORE, because early and late structures don't match
// ReadStructureEarly NukeStructure ReadButterfly ChangeButterfly ReadStructureLate PutNewStructure: IGNORE, because nuked structure read late
// ReadStructureEarly NukeStructure ReadButterfly ReadStructureLate ChangeButterfly PutNewStructure: IGNORE, because nuked structure read late
// ReadStructureEarly ReadButterfly NukeStructure ChangeButterfly PutNewStructure ReadStructureLate: IGNORE, because early and late structures don't match
// ReadStructureEarly ReadButterfly NukeStructure ChangeButterfly ReadStructureLate PutNewStructure: IGNORE, because nuked structure read late
// ReadStructureEarly ReadButterfly NukeStructure ReadStructureLate ChangeButterfly PutNewStructure: IGNORE, because nuked structure read late
// ReadStructureEarly ReadButterfly ReadStructureLate NukeStructure ChangeButterfly PutNewStructure: BEFORE, trivially.
//
// But we additionally have to worry about the size changing. We make this work by requiring that
// the collector reads the size early and late as well. Lets consider the interleaving of the
// mutator changing the size without changing the structure:
//
// NukeStructure ChangeButterfly ChangeMaxOffset RestoreStructure
//
// Meanwhile the collector does:
//
// ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ReadStructureLate ReadMaxOffsetLate
//
// The collector can detect races by not only comparing the early structure to the late structure
// (which will be the same before and after the algorithm runs) but also by comparing the early and
// late maxOffsets. Note: the IGNORE proofs do not cite all of the reasons why the collector will
// ignore the case, since we only need to identify one to say that we're in the ignore case.
//
// NukeStructure ChangeButterfly ChangeMaxOffset RestoreStructure ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ReadStructureLate ReadMaxOffsetLate: AFTER, trivially
// NukeStructure ChangeButterfly ChangeMaxOffset ReadStructureEarly RestoreStructure ReadMaxOffsetEarly ReadButterfly ReadStructureLate ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ChangeButterfly ChangeMaxOffset ReadStructureEarly ReadMaxOffsetEarly RestoreStructure ReadButterfly ReadStructureLate ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ChangeButterfly ChangeMaxOffset ReadStructureEarly ReadMaxOffsetEarly ReadButterfly RestoreStructure ReadStructureLate ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ChangeButterfly ChangeMaxOffset ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ReadStructureLate RestoreStructure ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ChangeButterfly ChangeMaxOffset ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ReadStructureLate ReadMaxOffsetLate RestoreStructure: IGNORE, read nuked structure early
// NukeStructure ChangeButterfly ReadStructureEarly ChangeMaxOffset RestoreStructure ReadMaxOffsetEarly ReadButterfly ReadStructureLate ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ChangeButterfly ReadStructureEarly ChangeMaxOffset ReadMaxOffsetEarly RestoreStructure ReadButterfly ReadStructureLate ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ChangeButterfly ReadStructureEarly ChangeMaxOffset ReadMaxOffsetEarly ReadButterfly RestoreStructure ReadStructureLate ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ChangeButterfly ReadStructureEarly ChangeMaxOffset ReadMaxOffsetEarly ReadButterfly ReadStructureLate RestoreStructure ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ChangeButterfly ReadStructureEarly ChangeMaxOffset ReadMaxOffsetEarly ReadButterfly ReadStructureLate ReadMaxOffsetLate RestoreStructure: IGNORE, read nuked structure early
// NukeStructure ChangeButterfly ReadStructureEarly ReadMaxOffsetEarly ChangeMaxOffset RestoreStructure ReadButterfly ReadStructureLate ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ChangeButterfly ReadStructureEarly ReadMaxOffsetEarly ChangeMaxOffset ReadButterfly RestoreStructure ReadStructureLate ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ChangeButterfly ReadStructureEarly ReadMaxOffsetEarly ChangeMaxOffset ReadButterfly ReadStructureLate RestoreStructure ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ChangeButterfly ReadStructureEarly ReadMaxOffsetEarly ChangeMaxOffset ReadButterfly ReadStructureLate ReadMaxOffsetLate RestoreStructure: IGNORE, read nuked structure early
// NukeStructure ChangeButterfly ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ChangeMaxOffset RestoreStructure ReadStructureLate ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ChangeButterfly ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ChangeMaxOffset ReadStructureLate RestoreStructure ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ChangeButterfly ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ChangeMaxOffset ReadStructureLate ReadMaxOffsetLate RestoreStructure: IGNORE, read nuked structure early
// NukeStructure ChangeButterfly ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ReadStructureLate ChangeMaxOffset RestoreStructure ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ChangeButterfly ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ReadStructureLate ChangeMaxOffset ReadMaxOffsetLate RestoreStructure: IGNORE, read nuked structure early
// NukeStructure ChangeButterfly ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ReadStructureLate ReadMaxOffsetLate ChangeMaxOffset RestoreStructure: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ChangeButterfly ChangeMaxOffset RestoreStructure ReadMaxOffsetEarly ReadButterfly ReadStructureLate ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ChangeButterfly ChangeMaxOffset ReadMaxOffsetEarly RestoreStructure ReadButterfly ReadStructureLate ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ChangeButterfly ChangeMaxOffset ReadMaxOffsetEarly ReadButterfly RestoreStructure ReadStructureLate ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ChangeButterfly ChangeMaxOffset ReadMaxOffsetEarly ReadButterfly ReadStructureLate RestoreStructure ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ChangeButterfly ChangeMaxOffset ReadMaxOffsetEarly ReadButterfly ReadStructureLate ReadMaxOffsetLate RestoreStructure: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ChangeButterfly ReadMaxOffsetEarly ChangeMaxOffset RestoreStructure ReadButterfly ReadStructureLate ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ChangeButterfly ReadMaxOffsetEarly ChangeMaxOffset ReadButterfly RestoreStructure ReadStructureLate ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ChangeButterfly ReadMaxOffsetEarly ChangeMaxOffset ReadButterfly ReadStructureLate RestoreStructure ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ChangeButterfly ReadMaxOffsetEarly ChangeMaxOffset ReadButterfly ReadStructureLate ReadMaxOffsetLate RestoreStructure: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ChangeButterfly ReadMaxOffsetEarly ReadButterfly ChangeMaxOffset RestoreStructure ReadStructureLate ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ChangeButterfly ReadMaxOffsetEarly ReadButterfly ChangeMaxOffset ReadStructureLate RestoreStructure ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ChangeButterfly ReadMaxOffsetEarly ReadButterfly ChangeMaxOffset ReadStructureLate ReadMaxOffsetLate RestoreStructure: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ChangeButterfly ReadMaxOffsetEarly ReadButterfly ReadStructureLate ChangeMaxOffset RestoreStructure ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ChangeButterfly ReadMaxOffsetEarly ReadButterfly ReadStructureLate ChangeMaxOffset ReadMaxOffsetLate RestoreStructure: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ChangeButterfly ReadMaxOffsetEarly ReadButterfly ReadStructureLate ReadMaxOffsetLate ChangeMaxOffset RestoreStructure: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ReadMaxOffsetEarly ChangeButterfly ChangeMaxOffset RestoreStructure ReadButterfly ReadStructureLate ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ReadMaxOffsetEarly ChangeButterfly ChangeMaxOffset ReadButterfly RestoreStructure ReadStructureLate ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ReadMaxOffsetEarly ChangeButterfly ChangeMaxOffset ReadButterfly ReadStructureLate RestoreStructure ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ReadMaxOffsetEarly ChangeButterfly ChangeMaxOffset ReadButterfly ReadStructureLate ReadMaxOffsetLate RestoreStructure: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ReadMaxOffsetEarly ChangeButterfly ReadButterfly ChangeMaxOffset RestoreStructure ReadStructureLate ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ReadMaxOffsetEarly ChangeButterfly ReadButterfly ChangeMaxOffset ReadStructureLate RestoreStructure ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ReadMaxOffsetEarly ChangeButterfly ReadButterfly ChangeMaxOffset ReadStructureLate ReadMaxOffsetLate RestoreStructure: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ReadMaxOffsetEarly ChangeButterfly ReadButterfly ReadStructureLate ChangeMaxOffset RestoreStructure ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ReadMaxOffsetEarly ChangeButterfly ReadButterfly ReadStructureLate ChangeMaxOffset ReadMaxOffsetLate RestoreStructure: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ReadMaxOffsetEarly ChangeButterfly ReadButterfly ReadStructureLate ReadMaxOffsetLate ChangeMaxOffset RestoreStructure: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ChangeButterfly ChangeMaxOffset RestoreStructure ReadStructureLate ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ChangeButterfly ChangeMaxOffset ReadStructureLate RestoreStructure ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ChangeButterfly ChangeMaxOffset ReadStructureLate ReadMaxOffsetLate RestoreStructure: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ChangeButterfly ReadStructureLate ChangeMaxOffset RestoreStructure ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ChangeButterfly ReadStructureLate ChangeMaxOffset ReadMaxOffsetLate RestoreStructure: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ChangeButterfly ReadStructureLate ReadMaxOffsetLate ChangeMaxOffset RestoreStructure: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ReadStructureLate ChangeButterfly ChangeMaxOffset RestoreStructure ReadMaxOffsetLate: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ReadStructureLate ChangeButterfly ChangeMaxOffset ReadMaxOffsetLate RestoreStructure: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ReadStructureLate ChangeButterfly ReadMaxOffsetLate ChangeMaxOffset RestoreStructure: IGNORE, read nuked structure early
// NukeStructure ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ReadStructureLate ReadMaxOffsetLate ChangeButterfly ChangeMaxOffset RestoreStructure: IGNORE, read nuked structure early
// ReadStructureEarly NukeStructure ChangeButterfly ChangeMaxOffset RestoreStructure ReadMaxOffsetEarly ReadButterfly ReadStructureLate ReadMaxOffsetLate: AFTER, the ReadStructureEarly sees the same structure as after and everything else runs after.
// ReadStructureEarly NukeStructure ChangeButterfly ChangeMaxOffset ReadMaxOffsetEarly RestoreStructure ReadButterfly ReadStructureLate ReadMaxOffsetLate: AFTER, as above and the ReadMaxOffsetEarly sees the maxOffset after.
// ReadStructureEarly NukeStructure ChangeButterfly ChangeMaxOffset ReadMaxOffsetEarly ReadButterfly RestoreStructure ReadStructureLate ReadMaxOffsetLate: AFTER, as above and the ReadButterfly sees the right butterfly after.
// ReadStructureEarly NukeStructure ChangeButterfly ChangeMaxOffset ReadMaxOffsetEarly ReadButterfly ReadStructureLate RestoreStructure ReadMaxOffsetLate: IGNORE, read nuked structure late
// ReadStructureEarly NukeStructure ChangeButterfly ChangeMaxOffset ReadMaxOffsetEarly ReadButterfly ReadStructureLate ReadMaxOffsetLate RestoreStructure: IGNORE, read nuked structure late
// ReadStructureEarly NukeStructure ChangeButterfly ReadMaxOffsetEarly ChangeMaxOffset RestoreStructure ReadButterfly ReadStructureLate ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ChangeButterfly ReadMaxOffsetEarly ChangeMaxOffset ReadButterfly RestoreStructure ReadStructureLate ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ChangeButterfly ReadMaxOffsetEarly ChangeMaxOffset ReadButterfly ReadStructureLate RestoreStructure ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ChangeButterfly ReadMaxOffsetEarly ChangeMaxOffset ReadButterfly ReadStructureLate ReadMaxOffsetLate RestoreStructure: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ChangeButterfly ReadMaxOffsetEarly ReadButterfly ChangeMaxOffset RestoreStructure ReadStructureLate ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ChangeButterfly ReadMaxOffsetEarly ReadButterfly ChangeMaxOffset ReadStructureLate RestoreStructure ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ChangeButterfly ReadMaxOffsetEarly ReadButterfly ChangeMaxOffset ReadStructureLate ReadMaxOffsetLate RestoreStructure: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ChangeButterfly ReadMaxOffsetEarly ReadButterfly ReadStructureLate ChangeMaxOffset RestoreStructure ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ChangeButterfly ReadMaxOffsetEarly ReadButterfly ReadStructureLate ChangeMaxOffset ReadMaxOffsetLate RestoreStructure: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ChangeButterfly ReadMaxOffsetEarly ReadButterfly ReadStructureLate ReadMaxOffsetLate ChangeMaxOffset RestoreStructure: IGNORE, read nuked structure late
// ReadStructureEarly NukeStructure ReadMaxOffsetEarly ChangeButterfly ChangeMaxOffset RestoreStructure ReadButterfly ReadStructureLate ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ReadMaxOffsetEarly ChangeButterfly ChangeMaxOffset ReadButterfly RestoreStructure ReadStructureLate ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ReadMaxOffsetEarly ChangeButterfly ChangeMaxOffset ReadButterfly ReadStructureLate RestoreStructure ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ReadMaxOffsetEarly ChangeButterfly ChangeMaxOffset ReadButterfly ReadStructureLate ReadMaxOffsetLate RestoreStructure: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ReadMaxOffsetEarly ChangeButterfly ReadButterfly ChangeMaxOffset RestoreStructure ReadStructureLate ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ReadMaxOffsetEarly ChangeButterfly ReadButterfly ChangeMaxOffset ReadStructureLate RestoreStructure ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ReadMaxOffsetEarly ChangeButterfly ReadButterfly ChangeMaxOffset ReadStructureLate ReadMaxOffsetLate RestoreStructure: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ReadMaxOffsetEarly ChangeButterfly ReadButterfly ReadStructureLate ChangeMaxOffset RestoreStructure ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ReadMaxOffsetEarly ChangeButterfly ReadButterfly ReadStructureLate ChangeMaxOffset ReadMaxOffsetLate RestoreStructure: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ReadMaxOffsetEarly ChangeButterfly ReadButterfly ReadStructureLate ReadMaxOffsetLate ChangeMaxOffset RestoreStructure: IGNORE, read nuked structure late
// ReadStructureEarly NukeStructure ReadMaxOffsetEarly ReadButterfly ChangeButterfly ChangeMaxOffset RestoreStructure ReadStructureLate ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ReadMaxOffsetEarly ReadButterfly ChangeButterfly ChangeMaxOffset ReadStructureLate RestoreStructure ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ReadMaxOffsetEarly ReadButterfly ChangeButterfly ChangeMaxOffset ReadStructureLate ReadMaxOffsetLate RestoreStructure: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ReadMaxOffsetEarly ReadButterfly ChangeButterfly ReadStructureLate ChangeMaxOffset RestoreStructure ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ReadMaxOffsetEarly ReadButterfly ChangeButterfly ReadStructureLate ChangeMaxOffset ReadMaxOffsetLate RestoreStructure: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ReadMaxOffsetEarly ReadButterfly ChangeButterfly ReadStructureLate ReadMaxOffsetLate ChangeMaxOffset RestoreStructure: IGNORE, read nuked structure late
// ReadStructureEarly NukeStructure ReadMaxOffsetEarly ReadButterfly ReadStructureLate ChangeButterfly ChangeMaxOffset RestoreStructure ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ReadMaxOffsetEarly ReadButterfly ReadStructureLate ChangeButterfly ChangeMaxOffset ReadMaxOffsetLate RestoreStructure: IGNORE, read different offsets
// ReadStructureEarly NukeStructure ReadMaxOffsetEarly ReadButterfly ReadStructureLate ChangeButterfly ReadMaxOffsetLate ChangeMaxOffset RestoreStructure: IGNORE, read nuked structure late
// ReadStructureEarly NukeStructure ReadMaxOffsetEarly ReadButterfly ReadStructureLate ReadMaxOffsetLate ChangeButterfly ChangeMaxOffset RestoreStructure: IGNORE, read nuked structure late
// ReadStructureEarly ReadMaxOffsetEarly NukeStructure ChangeButterfly ChangeMaxOffset RestoreStructure ReadButterfly ReadStructureLate ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly ReadMaxOffsetEarly NukeStructure ChangeButterfly ChangeMaxOffset ReadButterfly RestoreStructure ReadStructureLate ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly ReadMaxOffsetEarly NukeStructure ChangeButterfly ChangeMaxOffset ReadButterfly ReadStructureLate RestoreStructure ReadMaxOffsetLate: IGNORE, read nuked structure late
// ReadStructureEarly ReadMaxOffsetEarly NukeStructure ChangeButterfly ChangeMaxOffset ReadButterfly ReadStructureLate ReadMaxOffsetLate RestoreStructure: IGNORE, read nuked structure late
// ReadStructureEarly ReadMaxOffsetEarly NukeStructure ChangeButterfly ReadButterfly ChangeMaxOffset RestoreStructure ReadStructureLate ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly ReadMaxOffsetEarly NukeStructure ChangeButterfly ReadButterfly ChangeMaxOffset ReadStructureLate RestoreStructure ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly ReadMaxOffsetEarly NukeStructure ChangeButterfly ReadButterfly ChangeMaxOffset ReadStructureLate ReadMaxOffsetLate RestoreStructure: IGNORE, read different offsets
// ReadStructureEarly ReadMaxOffsetEarly NukeStructure ChangeButterfly ReadButterfly ReadStructureLate ChangeMaxOffset RestoreStructure ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly ReadMaxOffsetEarly NukeStructure ChangeButterfly ReadButterfly ReadStructureLate ChangeMaxOffset ReadMaxOffsetLate RestoreStructure: IGNORE, read different offsets
// ReadStructureEarly ReadMaxOffsetEarly NukeStructure ChangeButterfly ReadButterfly ReadStructureLate ReadMaxOffsetLate ChangeMaxOffset RestoreStructure: IGNORE, read nuked structure late
// ReadStructureEarly ReadMaxOffsetEarly NukeStructure ReadButterfly ChangeButterfly ChangeMaxOffset RestoreStructure ReadStructureLate ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly ReadMaxOffsetEarly NukeStructure ReadButterfly ChangeButterfly ChangeMaxOffset ReadStructureLate RestoreStructure ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly ReadMaxOffsetEarly NukeStructure ReadButterfly ChangeButterfly ChangeMaxOffset ReadStructureLate ReadMaxOffsetLate RestoreStructure: IGNORE, read different offsets
// ReadStructureEarly ReadMaxOffsetEarly NukeStructure ReadButterfly ChangeButterfly ReadStructureLate ChangeMaxOffset RestoreStructure ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly ReadMaxOffsetEarly NukeStructure ReadButterfly ChangeButterfly ReadStructureLate ChangeMaxOffset ReadMaxOffsetLate RestoreStructure: IGNORE, read different offsets
// ReadStructureEarly ReadMaxOffsetEarly NukeStructure ReadButterfly ChangeButterfly ReadStructureLate ReadMaxOffsetLate ChangeMaxOffset RestoreStructure: IGNORE, read nuked structure late
// ReadStructureEarly ReadMaxOffsetEarly NukeStructure ReadButterfly ReadStructureLate ChangeButterfly ChangeMaxOffset RestoreStructure ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly ReadMaxOffsetEarly NukeStructure ReadButterfly ReadStructureLate ChangeButterfly ChangeMaxOffset ReadMaxOffsetLate RestoreStructure: IGNORE, read nuked structure late
// ReadStructureEarly ReadMaxOffsetEarly NukeStructure ReadButterfly ReadStructureLate ChangeButterfly ReadMaxOffsetLate ChangeMaxOffset RestoreStructure: IGNORE, read nuked structure late
// ReadStructureEarly ReadMaxOffsetEarly NukeStructure ReadButterfly ReadStructureLate ReadMaxOffsetLate ChangeButterfly ChangeMaxOffset RestoreStructure: IGNORE, read nuked structure late
// ReadStructureEarly ReadMaxOffsetEarly ReadButterfly NukeStructure ChangeButterfly ChangeMaxOffset RestoreStructure ReadStructureLate ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly ReadMaxOffsetEarly ReadButterfly NukeStructure ChangeButterfly ChangeMaxOffset ReadStructureLate RestoreStructure ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly ReadMaxOffsetEarly ReadButterfly NukeStructure ChangeButterfly ChangeMaxOffset ReadStructureLate ReadMaxOffsetLate RestoreStructure: IGNORE, read different offsets
// ReadStructureEarly ReadMaxOffsetEarly ReadButterfly NukeStructure ChangeButterfly ReadStructureLate ChangeMaxOffset RestoreStructure ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly ReadMaxOffsetEarly ReadButterfly NukeStructure ChangeButterfly ReadStructureLate ChangeMaxOffset ReadMaxOffsetLate RestoreStructure: IGNORE, read different offsets
// ReadStructureEarly ReadMaxOffsetEarly ReadButterfly NukeStructure ChangeButterfly ReadStructureLate ReadMaxOffsetLate ChangeMaxOffset RestoreStructure: IGNORE, read nuked structure late
// ReadStructureEarly ReadMaxOffsetEarly ReadButterfly NukeStructure ReadStructureLate ChangeButterfly ChangeMaxOffset RestoreStructure ReadMaxOffsetLate: IGNORE, read nuked structure late
// ReadStructureEarly ReadMaxOffsetEarly ReadButterfly NukeStructure ReadStructureLate ChangeButterfly ChangeMaxOffset ReadMaxOffsetLate RestoreStructure: IGNORE, read nuked structure late
// ReadStructureEarly ReadMaxOffsetEarly ReadButterfly NukeStructure ReadStructureLate ChangeButterfly ReadMaxOffsetLate ChangeMaxOffset RestoreStructure: IGNORE, read nuked structure late
// ReadStructureEarly ReadMaxOffsetEarly ReadButterfly NukeStructure ReadStructureLate ReadMaxOffsetLate ChangeButterfly ChangeMaxOffset RestoreStructure: IGNORE, read nuked structure late
// ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ReadStructureLate NukeStructure ChangeButterfly ChangeMaxOffset RestoreStructure ReadMaxOffsetLate: IGNORE, read different offsets
// ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ReadStructureLate NukeStructure ChangeButterfly ChangeMaxOffset ReadMaxOffsetLate RestoreStructure: IGNORE, read different offsets
// ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ReadStructureLate NukeStructure ChangeButterfly ReadMaxOffsetLate ChangeMaxOffset RestoreStructure: BEFORE, reads the offset before, everything else happens before
// ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ReadStructureLate NukeStructure ReadMaxOffsetLate ChangeButterfly ChangeMaxOffset RestoreStructure: BEFORE, reads the offset before, everything else happens before
// ReadStructureEarly ReadMaxOffsetEarly ReadButterfly ReadStructureLate ReadMaxOffsetLate NukeStructure ChangeButterfly ChangeMaxOffset RestoreStructure: BEFORE, trivially
//
// Whew.
//
// What the collector is doing is just the "double collect" snapshot from "The Unbounded Single-
// Writer Algorithm" from Yehuda Afek et al's "Atomic Snapshots of Shared Memory" in JACM 1993,
// also available here:
//
// http://people.csail.mit.edu/shanir/publications/AADGMS.pdf
//
// Unlike Afek et al's algorithm, ours does not require extra hacks to force wait-freedom (see
// "Observation 2" in the paper). This simplifies the whole algorithm. Instead we are happy with
// obstruction-freedom, and like any good obstruction-free algorithm, we ensure progress using
// scheduling. We also only collect the butterfly once instead of twice; this optimization seems
// to hold up in my proofs above and I'm not sure it's part of Afek et al's algos.
//
// For more background on this kind of madness, I like this paper; it's where I learned about
// both the snapshot algorithm and obstruction-freedom:
//
// Lunchangco, Moir, Shavit. "Nonblocking k-compare-single-swap." SPAA '03
// https://pdfs.semanticscholar.org/343f/7182cde7669ca2a7de3dc01127927f384ef7.pdf
StructureID structureID = this->structureID();
if (structureID.isNuked())
return nullptr;
structure = structureID.decode();
maxOffset = structure->maxOffset();
IndexingType indexingMode;
Dependency indexingModeDependency = structure->fencedIndexingMode(indexingMode);
Locker<JSCellLock> locker(NoLockingNecessary);
switch (indexingMode) {
case ALL_ARRAY_STORAGE_INDEXING_TYPES:
// We need to hold this lock to protect against changes to the innards of the butterfly
// that can happen when the butterfly is used for array storage.
// We do not need to hold this lock for contiguous butterflies. We do not reuse the existing
// butterfly with contiguous shape for new array storage butterfly. When converting the butterfly
// with contiguous shape to array storage, we always allocate a new one. Holding this lock for contiguous
// butterflies is unnecessary since contiguous shaped butterfly never becomes broken state.
locker = Locker { cellLock() };
break;
default:
break;
}
Dependency butterflyDependency = indexingModeDependency.consume(this)->fencedButterfly(butterfly);
if (!butterfly)
return structure;
if (butterflyDependency.consume(this)->structureID() != structureID)
return nullptr;
if (butterflyDependency.consume(structure)->maxOffset() != maxOffset)
return nullptr;
markAuxiliaryAndVisitOutOfLineProperties(visitor, butterfly, structure, maxOffset);
ASSERT(indexingMode == structure->indexingMode());
visitElements(indexingMode);
return structure;
}
size_t JSObject::estimatedSize(JSCell* cell, VM& vm)
{
JSObject* thisObject = jsCast<JSObject*>(cell);
size_t butterflyOutOfLineSize = thisObject->m_butterfly ? thisObject->structure()->outOfLineSize() : 0;
return Base::estimatedSize(cell, vm) + butterflyOutOfLineSize;
}
template<typename Visitor>
void JSObject::visitChildrenImpl(JSCell* cell, Visitor& visitor)
{
JSObject* thisObject = jsCast<JSObject*>(cell);
ASSERT_GC_OBJECT_INHERITS(thisObject, info());
typename Visitor::DefaultMarkingViolationAssertionScope assertionScope(visitor);
JSCell::visitChildren(thisObject, visitor);
thisObject->visitButterfly(visitor);
}
DEFINE_VISIT_CHILDREN_WITH_MODIFIER(JS_EXPORT_PRIVATE, JSObject);
void JSObject::analyzeHeap(JSCell* cell, HeapAnalyzer& analyzer)
{
JSObject* thisObject = jsCast<JSObject*>(cell);
Base::analyzeHeap(cell, analyzer);
Structure* structure = thisObject->structure();
for (const auto& entry : structure->getPropertiesConcurrently()) {
JSValue toValue = thisObject->getDirect(entry.offset());
if (toValue && toValue.isCell())
analyzer.analyzePropertyNameEdge(thisObject, toValue.asCell(), entry.key());
}
Butterfly* butterfly = thisObject->butterfly();
if (butterfly) {
WriteBarrier<Unknown>* data = nullptr;
uint32_t count = 0;
switch (thisObject->indexingType()) {
case ALL_CONTIGUOUS_INDEXING_TYPES:
data = butterfly->contiguous().data();
count = butterfly->publicLength();
break;
case ALL_ARRAY_STORAGE_INDEXING_TYPES:
data = butterfly->arrayStorage()->m_vector;
count = butterfly->arrayStorage()->vectorLength();
break;
default:
break;
}
for (uint32_t i = 0; i < count; ++i) {
JSValue toValue = data[i].get();
if (toValue && toValue.isCell())
analyzer.analyzeIndexEdge(thisObject, toValue.asCell(), i);
}
}
}
template<typename Visitor>
void JSFinalObject::visitChildrenImpl(JSCell* cell, Visitor& visitor)
{
JSFinalObject* thisObject = jsCast<JSFinalObject*>(cell);
ASSERT_GC_OBJECT_INHERITS(thisObject, info());
typename Visitor::DefaultMarkingViolationAssertionScope assertionScope(visitor);
JSCell::visitChildren(thisObject, visitor);
if (Structure* structure = thisObject->visitButterfly(visitor)) {
if (unsigned storageSize = structure->inlineSize())
visitor.appendValuesHidden(thisObject->inlineStorage(), storageSize);
}
}
DEFINE_VISIT_CHILDREN_WITH_MODIFIER(JS_EXPORT_PRIVATE, JSFinalObject);
String JSObject::calculatedClassName(JSObject* object)
{
String constructorFunctionName;
auto* structure = object->structure();
auto* globalObject = structure->globalObject();
VM& vm = globalObject->vm();
auto scope = DECLARE_CATCH_SCOPE(vm);
// Check for a display name of obj.constructor.
// This is useful to get `Foo` for the `(class Foo).prototype` object.
PropertySlot slot(object, PropertySlot::InternalMethodType::VMInquiry, &vm);
if (object->getOwnPropertySlot(object, globalObject, vm.propertyNames->constructor, slot)) {
EXCEPTION_ASSERT(!scope.exception());
if (slot.isValue()) {
if (JSObject* ctorObject = jsDynamicCast<JSObject*>(slot.getValue(globalObject, vm.propertyNames->constructor))) {
if (JSFunction* constructorFunction = jsDynamicCast<JSFunction*>(ctorObject))
constructorFunctionName = constructorFunction->calculatedDisplayName(vm);
else if (InternalFunction* constructorFunction = jsDynamicCast<InternalFunction*>(ctorObject))
constructorFunctionName = constructorFunction->calculatedDisplayName(vm);
}
}
}
EXCEPTION_ASSERT(!scope.exception() || constructorFunctionName.isNull());
if (UNLIKELY(scope.exception()))
scope.clearException();
// Get the display name of obj.__proto__.constructor.
// This is useful to get `Foo` for a `new Foo` object.
if (constructorFunctionName.isNull()) {
if (LIKELY(!structure->typeInfo().overridesGetPrototype())) {
JSValue protoValue = object->getPrototypeDirect();
if (protoValue.isObject()) {
JSObject* protoObject = asObject(protoValue);
PropertySlot slot(protoValue, PropertySlot::InternalMethodType::VMInquiry, &vm);
if (protoObject->getPropertySlot(globalObject, vm.propertyNames->constructor, slot)) {
EXCEPTION_ASSERT(!scope.exception());
if (slot.isValue()) {
if (JSObject* ctorObject = jsDynamicCast<JSObject*>(slot.getValue(globalObject, vm.propertyNames->constructor))) {
if (JSFunction* constructorFunction = jsDynamicCast<JSFunction*>(ctorObject))
constructorFunctionName = constructorFunction->calculatedDisplayName(vm);
else if (InternalFunction* constructorFunction = jsDynamicCast<InternalFunction*>(ctorObject))
constructorFunctionName = constructorFunction->calculatedDisplayName(vm);
}
}
}
}
}
}
EXCEPTION_ASSERT(!scope.exception() || constructorFunctionName.isNull());
if (UNLIKELY(scope.exception()))
scope.clearException();
if (constructorFunctionName.isNull() || constructorFunctionName == "Object"_s) {
PropertySlot slot(object, PropertySlot::InternalMethodType::VMInquiry, &vm);
if (object->getPropertySlot(globalObject, vm.propertyNames->toStringTagSymbol, slot)) {
EXCEPTION_ASSERT(!scope.exception());
if (slot.isValue()) {
JSValue value = slot.getValue(globalObject, vm.propertyNames->toStringTagSymbol);
if (value.isString()) {
auto tag = asString(value)->value(globalObject);
if (UNLIKELY(scope.exception()))
scope.clearException();
return tag;
}
}
}
if (UNLIKELY(scope.exception()))
scope.clearException();
String classInfoName = object->classInfo()->className;
if (!classInfoName.isNull())
return classInfoName;
if (constructorFunctionName.isNull())
return "Object"_s;
}
return constructorFunctionName;
}
bool JSObject::getOwnPropertySlotByIndex(JSObject* thisObject, JSGlobalObject* globalObject, unsigned i, PropertySlot& slot)
{
VM& vm = globalObject->vm();
// NB. The fact that we're directly consulting our indexed storage implies that it is not
// legal for anyone to override getOwnPropertySlot() without also overriding
// getOwnPropertySlotByIndex().
if (i > MAX_ARRAY_INDEX)
return thisObject->methodTable()->getOwnPropertySlot(thisObject, globalObject, Identifier::from(vm, i), slot);
switch (thisObject->indexingType()) {
case ALL_BLANK_INDEXING_TYPES:
case ALL_UNDECIDED_INDEXING_TYPES:
break;
case ALL_INT32_INDEXING_TYPES:
case ALL_CONTIGUOUS_INDEXING_TYPES: {
Butterfly* butterfly = thisObject->butterfly();
if (i >= butterfly->vectorLength())
return false;
JSValue value = butterfly->contiguous().at(thisObject, i).get();
if (value) {
slot.setValue(thisObject, static_cast<unsigned>(PropertyAttribute::None), value);
return true;
}
return false;
}
case ALL_DOUBLE_INDEXING_TYPES: {
Butterfly* butterfly = thisObject->butterfly();
if (i >= butterfly->vectorLength())
return false;
double value = butterfly->contiguousDouble().at(thisObject, i);
if (value == value) {
slot.setValue(thisObject, static_cast<unsigned>(PropertyAttribute::None), JSValue(JSValue::EncodeAsDouble, value));
return true;
}
return false;
}
case ALL_ARRAY_STORAGE_INDEXING_TYPES: {
ArrayStorage* storage = thisObject->m_butterfly->arrayStorage();
if (i >= storage->length())
return false;
if (i < storage->vectorLength()) {
JSValue value = storage->m_vector[i].get();
if (value) {
slot.setValue(thisObject, static_cast<unsigned>(PropertyAttribute::None), value);
return true;
}
} else if (SparseArrayValueMap* map = storage->m_sparseMap.get()) {
SparseArrayValueMap::iterator it = map->find(i);
if (it != map->notFound()) {
it->value.get(thisObject, slot);
return true;
}
}
break;
}
default:
RELEASE_ASSERT_NOT_REACHED();
break;
}
return false;
}
#if ASSERT_ENABLED
// These needs to be unique (not inlined) for ASSERT_ENABLED builds to enable
// Structure::validateFlags() to do checks using function pointer comparisons.
bool JSObject::getOwnPropertySlot(JSObject* object, JSGlobalObject* globalObject, PropertyName propertyName, PropertySlot& slot)
{
return getOwnPropertySlotImpl(object, globalObject, propertyName, slot);
}
#endif // ASSERT_ENABLED
// https://tc39.github.io/ecma262/#sec-ordinaryset
bool ordinarySetSlow(JSGlobalObject* globalObject, JSObject* object, PropertyName propertyName, JSValue value, JSValue receiver, bool shouldThrow)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
PropertyDescriptor ownDescriptor;
if (object->type() != ProxyObjectType) {
object->getOwnPropertyDescriptor(globalObject, propertyName, ownDescriptor);
RETURN_IF_EXCEPTION(scope, false);
}
RELEASE_AND_RETURN(scope, ordinarySetWithOwnDescriptor(globalObject, object, propertyName, value, receiver, WTFMove(ownDescriptor), shouldThrow));
}
// https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-ordinarysetwithowndescriptor
bool ordinarySetWithOwnDescriptor(JSGlobalObject* globalObject, JSObject* object, PropertyName propertyName, JSValue value, JSValue receiver, PropertyDescriptor&& ownDescriptor, bool shouldThrow)
{
// If we find the receiver is not the same to the object, we fall to this slow path.
// Currently, there are 3 candidates.
// 1. Reflect.set can alter the receiver with an arbitrary value.
// 2. Window Proxy.
// 3. ES6 Proxy.
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSObject* current = object;
while (true) {
if (current->type() == ProxyObjectType) {
auto* proxy = jsCast<ProxyObject*>(current);
PutPropertySlot slot(receiver, shouldThrow);
RELEASE_AND_RETURN(scope, proxy->ProxyObject::put(proxy, globalObject, propertyName, value, slot));
}
// 9.1.9.1-2 Let ownDesc be ? O.[[GetOwnProperty]](P).
bool ownDescriptorFound;
if (current == object)
ownDescriptorFound = !ownDescriptor.isEmpty();
else {
ownDescriptorFound = current->getOwnPropertyDescriptor(globalObject, propertyName, ownDescriptor);
RETURN_IF_EXCEPTION(scope, false);
}
if (!ownDescriptorFound) {
// 9.1.9.1-3-a Let parent be ? O.[[GetPrototypeOf]]().
JSValue prototype = current->getPrototype(vm, globalObject);
RETURN_IF_EXCEPTION(scope, false);
// 9.1.9.1-3-b If parent is not null, then
if (!prototype.isNull()) {
// 9.1.9.1-3-b-i Return ? parent.[[Set]](P, V, Receiver).
current = asObject(prototype);
continue;
}
// 9.1.9.1-3-c-i Let ownDesc be the PropertyDescriptor{[[Value]]: undefined, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true}.
ownDescriptor = PropertyDescriptor(jsUndefined(), static_cast<unsigned>(PropertyAttribute::None));
}
break;
}
// 9.1.9.1-4 If IsDataDescriptor(ownDesc) is true, then
if (ownDescriptor.isDataDescriptor()) {
// 9.1.9.1-4-a If ownDesc.[[Writable]] is false, return false.
if (!ownDescriptor.writable())
return typeError(globalObject, scope, shouldThrow, ReadonlyPropertyWriteError);
// 9.1.9.1-4-b If Type(Receiver) is not Object, return false.
if (!receiver.isObject())
return typeError(globalObject, scope, shouldThrow, ReadonlyPropertyWriteError);
// In OrdinarySet, the receiver may not be the same to the object.
// So, we perform [[GetOwnProperty]] onto the receiver while we already perform [[GetOwnProperty]] onto the object.
// 9.1.9.1-4-c Let existingDescriptor be ? Receiver.[[GetOwnProperty]](P).
JSObject* receiverObject = asObject(receiver);
PropertyDescriptor existingDescriptor;
bool existingDescriptorFound = receiverObject->getOwnPropertyDescriptor(globalObject, propertyName, existingDescriptor);
RETURN_IF_EXCEPTION(scope, false);
// 9.1.9.1-4-d If existingDescriptor is not undefined, then
if (existingDescriptorFound) {
// 9.1.9.1-4-d-i If IsAccessorDescriptor(existingDescriptor) is true, return false.
if (existingDescriptor.isAccessorDescriptor())
return typeError(globalObject, scope, shouldThrow, ReadonlyPropertyWriteError);
// 9.1.9.1-4-d-ii If existingDescriptor.[[Writable]] is false, return false.
if (!existingDescriptor.writable())
return typeError(globalObject, scope, shouldThrow, ReadonlyPropertyWriteError);
// 9.1.9.1-4-d-iii Let valueDesc be the PropertyDescriptor{[[Value]]: V}.
PropertyDescriptor valueDescriptor;
valueDescriptor.setValue(value);
// 9.1.9.1-4-d-iv Return ? Receiver.[[DefineOwnProperty]](P, valueDesc).
RELEASE_AND_RETURN(scope, receiverObject->methodTable()->defineOwnProperty(receiverObject, globalObject, propertyName, valueDescriptor, shouldThrow));
}
// 9.1.9.1-4-e Else Receiver does not currently have a property P,
// 9.1.9.1-4-e-i Return ? CreateDataProperty(Receiver, P, V).
RELEASE_AND_RETURN(scope, receiverObject->methodTable()->defineOwnProperty(receiverObject, globalObject, propertyName, PropertyDescriptor(value, static_cast<unsigned>(PropertyAttribute::None)), shouldThrow));
}
// 9.1.9.1-5 Assert: IsAccessorDescriptor(ownDesc) is true.
ASSERT(ownDescriptor.isAccessorDescriptor());
// 9.1.9.1-6 Let setter be ownDesc.[[Set]].
// 9.1.9.1-7 If setter is undefined, return false.
JSValue setter = ownDescriptor.setter();
if (!setter.isObject())
return typeError(globalObject, scope, shouldThrow, ReadonlyPropertyWriteError);
// 9.1.9.1-8 Perform ? Call(setter, Receiver, << V >>).
JSObject* setterObject = asObject(setter);
MarkedArgumentBuffer args;
args.append(value);
ASSERT(!args.hasOverflowed());
auto callData = JSC::getCallData(setterObject);
scope.release();
call(globalObject, setterObject, callData, receiver, args);
// 9.1.9.1-9 Return true.
return true;
}
bool setterThatIgnoresPrototypeProperties(JSGlobalObject* globalObject, JSValue thisValue, JSObject* homeObject, PropertyName propertyName, JSValue value, bool shouldThrow)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
if (!thisValue.isObject())
return throwTypeError(globalObject, scope, "SetterThatIgnoresPrototypeProperties expected |this| to be an object."_s);
JSObject* thisObject = asObject(thisValue);
RETURN_IF_EXCEPTION(scope, { });
if (thisObject == homeObject)
return throwTypeError(globalObject, scope, "SetterThatIgnoresPrototypeProperties was called on a home object."_s);
bool hasProperty = thisObject->hasOwnProperty(globalObject, propertyName);
RETURN_IF_EXCEPTION(scope, { });
scope.release();
if (hasProperty) {
PutPropertySlot slot(thisObject, shouldThrow);
return thisObject->methodTable()->put(thisObject, globalObject, propertyName, value, slot);
}
return thisObject->createDataProperty(globalObject, propertyName, value, shouldThrow);
}
// https://tc39.es/ecma262/#sec-ordinaryset
bool JSObject::put(JSCell* cell, JSGlobalObject* globalObject, PropertyName propertyName, JSValue value, PutPropertySlot& slot)
{
return putInlineForJSObject(cell, globalObject, propertyName, value, slot);
}
bool JSObject::putInlineSlow(JSGlobalObject* globalObject, PropertyName propertyName, JSValue value, PutPropertySlot& slot)
{
ASSERT(!parseIndex(propertyName));
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
if (UNLIKELY(!vm.isSafeToRecurseSoft())) {
throwStackOverflowError(globalObject, scope);
return false;
}
JSObject* obj = this;
for (;;) {
Structure* structure = obj->structure();
if (obj != this && structure->typeInfo().overridesPut())
RELEASE_AND_RETURN(scope, obj->methodTable()->put(obj, globalObject, propertyName, value, slot));
bool hasProperty = false;
unsigned attributes;
PutValueFunc customSetter = nullptr;
PropertyOffset offset = structure->get(vm, propertyName, attributes);
if (isValidOffset(offset)) {
hasProperty = true;
if (attributes & PropertyAttribute::CustomAccessorOrValue)
customSetter = jsCast<CustomGetterSetter*>(obj->getDirect(offset))->setter();
} else if (structure->hasNonReifiedStaticProperties()) {
if (auto entry = structure->findPropertyHashEntry(propertyName)) {
hasProperty = true;
attributes = entry->value->attributes();
// FIXME: Remove this after we stop defaulting to CustomValue in static hash tables.
if (!(attributes & (PropertyAttribute::CustomAccessor | PropertyAttribute::BuiltinOrFunctionOrAccessorOrLazyPropertyOrConstant)))
attributes |= PropertyAttribute::CustomValue;
if (attributes & PropertyAttribute::CustomAccessorOrValue)
customSetter = entry->value->propertyPutter();
}
}
if (hasProperty) {
if (attributes & PropertyAttribute::ReadOnly)
return typeError(globalObject, scope, slot.isStrictMode(), ReadonlyPropertyWriteError);
if (attributes & PropertyAttribute::Accessor) {
ASSERT(isValidOffset(offset));
// We need to make sure that we decide to cache this property before we potentially execute aribitrary JS.
if (!this->structure()->isUncacheableDictionary())
slot.setCacheableSetter(obj, offset);
RELEASE_AND_RETURN(scope, jsCast<GetterSetter*>(obj->getDirect(offset))->callSetter(globalObject, slot.thisValue(), value, slot.isStrictMode()));
}
if (attributes & PropertyAttribute::CustomAccessor) {
// FIXME: Remove this after WebIDL generator is fixed to set ReadOnly for [RuntimeConditionallyReadWrite] attributes.
if (!customSetter)
return false;
ASSERT(customSetter);
// FIXME: We should only be caching these if we're not an uncacheable dictionary:
// https://bugs.webkit.org/show_bug.cgi?id=215347
slot.setCustomAccessor(obj, customSetter);
scope.release();
customSetter(obj->globalObject(), JSValue::encode(slot.thisValue()), JSValue::encode(value), propertyName);
return true;
}
if (attributes & PropertyAttribute::CustomValue) {
if (!isThisValueAltered(slot, obj)) {
if (customSetter) {
// FIXME: We should only be caching these if we're not an uncacheable dictionary:
// https://bugs.webkit.org/show_bug.cgi?id=215347
slot.setCustomValue(obj, customSetter);
RELEASE_AND_RETURN(scope, customSetter(obj->globalObject(), JSValue::encode(obj), JSValue::encode(value), propertyName));
}
// Avoid PutModePut because it fails for non-extensible structures.
obj->putDirect(vm, propertyName, value, attributesForStructure(attributes) & ~PropertyAttribute::CustomValue, slot);
return true;
}
}
if (attributes & PropertyAttribute::BuiltinOrFunctionOrLazyProperty) {
if (!isThisValueAltered(slot, obj)) {
// Avoid PutModePut because it fails for non-extensible structures.
obj->putDirect(vm, propertyName, value, attributesForStructure(attributes), slot);
return true;
}
}
// If there's an existing writable property on the base object, or on one of its
// prototypes, we should attempt to store the property on the receiver.
break;
}
JSValue prototype = obj->getPrototype(vm, globalObject);
RETURN_IF_EXCEPTION(scope, false);
if (prototype.isNull())
break;
obj = asObject(prototype);
}
scope.release();
if (UNLIKELY(isThisValueAltered(slot, this)))
return definePropertyOnReceiver(globalObject, propertyName, value, slot);
return putInlineFast(globalObject, propertyName, value, slot);
}
bool JSObject::mightBeSpecialProperty(VM& vm, JSType type, UniquedStringImpl* uid)
{
switch (type) {
case ArrayType:
case DerivedArrayType:
return uid == vm.propertyNames->length.impl();
case JSFunctionType:
return uid == vm.propertyNames->length.impl() || uid == vm.propertyNames->name.impl() || uid == vm.propertyNames->prototype.impl();
default:
return true;
}
}
static NEVER_INLINE bool definePropertyOnReceiverSlow(JSGlobalObject* globalObject, PropertyName propertyName, JSValue value, JSObject* receiver, bool shouldThrow)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
PropertySlot slot(receiver, PropertySlot::InternalMethodType::GetOwnProperty);
bool hasProperty = receiver->methodTable()->getOwnPropertySlot(receiver, globalObject, propertyName, slot);
RETURN_IF_EXCEPTION(scope, false);
if (hasProperty) {
// FIXME: For an accessor with setter, the error message is misleading.
if (slot.attributes() & PropertyAttribute::ReadOnlyOrAccessorOrCustomAccessor)
return typeError(globalObject, scope, shouldThrow, ReadonlyPropertyWriteError);
if (slot.attributes() & PropertyAttribute::CustomValue) {
PutValueFunc customSetter = slot.customSetter();
if (customSetter)
RELEASE_AND_RETURN(scope, customSetter(receiver->globalObject(), JSValue::encode(receiver), JSValue::encode(value), propertyName));
}
PropertyDescriptor descriptor;
descriptor.setValue(value);
RELEASE_AND_RETURN(scope, receiver->methodTable()->defineOwnProperty(receiver, globalObject, propertyName, descriptor, shouldThrow));
}
RELEASE_AND_RETURN(scope, receiver->createDataProperty(globalObject, propertyName, value, shouldThrow));
}
// https://tc39.es/ecma262/#sec-ordinaryset (step 3)
bool JSObject::definePropertyOnReceiver(JSGlobalObject* globalObject, PropertyName propertyName, JSValue value, PutPropertySlot& slot)
{
ASSERT(!parseIndex(propertyName));
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSObject* receiver = slot.thisValue().getObject();
// FIXME: For a failure due to primitive receiver, the error message is misleading.
if (!receiver)
return typeError(globalObject, scope, slot.isStrictMode(), ReadonlyPropertyWriteError);
scope.release();
if (receiver->type() == GlobalProxyType)
receiver = jsCast<JSGlobalProxy*>(receiver)->target();
if (slot.isTaintedByOpaqueObject() || receiver->methodTable()->defineOwnProperty != JSObject::defineOwnProperty) {
if (mightBeSpecialProperty(vm, receiver->type(), propertyName.uid()))
return definePropertyOnReceiverSlow(globalObject, propertyName, value, receiver, slot.isStrictMode());
}
if (receiver->structure()->hasAnyKindOfGetterSetterProperties()) {
unsigned attributes;
if (receiver->getDirectOffset(vm, propertyName, attributes) != invalidOffset && (attributes & PropertyAttribute::CustomValue))
return definePropertyOnReceiverSlow(globalObject, propertyName, value, receiver, slot.isStrictMode());
}
if (UNLIKELY(receiver->hasNonReifiedStaticProperties()))
return receiver->putInlineFastReplacingStaticPropertyIfNeeded(globalObject, propertyName, value, slot);
return receiver->putInlineFast(globalObject, propertyName, value, slot);
}
bool JSObject::putInlineFastReplacingStaticPropertyIfNeeded(JSGlobalObject* globalObject, PropertyName propertyName, JSValue value, PutPropertySlot& slot)
{
ASSERT(!parseIndex(propertyName));
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
Structure* structure = this->structure();
ASSERT(structure->hasNonReifiedStaticProperties());
if (!isValidOffset(structure->get(vm, propertyName))) {
if (auto entry = structure->findPropertyHashEntry(propertyName)) {
if (entry->value->attributes() & PropertyAttribute::ReadOnlyOrAccessorOrCustomAccessor) {
// FIXME: For an accessor with setter, the error message is misleading.
return typeError(globalObject, scope, slot.isStrictMode(), ReadonlyPropertyWriteError);
}
if (entry->value->attributes() & PropertyAttribute::CustomValue) {
PutValueFunc customSetter = entry->value->propertyPutter();
if (customSetter)
RELEASE_AND_RETURN(scope, customSetter(structure->globalObject(), JSValue::encode(this), JSValue::encode(value), propertyName));
}
// Avoid PutModePut because it fails for non-extensible structures.
putDirect(vm, propertyName, value, attributesForStructure(entry->value->attributes()) & ~PropertyAttribute::CustomValue, slot);
return true;
}
}
RELEASE_AND_RETURN(scope, putInlineFast(globalObject, propertyName, value, slot));
}
bool JSObject::putByIndex(JSCell* cell, JSGlobalObject* globalObject, unsigned propertyName, JSValue value, bool shouldThrow)
{
VM& vm = globalObject->vm();
JSObject* thisObject = jsCast<JSObject*>(cell);
if (propertyName > MAX_ARRAY_INDEX) {
PutPropertySlot slot(cell, shouldThrow);
return thisObject->methodTable()->put(thisObject, globalObject, Identifier::from(vm, propertyName), value, slot);
}
thisObject->ensureWritable(vm);
switch (thisObject->indexingType()) {
case ALL_BLANK_INDEXING_TYPES:
break;
case ALL_UNDECIDED_INDEXING_TYPES: {
thisObject->convertUndecidedForValue(vm, value);
// Reloop.
return putByIndex(cell, globalObject, propertyName, value, shouldThrow);
}
case ALL_INT32_INDEXING_TYPES: {
if (!value.isInt32()) {
thisObject->convertInt32ForValue(vm, value);
return putByIndex(cell, globalObject, propertyName, value, shouldThrow);
}
FALLTHROUGH;
}
case ALL_CONTIGUOUS_INDEXING_TYPES: {
Butterfly* butterfly = thisObject->butterfly();
if (propertyName >= butterfly->vectorLength())
break;
butterfly->contiguous().at(thisObject, propertyName).setWithoutWriteBarrier(value);
if (propertyName >= butterfly->publicLength())
butterfly->setPublicLength(propertyName + 1);
vm.writeBarrier(thisObject, value);
return true;
}
case ALL_DOUBLE_INDEXING_TYPES: {
if (!value.isNumber()) {
thisObject->convertDoubleToContiguous(vm);
// Reloop.
return putByIndex(cell, globalObject, propertyName, value, shouldThrow);
}
double valueAsDouble = value.asNumber();
if (valueAsDouble != valueAsDouble) {
thisObject->convertDoubleToContiguous(vm);
// Reloop.
return putByIndex(cell, globalObject, propertyName, value, shouldThrow);
}
Butterfly* butterfly = thisObject->butterfly();
if (propertyName >= butterfly->vectorLength())
break;
butterfly->contiguousDouble().at(thisObject, propertyName) = valueAsDouble;
if (propertyName >= butterfly->publicLength())
butterfly->setPublicLength(propertyName + 1);
return true;
}
case NonArrayWithArrayStorage:
case ArrayWithArrayStorage: {
ArrayStorage* storage = thisObject->m_butterfly->arrayStorage();
if (propertyName >= storage->vectorLength())
break;
WriteBarrier<Unknown>& valueSlot = storage->m_vector[propertyName];
unsigned length = storage->length();
// Update length & m_numValuesInVector as necessary.
if (propertyName >= length) {
length = propertyName + 1;
storage->setLength(length);
++storage->m_numValuesInVector;
} else if (!valueSlot)
++storage->m_numValuesInVector;
valueSlot.set(vm, thisObject, value);
return true;
}
case NonArrayWithSlowPutArrayStorage:
case ArrayWithSlowPutArrayStorage: {
ArrayStorage* storage = thisObject->m_butterfly->arrayStorage();
if (propertyName >= storage->vectorLength())
break;
WriteBarrier<Unknown>& valueSlot = storage->m_vector[propertyName];
unsigned length = storage->length();
auto scope = DECLARE_THROW_SCOPE(vm);
// Update length & m_numValuesInVector as necessary.
if (propertyName >= length) {
bool putResult = false;
bool result = thisObject->attemptToInterceptPutByIndexOnHole(globalObject, propertyName, value, shouldThrow, putResult);
RETURN_IF_EXCEPTION(scope, false);
if (result)
return putResult;
length = propertyName + 1;
storage->setLength(length);
++storage->m_numValuesInVector;
} else if (!valueSlot) {
bool putResult = false;
bool result = thisObject->attemptToInterceptPutByIndexOnHole(globalObject, propertyName, value, shouldThrow, putResult);
RETURN_IF_EXCEPTION(scope, false);
if (result)
return putResult;
++storage->m_numValuesInVector;
}
valueSlot.set(vm, thisObject, value);
return true;
}
default:
RELEASE_ASSERT_NOT_REACHED();
}
return thisObject->putByIndexBeyondVectorLength(globalObject, propertyName, value, shouldThrow);
}
ArrayStorage* JSObject::enterDictionaryIndexingModeWhenArrayStorageAlreadyExists(VM& vm, ArrayStorage* storage)
{
SparseArrayValueMap* map = storage->m_sparseMap.get();
if (!map)
map = allocateSparseIndexMap(vm);
if (map->sparseMode())
return storage;
map->setSparseMode();
unsigned usedVectorLength = std::min(storage->length(), storage->vectorLength());
for (unsigned i = 0; i < usedVectorLength; ++i) {
JSValue value = storage->m_vector[i].get();
// This will always be a new entry in the map, so no need to check we can write,
// and attributes are default so no need to set them.
if (value)
map->add(this, i).iterator->value.forceSet(vm, map, value, 0);
}
DeferGC deferGC(vm);
Butterfly* newButterfly = storage->butterfly()->resizeArray(vm, this, structure(), 0, ArrayStorage::sizeFor(0));
RELEASE_ASSERT(newButterfly);
newButterfly->arrayStorage()->m_indexBias = 0;
newButterfly->arrayStorage()->setVectorLength(0);
newButterfly->arrayStorage()->m_sparseMap.set(vm, this, map);
setButterfly(vm, newButterfly);
return newButterfly->arrayStorage();
}
void JSObject::enterDictionaryIndexingMode(VM& vm)
{
switch (indexingType()) {
case ALL_BLANK_INDEXING_TYPES:
case ALL_UNDECIDED_INDEXING_TYPES:
case ALL_INT32_INDEXING_TYPES:
case ALL_DOUBLE_INDEXING_TYPES:
case ALL_CONTIGUOUS_INDEXING_TYPES:
// NOTE: this is horribly inefficient, as it will perform two conversions. We could optimize
// this case if we ever cared. Note that ensureArrayStorage() can return null if the object
// doesn't support traditional indexed properties. At the time of writing, this just affects
// typed arrays.
if (ArrayStorage* storage = ensureArrayStorageSlow(vm))
enterDictionaryIndexingModeWhenArrayStorageAlreadyExists(vm, storage);
break;
case ALL_ARRAY_STORAGE_INDEXING_TYPES:
enterDictionaryIndexingModeWhenArrayStorageAlreadyExists(vm, m_butterfly->arrayStorage());
break;
default:
break;
}
}
void JSObject::notifyPresenceOfIndexedAccessors(VM& vm)
{
if (UNLIKELY(isGlobalObject())) {
jsCast<JSGlobalObject*>(this)->globalThis()->notifyPresenceOfIndexedAccessors(vm);
return;
}
if (mayInterceptIndexedAccesses())
return;
{
Structure* oldStructure = structure();
DeferredStructureTransitionWatchpointFire deferred(vm, oldStructure);
setStructure(vm, Structure::nonPropertyTransition(vm, oldStructure, TransitionKind::AddIndexedAccessors, &deferred));
}
if (!mayBePrototype())
return;
globalObject()->haveABadTime(vm);
}
Butterfly* JSObject::createInitialIndexedStorage(VM& vm, unsigned length)
{
ASSERT(length <= MAX_STORAGE_VECTOR_LENGTH);
IndexingType oldType = indexingType();
ASSERT_UNUSED(oldType, !hasIndexedProperties(oldType));
ASSERT(!needsSlowPutIndexing());
ASSERT(!indexingShouldBeSparse());
Structure* structure = this->structure();
unsigned propertyCapacity = structure->outOfLineCapacity();
unsigned vectorLength = Butterfly::optimalContiguousVectorLength(propertyCapacity, length);
Butterfly* newButterfly = Butterfly::createOrGrowArrayRight(
butterfly(), vm, this, structure, propertyCapacity, false, 0,
sizeof(EncodedJSValue) * vectorLength);
newButterfly->setPublicLength(length);
newButterfly->setVectorLength(vectorLength);
return newButterfly;
}
Butterfly* JSObject::createInitialUndecided(VM& vm, unsigned length)
{
DeferGC deferGC(vm);
Butterfly* newButterfly = createInitialIndexedStorage(vm, length);
StructureID oldStructureID = this->structureID();
Structure* oldStructure = oldStructureID.decode();
{
DeferredStructureTransitionWatchpointFire deferred(vm, oldStructure);
Structure* newStructure = Structure::nonPropertyTransition(vm, oldStructure, TransitionKind::AllocateUndecided, &deferred);
nukeStructureAndSetButterfly(vm, oldStructureID, newButterfly);
setStructure(vm, newStructure);
}
return newButterfly;
}
ContiguousJSValues JSObject::createInitialInt32(VM& vm, unsigned length)
{
DeferGC deferGC(vm);
Butterfly* newButterfly = createInitialIndexedStorage(vm, length);
for (unsigned i = newButterfly->vectorLength(); i--;)
newButterfly->contiguous().at(this, i).setWithoutWriteBarrier(JSValue());
StructureID oldStructureID = this->structureID();
Structure* oldStructure = oldStructureID.decode();
{
DeferredStructureTransitionWatchpointFire deferred(vm, oldStructure);
Structure* newStructure = Structure::nonPropertyTransition(vm, oldStructure, TransitionKind::AllocateInt32, &deferred);
nukeStructureAndSetButterfly(vm, oldStructureID, newButterfly);
setStructure(vm, newStructure);
}
return newButterfly->contiguousInt32();
}
ContiguousDoubles JSObject::createInitialDouble(VM& vm, unsigned length)
{
DeferGC deferGC(vm);
Butterfly* newButterfly = createInitialIndexedStorage(vm, length);
for (unsigned i = newButterfly->vectorLength(); i--;)
newButterfly->contiguousDouble().at(this, i) = PNaN;
StructureID oldStructureID = this->structureID();
Structure* oldStructure = oldStructureID.decode();
{
DeferredStructureTransitionWatchpointFire deferred(vm, oldStructure);
Structure* newStructure = Structure::nonPropertyTransition(vm, oldStructure, TransitionKind::AllocateDouble, &deferred);
nukeStructureAndSetButterfly(vm, oldStructureID, newButterfly);
setStructure(vm, newStructure);
}
return newButterfly->contiguousDouble();
}
ContiguousJSValues JSObject::createInitialContiguous(VM& vm, unsigned length)
{
DeferGC deferGC(vm);
Butterfly* newButterfly = createInitialIndexedStorage(vm, length);
for (unsigned i = newButterfly->vectorLength(); i--;)
newButterfly->contiguous().at(this, i).setWithoutWriteBarrier(JSValue());
StructureID oldStructureID = this->structureID();
Structure* oldStructure = oldStructureID.decode();
{
DeferredStructureTransitionWatchpointFire deferred(vm, oldStructure);
Structure* newStructure = Structure::nonPropertyTransition(vm, oldStructure, TransitionKind::AllocateContiguous, &deferred);
nukeStructureAndSetButterfly(vm, oldStructureID, newButterfly);
setStructure(vm, newStructure);
}
return newButterfly->contiguous();
}
static Butterfly* createArrayStorageButterflyImpl(VM& vm, JSObject* intendedOwner, Structure* structure, unsigned length, unsigned vectorLength, Butterfly* oldButterfly, AllocationFailureMode mode)
{
Butterfly* newButterfly = Butterfly::createOrGrowArrayRight(
oldButterfly, vm, intendedOwner, structure, structure->outOfLineCapacity(), false, 0,
ArrayStorage::sizeFor(vectorLength));
if (UNLIKELY(!newButterfly)) {
if (mode == AllocationFailureMode::Assert)
RELEASE_ASSERT(newButterfly, length, vectorLength, oldButterfly);
else {
ASSERT(mode == AllocationFailureMode::ReturnNull);
return nullptr;
}
}
ArrayStorage* result = newButterfly->arrayStorage();
result->setLength(length);
result->setVectorLength(vectorLength);
result->m_sparseMap.clear();
result->m_numValuesInVector = 0;
result->m_indexBias = 0;
for (size_t i = vectorLength; i--;)
result->m_vector[i].setWithoutWriteBarrier(JSValue());
return newButterfly;
}
Butterfly* JSObject::createArrayStorageButterfly(VM& vm, JSObject* intendedOwner, Structure* structure, unsigned length, unsigned vectorLength, Butterfly* oldButterfly)
{
return createArrayStorageButterflyImpl(vm, intendedOwner, structure, length, vectorLength, oldButterfly, AllocationFailureMode::Assert);
}
Butterfly* JSObject::tryCreateArrayStorageButterfly(VM& vm, JSObject* intendedOwner, Structure* structure, unsigned length, unsigned vectorLength, Butterfly* oldButterfly)
{
return createArrayStorageButterflyImpl(vm, intendedOwner, structure, length, vectorLength, oldButterfly, AllocationFailureMode::ReturnNull);
}
ArrayStorage* JSObject::createArrayStorage(VM& vm, unsigned length, unsigned vectorLength)
{
DeferGC deferGC(vm);
StructureID oldStructureID = this->structureID();
Structure* oldStructure = oldStructureID.decode();
IndexingType oldType = indexingType();
ASSERT_UNUSED(oldType, !hasIndexedProperties(oldType));
Butterfly* newButterfly = createArrayStorageButterfly(vm, this, oldStructure, length, vectorLength, butterfly());
ArrayStorage* result = newButterfly->arrayStorage();
{
DeferredStructureTransitionWatchpointFire deferred(vm, oldStructure);
Structure* newStructure = Structure::nonPropertyTransition(vm, oldStructure, suggestedArrayStorageTransition(), &deferred);
nukeStructureAndSetButterfly(vm, oldStructureID, newButterfly);
setStructure(vm, newStructure);
}
return result;
}
ArrayStorage* JSObject::createInitialArrayStorage(VM& vm)
{
return createArrayStorage(
vm, 0, ArrayStorage::optimalVectorLength(0, structure()->outOfLineCapacity(), 0));
}
ContiguousJSValues JSObject::convertUndecidedToInt32(VM& vm)
{
ASSERT(hasUndecided(indexingType()));
Butterfly* butterfly = this->butterfly();
for (unsigned i = butterfly->vectorLength(); i--;)
butterfly->contiguous().at(this, i).setWithoutWriteBarrier(JSValue());
{
Structure* oldStructure = structure();
DeferredStructureTransitionWatchpointFire deferred(vm, oldStructure);
setStructure(vm, Structure::nonPropertyTransition(vm, oldStructure, TransitionKind::AllocateInt32, &deferred));
}
return m_butterfly->contiguousInt32();
}
ContiguousDoubles JSObject::convertUndecidedToDouble(VM& vm)
{
ASSERT(Options::allowDoubleShape());
ASSERT(hasUndecided(indexingType()));
Butterfly* butterfly = m_butterfly.get();
for (unsigned i = butterfly->vectorLength(); i--;)
butterfly->contiguousDouble().at(this, i) = PNaN;
{
Structure* oldStructure = structure();
DeferredStructureTransitionWatchpointFire deferred(vm, oldStructure);
setStructure(vm, Structure::nonPropertyTransition(vm, oldStructure, TransitionKind::AllocateDouble, &deferred));
}
return m_butterfly->contiguousDouble();
}
ContiguousJSValues JSObject::convertUndecidedToContiguous(VM& vm)
{
ASSERT(hasUndecided(indexingType()));
Butterfly* butterfly = m_butterfly.get();
for (unsigned i = butterfly->vectorLength(); i--;)
butterfly->contiguous().at(this, i).setWithoutWriteBarrier(JSValue());
WTF::storeStoreFence();
{
Structure* oldStructure = structure();
DeferredStructureTransitionWatchpointFire deferred(vm, oldStructure);
setStructure(vm, Structure::nonPropertyTransition(vm, oldStructure, TransitionKind::AllocateContiguous, &deferred));
}
return m_butterfly->contiguous();
}
ArrayStorage* JSObject::constructConvertedArrayStorageWithoutCopyingElements(VM& vm, unsigned neededLength)
{
Structure* structure = this->structure();
unsigned publicLength = m_butterfly->publicLength();
unsigned propertyCapacity = structure->outOfLineCapacity();
Butterfly* newButterfly = Butterfly::createUninitialized(vm, this, 0, propertyCapacity, true, ArrayStorage::sizeFor(neededLength));
// memcpy is fine since newButterfly is not tied to any object yet.
memcpy(
static_cast<JSValue*>(newButterfly->base(0, propertyCapacity)),
static_cast<JSValue*>(m_butterfly->base(0, propertyCapacity)),
propertyCapacity * sizeof(EncodedJSValue));
ArrayStorage* newStorage = newButterfly->arrayStorage();
newStorage->setVectorLength(neededLength);
newStorage->setLength(publicLength);
newStorage->m_sparseMap.clear();
newStorage->m_indexBias = 0;
newStorage->m_numValuesInVector = 0;
return newStorage;
}
ArrayStorage* JSObject::convertUndecidedToArrayStorage(VM& vm, TransitionKind transition)
{
DeferGC deferGC(vm);
ASSERT(hasUndecided(indexingType()));
unsigned vectorLength = m_butterfly->vectorLength();
ArrayStorage* storage = constructConvertedArrayStorageWithoutCopyingElements(vm, vectorLength);
for (unsigned i = vectorLength; i--;)
storage->m_vector[i].setWithoutWriteBarrier(JSValue());
StructureID oldStructureID = this->structureID();
Structure* oldStructure = oldStructureID.decode();
{
DeferredStructureTransitionWatchpointFire deferred(vm, oldStructure);
Structure* newStructure = Structure::nonPropertyTransition(vm, oldStructure, transition, &deferred);
nukeStructureAndSetButterfly(vm, oldStructureID, storage->butterfly());
setStructure(vm, newStructure);
}
return storage;
}
ArrayStorage* JSObject::convertUndecidedToArrayStorage(VM& vm)
{
return convertUndecidedToArrayStorage(vm, suggestedArrayStorageTransition());
}
ContiguousDoubles JSObject::convertInt32ToDouble(VM& vm)
{
ASSERT(hasInt32(indexingType()));
ASSERT(!isCopyOnWrite(indexingMode()));
Butterfly* butterfly = m_butterfly.get();
for (unsigned i = butterfly->vectorLength(); i--;) {
WriteBarrier<Unknown>* current = &butterfly->contiguous().atUnsafe(i);
double* currentAsDouble = std::bit_cast<double*>(current);
JSValue v = current->get();
// NOTE: Since this may be used during initialization, v could be garbage. If it's garbage,
// that means it will be overwritten later.
if (!v.isInt32()) {
*currentAsDouble = PNaN;
continue;
}
*currentAsDouble = v.asInt32();
}
{
Structure* oldStructure = structure();
DeferredStructureTransitionWatchpointFire deferred(vm, oldStructure);
setStructure(vm, Structure::nonPropertyTransition(vm, oldStructure, TransitionKind::AllocateDouble, &deferred));
}
return m_butterfly->contiguousDouble();
}
ContiguousJSValues JSObject::convertInt32ToContiguous(VM& vm)
{
ASSERT(hasInt32(indexingType()));
{
Structure* oldStructure = structure();
DeferredStructureTransitionWatchpointFire deferred(vm, oldStructure);
setStructure(vm, Structure::nonPropertyTransition(vm, oldStructure, TransitionKind::AllocateContiguous, &deferred));
}
return m_butterfly->contiguous();
}
ArrayStorage* JSObject::convertInt32ToArrayStorage(VM& vm, TransitionKind transition)
{
DeferGC deferGC(vm);
ASSERT(hasInt32(indexingType()));
unsigned vectorLength = m_butterfly->vectorLength();
ArrayStorage* newStorage = constructConvertedArrayStorageWithoutCopyingElements(vm, vectorLength);
Butterfly* butterfly = m_butterfly.get();
for (unsigned i = 0; i < vectorLength; i++) {
JSValue v = butterfly->contiguous().at(this, i).get();
newStorage->m_vector[i].setWithoutWriteBarrier(v);
if (v)
newStorage->m_numValuesInVector++;
}
StructureID oldStructureID = this->structureID();
Structure* oldStructure = oldStructureID.decode();
{
DeferredStructureTransitionWatchpointFire deferred(vm, oldStructure);
Structure* newStructure = Structure::nonPropertyTransition(vm, oldStructure, transition, &deferred);
nukeStructureAndSetButterfly(vm, oldStructureID, newStorage->butterfly());
setStructure(vm, newStructure);
}
return newStorage;
}
ArrayStorage* JSObject::convertInt32ToArrayStorage(VM& vm)
{
return convertInt32ToArrayStorage(vm, suggestedArrayStorageTransition());
}
ContiguousJSValues JSObject::convertDoubleToContiguous(VM& vm)
{
ASSERT(hasDouble(indexingType()));
ASSERT(!isCopyOnWrite(indexingMode()));
Butterfly* butterfly = m_butterfly.get();
for (unsigned i = butterfly->vectorLength(); i--;) {
double* current = &butterfly->contiguousDouble().atUnsafe(i);
WriteBarrier<Unknown>* currentAsValue = std::bit_cast<WriteBarrier<Unknown>*>(current);
double value = *current;
if (value != value) {
currentAsValue->clear();
continue;
}
JSValue v = JSValue(JSValue::EncodeAsDouble, value);
currentAsValue->setWithoutWriteBarrier(v);
}
WTF::storeStoreFence();
{
Structure* oldStructure = structure();
DeferredStructureTransitionWatchpointFire deferred(vm, oldStructure);
setStructure(vm, Structure::nonPropertyTransition(vm, oldStructure, TransitionKind::AllocateContiguous, &deferred));
}
return m_butterfly->contiguous();
}
ArrayStorage* JSObject::convertDoubleToArrayStorage(VM& vm, TransitionKind transition)
{
DeferGC deferGC(vm);
ASSERT(hasDouble(indexingType()));
unsigned vectorLength = m_butterfly->vectorLength();
ArrayStorage* newStorage = constructConvertedArrayStorageWithoutCopyingElements(vm, vectorLength);
Butterfly* butterfly = m_butterfly.get();
for (unsigned i = 0; i < vectorLength; i++) {
double value = butterfly->contiguousDouble().at(this, i);
if (value != value) {
newStorage->m_vector[i].clear();
continue;
}
newStorage->m_vector[i].setWithoutWriteBarrier(JSValue(JSValue::EncodeAsDouble, value));
newStorage->m_numValuesInVector++;
}
StructureID oldStructureID = this->structureID();
Structure* oldStructure = oldStructureID.decode();
{
DeferredStructureTransitionWatchpointFire deferred(vm, oldStructure);
Structure* newStructure = Structure::nonPropertyTransition(vm, oldStructure, transition, &deferred);
nukeStructureAndSetButterfly(vm, oldStructureID, newStorage->butterfly());
setStructure(vm, newStructure);
}
return newStorage;
}
ArrayStorage* JSObject::convertDoubleToArrayStorage(VM& vm)
{
return convertDoubleToArrayStorage(vm, suggestedArrayStorageTransition());
}
ArrayStorage* JSObject::convertContiguousToArrayStorage(VM& vm, TransitionKind transition)
{
DeferGC deferGC(vm);
ASSERT(hasContiguous(indexingType()));
unsigned vectorLength = m_butterfly->vectorLength();
ArrayStorage* newStorage = constructConvertedArrayStorageWithoutCopyingElements(vm, vectorLength);
Butterfly* butterfly = m_butterfly.get();
for (unsigned i = 0; i < vectorLength; i++) {
JSValue v = butterfly->contiguous().at(this, i).get();
newStorage->m_vector[i].setWithoutWriteBarrier(v);
if (v)
newStorage->m_numValuesInVector++;
}
// While we modify the butterfly of Contiguous Array, we do not take any cellLock here. This is because
// (1) the old butterfly is not changed and (2) new butterfly is not changed after it is exposed to
// the collector.
// The mutator performs the following operations are sequentially executed by using storeStoreFence.
//
// CreateNewButterfly NukeStructure ChangeButterfly PutNewStructure
//
// Meanwhile the collector performs the following steps sequentially:
//
// ReadStructureEarly ReadButterfly ReadStructureLate
//
// We list up all the patterns by writing a tiny script, and ensure all the cases are categorized into BEFORE, AFTER, and IGNORE.
//
// CreateNewButterfly NukeStructure ChangeButterfly PutNewStructure ReadStructureEarly ReadButterfly ReadStructureLate: AFTER, trivially
// CreateNewButterfly NukeStructure ChangeButterfly ReadStructureEarly PutNewStructure ReadButterfly ReadStructureLate: IGNORE, because nuked structure read early
// CreateNewButterfly NukeStructure ChangeButterfly ReadStructureEarly ReadButterfly PutNewStructure ReadStructureLate: IGNORE, because nuked structure read early
// CreateNewButterfly NukeStructure ChangeButterfly ReadStructureEarly ReadButterfly ReadStructureLate PutNewStructure: IGNORE, because nuked structure read early
// CreateNewButterfly NukeStructure ReadStructureEarly ChangeButterfly PutNewStructure ReadButterfly ReadStructureLate: IGNORE, because nuked structure read early
// CreateNewButterfly NukeStructure ReadStructureEarly ChangeButterfly ReadButterfly PutNewStructure ReadStructureLate: IGNORE, because nuked structure read early
// CreateNewButterfly NukeStructure ReadStructureEarly ChangeButterfly ReadButterfly ReadStructureLate PutNewStructure: IGNORE, because nuked structure read early
// CreateNewButterfly NukeStructure ReadStructureEarly ReadButterfly ChangeButterfly PutNewStructure ReadStructureLate: IGNORE, because nuked structure read early
// CreateNewButterfly NukeStructure ReadStructureEarly ReadButterfly ChangeButterfly ReadStructureLate PutNewStructure: IGNORE, because nuked structure read early
// CreateNewButterfly NukeStructure ReadStructureEarly ReadButterfly ReadStructureLate ChangeButterfly PutNewStructure: IGNORE, because nuked structure read early
// CreateNewButterfly ReadStructureEarly NukeStructure ChangeButterfly PutNewStructure ReadButterfly ReadStructureLate: IGNORE, because early and late structures don't match
// CreateNewButterfly ReadStructureEarly NukeStructure ChangeButterfly ReadButterfly PutNewStructure ReadStructureLate: IGNORE, because early and late structures don't match
// CreateNewButterfly ReadStructureEarly NukeStructure ChangeButterfly ReadButterfly ReadStructureLate PutNewStructure: IGNORE, because nuked structure read late
// CreateNewButterfly ReadStructureEarly NukeStructure ReadButterfly ChangeButterfly PutNewStructure ReadStructureLate: IGNORE, because early and late structures don't match
// CreateNewButterfly ReadStructureEarly NukeStructure ReadButterfly ChangeButterfly ReadStructureLate PutNewStructure: IGNORE, because nuked structure read late
// CreateNewButterfly ReadStructureEarly NukeStructure ReadButterfly ReadStructureLate ChangeButterfly PutNewStructure: IGNORE, because nuked structure read late
// CreateNewButterfly ReadStructureEarly ReadButterfly NukeStructure ChangeButterfly PutNewStructure ReadStructureLate: IGNORE, because early and late structures don't match
// CreateNewButterfly ReadStructureEarly ReadButterfly NukeStructure ChangeButterfly ReadStructureLate PutNewStructure: IGNORE, because nuked structure read late
// CreateNewButterfly ReadStructureEarly ReadButterfly NukeStructure ReadStructureLate ChangeButterfly PutNewStructure: IGNORE, because nuked structure read late
// CreateNewButterfly ReadStructureEarly ReadButterfly ReadStructureLate NukeStructure ChangeButterfly PutNewStructure: BEFORE, trivially.
// ReadStructureEarly CreateNewButterfly NukeStructure ChangeButterfly PutNewStructure ReadButterfly ReadStructureLate: IGNORE, because early and late structures don't match
// ReadStructureEarly CreateNewButterfly NukeStructure ChangeButterfly ReadButterfly PutNewStructure ReadStructureLate: IGNORE, because early and late structures don't match
// ReadStructureEarly CreateNewButterfly NukeStructure ChangeButterfly ReadButterfly ReadStructureLate PutNewStructure: IGNORE, because nuked structure read late
// ReadStructureEarly CreateNewButterfly NukeStructure ReadButterfly ChangeButterfly PutNewStructure ReadStructureLate: IGNORE, because early and late structures don't match
// ReadStructureEarly CreateNewButterfly NukeStructure ReadButterfly ChangeButterfly ReadStructureLate PutNewStructure: IGNORE, because nuked structure read late
// ReadStructureEarly CreateNewButterfly NukeStructure ReadButterfly ReadStructureLate ChangeButterfly PutNewStructure: IGNORE, because nuked structure read late
// ReadStructureEarly CreateNewButterfly ReadButterfly NukeStructure ChangeButterfly PutNewStructure ReadStructureLate: IGNORE, because early and late structures don't match
// ReadStructureEarly CreateNewButterfly ReadButterfly NukeStructure ChangeButterfly ReadStructureLate PutNewStructure: IGNORE, because nuked structure read late
// ReadStructureEarly CreateNewButterfly ReadButterfly NukeStructure ReadStructureLate ChangeButterfly PutNewStructure: IGNORE, because nuked structure read late
// ReadStructureEarly CreateNewButterfly ReadButterfly ReadStructureLate NukeStructure ChangeButterfly PutNewStructure: BEFORE, CreateNewButterfly is not visible to collector.
// ReadStructureEarly ReadButterfly CreateNewButterfly NukeStructure ChangeButterfly PutNewStructure ReadStructureLate: IGNORE, because early and late structures don't match
// ReadStructureEarly ReadButterfly CreateNewButterfly NukeStructure ChangeButterfly ReadStructureLate PutNewStructure: IGNORE, because nuked structure read late
// ReadStructureEarly ReadButterfly CreateNewButterfly NukeStructure ReadStructureLate ChangeButterfly PutNewStructure: IGNORE, because nuked structure read late
// ReadStructureEarly ReadButterfly CreateNewButterfly ReadStructureLate NukeStructure ChangeButterfly PutNewStructure: BEFORE, CreateNewButterfly is not visible to collector.
// ReadStructureEarly ReadButterfly ReadStructureLate CreateNewButterfly NukeStructure ChangeButterfly PutNewStructure: BEFORE, trivially.
ASSERT(newStorage->butterfly() != butterfly);
StructureID oldStructureID = this->structureID();
Structure* oldStructure = oldStructureID.decode();
{
DeferredStructureTransitionWatchpointFire deferred(vm, oldStructure);
Structure* newStructure = Structure::nonPropertyTransition(vm, oldStructure, transition, &deferred);
// Ensure new Butterfly initialization is correctly done before exposing it to the concurrent threads.
if (isX86() || vm.heap.mutatorShouldBeFenced())
WTF::storeStoreFence();
nukeStructureAndSetButterfly(vm, oldStructureID, newStorage->butterfly());
setStructure(vm, newStructure);
}
return newStorage;
}
ArrayStorage* JSObject::convertContiguousToArrayStorage(VM& vm)
{
return convertContiguousToArrayStorage(vm, suggestedArrayStorageTransition());
}
void JSObject::convertToIndexingTypeIfNeeded(VM& vm, IndexingType nextType)
{
IndexingType currentType = indexingType();
if (currentType == nextType)
return;
switch (currentType) {
case ArrayWithUndecided: {
switch (nextType) {
case ArrayWithInt32:
convertUndecidedToInt32(vm);
break;
case ArrayWithDouble:
convertUndecidedToDouble(vm);
break;
case ArrayWithContiguous:
convertUndecidedToContiguous(vm);
break;
case ArrayWithArrayStorage:
convertUndecidedToArrayStorage(vm);
break;
}
break;
}
case ArrayWithInt32: {
switch (nextType) {
case ArrayWithDouble:
convertInt32ToDouble(vm);
break;
case ArrayWithContiguous:
convertInt32ToContiguous(vm);
break;
case ArrayWithArrayStorage:
convertInt32ToArrayStorage(vm);
break;
}
break;
}
case ArrayWithDouble: {
switch (nextType) {
case ArrayWithContiguous:
convertDoubleToContiguous(vm);
break;
case ArrayWithArrayStorage:
convertDoubleToArrayStorage(vm);
break;
}
break;
}
case ArrayWithContiguous: {
switch (nextType) {
case ArrayWithArrayStorage:
convertContiguousToArrayStorage(vm);
break;
}
break;
}
}
}
void JSObject::convertUndecidedForValue(VM& vm, JSValue value)
{
IndexingType type = indexingTypeForValue(value);
if (type == Int32Shape) {
convertUndecidedToInt32(vm);
return;
}
if (type == DoubleShape) {
ASSERT(Options::allowDoubleShape());
convertUndecidedToDouble(vm);
return;
}
ASSERT(type == ContiguousShape);
convertUndecidedToContiguous(vm);
}
void JSObject::createInitialForValueAndSet(VM& vm, unsigned index, JSValue value)
{
if (value.isInt32()) {
createInitialInt32(vm, index + 1).at(this, index).set(vm, this, value);
return;
}
if (value.isDouble() && Options::allowDoubleShape()) {
double doubleValue = value.asNumber();
if (doubleValue == doubleValue) {
createInitialDouble(vm, index + 1).at(this, index) = doubleValue;
return;
}
}
createInitialContiguous(vm, index + 1).at(this, index).set(vm, this, value);
}
void JSObject::convertInt32ForValue(VM& vm, JSValue value)
{
ASSERT(!value.isInt32());
if (value.isDouble() && !std::isnan(value.asDouble()) && Options::allowDoubleShape()) {
convertInt32ToDouble(vm);
return;
}
convertInt32ToContiguous(vm);
}
void JSObject::convertFromCopyOnWrite(VM& vm)
{
ASSERT(isCopyOnWrite(indexingMode()));
ASSERT(structure()->indexingMode() == indexingMode());
const bool hasIndexingHeader = true;
Butterfly* oldButterfly = butterfly();
size_t propertyCapacity = 0;
unsigned newVectorLength = Butterfly::optimalContiguousVectorLength(propertyCapacity, std::min(oldButterfly->vectorLength() * 2, MAX_STORAGE_VECTOR_LENGTH));
Butterfly* newButterfly = Butterfly::createUninitialized(vm, this, 0, propertyCapacity, hasIndexingHeader, newVectorLength * sizeof(JSValue));
// memcpy is fine since newButterfly is not tied to any object yet.
memcpy(newButterfly->propertyStorage(), oldButterfly->propertyStorage(), oldButterfly->vectorLength() * sizeof(JSValue) + sizeof(IndexingHeader));
WTF::storeStoreFence();
TransitionKind transition = ([&] () {
switch (indexingType()) {
case ArrayWithInt32:
return TransitionKind::AllocateInt32;
case ArrayWithDouble:
return TransitionKind::AllocateDouble;
case ArrayWithContiguous:
return TransitionKind::AllocateContiguous;
default:
RELEASE_ASSERT_NOT_REACHED();
return TransitionKind::AllocateContiguous;
}
})();
StructureID oldStructureID = structureID();
Structure* oldStructure = oldStructureID.decode();
{
DeferredStructureTransitionWatchpointFire deferred(vm, oldStructure);
Structure* newStructure = Structure::nonPropertyTransition(vm, oldStructure, transition, &deferred);
nukeStructureAndSetButterfly(vm, oldStructureID, newButterfly);
setStructure(vm, newStructure);
}
}
void JSObject::setIndexQuicklyToUndecided(VM& vm, unsigned index, JSValue value)
{
ASSERT(index < m_butterfly->publicLength());
ASSERT(index < m_butterfly->vectorLength());
convertUndecidedForValue(vm, value);
setIndexQuickly(vm, index, value);
}
void JSObject::convertInt32ToDoubleOrContiguousWhilePerformingSetIndex(VM& vm, unsigned index, JSValue value)
{
ASSERT(!value.isInt32());
convertInt32ForValue(vm, value);
setIndexQuickly(vm, index, value);
}
void JSObject::convertDoubleToContiguousWhilePerformingSetIndex(VM& vm, unsigned index, JSValue value)
{
ASSERT(!value.isNumber() || value.asNumber() != value.asNumber());
convertDoubleToContiguous(vm);
setIndexQuickly(vm, index, value);
}
ContiguousJSValues JSObject::tryMakeWritableInt32Slow(VM& vm)
{
ASSERT(inherits(info()));
if (isCopyOnWrite(indexingMode())) {
if (leastUpperBoundOfIndexingTypes(indexingType() & IndexingShapeMask, Int32Shape) == Int32Shape) {
ASSERT(hasInt32(indexingMode()));
convertFromCopyOnWrite(vm);
return butterfly()->contiguousInt32();
}
return ContiguousJSValues();
}
if (structure()->hijacksIndexingHeader())
return ContiguousJSValues();
switch (indexingType()) {
case ALL_BLANK_INDEXING_TYPES:
if (UNLIKELY(indexingShouldBeSparse() || needsSlowPutIndexing()))
return ContiguousJSValues();
return createInitialInt32(vm, 0);
case ALL_UNDECIDED_INDEXING_TYPES:
return convertUndecidedToInt32(vm);
case ALL_DOUBLE_INDEXING_TYPES:
case ALL_CONTIGUOUS_INDEXING_TYPES:
case ALL_ARRAY_STORAGE_INDEXING_TYPES:
return ContiguousJSValues();
default:
CRASH();
return ContiguousJSValues();
}
}
ContiguousDoubles JSObject::tryMakeWritableDoubleSlow(VM& vm)
{
ASSERT(Options::allowDoubleShape());
ASSERT(inherits(info()));
if (isCopyOnWrite(indexingMode())) {
if (leastUpperBoundOfIndexingTypes(indexingType() & IndexingShapeMask, DoubleShape) == DoubleShape) {
convertFromCopyOnWrite(vm);
if (hasDouble(indexingMode()))
return butterfly()->contiguousDouble();
ASSERT(hasInt32(indexingMode()));
} else
return ContiguousDoubles();
}
if (structure()->hijacksIndexingHeader())
return ContiguousDoubles();
switch (indexingType()) {
case ALL_BLANK_INDEXING_TYPES:
if (UNLIKELY(indexingShouldBeSparse() || needsSlowPutIndexing()))
return ContiguousDoubles();
return createInitialDouble(vm, 0);
case ALL_UNDECIDED_INDEXING_TYPES:
return convertUndecidedToDouble(vm);
case ALL_INT32_INDEXING_TYPES:
return convertInt32ToDouble(vm);
case ALL_CONTIGUOUS_INDEXING_TYPES:
case ALL_ARRAY_STORAGE_INDEXING_TYPES:
return ContiguousDoubles();
default:
CRASH();
return ContiguousDoubles();
}
}
ContiguousJSValues JSObject::tryMakeWritableContiguousSlow(VM& vm)
{
ASSERT(inherits(info()));
if (isCopyOnWrite(indexingMode())) {
if (leastUpperBoundOfIndexingTypes(indexingType() & IndexingShapeMask, ContiguousShape) == ContiguousShape) {
convertFromCopyOnWrite(vm);
if (hasContiguous(indexingMode()))
return butterfly()->contiguous();
ASSERT(hasInt32(indexingMode()) || hasDouble(indexingMode()));
} else
return ContiguousJSValues();
}
if (structure()->hijacksIndexingHeader())
return ContiguousJSValues();
switch (indexingType()) {
case ALL_BLANK_INDEXING_TYPES:
if (UNLIKELY(indexingShouldBeSparse() || needsSlowPutIndexing()))
return ContiguousJSValues();
return createInitialContiguous(vm, 0);
case ALL_UNDECIDED_INDEXING_TYPES:
return convertUndecidedToContiguous(vm);
case ALL_INT32_INDEXING_TYPES:
return convertInt32ToContiguous(vm);
case ALL_DOUBLE_INDEXING_TYPES:
return convertDoubleToContiguous(vm);
case ALL_ARRAY_STORAGE_INDEXING_TYPES:
return ContiguousJSValues();
default:
CRASH();
return ContiguousJSValues();
}
}
ArrayStorage* JSObject::ensureArrayStorageSlow(VM& vm)
{
ASSERT(inherits(info()));
if (structure()->hijacksIndexingHeader())
return nullptr;
ensureWritable(vm);
switch (indexingType()) {
case ALL_BLANK_INDEXING_TYPES:
if (UNLIKELY(indexingShouldBeSparse()))
return ensureArrayStorageExistsAndEnterDictionaryIndexingMode(vm);
return createInitialArrayStorage(vm);
case ALL_UNDECIDED_INDEXING_TYPES:
ASSERT(!indexingShouldBeSparse());
ASSERT(!needsSlowPutIndexing());
return convertUndecidedToArrayStorage(vm);
case ALL_INT32_INDEXING_TYPES:
ASSERT(!indexingShouldBeSparse());
ASSERT(!needsSlowPutIndexing());
return convertInt32ToArrayStorage(vm);
case ALL_DOUBLE_INDEXING_TYPES:
ASSERT(!indexingShouldBeSparse());
ASSERT(!needsSlowPutIndexing());
return convertDoubleToArrayStorage(vm);
case ALL_CONTIGUOUS_INDEXING_TYPES:
ASSERT(!indexingShouldBeSparse());
ASSERT(!needsSlowPutIndexing());
return convertContiguousToArrayStorage(vm);
default:
RELEASE_ASSERT_NOT_REACHED();
return nullptr;
}
}
ArrayStorage* JSObject::ensureArrayStorageExistsAndEnterDictionaryIndexingMode(VM& vm)
{
ensureWritable(vm);
switch (indexingType()) {
case ALL_BLANK_INDEXING_TYPES: {
createArrayStorage(vm, 0, 0);
SparseArrayValueMap* map = allocateSparseIndexMap(vm);
map->setSparseMode();
return arrayStorage();
}
case ALL_UNDECIDED_INDEXING_TYPES:
return enterDictionaryIndexingModeWhenArrayStorageAlreadyExists(vm, convertUndecidedToArrayStorage(vm));
case ALL_INT32_INDEXING_TYPES:
return enterDictionaryIndexingModeWhenArrayStorageAlreadyExists(vm, convertInt32ToArrayStorage(vm));
case ALL_DOUBLE_INDEXING_TYPES:
return enterDictionaryIndexingModeWhenArrayStorageAlreadyExists(vm, convertDoubleToArrayStorage(vm));
case ALL_CONTIGUOUS_INDEXING_TYPES:
return enterDictionaryIndexingModeWhenArrayStorageAlreadyExists(vm, convertContiguousToArrayStorage(vm));
case ALL_ARRAY_STORAGE_INDEXING_TYPES:
return enterDictionaryIndexingModeWhenArrayStorageAlreadyExists(vm, m_butterfly->arrayStorage());
default:
CRASH();
return nullptr;
}
}
void JSObject::switchToSlowPutArrayStorage(VM& vm)
{
ensureWritable(vm);
switch (indexingType()) {
case ArrayClass:
ensureArrayStorage(vm);
RELEASE_ASSERT(hasAnyArrayStorage(indexingType()));
if (hasSlowPutArrayStorage(indexingType()))
return;
switchToSlowPutArrayStorage(vm);
break;
case ALL_UNDECIDED_INDEXING_TYPES:
convertUndecidedToArrayStorage(vm, TransitionKind::AllocateSlowPutArrayStorage);
break;
case ALL_INT32_INDEXING_TYPES:
convertInt32ToArrayStorage(vm, TransitionKind::AllocateSlowPutArrayStorage);
break;
case ALL_DOUBLE_INDEXING_TYPES:
convertDoubleToArrayStorage(vm, TransitionKind::AllocateSlowPutArrayStorage);
break;
case ALL_CONTIGUOUS_INDEXING_TYPES:
convertContiguousToArrayStorage(vm, TransitionKind::AllocateSlowPutArrayStorage);
break;
case NonArrayWithArrayStorage:
case ArrayWithArrayStorage: {
Structure* oldStructure = structure();
DeferredStructureTransitionWatchpointFire deferred(vm, oldStructure);
Structure* newStructure = Structure::nonPropertyTransition(vm, oldStructure, TransitionKind::SwitchToSlowPutArrayStorage, &deferred);
setStructure(vm, newStructure);
break;
}
default:
CRASH();
break;
}
}
void JSObject::setPrototypeDirect(VM& vm, JSValue prototype)
{
ASSERT(prototype.isObject() || prototype.isNull());
if (prototype.isObject())
asObject(prototype)->didBecomePrototype(vm);
else if (UNLIKELY(!prototype.isNull())) // Conservative hardening.
return;
if (structure()->hasMonoProto()) {
DeferredStructureTransitionWatchpointFire deferred(vm, structure());
Structure* newStructure = Structure::changePrototypeTransition(vm, structure(), prototype, deferred);
setStructure(vm, newStructure);
// Prototype-chain gets changed for the already cached structures. Invalidate the cache.
if (UNLIKELY(mayBePrototype()))
vm.invalidateStructureChainIntegrity(VM::StructureChainIntegrityEvent::Prototype);
} else
putDirectOffset(vm, knownPolyProtoOffset, prototype);
if (!anyObjectInChainMayInterceptIndexedAccesses())
return;
if (mayBePrototype()) {
structure()->globalObject()->haveABadTime(vm);
return;
}
if (!hasIndexedProperties(indexingType()))
return;
if (shouldUseSlowPut(indexingType()))
return;
switchToSlowPutArrayStorage(vm);
}
bool JSObject::setPrototypeWithCycleCheck(VM& vm, JSGlobalObject* globalObject, JSValue prototype, bool shouldThrowIfCantSet)
{
auto scope = DECLARE_THROW_SCOPE(vm);
if (this->structure()->isImmutablePrototypeExoticObject()) {
// This implements https://tc39.github.io/ecma262/#sec-set-immutable-prototype.
if (this->getPrototype(vm, globalObject) == prototype)
return true;
return typeError(globalObject, scope, shouldThrowIfCantSet, "Cannot set prototype of immutable prototype object"_s);
}
// Default realm global objects should have mutable prototypes despite having
// a Proxy globalThis.
ASSERT(this->isGlobalObject() || JSValue(this).toThis(globalObject, ECMAMode::sloppy()) == this);
if (this->getPrototypeDirect() == prototype)
return true;
bool isExtensible = this->isExtensible(globalObject);
RETURN_IF_EXCEPTION(scope, false);
if (!isExtensible)
return typeError(globalObject, scope, shouldThrowIfCantSet, ReadonlyPropertyWriteError);
// Some clients would have already done this check because of the order of the check
// specified in their respective specifications. However, we still do this check here
// to document and enforce this invariant about the nature of prototype.
if (UNLIKELY(!prototype.isObject() && !prototype.isNull()))
return typeError(globalObject, scope, shouldThrowIfCantSet, PrototypeValueCanOnlyBeAnObjectOrNullTypeError);
JSValue nextPrototype = prototype;
while (nextPrototype && nextPrototype.isObject()) {
if (nextPrototype == this)
return typeError(globalObject, scope, shouldThrowIfCantSet, "cyclic __proto__ value"_s);
// FIXME: The specification currently says we should check if the [[GetPrototypeOf]] internal method of nextPrototype
// is not the ordinary object internal method. However, we currently restrict this to Proxy objects as it would allow
// for cycles with certain HTML objects (WindowProxy, Location) otherwise.
// https://bugs.webkit.org/show_bug.cgi?id=161534
if (UNLIKELY(asObject(nextPrototype)->type() == ProxyObjectType))
break; // We're done. Set the prototype.
nextPrototype = asObject(nextPrototype)->getPrototypeDirect();
}
setPrototypeDirect(vm, prototype);
return true;
}
bool JSObject::setPrototype(JSObject* object, JSGlobalObject* globalObject, JSValue prototype, bool shouldThrowIfCantSet)
{
return object->setPrototypeWithCycleCheck(globalObject->vm(), globalObject, prototype, shouldThrowIfCantSet);
}
JSValue JSObject::getPrototype(JSObject* object, JSGlobalObject*)
{
return object->getPrototypeDirect();
}
bool JSObject::setPrototype(VM&, JSGlobalObject* globalObject, JSValue prototype, bool shouldThrowIfCantSet)
{
return methodTable()->setPrototype(this, globalObject, prototype, shouldThrowIfCantSet);
}
bool JSObject::putGetter(JSGlobalObject* globalObject, PropertyName propertyName, JSValue getter, unsigned attributes)
{
PropertyDescriptor descriptor;
descriptor.setGetter(getter);
ASSERT(attributes & PropertyAttribute::Accessor);
if (!(attributes & PropertyAttribute::ReadOnly))
descriptor.setConfigurable(true);
if (!(attributes & PropertyAttribute::DontEnum))
descriptor.setEnumerable(true);
return defineOwnProperty(this, globalObject, propertyName, descriptor, true);
}
bool JSObject::putSetter(JSGlobalObject* globalObject, PropertyName propertyName, JSValue setter, unsigned attributes)
{
PropertyDescriptor descriptor;
descriptor.setSetter(setter);
ASSERT(attributes & PropertyAttribute::Accessor);
if (!(attributes & PropertyAttribute::ReadOnly))
descriptor.setConfigurable(true);
if (!(attributes & PropertyAttribute::DontEnum))
descriptor.setEnumerable(true);
return defineOwnProperty(this, globalObject, propertyName, descriptor, true);
}
bool JSObject::putDirectAccessor(JSGlobalObject* globalObject, PropertyName propertyName, GetterSetter* accessor, unsigned attributes)
{
ASSERT(attributes & PropertyAttribute::Accessor);
if (std::optional<uint32_t> index = parseIndex(propertyName))
return putDirectIndex(globalObject, index.value(), accessor, attributes, PutDirectIndexLikePutDirect);
return putDirectNonIndexAccessor(globalObject->vm(), propertyName, accessor, attributes);
}
// FIXME: Introduce a JSObject::putDirectCustomValue() method instead of using
// JSObject::putDirectCustomAccessor() to put CustomValues.
// https://bugs.webkit.org/show_bug.cgi?id=192576
bool JSObject::putDirectCustomAccessor(VM& vm, PropertyName propertyName, JSValue value, unsigned attributes)
{
ASSERT(!parseIndex(propertyName));
ASSERT(value.isCustomGetterSetter());
if (!(attributes & PropertyAttribute::CustomAccessor))
attributes |= PropertyAttribute::CustomValue;
PutPropertySlot slot(this);
bool result = putDirectInternal<PutModeDefineOwnProperty>(vm, propertyName, value, attributes, slot).isNull();
ASSERT(slot.type() == PutPropertySlot::NewProperty);
Structure* structure = this->structure();
if (attributes & PropertyAttribute::ReadOnly)
structure->setContainsReadOnlyProperties();
structure->setHasAnyKindOfGetterSetterPropertiesWithProtoCheck(propertyName == vm.propertyNames->underscoreProto);
return result;
}
void JSObject::putDirectCustomGetterSetterWithoutTransition(VM& vm, PropertyName propertyName, JSValue value, unsigned attributes)
{
ASSERT(!parseIndex(propertyName));
ASSERT(value.isCustomGetterSetter());
ASSERT(attributes & PropertyAttribute::CustomAccessorOrValue);
StructureID structureID = this->structureID();
Structure* structure = structureID.decode();
PropertyOffset offset = prepareToPutDirectWithoutTransition(vm, propertyName, attributes, structureID, structure);
putDirectOffset(vm, offset, value);
if (attributes & PropertyAttribute::ReadOnly)
structure->setContainsReadOnlyProperties();
structure->setHasAnyKindOfGetterSetterPropertiesWithProtoCheck(propertyName == vm.propertyNames->underscoreProto);
}
bool JSObject::putDirectNonIndexAccessor(VM& vm, PropertyName propertyName, GetterSetter* accessor, unsigned attributes)
{
ASSERT(attributes & PropertyAttribute::Accessor);
PutPropertySlot slot(this);
bool result = putDirectInternal<PutModeDefineOwnProperty>(vm, propertyName, accessor, attributes, slot).isNull();
Structure* structure = this->structure();
if (attributes & PropertyAttribute::ReadOnly)
structure->setContainsReadOnlyProperties();
structure->setHasAnyKindOfGetterSetterPropertiesWithProtoCheck(propertyName == vm.propertyNames->underscoreProto);
return result;
}
void JSObject::putDirectNonIndexAccessorWithoutTransition(VM& vm, PropertyName propertyName, GetterSetter* accessor, unsigned attributes)
{
ASSERT(attributes & PropertyAttribute::Accessor);
StructureID structureID = this->structureID();
Structure* structure = structureID.decode();
PropertyOffset offset = prepareToPutDirectWithoutTransition(vm, propertyName, attributes, structureID, structure);
putDirectOffset(vm, offset, accessor);
if (attributes & PropertyAttribute::ReadOnly)
structure->setContainsReadOnlyProperties();
structure->setHasAnyKindOfGetterSetterPropertiesWithProtoCheck(propertyName == vm.propertyNames->underscoreProto);
}
// https://tc39.es/ecma262/#sec-hasproperty
bool JSObject::hasProperty(JSGlobalObject* globalObject, PropertyName propertyName) const
{
PropertySlot slot(this, PropertySlot::InternalMethodType::HasProperty);
return const_cast<JSObject*>(this)->getPropertySlot(globalObject, propertyName, slot);
}
bool JSObject::hasProperty(JSGlobalObject* globalObject, unsigned propertyName) const
{
PropertySlot slot(this, PropertySlot::InternalMethodType::HasProperty);
return const_cast<JSObject*>(this)->getPropertySlot(globalObject, propertyName, slot);
}
bool JSObject::hasProperty(JSGlobalObject* globalObject, uint64_t propertyName) const
{
if (LIKELY(propertyName <= MAX_ARRAY_INDEX))
return hasProperty(globalObject, static_cast<uint32_t>(propertyName));
ASSERT(propertyName <= maxSafeInteger());
return hasProperty(globalObject, Identifier::from(globalObject->vm(), propertyName));
}
bool JSObject::hasEnumerableProperty(JSGlobalObject* globalObject, PropertyName propertyName) const
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
PropertySlot slot(this, PropertySlot::InternalMethodType::GetOwnProperty);
bool hasProperty = const_cast<JSObject*>(this)->getPropertySlot(globalObject, propertyName, slot);
RETURN_IF_EXCEPTION(scope, false);
if (!hasProperty)
return false;
return !(slot.attributes() & PropertyAttribute::DontEnum) || (slot.slotBase() && slot.slotBase()->structure()->typeInfo().getOwnPropertySlotMayBeWrongAboutDontEnum());
}
bool JSObject::hasEnumerableProperty(JSGlobalObject* globalObject, unsigned propertyName) const
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
PropertySlot slot(this, PropertySlot::InternalMethodType::GetOwnProperty);
bool hasProperty = const_cast<JSObject*>(this)->getPropertySlot(globalObject, propertyName, slot);
RETURN_IF_EXCEPTION(scope, false);
if (!hasProperty)
return false;
return !(slot.attributes() & PropertyAttribute::DontEnum) || (slot.slotBase() && slot.slotBase()->structure()->typeInfo().getOwnPropertySlotMayBeWrongAboutDontEnum());
}
// ECMA 8.6.2.5
bool JSObject::deleteProperty(JSCell* cell, JSGlobalObject* globalObject, PropertyName propertyName, DeletePropertySlot& slot)
{
JSObject* thisObject = jsCast<JSObject*>(cell);
VM& vm = globalObject->vm();
if (std::optional<uint32_t> index = parseIndex(propertyName))
return thisObject->methodTable()->deletePropertyByIndex(thisObject, globalObject, index.value());
unsigned attributes;
if (thisObject->hasNonReifiedStaticProperties()) {
if (auto entry = thisObject->findPropertyHashEntry(propertyName)) {
// If the static table contains a non-configurable (DontDelete) property then we can return early;
// if there is a property in the storage array it too must be non-configurable (the language does
// not allow repacement of a non-configurable property with a configurable one).
if (entry->value->attributes() & PropertyAttribute::DontDelete && vm.deletePropertyMode() != VM::DeletePropertyMode::IgnoreConfigurable) {
ASSERT(!isValidOffset(thisObject->structure()->get(vm, propertyName, attributes)) || attributes & PropertyAttribute::DontDelete);
return false;
}
thisObject->reifyAllStaticProperties(globalObject);
}
}
Structure* structure = thisObject->structure();
bool propertyIsPresent = isValidOffset(structure->get(vm, propertyName, attributes));
if (propertyIsPresent) {
if (attributes & PropertyAttribute::DontDelete && vm.deletePropertyMode() != VM::DeletePropertyMode::IgnoreConfigurable) {
slot.setNonconfigurable();
return false;
}
PropertyOffset offset = invalidOffset;
if (structure->isUncacheableDictionary()) {
offset = structure->removePropertyWithoutTransition(vm, propertyName, [] (const GCSafeConcurrentJSLocker&, PropertyOffset, PropertyOffset) { });
ASSERT(!isValidOffset(structure->get(vm, propertyName, attributes)));
if (offset != invalidOffset)
thisObject->locationForOffset(offset)->clear();
} else {
DeferredStructureTransitionWatchpointFire deferredWatchpointFire(vm, structure);
structure = Structure::removePropertyTransition(vm, structure, propertyName, offset, &deferredWatchpointFire);
slot.setHit(offset);
ASSERT(structure->outOfLineCapacity() || !thisObject->structure()->outOfLineCapacity());
thisObject->setStructure(vm, structure);
ASSERT(!isValidOffset(structure->get(vm, propertyName, attributes)));
if (offset != invalidOffset)
thisObject->locationForOffset(offset)->clear();
if (UNLIKELY(thisObject->mayBePrototype()))
vm.invalidateStructureChainIntegrity(VM::StructureChainIntegrityEvent::Remove);
}
} else
slot.setConfigurableMiss();
return true;
}
bool JSObject::deletePropertyByIndex(JSCell* cell, JSGlobalObject* globalObject, unsigned i)
{
VM& vm = globalObject->vm();
JSObject* thisObject = jsCast<JSObject*>(cell);
if (i > MAX_ARRAY_INDEX)
return JSCell::deleteProperty(thisObject, globalObject, Identifier::from(vm, i));
switch (thisObject->indexingMode()) {
case ALL_BLANK_INDEXING_TYPES:
case ALL_UNDECIDED_INDEXING_TYPES:
return true;
case CopyOnWriteArrayWithInt32:
case CopyOnWriteArrayWithContiguous: {
Butterfly* butterfly = thisObject->butterfly();
if (i >= butterfly->vectorLength())
return true;
thisObject->convertFromCopyOnWrite(vm);
FALLTHROUGH;
}
case ALL_WRITABLE_INT32_INDEXING_TYPES:
case ALL_WRITABLE_CONTIGUOUS_INDEXING_TYPES: {
Butterfly* butterfly = thisObject->butterfly();
if (i >= butterfly->vectorLength())
return true;
butterfly->contiguous().at(thisObject, i).clear();
return true;
}
case CopyOnWriteArrayWithDouble: {
Butterfly* butterfly = thisObject->butterfly();
if (i >= butterfly->vectorLength())
return true;
thisObject->convertFromCopyOnWrite(vm);
FALLTHROUGH;
}
case ALL_WRITABLE_DOUBLE_INDEXING_TYPES: {
Butterfly* butterfly = thisObject->butterfly();
if (i >= butterfly->vectorLength())
return true;
butterfly->contiguousDouble().at(thisObject, i) = PNaN;
return true;
}
case ALL_ARRAY_STORAGE_INDEXING_TYPES: {
ArrayStorage* storage = thisObject->m_butterfly->arrayStorage();
if (i < storage->vectorLength()) {
WriteBarrier<Unknown>& valueSlot = storage->m_vector[i];
if (valueSlot) {
valueSlot.clear();
--storage->m_numValuesInVector;
}
} else if (SparseArrayValueMap* map = storage->m_sparseMap.get()) {
SparseArrayValueMap::iterator it = map->find(i);
if (it != map->notFound()) {
if (it->value.attributes() & PropertyAttribute::DontDelete)
return false;
map->remove(it);
}
}
return true;
}
default:
RELEASE_ASSERT_NOT_REACHED();
return false;
}
}
template<CachedSpecialPropertyKey key>
static ALWAYS_INLINE JSValue callToPrimitiveFunction(JSGlobalObject* globalObject, const JSObject* object, PropertyName propertyName, PreferredPrimitiveType hint)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSValue function = object->structure()->cachedSpecialProperty(key);
if (!function) {
PropertySlot slot(object, PropertySlot::InternalMethodType::Get);
// FIXME: Remove this when we have fixed: rdar://problem/33451840
// https://bugs.webkit.org/show_bug.cgi?id=187109.
constexpr bool debugNullStructure = key == CachedSpecialPropertyKey::ToPrimitive;
bool hasProperty = const_cast<JSObject*>(object)->getPropertySlot<debugNullStructure>(globalObject, propertyName, slot);
RETURN_IF_EXCEPTION(scope, scope.exception());
function = hasProperty ? slot.getValue(globalObject, propertyName) : jsUndefined();
RETURN_IF_EXCEPTION(scope, scope.exception());
object->structure()->cacheSpecialProperty(globalObject, vm, function, key, slot);
RETURN_IF_EXCEPTION(scope, scope.exception());
}
if (function.isUndefinedOrNull())
return JSValue();
// Add optimizations for frequently called functions.
// https://bugs.webkit.org/show_bug.cgi?id=216084
if constexpr (key == CachedSpecialPropertyKey::ToString) {
if (function == globalObject->objectProtoToStringFunction()) {
if (auto result = object->structure()->cachedSpecialProperty(CachedSpecialPropertyKey::ToStringTag))
return result;
}
}
if constexpr (key == CachedSpecialPropertyKey::ValueOf) {
if (function == globalObject->objectProtoValueOfFunction())
return JSValue();
}
auto callData = JSC::getCallData(function);
if (callData.type == CallData::Type::None) {
if constexpr (key == CachedSpecialPropertyKey::ToPrimitive)
throwTypeError(globalObject, scope, "Symbol.toPrimitive is not a function, undefined, or null"_s);
return scope.exception();
}
MarkedArgumentBuffer callArgs;
if constexpr (key == CachedSpecialPropertyKey::ToPrimitive) {
JSString* hintString = nullptr;
switch (hint) {
case NoPreference:
hintString = vm.smallStrings.defaultString();
break;
case PreferNumber:
hintString = vm.smallStrings.numberString();
break;
case PreferString:
hintString = vm.smallStrings.stringString();
break;
}
callArgs.append(hintString);
} else {
UNUSED_PARAM(hint);
}
ASSERT(!callArgs.hasOverflowed());
JSValue result = call(globalObject, function, callData, const_cast<JSObject*>(object), callArgs);
RETURN_IF_EXCEPTION(scope, scope.exception());
ASSERT(!result.isGetterSetter());
if (result.isObject()) {
if constexpr (key == CachedSpecialPropertyKey::ToPrimitive)
return throwTypeError(globalObject, scope, "Symbol.toPrimitive returned an object"_s);
return JSValue();
}
return result;
}
// ECMA 7.1.1
JSValue JSObject::ordinaryToPrimitive(JSGlobalObject* globalObject, PreferredPrimitiveType hint) const
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
// Make sure that whatever default value methods there are on object's prototype chain are
// being watched.
// FIXME: Remove this hack for DFG.
// https://bugs.webkit.org/show_bug.cgi?id=216117
for (const JSObject* object = this; object; object = object->structure()->storedPrototypeObject(object))
object->structure()->startWatchingInternalPropertiesIfNecessary(vm);
JSValue value;
if (hint == PreferString) {
value = callToPrimitiveFunction<CachedSpecialPropertyKey::ToString>(globalObject, this, vm.propertyNames->toString, hint);
EXCEPTION_ASSERT(!scope.exception() || scope.exception() == value.asCell());
if (value)
return value;
value = callToPrimitiveFunction<CachedSpecialPropertyKey::ValueOf>(globalObject, this, vm.propertyNames->valueOf, hint);
EXCEPTION_ASSERT(!scope.exception() || scope.exception() == value.asCell());
if (value)
return value;
} else {
value = callToPrimitiveFunction<CachedSpecialPropertyKey::ValueOf>(globalObject, this, vm.propertyNames->valueOf, hint);
EXCEPTION_ASSERT(!scope.exception() || scope.exception() == value.asCell());
if (value)
return value;
value = callToPrimitiveFunction<CachedSpecialPropertyKey::ToString>(globalObject, this, vm.propertyNames->toString, hint);
EXCEPTION_ASSERT(!scope.exception() || scope.exception() == value.asCell());
if (value)
return value;
}
return throwTypeError(globalObject, scope, "No default value"_s);
}
JSValue JSObject::toPrimitive(JSGlobalObject* globalObject, PreferredPrimitiveType preferredType) const
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSValue value = callToPrimitiveFunction<CachedSpecialPropertyKey::ToPrimitive>(globalObject, this, vm.propertyNames->toPrimitiveSymbol, preferredType);
RETURN_IF_EXCEPTION(scope, { });
if (value)
return value;
RELEASE_AND_RETURN(scope, ordinaryToPrimitive(globalObject, preferredType));
}
bool JSObject::getOwnStaticPropertySlot(VM& vm, PropertyName propertyName, PropertySlot& slot)
{
for (auto* info = classInfo(); info; info = info->parentClass) {
if (auto* table = info->staticPropHashTable) {
if (getStaticPropertySlotFromTable(vm, table->classForThis, *table, this, propertyName, slot))
return true;
}
}
return false;
}
std::optional<Structure::PropertyHashEntry> JSObject::findPropertyHashEntry(PropertyName propertyName) const
{
return structure()->findPropertyHashEntry(propertyName);
}
bool JSObject::hasInstance(JSGlobalObject* globalObject, JSValue value, JSValue hasInstanceValue)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
if (!hasInstanceValue.isUndefinedOrNull() && hasInstanceValue != globalObject->functionProtoHasInstanceSymbolFunction()) {
auto callData = JSC::getCallData(hasInstanceValue);
if (callData.type == CallData::Type::None) {
throwException(globalObject, scope, createInvalidInstanceofParameterErrorHasInstanceValueNotFunction(globalObject, this));
return false;
}
MarkedArgumentBuffer args;
args.append(value);
ASSERT(!args.hasOverflowed());
JSValue result = call(globalObject, hasInstanceValue, callData, this, args);
RETURN_IF_EXCEPTION(scope, false);
return result.toBoolean(globalObject);
}
TypeInfo info = structure()->typeInfo();
if (info.implementsDefaultHasInstance()) {
JSValue prototype = get(globalObject, vm.propertyNames->prototype);
RETURN_IF_EXCEPTION(scope, false);
RELEASE_AND_RETURN(scope, defaultHasInstance(globalObject, value, prototype));
}
if (info.implementsHasInstance()) {
if (UNLIKELY(!vm.isSafeToRecurseSoft())) {
throwStackOverflowError(globalObject, scope);
return false;
}
RELEASE_AND_RETURN(scope, methodTable()->customHasInstance(this, globalObject, value));
}
throwException(globalObject, scope, createInvalidInstanceofParameterErrorNotFunction(globalObject, this));
return false;
}
bool JSObject::hasInstance(JSGlobalObject* globalObject, JSValue value)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSValue hasInstanceValue = get(globalObject, vm.propertyNames->hasInstanceSymbol);
RETURN_IF_EXCEPTION(scope, false);
RELEASE_AND_RETURN(scope, hasInstance(globalObject, value, hasInstanceValue));
}
bool JSObject::defaultHasInstance(JSGlobalObject* globalObject, JSValue value, JSValue proto)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
if (!value.isObject())
return false;
if (!proto.isObject()) {
throwTypeError(globalObject, scope, "instanceof called on an object with an invalid prototype property."_s);
return false;
}
JSObject* object = asObject(value);
while (true) {
JSValue objectValue = object->getPrototype(vm, globalObject);
RETURN_IF_EXCEPTION(scope, false);
if (!objectValue.isObject())
return false;
object = asObject(objectValue);
if (proto == object)
return true;
}
ASSERT_NOT_REACHED();
}
JSC_DEFINE_HOST_FUNCTION(objectPrivateFuncInstanceOf, (JSGlobalObject* globalObject, CallFrame* callFrame))
{
JSValue value = callFrame->uncheckedArgument(0);
JSValue proto = callFrame->uncheckedArgument(1);
return JSValue::encode(jsBoolean(JSObject::defaultHasInstance(globalObject, value, proto)));
}
void JSObject::getPropertyNames(JSGlobalObject* globalObject, PropertyNameArray& propertyNames, DontEnumPropertiesMode mode)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSObject* object = this;
unsigned prototypeCount = 0;
while (true) {
object->methodTable()->getOwnPropertyNames(object, globalObject, propertyNames, mode);
RETURN_IF_EXCEPTION(scope, void());
JSValue prototype = object->getPrototype(vm, globalObject);
RETURN_IF_EXCEPTION(scope, void());
if (prototype.isNull())
break;
if (UNLIKELY(++prototypeCount > maximumPrototypeChainDepth)) {
throwStackOverflowError(globalObject, scope);
return;
}
object = asObject(prototype);
}
}
void JSObject::getOwnPropertyNames(JSObject* object, JSGlobalObject* globalObject, PropertyNameArray& propertyNames, DontEnumPropertiesMode mode)
{
object->getOwnIndexedPropertyNames(globalObject, propertyNames, mode);
object->getOwnNonIndexPropertyNames(globalObject, propertyNames, mode);
}
void JSObject::getOwnSpecialPropertyNames(JSObject*, JSGlobalObject*, PropertyNameArray&, DontEnumPropertiesMode)
{
// Structure::validateFlags() breaks if this method isn't exported, which is impossible if it's inlined.
}
void JSObject::getOwnIndexedPropertyNames(JSGlobalObject*, PropertyNameArray& propertyNames, DontEnumPropertiesMode mode)
{
JSObject* object = this;
if (propertyNames.includeStringProperties()) {
// Add numeric properties first per step 2 of https://tc39.es/ecma262/#sec-ordinaryownpropertykeys
// FIXME: Filling PropertyNameArray with an identifier for every integer
// is incredibly inefficient for large arrays. We need a different approach,
// which almost certainly means a different structure for PropertyNameArray.
switch (object->indexingType()) {
case ALL_BLANK_INDEXING_TYPES:
case ALL_UNDECIDED_INDEXING_TYPES:
break;
case ALL_INT32_INDEXING_TYPES:
case ALL_CONTIGUOUS_INDEXING_TYPES: {
Butterfly* butterfly = object->butterfly();
unsigned usedLength = butterfly->publicLength();
for (unsigned i = 0; i < usedLength; ++i) {
if (!butterfly->contiguous().at(object, i))
continue;
propertyNames.add(i);
}
break;
}
case ALL_DOUBLE_INDEXING_TYPES: {
Butterfly* butterfly = object->butterfly();
unsigned usedLength = butterfly->publicLength();
for (unsigned i = 0; i < usedLength; ++i) {
double value = butterfly->contiguousDouble().at(object, i);
if (value != value)
continue;
propertyNames.add(i);
}
break;
}
case ALL_ARRAY_STORAGE_INDEXING_TYPES: {
ArrayStorage* storage = object->m_butterfly->arrayStorage();
unsigned usedVectorLength = std::min(storage->length(), storage->vectorLength());
for (unsigned i = 0; i < usedVectorLength; ++i) {
if (storage->m_vector[i])
propertyNames.add(i);
}
if (SparseArrayValueMap* map = storage->m_sparseMap.get()) {
auto keys = WTF::compactMap<0, UnsafeVectorOverflow>(*map, [mode](auto& entry) ->std::optional<unsigned> {
if (mode == DontEnumPropertiesMode::Include || !(entry.value.attributes() & PropertyAttribute::DontEnum))
return static_cast<unsigned>(entry.key);
return std::nullopt;
});
std::sort(keys.begin(), keys.end());
for (unsigned i = 0; i < keys.size(); ++i)
propertyNames.add(keys[i]);
}
break;
}
default:
RELEASE_ASSERT_NOT_REACHED();
}
}
}
void JSObject::getOwnNonIndexPropertyNames(JSGlobalObject* globalObject, PropertyNameArray& propertyNames, DontEnumPropertiesMode mode)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
methodTable()->getOwnSpecialPropertyNames(this, globalObject, propertyNames, mode);
RETURN_IF_EXCEPTION(scope, void());
scope.release();
getNonReifiedStaticPropertyNames(vm, propertyNames, mode);
structure()->getPropertyNamesFromStructure(vm, propertyNames, mode);
}
double JSObject::toNumber(JSGlobalObject* globalObject) const
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSValue primitive = toPrimitive(globalObject, PreferNumber);
RETURN_IF_EXCEPTION(scope, 0.0); // should be picked up soon in Nodes.cpp
RELEASE_AND_RETURN(scope, primitive.toNumber(globalObject));
}
JSString* JSObject::toString(JSGlobalObject* globalObject) const
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSValue primitive = callToPrimitiveFunction<CachedSpecialPropertyKey::ToPrimitive>(globalObject, this, vm.propertyNames->toPrimitiveSymbol, PreferString);
RETURN_IF_EXCEPTION(scope, jsEmptyString(vm));
if (LIKELY(!primitive)) {
primitive = ordinaryToPrimitive(globalObject, PreferString);
RETURN_IF_EXCEPTION(scope, jsEmptyString(vm));
}
RELEASE_AND_RETURN(scope, primitive.toString(globalObject));
}
void JSObject::seal(VM& vm)
{
if (isSealed(vm))
return;
enterDictionaryIndexingMode(vm);
{
Structure* oldStructure = structure();
DeferredStructureTransitionWatchpointFire deferred(vm, oldStructure);
setStructure(vm, Structure::sealTransition(vm, oldStructure, &deferred));
}
}
void JSObject::freeze(VM& vm)
{
if (isFrozen(vm))
return;
enterDictionaryIndexingMode(vm);
{
Structure* oldStructure = structure();
DeferredStructureTransitionWatchpointFire deferred(vm, oldStructure);
setStructure(vm, Structure::freezeTransition(vm, oldStructure, &deferred));
}
}
bool JSObject::preventExtensions(JSObject* object, JSGlobalObject* globalObject)
{
VM& vm = globalObject->vm();
if (!object->isStructureExtensible()) {
// We've already set the internal [[PreventExtensions]] field to false.
// We don't call the methodTable isExtensible here because it's not defined
// that way in the specification. We are just doing an optimization here.
return true;
}
object->enterDictionaryIndexingMode(vm);
{
Structure* oldStructure = object->structure();
DeferredStructureTransitionWatchpointFire deferred(vm, oldStructure);
object->setStructure(vm, Structure::preventExtensionsTransition(vm, oldStructure, &deferred));
}
return true;
}
bool JSObject::isExtensible(JSObject* obj, JSGlobalObject*)
{
return obj->isStructureExtensible();
}
bool JSObject::isExtensible(JSGlobalObject* globalObject)
{
return methodTable()->isExtensible(this, globalObject);
}
void JSObject::reifyAllStaticProperties(JSGlobalObject* globalObject)
{
VM& vm = globalObject->vm();
ASSERT(!staticPropertiesReified());
// If this object's ClassInfo has no static properties, then nothing to reify!
// We can safely set the flag to avoid the expensive check again in the future.
if (!TypeInfo::hasStaticPropertyTable(inlineTypeFlags())) {
structure()->setStaticPropertiesReified(true);
return;
}
if (!structure()->isDictionary())
convertToDictionary(vm);
for (const ClassInfo* info = classInfo(); info; info = info->parentClass) {
const HashTable* hashTable = info->staticPropHashTable;
if (!hashTable)
continue;
for (auto& value : *hashTable) {
unsigned attributes;
auto key = Identifier::fromString(vm, value.m_key);
PropertyOffset offset = getDirectOffset(vm, key, attributes);
if (!isValidOffset(offset))
reifyStaticProperty(vm, hashTable->classForThis, key, value, *this);
}
}
structure()->setStaticPropertiesReified(true);
}
NEVER_INLINE void JSObject::fillGetterPropertySlot(VM&, PropertySlot& slot, JSCell* getterSetter, unsigned attributes, PropertyOffset offset)
{
if (structure()->isUncacheableDictionary()) {
slot.setGetterSlot(this, attributes, jsCast<GetterSetter*>(getterSetter));
return;
}
// This access is cacheable because Structure requires an attributeChangedTransition
// if this property stops being an accessor.
slot.setCacheableGetterSlot(this, attributes, jsCast<GetterSetter*>(getterSetter), offset);
}
static bool putIndexedDescriptor(JSGlobalObject* globalObject, SparseArrayValueMap* map, SparseArrayEntry* entryInMap, const PropertyDescriptor& descriptor, PropertyDescriptor& oldDescriptor)
{
VM& vm = globalObject->vm();
if (descriptor.isDataDescriptor()) {
unsigned attributes = descriptor.attributesOverridingCurrent(oldDescriptor) & ~PropertyAttribute::Accessor;
if (descriptor.value())
entryInMap->forceSet(vm, map, descriptor.value(), attributes);
else if (oldDescriptor.isAccessorDescriptor())
entryInMap->forceSet(vm, map, jsUndefined(), attributes);
else
entryInMap->forceSet(map, attributes);
return true;
}
if (descriptor.isAccessorDescriptor()) {
JSObject* getter = nullptr;
if (descriptor.getterPresent())
getter = descriptor.getterObject();
else if (oldDescriptor.isAccessorDescriptor())
getter = oldDescriptor.getterObject();
JSObject* setter = nullptr;
if (descriptor.setterPresent())
setter = descriptor.setterObject();
else if (oldDescriptor.isAccessorDescriptor())
setter = oldDescriptor.setterObject();
GetterSetter* accessor = GetterSetter::create(vm, globalObject, getter, setter);
entryInMap->forceSet(vm, map, accessor, descriptor.attributesOverridingCurrent(oldDescriptor) & ~PropertyAttribute::ReadOnly);
return true;
}
ASSERT(descriptor.isGenericDescriptor());
entryInMap->forceSet(map, descriptor.attributesOverridingCurrent(oldDescriptor));
return true;
}
ALWAYS_INLINE static bool canDoFastPutDirectIndex(JSObject* object)
{
if (TypeInfo::isArgumentsType(object->type()))
return true;
if (object->inSparseIndexingMode())
return false;
return (isJSArray(object) && !isCopyOnWrite(object->indexingMode()))
|| jsDynamicCast<JSFinalObject*>(object);
}
// https://tc39.es/ecma262/#sec-ordinarydefineownproperty
bool JSObject::defineOwnIndexedProperty(JSGlobalObject* globalObject, unsigned index, const PropertyDescriptor& descriptor, bool throwException)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
ASSERT(index <= MAX_ARRAY_INDEX);
ensureWritable(vm);
if (!inSparseIndexingMode()) {
const PropertyDescriptor emptyAttributesDescriptor(jsUndefined(), static_cast<unsigned>(PropertyAttribute::None));
ASSERT(emptyAttributesDescriptor.attributes() == static_cast<unsigned>(PropertyAttribute::None));
#if ASSERT_ENABLED
if (canGetIndexQuickly(index) && canDoFastPutDirectIndex(this)) {
DeferTermination deferScope(vm);
PropertyDescriptor currentDescriptor;
bool found = getOwnPropertyDescriptor(globalObject, Identifier::from(vm, index), currentDescriptor);
scope.assertNoException();
if (found)
ASSERT(currentDescriptor.attributes() == emptyAttributesDescriptor.attributes());
}
#endif
// Fast case: we're putting a regular property to a regular array
if (descriptor.value()
&& (!descriptor.attributes() || (canGetIndexQuickly(index) && !descriptor.attributesOverridingCurrent(emptyAttributesDescriptor)))
&& canDoFastPutDirectIndex(this)) {
ASSERT(!descriptor.isAccessorDescriptor());
RELEASE_AND_RETURN(scope, putDirectIndex(globalObject, index, descriptor.value(), 0, throwException ? PutDirectIndexShouldThrow : PutDirectIndexShouldNotThrow));
}
ensureArrayStorageExistsAndEnterDictionaryIndexingMode(vm);
}
if (descriptor.attributes() & (PropertyAttribute::ReadOnly | PropertyAttribute::Accessor))
notifyPresenceOfIndexedAccessors(vm);
SparseArrayValueMap* map = m_butterfly->arrayStorage()->m_sparseMap.get();
RELEASE_ASSERT(map);
// 1. Let current be the result of calling the [[GetOwnProperty]] internal method of O with property name P.
SparseArrayValueMap::AddResult result = map->add(this, index);
SparseArrayEntry* entryInMap = &result.iterator->value;
// 2. Let extensible be the value of the [[Extensible]] internal property of O.
// 3. If current is undefined and extensible is false, then Reject.
// 4. If current is undefined and extensible is true, then
if (result.isNewEntry) {
if (!isStructureExtensible()) {
map->remove(result.iterator);
return typeError(globalObject, scope, throwException, NonExtensibleObjectPropertyDefineError);
}
// 4.a. If IsGenericDescriptor(Desc) or IsDataDescriptor(Desc) is true, then create an own data property
// named P of object O whose [[Value]], [[Writable]], [[Enumerable]] and [[Configurable]] attribute values
// are described by Desc. If the value of an attribute field of Desc is absent, the attribute of the newly
// created property is set to its default value.
// 4.b. Else, Desc must be an accessor Property Descriptor so, create an own accessor property named P of
// object O whose [[Get]], [[Set]], [[Enumerable]] and [[Configurable]] attribute values are described by
// Desc. If the value of an attribute field of Desc is absent, the attribute of the newly created property
// is set to its default value.
// 4.c. Return true.
PropertyDescriptor defaults(jsUndefined(), PropertyAttribute::DontDelete | PropertyAttribute::DontEnum | PropertyAttribute::ReadOnly);
putIndexedDescriptor(globalObject, map, entryInMap, descriptor, defaults);
Butterfly* butterfly = m_butterfly.get();
if (index >= butterfly->arrayStorage()->length())
butterfly->arrayStorage()->setLength(index + 1);
return true;
}
// 5. Return true, if every field in Desc is absent.
// 6. Return true, if every field in Desc also occurs in current and the value of every field in Desc is the same value as the corresponding field in current when compared using the SameValue algorithm (9.12).
PropertyDescriptor current;
entryInMap->get(current);
bool isEmptyOrEqual = descriptor.isEmpty() || descriptor.equalTo(globalObject, current);
RETURN_IF_EXCEPTION(scope, false);
if (isEmptyOrEqual)
return true;
// 7. If the [[Configurable]] field of current is false then
if (!current.configurable()) {
// 7.a. Reject, if the [[Configurable]] field of Desc is true.
if (descriptor.configurablePresent() && descriptor.configurable())
return typeError(globalObject, scope, throwException, UnconfigurablePropertyChangeConfigurabilityError);
// 7.b. Reject, if the [[Enumerable]] field of Desc is present and the [[Enumerable]] fields of current and Desc are the Boolean negation of each other.
if (descriptor.enumerablePresent() && current.enumerable() != descriptor.enumerable())
return typeError(globalObject, scope, throwException, UnconfigurablePropertyChangeEnumerabilityError);
}
// 8. If IsGenericDescriptor(Desc) is true, then no further validation is required.
if (!descriptor.isGenericDescriptor()) {
// 9. Else, if IsDataDescriptor(current) and IsDataDescriptor(Desc) have different results, then
if (current.isDataDescriptor() != descriptor.isDataDescriptor()) {
// 9.a. Reject, if the [[Configurable]] field of current is false.
if (!current.configurable())
return typeError(globalObject, scope, throwException, UnconfigurablePropertyChangeAccessMechanismError);
// 9.b. If IsDataDescriptor(current) is true, then convert the property named P of object O from a
// data property to an accessor property. Preserve the existing values of the converted property's
// [[Configurable]] and [[Enumerable]] attributes and set the rest of the property's attributes to
// their default values.
// 9.c. Else, convert the property named P of object O from an accessor property to a data property.
// Preserve the existing values of the converted property's [[Configurable]] and [[Enumerable]]
// attributes and set the rest of the property's attributes to their default values.
} else if (current.isDataDescriptor() && descriptor.isDataDescriptor()) {
// 10. Else, if IsDataDescriptor(current) and IsDataDescriptor(Desc) are both true, then
// 10.a. If the [[Configurable]] field of current is false, then
if (!current.configurable() && !current.writable()) {
// 10.a.i. Reject, if the [[Writable]] field of current is false and the [[Writable]] field of Desc is true.
if (descriptor.writable())
return typeError(globalObject, scope, throwException, UnconfigurablePropertyChangeWritabilityError);
// 10.a.ii. If the [[Writable]] field of current is false, then
// 10.a.ii.1. Reject, if the [[Value]] field of Desc is present and SameValue(Desc.[[Value]], current.[[Value]]) is false.
if (descriptor.value()) {
bool isSame = sameValue(globalObject, descriptor.value(), current.value());
RETURN_IF_EXCEPTION(scope, false);
if (!isSame)
return typeError(globalObject, scope, throwException, ReadonlyPropertyChangeError);
}
}
// 10.b. else, the [[Configurable]] field of current is true, so any change is acceptable.
} else {
ASSERT(current.isAccessorDescriptor() && current.getterPresent() && current.setterPresent());
// 11. Else, IsAccessorDescriptor(current) and IsAccessorDescriptor(Desc) are both true so, if the [[Configurable]] field of current is false, then
if (!current.configurable()) {
// 11.i. Reject, if the [[Set]] field of Desc is present and SameValue(Desc.[[Set]], current.[[Set]]) is false.
if (descriptor.setterPresent() && descriptor.setter() != current.setter())
return typeError(globalObject, scope, throwException, "Attempting to change the setter of an unconfigurable property."_s);
// 11.ii. Reject, if the [[Get]] field of Desc is present and SameValue(Desc.[[Get]], current.[[Get]]) is false.
if (descriptor.getterPresent() && descriptor.getter() != current.getter())
return typeError(globalObject, scope, throwException, "Attempting to change the getter of an unconfigurable property."_s);
}
}
}
// 12. For each attribute field of Desc that is present, set the correspondingly named attribute of the property named P of object O to the value of the field.
putIndexedDescriptor(globalObject, map, entryInMap, descriptor, current);
// 13. Return true.
return true;
}
SparseArrayValueMap* JSObject::allocateSparseIndexMap(VM& vm)
{
SparseArrayValueMap* result = SparseArrayValueMap::create(vm);
arrayStorage()->m_sparseMap.set(vm, this, result);
return result;
}
void JSObject::deallocateSparseIndexMap()
{
if (ArrayStorage* arrayStorage = arrayStorageOrNull())
arrayStorage->m_sparseMap.clear();
}
bool JSObject::attemptToInterceptPutByIndexOnHoleForPrototype(JSGlobalObject* globalObject, JSValue thisValue, unsigned i, JSValue value, bool shouldThrow, bool& putResult)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
for (JSObject* current = this; ;) {
// This has the same behavior with respect to prototypes as JSObject::put(). It only
// allows a prototype to intercept a put if (a) the prototype declares the property
// we're after rather than intercepting it via an override of JSObject::put(), and
// (b) that property is declared as ReadOnly or Accessor.
ArrayStorage* storage = current->arrayStorageOrNull();
if (storage && storage->m_sparseMap) {
SparseArrayValueMap::iterator iter = storage->m_sparseMap->find(i);
if (iter != storage->m_sparseMap->notFound() && (iter->value.attributes() & (PropertyAttribute::Accessor | PropertyAttribute::ReadOnly))) {
scope.release();
putResult = iter->value.put(globalObject, thisValue, storage->m_sparseMap.get(), value, shouldThrow);
return true;
}
}
if (current->type() == ProxyObjectType) {
scope.release();
auto* proxy = jsCast<ProxyObject*>(current);
putResult = proxy->putByIndexCommon(globalObject, thisValue, i, value, shouldThrow);
return true;
}
JSValue prototypeValue = current->getPrototype(vm, globalObject);
RETURN_IF_EXCEPTION(scope, false);
if (prototypeValue.isNull())
return false;
current = asObject(prototypeValue);
}
}
bool JSObject::attemptToInterceptPutByIndexOnHole(JSGlobalObject* globalObject, unsigned i, JSValue value, bool shouldThrow, bool& putResult)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSValue prototypeValue = getPrototype(vm, globalObject);
RETURN_IF_EXCEPTION(scope, false);
if (prototypeValue.isNull())
return false;
RELEASE_AND_RETURN(scope, asObject(prototypeValue)->attemptToInterceptPutByIndexOnHoleForPrototype(globalObject, this, i, value, shouldThrow, putResult));
}
template<IndexingType indexingShape>
bool JSObject::putByIndexBeyondVectorLengthWithoutAttributes(JSGlobalObject* globalObject, unsigned i, JSValue value)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(!isCopyOnWrite(indexingMode()));
ASSERT((indexingType() & IndexingShapeMask) == indexingShape);
ASSERT(!indexingShouldBeSparse());
Butterfly* butterfly = m_butterfly.get();
// For us to get here, the index is either greater than the public length, or greater than
// or equal to the vector length.
ASSERT(i >= butterfly->vectorLength());
if (i > MAX_STORAGE_VECTOR_INDEX
|| (i >= MIN_SPARSE_ARRAY_INDEX && !isDenseEnoughForVector(i, countElements<indexingShape>(butterfly)))
|| indexIsSufficientlyBeyondLengthForSparseMap(i, butterfly->vectorLength())) {
ASSERT(i <= MAX_ARRAY_INDEX);
ensureArrayStorageSlow(vm);
SparseArrayValueMap* map = allocateSparseIndexMap(vm);
bool result = map->putEntry(globalObject, this, i, value, false);
RETURN_IF_EXCEPTION(scope, false);
ASSERT(i >= arrayStorage()->length());
arrayStorage()->setLength(i + 1);
return result;
}
if (!ensureLength(vm, i + 1)) {
throwOutOfMemoryError(globalObject, scope);
return false;
}
butterfly = m_butterfly.get();
RELEASE_ASSERT(i < butterfly->vectorLength());
switch (indexingShape) {
case Int32Shape:
ASSERT(value.isInt32());
butterfly->contiguous().at(this, i).setWithoutWriteBarrier(value);
return true;
case DoubleShape: {
ASSERT(Options::allowDoubleShape());
ASSERT(value.isNumber());
double valueAsDouble = value.asNumber();
ASSERT(valueAsDouble == valueAsDouble);
butterfly->contiguousDouble().at(this, i) = valueAsDouble;
return true;
}
case ContiguousShape:
butterfly->contiguous().at(this, i).set(vm, this, value);
return true;
default:
CRASH();
return false;
}
}
// Explicit instantiations needed by JSArray.cpp.
template bool JSObject::putByIndexBeyondVectorLengthWithoutAttributes<Int32Shape>(JSGlobalObject*, unsigned, JSValue);
template bool JSObject::putByIndexBeyondVectorLengthWithoutAttributes<DoubleShape>(JSGlobalObject*, unsigned, JSValue);
template bool JSObject::putByIndexBeyondVectorLengthWithoutAttributes<ContiguousShape>(JSGlobalObject*, unsigned, JSValue);
bool JSObject::putByIndexBeyondVectorLengthWithArrayStorage(JSGlobalObject* globalObject, unsigned i, JSValue value, bool shouldThrow, ArrayStorage* storage)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
ASSERT(!isCopyOnWrite(indexingMode()));
// i should be a valid array index that is outside of the current vector.
ASSERT(i <= MAX_ARRAY_INDEX);
ASSERT(i >= storage->vectorLength());
SparseArrayValueMap* map = storage->m_sparseMap.get();
// First, handle cases where we don't currently have a sparse map.
if (LIKELY(!map)) {
// If the array is not extensible, we should have entered dictionary mode, and created the sparse map.
ASSERT(isStructureExtensible());
// Update m_length if necessary.
if (i >= storage->length())
storage->setLength(i + 1);
// Check that it is sensible to still be using a vector, and then try to grow the vector.
if (LIKELY(!indexIsSufficientlyBeyondLengthForSparseMap(i, storage->vectorLength())
&& isDenseEnoughForVector(i, storage->m_numValuesInVector)
&& increaseVectorLength(vm, i + 1))) {
// success! - reread m_storage since it has likely been reallocated, and store to the vector.
storage = arrayStorage();
storage->m_vector[i].set(vm, this, value);
++storage->m_numValuesInVector;
return true;
}
// We don't want to, or can't use a vector to hold this property - allocate a sparse map & add the value.
map = allocateSparseIndexMap(vm);
RELEASE_AND_RETURN(scope, map->putEntry(globalObject, this, i, value, shouldThrow));
}
// Update m_length if necessary.
unsigned length = storage->length();
if (i >= length) {
// Prohibit growing the array if length is not writable.
if (map->lengthIsReadOnly() || !isStructureExtensible())
return typeError(globalObject, scope, shouldThrow, ReadonlyPropertyWriteError);
length = i + 1;
storage->setLength(length);
}
// We are currently using a map - check whether we still want to be doing so.
// We will continue to use a sparse map if SparseMode is set, a vector would be too sparse, or if allocation fails.
unsigned numValuesInArray = storage->m_numValuesInVector + map->size();
if (map->sparseMode() || !isDenseEnoughForVector(length, numValuesInArray) || !increaseVectorLength(vm, length))
RELEASE_AND_RETURN(scope, map->putEntry(globalObject, this, i, value, shouldThrow));
// Reread m_storage after increaseVectorLength, update m_numValuesInVector.
storage = arrayStorage();
storage->m_numValuesInVector = numValuesInArray;
// Copy all values from the map into the vector, and delete the map.
WriteBarrier<Unknown>* vector = storage->m_vector;
SparseArrayValueMap::const_iterator end = map->end();
for (SparseArrayValueMap::const_iterator it = map->begin(); it != end; ++it)
vector[it->key].set(vm, this, it->value.getNonSparseMode());
deallocateSparseIndexMap();
// Store the new property into the vector.
WriteBarrier<Unknown>& valueSlot = vector[i];
if (!valueSlot)
++storage->m_numValuesInVector;
valueSlot.set(vm, this, value);
return true;
}
bool JSObject::putByIndexBeyondVectorLength(JSGlobalObject* globalObject, unsigned i, JSValue value, bool shouldThrow)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(!isCopyOnWrite(indexingMode()));
// i should be a valid array index that is outside of the current vector.
ASSERT(i <= MAX_ARRAY_INDEX);
switch (indexingType()) {
case ALL_BLANK_INDEXING_TYPES: {
if (indexingShouldBeSparse()) {
auto* arrayStorage = ensureArrayStorageExistsAndEnterDictionaryIndexingMode(vm);
if (LIKELY(!hasSlowPutArrayStorage(indexingType())))
RELEASE_AND_RETURN(scope, putByIndexBeyondVectorLengthWithArrayStorage(globalObject, i, value, shouldThrow, arrayStorage));
} else if (indexIsSufficientlyBeyondLengthForSparseMap(i, 0) || i >= MIN_SPARSE_ARRAY_INDEX) {
auto* arrayStorage = createArrayStorage(vm, 0, 0);
if (LIKELY(!hasSlowPutArrayStorage(indexingType())))
RELEASE_AND_RETURN(scope, putByIndexBeyondVectorLengthWithArrayStorage(globalObject, i, value, shouldThrow, arrayStorage));
} else if (UNLIKELY(needsSlowPutIndexing())) {
// Convert the indexing type to the SlowPutArrayStorage and retry.
createArrayStorage(vm, i + 1, getNewVectorLength(0, 0, 0, i + 1));
} else {
createInitialForValueAndSet(vm, i, value);
return true;
}
// Fallback with SlowPutArrayStorage.
RELEASE_AND_RETURN(scope, putByIndex(this, globalObject, i, value, shouldThrow));
}
case ALL_UNDECIDED_INDEXING_TYPES: {
CRASH();
break;
}
case ALL_INT32_INDEXING_TYPES:
RELEASE_AND_RETURN(scope, putByIndexBeyondVectorLengthWithoutAttributes<Int32Shape>(globalObject, i, value));
case ALL_DOUBLE_INDEXING_TYPES:
ASSERT(Options::allowDoubleShape());
RELEASE_AND_RETURN(scope, putByIndexBeyondVectorLengthWithoutAttributes<DoubleShape>(globalObject, i, value));
case ALL_CONTIGUOUS_INDEXING_TYPES:
RELEASE_AND_RETURN(scope, putByIndexBeyondVectorLengthWithoutAttributes<ContiguousShape>(globalObject, i, value));
case NonArrayWithSlowPutArrayStorage:
case ArrayWithSlowPutArrayStorage: {
// No own property present in the vector, but there might be in the sparse map!
SparseArrayValueMap* map = arrayStorage()->m_sparseMap.get();
bool putResult = false;
if (!(map && map->contains(i))) {
bool result = attemptToInterceptPutByIndexOnHole(globalObject, i, value, shouldThrow, putResult);
RETURN_IF_EXCEPTION(scope, false);
if (result)
return putResult;
}
FALLTHROUGH;
}
case NonArrayWithArrayStorage:
case ArrayWithArrayStorage:
RELEASE_AND_RETURN(scope, putByIndexBeyondVectorLengthWithArrayStorage(globalObject, i, value, shouldThrow, arrayStorage()));
default:
RELEASE_ASSERT_NOT_REACHED();
}
return false;
}
bool JSObject::putDirectIndexBeyondVectorLengthWithArrayStorage(JSGlobalObject* globalObject, unsigned i, JSValue value, unsigned attributes, PutDirectIndexMode mode, ArrayStorage* storage)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
// i should be a valid array index that is outside of the current vector.
ASSERT(hasAnyArrayStorage(indexingType()));
ASSERT(arrayStorage() == storage);
ASSERT(i >= storage->vectorLength() || attributes);
ASSERT(i <= MAX_ARRAY_INDEX);
SparseArrayValueMap* map = storage->m_sparseMap.get();
// First, handle cases where we don't currently have a sparse map.
if (LIKELY(!map)) {
// If the array is not extensible, we should have entered dictionary mode, and created the spare map.
ASSERT(isStructureExtensible());
// Update m_length if necessary.
if (i >= storage->length())
storage->setLength(i + 1);
// Check that it is sensible to still be using a vector, and then try to grow the vector.
if (LIKELY(
!attributes
&& (isDenseEnoughForVector(i, storage->m_numValuesInVector))
&& !indexIsSufficientlyBeyondLengthForSparseMap(i, storage->vectorLength()))
&& increaseVectorLength(vm, i + 1)) {
// success! - reread m_storage since it has likely been reallocated, and store to the vector.
storage = arrayStorage();
storage->m_vector[i].set(vm, this, value);
++storage->m_numValuesInVector;
return true;
}
// We don't want to, or can't use a vector to hold this property - allocate a sparse map & add the value.
map = allocateSparseIndexMap(vm);
RELEASE_AND_RETURN(scope, map->putDirect(globalObject, this, i, value, attributes, mode));
}
// Update m_length if necessary.
unsigned length = storage->length();
if (i >= length) {
if (mode != PutDirectIndexLikePutDirect) {
// Prohibit growing the array if length is not writable.
if (map->lengthIsReadOnly())
return typeError(globalObject, scope, mode == PutDirectIndexShouldThrow, ReadonlyPropertyWriteError);
if (!isStructureExtensible())
return typeError(globalObject, scope, mode == PutDirectIndexShouldThrow, NonExtensibleObjectPropertyDefineError);
}
length = i + 1;
storage->setLength(length);
}
// We are currently using a map - check whether we still want to be doing so.
// We will continue to use a sparse map if SparseMode is set, a vector would be too sparse, or if allocation fails.
unsigned numValuesInArray = storage->m_numValuesInVector + map->size();
if (map->sparseMode() || attributes || !isDenseEnoughForVector(length, numValuesInArray) || !increaseVectorLength(vm, length))
RELEASE_AND_RETURN(scope, map->putDirect(globalObject, this, i, value, attributes, mode));
// Reread m_storage after increaseVectorLength, update m_numValuesInVector.
storage = arrayStorage();
storage->m_numValuesInVector = numValuesInArray;
// Copy all values from the map into the vector, and delete the map.
WriteBarrier<Unknown>* vector = storage->m_vector;
SparseArrayValueMap::const_iterator end = map->end();
for (SparseArrayValueMap::const_iterator it = map->begin(); it != end; ++it)
vector[it->key].set(vm, this, it->value.getNonSparseMode());
deallocateSparseIndexMap();
// Store the new property into the vector.
WriteBarrier<Unknown>& valueSlot = vector[i];
if (!valueSlot)
++storage->m_numValuesInVector;
valueSlot.set(vm, this, value);
return true;
}
bool JSObject::putDirectIndexSlowOrBeyondVectorLength(JSGlobalObject* globalObject, unsigned i, JSValue value, unsigned attributes, PutDirectIndexMode mode)
{
VM& vm = globalObject->vm();
ASSERT(!value.isCustomGetterSetter());
if (!canDoFastPutDirectIndex(this)) {
PropertyDescriptor descriptor;
descriptor.setDescriptor(value, attributes);
return methodTable()->defineOwnProperty(this, globalObject, Identifier::from(vm, i), descriptor, mode == PutDirectIndexShouldThrow);
}
// i should be a valid array index that is outside of the current vector.
ASSERT(i <= MAX_ARRAY_INDEX);
if (attributes & (PropertyAttribute::ReadOnly | PropertyAttribute::Accessor))
notifyPresenceOfIndexedAccessors(vm);
switch (indexingType()) {
case ALL_BLANK_INDEXING_TYPES: {
if (indexingShouldBeSparse() || attributes) {
return putDirectIndexBeyondVectorLengthWithArrayStorage(
globalObject, i, value, attributes, mode,
ensureArrayStorageExistsAndEnterDictionaryIndexingMode(vm));
}
if (indexIsSufficientlyBeyondLengthForSparseMap(i, 0) || i >= MIN_SPARSE_ARRAY_INDEX) {
return putDirectIndexBeyondVectorLengthWithArrayStorage(
globalObject, i, value, attributes, mode, createArrayStorage(vm, 0, 0));
}
if (UNLIKELY(needsSlowPutIndexing())) {
ArrayStorage* storage = createArrayStorage(vm, i + 1, getNewVectorLength(0, 0, 0, i + 1));
storage->m_vector[i].set(vm, this, value);
storage->m_numValuesInVector++;
return true;
}
createInitialForValueAndSet(vm, i, value);
return true;
}
case ALL_UNDECIDED_INDEXING_TYPES: {
convertUndecidedForValue(vm, value);
// Reloop.
return putDirectIndex(globalObject, i, value, attributes, mode);
}
case ALL_INT32_INDEXING_TYPES: {
ASSERT(!indexingShouldBeSparse());
if (attributes)
return putDirectIndexBeyondVectorLengthWithArrayStorage(globalObject, i, value, attributes, mode, ensureArrayStorageExistsAndEnterDictionaryIndexingMode(vm));
if (!value.isInt32()) {
convertInt32ForValue(vm, value);
return putDirectIndexSlowOrBeyondVectorLength(globalObject, i, value, attributes, mode);
}
putByIndexBeyondVectorLengthWithoutAttributes<Int32Shape>(globalObject, i, value);
return true;
}
case ALL_DOUBLE_INDEXING_TYPES: {
ASSERT(Options::allowDoubleShape());
ASSERT(!indexingShouldBeSparse());
if (attributes)
return putDirectIndexBeyondVectorLengthWithArrayStorage(globalObject, i, value, attributes, mode, ensureArrayStorageExistsAndEnterDictionaryIndexingMode(vm));
if (!value.isNumber()) {
convertDoubleToContiguous(vm);
return putDirectIndexSlowOrBeyondVectorLength(globalObject, i, value, attributes, mode);
}
double valueAsDouble = value.asNumber();
if (valueAsDouble != valueAsDouble) {
convertDoubleToContiguous(vm);
return putDirectIndexSlowOrBeyondVectorLength(globalObject, i, value, attributes, mode);
}
putByIndexBeyondVectorLengthWithoutAttributes<DoubleShape>(globalObject, i, value);
return true;
}
case ALL_CONTIGUOUS_INDEXING_TYPES: {
ASSERT(!indexingShouldBeSparse());
if (attributes)
return putDirectIndexBeyondVectorLengthWithArrayStorage(globalObject, i, value, attributes, mode, ensureArrayStorageExistsAndEnterDictionaryIndexingMode(vm));
putByIndexBeyondVectorLengthWithoutAttributes<ContiguousShape>(globalObject, i, value);
return true;
}
case ALL_ARRAY_STORAGE_INDEXING_TYPES:
if (attributes)
return putDirectIndexBeyondVectorLengthWithArrayStorage(globalObject, i, value, attributes, mode, ensureArrayStorageExistsAndEnterDictionaryIndexingMode(vm));
return putDirectIndexBeyondVectorLengthWithArrayStorage(globalObject, i, value, attributes, mode, arrayStorage());
default:
RELEASE_ASSERT_NOT_REACHED();
return false;
}
}
bool JSObject::putDirectNativeIntrinsicGetter(VM& vm, JSGlobalObject* globalObject, Identifier name, NativeFunction nativeFunction, Intrinsic intrinsic, unsigned attributes)
{
JSFunction* function = JSFunction::create(vm, globalObject, 0, makeString("get "_s, name.string()), nativeFunction, ImplementationVisibility::Public, intrinsic);
GetterSetter* accessor = GetterSetter::create(vm, globalObject, function, nullptr);
return putDirectNonIndexAccessor(vm, name, accessor, attributes);
}
void JSObject::putDirectNativeIntrinsicGetterWithoutTransition(VM& vm, JSGlobalObject* globalObject, Identifier name, NativeFunction nativeFunction, Intrinsic intrinsic, unsigned attributes)
{
JSFunction* function = JSFunction::create(vm, globalObject, 0, makeString("get "_s, name.string()), nativeFunction, ImplementationVisibility::Public, intrinsic);
GetterSetter* accessor = GetterSetter::create(vm, globalObject, function, nullptr);
putDirectNonIndexAccessorWithoutTransition(vm, name, accessor, attributes);
}
bool JSObject::putDirectNativeFunction(VM& vm, JSGlobalObject* globalObject, const PropertyName& propertyName, unsigned functionLength, NativeFunction nativeFunction, ImplementationVisibility implementationVisibility, Intrinsic intrinsic, unsigned attributes)
{
StringImpl* name = propertyName.publicName();
if (!name)
name = vm.propertyNames->anonymous.impl();
ASSERT(name);
JSFunction* function = JSFunction::create(vm, globalObject, functionLength, name, nativeFunction, implementationVisibility, intrinsic);
return putDirect(vm, propertyName, function, attributes);
}
bool JSObject::putDirectNativeFunction(VM& vm, JSGlobalObject* globalObject, const PropertyName& propertyName, unsigned functionLength, NativeFunction nativeFunction, ImplementationVisibility implementationVisibility, Intrinsic intrinsic, const DOMJIT::Signature* signature, unsigned attributes)
{
StringImpl* name = propertyName.publicName();
if (!name)
name = vm.propertyNames->anonymous.impl();
ASSERT(name);
JSFunction* function = JSFunction::create(vm, globalObject, functionLength, name, nativeFunction, implementationVisibility, intrinsic, callHostFunctionAsConstructor, signature);
return putDirect(vm, propertyName, function, attributes);
}
void JSObject::putDirectNativeFunctionWithoutTransition(VM& vm, JSGlobalObject* globalObject, const PropertyName& propertyName, unsigned functionLength, NativeFunction nativeFunction, ImplementationVisibility implementationVisibility, Intrinsic intrinsic, unsigned attributes)
{
StringImpl* name = propertyName.publicName();
if (!name)
name = vm.propertyNames->anonymous.impl();
ASSERT(name);
JSFunction* function = JSFunction::create(vm, globalObject, functionLength, name, nativeFunction, implementationVisibility, intrinsic);
putDirectWithoutTransition(vm, propertyName, function, attributes);
}
JSFunction* JSObject::putDirectBuiltinFunction(VM& vm, JSGlobalObject* globalObject, const PropertyName& propertyName, FunctionExecutable* functionExecutable, unsigned attributes)
{
StringImpl* name = propertyName.publicName();
if (!name)
name = vm.propertyNames->anonymous.impl();
ASSERT(name);
JSFunction* function = JSFunction::create(vm, globalObject, static_cast<FunctionExecutable*>(functionExecutable), globalObject);
putDirect(vm, propertyName, function, attributes);
return function;
}
JSFunction* JSObject::putDirectBuiltinFunctionWithoutTransition(VM& vm, JSGlobalObject* globalObject, const PropertyName& propertyName, FunctionExecutable* functionExecutable, unsigned attributes)
{
JSFunction* function = JSFunction::create(vm, globalObject, static_cast<FunctionExecutable*>(functionExecutable), globalObject);
putDirectWithoutTransition(vm, propertyName, function, attributes);
return function;
}
// NOTE: This method is for ArrayStorage vectors.
ALWAYS_INLINE unsigned JSObject::getNewVectorLength(unsigned indexBias, unsigned currentVectorLength, unsigned currentLength, unsigned desiredLength)
{
ASSERT(desiredLength <= MAX_STORAGE_VECTOR_LENGTH);
unsigned increasedLength;
unsigned maxInitLength = std::min(currentLength, 100000U);
if (desiredLength < maxInitLength)
increasedLength = maxInitLength;
else if (!currentVectorLength)
increasedLength = std::max(desiredLength, lastArraySize);
else {
increasedLength = timesThreePlusOneDividedByTwo(desiredLength);
}
ASSERT(increasedLength >= desiredLength);
lastArraySize = std::min(increasedLength, FIRST_ARRAY_STORAGE_VECTOR_GROW);
return ArrayStorage::optimalVectorLength(
indexBias, structure()->outOfLineCapacity(),
std::min(increasedLength, MAX_STORAGE_VECTOR_LENGTH));
}
ALWAYS_INLINE unsigned JSObject::getNewVectorLength(unsigned desiredLength)
{
unsigned indexBias = 0;
unsigned vectorLength = 0;
unsigned length = 0;
if (hasIndexedProperties(indexingType())) {
if (ArrayStorage* storage = arrayStorageOrNull())
indexBias = storage->m_indexBias;
vectorLength = m_butterfly->vectorLength();
length = m_butterfly->publicLength();
}
return getNewVectorLength(indexBias, vectorLength, length, desiredLength);
}
template<IndexingType indexingShape>
unsigned JSObject::countElements(Butterfly* butterfly)
{
unsigned numValues = 0;
for (unsigned i = butterfly->publicLength(); i--;) {
switch (indexingShape) {
case Int32Shape:
case ContiguousShape:
if (butterfly->contiguous().at(this, i))
numValues++;
break;
case DoubleShape: {
ASSERT(Options::allowDoubleShape());
double value = butterfly->contiguousDouble().at(this, i);
if (value == value)
numValues++;
break;
}
default:
CRASH();
}
}
return numValues;
}
unsigned JSObject::countElements()
{
switch (indexingType()) {
case ALL_BLANK_INDEXING_TYPES:
case ALL_UNDECIDED_INDEXING_TYPES:
return 0;
case ALL_INT32_INDEXING_TYPES:
return countElements<Int32Shape>(butterfly());
case ALL_DOUBLE_INDEXING_TYPES:
ASSERT(Options::allowDoubleShape());
return countElements<DoubleShape>(butterfly());
case ALL_CONTIGUOUS_INDEXING_TYPES:
return countElements<ContiguousShape>(butterfly());
default:
CRASH();
return 0;
}
}
bool JSObject::increaseVectorLength(VM& vm, unsigned newLength)
{
ArrayStorage* storage = arrayStorage();
unsigned vectorLength = storage->vectorLength();
unsigned availableVectorLength = storage->availableVectorLength(structure(), vectorLength);
if (availableVectorLength >= newLength) {
// The cell was already big enough for the desired length!
for (unsigned i = vectorLength; i < availableVectorLength; ++i)
storage->m_vector[i].clear();
storage->setVectorLength(availableVectorLength);
return true;
}
// This function leaves the array in an internally inconsistent state, because it does not move any values from sparse value map
// to the vector. Callers have to account for that, because they can do it more efficiently.
if (newLength > MAX_STORAGE_VECTOR_LENGTH)
return false;
if (newLength >= MIN_SPARSE_ARRAY_INDEX
&& !isDenseEnoughForVector(newLength, storage->m_numValuesInVector))
return false;
unsigned indexBias = storage->m_indexBias;
ASSERT(newLength > vectorLength);
unsigned newVectorLength = getNewVectorLength(newLength);
// Fast case - there is no precapacity. In these cases a realloc makes sense.
Structure* structure = this->structure();
if (LIKELY(!indexBias)) {
DeferGC deferGC(vm);
Butterfly* newButterfly = storage->butterfly()->growArrayRight(
vm, this, structure, structure->outOfLineCapacity(), true,
ArrayStorage::sizeFor(vectorLength), ArrayStorage::sizeFor(newVectorLength));
if (!newButterfly)
return false;
for (unsigned i = vectorLength; i < newVectorLength; ++i)
newButterfly->arrayStorage()->m_vector[i].clear();
newButterfly->arrayStorage()->setVectorLength(newVectorLength);
setButterfly(vm, newButterfly);
return true;
}
// Remove some, but not all of the precapacity. Atomic decay, & capped to not overflow array length.
DeferGC deferGC(vm);
unsigned newIndexBias = std::min(indexBias >> 1, MAX_STORAGE_VECTOR_LENGTH - newVectorLength);
Butterfly* newButterfly = storage->butterfly()->resizeArray(
vm, this,
structure->outOfLineCapacity(), true, ArrayStorage::sizeFor(vectorLength),
newIndexBias, true, ArrayStorage::sizeFor(newVectorLength));
if (!newButterfly)
return false;
for (unsigned i = vectorLength; i < newVectorLength; ++i)
newButterfly->arrayStorage()->m_vector[i].clear();
newButterfly->arrayStorage()->setVectorLength(newVectorLength);
newButterfly->arrayStorage()->m_indexBias = newIndexBias;
setButterfly(vm, newButterfly);
return true;
}
bool JSObject::ensureLengthSlow(VM& vm, unsigned length)
{
if (isCopyOnWrite(indexingMode())) {
convertFromCopyOnWrite(vm);
if (m_butterfly->vectorLength() >= length)
return true;
}
Butterfly* butterfly = this->butterfly();
ASSERT(length <= MAX_STORAGE_VECTOR_LENGTH);
ASSERT(hasContiguous(indexingType()) || hasInt32(indexingType()) || hasDouble(indexingType()) || hasUndecided(indexingType()));
ASSERT(length > butterfly->vectorLength());
unsigned oldVectorLength = butterfly->vectorLength();
unsigned newVectorLength;
Structure* structure = this->structure();
unsigned propertyCapacity = structure->outOfLineCapacity();
GCDeferralContext deferralContext(vm);
AssertNoGC assertNoGC;
unsigned availableOldLength =
Butterfly::availableContiguousVectorLength(propertyCapacity, oldVectorLength);
Butterfly* newButterfly = nullptr;
if (availableOldLength >= length) {
// This is the case where someone else selected a vector length that caused internal
// fragmentation. If we did our jobs right, this would never happen. But I bet we will mess
// this up, so this defense should stay.
newVectorLength = availableOldLength;
} else {
newVectorLength = Butterfly::optimalContiguousVectorLength(
propertyCapacity, std::min(length * 2, MAX_STORAGE_VECTOR_LENGTH));
butterfly = butterfly->reallocArrayRightIfPossible(
vm, deferralContext, this, structure, propertyCapacity, true,
oldVectorLength * sizeof(EncodedJSValue),
newVectorLength * sizeof(EncodedJSValue));
if (!butterfly)
return false;
newButterfly = butterfly;
}
if (hasDouble(indexingType())) {
for (unsigned i = oldVectorLength; i < newVectorLength; ++i)
butterfly->indexingPayload<double>()[i] = PNaN;
} else {
for (unsigned i = oldVectorLength; i < newVectorLength; ++i)
butterfly->indexingPayload<WriteBarrier<Unknown>>()[i].clear();
}
if (newButterfly) {
butterfly->setVectorLength(newVectorLength);
WTF::storeStoreFence();
m_butterfly.set(vm, this, newButterfly);
} else {
WTF::storeStoreFence();
butterfly->setVectorLength(newVectorLength);
}
return true;
}
void JSObject::reallocateAndShrinkButterfly(VM& vm, unsigned length)
{
ASSERT(length <= MAX_STORAGE_VECTOR_LENGTH);
ASSERT(hasContiguous(indexingType()) || hasInt32(indexingType()) || hasDouble(indexingType()) || hasUndecided(indexingType()));
ASSERT(m_butterfly->vectorLength() > length);
ASSERT(m_butterfly->publicLength() >= length);
ASSERT(!m_butterfly->indexingHeader()->preCapacity(structure()));
DeferGC deferGC(vm);
Butterfly* newButterfly = butterfly()->resizeArray(vm, this, structure(), 0, ArrayStorage::sizeFor(length));
newButterfly->setVectorLength(length);
newButterfly->setPublicLength(length);
WTF::storeStoreFence();
m_butterfly.set(vm, this, newButterfly);
}
Butterfly* JSObject::allocateMoreOutOfLineStorage(VM& vm, size_t oldSize, size_t newSize)
{
ASSERT(newSize > oldSize);
// It's important that this function not rely on structure(), for the property
// capacity, since we might have already mutated the structure in-place.
return Butterfly::createOrGrowPropertyStorage(butterfly(), vm, this, structure(), oldSize, newSize);
}
bool JSObject::getOwnPropertyDescriptor(JSGlobalObject* globalObject, PropertyName propertyName, PropertyDescriptor& descriptor)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
PropertySlot slot(this, PropertySlot::InternalMethodType::GetOwnProperty);
bool result = methodTable()->getOwnPropertySlot(this, globalObject, propertyName, slot);
EXCEPTION_ASSERT_UNUSED(scope, !scope.exception() || !result);
if (!result)
return false;
RELEASE_AND_RETURN(scope, descriptor.setPropertySlot(globalObject, propertyName, slot));
}
bool JSObject::putDirectMayBeIndex(JSGlobalObject* globalObject, PropertyName propertyName, JSValue value)
{
if (std::optional<uint32_t> index = parseIndex(propertyName))
return putDirectIndex(globalObject, index.value(), value);
return putDirect(globalObject->vm(), propertyName, value);
}
// https://tc39.es/ecma262/#sec-validateandapplypropertydescriptor
bool validateAndApplyPropertyDescriptor(JSGlobalObject* globalObject, JSObject* object, PropertyName propertyName, bool isExtensible,
const PropertyDescriptor& descriptor, bool isCurrentDefined, const PropertyDescriptor& current, bool throwException)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
// If we have a new property we can just put it on normally
// Step 2.
if (!isCurrentDefined) {
// unless extensions are prevented!
// Step 2.a
if (!isExtensible)
return typeError(globalObject, scope, throwException, NonExtensibleObjectPropertyDefineError);
if (object) {
if (descriptor.isAccessorDescriptor()) {
unsigned attributes = (descriptor.attributes() | PropertyAttribute::Accessor) & ~PropertyAttribute::ReadOnly;
object->putDirectAccessor(globalObject, propertyName, descriptor.slowGetterSetter(globalObject), attributes);
} else {
ASSERT(descriptor.isGenericDescriptor() || descriptor.isDataDescriptor());
JSValue value = descriptor.value() ? descriptor.value() : jsUndefined();
object->putDirect(vm, propertyName, value, descriptor.attributes() & ~PropertyAttribute::Accessor);
}
}
return true;
}
// Step 3.
if (descriptor.isEmpty())
return true;
bool isEqual = current.equalTo(globalObject, descriptor);
RETURN_IF_EXCEPTION(scope, false);
if (isEqual)
return true;
// Step 4.
if (!current.configurable()) {
if (descriptor.configurable())
return typeError(globalObject, scope, throwException, UnconfigurablePropertyChangeConfigurabilityError);
if (descriptor.enumerablePresent() && descriptor.enumerable() != current.enumerable())
return typeError(globalObject, scope, throwException, UnconfigurablePropertyChangeEnumerabilityError);
}
if (descriptor.isGenericDescriptor()) {
// Step 5.
// Changing [[Enumerable]] and [[Configurable]] attributes of an existing property
} else if (current.isDataDescriptor() != descriptor.isDataDescriptor()) {
// Step 6.
// Changing between a data property and accessor property
if (!current.configurable())
return typeError(globalObject, scope, throwException, UnconfigurablePropertyChangeAccessMechanismError);
} else if (current.isDataDescriptor() && descriptor.isDataDescriptor()) {
// Step 7.
// Changing the value and attributes of an existing data property
if (!current.configurable() && !current.writable()) {
if (descriptor.writable())
return typeError(globalObject, scope, throwException, UnconfigurablePropertyChangeWritabilityError);
if (descriptor.value()) {
bool isSame = sameValue(globalObject, descriptor.value(), current.value());
RETURN_IF_EXCEPTION(scope, false);
if (!isSame)
return typeError(globalObject, scope, throwException, ReadonlyPropertyChangeError);
}
return true;
}
} else {
// Step 8.
// Changing the accessor functions and attributes of an existing accessor property
ASSERT(descriptor.isAccessorDescriptor());
if (!current.configurable()) {
if (descriptor.setterPresent() && descriptor.setter() != current.setter())
return typeError(globalObject, scope, throwException, "Attempting to change the setter of an unconfigurable property."_s);
if (descriptor.getterPresent() && descriptor.getter() != current.getter())
return typeError(globalObject, scope, throwException, "Attempting to change the getter of an unconfigurable property."_s);
return true;
}
}
if (!object)
return true;
// Step 9.
unsigned attributes = descriptor.attributesOverridingCurrent(current);
if (descriptor.isAccessorDescriptor() || (current.isAccessorDescriptor() && !descriptor.isDataDescriptor())) {
ASSERT(attributes & PropertyAttribute::Accessor);
JSObject* getter = descriptor.getterPresent() ? descriptor.getterObject() : (current.getterPresent() ? current.getterObject() : nullptr);
JSObject* setter = descriptor.setterPresent() ? descriptor.setterObject() : (current.setterPresent() ? current.setterObject() : nullptr);
GetterSetter* getterSetter = GetterSetter::create(vm, globalObject, getter, setter);
object->putDirectAccessor(globalObject, propertyName, getterSetter, attributes & ~PropertyAttribute::ReadOnly);
} else {
ASSERT(descriptor.isGenericDescriptor() || descriptor.isDataDescriptor());
JSValue value = descriptor.value() ? descriptor.value() : (current.value() ? current.value() : jsUndefined());
object->putDirect(vm, propertyName, value, attributes & ~PropertyAttribute::Accessor);
}
return true;
}
bool JSObject::defineOwnNonIndexProperty(JSGlobalObject* globalObject, PropertyName propertyName, const PropertyDescriptor& descriptor, bool throwException)
{
VM& vm = globalObject->vm();
auto throwScope = DECLARE_THROW_SCOPE(vm);
PropertyDescriptor current;
bool isCurrentDefined = getOwnPropertyDescriptor(globalObject, propertyName, current);
RETURN_IF_EXCEPTION(throwScope, false);
bool isExtensible = this->isExtensible(globalObject);
RETURN_IF_EXCEPTION(throwScope, false);
RELEASE_AND_RETURN(throwScope, validateAndApplyPropertyDescriptor(globalObject, this, propertyName, isExtensible, descriptor, isCurrentDefined, current, throwException));
}
bool JSObject::defineOwnProperty(JSObject* object, JSGlobalObject* globalObject, PropertyName propertyName, const PropertyDescriptor& descriptor, bool throwException)
{
// If it's an array index, then use the indexed property storage.
if (std::optional<uint32_t> index = parseIndex(propertyName)) {
// c. Let succeeded be the result of calling the default [[DefineOwnProperty]] internal method (8.12.9) on A passing P, Desc, and false as arguments.
// d. Reject if succeeded is false.
// e. If index >= oldLen
// e.i. Set oldLenDesc.[[Value]] to index + 1.
// e.ii. Call the default [[DefineOwnProperty]] internal method (8.12.9) on A passing "length", oldLenDesc, and false as arguments. This call will always return true.
// f. Return true.
return object->defineOwnIndexedProperty(globalObject, index.value(), descriptor, throwException);
}
return object->defineOwnNonIndexProperty(globalObject, propertyName, descriptor, throwException);
}
void JSObject::convertToDictionary(VM& vm)
{
Structure* oldStructure = structure();
DeferredStructureTransitionWatchpointFire deferredWatchpointFire(vm, oldStructure);
setStructure(vm, Structure::toCacheableDictionaryTransition(vm, oldStructure, &deferredWatchpointFire));
}
void JSObject::convertToUncacheableDictionary(VM& vm)
{
Structure* oldStructure = structure();
if (oldStructure->isUncacheableDictionary())
return;
DeferredStructureTransitionWatchpointFire deferredWatchpointFire(vm, oldStructure);
setStructure(vm, Structure::toUncacheableDictionaryTransition(vm, oldStructure, &deferredWatchpointFire));
if (UNLIKELY(mayBePrototype()))
vm.invalidateStructureChainIntegrity(VM::StructureChainIntegrityEvent::Change);
}
void JSObject::shiftButterflyAfterFlattening(const GCSafeConcurrentJSLocker&, VM& vm, Structure* structure, size_t outOfLineCapacityAfter)
{
// This could interleave visitChildren because some old structure could have been a non
// dictionary structure. We have to be crazy careful. But, we are guaranteed to be holding
// the structure's lock right now, and that helps a bit.
Butterfly* oldButterfly = this->butterfly();
size_t preCapacity;
size_t indexingPayloadSizeInBytes;
bool hasIndexingHeader = this->hasIndexingHeader();
if (UNLIKELY(hasIndexingHeader)) {
preCapacity = oldButterfly->indexingHeader()->preCapacity(structure);
indexingPayloadSizeInBytes = oldButterfly->indexingHeader()->indexingPayloadSizeInBytes(structure);
} else {
preCapacity = 0;
indexingPayloadSizeInBytes = 0;
}
Butterfly* newButterfly = Butterfly::createUninitialized(vm, this, preCapacity, outOfLineCapacityAfter, hasIndexingHeader, indexingPayloadSizeInBytes);
// No need to copy the precapacity.
void* currentBase = oldButterfly->base(0, outOfLineCapacityAfter);
void* newBase = newButterfly->base(0, outOfLineCapacityAfter);
// memcpy is fine since newButterfly is not tied to any object yet.
memcpy(static_cast<JSValue*>(newBase), static_cast<JSValue*>(currentBase), Butterfly::totalSize(0, outOfLineCapacityAfter, hasIndexingHeader, indexingPayloadSizeInBytes));
setButterfly(vm, newButterfly);
}
uint32_t JSObject::getEnumerableLength()
{
JSObject* object = this;
switch (object->indexingType()) {
case ALL_BLANK_INDEXING_TYPES:
case ALL_UNDECIDED_INDEXING_TYPES:
// Regardless of holesMustForwardToPrototype condition, it returns zero.
return 0;
case ALL_INT32_INDEXING_TYPES:
case ALL_CONTIGUOUS_INDEXING_TYPES: {
Butterfly* butterfly = object->butterfly();
unsigned enumerableLength = butterfly->publicLength();
if (!enumerableLength)
return 0;
if (object->structure()->holesMustForwardToPrototype(object))
return 0;
for (unsigned i = 0; i < enumerableLength; ++i) {
if (!butterfly->contiguous().at(object, i))
return 0;
}
return enumerableLength;
}
case ALL_DOUBLE_INDEXING_TYPES: {
Butterfly* butterfly = object->butterfly();
unsigned enumerableLength = butterfly->publicLength();
if (!enumerableLength)
return 0;
if (object->structure()->holesMustForwardToPrototype(object))
return 0;
for (unsigned i = 0; i < enumerableLength; ++i) {
double value = butterfly->contiguousDouble().at(object, i);
if (value != value)
return 0;
}
return enumerableLength;
}
case ALL_ARRAY_STORAGE_INDEXING_TYPES: {
ArrayStorage* storage = object->m_butterfly->arrayStorage();
if (storage->m_sparseMap.get())
return 0;
unsigned enumerableLength = std::min(storage->length(), storage->vectorLength());
if (!enumerableLength)
return 0;
if (object->structure()->holesMustForwardToPrototype(object))
return 0;
for (unsigned i = 0; i < enumerableLength; ++i) {
if (!storage->m_vector[i])
return 0;
}
return enumerableLength;
}
default:
RELEASE_ASSERT_NOT_REACHED();
return 0;
}
}
// Implements GetMethod(O, P) in section 7.3.9 of the spec.
// http://www.ecma-international.org/ecma-262/6.0/index.html#sec-getmethod
JSValue JSObject::getMethod(JSGlobalObject* globalObject, CallData& callData, const Identifier& ident, const String& errorMessage)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSValue method = get(globalObject, ident);
RETURN_IF_EXCEPTION(scope, JSValue());
if (!method.isCell()) {
if (method.isUndefinedOrNull())
return jsUndefined();
throwVMTypeError(globalObject, scope, errorMessage);
return jsUndefined();
}
callData = JSC::getCallData(method.asCell());
if (callData.type == CallData::Type::None) {
throwVMTypeError(globalObject, scope, errorMessage);
return jsUndefined();
}
return method;
}
bool JSObject::anyObjectInChainMayInterceptIndexedAccesses() const
{
for (const JSObject* current = this; ;) {
if (current->structure()->mayInterceptIndexedAccesses())
return true;
JSValue prototype = current->getPrototypeDirect();
if (prototype.isNull())
return false;
current = asObject(prototype);
}
}
bool JSObject::needsSlowPutIndexing() const
{
return anyObjectInChainMayInterceptIndexedAccesses() || globalObject()->isHavingABadTime();
}
TransitionKind JSObject::suggestedArrayStorageTransition() const
{
if (needsSlowPutIndexing())
return TransitionKind::AllocateSlowPutArrayStorage;
return TransitionKind::AllocateArrayStorage;
}
void JSObject::putOwnDataPropertyBatching(VM& vm, const RefPtr<UniquedStringImpl>* properties, const EncodedJSValue* values, unsigned size)
{
unsigned i = 0;
Structure* structure = this->structure();
if (!(structure->isDictionary() || (structure->transitionCountEstimate() + size) > Structure::s_maxTransitionLength || !structure->canPerformFastPropertyEnumerationCommon())) {
Vector<PropertyOffset, 16> offsets(size, [&](size_t index) -> std::optional<PropertyOffset> {
PropertyName propertyName(properties[index].get());
PropertyOffset offset;
if (Structure* newStructure = Structure::addPropertyTransitionToExistingStructure(structure, propertyName, 0, offset)) {
structure = newStructure;
return offset;
}
unsigned currentAttributes;
offset = structure->get(vm, propertyName, currentAttributes);
if (offset != invalidOffset) {
structure->didReplaceProperty(offset);
return offset;
}
// If we detect that this structure requires transition watchpoint firing, then we need to stop this batching and rest of the values
// should be put via generic way.
if (UNLIKELY(structure->transitionWatchpointSet().isBeingWatched() && structure->transitionWatchpointSet().isStillValid()))
return std::nullopt;
// It will go to the cacheable dictionary case. We stop the batching here and fall though to the generic case.
// We break here before adding offset to offsets since this property itself should be put via generic path.
if (UNLIKELY(structure->shouldDoCacheableDictionaryTransitionForAdd(PutPropertySlot::UnknownContext)))
return std::nullopt;
Structure* newStructure = Structure::addNewPropertyTransition(vm, structure, propertyName, 0, offset, PutPropertySlot::UnknownContext, nullptr);
validateOffset(offset);
ASSERT(newStructure->isValidOffset(offset));
structure = newStructure;
return offset;
});
// Flush batching here. Note that it is possible that offsets.size() is not equal to size, if we stop batching due to transition-watchpoint-firing.
Butterfly* newButterfly = butterfly();
auto* oldStructure = this->structure();
if (oldStructure->outOfLineCapacity() != structure->outOfLineCapacity()) {
ASSERT(structure != oldStructure);
newButterfly = allocateMoreOutOfLineStorage(vm, oldStructure->outOfLineCapacity(), structure->outOfLineCapacity());
nukeStructureAndSetButterfly(vm, StructureID::encode(oldStructure), newButterfly);
}
for (unsigned index = 0; index < offsets.size(); ++index)
putDirectOffset(vm, offsets[index], JSValue::decode(values[index]));
setStructure(vm, structure);
// We fall through to the generic case and consume the rest of put operations if batching stopped in the middle.
i = offsets.size();
if (mayBePrototype())
vm.invalidateStructureChainIntegrity(VM::StructureChainIntegrityEvent::Add);
}
for (; i < size; ++i) {
PutPropertySlot putPropertySlot(this, true);
putOwnDataProperty(vm, properties[i].get(), JSValue::decode(values[i]), putPropertySlot);
}
}
ASCIILiteral JSObject::putDirectToDictionaryWithoutExtensibility(VM& vm, PropertyName propertyName, JSValue value, PutPropertySlot& slot)
{
unsigned currentAttributes;
Structure* structure = this->structure();
PropertyOffset offset = structure->get(vm, propertyName, currentAttributes);
if (offset != invalidOffset) {
if (currentAttributes & PropertyAttribute::ReadOnlyOrAccessorOrCustomAccessor)
return ReadonlyPropertyChangeError;
putDirectOffset(vm, offset, value);
structure->didReplaceProperty(offset);
// FIXME: Check attributes against PropertyAttribute::CustomAccessorOrValue. Changing GetterSetter should work w/o transition.
// https://bugs.webkit.org/show_bug.cgi?id=214342
ASSERT(!(currentAttributes & PropertyAttribute::AccessorOrCustomAccessorOrValue));
slot.setExistingProperty(this, offset);
return { };
}
return NonExtensibleObjectPropertyDefineError;
}
NEVER_INLINE void JSObject::putDirectForJSONSlow(VM& vm, PropertyName propertyName, JSValue value)
{
PutPropertySlot slot(this);
putDirectInternal<PutModeDefineOwnPropertyForJSONSlow>(vm, propertyName, value, 0, slot);
}
} // namespace JSC
WTF_ALLOW_UNSAFE_BUFFER_USAGE_END
|