Add basic class along with exception and attach

Signed-off-by: varun-r-mallya <varunrmallya@gmail.com>
This commit is contained in:
2025-09-21 14:27:07 +05:30
parent ecefff6b81
commit 3c8c6deb68
8 changed files with 156 additions and 53 deletions

16
src/core/bpf_exception.h Normal file
View File

@ -0,0 +1,16 @@
#ifndef PYLIBBPF_BPF_EXCEPTION_H
#define PYLIBBPF_BPF_EXCEPTION_H
#include <stdexcept>
#include <string>
class BpfException final : public std::runtime_error {
public:
explicit BpfException(const std::string& message)
: std::runtime_error(message) {}
explicit BpfException(const char* message)
: std::runtime_error(message) {}
};
#endif // PYLIBBPF_BPF_EXCEPTION_H

58
src/core/bpf_program.cpp Normal file
View File

@ -0,0 +1,58 @@
#include "bpf_program.h"
#include "bpf_exception.h"
#include <filesystem>
BpfProgram::BpfProgram(const std::string& object_path, const std::string& program_name)
: obj_(nullptr), prog_(nullptr), link_(nullptr),
object_path_(object_path), program_name_(program_name) {
}
BpfProgram::~BpfProgram() {
//TODO: detach here as well
if (obj_) {
bpf_object__close(obj_);
}
}
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 {
// Use the first program if no name specified
prog_ = bpf_object__next_program(obj_, nullptr);
if (!prog_) {
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() {
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;
}

29
src/core/bpf_program.h Normal file
View File

@ -0,0 +1,29 @@
#ifndef PYLIBBPF_BPF_PROGRAM_H
#define PYLIBBPF_BPF_PROGRAM_H
#include "libbpf.h"
#include <pybind11/stl.h>
#include <string>
namespace py = pybind11;
class BpfProgram {
private:
struct bpf_object* obj_;
struct bpf_program* prog_;
struct bpf_link* link_;
std::string object_path_;
std::string program_name_;
public:
explicit BpfProgram(const std::string& object_path, const std::string& program_name = "");
~BpfProgram();
bool load();
bool attach();
bool is_loaded() const { return obj_ != nullptr; }
bool is_attached() const { return link_ != nullptr; }
};
#endif //PYLIBBPF_BPF_PROGRAM_H