diff --git a/examples/execve5.py b/examples/execve5.py index f3f03bc..ca37e4b 100644 --- a/examples/execve5.py +++ b/examples/execve5.py @@ -1,5 +1,5 @@ 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 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") def hello(ctx: c_void_p) -> c_int32: 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) diff --git a/pythonbpf/bpf_helper_handler.py b/pythonbpf/bpf_helper_handler.py index 3689338..471cc36 100644 --- a/pythonbpf/bpf_helper_handler.py +++ b/pythonbpf/bpf_helper_handler.py @@ -323,12 +323,30 @@ def bpf_map_delete_elem_emitter(call, map_ptr, module, builder, local_sym_tab=No 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 = { "lookup": bpf_map_lookup_elem_emitter, "print": bpf_printk_emitter, "ktime": bpf_ktime_get_ns_emitter, "update": bpf_map_update_elem_emitter, "delete": bpf_map_delete_elem_emitter, + "pid": bpf_get_current_pid_tgid_emitter, } diff --git a/pythonbpf/helpers.py b/pythonbpf/helpers.py index ae24d9f..6b776be 100644 --- a/pythonbpf/helpers.py +++ b/pythonbpf/helpers.py @@ -3,6 +3,9 @@ import ctypes def ktime(): return ctypes.c_int64(0) +def pid(): + return ctypes.c_int32(0) + def deref(ptr): "dereference a pointer" result = ctypes.cast(ptr, ctypes.POINTER(ctypes.c_void_p)).contents.value