add ringbuf map type

This commit is contained in:
2025-10-01 23:51:18 +05:30
parent 8ceb1d1ac3
commit da9df2e6bf
3 changed files with 114 additions and 28 deletions

View File

@ -1,30 +1,51 @@
#include "vmlinux.h"
// SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_core_read.h>
#include <linux/types.h>
// Define the structure to be sent via ringbuf
struct event {
__u32 pid;
__u32 uid;
__u64 timestamp;
char comm[16]; // Process name
};
// Define the ringbuffer map
struct {
__uint(type, BPF_MAP_TYPE_RINGBUF);
__uint(max_entries, 1 << 24); // 16 MB
} rb SEC(".maps");
__uint(max_entries, 256 * 1024); // 256 KB
} events SEC(".maps");
//struct msg {
// u32 pid;
// char comm[16];
//};
// Tracepoint for execve system calls
SEC("tracepoint/syscalls/sys_enter_execve")
int trace_execve(void *ctx)
{
struct event *e;
__u64 pid_tgid;
__u64 uid_gid;
//SEC("tracepoint/syscalls/sys_enter_execve")
//int handle_execve(struct trace_event_raw_sys_enter *ctx)
//{
// struct msg *m;
// m = bpf_ringbuf_reserve(&rb, sizeof(*m), 0);
// if (!m)
// return 0;
//
// m->pid = bpf_get_current_pid_tgid() >> 32;
// bpf_get_current_comm(&m->comm, sizeof(m->comm));
// bpf_ringbuf_submit(m, 0);
// return 0;
//}
// Reserve space in the ringbuffer
e = bpf_ringbuf_reserve(&events, sizeof(*e), 0);
if (!e)
return 0;
//char LICENSE[] SEC("license") = "GPL";
// Fill the struct with data
pid_tgid = bpf_get_current_pid_tgid();
e->pid = pid_tgid >> 32;
uid_gid = bpf_get_current_uid_gid();
e->uid = uid_gid & 0xFFFFFFFF;
e->timestamp = bpf_ktime_get_ns();
bpf_get_current_comm(&e->comm, sizeof(e->comm));
// Submit the event to ringbuffer
bpf_ringbuf_submit(e, 0);
return 0;
}
char LICENSE[] SEC("license") = "GPL";

View File

@ -1,5 +1,5 @@
from pythonbpf import bpf, map, bpfglobal, section
from pythonbpf.maps import RingBuf
from pythonbpf import bpf, BPF, map, bpfglobal, section, compile, compile_to_ir
from pythonbpf.maps import RingBuf, HashMap
from ctypes import c_int32, c_void_p
@ -7,12 +7,19 @@ from ctypes import c_int32, c_void_p
@bpf
@map
def mymap() -> RingBuf:
return RingBuf(max_entries=(1 << 24))
return RingBuf(max_entries=(1024))
@bpf
@map
def mymap2() -> HashMap:
return HashMap(key=c_int32, value=c_int32, max_entries=1024)
@bpf
@section("tracepoint/syscalls/sys_enter_clone")
def testing(ctx: c_void_p) -> c_int32:
def random_section(ctx: c_void_p) -> c_int32:
print("Hello")
return c_int32(0)
@ -22,4 +29,7 @@ def LICENSE() -> str:
return "GPL"
compile_to_ir("ringbuf.py", "ringbuf.ll")
compile()
b = BPF()
b.load_and_attach()