1 // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) 2 // Copyright (C) 2020 Facebook 3 4 #define _GNU_SOURCE 5 #include <linux/err.h> 6 #include <bpf/libbpf.h> 7 8 #include "main.h" 9 10 static int do_pin(int argc, char **argv) 11 { 12 const char *objfile, *path; 13 struct bpf_program *prog; 14 struct bpf_object *obj; 15 struct bpf_link *link; 16 int err; 17 18 if (!REQ_ARGS(2)) 19 usage(); 20 21 objfile = GET_ARG(); 22 path = GET_ARG(); 23 24 obj = bpf_object__open(objfile); 25 if (IS_ERR(obj)) { 26 p_err("can't open objfile %s", objfile); 27 return -1; 28 } 29 30 err = bpf_object__load(obj); 31 if (err) { 32 p_err("can't load objfile %s", objfile); 33 goto close_obj; 34 } 35 36 prog = bpf_program__next(NULL, obj); 37 if (!prog) { 38 p_err("can't find bpf program in objfile %s", objfile); 39 goto close_obj; 40 } 41 42 link = bpf_program__attach_iter(prog, NULL); 43 if (IS_ERR(link)) { 44 err = PTR_ERR(link); 45 p_err("attach_iter failed for program %s", 46 bpf_program__name(prog)); 47 goto close_obj; 48 } 49 50 err = mount_bpffs_for_pin(path); 51 if (err) 52 goto close_link; 53 54 err = bpf_link__pin(link, path); 55 if (err) { 56 p_err("pin_iter failed for program %s to path %s", 57 bpf_program__name(prog), path); 58 goto close_link; 59 } 60 61 close_link: 62 bpf_link__destroy(link); 63 close_obj: 64 bpf_object__close(obj); 65 return err; 66 } 67 68 static int do_help(int argc, char **argv) 69 { 70 fprintf(stderr, 71 "Usage: %1$s %2$s pin OBJ PATH\n" 72 " %1$s %2$s help\n" 73 "", 74 bin_name, "iter"); 75 76 return 0; 77 } 78 79 static const struct cmd cmds[] = { 80 { "help", do_help }, 81 { "pin", do_pin }, 82 { 0 } 83 }; 84 85 int do_iter(int argc, char **argv) 86 { 87 return cmd_select(cmds, argc, argv, do_help); 88 } 89