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
|
/**************************** disasm2.cpp ********************************
* Author: Agner Fog
* Date created: 2007-02-25
* Last modified: 2025-08-26
* Project: objconv
* Module: disasm2.cpp
* Description:
* Module for disassembler containing file output functions
*
* Changes that relate to assembly language syntax should be done in this file only.
*
* Copyright 2007-2025 GNU General Public License http://www.gnu.org/licenses
*****************************************************************************/
#include "stdafx.h"
/********************** Warning and error texts ***************************
These texts are inserted in disassembled code in case of warnings or errors.
The occurrence of an error makes the disassembler mark the code block between
the nearest known code labels as dubious. This means that the byte sequence
might be data in the code segment or the disassembler might be out of phase
with instruction boundaries. Dubious code will be shown both as code and as
data.
A warning will be shown as 'Note:' before the instruction it applies to.
This might indicate suboptimal coding or a possible cause for concern.
The criteria for distinguishing between warnings and errors is not the
severity of consequences, but whether the condition is likely to be caused
by common programming errors or by data in the code segment.
Some of the warning messages are quite benign, e.g. an unnecessary prefix.
Other warning messages can have severe consequences, e.g. a function missing
a return statement.
Still other warnings are no case for concern, but a condition requiring
attention. For example the message: "Multi-byte NOP. Replace with ALIGN",
might actually indicate a well optimized code. But it requires attention
because the assembler cannot re-create the multi-byte NOP if the code
is assembled again. The programmer needs to decide what level of alignment
is optimal and replace the NOP with an align statement.
*****************************************************************************/
// Define error texts.
SIntTxt AsmErrorTexts[] = {
{1, "Instruction longer than 15 bytes"},
{2, "Lock prefix not allowed for this opcode"},
{4, "Illegal opcode"},
{8, "Illegal operands for this opcode"},
{0x10, "Instruction extends beyond end of code block"},
{0x20, "Prefix after REX prefix not allowed"},
{0x40, "This instruction is not allowed in 64 bit mode"},
{0x80, "Instruction out of phase with next label"},
{0x100, "Attempt to use R13 as base register without displacement"},
{0x200, "Register 8 - 15 only allowed in 64 bit mode (Ignored)."},
{0x400, "REX prefix not allowed on instruction with DREX byte"},
{0x800, "VEX has X bit but no SIB byte (Probably ignored)"},
{0x1000, "Relocation source does not match address or operand field"},
{0x2000, "Overlapping relocations"},
{0x4000, "This is unlikely to be code"}, // Consecutive bytes of 0 found
{0x8000, "VEX.L bit not allowed here"},
{0x10000, "VEX.mmmm bits out of range"},
{0x80000, "Internal error in opcode table in opcodes.cpp"}
};
// Warning texts 1: Warnings about conditions that could be intentional and suboptimal code
SIntTxt AsmWarningTexts1[] = {
{1, "Immediate operand could be made smaller by sign extension"},
{2, "Immediate operand could be made smaller by zero extension"},
{4, "Zero displacement could be omitted"},
{8, "Displacement could be made smaller by sign extension"},
{0x10, "SIB byte unnecessary here"},
{0x20, "A shorter instruction exists for register operand"},
{0x40, "Length-changing prefix causes delay on old Intel processors"},
{0x80, "Address size prefix should be avoided"},
{0x100, "Same prefix occurs more than once"},
{0x200, "Prefix valid but unnecessary"},
{0x400, "Prefix bit or byte has no meaning in this context"},
{0x800, "Contradicting prefixes"},
{0x1000, "Required prefix missing"},
{0x2000, "Address has scale factor but no index register"},
{0x4000, "Address is not rip-relative"},
{0x8000, "Absolute memory address without relocation"},
{0x10000, "Unusual relocation type for this operand"},
{0x20000, "Instruction pointer truncated by operand size prefix"},
{0x40000, "Stack pointer truncated by address size prefix"},
{0x80000, "Jump or call to data segment not allowed"},
{0x100000, "Undocumented opcode"},
{0x200000, "Unknown opcode reserved for future extensions"},
{0x400000, "Memory operand is misaligned. Performance penalty"},
{0x800000, "Alignment fault. Memory operand must be aligned"},
{0x1000000, "Multi-byte NOP. Replace with ALIGN"},
{0x2000000, "Bogus length-changing prefix causes delay on old Intel processors here"},
{0x4000000, "Non-default size for stack operation"},
{0x8000000, "Function does not end with ret or jmp"},
{0x10000000, "No jump seems to point here"},
{0x20000000, "Full 64-bit address"},
{0x40000000, "VEX prefix bits not allowed here"}
};
// Warning texts 2: Warnings about possible misinterpretation; serious warnings
SIntTxt AsmWarningTexts2[] = {
{1, "Label out of phase with instruction. Possibly spurious"},
{2, "Planned future instruction, according to preliminary specification"},
{4, "This instruction has been planned but never implemented because plans were changed. Will not work"},
{0x10, "EVEX prefix not allowed for this instruction"},
{0x20, "MVEX prefix not allowed for this instruction"},
{0x40, "EVEX prefix option bits not allowed here"},
{0x80, "MVEX prefix option bits not allowed here"},
{0x100, "Mask register must be nonzero"},
{0x200, "Broadcasting to scalar not allowd"},
};
// Indication of relocation types in comments:
SIntTxt RelocationTypeNames[] = {
{0x001, "(d)" }, // Direct address in flat address space
{0x002, "(rel)" }, // Self-relative
{0x004, "(imgrel)" }, // Image-relative
{0x008, "(segrel)" }, // Segment-relative
{0x010, "(refpoint)" }, // Relative to arbitrary point (position-independent code in Mach-O)
{0x021, "(d)" }, // Direct (adjust by image base)
{0x041, "(d)" }, // Direct (make procecure linkage table entry)
{0x081, "(indirect)" }, // Gnu indirect function dispatcher (make procecure linkage table entry?)
{0x100, "(seg)" }, // Segment address or descriptor
{0x200, "(sseg)" }, // Segment of symbol
{0x400, "(far)" }, // Far segment:offset address
{0x1001, "(GOT)" }, // GOT entry
{0x1002, "(GOT r)" }, // self-relative to GOT entry
{0x2002, "(PLT r)" } // self-relative to PLT entry
};
// Instruction set names
const char * InstructionSetNames[] = {
"8086", "80186", "80286", "80386", // 0 - 3
"80486", "Pentium", "Pentium Pro", "MMX", // 4 - 7
"Pentium II", "", "", "", // 8 - B
"", "", "", "", // C - F
"", "SSE", "SSE2", "SSE3", // 10 - 13
"Supplementary SSE3", "SSE4.1", "SSE4.2", "AES", // 14 - 17
"CLMUL", "AVX", "FMA3", "?", // 18 - 1B
"AVX2", "BMI etc.", "?", "?", // 1C - 1F
"AVX-512", "AVX512PF/ER/CD", "MPX,SHA,TBD", "AVX512IFMA/VBMI/VBMI2", // 20 - 23
"Misc.extensions", "AVX512-FP16", "?", "?", // 24 - 27
"?", "?", "?", "?", // 28 - 2B
"?", "?", "?", "?", // 2C - 2F
"?", "?", "?", "?", // 30 - 33
"?", "?", "?", "?", // 34 - 37
"?", "?", "?", "?", // 38 - 3B
"?", "?", "?", "?", // 3C - 3F
"?", "?", "?", "?", // 40 - 43
"?", "?", "?", "?", // 44 - 47
"?", "?", "?", "?", // 48 - 4B
"?", "?", "?", "?", // 4C - 4F
"?", "?", "?", "?", // 50 - 53
"?", "?", "?", "?", // 54 - 57
"?", "?", "?", "?", // 58 - 5B
"?", "?", "?", "?", // 5C - 5F
"?", "?", "?", "?", // 60 - 63
"?", "?", "?", "?", // 64 - 67
"?", "?", "?", "?", // 68 - 6B
"?", "?", "?", "?", // 6C - 6F
"?", "?", "?", "?", // 70 - 73
"?", "?", "?", "?", // 74 - 77
"?", "?", "?", "?", // 78 - 7B
"?", "?", "?", "?", // 7C - 7F
"Knights Corner", "?", "?", "?", // 80 - 83
"?", "?", "?", "?" // 84 - 87
};
const int InstructionSetNamesLen = TableSize(InstructionSetNames);
/************************** class CDisassembler *****************************
Most member functions of CDisassembler are defined in disasm1.cpp
Only the functions that produce output are defined here:
******************************************************************************/
void CDisassembler::WriteShortRegOperand(uint32_t Type) {
// Write register operand from lower 3 bits of opcode byte to OutFile
uint32_t rnum = Get<uint8_t>(s.OpcodeStart2) & 7;
// Check REX.B prefix
if (s.Prefixes[7] & 1) rnum |= 8; // Add 8 if REX.B prefix
// Write register name
WriteRegisterName(rnum, Type);
}
void CDisassembler::WriteRegOperand(uint32_t Type) {
// Write register operand from reg bits
uint32_t Num = s.Reg; // Register number
// Write register name
WriteRegisterName(Num, Type);
}
void CDisassembler::WriteRMOperand(uint32_t Type) {
// Write memory or register operand from mod/rm bits of mod/reg/rm byte
// and possibly SIB byte or direct memory operand to OutFile.
// Also used for writing direct memory operand
if ((Type & 0xFF) == 0) {
// No explicit operand
return;
}
uint32_t Components = 0; // Count number of addends inside []
int64_t Addend = 0; // Inline displacement or addend
int AddressingMode = 0; // 0: 16- or 32 bit addressing mode
// 1: 64-bit pointer
// 2: 32-bit absolute in 64-bit mode
// 4: 64-bit rip-relative
// 8: 64-bit absolute
// Check if register or memory
if (s.Mod == 3) {
// Register operand
WriteRegisterName(s.RM, Type);
return;
}
// Find addend, if any
switch (s.AddressFieldSize) {
case 1: // 1 byte displacement
Addend = Get<int8_t>(s.AddressField);
break;
case 2: // 2 bytes displacement
Addend = Get<int16_t>(s.AddressField);
break;
case 4: // 4 bytes displacement
Addend = Get<int32_t>(s.AddressField);
if ((s.MFlags & 0x100) && !s.AddressRelocation) {
// rip-relative
Addend += ImageBase + uint64_t(SectionAddress + IEnd);
}
break;
case 8: // 8 bytes address
Addend = Get<int64_t>(s.AddressField);
break;
}
// Get AddressingMode
if (s.AddressSize > 32) {
if (s.MFlags & 0x100) {
AddressingMode = 4; // 64-bit rip-relative
}
else if (s.AddressFieldSize == 8) {
AddressingMode = 8; // 64-bit absolute
}
else if (s.AddressRelocation || (s.BaseReg==0 && s.IndexReg==0)) {
AddressingMode = 2; // 32-bit absolute in 64-bit mode
}
else {
AddressingMode = 1; // 64-bit pointer
}
}
// Make exception for LEA with no type
if (Opcodei == 0x8D) {
Type = 0;
}
// Write type override
if ((s.OpcodeDef->InstructionFormat & 0x1F) == 0x1E) {
WriteOperandType(Type & 0xFF); // has vsib address: write element type rather than vector type
}
else if (!(s.OpcodeDef->Options & 0x800)) {
WriteOperandType(Type); // write operand type
}
if (Syntax != SUBTYPE_MASM) {
// Write "[" around memory operands, before segment
OutFile.Put("[");
}
// Write segment prefix, if any
if (s.Prefixes[0]) {
OutFile.Put(RegisterNamesSeg[GetSegmentRegisterFromPrefix()]);
OutFile.Put(":");
}
else if (!s.BaseReg && !s.IndexReg && (!s.AddressRelocation || (s.Warnings1 & 0x10000)) && Syntax != SUBTYPE_NASM) {
// No pointer register and no memory reference or wrong type of memory reference.
// Write segment register to indicate that we have a memory operand
OutFile.Put("DS:");
}
if (Syntax == SUBTYPE_MASM) {
// Write "[" around memory operands, after segment
OutFile.Put("[");
}
if (Syntax == SUBTYPE_NASM && (AddressingMode & 0x0E)) {
// Specify absolute or relative addressing mode
switch (AddressingMode) {
case 2: OutFile.Put("abs "); break;
case 4: OutFile.Put("rel "); break;
case 8: OutFile.Put("abs qword "); break;
}
}
// Write relocation target, if any
if (s.AddressRelocation) {
// Write cross reference
WriteRelocationTarget(s.AddressRelocation, 4 | (s.MFlags & 0x100), Addend);
// Addend has been written, don't write it again
Addend = 0;
// Remember that something has been written
Components++;
}
// Check address size for pointer registers
//const char * * PointerRegisterNames;
uint32_t RegisterType = 0;
switch (s.AddressSize) {
case 16:
RegisterType = 2; break;
case 32:
RegisterType = 3; break;
case 64:
RegisterType = 4; break;
}
// Write base register, if any
if (s.BaseReg) {
if (Components++) OutFile.Put("+"); // Put "+" if anything before
WriteRegisterName(s.BaseReg - 1, RegisterType);
}
// Write index register, if any
if (s.IndexReg) {
if (Components++) OutFile.Put("+"); // Put "+" if anything before
if ((s.OpcodeDef->InstructionFormat & 0x1F) != 0x1E) {
// normal index register
WriteRegisterName(s.IndexReg - 1, RegisterType);
}
else {
// VSIB byte specifies vector index register
WriteRegisterName(s.IndexReg - 1, Type & 0xF00);
}
// Write scale factor, if any
if (s.Scale) {
OutFile.Put("*");
OutFile.PutDecimal(1 << s.Scale);
}
}
// Write +/- before addend
if (Components && Addend) {
// Displacement comes after base/index registers
if (Addend >= 0 || s.AddressFieldSize == 8) {
// Positive. Write +
OutFile.Put("+");
}
else {
// Negative. Write -
OutFile.Put("-");
Addend = -Addend;
}
}
if (Addend || Components == 0) {
// Find minimum number of digits needed
uint32_t AddendSize = s.AddressFieldSize;
if ((uint64_t)Addend < 0x100 && AddendSize > 1) AddendSize = 1;
else if ((uint64_t)Addend < 0x10000 && AddendSize > 2) AddendSize = 2;
// Write address or addend as hexadecimal
OutFile.PutHex((uint64_t)Addend, 2);
// Check if offset multiplier needed
if (s.OffsetMultiplier && s.AddressFieldSize == 1 && Addend) {
OutFile.Put("*");
OutFile.PutHex(s.OffsetMultiplier, 2);
}
}
if (Syntax == SUBTYPE_GASM && (AddressingMode == 4)) {
// Need to specify rip-relative address
OutFile.Put("+rip");
}
// End with "]"
OutFile.Put("]");
}
void CDisassembler::WriteOperandType(uint32_t type) {
switch (Syntax) {
case SUBTYPE_MASM:
WriteOperandTypeMASM(type); break;
case SUBTYPE_NASM:
WriteOperandTypeNASM(type); break;
case SUBTYPE_GASM:
WriteOperandTypeGASM(type); break;
}
}
void CDisassembler::WriteOperandTypeMASM(uint32_t type) {
// Write type override before operand, e.g. "dword ", MASM syntax
if (type & 0xF00) {
type &= 0xF00; // Ignore element type for vectors
}
else {
type &= 0xFF; // Use operand type only
}
switch (type) {
case 1: // 8 bits
OutFile.Put("byte "); break;
case 2: // 16 bits
OutFile.Put("word "); break;
case 3: // 32 bits
OutFile.Put("dword "); break;
case 4: // 64 bits
OutFile.Put("qword "); break;
case 5: // 80 bits
if ((s.OpcodeDef->Destination & 0xFF) == 0xD) {
// 64+16 bit far pointer. Not supported by MASM
OutFile.Put("fword ");
s.OpComment = "64+16 bit. Need REX.W prefix";
}
else {
OutFile.Put("tbyte ");}
break;
case 6: case 0x40: case 0x48: case 0:
// Other size. Write nothing
break;
case 7: case 0x0D: // 48 bits or far
OutFile.Put("fword ");
if ((s.OpcodeDef->Destination & 0xFF) == 0xD && WordSize == 64) {
// All assemblers I have tried forget the REX.W prefix here. Make a notice
s.OpComment = "32+16 bit. Possibly forgot REX.W prefix";
}
break;
case 0x4A: // 16 bits float
OutFile.Put("word "); break;
case 0x43: // 32 bits float (x87)
case 0x4B: // 32 bits float (SSE2)
OutFile.Put("dword "); break;
case 0x44: // 64 bits float
case 0x4C: // 64 bits float (SSE2)
OutFile.Put("qword "); break;
case 0x45: // 80 bits float
OutFile.Put("tbyte "); break;
case 0x84: case 0x85: // far call
OutFile.Put("far "); break;
case 0x95: // 16 bits mask register
OutFile.Put("word "); break;
case 0x300: // MMX
OutFile.Put("qword "); break;
case 0x400: // XMM
OutFile.Put("xmmword "); break;
case 0x500: // YMM
OutFile.Put("ymmword "); break;
case 0x600: // ZMM
OutFile.Put("zmmword "); break;
case 0x700: // future 1024 bit
OutFile.Put("?mmword "); break;
}
if (type) OutFile.Put("ptr ");
}
void CDisassembler::WriteOperandTypeNASM(uint32_t type) {
// Write type override before operand, e.g. "dword", NASM/YASM syntax
if (type & 0xF00) {
type &= 0xF00; // Ignore element type for vectors
}
else {
type &= 0xFF; // Use operand type only
}
uint32_t Dest = s.OpcodeDef->Destination & 0xFF;// Destination operand
if (Dest >= 0xB && Dest < 0x10) {
// This is a pointer
if (Dest < 0x0D) {
OutFile.Put("near "); // Near indirect jump/call
}
else {
// Far pointer
if ((WordSize == 16 && type == 3) || (WordSize == 32 && type == 7)) {
OutFile.Put("far ");
}
else {
// Size currently not supported by NASM
switch (type) {
case 3: OutFile.Put("far ");
s.OpComment = "16+16 bit. Needs 66H prefix";
break;
case 7: OutFile.Put("far ");
s.OpComment = "32+16 bit. Possibly forgot REX.W prefix";
break;
case 5: OutFile.Put("far ");
s.OpComment = "64+16 bit. Needs REX.W prefix";
break;
}
}
}
return;
}
switch (type) {
case 1: // 8 bits
OutFile.Put("byte "); break;
case 2: // 16 bits
OutFile.Put("word "); break;
case 3: // 32 bits
OutFile.Put("dword "); break;
case 4: // 64 bits
OutFile.Put("qword "); break;
case 5: // 80 bits
OutFile.Put("tbyte "); break;
case 7: // 48 bits
OutFile.Put("fword "); break;
case 0x4A: // 16 bits float
OutFile.Put("word "); break;
case 0x43: // 32 bits float (x87)
case 0x4B: // 32 bits float (SSE2)
OutFile.Put("dword "); break;
case 0x44: // 64 bits float
case 0x4C: // 64 bits float (SSE2)
OutFile.Put("qword "); break;
case 0x45: // 80 bits float
OutFile.Put("tbyte "); break;
case 0x84: case 0x85: // far call
OutFile.Put("far "); break;
case 0x95: // 16 bits mask register
OutFile.Put("word "); break;
case 0x300: // MMX
OutFile.Put("qword "); break;
case 0x400: // XMM
OutFile.Put("oword "); break;
case 0x500: // YMM
OutFile.Put("yword "); break;
case 0x600: // ZMM
OutFile.Put("zword "); break;
case 0x700: // Future 128 bytes
OutFile.Put("?word "); break;
default:; // Anything else: write nothing
}
}
void CDisassembler::WriteOperandTypeGASM(uint32_t type) {
// Write type override before operand, e.g. "dword ", GAS syntax
if (type & 0xF00) {
type &= 0xF00; // Ignore element type for vectors
}
else {
type &= 0xFF; // Use operand type only
}
switch (type) {
case 1: // 8 bits
OutFile.Put("byte "); break;
case 2: // 16 bits
OutFile.Put("word "); break;
case 3: // 32 bits
OutFile.Put("dword "); break;
case 4: // 64 bits
OutFile.Put("qword "); break;
case 5: // 80 bits
if ((s.OpcodeDef->Destination & 0xFF) == 0xD) {
// 64+16 bit far pointer. Not supported by Gas
OutFile.Put("fword ");
s.OpComment = "64+16 bit. Needs REX.W prefix";
}
else {
OutFile.Put("tbyte ");}
break;
case 6: case 0x40: case 0x48: case 0:
// Other size. Write nothing
break;
case 7: // 48 bits
OutFile.Put("fword ");
if ((s.OpcodeDef->Destination & 0xFF) == 0xD && WordSize == 64) {
// All assemblers I have tried forget the REX.W prefix here. Make a notice
s.OpComment = "32+16 bit. Possibly forgot REX.W prefix";
}
break;
case 0x4A: // 16 bits float
OutFile.Put("word "); break;
case 0x43: // 32 bits float (x87)
case 0x4B: // 32 bits float (SSE2)
OutFile.Put("dword "); break;
case 0x44: // 64 bits float
case 0x4C: // 64 bits float (SSE2)
OutFile.Put("qword "); break;
case 0x45: // 80 bits float
OutFile.Put("tbyte "); break;
case 0x84: case 0x85: // far call
OutFile.Put("far "); break;
case 0x95: // 16 bits mask register
OutFile.Put("word "); break;
case 0x300: // MMX
OutFile.Put("qword "); break;
case 0x400: // XMM
OutFile.Put("xmmword "); break;
case 0x500: // YMM
OutFile.Put("ymmword "); break;
case 0x600: // ZMM
OutFile.Put("zmmword "); break;
case 0x700: // future 1024 bit
OutFile.Put("?mmword "); break;
}
}
void CDisassembler::WriteDREXOperand(uint32_t Type) {
// Write register operand from dest bits of DREX byte (AMD only)
uint32_t Num = s.Vreg >> 4; // Register number
// Write register name
WriteRegisterName(Num, Type);
}
void CDisassembler::WriteVEXOperand(uint32_t Type, int i) {
// Write register operand from VEX.vvvv bits or immediate bits
uint32_t Num; // Register number
switch (i) {
case 0: // Use VEX.vvvv bits
Num = s.Vreg & 0x1F; break;
case 1: // Use immediate bits 4-7
Num = Get<uint8_t>(s.ImmediateField) >> 4; break;
case 2: // Use immediate bits 0-3 (Unused. For possible future use)
Num = Get<uint8_t>(s.ImmediateField) & 0x0F; break;
default:
Num = 0;
}
// Write register name
WriteRegisterName(Num, Type);
}
void CDisassembler::WriteOperandAttributeEVEX(int i, int isMem) {
// Write operand attributes and instruction attributes from EVEX z, LL, b and aaa bits
// i = operand number (0 = destination, 1 = first source, 2 = second source,
// 98 = after last SIMD operand, 99 = after last operand)
// isMem: true if memory operand, false if register operand
uint32_t swiz = s.OpcodeDef->EVEX; // indicates meaning of EVEX attribute bits
if ((swiz & 0x30) && (i == 0 || (s.OpcodeDef->Destination == 0 && i == 1))) { // first operand
// write mask
if (s.Kreg || (swiz & 0xC0)) {
OutFile.Put(" {k");
OutFile.PutDecimal(s.Kreg);
OutFile.Put("}");
if ((swiz & 0x20) && (s.Esss & 8)) {
// zeroing
OutFile.Put("{z}");
}
}
}
if (swiz & 0x07) {
// broadcast, rounding or sae allowed
if (isMem && i < 8) {
// memory operand
if ((swiz & 0x01) && (s.Esss & 1)) {
// write memory broadcast
// calculate broadcast factor
uint32_t op = s.Operands[i]; // operand
uint32_t elementsize = GetDataElementSize(op); // element size
uint32_t opv = s.Operands[0]; // any vector operand
if (!(opv & 0xF00)) opv = s.Operands[1]; // first operand is not a vector, use next
uint32_t vectorsize = GetDataItemSize(opv); // vector size
if (vectorsize > elementsize) { // avoid broadcasting to scalar
if (elementsize) { // avoid division by zero
OutFile.Put(" {1to");
OutFile.PutDecimal(vectorsize/elementsize);
OutFile.Put("}");
}
else {
OutFile.Put("{unknown broadcast}");
}
}
}
}
if (i == 98 && s.Mod == 3) { // after last SIMD operand. no memory operand
// NASM has rounding mode and sae decoration after last SIMD operand with a comma.
// No spec. for other assemblers available yet (2014).
// use i == 99 if it should be placed after last operand.
// Perhaps the comma should be removed for other assemblers?
if ((swiz & 0x4) && (s.Esss & 1)) {
// write rounding mode
uint32_t rounding = (s.Esss >> 1) & 3;
OutFile.Put(", {");
OutFile.Put(EVEXRoundingNames[rounding]);
OutFile.Put("}");
}
else if ((swiz & 0x2) && (s.Esss & 1)) {
// no rounding mode. write sae
OutFile.Put(", {");
OutFile.Put(EVEXRoundingNames[4]);
OutFile.Put("}");
}
}
}
}
void CDisassembler::WriteOperandAttributeMVEX(int i, int isMem) {
// Write operand attributes and instruction attributes from MVEX sss, e and kkk bits.
// i = operand number (0 = destination, 1 = first source, 2 = second source, 99 = after last operand)
// isMem: true if memory operand, false if register operand
uint32_t swiz = s.OpcodeDef->MVEX; // indicates meaning of MVEX attribute bits
const int R_sae_syntax = 0; // syntax alternatives for rounding mode + sae
// 0: {rn-sae}, 1: {rn}{sae}
const char * text = 0; // temporary text pointer
if ((swiz & 0x1000) && (i == 0 || (s.OpcodeDef->Destination == 0 && i == 1))) { // first operand
// write mask
if (s.Kreg || (swiz & 0x2000)) {
OutFile.Put(" {k");
OutFile.PutDecimal(s.Kreg);
OutFile.Put("}");
}
}
if (swiz & 0x1F) {
// swizzle allowed
if (isMem && i < 90) {
// write memory broadcast/up/down conversion
text = s.SwizRecord->name;
if (text && *text) {
OutFile.Put(" {"); OutFile.Put(text); OutFile.Put("}");
}
}
//if (i == 2 || ((s.OpcodeDef->Source2 & 0xF0F00) == 0 && i == 1)) {
if (i == 98) { // after last SIMD operand
// last register or memory operand
if (s.Mod == 3 && !((swiz & 0x700) && (s.Esss & 8))) { // skip alternative meaning of sss field for register operand when E=1
// write register swizzle
text = s.SwizRecord->name;
if (text && *text) {
OutFile.Put(" {"); OutFile.Put(text); OutFile.Put("}");
}
}
}
if (i == 99) { // after last operand
if (s.Mod == 3 && (swiz & 0x300) && (s.Esss & 8)) {
// alternative meaning of sss field for register operand when E=1
switch (swiz & 0x300) {
case 0x100: // rounding mode and not sae
text = SwizRoundTables[0][0][s.Esss & 3].name;
break;
case 0x200: // suppress all exceptions
if ((s.Esss & 4) && !(swiz & 0x800)) text = "sae";
break;
case 0x300: // rounding mode and sae
text = SwizRoundTables[0][R_sae_syntax][s.Esss & 7].name;
break;
}
}
if (text && *text) {
OutFile.Put(", {"); OutFile.Put(text); OutFile.Put("}");
}
}
}
if (isMem && (s.Esss & 8) && !(swiz & 0x800)) {
// cache eviction hint after memory operand
OutFile.Put(" {eh}");
}
}
void CDisassembler::WriteRegisterName(uint32_t Value, uint32_t Type) {
// Write name of register to OutFile
if (Type & 0xF00) {
// vector register
Type &= 0xF00;
}
else {
// Other register
Type &= 0xFF; // Remove irrelevant bits
}
// Check fixed registers (do not depend on Value)
switch (Type) {
case 0xA1: // al
Type = 1; Value = 0;
break;
case 0xA2: // ax
Type = 2; Value = 0;
break;
case 0xA3: // eax
Type = 3; Value = 0;
break;
case 0xA4: // rax
Type = 4; Value = 0;
break;
case 0xAE: // xmm0
Type = 0x400; Value = 0;
break;
case 0xAF: // st(0)
Type = 0x40; Value = 0;
break;
case 0xB2: // dx
Type = 2; Value = 2;
break;
case 0xB3: // cl
Type = 1; Value = 1;
break;
}
// Get register number limit
uint32_t RegNumLimit = 7; // largest register number
if (WordSize >= 64) {
RegNumLimit = 15;
if ((s.Prefixes[6] & 0x40) && (Type & 0xF40)) {
// EVEX or MVEX prefix and vector
RegNumLimit = 31;
}
}
switch (Type) {
case 0x91: // segment register
RegNumLimit = 5;
break;
case 0x300: // mmx
case 0x40: // st register
case 0x95: // k mask register
RegNumLimit = 7;
break;
case 0x98: // bounds register
RegNumLimit = 3;
break;
}
if (Value > RegNumLimit) {
// register number out of range
OutFile.Put("unknown register ");
switch (Type) {
case 1:
OutFile.Put("(8 bit) "); break;
case 2:
OutFile.Put("(16 bit) "); break;
case 3:
OutFile.Put("(32 bit) "); break;
case 4:
OutFile.Put("(64 bit) "); break;
case 0x40: // st register
OutFile.Put("st"); break;
case 0x91: // Segment register
OutFile.Put("seg"); break;
case 0x92: // Control register
OutFile.Put("cr"); break;
case 0x95: // k mask register
OutFile.Put("k"); break;
case 0x300: // mmx register
OutFile.Put("mm"); break;
case 0x400: // xmm register
OutFile.Put("xmm"); break;
case 0x500: // ymm register
OutFile.Put("ymm"); break;
case 0x600: // zmm register
OutFile.Put("zmm"); break;
case 0x700: // future 1024 bit register
OutFile.Put("?mm"); break;
}
OutFile.PutDecimal(Value);
}
else {
// Write register name depending on type
switch (Type) {
case 1: // 8 bit register. Depends on any REX prefix
OutFile.Put(s.Prefixes[7] ? RegisterNames8x[Value] : RegisterNames8[Value & 7]);
break;
case 2: // 16 bit register
OutFile.Put(RegisterNames16[Value]);
break;
case 3: // 32 bit register
OutFile.Put(RegisterNames32[Value]);
break;
case 4: // 64 bit register
OutFile.Put(RegisterNames64[Value]);
break;
case 0x300: // mmx register
OutFile.Put("mm");
OutFile.PutDecimal(Value);
break;
case 0x400: // xmm register (packed integer or float)
case 0x48: case 0x4B: case 0x4C: // xmm register (scalar float)
OutFile.Put("xmm");
OutFile.PutDecimal(Value);
break;
case 0x500: // ymm register (packed)
OutFile.Put("ymm");
OutFile.PutDecimal(Value);
break;
case 0x600: // zmm register (packed)
OutFile.Put("zmm");
OutFile.PutDecimal(Value);
break;
case 0x700: // future 1024 bit register
OutFile.Put("?mm");
OutFile.PutDecimal(Value);
break;
case 0x40: // st register
if (Syntax == SUBTYPE_NASM) {
// NASM, YASM and GAS-AT&T use st0
OutFile.Put("st");
OutFile.PutDecimal(Value);
}
else {
// MASM and GAS-Intel use st(0),
OutFile.Put("st(");
OutFile.PutDecimal(Value);
OutFile.Put(")");
}
break;
case 0x91: // Segment register
OutFile.Put(RegisterNamesSeg[Value & 7]);
break;
case 0x92: // Control register
OutFile.Put(RegisterNamesCR[Value]);
break;
case 0x93: // Debug register
OutFile.Put("dr");
OutFile.PutDecimal(Value);
break;
case 0x94: // Test register (obsolete)
OutFile.Put("tr");
OutFile.PutDecimal(Value);
break;
case 0x95: // k mask register
OutFile.Put("k");
OutFile.PutDecimal(Value);
break;
case 0x98: // bounds register
OutFile.Put("bnd");
OutFile.PutDecimal(Value);
break;
case 0xB1: // 1
OutFile.Put("1");
break;
default: // Unexpected
OutFile.Put("UNKNOWN REGISTER TYPE ");
OutFile.PutDecimal(Value);
break;
}
}
}
void CDisassembler::WriteImmediateOperand(uint32_t Type) {
// Write immediate operand or direct jump/call address
int WriteFormat; // 0: unsigned, 1: signed, 2: hexadecimal
int Components = 0; // Number of components in immediate operand
uint32_t OSize; // Operand size
uint32_t FieldPointer; // Pointer to field containing value
uint32_t FieldSize; // Size of field containing value
int64_t Value = 0; // Value of immediate operand
// Check if far
if ((Type & 0xFE) == 0x84) {
// Write far
WriteOperandType(Type);
}
// Check if type override needed
if ((s.OpcodeDef->AllowedPrefixes & 2) && s.Prefixes[4] == 0x66
&& (Opcodei == 0x68 || Opcodei == 0x6A)) {
// Push immediate with non-default operand size needs type override
WriteOperandType(s.OperandSize == 16 ? 2 : 3);
}
FieldPointer = s.ImmediateField;
FieldSize = s.ImmediateFieldSize;
if (Syntax == SUBTYPE_NASM && (Type & 0x0F) == 4 && FieldSize == 8) {
// Write type override to make sure we get 8 bytes address in case there is a relocation here
WriteOperandType(4);
}
if (Type & 0x200000) {
if (FieldSize > 1) {
// Uses second part of field. Single byte only
FieldPointer += FieldSize-1;
FieldSize = 1;
}
else {
// Uses half a byte
FieldSize = 0;
}
}
// Get inline value
switch (FieldSize) {
case 0: // 4 bits
Value = Get<uint8_t>(FieldPointer) & 0x0F;
break;
case 1: // 8 bits
Value = Get<int8_t>(FieldPointer);
break;
case 2: // 16 bits
Value = Get<int16_t>(FieldPointer); break;
case 6: // 48 bits
Value = Get<int32_t>(FieldPointer);
Value += (uint64_t)Get<uint16_t>(FieldPointer + 4) << 32;
break;
case 4: // 32 bits
Value = Get<int32_t>(FieldPointer); break;
case 8: // 64 bits
Value = Get<int64_t>(FieldPointer); break;
case 3: // 16+8 bits ("Enter" instruction)
if ((Type & 0xFF) == 0x12) {
// First 16 bits
FieldSize = 2; Value = Get<int16_t>(FieldPointer); break;
}
// else continue in default case to get error message
default: // Other sizes should not occur
err.submit(3000); Value = -1;
}
// Check if relocation
if (s.ImmediateRelocation) {
// Write relocation target name
uint32_t Context = 2;
if ((Type & 0xFC) == 0x80) Context = 8; // Near jump/call destination
if ((Type & 0xFC) == 0x84) Context = 0x10; // Far jump/call destination
// Write cross reference
WriteRelocationTarget(s.ImmediateRelocation, Context, Value);
// Remember that Value has been written
Value = 0;
Components++;
}
// Check if AAM or AAD
if (Value == 10 && (Opcodei & 0xFE) == 0xD4) {
// Don't write operand for AAM or AAD if = 10
return;
}
// Write as unsigned, signed or hexadecimal:
if ((Type & 0xF0) == 0x30 || (Type & 0xF0) == 0x80) {
// Hexadecimal
WriteFormat = 2;
}
else if (s.ImmediateFieldSize == 8) {
// 64 bit constant
if (Value == (int32_t)Value) {
// Signed
WriteFormat = 1;
}
else {
// Hexadecimal
WriteFormat = 2;
}
}
else if ((Type & 0xF0) == 0x20) {
// Signed
WriteFormat = 1;
}
else {
// Unsigned
WriteFormat = 0;
}
if ((Type & 0xFC) == 0x80 && !s.ImmediateRelocation) {
// Self-relative jump or call without relocation. Adjust immediate value
Value += IEnd; // Get absolute address of target
// Look for symbol at target address
uint32_t ISymbol = Symbols.FindByAddress(Section, (uint32_t)Value);
if (ISymbol && (Symbols[ISymbol].Name || CodeMode == 1)) {
// Symbol found. Write its name
OutFile.Put(Symbols.GetName(ISymbol));
// No offset to write
return;
}
// Target address has no name
Type |= 0x4000; // Write target as hexadecimal
}
// Operand size
if ((s.Operands[0] & 0xFFF) <= 0xA && s.Operands[0] != 0 || (s.Operands[0] & 0xF0) == 0xA0) {
// Destination is general purpose register
OSize = s.OperandSize;
if ((s.Operands[0] & 0x0F) < 3) {
OSize = (s.Operands[0] & 0x0F) << 3;
}
}
else {
// Constant probably unrelated to destination size
OSize = 8;
}
// Check if destination is 8 bit operand
//if ((s.Operands[0] & 0xFF) == 1 || (s.Operands[0] & 0xFF) == 0xA1) OSize = 8;
// Check if sign extended
if (OSize > s.ImmediateFieldSize * 8) {
if (WriteFormat == 2 && Value >= 0) {
// Hexadecimal sign extended
// Does not need full length
OSize = s.ImmediateFieldSize * 8;
}
else if (WriteFormat == 0) {
// Unsigned and sign extended, change to signed
WriteFormat = 1;
}
}
if (Components) {
// There was a relocated name
if (Value) {
// Addend to relocation is not zero
if (Value > 0 || WriteFormat != 1) {
OutFile.Put("+"); // Put "+" between name and addend
}
else {
OutFile.Put("-"); // Put "-" between name and addend
Value = - Value; // Change sign to avoid another "-"
}
}
else {
// No addend to relocated name
return;
}
}
// Write value
if (WriteFormat == 2) {
// Write with hexadecimal number appropriate size
switch (OSize) {
case 8: // 8 bits
OutFile.PutHex((uint8_t)Value, 1); break;
case 16: // 16 bits
if ((Type & 0xFC) == 0x84) {
// Segment of far call
OutFile.PutHex((uint16_t)(Value >> 16), 1);
OutFile.Put(':');
}
OutFile.PutHex((uint16_t)Value, 2); break;
case 32: // 32 bits
default: // Should not occur
if ((Type & 0xFC) == 0x84) {
// Segment of far call
OutFile.PutHex((uint16_t)(Value >> 32), 1);
OutFile.Put(':');
}
OutFile.PutHex((uint32_t)Value, 2); break;
case 64: // 64 bits
OutFile.PutHex((uint64_t)Value, 2); break;
}
}
else {
// Write as signed or unsigned decimal
if (WriteFormat == 0) { // unsigned
switch (OSize) {
case 8: // 8 bits
Value &= 0x00FF; break;
case 16: // 16 bits
Value &= 0xFFFF; break;
}
}
OutFile.PutDecimal((int32_t)Value, WriteFormat); // Write value. Signed or usigned decimal
}
}
void CDisassembler::WriteOtherOperand(uint32_t Type) {
// Write other type of operand
const char * * OpRegisterNames; // Pointer to list of register names
uint32_t RegI = 0; // Index into list of register names
switch (Type & 0x8FF) {
case 0xA1: // AL
OpRegisterNames = RegisterNames8;
break;
case 0xA2: // AX
OpRegisterNames = RegisterNames16;
break;
case 0xA3: // EAX
OpRegisterNames = RegisterNames32;
break;
case 0xA4: // RAX
OpRegisterNames = RegisterNames64;
break;
case 0xAE: // xmm0
OutFile.Put("xmm0");
return;
case 0xAF: // ST(0)
OutFile.Put("st(0)");
return;
case 0xB1: // 1
OutFile.Put("1");
return;
case 0xB2: // DX
OpRegisterNames = RegisterNames16;
RegI = 2;
break;
case 0xB3: // CL
OpRegisterNames = RegisterNames8;
RegI = 1;
break;
default:
OutFile.Put("unknown operand");
err.submit(3000);
return;
}
// Write register name
OutFile.Put(OpRegisterNames[RegI]);
}
void CDisassembler::WriteErrorsAndWarnings() {
// Write errors, warnings and comments, if any
uint32_t n; // Error bit
if (s.Errors) {
// There are errors
// Loop through all bits in s.Errors
for (n = 1; n; n <<= 1) {
if (s.Errors & n) {
if (OutFile.GetColumn()) OutFile.NewLine();
OutFile.Put(CommentSeparator); // Write "\n; "
OutFile.Put("Error: "); // Write "Error: "
OutFile.Put(Lookup(AsmErrorTexts,n));// Write error text
OutFile.NewLine();
}
}
}
if (s.Warnings1) {
// There are warnings 1
// Loop through all bits in s.Warnings1
for (n = 1; n; n <<= 1) {
if (s.Warnings1 & n) {
if (OutFile.GetColumn()) OutFile.NewLine();
OutFile.Put(CommentSeparator); // Write "; "
OutFile.Put("Note: "); // Write "Note: "
OutFile.Put(Lookup(AsmWarningTexts1, n));// Write warning text
OutFile.NewLine();
}
}
}
if (s.Warnings2) {
// There are warnings 2
// Loop through all bits in s.Warnings2
for (n = 1; n; n <<= 1) {
if (s.Warnings2 & n) {
if (OutFile.GetColumn()) OutFile.NewLine();
OutFile.Put(CommentSeparator); // Write "; "
OutFile.Put("Warning: "); // Write "Warning: "
OutFile.Put(Lookup(AsmWarningTexts2, n)); // Write warning text
OutFile.NewLine();
}
}
if (s.Warnings2 & 1) {
// Write spurious label
uint32_t sym1 = Symbols.FindByAddress(Section, LabelEnd);
if (sym1) {
const char * name = Symbols.GetName(sym1);
OutFile.Put(CommentSeparator);
OutFile.Put(name);
OutFile.Put("; Misplaced symbol at address ");
OutFile.PutHex(Symbols[sym1].Offset);
OutFile.NewLine();
}
}
}
if (s.OpcodeDef && (s.OpcodeDef->AllowedPrefixes & 8) && !s.Warnings1) {
if (s.Prefixes[0]) {
// Branch hint prefix. Write comment
OutFile.Put(CommentSeparator); // Write "; "
switch (s.Prefixes[0]) {
case 0x2E:
OutFile.Put("Branch hint prefix for Pentium 4: Predict no jump");
break;
case 0x3E:
OutFile.Put("Branch hint prefix for Pentium 4: Predict jump");
break;
case 0x64:
OutFile.Put("Branch hint prefix for Pentium 4: Predict alternate");
break;
default:
OutFile.Put("Note: Unrecognized branch hint prefix");
}
OutFile.NewLine();
}
}
}
void CDisassembler::WriteSymbolName(uint32_t symi) {
// Write symbol name. symi = new symbol index
OutFile.Put(Symbols.GetName(symi));
}
void CDisassembler::WriteSectionName(int32_t SegIndex) {
// Write name of section, segment or group from section index
const char * Name = 0;
// Check for special index values
switch (SegIndex) {
case ASM_SEGMENT_UNKNOWN: // Unknown segment. Typical for external symbols
Name = "Unknown"; break;
case ASM_SEGMENT_ABSOLUTE: // No segment. Used for absolute symbols
Name = "Absolute"; break;
case ASM_SEGMENT_FLAT: // Flat segment group
Name = "flat"; break;
case ASM_SEGMENT_NOTHING: // No segment
Name = "Nothing"; break;
case ASM_SEGMENT_ERROR: // Segment register assumed to error
Name = "Error"; break;
case ASM_SEGMENT_IMGREL: // Segment unknown. Offset relative to image base or file base
Name = "ImageBased"; break;
default: // > 0 means normal segment index
if ((uint32_t)SegIndex >= Sections.GetNumEntries()) {
// Out of range
Name = "IndexOutOfRange";
}
else {
// Get index into NameBuffer
uint32_t NameIndex = Sections[SegIndex].Name;
// Check if valid
if (NameIndex == 0 || NameIndex >= NameBuffer.GetDataSize()) {
Name = "ErrorNameMissing";
}
else {
// Normal valid name of segment, section or group
Name = (char*)NameBuffer.Buf() + NameIndex;
}
}
break;
}
if (Syntax == SUBTYPE_NASM && Name[0] == '_') {
// Change leading underscore to dot
OutFile.Put('.');
OutFile.Put(Name+1); // Write rest of name
}
else {
// Write name
OutFile.Put(Name);
}
}
void CDisassembler::WriteDataItems() {
// Write data items to output file
int LineState; // 0: Start of new line, write label
// 1: Label written if any, write data directive
// 2: Data directive written, write data
// 3: First data item written, write comma and more data
// 4: Last data item written, write comment
// 5: Comment written if any, start new line
uint32_t Pos = IBegin; // Current position
uint32_t LinePos = IBegin; // Position for beginning of output line
uint32_t BytesPerLine; // Number of bytes to write per line
uint32_t LineEnd; // Data position for end of line
uint32_t DataEnd; // End of data
uint32_t ElementSize, OldElementSize; // Size of each data element
uint32_t RelOffset; // Offset of relocation
uint32_t irel, Oldirel; // Relocation index
int64_t Value; // Inline value or addend
const char * Symname; // Symbol name
int SeparateLine; // Label is on separate line
SARelocation Rel; // Dummy relocation record
// Check if size is valid
if (DataSize == 0) DataSize = 1;
if (DataSize > 32) DataSize = 32;
// Expected end position
if (CodeMode & 3) {
// Writing data for dubious code. Make same length as code instruction
DataEnd = IEnd;
}
else {
// Regular data. End at next label
DataEnd = LabelEnd;
if (DataEnd > FunctionEnd) DataEnd = FunctionEnd;
if (DataEnd <= Pos) DataEnd = Pos + DataSize;
if (DataEnd > Sections[Section].InitSize && Pos < Sections[Section].InitSize) {
DataEnd = Sections[Section].InitSize;
}
}
// Size of each data element
ElementSize = DataSize;
// Check if packed type
if (DataType & 0xF00) {
// This is a packed vector type. Get element size
ElementSize = GetDataElementSize(DataType);
}
// Avoid sizes that are not powers of 2
if (ElementSize == 6 || ElementSize == 10) ElementSize = 2;
// Set maximum element size to 8
if (ElementSize > 8) ElementSize = 8;
// Set minimum element size to 1
if (ElementSize < 1) ElementSize = 1;
if (Pos + ElementSize > DataEnd) {
// Make sure we end at DataEnd
ElementSize = 1; BytesPerLine = 8;
LineEnd = DataEnd;
}
// Set number of bytes per line
BytesPerLine = (DataSize == 10) ? 10 : 8;
if (!(CodeMode & 3)) {
// Begin new line for each data item (except in code segment)
OutFile.NewLine();
}
LineState = 0; irel = 0;
// Check if alignment required
if (DataSize >= 16 && (DataType & 0xC00) && (DataType & 0xFF) != 0x51
&& (FlagPrevious & 0x100) < (DataSize << 4) && !(IBegin & (DataSize-1))) {
// Write align directive
WriteAlign(DataSize);
// Remember that data is aligned
FlagPrevious |= (DataSize << 4);
}
// Get symbol name for label
uint32_t sym; // Current symbol index
uint32_t sym1, sym2 = 0; // First and last symbol at current address
sym1 = Symbols.FindByAddress(Section, Pos, &sym2);
// Loop for one or more symbols at this address
for (sym = sym1; sym <= sym2; sym++) {
if (sym && Symbols[sym].Scope && !(Symbols[sym].Scope & 0x100) && !(Symbols[sym].Type & 0x80000000)) {
// Prepare for writing symbol label
Symname = Symbols.GetName(sym); // Symbol name
// Check if label needs a separate line
SeparateLine = (ElementSize != DataSize
|| Symbols[sym].Size != DataSize
|| strlen(Symname) > AsmTab1
|| sym < sym2
// || (Sections[Section].Type & 0xFF) == 3
|| ((Symbols[sym].Type+1) & 0xFE) == 0x0C);
// Write symbol label
switch (Syntax) {
case SUBTYPE_MASM:
WriteDataLabelMASM(Symname, sym, SeparateLine); break;
case SUBTYPE_NASM:
WriteDataLabelNASM(Symname, sym, SeparateLine); break;
case SUBTYPE_GASM:
WriteDataLabelGASM(Symname, sym, SeparateLine); break;
}
LineState = 1; // Label written
if (SeparateLine) {
LineState = 0;
}
}
}
if ((Sections[Section].Type & 0xFF) == 3 || Pos >= Sections[Section].InitSize) {
// This is an unitialized data (BSS) section
// Data repeat count
uint32_t DataCount = (DataEnd - Pos) / ElementSize;
if (DataCount) {
OutFile.Tabulate(AsmTab1);
// Write data directives
switch (Syntax) {
case SUBTYPE_MASM:
WriteUninitDataItemsMASM(ElementSize, DataCount); break;
case SUBTYPE_NASM:
WriteUninitDataItemsNASM(ElementSize, DataCount); break;
case SUBTYPE_GASM:
WriteUninitDataItemsGASM(ElementSize, DataCount); break;
}
// Write comment
WriteDataComment(ElementSize, Pos, Pos, 0);
OutFile.NewLine();
LineState = 0;
}
// Update data position
Pos += DataCount * ElementSize;
if (Pos < DataEnd) {
// Some odd data remain. Write as bytes
DataCount = DataEnd - Pos;
ElementSize = 1;
OutFile.Tabulate(AsmTab1);
switch (Syntax) {
case SUBTYPE_MASM:
WriteUninitDataItemsMASM(ElementSize, DataCount); break;
case SUBTYPE_NASM:
WriteUninitDataItemsNASM(ElementSize, DataCount); break;
case SUBTYPE_GASM:
WriteUninitDataItemsGASM(ElementSize, DataCount); break;
}
// Write comment
WriteDataComment(ElementSize, Pos, Pos, 0);
OutFile.NewLine();
Pos = DataEnd;
LineState = 0;
}
}
else {
// Not a BSS section
// Label has been written, write data
// Loop for one or more elements
LinePos = Pos;
while (Pos < DataEnd) {
// Find end of line position
LineEnd = LinePos + BytesPerLine;
// Remember element size and relocation
OldElementSize = ElementSize;
Oldirel = irel;
// Check if relocation
Rel.Section = Section;
Rel.Offset = Pos;
uint32_t irel = Relocations.FindFirst(Rel);
if (irel >= Relocations.GetNumEntries() || Relocations[irel].Section != (int32_t)Section) {
// No relevant relocation
irel = 0;
}
if (irel) {
// A relocation is found
// Check relocation source
RelOffset = Relocations[irel].Offset;
if (RelOffset == Pos) {
// Relocation source is here
// Make sure the size fits and begin new line
ElementSize = Relocations[irel].Size; BytesPerLine = 8;
if (ElementSize < 1) ElementSize = WordSize / 8;
if (ElementSize < 1) ElementSize = 4;
LineEnd = Pos + ElementSize;
if (LineState > 2) LineState = 4; // Make sure we begin at new line
}
else if (RelOffset < Pos + ElementSize) {
// Relocation source begins before end of element with current ElementSize
// Change ElementSize to make sure a new element begins at relocation source
ElementSize = 1; BytesPerLine = 8;
LineEnd = RelOffset;
if (LineState > 2) LineState = 4; // Make sure we begin at new line
irel = 0;
}
else {
// Relocation is after this element
irel = 0;
}
// Check for overlapping relocations
if (irel && irel+1 < Relocations.GetNumEntries()
&& Relocations[irel+1].Section == (int32_t)Section
&& Relocations[irel+1].Offset < RelOffset + ElementSize) {
// Overlapping relocations
s.Errors |= 0x2000;
WriteErrorsAndWarnings();
LineEnd = Relocations[irel+1].Offset;
if (LineState > 2) LineState = 4; // Make sure we begin at new line
}
// Drop alignment
FlagPrevious &= ~0xF00;
}
if (irel == 0) {
// No relocation here
// Check if DataEnd would be exceeded
if (Pos + ElementSize > DataEnd) {
// Make sure we end at DataEnd unless there is a relocation source here
ElementSize = 1; BytesPerLine = 8;
LineEnd = DataEnd;
if (LineState > 2) LineState = 4; // Make sure we begin at new line
FlagPrevious &= ~0xF00; // Drop alignment
}
}
// Check if new line needed
if (LineState == 4) {
// Finish this line
if (!(CodeMode & 3)) {
WriteDataComment(OldElementSize, LinePos, Pos, Oldirel);
}
// Start new line
OutFile.NewLine();
LineState = 0;
LinePos = Pos;
continue;
}
// Tabulate
OutFile.Tabulate(AsmTab1);
if (LineState < 2) {
// Write data definition directive for appropriate size
switch (Syntax) {
case SUBTYPE_MASM:
WriteDataDirectiveMASM(ElementSize); break;
case SUBTYPE_NASM:
WriteDataDirectiveNASM(ElementSize); break;
case SUBTYPE_GASM:
WriteDataDirectiveGASM(ElementSize); break;
}
LineState = 2;
}
else if (LineState == 3) {
// Not the first element, write comma
OutFile.Put(", ");
}
// Get inline value
switch (ElementSize) {
case 1: Value = Get<int8_t>(Pos); break;
case 2: Value = Get<int16_t>(Pos); break;
case 4: Value = Get<int32_t>(Pos); break;
case 6: Value = Get<uint32_t>(Pos) + ((uint64_t)Get<uint16_t>(Pos+4) << 32); break;
case 8: Value = Get<int64_t>(Pos); break;
case 10: Value = Get<int64_t>(Pos); break;
default: Value = 0; // should not occur
}
if (irel) {
// There is a relocation here. Write the name etc.
WriteRelocationTarget(irel, 1, Value);
}
else {
// Write value
switch (ElementSize) {
case 1:
OutFile.PutHex((uint8_t)Value, 1);
break;
case 2:
OutFile.PutHex((uint16_t)Value, 1);
break;
case 4:
OutFile.PutHex((uint32_t)Value, 1);
break;
case 6:
OutFile.PutHex((uint16_t)(Value >> 32), 1);
OutFile.Put(":");
OutFile.PutHex((uint32_t)Value, 1);
break;
case 8:
OutFile.PutHex((uint64_t)Value, 1);
break;
case 10:
OutFile.Put("??");
break;
}
}
LineState = 3;
// Increment position
Pos += ElementSize;
// Check if end of line
if (Pos >= LineEnd || Pos >= DataEnd) LineState = 4;
if (LineState == 4) {
// End of line
if (!(CodeMode & 3)) {
// Write comment
WriteDataComment(ElementSize, LinePos, Pos, irel);
}
OutFile.NewLine();
LinePos = Pos;
LineState = 0;
}
}
}
// Indicate end
if (IEnd < Pos) IEnd = Pos;
if (IEnd > LabelEnd) IEnd = LabelEnd;
if (IEnd > FunctionEnd && FunctionEnd) IEnd = FunctionEnd;
// Reset FlagPrevious if not aligned
if (DataSize < 16 || (DataType & 0xFF) == 0x28) FlagPrevious = 0;
}
void CDisassembler::WriteDataLabelMASM(const char * name, uint32_t sym, int line) {
// Write label before data item, MASM syntax
// name = name of data item(s)
// sym = symbol index
// line = 1 if label is on separate line, 0 if data follows on same line
// Write name
OutFile.Put(name);
// At least one space
OutFile.Put(" ");
// Tabulate
OutFile.Tabulate(AsmTab1);
if (line) {
// Write label and type on seperate line
// Get size
uint32_t Symsize = Symbols[sym].Size;
if (Symsize == 0) Symsize = DataSize;
OutFile.Put("label ");
// Write type
switch(Symsize) {
case 1: default:
OutFile.Put("byte"); break;
case 2:
OutFile.Put("word"); break;
case 4:
OutFile.Put("dword"); break;
case 6:
OutFile.Put("fword"); break;
case 8:
OutFile.Put("qword"); break;
case 10:
OutFile.Put("tbyte"); break;
case 16:
OutFile.Put("xmmword"); break;
case 32:
OutFile.Put("ymmword"); break;
}
// Check if jump table or call table
if (((Symbols[sym].Type+1) & 0xFE) == 0x0C) {
OutFile.Tabulate(AsmTab3);
OutFile.Put(CommentSeparator);
if (Symbols[sym].DLLName) {
// DLL import
OutFile.Put("import from ");
OutFile.Put(Symbols.GetDLLName(sym));
}
else if (Symbols[sym].Type & 1) {
OutFile.Put("switch/case jump table");
}
else {
OutFile.Put("virtual table or function pointer");
}
}
// New line
OutFile.NewLine();
}
}
void CDisassembler::WriteDataLabelNASM(const char * name, uint32_t sym, int line) {
// Write label before data item, NASM syntax
// name = name of data item(s)
// sym = symbol index
// line = 1 if label is on separate line, 0 if data follows on same line
// Write name and colon
OutFile.Put(name);
OutFile.Put(": ");
// Tabulate
OutFile.Tabulate(AsmTab1);
if (line) {
// Write label on seperate line
// Write comment
OutFile.Tabulate(AsmTab3);
OutFile.Put(CommentSeparator);
// Check if jump table or call table
if (((Symbols[sym].Type+1) & 0xFE) == 0x0C) {
if (Symbols[sym].DLLName) {
// DLL import
OutFile.Put("import from ");
OutFile.Put(Symbols.GetDLLName(sym));
}
else if (Symbols[sym].Type & 1) {
OutFile.Put("switch/case jump table");
}
else {
OutFile.Put("virtual table or function pointer");
}
}
else {
// Write size
uint32_t Symsize = Symbols[sym].Size;
if (Symsize == 0) Symsize = DataSize;
switch(Symsize) {
case 1: default:
OutFile.Put("byte"); break;
case 2:
OutFile.Put("word"); break;
case 4:
OutFile.Put("dword"); break;
case 6:
OutFile.Put("fword"); break;
case 8:
OutFile.Put("qword"); break;
case 10:
OutFile.Put("tbyte"); break;
case 16:
OutFile.Put("oword"); break;
case 32:
OutFile.Put("yword"); break;
case 64:
OutFile.Put("zword"); break;
}
}
// New line
OutFile.NewLine();
}
}
void CDisassembler::WriteDataLabelGASM(const char * name, uint32_t sym, int line) {
// Write label before data item, GAS syntax
// name = name of data item(s)
// sym = symbol index
// line = 1 if label is on separate line, 0 if data follows on same line
// Write name and colon
OutFile.Put(name);
OutFile.Put(": ");
// Tabulate
OutFile.Tabulate(AsmTab1);
if (line) {
// Write label on seperate line
// Write comment
OutFile.Tabulate(AsmTab3);
OutFile.Put(CommentSeparator);
// Check if jump table or call table
if (((Symbols[sym].Type+1) & 0xFE) == 0x0C) {
if (Symbols[sym].DLLName) {
// DLL import
OutFile.Put("import from ");
OutFile.Put(Symbols.GetDLLName(sym));
}
else if (Symbols[sym].Type & 1) {
OutFile.Put("switch/case jump table");
}
else {
OutFile.Put("virtual table or function pointer");
}
}
else {
// Write size
uint32_t Symsize = Symbols[sym].Size;
if (Symsize == 0) Symsize = DataSize;
switch(Symsize) {
case 1: default:
OutFile.Put("byte"); break;
case 2:
OutFile.Put("word"); break;
case 4:
OutFile.Put("int"); break;
case 6:
OutFile.Put("farword"); break;
case 8:
OutFile.Put("qword"); break;
case 10:
OutFile.Put("tfloat"); break;
case 16:
OutFile.Put("xmmword"); break;
case 32:
OutFile.Put("ymmword"); break;
}
}
// New line
OutFile.NewLine();
}
}
void CDisassembler::WriteUninitDataItemsMASM(uint32_t size, uint32_t count) {
// Write uninitialized (BSS) data, MASM syntax
// size = size of each data element
// count = number of data elements on each line
// Write data definition directive for appropriate size
switch (size) {
case 1:
OutFile.Put("db "); break;
case 2:
OutFile.Put("dw "); break;
case 4:
OutFile.Put("dd "); break;
case 6:
OutFile.Put("df "); break;
case 8:
OutFile.Put("dq "); break;
case 10:
OutFile.Put("dt "); break;
}
OutFile.Tabulate(AsmTab2);
if (count > 1) {
// Write duplication operator
OutFile.PutDecimal(count);
OutFile.Put(" dup (?)");
}
else {
// DataCount == 1
OutFile.Put("?");
}
}
void CDisassembler::WriteUninitDataItemsNASM(uint32_t size, uint32_t count) {
// Write uninitialized (BSS) data, NASM syntax
// Write data definition directive for appropriate size
switch (size) {
case 1:
OutFile.Put("resb "); break;
case 2:
OutFile.Put("resw "); break;
case 4:
OutFile.Put("resd "); break;
case 6:
OutFile.Put("resw "); count *= 3; break;
case 8:
OutFile.Put("resq "); break;
case 10:
OutFile.Put("rest "); break;
}
OutFile.Tabulate(AsmTab2);
OutFile.PutDecimal(count);
}
void CDisassembler::WriteUninitDataItemsGASM(uint32_t size, uint32_t count) {
// Write uninitialized (BSS) data, GAS syntax
OutFile.Put(".zero");
OutFile.Tabulate(AsmTab2);
if (count != 1) {
OutFile.PutDecimal(count); OutFile.Put(" * ");
}
OutFile.PutDecimal(size);
}
void CDisassembler::WriteDataDirectiveMASM(uint32_t size) {
// Write DB, etc., MASM syntax
// Write data definition directive for appropriate size
switch (size) {
case 1: OutFile.Put("db "); break;
case 2: OutFile.Put("dw "); break;
case 4: OutFile.Put("dd "); break;
case 6: OutFile.Put("df "); break;
case 8: OutFile.Put("dq "); break;
case 10: OutFile.Put("dt "); break;
case 16: OutFile.Put("xmmword "); break;
case 32: OutFile.Put("ymmword "); break;
default: OutFile.Put("Error "); break;
}
}
void CDisassembler::WriteDataDirectiveNASM(uint32_t size) {
// Write DB, etc., NASM syntax
// Write data definition directive for appropriate size
switch (size) {
case 1: OutFile.Put("db "); break;
case 2: OutFile.Put("dw "); break;
case 4: OutFile.Put("dd "); break;
case 6: OutFile.Put("df "); break;
case 8: OutFile.Put("dq "); break;
case 10: OutFile.Put("dt "); break;
case 16: OutFile.Put("ddq "); break;
default: OutFile.Put("Error "); break;
}
}
void CDisassembler::WriteDataDirectiveGASM(uint32_t size) {
// Write DB, etc., GAS syntax
// Write data definition directive for appropriate size
switch (size) {
case 1: OutFile.Put(".byte "); break;
case 2: OutFile.Put(".short "); break;
case 4: OutFile.Put(".int "); break;
case 8: OutFile.Put(".quad "); break;
case 10: OutFile.Put(".tfloat "); break;
default: OutFile.Put("Error "); break;
}
}
void CDisassembler::WriteDataComment(uint32_t ElementSize, uint32_t LinePos, uint32_t Pos, uint32_t irel) {
// Write comment after data item
uint32_t pos1; // Position of data for comment
uint32_t RelType = 0; // Relocation type
char TextBuffer[64]; // Buffer for writing floating point number
OutFile.Tabulate(AsmTab3); // Tabulate to comment field
OutFile.Put(CommentSeparator); // Start comment
// Write address
if (SectionEnd + SectionAddress + (uint32_t)ImageBase > 0xFFFF) {
// Write 32 bit address
OutFile.PutHex(LinePos + SectionAddress + (uint32_t)ImageBase);
}
else {
// Write 16 bit address
OutFile.PutHex((uint16_t)(LinePos + SectionAddress));
}
if ((Sections[Section].Type & 0xFF) == 3 || Pos > Sections[Section].InitSize) {
// Unitialized data. Write no data
return;
}
if (irel && irel < Relocations.GetNumEntries() && Relocations[irel].Offset == LinePos) {
// Value is relocated, get relocation type
RelType = Relocations[irel].Type;
}
// Space after address
OutFile.Put(" _ ");
// Comment type depends on ElementSize and DataType
switch (ElementSize) {
case 1:
// Bytes. Write ASCII characters
for (pos1 = LinePos; pos1 < Pos; pos1++) {
// Get character
int8_t c = Get<int8_t>(pos1);
// Avoid non-printable characters
if (c < ' ' || c == 0x7F) c = '.';
// Print ASCII character
OutFile.Put(c);
}
break;
case 2:
// Words. Write as decimal
for (pos1 = LinePos; pos1 < Pos; pos1 += 2) {
if (RelType) {
OutFile.PutHex(Get<uint16_t>(pos1), 1); // Write as hexadecimal
}
else {
OutFile.PutDecimal(Get<int16_t>(pos1), 1);// Write as signed decimal
}
OutFile.Put(' ');
}
break;
case 4:
// Dwords
for (pos1 = LinePos; pos1 < Pos; pos1 += 4) {
if ((DataType & 0x47) == 0x43) {
// Write as float
sprintf(TextBuffer, "%.8G", Get<float>(pos1));
OutFile.Put(TextBuffer);
// Make sure the number has a . or E to indicate a floating point number
if (!strchr(TextBuffer,'.') && !strchr(TextBuffer,'E')) OutFile.Put(".0");
}
else if (((DataType + 1) & 0xFF) == 0x0C || RelType) {
// jump/call address or offset. Write as hexadecimal
OutFile.PutHex(Get<uint32_t>(pos1));
}
else {
// Other. Write as decimal
OutFile.PutDecimal(Get<int32_t>(pos1), 1);
}
OutFile.Put(' ');
}
break;
case 8:
// Qwords
for (pos1 = LinePos; pos1 < Pos; pos1 += 8) {
if ((DataType & 0x47) == 0x44) {
// Write as double
sprintf(TextBuffer, "%.16G", Get<double>(pos1));
OutFile.Put(TextBuffer);
// Make sure the number has a . or E to indicate a floating point number
if (!strchr(TextBuffer,'.') && !strchr(TextBuffer,'E')) OutFile.Put(".0");
}
else {
// Write as hexadecimal
OutFile.PutHex(Get<uint64_t>(pos1));
}
OutFile.Put(' ');
}
break;
case 10:
// tbyte. Many compilers do not support long doubles in sprintf. Write as bytes
for (pos1 = LinePos; pos1 < Pos; pos1++) {
OutFile.PutHex(Get<uint8_t>(pos1), 1);
}
break;
}
if (RelType) {
// Indicate relocation type
OutFile.Put(Lookup(RelocationTypeNames, RelType));
}
}
void CDisassembler::WriteRelocationTarget(uint32_t irel, uint32_t Context, int64_t Addend) {
// Write cross reference, including addend, but not including segment override and []
// irel = index into Relocations
// Context:
// 1 = Data definition
// 2 = Immediate data field in instruction
// 4 = Data address in instruction
// 8 = Near jump/call destination
// 0x10 = Far jump/call destination
// 0x100 = Self-relative address expected
// Addend: inline addend
// Implicit parameters:
// IBegin: value of '$' operator
// IEnd: reference point for self-relative addressing
// BaseReg, IndexReg
uint32_t RefFrame; // Target segment
int32_t Addend2 = 0; // Difference between '$' and reference point
// Get relocation type
uint32_t RelType = Relocations[irel].Type;
if (RelType & 0x60) {
// Inline addend is already relocated.
// Ignore addend and treat as direct relocation
RelType = 1;
Addend = 0;
}
// Get relocation size
uint32_t RelSize = Relocations[irel].Size;
// Get relocation addend
Addend += Relocations[irel].Addend;
// Get relocation target
uint32_t Target = Relocations[irel].TargetOldIndex;
// Is offset operand needed?
if (Syntax != SUBTYPE_NASM && (
((RelType & 0xB) && (Context & 2))
|| ((RelType & 8) && (Context & 0x108)))) {
// offset operator needed to convert memory operand to immediate address
OutFile.Put("offset ");
}
// Is seg operand needed?
if (RelType & 0x200) {
// seg operator needed to convert memory operand to its segment
OutFile.Put("seg ");
}
// Is explicit segment or frame needed?
if ((RelType & 0x408) && (Context & 0x11B)) {
// Write name of segment/group frame
RefFrame = Relocations[irel].RefOldIndex;
if (!RefFrame) {
// No frame. Use segment of symbol
RefFrame = Symbols[Symbols.Old2NewIndex(Target)].Section;
}
if (RefFrame && RefFrame < Sections.GetNumEntries()) {
// Write segment or group name
const char * SecName = (char*)NameBuffer.Buf()+Sections[RefFrame].Name;
OutFile.Put(SecName);
OutFile.Put(":");
}
}
// Is imagerel operator needed?
if (RelType & 4) {
// imagerel operator needed to get image-relative address
OutFile.Put("imagerel(");
}
// Adjust addend
// Adjust offset if self-relative relocation expected and found
if ((RelType & 2) && (Context & 0x108)) {
// Self-relative relocation expected and found
// Adjust by size of address field and immediate field
Addend += IEnd - Relocations[irel].Offset;
}
// Subtract self-reference if unexpected self-relative relocation
if ((RelType & 2) && !(Context & 0x108)) {
// Self-relative relocation found but not expected
// Fix difference between '$' and reference point
Addend2 = Relocations[irel].Offset - IBegin;
Addend -= Addend2;
}
// Add self-reference if self-relative relocation expected but not found
if (!(RelType & 2) && (Context & 0x108)) {
// Self-relative relocation expected but not found
// Fix difference between '$' and reference point
Addend += IEnd - IBegin;
}
if (RelType & 0x100) {
// Target is a segment
RefFrame = Symbols[Symbols.Old2NewIndex(Target)].Section;
if (RefFrame && RefFrame < Sections.GetNumEntries()) {
const char * SecName = (char*)NameBuffer.Buf()+Sections[RefFrame].Name;
OutFile.Put(SecName);
}
else {
OutFile.Put("undefined segment");
}
}
else {
// Target is a symbol
// Find target symbol
uint32_t TargetSym = Symbols.Old2NewIndex(Target);
// Check if Target is appropriate
if (((Symbols[TargetSym].Type & 0x80000000) || (int32_t)Addend)
&& !(CodeMode == 1 && s.BaseReg)) {
// Symbol is a start-of-section entry in symbol table, or has an addend
// Look for a more appropriate symbol, except if code with base register
uint32_t sym, sym1, sym2 = 0;
sym1 = Symbols.FindByAddress(Symbols[TargetSym].Section, Symbols[TargetSym].Offset + (int32_t)Addend, &sym2);
for (sym = sym1; sym && sym <= sym2; sym++) {
if (Symbols[sym].Scope && !(Symbols[sym].Type & 0x80000000)) {
// Found a better symbol name for target address
TargetSym = sym;
Addend = Addend2;
}
}
}
// Write name of target symbol
OutFile.Put(Symbols.GetName(TargetSym));
if (Syntax == SUBTYPE_GASM && (
RelType == 0x41 || RelType == 0x81 || RelType == 0x2002)) {
// make PLT entry
OutFile.Put("@PLT");
}
}
// End parenthesis if we started one
if (RelType & 4) {
OutFile.Put(")");
}
// Subtract reference point, if any
if (RelType & 0x10) {
OutFile.Put("-");
// Write name of segment/group frame
uint32_t RefPoint = Relocations[irel].RefOldIndex;
if (RefPoint) {
// Reference point name valid
OutFile.Put(Symbols.GetNameO(RefPoint));
}
else {
OutFile.Put("Reference_Point_Missing");
}
}
// Subtract self-reference if unexpected self-relative relocation
if ((RelType & 2) && !(Context & 0x108)) {
// Self-relative relocation found but not expected
OutFile.Put("-"); OutFile.Put(HereOperator);
}
// Add self-reference if self-relative relocation expected but not found
if (!(RelType & 2) && (Context & 0x108)) {
// Self-relative relocation expected but not found
OutFile.Put("+"); OutFile.Put(HereOperator);
}
// Write addend, if not zero
if (Addend) {
if (Addend < 0) {
// Negative, write "-"
OutFile.Put("-");
Addend = -Addend;
}
else {
// Positive, write "+"
OutFile.Put("+");
}
// Write value as hexadecimal
switch (RelSize) {
case 1:
OutFile.PutHex((uint8_t)Addend, 1);
break;
case 2:
OutFile.PutHex((uint16_t)Addend, 2);
break;
case 4:
OutFile.PutHex((uint32_t)Addend, 2);
break;
case 6:
OutFile.PutHex((uint16_t)(Addend >> 32), 1);
OutFile.Put(":");
OutFile.PutHex((uint32_t)Addend, 1);
break;
case 8:
OutFile.PutHex((uint64_t)Addend, 2);
break;
default:
OutFile.Put("??"); // Should not occur
break;
}
}
}
int CDisassembler::WriteFillers() {
// Check if code is a series of NOPs or other fillers.
// If so then write it as filler and return 1.
// If not, then return 0.
// Check if code is filler
if (!(OpcodeOptions & 0x40)) {
// This instruction can not be used as filler
return 0;
}
uint32_t FillerType; // Type of filler
const char * FillerName = s.OpcodeDef->Name; // Name of filler
uint32_t IFillerBegin = IBegin; // Start of filling space
uint32_t IFillerEnd; // End of filling space
// check for CC = int 3 breakpoint, 3C00 = 90 NOP, 11F = multibyte NOP
if (Opcodei == 0xCC || (Opcodei & 0xFFFE) == 0x3C00 || Opcodei == 0x11F) {
// Instruction is a NOP or int 3 breakpoint
FillerType = Opcodei;
}
else if (s.Warnings1 & 0x1000000) {
// Instruction is a LEA, MOV, etc. with same source and destination
// used as a multi-byte NOP
FillerType = 0xFFFFFFFF;
}
else {
// This instruction does something. Not a filler
return 0;
}
// Save beginning position
IFillerEnd = IEnd = IBegin;
// Loop through instructions to find all consecutive fillers
while (NextInstruction2()) {
// Parse instruction
ParseInstruction();
// Check if code is filler
if (!(OpcodeOptions & 0x40)) {
// This instruction can not be a filler
// Save position of this instruction
IFillerEnd = IBegin;
break;
}
if (Opcodei != 0xCC && (Opcodei & 0xFFFE) != 0x3C00 && Opcodei != 0x11F
&& !(s.Warnings1 & 0x1000000)) {
// Not a filler
// Save position of this instruction
IFillerEnd = IBegin;
break;
}
// If loop exits here then fillers end at end of this instruction
IFillerEnd = IEnd;
}
// Safety check
if (IFillerEnd <= IFillerBegin) return 0;
// Size of fillers
uint32_t FillerSize = IFillerEnd - IFillerBegin;
// Write size of filling space
OutFile.Put(CommentSeparator);
OutFile.Put("Filling space: ");
OutFile.PutHex(FillerSize, 2);
OutFile.NewLine();
// Write filler type
OutFile.Put(CommentSeparator);
OutFile.Put("Filler type: ");
switch (FillerType) {
case 0xCC:
FillerName = "INT 3 Debug breakpoint"; break;
case 0x3C00:
FillerName = "NOP"; break;
case 0x3C01:
FillerName = "NOP with prefixes"; break;
case 0x011F:
FillerName = "Multi-byte NOP";break;
}
OutFile.Put(FillerName);
if (FillerType == 0xFFFFFFFF) {
OutFile.Put(" with same source and destination");
}
// Write as bytes
uint32_t Pos;
for (Pos = IFillerBegin; Pos < IFillerEnd; Pos++) {
if (((Pos - IFillerBegin) & 7) == 0) {
// Start new line
OutFile.NewLine();
OutFile.Put(CommentSeparator);
OutFile.Tabulate(AsmTab1);
OutFile.Put(Syntax == SUBTYPE_GASM ? ".byte " : "db ");
}
else {
// Continue on same line
OutFile.Put(", ");
}
// Write byte value
OutFile.PutHex(Get<uint8_t>(Pos), 1);
}
// Blank line
OutFile.NewLine(); OutFile.NewLine();
// Find alignment
uint32_t Alignment = 4; // Limit to 2^4 = 16
// Check if first non-filler is aligned by this value
while (Alignment && (IFillerEnd & ((1 << Alignment) - 1))) {
// Not aligned by 2^Alignment
Alignment--;
}
if (Alignment) {
// Check if smaller alignment would do
if (Alignment > 3 && FillerSize < 1u << (Alignment-1)) {
// End is aligned by 16, but there are less than 8 filler bytes.
// Change to align 8
Alignment--;
}
// Write align directive
WriteAlign(1 << Alignment);
// Prevent writing ALIGN again
FlagPrevious &= ~1;
}
// Restore IBegin and IEnd to beginning of first non-filler instruction
IBegin = IEnd = IFillerEnd;
if (LabelInaccessible == IFillerBegin && IFillerEnd < LabelEnd) {
// Mark first instruction after filler as inaccessible
LabelInaccessible = IFillerEnd;
}
// Return success. Fillers have been written. Don't write as normal instructions
return 1;
}
void CDisassembler::WriteAlign(uint32_t a) {
// Write alignment directive
OutFile.Put(Syntax == SUBTYPE_GASM ? ".ALIGN" : "ALIGN");
OutFile.Tabulate(AsmTab1);
OutFile.PutDecimal(a);
OutFile.NewLine();
}
void CDisassembler::WriteFileBegin() {
// Write begin of file
OutFile.SetFileType(FILETYPE_ASM);
// Initial comment
OutFile.Put(CommentSeparator);
OutFile.Put("Disassembly of file: ");
OutFile.Put(cmd.InputFile);
OutFile.NewLine();
// Date and time.
// Note: will fail after year 2038 on computers that use 32-bit time_t
time_t time1 = time(0);
char * timestring = ctime(&time1);
if (timestring) {
// Remove terminating '\n' in timestring
for (char *c = timestring; *c; c++) {
if (*c < ' ') *c = 0;
}
// Write date and time as comment
OutFile.Put(CommentSeparator);
OutFile.Put(timestring);
OutFile.NewLine();
}
// Write type and mode
OutFile.Put(CommentSeparator);
OutFile.Put("Type: ");
OutFile.Put(CFileBuffer::GetFileFormatName(cmd.InputType));
OutFile.PutDecimal(WordSize);
OutFile.NewLine();
// Write syntax dialect
OutFile.Put(CommentSeparator);
OutFile.Put("Syntax: ");
switch (Syntax) {
case SUBTYPE_MASM:
OutFile.Put(WordSize < 64 ? "MASM/ML" : "MASM/ML64"); break;
case SUBTYPE_NASM:
OutFile.Put("NASM"); break;
case SUBTYPE_GASM:
OutFile.Put("GAS(Intel)"); break;
}
OutFile.NewLine();
// Write instruction set as comment
// Instruction set is at least .386 if 32 bit mode
if (InstructionSetMax < 3 && (MasmOptions & 0x200)) InstructionSetMax = 3;
// Get name of basic instruction set
const char * set0 = "";
if (InstructionSetMax < InstructionSetNamesLen) {
set0 = InstructionSetNames[InstructionSetMax];
}
// Write as comment
OutFile.Put(CommentSeparator);
OutFile.Put("Instruction set: ");
OutFile.Put(set0);
if (InstructionSetAMDMAX) {
// Get name of any AMD-specific instruction set
const char * setA = "";
switch (InstructionSetAMDMAX) {
case 1: setA = "AMD 3DNow"; break;
case 2: setA = "AMD 3DNowE"; break;
case 4: setA = "AMD SSE4a"; break;
case 5: setA = "AMD XOP"; break;
case 6: setA = "AMD FMA4"; break;
case 7: setA = "AMD TBM"; break;
}
if (*setA) {
OutFile.Put(", ");
OutFile.Put(setA);
}
}
// VIA instruction set:
if (InstructionSetOR & 0x2000) OutFile.Put(", VIA");
// Additional instruction sets:
if (WordSize > 32) OutFile.Put(", x64");
if (InstructionSetOR & 0x100) OutFile.Put(", 80x87");
if (InstructionSetOR & 0x800) OutFile.Put(", privileged instructions");
OutFile.NewLine();
if (NamesChanged) {
// Tell that symbol names have been changed
OutFile.NewLine();
OutFile.Put(CommentSeparator);
OutFile.Put("Error: symbol names contain illegal characters,");
OutFile.NewLine(); OutFile.Put(CommentSeparator);
OutFile.PutDecimal(NamesChanged);
#if ReplaceIllegalChars
OutFile.Put(" Symbol names changed");
#else
OutFile.Put(" Symbol names not changed");
#endif
OutFile.NewLine();
}
// Write syntax-specific initializations
switch (Syntax) {
case SUBTYPE_MASM:
WriteFileBeginMASM();
WritePublicsAndExternalsMASM();
break;
case SUBTYPE_NASM:
WriteFileBeginNASM();
WritePublicsAndExternalsNASMGASM();
break;
case SUBTYPE_GASM:
WriteFileBeginGASM();
WritePublicsAndExternalsNASMGASM();
break;
}
}
void CDisassembler::WriteFileBeginMASM() {
// Write MASM-specific file init
if (WordSize < 64) {
// Write instruction set directive, except for 64 bit assembler
const char * set1 = "";
switch (InstructionSetMax) {
case 0: set1 = ".8086"; break;
case 1: set1 = ".186"; break;
case 2: set1 = ".286"; break;
case 3: set1 = ".386"; break;
case 4: set1 = ".486"; break;
case 5: set1 = ".586"; break;
case 6: default:
set1 = ".686"; break;
}
// Write basic instruction set
OutFile.NewLine();
OutFile.Put(set1);
if (InstructionSetOR & 0x800) {
// Privileged. Add "p"
OutFile.Put("p");
}
OutFile.NewLine();
// Write extended instruction set
if (InstructionSetOR & 0x100) {
// Floating point
if (InstructionSetMax < 3) {
OutFile.Put(".8087"); OutFile.NewLine();
}
else if (InstructionSetMax < 5) {
OutFile.Put(".387"); OutFile.NewLine();
}
}
if (InstructionSetMax >= 0x11) {
// .xmm directive. Not differentiated between SSE, SSE2, etc.
OutFile.Put(".xmm"); OutFile.NewLine();
}
else if (InstructionSetMax >= 7) {
// .mmx directive
OutFile.Put(".mmx"); OutFile.NewLine();
}
}
if (MasmOptions & 1) {
// Need dotname option
OutFile.Put("option dotname"); OutFile.NewLine();
}
if (WordSize == 32) {
// Write .model flat if 32 bit mode
OutFile.Put(".model flat"); OutFile.NewLine();
}
// Initialize Assumes for segment registers
if (!(MasmOptions & 0x100)) {
// No 16-bit segments. Assume CS=DS=ES=SS=flat
Assumes[0]=Assumes[1]=Assumes[2]=Assumes[3] = ASM_SEGMENT_FLAT;
}
else {
// 16-bit segmented model. Segment register values unknown
Assumes[0]=Assumes[1]=Assumes[2]=Assumes[3] = ASM_SEGMENT_UNKNOWN;
}
// FS and GS assumed to ERROR
Assumes[4] = Assumes[5] = ASM_SEGMENT_ERROR;
// Write assume if FS or GS used
// This is superfluous because an assume directive will be written at first use of FS/GS
if (MasmOptions & 2) {
OutFile.Put("assume fs:nothing"); OutFile.NewLine();
}
if (MasmOptions & 4) {
OutFile.Put("assume gs:nothing"); OutFile.NewLine();
}
OutFile.NewLine(); // Blank line
}
void CDisassembler::WriteFileBeginNASM() {
// Write NASM-specific file init
OutFile.NewLine();
if (WordSize == 64) {
OutFile.Put("default rel"); OutFile.NewLine();
}
//if (InstructionSetMax >= 0x11) {OutFile.Put("%define xmmword oword"); OutFile.NewLine();}
//if (InstructionSetMax >= 0x19) {OutFile.Put("%define ymmword"); OutFile.NewLine();}
OutFile.NewLine();
}
void CDisassembler::WriteFileBeginGASM() {
// Write GAS-specific file init
OutFile.NewLine();
OutFile.Put(CommentSeparator);
OutFile.Put("Note: Uses Intel syntax with destination operand first. Remember to");
OutFile.NewLine();
OutFile.Put(CommentSeparator);
OutFile.Put("put syntax directives in the beginning and end of inline assembly:");
OutFile.NewLine();
OutFile.Put(".intel_syntax noprefix ");
OutFile.NewLine(); OutFile.NewLine();
}
void CDisassembler::WritePublicsAndExternalsMASM() {
// Write public and external symbol definitions
uint32_t i; // Loop counter
uint32_t LinesWritten = 0; // Count lines written
const char * XName; // Name of external symbols
// Loop through public symbols
for (i = 0; i < Symbols.GetNumEntries(); i++) {
if (Symbols[i].Scope & 0x1C) {
// Symbol is public
OutFile.Put("public ");
// Write name
OutFile.Put(Symbols.GetName(i));
// Check if weak or communal
if (Symbols[i].Scope & 0x18) {
// Scope is weak or communal
OutFile.Tabulate(AsmTab3);
OutFile.Put(CommentSeparator);
if (Symbols[i].Scope & 8) OutFile.Put("Note: Weak. Not supported by MASM ");
if (Symbols[i].Scope & 0x10) OutFile.Put("Note: Communal. Not supported by MASM");
}
OutFile.NewLine(); LinesWritten++;
}
}
// Blank line if anything written
if (LinesWritten) {
OutFile.NewLine();
LinesWritten = 0;
}
// Loop through external symbols
for (i = 0; i < Symbols.GetNumEntries(); i++) {
if (Symbols[i].Scope & 0x20) {
// Symbol is external
OutFile.Put("extern ");
// Get name
XName = Symbols.GetName(i);
// Check for dynamic import
if (Symbols[i].DLLName && strncmp(XName, Symbols.ImportTablePrefix, (uint32_t)strlen(Symbols.ImportTablePrefix)) == 0) {
// Remove "_imp" prefix from name
XName += (uint32_t)strlen(Symbols.ImportTablePrefix);
}
// Write name
OutFile.Put(XName);
OutFile.Put(": ");
// Write type
if ((Symbols[i].Type & 0xFE) == 0x84) {
// Far
OutFile.Put("far");
}
else if ((Symbols[i].Type & 0xF0) == 0x80 || Symbols[i].DLLName) {
// Near
OutFile.Put("near");
}
else {
// Data. Write size
switch (GetDataItemSize(Symbols[i].Type)) {
case 1: default: OutFile.Put("byte"); break;
case 2: OutFile.Put("word"); break;
case 4: OutFile.Put("dword"); break;
case 6: OutFile.Put("fword"); break;
case 8: OutFile.Put("qword"); break;
case 10: OutFile.Put("tbyte"); break;
case 16: OutFile.Put("xmmword"); break;
case 32: OutFile.Put("ymmword"); break;
}
}
// Add comment if DLL import
if (Symbols[i].DLLName) {
OutFile.Tabulate(AsmTab3);
OutFile.Put(CommentSeparator);
OutFile.Put(Symbols.GetDLLName(i));
}
// Finished line
OutFile.NewLine(); LinesWritten++;
}
}
// Blank line if anything written
if (LinesWritten) {
OutFile.NewLine();
LinesWritten = 0;
}
// Write the value of any constants
// Loop through symbols
for (i = 0; i < Symbols.GetNumEntries(); i++) {
// Local symbols included because there might be a rip-relative address to a named constant = 0
if (Symbols[i].Section == ASM_SEGMENT_ABSOLUTE /*&& (Symbols[i].Scope & 0x1C)*/) {
// Symbol is constant
// Write name
OutFile.Put(Symbols.GetName(i));
OutFile.Put(" equ ");
// Write value as hexadecimal
OutFile.PutHex(Symbols[i].Offset, 1);
// Write decimal value as comment
OutFile.Tabulate(AsmTab3);
OutFile.Put(CommentSeparator);
OutFile.PutDecimal(Symbols[i].Offset, 1);
OutFile.NewLine(); LinesWritten++;
}
}
// Blank line if anything written
if (LinesWritten) {
OutFile.NewLine();
LinesWritten = 0;
}
// Write any group definitions
int32_t GroupId, SegmentId;
// Loop through sections to search for group definitions
for (GroupId = 1; GroupId < (int32_t)Sections.GetNumEntries(); GroupId++) {
// Get section type
uint32_t SectionType = Sections[GroupId].Type;
if (SectionType & 0x800) {
// This is a segment group definition
// Count number of members
uint32_t NumMembers = 0;
// Write group name
WriteSectionName(GroupId);
// Write "group"
OutFile.Put(" "); OutFile.Tabulate(AsmTab1); OutFile.Put("GROUP ");
// Search for group members
for (SegmentId = 1; SegmentId < (int32_t)Sections.GetNumEntries(); SegmentId++) {
if (Sections[SegmentId].Group == GroupId && !(Sections[SegmentId].Type & 0x800)) {
// is this first member?
if (NumMembers++) {
// Not first member. Write comma
OutFile.Put(", ");
}
// Write group member
WriteSectionName(SegmentId);
}
}
// End line
OutFile.NewLine(); LinesWritten++;
}
}
// Blank line if anything written
if (LinesWritten) {
OutFile.NewLine();
LinesWritten = 0;
}
}
void CDisassembler::WritePublicsAndExternalsNASMGASM() {
// Write public and external symbol definitions, NASM and GAS syntax
uint32_t i; // Loop counter
uint32_t LinesWritten = 0; // Count lines written
const char * XName; // Name of external symbols
// Loop through public symbols
for (i = 0; i < Symbols.GetNumEntries(); i++) {
if (Symbols[i].Scope & 0x1C) {
// Symbol is public
if (Syntax == SUBTYPE_GASM) OutFile.Put(".");
OutFile.Put("global ");
// Write name
OutFile.Put(Symbols.GetName(i));
// Write type
if ((Symbols[i].Type & 0xF0) == 0x80) {
// Symbol is a function
if (Syntax == SUBTYPE_NASM) {
OutFile.Put(": function");
}
else if (Syntax == SUBTYPE_GASM) {
OutFile.NewLine();
OutFile.Put(".type ");
OutFile.Put(Symbols.GetName(i));
OutFile.Put(", @function");
}
}
// Check if weak or communal
if (Symbols[i].Scope & 0x18) {
// Scope is weak or communal
OutFile.Tabulate(AsmTab3);
OutFile.Put(CommentSeparator);
if (Symbols[i].Scope & 8) OutFile.Put("Note: Weak.");
if (Symbols[i].Scope & 0x10) OutFile.Put("Note: Communal.");
}
OutFile.NewLine(); LinesWritten++;
}
}
// Blank line if anything written
if (LinesWritten) {
OutFile.NewLine();
LinesWritten = 0;
}
// Loop through external symbols
for (i = 0; i < Symbols.GetNumEntries(); i++) {
if (Symbols[i].Scope & 0x20) {
// Symbol is external
if (Syntax == SUBTYPE_GASM) OutFile.Put(".");
OutFile.Put("extern ");
// Get name
XName = Symbols.GetName(i);
// Check for dynamic import
if (Symbols[i].DLLName && strncmp(XName, Symbols.ImportTablePrefix, (uint32_t)strlen(Symbols.ImportTablePrefix)) == 0) {
// Remove "_imp" prefix from name
XName += (uint32_t)strlen(Symbols.ImportTablePrefix);
}
// Write name
OutFile.Put(XName);
OutFile.Put(" ");
OutFile.Tabulate(AsmTab3);
OutFile.Put(CommentSeparator);
// Write type
if ((Symbols[i].Type & 0xFE) == 0x84) {
// Far
OutFile.Put("far");
}
else if ((Symbols[i].Type & 0xF0) == 0x80 || Symbols[i].DLLName) {
// Near
OutFile.Put("near");
}
else {
// Data. Write size
switch (GetDataItemSize(Symbols[i].Type)) {
case 1: default: OutFile.Put("byte"); break;
case 2: OutFile.Put("word"); break;
case 4: OutFile.Put("dword"); break;
case 6: OutFile.Put("fword"); break;
case 8: OutFile.Put("qword"); break;
case 10: OutFile.Put("tbyte"); break;
case 16: OutFile.Put("xmmword"); break;
case 32: OutFile.Put("ymmword"); break;
}
}
// Add comment if DLL import
if (Symbols[i].DLLName) {
OutFile.Tabulate(AsmTab3);
OutFile.Put(CommentSeparator);
OutFile.Put(Symbols.GetDLLName(i));
}
// Finished line
OutFile.NewLine(); LinesWritten++;
}
}
// Blank line if anything written
if (LinesWritten) {
OutFile.NewLine(); LinesWritten = 0;
}
// Write the value of any constants
// Loop through symbols
for (i = 0; i < Symbols.GetNumEntries(); i++) {
if (Symbols[i].Section == ASM_SEGMENT_ABSOLUTE /*&& (Symbols[i].Scope & 0x1C)*/) {
// Symbol is constant
if (Syntax == SUBTYPE_NASM) {
// Write name equ value
OutFile.Put(Symbols.GetName(i));
OutFile.Put(" equ ");
}
else {
// Gas: write .equ name, value
OutFile.Put(".equ ");
OutFile.Tabulate(AsmTab1);
OutFile.Put(Symbols.GetName(i));
OutFile.Put(", ");
}
// Write value as hexadecimal
OutFile.PutHex(Symbols[i].Offset, 1);
// Write decimal value as comment
OutFile.Tabulate(AsmTab3);
OutFile.Put(CommentSeparator);
OutFile.PutDecimal(Symbols[i].Offset, 1);
OutFile.NewLine(); LinesWritten++;
}
}
// Blank line if anything written
if (LinesWritten) {
OutFile.NewLine();
LinesWritten = 0;
}
// Write any group definitions
int32_t GroupId, SegmentId;
// Loop through sections to search for group definitions
for (GroupId = 1; GroupId < (int32_t)Sections.GetNumEntries(); GroupId++) {
// Get section type
uint32_t SectionType = Sections[GroupId].Type;
if (SectionType & 0x800) {
// This is a segment group definition
// Count number of members
uint32_t NumMembers = 0;
// Write group name
WriteSectionName(GroupId);
// Write "group"
OutFile.Put(" "); OutFile.Tabulate(AsmTab1); OutFile.Put("GROUP ");
// Search for group members
for (SegmentId = 1; SegmentId < (int32_t)Sections.GetNumEntries(); SegmentId++) {
if (Sections[SegmentId].Group == GroupId && !(Sections[SegmentId].Type & 0x800)) {
// is this first member?
if (NumMembers++) {
// Not first member. Write comma
OutFile.Put(", ");
}
// Write group member
WriteSectionName(SegmentId);
}
}
// End line
OutFile.NewLine(); LinesWritten++;
}
}
// Blank line if anything written
if (LinesWritten) {
OutFile.NewLine();
LinesWritten = 0;
}
}
void CDisassembler::WriteFileEnd() {
// Write end of file
OutFile.NewLine();
switch(Syntax) {
case SUBTYPE_MASM:
OutFile.Put("END"); break;
case SUBTYPE_GASM:
OutFile.Put(CommentSeparator);
OutFile.Put("Return to AT&T syntax with destination operand last:");
OutFile.NewLine();
OutFile.Put(".att_syntax prefix ");
OutFile.NewLine();
break;
case SUBTYPE_NASM:
break;
}
}
void CDisassembler::WriteSegmentBegin() {
// Write begin of segment
// Choose dialect
switch (Syntax) {
case SUBTYPE_MASM:
WriteSegmentBeginMASM(); break;
case SUBTYPE_NASM:
WriteSegmentBeginNASM(); break;
case SUBTYPE_GASM:
WriteSegmentBeginGASM(); break;
}
}
void CDisassembler::WriteSegmentBeginMASM() {
// Write begin of segment
OutFile.NewLine(); // Blank line
// Check if Section is valid
if (Section == 0 || Section >= Sections.GetNumEntries()) {
// Illegal segment entry
OutFile.Put("UNKNOWN SEGMENT"); OutFile.NewLine();
return;
}
// Write segment name
WriteSectionName(Section);
// Tabulate
OutFile.Put(" "); OutFile.Tabulate(AsmTab1);
// Write "segment"
OutFile.Put("SEGMENT ");
// Write alignment
switch (Sections[Section].Align) {
case 0: // 1
OutFile.Put("BYTE "); break;
case 1: // 2
OutFile.Put("WORD "); break;
case 2: // 4
OutFile.Put("DWORD "); break;
case 4: // 16
OutFile.Put("PARA "); break;
//case 8: // 256 or 4096. Definition is ambiguous!
// OutFile.Put("PAGE "); break;
default:
// Non-standard alignment
OutFile.Put("ALIGN(");
OutFile.PutDecimal(1 << Sections[Section].Align);
OutFile.Put(") ");
break;
}
if (WordSize != 64) {
// "PUBLIC" not supported by ml64 assembler
OutFile.Put("PUBLIC ");
// Write segment word size if necessary
if (MasmOptions & 0x100) {
// There is at least one 16-bit segment. Write segment word size
OutFile.Put("USE");
OutFile.PutDecimal(Sections[Section].WordSize);
OutFile.Put(" ");
}
}
// Write segment class
switch (Sections[Section].Type & 0xFF) {
case 1:
OutFile.Put("'CODE'"); break;
case 2:
OutFile.Put("'DATA'"); break;
case 3:
OutFile.Put("'BSS'"); break;
case 4:
OutFile.Put("'CONST'"); break;
default:;
// Unknown class. Write nothing
}
// Tabulate to comment
OutFile.Put(" "); OutFile.Tabulate(AsmTab3);
OutFile.Put(CommentSeparator);
// Write section number
OutFile.Put("section number ");
OutFile.PutDecimal(Section);
// New line
OutFile.NewLine();
if (Sections[Section].Type & 0x1000) {
// Communal
OutFile.Put(CommentSeparator);
OutFile.Put(" Communal section not supported by MASM");
OutFile.NewLine();
}
if (WordSize == 16 && Sections[Section].Type == 1) {
// 16 bit code segment. Write ASSUME CS: SEGMENTNAME
OutFile.Put("ASSUME ");
OutFile.Tabulate(AsmTab1);
OutFile.Put("CS:");
if (Sections[Section].Group) {
// Group name takes precedence over segment name
WriteSectionName(Sections[Section].Group);
}
else {
WriteSectionName(Section);
}
OutFile.NewLine();
Assumes[1] = Section;
}
}
void CDisassembler::WriteSegmentBeginNASM() {
// Write begin of segment
OutFile.NewLine(); // Blank line
// Check if Section is valid
if (Section == 0 || Section >= Sections.GetNumEntries()) {
// Illegal segment entry
OutFile.Put("UNKNOWN SEGMENT"); OutFile.NewLine();
return;
}
// Write SECTION directive
OutFile.Put("SECTION ");
// Write segment name
WriteSectionName(Section);
// Tabulate
OutFile.Put(" "); OutFile.Tabulate(AsmTab2);
OutFile.Put("align=");
OutFile.PutDecimal(1 << Sections[Section].Align);
if (Sections[Section].WordSize != WordSize) {
OutFile.Put(" use");
OutFile.PutDecimal(Sections[Section].WordSize);
}
if ((Sections[Section].Type & 0xFF) == 1) {
OutFile.Put(" exec");
}
else {
OutFile.Put(" noexec");
}
// Tabulate to comment
OutFile.Put(" "); OutFile.Tabulate(AsmTab3);
OutFile.Put(CommentSeparator);
// Write section number
OutFile.Put("section number ");
OutFile.PutDecimal(Section);
// Write type
OutFile.Put(", ");
switch (Sections[Section].Type & 0xFF) {
case 1: OutFile.Put("code"); break;
case 2: OutFile.Put("data"); break;
case 3: OutFile.Put("bss"); break;
case 4: OutFile.Put("const"); break;
default: OutFile.Put("unknown type: ");
OutFile.PutHex(Sections[Section].Type & 0xFF);
break;
}
// New line
OutFile.NewLine();
if (Sections[Section].Type & 0x1000) {
// Communal
OutFile.Put(CommentSeparator);
OutFile.Put(" Communal section not supported by NASM");
OutFile.NewLine();
}
}
void CDisassembler::WriteSegmentBeginGASM() {
// Write begin of segment
uint32_t Type; // Section type
OutFile.NewLine(); // Blank line
// Check if Section is valid
if (Section == 0 || Section >= Sections.GetNumEntries()) {
// Illegal segment entry
OutFile.Put("UNKNOWN SEGMENT"); OutFile.NewLine();
return;
}
// Write SECTION directive
OutFile.Put(".SECTION ");
OutFile.Tabulate(AsmTab1);
// Write segment name
WriteSectionName(Section);
// Tabulate
OutFile.Put(" "); OutFile.Tabulate(AsmTab2);
// Flags not supported by all versions of Gas. Put as comment:
OutFile.Put(CommentSeparator);
// Write flags
OutFile.Put('"');
Type = Sections[Section].Type & 0xFF;
if (Type) OutFile.Put('a'); // Allocatable
if (Type != 1 && Type != 4) OutFile.Put('w'); // Writeable
if (Type == 1) OutFile.Put('x'); // Executable
OutFile.Put('"');
if (Type) OutFile.Put(", @progbits"); // Allocatable
// Tabulate to comment
OutFile.Put(" "); OutFile.Tabulate(AsmTab3);
OutFile.Put(CommentSeparator);
// Write section number
OutFile.Put("section number ");
OutFile.PutDecimal(Section);
// Write type
OutFile.Put(", ");
switch (Sections[Section].Type & 0xFF) {
case 1: OutFile.Put("code"); break;
case 2: OutFile.Put("data"); break;
case 3: OutFile.Put("bss"); break;
case 4: OutFile.Put("const"); break;
default: OutFile.Put("unknown"); break;
}
OutFile.NewLine(); // Blank line
if (Sections[Section].Type & 0x1000) {
// Communal
OutFile.Put(CommentSeparator);
OutFile.Put(" Communal section ");
OutFile.NewLine();
}
// Write alignment
OutFile.Tabulate(AsmTab1);
OutFile.Put(".ALIGN");
OutFile.Tabulate(AsmTab2);
OutFile.PutDecimal(1 << Sections[Section].Align);
// New line
OutFile.NewLine();
}
void CDisassembler::WriteSegmentEnd() {
// Write end of segment
OutFile.NewLine();
if (Syntax != SUBTYPE_MASM) {
// Not MASM syntax, write only blank line
return;
}
// Check if Section is valid
if (Section == 0 || Section >= Sections.GetNumEntries()) {
// Illegal segment entry
OutFile.Put("UNKNOWN ENDS"); OutFile.NewLine();
return;
}
// Write segment name
const char * segname = (char*)NameBuffer.Buf() + Sections[Section].Name;
OutFile.Put(segname);
// Tabulate
OutFile.Put(" "); OutFile.Tabulate(AsmTab1);
// Write "segment"
OutFile.Put("ENDS");
// New line
OutFile.NewLine();
}
void CDisassembler::WriteFunctionBegin() {
// Write begin of function IFunction
// Check if IFunction is valid
if (IFunction == 0 || IFunction >= FunctionList.GetNumEntries()) {
// Should not occur
OutFile.Put(CommentSeparator);
OutFile.Put("Internal error: undefined function begin");
return;
}
// Get symbol old index
uint32_t symi = FunctionList[IFunction].OldSymbolIndex;
// Get symbol record
uint32_t SymI = Symbols.Old2NewIndex(symi);
OutFile.NewLine(); // Blank line
// Remember that symbol has been written
Symbols[SymI].Scope |= 0x100;
// Check alignment if preceded by NOP
if ((FlagPrevious & 1) && (IBegin & 0x0F) == 0 && Sections[Section].Align >= 4) {
WriteAlign(16);
}
if (Symbols[SymI].Name == 0) {
// Has no name. Probably only NOP fillers
return;
}
// Write function name etc.
switch (Syntax) {
case SUBTYPE_MASM:
WriteFunctionBeginMASM(SymI, Symbols[SymI].Scope); break;
case SUBTYPE_NASM:
WriteFunctionBeginNASM(SymI, Symbols[SymI].Scope); break;
case SUBTYPE_GASM:
WriteFunctionBeginGASM(SymI, Symbols[SymI].Scope); break;
}
}
void CDisassembler::WriteFunctionBeginMASM(uint32_t symi, uint32_t scope) {
// Write begin of function, MASM syntax
// Write name
WriteSymbolName(symi);
// Space
OutFile.Put(" "); OutFile.Tabulate(AsmTab1);
if (scope & 0x1C) {
// Scope is public
// Write "PROC"
OutFile.Put("PROC");
// Write "NEAR" unless 64 bit mode
if (WordSize < 64) OutFile.Put(" NEAR");
// Check if weak
if (scope & 8) {
OutFile.NewLine();
OutFile.Put(CommentSeparator);
OutFile.Put(" WEAK ");
WriteSymbolName(symi);
}
// Check if communal
if (scope & 0x10) {
OutFile.NewLine();
OutFile.Put(CommentSeparator);
OutFile.Put(" COMDEF ");
WriteSymbolName(symi);
}
}
else {
// Scope is local
OutFile.Put("LABEL NEAR");
}
// Check if Gnu indirect
if (Symbols[symi].Type & 0x40000000) {
OutFile.Put(CommentSeparator);
OutFile.Put("Gnu indirect function"); // Cannot be represented in Masm syntax
}
// End line
OutFile.NewLine();
}
void CDisassembler::WriteFunctionBeginNASM(uint32_t symi, uint32_t scope) {
// Write begin of function, NASM syntax
// Write name
WriteSymbolName(symi);
// Colon
OutFile.Put(":"); OutFile.Tabulate(AsmTab1);
if (scope & 0x1C) {
// Scope is public
// Write comment
OutFile.Put(CommentSeparator);
OutFile.Put("Function begin");
// Check if weak
if (scope & 8) {
OutFile.Put(", weak");
}
// Check if communal
if (scope & 0x10) {
OutFile.Put(", communal");
}
}
else {
// Scope is local. Write comment
OutFile.Put(CommentSeparator);
OutFile.Put("Local function");
}
// Check if Gnu indirect
if (Symbols[symi].Type & 0x40000000) {
OutFile.Put(CommentSeparator);
OutFile.Put("Gnu indirect function"); // Cannot be represented in NASM/YASM syntax
}
// End line
OutFile.NewLine();
}
void CDisassembler::WriteFunctionBeginGASM(uint32_t symi, uint32_t scope) {
// Write begin of function, GAS syntax
WriteSymbolName(symi); // Write name
OutFile.Put(":");
OutFile.Tabulate(AsmTab3); OutFile.Put(CommentSeparator);
if (scope & 3) OutFile.Put("Local ");
if (scope & 8) OutFile.Put("weak ");
if (scope & 0x10) OutFile.Put("communal ");
OutFile.Put("Function");
OutFile.NewLine();
OutFile.Tabulate(AsmTab1);
OutFile.Put(".type ");
OutFile.Tabulate(AsmTab2);
WriteSymbolName(symi); // Write name
if (Symbols[symi].Type & 0x40000000) {
OutFile.Put(", @gnu_indirect_function");
}
else {
OutFile.Put(", @function");
}
OutFile.NewLine();
}
void CDisassembler::WriteFunctionEnd() {
// Write end of function
// Check if IFunction is valid
if (IFunction == 0 || IFunction >= FunctionList.GetNumEntries()) {
// Should not occur
OutFile.Put(CommentSeparator);
OutFile.Put("Internal error: undefined function end");
return;
}
// Get symbol index
uint32_t SymOldI = FunctionList[IFunction].OldSymbolIndex;
uint32_t SymNewI = Symbols.Old2NewIndex(SymOldI);
// check scope
if (Symbols[SymNewI].Scope & 0x1C) {
// Has public scope. Write end of function
switch (Syntax) {
case SUBTYPE_MASM:
WriteFunctionEndMASM(SymNewI); break;
case SUBTYPE_NASM:
WriteFunctionEndNASM(SymNewI); break;
case SUBTYPE_GASM:
WriteFunctionEndGASM(SymNewI); break;
}
}
}
void CDisassembler::WriteFunctionEndMASM(uint32_t symi) {
// Write end of function, MASM syntax
// Write name
WriteSymbolName(symi);
// Space
OutFile.Put(" "); OutFile.Tabulate(AsmTab1);
// Write "ENDP"
OutFile.Put("ENDP");
OutFile.NewLine();
}
void CDisassembler::WriteFunctionEndNASM(uint32_t symi) {
// Write end of function, NASM syntax
// Write comment
OutFile.Put(CommentSeparator);
// Write name
WriteSymbolName(symi);
OutFile.Put(" End of function");
OutFile.NewLine();
}
void CDisassembler::WriteFunctionEndGASM(uint32_t symi){
// Write end of function, GAS syntax
// Write .size directive
OutFile.Tabulate(AsmTab1);
OutFile.Put(".size ");
OutFile.Tabulate(AsmTab2);
WriteSymbolName(symi); // Name of function
OutFile.Put(", . - ");
WriteSymbolName(symi); // Name of function
OutFile.Tabulate(AsmTab3);
OutFile.Put(CommentSeparator);
OutFile.Put("End of function is probably here");
OutFile.NewLine();
}
void CDisassembler::WriteCodeLabel(uint32_t symi) {
// Write private or public code label. symi is new symbol index
// Get scope
uint32_t Scope = Symbols[symi].Scope;
// Check scope
if (Scope & 0x100) return; // Has been written as function begin
if (Scope == 0) {
// Inaccessible. No name. Make blank line
OutFile.NewLine();
// Remember position for warning check
LabelInaccessible = IBegin;
return;
}
// Begin on new line if preceded by another symbol
if (OutFile.GetColumn()) OutFile.NewLine();
// Check alignment if preceded by NOP
if ((Scope & 0xFF) > 1 && (FlagPrevious & 1) && (IBegin & 0x0F) == 0 && Sections[Section].Align >= 4) {
WriteAlign(16);
}
switch (Syntax) {
case SUBTYPE_MASM:
WriteCodeLabelMASM(symi, Symbols[symi].Scope); break;
case SUBTYPE_NASM:
WriteCodeLabelNASM(symi, Symbols[symi].Scope); break;
case SUBTYPE_GASM:
WriteCodeLabelGASM(symi, Symbols[symi].Scope); break;
}
// Remember this has been written
Symbols[symi].Scope |= 0x100;
}
void CDisassembler::WriteCodeLabelMASM(uint32_t symi, uint32_t scope) {
// Write private or public code label, MASM syntax
if ((scope & 0xFF) > 1) {
// Scope > function local. Write as label near
// Check if extra linefeed needed
// if (!(IFunction && FunctionList[IFunction].Start == IBegin))
// New line
OutFile.NewLine();
// Write name
WriteSymbolName(symi);
// Space
OutFile.Put(" "); OutFile.Tabulate(AsmTab1);
// Write "LABEL"
OutFile.Put("LABEL");
// Write "NEAR" even 64 bit mode
OutFile.Put(" NEAR");
// New line
OutFile.NewLine();
// Check if weak
if (scope & 8) {
OutFile.Put(CommentSeparator);
OutFile.Put(" WEAK ");
WriteSymbolName(symi);
OutFile.NewLine();
}
// Check if communal
if (scope & 0x10) {
OutFile.Put(CommentSeparator);
OutFile.Put(" COMDEF ");
WriteSymbolName(symi);
OutFile.NewLine();
}
}
else {
// Symbol is local to current function. Write name with colon
if (FlagPrevious & 2) {
// Insert blank line if previous instruction was unconditional jump or return
OutFile.NewLine();
}
// Write name
WriteSymbolName(symi);
// Write ":"
OutFile.Put(":");
if (OutFile.GetColumn() > AsmTab1) {
// Past tabstop. Go to next line
OutFile.NewLine(); // New line
}
}
}
void CDisassembler::WriteCodeLabelNASM(uint32_t symi, uint32_t scope) {
// Write private or public code label, NASM syntax
if ((scope & 0xFF) > 2) {
// Scope is public
OutFile.NewLine();
// Write name
WriteSymbolName(symi);
OutFile.Put(":");
// Check if weak
if (scope & 8) {
OutFile.Put(CommentSeparator);
OutFile.Put(" weak ");
WriteSymbolName(symi);
}
// Check if communal
if (scope & 0x10) {
OutFile.Put(CommentSeparator);
OutFile.Put(" communal ");
WriteSymbolName(symi);
}
OutFile.NewLine();
}
else {
// Symbol is local to current function. Write name with colon
if (FlagPrevious & 2) {
// Insert blank line if previous instruction was unconditional jump or return
OutFile.NewLine();
}
// Write name
WriteSymbolName(symi);
// Write ":"
OutFile.Put(":");
if (OutFile.GetColumn() > AsmTab1) {
// Past tabstop. Go to next line
OutFile.NewLine(); // New line
}
}
}
void CDisassembler::WriteCodeLabelGASM(uint32_t symi, uint32_t scope) {
// Write private or public code label, GAS syntax same as NASM syntax
WriteCodeLabelNASM(symi, scope);
}
void CDisassembler::WriteAssume() {
// Write assume directive for segment register if MASM syntax
if (Syntax != SUBTYPE_MASM) return;
if (!s.AddressField) return;
int32_t SegReg, PrefixSeg; // Segment register used
uint32_t symo; // Target symbol old index
uint32_t symi; // Target symbol new index
int32_t TargetSegment; // Target segment/section
int32_t TargetGroup; // Group containing target segment
// Find which segment register is used for addressing memory operand
SegReg = 3; // DS is default
if (s.BaseReg == 4+1 || s.BaseReg == 5+1) {
// Base register is (E)BP or ESP
SegReg = 2; // SS register used unless there is a prefix
}
if (s.Prefixes[0]) {
// There is a segment prefix
PrefixSeg = GetSegmentRegisterFromPrefix();
if (PrefixSeg >= 0 && PrefixSeg <= 5) {
// Segment prefix is valid. Segment determined by segment prefix
SegReg = PrefixSeg;
}
}
// Default target segment is none
TargetSegment = TargetGroup = 0;
// Find symbol referenced by next instruction
if (s.AddressRelocation && s.AddressRelocation < Relocations.GetNumEntries()) {
symo = Relocations[s.AddressRelocation].TargetOldIndex; // Target symbol old index
if (symo) {
symi = Symbols.Old2NewIndex(symo); // Target symbol new index
if (symi) {
TargetSegment = Symbols[symi].Section; // Target segment
if (TargetSegment < 0 || TargetSegment >= (int32_t)Sections.GetNumEntries()) {
TargetSegment = 0;
}
else {
TargetGroup = Sections[TargetSegment].Group; // Group containing target segment
if (TargetGroup <= ASM_SEGMENT_ERROR || TargetGroup >= (int32_t)Sections.GetNumEntries()) {
TargetGroup = 0;
}
}
}
}
}
if (TargetSegment) {
// Target has a segment. Check if it is different from currently assumed segment
if (TargetSegment != Assumes[SegReg] && TargetGroup != Assumes[SegReg]) {
// Assume directive needed
// If segment belongs to a group then the group takes precedence
if (TargetGroup) TargetSegment = TargetGroup;
// Write assume directive
OutFile.Put("ASSUME ");
OutFile.Tabulate(AsmTab1);
OutFile.Put(RegisterNamesSeg[SegReg]); // Name of segment register used
OutFile.Put(":");
WriteSectionName(TargetSegment); // Name of segment or group referenced
OutFile.NewLine();
Assumes[SegReg] = TargetSegment;
}
}
else {
// Target segment not specified. Assumed value may be anyting but 'error'
if (Assumes[SegReg] <= ASM_SEGMENT_ERROR) {
// Segment register is assumed to 'error'. Change assume to 'nothing'
OutFile.Put("ASSUME ");
OutFile.Tabulate(AsmTab1);
OutFile.Put(RegisterNamesSeg[SegReg]); // Name of segment register used
OutFile.Put(":NOTHING");
OutFile.NewLine();
Assumes[SegReg] = ASM_SEGMENT_NOTHING;
}
}
}
void CDisassembler::WriteInstruction() {
// Write instruction and operands
uint32_t NumOperands = 0; // Number of operands written
uint32_t i; // Loop index
const char * OpName; // Opcode name
if (s.AddressFieldSize && Syntax == SUBTYPE_MASM) {
// There is a memory operand. Check if ASSUME directive needed
WriteAssume();
}
if (CodeMode & 6) {
// Code is dubious. Show as comment only
OutFile.Put(CommentSeparator); // Start comment
}
else if ((s.OpcodeDef->Options & 0x20) && s.OpcodeStart1 > IBegin) {
// Write prefixes explicitly.
// This is used for rare cases where the assembler cannot generate the prefix
OutFile.Tabulate(AsmTab1); // Tabulate
OutFile.Put(Syntax == SUBTYPE_GASM ? ".byte " : "DB ");
OutFile.Tabulate(AsmTab2); // Tabulate
for (i = IBegin; i < s.OpcodeStart1; i++) {
if (i > IBegin) OutFile.Put(", ");
OutFile.PutHex(Get<uint8_t>(i), 1);
}
OutFile.Tabulate(AsmTab3); // Tabulate
OutFile.Put(CommentSeparator);
if ((s.OpcodeDef->AllowedPrefixes & 8) && Get<uint8_t>(IBegin) == 0xF2) {
OutFile.Put("BND prefix coded explicitly"); // Comment
}
else {
OutFile.Put("Prefix coded explicitly"); // Comment
}
OutFile.NewLine();
}
if ((s.Operands[0] & 0xF0) == 0xC0 || (s.Operands[1] & 0xF0) == 0xC0) {
// String instruction or xlat instruction
WriteStringInstruction();
return;
}
OutFile.Tabulate(AsmTab1); // Tabulate
if ((s.OpcodeDef->AllowedPrefixes & 0xC40) == 0xC40) {
switch (s.Prefixes[5]) {
case 0xF2:
OutFile.Put("xacquire "); break; // xacquire prefix
case 0xF3:
OutFile.Put("xrelease "); break; // xrelease prefix
}
}
if (s.Prefixes[2]) {
OutFile.Put("lock "); // Lock prefix
}
// Get opcode name
if (s.OpcodeDef->Name) {
// Opcode name
OpName = s.OpcodeDef->Name;
// Search for opcode comment
s.OpComment = strchr(OpName, ';');
if (s.OpComment) s.OpComment++; // Point to after ';'
}
else {
OpName = "UNDEFINED"; // Undefined code with no name
s.OpComment = 0;
}
// Check prefix option
if ((s.OpcodeDef->Options & 2) && (s.Prefixes[7] & 0x30)) {
// Put prefix 'v' for VEX-prefixed instruction
OutFile.Put('v');
}
// Write opcode name
if (s.OpComment) {
// OpName string contains opcode name and comment, separated by ';'
while (*OpName != ';' && *OpName != 0) { // Write opcode name until comment
OutFile.Put(*(OpName++));
}
}
else {
OutFile.Put(OpName); // Write normal opcode name
}
// Check suffix option
if (s.OpcodeDef->Options & 1) {
// Append suffix for operand size or type to name
if ((s.OpcodeDef->AllowedPrefixes & 0x7000) == 0x1000) {
// F.P. operand size defined by W prefix bit
i = s.Prefixes[7] & 8; // W prefix bit
OutFile.Put(i ? 'd' : 's');
}
else if ((s.OpcodeDef->AllowedPrefixes & 0x7000) == 0x3000) {
// Integer or f.p. operand size defined by W prefix bit
bool f = false;
// Find out if operands are integer or f.p.
for (i = 0; i < s.MaxNumOperands; i++) {
if ((s.Operands[i] & 0xF0) == 0x40) {
f = true; break;
}
}
i = s.Prefixes[7] & 8; // W prefix bit
if (f) {
OutFile.Put(i ? 'd' : 's'); // float precision suffix
}
else {
OutFile.Put(i ? 'q' : 'd'); // integer size suffix
}
}
else if ((s.OpcodeDef->AllowedPrefixes & 0x7000) == 0x4000) {
// Integer operand size defined by W prefix bit
i = s.Prefixes[7] & 8; // W prefix bit
OutFile.Put(i ? 'w' : 'b');
}
else if ((s.OpcodeDef->AllowedPrefixes & 0x7000) == 0x5000) {
// mask register operand size defined by W prefix bit and 66 prefix
i = (s.Prefixes[7] & 8) >> 2; // W prefix bit
i |= s.Prefixes[5] != 0x66; // 66 prefix bit
OutFile.Put("bwdq"[i]);
}
else if (s.OpcodeDef->AllowedPrefixes & 0xE00) {
// F.P. operand type and size defined by prefixes
switch (s.Prefixes[5]) {
case 0: // No prefix = ps
OutFile.Put("ps"); break;
case 0x66: // 66 prefix = pd
OutFile.Put("pd"); break;
case 0xF3: // F3 prefix = ss
OutFile.Put("ss"); break;
case 0xF2: // F2 prefix = sd
OutFile.Put("sd"); break;
default:
err.submit(9000); // Should not occur
}
}
else if (s.OpcodeDef->AllowedPrefixes & 0x100){
// Integer operand size defined by prefixes
// Suffix for operand size
i = s.OperandSize / 8;
if (i <= 8) {
static const char SizeSuffixes[] = " bw d f q"; // Table of suffixes
OutFile.Put(SizeSuffixes[i]);
}
}
}
// Alternative suffix option
if (s.OpcodeDef->Options & 0x1000) {
// Append alternative suffix for vector element size to name
if ((s.OpcodeDef->AllowedPrefixes & 0x7000) == 0x3000) {
// Integer operand size defined by W prefix bit
i = ((s.Prefixes[7] & 8) + 8) * 4; // W prefix bit -> 8 / 16
OutFile.PutDecimal(i);
}
if ((s.OpcodeDef->AllowedPrefixes & 0x7000) == 0x4000) { // 32 / 64
i = (s.Prefixes[7] & 8) + 8; // W prefix bit -> 8 / 16
OutFile.PutDecimal(i);
}
}
// More suffix option
if ((s.OpcodeDef->Options & 0x400) && s.ImmediateFieldSize == 8) {
// 64 bit immediate mov
if (Syntax == SUBTYPE_GASM) OutFile.Put("abs");
}
// Space between opcode name and operands
OutFile.Put(" "); OutFile.Tabulate(AsmTab2); // Tabulate. At least one space
// Loop for all operands to write
for (i = 0; i < s.MaxNumOperands; i++) {
if (s.Operands[i] & 0xFFFF) {
// Write operand i
if (NumOperands++) {
// At least one operand before this one. Separate by ", "
OutFile.Put(", ");
}
// Write constant and jump operands
switch (s.Operands[i] & 0xF0) {
case 0x10: case 0x20: case 0x30: case 0x80:
WriteImmediateOperand(s.Operands[i]);
continue;
}
// Write register and memory operands
uint32_t optype = (s.Operands[i] >> 16) & 0x0F;
switch (optype) {
case 0: // Other type of operand
WriteOtherOperand(s.Operands[i]); break;
case 0x1: // Direct memory operand
WriteRMOperand(s.Operands[i]); break;
case 0x2: // Register operand indicated by last bits of opcode
WriteShortRegOperand(s.Operands[i]); break;
case 0x3: // Register or memory operand indicated by mod/rm bits
WriteRMOperand(s.Operands[i]); break;
case 0x4: // Register operand indicated by reg bits
WriteRegOperand(s.Operands[i]); break;
case 0x5: // Register operand indicated by dest bits of DREX byte
WriteDREXOperand(s.Operands[i]); break;
case 0x6: // Register operand indicated by VEX.vvvv bits
WriteVEXOperand(s.Operands[i], 0); break;
case 0x7: // Register operand indicated by bits 4-7 of immediate operand
WriteVEXOperand(s.Operands[i], 1); break;
case 0x8: // Register operand indicated by bits 0-3 of immediate operand
WriteVEXOperand(s.Operands[i], 2); break; // Unused. For future use
}
int isMem = optype == 3 && s.Mod != 3;
if (s.Prefixes[3] == 0x62) { // EVEX and MVEX prefix can have extra operand attributes
if (s.Prefixes[6] & 0x20) {
WriteOperandAttributeEVEX(i, isMem);
}
else {
WriteOperandAttributeMVEX(i, isMem);
}
}
if (s.Prefixes[3] == 0x62 && (i == s.MaxNumOperands - 1 || (s.Operands[i+1] & 0xFFF) < 0x40)) {
// This is the last SIMD operand
if (!(s.Operands[4] & 0x80000000)) {
s.Operands[4] |= 0x80000000; // Make sure we don't write this twice
if (s.Prefixes[6] & 0x20) {
WriteOperandAttributeEVEX(98, isMem);
}
else {
WriteOperandAttributeMVEX(98, isMem);
}
}
}
}
}
if (s.Prefixes[3] == 0x62) { // EVEX and MVEX prefix can have extra attributes after operands
if (s.Prefixes[6] & 0x20) {
WriteOperandAttributeEVEX(99, 0);
}
else {
WriteOperandAttributeMVEX(99, 0);
}
}
if (s.OpComment) {
// Write opcode comment
OutFile.Put(' ');
OutFile.Put(CommentSeparator);
OutFile.Put(s.OpComment);
}
}
void CDisassembler::WriteStringInstruction() {
// Write string instruction or xlat instruction
uint32_t NumOperands = 0; // Number of operands written
uint32_t i; // Loop index
uint32_t Segment; // Possible segment prefix
if (!(s.OpcodeDef->AllowedPrefixes & 0x1100)) {
// Operand size is 8 if operand size prefixes not allowed
s.OperandSize = 8;
}
OutFile.Tabulate(AsmTab1); // Tabulate
if (Syntax != SUBTYPE_MASM && s.Prefixes[0] && (s.OpcodeDef->AllowedPrefixes & 4)) {
// Get segment prefix
Segment = GetSegmentRegisterFromPrefix(); // Interpret segment prefix
// Write segment override
OutFile.Put(RegisterNamesSeg[Segment]);
OutFile.Put(" ");
}
// Check repeat prefix
if (s.OpcodeDef->AllowedPrefixes & 0x20) {
if (s.Prefixes[3]) {
// Repeat prefix
OutFile.Put("rep ");
}
}
else if (s.OpcodeDef->AllowedPrefixes & 0x40) {
if (s.Prefixes[3] == 0xF2) {
// repne prefix
OutFile.Put("repne ");
}
else if (s.Prefixes[3] == 0xF3) {
// repe prefix
OutFile.Put("repe ");
}
}
// Write opcode name
OutFile.Put(s.OpcodeDef->Name); // Opcode name
if (Syntax == SUBTYPE_MASM
&& (((s.OpcodeDef->AllowedPrefixes & 4) && s.Prefixes[0])
|| ((s.OpcodeDef->AllowedPrefixes & 1) && s.Prefixes[1]))) {
// Has segment or address size prefix. Must write operands explicitly
OutFile.Put(" "); // Space before operands
// Check address size for pointer registers
const char * * PointerRegisterNames;
switch (s.AddressSize) {
case 16:
PointerRegisterNames = RegisterNames16; break;
case 32:
PointerRegisterNames = RegisterNames32; break;
case 64:
PointerRegisterNames = RegisterNames64; break;
default:
PointerRegisterNames = 0; // should not occur
}
// Loop for possibly two operands
for (i = 0; i < 2; i++) {
if (s.Operands[i]) {
// Operand i defined
if (NumOperands++) {
// An operand before this one. Separate by ", "
OutFile.Put(", ");
}
if (NumOperands == 1) {
// Write operand size for first operand
switch (s.OperandSize) {
case 8:
OutFile.Put("byte "); break;
case 16:
OutFile.Put("word "); break;
case 32:
OutFile.Put("dword "); break;
case 64:
OutFile.Put("qword "); break;
}
}
// Get segment
Segment = 1; // Default segment is DS
if (s.Prefixes[0]) {
Segment = GetSegmentRegisterFromPrefix(); // Interpret segment prefix
}
if ((s.Operands[i] & 0xCF) == 0xC2) {
Segment = 0; // Segment is ES regardless of prefix for [edi] operand
}
// Write segment override
OutFile.Put(RegisterNamesSeg[Segment]);
OutFile.Put(":");
// Opening "["
OutFile.Put("[");
// Write pointer register
switch (s.Operands[i] & 0xCF) {
case 0xC0: // [bx], [ebx] or [rbx]
OutFile.Put(PointerRegisterNames[3]);
break;
case 0xC1: // [si], [esi] or [rsi]
OutFile.Put(PointerRegisterNames[6]);
break;
case 0xC2: // [di], [edi] or [rdi]
OutFile.Put(PointerRegisterNames[7]);
break;
}
// Closing "]"
OutFile.Put("]");
}
}
}
else {
// We don't have to write the operands
// Append suffix for operand size, except for xlat
if ((s.Operands[1] & 0xCF) != 0xC0) {
// Suffix for operand size
uint32_t i = s.OperandSize / 8;
if (i <= 8) {
static const char SizeSuffixes[] = " bw d q"; // Table of suffixes
OutFile.Put(SizeSuffixes[i]);
}
}
}
}
void CDisassembler::WriteCodeComment() {
// Write hex listing of instruction as comment after instruction
uint32_t i; // Index to current byte
uint32_t FieldSize; // Number of bytes in field
const char * Spacer; // Space between fields
OutFile.Tabulate(AsmTab3); // Tabulate to comment field
OutFile.Put(CommentSeparator); // Start comment
// Write address
if (SectionEnd + SectionAddress + (uint32_t)ImageBase > 0xFFFF) {
// Write 32 bit address
OutFile.PutHex(IBegin + SectionAddress + (uint32_t)ImageBase);
}
else {
// Write 16 bit address
OutFile.PutHex((uint16_t)(IBegin + SectionAddress));
}
// Space after address
OutFile.Put(" _");
// Start of instruction
i = IBegin;
// Write bytes
while (i < IEnd) {
FieldSize = 1; // Size of field to write
Spacer = " "; // Space between fields
// Spacer and FieldSize depends on fields
if (i == s.OpcodeStart1 && i > IBegin) {
Spacer = ": "; // Space between prefixes and opcode
}
if (i == s.OpcodeStart2 + 1) {
Spacer = ". "; // Space between opcode and mod/reg/rm bytes
}
if (i == s.AddressField && s.AddressFieldSize) {
Spacer = ", "; // Space before address field
FieldSize = s.AddressFieldSize;
}
if (i == s.ImmediateField && s.ImmediateFieldSize) {
Spacer = ", "; // Space before immediate operand field
FieldSize = s.ImmediateFieldSize;
}
// Write space
OutFile.Put(Spacer);
// Write byte or bytes
switch (FieldSize) {
case 1: // Write single byte
OutFile.PutHex(Get<uint8_t>(i));
break;
case 2: // Write two bytes
OutFile.PutHex(Get<uint16_t>(i));
break;
case 3: // Write three bytes (operands for "enter" instruction)
OutFile.PutHex(Get<uint16_t>(i));
OutFile.Put(", ");
OutFile.PutHex(Get<uint8_t>(i+2));
break;
case 4: // Write four bytes
if ((s.Operands[0] & 0xFE) == 0x84) {
// Far jump/call address
OutFile.PutHex(Get<uint16_t>(i));
OutFile.Put(" ");
OutFile.PutHex(Get<uint16_t>(i+2));
}
else {
// Any other 32 bit operand
OutFile.PutHex(Get<uint32_t>(i));
}
break;
case 6: // Write six bytes (far jump address)
OutFile.PutHex(Get<uint32_t>(i));
OutFile.Put(" ");
OutFile.PutHex(Get<uint16_t>(i+4));
break;
case 8: // Write eight bytes
OutFile.PutHex(Get<uint64_t>(i));
break;
}
// Search for relocation
SARelocation rel1; // Make relocation records for searching
rel1.Section = Section;
rel1.Offset = i; // rel1 marks current field in instruction
// Is there a relocation source exactly here?
int32_t irel = Relocations.Exists(rel1); // Finds relocation with source = i
if (irel > 0) {
// This field has a relocation. Indicate relocation type
// 0 = unknown, 1 = direct, 2 = self-relative, 3 = image-relative,
// 4 = segment relative, 5 = relative to arbitrary ref. point, 8 = segment address/descriptor
uint32_t RelType = Relocations[irel].Type;
if (RelType) {
OutFile.Put(Lookup(RelocationTypeNames, RelType));
}
if (Relocations[irel].Size > FieldSize) {
// Relocation has wrong size
OutFile.Put(" Misplaced relocation.");
}
}
// Point to next byte
i += FieldSize;
}
// New line
OutFile.NewLine();
}
void CDisassembler::CountInstructions() {
// Count total number of instructions defined in opcodes.cpp
// Two instructions are regarded as the same and counted as one if they
// have the same name and differ only in the bits that define register
// name, operand size, etc.
uint32_t map; // Map number
uint32_t index; // Index into map
uint32_t n; // Number of instructions with same code
uint32_t iset; // Instruction set
uint32_t instructions = 0; // Total number of instructions
uint32_t mmxinstr = 0; // Number of MMX instructions
uint32_t sseinstr = 0; // Number of SSE instructions
uint32_t sse2instr = 0; // Number of SSE2 instructions
uint32_t sse3instr = 0; // Number of SSE3 instructions
uint32_t ssse3instr = 0; // Number of SSSE3 instructions
uint32_t sse41instr = 0; // Number of SSE4.1 instructions
uint32_t sse42instr = 0; // Number of SSE4.2 instructions
uint32_t AVXinstr = 0; // Number of AVX instructions
uint32_t FMAinstr = 0; // Number of FMA3 and later instructions
uint32_t AVX2instr = 0; // Number of AVX2 instructions
uint32_t BMIinstr = 0; // Number of BMI instructions and other small instruction sets
uint32_t AVX512instr = 0; // Number of AVX-512 instructions
uint32_t AVX512FP16instr = 0; // Number of AVX512-FP16 instructions
uint32_t MICinstr = 0; // Number of MIC instructions
uint32_t AMDinstr = 0; // Number of AMD instructions
uint32_t VIAinstr = 0; // Number of AMD instructions
uint32_t privilinstr = 0; // Number of privileged instructions
uint32_t undocinstr = 0; // Number of undocumented instructions
uint32_t droppedinstr = 0; // Number of opcodes planned but never implemented
uint32_t VEXdouble = 0; // Number of instructions that have both VEX and non-VEX version
SOpcodeDef const * opcode; // Pointer to map entry
// Loop through all maps
for (map = 0; map < NumOpcodeTables1; map++) {
// Loop through each map
for (index = 0; index < OpcodeTableLength[map]; index++) {
opcode = OpcodeTables[map] + index;
if (opcode->InstructionFormat && opcode->Name
&& !opcode->TableLink && !(opcode->InstructionFormat & 0x8000)) {
// instruction is defined
if ((opcode->InstructionFormat & 0xFFF) == 3
&& index > 0 && (opcode-1)->Name
&& strcmp(opcode->Name, (opcode-1)->Name) == 0) {
// Same as previous instruction, just with another register
continue; // Don't count this
}
n = 1; // Default = one instruction per map entry
// Check if we have multiple instructions with different prefixes
if (opcode->Options & 1) {
if (opcode->AllowedPrefixes & 0x3000) {
n++; // Extra instruction with W prefix bit
}
else if (opcode->AllowedPrefixes & 0xE00) {
if (opcode->AllowedPrefixes & 0x200) n++; // Extra instruction with 66 prefix
if (opcode->AllowedPrefixes & 0x400) n++; // Extra instruction with F3 prefix
if (opcode->AllowedPrefixes & 0x800) n++; // Extra instruction with F2 prefix
}
else if (opcode->AllowedPrefixes & 0x100) {
n++; // Extra instruction with 66 prefix
if (opcode->AllowedPrefixes & 0x1000) n++;// Extra instruction with L prefix bit
}
}
if (opcode->Options & 2) VEXdouble += n; // Instructions that have both VEX and non-VEX version
instructions += n; // Count total instructions
iset = opcode->InstructionSet; // Instruction set
if (iset & 0x20000) {
droppedinstr += n; iset = 0; // Opcodes planned but never implemented
}
if (iset & 0x800) privilinstr += n; // Privileged instruction
if (opcode->InstructionFormat & 0x4000) undocinstr += n; // Undocumented instruction
switch (iset & 0x37FF) {
case 7: // MMX
mmxinstr += n; break;
case 0x11: // SSE
sseinstr += n; break;
case 0x12: // SSE2
sse2instr += n; break;
case 0x13: // SSE3
sse3instr += n; break;
case 0x14: // SSSE3
ssse3instr += n; break;
case 0x15: // SSE4.1
sse41instr += n; break;
case 0x16: // SSE4.2
sse42instr += n; break;
case 0x17: case 0x18: case 0x19: // VEX etc.
AVXinstr += n; break;
case 0x1A: case 0x1B: // FMA and later instructions
FMAinstr += n; break;
case 0x1C: // AVX2 instructions
AVX2instr += n; break;
case 0x1D: case 0x1E: // BMI and other small instruction sets
BMIinstr += n; break;
case 0x20: // AVX-512 instructions
AVX512instr += n; break;
case 0x25: // AVX512-FP16 instructions
AVX512FP16instr += n; break;
case 0x80: // MIC instructions
MICinstr += n; break;
case 0x1001: case 0x1002: case 0x1004: case 0x1005: case 0x1006: // AMD
AMDinstr += n; break;
case 0x2001: // VIA
VIAinstr += n; break;
}
}
}
}
// output result
printf("\n\nNumber of instruction opcodes supported by disassembler:\n%5i Total, including:",
instructions);
printf("\n%5i Privileged instructions", privilinstr);
printf("\n%5i MMX instructions", mmxinstr);
printf("\n%5i SSE instructions", sseinstr);
printf("\n%5i SSE2 instructions", sse2instr);
printf("\n%5i SSE3 instructions", sse3instr);
printf("\n%5i SSSE3 instructions", ssse3instr);
printf("\n%5i SSE4.1 instructions", sse41instr);
printf("\n%5i SSE4.2 instructions", sse42instr);
printf("\n%5i AVX instructions etc.", AVXinstr);
printf("\n%5i AVX2 instructions", AVX2instr);
printf("\n%5i FMA3 instructions", FMAinstr);
printf("\n%5i BMI/micsellaneous instr.", BMIinstr);
printf("\n%5i AVX512 instructions", AVX512instr);
printf("\n%5i AVX512-FP16 instructions", AVX512FP16instr);
printf("\n%5i MIC/Xeon Phi instructions", MICinstr);
printf("\n%5i AMD instructions", AMDinstr);
printf("\n%5i VIA instructions", VIAinstr);
printf("\n%5i instructions planned but never implemented in any CPU", droppedinstr);
printf("\n%5i undocumented or illegal instructions", undocinstr);
printf("\n%5i instructions have both VEX and non-VEX versions", VEXdouble);
printf("\n");
#if 0 // temporary test code
// find entries with 0x2000 prefix code
printf("\n\nInstructions with operand swap flag:\n");
// Loop through all maps
for (map = 0; map < NumOpcodeTables1; map++) {
// Loop through each map
for (index = 0; index < OpcodeTableLength[map]; index++) {
opcode = OpcodeTables[map] + index;
if ((opcode->AllowedPrefixes & 0x2000) == 0x2000) {
printf("\n%04X %02X %s", map, index, opcode->Name);
}
}
}
/*
printf("\n\nTables linked by type 0x0E:\n");
// Loop through all maps
for (map = 0; map < NumOpcodeTables1; map++) {
// Loop through each map
for (index = 0; index < OpcodeTableLength[map]; index++) {
opcode = OpcodeTables[map] + index;
if (opcode->TableLink == 0x0E) {
printf(" 0x%02X", opcode->InstructionSet);
}
}
}*/
printf("\n");
#endif
}
|