blob: e53f1f6f0867de31f513a0671e53d7442001d13b [file] [log] [blame]
Greg Kroah-Hartmanb2441312017-11-01 15:07:57 +01001// SPDX-License-Identifier: GPL-2.0
David Ahern554ae6e2016-12-01 08:48:08 -08002/* eBPF example program:
3 *
4 * - Loads eBPF program
5 *
6 * The eBPF program loads a filter from file and attaches the
7 * program to a cgroup using BPF_PROG_ATTACH
8 */
9
10#define _GNU_SOURCE
11
12#include <stdio.h>
13#include <stdlib.h>
14#include <stddef.h>
15#include <string.h>
16#include <unistd.h>
17#include <assert.h>
18#include <errno.h>
19#include <fcntl.h>
20#include <net/if.h>
21#include <linux/bpf.h>
22
23#include "libbpf.h"
24#include "bpf_load.h"
25
26static int usage(const char *argv0)
27{
28 printf("Usage: %s cg-path filter-path [filter-id]\n", argv0);
29 return EXIT_FAILURE;
30}
31
32int main(int argc, char **argv)
33{
34 int cg_fd, ret, filter_id = 0;
35
36 if (argc < 3)
37 return usage(argv[0]);
38
39 cg_fd = open(argv[1], O_DIRECTORY | O_RDONLY);
40 if (cg_fd < 0) {
41 printf("Failed to open cgroup path: '%s'\n", strerror(errno));
42 return EXIT_FAILURE;
43 }
44
45 if (load_bpf_file(argv[2]))
46 return EXIT_FAILURE;
47
48 printf("Output from kernel verifier:\n%s\n-------\n", bpf_log_buf);
49
50 if (argc > 3)
51 filter_id = atoi(argv[3]);
52
53 if (filter_id > prog_cnt) {
54 printf("Invalid program id; program not found in file\n");
55 return EXIT_FAILURE;
56 }
57
58 ret = bpf_prog_attach(prog_fd[filter_id], cg_fd,
Alexei Starovoitov7f677632017-02-10 20:28:24 -080059 BPF_CGROUP_INET_SOCK_CREATE, 0);
David Ahern554ae6e2016-12-01 08:48:08 -080060 if (ret < 0) {
61 printf("Failed to attach prog to cgroup: '%s'\n",
62 strerror(errno));
63 return EXIT_FAILURE;
64 }
65
66 return EXIT_SUCCESS;
67}