Subject: [PATCH net-next 1/5] libbpf: add ability to guess program type based on section name

From: Roman Gushchin <[email-masked]>
Date: Thu, 30 Nov 2017 13:42:58 +0000

The bpf_prog_load() function will guess program type if it's not
specified explicitly. This functionality will be used to implement
loading of different programs without asking a user to specify
the program type. In first order it will be used by bpftool.

Signed-off-by: Roman Gushchin <[email-masked]>
Cc: Alexei Starovoitov <[email-masked]>
Cc: Daniel Borkmann <[email-masked]>
Cc: Jakub Kicinski <[email-masked]>
---
 tools/lib/bpf/libbpf.c | 47 +++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 47 insertions(+)

diff --git a/tools/lib/bpf/libbpf.c b/tools/lib/bpf/libbpf.c
index 5aa45f89da93..9f2410beaa18 100644
--- a/tools/lib/bpf/libbpf.c
+++ b/tools/lib/bpf/libbpf.c
@@ -1721,6 +1721,41 @@ BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
 
+static enum bpf_prog_type bpf_program__guess_type(struct bpf_program *prog)
+{
+	if (!prog->section_name)
+		goto err;
+
+	if (strncmp(prog->section_name, "socket", 6) == 0)
+		return BPF_PROG_TYPE_SOCKET_FILTER;
+	if (strncmp(prog->section_name, "kprobe/", 7) == 0)
+		return BPF_PROG_TYPE_KPROBE;
+	if (strncmp(prog->section_name, "kretprobe/", 10) == 0)
+		return BPF_PROG_TYPE_KPROBE;
+	if (strncmp(prog->section_name, "tracepoint/", 11) == 0)
+		return BPF_PROG_TYPE_TRACEPOINT;
+	if (strncmp(prog->section_name, "xdp", 3) == 0)
+		return BPF_PROG_TYPE_XDP;
+	if (strncmp(prog->section_name, "perf_event", 10) == 0)
+		return BPF_PROG_TYPE_PERF_EVENT;
+	if (strncmp(prog->section_name, "cgroup/skb", 10) == 0)
+		return BPF_PROG_TYPE_CGROUP_SKB;
+	if (strncmp(prog->section_name, "cgroup/sock", 11) == 0)
+		return BPF_PROG_TYPE_CGROUP_SOCK;
+	if (strncmp(prog->section_name, "cgroup/dev", 10) == 0)
+		return BPF_PROG_TYPE_CGROUP_DEVICE;
+	if (strncmp(prog->section_name, "sockops", 7) == 0)
+		return BPF_PROG_TYPE_SOCK_OPS;
+	if (strncmp(prog->section_name, "sk_skb", 6) == 0)
+		return BPF_PROG_TYPE_SK_SKB;
+
+err:
+	pr_warning("failed to guess program type based on section name %s\n",
+		   prog->section_name);
+
+	return BPF_PROG_TYPE_UNSPEC;
+}
+
 int bpf_map__fd(struct bpf_map *map)
 {
 	return map ? map->fd : -EINVAL;
@@ -1832,6 +1867,18 @@ int bpf_prog_load(const char *file, enum bpf_prog_type type,
 		return -ENOENT;
 	}
 
+	/*
+	 * If type is not specified, try to guess it based on
+	 * section name.
+	 */
+	if (type == BPF_PROG_TYPE_UNSPEC) {
+		type = bpf_program__guess_type(prog);
+		if (type == BPF_PROG_TYPE_UNSPEC) {
+			bpf_object__close(obj);
+			return -EINVAL;
+		}
+	}
+
 	bpf_program__set_type(prog, type);
 	err = bpf_object__load(obj);
 	if (err) {
-- 
2.14.3