1 /*
2 * Common eBPF ELF object loading operations.
3 *
4 * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
5 * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
6 * Copyright (C) 2015 Huawei Inc.
7 * Copyright (C) 2017 Nicira, Inc.
8 *
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation;
12 * version 2.1 of the License (not later!)
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this program; if not, see <http://www.gnu.org/licenses>
21 */
22
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <stdarg.h>
26 #include <libgen.h>
27 #include <inttypes.h>
28 #include <string.h>
29 #include <unistd.h>
30 #include <fcntl.h>
31 #include <errno.h>
32 #include <asm/unistd.h>
33 #include <linux/err.h>
34 #include <linux/kernel.h>
35 #include <linux/bpf.h>
36 #include <linux/list.h>
37 #include <linux/limits.h>
38 #include <sys/stat.h>
39 #include <sys/types.h>
40 #include <sys/vfs.h>
41 #include <libelf.h>
42 #include <gelf.h>
43
44 #include "libbpf.h"
45 #include "bpf.h"
46
47 #ifndef EM_BPF
48 #define EM_BPF 247
49 #endif
50
51 #ifndef BPF_FS_MAGIC
52 #define BPF_FS_MAGIC 0xcafe4a11
53 #endif
54
55 #define __printf(a, b) __attribute__((format(printf, a, b)))
56
57 __printf(1, 2)
__base_pr(const char * format,...)58 static int __base_pr(const char *format, ...)
59 {
60 va_list args;
61 int err;
62
63 va_start(args, format);
64 err = vfprintf(stderr, format, args);
65 va_end(args);
66 return err;
67 }
68
69 static __printf(1, 2) libbpf_print_fn_t __pr_warning = __base_pr;
70 static __printf(1, 2) libbpf_print_fn_t __pr_info = __base_pr;
71 static __printf(1, 2) libbpf_print_fn_t __pr_debug;
72
73 #define __pr(func, fmt, ...) \
74 do { \
75 if ((func)) \
76 (func)("libbpf: " fmt, ##__VA_ARGS__); \
77 } while (0)
78
79 #define pr_warning(fmt, ...) __pr(__pr_warning, fmt, ##__VA_ARGS__)
80 #define pr_info(fmt, ...) __pr(__pr_info, fmt, ##__VA_ARGS__)
81 #define pr_debug(fmt, ...) __pr(__pr_debug, fmt, ##__VA_ARGS__)
82
libbpf_set_print(libbpf_print_fn_t warn,libbpf_print_fn_t info,libbpf_print_fn_t debug)83 void libbpf_set_print(libbpf_print_fn_t warn,
84 libbpf_print_fn_t info,
85 libbpf_print_fn_t debug)
86 {
87 __pr_warning = warn;
88 __pr_info = info;
89 __pr_debug = debug;
90 }
91
92 #define STRERR_BUFSIZE 128
93
94 #define ERRNO_OFFSET(e) ((e) - __LIBBPF_ERRNO__START)
95 #define ERRCODE_OFFSET(c) ERRNO_OFFSET(LIBBPF_ERRNO__##c)
96 #define NR_ERRNO (__LIBBPF_ERRNO__END - __LIBBPF_ERRNO__START)
97
98 static const char *libbpf_strerror_table[NR_ERRNO] = {
99 [ERRCODE_OFFSET(LIBELF)] = "Something wrong in libelf",
100 [ERRCODE_OFFSET(FORMAT)] = "BPF object format invalid",
101 [ERRCODE_OFFSET(KVERSION)] = "'version' section incorrect or lost",
102 [ERRCODE_OFFSET(ENDIAN)] = "Endian mismatch",
103 [ERRCODE_OFFSET(INTERNAL)] = "Internal error in libbpf",
104 [ERRCODE_OFFSET(RELOC)] = "Relocation failed",
105 [ERRCODE_OFFSET(VERIFY)] = "Kernel verifier blocks program loading",
106 [ERRCODE_OFFSET(PROG2BIG)] = "Program too big",
107 [ERRCODE_OFFSET(KVER)] = "Incorrect kernel version",
108 [ERRCODE_OFFSET(PROGTYPE)] = "Kernel doesn't support this program type",
109 };
110
libbpf_strerror(int err,char * buf,size_t size)111 int libbpf_strerror(int err, char *buf, size_t size)
112 {
113 if (!buf || !size)
114 return -1;
115
116 err = err > 0 ? err : -err;
117
118 if (err < __LIBBPF_ERRNO__START) {
119 int ret;
120
121 ret = strerror_r(err, buf, size);
122 buf[size - 1] = '\0';
123 return ret;
124 }
125
126 if (err < __LIBBPF_ERRNO__END) {
127 const char *msg;
128
129 msg = libbpf_strerror_table[ERRNO_OFFSET(err)];
130 snprintf(buf, size, "%s", msg);
131 buf[size - 1] = '\0';
132 return 0;
133 }
134
135 snprintf(buf, size, "Unknown libbpf error %d", err);
136 buf[size - 1] = '\0';
137 return -1;
138 }
139
140 #define CHECK_ERR(action, err, out) do { \
141 err = action; \
142 if (err) \
143 goto out; \
144 } while(0)
145
146
147 /* Copied from tools/perf/util/util.h */
148 #ifndef zfree
149 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
150 #endif
151
152 #ifndef zclose
153 # define zclose(fd) ({ \
154 int ___err = 0; \
155 if ((fd) >= 0) \
156 ___err = close((fd)); \
157 fd = -1; \
158 ___err; })
159 #endif
160
161 #ifdef HAVE_LIBELF_MMAP_SUPPORT
162 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
163 #else
164 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
165 #endif
166
167 /*
168 * bpf_prog should be a better name but it has been used in
169 * linux/filter.h.
170 */
171 struct bpf_program {
172 /* Index in elf obj file, for relocation use. */
173 int idx;
174 char *section_name;
175 struct bpf_insn *insns;
176 size_t insns_cnt;
177 enum bpf_prog_type type;
178
179 struct {
180 int insn_idx;
181 int map_idx;
182 } *reloc_desc;
183 int nr_reloc;
184
185 struct {
186 int nr;
187 int *fds;
188 } instances;
189 bpf_program_prep_t preprocessor;
190
191 struct bpf_object *obj;
192 void *priv;
193 bpf_program_clear_priv_t clear_priv;
194 };
195
196 struct bpf_map {
197 int fd;
198 char *name;
199 size_t offset;
200 struct bpf_map_def def;
201 void *priv;
202 bpf_map_clear_priv_t clear_priv;
203 };
204
205 static LIST_HEAD(bpf_objects_list);
206
207 struct bpf_object {
208 char license[64];
209 u32 kern_version;
210
211 struct bpf_program *programs;
212 size_t nr_programs;
213 struct bpf_map *maps;
214 size_t nr_maps;
215
216 bool loaded;
217
218 /*
219 * Information when doing elf related work. Only valid if fd
220 * is valid.
221 */
222 struct {
223 int fd;
224 void *obj_buf;
225 size_t obj_buf_sz;
226 Elf *elf;
227 GElf_Ehdr ehdr;
228 Elf_Data *symbols;
229 size_t strtabidx;
230 struct {
231 GElf_Shdr shdr;
232 Elf_Data *data;
233 } *reloc;
234 int nr_reloc;
235 int maps_shndx;
236 } efile;
237 /*
238 * All loaded bpf_object is linked in a list, which is
239 * hidden to caller. bpf_objects__<func> handlers deal with
240 * all objects.
241 */
242 struct list_head list;
243
244 void *priv;
245 bpf_object_clear_priv_t clear_priv;
246
247 char path[];
248 };
249 #define obj_elf_valid(o) ((o)->efile.elf)
250
bpf_program__unload(struct bpf_program * prog)251 static void bpf_program__unload(struct bpf_program *prog)
252 {
253 int i;
254
255 if (!prog)
256 return;
257
258 /*
259 * If the object is opened but the program was never loaded,
260 * it is possible that prog->instances.nr == -1.
261 */
262 if (prog->instances.nr > 0) {
263 for (i = 0; i < prog->instances.nr; i++)
264 zclose(prog->instances.fds[i]);
265 } else if (prog->instances.nr != -1) {
266 pr_warning("Internal error: instances.nr is %d\n",
267 prog->instances.nr);
268 }
269
270 prog->instances.nr = -1;
271 zfree(&prog->instances.fds);
272 }
273
bpf_program__exit(struct bpf_program * prog)274 static void bpf_program__exit(struct bpf_program *prog)
275 {
276 if (!prog)
277 return;
278
279 if (prog->clear_priv)
280 prog->clear_priv(prog, prog->priv);
281
282 prog->priv = NULL;
283 prog->clear_priv = NULL;
284
285 bpf_program__unload(prog);
286 zfree(&prog->section_name);
287 zfree(&prog->insns);
288 zfree(&prog->reloc_desc);
289
290 prog->nr_reloc = 0;
291 prog->insns_cnt = 0;
292 prog->idx = -1;
293 }
294
295 static int
bpf_program__init(void * data,size_t size,char * name,int idx,struct bpf_program * prog)296 bpf_program__init(void *data, size_t size, char *name, int idx,
297 struct bpf_program *prog)
298 {
299 if (size < sizeof(struct bpf_insn)) {
300 pr_warning("corrupted section '%s'\n", name);
301 return -EINVAL;
302 }
303
304 bzero(prog, sizeof(*prog));
305
306 prog->section_name = strdup(name);
307 if (!prog->section_name) {
308 pr_warning("failed to alloc name for prog %s\n",
309 name);
310 goto errout;
311 }
312
313 prog->insns = malloc(size);
314 if (!prog->insns) {
315 pr_warning("failed to alloc insns for %s\n", name);
316 goto errout;
317 }
318 prog->insns_cnt = size / sizeof(struct bpf_insn);
319 memcpy(prog->insns, data,
320 prog->insns_cnt * sizeof(struct bpf_insn));
321 prog->idx = idx;
322 prog->instances.fds = NULL;
323 prog->instances.nr = -1;
324 prog->type = BPF_PROG_TYPE_KPROBE;
325
326 return 0;
327 errout:
328 bpf_program__exit(prog);
329 return -ENOMEM;
330 }
331
332 static int
bpf_object__add_program(struct bpf_object * obj,void * data,size_t size,char * name,int idx)333 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
334 char *name, int idx)
335 {
336 struct bpf_program prog, *progs;
337 int nr_progs, err;
338
339 err = bpf_program__init(data, size, name, idx, &prog);
340 if (err)
341 return err;
342
343 progs = obj->programs;
344 nr_progs = obj->nr_programs;
345
346 progs = realloc(progs, sizeof(progs[0]) * (nr_progs + 1));
347 if (!progs) {
348 /*
349 * In this case the original obj->programs
350 * is still valid, so don't need special treat for
351 * bpf_close_object().
352 */
353 pr_warning("failed to alloc a new program '%s'\n",
354 name);
355 bpf_program__exit(&prog);
356 return -ENOMEM;
357 }
358
359 pr_debug("found program %s\n", prog.section_name);
360 obj->programs = progs;
361 obj->nr_programs = nr_progs + 1;
362 prog.obj = obj;
363 progs[nr_progs] = prog;
364 return 0;
365 }
366
bpf_object__new(const char * path,void * obj_buf,size_t obj_buf_sz)367 static struct bpf_object *bpf_object__new(const char *path,
368 void *obj_buf,
369 size_t obj_buf_sz)
370 {
371 struct bpf_object *obj;
372
373 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
374 if (!obj) {
375 pr_warning("alloc memory failed for %s\n", path);
376 return ERR_PTR(-ENOMEM);
377 }
378
379 strcpy(obj->path, path);
380 obj->efile.fd = -1;
381
382 /*
383 * Caller of this function should also calls
384 * bpf_object__elf_finish() after data collection to return
385 * obj_buf to user. If not, we should duplicate the buffer to
386 * avoid user freeing them before elf finish.
387 */
388 obj->efile.obj_buf = obj_buf;
389 obj->efile.obj_buf_sz = obj_buf_sz;
390 obj->efile.maps_shndx = -1;
391
392 obj->loaded = false;
393
394 INIT_LIST_HEAD(&obj->list);
395 list_add(&obj->list, &bpf_objects_list);
396 return obj;
397 }
398
bpf_object__elf_finish(struct bpf_object * obj)399 static void bpf_object__elf_finish(struct bpf_object *obj)
400 {
401 if (!obj_elf_valid(obj))
402 return;
403
404 if (obj->efile.elf) {
405 elf_end(obj->efile.elf);
406 obj->efile.elf = NULL;
407 }
408 obj->efile.symbols = NULL;
409
410 zfree(&obj->efile.reloc);
411 obj->efile.nr_reloc = 0;
412 zclose(obj->efile.fd);
413 obj->efile.obj_buf = NULL;
414 obj->efile.obj_buf_sz = 0;
415 }
416
bpf_object__elf_init(struct bpf_object * obj)417 static int bpf_object__elf_init(struct bpf_object *obj)
418 {
419 int err = 0;
420 GElf_Ehdr *ep;
421
422 if (obj_elf_valid(obj)) {
423 pr_warning("elf init: internal error\n");
424 return -LIBBPF_ERRNO__LIBELF;
425 }
426
427 if (obj->efile.obj_buf_sz > 0) {
428 /*
429 * obj_buf should have been validated by
430 * bpf_object__open_buffer().
431 */
432 obj->efile.elf = elf_memory(obj->efile.obj_buf,
433 obj->efile.obj_buf_sz);
434 } else {
435 obj->efile.fd = open(obj->path, O_RDONLY);
436 if (obj->efile.fd < 0) {
437 pr_warning("failed to open %s: %s\n", obj->path,
438 strerror(errno));
439 return -errno;
440 }
441
442 obj->efile.elf = elf_begin(obj->efile.fd,
443 LIBBPF_ELF_C_READ_MMAP,
444 NULL);
445 }
446
447 if (!obj->efile.elf) {
448 pr_warning("failed to open %s as ELF file\n",
449 obj->path);
450 err = -LIBBPF_ERRNO__LIBELF;
451 goto errout;
452 }
453
454 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
455 pr_warning("failed to get EHDR from %s\n",
456 obj->path);
457 err = -LIBBPF_ERRNO__FORMAT;
458 goto errout;
459 }
460 ep = &obj->efile.ehdr;
461
462 /* Old LLVM set e_machine to EM_NONE */
463 if ((ep->e_type != ET_REL) || (ep->e_machine && (ep->e_machine != EM_BPF))) {
464 pr_warning("%s is not an eBPF object file\n",
465 obj->path);
466 err = -LIBBPF_ERRNO__FORMAT;
467 goto errout;
468 }
469
470 return 0;
471 errout:
472 bpf_object__elf_finish(obj);
473 return err;
474 }
475
476 static int
bpf_object__check_endianness(struct bpf_object * obj)477 bpf_object__check_endianness(struct bpf_object *obj)
478 {
479 static unsigned int const endian = 1;
480
481 switch (obj->efile.ehdr.e_ident[EI_DATA]) {
482 case ELFDATA2LSB:
483 /* We are big endian, BPF obj is little endian. */
484 if (*(unsigned char const *)&endian != 1)
485 goto mismatch;
486 break;
487
488 case ELFDATA2MSB:
489 /* We are little endian, BPF obj is big endian. */
490 if (*(unsigned char const *)&endian != 0)
491 goto mismatch;
492 break;
493 default:
494 return -LIBBPF_ERRNO__ENDIAN;
495 }
496
497 return 0;
498
499 mismatch:
500 pr_warning("Error: endianness mismatch.\n");
501 return -LIBBPF_ERRNO__ENDIAN;
502 }
503
504 static int
bpf_object__init_license(struct bpf_object * obj,void * data,size_t size)505 bpf_object__init_license(struct bpf_object *obj,
506 void *data, size_t size)
507 {
508 memcpy(obj->license, data,
509 min(size, sizeof(obj->license) - 1));
510 pr_debug("license of %s is %s\n", obj->path, obj->license);
511 return 0;
512 }
513
514 static int
bpf_object__init_kversion(struct bpf_object * obj,void * data,size_t size)515 bpf_object__init_kversion(struct bpf_object *obj,
516 void *data, size_t size)
517 {
518 u32 kver;
519
520 if (size != sizeof(kver)) {
521 pr_warning("invalid kver section in %s\n", obj->path);
522 return -LIBBPF_ERRNO__FORMAT;
523 }
524 memcpy(&kver, data, sizeof(kver));
525 obj->kern_version = kver;
526 pr_debug("kernel version of %s is %x\n", obj->path,
527 obj->kern_version);
528 return 0;
529 }
530
531 static int
bpf_object__validate_maps(struct bpf_object * obj)532 bpf_object__validate_maps(struct bpf_object *obj)
533 {
534 int i;
535
536 /*
537 * If there's only 1 map, the only error case should have been
538 * catched in bpf_object__init_maps().
539 */
540 if (!obj->maps || !obj->nr_maps || (obj->nr_maps == 1))
541 return 0;
542
543 for (i = 1; i < obj->nr_maps; i++) {
544 const struct bpf_map *a = &obj->maps[i - 1];
545 const struct bpf_map *b = &obj->maps[i];
546
547 if (b->offset - a->offset < sizeof(struct bpf_map_def)) {
548 pr_warning("corrupted map section in %s: map \"%s\" too small\n",
549 obj->path, a->name);
550 return -EINVAL;
551 }
552 }
553 return 0;
554 }
555
compare_bpf_map(const void * _a,const void * _b)556 static int compare_bpf_map(const void *_a, const void *_b)
557 {
558 const struct bpf_map *a = _a;
559 const struct bpf_map *b = _b;
560
561 return a->offset - b->offset;
562 }
563
564 static int
bpf_object__init_maps(struct bpf_object * obj)565 bpf_object__init_maps(struct bpf_object *obj)
566 {
567 int i, map_idx, nr_maps = 0;
568 Elf_Scn *scn;
569 Elf_Data *data;
570 Elf_Data *symbols = obj->efile.symbols;
571
572 if (obj->efile.maps_shndx < 0)
573 return -EINVAL;
574 if (!symbols)
575 return -EINVAL;
576
577 scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
578 if (scn)
579 data = elf_getdata(scn, NULL);
580 if (!scn || !data) {
581 pr_warning("failed to get Elf_Data from map section %d\n",
582 obj->efile.maps_shndx);
583 return -EINVAL;
584 }
585
586 /*
587 * Count number of maps. Each map has a name.
588 * Array of maps is not supported: only the first element is
589 * considered.
590 *
591 * TODO: Detect array of map and report error.
592 */
593 for (i = 0; i < symbols->d_size / sizeof(GElf_Sym); i++) {
594 GElf_Sym sym;
595
596 if (!gelf_getsym(symbols, i, &sym))
597 continue;
598 if (sym.st_shndx != obj->efile.maps_shndx)
599 continue;
600 nr_maps++;
601 }
602
603 /* Alloc obj->maps and fill nr_maps. */
604 pr_debug("maps in %s: %d maps in %zd bytes\n", obj->path,
605 nr_maps, data->d_size);
606
607 if (!nr_maps)
608 return 0;
609
610 obj->maps = calloc(nr_maps, sizeof(obj->maps[0]));
611 if (!obj->maps) {
612 pr_warning("alloc maps for object failed\n");
613 return -ENOMEM;
614 }
615 obj->nr_maps = nr_maps;
616
617 /*
618 * fill all fd with -1 so won't close incorrect
619 * fd (fd=0 is stdin) when failure (zclose won't close
620 * negative fd)).
621 */
622 for (i = 0; i < nr_maps; i++)
623 obj->maps[i].fd = -1;
624
625 /*
626 * Fill obj->maps using data in "maps" section.
627 */
628 for (i = 0, map_idx = 0; i < symbols->d_size / sizeof(GElf_Sym); i++) {
629 GElf_Sym sym;
630 const char *map_name;
631 struct bpf_map_def *def;
632
633 if (!gelf_getsym(symbols, i, &sym))
634 continue;
635 if (sym.st_shndx != obj->efile.maps_shndx)
636 continue;
637
638 map_name = elf_strptr(obj->efile.elf,
639 obj->efile.strtabidx,
640 sym.st_name);
641 obj->maps[map_idx].offset = sym.st_value;
642 if (sym.st_value + sizeof(struct bpf_map_def) > data->d_size) {
643 pr_warning("corrupted maps section in %s: last map \"%s\" too small\n",
644 obj->path, map_name);
645 return -EINVAL;
646 }
647
648 obj->maps[map_idx].name = strdup(map_name);
649 if (!obj->maps[map_idx].name) {
650 pr_warning("failed to alloc map name\n");
651 return -ENOMEM;
652 }
653 pr_debug("map %d is \"%s\"\n", map_idx,
654 obj->maps[map_idx].name);
655 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
656 obj->maps[map_idx].def = *def;
657 map_idx++;
658 }
659
660 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]), compare_bpf_map);
661 return bpf_object__validate_maps(obj);
662 }
663
section_have_execinstr(struct bpf_object * obj,int idx)664 static bool section_have_execinstr(struct bpf_object *obj, int idx)
665 {
666 Elf_Scn *scn;
667 GElf_Shdr sh;
668
669 scn = elf_getscn(obj->efile.elf, idx);
670 if (!scn)
671 return false;
672
673 if (gelf_getshdr(scn, &sh) != &sh)
674 return false;
675
676 if (sh.sh_flags & SHF_EXECINSTR)
677 return true;
678
679 return false;
680 }
681
bpf_object__elf_collect(struct bpf_object * obj)682 static int bpf_object__elf_collect(struct bpf_object *obj)
683 {
684 Elf *elf = obj->efile.elf;
685 GElf_Ehdr *ep = &obj->efile.ehdr;
686 Elf_Scn *scn = NULL;
687 int idx = 0, err = 0;
688
689 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
690 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
691 pr_warning("failed to get e_shstrndx from %s\n",
692 obj->path);
693 return -LIBBPF_ERRNO__FORMAT;
694 }
695
696 while ((scn = elf_nextscn(elf, scn)) != NULL) {
697 char *name;
698 GElf_Shdr sh;
699 Elf_Data *data;
700
701 idx++;
702 if (gelf_getshdr(scn, &sh) != &sh) {
703 pr_warning("failed to get section header from %s\n",
704 obj->path);
705 err = -LIBBPF_ERRNO__FORMAT;
706 goto out;
707 }
708
709 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
710 if (!name) {
711 pr_warning("failed to get section name from %s\n",
712 obj->path);
713 err = -LIBBPF_ERRNO__FORMAT;
714 goto out;
715 }
716
717 data = elf_getdata(scn, 0);
718 if (!data) {
719 pr_warning("failed to get section data from %s(%s)\n",
720 name, obj->path);
721 err = -LIBBPF_ERRNO__FORMAT;
722 goto out;
723 }
724 pr_debug("section %s, size %ld, link %d, flags %lx, type=%d\n",
725 name, (unsigned long)data->d_size,
726 (int)sh.sh_link, (unsigned long)sh.sh_flags,
727 (int)sh.sh_type);
728
729 if (strcmp(name, "license") == 0)
730 err = bpf_object__init_license(obj,
731 data->d_buf,
732 data->d_size);
733 else if (strcmp(name, "version") == 0)
734 err = bpf_object__init_kversion(obj,
735 data->d_buf,
736 data->d_size);
737 else if (strcmp(name, "maps") == 0)
738 obj->efile.maps_shndx = idx;
739 else if (sh.sh_type == SHT_SYMTAB) {
740 if (obj->efile.symbols) {
741 pr_warning("bpf: multiple SYMTAB in %s\n",
742 obj->path);
743 err = -LIBBPF_ERRNO__FORMAT;
744 } else {
745 obj->efile.symbols = data;
746 obj->efile.strtabidx = sh.sh_link;
747 }
748 } else if ((sh.sh_type == SHT_PROGBITS) &&
749 (sh.sh_flags & SHF_EXECINSTR) &&
750 (data->d_size > 0)) {
751 err = bpf_object__add_program(obj, data->d_buf,
752 data->d_size, name, idx);
753 if (err) {
754 char errmsg[STRERR_BUFSIZE];
755
756 strerror_r(-err, errmsg, sizeof(errmsg));
757 pr_warning("failed to alloc program %s (%s): %s",
758 name, obj->path, errmsg);
759 }
760 } else if (sh.sh_type == SHT_REL) {
761 void *reloc = obj->efile.reloc;
762 int nr_reloc = obj->efile.nr_reloc + 1;
763 int sec = sh.sh_info; /* points to other section */
764
765 /* Only do relo for section with exec instructions */
766 if (!section_have_execinstr(obj, sec)) {
767 pr_debug("skip relo %s(%d) for section(%d)\n",
768 name, idx, sec);
769 continue;
770 }
771
772 reloc = realloc(reloc,
773 sizeof(*obj->efile.reloc) * nr_reloc);
774 if (!reloc) {
775 pr_warning("realloc failed\n");
776 err = -ENOMEM;
777 } else {
778 int n = nr_reloc - 1;
779
780 obj->efile.reloc = reloc;
781 obj->efile.nr_reloc = nr_reloc;
782
783 obj->efile.reloc[n].shdr = sh;
784 obj->efile.reloc[n].data = data;
785 }
786 }
787 if (err)
788 goto out;
789 }
790
791 if (!obj->efile.strtabidx || obj->efile.strtabidx >= idx) {
792 pr_warning("Corrupted ELF file: index of strtab invalid\n");
793 return LIBBPF_ERRNO__FORMAT;
794 }
795 if (obj->efile.maps_shndx >= 0)
796 err = bpf_object__init_maps(obj);
797 out:
798 return err;
799 }
800
801 static struct bpf_program *
bpf_object__find_prog_by_idx(struct bpf_object * obj,int idx)802 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
803 {
804 struct bpf_program *prog;
805 size_t i;
806
807 for (i = 0; i < obj->nr_programs; i++) {
808 prog = &obj->programs[i];
809 if (prog->idx == idx)
810 return prog;
811 }
812 return NULL;
813 }
814
815 static int
bpf_program__collect_reloc(struct bpf_program * prog,size_t nr_maps,GElf_Shdr * shdr,Elf_Data * data,Elf_Data * symbols,int maps_shndx,struct bpf_map * maps)816 bpf_program__collect_reloc(struct bpf_program *prog,
817 size_t nr_maps, GElf_Shdr *shdr,
818 Elf_Data *data, Elf_Data *symbols,
819 int maps_shndx, struct bpf_map *maps)
820 {
821 int i, nrels;
822
823 pr_debug("collecting relocating info for: '%s'\n",
824 prog->section_name);
825 nrels = shdr->sh_size / shdr->sh_entsize;
826
827 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
828 if (!prog->reloc_desc) {
829 pr_warning("failed to alloc memory in relocation\n");
830 return -ENOMEM;
831 }
832 prog->nr_reloc = nrels;
833
834 for (i = 0; i < nrels; i++) {
835 GElf_Sym sym;
836 GElf_Rel rel;
837 unsigned int insn_idx;
838 struct bpf_insn *insns = prog->insns;
839 size_t map_idx;
840
841 if (!gelf_getrel(data, i, &rel)) {
842 pr_warning("relocation: failed to get %d reloc\n", i);
843 return -LIBBPF_ERRNO__FORMAT;
844 }
845
846 if (!gelf_getsym(symbols,
847 GELF_R_SYM(rel.r_info),
848 &sym)) {
849 pr_warning("relocation: symbol %"PRIx64" not found\n",
850 GELF_R_SYM(rel.r_info));
851 return -LIBBPF_ERRNO__FORMAT;
852 }
853
854 if (sym.st_shndx != maps_shndx) {
855 pr_warning("Program '%s' contains non-map related relo data pointing to section %u\n",
856 prog->section_name, sym.st_shndx);
857 return -LIBBPF_ERRNO__RELOC;
858 }
859
860 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
861 pr_debug("relocation: insn_idx=%u\n", insn_idx);
862
863 if (insns[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
864 pr_warning("bpf: relocation: invalid relo for insns[%d].code 0x%x\n",
865 insn_idx, insns[insn_idx].code);
866 return -LIBBPF_ERRNO__RELOC;
867 }
868
869 /* TODO: 'maps' is sorted. We can use bsearch to make it faster. */
870 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
871 if (maps[map_idx].offset == sym.st_value) {
872 pr_debug("relocation: find map %zd (%s) for insn %u\n",
873 map_idx, maps[map_idx].name, insn_idx);
874 break;
875 }
876 }
877
878 if (map_idx >= nr_maps) {
879 pr_warning("bpf relocation: map_idx %d large than %d\n",
880 (int)map_idx, (int)nr_maps - 1);
881 return -LIBBPF_ERRNO__RELOC;
882 }
883
884 prog->reloc_desc[i].insn_idx = insn_idx;
885 prog->reloc_desc[i].map_idx = map_idx;
886 }
887 return 0;
888 }
889
890 static int
bpf_object__create_maps(struct bpf_object * obj)891 bpf_object__create_maps(struct bpf_object *obj)
892 {
893 unsigned int i;
894
895 for (i = 0; i < obj->nr_maps; i++) {
896 struct bpf_map_def *def = &obj->maps[i].def;
897 int *pfd = &obj->maps[i].fd;
898
899 *pfd = bpf_create_map(def->type,
900 def->key_size,
901 def->value_size,
902 def->max_entries,
903 0);
904 if (*pfd < 0) {
905 size_t j;
906 int err = *pfd;
907
908 pr_warning("failed to create map (name: '%s'): %s\n",
909 obj->maps[i].name,
910 strerror(errno));
911 for (j = 0; j < i; j++)
912 zclose(obj->maps[j].fd);
913 return err;
914 }
915 pr_debug("create map %s: fd=%d\n", obj->maps[i].name, *pfd);
916 }
917
918 return 0;
919 }
920
921 static int
bpf_program__relocate(struct bpf_program * prog,struct bpf_object * obj)922 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
923 {
924 int i;
925
926 if (!prog || !prog->reloc_desc)
927 return 0;
928
929 for (i = 0; i < prog->nr_reloc; i++) {
930 int insn_idx, map_idx;
931 struct bpf_insn *insns = prog->insns;
932
933 insn_idx = prog->reloc_desc[i].insn_idx;
934 map_idx = prog->reloc_desc[i].map_idx;
935
936 if (insn_idx >= (int)prog->insns_cnt) {
937 pr_warning("relocation out of range: '%s'\n",
938 prog->section_name);
939 return -LIBBPF_ERRNO__RELOC;
940 }
941 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
942 insns[insn_idx].imm = obj->maps[map_idx].fd;
943 }
944
945 zfree(&prog->reloc_desc);
946 prog->nr_reloc = 0;
947 return 0;
948 }
949
950
951 static int
bpf_object__relocate(struct bpf_object * obj)952 bpf_object__relocate(struct bpf_object *obj)
953 {
954 struct bpf_program *prog;
955 size_t i;
956 int err;
957
958 for (i = 0; i < obj->nr_programs; i++) {
959 prog = &obj->programs[i];
960
961 err = bpf_program__relocate(prog, obj);
962 if (err) {
963 pr_warning("failed to relocate '%s'\n",
964 prog->section_name);
965 return err;
966 }
967 }
968 return 0;
969 }
970
bpf_object__collect_reloc(struct bpf_object * obj)971 static int bpf_object__collect_reloc(struct bpf_object *obj)
972 {
973 int i, err;
974
975 if (!obj_elf_valid(obj)) {
976 pr_warning("Internal error: elf object is closed\n");
977 return -LIBBPF_ERRNO__INTERNAL;
978 }
979
980 for (i = 0; i < obj->efile.nr_reloc; i++) {
981 GElf_Shdr *shdr = &obj->efile.reloc[i].shdr;
982 Elf_Data *data = obj->efile.reloc[i].data;
983 int idx = shdr->sh_info;
984 struct bpf_program *prog;
985 size_t nr_maps = obj->nr_maps;
986
987 if (shdr->sh_type != SHT_REL) {
988 pr_warning("internal error at %d\n", __LINE__);
989 return -LIBBPF_ERRNO__INTERNAL;
990 }
991
992 prog = bpf_object__find_prog_by_idx(obj, idx);
993 if (!prog) {
994 pr_warning("relocation failed: no %d section\n",
995 idx);
996 return -LIBBPF_ERRNO__RELOC;
997 }
998
999 err = bpf_program__collect_reloc(prog, nr_maps,
1000 shdr, data,
1001 obj->efile.symbols,
1002 obj->efile.maps_shndx,
1003 obj->maps);
1004 if (err)
1005 return err;
1006 }
1007 return 0;
1008 }
1009
1010 static int
load_program(enum bpf_prog_type type,struct bpf_insn * insns,int insns_cnt,char * license,u32 kern_version,int * pfd)1011 load_program(enum bpf_prog_type type, struct bpf_insn *insns,
1012 int insns_cnt, char *license, u32 kern_version, int *pfd)
1013 {
1014 int ret;
1015 char *log_buf;
1016
1017 if (!insns || !insns_cnt)
1018 return -EINVAL;
1019
1020 log_buf = malloc(BPF_LOG_BUF_SIZE);
1021 if (!log_buf)
1022 pr_warning("Alloc log buffer for bpf loader error, continue without log\n");
1023
1024 ret = bpf_load_program(type, insns, insns_cnt, license,
1025 kern_version, log_buf, BPF_LOG_BUF_SIZE);
1026
1027 if (ret >= 0) {
1028 *pfd = ret;
1029 ret = 0;
1030 goto out;
1031 }
1032
1033 ret = -LIBBPF_ERRNO__LOAD;
1034 pr_warning("load bpf program failed: %s\n", strerror(errno));
1035
1036 if (log_buf && log_buf[0] != '\0') {
1037 ret = -LIBBPF_ERRNO__VERIFY;
1038 pr_warning("-- BEGIN DUMP LOG ---\n");
1039 pr_warning("\n%s\n", log_buf);
1040 pr_warning("-- END LOG --\n");
1041 } else if (insns_cnt >= BPF_MAXINSNS) {
1042 pr_warning("Program too large (%d insns), at most %d insns\n",
1043 insns_cnt, BPF_MAXINSNS);
1044 ret = -LIBBPF_ERRNO__PROG2BIG;
1045 } else {
1046 /* Wrong program type? */
1047 if (type != BPF_PROG_TYPE_KPROBE) {
1048 int fd;
1049
1050 fd = bpf_load_program(BPF_PROG_TYPE_KPROBE, insns,
1051 insns_cnt, license, kern_version,
1052 NULL, 0);
1053 if (fd >= 0) {
1054 close(fd);
1055 ret = -LIBBPF_ERRNO__PROGTYPE;
1056 goto out;
1057 }
1058 }
1059
1060 if (log_buf)
1061 ret = -LIBBPF_ERRNO__KVER;
1062 }
1063
1064 out:
1065 free(log_buf);
1066 return ret;
1067 }
1068
1069 static int
bpf_program__load(struct bpf_program * prog,char * license,u32 kern_version)1070 bpf_program__load(struct bpf_program *prog,
1071 char *license, u32 kern_version)
1072 {
1073 int err = 0, fd, i;
1074
1075 if (prog->instances.nr < 0 || !prog->instances.fds) {
1076 if (prog->preprocessor) {
1077 pr_warning("Internal error: can't load program '%s'\n",
1078 prog->section_name);
1079 return -LIBBPF_ERRNO__INTERNAL;
1080 }
1081
1082 prog->instances.fds = malloc(sizeof(int));
1083 if (!prog->instances.fds) {
1084 pr_warning("Not enough memory for BPF fds\n");
1085 return -ENOMEM;
1086 }
1087 prog->instances.nr = 1;
1088 prog->instances.fds[0] = -1;
1089 }
1090
1091 if (!prog->preprocessor) {
1092 if (prog->instances.nr != 1) {
1093 pr_warning("Program '%s' is inconsistent: nr(%d) != 1\n",
1094 prog->section_name, prog->instances.nr);
1095 }
1096 err = load_program(prog->type, prog->insns, prog->insns_cnt,
1097 license, kern_version, &fd);
1098 if (!err)
1099 prog->instances.fds[0] = fd;
1100 goto out;
1101 }
1102
1103 for (i = 0; i < prog->instances.nr; i++) {
1104 struct bpf_prog_prep_result result;
1105 bpf_program_prep_t preprocessor = prog->preprocessor;
1106
1107 bzero(&result, sizeof(result));
1108 err = preprocessor(prog, i, prog->insns,
1109 prog->insns_cnt, &result);
1110 if (err) {
1111 pr_warning("Preprocessing the %dth instance of program '%s' failed\n",
1112 i, prog->section_name);
1113 goto out;
1114 }
1115
1116 if (!result.new_insn_ptr || !result.new_insn_cnt) {
1117 pr_debug("Skip loading the %dth instance of program '%s'\n",
1118 i, prog->section_name);
1119 prog->instances.fds[i] = -1;
1120 if (result.pfd)
1121 *result.pfd = -1;
1122 continue;
1123 }
1124
1125 err = load_program(prog->type, result.new_insn_ptr,
1126 result.new_insn_cnt,
1127 license, kern_version, &fd);
1128
1129 if (err) {
1130 pr_warning("Loading the %dth instance of program '%s' failed\n",
1131 i, prog->section_name);
1132 goto out;
1133 }
1134
1135 if (result.pfd)
1136 *result.pfd = fd;
1137 prog->instances.fds[i] = fd;
1138 }
1139 out:
1140 if (err)
1141 pr_warning("failed to load program '%s'\n",
1142 prog->section_name);
1143 zfree(&prog->insns);
1144 prog->insns_cnt = 0;
1145 return err;
1146 }
1147
1148 static int
bpf_object__load_progs(struct bpf_object * obj)1149 bpf_object__load_progs(struct bpf_object *obj)
1150 {
1151 size_t i;
1152 int err;
1153
1154 for (i = 0; i < obj->nr_programs; i++) {
1155 err = bpf_program__load(&obj->programs[i],
1156 obj->license,
1157 obj->kern_version);
1158 if (err)
1159 return err;
1160 }
1161 return 0;
1162 }
1163
bpf_object__validate(struct bpf_object * obj)1164 static int bpf_object__validate(struct bpf_object *obj)
1165 {
1166 if (obj->kern_version == 0) {
1167 pr_warning("%s doesn't provide kernel version\n",
1168 obj->path);
1169 return -LIBBPF_ERRNO__KVERSION;
1170 }
1171 return 0;
1172 }
1173
1174 static struct bpf_object *
__bpf_object__open(const char * path,void * obj_buf,size_t obj_buf_sz)1175 __bpf_object__open(const char *path, void *obj_buf, size_t obj_buf_sz)
1176 {
1177 struct bpf_object *obj;
1178 int err;
1179
1180 if (elf_version(EV_CURRENT) == EV_NONE) {
1181 pr_warning("failed to init libelf for %s\n", path);
1182 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
1183 }
1184
1185 obj = bpf_object__new(path, obj_buf, obj_buf_sz);
1186 if (IS_ERR(obj))
1187 return obj;
1188
1189 CHECK_ERR(bpf_object__elf_init(obj), err, out);
1190 CHECK_ERR(bpf_object__check_endianness(obj), err, out);
1191 CHECK_ERR(bpf_object__elf_collect(obj), err, out);
1192 CHECK_ERR(bpf_object__collect_reloc(obj), err, out);
1193 CHECK_ERR(bpf_object__validate(obj), err, out);
1194
1195 bpf_object__elf_finish(obj);
1196 return obj;
1197 out:
1198 bpf_object__close(obj);
1199 return ERR_PTR(err);
1200 }
1201
bpf_object__open(const char * path)1202 struct bpf_object *bpf_object__open(const char *path)
1203 {
1204 /* param validation */
1205 if (!path)
1206 return NULL;
1207
1208 pr_debug("loading %s\n", path);
1209
1210 return __bpf_object__open(path, NULL, 0);
1211 }
1212
bpf_object__open_buffer(void * obj_buf,size_t obj_buf_sz,const char * name)1213 struct bpf_object *bpf_object__open_buffer(void *obj_buf,
1214 size_t obj_buf_sz,
1215 const char *name)
1216 {
1217 char tmp_name[64];
1218
1219 /* param validation */
1220 if (!obj_buf || obj_buf_sz <= 0)
1221 return NULL;
1222
1223 if (!name) {
1224 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
1225 (unsigned long)obj_buf,
1226 (unsigned long)obj_buf_sz);
1227 tmp_name[sizeof(tmp_name) - 1] = '\0';
1228 name = tmp_name;
1229 }
1230 pr_debug("loading object '%s' from buffer\n",
1231 name);
1232
1233 return __bpf_object__open(name, obj_buf, obj_buf_sz);
1234 }
1235
bpf_object__unload(struct bpf_object * obj)1236 int bpf_object__unload(struct bpf_object *obj)
1237 {
1238 size_t i;
1239
1240 if (!obj)
1241 return -EINVAL;
1242
1243 for (i = 0; i < obj->nr_maps; i++)
1244 zclose(obj->maps[i].fd);
1245
1246 for (i = 0; i < obj->nr_programs; i++)
1247 bpf_program__unload(&obj->programs[i]);
1248
1249 return 0;
1250 }
1251
bpf_object__load(struct bpf_object * obj)1252 int bpf_object__load(struct bpf_object *obj)
1253 {
1254 int err;
1255
1256 if (!obj)
1257 return -EINVAL;
1258
1259 if (obj->loaded) {
1260 pr_warning("object should not be loaded twice\n");
1261 return -EINVAL;
1262 }
1263
1264 obj->loaded = true;
1265
1266 CHECK_ERR(bpf_object__create_maps(obj), err, out);
1267 CHECK_ERR(bpf_object__relocate(obj), err, out);
1268 CHECK_ERR(bpf_object__load_progs(obj), err, out);
1269
1270 return 0;
1271 out:
1272 bpf_object__unload(obj);
1273 pr_warning("failed to load object '%s'\n", obj->path);
1274 return err;
1275 }
1276
check_path(const char * path)1277 static int check_path(const char *path)
1278 {
1279 struct statfs st_fs;
1280 char *dname, *dir;
1281 int err = 0;
1282
1283 if (path == NULL)
1284 return -EINVAL;
1285
1286 dname = strdup(path);
1287 if (dname == NULL)
1288 return -ENOMEM;
1289
1290 dir = dirname(dname);
1291 if (statfs(dir, &st_fs)) {
1292 pr_warning("failed to statfs %s: %s\n", dir, strerror(errno));
1293 err = -errno;
1294 }
1295 free(dname);
1296
1297 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
1298 pr_warning("specified path %s is not on BPF FS\n", path);
1299 err = -EINVAL;
1300 }
1301
1302 return err;
1303 }
1304
bpf_program__pin_instance(struct bpf_program * prog,const char * path,int instance)1305 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
1306 int instance)
1307 {
1308 int err;
1309
1310 err = check_path(path);
1311 if (err)
1312 return err;
1313
1314 if (prog == NULL) {
1315 pr_warning("invalid program pointer\n");
1316 return -EINVAL;
1317 }
1318
1319 if (instance < 0 || instance >= prog->instances.nr) {
1320 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
1321 instance, prog->section_name, prog->instances.nr);
1322 return -EINVAL;
1323 }
1324
1325 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
1326 pr_warning("failed to pin program: %s\n", strerror(errno));
1327 return -errno;
1328 }
1329 pr_debug("pinned program '%s'\n", path);
1330
1331 return 0;
1332 }
1333
make_dir(const char * path)1334 static int make_dir(const char *path)
1335 {
1336 int err = 0;
1337
1338 if (mkdir(path, 0700) && errno != EEXIST)
1339 err = -errno;
1340
1341 if (err)
1342 pr_warning("failed to mkdir %s: %s\n", path, strerror(-err));
1343 return err;
1344 }
1345
bpf_program__pin(struct bpf_program * prog,const char * path)1346 int bpf_program__pin(struct bpf_program *prog, const char *path)
1347 {
1348 int i, err;
1349
1350 err = check_path(path);
1351 if (err)
1352 return err;
1353
1354 if (prog == NULL) {
1355 pr_warning("invalid program pointer\n");
1356 return -EINVAL;
1357 }
1358
1359 if (prog->instances.nr <= 0) {
1360 pr_warning("no instances of prog %s to pin\n",
1361 prog->section_name);
1362 return -EINVAL;
1363 }
1364
1365 err = make_dir(path);
1366 if (err)
1367 return err;
1368
1369 for (i = 0; i < prog->instances.nr; i++) {
1370 char buf[PATH_MAX];
1371 int len;
1372
1373 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
1374 if (len < 0)
1375 return -EINVAL;
1376 else if (len >= PATH_MAX)
1377 return -ENAMETOOLONG;
1378
1379 err = bpf_program__pin_instance(prog, buf, i);
1380 if (err)
1381 return err;
1382 }
1383
1384 return 0;
1385 }
1386
bpf_map__pin(struct bpf_map * map,const char * path)1387 int bpf_map__pin(struct bpf_map *map, const char *path)
1388 {
1389 int err;
1390
1391 err = check_path(path);
1392 if (err)
1393 return err;
1394
1395 if (map == NULL) {
1396 pr_warning("invalid map pointer\n");
1397 return -EINVAL;
1398 }
1399
1400 if (bpf_obj_pin(map->fd, path)) {
1401 pr_warning("failed to pin map: %s\n", strerror(errno));
1402 return -errno;
1403 }
1404
1405 pr_debug("pinned map '%s'\n", path);
1406 return 0;
1407 }
1408
bpf_object__pin(struct bpf_object * obj,const char * path)1409 int bpf_object__pin(struct bpf_object *obj, const char *path)
1410 {
1411 struct bpf_program *prog;
1412 struct bpf_map *map;
1413 int err;
1414
1415 if (!obj)
1416 return -ENOENT;
1417
1418 if (!obj->loaded) {
1419 pr_warning("object not yet loaded; load it first\n");
1420 return -ENOENT;
1421 }
1422
1423 err = make_dir(path);
1424 if (err)
1425 return err;
1426
1427 bpf_map__for_each(map, obj) {
1428 char buf[PATH_MAX];
1429 int len;
1430
1431 len = snprintf(buf, PATH_MAX, "%s/%s", path,
1432 bpf_map__name(map));
1433 if (len < 0)
1434 return -EINVAL;
1435 else if (len >= PATH_MAX)
1436 return -ENAMETOOLONG;
1437
1438 err = bpf_map__pin(map, buf);
1439 if (err)
1440 return err;
1441 }
1442
1443 bpf_object__for_each_program(prog, obj) {
1444 char buf[PATH_MAX];
1445 int len;
1446
1447 len = snprintf(buf, PATH_MAX, "%s/%s", path,
1448 prog->section_name);
1449 if (len < 0)
1450 return -EINVAL;
1451 else if (len >= PATH_MAX)
1452 return -ENAMETOOLONG;
1453
1454 err = bpf_program__pin(prog, buf);
1455 if (err)
1456 return err;
1457 }
1458
1459 return 0;
1460 }
1461
bpf_object__close(struct bpf_object * obj)1462 void bpf_object__close(struct bpf_object *obj)
1463 {
1464 size_t i;
1465
1466 if (!obj)
1467 return;
1468
1469 if (obj->clear_priv)
1470 obj->clear_priv(obj, obj->priv);
1471
1472 bpf_object__elf_finish(obj);
1473 bpf_object__unload(obj);
1474
1475 for (i = 0; i < obj->nr_maps; i++) {
1476 zfree(&obj->maps[i].name);
1477 if (obj->maps[i].clear_priv)
1478 obj->maps[i].clear_priv(&obj->maps[i],
1479 obj->maps[i].priv);
1480 obj->maps[i].priv = NULL;
1481 obj->maps[i].clear_priv = NULL;
1482 }
1483 zfree(&obj->maps);
1484 obj->nr_maps = 0;
1485
1486 if (obj->programs && obj->nr_programs) {
1487 for (i = 0; i < obj->nr_programs; i++)
1488 bpf_program__exit(&obj->programs[i]);
1489 }
1490 zfree(&obj->programs);
1491
1492 list_del(&obj->list);
1493 free(obj);
1494 }
1495
1496 struct bpf_object *
bpf_object__next(struct bpf_object * prev)1497 bpf_object__next(struct bpf_object *prev)
1498 {
1499 struct bpf_object *next;
1500
1501 if (!prev)
1502 next = list_first_entry(&bpf_objects_list,
1503 struct bpf_object,
1504 list);
1505 else
1506 next = list_next_entry(prev, list);
1507
1508 /* Empty list is noticed here so don't need checking on entry. */
1509 if (&next->list == &bpf_objects_list)
1510 return NULL;
1511
1512 return next;
1513 }
1514
bpf_object__name(struct bpf_object * obj)1515 const char *bpf_object__name(struct bpf_object *obj)
1516 {
1517 return obj ? obj->path : ERR_PTR(-EINVAL);
1518 }
1519
bpf_object__kversion(struct bpf_object * obj)1520 unsigned int bpf_object__kversion(struct bpf_object *obj)
1521 {
1522 return obj ? obj->kern_version : 0;
1523 }
1524
bpf_object__set_priv(struct bpf_object * obj,void * priv,bpf_object_clear_priv_t clear_priv)1525 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
1526 bpf_object_clear_priv_t clear_priv)
1527 {
1528 if (obj->priv && obj->clear_priv)
1529 obj->clear_priv(obj, obj->priv);
1530
1531 obj->priv = priv;
1532 obj->clear_priv = clear_priv;
1533 return 0;
1534 }
1535
bpf_object__priv(struct bpf_object * obj)1536 void *bpf_object__priv(struct bpf_object *obj)
1537 {
1538 return obj ? obj->priv : ERR_PTR(-EINVAL);
1539 }
1540
1541 struct bpf_program *
bpf_program__next(struct bpf_program * prev,struct bpf_object * obj)1542 bpf_program__next(struct bpf_program *prev, struct bpf_object *obj)
1543 {
1544 size_t idx;
1545
1546 if (!obj->programs)
1547 return NULL;
1548 /* First handler */
1549 if (prev == NULL)
1550 return &obj->programs[0];
1551
1552 if (prev->obj != obj) {
1553 pr_warning("error: program handler doesn't match object\n");
1554 return NULL;
1555 }
1556
1557 idx = (prev - obj->programs) + 1;
1558 if (idx >= obj->nr_programs)
1559 return NULL;
1560 return &obj->programs[idx];
1561 }
1562
bpf_program__set_priv(struct bpf_program * prog,void * priv,bpf_program_clear_priv_t clear_priv)1563 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
1564 bpf_program_clear_priv_t clear_priv)
1565 {
1566 if (prog->priv && prog->clear_priv)
1567 prog->clear_priv(prog, prog->priv);
1568
1569 prog->priv = priv;
1570 prog->clear_priv = clear_priv;
1571 return 0;
1572 }
1573
bpf_program__priv(struct bpf_program * prog)1574 void *bpf_program__priv(struct bpf_program *prog)
1575 {
1576 return prog ? prog->priv : ERR_PTR(-EINVAL);
1577 }
1578
bpf_program__title(struct bpf_program * prog,bool needs_copy)1579 const char *bpf_program__title(struct bpf_program *prog, bool needs_copy)
1580 {
1581 const char *title;
1582
1583 title = prog->section_name;
1584 if (needs_copy) {
1585 title = strdup(title);
1586 if (!title) {
1587 pr_warning("failed to strdup program title\n");
1588 return ERR_PTR(-ENOMEM);
1589 }
1590 }
1591
1592 return title;
1593 }
1594
bpf_program__fd(struct bpf_program * prog)1595 int bpf_program__fd(struct bpf_program *prog)
1596 {
1597 return bpf_program__nth_fd(prog, 0);
1598 }
1599
bpf_program__set_prep(struct bpf_program * prog,int nr_instances,bpf_program_prep_t prep)1600 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
1601 bpf_program_prep_t prep)
1602 {
1603 int *instances_fds;
1604
1605 if (nr_instances <= 0 || !prep)
1606 return -EINVAL;
1607
1608 if (prog->instances.nr > 0 || prog->instances.fds) {
1609 pr_warning("Can't set pre-processor after loading\n");
1610 return -EINVAL;
1611 }
1612
1613 instances_fds = malloc(sizeof(int) * nr_instances);
1614 if (!instances_fds) {
1615 pr_warning("alloc memory failed for fds\n");
1616 return -ENOMEM;
1617 }
1618
1619 /* fill all fd with -1 */
1620 memset(instances_fds, -1, sizeof(int) * nr_instances);
1621
1622 prog->instances.nr = nr_instances;
1623 prog->instances.fds = instances_fds;
1624 prog->preprocessor = prep;
1625 return 0;
1626 }
1627
bpf_program__nth_fd(struct bpf_program * prog,int n)1628 int bpf_program__nth_fd(struct bpf_program *prog, int n)
1629 {
1630 int fd;
1631
1632 if (n >= prog->instances.nr || n < 0) {
1633 pr_warning("Can't get the %dth fd from program %s: only %d instances\n",
1634 n, prog->section_name, prog->instances.nr);
1635 return -EINVAL;
1636 }
1637
1638 fd = prog->instances.fds[n];
1639 if (fd < 0) {
1640 pr_warning("%dth instance of program '%s' is invalid\n",
1641 n, prog->section_name);
1642 return -ENOENT;
1643 }
1644
1645 return fd;
1646 }
1647
bpf_program__set_type(struct bpf_program * prog,enum bpf_prog_type type)1648 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
1649 {
1650 prog->type = type;
1651 }
1652
bpf_program__is_type(struct bpf_program * prog,enum bpf_prog_type type)1653 static bool bpf_program__is_type(struct bpf_program *prog,
1654 enum bpf_prog_type type)
1655 {
1656 return prog ? (prog->type == type) : false;
1657 }
1658
1659 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
1660 int bpf_program__set_##NAME(struct bpf_program *prog) \
1661 { \
1662 if (!prog) \
1663 return -EINVAL; \
1664 bpf_program__set_type(prog, TYPE); \
1665 return 0; \
1666 } \
1667 \
1668 bool bpf_program__is_##NAME(struct bpf_program *prog) \
1669 { \
1670 return bpf_program__is_type(prog, TYPE); \
1671 } \
1672
1673 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
1674 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
1675 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
1676 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
1677 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
1678 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
1679 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
1680
bpf_map__fd(struct bpf_map * map)1681 int bpf_map__fd(struct bpf_map *map)
1682 {
1683 return map ? map->fd : -EINVAL;
1684 }
1685
bpf_map__def(struct bpf_map * map)1686 const struct bpf_map_def *bpf_map__def(struct bpf_map *map)
1687 {
1688 return map ? &map->def : ERR_PTR(-EINVAL);
1689 }
1690
bpf_map__name(struct bpf_map * map)1691 const char *bpf_map__name(struct bpf_map *map)
1692 {
1693 return map ? map->name : NULL;
1694 }
1695
bpf_map__set_priv(struct bpf_map * map,void * priv,bpf_map_clear_priv_t clear_priv)1696 int bpf_map__set_priv(struct bpf_map *map, void *priv,
1697 bpf_map_clear_priv_t clear_priv)
1698 {
1699 if (!map)
1700 return -EINVAL;
1701
1702 if (map->priv) {
1703 if (map->clear_priv)
1704 map->clear_priv(map, map->priv);
1705 }
1706
1707 map->priv = priv;
1708 map->clear_priv = clear_priv;
1709 return 0;
1710 }
1711
bpf_map__priv(struct bpf_map * map)1712 void *bpf_map__priv(struct bpf_map *map)
1713 {
1714 return map ? map->priv : ERR_PTR(-EINVAL);
1715 }
1716
1717 struct bpf_map *
bpf_map__next(struct bpf_map * prev,struct bpf_object * obj)1718 bpf_map__next(struct bpf_map *prev, struct bpf_object *obj)
1719 {
1720 size_t idx;
1721 struct bpf_map *s, *e;
1722
1723 if (!obj || !obj->maps)
1724 return NULL;
1725
1726 s = obj->maps;
1727 e = obj->maps + obj->nr_maps;
1728
1729 if (prev == NULL)
1730 return s;
1731
1732 if ((prev < s) || (prev >= e)) {
1733 pr_warning("error in %s: map handler doesn't belong to object\n",
1734 __func__);
1735 return NULL;
1736 }
1737
1738 idx = (prev - obj->maps) + 1;
1739 if (idx >= obj->nr_maps)
1740 return NULL;
1741 return &obj->maps[idx];
1742 }
1743
1744 struct bpf_map *
bpf_object__find_map_by_name(struct bpf_object * obj,const char * name)1745 bpf_object__find_map_by_name(struct bpf_object *obj, const char *name)
1746 {
1747 struct bpf_map *pos;
1748
1749 bpf_map__for_each(pos, obj) {
1750 if (pos->name && !strcmp(pos->name, name))
1751 return pos;
1752 }
1753 return NULL;
1754 }
1755
1756 struct bpf_map *
bpf_object__find_map_by_offset(struct bpf_object * obj,size_t offset)1757 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
1758 {
1759 int i;
1760
1761 for (i = 0; i < obj->nr_maps; i++) {
1762 if (obj->maps[i].offset == offset)
1763 return &obj->maps[i];
1764 }
1765 return ERR_PTR(-ENOENT);
1766 }
1767
libbpf_get_error(const void * ptr)1768 long libbpf_get_error(const void *ptr)
1769 {
1770 if (IS_ERR(ptr))
1771 return PTR_ERR(ptr);
1772 return 0;
1773 }
1774
bpf_prog_load(const char * file,enum bpf_prog_type type,struct bpf_object ** pobj,int * prog_fd)1775 int bpf_prog_load(const char *file, enum bpf_prog_type type,
1776 struct bpf_object **pobj, int *prog_fd)
1777 {
1778 struct bpf_program *prog;
1779 struct bpf_object *obj;
1780 int err;
1781
1782 obj = bpf_object__open(file);
1783 if (IS_ERR(obj))
1784 return -ENOENT;
1785
1786 prog = bpf_program__next(NULL, obj);
1787 if (!prog) {
1788 bpf_object__close(obj);
1789 return -ENOENT;
1790 }
1791
1792 bpf_program__set_type(prog, type);
1793 err = bpf_object__load(obj);
1794 if (err) {
1795 bpf_object__close(obj);
1796 return -EINVAL;
1797 }
1798
1799 *pobj = obj;
1800 *prog_fd = bpf_program__fd(prog);
1801 return 0;
1802 }
1803