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
|
/*
* Load, and verify ClamAV bytecode.
*
* Copyright (C) 2015 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2009-2013 Sourcefire, Inc.
*
* Authors: Török Edvin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif
#include <string.h>
#include <assert.h>
#include <fcntl.h>
#include "dconf.h"
#include "clamav.h"
#include "others.h"
#include "pe.h"
#include "bytecode.h"
#include "bytecode_priv.h"
#include "bytecode_detect.h"
#include "readdb.h"
#include "scanners.h"
#include "bytecode_api.h"
#include "bytecode_api_impl.h"
#include "builtin_bytecodes.h"
#if HAVE_JSON
#include "json.h"
#endif
#define MAX_BC 64
#define BC_EVENTS_PER_SIG 2
#define MAX_BC_SIGEVENT_ID MAX_BC*BC_EVENTS_PER_SIG
cli_events_t * g_sigevents = NULL;
unsigned int g_sigid;
/* dummy values */
static const uint32_t nomatch[64] = {
0xdeadbeef, 0xdeaddead, 0xbeefdead, 0xdeaddead, 0xdeadbeef, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
};
static const uint32_t nooffsets[64] = {
CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE,
CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE,
CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE,
CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE,
CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE,
CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE,
CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE,
CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE,
CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE,
CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE,
CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE,
CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE,
CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE,
CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE,
CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE,
CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE, CLI_OFF_NONE
};
static const uint16_t nokind;
static const uint32_t nofilesize;
static const struct cli_pe_hook_data nopedata;
static void context_safe(struct cli_bc_ctx *ctx)
{
/* make sure these are never NULL */
if (!ctx->hooks.kind)
ctx->hooks.kind = &nokind;
if (!ctx->hooks.match_counts)
ctx->hooks.match_counts = nomatch;
if (!ctx->hooks.match_offsets)
ctx->hooks.match_offsets = nooffsets;
if (!ctx->hooks.filesize)
ctx->hooks.filesize = &nofilesize;
if (!ctx->hooks.pedata)
ctx->hooks.pedata = &nopedata;
}
static int cli_bytecode_context_reset(struct cli_bc_ctx *ctx);
struct cli_bc_ctx *cli_bytecode_context_alloc(void)
{
struct cli_bc_ctx *ctx = cli_calloc(1, sizeof(*ctx));
if (!ctx) {
cli_errmsg("Out of memory allocating cli_bytecode_context_reset\n");
return NULL;
}
ctx->bytecode_timeout = 60000;
cli_bytecode_context_reset(ctx);
return ctx;
}
void cli_bytecode_context_destroy(struct cli_bc_ctx *ctx)
{
cli_bytecode_context_clear(ctx);
free(ctx);
}
int cli_bytecode_context_getresult_file(struct cli_bc_ctx *ctx, char **tempfilename)
{
int fd;
*tempfilename = ctx->tempfile;
fd = ctx->outfd;
ctx->tempfile = NULL;
ctx->outfd = 0;
return fd;
}
/* resets bytecode state, so you can run another bytecode with same ctx */
static int cli_bytecode_context_reset(struct cli_bc_ctx *ctx)
{
unsigned i;
free(ctx->opsizes);
ctx->opsizes = NULL;
free(ctx->values);
ctx->values = NULL;
free(ctx->operands);
ctx->operands = NULL;
if (ctx->outfd) {
cli_ctx *cctx = ctx->ctx;
if (ctx->outfd)
close(ctx->outfd);
if (ctx->tempfile && (!cctx || !cctx->engine->keeptmp)) {
cli_unlink(ctx->tempfile);
}
free(ctx->tempfile);
ctx->tempfile = NULL;
ctx->outfd = 0;
}
if (ctx->jsnormdir) {
char fullname[1025];
cli_ctx *cctx = ctx->ctx;
int fd, ret = CL_CLEAN;
if (!ctx->found) {
snprintf(fullname, 1024, "%s"PATHSEP"javascript", ctx->jsnormdir);
fd = open(fullname, O_RDONLY|O_BINARY);
if(fd >= 0) {
ret = cli_scandesc(fd, cctx, CL_TYPE_HTML, 0, NULL, AC_SCAN_VIR, NULL);
if (ret == CL_CLEAN) {
if (lseek(fd, 0, SEEK_SET) == -1)
cli_dbgmsg("cli_bytecode: call to lseek() has failed\n");
else
ret = cli_scandesc(fd, cctx, CL_TYPE_TEXT_ASCII, 0, NULL, AC_SCAN_VIR, NULL);
}
close(fd);
}
}
if (!cctx || !cctx->engine->keeptmp) {
cli_rmdirs(ctx->jsnormdir);
}
free(ctx->jsnormdir);
if (ret != CL_CLEAN)
ctx->found = 1;
}
ctx->numParams = 0;
ctx->funcid = 0;
/* don't touch fmap, file_size, and hooks, sections, ctx, timeout, pdf* */
ctx->off = 0;
ctx->written = 0;
ctx->jsnormwritten = 0;
#if USE_MPOOL
if (ctx->mpool) {
mpool_destroy(ctx->mpool);
ctx->mpool = NULL;
}
#else
/*TODO: implement for no-mmap case too*/
#endif
for (i=0;i<ctx->ninflates;i++)
cli_bcapi_inflate_done(ctx, i);
free(ctx->inflates);
ctx->inflates = NULL;
ctx->ninflates = 0;
for (i=0;i<ctx->nbuffers;i++)
cli_bcapi_buffer_pipe_done(ctx, i);
free(ctx->buffers);
ctx->buffers = NULL;
ctx->nbuffers = 0;
for (i=0;i<ctx->nhashsets;i++)
cli_bcapi_hashset_done(ctx, i);
free(ctx->hashsets);
ctx->hashsets = NULL;
ctx->nhashsets = 0;
for (i=0;i<ctx->njsnorms;i++)
cli_bcapi_jsnorm_done(ctx, i);
free(ctx->jsnorms);
ctx->jsnorms = NULL;
ctx->njsnorms = 0;
ctx->jsnormdir = NULL;
for (i=0;i<ctx->nmaps;i++)
cli_bcapi_map_done(ctx, i);
free(ctx->maps);
ctx->maps = NULL;
ctx->nmaps = 0;
#if HAVE_JSON
free((json_object**)(ctx->jsonobjs));
ctx->jsonobjs = NULL;
ctx->njsonobjs = 0;
#endif
ctx->containertype = CL_TYPE_ANY;
return CL_SUCCESS;
}
int cli_bytecode_context_clear(struct cli_bc_ctx *ctx)
{
cli_bytecode_context_reset(ctx);
memset(ctx, 0, sizeof(*ctx));
return CL_SUCCESS;
}
static unsigned typesize(const struct cli_bc *bc, uint16_t type)
{
struct cli_bc_type *ty;
unsigned j;
type &= 0x7fff;
if (!type)
return 0;
if (type <= 8)
return 1;
if (type <= 16)
return 2;
if (type <= 32)
return 4;
if (type <= 64)
return 8;
ty = &bc->types[type-65];
if (ty->size)
return ty->size;
switch (ty->kind) {
case 2:
case 3:
for (j=0;j<ty->numElements;j++)
ty->size += typesize(bc, ty->containedTypes[j]);
break;
case 4:
ty->size = ty->numElements * typesize(bc, ty->containedTypes[0]);
break;
default:
break;
}
if (!ty->size && ty->kind != DFunctionType) {
cli_warnmsg("type %d size is 0\n", type-65);
}
return ty->size;
}
static unsigned typealign(const struct cli_bc *bc, uint16_t type)
{
type &= 0x7fff;
if (type <= 64) {
unsigned size = typesize(bc, type);
return size ? size : 1;
}
return bc->types[type-65].align;
}
int cli_bytecode_context_setfuncid(struct cli_bc_ctx *ctx, const struct cli_bc *bc, unsigned funcid)
{
unsigned i, s=0;
const struct cli_bc_func *func;
if (funcid >= bc->num_func) {
cli_errmsg("bytecode: function ID doesn't exist: %u\n", funcid);
return CL_EARG;
}
func = ctx->func = &bc->funcs[funcid];
ctx->bc = bc;
ctx->numParams = func->numArgs;
ctx->funcid = funcid;
if (func->numArgs) {
ctx->operands = cli_malloc(sizeof(*ctx->operands)*func->numArgs);
if (!ctx->operands) {
cli_errmsg("bytecode: error allocating memory for parameters\n");
return CL_EMEM;
}
ctx->opsizes = cli_malloc(sizeof(*ctx->opsizes)*func->numArgs);
if (!ctx->opsizes) {
cli_errmsg("bytecode: error allocating memory for opsizes\n");
return CL_EMEM;
}
for (i=0;i<func->numArgs;i++) {
unsigned al = typealign(bc, func->types[i]);
s = (s+al-1)&~(al-1);
ctx->operands[i] = s;
s += ctx->opsizes[i] = typesize(bc, func->types[i]);
}
}
s += 8;/* return value */
ctx->bytes = s;
ctx->values = cli_malloc(s);
if (!ctx->values) {
cli_errmsg("bytecode: error allocating memory for parameters\n");
return CL_EMEM;
}
return CL_SUCCESS;
}
static inline int type_isint(uint16_t type)
{
return type > 0 && type <= 64;
}
int cli_bytecode_context_setparam_int(struct cli_bc_ctx *ctx, unsigned i, uint64_t c)
{
if (i >= ctx->numParams) {
cli_errmsg("bytecode: param index out of bounds: %u\n", i);
return CL_EARG;
}
if (!type_isint(ctx->func->types[i])) {
cli_errmsg("bytecode: parameter type mismatch\n");
return CL_EARG;
}
switch (ctx->opsizes[i]) {
case 1:
ctx->values[ctx->operands[i]] = c;
break;
case 2:
*(uint16_t*)&ctx->values[ctx->operands[i]] = c;
break;
case 4:
*(uint32_t*)&ctx->values[ctx->operands[i]] = c;
break;
case 8:
*(uint64_t*)&ctx->values[ctx->operands[i]] = c;
break;
}
return CL_SUCCESS;
}
int cli_bytecode_context_setparam_ptr(struct cli_bc_ctx *ctx, unsigned i, void *data, unsigned datalen)
{
UNUSEDPARAM(ctx);
UNUSEDPARAM(i);
UNUSEDPARAM(data);
UNUSEDPARAM(datalen);
cli_errmsg("Pointer parameters are not implemented yet!\n");
return CL_EARG;
}
static inline uint64_t readNumber(const unsigned char *p, unsigned *off, unsigned len, char *ok)
{
uint64_t n=0;
unsigned i, newoff, lim, p0 = p[*off], shift=0;
lim = p0 - 0x60;
if (lim > 0x10) {
cli_errmsg("Invalid number type: %c\n", p0);
*ok = 0;
return 0;
}
newoff = *off +lim+1;
if (newoff > len) {
cli_errmsg("End of line encountered while reading number\n");
*ok = 0;
return 0;
}
if (p0 == 0x60) {
*off = newoff;
return 0;
}
for (i=*off+1;i < newoff; i++) {
uint64_t v = p[i];
if (UNLIKELY((v&0xf0) != 0x60)) {
cli_errmsg("Invalid number part: %c\n", (char)v);
*ok = 0;
return 0;
}
v &= 0xf;
v <<= shift;
n |= v;
shift += 4;
}
*off = newoff;
return n;
}
static inline funcid_t readFuncID(struct cli_bc *bc, unsigned char *p,
unsigned *off, unsigned len, char *ok)
{
funcid_t id = readNumber(p, off, len, ok)-1;
if (*ok && id >= bc->num_func) {
cli_errmsg("Called function out of range: %u >= %u\n", id, bc->num_func);
*ok = 0;
return ~0;
}
return id;
}
static inline funcid_t readAPIFuncID(struct cli_bc *bc, unsigned char *p,
unsigned *off, unsigned len, char *ok)
{
funcid_t id = readNumber(p, off, len, ok)-1;
if (*ok && !cli_bitset_test(bc->uses_apis, id)) {
cli_errmsg("Called undeclared API function: %u\n", id);
*ok = 0;
return ~0;
}
return id;
}
static inline unsigned readFixedNumber(const unsigned char *p, unsigned *off,
unsigned len, char *ok, unsigned width)
{
unsigned i, n=0, shift=0;
unsigned newoff = *off + width;
if (newoff > len) {
cli_errmsg("Newline encountered while reading number\n");
*ok = 0;
return 0;
}
for (i=*off;i<newoff;i++) {
unsigned v = p[i];
if (UNLIKELY((v&0xf0) != 0x60)) {
cli_errmsg("Invalid number part: %c\n", v);
*ok = 0;
return 0;
}
v &= 0xf;
v <<= shift;
n |= v;
shift += 4;
}
*off = newoff;
return n;
}
static inline operand_t readOperand(struct cli_bc_func *func, unsigned char *p,
unsigned *off, unsigned len, char *ok)
{
uint64_t v;
if ((p[*off]&0xf0) == 0x40 || p[*off] == 0x50) {
uint64_t *dest;
uint16_t ty;
p[*off] |= 0x20;
/* TODO: unique constants */
func->constants = cli_realloc2(func->constants, (func->numConstants+1)*sizeof(*func->constants));
if (!func->constants) {
*ok = 0;
return MAX_OP;
}
v = readNumber(p, off, len, ok);
dest = &func->constants[func->numConstants];
/* Write the constant to the correct place according to its type.
* This is needed on big-endian machines, because constants are always
* read as u64, but accesed as one of these types: u8, u16, u32, u64 */
*dest= 0;
ty = 8*readFixedNumber(p, off, len, ok, 1);
if (!ty) {
/* This is a global variable */
return 0x80000000 | v;
}
if (ty <= 8)
*(uint8_t*)dest = v;
else if (ty <= 16)
*(uint16_t*)dest = v;
else if (ty <= 32)
*(uint32_t*)dest = v;
else
*dest = v;
return func->numValues + func->numConstants++;
}
v = readNumber(p, off, len, ok);
if (!*ok)
return MAX_OP;
if (v >= func->numValues) {
cli_errmsg("Operand index exceeds bounds: %u >= %u!\n", (unsigned)v, (unsigned)func->numValues);
*ok = 0;
return MAX_OP;
}
return v;
}
static inline char *readData(const unsigned char *p, unsigned *off, unsigned len, char *ok, unsigned *datalen)
{
unsigned char *dat, *q;
unsigned l, newoff, i;
if (p[*off] != '|') {
cli_errmsg("Data start marker missing: %c\n", p[*off]);
*ok = 0;
return NULL;
}
(*off)++;
l = readNumber(p, off, len, ok);
if (!l || !ok) {
*datalen = l;
return NULL;
}
newoff = *off + 2*l;
if (newoff > len) {
cli_errmsg("Line ended while reading data\n");
*ok = 0;
return 0;
}
dat = cli_malloc(l);
if (!dat) {
cli_errmsg("Cannot allocate memory for data\n");
*ok = 0;
return NULL;
}
q = dat;
for (i=*off;i<newoff;i += 2) {
const unsigned char v0 = p[i];
const unsigned char v1 = p[i+1];
if (UNLIKELY((v0&0xf0) != 0x60 || (v1&0xf0) != 0x60)) {
cli_errmsg("Invalid data part: %c%c\n", v0, v1);
*ok = 0;
free(dat);
return 0;
}
*q++ = (v0&0xf) | ((v1&0xf) << 4);
}
*off = newoff;
*datalen = l;
return (char*)dat;
}
static inline char *readString(const unsigned char *p, unsigned *off, unsigned len, char *ok)
{
unsigned stringlen;
char *str = readData(p, off, len, ok, &stringlen);
if (*ok && stringlen && str[stringlen-1] != '\0') {
str[stringlen-1] = '\0';
cli_errmsg("bytecode: string missing \\0 terminator: %s\n", str);
free(str);
*ok = 0;
return NULL;
}
return str;
}
static int parseHeader(struct cli_bc *bc, unsigned char *buffer, unsigned *linelength)
{
uint64_t magic1;
unsigned magic2;
char ok = 1;
unsigned offset, len, flevel;
char *pos;
if (strncmp((const char*)buffer, BC_HEADER, sizeof(BC_HEADER)-1)) {
cli_errmsg("Missing file magic in bytecode");
return CL_EMALFDB;
}
offset = sizeof(BC_HEADER)-1;
len = strlen((const char*)buffer);
bc->metadata.formatlevel = readNumber(buffer, &offset, len, &ok);
if (!ok) {
cli_errmsg("Unable to parse (format) functionality level in bytecode header\n");
return CL_EMALFDB;
}
/* we support 2 bytecode formats */
if (bc->metadata.formatlevel != BC_FORMAT_096 &&
bc->metadata.formatlevel != BC_FORMAT_LEVEL) {
cli_dbgmsg("Skipping bytecode with (format) functionality level: %u (current %u)\n",
bc->metadata.formatlevel, BC_FORMAT_LEVEL);
return CL_BREAK;
}
/* Optimistic parsing, check for error only at the end.*/
bc->metadata.timestamp = readNumber(buffer, &offset, len, &ok);
bc->metadata.sigmaker = readString(buffer, &offset, len, &ok);
bc->metadata.targetExclude = readNumber(buffer, &offset, len, &ok);
bc->kind = readNumber(buffer, &offset, len, &ok);
bc->metadata.minfunc = readNumber(buffer, &offset, len, &ok);
bc->metadata.maxfunc = readNumber(buffer, &offset, len, &ok);
flevel = cl_retflevel();
/* in 0.96 these 2 fields are unused / zero, in post 0.96 these mean
* min/max flevel.
* So 0 for min/max means no min/max
* Note that post 0.96 bytecode/bytecode lsig needs format 7, because
* 0.96 doesn't check lsig functionality level.
*/
if ((bc->metadata.minfunc && bc->metadata.minfunc > flevel) ||
(bc->metadata.maxfunc && bc->metadata.maxfunc < flevel)) {
cli_dbgmsg("Skipping bytecode with (engine) functionality level %u-%u (current %u)\n",
bc->metadata.minfunc, bc->metadata.maxfunc, flevel);
return CL_BREAK;
}
bc->metadata.maxresource = readNumber(buffer, &offset, len, &ok);
bc->metadata.compiler = readString(buffer, &offset, len, &ok);
bc->num_types = readNumber(buffer, &offset, len, &ok);
bc->num_func = readNumber(buffer, &offset, len, &ok);
bc->state = bc_loaded;
bc->uses_apis = NULL;
bc->dbgnodes = NULL;
bc->dbgnode_cnt = 0;
if (!ok) {
cli_errmsg("Invalid bytecode header at %u\n", offset);
return CL_EMALFDB;
}
magic1 = readNumber(buffer, &offset, len, &ok);
magic2 = readFixedNumber(buffer, &offset, len, &ok, 2);
if (!ok || magic1 != 0x53e5493e9f3d1c30ull || magic2 != 42) {
unsigned long m0 = magic1 >> 32;
unsigned long m1 = magic1;
cli_errmsg("Magic numbers don't match: %lx%lx, %u\n", m0, m1, magic2);
return CL_EMALFDB;
}
if (buffer[offset] != ':') {
cli_errmsg("Expected : but found: %c\n", buffer[offset]);
return CL_EMALFDB;
}
offset++;
*linelength = strtol((const char*)buffer+offset, &pos, 10);
if (*pos != '\0') {
cli_errmsg("Invalid number: %s\n", buffer+offset);
return CL_EMALFDB;
}
bc->funcs = cli_calloc(bc->num_func, sizeof(*bc->funcs));
if (!bc->funcs) {
cli_errmsg("Out of memory allocating %u functions\n", bc->num_func);
return CL_EMEM;
}
bc->types = cli_calloc(bc->num_types, sizeof(*bc->types));
if (!bc->types) {
cli_errmsg("Out of memory allocating %u types\n", bc->num_types);
return CL_EMEM;
}
return CL_SUCCESS;
}
static int parseLSig(struct cli_bc *bc, char *buffer)
{
const char *prefix;
char *vnames, *vend = strchr(buffer, ';');
if (vend) {
bc->lsig = cli_strdup(buffer);
*vend++ = '\0';
prefix = buffer;
vnames = strchr(vend, '{');
} else {
/* Not a logical signature, but we still have a virusname */
bc->hook_name = cli_strdup(buffer);
bc->lsig = NULL;
}
return CL_SUCCESS;
}
static uint16_t readTypeID(struct cli_bc *bc, unsigned char *buffer,
unsigned *offset, unsigned len, char *ok)
{
uint64_t t = readNumber(buffer, offset, len, ok);
if (!ok)
return ~0;
if (t >= bc->num_types + bc->start_tid) {
cli_errmsg("Invalid type id: %llu\n", (unsigned long long)t);
*ok = 0;
return ~0;
}
return t;
}
static void parseType(struct cli_bc *bc, struct cli_bc_type *ty,
unsigned char *buffer, unsigned *off, unsigned len,
char *ok)
{
unsigned j;
ty->numElements = readNumber(buffer, off, len, ok);
if (!*ok) {
cli_errmsg("Error parsing type\n");
*ok = 0;
return;
}
ty->containedTypes = cli_malloc(sizeof(*ty->containedTypes)*ty->numElements);
if (!ty->containedTypes) {
cli_errmsg("Out of memory allocating %u types\n", ty->numElements);
*ok = 0;
return;
}
for (j=0;j<ty->numElements;j++) {
ty->containedTypes[j] = readTypeID(bc, buffer, off, len, ok);
}
}
static uint16_t containedTy[] = {8,16,32,64};
#define NUM_STATIC_TYPES 4
static void add_static_types(struct cli_bc *bc)
{
unsigned i;
for (i=0;i<NUM_STATIC_TYPES;i++) {
bc->types[i].kind = DPointerType;
bc->types[i].numElements = 1;
bc->types[i].containedTypes = &containedTy[i];
bc->types[i].size = bc->types[i].align = 8;
}
}
static int parseTypes(struct cli_bc *bc, unsigned char *buffer)
{
unsigned i, offset = 1, len = strlen((const char*)buffer);
char ok=1;
if (buffer[0] != 'T') {
cli_errmsg("Invalid function types header: %c\n", buffer[0]);
return CL_EMALFDB;
}
bc->start_tid = readFixedNumber(buffer, &offset, len, &ok, 2);
if (bc->start_tid != BC_START_TID) {
cli_warnmsg("Type start id mismatch: %u != %u\n", bc->start_tid,
BC_START_TID);
return CL_BREAK;
}
add_static_types(bc);
for (i=(BC_START_TID - 65);i<bc->num_types-1;i++) {
struct cli_bc_type *ty = &bc->types[i];
uint8_t t = readFixedNumber(buffer, &offset, len, &ok, 1);
if (!ok) {
cli_errmsg("Error reading type kind\n");
return CL_EMALFDB;
}
switch (t) {
case 1:
ty->kind = DFunctionType;
ty->size = ty->align = sizeof(void*);
parseType(bc, ty, buffer, &offset, len, &ok);
if (!ok) {
cli_errmsg("Error parsing type %u\n", i);
return CL_EMALFDB;
}
if (!ty->numElements) {
cli_errmsg("Function with no return type? %u\n", i);
return CL_EMALFDB;
}
break;
case 2:
case 3:
ty->kind = (t == 2) ? DPackedStructType : DStructType;
ty->size = ty->align = 0;/* TODO:calculate size/align of structs */
ty->align = 8;
parseType(bc, ty, buffer, &offset, len, &ok);
if (!ok) {
cli_errmsg("Error parsing type %u\n", i);
return CL_EMALFDB;
}
break;
case 4:
ty->kind = DArrayType;
/* number of elements of array, not subtypes! */
ty->numElements = readNumber(buffer, &offset, len, &ok);
if (!ok) {
cli_errmsg("Error parsing type %u\n", i);
return CL_EMALFDB;
}
/* fall-through */
case 5:
if (t == 5) {
ty->kind = DPointerType;
ty->numElements = 1;
}
ty->containedTypes = cli_malloc(sizeof(*ty->containedTypes));
if (!ty->containedTypes) {
cli_errmsg("Out of memory allocating containedType\n");
return CL_EMALFDB;
}
ty->containedTypes[0] = readTypeID(bc, buffer, &offset, len, &ok);
if (!ok) {
cli_errmsg("Error parsing type %u\n", i);
return CL_EMALFDB;
}
if (t == 5) {
/* for interpreter, pointers 64-bit there */
ty->size = ty->align = 8;
} else {
ty->size = ty->numElements*typesize(bc, ty->containedTypes[0]);
ty->align = typealign(bc, ty->containedTypes[0]);
}
break;
default:
cli_errmsg("Invalid type kind: %u\n", t);
return CL_EMALFDB;
}
}
for (i=(BC_START_TID - 65);i<bc->num_types-1;i++) {
struct cli_bc_type *ty = &bc->types[i];
if (ty->kind == DArrayType) {
ty->size = ty->numElements*typesize(bc, ty->containedTypes[0]);
ty->align = typealign(bc, ty->containedTypes[0]);
}
}
return CL_SUCCESS;
}
/* checks whether the type described by tid is the same as the one described by
* expectty. */
static int types_equal(const struct cli_bc *bc, uint16_t *apity2ty, uint16_t tid, uint16_t apitid)
{
unsigned i;
const struct cli_bc_type *ty = &bc->types[tid - 65];
const struct cli_bc_type *apity = &cli_apicall_types[apitid];
/* If we've already verified type equality, return.
* Since we need to check equality of recursive types, we assume types are
* equal while checking equality of contained types, unless proven
* otherwise. */
if (apity2ty[apitid] == tid + 1)
return 1;
apity2ty[apitid] = tid+1;
if (ty->kind != apity->kind) {
cli_dbgmsg("bytecode: type kind mismatch: %u != %u\n", ty->kind, apity->kind);
return 0;
}
if (ty->numElements != apity->numElements) {
cli_dbgmsg("bytecode: type numElements mismatch: %u != %u\n", ty->numElements, apity->numElements);
return 0;
}
for (i=0;i<ty->numElements;i++) {
if (apity->containedTypes[i] < BC_START_TID) {
if (ty->containedTypes[i] != apity->containedTypes[i]) {
cli_dbgmsg("bytecode: contained type mismatch: %u != %u\n",
ty->containedTypes[i], apity->containedTypes[i]);
return 0;
}
} else if (!types_equal(bc, apity2ty, ty->containedTypes[i], apity->containedTypes[i] - BC_START_TID))
return 0;
if (ty->kind == DArrayType)
break;/* validated the contained type already */
}
return 1;
}
static int parseApis(struct cli_bc *bc, unsigned char *buffer)
{
unsigned i, offset = 1, len = strlen((const char*)buffer), maxapi, calls;
char ok =1;
uint16_t *apity2ty;/*map of api type to current bytecode type ID */
if (buffer[0] != 'E') {
cli_errmsg("bytecode: Invalid api header: %c\n", buffer[0]);
return CL_EMALFDB;
}
maxapi = readNumber(buffer, &offset, len, &ok);
if (!ok)
return CL_EMALFDB;
if (maxapi > cli_apicall_maxapi) {
cli_dbgmsg("bytecode using API %u, but highest API known to libclamav is %u, skipping\n", maxapi, cli_apicall_maxapi);
return CL_BREAK;
}
calls = readNumber(buffer, &offset, len, &ok);
if (!ok)
return CL_EMALFDB;
if (calls > maxapi) {
cli_errmsg("bytecode: attempting to describe more APIs than max: %u > %u\n", calls, maxapi);
return CL_EMALFDB;
}
bc->uses_apis = cli_bitset_init();
if (!bc->uses_apis) {
cli_errmsg("Out of memory allocating apis bitset\n");
return CL_EMEM;
}
apity2ty = cli_calloc(cli_apicall_maxtypes, sizeof(*cli_apicall_types));
if (!apity2ty) {
cli_errmsg("Out of memory allocating apity2ty\n");
return CL_EMEM;
}
for (i=0;i < calls; i++) {
unsigned id = readNumber(buffer, &offset, len, &ok);
uint16_t tid = readTypeID(bc, buffer, &offset, len, &ok);
char *name = readString(buffer, &offset, len, &ok);
/* validate APIcall prototype */
if (id > maxapi) {
cli_errmsg("bytecode: API id %u out of range, max %u\n", id, maxapi);
ok = 0;
}
/* API ids start from 1 */
id--;
if (ok && name && strcmp(cli_apicalls[id].name, name)) {
cli_errmsg("bytecode: API %u name mismatch: %s expected %s\n", id, name, cli_apicalls[id].name);
ok = 0;
}
if (ok && !types_equal(bc, apity2ty, tid, cli_apicalls[id].type)) {
cli_errmsg("bytecode: API %u prototype doesn't match\n", id);
ok = 0;
}
/* don't need the name anymore */
free(name);
if (!ok) {
free(apity2ty); /* free temporary map */
return CL_EMALFDB;
}
/* APIcall is valid */
cli_bitset_set(bc->uses_apis, id);
}
free(apity2ty); /* free temporary map */
cli_dbgmsg("bytecode: Parsed %u APIcalls, maxapi %u\n", calls, maxapi);
return CL_SUCCESS;
}
static uint16_t type_components(struct cli_bc *bc, uint16_t id, char *ok)
{
unsigned i, sum=0;
const struct cli_bc_type *ty;
if (id <= 64)
return 1;
ty = &bc->types[id-65];
/* TODO: protect against recursive types */
switch (ty->kind) {
case DFunctionType:
cli_errmsg("bytecode: function type not accepted for constant: %u\n", id);
/* don't accept functions as constant initializers */
*ok = 0;
return 0;
case DPointerType:
return 2;
case DStructType:
case DPackedStructType:
for (i=0;i<ty->numElements;i++) {
sum += type_components(bc, ty->containedTypes[i], ok);
}
return sum;
case DArrayType:
return type_components(bc, ty->containedTypes[0], ok)*ty->numElements;
default:
*ok = 0;
return 0;
}
}
static void readConstant(struct cli_bc *bc, unsigned i, unsigned comp,
unsigned char *buffer, unsigned *offset,
unsigned len, char *ok)
{
unsigned j=0;
if (*ok && buffer[*offset] == 0x40 &&
buffer [*offset+1] == 0x60) {
/* zero initializer */
memset(bc->globals[i], 0, sizeof(*bc->globals[0])*comp);
(*offset)+=2;
return;
}
while (*ok && buffer[*offset] != 0x60) {
if (j >= comp) {
cli_errmsg("bytecode: constant has too many subcomponents, expected %u\n", comp);
*ok = 0;
return;
}
buffer[*offset] |= 0x20;
bc->globals[i][j++] = readNumber(buffer, offset, len, ok);
}
if (*ok && j != comp) {
cli_errmsg("bytecode: constant has too few subcomponents: %u < %u\n", j, comp);
*ok = 0;
}
(*offset)++;
}
/* parse constant globals with constant initializers */
static int parseGlobals(struct cli_bc *bc, unsigned char *buffer)
{
unsigned i, offset = 1, len = strlen((const char*)buffer), numglobals;
unsigned maxglobal;
char ok=1;
if (buffer[0] != 'G') {
cli_errmsg("bytecode: Invalid globals header: %c\n", buffer[0]);
return CL_EMALFDB;
}
maxglobal = readNumber(buffer, &offset, len, &ok);
if (maxglobal > cli_apicall_maxglobal) {
cli_dbgmsg("bytecode using global %u, but highest global known to libclamav is %u, skipping\n", maxglobal, cli_apicall_maxglobal);
return CL_BREAK;
}
numglobals = readNumber(buffer, &offset, len, &ok);
bc->globals = cli_calloc(numglobals, sizeof(*bc->globals));
if (!bc->globals) {
cli_errmsg("bytecode: OOM allocating memory for %u globals\n", numglobals);
return CL_EMEM;
}
bc->globaltys = cli_calloc(numglobals, sizeof(*bc->globaltys));
if (!bc->globaltys) {
cli_errmsg("bytecode: OOM allocating memory for %u global types\n", numglobals);
return CL_EMEM;
}
bc->num_globals = numglobals;
if (!ok)
return CL_EMALFDB;
for (i=0;i<numglobals;i++) {
unsigned comp;
bc->globaltys[i] = readTypeID(bc, buffer, &offset, len, &ok);
comp = type_components(bc, bc->globaltys[i], &ok);
if (!ok)
return CL_EMALFDB;
bc->globals[i] = cli_malloc(sizeof(*bc->globals[0])*comp);
if (!bc->globals[i])
return CL_EMEM;
readConstant(bc, i, comp, buffer, &offset, len, &ok);
}
if (!ok)
return CL_EMALFDB;
if (offset != len) {
cli_errmsg("Trailing garbage in globals: %d extra bytes\n",
len-offset);
return CL_EMALFDB;
}
return CL_SUCCESS;
}
static int parseMD(struct cli_bc *bc, unsigned char *buffer)
{
unsigned offset = 1, len = strlen((const char*)buffer);
unsigned numMD, i, b;
char ok = 1;
if (buffer[0] != 'D')
return CL_EMALFDB;
numMD = readNumber(buffer, &offset, len, &ok);
if (!ok) {
cli_errmsg("Unable to parse number of MD nodes\n");
return CL_EMALFDB;
}
b = bc->dbgnode_cnt;
bc->dbgnode_cnt += numMD;
bc->dbgnodes = cli_realloc(bc->dbgnodes, bc->dbgnode_cnt * sizeof(*bc->dbgnodes));
if (!bc->dbgnodes)
return CL_EMEM;
for (i=0;i<numMD;i++) {
unsigned j;
struct cli_bc_dbgnode_element* elts;
unsigned el = readNumber(buffer, &offset, len, &ok);
if (!ok) {
cli_errmsg("Unable to parse number of elements\n");
return CL_EMALFDB;
}
bc->dbgnodes[b+i].numelements = el;
bc->dbgnodes[b+i].elements = elts = cli_calloc(el, sizeof(*elts));
if (!elts)
return CL_EMEM;
for (j=0;j<el;j++) {
if (buffer[offset] == '|') {
elts[j].string = readData(buffer, &offset, len, &ok, &elts[j].len);
if (!ok)
return CL_EMALFDB;
} else {
elts[j].len = readNumber(buffer, &offset, len, &ok);
if (!ok)
return CL_EMALFDB;
if (elts[j].len) {
elts[j].constant = readNumber(buffer, &offset, len, &ok);
}
else
elts[j].nodeid = readNumber(buffer, &offset, len, &ok);
if (!ok)
return CL_EMALFDB;
}
}
}
cli_dbgmsg("bytecode: Parsed %u nodes total\n", bc->dbgnode_cnt);
return CL_SUCCESS;
}
static int parseFunctionHeader(struct cli_bc *bc, unsigned fn, unsigned char *buffer)
{
char ok=1;
unsigned offset, len, all_locals=0, i;
struct cli_bc_func *func;
if (fn >= bc->num_func) {
cli_errmsg("Found more functions than declared: %u >= %u\n", fn,
bc->num_func);
return CL_EMALFDB;
}
func = &bc->funcs[fn];
len = strlen((const char*)buffer);
if (buffer[0] != 'A') {
cli_errmsg("Invalid function arguments header: %c\n", buffer[0]);
return CL_EMALFDB;
}
offset = 1;
func->numArgs = readFixedNumber(buffer, &offset, len, &ok, 1);
func->returnType = readTypeID(bc, buffer, &offset, len, &ok);
if (buffer[offset] != 'L') {
cli_errmsg("Invalid function locals header: %c\n", buffer[offset]);
return CL_EMALFDB;
}
offset++;
func->numLocals = readNumber(buffer, &offset, len, &ok);
if (!ok) {
cli_errmsg("Invalid number of arguments/locals\n");
return CL_EMALFDB;
}
all_locals = func->numArgs + func->numLocals;
if (!all_locals) {
func->types = NULL;
} else {
func->types = cli_calloc(all_locals, sizeof(*func->types));
if (!func->types) {
cli_errmsg("Out of memory allocating function arguments\n");
return CL_EMEM;
}
}
for (i=0;i<all_locals;i++) {
func->types[i] = readNumber(buffer, &offset, len, &ok);
if (readFixedNumber(buffer, &offset, len, &ok, 1))
func->types[i] |= 0x8000;
}
if (!ok) {
cli_errmsg("Invalid local types\n");
return CL_EMALFDB;
}
if (buffer[offset] != 'F') {
cli_errmsg("Invalid function body header: %c\n", buffer[offset]);
return CL_EMALFDB;
}
offset++;
func->numInsts = readNumber(buffer, &offset, len, &ok);
if (!ok ){
cli_errmsg("Invalid instructions count\n");
return CL_EMALFDB;
}
func->numValues = func->numArgs + func->numLocals;
func->insn_idx = 0;
func->numConstants=0;
func->allinsts = cli_calloc(func->numInsts, sizeof(*func->allinsts));
if (!func->allinsts) {
cli_errmsg("Out of memory allocating instructions\n");
return CL_EMEM;
}
func->numBB = readNumber(buffer, &offset, len, &ok);
if (!ok) {
cli_errmsg("Invalid basic block count\n");
return CL_EMALFDB;
}
func->BB = cli_calloc(func->numBB, sizeof(*func->BB));
if (!func->BB) {
cli_errmsg("Out of memory allocating basic blocks\n");
return CL_EMEM;
}
return CL_SUCCESS;
}
static bbid_t readBBID(struct cli_bc_func *func, const unsigned char *buffer, unsigned *off, unsigned len, char *ok) {
unsigned id = readNumber(buffer, off, len, ok);
if (!id || id >= func->numBB) {
cli_errmsg("Basic block ID out of range: %u\n", id);
*ok = 0;
}
if (!*ok)
return ~0;
return id;
}
/*
static uint16_t get_type(struct cli_bc_func *func, operand_t op)
{
if (op >= func->numValues)
return 64;
return func->types[op];
}*/
static int16_t get_optype(const struct cli_bc_func *bcfunc, operand_t op)
{
if (op >= bcfunc->numArgs + bcfunc->numLocals)
return 0;
return bcfunc->types[op]&0x7fff;
}
static int parseBB(struct cli_bc *bc, unsigned func, unsigned bb, unsigned char *buffer)
{
char ok=1;
unsigned offset, len, i, last = 0;
struct cli_bc_bb *BB;
struct cli_bc_func *bcfunc = &bc->funcs[func];
struct cli_bc_inst inst;
if (bb >= bcfunc->numBB) {
cli_errmsg("Found too many basic blocks\n");
return CL_EMALFDB;
}
BB = &bcfunc->BB[bb];
len = strlen((const char*) buffer);
if (buffer[0] != 'B') {
cli_errmsg("Invalid basic block header: %c\n", buffer[0]);
return CL_EMALFDB;
}
offset = 1;
BB->numInsts = 0;
BB->insts = &bcfunc->allinsts[bcfunc->insn_idx];
while (!last) {
unsigned numOp;
if (buffer[offset] == 'T') {
last = 1;
offset++;
/* terminators are void */
inst.type = 0;
inst.dest = 0;
} else {
inst.type = readNumber(buffer, &offset, len, &ok);
inst.dest = readNumber(buffer, &offset, len, &ok);
}
inst.opcode = readFixedNumber(buffer, &offset, len, &ok, 2);
if (!ok) {
cli_errmsg("Invalid type or operand\n");
return CL_EMALFDB;
}
if (inst.opcode >= OP_BC_INVALID) {
cli_errmsg("Invalid opcode: %u\n", inst.opcode);
return CL_EMALFDB;
}
switch (inst.opcode) {
case OP_BC_JMP:
inst.u.jump = readBBID(bcfunc, buffer, &offset, len, &ok);
break;
case OP_BC_RET:
inst.type = readNumber(buffer, &offset, len, &ok);
inst.u.unaryop = readOperand(bcfunc, buffer, &offset, len, &ok);
break;
case OP_BC_BRANCH:
inst.u.branch.condition = readOperand(bcfunc, buffer, &offset, len, &ok);
inst.u.branch.br_true = readBBID(bcfunc, buffer, &offset, len, &ok);
inst.u.branch.br_false = readBBID(bcfunc, buffer, &offset, len, &ok);
break;
case OP_BC_CALL_API:/* fall-through */
case OP_BC_CALL_DIRECT:
numOp = readFixedNumber(buffer, &offset, len, &ok, 1);
if (ok) {
inst.u.ops.numOps = numOp;
inst.u.ops.opsizes=NULL;
if (!numOp) {
inst.u.ops.ops = NULL;
} else {
inst.u.ops.ops = cli_calloc(numOp, sizeof(*inst.u.ops.ops));
if (!inst.u.ops.ops) {
cli_errmsg("Out of memory allocating operands\n");
return CL_EMEM;
}
}
if (inst.opcode == OP_BC_CALL_DIRECT)
inst.u.ops.funcid = readFuncID(bc, buffer, &offset, len, &ok);
else
inst.u.ops.funcid = readAPIFuncID(bc, buffer, &offset, len, &ok);
for (i=0;i<numOp;i++) {
inst.u.ops.ops[i] = readOperand(bcfunc, buffer, &offset, len, &ok);
}
}
break;
case OP_BC_ZEXT:
case OP_BC_SEXT:
case OP_BC_TRUNC:
inst.u.cast.source = readOperand(bcfunc, buffer, &offset, len, &ok);
inst.u.cast.mask = bcfunc->types[inst.u.cast.source];
if (inst.u.cast.mask == 1)
inst.u.cast.size = 0;
else if (inst.u.cast.mask <= 8)
inst.u.cast.size = 1;
else if (inst.u.cast.mask <= 16)
inst.u.cast.size = 2;
else if (inst.u.cast.mask <= 32)
inst.u.cast.size = 3;
else if (inst.u.cast.mask <= 64)
inst.u.cast.size = 4;
/* calculate mask */
if (inst.opcode != OP_BC_SEXT)
inst.u.cast.mask = inst.u.cast.mask != 64 ?
(1ull<<inst.u.cast.mask)-1 :
~0ull;
break;
case OP_BC_GEP1:
case OP_BC_GEPZ:
inst.u.three[0] = readNumber(buffer, &offset, len, &ok);
inst.u.three[1] = readOperand(bcfunc, buffer, &offset, len, &ok);
inst.u.three[2] = readOperand(bcfunc, buffer, &offset, len, &ok);
break;
case OP_BC_GEPN:
numOp = readFixedNumber(buffer, &offset, len, &ok, 1);
if (ok) {
inst.u.ops.numOps = numOp+2;
inst.u.ops.opsizes = NULL;
inst.u.ops.ops = cli_calloc(numOp+2, sizeof(*inst.u.ops.ops));
if (!inst.u.ops.ops) {
cli_errmsg("Out of memory allocating operands\n");
return CL_EMEM;
}
inst.u.ops.ops[0] = readNumber(buffer, &offset, len, &ok);
for (i=1;i<numOp+2;i++)
inst.u.ops.ops[i] = readOperand(bcfunc, buffer, &offset, len, &ok);
}
break;
case OP_BC_ICMP_EQ:
case OP_BC_ICMP_NE:
case OP_BC_ICMP_UGT:
case OP_BC_ICMP_UGE:
case OP_BC_ICMP_ULT:
case OP_BC_ICMP_ULE:
case OP_BC_ICMP_SGT:
case OP_BC_ICMP_SGE:
case OP_BC_ICMP_SLE:
case OP_BC_ICMP_SLT:
/* instruction type must be correct before readOperand! */
inst.type = readNumber(buffer, &offset, len, &ok);
/* fall-through */
default:
numOp = operand_counts[inst.opcode];
switch (numOp) {
case 0:
break;
case 1:
inst.u.unaryop = readOperand(bcfunc, buffer, &offset, len, &ok);
break;
case 2:
inst.u.binop[0] = readOperand(bcfunc, buffer, &offset, len, &ok);
inst.u.binop[1] = readOperand(bcfunc, buffer, &offset, len, &ok);
break;
case 3:
inst.u.three[0] = readOperand(bcfunc, buffer, &offset, len, &ok);
inst.u.three[1] = readOperand(bcfunc, buffer, &offset, len, &ok);
inst.u.three[2] = readOperand(bcfunc, buffer, &offset, len, &ok);
break;
default:
cli_errmsg("Opcode %u with too many operands: %u?\n", inst.opcode, numOp);
ok = 0;
break;
}
}
if (inst.opcode == OP_BC_STORE) {
int16_t t = get_optype(bcfunc, inst.u.binop[0]);
if (t)
inst.type = t;
}
if (inst.opcode == OP_BC_COPY)
inst.type = get_optype(bcfunc, inst.u.binop[1]);
if (!ok) {
cli_errmsg("Invalid instructions or operands\n");
return CL_EMALFDB;
}
if (bcfunc->insn_idx + BB->numInsts >= bcfunc->numInsts) {
cli_errmsg("More instructions than declared in total: %u > %u!\n",
bcfunc->insn_idx+BB->numInsts, bcfunc->numInsts);
return CL_EMALFDB;
}
inst.interp_op = inst.opcode*5;
if (inst.type > 1) {
if (inst.type <= 8)
inst.interp_op += 1;
else if (inst.type <= 16)
inst.interp_op += 2;
else if (inst.type <= 32)
inst.interp_op += 3;
else if (inst.type <= 65)
inst.interp_op += 4;
else {
cli_dbgmsg("unknown inst type: %d\n", inst.type);
}
}
BB->insts[BB->numInsts++] = inst;
}
if (bb+1 == bc->funcs[func].numBB) {
if (buffer[offset] != 'E') {
cli_errmsg("Missing basicblock terminator, got: %c\n", buffer[offset]);
return CL_EMALFDB;
}
offset++;
}
if (buffer[offset] == 'D') {
unsigned num;
offset += 3;
if (offset >= len)
return CL_EMALFDB;
num = readNumber(buffer, &offset, len, &ok);
if (!ok)
return CL_EMALFDB;
if (num != bcfunc->numInsts) {
cli_errmsg("invalid number of dbg nodes, expected: %u, got: %u\n", bcfunc->numInsts, num);
return CL_EMALFDB;
}
bcfunc->dbgnodes = cli_malloc(num*sizeof(*bcfunc->dbgnodes));
if (!bcfunc->dbgnodes) {
cli_errmsg("Unable to allocate memory for dbg nodes: %u\n", num*sizeof(*bcfunc->dbgnodes));
return CL_EMEM;
}
for (i=0;i<num;i++) {
bcfunc->dbgnodes[i] = readNumber(buffer, &offset, len, &ok);
if (!ok)
return CL_EMALFDB;
}
}
if (offset != len) {
cli_errmsg("Trailing garbage in basicblock: %d extra bytes\n",
len-offset);
return CL_EMALFDB;
}
bcfunc->numBytes = 0;
bcfunc->insn_idx += BB->numInsts;
return CL_SUCCESS;
}
enum parse_state {
PARSE_BC_TYPES=0,
PARSE_BC_APIS,
PARSE_BC_GLOBALS,
PARSE_BC_LSIG,
PARSE_MD_OPT_HEADER,
PARSE_FUNC_HEADER,
PARSE_BB,
PARSE_SKIP
};
struct sigperf_elem {
const char * bc_name;
uint64_t usecs;
unsigned long run_count;
unsigned long match_count;
};
static int sigelem_comp(const void * a, const void * b)
{
const struct sigperf_elem *ela = a;
const struct sigperf_elem *elb = b;
return elb->usecs/elb->run_count - ela->usecs/ela->run_count;
}
void cli_sigperf_print()
{
struct sigperf_elem stats[MAX_BC], *elem = stats;
int i, elems = 0, max_name_len = 0, name_len;
if (!g_sigid || !g_sigevents) {
cli_warnmsg("cli_sigperf_print: statistics requested but no bytecodes were loaded!\n");
return;
}
memset(stats, 0, sizeof(stats));
for (i=0;i<MAX_BC;i++) {
union ev_val val;
uint32_t count;
const char * name = cli_event_get_name(g_sigevents, i*BC_EVENTS_PER_SIG);
cli_event_get(g_sigevents, i*BC_EVENTS_PER_SIG, &val, &count);
if (!count) {
if (name)
cli_dbgmsg("No event triggered for %s\n", name);
continue;
}
if (name)
name_len = strlen(name);
else
name_len = 0;
if (name_len > max_name_len)
max_name_len = name_len;
elem->bc_name = name?name:"\"noname\"";
elem->usecs = val.v_int;
elem->run_count = count;
cli_event_get(g_sigevents, i*BC_EVENTS_PER_SIG+1, &val, &count);
elem->match_count = count;
elem++;
elems++;
}
if (max_name_len < strlen("Bytecode name"))
max_name_len = strlen("Bytecode name");
cli_qsort(stats, elems, sizeof(struct sigperf_elem), sigelem_comp);
elem = stats;
/* name runs matches microsecs avg */
cli_infomsg (NULL, "%-*s %*s %*s %*s %*s\n", max_name_len, "Bytecode name",
8, "#runs", 8, "#matches", 12, "usecs total", 9, "usecs avg");
cli_infomsg (NULL, "%-*s %*s %*s %*s %*s\n", max_name_len, "=============",
8, "=====", 8, "========", 12, "===========", 9, "=========");
while (elem->run_count) {
cli_infomsg (NULL, "%-*s %*lu %*lu %*" PRIu64 " %*.2f\n", max_name_len,
elem->bc_name, 8, elem->run_count, 8, elem->match_count,
12, elem->usecs, 9, (double)elem->usecs/elem->run_count);
elem++;
}
}
static void sigperf_events_init(struct cli_bc *bc)
{
int ret;
char * bc_name;
if (!g_sigevents)
g_sigevents = cli_events_new(MAX_BC_SIGEVENT_ID);
if (!g_sigevents) {
cli_errmsg("No memory for events table\n");
return;
}
if (g_sigid > MAX_BC_SIGEVENT_ID - BC_EVENTS_PER_SIG - 1) {
cli_errmsg("sigperf_events_init: events table full. Increase MAX_BC\n");
return;
}
if (!(bc_name = bc->lsig)) {
if (!(bc_name = bc->hook_name)) {
cli_dbgmsg("cli_event_define error for time event id %d\n", bc->sigtime_id);
return;
}
}
cli_dbgmsg("sigperf_events_init(): adding sig ids starting %u for %s\n", g_sigid, bc_name);
/* register time event */
bc->sigtime_id = g_sigid;
ret = cli_event_define(g_sigevents, g_sigid++, bc_name, ev_time, multiple_sum);
if (ret) {
cli_errmsg("sigperf_events_init: cli_event_define() error for time event id %d\n", bc->sigtime_id);
bc->sigtime_id = MAX_BC_SIGEVENT_ID+1;
return;
}
/* register match count */
bc->sigmatch_id = g_sigid;
ret = cli_event_define(g_sigevents, g_sigid++, bc_name, ev_int, multiple_sum);
if (ret) {
cli_errmsg("sigperf_events_init: cli_event_define() error for matches event id %d\n", bc->sigmatch_id);
bc->sigmatch_id = MAX_BC_SIGEVENT_ID+1;
return;
}
}
void cli_sigperf_events_destroy()
{
cli_events_free(g_sigevents);
}
int cli_bytecode_load(struct cli_bc *bc, FILE *f, struct cli_dbio *dbio, int trust, int sigperf)
{
unsigned row = 0, current_func = 0, bb=0;
char *buffer;
unsigned linelength=0;
char firstbuf[FILEBUFF];
enum parse_state state;
int rc, end=0;
memset(bc, 0, sizeof(*bc));
cli_dbgmsg("Loading %s bytecode\n", trust ? "trusted" : "untrusted");
bc->trusted = trust;
if (!f && !dbio) {
cli_errmsg("Unable to load bytecode (null file)\n");
return CL_ENULLARG;
}
if (!cli_dbgets(firstbuf, FILEBUFF, f, dbio)) {
cli_errmsg("Unable to load bytecode (empty file)\n");
return CL_EMALFDB;
}
cli_chomp(firstbuf);
rc = parseHeader(bc, (unsigned char*)firstbuf, &linelength);
state = PARSE_BC_LSIG;
if (rc == CL_BREAK) {
const char *len = strchr(firstbuf, ':');
bc->state = bc_skip;
if (!linelength) {
linelength = len ? atoi(len+1) : 4096;
}
if (linelength < 4096)
linelength = 4096;
cli_dbgmsg("line: %d\n", linelength);
state = PARSE_SKIP;
rc = CL_SUCCESS;
}
if (rc != CL_SUCCESS) {
cli_errmsg("Error at bytecode line %u\n", row);
return rc;
}
buffer = cli_malloc(linelength);
if (!buffer) {
cli_errmsg("Out of memory allocating line of length %u\n", linelength);
return CL_EMEM;
}
while (cli_dbgets(buffer, linelength, f, dbio) && !end) {
cli_chomp(buffer);
row++;
switch (state) {
case PARSE_BC_LSIG:
rc = parseLSig(bc, buffer);
#if 0
DEAD CODE
if (rc == CL_BREAK) /* skip */ { //FIXME: parseLSig always returns CL_SUCCESS
bc->state = bc_skip;
state = PARSE_SKIP;
continue;
}
if (rc != CL_SUCCESS) { //FIXME: parseLSig always returns CL_SUCCESS
cli_errmsg("Error at bytecode line %u\n", row);
free(buffer);
return rc;
}
#endif
state = PARSE_BC_TYPES;
break;
case PARSE_BC_TYPES:
rc = parseTypes(bc, (unsigned char*)buffer);
if (rc != CL_SUCCESS) {
cli_errmsg("Error at bytecode line %u\n", row);
free(buffer);
return rc;
}
state = PARSE_BC_APIS;
break;
case PARSE_BC_APIS:
rc = parseApis(bc, (unsigned char*)buffer);
if (rc == CL_BREAK) /* skip */ {
bc->state = bc_skip;
state = PARSE_SKIP;
continue;
}
if (rc != CL_SUCCESS) {
cli_errmsg("Error at bytecode line %u\n", row);
free(buffer);
return rc;
}
state = PARSE_BC_GLOBALS;
break;
case PARSE_BC_GLOBALS:
rc = parseGlobals(bc, (unsigned char*)buffer);
if (rc == CL_BREAK) /* skip */ {
bc->state = bc_skip;
state = PARSE_SKIP;
continue;
}
if (rc != CL_SUCCESS) {
cli_errmsg("Error at bytecode line %u\n", row);
free(buffer);
return rc;
}
state = PARSE_MD_OPT_HEADER;
break;
case PARSE_MD_OPT_HEADER:
if (buffer[0] == 'D') {
rc = parseMD(bc, (unsigned char*)buffer);
if (rc != CL_SUCCESS) {
cli_errmsg("Error at bytecode line %u\n", row);
free(buffer);
return rc;
}
break;
}
/* fall-through */
case PARSE_FUNC_HEADER:
if (*buffer == 'S') {
end = 1;
break;
}
rc = parseFunctionHeader(bc, current_func, (unsigned char*)buffer);
if (rc != CL_SUCCESS) {
cli_errmsg("Error at bytecode line %u\n", row);
free(buffer);
return rc;
}
bb = 0;
state = PARSE_BB;
break;
case PARSE_BB:
rc = parseBB(bc, current_func, bb++, (unsigned char*)buffer);
if (rc != CL_SUCCESS) {
cli_errmsg("Error at bytecode line %u\n", row);
free(buffer);
return rc;
}
if (bb >= bc->funcs[current_func].numBB) {
if (bc->funcs[current_func].insn_idx != bc->funcs[current_func].numInsts) {
cli_errmsg("Parsed different number of instructions than declared: %u != %u\n",
bc->funcs[current_func].insn_idx, bc->funcs[current_func].numInsts);
free(buffer);
return CL_EMALFDB;
}
cli_dbgmsg("Parsed %u BBs, %u instructions\n",
bb, bc->funcs[current_func].numInsts);
state = PARSE_FUNC_HEADER;
current_func++;
}
break;
case PARSE_SKIP:
/* stop at S (source code), readdb.c knows how to skip this one
* */
if (buffer[0] == 'S')
end = 1;
/* noop parse, but we need to use dbgets with dynamic buffer,
* otherwise we get 'Line too long for provided buffer' */
break;
}
}
free(buffer);
cli_dbgmsg("Parsed %d functions\n", current_func);
if (sigperf)
sigperf_events_init(bc);
if (current_func != bc->num_func && bc->state != bc_skip) {
cli_errmsg("Loaded less functions than declared: %u vs. %u\n",
current_func, bc->num_func);
return CL_EMALFDB;
}
return CL_SUCCESS;
}
static struct {
enum bc_events id;
const char *name;
enum ev_type type;
enum multiple_handling multiple;
} bc_events[] = {
{BCEV_VIRUSNAME, "virusname", ev_string, multiple_last},
{BCEV_EXEC_RETURNVALUE, "returnvalue", ev_int, multiple_last},
{BCEV_WRITE, "bcapi_write", ev_data_fast, multiple_sum},
{BCEV_OFFSET, "read offset", ev_int, multiple_sum},
{BCEV_READ, "read data", ev_data_fast, multiple_sum},
//{BCEV_READ, "read data", ev_data, multiple_concat},
{BCEV_DBG_STR, "debug message", ev_data_fast, multiple_sum},
{BCEV_DBG_INT, "debug int", ev_int, multiple_sum},
{BCEV_MEM_1, "memmem 1", ev_data_fast, multiple_sum},
{BCEV_MEM_2, "memmem 2", ev_data_fast, multiple_sum},
{BCEV_FIND, "find", ev_data_fast, multiple_sum},
{BCEV_EXTRACTED, "extracted files", ev_int, multiple_sum},
{BCEV_READ_ERR, "read errors", ev_int, multiple_sum},
{BCEV_DISASM_FAIL, "disasm fails", ev_int, multiple_sum},
{BCEV_EXEC_TIME, "bytecode execute", ev_time, multiple_sum}
};
static int register_events(cli_events_t *ev)
{
unsigned i;
for (i=0;i<sizeof(bc_events)/sizeof(bc_events[0]);i++) {
if (cli_event_define(ev, bc_events[i].id, bc_events[i].name, bc_events[i].type,
bc_events[i].multiple) == -1)
return -1;
}
return 0;
}
int cli_bytecode_run(const struct cli_all_bc *bcs, const struct cli_bc *bc, struct cli_bc_ctx *ctx)
{
int ret = CL_SUCCESS;
struct cli_bc_inst inst;
struct cli_bc_func func;
cli_events_t *jit_ev = NULL, *interp_ev = NULL;
int test_mode = 0;
cli_ctx *cctx =(cli_ctx*)ctx->ctx;
if (!ctx || !ctx->bc || !ctx->func)
return CL_ENULLARG;
if (ctx->numParams && (!ctx->values || !ctx->operands))
return CL_ENULLARG;
if (cctx && cctx->engine->bytecode_mode == CL_BYTECODE_MODE_TEST)
test_mode = 1;
if (bc->state == bc_loaded) {
cli_errmsg("bytecode has to be prepared either for interpreter or JIT!\n");
return CL_EARG;
}
if (bc->state == bc_disabled) {
cli_dbgmsg("bytecode triggered but running bytecodes is disabled\n");
return CL_SUCCESS;
}
if (cctx)
cli_event_time_start(cctx->perf, PERFT_BYTECODE);
ctx->env = &bcs->env;
context_safe(ctx);
if (test_mode) {
jit_ev = cli_events_new(BCEV_LASTEVENT);
interp_ev = cli_events_new(BCEV_LASTEVENT);
if (!jit_ev || !interp_ev) {
cli_events_free(jit_ev);
cli_events_free(interp_ev);
return CL_EMEM;
}
if (register_events(jit_ev) == -1 ||
register_events(interp_ev) == -1) {
cli_events_free(jit_ev);
cli_events_free(interp_ev);
return CL_EBYTECODE_TESTFAIL;
}
}
cli_event_time_start(g_sigevents, bc->sigtime_id);
if (bc->state == bc_interp || test_mode) {
ctx->bc_events = interp_ev;
memset(&func, 0, sizeof(func));
func.numInsts = 1;
func.numValues = 1;
func.numConstants = 0;
func.numBytes = ctx->bytes;
memset(ctx->values+ctx->bytes-8, 0, 8);
inst.opcode = OP_BC_CALL_DIRECT;
inst.interp_op = OP_BC_CALL_DIRECT*5;
inst.dest = func.numArgs;
inst.type = 0;
inst.u.ops.numOps = ctx->numParams;
inst.u.ops.funcid = ctx->funcid;
inst.u.ops.ops = ctx->operands;
inst.u.ops.opsizes = ctx->opsizes;
cli_dbgmsg("Bytecode %u: executing in interpeter mode\n", bc->id);
ctx->on_jit = 0;
cli_event_time_start(interp_ev, BCEV_EXEC_TIME);
ret = cli_vm_execute(ctx->bc, ctx, &func, &inst);
cli_event_time_stop(interp_ev, BCEV_EXEC_TIME);
cli_event_int(interp_ev, BCEV_EXEC_RETURNVALUE, ret);
cli_event_string(interp_ev, BCEV_VIRUSNAME, ctx->virname);
/* need to be called here to catch any extracted but not yet scanned files
*/
if (ctx->outfd)
cli_bcapi_extract_new(ctx, -1);
}
if (bc->state == bc_jit || test_mode) {
if (test_mode) {
ctx->off = 0;
}
ctx->bc_events = jit_ev;
cli_dbgmsg("Bytecode %u: executing in JIT mode\n", bc->id);
ctx->on_jit = 1;
cli_event_time_start(jit_ev, BCEV_EXEC_TIME);
ret = cli_vm_execute_jit(bcs, ctx, &bc->funcs[ctx->funcid]);
cli_event_time_stop(jit_ev, BCEV_EXEC_TIME);
cli_event_int(jit_ev, BCEV_EXEC_RETURNVALUE, ret);
cli_event_string(jit_ev, BCEV_VIRUSNAME, ctx->virname);
/* need to be called here to catch any extracted but not yet scanned files
*/
if (ctx->outfd)
cli_bcapi_extract_new(ctx, -1);
}
cli_event_time_stop(g_sigevents, bc->sigtime_id);
if (ctx->virname)
cli_event_count(g_sigevents, bc->sigmatch_id);
if (test_mode) {
unsigned interp_errors = cli_event_errors(interp_ev);
unsigned jit_errors = cli_event_errors(jit_ev);
unsigned interp_warns = 0, jit_warns = 0;
int ok = 1;
enum bc_events evid;
if (interp_errors || jit_errors) {
cli_infomsg(cctx, "bytecode %d encountered %u JIT and %u interpreter errors\n",
bc->id, interp_errors, jit_errors);
ok = 0;
}
if (!ctx->no_diff && cli_event_diff_all(interp_ev, jit_ev, NULL)) {
cli_infomsg(cctx, "bytecode %d execution different with JIT and interpreter, see --debug for details\n",
bc->id);
ok = 0;
}
for (evid=BCEV_API_WARN_BEGIN+1;evid < BCEV_API_WARN_END;evid++) {
union ev_val v;
uint32_t count = 0;
cli_event_get(interp_ev, evid, &v, &count);
interp_warns += count;
count = 0;
cli_event_get(jit_ev, evid, &v, &count);
jit_warns += count;
}
if (interp_warns || jit_warns) {
cli_infomsg(cctx, "bytecode %d encountered %u JIT and %u interpreter warnings\n",
bc->id, interp_warns, jit_warns);
ok = 0;
}
/*cli_event_debug(jit_ev, BCEV_EXEC_TIME);
cli_event_debug(interp_ev, BCEV_EXEC_TIME);
cli_event_debug(g_sigevents, bc->sigtime_id);*/
if (!ok) {
cli_events_free(jit_ev);
cli_events_free(interp_ev);
return CL_EBYTECODE_TESTFAIL;
}
}
cli_events_free(jit_ev);
cli_events_free(interp_ev);
if (cctx)
cli_event_time_stop(cctx->perf, PERFT_BYTECODE);
return ret;
}
uint64_t cli_bytecode_context_getresult_int(struct cli_bc_ctx *ctx)
{
return *(uint32_t*)ctx->values;/*XXX*/
}
void cli_bytecode_destroy(struct cli_bc *bc)
{
unsigned i, j, k;
free(bc->metadata.compiler);
free(bc->metadata.sigmaker);
if (bc->funcs) {
for (i=0;i<bc->num_func;i++) {
struct cli_bc_func *f = &bc->funcs[i];
if (!f)
continue;
free(f->types);
for (j=0;j<f->numBB;j++) {
struct cli_bc_bb *BB = &f->BB[j];
for(k=0;k<BB->numInsts;k++) {
struct cli_bc_inst *ii = &BB->insts[k];
if (operand_counts[ii->opcode] > 3 ||
ii->opcode == OP_BC_CALL_DIRECT || ii->opcode == OP_BC_CALL_API) {
free(ii->u.ops.ops);
free(ii->u.ops.opsizes);
}
}
}
free(f->BB);
free(f->allinsts);
free(f->constants);
}
free(bc->funcs);
}
if (bc->types) {
for (i=NUM_STATIC_TYPES;i<bc->num_types;i++) {
if (bc->types[i].containedTypes)
free(bc->types[i].containedTypes);
}
free(bc->types);
}
if (bc->globals) {
for (i=0;i<bc->num_globals;i++) {
free(bc->globals[i]);
}
free(bc->globals);
}
if (bc->dbgnodes) {
for (i=0;i<bc->dbgnode_cnt;i++) {
for (j=0;j<bc->dbgnodes[i].numelements;j++) {
struct cli_bc_dbgnode_element *el = &bc->dbgnodes[i].elements[j];
if (el && el->string)
free(el->string);
}
}
free(bc->dbgnodes);
}
free(bc->globaltys);
if (bc->uses_apis)
cli_bitset_free(bc->uses_apis);
free(bc->lsig);
free(bc->hook_name);
free(bc->globalBytes);
memset(bc, 0, sizeof(*bc));
}
#define MAP(val) do { operand_t o = val; \
if (o & 0x80000000) {\
o &= 0x7fffffff;\
if (o > bc->num_globals) {\
cli_errmsg("bytecode: global out of range: %u > %u, for instruction %u in function %u\n",\
o, (unsigned)bc->num_globals, j, i);\
free(map);\
free(gmap);\
return CL_EBYTECODE;\
}\
val = 0x80000000 | gmap[o];\
break;\
}\
if (o >= totValues) {\
cli_errmsg("bytecode: operand out of range: %u > %u, for instruction %u in function %u\n", o, totValues, j, i);\
free(map);\
free(gmap);\
return CL_EBYTECODE;\
}\
val = map[o]; } while (0)
#define MAPPTR(val) {\
if ((val < bcfunc->numValues) && bcfunc->types[val]&0x8000)\
val = map[val] | 0x40000000;\
else\
MAP(val);\
}
static inline int64_t ptr_compose(int32_t id, uint32_t offset)
{
uint64_t i = id;
return (i << 32) | offset;
}
static inline int get_geptypesize(const struct cli_bc *bc, uint16_t tid)
{
const struct cli_bc_type *ty;
if (tid >= bc->num_types+65) {
cli_errmsg("bytecode: typeid out of range %u >= %u\n", tid, bc->num_types);
return -1;
}
if (tid <= 64) {
cli_errmsg("bytecode: invalid type for gep (%u)\n", tid);
return -1;
}
ty = &bc->types[tid - 65];
if (ty->kind != DPointerType) {
cli_errmsg("bytecode: invalid gep type, must be pointer: %u\n", tid);
return -1;
}
return typesize(bc, ty->containedTypes[0]);
}
static int calc_gepz(struct cli_bc *bc, struct cli_bc_func *func, uint16_t tid, operand_t op)
{
unsigned off = 0, i;
uint32_t *gepoff;
const struct cli_bc_type *ty;
if (tid >= bc->num_types + 65) {
cli_errmsg("bytecode: typeid out of range %u >= %u\n", tid, bc->num_types);
return -1;
}
if (tid <= 65) {
cli_errmsg("bytecode: invalid type for gep (%u)\n", tid);
return -1;
}
ty = &bc->types[tid - 65];
if (ty->kind != DPointerType || ty->containedTypes[0] < 65) {
cli_errmsg("bytecode: invalid gep type, must be pointer to nonint: %u\n", tid);
return -1;
}
ty = &bc->types[ty->containedTypes[0] - 65];
if (ty->kind != DStructType && ty->kind != DPackedStructType)
return 0;
gepoff = (uint32_t*)&func->constants[op - func->numValues];
if (*gepoff >= ty->numElements) {
cli_errmsg("bytecode: gep offset out of range: %d >= %d\n",(uint32_t)*gepoff, ty->numElements);
return -1;
}
for (i=0;i<*gepoff;i++) {
off += typesize(bc, ty->containedTypes[i]);
}
*gepoff = off;
return 1;
}
static int cli_bytecode_prepare_interpreter(struct cli_bc *bc)
{
unsigned i, j, k;
uint64_t *gmap;
unsigned bcglobalid = cli_apicall_maxglobal - _FIRST_GLOBAL+2;
int ret=CL_SUCCESS;
bc->numGlobalBytes = 0;
gmap = cli_malloc(bc->num_globals*sizeof(*gmap));
if (!gmap) {
cli_errmsg("interpreter: Unable to allocate memory for global map: %u\n", bc->num_globals*sizeof(*gmap));
return CL_EMEM;
}
for (j=0;j<bc->num_globals;j++) {
uint16_t ty = bc->globaltys[j];
unsigned align = typealign(bc, ty);
assert(align);
bc->numGlobalBytes = (bc->numGlobalBytes + align-1)&(~(align-1));
gmap[j] = bc->numGlobalBytes;
bc->numGlobalBytes += typesize(bc, ty);
}
if (bc->numGlobalBytes) {
bc->globalBytes = cli_calloc(1, bc->numGlobalBytes);
if (!bc->globalBytes) {
cli_errmsg("interpreter: Unable to allocate memory for globalBytes: %u\n", bc->numGlobalBytes);
free(gmap);
return CL_EMEM;
}
} else
bc->globalBytes = NULL;
for (j=0;j<bc->num_globals;j++) {
struct cli_bc_type *ty;
if (bc->globaltys[j] < 65)
continue;
ty = &bc->types[bc->globaltys[j]-65];
switch (ty->kind) {
case DPointerType:
{
uint64_t ptr;
if (bc->globals[j][1] >= _FIRST_GLOBAL) {
ptr = ptr_compose(bc->globals[j][1] - _FIRST_GLOBAL + 1,
bc->globals[j][0]);
} else {
if (bc->globals[j][1] > bc->num_globals)
continue;
ptr = ptr_compose(bcglobalid,
gmap[bc->globals[j][1]] + bc->globals[j][0]);
}
*(uint64_t*)&bc->globalBytes[gmap[j]] = ptr;
break;
}
case DArrayType:
{
unsigned elsize, i, off = gmap[j];
/* TODO: support other than ints in arrays */
elsize = typesize(bc, ty->containedTypes[0]);
switch (elsize) {
case 1:
for(i=0;i<ty->numElements;i++)
bc->globalBytes[off+i] = bc->globals[j][i];
break;
case 2:
for(i=0;i<ty->numElements;i++)
*(uint16_t*)&bc->globalBytes[off+i*2] = bc->globals[j][i];
break;
case 4:
for(i=0;i<ty->numElements;i++)
*(uint32_t*)&bc->globalBytes[off+i*4] = bc->globals[j][i];
break;
case 8:
for(i=0;i<ty->numElements;i++)
*(uint64_t*)&bc->globalBytes[off+i*8] = bc->globals[j][i];
break;
default:
cli_dbgmsg("interpreter: unsupported elsize: %u\n", elsize);
}
break;
}
default:
/*TODO*/
if (!bc->globals[j][1])
continue; /* null */
break;
}
}
for (i=0;i<bc->num_func && ret == CL_SUCCESS;i++) {
struct cli_bc_func *bcfunc = &bc->funcs[i];
unsigned totValues = bcfunc->numValues + bcfunc->numConstants + bc->num_globals;
unsigned *map = cli_malloc(sizeof(*map)*totValues);
if (!map) {
cli_errmsg("interpreter: Unable to allocate memory for map: %u\n", sizeof(*map)*totValues);
free(gmap);
return CL_EMEM;
}
bcfunc->numBytes = 0;
for (j=0;j<bcfunc->numValues;j++) {
uint16_t ty = bcfunc->types[j];
unsigned align;
align = typealign(bc, ty);
assert(!ty || typesize(bc, ty));
assert(align);
bcfunc->numBytes = (bcfunc->numBytes + align-1)&(~(align-1));
map[j] = bcfunc->numBytes;
/* printf("%d -> %d, %u\n", j, map[j], typesize(bc, ty)); */
bcfunc->numBytes += typesize(bc, ty);
/* TODO: don't allow size 0, it is always a bug! */
}
bcfunc->numBytes = (bcfunc->numBytes + 7)&~7;
for (j=0;j<bcfunc->numConstants;j++) {
map[bcfunc->numValues+j] = bcfunc->numBytes;
bcfunc->numBytes += 8;
}
for (j=0;j<bcfunc->numInsts && ret == CL_SUCCESS;j++) {
struct cli_bc_inst *inst = &bcfunc->allinsts[j];
inst->dest = map[inst->dest];
switch (inst->opcode) {
case OP_BC_ADD:
case OP_BC_SUB:
case OP_BC_MUL:
case OP_BC_UDIV:
case OP_BC_SDIV:
case OP_BC_UREM:
case OP_BC_SREM:
case OP_BC_SHL:
case OP_BC_LSHR:
case OP_BC_ASHR:
case OP_BC_AND:
case OP_BC_OR:
case OP_BC_XOR:
case OP_BC_ICMP_EQ:
case OP_BC_ICMP_NE:
case OP_BC_ICMP_UGT:
case OP_BC_ICMP_UGE:
case OP_BC_ICMP_ULT:
case OP_BC_ICMP_ULE:
case OP_BC_ICMP_SGT:
case OP_BC_ICMP_SGE:
case OP_BC_ICMP_SLT:
case OP_BC_ICMP_SLE:
case OP_BC_COPY:
case OP_BC_STORE:
MAP(inst->u.binop[0]);
MAP(inst->u.binop[1]);
break;
case OP_BC_SEXT:
case OP_BC_ZEXT:
case OP_BC_TRUNC:
MAP(inst->u.cast.source);
break;
case OP_BC_BRANCH:
MAP(inst->u.branch.condition);
break;
case OP_BC_JMP:
break;
case OP_BC_RET:
MAP(inst->u.unaryop);
break;
case OP_BC_SELECT:
MAP(inst->u.three[0]);
MAP(inst->u.three[1]);
MAP(inst->u.three[2]);
break;
case OP_BC_CALL_API:/* fall-through */
case OP_BC_CALL_DIRECT:
{
struct cli_bc_func *target = NULL;
if (inst->opcode == OP_BC_CALL_DIRECT) {
target = &bc->funcs[inst->u.ops.funcid];
if (inst->u.ops.funcid > bc->num_func) {
cli_errmsg("bytecode: called function out of range: %u > %u\n", inst->u.ops.funcid, bc->num_func);
ret = CL_EBYTECODE;
}
else if (inst->u.ops.numOps != target->numArgs) {
cli_errmsg("bytecode: call operands don't match function prototype\n");
ret = CL_EBYTECODE;
}
} else {
/* APIs have at most 2 parameters always */
if (inst->u.ops.numOps > 5) {
cli_errmsg("bytecode: call operands don't match function prototype\n");
ret = CL_EBYTECODE;
}
}
if (ret != CL_SUCCESS)
break;
if (inst->u.ops.numOps > 0) {
inst->u.ops.opsizes = cli_malloc(sizeof(*inst->u.ops.opsizes)*inst->u.ops.numOps);
if (!inst->u.ops.opsizes) {
cli_errmsg("Out of memory when allocating operand sizes\n");
ret = CL_EMEM;
break;
}
} else {
inst->u.ops.opsizes = NULL;
break;
}
for (k=0;k<inst->u.ops.numOps;k++) {
MAPPTR(inst->u.ops.ops[k]);
if (inst->opcode == OP_BC_CALL_DIRECT)
inst->u.ops.opsizes[k] = typesize(bc, target->types[k]);
else
inst->u.ops.opsizes[k] = 32; /*XXX*/
}
break;
}
case OP_BC_LOAD:
MAPPTR(inst->u.unaryop);
break;
case OP_BC_GEP1:
if (inst->u.three[1]&0x80000000 ||
bcfunc->types[inst->u.binop[1]]&0x8000) {
cli_errmsg("bytecode: gep1 of alloca is not allowed\n");
ret = CL_EBYTECODE;
}
if (ret != CL_SUCCESS)
break;
MAP(inst->u.three[1]);
MAP(inst->u.three[2]);
inst->u.three[0] = get_geptypesize(bc, inst->u.three[0]);
if ((int)(inst->u.three[0]) == -1)
ret = CL_EBYTECODE;
break;
case OP_BC_GEPZ:
/*three[0] is the type*/
if (inst->u.three[1]&0x80000000 ||
bcfunc->types[inst->u.three[1]]&0x8000)
inst->interp_op = 5*(inst->interp_op/5);
else
inst->interp_op = 5*(inst->interp_op/5)+3;
MAP(inst->u.three[1]);
if (calc_gepz(bc, bcfunc, inst->u.three[0], inst->u.three[2]) == -1)
ret = CL_EBYTECODE;
if (ret == CL_SUCCESS)
MAP(inst->u.three[2]);
break;
/* case OP_BC_GEPN:
*TODO
break;*/
case OP_BC_MEMSET:
case OP_BC_MEMCPY:
case OP_BC_MEMMOVE:
case OP_BC_MEMCMP:
MAPPTR(inst->u.three[0]);
MAPPTR(inst->u.three[1]);
MAP(inst->u.three[2]);
break;
case OP_BC_RET_VOID:
case OP_BC_ISBIGENDIAN:
case OP_BC_ABORT:
/* no operands */
break;
case OP_BC_BSWAP16:
case OP_BC_BSWAP32:
case OP_BC_BSWAP64:
MAP(inst->u.unaryop);
break;
case OP_BC_PTRDIFF32:
MAPPTR(inst->u.binop[0]);
MAPPTR(inst->u.binop[1]);
break;
case OP_BC_PTRTOINT64:
MAPPTR(inst->u.unaryop);
break;
default:
cli_warnmsg("Bytecode: unhandled opcode: %d\n", inst->opcode);
ret = CL_EBYTECODE;
}
}
if (map)
free(map);
}
free(gmap);
bc->state = bc_interp;
return ret;
}
static int add_selfcheck(struct cli_all_bc *bcs)
{
struct cli_bc_func *func;
struct cli_bc_inst *inst;
struct cli_bc *bc;
bcs->all_bcs = cli_realloc2(bcs->all_bcs, sizeof(*bcs->all_bcs)*(bcs->count+1));
if (!bcs->all_bcs) {
cli_errmsg("cli_loadcbc: Can't allocate memory for bytecode entry\n");
return CL_EMEM;
}
bc = &bcs->all_bcs[bcs->count++];
memset(bc, 0, sizeof(*bc));
bc->trusted = 1;
bc->num_globals = 1;
bc->globals = cli_calloc(1, sizeof(*bc->globals));
if (!bc->globals) {
cli_errmsg("Failed to allocate memory for globals\n");
return CL_EMEM;
}
bc->globals[0] = cli_calloc(1, sizeof(*bc->globals[0]));
if (!bc->globals[0]) {
cli_errmsg("Failed to allocate memory for globals\n");
return CL_EMEM;
}
bc->globaltys = cli_calloc(1, sizeof(*bc->globaltys));
if (!bc->globaltys) {
cli_errmsg("Failed to allocate memory for globaltypes\n");
return CL_EMEM;
}
bc->globaltys[0] = 32;
*bc->globals[0] = 0;
bc->id = ~0;
bc->kind = 0;
bc->num_types = 5;
bc->num_func = 1;
bc->funcs = cli_calloc(1, sizeof(*bc->funcs));
if (!bc->funcs) {
cli_errmsg("Failed to allocate memory for func\n");
return CL_EMEM;
}
func = bc->funcs;
func->numInsts = 2;
func->numLocals = 1;
func->numValues = 1;
func->numConstants = 1;
func->numBB = 1;
func->returnType = 32;
func->types = cli_calloc(1, sizeof(*func->types));
if (!func->types) {
cli_errmsg("Failed to allocate memory for types\n");
return CL_EMEM;
}
func->types[0] = 32;
func->BB = cli_calloc(1, sizeof(*func->BB));
if (!func->BB) {
cli_errmsg("Failed to allocate memory for BB\n");
return CL_EMEM;
}
func->allinsts = cli_calloc(2, sizeof(*func->allinsts));
if (!func->allinsts) {
cli_errmsg("Failed to allocate memory for insts\n");
return CL_EMEM;
}
func->BB->numInsts = 2;
func->BB->insts = func->allinsts;
func->constants = cli_calloc(1, sizeof(*func->constants));
if (!func->constants) {
cli_errmsg("Failed to allocate memory for constants\n");
return CL_EMEM;
}
func->constants[0] = 0xf00d;
inst = func->allinsts;
inst->opcode = OP_BC_CALL_API;
inst->u.ops.numOps = 1;
inst->u.ops.opsizes = NULL;
inst->u.ops.ops = cli_calloc(1, sizeof(*inst->u.ops.ops));
if (!inst->u.ops.ops) {
cli_errmsg("Failed to allocate memory for instructions\n");
return CL_EMEM;
}
inst->u.ops.ops[0] = 1;
inst->u.ops.funcid = 18; /* test2 */
inst->dest = 0;
inst->type = 32;
inst->interp_op = inst->opcode* 5 + 3;
inst = &func->allinsts[1];
inst->opcode = OP_BC_RET;
inst->type = 32;
inst->u.unaryop = 0;
inst->interp_op = inst->opcode* 5;
bc->state = bc_loaded;
return 0;
}
static int run_selfcheck(struct cli_all_bc *bcs)
{
struct cli_bc_ctx *ctx;
struct cli_bc *bc = &bcs->all_bcs[bcs->count-1];
int rc;
if (bc->state != bc_jit && bc->state != bc_interp) {
cli_errmsg("Failed to prepare selfcheck bytecode\n");
return CL_EBYTECODE;
}
ctx = cli_bytecode_context_alloc();
if (!ctx) {
cli_errmsg("Failed to allocate bytecode context\n");
return CL_EMEM;
}
cli_bytecode_context_setfuncid(ctx, bc, 0);
cli_dbgmsg("bytecode self test running\n");
ctx->bytecode_timeout = 0;
rc = cli_bytecode_run(bcs, bc, ctx);
cli_bytecode_context_destroy(ctx);
if (rc != CL_SUCCESS) {
cli_errmsg("bytecode self test failed: %s\n",
cl_strerror(rc));
} else {
cli_dbgmsg("bytecode self test succeeded\n");
}
return rc;
}
static int selfcheck(int jit, struct cli_bcengine *engine)
{
struct cli_all_bc bcs;
int rc;
memset(&bcs, 0, sizeof(bcs));
bcs.all_bcs = NULL;
bcs.count = 0;
bcs.engine = engine;
rc = add_selfcheck(&bcs);
if (rc == CL_SUCCESS) {
if (jit) {
if (!bcs.engine) {
cli_dbgmsg("bytecode: JIT disabled\n");
rc = CL_BREAK;/* no JIT - not fatal */
} else {
rc = cli_bytecode_prepare_jit(&bcs);
}
} else {
rc = cli_bytecode_prepare_interpreter(bcs.all_bcs);
}
if (rc == CL_SUCCESS)
rc = run_selfcheck(&bcs);
if (rc == CL_BREAK)
rc = CL_SUCCESS;
}
cli_bytecode_destroy(bcs.all_bcs);
free(bcs.all_bcs);
cli_bytecode_done_jit(&bcs, 1);
if (rc != CL_SUCCESS) {
cli_errmsg("Bytecode: failed to run selfcheck in %s mode: %s\n",
jit ? "JIT" : "interpreter", cl_strerror(rc));
}
return rc;
}
static int set_mode(struct cl_engine *engine, enum bytecode_mode mode)
{
if (engine->bytecode_mode == mode)
return 0;
if (engine->bytecode_mode == CL_BYTECODE_MODE_OFF) {
cli_errmsg("bytecode: already turned off, can't turn it on again!\n");
return -1;
}
cli_dbgmsg("Bytecode: mode changed to %d\n", mode);
if (engine->bytecode_mode == CL_BYTECODE_MODE_TEST) {
if (mode == CL_BYTECODE_MODE_OFF || have_clamjit) {
cli_errmsg("bytecode: in test mode but JIT/bytecode is about to be disabled: %d\n", mode);
engine->bytecode_mode = mode;
return -1;
}
return 0;
}
if (engine->bytecode_mode == CL_BYTECODE_MODE_JIT) {
cli_errmsg("bytecode: in JIT mode but JIT is about to be disabled: %d\n", mode);
engine->bytecode_mode = mode;
return -1;
}
engine->bytecode_mode = mode;
return 0;
}
/* runs the first bytecode of the specified kind, or the builtin one if no
* bytecode of that kind is loaded */
static int run_builtin_or_loaded(struct cli_all_bc *bcs, uint8_t kind, const char* builtin_cbc, struct cli_bc_ctx *ctx, const char *desc)
{
unsigned i, builtin = 0, rc = 0;
struct cli_bc *bc = NULL;
for (i=0;i<bcs->count;i++) {
bc = &bcs->all_bcs[i];
if (bc->kind == kind)
break;
}
if (i == bcs->count)
bc = NULL;
if (!bc) {
/* no loaded bytecode found, load the builtin one! */
struct cli_dbio dbio;
bc = cli_calloc(1, sizeof(*bc));
if (!bc) {
cli_errmsg("Out of memory allocating bytecode\n");
return CL_EMEM;
}
builtin = 1;
memset(&dbio, 0, sizeof(dbio));
dbio.usebuf = 1;
dbio.bufpt = dbio.buf = (char*)builtin_cbc;
dbio.bufsize = strlen(builtin_cbc)+1;
if (!dbio.bufsize || dbio.bufpt[dbio.bufsize-2] != '\n') {
cli_errmsg("Invalid builtin bytecode: missing terminator\n");
free(bc);
return CL_EMALFDB;
}
rc = cli_bytecode_load(bc, NULL, &dbio, 1, 0);
if (rc) {
cli_errmsg("Failed to load builtin %s bytecode\n", desc);
free(bc);
return rc;
}
}
rc = cli_bytecode_prepare_interpreter(bc);
if (rc) {
cli_errmsg("Failed to prepare %s %s bytecode for interpreter: %s\n",
builtin ? "builtin" : "loaded", desc, cl_strerror(rc));
}
if (bc->state != bc_interp) {
cli_errmsg("Failed to prepare %s %s bytecode for interpreter\n",
builtin ? "builtin" : "loaded", desc);
rc = CL_EMALFDB;
}
if (!rc) {
cli_bytecode_context_setfuncid(ctx, bc, 0);
cli_dbgmsg("Bytecode: %s running (%s)\n", desc,
builtin ? "builtin" : "loaded");
rc = cli_bytecode_run(bcs, bc, ctx);
}
if (rc) {
cli_errmsg("Failed to execute %s %s bytecode: %s\n",builtin ? "builtin":"loaded",
desc, cl_strerror(rc));
}
if (builtin) {
cli_bytecode_destroy(bc);
free(bc);
}
return rc;
}
int cli_bytecode_prepare2(struct cl_engine *engine, struct cli_all_bc *bcs, unsigned dconfmask)
{
unsigned i, interp = 0, jitok = 0, jitcount=0;
int rc;
struct cli_bc_ctx *ctx;
if (!bcs->count) {
cli_dbgmsg("No bytecodes loaded, not running builtin test\n");
return CL_SUCCESS;
}
engine->bytecode_mode = CL_BYTECODE_MODE_AUTO;
cli_detect_environment(&bcs->env);
switch (bcs->env.arch) {
case arch_i386:
case arch_x86_64:
if (!(dconfmask & BYTECODE_JIT_X86)) {
cli_dbgmsg("Bytecode: disabled on X86 via DCONF\n");
if (set_mode(engine, CL_BYTECODE_MODE_INTERPRETER) == -1)
return CL_EBYTECODE_TESTFAIL;
}
break;
case arch_ppc32:
case arch_ppc64:
if (!(dconfmask & BYTECODE_JIT_PPC)) {
cli_dbgmsg("Bytecode: disabled on PPC via DCONF\n");
if (set_mode(engine, CL_BYTECODE_MODE_INTERPRETER) == -1)
return CL_EBYTECODE_TESTFAIL;
}
break;
case arch_arm:
if (!(dconfmask & BYTECODE_JIT_ARM)) {
cli_dbgmsg("Bytecode: disabled on ARM via DCONF\n");
if (set_mode(engine, CL_BYTECODE_MODE_INTERPRETER) == -1)
return CL_EBYTECODE_TESTFAIL;
}
break;
default:
cli_dbgmsg("Bytecode: JIT not supported on this architecture, falling back\n");
if (set_mode(engine, CL_BYTECODE_MODE_INTERPRETER) == -1)
return CL_EBYTECODE_TESTFAIL;
break;
}
cli_dbgmsg("Bytecode: mode is %d\n", engine->bytecode_mode);
ctx = cli_bytecode_context_alloc();
if (!ctx) {
cli_errmsg("Bytecode: failed to allocate bytecode context\n");
return CL_EMEM;
}
rc = run_builtin_or_loaded(bcs, BC_STARTUP, builtin_bc_startup, ctx, "BC_STARTUP");
if (rc != CL_SUCCESS) {
cli_warnmsg("Bytecode: BC_STARTUP failed to run, disabling ALL bytecodes! Please report to http://bugs.clamav.net\n");
ctx->bytecode_disable_status = 2;
} else {
cli_dbgmsg("Bytecode: disable status is %d\n", ctx->bytecode_disable_status);
rc = cli_bytecode_context_getresult_int(ctx);
/* check magic number, don't use 0 here because it is too easy for a
* buggy bytecode to return 0 */
if ((unsigned int)rc != (unsigned int)0xda7aba5e) {
cli_warnmsg("Bytecode: selftest failed with code %08x. Please report to http://bugs.clamav.net\n",
rc);
if (engine->bytecode_mode == CL_BYTECODE_MODE_TEST)
return CL_EBYTECODE_TESTFAIL;
}
}
switch (ctx->bytecode_disable_status) {
case 1:
if (set_mode(engine, CL_BYTECODE_MODE_INTERPRETER) == -1)
return CL_EBYTECODE_TESTFAIL;
break;
case 2:
if (set_mode(engine, CL_BYTECODE_MODE_OFF) == -1)
return CL_EBYTECODE_TESTFAIL;
break;
default:
break;
}
cli_bytecode_context_destroy(ctx);
if (engine->bytecode_mode != CL_BYTECODE_MODE_INTERPRETER &&
engine->bytecode_mode != CL_BYTECODE_MODE_OFF) {
selfcheck(1, bcs->engine);
rc = cli_bytecode_prepare_jit(bcs);
if (rc == CL_SUCCESS) {
jitok = 1;
cli_dbgmsg("Bytecode: %u bytecode prepared with JIT\n", bcs->count);
if (engine->bytecode_mode != CL_BYTECODE_MODE_TEST)
return CL_SUCCESS;
}
if (engine->bytecode_mode == CL_BYTECODE_MODE_JIT) {
cli_errmsg("Bytecode: JIT required, but not all bytecodes could be prepared with JIT\n");
return CL_EMALFDB;
}
if (rc && engine->bytecode_mode == CL_BYTECODE_MODE_TEST) {
cli_errmsg("Bytecode: Test mode, but not all bytecodes could be prepared with JIT\n");
return CL_EBYTECODE_TESTFAIL;
}
} else {
cli_bytecode_done_jit(bcs, 0);
}
if (!(dconfmask & BYTECODE_INTERPRETER)) {
cli_dbgmsg("Bytecode: needs interpreter, but interpreter is disabled\n");
if (set_mode(engine, CL_BYTECODE_MODE_OFF) == -1)
return CL_EBYTECODE_TESTFAIL;
}
if (engine->bytecode_mode == CL_BYTECODE_MODE_OFF) {
for (i=0;i<bcs->count;i++)
bcs->all_bcs[i].state = bc_disabled;
cli_dbgmsg("Bytecode: ALL bytecodes disabled\n");
return CL_SUCCESS;
}
for (i=0;i<bcs->count;i++) {
struct cli_bc *bc = &bcs->all_bcs[i];
if (bc->state == bc_jit) {
jitcount++;
if (engine->bytecode_mode != CL_BYTECODE_MODE_TEST)
continue;
}
if (bc->state == bc_interp) {
interp++;
continue;
}
rc = cli_bytecode_prepare_interpreter(bc);
if (rc != CL_SUCCESS) {
bc->state = bc_disabled;
cli_warnmsg("Bytecode: %d failed to prepare for interpreter mode\n", bc->id);
return rc;
}
interp++;
}
cli_dbgmsg("Bytecode: %u bytecode prepared with JIT, "
"%u prepared with interpreter, %u total\n", jitcount, interp, bcs->count);
return CL_SUCCESS;
}
int cli_bytecode_init(struct cli_all_bc *allbc)
{
int ret;
memset(allbc, 0, sizeof(*allbc));
ret = cli_bytecode_init_jit(allbc, 0/*XXX*/);
cli_dbgmsg("Bytecode initialized in %s mode\n",
allbc->engine ? "JIT" : "interpreter");
allbc->inited = 1;
return ret;
}
int cli_bytecode_done(struct cli_all_bc *allbc)
{
return cli_bytecode_done_jit(allbc, 0);
}
int cli_bytecode_context_setfile(struct cli_bc_ctx *ctx, fmap_t *map)
{
ctx->fmap = map;
ctx->file_size = map->len + map->offset;
ctx->hooks.filesize = &ctx->file_size;
return 0;
}
int cli_bytecode_runlsig(cli_ctx *cctx, struct cli_target_info *tinfo,
const struct cli_all_bc *bcs, unsigned bc_idx,
const uint32_t* lsigcnt,
const uint32_t *lsigsuboff, fmap_t *map)
{
int ret;
struct cli_bc_ctx ctx;
const struct cli_bc *bc = &bcs->all_bcs[bc_idx-1];
struct cli_pe_hook_data pehookdata;
memset(&ctx, 0, sizeof(ctx));
cli_bytecode_context_setfuncid(&ctx, bc, 0);
ctx.hooks.match_counts = lsigcnt;
ctx.hooks.match_offsets = lsigsuboff;
cli_bytecode_context_setctx(&ctx, cctx);
cli_bytecode_context_setfile(&ctx, map);
if (tinfo && tinfo->status == 1) {
ctx.sections = tinfo->exeinfo.section;
memset(&pehookdata, 0, sizeof(pehookdata));
pehookdata.offset = tinfo->exeinfo.offset;
pehookdata.ep = tinfo->exeinfo.ep;
pehookdata.nsections = tinfo->exeinfo.nsections;
pehookdata.hdr_size = tinfo->exeinfo.hdr_size;
ctx.hooks.pedata = &pehookdata;
ctx.resaddr = tinfo->exeinfo.res_addr;
}
if (bc->hook_lsig_id) {
cli_dbgmsg("hook lsig id %d matched (bc %d)\n", bc->hook_lsig_id, bc->id);
/* this is a bytecode for a hook, defer running it until hook is
* executed, so that it has all the info for the hook */
if (cctx->hook_lsig_matches)
cli_bitset_set(cctx->hook_lsig_matches, bc->hook_lsig_id-1);
/* save match counts */
memcpy(&ctx.lsigcnt, lsigcnt, 64*4);
memcpy(&ctx.lsigoff, lsigsuboff, 64*4);
cli_bytecode_context_clear(&ctx);
return CL_SUCCESS;
}
cli_dbgmsg("Running bytecode for logical signature match\n");
ret = cli_bytecode_run(bcs, bc, &ctx);
if (ret != CL_SUCCESS) {
cli_warnmsg("Bytcode %u failed to run: %s\n", bc->id, cl_strerror(ret));
cli_bytecode_context_clear(&ctx);
return CL_SUCCESS;
}
if (ctx.virname) {
int rc;
cli_dbgmsg("Bytecode found virus: %s\n", ctx.virname);
cli_append_virus(cctx, ctx.virname);
if (!strncmp(ctx.virname, "BC.Heuristics", 13))
rc = cli_found_possibly_unwanted(cctx);
else
rc = CL_VIRUS;
cli_bytecode_context_clear(&ctx);
return rc;
}
ret = cli_bytecode_context_getresult_int(&ctx);
cli_dbgmsg("Bytecode %u returned code: %u\n", bc->id, ret);
cli_bytecode_context_clear(&ctx);
return CL_SUCCESS;
}
int cli_bytecode_runhook(cli_ctx *cctx, const struct cl_engine *engine, struct cli_bc_ctx *ctx,
unsigned id, fmap_t *map)
{
const unsigned *hooks = engine->hooks[id - _BC_START_HOOKS];
unsigned i, hooks_cnt = engine->hooks_cnt[id - _BC_START_HOOKS];
int ret;
unsigned executed = 0, breakflag = 0, errorflag = 0;
if (!cctx)
return CL_ENULLARG;
cli_dbgmsg("Bytecode executing hook id %u (%u hooks)\n", id, hooks_cnt);
/* restore match counts */
cli_bytecode_context_setfile(ctx, map);
ctx->hooks.match_counts = ctx->lsigcnt;
ctx->hooks.match_offsets = ctx->lsigoff;
for (i=0;i < hooks_cnt;i++) {
const struct cli_bc *bc = &engine->bcs.all_bcs[hooks[i]];
if (bc->lsig) {
if (!cctx->hook_lsig_matches ||
!cli_bitset_test(cctx->hook_lsig_matches, bc->hook_lsig_id-1))
continue;
cli_dbgmsg("Bytecode: executing bytecode %u (lsig matched)\n" , bc->id);
}
cli_bytecode_context_setfuncid(ctx, bc, 0);
ret = cli_bytecode_run(&engine->bcs, bc, ctx);
executed++;
if (ret != CL_SUCCESS) {
cli_warnmsg("Bytecode %u failed to run: %s\n", bc->id, cl_strerror(ret));
errorflag = 1;
continue;
}
if (ctx->virname) {
cli_dbgmsg("Bytecode runhook found virus: %s\n", ctx->virname);
cli_append_virus(cctx, ctx->virname);
if (!(cctx->options & CL_SCAN_ALLMATCHES)) {
cli_bytecode_context_clear(ctx);
return CL_VIRUS;
}
cli_bytecode_context_reset(ctx);
continue;
}
ret = cli_bytecode_context_getresult_int(ctx);
/* TODO: use prefix here */
cli_dbgmsg("Bytecode %u returned %u\n", bc->id, ret);
if (ret == 0xcea5e) {
cli_dbgmsg("Bytecode set BREAK flag in hook!\n");
breakflag = 1;
}
if (!ret) {
char *tempfile;
int fd = cli_bytecode_context_getresult_file(ctx, &tempfile);
if (fd && fd != -1) {
if (cctx->engine->keeptmp)
cli_dbgmsg("Bytecode %u unpacked file saved in %s\n",
bc->id, tempfile);
else
cli_dbgmsg("Bytecode %u unpacked file\n", bc->id);
lseek(fd, 0, SEEK_SET);
cli_dbgmsg("***** Scanning unpacked file ******\n");
cctx->recursion++;
ret = cli_magic_scandesc(fd, cctx);
cctx->recursion--;
if (!cctx->engine->keeptmp)
if (ftruncate(fd, 0) == -1)
cli_dbgmsg("ftruncate failed on %d\n", fd);
close(fd);
if (!cctx->engine->keeptmp) {
if (tempfile && cli_unlink(tempfile))
ret = CL_EUNLINK;
}
free(tempfile);
if (ret != CL_CLEAN) {
if (ret == CL_VIRUS) {
cli_dbgmsg("Scanning unpacked file by bytecode %u found a virus\n", bc->id);
if (cctx->options & CL_SCAN_ALLMATCHES) {
cli_bytecode_context_reset(ctx);
continue;
}
cli_bytecode_context_clear(ctx);
return ret;
}
}
cli_bytecode_context_reset(ctx);
continue;
}
}
cli_bytecode_context_reset(ctx);
}
if (executed)
cli_dbgmsg("Bytecode: executed %u bytecodes for this hook\n", executed);
else
cli_dbgmsg("Bytecode: no logical signature matched, no bytecode executed\n");
if (errorflag && cctx->engine->bytecode_mode == CL_BYTECODE_MODE_TEST)
return CL_EBYTECODE_TESTFAIL;
return breakflag ? CL_BREAK : CL_CLEAN;
}
int cli_bytecode_context_setpe(struct cli_bc_ctx *ctx, const struct cli_pe_hook_data *data, const struct cli_exe_section *sections)
{
ctx->sections = sections;
ctx->hooks.pedata = data;
return 0;
}
void cli_bytecode_context_setctx(struct cli_bc_ctx *ctx, void *cctx)
{
ctx->ctx = cctx;
ctx->bytecode_timeout = ((cli_ctx*)cctx)->engine->bytecode_timeout;
}
void cli_bytecode_describe(const struct cli_bc *bc)
{
char buf[128];
int cols;
unsigned i;
time_t stamp;
int had;
if (!bc) {
printf("(null bytecode)\n");
return;
}
stamp = bc->metadata.timestamp;
printf("Bytecode format functionality level: %u\n", bc->metadata.formatlevel);
printf("Bytecode metadata:\n\tcompiler version: %s\n",
bc->metadata.compiler ? bc->metadata.compiler : "N/A");
printf("\tcompiled on: (%d) %s",
(uint32_t)stamp,
cli_ctime(&stamp, buf, sizeof(buf)));
printf("\tcompiled by: %s\n", bc->metadata.sigmaker ? bc->metadata.sigmaker : "N/A");
/*TODO: parse and display arch name, also take it into account when
JITing*/
printf("\ttarget exclude: %d\n", bc->metadata.targetExclude);
printf("\tbytecode type: ");
switch (bc->kind) {
case BC_GENERIC:
puts("generic, not loadable by clamscan/clamd");
break;
case BC_STARTUP:
puts("run on startup (unique)");
break;
case BC_LOGICAL:
puts("logical only");
break;
case BC_PE_UNPACKER:
puts("PE unpacker hook");
break;
case BC_PE_ALL:
puts("all PE hook");
break;
case BC_PRECLASS:
puts("preclass hook");
break;
default:
printf("Unknown (type %u)", bc->kind);
break;
}
/* 0 means no limit */
printf("\tbytecode functionality level: %u - %u\n",
bc->metadata.minfunc, bc->metadata.maxfunc);
printf("\tbytecode logical signature: %s\n",
bc->lsig ? bc->lsig : "<none>");
printf("\tvirusname prefix: %s\n",
bc->vnameprefix);
printf("\tvirusnames: %u\n", bc->vnames_cnt);
printf("\tbytecode triggered on: ");
switch (bc->kind) {
case BC_GENERIC:
puts("N/A (loaded in clambc only)");
break;
case BC_LOGICAL:
puts("files matching logical signature");
break;
case BC_PE_UNPACKER:
if (bc->lsig)
puts("PE files matching logical signature (unpacked)");
else
puts("all PE files! (unpacked)");
break;
case BC_PDF:
puts("PDF files");
break;
case BC_PE_ALL:
if (bc->lsig)
puts("PE files matching logical signature");
else
puts("all PE files!");
break;
case BC_PRECLASS:
if (bc->lsig)
puts("PRECLASS files matching logical signature");
else
puts("all PRECLASS files!");
break;
default:
puts("N/A (unknown type)\n");
break;
}
printf("\tnumber of functions: %u\n\tnumber of types: %u\n",
bc->num_func, bc->num_types);
printf("\tnumber of global constants: %u\n", (unsigned)bc->num_globals);
printf("\tnumber of debug nodes: %u\n", bc->dbgnode_cnt);
printf("\tbytecode APIs used:");
cols = 0; /* remaining */
had = 0;
for (i=0;i<cli_apicall_maxapi;i++) {
if (cli_bitset_test(bc->uses_apis, i)) {
unsigned len = strlen(cli_apicalls[i].name);
if (had)
printf(",");
if (len > (unsigned int)cols) {
printf("\n\t");
cols = 72;
}
printf(" %s", cli_apicalls[i].name);
had = 1;
cols -= len;
}
}
printf("\n");
}
const char *bc_tystr[] = {
"DFunctionType",
"DPointerType",
"DStructType",
"DPackedStructType",
"DArrayType"
};
const char *bc_opstr[] = {
"OP_BC_NULL",
"OP_BC_ADD", /* =1*/
"OP_BC_SUB",
"OP_BC_MUL",
"OP_BC_UDIV",
"OP_BC_SDIV",
"OP_BC_UREM",
"OP_BC_SREM",
"OP_BC_SHL",
"OP_BC_LSHR",
"OP_BC_ASHR",
"OP_BC_AND",
"OP_BC_OR",
"OP_BC_XOR",
"OP_BC_TRUNC",
"OP_BC_SEXT",
"OP_BC_ZEXT",
"OP_BC_BRANCH",
"OP_BC_JMP",
"OP_BC_RET",
"OP_BC_RET_VOID",
"OP_BC_ICMP_EQ",
"OP_BC_ICMP_NE",
"OP_BC_ICMP_UGT",
"OP_BC_ICMP_UGE",
"OP_BC_ICMP_ULT",
"OP_BC_ICMP_ULE",
"OP_BC_ICMP_SGT",
"OP_BC_ICMP_SGE",
"OP_BC_ICMP_SLE",
"OP_BC_ICMP_SLT",
"OP_BC_SELECT",
"OP_BC_CALL_DIRECT",
"OP_BC_CALL_API",
"OP_BC_COPY",
"OP_BC_GEP1",
"OP_BC_GEPZ",
"OP_BC_GEPN",
"OP_BC_STORE",
"OP_BC_LOAD",
"OP_BC_MEMSET",
"OP_BC_MEMCPY",
"OP_BC_MEMMOVE",
"OP_BC_MEMCMP",
"OP_BC_ISBIGENDIAN",
"OP_BC_ABORT",
"OP_BC_BSWAP16",
"OP_BC_BSWAP32",
"OP_BC_BSWAP64",
"OP_BC_PTRDIFF32",
"OP_BC_PTRTOINT64",
"OP_BC_INVALID" /* last */
};
extern unsigned cli_numapicalls;
static void cli_bytetype_helper(const struct cli_bc *bc, unsigned tid)
{
unsigned i, j;
const struct cli_bc_type *ty;
if (tid & 0x8000) {
printf("alloc ");
tid &= 0x7fff;
}
if (tid < 65) {
printf("i%d", tid);
return;
}
i = tid - 65;
if (i >= bc->num_types) {
printf("invaltype");
return;
}
ty = &bc->types[i];
switch (ty->kind) {
case DFunctionType:
cli_bytetype_helper(bc, ty->containedTypes[0]);
printf(" func ( ");
for (j = 1; j < ty->numElements; ++j) {
cli_bytetype_helper(bc, ty->containedTypes[0]);
printf(" ");
}
printf(")");
break;
case DPointerType:
cli_bytetype_helper(bc, ty->containedTypes[0]);
printf("*");
break;
case DStructType:
case DPackedStructType:
printf("{ ");
for (j = 0; j < ty->numElements; ++j) {
cli_bytetype_helper(bc, ty->containedTypes[0]);
printf(" ");
}
printf("}");
break;
case DArrayType:
printf("[");
printf("%d x ", ty->numElements);
cli_bytetype_helper(bc, ty->containedTypes[0]);
printf("]");
break;
default:
printf("unhandled type kind %d, cannot parse", ty->kind);
break;
}
}
void cli_bytetype_describe(const struct cli_bc *bc)
{
unsigned i, tid;
printf("found %d extra types of %d total, starting at tid %d\n",
bc->num_types, 64+bc->num_types, bc->start_tid);
printf("TID KIND INTERNAL\n");
printf("------------------------------------------------------------------------\n");
for (i = 0, tid = 65; i < bc->num_types-1; ++i, ++tid) {
printf("%3d: %-20s", tid, bc_tystr[bc->types[i].kind]);
cli_bytetype_helper(bc, tid);
printf("\n");
}
printf("------------------------------------------------------------------------\n");
}
void cli_bytevalue_describe(const struct cli_bc *bc, unsigned funcid)
{
unsigned i, j, total = 0;
const struct cli_bc_func *func;
if (funcid >= bc->num_func) {
printf("bytecode diagnostic: funcid [%u] outside byecode numfuncs [%u]\n",
funcid, bc->num_func);
return;
}
// globals
printf("found a total of %d globals\n", bc->num_globals);
printf("GID ID VALUE\n");
printf("------------------------------------------------------------------------\n");
for (i = 0; i < bc->num_globals; ++i) {
printf("%3u [%3u]: ", i, i);
cli_bytetype_helper(bc, bc->globaltys[i]);
printf(" unknown\n");
}
printf("------------------------------------------------------------------------\n");
// arguments and local values
func = &bc->funcs[funcid];
printf("found %d values with %d arguments and %d locals\n",
func->numValues, func->numArgs, func->numLocals);
printf("VID ID VALUE\n");
printf("------------------------------------------------------------------------\n");
for (i = 0; i < func->numValues; ++i) {
printf("%3u [%3u]: ", i, total++);
cli_bytetype_helper(bc, func->types[i]);
if (i < func->numArgs)
printf("argument");
printf("\n");
}
printf("------------------------------------------------------------------------\n");
// constants
printf("found a total of %d constants\n", func->numConstants);
printf("CID ID VALUE\n");
printf("------------------------------------------------------------------------\n");
for (i = 0; i < func->numConstants; ++i) {
printf("%3u [%3u]: %llu(0x%llx)\n", i, total++, func->constants[i], func->constants[i]);
}
printf("------------------------------------------------------------------------\n");
printf("found a total of %u total values\n", total);
printf("------------------------------------------------------------------------\n");
return;
}
void cli_byteinst_describe(const struct cli_bc_inst *inst, unsigned *bbnum)
{
unsigned j;
char inst_str[256];
const struct cli_apicall *api;
if (inst->opcode > OP_BC_INVALID) {
printf("opcode %u[%u] of type %u is not implemented yet!",
inst->opcode, inst->interp_op/5, inst->interp_op%5);
return;
}
snprintf(inst_str, sizeof(inst_str), "%-20s[%-3d/%3d/%3d]", bc_opstr[inst->opcode],
inst->opcode, inst->interp_op, inst->interp_op%inst->opcode);
printf("%-35s", inst_str);
switch (inst->opcode) {
// binary operations
case OP_BC_ADD:
printf("%d = %d + %d", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_SUB:
printf("%d = %d - %d", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_MUL:
printf("%d = %d * %d", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_UDIV:
printf("%d = %d / %d", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_SDIV:
printf("%d = %d / %d", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_UREM:
printf("%d = %d %% %d", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_SREM:
printf("%d = %d %% %d", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_SHL:
printf("%d = %d << %d", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_LSHR:
printf("%d = %d >> %d", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_ASHR:
printf("%d = %d >> %d", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_AND:
printf("%d = %d & %d", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_OR:
printf("%d = %d | %d", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_XOR:
printf("%d = %d ^ %d", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
// casting operations
case OP_BC_TRUNC:
printf("%d = %d trunc %llx", inst->dest, inst->u.cast.source, inst->u.cast.mask);
break;
case OP_BC_SEXT:
printf("%d = %d sext %llx", inst->dest, inst->u.cast.source, inst->u.cast.mask);
break;
case OP_BC_ZEXT:
printf("%d = %d zext %llx", inst->dest, inst->u.cast.source, inst->u.cast.mask);
break;
// control operations (termination instructions)
case OP_BC_BRANCH:
printf("br %d ? bb.%d : bb.%d", inst->u.branch.condition,
inst->u.branch.br_true, inst->u.branch.br_false);
(*bbnum)++;
break;
case OP_BC_JMP:
printf("jmp bb.%d", inst->u.jump);
(*bbnum)++;
break;
case OP_BC_RET:
printf("ret %d", inst->u.unaryop);
(*bbnum)++;
break;
case OP_BC_RET_VOID:
printf("ret void");
(*bbnum)++;
break;
// comparison operations
case OP_BC_ICMP_EQ:
printf("%d = (%d == %d)", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_ICMP_NE:
printf("%d = (%d != %d)", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_ICMP_UGT:
printf("%d = (%d > %d)", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_ICMP_UGE:
printf("%d = (%d >= %d)", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_ICMP_ULT:
printf("%d = (%d > %d)", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_ICMP_ULE:
printf("%d = (%d >= %d)", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_ICMP_SGT:
printf("%d = (%d > %d)", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_ICMP_SGE:
printf("%d = (%d >= %d)", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_ICMP_SLE:
printf("%d = (%d <= %d)", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_ICMP_SLT:
printf("%d = (%d < %d)", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_SELECT:
printf("%d = %d ? %d : %d)", inst->dest, inst->u.three[0],
inst->u.three[1], inst->u.three[2]);
break;
// function calling
case OP_BC_CALL_DIRECT:
printf("%d = call F.%d (", inst->dest, inst->u.ops.funcid);
for (j = 0; j < inst->u.ops.numOps; ++j) {
if (j == inst->u.ops.numOps-1) {
printf("%d", inst->u.ops.ops[j]);
}
else {
printf("%d, ", inst->u.ops.ops[j]);
}
}
printf(")");
break;
case OP_BC_CALL_API:
{
if (inst->u.ops.funcid > cli_numapicalls) {
printf("apicall FID %d not yet implemented!\n", inst->u.ops.funcid);
break;
}
api = &cli_apicalls[inst->u.ops.funcid];
switch (api->kind) {
case 0:
printf("%d = %s[%d] (%d, %d)", inst->dest, api->name,
inst->u.ops.funcid, inst->u.ops.ops[0], inst->u.ops.ops[1]);
break;
case 1:
printf("%d = %s[%d] (p.%d, %d)", inst->dest, api->name,
inst->u.ops.funcid, inst->u.ops.ops[0], inst->u.ops.ops[1]);
break;
case 2:
printf("%d = %s[%d] (%d)", inst->dest, api->name,
inst->u.ops.funcid, inst->u.ops.ops[0]);
break;
case 3:
printf("p.%d = %s[%d] (%d)", inst->dest, api->name,
inst->u.ops.funcid, inst->u.ops.ops[0]);
break;
case 4:
printf("%d = %s[%d] (p.%d, %d, %d, %d, %d)", inst->dest, api->name,
inst->u.ops.funcid, inst->u.ops.ops[0], inst->u.ops.ops[1],
inst->u.ops.ops[2], inst->u.ops.ops[3], inst->u.ops.ops[4]);
break;
case 5:
printf("%d = %s[%d] ()", inst->dest, api->name,
inst->u.ops.funcid);
break;
case 6:
printf("p.%d = %s[%d] (%d, %d)", inst->dest, api->name,
inst->u.ops.funcid, inst->u.ops.ops[0], inst->u.ops.ops[1]);
break;
case 7:
printf("%d = %s[%d] (%d, %d, %d)", inst->dest, api->name,
inst->u.ops.funcid, inst->u.ops.ops[0], inst->u.ops.ops[1],
inst->u.ops.ops[2]);
break;
case 8:
printf("%d = %s[%d] (p.%d, %d, p.%d, %d)", inst->dest, api->name,
inst->u.ops.funcid, inst->u.ops.ops[0], inst->u.ops.ops[1],
inst->u.ops.ops[2], inst->u.ops.ops[3]);
break;
case 9:
printf("%d = %s[%d] (p.%d, %d, %d)", inst->dest, api->name,
inst->u.ops.funcid, inst->u.ops.ops[0], inst->u.ops.ops[1],
inst->u.ops.ops[2]);
break;
default:
printf("type %u apicalls not yet implemented!\n", api->kind);
break;
}
}
break;
// memory operations
case OP_BC_COPY:
printf("cp %d -> %d", inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_GEP1:
printf("%d = gep1 p.%d + (%d * %d)", inst->dest, inst->u.three[1],
inst->u.three[2], inst->u.three[0]);
break;
case OP_BC_GEPZ:
printf("%d = gepz p.%d + (%d)", inst->dest,
inst->u.three[1], inst->u.three[2]);
break;
case OP_BC_GEPN:
printf("illegal opcode, impossible");
break;
case OP_BC_STORE:
printf("store %d -> p.%d", inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_LOAD:
printf("load %d <- p.%d", inst->dest, inst->u.unaryop);
break;
// llvm instrinsics
case OP_BC_MEMSET:
printf("%d = memset (p.%d, %d, %d)", inst->dest, inst->u.three[0],
inst->u.three[1], inst->u.three[2]);
break;
case OP_BC_MEMCPY:
printf("%d = memcpy (p.%d, p.%d, %d)", inst->dest, inst->u.three[0],
inst->u.three[1], inst->u.three[2]);
break;
case OP_BC_MEMMOVE:
printf("%d = memmove (p.%d, p.%d, %d)", inst->dest, inst->u.three[0],
inst->u.three[1], inst->u.three[2]);
break;
case OP_BC_MEMCMP:
printf("%d = memcmp (p.%d, p.%d, %d)", inst->dest, inst->u.three[0],
inst->u.three[1], inst->u.three[2]);
break;
// utility operations
case OP_BC_ISBIGENDIAN:
printf("%d = isbigendian()", inst->dest);
break;
case OP_BC_ABORT:
printf("ABORT!!");
break;
case OP_BC_BSWAP16:
printf("%d = bswap16 %d", inst->dest, inst->u.unaryop);
break;
case OP_BC_BSWAP32:
printf("%d = bswap32 %d", inst->dest, inst->u.unaryop);
break;
case OP_BC_BSWAP64:
printf("%d = bswap64 %d", inst->dest, inst->u.unaryop);
break;
case OP_BC_PTRDIFF32:
printf("%d = ptrdiff32 p.%d p.%d", inst->dest, inst->u.binop[0], inst->u.binop[1]);
break;
case OP_BC_PTRTOINT64:
printf("%d = ptrtoint64 p.%d", inst->dest, inst->u.unaryop);
break;
case OP_BC_INVALID: /* last */
printf("INVALID!!");
break;
default:
// redundant check
printf("opcode %u[%u] of type %u is not implemented yet!",
inst->opcode, inst->interp_op/5, inst->interp_op%5);
break;
}
}
void cli_bytefunc_describe(const struct cli_bc *bc, unsigned funcid)
{
unsigned i, bbnum, bbpre;
const struct cli_bc_func *func;
if (funcid >= bc->num_func) {
printf("bytecode diagnostic: funcid [%u] outside byecode numfuncs [%u]\n",
funcid, bc->num_func);
return;
}
func = &bc->funcs[funcid];
printf("FUNCTION ID: F.%d -> NUMINSTS %d\n", funcid, func->numInsts);
printf("BB IDX OPCODE [ID /IID/MOD] INST\n");
printf("------------------------------------------------------------------------\n");
bbpre = 0; bbnum = 0;
for (i = 0; i < func->numInsts; ++i) {
if (bbpre != bbnum) {
printf("\n");
bbpre = bbnum;
}
printf("%3d %3d ", bbnum, i);
cli_byteinst_describe(&func->allinsts[i], &bbnum);
printf("\n");
}
printf("------------------------------------------------------------------------\n");
}
|