1 /* SPDX-License-Identifier: GPL-2.0
2 * Copyright (c) 2018 Jesper Dangaard Brouer, Red Hat Inc.
4 static const char *__doc__ =
5 "Libbpf test program for loading BPF ELF object files";
11 #include <bpf/libbpf.h>
14 static const struct option long_options[] = {
15 {"help", no_argument, NULL, 'h' },
16 {"debug", no_argument, NULL, 'D' },
17 {"quiet", no_argument, NULL, 'q' },
21 static void usage(char *argv[])
25 printf("\nDOCUMENTATION:\n%s\n\n", __doc__);
26 printf(" Usage: %s (options-see-below) BPF_FILE\n", argv[0]);
27 printf(" Listing options:\n");
28 for (i = 0; long_options[i].name != 0; i++) {
29 printf(" --%-12s", long_options[i].name);
30 printf(" short-option: -%c",
37 static bool debug = 0;
38 static int libbpf_debug_print(enum libbpf_print_level level,
39 const char *fmt, va_list args)
41 if (level == LIBBPF_DEBUG && !debug)
44 fprintf(stderr, "[%d] ", level);
45 return vfprintf(stderr, fmt, args);
48 #define EXIT_FAIL_LIBBPF EXIT_FAILURE
49 #define EXIT_FAIL_OPTION 2
51 int test_walk_progs(struct bpf_object *obj, bool verbose)
53 struct bpf_program *prog;
56 bpf_object__for_each_program(prog, obj) {
59 printf("Prog (count:%d) section_name: %s\n", cnt,
60 bpf_program__title(prog, false));
65 int test_walk_maps(struct bpf_object *obj, bool verbose)
70 bpf_object__for_each_map(map, obj) {
73 printf("Map (count:%d) name: %s\n", cnt,
79 int test_open_file(char *filename, bool verbose)
81 struct bpf_object *bpfobj = NULL;
85 printf("Open BPF ELF-file with libbpf: %s\n", filename);
87 /* Load BPF ELF object file and check for errors */
88 bpfobj = bpf_object__open(filename);
89 err = libbpf_get_error(bpfobj);
92 libbpf_strerror(err, err_buf, sizeof(err_buf));
94 printf("Unable to load eBPF objects in file '%s': %s\n",
96 return EXIT_FAIL_LIBBPF;
98 test_walk_progs(bpfobj, verbose);
99 test_walk_maps(bpfobj, verbose);
102 printf("Close BPF ELF-file with libbpf: %s\n",
103 bpf_object__name(bpfobj));
104 bpf_object__close(bpfobj);
109 int main(int argc, char **argv)
111 char filename[1024] = { 0 };
116 libbpf_set_print(libbpf_debug_print);
118 /* Parse commands line args */
119 while ((opt = getopt_long(argc, argv, "hDq",
120 long_options, &longindex)) != -1) {
125 case 'q': /* Use in scripting mode */
131 return EXIT_FAIL_OPTION;
134 if (optind >= argc) {
136 printf("ERROR: Expected BPF_FILE argument after options\n");
137 return EXIT_FAIL_OPTION;
139 snprintf(filename, sizeof(filename), "%s", argv[optind]);
141 return test_open_file(filename, verbose);