Skip to content

Commit 5cbd9a5

Browse files
committed
Add bpf_get_prandom_u32 helper
1 parent 5c1e710 commit 5cbd9a5

3 files changed

Lines changed: 30 additions & 1 deletion

File tree

pythonbpf/helper/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from .helper_registry import HelperHandlerRegistry
22
from .helper_utils import reset_scratch_pool
33
from .bpf_helper_handler import handle_helper_call, emit_probe_read_kernel_str_call
4-
from .helpers import ktime, pid, deref, comm, probe_read_str, XDP_DROP, XDP_PASS
4+
from .helpers import ktime, pid, deref, comm, probe_read_str, random, XDP_DROP, XDP_PASS
55

66

77
# Register the helper handler with expr module
@@ -65,6 +65,7 @@ def helper_call_handler(
6565
"deref",
6666
"comm",
6767
"probe_read_str",
68+
"random",
6869
"XDP_DROP",
6970
"XDP_PASS",
7071
]

pythonbpf/helper/bpf_helper_handler.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ class BPFHelperID(Enum):
2525
BPF_MAP_DELETE_ELEM = 3
2626
BPF_KTIME_GET_NS = 5
2727
BPF_PRINTK = 6
28+
BPF_GET_PRANDOM_U32 = 7
2829
BPF_GET_CURRENT_PID_TGID = 14
2930
BPF_GET_CURRENT_COMM = 16
3031
BPF_PERF_EVENT_OUTPUT = 25
@@ -433,6 +434,28 @@ def bpf_probe_read_kernel_str_emitter(
433434
return result, ir.IntType(64)
434435

435436

437+
@HelperHandlerRegistry.register("random")
438+
def bpf_get_prandom_u32_emitter(
439+
call,
440+
map_ptr,
441+
module,
442+
builder,
443+
func,
444+
local_sym_tab=None,
445+
struct_sym_tab=None,
446+
map_sym_tab=None,
447+
):
448+
"""
449+
Emit LLVM IR for bpf_get_prandom_u32 helper function call.
450+
"""
451+
helper_id = ir.Constant(ir.IntType(64), BPFHelperID.BPF_GET_PRANDOM_U32.value)
452+
fn_type = ir.FunctionType(ir.IntType(32), [], var_arg=False)
453+
fn_ptr_type = ir.PointerType(fn_type)
454+
fn_ptr = builder.inttoptr(helper_id, fn_ptr_type)
455+
result = builder.call(fn_ptr, [], tail=False)
456+
return result, ir.IntType(32)
457+
458+
436459
def handle_helper_call(
437460
call,
438461
module,

pythonbpf/helper/helpers.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,11 @@ def probe_read_str(dst, src):
2727
return ctypes.c_int64(0)
2828

2929

30+
def random():
31+
"""get a pseudorandom u32 number"""
32+
return ctypes.c_int32(0)
33+
34+
3035
XDP_ABORTED = ctypes.c_int64(0)
3136
XDP_DROP = ctypes.c_int64(1)
3237
XDP_PASS = ctypes.c_int64(2)

0 commit comments

Comments
 (0)