1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217
|
//! End-to-end tests for `libbpf-rs`.
mod common;
use std::collections::HashMap;
use std::collections::HashSet;
use std::env::current_exe;
use std::ffi::c_int;
use std::ffi::c_void;
use std::ffi::OsStr;
use std::fs;
use std::hint;
use std::io;
use std::io::Read;
use std::mem::size_of;
use std::mem::size_of_val;
use std::os::unix::io::AsFd;
use std::path::Path;
use std::path::PathBuf;
use std::ptr;
use std::ptr::addr_of;
use std::slice;
use std::sync::atomic::AtomicI32;
use std::sync::atomic::Ordering;
use std::sync::mpsc::channel;
use std::time::Duration;
use libbpf_rs::num_possible_cpus;
use libbpf_rs::AsRawLibbpf;
use libbpf_rs::Iter;
use libbpf_rs::KprobeMultiOpts;
use libbpf_rs::KprobeOpts;
use libbpf_rs::Linker;
use libbpf_rs::MapCore;
use libbpf_rs::MapFlags;
use libbpf_rs::MapHandle;
use libbpf_rs::MapInfo;
use libbpf_rs::MapType;
use libbpf_rs::Object;
use libbpf_rs::ObjectBuilder;
use libbpf_rs::Program;
use libbpf_rs::ProgramInput;
use libbpf_rs::ProgramType;
use libbpf_rs::RawTracepointOpts;
use libbpf_rs::TracepointCategory;
use libbpf_rs::TracepointOpts;
use libbpf_rs::UprobeOpts;
use libbpf_rs::UsdtOpts;
use libbpf_rs::UserRingBuffer;
use plain::Plain;
use probe::probe;
use scopeguard::defer;
use tempfile::NamedTempFile;
use test_tag::tag;
use crate::common::get_map;
use crate::common::get_map_mut;
use crate::common::get_prog_mut;
use crate::common::get_symbol_offset;
use crate::common::get_test_object;
use crate::common::get_test_object_path;
use crate::common::open_test_object;
use crate::common::with_ringbuffer;
#[tag(root)]
#[test]
fn test_object_build_and_load() {
get_test_object("runqslower.bpf.o");
}
#[test]
fn test_object_build_from_memory() {
let obj_path = get_test_object_path("runqslower.bpf.o");
let contents = fs::read(obj_path).expect("failed to read object file");
let mut builder = ObjectBuilder::default();
let obj = builder
.name("memory name")
.unwrap()
.open_memory(&contents)
.expect("failed to build object");
let name = obj.name().expect("failed to get object name");
assert!(name == "memory name");
let obj = unsafe { Object::from_ptr(obj.take_ptr()) };
let name = obj.name().expect("failed to get object name");
assert!(name == "memory name");
}
#[test]
fn test_object_build_from_memory_empty_name() {
let obj_path = get_test_object_path("runqslower.bpf.o");
let contents = fs::read(obj_path).expect("failed to read object file");
let mut builder = ObjectBuilder::default();
let obj = builder
.name("")
.unwrap()
.open_memory(&contents)
.expect("failed to build object");
let name = obj.name().expect("failed to get object name");
assert!(name.is_empty());
let obj = unsafe { Object::from_ptr(obj.take_ptr()) };
let name = obj.name().expect("failed to get object name");
assert!(name.is_empty());
}
/// Check that loading an object from an empty file fails as expected.
#[tag(root)]
#[test]
fn test_object_load_invalid() {
let empty_file = NamedTempFile::new().unwrap();
let _err = ObjectBuilder::default()
.debug(true)
.open_file(empty_file.path())
.unwrap_err();
}
#[test]
fn test_object_name() {
let obj_path = get_test_object_path("runqslower.bpf.o");
let mut builder = ObjectBuilder::default();
builder.name("test name").unwrap();
let obj = builder.open_file(obj_path).expect("failed to build object");
let obj_name = obj.name().expect("failed to get object name");
assert!(obj_name == "test name");
}
#[tag(root)]
#[test]
fn test_object_maps() {
let mut obj = get_test_object("runqslower.bpf.o");
let _map = get_map_mut(&mut obj, "start");
let _map = get_map_mut(&mut obj, "events");
assert!(!obj.maps().any(|map| map.name() == OsStr::new("asdf")));
}
#[tag(root)]
#[test]
fn test_object_maps_iter() {
let obj = get_test_object("runqslower.bpf.o");
for map in obj.maps() {
eprintln!("{:?}", map.name());
}
// This will include .rodata and .bss, so our expected count is 4, not 2
assert!(obj.maps().count() == 4);
}
#[tag(root)]
#[test]
fn test_object_map_key_value_size() {
let mut obj = get_test_object("runqslower.bpf.o");
let start = get_map_mut(&mut obj, "start");
assert!(start.lookup(&[1, 2, 3, 4, 5], MapFlags::empty()).is_err());
assert!(start.delete(&[1]).is_err());
assert!(start.lookup_and_delete(&[1, 2, 3, 4, 5]).is_err());
assert!(start
.update(&[1, 2, 3, 4, 5], &[1], MapFlags::empty())
.is_err());
}
#[tag(root)]
#[test]
fn test_object_map_update_batch() {
let mut obj = get_test_object("runqslower.bpf.o");
let start = get_map_mut(&mut obj, "start");
let key1 = 1u32.to_ne_bytes();
let key2 = 2u32.to_ne_bytes();
let key3 = 3u32.to_ne_bytes();
let key4 = 4u32.to_ne_bytes();
let value1 = 369u64.to_ne_bytes();
let value2 = 258u64.to_ne_bytes();
let value3 = 147u64.to_ne_bytes();
let value4 = 159u64.to_ne_bytes();
let batch_key1 = key1.into_iter().chain(key2).collect::<Vec<_>>();
let batch_value1 = value1.into_iter().chain(value2).collect::<Vec<_>>();
let batch_key2 = key2.into_iter().chain(key3).chain(key4).collect::<Vec<_>>();
let batch_value2 = value2
.into_iter()
.chain(value3)
.chain(value4)
.collect::<Vec<_>>();
// Update batch with wrong key size
assert!(start
.update_batch(
&[1, 2, 3],
&batch_value1,
2,
MapFlags::ANY,
MapFlags::NO_EXIST
)
.is_err());
// Update batch with wrong value size
assert!(start
.update_batch(
&batch_key1,
&[1, 2, 3],
2,
MapFlags::ANY,
MapFlags::NO_EXIST
)
.is_err());
// Update batch with wrong count.
assert!(start
.update_batch(
&batch_key1,
&batch_value1,
1,
MapFlags::ANY,
MapFlags::NO_EXIST
)
.is_err());
// Update batch with 1 key.
assert!(start
.update_batch(&key1, &value1, 1, MapFlags::ANY, MapFlags::NO_EXIST)
.is_ok());
// Update batch with multiple keys.
assert!(start
.update_batch(
&batch_key2,
&batch_value2,
3,
MapFlags::ANY,
MapFlags::NO_EXIST
)
.is_ok());
// Update batch with existing keys.
assert!(start
.update_batch(
&batch_key2,
&batch_value2,
3,
MapFlags::NO_EXIST,
MapFlags::NO_EXIST
)
.is_err());
}
#[tag(root)]
#[test]
fn test_object_map_lookup_batch() {
let mut obj = get_test_object("runqslower.bpf.o");
let start = get_map_mut(&mut obj, "start");
let data = HashMap::from([
(1u32, 9999u64),
(2u32, 42u64),
(3u32, 18u64),
(4u32, 1337u64),
]);
for (key, val) in data.iter() {
assert!(start
.update(&key.to_ne_bytes(), &val.to_ne_bytes(), MapFlags::ANY)
.is_ok());
}
let elems = start
.lookup_batch(2, MapFlags::ANY, MapFlags::ANY)
.expect("failed to lookup batch")
.collect::<Vec<_>>();
assert_eq!(elems.len(), 4);
for (key, val) in elems.into_iter() {
let key = u32::from_ne_bytes(key.try_into().unwrap());
let val = u64::from_ne_bytes(val.try_into().unwrap());
assert_eq!(val, data[&key]);
}
// test lookup with batch size larger than the number of keys
let elems = start
.lookup_batch(5, MapFlags::ANY, MapFlags::ANY)
.expect("failed to lookup batch")
.collect::<Vec<_>>();
assert_eq!(elems.len(), 4);
for (key, val) in elems.into_iter() {
let key = u32::from_ne_bytes(key.try_into().unwrap());
let val = u64::from_ne_bytes(val.try_into().unwrap());
assert_eq!(val, data[&key]);
}
// test lookup and delete with batch size that does not divide total count
let elems = start
.lookup_and_delete_batch(3, MapFlags::ANY, MapFlags::ANY)
.expect("failed to lookup batch")
.collect::<Vec<_>>();
assert_eq!(elems.len(), 4);
for (key, val) in elems.into_iter() {
let key = u32::from_ne_bytes(key.try_into().unwrap());
let val = u64::from_ne_bytes(val.try_into().unwrap());
assert_eq!(val, data[&key]);
}
// Map should be empty now.
assert!(start.keys().collect::<Vec<_>>().is_empty())
}
#[tag(root)]
#[test]
fn test_object_map_delete_batch() {
let mut obj = get_test_object("runqslower.bpf.o");
let start = get_map_mut(&mut obj, "start");
let key1 = 1u32.to_ne_bytes();
assert!(start
.update(&key1, &9999u64.to_ne_bytes(), MapFlags::ANY)
.is_ok());
let key2 = 2u32.to_ne_bytes();
assert!(start
.update(&key2, &42u64.to_ne_bytes(), MapFlags::ANY)
.is_ok());
let key3 = 3u32.to_ne_bytes();
assert!(start
.update(&key3, &18u64.to_ne_bytes(), MapFlags::ANY)
.is_ok());
let key4 = 4u32.to_ne_bytes();
assert!(start
.update(&key4, &1337u64.to_ne_bytes(), MapFlags::ANY)
.is_ok());
// Delete 1 incomplete key.
assert!(start
.delete_batch(&[0, 0, 1], 1, MapFlags::empty(), MapFlags::empty())
.is_err());
// Delete keys with wrong count.
assert!(start
.delete_batch(&key4, 2, MapFlags::empty(), MapFlags::empty())
.is_err());
// Delete 1 key successfully.
assert!(start
.delete_batch(&key4, 1, MapFlags::empty(), MapFlags::empty())
.is_ok());
// Delete remaining 3 keys.
let keys = key1.into_iter().chain(key2).chain(key3).collect::<Vec<_>>();
assert!(start
.delete_batch(&keys, 3, MapFlags::empty(), MapFlags::empty())
.is_ok());
// Map should be empty now.
assert!(start.keys().collect::<Vec<_>>().is_empty())
}
/// Test whether `MapInfo` works properly
#[tag(root)]
#[test]
pub fn test_map_info() {
let opts = libbpf_sys::bpf_map_create_opts {
sz: size_of::<libbpf_sys::bpf_map_create_opts>() as libbpf_sys::size_t,
map_flags: libbpf_sys::BPF_ANY,
btf_fd: 0,
btf_key_type_id: 0,
btf_value_type_id: 0,
btf_vmlinux_value_type_id: 0,
inner_map_fd: 0,
map_extra: 0,
numa_node: 0,
map_ifindex: 0,
// bpf_map_create_opts might have padding fields on some platform
..Default::default()
};
let map = MapHandle::create(MapType::Hash, Some("simple_map"), 8, 64, 1024, &opts).unwrap();
let map_info = MapInfo::new(map.as_fd()).unwrap();
let name_received = map_info.name().unwrap();
assert_eq!(name_received, "simple_map");
assert_eq!(map_info.map_type(), MapType::Hash);
assert_eq!(map_info.flags() & MapFlags::ANY, MapFlags::ANY);
let map_info = &map_info.info;
assert_eq!(map_info.key_size, 8);
assert_eq!(map_info.value_size, 64);
assert_eq!(map_info.max_entries, 1024);
assert_eq!(map_info.btf_id, 0);
assert_eq!(map_info.btf_key_type_id, 0);
assert_eq!(map_info.btf_value_type_id, 0);
assert_eq!(map_info.btf_vmlinux_value_type_id, 0);
assert_eq!(map_info.map_extra, 0);
assert_eq!(map_info.ifindex, 0);
}
#[tag(root)]
#[test]
fn test_object_percpu_lookup() {
let mut obj = get_test_object("percpu_map.bpf.o");
let map = get_map_mut(&mut obj, "percpu_map");
let res = map
.lookup_percpu(&(0_u32).to_ne_bytes(), MapFlags::ANY)
.expect("failed to lookup")
.expect("failed to find value for key");
assert_eq!(
res.len(),
num_possible_cpus().expect("must be one value per cpu")
);
assert_eq!(res[0].len(), size_of::<u32>());
}
#[tag(root)]
#[test]
fn test_object_percpu_invalid_lookup_fn() {
let mut obj = get_test_object("percpu_map.bpf.o");
let map = get_map_mut(&mut obj, "percpu_map");
assert!(map.lookup(&(0_u32).to_ne_bytes(), MapFlags::ANY).is_err());
}
#[tag(root)]
#[test]
fn test_object_percpu_update() {
let mut obj = get_test_object("percpu_map.bpf.o");
let map = get_map_mut(&mut obj, "percpu_map");
let key = (0_u32).to_ne_bytes();
let mut vals: Vec<Vec<u8>> = Vec::new();
for i in 0..num_possible_cpus().unwrap() {
vals.push((i as u32).to_ne_bytes().to_vec());
}
map.update_percpu(&key, &vals, MapFlags::ANY)
.expect("failed to update map");
let res = map
.lookup_percpu(&key, MapFlags::ANY)
.expect("failed to lookup")
.expect("failed to find value for key");
assert_eq!(vals, res);
}
#[tag(root)]
#[test]
fn test_object_percpu_invalid_update_fn() {
let mut obj = get_test_object("percpu_map.bpf.o");
let map = get_map_mut(&mut obj, "percpu_map");
let key = (0_u32).to_ne_bytes();
let val = (1_u32).to_ne_bytes().to_vec();
assert!(map.update(&key, &val, MapFlags::ANY).is_err());
}
#[tag(root)]
#[test]
fn test_object_percpu_lookup_update() {
let mut obj = get_test_object("percpu_map.bpf.o");
let map = get_map_mut(&mut obj, "percpu_map");
let key = (0_u32).to_ne_bytes();
let mut res = map
.lookup_percpu(&key, MapFlags::ANY)
.expect("failed to lookup")
.expect("failed to find value for key");
for e in res.iter_mut() {
e[0] &= 0xf0;
}
map.update_percpu(&key, &res, MapFlags::ANY)
.expect("failed to update after first lookup");
let res2 = map
.lookup_percpu(&key, MapFlags::ANY)
.expect("failed to lookup")
.expect("failed to find value for key");
assert_eq!(res, res2);
}
#[tag(root)]
#[test]
fn test_object_map_empty_lookup() {
let mut obj = get_test_object("runqslower.bpf.o");
let start = get_map_mut(&mut obj, "start");
assert!(start
.lookup(&[1, 2, 3, 4], MapFlags::empty())
.expect("err in map lookup")
.is_none());
}
/// Test CRUD operations on map of type queue.
#[tag(root)]
#[test]
fn test_object_map_queue_crud() {
let mut obj = get_test_object("tracepoint.bpf.o");
let queue = get_map_mut(&mut obj, "queue");
let key: [u8; 0] = [];
let value1 = 42u32.to_ne_bytes();
let value2 = 43u32.to_ne_bytes();
// Test queue, FIFO expected
queue
.update(&key, &value1, MapFlags::ANY)
.expect("failed to update in queue");
queue
.update(&key, &value2, MapFlags::ANY)
.expect("failed to update in queue");
let mut val = queue
.lookup(&key, MapFlags::ANY)
.expect("failed to peek the queue")
.expect("failed to retrieve value");
assert_eq!(val.len(), 4);
assert_eq!(&val, &value1);
val = queue
.lookup_and_delete(&key)
.expect("failed to pop from queue")
.expect("failed to retrieve value");
assert_eq!(val.len(), 4);
assert_eq!(&val, &value1);
val = queue
.lookup_and_delete(&key)
.expect("failed to pop from queue")
.expect("failed to retrieve value");
assert_eq!(val.len(), 4);
assert_eq!(&val, &value2);
assert!(queue
.lookup_and_delete(&key)
.expect("failed to pop from queue")
.is_none());
}
/// Test CRUD operations on map of type bloomfilter.
#[tag(root)]
#[test]
fn test_object_map_bloom_filter_crud() {
let mut obj = get_test_object("tracepoint.bpf.o");
let bloom_filter = get_map_mut(&mut obj, "bloom_filter");
let key: [u8; 0] = [];
let value1 = 1337u32.to_ne_bytes();
let value2 = 2674u32.to_ne_bytes();
bloom_filter
.update(&key, &value1, MapFlags::ANY)
.expect("failed to add entry value1 to bloom filter");
bloom_filter
.update(&key, &value2, MapFlags::ANY)
.expect("failed to add entry value2 in bloom filter");
// Non empty keys should result in an error
bloom_filter
.update(&value1, &value1, MapFlags::ANY)
.expect_err("Non empty key should return an error");
for inserted_value in [value1, value2] {
let val = bloom_filter
.lookup_bloom_filter(&inserted_value)
.expect("failed retrieve item from bloom filter");
assert!(val);
}
// Test non existing element
let enoent_found = bloom_filter
.lookup_bloom_filter(&[1, 2, 3, 4])
.expect("failed retrieve item from bloom filter");
assert!(!enoent_found);
// Calling lookup should result in an error
bloom_filter
.lookup(&[1, 2, 3, 4], MapFlags::ANY)
.expect_err("lookup should fail since we should use lookup_bloom_filter");
// Deleting should not be possible
bloom_filter
.lookup_and_delete(&key)
.expect_err("Expect delete to fail");
}
/// Test CRUD operations on map of type stack.
#[tag(root)]
#[test]
fn test_object_map_stack_crud() {
let mut obj = get_test_object("tracepoint.bpf.o");
let stack = get_map_mut(&mut obj, "stack");
let key: [u8; 0] = [];
let value1 = 1337u32.to_ne_bytes();
let value2 = 2674u32.to_ne_bytes();
stack
.update(&key, &value1, MapFlags::ANY)
.expect("failed to update in stack");
stack
.update(&key, &value2, MapFlags::ANY)
.expect("failed to update in stack");
let mut val = stack
.lookup(&key, MapFlags::ANY)
.expect("failed to pop from stack")
.expect("failed to retrieve value");
assert_eq!(val.len(), 4);
assert_eq!(&val, &value2);
val = stack
.lookup_and_delete(&key)
.expect("failed to pop from stack")
.expect("failed to retrieve value");
assert_eq!(val.len(), 4);
assert_eq!(&val, &value2);
val = stack
.lookup_and_delete(&key)
.expect("failed to pop from stack")
.expect("failed to retrieve value");
assert_eq!(val.len(), 4);
assert_eq!(&val, &value1);
assert!(stack
.lookup_and_delete(&key)
.expect("failed to pop from stack")
.is_none());
}
#[tag(root)]
#[test]
fn test_object_map_mutation() {
let mut obj = get_test_object("runqslower.bpf.o");
let start = get_map_mut(&mut obj, "start");
start
.update(&[1, 2, 3, 4], &[1, 2, 3, 4, 5, 6, 7, 8], MapFlags::empty())
.expect("failed to write");
let val = start
.lookup(&[1, 2, 3, 4], MapFlags::empty())
.expect("failed to read map")
.expect("failed to find key");
assert_eq!(val.len(), 8);
assert_eq!(val, &[1, 2, 3, 4, 5, 6, 7, 8]);
start.delete(&[1, 2, 3, 4]).expect("failed to delete key");
assert!(start
.lookup(&[1, 2, 3, 4], MapFlags::empty())
.expect("failed to read map")
.is_none());
}
#[tag(root)]
#[test]
fn test_object_map_lookup_flags() {
let mut obj = get_test_object("runqslower.bpf.o");
let start = get_map_mut(&mut obj, "start");
start
.update(&[1, 2, 3, 4], &[1, 2, 3, 4, 5, 6, 7, 8], MapFlags::NO_EXIST)
.expect("failed to write");
assert!(start
.update(&[1, 2, 3, 4], &[1, 2, 3, 4, 5, 6, 7, 8], MapFlags::NO_EXIST)
.is_err());
}
#[tag(root)]
#[test]
fn test_object_map_key_iter() {
let mut obj = get_test_object("runqslower.bpf.o");
let start = get_map_mut(&mut obj, "start");
let key1 = vec![1, 2, 3, 4];
let key2 = vec![1, 2, 3, 5];
let key3 = vec![1, 2, 3, 6];
start
.update(&key1, &[1, 2, 3, 4, 5, 6, 7, 8], MapFlags::empty())
.expect("failed to write");
start
.update(&key2, &[1, 2, 3, 4, 5, 6, 7, 8], MapFlags::empty())
.expect("failed to write");
start
.update(&key3, &[1, 2, 3, 4, 5, 6, 7, 8], MapFlags::empty())
.expect("failed to write");
let mut keys = HashSet::new();
for key in start.keys() {
keys.insert(key);
}
assert_eq!(keys.len(), 3);
assert!(keys.contains(&key1));
assert!(keys.contains(&key2));
assert!(keys.contains(&key3));
}
#[tag(root)]
#[test]
fn test_object_map_key_iter_empty() {
let mut obj = get_test_object("runqslower.bpf.o");
let start = get_map_mut(&mut obj, "start");
let mut count = 0;
for _ in start.keys() {
count += 1;
}
assert_eq!(count, 0);
}
#[tag(root)]
#[test]
fn test_object_map_pin() {
let mut obj = get_test_object("runqslower.bpf.o");
let mut map = get_map_mut(&mut obj, "start");
let path = "/sys/fs/bpf/mymap_test_object_map_pin";
// Unpinning a unpinned map should be an error
assert!(map.unpin(path).is_err());
assert!(!Path::new(path).exists());
// Pin and unpin should be successful
map.pin(path).expect("failed to pin map");
assert!(Path::new(path).exists());
map.unpin(path).expect("failed to unpin map");
assert!(!Path::new(path).exists());
}
#[tag(root)]
#[test]
fn test_object_loading_pinned_map_from_path() {
let mut obj = get_test_object("runqslower.bpf.o");
let mut map = get_map_mut(&mut obj, "start");
let path = "/sys/fs/bpf/mymap_test_pin_to_load_from_path";
map.pin(path).expect("pinning map failed");
let pinned_map = MapHandle::from_pinned_path(path).expect("loading a map from a path failed");
map.unpin(path).expect("unpinning map failed");
assert_eq!(map.name(), pinned_map.name());
assert_eq!(
map.info().unwrap().info.id,
pinned_map.info().unwrap().info.id
);
}
#[tag(root)]
#[test]
fn test_program_loading_fd_from_pinned_path() {
let path = "/sys/fs/bpf/myprog_test_pin_to_load_from_path";
let prog_name = "handle__sched_switch";
let mut obj = get_test_object("runqslower.bpf.o");
let mut prog = get_prog_mut(&mut obj, prog_name);
prog.pin(path).expect("pinning prog failed");
let prog_id = Program::id_from_fd(prog.as_fd()).expect("failed to determine prog id");
let pinned_prog_fd =
Program::fd_from_pinned_path(path).expect("failed to get fd of pinned prog");
let pinned_prog_id =
Program::id_from_fd(pinned_prog_fd.as_fd()).expect("failed to determine pinned prog id");
assert_eq!(prog_id, pinned_prog_id);
prog.unpin(path).expect("unpinning program failed");
}
#[tag(root)]
#[test]
fn test_program_loading_fd_from_pinned_path_with_wrong_pin_type() {
let path = "/sys/fs/bpf/mymap_test_pin_to_load_from_path";
let map_name = "events";
let mut obj = get_test_object("runqslower.bpf.o");
let mut map = get_map_mut(&mut obj, map_name);
map.pin(path).expect("pinning map failed");
// Must fail, as the pinned path points to a map, not program.
let _err = Program::fd_from_pinned_path(path).expect_err("program fd obtained from pinned map");
map.unpin(path).expect("unpinning program failed");
}
#[tag(root)]
#[test]
fn test_object_loading_loaded_map_from_id() {
let mut obj = get_test_object("runqslower.bpf.o");
let map = get_map_mut(&mut obj, "start");
let id = map.info().expect("to get info from map 'start'").info.id;
let map_by_id = MapHandle::from_map_id(id).expect("map to load from id");
assert_eq!(map.name(), map_by_id.name());
assert_eq!(
map.info().unwrap().info.id,
map_by_id.info().unwrap().info.id
);
}
#[tag(root)]
#[test]
fn test_object_programs() {
let mut obj = get_test_object("runqslower.bpf.o");
let _prog = get_prog_mut(&mut obj, "handle__sched_wakeup");
let _prog = get_prog_mut(&mut obj, "handle__sched_wakeup_new");
let _prog = get_prog_mut(&mut obj, "handle__sched_switch");
assert!(!obj.progs().any(|prog| prog.name() == OsStr::new("asdf")));
}
#[tag(root)]
#[test]
fn test_object_programs_iter_mut() {
let obj = get_test_object("runqslower.bpf.o");
assert!(obj.progs().count() == 3);
}
#[tag(root)]
#[test]
fn test_object_program_pin() {
let mut obj = get_test_object("runqslower.bpf.o");
let mut prog = get_prog_mut(&mut obj, "handle__sched_wakeup");
let path = "/sys/fs/bpf/myprog";
// Unpinning a unpinned prog should be an error
assert!(prog.unpin(path).is_err());
assert!(!Path::new(path).exists());
// Pin should be successful
prog.pin(path).expect("failed to pin prog");
assert!(Path::new(path).exists());
// Backup cleanup method in case test errors
defer! {
let _unused = fs::remove_file(path);
}
// Unpin should be successful
prog.unpin(path).expect("failed to unpin prog");
assert!(!Path::new(path).exists());
}
#[tag(root)]
#[test]
fn test_object_link_pin() {
let mut obj = get_test_object("runqslower.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__sched_wakeup");
let mut link = prog.attach().expect("failed to attach prog");
let path = "/sys/fs/bpf/mylink";
// Unpinning a unpinned prog should be an error
assert!(link.unpin().is_err());
assert!(!Path::new(path).exists());
// Pin should be successful
link.pin(path).expect("failed to pin prog");
assert!(Path::new(path).exists());
// Backup cleanup method in case test errors
defer! {
let _unused = fs::remove_file(path);
}
// Unpin should be successful
link.unpin().expect("failed to unpin prog");
assert!(!Path::new(path).exists());
}
#[tag(root)]
#[test]
fn test_object_reuse_pined_map() {
let path = "/sys/fs/bpf/mymap_test_object_reuse_pined_map";
let key = vec![1, 2, 3, 4];
let val = vec![1, 2, 3, 4, 5, 6, 7, 8];
// Pin a map
{
let mut obj = get_test_object("runqslower.bpf.o");
let mut map = get_map_mut(&mut obj, "start");
map.update(&key, &val, MapFlags::empty())
.expect("failed to write");
// Pin map
map.pin(path).expect("failed to pin map");
assert!(Path::new(path).exists());
}
// Backup cleanup method in case test errors somewhere
defer! {
let _unused = fs::remove_file(path);
}
// Reuse the pinned map
let obj_path = get_test_object_path("runqslower.bpf.o");
let mut builder = ObjectBuilder::default();
builder.debug(true);
let mut open_obj = builder.open_file(obj_path).expect("failed to open object");
let mut start = open_obj
.maps_mut()
.find(|map| map.name() == OsStr::new("start"))
.expect("failed to find `start` map");
assert!(start.reuse_pinned_map("/asdf").is_err());
start.reuse_pinned_map(path).expect("failed to reuse map");
let mut obj = open_obj.load().expect("failed to load object");
let mut reused_map = get_map_mut(&mut obj, "start");
let found_val = reused_map
.lookup(&key, MapFlags::empty())
.expect("failed to read map")
.expect("failed to find key");
assert_eq!(&found_val, &val);
// Cleanup
reused_map.unpin(path).expect("failed to unpin map");
assert!(!Path::new(path).exists());
}
#[tag(root)]
#[test]
fn test_object_ringbuf_raw() {
let mut obj = get_test_object("ringbuf.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__sys_enter_getpid");
let _link = prog.attach().expect("failed to attach prog");
static V1: AtomicI32 = AtomicI32::new(0);
static V2: AtomicI32 = AtomicI32::new(0);
fn callback1(data: &[u8]) -> i32 {
let mut value: i32 = 0;
plain::copy_from_bytes(&mut value, data).expect("Wrong size");
V1.store(value, Ordering::SeqCst);
0
}
fn callback2(data: &[u8]) -> i32 {
let mut value: i32 = 0;
plain::copy_from_bytes(&mut value, data).expect("Wrong size");
V2.store(value, Ordering::SeqCst);
0
}
// Test trying to build without adding any ringbufs
// Can't use expect_err here since RingBuffer does not implement Debug
let builder = libbpf_rs::RingBufferBuilder::new();
assert!(
builder.build().is_err(),
"Should not be able to build without adding at least one ringbuf"
);
// Test building with multiple map objects
let mut builder = libbpf_rs::RingBufferBuilder::new();
// Add a first map and callback
let map1 = get_map(&obj, "ringbuf1");
builder
.add(&map1, callback1)
.expect("failed to add ringbuf");
// Add a second map and callback
let map2 = get_map(&obj, "ringbuf2");
builder
.add(&map2, callback2)
.expect("failed to add ringbuf");
let mgr = builder.build().expect("failed to build");
// Call getpid to ensure the BPF program runs
unsafe { libc::getpid() };
// Test raw primitives
let ret = mgr.consume_raw();
// We can't check for exact return values, since other tasks in the system may call getpid(),
// triggering the BPF program
assert!(ret >= 2);
assert_eq!(V1.load(Ordering::SeqCst), 1);
assert_eq!(V2.load(Ordering::SeqCst), 2);
// Consume from a (potentially) empty ring buffer
let ret = mgr.consume_raw();
assert!(ret >= 0);
// Consume from a (potentially) empty ring buffer using poll()
let ret = mgr.poll_raw(Duration::from_millis(100));
assert!(ret >= 0);
// Call getpid multiple times, to refill the ring buffer.
for _ in 1..=10 {
unsafe { libc::getpid() };
}
// Consume exactly one item
let ret = mgr.consume_raw_n(1);
assert!(ret == 1);
// Consume two items
let ret = mgr.consume_raw_n(2);
assert!(ret == 2);
// Consume all the remaining items, but no more than 10
let ret = mgr.consume_raw_n(10);
assert!((7..=10).contains(&ret));
}
#[tag(root)]
#[test]
fn test_object_ringbuf_err_callback() {
let mut obj = get_test_object("ringbuf.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__sys_enter_getpid");
let _link = prog.attach().expect("failed to attach prog");
// Immediately trigger an error that should be reported back to the consume_raw() or poll_raw()
fn callback1(_data: &[u8]) -> i32 {
-libc::ENOENT
}
// Immediately trigger an error that should be reported back to the consume_raw() or poll_raw()
fn callback2(_data: &[u8]) -> i32 {
-libc::EPERM
}
// Test trying to build without adding any ringbufs
// Can't use expect_err here since RingBuffer does not implement Debug
let builder = libbpf_rs::RingBufferBuilder::new();
assert!(
builder.build().is_err(),
"Should not be able to build without adding at least one ringbuf"
);
// Test building with multiple map objects
let mut builder = libbpf_rs::RingBufferBuilder::new();
// Add a first map and callback
let map1 = get_map(&obj, "ringbuf1");
builder
.add(&map1, callback1)
.expect("failed to add ringbuf");
// Add a second map and callback
let map2 = get_map(&obj, "ringbuf2");
builder
.add(&map2, callback2)
.expect("failed to add ringbuf");
let mgr = builder.build().expect("failed to build");
// Call getpid to ensure the BPF program runs
unsafe { libc::getpid() };
// Test raw primitives
let ret = mgr.consume_raw();
// The error originated from the first callback executed should be reported here, either
// from callback1() or callback2()
assert!(ret == -libc::ENOENT || ret == -libc::EPERM);
unsafe { libc::getpid() };
// The same behavior should happen with poll_raw()
let ret = mgr.poll_raw(Duration::from_millis(100));
assert!(ret == -libc::ENOENT || ret == -libc::EPERM);
}
#[tag(root)]
#[test]
fn test_object_ringbuf() {
let mut obj = get_test_object("ringbuf.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__sys_enter_getpid");
let _link = prog.attach().expect("failed to attach prog");
static V1: AtomicI32 = AtomicI32::new(0);
static V2: AtomicI32 = AtomicI32::new(0);
fn callback1(data: &[u8]) -> i32 {
let mut value: i32 = 0;
plain::copy_from_bytes(&mut value, data).expect("Wrong size");
V1.store(value, Ordering::SeqCst);
0
}
fn callback2(data: &[u8]) -> i32 {
let mut value: i32 = 0;
plain::copy_from_bytes(&mut value, data).expect("Wrong size");
V2.store(value, Ordering::SeqCst);
0
}
// Test trying to build without adding any ringbufs
// Can't use expect_err here since RingBuffer does not implement Debug
let builder = libbpf_rs::RingBufferBuilder::new();
assert!(
builder.build().is_err(),
"Should not be able to build without adding at least one ringbuf"
);
// Test building with multiple map objects
let mut builder = libbpf_rs::RingBufferBuilder::new();
// Add a first map and callback
let map1 = get_map(&obj, "ringbuf1");
builder
.add(&map1, callback1)
.expect("failed to add ringbuf");
// Add a second map and callback
let map2 = get_map(&obj, "ringbuf2");
builder
.add(&map2, callback2)
.expect("failed to add ringbuf");
let mgr = builder.build().expect("failed to build");
// Call getpid to ensure the BPF program runs
unsafe { libc::getpid() };
// This should result in both callbacks being called
mgr.consume().expect("failed to consume ringbuf");
// Our values should both reflect that the callbacks have been called
assert_eq!(V1.load(Ordering::SeqCst), 1);
assert_eq!(V2.load(Ordering::SeqCst), 2);
// Reset both values
V1.store(0, Ordering::SeqCst);
V2.store(0, Ordering::SeqCst);
// Call getpid to ensure the BPF program runs
unsafe { libc::getpid() };
// This should result in both callbacks being called
mgr.poll(Duration::from_millis(100))
.expect("failed to poll ringbuf");
// Our values should both reflect that the callbacks have been called
assert_eq!(V1.load(Ordering::SeqCst), 1);
assert_eq!(V2.load(Ordering::SeqCst), 2);
}
#[tag(root)]
#[test]
fn test_object_ringbuf_closure() {
let mut obj = get_test_object("ringbuf.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__sys_enter_getpid");
let _link = prog.attach().expect("failed to attach prog");
let (sender1, receiver1) = channel();
let callback1 = move |data: &[u8]| -> i32 {
let mut value: i32 = 0;
plain::copy_from_bytes(&mut value, data).expect("Wrong size");
sender1.send(value).expect("failed to send value");
0
};
let (sender2, receiver2) = channel();
let callback2 = move |data: &[u8]| -> i32 {
let mut value: i32 = 0;
plain::copy_from_bytes(&mut value, data).expect("Wrong size");
sender2.send(value).expect("failed to send value");
0
};
// Test trying to build without adding any ringbufs
// Can't use expect_err here since RingBuffer does not implement Debug
let builder = libbpf_rs::RingBufferBuilder::new();
assert!(
builder.build().is_err(),
"Should not be able to build without adding at least one ringbuf"
);
// Test building with multiple map objects
let mut builder = libbpf_rs::RingBufferBuilder::new();
// Add a first map and callback
let map1 = get_map(&obj, "ringbuf1");
builder
.add(&map1, callback1)
.expect("failed to add ringbuf");
// Add a second map and callback
let map2 = get_map(&obj, "ringbuf2");
builder
.add(&map2, callback2)
.expect("failed to add ringbuf");
let mgr = builder.build().expect("failed to build");
// Call getpid to ensure the BPF program runs
unsafe { libc::getpid() };
// This should result in both callbacks being called
mgr.consume().expect("failed to consume ringbuf");
let v1 = receiver1.recv().expect("failed to receive value");
let v2 = receiver2.recv().expect("failed to receive value");
assert_eq!(v1, 1);
assert_eq!(v2, 2);
}
/// Check that `RingBuffer` works correctly even if the map file descriptors
/// provided during construction are closed. This test validates that `libbpf`'s
/// refcount behavior is correctly reflected in our `RingBuffer` lifetimes.
#[tag(root)]
#[test]
fn test_object_ringbuf_with_closed_map() {
fn test(poll_fn: impl FnOnce(&libbpf_rs::RingBuffer)) {
let mut value = 0i32;
{
let mut obj = get_test_object("tracepoint.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__tracepoint");
let _link = prog
.attach_tracepoint(TracepointCategory::Syscalls, "sys_enter_getpid")
.expect("failed to attach prog");
let map = get_map_mut(&mut obj, "ringbuf");
let callback = |data: &[u8]| {
plain::copy_from_bytes(&mut value, data).expect("Wrong size");
0
};
let mut builder = libbpf_rs::RingBufferBuilder::new();
builder.add(&map, callback).expect("failed to add ringbuf");
let ringbuf = builder.build().expect("failed to build");
drop(obj);
// Trigger the tracepoint. At this point `map` along with the containing
// `obj` have been destroyed.
let _pid = unsafe { libc::getpid() };
let () = poll_fn(&ringbuf);
}
// If we see a 1 here the ring buffer was still working as expected.
assert_eq!(value, 1);
}
test(|ringbuf| ringbuf.consume().expect("failed to consume ringbuf"));
test(|ringbuf| {
ringbuf
.poll(Duration::from_secs(5))
.expect("failed to poll ringbuf")
});
}
#[tag(root)]
#[test]
fn test_object_user_ringbuf() {
#[repr(C)]
struct MyStruct {
key: u32,
value: u32,
}
unsafe impl Plain for MyStruct {}
let mut obj = get_test_object("user_ringbuf.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__sys_enter_getpid");
let _link = prog.attach().expect("failed to attach prog");
let urb_map = get_map_mut(&mut obj, "user_ringbuf");
let user_ringbuf = UserRingBuffer::new(&urb_map).expect("failed to create user ringbuf");
let mut urb_sample = user_ringbuf
.reserve(size_of::<MyStruct>())
.expect("failed to reserve space");
let bytes = urb_sample.as_mut();
let my_struct = plain::from_mut_bytes::<MyStruct>(bytes).expect("failed to convert bytes");
my_struct.key = 42;
my_struct.value = 1337;
user_ringbuf
.submit(urb_sample)
.expect("failed to submit sample");
// Trigger BPF program.
let _pid = unsafe { libc::getpid() };
// At this point, the BPF program should have run and consumed the sample in
// the user ring buffer, and stored the key/value in the samples map.
let samples_map = get_map_mut(&mut obj, "samples");
let key: u32 = 42;
let value: u32 = 1337;
let res = samples_map
.lookup(&key.to_ne_bytes(), MapFlags::ANY)
.expect("failed to lookup")
.expect("failed to find value for key");
// The value in the samples map should be the same as the value we submitted
assert_eq!(res.len(), size_of::<u32>());
let mut array = [0; size_of::<u32>()];
array.copy_from_slice(&res[..]);
assert_eq!(u32::from_ne_bytes(array), value);
}
#[tag(root)]
#[test]
fn test_object_user_ringbuf_reservation_too_big() {
let mut obj = get_test_object("user_ringbuf.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__sys_enter_getpid");
let _link = prog.attach().expect("failed to attach prog");
let urb_map = get_map_mut(&mut obj, "user_ringbuf");
let user_ringbuf = UserRingBuffer::new(&urb_map).expect("failed to create user ringbuf");
let err = user_ringbuf.reserve(1024 * 1024).unwrap_err();
assert!(
err.to_string().contains("requested size is too large"),
"{err:#}"
);
}
#[tag(root)]
#[test]
fn test_object_user_ringbuf_not_enough_space() {
let mut obj = get_test_object("user_ringbuf.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__sys_enter_getpid");
let _link = prog.attach().expect("failed to attach prog");
let urb_map = get_map_mut(&mut obj, "user_ringbuf");
let user_ringbuf = UserRingBuffer::new(&urb_map).expect("failed to create user ringbuf");
let _sample = user_ringbuf
.reserve(1024 * 3)
.expect("failed to reserve space");
let err = user_ringbuf.reserve(1024 * 3).unwrap_err();
assert!(
err.to_string()
.contains("not enough space in the ring buffer"),
"{err:#}"
);
}
#[tag(root)]
#[test]
fn test_object_task_iter() {
let mut obj = get_test_object("taskiter.bpf.o");
let prog = get_prog_mut(&mut obj, "dump_pid");
let link = prog.attach().expect("failed to attach prog");
let mut iter = Iter::new(&link).expect("failed to create iterator");
#[repr(C)]
#[derive(Clone, Copy)]
struct IndexPidPair {
i: u32,
pid: i32,
}
unsafe impl Plain for IndexPidPair {}
let mut buf = Vec::new();
let bytes_read = iter
.read_to_end(&mut buf)
.expect("failed to read from iterator");
assert!(bytes_read > 0);
assert_eq!(bytes_read % size_of::<IndexPidPair>(), 0);
let items: &[IndexPidPair] =
plain::slice_from_bytes(buf.as_slice()).expect("Input slice cannot satisfy length");
assert!(!items.is_empty());
assert_eq!(items[0].i, 0);
assert!(items.windows(2).all(|w| w[0].i + 1 == w[1].i));
// Check for init
assert!(items.iter().any(|&item| item.pid == 1));
}
#[tag(root)]
#[test]
fn test_object_map_iter() {
// Create a map for iteration test.
let opts = libbpf_sys::bpf_map_create_opts {
sz: size_of::<libbpf_sys::bpf_map_create_opts>() as libbpf_sys::size_t,
map_flags: libbpf_sys::BPF_F_NO_PREALLOC,
..Default::default()
};
let map = MapHandle::create(
MapType::Hash,
Some("mymap_test_object_map_iter"),
4,
8,
8,
&opts,
)
.expect("failed to create map");
// Insert 3 elements.
for i in 0..3 {
let key = i32::to_ne_bytes(i);
// We can change i to larger for more robust test, that's why we use a and b.
let val = [&key[..], &[0_u8; 4]].concat();
map.update(&key, val.as_slice(), MapFlags::empty())
.expect("failed to write");
}
let mut obj = get_test_object("mapiter.bpf.o");
let prog = get_prog_mut(&mut obj, "map_iter");
let link = prog
.attach_iter(map.as_fd())
.expect("failed to attach map iter prog");
let mut iter = Iter::new(&link).expect("failed to create map iterator");
let mut buf = Vec::new();
let bytes_read = iter
.read_to_end(&mut buf)
.expect("failed to read from iterator");
assert!(bytes_read > 0);
assert_eq!(bytes_read % size_of::<u32>(), 0);
// Convert buf to &[u32]
let buf =
plain::slice_from_bytes::<u32>(buf.as_slice()).expect("Input slice cannot satisfy length");
assert!(buf.contains(&0));
assert!(buf.contains(&1));
assert!(buf.contains(&2));
}
#[tag(root)]
#[test]
fn test_object_map_create_and_pin() {
let opts = libbpf_sys::bpf_map_create_opts {
sz: size_of::<libbpf_sys::bpf_map_create_opts>() as libbpf_sys::size_t,
map_flags: libbpf_sys::BPF_F_NO_PREALLOC,
..Default::default()
};
let mut map = MapHandle::create(
MapType::Hash,
Some("mymap_test_object_map_create_and_pin"),
4,
8,
8,
&opts,
)
.expect("failed to create map");
assert_eq!(map.name(), "mymap_test_object_map_create_and_pin");
let key = vec![1, 2, 3, 4];
let val = vec![1, 2, 3, 4, 5, 6, 7, 8];
map.update(&key, &val, MapFlags::empty())
.expect("failed to write");
let res = map
.lookup(&key, MapFlags::ANY)
.expect("failed to lookup")
.expect("failed to find value for key");
assert_eq!(val, res);
let path = "/sys/fs/bpf/mymap_test_object_map_create_and_pin";
// Unpinning a unpinned map should be an error
assert!(map.unpin(path).is_err());
assert!(!Path::new(path).exists());
// Pin and unpin should be successful
map.pin(path).expect("failed to pin map");
assert!(Path::new(path).exists());
map.unpin(path).expect("failed to unpin map");
assert!(!Path::new(path).exists());
}
#[tag(root)]
#[test]
fn test_object_map_create_without_name() {
let opts = libbpf_sys::bpf_map_create_opts {
sz: size_of::<libbpf_sys::bpf_map_create_opts>() as libbpf_sys::size_t,
map_flags: libbpf_sys::BPF_F_NO_PREALLOC,
btf_fd: 0,
btf_key_type_id: 0,
btf_value_type_id: 0,
btf_vmlinux_value_type_id: 0,
inner_map_fd: 0,
map_extra: 0,
numa_node: 0,
map_ifindex: 0,
// bpf_map_create_opts might have padding fields on some platform
..Default::default()
};
let map = MapHandle::create(MapType::Hash, Option::<&str>::None, 4, 8, 8, &opts)
.expect("failed to create map");
assert!(map.name().is_empty());
let key = vec![1, 2, 3, 4];
let val = vec![1, 2, 3, 4, 5, 6, 7, 8];
map.update(&key, &val, MapFlags::empty())
.expect("failed to write");
let res = map
.lookup(&key, MapFlags::ANY)
.expect("failed to lookup")
.expect("failed to find value for key");
assert_eq!(val, res);
}
/// Test whether we can obtain multiple `MapHandle`s from a `Map`.
#[tag(root)]
#[test]
fn test_object_map_handle_clone() {
let mut obj = get_test_object("runqslower.bpf.o");
let map = get_map_mut(&mut obj, "events");
let handle1 = MapHandle::try_from(&map).expect("failed to create handle from Map");
assert_eq!(map.name(), handle1.name());
assert_eq!(map.map_type(), handle1.map_type());
assert_eq!(map.key_size(), handle1.key_size());
assert_eq!(map.value_size(), handle1.value_size());
assert_eq!(map.max_entries(), handle1.max_entries());
let handle2 = MapHandle::try_from(&handle1).expect("failed to duplicate existing handle");
assert_eq!(handle1.name(), handle2.name());
assert_eq!(handle1.map_type(), handle2.map_type());
assert_eq!(handle1.key_size(), handle2.key_size());
assert_eq!(handle1.value_size(), handle2.value_size());
assert_eq!(handle1.max_entries(), handle2.max_entries());
let info1 = map.info().expect("failed to get map info from map");
let info2 = handle2.info().expect("failed to get map info from handle");
assert_eq!(
info1.info.id, info2.info.id,
"Map and MapHandle have different IDs"
);
}
#[tag(root)]
#[test]
fn test_object_usdt() {
let mut obj = get_test_object("usdt.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__usdt");
let path = current_exe().expect("failed to find executable name");
let _link = prog
.attach_usdt(
unsafe { libc::getpid() },
&path,
"test_provider",
"test_function",
)
.expect("failed to attach prog");
let map = get_map_mut(&mut obj, "ringbuf");
let action = || {
// Define a USDT probe point and exercise it as we are attaching to self.
probe!(test_provider, test_function, 1);
};
let result = with_ringbuffer(&map, action);
assert_eq!(result, 1);
}
#[tag(root)]
#[test]
fn test_object_usdt_cookie() {
let cookie_val = 1337u16;
let mut obj = get_test_object("usdt.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__usdt_with_cookie");
let path = current_exe().expect("failed to find executable name");
let _link = prog
.attach_usdt_with_opts(
unsafe { libc::getpid() },
&path,
"test_provider",
"test_function2",
UsdtOpts {
cookie: cookie_val.into(),
..UsdtOpts::default()
},
)
.expect("failed to attach prog");
let map = get_map_mut(&mut obj, "ringbuf");
let action = || {
// Define a USDT probe point and exercise it as we are attaching to self.
probe!(test_provider, test_function2, 1);
};
let result = with_ringbuffer(&map, action);
assert_eq!(result, cookie_val.into());
}
#[tag(root)]
#[test]
fn test_map_probes() {
let supported = MapType::Array
.is_supported()
.expect("failed to query if Array map is supported");
assert!(supported);
let supported_res = MapType::Unknown.is_supported();
assert!(supported_res.is_err());
}
#[tag(root)]
#[test]
fn test_program_probes() {
let supported = ProgramType::SocketFilter
.is_supported()
.expect("failed to query if SocketFilter program is supported");
assert!(supported);
let supported_res = ProgramType::Unknown.is_supported();
assert!(supported_res.is_err());
}
#[tag(root)]
#[test]
fn test_program_helper_probes() {
let supported = ProgramType::SocketFilter
.is_helper_supported(libbpf_sys::BPF_FUNC_map_lookup_elem)
.expect("failed to query if helper supported");
assert!(supported);
// redirect should not be supported from socket filter, as it is only used in TC/XDP.
let supported = ProgramType::SocketFilter
.is_helper_supported(libbpf_sys::BPF_FUNC_redirect)
.expect("failed to query if helper supported");
assert!(!supported);
let supported_res = MapType::Unknown.is_supported();
assert!(supported_res.is_err());
}
#[tag(root)]
#[test]
fn test_object_open_program_insns() {
let open_obj = open_test_object("usdt.bpf.o");
let prog = open_obj
.progs()
.find(|prog| prog.name() == OsStr::new("handle__usdt"))
.expect("failed to find program");
let insns = prog.insns();
assert!(!insns.is_empty());
}
#[tag(root)]
#[test]
fn test_object_program_insns() {
let mut obj = get_test_object("usdt.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__usdt");
let insns = prog.insns();
assert!(!insns.is_empty());
}
/// Check that we can attach a BPF program to a kernel kprobe.
#[tag(root)]
#[test]
fn test_object_kprobe() {
let mut obj = get_test_object("kprobe.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__kprobe");
let _link = prog
.attach_kprobe(false, "bpf_fentry_test1")
.expect("failed to attach prog");
}
/// Check that we can attach a BPF program to a kernel kprobe, providing
/// additional options.
#[tag(root)]
#[test]
fn test_object_kprobe_with_opts() {
let mut obj = get_test_object("kprobe.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__kprobe");
let opts = KprobeOpts::default();
let _link = prog
.attach_kprobe_with_opts(false, "bpf_fentry_test1", opts)
.expect("failed to attach prog");
}
/// Check that we can attach a BPF program to multiple kernel kprobes using
/// `kprobe_multi`.
#[tag(root)]
#[test]
#[ignore = "requires kernel with kprobe multi support"]
fn test_object_kprobe_multi() {
let mut open_obj = open_test_object("kprobe.bpf.o");
open_obj
.progs_mut()
.find(|prog| prog.name() == "handle__kprobe")
.expect("failed to find `handle__kprobe` program")
.set_attach_type(libbpf_rs::ProgramAttachType::KprobeMulti);
let mut obj = open_obj.load().expect("failed to load object");
let prog = get_prog_mut(&mut obj, "handle__kprobe");
let _link = prog
.attach_kprobe_multi(false, vec!["bpf_fentry_test1", "bpf_fentry_test2"])
.expect("failed to attach prog");
}
/// Check that we can attach a BPF program to multiple kernel kprobes using
/// `kprobe_multi`, providing additional options.
#[tag(root)]
#[test]
#[ignore = "requires kernel with kprobe multi support"]
fn test_object_kprobe_multi_with_opts() {
let mut open_obj = open_test_object("kprobe.bpf.o");
open_obj
.progs_mut()
.find(|prog| prog.name() == "handle__kprobe")
.expect("failed to find `handle__kprobe` program")
.set_attach_type(libbpf_rs::ProgramAttachType::KprobeMulti);
let mut obj = open_obj.load().expect("failed to load object");
let prog = get_prog_mut(&mut obj, "handle__kprobe");
let opts = KprobeMultiOpts {
symbols: vec![
"bpf_fentry_test1".to_string(),
"bpf_fentry_test2".to_string(),
],
..Default::default()
};
let _link = prog
.attach_kprobe_multi_with_opts(opts)
.expect("failed to attach prog");
}
/// Check that we can attach a BPF program to a kernel tracepoint.
#[tag(root)]
#[test]
fn test_object_tracepoint() {
let mut obj = get_test_object("tracepoint.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__tracepoint");
let _link = prog
.attach_tracepoint(TracepointCategory::Syscalls, "sys_enter_getpid")
.expect("failed to attach prog");
let map = get_map_mut(&mut obj, "ringbuf");
let action = || {
let _pid = unsafe { libc::getpid() };
};
let result = with_ringbuffer(&map, action);
assert_eq!(result, 1);
}
/// Check that we can attach a BPF program to a kernel tracepoint, providing
/// additional options.
#[tag(root)]
#[test]
fn test_object_tracepoint_with_opts() {
let cookie_val = 42u16;
let mut obj = get_test_object("tracepoint.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__tracepoint_with_cookie");
let opts = TracepointOpts {
cookie: cookie_val.into(),
..TracepointOpts::default()
};
let _link = prog
.attach_tracepoint_with_opts(TracepointCategory::Syscalls, "sys_enter_getpid", opts)
.expect("failed to attach prog");
let map = get_map_mut(&mut obj, "ringbuf");
let action = || {
let _pid = unsafe { libc::getpid() };
};
let result = with_ringbuffer(&map, action);
assert_eq!(result, cookie_val.into());
}
/// Check that we can attach a BPF program to a kernel raw tracepoint.
#[tag(root)]
#[test]
fn test_object_raw_tracepoint() {
let mut open_obj = open_test_object("tracepoint.bpf.o");
open_obj
.progs_mut()
.find(|prog| prog.name() == "handle__tracepoint")
.expect("failed to find `handle__tracepoint` program")
.set_prog_type(libbpf_rs::ProgramType::RawTracepoint);
let mut obj = open_obj.load().expect("failed to load object");
let prog = get_prog_mut(&mut obj, "handle__tracepoint");
let _link = prog
.attach_raw_tracepoint("sys_enter")
.expect("failed to attach prog");
let map = get_map_mut(&mut obj, "ringbuf");
let action = || {
let _pid = unsafe { libc::getpid() };
};
let result = with_ringbuffer(&map, action);
assert_eq!(result, 1);
}
/// Check that we can attach a BPF program to a kernel raw tracepoint, providing
/// additional options.
#[tag(root)]
#[test]
#[ignore = "requires kernel with bpf_get_attach_cookie for raw tracepoints"]
fn test_object_raw_tracepoint_with_opts() {
let cookie_val = 42u16;
let mut open_obj = open_test_object("tracepoint.bpf.o");
open_obj
.progs_mut()
.find(|prog| prog.name() == "handle__tracepoint_with_cookie")
.expect("failed to find `handle__tracepoint` program")
.set_prog_type(libbpf_rs::ProgramType::RawTracepoint);
let mut obj = open_obj.load().expect("failed to load object");
let prog = get_prog_mut(&mut obj, "handle__tracepoint_with_cookie");
let opts = RawTracepointOpts {
cookie: cookie_val.into(),
..Default::default()
};
let _link = prog
.attach_raw_tracepoint_with_opts("sys_enter", opts)
.expect("failed to attach prog");
let map = get_map_mut(&mut obj, "ringbuf");
let action = || {
let _pid = unsafe { libc::getpid() };
};
let result = with_ringbuffer(&map, action);
assert_eq!(result, cookie_val.into());
}
#[inline(never)]
#[no_mangle]
extern "C" fn uprobe_target() -> usize {
// Use `black_box` here as an additional barrier to inlining.
hint::black_box(42)
}
/// Check that we can attach a BPF program to a uprobe.
#[tag(root)]
#[test]
fn test_object_uprobe_with_opts() {
let mut obj = get_test_object("uprobe.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__uprobe");
let pid = unsafe { libc::getpid() };
let path = current_exe().expect("failed to find executable name");
let func_offset = 0;
let opts = UprobeOpts {
func_name: Some("uprobe_target".into()),
..Default::default()
};
let _link = prog
.attach_uprobe_with_opts(pid, path, func_offset, opts)
.expect("failed to attach prog");
let map = get_map_mut(&mut obj, "ringbuf");
let action = || {
let _ = uprobe_target();
};
let result = with_ringbuffer(&map, action);
assert_eq!(result, 1);
}
#[tag(root)]
#[test]
fn test_object_uprobe_with_func_offset() {
let mut obj = get_test_object("uprobe.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__uprobe");
let pid = unsafe { libc::getpid() };
let path = current_exe().expect("failed to find executable name");
let func_offset = get_symbol_offset(&path, "uprobe_target").unwrap();
let _link = prog
.attach_uprobe_with_opts(pid, path, func_offset, Default::default())
.expect("failed to attach prog");
let map = get_map_mut(&mut obj, "ringbuf");
let action = || {
let _ = uprobe_target();
};
let result = with_ringbuffer(&map, action);
assert_eq!(result, 1);
}
/// Check that we can attach a BPF program to a uprobe and access the cookie
/// provided during attach.
#[tag(root)]
#[test]
fn test_object_uprobe_with_cookie() {
let cookie_val = 5u16;
let mut obj = get_test_object("uprobe.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__uprobe_with_cookie");
let pid = unsafe { libc::getpid() };
let path = current_exe().expect("failed to find executable name");
let func_offset = 0;
let opts = UprobeOpts {
func_name: Some("uprobe_target".into()),
cookie: cookie_val.into(),
..Default::default()
};
let _link = prog
.attach_uprobe_with_opts(pid, path, func_offset, opts)
.expect("failed to attach prog");
let map = get_map_mut(&mut obj, "ringbuf");
let action = || {
let _ = uprobe_target();
};
let result = with_ringbuffer(&map, action);
assert_eq!(result, cookie_val.into());
}
/// Check that we can link multiple object files.
#[test]
fn test_object_link_files() {
fn test(files: Vec<PathBuf>) {
let output_file = NamedTempFile::new().unwrap();
let mut linker = Linker::new(output_file.path()).unwrap();
let () = files
.into_iter()
.try_for_each(|file| linker.add_file(file))
.unwrap();
let () = linker.link().unwrap();
// Check that we can load the resulting object file.
let _object = ObjectBuilder::default()
.debug(true)
.open_file(output_file.path())
.unwrap();
}
let obj_path1 = get_test_object_path("usdt.bpf.o");
let obj_path2 = get_test_object_path("ringbuf.bpf.o");
test(vec![obj_path1.clone()]);
test(vec![obj_path1, obj_path2]);
}
/// Get access to the underlying per-cpu ring buffer data.
fn buffer<'a>(perf: &'a libbpf_rs::PerfBuffer, buf_idx: usize) -> &'a [u8] {
let perf_buff_ptr = perf.as_libbpf_object();
let mut buffer_data_ptr: *mut c_void = ptr::null_mut();
let mut buffer_size: usize = 0;
let ret = unsafe {
libbpf_sys::perf_buffer__buffer(
perf_buff_ptr.as_ptr(),
buf_idx as i32,
ptr::addr_of_mut!(buffer_data_ptr),
ptr::addr_of_mut!(buffer_size) as *mut libbpf_sys::size_t,
)
};
assert!(ret >= 0);
unsafe { slice::from_raw_parts(buffer_data_ptr as *const u8, buffer_size) }
}
/// Check that we can see the raw ring buffer of the perf buffer and find a
/// value we have sent.
#[tag(root)]
#[test]
fn test_object_perf_buffer_raw() {
use memmem::Searcher;
use memmem::TwoWaySearcher;
let cookie_val = 42u16;
let mut obj = get_test_object("tracepoint.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__tracepoint_with_cookie_pb");
let opts = TracepointOpts {
cookie: cookie_val.into(),
..TracepointOpts::default()
};
let _link = prog
.attach_tracepoint_with_opts(TracepointCategory::Syscalls, "sys_enter_getpid", opts)
.expect("failed to attach prog");
let map = get_map_mut(&mut obj, "pb");
let cookie_bytes = cookie_val.to_ne_bytes();
let searcher = TwoWaySearcher::new(&cookie_bytes[..]);
let perf = libbpf_rs::PerfBufferBuilder::new(&map)
.build()
.expect("failed to build");
// Make an action that the tracepoint will see
let _pid = unsafe { libc::getpid() };
let found_cookie = (0..perf.buffer_cnt()).any(|buf_idx| {
let buf = buffer(&perf, buf_idx);
searcher.search_in(buf).is_some()
});
assert!(found_cookie);
}
/// Check that we can get map pin status and map pin path
#[tag(root)]
#[test]
fn test_map_pinned_status() {
let mut obj = get_test_object("map_auto_pin.bpf.o");
let map = get_map_mut(&mut obj, "auto_pin_map");
let is_pinned = map.is_pinned();
assert!(is_pinned);
let expected_path = "/sys/fs/bpf/auto_pin_map";
let get_path = map.get_pin_path().expect("get map pin path failed");
assert_eq!(expected_path, get_path.to_str().unwrap());
// cleanup
let _unused = fs::remove_file(expected_path);
}
/// Change the `root_pin_path` and see if it works.
#[tag(root)]
#[test]
fn test_map_pinned_status_with_pin_root_path() {
let obj_path = get_test_object_path("map_auto_pin.bpf.o");
let mut obj = ObjectBuilder::default()
.debug(true)
.pin_root_path("/sys/fs/bpf/test_namespace")
.expect("root_pin_path failed")
.open_file(obj_path)
.expect("failed to open object")
.load()
.expect("failed to load object");
let map = get_map_mut(&mut obj, "auto_pin_map");
let is_pinned = map.is_pinned();
assert!(is_pinned);
let expected_path = "/sys/fs/bpf/test_namespace/auto_pin_map";
let get_path = map.get_pin_path().expect("get map pin path failed");
assert_eq!(expected_path, get_path.to_str().unwrap());
// cleanup
let _unused = fs::remove_file(expected_path);
let _unused = fs::remove_dir("/sys/fs/bpf/test_namespace");
}
/// Check that we can get program fd by id and vice versa.
#[tag(root)]
#[test]
fn test_program_get_fd_and_id() {
let mut obj = get_test_object("runqslower.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__sched_wakeup");
let prog_fd = prog.as_fd();
let prog_id = Program::id_from_fd(prog_fd).expect("failed to get program id from fd");
let _owned_prog_fd = Program::fd_from_id(prog_id).expect("failed to get program fd from id");
}
/// Check that autocreate disabled maps don't prevent object loading
#[tag(root)]
#[test]
fn test_map_autocreate_disable() {
let mut open_obj = open_test_object("map_auto_pin.bpf.o");
let mut auto_pin_map = open_obj
.maps_mut()
.find(|map| map.name() == OsStr::new("auto_pin_map"))
.expect("failed to find `auto_pin_map` map");
auto_pin_map
.set_autocreate(false)
.expect("set_autocreate() failed");
open_obj.load().expect("failed to load object");
}
/// Check that we can adjust a map's value size.
#[tag(root)]
#[test]
fn test_map_adjust_value_size() {
let mut open_obj = open_test_object("map_auto_pin.bpf.o");
let mut resizable = open_obj
.maps_mut()
.find(|map| map.name() == OsStr::new(".data.resizable_data"))
.expect("failed to find `.data.resizable_data` map");
let len = resizable.initial_value().unwrap().len();
assert_eq!(len, size_of::<u64>());
let () = resizable
.set_value_size(len as u32 * 2)
.expect("failed to set value size");
let new_len = resizable.initial_value().unwrap().len();
assert_eq!(new_len, len * 2);
}
/// Check that we can adjust a map's maximum entries.
#[tag(root)]
#[test]
fn test_object_map_max_entries() {
let mut obj = open_test_object("runqslower.bpf.o");
// resize the map to have twice the number of entries
let mut start = obj
.maps_mut()
.find(|map| map.name() == OsStr::new("start"))
.expect("failed to find `start` map");
let initial_max_entries = start.max_entries();
let new_max_entries = initial_max_entries * 2;
start
.set_max_entries(new_max_entries)
.expect("failed to set max entries");
// check that it reflects on the open map
assert_eq!(start.max_entries(), new_max_entries);
// check that it reflects after loading the map
let obj = obj.load().expect("failed to load object");
let start = obj
.maps()
.find(|map| map.name() == OsStr::new("start"))
.expect("failed to find `start` map");
assert_eq!(start.max_entries(), new_max_entries);
// check that it reflects after recreating the map handle from map id
let start = MapHandle::from_map_id(start.info().expect("failed to get map info").info.id)
.expect("failed to get map handle from id");
assert!(start.max_entries() == new_max_entries);
}
/// Check that we are able to attach using ksyscall
#[tag(root)]
#[test]
fn test_attach_ksyscall() {
let mut obj = get_test_object("ksyscall.bpf.o");
let prog = get_prog_mut(&mut obj, "handle__ksyscall");
let _link = prog
.attach_ksyscall(false, "kill")
.expect("failed to attach prog");
let map = get_map_mut(&mut obj, "ringbuf");
let action = || {
// Send `SIGCHLD`, which is ignored by default, to our process.
let ret = unsafe { libc::kill(libc::getpid(), libc::SIGCHLD) };
if ret < 0 {
panic!("kill failed: {}", io::Error::last_os_error());
}
};
let result = with_ringbuffer(&map, action);
assert_eq!(result, 1);
}
/// Check that we can invoke a program directly.
#[tag(root)]
#[test]
fn test_run_prog_success() {
let mut obj = get_test_object("run_prog.bpf.o");
let prog = get_prog_mut(&mut obj, "test_1");
#[repr(C)]
struct bpf_dummy_ops_state {
val: c_int,
}
let value = 42;
let state = bpf_dummy_ops_state { val: value };
let mut args = [addr_of!(state) as u64];
let input = ProgramInput {
context_in: Some(unsafe {
slice::from_raw_parts_mut(&mut args as *mut _ as *mut u8, size_of_val(&args))
}),
..Default::default()
};
let output = prog.test_run(input).unwrap();
assert_eq!(output.return_value, value as _);
}
/// Check that we fail program invocation when providing insufficient arguments.
#[tag(root)]
#[test]
fn test_run_prog_fail() {
let mut obj = get_test_object("run_prog.bpf.o");
let prog = get_prog_mut(&mut obj, "test_2");
let input = ProgramInput::default();
let _err = prog.test_run(input).unwrap_err();
}
/// Check that we can run a program with `test_run` with `repeat` set.
///
/// We set a counter in the program which we bump each time we run the
/// program.
/// We check that the counter is equal to the value of `repeat`.
/// We also check that the duration is non-zero.
#[tag(root)]
#[test]
fn test_run_prog_repeat_and_duration() {
let repeat = 100;
let payload: [u8; 16] = [
0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, // src mac
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, // dst mac
0x08, 0x00, // ethertype
0x00, 0x00, // payload
];
let mut obj = get_test_object("run_prog.bpf.o");
let prog = get_prog_mut(&mut obj, "xdp_counter");
let input: ProgramInput<'_> = ProgramInput {
data_in: Some(&payload),
repeat,
..Default::default()
};
let output = prog.test_run(input).unwrap();
let map = get_map(&obj, "test_counter_map");
let counter = map
.lookup(&0u32.to_ne_bytes(), MapFlags::ANY)
.expect("failed to lookup counter")
.expect("failed to retrieve value");
assert_eq!(output.return_value, libbpf_sys::XDP_PASS);
assert_eq!(
counter,
repeat.to_ne_bytes(),
"counter {} != repeat {repeat}",
u32::from_ne_bytes(counter.clone().try_into().unwrap())
);
assert_ne!(
output.duration,
Duration::ZERO,
"duration should be non-zero"
);
}
|