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
|
/*
AngelCode Scripting Library
Copyright (c) 2003-2021 Andreas Jonsson
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you
must not claim that you wrote the original software. If you use
this software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
The original version of this library can be located at:
http://www.angelcode.com/angelscript/
Andreas Jonsson
andreas@angelcode.com
*/
//
// as_context.cpp
//
// This class handles the execution of the byte code
//
#include <math.h> // fmodf() pow()
#include "as_config.h"
#include "as_context.h"
#include "as_scriptengine.h"
#include "as_tokendef.h"
#include "as_texts.h"
#include "as_callfunc.h"
#include "as_generic.h"
#include "as_debug.h" // mkdir()
#include "as_bytecode.h"
#include "as_scriptobject.h"
#ifdef _MSC_VER
#pragma warning(disable:4702) // unreachable code
#endif
BEGIN_AS_NAMESPACE
// We need at least 2 PTRs reserved for exception handling
// We need at least 1 PTR reserved for calling system functions
const int RESERVE_STACK = 2 * AS_PTR_SIZE;
// For each script function call we push 9 PTRs on the call stack
const int CALLSTACK_FRAME_SIZE = 9;
#if defined(AS_DEBUG)
class asCDebugStats {
public:
asCDebugStats() {
memset(instrCount, 0, sizeof(instrCount));
memset(instrCount2, 0, sizeof(instrCount2));
lastBC = 255;
}
~asCDebugStats() {
// This code writes out some statistics for the VM.
// It's useful for determining what needs to be optimized.
#ifndef __MINGW32__
// _mkdir is broken on mingw
_mkdir("AS_DEBUG");
#endif
#if _MSC_VER >= 1500 && !defined(AS_MARMALADE)
FILE *f;
fopen_s(&f, "AS_DEBUG/stats.txt", "wt");
#else
FILE *f = fopen("AS_DEBUG/stats.txt", "wt");
#endif
if (f) {
// Output instruction statistics
fprintf(f, "\nTotal count\n");
int n;
for (n = 0; n < asBC_MAXBYTECODE; n++) {
if (asBCInfo[n].name && instrCount[n] > 0)
fprintf(f, "%-10.10s : %.0f\n", asBCInfo[n].name, instrCount[n]);
}
fprintf(f, "\nNever executed\n");
for (n = 0; n < asBC_MAXBYTECODE; n++) {
if (asBCInfo[n].name && instrCount[n] == 0)
fprintf(f, "%-10.10s\n", asBCInfo[n].name);
}
fprintf(f, "\nSequences\n");
for (n = 0; n < 256; n++) {
if (asBCInfo[n].name) {
for (int m = 0; m < 256; m++) {
if (instrCount2[n][m])
fprintf(f, "%-10.10s, %-10.10s : %.0f\n", asBCInfo[n].name, asBCInfo[m].name, instrCount2[n][m]);
}
}
}
fclose(f);
}
}
void Instr(asBYTE bc) {
++instrCount[bc];
++instrCount2[lastBC][bc];
lastBC = bc;
}
// Instruction statistics
double instrCount[256];
double instrCount2[256][256];
int lastBC;
} stats;
#endif
// interface
AS_API asIScriptContext *asGetActiveContext() {
asCThreadLocalData *tld = asCThreadManager::GetLocalData();
// tld can be 0 if asGetActiveContext is called before any engine has been created.
// Observe! I've seen a case where an application linked with the library twice
// and thus ended up with two separate instances of the code and global variables.
// The application somehow mixed the two instances so that a function called from
// a script ended up calling asGetActiveContext from the other instance that had
// never been initialized.
if (tld == 0 || tld->activeContexts.GetLength() == 0)
return 0;
return tld->activeContexts[tld->activeContexts.GetLength() - 1];
}
// internal
asCThreadLocalData *asPushActiveContext(asIScriptContext *ctx) {
asCThreadLocalData *tld = asCThreadManager::GetLocalData();
asASSERT(tld);
if (tld == 0)
return 0;
tld->activeContexts.PushLast(ctx);
return tld;
}
// internal
void asPopActiveContext(asCThreadLocalData *tld, asIScriptContext *ctx) {
UNUSED_VAR(ctx);
asASSERT(tld && tld->activeContexts[tld->activeContexts.GetLength() - 1] == ctx);
if (tld)
tld->activeContexts.PopLast();
}
asCContext::asCContext(asCScriptEngine *engine, bool holdRef) {
m_refCount.set(1);
m_holdEngineRef = holdRef;
if (holdRef)
engine->AddRef();
m_engine = engine;
m_status = asEXECUTION_UNINITIALIZED;
m_stackBlockSize = 0;
m_originalStackPointer = 0;
m_inExceptionHandler = false;
m_isStackMemoryNotAllocated = false;
m_needToCleanupArgs = false;
m_currentFunction = 0;
m_callingSystemFunction = 0;
m_regs.objectRegister = 0;
m_initialFunction = 0;
m_lineCallback = false;
m_exceptionCallback = false;
m_regs.doProcessSuspend = false;
m_doSuspend = false;
m_userData = 0;
m_regs.ctx = this;
m_exceptionWillBeCaught = false;
}
asCContext::~asCContext() {
DetachEngine();
}
// interface
bool asCContext::IsNested(asUINT *nestCount) const {
if (nestCount)
*nestCount = 0;
asUINT c = GetCallstackSize();
if (c == 0)
return false;
// Search for a marker on the call stack
// This loop starts at 2 because the 0th entry is not stored in m_callStack,
// and then we need to subtract one more to get the base of each frame
for (asUINT n = 2; n <= c; n++) {
const asPWORD *s = m_callStack.AddressOf() + (c - n) * CALLSTACK_FRAME_SIZE;
if (s && s[0] == 0) {
if (nestCount)
(*nestCount)++;
else
return true;
}
}
if (nestCount && *nestCount > 0)
return true;
return false;
}
// interface
int asCContext::AddRef() const {
return m_refCount.atomicInc();
}
// interface
int asCContext::Release() const {
int r = m_refCount.atomicDec();
if (r == 0) {
asDELETE(const_cast<asCContext *>(this), asCContext);
return 0;
}
return r;
}
// internal
void asCContext::DetachEngine() {
if (m_engine == 0) return;
// Clean up all calls, included nested ones
do {
// Abort any execution
Abort();
// Free all resources
Unprepare();
} while (IsNested());
// Free the stack blocks
for (asUINT n = 0; n < m_stackBlocks.GetLength(); n++) {
if (m_stackBlocks[n]) {
#ifndef WIP_16BYTE_ALIGN
asDELETEARRAY(m_stackBlocks[n]);
#else
asDELETEARRAYALIGNED(m_stackBlocks[n]);
#endif
}
}
m_stackBlocks.SetLength(0);
m_stackBlockSize = 0;
// Clean the user data
for (asUINT n = 0; n < m_userData.GetLength(); n += 2) {
if (m_userData[n + 1]) {
for (asUINT c = 0; c < m_engine->cleanContextFuncs.GetLength(); c++)
if (m_engine->cleanContextFuncs[c].type == m_userData[n])
m_engine->cleanContextFuncs[c].cleanFunc(this);
}
}
m_userData.SetLength(0);
// Clear engine pointer
if (m_holdEngineRef)
m_engine->Release();
m_engine = 0;
}
// interface
asIScriptEngine *asCContext::GetEngine() const {
return m_engine;
}
// interface
void *asCContext::SetUserData(void *data, asPWORD type) {
// As a thread might add a new new user data at the same time as another
// it is necessary to protect both read and write access to the userData member
ACQUIREEXCLUSIVE(m_engine->engineRWLock);
// It is not intended to store a lot of different types of userdata,
// so a more complex structure like a associative map would just have
// more overhead than a simple array.
for (asUINT n = 0; n < m_userData.GetLength(); n += 2) {
if (m_userData[n] == type) {
void *oldData = reinterpret_cast<void *>(m_userData[n + 1]);
m_userData[n + 1] = reinterpret_cast<asPWORD>(data);
RELEASEEXCLUSIVE(m_engine->engineRWLock);
return oldData;
}
}
m_userData.PushLast(type);
m_userData.PushLast(reinterpret_cast<asPWORD>(data));
RELEASEEXCLUSIVE(m_engine->engineRWLock);
return 0;
}
// interface
void *asCContext::GetUserData(asPWORD type) const {
// There may be multiple threads reading, but when
// setting the user data nobody must be reading.
ACQUIRESHARED(m_engine->engineRWLock);
for (asUINT n = 0; n < m_userData.GetLength(); n += 2) {
if (m_userData[n] == type) {
RELEASESHARED(m_engine->engineRWLock);
return reinterpret_cast<void *>(m_userData[n + 1]);
}
}
RELEASESHARED(m_engine->engineRWLock);
return 0;
}
// interface
asIScriptFunction *asCContext::GetSystemFunction() {
return m_callingSystemFunction;
}
// interface
int asCContext::Prepare(asIScriptFunction *func) {
if (func == 0) {
asCString str;
str.Format(TXT_FAILED_IN_FUNC_s_WITH_s_s_d, "Prepare", "null", errorNames[-asNO_FUNCTION], asNO_FUNCTION);
m_engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
return asNO_FUNCTION;
}
if (m_status == asEXECUTION_ACTIVE || m_status == asEXECUTION_SUSPENDED) {
asCString str;
str.Format(TXT_FAILED_IN_FUNC_s_WITH_s_s_d, "Prepare", func->GetDeclaration(true, true), errorNames[-asCONTEXT_ACTIVE], asCONTEXT_ACTIVE);
m_engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
return asCONTEXT_ACTIVE;
}
// Clean the stack if not done before
if (m_status != asEXECUTION_FINISHED && m_status != asEXECUTION_UNINITIALIZED)
CleanStack();
// Release the returned object (if any)
CleanReturnObject();
// Release the object if it is a script object
if (m_initialFunction && m_initialFunction->objectType && (m_initialFunction->objectType->flags & asOBJ_SCRIPT_OBJECT)) {
asCScriptObject *obj = *(asCScriptObject **)&m_regs.stackFramePointer[0];
if (obj)
obj->Release();
*(asPWORD *)&m_regs.stackFramePointer[0] = 0;
}
if (m_initialFunction && m_initialFunction == func) {
// If the same function is executed again, we can skip a lot of the setup
m_currentFunction = m_initialFunction;
// Reset stack pointer
m_regs.stackPointer = m_originalStackPointer;
// Make sure the stack pointer is pointing to the original position,
// otherwise something is wrong with the way it is being updated
asASSERT(IsNested() || m_stackIndex > 0 || (m_regs.stackPointer == m_stackBlocks[0] + m_stackBlockSize));
} else {
asASSERT(m_engine);
// Make sure the function is from the same engine as the context to avoid mixups
if (m_engine != func->GetEngine()) {
asCString str;
str.Format(TXT_FAILED_IN_FUNC_s_WITH_s_s_d, "Prepare", func->GetDeclaration(true, true), errorNames[-asINVALID_ARG], asINVALID_ARG);
m_engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
return asINVALID_ARG;
}
if (m_initialFunction) {
m_initialFunction->Release();
// Reset stack pointer
m_regs.stackPointer = m_originalStackPointer;
// Make sure the stack pointer is pointing to the original position,
// otherwise something is wrong with the way it is being updated
asASSERT(IsNested() || m_stackIndex > 0 || (m_regs.stackPointer == m_stackBlocks[0] + m_stackBlockSize));
}
// We trust the application not to pass anything else but a asCScriptFunction
m_initialFunction = reinterpret_cast<asCScriptFunction *>(func);
m_initialFunction->AddRef();
m_currentFunction = m_initialFunction;
// TODO: runtime optimize: GetSpaceNeededForArguments() should be precomputed
m_argumentsSize = m_currentFunction->GetSpaceNeededForArguments() + (m_currentFunction->objectType ? AS_PTR_SIZE : 0);
// Reserve space for the arguments and return value
if (m_currentFunction->DoesReturnOnStack()) {
m_returnValueSize = m_currentFunction->returnType.GetSizeInMemoryDWords();
m_argumentsSize += AS_PTR_SIZE;
} else
m_returnValueSize = 0;
// Determine the minimum stack size needed
int stackSize = m_argumentsSize + m_returnValueSize;
if (m_currentFunction->scriptData)
stackSize += m_currentFunction->scriptData->stackNeeded;
// Make sure there is enough space on the stack for the arguments and return value
if (!ReserveStackSpace(stackSize))
return asOUT_OF_MEMORY;
// Set up the call stack too
if (m_callStack.GetCapacity() < m_engine->ep.initCallStackSize)
m_callStack.AllocateNoConstruct(m_engine->ep.initCallStackSize * CALLSTACK_FRAME_SIZE, true);
}
// Reset state
// Most of the time the previous state will be asEXECUTION_FINISHED, in which case the values are already initialized
if (m_status != asEXECUTION_FINISHED) {
m_exceptionLine = -1;
m_exceptionFunction = 0;
m_doAbort = false;
m_doSuspend = false;
m_regs.doProcessSuspend = m_lineCallback;
m_externalSuspendRequest = false;
}
m_status = asEXECUTION_PREPARED;
m_regs.programPointer = 0;
// Reserve space for the arguments and return value
m_regs.stackFramePointer = m_regs.stackPointer - m_argumentsSize - m_returnValueSize;
m_originalStackPointer = m_regs.stackPointer;
m_regs.stackPointer = m_regs.stackFramePointer;
// Set arguments to 0
memset(m_regs.stackPointer, 0, 4 * m_argumentsSize);
if (m_returnValueSize) {
// Set the address of the location where the return value should be put
asDWORD *ptr = m_regs.stackFramePointer;
if (m_currentFunction->objectType)
ptr += AS_PTR_SIZE;
*(void **)ptr = (void *)(m_regs.stackFramePointer + m_argumentsSize);
}
return asSUCCESS;
}
// Free all resources
int asCContext::Unprepare() {
if (m_status == asEXECUTION_ACTIVE || m_status == asEXECUTION_SUSPENDED)
return asCONTEXT_ACTIVE;
// Set the context as active so that any clean up code can use access it if desired
asCThreadLocalData *tld = asPushActiveContext((asIScriptContext *)this);
asDWORD count = m_refCount.get();
UNUSED_VAR(count);
// Only clean the stack if the context was prepared but not executed until the end
if (m_status != asEXECUTION_UNINITIALIZED &&
m_status != asEXECUTION_FINISHED)
CleanStack();
asASSERT(m_needToCleanupArgs == false);
// Release the returned object (if any)
CleanReturnObject();
// TODO: Unprepare is called during destruction, so nobody
// must be allowed to keep an extra reference
asASSERT(m_refCount.get() == count);
asPopActiveContext(tld, this);
// Release the object if it is a script object
if (m_initialFunction && m_initialFunction->objectType && (m_initialFunction->objectType->flags & asOBJ_SCRIPT_OBJECT)) {
asCScriptObject *obj = *(asCScriptObject **)&m_regs.stackFramePointer[0];
if (obj)
obj->Release();
}
// Release the initial function
if (m_initialFunction) {
m_initialFunction->Release();
// Reset stack pointer
m_regs.stackPointer = m_originalStackPointer;
// Make sure the stack pointer is pointing to the original position,
// otherwise something is wrong with the way it is being updated
asASSERT(IsNested() || m_stackIndex > 0 || (m_regs.stackPointer == m_stackBlocks[0] + m_stackBlockSize));
}
// Clear function pointers
m_initialFunction = 0;
m_currentFunction = 0;
m_exceptionFunction = 0;
m_regs.programPointer = 0;
// Reset status
m_status = asEXECUTION_UNINITIALIZED;
m_regs.stackFramePointer = 0;
return 0;
}
asBYTE asCContext::GetReturnByte() {
if (m_status != asEXECUTION_FINISHED) return 0;
asCDataType *dt = &m_initialFunction->returnType;
if (dt->IsObject() || dt->IsFuncdef() || dt->IsReference()) return 0;
return *(asBYTE *)&m_regs.valueRegister;
}
asWORD asCContext::GetReturnWord() {
if (m_status != asEXECUTION_FINISHED) return 0;
asCDataType *dt = &m_initialFunction->returnType;
if (dt->IsObject() || dt->IsFuncdef() || dt->IsReference()) return 0;
return *(asWORD *)&m_regs.valueRegister;
}
asDWORD asCContext::GetReturnDWord() {
if (m_status != asEXECUTION_FINISHED) return 0;
asCDataType *dt = &m_initialFunction->returnType;
if (dt->IsObject() || dt->IsFuncdef() || dt->IsReference()) return 0;
return *(asDWORD *)&m_regs.valueRegister;
}
asQWORD asCContext::GetReturnQWord() {
if (m_status != asEXECUTION_FINISHED) return 0;
asCDataType *dt = &m_initialFunction->returnType;
if (dt->IsObject() || dt->IsFuncdef() || dt->IsReference()) return 0;
return m_regs.valueRegister;
}
float asCContext::GetReturnFloat() {
if (m_status != asEXECUTION_FINISHED) return 0;
asCDataType *dt = &m_initialFunction->returnType;
if (dt->IsObject() || dt->IsFuncdef() || dt->IsReference()) return 0;
return *(float *)&m_regs.valueRegister;
}
double asCContext::GetReturnDouble() {
if (m_status != asEXECUTION_FINISHED) return 0;
asCDataType *dt = &m_initialFunction->returnType;
if (dt->IsObject() || dt->IsFuncdef() || dt->IsReference()) return 0;
return *(double *)&m_regs.valueRegister;
}
void *asCContext::GetReturnAddress() {
if (m_status != asEXECUTION_FINISHED) return 0;
asCDataType *dt = &m_initialFunction->returnType;
if (dt->IsReference())
return *(void **)&m_regs.valueRegister;
else if (dt->IsObject() || dt->IsFuncdef()) {
if (m_initialFunction->DoesReturnOnStack()) {
// The address of the return value was passed as the first argument, after the object pointer
int offset = 0;
if (m_initialFunction->objectType)
offset += AS_PTR_SIZE;
return *(void **)(&m_regs.stackFramePointer[offset]);
}
return m_regs.objectRegister;
}
return 0;
}
void *asCContext::GetReturnObject() {
if (m_status != asEXECUTION_FINISHED) return 0;
asCDataType *dt = &m_initialFunction->returnType;
if (!dt->IsObject() && !dt->IsFuncdef()) return 0;
if (dt->IsReference())
return *(void **)(asPWORD)m_regs.valueRegister;
else {
if (m_initialFunction->DoesReturnOnStack()) {
// The address of the return value was passed as the first argument, after the object pointer
int offset = 0;
if (m_initialFunction->objectType)
offset += AS_PTR_SIZE;
return *(void **)(&m_regs.stackFramePointer[offset]);
}
return m_regs.objectRegister;
}
}
void *asCContext::GetAddressOfReturnValue() {
if (m_status != asEXECUTION_FINISHED) return 0;
asCDataType *dt = &m_initialFunction->returnType;
// An object is stored in the objectRegister
if (!dt->IsReference() && (dt->IsObject() || dt->IsFuncdef())) {
// Need to dereference objects
if (!dt->IsObjectHandle()) {
if (m_initialFunction->DoesReturnOnStack()) {
// The address of the return value was passed as the first argument, after the object pointer
int offset = 0;
if (m_initialFunction->objectType)
offset += AS_PTR_SIZE;
return *(void **)(&m_regs.stackFramePointer[offset]);
}
return *(void **)&m_regs.objectRegister;
}
return &m_regs.objectRegister;
}
// Primitives and references are stored in valueRegister
return &m_regs.valueRegister;
}
int asCContext::SetObject(void *obj) {
if (m_status != asEXECUTION_PREPARED)
return asCONTEXT_NOT_PREPARED;
if (!m_initialFunction->objectType) {
m_status = asEXECUTION_ERROR;
return asERROR;
}
asASSERT(*(asPWORD *)&m_regs.stackFramePointer[0] == 0);
*(asPWORD *)&m_regs.stackFramePointer[0] = (asPWORD)obj;
// TODO: This should be optional by having a flag where the application can chose whether it should be done or not
// The flag could be named something like takeOwnership and have default value of true
if (obj && (m_initialFunction->objectType->flags & asOBJ_SCRIPT_OBJECT))
reinterpret_cast<asCScriptObject *>(obj)->AddRef();
return 0;
}
int asCContext::SetArgByte(asUINT arg, asBYTE value) {
if (m_status != asEXECUTION_PREPARED)
return asCONTEXT_NOT_PREPARED;
if (arg >= (unsigned)m_initialFunction->parameterTypes.GetLength()) {
m_status = asEXECUTION_ERROR;
return asINVALID_ARG;
}
// Verify the type of the argument
asCDataType *dt = &m_initialFunction->parameterTypes[arg];
if (dt->IsObject() || dt->IsFuncdef() || dt->IsReference()) {
m_status = asEXECUTION_ERROR;
return asINVALID_TYPE;
}
if (dt->GetSizeInMemoryBytes() != 1) {
m_status = asEXECUTION_ERROR;
return asINVALID_TYPE;
}
// Determine the position of the argument
int offset = 0;
if (m_initialFunction->objectType)
offset += AS_PTR_SIZE;
// If function returns object by value an extra pointer is pushed on the stack
if (m_returnValueSize)
offset += AS_PTR_SIZE;
for (asUINT n = 0; n < arg; n++)
offset += m_initialFunction->parameterTypes[n].GetSizeOnStackDWords();
// Set the value
*(asBYTE *)&m_regs.stackFramePointer[offset] = value;
return 0;
}
int asCContext::SetArgWord(asUINT arg, asWORD value) {
if (m_status != asEXECUTION_PREPARED)
return asCONTEXT_NOT_PREPARED;
if (arg >= m_initialFunction->parameterTypes.GetLength()) {
m_status = asEXECUTION_ERROR;
return asINVALID_ARG;
}
// Verify the type of the argument
asCDataType *dt = &m_initialFunction->parameterTypes[arg];
if (dt->IsObject() || dt->IsFuncdef() || dt->IsReference()) {
m_status = asEXECUTION_ERROR;
return asINVALID_TYPE;
}
if (dt->GetSizeInMemoryBytes() != 2) {
m_status = asEXECUTION_ERROR;
return asINVALID_TYPE;
}
// Determine the position of the argument
int offset = 0;
if (m_initialFunction->objectType)
offset += AS_PTR_SIZE;
// If function returns object by value an extra pointer is pushed on the stack
if (m_returnValueSize)
offset += AS_PTR_SIZE;
for (asUINT n = 0; n < arg; n++)
offset += m_initialFunction->parameterTypes[n].GetSizeOnStackDWords();
// Set the value
*(asWORD *)&m_regs.stackFramePointer[offset] = value;
return 0;
}
int asCContext::SetArgDWord(asUINT arg, asDWORD value) {
if (m_status != asEXECUTION_PREPARED)
return asCONTEXT_NOT_PREPARED;
if (arg >= (unsigned)m_initialFunction->parameterTypes.GetLength()) {
m_status = asEXECUTION_ERROR;
return asINVALID_ARG;
}
// Verify the type of the argument
asCDataType *dt = &m_initialFunction->parameterTypes[arg];
if (dt->IsObject() || dt->IsFuncdef() || dt->IsReference()) {
m_status = asEXECUTION_ERROR;
return asINVALID_TYPE;
}
if (dt->GetSizeInMemoryBytes() != 4) {
m_status = asEXECUTION_ERROR;
return asINVALID_TYPE;
}
// Determine the position of the argument
int offset = 0;
if (m_initialFunction->objectType)
offset += AS_PTR_SIZE;
// If function returns object by value an extra pointer is pushed on the stack
if (m_returnValueSize)
offset += AS_PTR_SIZE;
for (asUINT n = 0; n < arg; n++)
offset += m_initialFunction->parameterTypes[n].GetSizeOnStackDWords();
// Set the value
*(asDWORD *)&m_regs.stackFramePointer[offset] = value;
return 0;
}
int asCContext::SetArgQWord(asUINT arg, asQWORD value) {
if (m_status != asEXECUTION_PREPARED)
return asCONTEXT_NOT_PREPARED;
if (arg >= (unsigned)m_initialFunction->parameterTypes.GetLength()) {
m_status = asEXECUTION_ERROR;
return asINVALID_ARG;
}
// Verify the type of the argument
asCDataType *dt = &m_initialFunction->parameterTypes[arg];
if (dt->IsObject() || dt->IsFuncdef() || dt->IsReference()) {
m_status = asEXECUTION_ERROR;
return asINVALID_TYPE;
}
if (dt->GetSizeOnStackDWords() != 2) {
m_status = asEXECUTION_ERROR;
return asINVALID_TYPE;
}
// Determine the position of the argument
int offset = 0;
if (m_initialFunction->objectType)
offset += AS_PTR_SIZE;
// If function returns object by value an extra pointer is pushed on the stack
if (m_returnValueSize)
offset += AS_PTR_SIZE;
for (asUINT n = 0; n < arg; n++)
offset += m_initialFunction->parameterTypes[n].GetSizeOnStackDWords();
// Set the value
*(asQWORD *)(&m_regs.stackFramePointer[offset]) = value;
return 0;
}
int asCContext::SetArgFloat(asUINT arg, float value) {
if (m_status != asEXECUTION_PREPARED)
return asCONTEXT_NOT_PREPARED;
if (arg >= (unsigned)m_initialFunction->parameterTypes.GetLength()) {
m_status = asEXECUTION_ERROR;
return asINVALID_ARG;
}
// Verify the type of the argument
asCDataType *dt = &m_initialFunction->parameterTypes[arg];
if (dt->IsObject() || dt->IsFuncdef() || dt->IsReference()) {
m_status = asEXECUTION_ERROR;
return asINVALID_TYPE;
}
if (dt->GetSizeOnStackDWords() != 1) {
m_status = asEXECUTION_ERROR;
return asINVALID_TYPE;
}
// Determine the position of the argument
int offset = 0;
if (m_initialFunction->objectType)
offset += AS_PTR_SIZE;
// If function returns object by value an extra pointer is pushed on the stack
if (m_returnValueSize)
offset += AS_PTR_SIZE;
for (asUINT n = 0; n < arg; n++)
offset += m_initialFunction->parameterTypes[n].GetSizeOnStackDWords();
// Set the value
*(float *)(&m_regs.stackFramePointer[offset]) = value;
return 0;
}
int asCContext::SetArgDouble(asUINT arg, double value) {
if (m_status != asEXECUTION_PREPARED)
return asCONTEXT_NOT_PREPARED;
if (arg >= (unsigned)m_initialFunction->parameterTypes.GetLength()) {
m_status = asEXECUTION_ERROR;
return asINVALID_ARG;
}
// Verify the type of the argument
asCDataType *dt = &m_initialFunction->parameterTypes[arg];
if (dt->IsObject() || dt->IsFuncdef() || dt->IsReference()) {
m_status = asEXECUTION_ERROR;
return asINVALID_TYPE;
}
if (dt->GetSizeOnStackDWords() != 2) {
m_status = asEXECUTION_ERROR;
return asINVALID_TYPE;
}
// Determine the position of the argument
int offset = 0;
if (m_initialFunction->objectType)
offset += AS_PTR_SIZE;
// If function returns object by value an extra pointer is pushed on the stack
if (m_returnValueSize)
offset += AS_PTR_SIZE;
for (asUINT n = 0; n < arg; n++)
offset += m_initialFunction->parameterTypes[n].GetSizeOnStackDWords();
// Set the value
*(double *)(&m_regs.stackFramePointer[offset]) = value;
return 0;
}
int asCContext::SetArgAddress(asUINT arg, void *value) {
if (m_status != asEXECUTION_PREPARED)
return asCONTEXT_NOT_PREPARED;
if (arg >= (unsigned)m_initialFunction->parameterTypes.GetLength()) {
m_status = asEXECUTION_ERROR;
return asINVALID_ARG;
}
// Verify the type of the argument
asCDataType *dt = &m_initialFunction->parameterTypes[arg];
if (!dt->IsReference() && !dt->IsObjectHandle()) {
m_status = asEXECUTION_ERROR;
return asINVALID_TYPE;
}
// Determine the position of the argument
int offset = 0;
if (m_initialFunction->objectType)
offset += AS_PTR_SIZE;
// If function returns object by value an extra pointer is pushed on the stack
if (m_returnValueSize)
offset += AS_PTR_SIZE;
for (asUINT n = 0; n < arg; n++)
offset += m_initialFunction->parameterTypes[n].GetSizeOnStackDWords();
// Set the value
*(asPWORD *)(&m_regs.stackFramePointer[offset]) = (asPWORD)value;
return 0;
}
int asCContext::SetArgObject(asUINT arg, void *obj) {
if (m_status != asEXECUTION_PREPARED)
return asCONTEXT_NOT_PREPARED;
if (arg >= (unsigned)m_initialFunction->parameterTypes.GetLength()) {
m_status = asEXECUTION_ERROR;
return asINVALID_ARG;
}
// Verify the type of the argument
asCDataType *dt = &m_initialFunction->parameterTypes[arg];
if (!dt->IsObject() && !dt->IsFuncdef()) {
m_status = asEXECUTION_ERROR;
return asINVALID_TYPE;
}
// If the object should be sent by value we must make a copy of it
if (!dt->IsReference()) {
if (dt->IsObjectHandle()) {
// Increase the reference counter
if (obj && dt->IsFuncdef())
((asIScriptFunction *)obj)->AddRef();
else {
asSTypeBehaviour *beh = &CastToObjectType(dt->GetTypeInfo())->beh;
if (obj && beh->addref)
m_engine->CallObjectMethod(obj, beh->addref);
}
} else {
obj = m_engine->CreateScriptObjectCopy(obj, dt->GetTypeInfo());
}
}
// Determine the position of the argument
int offset = 0;
if (m_initialFunction->objectType)
offset += AS_PTR_SIZE;
// If function returns object by value an extra pointer is pushed on the stack
if (m_returnValueSize)
offset += AS_PTR_SIZE;
for (asUINT n = 0; n < arg; n++)
offset += m_initialFunction->parameterTypes[n].GetSizeOnStackDWords();
// Set the value
*(asPWORD *)(&m_regs.stackFramePointer[offset]) = (asPWORD)obj;
return 0;
}
int asCContext::SetArgVarType(asUINT arg, void *ptr, int typeId) {
if (m_status != asEXECUTION_PREPARED)
return asCONTEXT_NOT_PREPARED;
if (arg >= (unsigned)m_initialFunction->parameterTypes.GetLength()) {
m_status = asEXECUTION_ERROR;
return asINVALID_ARG;
}
// Verify the type of the argument
asCDataType *dt = &m_initialFunction->parameterTypes[arg];
if (dt->GetTokenType() != ttQuestion) {
m_status = asEXECUTION_ERROR;
return asINVALID_TYPE;
}
// Determine the position of the argument
int offset = 0;
if (m_initialFunction->objectType)
offset += AS_PTR_SIZE;
// If function returns object by value an extra pointer is pushed on the stack
if (m_returnValueSize)
offset += AS_PTR_SIZE;
for (asUINT n = 0; n < arg; n++)
offset += m_initialFunction->parameterTypes[n].GetSizeOnStackDWords();
// Set the typeId and pointer
*(asPWORD *)(&m_regs.stackFramePointer[offset]) = (asPWORD)ptr;
offset += AS_PTR_SIZE;
*(int *)(&m_regs.stackFramePointer[offset]) = typeId;
return 0;
}
// TODO: Instead of GetAddressOfArg, maybe we need a SetArgValue(int arg, void *value, bool takeOwnership) instead.
// interface
void *asCContext::GetAddressOfArg(asUINT arg) {
if (m_status != asEXECUTION_PREPARED)
return 0;
if (arg >= (unsigned)m_initialFunction->parameterTypes.GetLength())
return 0;
// Determine the position of the argument
int offset = 0;
if (m_initialFunction->objectType)
offset += AS_PTR_SIZE;
// If function returns object by value an extra pointer is pushed on the stack
if (m_returnValueSize)
offset += AS_PTR_SIZE;
for (asUINT n = 0; n < arg; n++)
offset += m_initialFunction->parameterTypes[n].GetSizeOnStackDWords();
// We should return the address of the location where the argument value will be placed
// All registered types are always sent by reference, even if
// the function is declared to receive the argument by value.
return &m_regs.stackFramePointer[offset];
}
int asCContext::Abort() {
if (m_engine == 0) return asERROR;
// TODO: multithread: Make thread safe. There is a chance that the status
// changes to something else after being set to ABORTED here.
if (m_status == asEXECUTION_SUSPENDED)
m_status = asEXECUTION_ABORTED;
m_doSuspend = true;
m_regs.doProcessSuspend = true;
m_externalSuspendRequest = true;
m_doAbort = true;
return 0;
}
// interface
int asCContext::Suspend() {
// This function just sets some internal flags and is safe
// to call from a secondary thread, even if the library has
// been built without multi-thread support.
if (m_engine == 0) return asERROR;
m_doSuspend = true;
m_externalSuspendRequest = true;
m_regs.doProcessSuspend = true;
return 0;
}
// interface
int asCContext::Execute() {
asASSERT(m_engine != 0);
if (m_status != asEXECUTION_SUSPENDED && m_status != asEXECUTION_PREPARED) {
asCString str;
str.Format(TXT_FAILED_IN_FUNC_s_s_d, "Execute", errorNames[-asCONTEXT_NOT_PREPARED], asCONTEXT_NOT_PREPARED);
m_engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
return asCONTEXT_NOT_PREPARED;
}
m_status = asEXECUTION_ACTIVE;
asCThreadLocalData *tld = asPushActiveContext((asIScriptContext *)this);
// Make sure there are not too many nested calls, as it could crash the application
// by filling up the thread call stack
if (tld->activeContexts.GetLength() > m_engine->ep.maxNestedCalls)
SetInternalException(TXT_TOO_MANY_NESTED_CALLS);
else if (m_regs.programPointer == 0) {
if (m_currentFunction->funcType == asFUNC_DELEGATE) {
// Push the object pointer onto the stack
asASSERT(m_regs.stackPointer - AS_PTR_SIZE >= m_stackBlocks[m_stackIndex]);
m_regs.stackPointer -= AS_PTR_SIZE;
m_regs.stackFramePointer -= AS_PTR_SIZE;
*(asPWORD *)m_regs.stackPointer = asPWORD(m_currentFunction->objForDelegate);
// Make the call to the delegated object method
m_currentFunction = m_currentFunction->funcForDelegate;
}
if (m_currentFunction->funcType == asFUNC_VIRTUAL ||
m_currentFunction->funcType == asFUNC_INTERFACE) {
// The currentFunction is a virtual method
// Determine the true function from the object
asCScriptObject *obj = *(asCScriptObject **)(asPWORD *)m_regs.stackFramePointer;
if (obj == 0) {
SetInternalException(TXT_NULL_POINTER_ACCESS);
} else {
asCObjectType *objType = obj->objType;
asCScriptFunction *realFunc = 0;
if (m_currentFunction->funcType == asFUNC_VIRTUAL) {
if (objType->virtualFunctionTable.GetLength() > (asUINT)m_currentFunction->vfTableIdx) {
realFunc = objType->virtualFunctionTable[m_currentFunction->vfTableIdx];
}
} else {
// Search the object type for a function that matches the interface function
for (asUINT n = 0; n < objType->methods.GetLength(); n++) {
asCScriptFunction *f2 = m_engine->scriptFunctions[objType->methods[n]];
if (f2->signatureId == m_currentFunction->signatureId) {
if (f2->funcType == asFUNC_VIRTUAL)
realFunc = objType->virtualFunctionTable[f2->vfTableIdx];
else
realFunc = f2;
break;
}
}
}
if (realFunc && realFunc->signatureId == m_currentFunction->signatureId)
m_currentFunction = realFunc;
else
SetInternalException(TXT_NULL_POINTER_ACCESS);
}
} else if (m_currentFunction->funcType == asFUNC_IMPORTED) {
int funcId = m_engine->importedFunctions[m_currentFunction->id & ~FUNC_IMPORTED]->boundFunctionId;
if (funcId > 0)
m_currentFunction = m_engine->scriptFunctions[funcId];
else
SetInternalException(TXT_UNBOUND_FUNCTION);
}
if (m_currentFunction->funcType == asFUNC_SCRIPT) {
m_regs.programPointer = m_currentFunction->scriptData->byteCode.AddressOf();
// Set up the internal registers for executing the script function
PrepareScriptFunction();
} else if (m_currentFunction->funcType == asFUNC_SYSTEM) {
// The current function is an application registered function
// Call the function directly
CallSystemFunction(m_currentFunction->id, this);
// Was the call successful?
if (m_status == asEXECUTION_ACTIVE) {
m_status = asEXECUTION_FINISHED;
}
} else {
// This shouldn't happen unless there was an error in which
// case an exception should have been raised already
asASSERT(m_status == asEXECUTION_EXCEPTION);
}
}
asUINT gcPreObjects = 0;
if (m_engine->ep.autoGarbageCollect)
m_engine->gc.GetStatistics(&gcPreObjects, 0, 0, 0, 0);
while (m_status == asEXECUTION_ACTIVE) {
ExecuteNext();
// If an exception was raised that will be caught, then unwind the stack
// and move the program pointer to the catch block before proceeding
if (m_status == asEXECUTION_EXCEPTION && m_exceptionWillBeCaught)
CleanStack(true);
}
if (m_lineCallback) {
// Call the line callback one last time before leaving
// so anyone listening can catch the state change
CallLineCallback();
m_regs.doProcessSuspend = true;
} else
m_regs.doProcessSuspend = false;
m_doSuspend = false;
if (m_engine->ep.autoGarbageCollect) {
asUINT gcPosObjects = 0;
m_engine->gc.GetStatistics(&gcPosObjects, 0, 0, 0, 0);
if (gcPosObjects > gcPreObjects) {
// Execute as many steps as there were new objects created
m_engine->GarbageCollect(asGC_ONE_STEP | asGC_DESTROY_GARBAGE | asGC_DETECT_GARBAGE, gcPosObjects - gcPreObjects);
} else if (gcPosObjects > 0) {
// Execute at least one step, even if no new objects were created
m_engine->GarbageCollect(asGC_ONE_STEP | asGC_DESTROY_GARBAGE | asGC_DETECT_GARBAGE, 1);
}
}
// Pop the active context
asPopActiveContext(tld, this);
if (m_status == asEXECUTION_FINISHED) {
m_regs.objectType = m_initialFunction->returnType.GetTypeInfo();
return asEXECUTION_FINISHED;
}
if (m_doAbort) {
m_doAbort = false;
m_status = asEXECUTION_ABORTED;
return asEXECUTION_ABORTED;
}
if (m_status == asEXECUTION_SUSPENDED)
return asEXECUTION_SUSPENDED;
if (m_status == asEXECUTION_EXCEPTION)
return asEXECUTION_EXCEPTION;
return asERROR;
}
int asCContext::PushState() {
// Only allow the state to be pushed when active
// TODO: Can we support a suspended state too? So the reuse of
// the context can be done outside the Execute() call?
if (m_status != asEXECUTION_ACTIVE) {
// TODO: Write message. Wrong usage
return asERROR;
}
// Allocate space on the callstack for at least two states
if (m_callStack.GetLength() >= m_callStack.GetCapacity() - 2 * CALLSTACK_FRAME_SIZE) {
if (m_engine->ep.maxCallStackSize > 0 && m_callStack.GetLength() >= m_engine->ep.maxCallStackSize * CALLSTACK_FRAME_SIZE) {
// The call stack is too big to grow further
// If an error occurs, no change to the context should be done
return asOUT_OF_MEMORY;
}
// Allocate space for 10 call states at a time to save time
m_callStack.AllocateNoConstruct(m_callStack.GetLength() + 10 * CALLSTACK_FRAME_SIZE, true);
}
// Push the current script function that is calling the system function
// This cannot fail, since the memory was already allocated above
PushCallState();
// Push the system function too, which will serve both as a marker and
// informing which system function that created the nested call
m_callStack.SetLengthNoConstruct(m_callStack.GetLength() + CALLSTACK_FRAME_SIZE);
// Need to push m_initialFunction as it must be restored later
asPWORD *tmp = m_callStack.AddressOf() + m_callStack.GetLength() - CALLSTACK_FRAME_SIZE;
tmp[0] = 0;
tmp[1] = (asPWORD)m_callingSystemFunction;
tmp[2] = (asPWORD)m_initialFunction;
tmp[3] = (asPWORD)m_originalStackPointer;
tmp[4] = (asPWORD)m_argumentsSize;
// Need to push the value of registers so they can be restored
tmp[5] = (asPWORD)asDWORD(m_regs.valueRegister);
tmp[6] = (asPWORD)asDWORD(m_regs.valueRegister >> 32);
tmp[7] = (asPWORD)m_regs.objectRegister;
tmp[8] = (asPWORD)m_regs.objectType;
// Decrease stackpointer to prevent the top value from being overwritten
m_regs.stackPointer -= 2;
// Clear the initial function so that Prepare() knows it must do all validations
m_initialFunction = 0;
// After this the state should appear as if uninitialized
m_callingSystemFunction = 0;
m_regs.objectRegister = 0;
m_regs.objectType = 0;
// Set the status to uninitialized as application
// should call Prepare() after this to reuse the context
m_status = asEXECUTION_UNINITIALIZED;
return asSUCCESS;
}
int asCContext::PopState() {
if (!IsNested())
return asERROR;
// Clean up the current execution
Unprepare();
// The topmost state must be a marker for nested call
asASSERT(m_callStack[m_callStack.GetLength() - CALLSTACK_FRAME_SIZE] == 0);
// Restore the previous state
asPWORD *tmp = &m_callStack[m_callStack.GetLength() - CALLSTACK_FRAME_SIZE];
m_callingSystemFunction = reinterpret_cast<asCScriptFunction *>(tmp[1]);
m_callStack.SetLength(m_callStack.GetLength() - CALLSTACK_FRAME_SIZE);
// Restore the previous initial function and the associated values
m_initialFunction = reinterpret_cast<asCScriptFunction *>(tmp[2]);
m_originalStackPointer = (asDWORD *)tmp[3];
m_argumentsSize = (int)tmp[4];
m_regs.valueRegister = asQWORD(asDWORD(tmp[5]));
m_regs.valueRegister |= asQWORD(tmp[6]) << 32;
m_regs.objectRegister = (void *)tmp[7];
m_regs.objectType = (asITypeInfo *)tmp[8];
// Calculate the returnValueSize
if (m_initialFunction->DoesReturnOnStack())
m_returnValueSize = m_initialFunction->returnType.GetSizeInMemoryDWords();
else
m_returnValueSize = 0;
// Pop the current script function. This will also restore the previous stack pointer
PopCallState();
m_status = asEXECUTION_ACTIVE;
return asSUCCESS;
}
int asCContext::PushCallState() {
if (m_callStack.GetLength() == m_callStack.GetCapacity()) {
if (m_engine->ep.maxCallStackSize > 0 && m_callStack.GetLength() >= m_engine->ep.maxCallStackSize * CALLSTACK_FRAME_SIZE) {
// The call stack is too big to grow further
SetInternalException(TXT_STACK_OVERFLOW);
return asERROR;
}
// Allocate space for 10 call states at a time to save time
m_callStack.AllocateNoConstruct(m_callStack.GetLength() + 10 * CALLSTACK_FRAME_SIZE, true);
}
m_callStack.SetLengthNoConstruct(m_callStack.GetLength() + CALLSTACK_FRAME_SIZE);
// Separating the loads and stores limits data cache trash, and with a smart compiler
// could turn into SIMD style loading/storing if available.
// The compiler can't do this itself due to potential pointer aliasing between the pointers,
// ie writing to tmp could overwrite the data contained in registers.stackFramePointer for example
// for all the compiler knows. So introducing the local variable s, which is never referred to by
// its address we avoid this issue.
asPWORD s[5];
s[0] = (asPWORD)m_regs.stackFramePointer;
s[1] = (asPWORD)m_currentFunction;
s[2] = (asPWORD)m_regs.programPointer;
s[3] = (asPWORD)m_regs.stackPointer;
s[4] = m_stackIndex;
asPWORD *tmp = m_callStack.AddressOf() + m_callStack.GetLength() - CALLSTACK_FRAME_SIZE;
tmp[0] = s[0];
tmp[1] = s[1];
tmp[2] = s[2];
tmp[3] = s[3];
tmp[4] = s[4];
return asSUCCESS;
}
void asCContext::PopCallState() {
// See comments in PushCallState about pointer aliasing and data cache trashing
asPWORD *tmp = m_callStack.AddressOf() + m_callStack.GetLength() - CALLSTACK_FRAME_SIZE;
asPWORD s[5];
s[0] = tmp[0];
s[1] = tmp[1];
s[2] = tmp[2];
s[3] = tmp[3];
s[4] = tmp[4];
m_regs.stackFramePointer = (asDWORD *)s[0];
m_currentFunction = (asCScriptFunction *)s[1];
m_regs.programPointer = (asDWORD *)s[2];
m_regs.stackPointer = (asDWORD *)s[3];
m_stackIndex = (int)s[4];
m_callStack.SetLength(m_callStack.GetLength() - CALLSTACK_FRAME_SIZE);
}
// interface
asUINT asCContext::GetCallstackSize() const {
if (m_currentFunction == 0) return 0;
// The current function is accessed at stackLevel 0
return asUINT(1 + m_callStack.GetLength() / CALLSTACK_FRAME_SIZE);
}
// interface
asIScriptFunction *asCContext::GetFunction(asUINT stackLevel) {
if (stackLevel >= GetCallstackSize()) return 0;
if (stackLevel == 0) return m_currentFunction;
asPWORD *s = m_callStack.AddressOf() + (GetCallstackSize() - stackLevel - 1) * CALLSTACK_FRAME_SIZE;
asCScriptFunction *func = (asCScriptFunction *)s[1];
return func;
}
// interface
int asCContext::GetLineNumber(asUINT stackLevel, int *column, const char **sectionName) {
if (stackLevel >= GetCallstackSize()) return asINVALID_ARG;
asCScriptFunction *func;
asDWORD *bytePos;
if (stackLevel == 0) {
func = m_currentFunction;
if (func->scriptData == 0) return 0;
bytePos = m_regs.programPointer;
} else {
asPWORD *s = m_callStack.AddressOf() + (GetCallstackSize() - stackLevel - 1) * CALLSTACK_FRAME_SIZE;
func = (asCScriptFunction *)s[1];
if (func->scriptData == 0) return 0;
bytePos = (asDWORD *)s[2];
// Subract 1 from the bytePos, because we want the line where
// the call was made, and not the instruction after the call
bytePos -= 1;
}
// For nested calls it is possible that func is null
if (func == 0) {
if (column) *column = 0;
if (sectionName) *sectionName = 0;
return 0;
}
int sectionIdx;
asDWORD line = func->GetLineNumber(int(bytePos - func->scriptData->byteCode.AddressOf()), §ionIdx);
if (column) *column = (line >> 20);
if (sectionName) {
asASSERT(sectionIdx < int(m_engine->scriptSectionNames.GetLength()));
if (sectionIdx >= 0 && asUINT(sectionIdx) < m_engine->scriptSectionNames.GetLength())
*sectionName = m_engine->scriptSectionNames[sectionIdx]->AddressOf();
else
*sectionName = 0;
}
return (line & 0xFFFFF);
}
// internal
bool asCContext::ReserveStackSpace(asUINT size) {
#ifdef WIP_16BYTE_ALIGN
// Pad size to a multiple of MAX_TYPE_ALIGNMENT.
const asUINT remainder = size % MAX_TYPE_ALIGNMENT;
if (remainder != 0) {
size = size + (MAX_TYPE_ALIGNMENT - (size % MAX_TYPE_ALIGNMENT));
}
#endif
// Make sure the first stack block is allocated
if (m_stackBlocks.GetLength() == 0) {
m_stackBlockSize = m_engine->ep.initContextStackSize;
asASSERT(m_stackBlockSize > 0);
#ifndef WIP_16BYTE_ALIGN
asDWORD *stack = asNEWARRAY(asDWORD, m_stackBlockSize);
#else
asDWORD *stack = asNEWARRAYALIGNED(asDWORD, m_stackBlockSize, MAX_TYPE_ALIGNMENT);
#endif
if (stack == 0) {
// Out of memory
return false;
}
#ifdef WIP_16BYTE_ALIGN
asASSERT(isAligned(stack, MAX_TYPE_ALIGNMENT));
#endif
m_stackBlocks.PushLast(stack);
m_stackIndex = 0;
m_regs.stackPointer = m_stackBlocks[0] + m_stackBlockSize;
#ifdef WIP_16BYTE_ALIGN
// Align the stack pointer. This is necessary as the m_stackBlockSize is not necessarily evenly divisable with the max alignment
((asPWORD &)m_regs.stackPointer) &= ~(MAX_TYPE_ALIGNMENT - 1);
asASSERT(isAligned(m_regs.stackPointer, MAX_TYPE_ALIGNMENT));
#endif
}
// Check if there is enough space on the current stack block, otherwise move
// to the next one. New and larger blocks will be allocated as necessary
while (m_regs.stackPointer - (size + RESERVE_STACK) < m_stackBlocks[m_stackIndex]) {
// Make sure we don't allocate more space than allowed
if (m_engine->ep.maximumContextStackSize) {
// This test will only stop growth once it is on or already crossed the limit
if (m_stackBlockSize * ((1 << (m_stackIndex + 1)) - 1) >= m_engine->ep.maximumContextStackSize) {
m_isStackMemoryNotAllocated = true;
// Set the stackFramePointer, even though the stackPointer wasn't updated
m_regs.stackFramePointer = m_regs.stackPointer;
SetInternalException(TXT_STACK_OVERFLOW);
return false;
}
}
m_stackIndex++;
if (m_stackBlocks.GetLength() == m_stackIndex) {
// Allocate the new stack block, with twice the size of the previous
#ifndef WIP_16BYTE_ALIGN
asDWORD *stack = asNEWARRAY(asDWORD, (m_stackBlockSize << m_stackIndex));
#else
asDWORD *stack = asNEWARRAYALIGNED(asDWORD, (m_stackBlockSize << m_stackIndex), MAX_TYPE_ALIGNMENT);
#endif
if (stack == 0) {
// Out of memory
m_isStackMemoryNotAllocated = true;
// Set the stackFramePointer, even though the stackPointer wasn't updated
m_regs.stackFramePointer = m_regs.stackPointer;
SetInternalException(TXT_STACK_OVERFLOW);
return false;
}
#ifdef WIP_16BYTE_ALIGN
asASSERT(isAligned(stack, MAX_TYPE_ALIGNMENT));
#endif
m_stackBlocks.PushLast(stack);
}
// Update the stack pointer to point to the new block.
// Leave enough room above the stackpointer to copy the arguments from the previous stackblock
m_regs.stackPointer = m_stackBlocks[m_stackIndex] +
(m_stackBlockSize << m_stackIndex) -
m_currentFunction->GetSpaceNeededForArguments() -
(m_currentFunction->objectType ? AS_PTR_SIZE : 0) -
(m_currentFunction->DoesReturnOnStack() ? AS_PTR_SIZE : 0);
#ifdef WIP_16BYTE_ALIGN
// Align the stack pointer
(asPWORD &)m_regs.stackPointer &= ~(MAX_TYPE_ALIGNMENT - 1);
asASSERT(isAligned(m_regs.stackPointer, MAX_TYPE_ALIGNMENT));
#endif
}
return true;
}
// internal
void asCContext::CallScriptFunction(asCScriptFunction *func) {
asASSERT(func->scriptData);
// Push the framepointer, function id and programCounter on the stack
if (PushCallState() < 0)
return;
// Update the current function and program position before increasing the stack
// so the exception handler will know what to do if there is a stack overflow
m_currentFunction = func;
m_regs.programPointer = m_currentFunction->scriptData->byteCode.AddressOf();
PrepareScriptFunction();
}
void asCContext::PrepareScriptFunction() {
asASSERT(m_currentFunction->scriptData);
// Make sure there is space on the stack to execute the function
asDWORD *oldStackPointer = m_regs.stackPointer;
if (!ReserveStackSpace(m_currentFunction->scriptData->stackNeeded))
return;
// If a new stack block was allocated then we'll need to move
// over the function arguments to the new block.
if (m_regs.stackPointer != oldStackPointer) {
int numDwords = m_currentFunction->GetSpaceNeededForArguments() +
(m_currentFunction->objectType ? AS_PTR_SIZE : 0) +
(m_currentFunction->DoesReturnOnStack() ? AS_PTR_SIZE : 0);
memcpy(m_regs.stackPointer, oldStackPointer, sizeof(asDWORD)*numDwords);
}
// Update framepointer
m_regs.stackFramePointer = m_regs.stackPointer;
// Set all object variables to 0 to guarantee that they are null before they are used
// Only variables on the heap should be cleared. The rest will be cleared by calling the constructor
asUINT n = m_currentFunction->scriptData->objVariablesOnHeap;
while (n-- > 0) {
int pos = m_currentFunction->scriptData->objVariablePos[n];
*(asPWORD *)&m_regs.stackFramePointer[-pos] = 0;
}
// Initialize the stack pointer with the space needed for local variables
m_regs.stackPointer -= m_currentFunction->scriptData->variableSpace;
// Call the line callback for each script function, to guarantee that infinitely recursive scripts can
// be interrupted, even if the scripts have been compiled with asEP_BUILD_WITHOUT_LINE_CUES
if (m_regs.doProcessSuspend) {
if (m_lineCallback)
CallLineCallback();
if (m_doSuspend)
m_status = asEXECUTION_SUSPENDED;
}
}
void asCContext::CallInterfaceMethod(asCScriptFunction *func) {
// Resolve the interface method using the current script type
asCScriptObject *obj = *(asCScriptObject **)(asPWORD *)m_regs.stackPointer;
if (obj == 0) {
// Tell the exception handler to clean up the arguments to this method
m_needToCleanupArgs = true;
SetInternalException(TXT_NULL_POINTER_ACCESS);
return;
}
asCObjectType *objType = obj->objType;
// Search the object type for a function that matches the interface function
asCScriptFunction *realFunc = 0;
if (func->funcType == asFUNC_INTERFACE) {
// Find the offset for the interface's virtual function table chunk
asUINT offset = 0;
bool found = false;
asCObjectType *findInterface = func->objectType;
// TODO: runtime optimize: The list of interfaces should be ordered by the address
// Then a binary search pattern can be used.
asUINT intfCount = asUINT(objType->interfaces.GetLength());
for (asUINT n = 0; n < intfCount; n++) {
if (objType->interfaces[n] == findInterface) {
offset = objType->interfaceVFTOffsets[n];
found = true;
break;
}
}
if (!found) {
// Tell the exception handler to clean up the arguments to this method
m_needToCleanupArgs = true;
SetInternalException(TXT_NULL_POINTER_ACCESS);
return;
}
// Find the real function in the virtual table chunk with the found offset
realFunc = objType->virtualFunctionTable[func->vfTableIdx + offset];
// Since the interface was implemented by the class, it shouldn't
// be possible that the real function isn't found
asASSERT(realFunc);
asASSERT(realFunc->signatureId == func->signatureId);
} else { // if( func->funcType == asFUNC_VIRTUAL )
realFunc = objType->virtualFunctionTable[func->vfTableIdx];
}
// Then call the true script function
CallScriptFunction(realFunc);
}
void asCContext::ExecuteNext() {
asDWORD *l_bc = m_regs.programPointer;
asDWORD *l_sp = m_regs.stackPointer;
asDWORD *l_fp = m_regs.stackFramePointer;
for (;;) {
#ifdef AS_DEBUG
// Gather statistics on executed bytecode
stats.Instr(*(asBYTE *)l_bc);
// Used to verify that the size of the instructions are correct
asDWORD *old = l_bc;
#endif
// Remember to keep the cases in order and without
// gaps, because that will make the switch faster.
// It will be faster since only one lookup will be
// made to find the correct jump destination. If not
// in order, the switch will make two lookups.
switch (*(asBYTE *)l_bc) {
//--------------
// memory access functions
case asBC_PopPtr:
// Pop a pointer from the stack
l_sp += AS_PTR_SIZE;
l_bc++;
break;
case asBC_PshGPtr:
// Replaces PGA + RDSPtr
l_sp -= AS_PTR_SIZE;
*(asPWORD *)l_sp = *(asPWORD *)asBC_PTRARG(l_bc);
l_bc += 1 + AS_PTR_SIZE;
break;
// Push a dword value on the stack
case asBC_PshC4:
--l_sp;
*l_sp = asBC_DWORDARG(l_bc);
l_bc += 2;
break;
// Push the dword value of a variable on the stack
case asBC_PshV4:
--l_sp;
*l_sp = *(l_fp - asBC_SWORDARG0(l_bc));
l_bc++;
break;
// Push the address of a variable on the stack
case asBC_PSF:
l_sp -= AS_PTR_SIZE;
*(asPWORD *)l_sp = asPWORD(l_fp - asBC_SWORDARG0(l_bc));
l_bc++;
break;
// Swap the top 2 pointers on the stack
case asBC_SwapPtr: {
asPWORD p = *(asPWORD *)l_sp;
*(asPWORD *)l_sp = *(asPWORD *)(l_sp + AS_PTR_SIZE);
*(asPWORD *)(l_sp + AS_PTR_SIZE) = p;
l_bc++;
}
break;
// Do a boolean not operation, modifying the value of the variable
case asBC_NOT:
#if AS_SIZEOF_BOOL == 1
{
// Set the value to true if it is equal to 0
// We need to use volatile here to tell the compiler it cannot
// change the order of read and write operations on the pointer.
volatile asBYTE *ptr = (asBYTE *)(l_fp - asBC_SWORDARG0(l_bc));
asBYTE val = (ptr[0] == 0) ? VALUE_OF_BOOLEAN_TRUE : 0;
ptr[0] = val; // The result is stored in the lower byte
ptr[1] = 0; // Make sure the rest of the DWORD is 0
ptr[2] = 0;
ptr[3] = 0;
}
#else
*(l_fp - asBC_SWORDARG0(l_bc)) = (*(l_fp - asBC_SWORDARG0(l_bc)) == 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
#endif
l_bc++;
break;
// Push the dword value of a global variable on the stack
case asBC_PshG4:
--l_sp;
*l_sp = *(asDWORD *)asBC_PTRARG(l_bc);
l_bc += 1 + AS_PTR_SIZE;
break;
// Load the address of a global variable in the register, then
// copy the value of the global variable into a local variable
case asBC_LdGRdR4:
*(void **)&m_regs.valueRegister = (void *)asBC_PTRARG(l_bc);
*(l_fp - asBC_SWORDARG0(l_bc)) = **(asDWORD **)&m_regs.valueRegister;
l_bc += 1 + AS_PTR_SIZE;
break;
//----------------
// path control instructions
// Begin execution of a script function
case asBC_CALL: {
int i = asBC_INTARG(l_bc);
l_bc += 2;
asASSERT(i >= 0);
asASSERT((i & FUNC_IMPORTED) == 0);
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
CallScriptFunction(m_engine->scriptFunctions[i]);
// Extract the values from the context again
l_bc = m_regs.programPointer;
l_sp = m_regs.stackPointer;
l_fp = m_regs.stackFramePointer;
// If status isn't active anymore then we must stop
if (m_status != asEXECUTION_ACTIVE)
return;
}
break;
// Return to the caller, and remove the arguments from the stack
case asBC_RET: {
// Return if this was the first function, or a nested execution
if (m_callStack.GetLength() == 0 ||
m_callStack[m_callStack.GetLength() - CALLSTACK_FRAME_SIZE] == 0) {
m_status = asEXECUTION_FINISHED;
return;
}
asWORD w = asBC_WORDARG0(l_bc);
// Read the old framepointer, functionid, and programCounter from the call stack
PopCallState();
// Extract the values from the context again
l_bc = m_regs.programPointer;
l_sp = m_regs.stackPointer;
l_fp = m_regs.stackFramePointer;
// Pop arguments from stack
l_sp += w;
}
break;
// Jump to a relative position
case asBC_JMP:
l_bc += 2 + asBC_INTARG(l_bc);
break;
//----------------
// Conditional jumps
// Jump to a relative position if the value in the register is 0
case asBC_JZ:
if (*(int *)&m_regs.valueRegister == 0)
l_bc += asBC_INTARG(l_bc) + 2;
else
l_bc += 2;
break;
// Jump to a relative position if the value in the register is not 0
case asBC_JNZ:
if (*(int *)&m_regs.valueRegister != 0)
l_bc += asBC_INTARG(l_bc) + 2;
else
l_bc += 2;
break;
// Jump to a relative position if the value in the register is negative
case asBC_JS:
if (*(int *)&m_regs.valueRegister < 0)
l_bc += asBC_INTARG(l_bc) + 2;
else
l_bc += 2;
break;
// Jump to a relative position if the value in the register it not negative
case asBC_JNS:
if (*(int *)&m_regs.valueRegister >= 0)
l_bc += asBC_INTARG(l_bc) + 2;
else
l_bc += 2;
break;
// Jump to a relative position if the value in the register is greater than 0
case asBC_JP:
if (*(int *)&m_regs.valueRegister > 0)
l_bc += asBC_INTARG(l_bc) + 2;
else
l_bc += 2;
break;
// Jump to a relative position if the value in the register is not greater than 0
case asBC_JNP:
if (*(int *)&m_regs.valueRegister <= 0)
l_bc += asBC_INTARG(l_bc) + 2;
else
l_bc += 2;
break;
//--------------------
// test instructions
// If the value in the register is 0, then set the register to 1, else to 0
case asBC_TZ:
#if AS_SIZEOF_BOOL == 1
{
// Set the value to true if it is equal to 0
// We need to use volatile here to tell the compiler it cannot
// change the order of read and write operations on valueRegister.
volatile int *regPtr = (int *)&m_regs.valueRegister;
volatile asBYTE *regBptr = (asBYTE *)&m_regs.valueRegister;
asBYTE val = (regPtr[0] == 0) ? VALUE_OF_BOOLEAN_TRUE : 0;
regBptr[0] = val; // The result is stored in the lower byte
regBptr[1] = 0; // Make sure the rest of the register is 0
regBptr[2] = 0;
regBptr[3] = 0;
regBptr[4] = 0;
regBptr[5] = 0;
regBptr[6] = 0;
regBptr[7] = 0;
}
#else
*(int *)&m_regs.valueRegister = (*(int *)&m_regs.valueRegister == 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
#endif
l_bc++;
break;
// If the value in the register is not 0, then set the register to 1, else to 0
case asBC_TNZ:
#if AS_SIZEOF_BOOL == 1
{
// Set the value to true if it is not equal to 0
// We need to use volatile here to tell the compiler it cannot
// change the order of read and write operations on valueRegister.
volatile int *regPtr = (int *)&m_regs.valueRegister;
volatile asBYTE *regBptr = (asBYTE *)&m_regs.valueRegister;
asBYTE val = (regPtr[0] == 0) ? 0 : VALUE_OF_BOOLEAN_TRUE;
regBptr[0] = val; // The result is stored in the lower byte
regBptr[1] = 0; // Make sure the rest of the register is 0
regBptr[2] = 0;
regBptr[3] = 0;
regBptr[4] = 0;
regBptr[5] = 0;
regBptr[6] = 0;
regBptr[7] = 0;
}
#else
*(int *)&m_regs.valueRegister = (*(int *)&m_regs.valueRegister == 0 ? 0 : VALUE_OF_BOOLEAN_TRUE);
#endif
l_bc++;
break;
// If the value in the register is negative, then set the register to 1, else to 0
case asBC_TS:
#if AS_SIZEOF_BOOL == 1
{
// Set the value to true if it is less than 0
// We need to use volatile here to tell the compiler it cannot
// change the order of read and write operations on valueRegister.
volatile int *regPtr = (int *)&m_regs.valueRegister;
volatile asBYTE *regBptr = (asBYTE *)&m_regs.valueRegister;
asBYTE val = (regPtr[0] < 0) ? VALUE_OF_BOOLEAN_TRUE : 0;
regBptr[0] = val; // The result is stored in the lower byte
regBptr[1] = 0; // Make sure the rest of the register is 0
regBptr[2] = 0;
regBptr[3] = 0;
regBptr[4] = 0;
regBptr[5] = 0;
regBptr[6] = 0;
regBptr[7] = 0;
}
#else
*(int *)&m_regs.valueRegister = (*(int *)&m_regs.valueRegister < 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
#endif
l_bc++;
break;
// If the value in the register is not negative, then set the register to 1, else to 0
case asBC_TNS:
#if AS_SIZEOF_BOOL == 1
{
// Set the value to true if it is not less than 0
// We need to use volatile here to tell the compiler it cannot
// change the order of read and write operations on valueRegister.
volatile int *regPtr = (int *)&m_regs.valueRegister;
volatile asBYTE *regBptr = (asBYTE *)&m_regs.valueRegister;
asBYTE val = (regPtr[0] >= 0) ? VALUE_OF_BOOLEAN_TRUE : 0;
regBptr[0] = val; // The result is stored in the lower byte
regBptr[1] = 0; // Make sure the rest of the register is 0
regBptr[2] = 0;
regBptr[3] = 0;
regBptr[4] = 0;
regBptr[5] = 0;
regBptr[6] = 0;
regBptr[7] = 0;
}
#else
*(int *)&m_regs.valueRegister = (*(int *)&m_regs.valueRegister < 0 ? 0 : VALUE_OF_BOOLEAN_TRUE);
#endif
l_bc++;
break;
// If the value in the register is greater than 0, then set the register to 1, else to 0
case asBC_TP:
#if AS_SIZEOF_BOOL == 1
{
// Set the value to true if it is greater than 0
// We need to use volatile here to tell the compiler it cannot
// change the order of read and write operations on valueRegister.
volatile int *regPtr = (int *)&m_regs.valueRegister;
volatile asBYTE *regBptr = (asBYTE *)&m_regs.valueRegister;
asBYTE val = (regPtr[0] > 0) ? VALUE_OF_BOOLEAN_TRUE : 0;
regBptr[0] = val; // The result is stored in the lower byte
regBptr[1] = 0; // Make sure the rest of the register is 0
regBptr[2] = 0;
regBptr[3] = 0;
regBptr[4] = 0;
regBptr[5] = 0;
regBptr[6] = 0;
regBptr[7] = 0;
}
#else
*(int *)&m_regs.valueRegister = (*(int *)&m_regs.valueRegister > 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
#endif
l_bc++;
break;
// If the value in the register is not greater than 0, then set the register to 1, else to 0
case asBC_TNP:
#if AS_SIZEOF_BOOL == 1
{
// Set the value to true if it is not greater than 0
// We need to use volatile here to tell the compiler it cannot
// change the order of read and write operations on valueRegister.
volatile int *regPtr = (int *)&m_regs.valueRegister;
volatile asBYTE *regBptr = (asBYTE *)&m_regs.valueRegister;
asBYTE val = (regPtr[0] <= 0) ? VALUE_OF_BOOLEAN_TRUE : 0;
regBptr[0] = val; // The result is stored in the lower byte
regBptr[1] = 0; // Make sure the rest of the register is 0
regBptr[2] = 0;
regBptr[3] = 0;
regBptr[4] = 0;
regBptr[5] = 0;
regBptr[6] = 0;
regBptr[7] = 0;
}
#else
*(int *)&m_regs.valueRegister = (*(int *)&m_regs.valueRegister > 0 ? 0 : VALUE_OF_BOOLEAN_TRUE);
#endif
l_bc++;
break;
//--------------------
// negate value
// Negate the integer value in the variable
case asBC_NEGi:
*(l_fp - asBC_SWORDARG0(l_bc)) = asDWORD(-int(*(l_fp - asBC_SWORDARG0(l_bc))));
l_bc++;
break;
// Negate the float value in the variable
case asBC_NEGf:
*(float *)(l_fp - asBC_SWORDARG0(l_bc)) = -*(float *)(l_fp - asBC_SWORDARG0(l_bc));
l_bc++;
break;
// Negate the double value in the variable
case asBC_NEGd:
*(double *)(l_fp - asBC_SWORDARG0(l_bc)) = -*(double *)(l_fp - asBC_SWORDARG0(l_bc));
l_bc++;
break;
//-------------------------
// Increment value pointed to by address in register
// Increment the short value pointed to by the register
case asBC_INCi16:
(**(short **)&m_regs.valueRegister)++;
l_bc++;
break;
// Increment the byte value pointed to by the register
case asBC_INCi8:
(**(char **)&m_regs.valueRegister)++;
l_bc++;
break;
// Decrement the short value pointed to by the register
case asBC_DECi16:
(**(short **)&m_regs.valueRegister)--;
l_bc++;
break;
// Decrement the byte value pointed to by the register
case asBC_DECi8:
(**(char **)&m_regs.valueRegister)--;
l_bc++;
break;
// Increment the integer value pointed to by the register
case asBC_INCi:
++(**(int **)&m_regs.valueRegister);
l_bc++;
break;
// Decrement the integer value pointed to by the register
case asBC_DECi:
--(**(int **)&m_regs.valueRegister);
l_bc++;
break;
// Increment the float value pointed to by the register
case asBC_INCf:
++(**(float **)&m_regs.valueRegister);
l_bc++;
break;
// Decrement the float value pointed to by the register
case asBC_DECf:
--(**(float **)&m_regs.valueRegister);
l_bc++;
break;
// Increment the double value pointed to by the register
case asBC_INCd:
++(**(double **)&m_regs.valueRegister);
l_bc++;
break;
// Decrement the double value pointed to by the register
case asBC_DECd:
--(**(double **)&m_regs.valueRegister);
l_bc++;
break;
// Increment the local integer variable
case asBC_IncVi:
(*(int *)(l_fp - asBC_SWORDARG0(l_bc)))++;
l_bc++;
break;
// Decrement the local integer variable
case asBC_DecVi:
(*(int *)(l_fp - asBC_SWORDARG0(l_bc)))--;
l_bc++;
break;
//--------------------
// bits instructions
// Do a bitwise not on the value in the variable
case asBC_BNOT:
*(l_fp - asBC_SWORDARG0(l_bc)) = ~*(l_fp - asBC_SWORDARG0(l_bc));
l_bc++;
break;
// Do a bitwise and of two variables and store the result in a third variable
case asBC_BAND:
*(l_fp - asBC_SWORDARG0(l_bc)) = *(l_fp - asBC_SWORDARG1(l_bc)) & *(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
// Do a bitwise or of two variables and store the result in a third variable
case asBC_BOR:
*(l_fp - asBC_SWORDARG0(l_bc)) = *(l_fp - asBC_SWORDARG1(l_bc)) | *(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
// Do a bitwise xor of two variables and store the result in a third variable
case asBC_BXOR:
*(l_fp - asBC_SWORDARG0(l_bc)) = *(l_fp - asBC_SWORDARG1(l_bc)) ^ *(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
// Do a logical shift left of two variables and store the result in a third variable
case asBC_BSLL:
*(l_fp - asBC_SWORDARG0(l_bc)) = *(l_fp - asBC_SWORDARG1(l_bc)) << *(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
// Do a logical shift right of two variables and store the result in a third variable
case asBC_BSRL:
*(l_fp - asBC_SWORDARG0(l_bc)) = *(l_fp - asBC_SWORDARG1(l_bc)) >> *(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
// Do an arithmetic shift right of two variables and store the result in a third variable
case asBC_BSRA:
*(l_fp - asBC_SWORDARG0(l_bc)) = int(*(l_fp - asBC_SWORDARG1(l_bc))) >> *(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
case asBC_COPY: {
void *d = (void *) * (asPWORD *)l_sp;
l_sp += AS_PTR_SIZE;
void *s = (void *) * (asPWORD *)l_sp;
if (s == 0 || d == 0) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_NULL_POINTER_ACCESS);
return;
}
memcpy(d, s, asBC_WORDARG0(l_bc) * 4);
// replace the pointer on the stack with the lvalue
*(asPWORD **)l_sp = (asPWORD *)d;
}
l_bc += 2;
break;
case asBC_PshC8:
l_sp -= 2;
*(asQWORD *)l_sp = asBC_QWORDARG(l_bc);
l_bc += 3;
break;
case asBC_PshVPtr:
l_sp -= AS_PTR_SIZE;
*(asPWORD *)l_sp = *(asPWORD *)(l_fp - asBC_SWORDARG0(l_bc));
l_bc++;
break;
case asBC_RDSPtr: {
// The pointer must not be null
asPWORD a = *(asPWORD *)l_sp;
if (a == 0) {
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
SetInternalException(TXT_NULL_POINTER_ACCESS);
return;
}
// Pop an address from the stack, read a pointer from that address and push it on the stack
*(asPWORD *)l_sp = *(asPWORD *)a;
}
l_bc++;
break;
//----------------------------
// Comparisons
case asBC_CMPd: {
// Do a comparison of the values, rather than a subtraction
// in order to get proper behaviour for infinity values.
double dbl1 = *(double *)(l_fp - asBC_SWORDARG0(l_bc));
double dbl2 = *(double *)(l_fp - asBC_SWORDARG1(l_bc));
if (dbl1 == dbl2) *(int *)&m_regs.valueRegister = 0;
else if (dbl1 < dbl2) *(int *)&m_regs.valueRegister = -1;
else *(int *)&m_regs.valueRegister = 1;
l_bc += 2;
}
break;
case asBC_CMPu: {
asDWORD d1 = *(asDWORD *)(l_fp - asBC_SWORDARG0(l_bc));
asDWORD d2 = *(asDWORD *)(l_fp - asBC_SWORDARG1(l_bc));
if (d1 == d2) *(int *)&m_regs.valueRegister = 0;
else if (d1 < d2) *(int *)&m_regs.valueRegister = -1;
else *(int *)&m_regs.valueRegister = 1;
l_bc += 2;
}
break;
case asBC_CMPf: {
// Do a comparison of the values, rather than a subtraction
// in order to get proper behaviour for infinity values.
float f1 = *(float *)(l_fp - asBC_SWORDARG0(l_bc));
float f2 = *(float *)(l_fp - asBC_SWORDARG1(l_bc));
if (f1 == f2) *(int *)&m_regs.valueRegister = 0;
else if (f1 < f2) *(int *)&m_regs.valueRegister = -1;
else *(int *)&m_regs.valueRegister = 1;
l_bc += 2;
}
break;
case asBC_CMPi: {
int i1 = *(int *)(l_fp - asBC_SWORDARG0(l_bc));
int i2 = *(int *)(l_fp - asBC_SWORDARG1(l_bc));
if (i1 == i2) *(int *)&m_regs.valueRegister = 0;
else if (i1 < i2) *(int *)&m_regs.valueRegister = -1;
else *(int *)&m_regs.valueRegister = 1;
l_bc += 2;
}
break;
//----------------------------
// Comparisons with constant value
case asBC_CMPIi: {
int i1 = *(int *)(l_fp - asBC_SWORDARG0(l_bc));
int i2 = asBC_INTARG(l_bc);
if (i1 == i2) *(int *)&m_regs.valueRegister = 0;
else if (i1 < i2) *(int *)&m_regs.valueRegister = -1;
else *(int *)&m_regs.valueRegister = 1;
l_bc += 2;
}
break;
case asBC_CMPIf: {
// Do a comparison of the values, rather than a subtraction
// in order to get proper behaviour for infinity values.
float f1 = *(float *)(l_fp - asBC_SWORDARG0(l_bc));
float f2 = asBC_FLOATARG(l_bc);
if (f1 == f2) *(int *)&m_regs.valueRegister = 0;
else if (f1 < f2) *(int *)&m_regs.valueRegister = -1;
else *(int *)&m_regs.valueRegister = 1;
l_bc += 2;
}
break;
case asBC_CMPIu: {
asDWORD d1 = *(asDWORD *)(l_fp - asBC_SWORDARG0(l_bc));
asDWORD d2 = asBC_DWORDARG(l_bc);
if (d1 == d2) *(int *)&m_regs.valueRegister = 0;
else if (d1 < d2) *(int *)&m_regs.valueRegister = -1;
else *(int *)&m_regs.valueRegister = 1;
l_bc += 2;
}
break;
case asBC_JMPP:
l_bc += 1 + (*(int *)(l_fp - asBC_SWORDARG0(l_bc))) * 2;
break;
case asBC_PopRPtr:
*(asPWORD *)&m_regs.valueRegister = *(asPWORD *)l_sp;
l_sp += AS_PTR_SIZE;
l_bc++;
break;
case asBC_PshRPtr:
l_sp -= AS_PTR_SIZE;
*(asPWORD *)l_sp = *(asPWORD *)&m_regs.valueRegister;
l_bc++;
break;
case asBC_STR:
// TODO: NEWSTRING: Deprecate this instruction
asASSERT(false);
l_bc++;
break;
case asBC_CALLSYS: {
// Get function ID from the argument
int i = asBC_INTARG(l_bc);
// Need to move the values back to the context as the called functions
// may use the debug interface to inspect the registers
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
l_sp += CallSystemFunction(i, this);
// Update the program position after the call so that line number is correct
l_bc += 2;
if (m_regs.doProcessSuspend) {
// Should the execution be suspended?
if (m_doSuspend) {
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
m_status = asEXECUTION_SUSPENDED;
return;
}
// An exception might have been raised
if (m_status != asEXECUTION_ACTIVE) {
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
return;
}
}
}
break;
case asBC_CALLBND: {
// TODO: Clean-up: This code is very similar to asBC_CallPtr. Create a shared method for them
// Get the function ID from the stack
int i = asBC_INTARG(l_bc);
asASSERT(i >= 0);
asASSERT(i & FUNC_IMPORTED);
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
int funcId = m_engine->importedFunctions[i & ~FUNC_IMPORTED]->boundFunctionId;
if (funcId == -1) {
// Need to update the program pointer for the exception handler
m_regs.programPointer += 2;
// Tell the exception handler to clean up the arguments to this function
m_needToCleanupArgs = true;
SetInternalException(TXT_UNBOUND_FUNCTION);
return;
} else {
asCScriptFunction *func = m_engine->GetScriptFunction(funcId);
if (func->funcType == asFUNC_SCRIPT) {
m_regs.programPointer += 2;
CallScriptFunction(func);
} else if (func->funcType == asFUNC_DELEGATE) {
// Push the object pointer on the stack. There is always a reserved space for this so
// we don't don't need to worry about overflowing the allocated memory buffer
asASSERT(m_regs.stackPointer - AS_PTR_SIZE >= m_stackBlocks[m_stackIndex]);
m_regs.stackPointer -= AS_PTR_SIZE;
*(asPWORD *)m_regs.stackPointer = asPWORD(func->objForDelegate);
// Call the delegated method
if (func->funcForDelegate->funcType == asFUNC_SYSTEM) {
m_regs.stackPointer += CallSystemFunction(func->funcForDelegate->id, this);
// Update program position after the call so the line number
// is correct in case the system function queries it
m_regs.programPointer += 2;
} else {
m_regs.programPointer += 2;
// TODO: run-time optimize: The true method could be figured out when creating the delegate
CallInterfaceMethod(func->funcForDelegate);
}
} else {
asASSERT(func->funcType == asFUNC_SYSTEM);
m_regs.stackPointer += CallSystemFunction(func->id, this);
// Update program position after the call so the line number
// is correct in case the system function queries it
m_regs.programPointer += 2;
}
}
// Extract the values from the context again
l_bc = m_regs.programPointer;
l_sp = m_regs.stackPointer;
l_fp = m_regs.stackFramePointer;
// If status isn't active anymore then we must stop
if (m_status != asEXECUTION_ACTIVE)
return;
}
break;
case asBC_SUSPEND:
if (m_regs.doProcessSuspend) {
if (m_lineCallback) {
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
CallLineCallback();
}
if (m_doSuspend) {
l_bc++;
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
m_status = asEXECUTION_SUSPENDED;
return;
}
}
l_bc++;
break;
case asBC_ALLOC: {
asCObjectType *objType = (asCObjectType *)asBC_PTRARG(l_bc);
int func = asBC_INTARG(l_bc + AS_PTR_SIZE);
if (objType->flags & asOBJ_SCRIPT_OBJECT) {
// Need to move the values back to the context as the construction
// of the script object may reuse the context for nested calls.
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Pre-allocate the memory
asDWORD *mem = (asDWORD *)m_engine->CallAlloc(objType);
// Pre-initialize the memory by calling the constructor for asCScriptObject
ScriptObject_Construct(objType, (asCScriptObject *)mem);
// Call the constructor to initalize the memory
asCScriptFunction *f = m_engine->scriptFunctions[func];
asDWORD **a = (asDWORD **) * (asPWORD *)(m_regs.stackPointer + f->GetSpaceNeededForArguments());
if (a) *a = mem;
// Push the object pointer on the stack
m_regs.stackPointer -= AS_PTR_SIZE;
*(asPWORD *)m_regs.stackPointer = (asPWORD)mem;
m_regs.programPointer += 2 + AS_PTR_SIZE;
CallScriptFunction(f);
// Extract the values from the context again
l_bc = m_regs.programPointer;
l_sp = m_regs.stackPointer;
l_fp = m_regs.stackFramePointer;
// If status isn't active anymore then we must stop
if (m_status != asEXECUTION_ACTIVE)
return;
} else {
// Pre-allocate the memory
asDWORD *mem = (asDWORD *)m_engine->CallAlloc(objType);
if (func) {
// Push the object pointer on the stack (it will be popped by the function)
l_sp -= AS_PTR_SIZE;
*(asPWORD *)l_sp = (asPWORD)mem;
// Need to move the values back to the context as the called functions
// may use the debug interface to inspect the registers
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
l_sp += CallSystemFunction(func, this);
}
// Pop the variable address from the stack
asDWORD **a = (asDWORD **) * (asPWORD *)l_sp;
l_sp += AS_PTR_SIZE;
if (a) *a = mem;
l_bc += 2 + AS_PTR_SIZE;
if (m_regs.doProcessSuspend) {
// Should the execution be suspended?
if (m_doSuspend) {
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
m_status = asEXECUTION_SUSPENDED;
return;
}
// An exception might have been raised
if (m_status != asEXECUTION_ACTIVE) {
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
m_engine->CallFree(mem);
*a = 0;
return;
}
}
}
}
break;
case asBC_FREE: {
// Get the variable that holds the object handle/reference
asPWORD *a = (asPWORD *)asPWORD(l_fp - asBC_SWORDARG0(l_bc));
if (*a) {
asCObjectType *objType = (asCObjectType *)asBC_PTRARG(l_bc);
asSTypeBehaviour *beh = &objType->beh;
// Need to move the values back to the context as the called functions
// may use the debug interface to inspect the registers
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
if (objType->flags & asOBJ_REF) {
asASSERT((objType->flags & asOBJ_NOCOUNT) || beh->release);
if (beh->release)
m_engine->CallObjectMethod((void *)(asPWORD)*a, beh->release);
} else {
if (beh->destruct)
m_engine->CallObjectMethod((void *)(asPWORD)*a, beh->destruct);
else if (objType->flags & asOBJ_LIST_PATTERN)
m_engine->DestroyList((asBYTE *)(asPWORD)*a, objType);
m_engine->CallFree((void *)(asPWORD)*a);
}
// Clear the variable
*a = 0;
}
}
l_bc += 1 + AS_PTR_SIZE;
break;
case asBC_LOADOBJ: {
// Move the object pointer from the object variable into the object register
void **a = (void **)(l_fp - asBC_SWORDARG0(l_bc));
m_regs.objectType = 0;
m_regs.objectRegister = *a;
*a = 0;
}
l_bc++;
break;
case asBC_STOREOBJ:
// Move the object pointer from the object register to the object variable
*(asPWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = asPWORD(m_regs.objectRegister);
m_regs.objectRegister = 0;
l_bc++;
break;
case asBC_GETOBJ: {
// Read variable index from location on stack
asPWORD *a = (asPWORD *)(l_sp + asBC_WORDARG0(l_bc));
asPWORD offset = *a;
// Move pointer from variable to the same location on the stack
asPWORD *v = (asPWORD *)(l_fp - offset);
*a = *v;
// Clear variable
*v = 0;
}
l_bc++;
break;
case asBC_REFCPY: {
asCObjectType *objType = (asCObjectType *)asBC_PTRARG(l_bc);
asSTypeBehaviour *beh = &objType->beh;
// Pop address of destination pointer from the stack
void **d = (void **) * (asPWORD *)l_sp;
l_sp += AS_PTR_SIZE;
// Read wanted pointer from the stack
void *s = (void *) * (asPWORD *)l_sp;
// Need to move the values back to the context as the called functions
// may use the debug interface to inspect the registers
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Update ref counter for object types that require it
if (!(objType->flags & (asOBJ_NOCOUNT | asOBJ_VALUE))) {
// Release previous object held by destination pointer
if (*d != 0 && beh->release)
m_engine->CallObjectMethod(*d, beh->release);
// Increase ref counter of wanted object
if (s != 0 && beh->addref)
m_engine->CallObjectMethod(s, beh->addref);
}
// Set the new object in the destination
*d = s;
}
l_bc += 1 + AS_PTR_SIZE;
break;
case asBC_CHKREF: {
// Verify if the pointer on the stack is null
// This is used when validating a pointer that an operator will work on
asPWORD a = *(asPWORD *)l_sp;
if (a == 0) {
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
SetInternalException(TXT_NULL_POINTER_ACCESS);
return;
}
}
l_bc++;
break;
case asBC_GETOBJREF: {
// Get the location on the stack where the reference will be placed
asPWORD *a = (asPWORD *)(l_sp + asBC_WORDARG0(l_bc));
// Replace the variable index with the object handle held in the variable
*(asPWORD **)a = *(asPWORD **)(l_fp - *a);
}
l_bc++;
break;
case asBC_GETREF: {
// Get the location on the stack where the reference will be placed
asPWORD *a = (asPWORD *)(l_sp + asBC_WORDARG0(l_bc));
// Replace the variable index with the address of the variable
*(asPWORD **)a = (asPWORD *)(l_fp - (int) * a);
}
l_bc++;
break;
case asBC_PshNull:
// Push a null pointer on the stack
l_sp -= AS_PTR_SIZE;
*(asPWORD *)l_sp = 0;
l_bc++;
break;
case asBC_ClrVPtr:
// TODO: runtime optimize: Is this instruction really necessary?
// CallScriptFunction() can clear the null handles upon entry, just as is done for
// all other object variables
// Clear pointer variable
*(asPWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = 0;
l_bc++;
break;
case asBC_OBJTYPE:
// Push the object type on the stack
l_sp -= AS_PTR_SIZE;
*(asPWORD *)l_sp = asBC_PTRARG(l_bc);
l_bc += 1 + AS_PTR_SIZE;
break;
case asBC_TYPEID:
// Equivalent to PshC4, but kept as separate instruction for bytecode serialization
--l_sp;
*l_sp = asBC_DWORDARG(l_bc);
l_bc += 2;
break;
case asBC_SetV4:
*(l_fp - asBC_SWORDARG0(l_bc)) = asBC_DWORDARG(l_bc);
l_bc += 2;
break;
case asBC_SetV8:
*(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = asBC_QWORDARG(l_bc);
l_bc += 3;
break;
case asBC_ADDSi: {
// The pointer must not be null
asPWORD a = *(asPWORD *)l_sp;
if (a == 0) {
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
SetInternalException(TXT_NULL_POINTER_ACCESS);
return;
}
// Add an offset to the pointer
*(asPWORD *)l_sp = a + asBC_SWORDARG0(l_bc);
}
l_bc += 2;
break;
case asBC_CpyVtoV4:
*(l_fp - asBC_SWORDARG0(l_bc)) = *(l_fp - asBC_SWORDARG1(l_bc));
l_bc += 2;
break;
case asBC_CpyVtoV8:
*(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD *)(l_fp - asBC_SWORDARG1(l_bc));
l_bc += 2;
break;
case asBC_CpyVtoR4:
*(asDWORD *)&m_regs.valueRegister = *(asDWORD *)(l_fp - asBC_SWORDARG0(l_bc));
l_bc++;
break;
case asBC_CpyVtoR8:
*(asQWORD *)&m_regs.valueRegister = *(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc));
l_bc++;
break;
case asBC_CpyVtoG4:
*(asDWORD *)asBC_PTRARG(l_bc) = *(asDWORD *)(l_fp - asBC_SWORDARG0(l_bc));
l_bc += 1 + AS_PTR_SIZE;
break;
case asBC_CpyRtoV4:
*(asDWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = *(asDWORD *)&m_regs.valueRegister;
l_bc++;
break;
case asBC_CpyRtoV8:
*(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = m_regs.valueRegister;
l_bc++;
break;
case asBC_CpyGtoV4:
*(asDWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = *(asDWORD *)asBC_PTRARG(l_bc);
l_bc += 1 + AS_PTR_SIZE;
break;
case asBC_WRTV1:
// The pointer in the register points to a byte, and *(l_fp - offset) too
**(asBYTE **)&m_regs.valueRegister = *(asBYTE *)(l_fp - asBC_SWORDARG0(l_bc));
l_bc++;
break;
case asBC_WRTV2:
// The pointer in the register points to a word, and *(l_fp - offset) too
**(asWORD **)&m_regs.valueRegister = *(asWORD *)(l_fp - asBC_SWORDARG0(l_bc));
l_bc++;
break;
case asBC_WRTV4:
**(asDWORD **)&m_regs.valueRegister = *(l_fp - asBC_SWORDARG0(l_bc));
l_bc++;
break;
case asBC_WRTV8:
**(asQWORD **)&m_regs.valueRegister = *(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc));
l_bc++;
break;
case asBC_RDR1: {
// The pointer in the register points to a byte, and *(l_fp - offset) will also point to a byte
asBYTE *bPtr = (asBYTE *)(l_fp - asBC_SWORDARG0(l_bc));
bPtr[0] = **(asBYTE **)&m_regs.valueRegister; // read the byte
bPtr[1] = 0; // 0 the rest of the DWORD
bPtr[2] = 0;
bPtr[3] = 0;
}
l_bc++;
break;
case asBC_RDR2: {
// The pointer in the register points to a word, and *(l_fp - offset) will also point to a word
asWORD *wPtr = (asWORD *)(l_fp - asBC_SWORDARG0(l_bc));
wPtr[0] = **(asWORD **)&m_regs.valueRegister; // read the word
wPtr[1] = 0; // 0 the rest of the DWORD
}
l_bc++;
break;
case asBC_RDR4:
*(asDWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = **(asDWORD **)&m_regs.valueRegister;
l_bc++;
break;
case asBC_RDR8:
*(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = **(asQWORD **)&m_regs.valueRegister;
l_bc++;
break;
case asBC_LDG:
*(asPWORD *)&m_regs.valueRegister = asBC_PTRARG(l_bc);
l_bc += 1 + AS_PTR_SIZE;
break;
case asBC_LDV:
*(asDWORD **)&m_regs.valueRegister = (l_fp - asBC_SWORDARG0(l_bc));
l_bc++;
break;
case asBC_PGA:
l_sp -= AS_PTR_SIZE;
*(asPWORD *)l_sp = asBC_PTRARG(l_bc);
l_bc += 1 + AS_PTR_SIZE;
break;
case asBC_CmpPtr: {
// TODO: runtime optimize: This instruction should really just be an equals, and return true or false.
// The instruction is only used for is and !is tests anyway.
asPWORD p1 = *(asPWORD *)(l_fp - asBC_SWORDARG0(l_bc));
asPWORD p2 = *(asPWORD *)(l_fp - asBC_SWORDARG1(l_bc));
if (p1 == p2) *(int *)&m_regs.valueRegister = 0;
else if (p1 < p2) *(int *)&m_regs.valueRegister = -1;
else *(int *)&m_regs.valueRegister = 1;
l_bc += 2;
}
break;
case asBC_VAR:
l_sp -= AS_PTR_SIZE;
*(asPWORD *)l_sp = (asPWORD)asBC_SWORDARG0(l_bc);
l_bc++;
break;
//----------------------------
// Type conversions
case asBC_iTOf:
*(float *)(l_fp - asBC_SWORDARG0(l_bc)) = float(*(int *)(l_fp - asBC_SWORDARG0(l_bc)));
l_bc++;
break;
case asBC_fTOi:
*(l_fp - asBC_SWORDARG0(l_bc)) = int(*(float *)(l_fp - asBC_SWORDARG0(l_bc)));
l_bc++;
break;
case asBC_uTOf:
*(float *)(l_fp - asBC_SWORDARG0(l_bc)) = float(*(l_fp - asBC_SWORDARG0(l_bc)));
l_bc++;
break;
case asBC_fTOu:
// We must cast to int first, because on some compilers the cast of a negative float value to uint result in 0
*(l_fp - asBC_SWORDARG0(l_bc)) = asUINT(int(*(float *)(l_fp - asBC_SWORDARG0(l_bc))));
l_bc++;
break;
case asBC_sbTOi:
// *(l_fp - offset) points to a char, and will point to an int afterwards
*(l_fp - asBC_SWORDARG0(l_bc)) = *(signed char *)(l_fp - asBC_SWORDARG0(l_bc));
l_bc++;
break;
case asBC_swTOi:
// *(l_fp - offset) points to a short, and will point to an int afterwards
*(l_fp - asBC_SWORDARG0(l_bc)) = *(short *)(l_fp - asBC_SWORDARG0(l_bc));
l_bc++;
break;
case asBC_ubTOi:
// (l_fp - offset) points to a byte, and will point to an int afterwards
*(l_fp - asBC_SWORDARG0(l_bc)) = *(asBYTE *)(l_fp - asBC_SWORDARG0(l_bc));
l_bc++;
break;
case asBC_uwTOi:
// *(l_fp - offset) points to a word, and will point to an int afterwards
*(l_fp - asBC_SWORDARG0(l_bc)) = *(asWORD *)(l_fp - asBC_SWORDARG0(l_bc));
l_bc++;
break;
case asBC_dTOi:
*(l_fp - asBC_SWORDARG0(l_bc)) = int(*(double *)(l_fp - asBC_SWORDARG1(l_bc)));
l_bc += 2;
break;
case asBC_dTOu:
// We must cast to int first, because on some compilers the cast of a negative float value to uint result in 0
*(l_fp - asBC_SWORDARG0(l_bc)) = asUINT(int(*(double *)(l_fp - asBC_SWORDARG1(l_bc))));
l_bc += 2;
break;
case asBC_dTOf:
*(float *)(l_fp - asBC_SWORDARG0(l_bc)) = float(*(double *)(l_fp - asBC_SWORDARG1(l_bc)));
l_bc += 2;
break;
case asBC_iTOd:
*(double *)(l_fp - asBC_SWORDARG0(l_bc)) = double(*(int *)(l_fp - asBC_SWORDARG1(l_bc)));
l_bc += 2;
break;
case asBC_uTOd:
*(double *)(l_fp - asBC_SWORDARG0(l_bc)) = double(*(asUINT *)(l_fp - asBC_SWORDARG1(l_bc)));
l_bc += 2;
break;
case asBC_fTOd:
*(double *)(l_fp - asBC_SWORDARG0(l_bc)) = double(*(float *)(l_fp - asBC_SWORDARG1(l_bc)));
l_bc += 2;
break;
//------------------------------
// Math operations
case asBC_ADDi:
*(int *)(l_fp - asBC_SWORDARG0(l_bc)) = *(int *)(l_fp - asBC_SWORDARG1(l_bc)) + *(int *)(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
case asBC_SUBi:
*(int *)(l_fp - asBC_SWORDARG0(l_bc)) = *(int *)(l_fp - asBC_SWORDARG1(l_bc)) - *(int *)(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
case asBC_MULi:
*(int *)(l_fp - asBC_SWORDARG0(l_bc)) = *(int *)(l_fp - asBC_SWORDARG1(l_bc)) * *(int *)(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
case asBC_DIVi: {
int divider = *(int *)(l_fp - asBC_SWORDARG2(l_bc));
if (divider == 0) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_DIVIDE_BY_ZERO);
return;
} else if (divider == -1) {
// Need to check if the value that is divided is 0x80000000
// as dividing it with -1 will cause an overflow exception
if (*(int *)(l_fp - asBC_SWORDARG1(l_bc)) == int(0x80000000)) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_DIVIDE_OVERFLOW);
return;
}
}
*(int *)(l_fp - asBC_SWORDARG0(l_bc)) = *(int *)(l_fp - asBC_SWORDARG1(l_bc)) / divider;
}
l_bc += 2;
break;
case asBC_MODi: {
int divider = *(int *)(l_fp - asBC_SWORDARG2(l_bc));
if (divider == 0) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_DIVIDE_BY_ZERO);
return;
} else if (divider == -1) {
// Need to check if the value that is divided is 0x80000000
// as dividing it with -1 will cause an overflow exception
if (*(int *)(l_fp - asBC_SWORDARG1(l_bc)) == int(0x80000000)) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_DIVIDE_OVERFLOW);
return;
}
}
*(int *)(l_fp - asBC_SWORDARG0(l_bc)) = *(int *)(l_fp - asBC_SWORDARG1(l_bc)) % divider;
}
l_bc += 2;
break;
case asBC_ADDf:
*(float *)(l_fp - asBC_SWORDARG0(l_bc)) = *(float *)(l_fp - asBC_SWORDARG1(l_bc)) + *(float *)(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
case asBC_SUBf:
*(float *)(l_fp - asBC_SWORDARG0(l_bc)) = *(float *)(l_fp - asBC_SWORDARG1(l_bc)) - *(float *)(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
case asBC_MULf:
*(float *)(l_fp - asBC_SWORDARG0(l_bc)) = *(float *)(l_fp - asBC_SWORDARG1(l_bc)) * *(float *)(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
case asBC_DIVf: {
float divider = *(float *)(l_fp - asBC_SWORDARG2(l_bc));
if (divider == 0) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_DIVIDE_BY_ZERO);
return;
}
*(float *)(l_fp - asBC_SWORDARG0(l_bc)) = *(float *)(l_fp - asBC_SWORDARG1(l_bc)) / divider;
}
l_bc += 2;
break;
case asBC_MODf: {
float divider = *(float *)(l_fp - asBC_SWORDARG2(l_bc));
if (divider == 0) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_DIVIDE_BY_ZERO);
return;
}
*(float *)(l_fp - asBC_SWORDARG0(l_bc)) = fmodf(*(float *)(l_fp - asBC_SWORDARG1(l_bc)), divider);
}
l_bc += 2;
break;
case asBC_ADDd:
*(double *)(l_fp - asBC_SWORDARG0(l_bc)) = *(double *)(l_fp - asBC_SWORDARG1(l_bc)) + *(double *)(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
case asBC_SUBd:
*(double *)(l_fp - asBC_SWORDARG0(l_bc)) = *(double *)(l_fp - asBC_SWORDARG1(l_bc)) - *(double *)(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
case asBC_MULd:
*(double *)(l_fp - asBC_SWORDARG0(l_bc)) = *(double *)(l_fp - asBC_SWORDARG1(l_bc)) * *(double *)(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
case asBC_DIVd: {
double divider = *(double *)(l_fp - asBC_SWORDARG2(l_bc));
if (divider == 0) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_DIVIDE_BY_ZERO);
return;
}
*(double *)(l_fp - asBC_SWORDARG0(l_bc)) = *(double *)(l_fp - asBC_SWORDARG1(l_bc)) / divider;
l_bc += 2;
}
break;
case asBC_MODd: {
double divider = *(double *)(l_fp - asBC_SWORDARG2(l_bc));
if (divider == 0) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_DIVIDE_BY_ZERO);
return;
}
*(double *)(l_fp - asBC_SWORDARG0(l_bc)) = fmod(*(double *)(l_fp - asBC_SWORDARG1(l_bc)), divider);
l_bc += 2;
}
break;
//------------------------------
// Math operations with constant value
case asBC_ADDIi:
*(int *)(l_fp - asBC_SWORDARG0(l_bc)) = *(int *)(l_fp - asBC_SWORDARG1(l_bc)) + asBC_INTARG(l_bc + 1);
l_bc += 3;
break;
case asBC_SUBIi:
*(int *)(l_fp - asBC_SWORDARG0(l_bc)) = *(int *)(l_fp - asBC_SWORDARG1(l_bc)) - asBC_INTARG(l_bc + 1);
l_bc += 3;
break;
case asBC_MULIi:
*(int *)(l_fp - asBC_SWORDARG0(l_bc)) = *(int *)(l_fp - asBC_SWORDARG1(l_bc)) * asBC_INTARG(l_bc + 1);
l_bc += 3;
break;
case asBC_ADDIf:
*(float *)(l_fp - asBC_SWORDARG0(l_bc)) = *(float *)(l_fp - asBC_SWORDARG1(l_bc)) + asBC_FLOATARG(l_bc + 1);
l_bc += 3;
break;
case asBC_SUBIf:
*(float *)(l_fp - asBC_SWORDARG0(l_bc)) = *(float *)(l_fp - asBC_SWORDARG1(l_bc)) - asBC_FLOATARG(l_bc + 1);
l_bc += 3;
break;
case asBC_MULIf:
*(float *)(l_fp - asBC_SWORDARG0(l_bc)) = *(float *)(l_fp - asBC_SWORDARG1(l_bc)) * asBC_FLOATARG(l_bc + 1);
l_bc += 3;
break;
//-----------------------------------
case asBC_SetG4:
*(asDWORD *)asBC_PTRARG(l_bc) = asBC_DWORDARG(l_bc + AS_PTR_SIZE);
l_bc += 2 + AS_PTR_SIZE;
break;
case asBC_ChkRefS: {
// Verify if the pointer on the stack refers to a non-null value
// This is used to validate a reference to a handle
asPWORD *a = (asPWORD *) * (asPWORD *)l_sp;
if (*a == 0) {
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
SetInternalException(TXT_NULL_POINTER_ACCESS);
return;
}
}
l_bc++;
break;
case asBC_ChkNullV: {
// Verify if variable (on the stack) is not null
asDWORD *a = *(asDWORD **)(l_fp - asBC_SWORDARG0(l_bc));
if (a == 0) {
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
SetInternalException(TXT_NULL_POINTER_ACCESS);
return;
}
}
l_bc++;
break;
case asBC_CALLINTF: {
int i = asBC_INTARG(l_bc);
l_bc += 2;
asASSERT(i >= 0);
asASSERT((i & FUNC_IMPORTED) == 0);
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
CallInterfaceMethod(m_engine->GetScriptFunction(i));
// Extract the values from the context again
l_bc = m_regs.programPointer;
l_sp = m_regs.stackPointer;
l_fp = m_regs.stackFramePointer;
// If status isn't active anymore then we must stop
if (m_status != asEXECUTION_ACTIVE)
return;
}
break;
case asBC_iTOb: {
// *(l_fp - offset) points to an int, and will point to a byte afterwards
// We need to use volatile here to tell the compiler not to rearrange
// read and write operations during optimizations.
volatile asDWORD val = *(l_fp - asBC_SWORDARG0(l_bc));
volatile asBYTE *bPtr = (asBYTE *)(l_fp - asBC_SWORDARG0(l_bc));
bPtr[0] = (asBYTE)val; // write the byte
bPtr[1] = 0; // 0 the rest of the DWORD
bPtr[2] = 0;
bPtr[3] = 0;
}
l_bc++;
break;
case asBC_iTOw: {
// *(l_fp - offset) points to an int, and will point to word afterwards
// We need to use volatile here to tell the compiler not to rearrange
// read and write operations during optimizations.
volatile asDWORD val = *(l_fp - asBC_SWORDARG0(l_bc));
volatile asWORD *wPtr = (asWORD *)(l_fp - asBC_SWORDARG0(l_bc));
wPtr[0] = (asWORD)val; // write the word
wPtr[1] = 0; // 0 the rest of the DWORD
}
l_bc++;
break;
case asBC_SetV1:
// TODO: This is exactly the same as SetV4. This is a left over from the time
// when the bytecode instructions were more tightly packed. It can now
// be removed. When removing it, make sure the value is correctly converted
// on big-endian CPUs.
// The byte is already stored correctly in the argument
*(l_fp - asBC_SWORDARG0(l_bc)) = asBC_DWORDARG(l_bc);
l_bc += 2;
break;
case asBC_SetV2:
// TODO: This is exactly the same as SetV4. This is a left over from the time
// when the bytecode instructions were more tightly packed. It can now
// be removed. When removing it, make sure the value is correctly converted
// on big-endian CPUs.
// The word is already stored correctly in the argument
*(l_fp - asBC_SWORDARG0(l_bc)) = asBC_DWORDARG(l_bc);
l_bc += 2;
break;
case asBC_Cast:
// Cast the handle at the top of the stack to the type in the argument
{
asDWORD **a = (asDWORD **) * (asPWORD *)l_sp;
if (a && *a) {
asDWORD typeId = asBC_DWORDARG(l_bc);
asCScriptObject *obj = (asCScriptObject *)* a;
asCObjectType *objType = obj->objType;
asCObjectType *to = m_engine->GetObjectTypeFromTypeId(typeId);
// This instruction can only be used with script classes and interfaces
asASSERT(objType->flags & asOBJ_SCRIPT_OBJECT);
asASSERT(to->flags & asOBJ_SCRIPT_OBJECT);
if (objType->Implements(to) || objType->DerivesFrom(to)) {
m_regs.objectType = 0;
m_regs.objectRegister = obj;
obj->AddRef();
} else {
// The object register should already be null, so there
// is no need to clear it if the cast is unsuccessful
asASSERT(m_regs.objectRegister == 0);
}
}
l_sp += AS_PTR_SIZE;
}
l_bc += 2;
break;
case asBC_i64TOi:
*(l_fp - asBC_SWORDARG0(l_bc)) = int(*(asINT64 *)(l_fp - asBC_SWORDARG1(l_bc)));
l_bc += 2;
break;
case asBC_uTOi64:
*(asINT64 *)(l_fp - asBC_SWORDARG0(l_bc)) = asINT64(*(asUINT *)(l_fp - asBC_SWORDARG1(l_bc)));
l_bc += 2;
break;
case asBC_iTOi64:
*(asINT64 *)(l_fp - asBC_SWORDARG0(l_bc)) = asINT64(*(int *)(l_fp - asBC_SWORDARG1(l_bc)));
l_bc += 2;
break;
case asBC_fTOi64:
*(asINT64 *)(l_fp - asBC_SWORDARG0(l_bc)) = asINT64(*(float *)(l_fp - asBC_SWORDARG1(l_bc)));
l_bc += 2;
break;
case asBC_dTOi64:
*(asINT64 *)(l_fp - asBC_SWORDARG0(l_bc)) = asINT64(*(double *)(l_fp - asBC_SWORDARG0(l_bc)));
l_bc++;
break;
case asBC_fTOu64:
*(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = asQWORD(asINT64(*(float *)(l_fp - asBC_SWORDARG1(l_bc))));
l_bc += 2;
break;
case asBC_dTOu64:
*(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = asQWORD(asINT64(*(double *)(l_fp - asBC_SWORDARG0(l_bc))));
l_bc++;
break;
case asBC_i64TOf:
*(float *)(l_fp - asBC_SWORDARG0(l_bc)) = float(*(asINT64 *)(l_fp - asBC_SWORDARG1(l_bc)));
l_bc += 2;
break;
case asBC_u64TOf:
#if defined(_MSC_VER) && _MSC_VER <= 1200 // MSVC6
{
// MSVC6 doesn't permit UINT64 to double
asINT64 v = *(asINT64 *)(l_fp - asBC_SWORDARG1(l_bc));
if (v < 0)
*(float *)(l_fp - asBC_SWORDARG0(l_bc)) = 18446744073709551615.0f + float(v);
else
*(float *)(l_fp - asBC_SWORDARG0(l_bc)) = float(v);
}
#else
*(float *)(l_fp - asBC_SWORDARG0(l_bc)) = float(*(asQWORD *)(l_fp - asBC_SWORDARG1(l_bc)));
#endif
l_bc += 2;
break;
case asBC_i64TOd:
*(double *)(l_fp - asBC_SWORDARG0(l_bc)) = double(*(asINT64 *)(l_fp - asBC_SWORDARG0(l_bc)));
l_bc++;
break;
case asBC_u64TOd:
#if defined(_MSC_VER) && _MSC_VER <= 1200 // MSVC6
{
// MSVC6 doesn't permit UINT64 to double
asINT64 v = *(asINT64 *)(l_fp - asBC_SWORDARG0(l_bc));
if (v < 0)
*(double *)(l_fp - asBC_SWORDARG0(l_bc)) = 18446744073709551615.0 + double(v);
else
*(double *)(l_fp - asBC_SWORDARG0(l_bc)) = double(v);
}
#else
*(double *)(l_fp - asBC_SWORDARG0(l_bc)) = double(*(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc)));
#endif
l_bc++;
break;
case asBC_NEGi64:
*(asINT64 *)(l_fp - asBC_SWORDARG0(l_bc)) = -*(asINT64 *)(l_fp - asBC_SWORDARG0(l_bc));
l_bc++;
break;
case asBC_INCi64:
++(**(asQWORD **)&m_regs.valueRegister);
l_bc++;
break;
case asBC_DECi64:
--(**(asQWORD **)&m_regs.valueRegister);
l_bc++;
break;
case asBC_BNOT64:
*(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = ~*(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc));
l_bc++;
break;
case asBC_ADDi64:
*(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD *)(l_fp - asBC_SWORDARG1(l_bc)) + *(asQWORD *)(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
case asBC_SUBi64:
*(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD *)(l_fp - asBC_SWORDARG1(l_bc)) - *(asQWORD *)(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
case asBC_MULi64:
*(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD *)(l_fp - asBC_SWORDARG1(l_bc)) * *(asQWORD *)(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
case asBC_DIVi64: {
asINT64 divider = *(asINT64 *)(l_fp - asBC_SWORDARG2(l_bc));
if (divider == 0) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_DIVIDE_BY_ZERO);
return;
} else if (divider == -1) {
// Need to check if the value that is divided is 1<<63
// as dividing it with -1 will cause an overflow exception
if (*(asINT64 *)(l_fp - asBC_SWORDARG1(l_bc)) == (asINT64(1) << 63)) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_DIVIDE_OVERFLOW);
return;
}
}
*(asINT64 *)(l_fp - asBC_SWORDARG0(l_bc)) = *(asINT64 *)(l_fp - asBC_SWORDARG1(l_bc)) / divider;
}
l_bc += 2;
break;
case asBC_MODi64: {
asINT64 divider = *(asINT64 *)(l_fp - asBC_SWORDARG2(l_bc));
if (divider == 0) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_DIVIDE_BY_ZERO);
return;
} else if (divider == -1) {
// Need to check if the value that is divided is 1<<63
// as dividing it with -1 will cause an overflow exception
if (*(asINT64 *)(l_fp - asBC_SWORDARG1(l_bc)) == (asINT64(1) << 63)) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_DIVIDE_OVERFLOW);
return;
}
}
*(asINT64 *)(l_fp - asBC_SWORDARG0(l_bc)) = *(asINT64 *)(l_fp - asBC_SWORDARG1(l_bc)) % divider;
}
l_bc += 2;
break;
case asBC_BAND64:
*(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD *)(l_fp - asBC_SWORDARG1(l_bc)) & *(asQWORD *)(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
case asBC_BOR64:
*(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD *)(l_fp - asBC_SWORDARG1(l_bc)) | *(asQWORD *)(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
case asBC_BXOR64:
*(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD *)(l_fp - asBC_SWORDARG1(l_bc)) ^ *(asQWORD *)(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
case asBC_BSLL64:
*(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD *)(l_fp - asBC_SWORDARG1(l_bc)) << *(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
case asBC_BSRL64:
*(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD *)(l_fp - asBC_SWORDARG1(l_bc)) >> *(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
case asBC_BSRA64:
*(asINT64 *)(l_fp - asBC_SWORDARG0(l_bc)) = *(asINT64 *)(l_fp - asBC_SWORDARG1(l_bc)) >> *(l_fp - asBC_SWORDARG2(l_bc));
l_bc += 2;
break;
case asBC_CMPi64: {
asINT64 i1 = *(asINT64 *)(l_fp - asBC_SWORDARG0(l_bc));
asINT64 i2 = *(asINT64 *)(l_fp - asBC_SWORDARG1(l_bc));
if (i1 == i2) *(int *)&m_regs.valueRegister = 0;
else if (i1 < i2) *(int *)&m_regs.valueRegister = -1;
else *(int *)&m_regs.valueRegister = 1;
l_bc += 2;
}
break;
case asBC_CMPu64: {
asQWORD d1 = *(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc));
asQWORD d2 = *(asQWORD *)(l_fp - asBC_SWORDARG1(l_bc));
if (d1 == d2) *(int *)&m_regs.valueRegister = 0;
else if (d1 < d2) *(int *)&m_regs.valueRegister = -1;
else *(int *)&m_regs.valueRegister = 1;
l_bc += 2;
}
break;
case asBC_ChkNullS: {
// Verify if the pointer on the stack is null
// This is used for example when validating handles passed as function arguments
asPWORD a = *(asPWORD *)(l_sp + asBC_WORDARG0(l_bc));
if (a == 0) {
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
SetInternalException(TXT_NULL_POINTER_ACCESS);
return;
}
}
l_bc++;
break;
case asBC_ClrHi:
#if AS_SIZEOF_BOOL == 1
{
// Clear the upper bytes, so that trash data don't interfere with boolean operations
// We need to use volatile here to tell the compiler it cannot
// change the order of read and write operations on the pointer.
volatile asBYTE *ptr = (asBYTE *)&m_regs.valueRegister;
ptr[1] = 0; // The boolean value is stored in the lower byte, so we clear the rest
ptr[2] = 0;
ptr[3] = 0;
}
#else
// We don't have anything to do here
#endif
l_bc++;
break;
case asBC_JitEntry: {
if (m_currentFunction->scriptData->jitFunction) {
asPWORD jitArg = asBC_PTRARG(l_bc);
if (jitArg) {
// Resume JIT operation
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
(m_currentFunction->scriptData->jitFunction)(&m_regs, jitArg);
l_bc = m_regs.programPointer;
l_sp = m_regs.stackPointer;
l_fp = m_regs.stackFramePointer;
// If status isn't active anymore then we must stop
if (m_status != asEXECUTION_ACTIVE)
return;
break;
}
}
// Not a JIT resume point, treat as nop
l_bc += 1 + AS_PTR_SIZE;
}
break;
case asBC_CallPtr: {
// Get the function pointer from the local variable
asCScriptFunction *func = *(asCScriptFunction **)(l_fp - asBC_SWORDARG0(l_bc));
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
if (func == 0) {
// Need to update the program pointer anyway for the exception handler
m_regs.programPointer++;
// Tell the exception handler to clean up the arguments to this method
m_needToCleanupArgs = true;
// TODO: funcdef: Should we have a different exception string?
SetInternalException(TXT_UNBOUND_FUNCTION);
return;
} else {
if (func->funcType == asFUNC_SCRIPT) {
m_regs.programPointer++;
CallScriptFunction(func);
} else if (func->funcType == asFUNC_DELEGATE) {
// Push the object pointer on the stack. There is always a reserved space for this so
// we don't don't need to worry about overflowing the allocated memory buffer
asASSERT(m_regs.stackPointer - AS_PTR_SIZE >= m_stackBlocks[m_stackIndex]);
m_regs.stackPointer -= AS_PTR_SIZE;
*(asPWORD *)m_regs.stackPointer = asPWORD(func->objForDelegate);
// Call the delegated method
if (func->funcForDelegate->funcType == asFUNC_SYSTEM) {
m_regs.stackPointer += CallSystemFunction(func->funcForDelegate->id, this);
// Update program position after the call so the line number
// is correct in case the system function queries it
m_regs.programPointer++;
} else {
m_regs.programPointer++;
// TODO: run-time optimize: The true method could be figured out when creating the delegate
CallInterfaceMethod(func->funcForDelegate);
}
} else if (func->funcType == asFUNC_SYSTEM) {
m_regs.stackPointer += CallSystemFunction(func->id, this);
// Update program position after the call so the line number
// is correct in case the system function queries it
m_regs.programPointer++;
} else if (func->funcType == asFUNC_IMPORTED) {
m_regs.programPointer++;
int funcId = m_engine->importedFunctions[func->id & ~FUNC_IMPORTED]->boundFunctionId;
if (funcId > 0)
CallScriptFunction(m_engine->scriptFunctions[funcId]);
else {
// Tell the exception handler to clean up the arguments to this method
m_needToCleanupArgs = true;
SetInternalException(TXT_UNBOUND_FUNCTION);
}
} else {
// Should not get here
asASSERT(false);
}
}
// Extract the values from the context again
l_bc = m_regs.programPointer;
l_sp = m_regs.stackPointer;
l_fp = m_regs.stackFramePointer;
// If status isn't active anymore then we must stop
if (m_status != asEXECUTION_ACTIVE)
return;
}
break;
case asBC_FuncPtr:
// Push the function pointer on the stack. The pointer is in the argument
l_sp -= AS_PTR_SIZE;
*(asPWORD *)l_sp = asBC_PTRARG(l_bc);
l_bc += 1 + AS_PTR_SIZE;
break;
case asBC_LoadThisR: {
// PshVPtr 0
asPWORD tmp = *(asPWORD *)l_fp;
// Make sure the pointer is not null
if (tmp == 0) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_NULL_POINTER_ACCESS);
return;
}
// ADDSi
tmp = tmp + asBC_SWORDARG0(l_bc);
// PopRPtr
*(asPWORD *)&m_regs.valueRegister = tmp;
l_bc += 2;
}
break;
// Push the qword value of a variable on the stack
case asBC_PshV8:
l_sp -= 2;
*(asQWORD *)l_sp = *(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc));
l_bc++;
break;
case asBC_DIVu: {
asUINT divider = *(asUINT *)(l_fp - asBC_SWORDARG2(l_bc));
if (divider == 0) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_DIVIDE_BY_ZERO);
return;
}
*(asUINT *)(l_fp - asBC_SWORDARG0(l_bc)) = *(asUINT *)(l_fp - asBC_SWORDARG1(l_bc)) / divider;
}
l_bc += 2;
break;
case asBC_MODu: {
asUINT divider = *(asUINT *)(l_fp - asBC_SWORDARG2(l_bc));
if (divider == 0) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_DIVIDE_BY_ZERO);
return;
}
*(asUINT *)(l_fp - asBC_SWORDARG0(l_bc)) = *(asUINT *)(l_fp - asBC_SWORDARG1(l_bc)) % divider;
}
l_bc += 2;
break;
case asBC_DIVu64: {
asQWORD divider = *(asQWORD *)(l_fp - asBC_SWORDARG2(l_bc));
if (divider == 0) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_DIVIDE_BY_ZERO);
return;
}
*(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD *)(l_fp - asBC_SWORDARG1(l_bc)) / divider;
}
l_bc += 2;
break;
case asBC_MODu64: {
asQWORD divider = *(asQWORD *)(l_fp - asBC_SWORDARG2(l_bc));
if (divider == 0) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_DIVIDE_BY_ZERO);
return;
}
*(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = *(asQWORD *)(l_fp - asBC_SWORDARG1(l_bc)) % divider;
}
l_bc += 2;
break;
case asBC_LoadRObjR: {
// PshVPtr x
asPWORD tmp = *(asPWORD *)(l_fp - asBC_SWORDARG0(l_bc));
// Make sure the pointer is not null
if (tmp == 0) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_NULL_POINTER_ACCESS);
return;
}
// ADDSi y
tmp = tmp + asBC_SWORDARG1(l_bc);
// PopRPtr
*(asPWORD *)&m_regs.valueRegister = tmp;
l_bc += 3;
}
break;
case asBC_LoadVObjR: {
// PSF x
asPWORD tmp = (asPWORD)(l_fp - asBC_SWORDARG0(l_bc));
// ADDSi y
tmp = tmp + asBC_SWORDARG1(l_bc);
// PopRPtr
*(asPWORD *)&m_regs.valueRegister = tmp;
l_bc += 3;
}
break;
case asBC_RefCpyV:
// Same as PSF v, REFCPY
{
asCObjectType *objType = (asCObjectType *)asBC_PTRARG(l_bc);
asSTypeBehaviour *beh = &objType->beh;
// Determine destination from argument
void **d = (void **)asPWORD(l_fp - asBC_SWORDARG0(l_bc));
// Read wanted pointer from the stack
void *s = (void *) * (asPWORD *)l_sp;
// Need to move the values back to the context as the called functions
// may use the debug interface to inspect the registers
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Update ref counter for object types that require it
if (!(objType->flags & (asOBJ_NOCOUNT | asOBJ_VALUE))) {
// Release previous object held by destination pointer
if (*d != 0 && beh->release)
m_engine->CallObjectMethod(*d, beh->release);
// Increase ref counter of wanted object
if (s != 0 && beh->addref)
m_engine->CallObjectMethod(s, beh->addref);
}
// Set the new object in the destination
*d = s;
}
l_bc += 1 + AS_PTR_SIZE;
break;
case asBC_JLowZ:
if (*(asBYTE *)&m_regs.valueRegister == 0)
l_bc += asBC_INTARG(l_bc) + 2;
else
l_bc += 2;
break;
case asBC_JLowNZ:
if (*(asBYTE *)&m_regs.valueRegister != 0)
l_bc += asBC_INTARG(l_bc) + 2;
else
l_bc += 2;
break;
case asBC_AllocMem:
// Allocate a buffer and store the pointer in the local variable
{
// TODO: runtime optimize: As the list buffers are going to be short lived, it may be interesting
// to use a memory pool to avoid reallocating the memory all the time
asUINT size = asBC_DWORDARG(l_bc);
asBYTE **var = (asBYTE **)(l_fp - asBC_SWORDARG0(l_bc));
#ifndef WIP_16BYTE_ALIGN
*var = asNEWARRAY(asBYTE, size);
#else
*var = asNEWARRAYALIGNED(asBYTE, size, MAX_TYPE_ALIGNMENT);
#endif
// Clear the buffer for the pointers that will be placed in it
memset(*var, 0, size);
}
l_bc += 2;
break;
case asBC_SetListSize: {
// Set the size element in the buffer
asBYTE *var = *(asBYTE **)(l_fp - asBC_SWORDARG0(l_bc));
asUINT off = asBC_DWORDARG(l_bc);
asUINT size = asBC_DWORDARG(l_bc + 1);
asASSERT(var);
*(asUINT *)(var + off) = size;
}
l_bc += 3;
break;
case asBC_PshListElmnt: {
// Push the pointer to the list element on the stack
// In essence it does the same as PSF, RDSPtr, ADDSi
asBYTE *var = *(asBYTE **)(l_fp - asBC_SWORDARG0(l_bc));
asUINT off = asBC_DWORDARG(l_bc);
asASSERT(var);
l_sp -= AS_PTR_SIZE;
*(asPWORD *)l_sp = asPWORD(var + off);
}
l_bc += 2;
break;
case asBC_SetListType: {
// Set the type id in the buffer
asBYTE *var = *(asBYTE **)(l_fp - asBC_SWORDARG0(l_bc));
asUINT off = asBC_DWORDARG(l_bc);
asUINT type = asBC_DWORDARG(l_bc + 1);
asASSERT(var);
*(asUINT *)(var + off) = type;
}
l_bc += 3;
break;
//------------------------------
// Exponent operations
case asBC_POWi: {
bool isOverflow;
*(int *)(l_fp - asBC_SWORDARG0(l_bc)) = as_powi(*(int *)(l_fp - asBC_SWORDARG1(l_bc)), *(int *)(l_fp - asBC_SWORDARG2(l_bc)), isOverflow);
if (isOverflow) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_POW_OVERFLOW);
return;
}
}
l_bc += 2;
break;
case asBC_POWu: {
bool isOverflow;
*(asDWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = as_powu(*(asDWORD *)(l_fp - asBC_SWORDARG1(l_bc)), *(asDWORD *)(l_fp - asBC_SWORDARG2(l_bc)), isOverflow);
if (isOverflow) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_POW_OVERFLOW);
return;
}
}
l_bc += 2;
break;
case asBC_POWf: {
float r = powf(*(float *)(l_fp - asBC_SWORDARG1(l_bc)), *(float *)(l_fp - asBC_SWORDARG2(l_bc)));
*(float *)(l_fp - asBC_SWORDARG0(l_bc)) = r;
if (r == float(HUGE_VAL)) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_POW_OVERFLOW);
return;
}
}
l_bc += 2;
break;
case asBC_POWd: {
double r = pow(*(double *)(l_fp - asBC_SWORDARG1(l_bc)), *(double *)(l_fp - asBC_SWORDARG2(l_bc)));
*(double *)(l_fp - asBC_SWORDARG0(l_bc)) = r;
if (r == HUGE_VAL) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_POW_OVERFLOW);
return;
}
}
l_bc += 2;
break;
case asBC_POWdi: {
double r = pow(*(double *)(l_fp - asBC_SWORDARG1(l_bc)), *(int *)(l_fp - asBC_SWORDARG2(l_bc)));
*(double *)(l_fp - asBC_SWORDARG0(l_bc)) = r;
if (r == HUGE_VAL) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_POW_OVERFLOW);
return;
}
l_bc += 2;
}
break;
case asBC_POWi64: {
bool isOverflow;
*(asINT64 *)(l_fp - asBC_SWORDARG0(l_bc)) = as_powi64(*(asINT64 *)(l_fp - asBC_SWORDARG1(l_bc)), *(asINT64 *)(l_fp - asBC_SWORDARG2(l_bc)), isOverflow);
if (isOverflow) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_POW_OVERFLOW);
return;
}
}
l_bc += 2;
break;
case asBC_POWu64: {
bool isOverflow;
*(asQWORD *)(l_fp - asBC_SWORDARG0(l_bc)) = as_powu64(*(asQWORD *)(l_fp - asBC_SWORDARG1(l_bc)), *(asQWORD *)(l_fp - asBC_SWORDARG2(l_bc)), isOverflow);
if (isOverflow) {
// Need to move the values back to the context
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Raise exception
SetInternalException(TXT_POW_OVERFLOW);
return;
}
}
l_bc += 2;
break;
case asBC_Thiscall1:
// This instruction is a faster version of asBC_CALLSYS. It is faster because
// it has much less runtime overhead with determining the calling convention
// and no dynamic code for loading the parameters. The instruction can only
// be used to call functions with the following signatures:
//
// type &obj::func(int)
// type &obj::func(uint)
// void obj::func(int)
// void obj::func(uint)
{
// Get function ID from the argument
int i = asBC_INTARG(l_bc);
// Need to move the values back to the context as the called functions
// may use the debug interface to inspect the registers
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
// Pop the thispointer from the stack
void *obj = *(void **)l_sp;
if (obj == 0)
SetInternalException(TXT_NULL_POINTER_ACCESS);
else {
// Only update the stack pointer if all is OK so the
// exception handler can properly clean up the stack
l_sp += AS_PTR_SIZE;
// Pop the int arg from the stack
int arg = *(int *)l_sp;
l_sp++;
// Call the method
m_callingSystemFunction = m_engine->scriptFunctions[i];
void *ptr = 0;
#ifdef AS_NO_EXCEPTIONS
ptr = m_engine->CallObjectMethodRetPtr(obj, arg, m_callingSystemFunction);
#else
// This try/catch block is to catch potential exception that may
// be thrown by the registered function.
try {
ptr = m_engine->CallObjectMethodRetPtr(obj, arg, m_callingSystemFunction);
} catch (...) {
// Convert the exception to a script exception so the VM can
// properly report the error to the application and then clean up
HandleAppException();
}
#endif
m_callingSystemFunction = 0;
*(asPWORD *)&m_regs.valueRegister = (asPWORD)ptr;
}
// Update the program position after the call so that line number is correct
l_bc += 2;
if (m_regs.doProcessSuspend) {
// Should the execution be suspended?
if (m_doSuspend) {
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
m_status = asEXECUTION_SUSPENDED;
return;
}
// An exception might have been raised
if (m_status != asEXECUTION_ACTIVE) {
m_regs.programPointer = l_bc;
m_regs.stackPointer = l_sp;
m_regs.stackFramePointer = l_fp;
return;
}
}
}
break;
// Don't let the optimizer optimize for size,
// since it requires extra conditions and jumps
case 201:
l_bc = (asDWORD *)201;
break;
case 202:
l_bc = (asDWORD *)202;
break;
case 203:
l_bc = (asDWORD *)203;
break;
case 204:
l_bc = (asDWORD *)204;
break;
case 205:
l_bc = (asDWORD *)205;
break;
case 206:
l_bc = (asDWORD *)206;
break;
case 207:
l_bc = (asDWORD *)207;
break;
case 208:
l_bc = (asDWORD *)208;
break;
case 209:
l_bc = (asDWORD *)209;
break;
case 210:
l_bc = (asDWORD *)210;
break;
case 211:
l_bc = (asDWORD *)211;
break;
case 212:
l_bc = (asDWORD *)212;
break;
case 213:
l_bc = (asDWORD *)213;
break;
case 214:
l_bc = (asDWORD *)214;
break;
case 215:
l_bc = (asDWORD *)215;
break;
case 216:
l_bc = (asDWORD *)216;
break;
case 217:
l_bc = (asDWORD *)217;
break;
case 218:
l_bc = (asDWORD *)218;
break;
case 219:
l_bc = (asDWORD *)219;
break;
case 220:
l_bc = (asDWORD *)220;
break;
case 221:
l_bc = (asDWORD *)221;
break;
case 222:
l_bc = (asDWORD *)222;
break;
case 223:
l_bc = (asDWORD *)223;
break;
case 224:
l_bc = (asDWORD *)224;
break;
case 225:
l_bc = (asDWORD *)225;
break;
case 226:
l_bc = (asDWORD *)226;
break;
case 227:
l_bc = (asDWORD *)227;
break;
case 228:
l_bc = (asDWORD *)228;
break;
case 229:
l_bc = (asDWORD *)229;
break;
case 230:
l_bc = (asDWORD *)230;
break;
case 231:
l_bc = (asDWORD *)231;
break;
case 232:
l_bc = (asDWORD *)232;
break;
case 233:
l_bc = (asDWORD *)233;
break;
case 234:
l_bc = (asDWORD *)234;
break;
case 235:
l_bc = (asDWORD *)235;
break;
case 236:
l_bc = (asDWORD *)236;
break;
case 237:
l_bc = (asDWORD *)237;
break;
case 238:
l_bc = (asDWORD *)238;
break;
case 239:
l_bc = (asDWORD *)239;
break;
case 240:
l_bc = (asDWORD *)240;
break;
case 241:
l_bc = (asDWORD *)241;
break;
case 242:
l_bc = (asDWORD *)242;
break;
case 243:
l_bc = (asDWORD *)243;
break;
case 244:
l_bc = (asDWORD *)244;
break;
case 245:
l_bc = (asDWORD *)245;
break;
case 246:
l_bc = (asDWORD *)246;
break;
case 247:
l_bc = (asDWORD *)247;
break;
case 248:
l_bc = (asDWORD *)248;
break;
case 249:
l_bc = (asDWORD *)249;
break;
case 250:
l_bc = (asDWORD *)250;
break;
case 251:
l_bc = (asDWORD *)251;
break;
case 252:
l_bc = (asDWORD *)252;
break;
case 253:
l_bc = (asDWORD *)253;
break;
case 254:
l_bc = (asDWORD *)254;
break;
case 255:
l_bc = (asDWORD *)255;
break;
#ifdef AS_DEBUG
default:
asASSERT(false);
SetInternalException(TXT_UNRECOGNIZED_BYTE_CODE);
#endif
#if defined(_MSC_VER) && !defined(AS_DEBUG)
default:
// This Microsoft specific code allows the
// compiler to optimize the switch case as
// it will know that the code will never
// reach this point
__assume(0);
#endif
}
#ifdef AS_DEBUG
asDWORD instr = *(asBYTE *)old;
if (instr != asBC_JMP && instr != asBC_JMPP && (instr < asBC_JZ || instr > asBC_JNP) && instr != asBC_JLowZ && instr != asBC_JLowNZ &&
instr != asBC_CALL && instr != asBC_CALLBND && instr != asBC_CALLINTF && instr != asBC_RET && instr != asBC_ALLOC && instr != asBC_CallPtr &&
instr != asBC_JitEntry) {
asASSERT((l_bc - old) == asBCTypeSize[asBCInfo[instr].type]);
}
#endif
}
}
// interface
int asCContext::SetException(const char *descr, bool allowCatch) {
// Only allow this if we're executing a CALL byte code
if (m_callingSystemFunction == 0) return asERROR;
SetInternalException(descr, allowCatch);
return 0;
}
void asCContext::SetInternalException(const char *descr, bool allowCatch) {
if (m_inExceptionHandler) {
asASSERT(false); // Shouldn't happen
return; // but if it does, at least this will not crash the application
}
m_status = asEXECUTION_EXCEPTION;
m_regs.doProcessSuspend = true;
m_exceptionString = descr;
m_exceptionFunction = m_currentFunction->id;
if (m_currentFunction->scriptData) {
m_exceptionLine = m_currentFunction->GetLineNumber(int(m_regs.programPointer - m_currentFunction->scriptData->byteCode.AddressOf()), &m_exceptionSectionIdx);
m_exceptionColumn = m_exceptionLine >> 20;
m_exceptionLine &= 0xFFFFF;
} else {
m_exceptionSectionIdx = 0;
m_exceptionLine = 0;
m_exceptionColumn = 0;
}
// Recursively search the callstack for try/catch blocks
m_exceptionWillBeCaught = allowCatch && FindExceptionTryCatch();
if (m_exceptionCallback)
CallExceptionCallback();
}
// interface
bool asCContext::WillExceptionBeCaught() {
return m_exceptionWillBeCaught;
}
void asCContext::CleanReturnObject() {
if (m_initialFunction && m_initialFunction->DoesReturnOnStack() && m_status == asEXECUTION_FINISHED) {
// If function returns on stack we need to call the destructor on the returned object
if (CastToObjectType(m_initialFunction->returnType.GetTypeInfo())->beh.destruct)
m_engine->CallObjectMethod(GetReturnObject(), CastToObjectType(m_initialFunction->returnType.GetTypeInfo())->beh.destruct);
return;
}
if (m_regs.objectRegister == 0) return;
asASSERT(m_regs.objectType != 0);
if (m_regs.objectType) {
if (m_regs.objectType->GetFlags() & asOBJ_FUNCDEF) {
// Release the function pointer
reinterpret_cast<asIScriptFunction *>(m_regs.objectRegister)->Release();
m_regs.objectRegister = 0;
} else {
// Call the destructor on the object
asSTypeBehaviour *beh = &(CastToObjectType(reinterpret_cast<asCTypeInfo *>(m_regs.objectType))->beh);
if (m_regs.objectType->GetFlags() & asOBJ_REF) {
asASSERT(beh->release || (m_regs.objectType->GetFlags() & asOBJ_NOCOUNT));
if (beh->release)
m_engine->CallObjectMethod(m_regs.objectRegister, beh->release);
m_regs.objectRegister = 0;
} else {
if (beh->destruct)
m_engine->CallObjectMethod(m_regs.objectRegister, beh->destruct);
// Free the memory
m_engine->CallFree(m_regs.objectRegister);
m_regs.objectRegister = 0;
}
}
}
}
void asCContext::CleanStack(bool catchException) {
m_inExceptionHandler = true;
// Run the clean up code and move to catch block
bool caught = CleanStackFrame(catchException);
if (!caught) {
// Set the status to exception so that the stack unwind is done correctly.
// This shouldn't be done for the current function, which is why we only
// do this after the first CleanStackFrame() is done.
m_status = asEXECUTION_EXCEPTION;
while (!caught && m_callStack.GetLength() > 0) {
// Only clean up until the top most marker for a nested call
asPWORD *s = m_callStack.AddressOf() + m_callStack.GetLength() - CALLSTACK_FRAME_SIZE;
if (s[0] == 0)
break;
PopCallState();
caught = CleanStackFrame(catchException);
}
}
// If the exception was caught, then move the status to
// active as is now possible to resume the execution
if (caught)
m_status = asEXECUTION_ACTIVE;
m_inExceptionHandler = false;
}
// Interface
bool asCContext::IsVarInScope(asUINT varIndex, asUINT stackLevel) {
// Don't return anything if there is no bytecode, e.g. before calling Execute()
if (m_regs.programPointer == 0) return false;
if (stackLevel >= GetCallstackSize()) return false;
asCScriptFunction *func;
asUINT pos;
if (stackLevel == 0) {
func = m_currentFunction;
if (func->scriptData == 0) return false;
pos = asUINT(m_regs.programPointer - func->scriptData->byteCode.AddressOf());
} else {
asPWORD *s = m_callStack.AddressOf() + (GetCallstackSize() - stackLevel - 1) * CALLSTACK_FRAME_SIZE;
func = (asCScriptFunction *)s[1];
if (func->scriptData == 0) return false;
pos = asUINT((asDWORD *)s[2] - func->scriptData->byteCode.AddressOf());
}
// First determine if the program position is after the variable declaration
if (func->scriptData->variables.GetLength() <= varIndex) return false;
if (func->scriptData->variables[varIndex]->declaredAtProgramPos > pos) return false;
asUINT declaredAt = func->scriptData->variables[varIndex]->declaredAtProgramPos;
// If the program position is after the variable declaration it is necessary
// determine if the program position is still inside the statement block where
// the variable was delcared.
for (int n = 0; n < (int)func->scriptData->objVariableInfo.GetLength(); n++) {
if (func->scriptData->objVariableInfo[n].programPos >= declaredAt) {
// If the current block ends between the declaredAt and current
// program position, then we know the variable is no longer visible
int level = 0;
for (; n < (int)func->scriptData->objVariableInfo.GetLength(); n++) {
if (func->scriptData->objVariableInfo[n].programPos > pos)
break;
if (func->scriptData->objVariableInfo[n].option == asBLOCK_BEGIN) level++;
if (func->scriptData->objVariableInfo[n].option == asBLOCK_END && --level < 0)
return false;
}
break;
}
}
// Variable is visible
return true;
}
// Internal
void asCContext::DetermineLiveObjects(asCArray<int> &liveObjects, asUINT stackLevel) {
asASSERT(stackLevel < GetCallstackSize());
asCScriptFunction *func;
asUINT pos;
if (stackLevel == 0) {
func = m_currentFunction;
if (func->scriptData == 0)
return;
pos = asUINT(m_regs.programPointer - func->scriptData->byteCode.AddressOf());
if (m_status == asEXECUTION_EXCEPTION) {
// Don't consider the last instruction as executed, as it failed with an exception
// It's not actually necessary to decrease the exact size of the instruction. Just
// before the current position is enough to disconsider it.
pos--;
}
} else {
asPWORD *s = m_callStack.AddressOf() + (GetCallstackSize() - stackLevel - 1) * CALLSTACK_FRAME_SIZE;
func = (asCScriptFunction *)s[1];
if (func->scriptData == 0)
return;
pos = asUINT((asDWORD *)s[2] - func->scriptData->byteCode.AddressOf());
// Don't consider the last instruction as executed, as the function that was called by it
// is still being executed. If we consider it as executed already, then a value object
// returned by value would be considered alive, which it is not.
pos--;
}
// Determine which object variables that are really live ones
liveObjects.SetLength(func->scriptData->objVariablePos.GetLength());
memset(liveObjects.AddressOf(), 0, sizeof(int)*liveObjects.GetLength());
for (int n = 0; n < (int)func->scriptData->objVariableInfo.GetLength(); n++) {
// Find the first variable info with a larger position than the current
// As the variable info are always placed on the instruction right after the
// one that initialized or freed the object, the current position needs to be
// considered as valid.
if (func->scriptData->objVariableInfo[n].programPos > pos) {
// We've determined how far the execution ran, now determine which variables are alive
for (--n; n >= 0; n--) {
switch (func->scriptData->objVariableInfo[n].option) {
case asOBJ_UNINIT: { // Object was destroyed
// TODO: optimize: This should have been done by the compiler already
// Which variable is this?
asUINT var = 0;
for (asUINT v = 0; v < func->scriptData->objVariablePos.GetLength(); v++)
if (func->scriptData->objVariablePos[v] == func->scriptData->objVariableInfo[n].variableOffset) {
var = v;
break;
}
liveObjects[var] -= 1;
}
break;
case asOBJ_INIT: { // Object was created
// Which variable is this?
asUINT var = 0;
for (asUINT v = 0; v < func->scriptData->objVariablePos.GetLength(); v++)
if (func->scriptData->objVariablePos[v] == func->scriptData->objVariableInfo[n].variableOffset) {
var = v;
break;
}
liveObjects[var] += 1;
}
break;
case asBLOCK_BEGIN: // Start block
// We should ignore start blocks, since it just means the
// program was within the block when the exception occurred
break;
case asBLOCK_END: // End block
// We need to skip the entire block, as the objects created
// and destroyed inside this block are already out of scope
{
int nested = 1;
while (nested > 0) {
int option = func->scriptData->objVariableInfo[--n].option;
if (option == 3)
nested++;
if (option == 2)
nested--;
}
}
break;
case asOBJ_VARDECL: // A variable was declared
// We don't really care about the variable declarations at this moment
break;
}
}
// We're done with the investigation
break;
}
}
}
void asCContext::CleanArgsOnStack() {
if (!m_needToCleanupArgs)
return;
asASSERT(m_currentFunction->scriptData);
// Find the instruction just before the current program pointer
asDWORD *instr = m_currentFunction->scriptData->byteCode.AddressOf();
asDWORD *prevInstr = 0;
while (instr < m_regs.programPointer) {
prevInstr = instr;
instr += asBCTypeSize[asBCInfo[*(asBYTE *)(instr)].type];
}
// Determine what function was being called
asCScriptFunction *func = 0;
asBYTE bc = *(asBYTE *)prevInstr;
if (bc == asBC_CALL || bc == asBC_CALLSYS || bc == asBC_CALLINTF) {
int funcId = asBC_INTARG(prevInstr);
func = m_engine->scriptFunctions[funcId];
} else if (bc == asBC_CALLBND) {
int funcId = asBC_INTARG(prevInstr);
func = m_engine->importedFunctions[funcId & ~FUNC_IMPORTED]->importedFunctionSignature;
} else if (bc == asBC_CallPtr) {
asUINT v;
int var = asBC_SWORDARG0(prevInstr);
// Find the funcdef from the local variable
for (v = 0; v < m_currentFunction->scriptData->objVariablePos.GetLength(); v++)
if (m_currentFunction->scriptData->objVariablePos[v] == var) {
func = CastToFuncdefType(m_currentFunction->scriptData->objVariableTypes[v])->funcdef;
break;
}
if (func == 0) {
// Look in parameters
int paramPos = 0;
if (m_currentFunction->objectType)
paramPos -= AS_PTR_SIZE;
if (m_currentFunction->DoesReturnOnStack())
paramPos -= AS_PTR_SIZE;
for (v = 0; v < m_currentFunction->parameterTypes.GetLength(); v++) {
if (var == paramPos) {
if (m_currentFunction->parameterTypes[v].IsFuncdef())
func = CastToFuncdefType(m_currentFunction->parameterTypes[v].GetTypeInfo())->funcdef;
break;
}
paramPos -= m_currentFunction->parameterTypes[v].GetSizeOnStackDWords();
}
}
} else
asASSERT(false);
asASSERT(func);
// Clean parameters
int offset = 0;
if (func->objectType)
offset += AS_PTR_SIZE;
if (func->DoesReturnOnStack())
offset += AS_PTR_SIZE;
for (asUINT n = 0; n < func->parameterTypes.GetLength(); n++) {
if ((func->parameterTypes[n].IsObject() || func->parameterTypes[n].IsFuncdef()) && !func->parameterTypes[n].IsReference()) {
// TODO: cleanup: This logic is repeated twice in CleanStackFrame too. Should create a common function to share the code
if (*(asPWORD *)&m_regs.stackPointer[offset]) {
// Call the object's destructor
asSTypeBehaviour *beh = func->parameterTypes[n].GetBehaviour();
if (func->parameterTypes[n].GetTypeInfo()->flags & asOBJ_FUNCDEF) {
(*(asCScriptFunction **)&m_regs.stackPointer[offset])->Release();
} else if (func->parameterTypes[n].GetTypeInfo()->flags & asOBJ_REF) {
asASSERT((func->parameterTypes[n].GetTypeInfo()->flags & asOBJ_NOCOUNT) || beh->release);
if (beh->release)
m_engine->CallObjectMethod((void *) * (asPWORD *)&m_regs.stackPointer[offset], beh->release);
} else {
if (beh->destruct)
m_engine->CallObjectMethod((void *) * (asPWORD *)&m_regs.stackPointer[offset], beh->destruct);
// Free the memory
m_engine->CallFree((void *) * (asPWORD *)&m_regs.stackPointer[offset]);
}
*(asPWORD *)&m_regs.stackPointer[offset] = 0;
}
}
offset += func->parameterTypes[n].GetSizeOnStackDWords();
}
m_needToCleanupArgs = false;
}
bool asCContext::FindExceptionTryCatch() {
// Check each of the script functions on the callstack to see if
// the current program position is within a try/catch block
if (m_currentFunction && m_currentFunction->scriptData) {
asUINT currPos = asUINT(m_regs.programPointer - m_currentFunction->scriptData->byteCode.AddressOf());
for (asUINT n = 0; n < m_currentFunction->scriptData->tryCatchInfo.GetLength(); n++) {
if (currPos >= m_currentFunction->scriptData->tryCatchInfo[n].tryPos &&
currPos < m_currentFunction->scriptData->tryCatchInfo[n].catchPos)
return true;
}
}
int stackSize = GetCallstackSize();
for (int level = 1; level < stackSize; level++) {
asPWORD *s = m_callStack.AddressOf() + (stackSize - level - 1) * CALLSTACK_FRAME_SIZE;
asCScriptFunction *func = (asCScriptFunction *)s[1];
if (func && func->scriptData) {
asUINT currPos = asUINT((asDWORD *)s[2] - func->scriptData->byteCode.AddressOf());
for (asUINT n = 0; n < func->scriptData->tryCatchInfo.GetLength(); n++) {
if (currPos >= func->scriptData->tryCatchInfo[n].tryPos &&
currPos < func->scriptData->tryCatchInfo[n].catchPos)
return true;
}
}
}
return false;
}
bool asCContext::CleanStackFrame(bool catchException) {
bool exceptionCaught = false;
asSTryCatchInfo *tryCatchInfo = 0;
// Clean object variables on the stack
// If the stack memory is not allocated or the program pointer
// is not set, then there is nothing to clean up on the stack frame
if (!m_isStackMemoryNotAllocated && m_regs.programPointer) {
// If the exception occurred while calling a function it is necessary
// to clean up the arguments that were put on the stack.
CleanArgsOnStack();
// Check if this function will catch the exception
// Try blocks can be nested, so use the innermost block
asASSERT(m_currentFunction->scriptData);
if (catchException && m_currentFunction->scriptData) {
asUINT currPos = asUINT(m_regs.programPointer - m_currentFunction->scriptData->byteCode.AddressOf());
for (asUINT n = 0; n < m_currentFunction->scriptData->tryCatchInfo.GetLength(); n++) {
if (currPos >= m_currentFunction->scriptData->tryCatchInfo[n].tryPos &&
currPos < m_currentFunction->scriptData->tryCatchInfo[n].catchPos) {
tryCatchInfo = &m_currentFunction->scriptData->tryCatchInfo[n];
exceptionCaught = true;
}
if (currPos < m_currentFunction->scriptData->tryCatchInfo[n].tryPos)
break;
}
}
// Restore the stack pointer
if (!exceptionCaught)
m_regs.stackPointer += m_currentFunction->scriptData->variableSpace;
// Determine which object variables that are really live ones
asCArray<int> liveObjects;
DetermineLiveObjects(liveObjects, 0);
for (asUINT n = 0; n < m_currentFunction->scriptData->objVariablePos.GetLength(); n++) {
int pos = m_currentFunction->scriptData->objVariablePos[n];
// If the exception was caught, then only clean up objects within the try block
if (exceptionCaught) {
// Find out where the variable was declared, and skip cleaning of those that were declared before the try catch
// Multiple variables in different scopes may occupy the same slot on the stack so it is necessary to search
// the entire list to determine which variable occupies the slot now.
int skipClean = 0;
for (asUINT p = 0; p < m_currentFunction->scriptData->objVariableInfo.GetLength(); p++) {
asSObjectVariableInfo &info = m_currentFunction->scriptData->objVariableInfo[p];
if (info.variableOffset == pos &&
info.option == asOBJ_VARDECL) {
asUINT progPos = info.programPos;
if (progPos < tryCatchInfo->tryPos) {
if (skipClean >= 0)
skipClean = 1;
break;
} else if (progPos < tryCatchInfo->catchPos) {
skipClean = -1;
break;
}
}
}
// Skip only variables that have been declared before the try block. Variables declared
// within the try block and variables whose declaration was not identified (temporary objects)
// will not be skipped.
// TODO: What if a temporary variable reuses a slot from a declared variable that is no longer in scope?
if (skipClean > 0)
continue;
}
if (n < m_currentFunction->scriptData->objVariablesOnHeap) {
// Check if the pointer is initialized
if (*(asPWORD *)&m_regs.stackFramePointer[-pos]) {
// Call the object's destructor
if (m_currentFunction->scriptData->objVariableTypes[n]->flags & asOBJ_FUNCDEF) {
(*(asCScriptFunction **)&m_regs.stackFramePointer[-pos])->Release();
} else if (m_currentFunction->scriptData->objVariableTypes[n]->flags & asOBJ_REF) {
asSTypeBehaviour *beh = &CastToObjectType(m_currentFunction->scriptData->objVariableTypes[n])->beh;
asASSERT((m_currentFunction->scriptData->objVariableTypes[n]->flags & asOBJ_NOCOUNT) || beh->release);
if (beh->release)
m_engine->CallObjectMethod((void *) * (asPWORD *)&m_regs.stackFramePointer[-pos], beh->release);
} else {
asSTypeBehaviour *beh = &CastToObjectType(m_currentFunction->scriptData->objVariableTypes[n])->beh;
if (beh->destruct)
m_engine->CallObjectMethod((void *) * (asPWORD *)&m_regs.stackFramePointer[-pos], beh->destruct);
else if (m_currentFunction->scriptData->objVariableTypes[n]->flags & asOBJ_LIST_PATTERN)
m_engine->DestroyList((asBYTE *) * (asPWORD *)&m_regs.stackFramePointer[-pos], CastToObjectType(m_currentFunction->scriptData->objVariableTypes[n]));
// Free the memory
m_engine->CallFree((void *) * (asPWORD *)&m_regs.stackFramePointer[-pos]);
}
*(asPWORD *)&m_regs.stackFramePointer[-pos] = 0;
}
} else {
asASSERT(m_currentFunction->scriptData->objVariableTypes[n]->GetFlags() & asOBJ_VALUE);
// Only destroy the object if it is truly alive
if (liveObjects[n] > 0) {
asSTypeBehaviour *beh = &CastToObjectType(m_currentFunction->scriptData->objVariableTypes[n])->beh;
if (beh->destruct)
m_engine->CallObjectMethod((void *)(asPWORD *)&m_regs.stackFramePointer[-pos], beh->destruct);
}
}
}
} else
m_isStackMemoryNotAllocated = false;
// If the exception was caught then move the program position to the catch block then stop the unwinding
if (exceptionCaught) {
m_regs.programPointer = m_currentFunction->scriptData->byteCode.AddressOf() + tryCatchInfo->catchPos;
return exceptionCaught;
}
// Functions that do not own the object and parameters shouldn't do any clean up
if (m_currentFunction->dontCleanUpOnException)
return exceptionCaught;
// Clean object and parameters
int offset = 0;
if (m_currentFunction->objectType)
offset += AS_PTR_SIZE;
if (m_currentFunction->DoesReturnOnStack())
offset += AS_PTR_SIZE;
for (asUINT n = 0; n < m_currentFunction->parameterTypes.GetLength(); n++) {
if ((m_currentFunction->parameterTypes[n].IsObject() || m_currentFunction->parameterTypes[n].IsFuncdef()) && !m_currentFunction->parameterTypes[n].IsReference()) {
if (*(asPWORD *)&m_regs.stackFramePointer[offset]) {
// Call the object's destructor
asSTypeBehaviour *beh = m_currentFunction->parameterTypes[n].GetBehaviour();
if (m_currentFunction->parameterTypes[n].GetTypeInfo()->flags & asOBJ_FUNCDEF) {
(*(asCScriptFunction **)&m_regs.stackFramePointer[offset])->Release();
} else if (m_currentFunction->parameterTypes[n].GetTypeInfo()->flags & asOBJ_REF) {
asASSERT((m_currentFunction->parameterTypes[n].GetTypeInfo()->flags & asOBJ_NOCOUNT) || beh->release);
if (beh->release)
m_engine->CallObjectMethod((void *) * (asPWORD *)&m_regs.stackFramePointer[offset], beh->release);
} else {
if (beh->destruct)
m_engine->CallObjectMethod((void *) * (asPWORD *)&m_regs.stackFramePointer[offset], beh->destruct);
// Free the memory
m_engine->CallFree((void *) * (asPWORD *)&m_regs.stackFramePointer[offset]);
}
*(asPWORD *)&m_regs.stackFramePointer[offset] = 0;
}
}
offset += m_currentFunction->parameterTypes[n].GetSizeOnStackDWords();
}
return exceptionCaught;
}
// interface
int asCContext::GetExceptionLineNumber(int *column, const char **sectionName) {
// Return the last exception even if the context is no longer in the exception state
// if( GetState() != asEXECUTION_EXCEPTION ) return asERROR;
if (column) *column = m_exceptionColumn;
if (sectionName) {
// The section index can be -1 if the exception was raised in a generated function, e.g. $fact for templates
if (m_exceptionSectionIdx >= 0)
*sectionName = m_engine->scriptSectionNames[m_exceptionSectionIdx]->AddressOf();
else
*sectionName = 0;
}
return m_exceptionLine;
}
// interface
asIScriptFunction *asCContext::GetExceptionFunction() {
// Return the last exception even if the context is no longer in the exception state
// if( GetState() != asEXECUTION_EXCEPTION ) return 0;
return m_engine->scriptFunctions[m_exceptionFunction];
}
// interface
const char *asCContext::GetExceptionString() {
// Return the last exception even if the context is no longer in the exception state
// if( GetState() != asEXECUTION_EXCEPTION ) return 0;
return m_exceptionString.AddressOf();
}
// interface
asEContextState asCContext::GetState() const {
return m_status;
}
// interface
int asCContext::SetLineCallback(asSFuncPtr callback, void *obj, int callConv) {
// First turn off the line callback to avoid a second thread
// attempting to call it while the new one is still being set
m_lineCallback = false;
m_lineCallbackObj = obj;
bool isObj = false;
if ((unsigned)callConv == asCALL_GENERIC || (unsigned)callConv == asCALL_THISCALL_OBJFIRST || (unsigned)callConv == asCALL_THISCALL_OBJLAST) {
m_regs.doProcessSuspend = m_doSuspend;
return asNOT_SUPPORTED;
}
if ((unsigned)callConv >= asCALL_THISCALL) {
isObj = true;
if (obj == 0) {
m_regs.doProcessSuspend = m_doSuspend;
return asINVALID_ARG;
}
}
int r = DetectCallingConvention(isObj, callback, callConv, 0, &m_lineCallbackFunc);
// Turn on the line callback after setting both the function pointer and object pointer
if (r >= 0) m_lineCallback = true;
// The BC_SUSPEND instruction should be processed if either line
// callback is set or if the application has requested a suspension
m_regs.doProcessSuspend = m_doSuspend || m_lineCallback;
return r;
}
void asCContext::CallLineCallback() {
if (m_lineCallbackFunc.callConv < ICC_THISCALL)
m_engine->CallGlobalFunction(this, m_lineCallbackObj, &m_lineCallbackFunc, 0);
else
m_engine->CallObjectMethod(m_lineCallbackObj, this, &m_lineCallbackFunc, 0);
}
// interface
int asCContext::SetExceptionCallback(asSFuncPtr callback, void *obj, int callConv) {
m_exceptionCallback = true;
m_exceptionCallbackObj = obj;
bool isObj = false;
if ((unsigned)callConv == asCALL_GENERIC || (unsigned)callConv == asCALL_THISCALL_OBJFIRST || (unsigned)callConv == asCALL_THISCALL_OBJLAST)
return asNOT_SUPPORTED;
if ((unsigned)callConv >= asCALL_THISCALL) {
isObj = true;
if (obj == 0) {
m_exceptionCallback = false;
return asINVALID_ARG;
}
}
int r = DetectCallingConvention(isObj, callback, callConv, 0, &m_exceptionCallbackFunc);
if (r < 0) m_exceptionCallback = false;
return r;
}
void asCContext::CallExceptionCallback() {
if (m_exceptionCallbackFunc.callConv < ICC_THISCALL)
m_engine->CallGlobalFunction(this, m_exceptionCallbackObj, &m_exceptionCallbackFunc, 0);
else
m_engine->CallObjectMethod(m_exceptionCallbackObj, this, &m_exceptionCallbackFunc, 0);
}
#ifndef AS_NO_EXCEPTIONS
// internal
void asCContext::HandleAppException() {
// This method is called from within a catch(...) block
if (m_engine->translateExceptionCallback) {
// Allow the application to translate the application exception to a proper exception string
if (m_engine->translateExceptionCallbackFunc.callConv < ICC_THISCALL)
m_engine->CallGlobalFunction(this, m_engine->translateExceptionCallbackObj, &m_engine->translateExceptionCallbackFunc, 0);
else
m_engine->CallObjectMethod(m_engine->translateExceptionCallbackObj, this, &m_engine->translateExceptionCallbackFunc, 0);
}
// Make sure an exception is set even if the application decides not to do any specific translation
if (m_status != asEXECUTION_EXCEPTION)
SetException(TXT_EXCEPTION_CAUGHT);
}
#endif
// interface
void asCContext::ClearLineCallback() {
m_lineCallback = false;
m_regs.doProcessSuspend = m_doSuspend;
}
// interface
void asCContext::ClearExceptionCallback() {
m_exceptionCallback = false;
}
int asCContext::CallGeneric(asCScriptFunction *descr) {
asSSystemFunctionInterface *sysFunc = descr->sysFuncIntf;
void (*func)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))sysFunc->func;
int popSize = sysFunc->paramSize;
asDWORD *args = m_regs.stackPointer;
// Verify the object pointer if it is a class method
void *currentObject = 0;
asASSERT(sysFunc->callConv == ICC_GENERIC_FUNC || sysFunc->callConv == ICC_GENERIC_METHOD);
if (sysFunc->callConv == ICC_GENERIC_METHOD) {
// The object pointer should be popped from the context stack
popSize += AS_PTR_SIZE;
// Check for null pointer
currentObject = (void *) * (asPWORD *)(args);
if (currentObject == 0) {
SetInternalException(TXT_NULL_POINTER_ACCESS);
return 0;
}
asASSERT(sysFunc->baseOffset == 0);
// Skip object pointer
args += AS_PTR_SIZE;
}
if (descr->DoesReturnOnStack()) {
// Skip the address where the return value will be stored
args += AS_PTR_SIZE;
popSize += AS_PTR_SIZE;
}
asCGeneric gen(m_engine, descr, currentObject, args);
m_callingSystemFunction = descr;
#ifdef AS_NO_EXCEPTIONS
func(&gen);
#else
// This try/catch block is to catch potential exception that may
// be thrown by the registered function.
try {
func(&gen);
} catch (...) {
// Convert the exception to a script exception so the VM can
// properly report the error to the application and then clean up
HandleAppException();
}
#endif
m_callingSystemFunction = 0;
m_regs.valueRegister = gen.returnVal;
m_regs.objectRegister = gen.objectRegister;
m_regs.objectType = descr->returnType.GetTypeInfo();
// Increase the returned handle if the function has been declared with autohandles
// and the engine is not set to use the old mode for the generic calling convention
if (sysFunc->returnAutoHandle && m_engine->ep.genericCallMode == 1 && m_regs.objectRegister) {
asASSERT(!(descr->returnType.GetTypeInfo()->flags & asOBJ_NOCOUNT));
m_engine->CallObjectMethod(m_regs.objectRegister, CastToObjectType(descr->returnType.GetTypeInfo())->beh.addref);
}
// Clean up arguments
const asUINT cleanCount = sysFunc->cleanArgs.GetLength();
if (cleanCount) {
asSSystemFunctionInterface::SClean *clean = sysFunc->cleanArgs.AddressOf();
for (asUINT n = 0; n < cleanCount; n++, clean++) {
void **addr = (void **)&args[clean->off];
if (clean->op == 0) {
if (*addr != 0) {
m_engine->CallObjectMethod(*addr, clean->ot->beh.release);
*addr = 0;
}
} else {
asASSERT(clean->op == 1 || clean->op == 2);
asASSERT(*addr);
if (clean->op == 2)
m_engine->CallObjectMethod(*addr, clean->ot->beh.destruct);
m_engine->CallFree(*addr);
}
}
}
// Return how much should be popped from the stack
return popSize;
}
// interface
int asCContext::GetVarCount(asUINT stackLevel) {
asIScriptFunction *func = GetFunction(stackLevel);
if (func == 0) return asINVALID_ARG;
return func->GetVarCount();
}
// interface
const char *asCContext::GetVarName(asUINT varIndex, asUINT stackLevel) {
asIScriptFunction *func = GetFunction(stackLevel);
if (func == 0) return 0;
const char *name = 0;
int r = func->GetVar(varIndex, &name);
return r >= 0 ? name : 0;
}
// interface
const char *asCContext::GetVarDeclaration(asUINT varIndex, asUINT stackLevel, bool includeNamespace) {
asIScriptFunction *func = GetFunction(stackLevel);
if (func == 0) return 0;
return func->GetVarDecl(varIndex, includeNamespace);
}
// interface
int asCContext::GetVarTypeId(asUINT varIndex, asUINT stackLevel) {
asIScriptFunction *func = GetFunction(stackLevel);
if (func == 0) return asINVALID_ARG;
int typeId;
int r = func->GetVar(varIndex, 0, &typeId);
return r < 0 ? r : typeId;
}
// interface
void *asCContext::GetAddressOfVar(asUINT varIndex, asUINT stackLevel) {
// Don't return anything if there is no bytecode, e.g. before calling Execute()
if (m_regs.programPointer == 0) return 0;
if (stackLevel >= GetCallstackSize()) return 0;
asCScriptFunction *func;
asDWORD *sf;
if (stackLevel == 0) {
func = m_currentFunction;
sf = m_regs.stackFramePointer;
} else {
asPWORD *s = m_callStack.AddressOf() + (GetCallstackSize() - stackLevel - 1) * CALLSTACK_FRAME_SIZE;
func = (asCScriptFunction *)s[1];
sf = (asDWORD *)s[0];
}
if (func == 0)
return 0;
if (func->scriptData == 0)
return 0;
if (varIndex >= func->scriptData->variables.GetLength())
return 0;
// For object variables it's necessary to dereference the pointer to get the address of the value
// Reference parameters must also be dereferenced to give the address of the value
int pos = func->scriptData->variables[varIndex]->stackOffset;
if ((func->scriptData->variables[varIndex]->type.IsObject() && !func->scriptData->variables[varIndex]->type.IsObjectHandle()) || (pos <= 0)) {
// Determine if the object is really on the heap
bool onHeap = false;
if (func->scriptData->variables[varIndex]->type.IsObject() &&
!func->scriptData->variables[varIndex]->type.IsObjectHandle()) {
onHeap = true;
if (func->scriptData->variables[varIndex]->type.GetTypeInfo()->GetFlags() & asOBJ_VALUE) {
for (asUINT n = 0; n < func->scriptData->objVariablePos.GetLength(); n++) {
if (func->scriptData->objVariablePos[n] == pos) {
onHeap = n < func->scriptData->objVariablesOnHeap;
if (!onHeap) {
// If the object on the stack is not initialized return a null pointer instead
asCArray<int> liveObjects;
DetermineLiveObjects(liveObjects, stackLevel);
if (liveObjects[n] <= 0)
return 0;
}
break;
}
}
}
}
// If it wasn't an object on the heap, then check if it is a reference parameter
if (!onHeap && pos <= 0) {
// Determine what function argument this position matches
int stackPos = 0;
if (func->objectType)
stackPos -= AS_PTR_SIZE;
if (func->DoesReturnOnStack())
stackPos -= AS_PTR_SIZE;
for (asUINT n = 0; n < func->parameterTypes.GetLength(); n++) {
if (stackPos == pos) {
// The right argument was found. Is this a reference parameter?
if (func->inOutFlags[n] != asTM_NONE)
onHeap = true;
break;
}
stackPos -= func->parameterTypes[n].GetSizeOnStackDWords();
}
}
if (onHeap)
return *(void **)(sf - func->scriptData->variables[varIndex]->stackOffset);
}
return sf - func->scriptData->variables[varIndex]->stackOffset;
}
// interface
// returns the typeId of the 'this' object at the given call stack level (0 for current)
// returns 0 if the function call at the given stack level is not a method
int asCContext::GetThisTypeId(asUINT stackLevel) {
asIScriptFunction *func = GetFunction(stackLevel);
if (func == 0) return asINVALID_ARG;
if (func->GetObjectType() == 0)
return 0; // not in a method
// create a datatype
asCDataType dt = asCDataType::CreateType((asCObjectType *)func->GetObjectType(), false);
// return a typeId from the data type
return m_engine->GetTypeIdFromDataType(dt);
}
// interface
// returns the 'this' object pointer at the given call stack level (0 for current)
// returns 0 if the function call at the given stack level is not a method
void *asCContext::GetThisPointer(asUINT stackLevel) {
if (stackLevel >= GetCallstackSize())
return 0;
asCScriptFunction *func;
asDWORD *sf;
if (stackLevel == 0) {
func = m_currentFunction;
sf = m_regs.stackFramePointer;
} else {
asPWORD *s = m_callStack.AddressOf() + (GetCallstackSize() - stackLevel - 1) * CALLSTACK_FRAME_SIZE;
func = (asCScriptFunction *)s[1];
sf = (asDWORD *)s[0];
}
if (func == 0)
return 0;
if (func->objectType == 0)
return 0; // not in a method
void *thisPointer = (void *) * (asPWORD *)(sf);
if (thisPointer == 0) {
return 0;
}
// NOTE: this returns the pointer to the 'this' while the GetVarPointer functions return
// a pointer to a pointer. I can't imagine someone would want to change the 'this'
return thisPointer;
}
// TODO: Move these to as_utils.cpp
struct POW_INFO {
asQWORD MaxBaseu64;
asDWORD MaxBasei64;
asWORD MaxBaseu32;
asWORD MaxBasei32;
char HighBit;
};
const POW_INFO pow_info[] = {
{ 0ULL, 0UL, 0, 0, 0 }, // 0 is a special case
{ 0ULL, 0UL, 0, 0, 1 }, // 1 is a special case
{ 3037000499ULL, 2147483647UL, 65535, 46340, 2 }, // 2
{ 2097152ULL, 1664510UL, 1625, 1290, 2 }, // 3
{ 55108ULL, 46340UL, 255, 215, 3 }, // 4
{ 6208ULL, 5404UL, 84, 73, 3 }, // 5
{ 1448ULL, 1290UL, 40, 35, 3 }, // 6
{ 511ULL, 463UL, 23, 21, 3 }, // 7
{ 234ULL, 215UL, 15, 14, 4 }, // 8
{ 128ULL, 118UL, 11, 10, 4 }, // 9
{ 78ULL, 73UL, 9, 8, 4 }, // 10
{ 52ULL, 49UL, 7, 7, 4 }, // 11
{ 38ULL, 35UL, 6, 5, 4 }, // 12
{ 28ULL, 27UL, 5, 5, 4 }, // 13
{ 22ULL, 21UL, 4, 4, 4 }, // 14
{ 18ULL, 17UL, 4, 4, 4 }, // 15
{ 15ULL, 14UL, 3, 3, 5 }, // 16
{ 13ULL, 12UL, 3, 3, 5 }, // 17
{ 11ULL, 10UL, 3, 3, 5 }, // 18
{ 9ULL, 9UL, 3, 3, 5 }, // 19
{ 8ULL, 8UL, 3, 2, 5 }, // 20
{ 8ULL, 7UL, 2, 2, 5 }, // 21
{ 7ULL, 7UL, 2, 2, 5 }, // 22
{ 6ULL, 6UL, 2, 2, 5 }, // 23
{ 6ULL, 5UL, 2, 2, 5 }, // 24
{ 5ULL, 5UL, 2, 2, 5 }, // 25
{ 5ULL, 5UL, 2, 2, 5 }, // 26
{ 5ULL, 4UL, 2, 2, 5 }, // 27
{ 4ULL, 4UL, 2, 2, 5 }, // 28
{ 4ULL, 4UL, 2, 2, 5 }, // 29
{ 4ULL, 4UL, 2, 2, 5 }, // 30
{ 4ULL, 4UL, 2, 1, 5 }, // 31
{ 3ULL, 3UL, 1, 1, 6 }, // 32
{ 3ULL, 3UL, 1, 1, 6 }, // 33
{ 3ULL, 3UL, 1, 1, 6 }, // 34
{ 3ULL, 3UL, 1, 1, 6 }, // 35
{ 3ULL, 3UL, 1, 1, 6 }, // 36
{ 3ULL, 3UL, 1, 1, 6 }, // 37
{ 3ULL, 3UL, 1, 1, 6 }, // 38
{ 3ULL, 3UL, 1, 1, 6 }, // 39
{ 2ULL, 2UL, 1, 1, 6 }, // 40
{ 2ULL, 2UL, 1, 1, 6 }, // 41
{ 2ULL, 2UL, 1, 1, 6 }, // 42
{ 2ULL, 2UL, 1, 1, 6 }, // 43
{ 2ULL, 2UL, 1, 1, 6 }, // 44
{ 2ULL, 2UL, 1, 1, 6 }, // 45
{ 2ULL, 2UL, 1, 1, 6 }, // 46
{ 2ULL, 2UL, 1, 1, 6 }, // 47
{ 2ULL, 2UL, 1, 1, 6 }, // 48
{ 2ULL, 2UL, 1, 1, 6 }, // 49
{ 2ULL, 2UL, 1, 1, 6 }, // 50
{ 2ULL, 2UL, 1, 1, 6 }, // 51
{ 2ULL, 2UL, 1, 1, 6 }, // 52
{ 2ULL, 2UL, 1, 1, 6 }, // 53
{ 2ULL, 2UL, 1, 1, 6 }, // 54
{ 2ULL, 2UL, 1, 1, 6 }, // 55
{ 2ULL, 2UL, 1, 1, 6 }, // 56
{ 2ULL, 2UL, 1, 1, 6 }, // 57
{ 2ULL, 2UL, 1, 1, 6 }, // 58
{ 2ULL, 2UL, 1, 1, 6 }, // 59
{ 2ULL, 2UL, 1, 1, 6 }, // 60
{ 2ULL, 2UL, 1, 1, 6 }, // 61
{ 2ULL, 2UL, 1, 1, 6 }, // 62
{ 2ULL, 1UL, 1, 1, 6 }, // 63
};
int as_powi(int base, int exponent, bool &isOverflow) {
if (exponent < 0) {
if (base == 0)
// Divide by zero
isOverflow = true;
else
// Result is less than 1, so it truncates to 0
isOverflow = false;
return 0;
} else if (exponent == 0 && base == 0) {
// Domain error
isOverflow = true;
return 0;
} else if (exponent >= 31) {
switch (base) {
case -1:
isOverflow = false;
return exponent & 1 ? -1 : 1;
case 0:
isOverflow = false;
break;
case 1:
isOverflow = false;
return 1;
default:
isOverflow = true;
break;
}
return 0;
} else {
const asWORD max_base = pow_info[exponent].MaxBasei32;
const char high_bit = pow_info[exponent].HighBit;
if (max_base != 0 && max_base < (base < 0 ? -base : base)) {
isOverflow = true;
return 0; // overflow
}
int result = 1;
switch (high_bit) {
case 5:
if (exponent & 1) result *= base;
exponent >>= 1;
base *= base;
// fallthrough
case 4:
if (exponent & 1) result *= base;
exponent >>= 1;
base *= base;
// fallthrough
case 3:
if (exponent & 1) result *= base;
exponent >>= 1;
base *= base;
// fallthrough
case 2:
if (exponent & 1) result *= base;
exponent >>= 1;
base *= base;
// fallthrough
case 1:
if (exponent) result *= base;
// fallthrough
default:
isOverflow = false;
return result;
}
}
}
asDWORD as_powu(asDWORD base, asDWORD exponent, bool &isOverflow) {
if (exponent == 0 && base == 0) {
// Domain error
isOverflow = true;
return 0;
} else if (exponent >= 32) {
switch (base) {
case 0:
isOverflow = false;
break;
case 1:
isOverflow = false;
return 1;
default:
isOverflow = true;
break;
}
return 0;
} else {
const asWORD max_base = pow_info[exponent].MaxBaseu32;
const char high_bit = pow_info[exponent].HighBit;
if (max_base != 0 && max_base < base) {
isOverflow = true;
return 0; // overflow
}
asDWORD result = 1;
switch (high_bit) {
case 5:
if (exponent & 1) result *= base;
exponent >>= 1;
base *= base;
// fallthrough
case 4:
if (exponent & 1) result *= base;
exponent >>= 1;
base *= base;
// fallthrough
case 3:
if (exponent & 1) result *= base;
exponent >>= 1;
base *= base;
// fallthrough
case 2:
if (exponent & 1) result *= base;
exponent >>= 1;
base *= base;
// fallthrough
case 1:
if (exponent) result *= base;
// fallthrough
default:
isOverflow = false;
return result;
}
}
}
asINT64 as_powi64(asINT64 base, asINT64 exponent, bool &isOverflow) {
if (exponent < 0) {
if (base == 0)
// Divide by zero
isOverflow = true;
else
// Result is less than 1, so it truncates to 0
isOverflow = false;
return 0;
} else if (exponent == 0 && base == 0) {
// Domain error
isOverflow = true;
return 0;
} else if (exponent >= 63) {
switch (base) {
case -1:
isOverflow = false;
return exponent & 1 ? -1 : 1;
case 0:
isOverflow = false;
break;
case 1:
isOverflow = false;
return 1;
default:
isOverflow = true;
break;
}
return 0;
} else {
const asDWORD max_base = pow_info[exponent].MaxBasei64;
const char high_bit = pow_info[exponent].HighBit;
if (max_base != 0 && max_base < (base < 0 ? -base : base)) {
isOverflow = true;
return 0; // overflow
}
asINT64 result = 1;
switch (high_bit) {
case 6:
if (exponent & 1) result *= base;
exponent >>= 1;
base *= base;
// fallthrough
case 5:
if (exponent & 1) result *= base;
exponent >>= 1;
base *= base;
// fallthrough
case 4:
if (exponent & 1) result *= base;
exponent >>= 1;
base *= base;
// fallthrough
case 3:
if (exponent & 1) result *= base;
exponent >>= 1;
base *= base;
// fallthrough
case 2:
if (exponent & 1) result *= base;
exponent >>= 1;
base *= base;
// fallthrough
case 1:
if (exponent) result *= base;
// fallthrough
default:
isOverflow = false;
return result;
}
}
}
asQWORD as_powu64(asQWORD base, asQWORD exponent, bool &isOverflow) {
if (exponent == 0 && base == 0) {
// Domain error
isOverflow = true;
return 0;
} else if (exponent >= 64) {
switch (base) {
case 0:
isOverflow = false;
break;
case 1:
isOverflow = false;
return 1;
default:
isOverflow = true;
break;
}
return 0;
} else {
const asQWORD max_base = pow_info[exponent].MaxBaseu64;
const char high_bit = pow_info[exponent].HighBit;
if (max_base != 0 && max_base < base) {
isOverflow = true;
return 0; // overflow
}
asQWORD result = 1;
switch (high_bit) {
case 6:
if (exponent & 1) result *= base;
exponent >>= 1;
base *= base;
// fallthrough
case 5:
if (exponent & 1) result *= base;
exponent >>= 1;
base *= base;
// fallthrough
case 4:
if (exponent & 1) result *= base;
exponent >>= 1;
base *= base;
// fallthrough
case 3:
if (exponent & 1) result *= base;
exponent >>= 1;
base *= base;
// fallthrough
case 2:
if (exponent & 1) result *= base;
exponent >>= 1;
base *= base;
// fallthrough
case 1:
if (exponent) result *= base;
// fallthrough
default:
isOverflow = false;
return result;
}
}
}
END_AS_NAMESPACE
|