Skip to content

Instantly share code, notes, and snippets.

@teknoraver
Last active December 17, 2021 16:17
Show Gist options
  • Save teknoraver/2855e0f8770d1363b57d683fa32bccc3 to your computer and use it in GitHub Desktop.
Save teknoraver/2855e0f8770d1363b57d683fa32bccc3 to your computer and use it in GitHub Desktop.
eBPF CO-RE example
/core
*.o
*.lskel.h
vmlinux.h
*.pem
*.x509
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
struct {
__uint(type, BPF_MAP_TYPE_ARRAY);
__type(key, u32);
__type(value, u64);
__uint(max_entries, 256);
} array1 SEC(".maps");
struct {
__uint(type, BPF_MAP_TYPE_ARRAY);
__type(key, u32);
__type(value, u64);
__uint(max_entries, 256);
} array2 SEC(".maps");
int randmap(u64 data)
{
struct bpf_map *map = (struct bpf_map *)&array1;
int key = bpf_get_prandom_u32() & 0xff;
int *val;
if (bpf_get_prandom_u32() & 1)
map = (struct bpf_map *)&array2;
val = bpf_map_lookup_elem(map, &key);
if (val)
*val = data;
return 0;
}
SEC("tp_btf/xdp_devmap_xmit")
int BPF_PROG(tp_xdp_devmap_xmit_multi, const struct net_device *from_dev,
const struct net_device *to_dev, int sent, int drops, int err)
{
randmap(from_dev->ifindex + to_dev->ifindex);
return 0;
}
SEC("fentry/eth_type_trans")
int BPF_PROG(fentry_eth_type_trans, struct sk_buff *skb,
struct net_device *dev, unsigned short protocol)
{
randmap(dev->ifindex + skb->len);
return 0;
}
SEC("fexit/eth_type_trans")
int BPF_PROG(fexit_eth_type_trans, struct sk_buff *skb,
struct net_device *dev, unsigned short protocol)
{
randmap(dev->ifindex + skb->len);
return 0;
}
char LICENSE[] SEC("license") = "GPL";
#include <argp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <time.h>
#include <bpf/libbpf.h>
#include <bpf/bpf.h>
#include "core.lskel.h"
int main(int argc, char **argv)
{
struct core_bpf *obj;
int err;
obj = core_bpf__open_and_load();
if (!obj) {
fprintf(stderr, "failed to open and/or load BPF object\n");
return 1;
}
err = core_bpf__attach(obj);
if (err) {
fprintf(stderr, "failed to attach BPF programs\n");
return 1;
}
return 0;
}
LDLIBS := -lbpf
all:: core
core.o: core.lskel.h
%.bpf.o: %.bpf.c vmlinux.h
clang -g -O2 -target bpf -c $< -o $@
%.lskel.h: %.bpf.o
bpftool gen skeleton -L -s -H sha256 -k signing_key.pem -c signing_key.x509 $< > $@
vmlinux.h: /sys/kernel/btf/vmlinux
bpftool btf dump file /sys/kernel/btf/vmlinux format c >$@
clean::
$(RM) core *.o *.lskel.h vmlinux.h
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment