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
|
#![cfg(not(miri))]
use anyhow::bail;
use std::panic::{self, AssertUnwindSafe};
use std::process::Command;
use std::sync::{Arc, Mutex};
use wasmtime::*;
use wasmtime_test_macros::wasmtime_test;
#[test]
fn test_trap_return() -> Result<()> {
let mut store = Store::<()>::default();
let wat = r#"
(module
(func $hello (import "" "hello"))
(func (export "run") (call $hello))
)
"#;
let module = Module::new(store.engine(), wat)?;
let hello_type = FuncType::new(store.engine(), None, None);
let hello_func = Func::new(&mut store, hello_type, |_, _, _| bail!("test 123"));
let instance = Instance::new(&mut store, &module, &[hello_func.into()])?;
let run_func = instance.get_typed_func::<(), ()>(&mut store, "run")?;
let e = run_func.call(&mut store, ()).unwrap_err();
assert!(format!("{e:?}").contains("test 123"));
assert!(
e.downcast_ref::<WasmBacktrace>().is_some(),
"error should contain a WasmBacktrace"
);
Ok(())
}
#[test]
fn test_anyhow_error_return() -> Result<()> {
let mut store = Store::<()>::default();
let wat = r#"
(module
(func $hello (import "" "hello"))
(func (export "run") (call $hello))
)
"#;
let module = Module::new(store.engine(), wat)?;
let hello_type = FuncType::new(store.engine(), None, None);
let hello_func = Func::new(&mut store, hello_type, |_, _, _| {
Err(anyhow::Error::msg("test 1234"))
});
let instance = Instance::new(&mut store, &module, &[hello_func.into()])?;
let run_func = instance.get_typed_func::<(), ()>(&mut store, "run")?;
let e = run_func.call(&mut store, ()).unwrap_err();
assert!(!e.to_string().contains("test 1234"));
assert!(format!("{e:?}").contains("Caused by:\n test 1234"));
assert!(e.downcast_ref::<Trap>().is_none());
assert!(e.downcast_ref::<WasmBacktrace>().is_some());
Ok(())
}
#[test]
fn test_trap_return_downcast() -> Result<()> {
let mut store = Store::<()>::default();
let wat = r#"
(module
(func $hello (import "" "hello"))
(func (export "run") (call $hello))
)
"#;
#[derive(Debug)]
struct MyTrap;
impl std::fmt::Display for MyTrap {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "my trap")
}
}
impl std::error::Error for MyTrap {}
let module = Module::new(store.engine(), wat)?;
let hello_type = FuncType::new(store.engine(), None, None);
let hello_func = Func::new(&mut store, hello_type, |_, _, _| {
Err(anyhow::Error::from(MyTrap))
});
let instance = Instance::new(&mut store, &module, &[hello_func.into()])?;
let run_func = instance.get_typed_func::<(), ()>(&mut store, "run")?;
let e = run_func
.call(&mut store, ())
.err()
.expect("error calling function");
let dbg = format!("{e:?}");
println!("{dbg}");
assert!(!e.to_string().contains("my trap"));
assert!(dbg.contains("Caused by:\n my trap"));
e.downcast_ref::<MyTrap>()
.expect("error downcasts to MyTrap");
let bt = e
.downcast_ref::<WasmBacktrace>()
.expect("error downcasts to WasmBacktrace");
assert_eq!(bt.frames().len(), 1);
println!("{bt:?}");
Ok(())
}
#[test]
fn test_trap_trace() -> Result<()> {
let mut store = Store::<()>::default();
let wat = r#"
(module $hello_mod
(func (export "run") (call $hello))
(func $hello (unreachable))
)
"#;
let module = Module::new(store.engine(), wat)?;
let instance = Instance::new(&mut store, &module, &[])?;
let run_func = instance.get_typed_func::<(), ()>(&mut store, "run")?;
let e = run_func.call(&mut store, ()).unwrap_err();
let trace = e.downcast_ref::<WasmBacktrace>().unwrap().frames();
assert_eq!(trace.len(), 2);
assert_eq!(trace[0].module().name().unwrap(), "hello_mod");
assert_eq!(trace[0].func_index(), 1);
assert_eq!(trace[0].func_name(), Some("hello"));
assert_eq!(trace[0].func_offset(), Some(1));
assert_eq!(trace[0].module_offset(), Some(0x26));
assert_eq!(trace[1].module().name().unwrap(), "hello_mod");
assert_eq!(trace[1].func_index(), 0);
assert_eq!(trace[1].func_name(), None);
assert_eq!(trace[1].func_offset(), Some(1));
assert_eq!(trace[1].module_offset(), Some(0x21));
assert_eq!(e.downcast::<Trap>()?, Trap::UnreachableCodeReached);
Ok(())
}
#[test]
fn test_trap_through_host() -> Result<()> {
let wat = r#"
(module $hello_mod
(import "" "" (func $host_func_a))
(import "" "" (func $host_func_b))
(func $a (export "a")
call $host_func_a
)
(func $b (export "b")
call $host_func_b
)
(func $c (export "c")
unreachable
)
)
"#;
let engine = Engine::default();
let module = Module::new(&engine, wat)?;
let mut store = Store::<()>::new(&engine, ());
let host_func_a = Func::new(
&mut store,
FuncType::new(&engine, vec![], vec![]),
|mut caller, _args, _results| {
caller
.get_export("b")
.unwrap()
.into_func()
.unwrap()
.call(caller, &[], &mut [])?;
Ok(())
},
);
let host_func_b = Func::new(
&mut store,
FuncType::new(&engine, vec![], vec![]),
|mut caller, _args, _results| {
caller
.get_export("c")
.unwrap()
.into_func()
.unwrap()
.call(caller, &[], &mut [])?;
Ok(())
},
);
let instance = Instance::new(
&mut store,
&module,
&[host_func_a.into(), host_func_b.into()],
)?;
let a = instance.get_typed_func::<(), ()>(&mut store, "a")?;
let err = a.call(&mut store, ()).unwrap_err();
let trace = err.downcast_ref::<WasmBacktrace>().unwrap().frames();
assert_eq!(trace.len(), 3);
assert_eq!(trace[0].func_name(), Some("c"));
assert_eq!(trace[1].func_name(), Some("b"));
assert_eq!(trace[2].func_name(), Some("a"));
Ok(())
}
#[test]
#[allow(deprecated)]
fn test_trap_backtrace_disabled() -> Result<()> {
let mut config = Config::default();
config.wasm_backtrace(false);
let engine = Engine::new(&config).unwrap();
let mut store = Store::<()>::new(&engine, ());
let wat = r#"
(module $hello_mod
(func (export "run") (call $hello))
(func $hello (unreachable))
)
"#;
let module = Module::new(store.engine(), wat)?;
let instance = Instance::new(&mut store, &module, &[])?;
let run_func = instance.get_typed_func::<(), ()>(&mut store, "run")?;
let e = run_func.call(&mut store, ()).unwrap_err();
assert!(e.downcast_ref::<WasmBacktrace>().is_none());
Ok(())
}
#[test]
fn test_trap_trace_cb() -> Result<()> {
let mut store = Store::<()>::default();
let wat = r#"
(module $hello_mod
(import "" "throw" (func $throw))
(func (export "run") (call $hello))
(func $hello (call $throw))
)
"#;
let fn_type = FuncType::new(store.engine(), None, None);
let fn_func = Func::new(&mut store, fn_type, |_, _, _| bail!("cb throw"));
let module = Module::new(store.engine(), wat)?;
let instance = Instance::new(&mut store, &module, &[fn_func.into()])?;
let run_func = instance.get_typed_func::<(), ()>(&mut store, "run")?;
let e = run_func.call(&mut store, ()).unwrap_err();
let trace = e.downcast_ref::<WasmBacktrace>().unwrap().frames();
assert_eq!(trace.len(), 2);
assert_eq!(trace[0].module().name().unwrap(), "hello_mod");
assert_eq!(trace[0].func_index(), 2);
assert_eq!(trace[1].module().name().unwrap(), "hello_mod");
assert_eq!(trace[1].func_index(), 1);
assert!(format!("{e:?}").contains("cb throw"));
Ok(())
}
#[test]
fn test_trap_stack_overflow() -> Result<()> {
let mut store = Store::<()>::default();
let wat = r#"
(module $rec_mod
(func $run (export "run") (call $run))
)
"#;
let module = Module::new(store.engine(), wat)?;
let instance = Instance::new(&mut store, &module, &[])?;
let run_func = instance.get_typed_func::<(), ()>(&mut store, "run")?;
let e = run_func.call(&mut store, ()).unwrap_err();
let trace = e.downcast_ref::<WasmBacktrace>().unwrap().frames();
assert!(trace.len() >= 32);
for i in 0..trace.len() {
assert_eq!(trace[i].module().name().unwrap(), "rec_mod");
assert_eq!(trace[i].func_index(), 0);
assert_eq!(trace[i].func_name(), Some("run"));
}
assert_eq!(e.downcast::<Trap>()?, Trap::StackOverflow);
Ok(())
}
#[test]
fn trap_display_pretty() -> Result<()> {
let mut store = Store::<()>::default();
let wat = r#"
(module $m
(func $die unreachable)
(func call $die)
(func $foo call 1)
(func (export "bar") call $foo)
)
"#;
let module = Module::new(store.engine(), wat)?;
let instance = Instance::new(&mut store, &module, &[])?;
let run_func = instance.get_typed_func::<(), ()>(&mut store, "bar")?;
let e = run_func.call(&mut store, ()).unwrap_err();
let e = format!("{e:?}");
assert!(e.contains(
"\
error while executing at wasm backtrace:
0: 0x23 - m!die
1: 0x27 - m!<wasm function 1>
2: 0x2c - m!foo
3: 0x31 - m!<wasm function 3>
Caused by:
wasm trap: wasm `unreachable` instruction executed\
"
));
Ok(())
}
#[test]
fn trap_display_multi_module() -> Result<()> {
let mut store = Store::<()>::default();
let wat = r#"
(module $a
(func $die unreachable)
(func call $die)
(func $foo call 1)
(func (export "bar") call $foo)
)
"#;
let module = Module::new(store.engine(), wat)?;
let instance = Instance::new(&mut store, &module, &[])?;
let bar = instance.get_export(&mut store, "bar").unwrap();
let wat = r#"
(module $b
(import "" "" (func $bar))
(func $middle call $bar)
(func (export "bar2") call $middle)
)
"#;
let module = Module::new(store.engine(), wat)?;
let instance = Instance::new(&mut store, &module, &[bar])?;
let bar2 = instance.get_typed_func::<(), ()>(&mut store, "bar2")?;
let e = bar2.call(&mut store, ()).unwrap_err();
let e = format!("{e:?}");
assert!(e.contains(
"\
error while executing at wasm backtrace:
0: 0x23 - a!die
1: 0x27 - a!<wasm function 1>
2: 0x2c - a!foo
3: 0x31 - a!<wasm function 3>
4: 0x29 - b!middle
5: 0x2e - b!<wasm function 2>
Caused by:
wasm trap: wasm `unreachable` instruction executed\
"
));
Ok(())
}
#[test]
fn trap_start_function_import() -> Result<()> {
let mut store = Store::<()>::default();
let binary = wat::parse_str(
r#"
(module $a
(import "" "" (func $foo))
(start $foo)
)
"#,
)?;
let module = Module::new(store.engine(), &binary)?;
let sig = FuncType::new(store.engine(), None, None);
let func = Func::new(&mut store, sig, |_, _, _| bail!("user trap"));
let err = Instance::new(&mut store, &module, &[func.into()]).unwrap_err();
assert!(format!("{err:?}").contains("user trap"));
Ok(())
}
#[test]
fn rust_panic_import() -> Result<()> {
let mut store = Store::<()>::default();
let binary = wat::parse_str(
r#"
(module $a
(import "" "" (func $foo))
(import "" "" (func $bar))
(func (export "foo") call $foo)
(func (export "bar") call $bar)
)
"#,
)?;
let module = Module::new(store.engine(), &binary)?;
let sig = FuncType::new(store.engine(), None, None);
let func = Func::new(&mut store, sig, |_, _, _| panic!("this is a panic"));
let func2 = Func::wrap(&mut store, || -> () { panic!("this is another panic") });
let instance = Instance::new(&mut store, &module, &[func.into(), func2.into()])?;
let func = instance.get_typed_func::<(), ()>(&mut store, "foo")?;
let err =
panic::catch_unwind(AssertUnwindSafe(|| drop(func.call(&mut store, ())))).unwrap_err();
assert_eq!(err.downcast_ref::<&'static str>(), Some(&"this is a panic"));
let func = instance.get_typed_func::<(), ()>(&mut store, "bar")?;
let err = panic::catch_unwind(AssertUnwindSafe(|| {
drop(func.call(&mut store, ()));
}))
.unwrap_err();
assert_eq!(
err.downcast_ref::<&'static str>(),
Some(&"this is another panic")
);
Ok(())
}
// Test that we properly save/restore our trampolines' saved Wasm registers
// (used when capturing backtraces) before we resume panics.
#[test]
fn rust_catch_panic_import() -> Result<()> {
let mut store = Store::<()>::default();
let binary = wat::parse_str(
r#"
(module $a
(import "" "panic" (func $panic))
(import "" "catch panic" (func $catch_panic))
(func (export "panic") call $panic)
(func (export "run")
call $catch_panic
call $catch_panic
unreachable
)
)
"#,
)?;
let module = Module::new(store.engine(), &binary)?;
let num_panics = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
let sig = FuncType::new(store.engine(), None, None);
let panic = Func::new(&mut store, sig, {
let num_panics = num_panics.clone();
move |_, _, _| {
num_panics.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
panic!("this is a panic");
}
});
let catch_panic = Func::wrap(&mut store, |mut caller: Caller<'_, _>| {
panic::catch_unwind(AssertUnwindSafe(|| {
drop(
caller
.get_export("panic")
.unwrap()
.into_func()
.unwrap()
.call(&mut caller, &[], &mut []),
);
}))
.unwrap_err();
});
let instance = Instance::new(&mut store, &module, &[panic.into(), catch_panic.into()])?;
let run = instance.get_typed_func::<(), ()>(&mut store, "run")?;
let trap = run.call(&mut store, ()).unwrap_err();
let trace = trap.downcast_ref::<WasmBacktrace>().unwrap().frames();
assert_eq!(trace.len(), 1);
assert_eq!(trace[0].func_index(), 3);
assert_eq!(num_panics.load(std::sync::atomic::Ordering::SeqCst), 2);
Ok(())
}
#[test]
fn rust_panic_start_function() -> Result<()> {
let mut store = Store::<()>::default();
let binary = wat::parse_str(
r#"
(module $a
(import "" "" (func $foo))
(start $foo)
)
"#,
)?;
let module = Module::new(store.engine(), &binary)?;
let sig = FuncType::new(store.engine(), None, None);
let func = Func::new(&mut store, sig, |_, _, _| panic!("this is a panic"));
let err = panic::catch_unwind(AssertUnwindSafe(|| {
drop(Instance::new(&mut store, &module, &[func.into()]));
}))
.unwrap_err();
assert_eq!(err.downcast_ref::<&'static str>(), Some(&"this is a panic"));
let func = Func::wrap(&mut store, || -> () { panic!("this is another panic") });
let err = panic::catch_unwind(AssertUnwindSafe(|| {
drop(Instance::new(&mut store, &module, &[func.into()]));
}))
.unwrap_err();
assert_eq!(
err.downcast_ref::<&'static str>(),
Some(&"this is another panic")
);
Ok(())
}
#[test]
fn mismatched_arguments() -> Result<()> {
let mut store = Store::<()>::default();
let binary = wat::parse_str(
r#"
(module $a
(func (export "foo") (param i32))
)
"#,
)?;
let module = Module::new(store.engine(), &binary)?;
let instance = Instance::new(&mut store, &module, &[])?;
let func = instance.get_func(&mut store, "foo").unwrap();
assert_eq!(
func.call(&mut store, &[], &mut []).unwrap_err().to_string(),
"expected 1 arguments, got 0"
);
let e = func.call(&mut store, &[Val::F32(0)], &mut []).unwrap_err();
let e = format!("{e:?}");
assert!(e.contains("argument type mismatch"));
assert!(e.contains("expected i32, found f32"));
assert_eq!(
func.call(&mut store, &[Val::I32(0), Val::I32(1)], &mut [])
.unwrap_err()
.to_string(),
"expected 1 arguments, got 2"
);
Ok(())
}
#[test]
fn call_signature_mismatch() -> Result<()> {
let mut store = Store::<()>::default();
let binary = wat::parse_str(
r#"
(module $a
(func $foo
i32.const 0
call_indirect)
(func $bar (param i32))
(start $foo)
(table 1 funcref)
(elem (i32.const 0) 1)
)
"#,
)?;
let module = Module::new(store.engine(), &binary)?;
let err = Instance::new(&mut store, &module, &[])
.err()
.unwrap()
.downcast::<Trap>()
.unwrap();
assert!(err
.to_string()
.contains("wasm trap: indirect call type mismatch"));
Ok(())
}
#[test]
fn start_trap_pretty() -> Result<()> {
let mut store = Store::<()>::default();
let wat = r#"
(module $m
(func $die unreachable)
(func call $die)
(func $foo call 1)
(func $start call $foo)
(start $start)
)
"#;
let module = Module::new(store.engine(), wat)?;
let e = match Instance::new(&mut store, &module, &[]) {
Ok(_) => panic!("expected failure"),
Err(e) => format!("{e:?}"),
};
assert!(e.contains(
"\
error while executing at wasm backtrace:
0: 0x1d - m!die
1: 0x21 - m!<wasm function 1>
2: 0x26 - m!foo
3: 0x2b - m!start
Caused by:
wasm trap: wasm `unreachable` instruction executed\
"
));
Ok(())
}
#[test]
fn present_after_module_drop() -> Result<()> {
let mut store = Store::<()>::default();
let module = Module::new(store.engine(), r#"(func (export "foo") unreachable)"#)?;
let instance = Instance::new(&mut store, &module, &[])?;
let func = instance.get_typed_func::<(), ()>(&mut store, "foo")?;
println!("asserting before we drop modules");
assert_trap(func.call(&mut store, ()).unwrap_err());
drop((instance, module));
println!("asserting after drop");
assert_trap(func.call(&mut store, ()).unwrap_err());
return Ok(());
fn assert_trap(t: Error) {
println!("{t:?}");
let trace = t.downcast_ref::<WasmBacktrace>().unwrap().frames();
assert_eq!(trace.len(), 1);
assert_eq!(trace[0].func_index(), 0);
}
}
fn assert_trap_code(wat: &str, code: wasmtime::Trap) {
let mut store = Store::<()>::default();
let module = Module::new(store.engine(), wat).unwrap();
let err = match Instance::new(&mut store, &module, &[]) {
Ok(_) => unreachable!(),
Err(e) => e,
};
let trap = err.downcast_ref::<Trap>().unwrap();
assert_eq!(*trap, code);
let trace = err.downcast_ref::<WasmBacktrace>().unwrap().frames();
assert!(trace.len() > 0);
assert_eq!(trace[0].func_index(), 0);
assert!(trace[0].func_offset().is_some());
}
#[test]
fn trap_codes() {
assert_trap_code(
r#"
(module
(memory 0)
(func $start (drop (i32.load (i32.const 1000000))))
(start $start)
)
"#,
Trap::MemoryOutOfBounds,
);
assert_trap_code(
r#"
(module
(memory 0)
(func $start (drop (i32.load memory.size)))
(start $start)
)
"#,
Trap::MemoryOutOfBounds,
);
for (ty, min) in [("i32", i32::MIN as u32 as u64), ("i64", i64::MIN as u64)] {
for op in ["rem", "div"] {
for sign in ["u", "s"] {
println!("testing {ty}.{op}_{sign}");
assert_trap_code(
&format!(
r#"
(module
(func $div (param {ty} {ty}) (result {ty})
local.get 0
local.get 1
{ty}.{op}_{sign})
(func $start (drop (call $div ({ty}.const 1) ({ty}.const 0))))
(start $start)
)
"#
),
Trap::IntegerDivisionByZero,
);
}
}
println!("testing {ty}.div_s INT_MIN/-1");
assert_trap_code(
&format!(
r#"
(module
(func $div (param {ty} {ty}) (result {ty})
local.get 0
local.get 1
{ty}.div_s)
(func $start (drop (call $div ({ty}.const {min}) ({ty}.const -1))))
(start $start)
)
"#
),
Trap::IntegerOverflow,
);
}
}
fn rustc(src: &str) -> Vec<u8> {
let td = tempfile::TempDir::new().unwrap();
let output = td.path().join("foo.wasm");
let input = td.path().join("input.rs");
std::fs::write(&input, src).unwrap();
let result = Command::new("rustc")
.arg(&input)
.arg("-o")
.arg(&output)
.arg("--target")
.arg("wasm32-wasip1")
.arg("-g")
.output()
.unwrap();
if result.status.success() {
return std::fs::read(&output).unwrap();
}
panic!(
"rustc failed: {}\n{}",
result.status,
String::from_utf8_lossy(&result.stderr)
);
}
#[test]
fn parse_dwarf_info() -> Result<()> {
let wasm = rustc(
"
fn main() {
panic!();
}
",
);
let mut config = Config::new();
config.wasm_backtrace_details(WasmBacktraceDetails::Enable);
let engine = Engine::new(&config)?;
let module = Module::new(&engine, &wasm)?;
let mut linker = Linker::new(&engine);
wasmtime_wasi::preview1::add_to_linker_sync(&mut linker, |t| t)?;
let mut store = Store::new(&engine, wasmtime_wasi::WasiCtxBuilder::new().build_p1());
linker.module(&mut store, "", &module)?;
let run = linker.get_default(&mut store, "")?;
let trap = run.call(&mut store, &[], &mut []).unwrap_err();
let mut found = false;
let frames = trap.downcast_ref::<WasmBacktrace>().unwrap().frames();
for frame in frames {
for symbol in frame.symbols() {
if let Some(file) = symbol.file() {
if file.ends_with("input.rs") {
found = true;
assert!(symbol.name().unwrap().contains("main"));
assert_eq!(symbol.line(), Some(3));
}
}
}
}
assert!(found);
Ok(())
}
#[test]
fn no_hint_even_with_dwarf_info() -> Result<()> {
let mut config = Config::new();
config.wasm_backtrace_details(WasmBacktraceDetails::Disable);
let engine = Engine::new(&config)?;
let mut store = Store::new(&engine, ());
let module = Module::new(
&engine,
r#"
(module
(@custom ".debug_info" (after last) "")
(func $start
unreachable)
(start $start)
)
"#,
)?;
let trap = Instance::new(&mut store, &module, &[]).unwrap_err();
let trap = format!("{trap:?}");
assert!(trap.contains(
"\
error while executing at wasm backtrace:
0: 0x1a - <unknown>!start
Caused by:
wasm trap: wasm `unreachable` instruction executed\
"
));
assert!(!trap.contains("WASM_BACKTRACE_DETAILS"));
Ok(())
}
#[test]
fn hint_with_dwarf_info() -> Result<()> {
// Skip this test if the env var is already configure, but in CI we're sure
// to run tests without this env var configured.
if std::env::var("WASMTIME_BACKTRACE_DETAILS").is_ok() {
return Ok(());
}
let mut store = Store::<()>::default();
let module = Module::new(
store.engine(),
r#"
(module
(@custom ".debug_info" (after last) "")
(func $start
unreachable)
(start $start)
)
"#,
)?;
let trap = Instance::new(&mut store, &module, &[]).unwrap_err();
let trap = format!("{trap:?}");
assert!(trap.contains(
"\
error while executing at wasm backtrace:
0: 0x1a - <unknown>!start
note: using the `WASMTIME_BACKTRACE_DETAILS=1` environment variable may show more debugging information
Caused by:
wasm trap: wasm `unreachable` instruction executed"
));
Ok(())
}
#[test]
fn multithreaded_traps() -> Result<()> {
// Compile and run unreachable on a thread, then moves over the whole store to another thread,
// and make sure traps are still correctly caught after notifying the store of the move.
let mut store = Store::<()>::default();
let module = Module::new(
store.engine(),
r#"(module (func (export "run") unreachable))"#,
)?;
let instance = Instance::new(&mut store, &module, &[])?;
assert!(instance
.get_typed_func::<(), ()>(&mut store, "run")?
.call(&mut store, ())
.is_err());
let handle = std::thread::spawn(move || {
assert!(instance
.get_typed_func::<(), ()>(&mut store, "run")
.unwrap()
.call(&mut store, ())
.is_err());
});
handle.join().expect("couldn't join thread");
Ok(())
}
#[test]
fn traps_without_address_map() -> Result<()> {
let mut config = Config::new();
config.generate_address_map(false);
let engine = Engine::new(&config)?;
let mut store = Store::new(&engine, ());
let wat = r#"
(module $hello_mod
(func (export "run") (call $hello))
(func $hello (unreachable))
)
"#;
let module = Module::new(store.engine(), wat)?;
let instance = Instance::new(&mut store, &module, &[])?;
let run_func = instance.get_typed_func::<(), ()>(&mut store, "run")?;
let e = run_func.call(&mut store, ()).unwrap_err();
let trace = e.downcast_ref::<WasmBacktrace>().unwrap().frames();
assert_eq!(trace.len(), 2);
assert_eq!(trace[0].func_name(), Some("hello"));
assert_eq!(trace[0].func_index(), 1);
assert_eq!(trace[0].module_offset(), None);
assert_eq!(trace[1].func_name(), None);
assert_eq!(trace[1].func_index(), 0);
assert_eq!(trace[1].module_offset(), None);
Ok(())
}
#[test]
fn catch_trap_calling_across_stores() -> Result<()> {
let _ = env_logger::try_init();
let engine = Engine::default();
let mut child_store = Store::new(&engine, ());
let child_module = Module::new(
child_store.engine(),
r#"
(module $child
(func $trap (export "trap")
unreachable
)
)
"#,
)?;
let child_instance = Instance::new(&mut child_store, &child_module, &[])?;
struct ParentCtx {
child_store: Store<()>,
child_instance: Instance,
}
let mut linker = Linker::new(&engine);
linker.func_wrap(
"host",
"catch_child_trap",
move |mut caller: Caller<'_, ParentCtx>| {
let mut ctx = caller.as_context_mut();
let data = ctx.data_mut();
let func = data
.child_instance
.get_typed_func::<(), ()>(&mut data.child_store, "trap")
.expect("trap function should be exported");
let trap = func.call(&mut data.child_store, ()).unwrap_err();
assert!(
format!("{trap:?}").contains("unreachable"),
"trap should contain 'unreachable', got: {trap:?}"
);
let trace = trap.downcast_ref::<WasmBacktrace>().unwrap().frames();
assert_eq!(trace.len(), 1);
assert_eq!(trace[0].func_name(), Some("trap"));
// For now, we only get stack frames for Wasm in this store, not
// across all stores.
//
// assert_eq!(trace[1].func_name(), Some("run"));
Ok(())
},
)?;
let mut store = Store::new(
&engine,
ParentCtx {
child_store,
child_instance,
},
);
let parent_module = Module::new(
store.engine(),
r#"
(module $parent
(func $host.catch_child_trap (import "host" "catch_child_trap"))
(func $run (export "run")
call $host.catch_child_trap
)
)
"#,
)?;
let parent_instance = linker.instantiate(&mut store, &parent_module)?;
let func = parent_instance.get_typed_func::<(), ()>(&mut store, "run")?;
func.call(store, ())?;
Ok(())
}
#[tokio::test]
async fn async_then_sync_trap() -> Result<()> {
// Test the trapping and capturing the stack with the following sequence of
// calls:
//
// a[async] ---> b[host] ---> c[sync]
drop(env_logger::try_init());
let wat = r#"
(module
(import "" "b" (func $b))
(func $a (export "a")
call $b
)
(func $c (export "c")
unreachable
)
)
"#;
let mut sync_store = Store::new(&Engine::default(), ());
let sync_module = Module::new(sync_store.engine(), wat)?;
let mut sync_linker = Linker::new(sync_store.engine());
sync_linker.func_wrap("", "b", |_caller: Caller<_>| -> () { unreachable!() })?;
let sync_instance = sync_linker.instantiate(&mut sync_store, &sync_module)?;
struct AsyncCtx {
sync_instance: Instance,
sync_store: Store<()>,
}
let mut async_store = Store::new(
&Engine::new(Config::new().async_support(true)).unwrap(),
AsyncCtx {
sync_instance,
sync_store,
},
);
let async_module = Module::new(async_store.engine(), wat)?;
let mut async_linker = Linker::new(async_store.engine());
async_linker.func_wrap("", "b", move |mut caller: Caller<AsyncCtx>| {
log::info!("Called `b`...");
let sync_instance = caller.data().sync_instance;
let sync_store = &mut caller.data_mut().sync_store;
log::info!("Calling `c`...");
let c = sync_instance
.get_typed_func::<(), ()>(&mut *sync_store, "c")
.unwrap();
c.call(sync_store, ())?;
Ok(())
})?;
let async_instance = async_linker
.instantiate_async(&mut async_store, &async_module)
.await?;
log::info!("Calling `a`...");
let a = async_instance
.get_typed_func::<(), ()>(&mut async_store, "a")
.unwrap();
let trap = a.call_async(&mut async_store, ()).await.unwrap_err();
let trace = trap.downcast_ref::<WasmBacktrace>().unwrap().frames();
// We don't support cross-store or cross-engine symbolication currently, so
// the other frames are ignored.
assert_eq!(trace.len(), 1);
assert_eq!(trace[0].func_name(), Some("c"));
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn sync_then_async_trap() -> Result<()> {
// Test the trapping and capturing the stack with the following sequence of
// calls:
//
// a[sync] ---> b[host] ---> c[async]
drop(env_logger::try_init());
let wat = r#"
(module
(import "" "b" (func $b))
(func $a (export "a")
call $b
)
(func $c (export "c")
unreachable
)
)
"#;
let mut async_store = Store::new(&Engine::new(Config::new().async_support(true)).unwrap(), ());
let async_module = Module::new(async_store.engine(), wat)?;
let mut async_linker = Linker::new(async_store.engine());
async_linker.func_wrap("", "b", |_caller: Caller<_>| -> () { unreachable!() })?;
let async_instance = async_linker
.instantiate_async(&mut async_store, &async_module)
.await?;
struct SyncCtx {
async_instance: Instance,
async_store: Store<()>,
}
let mut sync_store = Store::new(
&Engine::default(),
SyncCtx {
async_instance,
async_store,
},
);
let sync_module = Module::new(sync_store.engine(), wat)?;
let mut sync_linker = Linker::new(sync_store.engine());
sync_linker.func_wrap("", "b", move |mut caller: Caller<SyncCtx>| -> Result<()> {
log::info!("Called `b`...");
let async_instance = caller.data().async_instance;
let async_store = &mut caller.data_mut().async_store;
log::info!("Calling `c`...");
let c = async_instance
.get_typed_func::<(), ()>(&mut *async_store, "c")
.unwrap();
tokio::task::block_in_place(|| {
tokio::runtime::Handle::current()
.block_on(async move { c.call_async(async_store, ()).await })
})?;
Ok(())
})?;
let sync_instance = sync_linker.instantiate(&mut sync_store, &sync_module)?;
log::info!("Calling `a`...");
let a = sync_instance
.get_typed_func::<(), ()>(&mut sync_store, "a")
.unwrap();
let trap = a.call(&mut sync_store, ()).unwrap_err();
let trace = trap.downcast_ref::<WasmBacktrace>().unwrap().frames();
// We don't support cross-store or cross-engine symbolication currently, so
// the other frames are ignored.
assert_eq!(trace.len(), 1);
assert_eq!(trace[0].func_name(), Some("c"));
Ok(())
}
#[test]
fn standalone_backtrace() -> Result<()> {
let engine = Engine::default();
let mut store = Store::new(&engine, ());
let trace = WasmBacktrace::capture(&store);
assert!(trace.frames().is_empty());
let module = Module::new(
&engine,
r#"
(module
(import "" "" (func $host))
(func $foo (export "f") call $bar)
(func $bar call $host)
)
"#,
)?;
let func = Func::wrap(&mut store, |cx: Caller<'_, ()>| {
let trace = WasmBacktrace::capture(&cx);
assert_eq!(trace.frames().len(), 2);
let frame1 = &trace.frames()[0];
let frame2 = &trace.frames()[1];
assert_eq!(frame1.func_index(), 2);
assert_eq!(frame1.func_name(), Some("bar"));
assert_eq!(frame2.func_index(), 1);
assert_eq!(frame2.func_name(), Some("foo"));
});
let instance = Instance::new(&mut store, &module, &[func.into()])?;
let f = instance.get_typed_func::<(), ()>(&mut store, "f")?;
f.call(&mut store, ())?;
Ok(())
}
#[test]
#[allow(deprecated)]
fn standalone_backtrace_disabled() -> Result<()> {
let mut config = Config::new();
config.wasm_backtrace(false);
let engine = Engine::new(&config)?;
let mut store = Store::new(&engine, ());
let module = Module::new(
&engine,
r#"
(module
(import "" "" (func $host))
(func $foo (export "f") call $bar)
(func $bar call $host)
)
"#,
)?;
let func = Func::wrap(&mut store, |cx: Caller<'_, ()>| {
let trace = WasmBacktrace::capture(&cx);
assert_eq!(trace.frames().len(), 0);
let trace = WasmBacktrace::force_capture(&cx);
assert_eq!(trace.frames().len(), 2);
});
let instance = Instance::new(&mut store, &module, &[func.into()])?;
let f = instance.get_typed_func::<(), ()>(&mut store, "f")?;
f.call(&mut store, ())?;
Ok(())
}
#[test]
fn host_return_error_no_backtrace() -> Result<()> {
let mut config = Config::new();
config.wasm_backtrace(false);
let engine = Engine::new(&config)?;
let mut store = Store::new(&engine, ());
let module = Module::new(
&engine,
r#"
(module
(import "" "" (func $host))
(func $foo (export "f") call $bar)
(func $bar call $host)
)
"#,
)?;
let func = Func::wrap(&mut store, |_cx: Caller<'_, ()>| -> Result<()> {
bail!("test")
});
let instance = Instance::new(&mut store, &module, &[func.into()])?;
let f = instance.get_typed_func::<(), ()>(&mut store, "f")?;
assert!(f.call(&mut store, ()).is_err());
Ok(())
}
#[test]
fn div_plus_load_reported_right() -> Result<()> {
let engine = Engine::default();
let mut store = Store::new(&engine, ());
let module = Module::new(
&engine,
r#"
(module
(memory (export "memory") 1)
(func (export "i32.div_s") (param i32 i32) (result i32)
(i32.div_s (local.get 0) (i32.load (local.get 1))))
(func (export "i32.div_u") (param i32 i32) (result i32)
(i32.div_u (local.get 0) (i32.load (local.get 1))))
(func (export "i32.rem_s") (param i32 i32) (result i32)
(i32.rem_s (local.get 0) (i32.load (local.get 1))))
(func (export "i32.rem_u") (param i32 i32) (result i32)
(i32.rem_u (local.get 0) (i32.load (local.get 1))))
)
"#,
)?;
let instance = Instance::new(&mut store, &module, &[])?;
let memory = instance.get_memory(&mut store, "memory").unwrap();
let i32_div_s = instance.get_typed_func::<(i32, i32), i32>(&mut store, "i32.div_s")?;
let i32_div_u = instance.get_typed_func::<(u32, u32), u32>(&mut store, "i32.div_u")?;
let i32_rem_s = instance.get_typed_func::<(i32, i32), i32>(&mut store, "i32.rem_s")?;
let i32_rem_u = instance.get_typed_func::<(u32, u32), u32>(&mut store, "i32.rem_u")?;
memory.write(&mut store, 0, &1i32.to_le_bytes()).unwrap();
memory.write(&mut store, 4, &0i32.to_le_bytes()).unwrap();
memory.write(&mut store, 8, &(-1i32).to_le_bytes()).unwrap();
assert_eq!(i32_div_s.call(&mut store, (100, 0))?, 100);
assert_eq!(i32_div_u.call(&mut store, (101, 0))?, 101);
assert_eq!(i32_rem_s.call(&mut store, (102, 0))?, 0);
assert_eq!(i32_rem_u.call(&mut store, (103, 0))?, 0);
assert_trap(
i32_div_s.call(&mut store, (100, 4)),
Trap::IntegerDivisionByZero,
);
assert_trap(
i32_div_u.call(&mut store, (100, 4)),
Trap::IntegerDivisionByZero,
);
assert_trap(
i32_rem_s.call(&mut store, (100, 4)),
Trap::IntegerDivisionByZero,
);
assert_trap(
i32_rem_u.call(&mut store, (100, 4)),
Trap::IntegerDivisionByZero,
);
assert_trap(
i32_div_s.call(&mut store, (i32::MIN, 8)),
Trap::IntegerOverflow,
);
assert_eq!(i32_rem_s.call(&mut store, (i32::MIN, 8))?, 0);
assert_trap(
i32_div_s.call(&mut store, (100, 100_000)),
Trap::MemoryOutOfBounds,
);
assert_trap(
i32_div_u.call(&mut store, (100, 100_000)),
Trap::MemoryOutOfBounds,
);
assert_trap(
i32_rem_s.call(&mut store, (100, 100_000)),
Trap::MemoryOutOfBounds,
);
assert_trap(
i32_rem_u.call(&mut store, (100, 100_000)),
Trap::MemoryOutOfBounds,
);
return Ok(());
#[track_caller]
fn assert_trap<T>(result: Result<T>, expected: Trap) {
match result {
Ok(_) => panic!("expected failure"),
Err(e) => {
if let Some(code) = e.downcast_ref::<Trap>() {
if *code == expected {
return;
}
}
panic!("unexpected error {e:?}");
}
}
}
}
#[test]
fn wasm_fault_address_reported_by_default() -> Result<()> {
let engine = Engine::default();
let mut store = Store::new(&engine, ());
let module = Module::new(
&engine,
r#"
(module
(memory 1)
(func $start
i32.const 0xdeadbeef
i32.load
drop)
(start $start)
)
"#,
)?;
let err = Instance::new(&mut store, &module, &[]).unwrap_err();
// NB: at this time there's no programmatic access to the fault address
// because it's not always available for load/store traps. Only static
// memories on 32-bit have this information, but bounds-checked memories use
// manual trapping instructions and otherwise don't have a means of
// communicating the faulting address at this time.
//
// It looks like the exact reported fault address may not be deterministic,
// so assert that we have the right error message, but not the exact
// address.
let err = format!("{err:?}");
assert!(
err.contains("memory fault at wasm address ")
&& err.contains(" in linear memory of size 0x10000"),
"bad error: {err}"
);
Ok(())
}
#[cfg(target_arch = "x86_64")]
#[test]
fn wasm_fault_address_reported_from_mpk_protected_memory() -> Result<()> {
// Trigger the case where an OOB memory access causes a segfault and the
// store attempts to convert it into a `WasmFault`, calculating the Wasm
// address from the raw faulting address. Previously, a store could not do
// this calculation for MPK-protected, causing an abort.
let mut pool = crate::small_pool_config();
pool.total_memories(16);
pool.memory_protection_keys(MpkEnabled::Auto);
let mut config = Config::new();
config.allocation_strategy(InstanceAllocationStrategy::Pooling(pool));
let engine = Engine::new(&config)?;
let mut store = Store::new(&engine, ());
let module = Module::new(
&engine,
r#"
(module
(memory 1)
(func $start
i32.const 0xdeadbeef
i32.load
drop)
(start $start)
)
"#,
)?;
let err = Instance::new(&mut store, &module, &[]).unwrap_err();
// We expect an error here, not an abort; but we also check that the store
// can now calculate the correct Wasm address. If this test is failing with
// an abort, use `--nocapture` to see more details.
let err = format!("{err:?}");
assert!(err.contains("0xdeadbeef"), "bad error: {err}");
Ok(())
}
#[test]
fn trap_with_array_to_wasm_stack_args() -> Result<()> {
let engine = Engine::default();
let mut store = Store::new(&engine, ());
let module = Module::new(
&engine,
r#"
(module
(func $trap
unreachable)
(func $run (param i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64)
call $trap)
(export "run" (func $run))
)
"#,
)?;
let instance = Instance::new(&mut store, &module, &[])?;
let run = instance.get_func(&mut store, "run").unwrap();
let err = run
.call(
&mut store,
&[
Val::I64(0),
Val::I64(0),
Val::I64(0),
Val::I64(0),
Val::I64(0),
Val::I64(0),
Val::I64(0),
Val::I64(0),
Val::I64(0),
Val::I64(0),
Val::I64(0),
Val::I64(0),
Val::I64(0),
Val::I64(0),
Val::I64(0),
],
&mut [],
)
.unwrap_err();
assert!(err.is::<Trap>());
let trace = err.downcast_ref::<WasmBacktrace>().unwrap();
assert_eq!(trace.frames().len(), 2);
assert_eq!(trace.frames()[0].func_name(), Some("trap"));
assert_eq!(trace.frames()[1].func_name(), Some("run"));
Ok(())
}
#[test]
fn trap_with_native_to_wasm_stack_args() -> Result<()> {
let engine = Engine::default();
let mut store = Store::new(&engine, ());
let module = Module::new(
&engine,
r#"
(module
(func $trap
unreachable)
(func $run (param i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64)
call $trap)
(export "run" (func $run))
)
"#,
)?;
let instance = Instance::new(&mut store, &module, &[])?;
let run = instance.get_func(&mut store, "run").unwrap();
let err = run
.typed::<(
i64,
i64,
i64,
i64,
i64,
i64,
i64,
i64,
i64,
i64,
i64,
i64,
i64,
i64,
i64,
), ()>(&mut store)?
.call(&mut store, (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
.unwrap_err();
assert!(err.is::<Trap>());
let trace = err.downcast_ref::<WasmBacktrace>().unwrap();
assert_eq!(trace.frames().len(), 2);
assert_eq!(trace.frames()[0].func_name(), Some("trap"));
assert_eq!(trace.frames()[1].func_name(), Some("run"));
Ok(())
}
#[test]
fn dont_see_stale_stack_walking_registers() -> Result<()> {
let engine = Engine::default();
let module = Module::new(
&engine,
r#"
(module
(import "" "host_start" (func $host_start))
(import "" "host_get_trap" (func $host_get_trap))
(export "get_trap" (func $host_get_trap))
;; We enter and exit Wasm, which saves registers in the
;; `VMRuntimeLimits`. Later, when we call a re-exported host
;; function, we should not accidentally reuse those saved
;; registers.
(start $start)
(func $start
(call $host_start)
)
)
"#,
)?;
let mut store = Store::new(&engine, ());
let mut linker = Linker::new(&engine);
let host_start = Func::new(
&mut store,
FuncType::new(&engine, [], []),
|_caller, _args, _results| Ok(()),
);
linker.define(&store, "", "host_start", host_start)?;
let host_get_trap = Func::new(
&mut store,
FuncType::new(&engine, [], []),
|_caller, _args, _results| Err(anyhow::anyhow!("trap!!!")),
);
linker.define(&store, "", "host_get_trap", host_get_trap)?;
let instance = linker.instantiate(&mut store, &module)?;
let get_trap = instance.get_func(&mut store, "get_trap").unwrap();
let err = get_trap.call(&mut store, &[], &mut []).unwrap_err();
assert!(err.to_string().contains("trap!!!"));
Ok(())
}
#[test]
fn same_module_multiple_stores() -> Result<()> {
let _ = env_logger::try_init();
let engine = Engine::default();
let module = Module::new(
&engine,
r#"
(module
(import "" "f" (func $f))
(import "" "call_ref" (func $call_ref (param funcref)))
(global $g (mut i32) (i32.const 0))
(func $a (export "a")
call $b
)
(func $b
call $c
)
(func $c
global.get $g
if
call $f
else
i32.const 1
global.set $g
ref.func $a
call $call_ref
end
)
)
"#,
)?;
let stacks = Arc::new(Mutex::new(vec![]));
let mut store3 = Store::new(&engine, ());
let f3 = Func::new(&mut store3, FuncType::new(&engine, [], []), {
let stacks = stacks.clone();
move |caller, _params, _results| {
stacks
.lock()
.unwrap()
.push(WasmBacktrace::force_capture(caller));
Ok(())
}
});
let call_ref3 = Func::wrap(&mut store3, |caller: Caller<'_, _>, f: Option<Func>| {
f.unwrap().call(caller, &[], &mut [])
});
let instance3 = Instance::new(&mut store3, &module, &[f3.into(), call_ref3.into()])?;
let mut store2 = Store::new(&engine, store3);
let f2 = Func::new(&mut store2, FuncType::new(&engine, [], []), {
let stacks = stacks.clone();
move |mut caller, _params, _results| {
stacks
.lock()
.unwrap()
.push(WasmBacktrace::force_capture(&mut caller));
instance3
.get_typed_func::<(), ()>(caller.data_mut(), "a")
.unwrap()
.call(caller.data_mut(), ())
.unwrap();
Ok(())
}
});
let call_ref2 = Func::wrap(&mut store2, |caller: Caller<'_, _>, f: Option<Func>| {
f.unwrap().call(caller, &[], &mut [])
});
let instance2 = Instance::new(&mut store2, &module, &[f2.into(), call_ref2.into()])?;
let mut store1 = Store::new(&engine, store2);
let f1 = Func::new(&mut store1, FuncType::new(&engine, [], []), {
let stacks = stacks.clone();
move |mut caller, _params, _results| {
stacks
.lock()
.unwrap()
.push(WasmBacktrace::force_capture(&mut caller));
instance2
.get_typed_func::<(), ()>(caller.data_mut(), "a")
.unwrap()
.call(caller.data_mut(), ())
.unwrap();
Ok(())
}
});
let call_ref1 = Func::wrap(&mut store1, |caller: Caller<'_, _>, f: Option<Func>| {
f.unwrap().call(caller, &[], &mut [])
});
let instance1 = Instance::new(&mut store1, &module, &[f1.into(), call_ref1.into()])?;
instance1
.get_typed_func::<(), ()>(&mut store1, "a")?
.call(&mut store1, ())?;
let expected_stacks = vec![
// [f1, c1, b1, a1, call_ref1, c1, b1, a1]
vec!["c", "b", "a", "c", "b", "a"],
// [f2, c2, b2, a2, call_ref2, c2, b2, a2, f1, c1, b1, a1, call_ref1, c1, b1, a1]
vec!["c", "b", "a", "c", "b", "a"],
// [f3, c3, b3, a3, call_ref3, c3, b3, a3, f2, c2, b2, a2, call_ref2, c2, b2, a2, f1, c1, b1, a1, call_ref1, c1, b1, a1]
vec!["c", "b", "a", "c", "b", "a"],
];
eprintln!("expected = {expected_stacks:#?}");
let actual_stacks = stacks.lock().unwrap();
eprintln!("actual = {actual_stacks:#?}");
assert_eq!(actual_stacks.len(), expected_stacks.len());
for (expected_stack, actual_stack) in expected_stacks.into_iter().zip(actual_stacks.iter()) {
assert_eq!(expected_stack.len(), actual_stack.frames().len());
for (expected_frame, actual_frame) in expected_stack.into_iter().zip(actual_stack.frames())
{
assert_eq!(actual_frame.func_name(), Some(expected_frame));
}
}
Ok(())
}
#[test]
fn async_stack_size_ignored_if_disabled() -> Result<()> {
let mut config = Config::new();
config.async_support(false);
config.max_wasm_stack(8 << 20);
Engine::new(&config)?;
Ok(())
}
#[wasmtime_test(wasm_features(tail_call))]
fn tail_call_to_imported_function(config: &mut Config) -> Result<()> {
let engine = Engine::new(config)?;
let module = Module::new(
&engine,
r#"
(module
(import "" "" (func (result i32)))
(func (export "run") (result i32)
return_call 0
)
)
"#,
)?;
let mut store = Store::new(&engine, ());
let host_func = Func::wrap(&mut store, || -> Result<i32> { bail!("whoopsie") });
let instance = Instance::new(&mut store, &module, &[host_func.into()])?;
let run = instance.get_typed_func::<(), i32>(&mut store, "run")?;
let err = run.call(&mut store, ()).unwrap_err();
assert!(err.to_string().contains("whoopsie"));
Ok(())
}
#[wasmtime_test(wasm_features(tail_call))]
fn tail_call_to_imported_function_in_start_function(config: &mut Config) -> Result<()> {
let engine = Engine::new(config)?;
let module = Module::new(
&engine,
r#"
(module
(import "" "" (func))
(func $f
return_call 0
)
(start $f)
)
"#,
)?;
let mut store = Store::new(&engine, ());
let host_func = Func::wrap(&mut store, || -> Result<()> { bail!("whoopsie") });
let err = Instance::new(&mut store, &module, &[host_func.into()]).unwrap_err();
assert!(err.to_string().contains("whoopsie"));
Ok(())
}
#[wasmtime_test(wasm_features(tail_call, function_references))]
fn return_call_ref_to_imported_function(config: &mut Config) -> Result<()> {
let engine = Engine::new(config)?;
let module = Module::new(
&engine,
r#"
(module
(type (func (result i32)))
(func (export "run") (param (ref 0)) (result i32)
(return_call_ref 0 (local.get 0))
)
)
"#,
)?;
let mut store = Store::new(&engine, ());
let host_func = Func::wrap(&mut store, || -> Result<i32> { bail!("whoopsie") });
let instance = Instance::new(&mut store, &module, &[])?;
let run = instance.get_typed_func::<Func, i32>(&mut store, "run")?;
let err = run.call(&mut store, host_func).unwrap_err();
assert!(err.to_string().contains("whoopsie"));
Ok(())
}
#[wasmtime_test(wasm_features(tail_call, function_references))]
fn return_call_indirect_to_imported_function(config: &mut Config) -> Result<()> {
let engine = Engine::new(config)?;
let module = Module::new(
&engine,
r#"
(module
(import "" "" (func (result i32)))
(table 1 funcref (ref.func 0))
(func (export "run") (result i32)
(return_call_indirect (result i32) (i32.const 0))
)
)
"#,
)?;
let mut store = Store::new(&engine, ());
let host_func = Func::wrap(&mut store, || -> Result<i32> { bail!("whoopsie") });
let instance = Instance::new(&mut store, &module, &[host_func.into()])?;
let run = instance.get_typed_func::<(), i32>(&mut store, "run")?;
let err = run.call(&mut store, ()).unwrap_err();
assert!(err.to_string().contains("whoopsie"));
Ok(())
}
|