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
|
/*
Copyright (C) 2002-2014 Jeroen Frijters
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jeroen Frijters
jeroen@frijters.net
*/
using System;
using System.IO;
using System.Collections.Generic;
using IKVM.Attributes;
namespace IKVM.Internal
{
enum HardError : short
{
NoClassDefFoundError,
IllegalAccessError,
InstantiationError,
IncompatibleClassChangeError,
NoSuchFieldError,
AbstractMethodError,
NoSuchMethodError,
LinkageError,
// "exceptions" that are wrapped in an IncompatibleClassChangeError
IllegalAccessException,
// if an error is added here, it must also be added to MethodAnalyzer.SetHardError()
}
[Flags]
enum ClassFileParseOptions
{
None = 0,
LocalVariableTable = 1,
LineNumberTable = 2,
RelaxedClassNameValidation = 4,
TrustedAnnotations = 8,
}
sealed class ClassFile
{
private ConstantPoolItem[] constantpool;
// Modifiers is a ushort, so the next four fields combine into two 32 bit slots
private Modifiers access_flags;
private ushort this_class;
private ushort super_class;
private ushort flags;
private const ushort FLAG_MASK_MAJORVERSION = 0xFF;
private const ushort FLAG_MASK_DEPRECATED = 0x100;
private const ushort FLAG_MASK_INTERNAL = 0x200;
private const ushort FLAG_CALLERSENSITIVE = 0x400;
private const ushort FLAG_LAMBDAFORM_COMPILED = 0x800;
private const ushort FLAG_LAMBDAFORM_HIDDEN = 0x1000;
private const ushort FLAG_FORCEINLINE = 0x2000;
private ConstantPoolItemClass[] interfaces;
private Field[] fields;
private Method[] methods;
private string sourceFile;
#if STATIC_COMPILER
private string sourcePath;
#endif
private string ikvmAssembly;
private InnerClass[] innerClasses;
private object[] annotations;
private string signature;
private string[] enclosingMethod;
private BootstrapMethod[] bootstrapMethods;
private byte[] runtimeVisibleTypeAnnotations;
private static class SupportedVersions
{
internal static readonly int Minimum = 45;
internal static readonly int Maximum = Experimental.JDK_9 ? 53 : 52;
}
#if STATIC_COMPILER
// This method parses just enough of the class file to obtain its name and
// determine if the class is a possible ikvmstub generated stub, it doesn't
// validate the class file structure, but it may throw a ClassFormatError if it
// encounters bogus data
internal static string GetClassName(byte[] buf, int offset, int length, out bool isstub)
{
isstub = false;
BigEndianBinaryReader br = new BigEndianBinaryReader(buf, offset, length);
if(br.ReadUInt32() != 0xCAFEBABE)
{
throw new ClassFormatError("Bad magic number");
}
int minorVersion = br.ReadUInt16();
int majorVersion = br.ReadUInt16();
if((majorVersion & FLAG_MASK_MAJORVERSION) != majorVersion
|| majorVersion < SupportedVersions.Minimum
|| majorVersion > SupportedVersions.Maximum
|| (majorVersion == SupportedVersions.Minimum && minorVersion < 3)
|| (majorVersion == SupportedVersions.Maximum && minorVersion != 0))
{
throw new UnsupportedClassVersionError(majorVersion + "." + minorVersion);
}
int constantpoolcount = br.ReadUInt16();
int[] cpclass = new int[constantpoolcount];
string[] utf8_cp = new string[constantpoolcount];
for(int i = 1; i < constantpoolcount; i++)
{
Constant tag = (Constant)br.ReadByte();
switch(tag)
{
case Constant.Class:
cpclass[i] = br.ReadUInt16();
break;
case Constant.Double:
case Constant.Long:
br.Skip(8);
i++;
break;
case Constant.Fieldref:
case Constant.InterfaceMethodref:
case Constant.Methodref:
case Constant.InvokeDynamic:
case Constant.NameAndType:
case Constant.Float:
case Constant.Integer:
br.Skip(4);
break;
case Constant.MethodHandle:
br.Skip(3);
break;
case Constant.String:
case Constant.MethodType:
br.Skip(2);
break;
case Constant.Utf8:
isstub |= (utf8_cp[i] = br.ReadString("<unknown>")) == "IKVM.NET.Assembly";
break;
default:
throw new ClassFormatError("Illegal constant pool type 0x{0:X}", tag);
}
}
br.ReadUInt16(); // access_flags
try
{
return String.Intern(utf8_cp[cpclass[br.ReadUInt16()]].Replace('/', '.'));
}
catch(Exception x)
{
throw new ClassFormatError("{0}: {1}", x.GetType().Name, x.Message);
}
}
#endif // STATIC_COMPILER
internal ClassFile(byte[] buf, int offset, int length, string inputClassName, ClassFileParseOptions options, object[] constantPoolPatches)
{
try
{
BigEndianBinaryReader br = new BigEndianBinaryReader(buf, offset, length);
if(br.ReadUInt32() != 0xCAFEBABE)
{
throw new ClassFormatError("{0} (Bad magic number)", inputClassName);
}
ushort minorVersion = br.ReadUInt16();
ushort majorVersion = br.ReadUInt16();
if((majorVersion & FLAG_MASK_MAJORVERSION) != majorVersion
|| majorVersion < SupportedVersions.Minimum
|| majorVersion > SupportedVersions.Maximum
|| (majorVersion == SupportedVersions.Minimum && minorVersion < 3)
|| (majorVersion == SupportedVersions.Maximum && minorVersion != 0))
{
throw new UnsupportedClassVersionError(inputClassName + " (" + majorVersion + "." + minorVersion + ")");
}
flags = majorVersion;
int constantpoolcount = br.ReadUInt16();
constantpool = new ConstantPoolItem[constantpoolcount];
string[] utf8_cp = new string[constantpoolcount];
for(int i = 1; i < constantpoolcount; i++)
{
Constant tag = (Constant)br.ReadByte();
switch(tag)
{
case Constant.Class:
constantpool[i] = new ConstantPoolItemClass(br);
break;
case Constant.Double:
constantpool[i] = new ConstantPoolItemDouble(br);
i++;
break;
case Constant.Fieldref:
constantpool[i] = new ConstantPoolItemFieldref(br);
break;
case Constant.Float:
constantpool[i] = new ConstantPoolItemFloat(br);
break;
case Constant.Integer:
constantpool[i] = new ConstantPoolItemInteger(br);
break;
case Constant.InterfaceMethodref:
constantpool[i] = new ConstantPoolItemInterfaceMethodref(br);
break;
case Constant.Long:
constantpool[i] = new ConstantPoolItemLong(br);
i++;
break;
case Constant.Methodref:
constantpool[i] = new ConstantPoolItemMethodref(br);
break;
case Constant.NameAndType:
constantpool[i] = new ConstantPoolItemNameAndType(br);
break;
case Constant.MethodHandle:
if (majorVersion < 51)
goto default;
constantpool[i] = new ConstantPoolItemMethodHandle(br);
break;
case Constant.MethodType:
if (majorVersion < 51)
goto default;
constantpool[i] = new ConstantPoolItemMethodType(br);
break;
case Constant.InvokeDynamic:
if (majorVersion < 51)
goto default;
constantpool[i] = new ConstantPoolItemInvokeDynamic(br);
break;
case Constant.String:
constantpool[i] = new ConstantPoolItemString(br);
break;
case Constant.Utf8:
utf8_cp[i] = br.ReadString(inputClassName);
break;
default:
throw new ClassFormatError("{0} (Illegal constant pool type 0x{1:X})", inputClassName, tag);
}
}
if (constantPoolPatches != null)
{
PatchConstantPool(constantPoolPatches, utf8_cp, inputClassName);
}
for(int i = 1; i < constantpoolcount; i++)
{
if(constantpool[i] != null)
{
try
{
constantpool[i].Resolve(this, utf8_cp, options);
}
catch(ClassFormatError x)
{
// HACK at this point we don't yet have the class name, so any exceptions throw
// are missing the class name
throw new ClassFormatError("{0} ({1})", inputClassName, x.Message);
}
catch(IndexOutOfRangeException)
{
throw new ClassFormatError("{0} (Invalid constant pool item #{1})", inputClassName, i);
}
catch(InvalidCastException)
{
throw new ClassFormatError("{0} (Invalid constant pool item #{1})", inputClassName, i);
}
}
}
access_flags = (Modifiers)br.ReadUInt16();
// NOTE although the vmspec says (in 4.1) that interfaces must be marked abstract, earlier versions of
// javac (JDK 1.1) didn't do this, so the VM doesn't enforce this rule for older class files.
// NOTE although the vmspec implies (in 4.1) that ACC_SUPER is illegal on interfaces, it doesn't enforce this
// for older class files.
// (See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6320322)
if((IsInterface && IsFinal)
|| (IsAbstract && IsFinal)
|| (majorVersion >= 49 && IsAnnotation && !IsInterface)
|| (majorVersion >= 49 && IsInterface && (!IsAbstract || IsSuper || IsEnum)))
{
throw new ClassFormatError("{0} (Illegal class modifiers 0x{1:X})", inputClassName, access_flags);
}
this_class = br.ReadUInt16();
ValidateConstantPoolItemClass(inputClassName, this_class);
super_class = br.ReadUInt16();
ValidateConstantPoolItemClass(inputClassName, super_class);
if(IsInterface && (super_class == 0 || this.SuperClass.Name != "java.lang.Object"))
{
throw new ClassFormatError("{0} (Interfaces must have java.lang.Object as superclass)", Name);
}
// most checks are already done by ConstantPoolItemClass.Resolve, but since it allows
// array types, we do need to check for that
if(this.Name[0] == '[')
{
throw new ClassFormatError("Bad name");
}
int interfaces_count = br.ReadUInt16();
interfaces = new ConstantPoolItemClass[interfaces_count];
for(int i = 0; i < interfaces.Length; i++)
{
int index = br.ReadUInt16();
if(index == 0 || index >= constantpool.Length)
{
throw new ClassFormatError("{0} (Illegal constant pool index)", Name);
}
ConstantPoolItemClass cpi = constantpool[index] as ConstantPoolItemClass;
if(cpi == null)
{
throw new ClassFormatError("{0} (Interface name has bad constant type)", Name);
}
interfaces[i] = cpi;
}
CheckDuplicates(interfaces, "Repetitive interface name");
int fields_count = br.ReadUInt16();
fields = new Field[fields_count];
for(int i = 0; i < fields_count; i++)
{
fields[i] = new Field(this, utf8_cp, br);
string name = fields[i].Name;
if(!IsValidFieldName(name, majorVersion))
{
throw new ClassFormatError("{0} (Illegal field name \"{1}\")", Name, name);
}
}
CheckDuplicates<FieldOrMethod>(fields, "Repetitive field name/signature");
int methods_count = br.ReadUInt16();
methods = new Method[methods_count];
for(int i = 0; i < methods_count; i++)
{
methods[i] = new Method(this, utf8_cp, options, br);
string name = methods[i].Name;
string sig = methods[i].Signature;
if(!IsValidMethodName(name, majorVersion))
{
if(!ReferenceEquals(name, StringConstants.INIT) && !ReferenceEquals(name, StringConstants.CLINIT))
{
throw new ClassFormatError("{0} (Illegal method name \"{1}\")", Name, name);
}
if(!sig.EndsWith("V"))
{
throw new ClassFormatError("{0} (Method \"{1}\" has illegal signature \"{2}\")", Name, name, sig);
}
}
}
CheckDuplicates<FieldOrMethod>(methods, "Repetitive method name/signature");
int attributes_count = br.ReadUInt16();
for(int i = 0; i < attributes_count; i++)
{
switch(GetConstantPoolUtf8String(utf8_cp, br.ReadUInt16()))
{
case "Deprecated":
if(br.ReadUInt32() != 0)
{
throw new ClassFormatError("Invalid Deprecated attribute length");
}
flags |= FLAG_MASK_DEPRECATED;
break;
case "SourceFile":
if(br.ReadUInt32() != 2)
{
throw new ClassFormatError("SourceFile attribute has incorrect length");
}
sourceFile = GetConstantPoolUtf8String(utf8_cp, br.ReadUInt16());
break;
case "InnerClasses":
{
BigEndianBinaryReader rdr = br;
uint attribute_length = br.ReadUInt32();
ushort count = rdr.ReadUInt16();
if(this.MajorVersion >= 49 && attribute_length != 2 + count * (2 + 2 + 2 + 2))
{
throw new ClassFormatError("{0} (InnerClasses attribute has incorrect length)", this.Name);
}
innerClasses = new InnerClass[count];
for(int j = 0; j < innerClasses.Length; j++)
{
innerClasses[j].innerClass = rdr.ReadUInt16();
innerClasses[j].outerClass = rdr.ReadUInt16();
innerClasses[j].name = rdr.ReadUInt16();
innerClasses[j].accessFlags = (Modifiers)rdr.ReadUInt16();
if(innerClasses[j].innerClass != 0 && !(GetConstantPoolItem(innerClasses[j].innerClass) is ConstantPoolItemClass))
{
throw new ClassFormatError("{0} (inner_class_info_index has bad constant pool index)", this.Name);
}
if(innerClasses[j].outerClass != 0 && !(GetConstantPoolItem(innerClasses[j].outerClass) is ConstantPoolItemClass))
{
throw new ClassFormatError("{0} (outer_class_info_index has bad constant pool index)", this.Name);
}
if(innerClasses[j].name != 0 && utf8_cp[innerClasses[j].name] == null)
{
throw new ClassFormatError("{0} (inner class name has bad constant pool index)", this.Name);
}
if(innerClasses[j].innerClass == innerClasses[j].outerClass)
{
throw new ClassFormatError("{0} (Class is both inner and outer class)", this.Name);
}
if(innerClasses[j].innerClass != 0 && innerClasses[j].outerClass != 0)
{
MarkLinkRequiredConstantPoolItem(innerClasses[j].innerClass);
MarkLinkRequiredConstantPoolItem(innerClasses[j].outerClass);
}
}
break;
}
case "Signature":
if(majorVersion < 49)
{
goto default;
}
if(br.ReadUInt32() != 2)
{
throw new ClassFormatError("Signature attribute has incorrect length");
}
signature = GetConstantPoolUtf8String(utf8_cp, br.ReadUInt16());
break;
case "EnclosingMethod":
if(majorVersion < 49)
{
goto default;
}
if(br.ReadUInt32() != 4)
{
throw new ClassFormatError("EnclosingMethod attribute has incorrect length");
}
else
{
ushort class_index = br.ReadUInt16();
ushort method_index = br.ReadUInt16();
ValidateConstantPoolItemClass(inputClassName, class_index);
if(method_index == 0)
{
enclosingMethod = new string[] {
GetConstantPoolClass(class_index),
null,
null
};
}
else
{
ConstantPoolItemNameAndType m = GetConstantPoolItem(method_index) as ConstantPoolItemNameAndType;
if(m == null)
{
throw new ClassFormatError("{0} (Bad constant pool index #{1})", inputClassName, method_index);
}
enclosingMethod = new string[] {
GetConstantPoolClass(class_index),
GetConstantPoolUtf8String(utf8_cp, m.name_index),
GetConstantPoolUtf8String(utf8_cp, m.descriptor_index).Replace('/', '.')
};
}
}
break;
case "RuntimeVisibleAnnotations":
if(majorVersion < 49)
{
goto default;
}
annotations = ReadAnnotations(br, this, utf8_cp);
break;
#if STATIC_COMPILER
case "RuntimeInvisibleAnnotations":
if(majorVersion < 49)
{
goto default;
}
foreach(object[] annot in ReadAnnotations(br, this, utf8_cp))
{
if(annot[1].Equals("Likvm/lang/Internal;"))
{
this.access_flags &= ~Modifiers.AccessMask;
flags |= FLAG_MASK_INTERNAL;
}
}
break;
#endif
case "BootstrapMethods":
if(majorVersion < 51)
{
goto default;
}
bootstrapMethods = ReadBootstrapMethods(br, this);
break;
case "RuntimeVisibleTypeAnnotations":
if(majorVersion < 52)
{
goto default;
}
CreateUtf8ConstantPoolItems(utf8_cp);
runtimeVisibleTypeAnnotations = br.Section(br.ReadUInt32()).ToArray();
break;
case "IKVM.NET.Assembly":
if(br.ReadUInt32() != 2)
{
throw new ClassFormatError("IKVM.NET.Assembly attribute has incorrect length");
}
ikvmAssembly = GetConstantPoolUtf8String(utf8_cp, br.ReadUInt16());
break;
default:
br.Skip(br.ReadUInt32());
break;
}
}
// validate the invokedynamic entries to point into the bootstrapMethods array
for(int i = 1; i < constantpoolcount; i++)
{
ConstantPoolItemInvokeDynamic cpi;
if(constantpool[i] != null
&& (cpi = constantpool[i] as ConstantPoolItemInvokeDynamic) != null)
{
if(bootstrapMethods == null || cpi.BootstrapMethod >= bootstrapMethods.Length)
{
throw new ClassFormatError("Short length on BootstrapMethods in class file");
}
}
}
if(br.Position != offset + length)
{
throw new ClassFormatError("Extra bytes at the end of the class file");
}
}
catch(OverflowException)
{
throw new ClassFormatError("Truncated class file (or section)");
}
catch(IndexOutOfRangeException)
{
// TODO we should throw more specific errors
throw new ClassFormatError("Unspecified class file format error");
}
// catch(Exception x)
// {
// Console.WriteLine(x);
// FileStream fs = File.Create(inputClassName + ".broken");
// fs.Write(buf, offset, length);
// fs.Close();
// throw;
// }
}
private void CreateUtf8ConstantPoolItems(string[] utf8_cp)
{
for (int i = 0; i < constantpool.Length; i++)
{
if (constantpool[i] == null && utf8_cp[i] != null)
{
constantpool[i] = new ConstantPoolItemUtf8(utf8_cp[i]);
}
}
}
private void CheckDuplicates<T>(T[] members, string msg)
where T : IEquatable<T>
{
if (members.Length < 100)
{
for (int i = 0; i < members.Length; i++)
{
for (int j = 0; j < i; j++)
{
if (members[i].Equals(members[j]))
{
throw new ClassFormatError("{0} ({1})", Name, msg);
}
}
}
}
else
{
Dictionary<T, object> dict = new Dictionary<T, object>();
for (int i = 0; i < members.Length; i++)
{
if (dict.ContainsKey(members[i]))
{
throw new ClassFormatError("{0} ({1})", Name, msg);
}
dict.Add(members[i], null);
}
}
}
private void PatchConstantPool(object[] constantPoolPatches, string[] utf8_cp, string inputClassName)
{
#if !STATIC_COMPILER && !FIRST_PASS
for (int i = 0; i < constantPoolPatches.Length; i++)
{
if (constantPoolPatches[i] != null)
{
if (utf8_cp[i] != null)
{
if (!(constantPoolPatches[i] is string))
{
throw new ClassFormatError("Illegal utf8 patch at {0} in class file {1}", i, inputClassName);
}
utf8_cp[i] = (string)constantPoolPatches[i];
}
else if (constantpool[i] != null)
{
switch (constantpool[i].GetConstantType())
{
case ConstantType.String:
constantpool[i] = new ConstantPoolItemLiveObject(constantPoolPatches[i]);
break;
case ConstantType.Class:
java.lang.Class clazz;
string name;
if ((clazz = constantPoolPatches[i] as java.lang.Class) != null)
{
TypeWrapper tw = TypeWrapper.FromClass(clazz);
constantpool[i] = new ConstantPoolItemClass(tw.Name, tw);
}
else if ((name = constantPoolPatches[i] as string) != null)
{
constantpool[i] = new ConstantPoolItemClass(String.Intern(name.Replace('/', '.')), null);
}
else
{
throw new ClassFormatError("Illegal class patch at {0} in class file {1}", i, inputClassName);
}
break;
case ConstantType.Integer:
((ConstantPoolItemInteger)constantpool[i]).v = ((java.lang.Integer)constantPoolPatches[i]).intValue();
break;
case ConstantType.Long:
((ConstantPoolItemLong)constantpool[i]).l = ((java.lang.Long)constantPoolPatches[i]).longValue();
break;
case ConstantType.Float:
((ConstantPoolItemFloat)constantpool[i]).v = ((java.lang.Float)constantPoolPatches[i]).floatValue();
break;
case ConstantType.Double:
((ConstantPoolItemDouble)constantpool[i]).d = ((java.lang.Double)constantPoolPatches[i]).doubleValue();
break;
default:
throw new NotImplementedException("ConstantPoolPatch: " + constantPoolPatches[i]);
}
}
}
}
#endif
}
private void MarkLinkRequiredConstantPoolItem(int index)
{
if (index > 0 && index < constantpool.Length && constantpool[index] != null)
{
constantpool[index].MarkLinkRequired();
}
}
private static BootstrapMethod[] ReadBootstrapMethods(BigEndianBinaryReader br, ClassFile classFile)
{
BigEndianBinaryReader rdr = br.Section(br.ReadUInt32());
ushort count = rdr.ReadUInt16();
BootstrapMethod[] bsm = new BootstrapMethod[count];
for(int i = 0; i < bsm.Length; i++)
{
ushort bsm_index = rdr.ReadUInt16();
if(bsm_index >= classFile.constantpool.Length || !(classFile.constantpool[bsm_index] is ConstantPoolItemMethodHandle))
{
throw new ClassFormatError("bootstrap_method_index {0} has bad constant type in class file {1}", bsm_index, classFile.Name);
}
classFile.MarkLinkRequiredConstantPoolItem(bsm_index);
ushort argument_count = rdr.ReadUInt16();
ushort[] args = new ushort[argument_count];
for(int j = 0; j < args.Length; j++)
{
ushort argument_index = rdr.ReadUInt16();
if(!classFile.IsValidConstant(argument_index))
{
throw new ClassFormatError("argument_index {0} has bad constant type in class file {1}", argument_index, classFile.Name);
}
classFile.MarkLinkRequiredConstantPoolItem(argument_index);
args[j] = argument_index;
}
bsm[i] = new BootstrapMethod(bsm_index, args);
}
if(!rdr.IsAtEnd)
{
throw new ClassFormatError("Bad length on BootstrapMethods in class file {0}", classFile.Name);
}
return bsm;
}
private bool IsValidConstant(ushort index)
{
if(index < constantpool.Length && constantpool[index] != null)
{
try
{
constantpool[index].GetConstantType();
return true;
}
catch (InvalidOperationException) { }
}
return false;
}
private static object[] ReadAnnotations(BigEndianBinaryReader br, ClassFile classFile, string[] utf8_cp)
{
BigEndianBinaryReader rdr = br.Section(br.ReadUInt32());
ushort num_annotations = rdr.ReadUInt16();
object[] annotations = new object[num_annotations];
for(int i = 0; i < annotations.Length; i++)
{
annotations[i] = ReadAnnotation(rdr, classFile, utf8_cp);
}
if(!rdr.IsAtEnd)
{
throw new ClassFormatError("{0} (RuntimeVisibleAnnotations attribute has wrong length)", classFile.Name);
}
return annotations;
}
private static object ReadAnnotation(BigEndianBinaryReader rdr, ClassFile classFile, string[] utf8_cp)
{
string type = classFile.GetConstantPoolUtf8String(utf8_cp, rdr.ReadUInt16());
ushort num_element_value_pairs = rdr.ReadUInt16();
object[] annot = new object[2 + num_element_value_pairs * 2];
annot[0] = AnnotationDefaultAttribute.TAG_ANNOTATION;
annot[1] = type;
for(int i = 0; i < num_element_value_pairs; i++)
{
annot[2 + i * 2 + 0] = classFile.GetConstantPoolUtf8String(utf8_cp, rdr.ReadUInt16());
annot[2 + i * 2 + 1] = ReadAnnotationElementValue(rdr, classFile, utf8_cp);
}
return annot;
}
private static object ReadAnnotationElementValue(BigEndianBinaryReader rdr, ClassFile classFile, string[] utf8_cp)
{
try
{
byte tag = rdr.ReadByte();
switch (tag)
{
case (byte)'Z':
return classFile.GetConstantPoolConstantInteger(rdr.ReadUInt16()) != 0;
case (byte)'B':
return (byte)classFile.GetConstantPoolConstantInteger(rdr.ReadUInt16());
case (byte)'C':
return (char)classFile.GetConstantPoolConstantInteger(rdr.ReadUInt16());
case (byte)'S':
return (short)classFile.GetConstantPoolConstantInteger(rdr.ReadUInt16());
case (byte)'I':
return classFile.GetConstantPoolConstantInteger(rdr.ReadUInt16());
case (byte)'F':
return classFile.GetConstantPoolConstantFloat(rdr.ReadUInt16());
case (byte)'J':
return classFile.GetConstantPoolConstantLong(rdr.ReadUInt16());
case (byte)'D':
return classFile.GetConstantPoolConstantDouble(rdr.ReadUInt16());
case (byte)'s':
return classFile.GetConstantPoolUtf8String(utf8_cp, rdr.ReadUInt16());
case (byte)'e':
{
ushort type_name_index = rdr.ReadUInt16();
ushort const_name_index = rdr.ReadUInt16();
return new object[] {
AnnotationDefaultAttribute.TAG_ENUM,
classFile.GetConstantPoolUtf8String(utf8_cp, type_name_index),
classFile.GetConstantPoolUtf8String(utf8_cp, const_name_index)
};
}
case (byte)'c':
return new object[] {
AnnotationDefaultAttribute.TAG_CLASS,
classFile.GetConstantPoolUtf8String(utf8_cp, rdr.ReadUInt16())
};
case (byte)'@':
return ReadAnnotation(rdr, classFile, utf8_cp);
case (byte)'[':
{
ushort num_values = rdr.ReadUInt16();
object[] array = new object[num_values + 1];
array[0] = AnnotationDefaultAttribute.TAG_ARRAY;
for (int i = 0; i < num_values; i++)
{
array[i + 1] = ReadAnnotationElementValue(rdr, classFile, utf8_cp);
}
return array;
}
default:
throw new ClassFormatError("Invalid tag {0} in annotation element_value", tag);
}
}
catch (NullReferenceException)
{
}
catch (InvalidCastException)
{
}
catch (IndexOutOfRangeException)
{
}
return new object[] { AnnotationDefaultAttribute.TAG_ERROR, "java.lang.IllegalArgumentException", "Wrong type at constant pool index" };
}
private void ValidateConstantPoolItemClass(string classFile, ushort index)
{
if(index >= constantpool.Length || !(constantpool[index] is ConstantPoolItemClass))
{
throw new ClassFormatError("{0} (Bad constant pool index #{1})", classFile, index);
}
}
private static bool IsValidMethodName(string name, int majorVersion)
{
if(name.Length == 0)
{
return false;
}
for(int i = 0; i < name.Length; i++)
{
if(".;[/<>".IndexOf(name[i]) != -1)
{
return false;
}
}
return majorVersion >= 49 || IsValidPre49Identifier(name);
}
private static bool IsValidFieldName(string name, int majorVersion)
{
if(name.Length == 0)
{
return false;
}
for(int i = 0; i < name.Length; i++)
{
if(".;[/".IndexOf(name[i]) != -1)
{
return false;
}
}
return majorVersion >= 49 || IsValidPre49Identifier(name);
}
private static bool IsValidPre49Identifier(string name)
{
if(!Char.IsLetter(name[0]) && "$_".IndexOf(name[0]) == -1)
{
return false;
}
for(int i = 1; i < name.Length; i++)
{
if(!Char.IsLetterOrDigit(name[i]) && "$_".IndexOf(name[i]) == -1)
{
return false;
}
}
return true;
}
internal static bool IsValidFieldSig(string sig)
{
return IsValidFieldSigImpl(sig, 0, sig.Length);
}
private static bool IsValidFieldSigImpl(string sig, int start, int end)
{
if(start >= end)
{
return false;
}
switch(sig[start])
{
case 'L':
return sig.IndexOf(';', start + 1) == end - 1;
case '[':
while(sig[start] == '[')
{
start++;
if(start == end)
{
return false;
}
}
return IsValidFieldSigImpl(sig, start, end);
case 'B':
case 'Z':
case 'C':
case 'S':
case 'I':
case 'J':
case 'F':
case 'D':
return start == end - 1;
default:
return false;
}
}
internal static bool IsValidMethodSig(string sig)
{
if(sig.Length < 3 || sig[0] != '(')
{
return false;
}
int end = sig.IndexOf(')');
if(end == -1)
{
return false;
}
if(!sig.EndsWith(")V") && !IsValidFieldSigImpl(sig, end + 1, sig.Length))
{
return false;
}
for(int i = 1; i < end; i++)
{
switch(sig[i])
{
case 'B':
case 'Z':
case 'C':
case 'S':
case 'I':
case 'J':
case 'F':
case 'D':
break;
case 'L':
i = sig.IndexOf(';', i);
break;
case '[':
while(sig[i] == '[')
{
i++;
}
if("BZCSIJFDL".IndexOf(sig[i]) == -1)
{
return false;
}
if(sig[i] == 'L')
{
i = sig.IndexOf(';', i);
}
break;
default:
return false;
}
if(i == -1 || i >= end)
{
return false;
}
}
return true;
}
internal int MajorVersion
{
get
{
return flags & FLAG_MASK_MAJORVERSION;
}
}
internal void Link(TypeWrapper thisType)
{
// this is not just an optimization, it's required for anonymous classes to be able to refer to themselves
((ConstantPoolItemClass)constantpool[this_class]).LinkSelf(thisType);
for(int i = 1; i < constantpool.Length; i++)
{
if(constantpool[i] != null)
{
constantpool[i].Link(thisType);
}
}
}
internal Modifiers Modifiers
{
get
{
return access_flags;
}
}
internal bool IsAbstract
{
get
{
// interfaces are implicitly abstract
return (access_flags & (Modifiers.Abstract | Modifiers.Interface)) != 0;
}
}
internal bool IsFinal
{
get
{
return (access_flags & Modifiers.Final) != 0;
}
}
internal bool IsPublic
{
get
{
return (access_flags & Modifiers.Public) != 0;
}
}
internal bool IsInterface
{
get
{
return (access_flags & Modifiers.Interface) != 0;
}
}
internal bool IsEnum
{
get
{
return (access_flags & Modifiers.Enum) != 0;
}
}
internal bool IsAnnotation
{
get
{
return (access_flags & Modifiers.Annotation) != 0;
}
}
internal bool IsSuper
{
get
{
return (access_flags & Modifiers.Super) != 0;
}
}
internal void RemoveUnusedFields()
{
List<Field> list = new List<Field>();
foreach(Field f in fields)
{
if(f.IsPrivate && f.IsStatic && f.Name != "serialVersionUID" && !IsReferenced(f))
{
// unused, so we skip it
Tracer.Info(Tracer.Compiler, "Unused field {0}::{1}", this.Name, f.Name);
}
else
{
list.Add(f);
}
}
fields = list.ToArray();
}
private bool IsReferenced(Field fld)
{
foreach(ConstantPoolItem cpi in constantpool)
{
ConstantPoolItemFieldref fieldref = cpi as ConstantPoolItemFieldref;
if(fieldref != null &&
fieldref.Class == this.Name &&
fieldref.Name == fld.Name &&
fieldref.Signature == fld.Signature)
{
return true;
}
}
return false;
}
internal ConstantPoolItemFieldref GetFieldref(int index)
{
return (ConstantPoolItemFieldref)constantpool[index];
}
// this won't throw an exception if index is invalid
// (used by IsSideEffectFreeStaticInitializer)
internal ConstantPoolItemFieldref SafeGetFieldref(int index)
{
if(index > 0 && index < constantpool.Length)
{
return constantpool[index] as ConstantPoolItemFieldref;
}
return null;
}
// NOTE this returns an MI, because it used for both normal methods and interface methods
internal ConstantPoolItemMI GetMethodref(int index)
{
return (ConstantPoolItemMI)constantpool[index];
}
// this won't throw an exception if index is invalid
// (used by IsAccessBridge)
internal ConstantPoolItemMI SafeGetMethodref(int index)
{
if (index > 0 && index < constantpool.Length)
{
return constantpool[index] as ConstantPoolItemMI;
}
return null;
}
internal ConstantPoolItemInvokeDynamic GetInvokeDynamic(int index)
{
return (ConstantPoolItemInvokeDynamic)constantpool[index];
}
private ConstantPoolItem GetConstantPoolItem(int index)
{
return constantpool[index];
}
internal string GetConstantPoolClass(int index)
{
return ((ConstantPoolItemClass)constantpool[index]).Name;
}
private bool SafeIsConstantPoolClass(int index)
{
if(index > 0 && index < constantpool.Length)
{
return constantpool[index] as ConstantPoolItemClass != null;
}
return false;
}
internal TypeWrapper GetConstantPoolClassType(int index)
{
return ((ConstantPoolItemClass)constantpool[index]).GetClassType();
}
private string GetConstantPoolUtf8String(string[] utf8_cp, int index)
{
string s = utf8_cp[index];
if(s == null)
{
if(this_class == 0)
{
throw new ClassFormatError("Bad constant pool index #{0}", index);
}
else
{
throw new ClassFormatError("{0} (Bad constant pool index #{1})", this.Name, index);
}
}
return s;
}
internal ConstantType GetConstantPoolConstantType(int index)
{
return constantpool[index].GetConstantType();
}
internal double GetConstantPoolConstantDouble(int index)
{
return ((ConstantPoolItemDouble)constantpool[index]).Value;
}
internal float GetConstantPoolConstantFloat(int index)
{
return ((ConstantPoolItemFloat)constantpool[index]).Value;
}
internal int GetConstantPoolConstantInteger(int index)
{
return ((ConstantPoolItemInteger)constantpool[index]).Value;
}
internal long GetConstantPoolConstantLong(int index)
{
return ((ConstantPoolItemLong)constantpool[index]).Value;
}
internal string GetConstantPoolConstantString(int index)
{
return ((ConstantPoolItemString)constantpool[index]).Value;
}
internal ConstantPoolItemMethodHandle GetConstantPoolConstantMethodHandle(int index)
{
return (ConstantPoolItemMethodHandle)constantpool[index];
}
internal ConstantPoolItemMethodType GetConstantPoolConstantMethodType(int index)
{
return (ConstantPoolItemMethodType)constantpool[index];
}
internal object GetConstantPoolConstantLiveObject(int index)
{
return ((ConstantPoolItemLiveObject)constantpool[index]).Value;
}
internal string Name
{
get
{
return GetConstantPoolClass(this_class);
}
}
internal ConstantPoolItemClass SuperClass
{
get
{
return (ConstantPoolItemClass)constantpool[super_class];
}
}
internal Field[] Fields
{
get
{
return fields;
}
}
internal Method[] Methods
{
get
{
return methods;
}
}
internal ConstantPoolItemClass[] Interfaces
{
get
{
return interfaces;
}
}
internal string SourceFileAttribute
{
get
{
return sourceFile;
}
}
internal string SourcePath
{
#if STATIC_COMPILER
get { return sourcePath; }
set { sourcePath = value; }
#else
get { return sourceFile; }
#endif
}
internal object[] Annotations
{
get
{
return annotations;
}
}
internal string GenericSignature
{
get
{
return signature;
}
}
internal string[] EnclosingMethod
{
get
{
return enclosingMethod;
}
}
internal byte[] RuntimeVisibleTypeAnnotations
{
get
{
return runtimeVisibleTypeAnnotations;
}
}
internal object[] GetConstantPool()
{
object[] cp = new object[constantpool.Length];
for (int i = 1; i < cp.Length; i++)
{
if (constantpool[i] != null)
{
cp[i] = constantpool[i].GetRuntimeValue();
}
}
return cp;
}
internal string IKVMAssemblyAttribute
{
get
{
return ikvmAssembly;
}
}
internal bool DeprecatedAttribute
{
get
{
return (flags & FLAG_MASK_DEPRECATED) != 0;
}
}
internal bool IsInternal
{
get
{
return (flags & FLAG_MASK_INTERNAL) != 0;
}
}
// for use by ikvmc (to implement the -privatepackage option)
internal void SetInternal()
{
access_flags &= ~Modifiers.AccessMask;
flags |= FLAG_MASK_INTERNAL;
}
internal bool HasInitializedFields
{
get
{
foreach (Field f in fields)
{
if (f.IsStatic && !f.IsFinal && f.ConstantValue != null)
{
return true;
}
}
return false;
}
}
internal BootstrapMethod GetBootstrapMethod(int index)
{
return bootstrapMethods[index];
}
internal struct BootstrapMethod
{
private ushort bsm_index;
private ushort[] args;
internal BootstrapMethod(ushort bsm_index, ushort[] args)
{
this.bsm_index = bsm_index;
this.args = args;
}
internal int BootstrapMethodIndex
{
get { return bsm_index; }
}
internal int ArgumentCount
{
get { return args.Length; }
}
internal int GetArgument(int index)
{
return args[index];
}
}
internal struct InnerClass
{
internal ushort innerClass; // ConstantPoolItemClass
internal ushort outerClass; // ConstantPoolItemClass
internal ushort name; // ConstantPoolItemUtf8
internal Modifiers accessFlags;
}
internal InnerClass[] InnerClasses
{
get
{
return innerClasses;
}
}
internal enum RefKind
{
getField = 1,
getStatic = 2,
putField = 3,
putStatic = 4,
invokeVirtual = 5,
invokeStatic = 6,
invokeSpecial = 7,
newInvokeSpecial = 8,
invokeInterface = 9
}
internal enum ConstantType
{
Integer,
Long,
Float,
Double,
String,
Class,
MethodHandle,
MethodType,
LiveObject, // used by anonymous class constant pool patching
}
internal abstract class ConstantPoolItem
{
internal virtual void Resolve(ClassFile classFile, string[] utf8_cp, ClassFileParseOptions options)
{
}
internal virtual void Link(TypeWrapper thisType)
{
}
internal virtual ConstantType GetConstantType()
{
throw new InvalidOperationException();
}
internal virtual void MarkLinkRequired()
{
}
// this is used for sun.reflect.ConstantPool
// it returns a boxed System.Int32, System.Int64, System.Float, System.Double or a string
internal virtual object GetRuntimeValue()
{
return null;
}
}
internal sealed class ConstantPoolItemClass : ConstantPoolItem, IEquatable<ConstantPoolItemClass>
{
private ushort name_index;
private string name;
private TypeWrapper typeWrapper;
private static char[] invalidJava15Characters = { '.', ';', '[', ']' };
internal ConstantPoolItemClass(BigEndianBinaryReader br)
{
name_index = br.ReadUInt16();
}
internal ConstantPoolItemClass(string name, TypeWrapper typeWrapper)
{
this.name = name;
this.typeWrapper = typeWrapper;
}
internal override void Resolve(ClassFile classFile, string[] utf8_cp, ClassFileParseOptions options)
{
// if the item was patched, we already have a name
if(name != null)
{
return;
}
name = classFile.GetConstantPoolUtf8String(utf8_cp, name_index);
if(name.Length > 0)
{
// We don't enforce the strict class name rules in the static compiler, since HotSpot doesn't enforce *any* rules on
// class names for the system (and boot) class loader. We still need to enforce the 1.5 restrictions, because we
// rely on those invariants.
#if !STATIC_COMPILER
if(classFile.MajorVersion < 49 && (options & ClassFileParseOptions.RelaxedClassNameValidation) == 0)
{
char prev = name[0];
if(Char.IsLetter(prev) || prev == '$' || prev == '_' || prev == '[' || prev == '/')
{
int skip = 1;
int end = name.Length;
if(prev == '[')
{
if(!IsValidFieldSig(name))
{
goto barf;
}
while(name[skip] == '[')
{
skip++;
}
if(name.EndsWith(";"))
{
end--;
}
}
for(int i = skip; i < end; i++)
{
char c = name[i];
if(!Char.IsLetterOrDigit(c) && c != '$' && c != '_' && (c != '/' || prev == '/'))
{
goto barf;
}
prev = c;
}
name = String.Intern(name.Replace('/', '.'));
return;
}
}
else
#endif
{
// since 1.5 the restrictions on class names have been greatly reduced
int start = 0;
int end = name.Length;
if(name[0] == '[')
{
if(!IsValidFieldSig(name))
{
goto barf;
}
// the semicolon is only allowed at the end and IsValidFieldSig enforces this,
// but since invalidJava15Characters contains the semicolon, we decrement end
// to make the following check against invalidJava15Characters ignore the
// trailing semicolon.
if(name[end - 1] == ';')
{
end--;
}
while(name[start] == '[')
{
start++;
}
}
if(name.IndexOfAny(invalidJava15Characters, start, end - start) >= 0)
{
goto barf;
}
name = String.Intern(name.Replace('/', '.'));
return;
}
}
barf:
throw new ClassFormatError("Invalid class name \"{0}\"", name);
}
internal override void MarkLinkRequired()
{
if(typeWrapper == null)
{
typeWrapper = VerifierTypeWrapper.Null;
}
}
internal void LinkSelf(TypeWrapper thisType)
{
this.typeWrapper = thisType;
}
internal override void Link(TypeWrapper thisType)
{
if(typeWrapper == VerifierTypeWrapper.Null)
{
TypeWrapper tw = ClassLoaderWrapper.LoadClassNoThrow(thisType.GetClassLoader(), name, true);
#if !STATIC_COMPILER && !FIRST_PASS
if(!tw.IsUnloadable)
{
try
{
thisType.GetClassLoader().CheckPackageAccess(tw, thisType.ClassObject.pd);
}
catch(java.lang.SecurityException)
{
tw = new UnloadableTypeWrapper(name);
}
}
#endif
typeWrapper = tw;
}
}
internal string Name
{
get
{
return name;
}
}
internal TypeWrapper GetClassType()
{
return typeWrapper;
}
internal override ConstantType GetConstantType()
{
return ConstantType.Class;
}
public sealed override int GetHashCode()
{
return name.GetHashCode();
}
public bool Equals(ConstantPoolItemClass other)
{
return ReferenceEquals(name, other.name);
}
}
private sealed class ConstantPoolItemDouble : ConstantPoolItem
{
internal double d;
internal ConstantPoolItemDouble(BigEndianBinaryReader br)
{
d = br.ReadDouble();
}
internal override ConstantType GetConstantType()
{
return ConstantType.Double;
}
internal double Value
{
get
{
return d;
}
}
internal override object GetRuntimeValue()
{
return d;
}
}
internal abstract class ConstantPoolItemFMI : ConstantPoolItem
{
private ushort class_index;
private ushort name_and_type_index;
private ConstantPoolItemClass clazz;
private string name;
private string descriptor;
internal ConstantPoolItemFMI(BigEndianBinaryReader br)
{
class_index = br.ReadUInt16();
name_and_type_index = br.ReadUInt16();
}
internal override void Resolve(ClassFile classFile, string[] utf8_cp, ClassFileParseOptions options)
{
ConstantPoolItemNameAndType name_and_type = (ConstantPoolItemNameAndType)classFile.GetConstantPoolItem(name_and_type_index);
clazz = (ConstantPoolItemClass)classFile.GetConstantPoolItem(class_index);
// if the constant pool items referred to were strings, GetConstantPoolItem returns null
if(name_and_type == null || clazz == null)
{
throw new ClassFormatError("Bad index in constant pool");
}
name = String.Intern(classFile.GetConstantPoolUtf8String(utf8_cp, name_and_type.name_index));
descriptor = classFile.GetConstantPoolUtf8String(utf8_cp, name_and_type.descriptor_index);
Validate(name, descriptor, classFile.MajorVersion);
descriptor = String.Intern(descriptor.Replace('/', '.'));
}
protected abstract void Validate(string name, string descriptor, int majorVersion);
internal override void MarkLinkRequired()
{
clazz.MarkLinkRequired();
}
internal override void Link(TypeWrapper thisType)
{
clazz.Link(thisType);
}
internal string Name
{
get
{
return name;
}
}
internal string Signature
{
get
{
return descriptor;
}
}
internal string Class
{
get
{
return clazz.Name;
}
}
internal TypeWrapper GetClassType()
{
return clazz.GetClassType();
}
internal abstract MemberWrapper GetMember();
}
internal sealed class ConstantPoolItemFieldref : ConstantPoolItemFMI
{
private FieldWrapper field;
private TypeWrapper fieldTypeWrapper;
internal ConstantPoolItemFieldref(BigEndianBinaryReader br) : base(br)
{
}
protected override void Validate(string name, string descriptor, int majorVersion)
{
if(!IsValidFieldSig(descriptor))
{
throw new ClassFormatError("Invalid field signature \"{0}\"", descriptor);
}
if(!IsValidFieldName(name, majorVersion))
{
throw new ClassFormatError("Invalid field name \"{0}\"", name);
}
}
internal TypeWrapper GetFieldType()
{
return fieldTypeWrapper;
}
internal override void Link(TypeWrapper thisType)
{
base.Link(thisType);
lock(this)
{
if(fieldTypeWrapper != null)
{
return;
}
}
FieldWrapper fw = null;
TypeWrapper wrapper = GetClassType();
if(wrapper == null)
{
return;
}
if(!wrapper.IsUnloadable)
{
fw = wrapper.GetFieldWrapper(Name, Signature);
if(fw != null)
{
fw.Link();
}
}
ClassLoaderWrapper classLoader = thisType.GetClassLoader();
TypeWrapper fld = classLoader.FieldTypeWrapperFromSigNoThrow(this.Signature);
lock(this)
{
if(fieldTypeWrapper == null)
{
fieldTypeWrapper = fld;
field = fw;
}
}
}
internal FieldWrapper GetField()
{
return field;
}
internal override MemberWrapper GetMember()
{
return field;
}
}
internal class ConstantPoolItemMI : ConstantPoolItemFMI
{
private TypeWrapper[] argTypeWrappers;
private TypeWrapper retTypeWrapper;
protected MethodWrapper method;
protected MethodWrapper invokespecialMethod;
internal ConstantPoolItemMI(BigEndianBinaryReader br) : base(br)
{
}
protected override void Validate(string name, string descriptor, int majorVersion)
{
if(!IsValidMethodSig(descriptor))
{
throw new ClassFormatError("Method {0} has invalid signature {1}", name, descriptor);
}
if(!IsValidMethodName(name, majorVersion))
{
if(!ReferenceEquals(name, StringConstants.INIT))
{
throw new ClassFormatError("Invalid method name \"{0}\"", name);
}
if(!descriptor.EndsWith("V"))
{
throw new ClassFormatError("Method {0} has invalid signature {1}", name, descriptor);
}
}
}
internal override void Link(TypeWrapper thisType)
{
base.Link(thisType);
lock(this)
{
if(argTypeWrappers != null)
{
return;
}
}
ClassLoaderWrapper classLoader = thisType.GetClassLoader();
TypeWrapper[] args = classLoader.ArgTypeWrapperListFromSigNoThrow(this.Signature);
TypeWrapper ret = classLoader.RetTypeWrapperFromSigNoThrow(this.Signature);
lock(this)
{
if(argTypeWrappers == null)
{
argTypeWrappers = args;
retTypeWrapper = ret;
}
}
}
internal TypeWrapper[] GetArgTypes()
{
return argTypeWrappers;
}
internal TypeWrapper GetRetType()
{
return retTypeWrapper;
}
internal MethodWrapper GetMethod()
{
return method;
}
internal MethodWrapper GetMethodForInvokespecial()
{
return invokespecialMethod != null ? invokespecialMethod : method;
}
internal override MemberWrapper GetMember()
{
return method;
}
}
internal sealed class ConstantPoolItemMethodref : ConstantPoolItemMI
{
internal ConstantPoolItemMethodref(BigEndianBinaryReader br) : base(br)
{
}
internal override void Link(TypeWrapper thisType)
{
base.Link(thisType);
TypeWrapper wrapper = GetClassType();
if(wrapper != null && !wrapper.IsUnloadable)
{
method = wrapper.GetMethodWrapper(Name, Signature, !ReferenceEquals(Name, StringConstants.INIT));
if(method != null)
{
method.Link();
}
if(Name != StringConstants.INIT
&& !thisType.IsInterface
&& (!JVM.AllowNonVirtualCalls || (thisType.Modifiers & Modifiers.Super) == Modifiers.Super)
&& thisType != wrapper
&& thisType.IsSubTypeOf(wrapper))
{
invokespecialMethod = thisType.BaseTypeWrapper.GetMethodWrapper(Name, Signature, true);
if(invokespecialMethod != null)
{
invokespecialMethod.Link();
}
}
}
}
}
internal sealed class ConstantPoolItemInterfaceMethodref : ConstantPoolItemMI
{
internal ConstantPoolItemInterfaceMethodref(BigEndianBinaryReader br) : base(br)
{
}
private static MethodWrapper GetInterfaceMethod(TypeWrapper wrapper, string name, string sig)
{
if(wrapper.IsUnloadable)
{
return null;
}
MethodWrapper method = wrapper.GetMethodWrapper(name, sig, false);
if(method != null)
{
return method;
}
TypeWrapper[] interfaces = wrapper.Interfaces;
for(int i = 0; i < interfaces.Length; i++)
{
method = GetInterfaceMethod(interfaces[i], name, sig);
if(method != null)
{
return method;
}
}
return null;
}
internal override void Link(TypeWrapper thisType)
{
base.Link(thisType);
TypeWrapper wrapper = GetClassType();
if(wrapper != null)
{
method = GetInterfaceMethod(wrapper, Name, Signature);
if(method == null)
{
// NOTE vmspec 5.4.3.4 clearly states that an interfacemethod may also refer to a method in Object
method = CoreClasses.java.lang.Object.Wrapper.GetMethodWrapper(Name, Signature, false);
}
if(method != null)
{
method.Link();
}
}
}
}
private sealed class ConstantPoolItemFloat : ConstantPoolItem
{
internal float v;
internal ConstantPoolItemFloat(BigEndianBinaryReader br)
{
v = br.ReadSingle();
}
internal override ConstantType GetConstantType()
{
return ConstantType.Float;
}
internal float Value
{
get
{
return v;
}
}
internal override object GetRuntimeValue()
{
return v;
}
}
private sealed class ConstantPoolItemInteger : ConstantPoolItem
{
internal int v;
internal ConstantPoolItemInteger(BigEndianBinaryReader br)
{
v = br.ReadInt32();
}
internal override ConstantType GetConstantType()
{
return ConstantType.Integer;
}
internal int Value
{
get
{
return v;
}
}
internal override object GetRuntimeValue()
{
return v;
}
}
private sealed class ConstantPoolItemLong : ConstantPoolItem
{
internal long l;
internal ConstantPoolItemLong(BigEndianBinaryReader br)
{
l = br.ReadInt64();
}
internal override ConstantType GetConstantType()
{
return ConstantType.Long;
}
internal long Value
{
get
{
return l;
}
}
internal override object GetRuntimeValue()
{
return l;
}
}
private sealed class ConstantPoolItemNameAndType : ConstantPoolItem
{
internal ushort name_index;
internal ushort descriptor_index;
internal ConstantPoolItemNameAndType(BigEndianBinaryReader br)
{
name_index = br.ReadUInt16();
descriptor_index = br.ReadUInt16();
}
internal override void Resolve(ClassFile classFile, string[] utf8_cp, ClassFileParseOptions options)
{
if(classFile.GetConstantPoolUtf8String(utf8_cp, name_index) == null
|| classFile.GetConstantPoolUtf8String(utf8_cp, descriptor_index) == null)
{
throw new ClassFormatError("Illegal constant pool index");
}
}
}
internal sealed class ConstantPoolItemMethodHandle : ConstantPoolItem
{
private byte ref_kind;
private ushort method_index;
private ConstantPoolItemFMI cpi;
internal ConstantPoolItemMethodHandle(BigEndianBinaryReader br)
{
ref_kind = br.ReadByte();
method_index = br.ReadUInt16();
}
internal override void Resolve(ClassFile classFile, string[] utf8_cp, ClassFileParseOptions options)
{
switch ((RefKind)ref_kind)
{
case RefKind.getField:
case RefKind.getStatic:
case RefKind.putField:
case RefKind.putStatic:
cpi = classFile.GetConstantPoolItem(method_index) as ConstantPoolItemFieldref;
break;
case RefKind.invokeSpecial:
case RefKind.invokeVirtual:
case RefKind.invokeStatic:
case RefKind.newInvokeSpecial:
cpi = classFile.GetConstantPoolItem(method_index) as ConstantPoolItemMethodref;
if (cpi == null && classFile.MajorVersion >= 52 && ((RefKind)ref_kind == RefKind.invokeStatic || (RefKind)ref_kind == RefKind.invokeSpecial))
goto case RefKind.invokeInterface;
break;
case RefKind.invokeInterface:
cpi = classFile.GetConstantPoolItem(method_index) as ConstantPoolItemInterfaceMethodref;
break;
}
if (cpi == null)
{
throw new ClassFormatError("Invalid constant pool item MethodHandle");
}
if (ReferenceEquals(cpi.Name, StringConstants.INIT) && Kind != RefKind.newInvokeSpecial)
{
throw new ClassFormatError("Bad method name");
}
}
internal override void MarkLinkRequired()
{
cpi.MarkLinkRequired();
}
internal string Class
{
get { return cpi.Class; }
}
internal string Name
{
get { return cpi.Name; }
}
internal string Signature
{
get { return cpi.Signature; }
}
internal ConstantPoolItemFMI MemberConstantPoolItem
{
get { return cpi; }
}
internal RefKind Kind
{
get { return (RefKind)ref_kind; }
}
internal MemberWrapper Member
{
get { return cpi.GetMember(); }
}
internal TypeWrapper GetClassType()
{
return cpi.GetClassType();
}
internal override void Link(TypeWrapper thisType)
{
cpi.Link(thisType);
}
internal override ConstantType GetConstantType()
{
return ConstantType.MethodHandle;
}
}
internal sealed class ConstantPoolItemMethodType : ConstantPoolItem
{
private ushort signature_index;
private string descriptor;
private TypeWrapper[] argTypeWrappers;
private TypeWrapper retTypeWrapper;
internal ConstantPoolItemMethodType(BigEndianBinaryReader br)
{
signature_index = br.ReadUInt16();
}
internal override void Resolve(ClassFile classFile, string[] utf8_cp, ClassFileParseOptions options)
{
string descriptor = classFile.GetConstantPoolUtf8String(utf8_cp, signature_index);
if (descriptor == null || !IsValidMethodSig(descriptor))
{
throw new ClassFormatError("Invalid MethodType signature");
}
this.descriptor = String.Intern(descriptor.Replace('/', '.'));
}
internal override void Link(TypeWrapper thisType)
{
lock (this)
{
if (argTypeWrappers != null)
{
return;
}
}
ClassLoaderWrapper classLoader = thisType.GetClassLoader();
TypeWrapper[] args = classLoader.ArgTypeWrapperListFromSigNoThrow(descriptor);
TypeWrapper ret = classLoader.RetTypeWrapperFromSigNoThrow(descriptor);
lock (this)
{
if (argTypeWrappers == null)
{
argTypeWrappers = args;
retTypeWrapper = ret;
}
}
}
internal string Signature
{
get { return descriptor; }
}
internal TypeWrapper[] GetArgTypes()
{
return argTypeWrappers;
}
internal TypeWrapper GetRetType()
{
return retTypeWrapper;
}
internal override ConstantType GetConstantType()
{
return ConstantType.MethodType;
}
}
internal sealed class ConstantPoolItemInvokeDynamic : ConstantPoolItem
{
private ushort bootstrap_specifier_index;
private ushort name_and_type_index;
private string name;
private string descriptor;
private TypeWrapper[] argTypeWrappers;
private TypeWrapper retTypeWrapper;
internal ConstantPoolItemInvokeDynamic(BigEndianBinaryReader br)
{
bootstrap_specifier_index = br.ReadUInt16();
name_and_type_index = br.ReadUInt16();
}
internal override void Resolve(ClassFile classFile, string[] utf8_cp, ClassFileParseOptions options)
{
ConstantPoolItemNameAndType name_and_type = (ConstantPoolItemNameAndType)classFile.GetConstantPoolItem(name_and_type_index);
// if the constant pool items referred to were strings, GetConstantPoolItem returns null
if (name_and_type == null)
{
throw new ClassFormatError("Bad index in constant pool");
}
name = String.Intern(classFile.GetConstantPoolUtf8String(utf8_cp, name_and_type.name_index));
descriptor = String.Intern(classFile.GetConstantPoolUtf8String(utf8_cp, name_and_type.descriptor_index).Replace('/', '.'));
}
internal override void Link(TypeWrapper thisType)
{
lock (this)
{
if (argTypeWrappers != null)
{
return;
}
}
ClassLoaderWrapper classLoader = thisType.GetClassLoader();
TypeWrapper[] args = classLoader.ArgTypeWrapperListFromSigNoThrow(descriptor);
TypeWrapper ret = classLoader.RetTypeWrapperFromSigNoThrow(descriptor);
lock (this)
{
if (argTypeWrappers == null)
{
argTypeWrappers = args;
retTypeWrapper = ret;
}
}
}
internal TypeWrapper[] GetArgTypes()
{
return argTypeWrappers;
}
internal TypeWrapper GetRetType()
{
return retTypeWrapper;
}
internal string Name
{
get { return name; }
}
internal ushort BootstrapMethod
{
get { return bootstrap_specifier_index; }
}
}
private sealed class ConstantPoolItemString : ConstantPoolItem
{
private ushort string_index;
private string s;
internal ConstantPoolItemString(BigEndianBinaryReader br)
{
string_index = br.ReadUInt16();
}
internal override void Resolve(ClassFile classFile, string[] utf8_cp, ClassFileParseOptions options)
{
s = classFile.GetConstantPoolUtf8String(utf8_cp, string_index);
}
internal override ConstantType GetConstantType()
{
return ConstantType.String;
}
internal string Value
{
get
{
return s;
}
}
}
// this is only used to copy strings into "constantpool" when we see a RuntimeVisibleTypeAnnotations attribute,
// because we need a consistent way of exposing constant pool items to the runtime and that case
private sealed class ConstantPoolItemUtf8 : ConstantPoolItem
{
private readonly string str;
internal ConstantPoolItemUtf8(string str)
{
this.str = str;
}
internal override object GetRuntimeValue()
{
return str;
}
}
private sealed class ConstantPoolItemLiveObject : ConstantPoolItem
{
internal readonly object Value;
internal ConstantPoolItemLiveObject(object value)
{
this.Value = value;
}
internal override ConstantType GetConstantType()
{
return ConstantType.LiveObject;
}
}
internal enum Constant
{
Utf8 = 1,
Integer = 3,
Float = 4,
Long = 5,
Double = 6,
Class = 7,
String = 8,
Fieldref = 9,
Methodref = 10,
InterfaceMethodref = 11,
NameAndType = 12,
MethodHandle = 15,
MethodType = 16,
InvokeDynamic = 18,
}
internal abstract class FieldOrMethod : IEquatable<FieldOrMethod>
{
// Note that Modifiers is a ushort, so it combines nicely with the following ushort field
protected Modifiers access_flags;
protected ushort flags;
private string name;
private string descriptor;
protected string signature;
protected object[] annotations;
protected byte[] runtimeVisibleTypeAnnotations;
internal FieldOrMethod(ClassFile classFile, string[] utf8_cp, BigEndianBinaryReader br)
{
access_flags = (Modifiers)br.ReadUInt16();
name = String.Intern(classFile.GetConstantPoolUtf8String(utf8_cp, br.ReadUInt16()));
descriptor = classFile.GetConstantPoolUtf8String(utf8_cp, br.ReadUInt16());
ValidateSig(classFile, descriptor);
descriptor = String.Intern(descriptor.Replace('/', '.'));
}
protected abstract void ValidateSig(ClassFile classFile, string descriptor);
internal string Name
{
get
{
return name;
}
}
internal string Signature
{
get
{
return descriptor;
}
}
internal object[] Annotations
{
get
{
return annotations;
}
}
internal string GenericSignature
{
get
{
return signature;
}
}
internal Modifiers Modifiers
{
get
{
return (Modifiers)access_flags;
}
}
internal bool IsAbstract
{
get
{
return (access_flags & Modifiers.Abstract) != 0;
}
}
internal bool IsFinal
{
get
{
return (access_flags & Modifiers.Final) != 0;
}
}
internal bool IsPublic
{
get
{
return (access_flags & Modifiers.Public) != 0;
}
}
internal bool IsPrivate
{
get
{
return (access_flags & Modifiers.Private) != 0;
}
}
internal bool IsProtected
{
get
{
return (access_flags & Modifiers.Protected) != 0;
}
}
internal bool IsStatic
{
get
{
return (access_flags & Modifiers.Static) != 0;
}
}
internal bool IsSynchronized
{
get
{
return (access_flags & Modifiers.Synchronized) != 0;
}
}
internal bool IsVolatile
{
get
{
return (access_flags & Modifiers.Volatile) != 0;
}
}
internal bool IsTransient
{
get
{
return (access_flags & Modifiers.Transient) != 0;
}
}
internal bool IsNative
{
get
{
return (access_flags & Modifiers.Native) != 0;
}
}
internal bool IsEnum
{
get
{
return (access_flags & Modifiers.Enum) != 0;
}
}
internal bool DeprecatedAttribute
{
get
{
return (flags & FLAG_MASK_DEPRECATED) != 0;
}
}
internal bool IsInternal
{
get
{
return (flags & FLAG_MASK_INTERNAL) != 0;
}
}
internal byte[] RuntimeVisibleTypeAnnotations
{
get
{
return runtimeVisibleTypeAnnotations;
}
}
public sealed override int GetHashCode()
{
return name.GetHashCode() ^ descriptor.GetHashCode();
}
public bool Equals(FieldOrMethod other)
{
return ReferenceEquals(name, other.name) && ReferenceEquals(descriptor, other.descriptor);
}
}
internal sealed class Field : FieldOrMethod
{
private object constantValue;
private string[] propertyGetterSetter;
internal Field(ClassFile classFile, string[] utf8_cp, BigEndianBinaryReader br) : base(classFile, utf8_cp, br)
{
if((IsPrivate && IsPublic) || (IsPrivate && IsProtected) || (IsPublic && IsProtected)
|| (IsFinal && IsVolatile)
|| (classFile.IsInterface && (!IsPublic || !IsStatic || !IsFinal || IsTransient)))
{
throw new ClassFormatError("{0} (Illegal field modifiers: 0x{1:X})", classFile.Name, access_flags);
}
int attributes_count = br.ReadUInt16();
for(int i = 0; i < attributes_count; i++)
{
switch(classFile.GetConstantPoolUtf8String(utf8_cp, br.ReadUInt16()))
{
case "Deprecated":
if(br.ReadUInt32() != 0)
{
throw new ClassFormatError("Invalid Deprecated attribute length");
}
flags |= FLAG_MASK_DEPRECATED;
break;
case "ConstantValue":
{
if(br.ReadUInt32() != 2)
{
throw new ClassFormatError("Invalid ConstantValue attribute length");
}
ushort index = br.ReadUInt16();
try
{
switch(Signature)
{
case "I":
constantValue = classFile.GetConstantPoolConstantInteger(index);
break;
case "S":
constantValue = (short)classFile.GetConstantPoolConstantInteger(index);
break;
case "B":
constantValue = (byte)classFile.GetConstantPoolConstantInteger(index);
break;
case "C":
constantValue = (char)classFile.GetConstantPoolConstantInteger(index);
break;
case "Z":
constantValue = classFile.GetConstantPoolConstantInteger(index) != 0;
break;
case "J":
constantValue = classFile.GetConstantPoolConstantLong(index);
break;
case "F":
constantValue = classFile.GetConstantPoolConstantFloat(index);
break;
case "D":
constantValue = classFile.GetConstantPoolConstantDouble(index);
break;
case "Ljava.lang.String;":
constantValue = classFile.GetConstantPoolConstantString(index);
break;
default:
throw new ClassFormatError("{0} (Invalid signature for constant)", classFile.Name);
}
}
catch(InvalidCastException)
{
throw new ClassFormatError("{0} (Bad index into constant pool)", classFile.Name);
}
catch(IndexOutOfRangeException)
{
throw new ClassFormatError("{0} (Bad index into constant pool)", classFile.Name);
}
catch(InvalidOperationException)
{
throw new ClassFormatError("{0} (Bad index into constant pool)", classFile.Name);
}
catch(NullReferenceException)
{
throw new ClassFormatError("{0} (Bad index into constant pool)", classFile.Name);
}
break;
}
case "Signature":
if(classFile.MajorVersion < 49)
{
goto default;
}
if(br.ReadUInt32() != 2)
{
throw new ClassFormatError("Signature attribute has incorrect length");
}
signature = classFile.GetConstantPoolUtf8String(utf8_cp, br.ReadUInt16());
break;
case "RuntimeVisibleAnnotations":
if(classFile.MajorVersion < 49)
{
goto default;
}
annotations = ReadAnnotations(br, classFile, utf8_cp);
break;
case "RuntimeInvisibleAnnotations":
if(classFile.MajorVersion < 49)
{
goto default;
}
foreach(object[] annot in ReadAnnotations(br, classFile, utf8_cp))
{
if(annot[1].Equals("Likvm/lang/Property;"))
{
DecodePropertyAnnotation(classFile, annot);
}
#if STATIC_COMPILER
else if(annot[1].Equals("Likvm/lang/Internal;"))
{
this.access_flags &= ~Modifiers.AccessMask;
flags |= FLAG_MASK_INTERNAL;
}
#endif
}
break;
case "RuntimeVisibleTypeAnnotations":
if (classFile.MajorVersion < 52)
{
goto default;
}
classFile.CreateUtf8ConstantPoolItems(utf8_cp);
runtimeVisibleTypeAnnotations = br.Section(br.ReadUInt32()).ToArray();
break;
default:
br.Skip(br.ReadUInt32());
break;
}
}
}
private void DecodePropertyAnnotation(ClassFile classFile, object[] annot)
{
if(propertyGetterSetter != null)
{
Tracer.Error(Tracer.ClassLoading, "Ignoring duplicate ikvm.lang.Property annotation on {0}.{1}", classFile.Name, this.Name);
return;
}
propertyGetterSetter = new string[2];
for(int i = 2; i < annot.Length - 1; i += 2)
{
string value = annot[i + 1] as string;
if(value == null)
{
propertyGetterSetter = null;
break;
}
if(annot[i].Equals("get") && propertyGetterSetter[0] == null)
{
propertyGetterSetter[0] = value;
}
else if(annot[i].Equals("set") && propertyGetterSetter[1] == null)
{
propertyGetterSetter[1] = value;
}
else
{
propertyGetterSetter = null;
break;
}
}
if(propertyGetterSetter == null || propertyGetterSetter[0] == null)
{
propertyGetterSetter = null;
Tracer.Error(Tracer.ClassLoading, "Ignoring malformed ikvm.lang.Property annotation on {0}.{1}", classFile.Name, this.Name);
return;
}
}
protected override void ValidateSig(ClassFile classFile, string descriptor)
{
if(!IsValidFieldSig(descriptor))
{
throw new ClassFormatError("{0} (Field \"{1}\" has invalid signature \"{2}\")", classFile.Name, this.Name, descriptor);
}
}
internal object ConstantValue
{
get
{
return constantValue;
}
}
internal bool IsStaticFinalConstant
{
get { return (access_flags & (Modifiers.Final | Modifiers.Static)) == (Modifiers.Final | Modifiers.Static) && constantValue != null; }
}
internal bool IsProperty
{
get
{
return propertyGetterSetter != null;
}
}
internal string PropertyGetter
{
get
{
return propertyGetterSetter[0];
}
}
internal string PropertySetter
{
get
{
return propertyGetterSetter[1];
}
}
}
internal sealed class Method : FieldOrMethod
{
private Code code;
private string[] exceptions;
private LowFreqData low;
private MethodParametersEntry[] parameters;
sealed class LowFreqData
{
internal object annotationDefault;
internal object[][] parameterAnnotations;
#if STATIC_COMPILER
internal string DllExportName;
internal int DllExportOrdinal;
internal string InterlockedCompareAndSetField;
#endif
}
internal Method(ClassFile classFile, string[] utf8_cp, ClassFileParseOptions options, BigEndianBinaryReader br) : base(classFile, utf8_cp, br)
{
// vmspec 4.6 says that all flags, except ACC_STRICT are ignored on <clinit>
// however, since Java 7 it does need to be marked static
if(ReferenceEquals(Name, StringConstants.CLINIT) && ReferenceEquals(Signature, StringConstants.SIG_VOID) && (classFile.MajorVersion < 51 || IsStatic))
{
access_flags &= Modifiers.Strictfp;
access_flags |= (Modifiers.Static | Modifiers.Private);
}
else
{
// LAMESPEC: vmspec 4.6 says that abstract methods can not be strictfp (and this makes sense), but
// javac (pre 1.5) is broken and marks abstract methods as strictfp (if you put the strictfp on the class)
if((ReferenceEquals(Name, StringConstants.INIT) && (IsStatic || IsSynchronized || IsFinal || IsAbstract || IsNative))
|| (IsPrivate && IsPublic) || (IsPrivate && IsProtected) || (IsPublic && IsProtected)
|| (IsAbstract && (IsFinal || IsNative || IsPrivate || IsStatic || IsSynchronized))
|| (classFile.IsInterface && classFile.MajorVersion <= 51 && (!IsPublic || IsFinal || IsNative || IsSynchronized || !IsAbstract))
|| (classFile.IsInterface && classFile.MajorVersion >= 52 && (!(IsPublic || IsPrivate) || IsFinal || IsNative || IsSynchronized)))
{
throw new ClassFormatError("Method {0} in class {1} has illegal modifiers: 0x{2:X}", Name, classFile.Name, (int)access_flags);
}
}
int attributes_count = br.ReadUInt16();
for(int i = 0; i < attributes_count; i++)
{
switch(classFile.GetConstantPoolUtf8String(utf8_cp, br.ReadUInt16()))
{
case "Deprecated":
if(br.ReadUInt32() != 0)
{
throw new ClassFormatError("Invalid Deprecated attribute length");
}
flags |= FLAG_MASK_DEPRECATED;
break;
case "Code":
{
if(!code.IsEmpty)
{
throw new ClassFormatError("{0} (Duplicate Code attribute)", classFile.Name);
}
BigEndianBinaryReader rdr = br.Section(br.ReadUInt32());
code.Read(classFile, utf8_cp, this, rdr, options);
if(!rdr.IsAtEnd)
{
throw new ClassFormatError("{0} (Code attribute has wrong length)", classFile.Name);
}
break;
}
case "Exceptions":
{
if(exceptions != null)
{
throw new ClassFormatError("{0} (Duplicate Exceptions attribute)", classFile.Name);
}
BigEndianBinaryReader rdr = br.Section(br.ReadUInt32());
ushort count = rdr.ReadUInt16();
exceptions = new string[count];
for(int j = 0; j < count; j++)
{
exceptions[j] = classFile.GetConstantPoolClass(rdr.ReadUInt16());
}
if(!rdr.IsAtEnd)
{
throw new ClassFormatError("{0} (Exceptions attribute has wrong length)", classFile.Name);
}
break;
}
case "Signature":
if(classFile.MajorVersion < 49)
{
goto default;
}
if(br.ReadUInt32() != 2)
{
throw new ClassFormatError("Signature attribute has incorrect length");
}
signature = classFile.GetConstantPoolUtf8String(utf8_cp, br.ReadUInt16());
break;
case "RuntimeVisibleAnnotations":
if(classFile.MajorVersion < 49)
{
goto default;
}
annotations = ReadAnnotations(br, classFile, utf8_cp);
if ((options & ClassFileParseOptions.TrustedAnnotations) != 0)
{
foreach(object[] annot in annotations)
{
switch((string)annot[1])
{
#if STATIC_COMPILER
case "Lsun/reflect/CallerSensitive;":
flags |= FLAG_CALLERSENSITIVE;
break;
#endif
case "Ljava/lang/invoke/LambdaForm$Compiled;":
flags |= FLAG_LAMBDAFORM_COMPILED;
break;
case "Ljava/lang/invoke/LambdaForm$Hidden;":
flags |= FLAG_LAMBDAFORM_HIDDEN;
break;
case "Ljava/lang/invoke/ForceInline;":
flags |= FLAG_FORCEINLINE;
break;
}
}
}
break;
case "RuntimeVisibleParameterAnnotations":
{
if(classFile.MajorVersion < 49)
{
goto default;
}
if(low == null)
{
low = new LowFreqData();
}
BigEndianBinaryReader rdr = br.Section(br.ReadUInt32());
byte num_parameters = rdr.ReadByte();
low.parameterAnnotations = new object[num_parameters][];
for(int j = 0; j < num_parameters; j++)
{
ushort num_annotations = rdr.ReadUInt16();
low.parameterAnnotations[j] = new object[num_annotations];
for(int k = 0; k < num_annotations; k++)
{
low.parameterAnnotations[j][k] = ReadAnnotation(rdr, classFile, utf8_cp);
}
}
if(!rdr.IsAtEnd)
{
throw new ClassFormatError("{0} (RuntimeVisibleParameterAnnotations attribute has wrong length)", classFile.Name);
}
break;
}
case "AnnotationDefault":
{
if(classFile.MajorVersion < 49)
{
goto default;
}
if(low == null)
{
low = new LowFreqData();
}
BigEndianBinaryReader rdr = br.Section(br.ReadUInt32());
low.annotationDefault = ReadAnnotationElementValue(rdr, classFile, utf8_cp);
if(!rdr.IsAtEnd)
{
throw new ClassFormatError("{0} (AnnotationDefault attribute has wrong length)", classFile.Name);
}
break;
}
#if STATIC_COMPILER
case "RuntimeInvisibleAnnotations":
if(classFile.MajorVersion < 49)
{
goto default;
}
foreach(object[] annot in ReadAnnotations(br, classFile, utf8_cp))
{
if(annot[1].Equals("Likvm/lang/Internal;"))
{
if (classFile.IsInterface)
{
StaticCompiler.IssueMessage(Message.InterfaceMethodCantBeInternal, classFile.Name, this.Name, this.Signature);
}
else
{
this.access_flags &= ~Modifiers.AccessMask;
flags |= FLAG_MASK_INTERNAL;
}
}
if(annot[1].Equals("Likvm/lang/DllExport;"))
{
string name = null;
int? ordinal = null;
for (int j = 2; j < annot.Length; j += 2)
{
if (annot[j].Equals("name") && annot[j + 1] is string)
{
name = (string)annot[j + 1];
}
else if (annot[j].Equals("ordinal") && annot[j + 1] is int)
{
ordinal = (int)annot[j + 1];
}
}
if (name != null && ordinal != null)
{
if (!IsStatic)
{
StaticCompiler.IssueMessage(Message.DllExportMustBeStaticMethod, classFile.Name, this.Name, this.Signature);
}
else
{
if (low == null)
{
low = new LowFreqData();
}
low.DllExportName = name;
low.DllExportOrdinal = ordinal.Value;
}
}
}
if(annot[1].Equals("Likvm/internal/InterlockedCompareAndSet;"))
{
string field = null;
for (int j = 2; j < annot.Length; j += 2)
{
if (annot[j].Equals("value") && annot[j + 1] is string)
{
field = (string)annot[j + 1];
}
}
if (field != null)
{
if (low == null)
{
low = new LowFreqData();
}
low.InterlockedCompareAndSetField = field;
}
}
}
break;
#endif
case "MethodParameters":
{
if(classFile.MajorVersion < 52)
{
goto default;
}
if(parameters != null)
{
throw new ClassFormatError("{0} (Duplicate MethodParameters attribute)", classFile.Name);
}
parameters = ReadMethodParameters(br, utf8_cp);
break;
}
case "RuntimeVisibleTypeAnnotations":
if (classFile.MajorVersion < 52)
{
goto default;
}
classFile.CreateUtf8ConstantPoolItems(utf8_cp);
runtimeVisibleTypeAnnotations = br.Section(br.ReadUInt32()).ToArray();
break;
default:
br.Skip(br.ReadUInt32());
break;
}
}
if(IsAbstract || IsNative)
{
if(!code.IsEmpty)
{
throw new ClassFormatError("Code attribute in native or abstract methods in class file " + classFile.Name);
}
}
else
{
if(code.IsEmpty)
{
if(ReferenceEquals(this.Name, StringConstants.CLINIT))
{
code.verifyError = string.Format("Class {0}, method {1} signature {2}: No Code attribute", classFile.Name, this.Name, this.Signature);
return;
}
throw new ClassFormatError("Absent Code attribute in method that is not native or abstract in class file " + classFile.Name);
}
}
}
private static MethodParametersEntry[] ReadMethodParameters(BigEndianBinaryReader br, string[] utf8_cp)
{
uint length = br.ReadUInt32();
if(length > 0)
{
BigEndianBinaryReader rdr = br.Section(length);
byte parameters_count = rdr.ReadByte();
if(length == 1 + parameters_count * 4)
{
MethodParametersEntry[] parameters = new MethodParametersEntry[parameters_count];
for(int j = 0; j < parameters_count; j++)
{
ushort name = rdr.ReadUInt16();
if(name >= utf8_cp.Length || (name != 0 && utf8_cp[name] == null))
{
return MethodParametersEntry.Malformed;
}
parameters[j].name = utf8_cp[name];
parameters[j].flags = rdr.ReadUInt16();
}
return parameters;
}
}
throw new ClassFormatError("Invalid MethodParameters method attribute length " + length + " in class file");
}
protected override void ValidateSig(ClassFile classFile, string descriptor)
{
if(!IsValidMethodSig(descriptor))
{
throw new ClassFormatError("{0} (Method \"{1}\" has invalid signature \"{2}\")", classFile.Name, this.Name, descriptor);
}
}
internal bool IsStrictfp
{
get
{
return (access_flags & Modifiers.Strictfp) != 0;
}
}
internal bool IsVirtual
{
get
{
return (access_flags & (Modifiers.Static | Modifiers.Private)) == 0
&& !IsConstructor;
}
}
// Is this the <clinit>()V method?
internal bool IsClassInitializer
{
get
{
return ReferenceEquals(Name, StringConstants.CLINIT) && ReferenceEquals(Signature, StringConstants.SIG_VOID) && IsStatic;
}
}
internal bool IsConstructor
{
get
{
return ReferenceEquals(Name, StringConstants.INIT);
}
}
#if STATIC_COMPILER
internal bool IsCallerSensitive
{
get
{
return (flags & FLAG_CALLERSENSITIVE) != 0;
}
}
#endif
internal bool IsLambdaFormCompiled
{
get
{
return (flags & FLAG_LAMBDAFORM_COMPILED) != 0;
}
}
internal bool IsLambdaFormHidden
{
get
{
return (flags & FLAG_LAMBDAFORM_HIDDEN) != 0;
}
}
internal bool IsForceInline
{
get
{
return (flags & FLAG_FORCEINLINE) != 0;
}
}
internal string[] ExceptionsAttribute
{
get
{
return exceptions;
}
}
internal object[][] ParameterAnnotations
{
get
{
return low == null ? null : low.parameterAnnotations;
}
}
internal object AnnotationDefault
{
get
{
return low == null ? null : low.annotationDefault;
}
}
#if STATIC_COMPILER
internal string DllExportName
{
get
{
return low == null ? null : low.DllExportName;
}
}
internal int DllExportOrdinal
{
get
{
return low == null ? -1 : low.DllExportOrdinal;
}
}
internal string InterlockedCompareAndSetField
{
get
{
return low == null ? null : low.InterlockedCompareAndSetField;
}
}
#endif
internal string VerifyError
{
get
{
return code.verifyError;
}
}
// maps argument 'slot' (as encoded in the xload/xstore instructions) into the ordinal
internal int[] ArgMap
{
get
{
return code.argmap;
}
}
internal int MaxStack
{
get
{
return code.max_stack;
}
}
internal int MaxLocals
{
get
{
return code.max_locals;
}
}
internal Instruction[] Instructions
{
get
{
return code.instructions;
}
set
{
code.instructions = value;
}
}
internal ExceptionTableEntry[] ExceptionTable
{
get
{
return code.exception_table;
}
set
{
code.exception_table = value;
}
}
internal LineNumberTableEntry[] LineNumberTableAttribute
{
get
{
return code.lineNumberTable;
}
}
internal LocalVariableTableEntry[] LocalVariableTableAttribute
{
get
{
return code.localVariableTable;
}
}
internal MethodParametersEntry[] MethodParameters
{
get
{
return parameters;
}
}
internal bool MalformedMethodParameters
{
get
{
return parameters == MethodParametersEntry.Malformed;
}
}
internal bool HasJsr
{
get
{
return code.hasJsr;
}
}
private struct Code
{
internal bool hasJsr;
internal string verifyError;
internal ushort max_stack;
internal ushort max_locals;
internal Instruction[] instructions;
internal ExceptionTableEntry[] exception_table;
internal int[] argmap;
internal LineNumberTableEntry[] lineNumberTable;
internal LocalVariableTableEntry[] localVariableTable;
internal void Read(ClassFile classFile, string[] utf8_cp, Method method, BigEndianBinaryReader br, ClassFileParseOptions options)
{
max_stack = br.ReadUInt16();
max_locals = br.ReadUInt16();
uint code_length = br.ReadUInt32();
if(code_length == 0 || code_length > 65535)
{
throw new ClassFormatError("Invalid method Code length {1} in class file {0}", classFile.Name, code_length);
}
Instruction[] instructions = new Instruction[code_length + 1];
int basePosition = br.Position;
int instructionIndex = 0;
try
{
BigEndianBinaryReader rdr = br.Section(code_length);
while(!rdr.IsAtEnd)
{
instructions[instructionIndex].Read((ushort)(rdr.Position - basePosition), rdr, classFile);
hasJsr |= instructions[instructionIndex].NormalizedOpCode == NormalizedByteCode.__jsr;
instructionIndex++;
}
// we add an additional nop instruction to make it easier for consumers of the code array
instructions[instructionIndex++].SetTermNop((ushort)(rdr.Position - basePosition));
}
catch(ClassFormatError x)
{
// any class format errors in the code block are actually verify errors
verifyError = x.Message;
}
this.instructions = new Instruction[instructionIndex];
Array.Copy(instructions, 0, this.instructions, 0, instructionIndex);
// build the pcIndexMap
int[] pcIndexMap = new int[this.instructions[instructionIndex - 1].PC + 1];
for(int i = 0; i < pcIndexMap.Length; i++)
{
pcIndexMap[i] = -1;
}
for(int i = 0; i < instructionIndex - 1; i++)
{
pcIndexMap[this.instructions[i].PC] = i;
}
// convert branch offsets to indexes
for(int i = 0; i < instructionIndex - 1; i++)
{
switch(this.instructions[i].NormalizedOpCode)
{
case NormalizedByteCode.__ifeq:
case NormalizedByteCode.__ifne:
case NormalizedByteCode.__iflt:
case NormalizedByteCode.__ifge:
case NormalizedByteCode.__ifgt:
case NormalizedByteCode.__ifle:
case NormalizedByteCode.__if_icmpeq:
case NormalizedByteCode.__if_icmpne:
case NormalizedByteCode.__if_icmplt:
case NormalizedByteCode.__if_icmpge:
case NormalizedByteCode.__if_icmpgt:
case NormalizedByteCode.__if_icmple:
case NormalizedByteCode.__if_acmpeq:
case NormalizedByteCode.__if_acmpne:
case NormalizedByteCode.__ifnull:
case NormalizedByteCode.__ifnonnull:
case NormalizedByteCode.__goto:
case NormalizedByteCode.__jsr:
this.instructions[i].SetTargetIndex(pcIndexMap[this.instructions[i].Arg1 + this.instructions[i].PC]);
break;
case NormalizedByteCode.__tableswitch:
case NormalizedByteCode.__lookupswitch:
this.instructions[i].MapSwitchTargets(pcIndexMap);
break;
}
}
// read exception table
ushort exception_table_length = br.ReadUInt16();
exception_table = new ExceptionTableEntry[exception_table_length];
for(int i = 0; i < exception_table_length; i++)
{
ushort start_pc = br.ReadUInt16();
ushort end_pc = br.ReadUInt16();
ushort handler_pc = br.ReadUInt16();
ushort catch_type = br.ReadUInt16();
if(start_pc >= end_pc
|| end_pc > code_length
|| handler_pc >= code_length
|| (catch_type != 0 && !classFile.SafeIsConstantPoolClass(catch_type)))
{
throw new ClassFormatError("Illegal exception table: {0}.{1}{2}", classFile.Name, method.Name, method.Signature);
}
classFile.MarkLinkRequiredConstantPoolItem(catch_type);
// if start_pc, end_pc or handler_pc is invalid (i.e. doesn't point to the start of an instruction),
// the index will be -1 and this will be handled by the verifier
int startIndex = pcIndexMap[start_pc];
int endIndex;
if (end_pc == code_length)
{
// it is legal for end_pc to point to just after the last instruction,
// but since there isn't an entry in our pcIndexMap for that, we have
// a special case for this
endIndex = instructionIndex - 1;
}
else
{
endIndex = pcIndexMap[end_pc];
}
int handlerIndex = pcIndexMap[handler_pc];
exception_table[i] = new ExceptionTableEntry(startIndex, endIndex, handlerIndex, catch_type, i);
}
ushort attributes_count = br.ReadUInt16();
for(int i = 0; i < attributes_count; i++)
{
switch(classFile.GetConstantPoolUtf8String(utf8_cp, br.ReadUInt16()))
{
case "LineNumberTable":
if((options & ClassFileParseOptions.LineNumberTable) != 0)
{
BigEndianBinaryReader rdr = br.Section(br.ReadUInt32());
int count = rdr.ReadUInt16();
lineNumberTable = new LineNumberTableEntry[count];
for(int j = 0; j < count; j++)
{
lineNumberTable[j].start_pc = rdr.ReadUInt16();
lineNumberTable[j].line_number = rdr.ReadUInt16();
if(lineNumberTable[j].start_pc >= code_length)
{
throw new ClassFormatError("{0} (LineNumberTable has invalid pc)", classFile.Name);
}
}
if(!rdr.IsAtEnd)
{
throw new ClassFormatError("{0} (LineNumberTable attribute has wrong length)", classFile.Name);
}
}
else
{
br.Skip(br.ReadUInt32());
}
break;
case "LocalVariableTable":
if((options & ClassFileParseOptions.LocalVariableTable) != 0)
{
BigEndianBinaryReader rdr = br.Section(br.ReadUInt32());
int count = rdr.ReadUInt16();
localVariableTable = new LocalVariableTableEntry[count];
for(int j = 0; j < count; j++)
{
localVariableTable[j].start_pc = rdr.ReadUInt16();
localVariableTable[j].length = rdr.ReadUInt16();
localVariableTable[j].name = classFile.GetConstantPoolUtf8String(utf8_cp, rdr.ReadUInt16());
localVariableTable[j].descriptor = classFile.GetConstantPoolUtf8String(utf8_cp, rdr.ReadUInt16()).Replace('/', '.');
localVariableTable[j].index = rdr.ReadUInt16();
}
// NOTE we're intentionally not checking that we're at the end of the section
// (optional attributes shouldn't cause ClassFormatError)
}
else
{
br.Skip(br.ReadUInt32());
}
break;
default:
br.Skip(br.ReadUInt32());
break;
}
}
// build the argmap
string sig = method.Signature;
List<int> args = new List<int>();
int pos = 0;
if(!method.IsStatic)
{
args.Add(pos++);
}
for(int i = 1; sig[i] != ')'; i++)
{
args.Add(pos++);
switch(sig[i])
{
case 'L':
i = sig.IndexOf(';', i);
break;
case 'D':
case 'J':
args.Add(-1);
break;
case '[':
{
while(sig[i] == '[')
{
i++;
}
if(sig[i] == 'L')
{
i = sig.IndexOf(';', i);
}
break;
}
}
}
argmap = args.ToArray();
if(args.Count > max_locals)
{
throw new ClassFormatError("{0} (Arguments can't fit into locals)", classFile.Name);
}
}
internal bool IsEmpty
{
get
{
return instructions == null;
}
}
}
internal sealed class ExceptionTableEntry
{
internal readonly int startIndex;
internal readonly int endIndex;
internal readonly int handlerIndex;
internal readonly ushort catch_type;
internal readonly int ordinal;
internal readonly bool isFinally;
internal ExceptionTableEntry(int startIndex, int endIndex, int handlerIndex, ushort catch_type, int ordinal)
: this(startIndex, endIndex, handlerIndex, catch_type, ordinal, false)
{
}
internal ExceptionTableEntry(int startIndex, int endIndex, int handlerIndex, ushort catch_type, int ordinal, bool isFinally)
{
this.startIndex = startIndex;
this.endIndex = endIndex;
this.handlerIndex = handlerIndex;
this.catch_type = catch_type;
this.ordinal = ordinal;
this.isFinally = isFinally;
}
}
[Flags]
internal enum InstructionFlags : byte
{
Reachable = 1,
Processed = 2,
BranchTarget = 4,
}
internal struct Instruction
{
private ushort pc;
private NormalizedByteCode normopcode;
private int arg1;
private short arg2;
private SwitchEntry[] switch_entries;
struct SwitchEntry
{
internal int value;
internal int target;
}
internal void SetHardError(HardError error, int messageId)
{
normopcode = NormalizedByteCode.__static_error;
arg2 = (short)error;
arg1 = messageId;
}
internal HardError HardError
{
get
{
return (HardError)arg2;
}
}
internal int HandlerIndex
{
get { return (ushort)arg2; }
}
internal int HardErrorMessageId
{
get
{
return arg1;
}
}
internal void PatchOpCode(NormalizedByteCode bc)
{
this.normopcode = bc;
}
internal void PatchOpCode(NormalizedByteCode bc, int arg1)
{
this.normopcode = bc;
this.arg1 = arg1;
}
internal void PatchOpCode(NormalizedByteCode bc, int arg1, short arg2)
{
this.normopcode = bc;
this.arg1 = arg1;
this.arg2 = arg2;
}
internal void SetPC(int pc)
{
this.pc = (ushort)pc;
}
internal void SetTargetIndex(int targetIndex)
{
this.arg1 = targetIndex;
}
internal void SetTermNop(ushort pc)
{
// TODO what happens if we already have exactly the maximum number of instructions?
this.pc = pc;
this.normopcode = NormalizedByteCode.__nop;
}
internal void MapSwitchTargets(int[] pcIndexMap)
{
arg1 = pcIndexMap[arg1 + pc];
for (int i = 0; i < switch_entries.Length; i++)
{
switch_entries[i].target = pcIndexMap[switch_entries[i].target + pc];
}
}
internal void Read(ushort pc, BigEndianBinaryReader br, ClassFile classFile)
{
this.pc = pc;
ByteCode bc = (ByteCode)br.ReadByte();
switch(ByteCodeMetaData.GetMode(bc))
{
case ByteCodeMode.Simple:
break;
case ByteCodeMode.Constant_1:
arg1 = br.ReadByte();
classFile.MarkLinkRequiredConstantPoolItem(arg1);
break;
case ByteCodeMode.Local_1:
arg1 = br.ReadByte();
break;
case ByteCodeMode.Constant_2:
arg1 = br.ReadUInt16();
classFile.MarkLinkRequiredConstantPoolItem(arg1);
break;
case ByteCodeMode.Branch_2:
arg1 = br.ReadInt16();
break;
case ByteCodeMode.Branch_4:
arg1 = br.ReadInt32();
break;
case ByteCodeMode.Constant_2_1_1:
arg1 = br.ReadUInt16();
classFile.MarkLinkRequiredConstantPoolItem(arg1);
arg2 = br.ReadByte();
if(br.ReadByte() != 0)
{
throw new ClassFormatError("invokeinterface filler must be zero");
}
break;
case ByteCodeMode.Immediate_1:
arg1 = br.ReadSByte();
break;
case ByteCodeMode.Immediate_2:
arg1 = br.ReadInt16();
break;
case ByteCodeMode.Local_1_Immediate_1:
arg1 = br.ReadByte();
arg2 = br.ReadSByte();
break;
case ByteCodeMode.Constant_2_Immediate_1:
arg1 = br.ReadUInt16();
classFile.MarkLinkRequiredConstantPoolItem(arg1);
arg2 = br.ReadSByte();
break;
case ByteCodeMode.Tableswitch:
{
// skip the padding
uint p = pc + 1u;
uint align = ((p + 3) & 0x7ffffffc) - p;
br.Skip(align);
int default_offset = br.ReadInt32();
this.arg1 = default_offset;
int low = br.ReadInt32();
int high = br.ReadInt32();
if(low > high || high > 16384L + low)
{
throw new ClassFormatError("Incorrect tableswitch");
}
SwitchEntry[] entries = new SwitchEntry[high - low + 1];
for(int i = low; i < high; i++)
{
entries[i - low].value = i;
entries[i - low].target = br.ReadInt32();
}
// do the last entry outside the loop, to avoid overflowing "i", if high == int.MaxValue
entries[high - low].value = high;
entries[high - low].target = br.ReadInt32();
this.switch_entries = entries;
break;
}
case ByteCodeMode.Lookupswitch:
{
// skip the padding
uint p = pc + 1u;
uint align = ((p + 3) & 0x7ffffffc) - p;
br.Skip(align);
int default_offset = br.ReadInt32();
this.arg1 = default_offset;
int count = br.ReadInt32();
if(count < 0 || count > 16384)
{
throw new ClassFormatError("Incorrect lookupswitch");
}
SwitchEntry[] entries = new SwitchEntry[count];
for(int i = 0; i < count; i++)
{
entries[i].value = br.ReadInt32();
entries[i].target = br.ReadInt32();
}
this.switch_entries = entries;
break;
}
case ByteCodeMode.WidePrefix:
bc = (ByteCode)br.ReadByte();
// NOTE the PC of a wide instruction is actually the PC of the
// wide prefix, not the following instruction (vmspec 4.9.2)
switch(ByteCodeMetaData.GetWideMode(bc))
{
case ByteCodeModeWide.Local_2:
arg1 = br.ReadUInt16();
break;
case ByteCodeModeWide.Local_2_Immediate_2:
arg1 = br.ReadUInt16();
arg2 = br.ReadInt16();
break;
default:
throw new ClassFormatError("Invalid wide prefix on opcode: {0}", bc);
}
break;
default:
throw new ClassFormatError("Invalid opcode: {0}", bc);
}
this.normopcode = ByteCodeMetaData.GetNormalizedByteCode(bc);
arg1 = ByteCodeMetaData.GetArg(bc, arg1);
}
internal int PC
{
get
{
return pc;
}
}
internal NormalizedByteCode NormalizedOpCode
{
get
{
return normopcode;
}
}
internal int Arg1
{
get
{
return arg1;
}
}
internal int TargetIndex
{
get
{
return arg1;
}
set
{
arg1 = value;
}
}
internal int Arg2
{
get
{
return arg2;
}
}
internal int NormalizedArg1
{
get
{
return arg1;
}
}
internal int DefaultTarget
{
get
{
return arg1;
}
set
{
arg1 = value;
}
}
internal int SwitchEntryCount
{
get
{
return switch_entries.Length;
}
}
internal int GetSwitchValue(int i)
{
return switch_entries[i].value;
}
internal int GetSwitchTargetIndex(int i)
{
return switch_entries[i].target;
}
internal void SetSwitchTargets(int[] targets)
{
SwitchEntry[] newEntries = (SwitchEntry[])switch_entries.Clone();
for (int i = 0; i < newEntries.Length; i++)
{
newEntries[i].target = targets[i];
}
switch_entries = newEntries;
}
}
internal struct LineNumberTableEntry
{
internal ushort start_pc;
internal ushort line_number;
}
internal struct LocalVariableTableEntry
{
internal ushort start_pc;
internal ushort length;
internal string name;
internal string descriptor;
internal ushort index;
}
}
internal Field GetField(string name, string sig)
{
for (int i = 0; i < fields.Length; i++)
{
if (fields[i].Name == name && fields[i].Signature == sig)
{
return fields[i];
}
}
return null;
}
internal bool HasSerialVersionUID
{
get
{
Field field = GetField("serialVersionUID", "J");
return field != null && field.IsStatic && field.IsFinal;
}
}
}
}
|