Add PID helper

This commit is contained in:
Pragyansh Chaturvedi
2025-09-19 22:58:16 +05:30
parent 95727e3374
commit b0f18229d9
3 changed files with 24 additions and 2 deletions

View File

@ -1,5 +1,5 @@
from pythonbpf import bpf, map, section, bpfglobal, compile from pythonbpf import bpf, map, section, bpfglobal, compile
from pythonbpf.helpers import ktime, deref from pythonbpf.helpers import ktime, pid
from pythonbpf.maps import HashMap from pythonbpf.maps import HashMap
from ctypes import c_void_p, c_int64, c_int32, c_uint64 from ctypes import c_void_p, c_int64, c_int32, c_uint64
@ -9,7 +9,8 @@ from ctypes import c_void_p, c_int64, c_int32, c_uint64
@section("tracepoint/syscalls/sys_enter_clone") @section("tracepoint/syscalls/sys_enter_clone")
def hello(ctx: c_void_p) -> c_int32: def hello(ctx: c_void_p) -> c_int32:
ts = ktime() ts = ktime()
print(f"clone called at {ts}") process_id = pid()
print(f"clone called at {ts} by pid {process_id}")
return c_int32(0) return c_int32(0)

View File

@ -323,12 +323,30 @@ def bpf_map_delete_elem_emitter(call, map_ptr, module, builder, local_sym_tab=No
return result return result
def bpf_get_current_pid_tgid_emitter(call, map_ptr, module, builder, func, local_sym_tab=None):
"""
Emit LLVM IR for bpf_get_current_pid_tgid helper function call.
"""
# func is an arg to just have a uniform signature with other emitters
helper_id = ir.Constant(ir.IntType(64), 14)
fn_type = ir.FunctionType(ir.IntType(64), [], var_arg=False)
fn_ptr_type = ir.PointerType(fn_type)
fn_ptr = builder.inttoptr(helper_id, fn_ptr_type)
result = builder.call(fn_ptr, [], tail=False)
# Extract the lower 32 bits (PID) using bitwise AND with 0xFFFFFFFF
mask = ir.Constant(ir.IntType(64), 0xFFFFFFFF)
pid = builder.and_(result, mask)
return pid
helper_func_list = { helper_func_list = {
"lookup": bpf_map_lookup_elem_emitter, "lookup": bpf_map_lookup_elem_emitter,
"print": bpf_printk_emitter, "print": bpf_printk_emitter,
"ktime": bpf_ktime_get_ns_emitter, "ktime": bpf_ktime_get_ns_emitter,
"update": bpf_map_update_elem_emitter, "update": bpf_map_update_elem_emitter,
"delete": bpf_map_delete_elem_emitter, "delete": bpf_map_delete_elem_emitter,
"pid": bpf_get_current_pid_tgid_emitter,
} }

View File

@ -3,6 +3,9 @@ import ctypes
def ktime(): def ktime():
return ctypes.c_int64(0) return ctypes.c_int64(0)
def pid():
return ctypes.c_int32(0)
def deref(ptr): def deref(ptr):
"dereference a pointer" "dereference a pointer"
result = ctypes.cast(ptr, ctypes.POINTER(ctypes.c_void_p)).contents.value result = ctypes.cast(ptr, ctypes.POINTER(ctypes.c_void_p)).contents.value