Janitorial: clang-format

This commit is contained in:
Pragyansh Chaturvedi
2025-10-18 21:00:16 +05:30
parent c5a485b526
commit 4a5ff0c1c2
8 changed files with 623 additions and 637 deletions

View File

@ -1,250 +1,227 @@
#include "bpf_map.h" #include "bpf_map.h"
#include "bpf_object.h"
#include "bpf_exception.h" #include "bpf_exception.h"
#include "bpf_object.h"
BpfMap::BpfMap(std::shared_ptr<BpfObject> parent, struct bpf_map *raw_map, const std::string &map_name) BpfMap::BpfMap(std::shared_ptr<BpfObject> parent, struct bpf_map *raw_map,
: parent_obj_(parent), const std::string &map_name)
map_(raw_map), : parent_obj_(parent), map_(raw_map), map_fd_(-1), map_name_(map_name),
map_fd_(-1), key_size_(0), value_size_(0) {
map_name_(map_name), if (!parent)
key_size_(0), throw BpfException("Parent BpfObject is null");
value_size_(0) { if (!(parent->is_loaded()))
if (!parent) throw BpfException("Parent BpfObject is not loaded");
throw BpfException("Parent BpfObject is null"); if (!raw_map)
if(!(parent->is_loaded())) throw BpfException("bpf_map pointer is null");
throw BpfException("Parent BpfObject is not loaded");
if (!raw_map)
throw BpfException("bpf_map pointer is null");
map_fd_ = bpf_map__fd(map_); map_fd_ = bpf_map__fd(map_);
if (map_fd_ < 0) if (map_fd_ < 0)
throw BpfException("Failed to get file descriptor for map '" + map_name_ + "'"); throw BpfException("Failed to get file descriptor for map '" + map_name_ +
"'");
key_size_ = bpf_map__key_size(map_); key_size_ = bpf_map__key_size(map_);
value_size_ = bpf_map__value_size(map_); value_size_ = bpf_map__value_size(map_);
} }
py::object BpfMap::lookup(const py::object &key) const { py::object BpfMap::lookup(const py::object &key) const {
if (map_fd_ < 0) if (map_fd_ < 0)
throw BpfException("Map '" + map_name_ + "' is not initialized properly"); throw BpfException("Map '" + map_name_ + "' is not initialized properly");
BufferManager<> key_buf, value_buf; BufferManager<> key_buf, value_buf;
auto key_span = key_buf.get_span(key_size_); auto key_span = key_buf.get_span(key_size_);
auto value_span = value_buf.get_span(value_size_); auto value_span = value_buf.get_span(value_size_);
// Convert Python → bytes // Convert Python → bytes
python_to_bytes_inplace(key, key_span); python_to_bytes_inplace(key, key_span);
// The flags field here matters only when spin locks are used. // The flags field here matters only when spin locks are used.
// Skipping it for now. // Skipping it for now.
const int ret = bpf_map__lookup_elem( const int ret = bpf_map__lookup_elem(map_, key_span.data(), key_size_,
map_, value_span.data(), value_size_, BPF_ANY);
key_span.data(), if (ret < 0) {
key_size_, if (ret == -ENOENT)
value_span.data(), throw py::key_error("Key not found in map '" + map_name_ + "'");
value_size_, throw BpfException("Failed to lookup key in map '" + map_name_ +
BPF_ANY); "': " + std::strerror(-ret));
if (ret < 0) { }
if (ret == -ENOENT)
throw py::key_error("Key not found in map '" + map_name_ + "'");
throw BpfException(
"Failed to lookup key in map '" + map_name_ + "': " +
std::strerror(-ret)
);
}
return bytes_to_python(value_span); return bytes_to_python(value_span);
} }
void BpfMap::update(const py::object &key, const py::object &value) const { void BpfMap::update(const py::object &key, const py::object &value) const {
if (map_fd_ < 0) if (map_fd_ < 0)
throw BpfException("Map '" + map_name_ + "' is not initialized properly"); throw BpfException("Map '" + map_name_ + "' is not initialized properly");
BufferManager<> key_buf, value_buf; BufferManager<> key_buf, value_buf;
auto key_span = key_buf.get_span(key_size_); auto key_span = key_buf.get_span(key_size_);
auto value_span = value_buf.get_span(value_size_); auto value_span = value_buf.get_span(value_size_);
python_to_bytes_inplace(key, key_span); python_to_bytes_inplace(key, key_span);
python_to_bytes_inplace(value, value_span); python_to_bytes_inplace(value, value_span);
const int ret = bpf_map__update_elem( const int ret = bpf_map__update_elem(map_, key_span.data(), key_size_,
map_, value_span.data(), value_size_, BPF_ANY);
key_span.data(), if (ret < 0) {
key_size_, throw BpfException("Failed to update key in map '" + map_name_ +
value_span.data(), "': " + std::strerror(-ret));
value_size_, }
BPF_ANY);
if (ret < 0) {
throw BpfException(
"Failed to update key in map '" + map_name_ + "': " +
std::strerror(-ret)
);
}
} }
void BpfMap::delete_elem(const py::object &key) const { void BpfMap::delete_elem(const py::object &key) const {
if (map_fd_ < 0) if (map_fd_ < 0)
throw BpfException("Map '" + map_name_ + "' is not initialized properly"); throw BpfException("Map '" + map_name_ + "' is not initialized properly");
BufferManager<> key_buf; BufferManager<> key_buf;
auto key_span = key_buf.get_span(key_size_); auto key_span = key_buf.get_span(key_size_);
// Convert Python → bytes // Convert Python → bytes
python_to_bytes_inplace(key, key_span); python_to_bytes_inplace(key, key_span);
const int ret = bpf_map__delete_elem(map_, key_span.data(), key_size_, BPF_ANY); const int ret =
bpf_map__delete_elem(map_, key_span.data(), key_size_, BPF_ANY);
if (ret != 0) { if (ret != 0) {
if (ret == -ENOENT) if (ret == -ENOENT)
throw py::key_error("Key not found in map '" + map_name_ + "'"); throw py::key_error("Key not found in map '" + map_name_ + "'");
throw BpfException( throw BpfException("Failed to delete key from map '" + map_name_ +
"Failed to delete key from map '" + map_name_ + "': " + "': " + std::strerror(-ret));
std::strerror(-ret) }
);
}
} }
py::object BpfMap::get_next_key(const py::object &key) const { py::object BpfMap::get_next_key(const py::object &key) const {
BufferManager<> next_key_buf; BufferManager<> next_key_buf;
auto next_key = next_key_buf.get_span(key_size_); auto next_key = next_key_buf.get_span(key_size_);
int ret; int ret;
if (key.is_none()) { if (key.is_none()) {
ret = bpf_map__get_next_key(map_, nullptr, next_key.data(), key_size_); ret = bpf_map__get_next_key(map_, nullptr, next_key.data(), key_size_);
} else { } else {
BufferManager<> key_buf; BufferManager<> key_buf;
auto key_bytes = key_buf.get_span(key_size_); auto key_bytes = key_buf.get_span(key_size_);
python_to_bytes_inplace(key, key_bytes); python_to_bytes_inplace(key, key_bytes);
ret = bpf_map__get_next_key(map_, key_bytes.data(), next_key.data(), key_size_); ret = bpf_map__get_next_key(map_, key_bytes.data(), next_key.data(),
key_size_);
}
if (ret < 0) {
if (ret == -ENOENT) {
// No more keys
return py::none();
} }
throw BpfException("Failed to get next key in map '" + map_name_ +
"': " + std::strerror(-ret));
}
if (ret < 0) { return bytes_to_python(next_key);
if (ret == -ENOENT) {
// No more keys
return py::none();
}
throw BpfException(
"Failed to get next key in map '" + map_name_ + "': " +
std::strerror(-ret)
);
}
return bytes_to_python(next_key);
} }
py::dict BpfMap::items() const { py::dict BpfMap::items() const {
py::dict result; py::dict result;
py::object current_key = get_next_key(py::none());
if (current_key.is_none()) {
return result;
}
while (!current_key.is_none()) {
try {
py::object value = lookup(current_key);
result[current_key] = value;
current_key = get_next_key(current_key);
} catch (const py::key_error&) {
break;
}
}
py::object current_key = get_next_key(py::none());
if (current_key.is_none()) {
return result; return result;
}
while (!current_key.is_none()) {
try {
py::object value = lookup(current_key);
result[current_key] = value;
current_key = get_next_key(current_key);
} catch (const py::key_error &) {
break;
}
}
return result;
} }
py::list BpfMap::keys() const { py::list BpfMap::keys() const {
py::list result; py::list result;
py::object current_key = get_next_key(py::none());
if (current_key.is_none()) {
return result;
}
while (!current_key.is_none()) {
result.append(current_key);
current_key = get_next_key(current_key);
}
py::object current_key = get_next_key(py::none());
if (current_key.is_none()) {
return result; return result;
}
while (!current_key.is_none()) {
result.append(current_key);
current_key = get_next_key(current_key);
}
return result;
} }
py::list BpfMap::values() const { py::list BpfMap::values() const {
py::list result; py::list result;
py::object current_key = get_next_key(py::none());
if (current_key.is_none()) {
return result;
}
while (!current_key.is_none()) {
try {
py::object value = lookup(current_key);
result.append(value);
current_key = get_next_key(current_key);
} catch (const py::key_error&) {
break;
}
}
py::object current_key = get_next_key(py::none());
if (current_key.is_none()) {
return result; return result;
}
while (!current_key.is_none()) {
try {
py::object value = lookup(current_key);
result.append(value);
current_key = get_next_key(current_key);
} catch (const py::key_error &) {
break;
}
}
return result;
} }
int BpfMap::get_type() const { int BpfMap::get_type() const { return bpf_map__type(map_); }
return bpf_map__type(map_);
}
int BpfMap::get_max_entries() const {
return bpf_map__max_entries(map_);
}
int BpfMap::get_max_entries() const { return bpf_map__max_entries(map_); }
// Helper functions // Helper functions
void BpfMap::python_to_bytes_inplace(const py::object &obj, std::span<uint8_t> buffer) { void BpfMap::python_to_bytes_inplace(const py::object &obj,
std::fill(buffer.begin(), buffer.end(), 0); std::span<uint8_t> buffer) {
std::fill(buffer.begin(), buffer.end(), 0);
if (py::isinstance<py::int_>(obj)) { if (py::isinstance<py::int_>(obj)) {
if (buffer.size() <= sizeof(uint64_t)) { if (buffer.size() <= sizeof(uint64_t)) {
uint64_t value = obj.cast<uint64_t>(); uint64_t value = obj.cast<uint64_t>();
std::memcpy(buffer.data(), &value, buffer.size()); std::memcpy(buffer.data(), &value, buffer.size());
} else {
throw BpfException("Integer key/value size exceeds maximum (8 bytes)");
}
} else if (py::isinstance<py::bytes>(obj)) {
std::string bytes_str = obj.cast<std::string>();
if (bytes_str.size() > buffer.size()) {
throw BpfException(
"Bytes size " + std::to_string(bytes_str.size()) +
" exceeds expected size " + std::to_string(buffer.size())
);
}
std::memcpy(buffer.data(), bytes_str.data(), bytes_str.size());
} else if (py::isinstance<py::str>(obj)) {
std::string str_val = obj.cast<std::string>();
if (str_val.size() >= buffer.size()) {
throw BpfException("String size exceeds expected size");
}
std::memcpy(buffer.data(), str_val.data(), str_val.size());
buffer[str_val.size()] = '\0';
} else { } else {
throw BpfException("Unsupported type for BPF map key/value"); throw BpfException("Integer key/value size exceeds maximum (8 bytes)");
} }
} else if (py::isinstance<py::bytes>(obj)) {
std::string bytes_str = obj.cast<std::string>();
if (bytes_str.size() > buffer.size()) {
throw BpfException("Bytes size " + std::to_string(bytes_str.size()) +
" exceeds expected size " +
std::to_string(buffer.size()));
}
std::memcpy(buffer.data(), bytes_str.data(), bytes_str.size());
} else if (py::isinstance<py::str>(obj)) {
std::string str_val = obj.cast<std::string>();
if (str_val.size() >= buffer.size()) {
throw BpfException("String size exceeds expected size");
}
std::memcpy(buffer.data(), str_val.data(), str_val.size());
buffer[str_val.size()] = '\0';
} else {
throw BpfException("Unsupported type for BPF map key/value");
}
} }
py::object BpfMap::bytes_to_python(std::span<const uint8_t> data) { py::object BpfMap::bytes_to_python(std::span<const uint8_t> data) {
if (data.size() == 4) { if (data.size() == 4) {
uint32_t value; uint32_t value;
std::memcpy(&value, data.data(), 4); std::memcpy(&value, data.data(), 4);
return py::cast(value); return py::cast(value);
} else if (data.size() == 8) { } else if (data.size() == 8) {
uint64_t value; uint64_t value;
std::memcpy(&value, data.data(), 8); std::memcpy(&value, data.data(), 8);
return py::cast(value); return py::cast(value);
} else { } else {
return py::bytes(reinterpret_cast<const char*>(data.data()), data.size()); return py::bytes(reinterpret_cast<const char *>(data.data()), data.size());
} }
} }

View File

@ -1,15 +1,15 @@
#ifndef PYLIBBPF_BPF_MAP_H #ifndef PYLIBBPF_BPF_MAP_H
#define PYLIBBPF_BPF_MAP_H #define PYLIBBPF_BPF_MAP_H
#include <algorithm>
#include <array>
#include <cerrno>
#include <cstring>
#include <libbpf.h> #include <libbpf.h>
#include <pybind11/pybind11.h> #include <pybind11/pybind11.h>
#include <vector>
#include <string>
#include <span> #include <span>
#include <array> #include <string>
#include <algorithm> #include <vector>
#include <cstring>
#include <cerrno>
class BpfObject; class BpfObject;
@ -17,55 +17,56 @@ namespace py = pybind11;
class BpfMap { class BpfMap {
private: private:
std::weak_ptr<BpfObject> parent_obj_; std::weak_ptr<BpfObject> parent_obj_;
struct bpf_map *map_; struct bpf_map *map_;
int map_fd_; int map_fd_;
std::string map_name_; std::string map_name_;
__u32 key_size_, value_size_; __u32 key_size_, value_size_;
template<size_t StackSize = 64> template <size_t StackSize = 64> struct BufferManager {
struct BufferManager { std::array<uint8_t, StackSize> stack_buf;
std::array<uint8_t, StackSize> stack_buf; std::vector<uint8_t> heap_buf;
std::vector<uint8_t> heap_buf;
std::span<uint8_t> get_span(size_t size) { std::span<uint8_t> get_span(size_t size) {
if (size <= StackSize) { if (size <= StackSize) {
return std::span<uint8_t>(stack_buf.data(), size); return std::span<uint8_t>(stack_buf.data(), size);
} else { } else {
heap_buf.resize(size); heap_buf.resize(size);
return std::span<uint8_t>(heap_buf); return std::span<uint8_t>(heap_buf);
} }
} }
}; };
public: public:
BpfMap(std::shared_ptr<BpfObject> parent, struct bpf_map *raw_map, const std::string &map_name); BpfMap(std::shared_ptr<BpfObject> parent, struct bpf_map *raw_map,
const std::string &map_name);
~BpfMap() = default; ~BpfMap() = default;
BpfMap(const BpfMap&) = delete; BpfMap(const BpfMap &) = delete;
BpfMap& operator=(const BpfMap&) = delete; BpfMap &operator=(const BpfMap &) = delete;
BpfMap(BpfMap&&) noexcept = default; BpfMap(BpfMap &&) noexcept = default;
BpfMap& operator=(BpfMap&&) noexcept = default; BpfMap &operator=(BpfMap &&) noexcept = 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::object get_next_key(const py::object &key = py::none()) const; py::object 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 { return map_name_; } [[nodiscard]] std::string get_name() const { return map_name_; }
[[nodiscard]] int get_fd() const { return map_fd_; } [[nodiscard]] int get_fd() const { return map_fd_; }
[[nodiscard]] int get_type() const; [[nodiscard]] int get_type() const;
[[nodiscard]] int get_key_size() const { return key_size_; }; [[nodiscard]] int get_key_size() const { return key_size_; };
[[nodiscard]] int get_value_size() const { return value_size_; }; [[nodiscard]] int get_value_size() const { return value_size_; };
[[nodiscard]] int get_max_entries() const; [[nodiscard]] int get_max_entries() const;
private: private:
static void python_to_bytes_inplace(const py::object &obj, std::span<uint8_t> buffer); static void python_to_bytes_inplace(const py::object &obj,
static py::object bytes_to_python(std::span<const uint8_t> data); std::span<uint8_t> buffer);
static py::object bytes_to_python(std::span<const uint8_t> data);
}; };
#endif //PYLIBBPF_MAPS_H #endif // PYLIBBPF_MAPS_H

View File

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

View File

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

View File

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

View File

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

View File

@ -1,75 +1,72 @@
#include "bpf_program.h" #include "bpf_program.h"
#include "bpf_exception.h" #include "bpf_exception.h"
#include <utility>
#include <cerrno> #include <cerrno>
#include <utility>
BpfProgram::BpfProgram(std::shared_ptr<BpfObject> parent, struct bpf_program *raw_prog, const std::string& program_name) BpfProgram::BpfProgram(std::shared_ptr<BpfObject> parent,
: parent_obj_(parent), struct bpf_program *raw_prog,
prog_(raw_prog), const std::string &program_name)
link_(nullptr), : parent_obj_(parent), prog_(raw_prog), link_(nullptr),
program_name_(program_name) { program_name_(program_name) {
if (!parent) if (!parent)
throw BpfException("Parent BpfObject is null"); throw BpfException("Parent BpfObject is null");
if(!(parent->is_loaded())) if (!(parent->is_loaded()))
throw BpfException("Parent BpfObject is not loaded"); throw BpfException("Parent BpfObject is not loaded");
if (!raw_prog) if (!raw_prog)
throw BpfException("bpf_program pointer is null"); throw BpfException("bpf_program pointer is null");
} }
BpfProgram::~BpfProgram() { BpfProgram::~BpfProgram() { detach(); }
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(); detach();
}
BpfProgram::BpfProgram(BpfProgram&& other) noexcept parent_obj_ = std::move(other.parent_obj_);
: parent_obj_(std::move(other.parent_obj_)), prog_ = other.prog_;
prog_(other.prog_), link_ = other.link_;
link_(other.link_), program_name_ = std::move(other.program_name_);
program_name_(std::move(other.program_name_)) {
other.prog_ = nullptr; other.prog_ = nullptr;
other.link_ = nullptr; other.link_ = nullptr;
} }
return *this;
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() { void BpfProgram::attach() {
// Check if parent is still alive // Check if parent is still alive
auto parent = parent_obj_.lock(); auto parent = parent_obj_.lock();
if (!parent) { if (!parent) {
throw BpfException("Parent BpfObject has been destroyed"); throw BpfException("Parent BpfObject has been destroyed");
} }
if (link_) { if (link_) {
throw BpfException("Program '" + program_name_ + "' already attached"); throw BpfException("Program '" + program_name_ + "' already attached");
} }
if (!prog_) { if (!prog_) {
throw BpfException("Program '" + program_name_ + "' not initialized"); throw BpfException("Program '" + program_name_ + "' not initialized");
} }
link_ = bpf_program__attach(prog_); link_ = bpf_program__attach(prog_);
if (!link_) { if (!link_) {
std::string err_msg = "bpf_program__attach failed for program '" + program_name_ + "': " + std::strerror(errno); std::string err_msg = "bpf_program__attach failed for program '" +
throw BpfException(err_msg); program_name_ + "': " + std::strerror(errno);
} throw BpfException(err_msg);
}
} }
void BpfProgram::detach() { void BpfProgram::detach() {
if (link_) { if (link_) {
bpf_link__destroy(link_); bpf_link__destroy(link_);
link_ = nullptr; link_ = nullptr;
} }
} }

View File

@ -9,26 +9,28 @@ class BpfObject;
class BpfProgram { class BpfProgram {
private: private:
std::weak_ptr<BpfObject> parent_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 program_name_; std::string program_name_;
public: public:
explicit BpfProgram(std::shared_ptr<BpfObject> parent, struct bpf_program *raw_prog, const std::string& program_name); explicit BpfProgram(std::shared_ptr<BpfObject> parent,
struct bpf_program *raw_prog,
const std::string &program_name);
~BpfProgram(); ~BpfProgram();
BpfProgram(const BpfProgram&) = delete; BpfProgram(const BpfProgram &) = delete;
BpfProgram& operator=(const BpfProgram&) = delete; BpfProgram &operator=(const BpfProgram &) = delete;
BpfProgram(BpfProgram&&) noexcept; BpfProgram(BpfProgram &&) noexcept;
BpfProgram& operator=(BpfProgram&&) noexcept; BpfProgram &operator=(BpfProgram &&) noexcept;
bool attach(); bool attach();
bool detach(); bool detach();
[[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_; } [[nodiscard]] std::string get_name() const { return program_name_; }
}; };
#endif //PYLIBBPF_BPF_PROGRAM_H #endif // PYLIBBPF_BPF_PROGRAM_H