From 05d5bba4f788898b73f68852f55276eea8e7afdc Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Sun, 19 Oct 2025 22:02:19 +0530 Subject: [PATCH] Add StructParser utility --- CMakeLists.txt | 17 ++++++++++++++--- src/utils/struct_parser.cpp | 25 +++++++++++++++++++++++++ src/utils/struct_parser.h | 20 ++++++++++++++++++++ 3 files changed, 59 insertions(+), 3 deletions(-) create mode 100644 src/utils/struct_parser.cpp create mode 100644 src/utils/struct_parser.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 268b08e..5aee60d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10,16 +10,27 @@ include_directories(${CMAKE_SOURCE_DIR}/src) add_subdirectory(pybind11) pybind11_add_module( pylibbpf + + # Core src/core/bpf_program.h src/core/bpf_exception.h src/core/bpf_map.h src/core/bpf_object.h - src/maps/bpf_perf_buffer.h - src/bindings/main.cpp src/core/bpf_program.cpp src/core/bpf_map.cpp src/core/bpf_object.cpp - src/maps/bpf_perf_buffer.cpp) + + # Maps + src/maps/bpf_perf_buffer.h + src/maps/bpf_perf_buffer.cpp + + # Utils + src/utils/struct_parser.h + src/utils/struct_parser.cpp + + # Bindings + src/bindings/main.cpp +) # --- libbpf build rules --- set(LIBBPF_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/libbpf/src) diff --git a/src/utils/struct_parser.cpp b/src/utils/struct_parser.cpp new file mode 100644 index 0000000..e1d1700 --- /dev/null +++ b/src/utils/struct_parser.cpp @@ -0,0 +1,25 @@ +#include "struct_parser.h" +#include "core/bpf_exception.h" + +StructParser::StructParser(py::dict structs) { + for (auto item : structs) { + std::string name = py::str(item.first); + struct_types_[name] = py::reinterpret_borrow(item.second); + } +} + +py::object StructParser::parse(const std::string &struct_name, py::bytes data) { + auto it = struct_types_.find(struct_name); + if (it == struct_types_.end()) { + throw BpfException("Unknown struct: " + struct_name); + } + + py::object struct_type = it->second; + + // Use ctypes.from_buffer_copy() to create struct from bytes + return struct_type.attr("from_buffer_copy")(data); +} + +bool StructParser::has_struct(const std::string &struct_name) const { + return struct_types_.find(struct_name) != struct_types_.end(); +} diff --git a/src/utils/struct_parser.h b/src/utils/struct_parser.h new file mode 100644 index 0000000..aa9ed64 --- /dev/null +++ b/src/utils/struct_parser.h @@ -0,0 +1,20 @@ +#ifndef PYLIBBPF_STRUCT_PARSER_H +#define PYLIBBPF_STRUCT_PARSER_H + +#include +#include +#include + +namespace py = pybind11; + +class StructParser { +private: + std::unordered_map struct_types_; + +public: + explicit StructParser(py::dict structs); + py::object parse(const std::string &struct_name, py::bytes data); + bool has_struct(const std::string &struct_name) const; +}; + +#endif