1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964
|
using System;
using System.IO;
using System.Collections;
using System.Text;
using System.Reflection;
namespace PEAPI {
#region Enums
/// <summary>
/// flags for the assembly (.corflags)
/// </summary>
public enum CorFlags {CF_IL_ONLY = 1, CF_32_BITREQUIRED = 2,
CF_STRONGNAMESIGNED = 8, CF_TRACKDEBUGDATA = 0x10000 }
/// <summary>
/// subsystem for the assembly (.subsystem)
/// </summary>
public enum SubSystem { Native = 1, Windows_GUI = 2,
Windows_CUI = 3, OS2_CUI = 5, POSIX_CUI = 7, Native_Windows = 8,
Windows_CE_GUI = 9}
/// <summary>
/// Hash algorithms for the assembly
/// </summary>
public enum HashAlgorithm { None, SHA1 }
/// <summary>
/// Attributes for this assembly
/// </summary>
public enum AssemAttr { Retargetable = 0x100, EnableJITCompileTracking = 0x8000,
DisableJITCompileOptimizer = 0x4000}
/// <summary>
/// Method call conventions
/// </summary>
[Flags]
public enum CallConv { Default, Cdecl, Stdcall, Thiscall,
Fastcall, Vararg, Instance = 0x20, Generic = 0x10, InstanceExplicit = 0x60 }
/// <summary>
/// Type custom modifier
/// </summary>
public enum CustomModifier { modreq = 0x1F, modopt };
/// <summary>
/// Attibutes for a class
/// </summary>
[Flags]
public enum TypeAttr {Private, Public, NestedPublic, NestedPrivate,
NestedFamily, NestedAssembly, NestedFamAndAssem, NestedFamOrAssem,
SequentialLayout, ExplicitLayout = 0x10, Interface = 0x20,
Abstract = 0x80, PublicAbstract = 0x81, Sealed = 0x100,
PublicSealed = 0x101, SpecialName = 0x400, RTSpecialName = 0x800,
Import = 0x1000, Serializable = 0x2000, UnicodeClass = 0x10000,
AutoClass = 0x20000, HasSecurity = 0x40000, BeforeFieldInit = 0x100000,
Forwarder = 0x200000,
VisibilityMask = 0x07 }
/// <summary>
/// Attributes for a field
/// </summary>
public enum FieldAttr {Default, Private, FamAndAssem, Assembly,
Family, FamOrAssem, Public, Static = 0x10, PublicStatic = 0x16,
Initonly = 0x20, Literal = 0x40, Notserialized = 0x80,
SpecialName = 0x200, RTSpecialName = 0x400, HasFieldMarshal = 0x1000 }
/// <summary>
/// Attributes for a method
/// </summary>
public enum MethAttr { Default, Private, FamAndAssem, Assembly,
Family, FamOrAssem, Public, Static = 0x0010, PublicStatic = 0x16,
Final = 0x0020, PublicStaticFinal = 0x36, Virtual = 0x0040,
PrivateVirtual, PublicVirtual = 0x0046, HideBySig = 0x0080,
NewSlot = 0x0100, Strict = 0x200, Abstract = 0x0400, SpecialName = 0x0800,
RTSpecialName = 0x1000, SpecialRTSpecialName = 0x1800,
HasSecurity = 0x4000, RequireSecObject = 0x8000}
/// <summary>
/// Attributes for .pinvokeimpl method declarations
/// </summary>
public enum PInvokeAttr { nomangle = 1, ansi = 2, unicode = 4, autochar = 6,
bestfit_on = 0x0010, bestfit_off = 0x0020, bestfit_mask = 0x0030,
lasterr = 0x0040, winapi = 0x0100, cdecl = 0x0200,
stdcall = 0x0300, thiscall = 0x0400, fastcall = 0x0500,
charmaperror_on = 0x1000, charmaperror_off = 0x2000
}
/// <summary>
/// Implementation attributes for a method
/// </summary>
public enum ImplAttr { IL, Native, Runtime = 0x03, Unmanaged = 0x04,
ForwardRef = 0x10, PreserveSig = 0x0080, InternalCall = 0x1000,
Synchronised = 0x0020, Synchronized = 0x0020, NoInLining = 0x0008, NoOptimization = 0x0040, Optil = 0x0002,
AggressiveInlining = 0x0100
}
/// <summary>
/// Storage location for initial field data
/// </summary>
public enum DataSegment { Data, TLS, CIL }
/// <summary>
/// Modes for a parameter
/// </summary>
public enum ParamAttr { Default, In, Out, Opt = 16, HasDefault = 0x1000, HasFieldMarshal = 0x2000 }
/// <summary>
/// CIL instructions
/// </summary>
public enum Op { nop, breakOp, ldarg_0, ldarg_1, ldarg_2, ldarg_3,
ldloc_0, ldloc_1, ldloc_2, ldloc_3, stloc_0, stloc_1, stloc_2, stloc_3,
ldnull = 0x14, ldc_i4_m1, ldc_i4_0, ldc_i4_1, ldc_i4_2, ldc_i4_3,
ldc_i4_4, ldc_i4_5, ldc_i4_6, ldc_i4_7, ldc_i4_8, dup = 0x25, pop,
ret = 0x2A, ldind_i1 = 0x46, ldind_u1, ldind_i2, ldind_u2, ldind_i4,
ldind_u4, ldind_i8, ldind_i, ldind_r4, ldind_r8, ldind_ref, stind_ref,
stind_i1, stind_i2, stind_i4, stind_i8, stind_r4, stind_r8, add, sub, mul,
div, div_un, rem, rem_un, and, or, xor, shl, shr, shr_un, neg, not,
conv_i1, conv_i2, conv_i4, conv_i8, conv_r4, conv_r8, conv_u4, conv_u8,
conv_r_un = 0x76, throwOp = 0x7A, conv_ovf_i1_un = 0x82, conv_ovf_i2_un,
conv_ovf_i4_un, conv_ovf_i8_un, conf_ovf_u1_un, conv_ovf_u2_un,
conv_ovf_u4_un, conv_ovf_u8_un, conv_ovf_i_un, conv_ovf_u_un,
ldlen = 0x8E, ldelem_i1 = 0x90, ldelem_u1, ldelem_i2, ldelem_u2,
ldelem_i4, ldelem_u4, ldelem_i8, ldelem_i, ldelem_r4, ldelem_r8,
ldelem_ref, stelem_i, stelem_i1, stelem_i2, stelem_i4, stelem_i8, stelem_r4 = 0xA0, stelem_r8,
stelem_ref, conv_ovf_i1 = 0xb3, conv_ovf_u1, conv_ovf_i2, conv_ovf_u2,
conv_ovf_i4, conv_ovf_u4, conv_ovf_i8, conv_ovf_u8, ckfinite = 0xC3,
conv_u2 = 0xD1, conv_u1, conv_i, conv_ovf_i, conv_ovf_u, add_ovf,
add_ovf_un, mul_ovf, mul_ovf_un, sub_ovf, sub_ovf_un, endfinally,
stind_i = 0xDF, conv_u, arglist = 0xFE00, ceq, cgt, cgt_un, clt, clt_un,
localloc = 0xFE0F, endfilter = 0xFE11, volatile_ = 0xFE13, tail_,
cpblk = 0xFE17, initblk, rethrow = 0xFE1A, refanytype = 0xFE1D, readonly_ = 0xFE1E }
/// <summary>
/// CIL instructions requiring an integer parameter
/// </summary>
public enum IntOp {ldarg_s = 0x0E, ldarga_s, starg_s, ldloc_s, ldloca_s,
stloc_s, ldc_i4_s = 0x1F, ldc_i4, ldarg = 0xFE09,
ldarga, starg, ldloc, ldloca, stloc, unaligned = 0xFE12 }
/// <summary>
/// CIL instructions requiring a field parameter
/// </summary>
public enum FieldOp {ldfld = 0x7B, ldflda, stfld, ldsfld, ldsflda,
stsfld, ldtoken = 0xD0 }
/// <summary>
/// CIL instructions requiring a method parameter
/// </summary>
public enum MethodOp {jmp = 0x27, call, callvirt = 0x6F, newobj = 0x73,
ldtoken = 0xD0, ldftn = 0xFE06, ldvirtfn }
/// <summary>
/// CIL instructions requiring a type parameter
/// </summary>
public enum TypeOp {cpobj = 0x70, ldobj, castclass = 0x74, isinst,
unbox = 0x79, stobj = 0x81, box = 0x8C, newarr,
ldelema = 0x8F, refanyval = 0xC2, mkrefany = 0xC6,
ldtoken = 0xD0, initobj = 0xFE15, constrained = 0xFE16,
sizeOf = 0xFE1C, ldelem = 0xA3, stelem = 0xA4, unbox_any }
/// <summary>
/// CIL branch instructions
/// </summary>
public enum BranchOp {
// short branches
br_s = 0x2B, brfalse_s, brtrue_s, beq_s, bge_s, bgt_s,
ble_s, blt_s, bne_un_s, bge_un_s, bgt_un_s, ble_un_s, blt_un_s,
// long branches
br = 0x38, brfalse, brtrue, beq, bge, bgt, ble, blt,
bne_un, bge_un, bgt_un, ble_un, blt_un,
leave = 0xDD, leave_s }
/// <summary>
/// Index for all the tables in the meta data
/// </summary>
public enum MDTable { Module, TypeRef, TypeDef, Field = 0x04, Method = 0x06,
Param = 0x08, InterfaceImpl, MemberRef, Constant, CustomAttribute,
FieldMarshal, DeclSecurity, ClassLayout, FieldLayout, StandAloneSig,
EventMap, Event = 0x14, PropertyMap, Property = 0x17, MethodSemantics,
MethodImpl, ModuleRef, TypeSpec, ImplMap, FieldRVA, Assembly = 0x20,
AssemblyProcessor, AssemblyOS, AssemblyRef, AssemblyRefProcessor,
AssemblyRefOS, File, ExportedType, ManifestResource, NestedClass,
GenericParam, MethodSpec, GenericParamConstraint }
public enum SafeArrayType { int16 = 2, int32, float32, float64,
currency, date, bstr, dispatch, error, boolean, variant, unknown,
Decimal, int8 = 16, uint8, uint16, uint32, Int = 22, UInt }
internal enum CIx { TypeDefOrRef, HasConst, HasCustomAttr, HasFieldMarshal,
HasDeclSecurity, MemberRefParent, HasSemantics, MethodDefOrRef,
MemberForwarded, Implementation, CustomAttributeType, ResolutionScope,
TypeOrMethodDef, MaxCIx }
internal enum MapType { eventMap, propertyMap, nestedClass }
public enum ValueClass { ValueType, Enum }
public enum GenParamType : byte {
Var = 0x13, MVar = 0x1E
}
[Flags]
public enum GenericParamAttributes : ushort {
VarianceMask = 0x0003,
NonVariant = 0x0000,
Covariant = 0x0001,
Contravariant = 0x0002,
SpecialConstraintMask = 0x001c,
ReferenceTypeConstraint = 0x0004,
NotNullableValueTypeConstraint = 0x0008,
DefaultConstructorConstrait = 0x0010
}
/* Taken from Mono.Cecil */
public enum SecurityAction : short {
Request = 1,
Demand = 2,
Assert = 3,
Deny = 4,
PermitOnly = 5,
LinkDemand = 6,
InheritDemand = 7,
RequestMinimum = 8,
RequestOptional = 9,
RequestRefuse = 10,
PreJitGrant = 11,
PreJitDeny = 12,
NonCasDemand = 13,
NonCasLinkDemand = 14,
NonCasInheritance = 15,
LinkDemandChoice = 16,
InheritDemandChoice = 17,
DemandChoice = 18
}
#endregion
/**************************************************************************/
/// <summary>
/// Base class for all Meta Data table elements
/// </summary>
public abstract class MetaDataElement: IComparable {
protected ArrayList customAttributes;
private uint row = 0;
protected bool done = false;
protected MDTable tabIx;
protected bool sortTable = false;
//Temporary hack..
private bool has_custom_attrs = false;
internal MetaDataElement() { }
public uint Row {
get {
return row;
}
set {
row = value;
}
}
public bool HasCustomAttr {
get { return has_custom_attrs; }
set { has_custom_attrs = value; }
}
internal virtual uint GetCodedIx(CIx code) { return 0; }
/// <summary>
/// Add a custom attribute to this item
/// </summary>
/// <param name="ctorMeth">the constructor method for this attribute</param>
/// <param name="val">the byte value of the parameters</param>
public void AddCustomAttribute(Method ctorMeth, byte[] val)
{
if (customAttributes == null) {
customAttributes = new ArrayList();
}
customAttributes.Add(new CustomAttribute(this,ctorMeth,val));
}
/// <summary>
/// Add a custom attribute to this item
/// </summary>
/// <param name="ctorMeth">the constructor method for this attribute</param>
/// <param name="val">the constant values of the parameters</param>
public void AddCustomAttribute(Method ctorMeth, Constant[] cVals)
{
if (customAttributes == null) {
customAttributes = new ArrayList();
}
// customAttributes.Add(new CustomAttribute(this,ctorMeth,cVals));
}
internal uint Token()
{
return (((uint)tabIx << 24) | row);
}
internal virtual void BuildTables(MetaData md)
{
done = true;
}
internal virtual uint Size(MetaData md)
{
return 0;
}
internal virtual void Write(FileImage output) { }
internal virtual uint SortKey()
{
throw new PEFileException("Trying to sort table of " + this);
//return 0;
}
internal virtual uint SortKey2()
{
return 0;
}
public int CompareTo(object obj)
{
uint otherKey = ((MetaDataElement)obj).SortKey();
uint thisKey = SortKey();
if (thisKey == otherKey) {
otherKey = ((MetaDataElement)obj).SortKey2();
thisKey = SortKey2();
if (thisKey == otherKey)
return 0;
if (thisKey < otherKey)
return -1;
return 1;
}
if (thisKey < otherKey) return -1;
return 1;
}
}
/**************************************************************************/
/// <summary>
/// Layout information for a class (.class [sequential | explicit])
/// </summary>
internal class ClassLayout : MetaDataElement {
ClassDef parent;
ushort packSize = 0;
uint classSize = 0;
internal ClassLayout(int pack, int cSize, ClassDef par)
{
packSize = (ushort)pack;
classSize = (uint)cSize;
parent = par;
tabIx = MDTable.ClassLayout;
}
internal sealed override uint Size(MetaData md)
{
return 6 + md.TableIndexSize(MDTable.TypeDef);
}
internal sealed override void Write(FileImage output)
{
output.Write(packSize);
output.Write(classSize);
output.WriteIndex(MDTable.TypeDef,parent.Row);
}
}
/**************************************************************************/
/// <summary>
/// Summary description for ConstantElem.
/// </summary>
internal class ConstantElem : MetaDataElement {
MetaDataElement parent;
Constant cValue;
uint valIx = 0;
internal ConstantElem(MetaDataElement parent, Constant val)
{
this.parent = parent;
cValue = val;
tabIx = MDTable.Constant;
sortTable = true;
}
internal override uint SortKey()
{
return (parent.Row << MetaData.CIxShiftMap[(uint)CIx.HasConst])
| parent.GetCodedIx(CIx.HasConst);
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
valIx = cValue.GetBlobIndex(md);
done = true;
}
internal void AddToBlob(BinaryWriter bw)
{
cValue.Write(bw);
}
internal sealed override uint Size(MetaData md)
{
return 2 + md.CodedIndexSize(CIx.HasConst) + md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.Write(cValue.GetTypeIndex());
output.Write((byte)0);
output.WriteCodedIndex(CIx.HasConst,parent);
output.BlobIndex(valIx);
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a Custom Attribute (.custom)
/// </summary>
public class CustomAttribute : MetaDataElement {
MetaDataElement parent;
Method type;
uint valIx;
Constant cVal;
byte[] byteVal;
ushort numNamed = 0;
ArrayList names, vals;
internal CustomAttribute(MetaDataElement paren, Method constrType,
Constant val) {
parent = paren;
type = constrType;
cVal = val;
tabIx = MDTable.CustomAttribute;
byteVal = ConstantToByteArray (val);
}
static byte[] ConstantToByteArray (Constant c)
{
var bac = c as ByteArrConst;
if (bac != null)
return bac.val;
var ms = new MemoryStream ();
// Version info
ms.WriteByte (1);
ms.WriteByte (0);
if (c == null) {
ms.WriteByte (0);
ms.WriteByte (0);
return ms.ToArray ();
}
var sc = c as StringConst;
if (sc != null) {
string value = sc.val;
if (value == null)
throw new NotImplementedException ();
var buf = Encoding.UTF8.GetBytes (value);
MetaData.CompressNum ((uint) buf.Length, ms);
var byteVal = ms.ToArray ();
System.Array.Resize (ref byteVal, (int) ms.Length + buf.Length + 2);
System.Array.Copy (buf, 0, byteVal, ms.Length, buf.Length);
return byteVal;
}
var ac = c as ArrayConstant;
if (ac != null) {
var bw = new BinaryWriter (ms);
if (ac.ExplicitSize != null)
bw.Write (ac.ExplicitSize.Value);
ac.Write (bw);
bw.Write ((short)0);
return ms.ToArray ();
}
var bc = c as DataConstant;
if (bc != null) {
var bw = new BinaryWriter (ms);
bc.Write (bw);
bw.Write ((short)0);
return ms.ToArray ();
}
throw new NotImplementedException (c.GetType ().ToString ());
}
internal CustomAttribute(MetaDataElement paren, Method constrType,
byte[] val) {
parent = paren;
type = constrType;
tabIx = MDTable.CustomAttribute;
byteVal = val;
}
internal override uint SortKey()
{
return (parent.Row << MetaData.CIxShiftMap[(uint)CIx.HasCustomAttr])
| parent.GetCodedIx(CIx.HasCustomAttr);
}
public void AddFieldOrProp(string name, Constant val)
{
if (numNamed == 0) {
names = new ArrayList();
vals = new ArrayList();
}
names.Add(name);
vals.Add(val);
}
internal sealed override void BuildTables(MetaData md)
{
md.AddToTable(MDTable.CustomAttribute, this);
if (byteVal == null) {
valIx = 0;
return;
}
BinaryWriter bw = new BinaryWriter(new MemoryStream());
bw.Write(byteVal);
MemoryStream str = (MemoryStream)bw.BaseStream;
valIx = md.AddToBlobHeap(str.ToArray());
}
internal sealed override uint Size(MetaData md)
{
return md.CodedIndexSize(CIx.HasCustomAttr) + md.CodedIndexSize(CIx.CustomAttributeType) + md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.WriteCodedIndex(CIx.HasCustomAttr,parent);
output.WriteCodedIndex(CIx.CustomAttributeType,type);
output.BlobIndex(valIx);
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for security permissions for a class or a method
/// </summary>
public abstract class BaseDeclSecurity : MetaDataElement {
ushort action;
MetaDataElement parent;
uint permissionIx;
internal BaseDeclSecurity(MetaDataElement paren, ushort act)
{
parent = paren;
action = act;
tabIx = MDTable.DeclSecurity;
}
internal override uint SortKey()
{
return (parent.Row << MetaData.CIxShiftMap[(uint)CIx.HasDeclSecurity])
| parent.GetCodedIx(CIx.HasDeclSecurity);
}
internal sealed override uint Size(MetaData md)
{
return 2 + md.CodedIndexSize(CIx.HasDeclSecurity) + md.BlobIndexSize();
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
BinaryWriter bw = new BinaryWriter (new MemoryStream ());
md.AddToTable (MDTable.DeclSecurity, this);
MemoryStream str = (MemoryStream)bw.BaseStream;
WriteSig (bw);
permissionIx = md.AddToBlobHeap(str.ToArray());
done = true;
}
internal abstract void WriteSig (BinaryWriter bw);
internal sealed override void Write(FileImage output)
{
output.Write(action);
output.WriteCodedIndex(CIx.HasDeclSecurity,parent);
output.BlobIndex(permissionIx);
}
}
public class DeclSecurity : BaseDeclSecurity {
byte [] byteVal;
internal DeclSecurity(MetaDataElement paren, ushort act, byte [] val)
: base (paren, act)
{
byteVal = val;
}
internal override void WriteSig (BinaryWriter bw)
{
bw.Write (byteVal);
}
}
public class DeclSecurity_20 : BaseDeclSecurity {
PermissionSet ps;
internal DeclSecurity_20 (MetaDataElement paren, ushort act, PermissionSet ps)
: base (paren, act)
{
this.ps = ps;
}
internal override void WriteSig (BinaryWriter bw)
{
ps.Write (bw);
}
}
public class PermissionMember {
MemberTypes member_type;
PEAPI.Type type;
string name;
object value;
public PermissionMember (MemberTypes member_type, PEAPI.Type type, string name, object value)
{
this.member_type = member_type;
this.type = type;
this.name = name;
this.value = value;
}
public void Write (BinaryWriter bw)
{
byte [] b;
if (member_type == MemberTypes.Field)
bw.Write ((byte) 0x53);
else
//Property
bw.Write ((byte) 0x54);
if (type is PrimitiveType) {
bw.Write (type.GetTypeIndex ());
} else {
//must be enum
bw.Write ((byte) 0x55); //ENUM
b = Encoding.UTF8.GetBytes (((ClassRef) type).TypeName ());
MetaData.CompressNum ((uint) b.Length, (MemoryStream) bw.BaseStream);
bw.Write (b);
}
b = Encoding.UTF8.GetBytes (name);
MetaData.CompressNum ((uint) b.Length, (MemoryStream) bw.BaseStream);
bw.Write (b);
((Constant) value).Write (bw);
}
}
public class Permission
{
PEAPI.Type type;
//PermissionMembers
ArrayList members;
string name;
public Permission (PEAPI.Type type, string name)
{
this.type = type;
this.name = name;
}
public void AddMember (PEAPI.PermissionMember member)
{
if (members == null)
members = new ArrayList ();
members.Add (member);
}
public void Write (BinaryWriter bw)
{
byte [] b = Encoding.UTF8.GetBytes (name);
MetaData.CompressNum ((uint) b.Length, (MemoryStream) bw.BaseStream);
bw.Write (b);
BinaryWriter perm_writer = new BinaryWriter (new MemoryStream (), Encoding.Unicode);
MemoryStream str = (MemoryStream) perm_writer.BaseStream;
MetaData.CompressNum ((uint) members.Count, str);//number of params
foreach (PermissionMember member in members)
member.Write (perm_writer);
bw.Write ((byte) str.Length); //(optional) parameters length
bw.Write (str.ToArray ());
}
}
public class PermissionSet
{
PEAPI.SecurityAction sec_action;
ArrayList permissions;
public PermissionSet (PEAPI.SecurityAction sec_action)
{
this.sec_action = sec_action;
}
public void AddPermission (PEAPI.Permission perm)
{
if (permissions == null)
permissions = new ArrayList ();
permissions.Add (perm);
}
public void Write (BinaryWriter bw)
{
bw.Write ((byte) 0x2e);
MetaData.CompressNum ((uint) permissions.Count, (MemoryStream) bw.BaseStream);
foreach (Permission perm in permissions)
perm.Write (bw);
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for layout information for a field
/// </summary>
public class FieldLayout : MetaDataElement {
Field field;
uint offset;
internal FieldLayout(Field field, uint offset)
{
this.field = field;
this.offset = offset;
tabIx = MDTable.FieldLayout;
}
internal sealed override uint Size(MetaData md)
{
return 4 + md.TableIndexSize(MDTable.Field);
}
internal sealed override void Write(FileImage output)
{
output.Write(offset);
output.WriteIndex(MDTable.Field,field.Row);
}
}
/*****************************************************************************/
/// <summary>
/// Marshalling information for a field or param
/// </summary>
public class FieldMarshal : MetaDataElement {
MetaDataElement field;
NativeType nt;
uint ntIx;
internal FieldMarshal(MetaDataElement field, NativeType nType)
{
this.field = field;
this.nt = nType;
tabIx = MDTable.FieldMarshal;
}
internal override uint SortKey()
{
return (field.Row << MetaData.CIxShiftMap[(uint)CIx.HasFieldMarshal])
| field.GetCodedIx(CIx.HasFieldMarshal);
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
ntIx = md.AddToBlobHeap(nt.ToBlob());
done = true;
}
internal sealed override uint Size(MetaData md)
{
return md.CodedIndexSize(CIx.HasFieldMarshal) + md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.WriteCodedIndex(CIx.HasFieldMarshal,field);
output.BlobIndex(ntIx);
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for the address of a field's value in the PE file
/// </summary>
public class FieldRVA : MetaDataElement {
Field field;
DataConstant data;
internal FieldRVA(Field field, DataConstant data)
{
this.field = field;
this.data = data;
tabIx = MDTable.FieldRVA;
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
md.AddData(data);
done = true;
}
internal sealed override uint Size(MetaData md)
{
return 4 + md.TableIndexSize(MDTable.Field);
}
internal sealed override void Write(FileImage output)
{
output.WriteDataRVA(data.DataOffset);
output.WriteIndex(MDTable.Field,field.Row);
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a file referenced in THIS assembly/module (.file)
/// </summary>
public class FileRef : MetaDataElement {
private static readonly uint NoMetaData = 0x1;
uint nameIx = 0, hashIx = 0;
uint flags = 0;
protected string name;
internal FileRef(string name, byte[] hashBytes, bool metaData,
bool entryPoint, MetaData md) {
if (!metaData) flags = NoMetaData;
if (entryPoint) md.SetEntryPoint(this);
this.name = name;
nameIx = md.AddToStringsHeap(name);
hashIx = md.AddToBlobHeap(hashBytes);
tabIx = MDTable.File;
}
internal FileRef(uint nameIx, byte[] hashBytes, bool metaData,
bool entryPoint, MetaData md) {
if (!metaData) flags = NoMetaData;
if (entryPoint) md.SetEntryPoint(this);
this.nameIx = nameIx;
hashIx = md.AddToBlobHeap(hashBytes);
tabIx = MDTable.File;
}
internal sealed override uint Size(MetaData md)
{
return 4 + md.StringsIndexSize() + md.BlobIndexSize();
}
internal sealed override void BuildTables(MetaData md)
{
md.AddToTable(MDTable.File,this);
}
internal sealed override void Write(FileImage output)
{
output.Write(flags);
output.StringsIndex(nameIx);
output.BlobIndex(hashIx);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 16;
case (CIx.Implementation) : return 0;
}
return 0;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for pinvoke information for a method NOT YET IMPLEMENTED
/// </summary>
public class ImplMap : MetaDataElement {
private static readonly ushort NoMangle = 0x01;
ushort flags;
Method meth;
string importName;
uint iNameIx;
ModuleRef importScope;
internal ImplMap(ushort flag, Method implMeth, string iName, ModuleRef mScope)
{
flags = flag;
meth = implMeth;
importName = iName;
importScope = mScope;
tabIx = MDTable.ImplMap;
if (iName == null) flags |= NoMangle;
//throw(new NotYetImplementedException("PInvoke "));
}
internal override uint SortKey()
{
return (meth.Row << MetaData.CIxShiftMap[(uint)CIx.MemberForwarded])
| meth.GetCodedIx(CIx.MemberForwarded);
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
iNameIx = md.AddToStringsHeap(importName);
done = true;
}
internal sealed override uint Size(MetaData md)
{
return 2+ md.CodedIndexSize(CIx.MemberForwarded) +
md.StringsIndexSize() + md.TableIndexSize(MDTable.ModuleRef);
}
internal sealed override void Write(FileImage output)
{
output.Write(flags);
output.WriteCodedIndex(CIx.MemberForwarded,meth);
output.StringsIndex(iNameIx);
output.WriteIndex(MDTable.ModuleRef,importScope.Row);
}
}
/**************************************************************************/
public class GenericParameter : MetaDataElement {
MetaDataElement owner;
MetaData metadata;
public string name;
uint nameIx;
short index;
GenericParamAttributes attr;
internal GenericParameter (ClassDef owner, MetaData metadata,
short index, string name, GenericParamAttributes attr) : this (owner, metadata, index, name, attr, true)
{
}
internal GenericParameter (MethodDef owner, MetaData metadata,
short index, string name, GenericParamAttributes attr) : this (owner, metadata, index, name, attr, true)
{
}
private GenericParameter (MetaDataElement owner, MetaData metadata,
short index, string name, GenericParamAttributes attr, bool nadda) {
this.owner = owner;
this.metadata = metadata;
this.index = index;
tabIx = MDTable.GenericParam;
this.name = name;
this.attr = attr;
}
internal override uint SortKey()
{
return (owner.Row << MetaData.CIxShiftMap[(uint)CIx.TypeOrMethodDef])
| owner.GetCodedIx(CIx.TypeOrMethodDef);
}
internal override uint SortKey2 ()
{
return (uint) index;
}
public void AddConstraint (Type constraint)
{
metadata.AddToTable (MDTable.GenericParamConstraint,
new GenericParamConstraint (this, constraint));
}
internal sealed override uint Size(MetaData md)
{
return (uint) (4 +
md.CodedIndexSize(CIx.TypeOrMethodDef) +
md.StringsIndexSize ());
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
nameIx = md.AddToStringsHeap(name);
done = true;
}
internal sealed override void Write(FileImage output)
{
output.Write ((short) index);
output.Write ((short) attr);
output.WriteCodedIndex(CIx.TypeOrMethodDef, owner);
output.StringsIndex (nameIx);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 19;
}
return 0;
}
}
internal class GenericParamConstraint : MetaDataElement {
GenericParameter param;
Type type;
public GenericParamConstraint (GenericParameter param, Type type)
{
this.param = param;
this.type = type;
tabIx = MDTable.GenericParamConstraint;
}
internal override uint SortKey()
{
return param.Row;
}
internal sealed override uint Size(MetaData md)
{
return (uint) (md.TableIndexSize(MDTable.GenericParam) +
md.CodedIndexSize(CIx.TypeDefOrRef));
}
internal sealed override void Write(FileImage output)
{
output.WriteIndex(MDTable.GenericParam, param.Row);
output.WriteCodedIndex(CIx.TypeDefOrRef, type);
}
}
internal class MethodSpec : Method {
Method meth;
GenericMethodSig g_sig;
uint sidx;
internal MethodSpec (Method meth, GenericMethodSig g_sig) : base ("")
{
this.meth = meth;
this.g_sig = g_sig;
tabIx = MDTable.MethodSpec;
}
internal override uint GetSigIx (MetaData md)
{
throw new Exception ("Should not be used.");
}
public override void AddCallConv (CallConv cconv)
{
throw new Exception ("Should not be used.");
}
internal sealed override void BuildTables (MetaData md)
{
if (done) return;
sidx = g_sig.GetSigIx (md);
done = true;
}
internal sealed override uint Size (MetaData md)
{
return (uint) (md.CodedIndexSize(CIx.MethodDefOrRef) +
md.BlobIndexSize ());
}
internal sealed override void Write (FileImage output)
{
output.WriteCodedIndex (CIx.MethodDefOrRef, meth);
output.BlobIndex (sidx);
}
internal sealed override void TypeSig (MemoryStream sig)
{
throw new Exception ("Should not be used.");
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for interface implemented by a class
/// </summary>
public class InterfaceImpl: MetaDataElement {
ClassDef theClass;
Class theInterface;
internal InterfaceImpl(ClassDef theClass, Class theInterface)
{
this.theClass = theClass;
this.theInterface = theInterface;
tabIx = MDTable.InterfaceImpl;
}
internal sealed override uint Size(MetaData md)
{
return md.TableIndexSize(MDTable.TypeDef) +
md.CodedIndexSize(CIx.TypeDefOrRef);
}
internal sealed override void Write(FileImage output)
{
output.WriteIndex(MDTable.TypeDef,theClass.Row);
output.WriteCodedIndex(CIx.TypeDefOrRef,theInterface);
}
internal sealed override uint GetCodedIx(CIx code) { return 5; }
internal override uint SortKey ()
{
throw new Exception ("Should not be used.");
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for resources used in this PE file
/// </summary>
public class ManifestResource : MetaDataElement {
public static readonly uint PublicResource = 0x1;
public static readonly uint PrivateResource = 0x2;
string mrName;
MetaDataElement rRef;
uint fileOffset;
uint nameIx = 0;
uint flags = 0;
byte [] resourceBytes;
public ManifestResource (string name, byte[] resBytes, uint flags)
{
InitResource (name, flags);
this.resourceBytes = resBytes;
}
public ManifestResource(string name, uint flags, FileRef fileRef)
{
InitResource (name, flags);
rRef = fileRef;
}
public ManifestResource(string name, uint flags, FileRef fileRef,
uint fileIx) {
InitResource (name, flags);
rRef = fileRef;
fileOffset = fileIx;
}
public ManifestResource(string name, uint flags, AssemblyRef assemRef)
{
InitResource (name, flags);
rRef = assemRef;
}
internal ManifestResource (ManifestResource mres)
{
mrName = mres.mrName;
flags = mres.flags;
rRef = mres.rRef;
fileOffset = mres.fileOffset;
resourceBytes = mres.resourceBytes;
}
private void InitResource (string name, uint flags)
{
mrName = name;
this.flags = flags;
tabIx = MDTable.ManifestResource;
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
md.AddToTable (MDTable.ManifestResource, this);
nameIx = md.AddToStringsHeap(mrName);
if (resourceBytes != null) {
if (rRef != null)
throw new PEFileException ("Manifest Resource has byte value and file reference");
fileOffset = md.AddResource(resourceBytes);
} else {
if (rRef == null)
throw new PEFileException ("Manifest Resource has no implementation or value");
rRef.BuildTables (md);
}
done = true;
}
internal sealed override uint Size(MetaData md)
{
return 8 + md.StringsIndexSize() +
md.CodedIndexSize(CIx.Implementation);
}
internal sealed override void Write(FileImage output)
{
output.Write(fileOffset);
output.Write(flags);
output.StringsIndex(nameIx);
output.WriteCodedIndex(CIx.Implementation,rRef);
}
internal sealed override uint GetCodedIx(CIx code) { return 18; }
public string Name {
get { return mrName; }
set { mrName = value; }
}
}
/**************************************************************************/
/// <summary>
/// Base class for elements in the PropertyMap, EventMap and
/// NestedClass MetaData tables
/// </summary>
public class MapElem : MetaDataElement {
ClassDef parent;
uint elemIx;
MDTable elemTable;
internal MapElem(ClassDef par, uint elIx, MDTable elemTab)
{
parent = par;
elemIx = elIx;
elemTable = elemTab;
}
internal sealed override uint Size(MetaData md)
{
return md.TableIndexSize(MDTable.TypeDef) + md.TableIndexSize(elemTable);
}
internal sealed override void Write(FileImage output)
{
output.WriteIndex(MDTable.TypeDef,parent.Row);
output.WriteIndex(elemTable,elemIx);
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for an overriding method (.override)
/// </summary>
public class MethodImpl : MetaDataElement {
ClassDef parent;
Method header, body;
internal MethodImpl(ClassDef par, Method decl, Method bod)
{
parent = par;
header = decl;
body = bod;
tabIx = MDTable.MethodImpl;
}
internal sealed override uint Size(MetaData md)
{
return md.TableIndexSize(MDTable.TypeDef) + 2 * md.CodedIndexSize(CIx.MethodDefOrRef);
}
internal sealed override void Write(FileImage output)
{
output.WriteIndex(MDTable.TypeDef,parent.Row);
output.WriteCodedIndex(CIx.MethodDefOrRef,body);
output.WriteCodedIndex(CIx.MethodDefOrRef,header);
}
internal override uint SortKey()
{
return parent.Row;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for Property and Event methods
/// </summary>
public class MethodSemantics : MetaDataElement {
Feature.MethodType type;
MethodDef meth;
Feature eventOrProp;
internal MethodSemantics(Feature.MethodType mType, MethodDef method, Feature feature)
{
type = mType;
meth = method;
eventOrProp = feature;
tabIx = MDTable.MethodSemantics;
}
internal override uint SortKey()
{
return (eventOrProp.Row << MetaData.CIxShiftMap [(uint)CIx.HasSemantics])
| eventOrProp.GetCodedIx (CIx.HasSemantics);
}
internal sealed override uint Size(MetaData md)
{
return 2 + md.TableIndexSize(MDTable.Method) + md.CodedIndexSize(CIx.HasSemantics);
}
internal sealed override void Write(FileImage output)
{
output.Write((ushort)type);
output.WriteIndex(MDTable.Method,meth.Row);
output.WriteCodedIndex(CIx.HasSemantics,eventOrProp);
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a parameter of a method defined in this assembly/module
/// </summary>
public class Param : MetaDataElement {
Type pType;
string pName;
internal ushort seqNo = 0;
ushort parMode;
ConstantElem defaultVal;
uint nameIx = 0;
FieldMarshal marshalInfo;
/// <summary>
/// Create a new parameter for a method
/// </summary>
/// <param name="mode">param mode (in, out, opt)</param>
/// <param name="parName">parameter name</param>
/// <param name="parType">parameter type</param>
public Param(ParamAttr mode, string parName, Type parType)
{
pName = parName;
pType = parType;
parMode = (ushort)mode;
tabIx = MDTable.Param;
}
public bool HasMarshalInfo {
get { return marshalInfo != null; }
}
/// <summary>
/// Add a default value to this parameter
/// </summary>
/// <param name="c">the default value for the parameter</param>
public void AddDefaultValue(Constant cVal)
{
defaultVal = new ConstantElem(this,cVal);
parMode |= (ushort) ParamAttr.HasDefault;
}
/// <summary>
/// Add marshalling information about this parameter
/// </summary>
public void AddMarshallInfo(NativeType marshallType)
{
parMode |= (ushort) ParamAttr.HasFieldMarshal;
marshalInfo = new FieldMarshal(this,marshallType);
}
internal Type GetParType() { return pType; }
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
nameIx = md.AddToStringsHeap(pName);
if (defaultVal != null) {
md.AddToTable(MDTable.Constant,defaultVal);
defaultVal.BuildTables(md);
}
if (marshalInfo != null) {
md.AddToTable(MDTable.FieldMarshal,marshalInfo);
marshalInfo.BuildTables(md);
}
done = true;
}
internal void TypeSig(MemoryStream str)
{
pType.TypeSig(str);
}
internal sealed override uint Size(MetaData md)
{
return 4 + md.StringsIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.Write(parMode);
output.Write(seqNo);
output.StringsIndex(nameIx);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 4;
case (CIx.HasConst) : return 1;
case (CIx.HasFieldMarshal) : return 1;
}
return 0;
}
}
/**************************************************************************/
public abstract class Signature : MetaDataElement {
protected uint sigIx;
internal Signature()
{
tabIx = MDTable.StandAloneSig;
}
internal sealed override uint Size(MetaData md)
{
return md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.BlobIndex(sigIx);
}
internal sealed override uint GetCodedIx(CIx code) { return (uint)tabIx; }
}
/**************************************************************************/
public class TypeSpec : MetaDataElement {
uint sigIx = 0;
internal TypeSpec(Type aType, MetaData md)
{
MemoryStream sig = new MemoryStream();
aType.TypeSig(sig);
sigIx = md.AddToBlobHeap(sig.ToArray());
tabIx = MDTable.TypeSpec;
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.TypeDefOrRef) : return 2;
case (CIx.HasCustomAttr) : return 13;
case (CIx.MemberRefParent) : return 4;
}
return 0;
}
internal override uint Size(MetaData md)
{
return md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
//Console.WriteLine("Writing the blob index for a TypeSpec");
output.BlobIndex(sigIx);
}
}
/**************************************************************************/
/// <summary>
/// Base class for all IL types
/// </summary>
public abstract class Type : MetaDataElement {
protected byte typeIndex;
protected TypeSpec typeSpec;
internal Type(byte tyIx) { typeIndex = tyIx; }
internal byte GetTypeIndex() { return typeIndex; }
internal void SetTypeIndex (byte b) { typeIndex = b; }
internal virtual MetaDataElement GetTypeSpec(MetaData md)
{
if (typeSpec == null) {
typeSpec = new TypeSpec(this,md);
md.AddToTable(MDTable.TypeSpec,typeSpec);
}
return typeSpec;
}
internal virtual void TypeSig(MemoryStream str)
{
throw(new TypeSignatureException(this.GetType().AssemblyQualifiedName +
" doesn't have a type signature!!"));
}
}
public class ClassRefInst : Type {
private Type type;
private bool is_value;
public ClassRefInst (Type type, bool is_value) : base (PrimitiveType.Class.GetTypeIndex ())
{
this.type = type;
this.is_value = is_value;
if (is_value)
typeIndex = PrimitiveType.ValueType.GetTypeIndex ();
tabIx = MDTable.TypeSpec;
}
internal sealed override void TypeSig(MemoryStream str)
{
type.TypeSig (str);
}
}
/**************************************************************************/
/// <summary>
/// The base descriptor for a class
/// </summary>
public abstract class Class : Type {
protected int row = 0;
public string name, nameSpace;
protected uint nameIx, nameSpaceIx;
protected MetaData _metaData;
internal Class(string nameSpaceName, string className, MetaData md)
: base(PrimitiveType.Class.GetTypeIndex ())
{
nameSpace = nameSpaceName;
name = className;
nameIx = md.AddToStringsHeap(name);
nameSpaceIx = md.AddToStringsHeap(nameSpace);
_metaData = md;
}
internal Class(uint nsIx, uint nIx) : base(PrimitiveType.Class.GetTypeIndex ())
{
nameSpaceIx = nsIx;
nameIx = nIx;
}
internal Class (byte typeIndex) : base (typeIndex)
{
nameSpace = "Should not be used";
name = "Should not be used";
}
internal virtual uint TypeDefOrRefToken() { return 0; }
internal virtual void MakeValueClass(ValueClass vClass)
{
typeIndex = PrimitiveType.ValueType.GetTypeIndex ();
}
internal virtual string TypeName()
{
return (nameSpace + "." + name);
}
internal override MetaDataElement GetTypeSpec(MetaData md)
{
return this;
}
}
/**************************************************************************/
// This Class produces entries in the TypeDef table of the MetaData
// in the PE meta data.
// NOTE: Entry 0 in TypeDef table is always the pseudo class <module>
// which is the parent for functions and variables declared a module level
/// <summary>
/// The descriptor for a class defined in the IL (.class) in the current assembly/module
/// </summary>
///
public class ClassDef : Class {
Class superType;
bool setSuperType;
ArrayList fields = new ArrayList();
ArrayList methods = new ArrayList();
ArrayList events;
ArrayList properties;
bool typeIndexChecked = true;
uint fieldIx = 0, methodIx = 0;
uint flags;
ClassLayout layout;
ClassDef parentClass;
MetaData metaData;
internal ClassDef(TypeAttr attrSet, string nsName, string name,
MetaData md) : base(nsName, name, md)
{
metaData = md;
flags = (uint)attrSet;
tabIx = MDTable.TypeDef;
}
internal void SetSuper(Class sClass)
{
superType = sClass;
setSuperType = true;
if (! (sClass is GenericTypeInst))
typeIndexChecked = false;
}
internal override void MakeValueClass(ValueClass vClass)
{
if (vClass == ValueClass.Enum)
superType = metaData.mscorlib.EnumType();
else
superType = metaData.mscorlib.ValueType();
setSuperType = true;
typeIndex = PrimitiveType.ValueType.GetTypeIndex ();
}
public void SpecialNoSuper()
{
setSuperType = true;
}
/// <summary>
/// Add an attribute to this class
/// </summary>
/// <param name="ta">the attribute to be added</param>
public void AddAttribute(TypeAttr ta)
{
flags |= (uint)ta;
}
/// <summary>
/// Add an interface that is implemented by this class
/// </summary>
/// <param name="iFace">the interface that is implemented</param>
public void AddImplementedInterface(Class iFace)
{
metaData.AddToTable(MDTable.InterfaceImpl,new InterfaceImpl(this,iFace));
}
/// <summary>
/// Add a named generic type parameter
/// </summary>
public GenericParameter AddGenericParameter (short index, string name)
{
return AddGenericParameter (index, name, 0);
}
/// <summary>
/// Add a named generic type parameter with attributes
/// </summary>
public GenericParameter AddGenericParameter (short index, string name, GenericParamAttributes attr)
{
GenericParameter gp = new GenericParameter (this, metaData, index, name, attr);
metaData.AddToTable (MDTable.GenericParam, gp);
return gp;
}
/// <summary>
/// Add a field to this class
/// </summary>
/// <param name="name">field name</param>
/// <param name="fType">field type</param>
/// <returns>a descriptor for this new field</returns>
public FieldDef AddField(string name, Type fType)
{
FieldDef field = new FieldDef(name,fType);
fields.Add(field);
return field;
}
/// <summary>
/// Add a field to this class
/// </summary>
/// <param name="fAtts">attributes for this field</param>
/// <param name="name">field name</param>
/// <param name="fType">field type</param>
/// <returns>a descriptor for this new field</returns>
public FieldDef AddField(FieldAttr fAtts, string name, Type fType)
{
FieldDef field = new FieldDef(fAtts,name,fType);
fields.Add(field);
return field;
}
public void SetFieldOrder (ArrayList fields)
{
this.fields = fields;
}
/// <summary>
/// Add a method to this class
/// </summary>
/// <param name="name">method name</param>
/// <param name="retType">return type</param>
/// <param name="pars">parameters</param>
/// <returns>a descriptor for this new method</returns>
public MethodDef AddMethod(string name, Type retType, Param[] pars)
{
return AddMethod (name, new Param (ParamAttr.Default, "", retType), pars);
}
public MethodDef AddMethod (string name, Param ret_param, Param [] pars)
{
// Console.WriteLine("Adding method " + name + " to class " + this.name);
MethodDef meth = new MethodDef(metaData,name, ret_param, pars);
methods.Add(meth);
return meth;
}
/// <summary>
/// Add a method to this class
/// </summary>
/// <param name="mAtts">attributes for this method</param>
/// <param name="iAtts">implementation attributes for this method</param>
/// <param name="name">method name</param>
/// <param name="retType">return type</param>
/// <param name="pars">parameters</param>
/// <returns>a descriptor for this new method</returns>
public MethodDef AddMethod(MethAttr mAtts, ImplAttr iAtts, string name,
Param ret_param, Param [] pars) {
// Console.WriteLine("Adding method " + name + " to class " + this.name);
MethodDef meth = new MethodDef (metaData, mAtts, iAtts, name, ret_param, pars);
methods.Add(meth);
return meth;
}
/// <summary>
/// Add an event to this class
/// </summary>
/// <param name="name">event name</param>
/// <param name="eType">event type</param>
/// <returns>a descriptor for this new event</returns>
public Event AddEvent(string name, Type eType)
{
Event e = new Event(name,eType,this);
if (events == null) events = new ArrayList();
events.Add(e);
return e;
}
/// <summary>
/// Add a property to this class
/// </summary>
/// <param name="name">property name</param>
/// <param name="propType">property type</param>
/// <returns>a descriptor for this new property</returns>
public Property AddProperty(string name, Type retType, Type[] pars)
{
Property p = new Property(name, retType, pars, this);
if (properties == null) properties = new ArrayList();
properties.Add(p);
return p;
}
/// <summary>
/// Add a nested class to this class
/// </summary>
/// <param name="attrSet">attributes for this nested class</param>
/// <param name="nsName">nested name space name</param>
/// <param name="name">nested class name</param>
/// <returns>a descriptor for this new nested class</returns>
public ClassDef AddNestedClass(TypeAttr attrSet, string nsName,
string name) {
ClassDef nClass = new ClassDef(attrSet,"",name,metaData);
metaData.AddToTable(MDTable.TypeDef,nClass);
metaData.AddToTable(MDTable.NestedClass,new MapElem(nClass,Row,MDTable.TypeDef));
nClass.parentClass = this;
return (nClass);
}
public static bool IsValueType (Class type)
{
return IsValueType (type.nameSpace, type.name);
}
public static bool IsEnum (Class type)
{
return IsEnum (type.nameSpace, type.name);
}
public static bool IsValueType (string nsName, string name)
{
return (nsName == "System" && name == "ValueType");
}
public static bool IsEnum (string nsName, string name)
{
return (nsName == "System" && name == "Enum");
}
/// <summary>
/// Add a nested class to this class
/// </summary>
/// <param name="attrSet">attributes for this nested class</param>
/// <param name="nsName">nested name space name</param>
/// <param name="name">nested class name</param>
/// <param name="sType">super type of this nested class</param>
/// <returns>a descriptor for this new nested class</returns>
public ClassDef AddNestedClass(TypeAttr attrSet, string nsName,
string name, Class sType) {
ClassDef nClass = AddNestedClass (attrSet, nsName, name);
nClass.SetSuper(sType);
if (ClassDef.IsValueType (sType))
nClass.MakeValueClass (ValueClass.ValueType);
else
if (ClassDef.IsEnum (sType))
nClass.MakeValueClass (ValueClass.Enum);
if (ClassDef.IsValueType (sType) || ClassDef.IsEnum (sType))
nClass.SetTypeIndex (PrimitiveType.ValueType.GetTypeIndex ());
nClass.typeIndexChecked = true;
return (nClass);
}
/// <summary>
/// Add layout information for this class. This class must have the
/// sequential or explicit attribute.
/// </summary>
/// <param name="packSize">packing size (.pack)</param>
/// <param name="classSize">class size (.size)</param>
public void AddLayoutInfo (int packSize, int classSize)
{
layout = new ClassLayout(packSize,classSize,this);
}
/// <summary>
/// Use a method as the implementation for another method (.override)
/// </summary>
/// <param name="decl">the method to be overridden</param>
/// <param name="body">the implementation to be used</param>
public void AddMethodOverride(Method decl, Method body)
{
metaData.AddToTable(MDTable.MethodImpl,new MethodImpl(this,decl,body));
}
/// <summary>
/// Add security to this class NOT YET IMPLEMENTED
/// </summary>
/// <param name="permissionSet"></param>
public void AddSecurity(byte[] permissionSet)
{
throw(new NotYetImplementedException("Class security "));
//flags |= HasSecurity;
// securityActions = permissionSet;
}
//public void AddLineInfo(int row, int col) { }
internal void CheckTypeIndex()
{
if (typeIndexChecked) return;
if (superType is ClassDef)
((ClassDef)superType).CheckTypeIndex();
typeIndex = superType.GetTypeIndex();
typeIndexChecked = true;
}
internal sealed override void BuildTables(MetaData md)
{
if (done)
return;
if ((flags & (uint)TypeAttr.Interface) != 0) {
superType = null;
setSuperType = true;
}
// Console.WriteLine("Building tables for " + name);
if (layout != null) md.AddToTable(MDTable.ClassLayout,layout);
// Console.WriteLine("adding methods " + methods.Count);
methodIx = md.TableIndex(MDTable.Method);
for (int i=0; i < methods.Count; i++) {
md.AddToTable(MDTable.Method,(MetaDataElement)methods[i]);
((MethodDef)methods[i]).BuildTables(md);
}
// Console.WriteLine("adding fields");
fieldIx = md.TableIndex(MDTable.Field);
for (int i=0; i < fields.Count; i++) {
md.AddToTable(MDTable.Field,(MetaDataElement)fields[i]);
((FieldDef)fields[i]).BuildTables(md);
}
// Console.WriteLine("adding events and properties");
if (events != null) {
for (int i=0; i < events.Count; i++) {
md.AddToTable(MDTable.Event,(Event)events[i]);
((Event)events[i]).BuildTables(md);
}
md.AddToTable(MDTable.EventMap,
new MapElem(this,((Event)events[0]).Row,MDTable.Event));
}
if (properties != null) {
for (int i=0; i < properties.Count; i++) {
md.AddToTable(MDTable.Property,(Property)properties[i]);
((Property)properties[i]).BuildTables(md);
}
md.AddToTable(MDTable.PropertyMap,new MapElem(this,
((Property)properties[0]).Row,MDTable.Property));
}
// Console.WriteLine("End of building tables");
if (!setSuperType)
superType = metaData.mscorlib.GetSpecialSystemClass(PrimitiveType.Object);
done = true;
}
internal sealed override uint Size(MetaData md)
{
return 4 + 2 * md.StringsIndexSize() +
md.CodedIndexSize(CIx.TypeDefOrRef) +
md.TableIndexSize(MDTable.Field) +
md.TableIndexSize(MDTable.Method);
}
internal sealed override void Write(FileImage output)
{
output.Write(flags);
output.StringsIndex(nameIx);
output.StringsIndex(nameSpaceIx);
//if (superType != null)
// Console.WriteLine("getting coded index for superType of " + name + " = " + superType.GetCodedIx(CIx.TypeDefOrRef));
output.WriteCodedIndex(CIx.TypeDefOrRef,superType);
output.WriteIndex(MDTable.Field,fieldIx);
output.WriteIndex(MDTable.Method,methodIx);
}
internal sealed override uint TypeDefOrRefToken()
{
uint cIx = Row;
cIx = cIx << 2;
return cIx;
}
internal sealed override void TypeSig(MemoryStream sig)
{
if (!typeIndexChecked) CheckTypeIndex();
sig.WriteByte(GetTypeIndex());
MetaData.CompressNum(TypeDefOrRefToken(),sig);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.TypeDefOrRef) : return 0;
case (CIx.HasCustomAttr) : return 3;
case (CIx.HasDeclSecurity) : return 0;
case (CIx.TypeOrMethodDef) : return 0;
}
return 0;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a class/interface declared in another module of THIS
/// assembly, or in another assembly.
/// </summary>
public class ClassRef : Class, IExternRef, IResolutionScope {
protected IResolutionScope parent;
protected MetaData metaData;
internal ClassRef(string nsName, string name, MetaData md) : base(nsName, name, md)
{
metaData = md;
tabIx = MDTable.TypeRef;
}
/// <summary>
/// Add a method to this class
/// </summary>
/// <param name="name">method name</param>
/// <param name="retType">return type</param>
/// <param name="pars">parameter types</param>
/// <returns>a descriptor for this method</returns>
public MethodRef AddMethod(string name, Type retType, Type[] pars)
{
return AddMethod (name, retType, pars, 0);
}
/// <summary>
/// Add a method to this class
/// </summary>
/// <param name="name">method name</param>
/// <param name="retType">return type</param>
/// <param name="pars">parameter types</param>
/// <param name="gen_param_count">num of generic parameters</param>
/// <returns>a descriptor for this method</returns>
public MethodRef AddMethod (string name, Type retType, Type[] pars, int gen_param_count)
{
MethodRef meth = new MethodRef (this, name, retType, pars, false, null, gen_param_count);
metaData.AddToTable(MDTable.MemberRef,meth);
return meth;
}
/// <summary>
/// Add a method to this class
/// </summary>
/// <param name="name">method name</param>
/// <param name="retType">return type</param>
/// <param name="pars">parameter types</param>
/// <returns>a descriptor for this method</returns>
public MethodRef AddVarArgMethod(string name, Type retType,
Type[] pars, Type[] optPars)
{
MethodRef meth = new MethodRef(this,name,retType,pars,true,optPars, 0);
metaData.AddToTable(MDTable.MemberRef,meth);
return meth;
}
/// <summary>
/// Add a field to this class
/// </summary>
/// <param name="name">field name</param>
/// <param name="fType">field type</param>
/// <returns>a descriptor for this field</returns>
public FieldRef AddField(string name, Type fType)
{
FieldRef field = new FieldRef(this,name,fType);
metaData.AddToTable(MDTable.MemberRef,field);
return field;
}
public ClassRef AddClass (string nsName, string name)
{
ClassRef aClass = new ClassRef(nsName,name,metaData);
metaData.AddToTable(MDTable.TypeRef,aClass);
aClass.SetParent(this);
return aClass;
}
public ClassRef AddValueClass (string nsName, string name)
{
ClassRef aClass = AddClass (nsName, name);
aClass.MakeValueClass (ValueClass.ValueType);
return aClass;
}
internal void SetParent(IResolutionScope par)
{
parent = par;
}
internal override string TypeName()
{
if ((parent != null) && (parent is AssemblyRef))
return (nameSpace + "." + name + ", " + ((AssemblyRef)parent).TypeName());
else
return (nameSpace + name);
}
internal sealed override uint Size(MetaData md)
{
return md.CodedIndexSize(CIx.ResolutionScope) + 2 *
md.StringsIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.WriteCodedIndex(CIx.ResolutionScope,(MetaDataElement) parent);
output.StringsIndex(nameIx);
output.StringsIndex(nameSpaceIx);
}
internal override sealed uint TypeDefOrRefToken()
{
uint cIx = Row;
cIx = (cIx << 2) | 0x1;
return cIx;
}
internal override void TypeSig(MemoryStream sig)
{
sig.WriteByte(GetTypeIndex());
MetaData.CompressNum(TypeDefOrRefToken(),sig);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.TypeDefOrRef) : return 1;
case (CIx.HasCustomAttr) : return 2;
case (CIx.MemberRefParent) : return 1;
case (CIx.ResolutionScope) : return 3;
}
return 0;
}
}
/**************************************************************************/
public class ExternClassRef : ClassRef {
ExternClass externClass;
internal ExternClassRef(TypeAttr attrs, string nsName, string name,
MetaDataElement declRef, MetaData md) : base(nsName,name,md)
{
externClass = new ExternClass(attrs,nameSpaceIx,nameIx,declRef);
metaData.AddToTable(MDTable.ExportedType,externClass);
}
internal ExternClassRef(string name, MetaData md) : base(null,name,md)
{
}
public ClassRef AddNestedClass(TypeAttr attrs, string name)
{
ExternClassRef nestedClass = new ExternClassRef(name,metaData);
externClass = new ExternClass(attrs,0,nameIx,this.externClass);
metaData.AddToTable(MDTable.ExportedType,externClass);
return nestedClass;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a class defined in another module of THIS assembly
/// and exported (.class extern)
/// </summary>
internal class ExternClass : Class {
MetaDataElement parent;
uint flags;
internal ExternClass(TypeAttr attr, uint nsIx, uint nIx,
MetaDataElement paren) : base(nsIx,nIx)
{
flags = (uint)attr;
parent = paren;
tabIx = MDTable.ExportedType;
}
internal sealed override uint Size(MetaData md)
{
return 8 + 2* md.StringsIndexSize() + md.CodedIndexSize(CIx.Implementation);
}
internal sealed override void Write(FileImage output)
{
output.Write(flags);
output.Write(0);
output.StringsIndex(nameIx);
output.StringsIndex(nameSpaceIx);
output.WriteCodedIndex(CIx.Implementation,parent);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 17;
case (CIx.Implementation) : return 2;
}
return 0;
}
}
public class GenParam : Class {
private int index;
private string param_name;
private uint sigIx = 0;
public GenParam (int index, string name, GenParamType ptype) : base ((byte) ptype)
{
this.index = index;
this.param_name = name;
tabIx = MDTable.TypeSpec;
}
public int Index {
get { return index; }
set { index = value; }
}
public string Name {
get { return param_name; }
set { param_name = value; }
}
public GenParamType Type {
get { return (GenParamType) GetTypeIndex (); }
}
internal sealed override void BuildTables (MetaData md)
{
if (done)
return;
MemoryStream str = new MemoryStream ();
TypeSig (str);
sigIx = md.AddToBlobHeap (str.ToArray ());
done = true;
}
internal sealed override void TypeSig(MemoryStream str)
{
if (index < 0)
throw new PEFileException (String.Format ("Unresolved {0} - {1}", (GenParamType) GetTypeIndex (), param_name));
str.WriteByte(typeIndex);
MetaData.CompressNum ((uint) index, str);
}
internal override uint Size(MetaData md)
{
return md.BlobIndexSize();
}
internal sealed override void Write (FileImage output)
{
output.BlobIndex (sigIx);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.TypeDefOrRef) : return 2;
case (CIx.HasCustomAttr) : return 13;
case (CIx.MemberRefParent) : return 4;
}
return 0;
}
}
public class GenericTypeInst : Class {
private Type gen_type;
private Type[] gen_param;
bool inTable = false;
uint sigIx = 0;
public GenericTypeInst (Type gen_type, Type[] gen_param)
: base ((byte) PrimitiveType.GenericInst.GetTypeIndex ())
{
this.gen_type = gen_type;
this.gen_param = gen_param;
tabIx = MDTable.TypeSpec;
}
internal override MetaDataElement GetTypeSpec (MetaData md)
{
if (!inTable) {
md.AddToTable (MDTable.TypeSpec, this);
inTable = true;
}
return this;
}
internal sealed override void TypeSig(MemoryStream str)
{
str.WriteByte(typeIndex);
gen_type.TypeSig (str);
MetaData.CompressNum ((uint) gen_param.Length, str);
foreach (Type param in gen_param)
param.TypeSig (str);
}
internal sealed override void BuildTables (MetaData md)
{
if (done)
return;
MemoryStream str = new MemoryStream ();
TypeSig (str);
sigIx = md.AddToBlobHeap (str.ToArray ());
done = true;
}
internal sealed override uint Size (MetaData md)
{
return md.BlobIndexSize ();
}
internal sealed override void Write (FileImage output)
{
output.BlobIndex (sigIx);
}
internal sealed override uint GetCodedIx (CIx code)
{
switch (code) {
case (CIx.TypeDefOrRef): return 2;
case (CIx.MemberRefParent): return 4;
case (CIx.HasCustomAttr): return 13;
}
return 0;
}
}
public class GenericMethodSig {
private Type[] gen_param;
private bool done;
private uint sigIx = 0;
public GenericMethodSig (Type[] gen_param)
{
this.gen_param = gen_param;
done = false;
}
internal void TypeSig (MemoryStream str)
{
str.WriteByte (0x0A); /* GENERIC_INST */
MetaData.CompressNum ((uint) gen_param.Length, str);
foreach (Type param in gen_param)
param.TypeSig (str);
}
internal uint GetSigIx (MetaData md)
{
if (done)
return sigIx;
MemoryStream sig = new MemoryStream();
TypeSig (sig);
sigIx = md.AddToBlobHeap (sig.ToArray());
done = true;
return sigIx;
}
}
public class Sentinel : Type {
public Sentinel () : base (0x41) { }
internal sealed override void TypeSig(MemoryStream str)
{
str.WriteByte(typeIndex);
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a FunctionPointer type
/// </summary>
///
public class MethPtrType : Type {
bool varArgMeth;
Type retType;
Type [] parList;
Type [] optParList;
CallConv callConv;
uint numPars;
uint numOptPars;
uint sigIx = 0;
/// <summary>
/// Create a new function pointer type
/// </summary>
/// <param name="meth">the function to be referenced</param>
public MethPtrType (CallConv callconv, Type retType, Type[] pars,
bool varArgMeth, Type[] optPars) : base(0x1B)
{
this.retType = retType;
callConv = callconv;
parList = pars;
this.varArgMeth = varArgMeth;
if (parList != null) numPars = (uint)parList.Length;
if (varArgMeth) {
optParList = optPars;
if (optParList != null) numOptPars = (uint)optParList.Length;
callConv |= CallConv.Vararg;
}
tabIx = MDTable.TypeSpec;
}
internal sealed override void TypeSig(MemoryStream sig)
{
sig.WriteByte(typeIndex);
// Bootlegged from method ref
sig.WriteByte((byte)callConv);
MetaData.CompressNum (numPars + numOptPars, sig);
retType.TypeSig (sig);
for (int i=0; i < numPars; i++) {
parList[i].TypeSig (sig);
}
if (varArgMeth) {
sig.WriteByte (0x41); // Write the sentinel
for (int i=0; i < numOptPars; i++) {
optParList[i].TypeSig (sig);
}
}
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
MemoryStream sig = new MemoryStream();
TypeSig(sig);
sigIx = md.AddToBlobHeap(sig.ToArray());
done = true;
}
internal sealed override uint Size(MetaData md)
{
return md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.BlobIndex(sigIx);
}
internal sealed override uint GetCodedIx(CIx code) { return 0x1B; }
}
#region Array Types
/* Classes for Arrays */
/// <summary>
/// The IL Array type
/// </summary>
public abstract class Array : Type {
protected Type elemType;
protected MetaData metaData;
protected string cnameSpace, cname;
internal Array(Type eType, byte TypeId) : base(TypeId)
{
elemType = eType;
tabIx = MDTable.TypeSpec;
}
}
/// <summary>
/// Single dimensional array with zero lower bound
/// </summary>
public class ZeroBasedArray : Array {
/// <summary>
/// Create a new array - elementType[]
/// </summary>
/// <param name="elementType">the type of the array elements</param>
public ZeroBasedArray(Type elementType) : base (elementType, PrimitiveType.SZArray.GetTypeIndex ()) { }
internal sealed override void TypeSig(MemoryStream str)
{
str.WriteByte(typeIndex);
elemType.TypeSig(str);
}
}
/// <summary>
/// Multi dimensional array with explicit bounds
/// </summary>
public class BoundArray : Array {
int[] lowerBounds;
int[] sizes;
uint numDims;
/// <summary>
/// Create a new multi dimensional array type
/// eg. elemType[1..5,3..10,5,,] would be
/// new BoundArray(elemType,5,[1,3,0],[5,10,4])
/// </summary>
/// <param name="elementType">the type of the elements</param>
/// <param name="dimensions">the number of dimensions</param>
/// <param name="loBounds">lower bounds of dimensions</param>
/// <param name="sizes">sizes for the dimensions</param>
public BoundArray(Type elementType, uint dimensions, int[] loBounds,
int[] sizes) : base (elementType,0x14)
{
numDims = dimensions;
lowerBounds = loBounds;
this.sizes = sizes;
}
/// <summary>
/// Create a new multi dimensional array type
/// eg. elemType[5,10,20] would be new BoundArray(elemType,3,[5,10,20])
/// </summary>
/// <param name="elementType">the type of the elements</param>
/// <param name="dimensions">the number of dimensions</param>
/// <param name="size">the sizes of the dimensions</param>
public BoundArray(Type elementType, uint dimensions, int[] size)
: base (elementType,0x14)
{
numDims = dimensions;
sizes = size;
}
/// <summary>
/// Create a new multi dimensional array type
/// eg. elemType[,,] would be new BoundArray(elemType,3)
/// </summary>
/// <param name="elementType">the type of the elements</param>
/// <param name="dimensions">the number of dimensions</param>
public BoundArray(Type elementType, uint dimensions)
: base (elementType,0x14)
{
numDims = dimensions;
}
internal sealed override void TypeSig(MemoryStream str)
{
str.WriteByte(typeIndex);
elemType.TypeSig(str);
MetaData.CompressNum(numDims,str);
if ((sizes != null) && (sizes.Length > 0)) {
MetaData.CompressNum((uint)sizes.Length,str);
for (int i=0; i < sizes.Length; i++) {
MetaData.CompressNum((uint)sizes[i],str);
}
} else str.WriteByte(0);
if ((lowerBounds != null) && (lowerBounds.Length > 0)) {
MetaData.CompressNum((uint)lowerBounds.Length,str);
for (int i=0; i < lowerBounds.Length; i++) {
CompressSignedNum (lowerBounds[i],str);
}
} else str.WriteByte(0);
}
private void CompressSignedNum (int val, MemoryStream str)
{
uint uval = (uint) val;
byte sign = 0;
if (val < 0) {
val = -val;
sign = 1;
}
/* Map the signed number to an unsigned number in two ways.
fval: left-rotated 2's complement representation
sval: map the signed number to unsigned as follows: 0 -> 0, -1 -> 1, 1 -> 2, -2 -> 3, 2 -> 4, ....
the mapping is: x -> 2*|x| - signbit(x)
*/
uint fval = (uval << 1) | sign;
int sval = (val << 1) - sign;
/* An overly clever transformation:
a. sval is used to determine the number of bytes in the compressed representation.
b. fval is truncated to the appropriate number of bits and output using the
normal unsigned-int compressor.
However, or certain values, the truncated fval doesn't carry enough information to round trip.
(fval & 0x3FFF) <= 0x7F => compressor emits 1 byte, not 2 => there is aliasing of values
So, we use full 4 bytes to encode such values.
LAMESPEC: The Microsoft implementation doesn't appear to handle this subtle case.
e.g., it ends up encoding -8192 as the byte 0x01, which decodes to -64
*/
if (sval <= 0x7F)
MetaData.CompressNum (fval & 0x7F, str);
else if (sval <= 0x3FFF && (fval & 0x3FFF) > 0x7F)
MetaData.CompressNum (fval & 0x3FFF, str);
else if (sval <= 0x1FFFFFFF && (fval & 0x1FFFFFFF) > 0x3FFF)
MetaData.CompressNum (fval & 0x1FFFFFFF, str);
else
/* FIXME: number cannot be represented. Report a warning. */
// throw new Exception ("cannot represent signed value" + -val);
MetaData.CompressNum (fval, str);
}
}
#endregion
/* Empty interface for grouping TypeRef's possible ResolutionScope
namely : Module, ModuleRef, AssemblyRef and TypeRef */
public interface IResolutionScope {
}
/**************************************************************************/
/// <summary>
/// Base class for scopes (extended by Module, ModuleRef, Assembly, AssemblyRef)
/// </summary>
public abstract class ResolutionScope : MetaDataElement, IResolutionScope {
protected uint nameIx = 0;
protected MetaData metaData;
protected string name;
internal ResolutionScope(string name, MetaData md)
{
metaData = md;
this.name = name;
nameIx = md.AddToStringsHeap(name);
}
internal string GetName() { return name; }
}
/**************************************************************************/
/// <summary>
/// Descriptor for THIS assembly (.assembly)
/// </summary>
public class Assembly : ResolutionScope {
ushort majorVer, minorVer, buildNo, revisionNo;
uint flags;
uint hashAlgId;
uint keyIx = 0, cultIx = 0;
bool hasPublicKey = false;
internal Assembly(string name, MetaData md) : base(name,md)
{
tabIx = MDTable.Assembly;
}
/// <summary>
/// Add details about THIS assembly
/// </summary>
/// <param name="majVer">Major Version</param>
/// <param name="minVer">Minor Version</param>
/// <param name="bldNo">Build Number</param>
/// <param name="revNo">Revision Number</param>
/// <param name="key">Hash Key</param>
/// <param name="hash">Hash Algorithm</param>
/// <param name="cult">Culture</param>
public void AddAssemblyInfo(int majVer, int minVer, int bldNo, int revNo,
byte[] key, uint hash, string cult)
{
majorVer = (ushort)majVer;
minorVer = (ushort)minVer;
buildNo = (ushort)bldNo;
revisionNo = (ushort)revNo;
hashAlgId = hash;
hasPublicKey = (key != null);
keyIx = metaData.AddToBlobHeap(key);
cultIx = metaData.AddToStringsHeap(cult);
}
/// <summary>
/// Add an attribute to THIS assembly
/// </summary>
/// <param name="aa">assembly attribute</param>
public void AddAssemblyAttr(AssemAttr aa)
{
flags |= (uint)aa;
}
internal sealed override uint Size(MetaData md)
{
return 16 + md.BlobIndexSize() + 2 * md.StringsIndexSize();
}
internal sealed override void Write(FileImage output)
{
// Console.WriteLine("Writing assembly element with nameIx of " + nameIx + " at file offset " + output.Seek(0,SeekOrigin.Current));
output.Write((uint)hashAlgId);
output.Write(majorVer);
output.Write(minorVer);
output.Write(buildNo);
output.Write(revisionNo);
output.Write(flags);
output.BlobIndex(keyIx);
output.StringsIndex(nameIx);
output.StringsIndex(cultIx);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 14;
case (CIx.HasDeclSecurity) : return 2;
}
return 0;
}
internal bool HasPublicKey {
get { return hasPublicKey; }
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for THIS module
/// </summary>
public class Module : ResolutionScope, IExternRef {
Guid mvid;
uint mvidIx = 0;
internal Module(string name, MetaData md) : base(name,md)
{
mvid = Guid.NewGuid();
mvidIx = md.AddToGUIDHeap(mvid);
tabIx = MDTable.Module;
}
public Guid Guid {
get { return mvid; }
}
public ClassRef AddClass(string nsName, string name)
{
ClassRef aClass = new ClassRef (nsName, name, metaData);
metaData.AddToTable (MDTable.TypeRef, aClass);
aClass.SetParent (this);
return aClass;
}
public ClassRef AddValueClass(string nsName, string name)
{
ClassRef aClass = AddClass (nsName, name);
aClass.MakeValueClass (ValueClass.ValueType);
return aClass;
}
internal sealed override uint Size(MetaData md)
{
return 2 + md.StringsIndexSize() + 3 * md.GUIDIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.Write((short)0);
output.StringsIndex(nameIx);
output.GUIDIndex(mvidIx);
output.GUIDIndex(0);
output.GUIDIndex(0);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 7;
case (CIx.ResolutionScope) : return 0;
}
return 0;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for another module in THIS assembly
/// </summary>
public class ModuleRef : ResolutionScope, IExternRef {
internal ModuleRef(MetaData md, string name) : base(name,md)
{
tabIx = MDTable.ModuleRef;
}
/// <summary>
/// Add a class to this external module. This is a class declared in
/// another module of THIS assembly.
/// </summary>
/// <param name="nsName">name space name</param>
/// <param name="name">class name</param>
/// <returns>a descriptor for this class in another module</returns>
public ClassRef AddClass(string nsName, string name)
{
ClassRef aClass = new ClassRef(nsName,name,metaData);
metaData.AddToTable(MDTable.TypeRef,aClass);
aClass.SetParent(this);
return aClass;
}
/// <summary>
/// Make a file descriptor to correspond to this module. The file
/// descriptor will have the same name as the module descriptor
/// </summary>
/// <param name="hashBytes">the hash of the file</param>
/// <param name="hasMetaData">the file contains metadata</param>
/// <param name="entryPoint">the program entry point is in this file</param>
/// <returns>a descriptor for the file which contains this module</returns>
public FileRef MakeFile(byte[] hashBytes, bool hasMetaData, bool entryPoint)
{
FileRef file = new FileRef(nameIx,hashBytes,hasMetaData,entryPoint,metaData);
metaData.AddToTable(MDTable.File,file);
return file;
}
/// <summary>
/// Add a value class to this module. This is a class declared in
/// another module of THIS assembly.
/// </summary>
/// <param name="nsName">name space name</param>
/// <param name="name">class name</param>
/// <returns></returns>
public ClassRef AddValueClass(string nsName, string name)
{
ClassRef aClass = new ClassRef(nsName,name,metaData);
metaData.AddToTable(MDTable.TypeRef,aClass);
aClass.SetParent(this);
aClass.MakeValueClass(ValueClass.ValueType);
return aClass;
}
/// <summary>
/// Add a class which is declared public in this external module of
/// THIS assembly. This class will be exported from this assembly.
/// The ilasm syntax for this is .extern class
/// </summary>
/// <param name="attrSet">attributes of the class to be exported</param>
/// <param name="nsName">name space name</param>
/// <param name="name">external class name</param>
/// <param name="declFile">the file where the class is declared</param>
/// <param name="isValueClass">is this class a value type?</param>
/// <returns>a descriptor for this external class</returns>
public ExternClassRef AddExternClass(TypeAttr attrSet, string nsName,
string name, FileRef declFile,
bool isValueClass) {
ExternClassRef cRef = new ExternClassRef(attrSet,nsName,name,declFile,metaData);
metaData.AddToTable(MDTable.TypeRef,cRef);
cRef.SetParent(this);
if (isValueClass) cRef.MakeValueClass(ValueClass.ValueType);
return cRef;
}
/// <summary>
/// Add a "global" method in another module
/// </summary>
/// <param name="name">method name</param>
/// <param name="retType">return type</param>
/// <param name="pars">method parameter types</param>
/// <returns>a descriptor for this method in anther module</returns>
public MethodRef AddMethod(string name, Type retType, Type[] pars)
{
MethodRef meth = new MethodRef(this,name,retType,pars,false,null, 0);
metaData.AddToTable(MDTable.MemberRef,meth);
return meth;
}
/// <summary>
/// Add a vararg method to this class
/// </summary>
/// <param name="name">method name</param>
/// <param name="retType">return type</param>
/// <param name="pars">parameter types</param>
/// <param name="optPars">optional param types for this vararg method</param>
/// <returns>a descriptor for this method</returns>
public MethodRef AddVarArgMethod(string name, Type retType,
Type[] pars, Type[] optPars) {
MethodRef meth = new MethodRef(this,name,retType,pars,true,optPars, 0);
metaData.AddToTable(MDTable.MemberRef,meth);
return meth;
}
/// <summary>
/// Add a field in another module
/// </summary>
/// <param name="name">field name</param>
/// <param name="fType">field type</param>
/// <returns>a descriptor for this field in another module</returns>
public FieldRef AddField(string name, Type fType)
{
FieldRef field = new FieldRef(this,name,fType);
metaData.AddToTable(MDTable.MemberRef,field);
return field;
}
internal sealed override uint Size(MetaData md)
{
return md.StringsIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.StringsIndex(nameIx);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 12;
case (CIx.MemberRefParent) : return 2;
case (CIx.ResolutionScope) : return 1;
}
return 0;
}
}
#region Classes for Constants
/// <summary>
/// Descriptor for a constant value
/// </summary>
public abstract class Constant {
protected uint size = 0;
protected Type type;
protected uint blobIndex;
protected bool addedToBlobHeap = false;
internal Constant() { }
internal virtual uint GetBlobIndex(MetaData md) { return 0; }
internal uint GetSize() { return size; }
internal byte GetTypeIndex() { return type.GetTypeIndex(); }
internal virtual void Write(BinaryWriter bw) { }
}
/// <summary>
/// Descriptor for a constant value
/// </summary>
public abstract class DataConstant : Constant {
private uint dataOffset = 0;
internal DataConstant() { }
public uint DataOffset {
get { return dataOffset; }
set { dataOffset = value; }
}
}
/// <summary>
/// Boolean constant
/// </summary>
public class BoolConst : DataConstant {
bool val;
/// <summary>
/// Create a new boolean constant with the value "val"
/// </summary>
/// <param name="val">value of this boolean constant</param>
public BoolConst(bool val)
{
this.val = val;
size = 1;
type = PrimitiveType.Boolean;
}
internal sealed override uint GetBlobIndex(MetaData md)
{
if (!addedToBlobHeap) {
if (val) blobIndex = md.AddToBlobHeap((sbyte)1);
else blobIndex = md.AddToBlobHeap((sbyte)0);
addedToBlobHeap = true;
}
return blobIndex;
}
internal sealed override void Write(BinaryWriter bw)
{
if (val) bw.Write((sbyte)1);
else bw.Write((sbyte)0);
}
}
public class ByteArrConst : DataConstant {
internal byte[] val;
public ByteArrConst(byte[] val)
{
type = PrimitiveType.String;
this.val = val;
size = (uint)val.Length;
}
public Type Type {
get { return type; }
set { type = value; }
}
internal sealed override uint GetBlobIndex(MetaData md)
{
if (!addedToBlobHeap) {
blobIndex = md.AddToBlobHeap(val);
addedToBlobHeap = true;
}
return blobIndex;
}
internal sealed override void Write(BinaryWriter bw)
{
bw.Write(val);
}
}
public class CharConst : Constant {
char val;
public CharConst(char val)
{
this.val = val;
size = 2;
type = PrimitiveType.Char;
}
internal sealed override uint GetBlobIndex(MetaData md)
{
if (!addedToBlobHeap) {
blobIndex = md.AddToBlobHeap(val);
addedToBlobHeap = true;
}
return blobIndex;
}
internal sealed override void Write(BinaryWriter bw)
{
bw.Write(val);
}
}
public class FloatConst : DataConstant {
float val;
public FloatConst(float val)
{
this.val = val;
size = 4;
type = PrimitiveType.Float32;
}
internal sealed override uint GetBlobIndex(MetaData md)
{
if (!addedToBlobHeap) {
blobIndex = md.AddToBlobHeap(val);
addedToBlobHeap = true;
}
return blobIndex;
}
internal sealed override void Write(BinaryWriter bw)
{
bw.Write(val);
}
}
public class DoubleConst : DataConstant {
double val;
public DoubleConst(double val)
{
this.val = val;
size = 8;
type = PrimitiveType.Float64;
}
internal sealed override uint GetBlobIndex(MetaData md)
{
if (!addedToBlobHeap) {
blobIndex = md.AddToBlobHeap(val);
addedToBlobHeap = true;
}
return blobIndex;
}
internal sealed override void Write(BinaryWriter bw)
{
bw.Write(val);
}
}
public class IntConst : DataConstant {
long val;
public IntConst(sbyte val)
{
this.val = val;
size = 1;
type = PrimitiveType.Int8;
}
public IntConst(short val)
{
this.val = val;
size = 2;
type = PrimitiveType.Int16;
}
public IntConst(int val)
{
this.val = val;
size = 4;
type = PrimitiveType.Int32;
}
public IntConst(long val)
{
this.val = val;
size = 8;
type = PrimitiveType.Int64;
}
internal sealed override uint GetBlobIndex(MetaData md)
{
if (!addedToBlobHeap) {
switch (size) {
case (1) : blobIndex = md.AddToBlobHeap((sbyte)val); break;
case (2) : blobIndex = md.AddToBlobHeap((short)val); break;
case (4) : blobIndex = md.AddToBlobHeap((int)val); break;
default : blobIndex = md.AddToBlobHeap(val); break;
}
addedToBlobHeap = true;
}
return blobIndex;
}
internal sealed override void Write(BinaryWriter bw)
{
switch (size) {
case (1) : bw.Write((sbyte)val); break;
case (2) : bw.Write((short)val); break;
case (4) : bw.Write((int)val); break;
default : bw.Write(val); break;
}
}
}
public class UIntConst : DataConstant {
ulong val;
public UIntConst(byte val)
{
this.val = val;
size = 1;
type = PrimitiveType.UInt8;
}
public UIntConst(ushort val)
{
this.val = val;
size = 2;
type = PrimitiveType.UInt16;
}
public UIntConst(uint val)
{
this.val = val;
size = 4;
type = PrimitiveType.UInt32;
}
public UIntConst(ulong val)
{
this.val = val;
size = 8;
type = PrimitiveType.UInt64;
}
internal sealed override uint GetBlobIndex(MetaData md)
{
if (!addedToBlobHeap) {
switch (size) {
case (1) : blobIndex = md.AddToBlobHeap((byte)val); break;
case (2) : blobIndex = md.AddToBlobHeap((ushort)val); break;
case (4) : blobIndex = md.AddToBlobHeap((uint)val); break;
default : blobIndex = md.AddToBlobHeap(val); break;
}
addedToBlobHeap = true;
}
return blobIndex;
}
internal sealed override void Write(BinaryWriter bw)
{
switch (size) {
case (1) : bw.Write((byte)val); break;
case (2) : bw.Write((ushort)val); break;
case (4) : bw.Write((uint)val); break;
default : bw.Write(val); break;
}
}
}
public class StringConst : DataConstant {
internal string val;
public StringConst(string val)
{
this.val = val;
size = (uint)val.Length; // need to add null ??
type = PrimitiveType.String;
}
internal sealed override uint GetBlobIndex(MetaData md)
{
if (!addedToBlobHeap) {
byte [] b = Encoding.Unicode.GetBytes (val);
blobIndex = md.AddToBlobHeap(b);
addedToBlobHeap = true;
}
return blobIndex;
}
internal sealed override void Write(BinaryWriter bw)
{
bw.Write(val);
}
}
public class NullConst : Constant {
public NullConst()
{
size = 4;
type = PrimitiveType.Class;
}
internal sealed override uint GetBlobIndex(MetaData md)
{
if (!addedToBlobHeap) {
blobIndex = md.AddToBlobHeap((int)0);
addedToBlobHeap = true;
}
return blobIndex;
}
internal sealed override void Write(BinaryWriter bw)
{
bw.Write((int)0);
}
}
public class AddressConstant : DataConstant {
DataConstant data;
public AddressConstant(DataConstant dConst)
{
data = dConst;
size = 4;
type = PrimitiveType.TypedRef;
}
internal sealed override void Write(BinaryWriter bw)
{
((FileImage)bw).WriteDataRVA(data.DataOffset);
}
}
public class RepeatedConstant : DataConstant {
DataConstant data;
uint repCount;
public RepeatedConstant(DataConstant dConst, int repeatCount)
{
data = dConst;
repCount = (uint)repeatCount;
int[] sizes = new int[1];
sizes[0] = repeatCount;
type = new BoundArray(type,1,sizes);
size = data.GetSize() * repCount;
}
internal sealed override void Write(BinaryWriter bw)
{
for (int i=0; i < repCount; i++) {
data.Write(bw);
}
}
}
public class ArrayConstant : DataConstant {
DataConstant[] dataVals;
public ArrayConstant(DataConstant[] dVals)
{
dataVals = dVals;
for (int i=0; i < dataVals.Length; i++) {
size += dataVals[i].GetSize();
}
}
public int? ExplicitSize { get; set; }
internal sealed override void Write(BinaryWriter bw)
{
for (int i=0; i < dataVals.Length; i++) {
dataVals[i].Write(bw);
}
}
}
public class ClassType : Constant {
string name;
Class desc;
public ClassType(string className)
{
name = className;
type = PrimitiveType.ClassType;
}
public ClassType(Class classDesc)
{
desc = classDesc;
type = PrimitiveType.ClassType;
}
internal override void Write(BinaryWriter bw)
{
if (name == null) name = desc.TypeName();
bw.Write(name);
}
}
#endregion
/**************************************************************************/
/// <summary>
/// Descriptor for a custom modifier of a type (modopt or modreq)
/// </summary>
public class CustomModifiedType : Type {
Type type;
Class cmodType;
PrimitiveTypeRef cmodPrimType;
/// <summary>
/// Create a new custom modifier for a type
/// </summary>
/// <param name="type">the type to be modified</param>
/// <param name="cmod">the modifier</param>
/// <param name="cmodType">the type reference to be associated with the type</param>
public CustomModifiedType(Type type, CustomModifier cmod, Class cmodType)
: base((byte)cmod)
{
this.type = type;
this.cmodType = cmodType;
}
public CustomModifiedType(Type type, CustomModifier cmod, PrimitiveTypeRef cmodType)
: base((byte)cmod)
{
this.type = type;
this.cmodPrimType = cmodType;
}
internal sealed override void TypeSig(MemoryStream str)
{
str.WriteByte(typeIndex);
if (cmodType != null) {
MetaData.CompressNum(cmodType.TypeDefOrRefToken(),str);
} else {
MetaData.CompressNum(cmodPrimType.TypeDefOrRefToken(),str);
}
type.TypeSig(str);
}
}
/**************************************************************************/
/// <summary>
/// Base class for Event and Property descriptors
/// </summary>
public class Feature : MetaDataElement {
internal enum MethodType : ushort { Setter = 0x01, Getter, Other = 0x04, AddOn = 0x08,
RemoveOn = 0x10, Fire = 0x20 }
private static readonly int INITSIZE = 5;
private static readonly ushort specialName = 0x200;
private static readonly ushort rtSpecialName = 0x400;
protected ClassDef parent;
protected ushort flags = 0;
protected string name;
protected int tide = 0;
protected uint nameIx;
protected MethodSemantics[] methods = new MethodSemantics[INITSIZE];
internal Feature(string name, ClassDef par)
{
parent = par;
this.name = name;
}
internal void AddMethod(MethodDef meth, MethodType mType)
{
if (tide >= methods.Length) {
int len = methods.Length;
MethodSemantics[] mTmp = methods;
methods = new MethodSemantics[len * 2];
for (int i=0; i < len; i++) {
methods[i] = mTmp[i];
}
}
methods[tide++] = new MethodSemantics(mType,meth,this);
}
/// <summary>
/// Set the specialName attribute for this Event or Property
/// </summary>
public void SetSpecialName()
{
flags |= specialName;
}
/// <summary>
/// Set the RTSpecialName attribute for this Event or Property
/// </summary>
public void SetRTSpecialName()
{
flags |= rtSpecialName;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for an event
/// </summary>
public class Event : Feature {
Type eventType;
internal Event(string name, Type eType, ClassDef parent)
: base(name, parent)
{
eventType = eType;
tabIx = MDTable.Event;
}
/// <summary>
/// Add the addon method to this event
/// </summary>
/// <param name="addon">the addon method</param>
public void AddAddon(MethodDef addon)
{
AddMethod(addon,MethodType.AddOn);
}
/// <summary>
/// Add the removeon method to this event
/// </summary>
/// <param name="removeOn">the removeon method</param>
public void AddRemoveOn(MethodDef removeOn)
{
AddMethod(removeOn,MethodType.RemoveOn);
}
/// <summary>
/// Add the fire method to this event
/// </summary>
/// <param name="fire">the fire method</param>
public void AddFire(MethodDef fire)
{
AddMethod(fire,MethodType.Fire);
}
/// <summary>
/// Add another method to this event
/// </summary>
/// <param name="other">the method to be added</param>
public void AddOther(MethodDef other)
{
AddMethod(other,MethodType.Other);
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
nameIx = md.AddToStringsHeap(name);
for (int i=0; i < tide; i++) {
md.AddToTable(MDTable.MethodSemantics,methods[i]);
}
done = true;
}
internal sealed override uint Size(MetaData md)
{
return 2 + md.StringsIndexSize() + md.CodedIndexSize(CIx.TypeDefOrRef);
}
internal sealed override void Write(FileImage output)
{
output.Write(flags);
output.StringsIndex(nameIx);
output.WriteCodedIndex(CIx.TypeDefOrRef,eventType);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 10;
case (CIx.HasSemantics) : return 0;
}
return 0;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for the Property of a class
/// </summary>
public class Property : Feature {
private static readonly byte PropertyTag = 0x8;
private bool instance;
MethodDef getterMeth;
ConstantElem constVal;
uint typeBlobIx = 0;
Type[] parList;
Type returnType;
uint numPars = 0;
internal Property(string name, Type retType, Type[] pars, ClassDef parent) : base(name, parent)
{
returnType = retType;
parList = pars;
if (pars != null) numPars = (uint)pars.Length;
tabIx = MDTable.Property;
}
/// <summary>
/// Add a set method to this property
/// </summary>
/// <param name="setter">the set method</param>
public void AddSetter(MethodDef setter)
{
AddMethod(setter,MethodType.Setter);
}
/// <summary>
/// Add a get method to this property
/// </summary>
/// <param name="getter">the get method</param>
public void AddGetter(MethodDef getter)
{
AddMethod(getter,MethodType.Getter);
getterMeth = getter;
}
/// <summary>
/// Add another method to this property
/// </summary>
/// <param name="other">the method</param>
public void AddOther(MethodDef other)
{
AddMethod(other,MethodType.Other);
}
/// <summary>
/// Add an initial value for this property
/// </summary>
/// <param name="constVal">the initial value for this property</param>
public void AddInitValue(Constant constVal)
{
this.constVal = new ConstantElem(this,constVal);
}
public void SetInstance (bool isInstance)
{
this.instance = isInstance;
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
nameIx = md.AddToStringsHeap(name);
MemoryStream sig = new MemoryStream();
byte tag = PropertyTag;
if (instance)
tag |= 0x20;
sig.WriteByte(tag);
MetaData.CompressNum(numPars,sig);
returnType.TypeSig(sig);
for (int i=0; i < numPars; i++) {
parList[i].TypeSig(sig);
}
typeBlobIx = md.AddToBlobHeap(sig.ToArray());
for (int i=0; i < tide; i++) {
md.AddToTable(MDTable.MethodSemantics,methods[i]);
}
if (constVal != null) {
md.AddToTable(MDTable.Constant,constVal);
constVal.BuildTables(md);
}
done = true;
}
internal sealed override uint Size(MetaData md)
{
return 2 + md.StringsIndexSize() + md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.Write(flags);
output.StringsIndex(nameIx);
output.BlobIndex(typeBlobIx);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 9;
case (CIx.HasConst) : return 2;
case (CIx.HasSemantics) : return 1;
}
return 0;
}
}
/**************************************************************************/
/// <summary>
/// Base class for field/methods (member of a class)
/// </summary>
public abstract class Member : MetaDataElement {
protected string name;
protected uint nameIx = 0, sigIx = 0;
internal Member(string memName)
{
name = memName;
tabIx = MDTable.MemberRef;
}
}
/*****************************************************************************/
/// <summary>
/// Descriptor for a field of a class
/// </summary>
public abstract class Field : Member {
protected static readonly byte FieldSig = 0x6;
protected Type type;
internal Field(string pfName, Type pfType) : base(pfName)
{
type = pfType;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a field defined in a class of THIS assembly/module
/// </summary>
public class FieldDef : Field {
//private static readonly uint PInvokeImpl = 0x2000;
private static readonly ushort HasFieldRVA = 0x100;
private static readonly ushort HasDefault = 0x8000;
FieldRVA rva;
ConstantElem constVal;
FieldLayout layout;
FieldMarshal marshalInfo;
ushort flags;
internal FieldDef(string name, Type fType) : base(name,fType)
{
tabIx = MDTable.Field;
}
internal FieldDef(FieldAttr attrSet, string name, Type fType) : base(name, fType)
{
flags = (ushort)attrSet;
tabIx = MDTable.Field;
}
/// <summary>
/// Add an attribute(s) to this field
/// </summary>
/// <param name="fa">the attribute(s) to be added</param>
public void AddFieldAttr(FieldAttr fa)
{
flags |= (ushort)fa;
}
/// <summary>
/// Add a value for this field
/// </summary>
/// <param name="val">the value for the field</param>
public void AddValue(Constant val)
{
constVal = new ConstantElem(this,val);
flags |= HasDefault;
}
/// <summary>
/// Add an initial value for this field (at dataLabel) (.data)
/// </summary>
/// <param name="val">the value for the field</param>
/// <param name="repeatVal">the number of repetitions of this value</param>
public void AddDataValue(DataConstant val)
{
flags |= HasFieldRVA;
rva = new FieldRVA(this,val);
}
/// <summary>
/// Set the offset of the field. Used for sequential or explicit classes.
/// (.field [offs])
/// </summary>
/// <param name="offs">field offset</param>
public void SetOffset(uint offs)
{
layout = new FieldLayout(this,offs);
}
/// <summary>
/// Set the marshalling info for a field
/// </summary>
/// <param name="mInf"></param>
public void SetMarshalInfo(NativeType marshallType)
{
flags |= (ushort) FieldAttr.HasFieldMarshal;
marshalInfo = new FieldMarshal(this,marshallType);
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
nameIx = md.AddToStringsHeap(name);
MemoryStream sig = new MemoryStream();
sig.WriteByte(FieldSig);
type.TypeSig(sig);
sigIx = md.AddToBlobHeap(sig.ToArray());
if (rva != null) {
md.AddToTable(MDTable.FieldRVA,rva);
rva.BuildTables(md);
} else if (constVal != null) {
md.AddToTable(MDTable.Constant,constVal);
constVal.BuildTables(md);
}
if (layout != null) md.AddToTable(MDTable.FieldLayout,layout);
if (marshalInfo != null) {
md.AddToTable(MDTable.FieldMarshal,marshalInfo);
marshalInfo.BuildTables(md);
}
done = true;
}
internal sealed override uint Size(MetaData md)
{
return 2 + md.StringsIndexSize() + md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.Write(flags);
output.StringsIndex(nameIx);
output.BlobIndex(sigIx);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasConst) : return 0;
case (CIx.HasCustomAttr) : return 1;
case (CIx.HasFieldMarshal) : return 0;
case (CIx.MemberForwarded) : return 0;
}
return 0;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a field of a class defined in another assembly/module
/// </summary>
public class FieldRef : Field {
MetaDataElement parent;
internal FieldRef(MetaDataElement paren, string name, Type fType) : base(name, fType)
{
parent = paren;
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
nameIx = md.AddToStringsHeap(name);
MemoryStream sig = new MemoryStream();
sig.WriteByte(FieldSig);
type.TypeSig(sig);
sigIx = md.AddToBlobHeap(sig.ToArray());
done = true;
}
internal sealed override uint Size(MetaData md)
{
return md.CodedIndexSize(CIx.MemberRefParent) + md.StringsIndexSize() + md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.WriteCodedIndex(CIx.MemberRefParent,parent);
output.StringsIndex(nameIx);
output.BlobIndex(sigIx);
}
internal sealed override uint GetCodedIx(CIx code) { return 6; }
}
/**************************************************************************/
/// <summary>
/// Base class for Method Descriptors
/// </summary>
public abstract class Method : Member {
internal Method (string methName) : base (methName)
{}
public abstract void AddCallConv(CallConv cconv);
internal abstract void TypeSig(MemoryStream sig);
internal abstract uint GetSigIx(MetaData md);
}
/**************************************************************************/
/// <summary>
/// Descriptor for a method defined in THIS assembly/module
/// IL .method
/// </summary>
public class MethodDef : Method {
private static readonly ushort PInvokeImpl = 0x2000;
//private static readonly uint UnmanagedExport = 0x0008;
// private static readonly byte LocalSigByte = 0x7;
uint parIx = 0, textOffset = 0;
private CallConv callConv = CallConv.Default;
private int gen_param_count;
MetaData metaData;
CILInstructions code;
Param[] parList;
Local[] locals;
bool initLocals;
ushort methFlags = 0, implFlags = 0;
int maxStack = 0, numPars = 0;
bool entryPoint = false;
LocalSig localSig;
ArrayList varArgSigList;
ImplMap pinvokeImpl;
Param ret_param;
internal MethodDef (MetaData md, string name, Param ret_param, Param [] pars)
: this (md, 0, 0, name, ret_param, pars)
{
}
internal MethodDef (MetaData md, MethAttr mAttrSet, ImplAttr iAttrSet, string name,
Param ret_param, Param [] pars)
: base (name)
{
methFlags = (ushort)mAttrSet;
implFlags = (ushort)iAttrSet;
this.ret_param = ret_param;
metaData = md;
parList = pars;
if (parList != null)
numPars = parList.Length;
tabIx = MDTable.Method;
}
internal Param[] GetPars()
{
return parList;
}
internal override uint GetSigIx(MetaData md)
{
MemoryStream sig = new MemoryStream();
TypeSig(sig);
return md.AddToBlobHeap(sig.ToArray());
}
public override void AddCallConv(CallConv cconv)
{
callConv |= cconv;
}
/// <summary>
/// Add some attributes to this method descriptor
/// </summary>
/// <param name="ma">the attributes to be added</param>
public void AddMethAttribute(MethAttr ma)
{
methFlags |= (ushort)ma;
}
/// <summary>
/// Add some implementation attributes to this method descriptor
/// </summary>
/// <param name="ia">the attributes to be added</param>
public void AddImplAttribute(ImplAttr ia)
{
implFlags |= (ushort)ia;
}
public void AddPInvokeInfo(ModuleRef scope, string methName,
PInvokeAttr callAttr) {
pinvokeImpl = new ImplMap((ushort)callAttr,this,methName,scope);
methFlags |= PInvokeImpl;
}
/// <summary>
/// Add a named generic type parameter
/// </summary>
public GenericParameter AddGenericParameter (short index, string name)
{
return AddGenericParameter (index, name, 0);
}
/// <summary>
/// Add a named generic type parameter with attributes
/// </summary>
public GenericParameter AddGenericParameter (short index, string name, GenericParamAttributes attr)
{
GenericParameter gp = new GenericParameter (this, metaData, index, name, attr);
metaData.AddToTable (MDTable.GenericParam, gp);
gen_param_count ++;
return gp;
}
/// <summary>
/// Set the maximum stack height for this method
/// </summary>
/// <param name="maxStack">the maximum height of the stack</param>
public void SetMaxStack(int maxStack)
{
this.maxStack = maxStack;
}
/// <summary>
/// Add local variables to this method
/// </summary>
/// <param name="locals">the locals to be added</param>
/// <param name="initLocals">are locals initialised to default values</param>
public void AddLocals(Local[] locals, bool initLocals)
{
this.locals = locals;
this.initLocals = initLocals;
}
/* Add Marshal info for return type */
public void AddRetTypeMarshallInfo (NativeType marshallType)
{
ret_param.AddMarshallInfo (marshallType);
}
/// <summary>
/// Mark this method as having an entry point
/// </summary>
public void DeclareEntryPoint()
{
entryPoint = true;
}
/// <summary>
/// Create a code buffer for this method to add the IL instructions to
/// </summary>
/// <returns>a buffer for this method's IL instructions</returns>
public CILInstructions CreateCodeBuffer()
{
code = new CILInstructions(metaData);
return code;
}
/// <summary>
/// Make a method reference descriptor for this method to be used
/// as a callsite signature for this vararg method
/// </summary>
/// <param name="optPars">the optional pars for the vararg method call</param>
/// <returns></returns>
public MethodRef MakeVarArgSignature(Type[] optPars)
{
Type[] pars = new Type[numPars];
MethodRef varArgSig;
for (int i=0; i < numPars; i++) {
pars[i] = parList[i].GetParType();
}
varArgSig = new MethodRef (this, name, ret_param.GetParType (), pars, true, optPars, 0);
if (varArgSigList == null)
varArgSigList = new ArrayList ();
varArgSigList.Add (varArgSig);
return varArgSig;
}
internal sealed override void TypeSig(MemoryStream sig)
{
sig.WriteByte((byte)callConv);
if ((callConv & CallConv.Generic) == CallConv.Generic)
MetaData.CompressNum ((uint) gen_param_count, sig);
MetaData.CompressNum((uint)numPars,sig);
ret_param.seqNo = 0;
ret_param.TypeSig (sig);
for (ushort i=0; i < numPars; i++) {
parList[i].seqNo = (ushort)(i+1);
parList[i].TypeSig(sig);
}
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
if (pinvokeImpl != null) {
md.AddToTable(MDTable.ImplMap,pinvokeImpl);
pinvokeImpl.BuildTables(md);
}
if (entryPoint) md.SetEntryPoint(this);
uint locToken = 0;
if (locals != null) {
localSig = new LocalSig(locals);
md.AddToTable(MDTable.StandAloneSig,localSig);
localSig.BuildTables(md);
locToken = localSig.Token();
}
if (code != null) {
code.CheckCode(locToken,initLocals,maxStack);
textOffset = md.AddCode(code);
}
nameIx = md.AddToStringsHeap(name);
sigIx = GetSigIx(md);
parIx = md.TableIndex(MDTable.Param);
if (ret_param.HasMarshalInfo || ret_param.HasCustomAttr) {
md.AddToTable(MDTable.Param, ret_param);
ret_param.BuildTables(md);
}
for (int i=0; i < numPars; i++) {
md.AddToTable(MDTable.Param,parList[i]);
parList[i].BuildTables(md);
}
if (varArgSigList != null) {
foreach (MethodRef varArgSig in varArgSigList) {
md.AddToTable(MDTable.MemberRef,varArgSig);
varArgSig.BuildTables(md);
}
}
// Console.WriteLine("method has " + numPars + " parameters");
done = true;
}
internal sealed override uint Size(MetaData md)
{
return 8 + md.StringsIndexSize() + md.BlobIndexSize() + md.TableIndexSize(MDTable.Param);
}
internal sealed override void Write(FileImage output)
{
if (ZeroRva ()) output.Write(0);
else output.WriteCodeRVA(textOffset);
output.Write(implFlags);
output.Write(methFlags);
output.StringsIndex(nameIx);
output.BlobIndex(sigIx);
output.WriteIndex(MDTable.Param,parIx);
}
internal bool ZeroRva ()
{
return (((methFlags & (ushort)MethAttr.Abstract) != 0) ||
((implFlags & (ushort)ImplAttr.Runtime) != 0) ||
((implFlags & (ushort)ImplAttr.InternalCall) != 0) ||
(pinvokeImpl != null)); // TODO: Not entirely true but works for now
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 0;
case (CIx.HasDeclSecurity) : return 1;
case (CIx.MemberRefParent) : return 3;
case (CIx.MethodDefOrRef) : return 0;
case (CIx.MemberForwarded) : return 1;
case (CIx.CustomAttributeType) : return 2;
case (CIx.TypeOrMethodDef) : return 1;
}
return 0;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a method defined in another assembly/module
/// </summary>
public class MethodRef : Method {
private static readonly byte Sentinel = 0x41;
Type[] parList, optParList;
MetaDataElement parent;
uint numPars = 0, numOptPars = 0;
CallConv callConv = CallConv.Default;
Type retType;
int gen_param_count;
internal MethodRef(MetaDataElement paren, string name, Type retType,
Type[] pars, bool varArgMeth, Type[] optPars, int gen_param_count) : base(name)
{
parent = paren;
parList = pars;
this.retType = retType;
if (parList != null) numPars = (uint)parList.Length;
if (varArgMeth) {
optParList = optPars;
if (optParList != null) numOptPars = (uint)optParList.Length;
callConv = CallConv.Vararg;
}
this.gen_param_count = gen_param_count;
}
internal override uint GetSigIx(MetaData md)
{
MemoryStream sig = new MemoryStream();
TypeSig(sig);
return md.AddToBlobHeap(sig.ToArray());
}
public override void AddCallConv(CallConv cconv)
{
callConv |= cconv;
}
internal sealed override void TypeSig(MemoryStream sig)
{
sig.WriteByte((byte)callConv);
if ((callConv & CallConv.Generic) == CallConv.Generic)
MetaData.CompressNum ((uint) gen_param_count, sig);
MetaData.CompressNum(numPars+numOptPars,sig);
retType.TypeSig(sig);
for (int i=0; i < numPars; i++) {
parList[i].TypeSig(sig);
}
if (numOptPars > 0) {
sig.WriteByte(Sentinel);
for (int i=0; i < numOptPars; i++) {
optParList[i].TypeSig(sig);
}
}
}
internal sealed override void BuildTables(MetaData md)
{
if (done) return;
nameIx = md.AddToStringsHeap(name);
sigIx = GetSigIx(md);
done = true;
}
internal sealed override uint Size(MetaData md)
{
return md.CodedIndexSize(CIx.MemberRefParent) + md.StringsIndexSize() + md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.WriteCodedIndex(CIx.MemberRefParent,parent);
output.StringsIndex(nameIx);
output.BlobIndex(sigIx);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.HasCustomAttr) : return 6;
case (CIx.MethodDefOrRef) : return 1;
case (CIx.CustomAttributeType) : return 3;
}
return 0;
}
}
/**************************************************************************/
/// <summary>
/// Descriptors for native types used for marshalling
/// </summary>
public class NativeType {
public static readonly NativeType Void = new NativeType(0x01);
public static readonly NativeType Boolean = new NativeType(0x02);
public static readonly NativeType Int8 = new NativeType(0x03);
public static readonly NativeType UInt8 = new NativeType(0x04);
public static readonly NativeType Int16 = new NativeType(0x05);
public static readonly NativeType UInt16 = new NativeType(0x06);
public static readonly NativeType Int32 = new NativeType(0x07);
public static readonly NativeType UInt32 = new NativeType(0x08);
public static readonly NativeType Int64 = new NativeType(0x09);
public static readonly NativeType UInt64 = new NativeType(0x0A);
public static readonly NativeType Float32 = new NativeType(0x0B);
public static readonly NativeType Float64 = new NativeType(0x0C);
public static readonly NativeType Currency = new NativeType(0x0F);
public static readonly NativeType BStr = new NativeType(0x13);
public static readonly NativeType LPStr = new NativeType(0x14);
public static readonly NativeType LPWStr = new NativeType(0x15);
public static readonly NativeType LPTStr = new NativeType(0x16);
public static readonly NativeType FixedSysString = new NativeType(0x17);
public static readonly NativeType IUnknown = new NativeType(0x19);
public static readonly NativeType IDispatch = new NativeType(0x1A);
public static readonly NativeType Struct = new NativeType(0x1B);
public static readonly NativeType Interface = new NativeType(0x1C);
public static readonly NativeType Int = new NativeType(0x1F);
public static readonly NativeType UInt = new NativeType(0x20);
public static readonly NativeType ByValStr = new NativeType(0x22);
public static readonly NativeType AnsiBStr = new NativeType(0x23);
public static readonly NativeType TBstr = new NativeType(0x24);
public static readonly NativeType VariantBool = new NativeType(0x25);
public static readonly NativeType FuncPtr = new NativeType(0x26);
public static readonly NativeType AsAny = new NativeType(0x28);
public static readonly NativeType LPStruct = new NativeType(0x2b);
public static readonly NativeType Error = new NativeType(0x2d);
protected byte typeIndex;
internal NativeType(byte tyIx) { typeIndex = tyIx; }
internal byte GetTypeIndex() { return typeIndex; }
internal virtual byte[] ToBlob()
{
byte[] bytes = new byte[1];
bytes[0] = GetTypeIndex();
return bytes;
}
}
public class FixedSysString : NativeType {
uint size;
public FixedSysString (uint size) : base (NativeType.FixedSysString.GetTypeIndex ())
{
this.size = size;
}
internal override byte [] ToBlob ()
{
MemoryStream str = new MemoryStream ();
str.WriteByte (GetTypeIndex ());
MetaData.CompressNum (size, str);
return str.ToArray ();
}
}
public class NativeArray : NativeType {
NativeType elemType;
int numElem = -1, parNum = -1, elemMult = -1;
public NativeArray(NativeType elemType) : this (elemType, -1, -1, -1)
{
this.elemType = elemType;
}
/* public NativeArray(NativeType elemType, int len) : base(0x2A) {
this.elemType = elemType;
this.len = len;
}
*/
public NativeArray(NativeType elemType, int numElem, int parNumForLen, int elemMult) : base(0x2A)
{
this.elemType = elemType;
this.numElem = numElem;
parNum = parNumForLen;
this.elemMult = elemMult;
}
public NativeArray(NativeType elemType, int numElem, int parNumForLen)
: this (elemType, numElem, parNumForLen, -1)
{
}
internal override byte[] ToBlob()
{
MemoryStream str = new MemoryStream();
str.WriteByte(GetTypeIndex());
if (elemType == null) str.WriteByte(0x50); // no info (MAX)
else str.WriteByte(elemType.GetTypeIndex());
/* see : mono/metadata/metadata.c:mono_metadata_parse_marshal_spec
* LAMESPEC: Older spec versions say elemMult comes before
* len. Newer spec versions don't talk about elemMult at
* all, but csc still emits it, and it is used to distinguish
* between parNum being 0, and parNum being omitted.
*/
if (parNum == -1)
// <native_type> []
return str.ToArray ();
MetaData.CompressNum((uint) parNum,str);
if (numElem != -1) {
MetaData.CompressNum ((uint) numElem, str);
if (elemMult != -1)
// <native_type> [ int32 ]
MetaData.CompressNum((uint) elemMult,str);
//else <native_type> [ int32 + int32 ]
} else if (elemMult != -1) {
// When can this occur ?
MetaData.CompressNum (0, str);
MetaData.CompressNum((uint) elemMult,str);
}
//else <native_type> [ + int32 ]
return str.ToArray();
}
}
public class SafeArray : NativeType {
SafeArrayType elemType;
bool hasElemType;
public SafeArray() : base(0x1D)
{
}
public SafeArray(SafeArrayType elemType) : base(0x1D)
{
this.elemType = elemType;
hasElemType = true;
}
internal override byte[] ToBlob()
{
byte[] bytes = new byte[hasElemType ? 2 : 1];
bytes[0] = GetTypeIndex();
if (hasElemType)
bytes[1] = (byte)elemType;
return bytes;
}
}
public class FixedArray : NativeType {
uint numElem;
//public FixedArray(NativeType elemType, int numElems) : base(0x1E) {
public FixedArray(int numElems) : base(0x1E)
{
//this.elemType = elemType;
numElem = (uint)numElems;
}
internal override byte[] ToBlob()
{
MemoryStream str = new MemoryStream();
str.WriteByte(GetTypeIndex());
MetaData.CompressNum(numElem,str);
/* FIXME:
fixed array [5] lpstr [2]
This format is not supported by ilasm 1.1.4322.2032,
but is supported by 2.0.5125..
ilasm 1.1 only supports "fixed array [5]"
if (elemType == null) str.WriteByte(0x50); // no info (MAX)
else str.WriteByte(elemType.GetTypeIndex());*/
return str.ToArray();
}
}
public class CustomMarshaller : NativeType {
string typeName;
string marshallerName;
string cookie;
public CustomMarshaller(string typeNameOrGUID, string marshallerName,
string optCookie) : base(0x2C)
{
typeName = typeNameOrGUID;
this.marshallerName = marshallerName;
cookie = optCookie;
}
public CustomMarshaller(string marshallerName, string optCookie)
:this (null, marshallerName, optCookie)
{
}
internal override byte[] ToBlob()
{
MemoryStream str = new MemoryStream();
BinaryWriter bw = new BinaryWriter(str,new UTF8Encoding());
bw.Write(GetTypeIndex());
//Native type name & unmanaged type - unused
//See mono/metadata/metadata.c : mono_metadata_parse_marshal_spec
bw.Write ((byte) 0); // Native Type name, unused
bw.Write ((byte) 0); // Unmanaged type, unused
if (marshallerName != null) {
MetaData.CompressNum ((uint)marshallerName.Length, str);
bw.Write(marshallerName.ToCharArray());
} else {
bw.Write ((byte) 0);
}
if (cookie != null) {
MetaData.CompressNum ((uint)cookie.Length, str);
bw.Write(cookie.ToCharArray());
} else {
bw.Write ((byte) 0);
}
bw.Flush();
return str.ToArray();
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for the Primitive types defined in IL
/// </summary>
public class PrimitiveType : Type {
private string name;
private int systemTypeIndex;
public static int NumSystemTypes = 18;
public static readonly PrimitiveType Void = new PrimitiveType(0x01,"Void",0);
public static readonly PrimitiveType Boolean = new PrimitiveType(0x02,"Boolean",1);
public static readonly PrimitiveType Char = new PrimitiveType(0x03,"Char",2);
public static readonly PrimitiveType Int8 = new PrimitiveType(0x04,"SByte",3);
public static readonly PrimitiveType UInt8 = new PrimitiveType(0x05,"Byte",4);
public static readonly PrimitiveType Int16 = new PrimitiveType(0x06,"Int16",5);
public static readonly PrimitiveType UInt16 = new PrimitiveType(0x07,"UInt16",6);
public static readonly PrimitiveType Int32 = new PrimitiveType(0x08,"Int32",7);
public static readonly PrimitiveType UInt32 = new PrimitiveType(0x09,"UInt32",8);
public static readonly PrimitiveType Int64 = new PrimitiveType(0x0A,"Int64",9);
public static readonly PrimitiveType UInt64 = new PrimitiveType(0x0B,"UInt64",10);
public static readonly PrimitiveType Float32 = new PrimitiveType(0x0C,"Single",11);
public static readonly PrimitiveType Float64 = new PrimitiveType(0x0D,"Double",12);
public static readonly PrimitiveType String = new PrimitiveType(0x0E,"String",13);
internal static readonly PrimitiveType Class = new PrimitiveType(0x12);
internal static readonly PrimitiveType Var = new PrimitiveType(0x13);
internal static readonly PrimitiveType GenericInst = new PrimitiveType(0x15);
public static readonly PrimitiveType TypedRef = new PrimitiveType(0x16,"TypedReference",14);
public static readonly PrimitiveType IntPtr = new PrimitiveType(0x18,"IntPtr",15);
public static readonly PrimitiveType UIntPtr = new PrimitiveType(0x19,"UIntPtr",16);
public static readonly PrimitiveType Object = new PrimitiveType(0x1C,"Object",17);
internal static readonly PrimitiveType ClassType = new PrimitiveType(0x50);
internal static readonly PrimitiveType SZArray = new PrimitiveType(0x1D);
internal static readonly PrimitiveType MVar = new PrimitiveType(0x1E);
internal static readonly PrimitiveType ValueType = new PrimitiveType(0x11, "ValueType", 18);
public static readonly PrimitiveType NativeInt = IntPtr;
public static readonly PrimitiveType NativeUInt = UIntPtr;
internal PrimitiveType(byte typeIx) : base(typeIx) { }
internal PrimitiveType(byte typeIx, string name, int STIx) : base(typeIx)
{
this.name = name;
this.systemTypeIndex = STIx;
}
internal string GetName() { return name; }
internal int GetSystemTypeIx() { return systemTypeIndex; }
internal sealed override void TypeSig(MemoryStream str)
{
str.WriteByte(typeIndex);
}
internal override MetaDataElement GetTypeSpec(MetaData md)
{
TypeSpec tS = md.GetPrimitiveTypeSpec(systemTypeIndex);
if (tS == null) {
tS = new TypeSpec(this,md);
md.SetPrimitiveTypeSpec(systemTypeIndex,tS);
md.AddToTable(MDTable.TypeSpec,tS);
}
return tS;
}
}
public class PrimitiveTypeRef : Type
{
PrimitiveType type;
MetaData metaData;
internal PrimitiveTypeRef(PrimitiveType type, MetaData md)
: base (0)
{
this.type = type;
this.metaData = md;
}
internal uint TypeDefOrRefToken()
{
uint cIx = type.GetTypeSpec (metaData).Row;
cIx = (cIx << 2) | 0x2;
return cIx;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for an pointer (type * or type &)
/// </summary>
public abstract class PtrType : Type {
Type baseType;
internal PtrType(Type bType, byte typeIx) : base(typeIx)
{
baseType = bType;
tabIx = MDTable.TypeSpec;
}
internal sealed override void TypeSig(MemoryStream str)
{
str.WriteByte(typeIndex);
baseType.TypeSig(str);
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a managed pointer (type & or byref)
/// </summary>
public class ManagedPointer : PtrType {
/// <summary>
/// Create new managed pointer to baseType
/// </summary>
/// <param name="bType">the base type of the pointer</param>
public ManagedPointer(Type baseType) : base(baseType,0x10) { }
}
/**************************************************************************/
/// <summary>
/// Descriptor for an unmanaged pointer (type *)
/// </summary>
public class UnmanagedPointer : PtrType {
/// <summary>
/// Create a new unmanaged pointer to baseType
/// </summary>
/// <param name="baseType">the base type of the pointer</param>
public UnmanagedPointer(Type baseType) : base(baseType, 0x0F) { }
}
/**************************************************************************/
public interface IExternRef {
ClassRef AddClass(string nsName, string name);
ClassRef AddValueClass(string nsName, string name);
}
/// <summary>
/// A reference to an external assembly (.assembly extern)
/// </summary>
public class AssemblyRef : ResolutionScope, IExternRef {
private ushort major, minor, build, revision;
uint flags, keyIx, hashIx, cultIx;
bool hasVersion = false, isKeyToken = false;
byte[] keyBytes;
string culture;
internal AssemblyRef(MetaData md, string name) : base(name,md)
{
tabIx = MDTable.AssemblyRef;
}
public void AddAssemblyAttr (AssemAttr aa)
{
flags |= (uint)aa;
}
/// <summary>
/// Add version information about this external assembly
/// </summary>
/// <param name="majVer">Major Version</param>
/// <param name="minVer">Minor Version</param>
/// <param name="bldNo">Build Number</param>
/// <param name="revNo">Revision Number</param>
public void AddVersionInfo(int majVer, int minVer, int bldNo, int revNo)
{
major = (ushort)majVer;
minor = (ushort)minVer;
build = (ushort)bldNo;
revision = (ushort)revNo;
hasVersion = true;
}
/// <summary>
/// Add the hash value for this external assembly
/// </summary>
/// <param name="hash">bytes of the hash value</param>
public void AddHash(byte[] hash)
{
hashIx = metaData.AddToBlobHeap(hash);
}
/// <summary>
/// Set the culture for this external assembly
/// </summary>
/// <param name="cult">the culture string</param>
public void AddCulture(string cult)
{
cultIx = metaData.AddToStringsHeap(cult);
culture = cult;
}
/// <summary>
/// Add the full public key for this external assembly
/// </summary>
/// <param name="key">bytes of the public key</param>
public void AddKey(byte[] key)
{
flags |= 0x0001; // full public key
keyBytes = key;
keyIx = metaData.AddToBlobHeap(key);
}
/// <summary>
/// Add the public key token (low 8 bytes of the public key)
/// </summary>
/// <param name="key">low 8 bytes of public key</param>
public void AddKeyToken(byte[] key)
{
keyIx = metaData.AddToBlobHeap(key);
keyBytes = key;
isKeyToken = true;
}
/// <summary>
/// Add a class to this external assembly
/// </summary>
/// <param name="nsName">name space name</param>
/// <param name="name">class name</param>
/// <returns></returns>
public virtual ClassRef AddClass(string nsName, string name)
{
ClassRef aClass = new ClassRef(nsName,name,metaData);
metaData.AddToTable(MDTable.TypeRef,aClass);
aClass.SetParent(this);
return aClass;
}
/// <summary>
/// Add a value class to this external assembly
/// </summary>
/// <param name="nsName">name space name</param>
/// <param name="name">class name</param>
/// <returns></returns>
public virtual ClassRef AddValueClass(string nsName, string name)
{
ClassRef aClass = new ClassRef(nsName,name,metaData);
metaData.AddToTable(MDTable.TypeRef,aClass);
aClass.SetParent(this);
aClass.MakeValueClass(ValueClass.ValueType);
return aClass;
}
internal string TypeName()
{
string result = name;
if (hasVersion)
result = result + ", Version=" + major + "." + minor + "." +
build + "." + revision;
if (keyBytes != null) {
string tokenStr = "=";
if (isKeyToken) tokenStr = "Token=";
result = result + ", PublicKey" + tokenStr;
for (int i=0; i < keyBytes.Length; i++) {
result = result + Hex.Byte(keyBytes[i]);
}
}
if (culture != null)
result = result + ", Culture=" + culture;
return result;
}
internal sealed override uint Size(MetaData md)
{
return 12 + 2 * md.StringsIndexSize() + 2 * md.BlobIndexSize();
}
internal sealed override void Write(FileImage output)
{
output.Write(major);
output.Write(minor);
output.Write(build);
output.Write(revision);
output.Write(flags);
output.BlobIndex(keyIx);
output.StringsIndex(nameIx);
output.StringsIndex(cultIx);
output.BlobIndex(hashIx);
}
internal sealed override uint GetCodedIx(CIx code)
{
switch (code) {
case (CIx.ResolutionScope) : return 2;
case (CIx.HasCustomAttr) : return 15;
case (CIx.Implementation) : return 1;
}
return 0;
}
}
/**************************************************************************/
/// <summary>
/// Descriptor for a class defined in System (mscorlib)
/// </summary>
internal class SystemClass : ClassRef {
PrimitiveType elemType;
internal SystemClass(PrimitiveType eType, AssemblyRef paren, MetaData md)
: base("System",eType.GetName(),md) {
elemType = eType;
parent = paren;
}
internal override sealed MetaDataElement GetTypeSpec(MetaData md)
{
if (typeSpec == null) typeSpec = (TypeSpec)elemType.GetTypeSpec(md);
return typeSpec;
}
internal sealed override void TypeSig(MemoryStream str)
{
str.WriteByte(elemType.GetTypeIndex());
}
}
/**************************************************************************/
/// <summary>
/// The assembly for mscorlib.
/// </summary>
public sealed class MSCorLib : AssemblyRef {
private static readonly int valueTypeIx = 18;
private readonly string systemName = "System";
private Class[] systemClasses = new Class[valueTypeIx+2];
private PrimitiveType[] systemTypes = new PrimitiveType[valueTypeIx];
private static int[] specialNames = {
PrimitiveType.Void.GetName().GetHashCode(),
PrimitiveType.Boolean.GetName().GetHashCode(),
PrimitiveType.Char.GetName().GetHashCode(),
PrimitiveType.Int8.GetName().GetHashCode(),
PrimitiveType.UInt8.GetName().GetHashCode(),
PrimitiveType.Int16.GetName().GetHashCode(),
PrimitiveType.UInt16.GetName().GetHashCode(),
PrimitiveType.Int32.GetName().GetHashCode(),
PrimitiveType.UInt32.GetName().GetHashCode(),
PrimitiveType.Int64.GetName().GetHashCode(),
PrimitiveType.UInt64.GetName().GetHashCode(),
PrimitiveType.Float32.GetName().GetHashCode(),
PrimitiveType.Float64.GetName().GetHashCode(),
PrimitiveType.String.GetName().GetHashCode(),
PrimitiveType.TypedRef.GetName().GetHashCode(),
PrimitiveType.IntPtr.GetName().GetHashCode(),
PrimitiveType.UIntPtr.GetName().GetHashCode(),
PrimitiveType.Object.GetName().GetHashCode(),
PrimitiveType.ValueType.GetName ().GetHashCode(),
"Enum".GetHashCode()
};
internal MSCorLib(MetaData md) : base(md,"mscorlib")
{
if (!PEFile.IsMSCorlib)
md.AddToTable(MDTable.AssemblyRef,this);
systemTypes[PrimitiveType.Void.GetSystemTypeIx()] = PrimitiveType.Void;
systemTypes[PrimitiveType.Boolean.GetSystemTypeIx()] = PrimitiveType.Boolean;
systemTypes[PrimitiveType.Char.GetSystemTypeIx()] = PrimitiveType.Char;
systemTypes[PrimitiveType.Int8.GetSystemTypeIx()] = PrimitiveType.Int8;
systemTypes[PrimitiveType.UInt8.GetSystemTypeIx()] = PrimitiveType.UInt8;
systemTypes[PrimitiveType.Int16.GetSystemTypeIx()] = PrimitiveType.Int16;
systemTypes[PrimitiveType.UInt16.GetSystemTypeIx()] = PrimitiveType.UInt16;
systemTypes[PrimitiveType.Int32.GetSystemTypeIx()] = PrimitiveType.Int32;
systemTypes[PrimitiveType.UInt32.GetSystemTypeIx()] = PrimitiveType.UInt32;
systemTypes[PrimitiveType.Int64.GetSystemTypeIx()] = PrimitiveType.Int64;
systemTypes[PrimitiveType.UInt64.GetSystemTypeIx()] = PrimitiveType.UInt64;
systemTypes[PrimitiveType.Float32.GetSystemTypeIx()] = PrimitiveType.Float32;
systemTypes[PrimitiveType.Float64.GetSystemTypeIx()] = PrimitiveType.Float64;
systemTypes[PrimitiveType.IntPtr.GetSystemTypeIx()] = PrimitiveType.IntPtr;
systemTypes[PrimitiveType.UIntPtr.GetSystemTypeIx()] = PrimitiveType.UIntPtr;
systemTypes[PrimitiveType.String.GetSystemTypeIx()] = PrimitiveType.String;
systemTypes[PrimitiveType.Object.GetSystemTypeIx()] = PrimitiveType.Object;
systemTypes[PrimitiveType.TypedRef.GetSystemTypeIx()] = PrimitiveType.TypedRef;
}
/// <summary>
/// Add a class to the mscorlib assembly
/// </summary>
/// <param name="nsName">name space name</param>
/// <param name="name">class name</param>
/// <returns></returns>
public override ClassRef AddClass(string nsName, string name)
{
/* This gets called by !mscorlib, for adding references INTO mscorlib, so
it should be returning ClassRef ..*/
Class aClass = GetSpecialClass(nsName,name);
if (aClass == null) {
aClass = new ClassRef(nsName,name,metaData);
metaData.AddToTable(MDTable.TypeRef,aClass);
if (aClass is ClassRef)
((ClassRef) aClass).SetParent(this);
}
//FIXME: Check for !ClassRef here?
return (ClassRef) aClass;
}
private Class GetSpecialClass(string nsName,string name)
{
if (nsName.CompareTo(systemName) != 0) return null;
int hash = name.GetHashCode();
for (int i=0; i < specialNames.Length; i++) {
if (hash != specialNames[i])
continue;
if (systemClasses[i] == null) {
if (i < valueTypeIx) {
systemClasses[i] = new SystemClass(systemTypes[i],this,metaData);
if ((systemTypes[i] != PrimitiveType.Object) &&
(systemTypes[i] != PrimitiveType.String)) {
systemClasses[i].MakeValueClass(ValueClass.ValueType);
}
} else {
systemClasses[i] = new ClassRef(nsName,name,metaData);
((ClassRef) systemClasses[i]).SetParent(this);
if (!ClassDef.IsValueType (nsName, name) && !ClassDef.IsEnum (nsName, name))
systemClasses[i].MakeValueClass(ValueClass.ValueType);
}
metaData.AddToTable(MDTable.TypeRef,systemClasses[i]);
}
return systemClasses[i];
}
return null;
}
internal void SetSpecialSystemClass (string nsName, string name, Class aClass)
{
if (nsName != systemName) return;
int hash = name.GetHashCode ();
for (int i = 0; i < specialNames.Length; i++) {
if (hash != specialNames [i])
continue;
if (systemClasses [i] == null) {
systemClasses [i] = aClass;
}
}
}
internal Class GetSpecialSystemClass(PrimitiveType pType)
{
int ix = pType.GetSystemTypeIx();
if (systemClasses[ix] == null && !PEFile.IsMSCorlib) {
systemClasses[ix] = new SystemClass(pType,this,metaData);
metaData.AddToTable(MDTable.TypeRef,systemClasses[ix]);
}
return systemClasses[ix];
}
private ClassRef GetValueClass(string name, int hash)
{
/* Called by MSCorLib.AddValueClass, which is called by
!mscorlib, for adding ref to value class INTO mscorlib,
so this should be classref */
int ix = valueTypeIx;
if (hash != specialNames[valueTypeIx]) ix++;
if (systemClasses[ix] == null) {
systemClasses[ix] = new ClassRef(systemName,name,metaData);
((ClassRef) systemClasses[ix]).SetParent(this);
((ClassRef) systemClasses[ix]).MakeValueClass(ValueClass.ValueType);
metaData.AddToTable(MDTable.TypeRef,systemClasses[ix]);
}
return (ClassRef) systemClasses[ix];
}
internal Class ValueType()
{
if (systemClasses[valueTypeIx] == null && !PEFile.IsMSCorlib) {
ClassRef valType = new ClassRef("System","ValueType",metaData);
valType.SetParent(this);
valType.MakeValueClass(ValueClass.ValueType);
metaData.AddToTable(MDTable.TypeRef,valType);
systemClasses[valueTypeIx] = valType;
}
return systemClasses[valueTypeIx];
}
internal Class EnumType()
{
/* Called by both mscorlib & !mscorlib, so can be
either ClassRef or ClassDef */
//systemClasses [ valueTypeIx + 1] -> System.Enum
if (systemClasses[valueTypeIx + 1] == null && !PEFile.IsMSCorlib) {
ClassRef valType = new ClassRef("System","Enum",metaData);
valType.SetParent(this);
valType.MakeValueClass(ValueClass.Enum);
metaData.AddToTable(MDTable.TypeRef,valType);
systemClasses[valueTypeIx + 1] = valType;
}
return systemClasses[valueTypeIx + 1];
}
/// <summary>
/// Add a value class to this external assembly
/// </summary>
/// <param name="nsName">name space name</param>
/// <param name="name">class name</param>
/// <returns></returns>
public override ClassRef AddValueClass(string nsName, string name)
{
if (nsName.CompareTo(systemName) == 0) {
int hash = name.GetHashCode();
if ((hash == specialNames[valueTypeIx]) ||
(hash == specialNames[valueTypeIx+1])) {
return GetValueClass(name,hash);
}
}
ClassRef aClass = new ClassRef(nsName,name,metaData);
metaData.AddToTable(MDTable.TypeRef,aClass);
aClass.SetParent(this);
aClass.MakeValueClass(ValueClass.ValueType);
return aClass;
}
}
/**************************************************************************/
/// <summary>
/// MetaData
/// Root (20 bytes + UTF-8 Version String + quad align padding)
/// StreamHeaders (8 bytes + null terminated name string + quad align padding)
/// Streams
/// #~ (always present - holds metadata tables)
/// #Strings (always present - holds identifier strings)
/// #US (Userstring heap)
/// #Blob (signature blobs)
/// #GUID (guids for assemblies or Modules)
/// </summary>
public class MetaData {
internal static readonly int[] CIxShiftMap = {2,2,5,1,2,3,1,1,1,2,3,2,1};
private static readonly byte StringsHeapMask = 0x1;
private static readonly byte GUIDHeapMask = 0x2;
private static readonly byte BlobHeapMask = 0x4;
private static readonly uint MetaDataSignature = 0x424A5342;
private static readonly uint maxSmlIxSize = 0xFFFF;
private static readonly uint max1BitSmlIx = 0x7FFF;
private static readonly uint max2BitSmlIx = 0x3FFF;
private static readonly uint max3BitSmlIx = 0x1FFF;
private static readonly uint max5BitSmlIx = 0x7FF;
// NOTE: version and stream name strings MUST always be quad padded
private static readonly string version = "v4.0.30319\0\0";
private static readonly char[] tildeName = {'#','~','\0','\0'};
private static readonly char[] stringsName = {'#','S','t','r','i','n','g','s','\0','\0','\0','\0'};
private static readonly char[] usName = {'#','U','S','\0'};
private static readonly char[] guidName = {'#','G','U','I','D','\0','\0','\0'};
private static readonly char[] blobName = {'#','B','l','o','b','\0','\0','\0'};
private static readonly uint MetaDataHeaderSize = 20 + (uint)version.Length;
private static readonly uint TildeHeaderSize = 24;
private static readonly uint StreamHeaderSize = 8;
private static readonly uint numMetaDataTables = (int)MDTable.GenericParamConstraint + 1;
MetaDataStream strings, us, guid, blob;
MetaDataStream[] streams = new MetaDataStream[5];
uint numStreams = 5;
uint tildeTide = 0, tildePadding = 0, tildeStart = 0;
uint numTables = 0, resourcesSize = 0;
ArrayList[] metaDataTables = new ArrayList[numMetaDataTables];
ArrayList byteCodes = new ArrayList();
uint codeSize = 0, codeStart, byteCodePadding = 0, metaDataSize = 0;
ulong valid = 0, /*sorted = 0x000002003301FA00;*/ sorted = 0;
bool[] largeIx = new bool[numMetaDataTables];
bool[] lgeCIx = new bool[(int)CIx.MaxCIx];
bool largeStrings = false, largeUS = false, largeGUID = false, largeBlob = false;
private FileImage file;
private byte heapSizes = 0;
MetaDataElement entryPoint;
BinaryWriter output;
MSCorLib _mscorlib;
private TypeSpec[] systemTypeSpecs = new TypeSpec[PrimitiveType.NumSystemTypes];
long mdStart;
private ArrayList cattr_list;
private ArrayList declsec_list;
ArrayList resources;
internal MetaData(FileImage file)
{
// tilde = new MetaDataStream(tildeName,false,0);
this.file = file;
strings = new MetaDataStream(stringsName,new UTF8Encoding(),true);
us = new MetaDataStream(usName,new UnicodeEncoding(),true);
guid = new MetaDataStream(guidName,false);
blob = new MetaDataStream(blobName,true);
streams[1] = strings;
streams[2] = us;
streams[3] = guid;
streams[4] = blob;
for (int i=0; i < numMetaDataTables; i++) {
largeIx[i] = false;
}
for (int i=0; i < lgeCIx.Length; i++) {
lgeCIx[i] = false;
}
}
public MSCorLib mscorlib {
get {
return _mscorlib ?? (_mscorlib = new MSCorLib (this));
}
}
internal TypeSpec GetPrimitiveTypeSpec(int ix)
{
return systemTypeSpecs[ix];
}
internal void SetPrimitiveTypeSpec(int ix, TypeSpec typeSpec)
{
systemTypeSpecs[ix] = typeSpec;
}
internal uint Size()
{
return metaDataSize;
}
private void CalcHeapSizes ()
{
if (strings.LargeIx()) {
largeStrings = true;
heapSizes |= StringsHeapMask;
}
if (guid.LargeIx()) {
largeGUID = true;
heapSizes |= GUIDHeapMask;
}
if (blob.LargeIx()) {
largeBlob = true;
heapSizes |= BlobHeapMask;
}
largeUS = us.LargeIx();
}
internal void StreamSize(byte mask)
{
heapSizes |= mask;
}
internal uint AddToUSHeap(string str)
{
if (str == null) return 0;
return us.Add(str,true);
}
internal uint AddToUSHeap(byte[] str)
{
if (str == null) return 0;
return us.Add (str, true);
}
internal uint AddToStringsHeap(string str)
{
if ((str == null) || (str.CompareTo("") == 0)) return 0;
return strings.Add(str,false);
}
internal uint AddToGUIDHeap(Guid guidNum)
{
return guid.Add(guidNum, false);
}
internal uint AddToBlobHeap(byte[] blobBytes)
{
if (blobBytes == null) return 0;
return blob.Add(blobBytes, true);
}
internal uint AddToBlobHeap(byte val)
{
return blob.Add(val, true);
}
internal uint AddToBlobHeap(sbyte val)
{
return blob.Add(val, true);
}
internal uint AddToBlobHeap(ushort val)
{
return blob.Add(val, true);
}
internal uint AddToBlobHeap(short val)
{
return blob.Add(val, true);
}
internal uint AddToBlobHeap(uint val)
{
return blob.Add(val, true);
}
internal uint AddToBlobHeap(int val)
{
return blob.Add(val, true);
}
internal uint AddToBlobHeap(ulong val)
{
return blob.Add(val, true);
}
internal uint AddToBlobHeap(long val)
{
return blob.Add(val, true);
}
internal uint AddToBlobHeap(float val)
{
return blob.Add(val, true);
}
internal uint AddToBlobHeap(double val)
{
return blob.Add(val, true);
}
internal uint AddToBlobHeap(string val)
{
return blob.Add(val,true);
}
internal void AddCustomAttribute (CustomAttribute cattr)
{
if (cattr_list == null)
cattr_list = new ArrayList ();
cattr_list.Add (cattr);
}
internal void AddDeclSecurity (BaseDeclSecurity decl_sec)
{
if (declsec_list == null)
declsec_list = new ArrayList ();
declsec_list.Add (decl_sec);
}
private ArrayList GetTable(MDTable tableIx)
{
int tabIx = (int)tableIx;
if (metaDataTables[tabIx] == null) {
metaDataTables[tabIx] = new ArrayList();
valid |= ((ulong)0x1 << tabIx);
// Console.WriteLine("after creating table " + tableIx + "(" + tabIx + ") valid = " + valid);
numTables++;
}
return metaDataTables[tabIx];
}
internal void AddToTable(MDTable tableIx, MetaDataElement elem)
{
if (elem.Row > 0) {
// Console.Out.WriteLine("ERROR - element already in table " + tableIx);
return;
}
// updates Row field of the element
// Console.WriteLine("Adding element to table " + (uint)tableIx);
ArrayList table = GetTable(tableIx);
elem.Row = (uint)table.Count + 1;
table.Add(elem);
}
internal uint TableIndex(MDTable tableIx)
{
if (metaDataTables[(int)tableIx] == null) return 1;
return (uint)metaDataTables[(int)tableIx].Count+1;
}
internal uint AddCode(CILInstructions byteCode)
{
byteCodes.Add(byteCode);
uint offset = codeSize + codeStart;
codeSize += byteCode.GetCodeSize();
return offset;
}
internal void SetEntryPoint(MetaDataElement ep)
{
entryPoint = ep;
}
internal uint AddResource(byte[] resBytes)
{
if (resources == null) resources = new ArrayList ();
resources.Add (resBytes);
uint offset = resourcesSize;
resourcesSize += (uint)resBytes.Length + 4;
return offset;
}
internal void AddData(DataConstant cVal)
{
file.AddInitData(cVal);
}
internal static void CompressNum(uint val, MemoryStream sig)
{
if (val <= 0x7F) {
sig.WriteByte((byte)val);
} else if (val <= 0x3FFF) {
byte b1 = (byte)((val >> 8) | 0x80);
byte b2 = (byte)(val & FileImage.iByteMask[0]);
sig.WriteByte(b1);
sig.WriteByte(b2);
} else {
byte b1 = (byte)((val >> 24) | 0xC0);
byte b2 = (byte)((val & FileImage.iByteMask[2]) >> 16);
byte b3 = (byte)((val & FileImage.iByteMask[1]) >> 8);;
byte b4 = (byte)(val & FileImage.iByteMask[0]);
sig.WriteByte(b1);
sig.WriteByte(b2);
sig.WriteByte(b3);
sig.WriteByte(b4);
}
}
internal uint CodeSize()
{
return codeSize + byteCodePadding;
}
internal uint GetResourcesSize()
{
return resourcesSize;
}
internal uint StringsIndexSize()
{
if (largeStrings) return 4;
return 2;
}
internal uint GUIDIndexSize()
{
if (largeGUID) return 4;
return 2;
}
internal uint USIndexSize()
{
if (largeUS) return 4;
return 2;
}
internal uint BlobIndexSize()
{
if (largeBlob) return 4;
return 2;
}
internal uint CodedIndexSize(CIx code)
{
if (lgeCIx[(uint)code]) return 4;
return 2;
}
internal uint TableIndexSize(MDTable tabIx)
{
if (largeIx[(uint)tabIx]) return 4;
return 2;
}
private void SetIndexSizes()
{
for (int i=0; i < numMetaDataTables; i++) {
if (metaDataTables[i] == null)
continue;
uint count = (uint)metaDataTables[i].Count;
if (count > maxSmlIxSize)
largeIx[i] = true;
MDTable tabIx = (MDTable)i;
if (count > max5BitSmlIx) {
if (tabIx == MDTable.Method || tabIx == MDTable.Field || tabIx == MDTable.TypeRef ||
tabIx == MDTable.TypeDef || tabIx == MDTable.Param || tabIx == MDTable.InterfaceImpl ||
tabIx == MDTable.MemberRef || tabIx == MDTable.Module || tabIx == MDTable.DeclSecurity ||
tabIx == MDTable.Property || tabIx == MDTable.Event || tabIx == MDTable.StandAloneSig ||
tabIx == MDTable.ModuleRef || tabIx == MDTable.TypeSpec || tabIx == MDTable.Assembly ||
tabIx == MDTable.AssemblyRef || tabIx == MDTable.File || tabIx == MDTable.ExportedType ||
tabIx == MDTable.ManifestResource || tabIx == MDTable.GenericParam)
lgeCIx[(int)CIx.HasCustomAttr] = true;
}
if (count > max3BitSmlIx) {
if (tabIx == MDTable.Method || tabIx == MDTable.MemberRef)
lgeCIx[(int)CIx.CustomAttributeType] = true;
if (tabIx == MDTable.TypeDef || tabIx == MDTable.TypeRef || tabIx == MDTable.ModuleRef ||
tabIx == MDTable.Method || tabIx == MDTable.TypeSpec)
lgeCIx[(int)CIx.MemberRefParent] = true;
}
if (count > max2BitSmlIx) {
if ((tabIx == MDTable.Field) || (tabIx == MDTable.Param) || (tabIx == MDTable.Property))
lgeCIx[(int)CIx.HasConst] = true;
if ((tabIx == MDTable.TypeDef) || (tabIx == MDTable.TypeRef) || (tabIx == MDTable.TypeSpec))
lgeCIx[(int)CIx.TypeDefOrRef] = true;
if ((tabIx == MDTable.TypeDef) || (tabIx == MDTable.Method) || (tabIx == MDTable.Assembly))
lgeCIx[(int)CIx.HasDeclSecurity] = true;
if ((tabIx == MDTable.File) || (tabIx == MDTable.AssemblyRef) || (tabIx == MDTable.ExportedType))
lgeCIx[(int)CIx.Implementation] = true;
if ((tabIx == MDTable.Module) || (tabIx == MDTable.ModuleRef) || (tabIx == MDTable.AssemblyRef) || (tabIx == MDTable.TypeRef))
lgeCIx[(int)CIx.ResolutionScope] = true;
}
if (count > max1BitSmlIx) {
if ((tabIx == MDTable.Field) || (tabIx == MDTable.Param))
lgeCIx[(int)CIx.HasFieldMarshal] = true;
if ((tabIx == MDTable.Event) || (tabIx == MDTable.Property))
lgeCIx[(int)CIx.HasSemantics] = true;
if ((tabIx == MDTable.Method) || (tabIx == MDTable.MemberRef))
lgeCIx[(int)CIx.MethodDefOrRef] = true;
if ((tabIx == MDTable.Field) || (tabIx == MDTable.Method))
lgeCIx[(int)CIx.MemberForwarded] = true;
if ((tabIx == MDTable.TypeDef) || (tabIx == MDTable.Method))
lgeCIx[(int)CIx.TypeOrMethodDef] = true;
}
}
}
private void SetStreamOffsets()
{
uint sizeOfHeaders = StreamHeaderSize + (uint)tildeName.Length;
for (int i=1; i < numStreams; i++) {
sizeOfHeaders += streams[i].headerSize();
}
metaDataSize = MetaDataHeaderSize + sizeOfHeaders;
tildeStart = metaDataSize;
metaDataSize += tildeTide + tildePadding;
for (int i=1; i < numStreams; i++) {
streams[i].Start = metaDataSize;
metaDataSize += streams[i].Size();
streams[i].WriteDetails();
}
}
internal void CalcTildeStreamSize()
{
CalcHeapSizes ();
//tilde.SetIndexSizes(strings.LargeIx(),us.LargeIx(),guid.LargeIx(),blob.LargeIx());
tildeTide = TildeHeaderSize;
tildeTide += 4 * numTables;
//Console.WriteLine("Tilde header + sizes = " + tildeTide);
for (int i=0; i < numMetaDataTables; i++) {
if (metaDataTables[i] != null) {
ArrayList table = metaDataTables[i];
// Console.WriteLine("Meta data table " + i + " at offset " + tildeTide);
tildeTide += (uint)table.Count * ((MetaDataElement)table[0]).Size(this);
// Console.WriteLine("Metadata table " + i + " has size " + table.Count);
// Console.WriteLine("tildeTide = " + tildeTide);
}
}
if ((tildeTide % 4) != 0) tildePadding = 4 - (tildeTide % 4);
//Console.WriteLine("tildePadding = " + tildePadding);
}
internal void WriteTildeStream(FileImage output)
{
output.Seek(0,SeekOrigin.Current);
output.Write((uint)0); // Reserved
output.Write((byte)2); // MajorVersion
output.Write((byte)0); // MinorVersion
output.Write(heapSizes);
output.Write((byte)1); // Reserved
output.Write(valid);
output.Write(sorted);
for (int i=0; i < numMetaDataTables; i++) {
if (metaDataTables[i] != null) {
uint count = (uint)metaDataTables[i].Count;
output.Write(count);
}
}
output.Seek(0,SeekOrigin.Current);
// Console.WriteLine("Starting metaData tables at " + tabStart);
for (int i=0; i < numMetaDataTables; i++) {
if (metaDataTables[i] != null) {
// Console.WriteLine("Starting metaData table " + i + " at " + (output.Seek(0,SeekOrigin.Current) - startTilde));
ArrayList table = metaDataTables[i];
for (int j=0; j < table.Count; j++) {
((MetaDataElement)table[j]).Write(output);
}
}
}
// Console.WriteLine("Writing padding at " + output.Seek(0,SeekOrigin.Current));
for (int i=0; i < tildePadding; i++) output.Write((byte)0);
}
private void BuildTable(ArrayList table)
{
if (table == null) return;
for (int j=0; j < table.Count; j++) {
((MetaDataElement)table[j]).BuildTables(this);
}
}
private void SortTable (ArrayList mTable)
{
if (mTable == null) return;
mTable.Sort();
for (int i=0; i < mTable.Count; i++) {
((MetaDataElement)mTable[i]).Row = (uint)i+1;
}
}
internal void BuildMetaData(uint codeStartOffset)
{
codeStart = codeStartOffset;
BuildTable(metaDataTables[(int)MDTable.TypeDef]);
BuildTable(metaDataTables[(int)MDTable.TypeSpec]);
BuildTable(metaDataTables[(int)MDTable.MemberRef]);
BuildTable(metaDataTables[(int)MDTable.GenericParam]);
BuildTable(metaDataTables[(int)MDTable.MethodSpec]);
BuildTable(metaDataTables[(int)MDTable.GenericParamConstraint]);
BuildTable(metaDataTables[(int)MDTable.ManifestResource]);
if (cattr_list != null) {
foreach (CustomAttribute cattr in cattr_list)
cattr.BuildTables (this);
}
if (declsec_list != null) {
foreach (BaseDeclSecurity decl_sec in declsec_list)
decl_sec.BuildTables (this);
}
/* for (int i=0; i < metaDataTables.Length; i++) {
ArrayList table = metaDataTables[i];
if (table != null) {
for (int j=0; j < table.Count; j++) {
((MetaDataElement)table[j]).BuildTables(this);
}
}
}
*/
SetIndexSizes();
for (int i=1; i < numStreams; i++) {
streams[i].EndStream();
}
CalcTildeStreamSize();
SetStreamOffsets();
byteCodePadding = NumToAlign(codeSize,4);
if (entryPoint != null) file.SetEntryPoint(entryPoint.Token());
// Check ordering of specific tables
// Constant, CustomAttribute, FieldMarshal, DeclSecurity, MethodSemantics
// ImplMap, GenericParam
// Need to load GenericParamConstraint AFTER GenericParam table in correct order
// The tables:
// InterfaceImpl, ClassLayout, FieldLayout, MethodImpl, FieldRVA, NestedClass
// will _ALWAYS_ be in the correct order as embedded in BuildMDTables
SortTable(metaDataTables[(int)MDTable.Constant]);
SortTable(metaDataTables[(int)MDTable.FieldMarshal]);
SortTable(metaDataTables[(int)MDTable.DeclSecurity]);
SortTable(metaDataTables[(int)MDTable.MethodSemantics]);
SortTable(metaDataTables[(int)MDTable.MethodImpl]);
SortTable(metaDataTables[(int)MDTable.ImplMap]);
if (metaDataTables[(int)MDTable.GenericParam] != null) {
SortTable(metaDataTables[(int)MDTable.GenericParam]);
// Now add GenericParamConstraints
/*for (int i=0; i < metaDataTables[(int)MDTable.GenericParam].Count; i++) {
((GenericParameter)metaDataTables[(int)MDTable.GenericParam][i]).AddConstraints(this);
}*/
}
SortTable(metaDataTables[(int)MDTable.GenericParamConstraint]);
SortTable(metaDataTables[(int)MDTable.CustomAttribute]);
}
internal void WriteByteCodes(FileImage output)
{
for (int i=0; i < byteCodes.Count; i++) {
((CILInstructions)byteCodes[i]).Write(output);
}
for (int i=0; i < byteCodePadding; i++) {
output.Write((byte)0);
}
}
internal void WriteResources (FileImage output)
{
if (resources == null) return;
for (int i = 0; i < resources.Count; i ++) {
byte [] resBytes = (byte []) resources [i];
output.Write ((uint) resBytes.Length);
output.Write (resBytes);
}
}
internal void WriteMetaData(FileImage output)
{
this.output = output;
mdStart = output.Seek(0,SeekOrigin.Current);
// Console.WriteLine("Writing metaData at " + Hex.Long(mdStart));
output.Write(MetaDataSignature);
output.Write((short)1); // Major Version
output.Write((short)1); // Minor Version ECMA = 0, PEFiles = 1
output.Write(0); // Reserved
output.Write(version.Length);
output.Write(version.ToCharArray()); // version string is already zero padded
output.Write((short)0);
output.Write((ushort)numStreams);
// write tilde header
output.Write(tildeStart);
output.Write(tildeTide + tildePadding);
output.Write(tildeName);
for (int i=1; i < numStreams; i++) streams[i].WriteHeader(output);
// Console.WriteLine("Writing tilde stream at " + output.Seek(0,SeekOrigin.Current) + " = " + tildeStart);
WriteTildeStream(output);
for (int i=1; i < numStreams; i++) streams[i].Write(output);
// Console.WriteLine("Finished Writing metaData at " + output.Seek(0,SeekOrigin.Current));
}
internal bool LargeStringsIndex() { return strings.LargeIx(); }
internal bool LargeGUIDIndex() { return guid.LargeIx(); }
internal bool LargeUSIndex() { return us.LargeIx(); }
internal bool LargeBlobIndex() { return blob.LargeIx(); }
internal bool LargeIx(MDTable tabIx) { return largeIx[(uint)tabIx]; }
private uint NumToAlign(uint val, uint alignVal)
{
if ((val % alignVal) == 0) return 0;
return alignVal - (val % alignVal);
}
internal void WriteCodedIndex(CIx code, MetaDataElement elem, FileImage output)
{
uint ix = 0;
if (elem != null) {
ix = (elem.Row << CIxShiftMap[(uint)code]) | elem.GetCodedIx(code);
// Console.WriteLine("coded index = " + ix + " row = " + elem.Row);
//} else {
// Console.WriteLine("elem for coded index is null");
}
if (lgeCIx[(uint)code])
output.Write(ix);
else
output.Write((ushort)ix);
}
}
/**************************************************************************/
/// <summary>
/// Stream in the Meta Data (#Strings, #US, #Blob and #GUID)
/// </summary>
internal class MetaDataStream : BinaryWriter {
private static readonly uint StreamHeaderSize = 8;
private static uint maxSmlIxSize = 0xFFFF;
private uint start = 0;
uint size = 0, tide = 1;
bool largeIx = false;
uint sizeOfHeader;
char[] name;
Hashtable htable = new Hashtable();
Hashtable btable = new Hashtable (new ByteArrayHashCodeProvider (), new ByteArrayComparer ());
bool addInitByte = false;
bool initByteAdded = false;
internal MetaDataStream(char[] name, bool addInitByte) : base(new MemoryStream())
{
this.addInitByte = addInitByte;
this.name = name;
sizeOfHeader = StreamHeaderSize + (uint)name.Length;
}
internal MetaDataStream(char[] name, System.Text.Encoding enc, bool addInitByte) : base(new MemoryStream(),enc)
{
this.addInitByte = addInitByte;
this.name = name;
sizeOfHeader = StreamHeaderSize + (uint)name.Length;
}
void AddInitByte () {
if (addInitByte && !initByteAdded) {
Write((byte)0);
size += 1;
initByteAdded = true;
}
}
public uint Start {
get { return start; }
set { start = value; }
}
internal uint headerSize()
{
// Console.WriteLine(name + " stream has headersize of " + sizeOfHeader);
return sizeOfHeader;
}
internal void SetSize(uint siz)
{
size = siz;
}
internal uint Size()
{
return size;
}
internal bool LargeIx()
{
return largeIx;
}
internal void WriteDetails()
{
// Console.WriteLine(name + " - size = " + size);
}
internal uint Add(string str, bool prependSize)
{
AddInitByte ();
Object val = htable[str];
uint index = 0;
if (val == null) {
index = size;
htable[str] = index;
char[] arr = str.ToCharArray();
if (prependSize) CompressNum((uint)arr.Length*2+1);
Write(arr);
Write((byte)0);
size = (uint)Seek(0,SeekOrigin.Current);
} else {
index = (uint)val;
}
return index;
}
internal uint Add (byte[] str, bool prependSize)
{
AddInitByte ();
Object val = btable [str];
uint index = 0;
if (val == null) {
index = size;
btable [str] = index;
if (prependSize) CompressNum ((uint) str.Length);
Write (str);
size = (uint) Seek (0, SeekOrigin.Current);
} else {
index = (uint) val;
}
return index;
}
internal uint Add(Guid guid, bool prependSize)
{
AddInitByte ();
byte [] b = guid.ToByteArray ();
if (prependSize) CompressNum ((uint) b.Length);
Write(guid.ToByteArray());
size =(uint)Seek(0,SeekOrigin.Current);
return tide++;
}
internal uint Add(byte[] blob)
{
AddInitByte ();
uint ix = size;
CompressNum((uint)blob.Length);
Write(blob);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
internal uint Add(byte val, bool prependSize)
{
AddInitByte ();
uint ix = size;
if (prependSize) CompressNum (1);
Write(val);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
internal uint Add(sbyte val, bool prependSize)
{
AddInitByte ();
uint ix = size;
if (prependSize) CompressNum (1);
Write(val);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
internal uint Add(ushort val, bool prependSize)
{
AddInitByte ();
uint ix = size;
if (prependSize) CompressNum (2);
Write(val);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
internal uint Add(short val, bool prependSize)
{
AddInitByte ();
uint ix = size;
if (prependSize) CompressNum (2);
Write(val);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
internal uint Add(uint val, bool prependSize)
{
AddInitByte ();
uint ix = size;
if (prependSize) CompressNum (4);
Write(val);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
internal uint Add(int val, bool prependSize)
{
AddInitByte ();
uint ix = size;
if (prependSize) CompressNum (4);
Write (val);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
internal uint Add(ulong val, bool prependSize)
{
AddInitByte ();
uint ix = size;
if (prependSize) CompressNum (8);
Write(val);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
internal uint Add(long val, bool prependSize)
{
AddInitByte ();
uint ix = size;
if (prependSize) CompressNum (8);
Write(val);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
internal uint Add(float val, bool prependSize)
{
AddInitByte ();
uint ix = size;
if (prependSize) CompressNum (4);
Write(val);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
internal uint Add(double val, bool prependSize)
{
AddInitByte ();
uint ix = size;
if (prependSize) CompressNum (8);
Write(val);
size = (uint)Seek(0,SeekOrigin.Current);
return ix;
}
private void CompressNum(uint val)
{
if (val < 0x7F) {
Write((byte)val);
} else if (val < 0x3FFF) {
byte b1 = (byte)((val >> 8) | 0x80);
byte b2 = (byte)(val & FileImage.iByteMask[0]);
Write(b1);
Write(b2);
} else {
byte b1 = (byte)((val >> 24) | 0xC0);
byte b2 = (byte)((val & FileImage.iByteMask[2]) >> 16);
byte b3 = (byte)((val & FileImage.iByteMask[1]) >> 8);;
byte b4 = (byte)(val & FileImage.iByteMask[0]);
Write(b1);
Write(b2);
Write(b3);
Write(b4);
}
}
private void QuadAlign()
{
if ((size % 4) != 0) {
uint pad = 4 - (size % 4);
size += pad;
for (int i=0; i < pad; i++) {
Write((byte)0);
}
}
}
internal void EndStream()
{
QuadAlign();
if (size > maxSmlIxSize) {
largeIx = true;
}
}
internal void WriteHeader(BinaryWriter output)
{
output.Write(start);
output.Write(size);
output.Write(name);
}
internal virtual void Write(BinaryWriter output)
{
// Console.WriteLine("Writing " + name + " stream at " + output.Seek(0,SeekOrigin.Current) + " = " + start);
MemoryStream str = (MemoryStream)BaseStream;
output.Write(str.ToArray());
}
}
/**************************************************************************/
class ByteArrayComparer : IComparer {
public int Compare (object x, object y)
{
byte [] a = (byte []) x;
byte [] b = (byte []) y;
int len = a.Length;
if (b.Length != len)
return 1;
for (int i = 0; i < len; ++i)
if (a [i] != b [i])
return 1;
return 0;
}
}
class ByteArrayHashCodeProvider : IHashCodeProvider {
public int GetHashCode (Object key)
{
byte [] arr = (byte []) key;
int len = arr.Length;
int h = 0;
for (int i = 0; i < len; ++i)
h = (h << 5) - h + arr [i];
return h;
}
}
}
|