11 Commits

Author SHA1 Message Date
54acc2c15d Redesign BpfMap 2025-10-18 14:53:35 +05:30
5c74be041e Reimplement BpfProgram 2025-10-18 13:24:03 +05:30
2b99f01b02 Rework BpfProgram.h, pass BpfObject as shared_ptr to BpfPrograms 2025-10-18 12:36:15 +05:30
763c188fa9 Implement BpfObject class 2025-10-18 04:59:14 +05:30
528a54247d Create bpf_object.h as a container for the object file having bpf progs and maps 2025-10-17 18:12:26 +05:30
8d27a351e0 Add src/core/bpf_perf_buffer 2025-10-17 03:47:31 +05:30
5a3937b7f6 Update README to include responsive image support 2025-10-01 17:47:54 +05:30
6e6e48acdd fix readme formatting 2025-10-01 01:51:31 +05:30
15c171b546 Enhance README with badges and clearer descriptions
Updated README with improved descriptions and badges.
2025-10-01 01:49:42 +05:30
aa8183b28c Merge pull request #3 from pythonbpf/dependabot/github_actions/actions-e3feb9629e
Bump the actions group with 4 updates
2025-10-01 01:31:24 +05:30
80a0afe74f Bump the actions group with 4 updates
Bumps the actions group with 4 updates: [actions/checkout](https://github.com/actions/checkout), [actions/setup-python](https://github.com/actions/setup-python), [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel) and [actions/download-artifact](https://github.com/actions/download-artifact).


Updates `actions/checkout` from 4 to 5
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v5)

Updates `actions/setup-python` from 5 to 6
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](https://github.com/actions/setup-python/compare/v5...v6)

Updates `pypa/cibuildwheel` from 2.17 to 3.1
- [Release notes](https://github.com/pypa/cibuildwheel/releases)
- [Changelog](https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md)
- [Commits](https://github.com/pypa/cibuildwheel/compare/v2.17...v3.1)

Updates `actions/download-artifact` from 4 to 5
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: actions/setup-python
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: pypa/cibuildwheel
  dependency-version: '3.1'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: actions/download-artifact
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-09-29 01:37:02 +00:00
11 changed files with 555 additions and 133 deletions

View File

@ -15,8 +15,8 @@ jobs:
name: Format name: Format
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v5
- uses: actions/setup-python@v5 - uses: actions/setup-python@v6
with: with:
python-version: "3.x" python-version: "3.x"
- uses: pre-commit/action@v3.0.1 - uses: pre-commit/action@v3.0.1

View File

@ -19,11 +19,11 @@ jobs:
runs-on: ${{ matrix.platform }} runs-on: ${{ matrix.platform }}
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v5
with: with:
submodules: true submodules: true
- uses: actions/setup-python@v5 - uses: actions/setup-python@v6
with: with:
python-version: ${{ matrix.python-version }} python-version: ${{ matrix.python-version }}

View File

@ -15,7 +15,7 @@ jobs:
name: Build SDist name: Build SDist
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v5
with: with:
submodules: true submodules: true
@ -39,12 +39,12 @@ jobs:
arch: [x86_64] arch: [x86_64]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v5
with: with:
submodules: true submodules: true
- name: Build wheels - name: Build wheels
uses: pypa/cibuildwheel@v2.17 uses: pypa/cibuildwheel@v3.2
env: env:
CIBW_PLATFORM: linux CIBW_PLATFORM: linux
CIBW_ARCHS_LINUX: ${{ matrix.arch }} CIBW_ARCHS_LINUX: ${{ matrix.arch }}
@ -80,7 +80,7 @@ jobs:
steps: steps:
- name: Download all artifacts - name: Download all artifacts
uses: actions/download-artifact@v4 uses: actions/download-artifact@v5
with: with:
pattern: cibw-* pattern: cibw-*
path: dist path: dist

View File

@ -1,24 +1,43 @@
# Py-libbpf <picture>
<source
media="(prefers-color-scheme: light)"
srcset="https://github.com/user-attachments/assets/dbd56f5b-4512-4c82-a404-30bce0ee5207"
width="450"
alt="pylibbpf light mode">
<img
src="https://github.com/user-attachments/assets/9e873d60-a834-4411-bc0c-361b14502f8b"
width="450"
alt="pylibbpf dark mode">
</picture>
<p align="center"> <p align="center">
<a href="https://www.python.org/downloads/release/python-3080/"><img src="https://img.shields.io/badge/python-3.8-blue.svg"></a> <!-- PyPI -->
<a href="https://pypi.org/project/pylibbpf"><img src="https://badge.fury.io/py/pylibbpf.svg"></a> <a href="https://www.python.org/downloads/release/python-3080/"><img src="https://img.shields.io/badge/python-3.8-blue.svg"></a>
<a href="https://pypi.org/project/pylibbpf"><img src="https://badge.fury.io/py/pylibbpf.svg"></a>
<!-- <a href="https://pypi.org/project/pythonbpf/"><img src="https://img.shields.io/pypi/status/pythonbpf" alt="PyPI Status"></a> -->
<a href="https://pepy.tech/project/pylibbpf"><img src="https://pepy.tech/badge/pylibbpf" alt="Downloads"></a>
<!-- Build & CI -->
<a href="https://github.com/pythonbpf/pylibbpf/actions"><img src="https://github.com/pythonbpf/pylibbpf/actions/workflows/wheels.yml/badge.svg" alt="Build Status"></a>
<!-- Meta -->
<a href="https://github.com/pythonbpf/pylibbpf/blob/master/LICENSE"><img src="https://img.shields.io/github/license/pythonbpf/pylibbpf" alt="License"></a>
</p> </p>
This library provides Python bindings for libbpf on Linux to make loading of eBPF object files easier. This is meant to
be used along with `pythonbpf`, the eBPF Python DSL compiler. This library makes it possible to attach these programs to
events in the kernel right from inside Python.
# IN DEVELOPMENT. DO NOT USE. This library provides Python bindings for **libbpf** on Linux, making it easier to load eBPF object files. It is designed to be used together with [PythonBPF](https://github.com/pythonbpf/python-bpf), the eBPF compiler for Python. With these bindings, you can attach eBPF programs to kernel events directly from Python.
All programs written with this are to be run with a `sudo` Python interpreter.
## Prerequisites > **Note**: This project is under active development and not ready for production use.
## Dependencies
* A compiler with C++11 support * A compiler with C++11 support
* Pip 10+ or CMake >= 4.1 * Pip 10+ or CMake >= 4.1
* Ninja or Pip 10+ * Ninja or Pip 10+
## Installation ## Installation
`pip install pylibbpf`
Just clone this repository and pip install. Note the `--recursive` option which is ## Development
Clone this repository and pip install. Note the `--recursive` option which is
needed for the pybind11 submodule: needed for the pybind11 submodule:
```bash ```bash
@ -30,11 +49,5 @@ pip install .
With the `setup.py` file included in this example, the `pip install` command will With the `setup.py` file included in this example, the `pip install` command will
invoke CMake and build the pybind11 module as specified in `CMakeLists.txt`. invoke CMake and build the pybind11 module as specified in `CMakeLists.txt`.
## Development
Do this before running to make sure Python can manipulate bpf programs without sudo
```bash
sudo setcap cap_bpf,cap_sys_admin+ep /usr/bin/python3.12
```
## Building the documentation ## Building the documentation
The documentation here is still boilerplate. The documentation here is still boilerplate.

View File

@ -1,54 +1,44 @@
#ifndef PYLIBBPF_MAPS_H #ifndef PYLIBBPF_BPF_MAP_H
#define PYLIBBPF_MAPS_H #define PYLIBBPF_BPF_MAP_H
#include <libbpf.h> #include <libbpf.h>
#include <pybind11/pybind11.h> #include <pybind11/pybind11.h>
#include <vector> #include <vector>
#include <string> #include <string>
#include "bpf_program.h" class BpfObject;
namespace py = pybind11; namespace py = pybind11;
class BpfMap { class BpfMap {
private: private:
std::weak_ptr<BpfObject> parent_obj_;
struct bpf_map *map_; struct bpf_map *map_;
int map_fd = -1; int map_fd_;
//TODO: turn below into a shared pointer and ref count it so that there is no resource leakage std::string map_name_;
BpfProgram *bpf_program;
public: public:
BpfMap(BpfProgram *program_, const py::object &map_from_python); BpfMap(std::shared_ptr<BpfObject>, struct bpf_map *raw_map, const std::string &map_name);
~BpfMap() = default; ~BpfMap() = default;
[[nodiscard]] py::object lookup(const py::object &key) const; [[nodiscard]] py::object lookup(const py::object &key) const;
void update(const py::object &key, const py::object &value) const; void update(const py::object &key, const py::object &value) const;
void delete_elem(const py::object &key) const; void delete_elem(const py::object &key) const;
py::list get_next_key(const py::object &key = py::none()) const; py::list get_next_key(const py::object &key = py::none()) const;
py::dict items() const; py::dict items() const;
py::list keys() const; py::list keys() const;
py::list values() const; py::list values() const;
[[nodiscard]] std::string get_name() const; [[nodiscard]] std::string get_name() const { return map_name_; }
[[nodiscard]] int get_fd() const { return map_fd_; }
int get_type() const; [[nodiscard]] int get_type() const;
[[nodiscard]] int get_key_size() const;
int get_key_size() const; [[nodiscard]] int get_value_size() const;
[[nodiscard]] int get_max_entries() const;
int get_value_size() const;
int get_max_entries() const;
private: private:
static std::vector<uint8_t> python_to_bytes(const py::object &obj, size_t size); static std::vector<uint8_t> python_to_bytes(const py::object &obj, size_t size);
static py::object bytes_to_python(const std::vector<uint8_t> &data); static py::object bytes_to_python(const std::vector<uint8_t> &data);
}; };

255
src/core/bpf_object.cpp Normal file
View File

@ -0,0 +1,255 @@
#include "bpf_object.h"
#include "bpf_program.h"
#include "bpf_map.h"
#include "bpf_exception.h"
#include <cerrno>
BpfObject::BpfObject(std::string object_path)
: obj_(nullptr), object_path_(std::move(object_path)), loaded_(false) {
}
BpfObject::~BpfObject() {
// Clear caches first (order matters!)
prog_cache_.clear(); // Detaches programs
maps_cache_.clear(); // Closes maps
// Then close object
if (obj_) {
bpf_object__close(obj_);
obj_ = nullptr;
}
}
BpfObject::BpfObject(BpfObject&& other) noexcept
: obj_(other.obj_),
object_path_(std::move(other.object_path_)),
loaded_(other.loaded_),
prog_cache_(std::move(other.prog_cache_)),
maps_cache_(std::move(other.maps_cache_)) {
other.obj_ = nullptr;
other.loaded_ = false;
}
BpfObject& BpfObject::operator=(BpfObject&& other) noexcept {
if (this != &other) {
prog_cache_.clear();
maps_cache_.clear();
if (obj_) {
bpf_object__close(obj_);
}
obj_ = other.obj_;
object_path_ = std::move(other.object_path_);
loaded_ = other.loaded_;
prog_cache_ = std::move(other.prog_cache_);
maps_cache_ = std::move(other.maps_cache_);
other.obj_ = nullptr;
other.loaded_ = false;
}
return *this;
}
void BpfObject::load() {
if (loaded_) {
throw BpfException("BPF object already loaded");
}
std::string error_msg = "Failed to open BPF object";
obj_ = bpf_object__open_file(object_path_.c_str(), nullptr);
if (!obj_) {
error_msg += " file '" + object_path_ + "': " + std::strerror(errno);
throw BpfException(error_msg);
}
if (bpf_object__load(obj_)) {
error_msg += " object from file '" + object_path_ + "': " + std::strerror(errno);
bpf_object__close(obj_);
obj_ = nullptr;
throw BpfException(error_msg);
}
loaded_ = true;
}
// ==================== Program Methods ====================
py::list BpfObject::get_program_names() const {
if (!loaded_) {
throw BpfException("BPF object not loaded");
}
py::list names;
struct bpf_program *prog = nullptr;
bpf_object__for_each_program(prog, obj_) {
_get_or_create_program(prog); // Ensure cached
names.append(bpf_program__name(prog));
}
return names;
}
std::shared_ptr<BpfProgram> BpfObject::_get_or_create_program(struct bpf_program *prog) {
if (!prog) {
throw BpfException("bpf_program pointer is null");
}
const char *name = bpf_program__name(prog);
std::string prog_name(name ? name : "");
// Check cache
auto it = prog_cache_.find(prog_name);
if (it != prog_cache_.end()) {
return it->second;
}
// Create and cache
auto bpf_prog = std::make_shared<BpfProgram>(this, prog, prog_name);
prog_cache_[prog_name] = bpf_prog;
return bpf_prog;
}
std::shared_ptr<BpfProgram> BpfObject::get_program(const std::string& name) {
if (!loaded_) {
throw BpfException("BPF object not loaded");
}
// Check cache
auto it = prog_cache_.find(name);
if (it != prog_cache_.end()) {
return it->second;
}
// Create and cache
struct bpf_program *raw_prog = find_program_by_name(name);
auto prog = std::make_shared<BpfProgram>(this, raw_prog, name);
prog_cache_[name] = prog;
return prog;
}
struct bpf_program* BpfObject::find_program_by_name(const std::string& name) const {
if (!loaded_) {
throw BpfException("BPF object not loaded");
}
struct bpf_program *prog = bpf_object__find_program_by_name(obj_, name.c_str());
if (!prog) {
throw BpfException("Program '" + name + "' not found");
}
return prog;
}
py::dict BpfObject::get_cached_programs() const {
py::dict programs;
for (const auto& [name, prog] : prog_cache_) {
programs[name] = prog;
}
return programs;
}
py::dict BpfObject::attach_all() {
if (!loaded_) {
throw BpfException("BPF object not loaded");
}
py::dict attached_programs;
struct bpf_program *prog = nullptr;
bpf_object__for_each_program(prog, obj_) {
auto bpf_prog = _get_or_create_program(prog);
if (!bpf_prog->is_attached()) {
bpf_prog->attach();
}
const char *name = bpf_program__name(prog);
attached_programs[name] = bpf_prog;
}
return attached_programs;
}
// ==================== Map Methods ====================
py::list BpfObject::get_map_names() const {
if (!loaded_) {
throw BpfException("BPF object not loaded");
}
py::list names;
struct bpf_map *map = nullptr;
bpf_object__for_each_map(map, obj_) {
_get_or_create_map(map); // Ensure cached
names.append(bpf_map__name(map));
}
return names;
}
std::shared_ptr<BpfMap> BpfObject::get_map(const std::string& name) {
if (!loaded_) {
throw BpfException("BPF object not loaded");
}
// Check cache
auto it = maps_cache_.find(name);
if (it != maps_cache_.end()) {
return it->second;
}
// Create and cache
struct bpf_map *raw_map = find_map_by_name(name);
auto map = std::make_shared<BpfMap>(shared_from_this(), raw_map, name);
maps_cache_[name] = map;
return map;
}
std::shared_ptr<BpfMap> BpfObject::_get_or_create_map(struct bpf_map *map) {
if (!map) {
throw BpfException("bpf_map pointer is null");
}
const char *name = bpf_map__name(map);
std::string map_name(name ? name : "");
// Check cache
auto it = maps_cache_.find(map_name);
if (it != maps_cache_.end()) {
return it->second;
}
// Create and cache
auto bpf_map = std::make_shared<BpfMap>(shared_from_this(), map, map_name);
maps_cache_[map_name] = bpf_map;
return bpf_map;
}
struct bpf_map* BpfObject::find_map_by_name(const std::string& name) const {
if (!loaded_) {
throw BpfException("BPF object not loaded");
}
struct bpf_map *map = bpf_object__find_map_by_name(obj_, name.c_str());
if (!map) {
throw BpfException("Map '" + name + "' not found");
}
return map;
}
py::dict BpfObject::get_cached_maps() const {
py::dict maps;
for (const auto& [name, map] : maps_cache_) {
maps[name] = map;
}
return maps;
}

79
src/core/bpf_object.h Normal file
View File

@ -0,0 +1,79 @@
#ifndef PYLIBBPF_BPF_OBJECT_H
#define PYLIBBPF_BPF_OBJECT_H
#include <libbpf.h>
#include <pybind11/pybind11.h>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
namespace py = pybind11;
class BpfProgram;
class BpfMap;
/**
* BpfObject - Represents a loaded BPF object file.
*
* This is the main entry point for loading BPF programs.
* Owns the bpf_object* and manages all programs and maps within it.
*/
class BpfObject : public std::enable_shared_from_this<BpfObject> {
private:
struct bpf_object *obj_;
std::string object_path_;
bool loaded_;
mutable std::unordered_map<std::string, std::shared_ptr<BpfMap>> maps_cache_;
mutable std::unordered_map<std::string, std::shared_ptr<BpfProgram>> prog_cache_;
std::shared_ptr<BpfProgram> _get_or_create_program(struct bpf_program *prog);
std::shared_ptr<BpfMap> _get_or_create_map(struct bpf_map *map);
public:
explicit BpfObject(std::string object_path);
~BpfObject();
// Disable copy, allow move
BpfObject(const BpfObject&) = delete;
BpfObject& operator=(const BpfObject&) = delete;
BpfObject(BpfObject&&) noexcept;
BpfObject& operator=(BpfObject&&) noexcept;
/**
* Load the BPF object into the kernel.
* Must be called before accessing programs or maps.
*/
void load();
/**
* Check if object is loaded.
*/
[[nodiscard]] bool is_loaded() const { return loaded_; }
/**
* Get the underlying bpf_object pointer.
* Only for internal use by BpfProgram and BpfMap.
*/
[[nodiscard]] struct bpf_object* get_obj() const { return obj_; }
/**
* Attach all programs in the object.
*/
py::dict attach_all();
// Program access
[[nodiscard]] py::list get_program_names() const;
[[nodiscard]] std::shared_ptr<BpfProgram> get_program(const std::string& name);
[[nodiscard]] struct bpf_program* find_program_by_name(const std::string& name) const;
[[nodiscard]] py::dict get_cached_programs() const;
// Map access
[[nodiscard]] py::list get_map_names() const;
[[nodiscard]] std::shared_ptr<BpfMap> get_map(const std::string& name);
[[nodiscard]] struct bpf_map* find_map_by_name(const std::string& name) const;
[[nodiscard]] py::dict get_cached_maps() const;
};
#endif // PYLIBBPF_BPF_OBJECT_H

View File

@ -0,0 +1,72 @@
#include "bpf_perf_buffer.h"
#include "bpf_exception.h"
void BpfPerfBuffer::sample_callback_wrapper(void *ctx, int cpu, void *data, unsigned int size) {
auto *self = static_cast<BpfPerfBuffer *>(ctx);
// Acquire GIL for Python calls
py::gil_scoped_acquire acquire;
try {
// Convert data to Python bytes
py::bytes py_data(static_cast<const char *>(data), size);
// Call Python callback: callback(cpu, data, size)
self->callback_(cpu, py_data, size);
} catch (const py::error_already_set &e) {
PyErr_Print();
}
}
void BpfPerfBuffer::lost_callback_wrapper(void *ctx, int cpu, unsigned long long cnt) {
auto *self = static_cast<BpfPerfBuffer *>(ctx);
if (self->lost_callback_.is_none()) {
return;
}
py::gil_scoped_acquire acquire;
try {
self->lost_callback_(cpu, cnt);
} catch (const py::error_already_set &e) {
PyErr_Print();
}
}
BpfPerfBuffer::BpfPerfBuffer(int map_fd, int page_cnt, py::function callback, py::object lost_callback)
: pb_(nullptr), callback_(std::move(callback)) {
if (!lost_callback.is_none()) {
lost_callback_ = lost_callback.cast<py::function>();
}
// Setup perf buffer options
perf_buffer_opts pb_opts = {};
pb_opts.sample_cb = sample_callback_wrapper;
pb_opts.lost_cb = lost_callback.is_none() ? nullptr : lost_callback_wrapper;
pb_opts.ctx = this;
// Create perf buffer
pb_ = perf_buffer__new(map_fd, page_cnt, &pb_opts);
if (!pb_) {
throw BpfException("Failed to create perf buffer");
}
}
BpfPerfBuffer::~BpfPerfBuffer() {
if (pb_) {
perf_buffer__free(pb_);
}
}
int BpfPerfBuffer::poll(int timeout_ms) {
// Release GIL during blocking poll
py::gil_scoped_release release;
return perf_buffer__poll(pb_, timeout_ms);
}
int BpfPerfBuffer::consume() {
py::gil_scoped_release release;
return perf_buffer__consume(pb_);
}

View File

@ -0,0 +1,28 @@
#ifndef PYLIBBPF_BPF_PERF_BUFFER_H
#define PYLIBBPF_BPF_PERF_BUFFER_H
#include <libbpf.h>
#include <pybind11/pybind11.h>
#include <pybind11/functional.h>
namespace py = pybind11;
class BpfPerfBuffer {
private:
struct perf_buffer *pb_;
py::function callback_;
py::function lost_callback_;
// Static callback wrappers for C API
static void sample_callback_wrapper(void *ctx, int cpu, void *data, unsigned int size);
static void lost_callback_wrapper(void *ctx, int cpu, unsigned long long cnt);
public:
BpfPerfBuffer(int map_fd, int page_cnt, py::function callback, py::object lost_callback);
~BpfPerfBuffer();
int poll(int timeout_ms);
int consume();
};
#endif // PYLIBBPF_BPF_PERF_BUFFER_H

View File

@ -1,84 +1,73 @@
#include "bpf_program.h" #include "bpf_program.h"
#include "bpf_exception.h" #include "bpf_exception.h"
#include <filesystem>
#include <utility> #include <utility>
#include <cerrno>
BpfProgram::BpfProgram(std::string object_path, std::string program_name) BpfProgram::BpfProgram(std::shared_ptr<BpfObject> parent, struct bpf_program *raw_prog, const std::string& program_name)
: obj_(nullptr), prog_(nullptr), link_(nullptr), : parent_obj_(parent),
object_path_(std::move(object_path)), program_name_(std::move(program_name)) { prog_(raw_prog),
link_(nullptr),
program_name_(program_name) {
if (!parent)
throw BpfException("Parent BpfObject is null");
if (!raw_prog)
throw BpfException("bpf_program pointer is null");
} }
BpfProgram::~BpfProgram() { BpfProgram::~BpfProgram() {
destroy(); detach();
if (obj_) { }
bpf_object__close(obj_);
BpfProgram::BpfProgram(BpfProgram&& other) noexcept
: parent_obj_(std::move(other.parent_obj_)),
prog_(other.prog_),
link_(other.link_),
program_name_(std::move(other.program_name_)) {
other.prog_ = nullptr;
other.link_ = nullptr;
}
BpfProgram& BpfProgram::operator=(BpfProgram&& other) noexcept {
if (this != &other) {
detach();
parent_obj_ = std::move(other.parent_obj_);
prog_ = other.prog_;
link_ = other.link_;
program_name_ = std::move(other.program_name_);
other.prog_ = nullptr;
other.link_ = nullptr;
}
return *this;
}
void BpfProgram::attach() {
// Check if parent is still alive
auto parent = parent_obj_.lock();
if (!parent) {
throw BpfException("Parent BpfObject has been destroyed");
}
if (link_) {
throw BpfException("Program '" + program_name_ + "' already attached");
}
if (!prog_) {
throw BpfException("Program '" + program_name_ + "' not initialized");
}
link_ = bpf_program__attach(prog_);
if (!link_) {
std::string err_msg = "bpf_program__attach failed for program '" + program_name_ + "': " + std::strerror(errno);
throw BpfException(err_msg);
} }
} }
struct bpf_object * BpfProgram::get_obj() const { void BpfProgram::detach() {
return obj_; if (link_) {
} bpf_link__destroy(link_);
link_ = nullptr;
bool BpfProgram::load() {
// Open the eBPF object file
obj_ = bpf_object__open_file(object_path_.c_str(), nullptr);
if (libbpf_get_error(obj_)) {
throw BpfException("Failed to open BPF object file: " + object_path_);
} }
// Find the program by name (if specified)
if (!program_name_.empty()) {
prog_ = bpf_object__find_program_by_name(obj_, program_name_.c_str());
if (!prog_) {
throw BpfException("Program '" + program_name_ + "' not found in object");
}
} else {
while ((prog_ = bpf_object__next_program(obj_, prog_)) != nullptr) {
programs.emplace_back(prog_, nullptr);
}
// throw if no programs found
if (programs.empty()) {
throw BpfException("No programs found in object file");
}
}
// Load the eBPF object into the kernel
if (bpf_object__load(obj_)) {
throw BpfException("Failed to load BPF object into kernel");
}
return true;
}
bool BpfProgram::attach() {
for (auto [prog, link]: programs) {
if (!prog) {
throw BpfException("Program not loaded");
}
link = bpf_program__attach(prog);
if (libbpf_get_error(link)) {
link = nullptr;
throw BpfException("Failed to attach BPF program");
}
}
return true;
}
bool BpfProgram::destroy() {
bool success = true;
for (auto [prog, link]: programs) {
if (!prog) {
throw BpfException("Program not loaded");
}
success = success & bpf_link__destroy(link);
}
return success;
}
void BpfProgram::load_and_attach() {
load();
attach();
} }

View File

@ -2,37 +2,33 @@
#define PYLIBBPF_BPF_PROGRAM_H #define PYLIBBPF_BPF_PROGRAM_H
#include <libbpf.h> #include <libbpf.h>
#include <pybind11/stl.h> #include <memory>
#include <string> #include <string>
namespace py = pybind11; class BpfObject;
class BpfProgram { class BpfProgram {
private: private:
struct bpf_object *obj_; std::weak_ptr<BpfObject> parent_obj_;
struct bpf_program *prog_; struct bpf_program *prog_;
struct bpf_link *link_; struct bpf_link *link_;
std::string object_path_;
std::string program_name_; std::string program_name_;
std::vector<std::pair<bpf_program *, bpf_link *> > programs;
public: public:
explicit BpfProgram(std::string object_path, std::string program_name = ""); explicit BpfProgram(std::shared_ptr<BpfObject> parent, struct bpf_program *raw_prog, const std::string& program_name);
~BpfProgram(); ~BpfProgram();
struct bpf_object *get_obj() const; BpfProgram(const BpfProgram&) = delete;
BpfProgram& operator=(const BpfProgram&) = delete;
bool load(); BpfProgram(BpfProgram&&) noexcept;
BpfProgram& operator=(BpfProgram&&) noexcept;
bool attach(); bool attach();
bool detach();
bool destroy();
void load_and_attach();
[[nodiscard]] bool is_loaded() const { return obj_ != nullptr; }
[[nodiscard]] bool is_attached() const { return link_ != nullptr; } [[nodiscard]] bool is_attached() const { return link_ != nullptr; }
[[nodiscard]] std::string get_name() const { return program_name_; }
}; };
#endif //PYLIBBPF_BPF_PROGRAM_H #endif //PYLIBBPF_BPF_PROGRAM_H