libbpf Development Guide: Automatically load the kernel modules required for BPF programs

Table of contents

Function prototypes and explanations

Code demo

makefile

cmake

expected output


Function prototypes and explanations

bool bpf_program__autoload(const struct bpf_program *prog);

Parameter Description:

  • prog: Pointer to struct bpf_program, indicating the BPF program to automatically load the kernel module.

return value:

  • Returns true on success and false on failure.

Code demo

#include <bpf/bpf_helpers.h>
#include <linux/bpf.h>

SEC("kprobe/__x64_sys_getpid")
int bpf_prog1(struct pt_regs *ctx) {
    return 0;
}

char _license[] SEC("license") = "GPL";
#include <stdio.h>
#include <stdlib.h>
#include <bpf/libbpf.h>

int main() {
    struct bpf_object *obj;
    struct bpf_program *prog;
    const char *section_name;

    obj = bpf_object__open_file("example.o", NULL);
    if (!obj) {
        printf("Failed to open BPF object file\n");
        return 1;
    }

    prog = bpf_program__next(NULL, obj);
    if (!prog) {
        printf("Failed to find BPF program\n");
        bpf_object__close(obj);
        return 1;
    }

    section_name = bpf_program__section_name(prog);
    printf("BPF program section name: %s\n", section_name);

    bpf_object__close(obj);
    return 0;
}

makefile

CC=gcc
CFLAGS=-I/usr/include/bpf -I./include
LDFLAGS=-lbpf

all: test

test: test.c
	$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)

clean:
	rm -f test

cmake

cmake_minimum_required(VERSION 2.8)
project(test)

set(CMAKE_C_FLAGS "-I/usr/include/bpf -I./include")

add_executable(test test.c)
target_link_libraries(test bpf)

expected output

make

./demo

BPF program loaded successfully

Guess you like

Origin blog.csdn.net/qq_32378713/article/details/131570190