1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025
|
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h"
#define CFFI_VERSION "1.14.5"
#ifdef MS_WIN32
#include <windows.h>
#include "misc_win32.h"
#else
#include <stddef.h>
#include <stdint.h>
#include <dlfcn.h>
#include <errno.h>
#include <ffi.h>
#include <sys/mman.h>
#endif
/* this block of #ifs should be kept exactly identical between
c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py */
#if defined(_MSC_VER)
# include <malloc.h> /* for alloca() */
# if _MSC_VER < 1600 /* MSVC < 2010 */
typedef __int8 int8_t;
typedef __int16 int16_t;
typedef __int32 int32_t;
typedef __int64 int64_t;
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
typedef __int8 int_least8_t;
typedef __int16 int_least16_t;
typedef __int32 int_least32_t;
typedef __int64 int_least64_t;
typedef unsigned __int8 uint_least8_t;
typedef unsigned __int16 uint_least16_t;
typedef unsigned __int32 uint_least32_t;
typedef unsigned __int64 uint_least64_t;
typedef __int8 int_fast8_t;
typedef __int16 int_fast16_t;
typedef __int32 int_fast32_t;
typedef __int64 int_fast64_t;
typedef unsigned __int8 uint_fast8_t;
typedef unsigned __int16 uint_fast16_t;
typedef unsigned __int32 uint_fast32_t;
typedef unsigned __int64 uint_fast64_t;
typedef __int64 intmax_t;
typedef unsigned __int64 uintmax_t;
# else
# include <stdint.h>
# endif
# if _MSC_VER < 1800 /* MSVC < 2013 */
typedef unsigned char _Bool;
# endif
#else
# include <stdint.h>
# if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux)
# include <alloca.h>
# endif
#endif
/* Define the following macro ONLY if you trust libffi's version of
* ffi_closure_alloc() more than the code in malloc_closure.h.
* IMPORTANT: DO NOT ENABLE THIS ON LINUX, unless you understand exactly
* why I recommend against it and decide that you trust it more than my
* analysis below.
*
* There are two versions of this code: one inside libffi itself, and
* one inside malloc_closure.h here. Both should be fine as long as the
* Linux distribution does _not_ enable extra security features. If it
* does, then the code in malloc_closure.h will cleanly crash because
* there is no reasonable way to obtain a read-write-execute memory
* page. On the other hand, the code in libffi will appear to
* work---but will actually randomly crash after a fork() if the child
* does not immediately call exec(). This second crash is of the kind
* that can be turned into an attack vector by a motivated attacker.
* So, _enabling_ extra security features _opens_ an attack vector.
* That sounds like a horribly bad idea to me, and is the reason for why
* I prefer CFFI crashing cleanly.
*
* Currently, we use libffi's ffi_closure_alloc() on NetBSD. It is
* known that on the NetBSD kernel, a different strategy is used which
* should not be open to the fork() bug.
*
* This is also used on macOS, provided we are executing on macOS 10.15 or
* above. It's a mess because it needs runtime checks in that case.
*/
#ifdef __NetBSD__
# define CFFI_CHECK_FFI_CLOSURE_ALLOC 1
# define CFFI_CHECK_FFI_CLOSURE_ALLOC_MAYBE 1
# define CFFI_CHECK_FFI_PREP_CLOSURE_LOC 1
# define CFFI_CHECK_FFI_PREP_CLOSURE_LOC_MAYBE 1
# define CFFI_CHECK_FFI_PREP_CIF_VAR 0
# define CFFI_CHECK_FFI_PREP_CIF_VAR_MAYBE 0
#elif defined(__APPLE__) && defined(FFI_AVAILABLE_APPLE)
# define CFFI_CHECK_FFI_CLOSURE_ALLOC __builtin_available(macos 10.15, ios 13, watchos 6, tvos 13, *)
# define CFFI_CHECK_FFI_CLOSURE_ALLOC_MAYBE 1
# define CFFI_CHECK_FFI_PREP_CLOSURE_LOC __builtin_available(macos 10.15, ios 13, watchos 6, tvos 13, *)
# define CFFI_CHECK_FFI_PREP_CLOSURE_LOC_MAYBE 1
# define CFFI_CHECK_FFI_PREP_CIF_VAR __builtin_available(macos 10.15, ios 13, watchos 6, tvos 13, *)
# define CFFI_CHECK_FFI_PREP_CIF_VAR_MAYBE 1
#else
# define CFFI_CHECK_FFI_CLOSURE_ALLOC 0
# define CFFI_CHECK_FFI_CLOSURE_ALLOC_MAYBE 0
# define CFFI_CHECK_FFI_PREP_CLOSURE_LOC 0
# define CFFI_CHECK_FFI_PREP_CLOSURE_LOC_MAYBE 0
# define CFFI_CHECK_FFI_PREP_CIF_VAR 0
# define CFFI_CHECK_FFI_PREP_CIF_VAR_MAYBE 0
#endif
/* always includes this, even if it turns out not to be used on NetBSD
because calls are behind "if (0)" */
#include "malloc_closure.h"
#if PY_MAJOR_VERSION >= 3
# define STR_OR_BYTES "bytes"
# define PyText_Type PyUnicode_Type
# define PyText_Check PyUnicode_Check
# define PyTextAny_Check PyUnicode_Check
# define PyText_FromFormat PyUnicode_FromFormat
# define PyText_AsUTF8 _PyUnicode_AsString /* PyUnicode_AsUTF8 in Py3.3 */
# define PyText_AS_UTF8 _PyUnicode_AsString
# if PY_VERSION_HEX >= 0x03030000
# define PyText_GetSize PyUnicode_GetLength
# else
# define PyText_GetSize PyUnicode_GetSize
# endif
# define PyText_FromString PyUnicode_FromString
# define PyText_FromStringAndSize PyUnicode_FromStringAndSize
# define PyText_InternInPlace PyUnicode_InternInPlace
# define PyText_InternFromString PyUnicode_InternFromString
# define PyIntOrLong_Check PyLong_Check
#else
# define STR_OR_BYTES "str"
# define PyText_Type PyString_Type
# define PyText_Check PyString_Check
# define PyTextAny_Check(op) (PyString_Check(op) || PyUnicode_Check(op))
# define PyText_FromFormat PyString_FromFormat
# define PyText_AsUTF8 PyString_AsString
# define PyText_AS_UTF8 PyString_AS_STRING
# define PyText_GetSize PyString_Size
# define PyText_FromString PyString_FromString
# define PyText_FromStringAndSize PyString_FromStringAndSize
# define PyText_InternInPlace PyString_InternInPlace
# define PyText_InternFromString PyString_InternFromString
# define PyIntOrLong_Check(op) (PyInt_Check(op) || PyLong_Check(op))
#endif
#if PY_MAJOR_VERSION >= 3
# define PyInt_FromLong PyLong_FromLong
# define PyInt_FromSsize_t PyLong_FromSsize_t
# define PyInt_AsSsize_t PyLong_AsSsize_t
# define PyInt_AsLong PyLong_AsLong
#endif
#if PY_MAJOR_VERSION >= 3
/* This is the default on Python3 and constant has been removed. */
# define Py_TPFLAGS_CHECKTYPES 0
#endif
#if PY_MAJOR_VERSION < 3
# undef PyCapsule_GetPointer
# undef PyCapsule_New
# define PyCapsule_GetPointer(capsule, name) \
(PyCObject_AsVoidPtr(capsule))
# define PyCapsule_New(pointer, name, destructor) \
(PyCObject_FromVoidPtr(pointer, destructor))
#endif
#if PY_VERSION_HEX < 0x030900a4
# define Py_SET_REFCNT(obj, val) (Py_REFCNT(obj) = (val))
#endif
/************************************************************/
/* base type flag: exactly one of the following: */
#define CT_PRIMITIVE_SIGNED 0x001 /* signed integer */
#define CT_PRIMITIVE_UNSIGNED 0x002 /* unsigned integer */
#define CT_PRIMITIVE_CHAR 0x004 /* char, wchar_t, charN_t */
#define CT_PRIMITIVE_FLOAT 0x008 /* float, double, long double */
#define CT_POINTER 0x010 /* pointer, excluding ptr-to-func */
#define CT_ARRAY 0x020 /* array */
#define CT_STRUCT 0x040 /* struct */
#define CT_UNION 0x080 /* union */
#define CT_FUNCTIONPTR 0x100 /* pointer to function */
#define CT_VOID 0x200 /* void */
#define CT_PRIMITIVE_COMPLEX 0x400 /* float _Complex, double _Complex */
/* other flags that may also be set in addition to the base flag: */
#define CT_IS_VOIDCHAR_PTR 0x00001000
#define CT_PRIMITIVE_FITS_LONG 0x00002000
#define CT_IS_OPAQUE 0x00004000
#define CT_IS_ENUM 0x00008000
#define CT_IS_PTR_TO_OWNED 0x00010000 /* only owned if CDataOwning_Type */
#define CT_CUSTOM_FIELD_POS 0x00020000
#define CT_IS_LONGDOUBLE 0x00040000
#define CT_IS_BOOL 0x00080000
#define CT_IS_FILE 0x00100000
#define CT_IS_VOID_PTR 0x00200000
#define CT_WITH_VAR_ARRAY 0x00400000 /* with open-ended array, anywhere */
/* unused 0x00800000 */
#define CT_LAZY_FIELD_LIST 0x01000000
#define CT_WITH_PACKED_CHANGE 0x02000000
#define CT_IS_SIGNED_WCHAR 0x04000000
#define CT_PRIMITIVE_ANY (CT_PRIMITIVE_SIGNED | \
CT_PRIMITIVE_UNSIGNED | \
CT_PRIMITIVE_CHAR | \
CT_PRIMITIVE_FLOAT | \
CT_PRIMITIVE_COMPLEX)
typedef struct _ctypedescr {
PyObject_VAR_HEAD
struct _ctypedescr *ct_itemdescr; /* ptrs and arrays: the item type */
PyObject *ct_stuff; /* structs: dict of the fields
arrays: ctypedescr of the ptr type
function: tuple(abi, ctres, ctargs..)
enum: pair {"name":x},{x:"name"}
ptrs: lazily, ctypedescr of array */
void *ct_extra; /* structs: first field (not a ref!)
function types: cif_description
primitives: prebuilt "cif" object */
PyObject *ct_weakreflist; /* weakref support */
PyObject *ct_unique_key; /* key in unique_cache (a string, but not
human-readable) */
Py_ssize_t ct_size; /* size of instances, or -1 if unknown */
Py_ssize_t ct_length; /* length of arrays, or -1 if unknown;
or alignment of primitive and struct types;
always -1 for pointers */
int ct_flags; /* CT_xxx flags */
int ct_name_position; /* index in ct_name of where to put a var name */
char ct_name[1]; /* string, e.g. "int *" for pointers to ints */
} CTypeDescrObject;
typedef struct {
PyObject_HEAD
CTypeDescrObject *c_type;
char *c_data;
PyObject *c_weakreflist;
} CDataObject;
typedef struct cfieldobject_s {
PyObject_HEAD
CTypeDescrObject *cf_type;
Py_ssize_t cf_offset;
short cf_bitshift; /* >= 0: bitshift; or BS_REGULAR or BS_EMPTY_ARRAY */
short cf_bitsize;
unsigned char cf_flags; /* BF_... */
struct cfieldobject_s *cf_next;
} CFieldObject;
#define BS_REGULAR (-1) /* a regular field, not with bitshift */
#define BS_EMPTY_ARRAY (-2) /* a field declared 'type[0]' or 'type[]' */
#define BF_IGNORE_IN_CTOR 0x01 /* union field not in the first place */
static PyTypeObject CTypeDescr_Type;
static PyTypeObject CField_Type;
static PyTypeObject CData_Type;
static PyTypeObject CDataOwning_Type;
static PyTypeObject CDataOwningGC_Type;
static PyTypeObject CDataFromBuf_Type;
static PyTypeObject CDataGCP_Type;
#define CTypeDescr_Check(ob) (Py_TYPE(ob) == &CTypeDescr_Type)
#define CData_Check(ob) (Py_TYPE(ob) == &CData_Type || \
Py_TYPE(ob) == &CDataOwning_Type || \
Py_TYPE(ob) == &CDataOwningGC_Type || \
Py_TYPE(ob) == &CDataFromBuf_Type || \
Py_TYPE(ob) == &CDataGCP_Type)
#define CDataOwn_Check(ob) (Py_TYPE(ob) == &CDataOwning_Type || \
Py_TYPE(ob) == &CDataOwningGC_Type)
typedef union {
unsigned char m_char;
unsigned short m_short;
unsigned int m_int;
unsigned long m_long;
unsigned long long m_longlong;
float m_float;
double m_double;
long double m_longdouble;
} union_alignment;
typedef struct {
CDataObject head;
union_alignment alignment;
} CDataObject_casted_primitive;
typedef struct {
CDataObject head;
union_alignment alignment;
} CDataObject_own_nolength;
typedef struct {
CDataObject head;
Py_ssize_t length;
union_alignment alignment;
} CDataObject_own_length;
typedef struct {
CDataObject head;
PyObject *structobj; /* for ffi.new_handle() or ffi.new("struct *") */
} CDataObject_own_structptr;
typedef struct {
CDataObject head;
Py_ssize_t length; /* same as CDataObject_own_length up to here */
Py_buffer *bufferview;
} CDataObject_frombuf;
typedef struct {
CDataObject head;
Py_ssize_t length; /* same as CDataObject_own_length up to here */
PyObject *origobj;
PyObject *destructor;
} CDataObject_gcp;
typedef struct {
CDataObject head;
ffi_closure *closure;
} CDataObject_closure;
typedef struct {
ffi_cif cif;
/* the following information is used when doing the call:
- a buffer of size 'exchange_size' is malloced
- the arguments are converted from Python objects to raw data
- the i'th raw data is stored at 'buffer + exchange_offset_arg[1+i]'
- the call is done
- the result is read back from 'buffer + exchange_offset_arg[0]' */
Py_ssize_t exchange_size;
Py_ssize_t exchange_offset_arg[1];
} cif_description_t;
#define ADD_WRAPAROUND(x, y) ((Py_ssize_t)(((size_t)(x)) + ((size_t)(y))))
#define MUL_WRAPAROUND(x, y) ((Py_ssize_t)(((size_t)(x)) * ((size_t)(y))))
/* whenever running Python code, the errno is saved in this thread-local
variable */
#ifndef MS_WIN32
# include "misc_thread_posix.h"
#endif
#include "minibuffer.h"
#if PY_MAJOR_VERSION >= 3
# include "file_emulator.h"
#endif
#ifdef PyUnicode_KIND /* Python >= 3.3 */
# include "wchar_helper_3.h"
#else
# include "wchar_helper.h"
#endif
#include "../cffi/_cffi_errors.h"
typedef struct _cffi_allocator_s {
PyObject *ca_alloc, *ca_free;
int ca_dont_clear;
} cffi_allocator_t;
static const cffi_allocator_t default_allocator = { NULL, NULL, 0 };
static PyObject *FFIError;
static PyObject *unique_cache;
/************************************************************/
static CTypeDescrObject *
ctypedescr_new(int name_size)
{
CTypeDescrObject *ct = PyObject_GC_NewVar(CTypeDescrObject,
&CTypeDescr_Type,
name_size);
if (ct == NULL)
return NULL;
ct->ct_itemdescr = NULL;
ct->ct_stuff = NULL;
ct->ct_weakreflist = NULL;
ct->ct_unique_key = NULL;
PyObject_GC_Track(ct);
return ct;
}
static CTypeDescrObject *
ctypedescr_new_on_top(CTypeDescrObject *ct_base, const char *extra_text,
int extra_position)
{
int base_name_len = strlen(ct_base->ct_name);
int extra_name_len = strlen(extra_text);
CTypeDescrObject *ct = ctypedescr_new(base_name_len + extra_name_len + 1);
char *p;
if (ct == NULL)
return NULL;
Py_INCREF(ct_base);
ct->ct_itemdescr = ct_base;
ct->ct_name_position = ct_base->ct_name_position + extra_position;
p = ct->ct_name;
memcpy(p, ct_base->ct_name, ct_base->ct_name_position);
p += ct_base->ct_name_position;
memcpy(p, extra_text, extra_name_len);
p += extra_name_len;
memcpy(p, ct_base->ct_name + ct_base->ct_name_position,
base_name_len - ct_base->ct_name_position + 1);
return ct;
}
static PyObject *
ctypedescr_repr(CTypeDescrObject *ct)
{
return PyText_FromFormat("<ctype '%s'>", ct->ct_name);
}
static void
ctypedescr_dealloc(CTypeDescrObject *ct)
{
PyObject_GC_UnTrack(ct);
if (ct->ct_weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *) ct);
if (ct->ct_unique_key != NULL) {
/* revive dead object temporarily for DelItem */
Py_SET_REFCNT(ct, 43);
PyDict_DelItem(unique_cache, ct->ct_unique_key);
assert(Py_REFCNT(ct) == 42);
Py_SET_REFCNT(ct, 0);
Py_DECREF(ct->ct_unique_key);
}
Py_XDECREF(ct->ct_itemdescr);
Py_XDECREF(ct->ct_stuff);
if (ct->ct_flags & CT_FUNCTIONPTR)
PyObject_Free(ct->ct_extra);
Py_TYPE(ct)->tp_free((PyObject *)ct);
}
static int
ctypedescr_traverse(CTypeDescrObject *ct, visitproc visit, void *arg)
{
Py_VISIT(ct->ct_itemdescr);
Py_VISIT(ct->ct_stuff);
return 0;
}
static int
ctypedescr_clear(CTypeDescrObject *ct)
{
Py_CLEAR(ct->ct_itemdescr);
Py_CLEAR(ct->ct_stuff);
return 0;
}
static PyObject *nosuchattr(const char *attr)
{
PyErr_SetString(PyExc_AttributeError, attr);
return NULL;
}
static PyObject *ctypeget_kind(CTypeDescrObject *ct, void *context)
{
char *result;
if (ct->ct_flags & CT_PRIMITIVE_ANY) {
if (ct->ct_flags & CT_IS_ENUM)
result = "enum";
else
result = "primitive";
}
else if (ct->ct_flags & CT_POINTER) {
result = "pointer";
}
else if (ct->ct_flags & CT_ARRAY) {
result = "array";
}
else if (ct->ct_flags & CT_VOID) {
result = "void";
}
else if (ct->ct_flags & CT_STRUCT) {
result = "struct";
}
else if (ct->ct_flags & CT_UNION) {
result = "union";
}
else if (ct->ct_flags & CT_FUNCTIONPTR) {
result = "function";
}
else
result = "?";
return PyText_FromString(result);
}
static PyObject *ctypeget_cname(CTypeDescrObject *ct, void *context)
{
return PyText_FromString(ct->ct_name);
}
static PyObject *ctypeget_item(CTypeDescrObject *ct, void *context)
{
if (ct->ct_flags & (CT_POINTER | CT_ARRAY)) {
Py_INCREF(ct->ct_itemdescr);
return (PyObject *)ct->ct_itemdescr;
}
return nosuchattr("item");
}
static PyObject *ctypeget_length(CTypeDescrObject *ct, void *context)
{
if (ct->ct_flags & CT_ARRAY) {
if (ct->ct_length >= 0) {
return PyInt_FromSsize_t(ct->ct_length);
}
else {
Py_INCREF(Py_None);
return Py_None;
}
}
return nosuchattr("length");
}
static PyObject *
get_field_name(CTypeDescrObject *ct, CFieldObject *cf); /* forward */
/* returns 0 if the struct ctype is opaque, 1 if it is not, or -1 if
an exception occurs */
#define force_lazy_struct(ct) \
((ct)->ct_stuff != NULL ? 1 : do_realize_lazy_struct(ct))
static int do_realize_lazy_struct(CTypeDescrObject *ct);
/* forward, implemented in realize_c_type.c */
static PyObject *ctypeget_fields(CTypeDescrObject *ct, void *context)
{
if (ct->ct_flags & (CT_STRUCT | CT_UNION)) {
if (!(ct->ct_flags & CT_IS_OPAQUE)) {
CFieldObject *cf;
PyObject *res;
if (force_lazy_struct(ct) < 0)
return NULL;
res = PyList_New(0);
if (res == NULL)
return NULL;
for (cf = (CFieldObject *)ct->ct_extra;
cf != NULL; cf = cf->cf_next) {
PyObject *o = PyTuple_Pack(2, get_field_name(ct, cf),
(PyObject *)cf);
int err = (o != NULL) ? PyList_Append(res, o) : -1;
Py_XDECREF(o);
if (err < 0) {
Py_DECREF(res);
return NULL;
}
}
return res;
}
else {
Py_INCREF(Py_None);
return Py_None;
}
}
return nosuchattr("fields");
}
static PyObject *ctypeget_args(CTypeDescrObject *ct, void *context)
{
if (ct->ct_flags & CT_FUNCTIONPTR) {
PyObject *t = ct->ct_stuff;
return PyTuple_GetSlice(t, 2, PyTuple_GET_SIZE(t));
}
return nosuchattr("args");
}
static PyObject *ctypeget_result(CTypeDescrObject *ct, void *context)
{
if (ct->ct_flags & CT_FUNCTIONPTR) {
PyObject *res = PyTuple_GetItem(ct->ct_stuff, 1);
Py_XINCREF(res);
return res;
}
return nosuchattr("result");
}
static PyObject *ctypeget_ellipsis(CTypeDescrObject *ct, void *context)
{
if (ct->ct_flags & CT_FUNCTIONPTR) {
PyObject *res = ct->ct_extra ? Py_False : Py_True;
Py_INCREF(res);
return res;
}
return nosuchattr("ellipsis");
}
static PyObject *ctypeget_abi(CTypeDescrObject *ct, void *context)
{
if (ct->ct_flags & CT_FUNCTIONPTR) {
PyObject *res = PyTuple_GetItem(ct->ct_stuff, 0);
Py_XINCREF(res);
return res;
}
return nosuchattr("abi");
}
static PyObject *ctypeget_elements(CTypeDescrObject *ct, void *context)
{
if (ct->ct_flags & CT_IS_ENUM) {
PyObject *res = PyTuple_GetItem(ct->ct_stuff, 1);
if (res) res = PyDict_Copy(res);
return res;
}
return nosuchattr("elements");
}
static PyObject *ctypeget_relements(CTypeDescrObject *ct, void *context)
{
if (ct->ct_flags & CT_IS_ENUM) {
PyObject *res = PyTuple_GetItem(ct->ct_stuff, 0);
if (res) res = PyDict_Copy(res);
return res;
}
return nosuchattr("relements");
}
static PyGetSetDef ctypedescr_getsets[] = {
{"kind", (getter)ctypeget_kind, NULL, "kind"},
{"cname", (getter)ctypeget_cname, NULL, "C name"},
{"item", (getter)ctypeget_item, NULL, "pointer to, or array of"},
{"length", (getter)ctypeget_length, NULL, "array length or None"},
{"fields", (getter)ctypeget_fields, NULL, "struct or union fields"},
{"args", (getter)ctypeget_args, NULL, "function argument types"},
{"result", (getter)ctypeget_result, NULL, "function result type"},
{"ellipsis", (getter)ctypeget_ellipsis, NULL, "function has '...'"},
{"abi", (getter)ctypeget_abi, NULL, "function ABI"},
{"elements", (getter)ctypeget_elements, NULL, "enum elements"},
{"relements", (getter)ctypeget_relements, NULL, "enum elements, reverse"},
{NULL} /* sentinel */
};
static PyObject *
ctypedescr_dir(PyObject *ct, PyObject *noarg)
{
int err;
struct PyGetSetDef *gsdef;
PyObject *res = PyList_New(0);
if (res == NULL)
return NULL;
for (gsdef = ctypedescr_getsets; gsdef->name; gsdef++) {
PyObject *x = PyObject_GetAttrString(ct, gsdef->name);
if (x == NULL) {
PyErr_Clear();
}
else {
Py_DECREF(x);
x = PyText_FromString(gsdef->name);
err = (x != NULL) ? PyList_Append(res, x) : -1;
Py_XDECREF(x);
if (err < 0) {
Py_DECREF(res);
return NULL;
}
}
}
return res;
}
static PyMethodDef ctypedescr_methods[] = {
{"__dir__", ctypedescr_dir, METH_NOARGS},
{NULL, NULL} /* sentinel */
};
static PyTypeObject CTypeDescr_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"_cffi_backend.CType",
offsetof(CTypeDescrObject, ct_name),
sizeof(char),
(destructor)ctypedescr_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
(reprfunc)ctypedescr_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
0, /* tp_doc */
(traverseproc)ctypedescr_traverse, /* tp_traverse */
(inquiry)ctypedescr_clear, /* tp_clear */
0, /* tp_richcompare */
offsetof(CTypeDescrObject, ct_weakreflist), /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
ctypedescr_methods, /* tp_methods */
0, /* tp_members */
ctypedescr_getsets, /* tp_getset */
};
/************************************************************/
static PyObject *
get_field_name(CTypeDescrObject *ct, CFieldObject *cf)
{
Py_ssize_t i = 0;
PyObject *d_key, *d_value;
while (PyDict_Next(ct->ct_stuff, &i, &d_key, &d_value)) {
if (d_value == (PyObject *)cf)
return d_key;
}
Py_FatalError("_cffi_backend: get_field_name()");
return NULL;
}
static void
cfield_dealloc(CFieldObject *cf)
{
Py_DECREF(cf->cf_type);
PyObject_Del(cf);
}
#undef OFF
#define OFF(x) offsetof(CFieldObject, x)
static PyMemberDef cfield_members[] = {
{"type", T_OBJECT, OFF(cf_type), READONLY},
{"offset", T_PYSSIZET, OFF(cf_offset), READONLY},
{"bitshift", T_SHORT, OFF(cf_bitshift), READONLY},
{"bitsize", T_SHORT, OFF(cf_bitsize), READONLY},
{"flags", T_UBYTE, OFF(cf_flags), READONLY},
{NULL} /* Sentinel */
};
#undef OFF
static PyTypeObject CField_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"_cffi_backend.CField",
sizeof(CFieldObject),
0,
(destructor)cfield_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
cfield_members, /* tp_members */
};
/************************************************************/
static int
CDataObject_Or_PyFloat_Check(PyObject *ob)
{
return (PyFloat_Check(ob) ||
(CData_Check(ob) &&
(((CDataObject *)ob)->c_type->ct_flags & CT_PRIMITIVE_FLOAT)));
}
static PY_LONG_LONG
_my_PyLong_AsLongLong(PyObject *ob)
{
/* (possibly) convert and cast a Python object to a long long.
Like PyLong_AsLongLong(), this version accepts a Python int too, and
does convertions from other types of objects. The difference is that
this version refuses floats. */
#if PY_MAJOR_VERSION < 3
if (PyInt_Check(ob)) {
return PyInt_AS_LONG(ob);
}
else
#endif
if (PyLong_Check(ob)) {
return PyLong_AsLongLong(ob);
}
else {
PyObject *io;
PY_LONG_LONG res;
PyNumberMethods *nb = ob->ob_type->tp_as_number;
if (CDataObject_Or_PyFloat_Check(ob) ||
nb == NULL || nb->nb_int == NULL) {
PyErr_SetString(PyExc_TypeError, "an integer is required");
return -1;
}
io = (*nb->nb_int) (ob);
if (io == NULL)
return -1;
if (PyIntOrLong_Check(io)) {
res = _my_PyLong_AsLongLong(io);
}
else {
PyErr_SetString(PyExc_TypeError, "integer conversion failed");
res = -1;
}
Py_DECREF(io);
return res;
}
}
static unsigned PY_LONG_LONG
_my_PyLong_AsUnsignedLongLong(PyObject *ob, int strict)
{
/* (possibly) convert and cast a Python object to an unsigned long long.
Like PyLong_AsLongLong(), this version accepts a Python int too, and
does convertions from other types of objects. If 'strict', complains
with OverflowError and refuses floats. If '!strict', rounds floats
and masks the result. */
#if PY_MAJOR_VERSION < 3
if (PyInt_Check(ob)) {
long value1 = PyInt_AS_LONG(ob);
if (strict && value1 < 0)
goto negative;
return (unsigned PY_LONG_LONG)(PY_LONG_LONG)value1;
}
else
#endif
if (PyLong_Check(ob)) {
if (strict) {
if (_PyLong_Sign(ob) < 0)
goto negative;
return PyLong_AsUnsignedLongLong(ob);
}
else {
return PyLong_AsUnsignedLongLongMask(ob);
}
}
else {
PyObject *io;
unsigned PY_LONG_LONG res;
PyNumberMethods *nb = ob->ob_type->tp_as_number;
if ((strict && CDataObject_Or_PyFloat_Check(ob)) ||
nb == NULL || nb->nb_int == NULL) {
PyErr_SetString(PyExc_TypeError, "an integer is required");
return (unsigned PY_LONG_LONG)-1;
}
io = (*nb->nb_int) (ob);
if (io == NULL)
return (unsigned PY_LONG_LONG)-1;
if (PyIntOrLong_Check(io)) {
res = _my_PyLong_AsUnsignedLongLong(io, strict);
}
else {
PyErr_SetString(PyExc_TypeError, "integer conversion failed");
res = (unsigned PY_LONG_LONG)-1;
}
Py_DECREF(io);
return res;
}
negative:
PyErr_SetString(PyExc_OverflowError,
"can't convert negative number to unsigned");
return (unsigned PY_LONG_LONG)-1;
}
#define _read_raw_data(type) \
do { \
if (size == sizeof(type)) { \
type r; \
memcpy(&r, target, sizeof(type)); \
return r; \
} \
} while(0)
static PY_LONG_LONG
read_raw_signed_data(char *target, int size)
{
_read_raw_data(signed char);
_read_raw_data(short);
_read_raw_data(int);
_read_raw_data(long);
_read_raw_data(PY_LONG_LONG);
Py_FatalError("read_raw_signed_data: bad integer size");
return 0;
}
static unsigned PY_LONG_LONG
read_raw_unsigned_data(char *target, int size)
{
_read_raw_data(unsigned char);
_read_raw_data(unsigned short);
_read_raw_data(unsigned int);
_read_raw_data(unsigned long);
_read_raw_data(unsigned PY_LONG_LONG);
Py_FatalError("read_raw_unsigned_data: bad integer size");
return 0;
}
#ifdef __GNUC__
/* This is a workaround for what I think is a GCC bug on several
platforms. See issue #378. */
__attribute__((noinline))
#endif
void _cffi_memcpy(char *target, const void *src, size_t size)
{
memcpy(target, src, size);
}
#define _write_raw_data(type) \
do { \
if (size == sizeof(type)) { \
type r = (type)source; \
_cffi_memcpy(target, &r, sizeof(type)); \
return; \
} \
} while(0)
static void
write_raw_integer_data(char *target, unsigned PY_LONG_LONG source, int size)
{
_write_raw_data(unsigned char);
_write_raw_data(unsigned short);
_write_raw_data(unsigned int);
_write_raw_data(unsigned long);
_write_raw_data(unsigned PY_LONG_LONG);
Py_FatalError("write_raw_integer_data: bad integer size");
}
static double
read_raw_float_data(char *target, int size)
{
_read_raw_data(float);
_read_raw_data(double);
Py_FatalError("read_raw_float_data: bad float size");
return 0;
}
static long double
read_raw_longdouble_data(char *target)
{
int size = sizeof(long double);
_read_raw_data(long double);
Py_FatalError("read_raw_longdouble_data: bad long double size");
return 0;
}
static Py_complex
read_raw_complex_data(char *target, int size)
{
Py_complex r = {0.0, 0.0};
if (size == 2*sizeof(float)) {
float real_part, imag_part;
memcpy(&real_part, target + 0, sizeof(float));
memcpy(&imag_part, target + sizeof(float), sizeof(float));
r.real = real_part;
r.imag = imag_part;
return r;
}
if (size == 2*sizeof(double)) {
memcpy(&r, target, 2*sizeof(double));
return r;
}
Py_FatalError("read_raw_complex_data: bad complex size");
return r;
}
static void
write_raw_float_data(char *target, double source, int size)
{
_write_raw_data(float);
_write_raw_data(double);
Py_FatalError("write_raw_float_data: bad float size");
}
static void
write_raw_longdouble_data(char *target, long double source)
{
int size = sizeof(long double);
_write_raw_data(long double);
}
#define _write_raw_complex_data(type) \
do { \
if (size == 2*sizeof(type)) { \
type r = (type)source.real; \
type i = (type)source.imag; \
_cffi_memcpy(target, &r, sizeof(type)); \
_cffi_memcpy(target+sizeof(type), &i, sizeof(type)); \
return; \
} \
} while(0)
static void
write_raw_complex_data(char *target, Py_complex source, int size)
{
_write_raw_complex_data(float);
_write_raw_complex_data(double);
Py_FatalError("write_raw_complex_data: bad complex size");
}
static PyObject *
new_simple_cdata(char *data, CTypeDescrObject *ct)
{
CDataObject *cd = PyObject_New(CDataObject, &CData_Type);
if (cd == NULL)
return NULL;
Py_INCREF(ct);
cd->c_data = data;
cd->c_type = ct;
cd->c_weakreflist = NULL;
return (PyObject *)cd;
}
static PyObject *
new_sized_cdata(char *data, CTypeDescrObject *ct, Py_ssize_t length)
{
CDataObject_own_length *scd;
scd = (CDataObject_own_length *)PyObject_Malloc(
offsetof(CDataObject_own_length, alignment));
if (PyObject_Init((PyObject *)scd, &CData_Type) == NULL)
return NULL;
Py_INCREF(ct);
scd->head.c_type = ct;
scd->head.c_data = data;
scd->head.c_weakreflist = NULL;
scd->length = length;
return (PyObject *)scd;
}
static CDataObject *_new_casted_primitive(CTypeDescrObject *ct); /*forward*/
static PyObject *
convert_to_object(char *data, CTypeDescrObject *ct)
{
if (!(ct->ct_flags & CT_PRIMITIVE_ANY)) {
/* non-primitive types (check done just for performance) */
if (ct->ct_flags & (CT_POINTER|CT_FUNCTIONPTR)) {
char *ptrdata = *(char **)data;
/*READ(data, sizeof(char *))*/
return new_simple_cdata(ptrdata, ct);
}
else if (ct->ct_flags & CT_IS_OPAQUE) {
PyErr_Format(PyExc_TypeError, "cdata '%s' is opaque",
ct->ct_name);
return NULL;
}
else if (ct->ct_flags & (CT_STRUCT|CT_UNION)) {
return new_simple_cdata(data, ct);
}
else if (ct->ct_flags & CT_ARRAY) {
if (ct->ct_length < 0) {
/* we can't return a <cdata 'int[]'> here, because we don't
know the length to give it. As a compromize, returns
<cdata 'int *'> in this case. */
ct = (CTypeDescrObject *)ct->ct_stuff;
}
return new_simple_cdata(data, ct);
}
}
else if (ct->ct_flags & CT_PRIMITIVE_SIGNED) {
PY_LONG_LONG value;
/*READ(data, ct->ct_size)*/
value = read_raw_signed_data(data, ct->ct_size);
if (ct->ct_flags & CT_PRIMITIVE_FITS_LONG)
return PyInt_FromLong((long)value);
else
return PyLong_FromLongLong(value);
}
else if (ct->ct_flags & CT_PRIMITIVE_UNSIGNED) {
unsigned PY_LONG_LONG value;
/*READ(data, ct->ct_size)*/
value = read_raw_unsigned_data(data, ct->ct_size);
if (ct->ct_flags & CT_PRIMITIVE_FITS_LONG) {
if (ct->ct_flags & CT_IS_BOOL) {
PyObject *x;
switch ((int)value) {
case 0: x = Py_False; break;
case 1: x = Py_True; break;
default:
PyErr_Format(PyExc_ValueError,
"got a _Bool of value %d, expected 0 or 1",
(int)value);
return NULL;
}
Py_INCREF(x);
return x;
}
return PyInt_FromLong((long)value);
}
else
return PyLong_FromUnsignedLongLong(value);
}
else if (ct->ct_flags & CT_PRIMITIVE_FLOAT) {
/*READ(data, ct->ct_size)*/
if (!(ct->ct_flags & CT_IS_LONGDOUBLE)) {
double value = read_raw_float_data(data, ct->ct_size);
return PyFloat_FromDouble(value);
}
else {
long double value = read_raw_longdouble_data(data);
CDataObject *cd = _new_casted_primitive(ct);
if (cd != NULL)
write_raw_longdouble_data(cd->c_data, value);
return (PyObject *)cd;
}
}
else if (ct->ct_flags & CT_PRIMITIVE_CHAR) {
/*READ(data, ct->ct_size)*/
switch (ct->ct_size) {
case sizeof(char):
return PyBytes_FromStringAndSize(data, 1);
case 2:
return _my_PyUnicode_FromChar16((cffi_char16_t *)data, 1);
case 4:
return _my_PyUnicode_FromChar32((cffi_char32_t *)data, 1);
}
}
else if (ct->ct_flags & CT_PRIMITIVE_COMPLEX) {
Py_complex value = read_raw_complex_data(data, ct->ct_size);
return PyComplex_FromCComplex(value);
}
PyErr_Format(PyExc_SystemError,
"convert_to_object: '%s'", ct->ct_name);
return NULL;
}
static PyObject *
convert_to_object_bitfield(char *data, CFieldObject *cf)
{
CTypeDescrObject *ct = cf->cf_type;
/*READ(data, ct->ct_size)*/
if (ct->ct_flags & CT_PRIMITIVE_SIGNED) {
unsigned PY_LONG_LONG value, valuemask, shiftforsign;
PY_LONG_LONG result;
value = (unsigned PY_LONG_LONG)read_raw_signed_data(data, ct->ct_size);
valuemask = (1ULL << cf->cf_bitsize) - 1ULL;
shiftforsign = 1ULL << (cf->cf_bitsize - 1);
value = ((value >> cf->cf_bitshift) + shiftforsign) & valuemask;
result = ((PY_LONG_LONG)value) - (PY_LONG_LONG)shiftforsign;
if (ct->ct_flags & CT_PRIMITIVE_FITS_LONG)
return PyInt_FromLong((long)result);
else
return PyLong_FromLongLong(result);
}
else {
unsigned PY_LONG_LONG value, valuemask;
value = read_raw_unsigned_data(data, ct->ct_size);
valuemask = (1ULL << cf->cf_bitsize) - 1ULL;
value = (value >> cf->cf_bitshift) & valuemask;
if (ct->ct_flags & CT_PRIMITIVE_FITS_LONG)
return PyInt_FromLong((long)value);
else
return PyLong_FromUnsignedLongLong(value);
}
}
static int _convert_overflow(PyObject *init, const char *ct_name)
{
PyObject *s;
if (PyErr_Occurred()) /* already an exception pending */
return -1;
s = PyObject_Str(init);
if (s == NULL)
return -1;
PyErr_Format(PyExc_OverflowError, "integer %s does not fit '%s'",
PyText_AS_UTF8(s), ct_name);
Py_DECREF(s);
return -1;
}
static int _convert_to_char(PyObject *init)
{
if (PyBytes_Check(init) && PyBytes_GET_SIZE(init) == 1) {
return (unsigned char)(PyBytes_AS_STRING(init)[0]);
}
if (CData_Check(init) &&
(((CDataObject *)init)->c_type->ct_flags & CT_PRIMITIVE_CHAR) &&
(((CDataObject *)init)->c_type->ct_size == sizeof(char))) {
char *data = ((CDataObject *)init)->c_data;
/*READ(data, 1)*/
return *(unsigned char *)data;
}
PyErr_Format(PyExc_TypeError,
"initializer for ctype 'char' must be a "STR_OR_BYTES
" of length 1, not %.200s", Py_TYPE(init)->tp_name);
return -1;
}
static cffi_char16_t _convert_to_char16_t(PyObject *init)
{
char err_got[80];
err_got[0] = 0;
if (PyUnicode_Check(init)) {
cffi_char16_t ordinal;
if (_my_PyUnicode_AsSingleChar16(init, &ordinal, err_got) == 0)
return ordinal;
}
if (CData_Check(init) &&
(((CDataObject *)init)->c_type->ct_flags & CT_PRIMITIVE_CHAR) &&
(((CDataObject *)init)->c_type->ct_size == 2)) {
char *data = ((CDataObject *)init)->c_data;
/*READ(data, 2)*/
return *(cffi_char16_t *)data;
}
PyErr_Format(PyExc_TypeError,
"initializer for ctype 'char16_t' must be a unicode string "
"of length 1, not %.200s",
err_got[0] == 0 ? Py_TYPE(init)->tp_name : err_got);
return (cffi_char16_t)-1;
}
static cffi_char32_t _convert_to_char32_t(PyObject *init)
{
char err_got[80];
err_got[0] = 0;
if (PyUnicode_Check(init)) {
cffi_char32_t ordinal;
if (_my_PyUnicode_AsSingleChar32(init, &ordinal, err_got) == 0)
return ordinal;
}
if (CData_Check(init) &&
(((CDataObject *)init)->c_type->ct_flags & CT_PRIMITIVE_CHAR) &&
(((CDataObject *)init)->c_type->ct_size == 4)) {
char *data = ((CDataObject *)init)->c_data;
/*READ(data, 4)*/
return *(cffi_char32_t *)data;
}
PyErr_Format(PyExc_TypeError,
"initializer for ctype 'char32_t' must be a unicode string "
"of length 1, not %.200s",
err_got[0] == 0 ? Py_TYPE(init)->tp_name : err_got);
return (cffi_char32_t)-1;
}
static int _convert_error(PyObject *init, CTypeDescrObject *ct,
const char *expected)
{
if (CData_Check(init)) {
CTypeDescrObject *ct2 = ((CDataObject *)init)->c_type;
if (strcmp(ct->ct_name, ct2->ct_name) != 0)
PyErr_Format(PyExc_TypeError,
"initializer for ctype '%s' must be a %s, "
"not cdata '%s'",
ct->ct_name, expected, ct2->ct_name);
else if (ct != ct2) {
/* in case we'd give the error message "initializer for
ctype 'A' must be a pointer to same type, not cdata
'B'", but with A=B, then give instead a different error
message to try to clear up the confusion */
PyErr_Format(PyExc_TypeError,
"initializer for ctype '%s' appears indeed to be '%s',"
" but the types are different (check that you are not"
" e.g. mixing up different ffi instances)",
ct->ct_name, ct2->ct_name);
}
else
{
PyErr_Format(PyExc_SystemError,
"initializer for ctype '%s' is correct, but we get "
"an internal mismatch--please report a bug",
ct->ct_name);
}
}
else
PyErr_Format(PyExc_TypeError,
"initializer for ctype '%s' must be a %s, "
"not %.200s",
ct->ct_name, expected, Py_TYPE(init)->tp_name);
return -1;
}
static int /* forward */
convert_from_object(char *data, CTypeDescrObject *ct, PyObject *init);
static int /* forward */
convert_from_object_bitfield(char *data, CFieldObject *cf, PyObject *init);
static Py_ssize_t
get_new_array_length(CTypeDescrObject *ctitem, PyObject **pvalue)
{
PyObject *value = *pvalue;
if (PyList_Check(value) || PyTuple_Check(value)) {
return PySequence_Fast_GET_SIZE(value);
}
else if (PyBytes_Check(value)) {
/* from a string, we add the null terminator */
return PyBytes_GET_SIZE(value) + 1;
}
else if (PyUnicode_Check(value)) {
/* from a unicode, we add the null terminator */
int length;
if (ctitem->ct_size == 2)
length = _my_PyUnicode_SizeAsChar16(value);
else
length = _my_PyUnicode_SizeAsChar32(value);
return length + 1;
}
else {
Py_ssize_t explicitlength;
explicitlength = PyNumber_AsSsize_t(value, PyExc_OverflowError);
if (explicitlength < 0) {
if (PyErr_Occurred()) {
if (PyErr_ExceptionMatches(PyExc_TypeError))
PyErr_Format(PyExc_TypeError,
"expected new array length or list/tuple/str, "
"not %.200s", Py_TYPE(value)->tp_name);
}
else
PyErr_SetString(PyExc_ValueError, "negative array length");
return -1;
}
*pvalue = Py_None;
return explicitlength;
}
}
static int
convert_field_from_object(char *data, CFieldObject *cf, PyObject *value)
{
data += cf->cf_offset;
if (cf->cf_bitshift >= 0)
return convert_from_object_bitfield(data, cf, value);
else
return convert_from_object(data, cf->cf_type, value);
}
static int
add_varsize_length(Py_ssize_t offset, Py_ssize_t itemsize,
Py_ssize_t varsizelength, Py_ssize_t *optvarsize)
{
/* update '*optvarsize' to account for an array of 'varsizelength'
elements, each of size 'itemsize', that starts at 'offset'. */
Py_ssize_t size = ADD_WRAPAROUND(offset,
MUL_WRAPAROUND(itemsize, varsizelength));
if (size < 0 ||
((size - offset) / itemsize) != varsizelength) {
PyErr_SetString(PyExc_OverflowError,
"array size would overflow a Py_ssize_t");
return -1;
}
if (size > *optvarsize)
*optvarsize = size;
return 0;
}
static int
convert_struct_from_object(char *data, CTypeDescrObject *ct, PyObject *init,
Py_ssize_t *optvarsize); /* forward */
static int
convert_vfield_from_object(char *data, CFieldObject *cf, PyObject *value,
Py_ssize_t *optvarsize)
{
/* a special case for var-sized C99 arrays */
if ((cf->cf_type->ct_flags & CT_ARRAY) && cf->cf_type->ct_size < 0) {
Py_ssize_t varsizelength = get_new_array_length(
cf->cf_type->ct_itemdescr, &value);
if (varsizelength < 0)
return -1;
if (optvarsize != NULL) {
/* in this mode, the only purpose of this function is to compute
the real size of the structure from a var-sized C99 array */
assert(data == NULL);
return add_varsize_length(cf->cf_offset,
cf->cf_type->ct_itemdescr->ct_size,
varsizelength,
optvarsize);
}
/* if 'value' was only an integer, get_new_array_length() returns
it and convert 'value' to be None. Detect if this was the case,
and if so, stop here, leaving the content uninitialized
(it should be zero-initialized from somewhere else). */
if (value == Py_None)
return 0;
}
if (optvarsize == NULL) {
return convert_field_from_object(data, cf, value);
}
else if ((cf->cf_type->ct_flags & CT_WITH_VAR_ARRAY) != 0 &&
!CData_Check(value)) {
Py_ssize_t subsize = cf->cf_type->ct_size;
if (convert_struct_from_object(NULL, cf->cf_type, value, &subsize) < 0)
return -1;
return add_varsize_length(cf->cf_offset, 1, subsize, optvarsize);
}
else
return 0;
}
static int
must_be_array_of_zero_or_one(const char *data, Py_ssize_t n)
{
Py_ssize_t i;
for (i = 0; i < n; i++) {
if (((unsigned char)data[i]) > 1) {
PyErr_SetString(PyExc_ValueError,
"an array of _Bool can only contain \\x00 or \\x01");
return -1;
}
}
return 0;
}
static Py_ssize_t
get_array_length(CDataObject *cd)
{
if (cd->c_type->ct_length < 0)
return ((CDataObject_own_length *)cd)->length;
else
return cd->c_type->ct_length;
}
static int
convert_array_from_object(char *data, CTypeDescrObject *ct, PyObject *init)
{
/* used by convert_from_object(), and also to decode lists/tuples/unicodes
passed as function arguments. 'ct' is an CT_ARRAY in the first case
and a CT_POINTER in the second case. */
const char *expected;
CTypeDescrObject *ctitem = ct->ct_itemdescr;
if (PyList_Check(init) || PyTuple_Check(init)) {
PyObject **items;
Py_ssize_t i, n;
n = PySequence_Fast_GET_SIZE(init);
if (ct->ct_length >= 0 && n > ct->ct_length) {
PyErr_Format(PyExc_IndexError,
"too many initializers for '%s' (got %zd)",
ct->ct_name, n);
return -1;
}
items = PySequence_Fast_ITEMS(init);
for (i=0; i<n; i++) {
if (convert_from_object(data, ctitem, items[i]) < 0)
return -1;
data += ctitem->ct_size;
}
return 0;
}
else if ((ctitem->ct_flags & CT_PRIMITIVE_CHAR) ||
((ctitem->ct_flags & (CT_PRIMITIVE_SIGNED|CT_PRIMITIVE_UNSIGNED))
&& (ctitem->ct_size == sizeof(char)))) {
if (ctitem->ct_size == sizeof(char)) {
char *srcdata;
Py_ssize_t n;
if (!PyBytes_Check(init)) {
expected = STR_OR_BYTES" or list or tuple";
goto cannot_convert;
}
n = PyBytes_GET_SIZE(init);
if (ct->ct_length >= 0 && n > ct->ct_length) {
PyErr_Format(PyExc_IndexError,
"initializer "STR_OR_BYTES" is too long for '%s' "
"(got %zd characters)", ct->ct_name, n);
return -1;
}
if (n != ct->ct_length)
n++;
srcdata = PyBytes_AS_STRING(init);
if (ctitem->ct_flags & CT_IS_BOOL)
if (must_be_array_of_zero_or_one(srcdata, n) < 0)
return -1;
memcpy(data, srcdata, n);
return 0;
}
else {
Py_ssize_t n;
if (!PyUnicode_Check(init)) {
expected = "unicode or list or tuple";
goto cannot_convert;
}
if (ctitem->ct_size == 4)
n = _my_PyUnicode_SizeAsChar32(init);
else
n = _my_PyUnicode_SizeAsChar16(init);
if (ct->ct_length >= 0 && n > ct->ct_length) {
PyErr_Format(PyExc_IndexError,
"initializer unicode is too long for '%s' "
"(got %zd characters)", ct->ct_name, n);
return -1;
}
if (n != ct->ct_length)
n++;
if (ctitem->ct_size == 4)
return _my_PyUnicode_AsChar32(init, (cffi_char32_t *)data, n);
else
return _my_PyUnicode_AsChar16(init, (cffi_char16_t *)data, n);
}
}
else {
expected = "list or tuple";
goto cannot_convert;
}
cannot_convert:
if ((ct->ct_flags & CT_ARRAY) && CData_Check(init))
{
CDataObject *cd = (CDataObject *)init;
if (cd->c_type == ct)
{
Py_ssize_t n = get_array_length(cd);
memcpy(data, cd->c_data, n * ctitem->ct_size);
return 0;
}
}
return _convert_error(init, ct, expected);
}
static int
convert_struct_from_object(char *data, CTypeDescrObject *ct, PyObject *init,
Py_ssize_t *optvarsize)
{
/* does not accept 'init' being already a CData */
const char *expected;
if (force_lazy_struct(ct) <= 0) {
if (!PyErr_Occurred())
PyErr_Format(PyExc_TypeError, "'%s' is opaque", ct->ct_name);
return -1;
}
if (PyList_Check(init) || PyTuple_Check(init)) {
PyObject **items = PySequence_Fast_ITEMS(init);
Py_ssize_t i, n = PySequence_Fast_GET_SIZE(init);
CFieldObject *cf = (CFieldObject *)ct->ct_extra;
for (i=0; i<n; i++) {
while (cf != NULL && (cf->cf_flags & BF_IGNORE_IN_CTOR))
cf = cf->cf_next;
if (cf == NULL) {
PyErr_Format(PyExc_ValueError,
"too many initializers for '%s' (got %zd)",
ct->ct_name, n);
return -1;
}
if (convert_vfield_from_object(data, cf, items[i], optvarsize) < 0)
return -1;
cf = cf->cf_next;
}
return 0;
}
if (PyDict_Check(init)) {
PyObject *d_key, *d_value;
Py_ssize_t i = 0;
CFieldObject *cf;
while (PyDict_Next(init, &i, &d_key, &d_value)) {
cf = (CFieldObject *)PyDict_GetItem(ct->ct_stuff, d_key);
if (cf == NULL) {
PyErr_SetObject(PyExc_KeyError, d_key);
return -1;
}
if (convert_vfield_from_object(data, cf, d_value, optvarsize) < 0)
return -1;
}
return 0;
}
expected = optvarsize == NULL ? "list or tuple or dict or struct-cdata"
: "list or tuple or dict";
return _convert_error(init, ct, expected);
}
#ifdef __GNUC__
# if __GNUC__ >= 4
/* Don't go inlining this huge function. Needed because occasionally
it gets inlined in places where is causes a warning: call to
__builtin___memcpy_chk will always overflow destination buffer
(which is places where the 'ct' should never represent such a large
primitive type anyway). */
__attribute__((noinline))
# endif
#endif
static int
convert_from_object(char *data, CTypeDescrObject *ct, PyObject *init)
{
const char *expected;
char buf[sizeof(PY_LONG_LONG)];
/*if (ct->ct_size > 0)*/
/*WRITE(data, ct->ct_size)*/
if (ct->ct_flags & CT_ARRAY) {
return convert_array_from_object(data, ct, init);
}
if (ct->ct_flags & (CT_POINTER|CT_FUNCTIONPTR)) {
char *ptrdata;
CTypeDescrObject *ctinit;
if (!CData_Check(init)) {
expected = "cdata pointer";
goto cannot_convert;
}
ctinit = ((CDataObject *)init)->c_type;
if (!(ctinit->ct_flags & (CT_POINTER|CT_FUNCTIONPTR))) {
if (ctinit->ct_flags & CT_ARRAY)
ctinit = (CTypeDescrObject *)ctinit->ct_stuff;
else {
expected = "pointer or array";
goto cannot_convert;
}
}
if (ctinit != ct) {
int combined_flags = ct->ct_flags | ctinit->ct_flags;
if (combined_flags & CT_IS_VOID_PTR)
; /* accept "void *" as either source or target */
else if (combined_flags & CT_IS_VOIDCHAR_PTR) {
/* for backward compatibility, accept "char *" as either
source of target. This is not what C does, though,
so emit a warning that will eventually turn into an
error. The warning is turned off if both types are
pointers to single bytes. */
char *msg = (ct->ct_flags & CT_IS_VOIDCHAR_PTR ?
"implicit cast to 'char *' from a different pointer type: "
"will be forbidden in the future (check that the types "
"are as you expect; use an explicit ffi.cast() if they "
"are correct)" :
"implicit cast from 'char *' to a different pointer type: "
"will be forbidden in the future (check that the types "
"are as you expect; use an explicit ffi.cast() if they "
"are correct)");
if ((ct->ct_flags & ctinit->ct_flags & CT_POINTER) &&
ct->ct_itemdescr->ct_size == 1 &&
ctinit->ct_itemdescr->ct_size == 1) {
/* no warning */
}
else if (PyErr_WarnEx(PyExc_UserWarning, msg, 1))
return -1;
}
else {
expected = "pointer to same type";
goto cannot_convert;
}
}
ptrdata = ((CDataObject *)init)->c_data;
*(char **)data = ptrdata;
return 0;
}
if (ct->ct_flags & CT_PRIMITIVE_SIGNED) {
PY_LONG_LONG value = _my_PyLong_AsLongLong(init);
if (value == -1 && PyErr_Occurred())
return -1;
write_raw_integer_data(buf, value, ct->ct_size);
if (value != read_raw_signed_data(buf, ct->ct_size))
goto overflow;
write_raw_integer_data(data, value, ct->ct_size);
return 0;
}
if (ct->ct_flags & CT_PRIMITIVE_UNSIGNED) {
unsigned PY_LONG_LONG value = _my_PyLong_AsUnsignedLongLong(init, 1);
if (value == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
return -1;
if (ct->ct_flags & CT_IS_BOOL) {
if (value > 1ULL) /* value != 0 && value != 1 */
goto overflow;
}
else {
write_raw_integer_data(buf, value, ct->ct_size);
if (value != read_raw_unsigned_data(buf, ct->ct_size))
goto overflow;
}
write_raw_integer_data(data, value, ct->ct_size);
return 0;
}
if (ct->ct_flags & CT_PRIMITIVE_FLOAT) {
double value;
if ((ct->ct_flags & CT_IS_LONGDOUBLE) &&
CData_Check(init) &&
(((CDataObject *)init)->c_type->ct_flags & CT_IS_LONGDOUBLE)) {
long double lvalue;
char *initdata = ((CDataObject *)init)->c_data;
/*READ(initdata, sizeof(long double))*/
lvalue = read_raw_longdouble_data(initdata);
write_raw_longdouble_data(data, lvalue);
return 0;
}
value = PyFloat_AsDouble(init);
if (value == -1.0 && PyErr_Occurred())
return -1;
if (!(ct->ct_flags & CT_IS_LONGDOUBLE))
write_raw_float_data(data, value, ct->ct_size);
else
write_raw_longdouble_data(data, (long double)value);
return 0;
}
if (ct->ct_flags & CT_PRIMITIVE_CHAR) {
switch (ct->ct_size) {
case sizeof(char): {
int res = _convert_to_char(init);
if (res < 0)
return -1;
data[0] = res;
return 0;
}
case 2: {
cffi_char16_t res = _convert_to_char16_t(init);
if (res == (cffi_char16_t)-1 && PyErr_Occurred())
return -1;
*(cffi_char16_t *)data = res;
return 0;
}
case 4: {
cffi_char32_t res = _convert_to_char32_t(init);
if (res == (cffi_char32_t)-1 && PyErr_Occurred())
return -1;
*(cffi_char32_t *)data = res;
return 0;
}
}
}
if (ct->ct_flags & (CT_STRUCT|CT_UNION)) {
if (CData_Check(init)) {
if (((CDataObject *)init)->c_type == ct && ct->ct_size >= 0) {
memcpy(data, ((CDataObject *)init)->c_data, ct->ct_size);
return 0;
}
}
return convert_struct_from_object(data, ct, init, NULL);
}
if (ct->ct_flags & CT_PRIMITIVE_COMPLEX) {
Py_complex value = PyComplex_AsCComplex(init);
if (PyErr_Occurred())
return -1;
write_raw_complex_data(data, value, ct->ct_size);
return 0;
}
PyErr_Format(PyExc_SystemError,
"convert_from_object: '%s'", ct->ct_name);
return -1;
overflow:
return _convert_overflow(init, ct->ct_name);
cannot_convert:
return _convert_error(init, ct, expected);
}
static int
convert_from_object_bitfield(char *data, CFieldObject *cf, PyObject *init)
{
CTypeDescrObject *ct = cf->cf_type;
PY_LONG_LONG fmin, fmax, value = PyLong_AsLongLong(init);
unsigned PY_LONG_LONG rawfielddata, rawvalue, rawmask;
if (value == -1 && PyErr_Occurred())
return -1;
if (ct->ct_flags & CT_PRIMITIVE_SIGNED) {
fmin = -(1LL << (cf->cf_bitsize-1));
fmax = (1LL << (cf->cf_bitsize-1)) - 1LL;
if (fmax == 0)
fmax = 1; /* special case to let "int x:1" receive "1" */
}
else {
fmin = 0LL;
fmax = (PY_LONG_LONG)((1ULL << cf->cf_bitsize) - 1ULL);
}
if (value < fmin || value > fmax) {
/* phew, PyErr_Format does not support "%lld" in Python 2.6 */
PyObject *svalue = NULL, *sfmin = NULL, *sfmax = NULL;
PyObject *lfmin = NULL, *lfmax = NULL;
svalue = PyObject_Str(init);
if (svalue == NULL) goto skip;
lfmin = PyLong_FromLongLong(fmin);
if (lfmin == NULL) goto skip;
sfmin = PyObject_Str(lfmin);
if (sfmin == NULL) goto skip;
lfmax = PyLong_FromLongLong(fmax);
if (lfmax == NULL) goto skip;
sfmax = PyObject_Str(lfmax);
if (sfmax == NULL) goto skip;
PyErr_Format(PyExc_OverflowError,
"value %s outside the range allowed by the "
"bit field width: %s <= x <= %s",
PyText_AS_UTF8(svalue),
PyText_AS_UTF8(sfmin),
PyText_AS_UTF8(sfmax));
skip:
Py_XDECREF(svalue);
Py_XDECREF(sfmin);
Py_XDECREF(sfmax);
Py_XDECREF(lfmin);
Py_XDECREF(lfmax);
return -1;
}
rawmask = ((1ULL << cf->cf_bitsize) - 1ULL) << cf->cf_bitshift;
rawvalue = ((unsigned PY_LONG_LONG)value) << cf->cf_bitshift;
/*WRITE(data, ct->ct_size)*/
rawfielddata = read_raw_unsigned_data(data, ct->ct_size);
rawfielddata = (rawfielddata & ~rawmask) | (rawvalue & rawmask);
write_raw_integer_data(data, rawfielddata, ct->ct_size);
return 0;
}
static int
get_alignment(CTypeDescrObject *ct)
{
int align;
retry:
if ((ct->ct_flags & (CT_PRIMITIVE_ANY|CT_STRUCT|CT_UNION)) &&
!(ct->ct_flags & CT_IS_OPAQUE)) {
align = ct->ct_length;
if (align == -1 && (ct->ct_flags & CT_LAZY_FIELD_LIST)) {
force_lazy_struct(ct);
align = ct->ct_length;
}
}
else if (ct->ct_flags & (CT_POINTER|CT_FUNCTIONPTR)) {
struct aligncheck_ptr { char x; char *y; };
align = offsetof(struct aligncheck_ptr, y);
}
else if (ct->ct_flags & CT_ARRAY) {
ct = ct->ct_itemdescr;
goto retry;
}
else {
PyErr_Format(PyExc_ValueError, "ctype '%s' is of unknown alignment",
ct->ct_name);
return -1;
}
if ((align < 1) || (align & (align-1))) {
PyErr_Format(PyExc_SystemError,
"found for ctype '%s' bogus alignment '%d'",
ct->ct_name, align);
return -1;
}
return align;
}
static void cdata_dealloc(CDataObject *cd)
{
if (cd->c_weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *) cd);
Py_DECREF(cd->c_type);
#ifndef CFFI_MEM_LEAK /* never release anything, tests only */
Py_TYPE(cd)->tp_free((PyObject *)cd);
#endif
}
static void cdataowning_dealloc(CDataObject *cd)
{
assert(!(cd->c_type->ct_flags & (CT_IS_VOID_PTR | CT_FUNCTIONPTR)));
if (cd->c_type->ct_flags & CT_IS_PTR_TO_OWNED) {
/* for ffi.new("struct *") */
Py_DECREF(((CDataObject_own_structptr *)cd)->structobj);
}
#if defined(CFFI_MEM_DEBUG) || defined(CFFI_MEM_LEAK)
if (cd->c_type->ct_flags & (CT_PRIMITIVE_ANY | CT_STRUCT | CT_UNION)) {
assert(cd->c_type->ct_size >= 0);
memset(cd->c_data, 0xDD, cd->c_type->ct_size);
}
else if (cd->c_type->ct_flags & CT_ARRAY) {
Py_ssize_t x = get_array_length(cd);
assert(x >= 0);
x *= cd->c_type->ct_itemdescr->ct_size;
assert(x >= 0);
memset(cd->c_data, 0xDD, x);
}
#endif
cdata_dealloc(cd);
}
static void cdataowninggc_dealloc(CDataObject *cd)
{
PyObject_GC_UnTrack(cd);
if (cd->c_type->ct_flags & CT_IS_VOID_PTR) { /* a handle */
PyObject *x = ((CDataObject_own_structptr *)cd)->structobj;
Py_DECREF(x);
}
else if (cd->c_type->ct_flags & CT_FUNCTIONPTR) { /* a callback */
ffi_closure *closure = ((CDataObject_closure *)cd)->closure;
PyObject *args = (PyObject *)(closure->user_data);
Py_XDECREF(args);
#if CFFI_CHECK_FFI_CLOSURE_ALLOC_MAYBE
if (CFFI_CHECK_FFI_CLOSURE_ALLOC) {
ffi_closure_free(closure);
} else
#endif
cffi_closure_free(closure);
}
else {
Py_FatalError("cdata CDataOwningGC_Type with unexpected type flags");
}
cdata_dealloc(cd);
}
static void cdatafrombuf_dealloc(CDataObject *cd)
{
Py_buffer *view = ((CDataObject_frombuf *)cd)->bufferview;
cdata_dealloc(cd);
PyBuffer_Release(view);
PyObject_Free(view);
}
static int cdataowninggc_traverse(CDataObject *cd, visitproc visit, void *arg)
{
if (cd->c_type->ct_flags & CT_IS_VOID_PTR) { /* a handle */
PyObject *x = ((CDataObject_own_structptr *)cd)->structobj;
Py_VISIT(x);
}
else if (cd->c_type->ct_flags & CT_FUNCTIONPTR) { /* a callback */
ffi_closure *closure = ((CDataObject_closure *)cd)->closure;
PyObject *args = (PyObject *)(closure->user_data);
Py_VISIT(args);
}
return 0;
}
static int cdatafrombuf_traverse(CDataObject *cd, visitproc visit, void *arg)
{
Py_buffer *view = ((CDataObject_frombuf *)cd)->bufferview;
Py_VISIT(view->obj);
return 0;
}
static int cdataowninggc_clear(CDataObject *cd)
{
if (cd->c_type->ct_flags & CT_IS_VOID_PTR) { /* a handle */
CDataObject_own_structptr *cd1 = (CDataObject_own_structptr *)cd;
PyObject *x = cd1->structobj;
Py_INCREF(Py_None);
cd1->structobj = Py_None;
Py_DECREF(x);
}
else if (cd->c_type->ct_flags & CT_FUNCTIONPTR) { /* a callback */
ffi_closure *closure = ((CDataObject_closure *)cd)->closure;
PyObject *args = (PyObject *)(closure->user_data);
closure->user_data = NULL;
Py_XDECREF(args);
}
return 0;
}
static int cdatafrombuf_clear(CDataObject *cd)
{
Py_buffer *view = ((CDataObject_frombuf *)cd)->bufferview;
PyBuffer_Release(view);
return 0;
}
/* forward */
static void _my_PyErr_WriteUnraisable(PyObject *t, PyObject *v, PyObject *tb,
char *objdescr, PyObject *obj,
char *extra_error_line);
static void gcp_finalize(PyObject *destructor, PyObject *origobj)
{
/* NOTE: this decrements the reference count of the two arguments */
if (destructor != NULL) {
PyObject *result;
PyObject *error_type, *error_value, *error_traceback;
/* Save the current exception */
PyErr_Fetch(&error_type, &error_value, &error_traceback);
result = PyObject_CallFunctionObjArgs(destructor, origobj, NULL);
if (result != NULL) {
Py_DECREF(result);
}
else {
PyObject *t, *v, *tb;
PyErr_Fetch(&t, &v, &tb);
/* Don't use error capture here, because it is very much
* like errors at __del__(), and these ones are not captured
* either */
/* ecap = _cffi_start_error_capture(); */
_my_PyErr_WriteUnraisable(t, v, tb, "From callback for ffi.gc ",
origobj, NULL);
/* _cffi_stop_error_capture(ecap); */
}
Py_DECREF(destructor);
/* Restore the saved exception */
PyErr_Restore(error_type, error_value, error_traceback);
}
Py_XDECREF(origobj);
}
static void cdatagcp_finalize(CDataObject_gcp *cd)
{
PyObject *destructor = cd->destructor;
PyObject *origobj = cd->origobj;
cd->destructor = NULL;
cd->origobj = NULL;
gcp_finalize(destructor, origobj);
}
static void cdatagcp_dealloc(CDataObject_gcp *cd)
{
PyObject *destructor = cd->destructor;
PyObject *origobj = cd->origobj;
cdata_dealloc((CDataObject *)cd);
gcp_finalize(destructor, origobj);
}
static int cdatagcp_traverse(CDataObject_gcp *cd, visitproc visit, void *arg)
{
Py_VISIT(cd->destructor);
Py_VISIT(cd->origobj);
return 0;
}
static PyObject *cdata_float(CDataObject *cd); /*forward*/
static PyObject *convert_cdata_to_enum_string(CDataObject *cd, int both)
{
PyObject *d_key, *d_value;
CTypeDescrObject *ct = cd->c_type;
assert(ct->ct_flags & CT_IS_ENUM);
d_key = convert_to_object(cd->c_data, ct);
if (d_key == NULL)
return NULL;
d_value = PyDict_GetItem(PyTuple_GET_ITEM(ct->ct_stuff, 1), d_key);
if (d_value != NULL) {
if (both) {
PyObject *o = PyObject_Str(d_key);
if (o == NULL)
d_value = NULL;
else {
d_value = PyText_FromFormat("%s: %s",
PyText_AS_UTF8(o),
PyText_AS_UTF8(d_value));
Py_DECREF(o);
}
}
else
Py_INCREF(d_value);
}
else
d_value = PyObject_Str(d_key);
Py_DECREF(d_key);
return d_value;
}
static PyObject *cdata_repr(CDataObject *cd)
{
char *extra;
PyObject *result, *s;
if (cd->c_type->ct_flags & CT_PRIMITIVE_ANY) {
if (cd->c_type->ct_flags & CT_IS_ENUM) {
s = convert_cdata_to_enum_string(cd, 1);
}
else if (cd->c_type->ct_flags & CT_IS_LONGDOUBLE) {
long double lvalue;
char buffer[128]; /* big enough */
/*READ(cd->c_data, sizeof(long double)*/
lvalue = read_raw_longdouble_data(cd->c_data);
sprintf(buffer, "%LE", lvalue);
s = PyText_FromString(buffer);
}
else {
PyObject *o = convert_to_object(cd->c_data, cd->c_type);
if (o == NULL)
return NULL;
s = PyObject_Repr(o);
Py_DECREF(o);
}
}
else if ((cd->c_type->ct_flags & CT_ARRAY) && cd->c_type->ct_length < 0) {
s = PyText_FromFormat("sliced length %zd", get_array_length(cd));
}
else {
if (cd->c_data != NULL) {
s = PyText_FromFormat("%p", cd->c_data);
}
else
s = PyText_FromString("NULL");
}
if (s == NULL)
return NULL;
/* it's slightly confusing to get "<cdata 'struct foo' 0x...>" because the
struct foo is not owned. Trying to make it clearer, write in this
case "<cdata 'struct foo &' 0x...>". */
if (cd->c_type->ct_flags & (CT_STRUCT|CT_UNION))
extra = " &";
else
extra = "";
result = PyText_FromFormat("<cdata '%s%s' %s>",
cd->c_type->ct_name, extra,
PyText_AsUTF8(s));
Py_DECREF(s);
return result;
}
static PyObject *_cdata_repr2(CDataObject *cd, char *text, PyObject *x)
{
PyObject *res, *s = PyObject_Repr(x);
if (s == NULL)
return NULL;
res = PyText_FromFormat("<cdata '%s' %s %s>",
cd->c_type->ct_name, text, PyText_AsUTF8(s));
Py_DECREF(s);
return res;
}
static Py_ssize_t _cdata_var_byte_size(CDataObject *cd)
{
/* If 'cd' is a 'struct foo' or 'struct foo *' allocated with
ffi.new(), and if the struct foo contains a varsize array,
then return the real allocated size. Otherwise, return -1. */
if (!CDataOwn_Check(cd))
return -1;
if (cd->c_type->ct_flags & CT_IS_PTR_TO_OWNED) {
cd = (CDataObject *)((CDataObject_own_structptr *)cd)->structobj;
}
if (cd->c_type->ct_flags & CT_WITH_VAR_ARRAY) {
return ((CDataObject_own_length *)cd)->length;
}
return -1;
}
static PyObject *_frombuf_repr(CDataObject *cd, const char *cd_type_name)
{
Py_buffer *view = ((CDataObject_frombuf *)cd)->bufferview;
const char *obj_tp_name;
if (view->obj == NULL) {
return PyText_FromFormat(
"<cdata '%s' buffer RELEASED>",
cd_type_name);
}
obj_tp_name = Py_TYPE(view->obj)->tp_name;
if (cd->c_type->ct_flags & CT_ARRAY)
{
Py_ssize_t buflen = get_array_length(cd);
return PyText_FromFormat(
"<cdata '%s' buffer len %zd from '%.200s' object>",
cd_type_name,
buflen,
obj_tp_name);
}
else
{
return PyText_FromFormat(
"<cdata '%s' buffer from '%.200s' object>",
cd_type_name,
obj_tp_name);
}
}
static PyObject *cdataowning_repr(CDataObject *cd)
{
Py_ssize_t size = _cdata_var_byte_size(cd);
if (size < 0) {
if (cd->c_type->ct_flags & CT_POINTER)
size = cd->c_type->ct_itemdescr->ct_size;
else if (cd->c_type->ct_flags & CT_ARRAY)
size = get_array_length(cd) * cd->c_type->ct_itemdescr->ct_size;
else
size = cd->c_type->ct_size;
}
return PyText_FromFormat("<cdata '%s' owning %zd bytes>",
cd->c_type->ct_name, size);
}
static PyObject *cdataowninggc_repr(CDataObject *cd)
{
if (cd->c_type->ct_flags & CT_IS_VOID_PTR) { /* a handle */
PyObject *x = ((CDataObject_own_structptr *)cd)->structobj;
return _cdata_repr2(cd, "handle to", x);
}
else if (cd->c_type->ct_flags & CT_FUNCTIONPTR) { /* a callback */
ffi_closure *closure = ((CDataObject_closure *)cd)->closure;
PyObject *args = (PyObject *)closure->user_data;
if (args == NULL)
return cdata_repr(cd);
else
return _cdata_repr2(cd, "calling", PyTuple_GET_ITEM(args, 1));
}
return cdataowning_repr(cd); /* but should be unreachable */
}
static PyObject *cdatafrombuf_repr(CDataObject *cd)
{
return _frombuf_repr(cd, cd->c_type->ct_name);
}
static int cdata_nonzero(CDataObject *cd)
{
if (cd->c_type->ct_flags & CT_PRIMITIVE_ANY) {
if (cd->c_type->ct_flags & (CT_PRIMITIVE_SIGNED |
CT_PRIMITIVE_UNSIGNED |
CT_PRIMITIVE_CHAR))
return read_raw_unsigned_data(cd->c_data, cd->c_type->ct_size) != 0;
if (cd->c_type->ct_flags & CT_PRIMITIVE_FLOAT) {
if (cd->c_type->ct_flags & CT_IS_LONGDOUBLE)
return read_raw_longdouble_data(cd->c_data) != 0.0;
return read_raw_float_data(cd->c_data, cd->c_type->ct_size) != 0.0;
}
if (cd->c_type->ct_flags & CT_PRIMITIVE_COMPLEX) {
Py_complex value = read_raw_complex_data(cd->c_data,
cd->c_type->ct_size);
return value.real != 0.0 || value.imag != 0.0;
}
}
return cd->c_data != NULL;
}
static PyObject *cdata_int(CDataObject *cd)
{
if ((cd->c_type->ct_flags & (CT_PRIMITIVE_SIGNED|CT_PRIMITIVE_FITS_LONG))
== (CT_PRIMITIVE_SIGNED|CT_PRIMITIVE_FITS_LONG)) {
/* this case is to handle enums, but also serves as a slight
performance improvement for some other primitive types */
long value;
/*READ(cd->c_data, cd->c_type->ct_size)*/
value = (long)read_raw_signed_data(cd->c_data, cd->c_type->ct_size);
return PyInt_FromLong(value);
}
if (cd->c_type->ct_flags & (CT_PRIMITIVE_SIGNED|CT_PRIMITIVE_UNSIGNED)) {
PyObject *result = convert_to_object(cd->c_data, cd->c_type);
if (result != NULL && PyBool_Check(result))
result = PyInt_FromLong(PyInt_AsLong(result));
return result;
}
else if (cd->c_type->ct_flags & CT_PRIMITIVE_CHAR) {
/*READ(cd->c_data, cd->c_type->ct_size)*/
switch (cd->c_type->ct_size) {
case sizeof(char):
return PyInt_FromLong((unsigned char)cd->c_data[0]);
case 2:
return PyInt_FromLong((long)*(cffi_char16_t *)cd->c_data);
case 4:
if (cd->c_type->ct_flags & CT_IS_SIGNED_WCHAR)
return PyInt_FromLong((long)*(int32_t *)cd->c_data);
else if (sizeof(long) > 4)
return PyInt_FromLong(*(uint32_t *)cd->c_data);
else
return PyLong_FromUnsignedLong(*(uint32_t *)cd->c_data);
}
}
else if (cd->c_type->ct_flags & CT_PRIMITIVE_FLOAT) {
PyObject *o = cdata_float(cd);
#if PY_MAJOR_VERSION < 3
PyObject *r = o ? PyNumber_Int(o) : NULL;
#else
PyObject *r = o ? PyNumber_Long(o) : NULL;
#endif
Py_XDECREF(o);
return r;
}
PyErr_Format(PyExc_TypeError, "int() not supported on cdata '%s'",
cd->c_type->ct_name);
return NULL;
}
#if PY_MAJOR_VERSION < 3
static PyObject *cdata_long(CDataObject *cd)
{
PyObject *res = cdata_int(cd);
if (res != NULL && PyInt_CheckExact(res)) {
PyObject *o = PyLong_FromLong(PyInt_AS_LONG(res));
Py_DECREF(res);
res = o;
}
return res;
}
#endif
static PyObject *cdata_float(CDataObject *cd)
{
if (cd->c_type->ct_flags & CT_PRIMITIVE_FLOAT) {
double value;
/*READ(cd->c_data, cd->c_type->ct_size)*/
if (!(cd->c_type->ct_flags & CT_IS_LONGDOUBLE)) {
value = read_raw_float_data(cd->c_data, cd->c_type->ct_size);
}
else {
value = (double)read_raw_longdouble_data(cd->c_data);
}
return PyFloat_FromDouble(value);
}
PyErr_Format(PyExc_TypeError, "float() not supported on cdata '%s'",
cd->c_type->ct_name);
return NULL;
}
static PyObject *cdata_richcompare(PyObject *v, PyObject *w, int op)
{
int v_is_ptr, w_is_ptr;
PyObject *pyres;
assert(CData_Check(v));
/* Comparisons involving a primitive cdata work differently than
* comparisons involving a struct/array/pointer.
*
* If v or w is a struct/array/pointer, then the other must be too
* (otherwise we return NotImplemented and leave the case to
* Python). If both are, then we compare the addresses.
*
* If v and/or w is a primitive cdata, then we convert the cdata(s)
* to regular Python objects and redo the comparison there.
*/
v_is_ptr = !(((CDataObject *)v)->c_type->ct_flags & CT_PRIMITIVE_ANY);
w_is_ptr = CData_Check(w) &&
!(((CDataObject *)w)->c_type->ct_flags & CT_PRIMITIVE_ANY);
if (v_is_ptr && w_is_ptr) {
int res;
char *v_cdata = ((CDataObject *)v)->c_data;
char *w_cdata = ((CDataObject *)w)->c_data;
switch (op) {
case Py_EQ: res = (v_cdata == w_cdata); break;
case Py_NE: res = (v_cdata != w_cdata); break;
case Py_LT: res = (v_cdata < w_cdata); break;
case Py_LE: res = (v_cdata <= w_cdata); break;
case Py_GT: res = (v_cdata > w_cdata); break;
case Py_GE: res = (v_cdata >= w_cdata); break;
default: res = -1;
}
pyres = res ? Py_True : Py_False;
}
else if (v_is_ptr || w_is_ptr) {
pyres = Py_NotImplemented;
}
else {
PyObject *aa[2];
int i;
aa[0] = v; Py_INCREF(v);
aa[1] = w; Py_INCREF(w);
pyres = NULL;
for (i = 0; i < 2; i++) {
v = aa[i];
if (!CData_Check(v))
continue;
w = convert_to_object(((CDataObject *)v)->c_data,
((CDataObject *)v)->c_type);
if (w == NULL)
goto error;
if (CData_Check(w)) {
Py_DECREF(w);
PyErr_Format(PyExc_NotImplementedError,
"cannot use <cdata '%s'> in a comparison",
((CDataObject *)v)->c_type->ct_name);
goto error;
}
aa[i] = w;
Py_DECREF(v);
}
pyres = PyObject_RichCompare(aa[0], aa[1], op);
error:
Py_DECREF(aa[1]);
Py_DECREF(aa[0]);
return pyres;
}
Py_INCREF(pyres);
return pyres;
}
#if PY_MAJOR_VERSION < 3
typedef long Py_hash_t;
#endif
static Py_hash_t cdata_hash(PyObject *v)
{
if (((CDataObject *)v)->c_type->ct_flags & CT_PRIMITIVE_ANY) {
PyObject *vv = convert_to_object(((CDataObject *)v)->c_data,
((CDataObject *)v)->c_type);
if (vv == NULL)
return -1;
if (!CData_Check(vv)) {
Py_hash_t hash = PyObject_Hash(vv);
Py_DECREF(vv);
return hash;
}
Py_DECREF(vv);
}
return _Py_HashPointer(((CDataObject *)v)->c_data);
}
static Py_ssize_t
cdata_length(CDataObject *cd)
{
if (cd->c_type->ct_flags & CT_ARRAY) {
return get_array_length(cd);
}
PyErr_Format(PyExc_TypeError, "cdata of type '%s' has no len()",
cd->c_type->ct_name);
return -1;
}
static char *
_cdata_get_indexed_ptr(CDataObject *cd, PyObject *key)
{
Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
if (i == -1 && PyErr_Occurred())
return NULL;
if (cd->c_type->ct_flags & CT_POINTER) {
if (CDataOwn_Check(cd)) {
if (i != 0) {
PyErr_Format(PyExc_IndexError,
"cdata '%s' can only be indexed by 0",
cd->c_type->ct_name);
return NULL;
}
}
else {
if (cd->c_data == NULL) {
PyErr_Format(PyExc_RuntimeError,
"cannot dereference null pointer from cdata '%s'",
cd->c_type->ct_name);
return NULL;
}
}
}
else if (cd->c_type->ct_flags & CT_ARRAY) {
if (i < 0) {
PyErr_SetString(PyExc_IndexError,
"negative index");
return NULL;
}
if (i >= get_array_length(cd)) {
PyErr_Format(PyExc_IndexError,
"index too large for cdata '%s' (expected %zd < %zd)",
cd->c_type->ct_name,
i, get_array_length(cd));
return NULL;
}
}
else {
PyErr_Format(PyExc_TypeError, "cdata of type '%s' cannot be indexed",
cd->c_type->ct_name);
return NULL;
}
return cd->c_data + i * cd->c_type->ct_itemdescr->ct_size;
}
static PyObject *
new_array_type(CTypeDescrObject *ctptr, Py_ssize_t length); /* forward */
static CTypeDescrObject *
_cdata_getslicearg(CDataObject *cd, PySliceObject *slice, Py_ssize_t bounds[])
{
Py_ssize_t start, stop;
CTypeDescrObject *ct;
start = PyInt_AsSsize_t(slice->start);
if (start == -1 && PyErr_Occurred()) {
if (slice->start == Py_None)
PyErr_SetString(PyExc_IndexError, "slice start must be specified");
return NULL;
}
stop = PyInt_AsSsize_t(slice->stop);
if (stop == -1 && PyErr_Occurred()) {
if (slice->stop == Py_None)
PyErr_SetString(PyExc_IndexError, "slice stop must be specified");
return NULL;
}
if (slice->step != Py_None) {
PyErr_SetString(PyExc_IndexError, "slice with step not supported");
return NULL;
}
if (start > stop) {
PyErr_SetString(PyExc_IndexError, "slice start > stop");
return NULL;
}
ct = cd->c_type;
if (ct->ct_flags & CT_ARRAY) {
if (start < 0) {
PyErr_SetString(PyExc_IndexError,
"negative index");
return NULL;
}
if (stop > get_array_length(cd)) {
PyErr_Format(PyExc_IndexError,
"index too large (expected %zd <= %zd)",
stop, get_array_length(cd));
return NULL;
}
ct = (CTypeDescrObject *)ct->ct_stuff;
}
else if (!(ct->ct_flags & CT_POINTER)) {
PyErr_Format(PyExc_TypeError, "cdata of type '%s' cannot be indexed",
ct->ct_name);
return NULL;
}
bounds[0] = start;
bounds[1] = stop - start;
return ct;
}
static PyObject *
cdata_slice(CDataObject *cd, PySliceObject *slice)
{
char *cdata;
Py_ssize_t bounds[2];
CTypeDescrObject *ct = _cdata_getslicearg(cd, slice, bounds);
if (ct == NULL)
return NULL;
if (ct->ct_stuff == NULL) {
ct->ct_stuff = new_array_type(ct, -1);
if (ct->ct_stuff == NULL)
return NULL;
}
ct = (CTypeDescrObject *)ct->ct_stuff;
cdata = cd->c_data + ct->ct_itemdescr->ct_size * bounds[0];
return new_sized_cdata(cdata, ct, bounds[1]);
}
static int
cdata_ass_slice(CDataObject *cd, PySliceObject *slice, PyObject *v)
{
Py_ssize_t bounds[2], i, length, itemsize;
PyObject *it, *item;
PyObject *(*iternext)(PyObject *);
char *cdata;
int err;
CTypeDescrObject *ct = _cdata_getslicearg(cd, slice, bounds);
if (ct == NULL)
return -1;
ct = ct->ct_itemdescr;
itemsize = ct->ct_size;
cdata = cd->c_data + itemsize * bounds[0];
length = bounds[1];
if (CData_Check(v)) {
CTypeDescrObject *ctv = ((CDataObject *)v)->c_type;
if ((ctv->ct_flags & CT_ARRAY) && (ctv->ct_itemdescr == ct) &&
(get_array_length((CDataObject *)v) == length)) {
/* fast path: copying from exactly the correct type */
memmove(cdata, ((CDataObject *)v)->c_data, itemsize * length);
return 0;
}
}
/* A fast path for <char[]>[0:N] = b"somestring" or bytearray, which
also adds support for Python 3: otherwise, you get integers while
enumerating the string, and you can't set them to characters :-/
*/
if ((ct->ct_flags & CT_PRIMITIVE_CHAR) && itemsize == sizeof(char)) {
char *src;
Py_ssize_t srclen;
if (PyBytes_Check(v)) {
srclen = PyBytes_GET_SIZE(v);
src = PyBytes_AS_STRING(v);
}
else if (PyByteArray_Check(v)) {
srclen = PyByteArray_GET_SIZE(v);
src = PyByteArray_AS_STRING(v);
}
else
goto other_types;
if (srclen != length) {
PyErr_Format(PyExc_ValueError,
"need a string of length %zd, got %zd",
length, srclen);
return -1;
}
memcpy(cdata, src, length);
return 0;
}
other_types:
it = PyObject_GetIter(v);
if (it == NULL)
return -1;
iternext = *it->ob_type->tp_iternext;
for (i = 0; i < length; i++) {
item = iternext(it);
if (item == NULL) {
if (!PyErr_Occurred())
PyErr_Format(PyExc_ValueError,
"need %zd values to unpack, got %zd",
length, i);
goto error;
}
err = convert_from_object(cdata, ct, item);
Py_DECREF(item);
if (err < 0)
goto error;
cdata += itemsize;
}
item = iternext(it);
if (item != NULL) {
Py_DECREF(item);
PyErr_Format(PyExc_ValueError,
"got more than %zd values to unpack", length);
}
error:
Py_DECREF(it);
return PyErr_Occurred() ? -1 : 0;
}
static PyObject *
cdataowning_subscript(CDataObject *cd, PyObject *key)
{
char *c;
if (PySlice_Check(key))
return cdata_slice(cd, (PySliceObject *)key);
c = _cdata_get_indexed_ptr(cd, key);
/* use 'mp_subscript' instead of 'sq_item' because we don't want
negative indexes to be corrected automatically */
if (c == NULL && PyErr_Occurred())
return NULL;
if (cd->c_type->ct_flags & CT_IS_PTR_TO_OWNED) {
PyObject *res = ((CDataObject_own_structptr *)cd)->structobj;
Py_INCREF(res);
return res;
}
else {
return convert_to_object(c, cd->c_type->ct_itemdescr);
}
}
static PyObject *
cdata_subscript(CDataObject *cd, PyObject *key)
{
char *c;
if (PySlice_Check(key))
return cdata_slice(cd, (PySliceObject *)key);
c = _cdata_get_indexed_ptr(cd, key);
/* use 'mp_subscript' instead of 'sq_item' because we don't want
negative indexes to be corrected automatically */
if (c == NULL && PyErr_Occurred())
return NULL;
return convert_to_object(c, cd->c_type->ct_itemdescr);
}
static int
cdata_ass_sub(CDataObject *cd, PyObject *key, PyObject *v)
{
char *c;
CTypeDescrObject *ctitem;
if (PySlice_Check(key))
return cdata_ass_slice(cd, (PySliceObject *)key, v);
c = _cdata_get_indexed_ptr(cd, key);
ctitem = cd->c_type->ct_itemdescr;
/* use 'mp_ass_subscript' instead of 'sq_ass_item' because we don't want
negative indexes to be corrected automatically */
if (c == NULL && PyErr_Occurred())
return -1;
if (v == NULL) {
PyErr_SetString(PyExc_TypeError,
"'del x[n]' not supported for cdata objects");
return -1;
}
return convert_from_object(c, ctitem, v);
}
static PyObject *
_cdata_add_or_sub(PyObject *v, PyObject *w, int sign)
{
Py_ssize_t i, itemsize;
CDataObject *cd;
CTypeDescrObject *ctptr;
if (!CData_Check(v)) {
PyObject *swap;
assert(CData_Check(w));
if (sign != 1)
goto not_implemented;
swap = v;
v = w;
w = swap;
}
i = PyNumber_AsSsize_t(w, PyExc_OverflowError);
if (i == -1 && PyErr_Occurred())
return NULL;
i *= sign;
cd = (CDataObject *)v;
if (cd->c_type->ct_flags & CT_POINTER)
ctptr = cd->c_type;
else if (cd->c_type->ct_flags & CT_ARRAY) {
ctptr = (CTypeDescrObject *)cd->c_type->ct_stuff;
}
else {
PyErr_Format(PyExc_TypeError, "cannot add a cdata '%s' and a number",
cd->c_type->ct_name);
return NULL;
}
itemsize = ctptr->ct_itemdescr->ct_size;
if (itemsize < 0) {
if (ctptr->ct_flags & CT_IS_VOID_PTR) {
itemsize = 1;
}
else {
PyErr_Format(PyExc_TypeError,
"ctype '%s' points to items of unknown size",
cd->c_type->ct_name);
return NULL;
}
}
return new_simple_cdata(cd->c_data + i * itemsize, ctptr);
not_implemented:
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
static PyObject *
cdata_add(PyObject *v, PyObject *w)
{
return _cdata_add_or_sub(v, w, +1);
}
static PyObject *
cdata_sub(PyObject *v, PyObject *w)
{
if (CData_Check(v) && CData_Check(w)) {
CDataObject *cdv = (CDataObject *)v;
CDataObject *cdw = (CDataObject *)w;
CTypeDescrObject *ct = cdw->c_type;
Py_ssize_t diff, itemsize;
if (ct->ct_flags & CT_ARRAY) /* ptr_to_T - array_of_T: ok */
ct = (CTypeDescrObject *)ct->ct_stuff;
if (ct != cdv->c_type || !(ct->ct_flags & CT_POINTER) ||
(ct->ct_itemdescr->ct_size <= 0 &&
!(ct->ct_flags & CT_IS_VOID_PTR))) {
PyErr_Format(PyExc_TypeError,
"cannot subtract cdata '%s' and cdata '%s'",
cdv->c_type->ct_name, ct->ct_name);
return NULL;
}
itemsize = ct->ct_itemdescr->ct_size;
diff = cdv->c_data - cdw->c_data;
if (itemsize > 1) {
if (diff % itemsize) {
PyErr_SetString(PyExc_ValueError,
"pointer subtraction: the distance between the two "
"pointers is not a multiple of the item size");
return NULL;
}
diff = diff / itemsize;
}
#if PY_MAJOR_VERSION < 3
return PyInt_FromSsize_t(diff);
#else
return PyLong_FromSsize_t(diff);
#endif
}
return _cdata_add_or_sub(v, w, -1);
}
static void
_cdata_attr_errmsg(char *errmsg, CDataObject *cd, PyObject *attr)
{
const char *text;
if (!PyErr_ExceptionMatches(PyExc_AttributeError))
return;
PyErr_Clear();
text = PyText_AsUTF8(attr);
if (text == NULL)
return;
PyErr_Format(PyExc_AttributeError, errmsg, cd->c_type->ct_name, text);
}
static PyObject *
cdata_getattro(CDataObject *cd, PyObject *attr)
{
CFieldObject *cf;
CTypeDescrObject *ct = cd->c_type;
char *errmsg = "cdata '%s' has no attribute '%s'";
PyObject *x;
if (ct->ct_flags & CT_POINTER)
ct = ct->ct_itemdescr;
if (ct->ct_flags & (CT_STRUCT|CT_UNION)) {
switch (force_lazy_struct(ct)) {
case 1:
cf = (CFieldObject *)PyDict_GetItem(ct->ct_stuff, attr);
if (cf != NULL) {
/* read the field 'cf' */
char *data = cd->c_data + cf->cf_offset;
Py_ssize_t array_len, size;
if (cf->cf_bitshift == BS_REGULAR) {
return convert_to_object(data, cf->cf_type);
}
else if (cf->cf_bitshift != BS_EMPTY_ARRAY) {
return convert_to_object_bitfield(data, cf);
}
/* variable-length array: */
/* if reading variable length array from variable length
struct, calculate array type from allocated length */
size = _cdata_var_byte_size(cd) - cf->cf_offset;
if (size >= 0) {
array_len = size / cf->cf_type->ct_itemdescr->ct_size;
return new_sized_cdata(data, cf->cf_type, array_len);
}
return new_simple_cdata(data,
(CTypeDescrObject *)cf->cf_type->ct_stuff);
}
errmsg = "cdata '%s' has no field '%s'";
break;
case -1:
return NULL;
default:
errmsg = "cdata '%s' points to an opaque type: cannot read fields";
break;
}
}
x = PyObject_GenericGetAttr((PyObject *)cd, attr);
if (x == NULL)
_cdata_attr_errmsg(errmsg, cd, attr);
return x;
}
static int
cdata_setattro(CDataObject *cd, PyObject *attr, PyObject *value)
{
CFieldObject *cf;
CTypeDescrObject *ct = cd->c_type;
char *errmsg = "cdata '%s' has no attribute '%s'";
int x;
if (ct->ct_flags & CT_POINTER)
ct = ct->ct_itemdescr;
if (ct->ct_flags & (CT_STRUCT|CT_UNION)) {
switch (force_lazy_struct(ct)) {
case 1:
cf = (CFieldObject *)PyDict_GetItem(ct->ct_stuff, attr);
if (cf != NULL) {
/* write the field 'cf' */
if (value != NULL) {
return convert_field_from_object(cd->c_data, cf, value);
}
else {
PyErr_SetString(PyExc_AttributeError,
"cannot delete struct field");
return -1;
}
}
errmsg = "cdata '%s' has no field '%s'";
break;
case -1:
return -1;
default:
errmsg = "cdata '%s' points to an opaque type: cannot write fields";
break;
}
}
x = PyObject_GenericSetAttr((PyObject *)cd, attr, value);
if (x < 0)
_cdata_attr_errmsg(errmsg, cd, attr);
return x;
}
static PyObject *
convert_struct_to_owning_object(char *data, CTypeDescrObject *ct); /*forward*/
static cif_description_t *
fb_prepare_cif(PyObject *fargs, CTypeDescrObject *, Py_ssize_t, ffi_abi);
/*forward*/
static PyObject *new_primitive_type(const char *name); /*forward*/
static CTypeDescrObject *_get_ct_int(void)
{
static CTypeDescrObject *ct_int = NULL;
if (ct_int == NULL) {
ct_int = (CTypeDescrObject *)new_primitive_type("int");
}
return ct_int;
}
static Py_ssize_t
_prepare_pointer_call_argument(CTypeDescrObject *ctptr, PyObject *init,
char **output_data)
{
/* 'ctptr' is here a pointer type 'ITEM *'. Accept as argument an
initializer for an array 'ITEM[]'. This includes the case of
passing a Python byte string to a 'char *' argument.
This function returns -1 if an error occurred,
0 if conversion succeeded (into *output_data),
or N > 0 if conversion would require N bytes of storage.
*/
Py_ssize_t length, datasize;
CTypeDescrObject *ctitem;
if (CData_Check(init))
goto convert_default;
ctitem = ctptr->ct_itemdescr;
/* XXX some code duplication, how to avoid it? */
if (PyBytes_Check(init)) {
/* from a string: just returning the string here is fine.
We assume that the C code won't modify the 'char *' data. */
if ((ctptr->ct_flags & CT_IS_VOIDCHAR_PTR) ||
((ctitem->ct_flags & (CT_PRIMITIVE_SIGNED|CT_PRIMITIVE_UNSIGNED))
&& (ctitem->ct_size == sizeof(char)))) {
#if defined(CFFI_MEM_DEBUG) || defined(CFFI_MEM_LEAK)
length = PyBytes_GET_SIZE(init) + 1;
#else
*output_data = PyBytes_AS_STRING(init);
if (ctitem->ct_flags & CT_IS_BOOL)
if (must_be_array_of_zero_or_one(*output_data,
PyBytes_GET_SIZE(init)) < 0)
return -1;
return 0;
#endif
}
else
goto convert_default;
}
else if (PyList_Check(init) || PyTuple_Check(init)) {
length = PySequence_Fast_GET_SIZE(init);
}
else if (PyUnicode_Check(init)) {
/* from a unicode, we add the null terminator */
if (ctitem->ct_size == 2)
length = _my_PyUnicode_SizeAsChar16(init);
else
length = _my_PyUnicode_SizeAsChar32(init);
length += 1;
}
else if ((ctitem->ct_flags & CT_IS_FILE) && PyFile_Check(init)) {
*output_data = (char *)PyFile_AsFile(init);
if (*output_data == NULL && PyErr_Occurred())
return -1;
return 0;
}
else {
/* refuse to receive just an integer (and interpret it
as the array size) */
goto convert_default;
}
if (ctitem->ct_size <= 0)
goto convert_default;
datasize = MUL_WRAPAROUND(length, ctitem->ct_size);
if ((datasize / ctitem->ct_size) != length) {
PyErr_SetString(PyExc_OverflowError,
"array size would overflow a Py_ssize_t");
return -1;
}
if (datasize <= 0)
datasize = 1;
return datasize;
convert_default:
return convert_from_object((char *)output_data, ctptr, init);
}
static PyObject*
cdata_call(CDataObject *cd, PyObject *args, PyObject *kwds)
{
char *buffer;
void** buffer_array;
cif_description_t *cif_descr;
Py_ssize_t i, nargs, nargs_declared;
PyObject *signature, *res = NULL, *fvarargs;
CTypeDescrObject *fresult;
char *resultdata;
char *errormsg;
struct freeme_s {
struct freeme_s *next;
union_alignment alignment;
} *freeme = NULL;
if (!(cd->c_type->ct_flags & CT_FUNCTIONPTR)) {
PyErr_Format(PyExc_TypeError, "cdata '%s' is not callable",
cd->c_type->ct_name);
return NULL;
}
if (cd->c_data == NULL) {
PyErr_Format(PyExc_RuntimeError,
"cannot call null pointer pointer from cdata '%s'",
cd->c_type->ct_name);
return NULL;
}
if (kwds != NULL && PyDict_Size(kwds) != 0) {
PyErr_SetString(PyExc_TypeError,
"a cdata function cannot be called with keyword arguments");
return NULL;
}
signature = cd->c_type->ct_stuff;
nargs = PyTuple_Size(args);
if (nargs < 0)
return NULL;
nargs_declared = PyTuple_GET_SIZE(signature) - 2;
fresult = (CTypeDescrObject *)PyTuple_GET_ITEM(signature, 1);
fvarargs = NULL;
buffer = NULL;
cif_descr = (cif_description_t *)cd->c_type->ct_extra;
if (cif_descr != NULL) {
/* regular case: this function does not take '...' arguments */
if (nargs != nargs_declared) {
errormsg = "'%s' expects %zd arguments, got %zd";
bad_number_of_arguments:
PyErr_Format(PyExc_TypeError, errormsg,
cd->c_type->ct_name, nargs_declared, nargs);
goto error;
}
}
else {
/* call of a variadic function */
ffi_abi fabi;
if (nargs < nargs_declared) {
errormsg = "'%s' expects at least %zd arguments, got %zd";
goto bad_number_of_arguments;
}
fvarargs = PyTuple_New(nargs);
if (fvarargs == NULL)
goto error;
for (i = 0; i < nargs_declared; i++) {
PyObject *o = PyTuple_GET_ITEM(signature, 2 + i);
Py_INCREF(o);
PyTuple_SET_ITEM(fvarargs, i, o);
}
for (i = nargs_declared; i < nargs; i++) {
PyObject *obj = PyTuple_GET_ITEM(args, i);
CTypeDescrObject *ct;
if (CData_Check(obj)) {
ct = ((CDataObject *)obj)->c_type;
if (ct->ct_flags & (CT_PRIMITIVE_CHAR | CT_PRIMITIVE_UNSIGNED |
CT_PRIMITIVE_SIGNED)) {
if (ct->ct_size < (Py_ssize_t)sizeof(int)) {
ct = _get_ct_int();
if (ct == NULL)
goto error;
}
}
else if (ct->ct_flags & CT_ARRAY) {
ct = (CTypeDescrObject *)ct->ct_stuff;
}
Py_INCREF(ct);
}
else {
PyErr_Format(PyExc_TypeError,
"argument %zd passed in the variadic part "
"needs to be a cdata object (got %.200s)",
i + 1, Py_TYPE(obj)->tp_name);
goto error;
}
PyTuple_SET_ITEM(fvarargs, i, (PyObject *)ct);
}
#if PY_MAJOR_VERSION < 3
fabi = PyInt_AS_LONG(PyTuple_GET_ITEM(signature, 0));
#else
fabi = PyLong_AS_LONG(PyTuple_GET_ITEM(signature, 0));
#endif
cif_descr = fb_prepare_cif(fvarargs, fresult, nargs_declared, fabi);
if (cif_descr == NULL)
goto error;
}
buffer = PyObject_Malloc(cif_descr->exchange_size);
if (buffer == NULL) {
PyErr_NoMemory();
goto error;
}
buffer_array = (void **)buffer;
for (i=0; i<nargs; i++) {
CTypeDescrObject *argtype;
char *data = buffer + cif_descr->exchange_offset_arg[1 + i];
PyObject *obj = PyTuple_GET_ITEM(args, i);
buffer_array[i] = data;
if (i < nargs_declared)
argtype = (CTypeDescrObject *)PyTuple_GET_ITEM(signature, 2 + i);
else
argtype = (CTypeDescrObject *)PyTuple_GET_ITEM(fvarargs, i);
if (argtype->ct_flags & CT_POINTER) {
char *tmpbuf;
Py_ssize_t datasize = _prepare_pointer_call_argument(
argtype, obj, (char **)data);
if (datasize == 0)
; /* successfully filled '*data' */
else if (datasize < 0)
goto error;
else {
if (datasize <= 512) {
tmpbuf = alloca(datasize);
}
else {
struct freeme_s *fp = (struct freeme_s *)PyObject_Malloc(
offsetof(struct freeme_s, alignment) +
(size_t)datasize);
if (fp == NULL) {
PyErr_NoMemory();
goto error;
}
fp->next = freeme;
freeme = fp;
tmpbuf = (char *)&fp->alignment;
}
memset(tmpbuf, 0, datasize);
*(char **)data = tmpbuf;
if (convert_array_from_object(tmpbuf, argtype, obj) < 0)
goto error;
}
}
else if (convert_from_object(data, argtype, obj) < 0)
goto error;
}
resultdata = buffer + cif_descr->exchange_offset_arg[0];
/*READ(cd->c_data, sizeof(void(*)(void)))*/
Py_BEGIN_ALLOW_THREADS
restore_errno();
ffi_call(&cif_descr->cif, (void (*)(void))(cd->c_data),
resultdata, buffer_array);
save_errno();
Py_END_ALLOW_THREADS
if (fresult->ct_flags & (CT_PRIMITIVE_CHAR | CT_PRIMITIVE_SIGNED |
CT_PRIMITIVE_UNSIGNED)) {
#ifdef WORDS_BIGENDIAN
/* For results of precisely these types, libffi has a strange
rule that they will be returned as a whole 'ffi_arg' if they
are smaller. The difference only matters on big-endian. */
if (fresult->ct_size < sizeof(ffi_arg))
resultdata += (sizeof(ffi_arg) - fresult->ct_size);
#endif
res = convert_to_object(resultdata, fresult);
}
else if (fresult->ct_flags & CT_VOID) {
res = Py_None;
Py_INCREF(res);
}
else if (fresult->ct_flags & CT_STRUCT) {
res = convert_struct_to_owning_object(resultdata, fresult);
}
else {
res = convert_to_object(resultdata, fresult);
}
/* fall-through */
error:
while (freeme != NULL) {
void *p = (void *)freeme;
freeme = freeme->next;
PyObject_Free(p);
}
if (buffer)
PyObject_Free(buffer);
if (fvarargs != NULL) {
Py_DECREF(fvarargs);
if (cif_descr != NULL) /* but only if fvarargs != NULL, if variadic */
PyObject_Free(cif_descr);
}
return res;
}
static PyObject *cdata_dir(PyObject *cd, PyObject *noarg)
{
CTypeDescrObject *ct = ((CDataObject *)cd)->c_type;
/* replace the type 'pointer-to-t' with just 't' */
if (ct->ct_flags & CT_POINTER) {
ct = ct->ct_itemdescr;
}
if ((ct->ct_flags & (CT_STRUCT | CT_UNION)) &&
!(ct->ct_flags & CT_IS_OPAQUE)) {
/* for non-opaque structs or unions */
if (force_lazy_struct(ct) < 0)
return NULL;
return PyDict_Keys(ct->ct_stuff);
}
else {
return PyList_New(0); /* empty list for the other cases */
}
}
static PyObject *cdata_complex(PyObject *cd_, PyObject *noarg)
{
CDataObject *cd = (CDataObject *)cd_;
if (cd->c_type->ct_flags & CT_PRIMITIVE_COMPLEX) {
Py_complex value = read_raw_complex_data(cd->c_data, cd->c_type->ct_size);
PyObject *op = PyComplex_FromCComplex(value);
return op;
}
/* <cdata 'float'> or <cdata 'int'> cannot be directly converted by
calling complex(), just like <cdata 'int'> cannot be directly
converted by calling float() */
PyErr_Format(PyExc_TypeError, "complex() not supported on cdata '%s'",
cd->c_type->ct_name);
return NULL;
}
static int explicit_release_case(PyObject *cd)
{
CTypeDescrObject *ct = ((CDataObject *)cd)->c_type;
if (Py_TYPE(cd) == &CDataOwning_Type) {
if ((ct->ct_flags & (CT_POINTER | CT_ARRAY)) != 0) /* ffi.new() */
return 0;
}
else if (Py_TYPE(cd) == &CDataFromBuf_Type) {
return 1; /* ffi.from_buffer() */
}
else if (Py_TYPE(cd) == &CDataGCP_Type) {
return 2; /* ffi.gc() */
}
PyErr_SetString(PyExc_ValueError,
"only 'cdata' object from ffi.new(), ffi.gc(), ffi.from_buffer() "
"or ffi.new_allocator()() can be used with the 'with' keyword or "
"ffi.release()");
return -1;
}
static PyObject *cdata_enter(PyObject *cd, PyObject *noarg)
{
if (explicit_release_case(cd) < 0) /* only to check the ctype */
return NULL;
Py_INCREF(cd);
return cd;
}
static PyObject *cdata_exit(PyObject *cd, PyObject *args)
{
/* 'args' ignored */
CTypeDescrObject *ct;
Py_buffer *view;
switch (explicit_release_case(cd))
{
case 0: /* ffi.new() */
/* no effect on CPython: raw memory is allocated with the
same malloc() as the object itself, so it can't be
released independently. If we use a custom allocator,
then it's implemented with ffi.gc(). */
ct = ((CDataObject *)cd)->c_type;
if (ct->ct_flags & CT_IS_PTR_TO_OWNED) {
PyObject *x = ((CDataObject_own_structptr *)cd)->structobj;
if (Py_TYPE(x) == &CDataGCP_Type) {
/* this is a special case for
ffi.new_allocator()("struct-or-union *") */
cdatagcp_finalize((CDataObject_gcp *)x);
}
}
break;
case 1: /* ffi.from_buffer() */
view = ((CDataObject_frombuf *)cd)->bufferview;
PyBuffer_Release(view);
break;
case 2: /* ffi.gc() or ffi.new_allocator()("not-struct-nor-union") */
/* call the destructor immediately */
cdatagcp_finalize((CDataObject_gcp *)cd);
break;
default:
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *cdata_iter(CDataObject *);
static PyNumberMethods CData_as_number = {
(binaryfunc)cdata_add, /*nb_add*/
(binaryfunc)cdata_sub, /*nb_subtract*/
0, /*nb_multiply*/
#if PY_MAJOR_VERSION < 3
0, /*nb_divide*/
#endif
0, /*nb_remainder*/
0, /*nb_divmod*/
0, /*nb_power*/
0, /*nb_negative*/
0, /*nb_positive*/
0, /*nb_absolute*/
(inquiry)cdata_nonzero, /*nb_nonzero*/
0, /*nb_invert*/
0, /*nb_lshift*/
0, /*nb_rshift*/
0, /*nb_and*/
0, /*nb_xor*/
0, /*nb_or*/
#if PY_MAJOR_VERSION < 3
0, /*nb_coerce*/
#endif
(unaryfunc)cdata_int, /*nb_int*/
#if PY_MAJOR_VERSION < 3
(unaryfunc)cdata_long, /*nb_long*/
#else
0,
#endif
(unaryfunc)cdata_float, /*nb_float*/
0, /*nb_oct*/
0, /*nb_hex*/
};
static PyMappingMethods CData_as_mapping = {
(lenfunc)cdata_length, /*mp_length*/
(binaryfunc)cdata_subscript, /*mp_subscript*/
(objobjargproc)cdata_ass_sub, /*mp_ass_subscript*/
};
static PyMappingMethods CDataOwn_as_mapping = {
(lenfunc)cdata_length, /*mp_length*/
(binaryfunc)cdataowning_subscript, /*mp_subscript*/
(objobjargproc)cdata_ass_sub, /*mp_ass_subscript*/
};
static PyMethodDef cdata_methods[] = {
{"__dir__", cdata_dir, METH_NOARGS},
{"__complex__", cdata_complex, METH_NOARGS},
{"__enter__", cdata_enter, METH_NOARGS},
{"__exit__", cdata_exit, METH_VARARGS},
{NULL, NULL} /* sentinel */
};
static PyTypeObject CData_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"_cffi_backend._CDataBase",
sizeof(CDataObject),
0,
(destructor)cdata_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
(reprfunc)cdata_repr, /* tp_repr */
&CData_as_number, /* tp_as_number */
0, /* tp_as_sequence */
&CData_as_mapping, /* tp_as_mapping */
cdata_hash, /* tp_hash */
(ternaryfunc)cdata_call, /* tp_call */
0, /* tp_str */
(getattrofunc)cdata_getattro, /* tp_getattro */
(setattrofunc)cdata_setattro, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES, /* tp_flags */
"The internal base type for CData objects. Use FFI.CData to access "
"it. Always check with isinstance(): subtypes are sometimes returned "
"on CPython, for performance reasons.", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
cdata_richcompare, /* tp_richcompare */
offsetof(CDataObject, c_weakreflist), /* tp_weaklistoffset */
(getiterfunc)cdata_iter, /* tp_iter */
0, /* tp_iternext */
cdata_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
PyObject_Del, /* tp_free */
};
static PyTypeObject CDataOwning_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"_cffi_backend.__CDataOwn",
sizeof(CDataObject),
0,
(destructor)cdataowning_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
(reprfunc)cdataowning_repr, /* tp_repr */
0, /* inherited */ /* tp_as_number */
0, /* tp_as_sequence */
&CDataOwn_as_mapping, /* tp_as_mapping */
0, /* inherited */ /* tp_hash */
0, /* inherited */ /* tp_call */
0, /* tp_str */
0, /* inherited */ /* tp_getattro */
0, /* inherited */ /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES, /* tp_flags */
"This is an internal subtype of _CDataBase for performance only on "
"CPython. Check with isinstance(x, ffi.CData).", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* inherited */ /* tp_richcompare */
0, /* inherited */ /* tp_weaklistoffset */
0, /* inherited */ /* tp_iter */
0, /* tp_iternext */
0, /* inherited */ /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
&CData_Type, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
free, /* tp_free */
};
static PyTypeObject CDataOwningGC_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"_cffi_backend.__CDataOwnGC",
sizeof(CDataObject_own_structptr),
0,
(destructor)cdataowninggc_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
(reprfunc)cdataowninggc_repr, /* tp_repr */
0, /* inherited */ /* tp_as_number */
0, /* tp_as_sequence */
0, /* inherited */ /* tp_as_mapping */
0, /* inherited */ /* tp_hash */
0, /* inherited */ /* tp_call */
0, /* tp_str */
0, /* inherited */ /* tp_getattro */
0, /* inherited */ /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES /* tp_flags */
| Py_TPFLAGS_HAVE_GC,
"This is an internal subtype of _CDataBase for performance only on "
"CPython. Check with isinstance(x, ffi.CData).", /* tp_doc */
(traverseproc)cdataowninggc_traverse, /* tp_traverse */
(inquiry)cdataowninggc_clear, /* tp_clear */
0, /* inherited */ /* tp_richcompare */
0, /* inherited */ /* tp_weaklistoffset */
0, /* inherited */ /* tp_iter */
0, /* tp_iternext */
0, /* inherited */ /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
&CDataOwning_Type, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
PyObject_GC_Del, /* tp_free */
};
static PyTypeObject CDataFromBuf_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"_cffi_backend.__CDataFromBuf",
sizeof(CDataObject_frombuf),
0,
(destructor)cdatafrombuf_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
(reprfunc)cdatafrombuf_repr, /* tp_repr */
0, /* inherited */ /* tp_as_number */
0, /* tp_as_sequence */
0, /* inherited */ /* tp_as_mapping */
0, /* inherited */ /* tp_hash */
0, /* inherited */ /* tp_call */
0, /* tp_str */
0, /* inherited */ /* tp_getattro */
0, /* inherited */ /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES /* tp_flags */
| Py_TPFLAGS_HAVE_GC,
"This is an internal subtype of _CDataBase for performance only on "
"CPython. Check with isinstance(x, ffi.CData).", /* tp_doc */
(traverseproc)cdatafrombuf_traverse, /* tp_traverse */
(inquiry)cdatafrombuf_clear, /* tp_clear */
0, /* inherited */ /* tp_richcompare */
0, /* inherited */ /* tp_weaklistoffset */
0, /* inherited */ /* tp_iter */
0, /* tp_iternext */
0, /* inherited */ /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
&CData_Type, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
PyObject_GC_Del, /* tp_free */
};
static PyTypeObject CDataGCP_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"_cffi_backend.__CDataGCP",
sizeof(CDataObject_gcp),
0,
(destructor)cdatagcp_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* inherited */ /* tp_repr */
0, /* inherited */ /* tp_as_number */
0, /* tp_as_sequence */
0, /* inherited */ /* tp_as_mapping */
0, /* inherited */ /* tp_hash */
0, /* inherited */ /* tp_call */
0, /* tp_str */
0, /* inherited */ /* tp_getattro */
0, /* inherited */ /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES /* tp_flags */
#ifdef Py_TPFLAGS_HAVE_FINALIZE
| Py_TPFLAGS_HAVE_FINALIZE
#endif
| Py_TPFLAGS_HAVE_GC,
"This is an internal subtype of _CDataBase for performance only on "
"CPython. Check with isinstance(x, ffi.CData).", /* tp_doc */
(traverseproc)cdatagcp_traverse, /* tp_traverse */
0, /* tp_clear */
0, /* inherited */ /* tp_richcompare */
0, /* inherited */ /* tp_weaklistoffset */
0, /* inherited */ /* tp_iter */
0, /* tp_iternext */
0, /* inherited */ /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
&CData_Type, /* tp_base */
#ifdef Py_TPFLAGS_HAVE_FINALIZE /* CPython >= 3.4 */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
0, /* inherited */ /* tp_free */
0, /* tp_is_gc */
0, /* tp_bases */
0, /* tp_mro */
0, /* tp_cache */
0, /* tp_subclasses */
0, /* tp_weaklist */
0, /* tp_del */
0, /* version_tag */
(destructor)cdatagcp_finalize, /* tp_finalize */
#endif
};
/************************************************************/
typedef struct {
PyObject_HEAD
char *di_next, *di_stop;
CDataObject *di_object;
CTypeDescrObject *di_itemtype;
} CDataIterObject;
static PyObject *
cdataiter_next(CDataIterObject *it)
{
char *result = it->di_next;
if (result != it->di_stop) {
it->di_next = result + it->di_itemtype->ct_size;
return convert_to_object(result, it->di_itemtype);
}
return NULL;
}
static void
cdataiter_dealloc(CDataIterObject *it)
{
Py_DECREF(it->di_object);
PyObject_Del(it);
}
static PyTypeObject CDataIter_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"_cffi_backend.__CData_iterator", /* tp_name */
sizeof(CDataIterObject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)cdataiter_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
PyObject_SelfIter, /* tp_iter */
(iternextfunc)cdataiter_next, /* tp_iternext */
};
static PyObject *
cdata_iter(CDataObject *cd)
{
CDataIterObject *it;
if (!(cd->c_type->ct_flags & CT_ARRAY)) {
PyErr_Format(PyExc_TypeError, "cdata '%s' does not support iteration",
cd->c_type->ct_name);
return NULL;
}
it = PyObject_New(CDataIterObject, &CDataIter_Type);
if (it == NULL)
return NULL;
Py_INCREF(cd);
it->di_object = cd;
it->di_itemtype = cd->c_type->ct_itemdescr;
it->di_next = cd->c_data;
it->di_stop = cd->c_data + get_array_length(cd) * it->di_itemtype->ct_size;
return (PyObject *)it;
}
/************************************************************/
static CDataObject *allocate_owning_object(Py_ssize_t size,
CTypeDescrObject *ct,
int dont_clear)
{
/* note: objects with &CDataOwning_Type are always allocated with
either a plain malloc() or calloc(), and freed with free(). */
CDataObject *cd;
if (dont_clear)
cd = malloc(size);
else
cd = calloc(size, 1);
if (PyObject_Init((PyObject *)cd, &CDataOwning_Type) == NULL)
return NULL;
Py_INCREF(ct);
cd->c_type = ct;
cd->c_weakreflist = NULL;
return cd;
}
static PyObject *
convert_struct_to_owning_object(char *data, CTypeDescrObject *ct)
{
/* also accepts unions, for the API mode */
CDataObject *cd;
Py_ssize_t dataoffset = offsetof(CDataObject_own_nolength, alignment);
Py_ssize_t datasize = ct->ct_size;
if (datasize < 0) {
PyErr_SetString(PyExc_TypeError,
"return type is an opaque structure or union");
return NULL;
}
if (ct->ct_flags & CT_WITH_VAR_ARRAY) {
PyErr_SetString(PyExc_TypeError,
"return type is a struct/union with a varsize array member");
return NULL;
}
cd = allocate_owning_object(dataoffset + datasize, ct, /*dont_clear=*/1);
if (cd == NULL)
return NULL;
cd->c_data = ((char *)cd) + dataoffset;
memcpy(cd->c_data, data, datasize);
return (PyObject *)cd;
}
static CDataObject *allocate_gcp_object(CDataObject *origobj,
CTypeDescrObject *ct,
PyObject *destructor)
{
CDataObject_gcp *cd = PyObject_GC_New(CDataObject_gcp, &CDataGCP_Type);
if (cd == NULL)
return NULL;
Py_XINCREF(destructor);
Py_INCREF(origobj);
Py_INCREF(ct);
cd->head.c_data = origobj->c_data;
cd->head.c_type = ct;
cd->head.c_weakreflist = NULL;
cd->origobj = (PyObject *)origobj;
cd->destructor = destructor;
PyObject_GC_Track(cd);
return (CDataObject *)cd;
}
static CDataObject *allocate_with_allocator(Py_ssize_t basesize,
Py_ssize_t datasize,
CTypeDescrObject *ct,
const cffi_allocator_t *allocator)
{
CDataObject *cd;
if (allocator->ca_alloc == NULL) {
cd = allocate_owning_object(basesize + datasize, ct,
allocator->ca_dont_clear);
if (cd == NULL)
return NULL;
cd->c_data = ((char *)cd) + basesize;
}
else {
PyObject *res = PyObject_CallFunction(allocator->ca_alloc, "n", datasize);
if (res == NULL)
return NULL;
if (!CData_Check(res)) {
PyErr_Format(PyExc_TypeError,
"alloc() must return a cdata object (got %.200s)",
Py_TYPE(res)->tp_name);
Py_DECREF(res);
return NULL;
}
cd = (CDataObject *)res;
if (!(cd->c_type->ct_flags & (CT_POINTER|CT_ARRAY))) {
PyErr_Format(PyExc_TypeError,
"alloc() must return a cdata pointer, not '%s'",
cd->c_type->ct_name);
Py_DECREF(res);
return NULL;
}
if (!cd->c_data) {
PyErr_SetString(PyExc_MemoryError, "alloc() returned NULL");
Py_DECREF(res);
return NULL;
}
cd = allocate_gcp_object(cd, ct, allocator->ca_free);
Py_DECREF(res);
if (!allocator->ca_dont_clear)
memset(cd->c_data, 0, datasize);
}
return cd;
}
static PyObject *direct_newp(CTypeDescrObject *ct, PyObject *init,
const cffi_allocator_t *allocator)
{
CTypeDescrObject *ctitem;
CDataObject *cd;
Py_ssize_t dataoffset, datasize, explicitlength;
explicitlength = -1;
if (ct->ct_flags & CT_POINTER) {
dataoffset = offsetof(CDataObject_own_nolength, alignment);
ctitem = ct->ct_itemdescr;
datasize = ctitem->ct_size;
if (datasize < 0) {
PyErr_Format(PyExc_TypeError,
"cannot instantiate ctype '%s' of unknown size",
ctitem->ct_name);
return NULL;
}
if (ctitem->ct_flags & CT_PRIMITIVE_CHAR)
datasize *= 2; /* forcefully add another character: a null */
if (ctitem->ct_flags & (CT_STRUCT | CT_UNION)) {
if (force_lazy_struct(ctitem) < 0) /* for CT_WITH_VAR_ARRAY */
return NULL;
if (ctitem->ct_flags & CT_WITH_VAR_ARRAY) {
assert(ct->ct_flags & CT_IS_PTR_TO_OWNED);
dataoffset = offsetof(CDataObject_own_length, alignment);
if (init != Py_None) {
Py_ssize_t optvarsize = datasize;
if (convert_struct_from_object(NULL, ctitem, init,
&optvarsize) < 0)
return NULL;
datasize = optvarsize;
}
}
}
}
else if (ct->ct_flags & CT_ARRAY) {
dataoffset = offsetof(CDataObject_own_nolength, alignment);
datasize = ct->ct_size;
if (datasize < 0) {
explicitlength = get_new_array_length(ct->ct_itemdescr, &init);
if (explicitlength < 0)
return NULL;
ctitem = ct->ct_itemdescr;
dataoffset = offsetof(CDataObject_own_length, alignment);
datasize = MUL_WRAPAROUND(explicitlength, ctitem->ct_size);
if (explicitlength > 0 &&
(datasize / explicitlength) != ctitem->ct_size) {
PyErr_SetString(PyExc_OverflowError,
"array size would overflow a Py_ssize_t");
return NULL;
}
}
}
else {
PyErr_Format(PyExc_TypeError,
"expected a pointer or array ctype, got '%s'",
ct->ct_name);
return NULL;
}
if (ct->ct_flags & CT_IS_PTR_TO_OWNED) {
/* common case of ptr-to-struct (or ptr-to-union): for this case
we build two objects instead of one, with the memory-owning
one being really the struct (or union) and the returned one
having a strong reference to it */
CDataObject *cds;
cds = allocate_with_allocator(dataoffset, datasize, ct->ct_itemdescr,
allocator);
if (cds == NULL)
return NULL;
cd = allocate_owning_object(sizeof(CDataObject_own_structptr), ct,
/*dont_clear=*/1);
if (cd == NULL) {
Py_DECREF(cds);
return NULL;
}
/* store the only reference to cds into cd */
((CDataObject_own_structptr *)cd)->structobj = (PyObject *)cds;
/* store information about the allocated size of the struct */
if (dataoffset == offsetof(CDataObject_own_length, alignment)) {
((CDataObject_own_length *)cds)->length = datasize;
}
assert(explicitlength < 0);
cd->c_data = cds->c_data;
}
else {
cd = allocate_with_allocator(dataoffset, datasize, ct, allocator);
if (cd == NULL)
return NULL;
if (explicitlength >= 0)
((CDataObject_own_length*)cd)->length = explicitlength;
}
if (init != Py_None) {
if (convert_from_object(cd->c_data,
(ct->ct_flags & CT_POINTER) ? ct->ct_itemdescr : ct, init) < 0) {
Py_DECREF(cd);
return NULL;
}
}
return (PyObject *)cd;
}
static PyObject *b_newp(PyObject *self, PyObject *args)
{
CTypeDescrObject *ct;
PyObject *init = Py_None;
if (!PyArg_ParseTuple(args, "O!|O:newp", &CTypeDescr_Type, &ct, &init))
return NULL;
return direct_newp(ct, init, &default_allocator);
}
static int
_my_PyObject_AsBool(PyObject *ob)
{
/* convert and cast a Python object to a boolean. Accept an integer
or a float object, up to a CData 'long double'. */
PyObject *io;
PyNumberMethods *nb;
int res;
#if PY_MAJOR_VERSION < 3
if (PyInt_Check(ob)) {
return PyInt_AS_LONG(ob) != 0;
}
else
#endif
if (PyLong_Check(ob)) {
return _PyLong_Sign(ob) != 0;
}
else if (PyFloat_Check(ob)) {
return PyFloat_AS_DOUBLE(ob) != 0.0;
}
else if (CData_Check(ob)) {
CDataObject *cd = (CDataObject *)ob;
if (cd->c_type->ct_flags & CT_PRIMITIVE_FLOAT) {
/*READ(cd->c_data, cd->c_type->ct_size)*/
if (cd->c_type->ct_flags & CT_IS_LONGDOUBLE) {
/* 'long double' objects: return the answer directly */
return read_raw_longdouble_data(cd->c_data) != 0.0;
}
else {
/* 'float'/'double' objects: return the answer directly */
return read_raw_float_data(cd->c_data,
cd->c_type->ct_size) != 0.0;
}
}
}
nb = ob->ob_type->tp_as_number;
if (nb == NULL || (nb->nb_float == NULL && nb->nb_int == NULL)) {
PyErr_SetString(PyExc_TypeError, "integer/float expected");
return -1;
}
if (nb->nb_float && !CData_Check(ob))
io = (*nb->nb_float) (ob);
else
io = (*nb->nb_int) (ob);
if (io == NULL)
return -1;
if (PyIntOrLong_Check(io) || PyFloat_Check(io)) {
res = _my_PyObject_AsBool(io);
}
else {
PyErr_SetString(PyExc_TypeError, "integer/float conversion failed");
res = -1;
}
Py_DECREF(io);
return res;
}
static CDataObject *_new_casted_primitive(CTypeDescrObject *ct)
{
int dataoffset = offsetof(CDataObject_casted_primitive, alignment);
CDataObject *cd = (CDataObject *)PyObject_Malloc(dataoffset + ct->ct_size);
if (PyObject_Init((PyObject *)cd, &CData_Type) == NULL)
return NULL;
Py_INCREF(ct);
cd->c_type = ct;
cd->c_data = ((char*)cd) + dataoffset;
cd->c_weakreflist = NULL;
return cd;
}
static CDataObject *cast_to_integer_or_char(CTypeDescrObject *ct, PyObject *ob)
{
unsigned PY_LONG_LONG value;
CDataObject *cd;
if (CData_Check(ob) &&
((CDataObject *)ob)->c_type->ct_flags &
(CT_POINTER|CT_FUNCTIONPTR|CT_ARRAY)) {
value = (Py_intptr_t)((CDataObject *)ob)->c_data;
}
#if PY_MAJOR_VERSION < 3
else if (PyString_Check(ob)) {
if (PyString_GET_SIZE(ob) != 1) {
PyErr_Format(PyExc_TypeError,
"cannot cast string of length %zd to ctype '%s'",
PyString_GET_SIZE(ob), ct->ct_name);
return NULL;
}
value = (unsigned char)PyString_AS_STRING(ob)[0];
}
#endif
else if (PyUnicode_Check(ob)) {
char err_buf[80];
cffi_char32_t ordinal;
if (_my_PyUnicode_AsSingleChar32(ob, &ordinal, err_buf) < 0) {
PyErr_Format(PyExc_TypeError,
"cannot cast %s to ctype '%s'", err_buf, ct->ct_name);
return NULL;
}
/* the types char16_t and char32_t are both unsigned. However,
wchar_t might be signed. In theory it does not matter,
because 'ordinal' comes from a regular Python unicode. */
#ifdef HAVE_WCHAR_H
if (ct->ct_flags & CT_IS_SIGNED_WCHAR)
value = (wchar_t)ordinal;
else
#endif
value = ordinal;
}
else if (PyBytes_Check(ob)) {
int res = _convert_to_char(ob);
if (res < 0)
return NULL;
value = (unsigned char)res;
}
else if (ct->ct_flags & CT_IS_BOOL) {
int res = _my_PyObject_AsBool(ob);
if (res < 0)
return NULL;
value = res;
}
else {
value = _my_PyLong_AsUnsignedLongLong(ob, 0);
if (value == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
return NULL;
}
if (ct->ct_flags & CT_IS_BOOL)
value = !!value;
cd = _new_casted_primitive(ct);
if (cd != NULL)
write_raw_integer_data(cd->c_data, value, ct->ct_size);
return cd;
}
/* returns -1 if cannot cast, 0 if we don't get a value, 1 if we do */
static int check_bytes_for_float_compatible(PyObject *io, double *out_value)
{
if (PyBytes_Check(io)) {
if (PyBytes_GET_SIZE(io) != 1)
goto error;
*out_value = (unsigned char)PyBytes_AS_STRING(io)[0];
return 1;
}
else if (PyUnicode_Check(io)) {
char ignored[80];
cffi_char32_t ordinal;
if (_my_PyUnicode_AsSingleChar32(io, &ordinal, ignored) < 0)
goto error;
/* the signness of the 32-bit version of wide chars should not
* matter here, because 'ordinal' comes from a normal Python
* unicode string */
*out_value = ordinal;
return 1;
}
*out_value = 0; /* silence a gcc warning if this function is inlined */
return 0;
error:
Py_DECREF(io);
*out_value = 0; /* silence a gcc warning if this function is inlined */
return -1;
}
static PyObject *do_cast(CTypeDescrObject *ct, PyObject *ob)
{
CDataObject *cd;
if (ct->ct_flags & (CT_POINTER|CT_FUNCTIONPTR|CT_ARRAY) &&
ct->ct_size >= 0) {
/* cast to a pointer, to a funcptr, or to an array.
Note that casting to an array is an extension to the C language,
which seems to be necessary in order to sanely get a
<cdata 'int[3]'> at some address. */
unsigned PY_LONG_LONG value;
if (CData_Check(ob)) {
CDataObject *cdsrc = (CDataObject *)ob;
if (cdsrc->c_type->ct_flags &
(CT_POINTER|CT_FUNCTIONPTR|CT_ARRAY)) {
return new_simple_cdata(cdsrc->c_data, ct);
}
}
if ((ct->ct_flags & CT_POINTER) &&
(ct->ct_itemdescr->ct_flags & CT_IS_FILE) &&
PyFile_Check(ob)) {
FILE *f = PyFile_AsFile(ob);
if (f == NULL && PyErr_Occurred())
return NULL;
return new_simple_cdata((char *)f, ct);
}
value = _my_PyLong_AsUnsignedLongLong(ob, 0);
if (value == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
return NULL;
return new_simple_cdata((char *)(Py_intptr_t)value, ct);
}
else if (ct->ct_flags & (CT_PRIMITIVE_SIGNED|CT_PRIMITIVE_UNSIGNED
|CT_PRIMITIVE_CHAR)) {
/* cast to an integer type or a char */
return (PyObject *)cast_to_integer_or_char(ct, ob);
}
else if (ct->ct_flags & CT_PRIMITIVE_FLOAT) {
/* cast to a float */
double value;
PyObject *io;
int res;
if (CData_Check(ob)) {
CDataObject *cdsrc = (CDataObject *)ob;
if (!(cdsrc->c_type->ct_flags & CT_PRIMITIVE_ANY))
goto cannot_cast;
io = convert_to_object(cdsrc->c_data, cdsrc->c_type);
if (io == NULL)
return NULL;
}
else {
io = ob;
Py_INCREF(io);
}
res = check_bytes_for_float_compatible(io, &value);
if (res == -1)
goto cannot_cast;
if (res == 0) {
if ((ct->ct_flags & CT_IS_LONGDOUBLE) &&
CData_Check(io) &&
(((CDataObject *)io)->c_type->ct_flags & CT_IS_LONGDOUBLE)) {
long double lvalue;
char *data = ((CDataObject *)io)->c_data;
/*READ(data, sizeof(long double)*/
lvalue = read_raw_longdouble_data(data);
Py_DECREF(io);
cd = _new_casted_primitive(ct);
if (cd != NULL)
write_raw_longdouble_data(cd->c_data, lvalue);
return (PyObject *)cd;
}
value = PyFloat_AsDouble(io);
}
Py_DECREF(io);
if (value == -1.0 && PyErr_Occurred())
return NULL;
cd = _new_casted_primitive(ct);
if (cd != NULL) {
if (!(ct->ct_flags & CT_IS_LONGDOUBLE))
write_raw_float_data(cd->c_data, value, ct->ct_size);
else
write_raw_longdouble_data(cd->c_data, (long double)value);
}
return (PyObject *)cd;
}
else if (ct->ct_flags & CT_PRIMITIVE_COMPLEX) {
/* cast to a complex */
Py_complex value;
PyObject *io;
int res;
if (CData_Check(ob)) {
CDataObject *cdsrc = (CDataObject *)ob;
if (!(cdsrc->c_type->ct_flags & CT_PRIMITIVE_ANY))
goto cannot_cast;
io = convert_to_object(cdsrc->c_data, cdsrc->c_type);
if (io == NULL)
return NULL;
}
else {
io = ob;
Py_INCREF(io);
}
res = check_bytes_for_float_compatible(io, &value.real);
if (res == -1)
goto cannot_cast;
if (res == 1) {
// got it from string
value.imag = 0.0;
} else {
value = PyComplex_AsCComplex(io);
}
Py_DECREF(io);
if (PyErr_Occurred()) {
return NULL;
}
cd = _new_casted_primitive(ct);
if (cd != NULL) {
write_raw_complex_data(cd->c_data, value, ct->ct_size);
}
return (PyObject *)cd;
}
else {
PyErr_Format(PyExc_TypeError, "cannot cast to ctype '%s'",
ct->ct_name);
return NULL;
}
cannot_cast:
if (CData_Check(ob))
PyErr_Format(PyExc_TypeError, "cannot cast ctype '%s' to ctype '%s'",
((CDataObject *)ob)->c_type->ct_name, ct->ct_name);
else
PyErr_Format(PyExc_TypeError,
"cannot cast %.200s object to ctype '%s'",
Py_TYPE(ob)->tp_name, ct->ct_name);
return NULL;
}
static PyObject *b_cast(PyObject *self, PyObject *args)
{
CTypeDescrObject *ct;
PyObject *ob;
if (!PyArg_ParseTuple(args, "O!O:cast", &CTypeDescr_Type, &ct, &ob))
return NULL;
return do_cast(ct, ob);
}
/************************************************************/
typedef struct {
PyObject_HEAD
void *dl_handle;
char *dl_name;
int dl_auto_close;
} DynLibObject;
static void dl_dealloc(DynLibObject *dlobj)
{
if (dlobj->dl_handle != NULL && dlobj->dl_auto_close)
dlclose(dlobj->dl_handle);
free(dlobj->dl_name);
PyObject_Del(dlobj);
}
static PyObject *dl_repr(DynLibObject *dlobj)
{
return PyText_FromFormat("<clibrary '%s'>", dlobj->dl_name);
}
static int dl_check_closed(DynLibObject *dlobj)
{
if (dlobj->dl_handle == NULL)
{
PyErr_Format(PyExc_ValueError, "library '%s' has already been closed",
dlobj->dl_name);
return -1;
}
return 0;
}
static PyObject *dl_load_function(DynLibObject *dlobj, PyObject *args)
{
CTypeDescrObject *ct;
char *funcname;
void *funcptr;
if (!PyArg_ParseTuple(args, "O!s:load_function",
&CTypeDescr_Type, &ct, &funcname))
return NULL;
if (dl_check_closed(dlobj) < 0)
return NULL;
if (!(ct->ct_flags & (CT_FUNCTIONPTR | CT_POINTER | CT_ARRAY))) {
PyErr_Format(PyExc_TypeError,
"function or pointer or array cdata expected, got '%s'",
ct->ct_name);
return NULL;
}
dlerror(); /* clear error condition */
funcptr = dlsym(dlobj->dl_handle, funcname);
if (funcptr == NULL) {
const char *error = dlerror();
PyErr_Format(PyExc_AttributeError,
"function/symbol '%s' not found in library '%s': %s",
funcname, dlobj->dl_name, error);
return NULL;
}
if ((ct->ct_flags & CT_ARRAY) && ct->ct_length < 0) {
ct = (CTypeDescrObject *)ct->ct_stuff;
}
return new_simple_cdata(funcptr, ct);
}
static PyObject *dl_read_variable(DynLibObject *dlobj, PyObject *args)
{
CTypeDescrObject *ct;
char *varname;
char *data;
if (!PyArg_ParseTuple(args, "O!s:read_variable",
&CTypeDescr_Type, &ct, &varname))
return NULL;
if (dl_check_closed(dlobj) < 0)
return NULL;
dlerror(); /* clear error condition */
data = dlsym(dlobj->dl_handle, varname);
if (data == NULL) {
const char *error = dlerror();
if (error != NULL) {
PyErr_Format(PyExc_KeyError,
"variable '%s' not found in library '%s': %s",
varname, dlobj->dl_name, error);
return NULL;
}
}
return convert_to_object(data, ct);
}
static PyObject *dl_write_variable(DynLibObject *dlobj, PyObject *args)
{
CTypeDescrObject *ct;
PyObject *value;
char *varname;
char *data;
if (!PyArg_ParseTuple(args, "O!sO:write_variable",
&CTypeDescr_Type, &ct, &varname, &value))
return NULL;
if (dl_check_closed(dlobj) < 0)
return NULL;
dlerror(); /* clear error condition */
data = dlsym(dlobj->dl_handle, varname);
if (data == NULL) {
const char *error = dlerror();
PyErr_Format(PyExc_KeyError,
"variable '%s' not found in library '%s': %s",
varname, dlobj->dl_name, error);
return NULL;
}
if (convert_from_object(data, ct, value) < 0)
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *dl_close_lib(DynLibObject *dlobj, PyObject *no_args)
{
if (dlobj->dl_handle != NULL)
{
dlclose(dlobj->dl_handle);
dlobj->dl_handle = NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef dl_methods[] = {
{"load_function", (PyCFunction)dl_load_function, METH_VARARGS},
{"read_variable", (PyCFunction)dl_read_variable, METH_VARARGS},
{"write_variable", (PyCFunction)dl_write_variable, METH_VARARGS},
{"close_lib", (PyCFunction)dl_close_lib, METH_NOARGS},
{NULL, NULL} /* sentinel */
};
static PyTypeObject dl_type = {
PyVarObject_HEAD_INIT(NULL, 0)
"_cffi_backend.CLibrary", /* tp_name */
sizeof(DynLibObject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)dl_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
(reprfunc)dl_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
dl_methods, /* tp_methods */
};
static void *b_do_dlopen(PyObject *args, const char **p_printable_filename,
PyObject **p_temp, int *auto_close)
{
/* Logic to call the correct version of dlopen(). Returns NULL in case of error.
Otherwise, '*p_printable_filename' will point to a printable char version of
the filename (maybe utf-8-encoded). '*p_temp' will be set either to NULL or
to a temporary object that must be freed after looking at printable_filename.
*/
void *handle;
char *filename_or_null;
int flags = 0;
*p_temp = NULL;
*auto_close = 1;
if (PyTuple_GET_SIZE(args) == 0 || PyTuple_GET_ITEM(args, 0) == Py_None) {
PyObject *dummy;
if (!PyArg_ParseTuple(args, "|Oi:load_library",
&dummy, &flags))
return NULL;
filename_or_null = NULL;
*p_printable_filename = "<None>";
}
else if (CData_Check(PyTuple_GET_ITEM(args, 0)))
{
CDataObject *cd;
if (!PyArg_ParseTuple(args, "O|i:load_library", &cd, &flags))
return NULL;
/* 'flags' is accepted but ignored in this case */
if ((cd->c_type->ct_flags & CT_IS_VOID_PTR) == 0) {
PyErr_Format(PyExc_TypeError,
"dlopen() takes a file name or 'void *' handle, not '%s'",
cd->c_type->ct_name);
return NULL;
}
handle = cd->c_data;
if (handle == NULL) {
PyErr_Format(PyExc_RuntimeError, "cannot call dlopen(NULL)");
return NULL;
}
*p_temp = PyText_FromFormat("%p", handle);
*p_printable_filename = PyText_AsUTF8(*p_temp);
*auto_close = 0;
return handle;
}
else
{
PyObject *s = PyTuple_GET_ITEM(args, 0);
#ifdef MS_WIN32
PyObject *filename_unicode;
if (PyArg_ParseTuple(args, "U|i:load_library", &filename_unicode, &flags))
{
Py_ssize_t sz1;
wchar_t *w1;
#if PY_MAJOR_VERSION < 3
s = PyUnicode_AsUTF8String(s);
if (s == NULL)
return NULL;
*p_temp = s;
#endif
*p_printable_filename = PyText_AsUTF8(s);
if (*p_printable_filename == NULL)
return NULL;
sz1 = PyUnicode_GetSize(filename_unicode) + 1;
sz1 *= 2; /* should not be needed, but you never know */
w1 = alloca(sizeof(wchar_t) * sz1);
sz1 = PyUnicode_AsWideChar((PyUnicodeObject *)filename_unicode,
w1, sz1 - 1);
if (sz1 < 0)
return NULL;
w1[sz1] = 0;
handle = dlopenW(w1);
goto got_handle;
}
PyErr_Clear();
#endif
if (!PyArg_ParseTuple(args, "et|i:load_library",
Py_FileSystemDefaultEncoding, &filename_or_null, &flags))
return NULL;
#if PY_MAJOR_VERSION < 3
if (PyUnicode_Check(s))
{
s = PyUnicode_AsUTF8String(s);
if (s == NULL)
return NULL;
*p_temp = s;
}
#endif
*p_printable_filename = PyText_AsUTF8(s);
if (*p_printable_filename == NULL)
return NULL;
}
if ((flags & (RTLD_NOW | RTLD_LAZY)) == 0)
flags |= RTLD_NOW;
#ifdef MS_WIN32
if (filename_or_null == NULL) {
PyErr_SetString(PyExc_OSError, "dlopen(None) not supported on Windows");
return NULL;
}
#endif
handle = dlopen(filename_or_null, flags);
#ifdef MS_WIN32
got_handle:
#endif
if (handle == NULL) {
const char *error = dlerror();
PyErr_Format(PyExc_OSError, "cannot load library '%s': %s",
*p_printable_filename, error);
return NULL;
}
return handle;
}
static PyObject *b_load_library(PyObject *self, PyObject *args)
{
const char *printable_filename;
PyObject *temp;
void *handle;
DynLibObject *dlobj = NULL;
int auto_close;
handle = b_do_dlopen(args, &printable_filename, &temp, &auto_close);
if (handle == NULL)
goto error;
dlobj = PyObject_New(DynLibObject, &dl_type);
if (dlobj == NULL) {
dlclose(handle);
goto error;
}
dlobj->dl_handle = handle;
dlobj->dl_name = strdup(printable_filename);
dlobj->dl_auto_close = auto_close;
error:
Py_XDECREF(temp);
return (PyObject *)dlobj;
}
/************************************************************/
static PyObject *get_unique_type(CTypeDescrObject *x,
const void *unique_key[], long keylength)
{
/* Replace the CTypeDescrObject 'x' with a standardized one.
This either just returns x, or x is decrefed and a new reference
to the already-existing equivalent is returned.
In this function, 'x' always contains a reference that must be
either decrefed or returned.
Keys:
void ["void"]
primitive [&static_struct]
pointer [ctype]
array [ctype, length]
funcptr [ctresult, ellipsis+abi, num_args, ctargs...]
*/
PyObject *key, *y;
void *pkey;
key = PyBytes_FromStringAndSize(NULL, keylength * sizeof(void *));
if (key == NULL)
goto error;
pkey = PyBytes_AS_STRING(key);
memcpy(pkey, unique_key, keylength * sizeof(void *));
y = PyDict_GetItem(unique_cache, key);
if (y != NULL) {
Py_DECREF(key);
Py_INCREF(y);
Py_DECREF(x);
return y;
}
if (PyDict_SetItem(unique_cache, key, (PyObject *)x) < 0) {
Py_DECREF(key);
goto error;
}
/* Haaaack for our reference count hack: gcmodule.c must not see this
dictionary. The problem is that any PyDict_SetItem() notices that
'x' is tracked and re-tracks the unique_cache dictionary. So here
we re-untrack it again... */
PyObject_GC_UnTrack(unique_cache);
assert(x->ct_unique_key == NULL);
x->ct_unique_key = key; /* the key will be freed in ctypedescr_dealloc() */
/* the 'value' in unique_cache doesn't count as 1, but don't use
Py_DECREF(x) here because it will confuse debug builds into thinking
there was an extra DECREF in total. */
((PyObject *)x)->ob_refcnt--;
return (PyObject *)x;
error:
Py_DECREF(x);
return NULL;
}
/* according to the C standard, these types should be equivalent to the
_Complex types for the purposes of storage (not arguments in calls!) */
typedef float cffi_float_complex_t[2];
typedef double cffi_double_complex_t[2];
static PyObject *new_primitive_type(const char *name)
{
#define ENUM_PRIMITIVE_TYPES \
EPTYPE(c, char, CT_PRIMITIVE_CHAR) \
EPTYPE(s, short, CT_PRIMITIVE_SIGNED ) \
EPTYPE(i, int, CT_PRIMITIVE_SIGNED ) \
EPTYPE(l, long, CT_PRIMITIVE_SIGNED ) \
EPTYPE(ll, long long, CT_PRIMITIVE_SIGNED ) \
EPTYPE(sc, signed char, CT_PRIMITIVE_SIGNED ) \
EPTYPE(uc, unsigned char, CT_PRIMITIVE_UNSIGNED ) \
EPTYPE(us, unsigned short, CT_PRIMITIVE_UNSIGNED ) \
EPTYPE(ui, unsigned int, CT_PRIMITIVE_UNSIGNED ) \
EPTYPE(ul, unsigned long, CT_PRIMITIVE_UNSIGNED ) \
EPTYPE(ull, unsigned long long, CT_PRIMITIVE_UNSIGNED ) \
EPTYPE(f, float, CT_PRIMITIVE_FLOAT ) \
EPTYPE(d, double, CT_PRIMITIVE_FLOAT ) \
EPTYPE(ld, long double, CT_PRIMITIVE_FLOAT | CT_IS_LONGDOUBLE ) \
EPTYPE2(fc, "float _Complex", cffi_float_complex_t, CT_PRIMITIVE_COMPLEX ) \
EPTYPE2(dc, "double _Complex", cffi_double_complex_t, CT_PRIMITIVE_COMPLEX ) \
ENUM_PRIMITIVE_TYPES_WCHAR \
EPTYPE2(c16, "char16_t", cffi_char16_t, CT_PRIMITIVE_CHAR ) \
EPTYPE2(c32, "char32_t", cffi_char32_t, CT_PRIMITIVE_CHAR ) \
EPTYPE(b, _Bool, CT_PRIMITIVE_UNSIGNED | CT_IS_BOOL ) \
/* the following types are not primitive in the C sense */ \
EPTYPE(i8, int8_t, CT_PRIMITIVE_SIGNED) \
EPTYPE(u8, uint8_t, CT_PRIMITIVE_UNSIGNED) \
EPTYPE(i16, int16_t, CT_PRIMITIVE_SIGNED) \
EPTYPE(u16, uint16_t, CT_PRIMITIVE_UNSIGNED) \
EPTYPE(i32, int32_t, CT_PRIMITIVE_SIGNED) \
EPTYPE(u32, uint32_t, CT_PRIMITIVE_UNSIGNED) \
EPTYPE(i64, int64_t, CT_PRIMITIVE_SIGNED) \
EPTYPE(u64, uint64_t, CT_PRIMITIVE_UNSIGNED) \
EPTYPE(il8, int_least8_t, CT_PRIMITIVE_SIGNED) \
EPTYPE(ul8, uint_least8_t, CT_PRIMITIVE_UNSIGNED) \
EPTYPE(il16, int_least16_t, CT_PRIMITIVE_SIGNED) \
EPTYPE(ul16, uint_least16_t, CT_PRIMITIVE_UNSIGNED) \
EPTYPE(il32, int_least32_t, CT_PRIMITIVE_SIGNED) \
EPTYPE(ul32, uint_least32_t, CT_PRIMITIVE_UNSIGNED) \
EPTYPE(il64, int_least64_t, CT_PRIMITIVE_SIGNED) \
EPTYPE(ul64, uint_least64_t, CT_PRIMITIVE_UNSIGNED) \
EPTYPE(if8, int_fast8_t, CT_PRIMITIVE_SIGNED) \
EPTYPE(uf8, uint_fast8_t, CT_PRIMITIVE_UNSIGNED) \
EPTYPE(if16, int_fast16_t, CT_PRIMITIVE_SIGNED) \
EPTYPE(uf16, uint_fast16_t, CT_PRIMITIVE_UNSIGNED) \
EPTYPE(if32, int_fast32_t, CT_PRIMITIVE_SIGNED) \
EPTYPE(uf32, uint_fast32_t, CT_PRIMITIVE_UNSIGNED) \
EPTYPE(if64, int_fast64_t, CT_PRIMITIVE_SIGNED) \
EPTYPE(uf64, uint_fast64_t, CT_PRIMITIVE_UNSIGNED) \
EPTYPE(ip, intptr_t, CT_PRIMITIVE_SIGNED) \
EPTYPE(up, uintptr_t, CT_PRIMITIVE_UNSIGNED) \
EPTYPE(im, intmax_t, CT_PRIMITIVE_SIGNED) \
EPTYPE(um, uintmax_t, CT_PRIMITIVE_UNSIGNED) \
EPTYPE(pd, ptrdiff_t, CT_PRIMITIVE_SIGNED) \
EPTYPE(sz, size_t, CT_PRIMITIVE_UNSIGNED) \
EPTYPE2(ssz, "ssize_t", Py_ssize_t, CT_PRIMITIVE_SIGNED)
#ifdef HAVE_WCHAR_H
# define ENUM_PRIMITIVE_TYPES_WCHAR \
EPTYPE(wc, wchar_t, CT_PRIMITIVE_CHAR | \
(((wchar_t)-1) > 0 ? 0 : CT_IS_SIGNED_WCHAR))
#else
# define ENUM_PRIMITIVE_TYPES_WCHAR /* nothing */
#endif
#define EPTYPE(code, typename, flags) EPTYPE2(code, #typename, typename, flags)
#define EPTYPE2(code, export_name, typename, flags) \
struct aligncheck_##code { char x; typename y; };
ENUM_PRIMITIVE_TYPES
#undef EPTYPE2
CTypeDescrObject *td;
static const struct descr_s { const char *name; int size, align, flags; }
types[] = {
#define EPTYPE2(code, export_name, typename, flags) \
{ export_name, \
sizeof(typename), \
offsetof(struct aligncheck_##code, y), \
flags \
},
ENUM_PRIMITIVE_TYPES
#undef EPTYPE2
#undef EPTYPE
#undef ENUM_PRIMITIVE_TYPES_WCHAR
#undef ENUM_PRIMITIVE_TYPES
{ NULL }
};
const struct descr_s *ptypes;
const void *unique_key[1];
int name_size;
ffi_type *ffitype;
for (ptypes=types; ; ptypes++) {
if (ptypes->name == NULL) {
#ifndef HAVE_WCHAR_H
if (strcmp(name, "wchar_t"))
PyErr_SetString(PyExc_NotImplementedError, name);
else
#endif
PyErr_SetString(PyExc_KeyError, name);
return NULL;
}
if (strcmp(name, ptypes->name) == 0)
break;
}
if (ptypes->flags & CT_PRIMITIVE_SIGNED) {
switch (ptypes->size) {
case 1: ffitype = &ffi_type_sint8; break;
case 2: ffitype = &ffi_type_sint16; break;
case 4: ffitype = &ffi_type_sint32; break;
case 8: ffitype = &ffi_type_sint64; break;
default: goto bad_ffi_type;
}
}
else if (ptypes->flags & CT_PRIMITIVE_FLOAT) {
if (strcmp(ptypes->name, "float") == 0)
ffitype = &ffi_type_float;
else if (strcmp(ptypes->name, "double") == 0)
ffitype = &ffi_type_double;
else if (strcmp(ptypes->name, "long double") == 0) {
/* assume that if sizeof(double) == sizeof(long double), then
the two types are equivalent for C. libffi bugs on Win64
if a function's return type is ffi_type_longdouble... */
if (sizeof(double) == sizeof(long double))
ffitype = &ffi_type_double;
else
ffitype = &ffi_type_longdouble;
}
else
goto bad_ffi_type;
}
else if (ptypes->flags & CT_PRIMITIVE_COMPLEX) {
/* As of March 2017, still no libffi support for complex.
It fails silently if we try to use ffi_type_complex_float
or ffi_type_complex_double. Better not use it at all.
*/
ffitype = NULL;
}
else {
switch (ptypes->size) {
case 1: ffitype = &ffi_type_uint8; break;
case 2: ffitype = &ffi_type_uint16; break;
case 4: ffitype = &ffi_type_uint32; break;
case 8: ffitype = &ffi_type_uint64; break;
default: goto bad_ffi_type;
}
}
name_size = strlen(ptypes->name) + 1;
td = ctypedescr_new(name_size);
if (td == NULL)
return NULL;
memcpy(td->ct_name, name, name_size);
td->ct_size = ptypes->size;
td->ct_length = ptypes->align;
td->ct_extra = ffitype;
td->ct_flags = ptypes->flags;
if (td->ct_flags & (CT_PRIMITIVE_SIGNED | CT_PRIMITIVE_CHAR)) {
if (td->ct_size <= (Py_ssize_t)sizeof(long))
td->ct_flags |= CT_PRIMITIVE_FITS_LONG;
}
else if (td->ct_flags & CT_PRIMITIVE_UNSIGNED) {
if (td->ct_size < (Py_ssize_t)sizeof(long))
td->ct_flags |= CT_PRIMITIVE_FITS_LONG;
}
td->ct_name_position = strlen(td->ct_name);
unique_key[0] = ptypes;
return get_unique_type(td, unique_key, 1);
bad_ffi_type:
PyErr_Format(PyExc_NotImplementedError,
"primitive type '%s' has size %d; "
"the supported sizes are 1, 2, 4, 8",
name, (int)ptypes->size);
return NULL;
}
static PyObject *b_new_primitive_type(PyObject *self, PyObject *args)
{
char *name;
if (!PyArg_ParseTuple(args, "s:new_primitive_type", &name))
return NULL;
return new_primitive_type(name);
}
static PyObject *new_pointer_type(CTypeDescrObject *ctitem)
{
CTypeDescrObject *td;
const char *extra;
const void *unique_key[1];
if (ctitem->ct_flags & CT_ARRAY)
extra = "(*)"; /* obscure case: see test_array_add */
else
extra = " *";
td = ctypedescr_new_on_top(ctitem, extra, 2);
if (td == NULL)
return NULL;
td->ct_size = sizeof(void *);
td->ct_length = -1;
td->ct_flags = CT_POINTER;
if (ctitem->ct_flags & (CT_STRUCT|CT_UNION))
td->ct_flags |= CT_IS_PTR_TO_OWNED;
if (ctitem->ct_flags & CT_VOID)
td->ct_flags |= CT_IS_VOID_PTR;
if ((ctitem->ct_flags & CT_VOID) ||
((ctitem->ct_flags & CT_PRIMITIVE_CHAR) &&
ctitem->ct_size == sizeof(char)))
td->ct_flags |= CT_IS_VOIDCHAR_PTR; /* 'void *' or 'char *' only */
unique_key[0] = ctitem;
return get_unique_type(td, unique_key, 1);
}
static PyObject *b_new_pointer_type(PyObject *self, PyObject *args)
{
CTypeDescrObject *ctitem;
if (!PyArg_ParseTuple(args, "O!:new_pointer_type",
&CTypeDescr_Type, &ctitem))
return NULL;
return new_pointer_type(ctitem);
}
static PyObject *b_new_array_type(PyObject *self, PyObject *args)
{
PyObject *lengthobj;
Py_ssize_t length;
CTypeDescrObject *ctptr;
if (!PyArg_ParseTuple(args, "O!O:new_array_type",
&CTypeDescr_Type, &ctptr, &lengthobj))
return NULL;
if (lengthobj == Py_None) {
length = -1;
}
else {
length = PyNumber_AsSsize_t(lengthobj, PyExc_OverflowError);
if (length < 0) {
if (!PyErr_Occurred())
PyErr_SetString(PyExc_ValueError, "negative array length");
return NULL;
}
}
return new_array_type(ctptr, length);
}
static PyObject *
new_array_type(CTypeDescrObject *ctptr, Py_ssize_t length)
{
CTypeDescrObject *td, *ctitem;
char extra_text[32];
Py_ssize_t arraysize;
int flags = CT_ARRAY;
const void *unique_key[2];
if (!(ctptr->ct_flags & CT_POINTER)) {
PyErr_SetString(PyExc_TypeError, "first arg must be a pointer ctype");
return NULL;
}
ctitem = ctptr->ct_itemdescr;
if (ctitem->ct_size < 0) {
PyErr_Format(PyExc_ValueError, "array item of unknown size: '%s'",
ctitem->ct_name);
return NULL;
}
if (length < 0) {
sprintf(extra_text, "[]");
length = -1;
arraysize = -1;
}
else {
sprintf(extra_text, "[%llu]", (unsigned PY_LONG_LONG)length);
arraysize = MUL_WRAPAROUND(length, ctitem->ct_size);
if (length > 0 && (arraysize / length) != ctitem->ct_size) {
PyErr_SetString(PyExc_OverflowError,
"array size would overflow a Py_ssize_t");
return NULL;
}
}
td = ctypedescr_new_on_top(ctitem, extra_text, 0);
if (td == NULL)
return NULL;
Py_INCREF(ctptr);
td->ct_stuff = (PyObject *)ctptr;
td->ct_size = arraysize;
td->ct_length = length;
td->ct_flags = flags;
unique_key[0] = ctptr;
unique_key[1] = (void *)length;
return get_unique_type(td, unique_key, 2);
}
static PyObject *new_void_type(void)
{
int name_size = strlen("void") + 1;
const void *unique_key[1];
CTypeDescrObject *td = ctypedescr_new(name_size);
if (td == NULL)
return NULL;
memcpy(td->ct_name, "void", name_size);
td->ct_size = -1;
td->ct_flags = CT_VOID | CT_IS_OPAQUE;
td->ct_name_position = strlen("void");
unique_key[0] = "void";
return get_unique_type(td, unique_key, 1);
}
static PyObject *b_new_void_type(PyObject *self, PyObject *args)
{
return new_void_type();
}
static PyObject *new_struct_or_union_type(const char *name, int flag)
{
int namelen = strlen(name);
CTypeDescrObject *td = ctypedescr_new(namelen + 1);
if (td == NULL)
return NULL;
td->ct_size = -1;
td->ct_length = -1;
td->ct_flags = flag | CT_IS_OPAQUE;
td->ct_extra = NULL;
memcpy(td->ct_name, name, namelen + 1);
td->ct_name_position = namelen;
return (PyObject *)td;
}
static PyObject *b_new_struct_type(PyObject *self, PyObject *args)
{
char *name;
int flag;
if (!PyArg_ParseTuple(args, "s:new_struct_type", &name))
return NULL;
flag = CT_STRUCT;
if (strcmp(name, "struct _IO_FILE") == 0 || strcmp(name, "FILE") == 0)
flag |= CT_IS_FILE;
return new_struct_or_union_type(name, flag);
}
static PyObject *b_new_union_type(PyObject *self, PyObject *args)
{
char *name;
if (!PyArg_ParseTuple(args, "s:new_union_type", &name))
return NULL;
return new_struct_or_union_type(name, CT_UNION);
}
static CFieldObject *
_add_field(PyObject *interned_fields, PyObject *fname, CTypeDescrObject *ftype,
Py_ssize_t offset, int bitshift, int fbitsize, int flags)
{
int err;
Py_ssize_t prev_size;
CFieldObject *cf = PyObject_New(CFieldObject, &CField_Type);
if (cf == NULL)
return NULL;
Py_INCREF(ftype);
cf->cf_type = ftype;
cf->cf_offset = offset;
cf->cf_bitshift = bitshift;
cf->cf_bitsize = fbitsize;
cf->cf_flags = flags;
Py_INCREF(fname);
PyText_InternInPlace(&fname);
prev_size = PyDict_Size(interned_fields);
err = PyDict_SetItem(interned_fields, fname, (PyObject *)cf);
Py_DECREF(fname);
Py_DECREF(cf);
if (err < 0)
return NULL;
if (PyDict_Size(interned_fields) != prev_size + 1) {
PyErr_Format(PyExc_KeyError, "duplicate field name '%s'",
PyText_AS_UTF8(fname));
return NULL;
}
return cf; /* borrowed reference */
}
#define SF_MSVC_BITFIELDS 0x01
#define SF_GCC_ARM_BITFIELDS 0x02
#define SF_GCC_X86_BITFIELDS 0x10
#define SF_GCC_BIG_ENDIAN 0x04
#define SF_GCC_LITTLE_ENDIAN 0x40
#define SF_PACKED 0x08
#define SF_STD_FIELD_POS 0x80
#ifdef MS_WIN32
# define SF_DEFAULT_PACKING 8
#else
# define SF_DEFAULT_PACKING 0x40000000 /* a huge power of two */
#endif
static int complete_sflags(int sflags)
{
/* add one of the SF_xxx_BITFIELDS flags if none is specified */
if (!(sflags & (SF_MSVC_BITFIELDS | SF_GCC_ARM_BITFIELDS |
SF_GCC_X86_BITFIELDS))) {
#ifdef MS_WIN32
sflags |= SF_MSVC_BITFIELDS;
#else
# if defined(__APPLE__) && defined(__arm64__)
sflags |= SF_GCC_X86_BITFIELDS;
# elif defined(__arm__) || defined(__aarch64__)
sflags |= SF_GCC_ARM_BITFIELDS;
# else
sflags |= SF_GCC_X86_BITFIELDS;
# endif
#endif
}
/* add one of SF_GCC_xx_ENDIAN if none is specified */
if (!(sflags & (SF_GCC_BIG_ENDIAN | SF_GCC_LITTLE_ENDIAN))) {
int _check_endian = 1;
if (*(char *)&_check_endian == 0)
sflags |= SF_GCC_BIG_ENDIAN;
else
sflags |= SF_GCC_LITTLE_ENDIAN;
}
return sflags;
}
static int detect_custom_layout(CTypeDescrObject *ct, int sflags,
Py_ssize_t cdef_value,
Py_ssize_t compiler_value,
const char *msg1, const char *txt,
const char *msg2)
{
if (compiler_value != cdef_value) {
if (sflags & SF_STD_FIELD_POS) {
PyErr_Format(FFIError,
"%s: %s%s%s (cdef says %zd, but C compiler says %zd)."
" fix it or use \"...;\" as the last field in the "
"cdef for %s to make it flexible",
ct->ct_name, msg1, txt, msg2,
cdef_value, compiler_value,
ct->ct_name);
return -1;
}
ct->ct_flags |= CT_CUSTOM_FIELD_POS;
}
return 0;
}
#define ROUNDUP_BYTES(bytes, bits) ((bytes) + ((bits) > 0))
static PyObject *b_complete_struct_or_union(PyObject *self, PyObject *args)
{
CTypeDescrObject *ct;
PyObject *fields, *interned_fields, *ignored;
int is_union, alignment;
Py_ssize_t byteoffset, i, nb_fields, byteoffsetmax, alignedsize;
int bitoffset;
Py_ssize_t byteoffsetorg;
Py_ssize_t totalsize = -1;
int totalalignment = -1;
CFieldObject **previous;
int prev_bitfield_size, prev_bitfield_free;
int sflags = 0, fflags;
int pack = 0;
if (!PyArg_ParseTuple(args, "O!O!|Oniii:complete_struct_or_union",
&CTypeDescr_Type, &ct,
&PyList_Type, &fields,
&ignored, &totalsize, &totalalignment, &sflags,
&pack))
return NULL;
sflags = complete_sflags(sflags);
if (sflags & SF_PACKED)
pack = 1;
else if (pack <= 0)
pack = SF_DEFAULT_PACKING;
else
sflags |= SF_PACKED;
if ((ct->ct_flags & (CT_STRUCT|CT_IS_OPAQUE)) ==
(CT_STRUCT|CT_IS_OPAQUE)) {
is_union = 0;
}
else if ((ct->ct_flags & (CT_UNION|CT_IS_OPAQUE)) ==
(CT_UNION|CT_IS_OPAQUE)) {
is_union = 1;
}
else {
PyErr_SetString(PyExc_TypeError,
"first arg must be a non-initialized struct or union ctype");
return NULL;
}
ct->ct_flags &= ~(CT_CUSTOM_FIELD_POS | CT_WITH_PACKED_CHANGE);
alignment = 1;
byteoffset = 0; /* the real value is 'byteoffset+bitoffset*8', which */
bitoffset = 0; /* counts the offset in bits */
byteoffsetmax = 0; /* the maximum value of byteoffset-rounded-up-to-byte */
prev_bitfield_size = 0;
prev_bitfield_free = 0;
nb_fields = PyList_GET_SIZE(fields);
interned_fields = PyDict_New();
if (interned_fields == NULL)
return NULL;
previous = (CFieldObject **)&ct->ct_extra;
for (i=0; i<nb_fields; i++) {
PyObject *fname;
CTypeDescrObject *ftype;
int fbitsize = -1, falign, falignorg, do_align;
Py_ssize_t foffset = -1;
if (!PyArg_ParseTuple(PyList_GET_ITEM(fields, i), "O!O!|in:list item",
&PyText_Type, &fname,
&CTypeDescr_Type, &ftype,
&fbitsize, &foffset))
goto error;
if (ftype->ct_size < 0) {
if ((ftype->ct_flags & CT_ARRAY) && fbitsize < 0
&& (i == nb_fields - 1 || foffset != -1)) {
ct->ct_flags |= CT_WITH_VAR_ARRAY;
}
else {
PyErr_Format(PyExc_TypeError,
"field '%s.%s' has ctype '%s' of unknown size",
ct->ct_name, PyText_AS_UTF8(fname),
ftype->ct_name);
goto error;
}
}
else if (ftype->ct_flags & (CT_STRUCT|CT_UNION)) {
if (force_lazy_struct(ftype) < 0) /* for CT_WITH_VAR_ARRAY */
return NULL;
/* GCC (or maybe C99) accepts var-sized struct fields that are not
the last field of a larger struct. That's why there is no
check here for "last field": we propagate the flag
CT_WITH_VAR_ARRAY to any struct that contains either an open-
ended array or another struct that recursively contains an
open-ended array. */
if (ftype->ct_flags & CT_WITH_VAR_ARRAY)
ct->ct_flags |= CT_WITH_VAR_ARRAY;
}
if (is_union)
byteoffset = bitoffset = 0; /* reset each field at offset 0 */
/* update the total alignment requirement, but skip it if the
field is an anonymous bitfield or if SF_PACKED */
falignorg = get_alignment(ftype);
if (falignorg < 0)
goto error;
falign = (pack < falignorg) ? pack : falignorg;
do_align = 1;
if (!(sflags & SF_GCC_ARM_BITFIELDS) && fbitsize >= 0) {
if (!(sflags & SF_MSVC_BITFIELDS)) {
/* GCC: anonymous bitfields (of any size) don't cause alignment */
do_align = PyText_GetSize(fname) > 0;
}
else {
/* MSVC: zero-sized bitfields don't cause alignment */
do_align = fbitsize > 0;
}
}
if (alignment < falign && do_align)
alignment = falign;
fflags = (is_union && i > 0) ? BF_IGNORE_IN_CTOR : 0;
if (fbitsize < 0) {
/* not a bitfield: common case */
int bs_flag;
if ((ftype->ct_flags & CT_ARRAY) && ftype->ct_length <= 0)
bs_flag = BS_EMPTY_ARRAY;
else
bs_flag = BS_REGULAR;
/* align this field to its own 'falign' by inserting padding */
/* first, pad to the next byte,
* then pad to 'falign' or 'falignorg' bytes */
byteoffset = ROUNDUP_BYTES(byteoffset, bitoffset);
bitoffset = 0;
byteoffsetorg = (byteoffset + falignorg-1) & ~(falignorg-1);
byteoffset = (byteoffset + falign-1) & ~(falign-1);
if (byteoffsetorg != byteoffset) {
ct->ct_flags |= CT_WITH_PACKED_CHANGE;
}
if (foffset >= 0) {
/* a forced field position: ignore the offset just computed,
except to know if we must set CT_CUSTOM_FIELD_POS */
if (detect_custom_layout(ct, sflags, byteoffset, foffset,
"wrong offset for field '",
PyText_AS_UTF8(fname), "'") < 0)
goto error;
byteoffset = foffset;
}
if (PyText_GetSize(fname) == 0 &&
ftype->ct_flags & (CT_STRUCT|CT_UNION)) {
/* a nested anonymous struct or union */
CFieldObject *cfsrc = (CFieldObject *)ftype->ct_extra;
for (; cfsrc != NULL; cfsrc = cfsrc->cf_next) {
/* broken complexity in the call to get_field_name(),
but we'll assume you never do that with nested
anonymous structures with thousand of fields */
*previous = _add_field(interned_fields,
get_field_name(ftype, cfsrc),
cfsrc->cf_type,
byteoffset + cfsrc->cf_offset,
cfsrc->cf_bitshift,
cfsrc->cf_bitsize,
cfsrc->cf_flags | fflags);
if (*previous == NULL)
goto error;
previous = &(*previous)->cf_next;
}
/* always forbid such structures from being passed by value */
ct->ct_flags |= CT_CUSTOM_FIELD_POS;
}
else {
*previous = _add_field(interned_fields, fname, ftype,
byteoffset, bs_flag, -1, fflags);
if (*previous == NULL)
goto error;
previous = &(*previous)->cf_next;
}
if (ftype->ct_size >= 0)
byteoffset += ftype->ct_size;
prev_bitfield_size = 0;
}
else {
/* this is the case of a bitfield */
Py_ssize_t field_offset_bytes;
int bits_already_occupied, bitshift;
if (foffset >= 0) {
PyErr_Format(PyExc_TypeError,
"field '%s.%s' is a bitfield, "
"but a fixed offset is specified",
ct->ct_name, PyText_AS_UTF8(fname));
goto error;
}
if (!(ftype->ct_flags & (CT_PRIMITIVE_SIGNED |
CT_PRIMITIVE_UNSIGNED |
CT_PRIMITIVE_CHAR))) {
PyErr_Format(PyExc_TypeError,
"field '%s.%s' declared as '%s' cannot be a bit field",
ct->ct_name, PyText_AS_UTF8(fname),
ftype->ct_name);
goto error;
}
if (fbitsize > 8 * ftype->ct_size) {
PyErr_Format(PyExc_TypeError,
"bit field '%s.%s' is declared '%s:%d', which "
"exceeds the width of the type",
ct->ct_name, PyText_AS_UTF8(fname),
ftype->ct_name, fbitsize);
goto error;
}
/* compute the starting position of the theoretical field
that covers a complete 'ftype', inside of which we will
locate the real bitfield */
field_offset_bytes = byteoffset;
field_offset_bytes &= ~(falign - 1);
if (fbitsize == 0) {
if (PyText_GetSize(fname) > 0) {
PyErr_Format(PyExc_TypeError,
"field '%s.%s' is declared with :0",
ct->ct_name, PyText_AS_UTF8(fname));
goto error;
}
if (!(sflags & SF_MSVC_BITFIELDS)) {
/* GCC's notion of "ftype :0;" */
/* pad byteoffset to a value aligned for "ftype" */
if (ROUNDUP_BYTES(byteoffset, bitoffset) > field_offset_bytes) {
field_offset_bytes += falign;
assert(byteoffset < field_offset_bytes);
}
byteoffset = field_offset_bytes;
bitoffset = 0;
}
else {
/* MSVC's notion of "ftype :0;" */
/* Mostly ignored. It seems they only serve as
separator between other bitfields, to force them
into separate words. */
}
prev_bitfield_size = 0;
}
else {
if (!(sflags & SF_MSVC_BITFIELDS)) {
/* GCC's algorithm */
/* Can the field start at the offset given by 'boffset'? It
can if it would entirely fit into an aligned ftype field. */
bits_already_occupied = (byteoffset-field_offset_bytes) * 8
+ bitoffset;
if (bits_already_occupied + fbitsize > 8 * ftype->ct_size) {
/* it would not fit, we need to start at the next
allowed position */
if ((sflags & SF_PACKED) &&
(bits_already_occupied & 7)) {
PyErr_Format(PyExc_NotImplementedError,
"with 'packed', gcc would compile field "
"'%s.%s' to reuse some bits in the previous "
"field", ct->ct_name, PyText_AS_UTF8(fname));
goto error;
}
field_offset_bytes += falign;
assert(byteoffset < field_offset_bytes);
byteoffset = field_offset_bytes;
bitoffset = 0;
bitshift = 0;
}
else {
bitshift = bits_already_occupied;
assert(bitshift >= 0);
}
bitoffset += fbitsize;
byteoffset += (bitoffset >> 3);
bitoffset &= 7;
}
else {
/* MSVC's algorithm */
/* A bitfield is considered as taking the full width
of their declared type. It can share some bits
with the previous field only if it was also a
bitfield and used a type of the same size. */
if (prev_bitfield_size == ftype->ct_size &&
prev_bitfield_free >= fbitsize) {
/* yes: reuse */
bitshift = 8 * prev_bitfield_size - prev_bitfield_free;
}
else {
/* no: start a new full field */
byteoffset = ROUNDUP_BYTES(byteoffset, bitoffset);
bitoffset = 0;
/* align */
byteoffset = (byteoffset + falign-1) & ~(falign-1);
byteoffset += ftype->ct_size;
bitshift = 0;
prev_bitfield_size = ftype->ct_size;
prev_bitfield_free = 8 * prev_bitfield_size;
}
prev_bitfield_free -= fbitsize;
field_offset_bytes = byteoffset - ftype->ct_size;
}
if (sflags & SF_GCC_BIG_ENDIAN)
bitshift = 8 * ftype->ct_size - fbitsize - bitshift;
if (PyText_GetSize(fname) > 0) {
*previous = _add_field(interned_fields, fname, ftype,
field_offset_bytes, bitshift, fbitsize,
fflags);
if (*previous == NULL)
goto error;
previous = &(*previous)->cf_next;
}
}
}
assert(bitoffset == (bitoffset & 7));
if (ROUNDUP_BYTES(byteoffset, bitoffset) > byteoffsetmax)
byteoffsetmax = ROUNDUP_BYTES(byteoffset, bitoffset);
}
*previous = NULL;
/* Like C, if the size of this structure would be zero, we compute it
as 1 instead. But for ctypes support, we allow the manually-
specified totalsize to be zero in this case. */
alignedsize = (byteoffsetmax + alignment - 1) & ~(alignment-1);
if (alignedsize == 0)
alignedsize = 1;
if (totalsize < 0) {
totalsize = alignedsize;
}
else {
if (detect_custom_layout(ct, sflags, alignedsize,
totalsize, "wrong total size", "", "") < 0)
goto error;
if (totalsize < byteoffsetmax) {
PyErr_Format(PyExc_TypeError,
"%s cannot be of size %zd: there are fields at least "
"up to %zd", ct->ct_name, totalsize, byteoffsetmax);
goto error;
}
}
if (totalalignment < 0) {
totalalignment = alignment;
}
else {
if (detect_custom_layout(ct, sflags, alignment, totalalignment,
"wrong total alignment", "", "") < 0)
goto error;
}
ct->ct_size = totalsize;
ct->ct_length = totalalignment;
ct->ct_stuff = interned_fields;
ct->ct_flags &= ~CT_IS_OPAQUE;
Py_INCREF(Py_None);
return Py_None;
error:
ct->ct_extra = NULL;
Py_DECREF(interned_fields);
return NULL;
}
struct funcbuilder_s {
Py_ssize_t nb_bytes;
char *bufferp;
ffi_type **atypes;
ffi_type *rtype;
Py_ssize_t nargs;
CTypeDescrObject *fct;
};
static void *fb_alloc(struct funcbuilder_s *fb, Py_ssize_t size)
{
if (fb->bufferp == NULL) {
fb->nb_bytes += size;
return NULL;
}
else {
char *result = fb->bufferp;
fb->bufferp += size;
return result;
}
}
#define SUPPORTED_IN_API_MODE \
" are only supported as %s if the function is " \
"'API mode' and non-variadic (i.e. declared inside ffibuilder" \
".cdef()+ffibuilder.set_source() and not taking a final '...' " \
"argument)"
static ffi_type *fb_unsupported(CTypeDescrObject *ct, const char *place,
const char *detail)
{
PyErr_Format(PyExc_NotImplementedError,
"ctype '%s' not supported as %s. %s. "
"Such structs" SUPPORTED_IN_API_MODE,
ct->ct_name, place, detail, place);
return NULL;
}
static ffi_type *fb_fill_type(struct funcbuilder_s *fb, CTypeDescrObject *ct,
int is_result_type)
{
const char *place = is_result_type ? "return value" : "argument";
if (ct->ct_flags & (CT_PRIMITIVE_ANY & ~CT_PRIMITIVE_COMPLEX)) {
return (ffi_type *)ct->ct_extra;
}
else if (ct->ct_flags & (CT_POINTER|CT_FUNCTIONPTR)) {
return &ffi_type_pointer;
}
else if ((ct->ct_flags & CT_VOID) && is_result_type) {
return &ffi_type_void;
}
if (ct->ct_size <= 0) {
PyErr_Format(PyExc_TypeError,
ct->ct_size < 0 ? "ctype '%s' has incomplete type"
: "ctype '%s' has size 0",
ct->ct_name);
return NULL;
}
if (ct->ct_flags & CT_STRUCT) {
ffi_type *ffistruct, *ffifield;
ffi_type **elements;
Py_ssize_t i, n, nflat;
CFieldObject *cf;
/* We can't pass a struct that was completed by verify().
Issue: assume verify() is given "struct { long b; ...; }".
Then it will complete it in the same way whether it is actually
"struct { long a, b; }" or "struct { double a; long b; }".
But on 64-bit UNIX, these two structs are passed by value
differently: e.g. on x86-64, "b" ends up in register "rsi" in
the first case and "rdi" in the second case.
Another reason for CT_CUSTOM_FIELD_POS would be anonymous
nested structures: we lost the information about having it
here, so better safe (and forbid it) than sorry (and maybe
crash). Note: it seems we only get in this case with
ffi.verify().
*/
if (force_lazy_struct(ct) < 0)
return NULL;
if (ct->ct_flags & CT_CUSTOM_FIELD_POS) {
/* these NotImplementedErrors may be caught and ignored until
a real call is made to a function of this type */
return fb_unsupported(ct, place,
"It is a struct declared with \"...;\", but the C "
"calling convention may depend on the missing fields; "
"or, it contains anonymous struct/unions");
}
/* Another reason: __attribute__((packed)) is not supported by libffi.
*/
if (ct->ct_flags & CT_WITH_PACKED_CHANGE) {
return fb_unsupported(ct, place,
"It is a 'packed' structure, with a different layout than "
"expected by libffi");
}
n = PyDict_Size(ct->ct_stuff);
nflat = 0;
/* walk the fields, expanding arrays into repetitions; first,
only count how many flattened fields there are */
cf = (CFieldObject *)ct->ct_extra;
for (i=0; i<n; i++) {
Py_ssize_t flat;
CTypeDescrObject *ct1;
assert(cf != NULL);
if (cf->cf_bitshift >= 0) {
return fb_unsupported(ct, place,
"It is a struct with bit fields, which libffi does not "
"support");
}
flat = 1;
ct1 = cf->cf_type;
while (ct1->ct_flags & CT_ARRAY) {
flat *= ct1->ct_length;
ct1 = ct1->ct_itemdescr;
}
if (flat <= 0) {
return fb_unsupported(ct, place,
"It is a struct with a zero-length array, which libffi "
"does not support");
}
nflat += flat;
cf = cf->cf_next;
}
assert(cf == NULL);
/* next, allocate and fill the flattened list */
elements = fb_alloc(fb, (nflat + 1) * sizeof(ffi_type*));
nflat = 0;
cf = (CFieldObject *)ct->ct_extra;
for (i=0; i<n; i++) {
Py_ssize_t j, flat = 1;
CTypeDescrObject *ct = cf->cf_type;
while (ct->ct_flags & CT_ARRAY) {
flat *= ct->ct_length;
ct = ct->ct_itemdescr;
}
ffifield = fb_fill_type(fb, ct, 0);
if (PyErr_Occurred())
return NULL;
if (elements != NULL) {
for (j=0; j<flat; j++)
elements[nflat++] = ffifield;
}
cf = cf->cf_next;
}
/* finally, allocate the FFI_TYPE_STRUCT */
ffistruct = fb_alloc(fb, sizeof(ffi_type));
if (ffistruct != NULL) {
elements[nflat] = NULL;
ffistruct->size = ct->ct_size;
ffistruct->alignment = ct->ct_length;
ffistruct->type = FFI_TYPE_STRUCT;
ffistruct->elements = elements;
}
return ffistruct;
}
else if (ct->ct_flags & CT_UNION) {
PyErr_Format(PyExc_NotImplementedError,
"ctype '%s' not supported as %s by libffi. "
"Unions" SUPPORTED_IN_API_MODE,
ct->ct_name, place, place);
return NULL;
}
else {
char *extra = "";
if (ct->ct_flags & CT_PRIMITIVE_COMPLEX)
extra = " (the support for complex types inside libffi "
"is mostly missing at this point, so CFFI only "
"supports complex types as arguments or return "
"value in API-mode functions)";
PyErr_Format(PyExc_NotImplementedError,
"ctype '%s' (size %zd) not supported as %s%s",
ct->ct_name, ct->ct_size, place, extra);
return NULL;
}
}
#define ALIGN_ARG(n) ((n) + 7) & ~7
static int fb_build(struct funcbuilder_s *fb, PyObject *fargs,
CTypeDescrObject *fresult)
{
Py_ssize_t i, nargs = PyTuple_GET_SIZE(fargs);
Py_ssize_t exchange_offset;
cif_description_t *cif_descr;
/* ffi buffer: start with a cif_description */
cif_descr = fb_alloc(fb, sizeof(cif_description_t) +
nargs * sizeof(Py_ssize_t));
/* ffi buffer: next comes an array of 'ffi_type*', one per argument */
fb->atypes = fb_alloc(fb, nargs * sizeof(ffi_type*));
fb->nargs = nargs;
/* ffi buffer: next comes the result type */
fb->rtype = fb_fill_type(fb, fresult, 1);
if (PyErr_Occurred())
return -1;
if (cif_descr != NULL) {
/* exchange data size */
/* first, enough room for an array of 'nargs' pointers */
exchange_offset = nargs * sizeof(void*);
exchange_offset = ALIGN_ARG(exchange_offset);
cif_descr->exchange_offset_arg[0] = exchange_offset;
/* then enough room for the result --- which means at least
sizeof(ffi_arg), according to the ffi docs */
i = fb->rtype->size;
if (i < (Py_ssize_t)sizeof(ffi_arg))
i = sizeof(ffi_arg);
exchange_offset += i;
}
else
exchange_offset = 0; /* not used */
/* loop over the arguments */
for (i=0; i<nargs; i++) {
CTypeDescrObject *farg;
ffi_type *atype;
farg = (CTypeDescrObject *)PyTuple_GET_ITEM(fargs, i);
/* convert arrays to pointers */
if (farg->ct_flags & CT_ARRAY)
farg = (CTypeDescrObject *)farg->ct_stuff;
/* ffi buffer: fill in the ffi for the i'th argument */
assert(farg != NULL);
atype = fb_fill_type(fb, farg, 0);
if (PyErr_Occurred())
return -1;
if (fb->atypes != NULL) {
fb->atypes[i] = atype;
/* exchange data size */
exchange_offset = ALIGN_ARG(exchange_offset);
cif_descr->exchange_offset_arg[1 + i] = exchange_offset;
exchange_offset += atype->size;
}
}
if (cif_descr != NULL) {
/* exchange data size */
/* we also align it to the next multiple of 8, in an attempt to
work around bugs(?) of libffi like #241 */
cif_descr->exchange_size = ALIGN_ARG(exchange_offset);
}
return 0;
}
#undef ALIGN_ARG
static void fb_cat_name(struct funcbuilder_s *fb, const char *piece,
int piecelen)
{
if (fb->bufferp == NULL) {
fb->nb_bytes += piecelen;
}
else {
memcpy(fb->bufferp, piece, piecelen);
fb->bufferp += piecelen;
}
}
static int fb_build_name(struct funcbuilder_s *fb, const char *repl,
CTypeDescrObject **pfargs, Py_ssize_t nargs,
CTypeDescrObject *fresult, int ellipsis)
{
Py_ssize_t i;
fb->nargs = nargs;
/* name: the function type name we build here is, like in C, made
as follows:
RESULT_TYPE_HEAD (*)(ARG_1_TYPE, ARG_2_TYPE, etc) RESULT_TYPE_TAIL
*/
fb_cat_name(fb, fresult->ct_name, fresult->ct_name_position);
if (repl[0] != '(' &&
fresult->ct_name[fresult->ct_name_position - 1] != '*')
fb_cat_name(fb, " ", 1); /* add a space */
fb_cat_name(fb, repl, strlen(repl));
if (fb->fct) {
i = strlen(repl) - 1; /* between '(*' and ')' */
assert(repl[i] == ')');
fb->fct->ct_name_position = fresult->ct_name_position + i;
}
fb_cat_name(fb, "(", 1);
/* loop over the arguments */
for (i=0; i<nargs; i++) {
CTypeDescrObject *farg;
farg = pfargs[i];
if (!CTypeDescr_Check(farg)) {
PyErr_SetString(PyExc_TypeError, "expected a tuple of ctypes");
return -1;
}
/* name: concatenate the name of the i'th argument's type */
if (i > 0)
fb_cat_name(fb, ", ", 2);
fb_cat_name(fb, farg->ct_name, strlen(farg->ct_name));
}
/* name: add the '...' if needed */
if (ellipsis) {
if (nargs > 0)
fb_cat_name(fb, ", ", 2);
fb_cat_name(fb, "...", 3);
}
/* name: concatenate the tail of the result type */
fb_cat_name(fb, ")", 1);
fb_cat_name(fb, fresult->ct_name + fresult->ct_name_position,
strlen(fresult->ct_name) - fresult->ct_name_position + 1);
return 0;
}
static CTypeDescrObject *fb_prepare_ctype(struct funcbuilder_s *fb,
PyObject *fargs,
CTypeDescrObject *fresult,
int ellipsis, int fabi)
{
CTypeDescrObject *fct, **pfargs;
Py_ssize_t nargs;
char *repl = "(*)";
fb->nb_bytes = 0;
fb->bufferp = NULL;
fb->fct = NULL;
pfargs = (CTypeDescrObject **)&PyTuple_GET_ITEM(fargs, 0);
nargs = PyTuple_GET_SIZE(fargs);
#if defined(MS_WIN32) && !defined(_WIN64)
if (fabi == FFI_STDCALL)
repl = "(__stdcall *)";
#endif
/* compute the total size needed for the name */
if (fb_build_name(fb, repl, pfargs, nargs, fresult, ellipsis) < 0)
return NULL;
/* allocate the function type */
fct = ctypedescr_new(fb->nb_bytes);
if (fct == NULL)
return NULL;
fb->fct = fct;
/* call again fb_build_name() to really build the ct_name */
fb->bufferp = fct->ct_name;
if (fb_build_name(fb, repl, pfargs, nargs, fresult, ellipsis) < 0)
goto error;
assert(fb->bufferp == fct->ct_name + fb->nb_bytes);
fct->ct_extra = NULL;
fct->ct_size = sizeof(void(*)(void));
fct->ct_flags = CT_FUNCTIONPTR;
return fct;
error:
Py_DECREF(fct);
return NULL;
}
static cif_description_t *fb_prepare_cif(PyObject *fargs,
CTypeDescrObject *fresult,
Py_ssize_t variadic_nargs_declared,
ffi_abi fabi)
{
char *buffer;
cif_description_t *cif_descr;
struct funcbuilder_s funcbuffer;
ffi_status status = -1;
funcbuffer.nb_bytes = 0;
funcbuffer.bufferp = NULL;
/* compute the total size needed in the buffer for libffi */
if (fb_build(&funcbuffer, fargs, fresult) < 0)
return NULL;
/* allocate the buffer */
buffer = PyObject_Malloc(funcbuffer.nb_bytes);
if (buffer == NULL) {
PyErr_NoMemory();
return NULL;
}
/* call again fb_build() to really build the libffi data structures */
funcbuffer.bufferp = buffer;
if (fb_build(&funcbuffer, fargs, fresult) < 0)
goto error;
assert(funcbuffer.bufferp == buffer + funcbuffer.nb_bytes);
cif_descr = (cif_description_t *)buffer;
/* use `ffi_prep_cif_var` if necessary and available */
#if CFFI_CHECK_FFI_PREP_CIF_VAR_MAYBE
if (variadic_nargs_declared >= 0) {
if (CFFI_CHECK_FFI_PREP_CIF_VAR) {
status = ffi_prep_cif_var(&cif_descr->cif, fabi,
variadic_nargs_declared, funcbuffer.nargs,
funcbuffer.rtype, funcbuffer.atypes);
}
}
#endif
if (status == -1) {
status = ffi_prep_cif(&cif_descr->cif, fabi, funcbuffer.nargs,
funcbuffer.rtype, funcbuffer.atypes);
}
if (status != FFI_OK) {
PyErr_SetString(PyExc_SystemError,
"libffi failed to build this function type");
goto error;
}
return cif_descr;
error:
PyObject_Free(buffer);
return NULL;
}
static PyObject *new_function_type(PyObject *fargs, /* tuple */
CTypeDescrObject *fresult,
int ellipsis, int fabi)
{
PyObject *fabiobj;
CTypeDescrObject *fct;
struct funcbuilder_s funcbuilder;
Py_ssize_t i;
const void **unique_key;
if ((fresult->ct_size < 0 && !(fresult->ct_flags & CT_VOID)) ||
(fresult->ct_flags & CT_ARRAY)) {
char *msg;
if (fresult->ct_flags & CT_IS_OPAQUE)
msg = "result type '%s' is opaque";
else
msg = "invalid result type: '%s'";
PyErr_Format(PyExc_TypeError, msg, fresult->ct_name);
return NULL;
}
fct = fb_prepare_ctype(&funcbuilder, fargs, fresult, ellipsis, fabi);
if (fct == NULL)
return NULL;
if (!ellipsis) {
/* Functions with '...' varargs are stored without a cif_descr
at all. The cif is computed on every call from the actual
types passed in. For all other functions, the cif_descr
is computed here. */
cif_description_t *cif_descr;
cif_descr = fb_prepare_cif(fargs, fresult, -1, fabi);
if (cif_descr == NULL) {
if (PyErr_ExceptionMatches(PyExc_NotImplementedError)) {
PyErr_Clear(); /* will get the exception if we see an
actual call */
}
else
goto error;
}
fct->ct_extra = (char *)cif_descr;
}
/* build the signature, given by a tuple of ctype objects */
fct->ct_stuff = PyTuple_New(2 + funcbuilder.nargs);
if (fct->ct_stuff == NULL)
goto error;
fabiobj = PyInt_FromLong(fabi);
if (fabiobj == NULL)
goto error;
PyTuple_SET_ITEM(fct->ct_stuff, 0, fabiobj);
Py_INCREF(fresult);
PyTuple_SET_ITEM(fct->ct_stuff, 1, (PyObject *)fresult);
for (i=0; i<funcbuilder.nargs; i++) {
PyObject *o = PyTuple_GET_ITEM(fargs, i);
/* convert arrays into pointers */
if (((CTypeDescrObject *)o)->ct_flags & CT_ARRAY)
o = ((CTypeDescrObject *)o)->ct_stuff;
Py_INCREF(o);
PyTuple_SET_ITEM(fct->ct_stuff, 2 + i, o);
}
/* [ctresult, ellipsis+abi, num_args, ctargs...] */
unique_key = alloca((3 + funcbuilder.nargs) * sizeof(void *));
unique_key[0] = fresult;
unique_key[1] = (const void *)(Py_ssize_t)((fabi << 1) | !!ellipsis);
unique_key[2] = (const void *)(Py_ssize_t)(funcbuilder.nargs);
for (i=0; i<funcbuilder.nargs; i++)
unique_key[3 + i] = PyTuple_GET_ITEM(fct->ct_stuff, 2 + i);
return get_unique_type(fct, unique_key, 3 + funcbuilder.nargs);
error:
Py_DECREF(fct);
return NULL;
}
static PyObject *b_new_function_type(PyObject *self, PyObject *args)
{
PyObject *fargs;
CTypeDescrObject *fresult;
int ellipsis = 0, fabi = FFI_DEFAULT_ABI;
if (!PyArg_ParseTuple(args, "O!O!|ii:new_function_type",
&PyTuple_Type, &fargs,
&CTypeDescr_Type, &fresult,
&ellipsis,
&fabi))
return NULL;
return new_function_type(fargs, fresult, ellipsis, fabi);
}
static int convert_from_object_fficallback(char *result,
CTypeDescrObject *ctype,
PyObject *pyobj,
int encode_result_for_libffi)
{
/* work work work around a libffi irregularity: for integer return
types we have to fill at least a complete 'ffi_arg'-sized result
buffer. */
if (ctype->ct_size < (Py_ssize_t)sizeof(ffi_arg)) {
if (ctype->ct_flags & CT_VOID) {
if (pyobj == Py_None) {
return 0;
}
else {
PyErr_SetString(PyExc_TypeError,
"callback with the return type 'void' must return None");
return -1;
}
}
if (!encode_result_for_libffi)
goto skip;
if (ctype->ct_flags & CT_PRIMITIVE_SIGNED) {
PY_LONG_LONG value;
/* It's probably fine to always zero-extend, but you never
know: maybe some code somewhere expects a negative
'short' result to be returned into EAX as a 32-bit
negative number. Better safe than sorry. This code
is about that case. Let's ignore this for enums.
*/
/* do a first conversion only to detect overflows. This
conversion produces stuff that is otherwise ignored. */
if (convert_from_object(result, ctype, pyobj) < 0)
return -1;
/* manual inlining and tweaking of convert_from_object()
in order to write a whole 'ffi_arg'. */
value = _my_PyLong_AsLongLong(pyobj);
if (value == -1 && PyErr_Occurred())
return -1;
write_raw_integer_data(result, value, sizeof(ffi_arg));
return 0;
}
else if (ctype->ct_flags & (CT_PRIMITIVE_CHAR | CT_PRIMITIVE_SIGNED |
CT_PRIMITIVE_UNSIGNED |
CT_POINTER | CT_FUNCTIONPTR)) {
/* zero extension: fill the '*result' with zeros, and (on big-
endian machines) correct the 'result' pointer to write to.
We also do that for pointers, even though we're normally not
in this branch because ctype->ct_size == sizeof(ffi_arg) for
pointers---except on some architectures like x32 (issue #372).
*/
memset(result, 0, sizeof(ffi_arg));
#ifdef WORDS_BIGENDIAN
result += (sizeof(ffi_arg) - ctype->ct_size);
#endif
}
}
skip:
return convert_from_object(result, ctype, pyobj);
}
static void _my_PyErr_WriteUnraisable(PyObject *t, PyObject *v, PyObject *tb,
char *objdescr, PyObject *obj,
char *extra_error_line)
{
/* like PyErr_WriteUnraisable(), but write a full traceback */
PyObject *f;
#if PY_MAJOR_VERSION >= 3
/* jump through hoops to ensure the tb is attached to v, on Python 3 */
PyErr_NormalizeException(&t, &v, &tb);
if (tb == NULL) {
tb = Py_None;
Py_INCREF(tb);
}
PyException_SetTraceback(v, tb);
#endif
f = PySys_GetObject("stderr");
if (f != NULL) {
if (obj != NULL) {
PyFile_WriteString(objdescr, f);
PyFile_WriteObject(obj, f, 0);
PyFile_WriteString(":\n", f);
}
if (extra_error_line != NULL)
PyFile_WriteString(extra_error_line, f);
PyErr_Display(t, v, tb);
}
Py_XDECREF(t);
Py_XDECREF(v);
Py_XDECREF(tb);
}
static void general_invoke_callback(int decode_args_from_libffi,
void *result, char *args, void *userdata)
{
PyObject *cb_args = (PyObject *)userdata;
CTypeDescrObject *ct = (CTypeDescrObject *)PyTuple_GET_ITEM(cb_args, 0);
PyObject *signature = ct->ct_stuff;
PyObject *py_ob = PyTuple_GET_ITEM(cb_args, 1);
PyObject *py_args = NULL;
PyObject *py_res = NULL;
PyObject *py_rawerr;
PyObject *onerror_cb;
Py_ssize_t i, n;
char *extra_error_line = NULL;
#define SIGNATURE(i) ((CTypeDescrObject *)PyTuple_GET_ITEM(signature, i))
Py_INCREF(cb_args);
n = PyTuple_GET_SIZE(signature) - 2;
py_args = PyTuple_New(n);
if (py_args == NULL)
goto error;
for (i=0; i<n; i++) {
char *a_src;
PyObject *a;
CTypeDescrObject *a_ct = SIGNATURE(2 + i);
if (decode_args_from_libffi) {
a_src = ((void **)args)[i];
}
else {
a_src = args + i * 8;
if (a_ct->ct_flags & (CT_IS_LONGDOUBLE | CT_STRUCT | CT_UNION))
a_src = *(char **)a_src;
}
a = convert_to_object(a_src, a_ct);
if (a == NULL)
goto error;
PyTuple_SET_ITEM(py_args, i, a);
}
py_res = PyObject_Call(py_ob, py_args, NULL);
if (py_res == NULL)
goto error;
if (convert_from_object_fficallback(result, SIGNATURE(1), py_res,
decode_args_from_libffi) < 0) {
extra_error_line = "Trying to convert the result back to C:\n";
goto error;
}
done:
Py_XDECREF(py_args);
Py_XDECREF(py_res);
Py_DECREF(cb_args);
return;
error:
if (SIGNATURE(1)->ct_size > 0) {
py_rawerr = PyTuple_GET_ITEM(cb_args, 2);
memcpy(result, PyBytes_AS_STRING(py_rawerr),
PyBytes_GET_SIZE(py_rawerr));
}
onerror_cb = PyTuple_GET_ITEM(cb_args, 3);
if (onerror_cb == Py_None) {
PyObject *ecap, *t, *v, *tb;
PyErr_Fetch(&t, &v, &tb);
ecap = _cffi_start_error_capture();
_my_PyErr_WriteUnraisable(t, v, tb, "From cffi callback ", py_ob,
extra_error_line);
_cffi_stop_error_capture(ecap);
}
else {
PyObject *exc1, *val1, *tb1, *res1, *exc2, *val2, *tb2;
PyErr_Fetch(&exc1, &val1, &tb1);
PyErr_NormalizeException(&exc1, &val1, &tb1);
res1 = PyObject_CallFunctionObjArgs(onerror_cb,
exc1 ? exc1 : Py_None,
val1 ? val1 : Py_None,
tb1 ? tb1 : Py_None,
NULL);
if (res1 != NULL) {
if (res1 != Py_None)
convert_from_object_fficallback(result, SIGNATURE(1), res1,
decode_args_from_libffi);
Py_DECREF(res1);
}
if (!PyErr_Occurred()) {
Py_XDECREF(exc1);
Py_XDECREF(val1);
Py_XDECREF(tb1);
}
else {
/* double exception! print a double-traceback... */
PyObject *ecap;
PyErr_Fetch(&exc2, &val2, &tb2);
ecap = _cffi_start_error_capture();
_my_PyErr_WriteUnraisable(exc1, val1, tb1,
"From cffi callback ", py_ob,
extra_error_line);
extra_error_line = ("\nDuring the call to 'onerror', "
"another exception occurred:\n\n");
_my_PyErr_WriteUnraisable(exc2, val2, tb2,
NULL, NULL, extra_error_line);
_cffi_stop_error_capture(ecap);
}
}
goto done;
#undef SIGNATURE
}
static void invoke_callback(ffi_cif *cif, void *result, void **args,
void *userdata)
{
save_errno();
{
PyGILState_STATE state = gil_ensure();
general_invoke_callback(1, result, (char *)args, userdata);
gil_release(state);
}
restore_errno();
}
static PyObject *prepare_callback_info_tuple(CTypeDescrObject *ct,
PyObject *ob,
PyObject *error_ob,
PyObject *onerror_ob,
int decode_args_from_libffi)
{
CTypeDescrObject *ctresult;
PyObject *py_rawerr, *infotuple;
Py_ssize_t size;
if (!(ct->ct_flags & CT_FUNCTIONPTR)) {
PyErr_Format(PyExc_TypeError, "expected a function ctype, got '%s'",
ct->ct_name);
return NULL;
}
if (!PyCallable_Check(ob)) {
PyErr_Format(PyExc_TypeError,
"expected a callable object, not %.200s",
Py_TYPE(ob)->tp_name);
return NULL;
}
if (onerror_ob != Py_None && !PyCallable_Check(onerror_ob)) {
PyErr_Format(PyExc_TypeError,
"expected a callable object for 'onerror', not %.200s",
Py_TYPE(onerror_ob)->tp_name);
return NULL;
}
ctresult = (CTypeDescrObject *)PyTuple_GET_ITEM(ct->ct_stuff, 1);
size = ctresult->ct_size;
if (size < (Py_ssize_t)sizeof(ffi_arg))
size = sizeof(ffi_arg);
py_rawerr = PyBytes_FromStringAndSize(NULL, size);
if (py_rawerr == NULL)
return NULL;
memset(PyBytes_AS_STRING(py_rawerr), 0, size);
if (error_ob != Py_None) {
if (convert_from_object_fficallback(
PyBytes_AS_STRING(py_rawerr), ctresult, error_ob,
decode_args_from_libffi) < 0) {
Py_DECREF(py_rawerr);
return NULL;
}
}
infotuple = Py_BuildValue("OOOO", ct, ob, py_rawerr, onerror_ob);
Py_DECREF(py_rawerr);
#if defined(WITH_THREAD) && PY_VERSION_HEX < 0x03070000
/* We must setup the GIL here, in case the callback is invoked in
some other non-Pythonic thread. This is the same as ctypes.
But PyEval_InitThreads() is always a no-op from CPython 3.7
(the call from ctypes was removed some time later I think). */
PyEval_InitThreads();
#endif
return infotuple;
}
/* messily try to silence a gcc/clang deprecation warning for
ffi_prep_closure. Don't miss the "pragma pop" after the function.
This is done around the whole function because very old GCCs don't
support it inside a function. */
#if defined(__clang__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wdeprecated-declarations"
#elif defined(__GNUC__)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
static PyObject *b_callback(PyObject *self, PyObject *args)
{
CTypeDescrObject *ct;
CDataObject_closure *cd;
PyObject *ob, *error_ob = Py_None, *onerror_ob = Py_None;
PyObject *infotuple;
cif_description_t *cif_descr;
ffi_closure *closure;
ffi_status status;
void *closure_exec;
if (!PyArg_ParseTuple(args, "O!O|OO:callback", &CTypeDescr_Type, &ct, &ob,
&error_ob, &onerror_ob))
return NULL;
infotuple = prepare_callback_info_tuple(ct, ob, error_ob, onerror_ob, 1);
if (infotuple == NULL)
return NULL;
#if CFFI_CHECK_FFI_CLOSURE_ALLOC_MAYBE
if (CFFI_CHECK_FFI_CLOSURE_ALLOC) {
closure = ffi_closure_alloc(sizeof(ffi_closure), &closure_exec);
} else
#endif
{
closure = cffi_closure_alloc();
closure_exec = closure;
}
if (closure == NULL) {
Py_DECREF(infotuple);
PyErr_SetString(PyExc_MemoryError,
"Cannot allocate write+execute memory for ffi.callback(). "
"You might be running on a system that prevents this. "
"For more information, see "
"https://cffi.readthedocs.io/en/latest/using.html#callbacks");
return NULL;
}
cd = PyObject_GC_New(CDataObject_closure, &CDataOwningGC_Type);
if (cd == NULL)
goto error;
Py_INCREF(ct);
cd->head.c_type = ct;
cd->head.c_data = (char *)closure_exec;
cd->head.c_weakreflist = NULL;
closure->user_data = NULL;
cd->closure = closure;
cif_descr = (cif_description_t *)ct->ct_extra;
if (cif_descr == NULL) {
PyErr_Format(PyExc_NotImplementedError,
"%s: callback with unsupported argument or "
"return type or with '...'", ct->ct_name);
goto error;
}
#if CFFI_CHECK_FFI_PREP_CLOSURE_LOC_MAYBE
if (CFFI_CHECK_FFI_PREP_CLOSURE_LOC) {
status = ffi_prep_closure_loc(closure, &cif_descr->cif,
invoke_callback, infotuple, closure_exec);
}
else
#endif
{
#if defined(__APPLE__) && defined(FFI_AVAILABLE_APPLE) && !FFI_LEGACY_CLOSURE_API
PyErr_Format(PyExc_SystemError, "ffi_prep_closure_loc() is missing");
goto error;
#else
status = ffi_prep_closure(closure, &cif_descr->cif,
invoke_callback, infotuple);
#endif
}
if (status != FFI_OK) {
PyErr_SetString(PyExc_SystemError,
"libffi failed to build this callback");
goto error;
}
if (closure->user_data != infotuple) {
/* Issue #266. Should not occur, but could, if we are using
at runtime a version of libffi compiled with a different
'ffi_closure' structure than the one we expect from ffi.h
(e.g. difference in details of the platform): a difference
in FFI_TRAMPOLINE_SIZE means that the 'user_data' field
ends up somewhere else, and so the test above fails.
*/
PyErr_SetString(PyExc_SystemError,
"ffi_prep_closure(): bad user_data (it seems that the "
"version of the libffi library seen at runtime is "
"different from the 'ffi.h' file seen at compile-time)");
goto error;
}
PyObject_GC_Track(cd);
return (PyObject *)cd;
error:
closure->user_data = NULL;
if (cd == NULL) {
#if CFFI_CHECK_FFI_CLOSURE_ALLOC_MAYBE
if (CFFI_CHECK_FFI_CLOSURE_ALLOC) {
ffi_closure_free(closure);
}
else
#endif
cffi_closure_free(closure);
}
else
Py_DECREF(cd);
Py_XDECREF(infotuple);
return NULL;
}
#if defined(__clang__)
# pragma clang diagnostic pop
#elif defined(__GNUC__)
# pragma GCC diagnostic pop
#endif
static PyObject *b_new_enum_type(PyObject *self, PyObject *args)
{
char *ename;
PyObject *enumerators, *enumvalues;
PyObject *dict1 = NULL, *dict2 = NULL, *combined = NULL, *tmpkey = NULL;
int name_size;
CTypeDescrObject *td, *basetd;
Py_ssize_t i, n;
if (!PyArg_ParseTuple(args, "sO!O!O!:new_enum_type",
&ename,
&PyTuple_Type, &enumerators,
&PyTuple_Type, &enumvalues,
&CTypeDescr_Type, &basetd))
return NULL;
n = PyTuple_GET_SIZE(enumerators);
if (n != PyTuple_GET_SIZE(enumvalues)) {
PyErr_SetString(PyExc_ValueError,
"tuple args must have the same size");
return NULL;
}
if (!(basetd->ct_flags & (CT_PRIMITIVE_SIGNED|CT_PRIMITIVE_UNSIGNED))) {
PyErr_SetString(PyExc_TypeError,
"expected a primitive signed or unsigned base type");
return NULL;
}
dict1 = PyDict_New();
if (dict1 == NULL)
goto error;
dict2 = PyDict_New();
if (dict2 == NULL)
goto error;
for (i=n; --i >= 0; ) {
long long lvalue;
PyObject *value = PyTuple_GET_ITEM(enumvalues, i);
tmpkey = PyTuple_GET_ITEM(enumerators, i);
Py_INCREF(tmpkey);
if (!PyText_Check(tmpkey)) {
#if PY_MAJOR_VERSION < 3
if (PyUnicode_Check(tmpkey)) {
const char *text = PyText_AsUTF8(tmpkey);
if (text == NULL)
goto error;
Py_DECREF(tmpkey);
tmpkey = PyString_FromString(text);
if (tmpkey == NULL)
goto error;
}
else
#endif
{
PyErr_SetString(PyExc_TypeError,
"enumerators must be a list of strings");
goto error;
}
}
if (convert_from_object((char*)&lvalue, basetd, value) < 0)
goto error; /* out-of-range or badly typed 'value' */
if (PyDict_SetItem(dict1, tmpkey, value) < 0)
goto error;
if (PyDict_SetItem(dict2, value, tmpkey) < 0)
goto error;
Py_DECREF(tmpkey);
tmpkey = NULL;
}
combined = PyTuple_Pack(2, dict1, dict2);
if (combined == NULL)
goto error;
Py_CLEAR(dict2);
Py_CLEAR(dict1);
name_size = strlen(ename) + 1;
td = ctypedescr_new(name_size);
if (td == NULL)
goto error;
memcpy(td->ct_name, ename, name_size);
td->ct_stuff = combined;
td->ct_size = basetd->ct_size;
td->ct_length = basetd->ct_length; /* alignment */
td->ct_extra = basetd->ct_extra; /* ffi type */
td->ct_flags = basetd->ct_flags | CT_IS_ENUM;
td->ct_name_position = name_size - 1;
return (PyObject *)td;
error:
Py_XDECREF(tmpkey);
Py_XDECREF(combined);
Py_XDECREF(dict2);
Py_XDECREF(dict1);
return NULL;
}
static PyObject *b_alignof(PyObject *self, PyObject *arg)
{
int align;
if (!CTypeDescr_Check(arg)) {
PyErr_SetString(PyExc_TypeError, "expected a 'ctype' object");
return NULL;
}
align = get_alignment((CTypeDescrObject *)arg);
if (align < 0)
return NULL;
return PyInt_FromLong(align);
}
static Py_ssize_t direct_sizeof_cdata(CDataObject *cd)
{
Py_ssize_t size;
if (cd->c_type->ct_flags & CT_ARRAY)
size = get_array_length(cd) * cd->c_type->ct_itemdescr->ct_size;
else {
size = -1;
if (cd->c_type->ct_flags & (CT_STRUCT | CT_UNION))
size = _cdata_var_byte_size(cd);
if (size < 0)
size = cd->c_type->ct_size;
}
return size;
}
static PyObject *b_sizeof(PyObject *self, PyObject *arg)
{
Py_ssize_t size;
if (CData_Check(arg)) {
size = direct_sizeof_cdata((CDataObject *)arg);
}
else if (CTypeDescr_Check(arg)) {
size = ((CTypeDescrObject *)arg)->ct_size;
if (size < 0) {
PyErr_Format(PyExc_ValueError, "ctype '%s' is of unknown size",
((CTypeDescrObject *)arg)->ct_name);
return NULL;
}
}
else {
PyErr_SetString(PyExc_TypeError,
"expected a 'cdata' or 'ctype' object");
return NULL;
}
return PyInt_FromSsize_t(size);
}
static PyObject *b_typeof(PyObject *self, PyObject *arg)
{
PyObject *res;
if (!CData_Check(arg)) {
PyErr_SetString(PyExc_TypeError, "expected a 'cdata' object");
return NULL;
}
res = (PyObject *)((CDataObject *)arg)->c_type;
Py_INCREF(res);
return res;
}
static CTypeDescrObject *direct_typeoffsetof(CTypeDescrObject *ct,
PyObject *fieldname,
int following, Py_ssize_t *offset)
{
/* Does not return a new reference! */
CTypeDescrObject *res;
CFieldObject *cf;
if (PyTextAny_Check(fieldname)) {
if (!following && (ct->ct_flags & CT_POINTER))
ct = ct->ct_itemdescr;
if (!(ct->ct_flags & (CT_STRUCT|CT_UNION))) {
PyErr_SetString(PyExc_TypeError,
"with a field name argument, expected a "
"struct or union ctype");
return NULL;
}
if (force_lazy_struct(ct) <= 0) {
if (!PyErr_Occurred())
PyErr_SetString(PyExc_TypeError, "struct/union is opaque");
return NULL;
}
cf = (CFieldObject *)PyDict_GetItem(ct->ct_stuff, fieldname);
if (cf == NULL) {
PyErr_SetObject(PyExc_KeyError, fieldname);
return NULL;
}
if (cf->cf_bitshift >= 0) {
PyErr_SetString(PyExc_TypeError, "not supported for bitfields");
return NULL;
}
res = cf->cf_type;
*offset = cf->cf_offset;
}
else {
Py_ssize_t index = PyInt_AsSsize_t(fieldname);
if (index < 0 && PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError,
"field name or array index expected");
return NULL;
}
if (!(ct->ct_flags & (CT_ARRAY|CT_POINTER)) ||
ct->ct_itemdescr->ct_size < 0) {
PyErr_SetString(PyExc_TypeError, "with an integer argument, "
"expected an array ctype or a "
"pointer to non-opaque");
return NULL;
}
res = ct->ct_itemdescr;
*offset = MUL_WRAPAROUND(index, ct->ct_itemdescr->ct_size);
if ((*offset / ct->ct_itemdescr->ct_size) != index) {
PyErr_SetString(PyExc_OverflowError,
"array offset would overflow a Py_ssize_t");
return NULL;
}
}
return res;
}
static PyObject *b_typeoffsetof(PyObject *self, PyObject *args)
{
PyObject *res, *fieldname;
CTypeDescrObject *ct;
Py_ssize_t offset;
int following = 0;
if (!PyArg_ParseTuple(args, "O!O|i:typeoffsetof",
&CTypeDescr_Type, &ct, &fieldname, &following))
return NULL;
res = (PyObject *)direct_typeoffsetof(ct, fieldname, following, &offset);
if (res == NULL)
return NULL;
return Py_BuildValue("(On)", res, offset);
}
static PyObject *b_rawaddressof(PyObject *self, PyObject *args)
{
CTypeDescrObject *ct;
CDataObject *cd;
Py_ssize_t offset;
int accepted_flags;
if (!PyArg_ParseTuple(args, "O!O!n:rawaddressof",
&CTypeDescr_Type, &ct,
&CData_Type, &cd,
&offset))
return NULL;
accepted_flags = CT_STRUCT | CT_UNION | CT_ARRAY | CT_POINTER;
if ((cd->c_type->ct_flags & accepted_flags) == 0) {
PyErr_SetString(PyExc_TypeError,
"expected a cdata struct/union/array/pointer object");
return NULL;
}
if ((ct->ct_flags & CT_POINTER) == 0) {
PyErr_SetString(PyExc_TypeError,
"expected a pointer ctype");
return NULL;
}
return new_simple_cdata(cd->c_data + offset, ct);
}
static PyObject *b_getcname(PyObject *self, PyObject *args)
{
CTypeDescrObject *ct;
char *replace_with, *p, *s;
Py_ssize_t namelen, replacelen;
if (!PyArg_ParseTuple(args, "O!s:getcname",
&CTypeDescr_Type, &ct, &replace_with))
return NULL;
namelen = strlen(ct->ct_name);
replacelen = strlen(replace_with);
s = p = alloca(namelen + replacelen + 1);
memcpy(p, ct->ct_name, ct->ct_name_position);
p += ct->ct_name_position;
memcpy(p, replace_with, replacelen);
p += replacelen;
memcpy(p, ct->ct_name + ct->ct_name_position,
namelen - ct->ct_name_position);
return PyText_FromStringAndSize(s, namelen + replacelen);
}
static PyObject *b_string(PyObject *self, PyObject *args, PyObject *kwds)
{
CDataObject *cd;
Py_ssize_t maxlen = -1;
static char *keywords[] = {"cdata", "maxlen", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!|n:string", keywords,
&CData_Type, &cd, &maxlen))
return NULL;
if (cd->c_type->ct_itemdescr != NULL &&
cd->c_type->ct_itemdescr->ct_flags & (CT_PRIMITIVE_CHAR |
CT_PRIMITIVE_SIGNED |
CT_PRIMITIVE_UNSIGNED) &&
!(cd->c_type->ct_itemdescr->ct_flags & CT_IS_BOOL)) {
Py_ssize_t length = maxlen;
if (cd->c_data == NULL) {
PyObject *s = cdata_repr(cd);
if (s != NULL) {
PyErr_Format(PyExc_RuntimeError,
"cannot use string() on %s",
PyText_AS_UTF8(s));
Py_DECREF(s);
}
return NULL;
}
if (length < 0 && cd->c_type->ct_flags & CT_ARRAY) {
length = get_array_length(cd);
}
if (cd->c_type->ct_itemdescr->ct_size == sizeof(char)) {
const char *start = cd->c_data;
if (length < 0) {
/*READ(start, 1)*/
length = strlen(start);
/*READ(start, length)*/
}
else {
const char *end;
/*READ(start, length)*/
end = (const char *)memchr(start, 0, length);
if (end != NULL)
length = end - start;
}
return PyBytes_FromStringAndSize(start, length);
}
else if (cd->c_type->ct_itemdescr->ct_flags & CT_PRIMITIVE_CHAR) {
switch (cd->c_type->ct_itemdescr->ct_size) {
case 2: {
const cffi_char16_t *start = (cffi_char16_t *)cd->c_data;
if (length < 0) {
/*READ(start, 2)*/
length = 0;
while (start[length])
length++;
/*READ(start, 2 * length)*/
}
else {
/*READ(start, 2 * length)*/
maxlen = length;
length = 0;
while (length < maxlen && start[length])
length++;
}
return _my_PyUnicode_FromChar16(start, length);
}
case 4: {
const cffi_char32_t *start = (cffi_char32_t *)cd->c_data;
if (length < 0) {
/*READ(start, 4)*/
length = 0;
while (start[length])
length++;
/*READ(start, 4 * length)*/
}
else {
/*READ(start, 4 * length)*/
maxlen = length;
length = 0;
while (length < maxlen && start[length])
length++;
}
return _my_PyUnicode_FromChar32(start, length);
}
}
}
}
else if (cd->c_type->ct_flags & CT_IS_ENUM) {
return convert_cdata_to_enum_string(cd, 0);
}
else if (cd->c_type->ct_flags & CT_IS_BOOL) {
/* fall through to TypeError */
}
else if (cd->c_type->ct_flags & (CT_PRIMITIVE_CHAR |
CT_PRIMITIVE_SIGNED |
CT_PRIMITIVE_UNSIGNED)) {
/*READ(cd->c_data, cd->c_type->ct_size)*/
if (cd->c_type->ct_size == sizeof(char))
return PyBytes_FromStringAndSize(cd->c_data, 1);
else if (cd->c_type->ct_flags & CT_PRIMITIVE_CHAR) {
switch (cd->c_type->ct_size) {
case 2:
return _my_PyUnicode_FromChar16((cffi_char16_t *)cd->c_data, 1);
case 4:
return _my_PyUnicode_FromChar32((cffi_char32_t *)cd->c_data, 1);
}
}
}
PyErr_Format(PyExc_TypeError, "string(): unexpected cdata '%s' argument",
cd->c_type->ct_name);
return NULL;
}
static PyObject *b_unpack(PyObject *self, PyObject *args, PyObject *kwds)
{
CDataObject *cd;
CTypeDescrObject *ctitem;
Py_ssize_t i, length, itemsize;
PyObject *result;
char *src;
int casenum;
static char *keywords[] = {"cdata", "length", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!n:unpack", keywords,
&CData_Type, &cd, &length))
return NULL;
if (!(cd->c_type->ct_flags & (CT_ARRAY|CT_POINTER))) {
PyErr_Format(PyExc_TypeError,
"expected a pointer or array, got '%s'",
cd->c_type->ct_name);
return NULL;
}
if (length < 0) {
PyErr_SetString(PyExc_ValueError, "'length' cannot be negative");
return NULL;
}
if (cd->c_data == NULL) {
PyObject *s = cdata_repr(cd);
if (s != NULL) {
PyErr_Format(PyExc_RuntimeError,
"cannot use unpack() on %s",
PyText_AS_UTF8(s));
Py_DECREF(s);
}
return NULL;
}
/* byte- and unicode strings */
ctitem = cd->c_type->ct_itemdescr;
if (ctitem->ct_flags & CT_PRIMITIVE_CHAR) {
switch (ctitem->ct_size) {
case sizeof(char):
return PyBytes_FromStringAndSize(cd->c_data, length);
case 2:
return _my_PyUnicode_FromChar16((cffi_char16_t *)cd->c_data,length);
case 4:
return _my_PyUnicode_FromChar32((cffi_char32_t *)cd->c_data,length);
}
}
/* else, the result is a list. This implementation should be
equivalent to but much faster than '[p[i] for i in range(length)]'.
(Note that on PyPy, 'list(p[0:length])' should be equally fast,
but arguably, finding out that there *is* such an unexpected way
to write things down is the real problem.)
*/
result = PyList_New(length);
if (result == NULL)
return NULL;
src = cd->c_data;
itemsize = ctitem->ct_size;
if (itemsize < 0) {
Py_DECREF(result);
PyErr_Format(PyExc_ValueError, "'%s' points to items of unknown size",
cd->c_type->ct_name);
return NULL;
}
/* Determine some common fast-paths for the loop below. The case -1
is the fall-back, which always gives the right answer. */
#define ALIGNMENT_CHECK(align) \
(((align) & ((align) - 1)) == 0 && \
(((uintptr_t)src) & ((align) - 1)) == 0)
casenum = -1;
if ((ctitem->ct_flags & CT_PRIMITIVE_ANY) &&
ALIGNMENT_CHECK(ctitem->ct_length)) {
/* Source data is fully aligned; we can directly read without
memcpy(). The unaligned case is expected to be rare; in
this situation it is ok to fall back to the general
convert_to_object() in the loop. For now we also use this
fall-back for types that are too large.
*/
if (ctitem->ct_flags & CT_PRIMITIVE_SIGNED) {
if (itemsize == sizeof(long)) casenum = 3;
else if (itemsize == sizeof(int)) casenum = 2;
else if (itemsize == sizeof(short)) casenum = 1;
else if (itemsize == sizeof(signed char)) casenum = 0;
}
else if (ctitem->ct_flags & CT_PRIMITIVE_UNSIGNED) {
/* Note: we never pick case 6 if sizeof(int) == sizeof(long),
so that case 6 below can assume that the 'unsigned int' result
would always fit in a 'signed long'. */
if (ctitem->ct_flags & CT_IS_BOOL) casenum = 11;
else if (itemsize == sizeof(unsigned long)) casenum = 7;
else if (itemsize == sizeof(unsigned int)) casenum = 6;
else if (itemsize == sizeof(unsigned short)) casenum = 5;
else if (itemsize == sizeof(unsigned char)) casenum = 4;
}
else if (ctitem->ct_flags & CT_PRIMITIVE_FLOAT) {
if (itemsize == sizeof(double)) casenum = 9;
else if (itemsize == sizeof(float)) casenum = 8;
}
}
else if (ctitem->ct_flags & (CT_POINTER | CT_FUNCTIONPTR)) {
casenum = 10; /* any pointer */
}
#undef ALIGNMENT_CHECK
for (i = 0; i < length; i++) {
PyObject *x;
switch (casenum) {
/* general case */
default: x = convert_to_object(src, ctitem); break;
/* special cases for performance only */
case 0: x = PyInt_FromLong(*(signed char *)src); break;
case 1: x = PyInt_FromLong(*(short *)src); break;
case 2: x = PyInt_FromLong(*(int *)src); break;
case 3: x = PyInt_FromLong(*(long *)src); break;
case 4: x = PyInt_FromLong(*(unsigned char *)src); break;
case 5: x = PyInt_FromLong(*(unsigned short *)src); break;
case 6: x = PyInt_FromLong((long)*(unsigned int *)src); break;
case 7: x = PyLong_FromUnsignedLong(*(unsigned long *)src); break;
case 8: x = PyFloat_FromDouble(*(float *)src); break;
case 9: x = PyFloat_FromDouble(*(double *)src); break;
case 10: x = new_simple_cdata(*(char **)src, ctitem); break;
case 11:
switch (*(unsigned char *)src) {
case 0: x = Py_False; Py_INCREF(x); break;
case 1: x = Py_True; Py_INCREF(x); break;
default: x = convert_to_object(src, ctitem); /* error */
}
break;
}
if (x == NULL) {
Py_DECREF(result);
return NULL;
}
PyList_SET_ITEM(result, i, x);
src += itemsize;
}
return result;
}
static PyObject *
b_buffer_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
/* this is the constructor of the type implemented in minibuffer.h */
CDataObject *cd;
Py_ssize_t size = -1;
static char *keywords[] = {"cdata", "size", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!|n:buffer", keywords,
&CData_Type, &cd, &size))
return NULL;
if (size < 0)
size = _cdata_var_byte_size(cd);
if (cd->c_type->ct_flags & CT_POINTER) {
if (size < 0)
size = cd->c_type->ct_itemdescr->ct_size;
}
else if (cd->c_type->ct_flags & CT_ARRAY) {
if (size < 0)
size = get_array_length(cd) * cd->c_type->ct_itemdescr->ct_size;
}
else {
PyErr_Format(PyExc_TypeError,
"expected a pointer or array cdata, got '%s'",
cd->c_type->ct_name);
return NULL;
}
if (size < 0) {
PyErr_Format(PyExc_TypeError,
"don't know the size pointed to by '%s'",
cd->c_type->ct_name);
return NULL;
}
/*WRITE(cd->c_data, size)*/
return minibuffer_new(cd->c_data, size, (PyObject *)cd);
}
static PyObject *b_get_errno(PyObject *self, PyObject *noarg)
{
int err;
restore_errno_only();
err = errno;
errno = 0;
return PyInt_FromLong(err);
}
static PyObject *b_set_errno(PyObject *self, PyObject *arg)
{
long ival = PyInt_AsLong(arg);
if (ival == -1 && PyErr_Occurred())
return NULL;
else if (ival < INT_MIN || ival > INT_MAX) {
PyErr_SetString(PyExc_OverflowError, "errno value too large");
return NULL;
}
errno = (int)ival;
save_errno_only();
errno = 0;
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *newp_handle(CTypeDescrObject *ct_voidp, PyObject *x)
{
CDataObject_own_structptr *cd;
cd = (CDataObject_own_structptr *)PyObject_GC_New(CDataObject_own_structptr,
&CDataOwningGC_Type);
if (cd == NULL)
return NULL;
Py_INCREF(ct_voidp); /* must be "void *" */
cd->head.c_type = ct_voidp;
cd->head.c_data = (char *)cd;
cd->head.c_weakreflist = NULL;
Py_INCREF(x);
cd->structobj = x;
PyObject_GC_Track(cd);
return (PyObject *)cd;
}
static PyObject *b_newp_handle(PyObject *self, PyObject *args)
{
CTypeDescrObject *ct;
PyObject *x;
if (!PyArg_ParseTuple(args, "O!O", &CTypeDescr_Type, &ct, &x))
return NULL;
if (!(ct->ct_flags & CT_IS_VOID_PTR)) {
PyErr_Format(PyExc_TypeError, "needs 'void *', got '%s'", ct->ct_name);
return NULL;
}
return newp_handle(ct, x);
}
static PyObject *b_from_handle(PyObject *self, PyObject *arg)
{
CTypeDescrObject *ct;
CDataObject_own_structptr *orgcd;
PyObject *x;
if (!CData_Check(arg)) {
PyErr_SetString(PyExc_TypeError, "expected a 'cdata' object");
return NULL;
}
ct = ((CDataObject *)arg)->c_type;
if (!(ct->ct_flags & CT_IS_VOIDCHAR_PTR)) {
PyErr_Format(PyExc_TypeError,
"expected a 'cdata' object with a 'void *' out of "
"new_handle(), got '%s'", ct->ct_name);
return NULL;
}
orgcd = (CDataObject_own_structptr *)((CDataObject *)arg)->c_data;
if (!orgcd) {
PyErr_SetString(PyExc_RuntimeError,
"cannot use from_handle() on NULL pointer");
return NULL;
}
if (Py_REFCNT(orgcd) <= 0 || Py_TYPE(orgcd) != &CDataOwningGC_Type) {
Py_FatalError("ffi.from_handle() detected that the address passed "
"points to garbage. If it is really the result of "
"ffi.new_handle(), then the Python object has already "
"been garbage collected");
}
x = orgcd->structobj;
Py_INCREF(x);
return x;
}
static int _my_PyObject_GetContiguousBuffer(PyObject *x, Py_buffer *view,
int writable_only)
{
#if PY_MAJOR_VERSION < 3
/* Some objects only support the buffer interface and CPython doesn't
translate it into the memoryview interface, mess. Hack a very
minimal content for 'view'. Don't care if the other fields are
uninitialized: we only call PyBuffer_Release(), which only reads
'view->obj'. */
PyBufferProcs *pb = x->ob_type->tp_as_buffer;
if (pb && !pb->bf_releasebuffer) {
/* we used to try all three in some vaguely sensible order,
i.e. first the write. But trying to call the write on a
read-only buffer fails with TypeError. So we use a less-
sensible order now. See test_from_buffer_more_cases.
If 'writable_only', we only try bf_getwritebuffer.
*/
readbufferproc proc = NULL;
if (!writable_only) {
proc = (readbufferproc)pb->bf_getreadbuffer;
if (!proc)
proc = (readbufferproc)pb->bf_getcharbuffer;
}
if (!proc)
proc = (readbufferproc)pb->bf_getwritebuffer;
if (proc && pb->bf_getsegcount) {
if ((*pb->bf_getsegcount)(x, NULL) != 1) {
PyErr_SetString(PyExc_TypeError,
"expected a single-segment buffer object");
return -1;
}
view->len = (*proc)(x, 0, &view->buf);
if (view->len < 0)
return -1;
view->obj = x;
Py_INCREF(x);
return 0;
}
}
#endif
if (PyObject_GetBuffer(x, view, writable_only ? PyBUF_WRITABLE
: PyBUF_SIMPLE) < 0)
return -1;
if (!PyBuffer_IsContiguous(view, 'A')) {
PyBuffer_Release(view);
PyErr_SetString(PyExc_TypeError, "contiguous buffer expected");
return -1;
}
return 0;
}
static PyObject *direct_from_buffer(CTypeDescrObject *ct, PyObject *x,
int require_writable)
{
CDataObject *cd;
Py_buffer *view;
Py_ssize_t arraylength, minimumlength = 0;
if (!(ct->ct_flags & (CT_ARRAY | CT_POINTER))) {
PyErr_Format(PyExc_TypeError,
"expected a pointer or array ctype, got '%s'",
ct->ct_name);
return NULL;
}
/* PyPy 5.7 can obtain buffers for string (python 2)
or bytes (python 3). from_buffer(u"foo") is disallowed.
*/
if (PyUnicode_Check(x)) {
PyErr_SetString(PyExc_TypeError,
"from_buffer() cannot return the address "
"of a unicode object");
return NULL;
}
view = PyObject_Malloc(sizeof(Py_buffer));
if (view == NULL) {
PyErr_NoMemory();
return NULL;
}
if (_my_PyObject_GetContiguousBuffer(x, view, require_writable) < 0)
goto error1;
if (ct->ct_flags & CT_POINTER)
{
arraylength = view->len; /* number of bytes, not used so far */
}
else {
/* ct->ct_flags & CT_ARRAY */
if (ct->ct_length >= 0) {
/* it's an array with a fixed length; make sure that the
buffer contains enough bytes. */
minimumlength = ct->ct_size;
arraylength = ct->ct_length;
}
else {
/* it's an open 'array[]' */
if (ct->ct_itemdescr->ct_size == 1) {
/* fast path, performance only */
arraylength = view->len;
}
else if (ct->ct_itemdescr->ct_size > 0) {
/* give it as many items as fit the buffer. Ignore a
partial last element. */
arraylength = view->len / ct->ct_itemdescr->ct_size;
}
else {
/* it's an array 'empty[]'. Unsupported obscure case:
the problem is that setting the length of the result
to anything large (like SSIZE_T_MAX) is dangerous,
because if someone tries to loop over it, it will
turn effectively into an infinite loop. */
PyErr_Format(PyExc_ZeroDivisionError,
"from_buffer('%s', ..): the actual length of the array "
"cannot be computed", ct->ct_name);
goto error2;
}
}
}
if (view->len < minimumlength) {
PyErr_Format(PyExc_ValueError,
"buffer is too small (%zd bytes) for '%s' (%zd bytes)",
view->len, ct->ct_name, minimumlength);
goto error2;
}
cd = (CDataObject *)PyObject_GC_New(CDataObject_frombuf,
&CDataFromBuf_Type);
if (cd == NULL)
goto error2;
Py_INCREF(ct);
cd->c_type = ct;
cd->c_data = view->buf;
cd->c_weakreflist = NULL;
((CDataObject_frombuf *)cd)->length = arraylength;
((CDataObject_frombuf *)cd)->bufferview = view;
PyObject_GC_Track(cd);
return (PyObject *)cd;
error2:
PyBuffer_Release(view);
error1:
PyObject_Free(view);
return NULL;
}
static PyObject *b_from_buffer(PyObject *self, PyObject *args)
{
CTypeDescrObject *ct;
PyObject *x;
int require_writable = 0;
if (!PyArg_ParseTuple(args, "O!O|i", &CTypeDescr_Type, &ct, &x,
&require_writable))
return NULL;
return direct_from_buffer(ct, x, require_writable);
}
static int _fetch_as_buffer(PyObject *x, Py_buffer *view, int writable_only)
{
if (CData_Check(x)) {
CTypeDescrObject *ct = ((CDataObject *)x)->c_type;
if (!(ct->ct_flags & (CT_POINTER|CT_ARRAY))) {
PyErr_Format(PyExc_TypeError,
"expected a pointer or array ctype, got '%s'",
ct->ct_name);
return -1;
}
view->buf = ((CDataObject *)x)->c_data;
view->obj = NULL;
return 0;
}
else {
return _my_PyObject_GetContiguousBuffer(x, view, writable_only);
}
}
static PyObject *b_memmove(PyObject *self, PyObject *args, PyObject *kwds)
{
PyObject *dest_obj, *src_obj;
Py_buffer dest_view, src_view;
Py_ssize_t n;
static char *keywords[] = {"dest", "src", "n", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOn", keywords,
&dest_obj, &src_obj, &n))
return NULL;
if (n < 0) {
PyErr_SetString(PyExc_ValueError, "negative size");
return NULL;
}
if (_fetch_as_buffer(src_obj, &src_view, 0) < 0) {
return NULL;
}
if (_fetch_as_buffer(dest_obj, &dest_view, 1) < 0) {
PyBuffer_Release(&src_view);
return NULL;
}
memmove(dest_view.buf, src_view.buf, n);
PyBuffer_Release(&dest_view);
PyBuffer_Release(&src_view);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *b__get_types(PyObject *self, PyObject *noarg)
{
return PyTuple_Pack(2, (PyObject *)&CData_Type,
(PyObject *)&CTypeDescr_Type);
}
/* forward, in commontypes.c */
static PyObject *b__get_common_types(PyObject *self, PyObject *arg);
static PyObject *b_gcp(PyObject *self, PyObject *args, PyObject *kwds)
{
CDataObject *cd;
CDataObject *origobj;
PyObject *destructor;
Py_ssize_t ignored; /* for pypy */
static char *keywords[] = {"cdata", "destructor", "size", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!O|n:gc", keywords,
&CData_Type, &origobj, &destructor,
&ignored))
return NULL;
if (destructor == Py_None) {
if (!PyObject_TypeCheck(origobj, &CDataGCP_Type)) {
PyErr_SetString(PyExc_TypeError,
"Can remove destructor only on a object "
"previously returned by ffi.gc()");
return NULL;
}
Py_CLEAR(((CDataObject_gcp *)origobj)->destructor);
Py_RETURN_NONE;
}
cd = allocate_gcp_object(origobj, origobj->c_type, destructor);
return (PyObject *)cd;
}
static PyObject *b_release(PyObject *self, PyObject *arg)
{
if (!CData_Check(arg)) {
PyErr_SetString(PyExc_TypeError, "expected a 'cdata' object");
return NULL;
}
return cdata_exit(arg, NULL);
}
/************************************************************/
static char _testfunc0(char a, char b)
{
return a + b;
}
static long _testfunc1(int a, long b)
{
return (long)a + b;
}
static PY_LONG_LONG _testfunc2(PY_LONG_LONG a, PY_LONG_LONG b)
{
return a + b;
}
static double _testfunc3(float a, double b)
{
return a + b;
}
static float _testfunc4(float a, double b)
{
return (float)(a + b);
}
static void _testfunc5(void)
{
errno = errno + 15;
}
static int *_testfunc6(int *x)
{
static int y;
y = *x - 1000;
return &y;
}
struct _testfunc7_s { unsigned char a1; short a2; };
static short _testfunc7(struct _testfunc7_s inlined)
{
return inlined.a1 + inlined.a2;
}
static int _testfunc9(int num, ...)
{
va_list vargs;
int i, total = 0;
va_start(vargs, num);
for (i=0; i<num; i++) {
int value = va_arg(vargs, int);
if (value == 0)
value = -66666666;
total += value;
}
va_end(vargs);
return total;
}
static struct _testfunc7_s _testfunc10(int n)
{
struct _testfunc7_s result;
result.a1 = n;
result.a2 = n * n;
return result;
}
struct _testfunc11_s { int a1, a2; };
static struct _testfunc11_s _testfunc11(int n)
{
struct _testfunc11_s result;
result.a1 = n;
result.a2 = n * n;
return result;
}
struct _testfunc12_s { double a1; };
static struct _testfunc12_s _testfunc12(int n)
{
struct _testfunc12_s result;
result.a1 = n;
return result;
}
struct _testfunc13_s { int a1, a2, a3; };
static struct _testfunc13_s _testfunc13(int n)
{
struct _testfunc13_s result;
result.a1 = n;
result.a2 = n * n;
result.a3 = n * n * n;
return result;
}
struct _testfunc14_s { float a1; };
static struct _testfunc14_s _testfunc14(int n)
{
struct _testfunc14_s result;
result.a1 = (float)n;
return result;
}
struct _testfunc15_s { float a1; int a2; };
static struct _testfunc15_s _testfunc15(int n)
{
struct _testfunc15_s result;
result.a1 = (float)n;
result.a2 = n * n;
return result;
}
struct _testfunc16_s { float a1, a2; };
static struct _testfunc16_s _testfunc16(int n)
{
struct _testfunc16_s result;
result.a1 = (float)n;
result.a2 = -(float)n;
return result;
}
struct _testfunc17_s { int a1; float a2; };
static struct _testfunc17_s _testfunc17(int n)
{
struct _testfunc17_s result;
result.a1 = n;
result.a2 = (float)n * (float)n;
return result;
}
static int _testfunc18(struct _testfunc17_s *ptr)
{
return ptr->a1 + (int)ptr->a2;
}
static long double _testfunc19(long double x, int count)
{
int i;
for (i=0; i<count; i++) {
x = 4*x - x*x;
}
return x;
}
static short _testfunc20(struct _testfunc7_s *ptr)
{
return ptr->a1 + ptr->a2;
}
struct _testfunc21_s { int a, b, c, d, e, f, g, h, i, j; };
static int _testfunc21(struct _testfunc21_s inlined)
{
return ((inlined.a << 0) +
(inlined.b << 1) +
(inlined.c << 2) +
(inlined.d << 3) +
(inlined.e << 4) +
(inlined.f << 5) +
(inlined.g << 6) +
(inlined.h << 7) +
(inlined.i << 8) +
(inlined.j << 9));
}
struct _testfunc22_s { int a[10]; };
static struct _testfunc22_s _testfunc22(struct _testfunc22_s s1,
struct _testfunc22_s s2)
{
struct _testfunc22_s result;
int i;
for (i=0; i<10; i++)
result.a[i] = s1.a[i] - s2.a[i];
return result;
}
static int _testfunc23(char *p)
{
if (p)
return 1000 * p[0];
return -42;
}
#if 0 /* libffi doesn't properly support complexes currently */
/* also, MSVC might not support _Complex... */
/* if this is enabled one day, remember to also add _Complex
* arguments in addition to return values. */
static float _Complex _testfunc24(float a, float b)
{
return a + I*2.0*b;
}
static double _Complex _testfunc25(double a, double b)
{
return a + I*2.0*b;
}
#endif
static PyObject *b__testfunc(PyObject *self, PyObject *args)
{
/* for testing only */
int i;
void *f;
if (!PyArg_ParseTuple(args, "i:_testfunc", &i))
return NULL;
switch (i) {
case 0: f = &_testfunc0; break;
case 1: f = &_testfunc1; break;
case 2: f = &_testfunc2; break;
case 3: f = &_testfunc3; break;
case 4: f = &_testfunc4; break;
case 5: f = &_testfunc5; break;
case 6: f = &_testfunc6; break;
case 7: f = &_testfunc7; break;
case 8: f = stderr; break;
case 9: f = &_testfunc9; break;
case 10: f = &_testfunc10; break;
case 11: f = &_testfunc11; break;
case 12: f = &_testfunc12; break;
case 13: f = &_testfunc13; break;
case 14: f = &_testfunc14; break;
case 15: f = &_testfunc15; break;
case 16: f = &_testfunc16; break;
case 17: f = &_testfunc17; break;
case 18: f = &_testfunc18; break;
case 19: f = &_testfunc19; break;
case 20: f = &_testfunc20; break;
case 21: f = &_testfunc21; break;
case 22: f = &_testfunc22; break;
case 23: f = &_testfunc23; break;
#if 0
case 24: f = &_testfunc24; break;
case 25: f = &_testfunc25; break;
#endif
default:
PyErr_SetNone(PyExc_ValueError);
return NULL;
}
return PyLong_FromVoidPtr(f);
}
#if PY_MAJOR_VERSION < 3
static Py_ssize_t _test_segcountproc(PyObject *o, Py_ssize_t *ignored)
{
return 1;
}
static Py_ssize_t _test_getreadbuf(PyObject *o, Py_ssize_t i, void **r)
{
static char buf[] = "RDB";
*r = buf;
return 3;
}
static Py_ssize_t _test_getwritebuf(PyObject *o, Py_ssize_t i, void **r)
{
static char buf[] = "WRB";
*r = buf;
return 3;
}
static Py_ssize_t _test_getcharbuf(PyObject *o, Py_ssize_t i, char **r)
{
static char buf[] = "CHB";
*r = buf;
return 3;
}
#endif
static int _test_getbuf(PyObject *self, Py_buffer *view, int flags)
{
static char buf[] = "GTB";
return PyBuffer_FillInfo(view, self, buf, 3, /*readonly=*/0, flags);
}
static int _test_getbuf_ro(PyObject *self, Py_buffer *view, int flags)
{
static char buf[] = "ROB";
return PyBuffer_FillInfo(view, self, buf, 3, /*readonly=*/1, flags);
}
static PyObject *b__testbuff(PyObject *self, PyObject *args)
{
/* for testing only */
int methods;
PyTypeObject *obj;
if (!PyArg_ParseTuple(args, "O!i|_testbuff", &PyType_Type, &obj, &methods))
return NULL;
assert(obj->tp_as_buffer != NULL);
#if PY_MAJOR_VERSION < 3
obj->tp_as_buffer->bf_getsegcount = &_test_segcountproc;
obj->tp_flags |= Py_TPFLAGS_HAVE_GETCHARBUFFER;
obj->tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
if (methods & 1) obj->tp_as_buffer->bf_getreadbuffer = &_test_getreadbuf;
if (methods & 2) obj->tp_as_buffer->bf_getwritebuffer = &_test_getwritebuf;
if (methods & 4) obj->tp_as_buffer->bf_getcharbuffer = &_test_getcharbuf;
#endif
if (methods & 8) obj->tp_as_buffer->bf_getbuffer = &_test_getbuf;
if (methods & 16) obj->tp_as_buffer->bf_getbuffer = &_test_getbuf_ro;
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *b_init_cffi_1_0_external_module(PyObject *, PyObject *);
/* forward, see cffi1_module.c */
static PyMethodDef FFIBackendMethods[] = {
{"load_library", b_load_library, METH_VARARGS},
{"new_primitive_type", b_new_primitive_type, METH_VARARGS},
{"new_pointer_type", b_new_pointer_type, METH_VARARGS},
{"new_array_type", b_new_array_type, METH_VARARGS},
{"new_void_type", b_new_void_type, METH_NOARGS},
{"new_struct_type", b_new_struct_type, METH_VARARGS},
{"new_union_type", b_new_union_type, METH_VARARGS},
{"complete_struct_or_union", b_complete_struct_or_union, METH_VARARGS},
{"new_function_type", b_new_function_type, METH_VARARGS},
{"new_enum_type", b_new_enum_type, METH_VARARGS},
{"newp", b_newp, METH_VARARGS},
{"cast", b_cast, METH_VARARGS},
{"callback", b_callback, METH_VARARGS},
{"alignof", b_alignof, METH_O},
{"sizeof", b_sizeof, METH_O},
{"typeof", b_typeof, METH_O},
{"typeoffsetof", b_typeoffsetof, METH_VARARGS},
{"rawaddressof", b_rawaddressof, METH_VARARGS},
{"getcname", b_getcname, METH_VARARGS},
{"string", (PyCFunction)b_string, METH_VARARGS | METH_KEYWORDS},
{"unpack", (PyCFunction)b_unpack, METH_VARARGS | METH_KEYWORDS},
{"get_errno", b_get_errno, METH_NOARGS},
{"set_errno", b_set_errno, METH_O},
{"newp_handle", b_newp_handle, METH_VARARGS},
{"from_handle", b_from_handle, METH_O},
{"from_buffer", b_from_buffer, METH_VARARGS},
{"memmove", (PyCFunction)b_memmove, METH_VARARGS | METH_KEYWORDS},
{"gcp", (PyCFunction)b_gcp, METH_VARARGS | METH_KEYWORDS},
{"release", b_release, METH_O},
#ifdef MS_WIN32
{"getwinerror", (PyCFunction)b_getwinerror, METH_VARARGS | METH_KEYWORDS},
#endif
{"_get_types", b__get_types, METH_NOARGS},
{"_get_common_types", b__get_common_types, METH_O},
{"_testfunc", b__testfunc, METH_VARARGS},
{"_testbuff", b__testbuff, METH_VARARGS},
{"_init_cffi_1_0_external_module", b_init_cffi_1_0_external_module, METH_O},
{NULL, NULL} /* Sentinel */
};
/************************************************************/
/* Functions used by '_cffi_N.so', the generated modules */
#define _cffi_to_c_SIGNED_FN(RETURNTYPE, SIZE) \
static RETURNTYPE _cffi_to_c_i##SIZE(PyObject *obj) { \
PY_LONG_LONG tmp = _my_PyLong_AsLongLong(obj); \
if ((tmp > (PY_LONG_LONG)((1ULL<<(SIZE-1)) - 1)) || \
(tmp < (PY_LONG_LONG)(0ULL-(1ULL<<(SIZE-1))))) \
if (!PyErr_Occurred()) \
return (RETURNTYPE)_convert_overflow(obj, #SIZE "-bit int"); \
return (RETURNTYPE)tmp; \
}
#define _cffi_to_c_UNSIGNED_FN(RETURNTYPE, SIZE) \
static RETURNTYPE _cffi_to_c_u##SIZE(PyObject *obj) { \
unsigned PY_LONG_LONG tmp = _my_PyLong_AsUnsignedLongLong(obj, 1); \
if (tmp > ~(((unsigned PY_LONG_LONG)-2) << (SIZE-1))) \
if (!PyErr_Occurred()) \
return (RETURNTYPE)_convert_overflow(obj, \
#SIZE "-bit unsigned int"); \
return (RETURNTYPE)tmp; \
}
_cffi_to_c_SIGNED_FN(int, 8)
_cffi_to_c_SIGNED_FN(int, 16)
_cffi_to_c_SIGNED_FN(int, 32)
_cffi_to_c_SIGNED_FN(PY_LONG_LONG, 64)
_cffi_to_c_UNSIGNED_FN(int, 8)
_cffi_to_c_UNSIGNED_FN(int, 16)
_cffi_to_c_UNSIGNED_FN(unsigned int, 32)
_cffi_to_c_UNSIGNED_FN(unsigned PY_LONG_LONG, 64)
static PyObject *_cffi_from_c_pointer(char *ptr, CTypeDescrObject *ct)
{
return convert_to_object((char *)&ptr, ct);
}
static char *_cffi_to_c_pointer(PyObject *obj, CTypeDescrObject *ct)
{
char *result;
if (convert_from_object((char *)&result, ct, obj) < 0) {
if ((ct->ct_flags & CT_POINTER) &&
(ct->ct_itemdescr->ct_flags & CT_IS_FILE) &&
PyFile_Check(obj)) {
PyErr_Clear();
return (char *)PyFile_AsFile(obj);
}
return NULL;
}
return result;
}
static long double _cffi_to_c_long_double(PyObject *obj)
{
if (CData_Check(obj) &&
(((CDataObject *)obj)->c_type->ct_flags & CT_IS_LONGDOUBLE)) {
char *data = ((CDataObject *)obj)->c_data;
/*READ(data, sizeof(long double))*/
return read_raw_longdouble_data(data);
}
else
return PyFloat_AsDouble(obj);
}
static _Bool _cffi_to_c__Bool(PyObject *obj)
{
PY_LONG_LONG tmp = _my_PyLong_AsLongLong(obj);
if (tmp == 0)
return 0;
else if (tmp == 1)
return 1;
else if (PyErr_Occurred())
return (_Bool)-1;
else
return (_Bool)_convert_overflow(obj, "_Bool");
}
static PyObject *_cffi_get_struct_layout(Py_ssize_t nums[])
{
PyObject *result;
int count = 0;
while (nums[count] >= 0)
count++;
result = PyList_New(count);
if (result == NULL)
return NULL;
while (--count >= 0) {
PyObject *o = PyInt_FromSsize_t(nums[count]);
if (o == NULL) {
Py_DECREF(result);
return NULL;
}
PyList_SET_ITEM(result, count, o);
}
return result;
}
static PyObject *_cffi_from_c_char(char x) {
return PyBytes_FromStringAndSize(&x, 1);
}
/* backward-compatibility hack: instead of _cffi_to_c_char16_t() and
* _cffi_to_c_char32_t(), we have _cffi_to_c_wchar_t() handling whatever
* size is wchar_t, and _cffi_to_c_wchar3216_t() handling the opposite.
*/
#ifdef HAVE_WCHAR_H
typedef wchar_t cffi_wchar_t;
#else
typedef uint16_t cffi_wchar_t; /* random pick... */
#endif
static cffi_wchar_t _cffi_to_c_wchar_t(PyObject *init)
{
if (sizeof(cffi_wchar_t) == 2)
return (cffi_wchar_t)_convert_to_char16_t(init);
else
return (cffi_wchar_t)_convert_to_char32_t(init);
}
static PyObject *_cffi_from_c_wchar_t(cffi_wchar_t x) {
if (sizeof(cffi_wchar_t) == 2) {
cffi_char16_t input = x;
return _my_PyUnicode_FromChar16(&input, 1);
}
else {
cffi_char32_t input = x;
return _my_PyUnicode_FromChar32(&input, 1);
}
}
static int _cffi_to_c_wchar3216_t(PyObject *init)
{
if (sizeof(cffi_wchar_t) == 4)
return (int)_convert_to_char16_t(init);
else
return (int)_convert_to_char32_t(init);
}
static PyObject *_cffi_from_c_wchar3216_t(int x) {
if (sizeof(cffi_wchar_t) == 4) {
cffi_char16_t input = x;
return _my_PyUnicode_FromChar16(&input, 1);
}
else {
cffi_char32_t input = x;
return _my_PyUnicode_FromChar32(&input, 1);
}
}
struct _cffi_externpy_s; /* forward declaration */
static void cffi_call_python(struct _cffi_externpy_s *, char *args);
static void *cffi_exports[] = {
NULL,
_cffi_to_c_i8,
_cffi_to_c_u8,
_cffi_to_c_i16,
_cffi_to_c_u16,
_cffi_to_c_i32,
_cffi_to_c_u32,
_cffi_to_c_i64,
_cffi_to_c_u64,
_convert_to_char,
_cffi_from_c_pointer,
_cffi_to_c_pointer,
_cffi_get_struct_layout,
restore_errno,
save_errno,
_cffi_from_c_char,
convert_to_object,
convert_from_object,
convert_struct_to_owning_object,
_cffi_to_c_wchar_t,
_cffi_from_c_wchar_t,
_cffi_to_c_long_double,
_cffi_to_c__Bool,
_prepare_pointer_call_argument,
convert_array_from_object,
cffi_call_python,
_cffi_to_c_wchar3216_t,
_cffi_from_c_wchar3216_t,
};
static struct { const char *name; int value; } all_dlopen_flags[] = {
{ "RTLD_LAZY", RTLD_LAZY },
{ "RTLD_NOW", RTLD_NOW },
{ "RTLD_GLOBAL", RTLD_GLOBAL },
#ifdef RTLD_LOCAL
{ "RTLD_LOCAL", RTLD_LOCAL },
#else
{ "RTLD_LOCAL", 0 },
#endif
#ifdef RTLD_NODELETE
{ "RTLD_NODELETE", RTLD_NODELETE },
#endif
#ifdef RTLD_NOLOAD
{ "RTLD_NOLOAD", RTLD_NOLOAD },
#endif
#ifdef RTLD_DEEPBIND
{ "RTLD_DEEPBIND", RTLD_DEEPBIND },
#endif
{ NULL, 0 }
};
/************************************************************/
#include "cffi1_module.c"
/************************************************************/
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef FFIBackendModuleDef = {
PyModuleDef_HEAD_INIT,
"_cffi_backend",
NULL,
-1,
FFIBackendMethods,
NULL, NULL, NULL, NULL
};
#define INITERROR return NULL
PyMODINIT_FUNC
PyInit__cffi_backend(void)
#else
#define INITERROR return
PyMODINIT_FUNC
init_cffi_backend(void)
#endif
{
PyObject *m, *v;
int i;
static char init_done = 0;
static PyTypeObject *all_types[] = {
&dl_type,
&CTypeDescr_Type,
&CField_Type,
&CData_Type,
&CDataOwning_Type,
&CDataOwningGC_Type,
&CDataFromBuf_Type,
&CDataGCP_Type,
&CDataIter_Type,
&MiniBuffer_Type,
&FFI_Type,
&Lib_Type,
&GlobSupport_Type,
NULL
};
v = PySys_GetObject("version");
if (v == NULL || !PyText_Check(v) ||
strncmp(PyText_AS_UTF8(v), PY_VERSION, 3) != 0) {
PyErr_Format(PyExc_ImportError,
"this module was compiled for Python %c%c%c",
PY_VERSION[0], PY_VERSION[1], PY_VERSION[2]);
INITERROR;
}
#if PY_MAJOR_VERSION >= 3
m = PyModule_Create(&FFIBackendModuleDef);
#else
m = Py_InitModule("_cffi_backend", FFIBackendMethods);
#endif
if (m == NULL)
INITERROR;
if (unique_cache == NULL) {
unique_cache = PyDict_New();
if (unique_cache == NULL)
INITERROR;
}
/* readify all types and add them to the module */
for (i = 0; all_types[i] != NULL; i++) {
PyTypeObject *tp = all_types[i];
PyObject *tpo = (PyObject *)tp;
if (strncmp(tp->tp_name, "_cffi_backend.", 14) != 0) {
PyErr_Format(PyExc_ImportError,
"'%s' is an ill-formed type name", tp->tp_name);
INITERROR;
}
if (PyType_Ready(tp) < 0)
INITERROR;
Py_INCREF(tpo);
if (PyModule_AddObject(m, tp->tp_name + 14, tpo) < 0)
INITERROR;
}
if (!init_done) {
v = PyText_FromString("_cffi_backend");
if (v == NULL || PyDict_SetItemString(CData_Type.tp_dict,
"__module__", v) < 0)
INITERROR;
v = PyText_FromString("<cdata>");
if (v == NULL || PyDict_SetItemString(CData_Type.tp_dict,
"__name__", v) < 0)
INITERROR;
init_done = 1;
}
/* this is for backward compatibility only */
v = PyCapsule_New((void *)cffi_exports, "cffi", NULL);
if (v == NULL || PyModule_AddObject(m, "_C_API", v) < 0)
INITERROR;
v = PyText_FromString(CFFI_VERSION);
if (v == NULL || PyModule_AddObject(m, "__version__", v) < 0)
INITERROR;
if (PyModule_AddIntConstant(m, "FFI_DEFAULT_ABI", FFI_DEFAULT_ABI) < 0 ||
#if defined(MS_WIN32) && !defined(_WIN64)
PyModule_AddIntConstant(m, "FFI_STDCALL", FFI_STDCALL) < 0 ||
#endif
PyModule_AddIntConstant(m, "FFI_CDECL", FFI_DEFAULT_ABI) < 0 ||
#ifdef MS_WIN32
# ifdef _WIN64
PyModule_AddIntConstant(m, "_WIN", 64) < 0 || /* win64 */
# else
PyModule_AddIntConstant(m, "_WIN", 32) < 0 || /* win32 */
# endif
#endif
0)
INITERROR;
for (i = 0; all_dlopen_flags[i].name != NULL; i++) {
if (PyModule_AddIntConstant(m,
all_dlopen_flags[i].name,
all_dlopen_flags[i].value) < 0)
INITERROR;
}
init_cffi_tls();
if (PyErr_Occurred())
INITERROR;
init_cffi_tls_zombie();
if (PyErr_Occurred())
INITERROR;
if (init_ffi_lib(m) < 0)
INITERROR;
#if PY_MAJOR_VERSION >= 3
if (init_file_emulator() < 0)
INITERROR;
return m;
#endif
}
|