Add wasm32 emscripten support (#763) * added build script * Apply libffi-emscripten patch * Some changes to wasm32/ffi.c * Remove exit(0); from test suites * Fix LONGDOUBLE argument type * Use more macros in ffi.c * Use switch statements instead of if chains * Implemented struct args * Finish struct implementation * Partially working closures * Got closures working (most of closures test suite passes) * Revert changes to test suite * Update .gitignore * Apply code formatter * Use stackSave and stackRestore rather than directly adjusting stack pointer * Add missing break * Fix visibility of ffi_closure_alloc and ffi_closure_free * Fix FFI_TYPE_STRUCT and FFI_TYPE_LONGDOUBLE when WASM_BIGINT is not used sig needs to be vi here for FFI_TYPE_STRUCT and FFI_TYPE_LONGDOUBLE, noticed this while running the test suite without WASM_BIGINT support. * Always use dynCall rather than direct wasmTable lookup (function pointer cast emulation changes dynCall) * Prevent closures.c from duplicating symbols * Try to set up CI * Add test with bigint * Make test methods static * Remove BigInt shorthand because it messes up terser * Add selenium tests * Update tests a bit to try to make CI work * WASM_BIGINT is a linker flag not a compile flag * Finish getting CI working (#1) * update gitignore * Avoid adding "use strict;" to generated JS This should be controlled by -s STRICT_JS in Emscripten. * Make JavaScript ES5 compliant * Remove redundant EXPORTED_RUNTIME_METHODS settings * Fix definition of DEREF_I16 * Avoid marshalling FFI_TYPE_LONGDOUBLE when WASM_BIGINT is not used * Add missing FFI_TYPE_STRUCT signature * Improve test scripts * Remove redundant EXPORTED_RUNTIME_METHODS settings * Add missing EOL * Add struct unpacking tests * Update ci config to try to actually use WASM_BIGINT * Revert "Avoid marshalling FFI_TYPE_LONGDOUBLE when WASM_BIGINT is not used" This reverts commit 61bd5a3e20891623715604581b6e872ab3dfab80. * Fix single_entry_structs tests * Fix return from closure call * Fix 64 bit return from closures * only allocate as much space on stack for return pointer as needed * Revert "only allocate as much space on stack for return pointer as needed" This reverts commit e54a30faea3803e7ac33eed191bde9e573850fc1. * xfail two tests * Fix err_bad_abi test * Remove test logging junk * Try to set up long double marshalling for closures * xfail err_bad_abi * Fix reference errors in previous commit * Add missing argument pointer assignment * Fix signature of function pointer in cls_dbls_struct * Fix longdouble argument * Try some changes to bigint handling * Fix BigInt handling * Fix cls_longdouble test * Fix long double closure arg with no WASM_BIGINT * Use EM_JS to factor out js helpers * Support for varargs closure calls * Fix varargs calls * Fix err_bad_abi test * Fix typo in previous commit * Add more assertions to closures test suite * Fix some asserts * Add assertions to a few more tests * Fix some tests * Fix more floating point assertions * Update more tests * Var args for ffi_call * Don't do node tests * Macro for allocating on stack * Add some comments, simplify struct handling * Try again to fix varargs calls, add comments * Consolidate WASM_BIGINT conditionals into LOAD_U64 and STORE_U64 macros * A bit of cleanup * Fix another typo * Some fixes to the testsuite * Another testsuite fix * Fix varags with closures? * Another attempt at getting closure varargs to work * sig is initialized later * Allow libffi.closures tests to be run * Improve build script * Remove redundant semicolons * Fix a few libffi.closures test failures * Cleanup * Legacy dynCall API is no longer used * Fix FFI_TYPE_LONGDOUBLE offset * xfail 2 tests for WASM - closure_loc_fn0; not applicable -- codeloc doesn't point to closure. - huge_struct; function signature too long. * Revert some redundant dg-output/printf statements Helps Node. * Revert "Don't do node tests" This reverts commit a341ef4b. * Fix assertions in cls_24byte * More tiny formating fixes to test suite * Revert "Revert "Don't do node tests"" This reverts commit 7722e685ea04e2420e042886816d8c4dd31f5dcb. * Fix 64 bit returns when WASM_BIGINT is absent * Fix print statement in cls_24byte * Add CALL_FUNC_PTR macro to allow pyodide to define custom calling behavior to handle fpcast * Update single_entry_structs tests * More explanations * Fix compile error in last commit * Add more support for pyodide fpcast emulation, update CI to try to test it * Clone via https * Fix path to pyodide emsdk_env * Add asserts to the rest of the test suite * Fix test compile errors * Fix some tests * Fix cls_ulonglong * Fix alignment of <4 byte args * fix cls_ulonglong again * Use snprintf instead of sprintf * Should assert than strncmp returned 0 * Fix va_struct1 and va_struct3 * Change double and long double tests These tests are failing because of a strange bug with prinft and doubles, but I am not convinced it necessarily has anything to do with libffi. This version casts the double to int before printing it and avoids the issue * Enable node tests * Revert "Change double and long double tests" This reverts commit 8f3ff89c6577dc99564181cd9974f2f1ba21f1e9. * Fix PYODIDE_FPCAST flag * add conftest.py back in * Fix emcc error: setting `EXPORTED_FUNCTIONS` expects `<class 'list'>` but got `<class 'str'>` See discussion on https://github.com/pyodide/pyodide/pull/1596 * Remove test.html * Remove duplicate test file * More changes from upstream * Fix some whitespace * Add some basic debug logging statements * Reapply libffi.exp changes * Don't build docs (#7) Works around build issue makeinfo: command not found. * Update long double alignment Emscripten 2.0.26 reduces the aligmnet of long double to 8. Quoting from `ChangeLog.md`: > The alignment of `long double`, which is a 128-bit floating-point > value implemented in software, is reduced from 16 to 8. The lower > alignment allows `max_align_t` to properly match the alignment we > use for malloc, which is 8 (raising malloc's alignment to achieve > correctness the other way would come with a performance regression). > (#10072) * Update long double alignment Emscripten 2.0.26 reduces the aligmnet of long double to 8. Quoting from `ChangeLog.md`: > The alignment of `long double`, which is a 128-bit floating-point > value implemented in software, is reduced from 16 to 8. The lower > alignment allows `max_align_t` to properly match the alignment we > use for malloc, which is 8 (raising malloc's alignment to achieve > correctness the other way would come with a performance regression). > (#10072) * Improve error handling a bit (#8) * Fix handling of signed arguments to ffi_call (#11) * Fix struct argument handling in ffi_call (#10) * Remove fpcast emulation tests * Align the stack to MAX_ALIGN before making call (#12) * Increase MAX_ARGS * Cleanup (#14) * Fix Closure compiler error with -sASSERTIONS=1 (#15) * Remove function pointer cast emulation (#13) This reverts commit 593b402 and cbc54da, as it's no longer needed after PR pyodide/pyodide#2019. * Prefer the `__EMSCRIPTEN__` definition over `EMSCRIPTEN` (#18) "The preprocessor define EMSCRIPTEN is deprecated. Don't pass it to code in strict mode. Code should use the define __EMSCRIPTEN__ instead." https://github.com/emscripten-core/emscripten/blob/84a634167a1cd9e8c47d37a559688153a4ceace6/emcc.py#L887-L890 * Install autoconf 2.71 * Try again with installing autoconf 2.71 * Fix compatibility with Emscripten 3.1.28 * CI: remove use of `EM_CONFIG` env See commit: https://github.com/emscripten-core/emsdk/commit/3d87d5ea8143b3636f872fb05b896eb4a19a070b * Fix cls_multi_schar: cast rest_call to signed char * Remove test xfails (#17) * Fix long double when used as a varargs argument * Enable unwindtest and fix it * Add EM_JS_DEPS * Also require convertJsFunctionToWasm * Run tests very very verbose * Echo the .emscripten file * Remove --experimental-wasm-bigint insertion * Build with assertions * Move verbosity flags back out of LDFLAGS * Remove debug print statement * Use up to date pyodide docker image * Explicitly cast res_call to fix test failure * Put back name of main function in cls_longdouble_va.c * Fix alignment The stack pointer apparently needs to be aligned to 16. There were some terrible subtle bugs caused by not respecting this. stackAlloc knows that the stack should be 16 aligned, so we can use stackAlloc(0) to enforce this. This way if alignment requirements change, as long as Emscripten updates stackAlloc to continue to enforce them we should be okay. * Fix handling of systems with no Js bigint integration When we run the node tests we use node v14 tests (since node v14 is vendored with Emscripten). Node v14 has no Js bigint integration unless the --experimental-wasm-bigint flag is passed. So only the node tests really notice if we get this right. Turns out, it didn't work. We can't call a JavaScript function with 64 bit integer arguments without bigint integration. In ffi_call, we are trying to call a wasm function that takes 64 bit integer arguments. dynCall is designed to do this. We need to go back to tracking the signature when we don't have WASM_BIGINT, and then use dynCall. This works better now that emscripten can dynamically fill in extra dynCall wrappers: https://github.com/emscripten-core/emscripten/pull/17328 On the other hand, for the closures we are not getting a function pointer as a first argument. We need to make our own wasm legalizer adaptor that splits 64 bit integer arguments and then calls the JavaScript trampoline, then the JavaScript trampoline reassembles them, calls the closure, then splits the result (if it's a 64 bit integer) and the adaptor puts it back together. * Improvements to emscripten test shell scripts (#21) This fixes the C++ unwinding tests and makes other minor improvements to the Emscripten test shell scripts. * Rename the test folder and move test files into emscripten test folder * Use docker image that has autoconf-2.71 * Cleanup * Pin emscripten 3.1.30 * Fix build.sh path * Rearrange ci pipeline * Fix bpo_38748 test * Cleanup * Improvements to comments, add static asserts, and update copyright * Use `*_js` instead of `*_helper` for EM_JS functions (#22) * Minor code simplification * Xfail first dejagnu test to work around emscripten cache messages See https://github.com/emscripten-core/emscripten/issues/18607 * Remove unneeded xfails * Shorten conftest.py by using pytest-pyodide * Apply formatters and linters to emscripten directory * Fix Emscripten xfail hack * Fix build-tests script * Patch emscripten to quiet info messages * Clean up compiler flags in scripts and remove some settings from circleci config * Rename emscripten quiet script * Add missing export * Don't remove go.exp * Add reference to emscripten logging issue --------- Co-authored-by: Kleis Auke Wolthuizen <info@kleisauke.nl> Co-authored-by: Kleis Auke Wolthuizen <github@kleisauke.nl> Co-authored-by: Christian Heimes <christian@python.org>
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
diff --git a/.circleci/config.yml b/.circleci/config.yml
new file mode 100644
index 0000000..aaf6556
--- /dev/null
+++ b/.circleci/config.yml
@@ -0,0 +1,157 @@
+version: 2.1
+
+defaults: &defaults
+ working_directory: ~/repo
+ docker:
+ # Built from:
+ # https://github.com/pyodide/pyodide/blob/2ab4b0ab6aefe99fd994bb4f9ab086e5c0aebb7b/Dockerfile
+ - image: pyodide/pyodide-env:20230126-chrome109-firefox109-py311
+
+jobs:
+ install-emsdk:
+ <<: *defaults
+ steps:
+ - checkout
+ - run:
+ name: install emsdk
+ command: |
+ git clone https://github.com/emscripten-core/emsdk.git --depth=1
+ cd emsdk
+ ./emsdk install 3.1.30
+ ./emsdk activate 3.1.30
+
+ - persist_to_workspace:
+ root: .
+ paths:
+ - emsdk
+
+ build:
+ parameters:
+ wasm-bigint:
+ description: Should we build with wasm-bigint?
+ type: string
+ default: ""
+ environment:
+ WASM_BIGINT: << parameters.wasm-bigint >>
+ <<: *defaults
+ steps:
+ - checkout
+ - attach_workspace:
+ at: .
+
+ - run:
+ name: build
+ command: |
+ source ./emsdk/emsdk_env.sh
+ ./testsuite/emscripten/build.sh
+
+ - run:
+ name: build tests
+ command: |
+ source ./emsdk/emsdk_env.sh
+ cp -r testsuite/libffi.call testsuite/libffi.call.test
+ cp -r testsuite/libffi.closures testsuite/libffi.closures.test
+ ./testsuite/emscripten/build-tests.sh testsuite/libffi.call.test
+ ./testsuite/emscripten/build-tests.sh testsuite/libffi.closures.test
+
+ - persist_to_workspace:
+ root: .
+ paths:
+ - target
+ - testsuite
+
+ test:
+ parameters:
+ test-params:
+ description: The tests to run.
+ type: string
+ <<: *defaults
+ steps:
+ - checkout
+
+ - attach_workspace:
+ at: .
+
+ - run:
+ name: run tests
+ command: |
+ git reset --hard
+ cd testsuite/emscripten/
+ mkdir test-results
+ pytest \
+ --junitxml=test-results/junit.xml \
+ test_libffi.py \
+ << parameters.test-params >>
+ - store_test_results:
+ path: testsuite/emscripten/test-results
+
+ test-dejagnu:
+ parameters:
+ params:
+ description: Parameters to node-tests
+ type: string
+ default: ""
+
+ <<: *defaults
+ steps:
+ - checkout
+
+ - attach_workspace:
+ at: .
+
+ - run:
+ name: run tests
+ command: |
+ source ./emsdk/emsdk_env.sh
+ python3 testsuite/emscripten/quiet_emcc_info.py
+ testsuite/emscripten/node-tests.sh << parameters.params >>
+
+workflows:
+ version: 2
+ build-and-test:
+ jobs:
+ - install-emsdk
+
+ - build:
+ name: build
+ requires:
+ - install-emsdk
+
+ - build:
+ name: build-bigint
+ wasm-bigint: "true"
+ requires:
+ - install-emsdk
+
+ - test:
+ name: test-firefox
+ test-params: -k firefox
+ requires:
+ - build
+ - test:
+ name: test-chrome
+ test-params: -k chrome
+ requires:
+ - build
+
+ - test:
+ name: test-firefox-bigint
+ test-params: -k firefox
+ requires:
+ - build-bigint
+
+ - test:
+ name: test-chrome-bigint
+ test-params: -k chrome
+ requires:
+ - build-bigint
+
+ - test-dejagnu:
+ name: test-dejagnu
+ requires:
+ - install-emsdk
+ - test-dejagnu:
+ name: test-dejagnu-bigint
+ params: --enable-wasm-bigint
+ requires:
+ - install-emsdk
diff --git a/.gitignore b/.gitignore
index f33ca3d..dea0b1b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,6 +2,10 @@
.deps
*.o
*.lo
+*.wasm
+*.js
+*.test
+*.log
.dirstamp
*.la
Makefile
@@ -35,3 +39,8 @@ build_*/
darwin_*/
src/arm/trampoline.S
**/texinfo.tex
+target/
+__pycache__
+.docker_home
+emsdk
+test-results
diff --git a/Makefile.am b/Makefile.am
index fde7ec2..3de0bea 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -62,6 +62,7 @@ noinst_HEADERS = src/aarch64/ffitarget.h src/aarch64/internal.h \
src/s390/ffitarget.h src/s390/internal.h src/sh/ffitarget.h \
src/sh64/ffitarget.h src/sparc/ffitarget.h \
src/sparc/internal.h src/tile/ffitarget.h src/vax/ffitarget.h \
+ src/wasm32/ffitarget.h \
src/x86/ffitarget.h src/x86/internal.h src/x86/internal64.h \
src/x86/asmnames.h src/xtensa/ffitarget.h src/dlmalloc.c \
src/kvx/ffitarget.h src/kvx/asm.h \
@@ -92,6 +93,7 @@ EXTRA_libffi_la_SOURCES = src/aarch64/ffi.c src/aarch64/sysv.S \
src/sh64/sysv.S src/sparc/ffi.c src/sparc/ffi64.c \
src/sparc/v8.S src/sparc/v9.S src/tile/ffi.c src/tile/tile.S \
src/vax/ffi.c src/vax/elfbsd.S src/x86/ffi.c src/x86/sysv.S \
+ src/wasm32/ffi.c \
src/x86/ffiw64.c src/x86/win64.S src/x86/ffi64.c \
src/x86/unix64.S src/x86/sysv_intel.S src/x86/win64_intel.S \
src/xtensa/ffi.c src/xtensa/sysv.S src/kvx/ffi.c \
diff --git a/configure.host b/configure.host
index a4ca511..b291bd0 100644
--- a/configure.host
+++ b/configure.host
@@ -265,6 +265,11 @@ case "${host}" in
SOURCES="ffi.c elfbsd.S"
;;
+ wasm32-*-*)
+ TARGET=wasm32; TARGETDIR=wasm32
+ SOURCES="ffi.c"
+ ;;
+
xtensa*-*)
TARGET=XTENSA; TARGETDIR=xtensa
SOURCES="ffi.c sysv.S"
diff --git a/src/closures.c b/src/closures.c
index 5c43313..0f2d619 100644
--- a/src/closures.c
+++ b/src/closures.c
@@ -31,6 +31,8 @@
#define _GNU_SOURCE 1
#endif
+#ifndef __EMSCRIPTEN__
+
#include <fficonfig.h>
#include <ffi.h>
#include <ffi_common.h>
@@ -1102,3 +1104,4 @@ ffi_tramp_is_present (__attribute__((unused)) void *ptr)
#endif /* FFI_CLOSURES */
#endif /* NetBSD with PROT_MPROTECT */
+#endif /* __EMSCRIPTEN__ */
diff --git a/src/wasm32/ffi.c b/src/wasm32/ffi.c
new file mode 100644
index 0000000..399a06e
--- /dev/null
+++ b/src/wasm32/ffi.c
@@ -0,0 +1,934 @@
+/* -----------------------------------------------------------------------
+ ffi.c - Copyright (c) 2018-2023 Hood Chatham, Brion Vibber, Kleis Auke Wolthuizen, and others.
+
+ wasm32/emscripten Foreign Function Interface
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+ ----------------------------------------------------------------------- */
+
+#include <ffi.h>
+#include <ffi_common.h>
+
+#include <stdlib.h>
+#include <stdint.h>
+
+#include <emscripten/emscripten.h>
+
+#ifdef DEBUG_F
+#define LOG_DEBUG(args...) \
+ console.warn(`====LIBFFI(line __LINE__)`, args)
+#else
+#define LOG_DEBUG(args...) 0
+#endif
+
+#define EM_JS_MACROS(ret, name, args, body...) EM_JS(ret, name, args, body)
+
+#if WASM_BIGINT
+EM_JS_DEPS(libffi, "$getWasmTableEntry,$setWasmTableEntry,$getEmptyTableSlot,$convertJsFunctionToWasm");
+#define CALL_FUNCTION_POINTER(ptr, args...) \
+ (LOG_DEBUG("CALL_FUNC_PTR", ptr, args), \
+ getWasmTableEntry(ptr).apply(null, args))
+
+#define JS_FUNCTION_TO_WASM convertJsFunctionToWasm
+#else
+EM_JS_DEPS(libffi, "$getWasmTableEntry,$setWasmTableEntry,$getEmptyTableSlot,$convertJsFunctionToWasm,$dynCall,$generateFuncType,$uleb128Encode");
+#define CALL_FUNCTION_POINTER(ptr, args...) \
+ (LOG_DEBUG("CALL_FUNC_PTR", sig, ptr, args), \
+ dynCall(sig, ptr, args))
+
+#define JS_FUNCTION_TO_WASM createLegalizerWrapper
+#endif
+
+// Signature calculations are not needed if WASM_BIGINT is present.
+#if WASM_BIGINT
+#define SIG(sig)
+#else
+#define SIG(sig) sig
+#endif
+
+#define DEREF_U8(addr, offset) HEAPU8[addr + offset]
+#define DEREF_S8(addr, offset) HEAP8[addr + offset]
+#define DEREF_U16(addr, offset) HEAPU16[(addr >> 1) + offset]
+#define DEREF_S16(addr, offset) HEAP16[(addr >> 1) + offset]
+#define DEREF_U32(addr, offset) HEAPU32[(addr >> 2) + offset]
+#define DEREF_S32(addr, offset) HEAP32[(addr >> 2) + offset]
+
+#define DEREF_F32(addr, offset) HEAPF32[(addr >> 2) + offset]
+#define DEREF_F64(addr, offset) HEAPF64[(addr >> 3) + offset]
+
+#if WASM_BIGINT
+// We have HEAPU64 in this case.
+#define DEREF_U64(addr, offset) HEAPU64[(addr >> 3) + offset]
+#endif
+
+
+#define CHECK_FIELD_OFFSET(struct, field, offset) \
+ _Static_assert( \
+ offsetof(struct, field) == offset, \
+ "Memory layout of '" #struct "' has changed: '" #field "' is in an unexpected location");
+
+CHECK_FIELD_OFFSET(ffi_cif, abi, 4*0);
+CHECK_FIELD_OFFSET(ffi_cif, nargs, 4*1);
+CHECK_FIELD_OFFSET(ffi_cif, arg_types, 4*2);
+CHECK_FIELD_OFFSET(ffi_cif, rtype, 4*3);
+CHECK_FIELD_OFFSET(ffi_cif, nfixedargs, 4*6);
+
+#define CIF__ABI(addr) DEREF_U32(addr, 0)
+#define CIF__NARGS(addr) DEREF_U32(addr, 1)
+#define CIF__ARGTYPES(addr) DEREF_U32(addr, 2)
+#define CIF__RTYPE(addr) DEREF_U32(addr, 3)
+#define CIF__NFIXEDARGS(addr) DEREF_U32(addr, 6)
+
+CHECK_FIELD_OFFSET(ffi_type, size, 0);
+CHECK_FIELD_OFFSET(ffi_type, alignment, 4);
+CHECK_FIELD_OFFSET(ffi_type, type, 6);
+CHECK_FIELD_OFFSET(ffi_type, elements, 8);
+
+#define FFI_TYPE__SIZE(addr) DEREF_U32(addr, 0)
+#define FFI_TYPE__ALIGN(addr) DEREF_U16(addr + 4, 0)
+#define FFI_TYPE__TYPEID(addr) DEREF_U16(addr + 6, 0)
+#define FFI_TYPE__ELEMENTS(addr) DEREF_U32(addr + 8, 0)
+
+#define ALIGN_ADDRESS(addr, align) (addr &= (~((align) - 1)))
+#define STACK_ALLOC(stack, size, align) ((stack -= (size)), ALIGN_ADDRESS(stack, align))
+
+// Most wasm runtimes support at most 1000 Js trampoline args.
+#define MAX_ARGS 1000
+
+#include <stddef.h>
+
+#define VARARGS_FLAG 1
+
+#define FFI_OK_MACRO 0
+_Static_assert(FFI_OK_MACRO == FFI_OK, "FFI_OK must be 0");
+
+#define FFI_BAD_TYPEDEF_MACRO 1
+_Static_assert(FFI_BAD_TYPEDEF_MACRO == FFI_BAD_TYPEDEF, "FFI_BAD_TYPEDEF must be 1");
+
+ffi_status FFI_HIDDEN
+ffi_prep_cif_machdep(ffi_cif *cif)
+{
+ if (cif->abi != FFI_WASM32_EMSCRIPTEN)
+ return FFI_BAD_ABI;
+ // This is called after ffi_prep_cif_machdep_var so we need to avoid
+ // overwriting cif->nfixedargs.
+ if (!(cif->flags & VARARGS_FLAG))
+ cif->nfixedargs = cif->nargs;
+ if (cif->nargs > MAX_ARGS)
+ return FFI_BAD_TYPEDEF;
+ if (cif->rtype->type == FFI_TYPE_COMPLEX)
+ return FFI_BAD_TYPEDEF;
+ // If they put the COMPLEX type into a struct we won't notice, but whatever.
+ for (int i = 0; i < cif->nargs; i++)
+ if (cif->arg_types[i]->type == FFI_TYPE_COMPLEX)
+ return FFI_BAD_TYPEDEF;
+ return FFI_OK;
+}
+
+ffi_status FFI_HIDDEN
+ffi_prep_cif_machdep_var(ffi_cif *cif, unsigned nfixedargs, unsigned ntotalargs)
+{
+ cif->flags |= VARARGS_FLAG;
+ cif->nfixedargs = nfixedargs;
+ // The varargs takes up one extra argument
+ if (cif->nfixedargs + 1 > MAX_ARGS)
+ return FFI_BAD_TYPEDEF;
+ return FFI_OK;
+}
+
+/**
+ * A Javascript helper function. This takes an argument typ which is a wasm
+ * pointer to an ffi_type object. It returns a pair a type and a type id.
+ *
+ * - If it is not a struct, return its type and its typeid field.
+ * - If it is a struct of size >= 2, return the type and its typeid (which
+ * will be FFI_TYPE_STRUCT)
+ * - If it is a struct of size 0, return FFI_TYPE_VOID (????? this is broken)
+ * - If it is a struct of size 1, replace it with the single field and apply
+ * the same logic again to that.
+ *
+ * By always unboxing structs up front, we can avoid messy casework later.
+ */
+EM_JS_MACROS(
+void,
+unbox_small_structs, (ffi_type type_ptr), {
+ var type_id = FFI_TYPE__TYPEID(type_ptr);
+ while (type_id === FFI_TYPE_STRUCT) {
+ var elements = FFI_TYPE__ELEMENTS(type_ptr);
+ var first_element = DEREF_U32(elements, 0);
+ if (first_element === 0) {
+ type_id = FFI_TYPE_VOID;
+ break;
+ } else if (DEREF_U32(elements, 1) === 0) {
+ type_ptr = first_element;
+ type_id = FFI_TYPE__TYPEID(first_element);
+ } else {
+ break;
+ }
+ }
+ return [type_ptr, type_id];
+})
+
+EM_JS_MACROS(
+void,
+ffi_call_js, (ffi_cif *cif, ffi_fp fn, void *rvalue, void **avalue),
+{
+ var abi = CIF__ABI(cif);
+ var nargs = CIF__NARGS(cif);
+ var nfixedargs = CIF__NFIXEDARGS(cif);
+ var arg_types_ptr = CIF__ARGTYPES(cif);
+ var rtype_unboxed = unbox_small_structs(CIF__RTYPE(cif));
+ var rtype_ptr = rtype_unboxed[0];
+ var rtype_id = rtype_unboxed[1];
+ var orig_stack_ptr = stackSave();
+ var cur_stack_ptr = orig_stack_ptr;
+
+ var args = [];
+ // Does our onwards call return by argument or normally? We return by argument
+ // no matter what.
+ var ret_by_arg = false;
+
+ if (rtype_id === FFI_TYPE_COMPLEX) {
+ throw new Error('complex ret marshalling nyi');
+ }
+ if (rtype_id < 0 || rtype_id > FFI_TYPE_LAST) {
+ throw new Error('Unexpected rtype ' + rtype_id);
+ }
+ // If the return type is a struct with multiple entries or a long double, the
+ // function takes an extra first argument which is a pointer to return value.
+ // Conveniently, we've already received a pointer to return value, so we can
+ // just use this. We also mark a flag that we don't need to convert the return
+ // value of the dynamic call back to C.
+ if (rtype_id === FFI_TYPE_LONGDOUBLE || rtype_id === FFI_TYPE_STRUCT) {
+ args.push(rvalue);
+ ret_by_arg = true;
+ }
+
+ SIG(var sig = "");
+
+#if !WASM_BIGINT
+ switch(rtype_id) {
+ case FFI_TYPE_VOID:
+ SIG(sig = 'v');
+ break;
+ case FFI_TYPE_STRUCT:
+ case FFI_TYPE_LONGDOUBLE:
+ SIG(sig = 'vi');
+ break;
+ case FFI_TYPE_INT:
+ case FFI_TYPE_UINT8:
+ case FFI_TYPE_SINT8:
+ case FFI_TYPE_UINT16:
+ case FFI_TYPE_SINT16:
+ case FFI_TYPE_UINT32:
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_POINTER:
+ SIG(sig = 'i');
+ break;
+ case FFI_TYPE_FLOAT:
+ SIG(sig = 'f');
+ break;
+ case FFI_TYPE_DOUBLE:
+ SIG(sig = 'd');
+ break;
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+ SIG(sig = 'j');
+ break;
+ }
+#endif
+
+ // Accumulate a Javascript list of arguments for the Javascript wrapper for
+ // the wasm function. The Javascript wrapper does a type conversion from
+ // Javascript to C automatically, here we manually do the inverse conversion
+ // from C to Javascript.
+ for (var i = 0; i < nfixedargs; i++) {
+ var arg_ptr = DEREF_U32(avalue, i);
+ var arg_unboxed = unbox_small_structs(DEREF_U32(arg_types_ptr, i));
+ var arg_type_ptr = arg_unboxed[0];
+ var arg_type_id = arg_unboxed[1];
+
+ // It's okay here to always use unsigned integers as long as the size is 32
+ // or 64 bits. Smaller sizes get extended to 32 bits differently according
+ // to whether they are signed or unsigned.
+ switch (arg_type_id) {
+ case FFI_TYPE_INT:
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_UINT32:
+ case FFI_TYPE_POINTER:
+ args.push(DEREF_U32(arg_ptr, 0));
+ SIG(sig += 'i');
+ break;
+ case FFI_TYPE_FLOAT:
+ args.push(DEREF_F32(arg_ptr, 0));
+ SIG(sig += 'f');
+ break;
+ case FFI_TYPE_DOUBLE:
+ args.push(DEREF_F64(arg_ptr, 0));
+ SIG(sig += 'd');
+ break;
+ case FFI_TYPE_UINT8:
+ args.push(DEREF_U8(arg_ptr, 0));
+ SIG(sig += 'i');
+ break;
+ case FFI_TYPE_SINT8:
+ args.push(DEREF_S8(arg_ptr, 0));
+ SIG(sig += 'i');
+ break;
+ case FFI_TYPE_UINT16:
+ args.push(DEREF_U16(arg_ptr, 0));
+ SIG(sig += 'i');
+ break;
+ case FFI_TYPE_SINT16:
+ args.push(DEREF_S16(arg_ptr, 0));
+ SIG(sig += 'i');
+ break;
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+ #if WASM_BIGINT
+ args.push(DEREF_U64(arg_ptr, 0));
+ #else
+ args.push(DEREF_U32(arg_ptr, 0));
+ args.push(DEREF_U32(arg_ptr, 1));
+ #endif
+ SIG(sig += 'j');
+ break;
+ case FFI_TYPE_LONGDOUBLE:
+ // long double is passed as a pair of BigInts.
+ #if WASM_BIGINT
+ args.push(DEREF_U64(arg_ptr, 0));
+ args.push(DEREF_U64(arg_ptr, 1));
+ #else
+ args.push(DEREF_U32(arg_ptr, 0));
+ args.push(DEREF_U32(arg_ptr, 1));
+ args.push(DEREF_U32(arg_ptr, 2));
+ args.push(DEREF_U32(arg_ptr, 3));
+ #endif
+ SIG(sig += "jj");
+ break;
+ case FFI_TYPE_STRUCT:
+ // Nontrivial structs are passed by pointer.
+ // Have to copy the struct onto the stack though because C ABI says it's
+ // call by value.
+ var size = FFI_TYPE__SIZE(arg_type_ptr);
+ var align = FFI_TYPE__ALIGN(arg_type_ptr);
+ STACK_ALLOC(cur_stack_ptr, size, align);
+ HEAP8.subarray(cur_stack_ptr, cur_stack_ptr+size).set(HEAP8.subarray(arg_ptr, arg_ptr + size));
+ args.push(cur_stack_ptr);
+ SIG(sig += 'i');
+ break;
+ case FFI_TYPE_COMPLEX:
+ throw new Error('complex marshalling nyi');
+ default:
+ throw new Error('Unexpected type ' + arg_type_id);
+ }
+ }
+
+ // Wasm functions can't directly manipulate the callstack, so varargs
+ // arguments have to go on a separate stack. A varags function takes one extra
+ // argument which is a pointer to where on the separate stack the args are
+ // located. Because stacks are allocated backwards, we have to loop over the
+ // varargs backwards.
+ //
+ // We don't have any way of knowing how many args were actually passed, so we
+ // just always copy extra nonsense past the end. The ownwards call will know
+ // not to look at it.
+ if (nfixedargs != nargs) {
+ SIG(sig += 'i');
+ var struct_arg_info = [];
+ for (var i = nargs - 1; i >= nfixedargs; i--) {
+ var arg_ptr = DEREF_U32(avalue, i);
+ var arg_unboxed = unbox_small_structs(DEREF_U32(arg_types_ptr, i));
+ var arg_type_ptr = arg_unboxed[0];
+ var arg_type_id = arg_unboxed[1];
+ switch (arg_type_id) {
+ case FFI_TYPE_UINT8:
+ case FFI_TYPE_SINT8:
+ STACK_ALLOC(cur_stack_ptr, 1, 1);
+ DEREF_U8(cur_stack_ptr, 0) = DEREF_U8(arg_ptr, 0);
+ break;
+ case FFI_TYPE_UINT16:
+ case FFI_TYPE_SINT16:
+ STACK_ALLOC(cur_stack_ptr, 2, 2);
+ DEREF_U16(cur_stack_ptr, 0) = DEREF_U16(arg_ptr, 0);
+ break;
+ case FFI_TYPE_INT:
+ case FFI_TYPE_UINT32:
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_POINTER:
+ case FFI_TYPE_FLOAT:
+ STACK_ALLOC(cur_stack_ptr, 4, 4);
+ DEREF_U32(cur_stack_ptr, 0) = DEREF_U32(arg_ptr, 0);
+ break;
+ case FFI_TYPE_DOUBLE:
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+ STACK_ALLOC(cur_stack_ptr, 8, 8);
+ DEREF_U32(cur_stack_ptr, 0) = DEREF_U32(arg_ptr, 0);
+ DEREF_U32(cur_stack_ptr, 1) = DEREF_U32(arg_ptr, 1);
+ break;
+ case FFI_TYPE_LONGDOUBLE:
+ STACK_ALLOC(cur_stack_ptr, 16, 8);
+ DEREF_U32(cur_stack_ptr, 0) = DEREF_U32(arg_ptr, 0);
+ DEREF_U32(cur_stack_ptr, 1) = DEREF_U32(arg_ptr, 1);
+ DEREF_U32(cur_stack_ptr, 2) = DEREF_U32(arg_ptr, 2);
+ DEREF_U32(cur_stack_ptr, 3) = DEREF_U32(arg_ptr, 3);
+ break;
+ case FFI_TYPE_STRUCT:
+ // Again, struct must be passed by pointer.
+ // But ABI is by value, so have to copy struct onto stack.
+ // Currently arguments are going onto stack so we can't put it there now. Come back for this.
+ STACK_ALLOC(cur_stack_ptr, 4, 4);
+ struct_arg_info.push([cur_stack_ptr, arg_ptr, FFI_TYPE__SIZE(arg_type_ptr), FFI_TYPE__ALIGN(arg_type_ptr)]);
+ break;
+ case FFI_TYPE_COMPLEX:
+ throw new Error('complex arg marshalling nyi');
+ default:
+ throw new Error('Unexpected argtype ' + arg_type_id);
+ }
+ }
+ // extra normal argument which is the pointer to the varargs.
+ args.push(cur_stack_ptr);
+ // Now allocate variable struct args on stack too.
+ for (var i = 0; i < struct_arg_info.length; i++) {
+ var struct_info = struct_arg_info[i];
+ var arg_target = struct_info[0];
+ var arg_ptr = struct_info[1];
+ var size = struct_info[2];
+ var align = struct_info[3];
+ STACK_ALLOC(cur_stack_ptr, size, align);
+ HEAP8.subarray(cur_stack_ptr, cur_stack_ptr+size).set(HEAP8.subarray(arg_ptr, arg_ptr + size));
+ DEREF_U32(arg_target, 0) = cur_stack_ptr;
+ }
+ }
+ stackRestore(cur_stack_ptr);
+ stackAlloc(0); // stackAlloc enforces alignment invariants on the stack pointer
+ var result = CALL_FUNCTION_POINTER(fn, args);
+ // Put the stack pointer back (we moved it if there were any struct args or we
+ // made a varargs call)
+ stackRestore(orig_stack_ptr);
+
+ // We need to return by argument. If return value was a nontrivial struct or
+ // long double, the onwards call already put the return value in rvalue
+ if (ret_by_arg) {
+ return;
+ }
+
+ // Otherwise the result was automatically converted from C into Javascript and
+ // we need to manually convert it back to C.
+ switch (rtype_id) {
+ case FFI_TYPE_VOID:
+ break;
+ case FFI_TYPE_INT:
+ case FFI_TYPE_UINT32:
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_POINTER:
+ DEREF_U32(rvalue, 0) = result;
+ break;
+ case FFI_TYPE_FLOAT:
+ DEREF_F32(rvalue, 0) = result;
+ break;
+ case FFI_TYPE_DOUBLE:
+ DEREF_F64(rvalue, 0) = result;
+ break;
+ case FFI_TYPE_UINT8:
+ case FFI_TYPE_SINT8:
+ DEREF_U8(rvalue, 0) = result;
+ break;
+ case FFI_TYPE_UINT16:
+ case FFI_TYPE_SINT16:
+ DEREF_U16(rvalue, 0) = result;
+ break;
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+ #if WASM_BIGINT
+ DEREF_U64(rvalue, 0) = result;
+ #else
+ DEREF_U32(rvalue, 0) = result;
+ DEREF_U32(rvalue, 1) = getTempRet0();
+ #endif
+ break;
+ case FFI_TYPE_COMPLEX:
+ throw new Error('complex ret marshalling nyi');
+ default:
+ throw new Error('Unexpected rtype ' + rtype_id);
+ }
+});
+
+void ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) {
+ ffi_call_js(cif, fn, rvalue, avalue);
+}
+
+CHECK_FIELD_OFFSET(ffi_closure, ftramp, 4*0);
+CHECK_FIELD_OFFSET(ffi_closure, cif, 4*1);
+CHECK_FIELD_OFFSET(ffi_closure, fun, 4*2);
+CHECK_FIELD_OFFSET(ffi_closure, user_data, 4*3);
+
+#define CLOSURE__wrapper(addr) DEREF_U32(addr, 0)
+#define CLOSURE__cif(addr) DEREF_U32(addr, 1)
+#define CLOSURE__fun(addr) DEREF_U32(addr, 2)
+#define CLOSURE__user_data(addr) DEREF_U32(addr, 3)
+
+EM_JS_MACROS(void *, ffi_closure_alloc_js, (size_t size, void **code), {
+ var closure = _malloc(size);
+ var index = getEmptyTableSlot();
+ DEREF_U32(code, 0) = index;
+ CLOSURE__wrapper(closure) = index;
+ return closure;
+})
+
+void * __attribute__ ((visibility ("default")))
+ffi_closure_alloc(size_t size, void **code) {
+ return ffi_closure_alloc_js(size, code);
+}
+
+EM_JS_MACROS(void, ffi_closure_free_js, (void *closure), {
+ var index = CLOSURE__wrapper(closure);
+ freeTableIndexes.push(index);
+ _free(closure);
+})
+
+void __attribute__ ((visibility ("default")))
+ffi_closure_free(void *closure) {
+ return ffi_closure_free_js(closure);
+}
+
+#if !WASM_BIGINT
+
+// When !WASM_BIGINT, we assume there is no JS bigint integration, so JavaScript
+// functions cannot take 64 bit integer arguments.
+//
+// We need to make our own wasm legalizer adaptor that splits 64 bit integer
+// arguments and then calls the JavaScript trampoline, then the JavaScript
+// trampoline reassembles them, calls the closure, then splits the result (if
+// it's a 64 bit integer) and the adaptor puts it back together.
+//
+// This is basically the reverse of the Emscripten function
+// createDyncallWrapper.
+EM_JS(void, createLegalizerWrapper, (int trampoline, int sig), {
+ if(!sig.includes("j")) {
+ return convertJsFunctionToWasm(trampoline, sig);
+ }
+ var sections = [];
+ var prelude = [
+ 0x00, 0x61, 0x73, 0x6d, // magic ("\0asm")
+ 0x01, 0x00, 0x00, 0x00, // version: 1
+ ];
+ sections.push(prelude);
+ var wrappersig = [
+ // if return type is j, we will put the upper 32 bits into tempRet0.
+ sig[0].replace("j", "i"),
+ // in the rest of the argument list, one 64 bit integer is legalized into
+ // two 32 bit integers.
+ sig.slice(1).replace(/j/g, "ii"),
+ ].join("");
+
+ var typeSectionBody = [
+ 0x03, // number of types = 3
+ ];
+ generateFuncType(wrappersig, typeSectionBody); // The signature of the wrapper we are generating
+ generateFuncType(sig, typeSectionBody); // the signature of the function pointer we will call
+ generateFuncType("i", typeSectionBody); // the signature of getTempRet0
+
+ var typeSection = [0x01 /* Type section code */];
+ uleb128Encode(typeSectionBody.length, typeSection); // length of section in bytes
+ typeSection.push.apply(typeSection, typeSectionBody);
+ sections.push(typeSection);
+
+ var importSection = [
+ 0x02, // import section code
+ 0x0d, // length of section in bytes
+ 0x02, // number of imports = 2
+ // Import the getTempRet0 function, which we will call "r"
+ 0x01, 0x65, // name "e"
+ 0x01, 0x72, // name "r"
+ 0x00, // importing a function
+ 0x02, // type 2 = () -> i32
+ // Import the wrapped function, which we will call "f"
+ 0x01, 0x65, // name "e"
+ 0x01, 0x66, // name "f"
+ 0x00, // importing a function
+ 0x00, // type 0 = wrappersig
+ ];
+ sections.push(importSection);
+
+ var functionSection = [
+ 0x03, // function section code
+ 0x02, // length of section in bytes
+ 0x01, // number of functions = 1
+ 0x01, // type 1 = sig
+ ];
+ sections.push(functionSection);
+
+ var exportSection = [
+ 0x07, // export section code
+ 0x05, // length of section in bytes
+ 0x01, // One export
+ 0x01, 0x66, // name "f"
+ 0x00, // type: function
+ 0x02, // function index 2 = the wrapper function
+ ];
+ sections.push(exportSection);
+
+ var convert_code = [];
+ convert_code.push(0x00); // no local variables (except the arguments)
+
+ function localGet(j) {
+ convert_code.push(0x20); // local.get
+ uleb128Encode(j, convert_code);
+ }
+
+ for (var i = 1; i < sig.length; i++) {
+ if (sig[i] == "j") {
+ localGet(i - 1);
+ convert_code.push(
+ 0xa7 // i32.wrap_i64
+ );
+ localGet(i - 1);
+ convert_code.push(
+ 0x42, 0x20, // i64.const 32
+ 0x88, // i64.shr_u
+ 0xa7 // i32.wrap_i64
+ );
+ } else {
+ localGet(i - 1);
+ }
+ }
+ convert_code.push(
+ 0x10, 0x01 // call f
+ );
+ if (sig[0] === "j") {
+ // Need to reassemble a 64 bit integer. Lower 32 bits is on stack. Upper 32
+ // bits we get from getTempRet0
+ convert_code.push(
+ 0xad, // i64.extend_i32_unsigned
+ 0x10, 0x00, // Call function 0 (r = getTempRet0)
+ // join lower 32 bits and upper 32 bits
+ 0xac, // i64.extend_i32_signed
+ 0x42, 0x20, // i64.const 32
+ 0x86, // i64.shl,
+ 0x84 // i64.or
+ );
+ }
+ convert_code.push(0x0b); // end
+
+ var codeBody = [0x01]; // one code
+ uleb128Encode(convert_code.length, codeBody);
+ codeBody.push.apply(codeBody, convert_code);
+ var codeSection = [0x0a /* Code section code */];
+ uleb128Encode(codeBody.length, codeSection);
+ codeSection.push.apply(codeSection, codeBody);
+ sections.push(codeSection);
+
+ var bytes = new Uint8Array([].concat.apply([], sections));
+ // We can compile this wasm module synchronously because it is small.
+ var module = new WebAssembly.Module(bytes);
+ var instance = new WebAssembly.Instance(module, {
+ e: {
+ r: getTempRet0,
+ f: trampoline,
+ },
+ });
+ return instance.exports.f;
+});
+#endif
+
+EM_JS_MACROS(
+ffi_status,
+ffi_prep_closure_loc_js,
+(ffi_closure *closure, ffi_cif *cif, void *fun, void *user_data, void *codeloc),
+{
+ var abi = CIF__ABI(cif);
+ var nargs = CIF__NARGS(cif);
+ var nfixedargs = CIF__NFIXEDARGS(cif);
+ var arg_types_ptr = CIF__ARGTYPES(cif);
+ var rtype_unboxed = unbox_small_structs(CIF__RTYPE(cif));
+ var rtype_ptr = rtype_unboxed[0];
+ var rtype_id = rtype_unboxed[1];
+
+ // First construct the signature of the javascript trampoline we are going to create.
+ // Important: this is the signature for calling us, the onward call always has sig viiii.
+ var sig;
+ var ret_by_arg = false;
+ switch (rtype_id) {
+ case FFI_TYPE_VOID:
+ sig = 'v';
+ break;
+ case FFI_TYPE_STRUCT:
+ case FFI_TYPE_LONGDOUBLE:
+ // Return via a first pointer argument.
+ sig = 'vi';
+ ret_by_arg = true;
+ break;
+ case FFI_TYPE_INT:
+ case FFI_TYPE_UINT8:
+ case FFI_TYPE_SINT8:
+ case FFI_TYPE_UINT16:
+ case FFI_TYPE_SINT16:
+ case FFI_TYPE_UINT32:
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_POINTER:
+ sig = 'i';
+ break;
+ case FFI_TYPE_FLOAT:
+ sig = 'f';
+ break;
+ case FFI_TYPE_DOUBLE:
+ sig = 'd';
+ break;
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+ sig = 'j';
+ break;
+ case FFI_TYPE_COMPLEX:
+ throw new Error('complex ret marshalling nyi');
+ default:
+ throw new Error('Unexpected rtype ' + rtype_id);
+ }
+ var unboxed_arg_type_id_list = [];
+ var unboxed_arg_type_info_list = [];
+ for (var i = 0; i < nargs; i++) {
+ var arg_unboxed = unbox_small_structs(DEREF_U32(arg_types_ptr, i));
+ var arg_type_ptr = arg_unboxed[0];
+ var arg_type_id = arg_unboxed[1];
+ unboxed_arg_type_id_list.push(arg_type_id);
+ unboxed_arg_type_info_list.push([FFI_TYPE__SIZE(arg_type_ptr), FFI_TYPE__ALIGN(arg_type_ptr)]);
+ }
+ for (var i = 0; i < nfixedargs; i++) {
+ switch (unboxed_arg_type_id_list[i]) {
+ case FFI_TYPE_INT:
+ case FFI_TYPE_UINT8:
+ case FFI_TYPE_SINT8:
+ case FFI_TYPE_UINT16:
+ case FFI_TYPE_SINT16:
+ case FFI_TYPE_UINT32:
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_POINTER:
+ case FFI_TYPE_STRUCT:
+ sig += 'i';
+ break;
+ case FFI_TYPE_FLOAT:
+ sig += 'f';
+ break;
+ case FFI_TYPE_DOUBLE:
+ sig += 'd';
+ break;
+ case FFI_TYPE_LONGDOUBLE:
+ sig += 'jj';
+ break;
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+ sig += 'j';
+ break;
+ case FFI_TYPE_COMPLEX:
+ throw new Error('complex marshalling nyi');
+ default:
+ throw new Error('Unexpected argtype ' + arg_type_id);
+ }
+ }
+ if (nfixedargs < nargs) {
+ // extra pointer to varargs stack
+ sig += "i";
+ }
+ LOG_DEBUG("CREATE_CLOSURE", "sig:", sig);
+ function trampoline() {
+ var args = Array.prototype.slice.call(arguments);
+ var size = 0;
+ var orig_stack_ptr = stackSave();
+ var cur_ptr = orig_stack_ptr;
+ var ret_ptr;
+ var jsarg_idx = 0;
+ // Should we return by argument or not? The onwards call returns by argument
+ // no matter what. (Warning: ret_by_arg means the opposite in ffi_call)
+ if (ret_by_arg) {
+ ret_ptr = args[jsarg_idx++];
+ } else {
+ // We might return 4 bytes or 8 bytes, allocate 8 just in case.
+ STACK_ALLOC(cur_ptr, 8, 8);
+ ret_ptr = cur_ptr;
+ }
+ cur_ptr -= 4 * nargs;
+ var args_ptr = cur_ptr;
+ var carg_idx = 0;
+ // Here we either have the actual argument, or a pair of BigInts for long
+ // double, or a pointer to struct. We have to store into args_ptr[i] a
+ // pointer to the ith argument. If the argument is a struct, just store the
+ // pointer. Otherwise allocate stack space and copy the js argument onto the
+ // stack.
+ for (; carg_idx < nfixedargs; carg_idx++) {
+ // jsarg_idx might start out as 0 or 1 depending on ret_by_arg
+ // it advances an extra time for long double
+ var cur_arg = args[jsarg_idx++];
+ var arg_type_info = unboxed_arg_type_info_list[carg_idx];
+ var arg_size = arg_type_info[0];
+ var arg_align = arg_type_info[1];
+ var arg_type_id = unboxed_arg_type_id_list[carg_idx];
+ switch (arg_type_id) {
+ case FFI_TYPE_UINT8:
+ case FFI_TYPE_SINT8:
+ // Bad things happen if we don't align to 4 here
+ STACK_ALLOC(cur_ptr, 1, 4);
+ DEREF_U32(args_ptr, carg_idx) = cur_ptr;
+ DEREF_U8(cur_ptr, 0) = cur_arg;
+ break;
+ case FFI_TYPE_UINT16:
+ case FFI_TYPE_SINT16:
+ // Bad things happen if we don't align to 4 here
+ STACK_ALLOC(cur_ptr, 2, 4);
+ DEREF_U32(args_ptr, carg_idx) = cur_ptr;
+ DEREF_U16(cur_ptr, 0) = cur_arg;
+ break;
+ case FFI_TYPE_INT:
+ case FFI_TYPE_UINT32:
+ case FFI_TYPE_SINT32:
+ case FFI_TYPE_POINTER:
+ STACK_ALLOC(cur_ptr, 4, 4);
+ DEREF_U32(args_ptr, carg_idx) = cur_ptr;
+ DEREF_U32(cur_ptr, 0) = cur_arg;
+ break;
+ case FFI_TYPE_STRUCT:
+ // cur_arg is already a pointer to struct
+ // copy it onto stack to pass by value
+ STACK_ALLOC(cur_ptr, arg_size, arg_align);
+ HEAP8.subarray(cur_ptr, cur_ptr + arg_size).set(HEAP8.subarray(cur_arg, cur_arg + arg_size));
+ DEREF_U32(args_ptr, carg_idx) = cur_ptr;
+ break;
+ case FFI_TYPE_FLOAT:
+ STACK_ALLOC(cur_ptr, 4, 4);
+ DEREF_U32(args_ptr, carg_idx) = cur_ptr;
+ DEREF_F32(cur_ptr, 0) = cur_arg;
+ break;
+ case FFI_TYPE_DOUBLE:
+ STACK_ALLOC(cur_ptr, 8, 8);
+ DEREF_U32(args_ptr, carg_idx) = cur_ptr;
+ DEREF_F64(cur_ptr, 0) = cur_arg;
+ break;
+ case FFI_TYPE_UINT64:
+ case FFI_TYPE_SINT64:
+ STACK_ALLOC(cur_ptr, 8, 8);
+ DEREF_U32(args_ptr, carg_idx) = cur_ptr;
+ #if WASM_BIGINT
+ DEREF_U64(cur_ptr, 0) = cur_arg;
+ #else
+ // Bigint arg was split by legalizer adaptor
+ DEREF_U32(cur_ptr, 0) = cur_arg;
+ cur_arg = args[jsarg_idx++];
+ DEREF_U32(cur_ptr, 1) = cur_arg;
+ #endif
+ break;
+ case FFI_TYPE_LONGDOUBLE:
+ STACK_ALLOC(cur_ptr, 16, 8);
+ DEREF_U32(args_ptr, carg_idx) = cur_ptr;
+ #if WASM_BIGINT
+ DEREF_U64(cur_ptr, 0) = cur_arg;
+ cur_arg = args[jsarg_idx++];
+ DEREF_U64(cur_ptr, 1) = cur_arg;
+ #else
+ // Was split by legalizer adaptor
+ DEREF_U32(cur_ptr, 0) = cur_arg;
+ cur_arg = args[jsarg_idx++];
+ DEREF_U32(cur_ptr, 1) = cur_arg;
+ cur_arg = args[jsarg_idx++];
+ DEREF_U32(cur_ptr, 2) = cur_arg;
+ cur_arg = args[jsarg_idx++];
+ DEREF_U32(cur_ptr, 3) = cur_arg;
+ #endif
+ break;
+ }
+ }
+ // If its a varargs call, last js argument is a pointer to the varargs.
+ var varargs = args[args.length - 1];
+ // We have no way of knowing how many varargs were actually provided, this
+ // fills the rest of the stack space allocated with nonsense. The onward
+ // call will know to ignore the nonsense.
+
+ // We either have a pointer to the argument if the argument is not a struct
+ // or a pointer to pointer to struct. We need to store a pointer to the
+ // argument into args_ptr[i]
+ for (; carg_idx < nargs; carg_idx++) {
+ var arg_type_id = unboxed_arg_type_id_list[carg_idx];
+ var arg_type_info = unboxed_arg_type_info_list[carg_idx];
+ var arg_size = arg_type_info[0];
+ var arg_align = arg_type_info[1];
+ if (arg_type_id === FFI_TYPE_STRUCT) {
+ // In this case varargs is a pointer to pointer to struct so we need to
+ // deref once
+ var struct_ptr = DEREF_U32(varargs, 0);
+ STACK_ALLOC(cur_ptr, arg_size, arg_align);
+ HEAP8.subarray(cur_ptr, cur_ptr + arg_size).set(HEAP8.subarray(struct_ptr, struct_ptr + arg_size));
+ DEREF_U32(args_ptr, carg_idx) = cur_ptr;
+ } else {
+ DEREF_U32(args_ptr, carg_idx) = varargs;
+ }
+ varargs += 4;
+ }
+ stackRestore(cur_ptr);
+ stackAlloc(0); // stackAlloc enforces alignment invariants on the stack pointer
+ LOG_DEBUG("CALL_CLOSURE", "closure:", closure, "fptr", CLOSURE__fun(closure), "cif", CLOSURE__cif(closure));
+ getWasmTableEntry(CLOSURE__fun(closure))(
+ CLOSURE__cif(closure), ret_ptr, args_ptr,
+ CLOSURE__user_data(closure)
+ );
+ stackRestore(orig_stack_ptr);
+
+ // If we aren't supposed to return by argument, figure out what to return.
+ if (!ret_by_arg) {
+ switch (sig[0]) {
+ case "i":
+ return DEREF_U32(ret_ptr, 0);
+ case "j":
+ #if WASM_BIGINT
+ return DEREF_U64(ret_ptr, 0);
+ #else
+ // Split the return i64, set the upper 32 bits into tempRet0 and return
+ // the lower 32 bits.
+ setTempRet0(DEREF_U32(ret_ptr, 1));
+ return DEREF_U32(ret_ptr, 0);
+ #endif
+ case "d":
+ return DEREF_F64(ret_ptr, 0);
+ case "f":
+ return DEREF_F32(ret_ptr, 0);
+ }
+ }
+ }
+ try {
+ var wasm_trampoline = JS_FUNCTION_TO_WASM(trampoline, sig);
+ } catch(e) {
+ return FFI_BAD_TYPEDEF_MACRO;
+ }
+ setWasmTableEntry(codeloc, wasm_trampoline);
+ CLOSURE__cif(closure) = cif;
+ CLOSURE__fun(closure) = fun;
+ CLOSURE__user_data(closure) = user_data;
+ return FFI_OK_MACRO;
+})
+
+// EM_JS does not correctly handle function pointer arguments, so we need a
+// helper
+ffi_status ffi_prep_closure_loc(ffi_closure *closure, ffi_cif *cif,
+ void (*fun)(ffi_cif *, void *, void **, void *),
+ void *user_data, void *codeloc) {
+ if (cif->abi != FFI_WASM32_EMSCRIPTEN)
+ return FFI_BAD_ABI;
+ return ffi_prep_closure_loc_js(closure, cif, (void *)fun, user_data,
+ codeloc);
+}
diff --git a/src/wasm32/ffitarget.h b/src/wasm32/ffitarget.h
new file mode 100644
index 0000000..ac78b74
--- /dev/null
+++ b/src/wasm32/ffitarget.h
@@ -0,0 +1,62 @@
+/* -----------------------------------------------------------------*-C-*-
+ ffitarget.h - Copyright (c) 2018-2023 Hood Chatham, Brion Vibber, Kleis Auke Wolthuizen, and others.
+
+ Target configuration macros for wasm32.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ ``Software''), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+ ----------------------------------------------------------------------- */
+
+#ifndef LIBFFI_TARGET_H
+#define LIBFFI_TARGET_H
+
+#ifndef LIBFFI_H
+#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
+#endif
+
+/* ---- Generic type definitions ----------------------------------------- */
+
+typedef unsigned long ffi_arg;
+typedef signed long ffi_sarg;
+
+// TODO: https://github.com/emscripten-core/emscripten/issues/9868
+typedef void (*ffi_fp)(void);
+
+typedef enum ffi_abi {
+ FFI_FIRST_ABI = 0,
+ FFI_WASM32, // "raw", no structures, varargs, or closures (not implemented!)
+ FFI_WASM32_EMSCRIPTEN, // structures, varargs, and split 64-bit params
+ FFI_LAST_ABI,
+#ifdef __EMSCRIPTEN__
+ FFI_DEFAULT_ABI = FFI_WASM32_EMSCRIPTEN
+#else
+ FFI_DEFAULT_ABI = FFI_WASM32
+#endif
+} ffi_abi;
+
+#define FFI_CLOSURES 1
+// #define FFI_GO_CLOSURES 0
+#define FFI_TRAMPOLINE_SIZE 4
+// #define FFI_NATIVE_RAW_API 0
+#define FFI_TARGET_SPECIFIC_VARIADIC 1
+#define FFI_EXTRA_CIF_FIELDS unsigned int nfixedargs
+
+#endif
diff --git a/testsuite/emscripten/build-tests.sh b/testsuite/emscripten/build-tests.sh
new file mode 100755
index 0000000..6b9d5ba
--- /dev/null
+++ b/testsuite/emscripten/build-tests.sh
@@ -0,0 +1,40 @@
+#!/usr/bin/env bash
+emcc_exists="$(command -v emcc)"
+if [ ! "${emcc_exists}" ]; then
+ echo "Emscripten not on path"
+ exit 1
+fi
+
+set -e
+
+cd "$1"
+export CFLAGS="-fPIC -O2 -I../../target/include $EXTRA_CFLAGS"
+export CXXFLAGS="$CFLAGS -sNO_DISABLE_EXCEPTION_CATCHING $EXTRA_CXXFLAGS"
+export LDFLAGS=" \
+ -L../../target/lib/ -lffi \
+ -sEXPORT_ALL \
+ -sMODULARIZE \
+ -sMAIN_MODULE \
+ -sSTRICT_JS \
+ -sNO_DISABLE_EXCEPTION_CATCHING \
+ $EXTRA_LD_FLAGS \
+"
+
+# This needs to test false if there exists an environment variable called
+# WASM_BIGINT whose contents are empty. Don't use +x.
+if [ -n "${WASM_BIGINT}" ] ; then
+ export LDFLAGS+=" -sWASM_BIGINT"
+else
+ export LDFLAGS+=" -sEXPORTED_RUNTIME_METHODS='getTempRet0,setTempRet0'"
+fi
+
+# Rename main functions to test__filename so we can link them together
+ls *c | sed 's!\(.*\)\.c!sed -i "s/main/test__\1/g" \0!g' | bash
+
+# Compile
+ls *.c | sed 's/\(.*\)\.c/emcc $CFLAGS -c \1.c -o \1.o /g' | bash
+ls *.cc | sed 's/\(.*\)\.cc/em++ $CXXFLAGS -c \1.cc -o \1.o /g' | bash
+
+# Link
+em++ $LDFLAGS *.o -o test.js
+cp ../emscripten/test.html .
diff --git a/testsuite/emscripten/build.sh b/testsuite/emscripten/build.sh
new file mode 100755
index 0000000..32596c3
--- /dev/null
+++ b/testsuite/emscripten/build.sh
@@ -0,0 +1,63 @@
+#!/usr/bin/env bash
+command -v emcc >/dev/null 2>&1 || {
+ echo >&2 "emsdk could not be found. Aborting."
+ exit 1
+}
+
+set -e
+
+SOURCE_DIR=$PWD
+
+# Working directories
+TARGET=$SOURCE_DIR/target
+mkdir -p "$TARGET"
+
+# Define default arguments
+
+# JS BigInt to Wasm i64 integration, disabled by default
+# This needs to test false if there exists an environment variable called
+# WASM_BIGINT whose contents are empty. Don't use +x.
+if [ -n "${WASM_BIGINT}" ]; then
+ WASM_BIGINT=true
+else
+ WASM_BIGINT=false
+fi
+
+# Parse arguments
+while [ $# -gt 0 ]; do
+ case $1 in
+ --enable-wasm-bigint) WASM_BIGINT=true ;;
+ --debug) DEBUG=true ;;
+ *)
+ echo "ERROR: Unknown parameter: $1" >&2
+ exit 1
+ ;;
+ esac
+ shift
+done
+
+# Common compiler flags
+export CFLAGS="-O3 -fPIC"
+if [ "$WASM_BIGINT" = "true" ]; then
+ # We need to detect WASM_BIGINT support at compile time
+ export CFLAGS+=" -DWASM_BIGINT"
+fi
+if [ "$DEBUG" = "true" ]; then
+ export CFLAGS+=" -DDEBUG_F"
+fi
+export CXXFLAGS="$CFLAGS"
+
+# Build paths
+export CPATH="$TARGET/include"
+export PKG_CONFIG_PATH="$TARGET/lib/pkgconfig"
+export EM_PKG_CONFIG_PATH="$PKG_CONFIG_PATH"
+
+# Specific variables for cross-compilation
+export CHOST="wasm32-unknown-linux" # wasm32-unknown-emscripten
+
+autoreconf -fiv
+emconfigure ./configure --host=$CHOST --prefix="$TARGET" --enable-static --disable-shared --disable-dependency-tracking \
+ --disable-builddir --disable-multi-os-directory --disable-raw-api --disable-docs
+make install
+cp fficonfig.h target/include/
+cp include/ffi_common.h target/include/
diff --git a/testsuite/emscripten/conftest.py b/testsuite/emscripten/conftest.py
new file mode 100644
index 0000000..57fac80
--- /dev/null
+++ b/testsuite/emscripten/conftest.py
@@ -0,0 +1,80 @@
+from pathlib import Path
+from pytest import fixture
+from pytest_pyodide.server import spawn_web_server
+from pytest_pyodide import runner
+
+TEST_PATH = Path(__file__).parents[1].resolve()
+
+
+class BaseRunner(runner._BrowserBaseRunner):
+ def __init__(
+ self,
+ *args,
+ test_dir,
+ **kwargs,
+ ):
+ self.test_dir = test_dir
+ super().__init__(
+ *args,
+ **kwargs,
+ load_pyodide=False,
+ )
+
+ def prepare_driver(self):
+ self.base_url = (
+ f"http://{self.server_hostname}:{self.server_port}/{self.test_dir}/"
+ )
+ self.goto(f"{self.base_url}/test.html")
+
+ def javascript_setup(self):
+ self.run_js("globalThis.TestModule = await globalThis.Module();")
+
+
+class FirefoxRunner(BaseRunner, runner.SeleniumFirefoxRunner):
+ pass
+
+
+class ChromeRunner(BaseRunner, runner.SeleniumChromeRunner):
+ pass
+
+
+# TODO: Figure out how to get NodeRunner to work.
+
+RUNNER_DICT = {x.browser: x for x in [FirefoxRunner, ChromeRunner]}
+
+
+@fixture(params=list(RUNNER_DICT), scope="class")
+def selenium_class_scope(request, web_server_main):
+ server_hostname, server_port, server_log = web_server_main
+ assert request.param in RUNNER_DICT
+ cls = RUNNER_DICT[request.param]
+ selenium = cls(
+ test_dir=request.cls.TEST_BUILD_DIR,
+ server_port=server_port,
+ server_hostname=server_hostname,
+ server_log=server_log,
+ )
+ request.cls.call_number = 0
+ try:
+ yield selenium
+ finally:
+ print(selenium.logs)
+ selenium.driver.quit()
+
+
+@fixture(scope="function")
+def selenium(selenium_class_scope, request):
+ selenium = selenium_class_scope
+ request.cls.call_number += 1
+ # Refresh page every 50 calls to prevent firefox out of memory errors
+ if request.cls.call_number % 50 == 0:
+ selenium.driver.refresh()
+ selenium.javascript_setup()
+ selenium.clean_logs()
+ yield selenium
+
+
+@fixture(scope="session")
+def web_server_main(request):
+ with spawn_web_server(TEST_PATH) as output:
+ yield output
diff --git a/testsuite/emscripten/node-tests.sh b/testsuite/emscripten/node-tests.sh
new file mode 100755
index 0000000..2ab79e8
--- /dev/null
+++ b/testsuite/emscripten/node-tests.sh
@@ -0,0 +1,48 @@
+#!/bin/bash
+
+# JS BigInt to Wasm i64 integration, disabled by default
+WASM_BIGINT=false
+
+emcc_exists="$(command -v emcc)"
+if [ ! "${emcc_exists}" ]; then
+ echo "Emscripten not on path"
+ exit 1
+fi
+
+# Parse arguments
+while [ $# -gt 0 ]; do
+ case $1 in
+ --enable-wasm-bigint) WASM_BIGINT=true ;;
+ *)
+ echo "ERROR: Unknown parameter: $1" >&2
+ exit 1
+ ;;
+ esac
+ shift
+done
+
+# Common compiler flags
+export CFLAGS="-fPIC $EXTRA_CFLAGS"
+if [ "$WASM_BIGINT" = "true" ]; then
+ # We need to detect WASM_BIGINT support at compile time
+ export CFLAGS+=" -DWASM_BIGINT"
+fi
+export CXXFLAGS="$CFLAGS -sNO_DISABLE_EXCEPTION_CATCHING $EXTRA_CXXFLAGS"
+export LDFLAGS="-sEXPORTED_FUNCTIONS=_main,_malloc,_free -sALLOW_TABLE_GROWTH -sASSERTIONS -sNO_DISABLE_EXCEPTION_CATCHING"
+if [ "$WASM_BIGINT" = "true" ]; then
+ export LDFLAGS+=" -sWASM_BIGINT"
+else
+ export LDFLAGS+=" -sEXPORTED_RUNTIME_METHODS='getTempRet0,setTempRet0'"
+fi
+
+# Specific variables for cross-compilation
+export CHOST="wasm32-unknown-linux" # wasm32-unknown-emscripten
+
+autoreconf -fiv
+emconfigure ./configure --prefix="$(pwd)/target" --host=$CHOST --enable-static --disable-shared \
+ --disable-builddir --disable-multi-os-directory --disable-raw-api --disable-docs ||
+ (cat config.log && exit 1)
+make
+
+EMMAKEN_JUST_CONFIGURE=1 emmake make check \
+ RUNTESTFLAGS="LDFLAGS_FOR_TARGET='$LDFLAGS'" || (cat testsuite/libffi.log && exit 1)
diff --git a/testsuite/emscripten/quiet_emcc_info.py b/testsuite/emscripten/quiet_emcc_info.py
new file mode 100644
index 0000000..b2b3f06
--- /dev/null
+++ b/testsuite/emscripten/quiet_emcc_info.py
@@ -0,0 +1,36 @@
+"""
+Prevent emcc from printing info level logging
+
+dejagnu will fail tests because of these log statements and the messages depend
+on emscripten cache state so xfailing the right tests is very hard.
+
+See emscripten issue:
+https://github.com/emscripten-core/emscripten/issues/18607
+"""
+
+from pathlib import Path
+from shutil import which
+from sys import exit
+from textwrap import dedent
+
+EMCC_PATH = Path(which("emcc") + ".py")
+
+emcc_text = EMCC_PATH.read_text()
+if "# quiet_emcc_info patch" in emcc_text:
+ exit(0)
+
+emcc_lines = emcc_text.splitlines()
+emcc_lines.insert(
+ 1,
+ dedent(
+ """
+ # quiet_emcc_info patch
+ import logging
+ for name in ["cache", "system_libs", "shared"]:
+ logger = logging.getLogger(name)
+ logger.setLevel(logging.WARN)
+ """
+ ),
+)
+
+EMCC_PATH.write_text("\n".join(emcc_lines))
diff --git a/testsuite/emscripten/test.html b/testsuite/emscripten/test.html
new file mode 100644
index 0000000..7701503
--- /dev/null
+++ b/testsuite/emscripten/test.html
@@ -0,0 +1,7 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <script src="test.js"></script>
+ </head>
+ <body></body>
+</html>
diff --git a/testsuite/emscripten/test_libffi.py b/testsuite/emscripten/test_libffi.py
new file mode 100644
index 0000000..059d535
--- /dev/null
+++ b/testsuite/emscripten/test_libffi.py
@@ -0,0 +1,51 @@
+import subprocess
+import pathlib
+import pytest
+
+TEST_PATH = pathlib.Path(__file__).parents[1].resolve()
+
+xfails = {}
+
+
+def libffi_tests(self, selenium, libffi_test):
+ if libffi_test in xfails:
+ pytest.xfail(f'known failure with code "{xfails[libffi_test]}"')
+ res = selenium.run_js(
+ """
+ window.TestModule = await Module();
+ """
+ )
+ selenium.run_js(
+ f"""
+ try {{
+ TestModule._test__{libffi_test}();
+ }} catch(e){{
+ if(e.name !== "ExitStatus"){{
+ throw e;
+ }}
+ if(e.status !== 0){{
+ throw new Error(`Terminated with nonzero status code ${{e.status}}: ` + e.message);
+ }}
+ }}
+ """
+ )
+
+
+class TestCall:
+ TEST_BUILD_DIR = "libffi.call.test"
+ test_call = libffi_tests
+
+
+class TestClosures:
+ TEST_BUILD_DIR = "libffi.closures.test"
+ test_closures = libffi_tests
+
+
+def pytest_generate_tests(metafunc):
+ test_build_dir = metafunc.cls.TEST_BUILD_DIR
+ test_names = [x.stem for x in (TEST_PATH / test_build_dir).glob("*.o")]
+ metafunc.parametrize("libffi_test", test_names)
+
+
+if __name__ == "__main__":
+ subprocess.call(["build-tests.sh", "libffi.call"])
diff --git a/testsuite/lib/libffi.exp b/testsuite/lib/libffi.exp
index 17d1ed5..a84e533 100644
--- a/testsuite/lib/libffi.exp
+++ b/testsuite/lib/libffi.exp
@@ -221,6 +221,13 @@ proc libffi-dg-test-1 { target_compile prog do_what extra_tool_flags } {
set output_match [lreplace $output_match 1 1 $x]
}
+ if { [ istarget "wasm32-*-*" ] } {
+ # emscripten will get confused if told to build as .exe
+ set exec_suffix ""
+ } else {
+ set exec_suffix ".exe"
+ }
+
# Set up the compiler flags, based on what we're going to do.
set options [list]
@@ -231,7 +238,7 @@ proc libffi-dg-test-1 { target_compile prog do_what extra_tool_flags } {
}
"link" {
set compile_type "executable"
- set output_file "[file rootname [file tail $prog]].exe"
+ set output_file "[file rootname [file tail $prog]]$exec_suffix"
# The following line is needed for targets like the i960 where
# the default output file is b.out. Sigh.
}
@@ -240,7 +247,7 @@ proc libffi-dg-test-1 { target_compile prog do_what extra_tool_flags } {
# FIXME: "./" is to cope with "." not being in $PATH.
# Should this be handled elsewhere?
# YES.
- set output_file "./[file rootname [file tail $prog]].exe"
+ set output_file "./[file rootname [file tail $prog]]$exec_suffix"
# This is the only place where we care if an executable was
# created or not. If it was, dg.exp will try to run it.
remote_file build delete $output_file;
@@ -417,6 +424,12 @@ proc libffi_target_compile { source dest type options } {
}
}
+ # emscripten emits this warning while building the feature test
+ # which causes it to be seen as unsupported.
+ if { [string match "wasm32-*" $target_triplet] } {
+ lappend options "additional_flags=-Wno-unused-command-line-argument"
+ }
+
verbose "options: $options"
return [target_compile $source $dest $type $options]
}
diff --git a/testsuite/libffi.call/bpo-38748.c b/testsuite/libffi.call/bpo-38748.c
deleted file mode 100644
index 294bda0..0000000
--- a/testsuite/libffi.call/bpo-38748.c
+++ /dev/null
@@ -1,41 +0,0 @@
-/* Area: bpo-38748
- Purpose: test for stdcall alignment problem
- Source: github.com/python/cpython/pull/26204 */
-
-/* { dg-do run } */
-
-#include "ffitest.h"
-#include "ffi_common.h"
-
-static UINT32 ABI_ATTR align_arguments(UINT32 l1,
- UINT64 l2)
-{
- return l1 + (UINT32) l2;
-}
-
-int main(void)
-{
- ffi_cif cif;
- ffi_type *args[4] = {
- &ffi_type_uint32,
- &ffi_type_uint64
- };
- ffi_arg lr1, lr2;
- UINT32 l1 = 1;
- UINT64 l2 = 2;
- void *values[2] = {&l1, &l2};
-
- /* Initialize the cif */
- CHECK(ffi_prep_cif(&cif, ABI_NUM, 2,
- &ffi_type_uint32, args) == FFI_OK);
-
- lr1 = align_arguments(l1, l2);
-
- ffi_call(&cif, FFI_FN(align_arguments), &lr2, values);
-
- if (lr1 == lr2)
- printf("bpo-38748 arguments tests ok!\n");
- else
- CHECK(0);
- exit(0);
-}
diff --git a/testsuite/libffi.call/bpo_38748.c b/testsuite/libffi.call/bpo_38748.c
new file mode 100644
index 0000000..294bda0
--- /dev/null
+++ b/testsuite/libffi.call/bpo_38748.c
@@ -0,0 +1,41 @@
+/* Area: bpo-38748
+ Purpose: test for stdcall alignment problem
+ Source: github.com/python/cpython/pull/26204 */
+
+/* { dg-do run } */
+
+#include "ffitest.h"
+#include "ffi_common.h"
+
+static UINT32 ABI_ATTR align_arguments(UINT32 l1,
+ UINT64 l2)
+{
+ return l1 + (UINT32) l2;
+}
+
+int main(void)
+{
+ ffi_cif cif;
+ ffi_type *args[4] = {
+ &ffi_type_uint32,
+ &ffi_type_uint64
+ };
+ ffi_arg lr1, lr2;
+ UINT32 l1 = 1;
+ UINT64 l2 = 2;
+ void *values[2] = {&l1, &l2};
+
+ /* Initialize the cif */
+ CHECK(ffi_prep_cif(&cif, ABI_NUM, 2,
+ &ffi_type_uint32, args) == FFI_OK);
+
+ lr1 = align_arguments(l1, l2);
+
+ ffi_call(&cif, FFI_FN(align_arguments), &lr2, values);
+
+ if (lr1 == lr2)
+ printf("bpo-38748 arguments tests ok!\n");
+ else
+ CHECK(0);
+ exit(0);
+}
diff --git a/testsuite/libffi.closures/closure_loc_fn0.c b/testsuite/libffi.closures/closure_loc_fn0.c
index 6f2e3d5..f344a60 100644
--- a/testsuite/libffi.closures/closure_loc_fn0.c
+++ b/testsuite/libffi.closures/closure_loc_fn0.c
@@ -7,9 +7,6 @@
Originator: <andreast@gcc.gnu.org> 20030828 */
-
-
-/* { dg-do run { xfail wasm32*-*-* } } */
#include "ffitest.h"
static void
@@ -83,7 +80,7 @@ int main (void)
CHECK(ffi_prep_closure_loc(pcl, &cif, closure_loc_test_fn0,
(void *) 3 /* userdata */, codeloc) == FFI_OK);
-#ifndef FFI_EXEC_STATIC_TRAMP
+#if !defined(FFI_EXEC_STATIC_TRAMP) && !defined(__EMSCRIPTEN__)
/* With static trampolines, the codeloc does not point to closure */
CHECK(memcmp(pcl, FFI_CL(codeloc), sizeof(*pcl)) == 0);
#endif
diff --git a/testsuite/libffi.closures/cls_longdouble_va.c b/testsuite/libffi.closures/cls_longdouble_va.c
index 493f0f6..ba32f5c 100644
--- a/testsuite/libffi.closures/cls_longdouble_va.c
+++ b/testsuite/libffi.closures/cls_longdouble_va.c
@@ -9,10 +9,21 @@
/* { dg-output "" { xfail mips-sgi-irix6* } } PR libffi/46660 */
#include "ffitest.h"
+#include <stdarg.h>
#define BUF_SIZE 50
static char buffer[BUF_SIZE];
+static int
+wrap_printf(char* fmt, ...) {
+ va_list ap;
+ va_start(ap, fmt);
+ long double ldArg = va_arg(ap, long double);
+ va_end(ap);
+ CHECK((int)ldArg == 7);
+ return printf(fmt, ldArg);
+}
+
static void
cls_longdouble_va_fn(ffi_cif* cif __UNUSED__, void* resp,
void** args, void* userdata __UNUSED__)
@@ -50,7 +61,7 @@ int main (void)
args[1] = &ldArg;
args[2] = NULL;
- ffi_call(&cif, FFI_FN(printf), &res, args);
+ ffi_call(&cif, FFI_FN(wrap_printf), &res, args);
/* { dg-output "7.0" } */
printf("res: %d\n", (int) res);
/* { dg-output "\nres: 4" } */
diff --git a/testsuite/libffi.closures/cls_multi_schar.c b/testsuite/libffi.closures/cls_multi_schar.c
index 921777a..9eb02f9 100644
--- a/testsuite/libffi.closures/cls_multi_schar.c
+++ b/testsuite/libffi.closures/cls_multi_schar.c
@@ -64,7 +64,7 @@ int main (void)
/* { dg-output "2 125: 127" } */
printf("res: %d\n", (signed char)res_call);
/* { dg-output "\nres: 127" } */
- CHECK(res_call == 127);
+ CHECK((signed char)res_call == 127);
CHECK(ffi_prep_closure_loc(pcl, &cif, test_func_gn, NULL, code) == FFI_OK);
diff --git a/testsuite/libffi.closures/cls_multi_sshort.c b/testsuite/libffi.closures/cls_multi_sshort.c
index d78c62d..9d4db5b 100644
--- a/testsuite/libffi.closures/cls_multi_sshort.c
+++ b/testsuite/libffi.closures/cls_multi_sshort.c
@@ -65,7 +65,7 @@ int main (void)
/* { dg-output "2 32765: 32767" } */
printf("res: %d\n", (unsigned short)res_call);
/* { dg-output "\nres: 32767" } */
- CHECK(res_call == 32767);
+ CHECK((unsigned short)res_call == 32767);
CHECK(ffi_prep_closure_loc(pcl, &cif, test_func_gn, NULL, code) == FFI_OK);
diff --git a/testsuite/libffi.closures/huge_struct.c b/testsuite/libffi.closures/huge_struct.c
index 71cae26..572a0c8 100644
--- a/testsuite/libffi.closures/huge_struct.c
+++ b/testsuite/libffi.closures/huge_struct.c
@@ -5,7 +5,7 @@
Originator: Blake Chaffin 6/18/2007
*/
-/* { dg-do run { xfail strongarm*-*-* xscale*-*-* wasm32*-*-* } } */
+/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */
/* { dg-options -mlong-double-128 { target powerpc64*-*-linux-gnu* } } */
/* { dg-options -Wformat=0 { target moxie*-*-elf or1k-*-* } } */
diff --git a/testsuite/libffi.closures/unwindtest.cc b/testsuite/libffi.closures/unwindtest.cc
index 6c97c61..b643c48 100644
--- a/testsuite/libffi.closures/unwindtest.cc
+++ b/testsuite/libffi.closures/unwindtest.cc
@@ -48,6 +48,7 @@ typedef int (*closure_test_type1)(float, float, float, float, signed short,
float, float, int, double, int, int, float,
int, int, int, int);
+extern "C"
int main (void)
{
ffi_cif cif;
diff --git a/testsuite/libffi.closures/unwindtest_ffi_call.cc b/testsuite/libffi.closures/unwindtest_ffi_call.cc
index 153d240..6feaa57 100644
--- a/testsuite/libffi.closures/unwindtest_ffi_call.cc
+++ b/testsuite/libffi.closures/unwindtest_ffi_call.cc
@@ -14,6 +14,7 @@ static int checking(int a __UNUSED__, short b __UNUSED__,
throw 9;
}
+extern "C"
int main (void)
{
ffi_cif cif;