1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2022 Benjamin Tissoires
4 * This is a pure HID-BPF example, and should be considered as such:
5 * on the Etekcity Scroll 6E, the X and Y axes will be swapped and
6 * inverted. On any other device... Not sure what this will do.
8 * This C main file is generic though. To adapt the code and test, users
9 * must amend only the .bpf.c file, which this program will load any
10 * eBPF program it finds.
22 #include <sys/resource.h>
25 #include <linux/bpf.h>
26 #include <linux/errno.h>
29 #include <bpf/libbpf.h>
31 #include "hid_mouse.skel.h"
32 #include "hid_bpf_attach.h"
34 static bool running = true;
36 static void int_exit(int sig)
42 static void usage(const char *prog)
45 "%s: %s /sys/bus/hid/devices/0BUS:0VID:0PID:00ID\n\n",
48 "This program will upload and attach a HID-BPF program to the given device.\n"
49 "On the Etekcity Scroll 6E, the X and Y axis will be inverted, but on any other\n"
50 "device, chances are high that the device will not be working anymore\n\n"
51 "consider this as a demo and adapt the eBPF program to your needs\n"
52 "Hit Ctrl-C to unbind the program and reset the device\n");
55 static int get_hid_id(const char *path)
57 const char *str_id, *dir;
61 memset(uevent, 0, sizeof(uevent));
62 snprintf(uevent, sizeof(uevent) - 1, "%s/uevent", path);
64 fd = open(uevent, O_RDONLY | O_NONBLOCK);
70 dir = basename((char *)path);
72 str_id = dir + sizeof("0003:0001:0A37.");
73 return (int)strtol(str_id, NULL, 16);
76 int main(int argc, char **argv)
78 struct hid_mouse *skel;
79 struct bpf_program *prog;
81 const char *optstr = "";
82 const char *sysfs_path;
83 int opt, hid_id, attach_fd;
84 struct attach_prog_args args = {
87 DECLARE_LIBBPF_OPTS(bpf_test_run_opts, tattr,
89 .ctx_size_in = sizeof(args),
92 while ((opt = getopt(argc, argv, optstr)) != -1) {
95 usage(basename(argv[0]));
100 if (optind == argc) {
101 usage(basename(argv[0]));
105 sysfs_path = argv[optind];
111 skel = hid_mouse__open_and_load();
113 fprintf(stderr, "%s %s:%d", __func__, __FILE__, __LINE__);
117 hid_id = get_hid_id(sysfs_path);
120 fprintf(stderr, "can not open HID device: %m\n");
125 attach_fd = bpf_program__fd(skel->progs.attach_prog);
127 fprintf(stderr, "can't locate attach prog: %m\n");
131 bpf_object__for_each_program(prog, *skel->skeleton->obj) {
132 /* ignore syscalls */
133 if (bpf_program__get_type(prog) != BPF_PROG_TYPE_TRACING)
137 args.prog_fd = bpf_program__fd(prog);
138 err = bpf_prog_test_run_opts(attach_fd, &tattr);
140 fprintf(stderr, "can't attach prog to hid device %d: %m (err: %d)\n",
146 signal(SIGINT, int_exit);
147 signal(SIGTERM, int_exit);
152 hid_mouse__destroy(skel);