GPUSuitabilityEst/code/kernel_module/ebpf.c
2026-07-20 12:30:11 +01:00

122 lines
2.7 KiB
C

#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_core_read.h>
#include "event.h"
char LICENSE[] SEC("license") = "GPL";
struct
{
__uint(type, BPF_MAP_TYPE_RINGBUF);
__uint(max_entries, 1 << 24);
} events SEC(".maps");
const char is_libcuda_needle[] = "libcuda";
static int is_libcuda(const char *p)
{
#pragma unroll
for (int i = 0; i < MAX_PATH - sizeof(is_libcuda_needle) - 1; i++)
{
int match = 1;
#pragma unroll
for (int j = 0; j < sizeof(is_libcuda_needle) - 1; j++)
{
if (p[i + j] != is_libcuda_needle[j])
{
match = 0;
break;
}
}
if (match)
return 1;
}
return 0;
}
const char is_libnv_needle[] = "libnv";
static int is_libnv(const char *p)
{
#pragma unroll
for (int i = 0; i < MAX_PATH - sizeof(is_libnv_needle) - 1; i++)
{
int match = 1;
#pragma unroll
for (int j = 0; j < sizeof(is_libnv_needle) - 1; j++)
{
if (p[i + j] != is_libnv_needle[j])
{
match = 0;
break;
}
}
if (match)
return 1;
}
return 0;
}
SEC("tracepoint/syscalls/sys_enter_openat")
int trace_openat(struct trace_event_raw_sys_enter *ctx)
{
const char *filename = (const char *)BPF_CORE_READ(ctx, args[1]);
char path[MAX_PATH];
if (bpf_probe_read_user_str(path, sizeof(path), filename) < 0)
return 0;
if (!is_libcuda(path) && !is_libnv(path))
return 0;
struct event *e = bpf_ringbuf_reserve(&events, sizeof(*e), 0);
if (!e)
return 0;
__builtin_memcpy(e->path, path, sizeof(path));
e->pid = bpf_get_current_pid_tgid() >> 32;
bpf_get_current_comm(&e->comm, sizeof(e->comm));
e->op = OPEN;
e->size = 0;
bpf_ringbuf_submit(e, 0);
return 0;
}
SEC("tracepoint/syscalls/sys_enter_mmap")
int trace_mmap(struct trace_event_raw_sys_enter *ctx)
{
struct event *e = bpf_ringbuf_reserve(&events, sizeof(*e), 0);
if (!e)
return 0;
e->pid = bpf_get_current_pid_tgid() >> 32;
bpf_get_current_comm(&e->comm, sizeof(e->comm));
e->op = MMAP;
e->size = BPF_CORE_READ(ctx, args[1]); // length
e->path[0] = 0;
bpf_ringbuf_submit(e, 0);
return 0;
}
SEC("tracepoint/syscalls/sys_enter_munmap")
int trace_munmap(struct trace_event_raw_sys_enter *ctx)
{
struct event *e = bpf_ringbuf_reserve(&events, sizeof(*e), 0);
if (!e)
return 0;
e->pid = bpf_get_current_pid_tgid() >> 32;
bpf_get_current_comm(&e->comm, sizeof(e->comm));
e->op = MUNMAP;
e->size = BPF_CORE_READ(ctx, args[1]); // length
e->path[0] = 0;
bpf_ringbuf_submit(e, 0);
return 0;
}