xref: /linux/tools/testing/selftests/net/lib/py/bpf.py (revision 4ce06406958b67fdddcc2e6948237dd6ff6ba112)
1# SPDX-License-Identifier: GPL-2.0
2
3"""
4BPF helper utilities for kernel selftests.
5
6Provides common operations for interacting with BPF maps and programs
7via bpftool, used by XDP and other BPF-based test files.
8"""
9
10from .utils import bpftool
11
12def _format_hex_bytes(value):
13    """
14    Helper function that converts an integer into a formatted hexadecimal byte string.
15
16    Args:
17        value: An integer representing the number to be converted.
18
19    Returns:
20        A string representing hexadecimal equivalent of value, with bytes separated by spaces.
21    """
22    hex_str = value.to_bytes(4, byteorder='little', signed=True)
23    return ' '.join(f'{byte:02x}' for byte in hex_str)
24
25
26def bpf_map_set(map_name, key, value):
27    """
28    Updates an XDP map with a given key-value pair using bpftool.
29
30    Args:
31        map_name: The name of the XDP map to update.
32        key: The key to update in the map, formatted as a hexadecimal string.
33        value: The value to associate with the key, formatted as a hexadecimal string.
34    """
35    key_formatted = _format_hex_bytes(key)
36    value_formatted = _format_hex_bytes(value)
37    bpftool(
38        f"map update name {map_name} key hex {key_formatted} value hex {value_formatted}"
39    )
40
41def bpf_map_dump(map_id):
42    """Dump all entries of a BPF array map.
43
44    Args:
45        map_id: Numeric map ID (as returned by bpftool prog show).
46
47    Returns:
48        A dict mapping formatted key (int) to formatted value (int).
49    """
50    raw = bpftool(f"map dump id {map_id}", json=True)
51    return {e["formatted"]["key"]: e["formatted"]["value"] for e in raw}
52
53
54def bpf_prog_map_ids(prog_id):
55    """Get the map name-to-ID mapping for a loaded BPF program.
56
57    Args:
58        prog_id: Numeric program ID.
59
60    Returns:
61        A dict mapping map name (str) to map ID (int).
62    """
63    map_ids = bpftool(f"prog show id {prog_id}", json=True)["map_ids"]
64    maps = {}
65    for mid in map_ids:
66        name = bpftool(f"map show id {mid}", json=True)["name"]
67        maps[name] = mid
68    return maps
69