• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* eBPF mini library */
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <linux/unistd.h>
5 #include <unistd.h>
6 #include <string.h>
7 #include <linux/netlink.h>
8 #include <linux/bpf.h>
9 #include <errno.h>
10 #include "libbpf.h"
11 
ptr_to_u64(void * ptr)12 static __u64 ptr_to_u64(void *ptr)
13 {
14 	return (__u64) (unsigned long) ptr;
15 }
16 
bpf_create_map(enum bpf_map_type map_type,int key_size,int value_size,int max_entries)17 int bpf_create_map(enum bpf_map_type map_type, int key_size, int value_size,
18 		   int max_entries)
19 {
20 	union bpf_attr attr = {
21 		.map_type = map_type,
22 		.key_size = key_size,
23 		.value_size = value_size,
24 		.max_entries = max_entries
25 	};
26 
27 	return syscall(__NR_bpf, BPF_MAP_CREATE, &attr, sizeof(attr));
28 }
29 
bpf_update_elem(int fd,void * key,void * value)30 int bpf_update_elem(int fd, void *key, void *value)
31 {
32 	union bpf_attr attr = {
33 		.map_fd = fd,
34 		.key = ptr_to_u64(key),
35 		.value = ptr_to_u64(value),
36 	};
37 
38 	return syscall(__NR_bpf, BPF_MAP_UPDATE_ELEM, &attr, sizeof(attr));
39 }
40 
bpf_lookup_elem(int fd,void * key,void * value)41 int bpf_lookup_elem(int fd, void *key, void *value)
42 {
43 	union bpf_attr attr = {
44 		.map_fd = fd,
45 		.key = ptr_to_u64(key),
46 		.value = ptr_to_u64(value),
47 	};
48 
49 	return syscall(__NR_bpf, BPF_MAP_LOOKUP_ELEM, &attr, sizeof(attr));
50 }
51 
bpf_delete_elem(int fd,void * key)52 int bpf_delete_elem(int fd, void *key)
53 {
54 	union bpf_attr attr = {
55 		.map_fd = fd,
56 		.key = ptr_to_u64(key),
57 	};
58 
59 	return syscall(__NR_bpf, BPF_MAP_DELETE_ELEM, &attr, sizeof(attr));
60 }
61 
bpf_get_next_key(int fd,void * key,void * next_key)62 int bpf_get_next_key(int fd, void *key, void *next_key)
63 {
64 	union bpf_attr attr = {
65 		.map_fd = fd,
66 		.key = ptr_to_u64(key),
67 		.next_key = ptr_to_u64(next_key),
68 	};
69 
70 	return syscall(__NR_bpf, BPF_MAP_GET_NEXT_KEY, &attr, sizeof(attr));
71 }
72 
73 #define ROUND_UP(x, n) (((x) + (n) - 1u) & ~((n) - 1u))
74 
75 char bpf_log_buf[LOG_BUF_SIZE];
76 
bpf_prog_load(enum bpf_prog_type prog_type,const struct bpf_insn * insns,int prog_len,const char * license)77 int bpf_prog_load(enum bpf_prog_type prog_type,
78 		  const struct bpf_insn *insns, int prog_len,
79 		  const char *license)
80 {
81 	union bpf_attr attr = {
82 		.prog_type = prog_type,
83 		.insns = ptr_to_u64((void *) insns),
84 		.insn_cnt = prog_len / sizeof(struct bpf_insn),
85 		.license = ptr_to_u64((void *) license),
86 		.log_buf = ptr_to_u64(bpf_log_buf),
87 		.log_size = LOG_BUF_SIZE,
88 		.log_level = 1,
89 	};
90 
91 	bpf_log_buf[0] = 0;
92 
93 	return syscall(__NR_bpf, BPF_PROG_LOAD, &attr, sizeof(attr));
94 }
95