1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417
|
/* ----------------------------------------------------------------------- *
*
* Copyright 1996-2024 The NASM Authors - All Rights Reserved
* See the file AUTHORS included with the NASM distribution for
* the specific copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ----------------------------------------------------------------------- */
/*
* preproc.c macro preprocessor for the Netwide Assembler
*/
/* Typical flow of text through preproc
*
* pp_getline gets tokenized lines, either
*
* from a macro expansion
*
* or
* {
* read_line gets raw text from stdmacpos, or predef, or current input file
* tokenize converts to tokens
* }
*
* expand_mmac_params is used to expand %1 etc., unless a macro is being
* defined or a false conditional is being processed
* (%0, %1, %+1, %-1, %%foo
*
* do_directive checks for directives
*
* expand_smacro is used to expand single line macros
*
* expand_mmacro is used to expand multi-line macros
*
* detoken is used to convert the line back to text
*/
#include "compiler.h"
#include "nctype.h"
#include "nasm.h"
#include "nasmlib.h"
#include "error.h"
#include "preproc.h"
#include "hashtbl.h"
#include "quote.h"
#include "stdscan.h"
#include "eval.h"
#include "tokens.h"
#include "tables.h"
#include "listing.h"
#include "dbginfo.h"
/*
* Preprocessor execution options that can be controlled by %pragma or
* other directives. This structure is initialized to zero on each
* pass; this *must* reflect the default initial state.
*/
static struct pp_config {
bool noaliases;
bool sane_empty_expansion;
} ppconf;
/*
* Preprocessor debug-related flags
*/
static enum pp_debug_flags {
PDBG_MMACROS = 1, /* Collect mmacro information */
PDBG_SMACROS = 2, /* Collect smacro information */
PDBG_LIST_SMACROS = 4, /* Smacros to list file (list option 's') */
PDBG_INCLUDE = 8 /* Collect %include information */
} ppdbg;
/*
* Preprocessor options configured on the command line
*/
static enum preproc_opt ppopt;
typedef struct SMacro SMacro;
typedef struct MMacro MMacro;
typedef struct Context Context;
typedef struct Token Token;
typedef struct Line Line;
typedef struct Include Include;
typedef struct Cond Cond;
/*
* Map of preprocessor directives that are also preprocessor functions;
* if they are at the beginning of a line they are a function if and
* only if they are followed by a (
*/
static bool pp_op_may_be_function[PP_count];
/*
* This is the internal form which we break input lines up into.
* Typically stored in linked lists.
*
* Note that `type' serves a double meaning: TOKEN_SMAC_START_PARAMS is
* not necessarily used as-is, but is also used to encode the number
* and expansion type of substituted parameter. So in the definition
*
* %define a(x,=y) ( (x) & ~(y) )
*
* the token representing `x' will have its type changed to
* tok_smac_param(0) but the one representing `y' will be
* tok_smac_param(1); see the accessor functions below.
*
* TOKEN_INTERNAL_STR is a string which has been unquoted, but should
* be treated as if it was a quoted string. The code is free to change
* one into the other at will. TOKEN_NAKED_STR is a text token which
* should be treated as a string, but which MUST NOT be turned into a
* quoted string. TOKEN_INTERNAL_STRs can contain any character,
* including NUL, but TOKEN_NAKED_STR must be a valid C string.
*/
static inline enum token_type tok_smac_param(int param)
{
return TOKEN_SMAC_START_PARAMS + param;
}
static int smac_nparam(enum token_type toktype)
{
return toktype - TOKEN_SMAC_START_PARAMS;
}
static bool is_smac_param(enum token_type toktype)
{
return toktype >= TOKEN_SMAC_START_PARAMS;
}
/*
* This is tuned so struct Token should be 64 bytes on 64-bit
* systems and 32 bytes on 32-bit systems. It enables them
* to be nicely cache aligned, and the text to still be kept
* inline for nearly all tokens.
*
* We prohibit tokens of length > MAX_TEXT even though
* length here is an unsigned int; this avoids problems
* if the length is passed through an interface with type "int",
* and is absurdly large anyway.
*
* Earlier versions of the source code incorrectly stated that
* examining the text string alone can be unconditionally valid. This
* is incorrect, as some token types strip parts of the string,
* e.g. indirect tokens.
*/
#define INLINE_TEXT (7*sizeof(char *)-sizeof(enum token_type)-sizeof(unsigned int)-1)
#define MAX_TEXT (INT_MAX-2)
struct Token {
Token *next;
enum token_type type;
unsigned int len;
union {
char a[INLINE_TEXT+1];
struct {
char pad[INLINE_TEXT+1 - sizeof(char *)];
char *ptr;
} p;
} text;
};
/*
* Note on the storage of both SMacro and MMacros: the hash table
* indexes them case-insensitively, and we then have to go through a
* linked list of potential case aliases (and, for MMacros, parameter
* ranges); this is to preserve the matching semantics of the earlier
* code. If the number of case aliases for a specific macro is a
* performance issue, you may want to reconsider your coding style.
*/
/*
* Function call tp obtain the expansion of an smacro
*/
typedef Token *(*ExpandSMacro)(const SMacro *s, Token **params, int nparams);
/*
* Store the definition of a single-line macro.
*
* Note: for user-defined macros, SPARM_VARADIC and SPARM_DEFAULT are
* currently never set, and SPARM_OPTIONAL is set if and only
* if SPARM_GREEDY is set.
*/
enum sparmflags {
SPARM_PLAIN = 0,
SPARM_EVAL = 1, /* Evaluate as a numeric expression (=) */
SPARM_STR = 2, /* Convert to quoted string ($) */
SPARM_NOSTRIP = 4, /* Don't strip braces (!) */
SPARM_GREEDY = 8, /* Greedy final parameter (+) */
SPARM_VARADIC = 16, /* Any number of separate arguments */
SPARM_OPTIONAL = 32, /* Optional argument */
SPARM_CONDQUOTE = 64, /* With SPARM_STR, don't re-quote a string */
SPARM_UNSIGNED = 128 /* With SPARM_EVAL, generate unsigned numbers */
};
struct smac_param {
Token name;
enum sparmflags flags;
char radix; /* Radix type for SPARM_EVAL */
const Token *def; /* Default, if any */
};
struct SMacro {
SMacro *next; /* MUST BE FIRST - see free_smacro() */
char *name;
Token *expansion;
ExpandSMacro expand;
intorptr expandpvt;
struct smac_param *params;
int nparam; /* length of the params structure */
int nparam_min; /* allows < nparam arguments */
int in_progress;
bool recursive;
bool varadic; /* greedy or supports > nparam arguments */
bool casesense;
bool alias; /* This is an alias macro */
};
/*
* "No listing" flags. Inside a loop (%rep..%endrep) we may have
* macro listing suppressed with .nolist, but we still need to
* update line numbers for error messages and debug information...
* unless we are nested inside an actual .nolist macro.
*/
enum nolist_flags {
NL_LIST = 1, /* Suppress list output */
NL_LINE = 2 /* Don't update line information */
};
/*
* Store the definition of a multi-line macro. This is also used to
* store the interiors of `%rep...%endrep' blocks, which are
* effectively self-re-invoking multi-line macros which simply
* don't have a name or bother to appear in the hash tables. %rep
* blocks are signified by having a NULL `name' field.
*
* In a MMacro describing a `%rep' block, the `in_progress' field
* isn't merely boolean, but gives the number of repeats left to
* run.
*
* The `next' field is used for storing MMacros in hash tables; the
* `next_active' field is for stacking them on istk entries.
*
* When a MMacro is being expanded, `params', `iline', `nparam',
* `paramlen', `rotate' and `unique' are local to the invocation.
*/
/*
* Expansion stack. Note that .mmac can point back to the macro itself,
* whereas .mstk cannot.
*/
struct mstk {
MMacro *mstk; /* Any expansion, real macro or not */
MMacro *mmac; /* Highest level actual mmacro */
};
struct MMacro {
MMacro *next;
#if 0
MMacroInvocation *prev; /* previous invocation */
#endif
char *name;
int nparam_min, nparam_max;
enum nolist_flags nolist; /* is this macro listing-inhibited? */
bool casesense;
bool plus; /* is the last parameter greedy? */
bool capture_label; /* macro definition has %00; capture label */
int32_t in_progress; /* is this macro currently being expanded? */
int32_t max_depth; /* maximum number of recursive expansions allowed */
Token *dlist; /* All defaults as one list */
Token **defaults; /* Parameter default pointers */
int ndefs; /* number of default parameters */
Line *expansion;
struct mstk mstk; /* Macro expansion stack */
struct mstk dstk; /* Macro definitions stack */
Token **params; /* actual parameters */
Token *iline; /* invocation line */
struct src_location where; /* location of definition */
unsigned int nparam, rotate;
char *iname; /* name invoked as */
int *paramlen;
uint64_t unique;
uint64_t condcnt; /* number of if blocks... */
struct { /* Debug information */
struct debug_macro_def *def; /* Definition */
struct debug_macro_inv *inv; /* Current invocation (if any) */
} dbg;
};
/* Store the definition of a multi-line macro, as defined in a
* previous recursive macro expansion.
*/
#if 0
struct MMacroInvocation {
MMacroInvocation *prev; /* previous invocation */
Token **params; /* actual parameters */
Token *iline; /* invocation line */
unsigned int nparam, rotate;
int *paramlen;
uint64_t unique;
uint64_t condcnt;
};
#endif
/*
* The context stack is composed of a linked list of these.
*/
struct Context {
Context *next;
const char *name;
struct hash_table localmac;
uint64_t number;
unsigned int depth;
};
static inline const char *tok_text(const struct Token *t)
{
return (t->len <= INLINE_TEXT) ? t->text.a : t->text.p.ptr;
}
/*
* Returns a mutable pointer to the text buffer. The text can be changed,
* but the length MUST NOT CHANGE, in either direction; nor is it permitted
* to pad with null characters to create an artificially shorter string.
*/
static inline char *tok_text_buf(struct Token *t)
{
return (t->len <= INLINE_TEXT) ? t->text.a : t->text.p.ptr;
}
static inline unsigned int tok_check_len(size_t len)
{
if (unlikely(len > MAX_TEXT))
nasm_fatal("impossibly large token");
return len;
}
static inline bool tok_text_match(const struct Token *a, const struct Token *b)
{
return a->len == b->len && !memcmp(tok_text(a), tok_text(b), a->len);
}
static inline unused_func bool
tok_match(const struct Token *a, const struct Token *b)
{
return a->type == b->type && tok_text_match(a, b);
}
/* strlen() variant useful for set_text() and its variants */
static size_t tok_strlen(const char *str)
{
return strnlen(str, MAX_TEXT+1);
}
/*
* Set the text field to a copy of the given string; the length if
* not given should be obtained with tok_strlen().
*/
static Token *set_text(struct Token *t, const char *text, size_t len)
{
char *textp;
if (t->len > INLINE_TEXT)
nasm_free(t->text.p.ptr);
nasm_zero(t->text);
t->len = len = tok_check_len(len);
textp = (len > INLINE_TEXT)
? (t->text.p.ptr = nasm_malloc(len+1)) : t->text.a;
memcpy(textp, text, len);
textp[len] = '\0';
return t;
}
/*
* Set the text field to the existing pre-allocated string, either
* taking over or freeing the allocation in the process.
*/
static Token *set_text_free(struct Token *t, char *text, unsigned int len)
{
char *textp;
if (t->len > INLINE_TEXT)
nasm_free(t->text.p.ptr);
nasm_zero(t->text);
t->len = len = tok_check_len(len);
if (len > INLINE_TEXT) {
textp = t->text.p.ptr = text;
} else {
textp = memcpy(t->text.a, text, len);
nasm_free(text);
}
textp[len] = '\0';
return t;
}
/*
* Allocate a new buffer containing a copy of the text field
* of the token.
*/
static char *dup_text(const struct Token *t)
{
size_t size = t->len + 1;
char *p = nasm_malloc(size);
return memcpy(p, tok_text(t), size);
}
/*
* Multi-line macro definitions are stored as a linked list of
* these, which is essentially a container to allow several linked
* lists of Tokens.
*
* Note that in this module, linked lists are treated as stacks
* wherever possible. For this reason, Lines are _pushed_ on to the
* `expansion' field in MMacro structures, so that the linked list,
* if walked, would give the macro lines in reverse order; this
* means that we can walk the list when expanding a macro, and thus
* push the lines on to the `expansion' field in _istk_ in reverse
* order (so that when popped back off they are in the right
* order). It may seem cockeyed, and it relies on my design having
* an even number of steps in, but it works...
*
* Some of these structures, rather than being actual lines, are
* markers delimiting the end of the expansion of a given macro.
* This is for use in the cycle-tracking and %rep-handling code.
* Such structures have `finishes' non-NULL, and `first' NULL. All
* others have `finishes' NULL, but `first' may still be NULL if
* the line is blank.
*/
struct Line {
Line *next;
MMacro *finishes;
Token *first;
struct src_location where; /* Where defined */
};
/*
* To handle an arbitrary level of file inclusion, we maintain a
* stack (ie linked list) of these things.
*
* Note: when we issue a message for a continuation line, we want to
* issue it for the actual *start* of the continuation line. This means
* we need to remember how many lines to skip over for the next one.
*/
struct Include {
Include *next;
FILE *fp;
Cond *conds;
Line *expansion;
uint64_t nolist; /* Listing inhibit counter */
uint64_t noline; /* Line number update inhibit counter */
struct mstk mstk;
struct src_location where; /* Filename and current line number */
int32_t lineinc; /* Increment given by %line */
int32_t lineskip; /* Accounting for passed continuation lines */
};
/*
* File real name hash, so we don't have to re-search the include
* path for every pass (and potentially more than that if a file
* is used more than once.)
*/
struct hash_table FileHash;
/*
* Counters to trap on insane macro recursion or processing.
* Note: for smacros these count *down*, for mmacros they count *up*.
*/
struct deadman {
int64_t total; /* Total number of macros/tokens */
int64_t levels; /* Descent depth across all macros */
bool triggered; /* Already triggered, no need for error msg */
};
static struct deadman smacro_deadman, mmacro_deadman;
/*
* Conditional assembly: we maintain a separate stack of these for
* each level of file inclusion. (The only reason we keep the
* stacks separate is to ensure that a stray `%endif' in a file
* included from within the true branch of a `%if' won't terminate
* it and cause confusion: instead, rightly, it'll cause an error.)
*/
enum cond_state {
/*
* These states are for use just after %if or %elif: IF_TRUE
* means the condition has evaluated to truth so we are
* currently emitting, whereas IF_FALSE means we are not
* currently emitting but will start doing so if a %else comes
* up. In these states, all directives are admissible: %elif,
* %else and %endif. (And of course %if.)
*/
COND_IF_TRUE, COND_IF_FALSE,
/*
* These states come up after a %else: ELSE_TRUE means we're
* emitting, and ELSE_FALSE means we're not. In ELSE_* states,
* any %elif or %else will cause an error.
*/
COND_ELSE_TRUE, COND_ELSE_FALSE,
/*
* These states mean that we're not emitting now, and also that
* nothing until %endif will be emitted at all. COND_DONE is
* used when we've had our moment of emission
* and have now started seeing %elifs. COND_NEVER is used when
* the condition construct in question is contained within a
* non-emitting branch of a larger condition construct,
* or if there is an error.
*/
COND_DONE, COND_NEVER
};
struct Cond {
Cond *next;
enum cond_state state;
};
#define emitting(x) ( (x) == COND_IF_TRUE || (x) == COND_ELSE_TRUE )
/*
* These defines are used as the possible return values for do_directive
*/
#define NO_DIRECTIVE_FOUND 0
#define DIRECTIVE_FOUND 1
/*
* Condition codes. Note that we use c_ prefix not C_ because C_ is
* used in nasm.h for the "real" condition codes. At _this_ level,
* we treat CXZ and ECXZ as condition codes, albeit non-invertible
* ones, so we need a different enum...
*/
static const char * const conditions[] = {
"a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
"na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
"np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
};
enum pp_conds {
c_A, c_AE, c_B, c_BE, c_C, c_CXZ, c_E, c_ECXZ, c_G, c_GE, c_L, c_LE,
c_NA, c_NAE, c_NB, c_NBE, c_NC, c_NE, c_NG, c_NGE, c_NL, c_NLE, c_NO,
c_NP, c_NS, c_NZ, c_O, c_P, c_PE, c_PO, c_RCXZ, c_S, c_Z,
c_none = -1
};
static const enum pp_conds inverse_ccs[] = {
c_NA, c_NAE, c_NB, c_NBE, c_NC, -1, c_NE, -1, c_NG, c_NGE, c_NL, c_NLE,
c_A, c_AE, c_B, c_BE, c_C, c_E, c_G, c_GE, c_L, c_LE, c_O, c_P, c_S,
c_Z, c_NO, c_NP, c_PO, c_PE, -1, c_NS, c_NZ
};
/*
* Directive names.
*/
/* If this is a an IF, ELIF, ELSE or ENDIF keyword */
static int is_condition(enum preproc_token arg)
{
return PP_IS_COND(arg) || (arg == PP_ELSE) || (arg == PP_ENDIF);
}
static int StackSize = 4;
static const char *StackPointer = "ebp";
static int ArgOffset = 8;
static int LocalOffset = 0;
static Context *cstk;
static Include *istk;
static const struct strlist *ipath_list;
static struct strlist *deplist;
static uint64_t unique; /* unique identifier numbers */
static Line *predef = NULL;
static bool do_predef;
static enum preproc_mode pp_mode;
/*
* The current set of multi-line macros we have defined.
*/
static struct hash_table mmacros;
/*
* The current set of single-line macros we have defined.
*/
static struct hash_table smacros;
/*
* The multi-line macro we are currently defining, or the %rep
* block we are currently reading, if any.
*/
static MMacro *defining;
static uint64_t nested_mac_count;
static uint64_t nested_rep_count;
/*
* The number of macro parameters to allocate space for at a time.
*/
#define PARAM_DELTA 16
/*
* The standard macro set: defined in macros.c in a set of arrays.
* This gives our position in any macro set, while we are processing it.
* The stdmacset is an array of such macro sets.
*/
static macros_t *stdmacpos;
static macros_t **stdmacnext;
static macros_t *stdmacros[8];
static macros_t *extrastdmac;
/*
* Map of which %use packages have been loaded
*/
static bool *use_loaded;
/*
* Forward declarations.
*/
static void pp_add_stdmac(macros_t *macros);
static Token *expand_mmac_params(Token * tline);
static Token *expand_smacro(Token * tline);
static Token *expand_id(Token * tline);
static Context *get_ctx(const char *name, const char **namep);
static Token *make_tok_num(Token *next, int64_t val);
static Token *
make_tok_num_radix(Token *next, int64_t val, char radix, bool uns);
static int64_t get_tok_num(const Token *t, bool *err);
static Token *make_tok_qstr(Token *next, const char *str);
static Token *make_tok_qstr_len(Token *next, const char *str, size_t len);
static Token *make_tok_char(Token *next, char op);
static Token *new_Token(Token * next, enum token_type type,
const char *text, size_t txtlen);
static Token *new_Token_free(Token * next, enum token_type type,
char *text, size_t txtlen);
static Token *dup_Token(Token *next, const Token *src);
static Token *new_White(Token *next);
static Token *delete_Token(Token *t);
static Token *steal_Token(Token *dst, Token *src);
static const struct use_package *
get_use_pkg(Token *t, const char *dname, const char **name);
static void mark_smac_params(Token *tline, const SMacro *tmpl,
enum token_type type);
/* Safe extraction of token type */
static inline enum token_type tok_type(const Token *x)
{
return x ? x->type : TOKEN_EOS;
}
/* Safe test for token type, false on x == NULL */
static inline bool tok_is(const Token *x, enum token_type t)
{
return tok_type(x) == t;
}
/* True if token is any other kind other that "c", but not NULL */
static inline bool tok_isnt(const Token *x, enum token_type t)
{
return x && x->type != t;
}
/* Whitespace token? */
static inline bool tok_white(const Token *x)
{
return tok_is(x, TOKEN_WHITESPACE);
}
/* Skip past any whitespace */
static inline Token *skip_white(Token *x)
{
while (tok_white(x))
x = x->next;
return x;
}
/* Delete any whitespace */
static Token *zap_white(Token *x)
{
while (tok_white(x))
x = delete_Token(x);
return x;
}
/*
* Unquote a token if it is a string, and set its type to
* TOKEN_INTERNAL_STR.
*/
/*
* Common version for any kind of quoted string; see asm/quote.c for
* information about the arguments.
*/
static const char *unquote_token_anystr(Token *t, uint32_t badctl, char qstart)
{
size_t nlen, olen;
char *p;
if (t->type != TOKEN_STR)
return tok_text(t);
olen = t->len;
p = (olen > INLINE_TEXT) ? t->text.p.ptr : t->text.a;
t->len = nlen = nasm_unquote_anystr(p, NULL, badctl, qstart);
t->type = TOKEN_INTERNAL_STR;
if (olen <= INLINE_TEXT || nlen > INLINE_TEXT)
return p;
nasm_zero(t->text.a);
memcpy(t->text.a, p, nlen);
nasm_free(p);
return t->text.a;
}
/* Unquote any string, can produce any arbitrary binary output */
static const char *unquote_token(Token *t)
{
return unquote_token_anystr(t, 0, STR_NASM);
}
/*
* Same as unquote_token(), but error out if the resulting string
* contains unacceptable control characters.
*/
static const char *unquote_token_cstr(Token *t)
{
return unquote_token_anystr(t, BADCTL, STR_NASM);
}
/*
* Convert a TOKEN_INTERNAL_STR token to a quoted
* TOKEN_STR tokens.
*/
static Token *quote_any_token(Token *t);
static inline unused_func
Token *quote_token(Token *t)
{
if (likely(!tok_is(t, TOKEN_INTERNAL_STR)))
return t;
return quote_any_token(t);
}
/*
* Convert *any* kind of token to a quoted
* TOKEN_STR token.
*/
static Token *quote_any_token(Token *t)
{
size_t len = t->len;
char *p;
p = nasm_quote(tok_text(t), &len);
t->type = TOKEN_STR;
return set_text_free(t, p, len);
}
/*
* In-place reverse a list of tokens.
*/
static Token *reverse_tokens(Token *t)
{
Token *prev = NULL;
Token *next;
while (t) {
next = t->next;
t->next = prev;
prev = t;
t = next;
}
return prev;
}
/*
* getenv() variant operating on an input token
*/
static const char *pp_getenv(const Token *t, bool warn)
{
const char *txt = tok_text(t);
const char *v;
char *buf = NULL;
bool is_string = false;
if (!t)
return NULL;
switch (t->type) {
case TOKEN_ENVIRON:
txt += 2; /* Skip leading %! */
is_string = nasm_isquote(*txt);
break;
case TOKEN_STR:
is_string = true;
break;
case TOKEN_INTERNAL_STR:
case TOKEN_NAKED_STR:
case TOKEN_ID:
is_string = false;
break;
default:
return NULL;
}
if (is_string) {
buf = nasm_strdup(txt);
nasm_unquote_cstr(buf, NULL);
txt = buf;
}
v = getenv(txt);
if (warn && !v) {
/*!
*!pp-environment [on] nonexistent environment variable
*!=environment
*! warns if a nonexistent environment variable
*! is accessed using the \c{%!} preprocessor
*! construct (see \k{getenv}.) Such environment
*! variables are treated as empty (with this
*! warning issued) starting in NASM 2.15;
*! earlier versions of NASM would treat this as
*! an error.
*/
nasm_warn(WARN_PP_ENVIRONMENT,
"nonexistent environment variable `%s'", txt);
v = "";
}
if (buf)
nasm_free(buf);
return v;
}
/*
* Free a linked list of tokens.
*/
static void free_tlist(Token * list)
{
while (list)
list = delete_Token(list);
}
/*
* Free a linked list of lines.
*/
static void free_llist(Line * list)
{
Line *l, *tmp;
list_for_each_safe(l, tmp, list) {
free_tlist(l->first);
nasm_free(l);
}
}
/*
* Free an array of linked lists of tokens
*/
static void free_tlist_array(Token **array, size_t nlists)
{
Token **listp = array;
if (!array)
return;
while (nlists--)
free_tlist(*listp++);
nasm_free(array);
}
/*
* Duplicate a linked list of tokens.
*/
static Token *dup_tlist(const Token *list, Token ***tailp)
{
Token *newlist = NULL;
Token **tailpp = &newlist;
const Token *t;
list_for_each(t, list) {
Token *nt;
*tailpp = nt = dup_Token(NULL, t);
tailpp = &nt->next;
}
if (tailp) {
**tailp = newlist;
*tailp = tailpp;
}
return newlist;
}
/*
* Duplicate a linked list of tokens with a maximum count
*/
static Token *dup_tlistn(const Token *list, size_t cnt, Token ***tailp)
{
Token *newlist = NULL;
Token **tailpp = &newlist;
const Token *t;
list_for_each(t, list) {
Token *nt;
if (!cnt--)
break;
*tailpp = nt = dup_Token(NULL, t);
tailpp = &nt->next;
}
if (tailp) {
**tailp = newlist;
if (newlist)
*tailp = tailpp;
}
return newlist;
}
/*
* Duplicate a linked list of tokens in reverse order
*/
static Token *dup_tlist_reverse(const Token *list, Token *tail)
{
const Token *t;
list_for_each(t, list)
tail = dup_Token(tail, t);
return tail;
}
/*
* Append an existing tlist to a tail pointer and returns the
* updated tail pointer.
*/
static Token **steal_tlist(Token *tlist, Token **tailp)
{
*tailp = tlist;
if (!tlist)
return tailp;
list_last(tlist, tlist);
return &tlist->next;
}
/*
* Free an MMacro
*/
static void free_mmacro(MMacro * m)
{
nasm_free(m->name);
free_tlist(m->dlist);
nasm_free(m->defaults);
free_llist(m->expansion);
nasm_free(m);
}
/*
* Clear or free an SMacro
*/
static void free_smacro_members(SMacro *s)
{
if (s->params) {
int i;
for (i = 0; i < s->nparam; i++) {
if (s->params[i].name.len > INLINE_TEXT)
nasm_free(s->params[i].name.text.p.ptr);
if (s->params[i].def)
free_tlist((Token *)s->params[i].def);
}
nasm_free(s->params);
}
nasm_free(s->name);
free_tlist(s->expansion);
}
static void clear_smacro(SMacro *s)
{
free_smacro_members(s);
/* Wipe everything except the next pointer */
memset(&s->name, 0, sizeof(*s) - offsetof(SMacro, name));
}
/*
* Free an SMacro
*/
static void free_smacro(SMacro *s)
{
free_smacro_members(s);
nasm_free(s);
}
/*
* Free all currently defined macros, and free the hash tables if empty
*/
enum clear_what {
CLEAR_NONE = 0,
CLEAR_DEFINE = 1, /* Clear smacros */
CLEAR_DEFALIAS = 2, /* Clear smacro aliases */
CLEAR_ALLDEFINE = CLEAR_DEFINE|CLEAR_DEFALIAS,
CLEAR_MMACRO = 4,
CLEAR_ALL = CLEAR_ALLDEFINE|CLEAR_MMACRO
};
static void clear_smacro_table(struct hash_table *smt, enum clear_what what)
{
struct hash_iterator it;
const struct hash_node *np;
bool empty = true;
/*
* Walk the hash table and clear out anything we don't want
*/
hash_for_each(smt, it, np) {
SMacro *tmp;
SMacro *s = np->data;
SMacro **head = (SMacro **)&np->data;
list_for_each_safe(s, tmp, s) {
if (what & ((enum clear_what)s->alias + 1)) {
*head = s->next;
free_smacro(s);
} else {
empty = false;
}
}
}
/*
* Free the hash table and keys if and only if it is now empty.
* Note: we cannot free keys even for an empty list above, as that
* mucks up the hash algorithm.
*/
if (empty)
hash_free_all(smt, true);
}
static void free_smacro_table(struct hash_table *smt)
{
clear_smacro_table(smt, CLEAR_ALLDEFINE);
}
static void free_mmacro_table(struct hash_table *mmt)
{
struct hash_iterator it;
const struct hash_node *np;
hash_for_each(mmt, it, np) {
MMacro *tmp;
MMacro *m = np->data;
nasm_free((void *)np->key);
list_for_each_safe(m, tmp, m)
free_mmacro(m);
}
hash_free(mmt);
}
static void free_macros(void)
{
free_smacro_table(&smacros);
free_mmacro_table(&mmacros);
}
/*
* Initialize the hash tables
*/
static void init_macros(void)
{
}
/*
* Pop the context stack.
*/
static void ctx_pop(void)
{
Context *c = cstk;
cstk = cstk->next;
free_smacro_table(&c->localmac);
nasm_free((char *)c->name);
nasm_free(c);
}
/*
* Search for a key in the hash index; adding it if necessary
* (in which case we initialize the data pointer to NULL.)
*/
static void **
hash_findi_add(struct hash_table *hash, const char *str)
{
struct hash_insert hi;
void **r;
char *strx;
size_t l = strlen(str) + 1;
r = hash_findib(hash, str, l, &hi);
if (r)
return r;
strx = nasm_malloc(l); /* Use a more efficient allocator here? */
memcpy(strx, str, l);
return hash_add(&hi, strx, NULL);
}
/*
* Like hash_findi, but returns the data element rather than a pointer
* to it. Used only when not adding a new element, hence no third
* argument.
*/
static void *
hash_findix(struct hash_table *hash, const char *str)
{
void **p;
p = hash_findi(hash, str, NULL);
return p ? *p : NULL;
}
/*
* read line from standard macros set,
* if there no more left -- return NULL
*/
static char *line_from_stdmac(void)
{
unsigned char c;
const unsigned char *p = stdmacpos;
char *line, *q;
size_t len = 0;
if (!stdmacpos)
return NULL;
/*
* 32-126 is ASCII, 127 is end of line, 128-31 are directives
* (allowed to wrap around) corresponding to PP_* tokens 0-159.
*/
while ((c = *p++) != 127) {
uint8_t ndir = c - 128;
if (ndir < 256-96)
len += pp_directives_len[ndir] + 1;
else
len++;
}
line = nasm_malloc(len + 1);
q = line;
while ((c = *stdmacpos++) != 127) {
uint8_t ndir = c - 128;
if (ndir < 256-96) {
memcpy(q, pp_directives[ndir], pp_directives_len[ndir]);
q += pp_directives_len[ndir];
*q++ = ' ';
} else {
*q++ = c;
}
}
stdmacpos = p;
*q = '\0';
if (*stdmacpos == 127) {
/* This was the last of this particular macro set */
stdmacpos = NULL;
if (*stdmacnext) {
stdmacpos = *stdmacnext++;
} else if (do_predef) {
Line *pd, *l;
/*
* Nasty hack: here we push the contents of
* `predef' on to the top-level expansion stack,
* since this is the most convenient way to
* implement the pre-include and pre-define
* features.
*/
list_for_each(pd, predef) {
nasm_new(l);
l->next = istk->expansion;
l->first = dup_tlist(pd->first, NULL);
l->finishes = NULL;
istk->expansion = l;
}
do_predef = false;
}
}
return line;
}
/*
* Read a line from a file. Return NULL on end of file.
*/
static char *line_from_file(FILE *f)
{
int c;
unsigned int size, next;
const unsigned int delta = 512;
const unsigned int pad = 8;
bool cont = false;
char *buffer, *p;
istk->where.lineno += istk->lineskip + istk->lineinc;
src_set_linnum(istk->where.lineno);
istk->lineskip = 0;
size = delta;
p = buffer = nasm_malloc(size);
do {
c = fgetc(f);
switch (c) {
case EOF:
if (p == buffer) {
nasm_free(buffer);
return NULL;
}
c = 0;
break;
case '\r':
next = fgetc(f);
if (next != '\n')
ungetc(next, f);
if (cont) {
cont = false;
continue;
}
c = 0;
break;
case '\n':
if (cont) {
cont = false;
continue;
}
c = 0;
break;
case 032: /* ^Z = legacy MS-DOS end of file mark */
c = 0;
break;
case '\\':
next = fgetc(f);
ungetc(next, f);
if (next == '\r' || next == '\n') {
cont = true;
istk->lineskip += istk->lineinc;
continue;
}
break;
}
if (p >= (buffer + size - pad)) {
buffer = nasm_realloc(buffer, size + delta);
p = buffer + size - pad;
size += delta;
}
*p++ = c;
} while (c);
return buffer;
}
/*
* Common read routine regardless of source
*/
static char *read_line(void)
{
char *line;
FILE *f = istk->fp;
if (f)
line = line_from_file(f);
else
line = line_from_stdmac();
if (!line)
return NULL;
if (!istk->nolist)
lfmt->line(LIST_READ, istk->where.lineno, line);
return line;
}
/*
* Tokenize a line of text. This is a very simple process since we
* don't need to parse the value out of e.g. numeric tokens: we
* simply split one string into many.
*/
static Token *tokenize(const char *line)
{
enum token_type type;
Token *list = NULL;
Token *t, **tail = &list;
while (*line) {
const char *p = line;
const char *ep = NULL; /* End of token, for trimming the end */
size_t toklen;
char firstchar = *p; /* Can be used to override the first char */
if (*p == '%') {
/*
* Preprocessor construct; find the end of the token.
* Classification is handled later, because %{...} can be
* used to create any preprocessor token.
*/
p++;
if (*p == '+' && !nasm_isdigit(p[1])) {
/* Paste token */
p++;
} else if (nasm_isdigit(*p) ||
((*p == '-' || *p == '+') && nasm_isdigit(p[1]))) {
do {
p++;
}
while (nasm_isdigit(*p));
} else if (*p == '{' || *p == '[') {
/* %{...} or %[...] */
char firstchar = *p;
char endchar = *p + 2; /* } or ] */
int lvl = 1;
line += (*p++ == '{'); /* Skip { but not [ (yet) */
while (lvl) {
if (*p == firstchar) {
lvl++;
} else if (*p == endchar) {
lvl--;
} else if (nasm_isquote(*p)) {
p = nasm_skip_string(p);
}
/*
* *p can have been advanced to a null character by
* nasm_skip_string()
*/
if (!*p) {
/*!
*!pp-open-brackets [on] unterminated \c{%[...]}
*! warns that a preprocessor \c{%[...]} construct
*! lacks the terminating \c{]} character.
*/
/*!
*!pp-open-braces [on] unterminated \c{%\{...\}}
*! warns that a preprocessor parameter
*! enclosed in braces \c{%\{...\}} lacks the
*! terminating \c{\}} character.
*/
nasm_warn(firstchar == '}' ?
WARN_PP_OPEN_BRACES : WARN_PP_OPEN_BRACKETS,
"unterminated %%%c...%c construct (missing `%c')",
firstchar, endchar, endchar);
break;
}
p++;
}
ep = lvl ? p : p-1; /* Terminal character not part of token */
} else if (*p == '?') {
/* %? or %?? */
p++;
if (*p == '?')
p++;
} else if (*p == '*' && p[1] == '?') {
/* %*? and %*?? */
p += 2;
if (*p == '?')
p++;
} else if (*p == '!') {
/* Environment variable reference */
p++;
if (nasm_isidchar(*p)) {
do {
p++;
}
while (nasm_isidchar(*p));
} else if (nasm_isquote(*p)) {
p = nasm_skip_string(p);
if (*p)
p++;
else
nasm_nonfatal("unterminated %%! string");
} else {
/* %! without anything else... */
}
} else if (*p == ',') {
/* Conditional comma */
p++;
} else if (nasm_isidchar(*p) ||
((*p == '%' || *p == '$') && nasm_isidchar(p[1]))) {
/* Identifier or some sort */
do {
p++;
}
while (nasm_isidchar(*p));
} else if (*p == '%') {
/* %% operator */
p++;
}
if (!ep)
ep = p;
toklen = ep - line;
/* Classify here, to handle %{...} correctly */
if (toklen < 2) {
type = '%'; /* % operator */
if (unlikely(*line == '{')) {
/*!
*!pp-empty-braces [on] empty \c{%\{\}} construct
*! warns that an empty \c{%\{\}} was encountered.
*! This expands to a single \c{%} character, which
*! is normally the \c{%} arithmetic operator.
*/
nasm_warn(WARN_PP_EMPTY_BRACES,
"empty %%{} construct expands to the %% operator");
}
} else {
char c0 = line[1];
switch (c0) {
case '+':
type = (toklen == 2) ? TOKEN_PASTE : TOKEN_MMACRO_PARAM;
break;
case '-':
type = TOKEN_MMACRO_PARAM;
break;
case '?':
if (toklen == 2)
type = TOKEN_PREPROC_Q;
else if (toklen == 3 && line[2] == '?')
type = TOKEN_PREPROC_QQ;
else
type = TOKEN_PREPROC_ID;
break;
case '*':
type = TOKEN_OTHER;
if (line[2] == '?') {
if (toklen == 3)
type = TOKEN_PREPROC_SQ;
else if (toklen == 4 && line[3] == '?')
type = TOKEN_PREPROC_SQQ;
}
break;
case '!':
type = (toklen == 2) ? TOKEN_OTHER : TOKEN_ENVIRON;
break;
case '%':
type = (toklen == 2) ? TOKEN_SMOD : TOKEN_LOCAL_SYMBOL;
break;
case '$':
type = (toklen == 2) ? TOKEN_OTHER : TOKEN_LOCAL_MACRO;
break;
case '[':
line += 2; /* Skip %[ */
firstchar = *line; /* Don't clobber */
toklen -= 2;
type = TOKEN_INDIRECT;
break;
case ',':
type = (toklen == 2) ? TOKEN_COND_COMMA : TOKEN_PREPROC_ID;
break;
case '\'':
case '\"':
case '`':
/* %{'string'} */
type = TOKEN_PREPROC_ID;
break;
case ':':
type = TOKEN_MMACRO_PARAM; /* %{:..} */
break;
default:
if (nasm_isdigit(c0))
type = TOKEN_MMACRO_PARAM;
else if (nasm_isidchar(c0) || toklen > 2)
type = TOKEN_PREPROC_ID;
else
type = TOKEN_OTHER;
break;
}
}
} else if (*p == '?' && !nasm_isidchar(p[1])) {
/* ? operator */
type = TOKEN_QMARK;
p++;
} else if (nasm_isidstart(*p) || (*p == '$' && nasm_isidstart(p[1]))) {
/*
* A regular identifier. This includes keywords which are not
* special to the preprocessor.
*/
type = TOKEN_ID;
while (nasm_isidchar(*++p))
;
} else if (nasm_isquote(*p)) {
/*
* A string token.
*/
char quote = *p;
type = TOKEN_STR;
p = nasm_skip_string(p);
if (*p) {
p++;
} else {
/*!
*!pp-open-string [on] unterminated string
*! warns that a quoted string without a closing quotation
*! mark was encountered during preprocessing.
*/
nasm_warn(WARN_PP_OPEN_STRING,
"unterminated string (missing `%c')", quote);
type = TOKEN_ERRSTR;
}
} else if (p[0] == '$' && p[1] == '$') {
type = TOKEN_BASE;
p += 2;
} else if (nasm_isnumstart(*p)) {
bool is_hex = false;
bool is_float = false;
bool has_e = false;
char c;
/*
* A numeric token.
*/
if (*p == '$') {
p++;
is_hex = true;
}
for (;;) {
c = *p++;
if (!is_hex && (c == 'e' || c == 'E')) {
has_e = true;
if (*p == '+' || *p == '-') {
/*
* e can only be followed by +/- if it is either a
* prefixed hex number or a floating-point number
*/
p++;
is_float = true;
}
} else if (c == 'H' || c == 'h' || c == 'X' || c == 'x') {
is_hex = true;
} else if (c == 'P' || c == 'p') {
is_float = true;
if (*p == '+' || *p == '-')
p++;
} else if (nasm_isnumchar(c))
; /* just advance */
else if (c == '.') {
/*
* we need to deal with consequences of the legacy
* parser, like "1.nolist" being two tokens
* (TOKEN_NUM, TOKEN_ID) here; at least give it
* a shot for now. In the future, we probably need
* a flex-based scanner with proper pattern matching
* to do it as well as it can be done. Nothing in
* the world is going to help the person who wants
* 0x123.p16 interpreted as two tokens, though.
*/
const char *r = p;
while (*r == '_')
r++;
if (nasm_isdigit(*r) || (is_hex && nasm_isxdigit(*r)) ||
(!is_hex && (*r == 'e' || *r == 'E')) ||
(*r == 'p' || *r == 'P')) {
p = r;
is_float = true;
} else
break; /* Terminate the token */
} else
break;
}
p--; /* Point to first character beyond number */
if (p == line+1 && *line == '$') {
type = TOKEN_HERE;
} else {
if (has_e && !is_hex) {
/* 1e13 is floating-point, but 1e13h is not */
is_float = true;
}
type = is_float ? TOKEN_FLOAT : TOKEN_NUM;
}
} else if (nasm_isspace(*p)) {
firstchar = ' '; /* Always a single space */
type = TOKEN_WHITESPACE;
p = nasm_skip_spaces(p);
/*
* Whitespace just before end-of-line is discarded by
* pretending it's a comment; whitespace just before a
* comment gets lumped into the comment.
*/
if (!*p || *p == ';')
type = TOKEN_EOS;
} else if (*p == ';') {
type = TOKEN_EOS;
} else {
/*
* Anything else is an operator of some kind. We check
* for all the double-character operators (>>, <<, //,
* %%, <=, >=, ==, !=, <>, &&, ||, ^^) and the triple-
* character operators (<<<, >>>, <=>) but anything
* else is a single-character operator.
*/
type = (unsigned char)*p;
switch (*p++) {
case '>':
if (*p == '>') {
p++;
type = TOKEN_SHR;
if (*p == '>') {
type = TOKEN_SAR;
p++;
}
} else if (*p == '=') {
type = TOKEN_GE;
p++;
}
break;
case '<':
if (*p == '<') {
p++;
type = TOKEN_SHL;
if (*p == '<')
p++;
} else if (*p == '=') {
p++;
type = TOKEN_LE;
if (*p == '>') {
p++;
type = TOKEN_LEG;
}
} else if (*p == '>') {
p++;
type = TOKEN_NE;
}
break;
case '!':
if (*p == '=') {
p++;
type = TOKEN_NE;
}
break;
case '/':
if (*p == '/') {
p++;
type = TOKEN_SDIV;
}
break;
case '=':
if (*p == '=')
p++; /* Still TOKEN_EQ == '=' though */
break;
case '&':
if (*p == '&') {
p++;
type = TOKEN_DBL_AND;
}
break;
case '|':
if (*p == '|') {
p++;
type = TOKEN_DBL_OR;
}
break;
case '^':
if (*p == '^') {
p++;
type = TOKEN_DBL_XOR;
}
break;
default:
break;
}
}
if (type == TOKEN_EOS)
break; /* done with the string... */
if (!ep)
ep = p;
toklen = ep - line;
if (toklen) {
*tail = t = new_Token(NULL, type, line, toklen);
*tok_text_buf(t) = firstchar; /* E.g. %{foo} -> {foo -> %foo */
tail = &t->next;
}
line = p;
}
return list;
}
/*
* Tokens are allocated in blocks to improve speed. Set the blocksize
* to 0 to use regular nasm_malloc(); this is useful for debugging.
*
* alloc_Token() returns a zero-initialized token structure.
*/
#define TOKEN_BLOCKSIZE 4096
#if TOKEN_BLOCKSIZE
static Token *freeTokens = NULL;
static Token *tokenblocks = NULL;
static Token *alloc_Token(void)
{
Token *t = freeTokens;
if (unlikely(!t)) {
Token *block;
size_t i;
nasm_newn(block, TOKEN_BLOCKSIZE);
/*
* The first entry in each array are a linked list of
* block allocations and is not used for data.
*/
block[0].next = tokenblocks;
block[0].type = TOKEN_BLOCK;
tokenblocks = block;
/*
* Add the rest to the free list
*/
for (i = 2; i < TOKEN_BLOCKSIZE - 1; i++)
block[i].next = &block[i+1];
freeTokens = &block[2];
/*
* Return the topmost usable token
*/
return &block[1];
}
freeTokens = t->next;
t->next = NULL;
return t;
}
static Token *delete_Token(Token *t)
{
Token *next;
nasm_assert(t && t->type != TOKEN_FREE);
next = t->next;
nasm_zero(*t);
t->type = TOKEN_FREE;
t->next = freeTokens;
freeTokens = t;
return next;
}
static void delete_Blocks(void)
{
Token *block, *blocktmp;
list_for_each_safe(block, blocktmp, tokenblocks)
nasm_free(block);
freeTokens = tokenblocks = NULL;
}
#else
static inline Token *alloc_Token(void)
{
Token *t;
nasm_new(t);
return t;
}
static Token *delete_Token(Token *t)
{
Token *next = t->next;
nasm_free(t);
return next;
}
static inline void delete_Blocks(void)
{
/* Nothing to do */
}
#endif
/*
* this function creates a new Token and passes a pointer to it
* back to the caller. It sets the type, text, and next pointer elements.
*/
static Token *new_Token(Token * next, enum token_type type,
const char *text, size_t txtlen)
{
Token *t = alloc_Token();
char *textp;
t->next = next;
t->type = type;
if (type == TOKEN_WHITESPACE) {
t->len = 1;
t->text.a[0] = ' ';
} else {
if (text && text[0] && !txtlen)
txtlen = tok_strlen(text);
t->len = tok_check_len(txtlen);
if (text) {
textp = (txtlen > INLINE_TEXT)
? (t->text.p.ptr = nasm_malloc(txtlen+1)) : t->text.a;
memcpy(textp, text, txtlen);
textp[txtlen] = '\0'; /* In case we needed malloc() */
} else {
/*
* Allocate a buffer but do not fill it. The caller
* can fill in text, but must not change the length.
* The filled in text must be exactly txtlen once
* the buffer is filled and before the token is added
* to any line lists.
*/
if (txtlen > INLINE_TEXT)
t->text.p.ptr = nasm_zalloc(txtlen+1);
}
}
return t;
}
/*
* Same as new_Token(), but text belongs to the new token and is
* either taken over or freed. This function MUST be called
* with valid txt and txtlen, unlike new_Token().
*/
static Token *new_Token_free(Token * next, enum token_type type,
char *text, size_t txtlen)
{
Token *t = alloc_Token();
t->next = next;
t->type = type;
t->len = tok_check_len(txtlen);
if (txtlen <= INLINE_TEXT) {
memcpy(t->text.a, text, txtlen);
nasm_free(text);
} else {
t->text.p.ptr = text;
}
return t;
}
static Token *dup_Token(Token *next, const Token *src)
{
Token *t = alloc_Token();
memcpy(t, src, sizeof *src);
t->next = next;
if (t->len > INLINE_TEXT) {
t->text.p.ptr = nasm_malloc(t->len + 1);
memcpy(t->text.p.ptr, src->text.p.ptr, t->len+1);
}
return t;
}
static Token *new_White(Token *next)
{
Token *t = alloc_Token();
t->next = next;
t->type = TOKEN_WHITESPACE;
t->len = 1;
t->text.a[0] = ' ';
return t;
}
/*
* This *transfers* the content from one token to another, leaving the
* next pointer of the latter intact. Unlike dup_Token(), the old
* token is destroyed, except for its next pointer, and the text
* pointer allocation, if any, is simply transferred.
*/
static Token *steal_Token(Token *dst, Token *src)
{
/* Overwrite everything except the next pointers */
memcpy((char *)dst + sizeof(Token *), (char *)src + sizeof(Token *),
sizeof(Token) - sizeof(Token *));
/* Clear the donor token */
memset((char *)src + sizeof(Token *), 0, sizeof(Token) - sizeof(Token *));
return dst;
}
/*
* Convert a line of tokens back into text. This modifies the list
* by expanding environment variables.
*
* If expand_locals is not zero, identifiers of the form "%$*xxx"
* are also transformed into ..@ctxnum.xxx
*/
static char *detoken(Token * tlist, bool expand_locals)
{
Token *t;
char *line, *p;
int len = 0;
list_for_each(t, tlist) {
switch (t->type) {
case TOKEN_ENVIRON:
{
const char *v = pp_getenv(t, true);
set_text(t, v, tok_strlen(v));
t->type = TOKEN_NAKED_STR;
break;
}
case TOKEN_LOCAL_MACRO:
case TOKEN_LOCAL_SYMBOL:
if (expand_locals) {
const char *q;
char *p;
Context *ctx = get_ctx(tok_text(t), &q);
if (ctx) {
p = nasm_asprintf("..@%"PRIu64".%s", ctx->number, q);
set_text_free(t, p, nasm_last_string_len());
t->type = TOKEN_ID;
}
}
break;
case TOKEN_INDIRECT:
/*
* This won't happen in when emitting to the assembler,
* but can happen when emitting output for some of the
* list options. The token string doesn't actually include
* the brackets in this case.
*/
len += 3; /* %[] */
break;
default:
break; /* No modifications */
}
if (debug_level(2)) {
unsigned int t_len = t->len;
unsigned int s_len = tok_strlen(tok_text(t));
if (t_len != s_len) {
nasm_panic("assertion failed: token \"%s\" type %u len %u has t->len %u\n",
tok_text(t), t->type, s_len, t_len);
t->len = s_len;
}
}
len += t->len;
}
p = line = nasm_malloc(len + 1);
list_for_each(t, tlist) {
switch (t->type) {
case TOKEN_INDIRECT:
*p++ = '%';
*p++ = '[';
p = mempcpy(p, tok_text(t), t->len);
*p++ = ']';
break;
default:
p = mempcpy(p, tok_text(t), t->len);
}
}
*p = '\0';
return line;
}
/*
* A scanner, suitable for use by the expression evaluator, which
* operates on a line of Tokens. Expects a pointer to a pointer to
* the first token in the line to be passed in as its private_data
* field.
*
* FIX: This really needs to be unified with stdscan.
*/
struct ppscan {
Token *tptr;
int ntokens;
};
static int ppscan(void *private_data, struct tokenval *tokval)
{
struct ppscan *pps = private_data;
Token *tline;
const char *txt;
do {
if (pps->ntokens && (tline = pps->tptr)) {
pps->ntokens--;
pps->tptr = tline->next;
} else {
pps->tptr = NULL;
pps->ntokens = 0;
return tokval->t_type = TOKEN_EOS;
}
} while (tline->type == TOKEN_WHITESPACE);
txt = tok_text(tline);
tokval->t_charptr = (char *)txt; /* Fix this */
switch (tline->type) {
default:
return tokval->t_type = tline->type;
case TOKEN_ID:
/* This could be an assembler keyword */
return nasm_token_hash(txt, tokval);
case TOKEN_NUM:
{
bool rn_error;
tokval->t_integer = readnum(txt, &rn_error);
if (rn_error)
return tokval->t_type = TOKEN_ERRNUM;
else
return tokval->t_type = TOKEN_NUM;
}
case TOKEN_STR:
tokval->t_charptr = (char *)unquote_token(tline);
/* fall through */
case TOKEN_INTERNAL_STR:
case TOKEN_NAKED_STR:
tokval->t_inttwo = tline->len;
return tokval->t_type = TOKEN_STR;
}
}
/*
* 1. An expression (true if nonzero 0)
* 2. The keywords true, on, yes for true
* 3. The keywords false, off, no for false
* 4. An empty line, for true
*
* On error, return defval (usually the previous value)
*/
static bool pp_get_boolean_option(Token *tline, bool defval)
{
static const char * const noyes[] = {
"no", "yes",
"false", "true",
"off", "on"
};
struct ppscan pps;
struct tokenval tokval;
expr *evalresult;
tline = skip_white(tline);
if (!tline)
return true;
if (tline->type == TOKEN_ID) {
size_t i;
const char *txt = tok_text(tline);
for (i = 0; i < ARRAY_SIZE(noyes); i++)
if (!nasm_stricmp(txt, noyes[i]))
return i & 1;
}
pps.tptr = NULL;
pps.tptr = tline;
pps.ntokens = -1;
tokval.t_type = TOKEN_INVALID;
evalresult = evaluate(ppscan, &pps, &tokval, NULL, true, NULL);
if (!evalresult)
return true;
if (tokval.t_type) {
/*!
*!pp-trailing [on] trailing garbage ignored
*! warns that the preprocessor encountered additional text
*! where no such text was expected. This can
*! sometimes be the result of an incorrectly written expression,
*! or arguments that are inadvertently separated.
*/
nasm_warn(WARN_PP_TRAILING,
"trailing garbage after expression ignored");
}
if (!is_really_simple(evalresult)) {
nasm_nonfatal("boolean flag expression must be a constant");
return defval;
}
return reloc_value(evalresult) != 0;
}
/*
* Compare a string to the name of an existing macro; this is a
* simple wrapper which calls either strcmp or nasm_stricmp
* depending on the value of the `casesense' parameter.
*/
static int mstrcmp(const char *p, const char *q, bool casesense)
{
return casesense ? strcmp(p, q) : nasm_stricmp(p, q);
}
/*
* Compare a string to the name of an existing macro; this is a
* simple wrapper which calls either strcmp or nasm_stricmp
* depending on the value of the `casesense' parameter.
*/
static int mmemcmp(const char *p, const char *q, size_t l, bool casesense)
{
return casesense ? memcmp(p, q, l) : nasm_memicmp(p, q, l);
}
/*
* Return the Context structure associated with a %$ token. Return
* NULL, having _already_ reported an error condition, if the
* context stack isn't deep enough for the supplied number of $
* signs.
*
* If "namep" is non-NULL, set it to the pointer to the macro name
* tail, i.e. the part beyond %$...
*/
static Context *get_ctx(const char *name, const char **namep)
{
Context *ctx;
int i;
if (namep)
*namep = name;
if (!name || name[0] != '%' || name[1] != '$')
return NULL;
if (!cstk) {
nasm_nonfatal("`%s': context stack is empty", name);
return NULL;
}
name += 2;
ctx = cstk;
i = 0;
while (ctx && *name == '$') {
name++;
i++;
ctx = ctx->next;
}
if (!ctx) {
nasm_nonfatal("`%s': context stack is only"
" %d level%s deep", name, i, (i == 1 ? "" : "s"));
return NULL;
}
if (namep)
*namep = name;
return ctx;
}
/*
* Open an include file. This routine must always return a valid
* file pointer if it returns - it's responsible for throwing an
* ERR_FATAL and bombing out completely if not. It should also try
* the include path one by one until it finds the file or reaches
* the end of the path.
*
* Note: for INC_PROBE the function returns NULL at all times;
* instead look for a filename in *slpath.
*/
enum incopen_mode {
INC_NEEDED, /* File must exist */
INC_REQUIRED, /* File must exist, but only open once/pass */
INC_OPTIONAL, /* Missing is OK */
INC_PROBE /* Only an existence probe */
};
/* This is conducts a full pathname search */
static FILE *inc_fopen_search(const char *file, char **slpath,
enum incopen_mode omode, enum file_flags fmode)
{
const struct strlist_entry *ip = strlist_head(ipath_list);
FILE *fp;
const char *prefix = "";
char *sp;
bool found;
while (1) {
sp = nasm_catfile(prefix, file);
if (omode == INC_PROBE) {
fp = NULL;
found = nasm_file_exists(sp);
} else {
fp = nasm_open_read(sp, fmode);
found = (fp != NULL);
}
if (found) {
*slpath = sp;
return fp;
}
nasm_free(sp);
if (!ip) {
*slpath = NULL;
return NULL;
}
prefix = ip->str;
ip = ip->next;
}
}
/*
* Open a file, or test for the presence of one (depending on omode),
* considering the include path.
*/
struct file_hash_entry {
const char *path;
struct file_hash_entry *full; /* Hash entry for the full path */
int64_t include_pass; /* Pass in which last included (for %require) */
};
static FILE *inc_fopen(const char *file,
struct strlist *dhead,
const char **found_path,
enum incopen_mode omode,
enum file_flags fmode)
{
struct file_hash_entry **fhep;
struct file_hash_entry *fhe = NULL;
struct hash_insert hi;
const char *path = NULL;
FILE *fp = NULL;
const int64_t pass = pass_count();
bool skip_open = (omode == INC_PROBE);
fhep = (struct file_hash_entry **)hash_find(&FileHash, file, &hi);
if (fhep) {
fhe = *fhep;
if (fhe) {
path = fhe->path;
skip_open |= (omode == INC_REQUIRED) &&
(fhe->full->include_pass >= pass);
}
} else {
/* Need to do the actual path search */
char *pptr;
fp = inc_fopen_search(file, &pptr, omode, fmode);
path = pptr;
/* Positive or negative result */
if (path) {
nasm_new(fhe);
fhe->path = path;
fhe->full = fhe; /* It is *possible*... */
}
hash_add(&hi, nasm_strdup(file), fhe);
/*
* Add a hash entry for the canonical path if there isn't one
* already. Try to get the unique name from the OS best we can.
* Note that ->path and ->full->path can be different, and that
* is okay (we don't want to print out a full canonical path
* in messages, for example.)
*/
if (path) {
char *fullpath = nasm_realpath(path);
if (!strcmp(file, fullpath)) {
nasm_free(fullpath);
} else {
struct file_hash_entry **fullp, *full;
fullp = (struct file_hash_entry **)
hash_find(&FileHash, fullpath, &hi);
if (fullp) {
full = *fullp;
nasm_free(fullpath);
} else {
nasm_new(full);
full->path = fullpath;
full->full = full;
hash_add(&hi, path, full);
}
fhe->full = full;
}
}
/*
* Add file to dependency path.
*/
strlist_add(dhead, path ? path : file);
}
if (path && !fp && omode != INC_PROBE)
fp = nasm_open_read(path, fmode);
if (omode < INC_OPTIONAL && !fp) {
if (!path)
errno = ENOENT;
nasm_nonfatal("unable to open include file `%s': %s",
file, strerror(errno));
}
if (fp)
fhe->full->include_pass = pass;
if (found_path)
*found_path = path;
return fp;
}
/*
* Opens an include or input file. Public version, for use by modules
* that get a file:lineno pair and need to look at the file again
* (e.g. the CodeView debug backend). Returns NULL on failure.
*/
FILE *pp_input_fopen(const char *filename, enum file_flags mode)
{
return inc_fopen(filename, NULL, NULL, INC_OPTIONAL, mode);
}
/*
* Determine if we should warn on defining a single-line macro of
* name `name', with `nparam' parameters. If nparam is 0 or -1, will
* return true if _any_ single-line macro of that name is defined.
* Otherwise, will return true if a single-line macro with either
* `nparam' or no parameters is defined.
*
* If a macro with precisely the right number of parameters is
* defined, or nparam is -1, the address of the definition structure
* will be returned in `defn'; otherwise NULL will be returned. If `defn'
* is NULL, no action will be taken regarding its contents, and no
* error will occur.
*
* Note that this is also called with nparam zero to resolve
* `ifdef'.
*/
static bool
smacro_defined(Context *ctx, const char *name, int nparam, SMacro **defn,
bool nocase, bool find_alias)
{
struct hash_table *smtbl;
SMacro *m;
smtbl = ctx ? &ctx->localmac : &smacros;
restart:
m = (SMacro *) hash_findix(smtbl, name);
while (m) {
if (!mstrcmp(m->name, name, m->casesense && nocase) &&
(nparam <= 0 || m->nparam == 0 ||
(nparam >= m->nparam_min &&
(m->varadic || nparam <= m->nparam)))) {
if (m->alias && !find_alias) {
if (!ppconf.noaliases) {
name = tok_text(m->expansion);
goto restart;
} else {
continue;
}
}
if (defn)
*defn = m;
return true;
}
m = m->next;
}
return false;
}
/* param should be a natural number [0; INT_MAX] */
static int read_param_count(const char *str)
{
int result;
bool err;
result = readnum(str, &err);
if (result < 0 || result > INT_MAX) {
result = 0;
nasm_nonfatal("parameter count `%s' is out of bounds [%d; %d]",
str, 0, INT_MAX);
} else if (err)
nasm_nonfatal("unable to parse parameter count `%s'", str);
return result;
}
/*
* Count and mark off the parameters in a multi-line macro call.
* This is called both from within the multi-line macro expansion
* code, and also to mark off the default parameters when provided
* in a %macro definition line.
*
* Note that we need space in the params array for parameter 0 being
* a possible captured label as well as the final NULL.
*
* Returns a pointer to the pointer to a terminal comma if present;
* used to drop an empty terminal argument for legacy reasons.
*/
static Token **count_mmac_params(Token *tline, int *nparamp, Token ***paramsp)
{
int paramsize;
int nparam = 0;
Token *t;
Token **comma = NULL, **maybe_comma = NULL;
Token **params;
paramsize = PARAM_DELTA;
nasm_newn(params, paramsize);
t = skip_white(tline);
if (t) {
while (true) {
/* Need two slots for captured label and NULL */
if (unlikely(nparam+2 >= paramsize)) {
paramsize += PARAM_DELTA;
params = nasm_realloc(params, sizeof(*params) * paramsize);
}
params[++nparam] = t;
if (tok_is(t, '{')) {
int brace = 1;
comma = NULL; /* Non-empty parameter */
while (brace && (t = t->next)) {
brace += tok_is(t, '{');
brace -= tok_is(t, '}');
}
if (t) {
/*
* Now we've found the closing brace, look further
* for the comma.
*/
t = skip_white(t->next);
if (tok_isnt(t, ','))
nasm_nonfatal("braces do not enclose all of macro parameter");
} else {
nasm_nonfatal("expecting closing brace in macro parameter");
}
}
/* Advance to the next comma */
maybe_comma = &t->next;
while (tok_isnt(t, ',')) {
if (!tok_white(t))
comma = NULL; /* Non-empty parameter */
maybe_comma = &t->next;
t = t->next;
}
if (!t)
break; /* End of string, no comma */
comma = maybe_comma; /* Point to comma pointer */
t = skip_white(t->next); /* Eat the comma and whitespace */
}
}
params[nparam+1] = NULL;
*paramsp = params;
*nparamp = nparam;
return comma;
}
/*
* Determine whether one of the various `if' conditions is true or
* not.
*
* We must free the tline we get passed.
*/
static enum cond_state if_condition(Token * tline, enum preproc_token ct)
{
bool j;
Token *t, *tt, *origline;
struct ppscan pps;
struct tokenval tokval;
expr *evalresult;
enum token_type needtype;
const char *dname = pp_directives[ct];
bool casesense = true;
enum preproc_token cond = PP_COND(ct);
origline = tline;
switch (cond) {
case PP_IFCTX:
j = false; /* have we matched yet? */
while (true) {
tline = skip_white(tline);
if (!tline)
break;
if (tline->type != TOKEN_ID) {
nasm_nonfatal("`%s' expects context identifiers",
dname);
goto fail;
}
if (cstk && cstk->name && !nasm_stricmp(tok_text(tline), cstk->name))
j = true;
tline = tline->next;
}
break;
case PP_IFDEF:
case PP_IFDEFALIAS:
{
bool alias = cond == PP_IFDEFALIAS;
SMacro *smac;
Context *ctx;
const char *mname;
j = false; /* have we matched yet? */
while (tline) {
tline = skip_white(tline);
if (!tline || (tline->type != TOKEN_ID &&
tline->type != TOKEN_LOCAL_MACRO)) {
nasm_nonfatal("`%s' expects macro identifiers",
dname);
goto fail;
}
mname = tok_text(tline);
ctx = get_ctx(mname, &mname);
if (smacro_defined(ctx, mname, -1, &smac, true, alias) && smac
&& smac->alias == alias) {
j = true;
break;
}
tline = tline->next;
}
break;
}
case PP_IFDIFI:
/*
* %ifdifi doesn't actually exist; it ignores its argument and is
* always false. This exists solely to stub out the corresponding
* TASM directive.
*/
j = false;
goto fail;
case PP_IFENV:
tline = expand_smacro(tline);
j = false; /* have we matched yet? */
while (tline) {
tline = skip_white(tline);
if (!tline || (tline->type != TOKEN_ID &&
tline->type != TOKEN_STR &&
tline->type != TOKEN_INTERNAL_STR &&
tline->type != TOKEN_ENVIRON)) {
nasm_nonfatal("`%s' expects environment variable names",
dname);
goto fail;
}
j |= !!pp_getenv(tline, false);
tline = tline->next;
}
break;
case PP_IFIDNI:
casesense = false;
/* fall through */
case PP_IFIDN:
tline = expand_smacro(tline);
t = tt = tline;
while (tok_isnt(tt, ','))
tt = tt->next;
if (!tt) {
nasm_nonfatal("`%s' expects two comma-separated arguments",
dname);
goto fail;
}
tt = tt->next;
j = true; /* assume equality unless proved not */
while (tok_isnt(t, ',') && tt) {
unsigned int l1, l2;
const char *t1, *t2;
if (tok_is(tt, ',')) {
nasm_nonfatal("`%s': more than one comma on line",
dname);
goto fail;
}
if (t->type == TOKEN_WHITESPACE) {
t = t->next;
continue;
}
if (tt->type == TOKEN_WHITESPACE) {
tt = tt->next;
continue;
}
if (tt->type != t->type) {
j = false; /* found mismatching tokens */
break;
}
t1 = unquote_token(t);
t2 = unquote_token(tt);
l1 = t->len;
l2 = tt->len;
if (l1 != l2 || mmemcmp(t1, t2, l1, casesense)) {
j = false;
break;
}
t = t->next;
tt = tt->next;
}
if (!tok_is(t, ',') || tt)
j = false; /* trailing gunk on one end or other */
break;
case PP_IFMACRO:
{
bool found = false;
MMacro searching, *mmac;
tline = skip_white(tline);
tline = expand_id(tline);
if (!tok_is(tline, TOKEN_ID)) {
nasm_nonfatal("`%s' expects a macro name", dname);
goto fail;
}
nasm_zero(searching);
searching.name = dup_text(tline);
searching.casesense = true;
searching.nparam_min = 0;
searching.nparam_max = INT_MAX;
tline = expand_smacro(tline->next);
tline = skip_white(tline);
if (!tline) {
} else if (!tok_is(tline, TOKEN_NUM)) {
nasm_nonfatal("`%s' expects a parameter count or nothing",
dname);
} else {
searching.nparam_min = searching.nparam_max =
read_param_count(tok_text(tline));
}
if (tline && tok_is(tline->next, '-')) {
tline = tline->next->next;
if (tok_is(tline, '*'))
searching.nparam_max = INT_MAX;
else if (!tok_is(tline, TOKEN_NUM))
nasm_nonfatal("`%s' expects a parameter count after `-'",
dname);
else {
searching.nparam_max = read_param_count(tok_text(tline));
if (searching.nparam_min > searching.nparam_max) {
nasm_nonfatal("minimum parameter count exceeds maximum");
searching.nparam_max = searching.nparam_min;
}
}
}
if (tline && tok_is(tline->next, '+')) {
tline = tline->next;
searching.plus = true;
}
mmac = (MMacro *) hash_findix(&mmacros, searching.name);
while (mmac) {
if (!strcmp(mmac->name, searching.name) &&
(mmac->nparam_min <= searching.nparam_max
|| searching.plus)
&& (searching.nparam_min <= mmac->nparam_max
|| mmac->plus)) {
found = true;
break;
}
mmac = mmac->next;
}
if (tline && tline->next) {
nasm_warn(WARN_PP_TRAILING,
"trailing garbage after `%s' ignored", dname);
}
nasm_free(searching.name);
j = found;
break;
}
case PP_IFID:
needtype = TOKEN_ID;
goto iftype;
case PP_IFNUM:
needtype = TOKEN_NUM;
goto iftype;
case PP_IFSTR:
needtype = TOKEN_STR;
goto iftype;
iftype:
t = tline = expand_smacro(tline);
while (tok_white(t) ||
(needtype == TOKEN_NUM && (tok_is(t, '-') || tok_is(t, '+'))))
t = t->next;
j = tok_is(t, needtype);
break;
case PP_IFTOKEN:
tline = expand_smacro(tline);
t = skip_white(tline);
j = false;
if (t) {
t = skip_white(t->next); /* Skip the actual token + whitespace */
j = !t;
}
break;
case PP_IFEMPTY:
tline = expand_smacro(tline);
t = skip_white(tline);
j = !t; /* Should be empty */
break;
case PP_IF:
pps.tptr = tline = expand_smacro(tline);
pps.ntokens = -1;
tokval.t_type = TOKEN_INVALID;
evalresult = evaluate(ppscan, &pps, &tokval, NULL, true, NULL);
if (!evalresult)
return -1;
if (tokval.t_type) {
nasm_warn(WARN_PP_TRAILING, "trailing garbage after expression ignored");
}
if (!is_simple(evalresult)) {
nasm_nonfatal("non-constant value given to `%s'",
dname);
goto fail;
}
j = reloc_value(evalresult) != 0;
break;
case PP_IFUSING:
case PP_IFUSABLE:
{
const struct use_package *pkg;
const char *name;
pkg = get_use_pkg(tline, dname, &name);
if (!name)
goto fail;
j = pkg && ((cond == PP_IFUSABLE) | use_loaded[pkg->index]);
break;
}
default:
nasm_nonfatal("unknown preprocessor directive `%s'", dname);
goto fail;
}
free_tlist(origline);
return (j ^ PP_COND_NEGATIVE(ct)) ? COND_IF_TRUE : COND_IF_FALSE;
fail:
free_tlist(origline);
return COND_NEVER;
}
/*
* Default smacro expansion routine: just returns a copy of the
* expansion list.
*/
static Token *
smacro_expand_default(const SMacro *s, Token **params, int nparams)
{
(void)params;
(void)nparams;
return dup_tlist(s->expansion, NULL);
}
/*
* Emit a macro definition or undef to the listing file or debug format
* if desired. This is similar to detoken(), but it handles the
* reverse expansion list, does not expand %! or local variable
* tokens, and does some special handling for macro parameters.
*/
static void
list_smacro_def(enum preproc_token op, const Context *ctx, const SMacro *m)
{
Token *t;
size_t namelen, size;
char *def, *p, *end_spec;
char *context_prefix = NULL;
size_t context_len;
namelen = strlen(m->name);
size = namelen + 2; /* Include room for space after name + NUL */
if (ctx) {
int context_depth = cstk->depth - ctx->depth + 1;
context_prefix =
nasm_asprintf("[%s::%"PRIu64"] %%%-*s",
ctx->name ? ctx->name : "",
ctx->number, context_depth, "");
context_len = nasm_last_string_len();
memset(context_prefix + context_len - context_depth,
'$', context_depth);
size += context_len;
}
list_for_each(t, m->expansion)
size += t->len;
if (m->nparam) {
/*
* Space for ( and either , or ) around each
* parameter, plus up to 5 flags + /ux
*/
int i;
size += 1 + 8 * m->nparam;
for (i = 0; i < m->nparam; i++)
size += m->params[i].name.len;
}
def = nasm_malloc(size);
p = def+size;
*--p = '\0';
list_for_each(t, m->expansion) {
p -= t->len;
memcpy(p, tok_text(t), t->len);
}
*--p = ' ';
end_spec = p; /* Truncate here for macro def only */
if (m->nparam) {
int i;
*--p = ')';
for (i = m->nparam-1; i >= 0; i--) {
enum sparmflags flags = m->params[i].flags;
bool slash = false;
if (m->params[i].radix) {
*--p = m->params[i].radix;
slash = true;
}
if (flags & SPARM_UNSIGNED) {
*--p = 'u';
slash = true;
}
if (slash)
*--p = '/';
if (flags & (SPARM_GREEDY|SPARM_VARADIC))
*--p = '+';
p -= m->params[i].name.len;
memcpy(p, tok_text(&m->params[i].name), m->params[i].name.len);
if (flags & SPARM_NOSTRIP)
*--p = '!';
if (flags & SPARM_STR) {
*--p = '&';
if (flags & SPARM_CONDQUOTE)
*--p = '&';
}
if (flags & SPARM_EVAL)
*--p = '=';
*--p = ',';
}
*p = '('; /* First parameter starts with ( not , */
}
p -= namelen;
memcpy(p, m->name, namelen);
if (context_prefix) {
p -= context_len;
memcpy(p, context_prefix, context_len);
nasm_free(context_prefix);
}
if (ppdbg & PDBG_LIST_SMACROS)
nasm_listmsg("%s %s", pp_directives[op], p);
if (ppdbg & PDBG_SMACROS) {
bool define = !(op == PP_UNDEF || op == PP_UNDEFALIAS);
if (!define)
*end_spec = '\0'; /* Remove the expansion (for list file only) */
dfmt->debug_smacros(define, p);
}
nasm_free(def);
}
/*
* Parse smacro arguments, return argument count. If the tmpl argument
* is set, set the nparam, varadic and params field in the template.
* The varadic field is not used by define_smacro(), but is provided
* in case the caller wants it for other purposes.
*
* *tpp is updated to point to the pointer to the first token after the
* prototype.
*
* The text values from any argument tokens are "stolen" and the
* corresponding text fields set to NULL.
*
* Note that the user can't define a true varadic macro; doing so
* would be meaningless. The true varadic macros are only used for
* internal "magic macro" functions.
*/
static int parse_smacro_template(Token ***tpp, SMacro *tmpl)
{
int nparam = 0;
enum sparmflags flags;
struct smac_param *params = NULL;
bool err, done;
bool greedy = false;
bool parsing_radix;
char radix;
Token **tn = *tpp;
Token *t = *tn;
Token *name;
/*
* DO NOT skip whitespace here, or we won't be able to distinguish:
*
* %define foo (a,b) ; no arguments, (a,b) is the expansion
* %define bar(a,b) ; two arguments, empty expansion
*
* This ambiguity was inherited from C.
*/
if (!tok_is(t, '('))
goto finish;
if (tmpl) {
Token *tx = t;
Token **txpp = &tx;
int sparam;
/* Count parameters first */
sparam = parse_smacro_template(&txpp, NULL);
if (!sparam)
goto finish; /* No parameters, we're done */
nasm_newn(params, sparam);
}
/* Skip leading paren */
tn = &t->next;
t = *tn;
name = NULL;
flags = 0;
radix = 0;
parsing_radix = false;
err = done = false;
while (!done) {
if (!t) {
if (name || flags)
nasm_nonfatal("`)' expected to terminate macro template");
else
nasm_nonfatal("parameter identifier expected");
break;
}
switch (t->type) {
case TOKEN_ID:
if (parsing_radix) {
const char *cp;
for (cp = tok_text(t); cp && *cp; cp++) {
switch (*cp | 0x20) {
case 'b': case 'y':
case 'd': case 't':
case 'o': case 'q':
case 'h': case 'x':
radix = *cp;
break;
case 's':
flags &= ~SPARM_UNSIGNED;
break;
case 'u':
flags |= SPARM_UNSIGNED;
break;
default:
nasm_nonfatal("invalid radix specifier `/%s'",
tok_text(t));
cp = NULL;
break;
}
}
} else {
if (name)
goto bad;
name = t;
}
break;
case '=':
flags |= SPARM_EVAL;
break;
case '&':
flags |= SPARM_STR;
break;
case TOKEN_DBL_AND:
flags |= SPARM_STR|SPARM_CONDQUOTE;
break;
case '!':
flags |= SPARM_NOSTRIP;
break;
case '+':
flags |= SPARM_GREEDY|SPARM_OPTIONAL;
greedy = true;
break;
case '/':
if (!(flags & SPARM_EVAL))
nasm_nonfatal("radix specifier for parameter without `='");
parsing_radix = true;
break;
case ',':
if (greedy)
nasm_nonfatal("greedy parameter must be last");
goto end_param;
case ')':
done = true;
goto end_param;
end_param:
if (params) {
if (name)
steal_Token(¶ms[nparam].name, name);
params[nparam].flags = flags;
params[nparam].radix = radix;
}
nparam++;
name = NULL;
flags = 0;
parsing_radix = false;
radix = 0;
break;
case TOKEN_WHITESPACE:
break;
default:
bad:
if (!err) {
nasm_nonfatal("garbage `%s' in macro parameter list",
tok_text(t));
err = true;
}
break;
}
tn = &t->next;
t = *tn;
}
finish:
while (t && t->type == TOKEN_WHITESPACE) {
tn = &t->next;
t = t->next;
}
*tpp = tn;
if (tmpl) {
tmpl->nparam = nparam;
tmpl->varadic = greedy;
tmpl->params = params;
}
return nparam;
}
/*
* Common code for defining an smacro. The tmpl argument, if not NULL,
* contains any macro parameters that aren't explicit arguments;
* those are the more uncommon macro variants.
*/
static SMacro *define_smacro(const char *mname, bool casesense,
Token *expansion, SMacro *tmpl)
{
SMacro *smac, **smhead;
struct hash_table *smtbl;
Context *ctx;
bool defining_alias = false;
int nparam = 0;
bool defined;
if (tmpl) {
defining_alias = tmpl->alias;
nparam = tmpl->nparam;
if (nparam && !defining_alias)
mark_smac_params(expansion, tmpl, 0);
}
ctx = get_ctx(mname, &mname);
defined = smacro_defined(ctx, mname, nparam, &smac, casesense, true);
if (defined) {
if (smac->alias) {
if (smac->in_progress) {
nasm_nonfatal("macro alias loop");
goto fail;
}
if (!defining_alias && !ppconf.noaliases) {
/* It is an alias macro; follow the alias link */
SMacro *s;
smac->in_progress++;
s = define_smacro(tok_text(smac->expansion), casesense,
expansion, tmpl);
smac->in_progress--;
return s;
}
}
if (casesense ^ smac->casesense) {
/*
*!pp-macro-def-case-single [on] single-line macro defined both case sensitive and insensitive
*!=macro-def-case-single
*! warns when a single-line macro is defined both case
*! sensitive and case insensitive.
*! The new macro
*! definition will override (shadow) the original one,
*! although the original macro is not deleted, and will
*! be re-exposed if the new macro is deleted with
*! \c{%undef}, or, if the original macro is the case
*! insensitive one, the macro call is done with a
*! different case.
*/
nasm_warn(WARN_PP_MACRO_DEF_CASE_SINGLE, "case %ssensitive definition of macro `%s' will shadow %ssensitive macro `%s'",
casesense ? "" : "in",
mname,
smac->casesense ? "" : "in",
smac->name);
defined = false;
} else if ((!!nparam) ^ (!!smac->nparam)) {
/*
* Most recent versions of NASM considered this an error,
* so promote this warning to error by default.
*
*!pp-macro-def-param-single [err] single-line macro defined with and without parameters
*!=macro-def-param-single
*! warns if the same single-line macro is defined with and
*! without parameters.
*! The new macro
*! definition will override (shadow) the original one,
*! although the original macro is not deleted, and will
*! be re-exposed if the new macro is deleted with
*! \c{%undef}.
*/
nasm_warn(WARN_PP_MACRO_DEF_PARAM_SINGLE,
"macro `%s' defined both with and without parameters",
mname);
defined = false;
} else if (smac->nparam < nparam) {
/*
*!pp-macro-def-greedy-single [on] single-line macro
*!=macro-def-greedy-single
*! definition shadows greedy macro warns when a
*! single-line macro is defined which would match a
*! previously existing greedy definition. The new macro
*! definition will override (shadow) the original one,
*! although the original macro is not deleted, and will
*! be re-exposed if the new macro is deleted with
*! \c{%undef}, and will be invoked if called with a
*! parameter count that does not match the new definition.
*/
nasm_warn(WARN_PP_MACRO_DEF_GREEDY_SINGLE,
"defining macro `%s' shadows previous greedy definition",
mname);
defined = false;
}
}
if (defined) {
/*
* We're redefinining, so we have to take over an
* existing SMacro structure. This means freeing
* what was already in it, but not the structure itself.
*/
clear_smacro(smac);
} else {
/* Create a new macro */
smtbl = ctx ? &ctx->localmac : &smacros;
smhead = (SMacro **) hash_findi_add(smtbl, mname);
nasm_new(smac);
smac->next = *smhead;
*smhead = smac;
}
smac->name = nasm_strdup(mname);
smac->casesense = casesense;
smac->expansion = reverse_tokens(expansion);
smac->expand = smacro_expand_default;
smac->nparam = nparam;
smac->nparam_min = nparam;
if (tmpl) {
smac->params = tmpl->params;
smac->alias = tmpl->alias;
smac->recursive = tmpl->recursive;
if (tmpl->expand) {
smac->expand = tmpl->expand;
smac->expandpvt = tmpl->expandpvt;
}
if (nparam) {
int nparam_min = nparam;
smac->varadic =
!!(tmpl->params[nparam-1].flags &
(SPARM_GREEDY|SPARM_VARADIC));
while (nparam_min > 1) {
if (!(tmpl->params[nparam_min-1].flags & SPARM_OPTIONAL))
break;
nparam_min--;
}
smac->nparam_min = nparam_min;
}
}
if (ppdbg & (PDBG_SMACROS|PDBG_LIST_SMACROS)) {
list_smacro_def((smac->alias ? PP_DEFALIAS : PP_DEFINE)
+ !casesense, ctx, smac);
}
return smac;
fail:
free_tlist(expansion);
if (tmpl)
free_smacro_members(tmpl);
return NULL;
}
/*
* Undefine an smacro
*/
static void undef_smacro(const char *mname, bool undefalias)
{
SMacro **smhead, *s, **sp;
struct hash_table *smtbl;
Context *ctx;
ctx = get_ctx(mname, &mname);
smtbl = ctx ? &ctx->localmac : &smacros;
smhead = (SMacro **)hash_findi(smtbl, mname, NULL);
if (smhead) {
/*
* We now have a macro name... go hunt for it.
*/
sp = smhead;
while ((s = *sp) != NULL) {
if (!mstrcmp(s->name, mname, s->casesense)) {
if (s->alias && !undefalias) {
if (!ppconf.noaliases) {
if (s->in_progress) {
nasm_nonfatal("macro alias loop");
} else {
s->in_progress = true;
undef_smacro(tok_text(s->expansion), false);
s->in_progress = false;
}
}
} else {
if (list_option('d'))
list_smacro_def(s->alias ? PP_UNDEFALIAS : PP_UNDEF,
ctx, s);
*sp = s->next;
free_smacro(s);
continue;
}
}
sp = &s->next;
}
}
}
/*
* Parse a mmacro specification.
*/
static bool parse_mmacro_spec(Token *tline, MMacro *def, const char *directive)
{
tline = tline->next;
tline = skip_white(tline);
tline = expand_id(tline);
if (!tok_is(tline, TOKEN_ID)) {
nasm_nonfatal("`%s' expects a macro name", directive);
return false;
}
#if 0
def->prev = NULL;
#endif
def->name = dup_text(tline);
def->plus = false;
def->nolist = 0;
def->nparam_min = 0;
def->nparam_max = 0;
tline = expand_smacro(tline->next);
tline = skip_white(tline);
if (!tok_is(tline, TOKEN_NUM))
nasm_nonfatal("`%s' expects a parameter count", directive);
else
def->nparam_min = def->nparam_max = read_param_count(tok_text(tline));
if (tline && tok_is(tline->next, '-')) {
tline = tline->next->next;
if (tok_is(tline, '*')) {
def->nparam_max = INT_MAX;
} else if (!tok_is(tline, TOKEN_NUM)) {
nasm_nonfatal("`%s' expects a parameter count after `-'", directive);
} else {
def->nparam_max = read_param_count(tok_text(tline));
if (def->nparam_min > def->nparam_max) {
nasm_nonfatal("minimum parameter count exceeds maximum");
def->nparam_max = def->nparam_min;
}
}
}
if (tline && tok_is(tline->next, '+')) {
tline = tline->next;
def->plus = true;
}
if (tline && tok_is(tline->next, TOKEN_ID) &&
tline->next->len == 7 &&
!nasm_stricmp(tline->next->text.a, ".nolist")) {
tline = tline->next;
if (!list_option('f'))
def->nolist |= NL_LIST|NL_LINE;
}
/*
* Handle default parameters.
*/
def->ndefs = 0;
if (tline && tline->next) {
Token **comma;
def->dlist = tline->next;
tline->next = NULL;
comma = count_mmac_params(def->dlist, &def->ndefs, &def->defaults);
if (!ppconf.sane_empty_expansion && comma) {
*comma = NULL;
def->ndefs--;
nasm_warn(WARN_PP_MACRO_PARAMS_LEGACY,
"dropping trailing empty default parameter in definition of multi-line macro `%s'",
def->name);
}
} else {
def->dlist = NULL;
def->defaults = NULL;
}
def->expansion = NULL;
if (def->defaults && def->ndefs > def->nparam_max - def->nparam_min &&
!def->plus) {
/*
*!pp-macro-defaults [on] macros with more default than optional parameters
*!=macro-defaults
*! warns when a macro has more default parameters than optional parameters.
*! See \k{mlmacdef} for why might want to disable this warning.
*/
nasm_warn(WARN_PP_MACRO_DEFAULTS,
"too many default macro parameters in macro `%s'", def->name);
}
return true;
}
/*
* Decode a size directive
*/
static int parse_size(const char *str) {
static const char *size_names[] =
{ "byte", "dword", "oword", "qword", "tword", "word", "yword" };
static const int sizes[] =
{ 0, 1, 4, 16, 8, 10, 2, 32 };
return str ? sizes[bsii(str, size_names, ARRAY_SIZE(size_names))+1] : 0;
}
/*
* Process a preprocessor %pragma directive. Currently there are none.
* Gets passed the token list starting with the "preproc" token from
* "%pragma preproc".
*/
static void do_pragma_preproc(Token *tline)
{
const char *txt;
/* Skip to the real stuff */
tline = tline->next;
tline = skip_white(tline);
if (!tok_is(tline, TOKEN_ID))
return;
txt = tok_text(tline);
if (!nasm_stricmp(txt, "sane_empty_expansion")) {
tline = skip_white(tline->next);
ppconf.sane_empty_expansion =
pp_get_boolean_option(tline, ppconf.sane_empty_expansion);
} else {
/* Unknown pragma, ignore for now */
}
}
static bool is_macro_id(const Token *t)
{
return tok_is(t, TOKEN_ID) || tok_is(t, TOKEN_LOCAL_MACRO);
}
static const char *get_id_noskip(Token **tp, const char *dname);
static const char *get_id(Token **tp, const char *dname)
{
*tp = (*tp)->next; /* Skip directive */
return get_id_noskip(tp, dname);
}
static const char *get_id_noskip(Token **tp, const char *dname)
{
const char *id;
Token *t = *tp;
t = skip_white(t);
t = expand_id(t);
if (!is_macro_id(t)) {
nasm_nonfatal("`%s' expects a macro identifier", dname);
return NULL;
}
id = tok_text(t);
nasm_assert(!tok_white(t)); /* Had skip_white() here?? */
*tp = t;
return id;
}
/* Parse a %use package name and find the package. Set *err on syntax error. */
static const struct use_package *
get_use_pkg(Token *t, const char *dname, const char **name)
{
const char *id;
t = skip_white(t);
t = expand_smacro(t);
*name = NULL;
if (!t) {
nasm_nonfatal("`%s' expects a package name, got end of line", dname);
return NULL;
} else if (t->type != TOKEN_ID && t->type != TOKEN_STR) {
nasm_nonfatal("`%s' expects a package name, got `%s'",
dname, tok_text(t));
return NULL;
}
*name = id = unquote_token(t);
t = t->next;
t = skip_white(t);
if (t) {
nasm_warn(WARN_PP_TRAILING,
"trailing garbage after `%s' ignored", dname);
}
return nasm_find_use_package(id);
}
/*
* Mark parameter tokens in an smacro definition. If the type argument
* is 0, create smac param tokens, otherwise use the type specified;
* normally this is used for TOKEN_XDEF_PARAM, which is used to protect
* parameter tokens during expansion during %xdefine.
*
* tmpl may not be NULL here.
*/
static void mark_smac_params(Token *tline, const SMacro *tmpl,
enum token_type type)
{
const struct smac_param *params = tmpl->params;
int nparam = tmpl->nparam;
Token *t;
int i;
list_for_each(t, tline) {
if (t->type != TOKEN_ID && t->type != TOKEN_XDEF_PARAM)
continue;
for (i = 0; i < nparam; i++) {
if (tok_text_match(t, ¶ms[i].name))
t->type = type ? type : tok_smac_param(i);
}
}
}
/**
* %clear selected macro sets either globally or in contexts
*/
static void do_clear(enum clear_what what, bool context)
{
if (context) {
if (what & CLEAR_ALLDEFINE) {
Context *ctx;
list_for_each(ctx, cstk)
clear_smacro_table(&ctx->localmac, what);
}
/* Nothing else can be context-local */
} else {
if (what & CLEAR_ALLDEFINE)
clear_smacro_table(&smacros, what);
if (what & CLEAR_MMACRO)
free_mmacro_table(&mmacros);
}
}
/*
* Process a %line directive, including the gcc/cpp compatibility
* form with a # at the front.
*/
static int line_directive(Token *origline, Token *tline)
{
int k, m;
bool err;
const char *dname;
/*
* Valid syntaxes:
* %line nnn[+mmm] [filename]
* %line nnn[+mmm] "filename" flags...
*
* "flags" are for gcc compatibility and are currently ignored.
*
* "#" at the beginning of the line is also treated as a %line
* directive, again for compatibility with gcc.
*/
if ((ppopt & PP_NOLINE) || istk->mstk.mstk)
goto done;
dname = tok_text(tline);
tline = tline->next;
tline = skip_white(tline);
if (!tok_is(tline, TOKEN_NUM)) {
nasm_nonfatal("`%s' expects a line number", dname);
goto done;
}
k = readnum(tok_text(tline), &err);
m = 1;
tline = tline->next;
if (tok_is(tline, '+') || tok_is(tline, '-')) {
bool minus = tok_is(tline, '-');
tline = tline->next;
if (!tok_is(tline, TOKEN_NUM)) {
nasm_nonfatal("`%s' expects a line increment", dname);
goto done;
}
m = readnum(tok_text(tline), &err);
if (minus)
m = -m;
tline = tline->next;
}
tline = skip_white(tline);
if (tline) {
if (tline->type == TOKEN_STR) {
const char *fname;
/*
* If this is a quoted string, ignore anything after
* it; this allows for compatibility with gcc's
* additional flags options.
*/
fname = unquote_token_anystr(tline, BADCTL,
dname[0] == '#' ? STR_C : STR_NASM);
src_set_fname(fname);
} else {
char *fname;
fname = detoken(tline, false);
src_set_fname(fname);
nasm_free(fname);
}
}
src_set_linnum(k);
istk->where = src_where();
istk->lineinc = m;
goto done;
done:
free_tlist(origline);
return DIRECTIVE_FOUND;
}
/*
* Used for the %arg and %local directives
*/
static void define_stack_smacro(const char *name, int offset)
{
Token *tt;
tt = make_tok_char(NULL, ')');
tt = make_tok_num(tt, offset);
if (!tok_is(tt, '-'))
tt = make_tok_char(tt, '+');
tt = new_Token(tt, TOKEN_ID, StackPointer, 0);
tt = make_tok_char(tt, '(');
define_smacro(name, true, tt, NULL);
}
/*
* This implements the %assign directive: expand an smacro expression,
* then evaluate it, and assign the corresponding number to an smacro.
*/
static void assign_smacro(const char *mname, bool casesense,
Token *tline, const char *dname)
{
struct ppscan pps;
expr *evalresult;
struct tokenval tokval;
tline = expand_smacro(tline);
pps.tptr = tline;
pps.ntokens = -1;
tokval.t_type = TOKEN_INVALID;
evalresult = evaluate(ppscan, &pps, &tokval, NULL, true, NULL);
free_tlist(tline);
if (!evalresult)
return;
if (tokval.t_type) {
nasm_warn(WARN_PP_TRAILING,
"trailing garbage after expression ignored");
}
if (!is_simple(evalresult)) {
nasm_nonfatal("non-constant value given to `%s'", dname);
} else {
tline = make_tok_num(NULL, reloc_value(evalresult));
/*
* We now have a macro name, an implicit parameter count of
* zero, and a numeric token to use as an expansion. Create
* and store an SMacro.
*/
define_smacro(mname, casesense, tline, NULL);
}
}
/*
* Implement string concatenation as used by the %strcat directive
* and function.
*/
static Token *pp_strcat(Token *tline, const char *dname)
{
size_t len;
Token *t;
Token *res = NULL;
char *q, *qbuf;
len = 0;
list_for_each(t, tline) {
switch (t->type) {
case TOKEN_WHITESPACE:
case TOKEN_COMMA:
break;
case TOKEN_STR:
unquote_token(t);
/* fall through */
case TOKEN_INTERNAL_STR:
len += t->len;
break;
default:
nasm_nonfatal("non-string passed to `%s': %s", dname,
tok_text(t));
goto err;
}
}
q = qbuf = nasm_malloc(len+1);
list_for_each(t, tline) {
if (t->type == TOKEN_INTERNAL_STR)
q = mempcpy(q, tok_text(t), t->len);
}
*q = '\0';
res = make_tok_qstr_len(NULL, qbuf, len);
nasm_free(qbuf);
err:
free_tlist(tline);
return res;
}
/*
* Implement substring extraction as used by the %substr directive
* and function.
*/
static Token *pp_substr_common(Token *t, int64_t start, int64_t count);
static Token *pp_substr(Token *tline, const char *dname)
{
int64_t start, count;
struct ppscan pps;
Token *t;
Token *res = NULL;
expr *evalresult;
struct tokenval tokval;
t = skip_white(tline);
if (!tok_is(t, TOKEN_STR)) {
nasm_nonfatal("`%s' requires a string as parameter", dname);
goto err;
}
pps.tptr = skip_white(t->next);
if (tok_is(pps.tptr, TOKEN_COMMA))
pps.tptr = skip_white(pps.tptr->next);
if (!pps.tptr) {
nasm_nonfatal("`%s' requires a starting index", dname);
goto err;
}
pps.ntokens = -1;
tokval.t_type = TOKEN_INVALID;
evalresult = evaluate(ppscan, &pps, &tokval, NULL, true, NULL);
if (!evalresult) {
goto err;
} else if (!is_simple(evalresult)) {
nasm_nonfatal("non-constant value given to `%s'", dname);
goto err;
}
start = evalresult->value;
pps.tptr = skip_white(pps.tptr);
if (!pps.tptr) {
count = 1; /* Backwards compatibility: one character */
} else {
tokval.t_type = TOKEN_INVALID;
evalresult = evaluate(ppscan, &pps, &tokval, NULL, true, NULL);
if (!evalresult) {
goto err;
} else if (!is_simple(evalresult)) {
nasm_nonfatal("non-constant value given to `%s'", dname);
goto err;
}
count = evalresult->value;
}
res = pp_substr_common(t, start, count);
err:
free_tlist(tline);
return res;
}
static Token *pp_substr_common(Token *t, int64_t start, int64_t count)
{
size_t len;
const char *txt;
unquote_token(t);
len = t->len;
/* make start and count being in range */
start -= 1; /* First character is 1 */
if (start < 0)
start = 0;
if (count < 0)
count = len + count + 1 - start;
if (start + count > (int64_t)len)
count = len - start;
if (!len || count < 0 || start >=(int64_t)len)
start = -1, count = 0; /* empty string */
txt = (start < 0) ? "" : tok_text(t) + start;
return make_tok_qstr_len(NULL, txt, count);
}
/**
* find and process preprocessor directive in passed line
* Find out if a line contains a preprocessor directive, and deal
* with it if so.
*
* If a directive _is_ found, it is the responsibility of this routine
* (and not the caller) to free_tlist() the line.
*
* @param tline a pointer to the current tokeninzed line linked list
* @param output if this directive generated output
* @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
*
*/
static int do_directive(Token *tline, Token **output)
{
enum preproc_token op;
int j;
enum nolist_flags nolist;
bool casesense;
int offset;
const char *p;
char *q;
const char *found_path;
const char *mname;
struct ppscan pps;
Include *inc;
Context *ctx;
Cond *cond;
MMacro *mmac, **mmhead;
Token *t = NULL, *tt, *macro_start, *last, *origline;
Line *l;
struct tokenval tokval;
expr *evalresult;
int64_t count;
errflags severity;
const char *dname; /* Name of directive, for messages */
*output = NULL; /* No output generated */
origline = tline;
/* cpp-like line directive, must not be preceded by whitespace */
if (tok_is(tline, '#'))
return line_directive(origline, tline);
tline = skip_white(tline);
if (!tline)
return NO_DIRECTIVE_FOUND;
switch (tline->type) {
case TOKEN_PREPROC_ID:
dname = tok_text(tline);
/*
* For it to be a directive, the second character has to be an
* ASCII letter; this is a very quick and dirty test for that;
* all other cases will get rejected by the token hash.
*/
if ((uint8_t)(dname[1] - 'A') > (uint8_t)('z' - 'A'))
return NO_DIRECTIVE_FOUND;
op = pp_token_hash(dname);
break;
case TOKEN_ID:
if (likely(!(ppopt & PP_TASM)))
return NO_DIRECTIVE_FOUND;
dname = tok_text(tline);
op = pp_tasm_token_hash(dname);
break;
default:
return NO_DIRECTIVE_FOUND;
}
switch (op) {
case PP_invalid:
return NO_DIRECTIVE_FOUND;
case PP_LINE:
/*
* %line directives are always processed immediately and
* unconditionally, as they are intended to reflect position
* in externally preprocessed sources.
*/
return line_directive(origline, tline);
default:
break;
}
if (unlikely(ppopt & PP_TRIVIAL))
goto done;
casesense = true;
if (PP_HAS_CASE(op) & PP_INSENSITIVE(op)) {
casesense = false;
op--;
}
/*
* If we're in a non-emitting branch of a condition construct,
* or walking to the end of an already terminated %rep block,
* we should ignore all directives except for condition
* directives.
*/
if (((istk->conds && !emitting(istk->conds->state)) ||
(istk->mstk.mstk && !istk->mstk.mstk->in_progress)) &&
!is_condition(op)) {
return NO_DIRECTIVE_FOUND;
}
/*
* If we're defining a macro or reading a %rep block, we should
* ignore all directives except for %macro/%imacro (which nest),
* %endm/%endmacro, %line and (only if we're in a %rep block) %endrep.
* If we're in a %rep block, another %rep nests, so should be let through.
*/
if (defining && op != PP_MACRO && op != PP_RMACRO &&
op != PP_ENDMACRO && op != PP_ENDM &&
(defining->name || (op != PP_ENDREP && op != PP_REP))) {
return NO_DIRECTIVE_FOUND;
}
if (defining) {
if (op == PP_MACRO || op == PP_RMACRO) {
nested_mac_count++;
return NO_DIRECTIVE_FOUND;
} else if (nested_mac_count > 0) {
if (op == PP_ENDMACRO) {
nested_mac_count--;
return NO_DIRECTIVE_FOUND;
}
}
if (!defining->name) {
if (op == PP_REP) {
nested_rep_count++;
return NO_DIRECTIVE_FOUND;
} else if (nested_rep_count > 0) {
if (op == PP_ENDREP) {
nested_rep_count--;
return NO_DIRECTIVE_FOUND;
}
}
}
}
if (pp_op_may_be_function[op]) {
if (tok_is(skip_white(tline->next), '('))
return NO_DIRECTIVE_FOUND; /* Expand as a preprocessor function */
}
switch (op) {
default:
nasm_nonfatal("unknown preprocessor directive `%s'", dname);
return NO_DIRECTIVE_FOUND; /* didn't get it */
case PP_PRAGMA:
/*
* %pragma namespace options...
*
* The namespace "preproc" is reserved for the preprocessor;
* all other namespaces generate a [pragma] assembly directive.
*
* Invalid %pragmas are ignored and may have different
* meaning in future versions of NASM.
*/
t = tline;
tline = tline->next;
t->next = NULL;
tline = zap_white(expand_smacro(tline));
if (tok_is(tline, TOKEN_ID)) {
if (!nasm_stricmp(tok_text(tline), "preproc")) {
/* Preprocessor pragma */
do_pragma_preproc(tline);
free_tlist(tline);
} else {
/* Build the assembler directive */
/* Append bracket to the end of the output */
for (t = tline; t->next; t = t->next)
;
t->next = make_tok_char(NULL, ']');
/* Prepend "[pragma " */
t = new_White(tline);
t = new_Token(t, TOKEN_ID, "pragma", 6);
t = make_tok_char(t, '[');
tline = t;
*output = tline;
}
}
break;
case PP_STACKSIZE:
{
const char *arg;
/* Directive to tell NASM what the default stack size is. The
* default is for a 16-bit stack, and this can be overridden with
* %stacksize large.
*/
tline = skip_white(tline->next);
if (!tline || tline->type != TOKEN_ID) {
nasm_nonfatal("`%s' missing size parameter", dname);
break;
}
arg = tok_text(tline);
if (nasm_stricmp(arg, "flat") == 0) {
/* All subsequent ARG directives are for a 32-bit stack */
StackSize = 4;
StackPointer = "ebp";
ArgOffset = 8;
LocalOffset = 0;
} else if (nasm_stricmp(arg, "flat64") == 0) {
/* All subsequent ARG directives are for a 64-bit stack */
StackSize = 8;
StackPointer = "rbp";
ArgOffset = 16;
LocalOffset = 0;
} else if (nasm_stricmp(arg, "large") == 0) {
/* All subsequent ARG directives are for a 16-bit stack,
* far function call.
*/
StackSize = 2;
StackPointer = "bp";
ArgOffset = 4;
LocalOffset = 0;
} else if (nasm_stricmp(arg, "small") == 0) {
/* All subsequent ARG directives are for a 16-bit stack,
* far function call. We don't support near functions.
*/
StackSize = 2;
StackPointer = "bp";
ArgOffset = 6;
LocalOffset = 0;
} else {
nasm_nonfatal("`%s' invalid size type", dname);
}
break;
}
case PP_ARG:
/* TASM like ARG directive to define arguments to functions, in
* the following form:
*
* ARG arg1:WORD, arg2:DWORD, arg4:QWORD
*/
offset = ArgOffset;
do {
const char *arg;
int size = StackSize;
/* Find the argument name */
tline = skip_white(tline->next);
if (!tline || tline->type != TOKEN_ID) {
nasm_nonfatal("`%s' missing argument parameter", dname);
goto done;
}
arg = tok_text(tline);
/* Find the argument size type */
tline = tline->next;
if (!tok_is(tline, ':')) {
nasm_nonfatal("syntax error processing `%s' directive", dname);
goto done;
}
tline = tline->next;
if (!tok_is(tline, TOKEN_ID)) {
nasm_nonfatal("`%s' missing size type parameter", dname);
goto done;
}
/* Allow macro expansion of type parameter */
tt = tokenize(tok_text(tline));
tt = expand_smacro(tt);
size = parse_size(tok_text(tt));
if (!size) {
nasm_nonfatal("invalid size type for `%s' missing directive", dname);
free_tlist(tt);
goto done;
}
free_tlist(tt);
/* Round up to even stack slots */
size = ALIGN(size, StackSize);
/* Now define the macro for the argument */
define_stack_smacro(arg, offset);
offset += size;
/* Move to the next argument in the list */
tline = skip_white(tline->next);
} while (tok_is(tline, ','));
ArgOffset = offset;
break;
case PP_LOCAL:
{
int total_size = 0;
/* TASM like LOCAL directive to define local variables for a
* function, in the following form:
*
* LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
*
* The '= LocalSize' at the end is ignored by NASM, but is
* required by TASM to define the local parameter size (and used
* by the TASM macro package).
*/
offset = LocalOffset;
do {
const char *local;
int size = StackSize;
/* Find the argument name */
tline = skip_white(tline->next);
if (!tline || tline->type != TOKEN_ID) {
nasm_nonfatal("`%s' missing argument parameter", dname);
goto done;
}
local = tok_text(tline);
/* Find the argument size type */
tline = tline->next;
if (!tok_is(tline, ':')) {
nasm_nonfatal("syntax error processing `%s' directive", dname);
goto done;
}
tline = tline->next;
if (!tok_is(tline, TOKEN_ID)) {
nasm_nonfatal("`%s' missing size type parameter", dname);
goto done;
}
/* Allow macro expansion of type parameter */
tt = tokenize(tok_text(tline));
tt = expand_smacro(tt);
size = parse_size(tok_text(tt));
if (!size) {
nasm_nonfatal("invalid size type for `%s' missing directive", dname);
free_tlist(tt);
goto done;
}
free_tlist(tt);
/* Round up to even stack slots */
size = ALIGN(size, StackSize);
offset += size; /* Negative offset, increment before */
/* Now define the macro for the argument */
define_stack_smacro(local, -offset);
/* How is this different from offset? */
total_size += size;
/* Move to the next argument in the list */
tline = skip_white(tline->next);
} while (tok_is(tline, ','));
/* Now define the assign to setup the enter_c macro correctly */
tt = make_tok_num(NULL, total_size);
tt = make_tok_char(tt, '+');
tt = new_Token(tt, TOKEN_LOCAL_MACRO, "%$localsize", 11);
assign_smacro("%$localsize", true, tt, dname);
LocalOffset = offset;
break;
}
case PP_CLEAR:
{
bool context = false;
t = tline->next = expand_smacro(tline->next);
t = skip_white(t);
if (!t) {
/* Emulate legacy behavior */
do_clear(CLEAR_DEFINE|CLEAR_MMACRO, false);
} else {
while ((t = skip_white(t)) && t->type == TOKEN_ID) {
const char *txt = tok_text(t);
if (!nasm_stricmp(txt, "all")) {
do_clear(CLEAR_ALL, context);
} else if (!nasm_stricmp(txt, "define") ||
!nasm_stricmp(txt, "def") ||
!nasm_stricmp(txt, "smacro")) {
do_clear(CLEAR_DEFINE, context);
} else if (!nasm_stricmp(txt, "defalias") ||
!nasm_stricmp(txt, "alias") ||
!nasm_stricmp(txt, "salias")) {
do_clear(CLEAR_DEFALIAS, context);
} else if (!nasm_stricmp(txt, "alldef") ||
!nasm_stricmp(txt, "alldefine")) {
do_clear(CLEAR_ALLDEFINE, context);
} else if (!nasm_stricmp(txt, "macro") ||
!nasm_stricmp(txt, "mmacro")) {
do_clear(CLEAR_MMACRO, context);
} else if (!nasm_stricmp(txt, "context") ||
!nasm_stricmp(txt, "ctx")) {
context = true;
} else if (!nasm_stricmp(txt, "global")) {
context = false;
} else if (!nasm_stricmp(txt, "nothing") ||
!nasm_stricmp(txt, "none") ||
!nasm_stricmp(txt, "ignore") ||
!nasm_stricmp(txt, "-") ||
!nasm_stricmp(txt, "--")) {
/* Do nothing */
} else {
nasm_nonfatal("invalid option to %s: %s", dname, txt);
t = NULL;
}
}
}
t = skip_white(t);
if (t) {
nasm_warn(WARN_PP_TRAILING,
"trailing garbage after `%s' ignored", dname);
}
break;
}
case PP_DEPEND:
t = tline->next = expand_smacro(tline->next);
t = skip_white(t);
if (!t || (t->type != TOKEN_STR &&
t->type != TOKEN_INTERNAL_STR)) {
nasm_nonfatal("`%s' expects a file name", dname);
goto done;
}
if (skip_white(t->next)) {
nasm_warn(WARN_PP_TRAILING,
"trailing garbage after `%s' ignored", dname);
}
strlist_add(deplist, unquote_token_cstr(t));
goto done;
case PP_INCLUDE:
case PP_REQUIRE:
t = tline->next = expand_smacro(tline->next);
t = skip_white(t);
if (!t || (t->type != TOKEN_STR &&
t->type != TOKEN_INTERNAL_STR)) {
nasm_nonfatal("`%s' expects a file name", dname);
goto done;
}
if (skip_white(t->next)) {
nasm_warn(WARN_PP_TRAILING,
"trailing garbage after `%s' ignored", dname);
}
p = unquote_token_cstr(t);
nasm_new(inc);
inc->next = istk;
found_path = NULL;
inc->fp = inc_fopen(p, deplist, &found_path,
(pp_mode == PP_DEPS) ? INC_OPTIONAL :
(op == PP_REQUIRE) ? INC_REQUIRED :
INC_NEEDED, NF_TEXT);
if (!inc->fp) {
/* -MG given but file not found, or repeated %require */
nasm_free(inc);
} else {
inc->nolist = istk->nolist;
inc->noline = istk->noline;
inc->where = istk->where;
inc->lineinc = 0;
istk = inc;
if (!istk->noline) {
src_set(0, found_path ? found_path : p);
istk->where = src_where();
istk->lineinc = 1;
if (ppdbg & PDBG_INCLUDE)
dfmt->debug_include(true, istk->next->where, istk->where);
}
if (!istk->nolist)
lfmt->uplevel(LIST_INCLUDE, 0);
}
break;
case PP_USE:
{
const struct use_package *pkg;
const char *name;
pkg = get_use_pkg(tline->next, dname, &name);
if (!name)
goto done;
if (!pkg) {
nasm_nonfatal("unknown `%s' package: `%s'", dname, name);
} else if (!use_loaded[pkg->index]) {
/*
* Not already included, go ahead and include it.
* Treat it as an include file for the purpose of
* producing a listing.
*/
use_loaded[pkg->index] = true;
stdmacpos = pkg->macros;
nasm_new(inc);
inc->next = istk;
if (!list_option('b')) {
inc->nolist++;
inc->noline++;
}
istk = inc;
if (!istk->nolist)
lfmt->uplevel(LIST_INCLUDE, 0);
if (!inc->noline)
src_set(0, NULL);
}
break;
}
case PP_PUSH:
case PP_REPL:
case PP_POP:
tline = tline->next;
tline = skip_white(tline);
tline = expand_id(tline);
if (tline) {
if (!tok_is(tline, TOKEN_ID)) {
nasm_nonfatal("`%s' expects a context identifier", dname);
goto done;
}
if (skip_white(tline->next)) {
nasm_warn(WARN_PP_TRAILING, "trailing garbage after `%s' ignored",
dname);
}
p = tok_text(tline);
} else {
p = NULL; /* Anonymous */
}
if (op == PP_PUSH) {
nasm_new(ctx);
ctx->depth = cstk ? cstk->depth + 1 : 1;
ctx->next = cstk;
ctx->name = p ? nasm_strdup(p) : NULL;
ctx->number = unique++;
cstk = ctx;
} else {
/* %pop or %repl */
if (!cstk) {
nasm_nonfatal("`%s': context stack is empty", dname);
} else if (op == PP_POP) {
if (p && (!cstk->name || nasm_stricmp(p, cstk->name)))
nasm_nonfatal("`%s' in wrong context: %s, "
"expected %s",
dname, cstk->name ? cstk->name : "anonymous", p);
else
ctx_pop();
} else {
/* op == PP_REPL */
nasm_free((char *)cstk->name);
cstk->name = p ? nasm_strdup(p) : NULL;
p = NULL;
}
}
break;
case PP_FATAL:
severity = ERR_FATAL;
goto issue_error;
case PP_ERROR:
severity = ERR_NONFATAL|ERR_PASS2;
goto issue_error;
case PP_WARNING:
/*!
*!user [on] \c{%warning} directives
*! controls output of \c{%warning} directives (see \k{pperror}).
*/
severity = ERR_WARNING|WARN_USER|ERR_PASS2;
goto issue_error;
case PP_NOTE:
severity = ERR_NOTE;
goto issue_error;
issue_error:
{
/* Only error out if this is the final pass */
tline->next = expand_smacro(tline->next);
tline = tline->next;
tline = skip_white(tline);
t = tline ? tline->next : NULL;
t = skip_white(t);
if (tok_is(tline, TOKEN_STR) && !t) {
/* The line contains only a quoted string */
p = unquote_token(tline); /* Ignore NUL character truncation */
nasm_error(severity, "%s", p);
} else {
/* Not a quoted string, or more than a quoted string */
q = detoken(tline, false);
nasm_error(severity, "%s", q);
nasm_free(q);
}
break;
}
CASE_PP_IF:
if (istk->conds && !emitting(istk->conds->state))
j = COND_NEVER;
else {
j = if_condition(tline->next, op);
tline->next = NULL; /* it got freed */
}
cond = nasm_malloc(sizeof(Cond));
cond->next = istk->conds;
cond->state = j;
istk->conds = cond;
if(istk->mstk.mstk)
istk->mstk.mstk->condcnt++;
break;
CASE_PP_ELIF:
if (!istk->conds) {
nasm_nonfatal("`%s': no matching `%%if'", dname);
break;
}
switch(istk->conds->state) {
case COND_IF_TRUE:
istk->conds->state = COND_DONE;
break;
case COND_DONE:
case COND_NEVER:
break;
case COND_ELSE_TRUE:
case COND_ELSE_FALSE:
/*!
*!pp-else-elif [on] \c{%elif} after \c{%else}
*! warns that an \c{%elif}-type directive was encountered
*! after \c{%else} has already been encounted. As a result, the
*! content of the \c{%elif} will never be expanded.
*/
nasm_warn(WARN_PP_ELSE_ELIF|ERR_PP_PRECOND,
"`%s' after `%%else', ignoring content", dname);
istk->conds->state = COND_NEVER;
break;
case COND_IF_FALSE:
/*
* IMPORTANT: In the case of %if, we will already have
* called expand_mmac_params(); however, if we're
* processing an %elif we must have been in a
* non-emitting mode, which would have inhibited
* the normal invocation of expand_mmac_params().
* Therefore, we have to do it explicitly here.
*/
j = if_condition(expand_mmac_params(tline->next), op);
tline->next = NULL; /* it got freed */
istk->conds->state = j;
break;
}
break;
case PP_ELSE:
if (tline->next)
nasm_warn(WARN_PP_TRAILING|ERR_PP_PRECOND,
"trailing garbage after `%s' ignored", dname);
if (!istk->conds) {
nasm_nonfatal("`%s': no matching `%%if'", dname);
break;
}
switch(istk->conds->state) {
case COND_IF_TRUE:
case COND_DONE:
istk->conds->state = COND_ELSE_FALSE;
break;
case COND_NEVER:
break;
case COND_IF_FALSE:
istk->conds->state = COND_ELSE_TRUE;
break;
case COND_ELSE_TRUE:
case COND_ELSE_FALSE:
/*!
*!pp-else-else [on] \c{%else} after \c{%else}
*! warns that a second \c{%else} clause was found for
*! the same \c{%if} statement. The content of this \c{%else}
*! clause will never be expanded.
*/
nasm_warn(WARN_PP_ELSE_ELSE|ERR_PP_PRECOND,
"`%s' after `%%else', ignoring content", dname);
istk->conds->state = COND_NEVER;
break;
}
break;
case PP_ENDIF:
if (tline->next) {
nasm_warn(WARN_PP_TRAILING|ERR_PP_PRECOND,
"trailing garbage after `%s' ignored", dname);
}
if (!istk->conds) {
nasm_nonfatal("`%s': no matching `%%if'", dname);
break;
}
cond = istk->conds;
istk->conds = cond->next;
nasm_free(cond);
if(istk->mstk.mstk)
istk->mstk.mstk->condcnt--;
break;
case PP_RMACRO:
case PP_MACRO:
{
MMacro *def;
nasm_assert(!defining);
nasm_new(def);
def->casesense = casesense;
/*
* dstk.mstk points to the previous definition bracket,
* whereas dstk.mmac points to the topmost mmacro, which
* in this case is the one we are just starting to create.
*/
def->dstk.mstk = defining;
def->dstk.mmac = def;
if (op == PP_RMACRO)
def->max_depth = nasm_limit[LIMIT_MACRO_LEVELS];
if (!parse_mmacro_spec(tline, def, dname)) {
nasm_free(def);
goto done;
}
defining = def;
defining->where = istk->where;
mmac = (MMacro *) hash_findix(&mmacros, defining->name);
while (mmac) {
if (!strcmp(mmac->name, defining->name) &&
(mmac->nparam_min <= defining->nparam_max
|| defining->plus)
&& (defining->nparam_min <= mmac->nparam_max
|| mmac->plus)) {
/*!
*!pp-macro-redef-multi [on] redefining multi-line macro
*! warns that a multi-line macro is being redefined,
*! without first removing the old definition with
*! \c{%unmacro}.
*/
nasm_warn(WARN_PP_MACRO_REDEF_MULTI,
"redefining multi-line macro `%s'",
defining->name);
break;
}
mmac = mmac->next;
}
break;
}
case PP_ENDM:
case PP_ENDMACRO:
if (!(defining && defining->name)) {
nasm_nonfatal("`%s': not defining a macro", tok_text(tline));
goto done;
}
mmhead = (MMacro **) hash_findi_add(&mmacros, defining->name);
defining->next = *mmhead;
*mmhead = defining;
defining = NULL;
break;
case PP_EXITMACRO:
/*
* We must search along istk->expansion until we hit a
* macro-end marker for a macro with a name. Then we
* bypass all lines between exitmacro and endmacro.
*/
list_for_each(l, istk->expansion)
if (l->finishes && l->finishes->name)
break;
if (l) {
/*
* Remove all conditional entries relative to this
* macro invocation. (safe to do in this context)
*/
for ( ; l->finishes->condcnt > 0; l->finishes->condcnt --) {
cond = istk->conds;
if (!cond) {
l->finishes->condcnt = 0;
break; /* Possible in case of invalid nesting */
}
istk->conds = cond->next;
nasm_free(cond);
}
istk->expansion = l;
} else {
nasm_nonfatal("`%%exitmacro' not within `%%macro' block");
}
break;
case PP_UNIMACRO:
casesense = false;
/* fall through */
case PP_UNMACRO:
{
MMacro **mmac_p;
MMacro spec;
nasm_zero(spec);
spec.casesense = casesense;
if (!parse_mmacro_spec(tline, &spec, dname)) {
goto done;
}
mmac_p = (MMacro **) hash_findi(&mmacros, spec.name, NULL);
if (!mmac_p) {
/* No such macro */
free_tlist(spec.dlist);
break;
}
/* Check the macro to be undefined is not being expanded */
list_for_each(l, istk->expansion) {
if (l->finishes == *mmac_p) {
nasm_nonfatal("`%%unmacro' can't undefine the macro being expanded");
/*
* Do not release the macro instance to avoid using the freed
* memory while proceeding the expansion.
*/
goto done;
}
}
while (mmac_p && *mmac_p) {
mmac = *mmac_p;
if (mmac->casesense == spec.casesense &&
!mstrcmp(mmac->name, spec.name, spec.casesense) &&
mmac->nparam_min == spec.nparam_min &&
mmac->nparam_max == spec.nparam_max &&
mmac->plus == spec.plus) {
*mmac_p = mmac->next;
free_mmacro(mmac);
} else {
mmac_p = &mmac->next;
}
}
free_tlist(spec.dlist);
break;
}
case PP_ROTATE:
while (tok_white(tline->next))
tline = tline->next;
if (!tline->next) {
free_tlist(origline);
nasm_nonfatal("`%s' missing rotate count", dname);
return DIRECTIVE_FOUND;
}
t = expand_smacro(tline->next);
tline->next = NULL;
pps.tptr = tline = t;
pps.ntokens = -1;
tokval.t_type = TOKEN_INVALID;
evalresult =
evaluate(ppscan, &pps, &tokval, NULL, true, NULL);
free_tlist(tline);
if (!evalresult)
return DIRECTIVE_FOUND;
if (tokval.t_type) {
nasm_warn(WARN_PP_TRAILING,
"trailing garbage after expression ignored");
}
if (!is_simple(evalresult)) {
nasm_nonfatal("non-constant value given to `%s'", dname);
return DIRECTIVE_FOUND;
}
mmac = istk->mstk.mmac;
if (!mmac) {
nasm_nonfatal("`%s' invoked outside a macro call", dname);;
} else if (mmac->nparam == 0) {
nasm_nonfatal("`%s' invoked within macro without parameters", dname);
} else {
int rotate = mmac->rotate + reloc_value(evalresult);
rotate %= (int)mmac->nparam;
if (rotate < 0)
rotate += mmac->nparam;
mmac->rotate = rotate;
}
break;
case PP_REP:
{
MMacro *tmp_defining;
nolist = 0;
tline = skip_white(tline->next);
if (tok_is(tline, TOKEN_ID) && tline->len == 7 &&
!nasm_memicmp(tline->text.a, ".nolist", 7)) {
if (!list_option('f'))
nolist |= NL_LIST; /* ... but update line numbers */
tline = skip_white(tline->next);
}
if (tline) {
pps.tptr = expand_smacro(tline);
pps.ntokens = -1;
tokval.t_type = TOKEN_INVALID;
/* XXX: really critical?! */
evalresult =
evaluate(ppscan, &pps, &tokval, NULL, true, NULL);
if (!evalresult)
goto done;
if (tokval.t_type)
nasm_warn(WARN_PP_TRAILING, "trailing garbage after expression ignored");
if (!is_simple(evalresult)) {
nasm_nonfatal("non-constant value given to `%s'", dname);
goto done;
}
count = reloc_value(evalresult);
if (count > nasm_limit[LIMIT_REP]) {
nasm_nonfatal("`%s' count %"PRId64" exceeds limit (currently %"PRId64")",
dname, count, nasm_limit[LIMIT_REP]);
count = 0;
} else if (count < 0) {
/*!
*!pp-rep-negative [on] regative \c{%rep} count
*!=negative-rep
*! warns about a negative count given to the \c{%rep}
*! preprocessor directive.
*/
nasm_warn(ERR_PASS2|WARN_PP_REP_NEGATIVE,
"negative `%s' count: %"PRId64, dname, count);
count = 0;
} else {
count++;
}
} else {
nasm_nonfatal("`%s' expects a repeat count", dname);
count = 0;
}
tmp_defining = defining;
nasm_new(defining);
defining->nolist = nolist;
defining->in_progress = count;
defining->mstk = istk->mstk;
defining->dstk.mstk = tmp_defining;
defining->dstk.mmac = tmp_defining ? tmp_defining->dstk.mmac : NULL;
defining->where = istk->where;
break;
}
case PP_ENDREP:
if (!defining || defining->name) {
nasm_nonfatal("`%%endrep': no matching `%%rep'");
goto done;
}
/*
* Now we have a "macro" defined - although it has no name
* and we won't be entering it in the hash tables - we must
* push a macro-end marker for it on to istk->expansion.
* After that, it will take care of propagating itself (a
* macro-end marker line for a macro which is really a %rep
* block will cause the macro to be re-expanded, complete
* with another macro-end marker to ensure the process
* continues) until the whole expansion is forcibly removed
* from istk->expansion by a %exitrep.
*/
nasm_new(l);
l->next = istk->expansion;
l->finishes = defining;
l->first = NULL;
l->where = src_where();
istk->expansion = l;
istk->mstk.mstk = defining;
/* A loop does not change istk->noline */
istk->nolist += !!(defining->nolist & NL_LIST);
if (!istk->nolist)
lfmt->uplevel(LIST_MACRO, 0);
defining = defining->dstk.mstk;
break;
case PP_EXITREP:
/*
* We must search along istk->expansion until we hit a
* macro-end marker for a macro with no name. Then we set
* its `in_progress' flag to 0.
*/
list_for_each(l, istk->expansion)
if (l->finishes && !l->finishes->name)
break;
if (l)
l->finishes->in_progress = 0;
else
nasm_nonfatal("`%%exitrep' not within `%%rep' block");
break;
case PP_DEFINE:
case PP_XDEFINE:
case PP_DEFALIAS:
{
SMacro tmpl;
Token **lastp;
int nparam;
if (!(mname = get_id(&tline, dname)))
goto done;
nasm_zero(tmpl);
lastp = &tline->next;
nparam = parse_smacro_template(&lastp, &tmpl);
tline = *lastp;
*lastp = NULL;
if (unlikely(op == PP_DEFALIAS)) {
macro_start = tline;
if (!is_macro_id(macro_start)) {
nasm_nonfatal("`%s' expects a macro identifier to alias",
dname);
goto done;
}
tt = macro_start->next;
macro_start->next = NULL;
tline = tline->next;
tline = skip_white(tline);
if (tline && tline->type) {
nasm_warn(WARN_PP_TRAILING,
"trailing garbage after aliasing identifier ignored");
}
free_tlist(tt);
tmpl.alias = true;
} else {
if (op == PP_XDEFINE) {
/* Protect macro parameter tokens */
if (nparam)
mark_smac_params(tline, &tmpl, TOKEN_XDEF_PARAM);
tline = expand_smacro(tline);
}
macro_start = tline;
}
/*
* Good. We now have a macro name, a parameter count, and a
* token list (in reverse order) for an expansion. We ought
* to be OK just to create an SMacro, store it, and let
* free_tlist have the rest of the line (which we have
* carefully re-terminated after chopping off the expansion
* from the end).
*/
define_smacro(mname, casesense, macro_start, &tmpl);
break;
}
case PP_UNDEF:
case PP_UNDEFALIAS:
if (!(mname = get_id(&tline, dname)))
goto done;
if (tline->next)
nasm_warn(WARN_PP_TRAILING,
"trailing garbage after macro name ignored");
undef_smacro(mname, op == PP_UNDEFALIAS);
break;
case PP_DEFSTR:
if (!(mname = get_id(&tline, dname)))
goto done;
last = tline;
tline = expand_smacro(tline->next);
last->next = NULL;
tline = zap_white(tline);
q = detoken(tline, false);
macro_start = make_tok_qstr(NULL, q);
nasm_free(q);
/*
* We now have a macro name, an implicit parameter count of
* zero, and a string token to use as an expansion. Create
* and store an SMacro.
*/
define_smacro(mname, casesense, macro_start, NULL);
break;
case PP_DEFTOK:
if (!(mname = get_id(&tline, dname)))
goto done;
last = tline;
tline = expand_smacro(tline->next);
last->next = NULL;
t = skip_white(tline);
/* t should now point to the string */
if (!tok_is(t, TOKEN_STR)) {
nasm_nonfatal("`%s' requires string as second parameter", dname);
free_tlist(tline);
goto done;
}
/*
* Convert the string to a token stream.
*/
macro_start = tokenize(unquote_token_cstr(t));
/*
* We now have a macro name, an implicit parameter count of
* zero, and a numeric token to use as an expansion. Create
* and store an SMacro.
*/
define_smacro(mname, casesense, macro_start, NULL);
free_tlist(tline);
break;
case PP_PATHSEARCH:
{
const char *found_path;
if (!(mname = get_id(&tline, dname)))
goto done;
last = tline;
tline = expand_smacro(tline->next);
last->next = NULL;
t = skip_white(tline);
if (!t || (t->type != TOKEN_STR &&
t->type != TOKEN_INTERNAL_STR)) {
nasm_nonfatal("`%s' expects a file name", dname);
free_tlist(tline);
goto done;
}
if (t->next)
nasm_warn(WARN_PP_TRAILING,
"trailing garbage after `%s' ignored", dname);
p = unquote_token_cstr(t);
inc_fopen(p, NULL, &found_path, INC_PROBE, NF_BINARY);
if (!found_path)
found_path = p;
macro_start = make_tok_qstr(NULL, found_path);
/*
* We now have a macro name, an implicit parameter count of
* zero, and a string token to use as an expansion. Create
* and store an SMacro.
*/
define_smacro(mname, casesense, macro_start, NULL);
free_tlist(tline);
break;
}
case PP_STRLEN:
if (!(mname = get_id(&tline, dname)))
goto done;
last = tline;
tline = expand_smacro(tline->next);
last->next = NULL;
t = skip_white(tline);
/* t should now point to the string */
if (!tok_is(t, TOKEN_STR)) {
nasm_nonfatal("`%s' requires string as second parameter", dname);
free_tlist(tline);
free_tlist(origline);
return DIRECTIVE_FOUND;
}
unquote_token(t);
macro_start = make_tok_num(NULL, t->len);
/*
* We now have a macro name, an implicit parameter count of
* zero, and a numeric token to use as an expansion. Create
* and store an SMacro.
*/
define_smacro(mname, casesense, macro_start, NULL);
free_tlist(tline);
free_tlist(origline);
return DIRECTIVE_FOUND;
case PP_STRCAT:
if (!(mname = get_id(&tline, dname)))
goto done;
last = tline;
tline = expand_smacro(tline->next);
last->next = NULL;
macro_start = pp_strcat(tline, dname);
/*
* We now have a macro name, an implicit parameter count of
* zero, and a string token to use as an expansion. Create
* and store an SMacro.
*/
if (macro_start)
define_smacro(mname, casesense, macro_start, NULL);
break;
case PP_SUBSTR:
if (!(mname = get_id(&tline, dname)))
goto done;
last = tline;
tline = expand_smacro(tline->next);
last->next = NULL;
macro_start = pp_substr(tline, dname);
/*
* We now have a macro name, an implicit parameter count of
* zero, and a string token to use as an expansion. Create
* and store an SMacro.
*/
if (macro_start)
define_smacro(mname, casesense, macro_start, NULL);
break;
case PP_ASSIGN:
if (!(mname = get_id(&tline, dname)))
goto done;
last = tline;
tline = tline->next;
last->next = NULL;
assign_smacro(mname, casesense, tline, dname);
goto done;
case PP_ALIASES:
tline = tline->next;
tline = expand_smacro(tline);
ppconf.noaliases = !pp_get_boolean_option(tline, !ppconf.noaliases);
break;
case PP_LINE:
nasm_panic("`%s' directive not preprocessed early", dname);
break;
case PP_NULL:
/* Goes nowhere, does nothing... */
break;
}
done:
free_tlist(origline);
return DIRECTIVE_FOUND;
}
/*
* Ensure that a macro parameter contains a condition code and
* nothing else. Return the condition code index if so, or -1
* otherwise.
*/
static int find_cc(Token * t)
{
Token *tt;
if (!t)
return -1; /* Probably a %+ without a space */
t = skip_white(t);
if (!tok_is(t, TOKEN_ID))
return -1;
tt = t->next;
tt = skip_white(tt);
if (tok_isnt(tt, ','))
return -1;
return bsii(tok_text(t), (const char **)conditions,
ARRAY_SIZE(conditions));
}
enum concat_flags {
CONCAT_ID = 0x01,
CONCAT_LOCAL_MACRO = 0x02,
CONCAT_ENVIRON = 0x04,
CONCAT_PREPROC_ID = 0x08,
CONCAT_NUM = 0x10,
CONCAT_FLOAT = 0x20,
CONCAT_OP = 0x40 /* Operators */
};
struct concat_mask {
enum concat_flags mask_head;
enum concat_flags mask_tail;
};
static inline bool pp_concat_match(const Token *t, enum concat_flags mask)
{
enum concat_flags ctype = 0;
if (!t)
return false;
switch (t->type) {
case TOKEN_ID:
case TOKEN_QMARK: /* Keyword, treated as ID for pasting */
ctype = CONCAT_ID;
break;
case TOKEN_LOCAL_MACRO:
ctype = CONCAT_LOCAL_MACRO;
break;
case TOKEN_ENVIRON:
ctype = CONCAT_ENVIRON;
break;
case TOKEN_PREPROC_ID:
ctype = CONCAT_PREPROC_ID;
break;
case TOKEN_NUM:
case TOKEN_FLOAT:
ctype = CONCAT_NUM;
break;
case TOKEN_HERE:
case TOKEN_BASE:
/* NASM 2.15 treats these as operators, but is that sane? */
ctype = CONCAT_OP;
break;
case TOKEN_OTHER:
ctype = CONCAT_OP; /* For historical reasons */
break;
default:
if (t->type > TOKEN_WHITESPACE && t->type < TOKEN_MAX_OPERATOR)
ctype = CONCAT_OP;
else
ctype = 0;
}
return !!(ctype & mask);
}
/*
* This routines walks over tokens stream and handles tokens
* pasting, if @handle_explicit passed then explicit pasting
* term is handled, otherwise -- implicit pastings only.
* The @m array can contain a series of token types which are
* executed as separate passes.
*/
static bool paste_tokens(Token **head, const struct concat_mask *m,
size_t mnum, bool handle_explicit)
{
Token *tok, *t, *next, **prev_next, **prev_nonspace, **nextp;
bool pasted = false;
char *buf, *p;
size_t len, i;
/*
* The last token before pasting. We need it
* to be able to connect new handled tokens.
* In other words if there were a tokens stream
*
* A -> B -> C -> D
*
* and we've joined tokens B and C, the resulting
* stream should be
*
* A -> BC -> D
*/
tok = *head;
prev_next = prev_nonspace = head;
if (tok_white(tok) || tok_is(tok, TOKEN_PASTE))
prev_nonspace = NULL;
while (tok && (next = tok->next)) {
bool did_paste = false;
switch (tok->type) {
case TOKEN_WHITESPACE:
/* Zap redundant whitespaces */
tok->next = next = zap_white(next);
break;
case TOKEN_PASTE:
/* Explicit pasting */
if (!handle_explicit)
break;
did_paste = true;
/* Left pasting token is start of line, just drop %+ */
if (!prev_nonspace) {
prev_next = nextp = head;
t = NULL;
} else {
prev_next = prev_nonspace;
t = *prev_next;
nextp = &t->next;
}
/*
* Delete the %+ token itself plus any whitespace.
* In a sequence of %+ ... %+ ... %+ pasting sequences where
* some expansions in the middle have ended up empty,
* we can end up having multiple %+ tokens in a row;
* just drop whem in that case.
*/
next = *nextp;
while (next) {
if (next->type == TOKEN_PASTE || next->type == TOKEN_WHITESPACE)
next = delete_Token(next);
else
break;
}
*nextp = next;
/*
* Nothing after? Just leave the existing token.
*/
if (!next)
break;
if (!t) {
/* Nothing to actually paste, just zapping the paste */
*prev_next = tok = next;
break;
}
/* An actual paste */
p = buf = nasm_malloc(t->len + next->len + 1);
p = mempcpy(p, tok_text(t), t->len);
p = mempcpy(p, tok_text(next), next->len);
*p = '\0';
delete_Token(t);
t = tokenize(buf);
nasm_free(buf);
if (unlikely(!t)) {
/*
* No output at all? Replace with a single whitespace.
* This should never happen.
*/
tok = t = new_White(NULL);
} else {
*prev_nonspace = tok = t;
}
while (t->next)
t = t->next; /* Find the last token produced */
/* Delete the second token and attach to the end of the list */
t->next = delete_Token(next);
/* We want to restart from the head of the pasted token */
*prev_next = next = tok;
break;
default:
/* implicit pasting */
for (i = 0; i < mnum; i++) {
if (pp_concat_match(tok, m[i].mask_head))
break;
}
if (i >= mnum)
break;
len = tok->len;
while (pp_concat_match(next, m[i].mask_tail)) {
len += next->len;
next = next->next;
}
/* No match or no text to process */
if (len == tok->len)
break;
p = buf = nasm_malloc(len + 1);
while (tok != next) {
p = mempcpy(p, tok_text(tok), tok->len);
tok = delete_Token(tok);
}
*p = '\0';
*prev_next = tok = t = tokenize(buf);
nasm_free(buf);
/*
* Connect pasted into original stream,
* ie A -> new-tokens -> B
*/
while ((tok = t->next)) {
if (tok->type != TOKEN_WHITESPACE && tok->type != TOKEN_PASTE)
prev_nonspace = &t->next;
t = tok;
}
t->next = next;
prev_next = &t->next;
did_paste = true;
break;
}
if (did_paste) {
pasted = true;
} else {
prev_next = &tok->next;
if (next && next->type != TOKEN_WHITESPACE &&
next->type != TOKEN_PASTE)
prev_nonspace = prev_next;
}
tok = next;
}
return pasted;
}
/*
* Computes the proper rotation of mmacro parameters
*/
static int mmac_rotate(const MMacro *mac, unsigned int n)
{
if (--n < mac->nparam)
n = (n + mac->rotate) % mac->nparam;
return n+1;
}
/*
* expands to a list of tokens from %{x:y}
*/
static void expand_mmac_params_range(MMacro *mac, Token *tline, Token ***tail)
{
Token *t;
const char *arg = tok_text(tline) + 1;
int fst, lst, incr, n;
int parsed;
parsed = sscanf(arg, "%d:%d", &fst, &lst);
nasm_assert(parsed == 2);
/*
* only macros params are accounted so
* if someone passes %0 -- we reject such
* value(s)
*/
if (lst == 0 || fst == 0)
goto err;
/* the values should be sane */
if ((fst > (int)mac->nparam || fst < (-(int)mac->nparam)) ||
(lst > (int)mac->nparam || lst < (-(int)mac->nparam)))
goto err;
fst = fst < 0 ? fst + (int)mac->nparam + 1: fst;
lst = lst < 0 ? lst + (int)mac->nparam + 1: lst;
/*
* It will be at least one parameter, as we can loop
* in either direction.
*/
incr = (fst < lst) ? 1 : -1;
while (true) {
n = mmac_rotate(mac, fst);
dup_tlistn(mac->params[n], mac->paramlen[n], tail);
if (fst == lst)
break;
t = make_tok_char(NULL, ',');
**tail = t;
*tail = &t->next;
fst += incr;
}
return;
err:
nasm_nonfatal("`%%{%s}': macro parameters out of range", arg);
return;
}
/*
* Expand MMacro-local things: parameter references (%0, %n, %+n,
* %-n) and MMacro-local identifiers (%%foo) as well as
* macro indirection (%[...]) and range (%{..:..}).
*/
static Token *expand_mmac_params(Token * tline)
{
Token **tail, *thead;
bool changed = false;
MMacro *mac = istk->mstk.mmac;
tail = &thead;
thead = NULL;
while (tline) {
bool change;
bool err_not_mac = false;
Token *t = tline;
const char *text = tok_text(t);
int type = t->type;
tline = tline->next;
t->next = NULL;
switch (type) {
case TOKEN_LOCAL_SYMBOL:
change = true;
if (!mac) {
err_not_mac = true;
break;
}
type = TOKEN_ID;
text = nasm_asprintf("..@%"PRIu64".%s", mac->unique, text+2);
break;
case TOKEN_MMACRO_PARAM:
{
Token *tt = NULL;
change = true;
if (!mac) {
err_not_mac = true;
break;
}
if (strchr(text, ':')) {
/* It is a range */
expand_mmac_params_range(mac, t, &tail);
text = NULL;
break;
}
switch (text[1]) {
/*
* We have to make a substitution of one of the
* forms %1, %-1, %+1, %%foo, %0, %00.
*/
case '0':
if (!text[2]) {
type = TOKEN_NUM;
text = nasm_asprintf("%d", mac->nparam);
break;
}
if (text[2] != '0' || text[3])
goto invalid;
/* a possible captured label == mac->params[0] */
/* fall through */
default:
{
unsigned long n;
char *ep;
n = strtoul(text + 1, &ep, 10);
if (unlikely(*ep))
goto invalid;
if (n <= mac->nparam) {
n = mmac_rotate(mac, n);
dup_tlistn(mac->params[n], mac->paramlen[n], &tail);
}
text = NULL;
break;
}
case '-':
case '+':
{
int cc;
unsigned long n;
char *ep;
n = strtoul(tok_text(t) + 2, &ep, 10);
if (unlikely(*ep))
goto invalid;
if (n && n <= mac->nparam) {
n = mmac_rotate(mac, n);
tt = mac->params[n];
}
cc = find_cc(tt);
if (cc == -1) {
nasm_nonfatal("macro parameter `%s' is not a condition code",
tok_text(t));
text = NULL;
break;
}
type = TOKEN_ID;
if (text[1] == '-') {
int ncc = inverse_ccs[cc];
if (unlikely(ncc == -1)) {
nasm_nonfatal("condition code `%s' is not invertible",
conditions[cc]);
break;
}
cc = ncc;
}
text = nasm_strdup(conditions[cc]);
break;
}
invalid:
nasm_nonfatal("invalid macro parameter: `%s'", text);
text = NULL;
break;
}
break;
}
case TOKEN_PREPROC_Q:
if (mac) {
type = TOKEN_ID;
text = nasm_strdup(mac->iname);
change = true;
} else {
change = false;
}
break;
case TOKEN_PREPROC_QQ:
if (mac) {
type = TOKEN_ID;
text = nasm_strdup(mac->name);
change = true;
} else {
change = false;
}
break;
case TOKEN_INDIRECT:
{
Token *tt;
tt = tokenize(tok_text(t));
tt = expand_mmac_params(tt);
tt = expand_smacro(tt);
tail = steal_tlist(tt, tail);
text = NULL;
change = true;
break;
}
default:
change = false;
break;
}
if (err_not_mac) {
nasm_nonfatal("`%s': not in a macro call", text);
text = NULL;
change = true;
}
if (change) {
if (!text) {
delete_Token(t);
} else {
*tail = t;
tail = &t->next;
set_text(t, text, tok_strlen(text));
t->type = type;
}
changed = true;
} else {
*tail = t;
tail = &t->next;
}
}
*tail = NULL;
if (changed) {
const struct concat_mask t[] = {
{
CONCAT_ID | CONCAT_FLOAT, /* head */
CONCAT_ID | CONCAT_NUM | CONCAT_FLOAT | CONCAT_OP /* tail */
},
{
CONCAT_NUM, /* head */
CONCAT_NUM /* tail */
}
};
paste_tokens(&thead, t, ARRAY_SIZE(t), false);
}
return thead;
}
static Token *expand_smacro_noreset(Token * tline);
static SMacro *expand_one_smacro(Token ***tpp);
/*
* Expand one single-line macro instance given a specific macro and a
* specific set of parameters. Returns a pointer to the expansion, and
* the pointer *epp pointing to the next pointer of the last token of
* the expansion; if the expansion is empty return NULL and *epp is
* unchanged.
*
* mstart is the token containing the token name *as invoked*.
*/
static Token *
expand_smacro_with_params(SMacro *m, Token *mstart, Token **params,
int nparam, Token ***epp)
{
/* Is it a macro or a preprocessor function? Used for diagnostics. */
const char * const mtype = m->name[0] == '%' ? "function" : "macro";
Token *t, *tline, *tup;
bool cond_comma;
const struct smac_param *mparm;
int i;
/* Expand the macro */
m->in_progress++;
/*
* Postprocessing of of parameters. Note that the ordering matters
* here.
*
* mparm points to the current parameter specification
* structure (struct smac_param); this may not match the index
* i in the case of varadic parameters.
*/
if (nparam) {
for (i = 0, mparm = m->params; i < nparam;
i++, mparm += !(mparm->flags & SPARM_VARADIC)) {
const enum sparmflags flags = mparm->flags;
if (flags & SPARM_EVAL) {
/* Evaluate this parameter as a number */
struct ppscan pps;
struct tokenval tokval;
expr *evalresult;
Token *eval_param;
eval_param = zap_white(expand_smacro_noreset(params[i]));
params[i] = NULL;
if (!eval_param) {
/* empty argument */
if (mparm->def) {
params[i] = dup_tlist(mparm->def, NULL);
continue;
} else if (flags & SPARM_OPTIONAL) {
continue;
}
/* otherwise, allow evaluate() to generate an error */
}
pps.tptr = eval_param;
pps.ntokens = -1;
tokval.t_type = TOKEN_INVALID;
evalresult = evaluate(ppscan, &pps, &tokval, NULL, true, NULL);
free_tlist(eval_param);
if (!evalresult) {
/* Nothing meaningful to do */
} else if (tokval.t_type) {
nasm_nonfatal("invalid expression in parameter %d of %s `%s'",
i+1, mtype, m->name);
} else if (!is_simple(evalresult)) {
nasm_nonfatal("non-constant expression in parameter %d of %s `%s'",
i+1, mtype, m->name);
} else {
int64_t v = reloc_value(evalresult);
params[i] = make_tok_num_radix(NULL, v, mparm->radix,
!!(flags & SPARM_UNSIGNED));
}
}
if (flags & SPARM_STR) {
/* Convert expansion to a quoted string */
Token *qs;
qs = expand_smacro_noreset(params[i]);
if ((flags & SPARM_CONDQUOTE) &&
tok_is(qs, TOKEN_STR) && !qs->next) {
/* A single quoted string token */
params[i] = qs;
} else {
char *arg = detoken(qs, false);
free_tlist(qs);
params[i] = make_tok_qstr(NULL, arg);
nasm_free(arg);
}
}
}
}
/* Note: we own the expansion this returns. */
t = m->expand(m, params, nparam);
tup = tline = NULL;
cond_comma = false;
while (t) {
enum token_type type = t->type;
Token *tnext = t->next;
switch (type) {
case TOKEN_PREPROC_Q:
case TOKEN_PREPROC_SQ:
delete_Token(t);
t = dup_Token(tline, mstart);
break;
case TOKEN_PREPROC_QQ:
case TOKEN_PREPROC_SQQ:
{
size_t mlen = strlen(m->name);
size_t len;
char *p, *from;
t->type = mstart->type;
if (t->type == TOKEN_LOCAL_MACRO) {
const char *psp; /* prefix start pointer */
const char *pep; /* prefix end pointer */
size_t plen;
psp = tok_text(mstart);
get_ctx(psp, &pep);
plen = pep - psp;
len = mlen + plen;
from = p = nasm_malloc(len + 1);
p = mempcpy(p, psp, plen);
} else {
len = mlen;
from = p = nasm_malloc(len + 1);
}
p = mempcpy(p, m->name, mlen);
*p = '\0';
set_text_free(t, from, len);
t->next = tline;
break;
}
case TOKEN_COND_COMMA:
delete_Token(t);
t = cond_comma ? make_tok_char(tline, ',') : NULL;
break;
case TOKEN_ID:
case TOKEN_PREPROC_ID:
case TOKEN_LOCAL_MACRO:
{
/*
* Chain this into the target line *before* expanding,
* that way we pick up any arguments to the new macro call,
* if applicable.
*/
Token **tp = &t;
t->next = tline;
expand_one_smacro(&tp);
tline = *tp; /* First token left after any macro call */
break;
}
default:
if (is_smac_param(t->type)) {
int param = smac_nparam(t->type);
nasm_assert(!tup && param < nparam);
delete_Token(t);
t = NULL;
tup = tnext;
tnext = dup_tlist_reverse(params[param], NULL);
cond_comma = false;
} else {
t->next = tline;
}
}
if (t) {
Token *endt = tline;
tline = t;
while (!cond_comma && t && t != endt) {
cond_comma = t->type != TOKEN_WHITESPACE;
t = t->next;
}
}
if (tnext) {
t = tnext;
} else {
t = tup;
tup = NULL;
}
}
if (epp) {
Token **ep = *epp;
for (t = tline; t; t = t->next)
ep = &t->next;
*epp = ep;
}
/* Expansion complete */
m->in_progress--;
return tline;
}
/*
* Count the arguments to an smacro call. Returns 0 if the token following
* is not a left paren. *tp is set to point to the final ) if non-NULL;
* it is left unchanged for the zero-argument case.
*/
static int count_smacro_args(Token *t, Token **tp)
{
int nparam;
int paren, brackets;
t = skip_white(t);
if (!tok_is(t, '('))
return 0;
paren = 1;
nparam = 1;
brackets = 0;
while (paren) {
t = t->next;
if (!t) {
nasm_nonfatal("macro call expects terminating `)'");
return 0;
}
switch (t->type) {
case ',':
if (!brackets && paren == 1)
nparam++;
break;
case '{':
brackets++;
break;
case '}':
if (brackets > 0)
brackets--;
break;
case '(':
if (!brackets)
paren++;
break;
case ')':
if (!brackets)
paren--;
break;
default:
break; /* Normal token */
}
}
if (tp)
*tp = t;
return nparam;
}
/*
* Collect the arguments to an smacro call. The size of the array must have
* been previously counted. It *is* permitted to call this with an nparam
* value that is too small for the macro in question; in that case the
* parameters are treated as missing optional arguments, even if they
* are not optional in the macro specification.
*
* *nparamp is adjusted if some arguments got merged as greedy or entered
* as optional/empty.
*
* Moves *tp to point to the final ) token.
*/
static Token **parse_smacro_args(Token **tp, int *nparamp, const SMacro *m)
{
Token **phead, **pep;
int white = 0;
int brackets = 0;
int paren;
bool bracketed = false;
bool bad_bracket = false;
int i;
enum sparmflags flags;
const struct smac_param *mparm;
Token *t = *tp;
int nparam = *nparamp;
Token **params;
/* Is it a macro or a preprocessor function? Used for diagnostics. */
const char * const mtype = m->name[0] == '%' ? "function" : "macro";
t = skip_white(t);
nasm_assert(tok_is(t, '('));
if (nparam > m->nparam) {
if (m->params[m->nparam-1].flags & SPARM_GREEDY)
*nparamp = nparam = m->nparam;
} else if (nparam < m->nparam) {
*nparamp = nparam = m->nparam; /* Missing optional arguments = empty */
}
paren = 1;
nasm_newn(params, nparam);
i = 0;
mparm = m->params;
flags = mparm->flags;
phead = pep = ¶ms[i];
*pep = NULL;
while (paren) {
bool skip;
t = t->next;
if (!t)
nasm_nonfatal("%s `%s' call expects terminating `)'",
mtype, m->name);
skip = false;
switch (t->type) {
case TOKEN_WHITESPACE:
if (!(flags & SPARM_NOSTRIP)) {
if (brackets || *phead)
white++; /* Keep interior whitespace */
skip = true;
}
break;
case ',':
if (!brackets && paren == 1 && !(flags & SPARM_GREEDY)) {
i++;
nasm_assert(i < nparam);
phead = pep = ¶ms[i];
*pep = NULL;
bracketed = false;
skip = true;
if (!(flags & SPARM_VARADIC)) {
mparm++;
flags = mparm->flags;
}
}
break;
case '{':
if (!bracketed) {
bracketed = !*phead && !(flags & SPARM_NOSTRIP);
skip = bracketed;
}
brackets++;
break;
case '}':
if (brackets > 0) {
if (!--brackets)
skip = bracketed;
}
break;
case '(':
if (!brackets)
paren++;
break;
case ')':
if (!brackets) {
paren--;
if (!paren) {
skip = true;
i++; /* Found last argument */
}
}
break;
default:
break; /* Normal token */
}
if (!skip) {
Token *tt;
bad_bracket |= bracketed && !brackets;
if (white) {
*pep = tt = new_White(NULL);
pep = &tt->next;
white = 0;
}
*pep = tt = dup_Token(NULL, t);
pep = &tt->next;
}
}
*tp = t;
return params;
}
/*
* Expand *one* single-line macro instance. If the first token is not
* a macro at all, it is simply copied to the output and the pointer
* advanced. tpp should be a pointer to a pointer (usually the next
* pointer of the previous token) to the first token. **tpp is updated
* to point to the first token of the expansion, and *tpp updated to
* point to the next pointer of the last token of the expansion.
*
* If the expansion is empty, *tpp will be unchanged but **tpp will
* be advanced past the macro call.
*
* Return the macro expanded, or NULL if no expansion took place.
*/
static SMacro *expand_one_smacro(Token ***tpp)
{
Token **params = NULL;
const char *mname;
Token *mstart = **tpp;
Token *tline = mstart;
SMacro *head, *m;
Token *tafter, **tep;
int nparam = 0;
if (!tline)
return false; /* Empty line, nothing to do */
mname = tok_text(mstart);
smacro_deadman.total--;
smacro_deadman.levels--;
if (unlikely(smacro_deadman.total < 0 || smacro_deadman.levels < 0)) {
if (unlikely(!smacro_deadman.triggered)) {
nasm_nonfatal("interminable macro recursion");
smacro_deadman.triggered = true;
}
goto not_a_macro;
} else if (tline->type == TOKEN_ID || tline->type == TOKEN_PREPROC_ID) {
head = (SMacro *)hash_findix(&smacros, mname);
} else if (tline->type == TOKEN_LOCAL_MACRO) {
Context *ctx = get_ctx(mname, &mname);
head = ctx ? (SMacro *)hash_findix(&ctx->localmac, mname) : NULL;
} else {
goto not_a_macro;
}
/*
* We've hit an identifier of some sort. First check whether the
* identifier is a single-line macro at all, then think about
* checking for parameters if necessary.
*/
list_for_each(m, head) {
if (unlikely(m->alias && ppconf.noaliases))
continue;
if (!mstrcmp(m->name, mname, m->casesense))
break;
}
if (!m) {
goto not_a_macro;
}
/* Parse parameters, if applicable */
params = NULL;
nparam = 0;
if (m->nparam == 0) {
/*
* Simple case: the macro is parameterless.
* Nothing to parse; the expansion code will
* drop the macro name token.
*/
} else {
/*
* Complicated case: at least one macro with this name
* exists and takes parameters. We must find the
* parameters in the call, count them, find the SMacro
* that corresponds to that form of the macro call, and
* substitute for the parameters when we expand. What a
* pain.
*/
tline = skip_white(tline->next);
nparam = count_smacro_args(tline, NULL);
if (!nparam)
goto not_a_macro;
/*
* Look for a macro matching in both name and parameter count.
* We already know any matches cannot be anywhere before the
* current position of "m", so there is no reason to
* backtrack.
*/
while (1) {
if (!m) {
/*!
*!pp-macro-params-single [on] single-line macro calls with wrong parameter count
*!=macro-params-single
*! warns about \i{single-line macros} being invoked
*! with the wrong number of parameters.
*/
nasm_warn(WARN_PP_MACRO_PARAMS_SINGLE|ERR_HOLD,
"single-line macro `%s' exists, "
"but not taking %d parameter%s",
mname, nparam, (nparam == 1) ? "" : "s");
goto not_a_macro;
}
if (!mstrcmp(m->name, mname, m->casesense)) {
if (nparam >= m->nparam_min &&
(m->varadic || nparam <= m->nparam))
break; /* It's good */
}
m = m->next;
}
}
if (m->in_progress && !m->recursive)
goto not_a_macro;
if (nparam) {
params = parse_smacro_args(&tline, &nparam, m);
}
tafter = tline->next; /* Skip past the macro call */
tline->next = NULL; /* Truncate mstart list at the macro call end */
tline = expand_smacro_with_params(m, mstart, params, nparam, &tep);
if (tline) {
**tpp = tline;
*tep = tafter;
*tpp = tep;
} else {
**tpp = tafter;
}
/* Don't do this until after expansion or we will clobber mname */
free_tlist(mstart);
goto done;
/*
* No macro expansion needed; roll back to mstart (if necessary)
* and then advance to the next input token. Note that this is
* by far the common case!
*/
not_a_macro:
*tpp = &mstart->next;
m = NULL;
done:
free_tlist_array(params, nparam);
smacro_deadman.levels++;
return m;
}
/*
* Expand all single-line macro calls made in the given line.
* Return the expanded version of the line. The original is deemed
* to be destroyed in the process. (In reality we'll just move
* Tokens from input to output a lot of the time, rather than
* actually bothering to destroy and replicate.)
*/
static Token *expand_smacro(Token *tline)
{
smacro_deadman.total = nasm_limit[LIMIT_MACRO_TOKENS];
smacro_deadman.levels = nasm_limit[LIMIT_MACRO_LEVELS];
smacro_deadman.triggered = false;
return expand_smacro_noreset(tline);
}
static Token *expand_smacro_noreset(Token *org_tline)
{
Token *tline;
bool expanded;
errhold errhold; /* Hold warning/errors during expansion */
if (!org_tline)
return NULL; /* Empty input */
/*
* Trick: we should avoid changing the start token pointer since it can
* be contained in "next" field of other token. Because of this
* we allocate a copy of first token and work with it; at the end of
* routine we copy it back
*/
tline = dup_Token(org_tline->next, org_tline);
/*
* Pretend that we always end up doing expansion on the first pass;
* that way %+ get processed. However, if we process %+ before the
* first pass, we end up with things like MACRO %+ TAIL trying to
* look up the macro "MACROTAIL", which we don't want.
*/
expanded = true;
while (true) {
static const struct concat_mask tmatch[] = {
{
CONCAT_ID | CONCAT_LOCAL_MACRO |
CONCAT_ENVIRON | CONCAT_PREPROC_ID, /* head */
CONCAT_ID | CONCAT_LOCAL_MACRO |
CONCAT_ENVIRON | CONCAT_PREPROC_ID |
CONCAT_NUM /* tail */
}
};
Token **tail = &tline;
/*
* We hold warnings/errors until we are done in this loop. It is
* possible for nuisance warnings to appear that disappear on later
* passes.
*/
errhold = nasm_error_hold_push();
while (*tail) /* main token loop */
expanded |= !!expand_one_smacro(&tail);
if (!expanded)
break; /* Done! */
/*
* Now scan the entire line and look for successive TOKEN_IDs
* that resulted after expansion (they can't be produced by
* tokenize()). The successive TOKEN_IDs should be concatenated.
* Also we look for %+ tokens and concatenate the tokens
* before and after them (without white spaces in between).
*/
if (!paste_tokens(&tline, tmatch, ARRAY_SIZE(tmatch), true))
break; /* Done again! */
nasm_error_hold_pop(errhold, false);
expanded = false;
}
nasm_error_hold_pop(errhold, true);
if (!tline) {
/*
* The expression expanded to empty line;
* we can't return NULL because of the "trick" above.
* Just set the line to a single WHITESPACE token.
*/
tline = new_White(NULL);
}
steal_Token(org_tline, tline);
org_tline->next = tline->next;
delete_Token(tline);
return org_tline;
}
/*
* Similar to expand_smacro but used exclusively with macro identifiers
* right before they are fetched in. The reason is that there can be
* identifiers consisting of several subparts. We consider that if there
* are more than one element forming the name, user wants a expansion,
* otherwise it will be left as-is. Example:
*
* %define %$abc cde
*
* the identifier %$abc will be left as-is so that the handler for %define
* will suck it and define the corresponding value. Other case:
*
* %define _%$abc cde
*
* In this case user wants name to be expanded *before* %define starts
* working, so we'll expand %$abc into something (if it has a value;
* otherwise it will be left as-is) then concatenate all successive
* PP_IDs into one.
*/
static Token *expand_id(Token * tline)
{
Token *cur, *oldnext = NULL;
if (!tline || !tline->next)
return tline;
cur = tline;
while (cur->next &&
(cur->next->type == TOKEN_ID ||
cur->next->type == TOKEN_PREPROC_ID ||
cur->next->type == TOKEN_LOCAL_MACRO ||
cur->next->type == TOKEN_NUM))
cur = cur->next;
/* If identifier consists of just one token, don't expand */
if (cur == tline)
return tline;
if (cur) {
oldnext = cur->next; /* Detach the tail past identifier */
cur->next = NULL; /* so that expand_smacro stops here */
}
tline = expand_smacro(tline);
if (cur) {
/* expand_smacro possibly changhed tline; re-scan for EOL */
cur = tline;
while (cur && cur->next)
cur = cur->next;
if (cur)
cur->next = oldnext;
}
return tline;
}
/*
* This is called from find_mmacro_in_list() after finding a suitable macro.
*/
static MMacro *use_mmacro(MMacro *m, int *nparamp, Token ***paramsp)
{
int nparam = *nparamp;
Token **params = *paramsp;
/*
* This one is right. Just check if cycle removal
* prohibits us using it before we actually celebrate...
*/
if (m->in_progress > m->max_depth) {
if (m->max_depth > 0) {
/* Document this properly when recursive mmacros re-implemented */
nasm_warn(WARN_OTHER, "reached maximum recursion depth of %i",
m->max_depth);
}
nasm_free(params);
*nparamp = 0;
*paramsp = NULL;
return NULL;
}
/*
* It's right, and we can use it. Add its default
* parameters to the end of our list if necessary.
*/
if (m->defaults && nparam < m->nparam_min + m->ndefs) {
int newnparam = m->nparam_min + m->ndefs;
params = nasm_realloc(params, sizeof(*params) * (newnparam+2));
memcpy(¶ms[nparam+1], &m->defaults[nparam+1-m->nparam_min],
(newnparam - nparam) * sizeof(*params));
nparam = newnparam;
}
/*
* If we've gone over the maximum parameter count (and
* we're in Plus mode), ignore parameters beyond
* nparam_max.
*/
if (m->plus && nparam > m->nparam_max)
nparam = m->nparam_max;
/*
* If nparam was adjusted above, make sure the list is still
* NULL-terminated.
*/
params[nparam+1] = NULL;
/* Done! */
*paramsp = params;
*nparamp = nparam;
return m;
}
/*
* Search a macro list and try to find a match. If matching, call
* use_mmacro() to set up the macro call. m points to the list of
* search, which is_mmacro() sets to the first *possible* match.
*/
static MMacro *
find_mmacro_in_list(MMacro *m, const char *finding,
int *nparamp, Token ***paramsp)
{
int nparam = *nparamp;
while (m) {
if (m->nparam_min <= nparam
&& (m->plus || nparam <= m->nparam_max)) {
/*
* This one matches, use it.
*/
return use_mmacro(m, nparamp, paramsp);
}
/*
* Otherwise search for the next one with a name match.
*/
list_for_each(m, m->next) {
if (!mstrcmp(m->name, finding, m->casesense))
break;
}
}
return NULL;
}
/*
* Determine whether the given line constitutes a multi-line macro
* call, and return the MMacro structure called if so. Doesn't have
* to check for an initial label - that's taken care of in
* expand_mmacro - but must check numbers of parameters. Guaranteed
* to be called with tline->type == TOKEN_ID, so the putative macro
* name is easy to find.
*/
static MMacro *is_mmacro(Token * tline, int *nparamp, Token ***paramsp)
{
MMacro *head, *m, *found;
Token **params, **comma;
int raw_nparam, nparam;
const char *finding = tok_text(tline);
bool empty_args = !tline->next;
*nparamp = 0;
*paramsp = NULL;
head = (MMacro *) hash_findix(&mmacros, finding);
/*
* Efficiency: first we see if any macro exists with the given
* name which isn't already excluded by macro cycle removal.
* (The cycle removal test here helps optimize the case of wrapping
* instructions, and is cheap to do here.)
*
* If not, we can return NULL immediately. _Then_ we
* count the parameters, and then we look further along the
* list if necessary to find the proper MMacro.
*/
list_for_each(m, head) {
if (!mstrcmp(m->name, finding, m->casesense) &&
(m->in_progress != 1 || m->max_depth > 0))
break; /* Found something that needs consideration */
}
if (!m)
return NULL;
/*
* OK, we have a potential macro. Count and demarcate the
* parameters.
*/
comma = count_mmac_params(tline->next, nparamp, paramsp);
raw_nparam = *nparamp;
/*
* Search for an exact match. This cannot come *before* the m
* found in the list search before, so we can start there.
*
* If found is NULL and *paramsp has been cleared, then we
* encountered an error for which we have already issued a
* diagnostic, so we should not proceed.
*/
found = find_mmacro_in_list(m, finding, nparamp, paramsp);
if (!*paramsp)
return NULL;
nparam = *nparamp;
params = *paramsp;
/*
* Special weirdness: in NASM < 2.15, an expansion of
* *only* whitespace, as can happen during macro expansion under
* certain circumstances, is counted as zero arguments for the
* purpose of %0, but one argument for the purpose of macro
* matching! In particular, this affects:
*
* foobar %1
*
* ... with %1 being empty; this would call the one-argument
* version of "foobar" with an empty argument, equivalent to
*
* foobar {%1}
*
* ... except that %0 would be set to 0 inside foobar, even if
* foobar is declared with "%macro foobar 1" or equivalent!
*
* The proper way to do that is to define "%macro foobar 0-1".
*
* To be compatible without doing something too stupid, try to
* match a zero-argument macro first, but if that fails, try
* for a one-argument macro with the above behavior.
*
* Furthermore, NASM < 2.15 will match stripping a tailing empty
* argument, but in that case %0 *does* reflect that this argument
* have been stripped; this is handled in count_mmac_params().
*
* To disable these insane legacy behaviors, use:
*
* %pragma preproc sane_empty_expansion yes
*
*!pp-macro-params-legacy [on] improperly calling multi-line macro for legacy support
*!=macro-params-legacy
*! warns about \i{multi-line macros} being invoked
*! with the wrong number of parameters, but for bug-compatibility
*! with NASM versions older than 2.15, NASM tried to fix up the
*! parameters to match the legacy behavior and call the macro anyway.
*! This can happen in certain cases where there are empty arguments
*! without braces, sometimes as a result of macro expansion.
*!-
*! The legacy behavior is quite strange and highly context-dependent,
*! and can be disabled with:
*!-
*! \c %pragma preproc sane_empty_expansion true
*!-
*! It is highly recommended to use this option in new code.
*/
if (!ppconf.sane_empty_expansion) {
if (!found) {
if (raw_nparam == 0 && !empty_args) {
/*
* A single all-whitespace parameter as the only thing?
* Look for a one-argument macro, but don't adjust
* *nparamp.
*/
int bogus_nparam = 1;
params[2] = NULL;
found = find_mmacro_in_list(m, finding, &bogus_nparam, paramsp);
} else if (raw_nparam > 1 && comma) {
Token *comma_tail = *comma;
/*
* Drop the terminal argument and try again.
* If we fail, we need to restore the comma to
* preserve tlist.
*/
*comma = NULL;
*nparamp = raw_nparam - 1;
found = find_mmacro_in_list(m, finding, nparamp, paramsp);
if (found)
free_tlist(comma_tail);
else
*comma = comma_tail;
}
if (!*paramsp)
return NULL;
} else if (comma) {
free_tlist(*comma);
*comma = NULL;
if (raw_nparam > found->nparam_min &&
raw_nparam <= found->nparam_min + found->ndefs) {
/* Replace empty argument with default parameter */
params[raw_nparam] =
found->defaults[raw_nparam - found->nparam_min];
} else if (raw_nparam > found->nparam_max && found->plus) {
/* Just drop the comma, don't adjust argument count */
} else {
/* Drop argument. This may cause nparam < nparam_min. */
params[raw_nparam] = NULL;
*nparamp = nparam = raw_nparam - 1;
}
}
if (found) {
if (raw_nparam < found->nparam_min ||
(raw_nparam > found->nparam_max && !found->plus)) {
nasm_warn(WARN_PP_MACRO_PARAMS_LEGACY,
"improperly calling multi-line macro `%s' with %d parameters",
found->name, raw_nparam);
} else if (comma) {
nasm_warn(WARN_PP_MACRO_PARAMS_LEGACY,
"dropping trailing empty parameter in call to multi-line macro `%s'", found->name);
}
}
}
/*
* After all that, we didn't find one with the right number of
* parameters. Issue a warning, and fail to expand the macro.
*!
*!pp-macro-params-multi [on] multi-line macro calls with wrong parameter count
*!=macro-params-multi
*! warns about \i{multi-line macros} being invoked
*! with the wrong number of parameters. See \k{mlmacover} for an
*! example of why you might want to disable this warning.
*/
if (found)
return found;
nasm_warn(WARN_PP_MACRO_PARAMS_MULTI,
"multi-line macro `%s' exists, but not taking %d parameter%s",
finding, nparam, (nparam == 1) ? "" : "s");
nasm_free(*paramsp);
return NULL;
}
#if 0
/*
* Save MMacro invocation specific fields in
* preparation for a recursive macro expansion
*/
static void push_mmacro(MMacro *m)
{
MMacroInvocation *i;
i = nasm_malloc(sizeof(MMacroInvocation));
i->prev = m->prev;
i->params = m->params;
i->iline = m->iline;
i->nparam = m->nparam;
i->rotate = m->rotate;
i->paramlen = m->paramlen;
i->unique = m->unique;
i->condcnt = m->condcnt;
m->prev = i;
}
/*
* Restore MMacro invocation specific fields that were
* saved during a previous recursive macro expansion
*/
static void pop_mmacro(MMacro *m)
{
MMacroInvocation *i;
if (m->prev) {
i = m->prev;
m->prev = i->prev;
m->params = i->params;
m->iline = i->iline;
m->nparam = i->nparam;
m->rotate = i->rotate;
m->paramlen = i->paramlen;
m->unique = i->unique;
m->condcnt = i->condcnt;
nasm_free(i);
}
}
#endif
/*
* List an mmacro call with arguments (-Lm option)
*/
static void list_mmacro_call(const MMacro *m)
{
const char prefix[] = " ;;; [macro] ";
size_t namelen, size;
char *buf, *p;
unsigned int i;
const Token *t;
namelen = strlen(m->iname);
size = namelen + sizeof(prefix); /* Includes final null (from prefix) */
for (i = 1; i <= m->nparam; i++) {
int j = 0;
size += 3; /* Braces and space/comma */
list_for_each(t, m->params[i]) {
if (j++ >= m->paramlen[i])
break;
size += (t->type == TOKEN_WHITESPACE) ? 1 : t->len;
}
}
buf = p = nasm_malloc(size);
p = mempcpy(p, prefix, sizeof(prefix) - 1);
p = mempcpy(p, m->iname, namelen);
*p++ = ' ';
for (i = 1; i <= m->nparam; i++) {
int j = 0;
*p++ = '{';
list_for_each(t, m->params[i]) {
if (j++ >= m->paramlen[i])
break;
p = mempcpy(p, tok_text(t), t->len);
}
*p++ = '}';
*p++ = ',';
}
*--p = '\0'; /* Replace last delimiter with null */
lfmt->line(LIST_MACRO, -1, buf);
nasm_free(buf);
}
/*
* Collect information about macro invocations for the benefit of
* the debugger. During execution we create a reverse list; before
* calling the backend reverse it to definition/invocation order just
* to be nicer. [XXX: not implemented yet]
*/
struct debug_macro_inv *debug_current_macro;
/* Get/create a addr structure for a seg:inv combo */
static struct debug_macro_addr *
debug_macro_get_addr_inv(int32_t seg, struct debug_macro_inv *inv)
{
struct debug_macro_addr *addr;
nasm_static_assert(offsetof(struct debug_macro_addr, tree) == 0);
if (likely(seg == inv->lastseg))
return inv->addr.last;
inv->lastseg = seg;
addr = (struct debug_macro_addr *)
rb_search_exact(inv->addr.tree, seg);
if (unlikely(!addr)) {
nasm_new(addr);
addr->tree.key = seg;
inv->addr.tree = rb_insert(inv->addr.tree, &addr->tree);
inv->naddr++;
if (inv->up)
addr->up = debug_macro_get_addr_inv(seg, inv->up);
}
return inv->addr.last = addr;
}
/* Get/create an addr structure for a seg in debug_current_macro */
struct debug_macro_addr *debug_macro_get_addr(int32_t seg)
{
return debug_macro_get_addr_inv(seg, debug_current_macro);
}
static struct debug_macro_info dmi;
static struct debug_macro_inv_list *current_inv_list = &dmi.inv;
static void debug_macro_start(MMacro *m, struct src_location where)
{
struct debug_macro_def *def = m->dbg.def;
struct debug_macro_inv *inv;
nasm_assert(!m->dbg.inv);
/* First invocation? Need to create a def structure */
if (unlikely(!def)) {
nasm_new(def);
def->name = nasm_strdup(m->name);
def->where = m->where;
def->next = dmi.def.l;
dmi.def.l = def;
dmi.def.n++;
m->dbg.def = def;
}
nasm_new(inv);
inv->lastseg = NO_SEG;
inv->where = where;
inv->up = debug_current_macro;
inv->next = current_inv_list->l;
inv->def = def;
current_inv_list->l = inv;
current_inv_list->n++;
current_inv_list = &inv->down;
def->ninv++;
m->dbg.inv = inv;
debug_current_macro = inv;
}
static void debug_macro_end(MMacro *m)
{
struct debug_macro_inv *inv = m->dbg.inv;
nasm_assert(inv == debug_current_macro);
list_reverse(inv->down.l);
m->dbg.inv = NULL;
inv = inv->up;
m = istk->mstk.mmac;
if (m) {
nasm_assert(inv == m->dbg.inv);
debug_current_macro = inv;
current_inv_list = &inv->down;
} else {
nasm_assert(!inv);
debug_current_macro = NULL;
current_inv_list = &dmi.inv;
}
}
static void free_debug_macro_addr_tree(struct rbtree *tree)
{
struct rbtree *left, *right;
nasm_static_assert(offsetof(struct debug_macro_addr,tree) == 0);
if (!tree)
return;
left = rb_left(tree);
right = rb_right(tree);
nasm_free(tree);
free_debug_macro_addr_tree(left);
free_debug_macro_addr_tree(right);
}
static void free_debug_macro_inv_list(struct debug_macro_inv *inv)
{
struct debug_macro_inv *itmp;
if (!inv)
return;
list_for_each_safe(inv, itmp, inv) {
free_debug_macro_inv_list(inv->down.l);
free_debug_macro_addr_tree(inv->addr.tree);
nasm_free(inv);
}
}
static void free_debug_macro_info(void)
{
struct debug_macro_def *def, *dtmp;
list_for_each_safe(def, dtmp, dmi.def.l)
nasm_free(def);
free_debug_macro_inv_list(dmi.inv.l);
nasm_zero(dmi);
}
static void debug_macro_output(void)
{
list_reverse(dmi.inv.l);
dfmt->debug_mmacros(&dmi);
free_debug_macro_info();
}
/*
* Expand the multi-line macro call made by the given line, if
* there is one to be expanded. If there is, push the expansion on
* istk->expansion and return 1. Otherwise return 0.
*/
static int expand_mmacro(Token * tline)
{
Token *startline = tline;
Token *label = NULL;
bool dont_prepend = false;
Token **params, *t, *tt;
MMacro *m;
Line *l, *ll;
int i, *paramlen;
const char *mname;
int nparam = 0;
t = tline;
t = skip_white(t);
if (!tok_is(t, TOKEN_ID) && !tok_is(t, TOKEN_LOCAL_MACRO))
return 0;
m = is_mmacro(t, &nparam, ¶ms);
if (m) {
mname = tok_text(t);
} else {
Token *last;
/*
* We have an id which isn't a macro call. We'll assume
* it might be a label; we'll also check to see if a
* colon follows it. Then, if there's another id after
* that lot, we'll check it again for macro-hood.
*/
label = last = t;
t = t->next;
if (tok_white(t))
last = t, t = t->next;
if (tok_is(t, ':')) {
dont_prepend = true;
last = t, t = t->next;
if (tok_white(t))
last = t, t = t->next;
}
if (!tok_is(t, TOKEN_ID) || !(m = is_mmacro(t, &nparam, ¶ms)))
return 0;
last->next = NULL;
mname = tok_text(t);
tline = t;
}
if (unlikely(mmacro_deadman.total >= nasm_limit[LIMIT_MMACROS] ||
mmacro_deadman.levels >= nasm_limit[LIMIT_MACRO_LEVELS])) {
if (!mmacro_deadman.triggered) {
nasm_nonfatal("interminable multiline macro recursion");
mmacro_deadman.triggered = true;
}
return 0;
}
mmacro_deadman.total++;
mmacro_deadman.levels++;
/*
* Fix up the parameters: this involves stripping leading and
* trailing whitespace and stripping braces if they are present.
*/
nasm_newn(paramlen, nparam+1);
for (i = 1; (t = params[i]); i++) {
bool braced = false;
int brace = 0;
int white = 0;
bool comma = !m->plus || i < nparam;
t = skip_white(t);
if (tok_is(t, '{')) {
t = t->next;
brace = 1;
braced = true;
comma = false;
}
params[i] = t;
for (; t; t = t->next) {
if (tok_white(t)) {
white++;
continue;
}
switch(t->type) {
case ',':
if (comma && !brace)
goto endparam;
break;
case '{':
brace++;
break;
case '}':
brace--;
if (braced && !brace) {
paramlen[i] += white;
goto endparam;
}
break;
default:
break;
}
paramlen[i] += white + 1;
white = 0;
}
endparam:
;
}
/*
* OK, we have a MMacro structure together with a set of
* parameters. We must now go through the expansion and push
* copies of each Line on to istk->expansion. Substitution of
* parameter tokens and macro-local tokens doesn't get done
* until the single-line macro substitution process; this is
* because delaying them allows us to change the semantics
* later through %rotate and give the right semantics for
* nested mmacros.
*
* First, push an end marker on to istk->expansion, mark this
* macro as in progress, and set up its invocation-specific
* variables.
*/
nasm_new(ll);
ll->next = istk->expansion;
ll->finishes = m;
ll->where = istk->where;
istk->expansion = ll;
/*
* Save the previous MMacro expansion in the case of
* macro recursion
*/
#if 0
if (m->max_depth && m->in_progress)
push_mmacro(m);
#endif
m->in_progress ++;
m->params = params;
m->iline = tline;
m->iname = nasm_strdup(mname);
m->nparam = nparam;
m->rotate = 0;
m->paramlen = paramlen;
m->unique = unique++;
m->condcnt = 0;
m->mstk = istk->mstk;
istk->mstk.mstk = istk->mstk.mmac = m;
list_for_each(l, m->expansion) {
nasm_new(ll);
ll->next = istk->expansion;
istk->expansion = ll;
ll->first = dup_tlist(l->first, NULL);
ll->where = l->where;
}
/*
* If we had a label, and this macro definition does not include
* a %00, push it on as the first line of, ot
* the macro expansion.
*/
if (label) {
/*
* We had a label. If this macro contains an %00 parameter,
* save the value as a special parameter (which is what it
* is), otherwise push it as the first line of the macro
* expansion.
*/
if (m->capture_label) {
params[0] = dup_Token(NULL, label);
paramlen[0] = 1;
free_tlist(startline);
} else {
nasm_new(ll);
ll->finishes = NULL;
ll->next = istk->expansion;
istk->expansion = ll;
ll->first = startline;
ll->where = istk->where;
if (!dont_prepend) {
while (label->next)
label = label->next;
label->next = tt = make_tok_char(NULL, ':');
}
}
}
istk->nolist += !!(m->nolist & NL_LIST);
istk->noline += !!(m->nolist & NL_LINE);
if (!istk->nolist) {
if (list_option('m'))
list_mmacro_call(m);
lfmt->uplevel(LIST_MACRO, 0);
if (ppdbg & PDBG_MMACROS)
debug_macro_start(m, src_where());
}
if (!istk->noline)
src_macro_push(m, istk->where);
return 1;
}
/*
* This function decides if an error message should be suppressed.
* It will never be called with a severity level of ERR_FATAL or
* higher.
*/
bool pp_suppress_error(errflags severity)
{
/*
* If we're in a dead branch of IF or something like it, ignore the error.
* However, because %else etc are evaluated in the state context
* of the previous branch, errors might get lost:
* %if 0 ... %else trailing garbage ... %endif
* So %else etc should set the ERR_PP_PRECOND flag.
*/
if (istk && istk->conds &&
((severity & ERR_PP_PRECOND) ?
istk->conds->state == COND_NEVER :
!emitting(istk->conds->state)))
return true;
return false;
}
static Token *
stdmac_file(const SMacro *s, Token **params, int nparams)
{
const char *fname = src_get_fname();
(void)s;
(void)params;
(void)nparams;
return fname ? make_tok_qstr(NULL, fname) : NULL;
}
static Token *
stdmac_line(const SMacro *s, Token **params, int nparams)
{
(void)s;
(void)params;
(void)nparams;
return make_tok_num(NULL, src_get_linnum());
}
static Token *
stdmac_bits(const SMacro *s, Token **params, int nparams)
{
(void)s;
(void)params;
(void)nparams;
return make_tok_num(NULL, globalbits);
}
static Token *
stdmac_ptr(const SMacro *s, Token **params, int nparams)
{
(void)s;
(void)params;
(void)nparams;
switch (globalbits) {
case 16:
return new_Token(NULL, TOKEN_ID, "word", 4);
case 32:
return new_Token(NULL, TOKEN_ID, "dword", 5);
case 64:
return new_Token(NULL, TOKEN_ID, "qword", 5);
default:
panic();
}
}
/* %is...() function macros */
static Token *
stdmac_is(const SMacro *s, Token **params, int nparams)
{
int retval;
struct Token *pline = params[0];
(void)nparams;
params[0] = NULL; /* Don't free this later */
retval = if_condition(pline, s->expandpvt.u) == COND_IF_TRUE;
return make_tok_num(NULL, retval);
}
/*
* Join all expanded macro arguments with commas, e.g. %eval().
* Remember that this needs to output the tokens in reverse order.
*
* This can also be used when only single argument is already ready
* to be emitted, e.g. %str().
*/
static Token *
stdmac_join(const SMacro *s, Token **params, int nparams)
{
struct Token *tline = NULL;
int i;
(void)s;
for (i = 0; i < nparams; i++) {
Token *t, *ttmp;
if (i)
tline = make_tok_char(tline, ',');
list_for_each_safe(t, ttmp, params[i]) {
t->next = tline;
tline = t;
}
/* Avoid freeing the tokens we "stole" */
params[i] = NULL;
}
return tline;
}
/* %strcat() function */
static Token *
stdmac_strcat(const SMacro *s, Token **params, int nparams)
{
int i;
size_t len = 0;
char *str, *p;
(void)s;
for (i = 0; i < nparams; i++) {
unquote_token(params[i]);
len += params[i]->len;
}
nasm_newn(str, len+1);
p = str;
for (i = 0; i < nparams; i++) {
p = mempcpy(p, tok_text(params[i]), params[i]->len);
}
return make_tok_qstr_len(NULL, str, len);
}
/* %substr() function */
static Token *
stdmac_substr(const SMacro *s, Token **params, int nparams)
{
int64_t start, count;
(void)nparams;
(void)s;
start = get_tok_num(params[1], NULL);
count = get_tok_num(params[2], NULL);
return pp_substr_common(params[0], start, count);
}
/* %strlen() function */
static Token *
stdmac_strlen(const SMacro *s, Token **params, int nparams)
{
(void)nparams;
(void)s;
unquote_token(params[0]);
return make_tok_num(NULL, params[0]->len);
}
/* %tok() function */
static Token *
stdmac_tok(const SMacro *s, Token **params, int nparams)
{
(void)nparams;
(void)s;
return reverse_tokens(tokenize(unquote_token_cstr(params[0])));
}
/* %cond() or %sel() */
static Token *
stdmac_cond_sel(const SMacro *s, Token **params, int nparams)
{
int64_t which;
/*
* params[0] will have been generated by make_tok_num.
*/
which = get_tok_num(params[0], NULL);
if (s->expandpvt.u) {
/* Booleanize (for %cond): true -> 1, false -> 2 (else) */
which = which ? 1 : 2;
if (which >= nparams) {
/* false, and no else clause */
return NULL;
}
} else {
/*!
*!pp-sel-range [on] \c{%sel()} argument out of range
*! warns that the \c{%sel()} preprocessor function was passed
*! a value less than 1 or larger than the number of available
*! arguments.
*/
if (unlikely(which < 1)) {
nasm_warn(WARN_PP_SEL_RANGE,
"%s(%"PRId64") is not a valid selector", s->name, which);
return NULL;
} else if (unlikely(which >= nparams)) {
nasm_warn(WARN_PP_SEL_RANGE,
"%s(%"PRId64") exceeds the number of arguments",
s->name, which);
return NULL;
}
}
return new_Token(NULL, tok_smac_param(which), "", 0);
}
/* %count() function */
static Token *
stdmac_count(const SMacro *s, Token **params, int nparams)
{
(void)s;
(void)params;
return make_tok_num(NULL, nparams);
}
/* %num() function */
static Token *
stdmac_num(const SMacro *s, Token **params, int nparam)
{
int64_t parm[3];
uint64_t n;
int64_t dparm, bparm;
const int maxlen = 256;
char numbuf[256+5];
char *p;
char decorate;
int i;
(void)nparam;
for (i = 0; i < (int)ARRAY_SIZE(parm); i++)
parm[i] = get_tok_num(params[i], NULL);
n = parm[0];
dparm = parm[1];
bparm = parm[2];
decorate = 0;
if (bparm < 0) {
bparm = -bparm;
switch (bparm) {
case 2:
decorate = 'b';
break;
case 8:
decorate = 'q';
break;
case 10:
decorate = 'd';
break;
case 16:
decorate = 'x';
break;
default:
bparm = -bparm; /* Error out below */
break;
}
}
if (bparm < 2 || bparm > NUMSTR_MAXBASE) {
nasm_nonfatal("invalid base %"PRId64" in %s()\n", bparm, s->name);
return NULL;
}
if (dparm < -maxlen || dparm > maxlen) {
nasm_nonfatal("digit count %"PRId64" specified to %s() too large",
dparm, s->name);
dparm = -1;
}
/* Are we supposed to generate an empty string for zero? */
if (!dparm && !n)
decorate = 0;
p = numbuf;
*p++ = '\'';
if (decorate) {
*p++ = '0';
*p++ = decorate;
}
p += numstr(p, maxlen, n, dparm, bparm, false);
*p++ = '\'';
*p = '\0';
return new_Token(NULL, TOKEN_STR, numbuf, p - numbuf);
}
/* %abs() function */
static Token *
stdmac_abs(const SMacro *s, Token **params, int nparam)
{
char numbuf[24];
int len;
int64_t v;
uint64_t u;
(void)s;
(void)nparam;
v = get_tok_num(params[0], NULL);
u = v < 0 ? -v : v;
/*
* Don't use make_tok_num() here, to make sure we don't emit
* a minus sign for the case of v = -2^63
*/
len = snprintf(numbuf, sizeof numbuf, "%"PRIu64, u);
return new_Token(NULL, TOKEN_NUM, numbuf, len);
}
/* %map() function */
static Token *
stdmac_map(const SMacro *s, Token **params, int nparam)
{
const char *mname, *ctxname;
SMacro *smac;
Context *ctx;
Token *t, *tline, *mstart;
int i;
Token *fixargs;
int fixparams; /* Number of fixed parameters */
int mparams; /* Number of variable parameters */
int tparams; /* Total number of parameters */
int greedify; /* Number of parameters that must be joined */
Token **fparam; /* Fixed parameters */
Token **cparam; /* Final list of macro call parameters */
t = params[0];
mname = get_id_noskip(&t, "%map");
if (!mname)
return NULL;
mstart = t;
fixargs = NULL;
fixparams = 0;
mparams = 1;
t = skip_white(t->next);
if (tok_is(t, ':')) {
fixargs = t->next;
fixparams = count_smacro_args(fixargs, &t);
t = skip_white(t->next);
if (tok_is(t, ':')) {
struct ppscan pps;
struct tokenval tokval;
expr *evalresult;
Token *ep;
pps.tptr = ep = zap_white(expand_smacro_noreset(t->next));
t->next = NULL;
pps.ntokens = -1;
tokval.t_type = TOKEN_INVALID;
evalresult = evaluate(ppscan, &pps, &tokval, NULL, true, NULL);
free_tlist(ep);
if (!evalresult || tokval.t_type) {
nasm_nonfatal("invalid expression in parameter count for `%s' in function %s",
mname, s->name);
return NULL;
} else if (!is_simple(evalresult)) {
nasm_nonfatal("non-constant expression in parameter count for `%s' in function %s",
mname, s->name);
return NULL;
}
mparams = reloc_value(evalresult);
if (mparams < 1) {
nasm_nonfatal("invalid parameter count for `%s' in function %s",
mname, s->name);
return NULL;
}
}
}
nparam--;
params++;
if (nparam % mparams) {
nasm_nonfatal("%s expected a multiple of %d expansion parameters, got %d\n",
s->name, mparams, nparam);
}
tparams = fixparams + mparams;
ctx = get_ctx(mname, &ctxname);
if (!smacro_defined(ctx, ctxname, tparams, &smac, true, false)
|| smac->nparam == 0 || (smac->in_progress && !smac->recursive)) {
nasm_nonfatal("macro `%s' taking %d parameter%s not found in function %s",
mname, tparams, tparams == 1 ? "" : "s", s->name);
return NULL;
}
if (nparam < mparams)
return NULL; /* Empty expansion */
fparam = NULL;
if (fixparams) {
int nfp = fixparams;
fparam = parse_smacro_args(&fixargs, &nfp, smac);
if (nfp < fixparams) {
fixparams = nfp;
tparams = fixparams + mparams;
}
}
greedify = 0;
if (unlikely(tparams > smac->nparam)) {
if (smac->params[smac->nparam-1].flags & SPARM_GREEDY)
greedify = smac->nparam;
}
nasm_newn(cparam, tparams);
tline = NULL;
while (1) {
int xparams;
for (i = 0; i < fixparams; i++) {
/* expand_smacro_with_params() is allowed to clobber the
* parameter array, so we need to give it its own copy.
*/
cparam[i] = dup_tlist(fparam[i], NULL);
}
for (i = fixparams; i < tparams; i++) {
cparam[i] = *params;
*params = NULL; /* Taking over ownership */
params++;
}
if (unlikely(greedify)) {
/* Need to re-concatenate some number of arguments as
comma-separated lists... */
int i;
Token **tp = &cparam[greedify-1];
while (*tp)
tp = &(*tp)->next;
for (i = greedify; i < tparams; i++) {
*tp = make_tok_char(NULL, ',');
tp = steal_tlist(cparam[i], &(*tp)->next);
cparam[i] = NULL;
}
xparams = greedify;
} else {
xparams = tparams;
}
t = expand_smacro_with_params(smac, mstart, cparam, xparams, NULL);
if (t) {
Token *rt = reverse_tokens(t);
t->next = tline;
tline = rt;
}
for (i = 0; i < xparams; i++)
free_tlist(cparam[i]);
nparam -= mparams;
if (nparam < mparams)
break;
tline = make_tok_char(tline, ',');
}
nasm_free(fparam);
nasm_free(cparam);
return tline;
}
/* Add magic standard macros */
struct magic_macros {
const char *name;
bool casesense;
int nparam;
enum sparmflags flags;
ExpandSMacro func;
};
static void pp_add_magic_stdmac(void)
{
static const struct magic_macros magic_macros[] = {
{ "__?FILE?__", true, 0, 0, stdmac_file },
{ "__?LINE?__", true, 0, 0, stdmac_line },
{ "__?BITS?__", true, 0, 0, stdmac_bits },
{ "__?PTR?__", true, 0, 0, stdmac_ptr },
{ "%abs", false, 1, SPARM_EVAL, stdmac_abs },
{ "%count", false, 1, SPARM_VARADIC, stdmac_count },
{ "%eval", false, 1, SPARM_EVAL|SPARM_VARADIC, stdmac_join },
{ "%map", false, 1, SPARM_VARADIC, stdmac_map },
{ "%str", false, 1, SPARM_GREEDY|SPARM_STR, stdmac_join },
{ "%strcat", false, 1, SPARM_STR|SPARM_CONDQUOTE|SPARM_VARADIC, stdmac_strcat },
{ "%strlen", false, 1, SPARM_STR|SPARM_CONDQUOTE, stdmac_strlen },
{ "%tok", false, 1, SPARM_STR|SPARM_CONDQUOTE, stdmac_tok },
{ NULL, false, 0, 0, NULL }
};
const struct magic_macros *m;
SMacro tmpl;
enum preproc_token pt;
char name_buf[PP_TOKLEN_MAX+1];
/*
* Simple standard magic macros and functions.
* Note that preprocessor functions are allowed to recurse.
*/
nasm_zero(tmpl);
for (m = magic_macros; m->name; m++) {
tmpl.nparam = m->nparam;
tmpl.expand = m->func;
tmpl.recursive = m->nparam && m->name[0] == '%';
if (m->nparam) {
int i;
enum sparmflags flags = m->flags;
nasm_newn(tmpl.params, m->nparam);
for (i = m->nparam-1; i >= 0; i--) {
tmpl.params[i].flags = flags;
/* These flags for the last arg only */
flags &= ~(SPARM_GREEDY|SPARM_VARADIC|SPARM_OPTIONAL);
}
}
define_smacro(m->name, m->casesense, NULL, &tmpl);
if (m->name[0] == '%') {
enum preproc_token op = pp_token_hash(m->name);
if (op != PP_invalid)
pp_op_may_be_function[op] = true;
}
}
/* %hex() function */
nasm_zero(tmpl);
tmpl.nparam = 1;
tmpl.recursive = true;
tmpl.expand = stdmac_join;
nasm_newn(tmpl.params, tmpl.nparam);
tmpl.params[0].flags = SPARM_EVAL|SPARM_UNSIGNED|SPARM_VARADIC;
tmpl.params[0].radix = 'x';
define_smacro("%hex", false, NULL, &tmpl);
/* %sel() function */
nasm_zero(tmpl);
tmpl.nparam = 2;
tmpl.recursive = true;
tmpl.expand = stdmac_cond_sel;
nasm_newn(tmpl.params, tmpl.nparam);
tmpl.params[0].flags = SPARM_EVAL;
tmpl.params[1].flags = SPARM_VARADIC;
define_smacro("%sel", false, NULL, &tmpl);
/* %cond() function, a variation on %sel */
tmpl.nparam = 3;
tmpl.expandpvt.u = 1; /* Booleanize */
nasm_newn(tmpl.params, tmpl.nparam);
tmpl.params[0].flags = SPARM_EVAL;
tmpl.params[1].flags = 0;
tmpl.params[2].flags = SPARM_OPTIONAL;
define_smacro("%cond", false, NULL, &tmpl);
/* %num() function */
nasm_zero(tmpl);
tmpl.nparam = 3;
tmpl.expand = stdmac_num;
tmpl.recursive = true;
nasm_newn(tmpl.params, tmpl.nparam);
tmpl.params[0].flags = SPARM_EVAL;
tmpl.params[1].flags = SPARM_EVAL|SPARM_OPTIONAL;
tmpl.params[1].def = make_tok_num(NULL, -1);
tmpl.params[2].flags = SPARM_EVAL|SPARM_OPTIONAL;
tmpl.params[2].def = make_tok_num(NULL, 10);
define_smacro("%num", false, NULL, &tmpl);
/* %substr() function */
nasm_zero(tmpl);
tmpl.nparam = 3;
tmpl.expand = stdmac_substr;
tmpl.recursive = true;
nasm_newn(tmpl.params, tmpl.nparam);
tmpl.params[0].flags = SPARM_STR|SPARM_CONDQUOTE;
tmpl.params[1].flags = SPARM_EVAL;
tmpl.params[2].flags = SPARM_EVAL|SPARM_OPTIONAL;
tmpl.params[2].def = make_tok_num(NULL, -1);
define_smacro("%substr", false, NULL, &tmpl);
/* %is...() macro functions */
nasm_zero(tmpl);
tmpl.nparam = 1;
tmpl.expand = stdmac_is;
tmpl.recursive = true;
name_buf[0] = '%';
name_buf[1] = 'i';
name_buf[2] = 's';
for (pt = PP_IF; pt < (PP_IFN+(PP_IFN-PP_IF)); pt++) {
if (!pp_directives[pt])
continue;
nasm_new(tmpl.params);
tmpl.params[0].flags = SPARM_GREEDY;
strcpy(name_buf+3, pp_directives[pt]+3);
tmpl.expandpvt.u = pt;
define_smacro(name_buf, false, NULL, &tmpl);
}
}
static void pp_reset_stdmac(enum preproc_mode mode)
{
int apass;
struct Include *inc;
/*
* Set up the stdmac packages as a virtual include file,
* indicated by a null file pointer.
*/
nasm_new(inc);
inc->next = istk;
inc->nolist = inc->noline = !list_option('b');
inc->where = istk->where;
istk = inc;
if (!istk->nolist) {
lfmt->uplevel(LIST_INCLUDE, 0);
}
if (!istk->noline) {
src_set(0, NULL);
istk->where = src_where();
if (ppdbg & PDBG_INCLUDE)
dfmt->debug_include(true, istk->next->where, istk->where);
}
pp_add_magic_stdmac();
if (tasm_compatible_mode)
pp_add_stdmac(nasm_stdmac_tasm);
pp_add_stdmac(nasm_stdmac_nasm);
pp_add_stdmac(nasm_stdmac_version);
if (extrastdmac)
pp_add_stdmac(extrastdmac);
stdmacpos = stdmacros[0];
stdmacnext = &stdmacros[1];
do_predef = true;
/*
* Define the __?PASS?__ macro. This is defined here unlike all the
* other builtins, because it is special -- it varies between
* passes -- but there is really no particular reason to make it
* magic.
*
* 0 = dependencies only
* 1 = preparatory passes
* 2 = final pass
* 3 = preprocess only
*/
switch (mode) {
case PP_NORMAL:
apass = pass_final() ? 2 : 1;
break;
case PP_DEPS:
apass = 0;
break;
case PP_PREPROC:
apass = 3;
break;
default:
panic();
}
define_smacro("__?PASS?__", true, make_tok_num(NULL, apass), NULL);
}
void pp_reset(const char *file, enum preproc_mode mode,
struct strlist *dep_list)
{
cstk = NULL;
defining = NULL;
nested_mac_count = 0;
nested_rep_count = 0;
init_macros();
unique = 0;
deplist = dep_list;
pp_mode = mode;
/* Reset options to default */
nasm_zero(ppconf);
/* Disable all debugging info, except in the last pass */
ppdbg = 0;
if (!(ppopt & PP_TRIVIAL)) {
if (pass_final()) {
if (dfmt->debug_mmacros)
ppdbg |= PDBG_MMACROS;
if (dfmt->debug_smacros)
ppdbg |= PDBG_SMACROS;
if (dfmt->debug_include)
ppdbg |= PDBG_INCLUDE;
}
if (list_option('s'))
ppdbg |= PDBG_LIST_SMACROS;
}
memset(use_loaded, 0, use_package_count * sizeof(bool));
/* First set up the top level input file */
nasm_new(istk);
istk->fp = nasm_open_read(file, NF_TEXT);
if (!istk->fp) {
nasm_fatalf(ERR_NOFILE, "unable to open input file `%s'%s%s",
file, errno ? " " : "", errno ? strerror(errno) : "");
}
src_set(0, file);
istk->where = src_where();
istk->lineinc = 1;
if (ppdbg & PDBG_INCLUDE) {
/* Let the debug format know the main file */
dfmt->debug_include(true, src_nowhere(), istk->where);
}
strlist_add(deplist, file);
do_predef = false;
if (!(ppopt & PP_TRIVIAL))
pp_reset_stdmac(mode);
}
void pp_init(enum preproc_opt opt)
{
ppopt = opt;
nasm_newn(use_loaded, use_package_count);
}
/*
* Get a line of tokens. If we popped the macro expansion/include stack,
* we return a pointer to the dummy token tok_pop; at that point if
* istk is NULL then we have reached end of input;
*/
static Token tok_pop; /* Dummy token placeholder */
static Token *pp_tokline(void)
{
while (true) {
Line *l = istk->expansion;
Token *tline = NULL;
Token *dtline;
/*
* Fetch a tokenized line, either from the macro-expansion
* buffer or from the input file.
*/
tline = NULL;
while (l && l->finishes) {
MMacro *fm = l->finishes;
nasm_assert(fm == istk->mstk.mstk);
if (!fm->name && fm->in_progress > 1) {
/*
* This is a macro-end marker for a macro with no
* name, which means it's not really a macro at all
* but a %rep block, and the `in_progress' field is
* more than 1, meaning that we still need to
* repeat. (1 means the natural last repetition; 0
* means termination by %exitrep.) We have
* therefore expanded up to the %endrep, and must
* push the whole block on to the expansion buffer
* again. We don't bother to remove the macro-end
* marker: we'd only have to generate another one
* if we did.
*/
fm->in_progress--;
list_for_each(l, fm->expansion) {
Line *ll;
nasm_new(ll);
ll->next = istk->expansion;
ll->first = dup_tlist(l->first, NULL);
ll->where = l->where;
istk->expansion = ll;
}
l = istk->expansion;
continue;
} else {
MMacro *m = istk->mstk.mstk;
/*
* Check whether a `%rep' was started and not ended
* within this macro expansion. This can happen and
* should be detected. It's a fatal error because
* I'm too confused to work out how to recover
* sensibly from it.
*/
if (defining) {
if (defining->name)
nasm_panic("defining with name in expansion");
else if (m->name)
nasm_fatal("`%%rep' without `%%endrep' within"
" expansion of macro `%s'", m->name);
}
/*
* FIXME: investigate the relationship at this point between
* istk->mstk.mstk and fm
*/
istk->mstk = m->mstk;
if (m->name) {
/*
* This was a real macro call, not a %rep, and
* therefore the parameter information needs to
* be freed and the iteration count/nesting
* depth adjusted.
*/
if (!--mmacro_deadman.levels) {
/*
* If all mmacro processing done,
* clear all counters and the deadman
* message trigger.
*/
nasm_zero(mmacro_deadman); /* Clear all counters */
}
#if 0
if (m->prev) {
pop_mmacro(m);
fm->in_progress --;
} else
#endif
{
nasm_free(m->params);
nasm_free(m->iname);
free_tlist(m->iline);
nasm_free(m->paramlen);
fm->in_progress = 0;
m->params = NULL;
m->iname = NULL;
m->iline = NULL;
m->paramlen = NULL;
}
}
if (fm->nolist & NL_LINE) {
istk->noline--;
} else if (!istk->noline) {
if (fm == src_macro_current())
src_macro_pop();
src_update(l->where);
}
if (fm->nolist & NL_LIST) {
istk->nolist--;
} else if (!istk->nolist) {
lfmt->downlevel(LIST_MACRO);
if ((ppdbg & PDBG_MMACROS) && fm->name)
debug_macro_end(fm);
}
istk->where = l->where;
if (!m->name)
free_mmacro(m);
}
istk->expansion = l->next;
nasm_free(l);
return &tok_pop;
}
do { /* until we get a line we can use */
char *line;
if (istk->expansion) { /* from a macro expansion */
Line *l = istk->expansion;
istk->expansion = l->next;
istk->where = l->where;
tline = l->first;
nasm_free(l);
if (!istk->noline)
src_update(istk->where);
if (!istk->nolist) {
line = detoken(tline, false);
lfmt->line(LIST_MACRO, istk->where.lineno, line);
nasm_free(line);
}
} else if ((line = read_line())) {
tline = tokenize(line);
nasm_free(line);
} else {
/*
* The current file has ended; work down the istk
*/
Include *i = istk;
if (i->fp)
fclose(i->fp);
if (i->conds) {
/* nasm_fatal can't be conditionally suppressed */
nasm_fatal("expected `%%endif' before end of file");
}
istk = i->next;
if (!i->nolist)
lfmt->downlevel(LIST_INCLUDE);
if (!i->noline) {
struct src_location whereto
= istk ? istk->where : src_nowhere();
if (ppdbg & PDBG_INCLUDE)
dfmt->debug_include(false, whereto, i->where);
if (istk)
src_update(istk->where);
}
nasm_free(i);
return &tok_pop;
}
} while (0);
/*
* We must expand MMacro parameters and MMacro-local labels
* _before_ we plunge into directive processing, to cope
* with things like `%define something %1' such as STRUC
* uses. Unless we're _defining_ a MMacro, in which case
* those tokens should be left alone to go into the
* definition; and unless we're in a non-emitting
* condition, in which case we don't want to meddle with
* anything.
*/
if (!defining &&
!(istk->conds && !emitting(istk->conds->state)) &&
!(istk->mstk.mmac && !istk->mstk.mmac->in_progress)) {
tline = expand_mmac_params(tline);
}
/*
* Check the line to see if it's a preprocessor directive.
*/
if (do_directive(tline, &dtline) == DIRECTIVE_FOUND) {
if (dtline)
return dtline;
} else if (defining) {
/*
* We're defining a multi-line macro. We emit nothing
* at all, and just
* shove the tokenized line on to the macro definition.
*/
MMacro *mmac = defining->dstk.mmac;
Line *l;
nasm_new(l);
l->next = defining->expansion;
l->first = tline;
l->finishes = NULL;
l->where = istk->where;
defining->expansion = l;
/*
* Remember if this mmacro expansion contains %00:
* if it does, we will have to handle leading labels
* specially.
*/
if (mmac) {
const Token *t;
list_for_each(t, tline) {
if (t->type == TOKEN_MMACRO_PARAM &&
!memcmp(t->text.a, "%00", 4))
mmac->capture_label = true;
}
}
} else if (istk->conds && !emitting(istk->conds->state)) {
/*
* We're in a non-emitting branch of a condition block.
* Emit nothing at all, not even a blank line: when we
* emerge from the condition we'll give a line-number
* directive so we keep our place correctly.
*/
free_tlist(tline);
} else if (istk->mstk.mstk && !istk->mstk.mstk->in_progress) {
/*
* We're in a %rep block which has been terminated, so
* we're walking through to the %endrep without
* emitting anything. Emit nothing at all, not even a
* blank line: when we emerge from the %rep block we'll
* give a line-number directive so we keep our place
* correctly.
*/
free_tlist(tline);
} else {
tline = expand_smacro(tline);
if (!expand_mmacro(tline))
return tline;
}
}
}
char *pp_getline(void)
{
char *line = NULL;
Token *tline;
while (true) {
tline = pp_tokline();
if (tline == &tok_pop) {
/*
* We popped the macro/include stack. If istk is empty,
* we are at end of input, otherwise just loop back.
*/
if (!istk)
break;
} else {
/*
* De-tokenize the line and emit it.
*/
line = detoken(tline, true);
free_tlist(tline);
break;
}
}
if (list_option('e') && istk && !istk->nolist && line && line[0]) {
char *buf = nasm_strcat(" ;;; ", line);
lfmt->line(LIST_MACRO, -1, buf);
nasm_free(buf);
}
return line;
}
void pp_cleanup_pass(void)
{
if (defining) {
if (defining->name) {
nasm_nonfatal("end of file while still defining macro `%s'",
defining->name);
} else {
nasm_nonfatal("end of file while still in %%rep");
}
free_mmacro(defining);
defining = NULL;
}
while (cstk)
ctx_pop();
free_macros();
while (istk) {
Include *i = istk;
istk = istk->next;
fclose(i->fp);
if (!istk && (ppdbg & PDBG_INCLUDE)) {
/* Signal closing the top-level input file */
dfmt->debug_include(false, src_nowhere(), i->where);
}
nasm_free(i);
}
while (cstk)
ctx_pop();
src_set_fname(NULL);
if (ppdbg & PDBG_MMACROS)
debug_macro_output();
}
void pp_cleanup_session(void)
{
nasm_free(use_loaded);
free_llist(predef);
predef = NULL;
delete_Blocks();
ipath_list = NULL;
}
void pp_include_path(struct strlist *list)
{
ipath_list = list;
}
void pp_pre_include(char *fname)
{
Token *inc, *space, *name;
Line *l;
name = new_Token(NULL, TOKEN_INTERNAL_STR, fname, 0);
space = new_White(name);
inc = new_Token(space, TOKEN_PREPROC_ID, "%include", 0);
l = nasm_malloc(sizeof(Line));
l->next = predef;
l->first = inc;
l->finishes = NULL;
predef = l;
}
void pp_pre_define(char *definition)
{
Token *def, *space;
Line *l;
char *equals;
equals = strchr(definition, '=');
space = new_White(NULL);
def = new_Token(space, TOKEN_PREPROC_ID, "%define", 0);
if (equals)
*equals = ' ';
space->next = tokenize(definition);
if (equals)
*equals = '=';
nasm_new(l);
l->next = predef;
l->first = def;
l->finishes = NULL;
predef = l;
}
void pp_pre_undefine(char *definition)
{
Token *def, *space;
Line *l;
space = new_White(NULL);
def = new_Token(space, TOKEN_PREPROC_ID, "%undef", 0);
space->next = tokenize(definition);
nasm_new(l);
l->next = predef;
l->first = def;
l->finishes = NULL;
predef = l;
}
/* Insert an early preprocessor command that doesn't need special handling */
void pp_pre_command(const char *what, char *string)
{
Token *def, *space;
Line *l;
def = tokenize(string);
if (what) {
space = new_White(def);
def = new_Token(space, TOKEN_PREPROC_ID, what, 0);
}
nasm_new(l);
l->next = predef;
l->first = def;
l->finishes = NULL;
predef = l;
}
static void pp_add_stdmac(macros_t *macros)
{
macros_t **mp;
/* Find the end of the list and avoid duplicates */
for (mp = stdmacros; *mp; mp++) {
if (*mp == macros)
return; /* Nothing to do */
}
nasm_assert(mp < &stdmacros[ARRAY_SIZE(stdmacros)-1]);
*mp = macros;
}
void pp_extra_stdmac(macros_t *macros)
{
extrastdmac = macros;
}
/* Create a numeric token, with possible - token in front */
static Token *make_tok_num(Token *next, int64_t val)
{
char numbuf[32];
int len;
uint64_t uval;
bool minus = val < 0;
uval = minus ? -val : val;
len = snprintf(numbuf, sizeof numbuf, "%"PRIu64, uval);
next = new_Token(next, TOKEN_NUM, numbuf, len);
if (minus)
next = make_tok_char(next, '-');
return next;
}
/*
* Create a numeric token with specified radix and signedness;
* prefix the number with 0<radix> if a radix letter is specified,
* otherwise generate a decimal constant without prefix.
*/
static Token *
make_tok_num_radix(Token *next, int64_t val, char radix, bool uns)
{
char numbuf[2+64+1]; /* Maximum possible: 0b + binary + null */
char *p;
uint64_t uval;
bool minus = val < 0 && !uns;
unsigned int base;
bool upper;
uval = minus ? -val : val;
p = numbuf;
base = 10;
upper = false;
if (radix) {
*p++ = '0';
*p++ = radix;
base = radix_letter(radix);
upper = !(radix & 0x20);
}
p += numstr(p, 64, uval, -1, base, upper);
next = new_Token(next, TOKEN_NUM, numbuf, p - numbuf);
if (minus)
next = make_tok_char(next, '-');
return next;
}
/*
* Do the inverse of make_tok_num(). This only needs to be able
* to parse the output of make_tok_num() or make_tok_hex().
*/
static int64_t get_tok_num(const Token *t, bool *err)
{
bool minus = false;
int64_t v;
if (tok_is(t, '-')) {
minus = true;
t = t->next;
}
if (!tok_is(t, TOKEN_NUM)) {
if (err)
*err = true;
return 0;
}
v = readnum(tok_text(t), err);
return minus ? -v : v;
}
/* Create a quoted string token */
static Token *make_tok_qstr_len(Token *next, const char *str, size_t len)
{
char *p = nasm_quote(str, &len);
return new_Token_free(next, TOKEN_STR, p, len);
}
static Token *make_tok_qstr(Token *next, const char *str)
{
return make_tok_qstr_len(next, str, strlen(str));
}
/* Create a single-character operator token */
static Token *make_tok_char(Token *next, char op)
{
Token *t = new_Token(next, op, NULL, 1);
t->text.a[0] = op;
return t;
}
/*
* Descent the macro hierarchy and display the expansion after
* encountering an error message.
*/
void pp_error_list_macros(errflags severity)
{
const MMacro *m;
severity |= ERR_PP_LISTMACRO | ERR_NO_SEVERITY | ERR_HERE;
while ((m = src_error_down())) {
if ((m->nolist & NL_LIST) || !m->where.filename)
break;
nasm_error(severity, "... from macro `%s' defined", m->name);
}
src_error_reset();
}
|