From 05c398dc2119c381c0c626ad9f3ee935e6e776f0 Mon Sep 17 00:00:00 2001 From: varun-r-mallya Date: Tue, 9 Sep 2025 16:48:05 +0530 Subject: [PATCH] add compile command --- examples/execve3.py | 22 ++++++++++++---------- pythonbpf/__init__.py | 2 ++ pythonbpf/codegen.py | 19 ++++++++++++++++++- 3 files changed, 32 insertions(+), 11 deletions(-) diff --git a/examples/execve3.py b/examples/execve3.py index bffbb03..4a9ee19 100644 --- a/examples/execve3.py +++ b/examples/execve3.py @@ -1,25 +1,25 @@ -from pythonbpf.decorators import bpf, map, section, bpfglobal -from ctypes import c_void_p, c_int64, c_int32, c_uint64 +import pythonbpf as pb from pythonbpf.helpers import bpf_ktime_get_ns from pythonbpf.maps import HashMap +from ctypes import c_void_p, c_int64, c_int32, c_uint64 -@bpf -@map +@pb.bpf +@pb.map def last() -> HashMap: return HashMap(key_type=c_uint64, value_type=c_uint64, max_entries=1) -@bpf -@section("tracepoint/syscalls/sys_enter_execve") +@pb.bpf +@pb.section("tracepoint/syscalls/sys_enter_execve") def hello(ctx: c_void_p) -> c_int32: print("entered") print("multi constant support") return c_int32(0) -@bpf -@section("tracepoint/syscalls/sys_exit_execve") +@pb.bpf +@pb.section("tracepoint/syscalls/sys_exit_execve") def hello_again(ctx: c_void_p) -> c_int64: print("exited") key = 0 @@ -34,7 +34,9 @@ def hello_again(ctx: c_void_p) -> c_int64: return c_int64(0) -@bpf -@bpfglobal +@pb.bpf +@pb.bpfglobal def LICENSE() -> str: return "GPL" + +pb.compile() diff --git a/pythonbpf/__init__.py b/pythonbpf/__init__.py index e69de29..31d7d7c 100644 --- a/pythonbpf/__init__.py +++ b/pythonbpf/__init__.py @@ -0,0 +1,2 @@ +from .decorators import bpf, map, section, bpfglobal +from .codegen import compile_to_ir, compile diff --git a/pythonbpf/codegen.py b/pythonbpf/codegen.py index 5c35954..fde27b0 100644 --- a/pythonbpf/codegen.py +++ b/pythonbpf/codegen.py @@ -5,7 +5,9 @@ from .functions_pass import func_proc from .maps_pass import maps_proc from .globals_pass import globals_processing import os - +import subprocess +import pathlib +import __main__ def find_bpf_chunks(tree): """Find all functions decorated with @bpf in the AST.""" @@ -92,3 +94,18 @@ def compile_to_ir(filename: str, output: str): f.write("\n") return output + +def compile(): + main_file = pathlib.Path(__main__.__file__).resolve() + + ll_file = pathlib.Path("/tmp") / main_file.with_suffix(".ll").name + o_file = main_file.with_suffix(".o") + + compile_to_ir(str(main_file), str(ll_file)) + + subprocess.run([ + "llc", "-march=bpf", "-filetype=obj", "-O2", + str(ll_file), "-o", str(o_file) + ], check=True) + + print(f"Object written to {o_file}")