Skip to content

Instantly share code, notes, and snippets.

@alessandrod
Created November 30, 2020 04:19
Show Gist options
  • Save alessandrod/ed6f11ba41bcd8a19d8655e57a00350b to your computer and use it in GitHub Desktop.
Save alessandrod/ed6f11ba41bcd8a19d8655e57a00350b to your computer and use it in GitHub Desktop.
#ifndef _BPF_H_
#define _BPF_H_
#ifndef SEC
#define SEC(x) __attribute__((section(x), used))
#endif
#ifndef memset
# define memset(dest, chr, n) __builtin_memset((dest), (chr), (n))
#endif
#ifndef memcpy
# define memcpy(dest, src, n) __builtin_memcpy((dest), (src), (n))
#endif
#define BPF_MAP_TYPE_PERF_EVENT_ARRAY 4
static int (*bpf_perf_event_output)(void *ctx, void *map, unsigned long long flags, void *data, unsigned long long size) = (void *) 25;
struct bpf_map_def {
unsigned int type;
unsigned int key_size;
unsigned int value_size;
unsigned int max_entries;
unsigned int map_flags;
};
#include "bpf.h"
#include "lib.h"
struct bpf_map_def SEC("maps/logs") logs_map = {
.type = BPF_MAP_TYPE_PERF_EVENT_ARRAY,
.key_size = sizeof(unsigned int),
.value_size = sizeof(unsigned int),
.max_entries = 1024,
.map_flags = 0
};
void log_message(void *ctx, struct message *msg) {
bpf_perf_event_output(ctx, &logs_map, 0, msg, sizeof(struct message));
}
#ifndef _LIB_H_
#define _LIB_H_
#define MESSAGE_LEN 256
struct message {
char text[MESSAGE_LEN];
};
void log_message(void *ctx, struct message *msg);
#define _LIB_H_
CC := clang
BUILD_DIR := build
LIB_SOURCES := lib.c
SOURCES := program.c
LIB_BITCODE := $(LIB_SOURCES:%.c=$(BUILD_DIR)/%.bc)
PROGRAM_BITCODE := $(SOURCES:%.c=$(BUILD_DIR)/%.bc)
BPF_LIB := $(BUILD_DIR)/lib.a
BPF_PROGRAM := $(BUILD_DIR)/program.o
CFLAGS := -c --target=bpf -O3 -emit-llvm
all: build_dir $(BPF_PROGRAM)
$(BUILD_DIR)/%.bc: %.c
$(CC) $(CFLAGS) $(INCLUDES) -o $@ $<
$(BPF_LIB): $(LIB_BITCODE)
ar rc build/lib.a $(LIB_BITCODE)
$(BPF_PROGRAM): $(BPF_LIB) $(PROGRAM_BITCODE)
bpf-linker -O3 -o $(BPF_PROGRAM) $(BPF_LIB) $(PROGRAM_BITCODE)
build_dir:
mkdir -p $(BUILD_DIR)
clean:
rm -rf build/
.PHONY: build_dir all
#include "bpf.h"
#include "lib.h"
char _license[] SEC("license") = "GPL";
SEC("kprobe/__x64_sys_clone")
void sys_clone(void *ctx) {
struct message msg = {0};
memcpy(msg.text, "clone", 5);
log_message(ctx, &msg);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment