From 28e6f9770822aedb387c9f97d1e94405a15026b1 Mon Sep 17 00:00:00 2001 From: varun-r-mallya Date: Sun, 21 Sep 2025 18:05:43 +0530 Subject: [PATCH] add support for compilation with pylibbpf Signed-off-by: varun-r-mallya --- pyproject.toml | 3 ++- pythonbpf/__init__.py | 2 +- pythonbpf/codegen.py | 15 +++++++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 7292091..1f8a3d5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,7 +16,8 @@ requires-python = ">=3.8" dependencies = [ "llvmlite", - "astpretty" + "astpretty", + "pylibbpf" ] [tool.setuptools.packages.find] diff --git a/pythonbpf/__init__.py b/pythonbpf/__init__.py index 96f6e50..e56aa06 100644 --- a/pythonbpf/__init__.py +++ b/pythonbpf/__init__.py @@ -1,2 +1,2 @@ from .decorators import bpf, map, section, bpfglobal, struct -from .codegen import compile_to_ir, compile +from .codegen import compile_to_ir, compile, BPF diff --git a/pythonbpf/codegen.py b/pythonbpf/codegen.py index 8530329..df30cde 100644 --- a/pythonbpf/codegen.py +++ b/pythonbpf/codegen.py @@ -9,6 +9,7 @@ import os import subprocess import inspect from pathlib import Path +from pylibbpf import BpfProgram def find_bpf_chunks(tree): @@ -116,3 +117,17 @@ def compile(): ], check=True) print(f"Object written to {o_file}, {ll_file} can be removed") + +def BPF() -> BpfProgram: + caller_frame = inspect.stack()[1] + caller_file = Path(caller_frame.filename).resolve() + ll_file = Path("/tmp") / caller_file.with_suffix(".ll").name + o_file = Path("/tmp") / caller_file.with_suffix(".o").name + compile_to_ir(str(caller_file), str(ll_file)) + + subprocess.run([ + "llc", "-march=bpf", "-filetype=obj", "-O2", + str(ll_file), "-o", str(o_file) + ], check=True) + + return BpfProgram(str(o_file))